text stringlengths 14 6.51M |
|---|
unit VSESound;
interface
uses
Windows, AvL, avlUtils, MMSystem, DirectSound, VSECore;
//{$I dsound.inc}
type
TSound=class(TModule)
private
FDirectSound: IDirectSound;
FMusicBuffer: IDirectSoundBuffer;
FMusicFile: TCustomMemoryStream;
FMusicPCM: TWaveFormatEx;
FMusicBufferDesc: TDSBufferDesc;
FEnableBGM: Boolean;
procedure SetEnableBGM(Value: Boolean);
function GetVolume: Integer;
procedure SetVolume(const Value: Integer);
{$IFDEF VSE_CONSOLE}
function BGMHandler(Sender: TObject; Args: array of const): Boolean;
function BGMVolHandler(Sender: TObject; Args: array of const): Boolean;
{$ENDIF}
public
constructor Create; override; //internally used
destructor Destroy; override; //internally used
{$IF Defined(VSE_LOG) and not Defined(VSE_NOSYSINFO)}procedure LogCaps;{$IFEND}
procedure Update; override;//internally used
procedure OnEvent(var Event: TCoreEvent); override;
procedure PlayMusic(const FileName: string); //Play music from file
procedure StopMusic; //Stop music
class function Name: string; override;
property EnableBGM: Boolean read FEnableBGM write SetEnableBGM; //Enable/disable music playing
property BGMVolume: Integer read GetVolume write SetVolume; //Music volume dB*100 from -100dB (-10000) to 0
end;
var
Sound: TSound; //Global variable for access to Sound Engine
implementation
uses
{$IFDEF VSE_CONSOLE}VSEConsole{$ENDIF}{$IFDEF VSE_LOG}, VSELog{$ENDIF};
{uFMOD}
const
SNameEnableBGM = 'EnableBGM';
XM_MEMORY=1;
uFMOD_BUFFER_SIZE=262144;
uFMOD_MixRate = 44100;
SSectionSound='Sound';
{$L dsufmod.obj}
function uFMOD_DSPlaySong(lpXM: Pointer; param, fdwSong: Integer;
lpDSBuffer: IDirectSoundBuffer): Integer; stdcall; external;
{TSound}
constructor TSound.Create;
begin
inherited Create;
Sound:=Self;
{$IFDEF VSE_CONSOLE}
Console['bgm ?val=eoff:on']:=BGMHandler;
Console['bgmvol ?val=f']:=BGMVolHandler;
{$ENDIF}
if DirectSoundCreate(nil, FDirectSound, nil)<>S_OK then
begin
{$IFDEF VSE_LOG}Log(llError, 'Sound: Cannot initialize DirectSound');{$ENDIF}
FDirectSound:=nil;
Exit;
end;
if FDirectSound.SetCooperativeLevel(Core.Handle, DSSCL_PRIORITY)<>S_OK then
begin
{$IFDEF VSE_LOG}Log(llError, 'Sound: Cannot set cooperative level');{$ENDIF}
FDirectSound:=nil;
Exit;
end;
with FMusicPCM do
begin
wFormatTag:=WAVE_FORMAT_PCM;
nChannels:=2;
nSamplesPerSec:=uFMOD_MixRate;
nAvgBytesPerSec:=uFMOD_MixRate*4;
nBlockAlign:=4;
wBitsPerSample:=16;
cbSize:=0;
end;
with FMusicBufferDesc do
begin
dwSize:=SizeOf(FMusicBufferDesc);
dwFlags:=DSBCAPS_STATIC or DSBCAPS_CTRLVOLUME or DSBCAPS_GLOBALFOCUS or DSBCAPS_GETCURRENTPOSITION2;
dwBufferBytes:=uFMOD_BUFFER_SIZE;
lpwfxFormat:=@FMusicPCM;
end;
if FDirectSound.CreateSoundBuffer(FMusicBufferDesc, FMusicBuffer, nil)<>S_OK then
begin
{$IFDEF VSE_LOG}Log(llError, 'Sound: Cannot create secondary buffer');{$ENDIF}
FMusicBuffer:=nil;
end;
if Settings.FirstRun
then Settings.Bool[SSectionSound, SNameEnableBGM]:=true;
EnableBGM:=Settings.Bool[SSectionSound, SNameEnableBGM];
end;
destructor TSound.Destroy;
begin
Sound:=nil;
Settings.Bool[SSectionSound, SNameEnableBGM]:=EnableBGM;
StopMusic;
FMusicBuffer:=nil;
FDirectSound:=nil;
inherited Destroy;
end;
class function TSound.Name: string;
begin
Result:='Sound';
end;
{$IF Defined(VSE_LOG) and not Defined(VSE_NOSYSINFO)}
procedure TSound.LogCaps;
const
Flags: array[0..10] of record Name: string; Value: DWORD; end = (
(Name: 'CONTINUOUSRATE'; Value: $00000010),
(Name: 'EMULDRIVER'; Value: $00000020),
(Name: 'CERTIFIED'; Value: $00000040),
(Name: 'PRIMARYMONO'; Value: $00000001),
(Name: 'PRIMARYSTEREO'; Value: $00000002),
(Name: 'PRIMARY8BIT'; Value: $00000004),
(Name: 'PRIMARY16BIT'; Value: $00000008),
(Name: 'SECONDARYMONO'; Value: $00000100),
(Name: 'SECONDARYSTEREO'; Value: $00000200),
(Name: 'SECONDARY8BIT'; Value: $00000400),
(Name: 'SECONDARY16BIT'; Value: $00000800));
var
Caps: TDSCaps;
i: Integer;
S: string;
begin
Caps.dwSize:=SizeOf(Caps);
if not Assigned(FDirectSound) or (FDirectSound.GetCaps(Caps)<>S_OK) then
begin
Log(llError, 'Sound: Can''t retrieve DirectSound capabilities');
Exit;
end;
with Caps do
begin
LogRaw(llInfo, 'DirectSound capabilities:');
LogRaw(llInfo, Format('Hardware secondary buffers sample rate: min=%d, max=%d', [dwMinSecondarySampleRate, dwMaxSecondarySampleRate]));
LogRaw(llInfo, 'Primary buffers: '+IntToStr(dwPrimaryBuffers));
LogRaw(llInfo, Format('Hardware secondary buffers: total=%d, static=%d, streaming=%d', [dwMaxHwMixingAllBuffers, dwMaxHwMixingStaticBuffers, dwMaxHwMixingStreamingBuffers]));
LogRaw(llInfo, Format('Free hardware secondary buffers: total=%d, static=%d, streaming=%d', [dwFreeHwMixingAllBuffers, dwFreeHwMixingStaticBuffers, dwFreeHwMixingStreamingBuffers]));
LogRaw(llInfo, Format('Hardware secondary 3D buffers: total=%d, static=%d, streaming=%d', [dwMaxHw3DAllBuffers, dwMaxHw3DStaticBuffers, dwMaxHw3DStreamingBuffers]));
LogRaw(llInfo, Format('Free hardware secondary 3D buffers: total=%d, static=%d, streaming=%d', [dwFreeHw3DAllBuffers, dwFreeHw3DStaticBuffers, dwFreeHw3DStreamingBuffers]));
LogRaw(llInfo, Format('Hardware memory: max=%d, free=%d, contig=%d', [dwTotalHwMemBytes, dwFreeHwMemBytes, dwMaxContigFreeHwMemBytes]));
LogRaw(llInfo, 'Hardware buffers transfer rate: '+IntToStr(dwUnlockTransferRateHwBuffers));
LogRaw(llInfo, 'CPU overhead: '+IntToStr(dwPlayCpuOverheadSwBuffers));
S:='Flags: ';
for i:=0 to High(Flags) do
if dwFlags and Flags[i].Value <> 0
then S:=S+Flags[i].Name+' ';
LogRaw(llInfo, S);
LogRaw(llInfo, '');
end;
end;
{$IFEND}
procedure TSound.Update;
begin
end;
procedure TSound.OnEvent(var Event: TCoreEvent);
begin
{$IF Defined(VSE_LOG) and not Defined(VSE_NOSYSINFO)}
if (Event is TSysNotify) and ((Event as TSysNotify).Notify = snLogSysInfo) then
LogCaps
else
{$IFEND}
inherited;
//TODO: pause on snPause
end;
procedure TSound.PlayMusic(const FileName: string);
var
Data: TStream;
begin
if not Assigned(FMusicBuffer) then Exit;
if Assigned(FMusicFile) then StopMusic;
Data:=Core.GetFile(FileName);
if not Assigned(Data) then Exit;
if Data is TCustomMemoryStream then
FMusicFile:=Data as TCustomMemoryStream
else begin
FMusicFile:=TMemoryStream.Create;
FMusicFile.CopyFrom(Data, 0);
Data.Free;
end;
if EnableBGM
then uFMOD_DSPlaySong(FMusicFile.Memory, FMusicFile.Size, XM_MEMORY, FMusicBuffer);
end;
procedure TSound.StopMusic;
begin
uFMOD_DSPlaySong(nil, 0, 0, nil);
FAN(FMusicFile);
end;
procedure TSound.SetEnableBGM(Value: Boolean);
begin
if Value=FEnableBGM
then Exit;
FEnableBGM:=Value;
if not FEnableBGM then
uFMOD_DSPlaySong(nil, 0, 0, nil)
else if Assigned(FMusicBuffer) and Assigned(FMusicFile) then
uFMOD_DSPlaySong(FMusicFile.Memory, FMusicFile.Size, XM_MEMORY, FMusicBuffer);
end;
function TSound.GetVolume: Integer;
begin
if Assigned(FMusicBuffer) then
FMusicBuffer.GetVolume(Result);
end;
procedure TSound.SetVolume(const Value: Integer);
begin
if Assigned(FMusicBuffer) then
FMusicBuffer.SetVolume(Value);
end;
{$IFDEF VSE_CONSOLE}
const
BoolState: array[Boolean] of string = ('off', 'on');
function TSound.BGMHandler(Sender: TObject; Args: array of const): Boolean;
begin
if Length(Args)>1 then
EnableBGM:=Boolean(Args[1].VInteger)
else
Console.WriteLn('BGM: '+BoolState[EnableBGM]);
Result:=true;
end;
function TSound.BGMVolHandler(Sender: TObject; Args: array of const): Boolean;
begin
if Length(Args)>1 then
BGMVolume:=Round(100*Args[1].VExtended^)
else
Console.WriteLn('BGM volume: '+FloatToStr2(BGMVolume/100, 1, 2)+'dB');
Result:=true;
end;
{$ENDIF}
initialization
RegisterModule(TSound);
end.
|
unit uHookedDrinks;
interface
type
TCaffeineBeverageWithHook = class abstract
procedure PrepareRecipe; virtual; final;
procedure Brew; virtual; abstract;
procedure AddCondiments; virtual; abstract;
procedure BoilWater;
procedure PourInCup;
function CustomerWantsCondiments: Boolean; virtual;
end;
TCoffeeWithHook = class(TCaffeineBeverageWithHook)
private
procedure Brew; override;
procedure AddCondiments; override;
function GetUserInput: string;
public
function CustomerWantsCondiments: Boolean; override;
end;
TTeaWithHook = class(TCaffeineBeverageWithHook)
private
procedure Brew; override;
procedure AddCondiments; override;
function GetUserInput: string;
public
function CustomerWantsCondiments: Boolean; override;
end;
implementation
uses
System.SysUtils
;
{ TCaffeineBeverageWithHook }
procedure TCaffeineBeverageWithHook.BoilWater;
begin
WriteLn('Boiling water...');
end;
function TCaffeineBeverageWithHook.CustomerWantsCondiments: Boolean;
begin
Result := True;
end;
procedure TCaffeineBeverageWithHook.PourInCup;
begin
WriteLn('Pouring into cup...');
end;
procedure TCaffeineBeverageWithHook.PrepareRecipe;
begin
BoilWater;
Brew;
PourInCup;
if CustomerWantsCondiments then
begin
AddCondiments;
end;
end;
{ TCoffeeWithHook }
procedure TCoffeeWithHook.AddCondiments;
begin
WriteLn('Adding sugar and milk...');
end;
procedure TCoffeeWithHook.Brew;
begin
WriteLn('Dripping water into the coffee/filter...');
end;
function TCoffeeWithHook.CustomerWantsCondiments: Boolean;
var
Answer: string;
begin
Answer := GetUserInput;
Result := Answer.LowerCase(Answer).StartsWith('y');
end;
function TCoffeeWithHook.GetUserInput: string;
begin
Write('Would you like milk and sugar with your coffee? (Y/N)');
ReadLn(Result);
end;
{ TTeaWithHook }
procedure TTeaWithHook.AddCondiments;
begin
WriteLn('Adding lemon...');
end;
procedure TTeaWithHook.Brew;
begin
WriteLn('Steeping tea bag...');
end;
function TTeaWithHook.CustomerWantsCondiments: Boolean;
var
Answer: string;
begin
Answer := GetUserInput;
Result := Answer.LowerCase(Answer).StartsWith('y');
end;
function TTeaWithHook.GetUserInput: string;
begin
Write('Would you like lemon with your tea? (Y/N)');
ReadLn(Result);
end;
end.
|
{ALGORITHME Jeu_Allumettes
//BUT: Jeu où deux utilisateurs s'affrontent. Ils doivent tour à tour retirer 1 à 3 allumettes sur un total de 21,
//celui qui retire la dernière perd.
//ENTREE: 21 allumettes
//SORTIE: gagnant du jeu
VAR
allum, choixj1, choixj2 : ENTIER
gagnantj1 : BOOL
DEBUT
//Bloc initialisation variables:
allum <- 21
choixj1 <- 0
choixj2 <- 0
gagnantj1 : VRAI
TANTQUE allum>1 FAIRE
ECRIRE "Joueur 1, a votre tour de choisir de retirer 1,2 ou 3 allumettes:"
LIRE choixj1
gagnantj1<-VRAI
SI (choixj1>=1) ET (choixj1<=3) ALORS
allum <- allum-choixj1
ECRIRE "Le nombre d'allumettes restantes est:",allum
SINON
REPETER
ECRIRE "Nombre d'allumettes invalide! Vous devez choisir un chiffre entre 1 et 3 (inclus)"
LIRE choixj1
JUSQU'A (choixj1>=1) ET (choixj1<=3)
allum <- allum-choixj1
ECRIRE "Le nombre d'allumettes restantes est:",allum
FINSI
ECRIRE "Joueur 2, a votre tour de choisir de retirer 1,2 ou 3 allumettes:"
LIRE choixj2
gagnantj1<-FAUX
SI (choixj2>=1) ET (choixj2<=3) ALORS
allum <- allum-choixj2
ECRIRE "Le nombre d'allumettes restantes est:",allum
SINON
REPETER
ECRIRE "Nombre d'allumettes invalide! Vous devez choisir un chiffre entre 1 et 3 (inclus)"
LIRE choixj2
JUSQU'A (choixj2>=1) ET (choixj2<=3)
allum <- allum-choixj2
ECRIRE "Le nombre d'allumettes restantes est",allum
FINSI
0 <- choixj1
0 <- choixj2
FINTANTQUE
SI allum<=1 ET gagnantj1=VRAI
ECRIRE "Le joueur 1 a gagné!"
SINON
SI allum<=1 ET gagnant=FAUX
ECRIRE "Le joueur 2 a gagné!"
FIN
JEU D'ESSAI:
Joueur 1, a votre tour de choisir de retirer 1,2 ou 3 allumettes:
2
Le nombre d'allumettes restantes est:19
Joueur 2, a votre tour de choisir de retirer 1,2 ou 3 allumettes:
3
Le nombre d'allumettes restantes est:16
Joueur 1, a votre tour de choisir de retirer 1,2 ou 3 allumettes:
1
Le nombre d'allumettes restantes est:15
Joueur 2, a votre tour de choisir de retirer 1,2 ou 3 allumettes:
3
Le nombre d'allumettes restantes est:12
Joueur 1, a votre tour de choisir de retirer 1,2 ou 3 allumettes:
3
Le nombre d'allumettes restantes est:9
Joueur 2, a votre tour de choisir de retirer 1,2 ou 3 allumettes:
1
Le nombre d'allumettes restantes est:8
Joueur 1, a votre tour de choisir de retirer 1,2 ou 3 allumettes:
2
Le nombre d'allumettes restantes est:6
Joueur 2, a votre tour de choisir de retirer 1,2 ou 3 allumettes:
3
Le nombre d'allumettes restantes est:3
Joueur 1, a votre tour de choisir de retirer 1,2 ou 3 allumettes:
2
Le joueur 1 a gagné!
} |
unit PJBank.Boleto.Extrato.Response;
interface
uses
System.Generics.Collections;
type
TBoletoPagamento = class
public
valor: string;
nosso_numero: string;
nosso_numero_original: string;
id_unico: string;
id_unico_original: string;
banco_numero: string;
token_facilitador: string;
valor_liquido: string;
data_vencimento: string;
data_pagamento: string;
data_credito: string;
pagador: string;
end;
TBoletoExtrato = TList<TBoletoPagamento>;
implementation
end.
|
unit Data.Main;
interface
uses
System.SysUtils, System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Stan.Param,
FireDAC.UI.Intf, FireDAC.VCLUI.Wait,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.IBDef,
FireDAC.Phys.FBDef, FireDAC.Phys.FB, FireDAC.Phys.IBBase,
FireDAC.Phys.IB,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.Client, FireDAC.Comp.DataSet,
Data.DB,
Model.Orders;
type
TDataModule1 = class(TDataModule)
FDConnection1: TFDConnection;
FDPhysIBDriverLink1: TFDPhysIBDriverLink;
FDPhysFBDriverLink1: TFDPhysFBDriverLink;
OrdersTable: TFDQuery;
fdqOrderORM: TFDQuery;
private
public
procedure LoadOrdersStore;
end;
var
DataModule1: TDataModule1;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses Plus.Nullable;
{$R *.dfm}
procedure TDataModule1.LoadOrdersStore;
var
Order: TOrder;
begin
fdqOrderORM.Open('SELECT ' + sLineBreak +
' ORDERID, CUSTOMERID, EMPLOYEEID, ORDERDATE, ' + sLineBreak +
' REQUIREDDATE, SHIPPEDDATE, SHIPVIA, FREIGHT ' + sLineBreak +
'FROM {id Orders} ');
TOrderStore.Store.Clear;
while not fdqOrderORM.Eof do
begin
Order := TOrder.Create;
Order.OrderID.Create(fdqOrderORM.FieldByName('OrderID').Value);
Order.CustomerID.Create(fdqOrderORM.FieldByName('CustomerID').Value);
Order.EmployeeID.Create(fdqOrderORM.FieldByName('EmployeeID').Value);
Order.OrderDate.Create(fdqOrderORM.FieldByName('OrderDate').Value);
Order.RequiredDate.Create(fdqOrderORM.FieldByName('RequiredDate').Value);
// Order.ShippedDate.Create(fdqOrderORM.FieldByName('ShippedDate').Value);
Order.ShippedDate := fdqOrderORM.FieldByName('ShippedDate').Value;
Order.ShipVia.Create(fdqOrderORM.FieldByName('ShipVia').Value);
Order.Freight.Create(fdqOrderORM.FieldByName('Freight').Value);
TOrderStore.Store.Add(Order);
fdqOrderORM.Next;
end;
fdqOrderORM.Close;
end;
end.
|
unit ClassStatus;
interface
uses Classes, DB, SysUtils, ClassPaiCadastro;
type
TClassStatus = class(TClassPaiCadastro)
public
class function Descricao: string; override;
class function TabelaPrincipal: string; override;
class function CampoChave: string; override;
class function CampoDescricao: string; override;
class function CamposCadastro: string; override;
class function SQLBaseCadastro: string; override;
class function SQLBaseRelatorio: string; override;
class function SQLBaseConsulta: string; override;
class procedure ConfigurarPropriedadesDoCampo(CDS: TDataSet; Campo: string);
end;
implementation
uses Constantes;
class function TClassStatus.Descricao: string;
begin
Result := 'Status';
end;
class function TClassStatus.TabelaPrincipal: string;
begin
Result := 'STATUS';
end;
class function TClassStatus.CampoChave: string;
begin
Result := 'CODIGO_STATUS';
end;
class function TClassStatus.CampoDescricao: string;
begin
Result := 'DESCRICAO_STATUS';
end;
class function TClassStatus.CamposCadastro: string;
begin
Result :=
' STATUS.CODIGO_STATUS,' +
' STATUS.DESCRICAO_STATUS';
end;
class function TClassStatus.SQLBaseCadastro: string;
begin
Result := 'select' + #13 +
CamposCadastro + #13 +
'from STATUS' + #13 +
'where (STATUS.CODIGO_STATUS = :COD)';
end;
class function TClassStatus.SQLBaseConsulta: string;
begin
Result := 'select' + #13 +
CamposCadastro + #13 +
'from STATUS';
end;
class function TClassStatus.SQLBaseRelatorio: string;
begin
Result := 'select' + #13 +
CamposCadastro + #13 +
'from STATUS';
end;
class procedure TClassStatus.ConfigurarPropriedadesDoCampo(CDS: TDataSet; Campo: string);
begin
inherited;
with CDS.FieldByName(Campo) do
if (Campo = 'CODIGO_STATUS') then
DisplayLabel := 'Código'
else if (Campo = 'DESCRICAO_STATUS') then
begin
DisplayLabel := 'Descrição do Status';
CustomConstraint := sCC_ValueIsNotNull;
end
end;
initialization
//Registra a Classe para ser utilizada posteriormente com a function FindClass('TClassStatus');
//Pode ser utilizada para criação dinâmica de formulários;
RegisterClass(TClassStatus);
end.
|
{
*************************
* Игра *
* "Водопровод" *
*************************
* Разработчик: *
* Карпов Максим *
*************************
}
unit UMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Registry, ComCtrls;
type
TMain = record
Start : TPoint;
Finish : TPoint;
end;
TForm1 = class(TForm)
POLE: TImage;
START: TButton;
PIPES: TImage;
NEXT: TImage;
BEVEL: TBevel;
MAINPIPES: TImage;
LoadTimer: TTimer;
Label1: TLabel;
LEVEL: TLabel;
Label3: TLabel;
PROGRESS: TProgressBar;
TimeLabel: TLabel;
Timer1: TTimer;
Label4: TLabel;
procedure SetPipe(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure NewPipe;
procedure FormCreate(Sender: TObject);
function CheckOut : Boolean;
procedure STARTClick(Sender: TObject);
function LoadLevel(number : Integer) : Boolean;
procedure DrawMP;
procedure LoadTimerTimer(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
Water : TColor = $00B000;
var
Form1: TForm1;
VPole: array [1..10, 1..10] of Boolean;
MP : TMain;
CurrentLevel : Integer = 1;
Time : Integer;
implementation
{$R *.dfm}
procedure TForm1.DrawMP;
begin
//Очистка от труб
POLE.Canvas.Brush.Color := clBlack;
POLE.Canvas.Rectangle(0,0,320, 320);
//Рисуем старт
Pole.Canvas.CopyRect(Rect(MP.Start.X * 32, MP.Start.Y * 32, (MP.Start.X + 1) * 32, (MP.Start.Y + 1) * 32), MAINPIPES.Canvas, Rect(0, 0, 32, 32));
//Рисуем финиш
Pole.Canvas.CopyRect(Rect(MP.Finish.X * 32, MP.Finish.Y * 32, (MP.Finish.X + 1) * 32, (MP.Finish.Y + 1) * 32), MAINPIPES.Canvas, Rect(33, 0, 64, 32));
end;
function TForm1.LoadLevel(number : Integer) : Boolean;
var REG : TRegistry;
begin
result := true;
REG := TRegistry.Create;
REG.RootKey := HKEY_LOCAL_MACHINE;
REG.OpenKey('SOFTWARE\Vodoprovod', false);
If REG.CurrentPath = '' then begin
Application.Terminate;
Abort;
end;
If REG.ReadInteger('Levels') < number then begin
result := false;
exit;
end;
Reg.OpenKey('Level' + IntToStr(number), false);
If Reg.CurrentPath = 'Vodoprovod' then begin
Application.Terminate;
Abort;
end;
MP.Start.X := Reg.ReadInteger('StartX');
MP.Start.Y := Reg.ReadInteger('StartY');
MP.Finish.X := Reg.ReadInteger('FinishX');
MP.Finish.Y := Reg.ReadInteger('FinishY');
Time := Reg.ReadInteger('Time');
PROGRESS.Max := Time;
PROGRESS.Position := Time;
DrawMP;
end;
function TForm1.CheckOut : Boolean;
var a, b : Integer;
waterout, onfinish : Boolean;
begin
onfinish := false;
waterout := false;
//Проверка, вылилась ли вода.
for a := 1 to 10 do begin
for b := 1 to 10 do begin
If ((a = MP.Start.X + 1) and (b = MP.Start.Y + 1)) or
((a = MP.Finish.X + 1) and (b = MP.Finish.Y + 1)) then continue;
If (VPole[a, b] = false) and (POLE.Canvas.Pixels[a*32-16, b*32-16] = Water)then
waterout := true;
end;
end;
//Проверка, досигла ли она финиша
If POLE.Canvas.Pixels[MP.Finish.X*32-16, MP.Finish.Y*32-16] = Water
then onfinish := true;
result := (not waterout) and onfinish;
end;
procedure TForm1.SetPipe(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var XClick, YClick : Integer;
begin
XClick := X div 32;
YClick := Y div 32;
//Проверка, не является ли точка стартом или финишом
If ((XClick = MP.Start.X) and (YClick = MP.Start.Y)) or ((XClick = MP.Finish.X) and (YClick = MP.Finish.Y)) then exit;
VPole[XClick + 1, YClick + 1] := true;
Pole.Canvas.CopyRect(Rect(XClick * 32, YClick * 32, (XClick + 1) * 32, (YClick + 1) * 32), NEXT.Canvas, Rect(0, 0, 32, 32));
NewPipe;
end;
procedure TForm1.NewPipe;
var num : integer;
begin
num := Random(6);
NEXT.Canvas.CopyRect(Rect(0, 0, 32, 32), PIPES.Canvas, Rect(num * 32, 0, (num + 1) * 32, 32));
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Randomize;
NewPipe;
LoadLevel(1);
end;
procedure TForm1.STARTClick(Sender: TObject);
begin
POLE.Canvas.Brush.Color := Water;
POLE.Canvas.FloodFill((MP.Start.X+1)*32-16, (MP.Start.Y+1)*32-16, clBlack, fsSurface);
If not CheckOut then begin
ShowMessage('Вы проиграли!');
CurrentLevel := 0;
end;
LoadTimer.Enabled := true;
end;
procedure TForm1.LoadTimerTimer(Sender: TObject);
begin
LoadTimer.Enabled := false;
CurrentLevel := CurrentLevel+1;
If not LoadLevel(CurrentLevel) then begin
ShowMessage('Вы выиграли');
START.Enabled := false;
Timer1.Enabled := false;
end;
LEVEL.Caption := 'Уровень: ' + IntToStr(CurrentLevel);
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Time := Time - 1;
TimeLabel.Caption := IntToStr(Time div 60) + ':' + IntToStr(Time mod 60);
If Time = 0 then START.Click;
PROGRESS.Position := TIME;
end;
end.
|
{ Mandelbrot set }
{ Turbo Pascal Source }
{ Adapted by Joao Paulo Schwarz Schuler }
uses dos,crt;
procedure DMG(b:BYTE);
{ define modo de video }
{ define video mode }
VAR R:REGISTERS;
BEGIN
R.AL:=B;
R.AH:=0;
INTR($10,R);
END;
procedure DPIXEL(X,Y:WORD;C:BYTE);
{define pixel}
VAR R:REGISTERS;
BEGIN
R.AH:=12;
R.DX:=Y;
R.CX:=X;
R.AL:=C;
r.bx:=0;
INTR($10,R);
END;
function MSetLevel(cx,cy,maxiter:real):integer;
(*
Function returning level set of a point
*)
var iter:integer;
x,y,x2,y2:real;
temp:real;
begin
X:=0;y:=0;x2:=0;y2:=0;
iter:=0;
while (iter < maxiter) and (x2+y2 < 10000) do begin
temp:=x2-y2+cx;
y:=2*x*y+cy;
x:=temp;
x2:=x*x;
y2:=y*y;
iter:=iter+1
end;
MSetLevel:=iter;
end;
procedure MSetLSM(NX,NY:integer;XMIN,XMAX,YMIN,YMAX,MAXITER:REAL);
(*
Mandelbrot set via Level Set Method LSM of page 188
*)
var ix,iy:integer;
cx,cy:real;
begin
for iy:=0 to ny-1 do begin
cy:=ymin+iy*(ymax-ymin)/(ny-1);
for ix:=0 to nx-1 do begin
cx:=xmin+ix*(xmax-xmin)/(nx-1);
dpixel(ix,iy,MSetLevel(cx,cy,maxiter)+48 );
end;
end;
end;
VAR Xi,Xa,Yi,Ya:real;
modo,b,MAX:byte;
c:char;
x,y,i:integer;
r:registers;
begin
WriteLn('Sugestion: -0.14 0');
Write('Xmin,Xmax(Real Number):');
ReadLn(Xi,Xa);
Writeln('Sugestion: -1 -.9');
write('Ymin,Ymax(Real Number):');
Readln(Yi,Ya);
Writeln('Sugestion: 200');
Write('MAXITER(Natural Number):');
Read(MAX);
writeln;writeln(' All display modes has 256 colors ');
writeln(' on VGA board.');
writeln('Try 1 first');
writeln('1 - 320 x 200 with 64000 pixels');
writeln('2 - 640 x 400 with 256000 pixels');
writeln('3 - 640 x 480 with 307200 pixels');
writeln('4 - 800 x 600 with 480000 pixels');
writeln('5 - 1024 x 768 with 768432 pixels');
c:=readkey;
if c='1' then begin modo:=$13; x:=320;y:=200; end;
if c='2' then begin modo:=$5c; x:=640;y:=400; end;
if c='3' then begin modo:=$5d; x:=640;y:=480; end;
if c='4' then begin modo:=$5e; x:=800;y:=600; end;
if c='5' then begin modo:=$62; x:=1024; y:=768; end;
(*SVGA/oak dmg($59); *)
dmg(modo);
MSetLSM(x,y,Xi,Xa,Yi,Ya,max);
repeat until keypressed;
dmg(2);
end. |
unit CSVSupport;
interface
uses
SysUtils, Classes,
AdvFiles, AdvCSVFormatters;
Type
TCSVWriter = class (TAdvCSVFormatter)
private
public
procedure cell(s : String); overload;
procedure cell(b : boolean); overload;
procedure cell(i : integer); overload;
procedure line;
end;
TGetCsvValues = reference to Procedure (csv : TCSVWriter);
procedure produceCsv(filename : String; headers : Array of String; values : TGetCsvValues);
implementation
procedure produceCsv(filename : String; headers : Array of String; values : TGetCsvValues);
var
csv : TCSVWriter;
arr : TArray<String>;
s : String;
begin
csv := TCSVWriter.Create;
try
csv.Stream := TAdvFile.Create(filename, fmCreate);
for s in headers do
csv.cell(s);
csv.line;
values(csv);
finally
csv.Free;
end;
end;
{ TCSVWriter }
procedure TCSVWriter.cell(s: String);
begin
HasQuote := (s.Contains('"') or s.Contains(','));
ProduceEntry(s);
end;
procedure TCSVWriter.cell(b: boolean);
begin
if (b) then
ProduceEntry('true')
else
ProduceEntry('false');
end;
procedure TCSVWriter.cell(i: integer);
begin
cell(inttostr(i));
end;
procedure TCSVWriter.line;
begin
ProduceNewLine;
end;
end.
|
unit uClient;
interface
// IdGlobal => 用到 TIdBytes, RawToBytes
//
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdContext,
IdCustomTCPServer, IdTCPServer, IdGlobal, IdException, Vcl.ExtCtrls,
UnitGlobal,
uThread;
type
TFormClient = class(TForm)
BtnSendStruct: TButton;
IdTCPClient1: TIdTCPClient;
BtnSendTString: TButton;
BtnSendUTF8: TButton;
Memo1: TMemo;
tmrAutoConnect: TTimer;
BtnStart: TButton;
BtnStop: TButton;
edtHost: TLabeledEdit;
edtPort: TLabeledEdit;
BtnClearMemo: TButton;
tmReadLn: TTimer;
edtMsg: TEdit;
btnDiscon: TButton;
btnASCII: TButton;
procedure BtnSendStructClick(Sender: TObject);
procedure BtnSendTStringClick(Sender: TObject);
procedure BtnSendUTF8Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure tmrAutoConnectTimer(Sender: TObject);
procedure IdTCPClient1Connected(Sender: TObject);
procedure BtnStopClick(Sender: TObject);
procedure BtnStartClick(Sender: TObject);
procedure IdTCPClient1AfterBind(Sender: TObject);
procedure IdTCPClient1BeforeBind(Sender: TObject);
procedure IdTCPClient1Disconnected(Sender: TObject);
procedure IdTCPClient1SocketAllocated(Sender: TObject);
procedure IdTCPClient1Status(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: string);
procedure IdTCPClient1Work(ASender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
procedure IdTCPClient1WorkBegin(ASender: TObject; AWorkMode: TWorkMode;
AWorkCountMax: Int64);
procedure IdTCPClient1WorkEnd(ASender: TObject; AWorkMode: TWorkMode);
procedure BtnClearMemoClick(Sender: TObject);
procedure tmReadLnTimer(Sender: TObject);
procedure btnDisconClick(Sender: TObject);
procedure edtMsgKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnASCIIClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
thread: TReadThread;
procedure InitConnectGUI(init: Boolean);
procedure EnableSendBtn(enable: Boolean);
public
{ Public declarations }
procedure ParseCmd(cmd: String);
end;
var
FormClient: TFormClient;
SendData: TMyData;
implementation
{$R *.dfm}
procedure TFormClient.FormCreate(Sender: TObject);
begin
// 先使用 IdTCPClient1 中的設定值
edtHost.Text := IdTCPClient1.Host;
edtPort.Text := IntToStr(IdTCPClient1.Port);
InitConnectGUI(True);
EnableSendBtn(False);
end;
procedure TFormClient.FormShow(Sender: TObject);
begin
// 執行後自動連線
BtnStartClick(Sender);
end;
procedure TFormClient.IdTCPClient1AfterBind(Sender: TObject);
begin
Memo1.Lines.Add('C-AfterBind');
end;
procedure TFormClient.IdTCPClient1BeforeBind(Sender: TObject);
begin
Memo1.Lines.Add('C-BeforeBind');
end;
procedure TFormClient.IdTCPClient1Connected(Sender: TObject);
begin
Memo1.Lines.Add(DateTimeToStr(Now));
Memo1.Lines.Add('C-Connected');
BtnStop.Enabled := False;
EnableSendBtn(True);
// 用 thread 的方法
thread := TReadThread.Create;
thread.IdTCPClient := IdTCPClient1;
thread.FreeOnTerminate := True;
// 用 timer 的方法,會影響 mian thread
// tmReadLn.Enabled := True;
end;
procedure TFormClient.IdTCPClient1Disconnected(Sender: TObject);
begin
tmReadLn.Enabled := False;
thread.Terminate;
Memo1.Lines.Add(DateTimeToStr(Now));
Memo1.Lines.Add('C-Disconnected');
end;
procedure TFormClient.IdTCPClient1SocketAllocated(Sender: TObject);
begin
Memo1.Lines.Add('C-SocketAllocated');
end;
procedure TFormClient.IdTCPClient1Status(ASender: TObject;
const AStatus: TIdStatus; const AStatusText: string);
begin
Memo1.Lines.Add(DateTimeToStr(Now));
Memo1.Lines.Add('C-Status: ' + AStatusText);
end;
procedure TFormClient.IdTCPClient1Work(ASender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
begin
// 這邊會一直 run
// Memo1.Lines.Add('C-Client1Work');
end;
procedure TFormClient.IdTCPClient1WorkBegin(ASender: TObject;
AWorkMode: TWorkMode; AWorkCountMax: Int64);
begin
Memo1.Lines.Add('C-WorkBegin');
end;
procedure TFormClient.IdTCPClient1WorkEnd(ASender: TObject;
AWorkMode: TWorkMode);
begin
Memo1.Lines.Add('C-WorkEnd');
end;
procedure TFormClient.tmrAutoConnectTimer(Sender: TObject);
begin
if not IdTCPClient1.Connected then
begin
Memo1.Lines.Add('Timer1每5秒自動連線中…');
try
IdTCPClient1.Connect;
except
on E: EIdException do
Memo1.Lines.Add('== EIdException: ' + E.Message);
end;
end
else
begin
tmrAutoConnect.Enabled := False;
Memo1.Lines.Add('自動連線已連上,關閉tmrAutoConnect');
end;
end;
// 只是比較用,實際使用時,用 thread 比較好
procedure TFormClient.tmReadLnTimer(Sender: TObject);
var
S: String;
begin
try
if IdTCPClient1.IOHandler.InputBufferIsEmpty then
IdTCPClient1.IOHandler.CheckForDataOnSource(0);
while not IdTCPClient1.IOHandler.InputBufferIsEmpty do
begin
S := IdTCPClient1.IOHandler.ReadLn(IndyTextEncoding_UTF8);
Memo1.Lines.Add(S);
end;
except
on E: EIdException do
IdTCPClient1.Disconnect;
end;
end;
procedure TFormClient.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if IdTCPClient1.Connected then
begin
try
IdTCPClient1.Disconnect;
except
on E: EIdException do
ShowMessage('EIdException: ' + E.Message);
end;
end;
end;
procedure TFormClient.btnASCIIClick(Sender: TObject);
begin
if not IdTCPClient1.Connected then
begin
Memo1.Lines.Add('IdTCPClient 已斷線');
Exit;
end;
IdTCPClient1.IOHandler.WriteLn(edtMsg.Text, IndyTextEncoding_ASCII);
end;
procedure TFormClient.BtnClearMemoClick(Sender: TObject);
begin
Memo1.Clear;
end;
procedure TFormClient.btnDisconClick(Sender: TObject);
begin
IdTCPClient1.Disconnect;
InitConnectGUI(False);
EnableSendBtn(False);
end;
procedure TFormClient.BtnSendStructClick(Sender: TObject);
begin
if not IdTCPClient1.Connected then
begin
Memo1.Lines.Add('IdTCPClient 已斷線');
Exit;
end;
SendData.ID := 10;
StrPCopy(SendData.Name, 'Roger');
StrPCopy(SendData.Sex, '男');
SendData.Age := 25;
StrPCopy(SendData.Address, '高雄市');
SendData.UpdateTime := Now;
IdTCPClient1.IOHandler.Write(MY_CMD_STRUCT);
// 把自訂的型態用 RawToBytes 送出
IdTCPClient1.IOHandler.Write(RawToBytes(SendData, SizeOf(SendData)));
end;
procedure TFormClient.BtnSendTStringClick(Sender: TObject);
var
sList: TStrings;
I: Integer;
begin
if not IdTCPClient1.Connected then
begin
Memo1.Lines.Add('IdTCPClient 已斷線');
Exit;
end;
sList := TStringList.Create;
for I := 0 to 30 do
begin
sList.Add('數據index' + IntToStr(I));
end;
IdTCPClient1.IOHandler.Write(MY_CMD_TSTRING);
IdTCPClient1.IOHandler.Write(sList.Count);
IdTCPClient1.IOHandler.Write(ToBytes(sList.Text, IndyTextEncoding_UTF8));
end;
procedure TFormClient.BtnSendUTF8Click(Sender: TObject);
begin
if not IdTCPClient1.Connected then
begin
Memo1.Lines.Add('IdTCPClient 已斷線');
Exit;
end;
IdTCPClient1.IOHandler.Write(MY_CMD_UTF8);
// 中文要指定編碼,接收時也要進行相應的轉換,否則中文會顯示成?號
IdTCPClient1.IOHandler.WriteLn(edtMsg.Text, IndyTextEncoding_UTF8);
end;
procedure TFormClient.BtnStartClick(Sender: TObject);
begin
IdTCPClient1.Host := edtHost.Text;
IdTCPClient1.Port := StrToInt(edtPort.Text);
Memo1.Lines.Add('tmrAutoConnect已啟動,稍待 ' + FloatToStr(tmrAutoConnect.Interval /
1000) + ' 秒');
InitConnectGUI(True);
end;
procedure TFormClient.BtnStopClick(Sender: TObject);
begin
InitConnectGUI(False);
end;
procedure TFormClient.edtMsgKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = vk_Return then
BtnSendUTF8Click(Sender);
end;
procedure TFormClient.ParseCmd(cmd: String);
begin
Memo1.Lines.Add(cmd);
end;
procedure TFormClient.InitConnectGUI(init: Boolean);
begin
tmrAutoConnect.Enabled := init;
BtnStart.Enabled := not init;
BtnStop.Enabled := init;
btnDiscon.Enabled := init;
end;
procedure TFormClient.EnableSendBtn(enable: Boolean);
begin
BtnSendStruct.Enabled := enable;
BtnSendTString.Enabled := enable;
BtnSendUTF8.Enabled := enable;
btnASCII.Enabled := enable;
end;
end.
|
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
unit corewebsocket;
interface
uses
corenetwork, sysutils;
//{$DEFINE WEBSOCKET_VERBOSE}
type
TWebSocket = class(TNetworkSocket)
protected
type
TWebSocketState = (wsRequestLine,
wsFieldTrailingEnd, wsFieldEnd, wsFieldNameStart, wsFieldName, wsFieldSeparator, wsFieldValue, wsHandshakeEnd,
wsFrameByte1, wsFrameByte2, wsFrameExtendedLength16, wsFrameExtendedLength64, wsFrameMask, wsFramePayload,
wsError);
TWebSocketFrameType = (ftContinuation := $00, ftText := $01, ftBinary := $02, ftClose := $08, ftPing := $09, ftPong := $0A);
TWebSocketFrame = record
FrameType: TWebSocketFrameType;
FinalFrame: Boolean;
MaskKey: array[0..3] of Byte;
Length, Index: Cardinal;
Data: RawByteString;
end;
var
FState: TWebSocketState;
FCanWriteFrames: Boolean;
FCurrentFrame: TWebSocketFrame;
FBufferType: TWebSocketFrameType;
FBuffer: RawByteString;
FCurrentFieldName, FCurrentFieldValue, FHandshakeKey: RawByteString;
function InternalRead(Data: array of Byte): Boolean; override;
procedure CheckField(); virtual;
procedure Handshake(); virtual;
procedure ProcessFrame();
// API for subclasses:
procedure HandleMessage(s: RawByteString); virtual; abstract;
procedure WriteFrame(s: RawByteString); {$IFDEF DEBUG} virtual; {$ENDIF}
public
constructor Create(Listener: TListenerSocket);
property Ready: Boolean read FCanWriteFrames;
end;
implementation
uses
sha1, base64encoder;
constructor TWebSocket.Create(Listener: TListenerSocket);
begin
inherited Create(Listener);
FState := wsRequestLine;
end;
function TWebSocket.InternalRead(Data: array of Byte): Boolean;
var
Index: Cardinal;
c: Byte;
begin
Result := True;
Assert(Length(Data) > 0);
for Index := 0 to Length(Data)-1 do {BOGUS Warning: Type size mismatch, possible loss of data / range check error}
begin
c := Data[Index];
case FState of
wsRequestLine, wsFieldTrailingEnd:
case c of
$0D: FState := wsFieldEnd;
end;
wsFieldEnd:
case c of
$0A: FState := wsFieldNameStart;
else
FState := wsError;
Result := False;
Exit;
end;
wsFieldNameStart:
case c of
$0D: FState := wsHandshakeEnd;
Ord(':'): FState := wsFieldTrailingEnd;
else
FCurrentFieldName := Chr(c);
FState := wsFieldName;
end;
wsFieldName:
case c of
Ord(':'): FState := wsFieldSeparator;
$0D: FState := wsFieldEnd;
else
FCurrentFieldName := FCurrentFieldName + Chr(c);
end;
wsFieldSeparator:
case c of
Ord(' '): begin FState := wsFieldValue; FCurrentFieldValue := ''; end;
$0D: FState := wsFieldEnd;
else
FState := wsError;
Result := False;
Exit;
end;
wsFieldValue:
case c of
$0D: begin FState := wsFieldEnd; CheckField(); end;
else
FCurrentFieldValue := FCurrentFieldValue + Chr(c);
end;
wsHandshakeEnd:
case c of
$0A: begin FState := wsFrameByte1; Handshake(); end;
else
FState := wsError;
Result := False;
Exit;
end;
wsFrameByte1:
begin
FCurrentFrame.FrameType := TWebSocketFrameType(c and $0F);
// assume bits 5, 6, and 7 are zero (extension bits, we don't negotiate any extensions)
FCurrentFrame.FinalFrame := (c and $80) = $80;
FState := wsFrameByte2;
end;
wsFrameByte2:
begin
FCurrentFrame.Length := (c and $7F);
// assume bit 8 is set (masking bit, client must mask)
FCurrentFrame.Index := 0;
case (FCurrentFrame.Length) of
0..125: FState := wsFrameMask;
126: begin FCurrentFrame.Length := 0; FState := wsFrameExtendedLength16; end;
127: begin FCurrentFrame.Length := 0; FState := wsFrameExtendedLength64; end;
else Assert(False);
end;
end;
wsFrameExtendedLength16, wsFrameExtendedLength64:
begin
FCurrentFrame.Length := FCurrentFrame.Length or (c shl (FCurrentFrame.Index * 8));
Inc(FCurrentFrame.Index);
if (((FState = wsFrameExtendedLength16) and (FCurrentFrame.Index = 2)) or
((FState = wsFrameExtendedLength64) and (FCurrentFrame.Index = 8))) then
begin
FCurrentFrame.Index := 0;
FState := wsFrameMask;
end;
end;
wsFrameMask:
begin
FCurrentFrame.MaskKey[FCurrentFrame.Index] := c;
Inc(FCurrentFrame.Index);
if (FCurrentFrame.Index = 4) then
begin
if (FCurrentFrame.Length > 1024) then
begin
FState := wsError;
Result := False;
Exit;
end
else
begin
SetLength(FCurrentFrame.Data, FCurrentFrame.Length);
if (FCurrentFrame.Length > 0) then
begin
FCurrentFrame.Index := 1;
FState := wsFramePayload;
end
else
begin
ProcessFrame();
FState := wsFrameByte1;
end;
end;
end;
end;
wsFramePayload:
begin
FCurrentFrame.Data[FCurrentFrame.Index] := Chr(c xor FCurrentFrame.MaskKey[(FCurrentFrame.Index-1) mod 4]);
Inc(FCurrentFrame.Index);
if (FCurrentFrame.Index > FCurrentFrame.Length) then
begin
ProcessFrame();
FState := wsFrameByte1;
end;
end;
else Assert(False);
end;
end;
end;
procedure TWebSocket.CheckField();
begin
if (FCurrentFieldName = 'Sec-WebSocket-Key') then
FHandshakeKey := FCurrentFieldValue
{ ... Host, Origin, Sec-WebSocket-Protocol, ... }
end;
procedure TWebSocket.Handshake();
var
Challenge, Response: RawByteString;
Digest: TSHA1Digest;
Index: Cardinal;
begin
Challenge := FHandshakeKey + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
Digest := SHA1String(Challenge);
Response := '';
for Index := Low(Digest) to High(Digest) do
Response := Response + Chr(Digest[Index]);
Response := Base64(Response);
Write('HTTP/1.1 101 WebSocket Protocol Handshake'#13#10);
Write('Upgrade: WebSocket'#13#10);
Write('Connection: Upgrade'#13#10);
Write('Sec-WebSocket-Accept: ' + Response + #13#10);
Write(#13#10);
FCanWriteFrames := True;
end;
procedure TWebSocket.ProcessFrame();
begin
case (FCurrentFrame.FrameType) of
ftContinuation:
begin
FBuffer := FBuffer + FCurrentFrame.Data;
if ((FCurrentFrame.FinalFrame) and (FBufferType = ftText)) then
begin
HandleMessage(FBuffer);
FBuffer := '';
end;
end;
ftText:
begin
FBuffer := FCurrentFrame.Data;
FBufferType := ftText;
if (FCurrentFrame.FinalFrame) then
begin
HandleMessage(FBuffer);
FBuffer := '';
end;
end;
ftBinary:
begin
// we don't support binary frames
FBuffer := '';
FBufferType := ftBinary;
end;
ftClose:
begin
// we don't support this per spec, just close the connection
Disconnect();
end;
ftPing, ftPong:
begin
// we don't support ping frames
end;
end;
end;
procedure TWebSocket.WriteFrame(s: RawByteString);
begin
{$IFDEF WEBSOCKET_VERBOSE} Writeln('Sending: ', s); {$ENDIF}
Assert(FCanWriteFrames);
Write([$81]); // unfragmented text frame
if (Length(s) > 65536) then
Write([127,
Byte((Length(s) shr 8*7) and $FF),
Byte((Length(s) shr 8*6) and $FF),
Byte((Length(s) shr 8*5) and $FF),
Byte((Length(s) shr 8*4) and $FF),
Byte((Length(s) shr 8*3) and $FF),
Byte((Length(s) shr 8*2) and $FF),
Byte((Length(s) shr 8*1) and $FF),
Byte((Length(s) ) and $FF)])
else
if (Length(s) > 126) then
Write([126,
Byte((Length(s) shr 8*1) and $FF),
Byte((Length(s) ) and $FF)])
else
Write([Byte(Length(s))]);
if (Length(s) > 0) then
Write(s);
end;
end.
|
unit Iocp.ApiFix;
interface
uses
Windows;
(*
Delphi自带的IOCP相关的几个函数定义是错的!
在32位程序下不会出问题,但是64位程序里就错了
Delphi XE2支持64位编译,但是XE2直到Update4的定义都是错的,希望以后官方会修正
// 这是Delphi的错误定义,
// CompletionKey: DWORD
// DWORD不管在32位还是64位程序中都是4字节,MSDN中正确的定义是ULONG_PTR
// ULONG_PTR在32位程序中是4字节,在64位程序中是8字节
function CreateIoCompletionPort(FileHandle, ExistingCompletionPort: THandle;
CompletionKey, NumberOfConcurrentThreads: DWORD): THandle; stdcall;
{$EXTERNALSYM CreateIoCompletionPort}
function GetQueuedCompletionStatus(CompletionPort: THandle;
var lpNumberOfBytesTransferred, lpCompletionKey: DWORD;
var lpOverlapped: POverlapped; dwMilliseconds: DWORD): BOOL; stdcall;
{$EXTERNALSYM GetQueuedCompletionStatus}
function PostQueuedCompletionStatus(CompletionPort: THandle; dwNumberOfBytesTransferred: DWORD;
dwCompletionKey: DWORD; lpOverlapped: POverlapped): BOOL; stdcall;
{$EXTERNALSYM PostQueuedCompletionStatus}
*)
// 后面是我自己根据MSDN相关文档修正后的定义
function CreateIoCompletionPort(FileHandle, ExistingCompletionPort: THandle;
CompletionKey: ULONG_PTR; NumberOfConcurrentThreads: DWORD): THandle; stdcall;
function GetQueuedCompletionStatus(CompletionPort: THandle;
var lpNumberOfBytesTransferred: DWORD; var lpCompletionKey: ULONG_PTR;
var lpOverlapped: POverlapped; dwMilliseconds: DWORD): BOOL; stdcall;
function PostQueuedCompletionStatus(CompletionPort: THandle; dwNumberOfBytesTransferred: DWORD;
dwCompletionKey: ULONG_PTR; lpOverlapped: POverlapped): BOOL; stdcall;
implementation
function CreateIoCompletionPort; external kernel32 name 'CreateIoCompletionPort';
function GetQueuedCompletionStatus; external kernel32 name 'GetQueuedCompletionStatus';
function PostQueuedCompletionStatus; external kernel32 name 'PostQueuedCompletionStatus';
end.
|
{$M 16384, $20000, $20000}
{$X+,G+,D-,L-,S-,R-}
unit Drive;
interface
uses Objects, Service, Crt;
type
TSector = Record
Flag : Byte;
No : Byte;
end;
PTrackMap = ^TTrackMap;
TTrackMap = Array [1..256] of TSector;
PDrive = ^TDrive;
TDrive = Object(TObject)
BIOSDriveNumber : Integer;
Heads : Byte;
Sectors : Byte;
Tracks : Word;
Status, {Current operation status}
LastError : Integer; {Last error code}
constructor Init(DrvNum : Integer);
destructor Done; virtual;
function ResetController : Byte; virtual;
function CheckDiskStatus : Byte; virtual;
function ControllerDiagnostic : Byte; virtual;
function RecalibrateDrive : Byte; virtual;
function IsDriveInstalled : Byte; virtual;
function GetBIOSGeometry(var BIOSTracks : Word; var BIOSHeads, BIOSSectors : Byte) : Byte; virtual;
function ReadSectors(Track : Word; Head, StartSect, SectorsCount : Byte; Buffer : Pointer) : Byte; virtual;
function WriteSectors(Track : Word; Head, StartSect, SectorsCount : Byte; Buffer : Pointer) : Byte; virtual;
function VerifySectors(Track : Word; Head, StartSect, SectorsCount : Byte) : Byte; virtual;
function DetailedVerifyTrack(Track : Word; Head : Byte; var TrackMap : TTrackMap) : Byte; virtual;
function FormatTrack(Track : Word; Head : Byte; Buffer : Pointer) : Byte; virtual;
function SeekToTrack(Track : Word) : Byte; virtual;
function RecoverTrack(Track : Word; Head : Byte; var TrackMap : TTrackMap) : Byte; virtual;
function GetErrorMessage(ErrorCode : Integer) : String; virtual;
function GetModel : String; virtual;
function GetType : String; virtual;
function GetSize : LongInt; virtual;
procedure ResetStatus; virtual;
end;
function GetDrivesNumber : Byte;
implementation
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function GetDrivesNumber : Byte; assembler;
asm
mov ah,08h
mov dl,80h
int 13h
mov al,0
jc @1
mov al,dl
@1:
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
constructor TDrive.Init(DrvNum : Integer);
begin
inherited Init;
BIOSDriveNumber := DrvNum;
GetBIOSGeometry(Tracks, Heads, Sectors);
If (Tracks = 1) or (Heads = 1) or (Sectors = 0) Then Status := -1;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
destructor TDrive.Done;
begin
inherited Done;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.ResetController : Byte;
var
Drive : Byte;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
asm
mov dl,Drive
mov ah,0
int 13h
jnc @1
mov Stat,ah
@1:
end;
Status := Stat; ResetController := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.CheckDiskStatus : Byte;
var
Drive : Byte;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
asm
mov dl,Drive
mov ah,1
int 13h
jnc @1
mov Stat,ah
@1:
end;
Status := Stat; CheckDiskStatus := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.ControllerDiagnostic : Byte;
var
Drive : Byte;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
asm
mov dl,Drive
mov ah,14h
int 13h
jnc @1
mov Stat,ah
@1:
end;
Status := Stat; ControllerDiagnostic := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.RecalibrateDrive : Byte;
var
Drive : Byte;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
asm
mov dl,Drive
mov ah,11h
int 13h
jnc @1
mov Stat,ah
@1:
end;
Status := Stat; RecalibrateDrive := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.IsDriveInstalled : Byte;
var
Drive : Byte;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
asm
mov dl,Drive
mov ah,15h
int 13h
jnc @1
mov Stat,ah
@1:
end;
Status := Stat; IsDriveInstalled := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.GetBIOSGeometry(var BIOSTracks : Word; var BIOSHeads, BIOSSectors : Byte) : Byte;
var
Drive : Byte;
MaxHead,
MaxSector : Byte;
MaxTrack : Word;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
MaxTrack := 0; MaxHead := 0; MaxSector := 0;
asm
mov ah,8
mov dl,Drive
int 13h
jnc @1
mov Stat,ah
jmp @2
@1:
dec dl
or dl,80h
cmp dl,BIOSDriveNumber
jc @2
mov MaxHead,dh
mov al,cl
and al,$3f
mov MaxSector,al
xor ax,ax
and cl,$C0
mov al,cl
shl ax,2
mov al,ch
mov MaxTrack,ax
@2:
end;
BIOSTracks := MaxTrack+1; BIOSHeads := MaxHead+1; BIOSSectors := MaxSector;
Status := Stat; GetBIOSGeometry := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.ReadSectors(Track : Word; Head, StartSect, SectorsCount : Byte; Buffer : Pointer) : Byte;
var
Drive : Byte;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
asm
mov dl,Drive
mov dh,Head
mov cx,Track
xchg cl,ch
shl cl,6
add cl,StartSect
les bx,Buffer
mov al,SectorsCount
mov ah,02h
int 13h
jnc @1
mov Stat,ah
@1:
end;
Status := Stat; ReadSectors := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.WriteSectors(Track : Word; Head, StartSect, SectorsCount : Byte; Buffer : Pointer) : Byte;
var
Drive : Byte;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
asm
mov dl,Drive
mov dh,Head
mov cx,Track
xchg cl,ch
shl cl,6
add cl,StartSect
les bx,Buffer
mov al,SectorsCount
mov ah,03h
int 13h
jnc @1
mov Stat,ah
@1:
end;
Status := Stat; WriteSectors := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.VerifySectors(Track : Word; Head, StartSect, SectorsCount : Byte) : Byte;
var
Drive : Byte;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
asm
mov dl,Drive
mov dh,Head
mov cx,Track
xchg cl,ch
shl cl,6
or cl,StartSect
mov al,SectorsCount
mov ah,04h
int 13h
jnc @1
mov Stat,ah
@1:
end;
Status := Stat; VerifySectors := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.DetailedVerifyTrack(Track : Word; Head : Byte; var TrackMap : TTrackMap) : Byte;
var
i : Word;
Errors : Byte;
begin
Errors := 0;
for i := 1 to Sectors do
With TrackMap[i] do
begin
Flag := VerifySectors(Track, Head, i, 1);
If Flag <> 0 Then Inc(Errors);
No := i;
end;
DetailedVerifyTrack := Errors;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.FormatTrack(Track : Word; Head : Byte; Buffer : Pointer) : Byte;
var
Drive : Byte;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
asm
mov dl,Drive
mov dh,Head
mov cx,Track
xchg cl,ch
shl cl,6
add cl,1
les bx,Buffer
mov ah,05h
int 13h
jnc @1
mov Stat,ah
@1:
end;
Status := Stat; FormatTrack := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.SeekToTrack(Track : Word) : Byte;
var
Drive : Byte;
Stat : Byte;
begin
Drive := BIOSDriveNumber; Stat := 0;
asm
mov dl,Drive
mov dh,0
mov cx,Track
xchg cl,ch
shl cl,6
or cl,1 {???}
mov ah,0Ch
int 13h
jnc @1
mov Stat,ah
@1:
end;
Status := Stat; SeekToTrack := Stat;
If Stat <> 0 Then LastError := Stat;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.RecoverTrack(Track : Word; Head : Byte; var TrackMap : TTrackMap) : Byte;
type
PTrackBuf = ^TTrackBuf;
TTrackBuf = Array [1..64] of Array [0..511] of Byte;
var
k : Byte;
Buffer : PTrackBuf;
Defects : Byte;
begin
RecoverTrack := $FF;
MemAlloc(Pointer(Buffer), 64*1024 div 16); {16 byte paragraphs}
If Buffer = Nil Then Exit;
Defects := 0;
for k := 1 to Sectors do
With TrackMap[k] do
begin
{20h - unassign alternate, 40h - assign alternate}
If Flag = 0
Then ReadSectors(Track, Head, k, 1, @Buffer^[k])
Else begin
Inc(Defects);
FillChar(Buffer^[k], 512, #0);
Flag := $40;
{Try to use write auto-reassignment}
WriteSectors(Track, Head, k, 1, @Buffer^[k]);
If VerifySectors(Track, Head, k, 1) = 0 Then
begin
Dec(Defects);
Flag := 0;
end;
end;
No := k;
end;
If Defects > 0 Then
begin
FormatTrack(Track, Head, @TrackMap);
ResetStatus;
for k := 1 to Sectors do
WriteSectors(Track, Head, k, 1, @Buffer^[k]);
MemFree(Pointer(Buffer));
RecoverTrack := LastError;
end;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.GetErrorMessage(ErrorCode : Integer) : String;
begin
Case ErrorCode of
-1 : GetErrorMessage := 'Specified drive not exist';
-2 : GetErrorMessage := 'Can''t allocate '+IntToStr(Sectors div 2)+'Kb of conventional memory for test buffer';
-3 : GetErrorMessage := 'Can''t allocate '+IntToStr(Heads*Sectors div 2+1)+'Kb of XMS memory for cylinder buffer';
$00 : GetErrorMessage := 'No error on last operation';
$01 : GetErrorMessage := 'Bad command: invalid request to controller';
$02 : GetErrorMessage := 'Bad address mark';
$03 : GetErrorMessage := 'Attempted to write on write-protected disk';
$04 : GetErrorMessage := 'Sector ID bad or not found';
$05 : GetErrorMessage := 'Reset failed';
$07 : GetErrorMessage := 'Drive parameter activity failed';
$08 : GetErrorMessage := 'DMA failure';
$09 : GetErrorMessage := 'DMA overrun: can''t write across 64K bound';
$0A : GetErrorMessage := 'Bad sector flag detected';
$0B : GetErrorMessage := 'Bad cylinder detected';
$0D : GetErrorMessage := 'Invalid umber of sectors in format';
$0E : GetErrorMessage := 'Control data address mark detected';
$0F : GetErrorMessage := 'DMA arbitration level out of range';
$10 : GetErrorMessage := 'Uncorrectable ECC or CRC';
$11 : GetErrorMessage := 'ECC corrected data error';
$20 : GetErrorMessage := 'Hard disk controller failure';
$40 : GetErrorMessage := 'Bad seek: requested track not found';
$80 : GetErrorMessage := 'Time-out';
$AA : GetErrorMessage := 'Drive not ready';
$BB : GetErrorMessage := 'Undefined error';
$CC : GetErrorMessage := 'Write fault on selected drive';
$E0 : GetErrorMessage := 'Status error/error register 0';
$FF : GetErrorMessage := 'Sense operation failed';
Else GetErrorMessage := 'Unknown error';
end
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.GetModel : String;
begin
GetModel := 'Non-IDE Drive';
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.GetType : String;
begin
GetType := 'Unknown Type';
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
function TDrive.GetSize : LongInt;
{Size in MBytes}
begin
GetSize := LongInt(Tracks)*LongInt(Heads)*LongInt(Sectors) div 2048;
end;
{ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ}
procedure TDrive.ResetStatus;
begin
Status := 0; LastError := 0;
end;
begin
end.
|
unit RT_DatabaseTest;
interface
uses
Classes, SysUtils, TestFramework,
RT_Database;
type
TDatabaseTest = class (TTestCase)
private
function CreateTestDatabase: TDatabase;
published
procedure TestObserver;
end;
implementation
{ TDatabaseTest }
{ Private declarations }
function TDatabaseTest.CreateTestDatabase: TDatabase;
var
TaxiStop: TTaxiStop;
Street: TStreet;
begin
Result := TDatabase.Create;
TaxiStop := TTaxiStop.Create;
TaxiStop.Id := 1;
TaxiStop.Name := 'Wieczorka';
Result.TaxiStops.Add(TaxiStop);
TaxiStop := TTaxiStop.Create;
TaxiStop.Id := 2;
TaxiStop.Name := 'Dworzec';
Result.TaxiStops.Add(TaxiStop);
Street := TStreet.Create;
Street.Id := 1;
Street.Name := 'Plebańska';
Street.Start := '1';
Street.Stop := '';
Street.TaxiStops.Add(Result.TaxiStops[0]);
Street.TaxiStops.Add(Result.TaxiStops[1]);
Result.Streets.Add(Street);
end;
{ Test cases }
procedure TDatabaseTest.TestObserver;
var
Database: TDatabase;
begin
Database := CreateTestDatabase;
Database.Free;
end;
initialization
RegisterTest(TDatabaseTest.Suite);
end.
|
Unit AdvEvents;
{
Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
AdvObjects, AdvItems, AdvMethods;
Type
TAdvEvent = Procedure (Sender : TAdvObject) Of Object;
TAdvEventList = Class(TAdvMethodList)
Private
Function GetEvent(iIndex : Integer): TAdvEvent;
Procedure SetEvent(iIndex : Integer; Const aValue : TAdvEvent);
Public
Function IndexByValue(aValue : TAdvEvent) : Integer;
Function ExistsByValue(aValue : TAdvEvent) : Boolean;
Function Add(aValue : TAdvEvent) : Integer;
Procedure Insert(iIndex : Integer; aValue : TAdvEvent);
Procedure DeleteByValue(aValue : TAdvEvent);
Property EventByIndex[iIndex : Integer] : TAdvEvent Read GetEvent Write SetEvent; Default;
End;
Implementation
Function TAdvEventList.IndexByValue(aValue : TAdvEvent): Integer;
Begin
Result := Inherited IndexByValue(TAdvMethod(aValue));
End;
Function TAdvEventList.ExistsByValue(aValue: TAdvEvent): Boolean;
Begin
Result := Inherited ExistsByValue(TAdvMethod(aValue));
End;
Function TAdvEventList.Add(aValue : TAdvEvent): Integer;
Begin
Result := Inherited Add(TAdvMethod(aValue));
End;
Procedure TAdvEventList.Insert(iIndex : Integer; aValue : TAdvEvent);
Begin
Inherited Insert(iIndex, TAdvMethod(aValue));
End;
Procedure TAdvEventList.DeleteByValue(aValue : TAdvEvent);
Begin
Inherited DeleteByValue(TAdvMethod(aValue));
End;
Function TAdvEventList.GetEvent(iIndex : Integer): TAdvEvent;
Begin
Assert(ValidateIndex('GetEvent', iIndex));
Result := TAdvEvent(MethodByIndex[iIndex]);
End;
Procedure TAdvEventList.SetEvent(iIndex : Integer; Const aValue : TAdvEvent);
Begin
Assert(ValidateIndex('SetEvent', iIndex));
MethodByIndex[iIndex] := TAdvMethod(aValue);
End;
End. // AdvEvents //
|
// Program to redirect output of a program to \PIPE\WarpMedia
// Based on Virtual Pascal's example program.
Program PipeExec;
{&PMTYPE VIO}
{$Delphi+,T-,X+,Use32-,H+}
Uses
MyOs2Exec, Os2Base, SysUtils, VPUtils;
function Parameters:string; // Returns every parameter of the program, starting from parameter number 2.
var w:word;
begin
result:='';
for w:=2 to paramcount do
begin
if w>2 then result:=result+' ';
result:=result+'"'+paramstr(w)+'"';
end;
end;
const Pipe_Ready:boolean=false;
p:HPipe=0;
function CreatePipeFunc(parm:pointer):longint;
var rc:longint;
begin
// Thread that tries to create the PIPE, and ends if it could.
rc:=DosCreateNPipe('\PIPE\WarpMedia',p,
np_Access_OutBound ,
np_wmesg or np_rmesg or 1,
256, // Output buffer size
256, // Input buffer size
0); // Use default time-out
if rc<>0 then writeln('Error creating pipe, rc=',rc)
else
begin
rc:=DosConnectNPipe(p);
if rc<>0 then writeln('Error connecting pipe, rc=',rc) else
Pipe_Ready:=True;
end;
end;
procedure ClosePipe;
var rc:longint;
begin
if p<>0 then
begin
DosDisConnectNPipe(p);
rc:=DosClose(p);
if rc<>0 then writeln('Error closing pipe, rc=',rc);
end;
Pipe_Ready:=false;
end;
Procedure SendToPipe(s:string);
var rc,actual:longint;
begin
if Pipe_Ready then
begin
rc:=DosWrite(p,s[1], length(s), Actual);
if rc<>0 then
begin
// error writing to pipe, so close it and reopen!
ClosePipe;
VPBeginThread(CreatePipeFunc, 16384, nil);
end;
end;
end;
procedure ExecuteProgram;
Var
tr : TRedirExec;
i : Integer;
x,y : Integer;
s:String;
begin
tr := TRedirExec.Create; // Create a TRedirExec instance
if Assigned( tr ) then // If creation was ok...
try // Catch any errors
{ Execute the command to grab the output from }
tr.Execute( paramstr(1), pchar(Parameters), nil );
While not tr.Terminated do // While command is executing
If tr.MessageReady then // Ask if a line is ready
begin
s:=tr.Message;
Write( s ); // - Display it
SendToPipe(s); // - Send it
end
else
DosSleep( 30 ); // - otherwise wait a little
finally
tr.Destroy; // Free the instance
end
else
Writeln( 'Error creating TRedirExec class instance' );
end;
begin
Writeln( '-= Output redirector active =-' );
PopupErrors := False; // Tell SysUtils to display
// exceptions on user screen
VPBeginThread(CreatePipeFunc, 16384, nil);
ExecuteProgram;
Writeln;
Writeln( '-= Program terminated =-' );
ClosePipe;
end.
|
unit GP3Tests;
interface
uses
TestFramework;
type
// Test methods for unit Geo.pas
TGP3UnitTest = class(TTestCase)
private
public
published
procedure GetVersionTest;
end;
implementation
uses Math, uGPFileParser;
procedure TGP3UnitTest.GetVersionTest;
var
Filename :string;
GP : TGPFileParser;
begin
Filename := '..\files\test.gp3';
GP := TGPFileParserFactory.Execute(Filename);
try
GP.Execute;
CheckEquals('FICHIER GUITAR PRO v3.00', GP.Version, 'Not GP 3 File');
finally
GP.Free;
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TGP3UnitTest.Suite);
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [PRODUTO_SUBGRUPO]
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author ()
@version 1.0
*******************************************************************************}
unit ProdutoSubGrupoVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, ProdutoGrupoVO;
type
[TEntity]
[TTable('PRODUTO_SUBGRUPO')]
TProdutoSubGrupoVO = class(TVO)
private
FID: Integer;
FID_GRUPO: Integer;
FNOME: String;
FDESCRICAO: String;
FProdutoGrupoNome: String;
FProdutoGrupoVO: TProdutoGrupoVO;
public
constructor Create; override;
destructor Destroy; override;
public
[TId('ID', [ldGrid, ldLookup, ldComboBox])]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_GRUPO','Id Grupo',[ldGrid, ldLookup] ,False)]
property IdGrupo: Integer read FID_GRUPO write FID_GRUPO;
[TColumn('NOME','Nome',[ldGrid, ldLookup] ,False)]
property Nome: String read FNOME write FNOME;
[TColumn('DESCRICAO','Descrição',[ldGrid, ldLookup] ,False)]
property Descricao: String read FDESCRICAO write FDESCRICAO;
[TAssociation('ID', 'ID_GRUPO')]
property ProdutoGrupoVO: TProdutoGrupoVO read FProdutoGrupoVO write FProdutoGrupoVO;
end;
implementation
constructor TProdutoSubGrupoVO.Create;
begin
inherited;
FProdutoGrupoVO := TProdutoGrupoVO.Create;
end;
destructor TProdutoSubGrupoVO.Destroy;
begin
FreeAndNil(FProdutoGrupoVO);
inherited;
end;
initialization
Classes.RegisterClass(TProdutoSubGrupoVO);
finalization
Classes.UnRegisterClass(TProdutoSubGrupoVO);
end.
|
//menconst nilai dengan indeks array 1..3 dengan boleean
CONST Nilai : array[1..3] of boolean = (True, False, False);
VAR
I : word;
Begin
//melakukan looping dan menetak nilai nya sesuai looping
FOR I := 1 To 3 Do WRITELN('Nilai ke ',I,' = ', Nilai[I]);
END. |
unit ListingForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, FolderList, Winshoes, WinshoeMessage, NNTPWinshoe;
type
TformListing = class(TForm)
NNTP: TWinshoeNNTP;
Animate1: TAnimate;
butnCancel: TButton;
lablStatus: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure NNTPNewsgroupList(const sNewsgroup: string;
const lLow, lHigh: Integer; const sType: string; var CanContinue: Boolean);
procedure FormActivate(Sender: TObject);
procedure butnCancelClick(Sender: TObject);
procedure NNTPStatus(Sender: TComponent; const sOut: String);
private
FHostData: THostData;
FDownloadCount: Integer;
FCanContinue: Boolean;
procedure SetHostData(Value: THostData);
protected
procedure SetStatusCaption(Value: string);
public
property HostData: THostData read FHostData write SetHostData;
end;
implementation
uses
Datamodule;
{$R *.DFM}
procedure TformListing.SetHostData(Value: THostData);
begin
FHostData := Value;
with NNTP do begin
Host := FHostData.HostName;
Port := FHostData.Port;
UserID := FHostData.UserID;
Password := FHostData.Password;
end;
Caption := 'Downloading Newsgroups from '+FHostData.HostName;
FCanContinue := True;
end;
procedure TformListing.SetStatusCaption(Value: string);
begin
lablStatus.Caption := Value;
lablStatus.Update;
end;
procedure TformListing.NNTPNewsgroupList(const sNewsgroup: string;
const lLow, lHigh: Integer; const sType: string; var CanContinue: Boolean);
begin
Inc(FDownloadCount);
SetStatusCaption(Format('Downloading newsgroups: %d received...', [FDownloadCount]));
with dataMain, tablNewsgroups do begin
if not FindKey([FHostData.HostID, sNewsgroup]) then begin
Append;
tablNewsgroupsNewsgroup_Name.Value := sNewsgroup;
tablNewsgroupsNewsgroup_Desc.Value := sNewsgroup;
tablNewsgroupsHost_ID.Value := FHostData.HostID;
tablNewsgroupsSubscribed.Value := False;
tablNewsgroupsMsg_High.Value := lHigh;
Post;
end;
end;
Application.ProcessMessages;
CanContinue := FCanContinue;
end;
procedure TformListing.FormActivate(Sender: TObject);
begin
Refresh;
dataMain.tablNewsgroups.IndexName := 'IX_HostNewsgroup';
try
Animate1.Active := True;
with NNTP do begin
Connect;
try
GetNewsgroupList;
finally
Disconnect;
SetStatusCaption('Updating display, please wait...');
end;
end;
finally
dataMain.tablNewsgroups.IndexName := '';
end;
end;
procedure TformListing.butnCancelClick(Sender: TObject);
begin
FCanContinue := False;
end;
procedure TformListing.NNTPStatus(Sender: TComponent; const sOut: String);
begin
SetStatusCaption(Trim(sOut));
end;
end.
|
(*
* Copyright (c) 2011, Ciobanu Alexandru
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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 Tests.Conformance.Bags;
interface
uses SysUtils,
Tests.Conformance.Base,
TestFramework,
Generics.Collections,
Collections.Base,
Collections.Bags;
type
TConformance_TBag = class(TConformance_IBag)
protected
procedure SetUp_IBag(out AEmpty, AOne, AFull: IBag<NativeInt>; out AElements: TElements; out AOrdering: TOrdering); override;
end;
TConformance_TSortedBag = class(TConformance_IBag)
protected
function GetSortOrder: Boolean; virtual; abstract;
procedure SetUp_IBag(out AEmpty, AOne, AFull: IBag<NativeInt>; out AElements: TElements; out AOrdering: TOrdering); override;
end;
TConformance_TSortedBag_Asc = class(TConformance_TSortedBag)
protected
function GetSortOrder: Boolean; override;
end;
TConformance_TSortedBag_Desc = class(TConformance_TSortedBag)
protected
function GetSortOrder: Boolean; override;
end;
implementation
{ TConformance_TBag }
procedure TConformance_TBag.SetUp_IBag(out AEmpty, AOne, AFull: IBag<NativeInt>;
out AElements: TElements; out AOrdering: TOrdering);
var
LItem: NativeInt;
LEmpty, LOne, LFull: TBag<NativeInt>;
begin
AElements := GenerateRepeatableRandomElements();
AOrdering := oNone;
LEmpty := TBag<NativeInt>.Create(); LEmpty.RemoveNotification := RemoveNotification;
LOne := TBag<NativeInt>.Create(); LOne.RemoveNotification := RemoveNotification;
LOne.Add(AElements[0]);
LFull := TBag<NativeInt>.Create(); LFull.RemoveNotification := RemoveNotification;
for LItem in AElements do
LFull.Add(LItem);
AEmpty := LEmpty;
AOne := LOne;
AFull := LFull;
end;
{ TConformance_TSortedBag }
procedure TConformance_TSortedBag.SetUp_IBag(out AEmpty, AOne,
AFull: IBag<NativeInt>; out AElements: TElements; out AOrdering: TOrdering);
var
LItem: NativeInt;
LEmpty, LOne, LFull: TSortedBag<NativeInt>;
begin
AElements := GenerateRepeatableRandomElements();
if GetSortOrder then
AOrdering := oAscending
else
AOrdering := oDescending;
LEmpty := TSortedBag<NativeInt>.Create(TRules<NativeInt>.Default, GetSortOrder); LEmpty.RemoveNotification := RemoveNotification;
LOne := TSortedBag<NativeInt>.Create(TRules<NativeInt>.Default, GetSortOrder); LOne.RemoveNotification := RemoveNotification;
LOne.Add(AElements[0]);
LFull := TSortedBag<NativeInt>.Create(TRules<NativeInt>.Default, GetSortOrder); LFull.RemoveNotification := RemoveNotification;
for LItem in AElements do
LFull.Add(LItem);
AEmpty := LEmpty;
AOne := LOne;
AFull := LFull;
end;
{ TConformance_TSortedBag_Asc }
function TConformance_TSortedBag_Asc.GetSortOrder: Boolean;
begin
Result := True;
end;
{ TConformance_TSortedBag_Desc }
function TConformance_TSortedBag_Desc.GetSortOrder: Boolean;
begin
Result := False;
end;
initialization
RegisterTests('Conformance.Simple.Bags', [
TConformance_TBag.Suite,
TConformance_TSortedBag_Asc.Suite,
TConformance_TSortedBag_Desc.Suite
]);
end.
|
unit UFormBackupPriority;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ImgList, StdCtrls, ToolWin, UMainForm, UMyUtil;
type
TfrmBackupPriority = class(TForm)
LvPc: TListView;
ToolBar1: TToolBar;
ilSelectHardCode: TImageList;
tbtnAlway: TToolButton;
tbtnLow: TToolButton;
tbtnNerver: TToolButton;
tbtnHigh: TToolButton;
tbtnNormal: TToolButton;
ilDiable: TImageList;
ToolButton1: TToolButton;
ilNw16: TImageList;
procedure LvPcChange(Sender: TObject; Item: TListItem; Change: TItemChange);
procedure LvPcDeletion(Sender: TObject; Item: TListItem);
procedure tbtnAlwayClick(Sender: TObject);
procedure tbtnNerverClick(Sender: TObject);
procedure tbtnHighClick(Sender: TObject);
procedure tbtnNormalClick(Sender: TObject);
procedure tbtnLowClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure LvPcCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
private
procedure SetPcPriority( Priority : string );
public
function getPriorityIcon( Priority : string ): Integer;
end;
const
LvPc_Avalible = 0;
LvPc_Priority = 1;
var
frmBackupPriority: TfrmBackupPriority;
implementation
uses UBackupInfoFace, UNetworkControl, UMyNetPcInfo, UFormUtil;
{$R *.dfm}
procedure TfrmBackupPriority.FormCreate(Sender: TObject);
begin
LvPc.OnColumnClick := ListviewUtil.ColumnClick;
end;
function TfrmBackupPriority.getPriorityIcon(Priority: string): Integer;
begin
if Priority = BackupPriority_Alway then
Result := BackupPriorityIcon_Alway
else
if Priority = BackupPriority_High then
Result := BackupPriorityIcon_High
else
if Priority = BackupPriority_Normal then
Result := BackupPriorityIcon_Normal
else
if Priority = BackupPriority_Low then
Result := BackupPriorityIcon_Low
else
if Priority = BackupPriority_Never then
Result := BackupPriorityIcon_Never
else
Result := -1;
end;
procedure TfrmBackupPriority.LvPcChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
var
IsSelect : Boolean;
begin
IsSelect := LvPc.Selected <> nil;
tbtnAlway.Enabled := IsSelect;
tbtnNerver.Enabled := IsSelect;
tbtnHigh.Enabled := IsSelect;
tbtnNormal.Enabled := IsSelect;
tbtnLow.Enabled := IsSelect;
end;
procedure TfrmBackupPriority.LvPcCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
var
LvTag : Integer;
ColumnNum, SortNum, SortType : Integer;
ItemStr1, ItemStr2 : string;
SortStr1, SortStr2 : string;
CompareSize : Int64;
begin
LvTag := ( Sender as TListView ).Tag;
SortType := LvTag div 1000;
LvTag := LvTag mod 1000;
SortNum := LvTag div 100;
LvTag := LvTag mod 100;
ColumnNum := LvTag;
// 找出 要排序的列
if ColumnNum = 0 then
begin
ItemStr1 := Item1.Caption;
ItemStr2 := Item2.Caption;
end
else
begin
ItemStr1 := Item1.SubItems[ ColumnNum - 1 ];
ItemStr2 := Item2.SubItems[ ColumnNum - 1 ];
end;
// 正序/倒序 排序
if SortNum = 1 then
begin
SortStr1 := ItemStr1;
SortStr2 := ItemStr2;
end
else
begin
SortStr1 := ItemStr2;
SortStr2 := ItemStr1;
end;
// 排序 方式
if ColumnNum = 0 then // Pc 名 排序
Compare := CompareText( SortStr1, SortStr2 )
else
if ColumnNum = LvPc_Avalible + 1 then // 可用空间 排序
begin
CompareSize := MySize.getFileSize( SortStr1 ) - MySize.getFileSize( SortStr2 );
if CompareSize > 0 then
Compare := 1
else
if CompareSize = 0 then
Compare := 0
else
Compare := -1;
end
else
if ColumnNum = LvPc_Priority + 1 then // 权重 排序
Compare := BackupPriorityUtil.getPriorityInt( SortStr1 ) - BackupPriorityUtil.getPriorityInt( SortStr2 )
else
Compare := CompareText( SortStr1, SortStr2 ); // Others
end;
procedure TfrmBackupPriority.LvPcDeletion(Sender: TObject; Item: TListItem);
var
Data : TObject;
begin
Data := Item.Data;
Data.Free;
end;
procedure TfrmBackupPriority.SetPcPriority(Priority: string);
var
i : Integer;
ItemData : TLvBackupPriorityData;
PcID : string;
begin
for i := 0 to LvPc.Items.Count - 1 do
if LvPc.Items[i].Selected then
begin
LvPc.Items[i].SubItems[ LvPc_Priority ] := Priority;
LvPc.Items[i].SubItemImages[ LvPc_Priority ] := getPriorityIcon( Priority );
ItemData := LvPc.Items[i].Data;
PcID := ItemData.PcID;
MyNetworkControl.SetPcBackupPriority( PcID, Priority );
end;
end;
procedure TfrmBackupPriority.tbtnAlwayClick(Sender: TObject);
begin
SetPcPriority( BackupPriority_Alway );
end;
procedure TfrmBackupPriority.tbtnHighClick(Sender: TObject);
begin
SetPcPriority( BackupPriority_High );
end;
procedure TfrmBackupPriority.tbtnLowClick(Sender: TObject);
begin
SetPcPriority( BackupPriority_Low );
end;
procedure TfrmBackupPriority.tbtnNerverClick(Sender: TObject);
begin
SetPcPriority( BackupPriority_Never );
end;
procedure TfrmBackupPriority.tbtnNormalClick(Sender: TObject);
begin
SetPcPriority( BackupPriority_Normal );
end;
end.
|
object AddSessionForm: TAddSessionForm
Left = 237
Top = 194
BorderStyle = bsDialog
Caption = 'Add a script'
ClientHeight = 146
ClientWidth = 387
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
PixelsPerInch = 96
TextHeight = 13
object Label1: TLabel
Left = 16
Top = 16
Width = 129
Height = 13
Caption = 'What would you like to do?'
end
object FileNameLabel: TLabel
Left = 48
Top = 92
Width = 31
Height = 13
Caption = 'Name:'
Enabled = False
end
object BrowseButton: TSpeedButton
Left = 240
Top = 88
Width = 23
Height = 22
Enabled = False
Glyph.Data = {
36020000424D3602000000000000360000002800000010000000100000000100
10000000000000020000000000000000000000000000000000001F7C1F7C1F7C
1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C
1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C000000000000
000000000000000000000000000000001F7C1F7C1F7C1F7C1F7C000000000042
0042004200420042004200420042004200001F7C1F7C1F7C1F7C0000E07F0000
00420042004200420042004200420042004200001F7C1F7C1F7C0000FF7FE07F
000000420042004200420042004200420042004200001F7C1F7C0000E07FFF7F
E07F000000420042004200420042004200420042004200001F7C0000FF7FE07F
FF7FE07F000000000000000000000000000000000000000000000000E07FFF7F
E07FFF7FE07FFF7FE07FFF7FE07F00001F7C1F7C1F7C1F7C1F7C0000FF7FE07F
FF7FE07FFF7FE07FFF7FE07FFF7F00001F7C1F7C1F7C1F7C1F7C0000E07FFF7F
E07F00000000000000000000000000001F7C1F7C1F7C1F7C1F7C1F7C00000000
00001F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C0000000000001F7C1F7C1F7C1F7C
1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C000000001F7C1F7C1F7C1F7C
1F7C1F7C1F7C1F7C1F7C00001F7C1F7C1F7C00001F7C00001F7C1F7C1F7C1F7C
1F7C1F7C1F7C1F7C1F7C1F7C0000000000001F7C1F7C1F7C1F7C1F7C1F7C1F7C
1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C1F7C}
OnClick = BrowseButtonClick
end
object DescrLabel: TLabel
Left = 48
Top = 116
Width = 56
Height = 13
Caption = 'Description:'
Enabled = False
end
object NewRadio: TRadioButton
Left = 32
Top = 40
Width = 169
Height = 17
Caption = 'Create a new login-session'
Checked = True
TabOrder = 0
TabStop = True
OnClick = NewRadioClick
end
object OpenRadio: TRadioButton
Left = 32
Top = 64
Width = 169
Height = 17
Caption = 'Add an existing script'
TabOrder = 1
OnClick = OpenRadioClick
end
object OKButton: TBitBtn
Left = 304
Top = 80
Width = 75
Height = 25
TabOrder = 4
Kind = bkOK
end
object CancelButton: TBitBtn
Left = 304
Top = 112
Width = 75
Height = 25
TabOrder = 5
Kind = bkCancel
end
object FileNameEdit: TEdit
Left = 112
Top = 88
Width = 121
Height = 21
Color = clBtnFace
Enabled = False
TabOrder = 2
OnChange = EditChange
end
object DescrEdit: TEdit
Left = 112
Top = 112
Width = 121
Height = 21
Color = clBtnFace
Enabled = False
TabOrder = 3
OnChange = EditChange
end
object OpenDialog: TOpenDialog
DefaultExt = '.msc'
Filter = 'Moops scripts (*.msc)|*.msc|All files (*.*)|*.*'#13#10'*.*'
Options = [ofHideReadOnly, ofPathMustExist, ofFileMustExist, ofEnableSizing]
Title = 'Select script to add'
Left = 264
Top = 88
end
end
|
unit SeisExemplePoster;
interface
uses PersistentObjects, DBGate, BaseObjects, DB, SeisExemple,SeisMaterial,Material;
type
TExempleTypeDataPoster = class(TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TExempleLocationDataPoster = class(TImplementedDataPoster)
FAllMaterialLocations:TMaterialLocations;
public
property AllMaterialLocations:TMaterialLocations read FAllMaterialLocations write FAllMaterialLocations;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TElementTypeDataPoster = class(TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TExempleSeismicMaterialDataPoster = class(TImplementedDataPoster)
private
FAllSeismicMaterials: TSeismicMaterials;
FAllExempleTypes: TExempleTypes;
FAllExempleLocations: TExempleLocations;
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
property AllSeismicMaterials: TSeismicMaterials read FAllSeismicMaterials write FAllSeismicMaterials;
property AllExempleTypes: TExempleTypes read FAllExempleTypes write FAllExempleTypes;
property AllExempleLocations: TExempleLocations read FAllExempleLocations write FAllExempleLocations;
constructor Create; override;
end;
TElementExempleDataPoster = class(TImplementedDataPoster)
private
FAllExempleSeismicMaterials: TExempleSeismicMaterials;
FAllElementTypes: TElementTypes;
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
property AllExempleSeismicMaterials: TExempleSeismicMaterials read FAllExempleSeismicMaterials write FAllExempleSeismicMaterials;
property AllElementTypes: TElementTypes read FAllElementTypes write FAllElementTypes;
constructor Create; override;
end;
implementation
uses Facade, SysUtils;
{ TExempleTypeDataPoster }
constructor TExempleTypeDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_exemple_TYPE';
DataDeletionString := 'TBL_exemple_TYPE';
DataPostString := 'TBL_exemple_TYPE';
KeyFieldNames := 'EXEMPLE_TYPE_ID';
FieldNames := 'EXEMPLE_TYPE_ID, VCH_EXEMPLE_TYPE_NAME';
AccessoryFieldNames := 'EXEMPLE_TYPE_ID, VCH_EXEMPLE_TYPE_NAME';
AutoFillDates := false;
Sort := 'VCH_EXEMPLE_TYPE_NAME';
end;
function TExempleTypeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result :=inherited DeleteFromDB(AObject, ACollection);
end;
function TExempleTypeDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TExempleType;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TExempleType;
o.ID := ds.FieldByName('EXEMPLE_TYPE_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_EXEMPLE_TYPE_NAME').AsString);
ds.Next;
end;
ds.First;
end;
end;
function TExempleTypeDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
w: TExempleType;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
w := AObject as TExempleType;
ds.FieldByName('EXEMPLE_TYPE_ID').AsInteger := w.ID;
ds.FieldByName('VCH_EXEMPLE_TYPE_NAME').AsString := w.Name;
ds.Post;
if w.ID = 0 then
Result := ds.FieldByName('EXEMPLE_TYPE_ID').AsInteger;
end;
{ TExempleLocationDataPoster }
constructor TExempleLocationDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_exemple_Location';
DataDeletionString := 'TBL_exemple_Location';
DataPostString := 'TBL_exemple_Location';
KeyFieldNames := 'EXEMPLE_Location_ID';
FieldNames := 'EXEMPLE_Location_ID, VCH_EXEMPLE_Location_NAME,Location_ID';
AccessoryFieldNames := 'EXEMPLE_Location_ID, VCH_EXEMPLE_Location_NAME,Location_ID';
AutoFillDates := false;
Sort := 'VCH_EXEMPLE_Location_NAME';
end;
function TExempleLocationDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result :=inherited DeleteFromDB(AObject, ACollection);
end;
function TExempleLocationDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TExempleLocation;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TExempleLocation;
o.ID := ds.FieldByName('EXEMPLE_Location_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_EXEMPLE_Location_NAME').AsString);
//if not Assigned(AllMaterialLocations) then FAllMaterialLocations:=AllMaterialLocations.Create;
if Assigned(AllMaterialLocations) then
o.MaterialLocation := AllMaterialLocations.ItemsByID[ds.FieldByName('Location_ID').AsInteger] as TMaterialLocation;
ds.Next;
end;
ds.First;
end;
end;
function TExempleLocationDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
w: TExempleLocation;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
w := AObject as TExempleLocation;
ds.FieldByName('EXEMPLE_Location_ID').AsInteger := w.ID;
ds.FieldByName('VCH_EXEMPLE_Location_NAME').AsString := w.Name;
ds.FieldByName('Location_ID').AsInteger := w.MaterialLocation.ID;
ds.Post;
if w.ID = 0 then
Result := ds.FieldByName('EXEMPLE_Location_ID').AsInteger;
end;
{ TElementTypeDataPoster }
constructor TElementTypeDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_Element_TYPE';
DataDeletionString := 'TBL_Element_TYPE';
DataPostString := 'TBL_Element_TYPE';
KeyFieldNames := 'Element_TYPE_ID';
FieldNames := 'Element_TYPE_ID, VCH_Element_TYPE_NAME';
AccessoryFieldNames := 'Element_TYPE_ID, VCH_Element_TYPE_NAME';
AutoFillDates := false;
Sort := 'VCH_Element_TYPE_NAME';
end;
function TElementTypeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result :=inherited DeleteFromDB(AObject, ACollection);
end;
function TElementTypeDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TElementType;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TElementType;
o.ID := ds.FieldByName('Element_TYPE_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_Element_TYPE_NAME').AsString);
ds.Next;
end;
ds.First;
end;
end;
function TElementTypeDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
w: TElementType;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
w := AObject as TElementType;
ds.FieldByName('Element_TYPE_ID').AsInteger := w.ID;
ds.FieldByName('VCH_Element_TYPE_NAME').AsString := w.Name;
ds.Post;
if w.ID = 0 then
Result := ds.FieldByName('Element_TYPE_ID').AsInteger;
end;
{ TExempleSeismicMaterialDataPoster }
constructor TExempleSeismicMaterialDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_Exemple_SEIS_MATERIAL';
DataDeletionString := 'TBL_Exemple_SEIS_MATERIAL';
DataPostString := 'TBL_Exemple_SEIS_MATERIAL';
KeyFieldNames := 'EXEMPLE_SEIS_MATERIAL_ID';
FieldNames := 'EXEMPLE_SEIS_MATERIAL_ID,SEIS_MATERIAL_ID,EXEMPLE_TYPE_ID,EXEMPLE_LOCATION_ID,NUM_EXEMPLE_SUM,VCH_EXEMPLE_COMMENT';
AccessoryFieldNames := 'EXEMPLE_SEIS_MATERIAL_ID,SEIS_MATERIAL_ID,EXEMPLE_TYPE_ID,EXEMPLE_LOCATION_ID,NUM_EXEMPLE_SUM,VCH_EXEMPLE_COMMENT';
AutoFillDates := false;
Sort := 'EXEMPLE_SEIS_MATERIAL_ID';
end;
function TExempleSeismicMaterialDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result :=inherited DeleteFromDB(AObject, ACollection);
end;
function TExempleSeismicMaterialDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TExempleSeismicMaterial;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TExempleSeismicMaterial;
o.ID := ds.FieldByName('EXEMPLE_SEIS_MATERIAL_ID').AsInteger;
o.ExempleSum := ds.FieldByName('NUM_EXEMPLE_SUM').AsInteger;
o.ExempleComment := ds.FieldByName('VCH_EXEMPLE_COMMENT').AsString;
if Assigned(AllExempleTypes) then //FAllExempleTypes:=AllExempleTypes.Create;
o.ExempleType := AllExempleTypes.ItemsByID[ds.FieldByName('EXEMPLE_TYPE_ID').AsInteger] as TExempleType;
if Assigned(AllExempleLocations) then //FAllExempleLocations:=AllExempleLocations.Create;
o.ExempleLocation := AllExempleLocations.ItemsByID[ds.FieldByName('Exemple_Location_ID').AsInteger] as TExempleLocation;
if Assigned(AllSeismicMaterials) then //FAllSeismicMaterials:=AllSeismicMaterials.Create;
o.SeismicMaterial := AllSeismicMaterials.ItemsByID[ds.FieldByName('SEIS_Material_ID').AsInteger] as TSeismicMaterial;
ds.Next;
end;
ds.First;
end;
end;
function TExempleSeismicMaterialDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
w: TExempleSeismicMaterial;
i:Integer;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
w := AObject as TExempleSeismicMaterial;
ds.FieldByName('EXEMPLE_SEIS_MATERIAL_ID').AsInteger := w.ID;
ds.FieldByName('NUM_Exemple_SUM').AsInteger:= w.ExempleSum;
ds.FieldByName('VCH_Exemple_COMMENT').AsString:= w.ExempleComment;
ds.FieldByName('EXEMPLE_TYPE_ID').AsInteger:= w.ExempleType.Id;
ds.FieldByName('Exemple_Location_ID').AsInteger:= w.ExempleLocation.Id;
ds.FieldByName('SEIS_Material_ID').AsInteger:= w.SeismicMaterial.Id;
ds.Post;
if w.ID <= 0 then
Result := ds.FieldByName('EXEMPLE_SEIS_MATERIAL_ID').AsInteger;
i:=Result;
end;
{ TElementExempleDataPoster }
constructor TElementExempleDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_Element_Exemple';
DataDeletionString := 'TBL_Element_Exemple';
DataPostString := 'TBL_Element_Exemple';
KeyFieldNames := 'Element_Exemple_ID';
FieldNames := 'Element_Exemple_ID,EXEMPLE_SEIS_MATERIAL_ID,ELEMENT_TYPE_ID,NUM_ELEMENT_NUMBER,VCH_ELEMENT_COMMENT,VCH_ELEMENT_EXEMPLE_NAME,VCH_ELEMENT_LOCATION';
AccessoryFieldNames := 'Element_Exemple_ID,EXEMPLE_SEIS_MATERIAL_ID,ELEMENT_TYPE_ID,NUM_ELEMENT_NUMBER,VCH_ELEMENT_COMMENT,VCH_ELEMENT_EXEMPLE_NAME,VCH_ELEMENT_LOCATION';
AutoFillDates := false;
Sort := 'EXEMPLE_SEIS_MATERIAL_ID';
end;
function TElementExempleDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result :=inherited DeleteFromDB(AObject, ACollection);
end;
function TElementExempleDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TElementExemple;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TElementExemple;
o.ID := ds.FieldByName('ELEMENT_Exemple_ID').AsInteger;
o.Name := ds.FieldByName('VCH_ELEMENT_EXEMPLE_NAME').AsString;
o.ElementNumber := ds.FieldByName('NUM_ELEMENT_NUMBER').AsInteger;
o.ElementComment := ds.FieldByName('VCH_ELEMENT_COMMENT').AsString;
o.ElementLocation := ds.FieldByName('VCH_ELEMENT_LOCATION').AsString;
if Assigned(AllElementTypes) then //FAllElementTypes:=AllElementTypes.Create;
o.ElementType := AllElementTypes.ItemsByID[ds.FieldByName('ELEMENT_TYPE_ID').AsInteger] as TElementType;
if Assigned(AllExempleSeismicMaterials) then //FAllExempleSeismicMaterials:=AllExempleSeismicMaterials.Create;
o.ExempleSeismicMaterial := AllExempleSeismicMaterials.ItemsByID[ds.FieldByName('Exemple_SEIS_MATERIAL_ID').AsInteger] as TExempleSeismicMaterial;
ds.Next;
end;
ds.First;
end;
end;
function TElementExempleDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
w: TElementExemple;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
w := AObject as TElementExemple;
ds.FieldByName('Element_Exemple_ID').AsInteger := w.ID;
ds.FieldByName('VCH_ELEMENT_EXEMPLE_NAME').AsString:= w.Name;
ds.FieldByName('NUM_ELEMENT_NUMBER').AsInteger:= w.ElementNumber;
ds.FieldByName('VCH_ELEMENT_COMMENT').AsString:= w.ElementComment;
ds.FieldByName('VCH_ELEMENT_LOCATION').AsString:= w.ElementLocation;
ds.FieldByName('ELEMENT_TYPE_ID').AsInteger:= w.ElementType.Id;
ds.FieldByName('EXEMPLE_SEIS_Material_ID').AsInteger:= w.ExempleSeismicMaterial.Id;
ds.Post;
if w.ID <= 0 then
Result := ds.FieldByName('Element_Exemple_ID').AsInteger;
end;
end.
|
{*******************************************************************************
作者: dmzn 2009-2-3
描述: 可以移动的控件集合
*******************************************************************************}
unit UMovedItems;
interface
uses
Windows, Classes, Controls, Graphics, SysUtils, ExtCtrls, Jpeg, GIFImage,
UMovedControl, UMgrLang;
type
TMovedItemClass = class of TZnMovedControl;
TTextMovedItem = class(TZnMovedControl)
private
FText: string;
{*文本内容*}
FLines: TStrings;
{*分行内容*}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{*创建释放*}
function SplitText: Boolean;
{拆分文本*}
procedure DoPaint(const nCanvas: TCanvas; const nRect: TRect); override;
property Lines: TStrings read FLines;
property Text: string read FText write FText;
end;
TPictureDataType = (ptText, ptPic);
//文本,图片
PPictureData = ^TPictureData;
TPictureData = record
FFile: string;
FType: TPictureDataType;
//数据内容
FSingleLine: Boolean;
//单行显示
FModeEnter: Byte;
FModeExit: Byte;
//进出场模式
FSpeedEnter: Byte;
FSpeedExit: Byte;
//进出场速度
FKeedTime: Byte;
FModeSerial: Byte;
//停留时间,跟随前屏
end;
TPictureMovedItem = class(TZnMovedControl)
private
FText: string;
{*文本内容*}
FImage: TPicture;
{*图片内容*}
FDataList: TList;
{*数据列表*}
FNowData: PPictureData;
{*活动数据*}
FStretch: Boolean;
{*拉伸显示*}
protected
procedure SetImage(const nValue: TPicture);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{*创建释放*}
procedure DoPaint(const nCanvas: TCanvas; const nRect: TRect); override;
function AddData(const nFile: string; nType: TPictureDataType): integer;
function FindData(const nFile: string): Integer;
procedure DeleteData(const nIdx: Integer);
{*数据处理*}
property DataList: TList read FDataList;
property NowData: PPictureData read FNowData write FNowData;
property Stretch: Boolean read FStretch write FStretch;
property Text: string read FText write FText;
property Image: TPicture read FImage write SetImage;
end;
TAnimateMovedItem = class(TZnMovedControl)
private
FText: string;
{*文本内容*}
FImage: TPicture;
{*图片内容*}
FImageFile: string;
{*图片文件*}
FPicNum: Word;
{*动画帧数*}
FSpeed: Word;
{*每秒帧数*}
FImageWH: TRect;
{*动画大小*}
FStretch: Boolean;
{*拉伸显示*}
FReverse: Boolean;
{*翻转扫描*}
protected
procedure SetFile(const nFile: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{*创建释放*}
procedure DoPaint(const nCanvas: TCanvas; const nRect: TRect); override;
{*绘制内容*}
property PicNum: Word read FPicNum;
property ImageWH: TRect read FImageWH;
property Text: string read FText write FText;
property Speed: Word read FSpeed write FSpeed;
property Reverse: Boolean read FReverse write FReverse;
property Stretch: Boolean read FStretch write FStretch;
property ImageFile: string read FImageFile write SetFile;
end;
TTimeItemOption = (toDate, toWeek, toTime);
TTimeItemOptons = set of TTimeItemOption;
TTimeTextStyle = (tsSingle, tsMulti);
TTimeMovedItem = class(TZnMovedControl)
private
FTimer: TTimer;
{*计时器*}
FOptions: TTimeItemOptons;
{*可选内容*}
FFixText: string;
FFixColor: TColor;
{*固定内容*}
FDateText: string;
FDateColor: TColor;
{*日期相关*}
FWeekText: string;
FWeekColor: TColor;
{*星期相关*}
FTimeText: string;
FTimeColor: TColor;
{*时间相关*}
FTextStyle: TTimeTextStyle;
{*显示风格*}
FModeChar: Byte;
FModeLine: Byte;
FModeDate: Byte;
FModeWeek: Byte;
FModeTime: Byte;
{*扩展属性*}
protected
procedure DoTimer(Sender: TObject);
procedure SetModeChar(const nValue: Byte);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{*创建释放*}
procedure DoPaint(const nCanvas: TCanvas; const nRect: TRect); override;
procedure SwitchTimer(const nEnable: Boolean);
{*计时器开关*}
property Options: TTimeItemOptons read FOptions write FOptions;
property TextStyle: TTimeTextStyle read FTextStyle write FTextStyle;
property FixText: string read FFixText write FFixText;
property DateText: string read FDateText write FDateText;
property WeekText: string read FWeekText write FWeekText;
property TimeText: string read FTimeText write FTimeText;
property FixColor: TColor read FFixColor write FFixColor;
property DateColor: TColor read FDateColor write FDateColor;
property WeekColor: TColor read FWeekColor write FWeekColor;
property TimeColor: TColor read FTimeColor write FTimeColor;
property ModeChar: Byte read FModeChar write SetModeChar;
property ModeLine: Byte read FModeLine write FModeLine;
property ModeDate: Byte read FModeDate write FModeDate;
property ModeWeek: Byte read FModeWeek write FModeWeek;
property ModeTime: Byte read FModeTime write FModeTime;
{*扩展属性*}
{*属性相关*}
end;
TClockMovedItem = class(TZnMovedControl)
private
FText: string;
{*文本内容*}
FImage: TPicture;
{*表盘数据*}
FAutoDot: Boolean;
FDotPoint: TPoint;
{*圆心坐标*}
FColorHour: TColor;
FColorMin: TColor;
FColorSec: TColor;
{*表针颜色*}
protected
procedure Resize;override;
procedure SetAutoDot(const nValue: Boolean);
procedure SetImage(const nValue: TPicture);
procedure PaintZhen(const nCanvas: TCanvas; const nR: integer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{*创建释放*}
function DefaultDotPoint: TPoint;
{*默认原点*}
procedure DoPaint(const nCanvas: TCanvas; const nRect: TRect); override;
{*绘制图形*}
property Image: TPicture read FImage;
property Text: string read FText write FText;
property AutoDot: Boolean read FAutoDot write SetAutoDot;
property DotPoint: TPoint read FDotPoint write FDotPoint;
property ColorHour: TColor read FColorHour write FColorHour;
property ColorMin: TColor read FColorMin write FColorMin;
property ColorSec: TColor read FColorSec write FColorSec;
end;
implementation
constructor TTextMovedItem.Create(AOwner: TComponent);
begin
inherited;
Width := 48;
Height := 23;
FText := '文本内容';
FLines := TStringList.Create;
end;
destructor TTextMovedItem.Destroy;
begin
FLines.Free;
inherited;
end;
procedure TTextMovedItem.DoPaint(const nCanvas: TCanvas; const nRect: TRect);
var nMid: integer;
begin
inherited;
nCanvas.Font.Assign(Font);
nMid := Round((Height - nCanvas.TextHeight(FText)) / 2);
SetBKMode(nCanvas.Handle, TransParent);
nCanvas.TextOut(2, nMid, FText);
end;
//Desc: 拆分字符串,保证每行可以拆分成整屏.
function TTextMovedItem.SplitText: Boolean;
var nStr,nText: WideString;
nPos,nLen,nSLen,nW,nSW: integer;
begin
Canvas.Font.Assign(Font);
nSW := Canvas.TextWidth('汉');
//单字宽度
FLines.Clear;
nText := FText;
nSLen := Length(nText);
nPos := 1;
while nPos <= nSLen do
begin
nStr := Copy(nText, nPos, 100);
nLen := Length(nStr);
nW := Canvas.TextWidth(nStr);
if nLen > 99 then
while (nW mod Width <> 0) And ((Width - nW mod Width) > nSW) do
begin
System.Delete(nStr, nLen, 1);
nLen := Length(nStr);
nW := Canvas.TextWidth(nStr);
end;
{-------------------------------- 分屏算法 ---------------------------------
1.文本不够一屏时,直接跳过.
2.文本正好够整屏时,直接跳过.
3.文本距整屏差一个字时,直接跳过.
---------------------------------------------------------------------------}
nPos := nPos + nLen;
//下一文本段起始位置
FLines.Add(nStr);
end;
Result := FLines.Count > 0;
end;
//------------------------------------------------------------------------------
constructor TPictureMovedItem.Create(AOwner: TComponent);
begin
inherited;
Width := 48;
Height := 23;
FStretch := True;
FText := '图文内容';
FImage := TPicture.Create;
FNowData := nil;
FDataList := TList.Create;
end;
destructor TPictureMovedItem.Destroy;
var nIdx: integer;
begin
for nIdx:=FDataList.Count - 1 downto 0 do
begin
Dispose(PPictureData(FDataList[nIdx]));
FDataList.Delete(nIdx);
end;
FDataList.Free;
FImage.Free;
inherited;
end;
function TPictureMovedItem.AddData(const nFile: string;
nType: TPictureDataType): integer;
var nStr: string;
nGif: TGIFImage;
nP: PPictureData;
begin
New(nP);
Result := FDataList.Add(nP);
nP.FFile := nFile;
nP.FType := nType;
nP.FModeEnter := ModeEnter;
nP.FModeExit := ModeExit;
nP.FSpeedEnter := SpeedEnter;
nP.FSpeedExit := SpeedExit;
nP.FKeedTime := KeedTime;
nP.FModeSerial := ModeSerial;
nGif := nil;
if nType = ptPic then
try
nStr := ExtractFileExt(nFile);
if CompareText(nStr, '.gif') <> 0 then Exit;
nGif := TGIFImage.Create;
nGif.LoadFromFile(nFile);
nP.FModeEnter := 0;
nP.FModeExit := 0;
nP.FSpeedEnter := 5;
nP.FSpeedExit := 0;
nP.FKeedTime := Round(nGif.AnimationSpeed / 1000);
nP.FModeSerial := 1;
finally
nGif.Free;
end;
end;
procedure TPictureMovedItem.DeleteData(const nIdx: Integer);
begin
if (nIdx > -1) and (nIdx < FDataList.Count) then
begin
Dispose(PPictureData(FDataList[nIdx]));
FDataList.Delete(nIdx);
end;
end;
function TPictureMovedItem.FindData(const nFile: string): Integer;
var nIdx: integer;
begin
Result := -1;
for nIdx:=0 to FDataList.Count - 1 do
if CompareText(nFile, PPictureData(FDataList[nIdx]).FFile) = 0 then
begin
Result := nIdx; Break;
end;
end;
procedure TPictureMovedItem.SetImage(const nValue: TPicture);
begin
FImage.Assign(nValue);
end;
procedure TPictureMovedItem.DoPaint(const nCanvas: TCanvas; const nRect: TRect);
var nMid: integer;
begin
inherited;
if FImage.Width < 1 then
begin
SetBKMode(nCanvas.Handle, TransParent);
nMid := Round((Height - nCanvas.TextHeight(FText)) / 2);
nCanvas.Font.Assign(Font);
nCanvas.TextOut(2, nMid, FText);
end else
if FStretch then
begin
nCanvas.StretchDraw(ClientRect, FImage.Graphic);
end else
begin
nCanvas.Draw(0, 0, FImage.Graphic);
end;
end;
//------------------------------------------------------------------------------
constructor TAnimateMovedItem.Create(AOwner: TComponent);
begin
inherited;
Width := 48;
Height := 23;
FPicNum := 0;
FSpeed := 0;
FImageWH := Rect(0, 0, 0, 0);
FStretch := True;
FReverse := False;
FText := '图文动画';
FImage := TPicture.Create;
end;
destructor TAnimateMovedItem.Destroy;
begin
FImage.Free;
inherited;
end;
procedure TAnimateMovedItem.SetFile(const nFile: string);
var nGif: TGIFImage;
begin
nGif := TGIFImage.Create;
try
nGif.LoadFromFile(nFile);
FImage.Graphic := nGif.Images[0].Bitmap;
FPicNum := nGif.Images.Count;
if nGif.AnimationSpeed > 0 then
FSpeed := Round(1000 / nGif.AnimationSpeed)
else FSpeed := 0;
FImageWH := Rect(0, 0, nGif.Width, nGif.Height);
FImageFile := nFile;
finally
nGif.Free;
end;
end;
procedure TAnimateMovedItem.DoPaint(const nCanvas: TCanvas;
const nRect: TRect);
var nMid: integer;
begin
inherited;
if FImage.Width < 1 then
begin
SetBKMode(nCanvas.Handle, TransParent);
nMid := Round((Height - nCanvas.TextHeight(FText)) / 2);
nCanvas.Font.Assign(Font);
nCanvas.TextOut(2, nMid, FText);
end else
if FStretch then
begin
nCanvas.StretchDraw(ClientRect, FImage.Graphic);
end else
begin
nCanvas.Draw(0, 0, FImage.Graphic);
end;
end;
//------------------------------------------------------------------------------
constructor TTimeMovedItem.Create(AOwner: TComponent);
var nStr: string;
begin
inherited;
Width := 96;
Height := 16;
FTimer := TTimer.Create(Self);
FTimer.Enabled := False;
FTimer.OnTimer := DoTimer;
FOptions := [toTime];
FTextStyle := tsSingle;
FFixText := '';
FFixColor := clRed;
nStr := gMultiLangManager.SectionID;
gMultiLangManager.SectionID := 'Common';
try
FDateText := ML('YYYY年MM月DD日');
FDateColor := clRed;
FWeekText := ML('星期X');
FWeekColor := clRed;
FTimeText := ML('HH时mm分ss秒');
FTimeColor := clRed;
finally
gMultiLangManager.SectionID := nStr;
end;
FModeChar := 1;
FModeLine := 0;
FModeDate := 0;
FModeWeek := 0;
FModeTime := 1;
end;
destructor TTimeMovedItem.Destroy;
begin
FTimer.Free;
inherited;
end;
procedure TTimeMovedItem.SwitchTimer(const nEnable: Boolean);
begin
FTimer.Enabled := nEnable;
end;
procedure TTimeMovedItem.DoTimer(Sender: TObject);
begin
Invalidate;
end;
procedure TTimeMovedItem.SetModeChar(const nValue: Byte);
var nStr: string;
begin
if nValue <> FModeChar then
begin
FModeChar := nValue;
if nValue = 0 then //字符显示
begin
FWeekText := '星期X';
FTimeText := 'HH:mm:ss';
end else
begin
FWeekText := '星期X';
FTimeText := 'HH时mm分ss秒';
end;
end;
nStr := gMultiLangManager.SectionID;
gMultiLangManager.SectionID := 'Common';
FWeekText := ML(FWeekText);
FTimeText := ML(FTimeText);
gMultiLangManager.SectionID := nStr;
end;
function GetDateText(const nModeChar,nModeDate: Byte): string;
var nStr: string;
begin
if nModeChar = 0 then //字符模式
begin
case nModeDate of
1: Result := 'YY-MM-DD';
2: Result := 'YYYY-MM-DD';
end;
end else
begin
case nModeDate of
1: Result := 'YY年MM月DD日';
2: Result := 'YYYY年MM月DD日';
end;
end;
nStr := gMultiLangManager.SectionID;
gMultiLangManager.SectionID := 'Common';
Result := ML(Result);
gMultiLangManager.SectionID := nStr;
end;
//Desc: 将nDate按nFormat格式化
function FormatWeekDay(const nFormat: string; const nDate: TDateTime): string;
var nStr: string;
begin
case DayOfWeek(nDate) of
1: nStr := '日';
2: nStr := '一';
3: nStr := '二';
4: nStr := '三';
5: nStr := '四';
6: nStr := '五';
7: nStr := '六' else nStr := '';
end;
Result := StringReplace(nFormat, 'X', nStr, [rfReplaceAll, rfIgnoreCase]);
nStr := gMultiLangManager.SectionID;
gMultiLangManager.SectionID := 'Common';
Result := ML(Result);
gMultiLangManager.SectionID := nStr;
end;
//Desc: 绘制
procedure TTimeMovedItem.DoPaint(const nCanvas: TCanvas; const nRect: TRect);
var nStr,nTmp: string;
nL,nT,nInt: integer;
begin
inherited;
nCanvas.Font.Assign(Font);
SetBKMode(nCanvas.Handle, Transparent);
if FModeLine = 0 then
begin
if FModeDate = 0 then
nStr := ''
else nStr := FormatDateTime(GetDateText(FModeChar, FModeDate), Now);
case FModeWeek of
0: ;
1: begin
nTmp := FormatWeekDay(FWeekText, Now);
if nStr = '' then
nStr := nTmp
else nStr := nStr + ' ' + nTmp;
end;
end;
case FModeTime of
0: ;
1: begin
nTmp := FormatDateTime(FTimeText, Now);
if nStr = '' then
nStr := nTmp
else nStr := nStr + ' ' + nTmp;
end;
end;
nL := Round((Width - nCanvas.TextWidth(nStr)) / 2);
if nL < 0 then nL := 0;
nT := Round((Height - nCanvas.TextHeight(nStr)) / 2);
if nT < 0 then nT := 0;
nCanvas.TextOut(nL, nT, nStr);
Exit; //单行绘制完毕
end;
//----------------------------------------------------------------------------
nT := 0;
nInt := 0;
if FModeDate <> 0 then
begin
Inc(nT, nCanvas.TextHeight(FormatDateTime(FDateText, Now))); Inc(nInt);
end;
if FModeWeek <> 0 then
begin
Inc(nT, nCanvas.TextHeight(FormatWeekDay(FWeekText, Now))); Inc(nInt);
end;
if FModeTime <> 0 then
begin
Inc(nT, nCanvas.TextHeight(FormatDateTime(FTimeText, Now))); Inc(nInt);
end;
if nInt > 1 then
begin
nInt := Round((Height - nT) / (nInt - 1)); nT := 0;
end else
begin
nInt := 0; nT := Round((Height - nT) / 2);
end;
//每行文本间隔与起始坐标
if FModeDate <> 0 then
begin
nStr := FormatDateTime(GetDateText(FModeChar, FModeDate), Now);
nL := Round((Width - nCanvas.TextWidth(nStr)) / 2);
if nL < 0 then nL := 0;
nCanvas.TextOut(nL, nT, nStr);
Inc(nT, nInt + nCanvas.TextHeight(nStr));
end;
if FModeWeek <> 0 then
begin
nStr := FormatWeekDay(FWeekText, Now);
nL := Round((Width - nCanvas.TextWidth(nStr)) / 2);
if nL < 0 then nL := 0;
nCanvas.TextOut(nL, nT, nStr);
Inc(nT, nInt + nCanvas.TextHeight(nStr));
end;
if FModeTime <> 0 then
begin
nStr := FormatDateTime(FTimeText, Now);
nL := Round((Width - nCanvas.TextWidth(nStr)) / 2);
if nL < 0 then nL := 0;
nCanvas.TextOut(nL, nT, nStr);
end;
end;
{
//Desc: 绘制
procedure TTimeMovedItem.DoPaint(const nCanvas: TCanvas; const nRect: TRect);
var nStr: string;
nL,nT,nInt: integer;
begin
inherited;
nCanvas.Font.Assign(Font);
SetBKMode(nCanvas.Handle, Transparent);
if FTextStyle = tsSingle then
begin
nStr := FFixText;
if toDate in FOptions then
nStr := nStr + FormatDateTime(FDateText, Now);
if toWeek in FOptions then
nStr := nStr + FormatWeekDay(FWeekText, Now);
if toTime in FOptions then
nStr := nStr + FormatDateTime(FTimeText, Now);
nL := Round((Width - nCanvas.TextWidth(nStr)) / 2);
if nL < 0 then nL := 0;
nT := Round((Height - nCanvas.TextHeight(nStr)) / 2);
if nT < 0 then nT := 0;
if FFixText <> '' then
begin
nCanvas.Font.Color := FFixColor;
nCanvas.TextOut(nL, nT, FFixText);
Inc(nL, nCanvas.TextWidth(FFixText));
end;
if toDate in FOptions then
begin
nStr := FormatDateTime(FDateText, Now);
nCanvas.Font.Color := FDateColor;
nCanvas.TextOut(nL, nT, nStr);
Inc(nL, nCanvas.TextWidth(nStr));
end;
if toWeek in FOptions then
begin
nStr := FormatWeekDay(FWeekText, Now);
nCanvas.Font.Color := FWeekColor;
nCanvas.TextOut(nL, nT, nStr);
Inc(nL, nCanvas.TextWidth(nStr));
end;
if toTime in FOptions then
begin
nStr := FormatDateTime(FTimeText, Now);
nCanvas.Font.Color := FTimeColor;
nCanvas.TextOut(nL, nT, nStr);
end;
Exit; //单行绘制完毕
end;
//----------------------------------------------------------------------------
nT := 0;
nInt := 0;
if FFixText <> '' then
begin
nT := nCanvas.TextHeight(FFixText); Inc(nInt);
end;
if toDate in FOptions then
begin
Inc(nT, nCanvas.TextHeight(FormatDateTime(FDateText, Now))); Inc(nInt);
end;
if toWeek in FOptions then
begin
Inc(nT, nCanvas.TextHeight(FormatWeekDay(FWeekText, Now))); Inc(nInt);
end;
if toTime in FOptions then
begin
Inc(nT, nCanvas.TextHeight(FormatDateTime(FTimeText, Now))); Inc(nInt);
end;
if nInt > 1 then
begin
nInt := Round((Height - nT) / (nInt - 1)); nT := 0;
end else
begin
nInt := 0; nT := Round((Height - nT) / 2);
end;
//每行文本间隔与起始坐标
if FFixText <> '' then
begin
nL := Round((Width - nCanvas.TextWidth(FFixText)) / 2);
if nL < 0 then nL := 0;
nCanvas.Font.Color := FFixColor;
nCanvas.TextOut(nL, nT, FFixText);
Inc(nT, nInt + nCanvas.TextHeight(FFixText));
end;
if toDate in FOptions then
begin
nStr := FormatDateTime(FDateText, Now);
nL := Round((Width - nCanvas.TextWidth(nStr)) / 2);
if nL < 0 then nL := 0;
nCanvas.Font.Color := FDateColor;
nCanvas.TextOut(nL, nT, nStr);
Inc(nT, nInt + nCanvas.TextHeight(nStr));
end;
if toWeek in FOptions then
begin
nStr := FormatWeekDay(FWeekText, Now);
nL := Round((Width - nCanvas.TextWidth(nStr)) / 2);
if nL < 0 then nL := 0;
nCanvas.Font.Color := FWeekColor;
nCanvas.TextOut(nL, nT, nStr);
Inc(nT, nInt + nCanvas.TextHeight(nStr));
end;
if toTime in FOptions then
begin
nStr := FormatDateTime(FTimeText, Now);
nL := Round((Width - nCanvas.TextWidth(nStr)) / 2);
if nL < 0 then nL := 0;
nCanvas.Font.Color := FTimeColor;
nCanvas.TextOut(nL, nT, nStr);
end;
end;
}
//------------------------------------------------------------------------------
constructor TClockMovedItem.Create(AOwner: TComponent);
begin
inherited;
Width := 32;
Height := 32;
Font.Color := clRed;
FColorHour := clYellow;
FColorMin := clGreen;
FColorSec := clRed;
FAutoDot := True;
FImage := TPicture.Create;
end;
destructor TClockMovedItem.Destroy;
begin
FImage.Free;
inherited;
end;
procedure TClockMovedItem.SetImage(const nValue: TPicture);
begin
FImage.Assign(nValue);
end;
procedure TClockMovedItem.Resize;
begin
inherited;
if FAutoDot then FDotPoint := DefaultDotPoint;
end;
procedure TClockMovedItem.SetAutoDot(const nValue: Boolean);
begin
if FAutoDot <> nValue then
begin
FAutoDot := nValue;
if FAutoDot then FDotPoint := DefaultDotPoint;
end;
end;
function TClockMovedItem.DefaultDotPoint: TPoint;
begin
Result.X := Trunc(Width / 2);
Result.Y := Trunc(Height / 2);
end;
//Desc: 绘制表针
procedure TClockMovedItem.PaintZhen(const nCanvas: TCanvas; const nR: integer);
var nInt: integer;
begin
nCanvas.Brush.Color := clRed;
with FDotPoint do
begin
nCanvas.Ellipse(X-2, Y-2, X+2, Y+2);
//绘制原点
nCanvas.Pen.Width := 3;
nCanvas.Pen.Color := FColorMin;
nCanvas.MoveTo(X - 1, Y - 2);
nInt := Trunc(nR*5/6);
nCanvas.LineTo(X - 1, Y - nInt);
//分针
nCanvas.Pen.Color := FColorHour;
nCanvas.MoveTo(X + 1, Y);
nInt := Trunc(nR*2/3);
nCanvas.LineTo(X + nInt, Y);
//时针
nCanvas.Pen.Width := 1;
nCanvas.Pen.Color := FColorSec;
nCanvas.MoveTo(X - 1, Y);
nInt := Trunc(nR*0.6);
nCanvas.LineTo(X - nInt, Y + nInt);
//秒针
end;
end;
procedure TClockMovedItem.DoPaint(const nCanvas: TCanvas;
const nRect: TRect);
var nR: integer;
begin
inherited;
nR := FDotPoint.X;
if nR > FDotPoint.Y then nR := FDotPoint.Y;
Dec(nR, 2);
if FImage.Width < 1 then
begin
nCanvas.Pen.Color := clRed;
nCanvas.Pen.Width := 1;
with FDotPoint do
begin
nCanvas.Ellipse(X - nR, Y - nR, X + nR, Y+ nR);
//绘制圆心
nCanvas.Pen.Color := clYellow;
nCanvas.Brush.Color := clYellow;
nCanvas.Rectangle(X - nR, Y - 1, X - nR + 2, Y + 2); //9点
nCanvas.Rectangle(X + nR - 2, Y - 1, X + nR, Y + 2); //3点
nCanvas.Rectangle(X - 1, Y - nR, X + 2, Y - nR + 2);//12点
nCanvas.Rectangle(X - 1, Y + nR - 2, X + 2, Y + nR); //6点
end;
end else
begin
nCanvas.StretchDraw(ClientRect, FImage.Graphic);
//绘制表盘
end;
PaintZhen(nCanvas, nR);
//绘制圆心和指针
end;
end.
|
unit IMPPR;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, XPLabel, jpeg, ExtCtrls, XPButton, XPEdit, StdCtrls, ShlObj;
const
AlignCenter = Wm_User + 1024;
type
TWmMoving = record
Msg: Cardinal;
fwSide: Cardinal;
lpRect: PRect;
Result: Integer;
end;
type
TImportFrm = class(TForm)
fr1: TPanel;
logo: TImage;
tx1: TXPLabel;
OK: TXPButton;
Cancel: TXPButton;
tx2: TXPLabel;
tx3: TXPLabel;
tx4: TXPLabel;
tx5: TXPLabel;
edExport: TXPEdit;
listFav: TListBox;
edResult: TEdit;
ChooseBt: TXPButton;
procedure FormShow(Sender: TObject);
procedure OKClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure ChooseBtClick(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
public
TextString: String;
msgCaption: PChar;
procedure ChangeMessageBoxPosition(var Msg: TMessage);
message AlignCenter;
procedure WMMoving(var msg: TWMMoving);
message WM_MOVING;
end;
var
ImportFrm: TImportFrm;
implementation
{$R *.dfm} uses NP, OP;
function GetIEFavourites(const favpath: string): TStrings;
var
searchrec: TSearchrec;
str: TStrings;
path, dir, filename: string;
Buffer: array [0..2047] of Char;
found: Integer;
begin
str := TStringList.Create;
path := FavPath + '\*.url';
dir := ExtractFilepath(path);
found := FindFirst(path, faAnyFile, searchrec);
while found = 0 do
begin
SetString(filename, Buffer, GetPrivateProfileString('InternetShortcut',
PChar('URL'), nil, Buffer, SizeOf(Buffer), PChar(dir+searchrec.name)));
str.Add(filename);
found := FindNext(searchrec);
end;
found := FindFirst(dir + '\*.*', faAnyFile, searchrec);
while found=0 do
begin
if ((searchrec.Attr and faDirectory) > 0) and (searchrec.name[1] <> '.') then
str.AddStrings(GetIEFavourites(dir + '\' + searchrec.name));
found := FindNext(searchrec);
end;
FindClose(searchrec);
Result := str;
end;
procedure TImportFrm.FormShow(Sender: TObject);
var
pidl: PItemIDList;
FavPath: array [0..MAX_PATH] of char;
begin
SHGetSpecialFolderLocation(Handle, CSIDL_FAVORITES, pidl);
SHGetPathFromIDList(pidl, favpath);
listFav.Items := GetIEFavourites(StrPas(FavPath));
if SetFrm.ch18.Checked then
begin
SetWindowLong(ImportFrm.Handle, GWL_EXSTYLE,
GetWindowLOng(ImportFrm.Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW);
end;
end;
procedure TImportFrm.OKClick(Sender: TObject);
begin
PostMessage(ImportFrm.Handle, WM_USER + 1024, 0, 0);
if FileExists(TextString) then
if Application.MessageBox(PChar('Файл "' + TextString +
'" существует.' + #13 + 'Заменить его?'), 'Подтвердите замену',
MB_ICONQUESTION + mb_YesNo) <> idYes then
begin
end else
begin
listFav.Items.SaveToFile(TextString);
end;
if not FileExists(TextString) then
begin
listFav.Items.SaveToFile(TextString);
end;
if OK.Caption = 'Готово' then
ImportFrm.Close;
end;
procedure TImportFrm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
TextString := '';
ChooseBt.Visible := True;
edExport.Visible := True;
tx1.Caption := 'Мастер экспорта избранного';
tx2.Caption := 'Мастер экспорта избранного позволяет легко';
tx3.Caption := 'экспортировать данные из Internet Explorer';
tx4.Caption := 'в другие приложения или файлы.';
tx5.Caption := 'Экспортировать в файл.';
edResult.Visible := False;
edResult.Text := '';
OK.Caption := 'OK';
edExport.Text := '';
edExport.SetFocus;
end;
procedure TImportFrm.FormDestroy(Sender: TObject);
begin
ImportFrm.OnActivate := nil;
ChooseBt.Free;
edExport.Free;
edResult.Free;
Cancel.Free;
tx1.Free;
tx2.Free;
tx3.Free;
tx4.Free;
tx5.Free;
fr1.Free;
OK.Free;
end;
procedure TImportFrm.ChangeMessageBoxPosition(var Msg: TMessage);
var
MbHwnd: longword;
MbRect: TRect;
x, y, w, h: integer;
begin
MbHwnd := FindWindow(MAKEINTRESOURCE(WC_DIALOG), msgCaption);
if (MbHwnd <> 0) then
begin
GetWindowRect(MBHWnd, MBRect);
with MbRect do
begin
w := Right - Left;
h := Bottom - Top;
end;
x := ImportFrm.Left + ((ImportFrm.Width - w) div 2);
if x < 0 then
x := 0
else if x + w > Screen.Width then x := Screen.Width - w;
y := ImportFrm.Top + ((ImportFrm.Height - h) div 2);
if y < 0 then y := 0
else if y + h > Screen.Height then y := Screen.Height - h;
SetWindowPos(MBHWnd, 0, x, y, 0, 0, SWP_NOACTIVATE or SWP_NOSIZE or SWP_NOZORDER);
end;
end;
procedure TImportFrm.ChooseBtClick(Sender: TObject);
begin
if OpenSaveFileDialog(Handle, '*.html',
'Файлы HTML (*.htm;*.html)|*.htm;*.html|Текстовые документы (*.txt)|*.txt|', ParamStr(1),
'', TextString, False) then
begin
ChooseBt.Visible := False;
edExport.Visible := False;
tx1.Caption := 'Завершение работы мастера';
tx2.Caption := 'Работа мастера экспорта успешно завершена.';
tx3.Caption := 'После нажатия кнопки "Готово" произойдет следующее.';
tx4.Caption := '';
tx5.Caption := '';
edResult.Visible := True;
edResult.Text := 'Экспорт избранного в "' + TextString + '".';
OK.Caption := 'Готово';
edExport.Text := TextString;
edResult.Top := 104;
end;
end;
procedure TImportFrm.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if SetFrm.ch19.Checked then
begin
ReleaseCapture;
Perform(Wm_SysCommand, $f012, 0);
end;
end;
procedure TImportFrm.WMMoving(var msg: TWMMoving);
var
r: TRect;
begin
if SetFrm.ch21.Checked then begin
r := Screen.WorkareaRect;
if msg.lprect^.left < r.left then
OffsetRect(msg.lprect^, r.left - msg.lprect^.left, 0);
if msg.lprect^.top < r.top then
OffsetRect(msg.lprect^, 0, r.top - msg.lprect^.top);
if msg.lprect^.right > r.right then
OffsetRect(msg.lprect^, r.right - msg.lprect^.right, 0);
if msg.lprect^.bottom > r.bottom then
OffsetRect(msg.lprect^, 0, r.bottom - msg.lprect^.bottom);
end;
inherited;
end;
end.
|
{$i deltics.inc}
unit Test.Utf8Reader;
interface
uses
Deltics.Smoketest;
type
Utf8Reader = class(TTest)
procedure ReadsUtf8StringToEnd;
procedure ReadsUtf8StringToEndIgnoringAsciiWhitespace;
procedure ReadsWideStringToEnd;
procedure MoveBackRereadsCharacterPreviouslyRead;
procedure LocationReportsLine1Character5For5CharactersOnFirstLine;
procedure LocationReportsLine1Character5For5CharactersOnFirstLineSkippingWhitespace;
procedure LocationReportsLine2Character1AfterReadingFirstCharacterAfterCR;
procedure LocationReportsLine2Character1AfterReadingFirstCharacterAfterCRLF;
procedure NextWideCharDecodesTrailBytesCorrectly;
procedure NextWideCharDecodesSurrogatesCorrectly;
procedure ReadLineReadsSingleLine;
procedure ReadLineReadsBlankLinesWithCR;
procedure ReadLineReadsBlankLinesWithCRLF;
procedure ReadLineReadsMultipleLinesWithCR;
procedure ReadLineReadsMultipleLinesWithCRLF;
procedure EOFIsFalseForProtectedMethodsWhenPreviousCharIsCachedAfterMoveBackAtTheEndOfStream;
procedure EOFIsFalseWhenPreviousCharIsCachedAfterMoveBackAtTheEndOfStream;
end;
implementation
uses
Deltics.Strings,
Deltics.IO.Text;
{ UtfReader }
type TProtectedReader = class(TUtf8Reader);
procedure Utf8Reader.EOFIsFalseForProtectedMethodsWhenPreviousCharIsCachedAfterMoveBackAtTheEndOfStream;
var
src: Utf8String;
sut: TProtectedReader;
begin
src := 'Test';
sut := TProtectedReader.Create(src);
sut.Skip(4);
Test('EOF').Assert(sut.EOF).IsTrue;
sut.MoveBack;
Test('EOF').Assert(sut.EOF).IsFALSE;
end;
procedure Utf8Reader.EOFIsFalseWhenPreviousCharIsCachedAfterMoveBackAtTheEndOfStream;
var
src: Utf8String;
sut: IUtf8Reader;
begin
src := 'Test';
sut := TUtf8Reader.Create(src);
sut.Skip(4);
Test('EOF').Assert(sut.EOF).IsTrue;
sut.MoveBack;
Test('EOF (after MoveBack)').Assert(sut.EOF).IsFalse;
Test('NextChar (after MoveBack)').AssertUtf8(sut.NextChar).Equals('t');
Test('EOF (after NextChar, after MoveBack)').Assert(sut.EOF).IsTrue;
end;
procedure Utf8Reader.LocationReportsLine1Character5For5CharactersOnFirstLine;
var
src: Utf8String;
sut: IUtf8Reader;
c: Utf8Char;
begin
src := 'The quick brown fox'#13'jumped over the lazy dog!';
sut := TUtf8Reader.Create(src);
sut.Skip(4);
c := sut.NextChar;
Test('c').Assert(c).Equals('q');
Test('Location.Line').Assert(sut.Location.Line).Equals(1);
Test('Location.Character').Assert(sut.Location.Character).Equals(5);
end;
procedure Utf8Reader.LocationReportsLine1Character5For5CharactersOnFirstLineSkippingWhitespace;
var
src: Utf8String;
sut: IUtf8Reader;
c: Utf8Char;
begin
src := 'The quick brown fox'#13'jumped over the lazy dog!';
sut := TUtf8Reader.Create(src);
sut.Skip(3);
c := sut.NextCharSkippingWhitespace;
Test('c').Assert(c).Equals('q');
Test('Location.Line').Assert(sut.Location.Line).Equals(1);
Test('Location.Character').Assert(sut.Location.Character).Equals(5);
end;
procedure Utf8Reader.LocationReportsLine2Character1AfterReadingFirstCharacterAfterCR;
var
src: Utf8String;
sut: IUtf8Reader;
c: Utf8Char;
begin
src := 'The quick brown fox'#13'jumped over the lazy dog!';
sut := TUtf8Reader.Create(src);
sut.Skip(19);
sut.SkipWhitespace;
c := sut.NextChar;
Test('c').Assert(c).Equals('j');
Test('Location.Line').Assert(sut.Location.Line).Equals(2);
Test('Location.Character').Assert(sut.Location.Character).Equals(1);
end;
procedure Utf8Reader.LocationReportsLine2Character1AfterReadingFirstCharacterAfterCRLF;
var
src: Utf8String;
sut: IUtf8Reader;
c: Utf8Char;
begin
src := 'The quick brown fox'#13#10'jumped over the lazy dog!';
sut := TUtf8Reader.Create(src);
sut.Skip(19);
sut.SkipWhitespace;
c := sut.NextChar;
Test('c').Assert(c).Equals('j');
Test('Location.Line').Assert(sut.Location.Line).Equals(2);
Test('Location.Character').Assert(sut.Location.Character).Equals(1);
end;
procedure Utf8Reader.MoveBackRereadsCharacterPreviouslyRead;
var
src: Utf8String;
s: Utf8String;
sut: IUtf8Reader;
begin
src := 'abc';
sut := TUtf8Reader.Create(src);
s := Utf8.Append(s, sut.NextChar);
s := Utf8.Append(s, sut.NextChar);
sut.MoveBack;
s := Utf8.Append(s, sut.NextChar);
s := Utf8.Append(s, sut.NextChar);
Test('s').Assert(STR.FromUTF8(s)).Equals('abbc');
end;
procedure Utf8Reader.NextWideCharDecodesSurrogatesCorrectly;
{
For this test we use Unicode codepoint Ux1d11e - the treble clef
UTF-8 Encoding : 0xF0 0x9D 0x84 0x9E
UTF-16 Encoding : 0xD834 0xDD1E
}
var
src: Utf8String;
hi, lo: WideChar;
c: Utf8Char;
sut: IUtf8Reader;
begin
src := 'a????b';
src[2] := Utf8Char($f0);
src[3] := Utf8Char($9d);
src[4] := Utf8Char($84);
src[5] := Utf8Char($9e);
sut := TUtf8Reader.Create(src);
sut.NextChar;
hi := sut.NextWideChar;
lo := sut.NextWideChar;
c := sut.NextChar;
Test('hi').Assert(Word(hi)).Equals($d834);
Test('lo').Assert(Word(lo)).Equals($dd1e);
Test('c').Assert(c).Equals('b');
end;
procedure Utf8Reader.NextWideCharDecodesTrailBytesCorrectly;
var
src: Utf8String;
wc: WideChar;
sut: IUtf8Reader;
begin
src := 'Quick Brown??2020';
src[12] := Utf8Char($c2);
src[13] := Utf8Char($a9);
sut := TUtf8Reader.Create(src);
sut.Skip(11);
wc := sut.NextWideChar;
Test('wc').Assert(Word(wc)).Equals(169);
end;
procedure Utf8Reader.ReadLineReadsBlankLinesWithCR;
const
LINE1: Utf8String = 'The quick brown fox';
LINE2: Utf8String = 'jumped over the lazy dog';
var
src: Utf8String;
s1, s2, s3: Utf8String;
sut: IUtf8Reader;
begin
src := LINE1 + #13#13 + LINE2;
sut := TUtf8Reader.Create(src);
Test('Line').Assert(sut.Location.Line).Equals(1);
s1 := sut.ReadLine;
Test('Line').Assert(sut.Location.Line).Equals(2);
s2 := sut.ReadLine;
Test('Line').Assert(sut.Location.Line).Equals(3);
s3 := sut.ReadLine;
Test('Line').Assert(sut.Location.Line).Equals(3);
Test('s1').Assert(STR.FromUtf8(s1)).Equals(STR.FromUtf8(LINE1));
Test('s2').Assert(STR.FromUtf8(s2)).IsEmpty;
Test('s3').Assert(STR.FromUtf8(s3)).Equals(STR.FromUtf8(LINE2));
end;
procedure Utf8Reader.ReadLineReadsBlankLinesWithCRLF;
const
LINE1: Utf8String = 'The quick brown fox';
LINE2: Utf8String = 'jumped over the lazy dog';
var
src: Utf8String;
s1, s2, s3: Utf8String;
sut: IUtf8Reader;
begin
src := LINE1 + #13#10#13#10 + LINE2;
sut := TUtf8Reader.Create(src);
Test('Line').Assert(sut.Location.Line).Equals(1);
s1 := sut.ReadLine;
Test('Line').Assert(sut.Location.Line).Equals(2);
s2 := sut.ReadLine;
Test('Line').Assert(sut.Location.Line).Equals(3);
s3 := sut.ReadLine;
Test('Line').Assert(sut.Location.Line).Equals(3);
Test('s1').Assert(STR.FromUtf8(s1)).Equals(STR.FromUtf8(LINE1));
Test('s2').Assert(STR.FromUtf8(s2)).IsEmpty;
Test('s3').Assert(STR.FromUtf8(s3)).Equals(STR.FromUtf8(LINE2));
end;
procedure Utf8Reader.ReadLineReadsMultipleLinesWithCR;
const
LINE1: Utf8String = 'The quick brown fox';
LINE2: Utf8String = 'jumped over the lazy dog';
var
src: Utf8String;
s1, s2: Utf8String;
sut: IUtf8Reader;
begin
src := LINE1 + #13 + LINE2;
sut := TUtf8Reader.Create(src);
Test('Line').Assert(sut.Location.Line).Equals(1);
s1 := sut.ReadLine;
Test('Line').Assert(sut.Location.Line).Equals(2);
s2 := sut.ReadLine;
Test('Line').Assert(sut.Location.Line).Equals(2);
Test('s1').Assert(STR.FromUtf8(s1)).Equals(STR.FromUtf8(LINE1));
Test('s2').Assert(STR.FromUtf8(s2)).Equals(STR.FromUtf8(LINE2));
end;
procedure Utf8Reader.ReadLineReadsMultipleLinesWithCRLF;
const
LINE1: Utf8String = 'The quick brown fox';
LINE2: Utf8String = 'jumped over the lazy dog';
var
src: Utf8String;
s1, s2: Utf8String;
sut: IUtf8Reader;
begin
src := LINE1 + #13#10 + LINE2;
sut := TUtf8Reader.Create(src);
Test('Line').Assert(sut.Location.Line).Equals(1);
s1 := sut.ReadLine;
Test('Line').Assert(sut.Location.Line).Equals(2);
s2 := sut.ReadLine;
Test('Line').Assert(sut.Location.Line).Equals(2);
Test('s1').Assert(STR.FromUtf8(s1)).Equals(STR.FromUtf8(LINE1));
Test('s2').Assert(STR.FromUtf8(s2)).Equals(STR.FromUtf8(LINE2));
end;
procedure Utf8Reader.ReadLineReadsSingleLine;
var
src: Utf8String;
s: Utf8String;
sut: IUtf8Reader;
begin
src := 'The quick brown fox jumped over the lazy dog!';
sut := TUtf8Reader.Create(src);
s := sut.ReadLine;
Test('s').Assert(STR.FromUtf8(s)).Equals(STR.FromUtf8(src));
end;
procedure Utf8Reader.ReadsUtf8StringToEnd;
var
src: Utf8String;
s: Utf8String;
sut: IUtf8Reader;
begin
src := 'The quick brown fox jumped over the lazy dog!';
sut := TUtf8Reader.Create(src);
while NOT sut.EOF do
s := Utf8.Append(s, sut.NextChar);
Test('').Assert(STR.FromUtf8(s)).Equals(STR.FromUtf8(src));
end;
procedure Utf8Reader.ReadsUtf8StringToEndIgnoringAsciiWhitespace;
var
src, csrc: Utf8String;
s: Utf8String;
sut: IUtf8Reader;
begin
src := 'The quick brown fox jumped over the lazy dog!';
csrc := 'Thequickbrownfoxjumpedoverthelazydog!';
sut := TUtf8Reader.Create(src);
while NOT sut.EOF do
s := Utf8.Append(s, sut.NextCharSkippingWhitespace);
Test('').Assert(STR.FromUTF8(s)).Equals(STR.FromUtf8(csrc));
end;
procedure Utf8Reader.ReadsWideStringToEnd;
var
src: UnicodeString;
s: Utf8String;
sut: IUtf8Reader;
begin
src := 'The quick brown fox jumped over the lazy dog!';
sut := TUtf8Reader.Create(src);
while NOT sut.EOF do
s := Utf8.Append(s, sut.NextChar);
Test('').Assert(STR.FromUTF8(s)).Equals(src);
end;
end.
|
unit uAccessRightRule;
interface
uses SysUtils, Classes, uData, Controls, Menus, ComCtrls;
procedure SetWindowAccessState(userType:integer; window:TComponent);
implementation
function isOurUserType(ut_id: integer; enabledUsers: string):boolean;
var sl: TStringList;
i:integer;
begin
if enabledUsers = '*' then exit(true);
i := 0;
result := false;
sl := TStringList.Create;
sl.Delimiter := ';';
sl.StrictDelimiter := true;
sl.DelimitedText := trim(enabledUsers);
while (result <> true) or (i < sl.Count) do
begin
result := strToInt(sl[i]) = ut_id;
inc(i);
end;
freeAndNil(sl);
end;
function findObject(window: TComponent; objName: string): TComponent;
begin
result := window.FindComponent(objName);
end;
// Устанавливаем состояние контрола. По смыслу: "+" - разрешить нажать/редактировать,
// "-" - read-only - можно смотреть, трогать низя, "/" - спрятать.
procedure setControlAccessState(control: TComponent; action: string);
begin
if action = '/' then
begin
if control is TTabSheet then TTabSheet(control).TabVisible := false;
end
else if action = '-' then
begin
if control is TTabSheet then TTabSheet(control).Enabled := false;
end
else if action = '+' then
begin
if control is TTabSheet then
begin
TTabSheet(control).TabVisible := true;
TTabSheet(control).Enabled := true;
end;
end;
end;
procedure ApplyRule(ut_id: integer;
window: TComponent;
enabledUsers, targetObject, checkObject, checkMode:string;
checkObjectValue: double;
action: String);
var sl:TStringList;
i:integer;
checkObjectFound:TComponent;
objectVal:double;
begin
if not isOurUserType(ut_id, enabledUsers) then exit;
sl := TStringList.Create;
sl.Delimiter := ';';
sl.StrictDelimiter := true;
sl.DelimitedText := trim(targetObject);
for i := 0 to sl.Count - 1 do
begin
checkObjectFound := findObject(window, sl[i]);
if checkObjectFound = nil then continue;
if (checkObjectFound is TControl) or
(checkObjectFound is TMenuItem) then
setControlAccessState(checkObjectFound, action);
end;
freeAndNil(sl);
end;
// Находит все правила, связанные с этим окном, и устанавливает их
procedure SetWindowAccessState(userType:integer; window:TComponent);
begin
data.qAccessRight.Close;
data.qAccessRight.ParamByName('wnd').AsString := window.Name;
data.qAccessRight.Open;
if data.qAccessRight.IsEmpty then exit;
while not data.qAccessRight.Eof do
begin
ApplyRule(userType,
window,
data.qAccessRightARR_USER_TYPES.AsString,
data.qAccessRightARR_TARGET_OBJECT_NAME.AsString,
data.qAccessRightARR_CHECK_OBJECT_NAME.AsString,
data.qAccessRightARR_CHECK_MODE.AsString,
data.qAccessRightARR_CHECK_OBJECT_VALUE.AsFloat,
data.qAccessRightARR_ACTION.AsString);
data.qAccessRight.Next
end;
end;
end.
|
unit uExceptions;
interface
uses
System.SysUtils, Vcl.Controls;
type
TControlException = class(Exception)
private
FControl: TWinControl;
procedure SetControl(const Value: TWinControl);
public
property Control: TWinControl read FControl write SetControl;
constructor Create(ipMsg: string; ipControl: TWinControl); reintroduce;
end;
//exception utilizada apenas para sinalizar que se deseja parar a execucao do programa, mas nao queremos mostrar erro algum
TPararExecucaoException = class(Exception)
end;
implementation
{ TEditException }
constructor TControlException.Create(ipMsg: string; ipControl: TWinControl);
begin
inherited Create(ipMsg);
FControl := ipControl;
end;
procedure TControlException.SetControl(const Value: TWinControl);
begin
FControl := Value;
end;
end.
|
unit Asn;
interface
type
HCkByteData = Pointer;
HCkAsn = Pointer;
HCkString = Pointer;
function CkAsn_Create: HCkAsn; stdcall;
procedure CkAsn_Dispose(handle: HCkAsn); stdcall;
function CkAsn_getBoolValue(objHandle: HCkAsn): wordbool; stdcall;
procedure CkAsn_putBoolValue(objHandle: HCkAsn; newPropVal: wordbool); stdcall;
function CkAsn_getConstructed(objHandle: HCkAsn): wordbool; stdcall;
procedure CkAsn_getContentStr(objHandle: HCkAsn; outPropVal: HCkString); stdcall;
procedure CkAsn_putContentStr(objHandle: HCkAsn; newPropVal: PWideChar); stdcall;
function CkAsn__contentStr(objHandle: HCkAsn): PWideChar; stdcall;
procedure CkAsn_getDebugLogFilePath(objHandle: HCkAsn; outPropVal: HCkString); stdcall;
procedure CkAsn_putDebugLogFilePath(objHandle: HCkAsn; newPropVal: PWideChar); stdcall;
function CkAsn__debugLogFilePath(objHandle: HCkAsn): PWideChar; stdcall;
function CkAsn_getIntValue(objHandle: HCkAsn): Integer; stdcall;
procedure CkAsn_putIntValue(objHandle: HCkAsn; newPropVal: Integer); stdcall;
procedure CkAsn_getLastErrorHtml(objHandle: HCkAsn; outPropVal: HCkString); stdcall;
function CkAsn__lastErrorHtml(objHandle: HCkAsn): PWideChar; stdcall;
procedure CkAsn_getLastErrorText(objHandle: HCkAsn; outPropVal: HCkString); stdcall;
function CkAsn__lastErrorText(objHandle: HCkAsn): PWideChar; stdcall;
procedure CkAsn_getLastErrorXml(objHandle: HCkAsn; outPropVal: HCkString); stdcall;
function CkAsn__lastErrorXml(objHandle: HCkAsn): PWideChar; stdcall;
function CkAsn_getLastMethodSuccess(objHandle: HCkAsn): wordbool; stdcall;
procedure CkAsn_putLastMethodSuccess(objHandle: HCkAsn; newPropVal: wordbool); stdcall;
function CkAsn_getNumSubItems(objHandle: HCkAsn): Integer; stdcall;
procedure CkAsn_getTag(objHandle: HCkAsn; outPropVal: HCkString); stdcall;
function CkAsn__tag(objHandle: HCkAsn): PWideChar; stdcall;
function CkAsn_getTagValue(objHandle: HCkAsn): Integer; stdcall;
function CkAsn_getVerboseLogging(objHandle: HCkAsn): wordbool; stdcall;
procedure CkAsn_putVerboseLogging(objHandle: HCkAsn; newPropVal: wordbool); stdcall;
procedure CkAsn_getVersion(objHandle: HCkAsn; outPropVal: HCkString); stdcall;
function CkAsn__version(objHandle: HCkAsn): PWideChar; stdcall;
function CkAsn_AppendBigInt(objHandle: HCkAsn; encodedBytes: PWideChar; encoding: PWideChar): wordbool; stdcall;
function CkAsn_AppendBits(objHandle: HCkAsn; encodedBytes: PWideChar; encoding: PWideChar): wordbool; stdcall;
function CkAsn_AppendBool(objHandle: HCkAsn; value: wordbool): wordbool; stdcall;
function CkAsn_AppendContextConstructed(objHandle: HCkAsn; tag: Integer): wordbool; stdcall;
function CkAsn_AppendContextPrimitive(objHandle: HCkAsn; tag: Integer; encodedBytes: PWideChar; encoding: PWideChar): wordbool; stdcall;
function CkAsn_AppendInt(objHandle: HCkAsn; value: Integer): wordbool; stdcall;
function CkAsn_AppendNull(objHandle: HCkAsn): wordbool; stdcall;
function CkAsn_AppendOctets(objHandle: HCkAsn; encodedBytes: PWideChar; encoding: PWideChar): wordbool; stdcall;
function CkAsn_AppendOid(objHandle: HCkAsn; oid: PWideChar): wordbool; stdcall;
function CkAsn_AppendSequence(objHandle: HCkAsn): wordbool; stdcall;
function CkAsn_AppendSequence2(objHandle: HCkAsn): wordbool; stdcall;
function CkAsn_AppendSequenceR(objHandle: HCkAsn): HCkAsn; stdcall;
function CkAsn_AppendSet(objHandle: HCkAsn): wordbool; stdcall;
function CkAsn_AppendSet2(objHandle: HCkAsn): wordbool; stdcall;
function CkAsn_AppendSetR(objHandle: HCkAsn): HCkAsn; stdcall;
function CkAsn_AppendString(objHandle: HCkAsn; strType: PWideChar; value: PWideChar): wordbool; stdcall;
function CkAsn_AppendTime(objHandle: HCkAsn; timeFormat: PWideChar; dateTimeStr: PWideChar): wordbool; stdcall;
function CkAsn_AsnToXml(objHandle: HCkAsn; outStr: HCkString): wordbool; stdcall;
function CkAsn__asnToXml(objHandle: HCkAsn): PWideChar; stdcall;
function CkAsn_DeleteSubItem(objHandle: HCkAsn; index: Integer): wordbool; stdcall;
function CkAsn_GetBinaryDer(objHandle: HCkAsn; outData: HCkByteData): wordbool; stdcall;
function CkAsn_GetEncodedContent(objHandle: HCkAsn; encoding: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkAsn__getEncodedContent(objHandle: HCkAsn; encoding: PWideChar): PWideChar; stdcall;
function CkAsn_GetEncodedDer(objHandle: HCkAsn; encoding: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkAsn__getEncodedDer(objHandle: HCkAsn; encoding: PWideChar): PWideChar; stdcall;
function CkAsn_GetLastSubItem(objHandle: HCkAsn): HCkAsn; stdcall;
function CkAsn_GetSubItem(objHandle: HCkAsn; index: Integer): HCkAsn; stdcall;
function CkAsn_LoadAsnXml(objHandle: HCkAsn; xmlStr: PWideChar): wordbool; stdcall;
function CkAsn_LoadBinary(objHandle: HCkAsn; derBytes: HCkByteData): wordbool; stdcall;
function CkAsn_LoadBinaryFile(objHandle: HCkAsn; path: PWideChar): wordbool; stdcall;
function CkAsn_LoadEncoded(objHandle: HCkAsn; asnContent: PWideChar; encoding: PWideChar): wordbool; stdcall;
function CkAsn_SaveLastError(objHandle: HCkAsn; path: PWideChar): wordbool; stdcall;
function CkAsn_SetEncodedContent(objHandle: HCkAsn; encodedBytes: PWideChar; encoding: PWideChar): wordbool; stdcall;
function CkAsn_WriteBinaryDer(objHandle: HCkAsn; path: PWideChar): wordbool; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkAsn_Create; external DLLName;
procedure CkAsn_Dispose; external DLLName;
function CkAsn_getBoolValue; external DLLName;
procedure CkAsn_putBoolValue; external DLLName;
function CkAsn_getConstructed; external DLLName;
procedure CkAsn_getContentStr; external DLLName;
procedure CkAsn_putContentStr; external DLLName;
function CkAsn__contentStr; external DLLName;
procedure CkAsn_getDebugLogFilePath; external DLLName;
procedure CkAsn_putDebugLogFilePath; external DLLName;
function CkAsn__debugLogFilePath; external DLLName;
function CkAsn_getIntValue; external DLLName;
procedure CkAsn_putIntValue; external DLLName;
procedure CkAsn_getLastErrorHtml; external DLLName;
function CkAsn__lastErrorHtml; external DLLName;
procedure CkAsn_getLastErrorText; external DLLName;
function CkAsn__lastErrorText; external DLLName;
procedure CkAsn_getLastErrorXml; external DLLName;
function CkAsn__lastErrorXml; external DLLName;
function CkAsn_getLastMethodSuccess; external DLLName;
procedure CkAsn_putLastMethodSuccess; external DLLName;
function CkAsn_getNumSubItems; external DLLName;
procedure CkAsn_getTag; external DLLName;
function CkAsn__tag; external DLLName;
function CkAsn_getTagValue; external DLLName;
function CkAsn_getVerboseLogging; external DLLName;
procedure CkAsn_putVerboseLogging; external DLLName;
procedure CkAsn_getVersion; external DLLName;
function CkAsn__version; external DLLName;
function CkAsn_AppendBigInt; external DLLName;
function CkAsn_AppendBits; external DLLName;
function CkAsn_AppendBool; external DLLName;
function CkAsn_AppendContextConstructed; external DLLName;
function CkAsn_AppendContextPrimitive; external DLLName;
function CkAsn_AppendInt; external DLLName;
function CkAsn_AppendNull; external DLLName;
function CkAsn_AppendOctets; external DLLName;
function CkAsn_AppendOid; external DLLName;
function CkAsn_AppendSequence; external DLLName;
function CkAsn_AppendSequence2; external DLLName;
function CkAsn_AppendSequenceR; external DLLName;
function CkAsn_AppendSet; external DLLName;
function CkAsn_AppendSet2; external DLLName;
function CkAsn_AppendSetR; external DLLName;
function CkAsn_AppendString; external DLLName;
function CkAsn_AppendTime; external DLLName;
function CkAsn_AsnToXml; external DLLName;
function CkAsn__asnToXml; external DLLName;
function CkAsn_DeleteSubItem; external DLLName;
function CkAsn_GetBinaryDer; external DLLName;
function CkAsn_GetEncodedContent; external DLLName;
function CkAsn__getEncodedContent; external DLLName;
function CkAsn_GetEncodedDer; external DLLName;
function CkAsn__getEncodedDer; external DLLName;
function CkAsn_GetLastSubItem; external DLLName;
function CkAsn_GetSubItem; external DLLName;
function CkAsn_LoadAsnXml; external DLLName;
function CkAsn_LoadBinary; external DLLName;
function CkAsn_LoadBinaryFile; external DLLName;
function CkAsn_LoadEncoded; external DLLName;
function CkAsn_SaveLastError; external DLLName;
function CkAsn_SetEncodedContent; external DLLName;
function CkAsn_WriteBinaryDer; external DLLName;
end.
|
{*******************************************************}
{ }
{ NTS Aero UI Library }
{ Created by GooD-NTS ( good.nts@gmail.com ) }
{ http://ntscorp.ru/ Copyright(c) 2011 }
{ License: Mozilla Public License 1.1 }
{ }
{*******************************************************}
unit UI.Aero.Core;
interface
{$I '../../Common/CompilerVersion.Inc'}
uses
{$IFDEF HAS_UNITSCOPE}
System.SysUtils,
System.Classes,
Winapi.Windows,
Winapi.UxTheme,
Vcl.Graphics;
{$ELSE}
SysUtils, Classes, Windows, UxTheme, Graphics;
{$ENDIF}
type
TDrawProcedure = procedure(ADC: hDC; ATheme: hTheme; APartID, AStateID: Integer; AFont: TFont; AFormat: DWORD; ARect: TRect; AText: String; AGlow: BooLean) of object;
AeroCore = Class(TComponent)
Private
class var RenderFunction: TDrawProcedure;
class procedure DrawVista(ADC: hDC; ATheme: hTheme; APartID, AStateID: Integer; AFont: TFont; AFormat: DWORD; ARect: TRect; AText: String; AGlow: BooLean);
class procedure DrawXP(ADC: hDC; ATheme: hTheme; APartID, AStateID: Integer; AFont: TFont; AFormat: DWORD; ARect: TRect; AText: String; AGlow: BooLean);
Public
class var FirstInstance: AeroCore;
class var RunWindowsVista: BooLean;
class var CompositionActive: BooLean;
class procedure RenderText(ADC: hDC; ATheme: hTheme; APartID, AStateID: Integer; AFont: TFont; AFormat: DWORD; ARect: TRect; AText: String; AGlow: BooLean); OverLoad;
class procedure RenderText(ADC: hDC; AFont: TFont; AFormat: DWORD; ARect: TRect; AText: String); OverLoad;
End;
implementation
{ AeroCore }
class procedure AeroCore.DrawVista(ADC: hDC; ATheme: hTheme; APartID, AStateID: Integer; AFont: TFont; AFormat: DWORD; ARect: TRect; AText: String; AGlow: BooLean);
var
Options: TDTTOpts;
begin
if CompositionActive and (ATheme <> 0) then
begin
SelectObject(ADC,AFont.Handle);
ZeroMemory(@Options,SizeOf(TDTTOpts));
Options.dwSize:= SizeOf(TDTTOpts);
Options.dwFlags:= DTT_COMPOSITED or DTT_TEXTCOLOR;
Options.crText:= ColorToRGB(AFont.Color);
if AGlow then
begin
Options.dwFlags:= Options.dwFlags or DTT_GLOWSIZE;
Options.iGlowSize:= 12;
end;
DrawThemeTextEx(ATheme, ADC, APartID, AStateID, PWideChar(AText), -1,
AFormat, @ARect, Options);
end
else
DrawXP(ADC,ATheme,APartID,AStateID,AFont,AFormat,ARect,AText,AGlow);
end;
class procedure AeroCore.DrawXP(ADC: hDC; ATheme: hTheme; APartID, AStateID: Integer; AFont: TFont; AFormat: DWORD; ARect: TRect; AText: String; AGlow: BooLean);
var
OldBkMode: Integer;
begin
SelectObject(ADC, AFont.Handle);
SetTextColor(ADC, ColorToRGB(AFont.Color));
OldBkMode := SetBkMode(ADC, Transparent);
DrawText(ADC, pChar(AText), -1, ARect, AFormat);
SetBkMode(ADC, OldBkMode);
end;
class procedure AeroCore.RenderText(ADC: hDC; AFont: TFont; AFormat: DWORD; ARect: TRect; AText: String);
begin
DrawXP(ADC, 0, 0, 0, AFont, AFormat, ARect, AText, False);
end;
class procedure AeroCore.RenderText(ADC: hDC; ATheme: hTheme; APartID, AStateID: Integer; AFont: TFont; AFormat: DWORD; ARect: TRect; AText: String; AGlow: BooLean);
begin
RenderFunction(ADC, ATheme, APartID, AStateID, AFont, AFormat, ARect, AText,
AGlow);
end;
Initialization
begin
InitThemeLibrary;
AeroCore.FirstInstance:= nil;
if CheckWin32Version(6, 0) then
begin
AeroCore.RunWindowsVista:= True;
AeroCore.CompositionActive:= IsCompositionActive;
AeroCore.RenderFunction:= AeroCore.DrawVista;
end
else
begin
AeroCore.RunWindowsVista:= False;
AeroCore.CompositionActive:= False;
AeroCore.RenderFunction:= AeroCore.DrawXP;
end;
end;
Finalization
begin
// To Do: Type code here;
end;
end.
|
unit newSpeedButton; //for some reason parentfont does not work
{$mode objfpc}{$H+}
interface
uses
jwawindows, windows, Classes, SysUtils, Controls, StdCtrls, Buttons;
type
TNewSpeedButton=class(TSpeedButton)
private
darkmode: boolean;
protected
procedure PaintBackground(var PaintRect: TRect); override;
procedure SetParent(NewParent: TWinControl); override;
public
end;
implementation
uses betterControls, themes, Graphics;
procedure TNewSpeedButton.PaintBackground(var PaintRect: TRect);
begin
if ShouldAppsUseDarkMode and darkmode then
begin
case FState of
bsUp: Canvas.Brush.Color := Color;
bsDisabled: Canvas.brush.Color:= Color xor $aaaaaa;
bsHot: Canvas.Brush.Color:=incColor(color,15); //or $aaaaaa;
bsDown: Canvas.Brush.Color :=incColor(color,32);
end;
Canvas.FillRect(PaintRect);
canvas.pen.color:=color xor $aaaaaa;
Canvas.Rectangle(PaintRect);
end
else
inherited PaintBackground(paintrect);
end;
procedure TNewSpeedButton.SetParent(NewParent: TWinControl);
begin
inherited SetParent(newparent);
if (NewParent<>nil) and ShouldAppsUseDarkMode then
begin
darkmode:=true;
color:=ColorSet.TextBackground;
end;
end;
end.
|
{ Subroutine STRING_LJ (S)
*
* Left justify string S by removing leading spaces.
}
module string_lj;
define string_lj;
%include 'string2.ins.pas';
procedure string_lj ( {left justify string by removing leading spaces}
in out s: univ string_var_arg_t); {string}
var
i, j, k: sys_int_machine_t; {index into string}
begin
for i := 1 to s.len do begin {scan all characters backwards}
if s.str[i] = ' ' {is this a blank character ?}
then next {still haven't hit non-blank}
else begin {this was a non-blank}
k := 0;
for j := i to s.len do begin
k := k + 1; {increment new location of character}
s.str[k] := s.str[j]; {move character to new location}
end;
s.len := s.len - (i - 1); {set new string length}
return; {all done}
end {done with non_blank}
;
end; {back and do next character}
s.len := 0; {only blanks, null string}
end;
|
unit Herramientas;
interface
uses crt;
const
FILAS = 32;
COLUMNAS = 32;
type
//Cambiar string por el tipo que corresponde
Pila = Record
elems: array[1..1024] of string;
tope: integer;
end;
//Cambiar tipo string y tamaņo despues 32x32=1024 elementos
Matriz = Array[1..FILAS,1..COLUMNAS] of string;
//Procedimientos Pila
procedure InicializarPila(var P:Pila);
procedure ApilarPila(var P:Pila; Elem:string);
function DesapilarPila(var P:Pila): string;
function CantidadPila(P:Pila): integer;
//Procedimientos Matriz
//Realmente ni idea que poner, pero por las dudas y porque estoy no tengo
//nada mejor que hacer igual asi que veo que sale
procedure InicializarMatriz(var M:Matriz);
procedure BuscarElemEnMatriz(var M:Matriz; elemBuscado: string;var fila:byte;var columna:byte);
implementation
//Pone el tope en 0
procedure InicializarPila(var P:Pila);
begin
P.tope := 0;
end;
//Aumenta el tope y agrega el nuevo elemento en la ultima posicion
procedure ApilarPila(var P:Pila; Elem:string);
begin
P.tope := P.tope + 1;
P.elems[P.tope] := elem;
end;
//Devuelve el elemento superior de la pila, lo elemina y decrementa el tope
function DesapilarPila(var P:Pila): string;
begin
DesapilarPila := P.elems[P.tope];
P.elems[P.tope] := '';
P.tope := P.tope - 1;
end;
//Devuelve el tope, es igual a la cantidad de elementos
function CantidadPila(P:Pila): integer;
begin
CantidadPila := P.tope;
end;
//Pone todos los elementos en blanco total la memoria ya esta ocupada
procedure InicializarMatriz(var M:Matriz);
var i,j:byte;
begin
for i:=1 to FILAS do
begin
for j:=1 to COLUMNAS do
begin
M[i,j]:='';
end;
end;
end;
//Busca la fila y columna de un determinado elemento
//No es muy util pero sirvio de practica
procedure BuscarElemEnMatriz(var M:Matriz; elemBuscado: string;var fila:byte;var columna:byte);
var
i,j:byte;
encontrado : boolean;
begin
i:=1;
j:=1;
encontrado := false;
while (i<>FILAS) or (encontrado = true) do
begin
while (j<>COLUMNAS) or (encontrado = true) do
begin
if (M[i,j] = elemBuscado) then
begin
fila:=i;
columna:=j;
encontrado := true;
end;
j += 1;
end;
i += 1;
end;
end;
begin
end.
|
unit _BSY;
/////////////////////////////////////////////////////////////////////
//
// Hi-Files Version 2
// Copyright (c) 1997-2004 Dmitry Liman [2:461/79]
//
// http://hi-files.narod.ru
//
/////////////////////////////////////////////////////////////////////
interface
function SetBusyFlag: Boolean;
procedure DropBusyFlag;
{ =================================================================== }
implementation
uses
Views, Dialogs, Drivers, _Working, Objects, App, MsgBox,
SysUtils, MyLib, _RES, HiFiHelp;
const
BUSY_EXT = '.bsy';
WAIT_DELAY = 30;
RIP_TIMEOUT = 30 * 60; // 30 min
type
PWaiting = ^TWaiting;
TWaiting = object (TDialog)
constructor Init( const aBusyFlag: String; aWaitDelay : Integer );
procedure GetEvent( var Event: TEvent ); virtual;
procedure HandleEvent( var Event: TEvent ); virtual;
private
Started: UnixTime;
Delayed: UnixTime;
TimeOut: UnixTime;
ProgBar: PProgress;
BusyFlag : String;
function BusyFlagDied: Boolean;
end; { TWaiting }
const
cmKillBusyFlag = 1000;
{ --------------------------------------------------------- }
{ TWaiting }
{ --------------------------------------------------------- }
constructor TWaiting.Init( const aBusyFlag: String; aWaitDelay : Integer );
var
R: TRect;
begin
R.Assign( 0, 0, 46, 9 );
inherited Init( R, LoadString(_SBusyCaption));
Options := Options or ofCentered;
BusyFlag := aBusyFlag;
Started := CurrentUnixTime;
TimeOut := Started + aWaitDelay;
R.Grow( -2, -2 );
R.B.Y := R.A.Y + 2;
Insert( New( PStaticText, Init( R, ^C + LoadString(_SBusyMsg1) + ^M^J^C + LoadString(_SBusyMsg2) )));
R.Move( 0, 2 ); R.B.Y := Succ( R.A.Y );
ProgBar := New( PProgress, Init( R, aWaitDelay ) );
Insert( ProgBar );
R.Move( 0, 2 ); Inc( R.B.Y ); R.B.X := R.A.X + 20;
Insert( New( PButton, Init( R, LoadString(_SKillFlagBtn), cmKillBusyFlag, bfNormal )));
R.Move( 22, 0 );
Insert( New( PButton, Init( R, LoadString(_SExitBtn), cmCancel, bfNormal )));
SelectNext( False );
HelpCtx := hcBusyWaiting;
end; { Init }
{ --------------------------------------------------------- }
{ GetEvent }
{ --------------------------------------------------------- }
procedure TWaiting.GetEvent( var Event: TEvent );
var
d: UnixTime;
begin
d := CurrentUnixTime;
if d <> Delayed then
begin
Delayed := d;
ProgBar^.Update( Delayed - Started );
if not FileExists( BusyFlag ) then
begin
Event.What := evCommand;
Event.Command := cmOk;
Exit;
end;
if Delayed >= TimeOut then
begin
Event.What := evCommand;
Event.Command := cmCancel;
Exit;
end;
end;
inherited GetEvent( Event );
end; { GetEvent }
{ --------------------------------------------------------- }
{ BusyFlagDied }
{ --------------------------------------------------------- }
function TWaiting.BusyFlagDied: Boolean;
begin
Result := VFS_EraseFile( BusyFlag );
if not Result then
MessageBox( Format(LoadString(_SCantKillFlag), [BusyFlag]), nil,
mfWarning + mfOkButton );
end; { BusyFlagDied }
{ --------------------------------------------------------- }
{ HandleEvent }
{ --------------------------------------------------------- }
procedure TWaiting.HandleEvent( var Event: TEvent );
begin
inherited HandleEvent( Event );
case Event.What of
evCommand:
begin
case Event.Command of
cmKillBusyFlag:
if BusyFlagDied then
EndModal( cmOk );
end;
ClearEvent( Event );
end;
end;
end; { HandleEvent }
{ --------------------------------------------------------- }
{ StillAlive }
{ --------------------------------------------------------- }
function StillAlive( const FileName: String; WaitDelay: Integer ) : Boolean;
var
D: PDialog;
begin
if (CurrentUnixTime - FileTimeToUnix( FileAge( FileName ) ) < RIP_TIMEOUT) or
not VFS_EraseFile( FileName ) then
begin
OpenWorking( LoadString(_SWaiting) );
D := New( PWaiting, Init( FileName, WaitDelay ) );
Result := Application^.ExecView( D ) <> cmOk;
D^.Free;
CloseWorking;
end
else
Result := False;
end; { StillAlive }
{ --------------------------------------------------------- }
{ CreateFlag }
{ --------------------------------------------------------- }
function CreateFlag( const Flag: String ) : Boolean;
var
h: Integer;
begin
Result := True;
h := FileCreate( Flag );
if h > 0 then
FileClose( h )
else
Result := False;
end; { CreateFlag }
{ --------------------------------------------------------- }
{ SetBusyFlag }
{ --------------------------------------------------------- }
function SetBusyFlag: Boolean;
var
Busy: String;
begin
Result := False;
Busy := ChangeFileExt( ParamStr(0), BUSY_EXT );
if FileExists( Busy ) and StillAlive( Busy, WAIT_DELAY ) then Exit;
Result := CreateFlag( Busy );
end; { SetBusyFlag }
{ --------------------------------------------------------- }
{ DropBusyFlag }
{ --------------------------------------------------------- }
procedure DropBusyFlag;
begin
VFS_EraseFile( ChangeFileExt( ParamStr(0), BUSY_EXT ) );
end; { DropBusyFlag }
end.
|
unit clUsers;
interface
uses Data.DB, Data.Win.ADODB, Vcl.Dialogs;
type
users = class
public
id_user : integer;
registration_date : TDate;
login : string;
procedure getAllUsers;
end;
var
all_users : array of users;
implementation
uses glbVar, clProjects, clTasks, tasks;
procedure users.getAllUsers();
var
sqlQuery : TADOQuery;
i : integer;
begin
// загрузить список пользователей / сформировать объект класса пользователь и проект
sqlQuery := TADOQuery.Create(nil);
if not currentTypeConnection then
sqlQuery.ConnectionString := sqlConnection_localhost
else
sqlQuery.ConnectionString := sqlConnection_remotehost;
sqlQuery.SQL.Clear;
sqlQuery.SQL.Add('SELECT * FROM ci53070_unionpro.Users;');
try
sqlQuery.Active := True;
except
on e: EADOError do
begin
MessageDlg('Ошибка при загрузке списка пользователей.', mtError,[mbOK], 0);
Exit;
end;
end;
// структура данных users
// 0 - id_users
// 2 - login (имя пользователя)
if length(all_users) <= 0 then
begin
SetLength(all_users, sqlQuery.RecordCount);
for i := 0 to sqlQuery.RecordCount-1 do
begin
all_users[i] := users.Create;
all_users[i].id_user := sqlQuery.Fields[0].AsInteger;
all_users[i].login := sqlQuery.Fields[2].AsString;
sqlQuery.Next;
end;
sqlQuery.Destroy;
end;
end;
end.
|
// AudioSlideParam.pas
{
音频合成的处理参数
}
unit AudioSlideParams;
interface
uses
Windows, DecoderParam, CodecDefine;
type
AudioSlideParam = record
nSampleRate : Integer;
nChannels : Integer;
nBitsPerSample : Integer; // 采样深度,目前仅支持16位
nInterpolation : AUDIO_INTERPOLATION; // 采样率转换插值算法
end;
PAudioSlideParam = ^AudioSlideParam;
VolumEffect = record // 音量特效
bUseEffect : BOOL; // 是否使用特效
dStartTime : Double; // 特效起止时间,单位:秒,以输出时间尺度为为准,有如下关系:
dEndTime : Double; // 0.0 <= dStartTime < dEndTime <= dTimeEnd - dTimeStart
nStartVoulm : Integer; // 开始音量
nEndVoulm : Integer; // 结束音量
nEffectID : Integer; // 过渡算法ID
end;
PVolumEffect = ^VolumEffect;
AudioProcessParam = record // 音频处理参数,注意:nVolum与Start/EndEffect效果有叠加,即若nVolum = 90,
// StartEffect.nStartVoulm = 80,则最终开始音量为 原音量×90%×80% = 原音量×72%
Time : CLIP_TIME; // 时间设置
nVolum : Integer; // 音量,0~200, 100保持原音量
StartEffect : VolumEffect; // 音频开始部分过渡效果(暂不使用)
EndEffect : VolumEffect; // 音频结尾部分过渡效果(暂不使用)
DecMod : DEC_MODEL; // 解码方式
audDecParam : DecParam; // 音频解码参数
end;
PAudioProcessParam = ^AudioProcessParam;
implementation
end. |
unit auth;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
lclproc, ExtCtrls;
type
TMyResAuth=procedure of object;
{ Tfrmauth }
Tfrmauth = class(TForm)
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
FAnimated:integer;
FcheckUsr: byte;
FOnMyResAuth: TMyResAuth;
FresultF: boolean;
function Getlogin: string;
function Getpwd: string;
procedure EnableControl(Enbld:boolean);
const checkuser:array[0..3] of string=('Идет проверка логина и пароля',
'Идет проверка логина и пароля.','Идет проверка логина и пароля..',
'Идет проверка логина и пароля...');
const connuser:array[0..3] of string=('Соединение пользователем',
'Соединение пользователем.','Соединение пользователем..',
'Соединение пользователем...');
const timeconnect:array[0..3] of string=('Соединение с базой',
'Соединение с базой.','Соединение с базой..',
'Соединение с базой...');
{ private declarations }
public
{ public declarations }
procedure ExF(resultF:boolean);
property login:string read Getlogin;
property pwd:string read Getpwd;
property OnMyResAuth:TMyResAuth read FOnMyResAuth write FOnMyResAuth;
property resultF:boolean read FresultF write FresultF default false;
property checkUsr:byte read FcheckUsr write FcheckUsr default 0;
end;
var
frmauth: Tfrmauth;
implementation
//uses main;
{$R *.lfm}
{ Tfrmauth }
procedure Tfrmauth.Edit1Change(Sender: TObject);
begin
button1.Enabled:=(length(trim(edit1.Text))>0)and(length(edit2.Text)>2);
end;
procedure Tfrmauth.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
//CloseAction:=caFree;
end;
procedure Tfrmauth.FormCreate(Sender: TObject);
begin
self.FAnimated:=0;
FresultF:=false;
Edit1.Text:='u02408001';//Полагин
//Edit1.Text:='u02408002';//Батищев
//self.Edit1.Text:='admin027';//Новоршавка
//self.Edit2.Text:='admin027';//Новоршавка
Edit2.Text:='26101979';//Полагин
//Edit2.Text:='13021967';//Батищев
end;
procedure Tfrmauth.FormShow(Sender: TObject);
begin
//self.Button1Click(self.Button1);
end;
procedure Tfrmauth.Timer1Timer(Sender: TObject);
begin
inc(self.FAnimated);
if self.FAnimated=4 then self.FAnimated:=0;
case checkUsr of
0:self.Label4.Caption:=timeconnect[self.FAnimated];
1:self.Label4.Caption:=checkuser[self.FAnimated];
2:self.Label4.Caption:=connuser[self.FAnimated];
end;
end;
function Tfrmauth.Getlogin: string;
begin
result:=edit1.Text;
end;
function Tfrmauth.Getpwd: string;
begin
result:=edit2.Text;
end;
procedure Tfrmauth.EnableControl(Enbld: boolean);
begin
self.Edit1.Enabled:=Enbld;
self.Edit2.Enabled:=Enbld;
self.Button1.Enabled:=Enbld;
self.Button2.Enabled:=Enbld;
end;
procedure Tfrmauth.ExF(resultF: boolean);
begin
self.Timer1.Enabled:=false;
FresultF:=resultF;
close;
end;
procedure Tfrmauth.Button1Click(Sender: TObject);
begin
//mainF.connlogin:=edit1.Text;mainF.connpwd:=edit2.Text;
self.Edit1.Text:=trim(self.Edit1.Text);
self.Edit2.Text:=trim(self.Edit2.Text);
if assigned(OnMyResAuth) then FOnMyResAuth
else
begin
self.ModalResult:=mrCancel;
close;
exit;
end;
EnableControl(false);
self.Timer1.Enabled:=true;
end;
procedure Tfrmauth.Button2Click(Sender: TObject);
begin
FresultF:=false;
end;
end.
|
(*
* Copyright (c) 2010, Ciobanu Alexandru
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
*)
{$I ../Library/src/DeHL.Defines.inc}
unit Tests.Serialization.Gross;
interface
uses SysUtils,
Types,
DateUtils,
Math,
ComObj,
Classes,
XmlIntf,
XmlDoc,
IniFiles,
Tests.Utils,
TestFramework,
DeHL.Box,
DeHL.Tuples,
DeHL.Strings,
DeHL.Arrays,
DeHL.Cloning,
DeHL.WideCharSet,
DeHL.Nullable,
DeHL.Bytes,
DeHL.DateTime,
DeHL.Base,
DeHL.Math.BigCardinal,
DeHL.Math.BigInteger,
DeHL.Math.BigDecimal,
DeHL.Types,
DeHL.Exceptions,
DeHL.Collections.List,
DeHL.Collections.SortedList,
DeHL.Collections.Dictionary,
DeHl.Collections.DoubleSortedBidiMap,
DeHL.Serialization,
DeHL.Serialization.Ini,
DeHL.Serialization.Binary,
DeHL.Serialization.XML;
type
TTestGrossSerialization = class(TDeHLTestCase)
private
class function SerializeInXML<T>(const AValue: T): T; static;
class function SerializeInIni<T>(const AValue: T): T; static;
class function SerializeInBinary<T>(const AValue: T): T; static;
published
procedure Test_Simple;
procedure Test_Integers;
procedure Test_Floats;
procedure Test_Strings;
procedure Test_Booleans;
procedure Test_Arrays;
procedure Test_DTs;
procedure Test_EnumsAndSets;
procedure Test_ClassSelfRef;
procedure Test_RecordSelfRef;
procedure Test_ClassComplicated;
procedure Test_ClassSameFields;
procedure Test_Bad_Serialized;
procedure Test_NonSerializable;
procedure Test_CustomISerializable;
procedure Test_BigCardinal;
procedure Test_BigInteger;
procedure Test_BigDecimal;
procedure Test_Date;
procedure Test_Metaclass;
procedure Test_DateTime;
procedure Test_Time;
procedure Test_Box;
procedure Test_KVP;
procedure Test_Tuple_1;
procedure Test_Tuple_2;
procedure Test_Tuple_3;
procedure Test_Tuple_4;
procedure Test_Tuple_5;
procedure Test_Tuple_6;
procedure Test_Tuple_7;
procedure Test_Nullable;
procedure Test_WideCharSet;
procedure Test_FixedArray;
procedure Test_DynamicArray;
procedure Test_Buffer;
procedure Test_Bug0;
end;
type
TTestEnexSerialization = class(TDeHLTestCase)
published
procedure Test_List;
procedure Test_SortedList;
procedure Test_Dictionary;
procedure Test_DoubleSortedBidiMap;
end;
type
{ Exception for fiedl tests }
EFieldFailError = class(Exception)
constructor Create(const AFieldName, AExp, AActual: String);
end;
{ Integers record }
type
TIntsRecord = record
private
FByte_Zero, FByte_Lo, FByte_Hi: Byte;
FShortInt_Zero, FShortInt_Lo, FShortInt_Hi: ShortInt;
FWord_Zero, FWord_Lo, FWord_Hi: Word;
FSmallInt_Zero, FSmallInt_Lo, FSmallInt_Hi: SmallInt;
FCardinal_Zero, FCardinal_Lo, FCardinal_Hi: Cardinal;
FInteger_Zero, FInteger_Lo, FInteger_Hi: Integer;
FUInt64_Zero, FUInt64_Lo, FUInt64_Hi: UInt64;
FInt64_Zero, FInt64_Lo, FInt64_Hi: Int64;
public
class function Create(): TIntsRecord; static;
procedure CompareTo(const AOther: TIntsRecord);
end;
{ Floats record }
type
TFloatsRecord = record
private
FHalf_Zero, FHalf_Lo, FHalf_Hi: Single;
FSingle_Zero, FSingle_Lo, FSingle_Hi: Single;
FDouble_Zero, FDouble_Lo, FDouble_Hi: Double;
FExtended_Zero, FExtended_Lo, FExtended_Hi: Extended;
FCurrency_Zero, FCurrency_Lo, FCurrency_Hi: Currency;
FComp_Zero, FComp_Lo, FComp_Hi: Comp;
public
class function Create(): TFloatsRecord; static;
procedure CompareTo(const AOther: TFloatsRecord);
end;
{ Strings record }
type
TStringsRecord = record
private
FShortString_Empty, FShortString_One, FShortString_Long: ShortString;
FUnicodeString_Empty, FUnicodeString_One, FUnicodeString_Long: UnicodeString;
FAnsiString_Empty, FAnsiString_One, FAnsiString_Long: AnsiString;
FWideString_Empty, FWideString_One, FWideString_Long: WideString;
FUcs4String_Empty, FUcs4String_One, FUcs4String_Long: UCS4String;
FRawByteString_Empty, FRawByteString_One, FRawByteString_Long: RawByteString;
FAnsiChar_Zero, FAnsiChar_Lo, FAnsiChar_Hi: AnsiChar;
FWideChar_Zero, FWideChar_Lo, FWideChar_Hi: WideChar;
FUcs4Char_Zero, FUcs4Char_Lo, FUcs4Char_Hi: UCS4Char;
FTString_Empty, FTString_One, FTString_Long: TString;
public
class function Create(): TStringsRecord; static;
procedure CompareTo(const AOther: TStringsRecord);
end;
{ Boolean record }
type
TBooleanRecord = record
private
FBoolean_True, FBoolean_False: Boolean;
FByteBool_True, FByteBool_False: ByteBool;
FWordBool_True, FWordBool_False: WordBool;
FLongBool_True, FLongBool_False: LongBool;
public
class function Create(): TBooleanRecord; static;
procedure CompareTo(const AOther: TBooleanRecord);
end;
{ Arrays record }
type
TOneStrArray = array[0..0] of String;
TOneIntArray = array[0..0] of Integer;
TThreeStrArray = array[1..3] of String;
TThreeIntArray = array[1..3] of Integer;
TTwoStrArray = array[0..0, 0..0] of String;
TTwoIntArray = array[0..0, 0..0] of Integer;
TFourStrArray = array[1..2, 0..1] of String;
TFourIntArray = array[1..2, 0..1] of Integer;
TArraysRecord = record
private
{ Dynamic arrays }
FDynArrayStr_Empty, FDynArrayStr_One, FDynArrayStr_Many: TArray<String>;
FDynArrayInt_Empty, FDynArrayInt_One, FDynArrayInt_Many: TIntegerDynArray;
{ One dimensional arrays }
FOneDimArrayStr_One: TOneStrArray;
FOneDimArrayStr_Three: TThreeStrArray;
FOneDimArrayInt_One: TOneIntArray;
FOneDimArrayInt_Three: TThreeIntArray;
{ Two dim arrays }
FTwoDimArrayStr_Two: TTwoStrArray;
FTwoDimArrayStr_Four: TFourStrArray;
FTwoDimArrayInt_Two: TTwoIntArray;
FTwoDimArrayInt_Four: TFourIntArray;
public
class function Create(): TArraysRecord; static;
procedure CompareTo(const AOther: TArraysRecord);
end;
{ Date-time record }
type
TDateTimeRecord = record
private
FDateTime_Zero, FDateTime_Now: System.TDateTime;
FTime_Zero, FTime_Now: System.TTime;
FDate_Zero, FDate_Now: System.TDate;
public
class function Create(): TDateTimeRecord; static;
procedure CompareTo(const AOther: TDateTimeRecord);
end;
{ Enums and sets }
type
TSomeEnum = (someOne, someTwo, someThree);
TSomeSet = set of TSomeEnum;
TEnumSetRecord = record
private
FEnum_One, FEnum_Two: TSomeEnum;
FSet_Empty, FSet_One, FSet_All: TSomeSet;
public
class function Create(): TEnumSetRecord; static;
procedure CompareTo(const AOther: TEnumSetRecord);
end;
{ Check for a chained class }
type
TChainedClass = class
public
FSelf: TObject;
FNil: TObject;
public
constructor Create();
end;
{ Records by ref test }
type
PLinkedItem = ^TLinkedItem;
TLinkedItem = record
FData: String;
[CloneKind(ckDeep)]
FSelf, FNil: PLinkedItem;
end;
{ Class with array of different subclasses }
type
TContainer = class
public type
TOne = class
FOneField: String;
constructor Create;
procedure Test;
end;
TTwo = class(TOne)
FTwoField: Cardinal;
constructor Create;
procedure Test;
end;
TThree = class
// no fields
end;
private
[CloneKind(ckDeep)]
FArray: array of TObject;
public
constructor Create(const CreateSubs: Boolean);
destructor Destroy(); override;
procedure Test(const WithSubs: Boolean);
end;
{ Non-serialized and non-serializable check }
type
TBadSerRecord = record
P: Pointer;
S: String;
end;
TBadSerRecord_NonSer = record
[NonSerialized]
P: Pointer;
S: String;
end;
{ Class with custom ser. handler }
type
TSpecialKukuClass = class(TRefCountedObject, ISerializable, IDeserializationCallback)
public
FSequence: String;
public
constructor Create();
{ Implementoooors }
procedure Serialize(const AData: TSerializationData);
procedure Deserialize(const AData: TDeserializationData);
procedure Deserialized(const AData: TDeserializationData);
end;
{ Test interitance with same field names }
type
TInhBase = class
private
FField: String;
public
procedure Test; virtual;
constructor Create();
end;
TInhDerived = class(TInhBase)
private
FField: String;
public
procedure Test; override;
constructor Create();
end;
TInhDerived2 = class(TInhDerived)
private
FField: String;
public
procedure Test; override;
constructor Create();
end;
implementation
{ TFieldFailError }
constructor EFieldFailError.Create(const AFieldName, AExp, AActual: String);
begin
inherited CreateFmt('Field [%s]. Expected = "%s" but actual was "%s".', [AFieldName, AExp, AActual]);
end;
{ TIntsRecord }
procedure TIntsRecord.CompareTo(const AOther: TIntsRecord);
begin
if FByte_Zero <> AOther.FByte_Zero then
raise EFieldFailError.Create('FByte_Zero', UIntToStr(FByte_Zero), UIntToStr(AOther.FByte_Zero));
if FByte_Lo <> AOther.FByte_Lo then
raise EFieldFailError.Create('FByte_Lo', UIntToStr(FByte_Lo), UIntToStr(AOther.FByte_Lo));
if FByte_Hi <> AOther.FByte_Hi then
raise EFieldFailError.Create('FByte_Hi', UIntToStr(FByte_Hi), UIntToStr(AOther.FByte_Hi));
if FShortInt_Zero <> AOther.FShortInt_Zero then
raise EFieldFailError.Create('FShortInt_Zero', IntToStr(FShortInt_Zero), IntToStr(AOther.FShortInt_Zero));
if FShortInt_Lo <> AOther.FShortInt_Lo then
raise EFieldFailError.Create('FShortInt_Lo', IntToStr(FShortInt_Lo), IntToStr(AOther.FShortInt_Lo));
if FShortInt_Hi <> AOther.FShortInt_Hi then
raise EFieldFailError.Create('FShortInt_Hi', IntToStr(FShortInt_Hi), IntToStr(AOther.FShortInt_Hi));
if FWord_Zero <> AOther.FWord_Zero then
raise EFieldFailError.Create('FWord_Zero', UIntToStr(FWord_Zero), UIntToStr(AOther.FWord_Zero));
if FWord_Lo <> AOther.FWord_Lo then
raise EFieldFailError.Create('FWord_Lo', UIntToStr(FWord_Lo), UIntToStr(AOther.FWord_Lo));
if FWord_Hi <> AOther.FWord_Hi then
raise EFieldFailError.Create('FWord_Hi', UIntToStr(FWord_Hi), UIntToStr(AOther.FWord_Hi));
if FSmallInt_Zero <> AOther.FSmallInt_Zero then
raise EFieldFailError.Create('FSmallInt_Zero', IntToStr(FSmallInt_Zero), IntToStr(AOther.FSmallInt_Zero));
if FSmallInt_Lo <> AOther.FSmallInt_Lo then
raise EFieldFailError.Create('FSmallInt_Lo', IntToStr(FSmallInt_Lo), IntToStr(AOther.FSmallInt_Lo));
if FSmallInt_Hi <> AOther.FSmallInt_Hi then
raise EFieldFailError.Create('FSmallInt_Hi', IntToStr(FSmallInt_Hi), IntToStr(AOther.FSmallInt_Hi));
if FCardinal_Zero <> AOther.FCardinal_Zero then
raise EFieldFailError.Create('FCardinal_Zero', UIntToStr(FCardinal_Zero), UIntToStr(AOther.FCardinal_Zero));
if FCardinal_Lo <> AOther.FCardinal_Lo then
raise EFieldFailError.Create('FCardinal_Lo', UIntToStr(FCardinal_Lo), UIntToStr(AOther.FCardinal_Lo));
if FCardinal_Hi <> AOther.FCardinal_Hi then
raise EFieldFailError.Create('FCardinal_Hi', UIntToStr(FCardinal_Hi), UIntToStr(AOther.FCardinal_Hi));
if FInteger_Zero <> AOther.FInteger_Zero then
raise EFieldFailError.Create('FInteger_Zero', IntToStr(FInteger_Zero), IntToStr(AOther.FInteger_Zero));
if FInteger_Lo <> AOther.FInteger_Lo then
raise EFieldFailError.Create('FInteger_Lo', IntToStr(FInteger_Lo), IntToStr(AOther.FInteger_Lo));
if FInteger_Hi <> AOther.FInteger_Hi then
raise EFieldFailError.Create('FInteger_Hi', IntToStr(FInteger_Hi), IntToStr(AOther.FInteger_Hi));
if FUInt64_Zero <> AOther.FUInt64_Zero then
raise EFieldFailError.Create('FUInt64_Zero', UIntToStr(FUInt64_Zero), UIntToStr(AOther.FUInt64_Zero));
if FUInt64_Lo <> AOther.FUInt64_Lo then
raise EFieldFailError.Create('FUInt64_Lo', UIntToStr(FUInt64_Lo), UIntToStr(AOther.FUInt64_Lo));
if FUInt64_Hi <> AOther.FUInt64_Hi then
raise EFieldFailError.Create('FUInt64_Hi', UIntToStr(FUInt64_Hi), UIntToStr(AOther.FUInt64_Hi));
if FInt64_Zero <> AOther.FInt64_Zero then
raise EFieldFailError.Create('FInt64_Zero', IntToStr(FInt64_Zero), IntToStr(AOther.FInt64_Zero));
if FInt64_Lo <> AOther.FInt64_Lo then
raise EFieldFailError.Create('FInt64_Lo', IntToStr(FInt64_Lo), IntToStr(AOther.FInt64_Lo));
if FInt64_Hi <> AOther.FInt64_Hi then
raise EFieldFailError.Create('FInt64_Hi', IntToStr(FInt64_Hi), IntToStr(AOther.FInt64_Hi));
end;
class function TIntsRecord.Create: TIntsRecord;
begin
Result.FByte_Zero := 0;
Result.FByte_Lo := Low(Byte);
Result.FByte_Hi := High(Byte);
Result.FShortInt_Zero := 0;
Result.FShortInt_Lo := Low(ShortInt);
Result.FShortInt_Hi := High(ShortInt);
Result.FWord_Zero := 0;
Result.FWord_Lo := Low(Word);
Result.FWord_Hi := High(Word);
Result.FSmallInt_Zero := 0;
Result.FSmallInt_Lo := Low(SmallInt);
Result.FSmallInt_Hi := High(SmallInt);
Result.FCardinal_Zero := 0;
Result.FCardinal_Lo := Low(Cardinal);
Result.FCardinal_Hi := High(Cardinal);
Result.FInteger_Zero := 0;
Result.FInteger_Lo := Low(Integer);
Result.FInteger_Hi := High(Integer);
Result.FUInt64_Zero := 0;
Result.FUInt64_Lo := Low(UInt64);
Result.FUInt64_Hi := High(UInt64);
Result.FInt64_Zero := 0;
Result.FInt64_Lo := Low(Int64);
Result.FInt64_Hi := High(Int64);
end;
{ TFloatsRecord }
procedure TFloatsRecord.CompareTo(const AOther: TFloatsRecord);
begin
if FHalf_Zero <> AOther.FHalf_Zero then
raise EFieldFailError.Create('FHalf_Zero', FloatToStr(FHalf_Zero), FloatToStr(AOther.FHalf_Zero));
if FHalf_Lo <> AOther.FHalf_Lo then
raise EFieldFailError.Create('FHalf_Lo', FloatToStr(FHalf_Lo), FloatToStr(AOther.FHalf_Lo));
if FHalf_Hi <> AOther.FHalf_Hi then
raise EFieldFailError.Create('FHalf_Hi', FloatToStr(FHalf_Hi), FloatToStr(AOther.FHalf_Hi));
if FSingle_Zero <> AOther.FSingle_Zero then
raise EFieldFailError.Create('FSingle_Zero', FloatToStr(FSingle_Zero), FloatToStr(AOther.FSingle_Zero));
if FSingle_Lo <> AOther.FSingle_Lo then
raise EFieldFailError.Create('FSingle_Lo', FloatToStr(FSingle_Lo), FloatToStr(AOther.FSingle_Lo));
if FSingle_Hi <> AOther.FSingle_Hi then
raise EFieldFailError.Create('FSingle_Hi', FloatToStr(FSingle_Hi), FloatToStr(AOther.FSingle_Hi));
if FDouble_Zero <> AOther.FDouble_Zero then
raise EFieldFailError.Create('FDouble_Zero', FloatToStr(FDouble_Zero), FloatToStr(AOther.FDouble_Zero));
if FDouble_Lo <> AOther.FDouble_Lo then
raise EFieldFailError.Create('FDouble_Lo', FloatToStr(FDouble_Lo), FloatToStr(AOther.FDouble_Lo));
if FDouble_Hi <> AOther.FDouble_Hi then
raise EFieldFailError.Create('FDouble_Hi', FloatToStr(FDouble_Hi), FloatToStr(AOther.FDouble_Hi));
if FExtended_Zero <> AOther.FExtended_Zero then
raise EFieldFailError.Create('FExtended_Zero', FloatToStr(FExtended_Zero), FloatToStr(AOther.FExtended_Zero));
if FExtended_Lo <> AOther.FExtended_Lo then
raise EFieldFailError.Create('FExtended_Lo', FloatToStr(FExtended_Lo), FloatToStr(AOther.FExtended_Lo));
if FExtended_Hi <> AOther.FExtended_Hi then
raise EFieldFailError.Create('FExtended_Hi', FloatToStr(FExtended_Hi), FloatToStr(AOther.FExtended_Hi));
if FCurrency_Zero <> AOther.FCurrency_Zero then
raise EFieldFailError.Create('FCurrency_Zero', FloatToStr(FCurrency_Zero), FloatToStr(AOther.FCurrency_Zero));
if FCurrency_Lo <> AOther.FCurrency_Lo then
raise EFieldFailError.Create('FCurrency_Lo', FloatToStr(FCurrency_Lo), FloatToStr(AOther.FCurrency_Lo));
if FCurrency_Hi <> AOther.FCurrency_Hi then
raise EFieldFailError.Create('FCurrency_Hi', FloatToStr(FCurrency_Hi), FloatToStr(AOther.FCurrency_Hi));
if FComp_Zero <> AOther.FComp_Zero then
raise EFieldFailError.Create('FComp_Zero', FloatToStr(FComp_Zero), FloatToStr(AOther.FComp_Zero));
if FComp_Lo <> AOther.FComp_Lo then
raise EFieldFailError.Create('FComp_Lo', FloatToStr(FComp_Lo), FloatToStr(AOther.FComp_Lo));
if FComp_Hi <> AOther.FComp_Hi then
raise EFieldFailError.Create('FComp_Hi', FloatToStr(FComp_Hi), FloatToStr(AOther.FComp_Hi));
end;
class function TFloatsRecord.Create: TFloatsRecord;
begin
Result.FSingle_Zero := 0;
Result.FSingle_Lo := -1000.7878;
Result.FSingle_Hi := 10000.733;
Result.FHalf_Zero := 0;
Result.FHalf_Lo := -1000.7878;
Result.FHalf_Hi := 10000.733;
Result.FDouble_Zero := 0;
Result.FDouble_Lo := MinSingle - 100;
Result.FDouble_Hi := MaxSingle + 100;
Result.FExtended_Zero := 0;
Result.FExtended_Lo := MinDouble - 100;
Result.FExtended_Hi := MaxDouble + 100;
Result.FCurrency_Zero := 0;
Result.FCurrency_Lo := -289892.3232;
Result.FCurrency_Hi := 37889881.32322;
Result.FComp_Zero := 0;
Result.FComp_Lo := -2789788728;
Result.FComp_Hi := 2121212121;
end;
{ TStringsRecord }
procedure TStringsRecord.CompareTo(const AOther: TStringsRecord);
begin
if FShortString_Empty <> AOther.FShortString_Empty then
raise EFieldFailError.Create('FShortString_Empty', string(FShortString_Empty), string(AOther.FShortString_Empty));
if FShortString_One <> AOther.FShortString_One then
raise EFieldFailError.Create('FShortString_One', string(FShortString_One), string(AOther.FShortString_One));
if FShortString_Long <> AOther.FShortString_Long then
raise EFieldFailError.Create('FShortString_Long', string(FShortString_Long), string(AOther.FShortString_Long));
if FUnicodeString_Empty <> AOther.FUnicodeString_Empty then
raise EFieldFailError.Create('FUnicodeString_Empty', FUnicodeString_Empty, AOther.FUnicodeString_Empty);
if FUnicodeString_One <> AOther.FUnicodeString_One then
raise EFieldFailError.Create('FUnicodeString_One', FUnicodeString_One, AOther.FUnicodeString_One);
if FUnicodeString_Long <> AOther.FUnicodeString_Long then
raise EFieldFailError.Create('FUnicodeString_Long', FUnicodeString_Long, AOther.FUnicodeString_Long);
if FAnsiString_Empty <> AOther.FAnsiString_Empty then
raise EFieldFailError.Create('FAnsiString_Empty', string(FAnsiString_Empty), string(AOther.FAnsiString_Empty));
if FAnsiString_One <> AOther.FAnsiString_One then
raise EFieldFailError.Create('FAnsiString_One', string(FAnsiString_One), string(AOther.FAnsiString_One));
if FAnsiString_Long <> AOther.FAnsiString_Long then
raise EFieldFailError.Create('FAnsiString_Long', string(FAnsiString_Long), string(AOther.FAnsiString_Long));
if FWideString_Empty <> AOther.FWideString_Empty then
raise EFieldFailError.Create('FWideString_Empty', FWideString_Empty, AOther.FWideString_Empty);
if FWideString_One <> AOther.FWideString_One then
raise EFieldFailError.Create('FWideString_One', FWideString_One, AOther.FWideString_One);
if FWideString_Long <> AOther.FWideString_Long then
raise EFieldFailError.Create('FWideString_Long', FWideString_Long, AOther.FWideString_Long);
if FTString_Empty <> AOther.FTString_Empty then
raise EFieldFailError.Create('FTString_Empty', FTString_Empty, AOther.FTString_Empty);
if FTString_One <> AOther.FTString_One then
raise EFieldFailError.Create('FTString_One', FTString_One, AOther.FTString_One);
if FTString_Long <> AOther.FTString_Long then
raise EFieldFailError.Create('FTString_Long', FTString_Long, AOther.FTString_Long);
if FRawByteString_Empty <> AOther.FRawByteString_Empty then
raise EFieldFailError.Create('FRawByteString_Empty', FRawByteString_Empty, AOther.FRawByteString_Empty);
if FRawByteString_One <> AOther.FRawByteString_One then
raise EFieldFailError.Create('FRawByteString_One', FRawByteString_One, AOther.FRawByteString_One);
if FRawByteString_Long <> AOther.FRawByteString_Long then
raise EFieldFailError.Create('FRawByteString_Long', FRawByteString_Long, AOther.FRawByteString_Long);
if UCS4StringToWideString(FUcs4String_Empty) <> UCS4StringToWideString(AOther.FUcs4String_Empty) then
raise EFieldFailError.Create('FUcs4String_Empty', UCS4StringToWideString(FUcs4String_Empty), UCS4StringToWideString(AOther.FUcs4String_Empty));
if UCS4StringToWideString(FUcs4String_One) <> UCS4StringToWideString(AOther.FUcs4String_One) then
raise EFieldFailError.Create('FUcs4String_One', UCS4StringToWideString(FUcs4String_One), UCS4StringToWideString(AOther.FUcs4String_One));
if UCS4StringToWideString(FUcs4String_Long) <> UCS4StringToWideString(AOther.FUcs4String_Long) then
raise EFieldFailError.Create('FUcs4String_Long', UCS4StringToWideString(FUcs4String_Long), UCS4StringToWideString(AOther.FUcs4String_Long));
if FAnsiChar_Zero <> AOther.FAnsiChar_Zero then
raise EFieldFailError.Create('FAnsiChar_Zero', string(FAnsiChar_Zero), string(AOther.FAnsiChar_Zero));
if FAnsiChar_Lo <> AOther.FAnsiChar_Lo then
raise EFieldFailError.Create('FAnsiChar_Lo', string(FAnsiChar_Lo), string(AOther.FAnsiChar_Lo));
if FAnsiChar_Hi <> AOther.FAnsiChar_Hi then
raise EFieldFailError.Create('FAnsiChar_Hi', string(FAnsiChar_Hi), string(AOther.FAnsiChar_Hi));
if FWideChar_Zero <> AOther.FWideChar_Zero then
raise EFieldFailError.Create('FWideChar_Zero', FWideChar_Zero, AOther.FWideChar_Zero);
if FWideChar_Lo <> AOther.FWideChar_Lo then
raise EFieldFailError.Create('FWideChar_Lo', FWideChar_Lo, AOther.FWideChar_Lo);
if FWideChar_Hi <> AOther.FWideChar_Hi then
raise EFieldFailError.Create('FWideChar_Hi', FWideChar_Hi, AOther.FWideChar_Hi);
if FUcs4Char_Zero <> AOther.FUcs4Char_Zero then
raise EFieldFailError.Create('FUcs4Char_Zero', IntToStr(FUcs4Char_Zero), IntToStr(AOther.FUcs4Char_Zero));
if FUcs4Char_Lo <> AOther.FUcs4Char_Lo then
raise EFieldFailError.Create('FUcs4Char_Lo', IntToStr(FUcs4Char_Lo), IntToStr(AOther.FUcs4Char_Lo));
if FUcs4Char_Hi <> AOther.FUcs4Char_Hi then
raise EFieldFailError.Create('FUcs4Char_Hi', IntToStr(FUcs4Char_Hi), IntToStr(AOther.FUcs4Char_Hi));
end;
class function TStringsRecord.Create: TStringsRecord;
begin
Result.FShortString_Empty := '';
Result.FShortString_One := '1';
Result.FShortString_Long := 'Testing Serialization!';
Result.FUnicodeString_Empty := '';
Result.FUnicodeString_One := '2';
Result.FUnicodeString_Long := 'тестинг сериализэйшан!';
Result.FAnsiString_Empty := '';
Result.FAnsiString_One := '3';
Result.FAnsiString_Long := 'Ansi Testing Serialization!';
Result.FWideString_Empty := '';
Result.FWideString_One := '4';
Result.FWideString_Long := 'Re-тестинг сериализэйшан!';
Result.FTString_Empty := '';
Result.FTString_One := '4';
Result.FTString_Long := 'Re-тестинг сериализэйшан!';
Result.FUcs4String_Empty := WideStringToUCS4String('');
Result.FUcs4String_One := WideStringToUCS4String('4');
Result.FUcs4String_Long := WideStringToUCS4String('Re-тестинг сериализэйшан!');
Result.FRawByteString_Empty := '';
Result.FRawByteString_One := '4';
Result.FRawByteString_Long := 'A block of data';
Result.FAnsiChar_Zero := #9;
Result.FAnsiChar_Lo := ' ';
Result.FAnsiChar_Hi := 'z';
Result.FWideChar_Zero := #9;
Result.FWideChar_Lo := ' ';
Result.FWideChar_Hi := #$FF00;
Result.FUcs4Char_Zero := 9;
Result.FUcs4Char_Lo := 32;
Result.FUcs4Char_Hi := $FF00;
end;
{ TBooleanRecord }
procedure TBooleanRecord.CompareTo(const AOther: TBooleanRecord);
begin
if FBoolean_True <> AOther.FBoolean_True then
raise EFieldFailError.Create('FBoolean_True', BoolToStr(FBoolean_True), BoolToStr(AOther.FBoolean_True));
if FBoolean_False <> AOther.FBoolean_False then
raise EFieldFailError.Create('FBoolean_False', BoolToStr(FBoolean_False), BoolToStr(AOther.FBoolean_False));
if FByteBool_True <> AOther.FByteBool_True then
raise EFieldFailError.Create('FByteBool_True', BoolToStr(FByteBool_True), BoolToStr(AOther.FByteBool_True));
if FByteBool_False <> AOther.FByteBool_False then
raise EFieldFailError.Create('FByteBool_False', BoolToStr(FByteBool_False), BoolToStr(AOther.FByteBool_False));
if FWordBool_True <> AOther.FWordBool_True then
raise EFieldFailError.Create('FWordBool_True', BoolToStr(FWordBool_True), BoolToStr(AOther.FWordBool_True));
if FWordBool_False <> AOther.FWordBool_False then
raise EFieldFailError.Create('FWordBool_False', BoolToStr(FWordBool_False), BoolToStr(AOther.FWordBool_False));
if FLongBool_True <> AOther.FLongBool_True then
raise EFieldFailError.Create('FLongBool_True', BoolToStr(FLongBool_True), BoolToStr(AOther.FLongBool_True));
if FLongBool_False <> AOther.FLongBool_False then
raise EFieldFailError.Create('FLongBool_False', BoolToStr(FLongBool_False), BoolToStr(AOther.FLongBool_False));
end;
class function TBooleanRecord.Create: TBooleanRecord;
begin
Result.FBoolean_True := true;
Result.FBoolean_False := false;
Result.FByteBool_True := true;
Result.FByteBool_False := false;
Result.FWordBool_True := true;
Result.FWordBool_False := false;
Result.FLongBool_True := true;
Result.FLongBool_False := false;
end;
{ TArraysRecord }
procedure TArraysRecord.CompareTo(const AOther: TArraysRecord);
var
I: Integer;
begin
if Length(FDynArrayStr_Empty) <> Length(AOther.FDynArrayStr_Empty) then
raise EFieldFailError.Create('(len) FDynArrayStr_Empty', '...', '...');
if Length(FDynArrayStr_One) <> Length(AOther.FDynArrayStr_One) then
raise EFieldFailError.Create('(len) FDynArrayStr_One', '...', '...')
else
begin
for I := 0 to Length(FDynArrayStr_One) - 1 do
if FDynArrayStr_One[I] <> AOther.FDynArrayStr_One[I] then
raise EFieldFailError.Create('(' + IntToStr(I) + ') FDynArrayStr_One', '...', '...');
end;
if Length(FDynArrayStr_Many) <> Length(AOther.FDynArrayStr_Many) then
raise EFieldFailError.Create('(len) FDynArrayStr_Many', '...', '...')
else
begin
for I := 0 to Length(FDynArrayStr_Many) - 1 do
if FDynArrayStr_Many[I] <> AOther.FDynArrayStr_Many[I] then
raise EFieldFailError.Create('(' + IntToStr(I) + ') FDynArrayStr_Many', '...', '...');
end;
if Length(FDynArrayInt_Empty) <> Length(AOther.FDynArrayInt_Empty) then
raise EFieldFailError.Create('(len) FDynArrayInt_Empty', '...', '...');
if Length(FDynArrayInt_One) <> Length(AOther.FDynArrayInt_One) then
raise EFieldFailError.Create('(len) FDynArrayInt_One', '...', '...')
else
begin
for I := 0 to Length(FDynArrayInt_One) - 1 do
if FDynArrayInt_One[I] <> AOther.FDynArrayInt_One[I] then
raise EFieldFailError.Create('(' + IntToStr(I) + ') FDynArrayInt_One', '...', '...');
end;
if Length(FDynArrayInt_Many) <> Length(AOther.FDynArrayInt_Many) then
raise EFieldFailError.Create('(len) FDynArrayInt_Many', '...', '...')
else
begin
for I := 0 to Length(FDynArrayInt_Many) - 1 do
if FDynArrayInt_Many[I] <> AOther.FDynArrayInt_Many[I] then
raise EFieldFailError.Create('(' + IntToStr(I) + ') FDynArrayInt_Many', '...', '...');
end;
if FOneDimArrayStr_One[0] <> AOther.FOneDimArrayStr_One[0] then
raise EFieldFailError.Create('FOneDimArrayStr_One', FOneDimArrayStr_One[0], AOther.FOneDimArrayStr_One[0]);
if FOneDimArrayInt_One[0] <> AOther.FOneDimArrayInt_One[0] then
raise EFieldFailError.Create('FOneDimArrayInt_One', IntToStr(FOneDimArrayInt_One[0]), IntToStr(AOther.FOneDimArrayInt_One[0]));
if FOneDimArrayStr_Three[1] <> AOther.FOneDimArrayStr_Three[1] then
raise EFieldFailError.Create('FOneDimArrayStr_Three[1]', FOneDimArrayStr_Three[1], AOther.FOneDimArrayStr_Three[1]);
if FOneDimArrayStr_Three[2] <> AOther.FOneDimArrayStr_Three[2] then
raise EFieldFailError.Create('FOneDimArrayStr_Three[2]', FOneDimArrayStr_Three[2], AOther.FOneDimArrayStr_Three[2]);
if FOneDimArrayStr_Three[3] <> AOther.FOneDimArrayStr_Three[3] then
raise EFieldFailError.Create('FOneDimArrayStr_Three[3]', FOneDimArrayStr_Three[3], AOther.FOneDimArrayStr_Three[3]);
if FOneDimArrayInt_Three[1] <> AOther.FOneDimArrayInt_Three[1] then
raise EFieldFailError.Create('FOneDimArrayInt_Three[1]', IntToStr(FOneDimArrayInt_Three[1]), IntToStr(AOther.FOneDimArrayInt_Three[1]));
if FOneDimArrayInt_Three[2] <> AOther.FOneDimArrayInt_Three[2] then
raise EFieldFailError.Create('FOneDimArrayStr_Three[2]', IntToStr(FOneDimArrayInt_Three[2]), IntToStr(AOther.FOneDimArrayInt_Three[2]));
if FOneDimArrayInt_Three[3] <> AOther.FOneDimArrayInt_Three[3] then
raise EFieldFailError.Create('FOneDimArrayStr_Three[3]', IntToStr(FOneDimArrayInt_Three[3]), IntToStr(AOther.FOneDimArrayInt_Three[3]));
if FTwoDimArrayStr_Two[0, 0] <> AOther.FTwoDimArrayStr_Two[0, 0] then
raise EFieldFailError.Create('FTwoDimArrayStr_Two', FTwoDimArrayStr_Two[0, 0], AOther.FTwoDimArrayStr_Two[0, 0]);
if FTwoDimArrayInt_Two[0, 0] <> AOther.FTwoDimArrayInt_Two[0, 0] then
raise EFieldFailError.Create('FTwoDimArrayInt_Two', IntToStr(FTwoDimArrayInt_Two[0, 0]), IntToStr(AOther.FTwoDimArrayInt_Two[0, 0]));
if FTwoDimArrayStr_Four[1, 0] <> AOther.FTwoDimArrayStr_Four[1, 0] then
raise EFieldFailError.Create('FTwoDimArrayStr_Four[1, 0]', FTwoDimArrayStr_Four[1, 0], AOther.FTwoDimArrayStr_Four[1, 0]);
if FTwoDimArrayStr_Four[1, 1] <> AOther.FTwoDimArrayStr_Four[1, 1] then
raise EFieldFailError.Create('FTwoDimArrayStr_Four[1, 1]', FTwoDimArrayStr_Four[1, 1], AOther.FTwoDimArrayStr_Four[1, 1]);
if FTwoDimArrayStr_Four[2, 0] <> AOther.FTwoDimArrayStr_Four[2, 0] then
raise EFieldFailError.Create('FTwoDimArrayStr_Four[2, 0]', FTwoDimArrayStr_Four[2, 0], AOther.FTwoDimArrayStr_Four[2, 0]);
if FTwoDimArrayStr_Four[2, 1] <> AOther.FTwoDimArrayStr_Four[2, 1] then
raise EFieldFailError.Create('FTwoDimArrayStr_Four[2, 1]', FTwoDimArrayStr_Four[2, 1], AOther.FTwoDimArrayStr_Four[2, 1]);
if FTwoDimArrayInt_Four[1, 0] <> AOther.FTwoDimArrayInt_Four[1, 0] then
raise EFieldFailError.Create('FOneDimArrayInt_Three[1, 0]', IntToStr(FTwoDimArrayInt_Four[1, 0]), IntToStr(AOther.FTwoDimArrayInt_Four[1, 0]));
if FTwoDimArrayInt_Four[1, 1] <> AOther.FTwoDimArrayInt_Four[1, 1] then
raise EFieldFailError.Create('FOneDimArrayStr_Three[1, 1]', IntToStr(FTwoDimArrayInt_Four[1, 1]), IntToStr(AOther.FTwoDimArrayInt_Four[1, 1]));
if FTwoDimArrayInt_Four[2, 0] <> AOther.FTwoDimArrayInt_Four[2, 0] then
raise EFieldFailError.Create('FOneDimArrayStr_Three[2, 0]', IntToStr(FTwoDimArrayInt_Four[2, 0]), IntToStr(AOther.FTwoDimArrayInt_Four[2, 0]));
if FTwoDimArrayInt_Four[2, 1] <> AOther.FTwoDimArrayInt_Four[2, 1] then
raise EFieldFailError.Create('FOneDimArrayStr_Three[2, 1]', IntToStr(FTwoDimArrayInt_Four[2, 1]), IntToStr(AOther.FTwoDimArrayInt_Four[2, 1]));
end;
class function TArraysRecord.Create: TArraysRecord;
begin
{ Dynamic arrays }
SetLength(Result.FDynArrayStr_Empty, 0);
Result.FDynArrayStr_One := TArray<String>.Create('A lovely string');
Result.FDynArrayStr_Many := TArray<String>.Create('One', 'More', 'String');
SetLength(Result.FDynArrayInt_Empty, 0);
Result.FDynArrayInt_One := TIntegerDynArray.Create(1);
Result.FDynArrayInt_Many := TIntegerDynArray.Create(10, 9, 8);
{ One dimensional arrays }
Result.FOneDimArrayStr_One[0] := '(0)';
Result.FOneDimArrayStr_Three[1] := '(1)'; Result.FOneDimArrayStr_Three[2] := '(2)'; Result.FOneDimArrayStr_Three[3] := '(3)';
Result.FOneDimArrayInt_One[0] := 10;
Result.FOneDimArrayInt_Three[1] := 11; Result.FOneDimArrayInt_Three[2] := 12; Result.FOneDimArrayInt_Three[3] := 13;
{ Two dim arrays }
Result.FTwoDimArrayStr_Two[0, 0] := '(0,0)';
Result.FTwoDimArrayStr_Four[1,0] := '(1,0)'; Result.FTwoDimArrayStr_Four[1,1] := '(1,1)';
Result.FTwoDimArrayStr_Four[2,0] := '(2,0)'; Result.FTwoDimArrayStr_Four[2,1] := '(2,1)';
Result.FTwoDimArrayInt_Two[0, 0] := 100;
Result.FTwoDimArrayInt_Four[1,0] := 100; Result.FTwoDimArrayInt_Four[1,1] := 110;
Result.FTwoDimArrayInt_Four[2,0] := 200; Result.FTwoDimArrayInt_Four[2,1] := 210;
end;
{ TDateTimeRecord }
procedure TDateTimeRecord.CompareTo(const AOther: TDateTimeRecord);
begin
if FDateTime_Zero <> AOther.FDateTime_Zero then
raise EFieldFailError.Create('FDateTime_Zero', DateTimeToStr(FDateTime_Zero), DateTimeToStr(AOther.FDateTime_Zero));
if System.Abs(FDateTime_Now - AOther.FDateTime_Now) > 0.0001 then
raise EFieldFailError.Create('FDateTime_Now', DateTimeToStr(FDateTime_Now), DateTimeToStr(AOther.FDateTime_Now));
if FTime_Zero <> AOther.FTime_Zero then
raise EFieldFailError.Create('FTime_Zero', TimeToStr(FTime_Zero), TimeToStr(AOther.FTime_Zero));
if System.Abs(FTime_Now - AOther.FTime_Now) > 0.0001 then
raise EFieldFailError.Create('FTime_Now', TimeToStr(FTime_Now), TimeToStr(AOther.FTime_Now));
if FDate_Zero <> AOther.FDate_Zero then
raise EFieldFailError.Create('FDate_Zero', DateToStr(FDate_Zero), DateToStr(AOther.FDate_Zero));
if not SameDate(FDate_Now, AOther.FDate_Now) then
raise EFieldFailError.Create('FDate_Now', DateToStr(FDate_Now), DateToStr(AOther.FDate_Now));
end;
class function TDateTimeRecord.Create: TDateTimeRecord;
begin
Result.FDateTime_Zero := 0;
Result.FDateTime_Now := Now;
Result.FTime_Zero := 0;
Result.FTime_Now := Time;
Result.FDate_Zero := 0;
Result.FDate_Now := Date;
end;
{ TEnumSetRecord }
procedure TEnumSetRecord.CompareTo(const AOther: TEnumSetRecord);
begin
if FEnum_One <> AOther.FEnum_One then
raise EFieldFailError.Create('FEnum_One', IntToStr(Integer(FEnum_One)), IntToStr(Integer(AOther.FEnum_One)));
if FEnum_Two <> AOther.FEnum_Two then
raise EFieldFailError.Create('FEnum_Two', IntToStr(Integer(FEnum_Two)), IntToStr(Integer(AOther.FEnum_Two)));
if FSet_Empty <> AOther.FSet_Empty then
raise EFieldFailError.Create('FSet_Empty', '...', '...');
if FSet_One <> AOther.FSet_One then
raise EFieldFailError.Create('FSet_One', '...', '...');
if FSet_All <> AOther.FSet_All then
raise EFieldFailError.Create('FSet_All', '...', '...');
end;
class function TEnumSetRecord.Create: TEnumSetRecord;
begin
Result.FEnum_One := someOne;
Result.FEnum_Two := someTwo;
Result.FSet_Empty := [];
Result.FSet_One := [someOne];
Result.FSet_All := [someOne .. someThree];
end;
{ TChainedClass }
constructor TChainedClass.Create;
begin
FSelf := Self;
FNil := nil;
end;
{ TContainer }
constructor TContainer.Create(const CreateSubs: Boolean);
begin
SetLength(FArray, 6);
{ 0 }
FArray[0] := TOne.Create();
{ 1 }
FArray[1] := TTwo.Create();
{ 2 }
FArray[2] := TThree.Create();
{ 3 --> 0 }
FArray[3] := FArray[0];
{ 4 --> nil }
FArray[4] := nil;
{ 5 -- Another container }
if CreateSubs then
FArray[5] := TContainer.Create(false)
else
FArray[5] := Self;
end;
destructor TContainer.Destroy;
begin
if Length(FArray) > 0 then
FArray[0].Free;
if Length(FArray) > 1 then
FArray[1].Free;
if Length(FArray) > 2 then
FArray[2].Free;
if Length(FArray) > 5 then
if FArray[5] <> Self then
FArray[5].Free;
inherited;
end;
procedure TContainer.Test(const WithSubs: Boolean);
begin
if Length(FArray) <> 6 then
raise EFieldFailError.Create('(length) FArray', '6', IntToStr(Length(FArray)));
if FArray[0] = nil then
raise EFieldFailError.Create('FArray[0]', 'non-nil', 'nil');
if not (FArray[0] is TOne) then
raise EFieldFailError.Create('(class) FArray[0]', 'TOne', FArray[0].ClassName);
{ Test object }
(FArray[0] as TOne).Test;
if FArray[1] = nil then
raise EFieldFailError.Create('FArray[1]', 'non-nil', 'nil');
if not (FArray[1] is TTwo) then
raise EFieldFailError.Create('(class) FArray[1]', 'TTwo', FArray[1].ClassName);
{ Test object }
(FArray[1] as TTwo).Test;
if FArray[2] = nil then
raise EFieldFailError.Create('FArray[2]', 'non-nil', 'nil');
if not (FArray[2] is TThree) then
raise EFieldFailError.Create('(class) FArray[2]', 'TThree', FArray[2].ClassName);
if FArray[3] <> FArray[0] then
raise EFieldFailError.Create('FArray[3]', 'equals to FArray[0]', 'different');
if FArray[4] <> nil then
raise EFieldFailError.Create('FArray[4]', 'nil', 'different');
if WithSubs then
begin
if FArray[5] = nil then
raise EFieldFailError.Create('FArray[5]', 'non-nil', 'nil');
if not (FArray[5] is TContainer) then
raise EFieldFailError.Create('(class) FArray[5]', 'TContainer', FArray[5].ClassName);
{ Invoke sub test }
(FArray[5] as TContainer).Test(false);
end else
begin
if FArray[5] <> Self then
raise EFieldFailError.Create('FArray[5]', '=Self', '<>Self');
end;
end;
{ TContainer.TOne }
constructor TContainer.TOne.Create;
begin
FOneField := 'TOne';
end;
procedure TContainer.TOne.Test;
begin
if FOneField <> 'TOne' then
raise EFieldFailError.Create('TOne.FOneField', 'TOne', FOneField);
end;
{ TContainer.TTwo }
constructor TContainer.TTwo.Create;
begin
FOneField := 'TTwo';
FTwoField := $DEADBABE;
end;
procedure TContainer.TTwo.Test;
begin
if FOneField <> 'TTwo' then
raise EFieldFailError.Create('TTwo.FOneField', 'TTwo', FOneField);
if FTwoField <> $DEADBABE then
raise EFieldFailError.Create('TTwo.FTwoField', '$DEADBABE', IntToStr(FTwoField));
end;
{ TSpecialKukuClass }
constructor TSpecialKukuClass.Create;
begin
FSequence := FSequence + 'c';
end;
procedure TSpecialKukuClass.Deserialize(const AData: TDeserializationData);
begin
FSequence := FSequence + 'de';
end;
procedure TSpecialKukuClass.Deserialized(const AData: TDeserializationData);
begin
FSequence := FSequence + 'dd';
end;
procedure TSpecialKukuClass.Serialize(const AData: TSerializationData);
begin
FSequence := FSequence + 'se';
end;
{ TInhBase }
constructor TInhBase.Create();
begin
FField := '1';
end;
procedure TInhBase.Test;
begin
if FField <> '1' then
raise EFieldFailError.Create('TInhBase.FField', '1', FField);
end;
{ TInhDerived }
constructor TInhDerived.Create();
begin
inherited;
FField := '2';
end;
procedure TInhDerived.Test;
begin
inherited;
if FField <> '2' then
raise EFieldFailError.Create('TInhDerived.FField', '2', FField);
end;
{ TInhDerived2 }
constructor TInhDerived2.Create();
begin
inherited;
FField := '3';
end;
procedure TInhDerived2.Test;
begin
inherited;
if FField <> '3' then
raise EFieldFailError.Create('TInhDerived2.FField', '3', FField);
end;
{ TTestGrossSerialization }
class function TTestGrossSerialization.SerializeInBinary<T>(const AValue: T): T;
var
LBinFile: TMemoryStream;
LBinSerializer: TBinarySerializer<T>;
begin
{ Create the serializer and an XML document }
LBinSerializer := TBinarySerializer<T>.Create();
LBinFile := TMemoryStream.Create();
{ Serialize the structure }
try
LBinSerializer.Serialize(AValue, LBinFile);
LBinFile.Seek(0, soFromBeginning);
LBinSerializer.Deserialize(Result, LBinFile);
finally
LBinFile.Free;
LBinSerializer.Free;
end;
end;
class function TTestGrossSerialization.SerializeInIni<T>(const AValue: T): T;
var
LIniFile: TMemIniFile;
LIniSerializer: TIniSerializer<T>;
begin
{ Create the serializer and an XML document }
LIniSerializer := TIniSerializer<T>.Create();
LIniFile := TMemIniFile.Create('_no_file_', TEncoding.UTF8);
try
{ Serialize the structure }
LIniSerializer.Serialize(AValue, LIniFile);
LIniSerializer.Deserialize(Result, LIniFile);
finally
LIniFile.Free;
LIniSerializer.Free;
end;
end;
class function TTestGrossSerialization.SerializeInXML<T>(const AValue: T): T;
var
LXmlFile: IXMLDocument;
LXmlSerializer: TXmlSerializer<T>;
begin
{ Create the serializer and an XML document }
LXmlSerializer := TXmlSerializer<T>.Create();
LXmlFile := TXMLDocument.Create(nil);
LXmlFile.Active := true;
{ Serialize the structure }
try
LXmlSerializer.Serialize(AValue, LXmlFile.Node);
LXmlSerializer.Deserialize(Result, LXmlFile.Node);
finally
LXmlSerializer.Free;
end;
end;
procedure TTestGrossSerialization.Test_Arrays;
var
LInput: TArraysRecord;
LOutXml, LOutIni, LOutBin: TArraysRecord;
begin
LInput := TArraysRecord.Create;
LOutXml := SerializeInXML<TArraysRecord>(LInput);
LOutIni := SerializeInIni<TArraysRecord>(LInput);
LOutBin := SerializeInBinary<TArraysRecord>(LInput);
LInput.CompareTo(LOutXml);
LInput.CompareTo(LOutIni);
LInput.CompareTo(LOutBin);
end;
procedure TTestGrossSerialization.Test_Booleans;
var
LInput: TBooleanRecord;
LOutXml, LOutIni, LOutBin: TBooleanRecord;
begin
LInput := TBooleanRecord.Create;
LOutXml := SerializeInXML<TBooleanRecord>(LInput);
LOutIni := SerializeInIni<TBooleanRecord>(LInput);
LOutBin := SerializeInBinary<TBooleanRecord>(LInput);
LInput.CompareTo(LOutXml);
LInput.CompareTo(LOutIni);
LInput.CompareTo(LOutBin);
end;
type
TStringBox = TBox<String>;
procedure TTestGrossSerialization.Test_Box;
var
LInput0, LInput1: TStringBox;
LOutXml0, LOutIni0, LOutBin0,
LOutXml1, LOutIni1, LOutBin1: TStringBox;
begin
LInput0 := TStringBox.Create(); LInput0.Unbox;
LInput1 := TStringBox.Create('One Two Three');
LOutXml0 := nil; LOutXml1 := nil;
LOutIni0 := nil; LOutIni1 := nil;
LOutBin0 := nil; LOutBin1 := nil;
try
LOutXml0 := SerializeInXML<TStringBox>(LInput0);
LOutIni0 := SerializeInIni<TStringBox>(LInput0);
LOutBin0 := SerializeInBinary<TStringBox>(LInput0);
LOutXml1 := SerializeInXML<TStringBox>(LInput1);
LOutIni1 := SerializeInIni<TStringBox>(LInput1);
LOutBin1 := SerializeInBinary<TStringBox>(LInput1);
CheckTrue(LOutXml0 <> nil, 'LOutXml0 is nil');
CheckTrue(LOutIni0 <> nil, 'LOutIni0 is nil');
CheckTrue(LOutBin0 <> nil, 'LOutBin0 is nil');
CheckTrue(LOutXml1 <> nil, 'LOutXml1 is nil');
CheckTrue(LOutIni1 <> nil, 'LOutIni1 is nil');
CheckTrue(LOutBin1 <> nil, 'LOutBin1 is nil');
CheckTrue(not LOutXml0.HasBoxedValue, 'LOutXml0 has a boxed value');
CheckTrue(not LOutIni0.HasBoxedValue, 'LOutIni0 has a boxed value');
CheckTrue(not LOutBin0.HasBoxedValue, 'LOutBin0 has a boxed value');
CheckTrue(LOutXml1.HasBoxedValue, 'LOutXml1 does not have a boxed value');
CheckTrue(LOutIni1.HasBoxedValue, 'LOutIni1 does not have a boxed value');
CheckTrue(LOutBin1.HasBoxedValue, 'LOutBin1 does not have a boxed value');
CheckEquals(LInput1.Peek, LOutXml1.Peek, 'LOutXml1 boxed value');
CheckEquals(LInput1.Peek, LOutXml1.Peek, 'LOutIni1 boxed value');
CheckEquals(LInput1.Peek, LOutXml1.Peek, 'LOutBin1 boxed value');
finally
LInput0.Free;
LInput1.Free;
LOutXml0.Free;
LOutIni0.Free;
LOutBin0.Free;
LOutXml1.Free;
LOutIni1.Free;
LOutBin1.Free;
end;
end;
type
TInnerArray = array of string;
TOuterArray = array of TInnerArray;
TNestedArrayTestClass = class
FSomeArray: TOuterArray;
constructor Create();
procedure Test(const AOther: TNestedArrayTestClass);
end;
constructor TNestedArrayTestClass.Create();
begin
FSomeArray := TOuterArray.Create(TInnerArray.Create('one', 'two'), nil, TInnerArray.Create('three'));
end;
procedure TNestedArrayTestClass.Test(const AOther: TNestedArrayTestClass);
begin
{ Main array }
if Length(FSomeArray) <> Length(AOther.FSomeArray) then
raise EFieldFailError.Create('(len) FSomeArray', '...', '...');
if Length(FSomeArray[0]) <> Length(AOther.FSomeArray[0]) then
raise EFieldFailError.Create('(len) FSomeArray[0]', '...', '...');
if Length(FSomeArray[1]) <> Length(AOther.FSomeArray[1]) then
raise EFieldFailError.Create('(len) FSomeArray[1]', '...', '...');
if Length(FSomeArray[2]) <> Length(AOther.FSomeArray[2]) then
raise EFieldFailError.Create('(len) FSomeArray[2]', '...', '...');
if FSomeArray[0][0] <> AOther.FSomeArray[0][0] then
raise EFieldFailError.Create('FSomeArray[0][0]', FSomeArray[0][0], AOther.FSomeArray[0][0]);
if FSomeArray[0][1] <> AOther.FSomeArray[0][1] then
raise EFieldFailError.Create('FSomeArray[0][1]', FSomeArray[0][1], AOther.FSomeArray[0][1]);
if FSomeArray[2][0] <> AOther.FSomeArray[2][0] then
raise EFieldFailError.Create('FSomeArray[2][0]', FSomeArray[2][0], AOther.FSomeArray[2][0]);
end;
procedure TTestGrossSerialization.Test_Buffer;
var
LInput0, LInput1: TBuffer;
LOutXml0, LOutIni0, LOutBin0,
LOutXml1, LOutIni1, LOutBin1: TBuffer;
begin
LInput0 := TBuffer.Create([]);
LInput1 := TBuffer.Create([1, 2, 3]);
LOutXml0 := SerializeInXML<TBuffer>(LInput0);
LOutIni0 := SerializeInIni<TBuffer>(LInput0);
LOutBin0 := SerializeInBinary<TBuffer>(LInput0);
LOutXml1 := SerializeInXML<TBuffer>(LInput1);
LOutIni1 := SerializeInIni<TBuffer>(LInput1);
LOutBin1 := SerializeInBinary<TBuffer>(LInput1);
CheckTrue(LOutXml0.Length = 0, '(not empty!) Xml serialization failed!');
CheckTrue(LOutIni0.Length = 0, '(not empty!) Ini serialization failed!');
CheckTrue(LOutBin0.Length = 0, '(not empty!) Bin serialization failed!');
CheckTrue(LOutXml1.Length = 3, '(empty!) Xml serialization failed!');
CheckTrue(LOutIni1.Length = 3, '(empty!) Ini serialization failed!');
CheckTrue(LOutBin1.Length = 3, '(empty!) Bin serialization failed!');
CheckEquals(LInput1[0], LOutXml1[0], 'Xml serialization failed! [0]');
CheckEquals(LInput1[1], LOutXml1[1], 'Xml serialization failed! [1]');
CheckEquals(LInput1[2], LOutXml1[2], 'Xml serialization failed! [2]');
CheckEquals(LInput1[0], LOutIni1[0], 'Ini serialization failed! [0]');
CheckEquals(LInput1[1], LOutIni1[1], 'Ini serialization failed! [1]');
CheckEquals(LInput1[2], LOutIni1[2], 'Ini serialization failed! [2]');
CheckEquals(LInput1[0], LOutBin1[0], 'Bin serialization failed! [0]');
CheckEquals(LInput1[1], LOutBin1[1], 'Bin serialization failed! [1]');
CheckEquals(LInput1[2], LOutBin1[2], 'Bin serialization failed! [2]');
end;
procedure TTestGrossSerialization.Test_Bug0;
var
LInput: TNestedArrayTestClass;
LOutXml, LOutIni, LOutBin: TNestedArrayTestClass;
begin
LInput := TNestedArrayTestClass.Create();
LOutXml := nil;
LOutIni := nil;
LOutBin := nil;
try
LOutXml := SerializeInXML<TNestedArrayTestClass>(LInput);
LOutIni := SerializeInIni<TNestedArrayTestClass>(LInput);
LOutBin := SerializeInBinary<TNestedArrayTestClass>(LInput);
CheckTrue(LOutXml <> nil, 'LOutXml is nil');
CheckTrue(LOutIni <> nil, 'LOutIni is nil');
CheckTrue(LOutBin <> nil, 'LOutBin is nil');
LInput.Test(LOutXml);
LInput.Test(LOutIni);
LInput.Test(LOutBin);
finally
LInput.Free;
LOutXml.Free;
LOutIni.Free;
LOutBin.Free;
end;
end;
procedure TTestGrossSerialization.Test_ClassComplicated;
var
LInput: TContainer;
LOutXml, LOutIni, LOutBin: TContainer;
begin
LInput := TContainer.Create(true);
LOutXml := nil;
LOutIni := nil;
LOutBin := nil;
try
LOutXml := TContainer(SerializeInXML<TObject>(LInput));
LOutIni := TContainer(SerializeInIni<TObject>(LInput));
LOutBin := TContainer(SerializeInBinary<TObject>(LInput));
CheckTrue(LOutXml <> nil, 'LOutXml is nil');
CheckTrue(LOutIni <> nil, 'LOutIni is nil');
CheckTrue(LOutBin <> nil, 'LOutBin is nil');
CheckTrue(LOutXml is TContainer, 'LOutXml is not TContainer');
CheckTrue(LOutIni is TContainer, 'LOutIni is not TContainer');
CheckTrue(LOutBin is TContainer, 'LOutBin is not TContainer');
LOutXml.Test(true);
LOutIni.Test(true);
LOutBin.Test(true);
finally
LInput.Free;
LOutXml.Free;
LOutIni.Free;
LOutBin.Free;
end;
end;
procedure TTestGrossSerialization.Test_ClassSameFields;
var
LInput: TInhDerived2;
LOutXml, LOutIni, LOutBin: TInhDerived2;
begin
LInput := TInhDerived2.Create();
LOutXml := nil;
LOutIni := nil;
LOutBin := nil;
try
LOutXml := SerializeInXML<TInhDerived2>(LInput);
LOutIni := SerializeInIni<TInhDerived2>(LInput);
LOutBin := SerializeInBinary<TInhDerived2>(LInput);
CheckTrue(LOutXml <> nil, 'LOutXml is nil');
CheckTrue(LOutIni <> nil, 'LOutIni is nil');
CheckTrue(LOutBin <> nil, 'LOutBin is nil');
LOutXml.Test();
LOutIni.Test();
LOutBin.Test();
finally
LInput.Free;
LOutXml.Free;
LOutIni.Free;
LOutBin.Free;
end;
end;
procedure TTestGrossSerialization.Test_ClassSelfRef;
var
LInput: TChainedClass;
LOutXml, LOutIni, LOutBin: TChainedClass;
begin
LInput := TChainedClass.Create;
LOutXml := nil;
LOutIni := nil;
LOutBin := nil;
try
LOutXml := SerializeInXML<TChainedClass>(LInput);
LOutIni := SerializeInIni<TChainedClass>(LInput);
LOutBin := SerializeInBinary<TChainedClass>(LInput);
CheckTrue(LOutXml <> nil, 'LOutXml is nil');
CheckTrue(LOutIni <> nil, 'LOutIni is nil');
CheckTrue(LOutBin <> nil, 'LOutBin is nil');
CheckTrue(LOutXml.FSelf = LOutXml, 'LOutXml.FSelf <> LOutXml');
CheckTrue(LOutIni.FSelf = LOutIni, 'LOutIni.FSelf <> LOutIni');
CheckTrue(LOutBin.FSelf = LOutBin, 'LOutBin.FSelf <> LOutBin');
CheckTrue(LOutXml.FNil = nil, 'LOutXml.FSelf <> nil');
CheckTrue(LOutIni.FNil = nil, 'LOutIni.FSelf <> nil');
CheckTrue(LOutBin.FNil = nil, 'LOutBin.FSelf <> nil');
finally
LInput.Free;
LOutXml.Free;
LOutIni.Free;
LOutBin.Free;
end;
end;
procedure TTestGrossSerialization.Test_CustomISerializable;
var
LInput: TSpecialKukuClass;
LOutXml, LOutIni, LOutBin: TSpecialKukuClass;
begin
LInput := TSpecialKukuClass.Create;
LOutXml := nil;
LOutIni := nil;
LOutBin := nil;
try
LOutXml := SerializeInXML<TSpecialKukuClass>(LInput);
LOutIni := SerializeInIni<TSpecialKukuClass>(LInput);
LOutBin := SerializeInBinary<TSpecialKukuClass>(LInput);
CheckTrue(LOutXml <> nil, 'LOutXml is nil');
CheckTrue(LOutIni <> nil, 'LOutIni is nil');
CheckTrue(LOutBin <> nil, 'LOutBin is nil');
CheckEquals('csesese', LInput.FSequence, 'LInput sequence broken');
CheckEquals('cdedd', LOutXml.FSequence, 'LOutXml sequence broken');
CheckEquals('cdedd', LOutIni.FSequence, 'LOutXml sequence broken');
CheckEquals('cdedd', LOutBin.FSequence, 'LOutXml sequence broken');
{ Check ref counts! }
CheckEquals(0, LInput.RefCount, 'LInput ref count broken');
CheckEquals(0, LOutXml.RefCount, 'LOutXml ref count broken');
CheckEquals(0, LOutIni.RefCount, 'LOutIni ref count broken');
CheckEquals(0, LOutBin.RefCount, 'LOutBin ref count broken');
finally
LInput.Free;
LOutXml.Free;
LOutIni.Free;
LOutBin.Free;
end;
end;
procedure TTestGrossSerialization.Test_Date;
var
LInput: TDate;
LOutXml, LOutIni, LOutBin: TDate;
begin
LInput := Date;
LOutXml := SerializeInXML<TDate>(LInput);
LOutIni := SerializeInIni<TDate>(LInput);
LOutBin := SerializeInBinary<TDate>(LInput);
CheckEquals(LInput.ToString(), LOutXml.ToString(), 'Xml serialization failed!');
CheckEquals(LInput.ToString(), LOutIni.ToString(), 'Ini serialization failed!');
CheckEquals(LInput.ToString(), LOutBin.ToString(), 'Binary serialization failed!');
end;
procedure TTestGrossSerialization.Test_DateTime;
var
LInput: TDateTime;
LOutXml, LOutIni, LOutBin: TDateTime;
begin
LInput := Now;
LOutXml := SerializeInXML<TDateTime>(LInput);
LOutIni := SerializeInIni<TDateTime>(LInput);
LOutBin := SerializeInBinary<TDateTime>(LInput);
CheckEquals(LInput.ToString(), LOutXml.ToString(), 'Xml serialization failed!');
CheckEquals(LInput.ToString(), LOutIni.ToString(), 'Ini serialization failed!');
CheckEquals(LInput.ToString(), LOutBin.ToString(), 'Binary serialization failed!');
end;
procedure TTestGrossSerialization.Test_DTs;
var
LInput: TDateTimeRecord;
LOutXml, LOutIni, LOutBin: TDateTimeRecord;
begin
LInput := TDateTimeRecord.Create;
LOutXml := SerializeInXML<TDateTimeRecord>(LInput);
LOutIni := SerializeInIni<TDateTimeRecord>(LInput);
LOutBin := SerializeInBinary<TDateTimeRecord>(LInput);
LInput.CompareTo(LOutXml);
LInput.CompareTo(LOutIni);
LInput.CompareTo(LOutBin);
end;
type
TIntDynArray = TDynamicArray<Integer>;
procedure TTestGrossSerialization.Test_DynamicArray;
var
LInput0, LInput1: TIntDynArray;
LOutXml0, LOutIni0, LOutBin0,
LOutXml1, LOutIni1, LOutBin1: TIntDynArray;
begin
LInput0 := TIntDynArray.Create([]);
LInput1 := TIntDynArray.Create([1, 2, 3]);
LOutXml0 := SerializeInXML<TIntDynArray>(LInput0);
LOutIni0 := SerializeInIni<TIntDynArray>(LInput0);
LOutBin0 := SerializeInBinary<TIntDynArray>(LInput0);
LOutXml1 := SerializeInXML<TIntDynArray>(LInput1);
LOutIni1 := SerializeInIni<TIntDynArray>(LInput1);
LOutBin1 := SerializeInBinary<TIntDynArray>(LInput1);
CheckTrue(LOutXml0.Length = 0, '(not empty!) Xml serialization failed!');
CheckTrue(LOutIni0.Length = 0, '(not empty!) Ini serialization failed!');
CheckTrue(LOutBin0.Length = 0, '(not empty!) Bin serialization failed!');
CheckTrue(LOutXml1.Length = 3, '(empty!) Xml serialization failed!');
CheckTrue(LOutIni1.Length = 3, '(empty!) Ini serialization failed!');
CheckTrue(LOutBin1.Length = 3, '(empty!) Bin serialization failed!');
CheckEquals(LInput1[0], LOutXml1[0], 'Xml serialization failed! [0]');
CheckEquals(LInput1[1], LOutXml1[1], 'Xml serialization failed! [1]');
CheckEquals(LInput1[2], LOutXml1[2], 'Xml serialization failed! [2]');
CheckEquals(LInput1[0], LOutIni1[0], 'Ini serialization failed! [0]');
CheckEquals(LInput1[1], LOutIni1[1], 'Ini serialization failed! [1]');
CheckEquals(LInput1[2], LOutIni1[2], 'Ini serialization failed! [2]');
CheckEquals(LInput1[0], LOutBin1[0], 'Bin serialization failed! [0]');
CheckEquals(LInput1[1], LOutBin1[1], 'Bin serialization failed! [1]');
CheckEquals(LInput1[2], LOutBin1[2], 'Bin serialization failed! [2]');
end;
procedure TTestGrossSerialization.Test_EnumsAndSets;
var
LInput: TEnumSetRecord;
LOutXml, LOutIni, LOutBin: TEnumSetRecord;
begin
LInput := TEnumSetRecord.Create;
LOutXml := SerializeInXML<TEnumSetRecord>(LInput);
LOutIni := SerializeInIni<TEnumSetRecord>(LInput);
LOutBin := SerializeInBinary<TEnumSetRecord>(LInput);
LInput.CompareTo(LOutXml);
LInput.CompareTo(LOutIni);
LInput.CompareTo(LOutBin);
end;
type
TIntFixedArray = TFixedArray<Integer>;
procedure TTestGrossSerialization.Test_FixedArray;
var
LInput0, LInput1: TIntFixedArray;
LOutXml0, LOutIni0, LOutBin0,
LOutXml1, LOutIni1, LOutBin1: TIntFixedArray;
begin
LInput0 := TIntFixedArray.Create([]);
LInput1 := TIntFixedArray.Create([1, 2, 3]);
LOutXml0 := SerializeInXML<TIntFixedArray>(LInput0);
LOutIni0 := SerializeInIni<TIntFixedArray>(LInput0);
LOutBin0 := SerializeInBinary<TIntFixedArray>(LInput0);
LOutXml1 := SerializeInXML<TIntFixedArray>(LInput1);
LOutIni1 := SerializeInIni<TIntFixedArray>(LInput1);
LOutBin1 := SerializeInBinary<TIntFixedArray>(LInput1);
CheckTrue(LOutXml0.Length = 0, '(not empty!) Xml serialization failed!');
CheckTrue(LOutIni0.Length = 0, '(not empty!) Ini serialization failed!');
CheckTrue(LOutBin0.Length = 0, '(not empty!) Bin serialization failed!');
CheckTrue(LOutXml1.Length = 3, '(empty!) Xml serialization failed!');
CheckTrue(LOutIni1.Length = 3, '(empty!) Ini serialization failed!');
CheckTrue(LOutBin1.Length = 3, '(empty!) Bin serialization failed!');
CheckEquals(LInput1[0], LOutXml1[0], 'Xml serialization failed! [0]');
CheckEquals(LInput1[1], LOutXml1[1], 'Xml serialization failed! [1]');
CheckEquals(LInput1[2], LOutXml1[2], 'Xml serialization failed! [2]');
CheckEquals(LInput1[0], LOutIni1[0], 'Ini serialization failed! [0]');
CheckEquals(LInput1[1], LOutIni1[1], 'Ini serialization failed! [1]');
CheckEquals(LInput1[2], LOutIni1[2], 'Ini serialization failed! [2]');
CheckEquals(LInput1[0], LOutBin1[0], 'Bin serialization failed! [0]');
CheckEquals(LInput1[1], LOutBin1[1], 'Bin serialization failed! [1]');
CheckEquals(LInput1[2], LOutBin1[2], 'Bin serialization failed! [2]');
end;
procedure TTestGrossSerialization.Test_Floats;
var
LInput: TFloatsRecord;
LOutXml, LOutIni, LOutBin: TFloatsRecord;
begin
LInput := TFloatsRecord.Create;
LOutXml := SerializeInXML<TFloatsRecord>(LInput);
LOutIni := SerializeInIni<TFloatsRecord>(LInput);
LOutBin := SerializeInBinary<TFloatsRecord>(LInput);
LInput.CompareTo(LOutXml);
LInput.CompareTo(LOutIni);
LInput.CompareTo(LOutBin);
end;
procedure TTestGrossSerialization.Test_Integers;
var
LInput: TIntsRecord;
LOutXml, LOutIni, LOutBin: TIntsRecord;
begin
LInput := TIntsRecord.Create;
LOutXml := SerializeInXML<TIntsRecord>(LInput);
LOutIni := SerializeInIni<TIntsRecord>(LInput);
LOutBin := SerializeInBinary<TIntsRecord>(LInput);
LInput.CompareTo(LOutXml);
LInput.CompareTo(LOutIni);
LInput.CompareTo(LOutBin);
end;
type
TIntStrKVP = KVPair<Integer, String>;
procedure TTestGrossSerialization.Test_KVP;
var
LInput: TIntStrKVP;
LOutXml, LOutIni, LOutBin: TIntStrKVP;
begin
LInput := TIntStrKVP.Create(123, 'Four__');
LOutXml := SerializeInXML<TIntStrKVP>(LInput);
LOutIni := SerializeInIni<TIntStrKVP>(LInput);
LOutBin := SerializeInBinary<TIntStrKVP>(LInput);
CheckEquals(LInput.Key, LOutXml.Key, '[key] Xml serialization failed!');
CheckEquals(LInput.Value, LOutXml.Value, '[val] Xml serialization failed!');
CheckEquals(LInput.Key, LOutIni.Key, '[key] Ini serialization failed!');
CheckEquals(LInput.Value, LOutIni.Value, '[val] Ini serialization failed!');
CheckEquals(LInput.Key, LOutBin.Key, '[key] Binary serialization failed!');
CheckEquals(LInput.Value, LOutBin.Value, '[val] Binary serialization failed!');
end;
procedure TTestGrossSerialization.Test_Metaclass;
var
LInput: TClass;
LOutXml, LOutIni, LOutBin: TClass;
begin
{ Real }
LInput := TTestGrossSerialization;
LOutXml := SerializeInXML<TClass>(LInput);
LOutIni := SerializeInIni<TClass>(LInput);
LOutBin := SerializeInBinary<TClass>(LInput);
CheckEquals(LInput, LOutXml, 'Xml serialization failed!');
CheckEquals(LInput, LOutIni, 'Ini serialization failed!');
CheckEquals(LInput, LOutBin, 'Binary serialization failed!');
{ nil }
LInput := nil;
LOutXml := SerializeInXML<TClass>(LInput);
LOutIni := SerializeInIni<TClass>(LInput);
LOutBin := SerializeInBinary<TClass>(LInput);
CheckEquals(LInput, LOutXml, 'Xml serialization failed!');
CheckEquals(LInput, LOutIni, 'Ini serialization failed!');
CheckEquals(LInput, LOutBin, 'Binary serialization failed!');
end;
procedure TTestGrossSerialization.Test_NonSerializable;
var
LInput: TBadSerRecord_NonSer;
LOutXml, LOutIni, LOutBin: TBadSerRecord_NonSer;
begin
LInput.S := 'One';
LInput.P := Ptr($BADC0DE);
LOutXml := SerializeInXML<TBadSerRecord_NonSer>(LInput);
LOutIni := SerializeInIni<TBadSerRecord_NonSer>(LInput);
LOutBin := SerializeInBinary<TBadSerRecord_NonSer>(LInput);
CheckEquals(LInput.S, LOutXml.S, 'Xml ser/deser failed for [NonSerialized]');
CheckEquals(LInput.S, LOutIni.S, 'Ini ser/deser failed for [NonSerialized]');
CheckEquals(LInput.S, LOutBin.S, 'Bin ser/deser failed for [NonSerialized]');
end;
type
TIntNullable = Nullable<Integer>;
procedure TTestGrossSerialization.Test_Nullable;
var
LInput0, LInput1: TIntNullable;
LOutXml0, LOutIni0, LOutBin0,
LOutXml1, LOutIni1, LOutBin1: TIntNullable;
begin
LInput0 := 100;
LInput1.MakeNull;
LOutXml0 := SerializeInXML<TIntNullable>(LInput0);
LOutIni0 := SerializeInIni<TIntNullable>(LInput0);
LOutBin0 := SerializeInBinary<TIntNullable>(LInput0);
LOutXml1 := SerializeInXML<TIntNullable>(LInput1);
LOutIni1 := SerializeInIni<TIntNullable>(LInput1);
LOutBin1 := SerializeInBinary<TIntNullable>(LInput1);
CheckTrue(not LOutXml0.IsNull, '(null!) Xml serialization failed!');
CheckTrue(not LOutIni0.IsNull, '(null!) Ini serialization failed!');
CheckTrue(not LOutBin0.IsNull, '(null!) Bin serialization failed!');
CheckEquals(LInput0.Value, LOutXml0.Value, 'Xml serialization failed! Values differ.');
CheckEquals(LInput0.Value, LOutIni0.Value, 'Ini serialization failed! Values differ.');
CheckEquals(LInput0.Value, LOutBin0.Value, 'Bin serialization failed! Values differ.');
CheckTrue(LOutXml1.IsNull, '(~null!) Xml serialization failed!');
CheckTrue(LOutIni1.IsNull, '(~null!) Ini serialization failed!');
CheckTrue(LOutBin1.IsNull, '(~null!) Bin serialization failed!');
end;
procedure TTestGrossSerialization.Test_Bad_Serialized;
var
LInput: TBadSerRecord;
LOutXml, LOutIni, LOutBin: Boolean;
begin
LInput.P := nil;
LInput.S := '66699';
try
LOutXml := false;
SerializeInXML<TBadSerRecord>(LInput);
except
on E: ESerializationException do
LOutXml := true;
end;
try
LOutIni := false;
SerializeInIni<TBadSerRecord>(LInput);
except
on E: ESerializationException do
LOutIni := true;
end;
try
LOutBin := false;
SerializeInBinary<TBadSerRecord>(LInput);
except
on E: ESerializationException do
LOutBin := true;
end;
CheckTrue(LOutXml, '(unser. member) Expected exception was not raised for XML.');
CheckTrue(LOutIni, '(unser. member) Expected exception was not raised for Ini.');
CheckTrue(LOutBin, '(unser. member) Expected exception was not raised for Binary.');
end;
procedure TTestGrossSerialization.Test_BigCardinal;
var
LInput: BigCardinal;
LOutXml, LOutIni, LOutBin: BigCardinal;
begin
LInput := BigCardinal.Parse('372189378912739286437285630234273462838493207416082644213254314');
LOutXml := SerializeInXML<BigCardinal>(LInput);
LOutIni := SerializeInIni<BigCardinal>(LInput);
LOutBin := SerializeInBinary<BigCardinal>(LInput);
CheckTrue(LOutXml = LInput, 'Xml serialization failed!');
CheckTrue(LOutIni = LInput, 'Ini serialization failed!');
CheckTrue(LOutBin = LInput, 'Binary serialization failed!');
end;
procedure TTestGrossSerialization.Test_BigDecimal;
var
LInput: BigDecimal;
LOutXml, LOutIni, LOutBin: BigDecimal;
begin
LInput := BigDecimal.Parse('37218937891273928643728563023427346283' + DecimalSeparator + '8493207416082644213254314');
LOutXml := SerializeInXML<BigDecimal>(LInput);
LOutIni := SerializeInIni<BigDecimal>(LInput);
LOutBin := SerializeInBinary<BigDecimal>(LInput);
CheckTrue(LOutXml = LInput, 'Xml serialization failed!');
CheckTrue(LOutIni = LInput, 'Ini serialization failed!');
CheckTrue(LOutBin = LInput, 'Binary serialization failed!');
end;
procedure TTestGrossSerialization.Test_BigInteger;
var
LInput: BigInteger;
LOutXml, LOutIni, LOutBin: BigInteger;
begin
LInput := BigInteger.Parse('-372189378912739286437285630234273462838493207416082644213254314');
LOutXml := SerializeInXML<BigInteger>(LInput);
LOutIni := SerializeInIni<BigInteger>(LInput);
LOutBin := SerializeInBinary<BigInteger>(LInput);
CheckTrue(LOutXml = LInput, 'Xml serialization failed!');
CheckTrue(LOutIni = LInput, 'Ini serialization failed!');
CheckTrue(LOutBin = LInput, 'Binary serialization failed!');
end;
procedure TTestGrossSerialization.Test_RecordSelfRef;
var
LInput: PLinkedItem;
LOutXml, LOutIni, LOutBin: PLinkedItem;
begin
New(LInput);
LInput.FData := 'Hello World!';
LInput.FSelf := LInput;
LInput.FNil := nil;
LOutXml := nil;
LOutIni := nil;
LOutBin := nil;
try
LOutXml := SerializeInXML<PLinkedItem>(LInput);
LOutIni := SerializeInIni<PLinkedItem>(LInput);
LOutBin := SerializeInBinary<PLinkedItem>(LInput);
CheckTrue(LOutXml <> nil, 'LOutXml is nil');
CheckTrue(LOutIni <> nil, 'LOutIni is nil');
CheckTrue(LOutBin <> nil, 'LOutBin is nil');
CheckTrue(LOutXml^.FSelf = LOutXml, 'LOutXml.FSelf <> LOutXml');
CheckTrue(LOutIni^.FSelf = LOutIni, 'LOutIni.FSelf <> LOutIni');
CheckTrue(LOutBin^.FSelf = LOutBin, 'LOutBin.FSelf <> LOutBin');
CheckTrue(LOutXml^.FNil = nil, 'LOutXml.FSelf <> nil');
CheckTrue(LOutIni^.FNil = nil, 'LOutIni.FSelf <> nil');
CheckTrue(LOutBin^.FNil = nil, 'LOutBin.FSelf <> nil');
finally
Dispose(LInput);
if LOutXml <> nil then
Dispose(LOutXml);
if LOutIni <> nil then
Dispose(LOutIni);
if LOutBin <> nil then
Dispose(LOutBin);
end;
end;
procedure TTestGrossSerialization.Test_Simple;
var
LInput: Integer;
LOutXml, LOutIni, LOutBin: Integer;
begin
LInput := -100;
LOutXml := SerializeInXML<Integer>(LInput);
LOutIni := SerializeInIni<Integer>(LInput);
LOutBin := SerializeInBinary<Integer>(LInput);
CheckEquals(LInput, LOutXml, '(Integer) Xml');
CheckEquals(LInput, LOutIni, '(Integer) Ini');
CheckEquals(LInput, LOutBin, '(Integer) Binary');
end;
procedure TTestGrossSerialization.Test_Strings;
var
LInput: TStringsRecord;
LOutXml, LOutIni, LOutBin: TStringsRecord;
begin
LInput := TStringsRecord.Create;
LOutXml := SerializeInXML<TStringsRecord>(LInput);
LOutIni := SerializeInIni<TStringsRecord>(LInput);
LOutBin := SerializeInBinary<TStringsRecord>(LInput);
LInput.CompareTo(LOutXml);
LInput.CompareTo(LOutIni);
LInput.CompareTo(LOutBin);
end;
procedure TTestGrossSerialization.Test_Time;
var
LInput: TTime;
LOutXml, LOutIni, LOutBin: TTime;
begin
LInput := Time;
LOutXml := SerializeInXML<TTime>(LInput);
LOutIni := SerializeInIni<TTime>(LInput);
LOutBin := SerializeInBinary<TTime>(LInput);
CheckEquals(LInput.ToString(), LOutXml.ToString(), 'Xml serialization failed!');
CheckEquals(LInput.ToString(), LOutIni.ToString(), 'Ini serialization failed!');
CheckEquals(LInput.ToString(), LOutBin.ToString(), 'Binary serialization failed!');
end;
type
TStrTuple = Tuple<string>;
procedure TTestGrossSerialization.Test_Tuple_1;
var
LInput: TStrTuple;
LOutXml, LOutIni, LOutBin: TStrTuple;
begin
LInput := Tuple.Create('Four__');
LOutXml := SerializeInXML<TStrTuple>(LInput);
LOutIni := SerializeInIni<TStrTuple>(LInput);
LOutBin := SerializeInBinary<TStrTuple>(LInput);
CheckEquals(LInput.Value1, LOutXml.Value1, '[1] Xml serialization failed!');
CheckEquals(LInput.Value1, LOutIni.Value1, '[1] Ini serialization failed!');
CheckEquals(LInput.Value1, LOutBin.Value1, '[1] Binary serialization failed!');
end;
type
TIntStrTuple = Tuple<Integer, string>;
procedure TTestGrossSerialization.Test_Tuple_2;
var
LInput: TIntStrTuple;
LOutXml, LOutIni, LOutBin: TIntStrTuple;
begin
LInput := Tuple.Create(Integer(188), 'Four__');
LOutXml := SerializeInXML<TIntStrTuple>(LInput);
LOutIni := SerializeInIni<TIntStrTuple>(LInput);
LOutBin := SerializeInBinary<TIntStrTuple>(LInput);
CheckEquals(LInput.Value1, LOutXml.Value1, '[1] Xml serialization failed!');
CheckEquals(LInput.Value1, LOutIni.Value1, '[1] Ini serialization failed!');
CheckEquals(LInput.Value1, LOutBin.Value1, '[1] Binary serialization failed!');
CheckEquals(LInput.Value2, LOutXml.Value2, '[2] Xml serialization failed!');
CheckEquals(LInput.Value2, LOutIni.Value2, '[2] Ini serialization failed!');
CheckEquals(LInput.Value2, LOutBin.Value2, '[2] Binary serialization failed!');
end;
type
TIntIntStrTuple = Tuple<Integer, Integer, string>;
procedure TTestGrossSerialization.Test_Tuple_3;
var
LInput: TIntIntStrTuple;
LOutXml, LOutIni, LOutBin: TIntIntStrTuple;
begin
LInput := Tuple.Create(Integer(-5), Integer(188), 'Four__');
LOutXml := SerializeInXML<TIntIntStrTuple>(LInput);
LOutIni := SerializeInIni<TIntIntStrTuple>(LInput);
LOutBin := SerializeInBinary<TIntIntStrTuple>(LInput);
CheckEquals(LInput.Value1, LOutXml.Value1, '[1] Xml serialization failed!');
CheckEquals(LInput.Value1, LOutIni.Value1, '[1] Ini serialization failed!');
CheckEquals(LInput.Value1, LOutBin.Value1, '[1] Binary serialization failed!');
CheckEquals(LInput.Value2, LOutXml.Value2, '[2] Xml serialization failed!');
CheckEquals(LInput.Value2, LOutIni.Value2, '[2] Ini serialization failed!');
CheckEquals(LInput.Value2, LOutBin.Value2, '[2] Binary serialization failed!');
CheckEquals(LInput.Value3, LOutXml.Value3, '[3] Xml serialization failed!');
CheckEquals(LInput.Value3, LOutIni.Value3, '[3] Ini serialization failed!');
CheckEquals(LInput.Value3, LOutBin.Value3, '[3] Binary serialization failed!');
end;
type
TBoolIntIntStrTuple = Tuple<Boolean, Integer, Integer, string>;
procedure TTestGrossSerialization.Test_Tuple_4;
var
LInput: TBoolIntIntStrTuple;
LOutXml, LOutIni, LOutBin: TBoolIntIntStrTuple;
begin
LInput := Tuple.Create(true, Integer(-5), Integer(188), 'Four__');
LOutXml := SerializeInXML<TBoolIntIntStrTuple>(LInput);
LOutIni := SerializeInIni<TBoolIntIntStrTuple>(LInput);
LOutBin := SerializeInBinary<TBoolIntIntStrTuple>(LInput);
CheckEquals(LInput.Value1, LOutXml.Value1, '[1] Xml serialization failed!');
CheckEquals(LInput.Value1, LOutIni.Value1, '[1] Ini serialization failed!');
CheckEquals(LInput.Value1, LOutBin.Value1, '[1] Binary serialization failed!');
CheckEquals(LInput.Value2, LOutXml.Value2, '[2] Xml serialization failed!');
CheckEquals(LInput.Value2, LOutIni.Value2, '[2] Ini serialization failed!');
CheckEquals(LInput.Value2, LOutBin.Value2, '[2] Binary serialization failed!');
CheckEquals(LInput.Value3, LOutXml.Value3, '[3] Xml serialization failed!');
CheckEquals(LInput.Value3, LOutIni.Value3, '[3] Ini serialization failed!');
CheckEquals(LInput.Value3, LOutBin.Value3, '[3] Binary serialization failed!');
CheckEquals(LInput.Value4, LOutXml.Value4, '[4] Xml serialization failed!');
CheckEquals(LInput.Value4, LOutIni.Value4, '[4] Ini serialization failed!');
CheckEquals(LInput.Value4, LOutBin.Value4, '[4] Binary serialization failed!');
end;
type
TStrBoolIntIntStrTuple = Tuple<string, Boolean, Integer, Integer, string>;
procedure TTestGrossSerialization.Test_Tuple_5;
var
LInput: TStrBoolIntIntStrTuple;
LOutXml, LOutIni, LOutBin: TStrBoolIntIntStrTuple;
begin
LInput := Tuple.Create('', true, Integer(222), Integer(188), 'Four__');
LOutXml := SerializeInXML<TStrBoolIntIntStrTuple>(LInput);
LOutIni := SerializeInIni<TStrBoolIntIntStrTuple>(LInput);
LOutBin := SerializeInBinary<TStrBoolIntIntStrTuple>(LInput);
CheckEquals(LInput.Value1, LOutXml.Value1, '[1] Xml serialization failed!');
CheckEquals(LInput.Value1, LOutIni.Value1, '[1] Ini serialization failed!');
CheckEquals(LInput.Value1, LOutBin.Value1, '[1] Binary serialization failed!');
CheckEquals(LInput.Value2, LOutXml.Value2, '[2] Xml serialization failed!');
CheckEquals(LInput.Value2, LOutIni.Value2, '[2] Ini serialization failed!');
CheckEquals(LInput.Value2, LOutBin.Value2, '[2] Binary serialization failed!');
CheckEquals(LInput.Value3, LOutXml.Value3, '[3] Xml serialization failed!');
CheckEquals(LInput.Value3, LOutIni.Value3, '[3] Ini serialization failed!');
CheckEquals(LInput.Value3, LOutBin.Value3, '[3] Binary serialization failed!');
CheckEquals(LInput.Value4, LOutXml.Value4, '[4] Xml serialization failed!');
CheckEquals(LInput.Value4, LOutIni.Value4, '[4] Ini serialization failed!');
CheckEquals(LInput.Value4, LOutBin.Value4, '[4] Binary serialization failed!');
CheckEquals(LInput.Value5, LOutXml.Value5, '[5] Xml serialization failed!');
CheckEquals(LInput.Value5, LOutIni.Value5, '[5] Ini serialization failed!');
CheckEquals(LInput.Value5, LOutBin.Value5, '[5] Binary serialization failed!');
end;
type
TByteStrBoolIntIntStrTuple = Tuple<Byte, string, Boolean, Integer, Integer, string>;
procedure TTestGrossSerialization.Test_Tuple_6;
var
LInput: TByteStrBoolIntIntStrTuple;
LOutXml, LOutIni, LOutBin: TByteStrBoolIntIntStrTuple;
begin
LInput := Tuple.Create(Byte(0), '', true, Integer(1999), Integer(188), 'Four__');
LOutXml := SerializeInXML<TByteStrBoolIntIntStrTuple>(LInput);
LOutIni := SerializeInIni<TByteStrBoolIntIntStrTuple>(LInput);
LOutBin := SerializeInBinary<TByteStrBoolIntIntStrTuple>(LInput);
CheckEquals(LInput.Value1, LOutXml.Value1, '[1] Xml serialization failed!');
CheckEquals(LInput.Value1, LOutIni.Value1, '[1] Ini serialization failed!');
CheckEquals(LInput.Value1, LOutBin.Value1, '[1] Binary serialization failed!');
CheckEquals(LInput.Value2, LOutXml.Value2, '[2] Xml serialization failed!');
CheckEquals(LInput.Value2, LOutIni.Value2, '[2] Ini serialization failed!');
CheckEquals(LInput.Value2, LOutBin.Value2, '[2] Binary serialization failed!');
CheckEquals(LInput.Value3, LOutXml.Value3, '[3] Xml serialization failed!');
CheckEquals(LInput.Value3, LOutIni.Value3, '[3] Ini serialization failed!');
CheckEquals(LInput.Value3, LOutBin.Value3, '[3] Binary serialization failed!');
CheckEquals(LInput.Value4, LOutXml.Value4, '[4] Xml serialization failed!');
CheckEquals(LInput.Value4, LOutIni.Value4, '[4] Ini serialization failed!');
CheckEquals(LInput.Value4, LOutBin.Value4, '[4] Binary serialization failed!');
CheckEquals(LInput.Value5, LOutXml.Value5, '[5] Xml serialization failed!');
CheckEquals(LInput.Value5, LOutIni.Value5, '[5] Ini serialization failed!');
CheckEquals(LInput.Value5, LOutBin.Value5, '[5] Binary serialization failed!');
CheckEquals(LInput.Value6, LOutXml.Value6, '[6] Xml serialization failed!');
CheckEquals(LInput.Value6, LOutIni.Value6, '[6] Ini serialization failed!');
CheckEquals(LInput.Value6, LOutBin.Value6, '[6] Binary serialization failed!');
end;
type
TTupByteStrBoolIntIntStrTuple = Tuple<TStrTuple, Byte, string, Boolean, Integer, Integer, string>;
procedure TTestGrossSerialization.Test_Tuple_7;
var
LInput: TTupByteStrBoolIntIntStrTuple;
LOutXml, LOutIni, LOutBin: TTupByteStrBoolIntIntStrTuple;
begin
LInput := Tuple.Create(Tuple.Create('Hello'), Byte(0), '', true, Integer(-5), Integer(188), 'Four__');
LOutXml := SerializeInXML<TTupByteStrBoolIntIntStrTuple>(LInput);
LOutIni := SerializeInIni<TTupByteStrBoolIntIntStrTuple>(LInput);
LOutBin := SerializeInBinary<TTupByteStrBoolIntIntStrTuple>(LInput);
CheckTrue(TType<TStrTuple>.Default.AreEqual(LInput.Value1, LOutXml.Value1), '[1] Xml serialization failed!');
CheckTrue(TType<TStrTuple>.Default.AreEqual(LInput.Value1, LOutIni.Value1), '[1] Ini serialization failed!');
CheckTrue(TType<TStrTuple>.Default.AreEqual(LInput.Value1, LOutBin.Value1), '[1] Binary serialization failed!');
CheckEquals(LInput.Value2, LOutXml.Value2, '[2] Xml serialization failed!');
CheckEquals(LInput.Value2, LOutIni.Value2, '[2] Ini serialization failed!');
CheckEquals(LInput.Value2, LOutBin.Value2, '[2] Binary serialization failed!');
CheckEquals(LInput.Value3, LOutXml.Value3, '[3] Xml serialization failed!');
CheckEquals(LInput.Value3, LOutIni.Value3, '[3] Ini serialization failed!');
CheckEquals(LInput.Value3, LOutBin.Value3, '[3] Binary serialization failed!');
CheckEquals(LInput.Value4, LOutXml.Value4, '[4] Xml serialization failed!');
CheckEquals(LInput.Value4, LOutIni.Value4, '[4] Ini serialization failed!');
CheckEquals(LInput.Value4, LOutBin.Value4, '[4] Binary serialization failed!');
CheckEquals(LInput.Value5, LOutXml.Value5, '[5] Xml serialization failed!');
CheckEquals(LInput.Value5, LOutIni.Value5, '[5] Ini serialization failed!');
CheckEquals(LInput.Value5, LOutBin.Value5, '[5] Binary serialization failed!');
CheckEquals(LInput.Value6, LOutXml.Value6, '[6] Xml serialization failed!');
CheckEquals(LInput.Value6, LOutIni.Value6, '[6] Ini serialization failed!');
CheckEquals(LInput.Value6, LOutBin.Value6, '[6] Binary serialization failed!');
CheckEquals(LInput.Value7, LOutXml.Value7, '[7] Xml serialization failed!');
CheckEquals(LInput.Value7, LOutIni.Value7, '[7] Ini serialization failed!');
CheckEquals(LInput.Value7, LOutBin.Value7, '[7] Binary serialization failed!');
end;
procedure TTestGrossSerialization.Test_WideCharSet;
var
LInput: TWideCharSet;
LOutXml, LOutIni, LOutBin: TWideCharSet;
begin
LInput := TWideCharSet.Create('637821');
LOutXml := SerializeInXML<TWideCharSet>(LInput);
LOutIni := SerializeInIni<TWideCharSet>(LInput);
LOutBin := SerializeInBinary<TWideCharSet>(LInput);
CheckTrue(LInput = LOutXml, '[charset] Xml serialization failed!');
CheckTrue(LInput = LOutIni, '[charset] Ini serialization failed!');
CheckTrue(LInput = LOutBin, '[charset] Bin serialization failed!');
end;
{ TTestEnexSerialization }
type
TIntStrDict = TDictionary<Integer, String>;
procedure TTestEnexSerialization.Test_Dictionary;
var
LInput: TIntStrDict;
LOutXml, LOutIni, LOutBin: TIntStrDict;
begin
LInput := TIntStrDict.Create();
LInput.Add(0, 'Hello');
LInput.Add(4, 'Serialization');
LInput.Add(2, 'You');
LInput.Add(8, '');
LInput.Add(3, 'Are');
LInput.Add(1, 'Now');
LInput.Add(9, 'Being');
LInput.Add(7, 'Tested');
LInput.Add(5, '.');
{LOutXml := nil;
LOutIni := nil;
LOutBin := nil;}
try
LOutXml := TTestGrossSerialization.SerializeInXML<TIntStrDict>(LInput);
LOutIni := TTestGrossSerialization.SerializeInIni<TIntStrDict>(LInput);
LOutBin := TTestGrossSerialization.SerializeInBinary<TIntStrDict>(LInput);
CheckTrue(LOutXml <> nil, 'LOutXml is nil');
CheckTrue(LOutIni <> nil, 'LOutIni is nil');
CheckTrue(LOutBin <> nil, 'LOutBin is nil');
CheckTrue(LOutXml.Includes(LInput), 'LOutXml did not read all');
CheckTrue(LOutIni.Includes(LInput), 'LOutIni did not read all');
CheckTrue(LOutBin.Includes(LInput), 'LOutBin did not read all');
CheckTrue(LInput.Includes(LOutXml), 'LOutXml did not read all');
CheckTrue(LInput.Includes(LOutIni), 'LOutIni did not read all');
CheckTrue(LInput.Includes(LOutBin), 'LOutBin did not read all');
finally
LInput.Free;
{LOutXml.Free; -- Ref counted
LOutIni.Free;
LOutBin.Free;}
end;
end;
type
TIntStrBDM = TDoubleSortedBiDiMap<Integer, String>;
procedure TTestEnexSerialization.Test_DoubleSortedBidiMap;
var
LInput: TIntStrBDM;
LOutXml, LOutIni, LOutBin: TIntStrBDM;
begin
LInput := TIntStrBDM.Create();
LInput.Add(0, 'Hello');
LInput.Add(4, 'Serialization');
LInput.Add(2, 'You');
LInput.Add(8, '');
LInput.Add(3, 'Are');
LInput.Add(1, 'Now');
LInput.Add(9, 'Being');
LInput.Add(7, 'Tested');
LInput.Add(5, '.');
{LOutXml := nil;
LOutIni := nil;
LOutBin := nil;}
try
LOutXml := TTestGrossSerialization.SerializeInXML<TIntStrBDM>(LInput);
LOutIni := TTestGrossSerialization.SerializeInIni<TIntStrBDM>(LInput);
LOutBin := TTestGrossSerialization.SerializeInBinary<TIntStrBDM>(LInput);
CheckTrue(LOutXml <> nil, 'LOutXml is nil');
CheckTrue(LOutIni <> nil, 'LOutIni is nil');
CheckTrue(LOutBin <> nil, 'LOutBin is nil');
CheckTrue(LOutXml.Includes(LInput), 'LOutXml did not read all');
CheckTrue(LOutIni.Includes(LInput), 'LOutIni did not read all');
CheckTrue(LOutBin.Includes(LInput), 'LOutBin did not read all');
CheckTrue(LInput.Includes(LOutXml), 'LOutXml did not read all');
CheckTrue(LInput.Includes(LOutIni), 'LOutIni did not read all');
CheckTrue(LInput.Includes(LOutBin), 'LOutBin did not read all');
finally
LInput.Free;
{LOutXml.Free; -- Ref counted
LOutIni.Free;
LOutBin.Free;}
end;
end;
type
TStringList = TList<String>;
procedure TTestEnexSerialization.Test_List;
var
LInput: TStringList;
LOutXml, LOutIni, LOutBin: TStringList;
begin
LInput := TStringList.Create();
LInput.Add('Hello');
LInput.Add('Serialization');
LInput.Add('You');
LInput.Add('');
LInput.Add('Are');
LInput.Add('Now');
LInput.Add('Being');
LInput.Add('Tested');
LInput.Add('.');
{LOutXml := nil;
LOutIni := nil;
LOutBin := nil;}
try
LOutXml := TTestGrossSerialization.SerializeInXML<TStringList>(LInput);
LOutIni := TTestGrossSerialization.SerializeInIni<TStringList>(LInput);
LOutBin := TTestGrossSerialization.SerializeInBinary<TStringList>(LInput);
CheckTrue(LOutXml <> nil, 'LOutXml is nil');
CheckTrue(LOutIni <> nil, 'LOutIni is nil');
CheckTrue(LOutBin <> nil, 'LOutBin is nil');
CheckTrue(LOutXml.EqualsTo(LInput), 'LOutXml did not read all');
CheckTrue(LOutIni.EqualsTo(LInput), 'LOutIni did not read all');
CheckTrue(LOutBin.EqualsTo(LInput), 'LOutBin did not read all');
finally
LInput.Free;
{LOutXml.Free; -- Ref counted
LOutIni.Free;
LOutBin.Free;}
end;
end;
type
TSortedStringList = TSortedList<String>;
procedure TTestEnexSerialization.Test_SortedList;
var
LInput: TSortedStringList;
LOutXml, LOutIni, LOutBin: TSortedStringList;
begin
LInput := TSortedStringList.Create(false);
LInput.Add('Hello');
LInput.Add('Serialization');
LInput.Add('You');
LInput.Add('');
LInput.Add('Are');
LInput.Add('Now');
LInput.Add('Being');
LInput.Add('Tested');
LInput.Add('.');
{LOutXml := nil;
LOutIni := nil;
LOutBin := nil;}
try
LOutXml := TTestGrossSerialization.SerializeInXML<TSortedStringList>(LInput);
LOutIni := TTestGrossSerialization.SerializeInIni<TSortedStringList>(LInput);
LOutBin := TTestGrossSerialization.SerializeInBinary<TSortedStringList>(LInput);
CheckTrue(LOutXml <> nil, 'LOutXml is nil');
CheckTrue(LOutIni <> nil, 'LOutIni is nil');
CheckTrue(LOutBin <> nil, 'LOutBin is nil');
CheckTrue(LOutXml.EqualsTo(LInput), 'LOutXml did not read all');
CheckTrue(LOutIni.EqualsTo(LInput), 'LOutIni did not read all');
CheckTrue(LOutBin.EqualsTo(LInput), 'LOutBin did not read all');
finally
LInput.Free;
{LOutXml.Free; -- Ref counted
LOutIni.Free;
LOutBin.Free;}
end;
end;
initialization
TestFramework.RegisterTest(TTestGrossSerialization.Suite);
TestFramework.RegisterTest(TTestEnexSerialization.Suite);
end.
|
unit BoardRepresentation;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Dialogs;
type
TBoardPoint = class
private
function findPlace(moveUp, moveRight: integer): integer;
protected
public
pt: integer; // 00 00 00 00 00 00 00 00
//pierwszy bit: czy zajęta góra, drugi bit: czy przez pierwszego gracza.
constructor Create();
procedure addMove(moveUp, moveRight, byWho: integer);
//moveUp = 1 - do góry, moveUp = 0 - nic, moveUp = -1 - do dołu etc.
procedure removeMove(moveUp, moveRight: integer);
function isFree(): boolean;
function isFreeLine(direction: integer): boolean;
function noWayOut(): boolean;//sprawdza czy wszystkie kierunki są zajęte
end;
TSegment = class
private
protected
public
fromx: integer;
fromy: integer;
tox: integer;
toy: integer;
byWho: integer;
procedure setSegment(fx, fy, tx, ty, who: integer);
constructor Create();
procedure write();
end;
TMove = class
private
container: TList;
protected
public
finished: boolean;
procedure addToMe(var another: TMove);
procedure addToMe(var moveRep: TSegment);
constructor Create();
constructor CreateFinished();
destructor Destroy(); override;
function getContainer(): TList;
function isEmpty(): boolean;
procedure clean();
procedure Write();
end;
TPossibleMoves = class
public
counter: integer;
function Next(): TPoint;
constructor Create();
procedure reset();
private
moves: array[0..7] of TPoint;
end;
TBoardRep = class
const
MAX_SIZE = 15;
public
ballPosX, ballPosY: integer;
sizeX, sizeY: integer;
points: array [-1..MAX_SIZE + 1, -2..MAX_SIZE + 2] of TBoardPoint; //x, y
constructor Create();
function giveMoves(): TMove;
procedure setSize(x, y: integer);
procedure addMove(fromx, fromy, tox, toy, who: integer);
procedure setBallPos(x, y: integer);
function isLineFree(fromX, fromY, toX, toY: integer): boolean;
procedure removeMove(fromx, fromy, tox, toy: integer);
private
posMoves: TPossibleMoves;
procedure borders();
protected
end;
implementation
constructor TBoardRep.Create();
var
counterx, countery: integer;
begin
for counterx := -1 to MAX_SIZE + 1 do
begin
for countery := -2 to MAX_SIZE + 2 do
begin
self.points[counterx, countery] := TBoardPoint.Create();
end;
end;
posMoves := TPossibleMoves.Create;
end;
function TBoardRep.giveMoves(): TMove;
begin
end;
procedure TBoardRep.setSize(x, y: integer);
begin
self.sizeX := x;
self.sizeY := y;
self.borders();
end;
procedure TBoardRep.addMove(fromx, fromy, tox, toy, who: integer);
begin
self.points[fromx, fromy].addMove(fromx - tox, toy - fromy, who);
self.points[tox, toy].addMove(tox - fromx, fromy - toy, who);
ballPosX := tox;
ballPosY := toy;
end;
procedure TBoardRep.setBallPos(x, y: integer);
begin
ballPosX := x;
ballPosY := y;
end;
procedure TMove.addToMe(var another: TMove);
begin
container.AddList(another.getContainer());
end;
procedure TMove.addToMe(var moveRep: TSegment);
begin
container.Add(@moveRep);
end;
constructor TMove.Create();
begin
container := TList.Create;
self.finished := False;
end;
destructor TMove.Destroy();
begin
container.Destroy();
end;
function TMove.getContainer: TList;
begin
getContainer := container;
end;
procedure TBoardPoint.addMove(moveUp, moveRight, byWho: integer);
var
place, by1: integer;
begin
place := self.findPlace(moveUp, moveRight);
if byWho = 1 then
by1 := 1
else
by1 := 0;
pt := (pt) or ((1 shl place) or (by1 shl (place + 1)));
end;
constructor TBoardPoint.Create();
begin
pt := 0;
end;
function TBoardPoint.isFree(): boolean;
var
counter, i: integer;
begin
counter := 0;
for i := 0 to 7 do
begin
counter := counter + ((self.pt shr (i * 2)) and 1);
end;
isFree := counter <= 1;
end;
constructor TPossibleMoves.Create();
var
tempTPoint: TPoint; //x - gora, y - prawo
begin
counter := 0;
tempTPoint.X := 1;
tempTPoint.Y := 0;
moves[0] := tempTPoint;//gora
tempTPoint.Y := 1;
moves[1] := tempTPoint; //gora i prawo
tempTPoint.X := 0;
moves[2] := tempTPoint; //prawo
tempTPoint.X := -1;
moves[3] := tempTPoint; //prawo i dol
tempTPoint.Y := 0;
moves[4] := tempTPoint; //dol
tempTPoint.Y := -1;
moves[5] := tempTPoint; //dol i lewo
tempTPoint.X := 0;
moves[6] := tempTPoint; //lewo
tempTPoint.X := 1;
moves[7] := tempTPoint; //gora i lewo
end;
function TPossibleMoves.Next(): TPoint;
begin
counter := counter + 1;
Next := moves[counter - 1];
end;
procedure TPossibleMoves.reset();
begin
counter := 0;
end;
function TBoardRep.isLineFree(fromX, fromY, toX, toY: integer): boolean;
var
tempPoint, vector: TPoint;
begin
posMoves.reset();
tempPoint := posMoves.Next();
vector.X := fromX - toX;
vector.Y := toY - fromY;
while ((vector.X <> tempPoint.X) or (vector.Y <> tempPoint.Y)) do
begin
tempPoint := posMoves.Next();
end;
isLineFree := self.points[fromX, fromY].isFreeLine(posMoves.counter - 1);
end;
function TBoardPoint.isFreeLine(direction: integer): boolean;
begin
isFreeLine := ((self.pt shr (direction * 2)) and 1) = 0;
end;
procedure TBoardRep.borders();
var
counter: integer;
begin
//boki
for counter := 0 to self.sizeY do
begin
self.addMove(0, counter, 0, counter + 1, 0);
self.addMove(0, counter, -1, counter, 0);
self.addMove(0, counter, -1, counter - 1, 0);
self.addMove(0, counter, -1, counter + 1, 0);
self.addMove(self.sizeX, counter, self.sizeX, counter + 1, 0);
self.addMove(self.sizeX, counter, self.sizeX + 1, counter, 0);
self.addMove(self.sizeX, counter, self.sizeX + 1, counter - 1, 0);
self.addMove(self.sizeX, counter, self.sizeX + 1, counter + 1, 0);
end;
//góra i dół
for counter := 0 to self.sizeX div 2 - 2 do
begin
self.addMove(counter, 0, counter + 1, 0, 0);
self.addMove(counter, 0, counter - 1, -1, 0);
self.addMove(counter, 0, counter + 1, -1, 0);
self.addMove(counter, 0, counter, -1, 0);
self.addMove(counter, self.sizeY, counter + 1, self.sizeY, 0);
self.addMove(counter, self.sizeY, counter - 1, self.sizeY + 1, 0);
self.addMove(counter, self.sizeY, counter + 1, self.sizeY + 1, 0);
self.addMove(counter, self.sizeY, counter, self.sizeY + 1, 0);
end;
for counter := self.sizeX downto self.sizeX div 2 + 2 do
begin
self.addMove(counter, 0, counter - 1, 0, 0);
self.addMove(counter, 0, counter - 1, -1, 0);
self.addMove(counter, 0, counter + 1, -1, 0);
self.addMove(counter, 0, counter, -1, 0);
self.addMove(counter, self.sizeY, counter - 1, self.sizeY, 0);
self.addMove(counter, self.sizeY, counter - 1, self.sizeY + 1, 0);
self.addMove(counter, self.sizeY, counter + 1, self.sizeY + 1, 0);
self.addMove(counter, self.sizeY, counter, self.sizeY + 1, 0);
end;
//bramki
for counter := self.sizeX div 2 - 1 to self.sizeX div 2 do
begin
self.addMove(counter, -1, counter + 1, -1, 0);
self.addMove(counter, self.sizeY + 1, counter + 1, self.sizeY + 1, 0);
end;
self.addMove(self.sizeX div 2 - 1, 0, self.sizeX div 2 - 1, -1, 0);
self.addMove(self.sizeX div 2 - 1, self.sizeY, self.sizeX div 2 -
1, self.sizeY + 1, 0);
self.addMove(self.sizeX div 2 + 1, 0, self.sizeX div 2 + 1, -1, 0);
self.addMove(self.sizeX div 2 + 1, self.sizeY, self.sizeX div 2 +
1, self.sizeY + 1, 0);
end;
function TBoardPoint.noWayOut(): boolean;
var
counter, i: integer;
begin
counter := 0;
for i := 0 to 7 do
begin
counter := counter + ((self.pt shr (i * 2)) and 1);
end;
noWayOut := counter = 8;
end;
function TMove.isEmpty(): boolean;
begin
isEmpty := self.container.Count = 0;
end;
constructor TMove.CreateFinished();
begin
self.finished := True;
end;
procedure TMove.clean();
begin
while self.container.Count > 0 do
begin
self.container.Remove(self.container.First);
end;
self.finished := False;
end;
procedure TMove.Write();
var
i: integer;
temp: ^TSegment;
begin
for i := 0 to self.container.Count - 1 do
begin
temp := self.container.Items[i];
//ShowMessage(IntToStr(temp^.x) + ' ' + IntToStr(temp^.y));
end;
end;
constructor TSegment.Create();
begin
end;
procedure TSegment.setSegment(fx, fy, tx, ty, who: integer);
begin
fromx := fx;
fromy := fy;
tox := tx;
toy := ty;
byWho := who;
end;
procedure TBoardRep.removeMove(fromx, fromy, tox, toy: integer);
begin
self.points[fromx, fromy].removeMove(fromx - tox, toy - fromy);
self.points[tox, toy].removeMove(tox - fromx, fromy - toy);
ballPosX := tox;
ballPosY := toy;
end;
function TBoardPoint.findPlace(moveUp, moveRight: integer): integer;
var
place: integer;
begin
if moveUp = 1 then
begin
if moveRight = 1 then
begin
place := 2;
end
else if moveRight = 0 then
begin
place := 0;
end
else
begin
place := 14;
end;
end
else if moveUp = 0 then
begin
if moveRight = 1 then
begin
place := 4;
end
else if moveRight = 0 then
begin
//impossible
end
else
begin
place := 12;
end;
end
else
begin
if moveRight = 1 then
begin
place := 6;
end
else if moveRight = 0 then
begin
place := 8;
end
else
begin
place := 10;
end;
end;
findPlace := place;
end;
procedure TBoardPoint.removeMove(moveUp, moveRight: integer);
var
place: integer;
begin
place := self.findPlace(moveUp, moveRight);
pt := (pt) and ((not (1 shl place)) and (not(1 shl (place + 1))));
end;
procedure TSegment.write();
begin
ShowMessage( ' segment: ' +
IntToStr(fromx) + ' ' + IntToStr(fromy) +
' ' + IntToStr(tox) + ' ' + IntToStr(toy) +
' ' + IntToStr(byWho));
end;
end.
|
{-------------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
Code template generated with SynGen.
The original code is: SynHighlighterScilab.pas, released 2003-08-04.
Description: Syntax Parser/Highlighter
The initial author of this file is Stefan Ascher.
Copyright (c) 2003, all rights reserved.
Contributors to the SynEdit and mwEdit projects are listed in the
Contributors.txt file.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
$Id: SynHighlighterScilab.pas,v 1.1.2.1 2003/08/13 00:38:45 neum Exp $
You may retrieve the latest version of this file at the SynEdit home page,
located at http://SynEdit.SourceForge.net
-------------------------------------------------------------------------------}
unit SynHighlighterScilab;
{$I SynEdit.inc}
interface
uses
SysUtils,
Classes,
{$IFDEF SYN_CLX}
QControls,
QGraphics,
{$ELSE}
Windows,
Controls,
Graphics,
{$ENDIF}
SynEditTypes,
SynEditHighlighter;
type
TtkTokenKind = (
tkComment,
tkIdentifier,
tkKey,
tkNull,
tkSpace,
tkString,
tkUnknown);
TRangeState = (rsUnKnown, rsComment, rsString);
TProcTableProc = procedure of object;
PIdentFuncTableFunc = ^TIdentFuncTableFunc;
TIdentFuncTableFunc = function: TtkTokenKind of object;
const
MaxKey = 136;
type
TSynScilabSyn = class(TSynCustomHighlighter)
private
fLine: PChar;
fLineNumber: Integer;
fProcTable: array[#0..#255] of TProcTableProc;
fRange: TRangeState;
Run: LongInt;
fStringLen: Integer;
fToIdent: PChar;
fTokenPos: Integer;
fTokenID: TtkTokenKind;
fIdentFuncTable: array[0 .. MaxKey] of TIdentFuncTableFunc;
fCommentAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fKeyAttri: TSynHighlighterAttributes;
fSpaceAttri: TSynHighlighterAttributes;
fStringAttri: TSynHighlighterAttributes;
function KeyHash(ToHash: PChar): Integer;
function KeyComp(const aKey: string): Boolean;
function Func21: TtkTokenKind;
function Func26: TtkTokenKind;
function Func32: TtkTokenKind;
function Func42: TtkTokenKind;
function Func44: TtkTokenKind;
function Func45: TtkTokenKind;
function Func51: TtkTokenKind;
function Func62: TtkTokenKind;
function Func70: TtkTokenKind;
function Func136: TtkTokenKind;
procedure IdentProc;
procedure UnknownProc;
function AltFunc: TtkTokenKind;
procedure InitIdent;
function IdentKind(MayBe: PChar): TtkTokenKind;
procedure MakeMethodTables;
procedure NullProc;
procedure SpaceProc;
procedure CRProc;
procedure LFProc;
procedure OpenProc;
procedure CommentProc;
procedure StringOpenProc;
procedure StringProc;
protected
function GetIdentChars: TSynIdentChars; override;
function GetSampleSource: string; override;
function IsFilterStored: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
{$IFNDEF SYN_CPPB_1} class {$ENDIF}
function GetLanguageName: string; override;
function GetRange: Pointer; override;
procedure ResetRange; override;
procedure SetRange(Value: Pointer); override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override;
function GetEol: Boolean; override;
function GetKeyWords: string;
function GetTokenID: TtkTokenKind;
procedure SetLine(NewValue: String; LineNumber: Integer); override;
function GetToken: String; override;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetTokenKind: integer; override;
function GetTokenPos: Integer; override;
procedure Next; override;
published
property CommentAttri: TSynHighlighterAttributes read fCommentAttri write fCommentAttri;
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri write fIdentifierAttri;
property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri;
property StringAttri: TSynHighlighterAttributes read fStringAttri write fStringAttri;
end;
procedure Register;
implementation
uses
SynEditStrConst;
{$IFDEF SYN_COMPILER_3_UP}
resourcestring
{$ELSE}
const
{$ENDIF}
SYNS_FilterScilab = 'Scilab files (*.sce;*.sci)|*.sce;*.sci';
SYNS_LangScilab = 'Scilab';
var
Identifiers: array[#0..#255] of ByteBool;
mHashTable : array[#0..#255] of Integer;
procedure Register;
begin
RegisterComponents(SYNS_HighlightersPage, [TSynScilabSyn]);
end;
procedure MakeIdentTable;
var
I: Char;
begin
for I := #0 to #255 do
begin
case I of
'_', 'a'..'z', 'A'..'Z': Identifiers[I] := True;
else
Identifiers[I] := False;
end;
case I in ['_', 'A'..'Z', 'a'..'z'] of
True:
begin
if (I > #64) and (I < #91) then
mHashTable[I] := Ord(I) - 64
else if (I > #96) then
mHashTable[I] := Ord(I) - 95;
end;
else
mHashTable[I] := 0;
end;
end;
end;
procedure TSynScilabSyn.InitIdent;
var
I: Integer;
pF: PIdentFuncTableFunc;
begin
pF := PIdentFuncTableFunc(@fIdentFuncTable);
for I := Low(fIdentFuncTable) to High(fIdentFuncTable) do
begin
pF^ := AltFunc;
Inc(pF);
end;
fIdentFuncTable[21] := Func21;
fIdentFuncTable[26] := Func26;
fIdentFuncTable[32] := Func32;
fIdentFuncTable[42] := Func42;
fIdentFuncTable[44] := Func44;
fIdentFuncTable[45] := Func45;
fIdentFuncTable[51] := Func51;
fIdentFuncTable[62] := Func62;
fIdentFuncTable[70] := Func70;
fIdentFuncTable[136] := Func136;
end;
function TSynScilabSyn.KeyHash(ToHash: PChar): Integer;
begin
Result := 0;
while ToHash^ in ['_', 'a'..'z', 'A'..'Z'] do
begin
inc(Result, mHashTable[ToHash^]);
inc(ToHash);
end;
fStringLen := ToHash - fToIdent;
end;
function TSynScilabSyn.KeyComp(const aKey: String): Boolean;
var
I: Integer;
Temp: PChar;
begin
Temp := fToIdent;
if Length(aKey) = fStringLen then
begin
Result := True;
for i := 1 to fStringLen do
begin
if Temp^ <> aKey[i] then
begin
Result := False;
break;
end;
inc(Temp);
end;
end else Result := False;
end;
function TSynScilabSyn.Func21: TtkTokenKind;
begin
if KeyComp('do') then Result := tkKey else Result := tkIdentifier;
end;
function TSynScilabSyn.Func26: TtkTokenKind;
begin
if KeyComp('end') then Result := tkKey else Result := tkIdentifier;
end;
function TSynScilabSyn.Func32: TtkTokenKind;
begin
if KeyComp('case') then Result := tkKey else Result := tkIdentifier;
end;
function TSynScilabSyn.Func42: TtkTokenKind;
begin
if KeyComp('for') then Result := tkKey else
if KeyComp('break') then Result := tkKey else Result := tkIdentifier;
end;
function TSynScilabSyn.Func44: TtkTokenKind;
begin
if KeyComp('clear') then Result := tkKey else Result := tkIdentifier;
end;
function TSynScilabSyn.Func45: TtkTokenKind;
begin
if KeyComp('else') then Result := tkKey else Result := tkIdentifier;
end;
function TSynScilabSyn.Func51: TtkTokenKind;
begin
if KeyComp('then') then Result := tkKey else Result := tkIdentifier;
end;
function TSynScilabSyn.Func62: TtkTokenKind;
begin
if KeyComp('while') then Result := tkKey else
if KeyComp('elseif') then Result := tkKey else Result := tkIdentifier;
end;
function TSynScilabSyn.Func70: TtkTokenKind;
begin
if KeyComp('select') then Result := tkKey else Result := tkIdentifier;
end;
function TSynScilabSyn.Func136: TtkTokenKind;
begin
if KeyComp('endfunction') then Result := tkKey else Result := tkIdentifier;
end;
function TSynScilabSyn.AltFunc: TtkTokenKind;
begin
Result := tkIdentifier;
end;
function TSynScilabSyn.IdentKind(MayBe: PChar): TtkTokenKind;
var
HashKey: Integer;
begin
fToIdent := MayBe;
HashKey := KeyHash(MayBe);
if HashKey <= MaxKey then
Result := fIdentFuncTable[HashKey]
else
Result := tkIdentifier;
end;
procedure TSynScilabSyn.MakeMethodTables;
var
I: Char;
begin
for I := #0 to #255 do
case I of
#0: fProcTable[I] := NullProc;
#10: fProcTable[I] := LFProc;
#13: fProcTable[I] := CRProc;
'"': fProcTable[I] := StringOpenProc;
#1..#9,
#11,
#12,
#14..#32 : fProcTable[I] := SpaceProc;
'A'..'Z', 'a'..'z', '_': fProcTable[I] := IdentProc;
'/': fProcTable[I] := OpenProc;
else
fProcTable[I] := UnknownProc;
end;
end;
procedure TSynScilabSyn.SpaceProc;
begin
fTokenID := tkSpace;
repeat
inc(Run);
until not (fLine[Run] in [#1..#32]);
end;
procedure TSynScilabSyn.NullProc;
begin
fTokenID := tkNull;
end;
procedure TSynScilabSyn.CRProc;
begin
fTokenID := tkSpace;
inc(Run);
if fLine[Run] = #10 then
inc(Run);
end;
procedure TSynScilabSyn.LFProc;
begin
fTokenID := tkSpace;
inc(Run);
end;
procedure TSynScilabSyn.OpenProc;
begin
Inc(Run);
fRange := rsComment;
CommentProc;
fTokenID := tkComment;
end;
procedure TSynScilabSyn.CommentProc;
begin
fTokenID := tkComment;
repeat
if (fLine[Run] = '/') and
(fLine[Run + 1] = '/') then
begin
Inc(Run, 2);
fRange := rsUnKnown;
Break;
end;
if not (fLine[Run] in [#0, #10, #13]) then
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
procedure TSynScilabSyn.StringOpenProc;
begin
Inc(Run);
fRange := rsString;
StringProc;
fTokenID := tkString;
end;
procedure TSynScilabSyn.StringProc;
begin
fTokenID := tkString;
repeat
if (fLine[Run] = '"') then
begin
Inc(Run, 1);
fRange := rsUnKnown;
Break;
end;
if not (fLine[Run] in [#0, #10, #13]) then
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
constructor TSynScilabSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fCommentAttri := TSynHighLighterAttributes.Create(SYNS_AttrComment);
fCommentAttri.Style := [fsItalic];
fCommentAttri.Foreground := clNavy;
AddAttribute(fCommentAttri);
fIdentifierAttri := TSynHighLighterAttributes.Create(SYNS_AttrIdentifier);
AddAttribute(fIdentifierAttri);
fKeyAttri := TSynHighLighterAttributes.Create(SYNS_AttrReservedWord);
fKeyAttri.Style := [fsBold];
AddAttribute(fKeyAttri);
fSpaceAttri := TSynHighLighterAttributes.Create(SYNS_AttrSpace);
AddAttribute(fSpaceAttri);
fStringAttri := TSynHighLighterAttributes.Create(SYNS_AttrString);
fStringAttri.Foreground := clRed;
AddAttribute(fStringAttri);
SetAttributesOnChange(DefHighlightChange);
InitIdent;
MakeMethodTables;
fDefaultFilter := SYNS_FilterScilab;
fRange := rsUnknown;
end;
procedure TSynScilabSyn.SetLine(NewValue: String; LineNumber: Integer);
begin
fLine := PChar(NewValue);
Run := 0;
fLineNumber := LineNumber;
Next;
end;
procedure TSynScilabSyn.IdentProc;
begin
fTokenID := IdentKind((fLine + Run));
inc(Run, fStringLen);
while Identifiers[fLine[Run]] do
Inc(Run);
end;
procedure TSynScilabSyn.UnknownProc;
begin
{$IFDEF SYN_MBCSSUPPORT}
if FLine[Run] in LeadBytes then
Inc(Run,2)
else
{$ENDIF}
inc(Run);
fTokenID := tkUnknown;
end;
procedure TSynScilabSyn.Next;
begin
fTokenPos := Run;
fRange := rsUnknown;
fProcTable[fLine[Run]];
end;
function TSynScilabSyn.GetDefaultAttribute(Index: integer): TSynHighLighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT : Result := fCommentAttri;
SYN_ATTR_IDENTIFIER : Result := fIdentifierAttri;
SYN_ATTR_KEYWORD : Result := fKeyAttri;
SYN_ATTR_STRING : Result := fStringAttri;
SYN_ATTR_WHITESPACE : Result := fSpaceAttri;
else
Result := nil;
end;
end;
function TSynScilabSyn.GetEol: Boolean;
begin
Result := fTokenID = tkNull;
end;
function TSynScilabSyn.GetKeyWords: string;
begin
Result :=
'break,case,clear,do,else,elseif,end,endfunction,for,select,then,while';
end;
function TSynScilabSyn.GetToken: String;
var
Len: LongInt;
begin
Len := Run - fTokenPos;
SetString(Result, (FLine + fTokenPos), Len);
end;
function TSynScilabSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function TSynScilabSyn.GetTokenAttribute: TSynHighLighterAttributes;
begin
case GetTokenID of
tkComment: Result := fCommentAttri;
tkIdentifier: Result := fIdentifierAttri;
tkKey: Result := fKeyAttri;
tkSpace: Result := fSpaceAttri;
tkString: Result := fStringAttri;
tkUnknown: Result := fIdentifierAttri;
else
Result := nil;
end;
end;
function TSynScilabSyn.GetTokenKind: integer;
begin
Result := Ord(fTokenId);
end;
function TSynScilabSyn.GetTokenPos: Integer;
begin
Result := fTokenPos;
end;
function TSynScilabSyn.GetIdentChars: TSynIdentChars;
begin
Result := ['_', 'a'..'z', 'A'..'Z'];
end;
function TSynScilabSyn.GetSampleSource: string;
begin
Result := '// Syntax highlighting'#13#10 +
'function[p1, p2] = myfunc(x, y)'#13#10 +
' i = 123456'#13#10 +
' for j = y:i,'#13#10 +
' if j = x then'#13#10 +
' p2 = 2i // Complex Number'#13#10 +
' p1 = 3.5E2 // Float Number with exponent'#13#10 +
' somestr = "This is a string"'#13#10 +
' end'#13#10 +
' end'#13#10 +
'endfunction';
end;
function TSynScilabSyn.IsFilterStored: Boolean;
begin
Result := fDefaultFilter <> SYNS_FilterScilab;
end;
{$IFNDEF SYN_CPPB_1} class {$ENDIF}
function TSynScilabSyn.GetLanguageName: string;
begin
Result := SYNS_LangScilab;
end;
procedure TSynScilabSyn.ResetRange;
begin
fRange := rsUnknown;
end;
procedure TSynScilabSyn.SetRange(Value: Pointer);
begin
fRange := TRangeState(Value);
end;
function TSynScilabSyn.GetRange: Pointer;
begin
Result := Pointer(fRange);
end;
initialization
MakeIdentTable;
{$IFNDEF SYN_CPPB_1}
RegisterPlaceableHighlighter(TSynScilabSyn);
{$ENDIF}
end.
|
unit JWTTests;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
SysUtils,
StringSupport, GuidSupport,
AdvObjects, AdvJson,
libeay32, JWT,
DUnitX.TestFramework;
Type
[TextFixture]
TJWTTests = Class (TObject)
Private
Published
[SetUp]
procedure Setup;
[TestCase]
procedure TestPacking;
[TestCase]
procedure TestUnpacking;
[TestCase]
procedure TestCert;
End;
Implementation
uses
IdSSLOpenSSLHeaders;
var
gs : String;
{ TJWTTests }
procedure TJWTTests.Setup;
begin
IdSSLOpenSSLHeaders.Load;
LoadEAYExtensions;
end;
procedure TJWTTests.TestCert;
var
jwk : TJWK;
s: String;
begin
jwk := TJWTUtils.loadKeyFromRSACert('C:\work\fhirserver\Exec\jwt-test.key.crt');
try
s := TJSONWriter.writeObjectStr(jwk.obj, true);
Writeln(s);
Assert.IsTrue(true);
finally
jwk.Free;
end;
end;
procedure TJWTTests.TestPacking;
var
jwk : TJWK;
s : String;
jwt : TJWT;
begin
jwk := TJWK.create(TJSONParser.Parse('{"kty": "oct", "k": "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"}'));
try
// this test is from the spec
s := TJWTUtils.pack(
'{"typ":"JWT",'+#13#10+' "alg":"HS256"}',
'{"iss":"joe",'+#13#10+' "exp":1300819380,'+#13#10+' "http://example.com/is_root":true}',
jwt_hmac_sha256, jwk);
Assert.IsTrue(s = 'eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk',
'packing failed. expected '+#13#10+'eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk, but got '+s);
finally
jwk.Free;
end;
jwk := TJWK.create(TJSONParser.Parse(
'{"kty":"RSA", '+#13#10+
' "kid": "http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-26#appendix-A.2.1", '+#13#10+
' "n":"ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdb'+'BYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ", '+#13#10+
' "e":"AQAB", '+#13#10+
' "d":"Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97IjlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn439X0M_V51gfpR'+'LI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYTCBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLhBOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ" '+#13#10+
' } '+#13#10
));
try
gs := TJWTUtils.pack(
'{"alg":"RS256"}',
'{"iss":"joe",'+#13#10+' "exp":1300819380,'+#13#10+' "http://example.com/is_root":true}',
jwt_hmac_rsa256, jwk);
finally
jwk.Free;
end;
jwt := TJWT.create;
try
jwt.id := GUIDToString(CreateGUID);
s := TJWTUtils.rsa_pack(jwt, jwt_hmac_rsa256, 'C:\work\fhirserver\Exec\jwt-test.key.key', 'fhirserver');
Assert.isTrue(true);
finally
jwt.Free;
end;
end;
var
jwk : TJWKList;
procedure TJWTTests.TestUnpacking;
var
jwt : TJWT;
begin
// HS256 test from the spec
jwk := TJWKList.create(TJSONParser.Parse('{"kty": "oct", "k": "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"}'));
try
jwt := TJWTUtils.unpack('eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk', true, jwk);
try
// inspect
Assert.IsTrue(true);
finally
jwt.Free;
end;
finally
jwk.Free;
end;
(*
// from google
jwk := TJWKList.create(TJSONParser.Parse(
// as downloaded from google at the same time as the JWT below
'{'+#13#10+
' "keys": ['+#13#10+
' {'+#13#10+
' "kty": "RSA",'+#13#10+
' "alg": "RS256",'+#13#10+
' "use": "sig",'+#13#10+
' "kid": "024806d09e6067ca21bc6e25219d15dd981ddf9d",'+#13#10+
' "n": "AKGBohjSehyKnx7t5HZGzLtNaFpbNBiCf9O6G/qUeOy8l7XBflg/79G+t23eP77dJ+iCPEoLU1R/3NKPAk6Y6hKbSIvuzLY+B877ozutOn/6H/DNWumVZKnkSpDa7A5nsCNSm63b7uJ4XO5W0NtueiXj855h8j+WLi9vP8UwXhmL",'+#13#10+
' "e": "AQAB"'+#13#10+
' },'+#13#10+
' {'+#13#10+
' "kty": "RSA",'+#13#10+
' "alg": "RS256",'+#13#10+
' "use": "sig",'+#13#10+
' "kid": "8140c5f1c9d0c738c1b6328528f7ab1f672f5ba0",'+#13#10+
' "n": "AMAxJozHjwYxXqcimf93scqnDKZrKm1O4+TSH4eTJyjM1NU1DnhRJ8xL8fJd/rZwBWgPCUNi34pYlLWwfzR/17diqPgGSMt+mBVKXo5HD7+9SfQPjH3Fw810BQpxslBuAPsSGaNcLvHPpUSJDB/NH2rTxw6YtQ/R3neo7Amcfn/d",'+#13#10+
' "e": "AQAB"'+#13#10+
' }'+#13#10+
' ]'+#13#10+
'}'+#13#10
));
try
jwt := TJWTUtils.unpack('eyJhbGciOiJSUzI1NiIsImtpZCI6IjAyNDgwNmQwOWU2MDY3Y2EyMWJjNmUyNTIxOWQxNWRkOTgxZGRmOWQifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTExOTA0NjIwMDUzMzY0MzkyMjg2Ii'+'wiYXpwIjoiOTQwMDA2MzEwMTM4LmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJncmFoYW1lZ0BnbWFpbC5jb20iLCJhdF9oYXNoIjoidDg0MGJMS3FsRU'+'ZqUmQwLWlJS2dZUSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJhdWQiOiI5NDAwMDYzMTAxMzguYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJpYXQiOjE0MDIxODUxMjksImV'+'4cCI6MTQwMjE4OTAyOX0.Jybn06gURs7lcpCYaXBuszC7vacnWxwSwH_ffIDDu7bxOPo9fiVnRDCidKSLy4m0sAL1xxDHA5gXSZ9C6nj7abGqQ_LOrcPdTncuvYUPhF7mUq7fr3EPW-34PVkBSiOrjYdO6SOYyeP443WzPQRkhVJkRP4oQF-k0zXuwCkWlfc', true, jwk);
try
// inspect
Assert.IsTrue(true);
finally
jwt.Free;
end;
finally
jwk.free;
end;
// RS256 test from the spec (except the value is from above, because the sig doesn't match)
jwk := TJWKList.create(TJSONParser.Parse(
'{"kty":"RSA", '+#13#10+
' "kid": "http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-26#appendix-A.2.1", '+#13#10+
' "n":"ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddxHmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMsD1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSHSXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg66'+'5xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ", '+#13#10+
' "e":"AQAB", '+#13#10+
' "d":"Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97IjlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvX'+'t4ehNYTCBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLhBOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ" '+#13#10+
' } '+#13#10
));
try
jwt := TJWTUtils.unpack(gs {'eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.LteI-Jtns1KTLm0-lnDU_gI8_QHDnnIfZCEB2dI-ix4YxLQjaOTVQolkaa-Y4Cie-mEd8c34vSWeeNRgVcXuJsZ_iVYywDWqUDpXY6KwdMx6kXZQ0-'+'mihsowKzrFbmhUWun2aGOx44w3wAxHpU5cqE55B0wx2v_f98zUojMp6mkje_pFRdgPmCIYTbym54npXz7goROYyVl8MEhi1HgKmkOVsihaVLfaf5rt3OMbK70Lup3RrkxFbneKslTQ3bwdMdl_Zk1vmjRklvjhmVXyFlEHZVAe4_4n_FYk6oq6UFFJDkEjrWo25B0lKC7XucZZ5b8NDr04xujyV4XaR11ZuQ'}, true, jwk);
try
// inspect
Assert.IsTrue(true);
finally
jwt.Free;
end;
finally
jwk.Free;
end;
*)
end;
initialization
TDUnitX.RegisterTestFixture(TJWTTests);
End.
|
unit PJBank.Empresa.Response;
interface
type
TEmpresaResponse = class
public
status: string;
msg: string;
credencial: string;
chave: string;
conta_virtual: string;
agencia_virtual: string;
end;
implementation
end.
|
(*======================================================================*
| unitExSettings |
| |
| Base application settings class using file persistors |
| |
| The contents of this file are subject to the Mozilla Public License |
| Version 1.1 (the "License"); you may not use this file except in |
| compliance with the License. You may obtain a copy of the License |
| at http://www.mozilla.org/MPL/ |
| |
| Software distributed under the License is distributed on an "AS IS" |
| basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See |
| the License for the specific language governing rights and |
| limitations under the License. |
| |
| Copyright © Colin Wilson 2005 All Rights Reserved |
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 1.0 02/03/2006 CPWW Original |
*======================================================================*)
unit unitExFileSettings;
interface
uses Windows, Sysutils, unitExSettings;
type
//-----------------------------------------------------------------------
// TExFileSettings.
//
// Base class for derived classes that store application and other settings
// in files - ini files, XML files, etc.
TExFileSettings = class (TExSettings)
private
fCustomPath: string;
procedure SetCustomPath(const Value: string);
protected
function GetFileName(const ext: string): string;
public
constructor CreateChild (AParent : TExSettings; const ASection : string); override;
property CustomPath : string read fCustomPath write SetCustomPath;
end;
implementation
uses ShFolder;
(*----------------------------------------------------------------------*
| procedure TExFileSettings.GetFileName |
| |
| Return the file name, including the path. |
| |
| For 'Machine' settings use the same path as the .exe file. |
| |
| For 'User' settings use the user's local appdata path, plus the |
| Application, Manufacturer and Version. |
*----------------------------------------------------------------------*)
constructor TExFileSettings.CreateChild(AParent: TExSettings;
const ASection: string);
begin
inherited;
CustomPath := TExFileSettings (AParent).CustomPath
end;
function TExFileSettings.GetFileName(const ext : string) : string;
var
path : string;
begin
if Application = '' then
Raise EExSettings.Create('Must specify an application');
if fCustomPath <> '' then
result := fCustomPath
else
begin
SetLength (path, MAX_PATH);
if (SettingsType = stMachine) or not SUCCEEDED (SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, 0, PChar (path))) then
result := ExtractFilePath (ParamStr (0))
else
begin
result := PChar (path);
result := result + '\';
if Manufacturer <> '' then
result := result + Manufacturer + '\';
if Application <> '' then
result := result + Application + '\';
if version <> '' then
result := result + Version + '\';
result := result + Application + ext;
end
end
end;
(*----------------------------------------------------------------------*
| procedure TExFileSettings.SetCustomPath |
| |
| 'Set' method for the CustomPath property. |
*---------------------------------------------------------------------*)
procedure TExFileSettings.SetCustomPath(const Value: string);
begin
if Value <> fCustomPath then
begin
Close;
fCustomPath := Value
end
end;
end. |
unit VisibleDSA.Position;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils;
type
TPosition = class(TObject)
private
_prev: TPosition;
_x: integer;
_y: integer;
public
constructor Create(x, y: integer; prev: TPosition = nil);
destructor Destroy; override;
property X: integer read _X;
property Y: integer read _Y;
property Prev: TPosition read _Prev;
end;
implementation
{ TPosition }
constructor TPosition.Create(x, y: integer; prev: TPosition);
begin
_x := x;
_y := y;
_prev := prev;
end;
destructor TPosition.Destroy;
begin
inherited Destroy;
end;
end.
|
unit SnomedPublisher;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
SysUtils, Classes, Math,
MathSupport, kCritSct,
AdvObjects, AdvStringMatches,
HTMLPublisher, SnomedServices;
Const
MAX_ROWS = 100;
Type
TIdArray = array of cardinal;
TArrayofIdArray = array of TIdArray;
TConceptDisplayType = (cdDesc, cdConceptId, cdBoth);
TSnomedPublisher = class (TAdvObject)
Private
FSnomed : TSnomedServices;
Lock : TCriticalSection;
FSearchCache : TStringList;
FFHIRPath : String;
Function GetPaths(iIndex : Cardinal) : TArrayofIdArray;
Function ConceptForDesc(iDesc : Cardinal; var iDescs : Cardinal):Cardinal;
Procedure ConceptRef(html : THtmlPublisher; const sPrefix : String; iIndex : cardinal; show : TConceptDisplayType; rRating : Double);
Procedure RefsetRef(html : THtmlPublisher; Const sPrefix : String; iIndex : cardinal);
Procedure CellConceptRef(html : THtmlPublisher; const sPrefix : String; iIndex : cardinal; show : TConceptDisplayType; iDesc : Cardinal = 0);
Procedure SortRefsets(var a : TCardinalArray);
Function GetConceptForRefset(iRefset : Cardinal) : Cardinal;
procedure PublishPaths(html: THtmlPublisher; Const sPrefix : String; aPaths : TArrayofIdArray; iFocus : Cardinal; iIndent, iStart, iLow, iHigh : Integer);
Procedure PublishConcept(bRoot : Boolean; showhist : boolean; Const sPrefix, sId : String; iStart : Integer; html : THtmlPublisher);
Procedure PublishTermConcept(bRoot : Boolean; Const sPrefix, sId : String; iStart : Integer; html : THtmlPublisher);
Procedure PublishConcepts(Const sPrefix : String; iStart : Integer; html : THtmlPublisher);
Procedure PublishSearch(Const sPrefix, sText, sContext : String; iStart: Integer; all : boolean; html : THtmlPublisher);
Procedure PublishHome(Const sPrefix : String; html : THtmlPublisher);
Procedure ProcessMap(Const sPath : String; oMap : TAdvStringMatch);
Procedure PublishDictInternal(oMap : TAdvStringMatch; Const sPrefix : String; html : THtmlPublisher);
Public
Constructor Create(oSnomed : TSnomedServices; FHIRPath : String);
Destructor Destroy; Override;
Procedure PublishDict(Const sPath, sPrefix : String; html : THtmlPublisher); Overload; Virtual;
Procedure PublishDict(oMap : TAdvStringMatch; Const sPrefix : String; html : THtmlPublisher); Overload; Virtual;
Procedure PublishTerm(Const sTerm : String; html : THtmlPublisher); Overload; Virtual;
End;
Implementation
Uses
EncodeSupport,
StringSupport;
Function Screen(Const s, s2: String):String;
Begin
result := StringReplace(s, 'Â', '');
if (s2 <> '') And StringEndsWith(result, s2) Then
delete(result, length(result) - length(s2) + 1, length(s));
End;
function StringToBoolDef(s : String; def : boolean):boolean;
begin
s := lowercase(s);
if s = 'true' then
result := true
else if s = '1' then
result := true
else if s = 'yes' then
result := true
else if s = 'y' then
result := true
else if s = 'false' then
result := false
else if s = '0' then
result := false
else if s = 'no' then
result := false
else if s = 'n' then
result := false
else
result := def;
end;
Procedure TSnomedPublisher.PublishDictInternal(oMap : TAdvStringMatch; Const sPrefix : String; html : THtmlPublisher);
Var
sURL : String;
sId : String;
Begin
sURL := sPrefix +'?type=snomed&';
sId := oMap.Matches['id'];
If sId = '*' Then
PublishConcepts(sURL, StrToIntDef(oMap.Matches['start'], 0), html)
else If (sId <> '') Then
PublishConcept(false, oMap['no-hist'] <> 'true', sURL, sId, StrToIntDef(oMap.Matches['start'], 0), html)
else if oMap.ExistsByKey('srch') then
if StringIsInteger64(oMap.Matches['srch']) and ((oMap.Matches['context'] = '') or (FSnomed.Subsumes(oMap.Matches['context'], oMap.Matches['srch']))) then
PublishConcept(false, oMap['no-hist'] <> 'true', sURL, oMap.Matches['srch'], StrToIntDef(oMap.Matches['start'], 0), html)
else
PublishSearch(sURL, oMap.Matches['srch'], oMap.Matches['context'], StrToIntDef(oMap.Matches['start'], 0), StringToBoolDef(oMap.matches['all'], false), html)
else
PublishHome(sURL, html)
End;
Procedure TSnomedPublisher.ProcessMap(Const sPath : String; oMap : TAdvStringMatch);
Var
sLeft, sRight : String;
sName, sValue : String;
Begin
if sPath.Contains('?') then
Stringsplit(sPath, '?', sLeft, sRight)
else
sRight := sPath;
oMap.Forced := True;
While sRight <> '' Do
Begin
StringSplit(sRight, '&', sLeft, sRight);
StringSplit(sLeft, '=', sName, sValue);
oMap.Matches[sName] := sValue;
End;
End;
Procedure TSnomedPublisher.PublishDict(Const sPath, sPrefix : String; html : THtmlPublisher);
Var
oMap : TAdvStringMatch;
Begin
oMap := TAdvStringMatch.Create;
Try
ProcessMap(sPath, oMap);
PublishDict(oMap, sPrefix, html);
Finally
oMap.Free;
End;
End;
procedure TSnomedPublisher.PublishDict(oMap: TAdvStringMatch; const sPrefix: String; html: THtmlPublisher);
begin
Try
PublishDictInternal(oMap, sPrefix, html);
Except
On e:Exception Do
Begin
html.AddTitle('Exception: '+e.Message);
html.AddParagraph(e.Message);
End;
End;
end;
procedure TSnomedPublisher.PublishHome(const sPrefix: String; html: THtmlPublisher);
var
i : integer;
iRef : Cardinal;
aRefs : TCardinalArray;
Begin
{ html.StartParagraph;
if oMap.ExistsByKey('id') Or oMap.ExistsByKey('srch') Then
Begin
html.AddTextPlain('Snomed-CT: ');
html.URL(FSnomed.Version, sURL);
End
Else
html.AddTextPlain('Snomed: '+FSnomed.Version);
html.EndParagraph;
html.AddLine(1);
}
html.Header('Snomed-CT Definitions (e: '+FSnomed.EditionName+', v: '+FSnomed.VersionDate+')');
if Not FSnomed.Loaded Then
Begin
html.StartParagraph;
html.AddText('Snomed Definitions are not loaded', true, false);
html.EndParagraph;
End
Else
Begin
html.StartForm('GET', sPrefix);
html.StartParagraph;
html.AddTextPlain('Search: ');
html.textInput('srch');
html.submit('Go');
html.AddTextPlain(' ');
html.checkbox('all', false, 'Tight');
html.endForm;
html.StartList;
html.StartListItem;
html.URL('Browse All Concepts', sPrefix+'id=*');
html.EndListItem;
html.EndList;
if Length(FSnomed.ActiveRoots) = 1 Then
begin
html.StartParagraph;
html.AddText('Snomed Root Concept', true, false);
html.EndParagraph;
PublishConcept(true, true, sPrefix, inttostr(FSnomed.Activeroots[0]), 0, html)
End
Else
Begin
html.StartParagraph;
html.AddText('Snomed Root Concepts ('+inttostr(Length(FSnomed.ActiveRoots))+')', true, false);
html.EndParagraph;
html.StartList;
for i := 0 to min(Length(FSnomed.ActiveRoots) - 1, 1000) Do
Begin
html.StartListItem;
if FSnomed.Concept.FindConcept(FSnomed.ActiveRoots[i], iRef) Then
ConceptRef(html, sPrefix, iRef, cdBoth, 0);
html.EndListItem;
End;
html.EndList;
End;
html.Line;
html.StartParagraph;
html.AddText('Reference Sets', true, false);
html.EndParagraph;
SetLength(aRefs, FSnomed.RefSetIndex.Count);
for i := 0 to FSnomed.RefSetIndex.Count - 1 Do
aRefs[i] := i;
SortRefsets(aRefs);
if FSnomed.RefSetIndex.Count = 0 Then
Begin
html.StartParagraph;
html.AddText('No Reference Sets defined', false, true);
html.EndParagraph;
End;
html.StartList;
for i := 0 to FSnomed.RefSetIndex.Count - 1 Do
Begin
html.StartListItem;
RefsetRef(html, sPrefix, aRefs[i]);
html.EndListItem;
End;
html.EndList;
html.Line;
Lock.Lock;
Try
if FSearchCache.Count <> 0 Then
Begin
html.AddParagraph('Past Searches:');
html.StartList(false);
For i := 0 to FSearchCache.Count - 1 Do
begin
html.StartListItem;
html.ParaURL('Search for "'+FSearchCache[i]+'"', sPrefix+'srch='+FSearchCache[i]+'&caption=Search Snomed Concepts&prompt=Text');
html.EndListItem;
end;
html.EndList(false);
End;
Finally
Lock.UnLock;
End;
End;
html.done;
End;
Procedure TSnomedPublisher.SortRefsets(var a : TCardinalArray);
Procedure QuickSort(L, R: Integer);
Var
I, J, K : Integer;
t : Cardinal;
Begin
// QuickSort routine (Recursive)
// * Items is the default indexed property that returns a pointer, subclasses
// specify these return values as their default type.
// * The Compare routine used must be aware of what this pointer actually means.
Repeat
I := L;
J := R;
K := (L + R) Shr 1;
Repeat
While FSnomed.GetPNForConcept(GetConceptForRefset(a[I])) < FSnomed.GetPNForConcept(GetConceptForRefset(a[K])) Do
Inc(I);
While FSnomed.GetPNForConcept(GetConceptForRefset(a[J])) > FSnomed.GetPNForConcept(GetConceptForRefset(a[K])) Do
Dec(J);
If I <= J Then
Begin
t := a[i];
a[i] := a[j];
a[j] := t;
// Keep K as the index of the original middle element as it might get exchanged.
If I = K Then
K := J
Else If J = K Then
K := I;
Inc(I);
Dec(J);
End;
Until I > J;
If L < J Then
QuickSort(L, J);
L := I;
Until I >= R;
End;
Begin
If length(a) > 1 Then
QuickSort(0, length(a) - 1);
End;
Function TSnomedPublisher.GetPaths(iIndex : Cardinal): TArrayofIdArray;
var
iParentIndex : Cardinal;
iParents : TCardinalArray;
aPath : TArrayofIdArray;
i,j,k : integer;
begin
SetLength(result, 0);
SetLength(aPath, 0);
SetLength(iParents, 0);
iParentIndex := FSnomed.Concept.GetParent(iIndex);
if iParentIndex = 0 then
Begin
SetLength(result, 1);
SetLength(result[0], 1);
result[0][0] := iIndex;
End
Else
begin
iParents := FSnomed.Refs.GetReferences(iParentIndex);
for i := Low(iParents) To High(iParents) Do
Begin
aPath := GetPaths(iParents[i]);
for j := Low(aPath) To High(aPath) Do
Begin
SetLength(result, Length(result)+1);
SetLength(result[Length(result)-1], length(aPath[j])+1);
For k := Low(aPath[j]) To High(aPath[j]) Do
result[Length(result)-1][k] := aPath[j][k];
result[Length(result)-1][length(aPath[j])] := iIndex;
End;
End;
End;
End;
Function GetRelGroup(iGroup : cardinal):String;
Begin
if iGroup = 0 Then
result := ''
Else
result := inttostr(iGroup);
End;
Procedure TSnomedPublisher.ConceptRef(html : THtmlPublisher; const sPrefix : String; iIndex : cardinal; show : TConceptDisplayType; rRating : Double);
Begin
if show = cdBoth Then
html.URL(inttostr(FSnomed.Concept.GetIdentity(iIndex))+' '+Screen(FSnomed.GetPNForConcept(iIndex), ''), sPrefix+'id='+inttostr(FSnomed.Concept.GetIdentity(iIndex)))
Else if show = cdDesc then
html.URL(Screen(FSnomed.GetPNForConcept(iIndex), ''), sPrefix+'id='+inttostr(FSnomed.Concept.GetIdentity(iIndex)))
else
html.URL(inttostr(FSnomed.Concept.GetIdentity(iIndex)), sPrefix+'id='+inttostr(FSnomed.Concept.GetIdentity(iIndex)), Screen(FSnomed.GetPNForConcept(iIndex), ''));
if rRating > 0 then
html.AddTextPlain(' '+inttostr(Trunc(rRating * 10)));
End;
Procedure TSnomedPublisher.CellConceptRef(html : THtmlPublisher; const sPrefix : String; iIndex : cardinal; show : TConceptDisplayType; iDesc : Cardinal = 0);
var
s : String;
Begin
if iDesc <> 0 Then
s := FSnomed.Strings.GetEntry(iDesc)
Else
s := FSnomed.GetPNForConcept(iIndex);
if show = cdBoth Then
html.AddTableCellURL(inttostr(FSnomed.Concept.GetIdentity(iIndex))+' '+Screen(s, ''), sPrefix+'id='+inttostr(FSnomed.Concept.GetIdentity(iIndex)))
Else if show = cdDesc then
html.AddTableCellURL(Screen(s, ''), sPrefix+'id='+inttostr(FSnomed.Concept.GetIdentity(iIndex)))
Else
html.AddTableCellURL(inttostr(FSnomed.Concept.GetIdentity(iIndex)), sPrefix+'id='+inttostr(FSnomed.Concept.GetIdentity(iIndex)), Screen(s, ''))
End;
Function ComparePaths(p1, p2: TIdArray) : Integer;
var
i : Integer;
Begin
result := 0;
for i := 0 to Min(High(p1), High(p2)) Do
if result = 0 Then
result := IntegerCompare(p1[i], p2[i]);
if result = 0 Then
result := IntegerCompare(Length(p1), length(p2));
End;
Procedure SortPaths(Var Paths : TArrayofIdArray);
var
i : Integer;
t : TIdArray;
bSwap : Boolean;
Begin
SetLength(t, 0);
Repeat
bSwap := false;
for i := 0 to high(Paths)-1 Do
if ComparePaths(Paths[i], paths[i+1]) < 0 Then
Begin
t := Paths[i];
Paths[i] := Paths[i+1];
Paths[i+1] := t;
bSwap := true;
End;
Until not bSwap;
End;
procedure TSnomedPublisher.PublishPaths(html: THtmlPublisher; Const sPrefix : String; aPaths : TArrayofIdArray; iFocus : Cardinal; iIndent, iStart, iLow, iHigh : Integer);
var
iCommon, iLoop, i, j : Integer;
iValue : Cardinal;
bOk : Boolean;
Begin
html.StartList;
if iLow < iHigh Then
Begin
iCommon := iStart-1;
repeat
bOk := false;
iLoop := iLow + 1;
if Length(aPaths[iLow]) > iCommon + 1 Then
Begin
bOk := true;
iValue := aPaths[iLow][iCommon+1];
while bOk and (iLoop <= iHigh) Do
Begin
bOk := (Length(aPaths[iLoop]) > iCommon + 1) And (iValue = aPaths[iLoop][iCommon+1]);
inc(iLoop);
End;
if bOk Then
inc(iCommon);
End;
Until not bOk;
if iCommon < iStart then
iCommon := iStart;
End
else
iCommon := iStart;
if iCommon > iStart Then
Begin
html.StartListItem;
For j := iStart to iCommon Do
Begin
if j > 0 Then
html.AddTextPlain('\');
if aPaths[iLow][j] = iFocus Then
html.AddText(Screen(FSnomed.GetPNForConcept(iFocus), ''), false, true)
Else
ConceptRef(html, sPrefix, aPaths[iLow][j], cdDesc, 0);
End;
html.AddTextPlain('\...');
html.EndListItem;
// now, can we find any child groups here?
iLoop := iLow;
while (iLoop <= iHigh) Do
Begin
iValue := aPaths[iLoop][iCommon+1];
i := iLoop;
While (iLoop < iHigh) And (aPaths[iLoop+1][iCommon+1] = iValue) Do
inc(iLoop);
PublishPaths(html, sPrefix, aPaths, iFocus, iIndent + 1, iCommon+1, i, iLoop);
inc(iLoop);
End;
End
Else
Begin
for i := iLow To iHigh do
Begin
html.StartListItem;
For j := iStart To High(aPaths[i]) Do
Begin
if j > 0 Then
html.AddTextPlain('\');
if aPaths[i][j] = iFocus Then
html.AddText(Screen(FSnomed.GetPNForConcept(iFocus), ''), false, true)
Else
ConceptRef(html, sPrefix, aPaths[i][j], cdDesc, 0);
End;
html.EndListItem;
End;
End;
html.EndList;
End;
function DescConceptFlags(flags : byte; bPrimitive : boolean):String;
begin
case flags and MASK_CONCEPT_STATUS of
0: result := 'current';
1: result := 'retired';
2: result := 'duplicate';
3: result := 'outdated';
4: result := 'ambiguous';
5: result := 'erroneous';
6: result := 'limited';
10: result := 'moved elsewhere';
11: result := 'pending move';
else
result := '??';
end;
if bPrimitive and(flags and MASK_CONCEPT_PRIMITIVE > 0) then
result := result + ', primitive';
end;
procedure TSnomedPublisher.PublishConcept(bRoot : Boolean; showhist : boolean; const sPrefix, sId: String; iStart : Integer; html: THtmlPublisher);
var
iId : UInt64;
iIndex : Cardinal;
Identity : UInt64;
Flags, lang : Byte;
Group : integer;
ParentIndex : Cardinal;
DescriptionIndex : Cardinal;
InboundIndex : Cardinal;
outboundIndex : Cardinal;
Parents : TCardinalArray;
Descriptions : TCardinalArray;
Inbounds : TCardinalArray;
outbounds : TCardinalArray;
allDesc : TCardinalArray;
Active, Defining : boolean;
iWork, iWork2, iWork3, kind, caps, module, refsets, valueses, modifier : Cardinal;
FSN : String;
PN : String;
FPaths : TArrayofIdArray;
i, j : integer;
iList : TRefSetMemberEntryArray;
iDummy, iRefSet, iMembers, iDescs, children, iTypes, iName, iFields : Cardinal;
types, fields, values : TCardinalArray;
bDescSet : Boolean;
aMembers : TSnomedReferenceSetMemberArray;
date : TSnomedDate;
ok : boolean;
did : UInt64;
Begin
bDescSet := false;
SetLength(aMembers, 0);
SetLength(iList, 0);
SetLength(alLDesc, 0);
iId := StrToUInt64Def(sId, 0);
ok := FSnomed.Concept.FindConcept(iId, iIndex);
if not ok then
begin
ok := FSnomed.DescRef.FindDescription(iId, iIndex);
if ok then
iIndex := FSnomed.Desc.ConceptByIndex(iIndex);
end;
if not ok Then
Begin
html.Header('Snomed Concept '+sId);
html.AddParagraph(sId+' is not a valid Snomed-CT Concept or Description Id');
SetLength(FPaths, 0);
SetLength(Parents, 0);
SetLength(Descriptions, 0);
SetLength(Inbounds, 0);
SetLength(outbounds, 0);
html.ParaURL('Back to Snomed Home', sPrefix);
End
else
Begin
FSnomed.Concept.GetConcept(iIndex, Identity, Flags, date, ParentIndex, DescriptionIndex, InboundIndex, outboundIndex, refsets);
if ParentIndex <> 0 Then
Parents := FSnomed.Refs.GetReferences(ParentIndex);
Descriptions := FSnomed.Refs.GetReferences(DescriptionIndex);
outbounds := FSnomed.Refs.GetReferences(outboundIndex);
FSN := FSnomed.GetFSN(Descriptions);
PN := FSnomed.GetPN(Descriptions);
if Not bRoot then
html.Header(inttostr(Identity)+': '+screen(FSN, ''));
if not bRoot Then
Begin
FPaths := GetPaths(iIndex);
SortPaths(FPaths);
PublishPaths(html, sPrefix, FPaths, iIndex, 0, 0, Low(FPaths), High(FPaths));
html.Line;
End;
html.StartParagraph;
iDummy := FSnomed.Concept.GetStatus(iIndex);
html.AddTextPlain('Status: '+DescConceptFlags(flags, iDummy = 0));
if iDummy <> 0 then
begin
html.AddTextPlain(', ');
ConceptRef(html, sPrefix, iDummy, cdDesc, 0);
end;
html.AddTextPlain('. Date: '+FormatDateTime('dd-mmm yyyy', date));
iDummy := FSnomed.Concept.GetModuleId(iIndex);
if iDummy <> 0 then
begin
html.AddTextPlain('. Module: ');
ConceptRef(html, sPrefix, iDummy, cdDesc, 0);
end;
html.EndParagraph;
// todo: flags
html.AddParagraph('Descriptions:');
html.StartTable(true, 'lines');
html.StartTableRow;
html.AddTableCell('Id', true);
html.AddTableCell('Description', true);
html.AddTableCell('Lang', true);
html.AddTableCell('Type', true);
html.AddTableCell('Status', true);
html.AddTableCell('Case?', true);
html.AddTableCell('Module', true);
if FSnomed.RefSetIndex.Count > 0 Then
html.AddTableCell('Reference Sets', true);
html.EndTableRow;
for i := Low(Descriptions) To High(Descriptions) Do
Begin
FSnomed.Desc.GetDescription(Descriptions[i], iWork, iId, date, iDummy, module, kind, caps, refsets, valueses, active, lang);
if active Then
Begin
html.StartRow();
html.AddTableCell(inttostr(iId));
html.AddTableCell(Screen(FSnomed.Strings.GetEntry(iWork), ''));
html.AddTableCell(codeForLang(lang));
CellConceptRef(html, sPrefix, kind, cdDesc);
if (active) then
html.AddTableCell('Active')
else
html.AddTableCell('Inactive');
CellConceptRef(html, sPrefix, caps, cdDesc);
if (module <> 0) then
CellConceptRef(html, sPrefix, module, cdDesc)
else
html.AddTableCell('');
if FSnomed.RefSetIndex.Count > 0 Then
Begin
iList := FSnomed.GetDescRefsets(Descriptions[i]);
if Length(ilist) = 0 Then
html.AddTableCell('')
Else
begin
html.StartTableCell;
ConceptRef(html, sPrefix, iList[0].refset, cdDesc, 0);
if (iList[0].types <> 0) and (iList[0].values <> 0) then
begin
Values := FSnomed.Refs.GetReferences(iList[0].values);
if values[1] = 1 then
begin
html.AddTextPlain(': ');
ConceptRef(html, sPrefix, values[0], cdDesc, 0);
end;
end;
html.EndTableCell;
end;
End;
// html.AddTableCell(BooleanToString(flags and MASK_DESC_CAPS > 0));
html.EndTableRow;
End;
End;
html.EndTable;
html.Line;
iRefSet := FSnomed.GetConceptRefSet(iIndex, true, iName, iMembers, itypes, iFields);
allDesc := FSnomed.Refs.GetReferences(FSnomed.Concept.GetAllDesc(iIndex));
SetLength(types, 0);
SetLength(fields, 0);
html.StartForm('GET', sPrefix);
html.StartParagraph;
if iRefSet = 0 then
begin
html.AddTextPlain(inttostr(length(alldesc))+' descendants. ');
children := length(alldesc);
if children > 0 then
html.AddTextPlain('Search Descendants: ');
End
else
Begin
children := FSnomed.RefSetMembers.GetMemberCount(iMembers);
if (iTypes <> 0) then
begin
types := FSnomed.Refs.GetReferences(iTypes);
fields := FSnomed.Refs.GetReferences(iFields);
end;
html.AddTextPlain(inttostr(children)+' members. ');
if children > 0 then
html.AddTextPlain('Search Members: ');
End;
if children > 0 then
begin
html.hiddenInput('context', sid);
html.textInput('srch');
html.submit('Go');
end;
html.endForm;
html.StartParagraph;
if iRefSet = 0 then
html.URL('Expanded Value Set', FFHIRPath+'ValueSet?_query=expand&identifier=http://snomed.info/id/'+sId)
else
html.URL('Expanded Value Set', FFHIRPath+'ValueSet?_query=expand&identifier=http://snomed.info/sct/'+sId);
html.EndParagraph;
html.Line;
if not bRoot and (Length(Outbounds) > 0) Then
Begin
html.StartTable(false);
html.StartTableRow;
html.AddTableCell('Outbound Relationships', true);
html.AddTableCell('Type', true);
html.AddTableCell('Target', true);
html.AddTableCell('Active', true);
html.AddTableCell('Characteristic', true);
html.AddTableCell('Refinability', true);
html.AddTableCell('Group', true);
html.AddTableCell('Values', true);
html.EndTableRow;
for i := Low(Outbounds) To High(Outbounds) Do
Begin
FSnomed.Rel.GetRelationship(Outbounds[i], did, iWork, iWork2, iWork3, module, kind, modifier, date, Active, Defining, Group);
if (showhist) or active then
begin
if not active then
html.StartRow('#EFEFEF')
else
html.StartRow();
html.AddTableCellHint(Screen(PN, ''), inttostr(did));
CellConceptRef(html, sPrefix, iWork3, cdDesc);
CellConceptRef(html, sPrefix, iWork2, cdDesc);
if (active) then
html.AddTableCell('true')
else
html.AddTableCell('false');
CellConceptRef(html, sPrefix, kind, cdDesc);
CellConceptRef(html, sPrefix, modifier, cdDesc);
html.AddTableCell(' '+GetRelGroup(Group));
html.AddTableCell(FSnomed.getRelationshipValues(Outbounds[i]));
html.EndTableRow;
end;
End;
html.EndTable;
html.Line;
End;
if iRefset <> 0 Then
Begin
aMembers := FSnomed.RefSetMembers.GetMembers(iMembers);
html.StartTable(false);
html.StartTableRow;
html.AddTableCell('Members', true);
For i := 0 to length(fields)-1 Do
html.AddTableCell(FSnomed.Strings.GetEntry(fields[i]), true);
html.EndTableRow;
For i := iStart to Min(iStart+MAX_ROWS, High(aMembers)) Do
Begin
html.StartRow();
case aMembers[i].kind of
0 {concept} :
CellConceptRef(html, sPrefix, aMembers[i].Ref, cdDesc);
1 {desc} :
begin
iDummy := ConceptForDesc(aMembers[i].Ref, iDescs);
CellConceptRef(html, sPrefix, iDummy, cdDesc, iDescs);
end;
2 {relationship} :
begin
html.StartTableCell;
FSnomed.Rel.GetRelationship(aMembers[i].Ref, did, iWork, iWork2, iWork3, module, kind, modifier, date, Active, Defining, Group);
html.AddTextPlain(' '+inttostr(did)+': ');
ConceptRef(html, sPrefix, iWork, cdConceptId, 0);
html.AddTextPlain('---');
ConceptRef(html, sPrefix, iWork3, cdConceptId, 0);
html.AddTextPlain('-->');
ConceptRef(html, sPrefix, iWork2, cdConceptId, 0);
html.EndTableCell;
end;
end;
if (aMembers[i].values <> 0) then
begin
values := FSnomed.Refs.GetReferences(aMembers[i].values);
for j := 0 to length(types) - 1 do
case values[j*2+1] of
1 {concept} : CellConceptRef(html, sPrefix, values[j*2], cdDesc);
// 2:
// 3:
4 {integer} : html.AddTableCell(inttostr(values[j*2]));
5 {string} : html.AddTableCell(FSnomed.Strings.GetEntry(values[j*2]));
else
html.AddTableCell('Unknown Cell Type '+inttostr(values[j*2+1]));
end;
end;
html.EndTableRow;
End;
html.EndTable;
if (iStart > 0) or (iStart+MAX_ROWS < High(aMembers)) Then
Begin
html.StartParagraph;
if iStart > 0 Then
Begin
html.URL('Start', sPrefix+'id='+sId);
html.AddTextPlain(' ');
End;
if iStart > MAX_ROWS Then
Begin
html.URL('Previous', sPrefix+'id='+sId+'&start='+inttostr(iStart - MAX_ROWS));
html.AddTextPlain(' ');
End;
html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(High(aMembers) div MAX_ROWS + 1), true, false);
if (iStart+MAX_ROWS < High(aMembers)) And (iStart + MAX_ROWS < MAX_ROWS * (High(aMembers) div MAX_ROWS)) Then
Begin
html.AddTextPlain(' ');
html.URL('Next', sPrefix+'id='+sId+'&start='+inttostr(iStart + MAX_ROWS));
End;
if (iStart+MAX_ROWS < High(aMembers)) Then
Begin
html.AddTextPlain(' ');
html.URL('End', sPrefix+'id='+sId+'&start='+inttostr(MAX_ROWS * (High(aMembers) div MAX_ROWS)));
End;
html.EndParagraph;
End;
End
Else
Begin
Inbounds := FSnomed.Refs.GetReferences(InboundIndex);
html.StartTable(false);
html.StartTableRow;
html.AddTableCell('Inbound Relationships', true);
html.AddTableCell('Type', true);
html.AddTableCell('Active', true);
html.AddTableCell('Source', true);
html.AddTableCell('Characteristic', true);
html.AddTableCell('Refinability', true);
html.AddTableCell('Group', true);
html.EndTableRow;
For i := iStart to Min(iStart+MAX_ROWS, High(Inbounds)) Do
Begin
FSnomed.Rel.GetRelationship(Inbounds[i], did, iWork, iWork2, iWork3, module, kind, modifier, date, Active, Defining, Group);
if (showhist) or (Active) then
begin
if not active then
html.StartRow('#EFEFEF')
else
html.StartRow();
CellConceptRef(html, sPrefix, iWork, cdDesc);
CellConceptRef(html, sPrefix, iWork3, cdDesc);
html.AddTableCell(BooleanToString(active));
html.AddTableCellHint(Screen(PN, ''), inttostr(did));
CellConceptRef(html, sPrefix, kind, cdDesc);
CellConceptRef(html, sPrefix, modifier, cdDesc);
html.AddTableCell(' '+GetRelGroup(Group));
html.EndTableRow;
End;
End;
html.EndTable;
if (iStart > 0) or (iStart+MAX_ROWS < High(Inbounds)) Then
Begin
html.StartParagraph;
if iStart > 0 Then
Begin
html.URL('Start', sPrefix+'id='+sId);
html.AddTextPlain(' ');
End;
if iStart > MAX_ROWS Then
Begin
html.URL('Previous', sPrefix+'id='+sId+'&start='+inttostr(iStart - MAX_ROWS));
html.AddTextPlain(' ');
End;
html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(High(Inbounds) div MAX_ROWS + 1), true, false);
if (iStart+MAX_ROWS < High(Inbounds)) And (iStart + MAX_ROWS < MAX_ROWS * (High(Inbounds) div MAX_ROWS)) Then
Begin
html.AddTextPlain(' ');
html.URL('Next', sPrefix+'id='+sId+'&start='+inttostr(iStart + MAX_ROWS));
End;
if (iStart+MAX_ROWS < High(Inbounds)) Then
Begin
html.AddTextPlain(' ');
html.URL('End', sPrefix+'id='+sId+'&start='+inttostr(MAX_ROWS * (High(Inbounds) div MAX_ROWS)));
End;
html.EndParagraph;
End;
End;
if FSnomed.RefSetIndex.count > 0 Then
Begin
iList := FSnomed.GetConceptRefsets(iIndex);
html.Line;
html.StartParagraph;
if Length(iList) = 0 Then
html.AddText('This concept is not in any reference sets', false, true)
Else
html.AddText('Reference Sets', true, false);
html.EndParagraph;
html.AddParagraph;
for i := 0 to Length(iList) - 1 Do
Begin
html.StartParagraph;
ConceptRef(html, sPrefix, iList[i].refset, cdDesc, 0);
html.EndParagraph;
End;
End;
if not bRoot then
begin
html.ParaURL('Back to Start', sPrefix);
html.Done;
end;
End;
End;
(*
function GetConceptDesc(iConcept : Word):String;
var
iName : Cardinal;
iChildren : Cardinal;
iCodes : Cardinal;
Begin
if iConcept = 0 then
result := ''
Else
Begin
FSnomed.Concepts.GetConcept(iConcept, iName, iChildren, iCodes);
result := FSnomed.Desc.GetEntry(iname);
End;
End;
procedure TSnomedPublisher.PublishCode(const sPrefix, sCode: String; html: THtmlPublisher);
var
iIndex : Cardinal;
iDescription, iOtherNames : Cardinal;
sCode1 : String;
iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iv2dt, iv3dt : Word;
iFlags : Byte;
iRefs : TCardinalArray;
i : integer;
iCount : integer;
Begin
if FSnomed.Code.FindCode(sCode, iIndex) Then
Begin
FSnomed.Code.GetInformation(iIndex, sCode1, iDescription, iOtherNames, iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iv2dt, iv3dt, iFlags);
assert(sCode = sCode1);
html.AddTitle('Snomed Code '+sCode+' : '+FSnomed.Desc.GetEntry(iDescription));
html.StartTable;
iCount := 0;
if iComponent <> 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Component');
html.AddTableCell(GetConceptDesc(iComponent));
html.EndTableRow;
End;
if iProperty <> 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Property');
html.AddTableCell(GetConceptDesc(iProperty));
html.EndTableRow;
End;
if iTimeAspect <> 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Time Aspect');
html.AddTableCell(GetConceptDesc(iTimeAspect));
html.EndTableRow;
End;
if iSystem <> 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('System');
html.AddTableCell(GetConceptDesc(iSystem));
html.EndTableRow;
End;
if iScale <> 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Scale');
html.AddTableCell(GetConceptDesc(iScale));
html.EndTableRow;
End;
if iMethod <> 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Method');
html.AddTableCell(GetConceptDesc(iMethod));
html.EndTableRow;
End;
if iClass <> 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Class');
html.AddTableCell(GetConceptDesc(iClass));
html.EndTableRow;
End;
if iv2dt <> 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('v2 Data Type');
html.AddTableCell(GetConceptDesc(iv2dt));
html.EndTableRow;
End;
if iv3dt <> 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('v3 Data Type');
html.AddTableCell(GetConceptDesc(iv3dt));
html.EndTableRow;
End;
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Type');
if iFlags and FLAGS_CLIN > 0 Then
html.AddTableCell('Clinical')
Else if iFlags and FLAGS_ATT > 0 Then
html.AddTableCell('Attachment')
Else if iFlags and FLAGS_SURV > 0 Then
html.AddTableCell('Survey')
Else
html.AddTableCell('Lab');
html.EndTableRow;
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Status');
if iFlags and FLAGS_HOLD > 0 Then
html.AddTableCell('Not yet final')
Else
html.AddTableCell('Final');
html.EndTableRow;
if iFlags and FLAGS_ROOT > 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Root');
html.AddTableCell('This is a root of a set');
html.EndTableRow;
End;
if iFlags and FLAGS_UNITS > 0 Then
Begin
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Units');
html.AddTableCell('Units are required');
html.EndTableRow;
End;
inc(iCount);
html.StartRowFlip(iCount);
html.AddTableCell('Order/Obs Status');
if (iFlags and FLAGS_ORDER> 0 ) and (iFlags and FLAGS_OBS> 0 ) Then
html.AddTableCell('Both')
Else if iFlags and FLAGS_ORDER > 0 Then
html.AddTableCell('Order')
Else if iFlags and FLAGS_OBS > 0 Then
html.AddTableCell('Observation')
Else
html.AddTableCell('');
html.EndTableRow;
html.EndTable;
html.AddParagraph('');
if iOtherNames <> 0 Then
Begin
html.StartParagraph;
html.AddText('Other Names', true, false);
html.EndParagraph;
iRefs := FSnomed.Refs.GetCardinals(iOtherNames);
html.StartTable;
for i := Low(iRefs) To High(iRefs) Do
begin
html.StartRow();
html.AddTableCell(FSnomed.desc.GetEntry(iRefs[i]));
html.EndTableRow;
End;
html.EndTable;
End;
End
Else
html.AddParagraph('Unable to find code '+sCode);
end;
procedure TSnomedPublisher.PublishConcept(bRoot : Boolean; const sPrefix, sId: String; iStart : Integer; html: THtmlPublisher);
var
aChildren : TWordArray;
aCodes : TCardinalArray;
iName : Cardinal;
iChildren : Cardinal;
iCodes : Cardinal;
i : Integer;
iDummy : Cardinal;
b2, b3, b4 : Boolean;
iDescription, iOtherNames : Cardinal;
sCode1 : String;
iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iv2dt, iv3dt : Word;
iFlags : Byte;
begin
FSnomed.Concepts.GetConcept(StrToInt(sId), iName, iChildren, iCodes);
if Not bRoot then
html.AddTitle('Snomed Concept '+FSnomed.Desc.GetEntry(iName));
b2 := false;
b3 := false;
b4 := false;
if iChildren <> 0 Then
begin
aChildren := FSnomed.Refs.GetWords(iChildren);
html.StartTable.BorderPolicy := WPDocumentTables.BorderPolicyNone;
html.StartTableRow;
html.StartTableCell;
html.AddParagraph(' ');
html.EndTableCell;
html.StartTableCell;
For i := iStart to Min(iStart+MAX_ROWS, High(aChildren)) Do
Begin
if not b2 And (Length(aChildren) > 20) And ((i - iStart) / Min(MAX_ROWS, Length(aChildren)) > 0.25) Then
Begin
html.EndTableCell;
html.StartTableCell;
b2 := true;
End;
if not b3 And (Length(aChildren) > 20) And ((i - iStart) / Min(MAX_ROWS, Length(aChildren)) > 0.5) Then
Begin
html.EndTableCell;
html.StartTableCell;
b3 := true;
End;
if not b4 And (Length(aChildren) > 20) And ((i - iStart) / Min(MAX_ROWS, Length(aChildren)) > 0.750) Then
Begin
html.EndTableCell;
html.StartTableCell;
b4 := true;
End;
FSnomed.Concepts.GetConcept(aChildren[i], iName, iChildren, iDummy);
html.ParaURL(FSnomed.Desc.GetEntry(iName), sPrefix + 'id='+inttostr(aChildren[i]));
End;
html.EndTableCell;
html.EndTableRow;
html.EndTable;
if (iStart > 0) or (iStart+MAX_ROWS < High(aChildren)) Then
Begin
html.StartParagraph;
if iStart > 0 Then
Begin
html.URL('Start', sPrefix+'id='+sId);
html.AddTextPlain(' ');
End;
if iStart > MAX_ROWS Then
Begin
html.URL('Previous', sPrefix+'id='+sId+'&start='+inttostr(iStart - MAX_ROWS));
html.AddTextPlain(' ');
End;
html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(High(aChildren) div MAX_ROWS + 1), true, false);
if (iStart+MAX_ROWS < High(aChildren)) And (iStart + MAX_ROWS < MAX_ROWS * (High(aChildren) div MAX_ROWS)) Then
Begin
html.AddTextPlain(' ');
html.URL('Next', sPrefix+'id='+sId+'&start='+inttostr(iStart + MAX_ROWS));
End;
if (iStart+MAX_ROWS < High(aChildren)) Then
Begin
html.AddTextPlain(' ');
html.URL('End', sPrefix+'id='+sId+'&start='+inttostr(MAX_ROWS * (High(aChildren) div MAX_ROWS)));
End;
html.EndParagraph;
End;
End;
b2 := false;
b3 := false;
b4 := false;
if iCodes <> 0 Then
begin
aCodes := FSnomed.Refs.GetCardinals(iCodes);
html.StartTable.BorderPolicy := WPDocumentTables.BorderPolicyNone;
html.StartTableRow;
html.StartTableCell;
html.AddParagraph(' ');
html.EndTableCell;
html.StartTableCell;
For i := iStart to Min(iStart+MAX_ROWS, High(aCodes)) Do
Begin
if not b2 And (Length(aCodes) > 20) And ((i - iStart) / Min(MAX_ROWS, Length(aCodes)) > 0.25) Then
Begin
html.EndTableCell;
html.StartTableCell;
b2 := true;
End;
if not b3 And (Length(aCodes) > 20) And ((i - iStart) / Min(MAX_ROWS, Length(aCodes)) > 0.5) Then
Begin
html.EndTableCell;
html.StartTableCell;
b3 := true;
End;
if not b4 And (Length(aCodes) > 20) And ((i - iStart) / Min(MAX_ROWS, Length(aCodes)) > 0.750) Then
Begin
html.EndTableCell;
html.StartTableCell;
b4 := true;
End;
FSnomed.Code.GetInformation(aCodes[i], sCode1, iDescription, iOtherNames, iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iv2dt, iv3dt, iFlags);
html.StartParagraph;
html.URL(sCode1, sPrefix + 'code='+sCode1);
html.AddTextPlain(': '+FSnomed.Desc.GetEntry(iDescription));
html.EndParagraph;
End;
html.EndTableCell;
html.EndTableRow;
html.EndTable;
if (iStart > 0) or (iStart+MAX_ROWS < High(aCodes)) Then
Begin
html.StartParagraph;
if iStart > 0 Then
Begin
html.URL('Start', sPrefix+'id='+sId);
html.AddTextPlain(' ');
End;
if iStart > MAX_ROWS Then
Begin
html.URL('Previous', sPrefix+'id='+sId+'&start='+inttostr(iStart - MAX_ROWS));
html.AddTextPlain(' ');
End;
html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(High(aCodes) div MAX_ROWS + 1), true, false);
if (iStart+MAX_ROWS < High(aCodes)) And (iStart + MAX_ROWS < MAX_ROWS * (High(aCodes) div MAX_ROWS)) Then
Begin
html.AddTextPlain(' ');
html.URL('Next', sPrefix+'id='+sId+'&start='+inttostr(iStart + MAX_ROWS));
End;
if (iStart+MAX_ROWS < High(aCodes)) Then
Begin
html.AddTextPlain(' ');
html.URL('End', sPrefix+'id='+sId+'&start='+inttostr(MAX_ROWS * (High(aCodes) div MAX_ROWS)));
End;
html.EndParagraph;
End;
End;
end;
procedure TSnomedPublisher.PublishCodes(const sPrefix: String; iStart: Integer; html: THtmlPublisher);
var
// aChildren : TWordArray;
// aCodes : TCardinalArray;
// iName : Cardinal;
// iChildren : Cardinal;
// iCodes : Cardinal;
i : Integer;
iTotal : Integer;
// iDummy : Cardinal;
b2, b3, b4 : Boolean;
iDescription, iOtherNames : Cardinal;
sCode1 : String;
iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iv2dt, iv3dt : Word;
iFlags : Byte;
begin
b2 := false;
b3 := false;
b4 := false;
html.StartTable.BorderPolicy := WPDocumentTables.BorderPolicyNone;
html.StartTableRow;
html.StartTableCell;
html.AddParagraph(' ');
html.EndTableCell;
html.StartTableCell;
iTotal := FSnomed.Code.Count;
For i := iStart to Min(iStart+MAX_ROWS, iTotal) Do
Begin
if not b2 And ((i - iStart) / Min(MAX_ROWS, iTotal) > 0.25) Then
Begin
html.EndTableCell;
html.StartTableCell;
b2 := true;
End;
if not b3 And ((i - iStart) / Min(MAX_ROWS, iTotal) > 0.5) Then
Begin
html.EndTableCell;
html.StartTableCell;
b3 := true;
End;
if not b4 And ((i - iStart) / Min(MAX_ROWS, iTotal) > 0.750) Then
Begin
html.EndTableCell;
html.StartTableCell;
b4 := true;
End;
FSnomed.Code.GetInformation(i, sCode1, iDescription, iOtherNames, iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iv2dt, iv3dt, iFlags);
html.StartParagraph;
html.URL(sCode1, sPrefix + 'code='+sCode1);
html.AddTextPlain(': '+FSnomed.Desc.GetEntry(iDescription));
html.EndParagraph;
End;
html.EndTableCell;
html.EndTableRow;
html.EndTable;
if (iStart > 0) or (iStart+MAX_ROWS < iTotal) Then
Begin
html.StartParagraph;
if iStart > 0 Then
Begin
html.URL('Start', sPrefix+'code=*');
html.AddTextPlain(' ');
End;
if iStart > MAX_ROWS Then
Begin
html.URL('Previous', sPrefix+'code=*&start='+inttostr(iStart - MAX_ROWS));
html.AddTextPlain(' ');
End;
html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(iTotal div MAX_ROWS + 1), true, false);
if (iStart+MAX_ROWS < iTotal) And (iStart + MAX_ROWS < MAX_ROWS * (iTotal div MAX_ROWS)) Then
Begin
html.AddTextPlain(' ');
html.URL('Next', sPrefix+'code=*&start='+inttostr(iStart + MAX_ROWS));
End;
if (iStart+MAX_ROWS < iTotal) Then
Begin
html.AddTextPlain(' ');
html.URL('End', sPrefix+'code=*&start='+inttostr(MAX_ROWS * (iTotal div MAX_ROWS)));
End;
html.EndParagraph;
End;
end;
procedure TSnomedPublisher.PublishSearch(const sPrefix, sText: String; iStart: Integer; html: THtmlPublisher);
var
a : TCardinalArray;
i : integer;
o : TSearchCache;
iTotal : Integer;
// iDummy : Cardinal;
b2, b3, b4 : Boolean;
iDescription, iOtherNames : Cardinal;
sCode1 : String;
iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iv2dt, iv3dt : Word;
iFlags : Byte;
begin
if FSearchCache.Find(sText, i) Then
a := TSearchCache(FSearchCache.Objects[i]).a
else
Begin
a := FSnomed.Search(sText);
o := TSearchCache.Create;
o.a := a;
FSearchCache.AddObject(sText, o);
End;
b2 := false;
b3 := false;
b4 := false;
html.StartTable.BorderPolicy := WPDocumentTables.BorderPolicyNone;
html.StartTableRow;
html.StartTableCell;
html.AddParagraph(' ');
html.EndTableCell;
html.StartTableCell;
iTotal := High(a);
For i := iStart to Min(iStart+MAX_ROWS, iTotal) Do
Begin
if not b2 And ((i - iStart) / Min(MAX_ROWS, iTotal) > 0.25) Then
Begin
html.EndTableCell;
html.StartTableCell;
b2 := true;
End;
if not b3 And ((i - iStart) / Min(MAX_ROWS, iTotal) > 0.5) Then
Begin
html.EndTableCell;
html.StartTableCell;
b3 := true;
End;
if not b4 And ((i - iStart) / Min(MAX_ROWS, iTotal) > 0.750) Then
Begin
html.EndTableCell;
html.StartTableCell;
b4 := true;
End;
FSnomed.Code.GetInformation(a[i], sCode1, iDescription, iOtherNames, iComponent, iProperty, iTimeAspect, iSystem, iScale, iMethod, iClass, iv2dt, iv3dt, iFlags);
html.StartParagraph;
html.URL(sCode1, sPrefix + 'code='+sCode1);
html.AddTextPlain(': '+FSnomed.Desc.GetEntry(iDescription));
html.EndParagraph;
End;
html.EndTableCell;
html.EndTableRow;
html.EndTable;
if (iStart > 0) or (iStart+MAX_ROWS < iTotal) Then
Begin
html.StartParagraph;
if iStart > 0 Then
Begin
html.URL('Start', sPrefix+'srch='+sText);
html.AddTextPlain(' ');
End;
if iStart > MAX_ROWS Then
Begin
html.URL('Previous', sPrefix+'srch='+sText+'&start='+inttostr(iStart - MAX_ROWS));
html.AddTextPlain(' ');
End;
html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(iTotal div MAX_ROWS + 1), true, false);
if (iStart+MAX_ROWS < iTotal) And (iStart + MAX_ROWS < MAX_ROWS * (iTotal div MAX_ROWS)) Then
Begin
html.AddTextPlain(' ');
html.URL('Next', sPrefix+'srch='+sText+'&start='+inttostr(iStart + MAX_ROWS));
End;
if (iStart+MAX_ROWS < iTotal) Then
Begin
html.AddTextPlain(' ');
html.URL('End', sPrefix+'srch='+sText+'&start='+inttostr(MAX_ROWS * (iTotal div MAX_ROWS)));
End;
html.EndParagraph;
End;
end;
*)
constructor TSnomedPublisher.Create;
begin
inherited Create;
Lock := TCriticalSection.Create;
FSearchCache := TStringList.Create;
FSearchCache.Sorted := true;
FSnomed := oSnomed.Link;
FFHIRPath := FHIRPath;
end;
destructor TSnomedPublisher.Destroy;
var
i : integer;
begin
For i := 0 to FSearchCache.Count - 1 do
FSearchCache.Objects[i].Free;
FSearchCache.Free;
Lock.Free;
FSnomed.Free;
inherited;
end;
Type
TSearchCache = class (TObject)
public
a : TMatchArray;
End;
procedure TSnomedPublisher.PublishConcepts(const sPrefix: String; iStart: Integer; html: THtmlPublisher);
var
i : Integer;
iTotal : Integer;
b2 : Boolean;
begin
b2 := false;
html.Header('Concept List');
html.StartTable(false, 'bare');
html.StartTableRow;
html.StartTableCell;
html.AddParagraph(' ');
html.EndTableCell;
html.StartTableCell;
html.StartList;
iTotal := FSnomed.Concept.Count;
For i := iStart to Min(iStart+MAX_ROWS, iTotal) Do
Begin
if not b2 And ((i - iStart) / Min(MAX_ROWS, iTotal) > 0.5) Then
Begin
html.EndList;
html.EndTableCell;
html.StartTableCell;
html.StartList;
b2 := true;
End;
html.StartListItem;
ConceptRef(html, sPrefix, i * CONCEPT_SIZE + 1, cdBoth, 0);
html.EndListItem;
End;
html.EndList;
html.EndTableCell;
html.EndTableRow;
html.EndTable;
if (iStart > 0) or (iStart+MAX_ROWS < iTotal) Then
Begin
html.StartParagraph;
if iStart > 0 Then
Begin
html.URL('Start', sPrefix+'id=*');
html.AddTextPlain(' ');
End;
if iStart > MAX_ROWS Then
Begin
html.URL('Previous', sPrefix+'id*&start='+inttostr(iStart - MAX_ROWS));
html.AddTextPlain(' ');
End;
html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(iTotal div MAX_ROWS + 1), true, false);
if (iStart+MAX_ROWS < iTotal) And (iStart + MAX_ROWS < MAX_ROWS * (iTotal div MAX_ROWS)) Then
Begin
html.AddTextPlain(' ');
html.URL('Next', sPrefix+'id=*&start='+inttostr(iStart + MAX_ROWS));
End;
if (iStart+MAX_ROWS < iTotal) Then
Begin
html.AddTextPlain(' ');
html.URL('End', sPrefix+'id=*&start='+inttostr(MAX_ROWS * (iTotal div MAX_ROWS)));
End;
html.EndParagraph;
End;
html.ParaURL('Back to Start', sPrefix);
html.Done;
end;
procedure TSnomedPublisher.PublishSearch(const sPrefix, sText, sContext: String; iStart: Integer; all : boolean; html: THtmlPublisher);
var
a : TMatchArray;
i : integer;
o : TSearchCache;
iTotal : Integer;
// iDummy : Cardinal;
b2 : Boolean;
icontext : UInt64;
begin
iContext := StrToUInt64Def(sContext, 0);
Lock.Lock;
Try
if FSearchCache.Find(sText+#0+sContext, i) Then
a := TSearchCache(FSearchCache.Objects[i]).a
else
Begin
a := FSnomed.Search(iContext, sText, 0, false, all);
o := TSearchCache.Create;
o.a := a;
FSearchCache.AddObject(sText+#0+sContext, o);
End;
Finally
Lock.Unlock;
End;
if iContext <> 0 then
html.header('Search for '+sText+' in '+sContext)
Else
html.header('Search for '+sText+' in all of Snomed');
b2 := false;
html.StartTable(false, 'bare');
html.StartTableRow;
html.StartTableCell;
html.AddParagraph(' ');
html.EndTableCell;
html.StartTableCell;
html.StartList;
iTotal := High(a);
For i := iStart to Min(iStart+MAX_ROWS, iTotal) Do
Begin
if not b2 And ((i - iStart) / Min(MAX_ROWS, iTotal+1) > 0.5) Then
Begin
html.EndList;
html.EndTableCell;
html.StartTableCell;
html.StartList;
b2 := true;
End;
html.StartListItem;
ConceptRef(html, sPrefix, a[i].index, cdBoth, a[i].Priority);
html.EndListItem;
End;
html.EndList;
html.EndTableCell;
html.EndTableRow;
html.EndTable;
if (iStart > 0) or (iStart+MAX_ROWS < iTotal) Then
Begin
html.StartParagraph;
if iStart > 0 Then
Begin
html.URL('Start', sPrefix+'srch='+sText);
html.AddTextPlain(' ');
End;
if iStart > MAX_ROWS Then
Begin
html.URL('Previous', sPrefix+'srch='+sText+'&start='+inttostr(iStart - MAX_ROWS));
html.AddTextPlain(' ');
End;
html.AddText('Page '+ inttostr((iStart div MAX_ROWS) + 1)+' of '+inttostr(iTotal div MAX_ROWS + 1), true, false);
if (iStart+MAX_ROWS < iTotal) And (iStart + MAX_ROWS < MAX_ROWS * (iTotal div MAX_ROWS)) Then
Begin
html.AddTextPlain(' ');
html.URL('Next', sPrefix+'srch='+sText+'&start='+inttostr(iStart + MAX_ROWS));
End;
if (iStart+MAX_ROWS < iTotal) Then
Begin
html.AddTextPlain(' ');
html.URL('End', sPrefix+'srch='+sText+'&start='+inttostr(MAX_ROWS * (iTotal div MAX_ROWS)));
End;
html.spacer;
html.spacer;
html.spacer;
if iContext = 0 then
html.URL('Back to Context', sPrefix)
else
html.URL('Back to Context', sPrefix+'id='+sContext);
html.EndParagraph;
End;
html.Done;
end;
procedure TSnomedPublisher.PublishTerm(const sTerm: String; html: THtmlPublisher);
Begin
PublishTermConcept(false, '?type=snomed&', sTerm, 0, html)
end;
procedure TSnomedPublisher.PublishTermConcept(bRoot : Boolean; const sPrefix, sId: String; iStart : Integer; html: THtmlPublisher);
var
did : UInt64;
iId : UInt64;
iIndex : Cardinal;
Identity : UInt64;
Flags : Byte;
Active, Defining : boolean;
Group: Integer;
ParentIndex : Cardinal;
DescriptionIndex : Cardinal;
InboundIndex : Cardinal;
outboundIndex, refsets : Cardinal;
Parents : TCardinalArray;
Descriptions : TCardinalArray;
Inbounds : TCardinalArray;
outbounds : TCardinalArray;
allDesc : TCardinalArray;
iWork, iWork2, iWork3, module, kind, modifier : Cardinal;
FSN : String;
PN : String;
FPaths : TArrayofIdArray;
date : TSnomedDate;
i : integer;
Begin
SetLength(allDesc, 0);
iId := StrToUInt64Def(sId, 0);
if not FSnomed.Concept.FindConcept(iId, iIndex) Then
Begin
html.AddTitle('Snomed Concept '+sId);
html.AddParagraph(sId+' is not a valid Snomed-CT Concept Id');
SetLength(FPaths, 0);
SetLength(Parents, 0);
SetLength(Descriptions, 0);
SetLength(Inbounds, 0);
SetLength(outbounds, 0);
End
else
Begin
FSnomed.Concept.GetConcept(iIndex, Identity, Flags, date, ParentIndex, DescriptionIndex, InboundIndex, outboundIndex, refsets);
if ParentIndex <> 0 Then
Parents := FSnomed.Refs.GetReferences(ParentIndex);
Descriptions := FSnomed.Refs.GetReferences(DescriptionIndex);
Inbounds := FSnomed.Refs.GetReferences(InboundIndex);
outbounds := FSnomed.Refs.GetReferences(outboundIndex);
FSN := FSnomed.GetFSN(Descriptions);
PN := FSnomed.GetPN(Descriptions);
html.StartParagraph;
html.AddText(sId, true, true);
html.AddText(': '+screen(PN, ''), true, false);
html.EndParagraph;
html.AddParagraph(FSN);
html.StartList(false);
for i := Low(Outbounds) To High(Outbounds) Do
Begin
FSnomed.Rel.GetRelationship(Outbounds[i], did, iWork, iWork2, iWork3, module, kind, modifier, date, Active, Defining, Group);
if Defining Then
Begin
html.StartListItem;
ConceptRef(html, sPrefix, iWork3, cdDesc, 0);
html.AddTextPlain(': ');
ConceptRef(html, sPrefix, iWork2, cdDesc, 0);
html.EndListItem;
End;
End;
html.EndList(false);
html.Line;
html.StartParagraph;
html.AddText('Children', true, false);
allDesc := FSnomed.Refs.GetReferences(FSnomed.Concept.GetAllDesc(iIndex));
html.AddTextPlain(' ('+inttostr(length(alldesc))+' descendants in all)');
html.EndParagraph;
html.StartList(false);
For i := iStart to Min(iStart+MAX_ROWS, High(Inbounds)) Do
Begin
FSnomed.Rel.GetRelationship(Inbounds[i], did, iWork, iWork2, iWork3, module, kind, modifier, date, Active, Defining, Group);
if Active and (iWork3 = FSnomed.Is_a_Index) Then
Begin
html.StartListItem;
ConceptRef(html, sPrefix, iWork, cdDesc, 0);
html.EndListItem;
End;
End;
html.EndList(false);
End;
End;
function describeRefSetType(t : cardinal) : String;
begin
case t of
99 {c} : result := 'concept';
105 {i} : result := 'integer';
115 {s} : result := 'string';
else
result := '??';
end;
end;
procedure TSnomedPublisher.RefsetRef(html: THtmlPublisher; const sPrefix: String; iIndex: cardinal);
var
iDefinition, iMembersByName, iMembersByRef, iTypes, iFilename, iName, iFields: Cardinal;
types : TCardinalArray;
id : String;
i : integer;
begin
FSnomed.RefSetIndex.GetReferenceSet(iIndex, iFilename, iName, iDefinition, iMembersByName, iMembersByRef, iTypes, iFields);
id := inttostr(FSnomed.Concept.GetIdentity(iDefinition));
html.URL(Screen(id+' '+FSnomed.GetPNForConcept(iDefinition), ' reference set'), sPrefix+'id='+id);
html.AddTextPlain('(');
html.AddTextPlain(inttostr(FSnomed.RefSetMembers.GetMemberCount(iMembersByRef))+' members)');
if iTypes <> 0 then
begin
types := FSnomed.Refs.GetReferences(iTypes);
html.AddTextPlain(' (values = ');
for i := 0 to length(types) - 1 do
begin
if i > 0 then
html.AddTextPlain(', ');
html.AddTextPlain(describeRefSetType(types[i]));
end;
html.AddTextPlain(')');
end;
end;
function TSnomedPublisher.ConceptForDesc(iDesc: Cardinal; var iDescs : Cardinal): Cardinal;
var
id : UInt64;
active : boolean;
date : TSnomedDate;
module, refsets, valueses, kind, caps : Cardinal;
lang : byte;
begin
FSnomed.Desc.GetDescription(iDesc, iDescs, id, date, result, module, kind, caps, refsets, valueses, active, lang);
end;
function TSnomedPublisher.GetConceptForRefset(iRefset: Cardinal): Cardinal;
var
iDummy : Cardinal;
begin
FSnomed.RefSetIndex.GetReferenceSet(iRefset, iDummy, iDummy, result, iDummy, iDummy, iDummy, iDummy);
end;
End.
|
unit PayUtil;
interface
uses SysUtils, DB, Variants, ADODB;
type
TPayUtil = class
private
public
class function showHistory(): Boolean; overload;
class function showHistory(startDate, endDate: TDateTime): Boolean; overload;
class function showCompany(): Boolean;
class function charge(shouHuo, p: string): Boolean; //充值
class function pay(shouHuo, sum: string): Boolean; //扣费
class function lowCredit(shouHuo: string; sum: Double): Boolean; //信用等级不够
class function getLeft(shouHuo: string): Double;
class function getLastSum(carNo: string): Double;
class function getLastNet(carNo: string): Double;
class function getLastQuanter(carNo: string): Double;
class function getLastBackup6(carNo: string): Double;
class function getLastBackup7(carNo: string): Double;
class function getLastBackup8(carNo: string): Double;
class function getLastBackup9(carNo: string): Double;
class function getLastBackup15(carNo: string): Double;
class function getLastBackup16(carNo: string): Double;
class function getLastBackup17(carNo: string): Double;
class function getLastBackup18(carNo: string): Double;
end;
implementation
uses QueryDM;
{ TPayUtil }
class function TPayUtil.charge(shouHuo, p: string): Boolean;
var sum, credit: string;
begin
if shouHuo = '' then
begin
Result := True;
Exit;
end;
QueryDataModule.DBConnection.BeginTrans;
try
with QueryDataModule.ADOQExec do
begin
Close;
SQL.Text := 'select * from 收货单位 where 收货单位 = :shouHuo';
Parameters.ParamByName('shouHuo').Value := shouHuo;
Open;
if RecordCount > 0 then
begin
sum := FieldByName('当前金额').AsString;
credit := FieldByName('信用额度').AsString;
if sum = '' then
begin
SQL.Text := 'update 收货单位 set 当前金额=0 where 收货单位 = :shouHuo';
Parameters.ParamByName('shouHuo').Value := shouHuo;
ExecSQL;
end;
if credit = '' then
begin
SQL.Text := 'update 收货单位 set 信用额度=0 where 收货单位 = :shouHuo';
Parameters.ParamByName('shouHuo').Value := shouHuo;
ExecSQL;
end;
SQL.Text := 'update 收货单位 set 当前金额=当前金额+:sum where 收货单位=:shouHuo';
Parameters.ParamByName('sum').Value := StrToFloatDef(p, 0);
Parameters.ParamByName('shouHuo').Value := shouHuo;
ExecSQL;
//写入充值历史
SQL.Text := 'insert into tbl_pay_history(shouHuo,updateTime,price) '
+ 'values(:shouHuo,:update_time,:price)';
Parameters.ParamByName('shouHuo').Value := shouHuo;
Parameters.ParamByName('update_time').Value := Now;
Parameters.ParamByName('price').Value := StrToFloatDef(p, 0);
ExecSQL;
Result := True;
end
else
begin
Result := False;
end;
end;
QueryDataModule.DBConnection.CommitTrans;
except
QueryDataModule.DBConnection.RollbackTrans;
Result := False;
end;
end;
class function TPayUtil.getLastBackup15(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select top 1 备用15 from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('备用15').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLastBackup16(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select top 1 备用16 from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('备用16').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLastBackup17(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select top 1 备用17 from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('备用17').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLastBackup18(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select Max(备用18) from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('备用18').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLastBackup6(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select top 1 备用6 from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('备用6').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLastBackup7(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select top 1 备用7 from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('备用7').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLastBackup8(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select top 1 备用8 from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('备用8').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLastBackup9(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select top 1 备用9 from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('备用9').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLastNet(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select top 1 实重 from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('实重').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLastQuanter(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select top 1 方量 from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('方量').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLastSum(carNo: string): Double;
var adoq: TADOQuery;
begin
Result := 0;
adoq := TADOQuery.Create(nil);
try
adoq.Connection := QueryDataModule.DBConnection;
with adoq do
begin
Close;
SQL.Text := 'select top 1 金额 from 称重信息 where (车号=:carNo) and (净重<>0) order by 序号 desc';
Parameters.ParamByName('carNo').Value := carNo;
Open;
if not IsEmpty then
begin
Result := FieldByName('金额').AsFloat;
end;
end;
finally
adoq.Free;
end;
end;
class function TPayUtil.getLeft(shouHuo: string): Double;
begin
if shouHuo = '' then
begin
Result := 0;
Exit;
end;
with QueryDataModule.ADOQExec do
begin
Close;
SQL.Text := 'select 当前金额 from 收货单位 where 收货单位=:shouHuo';
Parameters.ParamByName('shouHuo').Value := shouHuo;
Open;
if not IsEmpty then
begin
Result := FieldByName('当前金额').AsFloat;
end;
end;
end;
class function TPayUtil.lowCredit(shouHuo: string; sum: Double): Boolean;
begin
if shouHuo = '' then
begin
Result := False;
Exit;
end;
with QueryDataModule.ADOQExec do
begin
Close;
SQL.Text := 'select 当前金额,信用额度 from 收货单位 where 收货单位=:shouHuo';
Parameters.ParamByName('shouHuo').Value := shouHuo;
Open;
if not IsEmpty then
begin
Result := FieldByName('当前金额').AsFloat - sum < FieldByName('信用额度').AsFloat;
end;
end;
end;
class function TPayUtil.pay(shouHuo, sum: string): Boolean;
begin
if shouHuo = '' then
begin
Result := True;
Exit;
end;
with QueryDataModule.ADOQExec do
begin
Close;
SQL.Text := 'update 收货单位 set 当前金额 = 当前金额 - :sum where 收货单位 = :shouHuo';
Parameters.ParamByName('sum').Value := StrToFloatDef(sum, 0);
Parameters.ParamByName('shouHuo').Value := shouHuo;
Result := ExecSQL > 0;
//写入充值历史
SQL.Text := 'insert into tbl_pay_history(shouHuo,updateTime,price) '
+ 'values(:shouHuo,:update_time,:price)';
Parameters.ParamByName('shouHuo').Value := shouHuo;
Parameters.ParamByName('update_time').Value := Now;
Parameters.ParamByName('price').Value := 0 - StrToFloatDef(sum, 0);
ExecSQL;
end;
end;
class function TPayUtil.showCompany: Boolean;
begin
with QueryDataModule.ADOQPay do
begin
Close;
SQL.Text := 'select * from 收货单位';
Open;
end;
end;
class function TPayUtil.showHistory: Boolean;
begin
with QueryDataModule.ADOQPayHistory do
begin
Close;
SQL.Clear;
SQL.Add('select * from tbl_pay_history order by id desc');
Open
end
end;
class function TPayUtil.showHistory(startDate,
endDate: TDateTime): Boolean;
begin
with QueryDataModule.ADOQPayHistory do
begin
Close;
SQL.Clear;
SQL.Add('select * from tbl_pay_history '
+ 'where updateTime between :start and :end order by id desc');
Parameters.ParamByName('start').Value := FormatDateTime('yyyy-MM-dd 00:00:00', startDate);
Parameters.ParamByName('end').Value := FormatDateTime('yyyy-MM-dd 23:59:59', endDate);
Open
end
end;
end.
|
unit frm_listados;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
Buttons, StdCtrls, ComCtrls, dmgeneral, contnrs;
type
TReportOption = class
position: integer; //For sort
name: string; //Visible name
parameterIdx: integer; //Index of Visual Tab parameters need;
processIdx: integer; //Simplest, faster and unthought way to make report functions
end;
{ TfrmListados }
TfrmListados = class(TForm)
btnExit: TBitBtn;
btnPrint: TBitBtn;
btnSaveFile: TBitBtn;
cbFileFormats: TComboBox;
Label7: TLabel;
lbReports: TListBox;
PCParametros: TPageControl;
Panel2: TPanel;
tabNula: TTabSheet;
procedure btnExitClick(Sender: TObject);
procedure btnPrintClick(Sender: TObject);
procedure btnSaveFileClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lbReportsSelectionChange(Sender: TObject; User: boolean);
private
reportOptions:TObjectList;
_carreraID: GUID_ID;
procedure CreateOptions;
procedure Initialise;
procedure ExecuteReport (reportIdx: integer; rptAction: TReportAction);
public
property carreraID: GUID_ID read _carreraID write _carreraID;
end;
var
frmListados: TfrmListados;
implementation
{$R *.lfm}
uses
rpt_clasificaciones
;
const
PARAM_NULO = 0;
RPT_CLASIFIC = 1;
RPT_PODIOS = 2;
RPT_INSCRIPTOS = 3;
{ TfrmListados }
procedure TfrmListados.btnExitClick(Sender: TObject);
begin
ModalResult:= mrOK;
end;
procedure TfrmListados.btnPrintClick(Sender: TObject);
begin
if (lbReports.ItemIndex >= 0) then
ExecuteReport((reportOptions[lbReports.ItemIndex] as TReportOption).processIdx , raPrint);
end;
procedure TfrmListados.btnSaveFileClick(Sender: TObject);
begin
if (lbReports.ItemIndex >= 0) then
begin
ExecuteReport((reportOptions[lbReports.ItemIndex] as TReportOption).processIdx
,TReportAction (cbFileFormats.Items.Objects[cbFileFormats.ItemIndex])
);
end;
end;
procedure TfrmListados.FormCreate(Sender: TObject);
begin
_carreraID:= GUIDNULO;
reportOptions:= TObjectList.Create(true);
with cbFileFormats do
begin
Items.Clear;
items.AddObject('Archivo PDF', TObject(raPDF));
items.AddObject('Archivo Excel 97-2003', TObject(raXLS));
items.AddObject('Archivo Excel', TObject(raXLSX));
ItemIndex:= 0;
end;
end;
procedure TfrmListados.FormShow(Sender: TObject);
begin
Initialise;
end;
procedure TfrmListados.lbReportsSelectionChange(Sender: TObject; User: boolean);
begin
if ((lbReports.ItemIndex < lbReports.Items.Count)
and
(lbReports.ItemIndex >= 0)
)then
PCParametros.ActivePageIndex:= (reportOptions[lbReports.ItemIndex] as TReportOption).parameterIdx;
end;
procedure TfrmListados.CreateOptions;
procedure createObj( Objpos: integer; Objname: string; ObjtabIdx, ObjProcIdx: integer);
var
obj: TReportOption;
begin
obj:= TReportOption.Create;
obj.position:= Objpos;
obj.name:= Objname;
obj.parameterIdx:= ObjtabIdx;
obj.processIdx:= ObjProcIdx;
reportOptions.Add(obj);
end;
begin
createObj(1,'Clasificaciones carrera', PARAM_NULO, RPT_CLASIFIC);
// createObj(2,'Podios por distancias y categorías', PARAM_NULO, RPT_PODIOS);
// createObj(3,'Corredores inscriptos', PARAM_NULO, RPT_INSCRIPTOS);
end;
procedure TfrmListados.Initialise;
var
iter: integer;
begin
CreateOptions;
for iter:= 0 to reportOptions.Count - 1 do
begin
lbReports.Items.Add((reportOptions[iter] as TReportOption).name);
end;
PCParametros.ActivePageIndex:= 0;
end;
procedure TfrmListados.ExecuteReport(reportIdx: integer;
rptAction: TReportAction);
var
frm: TForm;
begin
try
case reportIdx of
RPT_CLASIFIC: begin
frm:= TrptClasificaciones.Create(self);
(frm as TrptClasificaciones ).runReport ( _carreraID
, rptAction
);
end;
end;
finally
if (frm <> nil) then
frm.Free;
end;
end;
end.
|
unit UTools;
{$mode objfpc}{$H+}{$M+}
interface
uses
Classes, Controls, Graphics,
Buttons, Math, Typinfo, UFigures, UCoordinateSystem, UToolProperties;
type
TChangeEvent = procedure of Object;
TSelectedFiguresMethods = class(TObject)
public
class procedure Delete();
class procedure ToTopFigures();
class procedure ToBottomFigures();
end;
TTool = Class(TObject)
public
Tools: array of TTool; static;
ButtonOnForm: TBitBtn;
ImageOfButton: TBitmap;
Figure: TFigure; static;
class procedure AddTool(Tool: TTool);
constructor Create(PathToFile: String);
class procedure FindMinMaxCoordinate(WPoint: TWorldPoint);
class procedure ShowProperties(ATool: TTool; Panel: TWinControl);
procedure CreateFigure(); virtual;
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); virtual; abstract;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); virtual; abstract;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); virtual; abstract;
end;
{ TTPaint }
TTPaint = Class(TTool)
public
OnChange: TChangeEvent; static;
end;
TTPen = Class(TTPaint)
public
procedure CreateFigure(); override;
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
end;
TTLine = Class(TTPaint)
public
procedure CreateFigure(); override;
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
end;
TTPolyline = Class(TTPaint)
public
procedure CreateFigure(); override;
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
end;
TTRectangle = Class(TTPaint)
public
procedure CreateFigure(); override;
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
end;
TTRoundRectangle = Class(TTPaint)
public
procedure CreateFigure(); override;
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
end;
TTEllipse = Class(TTPaint)
public
procedure CreateFigure(); override;
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
end;
TTLoupe = Class(TTool)
public
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
end;
TTHand = Class(TTool)
private
StartPos: TWorldPoint; static;
public
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
end;
TTRectangleLoupe = Class(TTool)
public
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
end;
TTSelect = Class(TTool)
private
OnDownPos, StartPos, FigureOffset: TWorldPoint;
IsShiftWasDown: Boolean;
public
procedure OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint); override;
procedure OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint); override;
end;
const
SpaceBetweenButtons = 7;
SizeOfButton = 36;
MinZoom = 0.01;
MaxZoom = 90;
var
IsMouseDown: Boolean;
MinCoordinate, MaxCoordinate: TWorldPoint;
PropPanel: TWinControl;
implementation
const
ZoomOfLoupe = 0.3;
var
ToolParams: TToolProps;
class procedure TTool.FindMinMaxCoordinate(WPoint: TWorldPoint);
begin
MinCoordinate:= WorldPoint(Min(WPoint.X, MinCoordinate.X), Min(WPoint.Y, MinCoordinate.Y));
MaxCoordinate:= WorldPoint(Max(WPoint.X, MaxCoordinate.X), Max(WPoint.Y, MaxCoordinate.Y));
end;
class procedure TSelectedFiguresMethods.Delete;
var
i: Integer;
TempFigures: array of TFigure;
begin
SetLength(TempFigures, 0);
for i:= 0 to High(Figures) do
if not Figures[i].IsSelected then begin
SetLength(TempFigures, Length(TempFigures) + 1);
TempFigures[High(TempFigures)]:= Figures[i];
end;
Figures:= TempFigures;
end;
class procedure TSelectedFiguresMethods.ToTopFigures;
var
i, j: Integer;
TempFigures: array of TFigure;
begin
SetLength(TempFigures, Length(Figures));
j:= High(Figures);
for i:= 0 to High(Figures) do
if Figures[i].IsSelected then begin
TempFigures[j]:= Figures[i];
dec(j);
end;
for i:= High(Figures) downto 0 do
if not Figures[i].IsSelected then begin
TempFigures[j]:= Figures[i];
Dec(j);
end;
Figures:= TempFigures;
end;
class procedure TSelectedFiguresMethods.ToBottomFigures;
var
i, j: Integer;
TempFigures: array of TFigure;
begin
SetLength(TempFigures, Length(Figures));
j:= 0;
for i:= 0 to High(Figures) do
if Figures[i].IsSelected then begin
TempFigures[j]:= Figures[i];
Inc(j);
end;
for i:= 0 to High(Figures) do
if not Figures[i].IsSelected then begin
TempFigures[j]:= Figures[i];
Inc(j);
end;
Figures:= TempFigures;
end;
class procedure TTool.ShowProperties(ATool: TTool; Panel: TWinControl);
begin
ToolParams.Delete;
ATool.CreateFigure();
ToolParams:= TToolProps.Create(Figure, Panel);
end;
constructor TTool.Create(PathToFile: String);
begin
ImageOfButton:= TBitmap.Create;
ImageOfButton.Height:= SizeOfButton;
ImageOfButton.Width:= SizeOfButton;
ImageOfButton.LoadFromFile(PathToFile);
end;
class procedure TTool.AddTool(Tool: TTool);
begin
SetLength(Tools, Length(Tools) + 1);
Tools[High(Tools)]:= Tool;
end;
procedure TTool.CreateFigure;
begin
Figure:= Nil;
end;
procedure TTPen.CreateFigure();
begin
Figure:= TPen.Create;
TToolProps.ApplyProps(Figure);
end;
procedure TTPen.OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TPen).AddPoint(WPoint);
TTool.FindMinMaxCoordinate(WPoint);
OnChange;
end;
procedure TTPen.OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TPen).AddPoint(WPoint);
TTool.FindMinMaxCoordinate(WPoint);
end;
procedure TTPen.OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TPen).AddPoint(WPoint);
TFigure.AddFigure(Figure);
CreateFigure();
TTool.FindMinMaxCoordinate(WPoint);
TFigure.SaveToHistory();
end;
procedure TTLine.CreateFigure();
begin
Figure:= TLine.Create;
TToolProps.ApplyProps(Figure);
end;
procedure TTLine.OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TLine).StartP:= WPoint;
(Figure as TLine).EndP:= WPoint;
TTool.FindMinMaxCoordinate(WPoint);
OnChange;
end;
procedure TTLine.OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TLine).EndP:= WPoint;
TTool.FindMinMaxCoordinate(WPoint);
end;
procedure TTLine.OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
var
ALine: TLine;
begin
ALine:= (Figure as TLine);
ALine.EndP:= WPoint;
ALine.MinP:= WorldPoint(Min(ALine.StartP.X, ALine.EndP.X), Min(ALine.StartP.Y, ALine.EndP.Y));
ALine.MaxP:= WorldPoint(Max(ALine.StartP.X, ALine.EndP.X), Max(ALine.StartP.Y, ALine.EndP.Y));
TFigure.AddFigure(Figure);
CreateFigure();
TTool.FindMinMaxCoordinate(WPoint);
TFigure.SaveToHistory();
end;
procedure TTPolyline.CreateFigure();
begin
Figure:= TPolyline.Create;
TToolProps.ApplyProps(Figure);
end;
procedure TTPolyline.OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
var
ALine: TLine;
begin
OnChange;
ALine:= TLine.Create;
ALine.StartP:= WPoint;
ALine.EndP:= WPoint;
if (Button = mbRight) and ((Figure as TPolyline).GetLastLine <> Nil) then begin
(Figure as TPolyline).GetLastLine().EndP:= WPoint;
(Figure as TPolyline).AddLine(ALine);
TFigure.AddFigure(Figure);
CreateFigure();
IsMouseDown:= False;
TFigure.SaveToHistory();
Exit;
end
else if Button = mbRight then Exit;
(Figure as TPolyline).AddLine(ALine);
TTool.FindMinMaxCoordinate(WPoint);
end;
procedure TTPolyline.OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint);
begin
if (Figure as TPolyline).GetLastLine <> Nil then
(Figure as TPolyline).GetLastLine().EndP:= WPoint;
TTool.FindMinMaxCoordinate(WPoint);
end;
procedure TTPolyline.OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
IsMouseDown:= True;
if Button = mbRight then IsMouseDown:= False;
TTool.FindMinMaxCoordinate(WPoint);
end;
procedure TTRectangle.CreateFigure();
begin
Figure:= TRectangle.Create;
TToolProps.ApplyProps(Figure);
end;
procedure TTRectangle.OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TRectangle).StartP:= WPoint;
(Figure as TRectangle).EndP:= WPoint;
TTool.FindMinMaxCoordinate(WPoint);
OnChange;
end;
procedure TTRectangle.OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TRectangle).EndP:= WPoint;
TTool.FindMinMaxCoordinate(WPoint);
end;
procedure TTRectangle.OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TRectangle).EndP:= WPoint;
TFigure.AddFigure(Figure);
CreateFigure();
TTool.FindMinMaxCoordinate(WPoint);
TFigure.SaveToHistory();
end;
procedure TTRoundRectangle.CreateFigure();
begin
Figure:= TRoundRectangle.Create;
TToolProps.ApplyProps(Figure);
end;
procedure TTRoundRectangle.OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TRoundRectangle).StartP:= WPoint;
(Figure as TRoundRectangle).EndP:= WPoint;
TTool.FindMinMaxCoordinate(WPoint);
OnChange;
end;
procedure TTRoundRectangle.OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TRoundRectangle).EndP:= WPoint;
TTool.FindMinMaxCoordinate(WPoint);
end;
procedure TTRoundRectangle.OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TRoundRectangle).EndP:= WPoint;
TFigure.AddFigure(Figure);
CreateFigure();
TTool.FindMinMaxCoordinate(WPoint);
TFigure.SaveToHistory();
end;
procedure TTEllipse.CreateFigure();
begin
Figure:= TEllipse.Create;
TToolProps.ApplyProps(Figure);
end;
procedure TTEllipse.OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TEllipse).StartP:= WPoint;
(Figure as TEllipse).EndP:= WPoint;
TTool.FindMinMaxCoordinate(WPoint);
OnChange;
end;
procedure TTEllipse.OnMouseMove(Shift: TShiftState;WPoint: TWorldPoint);
begin
(Figure as TEllipse).EndP:= WPoint;
TTool.FindMinMaxCoordinate(WPoint);
end;
procedure TTEllipse.OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
(Figure as TEllipse).EndP:= WPoint;
TFigure.AddFigure(Figure);
CreateFigure();
TTool.FindMinMaxCoordinate(WPoint);
TFigure.SaveToHistory();
end;
procedure TTLoupe.OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
var
startP: TPoint;
begin
startP:= ToScreenPoint(WPoint);
if Button = mbLeft then
Zoom+= ZoomOfLoupe
else if Button = mbRight then
Zoom-= ZoomOfLoupe;
Delta.X+= ToScreenPoint(WPoint).X - startP.X;
Delta.Y+= ToScreenPoint(WPoint).Y - startP.Y;
end;
procedure TTLoupe.OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint);
begin
end;
procedure TTLoupe.OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
end;
procedure TTHand.OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
TTHand.StartPos:= WPoint;
end;
procedure TTHand.OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint);
begin
Delta.X+= (StartPos.X - WPoint.X) * Zoom;
Delta.Y+= (StartPos.Y - WPoint.Y) * Zoom;
end;
procedure TTHand.OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
end;
procedure TTRectangleLoupe.OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
begin
TFigure.AddFigure(TRectangle.Create());
(TFigure.GetLastFigure() as TFillFigure).BrushStyle:= bsClear;
(TFigure.GetLastFigure() as TRectangle).StartP:= WPoint;
(TFigure.GetLastFigure() as TRectangle).EndP:= WPoint;
end;
procedure TTRectangleLoupe.OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint);
begin
(TFigure.GetLastFigure() as TRectangle).EndP:= WPoint;
end;
procedure TTRectangleLoupe.OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
var
Rect: TRectangle;
begin
(TFigure.GetLastFigure() as TRectangle).EndP:= WPoint;
Rect:=(TFigure.GetLastFigure() as TRectangle);
if (Rect.StartP.X = Rect.EndP.X) or (Rect.StartP.Y = Rect.EndP.Y) then Exit;
if Min(SizeOfWindow.X / Abs(Rect.StartP.X - Rect.EndP.X),
SizeOfWindow.Y / Abs(Rect.StartP.Y - Rect.EndP.Y)) < MaxZoom then
Zoom:= Min(SizeOfWindow.X / Abs(Rect.StartP.X - Rect.EndP.X),
SizeOfWindow.Y / Abs(Rect.StartP.Y - Rect.EndP.Y));
Delta.X:= Min(Rect.StartP.X, Rect.EndP.X) * Zoom;
Delta.Y:= Min(Rect.StartP.Y, Rect.EndP.Y) * Zoom;
TFigure.DeleteLastFigure();
end;
procedure TTSelect.OnMouseDown(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
var
i: Integer;
begin
StartPos:= WPoint;
OnDownPos:= WPoint;
if Shift = [ssShift] then begin
FigureOffset:= WorldPoint(0, 0);
Exit;
end
else if not(Shift = [ssCtrl]) then begin
for i:=0 to High(Figures) do
Figures[i].IsSelected:= False;
end
else if Shift = [ssShift, ssCtrl] then Exit;
if not(ssShift in Shift) and (IsShiftWasDown) then
IsShiftWasDown:= False;
TFigure.AddFigure(TRectangle.Create());
(TFigure.GetLastFigure() as TFillFigure).BrushStyle:= bsClear;
(TFigure.GetLastFigure() as TFillFigure).PenStyle:= psDash;
(TFigure.GetLastFigure() as TFillFigure).PenWidth:= 3;
(TFigure.GetLastFigure() as TFillFigure).SetPenColor(clBlue);
(TFigure.GetLastFigure() as TRectangle).StartP:= WPoint;
(TFigure.GetLastFigure() as TRectangle).EndP:= WPoint;
end;
procedure TTSelect.OnMouseMove(Shift: TShiftState; WPoint: TWorldPoint);
var
StartP, EndP: TPoint;
SelectRect: TRect;
i: Integer;
begin
if Shift = [ssShift] then begin
FigureOffset.X:= WPoint.X - StartPos.X;
FigureOffset.Y:= WPoint.Y - StartPos.Y;
StartPos:= WPoint;
for i:= 0 to High(Figures) do
if Figures[i].IsSelected then
Figures[i].Depose(FigureOffset);
IsShiftWasDown:= True;
Exit;
end
else if Shift = [ssShift, ssCtrl] then Exit;
if IsShiftWasDown then Exit;
(TFigure.GetLastFigure() as TRectangle).EndP:= WPoint;
StartP:= ToScreenPoint((TFigure.GetLastFigure() as TRectangle).StartP);
EndP:= ToScreenPoint((TFigure.GetLastFigure() as TRectangle).EndP);
SelectRect:= Rect(StartP.x, StartP.y, EndP.x, EndP.y);
for i:=High(Figures) - 1 downto 0 do begin
Figures[i].IsSelected:= Figures[i].IsInside(SelectRect);
if (Figures[i].IsInside(SelectRect)) and (StartPos.X = WPoint.X)
and (StartPos.Y = StartPos.Y) then
Break;
end;
end;
procedure TTSelect.OnMouseUp(Button: TMouseButton; Shift: TShiftState; WPoint: TWorldPoint);
var
SelectedFigures: array of TObject;
i: Integer;
begin
if IsShiftWasDown and (OnDownPos.X <> WPoint.X) and (OnDownPos.Y <> WPoint.Y) then
TFigure.SaveToHistory();
if (Shift = [ssShift, ssCtrl]) or (Shift = [ssShift]) then
Exit;
if not(ssShift in Shift) and (IsShiftWasDown) then begin
IsShiftWasDown:= False;
Exit;
end;
OnMouseMove(Shift, WPoint);
TFigure.DeleteLastFigure();
SetLength(SelectedFigures, 0);
for i:= 0 to High(Figures) do
if Figures[i].IsSelected then begin
SetLength(SelectedFigures, Length(SelectedFigures) + 1);
SelectedFigures[High(SelectedFigures)]:= Figures[i];
end;
ToolParams.Delete;
TToolProps.Create(SelectedFigures, PropPanel);
end;
initialization
TTool.AddTool(TTPen.Create('img\pen.bmp'));
TTool.AddTool(TTLine.Create('img\line.bmp'));
TTool.AddTool(TTPolyline.Create('img\polyline.bmp'));
TTool.AddTool(TTRectangle.Create('img\rectangle.bmp'));
TTool.AddTool(TTRoundRectangle.Create('img\roundRect.bmp'));
TTool.AddTool(TTEllipse.Create('img\ellipse.bmp'));
TTool.AddTool(TTLoupe.Create('img\loupe.bmp'));
TTool.AddTool(TTHand.Create('img\hand.bmp'));
TTool.AddTool(TTRectangleLoupe.Create('img\rectangleLoupe.bmp'));
TTool.AddTool(TTSelect.Create('img\cursor.bmp'));
end.
|
unit UFerramentasB;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, StdCtrls,
Forms, DBCtrls, DB, DBTables, Buttons, ExtCtrls, Dialogs, DConexao, Grids,
DBGrids, TeeProcs, TeEngine, Chart, DBChart, DBCGrids, Dbiprocs, DBClient;
procedure AbreQry(vptQry: TQuery);
procedure AbreTbl(vptTbl: TTable);
procedure AbreCds(vptCds: TClientDataSet);
function ProxCod(vpsTabela, vpsNomeCampo, vpsWhere: String): Integer;
function UltimoGeneratorCriado(vpsTabela: String): Integer;
function RegistroJaExiste(vpsTabela, vpsNomeCampo, vpsConteudo: String): Boolean;
function DataHoraAtual: TDateTime;
procedure SetaDataSource(vptDataSource: TDataSource; vptForm: TForm);
procedure SetaListSource(vptListSource: TDataSource; vptForm: TForm);
procedure BeginTransaction;
procedure CommitTransaction;
procedure RollbackTransaction;
function SomaAnosNaData(vpiQtdAnos: Integer; vptDataHora: TDateTime): TDateTime;
function SomaMesesNaData(vpiQtdMeses: Integer; vptDataHora: TDateTime): TDateTime;
function SomaDiasNaData(vpiQtdDias: Integer; vptDataHora: TDateTime): TDateTime;
function SomaHorasNaData(vpiQtdHoras: Integer; vptDataHora: TDateTime): TDateTime;
function SomaMinutosNaData(vpiQtdMinutos: Integer; vptDataHora: TDateTime): TDateTime;
function SomaSegundosNaData(vpiQtdSegundos: Integer; vptDataHora: TDateTime): TDateTime;
implementation
uses
uFerramentas;
procedure AbreQry(vptQry: TQuery);
begin
try
vptQry.Active := False;
vptQry.Active := True;
except
on E: Exception do
begin
Screen.Cursor:= crDefault;
MessageBeep(0);
MessageDlg(
'Erro ao abrir a query [' + vptQry.Name + '] ' + #13 + #13 +
'[' + E.message + '] ' + #13 + #13 +
'SQL [' + vptQry.SQL.Text + ']!',
mtWarning, [mbAbort], 0);
Halt;
end;
end;
end;
procedure AbreTbl(vptTbl: TTable);
begin
try
vptTbl.Open;
except
on E: Exception do
begin
Screen.Cursor:= crDefault;
MessageBeep(0);
MessageDlg(
'Não foi possível abrir a tabela [' + vptTbl.TableName + '] ' + #13 + #13 +
'[' + E.message + ']!',
mtWarning, [mbAbort], 0);
Halt;
end;
end;
end;
procedure AbreCds(vptCds: TClientDataSet);
begin
try
vptCds.Open;
except
on E: Exception do
begin
Screen.Cursor:= crDefault;
MessageBeep(0);
MessageDlg(
'Não foi possível abrir o ClientDataSet [' + vptCds.Name + '] ' + #13 + #13 +
'[' + E.message + ']!',
mtWarning, [mbAbort], 0);
Halt;
end;
end;
end;
function ProxCod(vpsTabela, vpsNomeCampo, vpsWhere: String): Integer;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
with vltQry do
begin
Close;
Databasename := DmConexao.DbsConexao.DatabaseName;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' MAX(' + vpsNomeCampo + ') ');
Sql.Add('FROM ');
Sql.Add(vpsTabela);
if vpsWhere > '' then
Sql.Add('WHERE ' + vpsWhere);
Open;
Result := vltQry.Fields[0].AsInteger + 1;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
function UltimoGeneratorCriado(vpsTabela: String): Integer;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
vltQry.Close;
vltQry.Databasename := DmConexao.DbsConexao.DatabaseName;
vltQry.Sql.Text :=
'SELECT GEN_ID(GN_' + vpsTabela + ',0) as GEN_ID '+#13+
'FROM RDB$DATABASE '+#13;
vltQry.Open;
Result := vltQry.FieldByName('GEN_ID').AsInteger;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
function RegistroJaExiste(vpsTabela, vpsNomeCampo, vpsConteudo: String): Boolean;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
with vltQry do
begin
Close;
Databasename := DmConexao.DbsConexao.DatabaseName;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' ' + vpsNomeCampo + ' as "COD" ');
Sql.Add('FROM ');
Sql.Add(vpsTabela);
Sql.Add('WHERE ' + vpsNomeCampo + ' = ' + vpsConteudo);
Open;
Result := not vltQry.IsEmpty;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
function DataHoraAtual: TDateTime;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
with vltQry do
begin
Close;
Databasename := DmConexao.DbsConexao.DatabaseName;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' CURRENT_TIMESTAMP AS DATAHORAATUAL ');
Sql.Add('FROM ');
Sql.Add(' RDB$DATABASE ');
Open;
Result := vltQry.Fields[0].AsDateTime;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
// SetaDataSource >> força o DataSource ser o Dml instaciado e não do Dm
// pois quando abre mais de uma vez o Dm ele utiliza o visual
procedure SetaDataSource(vptDataSource: TDataSource; vptForm: TForm);
var
vlb1: Boolean;
vli1,
vli2: Integer;
vltForm: TForm;
begin
vlb1 := False;
vltForm := nil;
with Application do
for vli1 := ComponentCount - 1 downto 0 do
if Components[vli1] is TForm then
if TForm(Components[vli1]).Name = vptForm.Name then
begin
vltForm := TForm(Components[vli1]);
vlb1 := True;
Break;
end;
if not vlb1 then
Exit;
for vli2 := vltForm.ComponentCount - 1 downto 0 do
begin
if vltForm.Components[vli2] is TDBGrid then
if (TDBGrid(vltForm.Components[vli2]).DataSource <> nil) then
if TDBGrid(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBGrid(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBNavigator then
if (TDBNavigator(vltForm.Components[vli2]).DataSource <> nil) then
if TDBNavigator(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBNavigator(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBText then
if (TDBText(vltForm.Components[vli2]).DataSource <> nil) then
if TDBText(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBText(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBEdit then
if (TDBEdit(vltForm.Components[vli2]).DataSource <> nil) then
if TDBEdit(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBEdit(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBMemo then
if (TDBMemo(vltForm.Components[vli2]).DataSource <> nil) then
if TDBMemo(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBMemo(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBImage then
if (TDBImage(vltForm.Components[vli2]).DataSource <> nil) then
if TDBImage(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBImage(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBListBox then
if (TDBListBox(vltForm.Components[vli2]).DataSource <> nil) then
if TDBListBox(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBListBox(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBComboBox then
if (TDBComboBox(vltForm.Components[vli2]).DataSource <> nil) then
if TDBComboBox(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBComboBox(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBCheckBox then
if (TDBCheckBox(vltForm.Components[vli2]).DataSource <> nil) then
if TDBCheckBox(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBCheckBox(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBRadioGroup then
if (TDBRadioGroup(vltForm.Components[vli2]).DataSource <> nil) then
if TDBRadioGroup(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBRadioGroup(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBLookupListBox then
begin
if (TDBLookupListBox(vltForm.Components[vli2]).DataSource <> nil) then
if TDBLookupListBox(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBLookupListBox(vltForm.Components[vli2]).DataSource := vptDataSource;
// Utilizar o SetaListSource para o ListSource
// if TDBLookupListBox(vltForm.Components[vli2]).ListSource.Name = vptListSource.Name then
// TDBLookupListBox(vltForm.Components[vli2]).ListSource.Name := vptListSource;
end;
if vltForm.Components[vli2] is TDBLookupComboBox then
begin
if (TDBLookupComboBox(vltForm.Components[vli2]).DataSource <> nil) then
if TDBLookupComboBox(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBLookupComboBox(vltForm.Components[vli2]).DataSource := vptDataSource;
// Utilizar o SetaListSource para o ListSource
// if TDBLookupComboBox(vltForm.Components[vli2]).ListSource.Name = vptListSource.Name then
// TDBLookupComboBox(vltForm.Components[vli2]).ListSource.Name := vptListSource;
end;
if vltForm.Components[vli2] is TDBRichEdit then
if (TDBRichEdit(vltForm.Components[vli2]).DataSource <> nil) then
if TDBRichEdit(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBRichEdit(vltForm.Components[vli2]).DataSource := vptDataSource;
if vltForm.Components[vli2] is TDBCtrlGrid then
if (TDBCtrlGrid(vltForm.Components[vli2]).DataSource <> nil) then
if TDBCtrlGrid(vltForm.Components[vli2]).DataSource.Name = vptDataSource.Name then
TDBCtrlGrid(vltForm.Components[vli2]).DataSource := vptDataSource;
end;
end;
procedure SetaListSource(vptListSource: TDataSource; vptForm: TForm);
var
vlb1: Boolean;
vli1,
vli2: Integer;
vltForm: TForm;
begin
vlb1 := False;
vltForm := nil;
with Application do
for vli1 := ComponentCount - 1 downto 0 do
if Components[vli1] is TForm then
if TForm(Components[vli1]).Name = vptForm.Name then
begin
vltForm := TForm(Components[vli1]);
vlb1 := True;
Break;
end;
if not vlb1 then
Exit;
for vli2 := vltForm.ComponentCount - 1 downto 0 do
begin
if vltForm.Components[vli2] is TDBLookupListBox then
begin
if TDBLookupListBox(vltForm.Components[vli2]).ListSource.Name = vptListSource.Name then
TDBLookupListBox(vltForm.Components[vli2]).ListSource := vptListSource;
end;
if vltForm.Components[vli2] is TDBLookupComboBox then
begin
if TDBLookupComboBox(vltForm.Components[vli2]).ListSource.Name = vptListSource.Name then
TDBLookupComboBox(vltForm.Components[vli2]).ListSource := vptListSource;
end;
end;
end;
procedure BeginTransaction;
begin
Inc(vgiTransaction);
if not DmConexao.DbsConexao.InTransaction then
DmConexao.DbsConexao.StartTransaction;
end;
procedure CommitTransaction;
begin
Dec(vgiTransaction);
if DmConexao.DbsConexao.InTransaction then
if vgiTransaction = 0 then
DmConexao.DbsConexao.Commit;
end;
procedure RollbackTransaction;
begin
Dec(vgiTransaction);
if DmConexao.DbsConexao.InTransaction then
if vgiTransaction = 0 then
DmConexao.DbsConexao.Rollback;
end;
function SomaAnosNaData(vpiQtdAnos: Integer; vptDataHora: TDateTime): TDateTime;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
with vltQry do
begin
Close;
Databasename := DmConexao.DbsConexao.DatabaseName;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' DATEADD(:VPIQTDANOS YEAR TO :VPTDATAHORA) AS DTH ');
Sql.Add('FROM ');
Sql.Add(' RDB$DATABASE ');
ParamByName('VPIQTDANOS').AsInteger := vpiQtdAnos;
ParamByName('VPTDATAHORA').AsDateTime := vptDataHora;
Open;
Result := vltQry.Fields[0].AsDateTime;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
function SomaMesesNaData(vpiQtdMeses: Integer; vptDataHora: TDateTime): TDateTime;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
with vltQry do
begin
Close;
Databasename := DmConexao.DbsConexao.DatabaseName;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' DATEADD(:VPIQTDMESES MONTH TO :VPTDATAHORA) AS DTH ');
Sql.Add('FROM ');
Sql.Add(' RDB$DATABASE ');
ParamByName('VPIQTDMESES').AsInteger := vpiQtdMeses;
ParamByName('VPTDATAHORA').AsDateTime := vptDataHora;
Open;
Result := vltQry.Fields[0].AsDateTime;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
function SomaDiasNaData(vpiQtdDias: Integer; vptDataHora: TDateTime): TDateTime;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
with vltQry do
begin
Close;
Databasename := DmConexao.DbsConexao.DatabaseName;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' DATEADD(:VPIQTDDIAS DAY TO :VPTDATAHORA) AS DTH ');
Sql.Add('FROM ');
Sql.Add(' RDB$DATABASE ');
ParamByName('VPIQTDDIAS').AsInteger := vpiQtdDias;
ParamByName('VPTDATAHORA').AsDateTime := vptDataHora;
Open;
Result := vltQry.Fields[0].AsDateTime;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
function SomaHorasNaData(vpiQtdHoras: Integer; vptDataHora: TDateTime): TDateTime;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
with vltQry do
begin
Close;
Databasename := DmConexao.DbsConexao.DatabaseName;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' DATEADD(:VPIQTDHORAS HOUR TO :VPTDATAHORA) AS DTH ');
Sql.Add('FROM ');
Sql.Add(' RDB$DATABASE ');
ParamByName('VPIQTDHORAS').AsInteger := vpiQtdHoras;
ParamByName('VPTDATAHORA').AsDateTime := vptDataHora;
Open;
Result := vltQry.Fields[0].AsDateTime;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
function SomaMinutosNaData(vpiQtdMinutos: Integer; vptDataHora: TDateTime): TDateTime;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
with vltQry do
begin
Close;
Databasename := DmConexao.DbsConexao.DatabaseName;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' DATEADD(:VPIQTDMINUTOS MINUTE TO :VPTDATAHORA) AS DTH ');
Sql.Add('FROM ');
Sql.Add(' RDB$DATABASE ');
ParamByName('VPIQTDMINUTOS').AsInteger := vpiQtdMinutos;
ParamByName('VPTDATAHORA').AsDateTime := vptDataHora;
Open;
Result := vltQry.Fields[0].AsDateTime;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
function SomaSegundosNaData(vpiQtdSegundos: Integer; vptDataHora: TDateTime): TDateTime;
var
vltQry: TQuery;
begin
vltQry := TQuery.Create(nil);
try
with vltQry do
begin
Close;
Databasename := DmConexao.DbsConexao.DatabaseName;
Sql.Clear;
Sql.Add('SELECT ');
Sql.Add(' DATEADD(:VPIQTDSEGUNDOS SECOND TO :VPTDATAHORA) AS DTH ');
Sql.Add('FROM ');
Sql.Add(' RDB$DATABASE ');
ParamByName('VPIQTDSEGUNDOS').AsInteger := vpiQtdSegundos;
ParamByName('VPTDATAHORA').AsDateTime := vptDataHora;
Open;
Result := vltQry.Fields[0].AsDateTime;
end;
finally
if Assigned(vltQry) then
vltQry.Free;
end;
end;
end.
|
unit AccessCheck;
{obsolete, all files are now in the user or temp folder}
{$MODE Delphi}
{
This unit will contain routines to be used for testing and verifying that ce has
the required access needed.
FileAccessTest is the main routine
}
interface
uses LCLIntf, SysUtils, classes, forms, CEFuncProc, NewKernelHandler;
procedure FileAccessTest;
implementation
uses Globals;
resourcestring
rsNoFileCreationRightsOrNoFileOverwriteRights = 'No file creation rights or no file overwrite rights';
rsNoFileModificationRights = 'No file modification rights';
rsNoFileDeletionRights = 'No file deletion rights';
rsNoDeleteRights = 'No delete rights';
rsButYouDoHaveModifyRights = 'But you do have modify rights';
procedure FileAccessTest;
var f: tfilestream;
begin
try
f:=TFilestream.Create(CheatEngineDir+'accesscheck.tmp', fmCreate);
try
f.WriteBuffer(rsNoDeleteRights+#13#10,18);
finally
f.Free;
end;
except
raise exception.Create(rsNoFileCreationRightsOrNoFileOverwriteRights);
end;
try
f:=TFilestream.Create(CheatEngineDir+'accesscheck.tmp', fmOpenReadWrite);
try
f.Seek(0,soFromEnd);
f.WriteBuffer(rsButYouDoHaveModifyRights+#13#10,31);
finally
f.free;
end;
except
raise exception.Create(rsNoFileModificationRights);
end;
if not deletefile(CheatEngineDir+'accesscheck.tmp') then
raise exception.Create(rsNoFileDeletionRights);
end;
end.
|
unit MatrixFunctionalTest;
{$mode objfpc}{$H+}
{$CODEALIGN LOCALMIN=16}
{$CODEALIGN CONSTMIN=16}
interface
uses
Classes, SysUtils, fpcunit, testregistry, BaseTestCase,
native, BZVectorMath;
type
TMatrixFunctionalTest = class(TVectorBaseTestCase)
private
{returns a matrix with the exception of the item Pos
can be used for finding the sign/position bug in code
Expand tests as needed with one of these it may lead to finding
which sign / position is wrong in the code. And it improves tests in
longer term Pos 1 - 16 any other value will default.}
function OddPosition(Pos: Integer; AValue: Single): TBZMatrix4f;
{ similar to above but alters 2x2 portion of the matrix
Pos 1 to 9 top left to bottom right in left -> right top -> bottom order}
function OddTwoByTwo(Pos: Integer; AValue: Single): TBZMatrix4f;
protected
procedure Setup; override;
public
{$CODEALIGN RECORDMIN=16}
mKnownDet, invKnown, ResMat: TBZMatrix4f; // has det of -50
mtx1, mtx2, mtx3, mtx4 : TBZMatrix4f;
aqt1 : TBZQuaternion;
apl1 : TBZHmgPlane;
{$CODEALIGN RECORDMIN=4}
published
procedure TestOpAddMatrix;
procedure TestOpAddSingle;
procedure TestOpSubMatrix;
procedure TestOpSubSingle;
procedure TestDeterminant;
procedure TestTranspose;
procedure TestGetDeterminant;
procedure TestInverse;
procedure TestOpMultMatrix;
procedure TestOpMulVector;
procedure TestOpVectorMulMat;
procedure TestTransposeVectorMulMat;
procedure TestOpDivSingle;
procedure TestOpNegate;
procedure TestCreateIdentity;
procedure TestCreateScaleVector;
procedure TestCreateScaleAffine;
procedure TestCreateTransVector;
procedure TestCreateTransAffine;
procedure TestCreateScaleTransVector;
procedure TestCreateRotationMatrixXAngle;
procedure TestCreateRotationMatrixXSinCos;
procedure TestCreateRotationMatrixYAngle;
procedure TestCreateRotationMatrixYSinCos;
procedure TestCreateRotationMatrixZAngle;
procedure TestCreateRotationMatrixZSinCos;
procedure TestCreateRotationMatrixAxisAngle;
procedure TestCreateLookAtMatrix;
procedure TestCreateParallelProjectionMatrix;
end;
implementation
{%region%----[ Const]---------------------------------------------------------}
const
// 1-9s are good matrices for testing look simple but have a nasty det of 0
// which is good for breaking naive routines. Also tests the where 3x3
// is used in an implementation
M_LOWER_LEFT_1_9 : TBZMatrix = (V:(
(X:1; Y:1; Z:1; W:1),
(X:1; Y:2; Z:3; W:1),
(X:4; Y:5; Z:6; W:1),
(X:7; Y:8; Z:9; W:1)
));
M_UPPER_LEFT_1_9 : TBZMatrix = (V:(
(X:1; Y:2; Z:3; W:1),
(X:4; Y:5; Z:6; W:1),
(X:7; Y:8; Z:9; W:1),
(X:1; Y:1; Z:1; W:1)
));
M_LOWER_RIGHT_1_9 : TBZMatrix = (V:(
(X:1; Y:1; Z:1; W:1),
(X:1; Y:1; Z:2; W:3),
(X:1; Y:4; Z:5; W:6),
(X:1; Y:7; Z:8; W:9)
));
M_UPPER_RIGHT_1_9 : TBZMatrix = (V:(
(X:1; Y:1; Z:2; W:3),
(X:1; Y:4; Z:5; W:6),
(X:1; Y:7; Z:8; W:9),
(X:1; Y:1; Z:1; W:1)
));
{%endregion%}
procedure TMatrixFunctionalTest.Setup;
begin
inherited Setup;
mKnownDet.V[0].Create(-2,2,-3,1);
mKnownDet.V[1].Create(-1,1,3,1);
mKnownDet.V[2].Create(2,0,-1,1);
mKnownDet.V[3].Create(2,2,2,1);
invKnown.V[0].Create(-0.1, -0.2, 0.1, 0.2 );
invKnown.V[1].Create(0.18, -0.24, -0.38, 0.44);
invKnown.V[2].Create(-0.12, 0.16, -0.08, 0.04);
invKnown.V[3].Create(0.08, 0.56, 0.72, -0.36);
end;
procedure TMatrixFunctionalTest.TestOpAddMatrix;
begin
mtx3 := M_LOWER_LEFT_1_9 + M_UPPER_RIGHT_1_9;
AssertEquals('AddMatrix:Sub1 m11 ', 2, mtx3.m11);
AssertEquals('AddMatrix:Sub2 m12 ', 2, mtx3.m12);
AssertEquals('AddMatrix:Sub3 m13 ', 3, mtx3.m13);
AssertEquals('AddMatrix:Sub4 m14 ', 4, mtx3.m14);
AssertEquals('AddMatrix:Sub5 m21 ', 2, mtx3.m21);
AssertEquals('AddMatrix:Sub6 m22 ', 6, mtx3.m22);
AssertEquals('AddMatrix:Sub7 m23 ', 8, mtx3.m23);
AssertEquals('AddMatrix:Sub8 m24 ', 7, mtx3.m24);
AssertEquals('AddMatrix:Sub9 m31 ', 5, mtx3.m31);
AssertEquals('AddMatrix:Sub10 m32 ', 12, mtx3.m32);
AssertEquals('AddMatrix:Sub11 m33 ', 14, mtx3.m33);
AssertEquals('AddMatrix:Sub12 m34 ', 10, mtx3.m34);
AssertEquals('AddMatrix:Sub13 m41 ', 8, mtx3.m41);
AssertEquals('AddMatrix:Sub14 m42 ', 9, mtx3.m42);
AssertEquals('AddMatrix:Sub15 m43 ', 10, mtx3.m43);
AssertEquals('AddMatrix:Sub16 m44 ', 2, mtx3.m44);
end;
procedure TMatrixFunctionalTest.TestOpAddSingle;
begin
mtx3 := M_LOWER_LEFT_1_9 + 2.0;
AssertEquals('AddSingle:Sub1 m11 ', 3, mtx3.m11);
AssertEquals('AddSingle:Sub2 m12 ', 3, mtx3.m12);
AssertEquals('AddSingle:Sub3 m13 ', 3, mtx3.m13);
AssertEquals('AddSingle:Sub4 m14 ', 3, mtx3.m14);
AssertEquals('AddSingle:Sub5 m21 ', 3, mtx3.m21);
AssertEquals('AddSingle:Sub6 m22 ', 4, mtx3.m22);
AssertEquals('AddSingle:Sub7 m23 ', 5, mtx3.m23);
AssertEquals('AddSingle:Sub8 m24 ', 3, mtx3.m24);
AssertEquals('AddSingle:Sub9 m31 ', 6, mtx3.m31);
AssertEquals('AddSingle:Sub10 m32 ', 7, mtx3.m32);
AssertEquals('AddSingle:Sub11 m33 ', 8, mtx3.m33);
AssertEquals('AddSingle:Sub12 m34 ', 3, mtx3.m34);
AssertEquals('AddSingle:Sub13 m41 ', 9, mtx3.m41);
AssertEquals('AddSingle:Sub14 m42 ', 10, mtx3.m42);
AssertEquals('AddSingle:Sub15 m43 ', 11, mtx3.m43);
AssertEquals('AddSingle:Sub16 m44 ', 3, mtx3.m44);
end;
//(X:1; Y:1; Z:2; W:3),
//(X:1; Y:4; Z:5; W:6),
//(X:1; Y:7; Z:8; W:9),
//(X:1; Y:1; Z:1; W:1)
procedure TMatrixFunctionalTest.TestOpSubMatrix;
begin
mtx3 := M_LOWER_LEFT_1_9 - M_UPPER_RIGHT_1_9;
AssertEquals('SubMatrix:Sub1 m11 ', 0, mtx3.m11);
AssertEquals('SubMatrix:Sub2 m12 ', 0, mtx3.m12);
AssertEquals('SubMatrix:Sub3 m13 ', -1, mtx3.m13);
AssertEquals('SubMatrix:Sub4 m14 ', -2, mtx3.m14);
AssertEquals('SubMatrix:Sub5 m21 ', 0, mtx3.m21);
AssertEquals('SubMatrix:Sub6 m22 ', -2, mtx3.m22);
AssertEquals('SubMatrix:Sub7 m23 ', -2, mtx3.m23);
AssertEquals('SubMatrix:Sub8 m24 ', -5, mtx3.m24);
AssertEquals('SubMatrix:Sub9 m31 ', 3, mtx3.m31);
AssertEquals('SubMatrix:Sub10 m32 ', -2, mtx3.m32);
AssertEquals('SubMatrix:Sub11 m33 ', -2, mtx3.m33);
AssertEquals('SubMatrix:Sub12 m34 ', -8, mtx3.m34);
AssertEquals('SubMatrix:Sub13 m41 ', 6, mtx3.m41);
AssertEquals('SubMatrix:Sub14 m42 ', 7, mtx3.m42);
AssertEquals('SubMatrix:Sub15 m43 ', 8, mtx3.m43);
AssertEquals('SubMatrix:Sub16 m44 ', 0, mtx3.m44);
end;
//(X:1; Y:1; Z:1; W:1),
//(X:1; Y:2; Z:3; W:1),
//(X:4; Y:5; Z:6; W:1),
//(X:7; Y:8; Z:9; W:1)
procedure TMatrixFunctionalTest.TestOpSubSingle;
begin
mtx3 := M_LOWER_LEFT_1_9 - 2;
AssertEquals('SubSingle:Sub1 m11 ', -1, mtx3.m11);
AssertEquals('SubSingle:Sub2 m12 ', -1, mtx3.m12);
AssertEquals('SubSingle:Sub3 m13 ', -1, mtx3.m13);
AssertEquals('SubSingle:Sub4 m14 ', -1, mtx3.m14);
AssertEquals('SubSingle:Sub5 m21 ', -1, mtx3.m21);
AssertEquals('SubSingle:Sub6 m22 ', 0, mtx3.m22);
AssertEquals('SubSingle:Sub7 m23 ', 1, mtx3.m23);
AssertEquals('SubSingle:Sub8 m24 ', -1, mtx3.m24);
AssertEquals('SubSingle:Sub9 m31 ', 2, mtx3.m31);
AssertEquals('SubSingle:Sub10 m32 ', 3, mtx3.m32);
AssertEquals('SubSingle:Sub11 m33 ', 4, mtx3.m33);
AssertEquals('SubSingle:Sub12 m34 ', -1, mtx3.m34);
AssertEquals('SubSingle:Sub13 m41 ', 5, mtx3.m41);
AssertEquals('SubSingle:Sub14 m42 ', 6, mtx3.m42);
AssertEquals('SubSingle:Sub15 m43 ', 7, mtx3.m43);
AssertEquals('SubSingle:Sub16 m44 ', -1, mtx3.m44);
end;
procedure TMatrixFunctionalTest.TestDeterminant;
begin
Fs1:=mKnownDet.Determinant;
AssertEquals('Determinant:Sub1 ', -50, fs1);
mtx1 := OddPosition(0,1); //default
Fs1:=mtx1.Determinant;
AssertEquals('Determinant:Sub1 ', 81, fs1);
mtx1 := OddPosition(1,2); //default
Fs1:=mtx1.Determinant;
AssertEquals('Determinant:Sub1 ', 90, fs1);
mtx1 := OddPosition(2,3); //default
Fs1:=mtx1.Determinant;
AssertEquals('Determinant:Sub1 ', 63, fs1);
mtx1 := OddPosition(4,5); //default
Fs1:=mtx1.Determinant;
AssertEquals('Determinant:Sub1 ', 117, fs1);
end;
procedure TMatrixFunctionalTest.TestTranspose;
begin
// quick and dirty check for transpose, check the transposed determinant
// which should show any out of order elements.
fs1 := mKnownDet.Transpose.Determinant;
AssertTrue('Matrix4f Transposed Determinant does not match expext -50 got '+FLoattostrF(fs1,fffixed,3,3), IsEqual(-50,fs1));
mtx1 := OddTwoByTwo(3, 4); // top right
mtx2 := OddTwoByTwo(7, 4); // bottom left
mtx3 := mtx1.Transpose;
AssertTrue('Invert:Sub1 ', compare(mtx3, mtx2));
mtx3 := mtx2.Transpose;
AssertTrue('Invert:Sub1 ', compare(mtx3, mtx1));
end;
// this function is called by a lot of the pascal routines
// basically it is just the determinant of a 3x3 matrix
// This function is private but we test using the following method
// Mat3 of ((123)(456)(789)) is a really nice matrix in that it has a det of 0
// we can test this inside a 4x4 by putting 1 in the other entries in a 4x4
// and it still has a det of 0. 4x4 det in pascal works by taking a value in the
// top row and multipying it with the 3x3 not in its col.
procedure TMatrixFunctionalTest.TestGetDeterminant;
begin
fs1 := M_LOWER_LEFT_1_9.Determinant;
AssertEquals('GetDeterminant:Sub1 ', 0, fs1);
fs1 := M_UPPER_LEFT_1_9.Determinant;
AssertEquals('GetDeterminant:Sub1 ', 0, fs1);
fs1 := M_LOWER_RIGHT_1_9.Determinant;
AssertEquals('GetDeterminant:Sub2 ', 0, fs1);
fs1 := M_UPPER_RIGHT_1_9.Determinant;
AssertEquals('GetDeterminant:Sub2 ', 0, fs1);
end;
procedure TMatrixFunctionalTest.TestInverse;
begin
// has det of 0 should return IdentityHmgMatrix
mtx1 := M_LOWER_LEFT_1_9;
ResMat := mtx1.Invert;
AssertTrue('Inverse:Sub1 ', compare(ResMat, IdentityHmgMatrix));
mtx1 := OddPosition(0,1); //default
mtx3 := mtx1.Invert;
fs1 := 0.11111111111;
AssertEquals('Inverse:Sub2 m11 ', mtx3.m11, fs1);
AssertEquals('Inverse:Sub3 m22 ', mtx3.m22, fs1);
AssertEquals('Inverse:Sub4 m33 ', mtx3.m33, fs1);
AssertEquals('Inverse:Sub5 m44 ', mtx3.m44, fs1);
fs1 := -0.2222222222;
AssertEquals('Inverse:Sub6 m12 ', mtx3.m12, fs1);
AssertEquals('Inverse:Sub7 m13 ', mtx3.m13, fs1);
AssertEquals('Inverse:Sub8 m21 ', mtx3.m21, fs1);
AssertEquals('Inverse:Sub9 m24 ', mtx3.m24, fs1);
AssertEquals('Inverse:Sub10 m31 ', mtx3.m31, fs1);
AssertEquals('Inverse:Sub11 m34 ', mtx3.m34, fs1);
AssertEquals('Inverse:Sub12 m42 ', mtx3.m42, fs1);
AssertEquals('Inverse:Sub13 m43 ', mtx3.m43, fs1);
fs1 := 0.44444444444;
AssertEquals('Inverse:Sub14 m14 ', mtx3.m14, fs1);
AssertEquals('Inverse:Sub15 m23 ', mtx3.m23, fs1);
AssertEquals('Inverse:Sub16 m32 ', mtx3.m32, fs1);
AssertEquals('Inverse:Sub17 m41 ', mtx3.m41, fs1);
mtx2 := mtx3.Invert;
AssertTrue('Inverse:Sub18 double inverse failed ', compare(mtx2, mtx1, 1e-5));
mtx1 := OddPosition(3,7);
mtx3 := mtx1.Invert;
mtx4 := mtx1 * mtx3; // inverse * matrix = Identity
AssertTrue('Inverse:Sub19 Inverse * Matrix failed ', compare(IdentityHmgMatrix, mtx4, 1e-5));
mtx2 := mtx3.Invert;
AssertTrue('Inverse:Sub20 double inverse failed ', compare(mtx2, mtx1, 1e-4));
mtx1 := OddTwoByTwo(3,7);
mtx3 := mtx1.Invert;
mtx4 := mtx1 * mtx3; // inverse * matrix = Identity
AssertTrue('Inverse:Sub21 Inverse * Matrix failed ', compare(IdentityHmgMatrix, mtx4, 1e-5));
mtx2 := mtx3.Invert;
AssertTrue('Inverse:Sub22 double inverse failed ', compare(mtx2, mtx1, 1e-5));
end;
procedure TMatrixFunctionalTest.TestOpMultMatrix;
begin
mtx1 := M_LOWER_LEFT_1_9;
mtx3 := mtx1 * mtx1;
AssertEquals('OpMultMatrix:Sub1 m11 ', 13, mtx3.m11);
AssertEquals('OpMultMatrix:Sub2 m12 ', 16, mtx3.m12);
AssertEquals('OpMultMatrix:Sub3 m13 ', 19, mtx3.m13);
AssertEquals('OpMultMatrix:Sub4 m14 ', 4, mtx3.m14);
AssertEquals('OpMultMatrix:Sub5 m21 ', 22, mtx3.m21);
AssertEquals('OpMultMatrix:Sub6 m22 ', 28, mtx3.m22);
AssertEquals('OpMultMatrix:Sub7 m23 ', 34, mtx3.m23);
AssertEquals('OpMultMatrix:Sub8 m24 ', 7, mtx3.m24);
AssertEquals('OpMultMatrix:Sub9 m31 ', 40, mtx3.m31);
AssertEquals('OpMultMatrix:Sub10 m32 ', 52, mtx3.m32);
AssertEquals('OpMultMatrix:Sub11 m33 ', 64, mtx3.m33);
AssertEquals('OpMultMatrix:Sub12 m34 ', 16, mtx3.m34);
AssertEquals('OpMultMatrix:Sub13 m41 ', 58, mtx3.m41);
AssertEquals('OpMultMatrix:Sub14 m42 ', 76, mtx3.m42);
AssertEquals('OpMultMatrix:Sub15 m43 ', 94, mtx3.m43);
AssertEquals('OpMultMatrix:Sub16 m44 ', 25, mtx3.m44);
end;
procedure TMatrixFunctionalTest.TestOpMulVector;
begin
mtx1 := M_LOWER_LEFT_1_9;
vt1.Create(1,3,1,2);
vt3 := mtx1 * vt1;
AssertEquals('OpMulVector:Sub1 X ', 7, vt3.X);
AssertEquals('OpMulVector:Sub2 Y ', 12, vt3.Y);
AssertEquals('OpMulVector:Sub3 Z ', 27, vt3.Z);
AssertEquals('OpMulVector:Sub4 W ', 42, vt3.W);
end;
procedure TMatrixFunctionalTest.TestOpVectorMulMat;
begin
mtx1 := M_LOWER_LEFT_1_9;
vt1.Create(1,3,1,2);
vt3 := vt1 * mtx1;
AssertEquals('OpMulVector:Sub1 X ', 22, vt3.X);
AssertEquals('OpMulVector:Sub2 Y ', 28, vt3.Y);
AssertEquals('OpMulVector:Sub3 Z ', 34, vt3.Z);
AssertEquals('OpMulVector:Sub4 W ', 7, vt3.W);
end;
procedure TMatrixFunctionalTest.TestTransposeVectorMulMat;
begin
mtx1 := M_LOWER_LEFT_1_9;
mtx1 := mtx1.Transpose;
vt1.Create(1,3,1,2);
vt3 := vt1 * mtx1;
AssertEquals('OpMulVector:Sub1 X ', 7, vt3.X);
AssertEquals('OpMulVector:Sub2 Y ', 12, vt3.Y);
AssertEquals('OpMulVector:Sub3 Z ', 27, vt3.Z);
AssertEquals('OpMulVector:Sub4 W ', 42, vt3.W);
end;
//(X:1; Y:1; Z:1; W:1),
//(X:1; Y:2; Z:3; W:1),
//(X:4; Y:5; Z:6; W:1),
//(X:7; Y:8; Z:9; W:1)
procedure TMatrixFunctionalTest.TestOpDivSingle;
begin
mtx1 := M_LOWER_LEFT_1_9;
mtx3 := mtx1 / 2;
AssertEquals('OpDivSingle:Sub1 m11 ', 0.5, mtx3.m11);
AssertEquals('OpDivSingle:Sub2 m12 ', 0.5, mtx3.m12);
AssertEquals('OpDivSingle:Sub3 m13 ', 0.5, mtx3.m13);
AssertEquals('OpDivSingle:Sub4 m14 ', 0.5, mtx3.m14);
AssertEquals('OpDivSingle:Sub5 m21 ', 0.5, mtx3.m21);
AssertEquals('OpDivSingle:Sub6 m22 ', 1.0, mtx3.m22);
AssertEquals('OpDivSingle:Sub7 m23 ', 1.5, mtx3.m23);
AssertEquals('OpDivSingle:Sub8 m24 ', 0.5, mtx3.m24);
AssertEquals('OpDivSingle:Sub9 m31 ', 2.0, mtx3.m31);
AssertEquals('OpDivSingle:Sub10 m32 ', 2.5, mtx3.m32);
AssertEquals('OpDivSingle:Sub11 m33 ', 3.0, mtx3.m33);
AssertEquals('OpDivSingle:Sub12 m34 ', 0.5, mtx3.m34);
AssertEquals('OpDivSingle:Sub13 m41 ', 3.5, mtx3.m41);
AssertEquals('OpDivSingle:Sub14 m42 ', 4.0, mtx3.m42);
AssertEquals('OpDivSingle:Sub15 m43 ', 4.5, mtx3.m43);
AssertEquals('OpDivSingle:Sub16 m44 ', 0.5, mtx3.m44);
end;
procedure TMatrixFunctionalTest.TestOpNegate;
begin
mtx1 := M_LOWER_LEFT_1_9;
mtx3 := -mtx1;
AssertEquals('OpDivSingle:Sub1 m11 ', -1, mtx3.m11);
AssertEquals('OpDivSingle:Sub2 m12 ', -1, mtx3.m12);
AssertEquals('OpDivSingle:Sub3 m13 ', -1, mtx3.m13);
AssertEquals('OpDivSingle:Sub4 m14 ', -1, mtx3.m14);
AssertEquals('OpDivSingle:Sub5 m21 ', -1, mtx3.m21);
AssertEquals('OpDivSingle:Sub6 m22 ', -2, mtx3.m22);
AssertEquals('OpDivSingle:Sub7 m23 ', -3, mtx3.m23);
AssertEquals('OpDivSingle:Sub8 m24 ', -1, mtx3.m24);
AssertEquals('OpDivSingle:Sub9 m31 ', -4, mtx3.m31);
AssertEquals('OpDivSingle:Sub10 m32 ', -5, mtx3.m32);
AssertEquals('OpDivSingle:Sub11 m33 ', -6, mtx3.m33);
AssertEquals('OpDivSingle:Sub12 m34 ', -1, mtx3.m34);
AssertEquals('OpDivSingle:Sub13 m41 ', -7, mtx3.m41);
AssertEquals('OpDivSingle:Sub14 m42 ', -8, mtx3.m42);
AssertEquals('OpDivSingle:Sub15 m43 ', -9, mtx3.m43);
AssertEquals('OpDivSingle:Sub16 m44 ', -1, mtx3.m44);
end;
procedure TMatrixFunctionalTest.TestCreateIdentity;
begin
mtx3.CreateIdentityMatrix;
AssertTrue('CreateIdentity:Sub1 failed ', compare(IdentityHmgMatrix, mtx3));
end;
procedure TMatrixFunctionalTest.TestCreateScaleVector;
begin
vt1.Create(2,2,2,1); // should a scale vector set the W?
mtx1.CreateScaleMatrix(vt1);
vt3 := mtx1 * vt1; // use the scale vector to scale itself
AssertEquals('ScaleVector:Sub1 X ', 4, vt3.X);
AssertEquals('ScaleVector:Sub2 Y ', 4, vt3.Y);
AssertEquals('ScaleVector:Sub3 Z ', 4, vt3.Z);
AssertEquals('ScaleVector:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(2,2,2,0); // should a scale vector set the W?
mtx1.CreateScaleMatrix(vt1);
vt3 := mtx1 * vt1; // use the scale vector to scale itself
AssertEquals('ScaleVector:Sub5 X ', 4, vt3.X);
AssertEquals('ScaleVector:Sub6 Y ', 4, vt3.Y);
AssertEquals('ScaleVector:Sub7 Z ', 4, vt3.Z);
AssertEquals('ScaleVector:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vector back
end;
procedure TMatrixFunctionalTest.TestCreateScaleAffine;
begin
vt1.Create(2,2,2,1); // should a scale vector set the W?
mtx1.CreateScaleMatrix(vt1.AsVector3f);
vt3 := mtx1 * vt1; // use the scale vector to scale itself
AssertEquals('ScaleAffine:Sub1 X ', 4, vt3.X);
AssertEquals('ScaleAffine:Sub2 Y ', 4, vt3.Y);
AssertEquals('ScaleAffine:Sub3 Z ', 4, vt3.Z);
AssertEquals('ScaleAffine:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(2,2,2,0); // should a scale vector set the W?
mtx1.CreateScaleMatrix(vt1.AsVector3f);
vt3 := mtx1 * vt1; // use the scale vector to scale itself
AssertEquals('ScaleAffine:Sub5 X ', 4, vt3.X);
AssertEquals('ScaleAffine:Sub6 Y ', 4, vt3.Y);
AssertEquals('ScaleAffine:Sub7 Z ', 4, vt3.Z);
AssertEquals('ScaleAffine:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vector back
end;
procedure TMatrixFunctionalTest.TestCreateTransVector;
begin
vt1.Create(3,4,5,1); // should a scale vector set the W?
mtx1.CreateTranslationMatrix(vt1);
vt3 := mtx1 * vt1; // use the transform on vector to transform itself
AssertEquals('TransVector:Sub1 X ', 6, vt3.X);
AssertEquals('TransVector:Sub2 Y ', 8, vt3.Y);
AssertEquals('TransVector:Sub3 Z ', 10, vt3.Z);
AssertEquals('TransVector:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(5,4,3,0); // should a scale vector set the W?
mtx1.CreateTranslationMatrix(vt1);
vt3 := mtx1 * vt1; // use the transform on a vector to transform itself
// vt1 was a vec should get vector back but vectors should not transform
AssertEquals('TransVector:Sub5 X ', 5, vt3.X);
AssertEquals('TransVector:Sub6 Y ', 4, vt3.Y);
AssertEquals('TransVector:Sub7 Z ', 3, vt3.Z);
AssertEquals('TransVector:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vector back
end;
procedure TMatrixFunctionalTest.TestCreateTransAffine;
begin
vt1.Create(3,4,5,1); // should a scale vector set the W?
mtx1.CreateTranslationMatrix(vt1.AsVector3f);
vt3 := mtx1 * vt1; // use the transform on vector to transform itself
AssertEquals('TransAffine:Sub1 X ', 6, vt3.X);
AssertEquals('TransAffine:Sub2 Y ', 8, vt3.Y);
AssertEquals('TransVector:Sub3 Z ', 10, vt3.Z);
AssertEquals('TransAffine:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(5,4,3,0); // should a scale vector set the W?
mtx1.CreateTranslationMatrix(vt1.AsVector3f);
vt3 := mtx1 * vt1; // use the transform on a vector to transform itself
// vt1 was a vec should get vector back but vectors should not transform
AssertEquals('TransAffine:Sub5 X ', 5, vt3.X);
AssertEquals('TransAffine:Sub6 Y ', 4, vt3.Y);
AssertEquals('TransAffine:Sub7 Z ', 3, vt3.Z);
AssertEquals('TransAffine:Sub8 W ', 0, vt3.W);
end;
procedure TMatrixFunctionalTest.TestCreateScaleTransVector;
begin
vt1.Create(2,2,2,1); // should a scale vector set the W?
vt2.Create(10,10,10,1);
mtx1.CreateScaleAndTranslationMatrix(vt1,vt2);
vt3 := mtx1 * vt1; // use the scale vector to scale itself
AssertEquals('ScaleTransVector:Sub1 X ', 14, vt3.X);
AssertEquals('ScaleTransVector:Sub2 Y ', 14, vt3.Y);
AssertEquals('ScaleTransVector:Sub3 Z ', 14, vt3.Z);
AssertEquals('ScaleTransVector:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(2,2,2,0); // should a scale vector set the W?
mtx1.CreateScaleAndTranslationMatrix(vt1,vt2);
vt3 := mtx1 * vt1; // use the scale vector to scale itself mo transform as it is a vector
AssertEquals('ScaleTransVector:Sub5 X ', 4, vt3.X);
AssertEquals('ScaleTransVector:Sub6 Y ', 4, vt3.Y);
AssertEquals('ScaleTransVector:Sub7 Z ', 4, vt3.Z);
AssertEquals('ScaleTransVector:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vector back
end;
// rotations around X axis RightHandRule
// looking down positive X towards origin y is right and z is up
// from this view a positive rotation imparts a CCV rotation of Z and Y
// pos zy quadrant is upper right.
procedure TMatrixFunctionalTest.TestCreateRotationMatrixXAngle;
begin
aqt1.Create(90,XVector);
mtx2 := aqt1.ConvertToMatrix;
mtx1.CreateRotationMatrixX(pi/2);
AssertTrue('RotationMatrixXAngle:Sub0 Quat v Mat do not match ', compare(mtx1,mtx2, 1e-6));
vt1.Create(0,1,1,1); // point in the pos quad
vt3 := mtx1 * vt1; // z remains pos y goes neg
AssertEquals('RotationMatrixXAngle:Sub1 X ', 0, vt3.X);
AssertEquals('RotationMatrixXAngle:Sub2 Y ', -1, vt3.Y);
AssertEquals('RotationMatrixXAngle:Sub3 Z ', 1, vt3.Z);
AssertEquals('RotationMatrixXAngle:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(0,1,1,0); // point in the pos quad
vt3 := mtx1 * vt1; // z remains pos y goes neg
AssertEquals('RotationMatrixXAngle:Sub5 X ', 0, vt3.X);
AssertEquals('RotationMatrixXAngle:Sub6 Y ', -1, vt3.Y);
AssertEquals('RotationMatrixXAngle:Sub7 Z ', 1, vt3.Z);
AssertEquals('RotationMatrixXAngle:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vec back
mtx1.CreateRotationMatrixX(-pi/2);
vt1.Create(0,1,1,1); // point in the pos quad
vt3 := mtx1 * vt1; // y remains pos z goes neg
AssertEquals('RotationMatrixXAngle:Sub9 X ', 0, vt3.X);
AssertEquals('RotationMatrixXAngle:Sub10 Y ', 1, vt3.Y);
AssertEquals('RotationMatrixXAngle:Sub11 Z ', -1, vt3.Z);
AssertEquals('RotationMatrixXAngle:Sub12 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(0,1,1,0); // point in the pos quad
vt3 := mtx1 * vt1; // y remains pos z goes neg
AssertEquals('RotationMatrixXAngle:Sub13 X ', 0, vt3.X);
AssertEquals('RotationMatrixXAngle:Sub14 Y ', 1, vt3.Y);
AssertEquals('RotationMatrixXAngle:Sub15 Z ', -1, vt3.Z);
AssertEquals('RotationMatrixXAngle:Sub16 W ', 0, vt3.W); // vt1 was a vec should get vec back
end;
procedure TMatrixFunctionalTest.TestCreateRotationMatrixXSinCos;
begin
mtx1.CreateRotationMatrixX(1,0);
vt1.Create(0,1,1,1); // point in the pos quad
vt3 := mtx1 * vt1; // z remains pos y goes neg
AssertEquals('RotationMatrixXSinCos:Sub1 X ', 0, vt3.X);
AssertEquals('RotationMatrixXSinCos:Sub2 Y ', -1, vt3.Y);
AssertEquals('RotationMatrixXSinCos:Sub3 Z ', 1, vt3.Z);
AssertEquals('RotationMatrixXSinCos:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(0,1,1,0); // point in the pos quad
vt3 := mtx1 * vt1; // z remains pos y goes neg
AssertEquals('RotationMatrixXSinCos:Sub5 X ', 0, vt3.X);
AssertEquals('RotationMatrixXSinCos:Sub6 Y ', -1, vt3.Y);
AssertEquals('RotationMatrixXSinCos:Sub7 Z ', 1, vt3.Z);
AssertEquals('RotationMatrixXSinCos:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vec back
mtx1.CreateRotationMatrixX(-1,0);
vt1.Create(0,1,1,1); // point in the pos quad
vt3 := mtx1 * vt1; // y remains pos z goes neg
AssertEquals('RotationMatrixXSinCos:Sub9 X ', 0, vt3.X);
AssertEquals('RotationMatrixXSinCos:Sub10 Y ', 1, vt3.Y);
AssertEquals('RotationMatrixXSinCos:Sub11 Z ', -1, vt3.Z);
AssertEquals('RotationMatrixXSinCos:Sub12 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(0,1,1,0); // point in the pos quad
vt3 := mtx1 * vt1; // y remains pos z goes neg
AssertEquals('RotationMatrixXSinCos:Sub13 X ', 0, vt3.X);
AssertEquals('RotationMatrixXSinCos:Sub14 Y ', 1, vt3.Y);
AssertEquals('RotationMatrixXSinCos:Sub15 Z ', -1, vt3.Z);
AssertEquals('RotationMatrixXSinCos:Sub16 W ', 0, vt3.W); // vt1 was a vec should get vec back
end;
// rotations around Y axis RightHandRule
// looking down positive Y towards origin Z is right and X is up
// from this view a positive rotation imparts a CCV rotation of Z and Y
// pos zx quadrant is upper right.
procedure TMatrixFunctionalTest.TestCreateRotationMatrixYAngle;
begin
mtx1.CreateRotationMatrixY(pi/2);
aqt1.Create(90,YVector);
mtx2 := aqt1.ConvertToMatrix;
AssertTrue('RotationMatrixYAngle:Sub0 Quat v Mat do not match ', compare(mtx1,mtx2, 1e-6));
vt1.Create(1,0,1,1); // point in the pos quad
vt3 := mtx1 * vt1; // x remains pos z goes neg
AssertEquals('RotationMatrixYAngle:Sub1 X ', 1, vt3.X);
AssertEquals('RotationMatrixYAngle:Sub2 Y ', 0, vt3.Y);
AssertEquals('RotationMatrixYAngle:Sub3 Z ', -1, vt3.Z);
AssertEquals('RotationMatrixYAngle:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(1,0,1,0); // point in the pos quad
vt3 := mtx1 * vt1; // x remains pos z goes neg
AssertEquals('RotationMatrixYAngle:Sub5 X ', 1, vt3.X);
AssertEquals('RotationMatrixYAngle:Sub6 Y ', 0, vt3.Y);
AssertEquals('RotationMatrixYAngle:Sub7 Z ', -1, vt3.Z);
AssertEquals('RotationMatrixYAngle:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vec back
mtx1.CreateRotationMatrixY(-pi/2);
vt1.Create(1,0,1,1); // point in the pos quad
vt3 := mtx1 * vt1; // z remains pos x goes neg
AssertEquals('RotationMatrixYAngle:Sub9 X ', -1, vt3.X);
AssertEquals('RotationMatrixYAngle:Sub10 Y ', 0, vt3.Y);
AssertEquals('RotationMatrixYAngle:Sub11 Z ', 1, vt3.Z);
AssertEquals('RotationMatrixYAngle:Sub12 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(1,0,1,0); // point in the pos quad
vt3 := mtx1 * vt1; // z remains pos x goes neg
AssertEquals('RotationMatrixYAngle:Sub13 X ', -1, vt3.X);
AssertEquals('RotationMatrixYAngle:Sub14 Y ', 0, vt3.Y);
AssertEquals('RotationMatrixYAngle:Sub15 Z ', 1, vt3.Z);
AssertEquals('RotationMatrixYAngle:Sub16 W ', 0, vt3.W); // vt1 was a vec should get vec back
end;
procedure TMatrixFunctionalTest.TestCreateRotationMatrixYSinCos;
begin
mtx1.CreateRotationMatrixY(1,0);
vt1.Create(1,0,1,1); // point in the pos quad
vt3 := mtx1 * vt1; // x remains pos z goes neg
AssertEquals('RotationMatrixYSinCos:Sub1 X ', 1, vt3.X);
AssertEquals('RotationMatrixYSinCos:Sub2 Y ', 0, vt3.Y);
AssertEquals('RotationMatrixYSinCos:Sub3 Z ', -1, vt3.Z);
AssertEquals('RotationMatrixYSinCos:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(1,0,1,0); // point in the pos quad
vt3 := mtx1 * vt1; // x remains pos z goes neg
AssertEquals('RotationMatrixYSinCos:Sub5 X ', 1, vt3.X);
AssertEquals('RotationMatrixYSinCos:Sub6 Y ', 0, vt3.Y);
AssertEquals('RotationMatrixYSinCos:Sub7 Z ', -1, vt3.Z);
AssertEquals('RotationMatrixYSinCos:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vec back
mtx1.CreateRotationMatrixY(-1,0);
vt1.Create(1,0,1,1); // point in the pos quad
vt3 := mtx1 * vt1; // z remains pos x goes neg
AssertEquals('RotationMatrixYSinCos:Sub9 X ', -1, vt3.X);
AssertEquals('RotationMatrixYSinCos:Sub10 Y ', 0, vt3.Y);
AssertEquals('RotationMatrixYSinCos:Sub11 Z ', 1, vt3.Z);
AssertEquals('RotationMatrixYSinCos:Sub12 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(1,0,1,0); // point in the pos quad
vt3 := mtx1 * vt1; // z remains pos x goes neg
AssertEquals('RotationMatrixYSinCos:Sub13 X ', -1, vt3.X);
AssertEquals('RotationMatrixYSinCos:Sub14 Y ', 0, vt3.Y);
AssertEquals('RotationMatrixYSinCos:Sub15 Z ', 1, vt3.Z);
AssertEquals('RotationMatrixYSinCos:Sub16 W ', 0, vt3.W); // vt1 was a vec should get vec back
end;
// rotations around Z axis RightHandRule
// looking down positive Z towards origin X is right and Y is up
// from this view a positive rotation imparts a CCV rotation of x and Y
// pos xy quadrant is upper right.
procedure TMatrixFunctionalTest.TestCreateRotationMatrixZAngle;
begin
aqt1.Create(90,ZVector);
mtx2 := aqt1.ConvertToMatrix;
mtx1.CreateRotationMatrixZ(pi/2);
AssertTrue('RotationMatrixZAngle:Sub0 Quat v Mat do not match ', compare(mtx1,mtx2, 1e-6));
vt1.Create(1,1,0,1); // point in the pos quad
vt3 := mtx1 * vt1; // y remains pos x goes neg
AssertEquals('RotationMatrixZAngle:Sub1 X ', -1, vt3.X);
AssertEquals('RotationMatrixZAngle:Sub2 Y ', 1, vt3.Y);
AssertEquals('RotationMatrixZAngle:Sub3 Z ', 0, vt3.Z);
AssertEquals('RotationMatrixZAngle:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(1,1,0,0); // point in the pos quad
vt3 := mtx1 * vt1; // y remains pos x goes neg
AssertEquals('RotationMatrixZAngle:Sub5 X ', -1, vt3.X);
AssertEquals('RotationMatrixZAngle:Sub6 Y ', 1, vt3.Y);
AssertEquals('RotationMatrixZAngle:Sub7 Z ', 0, vt3.Z);
AssertEquals('RotationMatrixZAngle:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vec back
mtx1.CreateRotationMatrixZ(-pi/2);
vt1.Create(1,1,0,1); // point in the pos quad
vt3 := mtx1 * vt1; // x remains pos y goes neg
AssertEquals('RotationMatrixZAngle:Sub9 X ', 1, vt3.X);
AssertEquals('RotationMatrixZAngle:Sub10 Y ', -1, vt3.Y);
AssertEquals('RotationMatrixZAngle:Sub11 Z ', 0, vt3.Z);
AssertEquals('RotationMatrixZAngle:Sub12 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(1,1,0,0); // point in the pos quad
vt3 := mtx1 * vt1; // x remains pos y goes neg
AssertEquals('RotationMatrixZAngle:Sub13 X ', 1, vt3.X);
AssertEquals('RotationMatrixZAngle:Sub14 Y ', -1, vt3.Y);
AssertEquals('RotationMatrixZAngle:Sub15 Z ', 0, vt3.Z);
AssertEquals('RotationMatrixZAngle:Sub16 W ', 0, vt3.W); // vt1 was a vec should get vec back
end;
procedure TMatrixFunctionalTest.TestCreateRotationMatrixZSinCos;
begin
mtx1.CreateRotationMatrixZ(1,0);
vt1.Create(1,1,0,1); // point in the pos quad
vt3 := mtx1 * vt1; // y remains pos x goes neg
AssertEquals('RotationMatrixZAngle:Sub1 X ', -1, vt3.X);
AssertEquals('RotationMatrixZAngle:Sub2 Y ', 1, vt3.Y);
AssertEquals('RotationMatrixZAngle:Sub3 Z ', 0, vt3.Z);
AssertEquals('RotationMatrixZAngle:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(1,1,0,0); // point in the pos quad
vt3 := mtx1 * vt1; // y remains pos x goes neg
AssertEquals('RotationMatrixZAngle:Sub5 X ', -1, vt3.X);
AssertEquals('RotationMatrixZAngle:Sub6 Y ', 1, vt3.Y);
AssertEquals('RotationMatrixZAngle:Sub7 Z ', 0, vt3.Z);
AssertEquals('RotationMatrixZAngle:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vec back
mtx1.CreateRotationMatrixZ(-1,0);
vt1.Create(1,1,0,1); // point in the pos quad
vt3 := mtx1 * vt1; // x remains pos y goes neg
AssertEquals('RotationMatrixZAngle:Sub9 X ', 1, vt3.X);
AssertEquals('RotationMatrixZAngle:Sub10 Y ', -1, vt3.Y);
AssertEquals('RotationMatrixZAngle:Sub11 Z ', 0, vt3.Z);
AssertEquals('RotationMatrixZAngle:Sub12 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(1,1,0,0); // point in the pos quad
vt3 := mtx1 * vt1; // x remains pos y goes neg
AssertEquals('RotationMatrixZAngle:Sub13 X ', 1, vt3.X);
AssertEquals('RotationMatrixZAngle:Sub14 Y ', -1, vt3.Y);
AssertEquals('RotationMatrixZAngle:Sub15 Z ', 0, vt3.Z);
AssertEquals('RotationMatrixZAngle:Sub16 W ', 0, vt3.W); // vt1 was a vec should get vec back
end;
// Angle in radians
procedure TMatrixFunctionalTest.TestCreateRotationMatrixAxisAngle;
begin
mtx1.CreateRotationMatrix(ZVector,pi/2);
mtx2.CreateRotationMatrix(ZHmgVector,pi/2);
AssertTrue('RotationMatrixAxisAngle:Sub0 Affinve v Hmg do not match ', compare(mtx1,mtx2));
vt1.Create(1,1,0,1); // point in the pos quad
vt3 := mtx1 * vt1; // y remains pos x goes neg
AssertEquals('RotationMatrixAxisAngle:Sub1 X ', -1, vt3.X);
AssertEquals('RotationMatrixAxisAngle:Sub2 Y ', 1, vt3.Y);
AssertEquals('RotationMatrixAxisAngle:Sub3 Z ', 0, vt3.Z);
AssertEquals('RotationMatrixAxisAngle:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(1,1,0,0); // point in the pos quad
vt3 := mtx1 * vt1; // y remains pos x goes neg
AssertEquals('RotationMatrixAxisAngle:Sub5 X ', -1, vt3.X);
AssertEquals('RotationMatrixAxisAngle:Sub6 Y ', 1, vt3.Y);
AssertEquals('RotationMatrixAxisAngle:Sub7 Z ', 0, vt3.Z);
AssertEquals('RotationMatrixAxisAngle:Sub8 W ', 0, vt3.W); // vt1 was a vec should get vec back
mtx1.CreateRotationMatrix(YVector,pi/2);
mtx2.CreateRotationMatrix(YHmgVector,pi/2);
AssertTrue('RotationMatrixAxisAngle:Sub9 Affinve v Hmg do not match ', compare(mtx1,mtx2));
vt1.Create(1,0,1,1); // point in the pos quad
vt3 := mtx1 * vt1; // x remains pos z goes neg
AssertEquals('RotationMatrixAxisAngle:Sub10 X ', 1, vt3.X);
AssertEquals('RotationMatrixAxisAngle:Sub11 Y ', 0, vt3.Y);
AssertEquals('RotationMatrixAxisAngle:Sub12 Z ', -1, vt3.Z);
AssertEquals('RotationMatrixAxisAngle:Sub13 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(1,0,1,0); // point in the pos quad
vt3 := mtx1 * vt1; // x remains pos z goes neg
AssertEquals('RotationMatrixAxisAngle:Sub14 X ', 1, vt3.X);
AssertEquals('RotationMatrixAxisAngle:Sub15 Y ', 0, vt3.Y);
AssertEquals('RotationMatrixAxisAngle:Sub16 Z ', -1, vt3.Z);
AssertEquals('RotationMatrixAxisAngle:Sub17 W ', 0, vt3.W); // vt1 was a vec should get vec back
mtx1.CreateRotationMatrix(XVector,pi/2);
mtx2.CreateRotationMatrix(XHmgVector,pi/2);
AssertTrue('RotationMatrixAxisAngle:Sub18 Affinve v Hmg do not match ', compare(mtx1,mtx2));
vt1.Create(0,1,1,1); // point in the pos quad
vt3 := mtx1 * vt1; // z remains pos y goes neg
AssertEquals('RotationMatrixAxisAngle:Sub19 X ', 0, vt3.X);
AssertEquals('RotationMatrixAxisAngle:Sub20 Y ', -1, vt3.Y);
AssertEquals('RotationMatrixAxisAngle:Sub21 Z ', 1, vt3.Z);
AssertEquals('RotationMatrixAxisAngle:Sub21 W ', 1, vt3.W); // vt1 was a point should get point back
vt1.Create(0,1,1,0); // point in the pos quad
vt3 := mtx1 * vt1; // z remains pos y goes neg
AssertEquals('RotationMatrixAxisAngle:Sub23 X ', 0, vt3.X);
AssertEquals('RotationMatrixAxisAngle:Sub24 Y ', -1, vt3.Y);
AssertEquals('RotationMatrixAxisAngle:Sub25 Z ', 1, vt3.Z);
AssertEquals('RotationMatrixAxisAngle:Sub26 W ', 0, vt3.W); // vt1 was a vec should get vec back
end;
// origin for Look at matrix seems to be eye
// eye is looking along the -Z axis of the new coordinate system
// center will be -(eye to center)length in -Z
// ergo should only need to set m34 value others should be 0 ???
// The center of the screen will eventually lie somewhere on the -z axis of
// this matrix view.
// This is an orthogonal representation of the world with an altered origin.
// In projection terms an orthographic projection.
// This is a parallel projection matrix on xy plane if z component is removed.
procedure TMatrixFunctionalTest.TestCreateLookAtMatrix;
begin
vt1.Create(0,0,10,1); // eye is a point; origin will be center up will be y
mtx1.CreateLookAtMatrix(vt1,NullHmgPoint,YHmgVector); // create look at matrix
vt2.Create(1,1,0,1); //create usual point on z = 0 plane.
vt3 := mtx1 * vt2; // vt2 should be unaffected by this transform
AssertEquals('CreateLookAtMatrix:Sub1 X ', 1, vt3.X);
AssertEquals('CreateLookAtMatrix:Sub2 Y ', 1, vt3.Y);
AssertEquals('CreateLookAtMatrix:Sub3 Z ', -10, vt3.Z);
AssertEquals('CreateLookAtMatrix:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
mtx1.CreateLookAtMatrix(vt1,NullHmgPoint,XHmgVector); // create look at matrix
vt2.Create(1,1,0,1); //create usual point on zplane.
vt3 := mtx1 * vt2; // vt2 should appear in +y-x quadrant
AssertEquals('CreateLookAtMatrix:Sub1 X ', -1, vt3.X);
AssertEquals('CreateLookAtMatrix:Sub2 Y ', 1, vt3.Y);
AssertEquals('CreateLookAtMatrix:Sub3 Z ', -10, vt3.Z);
AssertEquals('CreateLookAtMatrix:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
// try to test this assumption
vt1.Create(2,2,10,1); // eye is a point; up will be y
vt2.Create(2,2,0,1); // eye -> center is a ray parallel -Z axis vector
mtx1.CreateLookAtMatrix(vt1,vt2,YHmgVector); // create look at matrix
vt2.Create(1,1,0,1); //create usual point on z = 0 plane.
vt3 := mtx1 * vt2; // vt2 should be appear in the -x-y quadrant
AssertEquals('CreateLookAtMatrix:Sub1 X ', -1, vt3.X);
AssertEquals('CreateLookAtMatrix:Sub2 Y ', -1, vt3.Y);
AssertEquals('CreateLookAtMatrix:Sub3 Z ', -10, vt3.Z);
AssertEquals('CreateLookAtMatrix:Sub4 W ', 1, vt3.W); // vt1 was a point should get point back
end;
// given the above look at parallel projection, they should have exactly the same
// behaviour but from different?? starting parameters.
procedure TMatrixFunctionalTest.TestCreateParallelProjectionMatrix;
begin
//// first try to hit the IdentityHmgMatrix return
vt1.Create(1,1,0,1);
apl1.Create(vt1, ZHmgVector); // create a xy plane at 0
// first a vector on the plane
mtx1.CreateParallelProjectionMatrix(apl1, XHmgVector);
AssertTrue('CreateParallelProjectionMatrix:Sub1 not IdentityHmgMatrix ', compare(IdentityHmgMatrix,mtx1));
// next a vector created from two points parallel to the plane
vt1.Create(2.344, 23.4423, 3, 1);
vt2.Create(22.344, -23.4423, 3, 1);
vt3 := vt1-vt2; // subtraction of two points results in a vector.
mtx1.CreateParallelProjectionMatrix(apl1, vt3);
AssertTrue('CreateParallelProjectionMatrix:Sub2 not IdentityHmgMatrix ', compare(IdentityHmgMatrix,mtx1));
// now for the special case that v is perp to plane orthographic projection
// should behave as the lookat matrix above
vt1.Create(apl1.AsNormal3); // this will be half normal not unit see if that affects things
mtx1.CreateParallelProjectionMatrix(apl1, vt1);
vt2.Create(1,1,0,1); //create usual point on z = 0 plane.
vt3 := mtx1 * vt2; // vt2 should be unaffected by this transform
AssertEquals('CreateParallelProjectionMatrix:Sub3 X ', 1, vt3.X);
AssertEquals('CreateParallelProjectionMatrix:Sub4 Y ', 1, vt3.Y);
AssertEquals('CreateParallelProjectionMatrix:Sub5 Z ', 0, vt3.Z);
AssertEquals('CreateParallelProjectionMatrix:Sub6 W ', 1, vt3.W); // vt1 was a point should get point back
vt2.Create(1,1,23,1); //create usual point above the plane.
vt3 := mtx1 * vt2; // vt2 should be unaffected by this transform
AssertEquals('CreateParallelProjectionMatrix:Sub7 X ', 1, vt3.X);
AssertEquals('CreateParallelProjectionMatrix:Sub8 Y ', 1, vt3.Y);
AssertEquals('CreateParallelProjectionMatrix:Sub9 Z ', 0, vt3.Z);
AssertEquals('CreateParallelProjectionMatrix:Sub10 W ', 1, vt3.W); // vt1 was a point should get point back
vt2.Create(1,1,-23,1); //create usual point below the plane.
vt3 := mtx1 * vt2; // vt2 should be unaffected by this transform
AssertEquals('CreateParallelProjectionMatrix:Sub11 X ', 1, vt3.X);
AssertEquals('CreateParallelProjectionMatrix:Sub12 Y ', 1, vt3.Y);
AssertEquals('CreateParallelProjectionMatrix:Sub13 Z ', 0, vt3.Z);
AssertEquals('CreateParallelProjectionMatrix:Sub14 W ', 1, vt3.W); // vt1 was a point should get point back
// now create a vector which is 45deg to the plane along the X axis
// oblique projection
vt1.create(1,0,1,0);
vt1 := vt1.Normalize; // does the vector have to be normalised?
mtx1.CreateParallelProjectionMatrix(apl1, -vt1);
vt2.Create(1,1,0,1); //create usual point on z = 0 plane.
vt3 := mtx1 * vt2; // vt2 should be unaffected by this transform
AssertEquals('CreateParallelProjectionMatrix:Sub15 X ', 1, vt3.X);
AssertEquals('CreateParallelProjectionMatrix:Sub16 Y ', 1, vt3.Y);
AssertEquals('CreateParallelProjectionMatrix:Sub17 Z ', 0, vt3.Z);
AssertEquals('CreateParallelProjectionMatrix:Sub18 W ', 1, vt3.W); // vt1 was a point should get point back
// is should not matter if the vector is reversed they are the same Angle to the plane
mtx1.CreateParallelProjectionMatrix(apl1, vt1);
vt2.Create(1,1,0,1); //create usual point on z = 0 plane.
vt3 := mtx1 * vt2; // vt2 should be unaffected by this transform
AssertEquals('CreateParallelProjectionMatrix:Sub19 X ', 1, vt3.X);
AssertEquals('CreateParallelProjectionMatrix:Sub20 Y ', 1, vt3.Y);
AssertEquals('CreateParallelProjectionMatrix:Sub21 Z ', 0, vt3.Z);
AssertEquals('CreateParallelProjectionMatrix:Sub22 W ', 1, vt3.W); // vt1 was a point should get point back
vt2.Create(1,1,1,1); //create usual point above z=0 plane.
vt3 := mtx1 * vt2; // vt2 should be shifted in the -x axis (toward the Y by tan(45).
AssertEquals('CreateParallelProjectionMatrix:Sub23 X ', 1-1, vt3.X);
AssertEquals('CreateParallelProjectionMatrix:Sub24 Y ', 1, vt3.Y);
AssertEquals('CreateParallelProjectionMatrix:Sub25 Z ', 0, vt3.Z);
AssertEquals('CreateParallelProjectionMatrix:Sub26 W ', 1, vt3.W); // vt1 was a point should get point back
vt2.Create(1,1,2,1); //create usual point above z=0 plane.
vt3 := mtx1 * vt2; // vt2 should be shifted in the -x axis (toward the Y by tan(45).
AssertEquals('CreateParallelProjectionMatrix:Sub27 X ', 1-2, vt3.X);
AssertEquals('CreateParallelProjectionMatrix:Sub28 Y ', 1, vt3.Y);
AssertEquals('CreateParallelProjectionMatrix:Sub29 Z ', 0, vt3.Z);
AssertEquals('CreateParallelProjectionMatrix:Sub30 W ', 1, vt3.W); // vt1 was a point should get point back
vt2.Create(1,1,-2,1); //create usual point above z=0 plane.
vt3 := mtx1 * vt2; // vt2 should be shifted in the -x axis (toward the Y by tan(45).
AssertEquals('CreateParallelProjectionMatrix:Sub31 X ', 1+2, vt3.X);
AssertEquals('CreateParallelProjectionMatrix:Sub32 Y ', 1, vt3.Y);
AssertEquals('CreateParallelProjectionMatrix:Sub33 Z ', 0, vt3.Z);
AssertEquals('CreateParallelProjectionMatrix:Sub34 W ', 1, vt3.W); // vt1 was a point should get point back
end;
function TMatrixFunctionalTest.OddPosition(Pos: Integer; AValue: Single): TBZMatrix4f;
begin
Result.V[0].Create(1, 2, 2, 4); // interesting matrix this, inverse
Result.V[1].Create(2, 1, 4, 2); // is 0 point value reoccuring
Result.V[2].Create(2, 4, 1, 2);
Result.V[3].Create(4, 2, 2, 1);
case Pos of
1: Result.m11 := AValue ;
2: Result.m12 := AValue ;
3: Result.m13 := AValue ;
4: Result.m14 := AValue ;
5: Result.m21 := AValue ;
6: Result.m22 := AValue ;
7: Result.m23 := AValue ;
8: Result.m24 := AValue ;
9: Result.m31 := AValue ;
10: Result.m32 := AValue ;
11: Result.m33 := AValue ;
12: Result.m34 := AValue ;
13: Result.m41 := AValue ;
14: Result.m42 := AValue ;
15: Result.m43 := AValue ;
16: Result.m44 := AValue ;
end;
end;
function TMatrixFunctionalTest.OddTwoByTwo(Pos: Integer; AValue: Single): TBZMatrix4f;
begin
Result.V[0].Create(1, 2, 2, 4); // interesting matrix this, inverse
Result.V[1].Create(2, 1, 4, 2); // is 0 point value reoccuring
Result.V[2].Create(2, 4, 1, 2);
Result.V[3].Create(4, 2, 2, 1);
case Pos of
1: begin // top left
Result.m11 := AValue ;
Result.m12 := AValue ;
Result.m21 := AValue ;
Result.m22 := AValue ;
end;
2: begin // top mid
Result.m12 := AValue ;
Result.m13 := AValue ;
Result.m22 := AValue ;
Result.m23 := AValue ;
end;
3: begin // top right
Result.m13 := AValue ;
Result.m14 := AValue ;
Result.m23 := AValue ;
Result.m24 := AValue ;
end;
4: begin // mid left
Result.m21 := AValue ;
Result.m22 := AValue ;
Result.m31 := AValue ;
Result.m32 := AValue ;
end;
5: begin // mid mid
Result.m22 := AValue ;
Result.m23 := AValue ;
Result.m32 := AValue ;
Result.m33 := AValue ;
end;
6: begin // mid right
Result.m23 := AValue ;
Result.m24 := AValue ;
Result.m33 := AValue ;
Result.m34 := AValue ;
end;
7: begin // bottom left
Result.m31 := AValue ;
Result.m32 := AValue ;
Result.m41 := AValue ;
Result.m42 := AValue ;
end;
8: begin // bottom mid
Result.m32 := AValue ;
Result.m33 := AValue ;
Result.m42 := AValue ;
Result.m43 := AValue ;
end;
9: begin // bottom right
Result.m33 := AValue ;
Result.m34 := AValue ;
Result.m43 := AValue ;
Result.m44 := AValue ;
end;
end;
end;
initialization
RegisterTest(REPORT_GROUP_MATRIX4F, TMatrixFunctionalTest);
end.
|
unit UnitStaticDAELoader; // Copyright (C) 2006-2017, Benjamin Rosseaux - License: zlib
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpu386}
{$asmmode intel}
{$endif}
{$ifdef cpuamd64}
{$asmmode intel}
{$endif}
{$ifdef fpc_little_endian}
{$define little_endian}
{$else}
{$ifdef fpc_big_endian}
{$define big_endian}
{$endif}
{$endif}
{$ifdef fpc_has_internal_sar}
{$define HasSAR}
{$endif}
{-$pic off}
{$define caninline}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$else}
{$realcompatibility off}
{$localsymbols on}
{$define little_endian}
{$ifndef cpu64}
{$define cpu32}
{$endif}
{$define delphi}
{$undef HasSAR}
{$define UseDIV}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$define HAS_TYPE_SINGLE}
{$endif}
{$ifdef cpu386}
{$define cpux86}
{$endif}
{$ifdef cpuamd64}
{$define cpux86}
{$endif}
{$ifdef win32}
{$define windows}
{$endif}
{$ifdef win64}
{$define windows}
{$endif}
{$ifdef wince}
{$define windows}
{$endif}
{$ifdef windows}
{$define win}
{$endif}
{$ifdef sdl20}
{$define sdl}
{$endif}
{$rangechecks off}
{$extendedsyntax on}
{$writeableconst on}
{$hints off}
{$booleval off}
{$typedaddress off}
{$stackframes off}
{$varstringchecks on}
{$typeinfo on}
{$overflowchecks off}
{$longstrings on}
{$openstrings on}
{$ifndef HAS_TYPE_DOUBLE}
{$error No double floating point precision}
{$endif}
{$ifdef fpc}
{$define caninline}
{$else}
{$undef caninline}
{$ifdef ver180}
{$define caninline}
{$else}
{$ifdef conditionalexpressions}
{$if compilerversion>=18}
{$define caninline}
{$ifend}
{$endif}
{$endif}
{$endif}
interface
uses SysUtils,Classes,Math,UnitMath3D,UnitXML,UnitStringHashMap;
const dluaNONE=-1;
dluaXUP=0;
dluaYUP=1;
dluaZUP=2;
dlstCONSTANT=0;
dlstLAMBERT=1;
dlstBLINN=2;
dlstPHONG=3;
dlltAMBIENT=0;
dlltDIRECTIONAL=1;
dllTPOINT=2;
dlltSPOT=3;
dlctPERSPECTIVE=0;
dlctORTHOGRAPHIC=1;
dlmtTRIANGLES=0;
dlmtLINESTRIP=1;
dlMAXTEXCOORDSETS=8;
type PDAELight=^TDAELight;
TDAELight=record
Name:ansistring;
LightType:longint;
Position:TVector3;
Direction:TVector3;
Color:TVector3;
FallOffAngle:single;
FallOffExponent:single;
ConstantAttenuation:single;
LinearAttenuation:single;
QuadraticAttenuation:single;
end;
TDAELights=array of TDAELight;
PDAECamera=^TDAECamera;
TDAECamera=record
Name:ansistring;
Matrix:TMatrix4x4;
ZNear:single;
ZFar:single;
AspectRatio:single;
case CameraType:longint of
dlctPERSPECTIVE:(
XFov:single;
YFov:single;
);
dlctORTHOGRAPHIC:(
XMag:single;
YMag:single;
);
end;
TDAECameras=array of TDAECamera;
PDAEColorOrTexture=^TDAEColorOrTexture;
TDAEColorOrTexture=record
HasColor:boolean;
HasTexture:boolean;
Color:TVector4;
Texture:ansistring;
TexCoord:ansistring;
OffsetU:single;
OffsetV:single;
RepeatU:single;
RepeatV:single;
WrapU:longint;
WrapV:longint;
end;
PDAEMaterial=^TDAEMaterial;
TDAEMaterial=record
Name:ansistring;
ShadingType:longint;
Ambient:TDAEColorOrTexture;
Diffuse:TDAEColorOrTexture;
Emission:TDAEColorOrTexture;
Specular:TDAEColorOrTexture;
Transparent:TDAEColorOrTexture;
Shininess:single;
Reflectivity:single;
IndexOfRefraction:single;
Transparency:single;
end;
TDAEMaterials=array of TDAEMaterial;
PDAEVertex=^TDAEVertex;
TDAEVertex=record
Position:TVector3;
Normal:TVector3;
Tangent:TVector3;
Bitangent:TVector3;
TexCoords:array[0..dlMAXTEXCOORDSETS-1] of TVector2;
CountTexCoords:longint;
Color:TVector3;
end;
TDAEVertices=array of TDAEVertex;
TDAEVerticesArray=array of TDAEVertices;
TDAEIndices=array of longint;
PDAEMeshTexCoordSet=^TDAEMeshTexCoordSet;
TDAEMeshTexCoordSet=record
Semantic:ansistring;
InputSet:longint;
end;
TDAEMeshTexCoordSets=array of TDAEMeshTexCoordSet;
TDAEMesh=class
public
MeshType:longint;
MaterialIndex:longint;
TexCoordSets:TDAEMeshTexCoordSets;
Vertices:TDAEVertices;
Indices:TDAEIndices;
constructor Create;
destructor Destroy; override;
procedure Optimize;
procedure CalculateMissingInformations(Normals:boolean=true;Tangents:boolean=true);
end;
TDAEGeometry=class(TList)
private
function GetMesh(const Index:longint):TDAEMesh;
procedure SetMesh(const Index:longint;Mesh:TDAEMesh);
public
Name:ansistring;
constructor Create;
destructor Destroy; override;
procedure Clear; override;
property Items[const Index:longint]:TDAEMesh read GetMesh write SetMesh; default;
end;
TDAEGeometries=class(TList)
private
function GetGeometry(const Index:longint):TDAEGeometry;
procedure SetGeometry(const Index:longint;Geometry:TDAEGeometry);
public
constructor Create;
destructor Destroy; override;
procedure Clear; override;
property Items[const Index:longint]:TDAEGeometry read GetGeometry write SetGeometry; default;
end;
TDAELoader=class
private
public
COLLADAVersion:ansistring;
AuthoringTool:ansistring;
Created:TDateTime;
Modified:TDateTime;
UnitMeter:double;
UnitName:ansistring;
UpAxis:longint;
Lights:TDAELights;
CountLights:longint;
Cameras:TDAECameras;
CountCameras:longint;
Materials:TDAEMaterials;
CountMaterials:longint;
Geometries:TDAEGeometries;
constructor Create;
destructor Destroy; override;
function Load(Stream:TStream):boolean;
function ExportAsOBJ(FileName:ansistring):boolean;
end;
implementation
uses PasDblStrUtils;
function NextPowerOfTwo(i:longint;MinThreshold:longint=0):longint;
begin
result:=(i or MinThreshold)-1;
result:=result or (result shr 1);
result:=result or (result shr 2);
result:=result or (result shr 4);
result:=result or (result shr 8);
result:=result or (result shr 16);
inc(result);
end;
function CompareBytes(a,b:pointer;Count:longint):boolean;
var pa,pb:pansichar;
begin
pa:=a;
pb:=b;
result:=true;
while Count>7 do begin
if int64(pointer(pa)^)<>int64(pointer(pb)^) then begin
result:=false;
exit;
end;
inc(pa,8);
inc(pb,8);
dec(Count,8);
end;
while Count>3 do begin
if longword(pointer(pa)^)<>longword(pointer(pb)^) then begin
result:=false;
exit;
end;
inc(pa,4);
inc(pb,4);
dec(Count,4);
end;
while Count>1 do begin
if word(pointer(pa)^)<>word(pointer(pb)^) then begin
result:=false;
exit;
end;
inc(pa,2);
inc(pb,2);
dec(Count,2);
end;
while Count>0 do begin
if pa^<>pb^ then begin
result:=false;
exit;
end;
inc(pa);
inc(pb);
dec(Count);
end;
end;
function HashBytes(const a:pointer;Count:longint):longword;
{$ifdef cpuarm}
var b:pansichar;
len,h,i:longword;
begin
result:=2166136261;
len:=Count;
h:=len;
if len>0 then begin
b:=a;
while len>3 do begin
i:=longword(pointer(b)^);
h:=(h xor i) xor $2e63823a;
inc(h,(h shl 15) or (h shr (32-15)));
dec(h,(h shl 9) or (h shr (32-9)));
inc(h,(h shl 4) or (h shr (32-4)));
dec(h,(h shl 1) or (h shr (32-1)));
h:=h xor (h shl 2) or (h shr (32-2));
result:=result xor i;
inc(result,(result shl 1)+(result shl 4)+(result shl 7)+(result shl 8)+(result shl 24));
inc(b,4);
dec(len,4);
end;
if len>1 then begin
i:=word(pointer(b)^);
h:=(h xor i) xor $2e63823a;
inc(h,(h shl 15) or (h shr (32-15)));
dec(h,(h shl 9) or (h shr (32-9)));
inc(h,(h shl 4) or (h shr (32-4)));
dec(h,(h shl 1) or (h shr (32-1)));
h:=h xor (h shl 2) or (h shr (32-2));
result:=result xor i;
inc(result,(result shl 1)+(result shl 4)+(result shl 7)+(result shl 8)+(result shl 24));
inc(b,2);
dec(len,2);
end;
if len>0 then begin
i:=byte(b^);
h:=(h xor i) xor $2e63823a;
inc(h,(h shl 15) or (h shr (32-15)));
dec(h,(h shl 9) or (h shr (32-9)));
inc(h,(h shl 4) or (h shr (32-4)));
dec(h,(h shl 1) or (h shr (32-1)));
h:=h xor (h shl 2) or (h shr (32-2));
result:=result xor i;
inc(result,(result shl 1)+(result shl 4)+(result shl 7)+(result shl 8)+(result shl 24));
end;
end;
result:=result xor h;
if result=0 then begin
result:=$ffffffff;
end;
end;
{$else}
{$ifndef fpc}
type qword=int64;
{$endif}
const m=longword($57559429);
n=longword($5052acdb);
var b:pansichar;
h,k,len:longword;
p:{$ifdef fpc}qword{$else}int64{$endif};
begin
len:=Count;
h:=len;
k:=h+n+1;
if len>0 then begin
b:=a;
while len>7 do begin
begin
p:=longword(pointer(b)^)*qword(n);
h:=h xor longword(p and $ffffffff);
k:=k xor longword(p shr 32);
inc(b,4);
end;
begin
p:=longword(pointer(b)^)*qword(m);
k:=k xor longword(p and $ffffffff);
h:=h xor longword(p shr 32);
inc(b,4);
end;
dec(len,8);
end;
if len>3 then begin
p:=longword(pointer(b)^)*qword(n);
h:=h xor longword(p and $ffffffff);
k:=k xor longword(p shr 32);
inc(b,4);
dec(len,4);
end;
if len>0 then begin
if len>1 then begin
p:=word(pointer(b)^);
inc(b,2);
dec(len,2);
end else begin
p:=0;
end;
if len>0 then begin
p:=p or (byte(b^) shl 16);
end;
p:=p*qword(m);
k:=k xor longword(p and $ffffffff);
h:=h xor longword(p shr 32);
end;
end;
begin
p:=(h xor (k+n))*qword(n);
h:=h xor longword(p and $ffffffff);
k:=k xor longword(p shr 32);
end;
result:=k xor h;
if result=0 then begin
result:=$ffffffff;
end;
end;
{$endif}
function StrToDouble(s:ansistring;const DefaultValue:double=0.0):double;
var OK:TPasDblStrUtilsBoolean;
begin
OK:=false;
if length(s)>0 then begin
result:=ConvertStringToDouble(s,rmNearest,@OK);
if not OK then begin
result:=DefaultValue;
end;
end else begin
result:=DefaultValue;
end;
end;
function DoubleToStr(v:double):ansistring;
begin
result:=ConvertDoubleToString(v,omStandard,0);
end;
type TCharSet=set of ansichar;
function GetToken(var InputString:ansistring;const Divider:TCharSet=[#0..#32]):ansistring;
var i:longint;
begin
i:=1;
while (i<=length(InputString)) and (InputString[i] in Divider) do begin
inc(i);
end;
if i>1 then begin
Delete(InputString,1,i-1);
end;
i:=1;
while (i<=length(InputString)) and not (InputString[i] in Divider) do begin
inc(i);
end;
result:=Copy(InputString,1,i-1);
Delete(InputString,1,i);
end;
constructor TDAEMesh.Create;
begin
inherited Create;
MeshType:=dlmtTRIANGLES;
Vertices:=nil;
Indices:=nil;
TexCoordSets:=nil;
end;
destructor TDAEMesh.Destroy;
begin
SetLength(Vertices,0);
SetLength(Indices,0);
SetLength(TexCoordSets,0);
inherited Destroy;
end;
procedure TDAEMesh.Optimize;
const HashBits=16;
HashSize=1 shl HashBits;
HashMask=HashSize-1;
type PHashTableItem=^THashTableItem;
THashTableItem=record
Next:PHashTableItem;
Hash:longword;
VertexIndex:longint;
end;
PHashTable=^THashTable;
THashTable=array[0..HashSize-1] of PHashTableItem;
function HashVector(const v:TDAEVertex):longword;
begin
result:=((round(v.Position.x)*73856093) xor (round(v.Position.y)*19349663) xor (round(v.Position.z)*83492791));
end;
var NewVertices:TDAEVertices;
NewIndices:TDAEIndices;
NewVerticesCount,NewIndicesCount,IndicesIndex,VertexIndex,VertexCounter,FoundVertexIndex,TexCoordSetIndex,Index:longint;
OK:boolean;
HashTable:PHashTable;
HashTableItem,NextHashTableItem:PHashTableItem;
Hash:longword;
begin
NewVertices:=nil;
NewIndices:=nil;
HashTable:=nil;
try
GetMem(HashTable,SizeOf(THashTable));
FillChar(HashTable^,SizeOf(THashTable),AnsiChar(#0));
NewVerticesCount:=0;
NewIndicesCount:=0;
SetLength(NewVertices,length(Vertices));
SetLength(NewIndices,length(Indices));
for IndicesIndex:=0 to length(Indices)-1 do begin
VertexIndex:=Indices[IndicesIndex];
FoundVertexIndex:=-1;
Hash:=HashVector(Vertices[VertexIndex]);
HashTableItem:=HashTable[Hash and HashMask];
while assigned(HashTableItem) do begin
if HashTableItem^.Hash=Hash then begin
VertexCounter:=HashTableItem^.VertexIndex;
if Vector3Compare(Vertices[VertexIndex].Position,NewVertices[VertexCounter].Position) and
Vector3Compare(Vertices[VertexIndex].Normal,NewVertices[VertexCounter].Normal) and
Vector3Compare(Vertices[VertexIndex].Tangent,NewVertices[VertexCounter].Tangent) and
Vector3Compare(Vertices[VertexIndex].Bitangent,NewVertices[VertexCounter].Bitangent) and
Vector3Compare(Vertices[VertexIndex].Color,NewVertices[VertexCounter].Color) then begin
OK:=true;
for TexCoordSetIndex:=0 to Max(Min(Vertices[VertexIndex].CountTexCoords,dlMAXTEXCOORDSETS),0)-1 do begin
if not Vector2Compare(Vertices[VertexIndex].TexCoords[TexCoordSetIndex],NewVertices[VertexCounter].TexCoords[TexCoordSetIndex]) then begin
OK:=false;
break;
end;
end;
if OK then begin
FoundVertexIndex:=VertexCounter;
break;
end;
end;
end;
HashTableItem:=HashTableItem^.Next;
end;
if FoundVertexIndex<0 then begin
GetMem(HashTableItem,SizeOf(THashTableItem));
HashTableItem^.Next:=HashTable[Hash and HashMask];
HashTable[Hash and HashMask]:=HashTableItem;
HashTableItem^.Hash:=Hash;
HashTableItem^.VertexIndex:=NewVerticesCount;
FoundVertexIndex:=NewVerticesCount;
NewVertices[NewVerticesCount]:=Vertices[VertexIndex];
inc(NewVerticesCount);
end;
NewIndices[NewIndicesCount]:=FoundVertexIndex;
inc(NewIndicesCount);
end;
SetLength(NewVertices,NewVerticesCount);
SetLength(NewIndices,NewIndicesCount);
SetLength(Vertices,0);
SetLength(Indices,0);
Vertices:=NewVertices;
Indices:=NewIndices;
NewVertices:=nil;
NewIndices:=nil;
finally
SetLength(NewVertices,0);
SetLength(NewIndices,0);
for Index:=low(THashTable) to high(THashTable) do begin
HashTableItem:=HashTable[Index];
HashTable[Index]:=nil;
while assigned(HashTableItem) do begin
NextHashTableItem:=HashTableItem^.Next;
FreeMem(HashTableItem);
HashTableItem:=NextHashTableItem;
end;
end;
FreeMem(HashTable);
end;
end;
procedure TDAEMesh.CalculateMissingInformations(Normals:boolean=true;Tangents:boolean=true);
const f1d3=1.0/3.0;
var IndicesIndex,CountIndices,VertexIndex,CountVertices,CountTriangles,Counter:longint;
v0,v1,v2:PDAEVertex;
VerticesCounts:array of longint;
VerticesNormals,VerticesTangents,VerticesBitangents:array of TVector3;
TriangleNormal,TriangleTangent,TriangleBitangent,Normal:TVector3;
t1,t2,t3,t4,f:single;
begin
VerticesCounts:=nil;
VerticesNormals:=nil;
VerticesTangents:=nil;
VerticesBitangents:=nil;
try
if Normals or Tangents then begin
case MeshType of
dlmtTRIANGLES:begin
CountIndices:=length(Indices);
CountTriangles:=length(Indices) div 3;
if CountTriangles>0 then begin
CountVertices:=length(Vertices);
SetLength(VerticesCounts,CountVertices);
SetLength(VerticesNormals,CountVertices);
SetLength(VerticesTangents,CountVertices);
SetLength(VerticesBitangents,CountVertices);
for VertexIndex:=0 to CountVertices-1 do begin
VerticesCounts[VertexIndex]:=0;
VerticesNormals[VertexIndex]:=Vector3Origin;
VerticesTangents[VertexIndex]:=Vector3Origin;
VerticesBitangents[VertexIndex]:=Vector3Origin;
end;
IndicesIndex:=0;
while (IndicesIndex+2)<CountIndices do begin
v0:=@Vertices[Indices[IndicesIndex+0]];
v1:=@Vertices[Indices[IndicesIndex+1]];
v2:=@Vertices[Indices[IndicesIndex+2]];
TriangleNormal:=Vector3Norm(Vector3Cross(Vector3Sub(v2^.Position,v0^.Position),Vector3Sub(v1^.Position,v0^.Position)));
if not Normals then begin
Normal.x:=(v0^.Normal.x+v1^.Normal.x+v2^.Normal.x)*f1d3;
Normal.y:=(v0^.Normal.y+v1^.Normal.y+v2^.Normal.y)*f1d3;
Normal.z:=(v0^.Normal.z+v1^.Normal.z+v2^.Normal.z)*f1d3;
if ((TriangleNormal.x*Normal.x)+(TriangleNormal.y*Normal.y)+(TriangleNormal.z*Normal.z))<0.0 then begin
TriangleNormal.x:=-TriangleNormal.x;
TriangleNormal.y:=-TriangleNormal.y;
TriangleNormal.z:=-TriangleNormal.z;
end;
end;
t1:=v1^.TexCoords[0].v-v0^.TexCoords[0].v;
t2:=v2^.TexCoords[0].v-v0^.TexCoords[0].v;
t3:=v1^.TexCoords[0].u-v0^.TexCoords[0].u;
t4:=v2^.TexCoords[0].u-v0^.TexCoords[0].u;
TriangleTangent.x:=(t1*(v2^.Position.x-v0^.Position.x))-(t2*(v1^.Position.x-v0^.Position.x));
TriangleTangent.y:=(t1*(v2^.Position.y-v0^.Position.y))-(t2*(v1^.Position.y-v0^.Position.y));
TriangleTangent.z:=(t1*(v2^.Position.z-v0^.Position.z))-(t2*(v1^.Position.z-v0^.Position.z));
TriangleBitangent.x:=(t3*(v2^.Position.x-v0^.Position.x))-(t4*(v1^.Position.x-v0^.Position.x));
TriangleBitangent.y:=(t3*(v2^.Position.y-v0^.Position.y))-(t4*(v1^.Position.y-v0^.Position.y));
TriangleBitangent.z:=(t3*(v2^.Position.z-v0^.Position.z))-(t4*(v1^.Position.z-v0^.Position.z));
TriangleTangent:=Vector3Norm(Vector3Add(TriangleTangent,Vector3ScalarMul(TriangleNormal,-Vector3Dot(TriangleTangent,TriangleNormal))));
TriangleBitangent:=Vector3Norm(Vector3Add(TriangleBitangent,Vector3ScalarMul(TriangleNormal,-Vector3Dot(TriangleBitangent,TriangleNormal))));
if Vector3Dot(Vector3Cross(TriangleBitangent,TriangleTangent),TriangleNormal)<0 then begin
TriangleTangent.x:=-TriangleTangent.x;
TriangleTangent.y:=-TriangleTangent.y;
TriangleTangent.z:=-TriangleTangent.z;
TriangleBitangent.x:=-TriangleBitangent.x;
TriangleBitangent.y:=-TriangleBitangent.y;
TriangleBitangent.z:=-TriangleBitangent.z;
end;
for Counter:=0 to 2 do begin
VertexIndex:=Indices[IndicesIndex+Counter];
inc(VerticesCounts[VertexIndex]);
VerticesNormals[VertexIndex]:=Vector3Add(VerticesNormals[VertexIndex],TriangleNormal);
VerticesTangents[VertexIndex]:=Vector3Add(VerticesTangents[VertexIndex],TriangleTangent);
VerticesBitangents[VertexIndex]:=Vector3Add(VerticesBitangents[VertexIndex],TriangleBitangent);
end;
inc(IndicesIndex,3);
end;
for VertexIndex:=0 to CountVertices-1 do begin
if VerticesCounts[VertexIndex]>0 then begin
f:=1.0/VerticesCounts[VertexIndex];
end else begin
f:=0.0;
end;
v0:=@Vertices[VertexIndex];
if Normals then begin
v0^.Normal:=Vector3Norm(Vector3ScalarMul(VerticesNormals[VertexIndex],f));
end;
if Tangents then begin
v0^.Tangent:=Vector3Norm(Vector3ScalarMul(VerticesTangents[VertexIndex],f));
v0^.Bitangent:=Vector3Norm(Vector3ScalarMul(VerticesBitangents[VertexIndex],f));
end;
end;
end;
end;
end;
end;
finally
SetLength(VerticesCounts,0);
SetLength(VerticesNormals,0);
SetLength(VerticesTangents,0);
SetLength(VerticesBitangents,0);
end;
end;
constructor TDAEGeometry.Create;
begin
inherited Create;
Name:='';
end;
destructor TDAEGeometry.Destroy;
var i:longint;
Mesh:TDAEMesh;
begin
for i:=0 to Count-1 do begin
Mesh:=Items[i];
Mesh.Free;
Items[i]:=nil;
end;
inherited Destroy;
end;
procedure TDAEGeometry.Clear;
var i:longint;
Mesh:TDAEMesh;
begin
for i:=0 to Count-1 do begin
Mesh:=Items[i];
Mesh.Free;
Items[i]:=nil;
end;
Name:='';
inherited Clear;
end;
function TDAEGeometry.GetMesh(const Index:longint):TDAEMesh;
begin
result:=inherited Items[Index];
end;
procedure TDAEGeometry.SetMesh(const Index:longint;Mesh:TDAEMesh);
begin
inherited Items[Index]:=Mesh;
end;
constructor TDAEGeometries.Create;
begin
inherited Create;
end;
destructor TDAEGeometries.Destroy;
var i:longint;
Geometry:TDAEGeometry;
begin
for i:=0 to Count-1 do begin
Geometry:=Items[i];
Geometry.Free;
Items[i]:=nil;
end;
inherited Destroy;
end;
procedure TDAEGeometries.Clear;
var i:longint;
Geometry:TDAEGeometry;
begin
for i:=0 to Count-1 do begin
Geometry:=Items[i];
Geometry.Free;
Items[i]:=nil;
end;
inherited Clear;
end;
function TDAEGeometries.GetGeometry(const Index:longint):TDAEGeometry;
begin
result:=inherited Items[Index];
end;
procedure TDAEGeometries.SetGeometry(const Index:longint;Geometry:TDAEGeometry);
begin
inherited Items[Index]:=Geometry;
end;
constructor TDAELoader.Create;
begin
inherited Create;
COLLADAVersion:='1.5.0';
AuthoringTool:='';
Created:=Now;
Modified:=Now;
UnitMeter:=1.0;
UnitName:='meter';
UpAxis:=dluaYUP;
Lights:=nil;
CountLights:=0;
Cameras:=nil;
CountCameras:=0;
Materials:=nil;
CountMaterials:=0;
Geometries:=TDAEGeometries.Create;
end;
destructor TDAELoader.Destroy;
begin
SetLength(Lights,0);
SetLength(Cameras,0);
SetLength(Materials,0);
Geometries.Free;
inherited Destroy;
end;
function TDAELoader.Load(Stream:TStream):boolean;
const lstBOOL=0;
lstINT=1;
lstFLOAT=2;
lstIDREF=3;
lstNAME=4;
aptNONE=0;
aptIDREF=1;
aptNAME=2;
aptINT=3;
aptFLOAT=4;
aptFLOAT4x4=5;
ltAMBIENT=0;
ltDIRECTIONAL=1;
ltPOINT=2;
ltSPOT=3;
ntNODE=0;
ntROTATE=1;
ntTRANSLATE=2;
ntSCALE=3;
ntMATRIX=4;
ntLOOKAT=5;
ntSKEW=6;
ntEXTRA=7;
ntINSTANCECAMERA=8;
ntINSTANCELIGHT=9;
ntINSTANCECONTROLLER=10;
ntINSTANCEGEOMETRY=11;
ntINSTANCENODE=12;
mtNONE=0;
mtTRIANGLES=1;
mtTRIFANS=2;
mtTRISTRIPS=3;
mtPOLYGONS=4;
mtPOLYLIST=5;
mtLINES=6;
mtLINESTRIPS=7;
type PLibraryImage=^TLibraryImage;
TLibraryImage=record
Next:PLibraryImage;
ID:ansistring;
InitFrom:ansistring;
end;
PLibraryEffect=^TLibraryEffect;
PLibraryMaterial=^TLibraryMaterial;
TLibraryMaterial=record
Next:PLibraryMaterial;
ID:ansistring;
Name:ansistring;
EffectURL:ansistring;
Effect:PLibraryEffect;
Index:longint;
end;
PLibraryEffectSurface=^TLibraryEffectSurface;
TLibraryEffectSurface=record
Next:PLibraryEffectSurface;
Effect:PLibraryEffect;
SID:ansistring;
InitFrom:ansistring;
Format:ansistring;
end;
PLibraryEffectSampler2D=^TLibraryEffectSampler2D;
TLibraryEffectSampler2D=record
Next:PLibraryEffectSampler2D;
Effect:PLibraryEffect;
SID:ansistring;
Source:ansistring;
WrapS:ansistring;
WrapT:ansistring;
MinFilter:ansistring;
MagFilter:ansistring;
MipFilter:ansistring;
end;
PLibraryEffectFloat=^TLibraryEffectFloat;
TLibraryEffectFloat=record
Next:PLibraryEffectFloat;
Effect:PLibraryEffect;
SID:ansistring;
Value:single;
end;
PLibraryEffectFloat4=^TLibraryEffectFloat4;
TLibraryEffectFloat4=record
Next:PLibraryEffectFloat4;
Effect:PLibraryEffect;
SID:ansistring;
Values:array[0..3] of single;
end;
TLibraryEffect=record
Next:PLibraryEffect;
ID:ansistring;
Name:ansistring;
Images:TList;
Surfaces:PLibraryEffectSurface;
Sampler2D:PLibraryEffectSampler2D;
Floats:PLibraryEffectFloat;
Float4s:PLibraryEffectFloat4;
ShadingType:longint;
Ambient:TDAEColorOrTexture;
Diffuse:TDAEColorOrTexture;
Emission:TDAEColorOrTexture;
Specular:TDAEColorOrTexture;
Transparent:TDAEColorOrTexture;
Shininess:single;
Reflectivity:single;
IndexOfRefraction:single;
Transparency:single;
end;
PLibrarySourceData=^TLibrarySourceData;
TLibrarySourceData=record
Next:PLibrarySourceData;
ID:ansistring;
SourceType:longint;
Data:array of double;
Strings:array of ansistring;
end;
PLibrarySourceAccessorParam=^TLibrarySourceAccessorParam;
TLibrarySourceAccessorParam=record
ParamName:ansistring;
ParamType:longint;
end;
TLibrarySourceAccessorParams=array of TLibrarySourceAccessorParam;
PLibrarySourceAccessor=^TLibrarySourceAccessor;
TLibrarySourceAccessor=record
Source:ansistring;
Count:longint;
Offset:longint;
Stride:longint;
Params:TLibrarySourceAccessorParams;
end;
PLibrarySource=^TLibrarySource;
TLibrarySource=record
Next:PLibrarySource;
ID:ansistring;
SourceDatas:TList;
Accessor:TLibrarySourceAccessor;
end;
PInput=^TInput;
TInput=record
Semantic:ansistring;
Source:ansistring;
Set_:longint;
Offset:longint;
end;
TInputs=array of TInput;
PLibraryVertices=^TLibraryVertices;
TLibraryVertices=record
Next:PLibraryVertices;
ID:ansistring;
Inputs:TInputs;
end;
TInts=array of longint;
PLibraryGeometryMesh=^TLibraryGeometryMesh;
TLibraryGeometryMesh=record
MeshType:longint;
Count:longint;
Material:ansistring;
Inputs:TInputs;
VCounts:TInts;
Indices:array of TInts;
end;
TLibraryGeometryMeshs=array of TLibraryGeometryMesh;
PLibraryGeometry=^TLibraryGeometry;
TLibraryGeometry=record
Next:PLibraryGeometry;
ID:ansistring;
Meshs:TLibraryGeometryMeshs;
CountMeshs:longint;
end;
PLibraryLight=^TLibraryLight;
TLibraryLight=record
Next:PLibraryLight;
ID:ansistring;
Name:ansistring;
LightType:longint;
Color:TVector3;
FallOffAngle:single;
FallOffExponent:single;
ConstantAttenuation:single;
LinearAttenuation:single;
QuadraticAttenuation:single;
end;
PLibraryCamera=^TLibraryCamera;
TLibraryCamera=record
Next:PLibraryCamera;
ID:ansistring;
Name:ansistring;
Camera:TDAECamera;
SIDZNear:ansistring;
SIDZFar:ansistring;
SIDAspectRatio:ansistring;
SIDXFov:ansistring;
SIDYFov:ansistring;
SIDXMag:ansistring;
SIDYMag:ansistring;
end;
PInstanceMaterialTexCoordSet=^TInstanceMaterialTexCoordSet;
TInstanceMaterialTexCoordSet=record
Semantic:ansistring;
InputSet:longint;
end;
TInstanceMaterialTexCoordSets=array of TInstanceMaterialTexCoordSet;
PInstanceMaterial=^TInstanceMaterial;
TInstanceMaterial=record
Symbol:ansistring;
Target:ansistring;
TexCoordSets:TInstanceMaterialTexCoordSets;
end;
TInstanceMaterials=array of TInstanceMaterial;
PLibraryNode=^TLibraryNode;
TLibraryNode=record
Next:PLibraryNode;
ID:ansistring;
SID:ansistring;
Name:ansistring;
NodeType_:ansistring;
InstanceMaterials:TInstanceMaterials;
InstanceNode:ansistring;
case NodeType:longint of
ntNODE:(
Children:TList;
);
ntROTATE,
ntTRANSLATE,
ntSCALE,
ntMATRIX,
ntLOOKAT,
ntSKEW:(
Matrix:TMatrix4x4;
);
ntEXTRA:(
);
ntINSTANCECAMERA:(
InstanceCamera:PLibraryCamera;
);
ntINSTANCELIGHT:(
InstanceLight:PLibraryLight;
);
ntINSTANCECONTROLLER:(
);
ntINSTANCEGEOMETRY:(
InstanceGeometry:PLibraryGeometry;
);
ntINSTANCENODE:(
);
end;
PLibraryVisualScene=^TLibraryVisualScene;
TLibraryVisualScene=record
Next:PLibraryVisualScene;
ID:ansistring;
Items:TList;
end;
var IDStringHashMap:TStringHashMap;
LibraryImagesIDStringHashMap:TStringHashMap;
LibraryImages:PLibraryImage;
LibraryMaterialsIDStringHashMap:TStringHashMap;
LibraryMaterials:PLibraryMaterial;
LibraryEffectsIDStringHashMap:TStringHashMap;
LibraryEffects:PLibraryEffect;
LibrarySourcesIDStringHashMap:TStringHashMap;
LibrarySources:PLibrarySource;
LibrarySourceDatasIDStringHashMap:TStringHashMap;
LibrarySourceDatas:PLibrarySourceData;
LibraryVerticesesIDStringHashMap:TStringHashMap;
LibraryVerticeses:PLibraryVertices;
LibraryGeometriesIDStringHashMap:TStringHashMap;
LibraryGeometries:PLibraryGeometry;
LibraryCamerasIDStringHashMap:TStringHashMap;
LibraryCameras:PLibraryCamera;
LibraryLightsIDStringHashMap:TStringHashMap;
LibraryLights:PLibraryLight;
LibraryVisualScenesIDStringHashMap:TStringHashMap;
LibraryVisualScenes:PLibraryVisualScene;
LibraryNodesIDStringHashMap:TStringHashMap;
LibraryNodes:PLibraryNode;
MainVisualScene:PLibraryVisualScene;
AxisMatrix:TMatrix4x4;
BadAccessor:boolean;
FlipAngle:boolean;
NegJoints:boolean;
procedure CollectIDs(ParentItem:TXMLItem);
var XMLItemIndex:longint;
XMLItem:TXMLItem;
ID:ansistring;
begin
if assigned(ParentItem) then begin
for XMLItemIndex:=0 to ParentItem.Items.Count-1 do begin
XMLItem:=ParentItem.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
ID:=TXMLTag(XMLItem).GetParameter('id','');
if length(ID)>0 then begin
IDStringHashMap.Add(ID,XMLItem);
end;
end;
CollectIDs(XMLItem);
end;
end;
end;
end;
function ParseText(ParentItem:TXMLItem):ansistring;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
begin
result:='';
if assigned(ParentItem) then begin
for XMLItemIndex:=0 to ParentItem.Items.Count-1 do begin
XMLItem:=ParentItem.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLText then begin
result:=result+TXMLText(XMLItem).Text;
end else if XMLItem is TXMLTag then begin
if TXMLTag(XMLItem).Name='br' then begin
result:=result+#13#10;
end;
result:=result+ParseText(XMLItem);
end;
end;
end;
end;
end;
function ParseContributorTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='authoring_tool' then begin
AuthoringTool:=ParseText(XMLTag);
if AuthoringTool='COLLADA Mixamo exporter' then begin
BadAccessor:=true;
end else if AuthoringTool='FBX COLLADA exporter' then begin
BadAccessor:=true;
end else if pos('Blender 2.5',AuthoringTool)>0 then begin
FlipAngle:=true;
NegJoints:=true;
end;
end;
end;
end;
end;
result:=true;
end;
end;
function ParseAssetTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
s:ansistring;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='contributor' then begin
ParseContributorTag(XMLTag);
end else if XMLTag.Name='created' then begin
s:=ParseText(XMLTag);
if length(s)>0 then begin
end;
end else if XMLTag.Name='modified' then begin
s:=ParseText(XMLTag);
if length(s)>0 then begin
end;
end else if XMLTag.Name='unit' then begin
UnitMeter:=StrToDouble(XMLTag.GetParameter('meter','1.0'),1.0);
UnitName:=XMLTag.GetParameter('name','meter');
end else if XMLTag.Name='up_axis' then begin
s:=UpperCase(Trim(ParseText(XMLTag)));
if (s='X') or (s='X_UP') then begin
UpAxis:=dluaXUP;
end else if (s='Y') or (s='Y_UP') then begin
UpAxis:=dluaYUP;
end else if (s='Z') or (s='Z_UP') then begin
UpAxis:=dluaZUP;
end;
end;
end;
end;
end;
result:=true;
end;
end;
function ParseImageTag(ParentTag:TXMLTag):PLibraryImage;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag,XMLSubTag:TXMLTag;
ID,InitFrom:ansistring;
Image:PLibraryImage;
begin
result:=nil;
if assigned(ParentTag) then begin
ID:=TXMLTag(ParentTag).GetParameter('id','');
if length(ID)>0 then begin
InitFrom:='';
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='init_from' then begin
XMLSubTag:=XMLTag.FindTag('ref');
if assigned(XMLSubTag) then begin
InitFrom:=ParseText(XMLSubTag);
end else begin
InitFrom:=ParseText(XMLTag);
end;
end;
end;
end;
end;
if length(InitFrom)>0 then begin
GetMem(Image,SizeOf(TLibraryImage));
FillChar(Image^,SizeOf(TLibraryImage),AnsiChar(#0));
Image^.Next:=LibraryImages;
LibraryImages:=Image;
Image^.ID:=ID;
Image^.InitFrom:=InitFrom;
LibraryImagesIDStringHashMap.Add(ID,Image);
result:=Image;
end;
end;
end;
end;
function ParseLibraryImagesTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='image' then begin
ParseImageTag(XMLTag);
end;
end;
end;
end;
result:=true;
end;
end;
function ParseMaterialTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
ID,Name,EffectURL:ansistring;
Material:PLibraryMaterial;
begin
result:=false;
if assigned(ParentTag) then begin
ID:=TXMLTag(ParentTag).GetParameter('id','');
Name:=TXMLTag(ParentTag).GetParameter('name','');
if length(ID)>0 then begin
EffectURL:='';
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='instance_effect' then begin
EffectURL:=StringReplace(XMLTag.GetParameter('url',''),'#','',[rfReplaceAll]);
end;
end;
end;
end;
if length(EffectURL)>0 then begin
GetMem(Material,SizeOf(TLibraryMaterial));
FillChar(Material^,SizeOf(TLibraryMaterial),AnsiChar(#0));
Material^.Next:=LibraryMaterials;
LibraryMaterials:=Material;
Material^.ID:=ID;
Material^.Name:=Name;
Material^.EffectURL:=EffectURL;
Material^.Index:=-1;
LibraryMaterialsIDStringHashMap.Add(ID,Material);
end;
end;
result:=true;
end;
end;
function ParseLibraryMaterialsTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='material' then begin
ParseMaterialTag(XMLTag);
end;
end;
end;
end;
result:=true;
end;
end;
function ParseNewParamTag(ParentTag:TXMLTag;Effect:PLibraryEffect):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag,XMLSubTag,XMLSubSubTag:TXMLTag;
SID,s:ansistring;
Surface:PLibraryEffectSurface;
Sampler2D:PLibraryEffectSampler2D;
Float:PLibraryEffectFloat;
Float4:PLibraryEffectFloat4;
Image:PLibraryImage;
begin
result:=false;
if assigned(ParentTag) then begin
SID:=TXMLTag(ParentTag).GetParameter('sid','');
if length(SID)>0 then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='surface' then begin
GetMem(Surface,SizeOf(TLibraryEffectSurface));
FillChar(Surface^,SizeOf(TLibraryEffectSurface),AnsiChar(#0));
Surface^.Next:=Effect^.Surfaces;
Effect^.Surfaces:=Surface;
Surface^.Effect:=Effect;
Surface^.SID:=SID;
XMLSubTag:=XMLTag.FindTag('init_from');
if assigned(XMLSubTag) then begin
XMLSubSubTag:=XMLSubTag.FindTag('ref');
if assigned(XMLSubSubTag) then begin
Surface^.InitFrom:=ParseText(XMLSubSubTag);
end else begin
Surface^.InitFrom:=ParseText(XMLSubTag);
end;
end else begin
Surface^.InitFrom:='';
end;
Surface^.Format:=ParseText(XMLTag.FindTag('format'));
end else if XMLTag.Name='sampler2D' then begin
GetMem(Sampler2D,SizeOf(TLibraryEffectSampler2D));
FillChar(Sampler2D^,SizeOf(TLibraryEffectSampler2D),AnsiChar(#0));
Sampler2D^.Next:=Effect^.Sampler2D;
Effect^.Sampler2D:=Sampler2D;
Sampler2D^.Effect:=Effect;
Sampler2D^.SID:=SID;
Sampler2D^.Source:=ParseText(XMLTag.FindTag('source'));
Sampler2D^.WrapS:=ParseText(XMLTag.FindTag('wrap_s'));
Sampler2D^.WrapT:=ParseText(XMLTag.FindTag('wrap_t'));
Sampler2D^.MinFilter:=ParseText(XMLTag.FindTag('minfilter'));
Sampler2D^.MagFilter:=ParseText(XMLTag.FindTag('magfilter'));
Sampler2D^.MipFilter:=ParseText(XMLTag.FindTag('mipfilter'));
XMLSubTag:=XMLTag.FindTag('instance_image');
if assigned(XMLSubTag) then begin
Image:=LibraryImagesIDStringHashMap[StringReplace(XMLSubTag.GetParameter('url',''),'#','',[rfReplaceAll])];
if assigned(Image) then begin
Sampler2D^.Source:=Image^.InitFrom;
end;
end;
end else if XMLTag.Name='float' then begin
GetMem(Float,SizeOf(TLibraryEffectFloat));
FillChar(Float^,SizeOf(TLibraryEffectFloat),AnsiChar(#0));
Float^.Next:=Effect^.Floats;
Effect^.Floats:=Float;
Float^.Effect:=Effect;
Float^.SID:=SID;
Float^.Value:=StrToDouble(ParseText(XMLTag),0.0);
end else if XMLTag.Name='float4' then begin
GetMem(Float4,SizeOf(TLibraryEffectFloat4));
FillChar(Float4^,SizeOf(TLibraryEffectFloat4),AnsiChar(#0));
Float4^.Next:=Effect^.Float4s;
Effect^.Float4s:=Float4;
Float4^.Effect:=Effect;
Float4^.SID:=SID;
s:=ParseText(XMLTag);
Float4^.Values[0]:=StrToDouble(GetToken(s),0.0);
Float4^.Values[1]:=StrToDouble(GetToken(s),0.0);
Float4^.Values[2]:=StrToDouble(GetToken(s),0.0);
Float4^.Values[3]:=StrToDouble(GetToken(s),0.0);
end else if XMLTag.Name='extra' then begin
end;
end;
end;
end;
result:=true;
end;
end;
end;
function ParseFloat(ParentTag:TXMLTag;Effect:PLibraryEffect;const DefaultValue:single=0.0):single;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
s:ansistring;
Float:PLibraryEffectFloat;
begin
result:=DefaultValue;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='float' then begin
result:=StrToDouble(ParseText(XMLTag),DefaultValue);
exit;
end else if XMLTag.Name='param' then begin
s:=XMLTag.GetParameter('ref');
if length(s)>0 then begin
Float:=Effect^.Floats;
while assigned(Float) do begin
if Float^.SID=s then begin
result:=Float^.Value;
exit;
end;
Float:=Float^.Next;
end;
end;
end;
end;
end;
end;
result:=StrToDouble(ParseText(ParentTag),DefaultValue);
end;
end;
function ParseFloat4(ParentTag:TXMLTag;Effect:PLibraryEffect;const DefaultValue:TVector4):TVector4;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
s:ansistring;
Float4:PLibraryEffectFloat4;
begin
result:=DefaultValue;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='float' then begin
s:=ParseText(XMLTag);
result.x:=StrToDouble(GetToken(s),DefaultValue.x);
result.y:=StrToDouble(GetToken(s),DefaultValue.y);
result.z:=StrToDouble(GetToken(s),DefaultValue.z);
result.w:=StrToDouble(GetToken(s),DefaultValue.w);
exit;
end else if XMLTag.Name='param' then begin
s:=XMLTag.GetParameter('ref');
if length(s)>0 then begin
Float4:=Effect^.Float4s;
while assigned(Float4) do begin
if Float4^.SID=s then begin
result.x:=Float4.Values[0];
result.y:=Float4.Values[1];
result.z:=Float4.Values[2];
result.w:=Float4.Values[3];
exit;
end;
Float4:=Float4^.Next;
end;
end;
end;
end;
end;
end;
s:=ParseText(ParentTag);
result.x:=StrToDouble(GetToken(s),DefaultValue.x);
result.y:=StrToDouble(GetToken(s),DefaultValue.y);
result.z:=StrToDouble(GetToken(s),DefaultValue.z);
result.w:=StrToDouble(GetToken(s),DefaultValue.w);
end;
end;
function ParseColorOrTextureTag(ParentTag:TXMLTag;Effect:PLibraryEffect;const DefaultColor:TVector4):TDAEColorOrTexture;
var XMLTag,TempXMLTag:TXMLTag;
s:ansistring;
Sampler2D:PLibraryEffectSampler2D;
Surface:PLibraryEffectSurface;
Image:PLibraryImage;
begin
FillChar(result,SizeOf(TDAEColorOrTexture),AnsiChar(#0));
if assigned(ParentTag) then begin
begin
XMLTag:=ParentTag.FindTag('color');
if assigned(XMLTag) then begin
result.HasColor:=true;
s:=Trim(ParseText(XMLTag));
result.Color.r:=StrToDouble(GetToken(s),DefaultColor.r);
result.Color.g:=StrToDouble(GetToken(s),DefaultColor.g);
result.Color.b:=StrToDouble(GetToken(s),DefaultColor.b);
result.Color.a:=StrToDouble(GetToken(s),DefaultColor.a);
end else begin
XMLTag:=ParentTag.FindTag('param');
if assigned(XMLTag) then begin
result.HasColor:=true;
result.Color:=ParseFloat4(XMLTag,Effect,DefaultColor);
end else begin
result.Color:=DefaultColor;
end;
end;
end;
begin
XMLTag:=ParentTag.FindTag('texture');
if assigned(XMLTag) then begin
result.HasTexture:=true;
s:=XMLTag.GetParameter('texture');
result.Texture:=s;
if length(s)>0 then begin
Sampler2D:=Effect^.Sampler2D;
while assigned(Sampler2D) do begin
if Sampler2D^.SID=s then begin
result.Texture:=Sampler2D^.Source;
s:='';
break;
end;
Sampler2D:=Sampler2D^.Next;
end;
if length(s)>0 then begin
Surface:=Effect^.Surfaces;
while assigned(Surface) do begin
if Surface^.SID=s then begin
result.Texture:=Surface^.InitFrom;
s:='';
break;
end;
Surface:=Surface^.Next;
end;
end;
if length(s)>0 then begin
Image:=LibraryImagesIDStringHashMap[s];
if assigned(Image) then begin
result.Texture:=Image^.InitFrom;
s:='';
end;
end;
end;
result.TexCoord:=XMLTag.GetParameter('texcoord');
result.OffsetU:=0.0;
result.OffsetV:=0.0;
result.RepeatU:=1.0;
result.RepeatV:=1.0;
result.WrapU:=1;
result.WrapV:=1;
XMLTag:=XMLTag.FindTag('extra');
if assigned(XMLTag) then begin
TempXMLTag:=XMLTag.FindTag('technique');
if assigned(TempXMLTag) then begin
XMLTag:=TempXMLTag;
end;
result.OffsetU:=StrToDouble(ParseText(XMLTag.FindTag('offsetU')),0.0);
result.OffsetV:=StrToDouble(ParseText(XMLTag.FindTag('offsetV')),0.0);
result.RepeatU:=StrToDouble(ParseText(XMLTag.FindTag('repeatU')),1.0);
result.RepeatV:=StrToDouble(ParseText(XMLTag.FindTag('repeatV')),1.0);
result.WrapU:=StrToIntDef(ParseText(XMLTag.FindTag('wrapU')),1);
result.WrapV:=StrToIntDef(ParseText(XMLTag.FindTag('wrapV')),1);
end;
end;
end;
end;
end;
function ParseTechniqueTag(ParentTag:TXMLTag;Effect:PLibraryEffect):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
ShadingType:longint;
begin
result:=false;
if assigned(ParentTag) then begin
ShadingType:=-1;
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='constant' then begin
ShadingType:=dlstCONSTANT;
end else if XMLTag.Name='lambert' then begin
ShadingType:=dlstLAMBERT;
end else if XMLTag.Name='blinn' then begin
ShadingType:=dlstBLINN;
end else if XMLTag.Name='phong' then begin
ShadingType:=dlstPHONG;
end;
if ShadingType>=0 then begin
Effect^.ShadingType:=ShadingType;
Effect^.Ambient:=ParseColorOrTextureTag(XMLTag.FindTag('ambient'),Effect,Vector4(0.0,0.0,0.0,1.0));
Effect^.Diffuse:=ParseColorOrTextureTag(XMLTag.FindTag('diffuse'),Effect,Vector4(1.0,1.0,1.0,1.0));
Effect^.Emission:=ParseColorOrTextureTag(XMLTag.FindTag('emission'),Effect,Vector4(0.0,0.0,0.0,1.0));
Effect^.Specular:=ParseColorOrTextureTag(XMLTag.FindTag('specular'),Effect,Vector4(0.0,0.0,0.0,1.0));
Effect^.Transparent:=ParseColorOrTextureTag(XMLTag.FindTag('transparent'),Effect,Vector4(0.0,0.0,0.0,1.0));
Effect^.Shininess:=ParseFloat(XMLTag.FindTag('shininess'),Effect,-Infinity);
Effect^.Reflectivity:=ParseFloat(XMLTag.FindTag('reflectivity'),Effect,-Infinity);
Effect^.IndexOfRefraction:=ParseFloat(XMLTag.FindTag('index_of_refraction'),Effect,-Infinity);
Effect^.Transparency:=ParseFloat(XMLTag.FindTag('transparency'),Effect,-Infinity);
break;
end;
end;
result:=true;
end;
end;
end;
end;
function ParseProfileCommonTag(ParentTag:TXMLTag;Effect:PLibraryEffect):TXMLTag;
var PassIndex,XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
Image:PLibraryImage;
begin
result:=nil;
if assigned(ParentTag) then begin
for PassIndex:=0 to 4 do begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if (PassIndex=0) and (XMLTag.Name='profile_COMMON') then begin
result:=ParseProfileCommonTag(XMLTag,Effect);
end else if (PassIndex=1) and (XMLTag.Name='image') then begin
Image:=ParseImageTag(XMLTag);
if assigned(Image) then begin
Effect^.Images.Add(Image);
end;
end else if (PassIndex=2) and (XMLTag.Name='newparam') then begin
ParseNewParamTag(XMLTag,Effect);
end else if (PassIndex=3) and (XMLTag.Name='technique') then begin
result:=XMLTag;
end else if (PassIndex=4) and (XMLTag.Name='extra') then begin
end;
end;
end;
end;
end;
end;
end;
function ParseEffectTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
ID,Name:ansistring;
Effect:PLibraryEffect;
begin
result:=false;
if assigned(ParentTag) then begin
ID:=TXMLTag(ParentTag).GetParameter('id','');
Name:=TXMLTag(ParentTag).GetParameter('name','');
if length(ID)>0 then begin
GetMem(Effect,SizeOf(TLibraryEffect));
FillChar(Effect^,SizeOf(TLibraryEffect),AnsiChar(#0));
Effect^.Next:=LibraryEffects;
LibraryEffects:=Effect;
Effect^.ID:=ID;
Effect^.Name:=Name;
EFfect^.Images:=TList.Create;
Effect^.ShadingType:=-1;
LibraryEffectsIDStringHashMap.Add(ID,Effect);
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='profile_COMMON' then begin
ParseTechniqueTag(ParseProfileCommonTag(XMLTag,Effect),Effect);
end;
end;
end;
end;
end;
result:=true;
end;
end;
function ParseLibraryEffectsTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='effect' then begin
ParseEffectTag(XMLTag);
end;
end;
end;
end;
result:=true;
end;
end;
function ParseaAccessorTag(ParentTag:TXMLTag;const Accessor:PLibrarySourceAccessor):boolean;
var XMLItemIndex,Count:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
s:ansistring;
begin
result:=false;
if assigned(ParentTag) then begin
Accessor^.Source:=StringReplace(ParentTag.GetParameter('source',''),'#','',[rfReplaceAll]);
Accessor^.Count:=StrToIntDef(ParentTag.GetParameter('count'),0);
Accessor^.Offset:=StrToIntDef(ParentTag.GetParameter('offset'),0);
Accessor^.Stride:=StrToIntDef(ParentTag.GetParameter('stride'),1);
Count:=0;
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='param' then begin
if (Count+1)>length(Accessor^.Params) then begin
SetLength(Accessor^.Params,(Count+1)*2);
end;
Accessor^.Params[Count].ParamName:=XMLTag.GetParameter('name');
s:=XMLTag.GetParameter('type');
if s='IDREF' then begin
Accessor^.Params[Count].ParamType:=aptIDREF;
end else if (s='Name') or (s='name') then begin
Accessor^.Params[Count].ParamType:=aptNAME;
end else if s='int' then begin
Accessor^.Params[Count].ParamType:=aptINT;
end else if s='float' then begin
Accessor^.Params[Count].ParamType:=aptFLOAT;
end else if s='float4x4' then begin
Accessor^.Params[Count].ParamType:=aptFLOAT4x4;
end else begin
Accessor^.Params[Count].ParamType:=aptNONE;
end;
inc(Count);
end;
end;
end;
end;
SetLength(Accessor^.Params,Count);
result:=true;
end;
end;
function ParseSourceTag(ParentTag:TXMLTag):boolean;
var PassIndex,XMLItemIndex,Count,i,j:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
ID:ansistring;
s,si:ansistring;
Source:PLibrarySource;
SourceData:PLibrarySourceData;
begin
result:=false;
if assigned(ParentTag) then begin
ID:=TXMLTag(ParentTag).GetParameter('id','');
if length(ID)>0 then begin
GetMem(Source,SizeOf(TLibrarySource));
FillChar(Source^,SizeOf(TLibrarySource),AnsiChar(#0));
Source^.Next:=LibrarySources;
LibrarySources:=Source;
Source^.ID:=ID;
Source^.SourceDatas:=TList.Create;
LibrarySourcesIDStringHashMap.Add(ID,Source);
for PassIndex:=0 to 1 do begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if (PassIndex=0) and (XMLTag.Name='bool_array') then begin
GetMem(SourceData,SizeOf(TLibrarySourceData));
FillChar(SourceData^,SizeOf(TLibrarySourceData),AnsiChar(#0));
SourceData^.Next:=LibrarySourceDatas;
LibrarySourceDatas:=SourceData;
SourceData^.ID:=XMLTag.GetParameter('id');
LibrarySourceDatasIDStringHashMap.Add(SourceData^.ID,SourceData);
SourceData^.SourceType:=lstBOOL;
Source^.SourceDatas.Add(SourceData);
s:=ParseText(XMLTag);
Count:=0;
i:=1;
while i<=length(s) do begin
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
j:=i;
while (i<=length(s)) and not (s[i] in [#0..#32]) do begin
inc(i);
end;
if j<i then begin
si:=copy(s,j,i-j);
end else begin
si:='';
end;
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
if (Count+1)>length(SourceData^.Data) then begin
SetLength(SourceData^.Data,(Count+1)*2);
end;
si:=LowerCase(trim(si));
if (si='true') or (si='yes') or (si='1') then begin
SourceData^.Data[Count]:=1;
end else begin
SourceData^.Data[Count]:=0;
end;
inc(Count);
end;
SetLength(SourceData^.Data,Count);
break;
end else if (PassIndex=0) and (XMLTag.Name='float_array') then begin
GetMem(SourceData,SizeOf(TLibrarySourceData));
FillChar(SourceData^,SizeOf(TLibrarySourceData),AnsiChar(#0));
SourceData^.Next:=LibrarySourceDatas;
LibrarySourceDatas:=SourceData;
SourceData^.ID:=XMLTag.GetParameter('id');
LibrarySourceDatasIDStringHashMap.Add(SourceData^.ID,SourceData);
SourceData^.SourceType:=lstFLOAT;
Source^.SourceDatas.Add(SourceData);
s:=ParseText(XMLTag);
Count:=0;
i:=1;
while i<=length(s) do begin
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
j:=i;
while (i<=length(s)) and not (s[i] in [#0..#32]) do begin
inc(i);
end;
if j<i then begin
si:=copy(s,j,i-j);
end else begin
si:='';
end;
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
if (Count+1)>length(SourceData^.Data) then begin
SetLength(SourceData^.Data,(Count+1)*2);
end;
SourceData^.Data[Count]:=StrToDouble(Trim(si),0.0);
inc(Count);
end;
SetLength(SourceData^.Data,Count);
break;
end else if (PassIndex=0) and (XMLTag.Name='int_array') then begin
GetMem(SourceData,SizeOf(TLibrarySourceData));
FillChar(SourceData^,SizeOf(TLibrarySourceData),AnsiChar(#0));
SourceData^.Next:=LibrarySourceDatas;
LibrarySourceDatas:=SourceData;
SourceData^.ID:=XMLTag.GetParameter('id');
LibrarySourceDatasIDStringHashMap.Add(SourceData^.ID,SourceData);
SourceData^.SourceType:=lstINT;
Source^.SourceDatas.Add(SourceData);
s:=ParseText(XMLTag);
Count:=0;
i:=1;
while i<=length(s) do begin
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
j:=i;
while (i<=length(s)) and not (s[i] in [#0..#32]) do begin
inc(i);
end;
if j<i then begin
si:=copy(s,j,i-j);
end else begin
si:='';
end;
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
if (Count+1)>length(SourceData^.Data) then begin
SetLength(SourceData^.Data,(Count+1)*2);
end;
SourceData^.Data[Count]:=StrToIntDef(Trim(si),0);
inc(Count);
end;
SetLength(SourceData^.Data,Count);
break;
end else if (PassIndex=0) and (XMLTag.Name='IDREF_array') then begin
GetMem(SourceData,SizeOf(TLibrarySourceData));
FillChar(SourceData^,SizeOf(TLibrarySourceData),AnsiChar(#0));
SourceData^.Next:=LibrarySourceDatas;
LibrarySourceDatas:=SourceData;
SourceData^.ID:=XMLTag.GetParameter('id');
LibrarySourceDatasIDStringHashMap.Add(SourceData^.ID,SourceData);
SourceData^.SourceType:=lstIDREF;
Source^.SourceDatas.Add(SourceData);
s:=ParseText(XMLTag);
Count:=0;
i:=1;
while i<=length(s) do begin
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
j:=i;
while (i<=length(s)) and not (s[i] in [#0..#32]) do begin
inc(i);
end;
if j<i then begin
si:=copy(s,j,i-j);
end else begin
si:='';
end;
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
if (Count+1)>length(SourceData^.Strings) then begin
SetLength(SourceData^.Strings,(Count+1)*2);
end;
SourceData^.Strings[Count]:=si;
inc(Count);
end;
SetLength(SourceData^.Strings,Count);
break;
end else if (PassIndex=0) and (XMLTag.Name='Name_array') then begin
GetMem(SourceData,SizeOf(TLibrarySourceData));
FillChar(SourceData^,SizeOf(TLibrarySourceData),AnsiChar(#0));
SourceData^.Next:=LibrarySourceDatas;
LibrarySourceDatas:=SourceData;
SourceData^.ID:=XMLTag.GetParameter('id');
LibrarySourceDatasIDStringHashMap.Add(SourceData^.ID,SourceData);
SourceData^.SourceType:=lstNAME;
Source^.SourceDatas.Add(SourceData);
s:=ParseText(XMLTag);
Count:=0;
i:=1;
while i<=length(s) do begin
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
j:=i;
while (i<=length(s)) and not (s[i] in [#0..#32]) do begin
inc(i);
end;
if j<i then begin
si:=copy(s,j,i-j);
end else begin
si:='';
end;
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
if (Count+1)>length(SourceData^.Strings) then begin
SetLength(SourceData^.Strings,(Count+1)*2);
end;
SourceData^.Strings[Count]:=si;
inc(Count);
end;
SetLength(SourceData^.Strings,Count);
break;
end else if (PassIndex=1) and (XMLTag.Name='technique_common') then begin
ParseaAccessorTag(XMLTag.FindTag('accessor'),@Source^.Accessor);
end;
end;
end;
end;
end;
result:=true;
end;
end;
end;
function ParseInputTag(ParentTag:TXMLTag;var Input:TInput):boolean;
begin
result:=false;
if assigned(ParentTag) then begin
Input.Semantic:=ParentTag.GetParameter('semantic');
Input.Source:=StringReplace(ParentTag.GetParameter('source',''),'#','',[rfReplaceAll]);
Input.Set_:=StrToIntDef(ParentTag.GetParameter('set','-1'),-1);
Input.Offset:=StrToIntDef(ParentTag.GetParameter('offset','0'),0);
if (Input.Semantic='TEXCOORD') and (Input.Set_<0) then begin
Input.Set_:=0;
end;
result:=true;
end;
end;
function ParseVerticesTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex,Count:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
ID:ansistring;
Vertices:PLibraryVertices;
begin
result:=false;
if assigned(ParentTag) then begin
ID:=TXMLTag(ParentTag).GetParameter('id','');
if length(ID)>0 then begin
GetMem(Vertices,SizeOf(TLibraryVertices));
FillChar(Vertices^,SizeOf(TLibraryVertices),AnsiChar(#0));
Vertices^.Next:=LibraryVerticeses;
LibraryVerticeses:=Vertices;
Vertices^.ID:=ID;
LibraryVerticesesIDStringHashMap.Add(ID,Vertices);
Count:=0;
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='input' then begin
if (Count+1)>length(Vertices^.Inputs) then begin
SetLength(Vertices^.Inputs,(Count+1)*2);
end;
ParseInputTag(XMLTag,Vertices^.Inputs[Count]);
inc(Count);
end;
end;
end;
end;
SetLength(Vertices^.Inputs,Count);
result:=true;
end;
end;
end;
function ParseMeshTag(ParentTag:TXMLTag;Geometry:PLibraryGeometry):boolean;
var PassIndex,XMLItemIndex,XMLSubItemIndex,MeshType,InputCount,IndicesCount,Count,i,j,
TotalIndicesCount:longint;
XMLItem,XMLSubItem:TXMLItem;
XMLTag,XMLSubTag:TXMLTag;
s,si:ansistring;
Mesh:PLibraryGeometryMesh;
begin
result:=false;
if assigned(ParentTag) then begin
MeshType:=mtNONE;
IndicesCount:=0;
for PassIndex:=0 to 2 do begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if (PassIndex=0) and (XMLTag.Name='source') then begin
ParseSourceTag(XMLTag);
end else if (PassIndex=1) and (XMLTag.Name='vertices') then begin
ParseVerticesTag(XMLTag);
end else if (PassIndex=2) and ((XMLTag.Name='triangles') or
(XMLTag.Name='trifans') or
(XMLTag.Name='tristrips') or
(XMLTag.Name='polygons') or
(XMLTag.Name='polylist') or
(XMLTag.Name='lines') or
(XMLTag.Name='linestrips')) then begin
if XMLTag.Name='triangles' then begin
MeshType:=mtTRIANGLES;
end else if XMLTag.Name='trifans' then begin
MeshType:=mtTRIFANS;
end else if XMLTag.Name='tristrips' then begin
MeshType:=mtTRIFANS;
end else if XMLTag.Name='polygons' then begin
MeshType:=mtPOLYGONS;
end else if XMLTag.Name='polylist' then begin
MeshType:=mtPOLYLIST;
end else if XMLTag.Name='lines' then begin
MeshType:=mtLINES;
end else if XMLTag.Name='lines' then begin
MeshType:=mtLINES;
end else if XMLTag.Name='linestrips' then begin
MeshType:=mtLINESTRIPS;
end;
if (Geometry^.CountMeshs+1)>length(Geometry^.Meshs) then begin
SetLength(Geometry^.Meshs,(Geometry^.CountMeshs+1)*2);
end;
Mesh:=@Geometry^.Meshs[Geometry^.CountMeshs];
inc(Geometry^.CountMeshs);
Mesh^.MeshType:=MeshType;
Mesh^.Material:=XMLTag.GetParameter('material');
Mesh^.Count:=StrToIntDef(XMLTag.GetParameter('count'),0);
InputCount:=0;
TotalIndicesCount:=0;
for XMLSubItemIndex:=0 to XMLTag.Items.Count-1 do begin
XMLSubItem:=XMLTag.Items[XMLSubItemIndex];
if assigned(XMLSubItem) then begin
if XMLSubItem is TXMLTag then begin
XMLSubTag:=TXMLTag(XMLSubItem);
if XMLSubTag.Name='input' then begin
if (InputCount+1)>length(Mesh^.Inputs) then begin
SetLength(Mesh^.Inputs,(InputCount+1)*2);
end;
ParseInputTag(XMLSubTag,Mesh^.Inputs[InputCount]);
inc(InputCount);
end else if XMLSubTag.Name='vcount' then begin
s:=ParseText(XMLSubTag);
Count:=0;
i:=1;
while i<=length(s) do begin
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
j:=i;
while (i<=length(s)) and not (s[i] in [#0..#32]) do begin
inc(i);
end;
if j<i then begin
si:=copy(s,j,i-j);
end else begin
si:='';
end;
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
if (Count+1)>length(Mesh^.VCounts) then begin
SetLength(Mesh^.VCounts,(Count+1)*2);
end;
Mesh^.VCounts[Count]:=StrToIntDef(Trim(si),0);
inc(Count);
end;
SetLength(Mesh^.VCounts,Count);
end else if XMLSubTag.Name='p' then begin
if (IndicesCount+1)>length(Mesh^.Indices) then begin
SetLength(Mesh^.Indices,(IndicesCount+1)*2);
end;
s:=ParseText(XMLSubTag);
Count:=0;
i:=1;
while i<=length(s) do begin
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
j:=i;
while (i<=length(s)) and not (s[i] in [#0..#32]) do begin
inc(i);
end;
if j<i then begin
si:=copy(s,j,i-j);
end else begin
si:='';
end;
while (i<=length(s)) and (s[i] in [#0..#32]) do begin
inc(i);
end;
if (Count+1)>length(Mesh^.Indices[IndicesCount]) then begin
SetLength(Mesh^.Indices[IndicesCount],(Count+1)*2);
end;
Mesh^.Indices[IndicesCount,Count]:=StrToIntDef(Trim(si),0);
inc(Count);
end;
SetLength(Mesh^.Indices[IndicesCount],Count);
inc(IndicesCount);
inc(TotalIndicesCount,Count);
end;
end;
end;
end;
if TotalIndicesCount>0 then begin
end;
SetLength(Mesh^.Inputs,InputCount);
SetLength(Mesh^.Indices,IndicesCount);
end;
end;
end;
end;
end;
result:=true;
end;
end;
function ParseGeometryTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
ID:ansistring;
Geometry:PLibraryGeometry;
begin
result:=false;
if assigned(ParentTag) then begin
ID:=TXMLTag(ParentTag).GetParameter('id','');
if length(ID)>0 then begin
GetMem(Geometry,SizeOf(TLibraryGeometry));
FillChar(Geometry^,SizeOf(TLibraryGeometry),AnsiChar(#0));
Geometry^.Next:=LibraryGeometries;
LibraryGeometries:=Geometry;
Geometry^.ID:=ID;
LibraryGeometriesIDStringHashMap.Add(ID,Geometry);
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='mesh' then begin
ParseMeshTag(XMLTag,Geometry);
end;
end;
end;
end;
SetLength(Geometry^.Meshs,Geometry^.CountMeshs);
result:=true;
end;
end;
end;
function ParseLibraryGeometriesTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='geometry' then begin
ParseGeometryTag(XMLTag);
end;
end;
end;
end;
result:=true;
end;
end;
function ParseCameraTag(ParentTag:TXMLTag):boolean;
var XMLSubItemIndex:longint;
XMLSubItem:TXMLItem;
XMLTag,XMLSubTag,XMLSubSubTag:TXMLTag;
ID,Name:ansistring;
Camera:PLibraryCamera;
begin
result:=false;
if assigned(ParentTag) then begin
ID:=TXMLTag(ParentTag).GetParameter('id','');
Name:=TXMLTag(ParentTag).GetParameter('name','');
if length(ID)>0 then begin
GetMem(Camera,SizeOf(TLibraryCamera));
FillChar(Camera^,SizeOf(TLibraryCamera),AnsiChar(#0));
Camera^.Next:=LibraryCameras;
LibraryCameras:=Camera;
Camera^.ID:=ID;
Camera^.Name:=Name;
Camera^.Camera.Name:=Name;
LibraryCamerasIDStringHashMap.Add(ID,Camera);
XMLTag:=ParentTag.FindTag('optics');
if assigned(XMLTag) then begin
XMLTag:=XMLTag.FindTag('technique_common');
if assigned(XMLTag) then begin
for XMLSubItemIndex:=0 to XMLTag.Items.Count-1 do begin
XMLSubItem:=XMLTag.Items[XMLSubItemIndex];
if assigned(XMLSubItem) then begin
if XMLSubItem is TXMLTag then begin
XMLSubTag:=TXMLTag(XMLSubItem);
if XMLSubTag.Name='perspective' then begin
Camera^.Camera.CameraType:=dlctPERSPECTIVE;
Camera^.Camera.XFov:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('xfov'))),0.0);
Camera^.Camera.YFov:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('yfov'))),0.0);
Camera^.Camera.ZNear:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('znear'))),0.0);
Camera^.Camera.ZFar:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('zfar'))),0.0);
Camera^.Camera.AspectRatio:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('aspect_ratio'))),0.0);
begin
XMLSubSubTag:=XMLSubTag.FindTag('xfov');
if assigned(XMLSubSubTag) then begin
Camera^.SIDXFov:=XMLSubSubTag.GetParameter('sid','');
end;
end;
begin
XMLSubSubTag:=XMLSubTag.FindTag('yfov');
if assigned(XMLSubSubTag) then begin
Camera^.SIDYFov:=XMLSubSubTag.GetParameter('sid','');
end;
end;
begin
XMLSubSubTag:=XMLSubTag.FindTag('znear');
if assigned(XMLSubSubTag) then begin
Camera^.SIDZNear:=XMLSubSubTag.GetParameter('sid','');
end;
end;
begin
XMLSubSubTag:=XMLSubTag.FindTag('zfar');
if assigned(XMLSubSubTag) then begin
Camera^.SIDZFar:=XMLSubSubTag.GetParameter('sid','');
end;
end;
begin
XMLSubSubTag:=XMLSubTag.FindTag('aspect_ratio');
if assigned(XMLSubSubTag) then begin
Camera^.SIDAspectRatio:=XMLSubSubTag.GetParameter('sid','');
end;
end;
break;
end else if XMLSubTag.Name='orthographic' then begin
Camera^.Camera.CameraType:=dlctORTHOGRAPHIC;
Camera^.Camera.XMag:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('xmag'))),0.0);
Camera^.Camera.YMag:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('ymag'))),0.0);
Camera^.Camera.ZNear:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('znear'))),0.0);
Camera^.Camera.ZFar:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('zfar'))),0.0);
Camera^.Camera.AspectRatio:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('aspect_ratio'))),0.0);
begin
XMLSubSubTag:=XMLSubTag.FindTag('xmag');
if assigned(XMLSubSubTag) then begin
Camera^.SIDXMag:=XMLSubSubTag.GetParameter('sid','');
end;
end;
begin
XMLSubSubTag:=XMLSubTag.FindTag('ymag');
if assigned(XMLSubSubTag) then begin
Camera^.SIDYMag:=XMLSubSubTag.GetParameter('sid','');
end;
end;
begin
XMLSubSubTag:=XMLSubTag.FindTag('znear');
if assigned(XMLSubSubTag) then begin
Camera^.SIDZNear:=XMLSubSubTag.GetParameter('sid','');
end;
end;
begin
XMLSubSubTag:=XMLSubTag.FindTag('zfar');
if assigned(XMLSubSubTag) then begin
Camera^.SIDZFar:=XMLSubSubTag.GetParameter('sid','');
end;
end;
begin
XMLSubSubTag:=XMLSubTag.FindTag('aspect_ratio');
if assigned(XMLSubSubTag) then begin
Camera^.SIDAspectRatio:=XMLSubSubTag.GetParameter('sid','');
end;
end;
break;
end;
end;
end;
end;
end;
end;
result:=true;
end;
end;
end;
function ParseLibraryCamerasTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='camera' then begin
ParseCameraTag(XMLTag);
end;
end;
end;
end;
result:=true;
end;
end;
function ParseLightTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex,XMLSubItemIndex:longint;
XMLItem,XMLSubItem:TXMLItem;
XMLTag,XMLSubTag:TXMLTag;
ID,Name:ansistring;
Light:PLibraryLight;
s:ansistring;
begin
result:=false;
if assigned(ParentTag) then begin
ID:=TXMLTag(ParentTag).GetParameter('id','');
Name:=TXMLTag(ParentTag).GetParameter('name','');
if length(ID)>0 then begin
GetMem(Light,SizeOf(TLibraryLight));
FillChar(Light^,SizeOf(TLibraryLight),AnsiChar(#0));
Light^.Next:=LibraryLights;
LibraryLights:=Light;
Light^.ID:=ID;
Light^.Name:=Name;
LibraryLightsIDStringHashMap.Add(ID,Light);
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='technique_common' then begin
for XMLSubItemIndex:=0 to XMLTag.Items.Count-1 do begin
XMLSubItem:=XMLTag.Items[XMLSubItemIndex];
if assigned(XMLSubItem) then begin
if XMLSubItem is TXMLTag then begin
XMLSubTag:=TXMLTag(XMLSubItem);
if (XMLSubTag.Name='ambient') or
(XMLSubTag.Name='directional') or
(XMLSubTag.Name='point') or
(XMLSubTag.Name='spot') then begin
if XMLSubTag.Name='ambient' then begin
Light^.LightType:=ltAMBIENT;
end else if XMLSubTag.Name='directional' then begin
Light^.LightType:=ltDIRECTIONAL;
end else if XMLSubTag.Name='point' then begin
Light^.LightType:=ltPOINT;
end else if XMLSubTag.Name='spot' then begin
Light^.LightType:=ltSPOT;
end;
s:=Trim(ParseText(XMLSubTag.FindTag('color')));
Light^.Color.r:=StrToDouble(GetToken(s),1.0);
Light^.Color.g:=StrToDouble(GetToken(s),1.0);
Light^.Color.b:=StrToDouble(GetToken(s),1.0);
Light^.ConstantAttenuation:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('constant_attenuation'))),1.0);
Light^.LinearAttenuation:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('linear_attenuation'))),0.0);
Light^.QuadraticAttenuation:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('quadratic_attenuation'))),0.0);
if Light^.LightType=ltSPOT then begin
Light^.FallOffAngle:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('falloff_angle'))),180.0);
Light^.FallOffExponent:=StrToDouble(Trim(ParseText(XMLSubTag.FindTag('falloff_exponent'))),0.0);
end else begin
Light^.FallOffAngle:=180.0;
Light^.FallOffExponent:=0.0;
end;
break;
end;
end;
end;
end;
end;
end;
end;
end;
result:=true;
end;
end;
end;
function ParseLibraryLightsTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='light' then begin
ParseLightTag(XMLTag);
end;
end;
end;
end;
result:=true;
end;
end;
function ParseLibraryControllersTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='controller' then begin
end;
end;
end;
end;
result:=true;
end;
end;
function ParseLibraryAnimationsTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='animation' then begin
end;
end;
end;
end;
result:=true;
end;
end;
function ParseNodeTag(ParentTag:TXMLTag):PLibraryNode;
var XMLItemIndex,XMLSubItemIndex,XMLSubSubItemIndex,Count,SubCount:longint;
XMLItem,XMLSubItem,XMLSubSubItem:TXMLItem;
XMLTag,XMLSubTag,XMLSubSubTag,BindMaterialTag,TechniqueCommonTag:TXMLTag;
ID,Name,s:ansistring;
Node,Item:PLibraryNode;
Vector3,LookAtOrigin,LookAtDest,LookAtUp,LookAtDirection,LookAtRight,
SkewA,SkewB,SkewN1,SkewN2,SkewA1,SkewA2:TVector3;
Angle,SkewAngle,SkewAN1,SkewAN2,SkewRX,SkewRY,SkewAlpha:single;
procedure CreateItem(NodeType:longint);
begin
GetMem(Item,SizeOf(TLibraryNode));
FillChar(Item^,SizeOf(TLibraryNode),AnsiChar(#0));
Item^.Next:=LibraryNodes;
LibraryNodes:=Item;
Item^.ID:=XMLTag.GetParameter('id','');
Item^.SID:=XMLTag.GetParameter('sid','');
Item^.Name:=XMLTag.GetParameter('name','');
Item^.NodeType_:=XMLTag.GetParameter('type','');
Item^.NodeType:=NodeType;
LibraryNodesIDStringHashMap.Add(Item^.ID,Item);
end;
begin
result:=nil;
if assigned(ParentTag) then begin
ID:=TXMLTag(ParentTag).GetParameter('id','');
Name:=TXMLTag(ParentTag).GetParameter('name','');
if length(ID)>0 then begin
GetMem(Node,SizeOf(TLibraryNode));
FillChar(Node^,SizeOf(TLibraryNode),AnsiChar(#0));
Node^.Next:=LibraryNodes;
LibraryNodes:=Node;
Node^.ID:=ID;
Node^.SID:=ParentTag.GetParameter('sid','');
Node^.Name:=Name;
Node^.NodeType_:=ParentTag.GetParameter('type','node');
Node^.Children:=TList.Create;
Node^.NodeType:=ntNODE;
LibraryNodesIDStringHashMap.Add(ID,Node);
result:=Node;
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='node' then begin
Item:=ParseNodeTag(XMLTag);
end else if XMLTag.Name='rotate' then begin
CreateItem(ntROTATE);
s:=Trim(ParseText(XMLTag));
Vector3.x:=StrToDouble(GetToken(s),0.0);
Vector3.y:=StrToDouble(GetToken(s),0.0);
Vector3.z:=StrToDouble(GetToken(s),0.0);
Angle:=StrToDouble(GetToken(s),0.0);
Item^.Matrix:=Matrix4x4Rotate(Angle*DEG2RAD,Vector3);
end else if XMLTag.Name='translate' then begin
CreateItem(ntTRANSLATE);
s:=Trim(ParseText(XMLTag));
Vector3.x:=StrToDouble(GetToken(s),0.0);
Vector3.y:=StrToDouble(GetToken(s),0.0);
Vector3.z:=StrToDouble(GetToken(s),0.0);
Item^.Matrix:=Matrix4x4Translate(Vector3);
end else if XMLTag.Name='scale' then begin
CreateItem(ntSCALE);
s:=Trim(ParseText(XMLTag));
Vector3.x:=StrToDouble(GetToken(s),0.0);
Vector3.y:=StrToDouble(GetToken(s),0.0);
Vector3.z:=StrToDouble(GetToken(s),0.0);
Item^.Matrix:=Matrix4x4Scale(Vector3);
end else if XMLTag.Name='matrix' then begin
CreateItem(ntMATRIX);
s:=Trim(ParseText(XMLTag));
Item^.Matrix[0,0]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[1,0]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[2,0]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[3,0]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[0,1]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[1,1]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[2,1]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[3,1]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[0,2]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[1,2]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[2,2]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[3,2]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[0,3]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[1,3]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[2,3]:=StrToDouble(GetToken(s),0.0);
Item^.Matrix[3,3]:=StrToDouble(GetToken(s),0.0);
end else if XMLTag.Name='lookat' then begin
CreateItem(ntLOOKAT);
s:=Trim(ParseText(XMLTag));
LookAtOrigin.x:=StrToDouble(GetToken(s),0.0);
LookAtOrigin.y:=StrToDouble(GetToken(s),0.0);
LookAtOrigin.z:=StrToDouble(GetToken(s),0.0);
LookAtDest.x:=StrToDouble(GetToken(s),0.0);
LookAtDest.y:=StrToDouble(GetToken(s),0.0);
LookAtDest.z:=StrToDouble(GetToken(s),0.0);
LookAtUp.x:=StrToDouble(GetToken(s),0.0);
LookAtUp.y:=StrToDouble(GetToken(s),0.0);
LookAtUp.z:=StrToDouble(GetToken(s),0.0);
Vector3Normalize(LookAtUp);
LookAtDirection:=Vector3Norm(Vector3Sub(LookAtDest,LookAtOrigin));
LookAtRight:=Vector3Norm(Vector3Cross(LookAtDirection,LookAtUp));
Item^.Matrix[0,0]:=LookAtRight.x;
Item^.Matrix[0,1]:=LookAtUp.x;
Item^.Matrix[0,2]:=-LookAtDirection.x;
Item^.Matrix[0,3]:=LookAtOrigin.x;
Item^.Matrix[1,0]:=LookAtRight.y;
Item^.Matrix[1,1]:=LookAtUp.y;
Item^.Matrix[1,2]:=-LookAtDirection.y;
Item^.Matrix[1,3]:=LookAtOrigin.y;
Item^.Matrix[1,0]:=LookAtRight.z;
Item^.Matrix[2,1]:=LookAtUp.z;
Item^.Matrix[2,2]:=-LookAtDirection.z;
Item^.Matrix[2,3]:=LookAtOrigin.z;
Item^.Matrix[3,0]:=0.0;
Item^.Matrix[3,1]:=0.0;
Item^.Matrix[3,2]:=0.0;
Item^.Matrix[3,3]:=1.0;
end else if XMLTag.Name='skew' then begin
CreateItem(ntSKEW);
s:=Trim(ParseText(XMLTag));
SkewAngle:=StrToDouble(GetToken(s),0.0);
SkewA.x:=StrToDouble(GetToken(s),0.0);
SkewA.y:=StrToDouble(GetToken(s),1.0);
SkewA.z:=StrToDouble(GetToken(s),0.0);
SkewB.x:=StrToDouble(GetToken(s),1.0);
SkewB.y:=StrToDouble(GetToken(s),0.0);
SkewB.z:=StrToDouble(GetToken(s),0.0);
SkewN2:=Vector3Norm(SkewB);
SkewA1:=Vector3ScalarMul(SkewN2,Vector3Dot(SkewA,SkewN2));
SkewA2:=Vector3Sub(SkewA,SkewA1);
SkewN1:=Vector3Norm(SkewA2);
SkewAN1:=Vector3Dot(SkewA,SkewN1);
SkewAN2:=Vector3Dot(SkewA,SkewN2);
SkewRX:=(SkewAN1*cos(SkewAngle*DEG2RAD))-(SkewAN2*sin(SkewAngle*DEG2RAD));
SkewRY:=(SkewAN1*sin(SkewAngle*DEG2RAD))+(SkewAN2*cos(SkewAngle*DEG2RAD));
if SkewRX>EPSILON then begin
if SkewAN1<EPSILON then begin
SkewAlpha:=0.0;
end else begin
SkewAlpha:=(SkewRY/SkewRX)-(SkewAN2/SkewAN1);
end;
Item^.Matrix[0,0]:=(SkewN1.x*SkewN2.x*SkewAlpha)+1.0;
Item^.Matrix[0,1]:=SkewN1.y*SkewN2.x*SkewAlpha;
Item^.Matrix[0,2]:=SkewN1.z*SkewN2.x*SkewAlpha;
Item^.Matrix[0,3]:=0.0;
Item^.Matrix[1,0]:=SkewN1.x*SkewN2.y*SkewAlpha;
Item^.Matrix[1,1]:=(SkewN1.y*SkewN2.y*SkewAlpha)+1.0;
Item^.Matrix[1,2]:=SkewN1.z*SkewN2.y*SkewAlpha;
Item^.Matrix[1,3]:=0.0;
Item^.Matrix[2,0]:=SkewN1.x*SkewN2.z*SkewAlpha;
Item^.Matrix[2,1]:=SkewN1.y*SkewN2.z*SkewAlpha;
Item^.Matrix[2,2]:=(SkewN1.z*SkewN2.z*SkewAlpha)+1.0;
Item^.Matrix[2,3]:=0.0;
Item^.Matrix[2,3]:=0.0;
Item^.Matrix[3,0]:=0.0;
Item^.Matrix[3,1]:=0.0;
Item^.Matrix[3,2]:=0.0;
Item^.Matrix[3,3]:=1.0;
end else begin
Item^.Matrix:=Matrix4x4Identity;
end;
end else if XMLTag.Name='extra' then begin
CreateItem(ntEXTRA);
end else if XMLTag.Name='instance_camera' then begin
CreateItem(ntINSTANCECAMERA);
Item^.InstanceCamera:=LibraryCamerasIDStringHashMap.Values[StringReplace(XMLTag.GetParameter('url',''),'#','',[rfReplaceAll])];
end else if XMLTag.Name='instance_light' then begin
CreateItem(ntINSTANCELIGHT);
Item^.InstanceLight:=LibraryLightsIDStringHashMap.Values[StringReplace(XMLTag.GetParameter('url',''),'#','',[rfReplaceAll])];
end else if XMLTag.Name='instance_controller' then begin
CreateItem(ntINSTANCECONTROLLER);
end else if XMLTag.Name='instance_geometry' then begin
CreateItem(ntINSTANCEGEOMETRY);
Item^.InstanceGeometry:=LibraryGeometriesIDStringHashMap.Values[StringReplace(XMLTag.GetParameter('url',''),'#','',[rfReplaceAll])];
BindMaterialTag:=XMLTag.FindTag('bind_material');
if assigned(BindMaterialTag) then begin
TechniqueCommonTag:=BindMaterialTag.FindTag('technique_common');
if not assigned(TechniqueCommonTag) then begin
TechniqueCommonTag:=BindMaterialTag;
end;
Count:=0;
for XMLSubItemIndex:=0 to TechniqueCommonTag.Items.Count-1 do begin
XMLSubItem:=TechniqueCommonTag.Items[XMLSubItemIndex];
if assigned(XMLSubItem) then begin
if XMLSubItem is TXMLTag then begin
XMLSubTag:=TXMLTag(XMLSubItem);
if XMLSubTag.Name='instance_material' then begin
if (Count+1)>length(Item^.InstanceMaterials) then begin
SetLength(Item^.InstanceMaterials,(Count+1)*2);
end;
Item^.InstanceMaterials[Count].Symbol:=XMLSubTag.GetParameter('symbol');
Item^.InstanceMaterials[Count].Target:=StringReplace(XMLSubTag.GetParameter('target'),'#','',[rfReplaceAll]);
Item^.InstanceMaterials[Count].TexCoordSets:=nil;
SubCount:=0;
for XMLSubSubItemIndex:=0 to XMLSubTag.Items.Count-1 do begin
XMLSubSubItem:=TechniqueCommonTag.Items[XMLSubSubItemIndex];
if assigned(XMLSubSubItem) then begin
if XMLSubSubItem is TXMLTag then begin
XMLSubSubTag:=TXMLTag(XMLSubSubItem);
if XMLSubSubTag.Name='bind_vertex_input' then begin
if XMLSubSubTag.GetParameter('input_semantic')='TEXCOORD' then begin
if (SubCount+1)>length(Item^.InstanceMaterials[Count].TexCoordSets) then begin
SetLength(Item^.InstanceMaterials[Count].TexCoordSets,(SubCount+1)*2);
end;
Item^.InstanceMaterials[Count].TexCoordSets[SubCount].Semantic:=XMLSubSubTag.GetParameter('semantic');
Item^.InstanceMaterials[Count].TexCoordSets[SubCount].InputSet:=StrToIntDef(XMLSubSubTag.GetParameter('input_set'),0);
inc(SubCount);
end;
end;
end;
end;
end;
if SubCount=0 then begin
if (SubCount+1)>length(Item^.InstanceMaterials[Count].TexCoordSets) then begin
SetLength(Item^.InstanceMaterials[Count].TexCoordSets,(SubCount+1)*2);
end;
Item^.InstanceMaterials[Count].TexCoordSets[SubCount].Semantic:='UVSET0';
Item^.InstanceMaterials[Count].TexCoordSets[SubCount].InputSet:=0;
inc(SubCount);
end;
SetLength(Item^.InstanceMaterials[Count].TexCoordSets,SubCount);
inc(Count);
end;
end;
end;
end;
SetLength(Item^.InstanceMaterials,Count);
end;
end else if XMLTag.Name='instance_node' then begin
CreateItem(ntINSTANCENODE);
Item^.InstanceNode:=StringReplace(XMLTag.GetParameter('url',''),'#','',[rfReplaceAll]);
end else begin
Item:=nil;
end;
if assigned(Item) then begin
Node^.Children.Add(Item);
end;
end;
end;
end;
end;
end;
end;
function ParseVisualSceneTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
ID:ansistring;
VisualScene:PLibraryVisualScene;
Item:PLibraryNode;
begin
result:=false;
if assigned(ParentTag) then begin
ID:=TXMLTag(ParentTag).GetParameter('id','');
if length(ID)>0 then begin
GetMem(VisualScene,SizeOf(TLibraryVisualScene));
FillChar(VisualScene^,SizeOf(TLibraryVisualScene),AnsiChar(#0));
VisualScene^.Next:=LibraryVisualScenes;
LibraryVisualScenes:=VisualScene;
VisualScene^.ID:=ID;
VisualScene^.Items:=TList.Create;
LibraryVisualScenesIDStringHashMap.Add(ID,VisualScene);
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='node' then begin
Item:=ParseNodeTag(XMLTag);
if assigned(Item) then begin
VisualScene^.Items.Add(Item);
end;
end;
end;
end;
end;
result:=true;
end;
end;
end;
function ParseLibraryVisualScenesTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='visual_scene' then begin
ParseVisualSceneTag(XMLTag);
end;
end;
end;
end;
result:=true;
end;
end;
function ParseInstanceVisualSceneTag(ParentTag:TXMLTag):boolean;
var URL:ansistring;
begin
result:=false;
if assigned(ParentTag) then begin
URL:=StringReplace(ParentTag.GetParameter('url','#visual_scene0'),'#','',[rfReplaceAll]);
MainVisualScene:=LibraryVisualScenesIDStringHashMap.Values[URL];
result:=true;
end;
end;
function ParseSceneTag(ParentTag:TXMLTag):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentTag) then begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='instance_visual_scene' then begin
ParseInstanceVisualSceneTag(XMLTag);
end;
end;
end;
end;
result:=true;
end;
end;
function ParseCOLLADATag(ParentTag:TXMLTag):boolean;
var PassIndex,XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
Material:PLibraryMaterial;
begin
result:=false;
if assigned(ParentTag) then begin
COLLADAVersion:=ParentTag.GetParameter('version',COLLADAVersion);
for PassIndex:=0 to 10 do begin
for XMLItemIndex:=0 to ParentTag.Items.Count-1 do begin
XMLItem:=ParentTag.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if (PassIndex=0) and (XMLTag.Name='asset') then begin
ParseAssetTag(XMLTag);
end else if (PassIndex=1) and (XMLTag.Name='library_images') then begin
ParseLibraryImagesTag(XMLTag);
end else if (PassIndex=2) and (XMLTag.Name='library_materials') then begin
ParseLibraryMaterialsTag(XMLTag);
end else if (PassIndex=3) and (XMLTag.Name='library_effects') then begin
ParseLibraryEffectsTag(XMLTag);
end else if (PassIndex=4) and (XMLTag.Name='library_geometries') then begin
ParseLibraryGeometriesTag(XMLTag);
end else if (PassIndex=5) and (XMLTag.Name='library_cameras') then begin
ParseLibraryCamerasTag(XMLTag);
end else if (PassIndex=6) and (XMLTag.Name='library_lights') then begin
ParseLibraryLightsTag(XMLTag);
end else if (PassIndex=7) and (XMLTag.Name='library_controllers') then begin
ParseLibraryControllersTag(XMLTag);
end else if (PassIndex=8) and (XMLTag.Name='library_animations') then begin
ParseLibraryAnimationsTag(XMLTag);
end else if (PassIndex=9) and (XMLTag.Name='library_visual_scenes') then begin
ParseLibraryVisualScenesTag(XMLTag);
end else if (PassIndex=10) and (XMLTag.Name='scene') then begin
ParseSceneTag(XMLTag);
end;
end;
end;
end;
case PassIndex of
3:begin
Material:=LibraryMaterials;
while assigned(Material) do begin
Material^.Effect:=LibraryEffectsIDStringHashMap.Values[Material^.EffectURL];
Material:=Material^.Next;
end;
end;
end;
end;
result:=true;
end;
end;
function ParseRoot(ParentItem:TXMLItem):boolean;
var XMLItemIndex:longint;
XMLItem:TXMLItem;
XMLTag:TXMLTag;
begin
result:=false;
if assigned(ParentItem) then begin
for XMLItemIndex:=0 to ParentItem.Items.Count-1 do begin
XMLItem:=ParentItem.Items[XMLItemIndex];
if assigned(XMLItem) then begin
if XMLItem is TXMLTag then begin
XMLTag:=TXMLTag(XMLItem);
if XMLTag.Name='COLLADA' then begin
ParseCOLLADATag(XMLTag);
end;
end;
end;
end;
result:=true;
end;
end;
function ConvertNode(Node:PLibraryNode;var Matrix:TMatrix4x4;Name:ansistring):boolean;
const stPOSITION=0;
stNORMAL=1;
stTANGENT=2;
stBITANGENT=3;
stTEXCOORD=4;
stCOLOR=5;
type TVectorArray=record
Vectors:array of TVector4;
Count:longint;
end;
procedure ConvertVectorSource(Source:PLibrarySource;var Target:TVectorArray;SourceType:longint);
var Index,CountParams,Offset,Stride,DataSize,DataIndex,DataCount:longint;
Mapping:array[0..3] of longint;
Param:PLibrarySourceAccessorParam;
SourceData:PLibrarySourceData;
v:PVector4;
begin
if assigned(Source) then begin
Mapping[0]:=-1;
Mapping[1]:=-1;
Mapping[2]:=-1;
Mapping[3]:=-1;
CountParams:=length(Source^.Accessor.Params);
Offset:=Source^.Accessor.Offset;
if Offset>0 then begin
end;
Stride:=Source^.Accessor.Stride;
if Stride>0 then begin
if CountParams>0 then begin
for Index:=0 to CountParams-1 do begin
Param:=@Source^.Accessor.Params[Index];
if Param^.ParamType in [aptINT,aptFLOAT] then begin
if BadAccessor and (length(Param^.ParamName)=0) then begin
if (Index>=0) and (Index<=3) then begin
Mapping[Index]:=Index;
end;
end else if ((SourceType in [stPOSITION,stNORMAL,stTANGENT,stBITANGENT]) and (Param^.ParamName='X')) or
((SourceType in [stTEXCOORD]) and ((Param^.ParamName='X') or (Param^.ParamName='U') or (Param^.ParamName='S'))) or
((SourceType in [stCOLOR]) and ((Param^.ParamName='X') or (Param^.ParamName='R'))) then begin
Mapping[0]:=Index;
end else if ((SourceType in [stPOSITION,stNORMAL,stTANGENT,stBITANGENT]) and (Param^.ParamName='Y')) or
((SourceType in [stTEXCOORD]) and ((Param^.ParamName='Y') or (Param^.ParamName='V') or (Param^.ParamName='T'))) or
((SourceType in [stCOLOR]) and ((Param^.ParamName='Y') or (Param^.ParamName='G'))) then begin
Mapping[1]:=Index;
end else if ((SourceType in [stPOSITION,stNORMAL,stTANGENT,stBITANGENT]) and (Param^.ParamName='Z')) or
((SourceType in [stTEXCOORD]) and ((Param^.ParamName='Z') or (Param^.ParamName='W') or (Param^.ParamName='R'))) or
((SourceType in [stCOLOR]) and ((Param^.ParamName='Z') or (Param^.ParamName='B'))) then begin
Mapping[2]:=Index;
end else if ((SourceType in [stPOSITION,stNORMAL,stTANGENT,stBITANGENT]) and (Param^.ParamName='W')) or
((SourceType in [stCOLOR]) and ((Param^.ParamName='W') or (Param^.ParamName='A'))) then begin
Mapping[3]:=Index;
end;
end;
end;
end;
SourceData:=LibrarySourceDatasIDStringHashMap.Values[Source^.Accessor.Source];
if not assigned(SourceData) then begin
if Source^.SourceDatas.Count>0 then begin
SourceData:=Source^.SourceDatas.Items[0];
end;
end;
if assigned(SourceData) and (SourceData^.SourceType in [lstBOOL,lstINT,lstFLOAT]) then begin
DataSize:=length(SourceData^.Data);
DataCount:=DataSize div Stride;
SetLength(Target.Vectors,DataCount);
DataCount:=0;
DataIndex:=0;
while (DataIndex+(Stride-1))<DataSize do begin
v:=@Target.Vectors[DataCount];
for Index:=0 to 3 do begin
if Mapping[Index]>=0 then begin
v.xyzw[Index]:=SourceData^.Data[DataIndex+Mapping[Index]];
end else begin
v.xyzw[Index]:=0.0;
end;
end;
inc(DataCount);
inc(DataIndex,Stride);
end;
SetLength(Target.Vectors,DataCount);
Target.Count:=DataCount;
end;
end;
end;
end;
var Index,InputIndex,SubInputIndex,TexcoordSetIndex:longint;
NodeMatrix,RotationMatrix:TMatrix4x4;
Light:PDAELight;
RemappedMaterials,RemappedInstanceMaterials:TStringHashMap;
InstanceMaterial:PInstanceMaterial;
LibraryMaterial:PLibraryMaterial;
LibraryGeometryMesh:PLibraryGeometryMesh;
Positions,Normals,Tangents,Bitangents,Colors:TVectorArray;
PositionOffset,NormalOffset,TangentOffset,BitangentOffset,ColorOffset,
IndicesIndex,IndicesCount,CountOffsets,VCountIndex,
VertexIndex,VCount,ItemIndex,IndicesMeshIndex,VerticesCount,VertexSubCount,
ArrayIndex,BaseIndex,CountTexCoords:longint;
TexCoords:array[0..dlMAXTEXCOORDSETS-1] of TVectorArray;
TexCoordOffsets:array[0..dlMAXTEXCOORDSETS-1] of longint;
Input,SubInput:PInput;
LibraryVertices:PLibraryVertices;
LibrarySource:PLibrarySource;
VerticesArray:TDAEVerticesArray;
Camera:PDAECamera;
Geometry:TDAEGeometry;
Mesh:TDAEMesh;
HasNormals,HasTangents:boolean;
begin
result:=false;
VerticesArray:=nil;
Positions.Vectors:=nil;
Positions.Count:=0;
Normals.Vectors:=nil;
Normals.Count:=0;
Tangents.Vectors:=nil;
Tangents.Count:=0;
Bitangents.Vectors:=nil;
Bitangents.Count:=0;
Colors.Vectors:=nil;
Colors.Count:=0;
for TexCoordSetIndex:=0 to dlMAXTEXCOORDSETS-1 do begin
TexCoords[TexCoordSetIndex].Vectors:=nil;
TexCoords[TexCoordSetIndex].Count:=0;
end;
try
if assigned(Node) then begin
case Node^.NodeType of
ntNODE:begin
if length(Name)>0 then begin
Name:=Name+'/'+Node^.Name;
end else begin
Name:=Node^.Name;
end;
NodeMatrix:=Matrix;
for Index:=0 to Node^.Children.Count-1 do begin
ConvertNode(Node^.Children[Index],NodeMatrix,Name);
end;
end;
ntROTATE,
ntTRANSLATE,
ntSCALE,
ntMATRIX,
ntLOOKAT,
ntSKEW:begin
Matrix:=Matrix4x4TermMul(Node^.Matrix,Matrix);
end;
ntEXTRA:begin
end;
ntINSTANCECAMERA:begin
if assigned(Node^.InstanceCamera) then begin
Index:=CountCameras;
inc(CountCameras);
if CountCameras>=length(Cameras) then begin
SetLength(Cameras,CountCameras*2);
end;
Camera:=@Cameras[Index];
Camera^:=Node^.InstanceCamera^.Camera;
if length(Name)<>0 then begin
if (length(Node^.InstanceCamera^.Name)<>0) and (Name<>Node^.InstanceCamera^.Name) then begin
Camera^.Name:=Name+'/'+Node^.InstanceCamera^.Name;
end else begin
Camera^.Name:=Name;
end;
end else begin
Camera^.Name:=Node^.InstanceCamera^.Name;
end;
Camera^.Matrix:=Matrix4x4TermMul(Matrix,AxisMatrix);
end;
end;
ntINSTANCELIGHT:begin
if assigned(Node^.InstanceLight) then begin
Index:=CountLights;
inc(CountLights);
if CountLights>=length(Lights) then begin
SetLength(Lights,CountLights*2);
end;
Light:=@Lights[Index];
if length(Name)<>0 then begin
if (length(Node^.InstanceLight^.Name)<>0) and (Name<>Node^.InstanceLight^.Name) then begin
Light^.Name:=Name+'/'+Node^.InstanceLight^.Name;
end else begin
Light^.Name:=Name;
end;
end else begin
Light^.Name:=Node^.InstanceLight^.Name;
end;
case Node^.InstanceLight^.LightType of
ltAMBIENT:begin
Light^.LightType:=dlltAMBIENT;
Light^.Position:=Vector3TermMatrixMul(Vector3TermMatrixMul(Vector3Origin,Matrix),AxisMatrix);
Light^.Color:=Node^.InstanceLight^.Color;
Light^.ConstantAttenuation:=Node^.InstanceLight^.ConstantAttenuation;
Light^.LinearAttenuation:=Node^.InstanceLight^.LinearAttenuation;
Light^.QuadraticAttenuation:=Node^.InstanceLight^.QuadraticAttenuation;
end;
ltDIRECTIONAL:begin
Light^.LightType:=dlltDIRECTIONAL;
Light^.Position:=Vector3TermMatrixMul(Vector3TermMatrixMul(Vector3Origin,Matrix),AxisMatrix);
Light^.Color:=Node^.InstanceLight^.Color;
Light^.Direction:=Vector3Norm(Vector3Sub(Vector3TermMatrixMul(Vector3TermMatrixMul(Vector3(0.0,0.0,-1.0),Matrix),AxisMatrix),Light^.Position));
Light^.ConstantAttenuation:=Node^.InstanceLight^.ConstantAttenuation;
Light^.LinearAttenuation:=Node^.InstanceLight^.LinearAttenuation;
Light^.QuadraticAttenuation:=Node^.InstanceLight^.QuadraticAttenuation;
end;
ltPOINT:begin
Light^.LightType:=dlltPOINT;
Light^.Position:=Vector3TermMatrixMul(Vector3TermMatrixMul(Vector3Origin,Matrix),AxisMatrix);
Light^.Color:=Node^.InstanceLight^.Color;
Light^.ConstantAttenuation:=Node^.InstanceLight^.ConstantAttenuation;
Light^.LinearAttenuation:=Node^.InstanceLight^.LinearAttenuation;
Light^.QuadraticAttenuation:=Node^.InstanceLight^.QuadraticAttenuation;
end;
ltSPOT:begin
Light^.LightType:=dlltSPOT;
Light^.Position:=Vector3TermMatrixMul(Vector3TermMatrixMul(Vector3Origin,Matrix),AxisMatrix);
Light^.Color:=Node^.InstanceLight^.Color;
Light^.Direction:=Vector3Norm(Vector3Sub(Vector3TermMatrixMul(Vector3TermMatrixMul(Vector3(0.0,0.0,-1.0),Matrix),AxisMatrix),Light^.Position));
Light^.FallOffAngle:=Node^.InstanceLight^.FallOffAngle;
Light^.FallOffExponent:=Node^.InstanceLight^.FallOffExponent;
Light^.ConstantAttenuation:=Node^.InstanceLight^.ConstantAttenuation;
Light^.LinearAttenuation:=Node^.InstanceLight^.LinearAttenuation;
Light^.QuadraticAttenuation:=Node^.InstanceLight^.QuadraticAttenuation;
end;
end;
end;
end;
ntINSTANCECONTROLLER:begin
end;
ntINSTANCEGEOMETRY:begin
if assigned(Node^.InstanceGeometry) then begin
RotationMatrix:=Matrix4x4Rotation(Matrix);
Geometry:=TDAEGeometry.Create;
Geometry.Name:=Name;
Geometries.Add(Geometry);
RemappedMaterials:=TStringHashMap.Create;
RemappedInstanceMaterials:=TStringHashMap.Create;
try
for Index:=0 to length(Node^.InstanceMaterials)-1 do begin
LibraryMaterial:=LibraryMaterialsIDStringHashMap.Values[Node^.InstanceMaterials[Index].Target];
if assigned(LibraryMaterial) then begin
RemappedMaterials.Add(Node^.InstanceMaterials[Index].Symbol,LibraryMaterial);
RemappedInstanceMaterials.Add(Node^.InstanceMaterials[Index].Symbol,@Node^.InstanceMaterials[Index]);
end;
end;
for Index:=0 to length(Node^.InstanceGeometry.Meshs)-1 do begin
LibraryGeometryMesh:=@Node^.InstanceGeometry.Meshs[Index];
if length(LibraryGeometryMesh^.Indices)>0 then begin
SetLength(Positions.Vectors,0);
Positions.Count:=0;
SetLength(Normals.Vectors,0);
Normals.Count:=0;
SetLength(Tangents.Vectors,0);
Tangents.Count:=0;
SetLength(Bitangents.Vectors,0);
Bitangents.Count:=0;
SetLength(Colors.Vectors,0);
Colors.Count:=0;
for TexCoordSetIndex:=0 to dlMAXTEXCOORDSETS-1 do begin
SetLength(TexCoords[TexCoordSetIndex].Vectors,0);
TexCoords[TexCoordSetIndex].Count:=0;
end;
PositionOffset:=-1;
NormalOffset:=-1;
TangentOffset:=-1;
BitangentOffset:=-1;
ColorOffset:=-1;
for TexCoordSetIndex:=0 to dlMAXTEXCOORDSETS-1 do begin
TexCoordOffsets[TexCoordSetIndex]:=-1;
end;
CountTexCoords:=0;
CountOffsets:=0;
for InputIndex:=0 to length(LibraryGeometryMesh^.Inputs)-1 do begin
Input:=@LibraryGeometryMesh^.Inputs[InputIndex];
CountOffsets:=Max(CountOffsets,Input^.Offset+1);
LibrarySource:=nil;
if Input^.Semantic='VERTEX' then begin
LibraryVertices:=LibraryVerticesesIDStringHashMap.Values[Input^.Source];
if assigned(LibraryVertices) then begin
for SubInputIndex:=0 to length(LibraryVertices^.Inputs)-1 do begin
SubInput:=@LibraryVertices^.Inputs[SubInputIndex];
if SubInput^.Semantic='POSITION' then begin
PositionOffset:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[SubInput^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,Positions,stPOSITION);
end;
end else if SubInput^.Semantic='NORMAL' then begin
NormalOffset:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[SubInput^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,Normals,stNORMAL);
end;
end else if SubInput^.Semantic='TANGENT' then begin
TangentOffset:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[SubInput^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,Tangents,stTANGENT);
end;
end else if (SubInput^.Semantic='BINORMAL') or (SubInput^.Semantic='BITANGENT') then begin
BitangentOffset:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[SubInput^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,Bitangents,stBITANGENT);
end;
end else if SubInput^.Semantic='TEXCOORD' then begin
if (SubInput^.Set_>=0) and (SubInput^.Set_<dlMAXTEXCOORDSETS) then begin
CountTexCoords:=Max(CountTexCoords,SubInput^.Set_+1);
TexCoordOffsets[SubInput^.Set_]:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[SubInput^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,TexCoords[SubInput^.Set_],stTEXCOORD);
end;
end;
end else if SubInput^.Semantic='COLOR' then begin
ColorOffset:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[SubInput^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,Colors,stCOLOR);
end;
end;
end;
end;
end else if Input^.Semantic='POSITION' then begin
PositionOffset:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[Input^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,Positions,stPOSITION);
end;
end else if Input^.Semantic='NORMAL' then begin
NormalOffset:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[Input^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,Normals,stNORMAL);
end;
end else if Input^.Semantic='TANGENT' then begin
TangentOffset:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[Input^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,Tangents,stTANGENT);
end;
end else if (Input^.Semantic='BINORMAL') or (Input^.Semantic='BITANGENT') then begin
BitangentOffset:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[Input^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,Bitangents,stBITANGENT);
end;
end else if Input^.Semantic='TEXCOORD' then begin
if (Input^.Set_>=0) and (Input^.Set_<dlMAXTEXCOORDSETS) then begin
CountTexCoords:=Max(CountTexCoords,Input^.Set_+1);
TexCoordOffsets[Input^.Set_]:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[Input^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,TexCoords[Input^.Set_],stTEXCOORD);
end;
end;
end else if Input^.Semantic='COLOR' then begin
ColorOffset:=Input^.Offset;
LibrarySource:=LibrarySourcesIDStringHashMap.Values[Input^.Source];
if assigned(LibrarySource) then begin
ConvertVectorSource(LibrarySource,Colors,stCOLOR);
end;
end;
end;
if CountOffsets>0 then begin
for IndicesMeshIndex:=0 to length(LibraryGeometryMesh^.Indices)-1 do begin
if length(LibraryGeometryMesh^.Indices[IndicesMeshIndex])>0 then begin
HasNormals:=false;
HasTangents:=false;
VCountIndex:=0;
IndicesIndex:=0;
IndicesCount:=length(LibraryGeometryMesh.Indices[IndicesMeshIndex]);
SetLength(VerticesArray,IndicesCount);
VerticesCount:=0;
while IndicesIndex<IndicesCount do begin
if (LibraryGeometryMesh^.MeshType=mtPOLYLIST) and
((VCountIndex>=0) and (VCountIndex<length(LibraryGeometryMesh^.VCounts))) then begin
VCount:=LibraryGeometryMesh^.VCounts[VCountIndex];
inc(VCountIndex);
end else begin
case LibraryGeometryMesh^.MeshType of
mtTRIANGLES:begin
VCount:=3;
end;
mtTRIFANS:begin
VCount:=1;
end;
mtTRISTRIPS:begin
VCount:=1;
end;
mtPOLYGONS:begin
VCount:=1;
end;
mtPOLYLIST:begin
VCount:=IndicesCount div CountOffsets;
end;
mtLINES:begin
VCount:=2;
end;
mtLINESTRIPS:begin
VCount:=IndicesCount div CountOffsets;
end;
else begin
VCount:=IndicesCount div CountOffsets;
end;
end;
end;
SetLength(VerticesArray[VerticesCount],VCount);
FillChar(VerticesArray[VerticesCount,0],VCount*SizeOf(TDAEVertex),AnsiChar(#0));
for VertexIndex:=0 to VCount-1 do begin
VerticesArray[VerticesCount,VertexIndex].Position:=Vector3Origin;
VerticesArray[VerticesCount,VertexIndex].Normal:=Vector3Origin;
VerticesArray[VerticesCount,VertexIndex].Tangent:=Vector3Origin;
VerticesArray[VerticesCount,VertexIndex].Bitangent:=Vector3Origin;
for TexCoordSetIndex:=0 to dlMAXTEXCOORDSETS-1 do begin
VerticesArray[VerticesCount,VertexIndex].TexCoords[TexCoordSetIndex]:=Vector2Origin;
end;
VerticesArray[VerticesCount,VertexIndex].CountTexCoords:=CountTexCoords;
VerticesArray[VerticesCount,VertexIndex].Color.x:=1.0;
VerticesArray[VerticesCount,VertexIndex].Color.y:=1.0;
VerticesArray[VerticesCount,VertexIndex].Color.z:=1.0;
BaseIndex:=IndicesIndex+(VertexIndex*CountOffsets);
if PositionOffset>=0 then begin
ArrayIndex:=BaseIndex+PositionOffset;
if (ArrayIndex>=0) and (ArrayIndex<length(LibraryGeometryMesh^.Indices[IndicesMeshIndex])) then begin
ItemIndex:=LibraryGeometryMesh^.Indices[IndicesMeshIndex,ArrayIndex];
if (ItemIndex>=0) and (ItemIndex<Positions.Count) then begin
VerticesArray[VerticesCount,VertexIndex].Position.x:=Positions.Vectors[ItemIndex].x;
VerticesArray[VerticesCount,VertexIndex].Position.y:=Positions.Vectors[ItemIndex].y;
VerticesArray[VerticesCount,VertexIndex].Position.z:=Positions.Vectors[ItemIndex].z;
end;
end;
end;
if NormalOffset>=0 then begin
ArrayIndex:=BaseIndex+NormalOffset;
if (ArrayIndex>=0) and (ArrayIndex<length(LibraryGeometryMesh^.Indices[IndicesMeshIndex])) then begin
ItemIndex:=LibraryGeometryMesh^.Indices[IndicesMeshIndex,ArrayIndex];
if (ItemIndex>=0) and (ItemIndex<Normals.Count) then begin
VerticesArray[VerticesCount,VertexIndex].Normal.x:=Normals.Vectors[ItemIndex].x;
VerticesArray[VerticesCount,VertexIndex].Normal.y:=Normals.Vectors[ItemIndex].y;
VerticesArray[VerticesCount,VertexIndex].Normal.z:=Normals.Vectors[ItemIndex].z;
HasNormals:=true;
end;
end;
end;
if TangentOffset>=0 then begin
ArrayIndex:=BaseIndex+TangentOffset;
if (ArrayIndex>=0) and (ArrayIndex<length(LibraryGeometryMesh^.Indices[IndicesMeshIndex])) then begin
ItemIndex:=LibraryGeometryMesh^.Indices[IndicesMeshIndex,ArrayIndex];
if (ItemIndex>=0) and (ItemIndex<Tangents.Count) then begin
VerticesArray[VerticesCount,VertexIndex].Tangent.x:=Tangents.Vectors[ItemIndex].x;
VerticesArray[VerticesCount,VertexIndex].Tangent.y:=Tangents.Vectors[ItemIndex].y;
VerticesArray[VerticesCount,VertexIndex].Tangent.z:=Tangents.Vectors[ItemIndex].z;
HasTangents:=true;
end;
end;
end;
if BitangentOffset>=0 then begin
ArrayIndex:=BaseIndex+BitangentOffset;
if (ArrayIndex>=0) and (ArrayIndex<length(LibraryGeometryMesh^.Indices[IndicesMeshIndex])) then begin
ItemIndex:=LibraryGeometryMesh^.Indices[IndicesMeshIndex,ArrayIndex];
if (ItemIndex>=0) and (ItemIndex<Bitangents.Count) then begin
VerticesArray[VerticesCount,VertexIndex].Bitangent.x:=Bitangents.Vectors[ItemIndex].x;
VerticesArray[VerticesCount,VertexIndex].Bitangent.y:=Bitangents.Vectors[ItemIndex].y;
VerticesArray[VerticesCount,VertexIndex].Bitangent.z:=Bitangents.Vectors[ItemIndex].z;
HasTangents:=true;
end;
end;
end;
for TexCoordSetIndex:=0 to dlMAXTEXCOORDSETS-1 do begin
if TexCoordOffsets[TexCoordSetIndex]>=0 then begin
ArrayIndex:=BaseIndex+TexCoordOffsets[TexCoordSetIndex];
if (ArrayIndex>=0) and (ArrayIndex<length(LibraryGeometryMesh^.Indices[IndicesMeshIndex])) then begin
ItemIndex:=LibraryGeometryMesh^.Indices[IndicesMeshIndex,ArrayIndex];
if (ItemIndex>=0) and (ItemIndex<TexCoords[TexCoordSetIndex].Count) then begin
VerticesArray[VerticesCount,VertexIndex].CountTexCoords:=Max(VerticesArray[VerticesCount,VertexIndex].CountTexCoords,TexCoordSetIndex+1);
VerticesArray[VerticesCount,VertexIndex].TexCoords[TexCoordSetIndex].x:=TexCoords[TexCoordSetIndex].Vectors[ItemIndex].x;
VerticesArray[VerticesCount,VertexIndex].TexCoords[TexCoordSetIndex].y:=1.0-TexCoords[TexCoordSetIndex].Vectors[ItemIndex].y;
end;
end;
end;
end;
if ColorOffset>=0 then begin
ArrayIndex:=BaseIndex+ColorOffset;
if (ArrayIndex>=0) and (ArrayIndex<length(LibraryGeometryMesh^.Indices[IndicesMeshIndex])) then begin
ItemIndex:=LibraryGeometryMesh^.Indices[IndicesMeshIndex,ArrayIndex];
if (ItemIndex>=0) and (ItemIndex<Colors.Count) then begin
VerticesArray[VerticesCount,VertexIndex].Color.x:=Colors.Vectors[ItemIndex].x;
VerticesArray[VerticesCount,VertexIndex].Color.y:=Colors.Vectors[ItemIndex].y;
VerticesArray[VerticesCount,VertexIndex].Color.z:=Colors.Vectors[ItemIndex].z;
end;
end;
end;
Vector3MatrixMul(VerticesArray[VerticesCount,VertexIndex].Position,Matrix);
Vector3MatrixMul(VerticesArray[VerticesCount,VertexIndex].Normal,RotationMatrix);
Vector3MatrixMul(VerticesArray[VerticesCount,VertexIndex].Tangent,RotationMatrix);
Vector3MatrixMul(VerticesArray[VerticesCount,VertexIndex].Bitangent,RotationMatrix);
Vector3MatrixMul(VerticesArray[VerticesCount,VertexIndex].Position,AxisMatrix);
Vector3MatrixMul(VerticesArray[VerticesCount,VertexIndex].Normal,AxisMatrix);
Vector3MatrixMul(VerticesArray[VerticesCount,VertexIndex].Tangent,AxisMatrix);
Vector3MatrixMul(VerticesArray[VerticesCount,VertexIndex].Bitangent,AxisMatrix);
Vector3Normalize(VerticesArray[VerticesCount,VertexIndex].Normal);
Vector3Normalize(VerticesArray[VerticesCount,VertexIndex].Tangent);
Vector3Normalize(VerticesArray[VerticesCount,VertexIndex].Bitangent);
end;
inc(VerticesCount);
inc(IndicesIndex,CountOffsets*VCount);
end;
SetLength(VerticesArray,VerticesCount);
if VerticesCount>0 then begin
case LibraryGeometryMesh^.MeshType of
mtTRIANGLES:begin
Mesh:=TDAEMesh.Create;
Geometry.Add(Mesh);
Mesh.MeshType:=dlmtTRIANGLES;
Mesh.TexCoordSets:=nil;
LibraryMaterial:=RemappedMaterials.Values[LibraryGeometryMesh^.Material];
if assigned(LibraryMaterial) then begin
Mesh.MaterialIndex:=LibraryMaterial^.Index;
InstanceMaterial:=RemappedInstanceMaterials.Values[LibraryGeometryMesh^.Material];
if assigned(InstanceMaterial) then begin
SetLength(Mesh.TexCoordSets,length(InstanceMaterial^.TexCoordSets));
for TexCoordSetIndex:=0 to length(InstanceMaterial^.TexCoordSets)-1 do begin
Mesh.TexCoordSets[TexCoordSetIndex].Semantic:=InstanceMaterial^.TexCoordSets[TexCoordSetIndex].Semantic;
Mesh.TexCoordSets[TexCoordSetIndex].InputSet:=InstanceMaterial^.TexCoordSets[TexCoordSetIndex].InputSet;
end;
end;
end else begin
Mesh.MaterialIndex:=-1;
end;
SetLength(Mesh.Vertices,VerticesCount*3);
SetLength(Mesh.Indices,VerticesCount*3);
for BaseIndex:=0 to VerticesCount-1 do begin
Mesh.Vertices[(BaseIndex*3)+0]:=VerticesArray[BaseIndex,0];
Mesh.Vertices[(BaseIndex*3)+1]:=VerticesArray[BaseIndex,1];
Mesh.Vertices[(BaseIndex*3)+2]:=VerticesArray[BaseIndex,2];
Mesh.Indices[(BaseIndex*3)+0]:=(BaseIndex*3)+0;
Mesh.Indices[(BaseIndex*3)+1]:=(BaseIndex*3)+1;
Mesh.Indices[(BaseIndex*3)+2]:=(BaseIndex*3)+2;
end;
Mesh.Optimize;
Mesh.CalculateMissingInformations(not HasNormals,not HasTangents);
Mesh.Optimize;
end;
mtTRIFANS:begin
Mesh:=TDAEMesh.Create;
Geometry.Add(Mesh);
LibraryMaterial:=RemappedMaterials.Values[LibraryGeometryMesh^.Material];
Mesh.MeshType:=dlmtTRIANGLES;
if assigned(LibraryMaterial) then begin
Mesh.MaterialIndex:=LibraryMaterial^.Index;
end else begin
Mesh.MaterialIndex:=-1;
end;
SetLength(Mesh.Vertices,VerticesCount);
for BaseIndex:=0 to VerticesCount-1 do begin
Mesh.Vertices[BaseIndex]:=VerticesArray[BaseIndex,0];
end;
SetLength(Mesh.Indices,VerticesCount*3);
IndicesCount:=0;
for BaseIndex:=0 to VerticesCount-3 do begin
Mesh.Indices[IndicesCount+0]:=0;
Mesh.Indices[IndicesCount+1]:=BaseIndex+1;
Mesh.Indices[IndicesCount+2]:=BaseIndex+2;
inc(IndicesCount,3);
end;
SetLength(Mesh.Indices,IndicesCount);
Mesh.Optimize;
Mesh.CalculateMissingInformations(not HasNormals,not HasTangents);
Mesh.Optimize;
end;
mtTRISTRIPS:begin
Mesh:=TDAEMesh.Create;
Geometry.Add(Mesh);
LibraryMaterial:=RemappedMaterials.Values[LibraryGeometryMesh^.Material];
Mesh.MeshType:=dlmtTRIANGLES;
if assigned(LibraryMaterial) then begin
Mesh.MaterialIndex:=LibraryMaterial^.Index;
end else begin
Mesh.MaterialIndex:=-1;
end;
SetLength(Mesh.Vertices,VerticesCount);
for BaseIndex:=0 to VerticesCount-1 do begin
Mesh.Vertices[BaseIndex]:=VerticesArray[BaseIndex,0];
end;
SetLength(Mesh.Indices,VerticesCount*3);
IndicesCount:=0;
for BaseIndex:=0 to VerticesCount-3 do begin
if (BaseIndex and 1)<>0 then begin
Mesh.Indices[IndicesCount+0]:=BaseIndex;
Mesh.Indices[IndicesCount+1]:=BaseIndex+2;
Mesh.Indices[IndicesCount+2]:=BaseIndex+1;
end else begin
Mesh.Indices[IndicesCount+0]:=BaseIndex;
Mesh.Indices[IndicesCount+1]:=BaseIndex+1;
Mesh.Indices[IndicesCount+2]:=BaseIndex+2;
end;
inc(IndicesCount,3);
end;
SetLength(Mesh.Indices,IndicesCount);
Mesh.Optimize;
Mesh.CalculateMissingInformations(not HasNormals,not HasTangents);
Mesh.Optimize;
end;
mtPOLYGONS:begin
Mesh:=TDAEMesh.Create;
Geometry.Add(Mesh);
LibraryMaterial:=RemappedMaterials.Values[LibraryGeometryMesh^.Material];
Mesh.MeshType:=dlmtTRIANGLES;
if assigned(LibraryMaterial) then begin
Mesh.MaterialIndex:=LibraryMaterial^.Index;
end else begin
Mesh.MaterialIndex:=-1;
end;
SetLength(Mesh.Vertices,VerticesCount);
for BaseIndex:=0 to VerticesCount-1 do begin
Mesh.Vertices[BaseIndex]:=VerticesArray[BaseIndex,0];
end;
SetLength(Mesh.Indices,VerticesCount*3);
IndicesCount:=0;
for BaseIndex:=0 to VerticesCount-3 do begin
Mesh.Indices[IndicesCount+0]:=0;
Mesh.Indices[IndicesCount+1]:=BaseIndex+1;
Mesh.Indices[IndicesCount+2]:=BaseIndex+2;
inc(IndicesCount,3);
end;
SetLength(Mesh.Indices,IndicesCount);
Mesh.Optimize;
Mesh.CalculateMissingInformations(not HasNormals,not HasTangents);
Mesh.Optimize;
end;
mtPOLYLIST:begin
Mesh:=TDAEMesh.Create;
Geometry.Add(Mesh);
LibraryMaterial:=RemappedMaterials.Values[LibraryGeometryMesh^.Material];
Mesh.MeshType:=dlmtTRIANGLES;
if assigned(LibraryMaterial) then begin
Mesh.MaterialIndex:=LibraryMaterial^.Index;
end else begin
Mesh.MaterialIndex:=-1;
end;
VCount:=0;
for BaseIndex:=0 to VerticesCount-1 do begin
inc(VCount,length(VerticesArray[BaseIndex]));
end;
SetLength(Mesh.Vertices,VCount+2);
SetLength(Mesh.Indices,(VCount+2)*3);
VCount:=0;
IndicesCount:=0;
for BaseIndex:=0 to VerticesCount-1 do begin
VertexSubCount:=length(VerticesArray[BaseIndex]);
if (VCount+VertexSubCount)>length(Mesh.Indices) then begin
SetLength(Mesh.Vertices,NextPowerOfTwo(VCount+VertexSubCount));
end;
for ArrayIndex:=0 to VertexSubCount-1 do begin
Mesh.Vertices[VCount+ArrayIndex]:=VerticesArray[BaseIndex,ArrayIndex];
end;
for ArrayIndex:=0 to VertexSubCount-3 do begin
if (IndicesCount+3)>length(Mesh.Indices) then begin
SetLength(Mesh.Indices,NextPowerOfTwo(IndicesCount+3));
end;
Mesh.Indices[IndicesCount+0]:=VCount;
Mesh.Indices[IndicesCount+1]:=VCount+ArrayIndex+1;
Mesh.Indices[IndicesCount+2]:=VCount+ArrayIndex+2;
inc(IndicesCount,3);
end;
inc(VCount,VertexSubCount);
end;
SetLength(Mesh.Vertices,VCount);
SetLength(Mesh.Indices,IndicesCount);
Mesh.Optimize;
Mesh.CalculateMissingInformations(not HasNormals,not HasTangents);
Mesh.Optimize;
end;
mtLINES:begin
for BaseIndex:=0 to VerticesCount-1 do begin
Mesh:=TDAEMesh.Create;
Geometry.Add(Mesh);
Mesh.MeshType:=dlmtLINESTRIP;
LibraryMaterial:=RemappedMaterials.Values[LibraryGeometryMesh^.Material];
if assigned(LibraryMaterial) then begin
Mesh.MaterialIndex:=LibraryMaterial^.Index;
end else begin
Mesh.MaterialIndex:=-1;
end;
SetLength(Mesh.Vertices,2);
Mesh.Vertices[0]:=VerticesArray[BaseIndex,0];
Mesh.Vertices[1]:=VerticesArray[BaseIndex,1];
SetLength(Mesh.Indices,2);
Mesh.Indices[0]:=0;
Mesh.Indices[1]:=1;
Mesh.Optimize;
Mesh.CalculateMissingInformations(not HasNormals,not HasTangents);
Mesh.Optimize;
end;
end;
mtLINESTRIPS:begin
Mesh:=TDAEMesh.Create;
Geometry.Add(Mesh);
Mesh.MeshType:=dlmtLINESTRIP;
LibraryMaterial:=RemappedMaterials.Values[LibraryGeometryMesh^.Material];
if assigned(LibraryMaterial) then begin
Mesh.MaterialIndex:=LibraryMaterial^.Index;
end else begin
Mesh.MaterialIndex:=-1;
end;
if length(VerticesArray)>0 then begin
Mesh.Vertices:=copy(VerticesArray[0],0,length(VerticesArray[0]));
SetLength(Mesh.Indices,length(Mesh.Vertices));
for ArrayIndex:=0 to length(Mesh.Indices)-1 do begin
Mesh.Indices[ArrayIndex]:=ArrayIndex;
end;
Mesh.Optimize;
Mesh.CalculateMissingInformations(not HasNormals,not HasTangents);
Mesh.Optimize;
end else begin
Mesh.Vertices:=nil;
Mesh.Indices:=nil;
end;
end;
end;
end;
end;
end;
end;
end;
end;
finally
RemappedMaterials.Free;
RemappedInstanceMaterials.Free;
end;
end;
end;
ntINSTANCENODE:begin
ConvertNode(LibraryNodesIDStringHashMap.Values[Node^.InstanceNode],Matrix,Name);
end;
end;
result:=true;
end;
finally
SetLength(Positions.Vectors,0);
SetLength(Normals.Vectors,0);
SetLength(Tangents.Vectors,0);
SetLength(Bitangents.Vectors,0);
SetLength(Colors.Vectors,0);
for TexCoordSetIndex:=0 to dlMAXTEXCOORDSETS-1 do begin
SetLength(TexCoords[TexCoordSetIndex].Vectors,0);
end;
SetLength(VerticesArray,0);
end;
end;
procedure ConvertMaterials;
var LibraryMaterial:PLibraryMaterial;
Material:PDAEMaterial;
begin
LibraryMaterial:=LibraryMaterials;
while assigned(LibraryMaterial) do begin
if assigned(LibraryMaterial^.Effect) then begin
if (CountMaterials+1)>length(Materials) then begin
SetLength(Materials,(CountMaterials+1)*2);
end;
LibraryMaterial^.Index:=CountMaterials;
Material:=@Materials[CountMaterials];
FillChar(Material^,SizeOf(TDAEMaterial),AnsiChar(#0));
inc(CountMaterials);
Material^.Name:=LibraryMaterial^.Name;
Material^.ShadingType:=LibraryMaterial^.Effect^.ShadingType;
Material^.Ambient:=LibraryMaterial^.Effect^.Ambient;
Material^.Diffuse:=LibraryMaterial^.Effect^.Diffuse;
Material^.Emission:=LibraryMaterial^.Effect^.Emission;
Material^.Specular:=LibraryMaterial^.Effect^.Specular;
Material^.Transparent:=LibraryMaterial^.Effect^.Transparent;
Material^.Shininess:=LibraryMaterial^.Effect^.Shininess;
Material^.Reflectivity:=LibraryMaterial^.Effect^.Reflectivity;
Material^.IndexOfRefraction:=LibraryMaterial^.Effect^.IndexOfRefraction;
Material^.Transparency:=LibraryMaterial^.Effect^.Transparency;
end;
LibraryMaterial:=LibraryMaterial^.Next;
end;
end;
function Convert:boolean;
var Index:longint;
NodeMatrix:TMatrix4x4;
begin
result:=false;
if assigned(MainVisualScene) then begin
case UpAxis of
dluaXUP:begin
AxisMatrix:=Matrix4x4(0.0,-1.0,0.0,0.0,
1.0,0.0,0.0,0.0,
0.0,0.0,1.0,0.0,
0.0,0.0,0.0,1.0);
end;
dluaZUP:begin
AxisMatrix:=Matrix4x4(1.0,0.0,0.0,0.0,
0.0,0.0,1.0,0.0,
0.0,-1.0,0.0,0.0,
0.0,0.0,0.0,1.0);
end;
else {dluaYUP:}begin
AxisMatrix:=Matrix4x4(1.0,0.0,0.0,0.0,
0.0,1.0,0.0,0.0,
0.0,0.0,1.0,0.0,
0.0,0.0,0.0,1.0);
end;
end;
ConvertMaterials;
for Index:=0 to MainVisualScene^.Items.Count-1 do begin
NodeMatrix:=Matrix4x4Identity;
ConvertNode(MainVisualScene^.Items[Index],NodeMatrix,'');
end;
result:=true;
end;
end;
var Index:longint;
XML:TXML;
Next,SubNext:pointer;
begin
result:=false;
XML:=TXML.Create;
try
IDStringHashMap:=TStringHashMap.Create;
LibraryImagesIDStringHashMap:=TStringHashMap.Create;
LibraryImages:=nil;
LibraryMaterialsIDStringHashMap:=TStringHashMap.Create;
LibraryMaterials:=nil;
LibraryEffectsIDStringHashMap:=TStringHashMap.Create;
LibraryEffects:=nil;
LibrarySourcesIDStringHashMap:=TStringHashMap.Create;
LibrarySources:=nil;
LibrarySourceDatasIDStringHashMap:=TStringHashMap.Create;
LibrarySourceDatas:=nil;
LibraryVerticesesIDStringHashMap:=TStringHashMap.Create;
LibraryVerticeses:=nil;
LibraryGeometriesIDStringHashMap:=TStringHashMap.Create;
LibraryGeometries:=nil;
LibraryCamerasIDStringHashMap:=TStringHashMap.Create;
LibraryCameras:=nil;
LibraryLightsIDStringHashMap:=TStringHashMap.Create;
LibraryLights:=nil;
LibraryVisualScenesIDStringHashMap:=TStringHashMap.Create;
LibraryVisualScenes:=nil;
LibraryNodesIDStringHashMap:=TStringHashMap.Create;
LibraryNodes:=nil;
try
if XML.Read(Stream) then begin
COLLADAVersion:='1.5.0';
AuthoringTool:='';
Created:=Now;
Modified:=Now;
UnitMeter:=1.0;
UnitName:='meter';
UpAxis:=dluaYUP;
MainVisualScene:=nil;
SetLength(Lights,0);
CountLights:=0;
SetLength(Cameras,0);
CountCameras:=0;
SetLength(Materials,0);
CountMaterials:=0;
BadAccessor:=false;
FlipAngle:=false;
NegJoints:=false;
CollectIDs(XML.Root);
result:=ParseRoot(XML.Root);
if result then begin
result:=Convert;
end;
SetLength(Lights,CountLights);
SetLength(Materials,CountMaterials);
end;
finally
begin
while assigned(LibraryNodes) do begin
Next:=LibraryNodes^.Next;
LibraryNodes^.ID:='';
LibraryNodes^.Name:='';
for Index:=0 to length(LibraryNodes^.InstanceMaterials)-1 do begin
SetLength(LibraryNodes^.InstanceMaterials[Index].TexCoordSets,0);
end;
SetLength(LibraryNodes^.InstanceMaterials,0);
LibraryNodes^.InstanceNode:='';
if LibraryNodes^.NodeType=ntNODE then begin
FreeAndNil(LibraryNodes^.Children);
end;
FreeMem(LibraryNodes);
LibraryNodes:=Next;
end;
LibraryNodesIDStringHashMap.Free;
end;
begin
while assigned(LibraryVisualScenes) do begin
Next:=LibraryVisualScenes^.Next;
LibraryVisualScenes^.ID:='';
FreeAndNil(LibraryVisualScenes^.Items);
FreeMem(LibraryVisualScenes);
LibraryVisualScenes:=Next;
end;
LibraryVisualScenesIDStringHashMap.Free;
end;
begin
while assigned(LibraryCameras) do begin
Next:=LibraryCameras^.Next;
LibraryCameras^.ID:='';
LibraryCameras^.Name:='';
LibraryCameras^.Camera.Name:='';
Finalize(LibraryCameras^);
FreeMem(LibraryCameras);
LibraryCameras:=Next;
end;
LibraryCamerasIDStringHashMap.Free;
end;
begin
while assigned(LibraryLights) do begin
Next:=LibraryLights^.Next;
LibraryLights^.ID:='';
LibraryLights^.Name:='';
FreeMem(LibraryLights);
LibraryLights:=Next;
end;
LibraryLightsIDStringHashMap.Free;
end;
begin
while assigned(LibraryGeometries) do begin
Next:=LibraryGeometries^.Next;
LibraryGeometries^.ID:='';
SetLength(LibraryGeometries^.Meshs,0);
Finalize(LibraryGeometries^);
FreeMem(LibraryGeometries);
LibraryGeometries:=Next;
end;
LibraryGeometriesIDStringHashMap.Free;
end;
begin
while assigned(LibraryVerticeses) do begin
Next:=LibraryVerticeses^.Next;
LibraryVerticeses^.ID:='';
SetLength(LibraryVerticeses^.Inputs,0);
FreeMem(LibraryVerticeses);
LibraryVerticeses:=Next;
end;
LibraryVerticesesIDStringHashMap.Free;
end;
begin
while assigned(LibrarySources) do begin
Next:=LibrarySources^.Next;
LibrarySources^.ID:='';
FreeAndNil(LibrarySources^.SourceDatas);
LibrarySources^.Accessor.Source:='';
SetLength(LibrarySources^.Accessor.Params,0);
FreeMem(LibrarySources);
LibrarySources:=Next;
end;
LibrarySourcesIDStringHashMap.Free;
end;
begin
while assigned(LibrarySourceDatas) do begin
Next:=LibrarySourceDatas^.Next;
LibrarySourceDatas^.ID:='';
SetLength(LibrarySourceDatas^.Data,0);
SetLength(LibrarySourceDatas^.Strings,0);
FreeMem(LibrarySourceDatas);
LibrarySourceDatas:=Next;
end;
LibrarySourceDatasIDStringHashMap.Free;
end;
begin
while assigned(LibraryEffects) do begin
Next:=LibraryEffects^.Next;
LibraryEffects^.ID:='';
LibraryEffects^.Name:='';
while assigned(LibraryEffects^.Surfaces) do begin
SubNext:=LibraryEffects^.Surfaces^.Next;
LibraryEffects^.Surfaces^.SID:='';
LibraryEffects^.Surfaces^.InitFrom:='';
LibraryEffects^.Surfaces^.Format:='';
FreeMem(LibraryEffects^.Surfaces);
LibraryEffects^.Surfaces:=SubNext;
end;
while assigned(LibraryEffects^.Sampler2D) do begin
SubNext:=LibraryEffects^.Sampler2D^.Next;
LibraryEffects^.Sampler2D^.SID:='';
LibraryEffects^.Sampler2D^.Source:='';
LibraryEffects^.Sampler2D^.WrapS:='';
LibraryEffects^.Sampler2D^.WrapT:='';
LibraryEffects^.Sampler2D^.MinFilter:='';
LibraryEffects^.Sampler2D^.MagFilter:='';
LibraryEffects^.Sampler2D^.MipFilter:='';
Finalize(LibraryEffects^);
FreeMem(LibraryEffects^.Sampler2D);
LibraryEffects^.Sampler2D:=SubNext;
end;
while assigned(LibraryEffects^.Floats) do begin
SubNext:=LibraryEffects^.Floats^.Next;
LibraryEffects^.Floats^.SID:='';
FreeMem(LibraryEffects^.Floats);
LibraryEffects^.Floats:=SubNext;
end;
while assigned(LibraryEffects^.Float4s) do begin
SubNext:=LibraryEffects^.Float4s^.Next;
LibraryEffects^.Float4s^.SID:='';
FreeMem(LibraryEffects^.Float4s);
LibraryEffects^.Float4s:=SubNext;
end;
FreeAndNil(LibraryEffects^.Images);
FreeMem(LibraryEffects);
LibraryEffects:=Next;
end;
LibraryEffectsIDStringHashMap.Free;
end;
begin
while assigned(LibraryMaterials) do begin
Next:=LibraryMaterials^.Next;
LibraryMaterials^.ID:='';
LibraryMaterials^.Name:='';
LibraryMaterials^.EffectURL:='';
FreeMem(LibraryMaterials);
LibraryMaterials:=Next;
end;
LibraryMaterialsIDStringHashMap.Free;
end;
begin
while assigned(LibraryImages) do begin
Next:=LibraryImages^.Next;
LibraryImages^.ID:='';
LibraryImages^.InitFrom:='';
FreeMem(LibraryImages);
LibraryImages:=Next;
end;
LibraryImagesIDStringHashMap.Free;
end;
IDStringHashMap.Free;
end;
finally
XML.Free;
end;
end;
function TDAELoader.ExportAsOBJ(FileName:ansistring):boolean;
var i,j,k,VertexIndex:longint;
sl:TStringList;
Geometry:TDAEGeometry;
Mesh:TDAEMesh;
begin
result:=false;
if Geometries.Count>0 then begin
sl:=TStringList.Create;
try
VertexIndex:=1;
for i:=0 to Geometries.Count-1 do begin
Geometry:=Geometries[i];
for j:=0 to Geometry.Count-1 do begin
Mesh:=Geometry[j];
if Mesh.MeshType=dlmtTRIANGLES then begin
if j=0 then begin
sl.Add('o '+Geometry.Name);
end;
for k:=0 to length(Mesh.Vertices)-1 do begin
sl.Add('v '+DoubleToStr(Mesh.Vertices[k].Position.x)+' '+DoubleToStr(Mesh.Vertices[k].Position.y)+' '+DoubleToStr(Mesh.Vertices[k].Position.z));
end;
for k:=0 to length(Mesh.Vertices)-1 do begin
sl.Add('vn '+DoubleToStr(Mesh.Vertices[k].Normal.x)+' '+DoubleToStr(Mesh.Vertices[k].Normal.y)+' '+DoubleToStr(Mesh.Vertices[k].Normal.z));
end;
for k:=0 to length(Mesh.Vertices)-1 do begin
sl.Add('vt '+DoubleToStr(Mesh.Vertices[k].TexCoords[0].x)+' '+DoubleToStr(Mesh.Vertices[k].TexCoords[0].y));
end;
k:=0;
while (k+2)<length(Mesh.Indices) do begin
sl.Add('f '+IntToStr(VertexIndex+Mesh.Indices[k])+'/'+IntToStr(VertexIndex+Mesh.Indices[k])+'/'+IntToStr(VertexIndex+Mesh.Indices[k])+' '+IntToStr(VertexIndex+Mesh.Indices[k+1])+'/'+IntToStr(VertexIndex+Mesh.Indices[k+1])+'/'+IntToStr(VertexIndex+Mesh.Indices[k+1])+' '+IntToStr(VertexIndex+Mesh.Indices[k+2])+'/'+IntToStr(VertexIndex+Mesh.Indices[k+2])+'/'+IntToStr(VertexIndex+Mesh.Indices[k+2]));
inc(k,3);
end;
inc(VertexIndex,length(Mesh.Vertices));
end;
end;
end;
sl.SaveToFile(FileName);
result:=true;
finally
sl.Free;
end;
end;
end;
end.
|
unit glModel;
(* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the gl3ds main unit.
*
* The Initial Developer of the Original Code is
* Noeska Software.
* Portions created by the Initial Developer are Copyright (C) 2002-2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* M van der Honing
* Sascha Willems
* Jan Michalowsky
*
*)
interface
uses classes, Model;
type
TglModel = class(TBaseModel)
public
procedure Init; override;
procedure Render; override;
procedure RenderBoundBox; override;
procedure RenderSkeleton; override;
procedure UpdateTextures; override;
end;
implementation
uses dglOpenGl;
procedure TglModel.Init;
var
m: Integer;
begin
inherited;
for m := 0 to FNumMeshes - 1 do
begin
FMesh[FRenderOrder[m]].Init;
end;
end;
procedure TglModel.Render;
var
m: Integer;
begin
for m := 0 to FNumMeshes - 1 do
begin
if FMesh[FRenderOrder[m]].Visible then
begin
glpushmatrix();
FMesh[FRenderOrder[m]].Render;
glpopmatrix();
end;
end;
end;
procedure TglModel.RenderBoundBox;
var
loop: Integer;
begin
if fnummeshes>0 then
for loop:=0 to fnummeshes-1 do
begin
fmesh[loop].RenderBoundBox;
end;
glBegin(GL_LINE_LOOP);
glVertex3f(minimum.x, minimum.y, minimum.z);
glVertex3f(maximum.x, minimum.y, minimum.z);
glVertex3f(maximum.x, maximum.y, minimum.z);
glVertex3f(minimum.x, maximum.y, minimum.z);
glEnd;
glBegin(GL_LINE_LOOP);
glVertex3f(minimum.x, minimum.y, maximum.z);
glVertex3f(maximum.x, minimum.y, maximum.z);
glVertex3f(maximum.x, maximum.y, maximum.z);
glVertex3f(minimum.x, maximum.y, maximum.z);
glEnd;
glBegin(GL_LINES);
glVertex3f(minimum.x, minimum.y, minimum.z);
glVertex3f(minimum.x, minimum.y, maximum.z);
glVertex3f(maximum.x, minimum.y, minimum.z);
glVertex3f(maximum.x, minimum.y, maximum.z);
glVertex3f(maximum.x, maximum.y, minimum.z);
glVertex3f(maximum.x, maximum.y, maximum.z);
glVertex3f(minimum.x, maximum.y, minimum.z);
glVertex3f(minimum.x, maximum.y, maximum.z);
glEnd;
end;
procedure TglModel.RenderSkeleton;
var
b: integer;
begin
for b := 0 to fSkeleton[0].NumBones - 1 do
begin
fSkeleton[0].Bone[b].Render;
end;
end;
procedure TglModel.UpdateTextures;
var
m: integer;
begin
for m := 0 to FNumMaterials - 1 do
begin
fmaterial[m].UpdateTexture;
end;
end;
end.
|
unit UROWDataInfo;
interface
uses
System.Classes,UProperty,URawdataDataType;
type
RawDataInfo = class
private
sizeLength : LongInt;
dataType : RawdataDataType;
dimension : Integer;
numofValue : LongInt;
public
constructor Create();
destructor Destroy; override;
function getNumOfValue:LongInt;
function getDataType:RawdataDataType;
function getDimension:Integer;
procedure read(buffer:TFileStream);
end;
implementation
{ RawDataInfo }
constructor RawDataInfo.Create();
begin
inherited create;
end;
destructor RawDataInfo.Destroy;
begin
dataType.Free;
end;
function RawDataInfo.getDataType: RawdataDataType;
begin
Result:= dataType;
end;
function RawDataInfo.getDimension: Integer;
begin
Result := dimension;
end;
function RawDataInfo.getNumOfValue: LongInt;
begin
Result := numofValue;
end;
procedure RawDataInfo.read(buffer: TFileStream);
var
bytes:array[0..4] of Byte;
bys:array[0..8]of Byte;
serNum:Integer;
begin
dataType := RawdataDataType.Create;
buffer.Read(bytes,4);
serNum:=PInteger(@bytes)^;
dataType.get(serNum);
buffer.Read(bytes,4);
dimension:=Pinteger(@bytes)^;
buffer.Read(bys,8);
numofValue:=PInt64(@bys)^;
if dataType.type_name = tdsTypeString then
begin
buffer.Read(bys,8);
sizeLength:=Pinteger(@bys)^;
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [VIEW_PESSOA_COLABORADOR]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit ViewPessoaColaboradorVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils;
type
[TEntity]
[TTable('VIEW_PESSOA_COLABORADOR')]
TViewPessoaColaboradorVO = class(TVO)
private
FID: Integer;
FID_SINDICATO: Integer;
FID_TIPO_ADMISSAO: Integer;
FID_SITUACAO_COLABORADOR: Integer;
FID_PESSOA: Integer;
FID_TIPO_COLABORADOR: Integer;
FID_NIVEL_FORMACAO: Integer;
FID_CARGO: Integer;
FID_SETOR: Integer;
FMATRICULA: String;
FDATA_CADASTRO: TDateTime;
FDATA_ADMISSAO: TDateTime;
FLOGRADOURO: String;
FNUMERO: String;
FCOMPLEMENTO: String;
FBAIRRO: String;
FCIDADE: String;
FCEP: String;
FMUNICIPIO_IBGE: Integer;
FUF: String;
FFONE: String;
FNOME: String;
FTIPO: String;
FEMAIL: String;
FSITE: String;
FCPF_CNPJ: String;
FRG_IE: String;
FCODIGO_TURMA_PONTO: String;
FPIS_NUMERO: String;
//Transientes
public
[TId('ID')]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('NOME', 'Nome', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Nome: String read FNOME write FNOME;
[TColumn('ID_SINDICATO', 'Id Sindicato', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdSindicato: Integer read FID_SINDICATO write FID_SINDICATO;
[TColumn('ID_TIPO_ADMISSAO', 'Id Tipo Admissao', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdTipoAdmissao: Integer read FID_TIPO_ADMISSAO write FID_TIPO_ADMISSAO;
[TColumn('ID_SITUACAO_COLABORADOR', 'Id Situacao Colaborador', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdSituacaoColaborador: Integer read FID_SITUACAO_COLABORADOR write FID_SITUACAO_COLABORADOR;
[TColumn('ID_PESSOA', 'Id Pessoa', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdPessoa: Integer read FID_PESSOA write FID_PESSOA;
[TColumn('ID_TIPO_COLABORADOR', 'Id Tipo Colaborador', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdTipoColaborador: Integer read FID_TIPO_COLABORADOR write FID_TIPO_COLABORADOR;
[TColumn('ID_NIVEL_FORMACAO', 'Id Nivel Formacao', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdNivelFormacao: Integer read FID_NIVEL_FORMACAO write FID_NIVEL_FORMACAO;
[TColumn('ID_CARGO', 'Id Cargo', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdCargo: Integer read FID_CARGO write FID_CARGO;
[TColumn('ID_SETOR', 'Id Setor', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdSetor: Integer read FID_SETOR write FID_SETOR;
[TColumn('MATRICULA', 'Matricula', 80, [ldGrid, ldLookup, ldCombobox], False)]
property Matricula: String read FMATRICULA write FMATRICULA;
[TColumn('DATA_CADASTRO', 'Data Cadastro', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataCadastro: TDateTime read FDATA_CADASTRO write FDATA_CADASTRO;
[TColumn('DATA_ADMISSAO', 'Data Admissao', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataAdmissao: TDateTime read FDATA_ADMISSAO write FDATA_ADMISSAO;
[TColumn('LOGRADOURO', 'Logradouro', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Logradouro: String read FLOGRADOURO write FLOGRADOURO;
[TColumn('NUMERO', 'Numero', 80, [ldGrid, ldLookup, ldCombobox], False)]
property Numero: String read FNUMERO write FNUMERO;
[TColumn('COMPLEMENTO', 'Complemento', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Complemento: String read FCOMPLEMENTO write FCOMPLEMENTO;
[TColumn('BAIRRO', 'Bairro', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Bairro: String read FBAIRRO write FBAIRRO;
[TColumn('CIDADE', 'Cidade', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Cidade: String read FCIDADE write FCIDADE;
[TColumn('CEP', 'Cep', 64, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftCep, taLeftJustify)]
property Cep: String read FCEP write FCEP;
[TColumn('MUNICIPIO_IBGE', 'Municipio Ibge', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property MunicipioIbge: Integer read FMUNICIPIO_IBGE write FMUNICIPIO_IBGE;
[TColumn('UF', 'Uf', 16, [ldGrid, ldLookup, ldCombobox], False)]
property Uf: String read FUF write FUF;
[TColumn('FONE', 'Fone', 112, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftTelefone, taLeftJustify)]
property Fone: String read FFONE write FFONE;
[TColumn('TIPO', 'Tipo', 8, [ldGrid, ldLookup, ldCombobox], False)]
property Tipo: String read FTIPO write FTIPO;
[TColumn('EMAIL', 'Email', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Email: String read FEMAIL write FEMAIL;
[TColumn('SITE', 'Site', 450, [ldGrid, ldLookup, ldCombobox], False)]
property Site: String read FSITE write FSITE;
[TColumn('CPF_CNPJ', 'Cpf Cnpj', 112, [ldGrid, ldLookup, ldCombobox], False)]
property CpfCnpj: String read FCPF_CNPJ write FCPF_CNPJ;
[TColumn('RG_IE', 'Rg Ie', 240, [ldGrid, ldLookup, ldCombobox], False)]
property RgIe: String read FRG_IE write FRG_IE;
[TColumn('CODIGO_TURMA_PONTO', 'Código Turma Ponto', 200, [ldGrid, ldLookup, ldCombobox], False)]
property CodigoTurmaPonto: String read FCODIGO_TURMA_PONTO write FCODIGO_TURMA_PONTO;
[TColumn('PIS_NUMERO', 'Número PIS', 200, [ldGrid, ldLookup, ldCombobox], False)]
property PisNumero: String read FPIS_NUMERO write FPIS_NUMERO;
//Transientes
end;
implementation
initialization
Classes.RegisterClass(TViewPessoaColaboradorVO);
finalization
Classes.UnRegisterClass(TViewPessoaColaboradorVO);
end.
|
(********************************************************)
(* Модуль с реализацией потока в XMS-памяти *)
(* 1994 (c) Бурнашов А.В. 2:5030/254.36 *)
(********************************************************)
unit XMS;
interface
uses objects;
{ TXMSStream }
type
PXMSStream = ^TXMSStream;
TXMSStream = object(TStream)
Handle :word;
XMSSize :word;
Size :longint; {порядок и размер этих полей менять нельзя}
Position :longint; {см. Init в конце}
Delta :word; {}
constructor Init(ASize:word;ADelta:word);
destructor Done;virtual;
function GetPos: Longint; virtual;
function GetSize: Longint; virtual;
procedure Read(var Buf; Count: Word); virtual;
procedure Seek(Pos: Longint); virtual;
procedure Truncate; virtual;
procedure Write(var Buf; Count: Word); virtual;
end;
function CMOSGetBaseSize : Word;
function CMOSGetExtendedSize : Word;
function CMOSGetTotalSize : Word;
function XMSGetFree : Word;
function EMSGetTotal : Word;
function EMSGetFree : Word;
implementation
type
TXMSMoveStruct=
record
Length : longint; {кол-во пересылаемых байт }
SouHandle : word; {откуда (0-обычная память)}
SouOffset : longint; { }
DstHandle : word; {куда }
DstOffset : longint; { }
end;
const
XMM_Entry:pointer=nil;
{ TStream support routines }
const
TStream_Error = vmtHeaderSize + $04;
{ Stream error handler }
{ In AX = Error info }
{ DX = Error code }
{ ES:DI = Stream object pointer }
{ Uses AX,BX,CX,DX,SI }
procedure DoStreamError; near; assembler;
asm
PUSH ES
PUSH DI
PUSH DX
PUSH AX
PUSH ES
PUSH DI
MOV DI,ES:[DI]
CALL DWORD PTR [DI].TStream_Error
POP DI
POP ES
end;
constructor TXMSStream.Init(ASize:word;ADelta:word);assembler;
asm
{Инициализируем объект - inherited Init}
XOR AX,AX
PUSH AX
LES DI,Self
PUSH ES
PUSH DI
CALL TStream.Init
MOV AX,XMM_Entry.Word[0]
OR AX,XMM_Entry.Word[2]
JZ @@Error
{вделяем блок памяти}
LES DI,Self
MOV AH,09h
MOV DX,ASize
MOV ES:[DI].TXMSStream.XMSSize,DX
CALL XMM_Entry
OR AX,AX
MOV AL,BL
JNZ @@4
{ошибка}
@@Error:MOV DX,stInitError
CALL DoStreamError
MOV DX,-1
@@4: MOV ES:[DI].TXMSStream.Handle,DX
XOR AX,AX
ADD DI,offset TXMSStream.Size
CLD
STOSW
STOSW
STOSW
STOSW
MOV AX,ADelta
STOSW
end;
destructor TXMSStream.Done; assembler;
asm
LES DI,Self
MOV DX,ES:[DI].TXMSStream.Handle
CMP DX,-1
JE @@1
MOV AX,XMM_Entry.Word[0]
OR AX,XMM_Entry.Word[2]
JZ @@1
MOV AH,0Ah
CALL XMM_Entry
OR AX,AX
MOV AL,BL
JNZ @@1
MOV DX,stError
CALL DoStreamError
@@1: XOR AX,AX
PUSH AX
PUSH ES
PUSH DI
CALL TStream.Done
end;
function TXMSStream.GetPos: Longint; assembler;
asm
LES DI,Self
CMP ES:[DI].TXMSStream.Status,0
JNE @@1
MOV AX,ES:[DI].TXMSStream.Position.Word[0]
MOV DX,ES:[DI].TXMSStream.Position.Word[2]
JMP @@2
@@1: MOV AX,-1
CWD
@@2:
end;
function TXMSStream.GetSize: Longint; assembler;
asm
LES DI,Self
CMP ES:[DI].TXMSStream.Status,0
JNE @@1
MOV AX,ES:[DI].TXMSStream.Size.Word[0]
MOV DX,ES:[DI].TXMSStream.Size.Word[2]
JMP @@2
@@1: MOV AX,-1
CWD
@@2:
end;
procedure TXMSStream.Read(var Buf; Count: Word); assembler;
var MoveStruct:TXMSMoveStruct;
asm
{проверка инициализации}
MOV AX,XMM_Entry.Word[0]
OR AX,XMM_Entry.Word[2]
JZ @@Error
{проверка того, что мы читаем в пределах потока}
LES DI,Self
XOR BX,BX
CMP ES:[DI].TXMSStream.Status,BX
JNE @@Clear
MOV AX,ES:[DI].TXMSStream.Position.Word[0]
MOV DX,ES:[DI].TXMSStream.Position.Word[2]
ADD AX,Count
ADC DX,BX
CMP DX,ES:[DI].TXMSStream.Size.Word[2]
JA @@Error
JB @@Read
CMP AX,ES:[DI].TXMSStream.Size.Word[0]
JBE @@Read
{ошибка-чтение за пределом потока}
@@Error:
XOR AX,AX
@@Error2:
MOV DX,stReadError
@@2: CALL DoStreamError
{очистка буфера}
@@Clear:
LES DI,Buf
MOV CX,Count
XOR AL,AL
CLD
REP STOSB
JMP @@Exit
{читаем}
@@Read:
{fill MoveStruct}
PUSH DS
LDS SI,Self
MOV AX,SS
MOV ES,AX
LEA DI,MoveStruct
CLD
MOV AX,Count
MOV CX,AX
{adjust Count in AX to Odd and save byte}
TEST AL,1
JZ @@4
INC AX
@@4:
STOSW {Length[0]}
XOR AX,AX
STOSW {Length[2]}
MOV AX,DS:[SI].TXMSStream.Handle
STOSW {SouHandle}
MOV AX,DS:[SI].TXMSStream.Position.Word[0]
STOSW {SouOffset[0]}
MOV AX,DS:[SI].TXMSStream.Position.Word[2]
STOSW {SouOffset[2]}
XOR AX,AX
STOSW {DstHandle}
MOV AX,Buf.Word[0]
MOV SI,AX
STOSW {DstOffset[0]}
MOV AX,Buf.Word[2]
STOSW {DstOffset[2]}
{save byte, CX=count}
ADD SI,CX
JNC @@5
ADD AX,1000h
@@5:
MOV DS,AX
MOV CH,DS:[SI]
POP ES
PUSH ES
PUSH CX
PUSH DS
PUSH SI
MOV AX,SS
MOV DS,AX
LEA SI,MoveStruct
MOV AH,0Bh
CALL ES:XMM_Entry
POP SI
POP DS
POP CX
MOV DS:[SI],CH
POP DS
LES DI,Self
OR AX,AX
MOV AL,BL
JE @@Error2
MOV AX,Count
ADD ES:[DI].TXMSStream.Position.Word[0],AX
ADC ES:[DI].TXMSStream.Position.Word[2],0
@@Exit:
end;
procedure TXMSStream.Seek(Pos: Longint); assembler;
asm
LES DI,Self
CMP ES:[DI].TXMSStream.Status,0
JNE @@Exit
MOV AX,Pos.Word[0]
MOV DX,Pos.Word[2]
OR DX,DX
JNS @@1
XOR AX,AX
CWD
@@1: MOV ES:[DI].TXMSStream.Position.Word[0],AX
MOV ES:[DI].TXMSStream.Position.Word[2],DX
@@Exit:
end;
procedure TXMSStream.Truncate; assembler;
asm
XOR AX,AX
MOV DX,XMM_Entry.Word[0]
OR DX,XMM_Entry.Word[2]
JZ @@Error
LES DI,Self
CMP ES:[DI].TXMSStream.Status,0
JNE @@Exit
MOV AX,ES:[DI].TXMSStream.Position.Word[0]
MOV DX,ES:[DI].TXMSStream.Position.Word[2]
MOV ES:[DI].TXMSStream.Size.Word[0],AX
MOV ES:[DI].TXMSStream.Size.Word[2],DX
MOV CX,1024
DIV CX
OR DX,DX
JZ @@1
INC AX {реальный размер потока, Kb}
@@1:
MOV CX,ES:[DI].TXMSStream.Delta
ADD CX,AX
JC @@Exit
CMP CX,ES:[DI].TXMSStream.XMSSize
JNB @@Exit
MOV DX,ES:[DI].TXMSStream.Handle
MOV BX,AX {если Size+Delta<XMSSize то XMSSize:=Size}
MOV AH,0Fh
CALL XMM_Entry
OR AX,AX
MOV AL,BL
JNZ @@Exit
@@Error:MOV DX,stError
CALL DoStreamError
@@Exit:
end;
procedure TXMSStream.Write(var Buf; Count: Word); assembler;
var MoveStruct:TXMSMoveStruct;
asm
MOV AX,XMM_Entry.Word[0]
OR AX,XMM_Entry.Word[2]
JZ @@Error
LES DI,Self
CMP ES:[DI].TXMSStream.Status,0
JNE @@Exit
{загружаем текущую позицию}
MOV AX,ES:[DI].TXMSStream.Position.Word[0]
MOV DX,ES:[DI].TXMSStream.Position.Word[2]
{выравниваем Count до четного числа}
MOV CX,Count
TEST CL,1
JZ @@7
INC CX
@@7:
ADD AX,CX
ADC DX,0
{проверка на превышение памяти, отведенной в XMS (DX:AX = Position+Count)}
{Определяем число Kb}
ADD AX,1024-1 {: AX:=DX:AX/1024 with round}
ADC DX,0
MOV AL,AH
MOV AH,DL
MOV DL,DH {MOV SI,1024}
SHR DL,1 {DIV SI}
RCR AX,1 {OR DX,DX}
SHR DL,1 {JZ @@3}
RCR AX,1 {INC AX}
OR DL,DL {@@3:}
JNZ @@Error
MOV BX,ES:[DI].TXMSStream.XMSSize
CMP AX,BX
JBE @@Write
@@1:
{надо увеличивать выделенную в XMS память для потока,AX- нужный размер в Kb}
ADD BX,ES:[DI].TXMSStream.Delta
JC @@Error
CMP BX,AX
JNB @@2
MOV BX,AX
@@2:
MOV DX,ES:[DI].TXMSStream.Handle
MOV AH,0Fh
PUSH BX {Новый размер выделенной памяти в XMS}
PUSH CX {выровненный Count}
CALL XMM_Entry
POP CX
POP DX
OR AX,AX
MOV AL,BL
JZ @@Error2
MOV ES:[DI].TXMSStream.XMSSize,DX
JMP @@Write
{ошибка}
@@Error :
XOR AX,AX
@@Error2:
MOV DX,stWriteError
CALL DoStreamError
JMP @@Exit
{пишем}
@@Write:
PUSH DS
LDS SI,Self
PUSH SS
POP ES
LEA DI,MoveStruct
CLD
MOV AX,CX
STOSW {Length[0]}
XOR AX,AX
STOSW {Length[2]}
STOSW {SouHandle}
MOV AX,Buf.Word[0]
STOSW {SouOffset[0]}
MOV AX,Buf.Word[2]
STOSW {SouOffset[2]}
MOV AX,DS:[SI].TXMSStream.Handle
STOSW {DstHandle}
MOV AX,DS:[SI].TXMSStream.Position.Word[0]
STOSW {DstOffset[0]}
MOV AX,DS:[SI].TXMSStream.Position.Word[2]
STOSW {DstOffset[2]}
POP ES
PUSH ES
MOV AX,SS
MOV DS,AX
LEA SI,MoveStruct
MOV AH,0Bh
CALL ES:XMM_Entry
POP DS
LES DI,Self
OR AX,AX
MOV AL,BL
JE @@Error2
{увеличиваем позицию}
MOV AX,Count
ADD ES:[DI].TXMSStream.Position.Word[0],AX
ADC ES:[DI].TXMSStream.Position.Word[2],0
{увеличиваем при необходимости размер потока}
MOV AX,ES:[DI].TXMSStream.Position.Word[0]
MOV DX,ES:[DI].TXMSStream.Position.Word[2]
CMP DX,ES:[DI].TXMSStream.Size.Word[2]
JB @@Exit
JA @@6
CMP AX,ES:[DI].TXMSStream.Size.Word[0]
JBE @@Exit
@@6: MOV ES:[DI].TXMSStream.Size.Word[0],AX
MOV ES:[DI].TXMSStream.Size.Word[2],DX
@@Exit:
end;
function XMSGetFree:word;assembler;
asm
MOV AX,XMM_Entry.Word[0]
OR AX,XMM_Entry.Word[2]
JZ @@Error
MOV AH,08h
CALL XMM_Entry
OR AX,AX
JZ @@Error
MOV AX,DX
JMP @@Exit
@@Error:
XOR AX,AX
@@Exit:
end;
function EMSGetTotal:word;assembler;
asm
CALL EMSGetFree
MOV AX,DX
end;
function EMSGetFree:word;assembler;
const Sign:array[0..7]of char='EMMXXXX0';
asm
MOV AX,3567h
INT 21h
MOV AX,ES
OR AX,BX
JZ @@Error
MOV DI,10
MOV SI,offset Sign
MOV CX,8
CLD
REPE CMPSB
JNE @@Error
MOV AX,4200h
INT 67H
OR AH,AH
JNZ @@Error
SHL DX,4
SHL BX,4
MOV AX,BX
JMP @@Exit
@@Error:XOR AX,AX
XOR DX,DX
@@Exit:
end;
function CMOSGetTotalSize : Word;
begin
CMOSGetTotalSize := CMOSGetBaseSize+CMOSGetExtendedSize;
end;
function CMOSGetExtendedSize : Word; assembler;
asm
mov al,18h
out 70h,al
jmp @1
@1:
in al,71h
mov ah,al
mov al,17h
out 70h,al
jmp @2
@2:
in al,71h
end;
function CMOSGetBaseSize : Word; assembler;
asm
mov al,16h
out 70h,al
jmp @1
@1:
in al,71h
mov ah,al
mov al,15h
out 70h,al
jmp @2
@2:
in al,71h
end;
begin {ИНИЦИАЛИЗАЦИЯ МОДУЛЯ}
asm {определяем наличие XMS }
MOV AX,4300h
INT 2FH
CMP AL,80h
JNE @@NoXMS
{определяем точку входа}
MOV AX,4310h
INT 2Fh
MOV XMM_Entry.Word[0],BX
MOV XMM_Entry.Word[2],ES
@@NoXMS:
end;
End.
|
unit Unit2;
interface
uses
SysUtils, StdCtrls;
type
PTField = ^TField;
TField = record
Number: byte;
SP: PTField;
end;
TStack = class
constructor Create(n: byte);
procedure Push(Number: byte);
function Pop: byte;
procedure Print(ListBox: TListBox);
function Search(LookFor: byte; FP: PTField = nil): PTField;
procedure Sort;
function NumMoreThanAvr: byte;
destructor Destroy; override;
private
ESP: PTField;
end;
implementation
constructor TStack.Create(n: byte);
var
i: byte;
begin
Inherited Create;
ESP := nil;
Randomize;
for i := 0 to n do
Push(1 + Random(254));
end;
procedure TStack.Push;
var
ETP: PTField;
begin
New(ETP);
ETP^.Number := Number;
ETP^.SP := ESP;
ESP := ETP;
end;
function TStack.Pop: byte;
var
ETP: PTField;
begin
if ESP <> nil then
begin
Result := ESP^.Number;
ETP := ESP;
ESP := ESP^.SP;
Dispose(ETP);
end
else
Result := 0;
end;
procedure TStack.Print;
var
ETP: PTField;
begin
if ESP <> nil then
begin
ETP := ESP;
ListBox.Clear;
while ETP <> nil do
begin
ListBox.Items.Add(IntToStr(ETP^.Number));
ETP := ETP^.SP;
end;
end;
end;
function TStack.Search(LookFor: byte; FP: PTField = nil): PTField; // если не заработает, то FP: PTField = nil
begin
Result := nil;
if ESP = nil then
Exit;
if FP = nil then
Result := ESP
else
Result := FP;
while (LookFor <> Result^.Number) and (Result <> nil) do
Result := Result^.SP;
end;
procedure TStack.Sort;
procedure Obmen(FP: PTField);
var
ETP: PTField;
begin
ETP := FP^.SP^.SP;
FP^.SP^.SP := ETP^.SP;
ETP^.SP := FP^.SP;
FP^.SP := ETP;
end;
var
jsp, isp: PTField;
begin
if ESP^.SP = Nil then exit;
Push(0);
jsp := Nil;
repeat
isp := ESP;
while isp^.SP^.SP <> jsp do
begin
if isp^.SP^.Number > isp^.SP^.SP^.Number then
Obmen(isp);
isp := isp^.SP;
end;
jsp := isp^.SP;
until ESP^.SP^.SP = jsp;
Pop;
end;
function TStack.NumMoreThanAvr: byte;
var
Average, n: byte;
Sum: integer;
ETP: PTField;
begin
Result := 0;
if ESP = nil then Exit;
// находим среднее значение
Sum := 0;
n := 0;
ETP := ESP;
while ETP <> nil do
begin
Sum := Sum + ETP^.Number;
Inc(n);
ETP := ETP^.SP;
end;
Average := Sum div n;
// теперь выискиваем, сколько же элементов больше среднего значения
ETP := ESP;
Result := 0;
while ETP <> nil do
begin
if ETP^.Number > Average then
Result := Result + 1;
ETP := ETP^.SP;
end;
end;
destructor TStack.Destroy;
var
ETP: PTField;
begin
if ESP = nil then Exit;
while ESP <> nil do
begin
ETP := ESP;
ESP := ESP^.SP;
Dispose(ETP);
end;
Inherited Destroy;
end;
end.
|
Unit UcumValidators;
{
Copyright (c) 2001-2013, Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
SysUtils,
DecimalSupport,
Ucum,
UcumExpressions,
UcumHandlers,
AdvStringLists,
AdvNames,
AdvObjects;
Type
TUcumValidator = class (TAdvObject)
Private
Fmodel : TUcumModel;
Fresult : TAdvStringList;
Fhandlers : TUcumRegistry;
procedure checkCodes;
procedure checkUnits;
procedure checkUnitCode(code : String; primary : boolean);
Public
Constructor Create(oModel : TUcumModel; handlers : TUcumRegistry);
Destructor Destroy; Override;
Procedure validate(oList : TAdvStringList);
End;
Implementation
Constructor TUcumValidator.Create(oModel : TUcumModel; handlers : TUcumRegistry);
Begin
Inherited Create;
FModel := oModel;
FHandlers := Handlers;
End;
Destructor TUcumValidator.Destroy;
Begin
FModel.Free;
Fhandlers.Free;
FResult.Free;
Inherited;
End;
Procedure TUcumValidator.validate(oList : TAdvStringList);
Begin
Fresult := oList.Link;
checkCodes();
checkUnits();
End;
procedure TUcumValidator.checkCodes;
var
i : Integer;
Begin
for i := 0 to Fmodel.BaseUnits.Count - 1 Do
checkUnitCode(FModel.BaseUnits[i].Code, true);
for i := 0 to Fmodel.DefinedUnits.Count - 1 Do
checkUnitCode(FModel.DefinedUnits[i].Code, true);
End;
procedure TUcumValidator.checkUnits;
var
i : integer;
Begin
for i := 0 to Fmodel.DefinedUnits.Count - 1 Do
if not Fmodel.DefinedUnits[i].isSpecial Then
checkUnitCode(Fmodel.DefinedUnits[i].Value.Unit_, false)
else if not Fhandlers.ExistsByName(Fmodel.DefinedUnits[i].Code) Then
Fresult.add('No Handler for '+Fmodel.DefinedUnits[i].Code);
End;
procedure TUcumValidator.checkUnitCode(code : String; primary : boolean);
var
term : TUcumTerm;
oCan : TUcumCanonical;
c : String;
inBrack : boolean;
nonDigits : boolean;
i : integer;
oConv : TUcumConverter;
Begin
try
term := TUcumExpressionParser.parse(Fmodel, code);
try
c := TUcumExpressionComposer.compose(term);
if (c <> code) Then
FResult.add('Round trip failed: '+code+' -> '+c);
oConv := TUcumConverter.Create(Fmodel.Link, Fhandlers.Link);
Try
oCan := oConv.convert(term);
Try
// what? oCan.Unit_;
Finally
oCan.Free;
End;
Finally
oConv.Free;
End;
Finally
term.Free;
End;
except
on e : exception do
FResult.Add(Code+': '+e.Message);
End;
if (primary) Then
try
// there can't be any codes that have digits in them that aren't inside []
inBrack := false;
nonDigits := false;
for i := 1 to length(code) Do
begin
if (code[i] = '[') Then
if (inBrack) Then
raise Exception.create('nested [')
else
inBrack := true;
if (code[i] = ']') Then
if (not inBrack) Then
raise Exception.Create('] without [')
else
inBrack := false;
nonDigits := nonDigits or not ((code[i] >= '0') and (code[i] <= '9'));
if ((code[i] >= '0') and (code[i] <= '9')) And not inBrack and nonDigits Then
raise Exception.Create('code '+code+' is ambiguous because it has digits outside []');
End;
except
on e : exception do
FResult.Add(Code+': '+e.Message);
End;
End;
End. |
PROGRAM FormatSentence(INPUT, OUTPUT);
CONST
CharBegin = 'B';
CharLetter = 'L';
CharSpace = 'S';
CharPoint = 'P';
CharComma = 'C';
CharError = 'E';
BeginningOfAlphabet = 'A';
EndingOfAlphabet = 'z';
VAR
Ch, Status: CHAR;
PROCEDURE Begining;
BEGIN {Begining}
IF Status = CharBegin
THEN
IF (Ch >= BeginningOfAlphabet) AND (Ch <= EndingOfAlphabet)
THEN
Status := CharLetter
ELSE
IF Ch <> ' '
THEN
Status := CharError
END; {Begining}
PROCEDURE Letter;
BEGIN {Letter}
IF Status = CharLetter
THEN
IF Ch = ' '
THEN
Status := CharSpace
ELSE
IF Ch = ','
THEN
BEGIN
Status := CharComma;
WRITE(Ch)
END
ELSE
IF Ch = '.'
THEN
BEGIN
Status := CharPoint;
WRITE(Ch)
END
ELSE
IF NOT(Ch >= BeginningOfAlphabet) AND (Ch <= EndingOfAlphabet)
THEN
Status := CharError
END; {Word}
PROCEDURE Space;
BEGIN {Space}
IF Status = CharSpace
THEN
IF (Ch >= BeginningOfAlphabet) AND (Ch <= EndingOfAlphabet)
THEN
BEGIN
Status := CharLetter;
WRITE(' ')
END
ELSE
IF Ch = ','
THEN
BEGIN
Status := CharComma;
WRITE(Ch)
END
ELSE
IF Ch = '.'
THEN
BEGIN
Status := CharPoint;
WRITE(Ch)
END
ELSE
IF Ch <> ' '
THEN
Status := CharError
END; {Space}
PROCEDURE Comma;
BEGIN {Comma}
IF Status = CharComma
THEN
BEGIN
IF (Ch >= BeginningOfAlphabet) AND (Ch <= EndingOfAlphabet)
THEN
BEGIN
Status := CharLetter;
WRITE(' ')
END
ELSE
IF (Ch = ',') OR (Ch = '.') OR (Ch <> ' ')
THEN
Status := CharError
END
END; {Comma}
PROCEDURE Point;
BEGIN {Point}
IF (Status = CharPoint) AND (Ch <> ' ')
THEN
Status := CharError
END; {Point}
BEGIN{FormatSentence}
Status := CharBegin;
WHILE NOT(EOLN(INPUT)) AND (Status <> CharError)
DO
BEGIN
READ(Ch);
Point;
Begining;
Comma;
Letter;
Space;
IF Status = CharLetter
THEN
WRITE(Ch);
IF Status = CharError
THEN
BEGIN
WRITELN;
WRITE('Unexpected symbol: ', Ch)
END
END;
IF (Status <> CharPoint) AND (Status <> CharError)
THEN
BEGIN
WRITELN;
WRITE('Unexpected end of file')
END;
WRITELN
END.{FormatSentence}
|
unit vectorun;
INTERFACE
type vector = RECORD x,y,z:real; END;
type point = record x,y,z:real; end;
procedure vzero(var a:vector);
procedure vinit(ix,iy,iz:real; var a:vector);
procedure pinit(ix,iy,iz:real; var p:point);
procedure p2v(a,b:point; var v:vector);
procedure vnorm(v:vector; var n:vector);
function vcosw(v,w:vector):real;
function vdot(v,w:vector):real;
procedure vadd(a,b:vector; var c:vector);
procedure vsub(a,b:vector; var c:vector);
{
procedure vdot(a,b:vector; var c:vector);
procedure vcross(a,b:vector; var c:vector);
}
procedure vdiv(k:real; a:vector; var c:vector);
procedure vmul(k:real; a:vector; var c:vector);
procedure writevector(s:string; a:vector);
procedure writewinkel(s:string; r:real);
procedure drehx(a:real; var v:vector);
procedure drehy(a:real; var v:vector);
procedure drehz(a:real; var v:vector);
function det2(a11,a12,
a21,a22:real):real;
function det3(a11,a12,a13,
a21,a22,a23,
a31,a32,a33:real):real;
IMPLEMENTATION
procedure p2v(a,b:point; var v:vector);
begin
vinit(b.x-a.x,b.y-a.y,b.z-a.z,v);
end;
procedure vnorm(v:vector; var n:vector);
begin
writevector('v=',v);
vdiv(sqrt(sqr(v.x)+sqr(v.y)+sqr(v.z)),v,n);
end;
function vcosw(v,w:vector):real;
begin
vcosw:=vdot(v,w)/(vdot(v,v)*vdot(w,w));
end;
procedure drehx(a:real; var v:vector);
var p:vector;
sa,ca:real;
begin
p:=v;
sa:=sin(a);
ca:=cos(a);
v.z:=ca*p.z+sa*p.y;
v.y:=ca*p.y-sa*p.z;
end;
procedure drehy(a:real; var v:vector);
var p:vector;
sa,ca:real;
begin
p:=v;
sa:=sin(a);
ca:=cos(a);
v.x:=ca*p.x+sa*p.z;
v.z:=ca*p.z-sa*p.x;
end;
procedure drehz(a:real; var v:vector);
var p:vector;
sa,ca:real;
begin
p:=v;
sa:=sin(a);
ca:=cos(a);
v.x:=ca*p.x+sa*p.y;
v.y:=ca*p.y-sa*p.x;
end;
procedure writewinkel(s:string; r:real);
begin
writeln(s,r*180/pi:3:3);
end;
function det2(a11,a12,
a21,a22:real):real;
begin
det2:=a11*a22-a12*a21;
end;
function det3(a11,a12,a13,
a21,a22,a23,
a31,a32,a33:real):real;
begin
det3:= a11*a22*a33+a12*a23*a31+a13*a21*a32
-a13*a22*a31-a11*a23*a32-a12*a21*a33;
end;
procedure writevector(s:string; a:vector);
begin
writeln(s,'( ',a.x:3:3,' / ',a.y:3:3,' / ',a.z:3:3,' )');
end;
procedure vzero(var a:vector);
begin
a.x:=0;
a.y:=0;
a.z:=0;
end;
procedure vinit(ix,iy,iz:real; var a:vector);
begin
with a do begin
x:=ix; y:=iy; z:=iz;
end;
end;
procedure pinit(ix,iy,iz:real; var p:point);
begin
p.x:=ix; p.y:=iy; p.z:=iz;
end;
procedure vadd(a,b:vector; var c:vector);
begin
c.x:=a.x+b.x;
c.y:=a.y+b.y;
c.z:=a.z+b.z;
end;
procedure vsub(a,b:vector; var c:vector);
begin
c.x:=a.x-b.x;
c.y:=a.y-b.y;
c.z:=a.z-b.z;
end;
function vdot(v,w:vector):real;
begin
vdot:=v.x*w.x+v.y*w.y+v.z*w.z;
end;
{
procedure vdot(a,b:vector; var c:vector);
begin
c.x:=a.x*b.x;
c.y:=a.y*b.y;
c.z:=a.z*b.z;
end;
procedure vcross(a,b:vector; var c:vector);
begin
c.x:=a.y*b.z-b.y*a.z;
c.y:=a.z*b.x-b.z*a.x;
c.z:=a.x*b.y-b.x*a.y;
end;
}
procedure vdiv(k:real; a:vector; var c:vector);
begin
c.x:=a.x/k;
c.y:=a.y/k;
c.z:=a.z/k;
end;
procedure vmul(k:real; a:vector; var c:vector);
begin
c.x:=k*a.x;
c.y:=k*a.y;
c.z:=k*a.z;
end;
begin
end. |
unit uJxdGpComboBox;
interface
uses
SysUtils, Classes, Controls, StdCtrls, Messages, Windows, Graphics, uJxdGpStyle;
type
TxdComboBox = class(TCustomComboBox)
protected
procedure InvaliScroll;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP;
procedure WMMouseLeave(var Message: TMessage); message WM_MOUSELEAVE;
procedure WMMouseMove(var Message: TMessage); message WM_MOUSEMOVE;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property Text;
property Align;
property AutoComplete default True;
property AutoCompleteDelay default 500;
property AutoDropDown default False;
property AutoCloseUp default False;
property Anchors;
property BiDiMode;
property CharCase;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Style default csOwnerDrawVariable;
property DropDownCount;
property Enabled;
property Font;
property ImeMode;
property ImeName;
property ItemHeight;
property ItemIndex default -1;
property MaxLength;
property ParentBiDiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Sorted;
property TabOrder;
property TabStop;
property Visible;
property OnChange;
property OnClick;
property OnCloseUp;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDrawItem;
property OnDropDown;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMeasureItem;
property OnMouseEnter;
property OnMouseLeave;
property OnSelect;
property OnStartDock;
property OnStartDrag;
property Items; { Must be published after OnMeasureItem }
end;
implementation
{ TJxdComboBox }
constructor TxdComboBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TxdComboBox.Destroy;
begin
inherited;
end;
procedure TxdComboBox.InvaliScroll;
//var
// R: TRect;
begin
// R := FScrollRect;
// InvalidateRect(Handle, @R, False);
end;
procedure TxdComboBox.WMLButtonDown(var Message: TWMLButtonDown);
begin
inherited;
// if FMouseInSroll then
// begin
// FSrollState := msDown;
// InvaliScroll;
// end
// else
// FMouseMoveInScrollRect := False;
end;
procedure TxdComboBox.WMLButtonUp(var Message: TWMLButtonUp);
begin
inherited;
// if FMouseInSroll then
// begin
// FSrollState := msActive;
// InvaliScroll;
// end
// else
// begin
// FMouseMoveInScrollRect := False;
// FSrollState := msNormal;
// InvaliScroll;
// end;
end;
procedure TxdComboBox.WMMouseLeave(var Message: TMessage);
begin
inherited;
// FMouseMoveInScrollRect := False;
// FSrollState := msNormal;
// InvaliScroll;
end;
procedure TxdComboBox.WMMouseMove(var Message: TMessage);
begin
inherited;
// if FMouseInSroll then
// begin
// if not FMouseMoveInScrollRect then
// begin
// FMouseMoveInScrollRect := True;
// InvaliScroll;
// end;
// end
// else
// begin
// FMouseMoveInScrollRect := False;
// InvaliScroll;
// end;
end;
procedure TxdComboBox.WMPaint(var Message: TWMPaint);
//var
// R: TRect;
begin
inherited;
// R := GetClientRect;
// DrawClearRectagle(R);
// if FSrollState = msDown then
// OnMouseDownScroll(FScrollRect)
// else if FMouseInSroll then
// OnMouseInScroll(FScrollRect)
// else
// OnNormalScroll(FScrollRect);
// if not ( Assigned(FScrollBmp) and (not FScrollBmp.Empty) ) then
// DrawTrigon;
// Canvas.Brush.Color := Color;
end;
procedure TxdComboBox.WMSize(var Message: TWMSize);
begin
inherited;
end;
end.
|
unit dmPostRequest;
interface
uses
System.SysUtils,
System.Classes,
System.Generics.Collections,
System.JSON,
REST.Types,
REST.Client,
Data.Bind.Components,
Data.Bind.ObjectScope,
FMX.Dialogs;
type
TPostRequestDataModule = class(TDataModule)
RESTClient1: TRESTClient;
RESTRequest1: TRESTRequest;
RESTResponse1: TRESTResponse;
private
{ Private declarations }
public
{ Public declarations }
function DoRequest(AServerAddress: string;
ATable: TObjectList<TStringList>): string;
end;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
{ TDataModule1 }
function TPostRequestDataModule.DoRequest(AServerAddress: string;
ATable: TObjectList<TStringList>): string;
var
LStrList: TStringList;
LString: string;
LRowsCount: integer;
LColumnsCount: integer;
LJSON: TJSONObject;
LJSONTable: TJSONArray;
LJSONRow: TJSONArray;
begin
LRowsCount := ATable.Count;
if LRowsCount > 0 then
LColumnsCount := ATable[0].Count
else
LColumnsCount := 0;
LJSON := TJSONObject.Create;
LJSON.AddPair('rows', TJSONNumber.Create(LRowsCount));
LJSON.AddPair('columns', TJSONNumber.Create(LColumnsCount));
LJSONTable := TJSONArray.Create;
for LStrList in ATable do
begin
LJSONRow := TJSONArray.Create;
for LString in LStrList do
begin
LJSONRow.Add(StrToInt(LString));
end;
LJSONTable.Add(LJSONRow);
end;
LJSON.AddPair('table', LJSONTable);
RESTClient1.BaseURL := AServerAddress;
RESTRequest1.Body.Add(LJSON);
ShowMessage(LJSON.ToString);
RESTRequest1.Execute;
Result := ((RESTResponse1.JSONValue as TJSONObject).Values['id']
as TJSONNumber).ToString;
end;
end.
|
unit uRunTimeINfoTools;
interface
uses
SysUtils, DateUtils;
type
TRunTimeINfoTools = class(TObject)
public
class function getRunTimeINfo: String;
end;
implementation
var
__startTime:TDateTime;
class function TRunTimeINfoTools.getRunTimeINfo: String;
var
lvMSec, lvRemain:Int64;
lvDay, lvHour, lvMin, lvSec:Integer;
begin
lvMSec := MilliSecondsBetween(Now(), __startTime);
lvDay := Trunc(lvMSec / MSecsPerDay);
lvRemain := lvMSec mod MSecsPerDay;
lvHour := Trunc(lvRemain / (MSecsPerSec * 60 * 60));
lvRemain := lvRemain mod (MSecsPerSec * 60 * 60);
lvMin := Trunc(lvRemain / (MSecsPerSec * 60));
lvRemain := lvRemain mod (MSecsPerSec * 60);
lvSec := Trunc(lvRemain / (MSecsPerSec));
if lvDay > 0 then
Result := Result + IntToStr(lvDay) + ' d ';
if lvHour > 0 then
Result := Result + IntToStr(lvHour) + ' h ';
if lvMin > 0 then
Result := Result + IntToStr(lvMin) + ' m ';
if lvSec > 0 then
Result := Result + IntToStr(lvSec) + ' s ';
end;
initialization
__startTime := Now();
end.
|
{@unit RLPrintDialog - Implementação do diálogo de impressão e sua classe de setup. }
unit RLPrintDialog;
interface
uses
Classes, SysUtils, Windows, Messages, Graphics, Controls, Forms, Dialogs,
StdCtrls, RLFilters, RLConsts, RLPrinters, RLTypes;
type
{@type TRLPrintDialogOptions - Opções de configuração do diálogo de impressão.
Pode ser um conjunto dos seguintes valores:
rpoPrintToFile - Mostrar a opção de impressão em arquivo;
rpoPageNums - Mostrar a seleção de páginas por intervalo;
rpoSelection - Mostrar a seleção de páginas por números específicos;
rpoWarning - Exibir mensagens de advertência;
rpoHelp - Utilizar ajuda do sistema;
rpoDisablePrintToFile - Desabilitar opção de impressão em arquivo;
rpoDisableCopies - Desabilitar a opção de número de cópias;
rpoDisablePrintInBackground - Desabilitar a opção de impressão em segundo plano.
:}
TRLPrintDialogOption =(rpoPrintToFile,rpoPageNums,rpoSelection,rpoWarning,rpoHelp,rpoDisablePrintToFile,rpoDisableCopies,rpoDisablePrintInBackground);
TRLPrintDialogOptions=set of TRLPrintDialogOption;
{/@type}
{@type TRLPrintRange - Opções para o modo seleção de páginas.
Pode ser um dos seguintes valores:
rprAllPages - Imprimir todas as páginas;
rprSelection - Imprimir as páginas de números indicados;
rprPageNums - Imprimir o intervalo de páginas indicado.
:/}
TRLPrintRange=(rprAllPages,rprSelection,rprPageNums);
const
DefaultPrintOptions=[rpoPrintToFile,rpoPageNums,rpoSelection,rpoWarning,rpoDisablePrintToFile];
type
TRLPrintDialog = class(TForm)
GroupBoxPrinter: TGroupBox;
ComboBoxPrinterNames: TComboBox;
LabelPrinterName: TLabel;
GroupBoxPages: TGroupBox;
GroupBoxCopies: TGroupBox;
ButtonOk: TButton;
ButtonCancel: TButton;
RadioButtonPagesAll: TRadioButton;
RadioButtonPagesInterval: TRadioButton;
RadioButtonPagesSelect: TRadioButton;
LabelFromPage: TLabel;
EditFromPage: TEdit;
LabelToPage: TLabel;
EditToPage: TEdit;
LabelCopies: TLabel;
EditCopies: TEdit;
CheckBoxPrintToFile: TCheckBox;
ComboBoxFilters: TComboBox;
LabelFilterName: TLabel;
LabelOptions: TLabel;
ComboBoxOptions: TComboBox;
CheckBoxPrintInBackground: TCheckBox;
procedure EditFromPageChange(Sender: TObject);
procedure ComboBoxFiltersChange(Sender: TObject);
private
{ Private declarations }
procedure LoadEditors;
procedure SaveEditors;
procedure LoadPrinterList;
procedure LoadFilterList;
procedure Init;
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(aOwner:TComponent); override;
function Execute:boolean;
end;
{@class TRLPrintDialogSetup - Opções do diálogo de impressão.
O diálogo de impressão obedecerá as configurações da instância deste componente. Com ele, é
possível estabelecer o número de cópias inicial e configurar alguns itens de comportamento do
diálogo de impressão.
@pub}
TRLPrintDialogSetup=class(TComponent)
private
{ Private declarations }
function GetCopies: integer;
function GetOptions: TRLPrintDialogOptions;
function GetPrintInBackground: boolean;
procedure SetCopies(const Value: integer);
procedure SetOptions(const Value: TRLPrintDialogOptions);
procedure SetPrintInBackground(const Value: boolean);
function GetFilter: TRLCustomPrintFilter;
function GetPrintToFile: boolean;
procedure SetFilter(const Value: TRLCustomPrintFilter);
procedure SetPrintToFile(const Value: boolean);
public
{ Public declarations }
published
{@prop Options - Opções diversas do diálogo de impressão. @links TRLPrintDialogOptions. :/}
property Options:TRLPrintDialogOptions read GetOptions write SetOptions default DefaultPrintOptions;
{@prop Copies - Indica o valor inicial para o número de cópias. :/}
property Copies:integer read GetCopies write SetCopies default 1;
{@prop PrintInBackground - Indica o valor inicial para a opção de imprimir em segundo plano. :/}
property PrintInBackground:boolean read GetPrintInBackground write SetPrintInBackground default False;
{@prop PrintToFile - Indica o estado inicial para a opção de imprimir em arquivo. :/}
property PrintToFile:boolean read GetPrintToFile write SetPrintToFile default False;
{@prop Filter - Indica o filtro a oferecer no diálogo. @links TRLCustomPrintFilter:/}
property Filter:TRLCustomPrintFilter read GetFilter write SetFilter;
end;
{/@class}
{@class TRLPrintParams - Parâmetros de impressão.}
TRLPrintParams=class(TComponent)
private
fMaxPage :integer;
fToPage :integer;
fMinPage :integer;
fFromPage :integer;
fOptions :TRLPrintDialogOptions;
fPrintRange :TRLPrintRange;
fPrintToFile :boolean;
fPrintInBackground:boolean;
fFileName :string;
fOrientation :TRLPageOrientation;
fFilter :TRLCustomPrintFilter;
fHelpContext :integer;
fCopies :integer;
//
procedure SetMaxPage(const Value: integer);
procedure SetFilter(const Value: TRLCustomPrintFilter);
procedure SetCopies(const Value: integer);
protected
{ Protected declarations }
procedure Notification(Component:TComponent; Operation:TOperation); override;
public
{ Public declarations }
constructor Create(aOwner:TComponent); override;
destructor Destroy; override;
{@method Clear - Preenche todas as props com valores default.:/}
procedure Clear;
{@method Apply - Aplica as configurações ao relatório em andamento.:/}
procedure Apply;
published
{@prop Options - Opções diversas do diálogo de impressão. @links TRLPrintDialogOptions. :/}
property Options :TRLPrintDialogOptions read fOptions write fOptions default DefaultPrintOptions;
{@prop MaxPage - Máximo para número de página final. :/}
property MaxPage :integer read fMaxPage write SetMaxPage;
{@prop MinPage - Mínimo para número de página inicial. :/}
property MinPage :integer read fMinPage write fMinPage;
{@prop FromPage - Número selecionado pelo usuário como página inicial. :/}
property FromPage :integer read fFromPage write fFromPage;
{@prop ToPage - Número selecionado pelo usuário como página final. :/}
property ToPage :integer read fToPage write fToPage;
{@prop PrintRange - Modo de seleção de páginas. @links TRLPrintRange:/}
property PrintRange :TRLPrintRange read fPrintRange write fPrintRange;
{@prop Copies - Indica o valor inicial para o número de cópias. :/}
property Copies :integer read fCopies write SetCopies default 1;
{@prop PrintToFile - Imprimir para arquivo.:/}
property PrintToFile :boolean read fPrintToFile write fPrintToFile;
{@prop PrintInBackground - Imprimir em segundo plano.:/}
property PrintInBackground:boolean read fPrintInBackground write fPrintInBackground;
{@prop FileName - Nome do arquivo a gerar.:/}
property FileName :string read fFileName write fFileName;
{@prop Orientation - Orientação do papel. @links TRLPageOrientation:/}
property Orientation :TRLPageOrientation read fOrientation write fOrientation;
{@prop Filter - Filtro atualmente selecionado. @links TRLCustomPrintFilter:/}
property Filter :TRLCustomPrintFilter read fFilter write SetFilter;
{@prop HelpContext - Contexto de ajuda.:/}
property HelpContext :integer read fHelpContext write fHelpContext;
end;
{/@class}
{@var PrintParams - Parâmetros de impressão atuais. @links TRLPrintParams:/}
var PrintParams:TRLPrintParams=nil;
{/@unit}
implementation
//{$R *.DFM}
// UTILS
function IntToEmptyStr(aInt:integer):string;
begin
if aInt=0 then
Result:=''
else
Result:=IntToStr(aInt);
end;
function EmptyStrToInt(const aStr:string):integer;
begin
Result:=StrToIntDef(aStr,0);
end;
{ TRLPrintDialog }
// OVERRIDE
constructor TRLPrintDialog.Create(aOwner:TComponent);
begin
inherited CreateNew(aOwner);
//
Init;
end;
// PUBLIC
function TRLPrintDialog.Execute:boolean;
begin
LoadPrinterList;
LoadFilterList;
LoadEditors;
ActiveControl:=ComboBoxPrinterNames;
Result:=(ShowModal=mrOk);
if Result then
SaveEditors;
end;
// PRIVATE
procedure TRLPrintDialog.Init;
begin
Left := 324;
Top := 372;
BorderStyle := bsDialog;
Caption := 'Imprimir';
ClientHeight := 267;
ClientWidth := 430;
Color := clBtnFace;
Font.Charset := DEFAULT_CHARSET;
Font.Color := clWindowText;
Font.Height := -11;
Font.Name := 'MS Sans Serif';
Font.Style := [];
Position := poScreenCenter;
Scaled := False;
PixelsPerInch := 96;
GroupBoxPrinter:=TGroupBox.Create(Self);
with GroupBoxPrinter do
begin
Name := 'GroupBoxPrinter';
Parent := Self;
Left := 8;
Top := 4;
Width := 413;
Height := 113;
Caption := ' Impressora ';
TabOrder := 0;
LabelPrinterName:=TLabel.Create(Self);
with LabelPrinterName do
begin
Name := 'LabelPrinterName';
Parent := GroupBoxPrinter;
Left := 12;
Top := 24;
Width := 31;
Height := 13;
Caption := '&Nome:';
FocusControl := ComboBoxPrinterNames;
end;
ComboBoxPrinterNames:=TComboBox.Create(Self);
with ComboBoxPrinterNames do
begin
Name := 'ComboBoxPrinterNames';
Parent := GroupBoxPrinter;
Left := 68;
Top := 20;
Width := 329;
Height := 21;
Style := csDropDownList;
ItemHeight := 13;
TabOrder := 0;
end;
LabelFilterName:=TLabel.Create(Self);
with LabelFilterName do
begin
Name := 'LabelFilterName';
Parent := GroupBoxPrinter;
Left := 12;
Top := 48;
Width := 47;
Height := 13;
Caption := 'Usar &filtro:';
FocusControl := ComboBoxPrinterNames;
end;
ComboBoxFilters:=TComboBox.Create(Self);
with ComboBoxFilters do
begin
Name := 'ComboBoxFilters';
Parent := GroupBoxPrinter;
Left := 68;
Top := 44;
Width := 177;
Height := 21;
Style := csDropDownList;
TabOrder := 1;
OnChange := ComboBoxFiltersChange;
end;
LabelOptions:=TLabel.Create(Self);
with LabelOptions do
begin
Name := 'LabelOptions';
Parent := GroupBoxPrinter;
Left := 264;
Top := 48;
Width := 40;
Height := 13;
Alignment := taRightJustify;
Caption := 'Opções:';
FocusControl := ComboBoxOptions;
end;
ComboBoxOptions:=TComboBox.Create(Self);
with ComboBoxOptions do
begin
Name := 'ComboBoxOptions';
Parent := GroupBoxPrinter;
Left := 308;
Top := 44;
Width := 89;
Height := 21;
Style := csDropDownList;
ItemHeight := 13;
TabOrder := 2;
end;
CheckBoxPrintToFile:=TCheckBox.Create(Self);
with CheckBoxPrintToFile do
begin
Name := 'CheckBoxPrintToFile';
Parent := GroupBoxPrinter;
Left := 12;
Top := 68;
Width := 325;
Height := 17;
Caption := 'Imprimir em arquivo';
TabOrder := 3;
end;
CheckBoxPrintInBackground:=TCheckBox.Create(Self);
with CheckBoxPrintInBackground do
begin
Name := 'CheckBoxPrintInBackground';
Parent := GroupBoxPrinter;
Left := 12;
Top := 88;
Width := 325;
Height := 17;
Caption := 'Imprimir em segundo plano';
TabOrder := 4;
end;
end;
GroupBoxPages:=TGroupBox.Create(Self);
with GroupBoxPages do
begin
Name := 'GroupBoxPages';
Parent := Self;
Left := 8;
Top := 120;
Width := 217;
Height := 101;
Caption := ' Intervalo de impressão ';
TabOrder := 1;
LabelFromPage:=TLabel.Create(Self);
with LabelFromPage do
begin
Name := 'LabelFromPage';
Parent := GroupBoxPages;
Left := 72;
Top := 49;
Width := 15;
Height := 13;
Caption := '&de:';
FocusControl := EditFromPage;
end;
LabelToPage:=TLabel.Create(Self);
with LabelToPage do
begin
Name := 'LabelToPage';
Parent := GroupBoxPages;
Left := 140;
Top := 49;
Width := 18;
Height := 13;
Caption := '&até:';
FocusControl := EditToPage;
end;
RadioButtonPagesAll:=TRadioButton.Create(Self);
with RadioButtonPagesAll do
begin
Name := 'RadioButtonPagesAll';
Parent := GroupBoxPages;
Left := 12;
Top := 24;
Width := 113;
Height := 17;
Caption := '&Tudo';
Checked := True;
TabOrder := 0;
TabStop := True;
end;
RadioButtonPagesInterval:=TRadioButton.Create(Self);
with RadioButtonPagesInterval do
begin
Name := 'RadioButtonPagesInterval';
Parent := GroupBoxPages;
Left := 12;
Top := 48;
Width := 61;
Height := 17;
Caption := 'Páginas';
TabOrder := 1;
end;
RadioButtonPagesSelect:=TRadioButton.Create(Self);
with RadioButtonPagesSelect do
begin
Name := 'RadioButtonPagesSelect';
Parent := GroupBoxPages;
Left := 12;
Top := 72;
Width := 73;
Height := 17;
Caption := '&Seleção';
TabOrder := 2;
end;
EditFromPage:=TEdit.Create(Self);
with EditFromPage do
begin
Name := 'EditFromPage';
Parent := GroupBoxPages;
Left := 92;
Top := 44;
Width := 41;
Height := 21;
TabStop := False;
TabOrder := 3;
Text := '1';
OnChange := EditFromPageChange;
end;
EditToPage:=TEdit.Create(Self);
with EditToPage do
begin
Name := 'EditToPage';
Parent := GroupBoxPages;
Left := 164;
Top := 44;
Width := 41;
Height := 21;
TabStop := False;
TabOrder := 4;
OnChange := EditFromPageChange;
end;
end;
GroupBoxCopies:=TGroupBox.Create(Self);
with GroupBoxCopies do
begin
Name := 'GroupBoxCopies';
Parent := Self;
Left := 236;
Top := 120;
Width := 185;
Height := 101;
Caption := ' Cópias ';
TabOrder := 2;
LabelCopies:=TLabel.Create(Self);
with LabelCopies do
begin
Name := 'LabelCopies';
Parent := GroupBoxCopies;
Left := 12;
Top := 24;
Width := 89;
Height := 13;
Caption := 'Número de &cópias:';
end;
EditCopies:=TEdit.Create(Self);
with EditCopies do
begin
Name := 'EditCopies';
Parent := GroupBoxCopies;
Left := 108;
Top := 20;
Width := 49;
Height := 21;
TabOrder := 0;
Text := '1';
end;
end;
ButtonOk:=TButton.Create(Self);
with ButtonOk do
begin
Name := 'ButtonOk';
Parent := Self;
Left := 260;
Top := 232;
Width := 75;
Height := 25;
Caption := 'OK';
Default := True;
ModalResult := 1;
TabOrder := 3;
end;
ButtonCancel:=TButton.Create(Self);
with ButtonCancel do
begin
Name := 'ButtonCancel';
Parent := Self;
Left := 344;
Top := 232;
Width := 75;
Height := 25;
Cancel := True;
Caption := 'Cancelar';
ModalResult := 2;
TabOrder := 4;
end;
//
Caption :=LS_PrintStr;
GroupBoxPrinter.Caption :=' '+LS_PrinterStr+' ';
LabelPrinterName.Caption :=LS_NameStr+':';
LabelFilterName.Caption :=LS_UseFilterStr+':';
CheckBoxPrintToFile.Caption :=LS_PrintToFileStr;
CheckBoxPrintInBackground.Caption:=LS_PrintInBackgroundStr;
GroupBoxPages.Caption :=' '+LS_PageRangeStr+' ';
LabelFromPage.Caption :=LS_RangeFromStr+':';
LabelToPage.Caption :=LS_RangeToStr+':';
RadioButtonPagesAll.Caption :=LS_AllStr;
RadioButtonPagesInterval.Caption :=LS_PagesStr;
RadioButtonPagesSelect.Caption :=LS_SelectionStr;
GroupBoxCopies.Caption :=' '+LS_CopiesStr+' ';
EditCopies.Text :='';
LabelCopies.Caption :=LS_NumberOfCopiesStr+':';
ButtonOk.Caption :=LS_OkStr;
ButtonCancel.Caption :=LS_CancelStr;
LabelOptions.Visible :=False;
ComboBoxOptions.Visible :=False;
end;
procedure TRLPrintDialog.LoadPrinterList;
var
i,j:integer;
n,p:string;
begin
ComboBoxPrinterNames.Items.Clear;
j:=0;
RLPrinter.Refresh;
for i:=0 to RLPrinter.Printers.Count-1 do
begin
n:=RLPrinter.PrinterNames[i];
if n=RLPrinter.PrinterName then
j:=i;
p:=RLPrinter.PrinterPorts[i];
if (p<>'') and (p<>n) then
n:=n+' '+LS_AtStr+' '+p;
ComboBoxPrinterNames.Items.Add(n);
end;
ComboBoxPrinterNames.ItemIndex:=j
end;
procedure TRLPrintDialog.LoadFilterList;
var
i,j,p:integer;
n:string;
f:TRLCustomPrintFilter;
begin
ComboBoxFilters.Items.Clear;
ComboBoxFilters.Items.AddObject(LS_DefaultStr,nil);
//
j:=0;
for i:=0 to ActiveFilters.Count-1 do
if TObject(ActiveFilters[i]) is TRLCustomPrintFilter then
begin
f:=TRLCustomPrintFilter(ActiveFilters[i]);
n:=f.GetDisplayLabel;
if n<>'' then
begin
p:=ComboBoxFilters.Items.AddObject(n,f);
if Assigned(PrintParams.Filter) and (PrintParams.Filter=f) then
j:=p;
end;
end;
//
ComboBoxFilters.ItemIndex:=j;
if ComboBoxFilters.Items.Count<=1 then
begin
ComboBoxFilters.Enabled:=False;
ComboBoxFilters.Color :=Self.Color;
end;
ComboBoxFiltersChange(ComboBoxFilters);
end;
procedure TRLPrintDialog.LoadEditors;
const
StateColors:array[boolean] of TColor=(clBtnFace,clWindow);
begin
case PrintParams.PrintRange of
rprAllPages : RadioButtonPagesAll.Checked :=True;
rprSelection: RadioButtonPagesSelect.Checked :=True;
rprPageNums : RadioButtonPagesInterval.Checked:=True;
end;
EditFromPage.Text :=IntToEmptyStr(PrintParams.FromPage);
EditToPage.Text :=IntToEmptyStr(PrintParams.ToPage);
EditCopies.Text :=IntToEmptyStr(PrintParams.Copies);
EditCopies.Enabled :=not (rpoDisableCopies in PrintParams.Options);
EditCopies.Color :=StateColors[EditCopies.Enabled];
CheckBoxPrintToFile.Visible :=(rpoPrintToFile in PrintParams.Options);
CheckBoxPrintToFile.Enabled :=not (rpoDisablePrintToFile in PrintParams.Options);
CheckBoxPrintToFile.Checked :=PrintParams.PrintToFile;
CheckBoxPrintInBackground.Enabled:=not (rpoDisablePrintInBackground in PrintParams.Options);
CheckBoxPrintInBackground.Checked:=PrintParams.PrintInBackground;
RadioButtonPagesInterval.Enabled :=(rpoPageNums in PrintParams.Options);
EditFromPage.Enabled :=(rpoPageNums in PrintParams.Options);
EditFromPage.Color :=StateColors[EditFromPage.Enabled];
EditToPage.Enabled :=(rpoPageNums in PrintParams.Options);
EditToPage.Color :=StateColors[EditToPage.Enabled];
RadioButtonPagesSelect.Enabled :=(rpoSelection in PrintParams.Options);
if rpoHelp in PrintParams.Options then
BorderIcons:=BorderIcons+[biHelp]
else
BorderIcons:=BorderIcons-[biHelp];
end;
procedure TRLPrintDialog.SaveEditors;
begin
if RadioButtonPagesAll.Checked then
PrintParams.PrintRange:=rprAllPages
else if RadioButtonPagesSelect.Checked then
PrintParams.PrintRange:=rprSelection
else if RadioButtonPagesInterval.Checked then
PrintParams.PrintRange:=rprPageNums;
case PrintParams.PrintRange of
rprAllPages : begin
PrintParams.FromPage:=PrintParams.MinPage;
PrintParams.ToPage :=PrintParams.MaxPage;
end;
rprSelection: begin
PrintParams.FromPage:=EmptyStrToInt(EditFromPage.Text);
PrintParams.ToPage :=PrintParams.FromPage;
end;
rprPageNums : begin
PrintParams.FromPage:=EmptyStrToInt(EditFromPage.Text);
PrintParams.ToPage :=EmptyStrToInt(EditToPage.Text);
end;
end;
PrintParams.Copies :=EmptyStrToInt(EditCopies.Text);
PrintParams.PrintToFile :=CheckBoxPrintToFile.Checked;
PrintParams.PrintInBackground:=CheckBoxPrintInBackground.Checked;
//
if ComboBoxPrinterNames.ItemIndex<>-1 then
RLPrinter.PrinterIndex:=ComboBoxPrinterNames.ItemIndex;
if ComboBoxFilters.ItemIndex<>-1 then
begin
PrintParams.Filter:=TRLCustomPrintFilter(ComboBoxFilters.Items.Objects[ComboBoxFilters.ItemIndex]);
if Assigned(PrintParams.Filter) then
PrintParams.Filter.OptionIndex:=ComboBoxOptions.ItemIndex;
end
else
PrintParams.Filter:=nil;
//
RLPrinter.Copies:=PrintParams.Copies;
end;
// EVENTS
procedure TRLPrintDialog.EditFromPageChange(Sender: TObject);
begin
if not RadioButtonPagesInterval.Checked then
RadioButtonPagesInterval.Checked:=True;
end;
procedure TRLPrintDialog.ComboBoxFiltersChange(Sender: TObject);
var
p:TRLCustomPrintFilter;
begin
if ComboBoxFilters.ItemIndex=-1 then
p:=nil
else
p:=TRLCustomPrintFilter(ComboBoxFilters.Items.Objects[ComboBoxFilters.ItemIndex]);
if (p<>nil) and (p.Options<>nil) then
begin
p.SetOrientation(PrintParams.Orientation);
LabelOptions.Caption :=p.OptionsLabel+':';
ComboBoxOptions.Items :=p.Options;
ComboBoxOptions.ItemIndex:=p.OptionIndex;
LabelOptions.Show;
ComboBoxOptions.Show;
end
else
begin
LabelOptions.Hide;
ComboBoxOptions.Hide;
end;
end;
{ TRLPrintDialogSetup }
function TRLPrintDialogSetup.GetCopies: integer;
begin
Result:=PrintParams.Copies;
end;
function TRLPrintDialogSetup.GetFilter: TRLCustomPrintFilter;
begin
Result:=PrintParams.Filter;
end;
function TRLPrintDialogSetup.GetOptions: TRLPrintDialogOptions;
begin
Result:=PrintParams.Options;
end;
function TRLPrintDialogSetup.GetPrintInBackground: boolean;
begin
Result:=PrintParams.PrintInBackground;
end;
function TRLPrintDialogSetup.GetPrintToFile: boolean;
begin
Result:=PrintParams.PrintToFile;
end;
procedure TRLPrintDialogSetup.SetCopies(const Value: integer);
begin
PrintParams.Copies:=Value;
end;
procedure TRLPrintDialogSetup.SetFilter(const Value: TRLCustomPrintFilter);
begin
PrintParams.Filter:=Value;
end;
procedure TRLPrintDialogSetup.SetOptions(const Value: TRLPrintDialogOptions);
begin
PrintParams.Options:=Value;
end;
procedure TRLPrintDialogSetup.SetPrintInBackground(const Value: boolean);
begin
PrintParams.PrintInBackground:=Value;
end;
procedure TRLPrintDialogSetup.SetPrintToFile(const Value: boolean);
begin
PrintParams.PrintToFile:=Value;
end;
{ TRLPrintParams }
constructor TRLPrintParams.Create(aOwner: TComponent);
begin
fOptions :=DefaultPrintOptions;
fPrintToFile :=False;
fPrintInBackground:=False;
fFilter :=nil;
//
inherited;
end;
destructor TRLPrintParams.Destroy;
begin
inherited;
end;
procedure TRLPrintParams.Notification(Component: TComponent;
Operation: TOperation);
begin
inherited;
//
if Operation=opRemove then
if Component=fFilter then
fFilter:=nil;
end;
procedure TRLPrintParams.Clear;
begin
fMinPage :=1;
fMaxPage :=9999;
fFromPage :=fMinPage;
fToPage :=fMaxPage;
fPrintRange :=rprAllPages;
fFileName :='';
fHelpContext:=0;
fCopies :=RLPrinter.Copies;
end;
procedure TRLPrintParams.SetMaxPage(const Value: integer);
begin
if fToPage=fMaxPage then
fToPage:=Value;
fMaxPage:=Value;
end;
procedure TRLPrintParams.SetFilter(const Value: TRLCustomPrintFilter);
begin
if Assigned(fFilter) then
fFilter.RemoveFreeNotification(Self);
fFilter:=Value;
if Assigned(fFilter) then
fFilter.FreeNotification(Self);
end;
procedure TRLPrintParams.SetCopies(const Value: integer);
begin
fCopies:=Value;
end;
procedure TRLPrintParams.Apply;
begin
RLPrinter.Copies:=fCopies;
end;
initialization
PrintParams:=TRLPrintParams.Create(nil);
finalization
PrintParams.Free;
end.
|
unit PhotoUnit;
interface
uses
Windows, Messages, Classes, Graphics, Controls, Forms, SysUtils,
Dialogs, ExtCtrls, Buttons, StdCtrls, RzStatus, RzPanel, RzSplit;
type
TPhotoForm = class(TForm)
MainPanel: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
CloseBtn: TSpeedButton;
PGrossImage1: TPanel;
GrossImage1: TImage;
PGrossImage2: TPanel;
GrossImage2: TImage;
PEmptyImage1: TPanel;
EmptyImage1: TImage;
PEmptyImage2: TPanel;
EmptyImage2: TImage;
CongealFormBtn: TSpeedButton;
activeFormBtn: TSpeedButton;
PhotoSaveDialog: TSaveDialog;
MSWeightInfo: TRzMarqueeStatus;
RzSizePanel1: TRzSizePanel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
PGrossImage3: TPanel;
GrossImage3: TImage;
PGrossImage4: TPanel;
GrossImage4: TImage;
PEmptyImage3: TPanel;
EmptyImage3: TImage;
PEmptyImage4: TPanel;
EmptyImage4: TImage;
procedure CloseBtnClick(Sender: TObject);
procedure MainPanelMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CongealFormBtnClick(Sender: TObject);
procedure activeFormBtnClick(Sender: TObject);
procedure GrossImage1DblClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure setWeightInfo(const glideNo, carNo, faHuo, shouHuo, goods, spec, gross, tare, net: string);
end;
var
PhotoForm: TPhotoForm;
implementation
{$R *.dfm}
procedure TPhotoForm.CloseBtnClick(Sender: TObject);
begin
close;
end;
procedure TPhotoForm.MainPanelMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if activeFormBtn.Visible then
if Button = mbLeft then
begin
ReleaseCapture;
PhotoForm.perform(WM_SysCommand, $F012, 0);
end;
end;
procedure TPhotoForm.CongealFormBtnClick(Sender: TObject);
begin
if CongealFormBtn.Visible then
begin
CongealFormBtn.Visible := False;
activeFormBtn.Visible := True;
end;
end;
procedure TPhotoForm.activeFormBtnClick(Sender: TObject);
begin
if activeFormBtn.Visible then
begin
activeFormBtn.Visible := False;
CongealFormBtn.Visible := True;
end;
end;
procedure TPhotoForm.GrossImage1DblClick(Sender: TObject);
begin
PhotoSaveDialog.filename := '';
if PhotoSaveDialog.Execute then
(Sender as TImage).Picture.SaveToFile(PhotoSaveDialog.filename);
end;
procedure TPhotoForm.FormShow(Sender: TObject);
begin
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE);
end;
procedure TPhotoForm.setWeightInfo(const glideNo, carNo, faHuo, shouHuo,
goods, spec, gross, tare, net: string);
begin
MSWeightInfo.Caption := Format('流水号:%s,车号:%s,发货单位:%s,收货单位:%s,'
+ '货名:%s,规格:%s,毛重:%s,皮重:%s,净重:%s',
[glideNo, carNo, faHuo, shouHuo, goods, spec, gross, tare, net]);
end;
end.
d.
|
unit LuaRemoteThread;
{$mode delphi}
interface
uses
Classes, SysUtils,lua, lualib, lauxlib,LuaHandler, LCLType;
procedure initializeLuaRemoteThread;
implementation
uses
{$ifdef darwin}macport,pthreads, macCreateRemoteThread, {$endif}
{$ifdef windows}windows,{$endif}
ProcessHandlerUnit, LuaClass, LuaObject, NewKernelHandler;
type
TRemoteThread=class
private
h: THandle;
tid: dword;
public
function getResult: integer;
function waitForThread(timeout: integer): integer;
constructor create(address: ptruint; parameter: ptruint);
published
property Result: integer read getResult;
end;
function TRemoteThread.getResult: integer;
var r: dword;
begin
if GetExitCodeThread(h, r) then
result:=r
else
result:=-1;
end;
function TRemoteThread.waitForThread(timeout: integer): integer;
begin
result:=-1; //not yet implemented
{$ifdef windows}
result:=WaitForSingleObject(h,timeout);
{$endif}
{$ifdef darwin}
if macWaitForRemoteThread(h, timeout) then
result:=WAIT_OBJECT_0
else
result:=WAIT_TIMEOUT;
{$endif}
end;
constructor TRemoteThread.create(address: ptruint; parameter: ptruint);
begin
h:=CreateRemoteThread(processhandle, nil, 0, pointer(address), pointer(parameter), 0, tid);
end;
function remotethread_waitForThread(L: PLua_State): integer; cdecl;
var
timeout: dword;
r: integer;
rt: TRemoteThread;
begin
result:=0;
if lua_Gettop(L)>=1 then
timeout:=lua_tointeger(L,1)
else
timeout:=INFINITE;
rt:=TRemoteThread(luaclass_getClassObject(L));
r:=rt.waitForThread(timeout);
if r=WAIT_OBJECT_0 then
begin
result:=2;
lua_pushboolean(L, true);
lua_pushinteger(L, rt.Result);
end
else
if r=WAIT_TIMEOUT then
begin
result:=2;
lua_pushboolean(L, false);
lua_pushinteger(L, lua_integer(-2));
end
else
begin
result:=2;
lua_pushboolean(L, false);
lua_pushinteger(L, lua_integer(-3));
end;
end;
function lua_createRemoteThread(L: PLua_State): integer; cdecl;
var
rt: TRemoteThread;
address, parameter: ptruint;
begin
result:=0;
if lua_gettop(L)>=1 then
begin
if lua_isnil(L,1) then exit;
address:=lua_toaddress(L,1);
if lua_gettop(L)>=2 then
parameter:=lua_toaddress(L,2)
else
parameter:=0;
rt:=TRemoteThread.create(address, parameter);
if rt.h=0 then
begin
rt.free;
exit;
end
else
begin
luaclass_newClass(L,rt);
result:=1;
end;
end;
end;
procedure remotethread_addMetaData(L: PLua_state; metatable: integer; userdata: integer );
begin
object_addMetaData(L, metatable, userdata);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'waitForThread', remotethread_waitForThread);
end;
procedure initializeLuaRemoteThread;
begin
lua_register(LuaVM, 'createRemoteThread', lua_createRemoteThread);
end;
initialization
luaclass_register(TRemoteThread, remotethread_addMetaData);
end.
|
unit untInifilehelper;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IniFiles, Dialogs;
type
{ IniFileHelper }
TIniFileHelper = class
private
iniFile: TIniFile;
strLocalDatabasePath: string;
nFingerReadInterval: integer;
strRemoteDatabaseIp: string;
nRemoteDatabasePort: word;
strSoundsPath:string;
nLocationId:integer;
strMasterPassword:string;
nDBUpdaterInterval:integer;
nLogUpdaterInterval:integer;
bolLocationSeminar:Boolean;
public
constructor IniFileHelper;
destructor Destroy;
function GetValue(Key: string): string;
function SetValue(key: string; Value: string): boolean;
procedure SaveSettings;
end;
implementation
{ IniFileHelper }
destructor TIniFileHelper.Destroy;
begin
iniFile.Free;
end;
constructor TIniFileHelper.IniFileHelper;
begin
iniFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) +'system.ini');
strLocalDatabasePath := iniFile.ReadString('LocalDatabase', 'Path', '\NANDFlash\DestapPanel\panel.db');
nFingerReadInterval := iniFile.ReadInteger('DatabaseProcess', 'FingerPrintReadInterval', 2000);
strRemoteDatabaseIP := iniFile.ReadString('DatabaseProcess', 'RemoteDatabaseIp', '88.248.50.202');
nRemoteDatabasePort := iniFile.ReadInteger('DatabaseProcess','RemoteDatabasePort', 13000);
strSoundsPath := iniFile.ReadString('Others','SoundsPath', '\NANDFlash\DestapPanel\Sounds');
nLocationId:=iniFile.ReadInteger('Location','LocationId', 8);
strMasterPassword:=iniFile.ReadString('Others', 'MasterPassword', '1234');
nDBUpdaterInterval:=iniFile.ReadInteger('Program', 'DBUpdaterInterval', 300000);
nLogUpdaterInterval:=iniFile.ReadInteger('Program', 'LogUpdaterInterval',360000);
bolLocationSeminar:=iniFile.ReadBool('Location', 'SeminarLocation', true);
end;
function TIniFileHelper.GetValue(Key: string): string;
begin
if (Key = 'LocalDatabasePath') then
begin
Result := strLocalDatabasePath;
end
else if Key = 'FingerPrintReadInterval' then
begin
Result := IntToStr(nFingerReadInterval);
end
else if Key = 'RemoteDatabaseIp' then
begin
Result := strRemoteDatabaseIp;
end
else if Key = 'RemoteDatabasePort' then
begin
Result := IntToStr(nRemoteDatabasePort);
end
else if Key= 'SoundsPath' then
begin
Result:=strSoundsPath;
end
else if Key= 'LocationId' then
begin
Result:=IntToStr(nLocationId);
end
else if Key= 'MasterPassword' then
begin
Result:=strMasterPassword;
end
else if Key='DBUpdaterInterval' then
begin
Result:=IntToStr(nDBUpdaterInterval);
end
else if Key='LogUpdaterInterval' then
begin
Result:=IntToStr(nLogUpdaterInterval);
end
else if Key='SeminarLocation' then
begin
Result:=BoolToStr(bolLocationSeminar);
end
else
raise Exception.Create('İni Dosyasında Aranılan değer bulunamadı');
end;
function TIniFileHelper.SetValue(key: string; Value: string): boolean;
begin
if (Key = 'LocalDatabasePath') then
begin
strLocalDatabasePath := Value;
end
else if Key = 'FingerPrintReadInterval' then
begin
nFingerReadInterval := StrToInt(Value);
end
else if Key = 'RemoteDatabaseIp' then
begin
strRemoteDatabaseIp := Value;
end
else if Key = 'RemoteDatabasePort' then
begin
nRemoteDatabasePort := StrToInt(Value);
end
else if Key= 'SoundsPath' then
begin
strSoundsPath:=Value;
end
else if Key= 'LocationId' then
begin
nLocationId:=StrToInt(Value);
end
else if Key= 'MasterPassword' then
begin
strMasterPassword:=Value;
end
else if Key='DBUpdaterInterval' then
begin
nDBUpdaterInterval:=StrToInt(Value);
end
else if Key='LogUpdaterInterval' then
begin
nLogUpdaterInterval:=StrToInt(Value);
end
else if Key='SeminarLocation' then
begin
bolLocationSeminar:=StrToBool(Value);
end;
end;
procedure TIniFileHelper.SaveSettings;
begin
iniFile.WriteString('LocalDatabase', 'Path', strLocalDatabasePath);
iniFile.WriteInteger('DatabaseProcess', 'FingerPrintReadInterval', nFingerReadInterval);
iniFile.WriteString('DatabaseProcess', 'RemoteDatabaseIp', strRemoteDatabaseIp);
iniFile.WriteInteger('DatabaseProcess', 'RemoteDatabasePort', nRemoteDatabasePort);
iniFile.WriteString('Others','SoundsPath', strSoundsPath );
iniFile.WriteInteger('Location', 'LocationId',nLocationId );
iniFile.WriteString('Others', 'MasterPassword', strMasterPassword);
iniFile.WriteInteger('Program', 'DBUpdaterInterval', nDBUpdaterInterval);
iniFile.WriteInteger('Program', 'LogUpdaterInterval', nLogUpdaterInterval);
iniFile.WriteBool('Location', 'SeminarLocation', bolLocationSeminar);
end;
end.
|
unit ValueSetEditorCore;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
uses
SysUtils, Classes, IniFiles, ZLib, Math, RegExpr,
Dialogs,
SystemSupport, StringSupport, FileSupport, ShellSupport, GuidSupport, EncodeSupport,
AdvObjects, AdvStringMatches, AdvStringObjectMatches, AdvObjectLists, AdvBuffers, AdvWinInetClients, AdvMemories, AdvFiles, AdvGenerics,
MsXmlParser, IdUri, IdHTTP, AdvJSON,
FHIRBase, FHIRTypes, FHIRResources, FHIRParser, FHIRParserBase, FHIRConstants,
FHIRUtilities, FHIRClient;
Const
UIState_Welcome = 0;
UIState_Choose = 1;
UIState_Edit = 2;
ExpressionProperty = 'http://healthintersections.com.au/valueseteditor/expression';
MASTER_SERVER = 'http://fhir2.healthintersections.com.au/open';
CS_LIST = 'uri:uuid:185E783F-BE0D-451E-BEC1-2C92971BC762';
VS_LIST = 'uri:uuid:3BCEFFA8-4FF0-4EAC-9328-1B671CEC0B55';
Type
ENoServer = class (Exception);
TValidationOutcomeKind = (voOK, voMissing, voError, voWarning, voHint);
TValidationOutcome = record
kind : TValidationOutcomeKind;
msg : String;
end;
TClosureDirection = (cdNull, cdSubsumes, cdSubsumed);
TClosureTableRecordSource = class (TFHIRCoding)
private
FTargets: TAdvList<TFHIRCoding>;
public
constructor Create; override;
destructor Destroy; override;
function link : TClosureTableRecordSource; overload;
property targets : TAdvList<TFHIRCoding> read FTargets;
procedure add(uri, code : String);
end;
TClosureTableRecord = class (TAdvObject)
private
FConcepts: TAdvList<TFHIRCoding>;
FMaps : TAdvList<TClosureTableRecordSource>;
FId: string;
FName: String;
FFilename : String;
FVersion: String;
function GetLinks(row, col: integer): TClosureDirection;
function hasMap(src, tgt : TFHIRCoding) : boolean;
procedure save;
procedure process(cm : TFHIRConceptMap);
function getSource(uri, code : String) : TClosureTableRecordSource;
function GetMapCount: integer;
public
constructor create; overload; override;
constructor create(filename : String); overload;
constructor create(filename, id, name : String); overload;
destructor Destroy; override;
function link : TClosureTableRecord; overload;
property id : string read FId write FId;
property name : String read FName write FName;
property version : String read FVersion write FVersion;
property concepts : TAdvList<TFHIRCoding> read FConcepts;
property maps : TAdvList<TClosureTableRecordSource> read FMaps;
property links[row, col: integer] : TClosureDirection read GetLinks;
property mapCount : integer read GetMapCount;
end;
TValidationOutcomeMark = class (TAdvObject)
private
FMessage: string;
FObj: TFHIRElement;
FField: integer;
FKind: TValidationOutcomeKind;
procedure SetObj(const Value: TFHIRElement);
public
destructor destroy; override;
property obj : TFHIRElement read FObj write SetObj;
property field : integer read FField write FField;
property kind : TValidationOutcomeKind read FKind write FKind;
property message : string read FMessage write FMessage;
end;
TValidationOutcomeMarkList = class (TAdvObjectList)
private
function GetMark(index: integer): TValidationOutcomeMark;
protected
Function CompareByElement(pA, pB : Pointer) : Integer;
function itemClass : TAdvObjectClass; override;
public
Constructor Create; Override;
property mark[index : integer] : TValidationOutcomeMark read GetMark; default;
function GetByElement(elem : TFHIRElement; field : integer) : TValidationOutcomeMark;
procedure AddElement(elem : TFHIRElement; field : Integer; kind : TValidationOutcomeKind; message : String);
end;
TValueSetEditorCoreSettings = Class (TAdvObject)
private
ini : TIniFile;
FMRUList : TStringList;
function ValuesetListPath : string;
function ValuesetItemPath : string;
procedure SetServerURL(const Value: String);
function GetServerURL: String;
function GetValueSetId: String;
procedure SetValueSetId(const Value: String);
function GetvalueSetFilename: String;
procedure SetvalueSetFilename(const Value: String);
function GetVersionHigh: integer;
procedure SetVersionHigh(const Value: integer);
function GetFormatIsJson: boolean;
procedure SetFormatIsJson(const Value: boolean);
function GetFilter: String;
procedure SetFilter(const Value: String);
function GetWindowHeight: Integer;
function GetWindowLeft: Integer;
function GetWindowState: Integer;
function GetWindowTop: Integer;
function GetWindowWidth: Integer;
procedure SetWindowHeight(const Value: Integer);
procedure SetWindowLeft(const Value: Integer);
procedure SetWindowState(const Value: Integer);
procedure SetWindowTop(const Value: Integer);
procedure SetWindowWidth(const Value: Integer);
function GetDocoVisible: boolean;
procedure SetDocoVisible(const Value: boolean);
function GetHasViewedWelcomeScreen: boolean;
procedure SetHasViewedWelcomeScreen(const Value: boolean);
function GetValueSetURL: String;
procedure SetValueSetURL(const Value: String);
function GetServerFilter: String;
procedure SetServerFilter(const Value: String);
property valueSetFilename : String read GetvalueSetFilename write SetvalueSetFilename;
property valueSetServer : String read GetValueSetURL write SetValueSetURL;
property valueSetId : String read GetValueSetId write SetValueSetId;
property VersionHigh : integer read GetVersionHigh write SetVersionHigh;
Property FormatIsJson : boolean read GetFormatIsJson write SetFormatIsJson;
public
Constructor Create; Override;
Destructor Destroy; Override;
// mru list
procedure mru(src : String);
property MRUList : TStringList read FMRUList;
// window
function hasWindowState : Boolean;
Property WindowState : Integer read GetWindowState write SetWindowState;
Property WindowLeft : Integer read GetWindowLeft write SetWindowLeft;
Property WindowWidth : Integer read GetWindowWidth write SetWindowWidth;
Property WindowTop : Integer read GetWindowTop write SetWindowTop;
Property WindowHeight : Integer read GetWindowHeight write SetWindowHeight;
property DocoVisible : boolean read GetDocoVisible write SetDocoVisible;
property HasViewedWelcomeScreen : boolean read GetHasViewedWelcomeScreen write SetHasViewedWelcomeScreen;
// servers
function ServerCount : integer;
procedure getServer(index : integer; var name, address, username, password : String; var doesSearch : boolean);
procedure AddServer(name, address, username, password : String; doesSearch : boolean);
procedure UpdateServer(name, address, username, password : String);
procedure DeleteServer(name : String);
property WorkingServer : String read GetServerURL write SetServerURL;
// choice browser
function columnWidth(tree, name : string; default: integer) : integer;
procedure setColumnWidth(tree, name : string; value : integer);
function ValueSetNew : boolean;
// expansion
Property Filter : String read GetFilter write SetFilter;
Property ServerFilter : String read GetServerFilter write SetServerFilter;
End;
TValueSetEditorCodeSystemCodeStatus = (cscsUnknown, cscsOK, cscsPending, cscsInvalidSystem);
TValueSetEditorCodeSystem = class (TAdvObject)
public
function getCodeStatus(code : String; var msg : String) : TValueSetEditorCodeSystemCodeStatus; virtual;
function isWrongDisplay(code : String; display : String) : boolean; virtual;
function getDisplay(code : String; var display : String) : boolean; virtual;
function filterPropertyOK(prop : String; op : TFhirFilterOperatorEnum; value : String) : boolean; virtual;
function filterOperationOK(prop : String; op : TFhirFilterOperatorEnum; value : String) : boolean; virtual;
function filterValueOK(prop : String; op : TFhirFilterOperatorEnum; value : String) : boolean; virtual;
end;
TValueSetEditorCodeSystemValueSet = class (TValueSetEditorCodeSystem)
private
FConceptList : TFhirValueSetCodeSystemConceptList;
FCase : boolean;
function InList(list: TFhirValueSetCodeSystemConceptList; code: String): TFhirValueSetCodeSystemConcept;
public
constructor create(vs : TFhirValueSet); overload;
destructor destroy; override;
function getCodeStatus(code : String; var msg : String) : TValueSetEditorCodeSystemCodeStatus; override;
function isWrongDisplay(code : String; display : String) : boolean; override;
function getDisplay(code : String; var display : String) : boolean; override;
function filterPropertyOK(prop : String; op : TFhirFilterOperatorEnum; value : String) : boolean; override;
function filterOperationOK(prop : String; op : TFhirFilterOperatorEnum; value : String) : boolean; override;
function filterValueOK(prop : String; op : TFhirFilterOperatorEnum; value : String) : boolean; override;
end;
TServerCodeSystemCacheItem = class (TAdvObject)
private
status : TValueSetEditorCodeSystemCodeStatus;
message : String;
displays : TStringList;
public
constructor Create; overload; override;
constructor Create(status : TValueSetEditorCodeSystemCodeStatus; message : String); overload;
destructor Destroy; override;
end;
TServerCodeSystem = class (TValueSetEditorCodeSystem)
private
FSystem : String;
FClient : TFhirHTTPClient;
FCache : TAdvStringObjectMatch;
FFilename : String;
function HasCache(code : String; var item : TServerCodeSystemCacheItem) : boolean;
procedure loadCode(code : String; var item : TServerCodeSystemCacheItem);
procedure Load;
procedure Save;
public
constructor create(uri : String; url : String; filename : String); overload; virtual;
destructor Destroy; override;
function getCodeStatus(code : String; var msg : String) : TValueSetEditorCodeSystemCodeStatus; override;
function isWrongDisplay(code : String; display : String) : boolean; override;
function getDisplay(code : String; var display : String) : boolean; override;
function filterPropertyOK(prop : String; op : TFhirFilterOperatorEnum; value : String) : boolean; override;
function filterOperationOK(prop : String; op : TFhirFilterOperatorEnum; value : String) : boolean; override;
function filterValueOK(prop : String; op : TFhirFilterOperatorEnum; value : String) : boolean; override;
end;
TValueSetEditorServerCache = class (TAdvObject)
private
FLoaded : boolean;
FDoesSearch : boolean;
FName: String;
FUrl : String;
Fusername : String;
Fpassword : String;
FLastUpdated : String;
FKey : integer;
ini : TInifile;
Flist : TFHIRValueSetList;
valuesets : TAdvStringObjectMatch; // uri and actual value set (might be a summary)
FCodeSystems : TAdvStringObjectMatch; // uri and actual value set (might be a summary)
sortedCodesystems : TStringList;
sortedValueSets : TStringList;
specialCodeSystems : TAdvStringObjectMatch;
closures : TAdvMap<TClosureTableRecord>;
procedure SeeValueset(vs : TFhirValueSet; isSummary, loading : boolean);
function LoadFullCodeSystem(uri : String) : TFhirValueSet;
procedure CheckConnection;
procedure SynchroniseServer(event : TFhirHTTPClientStatusEvent);
procedure UpdateFromServer(event : TFhirHTTPClientStatusEvent);
public
Constructor Create(name, url, username, password : String; doesSearch : boolean; key : integer);
destructor Destroy; override;
Function Link : TValueSetEditorServerCache; overload;
procedure checkLoad(event : TFhirHTTPClientStatusEvent; null : String);
procedure load(event : TFhirHTTPClientStatusEvent = nil);
procedure update(event : TFhirHTTPClientStatusEvent; null : String);
procedure save;
function base : String;
Property URL : string read FUrl write FUrl;
property List : TFHIRValueSetList read FList;
Property Name : String read FName;
Property CodeSystems : TAdvStringObjectMatch read FCodeSystems;
Property LastUpdated : String read FLastUpdated;
procedure loadClosures(list : TStrings);
procedure addClosure(s : String);
procedure ResetClosure(name : String);
procedure updateClosure(name : String);
procedure AddToClosure(name : String; coding : TFhirCoding);
function expand(url, filter : String; count : integer; allowIncomplete : boolean): TFHIRValueSet;
property username : String read Fusername write Fusername;
property password : String read Fpassword write Fpassword;
end;
TValueSetEditorContext = class (TAdvObject)
private
FSettings: TValueSetEditorCoreSettings;
FWorkingServer : TValueSetEditorServerCache;
FServers : TAdvList<TValueSetEditorServerCache>;
FValueSet : TFhirValueSet; // working value set
FCodeSystemContexts : TAdvStringObjectMatch;
FVersionCount : integer;
FOnStateChange: TNotifyEvent;
FLastCommitSource : String;
FDirty: boolean;
FExpansion: TFhirValueSetExpansion;
FOnPreview: TNotifyEvent;
FPreview: TFhirValueSetExpansion;
FExpansions : TAdvStringObjectMatch;
FValidationErrors : TValidationOutcomeMarkList;
FOnValidate: TNotifyEvent;
FServerFilter: String;
Procedure LoadServers;
Procedure CompressFile(source, dest : String);
Procedure DeCompressFile(source, dest : String);
procedure openValueSet(vs : TFhirValueSet);
procedure GetDefinedCodesList(context : TFhirValueSetCodeSystemConceptList; list : TStrings);
procedure GetDefinedCodeDisplayList(context : TFhirValueSetCodeSystemConceptList; list : TStrings; code : String);
function FetchValueSetBySystem(uri : String) : TFhirValueSet;
procedure LoadFromFile(fn : String);
procedure ClearFutureVersions;
procedure ClearAllVersions;
function makeOutcome(kind : TValidationOutcomeKind; msg : String) : TValidationOutcome;
procedure InternalValidation;
procedure validateDefine;
procedure validateInclude(inc : TFhirValueSetComposeInclude);
procedure validateDefineConcepts(ts: TStringlist; list: TFhirValueSetCodeSystemConceptList);
procedure SetServerFilter(const Value: String);
public
Constructor Create; Override;
Destructor Destroy; Override;
Function Link : TValueSetEditorContext; overload;
Property Settings : TValueSetEditorCoreSettings read FSettings;
Property OnStateChange : TNotifyEvent read FOnStateChange write FOnStateChange;
Property OnValidate : TNotifyEvent read FOnValidate write FOnValidate;
// general
Function UIState : integer;
Property Dirty : boolean read FDirty;
// registering a server
function CheckServer(url : String; var msg : String; var doesSearch : boolean) : boolean;
procedure SetNominatedServer(url : String);
Property WorkingServer : TValueSetEditorServerCache read FWorkingServer;
Property Servers : TAdvList<TValueSetEditorServerCache> read FServers;
procedure AddServer(name, address, username, password : String; doesSearch : boolean);
procedure DeleteServer(name : String);
procedure UpdateServer(server : TValueSetEditorServerCache);
// opening a value set
procedure NewValueset;
procedure openFromFile(event : TFhirHTTPClientStatusEvent; fn : String);
procedure openFromServer(event : TFhirHTTPClientStatusEvent; id : String);
procedure openFromURL(event : TFhirHTTPClientStatusEvent; url : String);
// editing value set
Property ValueSet : TFhirValueSet read FValueSet;
function EditName : String;
procedure Commit(source : string);
function CanUndo : boolean;
Function CanRedo : boolean;
Function CanSave : boolean;
function Undo : boolean;
Function Redo : boolean;
procedure UndoBreak;
procedure Save;
procedure saveAsFile(fn : String);
procedure SaveAsServerNew;
procedure Close;
// editor grid support
function NameCodeSystem(uri : String) : String;
procedure GetList(context : String; list : TStrings);
procedure PrepareSystemContext(uri : String; version : String); // the editor is going to start editing in the named URI - be ready to provide code system support
function NameValueSet(uri : String) : String;
function GetCodeSystemValidator(uri : String) : TValueSetEditorCodeSystem;
function TryGetDisplay(system, code : String) : String;
// expansion
property Expansion : TFhirValueSetExpansion read FExpansion;
procedure Expand(event : TFhirHTTPClientStatusEvent; text : String);
procedure GetPreview(uri : String);
property Preview : TFhirValueSetExpansion read FPreview;
property OnPreview : TNotifyEvent read FOnPreview write FOnPreview;
// validation:
function validateIdentifier(value : string) : TValidationOutcome;
function validateSystem(value : string) : TValidationOutcome;
function validateImport(value : string) : TValidationOutcome;
function validateReference(value : string) : TValidationOutcome;
function validateName(value : string) : TValidationOutcome;
function validateDescription(value: string): TValidationOutcome;
function checkValidation(elem : TFHIRElement; field : integer; var kind : TValidationOutcomeKind; var msg : String): boolean;
// closures
procedure loadClosures(list : TStrings);
procedure AddClosure(name : String);
procedure ResetClosure(name : String);
procedure UpdateClosure(name : String);
procedure AddToClosure(name : String; coding : TFhirCoding);
function ClosureDetails(name : String): TClosureTableRecord;
end;
function IsURL(s : String) : boolean;
implementation
{ TValueSetEditorContext }
procedure TValueSetEditorContext.AddClosure(name: String);
begin
WorkingServer.AddClosure(name);
end;
procedure TValueSetEditorContext.AddServer(name, address, username, password: String; doesSearch : boolean);
var
server : TValueSetEditorServerCache;
begin
Settings.AddServer(name, address, username, password, doesSearch);
server := TValueSetEditorServerCache.Create(name, address, username, password, doesSearch, FServers.Count - 1);
try
server.load(nil);
FServers.Add(server.Link);
finally
server.Free;
end;
end;
procedure TValueSetEditorContext.AddToClosure(name: String; coding: TFhirCoding);
begin
WorkingServer.AddToClosure(name, coding);
end;
function TValueSetEditorContext.CanRedo: boolean;
begin
result := FileExists(Settings.ValuesetItemPath+'-'+inttostr(FVersionCount+1)+'.z');
end;
function TValueSetEditorContext.CanSave: boolean;
begin
result := (Settings.valueSetFilename <> '') or (Settings.valueSetId <> '');
end;
function TValueSetEditorContext.CanUndo: boolean;
begin
result := FileExists(Settings.ValuesetItemPath+'-'+inttostr(FVersionCount-1)+'.z')
end;
function TValueSetEditorContext.CheckServer(url: String; var msg: String; var doesSearch : boolean): boolean;
var
client : TFhirHTTPClient;
conf : TFhirConformance;
rest : TFhirConformanceRestResource;
begin
result := false;
client := TFhirHTTPClient.create(nil, url, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
try
conf := client.conformance(false);
try
if (conf.fhirVersion <> FHIR_GENERATED_VERSION) then
raise Exception.Create('The server is the wrong version. Expected '+FHIR_GENERATED_VERSION+', found '+conf.fhirVersion);
rest := conf.rest(frtValueset);
if (rest = nil) {or (rest.interaction(TypeRestfulInteractionSearchType) = nil) }or (rest.interaction(TypeRestfulInteractionRead) = nil) then
raise Exception.Create('The server does not support the required opeerations for value sets');
doesSearch := rest.interaction(TypeRestfulInteractionSearchType) <> nil;
result := true;
finally
conf.free;
end;
except
on e: Exception do
msg := e.Message;
end;
finally
client.Free;
end;
end;
function TValueSetEditorContext.checkValidation(elem: TFHIRElement; field: integer; var kind: TValidationOutcomeKind; var msg: String): boolean;
var
mark : TValidationOutcomeMark;
begin
mark := FValidationErrors.GetByElement(elem, field);
result := mark <> nil;
if result then
begin
kind := mark.kind;
msg := mark.message;
end;
end;
procedure TValueSetEditorContext.ClearAllVersions;
var
i : integer;
begin
for I := 1 to Settings.VersionHigh do
if FileExists(Settings.ValuesetItemPath+'-'+inttostr(i)+'.z') then
DeleteFile(Settings.ValuesetItemPath+'-'+inttostr(i)+'.z');
end;
procedure TValueSetEditorContext.ClearFutureVersions;
var
i : integer;
begin
for I := FVersionCount + 1 to Settings.VersionHigh do
if FileExists(Settings.ValuesetItemPath+'-'+inttostr(i)+'.z') then
DeleteFile(Settings.ValuesetItemPath+'-'+inttostr(i)+'.z');
end;
procedure TValueSetEditorContext.Close;
begin
FValueSet.Free;
FValueset := nil;
ClearAllVersions;
DeleteFile(Settings.ValuesetItemPath);
FVersionCount := 1;
FSettings.valueSetId := '';
FSettings.valueSetFilename := '';
FSettings.VersionHigh := 1;
FSettings.FormatIsJson := false;
FLastCommitSource := '';
FDirty := False;
if assigned(FOnStateChange) then
FOnStateChange(self);
end;
function TValueSetEditorContext.ClosureDetails(name: String): TClosureTableRecord;
begin
if WorkingServer.closures.ContainsKey(name) then
result := WorkingServer.closures[name]
else
result := nil;
end;
procedure TValueSetEditorContext.commit(source : string);
var
c : TFHIRJsonComposer;
f : TFileStream;
begin
ClearFutureVersions;
// current copy
f := TFileStream.Create(Settings.ValuesetItemPath, fmCreate);
try
c := TFHIRJsonComposer.Create(nil, 'en');
try
c.Compose(f, FValueSet, true);
finally
c.Free;
end;
finally
f.free;
end;
FDirty := true;
// now, create the redo copy
if (source = '') or (source <> FLastCommitSource) then
inc(FVersionCount); // else we just keep updating this version
FLastCommitSource := source;
Settings.VersionHigh := Max(Settings.VersionHigh, FVersionCount);
CompressFile(Settings.ValuesetItemPath, Settings.ValuesetItemPath+'-'+inttostr(FVersionCount)+'.z');
if Assigned(FOnStateChange) then
FOnStateChange(self);
InternalValidation;
if Assigned(FOnValidate) then
FOnValidate(self);
end;
procedure TValueSetEditorContext.CompressFile(source, dest: String);
var
LInput, LOutput: TFileStream;
LZip: TZCompressionStream;
begin
LOutput := TFileStream.Create(dest, fmCreate);
try
LInput := TFileStream.Create(source, fmOpenRead);
try
LZip := TZCompressionStream.Create(clMax, LOutput);
try
LZip.CopyFrom(LInput, LInput.Size);
finally
LZip.Free;
end;
finally
LInput.Free;
end;
finally
LOutput.Free;
end;
end;
function TValueSetEditorContext.Undo: boolean;
begin
result := CanUndo;
if result then
begin
DecompressFile(Settings.ValuesetItemPath+'-'+inttostr(FVersionCount-1)+'.z', Settings.ValuesetItemPath);
dec(FVersionCount);
LoadFromFile(Settings.ValuesetItemPath);
if FVersionCount = 0 then
FDirty := false;
FLastCommitSource := '';
if Assigned(FOnStateChange) then
FOnStateChange(self);
InternalValidation;
if Assigned(FOnValidate) then
FOnValidate(self);
end;
end;
procedure TValueSetEditorContext.UndoBreak;
begin
FLastCommitSource := '';
end;
procedure TValueSetEditorContext.UpdateClosure(name: String);
begin
WorkingServer.UpdateClosure(name);
end;
procedure TValueSetEditorContext.UpdateServer(server: TValueSetEditorServerCache);
begin
FSettings.updateServer(server.Name, server.URL, server.username, server.password);
end;
function TValueSetEditorContext.Redo: boolean;
begin
result := CanRedo;
if result then
begin
DecompressFile(Settings.ValuesetItemPath+'-'+inttostr(FVersionCount+1)+'.z', Settings.ValuesetItemPath);
inc(FVersionCount);
LoadFromFile(Settings.ValuesetItemPath);
FDirty := true;
FLastCommitSource := '';
if Assigned(FOnStateChange) then
FOnStateChange(self);
InternalValidation;
if Assigned(FOnValidate) then
FOnValidate(self);
end;
end;
procedure TValueSetEditorContext.ResetClosure(name: String);
begin
WorkingServer.ResetClosure(name);
end;
procedure TValueSetEditorContext.Save;
var
c : TFHIRComposer;
f : TFileStream;
client : TFhirHTTPClient;
begin
FValueSet.date := NowLocal;
if (Settings.valueSetFilename <> '') then
begin
f := TFileStream.create(Settings.valueSetFilename, fmCreate);
try
if Settings.FormatIsJson then
c := TFHIRJsonComposer.Create(nil, 'en')
else
c := TFHIRXmlComposer.Create(nil, 'en');
try
c.Compose(f, FValueSet, true);
finally
c.free;
end;
finally
f.Free;
end;
end
else
begin
if (Settings.valueSetId = '') then
raise Exception.Create('Cannot save to server as value set id has been lost');
client := TFhirHTTPClient.create(nil, Settings.valueSetServer, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
FValueSet.id := Settings.valueSetId;
client.updateResource(FValueSet);
finally
client.free;
end;
end;
FDirty := false;
if assigned(FOnStateChange) then
FOnStateChange(self);
end;
procedure TValueSetEditorContext.saveAsFile(fn: String);
begin
Settings.valueSetFilename := fn;
Settings.FormatIsJson := fn.EndsWith('.json');
Save;
end;
procedure TValueSetEditorContext.SaveAsServerNew;
var
client : TFhirHTTPClient;
vs : TFHIRValueSet;
id : String;
begin
FValueSet.date := NowLocal;
client := TFhirHTTPClient.create(nil, Settings.WorkingServer, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
vs := client.createResource(FValueSet, id) as TFhirValueSet;
try
Settings.valueSetId := id;
FValueSet.free;
FValueSet := vs.Link;
finally
vs.Free;
end;
finally
client.free;
end;
end;
procedure TValueSetEditorServerCache.UpdateFromServer(event : TFhirHTTPClientStatusEvent);
var
client : TFhirHTTPClient;
params : TAdvStringMatch;
list : TFHIRBundle;
i : integer;
vs : TFhirValueSet;
begin
client := TFhirHTTPClient.create(nil, url, true);
try
client.UseIndy := true;
client.OnClientStatus := Event;
params := TAdvStringMatch.Create;
try
params.Add('_since', FLastUpdated);
params.Add('_count', '50');
event(self, 'Fetch Valuesets');
list := client.historyType(frtValueset, true, params);
try
for i := 0 to list.entryList.Count -1 do
begin
event(self, 'Process Valueset '+inttostr(i+1)+' if '+inttostr(list.entryList.Count));
SeeValueset(list.entryList[i].resource as TFhirValueSet, false, false);
end;
// FServer.FLastUpdated := ;
finally
list.Free;
end;
save;
finally
params.free;
end;
finally
client.Free;
end;
end;
procedure TValueSetEditorServerCache.SynchroniseServer(event : TFhirHTTPClientStatusEvent);
var
client : TFhirHTTPClient;
params : TAdvStringMatch;
list : TFHIRBundle;
i : integer;
vs : TFhirValueSet;
begin
client := TFhirHTTPClient.create(nil, url, true);
try
client.UseIndy := true;
client.OnClientStatus := event;
params := TAdvStringMatch.Create;
try
params.Add('_summary', 'true');
params.Add('_count', 'all');
event(self, 'Fetch Valuesets');
list := client.search(frtValueset, true, params);
try
for i := 0 to list.entryList.Count - 1 do
begin
event(self, 'Process Valueset '+inttostr(i+1)+' if '+inttostr(list.entryList.Count));
SeeValueset(list.entryList[i].resource as TFhirValueSet, true, false);
end;
FLastUpdated := list.meta.lastUpdated.AsXML;
finally
list.Free;
end;
save;
finally
params.free;
end;
finally
client.Free;
end;
end;
procedure TValueSetEditorServerCache.update(event: TFhirHTTPClientStatusEvent; null: String);
begin
if not FLoaded then
load(event);
if FLastUpdated = '' then
SynchroniseServer(event)
else
UpdateFromServer(event);
end;
procedure TValueSetEditorServerCache.updateClosure(name: String);
var
client : TFhirHTTPClient;
pin : TFhirParameters;
pout : TFhirResource;
ct : TClosureTableRecord;
begin
ct := closures[name];
client := TFhirHTTPClient.create(nil, url, true);
try
client.UseIndy := true;
pin := TFhirParameters.Create;
try
pin.AddParameter('name', ct.id);
pin.AddParameter('version', ct.version);
pout := client.operation(frtConceptMap, 'closure', pin);
try
if pout is TFHIRConceptMap then
ct.process(pout as TFHIRConceptMap)
else
raise Exception.Create('Unexpected response from server');
finally
pout.Free;
end;
finally
pin.Free;
end;
finally
client.Free;
end;
ct.save;
end;
function TValueSetEditorContext.TryGetDisplay(system, code: String): String;
var
cs : TValueSetEditorCodeSystem;
begin
cs := GetCodeSystemValidator(system);
if (cs = nil) or not cs.getDisplay(code, result) then
result := '??';
end;
procedure TValueSetEditorContext.SetNominatedServer(url : String);
var
i, t : integer;
begin
t := -1;
for i := 0 to FServers.Count - 1 do
if FServers[i].FUrl = url then
t := i;
if (t = -1) then
raise Exception.Create('URL not registered as a server: '+url);
FWorkingServer.Free;
FWorkingServer := Servers[t].Link;
Settings.WorkingServer := FWorkingServer.FUrl;
end;
procedure TValueSetEditorContext.SetServerFilter(const Value: String);
begin
FServerFilter := Value;
end;
constructor TValueSetEditorContext.Create;
var
p : TFHIRJsonParser;
f : TFileStream;
list : TStringList;
s : String;
begin
inherited;
FCodeSystemContexts := TAdvStringObjectMatch.create;
FCodeSystemContexts.Forced := true;
FCodeSystemContexts.PreventDuplicates;
FValidationErrors := TValidationOutcomeMarkList.create;
FSettings := TValueSetEditorCoreSettings.Create;
if Settings.ServerCount = 0 then
if FileExists('C:\work\fhirserver\Exec\fhir.ini') then
Settings.AddServer('Local Development Server', 'http://local.healthintersections.com.au:960/open', '', '', true)
else
Settings.AddServer('Health Intersections General Server', 'http://fhir-dev.healthintersections.com.au/open', '', '', true);
FServers := TAdvList<TValueSetEditorServerCache>.create;
loadServers;
if FSettings.WorkingServer <> '' then
SetNominatedServer(FSettings.WorkingServer)
else
SetNominatedServer(Servers[0].URL);
FExpansions := TAdvStringObjectMatch.create;
ClearAllVersions;
FVersionCount := 0;
if FileExists(FSettings.ValuesetItemPath) then
begin
try
LoadFromFile(FSettings.ValuesetItemPath);
Commit('load');
except
showmessage('unable to load previous valueset');
end;
end
else
FValueSet := nil;
FDirty := False;
end;
procedure TValueSetEditorContext.DeCompressFile(source, dest: String);
var
LInput, LOutput: TFileStream;
LUnZip: TZDecompressionStream;
begin
LOutput := TFileStream.Create(dest, fmCreate);
try
LInput := TFileStream.Create(source, fmOpenRead);
try
LUnZip := TZDecompressionStream.Create(LInput);
try
LOutput.CopyFrom(LUnZip, 0);
finally
LUnZip.Free;
end;
finally
LInput.Free;
end;
finally
LOutput.Free;
end;
end;
procedure TValueSetEditorContext.DeleteServer(name: String);
var
i : integer;
done : boolean;
begin
done := false;
for i := FServers.Count -1 downto 0 do
if FServers[i].Name = name then
begin
FServers.Delete(i);
done := true;
end;
if not done then
raise Exception.Create('Server not found');
Settings.DeleteServer(name);
end;
destructor TValueSetEditorContext.Destroy;
begin
FWorkingServer.Free;
FServers.Free;
FValidationErrors.Free;
FExpansions.Free;
FValueSet.Free;
FCodeSystemContexts.Free;
FSettings.Free;
FExpansion.Free;
FPreview.Free;
inherited;
end;
procedure TValueSetEditorContext.LoadFromFile(fn : String);
var
p : TFHIRJsonParser;
f : TFileStream;
begin
f := TFileStream.Create(FSettings.ValuesetItemPath, fmOpenRead + fmShareDenyWrite);
try
p := TFHIRJsonParser.Create(nil, 'en');
try
p.source := f;
p.Parse;
FValueSet.Free;
FValueSet := p.resource.Link as TFhirValueSet;
finally
p.free
end;
finally
f.Free;
end;
end;
procedure TValueSetEditorContext.LoadServers;
var
i : integer;
name, address, username, password : String;
doesSearch : boolean;
server : TValueSetEditorServerCache;
begin
for i := 0 to Settings.ServerCount - 1 do
begin
settings.getServer(i, name, address, username, password, doesSearch);
server := TValueSetEditorServerCache.Create(name, address, username, password, doesSearch, i);
try
server.load(nil);
FServers.Add(server.Link);
finally
server.Free;
end;
end;
end;
function TValueSetEditorContext.EditName: String;
begin
if Settings.valueSetFilename <> '' then
result := Settings.valueSetFilename
else if Settings.valueSetId <> '' then
result := Settings.valueSetId +' on '+Settings.valueSetServer
else
result := 'New Value Set';
end;
procedure TValueSetEditorContext.Expand(event : TFhirHTTPClientStatusEvent; text : String);
var
client : TFhirHTTPClient;
pIn, pOut : TFhirParameters;
rOut : TFHIRResource;
feed : TFHIRBundle;
begin
client := TFhirHTTPClient.create(nil, FWorkingServer.FUrl, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
pIn := TFhirParameters.Create;
try
if text <> '' then
pIn.AddParameter('filter', text);
pIn.AddParameter('valueSet', ValueSet.Link);
rOut := client.operation(frtValueset, 'expand', pIn);
try
FExpansion.Free;
FExpansion := nil;
if rOut is TFhirValueSet then
FExpansion := (rOut as TFhirValueSet).expansion.Link
else if rOut is TFhirParameters then
begin
pOut := TFhirParameters(rOut);
if pOut.hasParameter('return') then
FExpansion := (pOut['return'] as TFHIRValueSet).expansion.Link
else
raise Exception.Create('Unable to process result from expansion server');
end
else
raise Exception.Create('Unable to process result from expansion server');
finally
rOut.Free;
end;
finally
pIn.free;
end;
finally
client.Free;
end;
end;
function TValueSetEditorContext.FetchValueSetBySystem(uri: String): TFhirValueSet;
var
client : TFhirHTTPClient;
params : TAdvStringMatch;
feed : TFHIRBundle;
begin
result := nil;
client := TFhirHTTPClient.create(nil, FWorkingServer.url, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
params := TAdvStringMatch.Create;
try
params.Add('system', uri);
feed := client.search(frtValueset, false, params);
try
if feed.entryList.Count > 0 then
begin
FWorkingServer.SeeValueset(feed.entryList[0].resource as TFhirValueSet, false, false);
FWorkingServer.save;
result := feed.entryList[0].resource.link as TFhirValueSet;
end;
finally
feed.Free;
end;
finally
params.free;
end;
finally
client.Free;
end;
end;
function TValueSetEditorContext.GetCodeSystemValidator(uri: String): TValueSetEditorCodeSystem;
var
vs : TFhirValueSet;
obj : TAdvObject;
i : integer;
begin
if FCodeSystemContexts.ExistsByKey(uri) then
begin
obj := FCodeSystemContexts.GetValueByKey(uri);
if obj is TValueSetEditorCodeSystem then
result := TValueSetEditorCodeSystem(obj.Link)
else
result := TValueSetEditorCodeSystemValueSet.Create(TFHIRValueSet(obj));
end
else if (FWorkingServer <> Nil) and (FWorkingServer.codesystems.ExistsByKey(uri)) then
begin
// this means that the server has code system. try and load the local copy
vs := FWorkingServer.LoadFullCodeSystem(uri);
try
if vs = nil then
vs := FetchValueSetBySystem(uri);
if vs = nil then
result := nil
else
begin
FCodeSystemContexts.Add(uri, vs.link);
result := TValueSetEditorCodeSystemValueSet.Create(TFHIRValueSet(vs));
end;
finally
vs.Free;
end;
end
else if (FWorkingServer <> nil) and FWorkingServer.specialCodeSystems.ExistsByKey(uri) then
result := FWorkingServer.specialCodeSystems.GetValueByKey(uri).Link as TServerCodeSystem
else
result := nil; // Not done yet;
end;
procedure TValueSetEditorContext.GetDefinedCodeDisplayList(context: TFhirValueSetCodeSystemConceptList; list: TStrings; code: String);
var
i : integer;
begin
for i := 0 to context.count - 1 do
begin
if context[i].code = code then
list.Add(context[i].display)
else
GetDefinedCodeDisplayList(context[i].conceptList, list, code);
end;
end;
procedure TValueSetEditorContext.GetDefinedCodesList(context: TFhirValueSetCodeSystemConceptList; list: TStrings);
var
i : integer;
begin
for i := 0 to context.count - 1 do
begin
if not context[i].abstract then
list.Add(context[i].code);
GetDefinedCodesList(context[i].conceptList, list);
end;
end;
procedure TValueSetEditorContext.GetList(context: String; list: TStrings);
var
obj : TAdvObject;
code : String;
i: Integer;
vs : TFhirValueSet;
begin
if context = '' then
exit;
if Context.Contains('#') then
StringSplitRight(Context, '#', Context, code);
list.BeginUpdate;
try
if context = CS_LIST then
list.AddStrings(FWorkingServer.sortedCodesystems)
else if context = VS_LIST then
list.AddStrings(FWorkingServer.sortedValueSets)
else if FCodeSystemContexts.ExistsByKey(context) then
begin
obj := FCodeSystemContexts.Matches[context];
if obj is TFhirValueSet then
if code = '' then
GetDefinedCodesList(TFhirValueSet(obj).codeSystem.conceptList, list)
else
begin
GetDefinedCodeDisplayList(TFhirValueSet(obj).codeSystem.conceptList, list, code);
if list.IndexOf('') = -1 then
list.Insert(0, '');
end;
end
else if context = ExpressionProperty then
begin
if (code = 'http://snomed.info/sct') then
begin
list.Add('concept');
list.Add('expression');
end
else if (code = 'http://loinc.org') then
begin
list.Add('COMPONENT');
list.Add('PROPERTY');
list.Add('TIME_ASPCT');
list.Add('SYSTEM');
list.Add('SCALE_TYP');
list.Add('METHOD_TYP');
list.Add('CLASS');
list.Add('Document.Kind');
list.Add('Document.TypeOfService');
list.Add('Document.Setting');
list.Add('Document.Role');
list.Add('Document.SubjectMatterDomain');
list.Add('LOINC_NUM');
list.Add('SOURCE');
list.Add('DATE_LAST_CHANGED');
list.Add('CHNG_TYPE');
list.Add('COMMENTS');
list.Add('STATUS');
list.Add('CONSUMER_NAME');
list.Add('MOLAR_MASS');
list.Add('CLASSTYP');
list.Add('FORMUL');
list.Add('SPECIES');
list.Add('EXMPL_ANSWERS');
list.Add('ACSSYM');
list.Add('BASE_NAME');
list.Add('NAACCR_ID');
list.Add('CODE_TABLE');
list.Add('SURVEY_QUEST_TXT');
list.Add('SURVEY_QUEST_SRC');
list.Add('UNITSREQUIRED');
list.Add('SUBMITTED_UNITS');
list.Add('RELATEDNAMES2');
list.Add('SHORTNAME');
list.Add('ORDER_OBS');
list.Add('CDISC_COMMON_TESTS');
list.Add('HL7_FIELD_SUBFIELD_ID');
list.Add('EXTERNAL_COPYRIGHT_NOTICE');
list.Add('EXAMPLE_UNITS');
list.Add('LONG_COMMON_NAME');
list.Add('HL7_V2_DATATYPE');
list.Add('HL7_V3_DATATYPE');
list.Add('CURATED_RANGE_AND_UNITS');
list.Add('DOCUMENT_SECTION');
list.Add('EXAMPLE_UCUM_UNIT');
list.Add('EXAMPLE_SI_UCUM_UNITS');
list.Add('STATUS_REASON');
list.Add('STATUS_TEXT');
list.Add('CHANGE_REASON_PUBLIC');
list.Add('COMMON_TEST_RANK');
list.Add('COMMON_ORDER_RANK');
list.Add('COMMON_SI_TEST_RANK');
list.Add('HL7_ATTACHMENT_STRUCTURE');
end
else
list.Add('concept');
end
else
// ??
finally
list.EndUpdate;
end;
end;
procedure TValueSetEditorContext.GetPreview(uri: String);
var
client : TFhirHTTPClient;
params : TAdvStringMatch;
feed : TFHIRBundle;
begin
FPreview.Free;
FPreview := nil;
if (uri = '') then
begin
FOnPreview(self);
end
else if (FExpansions.existsBykey(uri)) then
FPreview := FExpansions.Matches[uri].Link as TFhirValueSetExpansion
else
begin
// todo: make this a thread that waits
client := TFhirHTTPClient.create(nil, FWorkingServer.FUrl, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
params := TAdvStringMatch.Create;
try
params.Add('_query', 'expand');
params.Add('identifier', uri);
feed := client.search(frtValueset, false, params);
try
if feed.entryList.Count > 0 then
begin
FPreview.Free;
FPreview := nil;
FPreview := TFHIRValueset(feed.entryList[0].resource).expansion.link;
FExpansions.add(uri, FPreview.Link);
FOnPreview(self);
end;
finally
feed.Free;
end;
finally
params.free;
end;
finally
client.Free;
end;
end;
end;
procedure TValueSetEditorContext.validateDefineConcepts(ts : TStringlist; list : TFhirValueSetCodeSystemConceptList);
var
i : integer;
code : TFhirValueSetCodeSystemConcept;
begin
for I := 0 to list.Count - 1 do
begin
code := list[i];
if code.abstract and (code.code = '') then
FValidationErrors.AddElement(code, 0, voError, 'Missing Code - required if not an abstract code')
else if ts.IndexOf(code.code) > -1 then
FValidationErrors.AddElement(code, 0, voError, 'Duplicate Code '+code.code)
else
ts.Add(code.code);
if code.definition = '' then
FValidationErrors.AddElement(code, 3, voHint, 'Codes should have definitions, or their use is always fragile');
if code.abstract and code.conceptList.IsEmpty then
FValidationErrors.AddElement(code, 1, voWarning, 'This abstract element has no children');
validateDefineConcepts(ts, code.conceptList);
end;
end;
procedure TValueSetEditorContext.validateDefine;
var
ts : TStringList;
begin
ts := TStringList.Create;
try
validateDefineConcepts(ts, FValueSet.codeSystem.conceptList);
finally
ts.Free;
end;
end;
procedure TValueSetEditorContext.InternalValidation;
var
i : integer;
begin
FValidationErrors.Clear;
if (FValueSet <> nil) then
begin
if FValueSet.codeSystem <> nil then
validateDefine;
if FValueSet.compose <> nil then
begin
for i := 0 to FValueSet.compose.includeList.Count - 1 do
validateInclude(FValueSet.compose.includeList[i]);
for i := 0 to FValueSet.compose.excludeList.Count - 1 do
validateInclude(FValueSet.compose.excludeList[i]);
end;
end;
end;
function TValueSetEditorContext.Link: TValueSetEditorContext;
begin
result := TValueSetEditorContext(inherited Link);
end;
procedure TValueSetEditorContext.loadClosures(list: TStrings);
begin
WorkingServer.loadClosures(list);
end;
function TValueSetEditorContext.NameCodeSystem(uri: String): String;
var
client : TFhirHTTPClient;
params : TAdvStringMatch;
list : TFHIRBundle;
begin
if uri = '' then
result := '?Unnamed'
else if uri = 'http://snomed.info/sct' then
result := 'SNOMED CT'
else if uri = 'http://loinc.org' then
result := 'LOINC'
else if uri = 'http://unitsofmeasure.org' then
result := 'UCUM'
else if uri = 'http://www.radlex.org/' then
result := 'RadLex'
else if uri = 'http://hl7.org/fhir/sid/icd-10' then
result := 'ICD-10'
else if uri = 'http://hl7.org/fhir/sid/icd-9 ' then
result := 'ICD-9 USA'
else if uri = 'http://www.whocc.no/atc' then
result := 'ATC codes'
else if uri = 'urn:std:iso:11073:10101' then
result := 'ISO 11073'
else if uri = 'http://nema.org/dicom/dicm' then
result := 'DICOM codes'
else if FWorkingServer.codesystems.ExistsByKey(uri) then
result := TFhirValueSet(FWorkingServer.codesystems.GetValueByKey(uri)).name
else if not isURL(uri) then
result := uri
else
begin
try
client := TFhirHTTPClient.create(nil, FWorkingServer.URL, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
params := TAdvStringMatch.Create;
try
params.Add('system', uri);
list := client.search(frtValueset, false, params);
try
if list.entryList.Count > 0 then
begin
result := (list.entryList[0].resource as TFHIRValueSet).name;
FWorkingServer.SeeValueset(list.entryList[0].resource as TFHIRValueSet, false, false);
FWorkingServer.save;
end
else
result := uri;
finally
list.Free;
end;
finally
params.free;
end;
finally
client.Free;
end;
except
result := uri;
end;
end
end;
function TValueSetEditorContext.NameValueSet(uri: String): String;
var
client : TFhirHTTPClient;
params : TAdvStringMatch;
list : TFHIRBundle;
begin
if (uri = '') then
result := '??'
else if FWorkingServer.valuesets.ExistsByKey(uri) then
result := TFHIRValueSet(FWorkingServer.valuesets.Matches[uri]).name
else if not isUrl(uri) then
result := uri
else
begin
try
client := TFhirHTTPClient.create(nil, FWorkingServer.URL, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
params := TAdvStringMatch.Create;
try
params.Add('identifier', uri);
list := client.search(frtValueset, false, params);
try
if list.entryList.Count > 0 then
begin
result := (list.entryList[0].resource as TFHIRValueSet).name;
FWorkingServer.SeeValueset(list.entryList[0].resource as TFhirValueSet, false, false);
FWorkingServer.save;
end
else
result := uri;
finally
list.Free;
end;
finally
params.free;
end;
finally
client.Free;
end;
except
result := uri;
end;
end;
end;
procedure TValueSetEditorContext.NewValueset;
var
vs : TFhirValueSet;
begin
vs := TFhirValueSet.Create;
try
vs.experimental := true;
openValueSet(vs);
finally
vs.Free;
end;
Settings.valueSetFilename := '';
Settings.valueSetId := '';
end;
procedure TValueSetEditorContext.openFromFile(event : TFhirHTTPClientStatusEvent; fn: String);
var
p : TFHIRParser;
s : AnsiString;
f : TFileStream;
begin
Settings.mru('file:'+fn);
Settings.valueSetFilename := fn;
f := TFileStream.create(fn, fmOpenRead + fmShareDenyWrite);
try
SetLength(s, f.Size);
f.Read(s[1], f.Size);
f.Position := 0;
if pos('<', s) = 0 then
p := TFHIRJsonParser.Create(nil, 'en')
else if pos('{', s) = 0 then
p := TFHIRXmlParser.Create(nil, 'en')
else if pos('<', s) < pos('{', s) then
p := TFHIRXmlParser.Create(nil, 'en')
else
p := TFHIRJsonParser.Create(nil, 'en');
try
Settings.FormatIsJson := p is TFHIRJsonParser;
p.source := f;
p.Parse;
openValueSet(p.resource as TFhirValueSet);
finally
p.Free;
end;
finally
f.Free;
end;
end;
procedure TValueSetEditorContext.openFromServer(event : TFhirHTTPClientStatusEvent; id: String);
var
client : TFhirHTTPClient;
vs : TFhirValueSet;
begin
Settings.mru('id:'+id+':'+FWorkingServer.URL);
Settings.valueSetId := id;
client := TFhirHTTPClient.create(nil, FWorkingServer.URL, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
vs := client.readResource(frtValueSet, Settings.valueSetId) as TFhirValueSet;
try
openValueSet(vs);
finally
vs.Free;
end;
finally
client.free;
end;
end;
procedure TValueSetEditorContext.openFromURL(event : TFhirHTTPClientStatusEvent; url: String);
var
web : TIdHTTP;
vs : TFhirValueSet;
p : TFHIRParser;
mem : TMemoryStream;
begin
Settings.mru('url:'+url);
web := TIdHTTP.Create(nil);
try
web.HandleRedirects := true;
mem := TMemoryStream.Create;
try
web.Get(url, mem);
// mem.Position := 0;
// mem.SaveToFile('c:\temp\test.web');
mem.Position := 0;
p := MakeParser(nil, 'en', ffUnspecified, mem, xppAllow);
try
vs := p.resource as TFhirValueSet;
Settings.valueSetServer := url;
raise Exception.Create('not done yet');
openValueSet(vs);
finally
p.Free;
end;
finally
mem.Free;
end;
Finally
web.free;
End;
end;
procedure TValueSetEditorContext.openValueSet(vs: TFhirValueSet);
begin
FExpansion.Free;
FExpansion := nil;
FValueSet.Free;
FValueSet := vs.Link;
FVersionCount := 0;
ClearAllVersions;
Commit('open');
FDirty := False;
if Assigned(FOnStateChange) then
FOnStateChange(self);
end;
procedure TValueSetEditorContext.PrepareSystemContext(uri: String; version : String);
begin
if uri = '' then
exit;
GetCodeSystemValidator(uri);
end;
function TValueSetEditorContext.UIState: integer;
begin
if FValueSet <> nil then
result := UIState_Edit
// else if FValueSetList <> nil then
// result := UIState_Choose
else
result := UIState_Welcome;
end;
function TValueSetEditorContext.makeOutcome(kind: TValidationOutcomeKind; msg: String): TValidationOutcome;
begin
result.kind := kind;
result.msg := msg;
end;
function TValueSetEditorContext.validateIdentifier(value: string): TValidationOutcome;
begin
if value = '' then
result := makeOutcome(voMissing, 'A URL is required')
else if not isURL(value) then
result := makeOutcome(voError, 'A URL is required (not a valid url)')
else
result := makeOutcome(voOk, '');
end;
function TValueSetEditorContext.validateImport(value: string): TValidationOutcome;
begin
if value = '' then
result := makeOutcome(voMissing, 'A URL is required')
else if not isURL(value) then
result := makeOutcome(voError, 'A URL is required (not a valid url)')
else if not FWorkingServer.valuesets.ExistsByKey(value) then
result := makeOutcome(voWarning, 'No value set known by this URI')
else
result := makeOutcome(voOk, '');
end;
procedure TValueSetEditorContext.validateInclude(inc: TFhirValueSetComposeInclude);
var
i : integer;
ts : TStringList;
cs : TValueSetEditorCodeSystem;
c : TFhirCode;
status : TValueSetEditorCodeSystemCodeStatus;
filter : TFhirValueSetComposeIncludeFilter;
msg : String;
begin
cs := GetCodeSystemValidator(inc.system);
try
ts := TStringList.Create;
try
for i := 0 to inc.conceptList.Count - 1 do
begin
status := cscsUnknown;
c := inc.conceptList[i].codeElement;
if (c.value = '') then
FValidationErrors.AddElement(c, 0, voMissing, 'Code is required')
else if (ts.IndexOf(c.value) > -1) then
FValidationErrors.AddElement(c, 0, voError, 'Duplicate Code "'+c.value+'"')
else
begin
if cs = nil then
status := cscsInvalidSystem
else
status := cs.getCodeStatus(c.value, msg);
case status of
cscsOK: ; // nothing to do
cscsInvalidSystem: FValidationErrors.AddElement(c, 0, voWarning, 'Code system is not known');
cscsUnknown: FValidationErrors.AddElement(c, 0, voError, 'Code "'+c.value+'" is not valid in the code system ("'+msg+'")');
cscsPending: FValidationErrors.AddElement(c, 0, voHint, 'Code "'+c.value+'" stll being validated');
end;
end;
if (status = cscsOK) and (c.hasExtension('http://hl7.org/fhir/Profile/tools-extensions#display')) then
if cs.isWrongDisplay(c.Value, c.getExtensionString('http://hl7.org/fhir/Profile/tools-extensions#display')) then
FValidationErrors.AddElement(c, 1, voWarning, 'Display '+c.getExtensionString('http://hl7.org/fhir/Profile/tools-extensions#display')
+' is not valid in the code system for Code "'+c.value+'"');
end;
if cs <> nil then
begin
for i := 0 to inc.filterList.Count - 1 do
begin
filter := inc.filterList[i];
if not cs.filterPropertyOK(filter.property_, filter.op, filter.value) then
FValidationErrors.AddElement(c, 0, voWarning, 'Property '''+filter.property_+''' not known for code system '+inc.system)
else if not cs.filterOperationOK(filter.property_, filter.op, filter.value) then
FValidationErrors.AddElement(c, 0, voWarning, 'Operation '''+filter.opElement.value+''' not known for code system '+inc.system)
else if not cs.filterValueOK(filter.property_, filter.op, filter.value) then
FValidationErrors.AddElement(c, 0, voWarning, 'Property '''+filter.value+''' not known for code system '+inc.system);
end;
end;
finally
ts.Free;
end;
// ok, that was the codes. Now the filters....
finally
cs.free;
end;
end;
function TValueSetEditorContext.validateName(value: string): TValidationOutcome;
begin
if value = '' then
result := makeOutcome(voMissing, 'A Name is required')
else
result := makeOutcome(voOk, '');
end;
function TValueSetEditorContext.validateDescription(value: string): TValidationOutcome;
begin
if value = '' then
result := makeOutcome(voMissing, 'Some description is required')
else
result := makeOutcome(voOk, '');
end;
function TValueSetEditorContext.validateReference(value: string): TValidationOutcome;
begin
if value = '' then
result := makeOutcome(voMissing, 'A URL is required')
else if not isURL(value) then
result := makeOutcome(voError, 'A URL is required (not a valid url)')
else if not FWorkingServer.codesystems.ExistsByKey(value) and not FWorkingServer.specialCodeSystems.ExistsByKey(value) then
result := makeOutcome(voWarning, 'No code system known by this URI')
else
result := makeOutcome(voOk, '');
end;
function TValueSetEditorContext.validateSystem(value: string): TValidationOutcome;
begin
if (value = '') and (FValueSet <> nil) and (FValueSet.codeSystem <> nil) and not FValueSet.codeSystem.conceptList.IsEmpty then
result := makeOutcome(voMissing, 'A URL is required')
else if not isURL(value) then
result := makeOutcome(voError, 'A URL is required (not a valid url)')
else if (value <> '') and SameText(value, FValueSet.url) then
result := makeOutcome(voError, 'Cannot be the same as the value set identifier')
else
result := makeOutcome(voOk, '');
end;
{ TValueSetEditorCoreSettings }
procedure TValueSetEditorCoreSettings.AddServer(name, address, username, password: String; doesSearch : boolean);
begin
ini.WriteString('servers', name, address);
ini.WriteBool('servers-search', name, doesSearch);
if username <> '' then
ini.WriteString('servers-sec', name, EncodeMIME(username)+':'+EncodeMIME(password));
end;
function TValueSetEditorCoreSettings.columnWidth(tree, name : string; default: integer) : integer;
begin
result := ini.ReadInteger(tree, name, default);
end;
constructor TValueSetEditorCoreSettings.Create;
var
i : integer;
begin
inherited;
if not FileExists(Path([ShellLocalAppDataFolder, 'Health Intersections'])) then
CreateDir(Path([ShellLocalAppDataFolder, 'Health Intersections']));
if not FileExists(Path([ShellLocalAppDataFolder, 'Health Intersections', 'ValueSetEditor'])) then
CreateDir(Path([ShellLocalAppDataFolder, 'Health Intersections', 'ValueSetEditor']));
ini := TIniFile.create(Path([ShellLocalAppDataFolder, 'Health Intersections', 'ValueSetEditor', 'valueseteditor.ini']));
FMRUList := TStringList.Create;
for i := 0 to ini.ReadInteger('mru', 'count', 0) - 1 do
FMRUList.add(ini.ReadString('mru', 'item'+inttostr(i), ''));
end;
procedure TValueSetEditorCoreSettings.DeleteServer(name: String);
begin
ini.DeleteKey('servers', name);
end;
destructor TValueSetEditorCoreSettings.Destroy;
begin
FMRUList.Free;
ini.free;
inherited;
end;
function TValueSetEditorCoreSettings.GetDocoVisible: boolean;
begin
result := ini.ReadBool('window', 'doco', true);
end;
function TValueSetEditorCoreSettings.GetFilter: String;
begin
result := ini.ReadString('state', 'filter', '');
end;
function TValueSetEditorCoreSettings.GetFormatIsJson: boolean;
begin
result := ini.ReadBool('state', 'json', false);
end;
function TValueSetEditorCoreSettings.GetHasViewedWelcomeScreen: boolean;
begin
result := ini.ReadBool('window', 'HasViewedWelcomeScreen', false);
end;
procedure TValueSetEditorCoreSettings.getServer(index : integer; var name, address, username, password : String; var doesSearch : boolean);
var
list : TStringList;
s, l, r : String;
begin
list := TStringList.create;
try
ini.ReadSection('servers', list);
name := list[index];
address := ini.ReadString('servers', name, '');
doesSearch := ini.ReadBool('servers-search', name, false);
s := ini.ReadString('servers-sec', name, '');
if (s <> '') then
begin
StringSplit(s, [':'], l, r);
username := DecodeMIME(l);
password := DecodeMIME(r);
end;
finally
list.free;
end;
end;
function TValueSetEditorCoreSettings.GetServerFilter: String;
begin
result := ini.ReadString('ui', 'server-filter', '');
end;
function TValueSetEditorCoreSettings.GetServerURL: String;
begin
result := ini.ReadString('state', 'server', '');
end;
function TValueSetEditorCoreSettings.GetvalueSetFilename: String;
begin
result := ini.ReadString('state', 'valueset-filename', '');
end;
function TValueSetEditorCoreSettings.GetValueSetId: String;
begin
result := ini.ReadString('state', 'valueset-id', '');
end;
function TValueSetEditorCoreSettings.GetValueSetURL: String;
begin
result := ini.ReadString('state', 'valueset-url', '');
end;
function TValueSetEditorCoreSettings.GetVersionHigh: integer;
begin
result := ini.ReadInteger('state', 'version-high', 1);
end;
function TValueSetEditorCoreSettings.GetWindowHeight: Integer;
begin
result := ini.ReadInteger('window', 'height', 0);
end;
function TValueSetEditorCoreSettings.GetWindowLeft: Integer;
begin
result := ini.ReadInteger('window', 'left', 0);
end;
function TValueSetEditorCoreSettings.GetWindowState: Integer;
begin
result := ini.ReadInteger('window', 'state', 0);
end;
function TValueSetEditorCoreSettings.GetWindowTop: Integer;
begin
result := ini.ReadInteger('window', 'top', 0);
end;
function TValueSetEditorCoreSettings.GetWindowWidth: Integer;
begin
result := ini.ReadInteger('window', 'width', 0);
end;
function TValueSetEditorCoreSettings.hasWindowState: Boolean;
begin
result := WindowHeight > 0;
end;
procedure TValueSetEditorCoreSettings.mru(src: String);
var
i : integer;
begin
i := FMRUList.IndexOf(src);
if (i > -1) then
FMRUList.Delete(i);
FMRUList.Insert(0, src);
ini.WriteInteger('mru', 'count', FMRUList.Count);
for i := 0 to FMRUList.Count - 1 do
ini.WriteString('mru', 'item'+inttostr(i), FMRUList[i]);
end;
function TValueSetEditorCoreSettings.ServerCount: integer;
var
list : TStringList;
begin
list := TStringList.Create;
try
ini.ReadSection('servers', list);
result := list.Count;
finally
list.Free;
end;
end;
procedure TValueSetEditorCoreSettings.setColumnWidth(tree, name: string; value: integer);
begin
ini.WriteInteger(tree, name, value);
end;
procedure TValueSetEditorCoreSettings.SetDocoVisible(const Value: boolean);
begin
ini.WriteBool('window', 'doco', value);
end;
procedure TValueSetEditorCoreSettings.SetFilter(const Value: String);
begin
ini.WriteString('state', 'filter', value);
end;
procedure TValueSetEditorCoreSettings.SetFormatIsJson(const Value: boolean);
begin
ini.WriteBool('state', 'json', Value);
end;
procedure TValueSetEditorCoreSettings.SetHasViewedWelcomeScreen(const Value: boolean);
begin
ini.WriteBool('window', 'HasViewedWelcomeScreen', value);
end;
procedure TValueSetEditorCoreSettings.SetServerFilter(const Value: String);
begin
ini.WriteString('ui', 'server-filter', value);
end;
procedure TValueSetEditorCoreSettings.SetServerURL(const Value: String);
begin
ini.WriteString('state', 'server', value);
end;
procedure TValueSetEditorCoreSettings.SetvalueSetFilename(const Value: String);
begin
ini.WriteString('state', 'valueset-filename', value);
end;
procedure TValueSetEditorCoreSettings.SetValueSetId(const Value: String);
begin
ini.WriteString('state', 'valueset-id', value);
end;
procedure TValueSetEditorCoreSettings.SetValueSetURL(const Value: String);
begin
ini.WriteString('state', 'valueset-url', value);
end;
procedure TValueSetEditorCoreSettings.SetVersionHigh(const Value: integer);
begin
ini.WriteInteger('state', 'version-high', value);
end;
procedure TValueSetEditorCoreSettings.SetWindowHeight(const Value: Integer);
begin
ini.WriteInteger('window', 'height', value);
end;
procedure TValueSetEditorCoreSettings.SetWindowLeft(const Value: Integer);
begin
ini.WriteInteger('window', 'left', value);
end;
procedure TValueSetEditorCoreSettings.SetWindowState(const Value: Integer);
begin
ini.WriteInteger('window', 'state', value);
end;
procedure TValueSetEditorCoreSettings.SetWindowTop(const Value: Integer);
begin
ini.WriteInteger('window', 'top', value);
end;
procedure TValueSetEditorCoreSettings.SetWindowWidth(const Value: Integer);
begin
ini.WriteInteger('window', 'width', value);
end;
procedure TValueSetEditorCoreSettings.UpdateServer(name, address, username, password: String);
begin
ini.WriteString('servers', name, address);
if username <> '' then
ini.WriteString('servers-sec', name, EncodeMIME(username)+':'+EncodeMIME(password));
end;
function TValueSetEditorCoreSettings.ValuesetItemPath: string;
begin
result := IncludeTrailingPathDelimiter(SystemTemp)+'vs.json';
end;
function TValueSetEditorCoreSettings.ValuesetListPath: string;
begin
result := IncludeTrailingPathDelimiter(SystemTemp)+'vslist.json';
end;
function TValueSetEditorCoreSettings.ValueSetNew: boolean;
begin
result := (valueSetFilename = '') and (valueSetId = '');
end;
function IsURL(s : String) : boolean;
var
r : TRegExpr;
begin
r := TRegExpr.Create;
try
r.Expression := 'https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?'; // http://www.regexguru.com/2008/11/detecting-urls-in-a-block-of-text/
result := r.Exec(s);
finally
r.free;
end;
end;
{ TValidationOutcomeMark }
destructor TValidationOutcomeMark.destroy;
begin
FObj.Free;
inherited;
end;
procedure TValidationOutcomeMark.SetObj(const Value: TFHIRElement);
begin
FObj.Free;
FObj := Value;
end;
{ TValidationOutcomeMarkList }
constructor TValidationOutcomeMarkList.Create;
begin
inherited;
PreventDuplicates;
SortedBy(CompareByElement);
end;
function TValidationOutcomeMarkList.itemClass: TAdvObjectClass;
begin
result := TValidationOutcomeMark;
end;
function TValidationOutcomeMarkList.GetMark(index: integer): TValidationOutcomeMark;
begin
result := TValidationOutcomeMark(objectByIndex[index]);
end;
procedure TValidationOutcomeMarkList.AddElement(elem: TFHIRElement; field: Integer; kind: TValidationOutcomeKind; message: String);
var
mark : TValidationOutcomeMark;
begin
mark := TValidationOutcomeMark.Create;
try
mark.obj := elem.Link;
mark.FField := field;
mark.FKind := kind;
mark.FMessage := message;
add(mark.Link);
finally
mark.Free;
end;
end;
function TValidationOutcomeMarkList.CompareByElement(pA, pB: Pointer): Integer;
begin
result := integer(TValidationOutcomeMark(pA).FObj) - integer(TValidationOutcomeMark(pB).FObj);
if result = 0 then
result := TValidationOutcomeMark(pA).field - TValidationOutcomeMark(pB).field;
end;
function TValidationOutcomeMarkList.GetByElement(elem: TFHIRElement; field : integer): TValidationOutcomeMark;
var
mark : TValidationOutcomeMark;
index : integer;
begin
mark := TValidationOutcomeMark.Create;
try
mark.obj := elem.Link;
mark.field := field;
if Find(mark, index, CompareByElement) then
result := GetMark(index)
else
result := nil;
finally
mark.free;
end;
end;
{ TValueSetEditorCodeSystem }
function TValueSetEditorCodeSystem.filterPropertyOK(prop: String; op: TFhirFilterOperatorEnum; value: String): boolean;
begin
result := false;
end;
function TValueSetEditorCodeSystem.filterOperationOK(prop: String; op: TFhirFilterOperatorEnum; value: String): boolean;
begin
result := false;
end;
function TValueSetEditorCodeSystem.filterValueOK(prop: String; op: TFhirFilterOperatorEnum; value: String): boolean;
begin
result := false;
end;
function TValueSetEditorCodeSystem.getCodeStatus(code: String; var msg: String): TValueSetEditorCodeSystemCodeStatus;
begin
raise Exception.Create('Need to override getCodeStatus in '+className);
end;
function TValueSetEditorCodeSystem.getDisplay(code: String; var display: String): boolean;
begin
raise Exception.Create('Need to override getDisplay in '+className);
end;
function TValueSetEditorCodeSystem.isWrongDisplay(code, display: String): boolean;
begin
raise Exception.Create('Need to override isWrongDisplay in '+className);
end;
{ TValueSetEditorCodeSystemValueSet }
constructor TValueSetEditorCodeSystemValueSet.create(vs: TFhirValueSet);
begin
Create;
FConceptlist := vs.codeSystem.conceptList.Link;
FCase := vs.codeSystem.caseSensitive;
end;
destructor TValueSetEditorCodeSystemValueSet.destroy;
begin
FConceptList.Free;
inherited;
end;
function TValueSetEditorCodeSystemValueSet.filterPropertyOK(prop: String; op: TFhirFilterOperatorEnum; value: String): boolean;
begin
result := prop = 'concept';
end;
function TValueSetEditorCodeSystemValueSet.filterOperationOK(prop: String; op: TFhirFilterOperatorEnum; value: String): boolean;
begin
result := op = FilterOperatorIsA;
end;
function TValueSetEditorCodeSystemValueSet.filterValueOK(prop: String; op: TFhirFilterOperatorEnum; value: String): boolean;
var
msg : String;
begin
result := getCodeStatus(value, msg) = cscsOK;
end;
function TValueSetEditorCodeSystemValueSet.InList(list : TFhirValueSetCodeSystemConceptList; code : String) : TFhirValueSetCodeSystemConcept;
var
c : TFhirValueSetCodeSystemConcept;
i : integer;
begin
result := nil;
for i := 0 to list.count - 1 do
begin
c := list[i];
if FCase then
begin
if c.code = code then
result := c
end
else if SameText(c.code, code) then
result := c;
if result = nil then
result := InList(c.conceptList, code);
if result <> nil then
break;
end;
end;
function TValueSetEditorCodeSystemValueSet.getCodeStatus(code: String; var msg: String): TValueSetEditorCodeSystemCodeStatus;
begin
if inList(FConceptList, code) <> nil then
result := cscsOK
else
begin
result := cscsUnknown;
msg := 'No definition found for "'+code+'"';
end;
end;
function TValueSetEditorCodeSystemValueSet.getDisplay(code: String; var display: String): boolean;
var
c : TFhirValueSetCodeSystemConcept;
begin
c := inList(FConceptList, code);
if (c <> nil) and (c.display <> '') then
begin
result := true;
display := c.display;
end
else
result := false;
end;
function TValueSetEditorCodeSystemValueSet.isWrongDisplay(code, display: String): boolean;
var
c : TFhirValueSetCodeSystemConcept;
begin
c := inList(FConceptList, code);
if (c <> nil) and (c.display <> '') and not SameText(display, c.display) then
result := false
else
result := true;
end;
{ TValueSetEditorServerCache }
procedure TValueSetEditorServerCache.addClosure(s: String);
var
client : TFhirHTTPClient;
pin : TFhirParameters;
pout : TFhirResource;
ct : TClosureTableRecord;
begin
ct := TClosureTableRecord.create;
try
ct.id := NewGuidId;
ct.Name := s;
ct.version := '0';
ct.FFilename := IncludeTrailingBackslash(base)+'ct-'+ct.id+'.json';
client := TFhirHTTPClient.create(nil, url, true);
try
client.UseIndy := true;
pin := TFhirParameters.Create;
try
pin.AddParameter('name', ct.id);
pout := client.operation(frtConceptMap, 'closure', pin);
try
if not (pout as TFhirParameters).bool['outcome'] then
raise Exception.Create('Unexpected response from server');
finally
pout.Free;
end;
finally
pin.Free;
end;
finally
client.Free;
end;
ct.save;
ini.WriteString('closures', ct.id, ct.name);
closures.Add(s, ct.link);
finally
ct.Free;
end;
end;
procedure TValueSetEditorServerCache.AddToClosure(name: String; coding: TFhirCoding);
var
ct : TClosureTableRecord;
client : TFhirHTTPClient;
pin : TFhirParameters;
pout : TFhirResource;
fn : String;
begin
ct := closures[name];
ct.FConcepts.Add(coding.link);
client := TFhirHTTPClient.create(nil, url, true);
try
client.UseIndy := true;
pin := TFhirParameters.Create;
try
pin.AddParameter('name', ct.id);
pin.AddParameter('concept', coding.Link);
pout := client.operation(frtConceptMap, 'closure', pin);
try
if pout is TFHIRConceptMap then
ct.process(pout as TFHIRConceptMap)
else
raise Exception.Create('Unexpected response from server');
finally
pout.Free;
end;
finally
pin.Free;
end;
finally
client.Free;
end;
ct.save;
end;
function TValueSetEditorServerCache.base: String;
begin
result := Path([ShellLocalAppDataFolder, 'Health Intersections', 'ValueSetEditor' , 'server'+inttostr(FKey)]);
end;
procedure TValueSetEditorServerCache.CheckConnection;
var
client : TFhirHTTPClient;
conf : TFhirConformance;
rest : TFhirConformanceRestResource;
i, id : integer;
uri : string;
ini : TIniFile;
fn : String;
begin
client := TFhirHTTPClient.create(nil, url, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
conf := client.conformance(false);
try
if not conf.fhirVersion.StartsWith(FHIR_GENERATED_VERSION+'-') then
raise Exception.Create('Version Mismatch');
rest := conf.rest(frtValueset);
if (rest = nil) or (rest.interaction(TypeRestfulInteractionSearchType) = nil) or (rest.interaction(TypeRestfulInteractionRead) = nil) then
raise Exception.Create('The server does not support the required opeerations for value sets');
ini := TIniFile.Create(base+'server.ini');
try
for i := 0 to conf.getExtensionCount('http://hl7.org/fhir/Profile/tools-extensions#supported-system') - 1 do
begin
uri := conf.getExtensionString('http://hl7.org/fhir/Profile/tools-extensions#supported-system', i);
fn := ini.ReadString('system', uri, '');
if (fn = '') then
begin
id := ini.ReadInteger('system', 'last', 0) + 1;
ini.WriteInteger('system', 'last', id);
fn := 'cache-'+inttostr(id)+'.json';
ini.writeString('system', uri, fn);
end;
specialCodeSystems.Add(uri, TServerCodeSystem.create(uri, FUrl, base+fn));
end;
finally
ini.Free;
end;
finally
conf.free;
end;
finally
client.Free;
end;
end;
procedure TValueSetEditorServerCache.checkLoad(event: TFhirHTTPClientStatusEvent; null : String);
begin
if not FLoaded then
begin
load(event);
update(event, null);
end;
end;
constructor TValueSetEditorServerCache.Create(name, url, username, password : String; doesSearch : boolean; key : integer);
begin
inherited Create;
FKey := key;
Furl := url;
FName := name;
FLoaded := false;
Fusername := username;
Fpassword := password;
FDoesSearch := doesSearch;
ini := TIniFile.Create(IncludeTrailingPathDelimiter(base)+'server.ini');
Flist := TFHIRValueSetList.Create;
valuesets := TAdvStringObjectMatch.Create;
valuesets.Forced := true;
valuesets.PreventDuplicates;
Fcodesystems := TAdvStringObjectMatch.Create;
Fcodesystems.Forced := true;
Fcodesystems.PreventDuplicates;
sortedCodesystems := TStringList.Create;
sortedCodesystems.Sorted := true;
sortedValueSets := TStringList.Create;
sortedValueSets.Sorted := true;
specialCodeSystems := TAdvStringObjectMatch.create;
closures := TAdvMap<TClosureTableRecord>.create;
end;
destructor TValueSetEditorServerCache.Destroy;
begin
closures.Free;
specialCodeSystems.Free;
valuesets.Free;
codesystems.Free;
sortedCodesystems.Free;
sortedValueSets.Free;
FList.Free;
ini.Free;
inherited;
end;
function TValueSetEditorServerCache.expand(url, filter: String; count: integer; allowIncomplete : boolean): TFHIRValueSet;
var
client : TFhirHTTPClient;
pIn, pOut : TFhirParameters;
rOut : TFHIRResource;
feed : TFHIRBundle;
begin
client := TFhirHTTPClient.create(nil, FUrl, true);
try
client.UseIndy := true;
client.OnClientStatus := nil;
pIn := TFhirParameters.Create;
try
pIn.AddParameter('identifier', url);
if filter <> '' then
pIn.AddParameter('filter', filter);
if count <> 0 then
pIn.AddParameter('count', inttostr(count));
if allowIncomplete then
pIn.AddParameter('_incomplete', 'true');
rOut := client.operation(frtValueset, 'expand', pIn);
try
if rOut is TFhirValueSet then
result := (rOut as TFhirValueSet).Link
else if rOut is TFhirParameters then
begin
pOut := TFhirParameters(rOut);
if pOut.hasParameter('return') then
result := (pOut['return'] as TFHIRValueSet).Link
else
raise Exception.Create('Unable to process result from expansion server');
end
else
raise Exception.Create('Unable to process result from expansion server');
finally
rOut.Free;
end;
finally
pIn.free;
end;
finally
client.Free;
end;
end;
function TValueSetEditorServerCache.Link: TValueSetEditorServerCache;
begin
result := TValueSetEditorServerCache(inherited Link);
end;
procedure TValueSetEditorServerCache.load(event : TFhirHTTPClientStatusEvent);
var
json : TFHIRJsonParser;
f : TFileStream;
i : integer;
bundle : TFHIRBundle;
ts : TStringList;
fn : String;
begin
if not FileExists(ExtractFilePath(ini.FileName)) then
begin
CreateDir(ExtractFilePath(ini.FileName));
ini.WriteString('id', 'url', url)
end
else if (ini.ReadString('id', 'url', '') <> url) then
raise Exception.Create('Ini mismatch');
FLastUpdated := ini.ReadString('id', 'last-updated', '');
if FileExists(base+'list.json') then
begin
if assigned(event) then event(self, 'Load Cache');
json := TFHIRJsonParser.create(nil, 'en');
try
f := TFileStream.Create(base+'list.json', fmOpenRead + fmShareDenyWrite);
try
json.source := f;
json.Parse;
bundle := json.resource as TFhirBundle;
for i := 0 to bundle.entryList.Count - 1 do
begin
if assigned(event) then event(self, 'Load Cache, '+inttostr(i)+' of '+inttostr(bundle.entryList.Count));
SeeValueset(bundle.entryList[i].resource as TFhirValueSet, true, true);
end;
finally
f.Free;
end;
finally
json.free;
end;
FLoaded := true;
end;
ts := TStringList.Create;
try
ini.ReadSection('closures', ts);
for i := 0 to ts.Count - 1 do
begin
fn := IncludeTrailingBackslash(base)+'ct-'+ts[i]+'.json';
if FileExists(fn) then
closures.Add(ts[i], TClosureTableRecord.Create(fn))
else
closures.Add(ts[i], TClosureTableRecord.Create(fn, ts[i], ini.ReadString('closures', ts[i], '')));
end;
finally
ts.Free;
end;
end;
procedure TValueSetEditorServerCache.loadClosures(list: TStrings);
var
s : String;
begin
list.Clear;
for s in closures.Keys do
list.Add(s);
end;
procedure TValueSetEditorServerCache.save;
var
json : TFHIRComposer;
f : TFileStream;
bnd : TFHIRBundle;
vs : TFhirValueSet;
begin
ini.WriteString('id', 'last-updated', FLastUpdated);
bnd := TFhirBundle.Create(BundleTypeCollection);
try
for vs in FList do
bnd.entryList.Append.resource := vs.Link;
f := TFileStream.Create(base+'list.json', fmCreate);
try
json := TFHIRJsonComposer.Create(nil, 'en');
try
json.Compose(f, bnd, false);
finally
json.Free;
end;
finally
f.free;
end;
finally
bnd.free;
end;
end;
function TValueSetEditorServerCache.LoadFullCodeSystem(uri : String) : TFhirValueSet;
var
id : String;
json : TFHIRJsonParser;
f : TFileStream;
begin
id := ini.ReadString('codesystems', uri, '');
if (id = '') or not FileExists(base+id+'.json') then
result := nil
else
begin
f := TFileStream.Create(base+id+'.json', fmOpenRead + fmShareDenyWrite);
try
json := TFHIRJsonParser.Create(nil, 'en');
try
json.source := f;
json.Parse;
result := json.resource.link as TFhirValueSet;
finally
json.free;
end;
finally
f.Free;
end;
end;
end;
procedure TValueSetEditorServerCache.ResetClosure(name: String);
var
client : TFhirHTTPClient;
pin : TFhirParameters;
pout : TFhirResource;
ct : TClosureTableRecord;
begin
ct := closures[name];
client := TFhirHTTPClient.create(nil, url, true);
try
client.UseIndy := true;
pin := TFhirParameters.Create;
try
pin.AddParameter('name', ct.id);
pout := client.operation(frtConceptMap, 'closure', pin);
try
if not (pout as TFhirParameters).bool['outcome'] then
raise Exception.Create('Unexpected response from server');
finally
pout.Free;
end;
finally
pin.Free;
end;
finally
client.Free;
end;
ct.FConcepts.Clear;
ct.FMaps.Clear;
ct.save;
end;
procedure TValueSetEditorServerCache.SeeValueset(vs : TFHIRValueSet; isSummary, loading : boolean);
var
json : TFHIRComposer;
f : TFileStream;
id : String;
i : integer;
b : boolean;
begin
if not loading then
begin
if FileExists(base+vs.id+'.json') then
DeleteFile(base+vs.id+'.json');
if not (isSummary or vs.meta.HasTag('http://hl7.org/fhir/tag', 'http://healthintersections.com.au/fhir/tags/summary')) then
begin
f := TFileStream.Create(base+id+'.json', fmCreate);
try
json := TFHIRJsonComposer.Create(nil, 'en');
try
json.Compose(f, vs, false);
finally
json.Free;
end;
finally
f.free;
end;
if (vs.codeSystem <> nil) then
ini.WriteString('codeSystems', vs.codeSystem.system, id);
end;
// now, make it empty
if vs.codeSystem <> nil then
vs.codeSystem.conceptList.Clear;
if vs.compose <> nil then
for i := 0 to vs.compose.includeList.Count - 1 do
begin
vs.compose.includeList[i].conceptList.Clear;
vs.compose.includeList[i].filterList.Clear;
vs.text := nil;
end;
vs.expansion := nil;
end;
// registering it..
b := false;
for i := 0 to Flist.count - 1 do
if Flist[i].id = vs.id then
begin
Flist[i] := vs.link;
b := true;
end;
if not b then
Flist.add(vs.Link);
valuesets.Matches[vs.url] := vs.Link;
if not sortedValueSets.Find(vs.url, i) then
sortedValueSets.Add(vs.url);
if vs.codeSystem <> nil then
begin
codesystems.Matches[vs.codeSystem.System] := vs.Link;
if not sortedCodesystems.Find(vs.codeSystem.System, i) then
sortedCodesystems.Add(vs.codeSystem.System);
end;
end;
{ TServerCodeSystem }
constructor TServerCodeSystem.create(uri, url, filename: String);
begin
Create;
FSystem := uri;
FClient := TFhirHTTPClient.create(nil, url, true);
Fclient.UseIndy := true;
FCache := TAdvStringObjectMatch.create;
FFilename := filename;
if FileExists(FFilename) then
Load;
end;
destructor TServerCodeSystem.Destroy;
begin
FClient.Free;
FCache.Free;
inherited;
end;
function TServerCodeSystem.filterPropertyOK(prop: String; op: TFhirFilterOperatorEnum; value: String): boolean;
begin
result := false;
if FSystem = 'http://snomed.info' then
begin
result := (prop = 'expression') or (prop = 'concept');
end
else if FSystem = 'http://loinc.org' then
begin
result := StringArrayExistsSensitive(['COMPONENT', 'PROPERTY', 'TIME_ASPCT', 'SYSTEM', 'SCALE_TYP', 'METHOD_TYP',
'Document.Kind', 'Document.TypeOfService', 'Document.Setting', 'Document.Role', 'Document.SubjectMatterDomain'], prop)
end;
end;
function TServerCodeSystem.filterOperationOK(prop: String; op: TFhirFilterOperatorEnum; value: String): boolean;
begin
result := false;
if FSystem = 'http://snomed.info' then
begin
result := ((prop = 'expression') and (op in [FilterOperatorEqual])) or ((prop = 'concept') and (op in [FilterOperatorIsA, FilterOperatorIn]));
end
else if FSystem = 'http://loinc.org' then
begin
result := (StringArrayExistsSensitive(['COMPONENT', 'PROPERTY', 'TIME_ASPCT', 'SYSTEM', 'SCALE_TYP', 'METHOD_TYP',
'Document.Kind', 'Document.TypeOfService', 'Document.Setting', 'Document.Role', 'Document.SubjectMatterDomain'], prop) and (op in [FilterOperatorEqual, FilterOperatorRegex]))
or (('Type' = prop) and (op in [FilterOperatorEqual]));
end;
end;
function TServerCodeSystem.filterValueOK(prop: String; op: TFhirFilterOperatorEnum; value: String): boolean;
var
msg : String;
begin
result := false;
if FSystem = 'http://snomed.info' then
begin
if prop = 'expression' then
// we do not presently validate expressions
result := true
else if prop = 'concept' then
// todo: validate that a "in" is associated with a reference set
result := getCodeStatus(value, msg) = cscsOK;
end
else if FSystem = 'http://loinc.org' then
begin
// todo...
end;
end;
function TServerCodeSystem.getCodeStatus(code: String; var msg: String): TValueSetEditorCodeSystemCodeStatus;
var
item : TServerCodeSystemCacheItem;
begin
if not hasCache(code, item) then
loadCode(code, item);
result := item.status;
msg := item.message;
end;
function TServerCodeSystem.getDisplay(code: String; var display: String): boolean;
var
item : TServerCodeSystemCacheItem;
begin
if not hasCache(code, item) then
loadCode(code, item);
result := item.status = cscsOK;
if result and (item.displays.count > 0) then
display := item.displays[0];
end;
function TServerCodeSystem.HasCache(code: String; var item: TServerCodeSystemCacheItem): boolean;
var
i : integer;
begin
i := FCache.IndexByKey(code);
result := i > -1;
if result then
item := FCache.ValueByIndex[i] as TServerCodeSystemCacheItem;
end;
function TServerCodeSystem.isWrongDisplay(code, display: String): boolean;
var
item : TServerCodeSystemCacheItem;
begin
if not hasCache(code, item) then
loadCode(code, item);
result := item.displays.IndexOf(display) > -1;
end;
procedure TServerCodeSystem.loadCode(code: String; var item: TServerCodeSystemCacheItem);
var
params : TAdvStringMatch;
feed : TFHIRBundle;
vs : TFhirValueSet;
begin
params := TAdvStringMatch.Create;
try
params.forced := true;
params.Matches['_query'] := 'expand';
params.Matches['system'] := FSystem;
params.Matches['code'] := code;
feed := FClient.search(frtValueSet, true, params);
try
if (feed.entryList.Count = 1) and (feed.entryList[0].resource.ResourceType = frtValueSet) then
begin
vs := feed.entryList[0].resource as TFhirValueSet;
if (vs.expansion <> nil) and (vs.expansion.containsList.Count = 1)
and (vs.expansion.containsList[0].System = FSystem) and (vs.expansion.containsList[0].code = code) then
begin
item := TServerCodeSystemCacheItem.Create(cscsOK, '');
item.displays.Add(vs.expansion.containsList[0].display);
end
else
item := TServerCodeSystemCacheItem.Create(cscsUnknown, 'Code '''+code+''' not found');
end
else
item := TServerCodeSystemCacheItem.Create(cscsUnknown, 'Code '''+code+''' not found');
FCache.Add(code, item);
Save;
finally
feed.Free;
end;
finally
params.Free;
end;
end;
procedure TServerCodeSystem.Load;
var
json, o, d : TJsonObject;
n, n1 : TJsonNode;
f : TAdvFile;
item : TServerCodeSystemCacheItem;
begin
f := TAdvFile.Create;
try
f.Name := FFilename;
f.OpenRead;
json := TJSONParser.Parse(f);
try
for n in json.vArr['items'] do
begin
o := n as TJsonObject;
item := TServerCodeSystemCacheItem.Create;
try
if o['ok'] = 'no' then
item.status := cscsUnknown
else
item.status := cscsOK;
item.message := o['msg'];
for n1 in o.vArr['displays'] do
begin
d := n1 as TJsonObject;
item.displays.Add(d['value']);
end;
FCache.Add(o['code'], item.Link);
finally
item.Free;
end;
end;
finally
json.free;
end;
finally
f.Free;
end;
end;
procedure TServerCodeSystem.Save;
var
json : TJSONWriter;
f : TAdvFile;
i : integer;
c : String;
item : TServerCodeSystemCacheItem;
begin
f := TAdvFile.Create;
try
f.Name := FFilename;
f.OpenCreate;
json := TJSONWriter.Create;
try
json.Stream := f.link;
json.Start;
json.ValueArray('items');
for i := 0 to FCache.Count - 1 do
begin
json.ValueObject;
c := FCache.KeyByIndex[i];
item := FCache.ValueByIndex[i] as TServerCodeSystemCacheItem;
json.Value('code', c);
if item.status = cscsUnknown then
json.Value('ok', 'no');
if (item.message <> '') then
json.Value('msg', item.message);
json.ValueArray('displays');
for c in item.displays do
begin
json.ValueObject;
json.Value('value', c);
json.FinishObject;
end;
json.FinishArray;
json.FinishObject;
end;
json.FinishArray;
json.Finish;
finally
json.Free;
end;
finally
f.free;
end;
end;
{ TServerCodeSystemCacheItem }
constructor TServerCodeSystemCacheItem.Create;
begin
inherited;
displays := TStringList.Create;
end;
constructor TServerCodeSystemCacheItem.Create(status: TValueSetEditorCodeSystemCodeStatus; message: String);
begin
Create;
self.status := status;
self.message := message;
end;
destructor TServerCodeSystemCacheItem.Destroy;
begin
displays.Free;
inherited;
end;
{ TClosureTableRecord }
constructor TClosureTableRecord.create(filename: String);
var
f : TFileStream;
json, ao, ao1 : TJsonObject;
a, a1 : TJsonNode;
c : TFhirCoding;
s : TClosureTableRecordSource;
begin
Create;
FFilename := filename;
f := TFileStream.Create(filename, fmOpenRead + fmShareDenyWrite);
try
json := TJSONParser.Parse(f);
try
id := json.str['id'];
name := json.str['name'];
version := json.str['version'];
for a in json.arr['concepts'] do
begin
ao := a as TJsonObject;
c := TFhirCoding.Create;
FConcepts.Add(c);
c.system := ao.str['system'];
c.code := ao.str['code'];
c.display := ao.str['display'];
end;
for a in json.arr['maps'] do
begin
ao := a as TJsonObject;
s := TClosureTableRecordSource.Create;
FMaps.Add(s);
s.system := ao.str['system'];
s.code := ao.str['code'];
for a1 in ao.arr['targets'] do
begin
ao1 := a1 as TJsonObject;
c := TFhirCoding.Create;
s.targets.Add(c);
c.system := ao1.str['system'];
c.code := ao1.str['code'];
end;
end;
finally
json.Free;
end;
finally
f.Free;
end;
end;
procedure TClosureTableRecord.save;
var
f : TFileStream;
json, ao, ao1 : TJsonObject;
arr, arr1 : TJsonArray;
c : TFhirCoding;
s : TClosureTableRecordSource;
begin
json := TJsonObject.Create;
try
json.str['id'] := id;
json.str['name'] := name;
json.str['version'] := version;
arr := json.forceArr['concepts'];
for c in FConcepts do
begin
ao := arr.addObject;
ao.str['system'] := c.system;
ao.str['code'] := c.code;
ao.str['display'] := c.display;
end;
arr := json.forceArr['maps'];
for s in FMaps do
begin
ao := arr.addObject;
ao.str['system'] := s.system;
ao.str['code'] := s.code;
arr1 := ao.forceArr['targets'];
for c in s.targets do
begin
ao1 := arr1.addObject;
ao1.str['system'] := c.system;
ao1.str['code'] := c.code;
end;
end;
f := TFileStream.Create(Ffilename, fmCreate);
try
TJSONWriter.writeObject(f, json, true);
finally
f.Free;
end;
finally
json.Free;
end;
end;
constructor TClosureTableRecord.create(filename, id, name: String);
begin
Create;
FFilename := filename;
self.id := id;
self.name := name;
version := '0';
end;
destructor TClosureTableRecord.Destroy;
begin
FMaps.Free;
FConcepts.Free;
inherited;
end;
constructor TClosureTableRecord.create;
begin
inherited;
FMaps := TAdvList<TClosureTableRecordSource>.create;
FConcepts := TAdvList<TFHIRCoding>.create;
end;
function TClosureTableRecord.GetLinks(row, col: integer): TClosureDirection;
var
r, c : TFHIRCoding;
begin
r := FConcepts[row];
c := FConcepts[col];
if hasMap(r, c) then
result := cdSubsumes
else if hasMap(c, r) then
result := cdSubsumed
else
result := cdNull;
end;
function TClosureTableRecord.GetMapCount: integer;
var
s : TClosureTableRecordSource;
begin
result := FMaps.Count;
for s in FMaps do
result := result + s.targets.Count;
end;
function TClosureTableRecord.getSource(uri, code: String): TClosureTableRecordSource;
begin
for result in FMaps do
if (result.system = uri) and (result.code = code) then
exit;
result := TClosureTableRecordSource.Create;
try
result.system := uri;
result.code := code;
FMaps.Add(result.link);
finally
result.Free;
end;
end;
function TClosureTableRecord.hasMap(src, tgt: TFHIRCoding): boolean;
var
s : TClosureTableRecordSource;
c : TFHIRCoding;
begin
result := false;
for s in FMaps do
if (s.system = src.system) and (s.code = src.code) then
for c in s.targets do
if (c.system = tgt.system) and (c.code = tgt.code) then
exit(true);
end;
function TClosureTableRecord.link: TClosureTableRecord;
begin
result := TClosureTableRecord(inherited Link);
end;
procedure TClosureTableRecord.process(cm: TFHIRConceptMap);
var
element : TFhirConceptMapElement;
src : TClosureTableRecordSource;
target : TFhirConceptMapElementTarget;
begin
version := cm.version;
for element in cm.elementList do
for target in element.targetList do
if target.equivalence = ConceptMapEquivalenceSubsumes then
begin
src := getSource(element.codeSystem, element.code);
src.add(target.codeSystem, target.code);
end
else if target.equivalence = ConceptMapEquivalenceSpecializes then
begin
src := getSource(target.codeSystem, target.code);
src.add(element.codeSystem, element.code);
end
else
raise Exception.Create('Unhandled equivalance '+CODES_TFhirConceptMapEquivalenceEnum[target.equivalence]);
end;
{ TClosureTableRecordSource }
procedure TClosureTableRecordSource.add(uri, code: String);
var
c : TFhirCoding;
begin
for c in targets do
if (c.system = uri) and (c.code = code) then
exit;
c := TFhirCoding.Create;
try
c.system := uri;
c.code := code;
targets.Add(c.link);
finally
c.Free;
end;
end;
constructor TClosureTableRecordSource.Create;
begin
inherited Create;
FTargets := TAdvList<TFHIRCoding>.create;
end;
destructor TClosureTableRecordSource.Destroy;
begin
FTargets.Free;
inherited;
end;
function TClosureTableRecordSource.link: TClosureTableRecordSource;
begin
result := TClosureTableRecordSource(inherited Link);
end;
end.
(*
list := TStringList.Create;
try
Settings.ini.ReadSection('systems', list);
for s in list do
FCodeSystemNames.Add(s, Settings.ini.ReadString('systems', s, '??'));
Settings.ini.ReadSection('valuesets', list);
for s in list do
FValueSetNames.Add(s, Settings.ini.ReadString('valuesets', s, '??'));
finally
list.Free;
end;
if FileExists(FSettings.ValuesetListPath) then
begin
f := TFileStream.Create(FSettings.ValuesetListPath, fmOpenRead + fmShareDenyWrite);
try
p := TFHIRJsonParser.Create('en');
try
p.source := F;
p.Parse;
FValueSetlist := p.feed.Link;
finally
p.free
end;
finally
f.Free;
end;
end
else
FValueSetlist := nil;
FCodeSystemNames.Free;
FValueSetNames.Free;
FValueSetList.Free;
procedure TValueSetEditorContext.listServerValuesets(url: String);
var
client : TFhirHTTPClient;
params : TAdvStringMatch;
c : TFHIRJsonComposer;
f : TFileStream;
i : Integer;
vs : TFhirValueSet;
begin
Settings.ServerURL := url;
client := TFhirHTTPClient.create(nil, url, true);
try
client.UseIndy := true;
params := TAdvStringMatch.Create;
try
params.Add('_summary', 'true');
params.Add('_count', '1000');
FValueSetlist := client.search(frtValueset, true, params);
for i := 0 to FValueSetList.entryList.Count -1 do
begin
vs := TFhirValueSet(FValueSetList.entryList[i].resource);
FValueSetNames.Add(vs.identifier, vs.nameST);
FSettings.ini.WriteString('valuesets', vs.identifier, vs.nameST);
end;
f := TFileStream.Create(Settings.ValuesetListPath, fmCreate);
try
c := TFHIRJsonComposer.Create('en');
try
c.Compose(f, FValueSetList, true);
finally
c.Free;
end;
finally
f.free;
end;
finally
params.free;
end;
finally
client.Free;
end;
end;
*)
|
{$include kode.inc}
unit syn_s2_const;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
const
S2_MAX_VOICES = 16;
S2_NUM_PROGRAMS = 32;
//S2_OVERSAMPLING = 4;
const
// anaialiasing waveform types (osc)
s2a_off = 0;
s2a_dpw = 1;
s2a_dpw2 = 2;
s2a_dpw3 = 3;
s2a_eptr = 4;
s2a_polyblep = 5;
s2a_count = 6;
//s2a_blamp = 6;
//s2a_sinc = 7;
// envelope stages
s2e_stage_off = 0;
s2e_stage_attack = 1;
s2e_stage_decay = 2;
s2e_stage_sustain = 3;
s2e_stage_release = 4;
s2e_stage_finished = 5;
s2e_stage_count = 6;
s2e_stage_threshold = 0.001; //KODE_TINY;//KODE_EPSILON;
// filter types
s2f_off = 0;
s2f_lp = 1;
s2f_hp = 2;
s2f_bp = 3;
s2f_n = 4;
s2f_count = 5;
// group (controls)
s2g_osc1 = 0;
s2g_osc2 = 1;
s2g_osc3 = 2;
s2g_mix = 3;
s2g_env1 = 4;
s2g_env2 = 5;
s2g_env3 = 6;
s2g_lfo1 = 7;
s2g_lfo2 = 8;
s2g_lfo3 = 9;
s2g_master = 10;
s2g_config = 11;
// group (osc)
s2g_osc_phase = 0;
s2g_osc_phaseshape = 1;
s2g_osc_wave = 2;
s2g_osc_waveshape = 3;
s2g_osc_filter = 4;
s2g_osc_volume = 5;
// group (master)
s2g_master_fx = 0;
s2g_master_filter = 1;
s2g_master_volume = 2;
// lfo types
s2l_off = 0;
s2l_sin = 1;
s2l_tri = 2;
s2l_saw = 3;
s2l_ramp = 4;
s2l_squ = 5;
s2l_sh = 6;
s2l_noise = 7;
s2l_count = 8;
// modulation sources
s2m_off = 0;
s2m_const = 1;
s2m_inl = 2;
s2m_inr = 3;
s2m_bend = 4;
s2m_env1 = 5;
s2m_env2 = 6;
s2m_env3 = 7;
s2m_lfo1 = 8;
s2m_lfo2 = 9;
s2m_lfo3 = 10;
s2m_p1 = 11;
s2m_p2 = 12;
s2m_p3 = 13;
s2m_pa1 = 14;
s2m_pa2 = 15;
s2m_pa3 = 16;
s2m_pw1 = 17;
s2m_pw2 = 18;
s2m_pw3 = 19;
s2m_ps1 = 20;
s2m_ps2 = 21;
s2m_ps3 = 22;
s2m_w1 = 23;
s2m_w2 = 24;
s2m_w3 = 25;
s2m_ws1 = 26;
s2m_ws2 = 27;
s2m_ws3 = 28;
s2m_f1 = 29;
s2m_f2 = 30;
s2m_f3 = 31;
s2m_osc1 = 32;
s2m_osc2 = 33;
s2m_osc3 = 34;
s2m_count = 35;
// config
s2o_none = 0;
//s2o_hiir2 = 1;
//s2o_hiir2s = 2;
//s2o_hiir4 = 3;
//s2o_hiir4s = 4;
//s2o_hiir6 = 5;
//s2o_hiir6s = 6;
//s2o_hiir8 = 7;
//s2o_hiir8s = 8;
//s2o_hiir10 = 9;
//s2o_hiir10s = 10;
//s2o_hiir12 = 11;
s2o_hiir12s = 1;//12;
s2o_decimator5 = 2;//13;
s2o_decimator7 = 3;//14;
s2o_decimator9 = 4;//15;
s2o_count = 5;//16;
// shaper types (wave/phase)
s2s_off = 0;
s2s_add = 1;
s2s_mul = 2;
s2s_curve = 3;
s2s_count = 4;
// waveform types (wave)
s2w_off = 0;
s2w_const = 1;
s2w_inl = 2;
s2w_inr = 3;
s2w_sin = 4;
s2w_tri = 5;
s2w_saw = 6;
s2w_ramp = 7;
s2w_squ = 8;
s2w_noise = 9;
s2w_count = 10;
// fx types
s2x_off = 0;
s2x_on = 1;
s2x_count = 2;
//----------
const
txt_src : array[0..s2m_count-1] of pchar =
(
'off',
'const',
'left input',
'right input',
'pitch bend',
'env 1',
'env 2',
'env 3',
'lfo 1',
'lfo 2',
'lfo 3',
'phase 1',
'phase 2',
'phase 3',
'phase add 1',
'phase add 2',
'phase add 3',
'phase wrap 1',
'phase wrap 2',
'phase wrap 3',
'phase shape 1',
'phase shape 2',
'phase shape 3',
'wave 1',
'wave 2',
'wave 3',
'wave shape 1',
'wave shape 2',
'wave shape 3',
'filter 1',
'filter 2',
'filter 3',
'osc1',
'osc2',
'osc3'
);
txt_shape : array[0..s2s_count-1] of pchar =
(
'off',
'add',
'mul',
'curve'
);
txt_wave : array[0..s2w_count-1] of pchar =
(
'off',
'const',
'in l',
'in r',
'sin',
'tri',
'saw',
'ramp',
'squ',
'noise'
);
txt_aa : array[0..s2a_count-1] of pchar =
(
'off',
'dpw',
'dpw2',
'dpw3',
'eptr',
'polyblep'
//'blamp'
//'sinc'
);
txt_flt : array[0..s2f_count-1] of pchar =
(
'off',
'lowpass',
'highpass',
'bandpass',
'notch'
);
txt_lfo : array[0..s2l_count-1] of pchar =
(
'off',
'sin',
'tri',
'saw',
'ramp',
'squ',
's&h',
'noise'
);
txt_fx : array[0..s2x_count-1] of pchar =
(
'off',
'on'
);
txt_ostype : array[0..s2o_count-1] of pchar =
(
'none',
//'s2o_hiir2',
//'s2o_hiir2s',
//'s2o_hiir4',
//'s2o_hiir4s',
//'s2o_hiir6',
//'s2o_hiir6s',
//'s2o_hiir8',
//'s2o_hiir8s',
//'s2o_hiir10',
//'s2o_hiir10s',
//'s2o_hiir12',
'hiir 12 s',
'decimator 5',
'decimator 7',
'decimator 9'
);
txt_osamt : array[0..4] of pchar =
(
'1',
'2',
'4',
'8',
'16'
);
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
//----------------------------------------------------------------------
end.
|
Unit MathSupport;
{
Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
Math;
Function IntegerCompare(Const iA, iB : Byte) : Integer; Overload;
Function IntegerCompare(Const iA, iB : Word) : Integer; Overload;
Function IntegerCompare(Const iA, iB : Integer) : Integer; Overload;
Function IntegerCompare(Const iA, iB : Cardinal) : Integer; Overload;
Function IntegerCompare(Const iA, iB : Int64) : Integer; Overload;
Function IntegerCompare(Const iA, iB, iThreshold : Int64) : Integer; Overload;
Function BooleanCompare(Const bA, bB : Boolean) : Integer; Overload;
Function RealCompare(Const rA, rB : Extended) : Integer; Overload;
Function RealCompare(Const rA, rB : Real) : Integer; Overload;
Function RealCompare(Const rA, rB, rThreshold : Real) : Integer; Overload;
Function IntegerEquals(Const iA, iB : Byte) : Boolean; Overload;
Function IntegerEquals(Const iA, iB : Word) : Boolean; Overload;
Function IntegerEquals(Const iA, iB : Integer) : Boolean; Overload;
Function IntegerEquals(Const iA, iB : Cardinal) : Boolean; Overload;
Function IntegerEquals(Const iA, iB : Int64) : Boolean; Overload;
Function IntegerEquals(Const iA, iB, iThreshold : Int64) : Boolean; Overload;
Function BooleanEquals(Const bA, bB : Boolean) : Boolean; Overload;
Function RealEquals(Const rA, rB : Real) : Boolean; Overload;
Function RealEquals(Const rA, rB, rThreshold : Real) : Boolean; Overload;
Function IntegerBetweenInclusive(Const iLeft, iCheck, iRight : Integer) : Boolean; Overload;
Function IntegerBetweenExclusive(Const iLeft, iCheck, iRight : Integer) : Boolean; Overload;
Function IntegerBetween(Const iLeft, iCheck, iRight : Integer) : Boolean; Overload;
Function CardinalBetweenInclusive(Const iLeft, iCheck, iRight : Cardinal) : Boolean; Overload;
Function CardinalBetweenExclusive(Const iLeft, iCheck, iRight : Cardinal) : Boolean; Overload;
Function IntegerBetweenInclusive(Const iLeft, iCheck, iRight : Int64) : Boolean; Overload;
Function IntegerBetweenExclusive(Const iLeft, iCheck, iRight : Int64) : Boolean; Overload;
Function IntegerBetween(Const iLeft, iCheck, iRight : Int64) : Boolean; Overload;
Function RealBetweenInclusive(Const rLeft, rCheck, rRight : Real) : Boolean; Overload;
Function RealBetweenExclusive(Const rLeft, rCheck, rRight : Real) : Boolean; Overload;
Function RealBetween(Const rLeft, rCheck, rRight : Real) : Boolean; Overload;
Function RealBetweenInclusive(Const rLeft, rCheck, rRight : Extended) : Boolean; Overload;
Function RealBetweenExclusive(Const rLeft, rCheck, rRight : Extended) : Boolean; Overload;
Function RealBetween(Const rLeft, rCheck, rRight : Extended) : Boolean; Overload;
Function IntegerMin(Const A, B : Integer) : Integer; Overload;
Function IntegerMax(Const A, B : Integer) : Integer; Overload;
Function IntegerMin(Const A, B : Cardinal) : Cardinal; Overload;
Function IntegerMax(Const A, B : Cardinal) : Cardinal; Overload;
Function IntegerMin(Const A, B : Word) : Word; Overload;
Function IntegerMax(Const A, B : Word) : Word; Overload;
Function IntegerMin(Const A, B : Byte) : Byte; Overload;
Function IntegerMax(Const A, B : Byte) : Byte; Overload;
Function IntegerMin(Const A, B : Int64) : Int64; Overload;
Function IntegerMax(Const A, B : Int64) : Int64; Overload;
Function RealMin(Const A, B : Real) : Real; Overload;
Function RealMax(Const A, B : Real) : Real; Overload;
Function RealCeiling(Const rValue : Real) : Int64; Overload;
Function RealFloor(Const rValue : Real) : Int64; Overload;
Function Int64Round(Const iValue, iFactor : Int64) : Int64; Overload;
Function RealSquare(Const rValue : Extended) : Extended; Overload;
Function RealSquareRoot(Const rValue : Extended) : Extended; Overload;
Function IntegerArrayMax(Const aIntegers : Array Of Integer) : Integer; Overload;
Function IntegerArrayMin(Const aIntegers : Array Of Integer) : Integer; Overload;
Function IntegerArraySum(Const aIntegers : Array Of Integer) : Integer; Overload;
Function IntegerArrayIndexOf(Const aIntegers : Array Of Word; iValue : Word) : Integer; Overload;
Function IntegerArrayIndexOf(Const aIntegers : Array Of Integer; iValue : Integer) : Integer; Overload;
Function IntegerArrayIndexOf(Const aIntegers : Array Of Cardinal; iValue : Cardinal) : Integer; Overload;
Function IntegerArrayExists(Const aIntegers : Array Of Integer; iValue : Integer) : Boolean; Overload;
Function IntegerArrayValid(Const aIntegers : Array Of Integer; iIndex : Integer) : Boolean; Overload;
Function RealRoundToInteger(Const aValue : Extended) : Int64; Overload;
Function Abs(Const iValue : Int64) : Int64; Overload;
Function Abs(Const iValue : Integer) : Integer; Overload;
Function Abs(Const rValue : Real) : Real; Overload;
Function Sign(Const iValue : Integer) : Integer; Overload;
Function IntegerConstrain(Const iValue, iMin, iMax : Integer) : Integer; Overload;
Function RealConstrain(Const rValue, rMin, rMax : Real) : Real; Overload;
Function Sin(Const Theta : Extended) : Extended; Overload;
Function Cos(Const Theta : Extended) : Extended; Overload;
Function ArcTan(Const Theta : Extended) : Extended; Overload;
Function ArcTan2(Const X, Y : Extended) : Extended; Overload;
Function DegreesToRadians(Const rDegrees : Extended) : Extended; Overload;
Function RadiansToDegrees(Const rRadians : Extended) : Extended; Overload;
Function Power(Const rBase : Extended; Const iExponent : Integer) : Extended; Overload;
Function Power(Const rBase, rExponent : Extended) : Extended; Overload;
Function LnXP1(Const X : Extended) : Extended; Overload;
Function LogN(Const Base, X : Extended) : Extended; Overload;
Function Log10(Const X : Extended) : Extended; Overload;
Function Log2(Const X : Extended) : Extended; Overload;
Function Hypotenuse(Const X, Y : Extended) : Extended; Overload;
Function Percentage(Const iPart, iTotal : Integer) : Real; Overload;
Function SignedMod(Const iValue : Integer; Const iRange : Integer) : Integer; Overload;
Function SignedMod(Const iValue : Int64; Const iRange : Int64) : Int64; Overload;
Function UnsignedMod(Const iValue : Cardinal; Const iRange : Cardinal) : Cardinal; Overload;
Function UnsignedMod(Const iValue : Integer; Const iRange : Integer) : Integer; Overload;
Function UnsignedMod(Const iValue : Int64; Const iRange : Int64) : Int64; Overload;
Function RemoveRemainder(Const iValue : Cardinal; Const iRange : Cardinal) : Cardinal; Overload;
Function RemoveRemainder(Const iValue : Integer; Const iRange : Integer) : Integer; Overload;
Function RemoveRemainder(Const iValue : Int64; Const iRange : Int64) : Int64; Overload;
Function GreatestCommonDivisor(Const iA, iB : Integer) : Integer;
Implementation
Function Percentage(Const iPart, iTotal : Integer) : Real;
Begin
If (iTotal = 0) Then
Result := 0
Else
Result := iPart / iTotal;
End;
Function IntegerBetweenInclusive(Const iLeft, iCheck, iRight : Integer) : Boolean;
Begin
Result := (iLeft <= iCheck) And (iCheck <= iRight);
End;
Function IntegerBetweenExclusive(Const iLeft, iCheck, iRight : Integer) : Boolean;
Begin
Result := (iLeft < iCheck) And (iCheck < iRight);
End;
Function IntegerBetween(Const iLeft, iCheck, iRight : Integer) : Boolean;
Begin
Result := IntegerBetweenInclusive(iLeft, iCheck, iRight);
End;
Function CardinalBetweenInclusive(Const iLeft, iCheck, iRight : Cardinal) : Boolean;
Begin
Result := (iLeft <= iCheck) And (iCheck <= iRight);
End;
Function CardinalBetweenExclusive(Const iLeft, iCheck, iRight : Cardinal) : Boolean;
Begin
Result := (iLeft < iCheck) And (iCheck < iRight);
End;
Function IntegerBetweenInclusive(Const iLeft, iCheck, iRight : Int64) : Boolean;
Begin
Result := (iLeft <= iCheck) And (iCheck <= iRight);
End;
Function IntegerBetweenExclusive(Const iLeft, iCheck, iRight : Int64) : Boolean;
Begin
Result := (iLeft < iCheck) And (iCheck < iRight);
End;
Function IntegerBetween(Const iLeft, iCheck, iRight : Int64) : Boolean;
Begin
Result := IntegerBetweenInclusive(iLeft, iCheck, iRight);
End;
Function RealBetweenInclusive(Const rLeft, rCheck, rRight : Real) : Boolean;
Begin
Result := (rLeft <= rCheck) And (rCheck <= rRight);
End;
Function RealBetweenExclusive(Const rLeft, rCheck, rRight : Real) : Boolean;
Begin
Result := (rLeft < rCheck) And (rCheck < rRight);
End;
Function RealBetween(Const rLeft, rCheck, rRight : Real) : Boolean;
Begin
Result := RealBetweenInclusive(rLeft, rCheck, rRight);
End;
Function RealBetweenInclusive(Const rLeft, rCheck, rRight : Extended) : Boolean;
Begin
Result := (rLeft <= rCheck) And (rCheck <= rRight);
End;
Function RealBetweenExclusive(Const rLeft, rCheck, rRight : Extended) : Boolean;
Begin
Result := (rLeft < rCheck) And (rCheck < rRight);
End;
Function RealBetween(Const rLeft, rCheck, rRight : Extended) : Boolean;
Begin
Result := RealBetweenInclusive(rLeft, rCheck, rRight);
End;
Function IntegerMin(Const A, B : Integer) : Integer;
Begin
If A < B Then
Result := A
Else
Result := B;
End;
Function IntegerMax(Const A, B : Integer) : Integer;
Begin
If A > B Then
Result := A
Else
Result := B;
End;
Function RealMin(Const A, B : Real) : Real;
Begin
If A < B Then
Result := A
Else
Result := B;
End;
Function RealMax(Const A, B : Real) : Real;
Begin
If A > B Then
Result := A
Else
Result := B;
End;
Function IntegerMin(Const A, B : Cardinal) : Cardinal;
Begin
If A < B Then
Result := A
Else
Result := B;
End;
Function IntegerMax(Const A, B : Cardinal) : Cardinal;
Begin
If A > B Then
Result := A
Else
Result := B;
End;
Function IntegerMin(Const A, B : Word) : Word;
Begin
If A < B Then
Result := A
Else
Result := B;
End;
Function IntegerMax(Const A, B : Word) : Word;
Begin
If A > B Then
Result := A
Else
Result := B;
End;
Function IntegerMin(Const A, B : Byte) : Byte;
Begin
If A < B Then
Result := A
Else
Result := B;
End;
Function IntegerMax(Const A, B : Byte) : Byte;
Begin
If A > B Then
Result := A
Else
Result := B;
End;
Function IntegerMin(Const A, B : Int64) : Int64;
Begin
If A < B Then
Result := A
Else
Result := B;
End;
Function IntegerMax(Const A, B : Int64) : Int64;
Begin
If A > B Then
Result := A
Else
Result := B;
End;
Function IntegerArrayMin(Const aIntegers : Array Of Integer) : Integer;
Var
iLoop : Integer;
Begin
Result := aIntegers[Low(aIntegers)];
For iLoop := Low(aIntegers) + 1 To High(aIntegers) Do
Begin
If Result > aIntegers[iLoop] Then
Result := aIntegers[iLoop];
End;
End;
Function IntegerArrayMax(Const aIntegers : Array Of Integer) : Integer;
Var
iLoop : Integer;
Begin
Result := aIntegers[Low(aIntegers)];
For iLoop := Low(aIntegers) + 1 To High(aIntegers) Do
Begin
If Result < aIntegers[iLoop] Then
Result := aIntegers[iLoop];
End;
End;
Function IntegerArraySum(Const aIntegers : Array Of Integer) : Integer;
Var
iLoop : Integer;
Begin
Result := 0;
For iLoop := 0 To Length(aIntegers) - 1 Do
Inc(Result, aIntegers[iLoop]);
End;
Function RealCeiling(Const rValue : Real) : Int64;
Begin
Result := Trunc(rValue);
If Frac(rValue) > 0 Then
Inc(Result);
End;
Function RealFloor(Const rValue : Real) : Int64;
Begin
Result := Trunc(rValue);
If Frac(rValue) < 0 Then
Dec(Result);
End;
Function Int64Round(Const iValue, iFactor : Int64) : Int64;
Var
iFulcrum : Int64;
iRemain : Int64;
Begin
iFulcrum := iFactor Div 2;
iRemain := SignedMod(iValue, iFactor);
If iRemain < iFulcrum Then
Result := iValue - iRemain
Else If iRemain > iFulcrum Then
Result := iValue + (iFactor - iRemain)
Else
Result := iValue;
End;
Function RealSquare(Const rValue : Extended) : Extended;
Begin
Result := rValue * rValue;
End;
Function RealSquareRoot(Const rValue : Extended) : Extended;
Begin
Result := System.Sqrt(rValue);
End;
Function IntegerArrayIndexOf(Const aIntegers : Array Of Word; iValue : Word) : Integer;
Begin
Result := High(aIntegers);
While (Result >= 0) And (aIntegers[Result] <> iValue) Do
Dec(Result);
End;
Function IntegerArrayIndexOf(Const aIntegers : Array Of Integer; iValue : Integer) : Integer;
Begin
Result := High(aIntegers);
While (Result >= 0) And (aIntegers[Result] <> iValue) Do
Dec(Result);
End;
Function IntegerArrayIndexOf(Const aIntegers : Array Of Cardinal; iValue : Cardinal) : Integer;
Begin
Result := High(aIntegers);
While (Result >= 0) And (aIntegers[Result] <> iValue) Do
Dec(Result);
End;
Function IntegerArrayExists(Const aIntegers : Array Of Integer; iValue : Integer) : Boolean;
Begin
Result := IntegerArrayValid(aIntegers, IntegerArrayIndexOf(aIntegers, iValue));
End;
Function IntegerArrayValid(Const aIntegers : Array Of Integer; iIndex : Integer) : Boolean;
Begin
Result := IntegerBetweenInclusive(Low(aIntegers), iIndex, High(aIntegers));
End;
Function RealRoundToInteger(Const aValue : Extended) : Int64;
Begin
Result := System.Round(aValue);
End;
Function Sign(Const iValue : Integer) : Integer;
Begin
If iValue < 0 Then
Result := -1
Else If iValue > 0 Then
Result := 1
Else
Result := 0;
End;
Function IntegerConstrain(Const iValue, iMin, iMax : Integer) : Integer;
Begin
If iValue < iMin Then
Result := iMin
Else If iValue > iMax Then
Result := iMax
Else
Result := iValue;
End;
Function RealConstrain(Const rValue, rMin, rMax : Real) : Real;
Begin
If rValue < rMin Then
Result := rMin
Else If rValue > rMax Then
Result := rMax
Else
Result := rValue;
End;
Function Abs(Const iValue : Int64) : Int64;
Begin
If iValue < 0 Then
Result := -iValue
Else
Result := iValue;
End;
Function Abs(Const iValue : Integer) : Integer;
Begin
If iValue < 0 Then
Result := -iValue
Else
Result := iValue;
End;
Function Abs(Const rValue : Real) : Real;
Begin
If rValue < 0 Then
Result := -rValue
Else
Result := rValue;
End;
Function IntegerCompare(Const iA, iB : Byte) : Integer;
Begin
If iA < iB Then
Result := -1
Else If iA > iB Then
Result := 1
Else
Result := 0
End;
Function BooleanCompare(Const bA, bB : Boolean) : Integer;
Begin
If bA < bB Then
Result := -1
Else If bA > bB Then
Result := 1
Else
Result := 0
End;
Function IntegerCompare(Const iA, iB : Word) : Integer;
Begin
If iA < iB Then
Result := -1
Else If iA > iB Then
Result := 1
Else
Result := 0
End;
Function IntegerCompare(Const iA, iB, iThreshold : Int64) : Integer;
Begin
If iA - iThreshold > iB Then
Result := 1
Else If iB - iThreshold > iA Then
Result := -1
Else
Result := 0;
End;
Function IntegerCompare(Const iA, iB : Integer) : Integer;
Begin
If iA < iB Then
Result := -1
Else If iA > iB Then
Result := 1
Else
Result := 0
End;
Function IntegerCompare(Const iA, iB : Cardinal) : Integer;
Begin
If iA < iB Then
Result := -1
Else If iA > iB Then
Result := 1
Else
Result := 0
End;
Function IntegerCompare(Const iA, iB : Int64) : Integer;
Begin
If iA < iB Then
Result := -1
Else If iA > iB Then
Result := 1
Else
Result := 0
End;
Function RealCompare(Const rA, rB : Real) : Integer;
Begin
If rA > rB Then
Result := 1
Else If rA < rB Then
Result := -1
Else
Result := 0;
End;
Function RealCompare(Const rA, rB : Extended) : Integer;
Begin
If rA > rB Then
Result := 1
Else If rA < rB Then
Result := -1
Else
Result := 0;
End;
Function RealCompare(Const rA, rB, rThreshold : Real) : Integer;
Begin
If rA - rThreshold > rB Then
Result := 1
Else If rB - rThreshold > rA Then
Result := -1
Else
Result := 0;
End;
Function RealEquals(Const rA, rB, rThreshold : Real) : Boolean;
Begin
Result := RealCompare(rA, rB, rThreshold) = 0;
End;
Function BooleanEquals(Const bA, bB : Boolean) : Boolean;
Begin
Result := BooleanCompare(bA, bB) = 0;
End;
Function IntegerEquals(Const iA, iB : Byte) : Boolean;
Begin
Result := IntegerCompare(iA, iB) = 0;
End;
Function IntegerEquals(Const iA, iB : Word) : Boolean;
Begin
Result := IntegerCompare(iA, iB) = 0;
End;
Function IntegerEquals(Const iA, iB : Integer) : Boolean;
Begin
Result := IntegerCompare(iA, iB) = 0;
End;
Function IntegerEquals(Const iA, iB : Cardinal) : Boolean;
Begin
Result := IntegerCompare(iA, iB) = 0;
End;
Function IntegerEquals(Const iA, iB : Int64) : Boolean;
Begin
Result := IntegerCompare(iA, iB) = 0;
End;
Function IntegerEquals(Const iA, iB, iThreshold : Int64) : Boolean;
Begin
Result := IntegerCompare(iA, iB, iThreshold) = 0;
End;
Function RealEquals(Const rA, rB : Real) : Boolean;
Begin
Result := RealCompare(rA, rB) = 0;
End;
Function Sin(Const Theta : Extended) : Extended;
Begin
Result := System.Sin(Theta);
End;
Function Cos(Const Theta : Extended) : Extended;
Begin
Result := System.Cos(Theta);
End;
Function ArcTan(Const Theta : Extended) : Extended;
Begin
Result := System.ArcTan(Theta);
End;
Function ArcTan2(Const X, Y : Extended) : Extended;
Begin
Result := Math.ArcTan2(X, Y);
End;
Function DegreesToRadians(Const rDegrees : Extended) : Extended;
Begin
Result := Math.DegToRad(rDegrees);
End;
Function RadiansToDegrees(Const rRadians : Extended) : Extended;
Begin
Result := Math.RadToDeg(rRadians);
End;
Function Power(Const rBase : Extended; Const iExponent: Integer): Extended;
Begin
Result := Math.Power(rBase, iExponent);
End;
Function Power(Const rBase, rExponent: Extended): Extended;
Begin
Result := Math.Power(rBase, rExponent);
End;
Function LnXP1(Const X: Extended): Extended;
Begin
Result := Math.LnXP1(X);
End;
Function LogN(Const Base, X: Extended): Extended;
Begin
Result := Math.LogN(Base, X);
End;
Function Log10(Const X: Extended): Extended;
Begin
Result := Math.Log10(X);
End;
Function Log2(Const X: Extended): Extended;
Begin
Result := Math.Log2(X);
End;
Function Hypotenuse(Const X, Y: Extended): Extended;
Begin
Result := Math.Hypot(X, Y);
End;
Function SignedMod(Const iValue : Integer; Const iRange : Integer) : Integer;
Begin
Result := iValue Mod iRange;
End;
Function SignedMod(Const iValue : Int64; Const iRange : Int64) : Int64;
Begin
Result := iValue Mod iRange;
End;
Function UnsignedMod(Const iValue : Cardinal; Const iRange : Cardinal) : Cardinal;
Begin
Result := iValue Mod iRange;
End;
Function UnsignedMod(Const iValue : Integer; Const iRange : Integer) : Integer;
Begin
Result := iValue Mod iRange;
If Result < 0 Then
Result := Result + iRange;
End;
Function UnsignedMod(Const iValue : Int64; Const iRange : Int64) : Int64;
Begin
Result := iValue Mod iRange;
If Result < 0 Then
Result := Result + iRange;
End;
Function RemoveRemainder(Const iValue : Cardinal; Const iRange : Cardinal) : Cardinal;
Begin
Result := iValue - UnsignedMod(iValue, iRange);
End;
Function RemoveRemainder(Const iValue : Integer; Const iRange : Integer) : Integer;
Begin
Result := iValue - UnsignedMod(iValue, iRange);
End;
Function RemoveRemainder(Const iValue : Int64; Const iRange : Int64) : Int64;
Begin
Result := iValue - UnsignedMod(iValue, iRange);
End;
Function GreatestCommonDivisor(Const iA, iB : Integer) : Integer;
Var
iMinValue : Integer;
iMaxValue : Integer;
iCurrentNumerator : Integer;
iCurrentDenominator : Integer;
iCurrentRemainder : Integer;
Begin
If iA = iB Then
Begin
Result := iA;
End
Else
Begin
If iA > iB Then
Begin
iMaxValue := iA;
iMinValue := iB;
End
Else
Begin
iMaxValue := iB;
iMinValue := iA;
End;
If (iMinValue = 0) Then
Begin
Result := 0;
End
Else
Begin
iCurrentNumerator := iMaxValue;
iCurrentDenominator := iMinValue;
Repeat
iCurrentRemainder := iCurrentNumerator Mod iCurrentDenominator;
iCurrentNumerator := iCurrentDenominator;
iCurrentDenominator := iCurrentRemainder;
Until iCurrentRemainder = 0;
Result := iCurrentNumerator;
End;
End;
End;
End. // MathSupport //
|
Unit RectSupport;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
Windows,
CoordinateSupport, MathSupport;
Type
TRect = Windows.TRect;
TPoint = Windows.TPoint;
Function Rect(iLeft, iTop, iRight, iBottom : Integer) : TRect; Overload;
Procedure RectZero(Var aRect : TRect); Overload;
Function RectZero : TRect; Overload;
Function RectEmpty(Const aRect : TRect) : Boolean; Overload;
Function RectEqual(Const A, B : TRect) : Boolean; Overload;
Function RectOffset(Const aRect : TRect; iX, iY : Integer) : TRect; Overload;
Function RectIntersect(Const A, B : TRect) : TRect; Overload;
Function RectSubtract(Const A, B : TRect) : TRect; Overload;
Function RectUnion(Const A, B : TRect) : TRect; Overload;
Function RectHasIntersection(Const A, B : TRect) : Boolean; Overload;
Function RectInflate(Const aRect : TRect; iValue : Integer) : TRect; Overload;
Function RectInflate(Const aRect : TRect; iX, iY : Integer) : TRect; Overload;
Function RectWidth(Const aRect : TRect) : Integer; Overload;
Function RectHeight(Const aRect : TRect) : Integer; Overload;
Function RectHit(Const aRect : TRect; Const aPoint : TPoint) : Boolean; Overload;
Function RectBound(Const aRect, aBoundary : TRect) : TRect; Overload;
Implementation
Function Rect(iLeft, iTop, iRight, iBottom : Integer) : TRect;
Begin
Result.Left := iLeft;
Result.Top := iTop;
Result.Right := iRight;
Result.Bottom := iBottom;
End;
Procedure RectZero(Var aRect : TRect);
Begin
SetRectEmpty(Windows.TRect(aRect));
End;
Function RectZero : TRect;
Begin
RectZero(Result);
End;
Function RectEmpty(Const aRect : TRect) : Boolean;
Begin
Result := Windows.IsRectEmpty(Windows.TRect(aRect));
End;
Function RectEqual(Const A, B : TRect) : Boolean;
Begin
Result := Windows.EqualRect(Windows.TRect(A), Windows.TRect(B));
End;
Function RectOffset(Const aRect : TRect; iX, iY : Integer) : TRect;
Begin
Result := aRect;
OffsetRect(Windows.TRect(Result), iX, iY);
End;
Function RectIntersect(Const A, B : TRect) : TRect;
Begin
Windows.IntersectRect(Windows.TRect(Result), Windows.TRect(A), Windows.TRect(B));
End;
Function RectSubtract(Const A, B : TRect) : TRect;
Begin
Windows.SubtractRect(Windows.TRect(Result), Windows.TRect(A), Windows.TRect(B));
End;
Function RectUnion(Const A, B : TRect) : TRect;
Begin
Windows.UnionRect(Windows.TRect(Result), Windows.TRect(A), Windows.TRect(B));
End;
Function RectHasIntersection(Const A, B : TRect) : Boolean;
Var
aTemp : Windows.TRect;
Begin
Result := Windows.IntersectRect(aTemp, Windows.TRect(A), Windows.TRect(B));
End;
Function RectInflate(Const aRect : TRect; iValue : Integer) : TRect;
Begin
Result := RectInflate(aRect, iValue, iValue);
End;
Function RectInflate(Const aRect : TRect; iX, iY : Integer) : TRect;
Begin
Result := aRect;
Windows.InflateRect(Windows.TRect(Result), iX, iY);
End;
Function RectWidth(Const aRect : TRect) : Integer;
Begin
Result := aRect.Right - aRect.Left;
End;
Function RectHeight(Const aRect : TRect) : Integer;
Begin
Result := aRect.Bottom - aRect.Top;
End;
Function RectHit(Const aRect : TRect; Const aPoint : TPoint) : Boolean;
Begin
Result := Windows.PtInRect(Windows.TRect(aRect), Windows.TPoint(aPoint));
End;
Function RectBound(Const aRect, aBoundary : TRect) : TRect;
Begin
Result.Left := IntegerMax(aRect.Left, aBoundary.Left);
Result.Top := IntegerMax(aRect.Top, aBoundary.Top);
Result.Right := IntegerMin(aRect.Right, aBoundary.Right);
Result.Bottom := IntegerMin(aRect.Bottom, aBoundary.Bottom);
End;
End. // RectSupport //
|
unit sUpDown;
{$I sDefs.inc}
{.$DEFINE LOGGED}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs{$IFNDEF DELPHI5}, Types{$ENDIF},
ComCtrls, sConst, sDefaults;
type
{$IFNDEF NOTFORHELP}
TsDrawingState = (dsDefault, dsPrevUp, dsNextUp, dsPrevDown, dsNextDown);
TsBtnKind = (sbkTop, sbkLeft, sbkBottom, sbkRight);
{$ENDIF} // NOTFORHELP
TsUpDown = class(TCustomUpDown)
{$IFNDEF NOTFORHELP}
private
FShowInaccessibility: boolean;
FDisabledKind: TsDisabledKind;
FDrawingState: TsDrawingState;
FButtonSkin: TsSkinSection;
procedure SetShowInaccessibility(const Value: boolean);
procedure SetDisabledKind(const Value: TsDisabledKind);
procedure SetDrawingState(const Value: TsDrawingState);
procedure SetSkinSection(const Value: TsSkinSection);
protected
Pressed : boolean;
function BtnRect : TRect;
procedure WndProc (var Message: TMessage); override;
public
procedure DrawBtn(Btn : TBitmap; Kind : TsBtnKind);
constructor Create (AOwner: TComponent); override;
property DrawingState : TsDrawingState read FDrawingState write SetDrawingState default dsDefault;
published
property Align;
property AlignButton;
property Anchors;
property Associate;
property ArrowKeys;
property Enabled;
property Hint;
property Min;
property Max;
property Increment;
property Constraints;
property Orientation;
property ParentShowHint;
property PopupMenu;
property Position;
property ShowHint;
property TabOrder;
property TabStop;
property Thousands;
property Visible;
property Wrap;
property OnChanging;
property OnChangingEx;
property OnContextPopup;
property OnClick;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
{$ENDIF} // NOTFORHELP
property ButtonSkin : TsSkinSection read FButtonSkin write SetSkinSection;
property DisabledKind : TsDisabledKind read FDisabledKind write SetDisabledKind default DefDisabledKind;
property ShowInaccessibility : boolean read FShowInaccessibility write SetShowInaccessibility default True;
end;
implementation
uses sStyleSimply, sPageControl, sMessages, sGraphUtils, sSkinProps, sMaskData, acntUtils, sAlphaGraph,
sVclUtils, sSkinManager, sCommonData{$IFDEF LOGGED}, sDebugMsgs{$ENDIF};
{ TsUpDown }
function TsUpDown.BtnRect: TRect;
begin
if Orientation = udVertical then begin
Result := Rect(0, 0, Width, Height div 2);
end
else begin
Result := Rect(0, 0, Width div 2, Height);
end;
end;
constructor TsUpDown.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Pressed := False;
FDrawingState := dsDefault;
FShowInaccessibility := True;
FDisabledKind := DefDisabledKind;
ControlStyle := ControlStyle - [csDoubleClicks];
end;
procedure TsUpDown.SetDisabledKind(const Value: TsDisabledKind);
begin
if FDisabledKind <> Value then begin
FDisabledKind := Value;
Repaint;
end;
end;
procedure TsUpDown.SetDrawingState(const Value: TsDrawingState);
begin
if FDrawingState <> Value then begin
FDrawingState := Value;
Repaint;
end;
end;
procedure TsUpDown.SetShowInaccessibility(const Value: boolean);
begin
if FShowInaccessibility <> Value then begin FShowInaccessibility := Value; Repaint; end;
end;
procedure TsUpDown.WndProc(var Message: TMessage);
var
PS : TPaintStruct;
SaveIndex, DC : hdc;
Btn : TBitmap;
h : integer;
R : TRect;
function BtnPrevDisabled : boolean; begin
if Orientation = udVertical then Result := Position = Max else Result := Position = Min;
end;
function BtnNextDisabled : boolean; begin
if Orientation = udVertical then Result := Position = Min else Result := Position = Max;
end;
begin
{$IFDEF LOGGED}
AddToLog(Message);
{$ENDIF}
if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_CTRLHANDLED : begin Message.Result := 1; Exit end;
AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end;
AC_REMOVESKIN : if Message.LParam = LongInt(DefaultManager) then begin
Repaint;
exit
end;
AC_REFRESH : if Message.LParam = LongInt(DefaultManager) then begin
Repaint;
exit
end
end;
Case Message.Msg of
WM_LBUTTONDBLCLK, WM_NCLBUTTONDBLCLK : begin
inherited;
Pressed := True;
if (DrawingState = dsPrevUp) and (Position < Max)
then DrawingState := dsPrevDown
else if (DrawingState = dsNextUp) and (Position > Min) then DrawingState := dsNextDown;
end;
WM_NCHITTEST : begin
inherited;
if csDesigning in ComponentState then Exit;
R := BtnRect;
if PtInRect(R, ScreenToClient(Point(TWMMouse(Message).XPos, TWMMouse(Message).YPos))) then begin
if (FShowInaccessibility and BtnPrevDisabled) then begin DrawingState := dsDefault; Exit end else
if (DrawingState <> dsPrevUp) and not Pressed then begin
DrawingState := dsPrevUp;
Repaint
end
end
else begin
if (FShowInaccessibility and BtnNextDisabled) then begin DrawingState := dsDefault; Exit end else
if (DrawingState <> dsNextUp) and not Pressed then begin
DrawingState := dsNextUp;
Repaint
end
end;
end;
WM_LBUTTONUP : begin
inherited;
if csDesigning in ComponentState then Exit;
if Pressed then begin
Pressed := False;
if DrawingState = dsPrevDown then begin
if (FShowInaccessibility and (Position = Max)) then Exit;
DrawingState := dsPrevUp
end
else begin
if (FShowInaccessibility and (Position = Min)) then Exit;
DrawingState := dsNextUp;
end;
Message.Result := 1;
end;
end;
WM_LBUTTONDOWN : begin
inherited;
if csDesigning in ComponentState then Exit;
Pressed := True;
if (DrawingState = dsPrevUp) and (Position < Max)
then DrawingState := dsPrevDown
else if (DrawingState = dsNextUp) and (Position > Min) then DrawingState := dsNextDown;
Message.Result := 1;
end;
CM_MOUSELEAVE : begin
inherited;
if csDesigning in ComponentState then Exit;
Pressed := False;
DrawingState := dsDefault;
end;
WM_NCPAINT, WM_ERASEBKGND : if Assigned(DefaultManager) and DefaultManager.Active then Exit else inherited;
WM_PRINT : SendMessage(Handle, WM_PAINT, Message.WParam, Message.LParam);
WM_PAINT : begin
if Assigned(DefaultManager) and DefaultManager.SkinData.Active then with DefaultManager.ConstData do begin
if Orientation = udVertical then begin
if (IndexScrollTop > -1) and (IndexScrollBottom > -1) then begin
DC := TWMPaint(Message).DC; if DC = 0 then DC := BeginPaint(Handle, PS);
SaveIndex := SaveDC(DC);
try
h := Height div 2;
Btn := CreateBmp32(Width, h);
try
DrawBtn(Btn, sbkTop);
BitBlt(DC, 0, 0, Btn.Width, Btn.Height, Btn.Canvas.Handle, 0, 0, SRCCOPY);
DrawBtn(Btn, sbkBottom);
BitBlt(DC, 0, h, Btn.Width, Btn.Height, Btn.Canvas.Handle, 0, 0, SRCCOPY);
finally
FreeAndNil(Btn);
end;
finally
RestoreDC(DC, SaveIndex);
if TWMPaint(Message).DC = 0 then EndPaint(Handle, PS);
end;
end else inherited;
end
else begin
if (DefaultManager.ConstData.IndexScrollLeft > -1) and (DefaultManager.ConstData.IndexScrollRight > -1) then begin
DC := TWMPaint(Message).DC; if DC = 0 then DC := BeginPaint(Handle, PS);
SaveIndex := SaveDC(DC);
try
h := Width div 2;
Btn := CreateBmp32(h, Height);
try
DrawBtn(Btn, sbkLeft);
BitBlt(DC, 0, 0, Btn.Width, Btn.Height, Btn.Canvas.Handle, 0, 0, SRCCOPY);
DrawBtn(Btn, sbkRight);
BitBlt(DC, h, 0, Btn.Width, Btn.Height, Btn.Canvas.Handle, 0, 0, SRCCOPY);
finally
FreeAndNil(Btn);
end;
finally
RestoreDC(DC, SaveIndex);
if TWMPaint(Message).DC = 0 then EndPaint(Handle, PS);
end;
end else inherited;
end;
end
else inherited;
end
else inherited;
end;
end;
procedure TsUpDown.SetSkinSection(const Value: TsSkinSection);
begin
if FButtonSkin <> Value then begin
FButtonSkin := Value;
Invalidate;
end;
end;
procedure TsUpDown.DrawBtn(Btn: TBitmap; Kind: TsBtnKind);
var
CI : TCacheInfo;
p : TPoint;
State : integer;
c : TsColor;
R : TRect;
sSkinIndex, sArrowMask, sLimPosition, XOffset, YOffset : integer;
sSkinSection : string;
SkinManager : TsSkinManager;
begin
if Parent is TsPageControl then begin
SkinManager := TsPageControl(Parent).SkinData.SkinManager;
CI.Ready := False;
end
else begin
SkinManager := DefaultManager;
CI := GetParentCacheHwnd({Parent.}Handle);
end;
if not Assigned(SkinManager) then Exit;
sSkinIndex := -1;
if ButtonSkin <> '' then begin
sSkinSection := ButtonSkin;
sSkinIndex := SkinManager.GetSkinIndex(sSkinSection);
end;
with SkinManager.ConstData do begin
case Kind of
sbkTop : begin
if sSkinIndex < 0 then begin
sSkinIndex := IndexScrollTop;
sSkinSection := s_ScrollBtnTop;
end;
sArrowMask := MaskArrowTop;
sLimPosition := Max;
case DrawingState of dsPrevUp : State := 1; dsPrevDown : State := 2 else State := 0; end;
XOffset := 0;
YOffset := 0;
end;
sbkBottom : begin
Btn.Height := Height - Btn.Height;
if sSkinIndex < 0 then begin
sSkinIndex := IndexScrollBottom;
sSkinSection := s_ScrollBtnBottom;
end;
sArrowMask := MaskArrowBottom;
sLimPosition := Min;
case DrawingState of dsNextUp : State := 1; dsNextDown : State := 2 else State := 0 end;
XOffset := 0;
YOffset := Height - Btn.Height;
end;
sbkLeft : begin
if sSkinIndex < 0 then begin
sSkinIndex := IndexScrollLeft;
sSkinSection := s_ScrollBtnLeft;
end;
sArrowMask := MaskArrowLeft;
sLimPosition := Min;
case DrawingState of dsPrevUp : State := 1; dsPrevDown : State := 2 else State := 0; end;
XOffset := 0;
YOffset := 0;
end
else begin
Btn.Width := Width - Btn.Width;
if sSkinIndex < 0 then begin
sSkinIndex := IndexScrollRight;
sSkinSection := s_ScrollBtnRight;
end;
sArrowMask := MaskArrowRight;
sLimPosition := Max;
case DrawingState of dsNextUp : State := 1; dsNextDown : State := 2 else State := 0 end;
YOffset := 0;
XOffset := Width - Btn.Width;
end;
end;
if Assigned(SkinManager) then begin
R := Rect(0, 0, Btn.Width, Btn.Height);
CI := GetParentCacheHwnd(Handle);
PaintItem(sSkinIndex, sSkinSection, CI, True, State, R, Point(Left + XOffset, Top + YOffset), Btn, SkinManager);
end;
Ci.Bmp := Btn;
CI.Ready := True;
if (sArrowMask > -1) then begin
if SkinManager.ma[sArrowMask].Bmp = nil then begin
p.x := (Btn.Width - WidthOf(SkinManager.ma[sArrowMask].R) div SkinManager.ma[sArrowMask].ImageCount) div 2;
p.y := (Btn.Height - HeightOf(SkinManager.ma[sArrowMask].R) div (1 + SkinManager.ma[sArrowMask].MaskType)) div 2;
end
else if (SkinManager.ma[sArrowMask].Bmp.Height div 2 < Btn.Height) then begin
p.x := (Btn.Width - SkinManager.ma[sArrowMask].Bmp.Width div 3) div 2;
p.y := (Btn.Height - SkinManager.ma[sArrowMask].Bmp.Height div 2) div 2;
end;
if (p.x < 0) or (p.y < 0) then Exit;
DrawSkinGlyph(Btn, p, State, 1, SkinManager.ma[sArrowMask], CI);
end;
if not Enabled or (FShowInaccessibility and (Position = sLimPosition)) then begin
CI := GetParentCacheHwnd(Handle);
if not CI.Ready then begin
c.C := ColorToRGB(TsHackedControl(Parent).Color);
FadeBmp(Btn, Rect(0, 0, Btn.Width + 1, Btn.Height + 1), 60, c, 0, 0);
end
else BmpDisabledKind(Btn, FDisabledKind, Parent, CI, Point(Left + XOffset, Top + YOffset));
end;
end;
end;
end.
|
unit InfraRenderer;
interface
uses
InfraCommon,
InfraValueType,
InfraSingleton,
InfraMVPIntf,
InfraValueTypeIntf;
type
TObjectToPropertyConverter = class(TElement,
ITypeConverter, IObjectToProperty)
private
FObj: IInfraObject;
protected
function ConvertToRight(const Value: IInfraType;
const Format: IInfraType = nil): IInfraType;
function ConvertToLeft(const Value: IInfraType;
const Format: IInfraType = nil): IInfraType;
end;
TFormatProperty = class(TInfraType, IFormatProperty)
private
FPropertyName: string;
FRenderer: IRenderer;
protected
function GetPropertyName: string;
function GetRenderer: IRenderer;
procedure SetPropertyName(const Value: string);
procedure SetRenderer(const Value: IRenderer);
property PropertyName: string read GetPropertyName write SetPropertyName;
property Renderer: IRenderer read GetRenderer write SetRenderer;
end;
TRenderer = class(TElement, IRenderer)
private
FFormat: IInfraType;
FConverter: ITypeConverter;
FView: IView;
public
function GetFormat: IInfraType;
function GetTypeConverter: ITypeConverter;
function GetView: IView;
procedure SetFormat(const Value: IInfraType);
procedure SetTypeConverter(const Value: ITypeConverter);
procedure SetView(const Value: IView);
property Format: IInfraType read GetFormat write SetFormat;
property View: IView read GetView write SetView;
property TypeConverter: ITypeConverter read GetTypeConverter
write SetTypeConverter;
end;
implementation
uses
SysUtils, InfraValueTypeConvert;
{ TObjectToPropertyConverter }
function TObjectToPropertyConverter.ConvertToRight(const Value,
Format: IInfraType): IInfraType;
begin
Result := nil;
if Supports(Value, IInfraObject, FObj) then
begin
with Format as IFormatProperty do
if Assigned(Renderer) then
Result := Renderer.TypeConverter.ConvertToRight(
FObj.GetProperty(PropertyName), Renderer.Format) as IInfraType
else
Result := FObj.GetProperty(PropertyName) as IInfraType;
end;
end;
function TObjectToPropertyConverter.ConvertToLeft(const Value,
Format: IInfraType): IInfraType;
var
lProperty: IProperty;
begin
if Supports(Value, IProperty, lProperty) then
begin
with Format as IFormatProperty do
lProperty.Assign(Renderer.TypeConverter.ConvertToLeft(
FObj.GetProperty(PropertyName), Renderer.Format));
end;
Result := lProperty as IInfraType;
end;
{ TFormatProperty }
function TFormatProperty.GetPropertyName: string;
begin
Result := FPropertyName;
end;
function TFormatProperty.GetRenderer: IRenderer;
begin
Result := FRenderer;
end;
procedure TFormatProperty.SetPropertyName(const Value: string);
begin
FPropertyName := Value;
end;
procedure TFormatProperty.SetRenderer(const Value: IRenderer);
begin
FRenderer := Value;
end;
{ TRenderer }
function TRenderer.GetFormat: IInfraType;
begin
Result := FFormat;
end;
function TRenderer.GetTypeConverter: ITypeConverter;
begin
if not Assigned(FConverter) then
FConverter := TNullConverter.Create;
Result := FConverter;
end;
function TRenderer.GetView: IView;
begin
Result := FView;
end;
procedure TRenderer.SetFormat(const Value: IInfraType);
begin
if FFormat <> Value then
FFormat := Value;
end;
procedure TRenderer.SetTypeConverter(const Value: ITypeConverter);
begin
if FConverter <> Value then
FConverter := Value;
end;
procedure TRenderer.SetView(const Value: IView);
begin
SetReference(IInterface(FView), Value);
end;
end.
|
unit UResponseUdpThread;
interface
uses
Windows,
Classes,
SysUtils,
WinSock,
eiTypes,
eiConstants,
eiExceptions,
UServerTypes,
UBaseThread,
UPacketHandlers;
type
TResponseUdpThread = class(TBaseSocketThread)
private
FClientAddr: TSockAddrIn;
FHandler: IHandler;
FBuffer: DynamicByteArray;
public
constructor Create(logger: ILogger; const request: RequestStruct);
destructor Destroy; override;
procedure Execute; override;
end;
implementation
constructor TResponseUdpThread.Create(logger: ILogger; const request: RequestStruct);
var
code: int;
bufferLength: int;
begin
inherited Create(true);
FLogger := logger;
try
ZeroMemory(@FClientAddr, SizeOf(TSockAddrIn));
CopyMemory(@FClientAddr, @request.Target, SizeOf(TSockAddrIn));
// FClientAddr := target;
bufferLength := Length(request.Buffer);
SetLength(FBuffer, bufferLength);
CopyMemory(FBuffer, request.Buffer, bufferLength);
FHandler := request.Handler;
ZeroMemory(@FWsaData, SizeOf(TWsaData));
code := WSAStartup(WINSOCK_VERSION, FWsaData);
if code <> 0 then
raise ESocketException.Create(GetLastErrorString());
FSocket := request.Socket;
if FSocket = INVALID_SOCKET then
raise ESocketException.Create(GetLastErrorString());
FLogger.Log('Response thread created', elNotice);
except
on Ex: Exception do
FLogger.Log(Ex.Message, elError);
end;
end;
destructor TResponseUdpThread.Destroy;
begin
FLogger.Log('Response thread destroyed');
inherited;
end;
procedure TResponseUdpThread.Execute;
var
returnLength: int;
sendBuffer: DynamicByteArray;
len: int;
begin
try
sendBuffer := FHandler.Process(FBuffer);
len := SizeOf(TSockAddrIn);
returnLength := sendto(FSocket, Pointer(sendBuffer)^, Length(sendBuffer), 0, FClientAddr, len);
if (returnLength = SOCKET_ERROR) then
raise ESocketException.Create(GetLastErrorString());
FLogger.Log('Outbound data length ' + IntToStr(returnLength));
FLogger.Log('To ' + inet_ntoa(FClientAddr.sin_addr) + ' : ' + IntToStr(FClientAddr.sin_port));
except
on Ex: Exception do
FLogger.Log(Ex.Message, elError);
end;
end;
end.
|
unit iptypes;
interface
{$WEAKPACKAGEUNIT}
uses Windows;
const
MAX_ADAPTER_DESCRIPTION_LENGTH = 128; // arb.
MAX_ADAPTER_NAME_LENGTH = 256; // arb.
MAX_ADAPTER_ADDRESS_LENGTH = 8; // arb.
DEFAULT_MINIMUM_ENTITIES = 32; // arb.
MAX_HOSTNAME_LEN = 128; // arb.
MAX_DOMAIN_NAME_LEN = 128; // arb.
MAX_SCOPE_ID_LEN = 256; // arb.
//
// types
//
// Node Type
BROADCAST_NODETYPE = 1;
PEER_TO_PEER_NODETYPE = 2;
MIXED_NODETYPE = 4;
HYBRID_NODETYPE = 8;
// Adapter Type
IF_OTHER_ADAPTERTYPE = 0;
IF_ETHERNET_ADAPTERTYPE = 1;
IF_TOKEN_RING_ADAPTERTYPE = 2;
IF_FDDI_ADAPTERTYPE = 3;
IF_PPP_ADAPTERTYPE = 4;
IF_LOOPBACK_ADAPTERTYPE = 5;
IF_SLIP_ADAPTERTYPE = 6;
//
// IP_ADDRESS_STRING - store an IP address as a dotted decimal string
//
type
IP_ADDRESS_STRING = record
_String : array [0..4*4-1] of char;
end;
PIP_ADDRESS_STRING = ^IP_ADDRESS_STRING;
IP_MASK_STRING = IP_ADDRESS_STRING;
PIP_MASK_STRING = ^IP_MASK_STRING;
//
// IP_ADDR_STRING - store an IP address with its corresponding subnet mask,
// both as dotted decimal strings
//
PIP_ADDR_STRING = ^IP_ADDR_STRING;
IP_ADDR_STRING = record
Next : PIP_ADDR_STRING;
IpAddress : IP_ADDRESS_STRING;
IpMask : IP_MASK_STRING;
Context : DWORD;
end;
//
// ADAPTER_INFO - per-adapter information. All IP addresses are stored as
// strings
//
PIP_ADAPTER_INFO = ^IP_ADAPTER_INFO;
IP_ADAPTER_INFO = record
Next : PIP_ADAPTER_INFO;
ComboIndex : DWORD;
AdapterName : array [0..MAX_ADAPTER_NAME_LENGTH + 4 - 1] of char;
Description : array [0..MAX_ADAPTER_DESCRIPTION_LENGTH + 4 - 1] of char;
AddressLength : DWORD;
Address : array [0..MAX_ADAPTER_ADDRESS_LENGTH - 1] of byte;
Index : DWORD;
_Type : UINT;
DhcpEnabled : UINT;
CurrentIpAddress : PIP_ADDR_STRING;
IpAddressList : IP_ADDR_STRING;
GatewayList : IP_ADDR_STRING;
DhcpServer : IP_ADDR_STRING;
HaveWins : BOOL;
PrimaryWinsServer : IP_ADDR_STRING;
SecondaryWinsServer : IP_ADDR_STRING;
LeaseObtained : DWORD; // time_t
LeaseExpires : DWORD; // time_t
end;
//
// IP_PER_ADAPTER_INFO - per-adapter IP information such as DNS server list.
//
IP_PER_ADAPTER_INFO = record
AutoconfigEnabled : UINT;
AutoconfigActive : UINT;
CurrentDnsServer : PIP_ADDR_STRING;
DnsServerList : IP_ADDR_STRING;
end;
PIP_PER_ADAPTER_INFO= ^IP_PER_ADAPTER_INFO;
//
// FIXED_INFO - the set of IP-related information which does not depend on DHCP
//
FIXED_INFO = record
HostName : array [0..MAX_HOSTNAME_LEN + 4 - 1] of char;
DomainName : array [0..MAX_DOMAIN_NAME_LEN + 4 - 1] of char;
CurrentDnsServer : PIP_ADDR_STRING;
DnsServerList : IP_ADDR_STRING;
NodeType : UINT;
ScopeId : array [0..MAX_SCOPE_ID_LEN + 4 - 1] of char;
EnableRouting : UINT;
EnableProxy : UINT;
EnableDns : UINT;
end;
PFIXED_INFO = ^FIXED_INFO;
implementation
end.
|
unit BaseWizard;
interface
uses
Windows, Classes, SysUtils, ToolsAPI;
type
TBaseWizard = class(TNotifierObject, IOTAWizard, IOTANotifier)
private
FIDString: string;
FName: string;
protected
// IOTAWizard
function GetIDString: string; virtual;
function GetName: string; virtual;
function GetState: TWizardState; virtual;
procedure Execute; virtual;
//
function GetEditor: IOTASourceEditor;
procedure GetSource(Source: TStream);
public
constructor Create(IDString, Name: String);
end;
implementation
{ TBaseWizard }
{ Private declarations }
{ Protected declarations }
function TBaseWizard.GetIDString: string;
begin
Result := FIDString;
end;
function TBaseWizard.GetName: string;
begin
Result := FName;
end;
function TBaseWizard.GetState: TWizardState;
begin
Result := [];
end;
procedure TBaseWizard.Execute;
begin
end;
function TBaseWizard.GetEditor: IOTASourceEditor;
var
ModuleServices: IOTAModuleServices;
Module: IOTAModule;
Intf: IOTAEditor;
I: Integer;
begin
Result := nil;
ModuleServices := BorlandIDEServices as IOTAModuleServices;
// Get the module interface for the current file.
Module := ModuleServices.CurrentModule;
// If no file is open, Module is nil.
if Module = nil then
Exit;
// Get the interface to the source editor.
for I := 0 to Module.GetModuleFileCount-1 do
begin
Intf := Module.GetModuleFileEditor(I);
if Intf.QueryInterface(IOTASourceEditor, Result) = S_OK then
Break;
end;
end;
procedure TBaseWizard.GetSource(Source: TStream);
var
Editor: IOTASourceEditor;
Reader: IOTAEditReader;
Buffer: array[0..1023] of Char;
Position, ReadLength: Integer;
begin
Editor := GetEditor;
Reader := Editor.CreateReader;
Position := 0;
repeat
ReadLength := Reader.GetText(Position, PChar(@Buffer), SizeOf(Buffer));
if ReadLength > 0 then
Source.Write(Buffer, ReadLength);
Position := Position + ReadLength;
until ReadLength = 0;
end;
{ Public declarations }
constructor TBaseWizard.Create(IDString, Name: String);
begin
Assert(IDString <> '', 'Error: IDString cannot be empty');
Assert(Name <> '', 'Error: Name cannot be empty');
inherited Create;
FIDString := IDString;
FName := Name;
end;
end.
|
UNIT dempak;
INTERFACE
USES
General_Res;
TYPE
TDeMPAKCommand=(dcExtractAll,dcGetCatalog,dcGetEntry);
FUNCTION _IsMPAK( InputFileName:STRING):Boolean;
FUNCTION _DeMPAK( InputFileName:STRING;
BaseDirectory:STRING;
Command:TDeMPAKCommand=dcExtractAll
):TStringMemoryStream;
IMPLEMENTATION
USES
SysUtils,
ZlibEX,
Windows,
FileCtrl,
Classes;
CONST
ChunkSize = 1024;
VAR
// Variable de décompression
ZStream:TZStreamRec;
ZLIB_Initialized:Boolean; // Indique si il s'agit du premier appel à zLib
Junk_Input:Integer; // Quantité de données non utilisé lors de la décompression
// Variable du catalogue
FileDirectory:TStringList;
FilePosDirectory:ARRAY OF Integer;
// Variable fichier
InputFile:FILE;
// Flux mémoire temporaire
TempStream:TStringMemoryStream;
FUNCTION _IsMPAK;
VAR
f:FILE;
s:STRING;
BEGIN
AssignFile( f, InputFileName);
ReSet(f,1);
s := 'XXXX';
BlockRead(f,s[1],4);
CloseFile(f);
Result := s = 'MPAK';
END;
PROCEDURE SafeFreeMem;
BEGIN
TRY
CloseFile(InputFile);
EXCEPT
END;
FileDirectory.Free;
TempStream.Free;
END;
FUNCTION CZInflate(DeflatedString:STRING):STRING;
VAR
Input_Size:Integer;
OutputBuffer:STRING;
LoopChecker:Boolean;
FuncResult:HResult;
BEGIN
OutStr('Entrée dans CZInflate',3);
Junk_Input := 0;
Result := '';
IF ZLIB_Initialized THEN BEGIN
Input_Size := Length(DeflatedString) + ZStream.Total_In;
ZStream.Next_In := @DeflatedString[1];
ZStream.Avail_In := Length(DeflatedString);
ZStream.Opaque := NIL;
LoopChecker := False;
SetLength(OutputBuffer,chunksize);
ZStream.Avail_Out := ChunkSize;
ZStream.Next_Out := @OutputBuffer[1];
REPEAT
FuncResult := Inflate( ZStream, 0);
CASE FuncResult OF
Z_Ok:BEGIN
IF ZStream.Avail_Out = 0 THEN BEGIN
Result := Result + OutputBuffer;
ZStream.Next_Out := @OutputBuffer[1];
ZStream.Avail_Out := ChunkSize;
END;
END;
Z_Stream_End:BEGIN
LoopChecker := True;
END;
Z_Buf_Error:BEGIN
LoopChecker := True;
END;
END;
IF ( FuncResult < 0 ) AND ( NOT LoopChecker ) THEN RAISE EMPAKError.RaiseMe(2);
UNTIL LoopChecker;
Result := Result + Copy( OutputBuffer, 1, Chunksize - ZStream.Avail_Out);
Junk_Input := Input_Size - ZStream.Total_In;
END ELSE BEGIN
OutStr('Initialisation du flux de décompression',2);
ZLIB_Initialized := True;
Input_Size := Length(DeflatedString);
ZeroMemory( @ZStream, SizeOf(ZStream));
ZStream.Next_In := @DeflatedString[1];
ZStream.Avail_In := Length(DeflatedString);
ZStream.Opaque := NIL;
FuncResult := InflateInit(ZStream);
IF FuncResult <> Z_Ok THEN RAISE EMPAKError.RaiseMe(3);
LoopChecker := False;
SetLength( OutputBuffer, ChunkSize);
ZStream.Next_Out := @OutputBuffer[1];
ZStream.Avail_Out := ChunkSize;
REPEAT
FuncResult := Inflate( ZStream, 0);
CASE FuncResult OF
Z_Ok:BEGIN
IF ZStream.Avail_Out = 0 THEN BEGIN
Result := Result + OutputBuffer;
ZStream.Next_Out := @OutputBuffer[1];
ZStream.Avail_Out := ChunkSize;
END;
END;
Z_Stream_End:BEGIN
LoopChecker := True;
END;
Z_Buf_Error:BEGIN
LoopChecker := True;
END;
END;
IF ( FuncResult < 0 ) AND ( NOT LoopChecker ) THEN RAISE EMPAKError.RaiseMe(2);
UNTIL LoopChecker;
Result := Result + Copy( OutputBuffer, 1, ChunkSize - ZStream.Avail_Out);
Junk_Input := Input_Size - ZStream.Total_In;
END;
END;
PROCEDURE CZStop;
BEGIN
InflateEnd(ZStream);
ZLIB_Initialized := False;
END;
FUNCTION ReadStream:HResult;
VAR
StreamOrigin:Integer;
ByteRead:Integer;
ReadBuffer:STRING;
ReadSize:Integer;
BEGIN
OutStr( 'Entrée dans la procédure ReadStream', 3);
Result := 0;
StreamOrigin := Filepos(InputFile);
ByteRead := 0;
OutStr( 'Vidage du flux mémoire temporaire', 3);
TempStream.Clear;
REPEAT
SetLength( ReadBuffer, ChunkSize);
BlockRead( InputFile, ReadBuffer[1], ChunkSize, ReadSize);
SetLength( ReadBuffer, ReadSize);
ByteRead := ByteRead + ReadSize;
TempStream.WriteStr(CZInflate(ReadBuffer));
UNTIL ( Junk_Input <> 0 ) OR ( ReadSize < ChunkSize);
Seek( InputFile, StreamOrigin + ByteRead - Junk_Input);
CZStop;
END;
PROCEDURE AddFilePos(Value:Integer);
BEGIN
SetLength( FilePosDirectory, Length(FilePosDirectory) + 1);
FilePosDirectory[High(FilePosDirectory)] := Value;
END;
PROCEDURE DecodeDirectory;
var
BaseOffSet:Integer;
Catalog:STRING;
Offset:Integer;
TempName:STRING;
Reader:Integer;
EntryOffset:Integer;
begin
OutStr( 'Entrée dans DecodeDirectory', 3);
BaseOffset := FilePos(InputFile);
Catalog := TempStream.ReadStr;
FileDirectory.Clear;
SetLength(FilePosDirectory,0);
Offset := 1;
WHILE Offset + 283 <= Length(Catalog) DO BEGIN
TempName := '';
Reader := 0;
WHILE ( ( Offset + Reader ) < Length(Catalog) ) AND (Catalog[Offset + Reader] <> Chr(0) ) DO BEGIN
TempName := TempName + Catalog[Offset + Reader];
Reader := Reader + 1;
END;
CopyMemory(@EntryOffset,@Catalog[OffSet+272],4);
AddFilePos(BaseOffset + EntryOffset);
FileDirectory.Add(LowerCase(TempName));
Offset := Offset + 284;
END;
END;
FUNCTION _DeMPAK;
VAR
i:Integer;
s,s2:STRING;
WritingStream:TFileStream;
BEGIN
Result := NIL;
TRY
// Initialisation des variables communes aux fonctions
OutStr( 'Initialisation des variables', 2);
OutStr( '-->ZLIB_Initialized', 3);
ZLIB_Initialized := false;
OutStr( '-->FileCatalog', 3);
FileDirectory := TStringList.Create;
OutStr( '-->TempStream', 3);
TempStream := TStringMemoryStream.Create;
// Ouverture du fichier
OutStr( 'Ouverture du fichier '+InputFileName, 2);
AssignFile(InputFile, InputFileName);
ReSet(InputFile, 1);
// On vérifie que c'est un MPAK
OutStr( 'Vérification du FCC', 2);
s := 'XXXX';
BlockRead(InputFile,s[1],4);
OutStr( 'FCC:'+s, 3);
IF s = 'MPAK' THEN BEGIN
// Fichier MPAK, on continue dans cette indentation
// Le début des est au 21eme octet
OutStr( 'Décalage 21 et lecture du premier flux', 2);
Seek( InputFile, 21);
ReadStream;
s:=TempStream.ReadStr;
OutStr( 'Nom du fichier d''origine:'+s, 2);
OutStr( 'Lecture de la liste de fichier', 2);
ReadStream;
OutStr( 'Décodage de la liste de ficheir', 2);
DecodeDirectory;
IF Command = dcGetCatalog THEN BEGIN
Result := TStringMemoryStream.Create;
Result.WriteStr(FileDirectory.CommaText);
END;
IF Command = dcExtractAll THEN BEGIN
Pathyfy(BaseDirectory);
BaseDirectory := BaseDirectory + ExtractFileName(InputFileName) + '.out\';
ForceDirectories(BaseDirectory);
FOR i:=0 TO FileDirectory.Count-1 DO BEGIN
Seek(InputFile,FilePosDirectory[i]);
OutStr( 'Décompression du fichier '+FileDirectory.Strings[i], 1);
ReadStream;
OutStr( 'Ecriture du fichier '+basedirectory+FileDirectory.Strings[i], 1);
s:=BaseDirectory+FileDirectory.Strings[i];
s2:=s+#0;
IF FileExists(s) THEN DeleteFile(@s2[1]);
WritingStream := TFileStream.Create( s, fmCreate);
WritingStream.CopyFrom( TempStream, 0);
WritingStream.Free;
END;
END;
IF Command = dcGetEntry THEN BEGIN
BaseDirectory := LowerCase(BaseDirectory);
IF FileDirectory.IndexOf(BaseDirectory) = -1 THEN BEGIN
RAISE EMPAKError.RaiseMe(1);
END;
Seek(InputFile,FilePosDirectory[FileDirectory.IndexOf(BaseDirectory)]);
OutStr( 'Décompression du fichier '+BaseDirectory, 2);
ReadStream;
OutStr( 'Transfert des données décompressée comme résultat de la fonction', 2);
Result := TStringMemoryStream.Create;
Result.CopyFrom( TempStream, 0);
END;
OutStr( 'Terminé', 2);
END ELSE BEGIN
OutStr( 'Le fichier '+InputFileName+' n''est pas un fichier MPAK', 2);
END;
FINALLY
SafeFreeMem;
END;
END;
END.
(*
Mode d'emploi de cette unitée:
Elle permet de décoder les fichiers MPAK(mpk et npk) de DAoC
_IsMPAK
PAramères:
InputFileName:STRING Nom du fichier à vérifier
Renvoie True si le fichier est un MPAK(d'après FCC)
_DeMPAK
Paramètres:
InputFileName:STRING Nom du fichier MPAK source
BaseDirectory:STRING Dossier où seront placé les fichiers extraits
OU nom du fichier à extraire
Command:TDeMPAKCommand Commande à éxécuter
Result:TStringMemoryStream Dépend du paramètre Command.
Type de données:
TDeMPAKCommand=(dcExtractAll,dcGetCatalog,dcGetEntry)
-dcCheckMPAK : Vérifie qu'il s'agit bien d'un fichier MPAK
-dcExtractAll : extrait tout les fichiers de la source vers le dossier
BaseDirectory spécifié, sous dossiers sources.out\
-dcGetCatalog : renvoie dans Result le CommaText du catalogue de fichier
-dcGetEntry : renvoie dans Result le fichier spécifié par BaseDirectory
(exception MPAK1 si fichier introuvable)
(le fichier zones.mpk est géré spécialement et ne permet
d'extraire que zones.dat)
Auteur : Gabriel Paul 'Cley Faye' Risterucci
Homepage : new664.fr.st
mail : dareaperpa666@hotmail.com
Le fichier source de mon mapper DAoC est grandement inspiré de celui trouvé
sur www.randomly.org.
|
unit eVideoMovie;
interface
uses
API_ORM,
eCommon,
eExtLink,
eGenre,
eVideoFile;
type
TMovie = class(TEntity)
private
FExtLinks: TMovieExtLinkList;
FGenreRels: TGenreRelList;
FStoryline: string;
FTitle: string;
FTitleOrig: string;
FVideoFiles: TVideoFileList;
FYear: Integer;
function GetExtLinks: TMovieExtLinkList;
function GetGenreRels: TGenreRelList;
function GetVideoFiles: TVideoFileList;
public
class function GetStructure: TSructure; override;
property ExtLinks: TMovieExtLinkList read GetExtLinks;
property GenreRels: TGenreRelList read GetGenreRels;
property VideoFiles: TVideoFileList read GetVideoFiles;
published
property Storyline: string read FStoryline write FStoryline;
property Title: string read FTitle write FTitle;
property TitleOrig: string read FTitleOrig write FTitleOrig;
property Year: Integer read FYear write FYear;
end;
TVideoList = TEntityList<TMovie>;
implementation
function TMovie.GetVideoFiles: TVideoFileList;
begin
if not Assigned(FVideoFiles) then
FVideoFiles := TVideoFileList.Create(Self);
Result := FVideoFiles;
end;
function TMovie.GetGenreRels: TGenreRelList;
begin
if not Assigned(FGenreRels) then
FGenreRels := TGenreRelList.Create(Self);
Result := FGenreRels;
end;
function TMovie.GetExtLinks: TMovieExtLinkList;
begin
if not Assigned(FExtLinks) then
FExtLinks := TMovieExtLinkList.Create(Self);
Result := FExtLinks;
end;
class function TMovie.GetStructure: TSructure;
begin
Result.TableName := 'VIDEO_MOVIES';
end;
end.
|
//Banco de dados
unit uEstadoModel;
interface
uses
System.SysUtils, FireDAC.Comp.Client, Data.DB, FireDAC.DApt, FireDAC.Comp.UI,
FireDAC.Comp.DataSet, uListaEstados,
uEstadoDto, uClassConexaoSingleton;
type
TEstadoModel = class
public
function BuscarEstados: TDataSource;
function BuscarListaEstados(out ALista: TListaEstados): Boolean;
function Ler(var AEstado: TEstadoDto): Boolean;
function Inserir(var AEstado: TEstadoDto): Boolean;
function Alterar(var AEstado: TEstadoDto): Boolean;
function Deletar(const AIDUF: Integer): Boolean;
function BuscarID: Integer;
end;
implementation
{ TEstadoModel }
function TEstadoModel.Alterar(var AEstado: TEstadoDto): Boolean;
var
sSql: String;
begin
sSql := 'update Estado'+
' set UF = '+QuotedStr(AEstado.UF)+
' , Nome = '+QuotedStr(AEstado.Nome)+
' where idEstado = '+IntToStr(AEstado.ID);
Result := TConexaoSingleton.GetInstancia.ExecSQL(sSql) > 0;
end;
function TEstadoModel.BuscarEstados: TDataSource;
var
oQuery: TFDQuery;
begin
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TConexaoSingleton.GetInstancia;
oQuery.Open('select UF, NOME from Estado');
if (not(oQuery.IsEmpty)) then
Result := oQuery.DataSource;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
function TEstadoModel.BuscarID: Integer;
var
oQuery: TFDQuery;
begin
Result := 1;
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TConexaoSingleton.GetInstancia;
oQuery.Open('select max(idEstado) as ID'+
' from Estado');
if (not(oQuery.IsEmpty)) then
Result := oQuery.FieldByName('ID').AsInteger + 1;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
function TEstadoModel.BuscarListaEstados(out ALista: TListaEstados): Boolean;
var
oEstadoDTO: TEstadoDTO;
oQuery: TFDQuery;
begin
Result := False;
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TConexaoSingleton.GetInstancia;
oQuery.Open('select IdEstado, UF, NOME from Estado');
if (not(oQuery.IsEmpty)) then
begin
oQuery.First;
while (not(oQuery.Eof)) do
begin
oEstadoDTO := TEstadoDto.Create;
oEstadoDTO.ID := oQuery.FieldByName('IdEstado').AsInteger;
oEstadoDTO.Nome := oQuery.FieldByName('Nome').AsString;
oEstadoDTO.UF := oQuery.FieldByName('UF').AsString;
ALista.Add(oEstadoDTO.Nome, oEstadoDTO);
oQuery.Next;
end;
Result := True;
end;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
function TEstadoModel.Deletar(const AIDUF: Integer): Boolean;
begin
Result := TConexaoSingleton.GetInstancia.ExecSQL(
'delete from Estado where idEstado = '+IntToStr(AIDUF)) > 0;
end;
function TEstadoModel.Inserir(var AEstado: TEstadoDto): Boolean;
var
sSql: String;
begin
sSql := 'insert into Estado (idEstado,'+
' UF,'+
' Nome) values ('+
IntToStr(AEstado.ID)+', '+
QuotedStr(AEstado.UF)+', '+
QuotedStr(AEstado.Nome)+')';
Result := TConexaoSingleton.GetInstancia.ExecSQL(sSql) > 0;
end;
function TEstadoModel.Ler(var AEstado: TEstadoDto): Boolean;
var
oQuery: TFDQuery;
begin
Result := False;
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TConexaoSingleton.GetInstancia;
// oQuery.Open('select idEstado, Nome from Estado where UF = '''+AEstado.UF+'''');
oQuery.Open('select idEstado, Nome'+
' from Estado'+
' where UF = '+QuotedStr(AEstado.UF));
if (not(oQuery.IsEmpty)) then
begin
AEstado.ID := oQuery.FieldByName('idEstado').AsInteger;
AEstado.Nome := oQuery.FieldByName('Nome').AsString;
Result := True;
end;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
end.
|
unit SQLEditor;
interface
uses
Winapi.Windows, Winapi.CommDlg, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls,
Vcl.Forms, Vcl.Dialogs, SynEdit, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.ImgList, JvExComCtrls, JvComCtrls, Vcl.Menus,
SynHighlighterSQL, Output, SynEditHighlighter, SynEditPrint, OraError, SynEditMiscClasses, SynEditSearch,
SynEditTypes, Vcl.Buttons, Vcl.StdCtrls, Vcl.ActnList, JvExExtCtrls, JvSplitter, DAScript, OraScript, MemDS, DBAccess,
Ora, ToolWin, SynCompletionProposal, JvStringHolder, BCControls.PageControl,
Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, Vcl.ActnMan, BCControls.ToolBar, BCControls.ImageList,
BCControls.DBGrid, Vcl.Themes, Data.DB, BCControls.CheckBox, SynEditRegexSearch, BCControls.OraSynEdit,
SQLEditorTabSheet, BCFrames.Compare, SynEditWildcardSearch, System.Actions, Vcl.ActnCtrls, BCControls.ButtonedEdit,
System.Contnrs, JvExStdCtrls, JvCheckBox;
type
TSQLEditorFrame = class(TFrame)
SynEditPrint: TSynEditPrint;
SynEditSearch: TSynEditSearch;
SearchPanel: TPanel;
ActionList: TActionList;
SearchCloseAction: TAction;
SearchFindNextAction: TAction;
SearchFindPreviousAction: TAction;
DocumentPanel: TPanel;
PageControl: TBCPageControl;
OutputPanel: TPanel;
HorizontalSplitter: TJvSplitter;
ToolbarPanel: TPanel;
SynSQLSyn: TSynSQLSyn;
OraScript: TOraScript;
EditorPopupActionBar: TPopupActionBar;
InsertObjectMenuItem: TMenuItem;
ColumnsQuery: TOraQuery;
SQLStringHolder: TJvMultiStringHolder;
ScriptQuery: TOraQuery;
Separator7MenuItem: TMenuItem;
FormatSQLMenuItem: TMenuItem;
ErrorsQuery: TOraQuery;
ImageList16: TImageList;
BookmarkImagesList: TBCImageList;
CutMenuItem: TMenuItem;
CopyMenuItem: TMenuItem;
PasteMenuItem: TMenuItem;
Separator1MenuItem: TMenuItem;
IncreaseIndentMenuItem: TMenuItem;
DecreaseIndentMenuItem: TMenuItem;
Separator4MenuItem: TMenuItem;
SortAscendingMenuItem: TMenuItem;
SortDescendingMenuItem: TMenuItem;
Separator6MenuItem: TMenuItem;
UndoMenuItem: TMenuItem;
RedoMenuItem: TMenuItem;
Separator2MenuItem: TMenuItem;
SelectAllMenuItem: TMenuItem;
Separator5MenuItem: TMenuItem;
ToggleCaseMenuItem: TMenuItem;
ToggleBookmarksMenuItem: TMenuItem;
GotoBookmarksMenuItem: TMenuItem;
Separator3MenuItem: TMenuItem;
ClearBookmarksMenuItem: TMenuItem;
ToggleBookmark1MenuItem: TMenuItem;
ToggleBookmark2MenuItem: TMenuItem;
ToggleBookmark3MenuItem: TMenuItem;
ToggleBookmark4MenuItem: TMenuItem;
ToggleBookmark5MenuItem: TMenuItem;
ToggleBookmark6MenuItem: TMenuItem;
ToggleBookmark7MenuItem: TMenuItem;
ToggleBookmark8MenuItem: TMenuItem;
ToggleBookmark9MenuItem: TMenuItem;
GotoBookmark1MenuItem: TMenuItem;
GotoBookmark2MenuItem: TMenuItem;
GotoBookmark3MenuItem: TMenuItem;
GotoBookmark4MenuItem: TMenuItem;
GotoBookmark5MenuItem: TMenuItem;
GotoBookmark6MenuItem: TMenuItem;
GotoBookmark7MenuItem: TMenuItem;
GotoBookmark8MenuItem: TMenuItem;
GotoBookmark9MenuItem: TMenuItem;
ExecuteToolbarPanel: TPanel;
ExecuteToolBar: TBCToolBar;
ExecuteToolButton: TToolButton;
ExecuteScriptToolButton: TToolButton;
Toolbar1Bevel: TBevel;
TransactionToolbarPanel: TPanel;
CommitRollbackToolBar: TBCToolBar;
CommitToolButton: TToolButton;
RollbackToolButton: TToolButton;
Bevel1: TBevel;
DBMSToolbarPanel: TPanel;
DBMSToolBar: TBCToolBar;
DBMSOutputToolButton: TToolButton;
Bevel3: TBevel;
ExplainPlanToolbarPanel: TPanel;
PlanToolBar: TBCToolBar;
ExplainPlanToolButton: TToolButton;
Bevel4: TBevel;
StandardToolbarPanel: TPanel;
StandardToolBar: TBCToolBar;
FileNewToolButton: TToolButton;
FileOpenToolButton: TToolButton;
Bevel5: TBevel;
PrintToolbarPanel: TPanel;
PrintToolBar: TBCToolBar;
FilePrintToolButton: TToolButton;
FilePrintPreviewToolButton: TToolButton;
Bevel7: TBevel;
IndentToolbarPanel: TPanel;
IncreaseToolBar: TBCToolBar;
EditIncreaseIndentToolButton: TToolButton;
EditDecreaseIndentToolButton: TToolButton;
Bevel8: TBevel;
SortToolbarPanel: TPanel;
SortToolBar: TBCToolBar;
EditSortAscToolButton: TToolButton;
EditSortDescToolButton: TToolButton;
Bevel9: TBevel;
CaseToolbarPanel: TPanel;
CaseToolBar: TBCToolBar;
EditToggleCaseToolButton: TToolButton;
Bevel10: TBevel;
CommandToolbarPanel: TPanel;
CommandToolBar: TBCToolBar;
EditUndoToolButton: TToolButton;
EditRedoToolButton: TToolButton;
Bevel11: TBevel;
SearchToolbarPanel: TPanel;
SearchToolBar: TBCToolBar;
SearchToolButton: TToolButton;
SearchReplaceToolButton: TToolButton;
SearchFindInFilesToolButton: TToolButton;
Bevel13: TBevel;
ModeToolbarPanel: TPanel;
ViewToolBar: TBCToolBar;
ViewWordWrapToolButton: TToolButton;
ViewLineNumbersToolButton: TToolButton;
ViewSpecialCharsToolButton: TToolButton;
ViewSelectionModeToolButton: TToolButton;
Bevel14: TBevel;
ToolsToolBarPanel: TPanel;
CompareToolBar: TBCToolBar;
ToolsCompareFilesToolButton: TToolButton;
SaveToolBar: TBCToolBar;
FileSaveToolButton: TToolButton;
FileSaveAsToolButton: TToolButton;
FileSaveAllToolButton: TToolButton;
Bevel6: TBevel;
ToggleBookmarkMenuItem: TMenuItem;
ImageList20: TBCImageList;
ImageList24: TBCImageList;
SearchPanel2: TPanel;
SearchForLabel: TLabel;
SearchPanel3: TPanel;
SearchForEdit: TBCButtonedEdit;
SearchPanel1: TPanel;
JvSpeedButton1: TSpeedButton;
SearchPanel5: TPanel;
SpeedButton1: TSpeedButton;
SearchPanel6: TPanel;
SpeedButton2: TSpeedButton;
SearchPanel7: TPanel;
CaseSensitiveCheckBox: TBCCheckBox;
Panel1: TPanel;
WholeWordsCheckBox: TBCCheckBox;
Panel2: TPanel;
RegularExpressionCheckBox: TBCCheckBox;
SynEditRegexSearch: TSynEditRegexSearch;
GotoLinePanel: TPanel;
GotoLineClosePanel: TPanel;
GotoLineCloseSpeedButton: TSpeedButton;
GotoLineLabelPanel: TPanel;
GotoLineLabel: TLabel;
LineNumberPanel: TPanel;
GotoLineNumberEdit: TBCButtonedEdit;
GotoLineButtonPanel: TPanel;
GotoLineGoSpeedButton: TSpeedButton;
GotoLineAction: TAction;
GotoLineCloseAction: TAction;
FileCloseToolButton: TToolButton;
FileCloseAllToolButton: TToolButton;
SynEditWildcardSearch: TSynEditWildcardSearch;
ExecuteCurrentToolButton: TToolButton;
SearchClearAction: TAction;
GotoLineClearAction: TAction;
AfterRegularExpressionPanel: TPanel;
WildCardCheckBox: TBCCheckBox;
BoxDownAction: TAction;
BoxLeftAction: TAction;
BoxRightAction: TAction;
BoxUpAction: TAction;
procedure SynEditOnChange(Sender: TObject);
procedure SynEditorReplaceText(Sender: TObject; const ASearch,
AReplace: UnicodeString; Line, Column: Integer; DeleteLine: Boolean;
var Action: TSynReplaceAction);
procedure PageControlChange(Sender: TObject);
procedure SearchForEditChange(Sender: TObject);
procedure SearchCloseActionExecute(Sender: TObject);
procedure SearchFindNextActionExecute(Sender: TObject);
procedure SearchFindPreviousActionExecute(Sender: TObject);
procedure OutputDblClickActionExecute(Sender: TObject);
procedure OraScriptError(Sender: TObject; E: Exception; SQL: string; var Action: TErrorAction);
procedure OraSQLAfterExecuteEvent(Sender: TObject; Result: Boolean);
//procedure OraScriptAfterExecuteEvent(Sender: TObject; SQL: string);
procedure OraScriptQueryAfterExecuteEvent(Sender: TObject; Result: Boolean);
procedure ObjectFieldCompletionProposalExecute(Kind: SynCompletionType; Sender: TObject;
var CurrentInput: UnicodeString; var x, y: Integer; var CanExecute: Boolean);
procedure DBMSOutputTimer(Sender: TObject);
procedure OraSessionError(Sender: TObject; E: EDAError; var Fail: Boolean);
procedure SynEditPaintTransient(Sender: TObject; Canvas: TCanvas; TransientType: TTransientType);
procedure GotoLineActionExecute(Sender: TObject);
procedure GotoLineCloseActionExecute(Sender: TObject);
procedure GotoLineNumberEditKeyPress(Sender: TObject; var Key: Char);
procedure PageControlCloseButtonClick(Sender: TObject);
procedure PageControlDblClick(Sender: TObject);
procedure PageControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure SearchClearActionExecute(Sender: TObject);
procedure GotoLineClearActionExecute(Sender: TObject);
procedure GotoLineNumberEditChange(Sender: TObject);
procedure BoxDownActionExecute(Sender: TObject);
procedure BoxLeftActionExecute(Sender: TObject);
procedure BoxRightActionExecute(Sender: TObject);
procedure BoxUpActionExecute(Sender: TObject);
private
{ Private declarations }
FCaseCycle: Byte;
FSelectedText: UnicodeString;
FNumberOfNewDocument: Integer;
FOutputFrame: TOutputFrame;
FSession: TOraSession;
FObjectNames: TStrings;
FSchemaParam: string;
FDBMSTimer: TTimer;
FCompareImageIndex, FNewImageIndex: Integer;
FImages: TImageList;
FProcessing: Boolean;
FModifiedDocuments: Boolean;
FFoundSearchItems: TObjectList;
function CreateNewTabSheet(FileName: string = ''): TBCOraSynEdit;
function GetActiveTabSheetCaption: string;
function GetActiveDocumentName: string;
function GetActiveDocumentFound: Boolean;
function GetSynEdit(TabSheet: TTabSheet): TBCOraSynEdit;
function GetSQLEditorTabSheetFrame(TabSheet: TTabSheet): TSQLEditorTabSheetFrame;
function Save(TabSheet: TTabSheet; ShowDialog: Boolean = False): string; overload;
procedure InitializeSynEditPrint;
function GetOpenTabSheets: Boolean;
function GetSelectionFound: Boolean;
function GetOpenTabSheetCount: Integer;
function GetCanUndo: Boolean;
function GetCanRedo: Boolean;
function CanFindNextPrevious: Boolean;
function SearchOptions(IncludeBackwards: Boolean): TSynSearchOptions;
function FindOpenFile(FileName: string): TBCOraSynEdit;
procedure SetBookmarks(SynEdit: TBCOraSynEdit; Bookmarks: TStrings);
procedure DoSearch(SearchOnly: Boolean = False);
procedure DoSearch2;
procedure FreePage(TabSheet: TTabSheet);
procedure AddToReopenFiles(FileName: string);
procedure SetHighlighterTableNames(Value: TStrings);
procedure ExecuteStatement(SynEdit: TBCOraSynEdit; SQL: string = ''); overload;
procedure ExecuteNoRowsStatement(SynEdit: TBCOraSynEdit);
procedure SetSession(Value: TOraSession);
procedure EnableDBMSOutput;
procedure GetDBMSOutput;
procedure WriteHistory(OraSession: TOraSession; SQL: WideString);
function GetDataQueryOpened: Boolean;
function CreateSession(OraSession: TOraSession): TOraSession;
procedure CheckModifiedDocuments;
procedure GetUserErrors;
function RemoveComments(s: WideString): WideString; //SynEdit: TBCOraSynEdit): WideString;
function RemoveParenthesisFromBegin(Text: WideString): WideString;
function GetOutputGridHasFocus: Boolean;
function GetActivePageCaption: string;
procedure GetText(Sender: TField; var Text: String; DisplayText: Boolean);
procedure SetClobAndTimestampFields(OraQuery: TOraQuery);
function GetActiveDocumentModified: Boolean;
procedure SetActivePageCaptionModified;
function GetCompareFrame(TabSheet: TTabSheet): TCompareFrame;
function GetModifiedDocuments(CheckActive: Boolean = True): Boolean;
function GetInTransAction: Boolean;
function GetMinimapChecked: Boolean;
procedure SetSearchMapVisible(Value: Boolean);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure New;
procedure Open(FileName: string = ''; Bookmarks: TStrings = nil;
Ln: Integer = 0; Ch: Integer = 0);
procedure Close(IncludeCancel: Boolean = True);
function CloseAll(CloseDocuments: Boolean = True; IncludeCancel: Boolean = True): Integer;
procedure CloseAllOtherPages;
procedure Save; overload;
function SaveAs: string;
procedure SaveAll;
procedure Undo;
procedure Redo;
procedure Cut;
procedure CopyToClipboard;
procedure Paste;
procedure Print;
procedure PrintPreview;
procedure Search;
procedure FindNext;
procedure FindPrevious;
procedure Replace;
procedure NextPage;
procedure PreviousPage;
procedure CheckFileDateTimes;
procedure Refresh(Page: Integer);
function WordWrap: Boolean;
function ToggleWordWrap: Boolean;
function ToggleLineNumbers: Boolean;
function LineNumbers: Boolean;
function ToggleSpecialChars: Boolean;
function SpecialChars: Boolean;
function ToggleSelectionMode: Boolean;
function SelectionMode: Boolean;
procedure CompareFiles(FileName: string = ''; AFileDragDrop: Boolean = False);
procedure SelectForCompare;
function GetActiveSynEdit: TBCOraSynEdit;
function GetCaretInfo: string;
function GetModifiedInfo: string;
function GetActiveBookmarkList: TSynEditMarkList;
procedure AssignOptions;
procedure CreateActionToolBar(CreateToolBar: Boolean = False);
property ActiveTabSheetCaption: string read GetActiveTabSheetCaption;
property ActiveDocumentName: string read GetActiveDocumentName;
property ActiveDocumentFound: Boolean read GetActiveDocumentFound;
property ActiveDocumentModified: Boolean read GetActiveDocumentModified;
property OpenTabSheets: Boolean read GetOpenTabSheets;
property SelectionFound: Boolean read GetSelectionFound;
property CanUndo: Boolean read GetCanUndo;
property CanRedo: Boolean read GetCanRedo;
property HighlighterTableNames: TStrings write SetHighlighterTableNames;
property OutputFrame: TOutputFrame read FOutputFrame write FOutputFrame;
property Session: TOraSession read FSession write SetSession;
property ObjectNames: TStrings write FObjectNames;
property SchemaParam: string read FSchemaParam write FSchemaParam;
property DataQueryOpened: Boolean read GetDataQueryOpened;
property OutputGridHasFocus: Boolean read GetOutputGridHasFocus;
property InTransaction: Boolean read GetInTransaction;
property OpenTabSheetCount: Integer read GetOpenTabSheetCount;
property Processing: Boolean read FProcessing;
property ModifiedDocuments: Boolean Read FModifiedDocuments write FModifiedDocuments;
property MinimapChecked: Boolean read GetMinimapChecked;
procedure ExecuteStatement(Current: Boolean = False); overload;
procedure ExecuteCurrentStatement;
procedure ExecuteScript(Current: Boolean = False);
procedure ShowObjects;
procedure ExplainPlan;
procedure DecreaseIndent;
procedure IncreaseIndent;
procedure ToggleCase;
procedure SortAsc;
procedure SortDesc;
procedure ToggleMiniMap;
procedure ClearBookmarks;
procedure InsertLine;
procedure DeleteWord;
procedure DeleteLine;
procedure DeleteEOL;
procedure UpdateMarginsAndControls;
procedure UpdateMarginAndColors(SQLEditorTabSheetFrame: TSQLEditorTabSheetFrame);
procedure RepaintToolButtons;
function IsCompareFilesActivePage: Boolean;
procedure GotoBookmarks(ItemIndex: Integer);
procedure ToggleBookmarks(ItemIndex: Integer);
procedure GotoLine;
end;
implementation
{$R *.dfm}
uses
SynEditKeyCmds, BCForms.PrintPreview, BCDialogs.Replace, BCDialogs.ConfirmReplace, Lib, BCCommon.StyleUtils, SynUnicode,
BCCommon.OptionsContainer, System.Math, BCCommon.FileUtils, BCCommon.Messages, BCCommon.Images,
Types, Parameters, BCSQL.Tokenizer, SQLProgress, QueryProgress, Main, BigIni, BCCommon.Lib, BCCommon.StringUtils,
AnsiStrings, ShellAPI, WideStrings, Vcl.GraphUtil, BCCommon.Dialogs, BCCommon.LanguageStrings, SynEditPrintTypes,
SynEditSearchHighlighter;
const
DEFAULT_FILENAME = 'Sql';
{ TSQLEditorFrame }
function TSQLEditorFrame.GetDataQueryOpened: Boolean;
begin
Result := GetActiveSynEdit.QueryOpened and Assigned(FOutputFrame) and (FOutputFrame.PageControl.PageCount > 0) and (FOutputFrame.PageControl.ActivePage.ImageIndex = IMAGE_INDEX_GRID);
end;
function TSQLEditorFrame.GetSQLEditorTabSheetFrame(TabSheet: TTabSheet): TSQLEditorTabSheetFrame;
begin
Result := nil;
if Assigned(TabSheet) then
if TabSheet.ComponentCount <> 0 then
if TabSheet.Components[0] is TSQLEditorTabSheetFrame then
Result := TSQLEditorTabSheetFrame(TabSheet.Components[0]);
end;
function TSQLEditorFrame.GetOutputGridHasFocus: Boolean;
var
Grid: TBCDBGrid;
begin
Result := False;
if Assigned(FOutputFrame) then
begin
Grid := FOutputFrame.GetActiveGrid;
Result := Assigned(Grid) and Grid.Focused;
end;
end;
procedure TSQLEditorFrame.SetSession(Value: TOraSession);
begin
FSession := Value;
ColumnsQuery.Session := Value;
ErrorsQuery.Session := Value;
end;
constructor TSQLEditorFrame.Create(AOwner: TComponent);
var
SysImageList: THandle;
Icon: TIcon;
begin
inherited Create(AOwner);
FNumberOfNewDocument := 0;
FCaseCycle := 0;
FSelectedText := '';
FProcessing := False;
FModifiedDocuments := False;
FOutputFrame := TOutputFrame.Create(OutputPanel);
FOutputFrame.Parent := OutputPanel;
FOutputFrame.OnTabsheetDblClick := OutputDblClickActionExecute;
FOutputFrame.OnOpenAll := OutputOpenAllEvent;
FFoundSearchItems := TObjectList.Create;
{ IDE can lose these, if the main form is not open }
EditorPopupActionBar.Images := ImagesDataModule.ImageList;
CutMenuItem.Action := MainForm.EditCutAction;
CopyMenuItem.Action := MainForm.EditCopyAction;
PasteMenuItem.Action := MainForm.EditPasteAction;
SelectAllMenuItem.Action := MainForm.EditSelectAllAction;
UndoMenuItem.Action := MainForm.EditUndoAction;
RedoMenuItem.Action := MainForm.EditRedoAction;
IncreaseIndentMenuItem.Action := MainForm.EditIncreaseIndentAction;
DecreaseIndentMenuItem.Action := MainForm.EditDecreaseIndentAction;
SortAscendingMenuItem.Action := MainForm.EditSortAscAction;
SortDescendingMenuItem.Action := MainForm.EditSortDescAction;
ToggleCaseMenuItem.Action := MainForm.EditToggleCaseAction;
InsertObjectMenuItem.Action := MainForm.InsertObjectAction;
FormatSQLMenuItem.Action := MainForm.FormatSQLAction;
ToggleBookmarkMenuItem.Action := MainForm.SearchToggleBookmarkAction;
ToggleBookmarksMenuItem.Action := MainForm.SearchToggleBookmarksAction;
ToggleBookmark1MenuItem.Action := MainForm.ToggleBookmarks1Action;
ToggleBookmark2MenuItem.Action := MainForm.ToggleBookmarks2Action;
ToggleBookmark3MenuItem.Action := MainForm.ToggleBookmarks3Action;
ToggleBookmark4MenuItem.Action := MainForm.ToggleBookmarks4Action;
ToggleBookmark5MenuItem.Action := MainForm.ToggleBookmarks5Action;
ToggleBookmark6MenuItem.Action := MainForm.ToggleBookmarks6Action;
ToggleBookmark7MenuItem.Action := MainForm.ToggleBookmarks7Action;
ToggleBookmark8MenuItem.Action := MainForm.ToggleBookmarks8Action;
ToggleBookmark9MenuItem.Action := MainForm.ToggleBookmarks9Action;
GotoBookmarksMenuItem.Action := MainForm.SearchGotoBookmarksAction;
ClearBookmarksMenuItem.Action := MainForm.SearchClearBookmarksAction;
GotoBookmark1MenuItem.Action := MainForm.GotoBookmarks1Action;
GotoBookmark2MenuItem.Action := MainForm.GotoBookmarks2Action;
GotoBookmark3MenuItem.Action := MainForm.GotoBookmarks3Action;
GotoBookmark4MenuItem.Action := MainForm.GotoBookmarks4Action;
GotoBookmark5MenuItem.Action := MainForm.GotoBookmarks5Action;
GotoBookmark6MenuItem.Action := MainForm.GotoBookmarks6Action;
GotoBookmark7MenuItem.Action := MainForm.GotoBookmarks7Action;
GotoBookmark8MenuItem.Action := MainForm.GotoBookmarks8Action;
GotoBookmark9MenuItem.Action := MainForm.GotoBookmarks9Action;
FImages := TImageList.Create(Self);
SysImageList := GetSysImageList;
if SysImageList <> 0 then
begin
FImages.Handle := SysImageList;
FImages.BkColor := ClNone;
FImages.ShareImages := True;
end;
PageControl.Images := FImages;
{ compare and new image index }
Icon := TIcon.Create;
try
{ Windows font size causing a problem: Icon size will be smaller than PageControl.Images size }
case PageControl.Images.Height of
16:
begin
{ smaller }
ImageList16.GetIcon(0, Icon);
FCompareImageIndex := PageControl.Images.AddIcon(Icon);
ImageList16.GetIcon(1, Icon);
FNewImageIndex := PageControl.Images.AddIcon(Icon);
end;
20:
begin
{ medium }
ImageList20.GetIcon(0, Icon);
FCompareImageIndex := PageControl.Images.AddIcon(Icon);
ImageList20.GetIcon(1, Icon);
FNewImageIndex := PageControl.Images.AddIcon(Icon);
end;
24:
begin
{ larger }
ImageList24.GetIcon(0, Icon);
FCompareImageIndex := PageControl.Images.AddIcon(Icon);
ImageList24.GetIcon(1, Icon);
FNewImageIndex := PageControl.Images.AddIcon(Icon);
end;
end;
finally
Icon.Free;
end;
CreateActionToolBar(True);
end;
procedure TSQLEditorFrame.FreePage(TabSheet: TTabSheet);
var
SQLEditorTabSheetFrame: TSQLEditorTabSheetFrame;
SynEdit: TBCOraSynEdit;
begin
SQLEditorTabSheetFrame := GetSQLEditorTabSheetFrame(TabSheet);
if Assigned(SQLEditorTabSheetFrame) then
begin
SynEdit := SQLEditorTabSheetFrame.OraSynEdit;
if Assigned(SynEdit) then
begin
if Assigned(SynEdit.OraQuery) then
SynEdit.OraQuery.Free;
if Assigned(SynEdit.PlanQuery) then
SynEdit.PlanQuery.Free;
if Assigned(SynEdit.ObjectCompletionProposal) then
SynEdit.ObjectCompletionProposal.Free;
if Assigned(SynEdit.ObjectFieldCompletionProposal) then
SynEdit.ObjectFieldCompletionProposal.Free;
end;
SQLEditorTabSheetFrame.Free;
TabSheet.Free;
end;
end;
destructor TSQLEditorFrame.Destroy;
begin
FFoundSearchItems.Free;
if Assigned(FObjectNames) then
FObjectNames.Free;
PageControl.Images.Free;
inherited Destroy;
end;
function TSQLEditorFrame.CreateNewTabSheet(FileName: string = ''): TBCOraSynEdit;
var
TabSheet: TTabSheet;
SQLEditorTabSheetFrame: TSQLEditorTabSheetFrame;
begin
{ create a TabSheet }
TabSheet := TTabSheet.Create(PageControl);
TabSheet.PageControl := PageControl;
if FileName <> '' then
TabSheet.ImageIndex := GetIconIndex(FileName)
else
TabSheet.ImageIndex := FNewImageIndex;
PageControl.ActivePage := TabSheet;
SetSearchMapVisible(SearchPanel.Visible);
if SearchPanel.Visible then
if OptionsContainer.DocumentSpecificSearch then
SearchForEdit.Text := '';
{ set the Caption property }
if FileName = '' then
PageControl.ActivePageCaption := DEFAULT_FILENAME + IntToStr(FNumberOfNewDocument)
else
PageControl.ActivePageCaption := ExtractFileName(FileName);
{ create a SynEdit }
SQLEditorTabSheetFrame := TSQLEditorTabSheetFrame.Create(TabSheet);
with SQLEditorTabSheetFrame do
begin
OraSynEdit.Visible := False;
Parent := TabSheet;
with OraSynEdit do
begin
DocumentName := FileName;
FileDateTime := GetFileDateTime(FileName);
OnChange := SynEditOnChange;
OnReplaceText := SynEditorReplaceText;
SearchEngine := SynEditSearch;
Highlighter := SynSQLSyn;
PopupMenu := EditorPopupActionBar;
OnPaintTransient := SynEditPaintTransient;
BookMarkOptions.BookmarkImages := BookmarkImagesList;
end;
{ Search highlighter plugin }
THighlightSearchPlugin.Create(OraSynEdit, FFoundSearchItems);
OptionsContainer.AssignTo(OraSynEdit);
UpdateMarginAndColors(SQLEditorTabSheetFrame);
OraSynEdit.ObjectCompletionProposal := TSynCompletionProposal.Create(nil);
with OraSynEdit.ObjectCompletionProposal do
begin
Editor := OraSynEdit;
ShortCut := TextToShortCut('Ctrl+O');
Options := Options + [scoUseInsertList, scoCompleteWithTab, scoCompleteWithEnter, scoLimitToMatchedText];
InsertList.Assign(SynSQLSyn.TableNames);
ItemList.Assign(FObjectNames);
end;
OraSynEdit.ObjectFieldCompletionProposal := TSynCompletionProposal.Create(nil);
with OraSynEdit.ObjectFieldCompletionProposal do
begin
Editor := OraSynEdit;
ShortCut := TextToShortCut('');
Options := Options + [scoUseInsertList, scoUseBuiltInTimer, scoCompleteWithTab, scoCompleteWithEnter, scoLimitToMatchedText];
TimerInterval := 500;
TriggerChars := '.';
OnExecute := ObjectFieldCompletionProposalExecute
end;
if Filename <> '' then
OraSynEdit.Lines.LoadFromFile(FileName);
Application.ProcessMessages;
OraSynEdit.Visible := True;
if Visible and OraSynEdit.CanFocus then
OraSynEdit.SetFocus;
Result := OraSynEdit;
end;
end;
procedure TSQLEditorFrame.UpdateMarginsAndControls;
var
i, Right: Integer;
SQLEditorTabSheetFrame: TSQLEditorTabSheetFrame;
CompareFrame: TCompareFrame;
begin
PageControl.DoubleBuffered := OptionsContainer.EditorDoubleBuffered;
PageControl.MultiLine := OptionsContainer.EditorMultiLine;
PageControl.ShowCloseButton := OptionsContainer.EditorShowCloseButton;
PageControl.RightClickSelect := OptionsContainer.EditorRightClickSelect;
if OptionsContainer.EditorShowImage then
PageControl.Images := FImages
else
PageControl.Images := nil;
FOutputFrame.UpdateControls;
Application.ProcessMessages;
Right := GetRightPadding;
for i := 0 to PageControl.PageCount - 1 do
begin
SQLEditorTabSheetFrame := GetSQLEditorTabSheetFrame(PageControl.Pages[i]);
if Assigned(SQLEditorTabSheetFrame) then
begin
UpdateMarginAndColors(SQLEditorTabSheetFrame);
SQLEditorTabSheetFrame.UpdateOptionsAndStyles(Right);
end;
CompareFrame := GetCompareFrame(PageControl.Pages[i]);
if Assigned(CompareFrame) then
CompareFrame.Panel.Padding.Right := Right
end;
UpdateSQLSynColors(SynSQLSyn);
end;
procedure TSQLEditorFrame.UpdateMarginAndColors(SQLEditorTabSheetFrame: TSQLEditorTabSheetFrame);
begin
BCCommon.StyleUtils.UpdateMargin(SQLEditorTabSheetFrame.OraSynEdit);
SQLEditorTabSheetFrame.OraSynEdit.ActiveLineColor := LightenColor(SQLEditorTabSheetFrame.OraSynEdit.Color, 1 - (10 - OptionsContainer.ColorBrightness)/10);
end;
procedure TSQLEditorFrame.SynEditPaintTransient(Sender: TObject; Canvas: TCanvas; TransientType: TTransientType);
var
Editor : TSynEdit;
OpenChars: array [0..0] of WideChar;
CloseChars: array [0..0] of WideChar;
function IsCharBracket(AChar: WideChar): Boolean;
begin
case AChar of
'(', ')':
Result := True;
else
Result := False;
end;
end;
function CharToPixels(P: TBufferCoord): TPoint;
begin
Result := Editor.RowColumnToPixels(Editor.BufferToDisplayPos(P));
end;
var
P, PM: TBufferCoord;
Pix: TPoint;
D : TDisplayCoord;
S: UnicodeString;
I: Integer;
Attri: TSynHighlighterAttributes;
ArrayLength: Integer;
start: Integer;
TmpCharA, TmpCharB: WideChar;
begin
Editor := TSynEdit(Sender);
if Editor.SelAvail then
Exit;
if Length(Editor.Text) = 0 then
Exit;
ArrayLength:= 1;
for i := 0 to ArrayLength - 1 do
Case i of
0: begin OpenChars[i] := '('; CloseChars[i] := ')'; end;
end;
P := Editor.CaretXY;
D := Editor.DisplayXY;
Start := Editor.SelStart;
if (Start > 0) and (Start <= length(Editor.Text)) then
TmpCharA := Editor.Text[Start]
else
TmpCharA := #0;
if Start < Length(Editor.Text) then
TmpCharB := Editor.Text[Start + 1]
else
TmpCharB := #0;
if not IsCharBracket(TmpCharA) and not IsCharBracket(TmpCharB) then
Exit;
S := TmpCharB;
if not IsCharBracket(TmpCharB) then
begin
P.Char := P.Char - 1;
S := TmpCharA;
end;
Editor.GetHighlighterAttriAtRowCol(P, S, Attri);
PM := Editor.GetMatchingBracketEx(P);
if TransientType = SynEdit.ttBefore then
begin
Editor.InvalidateLines(P.Line, PM.Line);
Exit;
end;
if (Editor.Highlighter.SymbolAttribute = Attri) then
begin
for i := low(OpenChars) to High(OpenChars) do
begin
if (S = OpenChars[i]) or (S = CloseChars[i]) then
begin
Pix := CharToPixels(P);
Canvas.Font.Assign(Editor.Font);
Canvas.Font.Style := Attri.Style;
if (TransientType = SynEdit.ttAfter) then
begin
Canvas.Font.Color := clNone;
Canvas.Brush.Color := clAqua;
end;
Canvas.TextOut(Pix.X, Pix.Y, S);
if (PM.Char > 0) and (PM.Line > 0) then
begin
Pix := CharToPixels(PM);
if Pix.X > Editor.Gutter.Width then
begin
if S = OpenChars[i] then
Canvas.TextOut(Pix.X, Pix.Y, CloseChars[i])
else
Canvas.TextOut(Pix.X, Pix.Y, OpenChars[i]);
end;
end;
end; //if
end;//for i :=
end;
end;
procedure TSQLEditorFrame.ObjectFieldCompletionProposalExecute(Kind: SynCompletionType; Sender: TObject;
var CurrentInput: UnicodeString; var x, y: Integer; var CanExecute: Boolean);
var
// Line: Integer;
Proposal: TSynCompletionProposal;
Tablename: string;
Input: string;
SQLTokenizer: TSQLTokenizer;
begin
CanExecute := False;
Proposal := Sender as TSynCompletionProposal;
SQLTokenizer := TSQLTokenizer.Create;
try
Input := System.Copy(Proposal.Editor.LineText, 0, Proposal.Editor.CaretX - 2);
while Pos(' ', Input) <> 0 do
Input := System.Copy(Input, Pos(' ', Input) + 1, Length(Input));
while Pos('(', Input) <> 0 do // example function(alias.
Input := System.Copy(Input, Pos('(', Input) + 1, Length(Input));
SQLTokenizer.SetText(Proposal.Editor.Text);
while (not SQLTokenizer.Eof) and not SQLTokenizer.TokenStrIs('FROM') do
SQLTokenizer.Next;
SQLTokenizer.Next; // FROM
while not SQLTokenizer.Eof do
begin
if (Trim(SQLTokenizer.TokenStr) = '') or SQLTokenizer.TokenStrIs('AS') then
SQLTokenizer.Next
else
begin
Tablename := String(SQLTokenizer.TokenStr);
SQLTokenizer.Next;
while (not SQLTokenizer.Eof) and ((Trim(SQLTokenizer.TokenStr) = '') or SQLTokenizer.TokenStrIs('AS')) do
SQLTokenizer.Next;
if Input = String(SQLTokenizer.TokenStr) then
begin
with ColumnsQuery do
begin
if not Session.Connected then
begin
Session.ConnectPrompt := False;
Session.Connect;
Session.ConnectPrompt := True;
end;
ParamByName('P_OBJECT_NAME').AsString := UpperCase(Tablename);
ParamByName('P_OWNER').AsWideString := FSchemaParam;
Prepare;
Open;
Proposal.InsertList.Clear;
Proposal.ItemList.Clear;
while not Eof do
begin
Proposal.InsertList.Add(FieldByName('COLUMN_NAME').AsWideString);
Proposal.ItemList.Add(FieldByName('ITEM').AsWideString);
Next;
end;
Close;
UnPrepare;
end;
CanExecute := True;
Break;
end;
end;
end;
finally
SQLTokenizer.Free;
end;
end;
function TSQLEditorFrame.GetCompareFrame(TabSheet: TTabSheet): TCompareFrame;
begin
Result := nil;
if Assigned(TabSheet) then
if TabSheet.ComponentCount <> 0 then
if TabSheet.Components[0] is TCompareFrame then
Result := TCompareFrame(TabSheet.Components[0]);
end;
procedure TSQLEditorFrame.CompareFiles(FileName: string; AFileDragDrop: Boolean);
var
i: Integer;
TabSheet: TTabSheet;
Frame: TCompareFrame;
TempList: TStringList;
SynEdit: TBCOraSynEdit;
begin
SearchPanel.Visible := False;
GotoLinePanel.Visible := False;
{ create list of open documents }
TempList := TStringList.Create;
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) then
TempList.Add(SynEdit.DocumentName);
end;
if Filename <> '' then
begin
{ find compare tab }
for i := 0 to PageControl.PageCount - 1 do
if PageControl.Pages[i].ImageIndex = FCompareImageIndex then
begin
Frame := GetCompareFrame(PageControl.Pages[i]);
{ if there already are two files to compare then continue }
if Frame.ComparedFilesSet then
Continue
else
begin
{ else set file and exit}
PageControl.ActivePageIndex := i;
Frame.SetCompareFile(Filename, AFileDragDrop);
Exit;
end;
end;
end;
{ create a TabSheet }
TabSheet := TTabSheet.Create(PageControl);
TabSheet.PageControl := PageControl;
TabSheet.ImageIndex := FCompareImageIndex;
TabSheet.Caption := LanguageDataModule.GetConstant('CompareFiles');
PageControl.UpdatePageCaption(TabSheet);
PageControl.ActivePage := TabSheet;
{ create a compare frame }
Frame := TCompareFrame.Create(TabSheet);
with Frame do
begin
Parent := TabSheet;
Align := alClient;
OpenDocumentsList := TempList;
SetCompareFile(Filename);
SpecialChars := OptionsContainer.EnableSpecialChars;
LineNumbers := OptionsContainer.EnableLineNumbers;
end;
end;
procedure TSQLEditorFrame.SelectForCompare;
begin
CompareFiles(GetActiveSynEdit.DocumentName);
end;
function TSQLEditorFrame.FindOpenFile(FileName: string): TBCOraSynEdit;
var
i: Integer;
SynEdit: TBCOraSynEdit;
begin
Result := nil;
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) then
if CompareText(UpperCase(SynEdit.DocumentName), UpperCase(FileName))
= 0 then
begin
PageControl.ActivePage := PageControl.Pages[i];
Result := SynEdit;
Break;
end;
end;
end;
procedure TSQLEditorFrame.New;
begin
Inc(FNumberOfNewDocument);
CreateNewTabSheet;
end;
procedure TSQLEditorFrame.SetBookmarks(SynEdit: TBCOraSynEdit; Bookmarks: TStrings);
var
i: Integer;
Temp: string;
BookmarkNumber, Ln, Ch: Integer;
begin
if Assigned(Bookmarks) then
begin
for i := 0 to Bookmarks.Count - 1 do
begin
Temp := Bookmarks.Strings[i];
if Pos(SynEdit.DocumentName, Temp) <> 0 then
begin
Temp := System.Copy(Temp, Pos('=', Temp) + 1, Length(Temp));
BookmarkNumber := StrToInt(System.Copy(Temp, 1, Pos(';', Temp) - 1));
Temp := System.Copy(Temp, Pos(';', Temp) + 1, Length(Temp));
Ln := StrToInt(System.Copy(Temp, 1, Pos(';', Temp) - 1));
Temp := System.Copy(Temp, Pos(';', Temp) + 1, Length(Temp));
Ch := StrToInt(Temp);
SynEdit.SetBookMark(BookmarkNumber, Ch, Ln);
end;
end;
end;
end;
procedure TSQLEditorFrame.AddToReopenFiles(FileName: string);
var
i: Integer;
Files: TStrings;
begin
Files := TStringList.Create;
{ Read section }
with TBigIniFile.Create(GetINIFilename) do
try
ReadSectionValues('FileReopenFiles', Files);
finally
Free;
end;
{ Insert filename }
for i := 0 to Files.Count - 1 do
Files[i] := System.Copy(Files[i], Pos('=', Files[i]) + 1, Length(Files[i]));
for i := Files.Count - 1 downto 0 do
if Files[i] = FileName then
Files.Delete(i);
Files.Insert(0, FileName);
while Files.Count > 10 do
Files.Delete(Files.Count - 1);
{ write section }
with TBigIniFile.Create(GetINIFilename) do
try
EraseSection('FileReopenFiles');
for i := 0 to Files.Count - 1 do
WriteString('FileReopenFiles', IntToStr(i), Files.Strings[i]);
finally
Free;
end;
end;
procedure TSQLEditorFrame.Open(FileName: string = ''; Bookmarks: TStrings = nil;
Ln: Integer = 0; Ch: Integer = 0);
var
i: Integer;
SynEdit: TBCOraSynEdit;
begin
FProcessing := True;
try
if FileName = '' then
begin
if BCCommon.Dialogs.OpenFiles(Handle, '',
Format('%s'#0'*.*'#0, [LanguageDataModule.GetConstant('AllFiles')]) + 'SQL files (*.sql)'#0'*.sql'#0#0, LanguageDataModule.GetConstant('Open')) then
begin
Application.ProcessMessages; { style fix }
for i := 0 to BCCommon.Dialogs.Files.Count - 1 do
Open(BCCommon.Dialogs.Files[i])
end;
end
else
begin
if FileExists(FileName) then
begin
SynEdit := FindOpenFile(FileName);
if not Assigned(SynEdit) then
SynEdit := CreateNewTabSheet(FileName);
DoSearch2;
SynEdit.CaretXY := BufferCoord(Ch, Ln);
SynEdit.GotoLineAndCenter(Ln);
SetBookmarks(SynEdit, Bookmarks);
if SynEdit.CanFocus then
SynEdit.SetFocus;
AddToReopenFiles(FileName);
MainForm.CreateFileReopenList;
end
else
if ExtractFileName(FileName) <> '' then
ShowErrorMessage(Format(LanguageDataModule.GetErrorMessage('FileNotFound'), [Filename]))
end;
finally
FProcessing := False;
end;
end;
function TSQLEditorFrame.GetActivePageCaption: string;
begin
Result := PageControl.ActivePageCaption;
if Pos('~', Result) = Length(Result) then
Result := System.Copy(Result, 0, Length(Result) - 1);
end;
procedure TSQLEditorFrame.OraScriptError(Sender: TObject; E: Exception; SQL: string;
var Action: TErrorAction);
begin
FOutputFrame.AddErrors('Errors: ' + GetActivePageCaption, E.Message);
Action := eaFail;
end;
procedure TSQLEditorFrame.Close(IncludeCancel: Boolean);
var
ActivePageIndex: Integer;
Rslt: Integer;
SynEdit: TBCOraSynEdit;
begin
Rslt := mrNone;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) and SynEdit.Modified then
begin
Rslt := SaveChanges(IncludeCancel);
if Rslt = mrYes then
Save;
end;
if Rslt <> mrCancel then
begin
PageControl.TabClosed := True;
ActivePageIndex := PageControl.ActivePageIndex;
{ Fixed Delphi Bug: http://qc.embarcadero.com/wc/qcmain.aspx?d=5473 }
if (ActivePageIndex = PageControl.PageCount - 1) and (PageControl.PageCount > 1) then
begin
Dec(ActivePageIndex);
PageControl.ActivePage.PageIndex := ActivePageIndex;
end;
if PageControl.PageCount > 0 then
FreePage(PageControl.Pages[ActivePageIndex]);
if PageControl.PageCount = 0 then
FNumberOfNewDocument := 0;
end;
DoSearch2;
CheckModifiedDocuments;
end;
function TSQLEditorFrame.CloseAll(CloseDocuments: Boolean; IncludeCancel: Boolean): Integer;
var
i, j: Integer;
begin
Result := mrNone;
if FModifiedDocuments then
begin
Result := SaveChanges(IncludeCancel);
if Result = mrYes then
SaveAll;
end;
if CloseDocuments and (Result <> mrCancel) then
begin
j := PageControl.PageCount - 1;
for i := j downto 0 do
FreePage(PageControl.Pages[i]);
FNumberOfNewDocument := 0;
Result := mrYes;
end;
CheckModifiedDocuments;
end;
procedure TSQLEditorFrame.CloseAllOtherPages;
var
i, j: Integer;
Rslt: Integer;
ActiveSynEdit, SynEdit: TBCOraSynEdit;
begin
FProcessing := True;
Application.ProcessMessages;
Rslt := mrNone;
ActiveSynEdit := GetActiveSynEdit;
if GetModifiedDocuments(False) then
begin
Rslt := SaveChanges(True);
if Rslt = mrYes then
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) and SynEdit.Modified and (Synedit <> ActiveSynEdit) then
Save(PageControl.Pages[i]);
end;
end;
if Rslt <> mrCancel then
begin
PageControl.ActivePage.PageIndex := 0; { move the page first }
j := PageControl.PageCount - 1;
for i := j downto 1 do
FreePage(PageControl.Pages[i]);
if GetActiveSynEdit.DocumentName = '' then
FNumberOfNewDocument := 1
else
FNumberOfNewDocument := 0
end;
DoSearch2;
CheckModifiedDocuments;
FProcessing := False;
end;
procedure TSQLEditorFrame.CheckModifiedDocuments;
begin
FModifiedDocuments := GetModifiedDocuments;
end;
function TSQLEditorFrame.Save(TabSheet: TTabSheet; ShowDialog: Boolean): string;
var
OraSynEdit: TBCOraSynEdit;
AFileName: string;
FilterIndex: Cardinal;
begin
Result := '';
OraSynEdit := GetSynEdit(TabSheet);
Screen.Cursor := crHourGlass;
try
if Assigned(OraSynEdit) then
begin
if (OraSynEdit.DocumentName = '') or ShowDialog then
begin
AFileName := Trim(TabSheet.Caption);
if Pos('~', AFileName) = Length(AFileName) then
AFileName := System.Copy(AFileName, 0, Length(AFileName) - 1);
if BCCommon.Dialogs.SaveFile(Handle, '',
Format('%s'#0'*.*'#0, [LanguageDataModule.GetConstant('AllFiles')]) + 'SQL files (*.sql)'#0'*.sql'#0#0, LanguageDataModule.GetConstant('SaveAs'), FilterIndex, AFileName, 'sql') then
begin
Application.ProcessMessages; { style fix }
Result := BCCommon.Dialogs.Files[0];
PageControl.ActivePageCaption := ExtractFileName(Result);
OraSynEdit.DocumentName := Result;
end
else
begin
if OraSynEdit.CanFocus then
OraSynEdit.SetFocus;
Exit;
end;
end;
with OraSynEdit do
begin
Lines.SaveToFile(DocumentName);
if not OptionsContainer.UndoAfterSave then
UndoList.Clear;
FileDateTime := GetFileDateTime(DocumentName);
TabSheet.ImageIndex := GetIconIndex(DocumentName);
Modified := False;
AFileName := Trim(TabSheet.Caption);
if Pos('~', AFileName) = Length(AFileName) then
TabSheet.Caption := System.Copy(AFileName, 0, Length(AFileName) - 1);
PageControl.UpdatePageCaption(TabSheet);
end;
CheckModifiedDocuments;
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TSQLEditorFrame.Save;
begin
Save(PageControl.ActivePage);
end;
function TSQLEditorFrame.SaveAs: string;
begin
Result := Save(PageControl.ActivePage, True);
end;
procedure TSQLEditorFrame.SaveAll;
var
i: Integer;
SynEdit: TBCOraSynEdit;
begin
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) and SynEdit.Modified then
Save(PageControl.Pages[i]);
end;
end;
procedure TSQLEditorFrame.Undo;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
SynEdit.Undo;
if SynEdit.UndoList.ItemCount = 0 then
PageControl.ActivePageCaption := GetActivePageCaption;
CheckModifiedDocuments;
end;
procedure TSQLEditorFrame.Redo;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
SynEdit.Redo;
CheckModifiedDocuments;
end;
procedure TSQLEditorFrame.Cut;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
SynEdit.CutToClipboard;
end;
procedure TSQLEditorFrame.CopyToClipboard;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if SynEdit.Focused then
SynEdit.CopyToClipboard
else
FOutputFrame.CopyToClipboard;
end;
procedure TSQLEditorFrame.PageControlChange(Sender: TObject);
var
BufferCoord: TBufferCoord;
SynEdit: TBCOraSynEdit;
procedure PositionAndSearch;
begin
SynEdit.RightEdge.Position := OptionsContainer.MarginRightMargin;
if SearchPanel.Visible then
begin
if OptionsContainer.DocumentSpecificSearch and (SearchForEdit.Text <> SynEdit.SearchString) then
SearchForEdit.Text := SynEdit.SearchString
else
DoSearch(True);
end;
end;
begin
if FProcessing then
Exit;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
begin
BufferCoord := SynEdit.CaretXY;
PositionAndSearch;
SynEdit.CaretXY := BufferCoord;
end
else
begin
SearchCloseAction.Execute;
GotoLineCloseAction.Execute;
end;
CheckFileDateTimes; { compare can change file datetime }
PageControl.Repaint;
end;
procedure TSQLEditorFrame.PageControlCloseButtonClick(Sender: TObject);
begin
Close;
end;
procedure TSQLEditorFrame.PageControlDblClick(Sender: TObject);
begin
if OptionsContainer.EditorCloseTabByDblClick then
Close;
end;
procedure TSQLEditorFrame.PageControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
if (Button = mbMiddle) and OptionsContainer.EditorCloseTabByMiddleClick then
Close
end;
procedure TSQLEditorFrame.Paste;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) and SynEdit.Focused then
SynEdit.PasteFromClipboard
else
if SearchPanel.Visible then
SearchForEdit.PasteFromClipboard;
end;
procedure TSQLEditorFrame.InitializeSynEditPrint;
var
SynEdit: TBCOraSynEdit;
Alignment: TAlignment;
procedure SetHeaderFooter(Option: Integer; Value: string);
begin
case Option of
0, 1:
with SynEditPrint.Footer do
begin
case Option of
0: Alignment := taLeftJustify;
1: Alignment := taRightJustify;
end;
Add(Value, nil, Alignment, 1);
end;
2, 3:
with SynEditPrint.Header do
begin
case Option of
2: Alignment := taLeftJustify;
3: Alignment := taRightJustify;
end;
Add(Value, nil, Alignment, 1);
end;
end;
end;
begin
SynEdit := GetActiveSynEdit;
SynEditPrint.Header.Clear;
SynEditPrint.Footer.Clear;
SetHeaderFooter(OptionsContainer.PrintDocumentName, SynEdit.DocumentName);
SetHeaderFooter(OptionsContainer.PrintPageNumber, LanguageDataModule.GetConstant('PreviewDocumentPage'));
SetHeaderFooter(OptionsContainer.PrintPrintedBy, Format(LanguageDataModule.GetConstant('PrintedBy'), [Application.Title]));
SetHeaderFooter(OptionsContainer.PrintDateTime, '$DATE$ $TIME$');
if OptionsContainer.PrintShowHeaderLine then
SynEditPrint.Header.FrameTypes := [ftLine]
else
SynEditPrint.Header.FrameTypes := [];
if OptionsContainer.PrintShowFooterLine then
SynEditPrint.Footer.FrameTypes := [ftLine]
else
SynEditPrint.Footer.FrameTypes := [];
SynEditPrint.LineNumbers := OptionsContainer.PrintShowLineNumbers;
SynEditPrint.Wrap := OptionsContainer.PrintWordWrapLine;
SynEditPrint.SynEdit := SynEdit;
SynEditPrint.Title := SynEdit.DocumentName;
end;
procedure TSQLEditorFrame.Print;
var
PrintDlgRec: TPrintDlg;
begin
if BCCommon.Dialogs.Print(Handle, PrintDlgRec) then
begin
Application.ProcessMessages; { style fix }
SynEditPrint.Copies := PrintDlgRec.nCopies;
SynEditPrint.SelectedOnly := PrintDlgRec.Flags and PD_SELECTION <> 0;
if PrintDlgRec.Flags and PD_PAGENUMS <> 0 then
SynEditPrint.PrintRange(PrintDlgRec.nFromPage, PrintDlgRec.nToPage);
InitializeSynEditPrint;
SynEditPrint.Print;
end;
end;
procedure TSQLEditorFrame.PrintPreview;
begin
InitializeSynEditPrint;
with PrintPreviewDialog do
begin
SynEditPrintPreview.SynEditPrint := SynEditPrint;
ShowModal;
end;
end;
function TSQLEditorFrame.SearchOptions(IncludeBackwards: Boolean): TSynSearchOptions;
begin
Result := [];
if IncludeBackwards then
Include(Result, ssoBackwards);
if CaseSensitiveCheckBox.Checked then
Include(Result, ssoMatchCase);
if WholeWordsCheckBox.Checked then
Include(Result, ssoWholeWord);
end;
procedure TSQLEditorFrame.Search;
var
SynEdit: TBCOraSynEdit;
begin
SearchPanel.Show;
SetSearchMapVisible(True);
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
begin
SearchPanel.Height := SearchForEdit.Height;
if SynEdit.SelAvail then
SearchForEdit.Text := SynEdit.SelText
else
if OptionsContainer.DocumentSpecificSearch then
SearchForEdit.Text := SynEdit.SearchString;
if SearchForEdit.CanFocus then
SearchForEdit.SetFocus;
SynEdit.CaretXY := BufferCoord(0, 0);
DoSearch;
end;
end;
procedure TSQLEditorFrame.DoSearch(SearchOnly: Boolean = False);
var
SynSearchOptions: TSynSearchOptions;
SynEdit: TBCOraSynEdit;
begin
if not SearchPanel.Visible then
Exit;
SynEdit := GetActiveSynEdit;
if not Assigned(SynEdit) then
Exit;
SynEdit.SearchString := SearchForEdit.Text;
if RegularExpressionCheckBox.Checked then
SynEdit.SearchEngine := SynEditRegexSearch
else
if WildCardCheckBox.Checked then
SynEdit.SearchEngine := SynEditWildCardSearch
else
SynEdit.SearchEngine := SynEditSearch;
SynSearchOptions := SearchOptions(False);
try
FFoundSearchItems.Clear;
if not SynEdit.FindSearchTerm(SearchForEdit.Text, FFoundSearchItems, SynSearchOptions) then
begin
if not SearchOnly then
begin
if OptionsContainer.BeepIfSearchStringNotFound then
MessageBeep;
SynEdit.BlockBegin := SynEdit.BlockEnd;
SynEdit.CaretXY := SynEdit.BlockBegin;
if OptionsContainer.ShowSearchStringNotFound then
ShowMessage(Format(LanguageDataModule.GetYesOrNoMessage('SearchStringNotFound'), [SearchForEdit.Text]));
PageControl.TabClosed := True; { just to avoid begin drag }
end;
end
else
if not SearchOnly then
FindNext;
SynEdit.Invalidate;
except
{ silent }
end;
end;
procedure TSQLEditorFrame.DoSearch2;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if not Assigned(SynEdit) then
Exit;
SetSearchMapVisible(SearchPanel.Visible);
if SearchPanel.Visible then
begin
if OptionsContainer.DocumentSpecificSearch then
SearchForEdit.Text := SynEdit.SearchString;
DoSearch(True);
end;
if SynEdit.CanFocus then
SynEdit.SetFocus;
end;
procedure TSQLEditorFrame.SearchClearActionExecute(Sender: TObject);
begin
SearchForEdit.Text := '';
end;
procedure TSQLEditorFrame.SearchCloseActionExecute(Sender: TObject);
begin
SearchForEdit.Text := '';
SearchPanel.Hide;
SetSearchMapVisible(False);
end;
procedure TSQLEditorFrame.SearchFindNextActionExecute(Sender: TObject);
begin
FindNext;
end;
procedure TSQLEditorFrame.SearchFindPreviousActionExecute(Sender: TObject);
begin
FindPrevious;
end;
procedure TSQLEditorFrame.SearchForEditChange(Sender: TObject);
var
SynEdit: TBCOraSynEdit;
CaretXY: TBufferCoord;
begin
SearchForEdit.RightButton.Visible := Trim(SearchForEdit.Text) <> '';
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
begin
CaretXY := SynEdit.CaretXY;
SynEdit.CaretXY := BufferCoord(0, 0);
SearchFindNextAction.Enabled := CanFindNextPrevious;
SearchFindPreviousAction.Enabled := SearchFindNextAction.Enabled;
DoSearch;
if Trim(SearchForEdit.Text) = '' then
begin
SynEdit.GotoLineAndCenter(CaretXY.Line);
SynEdit.CaretXY := CaretXY;
end;
end;
end;
procedure TSQLEditorFrame.FindNext;
var
SynSearchOptions: TSynSearchOptions;
SynEdit: TBCOraSynEdit;
begin
if SearchForEdit.Text = '' then
Exit;
SynSearchOptions := SearchOptions(False);
SynEdit := GetActiveSynEdit;
if SynEdit.SearchReplace(SearchForEdit.Text, '', SynSearchOptions) = 0 then
begin
if OptionsContainer.BeepIfSearchStringNotFound then
MessageBeep;
SynEdit.BlockBegin := SynEdit.BlockEnd;
SynEdit.CaretXY := SynEdit.BlockBegin;
if (SynEdit.CaretX = 1) and (SynEdit.CaretY = 1) then
begin
if OptionsContainer.ShowSearchStringNotFound then
ShowMessage(Format(LanguageDataModule.GetYesOrNoMessage('SearchStringNotFound'), [SearchForEdit.Text]))
end
else
if AskYesOrNo(Format(LanguageDataModule.GetYesOrNoMessage('SearchMatchNotFound'), [CHR_DOUBLE_ENTER])) then
begin
SynEdit.CaretX := 0;
SynEdit.CaretY := 0;
FindNext;
end;
end;
end;
procedure TSQLEditorFrame.FindPrevious;
var
SynSearchOptions: TSynSearchOptions;
SynEdit: TBCOraSynEdit;
begin
if SearchForEdit.Text = '' then
Exit;
SynSearchOptions := SearchOptions(True);
SynEdit := GetActiveSynEdit;
if SynEdit.SearchReplace(SearchForEdit.Text, '', SynSearchOptions) = 0 then
begin
MessageBeep;
SynEdit.BlockEnd := SynEdit.BlockBegin;
SynEdit.CaretXY := SynEdit.BlockBegin;
end;
end;
procedure TSQLEditorFrame.Replace;
var
SynSearchOptions: TSynSearchOptions;
SynEdit: TBCOraSynEdit;
i, MResult: Integer;
begin
with ReplaceDialog do
begin
SynEdit := GetActiveSynEdit;
if SynEdit.SelAvail then
SearchForComboBox.Text := SynEdit.SelText;
MResult := ShowModal;
if (MResult = mrOK) or (MResult = mrYes) then
begin
SynSearchOptions := SearchOptions(False);
if MResult = mrOK then
Include(SynSearchOptions, ssoPrompt);
Include(SynSearchOptions, ssoReplace);
Include(SynSearchOptions, ssoReplaceAll);
if ReplaceInWholeFile then
begin
SynEdit.CaretXY := BufferCoord(0, 0);
SynEdit.SearchReplace(SearchText, ReplaceText, SynSearchOptions);
end
else
begin
FProcessing := True;
Screen.Cursor := crHourGlass;
for i := 0 to PageControl.PageCount - 1 do
begin
PageControl.ActivePageIndex := i;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
begin
SynEdit.CaretXY := BufferCoord(0, 0);
SynEdit.SearchReplace(SearchText, ReplaceText, SynSearchOptions);
PageControl.Pages[i].Caption := FormatFileName(PageControl.Pages[i].Caption, SynEdit.Modified);
PageControl.UpdatePageCaption(PageControl.Pages[i]);
end;
end;
Screen.Cursor := crDefault;
FProcessing := False;
end;
end;
end;
end;
function TSQLEditorFrame.CanFindNextPrevious: Boolean;
begin
Result := SearchForEdit.Text <> '';
end;
function TSQLEditorFrame.WordWrap: Boolean;
var
SynEdit: TBCOraSynEdit;
begin
Result := False;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
Result := SynEdit.WordWrap.Enabled;
end;
function TSQLEditorFrame.ToggleWordWrap: Boolean;
var
i: Integer;
SynEdit: TSynEdit;
begin
Result := False;
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) then
begin
SynEdit.WordWrap.Enabled := not SynEdit.WordWrap.Enabled;
Result := SynEdit.WordWrap.Enabled;
end;
end;
end;
function TSQLEditorFrame.SpecialChars: Boolean;
var
SynEdit: TBCOraSynEdit;
begin
Result := False;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
Result := eoShowSpecialChars in SynEdit.Options;
end;
function TSQLEditorFrame.GetOpenTabSheetCount: Integer;
begin
Result := PageControl.PageCount;
end;
function TSQLEditorFrame.ToggleSpecialChars: Boolean;
var
i: Integer;
SynEdit: TSynEdit;
begin
Result := False;
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) then
begin
if eoShowSpecialChars in SynEdit.Options then
SynEdit.Options := SynEdit.Options - [eoShowSpecialChars]
else
SynEdit.Options := SynEdit.Options + [eoShowSpecialChars];
Result := eoShowSpecialChars in SynEdit.Options;
end;
if PageControl.Pages[i].Components[0] is TCompareFrame then
Result := TCompareFrame(PageControl.Pages[i].Components[0]).ToggleSpecialChars
end;
end;
function TSQLEditorFrame.SelectionMode: Boolean;
var
SynEdit: TBCOraSynEdit;
begin
Result := False;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
Result := SynEdit.SelectionMode = smColumn;
end;
function TSQLEditorFrame.ToggleSelectionMode: Boolean;
var
i: Integer;
SynEdit: TBCOraSynEdit;
begin
Result := False;
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) then
begin
if SynEdit.SelectionMode = smColumn then
begin
SynEdit.Options := SynEdit.Options + [eoAltSetsColumnMode];
SynEdit.SelectionMode := smNormal
end
else
begin
SynEdit.Options := SynEdit.Options - [eoAltSetsColumnMode];
SynEdit.SelectionMode := smColumn;
end;
Result := SynEdit.SelectionMode = smColumn;
end;
end;
end;
function TSQLEditorFrame.LineNumbers: Boolean;
var
SynEdit: TBCOraSynEdit;
begin
Result := False;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
Result := SynEdit.Gutter.ShowLineNumbers;
end;
function TSQLEditorFrame.ToggleLineNumbers: Boolean;
var
i: Integer;
SynEdit: TSynEdit;
begin
Result := False;
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) then
begin
SynEdit.Gutter.ShowLineNumbers := not SynEdit.Gutter.ShowLineNumbers;
Result := SynEdit.Gutter.ShowLineNumbers;
end;
if PageControl.Pages[i].Components[0] is TCompareFrame then
Result := TCompareFrame(PageControl.Pages[i].Components[0]).ToggleLineNumbers
end;
end;
function TSQLEditorFrame.GetSynEdit(TabSheet: TTabSheet): TBCOraSynEdit;
var
SQLEditorTabSheetFrame: TSQLEditorTabSheetFrame;
begin
Result := nil;
SQLEditorTabSheetFrame := GetSQLEditorTabSheetFrame(TabSheet);
if Assigned(SQLEditorTabSheetFrame) then
Result := SQLEditorTabSheetFrame.OraSynEdit;
end;
function TSQLEditorFrame.GetActiveSynEdit: TBCOraSynEdit;
begin
if Assigned(PageControl.ActivePage) then
Result := GetSynEdit(PageControl.ActivePage)
else
Result := nil;
end;
procedure TSQLEditorFrame.RepaintToolButtons;
var
i: Integer;
begin
MainForm.SetSQLEditorFields;
for i := 0 to ComponentCount - 1 do
if Components[i] is TToolButton then
TToolButton(Components[i]).Repaint;
end;
procedure TSQLEditorFrame.SetActivePageCaptionModified;
begin
if Pos('~', PageControl.ActivePageCaption) = 0 then
begin
PageControl.ActivePageCaption := Format('%s~', [PageControl.ActivePageCaption]);
PageControl.Invalidate;
end;
end;
procedure TSQLEditorFrame.SynEditOnChange(Sender: TObject);
begin
FModifiedDocuments := True;
if OptionsContainer.AutoSave then
Save
else
if not FProcessing then
SetActivePageCaptionModified;
DoSearch(True);
RepaintToolButtons;
end;
function TSQLEditorFrame.GetActiveTabSheetCaption: string;
begin
Result := '';
if Assigned(PageControl.ActivePage) then
Result := PageControl.ActivePageCaption;
end;
function TSQLEditorFrame.GetActiveDocumentFound: Boolean;
var
SynEdit: TBCOraSynEdit;
begin
Result := False;
if Assigned(PageControl.ActivePage) then
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
Result := True;
end;
end;
function TSQLEditorFrame.GetActiveDocumentName: string;
var
SynEdit: TBCOraSynEdit;
begin
Result := '';
if Assigned(PageControl.ActivePage) then
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
if SynEdit.DocumentName <> '' then
begin
Result := SynEdit.DocumentName;
if SynEdit.Modified then
Result := Result + ' - Modified';
end
end;
end;
function TSQLEditorFrame.GetOpenTabSheets: Boolean;
begin
Result := PageControl.PageCount > 0;
end;
function TSQLEditorFrame.GetModifiedDocuments(CheckActive: Boolean): Boolean;
var
i: Integer;
SynEdit: TBCOraSynEdit;
begin
Result := True;
for i := 0 to PageControl.PageCount - 1 do
begin
if CheckActive or ((PageControl.ActivePageIndex = i) and not CheckActive) then
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) then
if SynEdit.Modified then
Exit;
end;
end;
Result := False;
end;
function TSQLEditorFrame.GetSelectionFound: Boolean;
var
SynEdit: TBCOraSynEdit;
begin
Result := False;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
Result := SynEdit.SelAvail;
end;
function TSQLEditorFrame.GetCanUndo: Boolean;
var
SynEdit: TBCOraSynEdit;
begin
Result := False;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
Result := SynEdit.UndoList.ItemCount > 0;
end;
function TSQLEditorFrame.GetCanRedo: Boolean;
var
SynEdit: TBCOraSynEdit;
begin
Result := False;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
Result := SynEdit.RedoList.ItemCount > 0;
end;
procedure TSQLEditorFrame.SynEditorReplaceText(Sender: TObject; const ASearch,
AReplace: UnicodeString; Line, Column: Integer; DeleteLine: Boolean;
var Action: TSynReplaceAction);
var
APos: TPoint;
EditRect: TRect;
SynEdit: TBCOraSynEdit;
ConfirmText: string;
begin
if ASearch = AReplace then
Action := raSkip
else
begin
SynEdit := GetActiveSynEdit;
APos := SynEdit.ClientToScreen(SynEdit.RowColumnToPixels(SynEdit.BufferToDisplayPos(BufferCoord(Column, Line))));
EditRect := ClientRect;
EditRect.TopLeft := ClientToScreen(EditRect.TopLeft);
EditRect.BottomRight := ClientToScreen(EditRect.BottomRight);
if DeleteLine then
ConfirmText := LanguageDataModule.GetYesOrNoMessage('DeleteLine')
else
ConfirmText := Format(LanguageDataModule.GetYesOrNoMessage('ReplaceOccurence'), [ASearch]);
ConfirmReplaceDialog.Initialize(EditRect, APos.X, APos.Y, APos.Y + SynEdit.LineHeight,
ConfirmText);
try
case ConfirmReplaceDialog.ShowModal of
mrYes:
Action := raReplace;
mrYesToAll:
Action := raReplaceAll;
mrNo:
Action := raSkip;
else
Action := raCancel;
end;
finally
ConfirmReplaceDialog.Free;
end;
end;
end;
procedure TSQLEditorFrame.ToggleBookmarks(ItemIndex: Integer);
var
SynEdit: TBCOraSynEdit;
SynEditorCommand: TSynEditorCommand;
begin
SynEditorCommand := ecNone;
case ItemIndex of
0: SynEditorCommand := ecSetMarker0;
1: SynEditorCommand := ecSetMarker1;
2: SynEditorCommand := ecSetMarker2;
3: SynEditorCommand := ecSetMarker3;
4: SynEditorCommand := ecSetMarker4;
5: SynEditorCommand := ecSetMarker5;
6: SynEditorCommand := ecSetMarker6;
7: SynEditorCommand := ecSetMarker7;
8: SynEditorCommand := ecSetMarker8;
9: SynEditorCommand := ecSetMarker9;
end;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
SynEdit.ExecuteCommand(SynEditorCommand, Char(ItemIndex), nil);
end;
procedure TSQLEditorFrame.NextPage;
var
i: Integer;
begin
if Assigned(PageControl) then
begin
i := PageControl.ActivePageIndex + 1;
if i >= PageControl.PageCount then
i := 0;
PageControl.ActivePage := PageControl.Pages[i];
end;
end;
procedure TSQLEditorFrame.PreviousPage;
var
i: Integer;
begin
if Assigned(PageControl) then
begin
i := PageControl.ActivePageIndex - 1;
if i < 0 then
i := PageControl.PageCount - 1;
PageControl.ActivePage := PageControl.Pages[i];
end;
end;
procedure TSQLEditorFrame.CheckFileDateTimes;
var
i: Integer;
SynEdit: TBCOraSynEdit;
FileDateTime: TDateTime;
DialogResult: Integer;
begin
DialogResult := mrNo;
if FProcessing then
Exit;
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) then
if SynEdit.DocumentName <> '' then
begin
FileDateTime := GetFileDateTime(SynEdit.DocumentName);
if (FileDateTime <> 0) and (FileDateTime <> SynEdit.FileDateTime) then
begin
if FileExists(SynEdit.DocumentName) then
begin
PageControl.TabClosed := True; { just to avoid begin drag }
if not (DialogResult in [mrYesToAll, mrNoToAll]) then
DialogResult := AskYesOrNoAll(Format(LanguageDataModule.GetYesOrNoMessage('DocumentTimeChanged'), [SynEdit.DocumentName]));
if DialogResult in [mrYes, mrYesToAll] then
Refresh(i);
end
else
begin
if OptionsContainer.AutoSave then
Save
else
begin
SynEdit.Modified := True;
PageControl.Pages[i].Caption := FormatFileName(PageControl.Pages[i].Caption, SynEdit.Modified);
PageControl.Invalidate;
end;
end;
end;
end;
end;
end;
procedure TSQLEditorFrame.Refresh(Page: Integer);
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetSynEdit(PageControl.Pages[Page]);
if Assigned(SynEdit) then
begin
SynEdit.Lines.LoadFromFile(SynEdit.DocumentName);
SynEdit.FileDateTime := GetFileDateTime(SynEdit.DocumentName);
end;
end;
procedure TSQLEditorFrame.AssignOptions;
var
i: Integer;
SynEdit: TBCOraSynEdit;
begin
{ assign to every synedit }
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) then
OptionsContainer.AssignTo(SynEdit);
end;
{ set output options }
if Assigned(FOutputFrame) then
FOutputFrame.SetOptions;
end;
procedure TSQLEditorFrame.BoxDownActionExecute(Sender: TObject);
procedure BoxDown(SynEdit: TBCOraSynEdit);
begin
if Assigned(SynEdit) then
if SynEdit.Focused then
begin
OptionsContainer.EnableSelectionMode := True;
SynEdit.Options := SynEdit.Options + [eoAltSetsColumnMode];
SynEdit.Selectionmode := smColumn;
Keybd_Event(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0), 0, 0);
Keybd_Event(VK_DOWN, MapVirtualKey(VK_DOWN, 0), 0, 0);
Keybd_Event(VK_DOWN, MapVirtualKey(VK_DOWN, 0), KEYEVENTF_KEYUP, 0);
Keybd_Event(VK_MENU, MapVirtualKey(VK_MENU, 0), KEYEVENTF_KEYUP, 0);
end;
end;
begin
BoxDown(GetActiveSynEdit);
end;
procedure TSQLEditorFrame.BoxLeftActionExecute(Sender: TObject);
procedure BoxLeft(SynEdit: TBCOraSynEdit);
begin
if Assigned(SynEdit) then
if SynEdit.Focused then
begin
OptionsContainer.EnableSelectionMode := True;
SynEdit.Options := SynEdit.Options + [eoAltSetsColumnMode];
SynEdit.Selectionmode := smColumn;
Keybd_Event(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0), 0, 0);
Keybd_Event(VK_LEFT, MapVirtualKey(VK_LEFT, 0), 0, 0);
Keybd_Event(VK_LEFT, MapVirtualKey(VK_LEFT, 0), KEYEVENTF_KEYUP, 0);
Keybd_Event(VK_MENU, MapVirtualKey(VK_MENU, 0), KEYEVENTF_KEYUP, 0);
end;
end;
begin
BoxLeft(GetActiveSynEdit);
end;
procedure TSQLEditorFrame.BoxRightActionExecute(Sender: TObject);
procedure BoxRight(SynEdit: TBCOraSynEdit);
begin
if Assigned(SynEdit) then
if SynEdit.Focused then
begin
OptionsContainer.EnableSelectionMode := True;
SynEdit.Options := SynEdit.Options + [eoAltSetsColumnMode];
SynEdit.Selectionmode := smColumn;
Keybd_Event(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0), 0, 0);
Keybd_Event(VK_RIGHT, MapVirtualKey(VK_RIGHT, 0), 0, 0);
Keybd_Event(VK_RIGHT, MapVirtualKey(VK_RIGHT, 0), KEYEVENTF_KEYUP, 0);
Keybd_Event(VK_MENU, MapVirtualKey(VK_MENU, 0), KEYEVENTF_KEYUP, 0);
end;
end;
begin
BoxRight(GetActiveSynEdit);
end;
procedure TSQLEditorFrame.BoxUpActionExecute(Sender: TObject);
procedure BoxUp(SynEdit: TBCOraSynEdit);
begin
if Assigned(SynEdit) then
if SynEdit.Focused then
begin
OptionsContainer.EnableSelectionMode := True;
SynEdit.Options := SynEdit.Options + [eoAltSetsColumnMode];
SynEdit.Selectionmode := smColumn;
Keybd_Event(VK_SHIFT, MapVirtualKey(VK_SHIFT, 0), 0, 0);
Keybd_Event(VK_UP, MapVirtualKey(VK_UP, 0), 0, 0);
Keybd_Event(VK_UP, MapVirtualKey(VK_UP, 0), KEYEVENTF_KEYUP, 0);
Keybd_Event(VK_MENU ,MapVirtualKey(VK_MENU ,0), KEYEVENTF_KEYUP, 0);
end;
end;
begin
BoxUp(GetActiveSynEdit);
end;
procedure TSQLEditorFrame.SetHighlighterTableNames(Value: TStrings);
begin
SynSQLSyn.TableNames.Text := LowerCase(Value.Text);
end;
procedure TSQLEditorFrame.ShowObjects;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
SynEdit.ObjectCompletionProposal.ActivateCompletion;
end;
procedure TSQLEditorFrame.OutputDblClickActionExecute(Sender: TObject);
var
Filename: string;
Ln, Ch: LongWord;
begin
if FOutputFrame.SelectedLine(Filename, Ln, Ch) then
Open(Filename, nil, Ln, Ch);
end;
function GetOraScriptErrorPos(Msg: string; var Row, Col: Integer): Boolean;
var
Error: string;
begin
Result := False;
Row := 1;
Col := 1;
Error := Msg;
if Pos(' ', Error) <> 0 then
Error := System.Copy(Error, 1, Pos(' ', Error) - 1);
if Pos('/', Error) <> 0 then
begin
try
Row := StrToInt(System.Copy(Error, 1, Pos('/', Error) - 1));
Error := System.Copy(Error, Pos('/', Error) + 1, Length(Error));
Col := StrToInt(Error);
Result := True;
except
end;
end
end;
procedure TSQLEditorFrame.ExecuteScript(Current: Boolean);
var
i, Row, Col: Integer;
SynEdit: TBCOraSynEdit;
CreateStatement: Boolean;
s, Temp: WideString;
begin
SynEdit := GetActiveSynEdit;
if SynEdit.SelAvail then
s := SynEdit.SelText
else
s := Trim(SynEdit.Text);
CreateStatement := Pos(ShortString('CREATE'), UpperCase(Trim(RemoveParenthesisFromBegin(RemoveComments(s))))) = 1;
OraScript.SQL.Text := s;
if Current then
begin
{ find current script }
for i := 0 to OraScript.Statements.Count - 1 do
if (OraScript.Statements.Items[i].StartLine <= SynEdit.CaretXY.Line - 1) and
(OraScript.Statements.Items[i].EndLine >= SynEdit.CaretXY.Line - 1) then
begin
s := OraScript.Statements.Items[i].SQL;
OraScript.SQL.Text := s;
Break;
end;
end;
if (System.Pos(WideString('SELECT'), WideString(Trim(UpperCase(s)))) = 1) or
(System.Pos(WideString('DESC'), WideString(Trim(UpperCase(s)))) = 1) then
ExecuteStatement(GetActiveSynEdit, s)
else
begin
ScriptQuery.SQL.Text := s;
try
OraScript.Session := FSession;
ScriptQuery.Session := FSession;
ScriptQuery.AfterExecute := OraScriptQueryAfterExecuteEvent;
FOutputFrame.ClearStrings('Output: ' + GetActivePageCaption);
SynEdit.StartTime := Now;
if MainForm.DBMSOutputAction.Checked then // DBMSOutputToolButton.Down then
EnableDBMSOutput;
{ parameters }
if ScriptQuery.ParamCount > 0 then
if not ParametersDialog.Open(ScriptQuery) then
Exit;
if not CreateStatement then
if not FSession.InTransaction then
FSession.StartTransaction;
for i := 0 to OraScript.Statements.Count - 1 do
begin
Temp := OraScript.Statements.Items[i].SQL;
if System.Pos('EXECUTE', UpperCase(Temp)) = 1 then
begin
Temp := 'BEGIN ' + System.Copy(Temp, 8, Length(Temp)) + '; END;';
ScriptQuery.SQL.Text := Temp;
ScriptQuery.Execute;
end
else
if System.Pos('EXEC', UpperCase(Temp)) = 1 then
begin
Temp := 'BEGIN ' + System.Copy(Temp, 5, Length(Temp)) + '; END;';
ScriptQuery.SQL.Text := Temp;
ScriptQuery.Execute;
end
else
OraScript.Statements.Items[i].Execute;
end;
if MainForm.DBMSOutputAction.Checked then //DBMSOutputToolButton.Down then
GetDBMSOutput;
OutputPanel.Visible := True;
except
on E: EOraError do
begin
if not GetOraScriptErrorPos(E.Message, Row, Col) then
OraScript.DataSet.GetErrorPos(Row, Col);
OutputPanel.Visible := True;
SynEdit.SetFocus;
SynEdit.CaretY := Row;
SynEdit.CaretX := Col;
end;
end;
end;
end;
function TSQLEditorFrame.RemoveComments(s: WideString): WideString; //SynEdit: TBCOraSynEdit): WideString;
var
Line, Temp: string;
i: Integer;
InComment: Boolean;
SQLSynEdit: TSynEdit;
begin
Result := '';
// remove comments
InComment := False;
SQLSynEdit := TSynEdit.Create(nil);
try
SQLSynEdit.Text := s;
for i := 0 to SQLSynEdit.Lines.Count - 1 do
begin
Line := SQLSynEdit.Lines[i];
if not InComment then
begin
Temp := Line;
if Pos('--', Line) <> 0 then
Temp := System.Copy(Line, 0, Pos('--', Line) - 1);
if Pos('/*', Line) <> 0 then
begin
InComment := True;
Temp := System.Copy(Temp, 0, Pos('/*', Temp) - 1)
end;
if Pos('*/', Line) <> 0 then
begin
InComment := False;
Temp := Temp + System.Copy(Line, Pos('*/', Line) + 2, Length(Line))
end;
Result := Result + Temp + CHR_ENTER;
end
else
if InComment and (Pos('*/', Line) <> 0) then
begin
InComment := False;
Result := Result + System.Copy(Line, Pos('*/', Line) + 2, Length(Line))
end
end;
finally
SQLSynEdit.Free;
end;
end;
function TSQLEditorFrame.RemoveParenthesisFromBegin(Text: WideString): WideString;
begin
Result := Text;
while Pos('(', Result) = 1 do
Result := Trim(System.Copy(Result, 2, Length(Result)));
end;
procedure TSQLEditorFrame.ExecuteCurrentStatement;
begin
ExecuteStatement(True);
end;
procedure TSQLEditorFrame.ExecuteStatement(Current: Boolean);
var
SynEdit: TBCOraSynEdit;
s: WideString;
begin
SynEdit := GetActiveSynEdit;
if SynEdit.SelAvail then
s := SynEdit.SelText
else
s := Trim(SynEdit.Text);
s := Trim(UpperCase(RemoveParenthesisFromBegin(RemoveComments(s))));
if s = '' then
Exit;
if s[Length(s)] = ';' then
ExecuteScript(Current)
else
if (System.Pos(WideString('SELECT'), s) = 1) or (System.Pos(WideString('DESC'), s) = 1) then
ExecuteStatement(SynEdit)
else
ExecuteNoRowsStatement(SynEdit);
end;
procedure TSQLEditorFrame.ExplainPlan;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Trim(SynEdit.Text) = '' then
Exit;
if not Assigned(SynEdit.PlanQuery) then
begin
SynEdit.PlanQuery := TOraQuery.Create(nil);
SynEdit.PlanQuery.Session := FSession;
SynEdit.PlanQuery.ReadOnly := True;
SynEdit.PlanQuery.SQL.Clear;
SynEdit.PlanQuery.SQL.Add(SQLStringHolder.StringsByName['ExplainPlanSQL'].Text);
end;
FSession.ExecSQL('DELETE plan_table', ['',0]);
try
FSession.ExecSQL('EXPLAIN PLAN FOR ' + SynEdit.Text, ['',0]);
except
on E: EOraError do
begin
FOutputFrame.AddErrors('Errors: ' + GetActivePageCaption, E.Message);
OutputPanel.Visible := True;
Exit;
end;
end;
SynEdit.PlanQuery.Close;
SynEdit.PlanQuery.UnPrepare;
SynEdit.PlanQuery.Prepare;
SynEdit.PlanQuery.Open;
FOutputFrame.AddPlanGrid('Plan: ' + GetActivePageCaption, SynEdit.PlanQuery);
OutputPanel.Visible := True;
end;
function TSQLEditorFrame.CreateSession(OraSession: TOraSession): TOraSession;
begin
Result := TOraSession.Create(Self);
Result.ConnectString := OraSession.ConnectString;
Result.Options.Direct := OraSession.Options.Direct;
Result.Options.DateFormat := OptionsContainer.DateFormat;
Result.Options.UseUnicode := True;
Result.Options.UnicodeEnvironment := True; // False;
Result.AutoCommit := False;
Result.ThreadSafety := True;
Result.ConnectPrompt := False;
Result.OnError := OraSessionError;
Result.Connect;
end;
procedure TSQLEditorFrame.GetUserErrors;
var
s: string;
ObjectName: string;
SQLTokenizer: TSQLTokenizer;
SynEdit: TBCOraSynEdit;
begin
{ Get objectname }
SQLTokenizer := TSQLTokenizer.Create;
SynEdit := GetActiveSynEdit;
try
SQLTokenizer.SetText(SynEdit.Text);
while not SQLTokenizer.Eof do
begin
if SQLTokenizer.TokenStrIs('PROCEDURE') or
SQLTokenizer.TokenStrIs('FUNCTION') or
SQLTokenizer.TokenStrIs('PACKAGE') or
SQLTokenizer.TokenStrIs('TRIGGER') or
SQLTokenizer.TokenStrIs('FROM') then
begin
SQLTokenizer.Next;
while not SQLTokenizer.Eof do
if (UpperCase(Trim(SQLTokenizer.TokenStr)) <> '') and not SQLTokenizer.TokenStrIs('BODY') then
Break
else
SQLTokenizer.Next;
ObjectName := UpperCase(SQLTokenizer.TokenStr);
SQLTokenizer.Next;
if SQLTokenizer.TokenType = ttPeriod then
begin
SQLTokenizer.Next;
ObjectName := UpperCase(SQLTokenizer.TokenStr);
end;
Break;
end;
SQLTokenizer.Next;
end;
finally
SQLTokenizer.Free;
end;
{ Get errors from user_errors }
with ErrorsQuery do
begin
if not Session.Connected then
begin
Session.ConnectPrompt := False;
Session.Connect;
Session.ConnectPrompt := True;
end;
ParamByName('P_NAME').AsString := ObjectName;
Open;
while not Eof do
begin
s := Format('(%d, %d): %s', [FieldByName('LINE').AsInteger, FieldByName('POSITION').AsInteger,
FieldByName('TEXT').AsWideString]);
SynEdit.CaretX := FieldByName('POSITION').AsInteger;
SynEdit.CaretY := FieldByName('LINE').AsInteger;
FOutputFrame.AddErrors('Errors: ' + GetActivePageCaption, s);
Next;
end;
Close;
end;
end;
procedure TSQLEditorFrame.GotoBookmarks(ItemIndex: Integer);
var
SynEdit: TBCOraSynEdit;
SynEditorCommand: TSynEditorCommand;
begin
SynEditorCommand := ecNone;
case ItemIndex of
0: SynEditorCommand := ecGotoMarker0;
1: SynEditorCommand := ecGotoMarker1;
2: SynEditorCommand := ecGotoMarker2;
3: SynEditorCommand := ecGotoMarker3;
4: SynEditorCommand := ecGotoMarker4;
5: SynEditorCommand := ecGotoMarker5;
6: SynEditorCommand := ecGotoMarker6;
7: SynEditorCommand := ecGotoMarker7;
8: SynEditorCommand := ecGotoMarker8;
9: SynEditorCommand := ecGotoMarker9;
end;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
SynEdit.ExecuteCommand(SynEditorCommand, Char(ItemIndex), nil);
end;
procedure TSQLEditorFrame.OraSessionError(Sender: TObject; E: EDAError; var Fail: Boolean);
begin
FOutputFrame.AddErrors('Errors: ' + GetActivePageCaption, E.Message);
GetUserErrors;
Application.ProcessMessages;
Fail := True;
end;
procedure TSQLEditorFrame.GetText(Sender: TField; var Text: String; DisplayText: Boolean);
begin
Text := Copy(Sender.AsString, 1, 50);
end;
procedure TSQLEditorFrame.SetClobAndTimestampFields(OraQuery: TOraQuery);
var
i: Integer;
begin
for i := 0 to OraQuery.Fields.Count - 1 do
begin
if OraQuery.Fields[i].DataType = ftOraClob then
OraQuery.Fields[i].OnGetText := GetText
else
if OraQuery.Fields[i].DataType = ftTimestamp then
TOraTimeStampField (OraQuery.Fields[i]).Format := OptionsContainer.DateFormat + ' ' + OptionsContainer.TimeFormat;
end
end;
procedure TSQLEditorFrame.ExecuteStatement(SynEdit: TBCOraSynEdit; SQL: string = '');
var
s, Owner, TableName: string;
T1, T2: TTime;
QuerySuccess: Boolean;
Row, Col: Integer;
begin
if not Assigned(SynEdit.OraQuery) then
begin
SynEdit.OraQuery := TOraQuery.Create(nil);
SynEdit.OraQuery.Session := CreateSession(FSession);
SynEdit.OraQuery.AutoCommit := False;
SynEdit.OraQuery.FetchRows := 500;
SynEdit.OraQuery.Options.StrictUpdate := False;
SynEdit.OraQuery.Options.RequiredFields := False;
SynEdit.OraQuery.Options.RawAsString := True;
SynEdit.OraQuery.LocalUpdate := True;
SynEdit.OraQuery.NonBlocking := True;
SynEdit.OraQuery.Options.CacheLobs := False;
SynEdit.OraQuery.Options.DeferredLobRead := True;
end;
SynEdit.OraQuery.SQL.Clear;
if SQL <> '' then
s := SQL
else
if SynEdit.SelAvail then
s := SynEdit.SelText
else
s := Trim(SynEdit.Text);
if s[Length(s)] = ';' then // remove ; at the end, if exists
s[Length(s)] := ' ';
if System.Pos('DESC', UpperCase(s)) = 1 then
begin
Owner := SchemaParam;
TableName := UpperCase(Trim(System.Copy(s, 5, Length(s))));
if Pos('.', TableName) <> 0 then
begin
Owner := Copy(TableName, 1, Pos('.', TableName) - 1);
TableName := Copy(TableName, Pos('.', TableName) + 1, Length(TableName));
end;
s := Format(SQLStringHolder.StringsByName['ColumnsSQL'].Text, [Owner, TableName, Owner, TableName]);
end;
SynEdit.OraQuery.SQL.Add(s);
{ parameters }
if SynEdit.OraQuery.ParamCount > 0 then
if not ParametersDialog.Open(SynEdit.OraQuery) then
Exit;
T1 := Now;
QuerySuccess := False;
try
SynEdit.InThread := True;
SynEdit.OraQuery.Prepare;
AddAllFields(SynEdit.OraQuery); { these are important to do after prepare because if there is }
SetClobAndTimestampFields(SynEdit.OraQuery); { problem with fields it may cause OCI_INVALID_HANDLE }
SynEdit.OraQuery.Open;
QuerySuccess := QueryProgressDialog.Open(SynEdit.OraQuery, T1);
if not QuerySuccess then
SynEdit.OraQuery.Active := False;
SynEdit.InThread := False;
except
end;
if QuerySuccess then
begin
T2 := Now;
FOutputFrame.AddDataGrid('Data: ' + GetActivePageCaption, SynEdit.OraQuery, System.SysUtils.FormatDateTime('hh:nn:ss.zzz', T2 - T1));
WriteHistory(SynEdit.OraQuery.Session, SynEdit.Text);
end
else
begin
SynEdit.OraQuery.GetErrorPos(Row, Col);
SynEdit.SetFocus;
SynEdit.CaretY := Row;
SynEdit.CaretX := Col;
end;
OutputPanel.Visible := True;
end;
procedure TSQLEditorFrame.EnableDBMSOutput;
var
SynEdit: TBCOraSynEdit;
OraSession: TOraSession;
begin
SynEdit := GetActiveSynEdit;
OraSession := nil;
if Assigned(SynEdit) and Assigned(SynEdit.OraSQL) then
OraSession := SynEdit.OraSQL.Session
else
if Assigned(OraScript.Session) then
OraSession := OraScript.Session;
if Assigned(OraSession) then
OraSession.ExecSQL('BEGIN dbms_output.enable(1000000); END;', []);
end;
procedure TSQLEditorFrame.ExecuteNoRowsStatement(SynEdit: TBCOraSynEdit);
var
s: WideString;
QuerySuccess: Boolean;
CreateNewSession: Boolean;
begin
{ if update, insert or delete statement then use FSession and transaction otherwise create new session
and no transaction }
if SynEdit.SelAvail then
s := SynEdit.SelText
else
s := Trim(SynEdit.Text);
s := UpperCase(s);
// remove ('s
while Pos('(', s) = 1 do
s := Trim(System.Copy(s, 2, Length(s)));
CreateNewSession := (Pos(WideString('UPDATE'), s) <> 1) and (Pos(WideString('INSERT'), s) <> 1) and
(Pos(WideString('DELETE'), s) <> 1);
SynEdit.OraSQL := TOraSQL.Create(nil);
if CreateNewSession then
SynEdit.OraSQL.Session := CreateSession(FSession)
else
SynEdit.OraSQL.Session := FSession;
SynEdit.OraSQL.AutoCommit := False;
SynEdit.OraSQL.AfterExecute := OraSQLAfterExecuteEvent;
SynEdit.OraSQL.NonBlocking := CreateNewSession;
try
SynEdit.OraSQL.SQL.Clear;
if SynEdit.SelAvail then
s := SynEdit.SelText
else
s := Trim(SynEdit.Text);
if System.Pos('EXECUTE', UpperCase(s)) = 1 then
s := 'BEGIN ' + System.Copy(s, 8, Length(s)) + '; END;';
if System.Pos('EXEC', UpperCase(s)) = 1 then
s := 'BEGIN ' + System.Copy(s, 5, Length(s)) + '; END;';
SynEdit.OraSQL.SQL.Add(s);
{ parameters }
if SynEdit.OraSQL.ParamCount > 0 then
if not ParametersDialog.Open(SynEdit.OraSQL) then
Exit;
SynEdit.StartTime := Now;
try
if MainForm.DBMSOutputAction.Checked then //DBMSOutputToolButton.Down then
EnableDBMSOutput;
if not CreateNewSession then
if not FSession.InTransaction then
FSession.StartTransaction;
SynEdit.InThread := True;
QuerySuccess := True;
SynEdit.OraSQL.Prepare;
SynEdit.OraSQL.Execute;
if CreateNewSession then
begin
QuerySuccess := SQLProgressDialog.Open(SynEdit.OraSQL, SynEdit.StartTime);
if not QuerySuccess then
SynEdit.OraSQL.BreakExec;
end;
SynEdit.InThread := False;
if QuerySuccess then
if MainForm.DBMSOutputAction.Checked then //DBMSOutputToolButton.Down then
GetDBMSOutput;
except
QuerySuccess := SynEdit.OraSQL.ErrorOffset = 0;
end;
if not QuerySuccess then
begin
SynEdit.SetFocus;
SynEdit.SelStart := SynEdit.OraSQL.ErrorOffset + 2;
end;
OutputPanel.Visible := True;
finally
SynEdit.OraSQL.Free;
end;
end;
procedure TSQLEditorFrame.OraSQLAfterExecuteEvent(Sender: TObject; Result: Boolean);
var
i:integer;
SynEdit: TBCOraSynEdit;
StringList: TStringList;
s: string;
begin
SynEdit := GetActiveSynEdit;
if Result then
begin
StringList := TStringList.Create;
try
for i := 0 to SynEdit.OraSQL.Params.Count-1 do
StringList.Add(Format('%s = %s', [SynEdit.OraSQL.Params[i].Name, SynEdit.OraSQL.Params[i].AsWideString]));
if SynEdit.OraSQL.RowsProcessed <> 0 then
s := Format('%d row(s) processed.', [SynEdit.OraSQL.RowsProcessed])
else
s := 'Success.';
StringList.Add(Format('%s Time Elapsed: %s', [s, System.SysUtils.FormatDateTime('hh:nn:ss.zzz', Now - SynEdit.StartTime)]));
FOutputFrame.AddStrings(Format('Output: %s', [GetActivePageCaption]), StringList.Text);
finally
WriteHistory(SynEdit.OraSQL.Session, SynEdit.Text);
StringList.Free;
end;
end
end;
procedure TSQLEditorFrame.OraScriptQueryAfterExecuteEvent(Sender: TObject; Result: Boolean);
var
i:integer;
SynEdit: TBCOraSynEdit;
StringList: TStringList;
s: string;
begin
SynEdit := GetActiveSynEdit;
if Result then
begin
StringList := TStringList.Create;
try
for i := 0 to ScriptQuery.Params.Count-1 do
StringList.Add(Format('%s = %s', [ScriptQuery.Params[i].Name, ScriptQuery.Params[i].AsWideString]));
if ScriptQuery.RowsProcessed <> 0 then
s := Format('%d row(s) processed.', [ScriptQuery.RowsProcessed])
else
s := 'Success.';
StringList.Add(Format('%s Time Elapsed: %s', [s, System.SysUtils.FormatDateTime('hh:nn:ss.zzz', Now - SynEdit.StartTime)]));
FOutputFrame.AddStrings(Format('Output: %s', [GetActivePageCaption]), StringList.Text);
finally
WriteHistory(ScriptQuery.Session, SynEdit.Text);
StringList.Free;
end;
end
end;
procedure TSQLEditorFrame.GetDBMSOutput;
begin
{ start timer }
if not Assigned(FDBMSTimer) then
begin
FDBMSTimer := TTimer.Create(nil);
FDBMSTimer.Interval := OptionsContainer.PollingInterval * 1000; // milliseconds
FDBMSTimer.OnTimer := DBMSOutputTimer;
end;
FDBMSTimer.Enabled := True;
end;
procedure TSQLEditorFrame.DBMSOutputTimer(Sender: TObject);
var
Found: Boolean;
SynEdit: TBCOraSynEdit;
OraSession: TOraSession;
begin
Found := False;
SynEdit := GetActiveSynEdit;
OraSession := nil;
if Assigned(SynEdit) and Assigned(SynEdit.OraSQL) then
OraSession := SynEdit.OraSQL.Session
else
if Assigned(OraScript.Session) then
OraSession := OraScript.Session;
try
if Assigned(OraSession) then
begin
OraSession.ExecSQL('BEGIN dbms_output.get_line(:buffer,:status); END;', ['',0]);
while OraSession.ParamByName('STATUS').AsFloat = 0 do
begin
Found := True;
FOutputFrame.AddDBMSOutput('DBMS output: ' + GetActivePageCaption, OraSession.ParamByName('BUFFER').AsWideString);
OraSession.ExecSQL('BEGIN dbms_output.get_line(:buffer,:status); END;', ['',0]);
end;
if Found or not MainForm.DBMSOutputAction.Checked then //DBMSOutputToolButton.Down then
begin
OraSession.ExecSQL('BEGIN dbms_output.disable; END;', []);
FDBMSTimer.Enabled := False;
FDBMSTimer.Free;
FDBMSTimer := nil;
end;
end;
except
end;
end;
procedure TSQLEditorFrame.WriteHistory(OraSession: TOraSession; SQL: WideString);
var
History: TStrings;
begin
History := TStringList.Create;
try
if FileExists(GetHistoryFile) then
History.LoadFromFile(GetHistoryFile);
// date;schema;sql#!ENDSQL!#
History.Insert(0, EncryptString(DateTimeToStr(Now) + ';' +
Lib.FormatSchema(OraSession.Schema + '@' + OraSession.Server) + ';' +
SQL + END_OF_SQL_STATEMENT));
History.SaveToFile(GetHistoryFile);
finally
History.Free;
end;
end;
function TSQLEditorFrame.GetCaretInfo: string;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
Result := Format('%d: %d', [SynEdit.CaretY, SynEdit.CaretX]);
end;
function TSQLEditorFrame.GetModifiedInfo: string;
var
SynEdit: TBCOraSynEdit;
begin
Result := '';
if OptionsContainer.AutoSave then
Result := LanguageDataModule.GetConstant('AutoSave')
else
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) and SynEdit.Modified then
Result := LanguageDataModule.GetConstant('Modified');
end;
end;
procedure TSQLEditorFrame.DecreaseIndent;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
SynEdit.ExecuteCommand(ecBlockUnindent, 'U', nil);
end;
procedure TSQLEditorFrame.IncreaseIndent;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
SynEdit.ExecuteCommand(ecBlockIndent, 'I', nil);
end;
procedure TSQLEditorFrame.ToggleCase;
var
SelStart, SelEnd: Integer;
SynEdit: TBCOraSynEdit;
function Toggle(const aStr: UnicodeString): UnicodeString;
var
i: Integer;
sLower: UnicodeString;
begin
Result := SynWideUpperCase(aStr);
sLower := SynWideLowerCase(aStr);
for i := 1 to Length(aStr) do
begin
if Result[i] = aStr[i] then
Result[i] := sLower[i];
end;
end;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
if SynEdit.Focused then
begin
if SynWideUpperCase(SynEdit.SelText) <> SynWideUpperCase(FSelectedText) then
begin
FCaseCycle := 0;
FSelectedText := SynEdit.SelText;
end;
SynEdit.BeginUpdate;
SelStart := SynEdit.SelStart;
SelEnd := SynEdit.SelEnd;
{ UPPER/lower/Sentence/And Title }
case FCaseCycle of
0: SynEdit.SelText := SynWideUpperCase(FSelectedText);
1: SynEdit.SelText := SynWideLowerCase(FSelectedText);
2: SynEdit.SelText := Toggle(FSelectedText);
3: SynEdit.SelText := SynWideUpperCase(FSelectedText[1]) + SynWideLowerCase(System.Copy(FSelectedText, 2, Length(FSelectedText)));
4: SynEdit.SelText := FSelectedText;
end;
SynEdit.SelStart := SelStart;
SynEdit.SelEnd := SelEnd;
SynEdit.EndUpdate;
Inc(FCaseCycle);
if FCaseCycle > 4 then
FCaseCycle := 0;
end;
end;
procedure TSQLEditorFrame.SortAsc;
var
SynEdit: TBCOraSynEdit;
Strings: TWideStringList;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
begin
Strings := TWideStringList.Create;
with Strings do
try
Text := SynEdit.SelText;
Sort;
SynEdit.SelText := TrimRight(Text);
finally
Free;
end;
end;
end;
procedure TSQLEditorFrame.SortDesc;
var
i: Integer;
SynEdit: TBCOraSynEdit;
s: WideString;
Strings: TWideStringList;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
begin
Strings := TWideStringList.Create;
with Strings do
try
Text := SynEdit.SelText;
Sort;
for i := Count - 1 downto 0 do
s := s + Strings[i] + Chr(13) + Chr(10);
SynEdit.SelText := TrimRight(s);
finally
Free;
end;
end;
end;
procedure TSQLEditorFrame.ClearBookmarks;
var
i: Integer;
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
for i := 0 to 9 do
SynEdit.ClearBookMark(i);
end;
procedure TSQLEditorFrame.InsertLine;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
SynEdit.ExecuteCommand(ecInsertLine, 'N', nil);
end;
procedure TSQLEditorFrame.DeleteWord;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
SynEdit.ExecuteCommand(ecDeleteWord, 'T', nil);
end;
procedure TSQLEditorFrame.DeleteLine;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
SynEdit.ExecuteCommand(ecDeleteLine, 'Y', nil);
end;
procedure TSQLEditorFrame.DeleteEOL;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
SynEdit.ExecuteCommand(ecDeleteEOL, 'Y', nil);
end;
function TSQLEditorFrame.GetActiveDocumentModified: Boolean;
var
SynEdit: TBCOraSynEdit;
begin
SynEdit := GetActiveSynEdit;
Result := Assigned(SynEdit) and SynEdit.Modified;
end;
function TSQLEditorFrame.IsCompareFilesActivePage: Boolean;
begin
Result := Assigned(PageControl.ActivePage) and (PageControl.ActivePage.ImageIndex = FCompareImageIndex);
end;
procedure TSQLEditorFrame.GotoLine;
begin
GotoLinePanel.Show;
if GotoLineNumberEdit.CanFocus then
GotoLineNumberEdit.SetFocus;
end;
procedure TSQLEditorFrame.SetSearchMapVisible(Value: Boolean);
var
i: Integer;
SynEdit: TBCOraSynEdit;
begin
for i := 0 to PageControl.PageCount - 1 do
begin
SynEdit := GetSynEdit(PageControl.Pages[i]);
if Assigned(SynEdit) then
SynEdit.SearchMap.Visible := OptionsContainer.ShowSearchMap and Value;
end;
end;
procedure TSQLEditorFrame.GotoLineActionExecute(Sender: TObject);
begin
try
GetActiveSynEdit.CaretY := StrToInt(GotoLineNumberEdit.Text);
except
{ silent }
end;
end;
procedure TSQLEditorFrame.GotoLineClearActionExecute(Sender: TObject);
begin
GotoLineNumberEdit.Text := '';
end;
procedure TSQLEditorFrame.GotoLineCloseActionExecute(Sender: TObject);
begin
GotoLinePanel.Hide;
end;
procedure TSQLEditorFrame.GotoLineNumberEditChange(Sender: TObject);
begin
GotoLineNumberEdit.RightButton.Visible := Trim(GotoLineNumberEdit.Text) <> '';
end;
procedure TSQLEditorFrame.GotoLineNumberEditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
GotoLineAction.Execute;
end;
function TSQLEditorFrame.GetActiveBookmarkList: TSynEditMarkList;
var
SynEdit: TBCOraSynEdit;
begin
Result := nil;
SynEdit := GetActiveSynEdit;
if Assigned(SynEdit) then
Result := SynEdit.Marks;
end;
function TSQLEditorFrame.GetInTransAction: Boolean;
begin
Result := FSession.InTransaction;
end;
procedure TSQLEditorFrame.ToggleMiniMap;
var
SQLEditorTabSheetFrame: TSQLEditorTabSheetFrame;
begin
SQLEditorTabSheetFrame := GetSQLEditorTabSheetFrame(PageControl.ActivePage);
if Assigned(SQLEditorTabSheetFrame) then
SQLEditorTabSheetFrame.MinimapVisible := not SQLEditorTabSheetFrame.MinimapVisible;
end;
function TSQLEditorFrame.GetMinimapChecked: Boolean;
var
SQLEditorTabSheetFrame: TSQLEditorTabSheetFrame;
begin
Result := False;
SQLEditorTabSheetFrame := GetSQLEditorTabSheetFrame(PageControl.ActivePage);
if Assigned(SQLEditorTabSheetFrame) then
Result := SQLEditorTabSheetFrame.MinimapVisible;
end;
procedure TSQLEditorFrame.CreateActionToolBar(CreateToolBar: Boolean);
var
i, k, ButtonCount: Integer;
s: string;
Action: TCustomAction;
ToolBarItems: TStrings;
Panel: TPanel;
ToolBar: TBCToolBar;
ToolButton: TToolButton;
Bevel: TBevel;
IsChanged: Boolean;
function FindItemByName(ItemName: string): TCustomAction;
var
j: Integer;
begin
Result := nil;
for j := 0 to MainForm.ActionManager.ActionCount - 1 do
if MainForm.ActionManager.Actions[j].Name = ItemName then
Exit(MainForm.ActionManager.Actions[j] as TCustomAction);
end;
begin
ToolBarItems := TStringList.Create;
with TBigIniFile.Create(GetIniFilename) do
try
{ update if changed }
IsChanged := ReadBool('ToolBarItemsChanged', 'Changed', False);
EraseSection('ToolBarItemsChanged');
if IsChanged or CreateToolBar then
begin
ToolbarPanel.Visible := False;
{ read items from ini }
ReadSectionValues('ToolBarItems', ToolBarItems);
if ToolBarItems.Count > 0 then
begin
{ add items to action bar }
for i := ToolbarPanel.ControlCount - 1 downto 0 do
(ToolbarPanel.Controls[i] as TPanel).Free;
i := ToolBarItems.Count - 1;
while i >= 0 do
begin
Panel := TPanel.Create(ToolbarPanel);
Panel.Parent := ToolbarPanel;
Panel.Align := alLeft;
Panel.BevelOuter := bvNone;
Panel.ParentColor := True;
Panel.AutoSize := True;
Toolbar := TBCToolBar.Create(Panel);
Toolbar.Parent := Panel;
Toolbar.Images := ImagesDataModule.ImageList;
Toolbar.Align := alLeft;
//ToolBar.Autosize := True;
{ Fuck this, Embarcadero! AutoSize can't be used because syncronizing between action's checked property and
the tool button's down property will be lost.
See Vcl.ComCtrls.pas: procedure TToolButton.SetAutoSize(Value: Boolean); buttons are recreated. }
k := i;
ButtonCount := 0;
while (k >= 0) and (Pos('-', ToolBarItems.Strings[k]) = 0) do
begin
Inc(ButtonCount);
Dec(k);
end;
ToolBar.Width := ButtonCount * 23;
s := '';
while (i >= 0) and (s <> '-') do
begin
s := System.Copy(ToolBarItems.Strings[i], Pos('=', ToolBarItems.Strings[i]) + 1, Length(ToolBarItems.Strings[i]));
if s <> '-' then
begin
ToolButton := TToolButton.Create(Toolbar);
ToolButton.Parent := Toolbar;
Action := FindItemByName(s);
if Action.Tag = 99 then
ToolButton.Style := tbsCheck;
ToolButton.Action := Action;
end
else
begin
if i > 0 then { no bevel after last item }
begin
Bevel := TBevel.Create(Panel);
with Bevel do
begin
Parent := Panel;
Align := alLeft;
Shape := bsLeftLine;
Width := 4;
AlignWithMargins := True;
Margins.Bottom := 2;
Margins.Left := 6;
Margins.Top := 2;
end;
end;
end;
Dec(i);
end;
end;
//Toolbar.AutoSize := False;
//Panel.AutoSize := False;
end;
ToolbarPanel.Visible := True;
end
finally
Free;
ToolBarItems.Free;
end;
end;
end.
|
program HSI; { by Bret Mulvey }
{ illustrates conversion of Hue-Saturation-Intensity to Red-Green-Blue }
uses
Crt,VGA256;
procedure hsi2rgb(h,s,i: real; var C: ColorValue);
var
t: real;
rv,gv,bv: real;
begin { procedure hsi2rgb }
t:=2*pi*h;
rv:=1+s*sin(t-2*pi/3);
gv:=1+s*sin(t);
bv:=1+s*sin(t+2*pi/3);
t:=63.999*i/2;
C.Rvalue:=trunc(rv*t);
C.Gvalue:=trunc(gv*t);
C.Bvalue:=trunc(bv*t);
end; { procedure hsi2rgb }
var
h,s,i: real;
x,y,z: integer;
C: ColorValue;
p: vgaPaletteType;
ch: char;
xx,yy: integer;
ii,jj: integer;
K: integer;
t: Real;
begin
{ create grey scale }
for z:=0 to 15 do with p[z] do begin Rvalue:=z*4; Gvalue:=z*4; Bvalue:=z*4; end;
{ create HSI spectrum }
for x:=0 to 3 do { four different intensities }
for y:=0 to 2 do { three different saturations }
for z:=0 to 19 do { twenty different hues }
begin
{ determine H,S,I between 0 and 1 }
h:=z/20;
s:=(y+1)/3;
i:=(x+1)/4;
{ calculate and store R,G,B values }
hsi2rgb(h,s,i,C);
p[16+z+20*y+60*x]:=C;
end;
InitVGA256;
vgaSetAllPalette(p);
{ draw grey scale }
for x:=0 to 15 do
begin
xx:=200; yy:=x*8;
for ii:=0 to 7 do
for jj:=0 to 7 do
vgaPutPixel(xx+ii,yy+jj,15-x);
end;
{ draw spectrum }
for z:=0 to 19 do
for x:=0 to 3 do
for y:=0 to 2 do
begin
K:=16+z+20*y+60*x;
xx:=8*x+40*(z mod 5);
yy:=8*y+32*(z div 5);
for ii:=0 to 7 do
for jj:=0 to 7 do
vgaPutPixel(xx+ii,yy+jj,K);
end;
ch:=ReadKey; if ch=#0 then ch:=ReadKey;
CloseVGA256;
end. |
unit UfcNLDIBGeneratorIBX;
interface
uses
SysUtils, Classes, IBDatabase, IBQuery;
type
TNLDIBGeneratorIBX = class (TComponent)
private
FGenerator: string;
FIBDatabase: TIBDatabase;
FQuery: TIBQuery;
FTransaction: TIBTransaction;
function GetCurrentValue: LongInt;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetValue(StepSize: integer): LongInt;
property CurrentValue: LongInt read GetCurrentValue;
published
property Generator: string read FGenerator write FGenerator;
property IBDatabase: TIBDatabase read FIBDatabase write FIBDatabase;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NLDelphi', [TNLDIBGeneratorIBX]);
end;
{
****************************** TNLDIBGeneratorIBX ******************************
}
constructor TNLDIBGeneratorIBX.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FQuery:=TIBQuery.Create(nil);
FTransaction:=TIBTransaction.Create(nil);
end;
destructor TNLDIBGeneratorIBX.Destroy;
begin
FreeAndNil(FQuery);
FreeAndNil(FTransaction);
inherited Destroy;
end;
function TNLDIBGeneratorIBX.GetCurrentValue: LongInt;
begin
result:=GetValue(0);
end;
function TNLDIBGeneratorIBX.GetValue(StepSize: integer): LongInt;
begin
with FQuery do
begin
try
Close;
IBDatabase:=FIBDatabase;
Transaction:=FTransaction;
FTransaction.DefaultDatabase:=FIBDatabase;
SQL.Text:=Format('select GEN_ID(%s,%d) as ID from RDB$DATABASE',[FGenerator,StepSize]);
Open;
First;
Result:=FieldByName('ID').AsInteger;
Close;
except
raise Exception.create('Failed to retrieve generator value');
end;
end;
end;
end.
|
{
SCRSAV.PAS - A ScreenSaving unit (version 5) for TurboVision 2.0
This ScreenSaving-unit for TurboVision 2.0 is (c) by Edwin Groothuis
You are allowed to use this unit in your programs if you agree to
these two rules:
1. You give me proper credit in the documentation of the program.
2. You tell me you're using this unit.
If you don't agree with these two rules, you're not allowed to
use it!
How to use this ScreenSaving-unit:
Initialisation:
- Add the ScrSav-unit to the uses-command.
- Make the (global) variable ScreenSaver as PScreenSaver
- In the Initialisation of an Application, put the following
line behind the Inherited Init:
Inherited Init;
ScreenSaver:=New(PScreenSaver,Init(0,1));
The zero means ScreenSaver #0 and the one means that the timeout
time is 1 minute.
Heartbeat:
To tell the ScreenSaver that the user isn't idle at this moment,
put the following line in the Application^.GetEvent:
Inherited GetEvent(E);
if E.What<>evNothing then
if ScreenSaver<>nil then
if E.What=evKeyDown then
begin
if ScreenSaver^.Saving then
E.What:=evNothing;
ScreenSaver^.HeartBeat;
end else
if E.What and evMouse<>0 then
ScreenSaver^.HeartBeat;
CountDown:
To let the ScreenSaver know the user is idle at this moment, put
the following line in the Application^.Idle:
Inherited Idle;
if ScreenSaver<>nil then
ScreenSaver^.CountDown;
Options:
What is a ScreenSaver without options? You can change the
options by calling the ScreenSaver^.Options-procedure. The user
gets a nice options-dialog and he can change some settings. If
you have added more ScreenSaver-modules, please add them in the
constants ScreenSaverNames and ScreenSaverProcs. Make sure you
put them in alphabetic order!
Now start your application. After 60 seconds your screen will
go blank. There are several ScreenSavers designed by me, if
you have created more, I would like to have a copy of them ;-)
A small note about the use of a delay in the ScreenSaver^.Update:
It's not nice to use the Delay-function of the Crt-unit. Instead
of using that, you'd better check if a certain time (100 ms, 200 ms
and so on) has elapsed. See the StarFieldScreenSaver.Update-function
for an example of it.
Send all your suggestions/money/cards (I love to get cards from
people who are using my programs) to:
Edwin Groothuis ECA-BBS
Johann Strausslaan 1 tel. +31-40-550352 (up to 14k4/V42b)
5583ZA Aalst-Waalre FTN: 2:284/205@fidonet
The Netherlands 115:3145/102@pascal-net
request SCRSAV for the last version!
}
{$define WORM}
{$define MESSAGE}
{$define STANDARD}
{$define MOVINGSTAR}
{$define STARFIELD}
unit ScrSav;
interface
uses Views,Objects,Crt;
type PScreenSaver=^TScreenSaver;
TScreenSaver=object(TObject)
constructor Init(SaverNumber:Word;Time:word);
Constructor Load(Var S:TStream);
destructor Done; Virtual;
procedure Activate;
procedure Deactivate;
procedure HeartBeat;
procedure CountDown;
procedure Update;virtual;
function Saving:boolean;
procedure Options;
procedure Enable(b:boolean);
Procedure Store(Var S:TStream); Virtual;
private
SaverNo:Word;
W:PView;
LastBeat:longint;
_Saving:boolean;
SavingTime:word;
WasEnabled,
Enabled:boolean;
Testing:boolean;
end;
type PStandardScreenSaver=^TStandardScreenSaver;
TStandardScreenSaver=object(TView)
constructor Init;
procedure Draw;virtual;
end;
Const
RScreenSaver: TStreamRec = (
ObjType: 23114;
VmtLink: Ofs(TypeOf(TScreenSaver)^);
Load: @TScreenSaver.Load;
Store: @TScreenSaver.Store);
Procedure RegisterScreenSaver;
{$ifdef WORM}
function MakeWormScreenSaver :PStandardScreenSaver;
{$endif}
{$ifdef MESSAGE}
function MakeMessageScreenSaver :PStandardScreenSaver;
{$endif}
{$ifdef MOVINGSTAR}
function MakeMovingStarScreenSaver:PStandardScreenSaver;
{$endif}
{$ifdef STARFIELD}
function MakeStarFieldScreenSaver :PStandardScreenSaver;
{$endif}
{$ifdef STANDARD}
function MakeStandardScreenSaver :PStandardScreenSaver;
{$endif}
implementation
uses Drivers,App,Dialogs,InpLong,MsgBox;
const NumScreenSavers=
{$ifdef WORM}
1+
{$endif}
{$ifdef MESSAGE}
1+
{$endif}
{$ifdef MOVINGSTAR}
1+
{$endif}
{$ifdef STARFIELD}
1+
{$endif}
{$ifdef STANDARD}
1+
{$endif}
0;
{ Please note that the names of the screensaver must be in alphabetical
order. This is because a TStringCollection is a derivative of a
TSortedCollection. }
const ScreenSaverNames:array[0..NumScreenSavers] of string[20]=
(
{$ifdef MESSAGE}
'Message',
{$endif}
{$ifdef MOVINGSTAR}
'Moving Star',
{$endif}
{$ifdef STANDARD}
'Standard',
{$endif}
{$ifdef STARFIELD}
'Starfield',
{$endif}
{$ifdef WORM}
'Worm',
{$endif}
''
);
ScreenSaverProcs:array[0..NumScreenSavers] of function:
PStandardScreenSaver=(
{$ifdef MESSAGE}
MakeMessageScreenSaver,
{$endif}
{$ifdef MOVINGSTAR}
MakeMovingStarScreenSaver,
{$endif}
{$ifdef STANDARD}
MakeStandardScreenSaver,
{$endif}
{$ifdef STARFIELD}
MakeStarfieldScreenSaver,
{$endif}
{$ifdef WORM}
MakeWormScreenSaver,
{$endif}
nil);
const cmTest=1000;
wdUp =0;
wdUpRight=1;
wdRight=2;
wdDownRight=3;
wdDown=4;
wdDownLeft=5;
wdLeft=6;
wdUpLeft=7;
{----------------------------------------------------------------------------}
{ Object-definitions of the screensave-routines. Note that these are not the
screensaverobject! }
{$ifdef MOVINGSTAR}
type PMovingStarScreenSaver=^TMovingStarScreenSaver;
TMovingStarScreenSaver=object(TStandardScreenSaver)
constructor Init;
procedure Draw;virtual;
private
dx,dy,x,y:array[1..10] of integer;
LastUpdate:longint;
end;
{$endif}
{$ifdef WORM}
PWormScreenSaver=^TWormScreenSaver;
TWormScreenSaver=object(TStandardScreenSaver)
constructor Init;
procedure Draw;virtual;
private
LastUpdate:longint;
Display:Array[1..40,1..25] Of Byte;
X,Y:Byte;
Direction:Byte;
end;
{$endif}
{$ifdef STARFIELD}
PStarFieldScreenSaver=^TStarFieldScreenSaver;
TStarFieldScreenSaver=object(TStandardScreenSaver)
constructor Init;
procedure Draw;virtual;
private
states:array[1..7] of char;
starstate,x,y:array[1..10] of integer;
LastUpdate:longint;
end;
{$endif}
{$ifdef MESSAGE}
PMessageScreenSaver=^TMessageScreenSaver;
TMessageScreenSaver=object(TStandardScreenSaver)
constructor Init;
procedure Draw;virtual;
procedure SetMessage(Var s:string);
private
Message:string;
X,Y:integer;
LastUpdate:longInt;
Colour:byte;
end;
{$endif}
{----------------------------------------------------------------------------}
{ Object-definition of the screensaver }
type PScrSavDialog=^TScrSavDialog;
TScrSavDialog=object(TDialog)
UserSavingTime:PInputLine;
LB:PListBox;
TestButton:PButton;
Timer:PRadioButtons;
procedure HandleEvent(var E:TEvent);virtual;
end;
var CurrentScreenSaver:PScreenSaver;
{----------------------------------------------------------------------------}
{----------------------------------------------------------------------------}
{ Initialise the ScreenSaver.
Notes:
*18.2 is because the timertick goes 18.2 times/second }
constructor TScreenSaver.Init(SaverNumber:Word;Time:word);
begin
Inherited Init;
_Saving:=false;
SavingTime:=round(Time*60*18.2);
HeartBeat;
W:=ScreenSaverProcs[SaverNumber];
Enabled:=true;
Testing:=false;
CurrentScreenSaver:=@Self;
SaverNo:=SaverNumber;
end;
{----------------------------------------------------------------------------}
{ Disposes the ScreenSaver }
destructor TScreenSaver.Done;
begin
if W<>nil then
Dispose(W,Done);
CurrentScreenSaver:=nil;
end;
{----------------------------------------------------------------------------}
{ Activate the ScreenSaver
First, allocate the memory for the Screen.
Second, copy the contents of the screen to the allocated memory. }
procedure TScreenSaver.Activate;
begin
if Enabled then
begin
_Saving:=true;
HideMouse;
Asm { hide cursor. It is automaticly unhidden by TurboVision }
Mov Ah,1
Mov CX,100h
Int 010H
End;
if W<>nil then
Application^.Insert(W);
Update;
end;
end;
{----------------------------------------------------------------------------}
{ Deactivate the ScreenSaver.
Second, dispose the memory allocated
Third, give the application a Redraw }
procedure TScreenSaver.Deactivate;
begin
if W<>nil then
Application^.Delete(W);
Application^.Redraw;
_Saving:=false;
if Testing then
begin
Testing:=false;
Enabled:=WasEnabled;
end;
ShowMouse;
end;
{----------------------------------------------------------------------------}
{ The use is doing something, so stop the CountDown
First, deactivate the ScreenSaver if Saving
Second, update the timer }
procedure TScreenSaver.HeartBeat;
var TT:longint absolute $40:$6c;
begin
if Saving then
Deactivate;
LastBeat:=TT;
end;
{----------------------------------------------------------------------------}
{ CountDown to the SavingTime
If not yet saving, look if it's time to save. If saving, update the screen }
procedure TScreenSaver.CountDown;
var TT:longint absolute $40:$6c;
begin
if not Saving then
begin
if (TT-LastBeat>SavingTime) then
Activate;
end else
Update;
end;
{----------------------------------------------------------------------------}
{ Update
Update the ScreenSaving-procedure. Override this one if you want a custom
ScreenSaver }
procedure TScreenSaver.Update;
begin
if Enabled then
if W<>nil then
W^.Draw;
end;
{----------------------------------------------------------------------------}
{ Saving
Returns true if the Screen is being Saved. }
function TScreenSaver.Saving:boolean;
begin
Saving:=_Saving;
end;
{----------------------------------------------------------------------------}
{ Read & Write the ScreenSaver-screens
This part is added by Michael Turner (115:4401/4@PascalNet or
2:254/80@FidoNet)
Thanks Micheal! }
constructor TScreenSaver.Load;
begin
S.Read(SaverNo,SizeOf(SaverNo));
S.Read(Enabled,SizeOf(Enabled));
S.Read(SavingTime,SizeOf(SavingTime));
_Saving:=False;
HeartBeat;
W:=ScreenSaverProcs[SaverNo];
Testing:=False;
CurrentScreenSaver:=@Self;
end;
procedure TScreenSaver.Store;
begin
S.Write(SaverNo,SizeOf(SaverNo));
S.Write(Enabled,SizeOf(Enabled));
S.Write(SavingTime,SizeOf(SavingTime));
end;
{----------------------------------------------------------------------------}
{----------------------------------------------------------------------------}
{ Handles the events for the options-dialog. The only exception that is
really handled by this procedure is the command cmTest: Test the
screensaver }
procedure TScrSavDialog.HandleEvent(var E:TEvent);
var V:longint;
W:Word;
begin
if E.What<>evNothing then
begin
if Timer^.State and sfFocused<>0 then
begin
Inherited HandleEvent(E);
Timer^.GetData(w);
UserSavingTime^.SetState(sfDisabled,false);
if W<>6 then
begin
case W of
0: v:=60;
1: v:=120;
2: v:=180;
3: v:=300;
4: v:=600;
5: v:=900;
end;
UserSavingTime^.SetData(v);
UserSavingTime^.Draw;
UserSavingTime^.SetState(sfDisabled,true);
end;
end;
if E.What=evCommand then
if E.Command=cmTest then
begin
MessageBox(ScreenSaverNames[LB^.Focused],nil,mfOkButton);
Dispose(CurrentScreenSaver^.W,Done);
CurrentScreenSaver^.W:=ScreenSaverProcs[LB^.Focused];
CurrentScreenSaver^.WasEnabled:=CurrentScreenSaver^.Enabled;
CurrentScreenSaver^.Enabled:=true;
CurrentScreenSaver^.Testing:=true;
CurrentScreenSaver^.Activate;
end;
end;
Inherited HandleEvent(E);
end;
{----------------------------------------------------------------------------}
{ Options
Pops up a dialogbox with several functions, like enable/disable, time to
save, which screensaver etc }
procedure TScreenSaver.Options;
function MakeDialog : PScrSavDialog;
var Dlg : PScrSavDialog;
R : TRect;
Control : PView;
begin
R.Assign(4, 1, 49, 16);
New(Dlg, Init(R, 'Screen Saver'));
Dlg^.Options:=Dlg^.Options or ofCentered;
R.Assign(2, 3, 20, 10);
Dlg^.Timer := New(PRadioButtons, Init(R,
NewSItem('1 minute',NewSItem('2 minutes',
NewSItem('3 minutes',NewSItem('5 minutes',
NewSItem('10 minutes',NewSItem('15 minutes',
NewSItem('user defined', Nil)))))))));
Dlg^.Insert(Dlg^.Timer);
R.Assign(1, 2, 13, 3);
Dlg^.Insert(New(PLabel, Init(R, 'Saving time', Control)));
R.Assign(6, 10, 20, 11);
Dlg^.UserSavingTime := New(PInputLong, Init(R, 12, 0, 3600, 0));
Dlg^.Insert(Dlg^.UserSavingTime);
R.Assign(42, 3, 43, 7);
Control := New(PScrollBar, Init(R));
Dlg^.Insert(Control);
R.Assign(22, 3, 42, 7);
Dlg^.LB:= New(PListBox, Init(R, 1, PScrollbar(Control)));
Dlg^.Insert(Dlg^.LB);
R.Assign(21, 2, 33, 3);
Dlg^.Insert(New(PLabel, Init(R, 'Which saver', Control)));
R.Assign(22, 8, 42, 10);
Control := New(PRadioButtons, Init(R,
NewSItem('Enable saver',NewSItem('Disable saver', Nil))));
Dlg^.Insert(Control);
R.Assign(3, 12, 13, 14);
Dlg^.Insert(New(PButton, Init(R, 'O~K~', cmOK, bfDefault)));
R.Assign(17, 12, 27, 14);
Dlg^.Insert(New(PButton, Init(R, 'Cancel', cmCancel, bfNormal)));
R.Assign(32, 12, 42, 14);
Dlg^.TestButton := New(PButton, Init(R, 'Test', cmTest, bfNormal));
Dlg^.Insert(Dlg^.TestButton);
Dlg^.SelectNext(False);
MakeDialog := Dlg;
end;
type TListBoxRec = record {<-- omit if TListBoxRec is defined elsewhere}
PS : PStringCollection;
Selection : Integer;
end;
var d:PScrSavDialog;
DataRec : record
SavingTime : Word;
UserSavingTime : LongInt;
WhichSaver : TListBoxRec;
Enabled : Word;
end;
s:string;
i:word;
Changed:Boolean;
begin
d:=MakeDialog;
DataRec.SavingTime:=6;
DataRec.UserSavingTime:=round(SavingTime/(60*18.2));
if Enabled then
DataRec.Enabled:=0
else
DataRec.Enabled:=1;
d^.UserSavingTime^.SetState(sfDisabled,true);
DataRec.WhichSaver.PS:=New(PStringCollection,Init(5,5));
for i:=0 to NumScreenSavers-1 do
DataRec.WhichSaver.PS^.Insert(NewStr(ScreenSaverNames[i]));
DataRec.WhichSaver.Selection:=0;
d^.SetData(DataRec);
d^.LB^.Draw;
D^.LB^.FocusItem(SaverNo);
if (SavingTime Shr 10)=0 Then
begin
SavingTime:=SavingTime Or 1024;
Changed:=True;
end else
Changed:=False;
if (desktop^.execview(d))=cmOk then
begin
d^.GetData(DataRec);
SaverNo:=D^.LB^.Focused;
SavingTime:=round(DataRec.UserSavingTime*60*18.2);
Enabled:=DataRec.Enabled=0;
Dispose(CurrentScreenSaver^.W,Done);
CurrentScreenSaver^.W:=ScreenSaverProcs[d^.LB^.Focused];
end else begin
if Changed then
SavingTime:=SavingTime and 255;
Dispose(CurrentScreenSaver^.W,Done);
CurrentScreenSaver^.W:=ScreenSaverProcs[SaverNo];
end;
dispose(DataRec.WhichSaver.PS,Done);
dispose(d,done);
end;
{----------------------------------------------------------------------------}
{ Enable or disable the screensaver }
procedure TScreenSaver.Enable(b:boolean);
begin
if b then
Enabled:=true
else
Enabled:=false;
end;
{$ifdef STANDARD}
{----------------------------------------------------------------------------}
{----------------------------------------------------------------------------}
function MakeStandardScreenSaver:PStandardScreenSaver;
var S:PStandardScreenSaver;
begin
S:=new(PStandardScreenSaver,Init);
MakeStandardScreenSaver:=S;
end;
{----------------------------------------------------------------------------}
constructor TStandardScreenSaver.Init;
var R:TRect;
begin
Application^.GetExtent(R);
Inherited Init(R);
end;
{----------------------------------------------------------------------------}
procedure TStandardScreenSaver.Draw;
begin
ClearScreen;
end;
{$endif}
{$ifdef MOVINGSTAR}
{----------------------------------------------------------------------------}
{ The rest are examples of different ScreenSavers. }
{----------------------------------------------------------------------------}
{----------------------------------------------------------------------------}
function MakeMovingStarScreenSaver:PStandardScreenSaver;
var S:PMovingStarScreenSaver;
begin
S:=new(PMovingStarScreenSaver,Init);
MakeMovingStarScreenSaver:=S;
end;
{----------------------------------------------------------------------------}
constructor TMovingStarScreenSaver.Init;
var i:byte;
begin
Inherited Init;
Randomize;
for i:=1 to 10 do
begin
x[i]:=random(ScreenWidth div 2)+(ScreenWidth div 4);
y[i]:=random(ScreenHeight div 2)+(ScreenHeight div 4);
dx[i]:=random(2);if dx[i]=0 then dx[i]:=-1;
dy[i]:=random(2);if dy[i]=0 then dy[i]:=-1;
end;
end;
{----------------------------------------------------------------------------}
procedure TMovingStarScreenSaver.Draw;
var i:byte;
TT:longint absolute $40:$6c;
B:TDrawBuffer;
begin
if TT-LastUpdate>2 then
begin
LastUpdate:=TT;
ClearScreen;
for i:=1 to 10 do
begin
if x[i] in [0,ScreenWidth-3] then dx[i]:=-dx[i];
if y[i] in [0,ScreenHeight-3] then dy[i]:=-dy[i];
inc(x[i],dx[i]);inc(y[i],dy[i]);
MoveChar(B,'*',i,1);
WriteLine(x[i],y[i],1,1,B);
end;
end;
end;
{$endif}
{$ifdef WORM}
{----------------------------------------------------------------------------}
{----------------------------------------------------------------------------}
function MakeWormScreenSaver:PStandardScreenSaver;
var S:PWormScreenSaver;
begin
S:=new(PWormScreenSaver,Init);
MakeWormScreenSaver:=S;
end;
{----------------------------------------------------------------------------}
constructor TWormScreenSaver.Init;
begin
Inherited Init;
FillChar(Display,SizeOf(Display),0);
Randomize;
Direction:=Random(8);
X:=20;
Y:=13;
end;
{----------------------------------------------------------------------------}
procedure TWormScreenSaver.Draw;
const States : Array [0..8] Of Char =
(' ','°','°','±','±','²','²','Û','Û');
var TT:longint absolute $40:$6c;
procedure Cycle;
var AX,AY:byte;
begin
for AX:=1 to 40 do
for AY:=1 to 25 do
if Display[AX,AY]>0 then Dec(Display[AX,AY]);
end;
procedure PutNewHead;
procedure UpdateHead;
begin
case Direction of
wdUp : Dec(X);
wdUpRight : begin Dec(X);Inc(Y);end;
wdRight : Inc(Y);
wdDownRight: begin Inc(X);Inc(Y);end;
wdDown : Inc(X);
wdDownLeft : begin Inc(X);Dec(Y);end;
wdLeft : Dec(Y);
wdUpLeft : begin Dec(X);Dec(Y);end;
end;
end;
var StoreX,StoreY:byte;
DOK:boolean;
StoreDirection:byte;
begin
if (Y=1) or (X=1) or (Y=25) or (X=40) or (random(100)<5) then
begin
StoreX:=X;
StoreY:=Y;
StoreDirection:=Direction;
repeat
X:=StoreX;
Y:=StoreY;
Direction:=random(8);
case StoreDirection of
wdUp : DOK:=Direction<>wdDown;
wdUpRight : DOK:=Direction<>wdDownLeft;
wdRight : DOK:=Direction<>wdLeft;
wdDownRight : DOK:=Direction<>wdUpLeft;
wdDown : DOK:=Direction<>wdUp;
wdDownLeft : DOK:=Direction<>wdUpRight;
wdLeft : DOK:=Direction<>wdRight;
wdUpLeft : DOK:=Direction=wdDownRight;
end;
UpdateHead;
until (Y<>0) and (X<>0) and (Y<>26) and (X<>41) and DOK;
end else
UpdateHead;
Display[X,Y]:=8;
end;
procedure UpdateDisplay;
var D:TDrawBuffer;
AX,AY:byte;
begin
if ScreenHeight=43 then
ClearScreen;
for AY:=0 to 24 do
begin
for AX:=0 to 39 do
begin
D[AX*2]:=Word(Ord(States[Display[Succ(AX),Succ(AY)]])) Or ($100);
D[Succ(AX*2)]:=D[AX*2];
end;
if ScreenHeight<>50 then
WriteLine(0,AY,ScreenWidth,1,D)
else
WriteLine(0,AY*2,ScreenWidth,2,D);
end;
end;
begin
if TT-LastUpdate>2 then
begin
LastUpdate:=TT;
Cycle;
PutNewHead;
UpdateDisplay;
end;
end;
{$endif}
{$ifdef STARFIELD}
{----------------------------------------------------------------------------}
{----------------------------------------------------------------------------}
function MakeStarfieldScreenSaver:PStandardScreenSaver;
var S:PStarFieldScreenSaver;
begin
S:=new(PStarFieldScreenSaver,Init);
MakeStarfieldScreenSaver:=S;
end;
{----------------------------------------------------------------------------}
constructor TStarFieldScreenSaver.Init;
var i:byte;
R:TRect;
begin
Inherited Init;
Randomize;
States[1]:='ú';States[2]:='ù';States[3]:='';
States[4]:='o';States[5]:='*';States[6]:='';States[7]:=' ';
for i:=1 to 10 do
begin
x[i]:=random(ScreenWidth-1)+2;
y[i]:=random(ScreenHeight-1)+2;
starstate[i]:=random(7)+1;
end;
end;
{----------------------------------------------------------------------------}
procedure TStarFieldScreenSaver.Draw;
var i:byte;
TT:longint absolute $40:$6c;
B:TDrawBuffer;
begin
if TT-LastUpdate>2 then
begin
LastUpdate:=TT;
ClearScreen;
for i:=1 to 10 do
begin
MoveChar(B,States[StarState[i]],i,1);
WriteLine(x[i],y[i],1,1,B);
StarState[i]:=(StarState[i] mod 7)+1;
if StarState[i]=1 then
begin
x[i]:=random(ScreenWidth)+1;
y[i]:=random(ScreenHeight)+1;
end;
end;
end;
end;
{$endif}
{$ifdef MESSAGE}
{----------------------------------------------------------------------------
This part is added by Michael Turner (115:4401/4@PascalNet or
2:254/80@FidoNet)
Thanks Micheal!
{----------------------------------------------------------------------------}
function MakeMessageScreenSaver:PStandardScreenSaver;
var S:PMessageScreenSaver;
begin
S:=New(PMessageScreenSaver,Init);
MakeMessageScreenSaver:=S;
end;
constructor TMessageScreenSaver.Init;
begin
inherited Init;
randomize;
X:=ScreenWidth;
Y:=Random(23);
Message:='The screen is being saved. Press nearly any key or move the mouse to continue';
{This string must not be longer than the screen width}
Colour:=LightGreen;
end;
procedure TMessageScreenSaver.Draw;
var TT:longint absolute $40:$6c;
B:TDrawBuffer;
begin
if TT-LastUpdate>2 then
begin
LastUpdate:=TT;
ClearScreen;
if (Length(Message+' ')+X)>ScreenWidth then
begin
MoveStr(B,Copy(Message+' ',1,ScreenWidth-X),Colour);
WriteLine(X,Y,ScreenWidth-X,1,B);
end else
if X<0 then
begin
MoveStr(B,Copy(Message+' ',Abs(X),Length(Message+' ')-Abs(X)),Colour);
WriteLine(0,Y,Length(Message+' ')-Abs(X),1,B);
end else begin
MoveStr(B,Message+' ',Colour);
WriteLine(X,Y,Length(Message+' '),1,B);
end;
Dec(X);
if (X<0) and (Abs(X)>Length(Message+' ')) then
begin
X:=ScreenWidth;
Y:=Random(23);
end;
end;
end;
procedure TMessageScreenSaver.SetMessage;
begin
if Length(S)>76 then
S[0]:=Chr(76);
Message:=S;
end;
{$endif}
procedure RegisterScreenSaver;
begin
RegisterType(RScreenSaver);
end;
begin
CurrentScreenSaver:=nil;
end.
|
{******************************************************************************}
{* DCPcrypt v2.0 written by David Barton (crypto@cityinthesky.co.uk) **********}
{******************************************************************************}
{* A binary compatible implementation of RC5 **********************************}
{******************************************************************************}
{* Copyright (c) 1999-2002 David Barton *}
{* Permission is hereby granted, free of charge, to any person obtaining a *}
{* copy of this software and associated documentation files (the "Software"), *}
{* to deal in the Software without restriction, including without limitation *}
{* the rights to use, copy, modify, merge, publish, distribute, sublicense, *}
{* and/or sell copies of the Software, and to permit persons to whom the *}
{* Software is furnished to do so, subject to the following conditions: *}
{* *}
{* The above copyright notice and this permission notice shall be included in *}
{* all copies or substantial portions of the Software. *}
{* *}
{* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *}
{* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *}
{* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *}
{* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *}
{* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *}
{* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *}
{* DEALINGS IN THE SOFTWARE. *}
{******************************************************************************}
unit DCPrc5;
interface
uses
Classes, Sysutils, DCPcrypt2, DCPconst, DCPblockciphers;
const
NUMROUNDS= 12; { number of rounds must be between 12-16 }
type
TDCP_rc5= class(TDCP_blockcipher64)
protected
KeyData: array[0..((NUMROUNDS*2)+1)] of DWord;
procedure InitKey(const Key; Size: longword); override;
public
class function GetId: integer; override;
class function GetAlgorithm: string; override;
class function GetMaxKeySize: integer; override;
class function SelfTest: boolean; override;
procedure Burn; override;
procedure EncryptECB(const InData; var OutData); override;
procedure DecryptECB(const InData; var OutData); override;
end;
{******************************************************************************}
{******************************************************************************}
implementation
{$R-}{$Q-}
const
sBox: array[0..33] of dword= (
$B7E15163,$5618CB1C,$F45044D5,$9287BE8E,$30BF3847,$CEF6B200,
$6D2E2BB9,$0B65A572,$A99D1F2B,$47D498E4,$E60C129D,$84438C56,
$227B060F,$C0B27FC8,$5EE9F981,$FD21733A,$9B58ECF3,$399066AC,
$D7C7E065,$75FF5A1E,$1436D3D7,$B26E4D90,$50A5C749,$EEDD4102,
$8D14BABB,$2B4C3474,$C983AE2D,$67BB27E6,$05F2A19F,$A42A1B58,
$42619511,$E0990ECA,$7ED08883,$1D08023C);
function LRot32(a, b: longword): longword;
begin
Result:= (a shl b) or (a shr (32-b));
end;
function RRot32(a, b: longword): longword;
begin
Result:= (a shr b) or (a shl (32-b));
end;
class function TDCP_rc5.GetID: integer;
begin
Result:= DCP_rc5;
end;
class function TDCP_rc5.GetAlgorithm: string;
begin
Result:= 'RC5';
end;
class function TDCP_rc5.GetMaxKeySize: integer;
begin
Result:= 2048;
end;
class function TDCP_rc5.SelfTest: boolean;
const
Key1: array[0..15] of byte=
($DC,$49,$DB,$13,$75,$A5,$58,$4F,$64,$85,$B4,$13,$B5,$F1,$2B,$AF);
Plain1: array[0..1] of dword=
($B7B3422F,$92FC6903);
Cipher1: array[0..1] of dword=
($B278C165,$CC97D184);
Key2: array[0..15] of byte=
($52,$69,$F1,$49,$D4,$1B,$A0,$15,$24,$97,$57,$4D,$7F,$15,$31,$25);
Plain2: array[0..1] of dword=
($B278C165,$CC97D184);
Cipher2: array[0..1] of dword=
($15E444EB,$249831DA);
var
Cipher: TDCP_rc5;
Data: array[0..1] of dword;
begin
Cipher:= TDCP_rc5.Create(nil);
Cipher.Init(Key1,Sizeof(Key1)*8,nil);
Cipher.EncryptECB(Plain1,Data);
Result:= boolean(CompareMem(@Data,@Cipher1,Sizeof(Data)));
Cipher.DecryptECB(Data,Data);
Result:= Result and boolean(CompareMem(@Data,@Plain1,Sizeof(Data)));
Cipher.Burn;
Cipher.Init(Key2,Sizeof(Key2)*8,nil);
Cipher.EncryptECB(Plain2,Data);
Result:= Result and boolean(CompareMem(@Data,@Cipher2,Sizeof(Data)));
Cipher.DecryptECB(Data,Data);
Result:= Result and boolean(CompareMem(@Data,@Plain2,Sizeof(Data)));
Cipher.Burn;
Cipher.Free;
end;
procedure TDCP_rc5.InitKey(const Key; Size: longword);
var
xKeyD: array[0..63] of DWord;
i, j, k, xKeyLen: longword;
A, B: DWord;
begin
FillChar(xKeyD,Sizeof(xKeyD),0);
Size:= Size div 8;
Move(Key,xKeyD,Size);
xKeyLen:= Size div 4;
if (Size mod 4)<> 0 then
Inc(xKeyLen);
Move(sBox,KeyData,(NUMROUNDS+1)*8);
i:= 0; j:= 0;
A:= 0; B:= 0;
if xKeyLen> ((NUMROUNDS+1)*2) then
k:= xKeyLen*3
else
k:= (NUMROUNDS+1)*6;
for k:= k downto 1 do
begin
A:= LRot32(KeyData[i]+A+B,3);
KeyData[i]:= A;
B:= LRot32(xKeyD[j]+A+B,A+B);
xKeyD[j]:= B;
i:= (i+1) mod ((NUMROUNDS+1)*2);
j:= (j+1) mod xKeyLen;
end;
FillChar(xKeyD,Sizeof(xKeyD),0);
end;
procedure TDCP_rc5.Burn;
begin
FillChar(KeyData,Sizeof(KeyData),$FF);
inherited Burn;
end;
procedure TDCP_rc5.EncryptECB(const InData; var OutData);
var
A, B: DWord;
i: longword;
begin
if not fInitialized then
raise EDCP_blockcipher.Create('Cipher not initialized');
A:= PDword(@InData)^ + KeyData[0];
B:= PDword(longword(@InData)+4)^ + KeyData[1];
for i:= 1 to NUMROUNDS do
begin
A:= A xor B;
A:= LRot32(A,B)+KeyData[2*i];
B:= B xor A;
B:= LRot32(B,A)+KeyData[(2*i)+1];
end;
PDword(@OutData)^:= A;
PDword(longword(@OutData)+4)^:= B;
end;
procedure TDCP_rc5.DecryptECB(const InData; var OutData);
var
A, B: DWord;
i: longword;
begin
if not fInitialized then
raise EDCP_blockcipher.Create('Cipher not initialized');
A:= PDword(@InData)^;
B:= PDword(longword(@InData)+4)^;
for i:= NUMROUNDS downto 1 do
begin
B:= RRot32(B-KeyData[(2*i)+1],A);
B:= B xor A;
A:= RRot32(A-KeyData[2*i],B);
A:= A xor B;
end;
PDword(@OutData)^:= A - KeyData[0];
PDword(longword(@OutData)+4)^:= B - KeyData[1];
end;
end.
|
PROGRAM tiendaURJC;
CONST
NCTIPO = 15;
NCIDENTIFICADOR = 4;
MAXPC = 25;
MAXCOMPONENTES = 100;
MIN = 1;
TYPE
tTipo = string[NCTIPO];
tIdentificador = string[NCIDENTIFICADOR];
tNumComponentes = MIN..MAXCOMPONENTES;
tNumPc = MIN..MAXPC;
tComponente = RECORD
tipo: tTipo;
id: tIdentificador;
descripcion: string;
precio : real;
END;
tPc = RECORD
datos, memoria, procesador, discoDuro: tComponente;
END;
tListaComponentes= ARRAY [tNumComponentes] OF tComponente;
tListaPcs = ARRAY [tNumPc] OF tPc;
tAlmacenComponentes = RECORD
listaComponentes : tListaComponentes;
tope: integer;
END;
tAlmacenPcs = RECORD
listaPcs : tListaPcs;
tope: integer;
END;
tTienda = RECORD
almacenPcs : tAlmacenPcs;
almacenComponentes: tAlmacenComponentes;
ventasTotales: real;
END;
tFicheroPcs = FILE OF tPc;
tFicheroComponentes = FILE OF tComponente;
{-----------------------------------------Aqui empiezan los subprogramas de Daniel----------------------------------------}
PROCEDURE mostrarPc (pc:tPc);
BEGIN
WITH pc DO BEGIN
writeln('identificador del pc:');
writeln(datos.id);
writeln('Descripcion del pc:');
writeln(datos.descripcion);
writeln('Precio del pc');
writeln(datos.precio:0:2);
END;
END;
FUNCTION posicionPc(almaPc:tAlmacenPcs;idenPc:tIdentificador):integer;
VAR
i:integer;
BEGIN
i:=-1;
REPEAT
i:=i+1;
UNTIL (i=(almaPc.tope)) OR ((almaPc.listaPcs[i].datos.id)=(idenPc));
IF ((almaPc.listaPcs[i].datos.id)=(idenPc))THEN
posicionPc:=i
ELSE
posicionPc:=0;
END;
PROCEDURE eliminarPc(VAR almaPc:tAlmacenPcs;idenPc:tIdentificador);
VAR
i:integer;
BEGIN
i:=posicionPc(almaPc,idenPc);
WITH almaPc DO BEGIN
listaPcs[i]:=listaPcs[tope];
tope:=tope-1;
END;
END;
PROCEDURE mostrarComp (componenteMod:tComponente);
BEGIN{mostrar}
WITH componenteMod DO BEGIN
writeln('----------------------------------------');
writeln('Identificador del componente: ',id);
writeln('Tipo del componente: ',tipo);
writeln('Descripcion del componente: ',descripcion);
writeln('Precio del componente ',precio:0:2);
writeln('----------------------------------------');
END;
END;{mostrar}
PROCEDURE mostrarComponentes (almacenComponentes: tAlmacenComponentes);
VAR
i : integer;
BEGIN
WITH almacenComponentes DO BEGIN
FOR i:= 1 TO tope DO BEGIN
writeln('Componente ', i);
mostrarComp(listaComponentes[i]);
writeln;
readln;
END;
END;
END;
PROCEDURE mostrarPcs (almaPc: tAlmacenPcs);
VAR
i : integer;
BEGIN
WITH almaPc DO BEGIN
FOR i:= 1 TO tope DO BEGIN
writeln('Pc ', i);
mostrarPc(listaPcs[i]);
writeln;
readln;
END;
END;
END;
PROCEDURE ordenarPrecios (VAR almaPc:tAlmacenPcs);
VAR
i,j,posMenor:integer;
valorMenor:real;
aux:tPc;
BEGIN
FOR i:= 1 TO almaPc.tope DO
BEGIN
valorMenor:= almaPc.listaPcs[i].datos.precio;
posMenor:=i;
FOR j:= succ(i) TO almaPc.tope DO
IF (almaPc.listaPcs[j].datos.precio < valorMenor) THEN
BEGIN
valorMenor:= almaPc.listaPcs[j].datos.precio;
posMenor:=j;
END;
IF (posMenor <> i) THEN
BEGIN
aux:=almaPc.listaPcs[posMenor];
almaPc.listaPcs[posMenor]:= almaPc.listaPcs[i];
almaPc.listaPcs[i]:= aux;
END;
END;
END;
{-----------------------------------------Aqui empiezan los subprogramas de Raul y terminan los de Garcy---------------------------}
PROCEDURE inicio(VAR tien:tTienda);
BEGIN{inicio}
WITH tien DO
BEGIN
almacenComponentes.tope:=0;
almacenPcs.tope:=0;
ventasTotales:=0;
END;
END;{inicio}
FUNCTION comprobAlmacen (almacenComp:tAlmacenComponentes):boolean;
BEGIN{comprobAlmacen}
IF almacenComp.tope = MAXCOMPONENTES THEN
comprobAlmacen:= TRUE
ELSE
comprobAlmacen:= FALSE
END;{comprobAlmacen}
PROCEDURE leerComponente( VAR comp:tComponente);
VAR
opc:char;
BEGIN{leerComp}
WITH comp DO
BEGIN
REPEAT
writeln('Seleccione el tipo de componente:');
writeln('1) Procesador.');
writeln('2) Disco duro.');
writeln('3) Memoria.');
readln(opc);
CASE opc OF
'1':tipo:='procesador';
'2':tipo:='disco duro';
'3':tipo:='memoria';
END;
UNTIL ((opc='1') OR (opc='2') OR (opc='3'));
writeln('Introduzca el identificador:');
readln(id);
writeln('Introduzca la descripcion:');
readln(descripcion);
writeln('Introduzca el precio');
readln(precio);
END;
END;{leerComp}
PROCEDURE altaComponente (comp:tComponente; VAR almacenComp:tAlmacenComponentes);
VAR
i:integer;
exi:boolean;
BEGIN{alta}
exi:=FALSE;
FOR i:=0 to almacenComp.tope DO
IF comp.id=almacenComp.listaComponentes[i].id THEN
BEGIN
writeln('El identificador ya corresponde a otro componente');
exi:=TRUE;
END;
IF NOT exi THEN
BEGIN
almacenComp.tope:=almacenComp.tope + 1;
almacenComp.listaComponentes[almacenComp.tope]:=comp;
END;
END;{alta}
PROCEDURE buscar (iden:tIdentificador;almacen:tAlmacenComponentes;VAR compo:tComponente; tip:string;VAR auxi:integer);
VAR
i:integer;
BEGIN{proce}
i:=0;
REPEAT
i:=i+1;
UNTIL(i=(almacen.tope)) OR ((almacen.listaComponentes[i].id)=(iden));
IF ((almacen.listaComponentes[i].id)=(iden)) THEN
IF almacen.listaComponentes[i].tipo=tip THEN
BEGIN
compo:=almacen.listaComponentes[i];
auxi:=1;
END
ELSE
writeln('El componente elegido no es un ',tip)
ELSE
writeln('El identificador no corresponde a un componente');
END;{proce}
PROCEDURE altaPc (ordenador:tPc; VAR almacen:tAlmacenPcs);
VAR
i:integer;
exi:boolean;
BEGIN{alta}
exi:=FALSE;
FOR i:=0 to almacen.tope DO
IF ordenador.datos.id=almacen.listaPcs[i].datos.id THEN BEGIN
exi:=TRUE;
writeln('El identificador ya corresponde a otro ordenador');
END
ELSE IF almacen.tope=MAXPC THEN BEGIN
exi:=TRUE;
writeln('El almacen de ordenadores está lleno');
END;
IF NOT exi THEN
BEGIN
almacen.tope:=almacen.tope + 1;
almacen.listaPcs[almacen.tope]:=ordenador;
END;
END;{alta}
FUNCTION posicion(almacen:tAlmacenComponentes;comp:tIdentificador):integer;
VAR
i:integer;
BEGIN{posicion}
i:=-1;
REPEAT
i:=i+1;
UNTIL (i=(almacen.tope)) OR ((almacen.listaComponentes[i].id)=(comp));
IF ((almacen.listaComponentes[i].id)=(comp))THEN
posicion:=i
ELSE
posicion:=0;
END;{posicion}
PROCEDURE eliminar(VAR almacen:tAlmacenComponentes;componente:tIdentificador);
VAR
posi:integer;
BEGIN{eliminar}
posi:=posicion(almacen,componente);
WITH almacen DO BEGIN
listaComponentes[posi]:=listaComponentes[tope];
tope:=tope-1;
END;
END;{eliminar}
PROCEDURE menuComp;
BEGIN{menu}
writeln('MENU DE MODIFICACION');
writeln('1) Modificar el tipo');
writeln('2) Modificar la descripcion');
writeln('3) Modificar el precio');
writeln('4)Finalizar modificacion');
END;{menu}
{---------------------------------Aqui acaban los subprogramas de Raul y empiezan los de Aitor-----------------------}
PROCEDURE mostrarMenu;
BEGIN
writeln('------------------------------------------------------------------------');
writeln('A) Dar de alta un componente.');
writeln('B) Configurar un ordenador.');
writeln('C) Modificar un componente.');
writeln('D) Vender un componente.');
writeln('E) Vender un ordenador.');
writeln('F) Mostrar las ventas actuales.');
writeln('G) Mostrar todos los ordenadores ordenados por precio de menor a mayor.');
writeln('H) Mostrar todos los componentes sueltos.');
writeln('I) Guardar datos en ficheros binarios.');
writeln('J) Guardar datos en ficheros de texto.');
writeln('K) Cargar datos de ficheros binarios.');
writeln('L) Cargar datos de ficheros de texto.');
writeln('M) Finalizar.');
writeln('Introduzca una opcion:');
END;
PROCEDURE guardarBin (tien:tTienda; VAR fichComp:tFicheroComponentes; VAR fichPcs:tFicheroPcs);
VAR
i:integer;
BEGIN
assign(fichComp,'componentes.dat');
rewrite(fichComp);
WITH tien DO
WITH almacenComponentes DO
FOR i:=1 TO tope DO
write(fichComp,listaComponentes[i]);
close(fichComp);
assign(fichPcs,'ordenadores.dat');
rewrite(fichPcs);
WITH tien DO
WITH almacenPcs DO
FOR i:=1 TO tope DO
write(fichPcs,listaPcs[i]);
CLOSE(fichPcs);
END;
PROCEDURE cargarBin(VAR tien:tTienda; VAR fichComp:tFicheroComponentes; VAR fichPcs:tFicheroPcs);
VAR
i,j:integer;
listaC:tListaComponentes;
listaP:tListaPcs;
BEGIN
i:=1;
j:=1;
assign (fichComp,'componentes.dat');
reset (fichComp);
WHILE NOT EOF(fichComp) DO
BEGIN
read(fichComp,listaC[i]);
i:=i+1;
END;
close(fichComp);
assign(fichPcs,'ordenadores.dat');
reset(fichPcs);
WHILE NOT EOF(fichPcs) DO
BEGIN
read(fichPcs,listaP[j]);
j:=j+1;
END;
close(fichPcs);
WITH tien DO
BEGIN
WITH almacenPcs DO
BEGIN
tope:=j-1;
listaPcs:=listaP;
END;
WITH almacenComponentes DO
BEGIN
tope:=i-1;
listaComponentes:=listaC;
END;
ventasTotales:=0;
END;
END;
PROCEDURE escribirGuardado(VAR fich:text;compo:tComponente);
BEGIN
WITH compo DO
BEGIN
writeln(fich,tipo);
writeln(fich,id);
writeln(fich,descripcion);
writeln(fich,precio);
END;
END;
PROCEDURE escribirGuardadoPc(VAR fich:text;pcc:tPc);
BEGIN
WITH pcc DO
BEGIN
escribirGuardado(fich,datos);
escribirGuardado(fich,memoria);
escribirGuardado(fich,procesador);
escribirGuardado(fich,discoDuro);
END;
END;
PROCEDURE guardarText (tien:tTienda; VAR fichComp:text; VAR fichPcs:text);
VAR
i:integer;
BEGIN
assign(fichComp,'componentes.txt');
rewrite(fichComp);
WITH tien DO
WITH almacenComponentes DO
FOR i:=1 TO tope DO
escribirGuardado(fichComp,listaComponentes[i]);
close(fichComp);
assign(fichPcs,'ordenadores.txt');
rewrite(fichPcs);
WITH tien DO
WITH almacenPcs DO
FOR i:=1 TO tope DO
escribirGuardadoPc(fichPcs,listaPcs[i]);
close(fichPcs);
END;
PROCEDURE leerCarga(VAR fich:text;VAR compo:tComponente);
BEGIN
WITH compo DO
BEGIN
readln(fich,tipo);
readln(fich,id);
readln(fich,descripcion);
readln(fich,precio);
END;
END;
PROCEDURE leerCargaPC(VAR fich:text;VAR pcc:tPc);
BEGIN
WITH pcc DO
BEGIN
leerCarga(fich,datos);
leerCarga(fich,memoria);
leerCarga(fich,procesador);
leerCarga(fich,discoDuro);
END;
END;
PROCEDURE cargarText(VAR tien:tTienda; VAR fichComp:text; VAR fichPcs:text);
VAR
i,j:integer;
listaC:tListaComponentes;
listaP:tListaPcs;
BEGIN
i:=1;
j:=1;
assign(fichComp,'componentes.txt');
reset(fichComp);
WHILE NOT EOF(fichComp) DO
BEGIN
leerCarga(fichComp,listaC[i]);
i:=i+1;
END;
close(fichComp);
assign(fichPcs,'ordenadores.txt');
reset(fichPcs);
WHILE NOT EOF(fichPcs) DO
BEGIN
leerCargaPc(fichPcs,listaP[j]);
j:=j+1;
END;
close(fichPcs);
WITH tien DO
BEGIN
WITH almacenPcs DO
BEGIN
listaPcs:=listaP;
tope:=j-1;
END;
WITH almacenComponentes DO
BEGIN
listaComponentes:=listaC;
tope:=i-1;
END;
ventasTotales:=0;
END;
END;
FUNCTION comprobarFicheros(tipo:string):boolean;
VAR
fich:text;
BEGIN
assign(fich,'componentes.'+tipo);
{$i-}
reset(fich);
{$i+}
IF (IOResult<>0) THEN
comprobarFicheros:=FALSE
ELSE
BEGIN
close(fich);
assign(fich,'ordenadores.'+tipo);
{$i-}
reset(fich);
{$i+}
IF (IOResult<>0) THEN
comprobarFicheros:=FALSE
ELSE
BEGIN
close(fich);
comprobarFicheros:=TRUE;
END;
END;
END;
{----------------------Aqui estan las VAR----------------------}
VAR
opcion,subopcion:char;
tienda:tTienda;
compBin:tFicheroComponentes;
ordBin:tFicheroPcs;
compText,ordText:text;
existe:boolean;
componente,comp:tComponente;
pc:tPc;
modComp,ide,venta:tIdentificador;
aux:integer;
{----------------------Aqui empieza el programa principal----------------------}
BEGIN
inicio(tienda);
REPEAT
mostrarMenu;
readln(opcion);
CASE opcion OF
'A','a':
BEGIN
writeln('Dar de alta un componente');
IF comprobAlmacen(tienda.almacenComponentes) = TRUE THEN
writeln('El almacen esta lleno')
ELSE
BEGIN
leerComponente(componente);
altaComponente(componente,tienda.almacenComponentes);
END;
END;
'B','b':
BEGIN
WITH pc DO BEGIN
writeln('Configurar un ordenador:');
aux:=0;
REPEAT
writeln('Introduzca un identificador de procesador');
readln(ide);
buscar(ide,tienda.almacenComponentes,comp,'procesador',aux);
UNTIL (aux=1);
procesador:=comp;
aux:=0;
REPEAT
writeln('Introduzca un identificador de disco duro');
readln(ide);
buscar(ide,tienda.almacenComponentes,comp,'disco duro',aux);
UNTIL (aux=1);
discoDuro:=comp;
aux:=0;
REPEAT
writeln('Introduzca un identificador de memoria');
readln(ide);
buscar(ide,tienda.almacenComponentes,comp,'memoria',aux);
UNTIL (aux=1);
memoria:=comp;
writeln('Introduzca un identificador para el ordenador');
readln(datos.id);
writeln('Introduzca una descripcion del ordenador');
readln(datos.descripcion);
datos.precio:= procesador.precio+discoDuro.precio+memoria.precio+10;
datos.tipo:='Ordenador';
END;{WITH}
altaPc(pc,tienda.almacenPcs);
eliminar(tienda.almacenComponentes,pc.procesador.id);
eliminar(tienda.almacenComponentes,pc.discoDuro.id);
eliminar(tienda.almacenComponentes,pc.memoria.id);
END;
'C','c':
BEGIN
writeln('Modificar un componente');
writeln('Introduzca el identificador del componente');
readln(modComp);
aux:=posicion(tienda.almacenComponentes,modComp);
IF (aux=0) THEN
writeln('El componente no esta en el almacen')
ELSE BEGIN
REPEAT
mostrarComp(tienda.almacenComponentes.listaComponentes[aux]);
menuComp;
readln(subopcion);
CASE subopcion OF
'1':BEGIN
REPEAT
writeln('Seleccione el tipo deseado :');
writeln('1) Procesador.');
writeln('2) Disco duro.');
writeln('3) Memoria.');
readln(subopcion);
CASE subopcion OF
'1':tienda.almacenComponentes.listaComponentes[aux].tipo:='procesador';
'2':tienda.almacenComponentes.listaComponentes[aux].tipo:='disco duro';
'3':tienda.almacenComponentes.listaComponentes[aux].tipo:='memoria';
END;
UNTIL ((subopcion='1') OR (subopcion='2') OR (subopcion='3'));
END;
'2':BEGIN
writeln('Modificar la descripcion');
readln(tienda.almacenComponentes.listaComponentes[aux].descripcion);
END;
'3':BEGIN
writeln('Modificar el precio');
readln(tienda.almacenComponentes.listaComponentes[aux].precio);
END;
END;{CASE}
readln;
UNTIL (subopcion='f') OR (subopcion='F');
END;{BEGIN IF}
END;
'D','d':
BEGIN
writeln('Vender componente');
writeln('Introduzca el identificador del componente');
readln(venta);
aux:=posicion(tienda.almacenComponentes,venta);
IF (aux=0) THEN
writeln('El componente no existe')
ELSE BEGIN
mostrarComp(tienda.almacenComponentes.listaComponentes[aux]);
tienda.ventasTotales:= (tienda.ventasTotales + tienda.almacenComponentes.listaComponentes[aux].precio);
eliminar(tienda.almacenComponentes,tienda.almacenComponentes.listaComponentes[aux].id);
END;
END;
'e','E':
BEGIN
writeln('Introduzca el identificador del ordenador que desee comprar:');
readln(ide);
aux:=posicionPc(tienda.almacenPcs,ide);
IF(aux=0) THEN
writeln('El pc no esta en stock')
ELSE BEGIN
mostrarPc(tienda.almacenPcs.listaPcs[aux]);
writeln('¿Esta seguro de querer comprar este ordenador? (S/N)');
readln(subopcion);
IF ((subopcion='s') OR (subopcion='S')) THEN BEGIN
tienda.ventasTotales:= (tienda.ventasTotales + tienda.almacenPcs.listaPcs[aux].datos.precio);
eliminarPc(tienda.almacenPcs,tienda.almacenPcs.listaPcs[aux].datos.id);
END;
END;
END;
'F','f':
BEGIN
writeln('Las ventas totales de la tienda fueron de: ', tienda.ventasTotales:0:2);
END;
'G','g':
BEGIN
writeln('Muestra todos los ordenadores de menor a mayor precio');
IF tienda.almacenPcs.tope=0 THEN
writeln('Almacen de pcs vacio')
ELSE
BEGIN
ordenarPrecios(tienda.almacenPcs);
mostrarPcs(tienda.almacenPcs);
END;
END;
'H','h':
BEGIN
writeln('Muestra de todos los componentes sueltos');
IF tienda.almacenComponentes.tope= 0 THEN
writeln('Almacen de componentes vacio')
ELSE
mostrarComponentes(tienda.almacenComponentes);
END;
'I','i':
BEGIN
writeln('Al guardar los datos, se sobreescribiran los datos anteriormente guardados.');
REPEAT
writeln('¿Desea continuar? (S/N)');
readln(subopcion)
UNTIL ((subopcion='S') OR (subopcion='N'));
IF (subopcion='S') THEN
guardarBin(tienda,compBin,ordBin);
END;
'J','j':
BEGIN
writeln('Al guardar los datos, se sobreescribiran los datos anteriormente guardados.');
REPEAT
writeln('¿Desea continuar? (S/N)');
readln(subopcion)
UNTIL ((subopcion='S') OR (subopcion='N'));
IF (subopcion='S') THEN
guardarText(tienda,compText,ordText);
END;
'K','k':
BEGIN
writeln('Al cargar los datos desde el fichero, se sobreescribiran los datos cargados en el sistema.');
REPEAT
writeln('¿Desea continuar? (S/N)');
readln(subopcion)
UNTIL ((subopcion='S') OR (subopcion='N'));
IF (subopcion='S') THEN
BEGIN
existe:=comprobarFicheros('dat');
IF existe THEN
cargarBin(tienda,compBin,ordBin)
ELSE
writeln('El fichero no existe');
END;
END;
'L','l':
BEGIN
writeln('Al cargar los datos desde el fichero, se sobreescribiran los datos cargados en el sistema.');
REPEAT
writeln('¿Desea continuar? (S/N)');
readln(subopcion)
UNTIL ((subopcion='S') OR (subopcion='N'));
IF (subopcion='S') THEN
BEGIN
existe:=comprobarFicheros('txt');
IF existe THEN
cargarText(tienda,compText,ordText)
ELSE
writeln('El fichero no existe');
END;
END;
'M','m': writeln('Fin del programa.');
ELSE
writeln('Opción incorrecta.');
END;
readln;
UNTIL ((opcion='M') OR (opcion='m'));
END.
|
unit SFtpFile;
interface
type
HCkSFtpFile = Pointer;
HCkDateTime = Pointer;
HCkString = Pointer;
function CkSFtpFile_Create: HCkSFtpFile; stdcall;
procedure CkSFtpFile_Dispose(handle: HCkSFtpFile); stdcall;
procedure CkSFtpFile_getCreateTimeStr(objHandle: HCkSFtpFile; outPropVal: HCkString); stdcall;
function CkSFtpFile__createTimeStr(objHandle: HCkSFtpFile): PWideChar; stdcall;
procedure CkSFtpFile_getFilename(objHandle: HCkSFtpFile; outPropVal: HCkString); stdcall;
function CkSFtpFile__filename(objHandle: HCkSFtpFile): PWideChar; stdcall;
procedure CkSFtpFile_getFileType(objHandle: HCkSFtpFile; outPropVal: HCkString); stdcall;
function CkSFtpFile__fileType(objHandle: HCkSFtpFile): PWideChar; stdcall;
function CkSFtpFile_getGid(objHandle: HCkSFtpFile): Integer; stdcall;
procedure CkSFtpFile_getGroup(objHandle: HCkSFtpFile; outPropVal: HCkString); stdcall;
function CkSFtpFile__group(objHandle: HCkSFtpFile): PWideChar; stdcall;
function CkSFtpFile_getIsAppendOnly(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsArchive(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsCaseInsensitive(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsCompressed(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsDirectory(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsEncrypted(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsHidden(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsImmutable(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsReadOnly(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsRegular(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsSparse(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsSymLink(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsSync(objHandle: HCkSFtpFile): wordbool; stdcall;
function CkSFtpFile_getIsSystem(objHandle: HCkSFtpFile): wordbool; stdcall;
procedure CkSFtpFile_getLastAccessTimeStr(objHandle: HCkSFtpFile; outPropVal: HCkString); stdcall;
function CkSFtpFile__lastAccessTimeStr(objHandle: HCkSFtpFile): PWideChar; stdcall;
function CkSFtpFile_getLastMethodSuccess(objHandle: HCkSFtpFile): wordbool; stdcall;
procedure CkSFtpFile_putLastMethodSuccess(objHandle: HCkSFtpFile; newPropVal: wordbool); stdcall;
procedure CkSFtpFile_getLastModifiedTimeStr(objHandle: HCkSFtpFile; outPropVal: HCkString); stdcall;
function CkSFtpFile__lastModifiedTimeStr(objHandle: HCkSFtpFile): PWideChar; stdcall;
procedure CkSFtpFile_getOwner(objHandle: HCkSFtpFile; outPropVal: HCkString); stdcall;
function CkSFtpFile__owner(objHandle: HCkSFtpFile): PWideChar; stdcall;
function CkSFtpFile_getPermissions(objHandle: HCkSFtpFile): Integer; stdcall;
function CkSFtpFile_getSize32(objHandle: HCkSFtpFile): Integer; stdcall;
function CkSFtpFile_getSize64(objHandle: HCkSFtpFile): Int64; stdcall;
procedure CkSFtpFile_getSizeStr(objHandle: HCkSFtpFile; outPropVal: HCkString); stdcall;
function CkSFtpFile__sizeStr(objHandle: HCkSFtpFile): PWideChar; stdcall;
function CkSFtpFile_getUid(objHandle: HCkSFtpFile): Integer; stdcall;
function CkSFtpFile_GetCreateDt(objHandle: HCkSFtpFile): HCkDateTime; stdcall;
function CkSFtpFile_GetLastAccessDt(objHandle: HCkSFtpFile): HCkDateTime; stdcall;
function CkSFtpFile_GetLastModifiedDt(objHandle: HCkSFtpFile): HCkDateTime; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkSFtpFile_Create; external DLLName;
procedure CkSFtpFile_Dispose; external DLLName;
procedure CkSFtpFile_getCreateTimeStr; external DLLName;
function CkSFtpFile__createTimeStr; external DLLName;
procedure CkSFtpFile_getFilename; external DLLName;
function CkSFtpFile__filename; external DLLName;
procedure CkSFtpFile_getFileType; external DLLName;
function CkSFtpFile__fileType; external DLLName;
function CkSFtpFile_getGid; external DLLName;
procedure CkSFtpFile_getGroup; external DLLName;
function CkSFtpFile__group; external DLLName;
function CkSFtpFile_getIsAppendOnly; external DLLName;
function CkSFtpFile_getIsArchive; external DLLName;
function CkSFtpFile_getIsCaseInsensitive; external DLLName;
function CkSFtpFile_getIsCompressed; external DLLName;
function CkSFtpFile_getIsDirectory; external DLLName;
function CkSFtpFile_getIsEncrypted; external DLLName;
function CkSFtpFile_getIsHidden; external DLLName;
function CkSFtpFile_getIsImmutable; external DLLName;
function CkSFtpFile_getIsReadOnly; external DLLName;
function CkSFtpFile_getIsRegular; external DLLName;
function CkSFtpFile_getIsSparse; external DLLName;
function CkSFtpFile_getIsSymLink; external DLLName;
function CkSFtpFile_getIsSync; external DLLName;
function CkSFtpFile_getIsSystem; external DLLName;
procedure CkSFtpFile_getLastAccessTimeStr; external DLLName;
function CkSFtpFile__lastAccessTimeStr; external DLLName;
function CkSFtpFile_getLastMethodSuccess; external DLLName;
procedure CkSFtpFile_putLastMethodSuccess; external DLLName;
procedure CkSFtpFile_getLastModifiedTimeStr; external DLLName;
function CkSFtpFile__lastModifiedTimeStr; external DLLName;
procedure CkSFtpFile_getOwner; external DLLName;
function CkSFtpFile__owner; external DLLName;
function CkSFtpFile_getPermissions; external DLLName;
function CkSFtpFile_getSize32; external DLLName;
function CkSFtpFile_getSize64; external DLLName;
procedure CkSFtpFile_getSizeStr; external DLLName;
function CkSFtpFile__sizeStr; external DLLName;
function CkSFtpFile_getUid; external DLLName;
function CkSFtpFile_GetCreateDt; external DLLName;
function CkSFtpFile_GetLastAccessDt; external DLLName;
function CkSFtpFile_GetLastModifiedDt; external DLLName;
end.
|
unit uCefScriptActionBase;
interface
uses
//
System.SysUtils, System.Classes, System.SyncObjs,
//
uCEFTypes, uCEFInterfaces, uCEFProcessMessage, uCEFDownloadImageCallBack,
//
uCefWebAction, uCefScriptBase, uCefWebActionBase, uCefScriptNav, uCefUtilFunc,
uCefUtilType, uCefScriptDict;
type
TCefProcMethod0 = procedure of object;
TCefScriptStep1 = function(const ASender: TCefScriptBase): Boolean of object;
TCefScriptStep1Array = array of TCefScriptStep1;
TCefScriptActionBase = class abstract (TCefScriptBase)
private
procedure RunActionStopFree;
function RunActionStartWait: TWaitResult; overload;
function RunActionStartWait(var AResult: Boolean;
const ASetFail: Boolean): TWaitResult; overload;
protected
FAction: TCefWebActionBase;
FScriptDict: TCefScriptDict;
//---
function DoNavGoBack(const AActionName: string): Boolean;
function RunScript(const AScript: string; const ASetFail: Boolean = True): Boolean;
function RunScriptNav(const AActionName, AUrl: string; const ANavFunc: TCefScriptNavFunc;
const ANavProc0: TCefScriptNavProc0;
const ASetFail, AIsNavigation: Boolean): Boolean; overload;
function RunScriptNav(const AActionName: string; const AUrl: string; const ASetFail: Boolean = True;
const AIsNavigation: Boolean = True): Boolean; overload;
function RunScriptNav(const AActionName: string; const ANavFunc: TCefScriptNavFunc; const ASetFail: Boolean = True;
const AIsNavigation: Boolean = False): Boolean; overload;
function RunScriptNav(const AActionName: string; const ANavProc0: TCefScriptNavProc0; const ASetFail: Boolean = True;
const AIsNavigation: Boolean = False): Boolean; overload;
//---
function RunScriptClickById(const AId: string;
const ASetFail: Boolean = True; const ASetIsNav: Boolean = False): Boolean;
function RunScriptScrollAndClickElement(const ASpeed: TCefUISpeed;
const AElem: TElementParams; const ASetFail: Boolean;
const ASetIsNav: Boolean): Boolean; overload;
function RunScriptScrollAndClickElement(const AElem: TElementParams;
const ASetFail: Boolean = True; const ASetIsNav: Boolean = False): Boolean; overload;
function RunScriptScrollAndClickElementNav(const AElem: TElementParams;
const ASetFail: Boolean = True): Boolean;
//---
function DoStepPause(const ATimeout: string; const ASteps: array of TCefScriptStep1): Boolean; overload;
function DoPause(const ATimeout: string; const ASteps: TCefScriptStep1 = nil): Boolean;
public
destructor Destroy; override;
//---
//---
function Wait: TWaitResult; override;
procedure Abort; override;
//---
procedure SetScriptDict(const A: TCefScriptDict);
property ScriptDict: TCefScriptDict read FScriptDict write SetScriptDict;
end;
implementation
uses
uStringUtils,
//
uCefScriptClickElement, uCefWaitEventList, uCefUIFunc;
{ TCefScriptActionBase }
destructor TCefScriptActionBase.Destroy;
begin
if Assigned(FAction) then
FAction.Free;
inherited;
end;
function TCefScriptActionBase.DoStepPause(const ATimeout: string;
const ASteps: array of TCefScriptStep1): Boolean;
var step: TCefScriptStep1;
begin
for step in ASteps do
begin
if Sleep(RandomRangeStr(ATimeout, PAUSE_STEP_DEF)) <> wrTimeout then
Exit(False);
if Assigned(step) then
if not step(Self) then
Exit(False);
end;
Exit(Sleep(ATimeout) = wrTimeout)
end;
function TCefScriptActionBase.DoPause(const ATimeout: string;
const ASteps: TCefScriptStep1): Boolean;
begin
if Assigned(ASteps) then
Result := DoStepPause(ATimeout, [ASteps])
else
Result := Sleep(ATimeout) = wrTimeout
end;
function TCefScriptActionBase.DoNavGoBack(const AActionName: string): Boolean;
begin
LogInfo('go <- back');
if Chromium.CanGoBack then
begin
Result := RunScriptNav(AActionName,
procedure
begin
Chromium.GoBack();
end,
True, True);
end
else
begin
LogError('not canGoBack');
Result := False
end
end;
function TCefScriptActionBase.RunActionStartWait: TWaitResult;
begin
if FAction.Start() then
Result := FAction.Wait()
else
Result := wrError
end;
function TCefScriptActionBase.RunActionStartWait(var AResult: Boolean;
const ASetFail: Boolean): TWaitResult;
var wr: TWaitResult;
begin
AResult := False;
wr := RunActionStartWait();
if wr = wrSignaled then
begin
FAction.LogDebug('action wrSignaled');
if FAction.IsSuccess then
AResult := True;
end
else
if wr = wrTimeout then
begin
if FAction.IsSuccess then
begin
AResult := True;
FAction.LogDebug('action wrTimeout');
end
else
begin
FAction.LogError('action wrTimeout')
end
end
else
if wr = wrAbandoned then
begin
FAction.LogError('action wrAbandoned');
end
else
if wr = wrError then
begin
FAction.LogError('action wrError');
end;
if ASetFail and FAction.IsFail and not FAction.IgnoreFail then
FFail := True;
Result := wr;
end;
procedure TCefScriptActionBase.RunActionStopFree;
begin
if Assigned(FAction) then
begin
FAction.Abort();
FAction.Wait();
FAction.Free;
FAction := nil;
end;
end;
function TCefScriptActionBase.RunScript(const AScript: string; const ASetFail: Boolean): Boolean;
begin
RunActionStopFree();
try
if not Assigned(FScriptDict) then
begin
LogError('no script dict');
if ASetFail then
FFail := True;
Exit(False)
end;
FAction := FScriptDict.MakeScript(AScript, FController, FLogger, Chromium, FAbortEvent);
if not Assigned(FAction) then
begin
LogError('not found script "%s"', [AScript]);
if ASetFail then
FFail := True;
Exit(False)
end;
RunActionStartWait(Result, ASetFail);
finally
FreeAndNil(FAction);
end;
end;
function TCefScriptActionBase.RunScriptClickById(const AId: string;
const ASetFail, ASetIsNav: Boolean): Boolean;
begin
RunActionStopFree();
try
FAction := TScriptClickElement.Create(FController.Pause, AId, ASetIsNav, Self);
RunActionStartWait(Result, ASetFail);
finally
FreeAndNil(FAction);
end;
end;
function TCefScriptActionBase.RunScriptScrollAndClickElement(const ASpeed: TCefUISpeed;
const AElem: TElementParams; const ASetFail, ASetIsNav: Boolean): Boolean;
var bol: Boolean;
begin
LogDebug('scroll to element');
bol := CefUIScrollToElement(Self, ASpeed, AElem);
if bol then
begin
DoPause(PAUSE_DEF);
LogDebug('mouse move to element');
bol := CefUIMouseMoveToElement(Self, ASpeed, AElem);
if bol then
begin
DoPause(PAUSE_DEF);
bol := RunScriptNav('nav-click',
procedure
begin
LogDebug('click element');
CefUIMouseClick(Self);
end,
ASetFail, ASetIsNav);
//---
if not bol then
LogError('fail click to element');
Exit(bol)
end
else
begin
LogError('fail mouse move to element');
end;
end
else
begin
LogError('fail scroll to element');
end;
Result := False;
end;
function TCefScriptActionBase.RunScriptScrollAndClickElement(
const AElem: TElementParams; const ASetFail, ASetIsNav: Boolean): Boolean;
begin
Result := RunScriptScrollAndClickElement(FController.Speed, AElem, ASetFail, ASetIsNav)
end;
function TCefScriptActionBase.RunScriptScrollAndClickElementNav(
const AElem: TElementParams; const ASetFail: Boolean): Boolean;
begin
Result := RunScriptScrollAndClickElement(FController.Speed, AElem, ASetFail, True)
end;
procedure TCefScriptActionBase.SetScriptDict(const A: TCefScriptDict);
begin
FScriptDict := A
end;
function TCefScriptActionBase.RunScriptNav(const AActionName, AUrl: string;
const ANavFunc: TCefScriptNavFunc; const ANavProc0: TCefScriptNavProc0;
const ASetFail, AIsNavigation: Boolean): Boolean;
begin
RunActionStopFree();
try
FAction := TCefScriptNav.Create(AActionName, AUrl, ANavFunc, ANavProc0, AIsNavigation, Self);
RunActionStartWait(Result, ASetFail);
finally
FreeAndNil(FAction);
end;
end;
function TCefScriptActionBase.RunScriptNav(const AActionName, AUrl: string;
const ASetFail, AIsNavigation: Boolean): Boolean;
begin
Result := RunScriptNav(AActionName, AUrl, nil, nil, ASetFail, AIsNavigation)
end;
function TCefScriptActionBase.RunScriptNav(const AActionName: string;
const ANavFunc: TCefScriptNavFunc; const ASetFail, AIsNavigation: Boolean): Boolean;
begin
Result := RunScriptNav(AActionName, '', ANavFunc, nil, ASetFail, AIsNavigation)
end;
function TCefScriptActionBase.RunScriptNav(const AActionName: string;
const ANavProc0: TCefScriptNavProc0; const ASetFail, AIsNavigation: Boolean): Boolean;
begin
Result := RunScriptNav(AActionName, '', nil, ANavProc0, ASetFail, AIsNavigation)
end;
procedure TCefScriptActionBase.Abort;
begin
if Assigned(FAction) then
FAction.Abort();
inherited;
end;
function TCefScriptActionBase.Wait: TWaitResult;
begin
if Assigned(FAction) then
Result := FAction.Wait()
else
Result := inherited Wait()
end;
end.
|
unit ServerThread;
interface
uses
winsock, sysutils, Messanger;
const BSIZE = 128;
M_RECIEVE_UDP = 100;
M_RECIEVE_TCP = 101;
M_CONNECT = 102;
M_DISCONECT = 103;
MAX_CONNECTIONS = 5;
PORT : word = 1234;
type
TTHreadFunc = function(ThParams : pointer): integer;stdcall;
TThreadTCPFunc = function(): integer of object; stdcall;
TThreadParams = record
terminate : Boolean;
sock : TSocket;
ListenStat,
NotifyAddr : TAddress;
id : byte;
sendersock : PSockAddrIn; // out
fsenderIP : PAnsiString; // out
end;
TBuf = array[0..BSIZE - 1] of byte;
PBuf = ^TBuf;
TSrvUDP = class
strict private
thread_id : cardinal;
thread : integer;
srvUDP : TSocket;
NotifyAddr : TAddress;
sendersock : TSockAddrIn;
ThFunc : TTHreadFunc;
ThParams : TThreadParams;
UDPBufOUT : TBuf;
procedure CreateSrvThread();
public
function GetMsg(MessageBuf: PBuf): string;
procedure SendData(const Data: string; var ToAddr: TSockAddrIn; broadcast : boolean);
property ServerUDP : TSocket read srvUDP;
constructor Create(NotifyAddr: TAddress);
destructor Destroy(); override;
end;
TConnection = class
public
thread_id,
thread : cardinal;
iip : in_addr;
cltTCP : TSocket;
ThParams : TThreadParams;
ThFunc : TThreadTCPFunc;
TCPbufOUT : TBuf;
function Execute(): integer; stdcall;
constructor Create(id: byte; Srv: TSocket; Listen: TAddress);
destructor Destroy(); override;
end;
TSrvTCP = class
strict private
NotifyAddr : TAddress;
srvTCP : TSocket;
Connections : array [0 .. MAX_CONNECTIONS - 1] of TConnection;
procedure ListenConnectionStatus(var Msg: TMessage);
function GetConnectionByIP(IP: in_addr): TConnection;
function GetFreeConnection(): integer;
public
initiator : boolean;
function GetMsg(MessageBuf: PBuf): string;
procedure Connect(const IP: string; out Connect_id: integer);
function Connected(Connect_id: integer): boolean;
procedure Disconnect(Connect_id: integer);
procedure SendDataTo(const Data: string; Connect_id: integer);
constructor Create(NotifyAddr: TAddress);
destructor Destroy; override;
end;
procedure StopNet();
implementation
uses uLogging, Winapi.Windows;
const M_CONNECTION_ERROR = 500;
var inf : TWSAData;
sockAddr : TSockAddrIn;
res : integer;
procedure StopNet();
begin
WSACleanup;
end;
function PrepeareMsg(const Msg : string; var Buf : TBuf): integer;
var i, j, len : integer;
s : UTF8String;
begin
result := 0;
len := Length(Msg);
s := UTF8String(StringOfChar(#0, BSIZE - 1));
UnicodeToUTF8(PAnsiChar(s), BSIZE - 1, PWideChar(Msg), len);
FillChar(buf, sizeof(TBuf), 0);
j := 1;
for i := 0 to BSIZE - 1 do
begin
if s[j] = #0 then
begin
buf[i] := ord('.');
inc(result);
break;
end;
buf[i] := ord(s[j]);
inc(j);
inc(result)
end;
end;
function ReadBufAsString(Buf: PBuf): string;
var i : byte;
ch : AnsiChar;
s : UTF8String;
begin
s := UTF8String(StringOfChar(#0, BSIZE));
result := StringOfChar(#0, length(s));
for i := 0 to BSIZE do
begin
ch := AnsiChar(Buf^[i]);
if ch in ['.', #0] then break else s[i + 1] := ch;
end;
Utf8ToUnicode(PWideChar(result), length(s), PansiChar(s), BSIZE - 1);
Result := TrimRight(result);
end;
{ TSrv }
{$REGION ' UDP '}
function TSrvUDP.GetMsg(MessageBuf: PBuf): string;
begin
result := ReadBufAsString(MessageBuf);
FreeMem(MessageBuf, BSIZE);
end;
procedure TSrvUDP.SendData(const Data: string; var ToAddr: TSockAddrIn; broadcast: boolean);
begin
if broadcast then ToAddr.sin_addr.S_addr := inet_addr('255.255.255.255');
Logger.Logg(['Send ', Data, ' to ', string(inet_ntoa(ToAddr.sin_addr))]);
res := PrepeareMsg(Data, UDPbufOUT);
res := sendto(srvUDP, UDPbufOUT, res, 0, ToAddr, sizeof(ToAddr));
if res = SOCKET_ERROR then
begin
Logger.Logg(['Error: ', WSAGetLastError()]);
exit;
end;
end;
function ThreadUDPFunc(ThParams: pointer):integer;stdcall;
var cb, len : integer;
buf: PBuf;
begin
result := 0;
with TThreadParams(ThParams^) do
begin
while not terminate do
begin
cb := 0;
FillChar(sendersock^, sizeof(sendersock^), 0);
len := SizeOf(sendersock^);
buf := nil;
if sock <> INVALID_SOCKET then
begin
buf := AllocMem(BSIZE);
cb := recvfrom(sock, buf^, BSIZE, 0, sendersock^, len);
end;
if (cb = 0) or (cb = INVALID_SOCKET) then
begin
Logger.Logg(['Reciving UDP data error ', WSAGetLastError]);
FreeMem(buf, BSIZE);
end
else if cb > 0 then
SendMsg(NotifyAddr, M_RECIEVE_UDP, cardinal(buf), TSockAddrIn(sendersock^).sin_addr.S_addr);
end;
end
end;
procedure TSrvUDP.CreateSrvThread;
begin
ThParams.terminate := false;
ThParams.sock := self.srvUDP;
ThParams.NotifyAddr := NotifyAddr;
ThParams.sendersock := @sendersock;
ThFunc := ThreadUDPFunc;
thread := CreateThread(nil, 0, @ThFunc, @ThParams, 0, thread_id);
if thread = 0 then
begin
Logger.Logg(['Error while create UDP thread ', GetLastError]);
exit;
end;
end;
destructor TSrvUDP.Destroy;
begin
if srvUDP <> 0 then
begin
res := shutdown(srvUDP, SD_BOTH);
res := closesocket(srvUDP);
end;
srvUDP := 0;
if thread <> 0 then
begin
ThParams.terminate := true;
WaitForSingleObject(thread, 1000);
CloseHandle(thread);
end;
Logger.Logg(['TSrvTUDP Thread terminated.']);
inherited
end;
constructor TSrvUDP.Create(NotifyAddr: TAddress);
var opt,optlen,res: integer;
begin
self.NotifyAddr := NotifyAddr;
Logger.Logg(['Create UDPsocket']);
FillChar(sendersock, sizeof(TSockAddrIn) ,0);
srvUDP := socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (srvUDP = INVALID_SOCKET) then
begin
Logger.Logg(['Socket error: ', WSAGetLastError]);
exit;
end;
res := bind(srvUDP,sockAddr,sizeof(sockAddr));
if res = SOCKET_ERROR then
begin
Logger.Logg(['Bind error: ', WSAGetLastError]);
exit;
end;
opt := 0;
optlen := sizeof(integer);
res := getsockopt(srvUDP, SOL_SOCKET, SO_BROADCAST, @opt, optlen);
if res = SOCKET_ERROR then
begin
Logger.Logg(['Get opt error: ', WSAGetLastError()]);
exit;
end;
opt := 1;
res := setsockopt(srvUDP, SOL_SOCKET, SO_BROADCAST, @opt, optlen);
if res = SOCKET_ERROR then
begin
Logger.Logg(['Set opt error: ', WSAGetLastError()]);
exit;
end;
CreateSrvThread();
Logger.Logg(['UDPsocket created']);
end;
{$ENDREGION}
{ TConnection }
function TConnection.Execute(): integer;
var cb, len : integer;
cs : TSocket;
buf : PBuf;
ssock : TSockAddr;
begin
result := 0;
FillChar(ssock, sizeof(TSockAddr), 0);
len := sizeof(TSockAddrIn);
cs := accept(ThParams.sock, @ssock, @len);
if cs = INVALID_SOCKET then
begin
Logger.Logg(['Accepting connection error ', WSAGetLastError]);
exit;
end;
while not ThParams.terminate do
begin
buf := AllocMem(BSIZE);
cb := recv(cs, buf^, BSIZE, 0);
if (cb <= 0) then
begin
Logger.Logg(['Reciving TCP data error ', WSAGetLastError]);
closesocket(cs);
ThParams.terminate := true;
FreeMem(buf, BSIZE);
SendMsg(ThParams.ListenStat, M_CONNECTION_ERROR, ThParams.id, ssock.sin_addr.S_addr);
end
else
SendMsg(ThParams.ListenStat, M_RECIEVE_TCP, cardinal(buf), ssock.sin_addr.S_addr);
end;
end;
constructor TConnection.Create(id: byte; Srv: TSocket; Listen: TAddress);
begin
inherited Create();
ThParams.terminate := false;
ThParams.sock := Srv;
ThParams.ListenStat := Listen;
ThParams.id := id;
ThFunc := Execute;
cltTCP := socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (cltTCP = INVALID_SOCKET) then
begin
Logger.Logg(['Create TCPClient error: ', WSAGetLastError]);
exit;
end;
thread := CreateThread(nil, 0, @ThFunc, self, 0, thread_id);
if thread = 0 then
begin
Logger.Logg(['Error while create TCP thread ', GetLastError]);
exit;
end;
end;
destructor TConnection.Destroy;
begin
ThParams.terminate := True;
if cltTCP <> 0 then
begin
shutdown(cltTCP, SD_BOTH);
closesocket(cltTCP);
end;
WaitForSingleObject(thread, 1000);
CloseHandle(thread);
inherited Destroy;
end;
{ TSrvTCP }
{$REGION ' TCP '}
function TSrvTCP.GetConnectionByIP(IP: in_addr): TConnection;
var i: integer;
begin
result := nil;
for i := 0 to MAX_CONNECTIONS - 1 do
if Assigned(Connections[i]) and (Connections[i].iip.S_addr = ip.S_addr)
then exit(Connections[i])
end;
function TSrvTCP.GetFreeConnection: integer;
var i: integer;
begin
for i := 0 to MAX_CONNECTIONS - 1 do
if self.Connections[i] = nil then exit(i);
result := -1;
end;
function TSrvTCP.GetMsg(MessageBuf: PBuf): string;
begin
result := ReadBufAsString(MessageBuf);
FreeMem(MessageBuf, BSIZE);
end;
procedure TSrvTCP.ListenConnectionStatus(var Msg: TMessage);
var s: string;
begin
if Msg.msg = M_CONNECTION_ERROR then
begin
if Msg.wparam1 in [0..MAX_CONNECTIONS - 1] then
begin
SendMsg(NotifyAddr, M_DISCONECT, Msg.iparam1, Msg.iparam2);
FreeAndNil(Connections[msg.wparam1]);
s := 'Connection lost with ' + string(inet_ntoa(in_addr(Msg.iparam2)));
Logger.Logg([s]);
end
else Logger.Logg(['Invalid connection index ', Msg.wparam1]);
end
else SendMsg(NotifyAddr, Msg.msg, Msg.iparam1, Msg.iparam2);
end;
procedure TSrvTCP.SendDataTo(const Data: string; Connect_id: integer);
var Con: TConnection;
begin
if not Connect_id in [0..MAX_CONNECTIONS - 1] then
begin
Logger.Logg(['Send Error: Not Connected or invalid IP']);
exit;
end;
if not Connected(Connect_id) then
begin
Logger.Logg(['Send Fail not connected.']);
exit;
end;
Con := self.Connections[Connect_id];
Logger.Logg(['Send ', Data, ' to ', string(inet_ntoa(Con.iip))]);
res := PrepeareMsg(Data, Con.TCPbufOUT);
res := send(Con.cltTCP, Con.TCPbufOUT, res, 0);
if res = INVALID_SOCKET then
begin
Logger.Logg(['Error while send data ', WSAGetLastError]);
exit;
end;
end;
procedure TSrvTCP.Connect(const IP: string; out Connect_id: integer);
var iip: in_addr;
Con: TConnection;
sendersock: TSockAddr;
begin
Logger.Logg(['Connecting to ', IP]);
iip.S_addr := inet_addr(PansiChar(AnsiString(IP)));
Con := GetConnectionByIP(iip);
if Assigned(Con) then
begin
Logger.Logg(['Already connected.']);
exit;
end;
Connect_id := GetFreeConnection();
if Connect_id < 0 then
begin
Logger.Logg(['Connection Limit ', MAX_CONNECTIONS]);
exit;
end;
Logger.Logg(['Launch Thread #', Connect_id]);
Connections[Connect_id] := TConnection.Create(Connect_id, srvTCP, ListenConnectionStatus);
Con := Connections[Connect_id];
FillChar(sendersock, sizeof(sendersock), 0);
sendersock.sin_family := AF_INET;
sendersock.sin_port := htons(PORT);
sendersock.sin_addr := iip;
res := winsock.connect(Con.cltTCP, sendersock, sizeof(sendersock));
if res = SOCKET_ERROR then
begin
Logger.Logg(['Connect Error: ', WSAGetLastError]);
exit;
end;
Con.iip := iip;
Logger.Logg(['Connected.']);
end;
procedure TSrvTCP.Disconnect(Connect_id: integer);
begin
initiator := true;
FreeAndNil(Connections[Connect_id])
end;
function TSrvTCP.Connected(Connect_id: integer): boolean;
begin
result := (Connect_id in [0..MAX_CONNECTIONS - 1]) and
Assigned(Connections[Connect_id]);
end;
constructor TSrvTCP.Create(NotifyAddr: TAddress);
begin
Logger.Logg(['Create TCPsocket.']);
FillChar(Self.Connections, sizeof(Self.Connections), 0);
self.NotifyAddr := NotifyAddr;
srvTCP := socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (srvTCP = INVALID_SOCKET) then
begin
Logger.Logg(['Create TCPsocket error: ', WSAGetLastError]);
exit;
end;
if bind(srvTCP,sockAddr,sizeof(sockAddr)) = SOCKET_ERROR then
begin
Logger.Logg(['Bind TCPsocket error: ', WSAGetLastError]);
exit;
end;
if listen(srvTCP, MAX_CONNECTIONS - 1) = SOCKET_ERROR then
begin
Logger.Logg(['Listen TCPsocket error: ', WSAGetLastError]);
exit;
end;
end;
destructor TSrvTCP.Destroy;
var i : integer;
begin
if srvTCP <> 0 then
begin
shutdown(srvTCP, SD_BOTH);
closesocket(srvTCP);
end;
srvTCP := 0;
for i := 0 to MAX_CONNECTIONS - 1 do
if Assigned(self.Connections[i]) then
begin
Disconnect(i);
Logger.Logg(['TSrvTCP Thread #', i, ' terminated.']);
end;
inherited;
end;
{$ENDREGION}
initialization
WSAStartUp(MakeWord(1,1),inf);
FillChar(sockAddr, sizeof(TSockAddrIn), 0);
sockAddr.sin_family := AF_INET;
sockAddr.sin_port := htons(PORT);
sockAddr.sin_addr.S_addr := INADDR_ANY;
end.
|
{$include kode.inc}
unit kode_filter_rc;
{
https://christianfloisand.wordpress.com/tag/leaky-integrator/
We calculate the coefficients using the time-constant equation:
g = e ^ ( -1 / (time * sample rate) ),
where time is in seconds, and sample rate in Hz.
out = in + g * (out – in),
}
//----------
{
http://www.kvraudio.com/forum/viewtopic.php?f=33&t=300689&start=15
time in samples to reach level = log(1.0 - level) / log(1.0 - coefficient)
so say you're decaying from 1.0 to 0.0, you want to figure out how
long it takes to get within 1/100th of that point:
time in samples = log(0.01) / log(1.0 - coefficient)
percentage = (1 - coefficient) ^ samples
position = lerp(start, end, percentage)
coefficient = 1 - percentage ^ (1 / samples)
}
//----------
{
http://www.kvraudio.com/forum/viewtopic.php?f=33&t=206245
If you have an RC filter, the input is constant, and you need to
process a certain amount of samples but don't need the intermediate
sample values (for example, "analog-style" ADSR envelopes), there's
a neat thing you can do to make it an O(1) operation.
// distance to input value, increase for more accuracy
#define THRESHOLD (0.001f)
// number of samples at sampleRate
float timeConstant = speedInMillisecondsToReachThreshold * sampleRate * 0.001f;
// adjusted rate
timeConstant = timeConstant / (float) numSamplesToProcess;
// coefficient, adjusted to the new sampleRate
float coeff = powf(1.0f / THRESHOLD, -1.0f / timeConstant);
// one "iteration"
y0 = coeff * y0 + (1.0f - coeff) * input;
---
That's basically a 1st order low-pass filter
- the DSP block I like the most :)
You may write y0 = coeff * ( y0 - input ) + input without difference
in results. But I usually transform it into
y0 += ( input - y0 ) * coeff
- looks neater - you only need to equate coeff to 1-coeff.
By the way, if you are not aware, this is the code that calculates
coeff (for the form I have given):
inline double calcLP1Coeff( const double theta )
{
const double costheta2 = 2.0 - cos( theta );
return( 1.0 - ( costheta2 - sqrt( costheta2 * costheta2 - 1.0 )));
}
(theta = 2*pi*freq/SampleRate)
This function takes care of frequency warping near the Nyquist freq
whereas 'powf' will give wrong results.
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
type
KFilter_RC = class
private
FValue : Single;
FTarget : Single;
FWeight : Single;
public
property value : Single read FValue write FValue;
property target : Single read FTarget write FTarget;
property weight : Single read FWeight write FWeight;
public
constructor create;
destructor destroy; override;
//procedure setup(AValue:Single=0; ATarget:Single=0; AWeight:Single=0);
function getValue : Single;
procedure setValue(AValue:Single);
procedure setTarget(ATarget:Single);
procedure setWeight(AWeight:Single);
procedure setFrequency(AFrequency:Single; ASampleRate:Single);
procedure setTime(ATime:Single);
function process : Single;
function process(AValue:Single) : Single;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_const;
//----------
constructor KFilter_RC.create;
begin
FValue := 0;
FTarget := 1;
FWeight := 1;
end;
//----------
destructor KFilter_RC.destroy;
begin
end;
//----------
{procedure KFilter_RC.setup(AValue:Single; ATarget:Single; AWeight:Single);
begin
FValue := AValue;
FTarget := ATarget;
FWeight := AWeight;
end;}
//----------
function KFilter_RC.getValue : Single;
begin
result := FValue;
end;
//----------
procedure KFilter_RC.setValue(AValue:Single);
begin
FValue := AValue;
end;
//----------
procedure KFilter_RC.setTarget(ATarget:Single);
begin
FTarget := ATarget;
end;
//----------
procedure KFilter_RC.setWeight(AWeight:Single);
begin
FWeight := AWeight;
end;
//----------
// filter
procedure KFilter_RC.setFrequency(AFrequency:Single; ASampleRate:Single);
begin
if ASampleRate > 0 then FWeight := 1 - exp(-KODE_PI2 * AFrequency / ASampleRate )
else FWeight := 0;
end;
//----------
{
ATime is the time it takes the filter to decay to
36.8% of its initial input or reach 63.2% of its final output.
seconds? millisecond?
}
procedure KFilter_RC.setTime(ATime:Single);
begin
if ATime > 0 then FWeight := 1 - exp(-1 / ATime)
else FWeight := 0;
end;
//----------
function KFilter_RC.process : Single;
begin
FValue += (FTarget-FValue) * FWeight;
result := FValue;
end;
//----------
{
rc filter as lowpass filter..
input = target
}
function KFilter_RC.process(AValue:Single) : Single;
begin
FTarget := AValue;
result := self.process();
end;
//----------------------------------------------------------------------
end.
|
// gets record by its HEX FormID
function getRecordByFormID(id: string): IInterface;
var
tmp: IInterface;
begin
// if file or record was not found => return nil
Result := nil;
// if records plugin id is loaded
if not (StrToInt(Copy(id, 1, 2)) > (FileCount - 1)) then begin
// basically we took record like 00049BB7, and by slicing 2 first symbols, we get its file index, in this case Skyrim (00)
tmp := FileByLoadOrder(StrToInt('$' + Copy(id, 1, 2)));
// file was found
if Assigned(tmp) then begin
// look for this record in founded file, and return it
tmp := RecordByFormID(tmp, StrToInt('$' + id), true);
// check that record was found
if Assigned(tmp) then
Result := tmp;
end;
end;
end;
|
unit LoginForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, UserClass, CreateAccountForm, MenuForm,
Vcl.Touch.Keyboard;
type
TLogin = class(TForm)
edtUsername: TEdit;
edtPassword: TEdit;
btnLogin: TButton;
btnNewAccount: TButton;
procedure btnLoginClick(Sender: TObject);
procedure btnNewAccountClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Login: TLogin;
implementation
{$R *.dfm}
procedure TLogin.btnLoginClick(Sender: TObject);
var UserFile : TextFile; ReadInUser : String; UserPassCombo : TStringList; LoginSuccessful : Boolean;
begin
// Log in only to become true if matches user-pass combo
LoginSuccessful := false;
// Read in user from file
AssignFile(UserFile, 'Users.AMF');
Reset(UserFile);
while not EoF(UserFile) do
begin
UserPassCombo := TStringList.Create;
Readln(UserFile, ReadInUser);
ExtractStrings(['|'], [], PChar(ReadInUser), UserPassCombo);
// Compare read in details to what user has entered
if (UserPassCombo[0] = edtUsername.Text) and (UserPassCombo[1] = edtPassword.Text) then LoginSuccessful := true;
UserPassCombo.Free;
end;
// Close file and string list
CloseFile(UserFile);
// If the username and password combination is correct, log in
if LoginSuccessful then
begin
Login.Hide();
TheMenu.LoggedInUser := edtUsername.Text;
TheMenu.Show();
end
else ShowMessage('Username or password incorrect. Login failed.');
end;
// Show new account form
procedure TLogin.btnNewAccountClick(Sender: TObject);
begin
CreateAccount.Show();
end;
// Make sure text boxes are blank when form is shown
procedure TLogin.FormShow(Sender: TObject);
begin
edtUsername.Text := '';
edtPassword.Text := '';
end;
end.
|
object formSettings: TformSettings
Left = 257
Top = 306
Width = 785
Height = 574
BorderIcons = [biSystemMenu]
Caption = 'Cheat Engine settings'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -14
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poMainFormCenter
OnClose = FormClose
OnCreate = FormCreate
OnShow = FormShow
PixelsPerInch = 120
TextHeight = 16
object pnlConfig: TPanel
Left = 0
Top = 0
Width = 767
Height = 482
Align = alClient
TabOrder = 0
object tvMenuSelection: TTreeView
Left = 1
Top = 1
Width = 148
Height = 480
Align = alLeft
HideSelection = False
Indent = 19
ReadOnly = True
RightClickSelect = True
ShowRoot = False
TabOrder = 0
OnChange = tvMenuSelectionChange
OnCollapsing = tvMenuSelectionCollapsing
Items.Data = {
08000000290000000000000000000000FFFFFFFFFFFFFFFF0000000001000000
1047656E6572616C2073657474696E6773230000000000000000000000FFFFFF
FFFFFFFFFF00000000000000000A546F6F6C73206D656E752000000000000000
00000000FFFFFFFFFFFFFFFF000000000000000007486F746B65797325000000
0000000000000000FFFFFFFFFFFFFFFF00000000000000000C556E72616E646F
6D697A6572260000000000000000000000FFFFFFFFFFFFFFFF00000000000000
000D5363616E2073657474696E6773200000000000000000000000FFFFFFFFFF
FFFFFF000000000000000007506C7567696E73240000000000000000000000FF
FFFFFFFFFFFFFF00000000000000000B436F64652046696E6465722A00000000
00000000000000FFFFFFFFFFFFFFFF000000000000000011417373656D626C65
72206F7074696F6E731E0000000000000000000000FFFFFFFFFFFFFFFF000000
0000000000054578747261}
end
object pcSetting: TPageControl
Left = 149
Top = 1
Width = 617
Height = 480
ActivePage = GeneralSettings
Align = alClient
Style = tsFlatButtons
TabOrder = 1
object GeneralSettings: TTabSheet
Caption = 'General Settings'
object Label11: TLabel
Left = 209
Top = 395
Width = 18
Height = 16
Caption = 'ms'
end
object Label12: TLabel
Left = 209
Top = 425
Width = 18
Height = 16
Caption = 'ms'
end
object Label13: TLabel
Left = 63
Top = 395
Width = 91
Height = 16
Caption = 'Update interval'
end
object Label14: TLabel
Left = 66
Top = 425
Width = 88
Height = 16
Caption = 'Freeze interval'
end
object Label16: TLabel
Left = 10
Top = 464
Width = 143
Height = 16
Caption = 'Network Update Interval'
Visible = False
end
object Label17: TLabel
Left = 209
Top = 464
Width = 18
Height = 16
Caption = 'ms'
Visible = False
end
object Label18: TLabel
Left = 256
Top = 395
Width = 201
Height = 16
Caption = 'Found address list update interval'
end
object Label19: TLabel
Left = 508
Top = 396
Width = 18
Height = 16
Caption = 'ms'
end
object Label23: TLabel
Left = 10
Top = 345
Width = 245
Height = 16
Caption = 'Automatically attach to processes named'
end
object Label24: TLabel
Left = 408
Top = 345
Width = 141
Height = 16
Caption = '(Seperate entries with ; )'
end
object cbShowUndo: TCheckBox
Left = 1
Top = 2
Width = 601
Height = 21
Caption = 'Show undo button'
Checked = True
State = cbChecked
TabOrder = 0
end
object cbShowAdvanced: TCheckBox
Left = 1
Top = 22
Width = 601
Height = 21
Caption = 'Show advanced options.'
Checked = True
State = cbChecked
TabOrder = 1
end
object cbCenterOnPopup: TCheckBox
Left = 1
Top = 60
Width = 601
Height = 21
Caption = 'Center Cheat Engine when bringing to front'
Checked = True
State = cbChecked
TabOrder = 2
end
object EditUpdateInterval: TEdit
Left = 156
Top = 390
Width = 53
Height = 24
Hint =
'The number of milliseconds that Cheat Engine will wait before re' +
'freshing the list of addresses'
ParentShowHint = False
ShowHint = True
TabOrder = 3
Text = '500'
end
object EditFreezeInterval: TEdit
Left = 156
Top = 420
Width = 53
Height = 24
Hint =
'The number of milliseconds that Cheat Engine will wait before re' +
'setting the frozen addresses to their original value.'
ParentShowHint = False
ShowHint = True
TabOrder = 4
Text = '250'
end
object GroupBox1: TGroupBox
Left = 0
Top = 228
Width = 602
Height = 86
Caption = 'Address list specific'
TabOrder = 5
object cbShowAsSigned: TCheckBox
Left = 20
Top = 20
Width = 542
Height = 21
Caption = 'Show values as if they are signed'
TabOrder = 0
end
object cbBinariesAsDecimal: TCheckBox
Left = 20
Top = 39
Width = 542
Height = 21
Caption = 'Show and work with binaries as if they are decimals'
TabOrder = 1
end
object cbsimplecopypaste: TCheckBox
Left = 20
Top = 59
Width = 542
Height = 21
Caption = 'Simple paste'
TabOrder = 2
end
end
object EditNetworkUpdateInterval: TEdit
Left = 156
Top = 459
Width = 53
Height = 24
Hint =
'The number of milliseconds that Cheat Engine will wait before re' +
'freshing the list of addresses'
ParentShowHint = False
ShowHint = True
TabOrder = 6
Text = '500'
Visible = False
end
object cbUpdatefoundList: TCheckBox
Left = 1
Top = 41
Width = 601
Height = 21
Caption = 'Update the list of found addresses even after scanning'
Checked = True
State = cbChecked
TabOrder = 7
OnClick = cbUpdatefoundListClick
end
object editUpdatefoundInterval: TEdit
Left = 455
Top = 391
Width = 51
Height = 24
Hint =
'The number of milliseconds that Cheat Engine will wait before re' +
'freshing the list of addresses'
ParentShowHint = False
ShowHint = True
TabOrder = 8
Text = '1000'
end
object cbHideAllWindows: TCheckBox
Left = 1
Top = 79
Width = 429
Height = 21
Caption =
'Hide some/all windows instead of trying to bring cheat engine to' +
' front'
Checked = True
State = cbChecked
TabOrder = 9
OnClick = cbHideAllWindowsClick
end
object btnExcludeProcesses: TButton
Left = 433
Top = 78
Width = 90
Height = 21
Caption = 'More...'
TabOrder = 10
OnClick = btnExcludeProcessesClick
end
object EditAutoAttach: TEdit
Left = 259
Top = 340
Width = 143
Height = 24
Hint =
'Type the name of the process you want to automatically open. Not' +
'e: Only works when NO process has been opened yet'
TabOrder = 11
end
object cbAlwaysAutoAttach: TCheckBox
Left = 10
Top = 367
Width = 592
Height = 21
Caption = 'Even autoattach when another process has already been selected'
TabOrder = 12
end
object cbSaveWindowPos: TCheckBox
Left = 1
Top = 138
Width = 601
Height = 21
Caption = 'Save window positions'
TabOrder = 13
end
object cbOldSpeedhack: TCheckBox
Left = 1
Top = 118
Width = 601
Height = 21
Caption = 'Use old speedhack'
TabOrder = 14
end
object cbProcessIcons: TCheckBox
Left = 1
Top = 177
Width = 542
Height = 21
Caption = 'Get process icons for processlist'
Checked = True
State = cbChecked
TabOrder = 15
OnClick = cbProcessIconsClick
end
object cbProcessIconsOnly: TCheckBox
Left = 20
Top = 197
Width = 237
Height = 21
Caption = 'Only show processes with an icon'
TabOrder = 16
end
object cbShowMainMenu: TCheckBox
Left = 1
Top = 158
Width = 601
Height = 20
Caption = 'Show main menu'
Checked = True
State = cbChecked
TabOrder = 17
end
object cbOldPointerAddMethod: TCheckBox
Left = 1
Top = 98
Width = 614
Height = 21
Caption = 'Pointer adding: Append pointerline instead of insert'
Checked = True
State = cbChecked
TabOrder = 18
end
end
object tsHotkeys: TTabSheet
Caption = 'Hotkeys'
ImageIndex = 7
inline frameHotkeyConfig: TframeHotkeyConfig
Left = 0
Top = 0
Width = 609
Height = 446
Align = alClient
TabOrder = 0
inherited Panel1: TPanel
Top = 62
Width = 383
Height = 384
inherited Label1: TLabel
Width = 383
end
inherited ListBox1: TListBox
Width = 383
Height = 368
end
end
inherited Panel2: TPanel
Left = 383
Top = 62
Width = 226
Height = 384
DesignSize = (
226
384)
inherited Label2: TLabel
Left = 7
end
inherited Edit1: TEdit
Left = 6
Top = 20
Width = 212
end
inherited Button3: TButton
Left = 158
Top = 49
Width = 60
Height = 21
end
inherited Panel3: TPanel
Left = 10
Top = 79
Width = 209
Height = 366
DesignSize = (
209
366)
inherited Label52: TLabel
Left = 14
end
inherited Label51: TLabel
Left = 74
end
inherited edtSHSpeed: TEdit
Left = 5
Top = 22
Width = 57
end
inherited edtSHSleep: TEdit
Left = 74
Top = 22
Width = 56
end
end
inherited Panel4: TPanel
Left = 10
Top = 82
Width = 213
Height = 120
inherited Label3: TLabel
Left = 4
end
inherited Edit4: TEdit
Top = 20
Width = 205
end
end
end
inherited Panel5: TPanel
Width = 609
Height = 62
inherited Label4: TLabel
Left = 128
Top = 7
end
inherited Label5: TLabel
Left = 128
Top = 39
end
inherited edtKeypollInterval: TEdit
Width = 117
end
inherited edtHotkeyDelay: TEdit
Top = 32
Width = 117
end
end
end
end
object Unrandomizer: TTabSheet
Caption = 'Unrandomizer'
ImageIndex = 8
object Label5: TLabel
Left = 10
Top = 10
Width = 114
Height = 16
Caption = 'Default return value'
end
object edtDefault: TEdit
Left = 128
Top = 7
Width = 149
Height = 24
TabOrder = 0
Text = '0'
end
object cbIncremental: TCheckBox
Left = 11
Top = 39
Width = 129
Height = 21
Caption = 'Incremental value'
TabOrder = 1
end
end
object ScanSettings: TTabSheet
Caption = 'Scan Settings'
ImageIndex = 1
object Label2: TLabel
Left = 0
Top = 246
Width = 590
Height = 32
Caption =
'Running the scan in a seperate thread will give you a cancel but' +
'ton, and prevents CE from starvation. (meaning parts of the wind' +
'ow turn white) but it also makes scanning a little slower'
Transparent = True
WordWrap = True
end
object Label3: TLabel
Left = 218
Top = 309
Width = 87
Height = 16
Caption = 'Thread priority'
end
object Label1: TLabel
Left = 0
Top = 7
Width = 139
Height = 16
Caption = 'Size of scanbuffer (KB) :'
end
object Label15: TLabel
Left = 233
Top = 7
Width = 169
Height = 16
Caption = '(Can effect scan speed a lot)'
end
object Label21: TLabel
Left = 0
Top = 158
Width = 198
Height = 16
Caption = 'Scan the following memory types:'
end
object checkThread: TCheckBox
Left = 208
Top = 286
Width = 198
Height = 20
Caption = 'Run scan in seperate thread'
Checked = True
State = cbChecked
TabOrder = 0
Visible = False
OnClick = checkThreadClick
end
object combothreadpriority: TComboBox
Left = 306
Top = 305
Width = 90
Height = 24
ItemHeight = 16
ItemIndex = 4
PopupMenu = MainForm.emptypopup
TabOrder = 1
Text = 'Higher'
Items.Strings = (
'Idle'
'Lowest'
'Lower'
'Normal'
'Higher'
'Highest'
'TimeCritical')
end
object cbFastscan: TCheckBox
Left = 0
Top = 39
Width = 602
Height = 21
Caption = 'Fast scan on by default'
TabOrder = 2
end
object cbSkip_PAGE_NOCACHE: TCheckBox
Left = 0
Top = 79
Width = 602
Height = 21
Hint =
'Some systems crash when trying to read memory with this protecti' +
'on. If that happens check this option.'
Caption = 'Don'#39't scan memory that is protected with the No Cache option'
ParentShowHint = False
ShowHint = True
TabOrder = 3
end
object cbLowMemoryUsage: TCheckBox
Left = 0
Top = 98
Width = 602
Height = 21
Caption =
'Keep low memory usage when doing an "Unkown Initial Value scan" ' +
'with Hyper Scan'
TabOrder = 4
end
object cbMemImage: TCheckBox
Left = 0
Top = 197
Width = 602
Height = 21
Caption =
'MEM_IMAGE:Memory that is mapped into the view of an image sectio' +
'n'
Checked = True
State = cbChecked
TabOrder = 5
end
object cbMemMapped: TCheckBox
Left = 0
Top = 217
Width = 602
Height = 21
Caption =
'MEM_MAPPED:Memory that is mapped into the view of a section. (E.' +
'g:File mapping, slow)'
TabOrder = 6
end
object cbMemPrivate: TCheckBox
Left = 0
Top = 177
Width = 602
Height = 21
Caption = 'MEM_PRIVATE:Memory that is private.'
Checked = True
State = cbChecked
TabOrder = 7
end
object cbEnableHyperscanWhenPossible: TCheckBox
Left = 0
Top = 59
Width = 602
Height = 21
Caption = 'Enable Hyperscan when possible'
TabOrder = 8
end
object EditBufsize: TEdit
Left = 177
Top = 2
Width = 51
Height = 24
TabOrder = 9
Text = '1024'
end
end
object Plugins: TTabSheet
Caption = 'Plugins'
ImageIndex = 3
object Panel7: TPanel
Left = 512
Top = 0
Width = 97
Height = 446
Align = alRight
BevelOuter = bvNone
TabOrder = 0
object Button5: TButton
Left = 5
Top = 43
Width = 92
Height = 31
Caption = 'Delete'
TabOrder = 0
OnClick = Button5Click
end
object Button4: TButton
Left = 5
Top = 4
Width = 92
Height = 30
Caption = 'Add new'
TabOrder = 1
OnClick = Button4Click
end
end
object Panel8: TPanel
Left = 0
Top = 0
Width = 512
Height = 446
Align = alClient
BevelOuter = bvNone
TabOrder = 1
object Label22: TLabel
Left = 0
Top = 0
Width = 512
Height = 16
Align = alTop
Caption = 'The following plugins are available:'
end
object clbPlugins: TCheckListBox
Left = 0
Top = 16
Width = 512
Height = 430
Align = alClient
ItemHeight = 16
TabOrder = 0
end
end
end
object CodeFinder: TTabSheet
Caption = 'CodeFinder'
ImageIndex = 4
object Label4: TLabel
Left = 0
Top = 0
Width = 609
Height = 48
Align = alTop
Caption =
'There are 2 ways Cheat Engine can find the addresss of code that' +
' writes to a specific address. Each type has it advantages and i' +
't'#39's disadvantages. So choose which one suits you better. (or cho' +
'ose the one that doesnt give you problems.)'
WordWrap = True
end
object Label6: TLabel
Left = 0
Top = 79
Width = 568
Height = 16
Caption =
'Advantage: Not as memory intensive as the "Write Exceptions" typ' +
'e. And very high compatibility.'
end
object Label7: TLabel
Left = 0
Top = 97
Width = 325
Height = 16
Caption = 'Disadvantage: May sometimes return a wrong address'
end
object Label8: TLabel
Left = 0
Top = 138
Width = 416
Height = 16
Caption =
'Advantage: Finds every address that accesses the specified addre' +
'ss.'
end
object Label9: TLabel
Left = 0
Top = 155
Width = 595
Height = 32
Caption =
'Disadvantage: Memory intensive so slows down the game. And might' +
' cause stability problems in the game'
WordWrap = True
end
object rbDebugRegisters: TRadioButton
Left = 0
Top = 59
Width = 602
Height = 21
Caption = 'Use Debug Registers (aka Hardware Breakpoints)'
Checked = True
TabOrder = 0
TabStop = True
end
object rdWriteExceptions: TRadioButton
Left = 0
Top = 118
Width = 602
Height = 21
Caption = 'Memory Access Exceptions'
TabOrder = 1
end
object CheckBox1: TCheckBox
Left = 0
Top = 188
Width = 602
Height = 21
Caption = 'Try to prevent detection of the debugger'
TabOrder = 2
OnClick = CheckBox1Click
end
object cbHandleBreakpoints: TCheckBox
Left = 0
Top = 208
Width = 602
Height = 21
Caption = 'Handle beakpoints not caused by CE'
TabOrder = 3
OnClick = CheckBox1Click
end
end
object Assembler: TTabSheet
Caption = 'Assembler'
ImageIndex = 5
object cbShowDisassembler: TCheckBox
Left = 1
Top = 2
Width = 601
Height = 21
Caption = 'Show disassembler'
Checked = True
State = cbChecked
TabOrder = 0
OnClick = cbShowDisassemblerClick
end
object cbShowDebugoptions: TCheckBox
Left = 20
Top = 30
Width = 582
Height = 20
Caption = 'Show debugger options'
Checked = True
State = cbChecked
TabOrder = 1
end
object replacewithnops: TCheckBox
Left = 20
Top = 89
Width = 582
Height = 21
Hint =
'If you type in a opcode and it is smaller than the opcode you re' +
'placed, it will fill the missing bytes with NOP instructions. If' +
' the opcode is longer it will replace the opcode(s) that have be' +
'en overwritten with NOP'#39's'
Caption = 'Replace incomplete opcodes with nops'
Checked = True
ParentShowHint = False
ShowHint = True
State = cbChecked
TabOrder = 2
OnClick = replacewithnopsClick
end
object askforreplacewithnops: TCheckBox
Left = 39
Top = 108
Width = 563
Height = 21
Caption = 'Ask for replace with nop'
Checked = True
State = cbChecked
TabOrder = 3
end
object CheckBox2: TCheckBox
Left = 0
Top = 180
Width = 602
Height = 21
Caption = 'Try to prevent detection of the debugger'
TabOrder = 4
OnClick = CheckBox2Click
end
object rbDebugAsBreakpoint: TRadioButton
Left = 39
Top = 49
Width = 563
Height = 21
Caption = 'Use hardware breakpoints (Max 3)'
Checked = True
TabOrder = 5
TabStop = True
end
object rbInt3AsBreakpoint: TRadioButton
Left = 39
Top = 69
Width = 563
Height = 21
Caption = 'Use int3 instructions for breakpoints (Unlimited)'
TabOrder = 6
end
object cbBreakOnAttach: TCheckBox
Left = 20
Top = 148
Width = 582
Height = 21
Caption = 'Break when attaching/creating process using the process list'
TabOrder = 7
Visible = False
end
end
object Extra: TTabSheet
Caption = 'Extra'
ImageIndex = 6
object TauntOldOsUser: TLabel
Left = 0
Top = 430
Width = 424
Height = 16
Align = alBottom
Alignment = taCenter
Caption =
'I really recommend upgrading to Windows 2000 or later mister Fli' +
'ntstone'
Visible = False
end
object GroupBox3: TGroupBox
Left = 0
Top = 0
Width = 609
Height = 86
Align = alTop
Caption =
'Use the following CE Kernel routines instead of the original win' +
'dows version'
TabOrder = 0
object cbKernelQueryMemoryRegion: TCheckBox
Left = 10
Top = 20
Width = 592
Height = 21
Caption = 'Query memory region routines'
TabOrder = 0
OnClick = cbKernelQueryMemoryRegionClick
end
object cbKernelReadWriteProcessMemory: TCheckBox
Left = 10
Top = 39
Width = 592
Height = 21
Caption = 'Read/Write Process Memory (Will cause slower scans)'
TabOrder = 1
OnClick = cbKernelQueryMemoryRegionClick
end
object cbKernelOpenProcess: TCheckBox
Left = 10
Top = 59
Width = 592
Height = 21
Caption = 'Open Process'
TabOrder = 2
end
end
object cbProcessWatcher: TCheckBox
Left = 1
Top = 91
Width = 593
Height = 21
Caption = 'Enable use of the Process Watcher'
TabOrder = 1
OnClick = cbProcessWatcherClick
end
object cbKdebug: TCheckBox
Left = 1
Top = 111
Width = 593
Height = 21
Caption = 'Use kernelmode debugger options when possible'
TabOrder = 2
OnClick = cbKdebugClick
end
object CheckBox3: TCheckBox
Left = 1
Top = 296
Width = 593
Height = 21
Caption = 'Use APC to inject dll'#39's'
TabOrder = 3
Visible = False
end
object CheckBox4: TCheckBox
Left = 1
Top = 316
Width = 593
Height = 21
Caption = 'Use APC to create new threads'
TabOrder = 4
Visible = False
end
object cbGlobalDebug: TCheckBox
Left = 22
Top = 129
Width = 572
Height = 21
Caption = 'Use Global Debug routines'
Enabled = False
TabOrder = 5
end
end
object tsTools: TTabSheet
Caption = 'tsTools'
ImageIndex = 9
object Panel2: TPanel
Left = 0
Top = 0
Width = 609
Height = 26
Align = alTop
BevelOuter = bvNone
TabOrder = 0
object cbShowTools: TCheckBox
Left = 0
Top = 0
Width = 484
Height = 21
Caption = 'Show '#39'tools'#39' menu item'
Checked = True
State = cbChecked
TabOrder = 0
OnClick = cbShowToolsClick
end
end
object Panel3: TPanel
Left = 381
Top = 26
Width = 228
Height = 420
Align = alRight
BevelOuter = bvNone
TabOrder = 1
object lblApplicationTool: TLabel
Left = 10
Top = 49
Width = 133
Height = 16
Caption = 'Application/Command'
Enabled = False
end
object lblShortcut: TLabel
Left = 10
Top = 98
Width = 51
Height = 16
Caption = 'Shortcut:'
Enabled = False
end
object lblShortcutText: TLabel
Left = 10
Top = 118
Width = 48
Height = 16
Caption = 'xxxxxxxx'
Enabled = False
end
object lblToolsName: TLabel
Left = 10
Top = 0
Width = 37
Height = 16
Caption = 'Name'
Enabled = False
end
object OpenButton: TSpeedButton
Left = 197
Top = 69
Width = 31
Height = 26
Enabled = False
Glyph.Data = {
D6020000424DD6020000000000003600000028000000100000000E0000000100
180000000000A0020000C40E0000C40E00000000000000000000C0C0C0C0C0C0
C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0
C0C0C0C0C0C0C0C0C0C000000000000000000000000000000000000000000000
0000000000000000000000C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0000000000000
008484008484008484008484008484008484008484008484008484000000C0C0
C0C0C0C0C0C0C0C0C0C000000000FFFF00000000848400848400848400848400
8484008484008484008484008484000000C0C0C0C0C0C0C0C0C0000000FFFFFF
00FFFF0000000084840084840084840084840084840084840084840084840084
84000000C0C0C0C0C0C000000000FFFFFFFFFF00FFFF00000000848400848400
8484008484008484008484008484008484008484000000C0C0C0000000FFFFFF
00FFFFFFFFFF00FFFF0000000000000000000000000000000000000000000000
0000000000000000000000000000FFFFFFFFFF00FFFFFFFFFF00FFFFFFFFFF00
FFFFFFFFFF00FFFF000000C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0000000FFFFFF
00FFFFFFFFFF00FFFFFFFFFF00FFFFFFFFFF00FFFFFFFFFF000000C0C0C0C0C0
C0C0C0C0C0C0C0C0C0C000000000FFFFFFFFFF00FFFF00000000000000000000
0000000000000000000000C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0000000
000000000000C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C00000
00000000000000C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0
C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0000000000000C0C0C0C0C0C0C0C0C0
C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0000000C0C0C0C0C0C0C0C0C00000
00C0C0C0000000C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0
C0C0C0C0C0000000000000000000C0C0C0C0C0C0C0C0C0C0C0C0}
ParentShowHint = False
ShowHint = True
OnClick = OpenButtonClick
end
object edtApplicationTool: TEdit
Left = 10
Top = 69
Width = 186
Height = 24
Enabled = False
MaxLength = 255
TabOrder = 1
OnChange = edtApplicationToolChange
end
object btnSetToolShortcut: TButton
Left = 10
Top = 138
Width = 92
Height = 21
Caption = 'Set shortcut'
Enabled = False
TabOrder = 2
OnClick = btnSetToolShortcutClick
end
object edtToolsName: TEdit
Left = 10
Top = 20
Width = 218
Height = 24
Enabled = False
MaxLength = 255
TabOrder = 0
OnChange = edtToolsNameChange
end
end
object Panel5: TPanel
Left = 0
Top = 26
Width = 381
Height = 420
Align = alClient
BevelOuter = bvNone
TabOrder = 2
object Panel4: TPanel
Left = 0
Top = 392
Width = 381
Height = 28
Align = alBottom
BevelOuter = bvNone
TabOrder = 0
object btnToolNew: TButton
Left = 10
Top = 4
Width = 92
Height = 21
Caption = 'New'
TabOrder = 0
OnClick = btnToolNewClick
end
object btnToolDelete: TButton
Left = 108
Top = 4
Width = 93
Height = 21
Caption = 'Delete'
TabOrder = 1
OnClick = btnToolDeleteClick
end
end
object lvTools: TListView
Left = 0
Top = 0
Width = 381
Height = 392
Align = alClient
Columns = <
item
Caption = 'Name'
Width = 74
end
item
Caption = 'Application'
Width = 234
end
item
AutoSize = True
Caption = 'Shortcut'
end>
HideSelection = False
ReadOnly = True
RowSelect = True
TabOrder = 1
ViewStyle = vsReport
OnClick = lvToolsClick
end
end
end
end
end
object Panel6: TPanel
Left = 0
Top = 482
Width = 767
Height = 47
Align = alBottom
BevelOuter = bvNone
TabOrder = 1
OnResize = Panel6Resize
DesignSize = (
767
47)
object AboutLabel: TLabel
Left = 866
Top = 31
Width = 56
Height = 16
Cursor = crHandPoint
Anchors = [akRight, akBottom]
Caption = 'About CE'
Font.Charset = DEFAULT_CHARSET
Font.Color = clBlue
Font.Height = -15
Font.Name = 'MS Sans Serif'
Font.Style = [fsUnderline]
ParentFont = False
OnClick = AboutLabelClick
end
object Button2: TButton
Left = 401
Top = 6
Width = 92
Height = 31
Anchors = [akTop, akRight]
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 0
end
object Button1: TButton
Left = 295
Top = 6
Width = 92
Height = 31
Anchors = [akTop, akRight]
Caption = 'OK'
Default = True
TabOrder = 1
OnClick = Button1Click
end
end
object defaultbuffer: TPopupMenu
Left = 16
Top = 264
object Default1: TMenuItem
Caption = 'Default'
OnClick = Default1Click
end
end
object OpenDialog1: TOpenDialog
DefaultExt = 'DLL'
Filter = 'Cheat Engine Plugins (*.dll)|*.dll'
Left = 52
Top = 264
end
object OpenDialog2: TOpenDialog
DefaultExt = 'exe'
Filter = 'Application (*.exe)|*.exe'
Left = 3
Top = 441
end
end
|
(**
* $Id: dco.framework.Backlog.pas 840 2014-05-24 06:04:58Z QXu $
*
* 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.
*)
unit dco.framework.Backlog;
interface
uses
System.Generics.Collections,
System.SyncObjs,
superobject { An universal object serialization framework with Json support },
dutil.util.concurrent.Result,
dco.rpc.Identifier;
type
/// <summary>This repository class allows to store and retrieve specified result containers using consecutively
/// numbered asynchronous completion tokens.</summary>
TBacklog = class
private
FLock: TCriticalSection;
FResults: TDictionary<Cardinal, TResult<ISuperObject>>;
FSequenceNumber: Cardinal;
FClosed: Boolean;
function NextSequenceNumber: Cardinal;
class procedure Abort(Result: TResult<ISuperObject>; const Id: TIdentifier); static;
/// <exception cref="EJsonException">When the identifier does not represent a sequence number.</exception>
function TakeInternal(const Id: TIdentifier; FailResult: Boolean): TResult<ISuperObject>;
public
constructor Create;
destructor Destroy; override;
/// <exception cref="EJsonException">When the identifier does not represent a sequence number.</exception>
function Take(const Id: TIdentifier): TResult<ISuperObject>;
/// <exception cref="EJsonException">When the identifier does not represent a sequence number.</exception>
function TakeAndFailResult(const Id: TIdentifier): TResult<ISuperObject>;
function Put(Result_: TResult<ISuperObject>): TIdentifier;
procedure Close;
end;
implementation
uses
{$IFDEF LOGGING}
Log4D,
System.SysUtils,
{$ENDIF}
dutil.core.Exception,
dutil.text.json.Validation,
dco.rpc.ErrorObject,
dco.rpc.RPCException;
constructor TBacklog.Create;
begin
inherited;
FLock := TCriticalSection.Create;
FResults := TDictionary<Cardinal, TResult<ISuperObject>>.Create;
FClosed := False;
FSequenceNumber := 0;
end;
destructor TBacklog.Destroy;
begin
assert(FResults.Count = 0);
FLock.Acquire;
try
FResults.Free;
finally
FLock.Release;
end;
FLock.Free;
inherited;
end;
function TBacklog.Put(Result_: TResult<ISuperObject>): TIdentifier;
var
SequenceNumber: Cardinal;
begin
assert(Result_ <> nil);
FLock.Acquire;
try
SequenceNumber := NextSequenceNumber;
Result := TIdentifier.NumberIdentifier(SequenceNumber);
if FClosed then
Abort(Result_, Result)
else
FResults.Add(SequenceNumber, Result_);
finally
FLock.Release;
end;
end;
function TBacklog.TakeInternal(const Id: TIdentifier; FailResult: Boolean): TResult<ISuperObject>;
var
SequenceNumber: Cardinal;
begin
assert(Id.Valid);
Result := nil;
FLock.Acquire;
try
SequenceNumber := TValidation.RequireUInt(Id.Value); // throws EJsonException
if FResults.ContainsKey(SequenceNumber) then
begin
Result := FResults.ExtractPair(SequenceNumber).Value;
assert(Result <> nil);
if FailResult then
Abort(Result, Id);
end;
finally
FLock.Release;
end;
end;
function TBacklog.Take(const Id: TIdentifier): TResult<ISuperObject>;
begin
Result := TakeInternal(Id, {FailResult=}False);
end;
function TBacklog.TakeAndFailResult(const Id: TIdentifier): TResult<ISuperObject>;
begin
Result := TakeInternal(Id, {FailResult=}True);
end;
procedure TBacklog.Close;
var
Item: TPair<Cardinal, TResult<ISuperObject>>;
begin
FLock.Acquire;
try
for Item in FResults do
Abort(Item.Value, TIdentifier.NumberIdentifier(Item.Key));
FResults.Clear;
FClosed := True;
finally
FLock.Release;
end;
end;
function TBacklog.NextSequenceNumber: Cardinal;
begin
// To avoid potential problems, only non-negative values of the signed 32-bit integral type are used.
if FSequenceNumber < High(Cardinal) then
FSequenceNumber := FSequenceNumber + 1
else
begin
{$IFDEF LOGGING}
TLogLogger.GetLogger(ClassName).Warn('Sequence number wraparound');
{$ENDIF}
FSequenceNumber := 1;
end;
Result := FSequenceNumber;
end;
class procedure TBacklog.Abort(Result: TResult<ISuperObject>; const Id: TIdentifier);
var
Error: TErrorObject;
begin
assert(Result <> nil);
assert(Id.Valid);
Error := TErrorObject.CreateNoResponseReceived('');
{$IFDEF LOGGING}
TLogLogger.GetLogger(ClassName).Warn('Abort to wait (id=%s)', [Id.ToString]);
{$ENDIF}
Result.PutException(ERPCException.Create(Error, Id));
end;
end.
|
unit VBBase_DM;
interface
uses
System.SysUtils, System.Classes, Data.DBXDataSnap, Data.DBXCommon, Vcl.Forms,
Vcl.Controls, System.Win.Registry, System.ImageList, Vcl.ImgList, Winapi.Windows,
System.IOUtils, System.Variants, System.DateUtils,
VBProxyClass, Base_DM, CommonValues, VBCommonValues,
Data.DB, Data.SqlExpr, Data.FireDACJSONReflect, DataSnap.DSCommon, IPPeerClient,
FireDAC.Stan.StorageXML, FireDAC.Stan.StorageJSON, FireDAC.Stan.StorageBin,
FireDAC.Comp.Client, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.UI.Intf, FireDAC.VCLUI.Wait,
FireDAC.Phys.DSDef, FireDAC.Phys, FireDAC.Phys.TDBXBase, FireDAC.Phys.DS,
FireDAC.Comp.UI;
type
TShellResource = record
RootFolder: string;
ResourceFolder: string;
ReportFolder: string;
SkinName: string;
RemoteServerName: string;
ConnectionDefinitionFileLocation: string;
ConnectionDefinitionFileName: string;
ApplicationFolder: string;
UserID: Integer;
end;
TUserData = record
UserName: string; // Login name
FirstName: string;
LastName: string;
UserID: Integer;
EmailAddress: string;
AccountEnabled: Boolean;
PW: string;
end;
TVBBaseDM = class(TBaseDM)
cdsRepository: TFDMemTable;
dtsRepository: TDataSource;
cdsRepositoryID: TIntegerField;
cdsRepositoryAPP_ID: TIntegerField;
cdsRepositorySOURCE_FOLDER: TStringField;
cdsRepositoryDEST_FOLDER: TStringField;
cdsRepositoryFILE_NAME: TStringField;
cdsRepositoryUPDATE_FILE: TIntegerField;
cdsRepositoryDELETE_FILE: TIntegerField;
procedure SetConnectionProperties;
function GetShellResource: TShellResource;
function GetDateOrder(const DateFormat: string): TDateOrder;
function UpdatesPending(DataSetArray: TDataSetArray): Boolean;
function GetMasterData(DataRequestList, ParameterList, Generatorname, Tablename, DataSetName: string): TFDJSONDataSets;
procedure GetData(ID: Integer; DataSet: TFDMemTable; DataSetName, ParameterList, FileName, Generatorname, Tablename: string);
function GetNextID(TableName: string): Integer;
procedure PopulateUserData;
function CopyRecord(DataSet: TFDMemTable): OleVariant;
function GetuseCount(Request: string): Integer;
// function GetDelta(DataSetArray: TDataSetArray): TFDJSONDeltas;
procedure PostData(DataSet: TFDMemTable);
procedure ApplyUpdates(DataSetArray: TDataSetArray; GeneratorName, TableName: string; ScriptID: Integer);
procedure CancelUpdates(DataSetArray: TDataSetArray);
function ExecuteSQLCommand(Request: string): string;
function ExecuteStoredProcedure(ProcedureName, ParameterList: string): string;
function EchoTheString(Request: string; var Response: string): string;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
FResponse: string;
FShellResource: TShellResource;
FClient: TVBServerMethodsClient;
FServerErrorMsg: string;
FCurrentYear: Integer;
FCurrentPeriod: Integer;
FCurrentMonth: Integer;
FMadeChanges: Boolean;
FDBAction: TDBActions;
FQueryRequest: string;
FItemToCount: string;
FSourceFolder: string;
FDestFolder: string;
FFileName: string;
FFullFileName: string;
FAppID: Integer;
FAppName: string;
FCounter: Integer;
FCurrentFileTimeStamp: TDateTime;
FNewFileTimeStamp: TDateTime;
FNewFileTimeStampString: string;
FFilesToUpdate: Integer;
FMyDataSet: TFDMemTable;
FMyDataSource: TDataSource;
public
{ Public declarations }
DataSetArray: TDataSetArray;
UserData: TUserData;
property ShellResource: TShellResource read FShellResource write FShellResource;
property Client: TVBServerMethodsClient read FClient write FClient;
property ServerErrorMsg: string read FServerErrorMsg write FServerErrorMsg;
property CurrentYear: Integer read FCurrentYear write FCurrentYear;
property CurrentPeriod: Integer read FCurrentPeriod write FCurrentPeriod;
property CurrentMonth: Integer read FCurrentMonth write FCurrentMonth;
property MadeChanges: Boolean read FMadeChanges write FMadeChanges;
property DBAction: TDBActions read FDBAction write FDBAction;
property QueryRequest: string read FQueryRequest write FQueryRequest;
property ItemToCount: string read FItemToCount write FItemToCount;
property MyDataSet: TFDMemTable read FMyDataSet write FMyDataSet;
property MyDataSource: TDataSource read FMyDataSource write FMyDataSource;
// property DataSetArray: TDataSetArray read FDataSetArray write FDataSetArray;
// property UserData: TUserData read FUserData write FUserData;
function FoundNewVersion: Boolean;
function CheckForUpdates(AppID: Integer; AppName: string): Boolean;
procedure DownLoadFile;
procedure ResetFileTimeStatmp;
end;
var
VBBaseDM: TVBBaseDM;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses
RUtils,
Progress_Frm;
{$R *.dfm}
{ TVBBaseDM }
procedure TVBBaseDM.DataModuleCreate(Sender: TObject);
begin
inherited;
//// FBeepFreq := 800;
//// FBeepDuration := 300;
//// GetLocaleFormatSettings is deprecated!!
//// GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, FAFormatSettings);
//// FAFormatSettings := TFormatSettings.Create(LOCALE_SYSTEM_DEFAULT);
// FAFormatSettings := TFormatSettings.Create('');
// FDateOrder := GetDateOrder(FAFormatSettings.ShortDateFormat);
//
// case FDateOrder of
// doDMY: FDateStringFormat := 'dd/mm/yyyy';
// doMDY: FDateStringFormat := 'mm/dd/yyyy';
// doYMD: FDateStringFormat := 'yyyy-mm-dd';
// end;
end;
procedure TVBBaseDM.DataModuleDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FClient);
end;
procedure TVBBaseDM.GetData(ID: Integer; DataSet: TFDMemTable; DataSetName,
ParameterList, FileName, Generatorname, Tablename: string);
var
DataSetList: TFDJSONDataSets;
IDList, ParamList: string;
begin
if DataSet.Active then
begin
DataSet.Close;
// DataSet.EmptyDataSet;
end;
IDList := 'SQL_STATEMENT_ID=' + ID.ToString;
if Length(Trim(ParameterList)) = 0 then
ParamList := 'PARAMETER_LIST=' + ONE_SPACE
else
ParamList := 'PARAMETER_LIST=' + ParameterList;
DataSetList := GetMasterData(IDList, ParamList, Generatorname, Tablename, DataSetName);
if FResponse = 'NO_DATA' then
Exit;
// Note to developer...
// If you have any Calcculated or InternalCalc fields you MUST open the
// dataset BEFORE populating it with data. If you don't do this you will get
// the following FireDAC error:
// Cannot change table [DataSetname] table structure when table has rows
// The Open action prepares the dataset and resolves calculated and/or
// InternalCalc fields.
DataSet.Open;
DataSet.AppendData(TFDJSONDataSetsReader.GetListValueByName(DataSetList, DataSetName));
{$IFDEF DEBUG}
DataSet.SaveToFile(FileName, sfXML);
{$ENDIF}
end;
function TVBBaseDM.GetNextID(TableName: string): Integer;
begin
Result := StrToInt(FClient.GetNextID(Tablename));
end;
function TVBBaseDM.GetuseCount(Request: string): Integer;
begin
Result := StrToInt(FClient.GetUseCount(Request));
end;
function TVBBaseDM.GetMasterData(DataRequestList, ParameterList, Generatorname, Tablename, DataSetName: string): TFDJSONDataSets;
//var
// Response: string;
begin
// if FClient = nil then
// FClient := TLeaveServerMethodsClient.Create(BaseDM.sqlConnection.DBXConnection);
FResponse := '';
Result := FClient.GetData(DataRequestList, ParameterList, Generatorname, Tablename, DataSetName, FResponse);
end;
function TVBBaseDM.GetShellResource: TShellResource;
var
RegKey: TRegistry;
// SL: TStringList;
begin
// RegKey := TRegistry.Create(KEY_ALL_ACCESS or KEY_WRITE or KEY_WOW64_64KEY);
// SL := RUtils.CreateStringList(SL, COMMA);
TDirectory.CreateDirectory('C:\Data');
RegKey := TRegistry.Create(KEY_ALL_ACCESS or KEY_WRITE or KEY_WOW64_64KEY);
RegKey.RootKey := HKEY_CURRENT_USER;
try
RegKey.OpenKey(KEY_RESOURCE, True);
Result.RootFolder := ROOT_FOLDER;
// Result.RootFolder := RUtils.AddChar(RUtils.GetShellFolderName(CSIDL_COMMON_DOCUMENTS), '\', rpEnd) + ROOT_DATA_FOLDER;
// SL.Add(FormatDateTime('dd/MM/yyyy hh:mm:ss', Now) + 'Before writing Root Folder value to registry');
// SL.SaveToFile('C:\Data\RegLog.txt');
try
RegKey.WriteString('Root Folder', Result.RootFolder);
except
on E: Exception do
begin
// SL.Add(FormatDateTime('dd/MM/yyyy hh:mm:ss', Now) + 'Exception: ' + E.Message);
// SL.SaveToFile('C:\Data\RegLog.txt');
end;
end;
// SL.Add(FormatDateTime('dd/MM/yyyy hh:mm:ss', Now) + 'After successfully writing Root Folder value to registry');
// SL.SaveToFile('C:\Data\RegLog.txt');
// if not RegKey.ValueExists('Resource') then
// RegKey.WriteString('Resource', '\\VBSERVER\Apps\VB\');
Result.ResourceFolder := RegKey.ReadString('Resource');
Result.ReportFolder := RegKey.ReadString('Reports');
RegKey.CloseKey;
RegKey.OpenKey(KEY_DATABASE, True);
Result.ConnectionDefinitionFileLocation := RegKey.ReadString('Connection Definition File Location');
Result.ConnectionDefinitionFileName := RegKey.ReadString('Connection Definition File Name');
RegKey.CloseKey;
RegKey.OpenKey(KEY_USER_PREFERENCES, True);
if not RegKey.ValueExists('Skin Name') then
RegKey.WriteString('Skin Name', DEFAULT_SKIN_NAME);
Result.SkinName := RegKey.ReadString('Skin Name');
RegKey.CloseKey;
finally
RegKey.Free;
end;
end;
procedure TVBBaseDM.PopulateUserData;
var
RegKey: TRegistry;
begin
RegKey := TRegistry.Create(KEY_ALL_ACCESS or KEY_WRITE or KEY_WOW64_64KEY);
try
RegKey.RootKey := HKEY_CURRENT_USER;
Regkey.OpenKey(KEY_USER_DATA, True);
UserData.UserID := RegKey.ReadInteger('User ID');
UserData.UserName := RegKey.ReadString('Login Name');
UserData.FirstName := RegKey.ReadString('First Name');
UserData.LastName := RegKey.ReadString('Last Name');
UserData.EmailAddress := RegKey.ReadString('Email Address');
UserData.AccountEnabled := RegKey.ReadBool('Account Enabled');
finally
RegKey.Free
end;
end;
procedure TVBBaseDM.PostData(DataSet: TFDMemTable);
begin
SetLength(DataSetArray, 1);
DataSetArray[0] := TFDMemTable(DataSet);
ApplyUpdates(DataSetArray, TFDMemTable(DataSet).UpdateOptions.Generatorname,
TFDMemTable(DataSet).UpdateOptions.UpdateTableName,
TFDMemTable(DataSet).Tag);
TFDMemTable(DataSet).CommitUpdates;
end;
function TVBBaseDM.UpdatesPending(DataSetArray: TDataSetArray): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Length(DataSetArray) - 1 do
begin
Result := DataSetArray[I].UpdatesPending;
if Result then
Break
end;
end;
//function TVBBaseDM.GetDelta(DataSetArray: TDataSetArray): TFDJSONDeltas;
//var
// I: Integer;
//begin
// // Create a delta list
// Result := TFDJSONDeltas.Create;
//
// for I := 0 to Length(DataSetArray) - 1 do
// begin
// // Post if edits pending
// if DataSetArray[I].State in dsEditModes then
// DataSetArray[I].Post;
//
// // Add deltas
// if DataSetArray[I].UpdatesPending then
// TFDJSONDeltasWriter.ListAdd(Result, DataSetArray[I].Name, DataSetArray[I]);
// end;
//end;
procedure TVBBaseDM.ApplyUpdates(DataSetArray: TDataSetArray; GeneratorName, TableName: string;
ScriptID: Integer);
var
DeltaList: TFDJSONDeltas;
Response: string;
begin
Response := '';
DeltaList := GetDelta(DataSetArray);
// try
Response := FClient.ApplyDataUpdates(DeltaList, Response, GeneratorName, TableName, ScriptID);
FServerErrorMsg := Format(Response, [TableName]);
// except
// on E: TDSServiceException do
// raise Exception.Create('Error Applying Updates: ' + E.Message)
// end;
end;
procedure TVBBaseDM.CancelUpdates(DataSetArray: TDataSetArray);
begin
//for var
// I := 0 to Length(DataSetArray) - 1 do
// begin
// if DataSetArray[I].UpdatesPending then
// DataSetArray[I].CancelUpdates;
// end;
end;
function TVBBaseDM.CopyRecord(DataSet: TFDMemTable): OleVariant;
var
I: Integer;
CDS: TFDMemTable;
FieldName: string;
begin
CDS := TFDMemTable.Create(nil);
try
CDS.FieldDefs.Assign(DataSet.FieldDefs);
CDS.CreateDataSet;
CDS.Open;
CDS.Append;
for I := 0 to DataSet.FieldCount - 1 do
begin
FieldName := DataSet.Fields[I].FieldName;
if VarIsNull(DataSet.Fields[I].Value) then
CDS.Fields[I].Value := null
else
CDS.FieldByName(FieldName).Value := DataSet.FieldByName(FieldName).Value;
end;
CDS.Post;
Result := CDS.Data;
finally
CDS.Free;
end;
end;
function TVBBaseDM.ExecuteSQLCommand(Request: string): string;
//var
// Response: string;
begin
// Response := '';
Result := FClient.ExecuteSQLCommand(Request);
end;
function TVBBaseDM.ExecuteStoredProcedure(ProcedureName, ParameterList: string): string;
var
SL: TStringList;
begin
SL := RUtils.CreateStringList(PIPE);
try
SL.DelimitedText := FClient.ExecuteStoredProcedure(ProcedureName, ParameterList);
finally
SL.Free;
end;
end;
function TVBBaseDM.GetDateOrder(const DateFormat: string): TDateOrder;
begin
Result := doMDY;
var
I := Low(string);
while I <= High(DateFormat) do
begin
case Chr(Ord(DateFormat[I]) and $DF) of
'E': Result := doYMD;
'Y': Result := doYMD;
'M': Result := doMDY;
'D': Result := doDMY;
else
Inc(I);
Continue;
end;
Exit;
end;
end;
function TVBBaseDM.FoundNewVersion: Boolean;
var
VersionInfo: TStringList;
Request, Response: string;
begin
VersionInfo := RUtils.CreateStringList(PIPE, SINGLE_QUOTE);
FileAge(FDestFolder + FFileName, FCurrentFileTimeStamp);
Request :=
'FILE_NAME=' + FFileName + PIPE +
'TARGET_FILE_TIMESTAMP=' + FormatDateTime('yyyy-MM-dd hh:mm:ss',
FCurrentFileTimeStamp); // DateTimeToStr(CurrentAppFileTimestamp);
try
VersionInfo.DelimitedText := VBBaseDM.Client.GetFileVersion(Request, Response);
Result := VersionInfo.Values['RESPONSE'] = 'FOUND_NEW_VERSION';
if Result then
begin
if Length(Trim(FNewFileTimeStampString)) = 0 then
FNewFileTimeStampString := VersionInfo.Values['FILE_TIMESTAMP'];
end
else
FNewFileTimeStampString := FormatDateTime('yyyy-MM-dd hh:mm:ss', Now);
finally
VersionInfo.Free;
end;
end;
function TVBBaseDM.CheckForUpdates(AppID: Integer; AppName: string): Boolean;
var
VersionInfo: TStringList;
Request, Response: string;
// CurrentAppFileTimestamp: TDateTime;
UpdateFile: Boolean;
// Iteration: Extended;
begin
FAppID := AppID;
FAppName := AppName;
VersionInfo := RUtils.CreateStringList(PIPE, SINGLE_QUOTE);
Result := False;
Response := '';
if AppID > 0 then
GetData(82, cdsRepository, cdsRepository.Name, ' WHERE R.APP_ID = ' + FAppID.ToString + ' ORDER BY R.ID',
'C:\Data\Xml\Repository.xml', cdsRepository.UpdateOptions.Generatorname,
cdsRepository.UpdateOptions.UpdateTableName)
else
GetData(82, cdsRepository, cdsRepository.Name, ' WHERE R.FILE_NAME = ' + AnsiQuotedStr(FAppName, ''''),
'C:\Data\Xml\Repository.xml', cdsRepository.UpdateOptions.Generatorname,
cdsRepository.UpdateOptions.UpdateTableName);
if cdsRepository.IsEmpty then
Exit;
if ProgressFrm = nil then
ProgressFrm := TProgressFrm.Create(nil);
ProgressFrm.FormStyle := fsStayOnTop;
// ProgressFrm.prgDownload.Style.LookAndFeel.NativeStyle := True;
// ProgressFrm.prgDownload.Properties.BeginColor := $F0CAA6; //clSkyBlue;
ProgressFrm.Update;
ProgressFrm.Show;
FCounter := 0;
FFilesToUpdate := cdsRepository.RecordCount;
try
cdsRepository.First;
while not cdsRepository.EOF do
begin
SendMessage(ProgressFrm.Handle, WM_DOWNLOAD_CAPTION, DWORD(PChar('Preparing downloads. Please wait...')), 0);
Inc(FCounter);
// Iteration := FCounter / FFilesToUpdate * 100;
FSourceFolder := RUtils.AddChar(cdsRepository.FieldByName('SOURCE_FOLDER').AsString, '\', rpEnd);
FDestFolder := RUtils.AddChar(cdsRepository.FieldByName('DEST_FOLDER').AsString, '\', rpEnd);
FFileName := cdsRepository.FieldByName('FILE_NAME').AsString;
FFullFileName := FDestFolder + FFileName;
if TFile.Exists(FFullFileName) then
FileAge(FFullFileName, FNewFileTimeStamp)
else
FNewFileTimeStamp := Now;
UpdateFile := IntegerToBoolean(cdsRepository.FieldByName('UPDATE_FILE').AsInteger);
if TFile.Exists(FFullFileName) then
begin
// If this file has been marked as NOT updateable AND has been marked
// for deletion, then delete the file.
if not (UpdateFile)
and (IntegerToBoolean(cdsRepository.FieldByName('DELETE_FILE').AsInteger)) then
TFile.Delete(FFullFileName)
// If this file has been marked as updateable then download and replace it.
else if IntegerToBoolean(cdsRepository.FieldByName('UPDATE_FILE').AsInteger) then
UpdateFile := FoundNewVersion
else
UpdateFile := False;
end;
// Download a new version of the file if a new one is found or if the file
// is missing and updateable.
// else
// UpdateFile := True;
if UpdateFile then
DownLoadFile;
cdsRepository.Next;
end;
VersionInfo.DelimitedText := VBBaseDM.Client.GetFileVersion(Request, Response);
finally
VersionInfo.Free;
FreeAndNil(ProgressFrm);
end;
end;
procedure TVBBaseDM.DownLoadFile;
var
TheFileStream: TStream;
Buffer: PByte;
MemStream: TMemoryStream;
BufSize, BytesRead, TotalBytesRead: Integer;
StreamSize: Int64;
Response: string;
ResponseList: TStringList;
Progress: Extended;
begin
SendMessage(ProgressFrm.Handle, WM_DOWNLOAD_CAPTION, DWORD(PChar('Downloading: ' +
FFileName + ' (' + FCounter.ToString + ' of ' + FFilesToUpdate.ToString + ')')), 0);
BufSize := 1024;
MemStream := TMemoryStream.Create;
// TheFileStream := TStream.Create;
GetMem(Buffer, BufSize);
Response := '';
StreamSize := 0;
ResponseList := RUtils.CreateStringList(PIPE, SINGLE_QUOTE);
TotalBytesRead := 0;
try
TheFileStream := FClient.DownloadFile(FFileName, Response, StreamSize);
ResponseList.DelimitedText := Response;
if ResponseList.Values['RESPONSE'] = 'FILE_NOT_FOUND' then
Exit;
TheFileStream.Position := 0;
if (StreamSize <> 0) then
begin
// filename := 'download.fil';
repeat
BytesRead := TheFileStream.Read(Pointer(Buffer)^, BufSize);
if (BytesRead > 0) then
begin
TotalBytesRead := TotalBytesRead + BytesRead;
MemStream.WriteBuffer(Pointer(Buffer)^, BytesRead);
Progress := StrToFloat(TotalBytesRead.ToString) / StrToFloat(StreamSize.ToString) * 100;
SendMessage(ProgressFrm.Handle, WM_DOWNLOAD_PROGRESS, DWORD(PChar(FloatToStr(Progress))), 0);
Application.ProcessMessages;
// SendMessage(ProgressFrm.Handle, WM_DOWNLOAD_CAPTION, DWORD(PChar('CAPTION=Downloading: ' +
// FFileName + ' (' + FCounter.ToString + ' of ' + FFilesToUpdate.ToString + ')' + '|PROGRESS=' + FloatToStr(Progress))), 0);
end;
until (BytesRead < BufSize);
if (StreamSize <> MemStream.Size) then
begin
raise Exception.Create('Error downloading file...');
end
else
begin
MemStream.SaveToFile(FDestFolder + FFileName);
ResetFileTimeStatmp;
end;
end
finally
ResponseList.Free;
FreeMem(Buffer, BufSize);
FreeAndNil(MemStream);
// Note to developer:
// DO NOT FREE THE TheFileStream STREAM HERE!!!
// The DBXConnection unit takes care of this. If you free it here you will
// get an AV error the next time you try to free it.
end;
end;
procedure TVBBaseDM.ResetFileTimeStatmp;
var
TargetFileHandle: Integer;
aYear, aMonth, aDay, aHour, aMin, aSec, aMSec: Word;
TheDate: Double;
begin
// FileAge(FFullFileName, FNewFileTimeStamp);
// FNewFileTimestamp := VarToDateTime(FNewFileTimeStampString);
// Get the handle of the file.
TargetFileHandle := FileOpen(FDestFolder + FFileName, fmOpenReadWrite);
// Decode timestamp and resolve to its constituent parts.
DecodeDateTime(FNewFileTimeStamp, aYear, aMonth, aDay, aHour, aMin, aSec, aMSec);
TheDate := EncodeDate(aYear, aMonth, aDay);
if (aSec = 59) and (aMin = 59) then
Inc(aHour)
else if aSec mod 2 <> 0 then
Inc(aSec);
if aSec = 59 then
aSec := 0;
if aMin = 59 then
aMin := 0;
// If handle was successfully generated then reset the timestamp
if TargetFileHandle > 0 then
begin
FileSetDate(TargetFileHandle, DateTimeToFileDate(TheDate + (aHour / 24) + (aMin / (24 * 60)) + (aSec / 24 / 60 / 60)));
end;
// Close the file
FileClose(TargetFileHandle);
// // Copy the newly downloaded app to its actual location.
// TFile.Copy(TempFolder + APP_NAME, AppFileName);
// while not TFile.Exists(AppFileName) do
// Application.ProcessMessages;
end;
procedure TVBBaseDM.SetConnectionProperties;
var
RegKey: TRegistry;
Port: string;
begin
RegKey := TRegistry.Create(KEY_ALL_ACCESS or KEY_WRITE or KEY_WOW64_64KEY);
RegKey.RootKey := HKEY_CURRENT_USER;
RegKey.OpenKey(KEY_DATASNAP, True);
try
if not RegKey.ValueExists('Host Name') then
RegKey.WriteString('Host Name', 'localhost');
{$IFDEF DEBUG}
if not RegKey.ValueExists(VB_SHELL_DEV_TCP_KEY_NAME) then
RegKey.WriteString(VB_SHELL_DEV_TCP_KEY_NAME, VB_SHELL_DEV_TCP_PORT);
if not RegKey.ValueExists(VB_SHELL_DEV_HTTP_KEY_NAME) then
RegKey.WriteString(VB_SHELL_DEV_HTTP_KEY_NAME, VB_SHELL_DEV_HTTP_PORT);
Port := RegKey.ReadString(VB_SHELL_DEV_TCP_KEY_NAME);
{$ELSE}
if not RegKey.ValueExists(VB_SHELLX_TCP_KEY_NAME) then
RegKey.WriteString(VB_SHELLX_TCP_KEY_NAME, VB_SHELLX_TCP_PORT);
if not RegKey.ValueExists(VB_SHELLX_HTTP_KEY_NAME) then
RegKey.WriteString(VB_SHELLX_HTTP_KEY_NAME, VB_SHELLX_HTTP_PORT);
Port := RegKey.ReadString(VB_SHELLX_TCP_KEY_NAME);
{$ENDIF}
sqlConnection.Params.Values['DriverName'] := 'DataSnap';
sqlConnection.Params.Values['DatasnapContext'] := 'DataSnap/';
sqlConnection.Params.Values['CommunicationProtocol'] := 'tcp/ip';
sqlConnection.Params.Values['Port'] := Port;
sqlConnection.Params.Values['HostName'] := RegKey.ReadString('Host Name');
RegKey.CloseKey;
finally
RegKey.Free;
end;
// try
// if not RegKey.ValueExists('Host Name') then
// RegKey.WriteString('Host Name', 'localhost');
//
//{$IFDEF DEBUG}
// if not RegKey.ValueExists(VB_SHELL_DEV_TCP_KEY_NAME) then
// RegKey.WriteString(VB_SHELL_DEV_TCP_KEY_NAME, VB_SHELL_DEV_TCP_PORT);
//
// if not RegKey.ValueExists(VB_SHELL_DEV_HTTP_KEY_NAME) then
// RegKey.WriteString(VB_SHELL_DEV_HTTP_KEY_NAME, VB_SHELL_DEV_HTTP_PORT);
//
// sqlConnection.Params.Values['Port'] := RegKey.ReadString(VB_SHELL_DEV_TCP_KEY_NAME);
//{$ELSE}
// if not RegKey.ValueExists(VB_SHELLX_TCP_KEY_NAME) then
// RegKey.WriteString(VB_SHELLX_TCP_KEY_NAME, VB_SHELLX_TCP_PORT);
//
// if not RegKey.ValueExists(VB_SHELLX_HTTP_KEY_NAME) then
// RegKey.WriteString(VB_SHELLX_HTTP_KEY_NAME, VB_SHELLX_HTTP_PORT);
//
// sqlConnection.Params.Values['Port'] := RegKey.ReadString(VB_SHELLX_TCP_KEY_NAME);
//{$ENDIF}
//
// sqlConnection.Params.Values['DatasnapContext'] := 'DataSnap/';
// sqlConnection.Params.Values['CommunicationProtocol'] := 'tcp/ip';
//// sqlConnection.Params.Values['HostName'] := 'localhost';
//
//// if ReleaseVersion then
// sqlConnection.Params.Values['HostName'] := RegKey.ReadString('Host Name');
// sqlConnection.Open;
//// FClient := TVBServerMethodsClient.Create(VBBaseDM.sqlConnection.DBXConnection);
// RegKey.CloseKey;
// finally
// RegKey.Free;
// end;
end;
function TVBBaseDM.EchoTheString(Request: string; var Response: string): string;
begin
Result := FClient.EchoString(Request, Response);
end;
end.
|
unit DataContext;
interface
uses EF.Engine.DbSet, EF.Engine.DbContext, EF.Mapping.Base, Domain.Entity.Cliente, Domain.Entity.Contato, EF.Drivers.Connection;
type
TDataContextPessoal = class(TDbContext)
public
Clientes : TDbset<TCliente>;
Contatos : TDbset<TContato>;
//Funcionarios : TDbset<TFuncionarios>;
//Fornecedores : TDbset<TFornecedores>;
constructor Create( aDatabase: TDatabaseFacade );override;
destructor Destroy;override;
end;
implementation
{ BoundContext }
constructor TDataContextPessoal.Create( aDatabase: TDatabaseFacade );
begin
inherited;
Clientes := TDbset<TCliente>.create( aDatabase );
Contatos := TDbset<TContato>.create( aDatabase );
end;
destructor TDataContextPessoal.Destroy;
begin
inherited;
Clientes.Free;
Contatos.Free;
end;
end.
|
unit VBPrintExportData;
interface
uses
System.SysUtils, System.Win.Registry, WinApi.Windows, System.IOUtils,
Vcl.Dialogs, Vcl.Controls, WinApi.ShellApi,
CommonValues,
frxClass, frxDBSet,
cxGrid, dxPrnDlg, cxGridExportLink, frxExportPDF,
{$IFDEF VB}
VBProxyClasses,
{$ENDIF}
FireDAC.Comp.Client;
type
TVBPrintExportData = class
private
FSourceDataSet: TFDMemTable;
FTargetDataSet: TFDMemTable;
FReport: TfrxReport;
FReportDataSet: TfrxDBDataset;
FReportTypeName: string;
FReportFileName: string;
FReportAction: TReportActions;
FPrintDlg: TdxPrintDialog;
FSaveDlg: TFileSaveDialog;
FExportFileName: string;
FMsgDlg: TTaskDialog;
FGrid: TcxGrid;
FOpenAfterExport: Boolean;
FPDFExport: TfrxPDFExport;
public
// constructor Create(SourceDataSet: TFDMemTable;
// TargetDataSet: TFDMemTable;
// Report: TfrxReport;
// ReportDataSet: TfrxDBDataset;
// ReportTypeName: string;
// ReportFileName: string;
// ReportAction: TReportActions);
constructor Create;
destructor Destroy; override;
procedure PrintPreview;
procedure ExportToExcel;
procedure ExportToPDF;
property SourceDataSet: TFDMemTable read FSourceDataSet write FSourceDataSet;
property TargetDataSet: TFDMemTable read FTargetDataSet write FTargetDataSet;
property Report: TfrxReport read FReport write FReport;
property ReportDataSet: TfrxDBDataset read FReportDataSet write FReportDataSet;
property ReportTypeName: string read FReportTypeName write FReportTypeName;
property ReportFileName: string read FReportFileName write FReportFileName;
property ReportAction: TReportActions read FReportAction write FReportAction;
property ExportFileName: string read FExportFileName write FExportFileName;
property Grid: TcxGrid read FGrid write FGrid;
property OpenAfterExport: Boolean read FOpenAfterExport write FOpenAfterExport;
end;
implementation
{ TVBPrintExportData }
{ TVBPrintExportData }
constructor TVBPrintExportData.Create;
begin
FSourceDataSet := nil;
FTargetDataSet := nil;
FReport := nil;
FReportDataSet := nil;
FReportTypeName := '';
FReportFileName := '';
FReportAction := raPreview;
FPrintDlg := TdxPrintDialog.Create(nil);
FSaveDlg := TFileSaveDialog.Create(nil);
FPDFExport := TfrxPDFExport.Create(nil);
// FSourceDataSet := SourceDataSet;
// FTargetDataSet := TargetDataSet;
// FReport := Report;
// FReportDataSet := ReportDataSet;
// FReportTypeName := ReportTypeName;
// FReportFileName := ReportFileName;
// FReportAction := ReportAction;
// FPrintDlg := TdxPrintDialog.Create(nil);
end;
destructor TVBPrintExportData.Destroy;
begin
FPrintDlg.Free;
FSaveDlg.Free;
FPDFExport.Free;
inherited;
end;
procedure TVBPrintExportData.ExportToExcel;
var
DestFolder: string;
FileSaved: Boolean;
begin
inherited;
DestFolder := ExtractFilePath(FExportFileName);
TDirectory.CreateDirectory(DestFolder);
FSaveDlg.DefaultExtension := 'xlsx';
FSaveDlg.DefaultFolder := DestFolder;
FSaveDlg.FileName := ExtractFileName(FExportFilename);
FileSaved := FSaveDlg.Execute;
if not FileSaved then
Exit;
// UseLatestCommonDialogs := True;
if TFile.Exists(FSaveDlg.FileName) then
try
FMsgDlg := TTaskDialog.Create(nil);
FMsgDlg.Caption := 'VB Applications';
FMsgDlg.Title := 'File Overwrite';
FMsgDlg.Text :=
'The file ' + FSaveDlg.FileName + ' already exists.' + CRLF +
'Do you want to overwrite this file?';
FMsgDlg.MainIcon := tdiInformation;
FMsgDlg.DefaultButton := tcbYes;
FMsgDlg.CommonButtons := [tcbYes, tcbNo];
if FMsgDlg.Execute then
if FMsgDlg.ModalResult = mrNo then
Exit;
finally
FMsgDlg.Free;
end;
FExportFileName := FSaveDlg.FileName;
ExportGridToXLSX(
FExportFileName, // Filename to export
FGrid, // Grid whose data must be exported
True, // Expand groups
True, // Save all records (Selected and un-selected ones)
True, // Use native format
'xlsx');
if FOpenAfterExport then
ShellExecute(0, 'open', PChar('Excel.exe'), PChar('"' + ExportFileName + '"'), nil, SW_SHOWNORMAL)
end;
procedure TVBPrintExportData.ExportToPDF;
var
FileSaved: Boolean;
DestFolder: string;
begin
inherited;
// FTargetDataSet.Close;
// FTargetDataSet.Data := SourceDataSet.Data;
FReportDataSet.DataSet := TargetDataSet;
FReport.DataSets.Clear;
FReport.DataSets.Add(FReportDataSet);
if FReportDataSet.Name <> 'fdsPriceHistory' then
FReport.LoadFromFile(ReportFileName, False);
TfrxMemoView(Report.FindObject('lblReportTypeName')).Text := FReportTypeName;
FPDFExport.ShowDialog := False;
FPDFExport.Background := True;
FPDFExport.OpenAfterExport := FOpenAfterExport;
FPDFExport.OverwritePrompt := True;
FPDFExport.ShowProgress := True;
DestFolder := ExtractFilePath(FExportFileName);
TDirectory.CreateDirectory(DestFolder);
FSaveDlg.DefaultExtension := 'pdf';
FSaveDlg.DefaultFolder := DestFolder;
FSaveDlg.FileName := ExtractFileName(FExportFilename);
FileSaved := FSaveDlg.Execute;
if not FileSaved then
Exit;
if TFile.Exists(FSaveDlg.FileName) then
try
FMsgDlg := TTaskDialog.Create(nil);
FMsgDlg.Caption := 'VB Applications';
FMsgDlg.Title := 'File Overwrite';
FMsgDlg.Text :=
'The file ' + FSaveDlg.FileName + ' already exists.' + CRLF +
'Do you want to overwrite this file?';
FMsgDlg.MainIcon := tdiInformation;
FMsgDlg.DefaultButton := tcbYes;
FMsgDlg.CommonButtons := [tcbYes, tcbNo];
if FMsgDlg.Execute then
if FMsgDlg.ModalResult = mrNo then
Exit;
finally
FMsgDlg.Free;
end;
FExportFileName := FSaveDlg.FileName;
FPDFExport.FileName := FExportFileName;
if FReport.PrepareReport then
FReport.Export(FPDFExport);
// if TFile.Exists(dlgFileSave.FileName) then
// begin
// Beep;
// if DisplayMsg(Application.Title,
// 'File Overwrite',
// 'The file ' + dlgFileSave.FileName + ' already exists. Do you want to overwrite this file?',
// mtConfirmation,
// [mbYes, mbNo]
// ) = mrNo then
// Exit;
// end;
end;
procedure TVBPrintExportData.PrintPreview;
begin
// if FSourceDataSet <> nil then
// begin
// FTargetDataSet.Close;
// FTargetDataSet.Data := SourceDataSet.Data;
// end;
FReportDataSet.DataSet := TargetDataSet;
FReport.DataSets.Clear;
FReport.DataSets.Add(FReportDataSet);
if FReportDataSet.Name <> 'fdsPriceHistory' then
FReport.LoadFromFile(ReportFileName, False);
TfrxMemoView(Report.FindObject('lblReportTypeName')).Text := FReportTypeName;
case FReportAction of
raPreview, raPrint:
begin
if FReport.PrepareReport then
if ReportAction = raPreview then
FReport.ShowPreparedReport
else
begin
if FPrintDlg.Execute then
begin
FReport.PrintOptions.Copies :=
FPrintDlg.DialogData.Copies;
FReport.Print;
end;
end;
end;
end;
end;
end.
|
{***************************************************************************}
{ }
{ DelphiWebDriver }
{ }
{ Copyright 2017 inpwtepydjuf@gmail.com }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit Commands.PostExecute;
interface
uses
Sessions,
Vcl.Forms,
CommandRegistry,
HttpServerCommand;
type
/// <summary>
/// Handles POST /session/{sessionId}/execute
/// </summary>
/// <remarks>
/// Only for certain specific controls - StringGrids and ToolButtons
/// </remarks>
TPostExecuteCommand = class(TRestCommand)
private
/// <summary>
/// Right click on the control
/// </summary>
/// <remarks>
/// Currently only implemented for some controls
/// </remarks>
procedure RightClick (AOwner: TForm; Const control: String);
/// <summary>
/// Right click on the control
/// </summary>
/// <remarks>
/// Currently only implemented for some controls
/// </remarks>
procedure LeftClick (AOwner: TForm; Const control: String);
/// <summary>
/// Right click on the control
/// </summary>
/// <remarks>
/// Currently only implemented for some controls
/// </remarks>
procedure DoubleClick (AOwner: TForm; Const control: String);
function OKResponse(const sessionId, control: String): String;
public
class function GetCommand: String; override;
class function GetRoute: String; override;
/// <summary>
/// Highjacked for left and right clicks on controls
/// </summary>
procedure Execute(AOwner: TForm); override;
end;
implementation
uses
Vcl.ComCtrls,
System.StrUtils,
System.SysUtils,
Vcl.Grids,
System.Classes,
System.JSON;
procedure TPostExecuteCommand.Execute(AOwner: TForm);
var
jsonObj : TJSONObject;
argsObj : TJsonValue;
script: String;
control: String;
begin
// Decode the incoming JSON and see what we have
jsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(self.StreamContents),0) as TJSONObject;
try
(jsonObj as TJsonObject).TryGetValue<String>('script', script);
//(jsonObj as TJsonObject).TryGetValue<String>('args', value);
argsObj := jsonObj.Get('args').JsonValue;
(argsObj as TJsonObject).TryGetValue<String>('first', control);
finally
jsonObj.Free;
end;
try
if (script = 'right click') then
RightClick(AOwner, control)
else if (script = 'left click') then
LeftClick(AOwner, control)
else if (script = 'double click') then
DoubleClick(AOwner, control)
else
Error(404);
except on e: Exception do
Error(404);
end;
end;
procedure TPostExecuteCommand.DoubleClick (AOwner: TForm; Const control: String);
begin
end;
procedure TPostExecuteCommand.LeftClick (AOwner: TForm; Const control: String);
begin
end;
procedure TPostExecuteCommand.RightClick (AOwner: TForm; Const control: String);
var
gridTop, top: Integer;
gridLeft, left: Integer;
parent, comp: TComponent;
values : TStringList;
parentGrid: TStringGrid;
const
Delimiter = '.';
begin
// find the control / component - currently only implemented for stringgrids
if (ContainsText(control, Delimiter)) then
begin
values := TStringList.Create;
try
values.Delimiter := Delimiter;
values.StrictDelimiter := True;
values.DelimitedText := control;
// Get parent
parent := AOwner.FindComponent(values[0]);
if (parent is TStringGrid) then
begin
parentGrid := (parent as TStringGrid);
gridTop := parentGrid.top;
gridLeft := parentGrid.left;
left := parentGrid.CellRect(StrToInt(values[1]),StrToInt(values[2])).left -gridLeft +1;
top := parentGrid.CellRect(StrToInt(values[1]),StrToInt(values[2])).top -gridTop +1;
// Cell 2,2 : left = 179, top = 85 ???
// Here we have to call into the grid itself somehow
ResponseJSON(OKResponse(self.Params[2], control));
end
else
Error(404);
finally
values.free;
end;
end
else
begin
comp := AOwner.FindComponent(control);
if comp <> nil then
begin
if (comp is TToolButton) then
begin
if (comp as TToolButton).PopupMenu <> nil then
begin
// Popup a menu item here
(comp as TToolButton).PopupMenu.Popup(100, 100);
ResponseJSON(OKResponse(self.Params[2], control));
end
else
begin
Error(404);
end;
end;
end
else
Error(404);
end;
end;
function TPostExecuteCommand.OKResponse(const sessionId, control: String): String;
var
jsonObject: TJSONObject;
begin
jsonObject := TJSONObject.Create;
jsonObject.AddPair(TJSONPair.Create('sessionId', sessionId));
// jsonObject.AddPair(TJSONPair.Create('status', '0'));
jsonObject.AddPair(TJSONPair.Create('value', control));
result := jsonObject.ToString;
end;
class function TPostExecuteCommand.GetCommand: String;
begin
result := 'POST';
end;
class function TPostExecuteCommand.GetRoute: String;
begin
result := '/session/(.*)/execute';
end;
end.
|
unit DBConnection;
interface
uses
IOUtils,
Generics.Collections, Classes, IniFiles,
Aurelius.Commands.Listeners,
Aurelius.Drivers.Interfaces,
Aurelius.Engine.AbstractManager,
Aurelius.Engine.ObjectManager,
Aurelius.Engine.DatabaseManager,
Aurelius.Sql.SQLite,
Aurelius.Mapping.Explorer,
DMConnection;
type
TDBConnection = class sealed
private
class var FInstance: TDBConnection;
private
FConnection: IDBConnection;
FDMConnection: TDMConn;
FMappingExplorer: TMappingExplorer;
FListeners: TList<ICommandExecutionListener>;
procedure PrivateCreate;
procedure PrivateDestroy;
function DatabaseFileName: string;
function CreateConnection: IDBConnection;
function GetConnection: IDBConnection;
procedure AddListeners(AManager: TAbstractManager);
procedure MapClasses;
public
class function GetInstance: TDBConnection;
procedure AddCommandListener(Listener: ICommandExecutionListener);
class procedure AddLines(List: TStrings; Sql: string;
Params: TEnumerable<TDBParam>);
property Connection: IDBConnection read GetConnection;
function HasConnection: boolean;
function CreateObjectManager: TObjectManager;
function GetNewDatabaseManager: TDatabaseManager;
procedure UnloadConnection;
end;
implementation
uses
Variants, DB, SysUtils, TypInfo, Aurelius.Drivers.AnyDac,
BeaconItem, Routs, BusExitTime, BusLine, BusStop, Aurelius.Mapping.Setup;
{ TConexaoUnica }
procedure TDBConnection.AddCommandListener(Listener: ICommandExecutionListener);
begin
FListeners.Add(Listener);
end;
class procedure TDBConnection.AddLines(List: TStrings; Sql: string;
Params: TEnumerable<TDBParam>);
var
P: TDBParam;
ValueAsString: string;
HasParams: boolean;
begin
List.Add(Sql);
if Params <> nil then
begin
HasParams := False;
for P in Params do
begin
if not HasParams then
begin
List.Add('');
HasParams := True;
end;
if P.ParamValue = Variants.Null then
ValueAsString := 'NULL'
else if P.ParamType = ftDateTime then
ValueAsString := '"' + DateTimeToStr(P.ParamValue) + '"'
else if P.ParamType = ftDate then
ValueAsString := '"' + DateToStr(P.ParamValue) + '"'
else
ValueAsString := '"' + VarToStr(P.ParamValue) + '"';
List.Add(P.ParamName + ' = ' + ValueAsString + ' (' +
GetEnumName(TypeInfo(TFieldType), Ord(P.ParamType)) + ')');
end;
end;
List.Add('');
List.Add('================================================');
end;
procedure TDBConnection.AddListeners(AManager: TAbstractManager);
var
Listener: ICommandExecutionListener;
begin
for Listener in FListeners do
AManager.AddCommandListener(Listener);
end;
function TDBConnection.DatabaseFileName: string;
begin
Result :=
IOUtils.TPath.Combine(IOUtils.TPath.GetDocumentsPath, 'aurelius.sqlite');
end;
procedure TDBConnection.UnloadConnection;
begin
if FConnection <> nil then
begin
FConnection.Disconnect;
FConnection := nil;
FDMConnection := nil;
FMappingExplorer := nil;
end;
end;
function TDBConnection.CreateConnection: IDBConnection;
begin
if FConnection <> nil then
Exit(FConnection);
FDMConnection := TDMConn.Create(nil);
FDMConnection.FDConnection.Params.Values['Database'] := DatabaseFileName;
FDMConnection.FDConnection.Connected := True;
FConnection := TAnyDacConnectionAdapter.Create(FDMConnection.FDConnection, False);
MapClasses;
GetNewDatabaseManager.UpdateDatabase;
Result := FConnection;
end;
function TDBConnection.GetConnection: IDBConnection;
begin
Result := CreateConnection;
if Result = nil then
raise Exception.Create
('Não foi possível se conectar ao banco de dados.');
if not Result.IsConnected then
Result.Connect;
end;
class function TDBConnection.GetInstance: TDBConnection;
begin
if FInstance = nil then
begin
FInstance := TDBConnection.Create;
FInstance.PrivateCreate;
end;
Result := FInstance;
end;
function TDBConnection.GetNewDatabaseManager: TDatabaseManager;
begin
Result := TDatabaseManager.Create(Connection);
AddListeners(Result);
end;
function TDBConnection.CreateObjectManager: TObjectManager;
begin
Result := TObjectManager.Create(Connection);
Result.OwnsObjects := True;
AddListeners(Result);
end;
function TDBConnection.HasConnection: boolean;
begin
Result := CreateConnection <> nil;
end;
procedure TDBConnection.MapClasses;
var
MapSetupSQLite: TMappingSetup;
begin
MapSetupSQLite := TMappingSetup.Create;
try
MapSetupSQLite.MappedClasses.RegisterClass(TBeaconItem);
MapSetupSQLite.MappedClasses.RegisterClass(TBusStop);
MapSetupSQLite.MappedClasses.RegisterClass(TBusLine);
MapSetupSQLite.MappedClasses.RegisterClass(TRout);
MapSetupSQLite.MappedClasses.RegisterClass(TBusExitTime);
FMappingExplorer := TMappingExplorer.Create(MapSetupSQLite);
finally
MapSetupSQLite.Free;
end;
end;
procedure TDBConnection.PrivateCreate;
begin
FListeners := TList<ICommandExecutionListener>.Create;
end;
procedure TDBConnection.PrivateDestroy;
begin
UnloadConnection;
FListeners.Free;
end;
initialization
finalization
if TDBConnection.FInstance <> nil then
begin
TDBConnection.FInstance.PrivateDestroy;
TDBConnection.FInstance.Free;
TDBConnection.FInstance := nil;
end;
end.
|
unit ServiceModule;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs;
type
TService1 = class(TService)
procedure ServiceShutdown(Sender: TService);
procedure ServiceStart(Sender: TService; var Started: Boolean);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
procedure ServiceCreate(Sender: TObject);
private
{ Private declarations }
public
function GetServiceController: TServiceController; override;
{ Public declarations }
end;
var
Service1: TService1;
implementation
uses
AlfaPetServerUnit, IOUtils;
{$R *.dfm}
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
Service1.Controller(CtrlCode);
end;
function TService1.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TService1.ServiceCreate(Sender: TObject);
begin
Self.Name := TFile.ReadAllText(TPath.ChangeExtension(ParamStr(0), '.servicename.txt'));
Self.DisplayName := TFile.ReadAllText(TPath.ChangeExtension(ParamStr(0), '.displayname.txt'));
end;
procedure TService1.ServiceShutdown(Sender: TService);
begin
StopAlfaPetServer;
end;
procedure TService1.ServiceStart(Sender: TService; var Started: Boolean);
begin
StartAlfaPetServer;
end;
procedure TService1.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
StopAlfaPetServer;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.