text stringlengths 14 6.51M |
|---|
unit configuration;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ Configuration }
Configuration=class
private
KeyValueToken:Char;
KEY_ServerName:UnicodeString;
KEY_ServerDatabase:UnicodeString;
KEY_ServerUser:UnicodeString;
KEY_ServerPassword:UnicodeString;
KEY_LocationId:UnicodeString;
KEY_LocalDBPath:UnicodeString;
m_strConfigFile, m_strServerName, m_strServerDatabase:UnicodeString;
m_strServerUser, m_strServerPassword, m_strLocalDBPath :UnicodeString;
function GetConfigFile: UnicodeString;
function GetLocalDBPath: UnicodeString;
function GetServerDatabase: UnicodeString;
function GetServerName: UnicodeString;
function GetServerPassword: UnicodeString;
function GetServerUser: UnicodeString;
procedure SetConfigFile(AValue: UnicodeString);
procedure SetLocalDBPath(AValue: UnicodeString);
procedure SetServerDatabase(AValue: UnicodeString);
procedure SetServerName(AValue: UnicodeString);
procedure SetServerPassword(AValue: UnicodeString);
procedure SetServerUser(AValue: UnicodeString);
procedure ReadConfigFile;
procedure LoadDefaultValues;
public
DefaultConfigFile, LocalDBFileName: UnicodeString;
m_bIsReadSuccess:BOOLEAN;
constructor Configuration;
constructor Configuration(configFile:UnicodeString);
function ServerConnString:UnicodeString;
function LocalConnString:UnicodeString;
function ExecutePath:UnicodeString;
property ConfigFile:UnicodeString read GetConfigFile write SetConfigFile;
property ServerName:UnicodeString read GetServerName write SetServerName;
property ServerDatabase:UnicodeString read GetServerDatabase write SetServerDatabase;
property ServerUser:UnicodeString read GetServerUser write SetServerUser;
property ServerPassword:UnicodeString read GetServerPassword write SetServerPassword;
property LocalDBPath:UnicodeString read GetLocalDBPath write SetLocalDBPath;
end;
implementation
{ Configuration }
function Configuration.GetConfigFile: UnicodeString;
begin
Result:=m_strConfigFile;
end;
function Configuration.GetLocalDBPath: UnicodeString;
begin
Result:= m_strLocalDBPath;
end;
function Configuration.GetServerDatabase: UnicodeString;
begin
Result:=m_strServerDatabase;
end;
function Configuration.GetServerName: UnicodeString;
begin
Result:=m_strServerName;
end;
function Configuration.GetServerPassword: UnicodeString;
begin
Result:=m_strServerPassword;
end;
function Configuration.GetServerUser: UnicodeString;
begin
Result:=m_strServerUser;
end;
procedure Configuration.SetConfigFile(AValue: UnicodeString);
begin
m_strConfigFile:=AValue;
end;
procedure Configuration.SetLocalDBPath(AValue: UnicodeString);
begin
m_strLocalDBPath:=AValue;
end;
procedure Configuration.SetServerDatabase(AValue: UnicodeString);
begin
m_strServerDatabase:=AValue;
end;
procedure Configuration.SetServerName(AValue: UnicodeString);
begin
m_strServerName:=AValue;
end;
procedure Configuration.SetServerPassword(AValue: UnicodeString);
begin
m_strServerPassword:=AValue;
end;
procedure Configuration.SetServerUser(AValue: UnicodeString);
begin
m_strServerUser:=AValue;
end;
procedure Configuration.ReadConfigFile;
begin
m_bIsReadSuccess:=False;
end;
procedure Configuration.LoadDefaultValues;
begin
DefaultConfigFile:=:='Config.ini';
LocalDbFile:='panel.db';
KeyValueToken:='=';
KEY_ServerName:='SERVER_NAME';
KEY_ServerDatabase:='SERVER_DB';
KEY_ServerUser:='SERVER_USER';
KEY_ServerPassword:='SERVER_PSWD';
KEY_LocationId:='LOCATION_ID';
KEY_LocalDBPath:='LOCALDBPATH';
end;
constructor Configuration.Configuration;
begin
LoadDefaultValues;
ConfigFile:=DefaultConfigFile;
ReadConfigFile;
end;
constructor Configuration.Configuration(configFile: UnicodeString);
begin
LoadDefaultValues;
m_strConfigFile:=configFile;
ReadConfigFile;
end;
function Configuration.ServerConnString: UnicodeString;
begin
Result:= Format('server=%s;user id=%s;password=%s;initial catalog=%s'
[m_strServerName, m_strServerUser, m_strServerPassword,
m_strServerDatabase]);
end;
function Configuration.LocalConnString: UnicodeString;
begin
end;
function Configuration.ExecutePath: UnicodeString;
begin
end;
end.
|
unit UFtpImagen;
interface
uses
SysUtils, strutils, DBClient,
UDAOParametro;
type
TFtpImagen = class
private
FHostFtpImg : string; {DIRECCION FTP DESCARGA DE LAS IMAGENES}
FPuertoFtpImg : word; {PUERTO DEL FTP DE IMAGENES}
FUsuarioFtpImg : string; {USUARIO DEL FTP DE IMAGENES}
FPasswordFtpImg : string; {PASSWORD DEL USUARIO FTP DE IMAGENES}
FCarpetaRaizFtpImg : string; {CARPETA RAIZ DEL FTP DE IMAGENES TIF}
FCarpetaRaizFtpPdf : string; {CARPETA RAIZ DEL FTP DE IMAGENES PDF}
FHostRemotoFtpImg : string; {DIRECCION FTP DESCARGA DE LAS IMAGENES PARA ACCESO REMOTO}
FUsuarioConFtpImg : string; {USUARIO DEL FTP DE IMAGENES DE SOLO LECTURA}
FPasswordConFtpImg : string; {PASSWORD DEL USUARIO FTP DE IMAGENES DE SOLO CONSULTA}
FFechaAcceso : TDateTime;{FECHA EN LA QUE SE ACCESA AL SERVIDOR DE BASE DE DATOS}
public
constructor Create;
{PROPERTIES}
Property HostFtpImg : string read FHostFtpImg write FHostFtpImg;
Property PuertoFtpImg : word read FPuertoFtpImg write FPuertoFtpImg;
Property UsuarioFtpImg : string read FUsuarioFtpImg write FUsuarioFtpImg;
Property PasswordFtpImg : string read FPasswordFtpImg write FPasswordFtpImg;
Property CarpetaRaizFtpImg : string read FCarpetaRaizFtpImg write FCarpetaRaizFtpImg;
Property CarpetaRaizFtpPdf : string read FCarpetaRaizFtpPdf write FCarpetaRaizFtpPdf;
Property HostRemotoFtpImg : string read FHostRemotoFtpImg write FHostRemotoFtpImg;
Property UsuarioConFtpImg : string read FUsuarioConFtpImg write FUsuarioConFtpImg;
Property PasswordConFtpImg : string read FPasswordConFtpImg write FPasswordConFtpImg;
Property FechaAcceso : TDateTime read FFechaAcceso write FFechaAcceso;
{METODOS}
procedure ConfigurarFtpImg;
end;
implementation
{ TFTP }
{$REGION 'METODOS'}
procedure TFtpImagen.ConfigurarFtpImg;
var
CodiErro : Integer;
DatoPara : TDAOParametro;
NumePuer : string;
ParaImag : TClientDataSet;
begin
try
DatoPara := TDAOParametro.create;
ParaImag := TclientDataSet.create(nil);
ParaImag := DatoPara.BuscarParametros('FTP');
ParaImag.First;
if ParaImag.RecordCount > 0 then
begin
FHostFtpImg := IfThen(ParaImag.Locate('PROPIEDAD','HOST',[]),
ParaImag.Fields[2].value,'');
NumePuer := IfThen(ParaImag.Locate('PROPIEDAD','PUERTO',[]),
ParaImag.Fields[2].value,'');
FUsuarioFtpImg := IfThen(ParaImag.Locate('PROPIEDAD','USUARIO',[]),
ParaImag.Fields[2].value,'');
FPasswordFtpImg := IfThen(ParaImag.Locate('PROPIEDAD','PASSWORD',[]),
ParaImag.Fields[2].value,'');
if ParaImag.Locate('PROPIEDAD','CARPETARAIZ',[]) then
begin
FCarpetaRaizFtpImg := ifThen(AnsiRightStr(ParaImag.Fields[2].value,1) = '\',
ParaImag.Fields[2].value,ParaImag.Fields[2].value + '\');
{LA RUTA RAIZ EN EL FTP DE LAS IMAGENES PDF ES CASI LA MISMA A LA DE LOS TIF,
TERMINA EN 'FE\'}
FCarpetaRaizFtpPdf := LeftStr(FCarpetaRaizFtpImg,Length(FCarpetaRaizFtpImg)-1)+ 'FE\';
end
else
begin
FCarpetaRaizFtpImg := '';
FCarpetaRaizFtpPdf := '';
end;
FHostRemotoFtpImg := IfThen(ParaImag.Locate('PROPIEDAD','HOSTREMOTO',[]),
ParaImag.Fields[2].value,'');
FUsuarioConFtpImg := IfThen(ParaImag.Locate('PROPIEDAD','USUARIOCONS',[]),
ParaImag.Fields[2].value,'');
FPasswordConFtpImg := IfThen(ParaImag.Locate('PROPIEDAD','PASSWORDCONS',[]),
ParaImag.Fields[2].value,'');
FechaAcceso := ParaImag .Fields[3].value;
if (Trim(FHostFtpImg) = '') or (Trim(NumePuer) = '') or (Trim(FUsuarioFtpImg) = '') or
(Trim(FPasswordFtpImg) = '') or (Trim(FCarpetaRaizFtpImg) = '') or
(Trim(FHostRemotoFtpImg) = '') or (Trim(FUsuarioConFtpImg) = '') or
(Trim(FPasswordConFtpImg) = '') then
raise Exception.Create('La información de Parámetros está incompleta.')
else
begin
val(NumePuer,FPuertoFtpImg,CodiErro);
if CodiErro <> 0 then
raise Exception.Create('Valor incorrecto en el Puerto del FTP: [' + NumePuer + '].');
end;
end
else
raise Exception.Create('No existe Información de Parámetros para el FTP de Imágenes.');
except
on e:exception do
raise Exception.Create('Error configurando FTP de Imágenes. ' + #10#13 + '* '
+ e.Message);
end;
end;
{$ENDREGION}
{$REGION 'CREATE AND DESTRUCTOR'}
constructor TFtpImagen.Create;
begin
ConfigurarFtpImg;
end;
{$ENDREGION}
{$REGION 'GETTERS Y SETTERS'}
{$ENDREGION}
end.
|
unit Form.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls;
type
TFormMain = class(TForm)
GroupBox1: TGroupBox;
Bevel1: TBevel;
Bevel2: TBevel;
Bevel3: TBevel;
Bevel4: TBevel;
btnPostMessage1: TButton;
btnShowSubscribers: TButton;
Edit1: TEdit;
chkFastAnimataion: TCheckBox;
btnExit: TButton;
ColorBox1: TColorBox;
GridPanel1: TGridPanel;
btnPause: TButton;
btnAnimate: TButton;
tmrReady: TTimer;
procedure FormCreate(Sender: TObject);
procedure btnAnimateClick(Sender: TObject);
procedure btnExitClick(Sender: TObject);
procedure btnPauseClick(Sender: TObject);
procedure btnPostMessage1Click(Sender: TObject);
procedure btnShowSubscribersClick(Sender: TObject);
procedure chkFastAnimataionClick(Sender: TObject);
procedure ColorBox1Change(Sender: TObject);
procedure Edit1DblClick(Sender: TObject);
procedure tmrReadyTimer(Sender: TObject);
private
procedure UpdateControlsActivity(IsEnable: boolean);
{ Private declarations }
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.dfm}
uses Messaging.EventBus, Global.MessagesID, Unit1, Unit2;
procedure TFormMain.FormCreate(Sender: TObject);
begin
ReportMemoryLeaksOnShutdown := True;
end;
procedure TFormMain.UpdateControlsActivity(IsEnable: boolean);
begin
btnShowSubscribers.Enabled := not IsEnable;
btnPostMessage1.Enabled := IsEnable;
Edit1.Enabled := IsEnable;
chkFastAnimataion.Enabled := IsEnable;
ColorBox1.Enabled := IsEnable;
btnPause.Enabled := IsEnable;
btnAnimate.Enabled := IsEnable;
end;
procedure TFormMain.btnShowSubscribersClick(Sender: TObject);
var
frm1: TForm1;
frm2: TForm2;
begin
UpdateControlsActivity(True);
// ---
frm1 := TForm1.Create(Application);
frm1.Visible := True;
frm1.Left := Left + Width;
frm1.Top := Top;
frm1.Show();
// ---
frm2 := TForm2.Create(Application);
frm2.Visible := True;
frm2.Left := frm1.Left + frm1.Width;
frm2.Top := Top;
frm2.Show();
end;
procedure TFormMain.btnPostMessage1Click(Sender: TObject);
var
AMessage: TEventMessage;
begin
AMessage.TagString := Edit1.Text;
TEventBus._Post(EB_BOARD_StartScroll, AMessage);
end;
procedure TFormMain.chkFastAnimataionClick(Sender: TObject);
var
AMessage: TEventMessage;
begin
AMessage.TagBoolean := chkFastAnimataion.Checked;
TEventBus._Post(EB_BOARD_ChangeSpeed, AMessage);
end;
procedure TFormMain.ColorBox1Change(Sender: TObject);
var
AMessage: TEventMessage;
begin
AMessage.TagInt := ColorBox1.Selected;
TEventBus._Post(EB_BOARD_ChangeColor, AMessage);
end;
procedure TFormMain.btnPauseClick(Sender: TObject);
begin
TEventBus._Ping(EB_BOARD_Pause);
end;
procedure TFormMain.btnAnimateClick(Sender: TObject);
begin
TEventBus._Ping(EB_BOARD_Animate);
end;
procedure TFormMain.btnExitClick(Sender: TObject);
begin
Close;
end;
procedure TFormMain.Edit1DblClick(Sender: TObject);
begin
Edit1.SelectAll;
end;
procedure TFormMain.tmrReadyTimer(Sender: TObject);
begin
tmrReady.Enabled := False;
Self.UpdateControlsActivity(False);
end;
end.
|
unit LogEntity;
{$mode objfpc}{$H+}
{$INTERFACES CORBA}
interface
uses
Classes, SysUtils, SyncObjs,
LogItem, LogManager, LogEntityFace;
type
{ TLog }
TLog = class(TInterfacedObject, ILog)
public
constructor Create(const aManager: TLogManager; const aName: string);
private
fManager: TLogManager;
fName: string;
fLock: TCriticalSection;
public
property Manager: TLogManager read fManager;
property Name: string read fName;
procedure Write(const aText: string);
procedure Write(const aTag: string; const aText: string);
procedure Write(const aTag: TStandardLogTag; const aText: string);
destructor Destroy; override;
end;
implementation
{ TLog }
constructor TLog.Create(const aManager: TLogManager; const aName: string);
begin
inherited Create;
fManager := aManager;
fName := aName;
fLock := TCriticalSection.Create;
end;
procedure TLog.Write(const aText: string);
begin
Write(logTagDebug, aText);
end;
procedure TLog.Write(const aTag: string; const aText: string);
var
pItem: PLogItem;
begin
fLock.Enter;
if not assigned(self) then exit;
new(pItem, Init);
pItem^.Tag := aTag;
pItem^.ObjectName := Name;
pItem^.Text := aText;
Manager.Write(pItem);
fLock.Leave;
end;
procedure TLog.Write(const aTag: TStandardLogTag; const aText: string);
var
tagCaption: string;
begin
if not assigned(self) then exit;
tagCaption := manager.StandardLogTagToString.ToString(aTag);
write(tagCaption, aText);
end;
destructor TLog.Destroy;
begin
FreeAndNil(fLock);
inherited Destroy;
end;
end.
|
program _12_28;
function Pop(var s: string):char;
var
c:char;
begin
c:=s[length(s)];
Delete(s,length(s),1);
Pop:=c
end;
function GreaterOrder(a,b: char):boolean;
begin
if (b='+') or (b='-') then GreaterOrder:=true
else if (b='*') or (b='/') then GreaterOrder:=(a='*') or (a='/')
else GreaterOrder:=true;
end;
function ToRPN(math: string): string;
var
res, stack: string;
i: integer;
begin
stack:='$';
for i:=1 to length(math) do
if ('a'<=math[i]) AND ('z'>= math[i]) then res:=res+math[i]
else if math[i]='(' then stack:=stack+'('
else if math[i]=')' then begin
while stack[length(stack)]<>'(' do
res:=res+Pop(stack);
Pop(stack) end
else begin
while not GreaterOrder(math[i],stack[length(stack)]) do res:=res+Pop(stack);
stack:=stack+math[i];
end;
for i:=1 to length(stack)-1 do res:=res+Pop(stack);
ToRPN:=res; exit
end;
procedure PrintRPN(var f: text);
var
math: string;
begin
reset(f);
while not EoF(f) do begin
readln(f,math);
writeln(ToRPN(math))
end
end;
var
f: text;
begin
assign(f,'task12.txt');
PrintRPN(f);
end. |
PROGRAM ReadDigitPrgm(INPUT, OUTPUT);
VAR
D, S: INTEGER;
PROCEDURE ReadDigit(VAR F: TEXT; VAR D: INTEGER);
{Считывает текущий символ из файла, если он - цифра, возвращает его
преобразуя в значение типа INTEGER. Если считанный символ не цифра
возвращает -1}
VAR
Ch: CHAR;
BEGIN{ReadDigit}
IF NOT EOLN(F)
THEN
BEGIN
READ(F, Ch);
IF Ch = '0' THEN D := 0 ELSE
IF Ch = '1' THEN D := 1 ELSE
IF Ch = '2' THEN D := 2 ELSE
IF Ch = '3' THEN D := 3 ELSE
IF Ch = '4' THEN D := 4 ELSE
IF Ch = '5' THEN D := 5 ELSE
IF Ch = '6' THEN D := 6 ELSE
IF Ch = '7' THEN D := 7 ELSE
IF Ch = '8' THEN D := 8 ELSE
IF Ch = '9' THEN D := 9 ELSE
D := -1
END
ELSE
D := -1
END;{ReadDigit}
BEGIN{ReadDigitPrgm}
ReadDigit(INPUT, D);
S := 0;
WHILE D <> -1
DO
BEGIN
S := S + D;
ReadDigit(INPUT, D)
END;
WRITELN(OUTPUT, 'Сумма введенных цифр:', S)
END.{ReadDigitPrgm}
|
program dt;
uses sysutils;
{Initializes date_t as a record with fields dt_day, dt_month, and dt_year, and declares
day_range and month_range as subranges}
type
date_t = record
dt_day: 1..31;
dt_month: 1..12;
dt_year: integer;
end;
day_range = 1..31;
month_range = 1..12;
{Initializes the date with the passed in day, month, and year values}
procedure init_date (var dt : date_t; day : day_range; month : month_range; year : integer);
begin
dt.dt_day := day;
dt.dt_month := month;
dt.dt_year := year;
end;
{Initializes the date with today's current day, month, and year values}
procedure init_date1 (var dt : date_t);
var
day : word;
month : word;
year : word;
begin
DecodeDate (Date, year, month, day);
dt.dt_day := day;
dt.dt_month := month;
dt.dt_year := year;
end;
{Checks if the two dates passed in are equal and returns true if this is the case}
function date_equal (date1 : date_t; date2 : date_t) : boolean;
begin
date_equal := false;
if (date1.dt_day = date2.dt_day) and (date1.dt_month = date2.dt_month) and (date1.dt_year = date2.dt_year) then
date_equal := true;
end;
{Checks if one date comes before another and returns true if so}
function date_less_than (date1 : date_t; date2 : date_t) : boolean;
begin
date_less_than := false;
if (date1.dt_year < date2.dt_year) then
date_less_than := true
else if (date1.dt_year = date2.dt_year) and (date1.dt_month < date2.dt_month) then
date_less_than := true
else if (date1.dt_year = date2.dt_year) and (date1.dt_month = date2.dt_month) and (date1.dt_day < date2.dt_day) then
date_less_than := true;
end;
{Returns the name of the month corresponding to the month integer passed in}
function month_str (month : month_range) : string;
var
month_names: array [1..12] of string = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
begin
month_str := month_names[month];
end;
{Formats the date into a string so it reads Month day, year}
procedure format_date (dt : date_t; var ret_str : string);
var
day_string : string;
year_string : string;
begin
str(dt.dt_day, day_string);
str(dt.dt_year, year_string);
ret_str := month_str(dt.dt_month) + ' ' + day_string + ', ' + year_string;
end;
{Sets the date equal to the next day}
procedure next_day (var dt : date_t);
{Returns true if the year is a leap year}
function leap_year (year : integer) : boolean;
begin
leap_year := false;
if (year mod 4 = 0) then
leap_year := true;
if (year mod 100 = 0) then
leap_year := false;
if (year mod 400 = 0) then
leap_year := true;
end;
{Returns how many days are in the month that is passed in}
function month_length (month: month_range; leap: boolean): day_range;
var
month_num_days : array [1..12] of integer = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
begin
if(month = 2) then
begin
if (leap_year(dt.dt_year)) then
month_length := 29
else
month_length := 28;
end
else
month_length := month_num_days[month];
end;
begin
if (dt.dt_month = 12) and (dt.dt_day = month_length(dt.dt_month, leap_year(dt.dt_year))) then
begin
dt.dt_day := 1;
dt.dt_month := 1;
dt.dt_year := dt.dt_year + 1;
end
else if (dt.dt_day = month_length(dt.dt_month, leap_year(dt.dt_year))) then
begin
dt.dt_day := 1;
dt.dt_month := dt.dt_month + 1;
end
else
dt.dt_day := dt.dt_day + 1;
end;
{Main}
var
d1, d2, d3 : date_t;
format_str : string;
begin
init_date1(d1);
init_date(d2, 30, 12, 1999);
init_date(d3, 1, 1, 2000);
format_date(d1, format_str);
writeln('d1: ' + format_str);
format_date(d2, format_str);
writeln('d2: ' + format_str);
format_date(d3, format_str);
writeln('d3: ' + format_str);
writeln();
writeln('d1 < d2? ' , date_less_than(d1, d2));
writeln('d2 < d3? ' , date_less_than(d2, d3));
writeln();
next_day(d2);
format_date(d2, format_str);
writeln('next day d2: ' + format_str);
writeln('d2 < d3? ' , date_less_than(d2, d3));
writeln('d2 = d3? ' , date_equal(d2, d3));
writeln('d2 > d3? ' , date_less_than(d3, d2));
writeln();
next_day(d2);
format_date(d2, format_str);
writeln('next day d2: ' + format_str);
writeln('d2 = d3? ' , date_equal(d2, d3));
writeln();
init_date(d1, 28, 2, 1529);
format_date(d1, format_str);
writeln('initialized d1 to ' + format_str);
next_day(d1);
format_date(d1, format_str);
writeln('next day d1: ' + format_str);
writeln();
init_date(d1, 28, 2, 1460);
format_date(d1, format_str);
writeln('initialized d1 to ' + format_str);
next_day(d1);
format_date(d1, format_str);
writeln('next day d1: ' + format_str);
writeln();
init_date(d1, 28, 2, 1700);
format_date(d1, format_str);
writeln('initialized d1 to ' + format_str);
next_day(d1);
format_date(d1, format_str);
writeln('next day d1: ' + format_str);
writeln();
init_date(d1, 28, 2, 1600);
format_date(d1, format_str);
writeln('initialized d1 to ' + format_str);
next_day(d1);
format_date(d1, format_str);
writeln('next day d1: ' + format_str);
end.
|
// errorsoft(c)
// MIT License
// this unit is thread safe
unit CalcIntegral;
interface
uses
System.SysUtils;
type
// не сходящийся интеграл
EIntNotConverge = class(Exception);
// интегрируемая функция
TXFunc = reference to function (x: Double): Double;
// функция вычисляющая интеграл для "n" шагов
TIntFunc = function(fx: TXFunc; a, b: Double; n: Integer): Double;
const
// дефолтное количество разбиений для методов с переменным шагом
DefualtN = 20;
// дефолтный таймаут
DefaultTimeOut = 60000;// 60 seconds
// метод левых прямоугольников
function IntLeftRect(fx: TXFunc; a, b: Double; n: Integer): Double;
// метод правых прямоугольников
function IntRightRect(fx: TXFunc; a, b: Double; n: Integer): Double;
// метод срединных прямоугольников
function IntMedianRect(fx: TXFunc; a, b: Double; n: Integer): Double;
// метод трапеций
function IntTrapeze(fx: TXFunc; a, b: Double; n: Integer): Double;
// метод симпсона(парабол)
function IntSimpson(fx: TXFunc; a, b: Double; n: Integer): Double;
// двойной пересчет
function IntDoubleCalc(IntFunc: TIntFunc; fx: TXFunc; a, b: Double; Epsilon: Double;
n: Integer = DefualtN): Double;
// mixed function
function IntMixedCalc(fx: TXFunc; a, b: Double; Epsilon: Double;
n: Integer = DefualtN): Double;
// возвращает кол-во интераций для последнего вычисленного интеграла
function GetLastInterationCount: Integer;
// таймаут
threadvar
TimeOut: Integer;
implementation
uses
System.Classes, System.Math, System.Diagnostics;
threadvar
InterationCount: Integer;
Time: TStopwatch;
function GetLastInterationCount: Integer;
begin
Result := InterationCount;
end;
// возвращает true если поток "убит"
function IsTerminated: Boolean; inline;
begin
Result := TThread.Current.CheckTerminated;
end;
procedure StartCalculation;
begin
Time := TStopwatch.StartNew;
end;
function IsTimeOut: Boolean;
begin
Result := Time.ElapsedMilliseconds > DefaultTimeOut;
end;
function IntLeftRect(fx: TXFunc; a, b: Double; n: Integer): Double;
var
x, s, h: Double;
begin
s := 0;
h := (b - a) / n;
x := a;
while x < b do
begin
s := s + fx(x);
x := x + h;
// если поток "убит" выходим из функции не досчитывая
if IsTerminated then
Exit(NaN);
end;
Result := h * s
end;
function IntRightRect(fx: TXFunc; a, b: Double; n: Integer): Double;
var
x, s, h: Double;
begin
s := 0;
h := (b - a) / n;
x := a + h;
while x < b + h do
begin
s := s + fx(x);
x := x + h;
// если поток "убит" выходим из функции не досчитывая
if IsTerminated then
Exit(NaN);
end;
Result := h * s
end;
function IntMedianRect(fx: TXFunc; a, b: Double; n: Integer): Double;
var
x, s, h: Double;
begin
s := 0;
h := (b - a) / n;
x := a + h * 0.5;
while x < b do
begin
s := s + fx(x);
x := x + h;
// если поток "убит" выходим из функции не досчитывая
if IsTerminated then
Exit(NaN);
end;
Result := h * s
end;
function IntTrapeze(fx: TXFunc; a, b: Double; n: Integer): Double;
var
y1, y2: Double;
x, s, h: Double;
begin
s := 0;
h := (b - a) / n;
y1 := fx(a);
y2 := fx(b);
x := a + h;
while x < b do
begin
s := s + fx(x);
x := x + h;
// если поток "убит" выходим из функции не досчитывая
if IsTerminated then
Exit(NaN);
end;
Result := h * ((y1 + y2) / 2 + s)
end;
function IntSimpson(fx: TXFunc; a, b: Double; n: Integer): Double;
var
h: Double;
s: Double;
i: Integer;
begin
h := (b - a) / n;
s := 0;
i := 1;
while i <= n - 1 do
begin
s := s + fx(a + (i + 1) * h) + fx(a + (i - 1) * h);// s1
s := s + 4 * fx(a + i * h);// s2
i := i + 2;
// если поток "убит" выходим из функции не досчитывая
if IsTerminated then
Exit(NaN);
end;
Result := s * (h / 3);
end;
function IntDoubleCalc(IntFunc: TIntFunc; fx: TXFunc; a, b: Double; Epsilon: Double;
n: Integer = DefualtN): Double;
var
s, s2: Double;
begin
StartCalculation;
InterationCount := n;
s2 := IntFunc(fx, a, b, n);
repeat
s := s2;
n := n * 2;
s2 := IntFunc(fx, a, b, n);
Inc(InterationCount, n);
// если вычисление происходит слишком долго, то интеграл не сходиться
if IsTimeOut then
raise EIntNotConverge.Create('Integral does not converge');
// если поток "убит" выходим из функции не досчитывая
if IsTerminated then
Exit(NaN);
until Abs(s - s2) <= Epsilon;
Result := s2;
end;
// ______ ______ ______ ______
// / \/ \/ \/ \ <- s1
// (a)*---$---*---$---*---$---*---$---*---$---#(b)
// --> \______/\______/\______/\______/ <- s2
// shift
// эксперементальная
function IntMixedCalc(fx: TXFunc; a, b: Double; Epsilon: Double;
n: Integer = DefualtN): Double;
function Int(fx: TXFunc; a, b: Double; n: Integer; IsShift: Boolean): Double;
var
x, s, h: Double;
begin
s := 0;
h := (b - a) / n;
x := a;
if IsShift then
x := x + h * 0.5;
while x < b do
begin
s := s + fx(x);
x := x + h;
// если поток "убит" выходим из функции не досчитывая
if IsTerminated then
Exit(NaN);
end;
Result := s;
end;
var
s: Double;
i1, i2: Double;
ns: Integer;
begin
StartCalculation;
InterationCount := n * 2;
s := Int(fx, a, b, n, False);
s := s + Int(fx, a, b, n, True);
ns := 0;
i1 := s;
repeat
i2 := i1;
ns := ns + n * 2;
n := n * 2;
s := s + Int(fx, a, b, n, True);
i1 := s * ((b - a) / ns);
Inc(InterationCount, n);
// проверяем на сходимость
if IsTimeOut then
raise EIntNotConverge.Create('Integral does not converge');
// если поток "убит" выходим из функции не досчитывая
if IsTerminated then
Exit(NaN);
until Abs(i1 - i2) <= Epsilon;
Result := i1;
end;
initialization
TimeOut := DefaultTimeOut;
end.
|
{
IndySOAP: Global Constants
}
Unit IdSoapConsts;
{$I IdSoapDefines.inc}
Interface
{$I IdSoapVersion.inc}
{$IFNDEF VER240}
Type
TSymbolName = ShortString;
{$ENDIF}
Const
LF = #10;
CR = #13;
EOL_WINDOWS = CR + LF;
EOL_PLATFORM = EOL_WINDOWS;
//
CHAR0 = #0;
BACKSPACE = #8;
TAB = #9;
CHAR32 = ' ';
{$IFDEF DELPHI5}
PathDelim = '\'; // do not localise
{$ENDIF}
MININT = Integer($80000000); // when no default is set on a property
// ITI management
ID_SOAP_CONFIG_FILE_EXT = '.IdSoapCfg'; // do not localise
// Interface specifics
ID_SOAP_INTERFACE_BASE_NAME = 'IIdSoapInterface'; // do not localise MUST be the name of the base IndySoap interface
// ITI related constants
ID_SOAP_ITI_BIN_STREAM_VERSION_OLDEST = 7;
ID_SOAP_ITI_BIN_STREAM_VERSION_SOAPACTION = 8; // When SOAP Action was introduced
ID_SOAP_ITI_BIN_STREAM_VERSION_NAMES = 9; // When Name ReDefining was introduced
ID_SOAP_ITI_BIN_STREAM_VERSION_SOAPOP = 10; // When Doc|Lit support was introduced
ID_SOAP_ITI_BIN_STREAM_VERSION_SESSION = 11; // When Sessional support was introduced
ID_SOAP_ITI_BIN_STREAM_VERSION_INTF_FIX = 12; // When interface inheritance was fixed
ID_SOAP_ITI_BIN_STREAM_VERSION_HEADERS = 13; // When headers were added
ID_SOAP_ITI_BIN_STREAM_VERSION_ATTACHMENTS = 14; // When attachment encoding type was added
ID_SOAP_ITI_BIN_STREAM_VERSION_ENCODINGOVERRIDE = 15; // When encoding override type was added
ID_SOAP_ITI_BIN_STREAM_VERSION_CATEGORY = 16; // When Interface category was added
ID_SOAP_ITI_BIN_STREAM_VERSION_SESSION2 = 17; // Change session from boolean to TIdSoapSessionOption
ID_SOAP_ITI_BIN_STREAM_VERSION_VISIBILITY = 18; // When Interface.Visibility was introduced
ID_SOAP_ITI_BIN_STREAM_VERSION_COMINITMODE = 19; // When Method.WantCOMInit was introduced
ID_SOAP_ITI_BIN_STREAM_VERSION = 19; // SOAP ITI stream version number
ID_SOAP_ITI_XML_STREAM_VERSION = 7; // SOAP ITI stream version number
// ITI XML Node Names
ID_SOAP_ITI_XML_NODE_NAME = 'Name'; // do not localise
ID_SOAP_ITI_XML_NODE_UNITNAME = 'UnitName'; // do not localise
ID_SOAP_ITI_XML_NODE_GUID = 'GUID'; // do not localise
ID_SOAP_ITI_XML_NODE_ANCESTOR = 'Ancestor'; // do not localise
ID_SOAP_ITI_XML_NODE_METHOD = 'Method'; // do not localise
ID_SOAP_ITI_XML_NODE_CALLINGCONVENTION = 'CallingConvention'; // do not localise
ID_SOAP_ITI_XML_NODE_METHODKIND = 'MethodKind'; // do not localise
ID_SOAP_ITI_XML_NODE_METHODSESSION = 'Sessional'; // do not localise
ID_SOAP_ITI_XML_NODE_METHODSESSION2 = 'Session2'; // do not localise
ID_SOAP_ITI_XML_NODE_RESULTTYPE = 'ResultType'; // do not localise
ID_SOAP_ITI_XML_NODE_PARAMETER = 'Parameter'; // do not localise
ID_SOAP_ITI_XML_NODE_PARAMFLAG = 'ParamFlag'; // do not localise
ID_SOAP_ITI_XML_NODE_NAMEOFTYPE = 'NameOfType'; // do not localise
ID_SOAP_ITI_XML_NODE_VERSION = 'Version'; // do not localise
ID_SOAP_ITI_XML_NODE_ITI = 'ITI'; // do not localise
ID_SOAP_ITI_XML_NODE_INTERFACE = 'Interface'; // do not localise
ID_SOAP_ITI_XML_NODE_DOCUMENTATION = 'Documentation'; // do not localise
ID_SOAP_ITI_XML_NODE_REQUEST_NAME = 'RequestMsgName'; // do not localise
ID_SOAP_ITI_XML_NODE_RESPONSE_NAME = 'ResponseMsgName'; // do not localise
ID_SOAP_ITI_XML_NODE_NAMESPACE = 'Namespace'; // do not localise
ID_SOAP_ITI_XML_NODE_SOAPACTION = 'SoapAction'; // do not localise
ID_SOAP_ITI_XML_NODE_SOAPOPTYPE = 'SoapOpType'; // do not localise
ID_SOAP_ITI_XML_NODE_INHERITED_METHOD = 'InheritedMethod'; // do not localise
ID_SOAP_ITI_XML_NODE_IS_INHERITED = 'IsInherited'; // do not localise
ID_SOAP_ITI_XML_NODE_HEADER = 'Header'; // do not localise
ID_SOAP_ITI_XML_NODE_RESPHEADER = 'Respheader'; // do not localise
ID_SOAP_ITI_XML_NODE_ATTACHMENTTYPE = 'AttachmentType'; // do not localise
ID_SOAP_ITI_XML_NODE_ENCODINGOVERRIDE = 'EncodingOverride'; // do not localise
ID_SOAP_ITI_XML_NODE_CATEGORY = 'Category'; // do not localise
ID_SOAP_ITI_XML_NODE_VISIBILITY = 'Visibility'; // do not localise
ID_SOAP_ITI_XML_NODE_COMINITMODE = 'ComInitMode'; // do not localise
ID_SOAP_ITI_XML_NODE_MANDATORY = 'Mandatory'; // do not localise
// XML encoding support:
ID_SOAP_DEFAULT_NAMESPACE_CODE = 'ns'; // do not localise
ID_SOAP_DS_DEFAULT_ROOT = 'urn:nevrona.com/indysoap/v1/'; // do not localise
ID_SOAP_NS_SOAPENV = 'http://schemas.xmlsoap.org/soap/envelope/'; // do not localise
ID_SOAP_NS_SOAPENC = 'http://schemas.xmlsoap.org/soap/encoding/'; // do not localise
ID_SOAP_NS_SCHEMA_1999 = 'http://www.w3.org/1999/XMLSchema'; // do not localise
ID_SOAP_NS_SCHEMA_INST_1999 = 'http://www.w3.org/1999/XMLSchema-instance'; // do not localise
ID_SOAP_NS_SCHEMA_2001 = 'http://www.w3.org/2001/XMLSchema'; // do not localise
ID_SOAP_NS_SCHEMA_INST_2001 = 'http://www.w3.org/2001/XMLSchema-instance'; // do not localise
ID_SOAP_NS_WSDL_SOAP = 'http://schemas.xmlsoap.org/wsdl/soap/'; // do not localise
ID_SOAP_NS_WSDL_SOAP12 = 'http://schemas.xmlsoap.org/wsdl/soap12/'; // do not localise
ID_SOAP_NS_SOAP_HTTP = 'http://schemas.xmlsoap.org/soap/http'; // do not localise
ID_SOAP_NS_WSDL = 'http://schemas.xmlsoap.org/wsdl/'; // do not localise
ID_SOAP_NS_WSDL_DIME = 'http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/'; // do not localise
ID_SOAP_NS_WSDL_MIME = 'http://schemas.xmlsoap.org/wsdl/mime/'; // do not localise
ID_SOAP_NS_XML_CORE = 'http://www.w3.org/XML/1998/namespace';
ID_SOAP_NS_SOAPENV_CODE = 'soap'; // do not localise
ID_SOAP_NS_SOAPENC_CODE = 'soap-enc'; // do not localise
ID_SOAP_NS_SCHEMA_CODE = 'xsd'; // do not localise
ID_SOAP_NS_SCHEMA_INST_CODE = 'xsi'; // do not localise
ID_SOAP_NS_WSDL_SOAP_CODE = 'soap'; // do not localise
ID_SOAP_NS_WSDL_DIME_CODE = 'dime'; // do not localise
ID_SOAP_NS_WSDL_MIME_CODE = 'mime'; // do not localise
ID_SOAP_NS_WSDL_CODE = 'wsdl'; // do not localise
ID_SOAP_NS_SCHEMA = ID_SOAP_NS_SCHEMA_2001; // do not localise
ID_SOAP_NS_SCHEMA_INST = ID_SOAP_NS_SCHEMA_INST_2001; // do not localise
ID_SOAP_XML_LANG = 'lang';
ID_SOAP_SCHEMA_INCLUDE = 'include';
ID_SOAP_SCHEMA_QNAME = 'QName';
ID_SOAP_SCHEMA_MINOCCURS = 'minOccurs'; // do not localise
ID_SOAP_SCHEMA_MAXOCCURS = 'maxOccurs'; // do not localise
ID_SOAP_SCHEMA_IMPORT = 'import'; // do not localise
ID_SOAP_SCHEMA_NAMESPACE = 'namespace'; // do not localise
ID_SOAP_SCHEMA_REF = 'ref'; // do not localise
ID_SOAP_SCHEMA_ELEMENT = 'element'; // do not localise
ID_SOAP_SCHEMA_LOCATION = 'schemaLocation';
ID_SOAP_SCHEMA_SCHEMA = 'schema';
ID_SOAP_SCHEMA_TARGETNS = 'targetNamespace';
ID_SOAP_SCHEMA_ATTRFORMDEF = 'attributeFormDefault';
ID_SOAP_SCHEMA_ELEMFORMDEF = 'elementFormDefault';
ID_SOAP_SCHEMA_ID = 'id';
ID_SOAP_SCHEMA_VERSION = 'version';
ID_SOAP_SCHEMA_ATTRIBUTE = 'attribute';
ID_SOAP_SCHEMA_DEFAULT = 'default';
ID_SOAP_SCHEMA_FIXED = 'fixed';
ID_SOAP_SCHEMA_FORM = 'form';
ID_SOAP_SCHEMA_NAME = 'name';
ID_SOAP_SCHEMA_TYPE = 'type';
ID_SOAP_SCHEMA_USE = 'use';
ID_SOAP_SCHEMA_SUBSTGROUP = 'substitutionGroup';
ID_SOAP_SCHEMA_ABSTRACT = 'abstract';
ID_SOAP_SCHEMA_NILLABLE = 'nillable';
ID_SOAP_SCHEMA_MIXED = 'mixed';
ID_SOAP_SCHEMA_COMPLEXTYPE = 'complexType';
ID_SOAP_SCHEMA_SIMPLETYPE = 'simpleType';
ID_SOAP_SCHEMA_LIST = 'list';
ID_SOAP_SCHEMA_ITEMTYPE = 'itemType';
ID_SOAP_SCHEMA_COMPLEXCONTENT = 'complexContent';
ID_SOAP_SCHEMA_SIMPLECONTENT = 'simpleContent';
ID_SOAP_SCHEMA_ALL = 'all';
ID_SOAP_SCHEMA_CHOICE = 'choice';
ID_SOAP_SCHEMA_SEQUENCE = 'sequence';
ID_SOAP_SCHEMA_ATTRGROUP = 'attributeGroup';
ID_SOAP_SCHEMA_EXTENSION = 'extension';
ID_SOAP_SCHEMA_RESTRICTION = 'restriction';
ID_SOAP_SCHEMA_BASE = 'base';
ID_SOAP_SCHEMA_ENUMERATION = 'enumeration';
ID_SOAP_SCHEMA_VALUE = 'value';
ID_SOAP_SCHEMA_ANNOTATION = 'annotation';
ID_SOAP_SCHEMA_APPINFO = 'appinfo';
ID_SOAP_SCHEMA_PATTERN = 'pattern';
ID_SOAP_NS_SCHEMATRON = 'http://www.ascc.net/xml/schematron';
ID_SOAP_SCHEMATRON_PATTERN = 'pattern';
ID_SOAP_SCHEMATRON_NAME = 'name';
ID_SOAP_SCHEMATRON_ABSTRACT = 'abstract';
ID_SOAP_SCHEMATRON_ID = 'id';
ID_SOAP_SCHEMATRON_REPORT = 'report';
ID_SOAP_SCHEMATRON_ASSERT = 'assert';
ID_SOAP_SCHEMATRON_TEST = 'test';
ID_SOAP_SCHEMATRON_RULE = 'rule';
ID_SOAP_NAME_ENCODINGSTYLE = 'encodingStyle'; // do not localise
ID_SOAP_NAME_MUSTUNDERSTAND = 'mustUnderstand'; // do not localise
ID_SOAP_NAME_FAULT = 'Fault'; // do not localise
ID_SOAP_NAME_FAULTCODE = 'faultcode'; // do not localise
ID_SOAP_NAME_FAULTACTOR = 'faultactor'; // do not localise
ID_SOAP_NAME_FAULTSTRING = 'faultstring'; // do not localise
ID_SOAP_NAME_FAULTDETAIL = 'detail'; // do not localise
ID_SOAP_NAME_SCHEMA_TYPE = 'type'; // do not localise
ID_SOAP_NAME_ENV = 'Envelope'; // do not localise
ID_SOAP_NAME_BODY = 'Body'; // do not localise
ID_SOAP_NAME_HEADER = 'Header'; // do not localise
ID_SOAP_NAME_XML_ID = 'id'; // do not localise
ID_SOAP_NAME_XML_HREF = 'href'; // do not localise
ID_SOAP_NAME_XML_XMLNS = 'xmlns'; // do not localise
ID_SOAP_NAME_SCHEMA_POSITION = 'position'; // do not localise
ID_SOAP_NAME_SCHEMA_OFFSET = 'offset'; // do not localise
ID_SOAP_NAME_SCHEMA_ITEM = 'item'; // do not localise
ID_SOAP_WSDL_OPEN = '##any';
ID_SOAP_CHARSET_8 = 'charset=utf-8';
ID_SOAP_CHARSET_16 = 'charset=utf-16';
// SOAP NAMES OF SIGNIFICANCE
ID_SOAP_NAME_RESULT = 'return';
ID_SOAP_NULL_TYPE = 'NULL'; // this is used for the class type for an null and unnamed class reading a SOAP packet
// SOAP NAMES OF INSIGNIFICANCE
ID_SOAP_NULL_NODE_NAME = 'Root';
ID_SOAP_NULL_NODE_TYPE = 'Null';
ID_SOAP_NAME_REF_TYPE = '#ref'; // this is the arbitrary type assigned to a reference node
// Schema Types
ID_SOAP_XSI_TYPE_ANY = 'anyType'; // do not localise
ID_SOAP_XSI_TYPE_STRING = 'string'; // do not localise
ID_SOAP_XSI_TYPE_INTEGER = 'int'; // do not localise
ID_SOAP_XSI_TYPE_BOOLEAN = 'boolean'; // do not localise
ID_SOAP_XSI_TYPE_BYTE = 'unsignedByte'; // do not localise
ID_SOAP_XSI_TYPE_CARDINAL = 'unsignedInt'; // do not localise
ID_SOAP_XSI_TYPE_UNSIGNEDLONG = 'unsignedLong'; // do not localise
ID_SOAP_XSI_TYPE_COMP = 'long'; // do not localise
ID_SOAP_XSI_TYPE_CURRENCY = 'decimal'; // do not localise
ID_SOAP_XSI_TYPE_DATETIME = 'dateTime'; // do not localise
ID_SOAP_XSI_TYPE_DURATION = 'duration'; // do not localise
ID_SOAP_XSI_TYPE_TIMEINSTANT = 'timeInstant';{from 1999 schema but we allow it}// do not localise
ID_SOAP_XSI_TYPE_DATE = 'date'; // do not localise
ID_SOAP_XSI_TYPE_TIME = 'time'; // do not localise
ID_SOAP_XSI_TYPE_DOUBLE = 'double'; // do not localise
ID_SOAP_XSI_TYPE_EXTENDED = 'double'; // do not localise
ID_SOAP_XSI_TYPE_INT64 = 'long'; // do not localise
ID_SOAP_XSI_TYPE_SHORTINT = 'byte'; // do not localise
ID_SOAP_XSI_TYPE_SINGLE = 'float'; // do not localise
ID_SOAP_XSI_TYPE_SMALLINT = 'short'; // do not localise
ID_SOAP_XSI_TYPE_WORD = 'unsignedShort'; // do not localise
ID_SOAP_XSI_TYPE_BASE64BINARY = 'base64Binary'; // do not localise
ID_SOAP_SOAP_TYPE_BASE64BINARY = 'base64'; {Apache error} // do not localise
ID_SOAP_XSI_TYPE_HEXBINARY = 'hexBinary'; // do not localise
ID_SOAP_SOAPENC_ARRAY = 'Array'; // do not localise
ID_SOAP_SOAPENC_ARRAYTYPE = 'arrayType'; // do not localise
ID_SOAP_XSI_TYPE_QNAME = 'QName'; // do not localise
ID_SOAP_XSI_ATTR_NIL = 'nil'; // do not localise
ID_SOAP_XSI_ATTR_NULL = 'null'; // do not localise
ID_SOAP_XSI_ATTR_NILLABLE = 'nillable'; // do not localise
ID_SOAP_XSI_TYPE_ANYURI = 'anyURI'; // do not localise
ID_SOAP_XSI_TYPE_ID = 'ID'; // do not localise
ID_SOAP_XSI_TYPE_IDREF = 'IDREF'; // do not localise
// HTTP RPC settings // do not localise
ID_SOAP_DEFAULT_SOAP_PATH = '/soap'; // do not localise
ID_SOAP_HTTP_ACTION_HEADER = 'SOAPAction'; // do not localise
// V1.2 ID_SOAP_HTTP_SOAP_TYPE = 'application/soap'; // do not localise
ID_SOAP_HTTP_SOAP_TYPE = 'text/xml'; // do not localise
ID_SOAP_HTTP_BIN_TYPE = 'application/Octet-Stream'; // do not localise
ID_SOAP_HTTP_DIME_TYPE = 'application/dime'; // do not localise
ID_SOAP_HTTP_PARAMS_TYPE = 'application/x-www-form-urlencoded'; // do not localise
ID_SOAP_DEFAULT_WSDL_PATH = '/wsdl'; // do not localise
ID_SOAP_HTTP_DEFLATE = 'deflate';
// TCPIP Communications constants
ID_SOAP_TCPIP_MAGIC_REQUEST : Longint = $49445351; // IDSQ
ID_SOAP_TCPIP_MAGIC_RESPONSE : Longint = $49445341; // IDSA
ID_SOAP_TCPIP_MAGIC_FOOTER : Longint = $49445345; // IDSE
ID_SOAP_MAX_MIMETYPE_LENGTH = 100; // not allowed to have interface names longer than this in requests (DoS protection)
ID_SOAP_MAX_PACKET_LENGTH = 100 * 1024 * 1024; // not allowed to have interface names longer than 100MB in requests (DoS protection) (should be long enough! - needs more work)
ID_SOAP_TCPIP_TIMEOUT = 60000;
// client Interface Handling Settings
ID_SOAP_BUFFER_SIZE = 8192; // size of SOAP stub buffer (keep it large for efficient allocs)
ID_SOAP_MAX_STUB_BUFFER_SIZE = 20; // max size of a SOAP stub
ID_SOAP_MAX_STRING_PARAMS = 50; // max num of string OR widestring params allowed in a single method.
ID_SOAP_INVALID = '|||';
// you may have up to IDSOAP_MAX_STRING_PARAMS AnsiStrings AND
// IDSOAP_MAX_STRING_PARAMS WideStrings but no more
// This option uses IDSOAP_MAX_STRING_PARAMS * 8 bytes only during
// server Interface Handling Settings
ID_SOAP_INIT_MEM_VALUE = #0; // what to initialize mem to (generally for the OUT param type). Leave this at 0 - anything else will have fatal consequences
{$IFNDEF CLR}
ID_SOAP_INVALID_POINTER = pointer($fffffffe); // just to prevent use of invalid pointers
{$ENDIF}
// Binary Stream Constants
ID_SOAP_BIN_MAGIC = $10EA8F0A;
ID_SOAP_BIN_PACKET_EXCEPTION = 1;
ID_SOAP_BIN_PACKET_MESSAGE = 2;
ID_SOAP_BIN_NODE_STRUCT = 1;
ID_SOAP_BIN_NODE_ARRAY = 2;
ID_SOAP_BIN_NODE_REFERENCE = 3;
ID_SOAP_BIN_NOTVALID = 0;
ID_SOAP_BIN_TYPE_PARAM = 1;
ID_SOAP_BIN_TYPE_NODE = 2;
ID_SOAP_BIN_CLASS_NIL = 0;
ID_SOAP_BIN_CLASS_NOT_NIL = 1;
ID_SOAP_BIN_TYPE_BOOLEAN = 2;
ID_SOAP_BIN_TYPE_BYTE = 3;
ID_SOAP_BIN_TYPE_CARDINAL = 4;
ID_SOAP_BIN_TYPE_CHAR = 5;
ID_SOAP_BIN_TYPE_COMP = 6;
ID_SOAP_BIN_TYPE_CURRENCY = 7;
ID_SOAP_BIN_TYPE_DOUBLE = 8;
ID_SOAP_BIN_TYPE_ENUM = 9;
ID_SOAP_BIN_TYPE_EXTENDED = 10;
ID_SOAP_BIN_TYPE_INT64 = 11;
ID_SOAP_BIN_TYPE_INTEGER = 12;
ID_SOAP_BIN_TYPE_SHORTINT = 13;
ID_SOAP_BIN_TYPE_SHORTSTRING = 14;
ID_SOAP_BIN_TYPE_SINGLE = 15;
ID_SOAP_BIN_TYPE_SMALLINT = 16;
ID_SOAP_BIN_TYPE_STRING = 17;
ID_SOAP_BIN_TYPE_WIDECHAR = 18;
ID_SOAP_BIN_TYPE_WIDESTRING = 19;
ID_SOAP_BIN_TYPE_WORD = 20;
ID_SOAP_BIN_TYPE_SET = 21;
ID_SOAP_BIN_TYPE_BINARY = 22;
ID_SOAP_BIN_TYPE_DATETIME = 23;
ID_SOAP_BIN_TYPE_DATETIME_NULL = 24;
ID_SOAP_BIN_TYPE_GENERAL = 25;
ID_SOAP_BIN_TYPE_XML = 26;
ID_SOAP_BIN_TYPE_ANSISTRING = 27;
ID_SOAP_WSDL_SUFFIX_SERVICE = 'Service';
ID_SOAP_WSDL_SUFFIX_PORT = 'Port';
ID_SOAP_WSDL_SUFFIX_BINDING = 'Binding';
ID_SOAP_WSDL_DIME_CLOSED = 'http://schemas.xmlsoap.org/ws/2002/04/dime/closed-layout';
ID_SOAP_CONTENT_TYPE = 'Content-Type';
ID_SOAP_CONTENT_DISPOSITION = 'Content-Disposition';
ID_SOAP_MULTIPART_RELATED : AnsiString = 'multipart/related';
ID_SOAP_MULTIPART_FORMDATA : AnsiString = 'multipart/form-data';
ID_SOAP_MIME_BOUNDARY : AnsiString = 'boundary';
ID_SOAP_MIME_START : AnsiString = 'start';
ID_SOAP_MIME_TYPE : AnsiString = 'type';
ID_SOAP_MIME_ID = 'Content-ID';
ID_SOAP_MIME_TRANSFERENCODING = 'Content-Transfer-Encoding';
ID_SOAP_MIME_DEFAULT_START = 'uuid:{FF461456-FE30-4933-9AF6-F8EB226E1BF7}';
ID_SOAP_MIME_DEFAULT_BOUNDARY = 'MIME_boundary';
Implementation
End.
|
unit UReservaApto;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UBasePesquisaSimples, Vcl.ExtCtrls,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer,
cxEdit, dxSkinsCore, dxSkinsDefaultPainters, Vcl.ComCtrls, dxCore,
cxDateUtils, cxMaskEdit, cxDropDownEdit, cxCalendar, cxTextEdit,
cxCurrencyEdit, Vcl.StdCtrls, dxGDIPlusClasses, Vcl.Buttons, UFunctions,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, cxDBEdit, dxSkinBlueprint, dxSkinDevExpressDarkStyle,
dxSkinLilian, dxSkinOffice2007Black, dxSkinOffice2010Black,
dxSkinVisualStudio2013Blue, dxSkinXmas2008Blue;
type
TF_reservaApto = class(TF_baseTelaSimples)
pnlControle: TPanel;
btnSalvar: TSpeedButton;
pnlDados: TPanel;
imgEntraHospede: TImage;
lblCodCli: TLabel;
lblCliente: TLabel;
btnPesquisar: TSpeedButton;
lblQtdAtuldos: TLabel;
lblQtdCriancas: TLabel;
lblQtdPagantes: TLabel;
lblQtdDNormal: TLabel;
lblVlrDNormal: TLabel;
lblDtaReserva: TLabel;
lblHoraReserva: TLabel;
lblPrevisaoEntrada: TLabel;
lblPlaca: TLabel;
lblModelo: TLabel;
lblMarca: TLabel;
lblVlrGDNormal: TLabel;
lblQtdDExtras: TLabel;
lblVlrDExtra: TLabel;
lblVlrGDExtra: TLabel;
lblSutTotDiarias: TLabel;
lblTGDiarias: TLabel;
btnCadVeiculos: TSpeedButton;
lblApto: TLabel;
edtCodCli: TcxCurrencyEdit;
edtCliente: TcxTextEdit;
edtQtdAdultos: TcxCurrencyEdit;
edtQtdCriancas: TcxCurrencyEdit;
edtQtdPagantes: TcxCurrencyEdit;
edtQtdDNormal: TcxCurrencyEdit;
edtVlrDNormal: TcxCurrencyEdit;
edtVlrGDNormal: TcxCurrencyEdit;
edtQtdDExtra: TcxCurrencyEdit;
edtVlrDExtra: TcxCurrencyEdit;
edtVlrGDExtra: TcxCurrencyEdit;
edtSubTDiarias: TcxCurrencyEdit;
edtVlrTDiarias: TcxCurrencyEdit;
dtaReserva: TcxDateEdit;
dtaPrevisaoEntrada: TcxDateEdit;
edtModeloVeiculo: TcxTextEdit;
edtMarcaVeiculo: TcxTextEdit;
edtPlaca: TcxMaskEdit;
edtApto: TcxCurrencyEdit;
QRY_calculaDiarias: TFDQuery;
QRY_calculaDiariasCAT_CODCATEGORIA: TIntegerField;
QRY_calculaDiariasCAT_CATEGORIA: TStringField;
QRY_calculaDiariasCAT_ATPESSOAS: TIntegerField;
QRY_calculaDiariasCAT_VALORDIARIA1: TBCDField;
QRY_calculaDiariasCAT_VALORDIARIA2: TBCDField;
QRY_qtdPessoasCategoria: TFDQuery;
QRY_qtdPessoasCategoriaCAT_CODCATEGORIA: TIntegerField;
QRY_qtdPessoasCategoriaCAT_CATEGORIA: TStringField;
QRY_qtdPessoasCategoriaCAT_ATPESSOAS: TIntegerField;
QRY_qtdPessoasCategoriaCAT_VALORDIARIA1: TBCDField;
QRY_qtdPessoasCategoriaCAT_VALORDIARIA2: TBCDField;
QRY_veiculos: TFDQuery;
QRY_veiculosVEI_CODIGO: TIntegerField;
QRY_veiculosVEI_MODELO: TStringField;
QRY_veiculosVEI_MARCA: TStringField;
QRY_veiculosVEI_LINHA: TStringField;
QRY_veiculosVEI_PLACA: TStringField;
QRY_veiculosVEI_COR: TStringField;
hraReserva: TcxCurrencyEdit;
procedure FormShow(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnSalvarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure edtQtdPagantesExit(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edtVlrDNormalExit(Sender: TObject);
procedure edtVlrDExtraExit(Sender: TObject);
procedure edtPlacaExit(Sender: TObject);
procedure edtClienteExit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
var reservaHospede, cadVeiculo, libera: String;
end;
var
F_reservaApto: TF_reservaApto;
implementation
{$R *.dfm}
uses UDMRackApto, UDMConexao, UMsg, UDMHospedes, UPesquisaHospedes,
USenhaLiberacao, UCheckIn;
procedure TF_reservaApto.btnPesquisarClick(Sender: TObject);
begin
inherited;
// reservaHospede := 'S';
CriaFormDestroy(TF_pesquisaHospede, F_pesquisaHospede);
end;
procedure TF_reservaApto.btnSalvarClick(Sender: TObject);
var hReserva : TTime;
begin
inherited;
try
if F_dmHospedes = nil then begin
Application.CreateForm(TF_dmHospedes, F_dmHospedes);
end;
hReserva := Time;
{se nao fizer isso, corre o risto de gravar a reserva duas vezes visto que o codigo ainda fica na Qry}
F_dmHospedes.QRY_reservaApto.Close;
F_dmHospedes.QRY_reservaApto.Open();
{se o atendende demorar gravar, atualiza a data e a hora.}
hraReserva.Text := TimeToStr(hReserva);
dtaReserva.Date := Date;
if (StrToInt(edtCodCli.Text) <= 0) or (StrToInt(edtQtdPagantes.Text) <= 0) then begin
TF_msg.Mensagem('Faltam algumas informações do Hóspede! O Nome do Hósdede ou a Qtd. de Pagantes são obrigatórios.','I',[mbOk]);
edtCliente.SetFocus;
exit;
end;
if Situacao = 'LIVRE' then begin
try
F_dmConexao.FDConn.StartTransaction; {inicia a transação}
hraReserva.Text := TimeToStr(hReserva); {atualiza a hora. se o funcionario demorar clicar no salvar}
F_dmHospedes.QRY_reservaApto.Open();
F_dmHospedes.QRY_reservaApto.Append;
F_dmHospedes.QRY_reservaAptoENT_CODAPARTAMENTO.AsInteger := StrToInt(CodApartamento);
F_dmHospedes.QRY_reservaAptoENT_CODHOSPEDE.AsInteger := StrToInt(edtCodCli.Text);
F_dmHospedes.QRY_reservaAptoENT_DATARESERVA.AsDateTime := dtaReserva.Date;
F_dmHospedes.QRY_reservaAptoENT_HORARESERVA.AsDateTime := Time;
F_dmHospedes.QRY_reservaAptoENT_QTDADULTOS.AsInteger := StrToInt(edtQtdAdultos.Text);
F_dmHospedes.QRY_reservaAptoENT_QTDCRIANCAS.AsInteger := StrToInt(edtQtdCriancas.Text);
F_dmHospedes.QRY_reservaAptoENT_QTDPAGANTES.AsInteger := StrToInt(edtQtdPagantes.Text);
F_dmHospedes.QRY_reservaAptoENT_VLR_DIARIA_NORMAL.AsCurrency := edtVlrDNormal.Value;
F_dmHospedes.QRY_reservaAptoENT_VLR_DIARIA_EXTRA.AsCurrency := edtVlrDExtra.Value;
F_dmHospedes.QRY_reservaAptoENT_QTD_DIARIA_NORMAL.AsInteger := StrToInt(edtQtdDNormal.Text);
F_dmHospedes.QRY_reservaAptoENT_VLR_G_DIARIA_NORMAL.AsCurrency := edtVlrGDNormal.Value;
F_dmHospedes.QRY_reservaAptoENT_VLR_G_DIARIA_EXTRA.AsCurrency := edtVlrGDExtra.Value;
F_dmHospedes.QRY_reservaAptoENT_QTD_DIARIA_EXTRA.AsInteger := StrToInt(edtQtdDExtra.Text);
F_dmHospedes.QRY_reservaAptoENT_VLR_G_DIARIA_EXTRA.AsCurrency := edtVlrGDExtra.Value;
F_dmHospedes.QRY_reservaAptoENT_DATAPREVISAOEFETIVAR.AsDateTime := dtaPrevisaoEntrada.Date;
F_dmHospedes.QRY_reservaAptoENT_PLACA.AsString := edtPlaca.Text;
F_dmHospedes.QRY_reservaAptoENT_MODELOVEICULO.AsString := edtModeloVeiculo.Text;
F_dmHospedes.QRY_reservaAptoENT_MARCAVEICULO.AsString := edtMarcaVeiculo.Text;
F_dmHospedes.QRY_reservaAptoENT_USUARIORESERVOU.AsInteger := 1; {pegar o logado}
F_dmHospedes.QRY_reservaAptoENT_FILIAL.AsString := '1'; {pegar a filial logada}
F_dmHospedes.QRY_reservaAptoENT_STATUS.AsString := 'RESERVADO'; {NA TABELA HOTENTRAHOSPEDE}
{19-05-2017}
F_dmHospedes.QRY_reservaAptoENT_VLR_TOTAL_DIARIAS.AsCurrency := edtVlrTDiarias.Value;
F_dmHospedes.QRY_reservaAptoENT_QTD_TOTAL_DIARIAS.AsInteger := StrToInt(edtSubTDiarias.Text);
F_dmHospedes.QRY_reservaApto.Post;
F_dmHospedes.QRY_reservaApto.ApplyUpdates();
{pega o codigo de entrada para atualizar a tabela hotApartamento}
with F_dmRackApto.QRY_codEntrada do begin
Close;
SQL.Clear;
SQL.Add('select * from hotentrahospede where ent_codapartamento = :codApto and ent_datasaida is null');
ParamByName('codApto').Value := CodApartamento;
Open();
end;
{Atualiza a tabela hotApartamento colocando o código de entrada}
with F_dmRackApto.QRY_atualizaApto do begin
Close;
SQL.Clear;
SQL.Add('update hotApartamento set apa_codEntrada = :codEntrada where apa_codapartamento = :codApto');
ParamByName('codEntrada').Value := F_dmRackApto.QRY_codEntradaENT_CODENTRADA.AsInteger;
ParamByName('codApto').Value := CodApartamento;
ExecSQL;
end;
{Atualiza o status do apto na tabela hotApartamento}
with F_dmRackApto.QRY_atualizaApto do begin
Close;
SQL.Clear;
SQL.Add('update hotApartamento set apa_situacao = :situacao where apa_codapartamento = :codApto');
ParamByName('situacao').Value := 'RESERVADO';
ParamByName('codApto').Value := CodApartamento;
ExecSQL;
end;
F_dmConexao.FDConn.Commit; {se tudo der certo, commita a transação}
OrdenaLista; {atualiza a lista}
TF_msg.Mensagem('Apto Reservado com sucesso.','I',[mbOk]);
Self.Close; {fecha o form para o cliente nao salvar novamente}
if F_checkIn <> nil then begin
F_checkIn.Close;
end;
except on e:Exception do
begin
F_dmConexao.FDConn.Rollback;
TF_msg.Mensagem('Erro na Reserva do Apto. Verifique os dados de entrada corretamente.','I',[mbOk]);
exit;
end;
end;
End
else begin
TF_msg.Mensagem('Esse Apto ja foi Reservado. Obrigado!','I',[mbOk]);
Self.Close;
exit;
end;
finally
FreeAndNil(F_dmHospedes);
end;
end;
procedure TF_reservaApto.edtClienteExit(Sender: TObject);
begin
inherited;
{sair do cliente}
if (edtCliente.Text = '') or (edtCodCli.Text = '0') then begin
TF_msg.Mensagem('Cliente inválido ou em Branco.','I',[mbOk]);
TcxTextEdit(Sender).SetFocus;
btnPesquisar.Click;
end;
end;
procedure TF_reservaApto.edtPlacaExit(Sender: TObject);
begin{pesquisa pela placa}
inherited;
if edtPlaca.Text = ' - ' then begin
exit;
end
else begin
QRY_veiculos.Close;
QRY_veiculos.Params[0].Value := '%'+ edtPlaca.Text + '%';
QRY_veiculos.Open();
if QRY_veiculos.RecordCount > 0 then begin
edtPlaca.Text := QRY_veiculosVEI_PLACA.AsString;
edtModeloVeiculo.Text := QRY_veiculosVEI_MODELO.AsString;
edtMarcaVeiculo.Text := QRY_veiculosVEI_MARCA.AsString;
end
else begin
TF_msg.Mensagem('Veículo não encontrado. Favor, faça o cadastro.','I',[mbOk]);
edtPlaca.Clear;
edtPlaca.SetFocus;
btnCadVeiculos.Click;
exit;
end;
end;
end;
procedure TF_reservaApto.edtQtdPagantesExit(Sender: TObject);
begin
inherited;
{sair do qtdPagantes}
if ENumerico2(edtQtdPagantes.Text) = True then begin
{faz as regras}
if edtQtdPagantes.Value < 1 then begin
TF_msg.Mensagem('Valor inválido! Favor, informar um valor maior ou igual a 1.','I',[mbOk]);
TcxTextEdit(Sender).SetFocus;
exit;
end;
QRY_qtdPessoasCategoria.Close;
QRY_qtdPessoasCategoria.Params[0].Value := CodApartamento;
QRY_qtdPessoasCategoria.Open();
{qtd. diarias extras e normais}
if edtQtdPagantes.Value > QRY_qtdPessoasCategoriaCAT_ATPESSOAS.AsInteger then begin {QRY_qtdPessoasCategoria era 1 por padrão}
edtQtdDExtra.Value := (edtQtdPagantes.Value - QRY_qtdPessoasCategoriaCAT_ATPESSOAS.AsInteger); {qtd. diarias extras}
edtQtdDNormal.Value := (edtQtdPagantes.Value - edtQtdDExtra.Value); {qtd. diarias normais}
edtVlrGDNormal.Value := edtVlrDNormal.Value; // edtQtdDNormal.Value * edtVlrDNormal.Value; {vlr. geral. diarias normais}
edtVlrGDExtra.Value := edtQtdDExtra.Value * edtVlrDExtra.Value; {vlr. geral. diarias extras}
edtSubTDiarias.Value := edtQtdDNormal.Value + edtQtdDExtra.Value; {tot. geral. diarias}
edtVlrTDiarias.Value := edtVlrGDNormal.Value + edtVlrGDExtra.Value; {vlr. geral. diarias}
end
else begin
edtQtdDExtra.Value := 0; {qtd. diarias extras}
edtQtdDNormal.Value := edtQtdPagantes.Value; {qtd. diarias normais}
edtVlrGDNormal.Value := edtVlrDNormal.Value; // edtQtdDNormal.Value * edtVlrDNormal.Value; {vlr. geral. diarias normais}
edtVlrGDExtra.Value := edtQtdDExtra.Value * edtVlrDExtra.Value; {vlr. geral. diarias extras}
edtSubTDiarias.Value := edtQtdDNormal.Value + edtQtdDExtra.Value; {tot. geral. diarias}
edtVlrTDiarias.Value := edtVlrGDNormal.Value + edtVlrGDExtra.Value; {vlr. geral. diarias}
end;
end
else begin
{bloqueia}
TF_msg.Mensagem('Valor inválido!','I',[mbOk]);
TcxCurrencyEdit(Sender).SetFocus;
end;
end;
procedure TF_reservaApto.edtVlrDExtraExit(Sender: TObject);
begin{saindo da extra}
inherited;
{verificar se o percentual do desconto é menor que o valor definido no parametro de desconto}
if edtVlrDExtra.Value < 0 then begin
TF_msg.Mensagem('Desconto incorreto.','E',[mbOk]);
TcxCurrencyEdit(Sender).SetFocus;
exit;
end;
if edtVlrDExtra.Value < F_dmRackApto.QRY_rackAptoCAT_VALORDIARIA2.AsCurrency then begin
if TF_msg.Mensagem('Desconto maior que o permitido. Deseja fazer a liberação?','Q',[mbSim, mbNao]) then begin
CriaFormDestroy(TF_senhaLiberacao, F_senhaLiberacao);
if libera = 'S' then begin
edtVlrGDExtra.Value := edtQtdDExtra.Value * edtVlrDExtra.Value; {vlr. geral. diarias extras}
edtSubTDiarias.Value := edtQtdDNormal.Value + edtQtdDExtra.Value; {tot. geral. diarias}
edtVlrTDiarias.Value := edtVlrGDNormal.Value + edtVlrGDExtra.Value; {vlr. geral. diarias}
exit;
end
else begin
edtVlrDExtra.Value := F_dmRackApto.QRY_rackAptoCAT_VALORDIARIA2.AsCurrency;
edtVlrGDExtra.Value := edtQtdDExtra.Value * edtVlrDExtra.Value; {vlr. geral. diarias extras}
edtSubTDiarias.Value := edtQtdDNormal.Value + edtQtdDExtra.Value; {tot. geral. diarias}
edtVlrTDiarias.Value := edtVlrGDNormal.Value + edtVlrGDExtra.Value; {vlr. geral. diarias}
exit;
end;
end;
{so cai se nao fazer nada}
edtVlrDExtra.Value := F_dmRackApto.QRY_rackAptoCAT_VALORDIARIA2.AsCurrency;
edtVlrGDExtra.Value := edtQtdDExtra.Value * edtVlrDExtra.Value; {vlr. geral. diarias extras}
edtSubTDiarias.Value := edtQtdDNormal.Value + edtQtdDExtra.Value; {tot. geral. diarias}
edtVlrTDiarias.Value := edtVlrGDNormal.Value + edtVlrGDExtra.Value; {vlr. geral. diarias}
end
else begin
edtVlrGDExtra.Value := edtQtdDExtra.Value * edtVlrDExtra.Value; {vlr. geral. diarias extras}
edtSubTDiarias.Value := edtQtdDNormal.Value + edtQtdDExtra.Value; {tot. geral. diarias}
edtVlrTDiarias.Value := edtVlrGDNormal.Value + edtVlrGDExtra.Value; {vlr. geral. diarias}
end;
end;
procedure TF_reservaApto.edtVlrDNormalExit(Sender: TObject);
begin{saindo da normal}
inherited;
{verificar se o percentual do desconto é menor que o valor definido no parametro de desconto}
if edtVlrDNormal.Value < 0 then begin
TF_msg.Mensagem('Desconto incorreto.','E',[mbOk]);
TcxCurrencyEdit(Sender).SetFocus;
exit;
end;
if edtVlrDNormal.Value < F_dmRackApto.QRY_rackAptoCAT_VALORDIARIA1.AsCurrency then begin
if TF_msg.Mensagem('Desconto maior que o permitido. Deseja fazer a liberação?','Q',[mbSim, mbNao]) then begin
CriaFormDestroy(TF_senhaLiberacao, F_senhaLiberacao);
if libera = 'S' then begin
edtVlrGDNormal.Value := edtQtdDNormal.Value * edtVlrDNormal.Value; {vlr. geral. diarias normais}
edtSubTDiarias.Value := edtQtdDNormal.Value + edtQtdDExtra.Value; {tot. geral. diarias}
edtVlrTDiarias.Value := edtVlrGDNormal.Value + edtVlrGDExtra.Value; {vlr. geral. diarias}
exit;
end
else begin
edtVlrDNormal.Value := F_dmRackApto.QRY_rackAptoCAT_VALORDIARIA1.AsCurrency;
edtVlrGDNormal.Value := edtQtdDNormal.Value * edtVlrDNormal.Value; {vlr. geral. diarias normais}
edtSubTDiarias.Value := edtQtdDNormal.Value + edtQtdDExtra.Value; {tot. geral. diarias}
edtVlrTDiarias.Value := edtVlrGDNormal.Value + edtVlrGDExtra.Value; {vlr. geral. diarias}
exit;
end;
end;
{so cai se nao fazer nada}
edtVlrDNormal.Value := F_dmRackApto.QRY_rackAptoCAT_VALORDIARIA1.AsCurrency;
edtVlrGDNormal.Value := edtQtdDNormal.Value * edtVlrDNormal.Value; {vlr. geral. diarias normais}
edtSubTDiarias.Value := edtQtdDNormal.Value + edtQtdDExtra.Value; {tot. geral. diarias}
edtVlrTDiarias.Value := edtVlrGDNormal.Value + edtVlrGDExtra.Value; {vlr. geral. diarias}
end
else begin
edtVlrGDNormal.Value := edtQtdDNormal.Value * edtVlrDNormal.Value; {vlr. geral. diarias normais}
edtSubTDiarias.Value := edtQtdDNormal.Value + edtQtdDExtra.Value; {tot. geral. diarias}
edtVlrTDiarias.Value := edtVlrGDNormal.Value + edtVlrGDExtra.Value; {vlr. geral. diarias}
end;
end;
procedure TF_reservaApto.FormCreate(Sender: TObject);
begin
inherited;
if F_dmHospedes = nil then begin
Application.CreateForm(TF_dmHospedes, F_dmHospedes);
end;
end;
procedure TF_reservaApto.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if key = VK_F2 then begin
btnPesquisar.Click;
end;
end;
procedure TF_reservaApto.FormKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
if Key = #13 then begin
Key := #0;
Perform(WM_NEXTDLGCTL, 0,0); //mais rápido
end;
end;
procedure TF_reservaApto.FormShow(Sender: TObject);
var hReserva : TTime;
begin
inherited;
hReserva := Time;
hraReserva.Text := TimeToStr(hReserva);
dtaReserva.Date := Date;
dtaPrevisaoEntrada.Date := Date;
edtCliente.SelStart := Length(edtCliente.Text);
If Situacao = 'LIVRE' Then
Begin
edtApto.Text := Apartamento; //F_dmRackApto.QRY_rackAptoAPA_APARTAMENTO.AsString;
edtVlrDNormal.Value := F_dmRackApto.QRY_rackAptoCAT_VALORDIARIA1.AsCurrency;
edtVlrDExtra.Value := F_dmRackApto.QRY_rackAptoCAT_VALORDIARIA2.AsCurrency;
End;
//Vamos fazer o calculo das diárias baseado no apto escolhido
with QRY_calculaDiarias do begin
Close;
SQL.Clear;
SQL.Add('select ct.* from hotcategoria ct');
SQL.Add('inner join hotapartamento ap');
SQL.Add('on (ct.cat_codcategoria = ap.apa_codcategoria)');
SQL.Add('where ap.apa_codapartamento = :codApto');
ParamByName('codApto').Value := CodApartamento;
Open();
end;
end;
end.
|
{ p_33_2.pas - Программа для исследования точности вещественных типов}
var F0 : real;
F1 : single;
F2 : double;
F3 : extended;
begin
F0:= 1/3;
F1:= 1/3;
F2:= 1/3;
F3:= 1/3;
Writeln('Single = ', F1:23:18);
Writeln('Real = ', F0:23:18);
Writeln('Double = ', F2:23:18);
Writeln('Extended= ', F3:23:18);
end. |
unit Citys;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
const
CityNumber = 180;
CityData:array[1..CityNumber] of string =
(
('ACX'),('CAN'),('HFE'),('PEK'),
('KWL'),('AKU'),('AOG'),('BSD'),
('AQG'),('BFU'),('CGQ'),('BPX'),
('CGD'),('CSX'),('CIH'),('CZX'),
('CHG'),('CTU'),('CIF'),('CKG'),
('DAX'),('DIG'),('DLC'),('DLU'),
('DDG'),('DAT'),('DYG'),('DNH'),
('ENH'),('FYN'),('JNZ'),('KOW'),
('GOQ'),('GHN'),('AAT'),('BAV'),
('KWE'),('HRB'),('HAK'),('HLD'),
('HMI'),('HGH'),('HZG'),('AKA'),
('HEK'),('HNY'),('HTN'),('HKG'),
('TXN'),('HYN'),('HET'),('JMU'),
('JGN'),('JIL'),('TNA'),('JNG'),
('JDZ'),('JHG'),('JJN'),('FOC'),
('CHW'),('JIU'),('KRY'),('KHG'),
('KRL'),('KMG'),('KCA'),('LHW'),
('LNJ'),('LXA'),('LYG'),('LJG'),
('LYI'),('LZH'),('LYA'),('LZO'),
('MFM'),('LUM'),('MXZ'),('MDG'),
('MIG'),('KHN'),('NAO'),('NKG'),
('NNG'),('NTG'),('NNY'),('NNN'),
('NGB'),('IQM'),('TAO'),('IQN'),
('SHP'),('NDG'),('JUZ'),('SYX'),
('SHA'),('PVG'),('SWA'),('SHS'),
('SZX'),('SHE'),('SJW'),('SYM'),
('SZV'),('TCG'),('TYN'),('TSN'),
('TNH'),('TGO'),('TEN'),('WXN'),
('WEF'),('WEH'),('WNZ'),('WUH'),
('WJD'),('HLH'),('URC'),('WUS'),
('WUZ'),('XMN'),('XIY'),('XFN'),
('XIC'),('XIL'),('XNN'),('XUZ'),
('ENY'),('YNJ'),('YNT'),('YBP'),
('YIH'),('INC'),('YIN'),('YIW'),
('UYN'),('BHY'),('ZHA'),('CGO'),
('HSN'),('ZUH'),('ZYI'),('TSA'),
('TPE'),('TNN'),('KHH'),('TTG'),
('HLN'),('CYI'),('TXG'),('JZH'),
('WUX'),('NAY'),('NLT'),('LZY'),
('WUA'),('PZI'),('NZH'),('KGT'),
('HJJ'),('HDG'),('YNZ'),('AVA'),
('AEB'),('WNH'),('YUS'),('LLB'),
('KJI'),('DSN'),('HZH'),('OHE'),
('NBS'),('TCZ'),('ZHY'),('YCU'),
('DOY'),('THQ'),('CNI'),('ZAT')
);
Function GetTWCodeByID(Const ID:integer):string; //获取编号对应的三字码
Function GetIDByTWCode(Const Code:string):integer; //获得三字码的城市编号
implementation
Function GetTWCodeByID(Const ID:integer):string;
begin
result:=CityData[ID];
end;
Function GetIDByTWCode(Const Code:string):integer;
var
i:integer;
begin
result:=0; //三字码不存在
for i:=1 to CityNumber do
begin
if CityData[i]=Code then
begin
result:=i;
break;
end;
end;
end;
end.
|
Unit Initialisation;
Interface
// variables, types et structures
uses SDL, SDL_image, crt, sysutils;
Type Symbole = (coeur, carreau, pique, trefle);
Type Position = Record
x : LongInt ;
y : LongInt ;
end;
Type Indice = 1..52;
// Structure définie pour les cartes
Type Cartes = Record
retournee : Boolean ;
valeur : Integer ;
couleur : Boolean ;
sym : Symbole ;
pos : Position ;
ind : Indice;
existe : Boolean; // certaines cartes n'existent pas et sont là juste pour remplir le tableau
end;
Type Cartes_Restantes = set of Indice;
Type Pioche = Array[1..24] of Cartes;
Type Plateau = Array[1..7,1..21] of Cartes;
// Tableaux permettant de stocker l'état du jeu pour un tour donné pour le retour en arrière
Type SauvegardePlateau = Array[1..6] of Plateau;
Type SauvegardePioche = Array[1..6] of Pioche;
// Structure nécessaire pour l'interface graphique
Type TableauImages = Record
Verso : PSDL_surface;
Fond :PSDL_surface;
RetourArriere : PSDL_surface;
TabIm : Array[1..52] of PSDL_surface;
TabBouton : Array[1..3] of PSDL_Surface;
TabConfirmation : Array[1..3] of PSDL_Surface;
TabHighlight : Array[1..13] of PSDL_Surface;
end;
// Structure qui permet de changer les constantes afin de les adapter à la résolution de l'écran
Type Constantes = Record
E_cx, E_cy, Dx, Dy, Dyco, Dxco, Dypio, E_coy, w, l : Integer;
TailleFenetreX, TailleFenetreY : Integer;
Dxb, Dyb, E_b, TailleBoutonX, TailleBoutonY : Integer;
ConfX, ConfY, ConfOui, ConfBoutonY, ConfTailleBoutonX, ConfTailleBoutonY, ConfEspaceBouton : Integer;
end;
// Structure utilisée pour stocker tous les coups possible pour une carte
Type PositionsPossibles = record
pp : Array[1..7] of Position;
exists : Boolean;
nbPos : Integer;
end;
/////////////////////////////////////////////////////////////////////////////////////////
// Procédures et fonctions
Procedure initialiser_tout(var pl : Plateau; var pio : Pioche; var fenetre, ImageDeFond : PSDL_Surface; var images : TableauImages; var cst : Constantes);
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
Implementation
// Permet de connaître la definition de l'écran
Procedure TrouverDefinition (var fenetre : PSDL_Surface; var TailleEcran : TSDL_Rect);
begin
SDL_Init(SDL_INIT_VIDEO);
fenetre := SDL_SetVideoMode(0, 0, 32, SDL_FULLSCREEN);
sdl_getcliprect(fenetre, @TailleEcran);
end;
/////////////////////////////////////////////////////////////////////////////////////////
//
Function Load(TailleEcran : TSDL_Rect; str : String) : PSDL_Surface;
var chemin : String;
pchemin : pchar;
begin
if TailleEcran.w > 1400 then
begin
chemin := 'Ressources/1080p/' + str + '.png';
pchemin := StrAlloc(length(chemin) + 1);
strPCopy(pchemin, chemin);
end
else
begin
chemin := 'Ressources/720p/' + str + '.png';
pchemin := StrAlloc(length(chemin) + 1);
strPCopy(pchemin, chemin);
end;
Load := IMG_Load(pchemin);
end;
/////////////////////////////////////////////////////////////////////////////////////////
// Iitialisation de la SDL
Procedure Lancement (TailleEcran : TSDL_Rect; var images : TableauImages);
var str, chemin : String;
pimage : pchar;
i : Integer;
begin
images.RetourArriere := Load(TailleEcran, 'RetourArriere');
images.fond := Load(TailleEcran, 'Fond');
images.verso := Load(TailleEcran, 'Verso');
images.TabBouton[1] := Load(TailleEcran, 'RetourClic');
images.TabBouton[2] := Load(TailleEcran, 'AideClic');
images.TabBouton[3] := Load(TailleEcran, 'MenuClic');
images.TabConfirmation[1] := Load(TailleEcran, 'Confirmation');
images.TabConfirmation[2] := Load(TailleEcran, 'ConfirmationOui');
images.TabConfirmation[3] := Load(TailleEcran, 'ConfirmationNon');
if TailleEcran.w > 1400 then
chemin := 'Ressources/1080p/'
else
chemin := 'Ressources/720p/';
for i:= 1 to 52 do
begin
str := chemin + 'Carte_' + IntToStr(i) + '.png';
pimage := StrAlloc(length(str) + 1);
strPCopy(pimage, str);
images.TabIm[i] := IMG_Load(pimage);
end;
for i:= 1 to 13 do
begin
str := chemin + 'Highlight' + IntToStr(i) + '.png';
pimage := StrAlloc(length(str) + 1);
strPCopy(pimage, str);
images.TabHighlight[i] := IMG_Load(pimage);
end;
end;
// Créée les cartes et leur assigne un nombre entre 1 et 52
Function FabriquerCartes(ind : Integer) : Cartes;
begin
FabriquerCartes.retournee := False;
FabriquerCartes.pos.x := 1;
FabriquerCartes.pos.y := 1;
FabriquerCartes.ind := ind;
FabriquerCartes.existe := True;
if ind MOD 2 = 0
then
FabriquerCartes.couleur := True
else
FabriquerCartes.couleur := False;
FabriquerCartes.valeur := (1*(ind- ind MOD 4 + 1) + 3) MOD 4;
case (ind MOD 4) of
1 : begin
FabriquerCartes.sym := pique;
FabriquerCartes.valeur := trunc((ind + 3)/4);
end;
2 : begin
FabriquerCartes.sym := coeur;
FabriquerCartes.valeur := trunc((ind + 2)/4);
end;
3 : begin
FabriquerCartes.sym := trefle;
FabriquerCartes.valeur := trunc((ind + 1)/4);
end;
0 : begin
FabriquerCartes.sym := carreau;
FabriquerCartes.valeur := trunc(ind/4);
end;
end;
end;
/////////////////////////////////////////////////////////////////////////////////////////
// Remplit le tableau qui correspond au plateau de jeu (= distribue les cartes)
Procedure RemplirTableau(var pl : Plateau; var pio : Cartes_Restantes);
var i, j : Integer;
ind : Indice;
begin
for j:= 1 to 21 do // chaque case du tableau ne comporte pas carte
begin
for i:= 1 to 7 do
pl[i][j].existe := False;
end;
for i:= 1 to 4 do // 1ère ligne = les cartes "0" pour mettre avant les AS du haut
begin
pl[i][1].valeur := 0;
pl[i][1].pos.x := i;
pl[i][1].pos.y := 1;
if (i MOD 2) = 1 then
pl[i][1].couleur := false
else
pl[i][1].couleur := true;
case (i MOD 4) of
1 : pl[i][1].sym := pique;
2 : pl[i][1].sym := coeur;
3 : pl[i][1].sym := trefle;
0 : pl[i][1].sym := carreau;
end;
end;
for i:= 1 to 7 do // ligne 2 : carte de valeur "14" pour pouvoir ensuite placer un roi en dessous
begin
pl[i][2].valeur := 14;
pl[i][2].pos.x := i;
pl[i][2].pos.y := 2;
pl[i][2].retournee := true;
end;
i:=0;
repeat
i := i + 1;
Include(pio, i);
until i = 52;
randomize;
for j:= 3 to 9 do
begin
for i:=(j-2) to 7 do
begin
repeat
ind := random(52) + 1;
until ind in pio;
Exclude(pio, ind);
pl[i][j] := FabriquerCartes(ind);
pl[i][j].pos.x := i;
pl[i][j].pos.y := j;
if i = j-2 then
pl[i][j].retournee := True;
end;
end;
end;
/////////////////////////////////////////////////////////////////////////////////////////
// Crée un tableau avec la pioche
Procedure FabriquePioche(pio : Cartes_Restantes; var tpio : Pioche);
var a, i : Integer;
ind : set of 1..24;
begin
for i:= 1 to 24 do
Include(ind, i);
randomize;
for i:= 1 to 52 do
begin
if i in pio then
begin
repeat
a := random(24) + 1;
until a in ind;
tpio[a] := FabriquerCartes(i);
Exclude(ind, a);
end;
end;
end;
/////////////////////////////////////////////////////////////////////////////////////////
// Initialise la partie
Procedure Init(var pl : Plateau; var tpio : Pioche);
var pio : Cartes_Restantes;
begin
RemplirTableau(pl, pio);
FabriquePioche(pio, tpio);
end;
/////////////////////////////////////////////////////////////////////////////////////////
// Définit les constantes en fonction de la taille de l'écran
Procedure InitConstantes(TailleEcran : TSDL_Rect; var cst : Constantes);
begin
if TailleEcran.w > 1400 then
begin
cst.E_cx := 38; //Espacement en pixels entre 2 colonne de cartes
cst.E_cy := 30; //Espacement en pixels entre 2 cartes l'une sur l'autre
cst.Dx := 78; //Espacement en pixels entre le bord et la première colonne (x)
cst.Dy := 346; //Espacement en pixels entre le bord et la première colonne (y)
cst.Dyco := 108; //Espacement en pixels entre le bord et la première carte sur le côté (y)
cst.Dxco := 1544; //Espacement en pixels entre le bord et les cartes sur le côté (x)
cst.Dypio := 52; //Espacement en pixels entre le bord et la pioche (y)
cst.E_coy := 20; //Espacement en pixels entre 2 cartes sur le côté
cst.w := 154; // Largeur d'une carte en pixels
cst.l := 202; // Longueur d'une carte en pixels
cst.Dxb := 1011; //Espacement en pixels entre le bord et le bouton retour (x)
cst.Dyb := 132; //Espacement en pixels entre le bord et les boutons (y)
cst.E_b := 20; //Espacement en pixels entre 2 boutons (x)
cst.TailleBoutonX := 82;
cst.TailleBoutonY := 60;
cst.TailleFenetreX := 1920;
cst.TailleFenetreY := 1080;
cst.ConfX := 594;
cst.ConfY := 203;
cst.ConfOui := 196;
cst.ConfBoutonY := 109;
cst.ConfTailleBoutonX := 74;
cst.ConfTailleBoutonY := 38;
cst.ConfEspaceBouton := 48;
end
else
begin
cst.E_cx := 25; //Espacement en pixels entre 2 colonne de cartes
cst.E_cy := 20; //Espacement en pixels entre 2 cartes l'une sur l'autre
cst.Dx := 52; //Espacement en pixels entre le bord et la première colonne (x)
cst.Dy := 230; //Espacement en pixels entre le bord et la première colonne (y)
cst.Dyco := 72; //Espacement en pixels entre le bord et la première carte sur le côté (y)
cst.Dxco := 1029; //Espacement en pixels entre le bord et les cartes sur le côté (x)
cst.Dypio := 34; //Espacement en pixels entre le bord et la pioche (y)
cst.E_coy := 13; //Espacement en pixels entre 2 cartes sur le côté
cst.w := 102; // Largeur d'une carte en pixels
cst.l := 134; // Longueur d'une carte en pixels
cst.Dxb := 674; //Espacement en pixels entre le bord et le bouton retour (x)
cst.Dyb := 88; //Espacement en pixels entre le bord et les boutons (y)
cst.E_b := 13; //Espacement en pixels entre 2 boutons (x)
cst.TailleBoutonX := 54;
cst.TailleBoutonY := 40;
cst.TailleFenetreX := 1280;
cst.TailleFenetreY := 720;
cst.ConfX := 396;
cst.ConfY := 135;
cst.ConfOui := 130;
cst.ConfBoutonY := 72;
cst.ConfTailleBoutonX := 49;
cst.ConfTailleBoutonY := 25;
cst.ConfEspaceBouton := 32;
end;
end;
/////////////////////////////////////////////////////////////////////////////////////////
// initialise tout
Procedure initialiser_tout(var pl : Plateau; var pio : Pioche; var fenetre, ImageDeFond : PSDL_Surface; var images : TableauImages; var cst : Constantes);
var TailleEcran : TSDL_Rect;
begin
Init(pl, pio);
TrouverDefinition(fenetre, TailleEcran);
writeln('TailleEcran : ', TailleEcran.w, TailleEcran.h);
InitConstantes(TailleEcran, cst);
Lancement(TailleEcran, images);
writeln('lancement de la sdl');
end;
end.
|
unit uUnmarshall;
{
**Ronald Rodrigues Farias**
Observação: todo TJSONArray será tratado como um TObjectList<>
Certifique-se de instanciar todas as variáveis antes de passa-las para a função.
Faça o TypeCast de retorno nas chamadas;
Exemplo:
TLoja oJoalheria := TRttiunmarshall.JsonParaObjeto(oJoalheria, oJson) as TLoja;
TObjectList<TLoja> oShopping := TRttiunmarshall.JsonParaObjeto(oShopping, oJson) as TObjectList<TLoja>;
#o parâmetro Json pode ser enviado como TJSONValue ou String.:
oJson : TJSONValue;
...
oJson : string;
}
interface
uses
System.JSON, System.Rtti, System.SysUtils, System.Variants, System.Generics.Collections;
type
TRttiunmarshall = class
class function JsonParaObjeto(aOBJETO : TOBject ; aJSON : TJSONValue) : TObject; overload;
class function JsonParaObjeto(aOBJETO : TOBject ; aJSON : string) : TObject; overload;
end;
implementation
{ TRttiunmarshall }
class function TRttiunmarshall.JsonParaObjeto(aOBJETO : TOBject ; aJSON : TJSONValue): TObject;
var
rtContexto : TrttiContext; // variavel principal de rtti, deve ser iniciada antes de todas as outras
rtProperty : TRttiProperty; // property do atributo a ser preenchido do objeto a ser desserializado passado como argumento
rtMetodo : TRttiMethod; // metodo add do TObjectList<> a ser usado em contexto
rtTipoVarInObjeto: TTypeKind; // Tipo da Var json a ser assignada ao objeto
arraysFields : TArray<TRttiProperty>; // array com o nome das propertys do objeto, coletada no inicio da chamada
cont, i : integer; // variaveis contadoras
strClasse : string; // extrai o nome em texto da classe tipada no caso de TObjectList<>
oJson : TJSONObject; // simples conversão para evitar uso de cast do argumento aJSON (caso seja)
arrayJson : TJSONArray; // simples conversão para evitar uso de cast do argumento aJSON (caso seja)
oList, oRecurr : TObject; // variaveis auxiliares usadas quando há listas dentro de objetos ou listas diretas
oClass : TClass; // classe do objeto a ser preenchido, usado para instâncias e typecast ao add em lista
begin
rtContexto := TRttiContext.Create;
try
if aJSON is TJSONObject then begin
FreeAndNil(arraysFields);
arraysFields := rtContexto.GetType(aOBJETO.ClassType).GetProperties;
for i := 0 to Length(arraysFields)-1 do
begin
{--coleta das variaveis rtti utilizadas--}
rtProperty := rtContexto.GetType(aOBJETO.ClassType).GetProperty(arraysFields[i].Name);
rtTipoVarInObjeto := rtProperty.PropertyType.TypeKind;
{-}
oJson := aJSON as TJSONObject;
if oJson.GetValue(arraysFields[i].Name).Value <> 'null' then
begin
if oJson.GetValue(arraysFields[i].Name) is TJSONString then
begin
case rtTipoVarInObjeto of
tkInteger, tkInt64:
rtProperty.SetValue(aOBJETO, StrToInt(oJson.GetValue(arraysFields[i].Name).Value));
tkString, tkUString, tkLString, tkWString:
rtProperty.SetValue(aOBJETO, oJson.GetValue(arraysFields[i].Name).Value);
tkFloat:
begin
if rtProperty.PropertyType.ToString = 'TDateTime' then
rtProperty.SetValue(aOBJETO, VarToDateTime(oJson.GetValue(arraysFields[i].Name).Value))
else
rtProperty.SetValue(aOBJETO, StrToFloat(oJson.GetValue(arraysFields[i].Name).Value));
end;
end;
end
else if oJson.GetValue(arraysFields[i].Name) is TJSONArray then
begin
arrayJson := oJson.GetValue(arraysFields[i].Name) as TJSONArray;
strClasse := StringReplace(rtProperty.PropertyType.ToString, 'TOBjectList<', '', [rfReplaceAll, rfIgnoreCase]);
strClasse := StringReplace(strClasse, '>', '', [rfReplaceAll, rfIgnoreCase]);
oList := rtProperty.GetValue(aOBJETO).AsObject;
rtMetodo := rtContexto.GetType(oList.ClassType).GetMethod('Add');
for cont := 0 to arrayJson.Count -1 do
begin
try
oClass := TRttiInstanceType(rtContexto.FindType(strClasse)).MetaclassType;
oRecurr := oClass.Create;
oRecurr := Self.JsonParaObjeto(oRecurr, arrayJson.Items[cont]);
rtMetodo.Invoke(oList, [oRecurr]);
finally
end;
end;
rtProperty.SetValue(aOBJETO, oList); //adiciona a lista auxiliar no objeto
end;
end;
end;
end
else if aJSON is TJSONArray then
begin
arrayJson := aJSON as TJSONArray;
strClasse := StringReplace(aOBJETO.ClassName, 'TOBjectList<', '', [rfReplaceAll, rfIgnoreCase]);
strClasse := StringReplace(strClasse, '>', '', [rfReplaceAll, rfIgnoreCase]);
rtMetodo := rtContexto.GetType(aOBJETO.ClassType).GetMethod('Add');
for cont := 0 to arrayJson.Count -1 do
begin
oClass := TRttiInstanceType(rtContexto.FindType(strClasse)).MetaclassType;
oRecurr := oClass.Create;
oRecurr := Self.JsonParaObjeto(oRecurr, arrayJson.Items[cont]);
rtMetodo.Invoke(aOBJETO, [oRecurr]);
end;
end;
Result := aOBJETO;
finally
rtContexto.Free;
end;
end;
class function TRttiunmarshall.JsonParaObjeto(aOBJETO: TOBject; aJSON: string): TObject;
var
oJSON : TJSONValue;
begin
oJSON := TJSONObject.ParseJSONValue(aJSON);
try
Result := Self.JsonParaObjeto(aOBJETO, oJSON);
finally
oJSON.Free;
end;
end;
end.
|
unit ErrorMsg;
(*
Permission is hereby granted, on 6-May-2003, free of charge, to any person
obtaining a copy of this file (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.
*)
// Author of original version of this file: Michael Ax
interface
uses Classes, Graphics, Forms, Controls, Buttons
, Windows
{$IFNDEF NoEDIT}
, tpDbg
{$ENDIF}
, StdCtrls, ExtCtrls, SysUtils, Dialogs
, UpdateOk
, tpAction
, uctypes
;
{------------------------------------------------------------------------------}
type
TErrorDialog = class(TtpAction)
Error:Exception;
eSender: TObject;
private
fResult: TExceptionReAction;
fCanRetry: Boolean; {can an exception be retried?}
fCanIgnore: Boolean; {can an exception be ignored?}
protected
function GetTest:Boolean; override;
procedure SetTest(Value:Boolean); override;
public
constructor Create(aOwner:Tcomponent); override;
procedure ExceptionProc(Sender: TObject;E:Exception);
procedure RetryException(Sender:TObject;E:Exception;var Action:TExceptionReAction);
procedure DoExecute; Override;
published
property CanRetry: Boolean read fCanRetry write fCanRetry;
property CanIgnore: Boolean read fCanIgnore write fCanIgnore default true;
property Result: TExceptionReAction read fResult write fResult;
end;
{----------------------------------------------------------------------------------------}
//procedure Register;
implementation
{----------------------------------------------------------------------------------------}
{xxx$R *.DFM}
constructor TErrorDialog.Create(aOwner:TComponent);
begin
inherited Create(aOwner);
Error:=nil;
eSender:=nil;
fCanIgnore:=true;
Application.OnException:=ExceptionProc;
end;
procedure TErrorDialog.ExceptionProc(Sender: TObject;E:Exception);
begin
{$IFNDEF NoEDIT}
debuglog(sender,e.message);
{$ENDIF}
messagebeep($FFFF);
Error:=E;
eSender:=Sender;
Screen.Cursor:=crDefault;
Execute;
{ Application.ShowException(E); }
end;
procedure TErrorDialog.SetTest(Value:Boolean);
begin
Error:=Exception.Create('Test of '+Classname+'.'+Name);
eSender:=Self;
Execute;
Error.Free;
Error:=nil;
end;
function TErrorDialog.GetTest:Boolean;
begin
Result:=(fResult=reRetry);
end;
{------------------------------------------------------------------------------}
procedure TErrorDialog.RetryException(Sender:TObject;E:Exception;var Action:TExceptionReAction);
begin
eSender:=Sender;
Error:=E;
fResult:=Action;
Execute;
Action:=fResult;
end;
procedure TErrorDialog.DoExecute;
var
a1:string;
b:TMsgDlgButtons;
Cursor:TCursor;
begin
inherited DoExecute;
Cursor:=Screen.Cursor;
Screen.Cursor:=crDefault;
if fCanIgnore and fCanRetry then
b:=mbAbortRetryIgnore
else
if fCanIgnore then
b:=[mbIgnore,mbCancel]
else
if fCanRetry then
b:=[mbRetry,mbCancel]
else
b:=[mbCancel];
a1:=Error.ClassName+'! in '+eSender.ClassName;
if eSender is tComponent then
with tComponent(eSender) do
a1:=a1+'.'+Name;
a1:=a1+#13+Error.Message;
case MessageDlg(a1, mtError,b,0) of
mrOk,
mrRetry: fResult:=reRetry;
mrIgnore: fResult:=reIgnore;
else
fResult:=reRaise;
end;
Screen.Cursor:=Cursor;
end;
{----------------------------------------------------------------------------------------}
//procedure Register;
//begin
// RegisterComponents('TPACK', [TErrorDialog]);
//end;
(*
procedure TErrorDialogForm.DecodeError(Error:Exception);
var
i,n:integer;
plural:boolean;
a:string[3];
begin
if Error = nil then begin
Memo1.Text:='';
exit;
end;
plural:=false;
{
if Error is EdbEngineError then
with Error as EdbEngineError do begin
n:=ErrorCount;
plural:= n>1;
Memo1.Text:='Received '+inttostr(n)+' Error';
if plural then
Memo1.Text:=Memo1.Text+'s';
Memo1.Text:=Memo1.Text+' from the Database Engine that';
end
else
if Error is EdbEngineError then
Memo1.Text:='The Database Access layer reports an error that'
else
}
Memo1.Text:='An Error';
if plural then
a:='are'
else
a:='is';
Memo1.Text:=Memo1.Text+' '+a+' detailed below. Please decide how to proceed.';
Memo1.Lines.Add(' ');
{
if Error is EdbEngineError then
with Error as EdbEngineError do begin
for i:=0 to n-1 do
Memo1.Lines.Add(
inttostr(i+1)+'/'+inttostr(n)+': '
+'#'+inttostr(Errors[i].ErrorCode)+': '
+Errors[i].Message);
end
else
}
Memo1.Text:=Memo1.Text+' '+Error.ClassName+': '+Error.Message+'.';
end;
*)
{----------------------------------------------------------------------------------------}
end.
|
// -------------------------------------------------
// Isometric map demo / staggered and diamond
//--------------------------------------------------
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms,Dialogs, jpeg, ExtCtrls, StdCtrls;
type
TMapType = (DIAMOND, STAGGERED);
TForm1 = class(TForm)
image1: TImage;
btnDiamond: TButton;
btnStaggered: TButton;
procedure FormCreate(Sender: TObject);
procedure btnStaggeredClick(Sender: TObject);
procedure btnDiamondClick(Sender: TObject);
private
Tile: TBitmap;
offsetX, offsetY: integer; // X Y offsets to center map on screen
public
procedure RenderMap(xTiles, yTiles : integer; Tile: TBitmap; MapType: TMapType);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.RenderMap(xTiles, yTiles : integer; Tile: TBitmap; MapType: TMapType);
var
x, y, i, j : integer;
begin
offsetY := (ClientHeight - (yTiles * Tile.Height)) div 2; // Y Offset
if MapType = STAGGERED then
begin
offsetX := (ClientWidth - ((xTiles + 1) div 2 * Tile.Width)) div 2; // X Offset
for i := 0 to xTiles - 1 do
for j := 0 to yTiles - 1 do
begin
X := Tile.Width div 2 * i + offsetX;
if (i mod 2) = 0 then
Y := Tile.Height * j + offsetY
else
Y := Tile.Height * j + Tile.Height div 2 + offsetY;
// Render tile
Canvas.Draw(X, Y, Tile);
// Render tile's x,y coordinates on top of tile
Canvas.TextOut(x+20, y+10, IntToStr(i)+','+IntToStr(j));
sleep(50);
end;
end;
if MapType = DIAMOND then
begin
offsetX := ClientWidth div 2 - (Tile.Width div 2); // X Offset
for i := 0 to xTiles - 1 do
for j := 0 to yTiles - 1 do
begin
X := (i - j) * (Tile.Width div 2) + offsetX;
Y := (i + j) * (Tile.Height div 2) + offsetY;
// Render tile
Canvas.Draw(x , y, Tile);
// Render tile's x,y coordinates on top of tile
Canvas.TextOut(x + 20, y + 10, IntToStr(i)+','+IntToStr(j));
sleep(50);
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Canvas.Font.Style := [fsBold];
Canvas.Font.Color := ClYellow;
Canvas.Brush.Style := bsClear;
Tile := image1.Picture.Bitmap;
end;
procedure TForm1.btnStaggeredClick(Sender: TObject);
begin
// Clear form canvas
PatBlt(Canvas.Handle, 0, 0, ClientWidth, ClientHeight,BLACKNESS);
// Draw a 14x8 tiles staggered map
RenderMap(14, 8, Tile, STAGGERED);
end;
procedure TForm1.btnDiamondClick(Sender: TObject);
begin
// Clear form canvas
PatBlt(Canvas.Handle, 0, 0, ClientWidth, ClientHeight,BLACKNESS);
// Draw a 10x10 tiles diamond map
RenderMap(10, 10, Tile, DIAMOND);
end;
end.
|
unit Jwt;
interface
type
HCkJwt = Pointer;
HCkPrivateKey = Pointer;
HCkPublicKey = Pointer;
HCkString = Pointer;
function CkJwt_Create: HCkJwt; stdcall;
procedure CkJwt_Dispose(handle: HCkJwt); stdcall;
function CkJwt_getAutoCompact(objHandle: HCkJwt): wordbool; stdcall;
procedure CkJwt_putAutoCompact(objHandle: HCkJwt; newPropVal: wordbool); stdcall;
procedure CkJwt_getDebugLogFilePath(objHandle: HCkJwt; outPropVal: HCkString); stdcall;
procedure CkJwt_putDebugLogFilePath(objHandle: HCkJwt; newPropVal: PWideChar); stdcall;
function CkJwt__debugLogFilePath(objHandle: HCkJwt): PWideChar; stdcall;
procedure CkJwt_getLastErrorHtml(objHandle: HCkJwt; outPropVal: HCkString); stdcall;
function CkJwt__lastErrorHtml(objHandle: HCkJwt): PWideChar; stdcall;
procedure CkJwt_getLastErrorText(objHandle: HCkJwt; outPropVal: HCkString); stdcall;
function CkJwt__lastErrorText(objHandle: HCkJwt): PWideChar; stdcall;
procedure CkJwt_getLastErrorXml(objHandle: HCkJwt; outPropVal: HCkString); stdcall;
function CkJwt__lastErrorXml(objHandle: HCkJwt): PWideChar; stdcall;
function CkJwt_getLastMethodSuccess(objHandle: HCkJwt): wordbool; stdcall;
procedure CkJwt_putLastMethodSuccess(objHandle: HCkJwt; newPropVal: wordbool); stdcall;
function CkJwt_getVerboseLogging(objHandle: HCkJwt): wordbool; stdcall;
procedure CkJwt_putVerboseLogging(objHandle: HCkJwt; newPropVal: wordbool); stdcall;
procedure CkJwt_getVersion(objHandle: HCkJwt; outPropVal: HCkString); stdcall;
function CkJwt__version(objHandle: HCkJwt): PWideChar; stdcall;
function CkJwt_CreateJwt(objHandle: HCkJwt; header: PWideChar; payload: PWideChar; password: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkJwt__createJwt(objHandle: HCkJwt; header: PWideChar; payload: PWideChar; password: PWideChar): PWideChar; stdcall;
function CkJwt_CreateJwtPk(objHandle: HCkJwt; header: PWideChar; payload: PWideChar; key: HCkPrivateKey; outStr: HCkString): wordbool; stdcall;
function CkJwt__createJwtPk(objHandle: HCkJwt; header: PWideChar; payload: PWideChar; key: HCkPrivateKey): PWideChar; stdcall;
function CkJwt_GenNumericDate(objHandle: HCkJwt; numSecOffset: Integer): Integer; stdcall;
function CkJwt_GetHeader(objHandle: HCkJwt; token: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkJwt__getHeader(objHandle: HCkJwt; token: PWideChar): PWideChar; stdcall;
function CkJwt_GetPayload(objHandle: HCkJwt; token: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkJwt__getPayload(objHandle: HCkJwt; token: PWideChar): PWideChar; stdcall;
function CkJwt_IsTimeValid(objHandle: HCkJwt; jwt: PWideChar; leeway: Integer): wordbool; stdcall;
function CkJwt_SaveLastError(objHandle: HCkJwt; path: PWideChar): wordbool; stdcall;
function CkJwt_VerifyJwt(objHandle: HCkJwt; token: PWideChar; password: PWideChar): wordbool; stdcall;
function CkJwt_VerifyJwtPk(objHandle: HCkJwt; token: PWideChar; key: HCkPublicKey): wordbool; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkJwt_Create; external DLLName;
procedure CkJwt_Dispose; external DLLName;
function CkJwt_getAutoCompact; external DLLName;
procedure CkJwt_putAutoCompact; external DLLName;
procedure CkJwt_getDebugLogFilePath; external DLLName;
procedure CkJwt_putDebugLogFilePath; external DLLName;
function CkJwt__debugLogFilePath; external DLLName;
procedure CkJwt_getLastErrorHtml; external DLLName;
function CkJwt__lastErrorHtml; external DLLName;
procedure CkJwt_getLastErrorText; external DLLName;
function CkJwt__lastErrorText; external DLLName;
procedure CkJwt_getLastErrorXml; external DLLName;
function CkJwt__lastErrorXml; external DLLName;
function CkJwt_getLastMethodSuccess; external DLLName;
procedure CkJwt_putLastMethodSuccess; external DLLName;
function CkJwt_getVerboseLogging; external DLLName;
procedure CkJwt_putVerboseLogging; external DLLName;
procedure CkJwt_getVersion; external DLLName;
function CkJwt__version; external DLLName;
function CkJwt_CreateJwt; external DLLName;
function CkJwt__createJwt; external DLLName;
function CkJwt_CreateJwtPk; external DLLName;
function CkJwt__createJwtPk; external DLLName;
function CkJwt_GenNumericDate; external DLLName;
function CkJwt_GetHeader; external DLLName;
function CkJwt__getHeader; external DLLName;
function CkJwt_GetPayload; external DLLName;
function CkJwt__getPayload; external DLLName;
function CkJwt_IsTimeValid; external DLLName;
function CkJwt_SaveLastError; external DLLName;
function CkJwt_VerifyJwt; external DLLName;
function CkJwt_VerifyJwtPk; external DLLName;
end.
|
unit UAgendamento;
interface
uses
UEntidade
;
type
TAgendamento = class(TENTIDADE)
private
//Consultor:
FId_Consultor : Integer;
FNome_Consultor : String;
//Cliente:
FId_Cliente : Integer;
FNome_Cliente : String;
//Agendamento:
FData_Inicio : TDate;
FData_Termino : TDate;
FHorario_Inicio : TTime;
FHorario_Termino : TTime;
FDuracao : TTime;
FObeservacao : String;
function RetornaDataHoraInicio: TDateTime;
function RetornaDataHoraTermino: TDateTime;
public
//Consultor:
property ID_CONSULTOR : Integer read FId_Consultor write FId_Consultor;
property NOME_CONSULTOR : String read FNome_Consultor write FNome_Consultor;
//Cliente:
property ID_CLIENTE : Integer read FId_Cliente write FId_Cliente;
property NOME_CLIENTE : String read FNome_Cliente write FNome_Cliente;
//Agendamento:
property DATA_INICIO : TDate read FData_Inicio write FData_Inicio;
property DATA_TERMINO : TDate read FData_Termino write FData_Termino;
property HORARIO_INICIO : TTime read FHorario_Inicio write FHorario_Inicio;
property HORARIO_TERMINO : TTime read FHorario_Termino write FHorario_Termino;
property DURACAO : TTime read FDuracao write FDuracao;
property OBSERVACAO : String read FObeservacao write FObeservacao;
property DATA_HORA_INICIO: TDateTime read RetornaDataHoraInicio;
property DATA_HORA_TERMINO: TDateTime read RetornaDataHoraTermino;
end;
//Acesso banco de dados:
const
TBL_AGENDAMENTO = 'AGENDAMENTO';
//Consultor:
FLD_AGENDAMENTO_ID_CONSULTOR = 'ID_CONSULTOR';
FLD_AGENDAMENTO_NOME_CONSULTOR = 'NOME_CONSULTOR';
//Cliente:
FLD_AGENDAMENTO_ID_CLIENTE = 'ID_CLIENTE';
FLD_AGENDAMENTO_NOME_CLIENTE = 'NOME_CLIENTE';
FLD_AGENDAMENTO_DATA_INICIO = 'DATA_INICIO';
FLD_AGENDAMENTO_DATA_TERMINO = 'DATA_TERMINO';
FLD_AGENDAMENTO_HORARIO_INICIO = 'HORARIO_INICIO';
FLD_AGENDAMENTO_HORARIO_TERMINO = 'HORARIO_TERMINO';
FLD_AGENDAMENTO_DURACAO = 'DURACAO';
FLD_AGENDAMENTO_OBSERVACAO = 'OBSERVACAO';
//View:
VW_AGENDAMENTO = 'VW_AGENDAMENTO';
VW_AGENDAMENTO_ID = 'Código Agendamento';
VW_AGENDAMENTO_ID_CONSULTOR = 'Código Consultor';
VW_AGENDAMENTO_NOME_CONSULTOR = 'Consultor';
VW_AGENDAMENTO_ID_CLIENTE = 'Código Cliente';
VW_AGENDAMENTO_NOME_CLIENTE = 'Cliente';
VW_AGENDAMENTO_DATA_INICIO = 'Data Inícial';
VW_AGENDAMENTO_DATA_TERMINO = 'Data Termino';
VW_AGENDAMENTO_HORARIO_INICIO = 'Horario Inícial';
VW_AGENDAMENTO_HORARIO_TERMINO = 'Horario Termino';
VW_AGENDAMENTO_DURACAO = 'Duração';
VW_AGENDAMENTO_OBSERVACAO = 'Observação';
implementation
uses
SysUtils
;
{ TAgendamento }
function TAgendamento.RetornaDataHoraInicio: TDateTime;
var
loDataHoraInicio: TDateTime;
begin
loDataHoraInicio := DATA_INICIO;
ReplaceTime(loDataHoraInicio, HORARIO_INICIO + StrToTime('00:01:00'));
Result := loDataHoraInicio;
end;
function TAgendamento.RetornaDataHoraTermino: TDateTime;
var
loDataHoraTermino: TDateTime;
begin
loDataHoraTermino := DATA_TERMINO;
ReplaceTime(loDataHoraTermino, HORARIO_TERMINO - StrToTime('00:01:00'));
Result := loDataHoraTermino;
end;
end.
|
unit uHandlerStationR415DM;
interface
uses
uClientDM,
Generics.Collections,
IdTCPConnection,
SyncObjs,
SysUtils,
uRequestDM,
uStationR415DM,
uHandlerClientDM;
type
THandlerStationR415 = class (THandlerClient)
private
FOnAddStationR415: TAddRemoveUpdateClientEvent;
FOnRemoveStationR415: TAddRemoveUpdateClientEvent;
FonUpdateStationR415: TAddRemoveUpdateClientEvent;
procedure FindLinkedStation;
public
function RegistrationClient(Request: TRequest;Connection: TIdTCPConnection): Boolean;
function RemoveClient(Connection: TIdTCPConnection):Boolean;
procedure SendDisconnectClient(StationR415: TStationR415);
function FindByConnection (Connection: TIdTCPConnection):TStationR415;
procedure Update;
procedure SendTypeStation(StationR415: TStationR415);
procedure SendUserNameLinkedStation(StationR415:TStationR415);
procedure IsFinished(StationR415: TStationR415; state: string);
procedure SendTextMessageLinkedStation(StationR415: TStationR415; txtMeessage:string);
procedure StationFinished(StationR415: TStationR415);
procedure StationNoFinished(StationR415: TStationR415);
procedure SendWavesLinkedStation(StationR415: TStationR415; prd:String;prm:String);
procedure sendSetUstSvaziLinkedStation(StationR415: TStationR415; ustSvaz: string);
procedure sendStateOfGenerate(StationR415: TStationR415; state: string);
property onAddStationR415: TAddRemoveUpdateClientEvent
read FOnAddStationR415
write FOnAddStationR415;
property onRemoveStationR415: TAddRemoveUpdateClientEvent
read FOnRemoveStationR415
write FOnRemoveStationR415;
property onUpdateStationR415: TAddRemoveUpdateClientEvent
read FonUpdateStationR415
write FonUpdateStationR415;
end;
implementation
/// <summary>
/// Узнаем что клиент закончил и сохраняем данные на сервере
/// </summary>
/// <param name="StationR415">Объект класса TStationR415.</param>
procedure THandlerStationR415.IsFinished(StationR415: TStationR415; state: string);
begin
if StationR415 <> nil then
begin
if state = 'on' then
StationR415.AnotherFinish := true
else
StationR415.AnotherFinish := false;
end;
end;
/// <summary>
/// Пересылаем инфу о генераторе сопряженной станции
/// </summary>
/// <param name="StationR415">Объект класса TStationR415.</param>
procedure THandlerStationR415.sendStateOfGenerate(StationR415: TStationR415; state: string);
var Request: TRequest;
begin
if StationR415 <> nil then
begin
Request := TRequest.Create;
Request.Name := REQUEST_NAME_GEN_ACT;
Request.AddKeyValue(KEY_TYPE, 'r415'); // Тип клиента
Request.AddKeyValue(KEY_GENERATE, state);
if StationR415.LinkedStation <> nil then
begin
StationR415.LinkedStation.SendMessage(Request);
end;
Request.Destroy;
end;
end;
procedure THandlerStationR415.sendSetUstSvaziLinkedStation(StationR415: TStationR415; ustSvaz: string);
var Request: TRequest;
begin
if StationR415 <> nil then
begin
Request := TRequest.Create;
Request.Name := REQUEST_NAME_UST_SVAZI;
Request.AddKeyValue(KEY_TYPE, 'r415'); // Тип клиента
Request.AddKeyValue(KEY_SVAZ_SET, ustSvaz);
if StationR415.LinkedStation <> nil then
begin
StationR415.LinkedStation.SendMessage(Request);
end;
Request.Destroy;
end;
end;
procedure THandlerStationR415.SendWavesLinkedStation(StationR415: TStationR415;
prd:String;prm:String);
var Request: TRequest;
begin
if StationR415 <> nil then
begin
Request := TRequest.Create;
Request.Name := REQUEST_NAME_WAVES;
Request.AddKeyValue(KEY_TYPE, 'r415'); // Тип клиента
Request.AddKeyValue(KEY_TRANSMITTER_WAVE_A,prd); // Наши ключ и значение
Request.AddKeyValue(KEY_RECEIVER_WAVE_A,prm);
if StationR415.LinkedStation <> nil then
begin
StationR415.LinkedStation.SendMessage(Request);
end;
Request.Destroy;
end;
end;
/// <summary>
/// Передает клиенту текстовое сообщение для чата
/// </summary>
/// <param name="StationR415">Объект класса TStationR415.</param>
/// <param name="txtMeessage">Текстовое сообщение для отправки</param>
procedure THandlerStationR415.SendTextMessageLinkedStation(StationR415: TStationR415;
txtMeessage:string);
var Request: TRequest;
begin
if StationR415 <> nil then
begin
Request := TRequest.Create;
Request.Name := REQUEST_NAME_TEXT_MESSAGE;
Request.AddKeyValue(KEY_TYPE, 'r415'); // Тип клиента
Request.AddKeyValue(KEY_TEXT,txtMeessage); // Наши ключ и значение
if StationR415.LinkedStation <> nil then
begin
StationR415.LinkedStation.SendMessage(Request);
end;
Request.Destroy;
end;
end;
/// <summary>
/// Передает клиенту сообщение о типе клиента(главный/подчиненный).
/// </summary>
/// <param name="StationR415">Объект класса TStationR415.</param>
procedure THandlerStationR415.SendTypeStation(StationR415: TStationR415);
var Request: TRequest;
begin
if StationR415 <> nil then
begin
Request := TRequest.Create;
Request.Name := REQUEST_NAME_STATION_PARAMS;
Request.AddKeyValue(KEY_TYPE, VALUE_SERVER);
if StationR415.Head then
Request.AddKeyValue(KEY_STATUS, STATION_STATUS_MAIN)
else
Request.AddKeyValue(KEY_STATUS,STATION_STATUS_SUBORDINATE);
StationR415.SendMessage(Request);
Request.Destroy;
end;
end;
/// <summary>
/// Передает клиенту сообщение с позывным сопряженной станции.
/// </summary>
/// <param name="StationR415">Объект класса TStationR415.</param>
procedure THandlerStationR415.SendUserNameLinkedStation(StationR415:
TStationR415);
var Request: TRequest;
begin
if StationR415 <> nil then
begin
Request := TRequest.Create;
Request.Name := REQUEST_NAME_STATION_PARAMS;
Request.AddKeyValue(KEY_TYPE, CLIENT_STATION_R415);
Request.AddKeyValue(KEY_CONNECTED, BoolToStr(KEY_CONNECTED_TRUE));
Request.AddKeyValue(KEY_USERNAME, StationR415.LinkedStation.UserName);
StationR415.SendMessage(Request);
Request.Destroy;
end;
end;
/// <summary>
/// Сообщаем о том что настроились и сохраняем результат
/// </summary>
/// <param name="StationR415">Объект класса TStationR415.</param>
procedure THandlerStationR415.StationFinished(StationR415: TStationR415);
begin
if StationR415 <> nil then
begin
StationR415.AnotherFinish := true;
end;
end;
/// <summary>
/// Сообщаем о том что станция расстроена и сохраняем результат
/// </summary>
/// <param name="StationR415">Объект класса TStationR415.</param>
procedure THandlerStationR415.StationNoFinished(StationR415: TStationR415);
begin
if StationR415 <> nil then
begin
StationR415.AnotherFinish := false;
end;
end;
/// <summary>
/// Ищет не связанные станции и производит их связывание.
/// </summary>
procedure THandlerStationR415.FindLinkedStation;
var
i, j: Integer;
begin
for i := 0 to Count - 1 do
begin
if (Clients.Items[i] as TStationR415).LinkedStation = nil then
begin
for j := 0 to Count - 1 do
begin
if ((Clients.Items[j]as TStationR415).LinkedStation = nil)
and (Clients.Items[i] <> Clients.Items[j])
and (i <> j) then
begin
Section.Enter;
(Clients.Items[j] as TStationR415).LinkedStation :=
(Clients.Items[i] as TStationR415);
(Clients.Items[i] as TStationR415).LinkedStation :=
(Clients.Items[j] as TStationR415);
(Clients.Items[j] as TStationR415).Head := True;
SendTypeStation((Clients.Items[j] as TStationR415));
(Clients.Items[i] as TStationR415).Head := False;
SendTypeStation((Clients.Items[i] as TStationR415));
SendUserNameLinkedStation((Clients.Items[j] as TStationR415));
SendUserNameLinkedStation((Clients.Items[i] as TStationR415));
onUpdateStationR415((Clients.Items[j] as TStationR415));
onUpdateStationR415((Clients.Items[i] as TStationR415));
Section.Leave;
Break;
end;
end;
end;
end;
end;
/// <summary>
/// Производит обновление.
/// </summary>
procedure THandlerStationR415.Update;
begin
FindLinkedStation;
end;
/// <summary>
/// Передает клиенту сообщение о отключении клиента.
/// </summary>
/// <param name="StationR415">Объект класса TStationR415.</param>
procedure THandlerStationR415.SendDisconnectClient(StationR415: TStationR415);
var
Request: TRequest;
begin
Request := TRequest.Create;
Request.Name := REQUEST_NAME_STATION_PARAMS;
Request.AddKeyValue(KEY_TYPE, CLIENT_STATION_R415);
Request.AddKeyValue(KEY_USERNAME, StationR415.UserName);
Request.AddKeyValue(KEY_CONNECTED, BoolToStr(KEY_CONNECTED_FALSE));
if StationR415.LinkedStation <> nil then
begin
StationR415.LinkedStation.SendMessage(Request);
end;
end;
/// <summary>
/// Производит поиск клиента по подключению.
/// </summary>
/// <param name="Connection">Объект класса TIdTCPConnection.</param>
function THandlerStationR415.FindByConnection (Connection: TIdTCPConnection):
TStationR415;
var
Client: TClient;
begin
Client := inherited FindByConnection(Connection);
if ((Client <> nil) and (Client is TStationR415)) then
begin
Exit((Client as TStationR415))
end;
Exit(nil);
end;
/// <summary>
/// Производит удаление станции из списка.
/// </summary>
/// <param name="Connection">Объект класса TIdTCPConnection.</param>
function THandlerStationR415.RemoveClient(Connection: TIdTCPConnection):
Boolean;
var
bStation: TStationR415;
begin
bStation := FindByConnection(Connection);
if bStation <> nil then
begin
bStation.Head := False;
if bStation.LinkedStation <> nil then
begin
bStation.LinkedStation.Head := False;
bStation.LinkedStation.LinkedStation := nil;
end;
if bStation.LinkedStation <> nil then
begin
SendDisconnectClient(bStation);
bStation.LinkedStation.Head := False;
onUpdateStationR415(bStation.LinkedStation);
end;
onRemoveStationR415(bStation);
Clients.Remove(bStation);
Update;
Exit(True);
end;
Exit(False);
end;
function THandlerStationR415.RegistrationClient(Request: TRequest;
Connection: TIdTCPConnection): Boolean;
var
bStationR415: TStationR415;
Name: string;
begin
Name := Request.GetValue('username');
bStationR415 := TStationR415.Create;
if (Connection <> nil)
and (Length(Name) > 0)
and (CheckUserName(Name)) then
begin
bStationR415.UserName := Name;
bStationR415.Connection := Connection;
Clients.Add(bStationR415);
SendOkClient(bStationR415);
onAddStationR415(bStationR415);
Update;
Exit(True);
end;
Exit(False);
end;
end.
|
// GLSkydome
{: Skydome object<p>
<b>Historique : </b><font size=-1><ul>
<li>12/03/01 - EG - Reversed polar caps orientation
<li>28/01/01 - EG - Fixed TSkyDomeBand rendering (vertex coordinates)
<li>18/01/01 - EG - First working version of TEarthSkyDome
<li>14/01/01 - EG - Creation
</ul></font>
}
unit GLSkydome;
interface
uses Classes, GLScene, GLMisc, GLTexture;
type
// TSkyDomeBand
//
TSkyDomeBand = class (TCollectionItem)
private
{ Private Declarations }
FStartAngle : Single;
FStopAngle : Single;
FStartColor : TGLColor;
FStopColor : TGLColor;
FSlices : Integer;
FStacks : Integer;
protected
{ Protected Declarations }
function GetDisplayName : String; override;
procedure SetStartAngle(const val : Single);
procedure SetStartColor(const val : TGLColor);
procedure SetStopAngle(const val : Single);
procedure SetStopColor(const val : TGLColor);
procedure SetSlices(const val : Integer);
procedure SetStacks(const val : Integer);
procedure OnColorChange(sender : TObject);
public
{ Public Declarations }
constructor Create(Collection : TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure BuildList(var rci : TRenderContextInfo);
published
{ Published Declarations }
property StartAngle : Single read FStartAngle write SetStartAngle;
property StartColor : TGLColor read FStartColor write SetStartColor;
property StopAngle : Single read FStopAngle write SetStopAngle;
property StopColor : TGLColor read FStopColor write SetStopColor;
property Slices : Integer read FSlices write SetSlices default 12;
property Stacks : Integer read FStacks write SetStacks default 1;
end;
// TSkyDomeBands
//
TSkyDomeBands = class (TCollection)
protected
{ Protected Declarations }
owner : TComponent;
function GetOwner: TPersistent; override;
procedure SetItems(index : Integer; const val : TSkyDomeBand);
function GetItems(index : Integer) : TSkyDomeBand;
public
{ Public Declarations }
constructor Create(AOwner : TComponent);
function Add: TSkyDomeBand;
function FindItemID(ID: Integer): TSkyDomeBand;
property Items[index : Integer] : TSkyDomeBand read GetItems write SetItems; default;
procedure NotifyChange;
procedure BuildList(var rci : TRenderContextInfo);
end;
// TSkyDome
//
{: Renders a sky dome always centered on the camera.<p>
If you use this object make sure it is rendered *first*, as it ignores
depth buffering and overwrites everything.<p>
The skydome is described by "bands", each "band" is an horizontal cut
of a sphere, and you can have as many bands as you wish.<p>
Estimated CPU cost (K7-500, GeForce SDR, default bands):<ul>
<li>800x600 fullscreen filled: 4.5 ms (220 FPS, worst case)
<li>Geometry cost (0% fill): 0.7 ms (1300 FPS, best case)
</ul> }
TSkyDome = class (TGLImmaterialSceneObject)
private
{ Private Declarations }
FBands : TSkyDomeBands;
protected
{ Protected Declarations }
procedure SetBands(const val : TSkyDomeBands);
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure DoRender(var rci : TRenderContextInfo); override;
procedure BuildList(var rci : TRenderContextInfo); override;
published
{ Published Declarations }
property Bands : TSkyDomeBands read FBands write SetBands;
end;
// TEarthSkyDome
//
{: Render a skydome like what can be seen on earth.<p>
Color is based on sun position and turbidity, to "mimic" atmospheric
Rayleigh and Mie scatterings. The colors can be adjusted to render
weird/extra-terrestrial atmospheres too.<p>
The default slices/stacks values make for an average quality rendering,
for a very clean rendering, use 64/64 (more is overkill in most cases).
The complexity is quite high though, making a T&L 3D board a necessity
for using TEarthSkyDome. }
TEarthSkyDome = class (TSkyDome)
private
{ Private Declarations }
FSunElevation : Single;
FTurbidity : Single;
FCurSunColor, FCurSkyColor, FCurHazeColor : TColorVector;
FCurHazeTurbid, FCurSunSkyTurbid : Single;
FSunZenithColor : TGLColor;
FSunDawnColor : TGLColor;
FHazeColor : TGLColor;
FSkyColor : TGLColor;
FNightColor : TGLColor;
FSlices, FStacks : Integer;
protected
{ Protected Declarations }
procedure SetSunElevation(const val : Single);
procedure SetTurbidity(const val : Single);
procedure SetSunZenithColor(const val : TGLColor);
procedure SetSunDawnColor(const val : TGLColor);
procedure SetHazeColor(const val : TGLColor);
procedure SetSkyColor(const val : TGLColor);
procedure SetNightColor(const val : TGLColor);
procedure SetSlices(const val : Integer);
procedure SetStacks(const val : Integer);
procedure OnColorChanged(Sender : TObject);
procedure PreCalculate;
procedure RenderDome;
function CalculateColor(const theta, cosGamma : Single) : TColorVector;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure BuildList(var rci : TRenderContextInfo); override;
published
{ Published Declarations }
{: Elevation of the sun, measured in degrees. }
property SunElevation : Single read FSunElevation write SetSunElevation;
{: Expresses the purity of air.<p>
Value range is from 1 (pure athmosphere) to 120 (very nebulous) }
property Turbidity : Single read FTurbidity write SetTurbidity;
property SunZenithColor : TGLColor read FSunZenithColor write SetSunZenithColor;
property SunDawnColor : TGLColor read FSunDawnColor write SetSunDawnColor;
property HazeColor : TGLColor read FHazeColor write SetHazeColor;
property SkyColor : TGLColor read FSkyColor write SetSkyColor;
property NightColor : TGLColor read FNightColor write SetNightColor;
property Slices : Integer read FSlices write SetSlices default 24;
property Stacks : Integer read FStacks write SetStacks default 48;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils, Geometry, OpenGL12;
// ------------------
// ------------------ TSkyDomeBand ------------------
// ------------------
// Create
//
constructor TSkyDomeBand.Create(Collection : TCollection);
begin
inherited Create(Collection);
FStartColor:=TGLColor.Create(Self);
FStartColor.Initialize(clrBlue);
FStartColor.OnNotifyChange:=OnColorChange;
FStopColor:=TGLColor.Create(Self);
FStopColor.Initialize(clrBlue);
FStopColor.OnNotifyChange:=OnColorChange;
FSlices:=12;
FStacks:=1;
end;
// Destroy
//
destructor TSkyDomeBand.Destroy;
begin
FStartColor.Free;
FStopColor.Free;
inherited Destroy;
end;
// Assign
//
procedure TSkyDomeBand.Assign(Source: TPersistent);
begin
if Source is TSkyDomeBand then begin
FStartAngle:=TSkyDomeBand(Source).FStartAngle;
FStopAngle:=TSkyDomeBand(Source).FStopAngle;
FStartColor.Assign(TSkyDomeBand(Source).FStartColor);
FStopColor.Assign(TSkyDomeBand(Source).FStopColor);
FSlices:=TSkyDomeBand(Source).FSlices;
FStacks:=TSkyDomeBand(Source).FStacks;
end;
inherited Destroy;
end;
// GetDisplayName
//
function TSkyDomeBand.GetDisplayName : String;
begin
Result:=Format('%d: %.1f° - %.1f°', [Index, StartAngle, StopAngle]);
end;
// SetStartAngle
//
procedure TSkyDomeBand.SetStartAngle(const val : Single);
begin
FStartAngle:=ClampValue(val, -90, 90);
if FStartAngle>FStopAngle then
FStopAngle:=FStartAngle;
TSkyDomeBands(Collection).NotifyChange;
end;
// SetStartColor
//
procedure TSkyDomeBand.SetStartColor(const val : TGLColor);
begin
FStartColor.Assign(val);
end;
// SetStopAngle
//
procedure TSkyDomeBand.SetStopAngle(const val : Single);
begin
FStopAngle:=ClampValue(val, -90, 90);
if FStopAngle<FStartAngle then
FStartAngle:=FStopAngle;
TSkyDomeBands(Collection).NotifyChange;
end;
// SetStopColor
//
procedure TSkyDomeBand.SetStopColor(const val : TGLColor);
begin
FStopColor.Assign(val);
end;
// SetSlices
//
procedure TSkyDomeBand.SetSlices(const val : Integer);
begin
if val<3 then
FSlices:=3
else FSlices:=val;
TSkyDomeBands(Collection).NotifyChange;
end;
// SetStacks
//
procedure TSkyDomeBand.SetStacks(const val : Integer);
begin
if val<1 then
FStacks:=1
else FStacks:=val;
TSkyDomeBands(Collection).NotifyChange;
end;
// OnColorChange
//
procedure TSkyDomeBand.OnColorChange(sender : TObject);
begin
TSkyDomeBands(Collection).NotifyChange;
end;
// BuildList
//
procedure TSkyDomeBand.BuildList(var rci : TRenderContextInfo);
// coordinates system note: X is forward, Y is left and Z is up
// always rendered as sphere of radius 1
procedure RenderBand(start, stop : Single; const colStart, colStop : TColorVector);
var
i : Integer;
f, r, r2 : Single;
vertex1, vertex2 : TVector;
begin
vertex1[3]:=1;
if start=-90 then begin
// triangle fan with south pole
glBegin(GL_TRIANGLE_FAN);
glColor4fv(@colStart);
glVertex3f(0, 0, -1);
f:=2*PI/Slices;
SinCos(DegToRad(stop), vertex1[2], r);
glColor4fv(@colStop);
for i:=0 to Slices do begin
SinCos(i*f, r, vertex1[1], vertex1[0]);
glVertex4fv(@vertex1);
end;
glEnd;
end else if stop=90 then begin
// triangle fan with north pole
glBegin(GL_TRIANGLE_FAN);
glColor4fv(@colStop);
glVertex3fv(@ZHmgPoint);
f:=2*PI/Slices;
SinCos(DegToRad(start), vertex1[2], r);
glColor4fv(@colStart);
for i:=Slices downto 0 do begin
SinCos(i*f, r, vertex1[1], vertex1[0]);
glVertex4fv(@vertex1);
end;
glEnd;
end else begin
vertex2[3]:=1;
// triangle strip
glBegin(GL_TRIANGLE_STRIP);
f:=2*PI/Slices;
SinCos(DegToRad(start), vertex1[2], r);
SinCos(DegToRad(stop), vertex2[2], r2);
for i:=0 to Slices do begin
SinCos(i*f, r, vertex1[1], vertex1[0]);
glColor4fv(@colStart);
glVertex4fv(@vertex1);
SinCos(i*f, r2, vertex2[1], vertex2[0]);
glColor4fv(@colStop);
glVertex4fv(@vertex2);
end;
glEnd;
end;
end;
var
n : Integer;
t, t2 : Single;
begin
if StartAngle=StopAngle then Exit;
for n:=0 to Stacks-1 do begin
t:=n/Stacks;
t2:=(n+1)/Stacks;
RenderBand(Lerp(StartAngle, StopAngle, t),
Lerp(StartAngle, StopAngle, t2),
VectorLerp(StartColor.Color, StopColor.Color, t),
VectorLerp(StartColor.Color, StopColor.Color, t2));
end;
end;
// ------------------
// ------------------ TSkyDomeBands ------------------
// ------------------
constructor TSkyDomeBands.Create(AOwner : TComponent);
begin
Owner:=AOwner;
inherited Create(TSkyDomeBand);
end;
function TSkyDomeBands.GetOwner: TPersistent;
begin
Result:=Owner;
end;
procedure TSkyDomeBands.SetItems(index : Integer; const val : TSkyDomeBand);
begin
inherited Items[index]:=val;
end;
function TSkyDomeBands.GetItems(index : Integer) : TSkyDomeBand;
begin
Result:=TSkyDomeBand(inherited Items[index]);
end;
function TSkyDomeBands.Add: TSkyDomeBand;
begin
Result:=(inherited Add) as TSkyDomeBand;
end;
function TSkyDomeBands.FindItemID(ID: Integer): TSkyDomeBand;
begin
Result:=(inherited FindItemID(ID)) as TSkyDomeBand;
end;
procedure TSkyDomeBands.NotifyChange;
begin
if Assigned(owner) and (owner is TGLBaseSceneObject) then
TGLBaseSceneObject(owner).StructureChanged;
end;
// BuildList
//
procedure TSkyDomeBands.BuildList(var rci : TRenderContextInfo);
var
i : Integer;
begin
for i:=0 to Count-1 do
Items[i].BuildList(rci);
end;
// ------------------
// ------------------ TSkyDome ------------------
// ------------------
// CreateOwned
//
constructor TSkyDome.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBands:=TSkyDomeBands.Create(Self);
with FBands.Add do begin
StartAngle:=0;
StartColor.Color:=clrWhite;
StopAngle:=15;
StopColor.Color:=clrBlue;
end;
with FBands.Add do begin
StartAngle:=15;
StartColor.Color:=clrBlue;
StopAngle:=90;
Stacks:=4;
StopColor.Color:=clrNavy;
end;
end;
// Destroy
//
destructor TSkyDome.Destroy;
begin
FBands.Free;
inherited Destroy;
end;
// Assign
//
procedure TSkyDome.Assign(Source: TPersistent);
begin
if Source is TSkyDome then begin
FBands.Assign(TSkyDome(Source).FBands);
end;
inherited;
end;
// SetBands
//
procedure TSkyDome.SetBands(const val : TSkyDomeBands);
begin
FBands.Assign(val);
StructureChanged;
end;
// BuildList
//
procedure TSkyDome.BuildList(var rci : TRenderContextInfo);
begin
Bands.BuildList(rci);
end;
// DoRender
//
procedure TSkyDome.DoRender(var rci : TRenderContextInfo);
var
f : Single;
begin
// prepare
glPushAttrib(GL_ENABLE_BIT);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glDisable(GL_FOG);
glPushMatrix;
glLoadMatrixf(@Scene.CurrentViewer.ModelViewMatrix);
glTranslatef(rci.cameraPosition[0], rci.cameraPosition[1], rci.cameraPosition[2]);
with Scene.CurrentGLCamera do
f:=(NearPlane+DepthOfView)*0.9;
glScalef(f, f, f);
glMultMatrixf(@LocalMatrix);
// render
glCallList(GetHandle(rci));
// restore
glPopMatrix;
glPopAttrib;
// process childs
if Count>0 then
RenderChildren(0, Count-1, rci);
end;
// ------------------
// ------------------ TEarthSkyDome ------------------
// ------------------
// CreateOwned
//
constructor TEarthSkyDome.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Bands.Clear;
FSunElevation:=75;
FTurbidity:=15;
FSunZenithColor:=TGLColor.CreateInitialized(Self, clrWhite, OnColorChanged);
FSunDawnColor:=TGLColor.CreateInitialized(Self, clrCoral, OnColorChanged);
FHazeColor:=TGLColor.CreateInitialized(Self, clrWhite, OnColorChanged);
FSkyColor:=TGLColor.CreateInitialized(Self, clrBlue, OnColorChanged);
FNightColor:=TGLColor.CreateInitialized(Self, clrBlack, OnColorChanged);
FStacks:=24;
FSlices:=48;
PreCalculate;
end;
// Destroy
//
destructor TEarthSkyDome.Destroy;
begin
FSunZenithColor.Free;
FSunDawnColor.Free;
FHazeColor.Free;
FSkyColor.Free;
FNightColor.Free;
inherited Destroy;
end;
// Assign
//
procedure TEarthSkyDome.Assign(Source: TPersistent);
begin
if Source is TSkyDome then begin
FSunElevation:=TEarthSkyDome(Source).SunElevation;
FTurbidity:=TEarthSkyDome(Source).Turbidity;
FSunZenithColor.Assign(TEarthSkyDome(Source).FSunZenithColor);
FSunDawnColor.Assign(TEarthSkyDome(Source).FSunDawnColor);
FHazeColor.Assign(TEarthSkyDome(Source).FHazeColor);
FSkyColor.Assign(TEarthSkyDome(Source).FSkyColor);
FNightColor.Assign(TEarthSkyDome(Source).FNightColor);
FSlices:=TEarthSkyDome(Source).FSlices;
FStacks:=TEarthSkyDome(Source).FStacks;
PreCalculate;
end;
inherited;
end;
// SetSunElevation
//
procedure TEarthSkyDome.SetSunElevation(const val : Single);
begin
FSunElevation:=ClampValue(val, -90, 90);
PreCalculate;
end;
// SetTurbidity
//
procedure TEarthSkyDome.SetTurbidity(const val : Single);
begin
FTurbidity:=ClampValue(val, 1, 120);
PreCalculate;
end;
// SetSunZenithColor
//
procedure TEarthSkyDome.SetSunZenithColor(const val : TGLColor);
begin
FSunZenithColor.Assign(val);
PreCalculate;
end;
// SetSunDawnColor
//
procedure TEarthSkyDome.SetSunDawnColor(const val : TGLColor);
begin
FSunDawnColor.Assign(val);
PreCalculate;
end;
// SetHazeColor
//
procedure TEarthSkyDome.SetHazeColor(const val : TGLColor);
begin
FHazeColor.Assign(val);
PreCalculate;
end;
// SetSkyColor
//
procedure TEarthSkyDome.SetSkyColor(const val : TGLColor);
begin
FSkyColor.Assign(val);
PreCalculate;
end;
// SetNightColor
//
procedure TEarthSkyDome.SetNightColor(const val : TGLColor);
begin
FNightColor.Assign(val);
PreCalculate;
end;
// SetSlices
//
procedure TEarthSkyDome.SetSlices(const val : Integer);
begin
if val>6 then
FSlices:=val
else FSlices:=6;
StructureChanged;
end;
// SetStacks
//
procedure TEarthSkyDome.SetStacks(const val : Integer);
begin
if val>1 then
FStacks:=val
else FStacks:=1;
StructureChanged;
end;
// BuildList
//
procedure TEarthSkyDome.BuildList(var rci : TRenderContextInfo);
begin
RenderDome;
inherited;
end;
// OnColorChanged
//
procedure TEarthSkyDome.OnColorChanged(Sender : TObject);
begin
PreCalculate;
end;
// PreCalculate
//
procedure TEarthSkyDome.PreCalculate;
var
ts : Single;
fts : Single;
begin
ts:=DegToRad(90-SunElevation);
// Precompose base colors
fts:=exp(-3*(PI/2-ts));
VectorLerp(clrWhite, clrYellow, fts, FCurSunColor);
fts:=1-cos(ts-0.5);
VectorLerp(clrWhite, clrBlack, fts, FCurHazeColor);
VectorLerp(clrBlue, clrBlack, fts, FCurSkyColor);
// Precalculate Turbidity factors
FCurHazeTurbid:=-sqrt(121-Turbidity)*2;
FCurSunSkyTurbid:=-(121-Turbidity);
StructureChanged;
end;
// CalculateColor
//
function TEarthSkyDome.CalculateColor(const theta, cosGamma : Single) : TColorVector;
var
t : Single;
begin
t:=PI/2-theta;
// mix to get haze/sky
VectorLerp(FCurSkyColor, FCurHazeColor, exp(FCurHazeTurbid*t), Result);
// then mix sky with sun
VectorLerp(Result, FCurSunColor, exp(FCurSunSkyTurbid*cosGamma*(1+t)), Result);
end;
// SetSunElevation
//
procedure TEarthSkyDome.RenderDome;
var
ts : Single;
steps : Integer;
sunPos : TAffineVector;
sinTable, cosTable : PFloatArray;
// coordinates system note: X is forward, Y is left and Z is up
// always rendered as sphere of radius 1
function CalculateCosGamma(const p : TVector) : Single;
begin
Result:=1-VectorAngle(PAffineVector(@p)^, sunPos);
end;
procedure RenderBand(start, stop : Single);
var
i : Integer;
r, r2, thetaStart, thetaStop : Single;
vertex1, vertex2 : TVector;
color : TColorVector;
begin
vertex1[3]:=1;
if stop=90 then begin
// triangle fan with north pole
glBegin(GL_TRIANGLE_FAN);
color:=CalculateColor(0, CalculateCosGamma(ZHmgPoint));
glColor4fv(@color);
glVertex4fv(@ZHmgPoint);
SinCos(DegToRad(start), vertex1[2], r);
thetaStart:=DegToRad(90-start);
for i:=0 to steps do begin
vertex1[0]:=r*cosTable[i];
vertex1[1]:=r*sinTable[i];
color:=CalculateColor(thetaStart, CalculateCosGamma(vertex1));
glColor4fv(@color);
glVertex4fv(@vertex1);
end;
glEnd;
end else begin
vertex2[3]:=1;
// triangle strip
glBegin(GL_TRIANGLE_STRIP);
SinCos(DegToRad(start), vertex1[2], r);
SinCos(DegToRad(stop), vertex2[2], r2);
thetaStart:=DegToRad(90-start);
thetaStop:=DegToRad(90-stop);
for i:=0 to steps do begin
vertex1[0]:=r*cosTable[i];
vertex1[1]:=r*sinTable[i];
color:=CalculateColor(thetaStart, CalculateCosGamma(vertex1));
glColor4fv(@color);
glVertex4fv(@vertex1);
vertex2[0]:=r2*cosTable[i];
vertex2[1]:=r2*sinTable[i];
color:=CalculateColor(thetaStop, CalculateCosGamma(vertex2));
glColor4fv(@color);
glVertex4fv(@vertex2);
end;
glEnd;
end;
end;
var
n, i : Integer;
t, t2, p : Single;
begin
ts:=DegToRad(90-SunElevation);
SetVector(sunPos, sin(ts), 0, cos(ts));
// prepare sin/cos LUT, with a higher sampling around 0°
n:=Slices div 2;
steps:=2*n+1;
GetMem(sinTable, steps*SizeOf(Single));
GetMem(cosTable, steps*SizeOf(Single));
for i:=1 to n do begin
p:=(1-sqrt(cos(i/n*PI/2)))*PI;
SinCos(p, sinTable[n+i], cosTable[n+i]);
sinTable[n-i]:=-sinTable[n+i];
cosTable[n-i]:=cosTable[n+i];
end;
sinTable[n]:=0;
cosTable[n]:=1;
// start render
for n:=0 to Stacks-1 do begin
t:=n/Stacks;
t2:=(n+1)/Stacks;
RenderBand(Lerp(1, 90, t), Lerp(1, 90, t2));
end;
FreeMem(sinTable);
FreeMem(cosTable);
end;
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
initialization
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
RegisterClasses([TSkyDome, TEarthSkyDome]);
end.
|
unit uFrameInOutSearch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxControls,
cxContainer, cxEdit, dxSkinsCore, dxSkinCaramel, cxTextEdit, cxMaskEdit,
cxDropDownEdit, StdCtrls, cxButtons, ADODB, uGlobal, uConfig, uDB, cxLabel,
dxSkinBlack, dxSkinBlue, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinFoggy, dxSkinGlassOceans, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinPumpkin, dxSkinSeven,
dxSkinSharp, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinsDefaultPainters, dxSkinValentine, dxSkinXmas2008Blue, dxSkinBlueprint,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinHighContrast,
dxSkinMetropolis, dxSkinMetropolisDark, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray,
dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinSevenClassic,
dxSkinSharpPlus, dxSkinTheAsphaltWorld, dxSkinVS2010, dxSkinWhiteprint;
type
TframeInOutSearch = class(TFrame)
Label3: TLabel;
btnSearch: TcxButton;
cboCondition: TcxComboBox;
txtSearch: TcxTextEdit;
cboInOut: TcxComboBox;
cboBohum: TcxComboBox;
Label1: TLabel;
Label2: TLabel;
cboWard: TcxComboBox;
lblWard: TLabel;
cboSort: TcxComboBox;
Label4: TLabel;
procedure btnSearchClick(Sender: TObject);
procedure cboWardPropertiesChange(Sender: TObject);
procedure cboInOutPropertiesChange(Sender: TObject);
procedure cboBohumPropertiesChange(Sender: TObject);
procedure cboSortPropertiesChange(Sender: TObject);
procedure txtSearchKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
FDate: string;
FPPYearMonth: string;
FLoaded: Boolean;
FWardID: integer;
public
{ Public declarations }
FInOut: TADOStoredProc;
procedure LoadInOut;
procedure ClearControls;
procedure SetValue(oT: TADOStoredProc; nWardID: integer; sDate, sPPYearMonth: string);
end;
implementation
{$R *.dfm}
{ TframeInOutSearch }
procedure TframeInOutSearch.btnSearchClick(Sender: TObject);
begin
LoadInOut;
end;
procedure TframeInOutSearch.cboBohumPropertiesChange(Sender: TObject);
begin
LoadInOut;
end;
procedure TframeInOutSearch.cboInOutPropertiesChange(Sender: TObject);
begin
LoadInOut;
end;
procedure TframeInOutSearch.cboSortPropertiesChange(Sender: TObject);
begin
LoadInOut;
end;
procedure TframeInOutSearch.cboWardPropertiesChange(Sender: TObject);
begin
LoadInOut;
end;
procedure TframeInOutSearch.ClearControls;
begin
cboSort.ItemIndex := 0;
cboCondition.ItemIndex := 0;
txtSearch.Clear;
cboInOut.ItemIndex := 0;
dbMain.GetWardList(oConfig.User.HospitalID, cboWard.Properties.Items, True);
if cboWard.Properties.Items.Count > 0 then
begin
if FWardID > -1 then
cboWard.ItemIndex := cboWard.Properties.Items.IndexOf
(dbMain.GetWardName(oConfig.User.HospitalID, FWardID))
else
cboWard.ItemIndex := 0;
end;
dbMain.GetBohumList(cboBohum.Properties.Items, True);
if cboBohum.Properties.Items.Count > 0 then
cboBohum.ItemIndex := 0;
end;
procedure TframeInOutSearch.LoadInOut;
var
nHospitalID: integer;
sSearch: string;
begin
if not FLoaded then
Exit;
FLoaded := False;
nHospitalID := oConfig.User.HospitalID;
sSearch := trim(txtSearch.Text);
FInOut.DisableControls;
FInOut.Close;
FInOut.Parameters.ParamValues['@HospitalID'] := nHospitalID;
FInOut.Parameters.ParamValues['@CurDate'] := FDate;
FInOut.Parameters.ParamValues['@PPYearMonth'] := FPPYearMonth;
FInOut.Parameters.ParamValues['@SearchCondition'] := cboCondition.ItemIndex;
FInOut.Parameters.ParamValues['@SearchText'] := sSearch;
if cboWard.ItemIndex > 0 then
FInOut.Parameters.ParamValues['@WardID'] := dbMain.GetWardID
(nHospitalID, cboWard.Text)
else
FInOut.Parameters.ParamValues['@WardID'] := -1;
if cboInOut.ItemIndex > 0 then
FInOut.Parameters.ParamValues['@InOutState'] := cboInOut.ItemIndex - 1
else
FInOut.Parameters.ParamValues['@InOutState'] := -1;
if cboBohum.ItemIndex > 0 then
FInOut.Parameters.ParamValues['@BohumID'] := dbMain.GetBohumID
(cboBohum.Text)
else
FInOut.Parameters.ParamValues['@BohumID'] := -1;
FInOut.Parameters.ParamValues['@Order'] := cboSort.ItemIndex;
try
FInOut.Open;
except
oGlobal.Msg('입원정보에 접근할 수 없습니다!');
end;
FInOut.EnableControls;
FLoaded := True;
end;
procedure TframeInOutSearch.SetValue(oT: TADOStoredProc; nWardID: integer;
sDate, sPPYearMonth: string);
begin
FLoaded := False;
FInOut := oT;
FWardID := nWardID;
FDate := sDate;
FPPYearMonth := sPPYearMonth;
ClearControls;
FLoaded := True;
LoadInOut;
end;
procedure TframeInOutSearch.txtSearchKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
btnSearch.Click;
end;
end.
|
unit Casbin.Functions.IPMatch;
interface
/// <summary>
/// Determines whether an IP address ip1 matches the pattern of ip2
/// ip1 and ip2 can be an IP address or a CIDR pattern
/// eg. '192.168.2.123' matches '192.168.2.0/24'
/// </summary>
function IPMatch (const aArgs: array of string): Boolean; overload;
function IPMatch (const aIP1, aIP2: string; const aInvalidIPAsError: Boolean): Boolean; overload;
implementation
uses
System.SysUtils,
System.Types, System.StrUtils;
function IPMatch (const aArgs: array of string): Boolean;
begin
if Length(aArgs)<>2 then
raise Exception.Create('Wrong number of arguments in IPMatch');
Result := IPMatch(aArgs[0], aArgs[1], True);
end;
function IPMatch(const aIP1, aIP2: string; const aInvalidIPAsError: Boolean): Boolean;
var
ip1: string;
ip2: string;
IPArr1: TStringDynArray;
IPArr2: TStringDynArray;
function validIP(const aIP: string): Boolean; //PALOFF
var
strArr: TStringDynArray;
i: Integer;
numIP: integer;
begin
Result:=True;
strArr:=aIP.Split(['.']);
if Length(strArr) <> 4 then
Result:=false
else
begin
for i:=0 to Length(strArr)-1 do
begin
if not (TryStrToInt(strArr[i], numIP)
and (numIP>=0) and (numIP<=255)) then
begin
Result:=False;
Break;
end;
end;
end;
end;
begin
result:=false;
ip1 := aIP1.Trim;
ip2 := aIP2.Trim;
if ip1.IsEmpty or ip2.IsEmpty then
Exit;
if ip1.IndexOf('/') > -1 then
ip1:=ip1.Split(['/'])[0];
if ip2.IndexOf('/') > -1 then
ip2:=ip2.Split(['/'])[0];
if not validIP(ip1) then
begin
if aInvalidIPAsError then
raise Exception.Create('Invalid IP: '+ip1+' in IPMatch');
Exit(False);
end;
if not validIP(ip2) then
begin
if aInvalidIPAsError then
raise Exception.Create('Invalid IP: '+ip1+' in IPMatch');
Exit(False);
end;
if ip1.Equals(ip2) then
begin
result:=true;
exit;
end;
IPArr1:=ip1.Split(['.']);
IPArr2:=ip2.Split(['.']);
Result:= (IPArr1[0]=IPArr2[0]) and (IPArr1[1]=IPArr2[1])
and (IPArr1[2]=IPArr2[2]);
end;
end.
|
{
TShellCommandRunner: class to run external programs threaded to capture the output created.
Copyright (C) 2012 G.A. Nijland - lemjeu@gmail.com
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit ShellCommandRunner;
{$mode objfpc}{$H+}
interface
uses
StrUtils,
Classes, SysUtils, Process;
const
READ_BLOKCSIZE = 4096; // Default buffer size when reading process output data
type
{ Notify procedure when there is data available }
TNotifyOutputAvailable = procedure(const pBuffer: PByteArray; const pCount: integer) of object;
{ TShellCommandRunner }
TShellCommandRunner = class
private
FCommandline: string;
FBlockSize: longint;
FSize: longint;
FDirectory: string;
FExitStatus: integer;
FShowWindow: TShowWindowOptions;
FOnOutputAvailable: TNotifyOutputAvailable;
FProcess: TProcess;
// Signal that a termination was requested from outside
FTerminationRequested: boolean;
property Process: TProcess read FProcess write FProcess;
property TerminationRequested: boolean read FTerminationRequested write FTerminationRequested;
public
constructor Create; reintroduce;
function Execute(const pStream: TStream = nil; const pWaitForProcess: boolean = true): integer;
class function BufferToString(const pBuffer: PByteArray; const pCount: integer): string;
procedure Abort;
property Commandline: string read FCommandline write FCommandline;
property Directory: string read FDirectory write FDirectory;
property BlockSize: longint read FBlockSize write FBlockSize;
property Size: longint read FSize write FSize;
property ExitStatus: integer read FExitStatus;
property ShowWindow: TShowWindowOptions write FShowWindow;
property OnOutputAvailable: TNotifyOutputAvailable read FOnOutputAvailable write FOnOutputAvailable;
end;
{ TShellCommandRunnerThread }
TShellCommandRunnerThread = class(TThread)
private
FRunner: TShellCommandRunner;
FOnOutputAvailable: TNotifyOutputAvailable;
FBuffer: PByteArray;
FBufferCount: integer;
FLocalEcho: boolean;
procedure SetCommand(const AValue: string);
procedure SynchronizeOutput;
protected
procedure Execute; override;
procedure OnOutput(const pBuffer: PByteArray; const pCount: integer);
public
constructor Create;
procedure Abort;
procedure Write(const pInfo: string);
function ToString(const pBuffer: PByteArray; const pCount: integer): string; reintroduce;
property Runner: TShellCommandRunner read FRunner;
property OnOutputAvailable: TNotifyOutputAvailable read FOnOutputAvailable write FOnOutputAvailable;
property LocalEcho: boolean read FLocalEcho write FLocalEcho;
property CommandLine: string write SetCommand;
end;
implementation
{ TShellCommandRunner }
constructor TShellCommandRunner.Create;
begin
inherited Create;
BlockSize := READ_BLOKCSIZE;
FShowWindow := swoHide;
TerminationRequested := false;
end;
function TShellCommandRunner.Execute(const pStream: TStream; const pWaitForProcess: boolean): integer;
var nread : longint;
Buffer : PByteArray;
OutputStream: TStream;
// Local procedure to process bytes read; to prevent duplicated code.
// 'Global' variables are used i.e. the local variables of the Execute procedure above.
procedure ProcessNewData(const pNumBytes: longint);
begin
if pNumBytes > 0 then
begin
// Increase counter for total size of data read
Inc(FSize, pNumBytes);
// Write data to output stream
if assigned(OutputStream) then
OutputStream.Write(Buffer^, pNumBytes);
// Signal other processes that data is available
if assigned(FOnOutputAvailable) then
FOnOutputAvailable(Buffer, pNumBytes);
end;
end;
begin
// Init
Size := 0;
// Create process to handle the command
Process := TProcess.Create(nil);
Process.CommandLine := CommandLine;
Process.Options := [poUsePipes, poStderrToOutPut];
Process.ShowWindow := FShowWindow;
// If the directory is entered, use it, 'escaping' all backslashes for windows only.
if Directory <> '' then
Process.CurrentDirectory := AnsiReplaceStr(Directory,'\','\\');
// Buffer for data; use the given output size
Buffer := GetMem(BlockSize);
// Output stream; when provided use it.
if assigned(pStream) then
OutputStream := pStream
else
OutputStream := nil;
// Execute
Process.Execute;
// Grab the output when required
if not pWaitForProcess then
FExitStatus := 0
else
begin
// While the process is running, wait until it is finished or
// a terminatio was requested.
while Process.Running and (not TerminationRequested) do
begin
if Process.Output.NumBytesAvailable = 0 then
sleep(50) // No data avaible; wait some time
else
begin
// Get next available data from the process and process it
nread := Process.Output.Read(Buffer^, BlockSize);
ProcessNewData(nread);
end;
end; // while...
// If termination was requested, abort the process else process the remaining output.
if TerminationRequested then
Process.Terminate(-1)
else
begin
// Process ended by itself; grab the remainder of the output data
repeat
// Get remainder of the process data
nread := Process.Output.Read(Buffer^, BlockSize);
ProcessNewData(nread);
until nread = 0;
// Signal end of processing; no data to process anymore.
if assigned(FOnOutputAvailable) then
FOnOutputAvailable(Buffer,0);
end;
// Keep exit status to report back
FExitStatus := Process.ExitStatus;
end;
// Clean up
Freemem(Buffer);
FreeAndNil(FProcess);
// Return result of the process
result := ExitStatus
end;
class function TShellCommandRunner.BufferToString(const pBuffer: PByteArray; const pCount: integer): string;
var i: integer;
begin
setlength(result,pCount);
for i := 0 to pCount-1 do
result[i+1] := chr(pBuffer^[i]);
end;
procedure TShellCommandRunner.Abort;
begin
TerminationRequested := true;
end;
{ TShellCommandRunnerThread }
procedure TShellCommandRunnerThread.SynchronizeOutput;
begin
if assigned(FOnOutputAvailable) then
FOnOutputAvailable(FBuffer,FBufferCount);
end;
procedure TShellCommandRunnerThread.SetCommand(const AValue: string);
begin
FRunner.Commandline := AValue
end;
procedure TShellCommandRunnerThread.Execute;
begin
FRunner.Execute;
FRunner.Free;
end;
constructor TShellCommandRunnerThread.Create;
begin
FreeOnTerminate := true; // Default: free after end
inherited Create(true); // Create suspended so more parms can be set
FLocalEcho := true; // Give local echo of data that is written; default yes
// Create the runner class that executes the process in the thread
FRunner := TShellCommandRunner.Create;
FRunner.OnOutputAvailable := @OnOutput;
end;
procedure TShellCommandRunnerThread.Write(const pInfo: string);
begin
if pInfo <> '' then
begin
if FLocalEcho then
OnOutput(@pInfo[1], length(pInfo));
FRunner.Process.Input.Write(pInfo[1], length(pInfo));
end;
end;
function TShellCommandRunnerThread.ToString(const pBuffer: PByteArray; const pCount: integer): string;
begin
result := TShellCommandRunner.BufferToString(pBuffer,pCount);
end;
procedure TShellCommandRunnerThread.Abort;
begin
// Signal the running process to abort.
FRunner.Abort;
end;
procedure TShellCommandRunnerThread.OnOutput(const pBuffer: PByteArray; const pCount: integer);
begin
if assigned(FOnOutputAvailable) then
begin
FBuffer := pBuffer;
FBufferCount := pCount;
Synchronize(@SynchronizeOutput);
end;
end;
end.
|
unit uGnLog;
interface
uses
SysUtils, IOUtils, uGnGeneral;
type
TLog = class
class procedure Init;
class procedure Log(const AMsg: string); overload;
class procedure Log(const AMsg: string; AArgs: array of const); overload;
end;
implementation
const
cFileName = 'log.txt';
cLogEnabled = True;
{ TLog }
class procedure TLog.Log(const AMsg: string);
begin
if cLogEnabled then
TFile.AppendAllText(Gnr.ProgramUserDataPath + cFileName, AMsg + #13#10);
end;
class procedure TLog.Init;
begin
TFile.Delete(Gnr.ProgramUserDataPath + cFileName);
end;
class procedure TLog.Log(const AMsg: string; AArgs: array of const);
begin
Log(Format(AMsg, AArgs));
end;
end.
|
module string_blank;
define string_nblanks;
%include 'string2.ins.pas';
{
********************************************************************************
*
* Subroutine STRING_NBLANKS (N)
*
* Write N blanks to standard output. Nothing is done when N is 0 or less.
}
procedure string_nblanks ( {write N blanks to STDOUT}
in n: sys_int_machine_t); {number of blanks to write, nothing for <= 0}
val_param;
begin
if n <= 0 then return; {nothing to do ?}
write (' ':n); {write the blanks}
end;
|
{------------------------------------
功能说明:数据库操作接口
创建日期:2010/04/26
作者:wzw
版权:wzw
-------------------------------------}
unit DBIntf;
{$weakpackageunit on}
interface
uses Classes, DB, DBClient;
type
IDBConnection = interface
['{C2AF5DCA-985A-4915-B2CB-4F3FDD321BA5}']
function GetConnected: Boolean;
procedure SetConnected(const Value: Boolean);
property Connected: Boolean read GetConnected write SetConnected;
procedure ConnConfig;
function GetDBConnection: TObject;
end;
IDBAccess = interface
['{FC3B34E7-55E3-492E-B029-31646DC7522C}']
procedure BeginTrans;
procedure CommitTrans;
procedure RollbackTrans;
procedure QuerySQL(Cds: TClientDataSet; const SQLStr: String);
procedure ExecuteSQL(const SQLStr: String);
procedure ApplyUpdate(const TableName: String; Cds: TClientDataSet);
//function ExecProcedure(const ProName:String;Param:Array of Variant):Boolean;
end;
IDataRecord = interface
['{7738C1DF-DE2D-46A6-BA4C-AF1F69DBE856}']
procedure LoadFromDataSet(DataSet: TDataSet);
procedure SaveToDataSet(const KeyFields: String; DataSet: TDataSet; FieldsMapping: string = '');
procedure CloneFrom(DataRecord: IDataRecord);
function GetFieldValue(const FieldName: String): Variant;
procedure SetFieldValue(const FieldName: String; Value: Variant);
property FieldValues[const FieldName: string]: Variant read GetFieldValue write SetFieldValue;
function FieldValueAsString(const FieldName: String): String;
function FieldValueAsBoolean(const FieldName: String): Boolean;
function FieldValueAsCurrency(const FieldName: String): Currency;
function FieldValueAsDateTime(const FieldName: String): TDateTime;
function FieldValueAsFloat(const FieldName: String): Double;
function FieldValueAsInteger(const FieldName: String): Integer;
function GetFieldCount: Integer;
function GetFieldName(const Index: Integer): String;
end;
IListFiller = interface
['{ED67EA0E-3385-4EBA-8094-44E26B81077F}']
procedure FillList(DataSet: TDataSet; const FieldName: String; aList: TStrings); overload;
procedure FillList(const TableName, FieldName: string; aList: TStrings); overload;
procedure ClearList(aList: TStrings);
procedure DeleteListItem(const Index: Integer; aList: TStrings);
function GetDataRecord(const Index: Integer; aList: TStrings): IDataRecord;
end;
implementation
end.
|
{ Turbo Compressor ver 0.1 }
{ by Toupao Chieng }
{ Dec 31, 1990, 3:27pm }
program TCCompress(Input, Output);
(*
This is a simple file compression program written in Turbo Pascal 5.5.
The program does no more than compress and decompress files. But this
is good way of starting and learning how file compression is done in
Pascal (for beginning programmers who are interested in how a program
works, like me!).
Notes: *The program is kind of slow, but it works. It also can't store all
the files in a single archive like PKZIP or PKPAK.
*The compression is not so great either!...
*There is no display indicator, so don't assume your system is lock
if your compressing/decompressing big files.
Others: *Bug reports are also welcome to the author...
(Toupao Chieng, Clovis West High School Computer Club.)
Have fun...
*)
uses
Dos;
const
NumOfChars = 256;
NumOfSyms = NumOfChars + 1;
MaxFreq = 16383;
Adaptive: Boolean = True;
CodeValueBits = 16;
EOFSymbol = NumOfChars + 1;
BufSize = $A000;
HdrLen: Integer = 32;
FreqTable: array [0..NumOfSyms + 1] of Word =
(0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 124, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1236, 1, 21, 9, 3, 1, 25, 15, 2, 2,
2, 1, 79, 19, 60, 1, 15, 15, 8, 5, 4, 7, 5, 4, 4, 6, 3, 2, 1, 1, 1,
1, 1, 24, 15, 22, 12, 15, 10, 9, 16, 16, 8, 6, 12, 23, 13, 11, 14, 1,
14, 28, 29, 6, 3, 11, 1, 3, 1, 1, 1, 1, 1, 3, 1, 491, 85, 173, 232,
744, 127, 110, 293, 418, 6, 39, 250, 139, 429, 446, 111, 5, 388, 375,
531, 152, 57, 97, 12, 101, 5, 2, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1);
type
BufPtr = ^Buffer;
Buffer = array [1..BufSize] of Byte;
CodeValue = Longint;
FileRecPtr = ^FileRec;
FileRec = record
Name: String [14];
Next: FileRecPtr;
end;
var
CharToIndex: array [0..NumOfChars] of Integer;
IndexToChar: array [0..NumOfSyms + 1] of Integer;
CumFreq: array [0..NumOfSyms] of Integer;
OrigFileSize, ByteCnt: Real;
IFile, OFile: File;
EOFile, Decompression: Boolean;
InBufPtr, OutBufPtr: BufPtr;
Symbol, InBufCnt,InBufPos, OutBufPos: Word;
BitBuffer, BitsToGo: Byte;
Low, High: Codevalue;
BitsToFollow, FileIndex,
TopValue, FirstQrtr,
Half, ThirdQrtr: Longint;
FileListHead, FP: FileRecPtr;
Int, FileCount, HdrCnt: Integer;
Ch, GarbageBits, Bite: Byte;
Mode: Char;
OutFileName, Header: String;
Value: CodeValue;
procedure BuildList(FParam: String);
var
FP: FileRecPtr;
S: String;
SR: SearchRec;
begin
FindFirst(FParam, AnyFile, SR);
while DosError = 0 do begin
New(FP);
FP^.Name := SR.Name;
FP^.Next := FileListHead;
FileListHead := FP;
Inc(FileCount);
FindNext(SR);
end;
end; { BuildList }
procedure LoadFiles;
var
I: Integer;
begin
FileListHead := nil;
FileCount := 0;
for I := 1 to ParamCount do
BuildList(ParamStr(I));
if FileListHead = nil then begin
Writeln(^G'No matching files found.');
Halt;
end else begin
if Decompression then
Writeln(FileCount, ' file(s) to decompress.')
else
Writeln(FileCount,' file(s) to compress.');
end;
end; { LoadFiles }
function Exist(FileName: String): Boolean;
var
Inf: SearchRec;
begin
FindFirst(FileName, AnyFile, Inf);
Exist := (DosError = 0);
end; { Exist }
procedure StartModel;
var
I: Integer;
begin
for I := 0 to NumOfChars - 1 do begin
CharToIndex[I] := I + 1;
IndexToChar[I + 1] := I;
end;
if not Adaptive then begin
CumFreq[NumOfSyms] := 0;
for I := NumOfSyms downto 1 do
CumFreq[I - 1] := CumFreq[I] + FreqTable[I];
if CumFreq[0] > MaxFreq then begin
Writeln(^G'Cumulative frequency count too high.');
Halt;
end;
end else begin
for I := 0 to NumOfSyms do begin
FreqTable[I] := 1;
CumFreq[I] := NumOfSyms - I;
end;
FreqTable[0] := 0;
end;
end; { StartModel }
procedure UpdateModel(Symbol: Integer);
var
I: Integer;
C1, C2: Integer;
begin
if not Adaptive then begin
end else begin
if CumFreq[0] = MaxFreq then begin
C1 := 0;
for I := NumOfSyms downto 0 do begin
FreqTable[I] := (FreqTable[I] + 1) shr 1;
CumFreq[I] := C1;
C1 := C1 + FreqTable[I];
end;
end;
I := Symbol;
while FreqTable[I] = FreqTable[I - 1] do
Dec(I);
if I < symbol then begin
C1 := IndexToChar[I];
C2 := IndexToChar[Symbol];
IndexToChar[I] := C2;
IndexToChar[Symbol] := C1;
CharToIndex[C1] := Symbol;
CharToIndex[C2] := I;
end;
Inc(FreqTable[I]);
while I > 0 do begin
Dec(I);
Inc(CumFreq[I]);
end;
end;
end; { UpdateModel }
procedure Initialize;
var
I: Integer;
Temp: String;
begin
if ParamCount = 0 then begin
Writeln('COMPRESS version 0.1 (12/31/90) by Toupao Chieng C.W. H.S. C.C.');
Writeln('usage: COMPRESS [{-|/}option] [filename...]');
Writeln;
Writeln('option: /d = decompress file(s)');
Writeln;
Writeln('example:');
Writeln(' { file compression }');
Writeln(' COMPRESS myfile.pas bgidemo.pas tcalc.pas');
Writeln(' COMPRESS *.pas *.exe');
Writeln;
Writeln(' { file decompression }');
Writeln(' COMPRESS /d myfile.tcc bgidemo.tcc tcalc.tcc');
Writeln(' COMPRESS /d *.tcc');
Writeln;
Writeln('You may copy and distribute this program if you''d like...');
Writeln('See COMPRESS.PAS (source) for some notes on the program...');
Halt;
end else begin
Decompression := False;
for I := 1 to ParamCount do begin
Temp := ParamStr(I);
if Temp[1] in ['-','/'] then begin
if Not (UpCase(Temp[2]) in ['C','D']) then begin
if Not Exist(Temp) then begin
Writeln(^G'ERROR: Illegal option (',Temp[2],')');
Halt;
end;
end else begin
if UpCase(Temp[2]) = 'D' then
Decompression := True;
end;
end;
end;
end;
end; { Initialize }
procedure SetCompressor;
begin
TopValue := $FFFE;
FirstQrtr := (TopValue div 4) + 1;
Half := 2 * FirstQrtr;
ThirdQrtr := 3 * FirstQrtr;
Adaptive := True;
New(InBufPtr);
New(OutBufPtr);
EOFile := False;
StartModel;
end; { SetCompressor }
procedure SetDecompressor;
begin
TopValue := $FFFE;
FirstQrtr := (TopValue div 4) + 1;
Half := 2 * FirstQrtr;
ThirdQrtr := 3 * FirstQrtr;
New(InBufPtr);
New(OutBufPtr);
OutBufPos := 1;
EOFile := False;
StartModel;
end; { SetDecompressor }
procedure FillInputBuf;
begin
if Eof(IFile) then
EOFile := True
else begin
BlockRead(IFile, InBufPtr^, BufSize, InBufCnt);
end;
InBufPos := 1;
end; { FillInputBuf }
procedure WriteOutBuf;
begin
if OutBufPos > 1 then begin
BlockWrite(OFile, OutBufPtr^, OutBufPos - 1);
OutBufPos := 1;
end;
end; { WriteOutBuf }
procedure StoreByte(B: Byte);
begin
OutBufPtr^[OutBufPos] := B;
Inc(OutBufPos);
if OutBufPos > BufSize then WriteOutBuf;
end; { StoreByte }
function GetByte: Byte;
begin
if not EOFile then begin
GetByte := InBufPtr^[InBufPos];
if InBufPos = InBufCnt then
FillInputBuf
else
Inc(InBufPos);
end;
end; { GetByte }
procedure StartOutputingBits;
begin
BitBuffer := 0;
BitsToGo := 8;
ByteCnt := 0;
end; { StartOutputingBits }
procedure OutputBit(B: Byte);
begin
BitBuffer := BitBuffer shr 1;
if B = 0 then
BitBuffer := BitBuffer and $7F
else
BitBuffer := BitBuffer or $80;
Dec(BitsToGo);
if BitsToGo = 0 then begin
StoreByte(BitBuffer);
BitsToGo := 8;
ByteCnt := ByteCnt + 1;
end;
end; { OutputBit }
procedure StartEncoding;
begin
Low := 0;
High := TopValue;
BitsToFollow := 0;
OrigFileSize := 0;
end; { StartEncoding }
function InputBit: Word;
var
T: Word;
begin
if BitsToGo = 0 then begin
BitBuffer := GetByte;
if EOFile then begin
Inc(GarbageBits);
if GarbageBits > CodeValueBits - 2 then begin
Writeln(^G'Bad input file.');
Halt;
end;
end;
BitsToGo := 8;
end;
T := BitBuffer and $01;
BitBuffer := BitBuffer shr 1;
Dec(BitsToGo);
InputBit := T;
end; { InputBit }
procedure StartDecoding;
var
I: Byte;
begin
I := GetByte;
Mode := Chr(I);
if UpCase(Mode) = 'A' then
Adaptive := True
else
Adaptive := False;
Value := 0;
for I := 0 to CodeValueBits - 1 do begin
Value := 2 * Value + InputBit;
end;
Low := 0;
High := TopValue;
end; { StartDecoding }
procedure BitPlusFollow(B: Byte);
begin
OutputBit(B);
while BitsToFollow > 0 do begin
if B = 1 then
OutPutBit(0)
else
OutputBit(1);
Dec(BitsToFollow);
end;
end; { BitPlusFollow }
procedure EncodeSymbol(Sym: Word);
var
Range: Longint;
begin
Range := Longint((High - Low) + 1);
High := Low + (Range * CumFreq[Sym - 1]) div CumFreq[0] - 1;
Low := Low + (Range * CumFreq[Sym]) div CumFreq[0];
repeat
if High < Half then begin
BitPlusFollow(0);
end else if Low >= Half then begin
BitPlusFollow(1);
Low := Low - Half;
High := High - Half;
end else if (Low >= FirstQrtr) and (High < ThirdQrtr) then begin
Inc(BitsToFollow);
Low := Low - FirstQrtr;
High := High - FirstQrtr;
end else Exit;
Low := 2 * Low;
High := 2 * High + 1;
until 0 <> 0;
end; { EncodeSymbol }
procedure DoneEncoding;
begin
Inc(BitsToFollow);
if (Low < FIrstQrtr) then
BitPlusFollow(0)
else
BitPlusFollow(1);
end; { DoneEncodeing }
procedure DoneOutputingBits;
begin
BitBuffer := BitBuffer shr BitsToGo;
StoreByte(BitBuffer);
ByteCnt := ByteCnt + 1;
end; { DoneOutputingBits }
procedure Compress(F: String);
const
HdrLen = 32;
Blanks = ' ';
var
OName: String;
FSize: String;
Header: String;
I: Byte;
begin
Assign(IFile, F);
Reset(IFile, 1);
if Pos('.', F) > 0 then
OName := Copy(F, 1, Pos('.', F)) + 'TCC'
else
OName := F + '.TCC';
Assign(OFile, OName);
Rewrite(OFile, 1);
FillInputBuf;
OutBufPos := 1;
StoreByte(Ord('A'));
Write('Compressing: ', F);
StartOutPutingBits;
StartEncoding;
Str(FileSize(IFile), FSize);
Header := F + '|' + FSize;
Header := Header + Copy(Blanks, 1, HdrLen - Length(Header));
for I := 1 to Length(Header) do begin
Symbol := CharToIndex[Ord(Header[I])];
EncodeSymbol(Symbol);
UpdateModel(Symbol);
end;
repeat
Bite := GetByte;
OrigFileSize := OrigFileSize + 1;
if not EOFile then begin
Symbol := CharToIndex[Bite];
EncodeSymbol(Symbol);
UpdateModel(Symbol);
end;
until EOFile;
EncodeSymbol(EOFSymbol);
DoneEncoding;
DoneOutputingBits;
WriteOutBuf;
Close(IFile);
Close(OFile);
Writeln(' (', ((ByteCnt / OrigFileSize) * 100): 4: 2, '%) done.');
end; { Compress }
function DecodeSymbol: Word;
var
Range: Longint;
Cum: Word;
Sym: Word;
Done: Boolean;
begin
Range := Longint((High - Low) + 1);
Cum := (((Value - Low) + 1) * CumFreq[0] - 1) div Range;
Sym := 1;
Done := False;
while CumFreq[Sym] > Cum do
Inc(Sym);
High := Low + (Range * CumFreq[Sym - 1]) div CumFreq[0] - 1;
Low := Low + (Range * CumFreq[Sym]) div CumFreq[0];
repeat
if High < Half then
else if (Low >= Half) then begin
Value := Value - Half;
Low := Low - Half;
High := High - Half;
end else if (Low >= FirstQrtr) and (High < ThirdQrtr) then begin
Value := Value - FirstQrtr;
Low := Low - FirstQrtr;
High := High - FirstQrtr;
end else
Done := True;
if not Done then begin
Low := 2 * Low;
High := 2 * High + 1;
Value := 2 * Value + InputBit;
end;
until Done;
DecodeSymbol := Sym;
end; { DecodeSymbol }
procedure Decompress(F: String);
begin
Assign(IFile, F);
Reset(IFile, 1);
FillInputBuf;
HdrCnt := 1;
BitsToGo := 0;
GarbageBits := 0;
ByteCnt := 0;
StartDecoding;
repeat
Symbol := DecodeSymbol;
if Symbol <> EOFSymbol then begin
Ch := IndexToChar[Symbol];
if HdrCnt < HdrLen then begin
Header[HdrCnt] := Chr(Ch);
Inc(HdrCnt);
end else if HdrCnt = HdrLen then begin
Header[0] := Chr(HdrLen);
OutFileName := Copy(Header, 1, Pos('|', Header) - 1);
Assign(OFile, OutFileName);
Rewrite(OFile, 1);
Writeln('Decompressing: ', OutFileName);
Inc(HdrCnt);
end else
StoreByte(Ch);
UpdateModel(Symbol);
end;
until EOFile;
WriteOutBuf;
Close(OFile);
Close(IFile);
end; { Decompress }
begin { main program }
Initialize;
Writeln('COMPRESS version 0.1 (12/31/90) by Toupao Chieng');
if Not Decompression then begin
LoadFiles;
FP := FileListHead;
repeat
SetCompressor;
Compress(FP^.Name);
FP := FP^.Next;
until FP = nil;
end else begin
LoadFiles;
FP := FileListHead;
repeat
SetDecompressor;
Decompress(FP^.Name);
FP := FP^.Next;
until FP = nil;
end;
end. { TCCompress } |
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LazUtf8, Forms, Controls, Graphics, Dialogs, Menus,
StdCtrls, ExtCtrls, BCButton, SynHighlighterCss, SynEdit,
SynHighlighterJScript, SynHighlighterHTML;
type
{ TForm1 }
TForm1 = class(TForm)
Label_JS: TLabel;
Label_CSS: TLabel;
Label_HTML: TLabel;
MenuItem1: TMenuItem;
Spec_JS_1: TMenuItem;
Menu_JS: TMenuItem;
Save1_JS: TBCButton;
Save1_CSS: TBCButton;
Save1_HTML: TBCButton;
Formatt_CSS: TBCButton;
Formatt_JS: TBCButton;
Open_CSS: TBCButton;
Open_JS: TBCButton;
Save_HTML: TBCButton;
Open_HTML: TBCButton;
Formatt_HTML: TBCButton;
ch_ClearAll: TMenuItem;
ch_utf16_t: TMenuItem;
ch_Text_utf16: TMenuItem;
Panel3: TPanel;
Save_CSS: TBCButton;
Save_JS: TBCButton;
sl_Ukraine: TMenuItem;
select_Lang: TMenuItem;
Splitter1: TSplitter;
Splitter2: TSplitter;
Syn_HTML: TSynEdit;
Syn_JS: TSynEdit;
MainMenu1: TMainMenu;
Menu_Change: TMenuItem;
Menu_Appearance: TMenuItem;
Menu_About: TMenuItem;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
Panel2: TPanel;
SaveDialog1: TSaveDialog;
SynCssSyn1: TSynCssSyn;
Syn_CSS: TSynEdit;
SynHTMLSyn1: TSynHTMLSyn;
SynJScriptSyn1: TSynJScriptSyn;
procedure ch_ClearAllClick(Sender: TObject);
procedure ch_Text_utf16Click(Sender: TObject);
procedure Formatt_CSSClick(Sender: TObject);
procedure Formatt_HTMLClick(Sender: TObject);
procedure Formatt_JSClick(Sender: TObject);
procedure F_CSS1();
procedure F_CSS2();
procedure F_CSS3();
procedure F_CSS4();
procedure F_CSS5();
procedure F_XML1();
procedure F_XML2();
procedure F_XML3();
procedure F_XML4();
procedure F_XML5();
procedure F_JS1();
procedure F_JS2();
procedure F_JS3();
procedure F_JS4();
procedure F_JS5();
procedure Menu_AboutClick(Sender: TObject);
procedure Open_CSSClick(Sender: TObject);
procedure Open_HTMLClick(Sender: TObject);
procedure Open_JSClick(Sender: TObject);
procedure Save1_CSSClick(Sender: TObject);
procedure Save1_HTMLClick(Sender: TObject);
procedure Save1_JSClick(Sender: TObject);
procedure Save_CSSClick(Sender: TObject);
procedure Save_HTMLClick(Sender: TObject);
procedure Save_JSClick(Sender: TObject);
procedure sl_UkraineClick(Sender: TObject);
procedure ch_utf16_tClick(Sender: TObject);
private
public
end;
type Tutf16conv=record
case byte of
0:(C:UnicodeChar);
1:(W:word);
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
var
file_name_css, file_name_html, file_name_js,
s1,s2,s3, ts, name_syn, name_format : String;
lang_Ukr:boolean;
procedure TForm1.ch_ClearAllClick(Sender: TObject);
begin
Syn_CSS.Clear;
Syn_HTML.Clear;
Syn_JS.Clear;
if lang_Ukr=true then begin name_format:=' Поля очищені'; end else
begin name_format:=' Cleared'; end;
end;
procedure TForm1.ch_Text_utf16Click(Sender: TObject);
var T:Tutf16conv; i1, l_m : integer; mem0_copy : string;
begin
mem0_copy:='';
l_m:=0;
while (l_m<=(Length(Syn_HTML.Text))) do begin
s1 :=Syn_HTML.Text[l_m]; //!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
inc(l_m);
for i1:=33 to 126 do begin
T.w:=i1;
if (UTF16ToUTF8(T.c))=s1 then
mem0_copy:=mem0_copy+'\u00'+IntToHex(i1,2);
end;
end;
Syn_HTML.Text:=mem0_copy;
end;
procedure TForm1.Formatt_CSSClick(Sender: TObject);
begin
F_CSS1(); F_CSS2(); F_CSS3(); F_CSS4(); F_CSS5();
end;
procedure TForm1.Formatt_HTMLClick(Sender: TObject);
begin
F_XML1(); F_XML2(); F_XML3();
end;
procedure TForm1.Formatt_JSClick(Sender: TObject);
begin
F_JS1(); F_JS2(); F_JS3(); F_JS4(); F_JS5();
end;
procedure TForm1.F_XML1();
begin
s1 := Syn_HTML.Text;
s2 := '><';
s3 := '>'+#10+#$9+'<';
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_HTML.Text:=ts;
end;
procedure TForm1.F_XML2();
begin
s1 := Syn_HTML.Text;
s2 := '" ';
s3 := '"'+#10+#$9;
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_HTML.Text:=ts;
end;
procedure TForm1.F_XML3();
begin
s1 := Syn_HTML.Text;
s2 := '<div';
s3 := #10+#$9+#$9+'<div';
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_HTML.Text:=ts;
end;
procedure TForm1.F_XML4();
begin
end;
procedure TForm1.F_XML5();
begin
end;
procedure TForm1.F_JS1();
begin
s1 := Syn_JS.Text;
s2 := '{"';
s3 := '{ "';
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_JS.Text:=ts;
end;
procedure TForm1.F_JS2();
begin
s1 := Syn_JS.Text;
s2 := ';';
s3 := ';'+#10+#$9;
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_JS.Text:=ts;
end;
procedure TForm1.F_JS3();
begin
s1 := Syn_JS.Text;
s2 := '}';
s3 := '}'+' ';
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_JS.Text:=ts;
end;
procedure TForm1.F_JS4();
begin
s1 := Syn_JS.Text;
s2 := ',';
s3 := ','+' ';
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_JS.Text:=ts;
end;
procedure TForm1.F_JS5();
begin
end;
procedure TForm1.Menu_AboutClick(Sender: TObject);
begin
if lang_Ukr=true then begin ShowMessage('Створив Володимир Недоляк https://github.com/VovcheKuss'); end else begin
ShowMessage('Autor Volodymyr Nedoljak https://github.com/VovcheKuss'); end;
end;
procedure TForm1.F_CSS1();
begin
s1 := Syn_CSS.Text;
s2 := ';';
s3 := ';'+#10+#$9;
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_CSS.Text:=ts;
end;
procedure TForm1.F_CSS2();
begin
s1 := Syn_CSS.Text;
s2 := '{';
s3 := {#10+}'{'+#10+#$9;
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_CSS.Text:=ts;
end;
procedure TForm1.F_CSS3();
begin
s1 := Syn_CSS.Text;
s2 := '}';
s3 := #10+'}'+#10+#10+#$9;
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_CSS.Text:=ts;
end;
procedure TForm1.F_CSS4();
begin
s1 := Syn_CSS.Text;
s2 := '*/';
s3 := '*/'+#10;
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_CSS.Text:=ts;
end;
procedure TForm1.F_CSS5();
begin
s1 := Syn_CSS.Text;
s2 := '/*';
s3 := #10+'/*';
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_CSS.Text:=ts;
end;
procedure TForm1.Open_CSSClick(Sender: TObject); //-------- IMPORT CSS CODE
begin
if OpenDialog1.Execute then begin
Syn_CSS.Lines.LoadFromFile(OpenDialog1.FileName);
file_name_css:= OpenDialog1.Filename;
Label_CSS.Caption:=ExtractFileName(file_name_css);
end;
end;
procedure TForm1.Open_HTMLClick(Sender: TObject); //---- IMPORT HTML CODE
begin
if OpenDialog1.Execute then begin
Syn_HTML.Lines.LoadFromFile(OpenDialog1.FileName);
file_name_html:= OpenDialog1.Filename;
Label_HTML.Caption:=ExtractFileName(file_name_html);
end;
end;
procedure TForm1.Open_JSClick(Sender: TObject); //--------- IMPORT JS CODE
begin
if OpenDialog1.Execute then begin
Syn_JS.Lines.LoadFromFile(OpenDialog1.FileName);
file_name_js:= OpenDialog1.Filename;
Label_JS.Caption:=ExtractFileName(file_name_js);
end;
end;
procedure TForm1.Save1_CSSClick(Sender: TObject);
begin
Syn_CSS.Lines.SaveToFile(file_name_css);
end;
procedure TForm1.Save1_HTMLClick(Sender: TObject);
begin
Syn_HTML.Lines.SaveToFile(file_name_html);
end;
procedure TForm1.Save1_JSClick(Sender: TObject);
begin
Syn_JS.Lines.SaveToFile(file_name_js);
end;
procedure TForm1.Save_CSSClick(Sender: TObject); //--------- EXXXPORT CSS CODE
begin
if SaveDialog1.Execute then begin
SaveDialog1.FileName:=file_name_css;
Syn_CSS.Lines.SaveToFile(SaveDialog1.FileName);
end;
end;
procedure TForm1.Save_HTMLClick(Sender: TObject); //-------- EXXXPORT HTML CODE
begin
if SaveDialog1.Execute then begin
SaveDialog1.FileName:=file_name_html;
Syn_HTML.Lines.SaveToFile(SaveDialog1.FileName);
end;
end;
procedure TForm1.Save_JSClick(Sender: TObject); //--------- EXXXPORT JS CODE
begin
if SaveDialog1.Execute then begin
SaveDialog1.FileName:=file_name_js;
Syn_JS.Lines.SaveToFile(SaveDialog1.FileName);
end;
end;
procedure TForm1.sl_UkraineClick(Sender: TObject);
begin
lang_Ukr:=true;
ch_ClearAll.Caption:='Очистити всі поля';
sl_Ukraine.Caption:='Українська';
select_Lang.Caption:='Вибрати мову';
ch_utf16_t.Caption:='номер UTF16 у символ UTF16';
Menu_Change.Caption:='Зміни';
Menu_Appearance.Caption:='Вигляд';
Menu_About.Caption:='Про';
end;
procedure TForm1.ch_utf16_tClick(Sender: TObject);
var s16 :string;
T:Tutf16conv;
i1 : integer;
begin
// \u000a
i1:=0;
for i1:=0 to 65535 do begin
s1 := Syn_HTML.Text;
s2 := '\u'+IntToHex(i1,4);
T.w:=i1;
s16:=UTF16ToUTF8(T.c);
s3:= s16;
ts := StringReplace(s1, s2, s3, [RFReplaceAll, rfIgnoreCase]);
Syn_HTML.Text:=ts;
end;
end;
end.
|
unit newStatusBar;
{$mode objfpc}{$H+}
interface
uses
jwawindows, windows, Classes, SysUtils, Controls, StdCtrls,ComCtrls, LCLType, lmessages;
type
TNewStatusPanel=class(TStatusPanel)
public
constructor Create(ACollection: TCollection); override;
end;
TNewStatusBar=class(TStatusBar)
private
protected
procedure CreateHandle; override;
function GetPanelClass: TStatusPanelClass; override;
procedure DrawPanel(Panel: TStatusPanel; const Rect: TRect); override;
public
constructor Create(TheOwner: TComponent); override;
end;
implementation
uses betterControls, Graphics;
constructor TNewStatusPanel.Create(ACollection: TCollection);
begin
inherited create(ACollection);
style:=psOwnerDraw;
end;
function TNewStatusBar.GetPanelClass: TStatusPanelClass;
begin
if ShouldAppsUseDarkMode() then
result:=TNewStatusPanel
else
result:=TStatusPanel;
end;
procedure TNewStatusBar.DrawPanel(Panel: TStatusPanel; const Rect: TRect);
var ts: TTextStyle;
begin
if ShouldAppsUseDarkMode then
begin
if Assigned(OnDrawPanel) then
OnDrawPanel(self, panel, rect)
else
begin
ts.Alignment:=taLeftJustify;
ts.Layout:=tlCenter;
canvas.font.color:=font.color;
canvas.brush.style:=bsClear;
canvas.fillrect(rect);
canvas.TextRect(rect,rect.left,0,panel.Text,ts);
end;
end
else
inherited DrawPanel(panel, rect);
end;
procedure TNewStatusBar.CreateHandle;
var r: ptruint;
begin
inherited CreateHandle;
if ShouldAppsUseDarkMode() then
SetWindowTheme(Handle, '', '');
end;
constructor TNewStatusBar.Create(TheOwner: TComponent);
begin
inherited create(theowner);
if ShouldAppsUseDarkMode() then
SizeGrip:=false;
end;
end.
|
{
Counts how much baseforms are used in references
}
unit UserScript;
var
slForms: TStringList;
i: integer;
function Initialize: integer;
begin
slForms := TStringList.Create;
end;
function Process(e: IInterface): integer;
var
s: string;
begin
Result := 0;
s := Signature(e);
if (s <> 'REFR') and (s <> 'ACHR') and (s <> 'PHZD') and (s <> 'PGRD') then
Exit;
s := GetElementEditValues(e, 'NAME');
if s = '' then Exit;
i := slForms.IndexOf(s);
if i = -1 then
slForms.AddObject(s, 1)
else
slForms.Objects[i] := Integer(slForms.Objects[i]) + 1;
end;
function Finalize: integer;
begin
slForms.Sort;
for i := 0 to slForms.Count - 1 do
AddMessage(slForms[i] + ' ' + IntToStr(slForms.Objects[i]));
slForms.Free;
end;
end.
|
// Copyright 2014 Asbjørn Heid
//
// 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 AsyncIO;
interface
uses
WinAPI.Windows,
System.SysUtils,
System.Classes,
AsyncIO.OpResults;
type
CompletionHandler = reference to procedure;
OpHandler = reference to procedure(const Res: OpResult);
IOHandler = reference to procedure(const Res: OpResult; const BytesTransferred: UInt64);
type
EIOServiceStopped = class(Exception);
IOService = interface
{$REGION 'Property accessors'}
function GetStopped: boolean;
{$ENDREGION}
function Poll: Int64;
function PollOne: Int64;
function Run: Int64;
function RunOne: Int64;
procedure Post(const Handler: CompletionHandler);
procedure Stop;
property Stopped: boolean read GetStopped;
end;
function NewIOService(const MaxConcurrentThreads: Cardinal = 0): IOService;
type
MemoryBuffer = record
strict private
FData: pointer;
FSize: cardinal;
private
procedure SetSize(const MaxSize: cardinal);
class function Create(const Data: pointer; const Size: cardinal): MemoryBuffer; inline; static;
public
class operator Implicit(const a: TBytes): MemoryBuffer;
property Data: pointer read FData;
property Size: cardinal read FSize;
end;
StreamBuffer = record
{$REGION 'Implementation details'}
public
type
IStreamBuffer = interface
{$REGION 'Property accessors'}
function GetData: pointer;
function GetBufferSize: UInt64;
function GetMaxBufferSize: UInt64;
function GetStream: TStream;
{$ENDREGION}
function PrepareCommit(const Size: UInt32): MemoryBuffer;
procedure Commit(const Size: UInt32);
function PrepareConsume(const Size: UInt32): MemoryBuffer;
procedure Consume(const Size: UInt32);
property Data: pointer read GetData;
property BufferSize: UInt64 read GetBufferSize;
property MaxBufferSize: UInt64 read GetMaxBufferSize;
property Stream: TStream read GetStream; // for TStream access to buffered data
end;
{$ENDREGION}
strict private
FImpl: IStreamBuffer;
function GetData: pointer;
function GetBufferSize: UInt64;
function GetMaxBufferSize: UInt64;
function GetStream: TStream;
private
property Impl: IStreamBuffer read FImpl;
public
type
StreamBufferParam = (StreamBufferOwnsStream);
StreamBufferParams = set of StreamBufferParam;
public
class operator Implicit(const Impl: IStreamBuffer): StreamBuffer;
class function Create(const MaxBufferSize: UInt64 = MaxInt): StreamBuffer; static;
// writing to buffer
function PrepareCommit(const Size: UInt32): MemoryBuffer;
procedure Commit(const Size: UInt32);
// reading from buffer
function PrepareConsume(const Size: UInt32): MemoryBuffer;
procedure Consume(const Size: UInt32);
property Data: pointer read GetData;
property BufferSize: UInt64 read GetBufferSize;
property MaxBufferSize: UInt64 read GetMaxBufferSize;
property Stream: TStream read GetStream; // for TStream access to buffered data
end;
AsyncStream = interface
['{B134C820-D282-4D7E-B1CB-53C16FCAE7C8}']
{$REGION 'Property accessors'}
function GetService: IOService;
{$ENDREGION}
procedure AsyncReadSome(const Buffer: MemoryBuffer; const Handler: IOHandler);
procedure AsyncWriteSome(const Buffer: MemoryBuffer; const Handler: IOHandler);
property Service: IOService read GetService;
end;
AsyncMemoryStream = interface(AsyncStream)
['{7B9C1872-4983-4564-B5A9-101943910AE0}']
{$REGION 'Property accessors'}
function GetData: TBytes;
{$ENDREGION}
property Data: TBytes read GetData;
end;
AsyncHandleStream = interface(AsyncStream)
['{BBA2A04F-C0D5-4834-81AC-87D6AAB627AB}']
{$REGION 'Property accessors'}
function GetHandle: THandle;
{$ENDREGION}
property Handle: THandle read GetHandle;
end;
AsyncFileStream = interface(AsyncHandleStream)
['{011E1F49-4CF9-48FB-BEE5-4DF21E1EF1BB}']
{$REGION 'Property accessors'}
function GetFilename: string;
{$ENDREGION}
property Filename: string read GetFilename;
end;
// returns 0 if io operation is complete, otherwise the maximum number of bytes for the subsequent request
IOCompletionCondition = reference to function(const Res: OpResult; const BytesTransferred: UInt64): UInt64;
function MakeBuffer(const Buffer: MemoryBuffer; const MaxSize: cardinal): MemoryBuffer; overload;
function MakeBuffer(const Data: pointer; const Size: cardinal): MemoryBuffer; overload;
function NewAsyncMemoryStream(const Service: IOService; const Data: TBytes): AsyncMemoryStream; overload;
function NewAsyncMemoryStream(const Service: IOService): AsyncMemoryStream; overload;
var
MaxTransferSize: UInt64 = 65536; // default
function TransferAll: IOCompletionCondition;
function TransferAtLeast(const Minimum: UInt64): IOCompletionCondition;
function TransferExactly(const Size: UInt64): IOCompletionCondition;
procedure AsyncRead(const Stream: AsyncStream; const Buffer: MemoryBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler); overload;
procedure AsyncRead(const Stream: AsyncStream; const Buffer: StreamBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler); overload;
procedure AsyncReadUntil(const Stream: AsyncStream; const Buffer: StreamBuffer; const Delim: array of Byte; const Handler: IOHandler); overload;
procedure AsyncReadUntil(const Stream: AsyncStream; const Buffer: StreamBuffer; const Delim: TArray<Byte>; const Handler: IOHandler); overload;
procedure AsyncWrite(const Stream: AsyncStream; const Buffer: MemoryBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler); overload;
procedure AsyncWrite(const Stream: AsyncStream; const Buffer: StreamBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler); overload;
implementation
uses
System.Math, AsyncIO.Detail, AsyncIO.Detail.StreamBufferImpl;
{$POINTERMATH ON}
function NewIOService(const MaxConcurrentThreads: Cardinal = 0): IOService;
begin
result := IOServiceImpl.Create(MaxConcurrentThreads);
end;
function MakeBuffer(const Buffer: MemoryBuffer; const MaxSize: cardinal): MemoryBuffer;
begin
result := Buffer;
result.SetSize(MaxSize);
end;
function MakeBuffer(const Data: pointer; const Size: cardinal): MemoryBuffer; overload;
begin
result := MemoryBuffer.Create(Data, Size);
end;
function NewAsyncMemoryStream(const Service: IOService; const Data: TBytes): AsyncMemoryStream;
begin
result := AsyncMemoryStreamImpl.Create(Service, Data);
end;
function NewAsyncMemoryStream(const Service: IOService): AsyncMemoryStream;
begin
result := NewAsyncMemoryStream(Service, nil);
end;
function TransferAll: IOCompletionCondition;
begin
result :=
function(const Res: OpResult; const BytesTransferred: UInt64): UInt64
begin
result := IfThen(Res.Success, MaxTransferSize, 0);
end;
end;
function TransferAtLeast(const Minimum: UInt64): IOCompletionCondition;
begin
result :=
function(const Res: OpResult; const BytesTransferred: UInt64): UInt64
begin
result := IfThen(Res.Success and (BytesTransferred < Minimum), MaxTransferSize, 0);
end;
end;
function TransferExactly(const Size: UInt64): IOCompletionCondition;
begin
result :=
function(const Res: OpResult; const BytesTransferred: UInt64): UInt64
begin
result := IfThen(Res.Success and (BytesTransferred < Size), Min(Size - BytesTransferred, MaxTransferSize), 0);
end;
end;
type
AsyncReadOp = class(TInterfacedObject, IOHandler)
strict private
FTotalBytesTransferred: UInt64;
FStream: AsyncStream;
FBuffer: MemoryBuffer;
FCompletionCondition: IOCompletionCondition;
FHandler: IOHandler;
procedure Invoke(const Res: OpResult; const BytesTransferred: UInt64);
public
constructor Create(const Stream: AsyncStream; const Buffer: MemoryBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler);
end;
{ AsyncReadOp }
constructor AsyncReadOp.Create(const Stream: AsyncStream;
const Buffer: MemoryBuffer; const CompletionCondition: IOCompletionCondition;
const Handler: IOHandler);
begin
inherited Create;
FTotalBytesTransferred := 0;
FStream := Stream;
FBuffer := Buffer;
FCompletionCondition := CompletionCondition;
FHandler := Handler;
end;
procedure AsyncReadOp.Invoke(const Res: OpResult;
const BytesTransferred: UInt64);
var
n: UInt64;
readMore: boolean;
begin
FTotalBytesTransferred := FTotalBytesTransferred + BytesTransferred;
readMore := True;
if (Res.Success and (BytesTransferred = 0)) then
readMore := False;
n := FCompletionCondition(Res, FTotalBytesTransferred);
if (n = 0) or (FTotalBytesTransferred = FBuffer.Size) then
readMore := False;
if (readMore) then
begin
FStream.AsyncReadSome(MakeBuffer(FBuffer, n), Self);
end
else
begin
FHandler(Res, FTotalBytesTransferred);
end;
end;
procedure AsyncRead(const Stream: AsyncStream; const Buffer: MemoryBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler);
var
n: UInt64;
readOp: IOHandler;
begin
n := CompletionCondition(GenericResults.Success, 0);
if (n = 0) then
begin
Stream.Service.Post(
procedure
begin
Handler(GenericResults.Success, 0);
end
);
exit;
end;
readOp := AsyncReadOp.Create(Stream, Buffer, CompletionCondition, Handler);
Stream.AsyncReadSome(MakeBuffer(Buffer, n), readOp);
end;
type
AsyncReadStreamAdapterOp = class(TInterfacedObject, IOHandler)
strict private
FTotalBytesTransferred: UInt64;
FStream: AsyncStream;
FBuffer: StreamBuffer;
FCompletionCondition: IOCompletionCondition;
FHandler: IOHandler;
procedure Invoke(const Res: OpResult; const BytesTransferred: UInt64);
public
constructor Create(const Stream: AsyncStream; const Buffer: StreamBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler);
end;
{ AsyncReadStreamAdapterOp }
constructor AsyncReadStreamAdapterOp.Create(const Stream: AsyncStream;
const Buffer: StreamBuffer; const CompletionCondition: IOCompletionCondition;
const Handler: IOHandler);
begin
inherited Create;
FTotalBytesTransferred := 0;
FStream := Stream;
FBuffer := Buffer;
FCompletionCondition := CompletionCondition;
FHandler := Handler;
end;
procedure AsyncReadStreamAdapterOp.Invoke(const Res: OpResult;
const BytesTransferred: UInt64);
var
n: UInt64;
readMore: boolean;
buf: MemoryBuffer;
begin
FTotalBytesTransferred := FTotalBytesTransferred + BytesTransferred;
FBuffer.Commit(BytesTransferred);
readMore := True;
if (Res.Success and (BytesTransferred = 0)) then
readMore := False;
n := FCompletionCondition(Res, FTotalBytesTransferred);
n := Min(n, FBuffer.MaxBufferSize - FBuffer.BufferSize);
if (n = 0) then
readMore := False;
if (readMore) then
begin
buf := FBuffer.PrepareCommit(n);
FStream.AsyncReadSome(buf, Self);
end
else
begin
FHandler(Res, FTotalBytesTransferred);
end;
end;
procedure AsyncRead(const Stream: AsyncStream; const Buffer: StreamBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler);
var
n: UInt64;
readOp: IOHandler;
buf: MemoryBuffer;
begin
n := CompletionCondition(GenericResults.Success, 0);
n := Min(n, Buffer.MaxBufferSize);
if (n = 0) then
begin
Stream.Service.Post(
procedure
begin
Handler(GenericResults.Success, 0);
end
);
exit;
end;
readOp := AsyncReadStreamAdapterOp.Create(Stream, Buffer, CompletionCondition, Handler);
buf := Buffer.PrepareCommit(n);
Stream.AsyncReadSome(buf, readOp);
end;
type
AsyncReadUntilDelimOp = class(TInterfacedObject, IOHandler)
strict private
FTotalBytesTransferred: UInt64;
FStream: AsyncStream;
FBuffer: StreamBuffer;
FSearchPosition: UInt64;
FDelim: TBytes;
FHandler: IOHandler;
procedure Invoke(const Res: OpResult; const BytesTransferred: UInt64);
public
constructor Create(const Stream: AsyncStream; const Buffer: StreamBuffer; const Delim: TArray<Byte>; const Handler: IOHandler);
end;
function ReadSizeHelper(const Buffer: StreamBuffer; const MaxSize: UInt64): cardinal;
begin
result := Min(512,
Max(MaxSize, Buffer.BufferSize));
end;
// returns true if a complete match has been found, start of match in MatchPosition
// returns false with MatchPosition >= 0 indicating the start of the partial match
// returns false with MatchPosition < 0 if no match was found
function PartialSearch(const Data: pointer; const DataLength: NativeInt; const Delim: TArray<Byte>; out MatchPosition: NativeInt): boolean;
var
d, dataEnd: PByte;
delimLength: NativeInt;
i: integer;
begin
result := False;
MatchPosition := 0;
d := PByte(Data);
dataEnd := d + DataLength;
delimLength := Length(Delim);
while (d < dataEnd) do
begin
result := False;
for i := 0 to delimLength-1 do
begin
if ((d + i) >= dataEnd) then
break;
result := (d[i] = Delim[i]);
if (not result) then
break;
end;
if (result) then
begin
result := ((d + i) >= dataEnd);
MatchPosition := d - PByte(Data);
exit;
end;
d := d + 1;
end;
// no match
MatchPosition := -1;
end;
{ AsyncReadUntilDelimOp }
constructor AsyncReadUntilDelimOp.Create(const Stream: AsyncStream;
const Buffer: StreamBuffer; const Delim: TArray<Byte>;
const Handler: IOHandler);
begin
inherited Create;
FTotalBytesTransferred := 0;
FStream := Stream;
FBuffer := Buffer;
FSearchPosition := 0;
FDelim := Delim;
FHandler := Handler;
end;
procedure AsyncReadUntilDelimOp.Invoke(const Res: OpResult;
const BytesTransferred: UInt64);
var
n: UInt64;
readMore: boolean;
buf: MemoryBuffer;
matchPos: NativeInt;
match: boolean;
begin
FTotalBytesTransferred := FTotalBytesTransferred + BytesTransferred;
FBuffer.Commit(BytesTransferred);
readMore := True;
if ((not Res.Success) or (BytesTransferred = 0)) then
readMore := False;
match := PartialSearch(PByte(FBuffer) + FSearchPosition, FSearchPosition - FBuffer.BufferSize, FDelim, matchPos);
if (match) then
begin
// match, we're done
FSearchPosition := FSearchPosition + matchPos;
n := 0;
end
else if (FBuffer.BufferSize >= FBuffer.MaxBufferSize) then
begin
// no more room
n := 0;
end
else
begin
if (matchPos >= 0) then
begin
// partial match, need more data
// next search starts at start of match
FSearchPosition := FSearchPosition + matchPos;
end
else
begin
// no match
// next search starts at new data
FSearchPosition := FSearchPosition + BytesTransferred;
end;
n := ReadSizeHelper(FBuffer, MaxTransferSize);
end;
if (n = 0) then
readMore := False;
if (readMore) then
begin
buf := FBuffer.PrepareCommit(n);
FStream.AsyncReadSome(buf, Self);
end
else
begin
// write what we have to the destination stream
n := IfThen(Res.Success and match, FSearchPosition, 0);
FHandler(Res, n);
end;
end;
procedure AsyncReadUntil(const Stream: AsyncStream; const Buffer: StreamBuffer; const Delim: array of Byte; const Handler: IOHandler);
var
d: TArray<Byte>;
i: integer;
begin
SetLength(d, Length(Delim));
for i := 0 to High(Delim) do
d[i] := Delim[i];
AsyncReadUntil(Stream, Buffer, d, Handler);
end;
procedure AsyncReadUntil(const Stream: AsyncStream; const Buffer: StreamBuffer; const Delim: TArray<Byte>; const Handler: IOHandler);
var
n: UInt64;
readOp: IOHandler;
buf: MemoryBuffer;
begin
n := ReadSizeHelper(Buffer, MaxTransferSize);
buf := Buffer.PrepareCommit(n);
readOp := AsyncReadUntilDelimOp.Create(Stream, Buffer, Delim, Handler);
Stream.AsyncReadSome(buf, readOp);
end;
type
AsyncWriteOp = class(TInterfacedObject, IOHandler)
strict private
FTotalBytesTransferred: UInt64;
FStream: AsyncStream;
FBuffer: MemoryBuffer;
FCompletionCondition: IOCompletionCondition;
FHandler: IOHandler;
procedure Invoke(const Res: OpResult; const BytesTransferred: UInt64);
public
constructor Create(const Stream: AsyncStream; const Buffer: MemoryBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler);
end;
{ AsyncWriteOp }
constructor AsyncWriteOp.Create(const Stream: AsyncStream;
const Buffer: MemoryBuffer; const CompletionCondition: IOCompletionCondition;
const Handler: IOHandler);
begin
inherited Create;
FTotalBytesTransferred := 0;
FStream := Stream;
FBuffer := Buffer;
FCompletionCondition := CompletionCondition;
FHandler := Handler;
end;
procedure AsyncWriteOp.Invoke(const Res: OpResult;
const BytesTransferred: UInt64);
var
n: UInt64;
writeMore: boolean;
begin
FTotalBytesTransferred := FTotalBytesTransferred + BytesTransferred;
writeMore := True;
if ((not Res.Success) or (BytesTransferred = 0)) then
writeMore := False;
n := FCompletionCondition(Res, FTotalBytesTransferred);
if (n = 0) or (FTotalBytesTransferred = FBuffer.Size) then
writeMore := False;
if (writeMore) then
begin
FStream.AsyncWriteSome(MakeBuffer(FBuffer, n), Self);
end
else
begin
FHandler(Res, FTotalBytesTransferred);
end;
end;
procedure AsyncWrite(const Stream: AsyncStream; const Buffer: MemoryBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler);
var
n: UInt64;
writeOp: IOHandler;
begin
n := CompletionCondition(GenericResults.Success, 0);
if (n = 0) then
begin
Stream.Service.Post(
procedure
begin
Handler(GenericResults.Success, 0);
end
);
exit;
end;
writeOp := AsyncWriteOp.Create(Stream, Buffer, CompletionCondition, Handler);
Stream.AsyncWriteSome(MakeBuffer(Buffer, n), writeOp);
end;
type
AsyncWriteStreamAdapterOp = class(TInterfacedObject, IOHandler)
strict private
FTotalBytesTransferred: UInt64;
FStream: AsyncStream;
FBuffer: StreamBuffer;
FCompletionCondition: IOCompletionCondition;
FHandler: IOHandler;
procedure Invoke(const Res: OpResult; const BytesTransferred: UInt64);
public
constructor Create(const Stream: AsyncStream; const Buffer: StreamBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler);
end;
{ AsyncWriteStreamAdapterOp }
constructor AsyncWriteStreamAdapterOp.Create(const Stream: AsyncStream;
const Buffer: StreamBuffer; const CompletionCondition: IOCompletionCondition;
const Handler: IOHandler);
begin
inherited Create;
FTotalBytesTransferred := 0;
FStream := Stream;
FBuffer := Buffer;
FCompletionCondition := CompletionCondition;
FHandler := Handler;
end;
procedure AsyncWriteStreamAdapterOp.Invoke(const Res: OpResult;
const BytesTransferred: UInt64);
var
n: UInt64;
readMore: boolean;
buf: MemoryBuffer;
begin
FTotalBytesTransferred := FTotalBytesTransferred + BytesTransferred;
FBuffer.Consume(BytesTransferred);
readMore := True;
if ((not Res.Success) or (BytesTransferred = 0)) then
readMore := False;
n := FCompletionCondition(Res, FTotalBytesTransferred);
n := Min(n, FBuffer.BufferSize);
if (n = 0) then
readMore := False;
if (readMore) then
begin
buf := FBuffer.PrepareConsume(n);
FStream.AsyncWriteSome(buf, Self);
end
else
begin
FHandler(Res, FTotalBytesTransferred);
end;
end;
procedure AsyncWrite(const Stream: AsyncStream; const Buffer: StreamBuffer; const CompletionCondition: IOCompletionCondition; const Handler: IOHandler); overload;
var
n: UInt64;
writeOp: IOHandler;
buf: MemoryBuffer;
begin
n := CompletionCondition(GenericResults.Success, 0);
n := Min(n, Buffer.BufferSize);
if (n = 0) then
begin
Stream.Service.Post(
procedure
begin
Handler(GenericResults.Success, 0);
end
);
exit;
end;
writeOp := AsyncWriteStreamAdapterOp.Create(Stream, Buffer, CompletionCondition, Handler);
buf := Buffer.PrepareConsume(n);
Stream.AsyncWriteSome(buf, writeOp);
end;
{ MemoryBuffer }
class function MemoryBuffer.Create(const Data: pointer;
const Size: cardinal): MemoryBuffer;
begin
result.FData := Data;
result.FSize := Size;
end;
class operator MemoryBuffer.Implicit(const a: TBytes): MemoryBuffer;
begin
result.FData := @a[0];
result.FSize := Length(a);
end;
procedure MemoryBuffer.SetSize(const MaxSize: cardinal);
begin
FSize := Min(FSize, MaxSize);
end;
{ StreamBuffer }
procedure StreamBuffer.Commit(const Size: UInt32);
begin
Impl.Commit(Size);
end;
procedure StreamBuffer.Consume(const Size: UInt32);
begin
Impl.Consume(Size);
end;
class function StreamBuffer.Create(const MaxBufferSize: UInt64): StreamBuffer;
begin
result := StreamBufferImpl.Create(MaxBufferSize);
end;
function StreamBuffer.GetBufferSize: UInt64;
begin
result := Impl.BufferSize;
end;
function StreamBuffer.GetData: pointer;
begin
result := Impl.Data;
end;
function StreamBuffer.GetMaxBufferSize: UInt64;
begin
result := Impl.MaxBufferSize;
end;
function StreamBuffer.GetStream: TStream;
begin
result := Impl.Stream;
end;
class operator StreamBuffer.Implicit(const Impl: StreamBuffer.IStreamBuffer): StreamBuffer;
begin
result.FImpl := Impl;
end;
function StreamBuffer.PrepareCommit(const Size: UInt32): MemoryBuffer;
begin
result := Impl.PrepareCommit(Size);
end;
function StreamBuffer.PrepareConsume(const Size: UInt32): MemoryBuffer;
begin
result := Impl.PrepareConsume(Size);
end;
end.
|
// Copyright (c) 2016, Jordi Corbilla
// 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 this library 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.
unit lib.urls.converter;
interface
uses
System.Contnrs, Generics.Collections, lib.urls;
type
TUrlConverter = class(TObject)
private
FJsonString : string;
public
constructor Create(jsonString : string);
function GetCollection() : TList<IUrls>;
end;
implementation
uses
DBXJSON, System.JSON, System.SysUtils;
{ TUrlConverter }
constructor TUrlConverter.Create(jsonString: string);
begin
FJsonString := jsonString;
end;
function TUrlConverter.GetCollection: TList<IUrls>;
var
LJsonArr : TJSONArray;
LJsonValue : TJSONValue;
LItem : TJSONValue;
user : string;
password : string;
url : string;
collection : TList<IUrls>;
begin
collection := TList<IUrls>.create();
try
LJsonArr := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(FJsonString),0) as TJSONArray;
for LJsonValue in LJsonArr do
begin
for LItem in TJSONArray(LJsonValue) do
begin
if (TJSONPair(LItem).JsonString.Value = 'user') then
user := TJSONPair(LItem).JsonValue.Value;
if (TJSONPair(LItem).JsonString.Value = 'password') then
password := TJSONPair(LItem).JsonValue.Value;
if (TJSONPair(LItem).JsonString.Value = 'url') then
url := TJSONPair(LItem).JsonValue.Value;
end;
collection.Add(TUrls.Create(user, password, url));
end;
finally
result := collection;
end;
end;
end.
|
{
this file is part of Ares
Aresgalaxy ( http://aresgalaxy.sourceforge.net )
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
}
{
Description:
main bittorrent constants
}
unit bittorrentConst;
interface
uses
classes,helper_datetime,const_ares;
const
TIMEOUTTCPCONNECTION=10*SECOND;
TIMEOUTTCPRECEIVE=15*SECOND;
TIMEOUTTCPCONNECTIONTRACKER=15*SECOND;
TIMEOUTTCPRECEIVETRACKER=30*SECOND;
BTSOURCE_CONN_ATTEMPT_INTERVAL=MINUTE;
BT_MAXSOURCE_FAILED_ATTEMPTS=2;
BTKEEPALIVETIMEOUT=2*MINUTE;
BITTORRENT_PIECE_LENGTH=16*KBYTE;
EXPIRE_OUTREQUEST_INTERVAL=60*SECOND;
INTERVAL_REREQUEST_WHENNOTCHOCKED=10*SECOND;
TRACKER_NUMPEER_REQUESTED=100;
BITTORRENT_INTERVAL_BETWEENCHOKES=10*SECOND;
BITTORENT_MAXNUMBER_CONNECTION_ESTABLISH = 35;
BITTORENT_MAXNUMBER_CONNECTION_ACCEPTED = 55;
TRACKERINTERVAL_WHENFAILED=2*MINUTE;
BITTORRENT_MAX_ALLOWED_SOURCES = 300;
BITTORRENT_DONTASKMORESOURCES = 200;
SEVERE_LEECHING_RATIO=10;
NUMMAX_SOURCES_DOWNLOADING = 4;
MAX_OUTGOING_ATTEMPTS = 3;
MAXNUM_OUTBUFFER_PACKETS = 10;
NUMMAX_TRANSFER_HASHFAILS = 8;
NUMMAX_SOURCE_HASHFAILS = 4;
STR_BITTORRENT_PROTOCOL_HANDSHAKE=chr(19)+'BitTorrent protocol';
STR_BITTORRENT_PROTOCOL_EXTENSIONS=CHRNULL{chr($80)}+CHRNULL+CHRNULL+CHRNULL+
CHRNULL+chr($10)+CHRNULL+chr(1); // support extension protocol + dht
TORRENT_DONTSHARE_INTERVAL=2592000;//30 days
CMD_BITTORRENT_CHOKE = 0;
CMD_BITTORRENT_UNCHOKE = 1;
CMD_BITTORRENT_INTERESTED = 2;
CMD_BITTORRENT_NOTINTERESTED = 3;
CMD_BITTORRENT_HAVE = 4;
CMD_BITTORRENT_BITFIELD = 5;
CMD_BITTORRENT_REQUEST = 6;
CMD_BITTORRENT_PIECE = 7;
CMD_BITTORRENT_CANCEL = 8;
CMD_BITTORRENT_DHTUDPPORT = 9;
// fast peer extensions
CMD_BITTORRENT_SUGGESTPIECE = 13;
CMD_BITTORRENT_HAVEALL = 14;
CMD_BITTORRENT_HAVENONE = 15;
CMD_BITTORRENT_REJECTREQUEST = 16;
CMD_BITTORRENT_ALLOWEDFAST = 17;
// extension protocol
CMD_BITTORRENT_EXTENSION = 20;
OPCODE_EXTENDED_HANDSHAKE = 0;
OUR_UT_PEX_OPCODE = 1;
OUR_UT_METADATA_OPCODE = 2;
// dummy value for addpacket procedure
CMD_BITTORRENT_KEEPALIVE = 100;
CMD_BITTORRENT_UNKNOWN = 101;
implementation
end. |
unit EditAlbum;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.Objects,
FMX.Edit, MediaFile,
EditAlbumController;
type
TfrmEditAlbum = class(TForm)
TopLabel: TLabel;
ButtonLayout: TLayout;
btCancel: TButton;
btSave: TButton;
BottomLayout: TLayout;
CenterLayout: TLayout;
NameLayout: TLayout;
edName: TEdit;
lbName: TLabel;
YearLayout: TLayout;
edYear: TEdit;
lbYear: TLabel;
procedure btCancelClick(Sender: TObject);
procedure btSaveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FController: TEditAlbumController;
public
procedure SetAlbum(AlbumId: Variant);
end;
implementation
{$R *.fmx}
procedure TfrmEditAlbum.btCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfrmEditAlbum.btSaveClick(Sender: TObject);
var
Album: TAlbum;
begin
Album := FController.Album;
Album.AlbumName := edName.Text;
if edYear.Text <> '' then
Album.ReleaseYear := StrToInt(edYear.Text);
FController.SaveAlbum(Album);
ModalResult := mrOk;
end;
procedure TfrmEditAlbum.FormCreate(Sender: TObject);
begin
FController := TEditAlbumController.Create;
end;
procedure TfrmEditAlbum.FormDestroy(Sender: TObject);
begin
FController.Free;
end;
procedure TfrmEditAlbum.SetAlbum(AlbumId: Variant);
var
Album: TAlbum;
begin
FController.Load(AlbumId);
Album := FController.Album;
edName.Text := Album.AlbumName;
if Album.ReleaseYear.HasValue then
edYear.Text := IntToStr(Album.ReleaseYear);
end;
end.
|
unit uRelatorioGestaoMercados;
interface
uses
System.IOUtils,
System.DateUtils,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore,
dxSkinscxPCPainter, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, cxClasses, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxCustomPivotGrid, cxDBPivotGrid, cxLabel,
dxGDIPlusClasses, Vcl.ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridCustomView,
cxGrid, cxPC, dxSkinsDefaultPainters, dxSkinOffice2013White, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, Vcl.StdCtrls,
cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxCheckBox, cxCheckComboBox, FireDAC.Comp.ScriptCommands,
FireDAC.Comp.Script, cxCurrencyEdit, cxMemo, dxSkinBlack, dxSkinBlue,
dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue;
type
TFr_RelatorioGestaoMercados = class(TForm)
DataSourceVSOP_OrderBillingFaturamento: TDataSource;
FDConnection: TFDConnection;
FDQueryVSOP_OrderBillingFaturamento: TFDQuery;
FDQueryVSOP_OrderBillingPedidos: TFDQuery;
FDQueryVSOP_OrderBillingPedidosTSOP_ORDBILCANNOM: TStringField;
FDQueryVSOP_OrderBillingPedidosTSOP_ORDBILGRUCLINOM: TStringField;
FDQueryVSOP_OrderBillingPedidosTSOP_ORDBILREPNOM: TStringField;
FDQueryVSOP_OrderBillingPedidosTSOP_ORDBILVALLIQ: TBCDField;
DataSourceVSOP_OrderBillingPedidos: TDataSource;
FDQueryVSOP_OrderBillingFaturamentoTSOP_ORDBILCANNOM: TStringField;
FDQueryVSOP_OrderBillingFaturamentoTSOP_ORDBILGRUCLINOM: TStringField;
FDQueryVSOP_OrderBillingFaturamentoTSOP_ORDBILREPNOM: TStringField;
FDQueryVSOP_OrderBillingFaturamentoTSOP_ORDBILVALLIQ: TBCDField;
PanelSQLSplashScreen: TPanel;
ImageSQLSplashScreen: TImage;
cxLabelMensagem: TcxLabel;
FDQueryVSOP_OrderBillingPedidosTSOP_ORDBILDAT: TMemoField;
FDQueryVSOP_OrderBillingFaturamentoTSOP_ORDBILDAT: TMemoField;
FDQueryVSOP_OrderBillingPedidosTSOP_ORDBILTYP: TStringField;
FDQueryVSOP_OrderBillingPedidosTSOP_REPNOMINT: TStringField;
FDQueryVSOP_OrderBillingPedidosTSOP_REPMKT: TStringField;
FDQueryVSOP_OrderBillingPedidosTSOP_ORDBILCLINOM: TStringField;
FDQueryVSOP_OrderBillingPedidosTSOP_GRUCLIMER: TStringField;
FDQueryVSOP_OrderBillingPedidosTSOP_ORDBILSITNOM: TStringField;
FDQueryVSOP_OrderBillingFaturamentoTSOP_REPNOMINT: TStringField;
FDQueryVSOP_OrderBillingFaturamentoTSOP_REPMKT: TStringField;
FDQueryVSOP_OrderBillingFaturamentoTSOP_ORDBILCLINOM: TStringField;
FDQueryVSOP_OrderBillingFaturamentoTSOP_GRUCLIMER: TStringField;
FDQueryVSOP_OrderBillingFaturamentoTSOP_ORDBILSITNOM: TStringField;
FDQueryVSOP_OrderBillingFaturamentoTSOP_ORDBILTYP: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracy: TFDQuery;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILREPNOM: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILGRUCLINOM: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILCANNOM: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILDAT: TMemoField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILTYP: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILVALLIQ: TBCDField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_REPNOMINT: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_REPMKT: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILCLINOM: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_GRUCLIMER: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILSITNOM: TStringField;
DataSourceVSOP_OrderBillingForecastAccuracy: TDataSource;
cxPageControlPivot: TcxPageControl;
cxTabSheetPivot00: TcxTabSheet;
cxDBPivotGrid000: TcxDBPivotGrid;
cxDBPivotGrid00FieldTSOP_ORDBILREPNOM: TcxDBPivotGridField;
cxDBPivotGrid00FieldTSOP_ORDBILGRUCLINOM: TcxDBPivotGridField;
cxDBPivotGrid00FieldTSOP_ORDBILCANNOM: TcxDBPivotGridField;
cxDBPivotGrid00FieldTSOP_ORDBILDAT: TcxDBPivotGridField;
cxDBPivotGrid00FieldTSOP_ORDBILVALLIQ: TcxDBPivotGridField;
cxDBPivotGrid00FieldTSOP_REPNOMINT: TcxDBPivotGridField;
cxDBPivotGrid00FieldTSOP_ORDBILSITNOM: TcxDBPivotGridField;
cxDBPivotGrid00FieldTSOP_ORDBILCLINOM: TcxDBPivotGridField;
cxDBPivotGrid00FieldTSOP_GRUCLIMER: TcxDBPivotGridField;
cxDBPivotGrid00FieldTSOP_REPMKT: TcxDBPivotGridField;
cxTabSheetPivot01: TcxTabSheet;
cxDBPivotGrid001: TcxDBPivotGrid;
cxDBPivotGrid01FieldTSOP_ORDBILREPNOM: TcxDBPivotGridField;
cxDBPivotGrid01FieldTSOP_ORDBILGRUCLINOM: TcxDBPivotGridField;
cxDBPivotGrid01FieldTSOP_ORDBILCANNOM: TcxDBPivotGridField;
cxDBPivotGrid01FieldTSOP_ORDBILDAT: TcxDBPivotGridField;
cxDBPivotGrid01FieldTSOP_ORDBILVALLIQ: TcxDBPivotGridField;
cxDBPivotGrid01FieldTSOP_REPNOMINT: TcxDBPivotGridField;
cxDBPivotGrid01FieldTSOP_ORDBILSITNOM: TcxDBPivotGridField;
cxDBPivotGrid01FieldTSOP_ORDBILCLINOM: TcxDBPivotGridField;
cxDBPivotGrid01FieldTSOP_GRUCLIMER: TcxDBPivotGridField;
cxDBPivotGrid01FieldTSOP_REPMKT: TcxDBPivotGridField;
cxDBPivotGrid01FieldTSOP_ORDBILTYP: TcxDBPivotGridField;
cxTabSheetPivot02: TcxTabSheet;
cxDBPivotGrid02: TcxDBPivotGrid;
cxDBPivotGrid02FieldTSOP_ORDBILREPNOM: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_ORDBILGRUCLINOM: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_ORDBILCANNOM: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_ORDBILDAT: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_ORDBILVALLIQSAL: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_REPNOMINT: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_ORDBILSITNOM: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_ORDBILCLINOM: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_GRUCLIMER: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_REPMKT: TcxDBPivotGridField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILVALLIQSAL: TFloatField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILVALLIQFOR: TFloatField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILVALLIQACC: TFloatField;
cxDBPivotGrid02FieldTSOP_ORDBILVALLIQFOR: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_ORDBILVALLIQACC: TcxDBPivotGridField;
cxStyleRepositoryColumns: TcxStyleRepository;
cxStyleColumnAccuracy: TcxStyle;
FDQueryVSOP_OrderBillingForecastAccuracyFamilia: TFDQuery;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILREPNOM: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILGRUCLINOM: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILCANNOM: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILDAT: TMemoField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILTYP: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILVALLIQ: TBCDField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_REPNOMINT: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_REPMKT: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILCLINOM: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_GRUCLIMER: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILSITNOM: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILVALLIQSAL: TFloatField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILVALLIQFOR: TFloatField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILVALLIQACC: TFloatField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILITEFAM: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILITEFAMPAI: TStringField;
cxTabSheetPivot03: TcxTabSheet;
cxDBPivotGrid03: TcxDBPivotGrid;
cxDBPivotGrid03FieldTSOP_ORDBILREPNOM: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILGRUCLINOM: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILCANNOM: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILDAT: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILVALLIQSAL: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILVALLIQFOR: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_REPNOMINT: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILSITNOM: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILCLINOM: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILITEFAMPAI: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILITEFAM: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_GRUCLIMER: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_REPMKT: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILVALLIQACC: TcxDBPivotGridField;
DataSourceVSOP_OrderBillingForecastAccuracyFamilia: TDataSource;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILREG: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyTSOP_ORDBILREGEST: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILREG: TStringField;
FDQueryVSOP_OrderBillingForecastAccuracyFamiliaTSOP_ORDBILREGEST: TStringField;
cxDBPivotGrid02FieldTSOP_ORDBILREGEST: TcxDBPivotGridField;
cxDBPivotGrid02FieldTSOP_ORDBILREG: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILREGEST: TcxDBPivotGridField;
cxDBPivotGrid03FieldTSOP_ORDBILREG: TcxDBPivotGridField;
cxDBPivotGrid00FieldTSOP_ORDBILTYP: TcxDBPivotGridField;
Panel1: TPanel;
cxButtonRefresh: TcxButton;
cxLabel3: TcxLabel;
cxCheckComboBoxTSOP_CANAL: TcxCheckComboBox;
cxLabelData: TcxLabel;
cxDateEdit_DATINI: TcxDateEdit;
cxLabelDataFinal: TcxLabel;
FDQueryVSOP_OrderBillingPedidosTSOP_ORDBILITECOD: TStringField;
cxDBPivotGrid00FieldTSOP_ORDBILITECOD: TcxDBPivotGridField;
cxDateEdit_DATFIM: TcxDateEdit;
cbxData: TcxComboBox;
FDQueryVSOP_OrderBillingPedidosTSOP_ORDBILQTDSKU: TBCDField;
cxDBPivotGrid000FieldTSOP_ORDBILQTDSKU: TcxDBPivotGridField;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
procedure FormCreate(Sender: TObject);
procedure FDQueryVSOP_OrderBillingForecastAccuracyCalcFields(
DataSet: TDataSet);
procedure cxDBPivotGrid02FieldTSOP_ORDBILVALLIQACCGetDisplayText(
Sender: TcxPivotGridField; ACell: TcxPivotGridDataCellViewInfo;
var AText: string);
procedure Button1Click(Sender: TObject);
procedure FDQueryVSOP_OrderBillingForecastAccuracyFamiliaCalcFields(
DataSet: TDataSet);
procedure cxDBPivotGrid03FieldTSOP_ORDBILVALLIQACCGetDisplayText(
Sender: TcxPivotGridField; ACell: TcxPivotGridDataCellViewInfo;
var AText: string);
procedure cxButtonRefreshClick(Sender: TObject);
procedure cbxDataPropertiesChange(Sender: TObject);
private
TextVendas: String;
TextForecast: String;
procedure Mensagem( pMensagem: String );
{ Private declarations }
public
procedure AbrirDataset;
procedure LoadGridCustomization;
function getText( AText: String ): String;
{ Public declarations }
end;
var
Fr_RelatorioGestaoMercados: TFr_RelatorioGestaoMercados;
implementation
{$R *.dfm}
uses uBrady, uUtils, uDados;
procedure TFr_RelatorioGestaoMercados.AbrirDataset;
var
varTSOP_CANAL : String;
begin
Mensagem( 'Abrindo conex„o...' );
try
if not FDConnection.Connected then
begin
FDConnection.Params.LoadFromFile( MyDocumentsPath + '\DB.ini' );
FDConnection.Open;
end;
Mensagem( 'Obtendo dados (Entrada de Pedidos do MÍs)...' );
// FDQueryVSOP_OrderBillingPedidos.ParamByName( 'MES_INI' ).AsDateTime := System.DateUtils.StartOfTheMonth(cxDateEdit_DATINI.Date);
// FDQueryVSOP_OrderBillingPedidos.ParamByName( 'MES_INI_ANT' ).AsDateTime := System.DateUtils.StartOfTheMonth(cxDateEdit_DATINI.Date)-365;
{
if System.DateUtils.MonthOf(Now) >= 8 then
begin
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'YEARDOC' ).AsInteger := System.DateUtils.YearOf(cxDateEdit_DATINI.Date) + 1 ;
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'YEARDOC_ANT' ).AsInteger := System.DateUtils.YearOf(cxDateEdit_DATINI.Date);
end
else
begin
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'YEARDOC' ).AsInteger := System.DateUtils.YearOf(cxDateEdit_DATINI.Date);
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'YEARDOC_ANT' ).AsInteger := System.DateUtils.YearOf(cxDateEdit_DATINI.Date) - 1;
end;
if System.DateUtils.MonthOf(Now) >= 8 then
begin
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'MONTHDOC' ).AsInteger := System.DateUtils.MonthOf(cxDateEdit_DATINI.Date) - 7;
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'MONTHDOC_ANT' ).AsInteger := System.DateUtils.MonthOf(cxDateEdit_DATINI.Date) - 7;
end
else
begin
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'MONTHDOC' ).AsInteger := System.DateUtils.MonthOf(cxDateEdit_DATINI.Date) + 5;
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'MONTHDOC_ANT' ).AsInteger := System.DateUtils.MonthOf(cxDateEdit_DATINI.Date) + 5;
end;
}
varTSOP_CANAL := EmptyStr;
if cxCheckComboBoxTSOP_CANAL.States[0] = cbsChecked then
begin
if varTSOP_CANAL = EmptyStr then
varTSOP_CANAL := ' AND B01.TSOP_ORDBILCANNOM IN ('
else
varTSOP_CANAL := varTSOP_CANAL + ',';
varTSOP_CANAL := varTSOP_CANAL + QuotedStr('DISTRIBUTORS');
end;
if cxCheckComboBoxTSOP_CANAL.States[1] = cbsChecked then
begin
if varTSOP_CANAL = EmptyStr then
varTSOP_CANAL := ' AND B01.TSOP_ORDBILCANNOM IN ('
else
varTSOP_CANAL := varTSOP_CANAL + ',';
varTSOP_CANAL := varTSOP_CANAL + QuotedStr('PID');
end;
if not (varTSOP_CANAL = EmptyStr) then
begin
varTSOP_CANAL := varTSOP_CANAL + ')';
end;
if cbxData.ItemIndex = 1 then
begin
{
FDQueryVSOP_OrderBillingPedidos.MacroByName( 'WHERE3' ).AsRaw := ' AND C01.TSOP_ORDBILDATDOCREQ >= ''' +
FormatDateTime('yyyy-mm-dd 00:00:01', cxDateEdit_DATINI.Date) + '''' +
' and C01.TSOP_ORDBILDATDOCREQ <= ''' + FormatDateTime('yyyy-mm-dd 23:59:59', cxDateEdit_DATFIM.Date) + '''';
}
FDQueryVSOP_OrderBillingPedidos.MacroByName( 'WHERE3' ).AsRaw := ' AND C01.TSOP_ORDBILDATDOCREQ >= :DtRecIni and C01.TSOP_ORDBILDATDOCREQ <= :DtRecFim ';
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'DtRecIni' ).AsString := FormatDateTime('yyyy-mm-dd 00:00:01', System.DateUtils.StartOfTheMonth(System.DateUtils.EndOfTheMonth(cxDateEdit_DATINI.Date)));
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'DtRecFim' ).AsString := FormatDateTime('yyyy-mm-dd 23:59:59', System.DateUtils.EndOfTheMonth(System.DateUtils.EndOfTheMonth(cxDateEdit_DATINI.Date)));
{
FDQueryVSOP_OrderBillingPedidos.MacroByName( 'WHERE3ANT' ).AsRaw := ' AND C01.TSOP_ORDBILDATDOCREQ >= ''' +
FormatDateTime('yyyy-mm-dd 00:00:01', cxDateEdit_DATINI.Date-365 ) + '''' +
' and C01.TSOP_ORDBILDATDOCREQ <= ''' + FormatDateTime('yyyy-mm-dd 23:59:59', cxDateEdit_DATFIM.Date-365) + '''';
}
FDQueryVSOP_OrderBillingPedidos.MacroByName( 'WHERE3ANT' ).AsRaw := ' AND C01.TSOP_ORDBILDATDOCREQ >= :DtRecIniAnt and C01.TSOP_ORDBILDATDOCREQ <= :DtRecFimAnt ';
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'DtRecIniAnt' ).AsString := FormatDateTime('yyyy-mm-dd 00:00:01', System.DateUtils.StartOfTheMonth(System.DateUtils.EndOfTheMonth(cxDateEdit_DATINI.Date)-365));
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'DtRecFimAnt' ).AsString := FormatDateTime('yyyy-mm-dd 23:59:59', System.DateUtils.EndOfTheMonth(System.DateUtils.EndOfTheMonth(cxDateEdit_DATINI.Date)-365));
cxDBPivotGrid00FieldTSOP_ORDBILDAT.Caption := 'Data Requerida';
end
else
begin
FDQueryVSOP_OrderBillingPedidos.MacroByName( 'WHERE3' ).AsRaw := ' AND C01.TSOP_ORDBILDATDOC >= :DtDocIni and C01.TSOP_ORDBILDATDOC <= :DtDocFim';
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'DtDocIni' ).AsDateTime := System.DateUtils.StartOfTheMonth(System.DateUtils.EndOfTheMonth(cxDateEdit_DATINI.Date));
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'DtDocFim' ).AsDateTime := System.DateUtils.EndOfTheMonth(System.DateUtils.EndOfTheMonth(cxDateEdit_DATINI.Date));
FDQueryVSOP_OrderBillingPedidos.MacroByName( 'WHERE3ANT' ).AsRaw := ' AND C01.TSOP_ORDBILDATDOC >= :DtDocIniAnt and C01.TSOP_ORDBILDATDOC <= :DtDocFimAnt';
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'DtDocIniAnt' ).AsDateTime := System.DateUtils.StartOfTheMonth(System.DateUtils.EndOfTheMonth(cxDateEdit_DATINI.Date)-365);
FDQueryVSOP_OrderBillingPedidos.ParamByName( 'DtDocFimAnt' ).AsDateTime := System.DateUtils.EndOfTheMonth(System.DateUtils.EndOfTheMonth(cxDateEdit_DATINI.Date)-365);
cxDBPivotGrid00FieldTSOP_ORDBILDAT.Caption := 'Data Documento';
end;
if Fr_Brady.SalesRep then
FDQueryVSOP_OrderBillingPedidos.MacroByName( 'WHERE1' ).AsRaw := 'AND (B01.TSOP_ORDBILREPNOM = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ' OR B01.TSOP_REPMKT = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ' OR B01.TSOP_REPNOMINT = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ')';
if Fr_Brady.CustomerService then
FDQueryVSOP_OrderBillingPedidos.MacroByName( 'WHERE1' ).AsRaw := 'AND B01.TSOP_ORDBILREPCSR = ' + QuotedStr(Fr_Brady.TSIS_USUNOM);
FDQueryVSOP_OrderBillingPedidos.MacroByName( 'WHERE2' ).AsRaw := varTSOP_CANAL;
FDQueryVSOP_OrderBillingPedidos.Open;
{
Mensagem( 'Obtendo dados (Faturamento do MÍs)...' );
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANO_INI' ).AsDateTime := System.DateUtils.StartOfTheMonth(System.DateUtils.EndOfTheMonth(Now)-365);
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANO_FIM' ).AsDateTime := System.DateUtils.EndOfTheMonth(System.DateUtils.EndOfTheMonth(Now)-365);
if System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANO_INI' ).AsDateTime) >= 8 then
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'YEARDOC_ANO' ).AsInteger := System.DateUtils.YearOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANO_INI' ).AsDateTime) + 1
else
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'YEARDOC_ANO' ).AsInteger := System.DateUtils.YearOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANO_INI' ).AsDateTime);
if System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANO_INI' ).AsDateTime) >= 8 then
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MONTHDOC_ANO' ).AsInteger := System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANO_INI' ).AsDateTime) - 7
else
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MONTHDOC_ANO' ).AsInteger := System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANO_INI' ).AsDateTime) + 5;
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANT_INI' ).AsDateTime := System.DateUtils.StartOfTheMonth(System.DateUtils.StartOfTheMonth(Now)-1);
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANT_FIM' ).AsDateTime := System.DateUtils.EndOfTheMonth(System.DateUtils.StartOfTheMonth(Now)-1);
if System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANT_INI' ).AsDateTime) >= 8 then
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'YEARDOC_ANT' ).AsInteger := System.DateUtils.YearOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANT_INI' ).AsDateTime) + 1
else
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'YEARDOC_ANT' ).AsInteger := System.DateUtils.YearOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANT_INI' ).AsDateTime);
if System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANO_INI' ).AsDateTime) >= 8 then
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MONTHDOC_ANT' ).AsInteger := System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANT_INI' ).AsDateTime) - 7
else
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MONTHDOC_ANT' ).AsInteger := System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_ANT_INI' ).AsDateTime) + 5;
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_INI' ).AsDateTime := System.DateUtils.StartOfTheMonth(Now);
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_FIM' ).AsDateTime := System.DateUtils.EndOfTheMonth(Now);
if System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_INI' ).AsDateTime) >= 8 then
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'YEARDOC' ).AsInteger := System.DateUtils.YearOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_INI' ).AsDateTime) + 1
else
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'YEARDOC' ).AsInteger := System.DateUtils.YearOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_INI' ).AsDateTime);
if System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_INI' ).AsDateTime) >= 8 then
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MONTHDOC' ).AsInteger := System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_INI' ).AsDateTime) - 7
else
FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MONTHDOC' ).AsInteger := System.DateUtils.MonthOf(FDQueryVSOP_OrderBillingFaturamento.ParamByName( 'MES_INI' ).AsDateTime) + 5;
if Fr_Brady.SalesRep then
FDQueryVSOP_OrderBillingFaturamento.MacroByName( 'WHERE1' ).AsRaw := 'AND (B01.TSOP_ORDBILREPNOM = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ' OR B01.TSOP_REPMKT = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ' OR B01.TSOP_REPNOMINT = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ')';
if Fr_Brady.CustomerService then
FDQueryVSOP_OrderBillingFaturamento.MacroByName( 'WHERE1' ).AsRaw := 'AND B01.TSOP_ORDBILREPCSR = ' + QuotedStr(Fr_Brady.TSIS_USUNOM);
FDQueryVSOP_OrderBillingFaturamento.Open;
Mensagem( 'Obtendo dados (Forecast Accuracy)...' );
FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'MES_INI' ).AsDateTime := System.DateUtils.IncYear(System.DateUtils.EndOfTheMonth(Now)+1,-1);
if System.DateUtils.MonthOf(Now) >= 8 then
FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'YEARDOC' ).AsInteger := System.DateUtils.YearOf(Now) + 1
else
FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'YEARDOC' ).AsInteger := System.DateUtils.YearOf(Now);
if System.DateUtils.MonthOf(Now) >= 8 then
FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'MONTHDOC' ).AsInteger := System.DateUtils.MonthOf(Now) - 7
else
FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'MONTHDOC' ).AsInteger := System.DateUtils.MonthOf(Now) + 5;
if FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'MONTHDOC' ).AsInteger = 12 then
begin
FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'MONTHDOC' ).AsInteger := 01
end
else
begin
FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'MONTHDOC' ).AsInteger := FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'MONTHDOC' ).AsInteger + 1;
FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'YEARDOC' ).AsInteger := FDQueryVSOP_OrderBillingForecastAccuracy.ParamByName( 'YEARDOC' ).AsInteger -1;
end;
if Fr_Brady.SalesRep then
FDQueryVSOP_OrderBillingForecastAccuracy.MacroByName( 'WHERE1' ).AsRaw := 'AND (B01.TSOP_ORDBILREPNOM = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ' OR B01.TSOP_REPMKT = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ' OR B01.TSOP_REPNOMINT = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ')';
if Fr_Brady.CustomerService then
FDQueryVSOP_OrderBillingForecastAccuracy.MacroByName( 'WHERE1' ).AsRaw := 'AND B01.TSOP_ORDBILREPCSR = ' + QuotedStr(Fr_Brady.TSIS_USUNOM);
FDQueryVSOP_OrderBillingForecastAccuracy.Open;
Mensagem( 'Obtendo dados (Forecast Accuracy Familia)...' );
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'MES_INI' ).AsDateTime := System.DateUtils.IncYear(System.DateUtils.EndOfTheMonth(Now)+1,-1);
if System.DateUtils.MonthOf(Now) >= 8 then
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'YEARDOC' ).AsInteger := System.DateUtils.YearOf(Now) + 1
else
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'YEARDOC' ).AsInteger := System.DateUtils.YearOf(Now);
if System.DateUtils.MonthOf(Now) >= 8 then
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'MONTHDOC' ).AsInteger := System.DateUtils.MonthOf(Now) - 7
else
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'MONTHDOC' ).AsInteger := System.DateUtils.MonthOf(Now) + 5;
if FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'MONTHDOC' ).AsInteger = 12 then
begin
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'MONTHDOC' ).AsInteger := 01
end
else
begin
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'MONTHDOC' ).AsInteger := FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'MONTHDOC' ).AsInteger + 1;
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'YEARDOC' ).AsInteger := FDQueryVSOP_OrderBillingForecastAccuracyFamilia.ParamByName( 'YEARDOC' ).AsInteger -1;
end;
if Fr_Brady.SalesRep then
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.MacroByName( 'WHERE1' ).AsRaw := 'AND (B01.TSOP_ORDBILREPNOM = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ' OR B01.TSOP_REPMKT = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ' OR B01.TSOP_REPNOMINT = ' + QuotedStr(Fr_Brady.TSIS_USUNOM) + ')';
if Fr_Brady.CustomerService then
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.MacroByName( 'WHERE1' ).AsRaw := 'AND B01.TSOP_ORDBILREPCSR = ' + QuotedStr(Fr_Brady.TSIS_USUNOM);
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.Open;
}
finally
Mensagem( EmptyStr );
end;
end;
procedure TFr_RelatorioGestaoMercados.Button1Click(Sender: TObject);
begin
FDQueryVSOP_OrderBillingFaturamento.SQL.SaveToFile( '.\FDQueryVSOP_OrderBillingFaturamento.SQL' );
FDQueryVSOP_OrderBillingPedidos.SQL.SaveToFile( '.\FDQueryVSOP_OrderBillingPedidos.SQL' );
FDQueryVSOP_OrderBillingForecastAccuracy.SQL.SaveToFile( '.\FDQueryVSOP_OrderBillingForecastAccuracy.SQL' );
FDQueryVSOP_OrderBillingForecastAccuracyFamilia.SQL.SaveToFile( '.\FDQueryVSOP_OrderBillingForecastAccuracyFamilia.SQL' );
end;
procedure TFr_RelatorioGestaoMercados.cbxDataPropertiesChange(Sender: TObject);
begin
if cbxData.ItemIndex = 0 then
cxLabelData.Caption := 'Data Documento:'
else cxLabelData.Caption := 'Data Requerida:';
end;
procedure TFr_RelatorioGestaoMercados.cxButtonRefreshClick(Sender: TObject);
begin
FDQueryVSOP_OrderBillingPedidos.Close;
AbrirDataset;
end;
procedure TFr_RelatorioGestaoMercados.cxDBPivotGrid02FieldTSOP_ORDBILVALLIQACCGetDisplayText(
Sender: TcxPivotGridField; ACell: TcxPivotGridDataCellViewInfo;
var AText: string);
var
I: Integer;
SumSales: Extended;
SumForecast: Extended;
begin
for I := 0 to ACell.CrossCell.Records.Count-1 do
begin
if not VarIsNull(ACell.CrossCell.DataController.Values[ACell.CrossCell.Records.Items[I],cxDBPivotGrid02FieldTSOP_ORDBILVALLIQSAL.Index]) then
SumSales := SumSales + ACell.CrossCell.DataController.Values[ACell.CrossCell.Records.Items[I],cxDBPivotGrid02FieldTSOP_ORDBILVALLIQSAL.Index];
if not VarIsNull(ACell.CrossCell.DataController.Values[ACell.CrossCell.Records.Items[I],cxDBPivotGrid02FieldTSOP_ORDBILVALLIQFOR.Index]) then
SumForecast := SumForecast + ACell.CrossCell.DataController.Values[ACell.CrossCell.Records.Items[I],cxDBPivotGrid02FieldTSOP_ORDBILVALLIQFOR.Index];
end;
AText := '';
if SumForecast > 0 then
AText := FormatFloat('#,##0%', SumSales / SumForecast * 100);
end;
procedure TFr_RelatorioGestaoMercados.cxDBPivotGrid03FieldTSOP_ORDBILVALLIQACCGetDisplayText(
Sender: TcxPivotGridField; ACell: TcxPivotGridDataCellViewInfo;
var AText: string);
var
I: Integer;
SumSales: Extended;
SumForecast: Extended;
begin
for I := 0 to ACell.CrossCell.Records.Count-1 do
begin
if not VarIsNull(ACell.CrossCell.DataController.Values[ACell.CrossCell.Records.Items[I],cxDBPivotGrid03FieldTSOP_ORDBILVALLIQSAL.Index]) then
SumSales := SumSales + ACell.CrossCell.DataController.Values[ACell.CrossCell.Records.Items[I],cxDBPivotGrid03FieldTSOP_ORDBILVALLIQSAL.Index];
if not VarIsNull(ACell.CrossCell.DataController.Values[ACell.CrossCell.Records.Items[I],cxDBPivotGrid03FieldTSOP_ORDBILVALLIQFOR.Index]) then
SumForecast := SumForecast + ACell.CrossCell.DataController.Values[ACell.CrossCell.Records.Items[I],cxDBPivotGrid03FieldTSOP_ORDBILVALLIQFOR.Index];
end;
AText := '';
if SumForecast > 0 then
AText := FormatFloat('#,##0%', SumSales / SumForecast * 100);
end;
procedure TFr_RelatorioGestaoMercados.FDQueryVSOP_OrderBillingForecastAccuracyCalcFields(
DataSet: TDataSet);
begin
if DataSet.FieldByName('TSOP_ORDBILTYP').AsString = '1 - Vendas' then
DataSet.FieldByName('TSOP_ORDBILVALLIQSAL').AsFloat := DataSet.FieldByName('TSOP_ORDBILVALLIQ').AsFloat
else
if DataSet.FieldByName('TSOP_ORDBILTYP').AsString = '2 - Forecast' then
DataSet.FieldByName('TSOP_ORDBILVALLIQFOR').AsFloat := DataSet.FieldByName('TSOP_ORDBILVALLIQ').AsFloat;
end;
procedure TFr_RelatorioGestaoMercados.FDQueryVSOP_OrderBillingForecastAccuracyFamiliaCalcFields(
DataSet: TDataSet);
begin
if DataSet.FieldByName('TSOP_ORDBILTYP').AsString = '1 - Vendas' then
DataSet.FieldByName('TSOP_ORDBILVALLIQSAL').AsFloat := DataSet.FieldByName('TSOP_ORDBILVALLIQ').AsFloat
else
if DataSet.FieldByName('TSOP_ORDBILTYP').AsString = '2 - Forecast' then
DataSet.FieldByName('TSOP_ORDBILVALLIQFOR').AsFloat := DataSet.FieldByName('TSOP_ORDBILVALLIQ').AsFloat;
end;
procedure TFr_RelatorioGestaoMercados.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FDQueryVSOP_OrderBillingPedidos.Close;
FDQueryVSOP_OrderBillingFaturamento.Close;
FDConnection.Close;
Fr_RelatorioGestaoMercados := nil;
Action := caFree;
end;
procedure TFr_RelatorioGestaoMercados.FormContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
begin
if cxPageControlPivot.ActivePage = cxTabSheetPivot00 then
Fr_Brady.PopupPivotTools( cxDBPivotGrid000 )
else
if cxPageControlPivot.ActivePage = cxTabSheetPivot01 then
Fr_Brady.PopupPivotTools( cxDBPivotGrid001 );
end;
procedure TFr_RelatorioGestaoMercados.FormCreate(Sender: TObject);
begin
LoadGridCustomization;
cxDateEdit_DATINI.Date := System.DateUtils.StartOfTheMonth(Now);
cxDateEdit_DATFIM.Date := System.DateUtils.EndOfTheMonth(Now);
cxCheckComboBoxTSOP_CANAL.States[0] := cbsChecked;
cxCheckComboBoxTSOP_CANAL.States[1] := cbsChecked;
end;
function TFr_RelatorioGestaoMercados.getText(AText: String): String;
begin
if TextVendas.IsEmpty then
begin
Result := 'Vendas';
TextVendas := AText;
end
else
if TextForecast.IsEmpty then
begin
Result := 'Forecast';
TextForecast := AText;
end
else
begin
Result := 'Accuracy';
TextForecast := EmptyStr;
TextVendas := EmptyStr;
end;
end;
procedure TFr_RelatorioGestaoMercados.LoadGridCustomization;
begin
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + Name + '_' + cxDBPivotGrid000.Name + '.ini' ) then
cxDBPivotGrid000.RestoreFromIniFile( MyDocumentsPath + '\' + Name + '_' + cxDBPivotGrid000.Name + '.ini' );
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + Name + '_' + cxDBPivotGrid001.Name + '.ini' ) then
cxDBPivotGrid001.RestoreFromIniFile( MyDocumentsPath + '\' + Name + '_' + cxDBPivotGrid001.Name + '.ini' );
end;
procedure TFr_RelatorioGestaoMercados.Mensagem(pMensagem: String);
begin
cxLabelMensagem.Caption := pMensagem;
PanelSQLSplashScreen.Visible := not pMensagem.IsEmpty;
Update;
Application.ProcessMessages;
end;
end.
|
unit MinimalProgressBar;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, DrawUtils, Math;
type
TCaptionType = (ctNone, ctValue, ctPercent);
TMinimalProgressBar = class(TGraphicControl)
private
FCaption: TCaptionType;
FMouseOver: boolean;
FBackground: TColor;
FMin, FMax, FPosition: integer;
FCaption_: string;
FRadius: integer;
procedure SetRadius(x: integer);
procedure SetPosition(x: integer);
procedure SetMin(x: integer);
procedure SetMax(x: integer);
{ Private declarations }
protected
procedure Paint; override;
procedure MouseLeave; override;
procedure MouseEnter; override;
procedure Resize; override;
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
{ Public declarations }
published
property Background: TColor read FBackground write FBackground;
property Radius: integer read FRadius write SetRadius;
property MouseOver: boolean read FMouseOver;
property Position: integer read FPosition write SetPosition;
property Max: integer read FMax write SetMax;
property Min: integer read FMin write SetMin;
property Caption_: string read FCaption_ write FCaption_;
property Action;
property Align;
property Anchors;
property AutoSize;
property BidiMode;
property BorderSpacing;
property Caption: TCaptionType read FCaption write FCaption;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property ParentBidiMode;
property OnChangeBounds;
property OnClick;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDrag;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
end;
procedure Register;
implementation
constructor TMinimalProgressBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
SetInitialBounds(0, 0, 120, 14);
FMax := 100;
Color := clRed;
Font.Size := 12;
FCaption_ := '';
FPosition := 50;
FRadius := -1;
Caption := ctPercent;
FBackground := clSilver;
end;
procedure TMinimalProgressBar.SetRadius(x: integer);
begin
FRadius := x;
end;
procedure TMinimalProgressBar.SetPosition(x: integer);
begin
if (x >= FMin) and (x <= FMax) then
FPosition := x;
Invalidate;
end;
procedure TMinimalProgressBar.SetMin(x: integer);
begin
if FMax - FMin > 0 then
FMin := x;
Invalidate;
end;
procedure TMinimalProgressBar.SetMax(x: integer);
begin
if FMax - FMin > 0 then
FMax := x;
Invalidate;
end;
procedure TMinimalProgressBar.Resize;
begin
Self.Height := Math.Max(Math.Max(Height, 10), Self.Font.Height);
Self.Height := Math.Min(Height, Width div 3);
Invalidate;
inherited Resize;
end;
procedure TMinimalProgressBar.Paint;
var
cap: string;
r: integer;
o: integer;
begin
with Canvas do
begin
if Radius = -1 then
begin
r := 5;
if Self.Height <= 18 then
r := Self.Height - 4;
end
else
r := Radius;
o := ifthen(FCaption = ctNone, 0, 4);
Brush.Style := bsSolid;
Pen.Width := 1;
Pen.Style := psSolid;
Brush.Color := FBackground;
Pen.Color := DarkenColor(Brush.Color, 20);
RoundRect(0, o, Self.Width, Self.Height - (o + 1), r, r);
if Enabled then
begin
Brush.Color := Self.Color;
Pen.Style := psClear;
RoundRect(0, o, Round((FPosition - FMin) / (FMax - FMin) * (Self.Width)),
Self.Height - o, r, r);
Brush.Style := bsClear;
Font.Assign(Self.Font);
end;
end;
if MouseOver and Enabled then
begin
case Caption of
ctNone: cap := FCaption_;
ctPercent: cap := IntToStr(Round((FPosition - FMin) / (FMax - FMin) *
(100))) + '%' + FCaption_;
ctValue: cap := IntToStr(FPosition) + FCaption_;
end;
DrawTextCenter(Canvas, Width, Height, cap);
end;
inherited Paint;
end;
procedure TMinimalProgressBar.MouseLeave;
begin
FMouseOver := False;
Invalidate;
inherited MouseLeave;
end;
procedure TMinimalProgressBar.MouseEnter;
begin
FMouseOver := True;
Invalidate;
inherited MouseEnter;
end;
procedure Register;
begin
{$I minimalprogressbar_icon.lrs}
RegisterComponents('Minimal Components', [TMinimalProgressBar]);
end;
end.
|
Program ejer3;
uses Crt;
type
fecha = record
dia: integer;
mes: integer;
anio: integer;
end;
actReparto = record
apellido: string[20];
nombre: string[20];
id: string[5];
dni: longint;
nacionalidad: string[50];
fechaNac: fecha;
end;
archivo = file of actReparto;
{ Escribe los actores al archivo }
procedure agregar(var actores: archivo);
var
act: actReparto;
ok: boolean;
begin
ok := true;
readln(act.apellido);
while (ok) do
begin
write('Apellido: '); readln(act.apellido);
if act.apellido = '' then
ok := false
else
begin
write('Nombre: '); readln(act.nombre);
write('ID: '); readln(act.id);
write('DNI: '); readln(act.dni);
write('Nacionalidad: '); readln(act.nacionalidad);
write('Fecha de nacimiento, dia - mes - año: ');
readln(act.fechaNac.dia); readln(act.fechaNac.mes); readln(act.fechaNac.anio);
end;
if ok then
write(actores, act);
end;
end;
{ Agregar actores al final del archivo }
procedure agregarActores(var actores: archivo);
begin
reset(actores);
seek(actores, filesize(actores));
agregar(actores);
close(actores);
end;
{ Sobreescribe el archivo con actores }
procedure escribir(var actores: archivo);
begin
rewrite(actores);
agregar(actores);
close(actores);
end;
{ Reporta la cantidad de actores con año de nacimiento previo al 1980 }
procedure rep1980(var actores: archivo);
var
cant: integer;
act: actReparto;
begin
reset(actores); cant := 0;
while(not eof(actores)) do
begin
read(actores, act);
if act.fechaNac.anio < 1980 then
cant := cant + 1;
end;
close(actores);
writeln('Cantidad de actores con fecha previa a 1980: ', cant);
end;
{ Reporta la cantidad de actores con nacionalidad venezolana }
procedure venezolanos(var actores: archivo);
var
cant: integer;
act: actReparto;
begin
reset(actores); cant := 0;
while(not eof(actores)) do
begin
read(actores, act);
if act.nacionalidad = 'venezolano' then
cant := cant + 1;
end;
close(actores);
writeln('Cantidad de actores venezolanos: ', cant);
end;
{ Reporta la cantidad de actores con DNI superior a 30.000.000 }
procedure dnisup(var actores: archivo);
var
cant: integer;
act: actReparto;
begin
reset(actores); cant := 0;
while(not eof(actores)) do
begin
read(actores, act);
if act.dni > 30000000 then
cant := cant + 1;
end;
close(actores);
writeln('Cantidad de actores con dni superior a 30.000.000: ', cant);
end;
{ Lista todos los actores }
procedure todos(var actores: archivo);
var
act: actReparto;
begin
reset(actores);
while(not eof(actores)) do
begin
read(actores, act);
writeln('nombre: ', act.nombre, '| apellido: ', act.apellido, '| id: ', act.id, '| dni: ', act.dni, '| nacionalidad: ', act.nacionalidad, '| fecha: ', act.fechaNac.dia, '/', act.fechaNac.mes, '/', act.fechaNac.anio)
end;
close(actores);
end;
procedure bajaLogica(var actores: archivo);
var
dni: longint;
actor: actReparto;
begin
reset(actores);
write('Introduzca DNI de actor a borrar: ');
readln(dni);
repeat read(actores, actor) until (actor.dni = dni) or eof(actores);
if not eof(actores) then
begin
seek(actores, filepos(actores)-1);
actor.dni := -1;
write(actores, actor);
end;
close(actores);
end;
procedure todosBorrados(var actores: archivo);
var
actor: actReparto;
begin
reset(actores);
while(not eof(actores)) do
begin
read(actores, actor);
if(actor.dni < 0) then
writeln('nombre: ', actor.nombre, '| apellido: ', actor.apellido, '| id: ', actor.id, '| dni: ', actor.dni, '| nacionalidad: ', actor.nacionalidad, '| fecha: ', actor.fechaNac.dia, '/', actor.fechaNac.mes, '/', actor.fechaNac.anio);
end;
close(actores);
end;
procedure comprimirArchivo(var actores: archivo; var comprimido: archivo);
var
actor: actReparto;
begin
reset(actores); rewrite(comprimido);
while(not eof(actores)) do
begin
read(actores, actor);
if actor.dni > 0 then
write(comprimido, actor);
end;
close(actores); close(comprimido);
erase(actores);
rename(comprimido, 'actores.txt');
end;
procedure modificarActor(var actores: archivo);
var
act: actReparto;
auxdni: longint;
tmp: string[50];
begin
act.dni := 0;
write('DNI del actor: '); readln(auxdni);
reset(actores);
while(not eof(actores)) do
while(act.dni <> auxdni) do
begin
write(act.dni);
read(actores, act);
end;
write('Nueva nacionalidad del actor: '); readln(tmp);
act.nacionalidad := tmp;
seek(actores, filepos(actores)-1);
write(actores, act);
writeln('Nueva nacionalidad es: ', tmp);
close(actores);
end;
var
actores, comprimido: archivo;
decision: integer;
ok: boolean;
begin
assign(actores, 'actores.txt'); assign(comprimido, 'comprimido.txt');
ClrScr;
decision := 9;
ok := true;
while (ok) do
begin
writeln('');
writeln('***** 1. Escribir actores al archivo');
writeln('***** 2. Reportar actores con fecha de nacimiento previa a 1980');
writeln('***** 3. Reportar actores venezolanos');
writeln('***** 4. Reportar actores con DNI > 30.000.000');
writeln('***** 5. Modificar nacionalidad de actor');
writeln('***** 6. Baja logica acorde a DNI');
writeln('***** 7. Agregar actores');
writeln('***** 8. Listar actores');
writeln('***** 9. Listar actores borrados');
writeln('***** 10. Comprimir archivo');
writeln('***** 0. Salir');
write('Que accion desea realizar? ');
read(decision);
writeln('');
ClrScr;
case decision of
0: ok := false;
1: escribir(actores);
2: rep1980(actores);
3: venezolanos(actores);
4: dnisup(actores);
5: modificarActor(actores);
6: bajaLogica(actores);
7: agregarActores(actores);
8: todos(actores);
9: todosBorrados(actores);
10: comprimirArchivo(actores, comprimido);
otherwise writeln('Selecciona una de la lista.');
end;
end;
end.
|
{*
* Author: Raman Liubimau <raman@cmstuning.net>
* Date: 07 December 2014
*
* Architecture changed.
*}
unit Render;
interface
uses Phys_TLB, VCLTee.Series, Vcl.StdCtrls, SysUtils;
type
{*
* The abstract base class for all chart renders. Provides base functionality
* for rendering custom charts.
*}
TChartRender = class abstract(TInterfacedObject, IPhysObserver)
private
fSeries: TFastLineSeries;
function IsNeedClipping(Duration: Single): Boolean;
procedure ClipChart();
protected
function GetCurrentValue(const Model: IPhysModel): Single; virtual; abstract;
function GetIntervalLength(): Single; virtual;
public
constructor Create(Series: TFastLineSeries);
procedure Update(const Model: IPhysModel; Duration, Elapsed: Single); safecall;
end;
{*
* Simple chart for angle deviation
*}
TAngleChart = class(TChartRender)
protected
function GetCurrentValue(const Model: IPhysModel): Single; override;
public
constructor Create(Series: TFastLineSeries);
end;
{*
* Kinetic energy chart
*}
TKEnergyChart = class(TChartRender)
protected
function GetCurrentValue(const Model: IPhysModel): Single; override;
public
constructor Create(Series: TFastLineSeries);
end;
{*
* Potential energy chart
*}
TPEnergyChart = class(TChartRender)
protected
function GetCurrentValue(const Model: IPhysModel): Single; override;
public
constructor Create(Series: TFastLineSeries);
end;
{*
* A simple info render
*}
TInfoRender = class abstract(TInterfacedObject, IPhysObserver)
private
fAngle, fSpeed, fAccel: TEdit;
public
constructor Create(Angle, Speed, Accel: TEdit);
procedure Update(const Model: IPhysModel; Duration, Elapsed: Single); safecall;
end;
implementation
{*
* TChartRender
*}
constructor TChartRender.Create(Series: TFastLineSeries);
begin
fSeries := Series;
end;
procedure TChartRender.Update(const Model: IPhysModel; Duration: Single; Elapsed: Single);
begin
// Check if we need to clip chart
if IsNeedClipping(Duration) then
ClipChart();
// Add new point to chart
fSeries.AddXY(Duration, GetCurrentValue(Model));
end;
function TChartRender.IsNeedClipping(Duration: Single): Boolean;
begin
Result := (Duration > GetIntervalLength());
end;
procedure TChartRender.ClipChart();
begin
// Remove value from left
fSeries.Delete(0);
end;
function TChartRender.GetIntervalLength(): Single;
begin
Result := 1.0; // 1s
end;
{*
* Angle chart
*}
constructor TAngleChart.Create(Series: TFastLineSeries);
begin
inherited Create(Series);
end;
function TAngleChart.GetCurrentValue(const Model: IPhysModel): Single;
begin
Result := Model.Get_Angle();
end;
{*
* Kinetic energy chart
*}
constructor TKEnergyChart.Create(Series: TFastLineSeries);
begin
inherited Create(Series);
end;
function TKEnergyChart.GetCurrentValue(const Model: IPhysModel): Single;
begin
Result := Model.Get_Kinetic();
end;
{*
* Potential energy chart
*}
constructor TPEnergyChart.Create(Series: TFastLineSeries);
begin
inherited Create(Series);
end;
function TPEnergyChart.GetCurrentValue(const Model: IPhysModel): Single;
begin
Result := Model.Get_Potential();
end;
{*
* TInfoRender
*}
constructor TInfoRender.Create(Angle, Speed, Accel: TEdit);
begin
fAngle := Angle;
fSpeed := Speed;
fAccel := Accel;
end;
procedure TInfoRender.Update(const Model: IPhysModel; Duration, Elapsed: Single); safecall;
begin
fAngle.Text := FloatToStrF(Model.Get_Angle(), ffFixed, 3, 3);
fSpeed.Text := FloatToStrF(Model.Get_Speed(), ffFixed, 3, 3);
fAccel.Text := FloatToStrF(Model.Get_Accel(), ffFixed, 3, 3);
end;
end.
|
program test;
(* Test program. *)
uses
andante, anBitmap, anVga;
type
TPoint = record x, y: Real end;
TSprite = record
Color, cInc: Integer;
Position, Increment: TPoint
end;
var
Atractors: array [1..8] of TPoint;
Ball: TSprite;
(* Helper to show error messages. *)
procedure ShowError (aMessage: String);
begin
WriteLn ('Error [', anError, ']: ', aMessage);
WriteLn
end;
(* Initializes. *)
function InitializeAndante: Boolean;
begin
if not anInstall then
begin
ShowError ('Can''t initialize Andante!');
Exit (False)
end;
if not anInstallKeyboard then
begin
ShowError ('Keyboard out.');
Exit (False)
end;
if not anSetGraphicsMode (anGfx13) then
begin
ShowError ('Can''t initialize VGA.');
Exit (False)
end;
Randomize;
InitializeAndante := True
end;
(* Create a new field. *)
procedure CreateField;
var
Cnt: Integer;
begin
for Cnt := Low (Atractors) to High (Atractors) do
begin
anDrawPixel (anScreen, Trunc (Atractors[Cnt].x), Trunc (Atractors[Cnt].y), 0);
Atractors[Cnt].x := Random (300) + 10;
Atractors[Cnt].y := Random (180) + 10;
anDrawPixel (anScreen, Trunc (Atractors[Cnt].x), Trunc (Atractors[Cnt].y), 12)
end;
Ball.Position.x := Random (300) + 10;
Ball.Position.y := Random (180) + 10;
Ball.Increment.x := 0;
Ball.Increment.y := 0
end;
(* Some vector math. *)
function Add (const vA, vB: TPoint): TPoint; inline;
begin
Add.x := vA.x + vB.x;
Add.y := vA.y + vB.y
end;
function Subs (const vA, vB: TPoint): TPoint; inline;
begin
Subs.x := vA.x - vB.x;
Subs.y := vA.y - vB.y
end;
function Normalize (const aVector: TPoint): TPoint;
var
lLength: Real;
begin
lLength := sqrt (aVector.x * aVector.x + aVector.y * aVector.y);
if lLength <> 0 then
begin
Normalize.x := aVector.x / lLength;
Normalize.y := aVector.y / lLength
end
else
Normalize := aVector
end;
var
Cnt: Integer;
OldCount: LongWord;
begin
WriteLn ('Andante ', anVersionString);
WriteLn;
if not InitializeAndante then Halt;
{ Animation. }
CreateField;
Ball.Color := 31; Ball.cInc := -1;
repeat
OldCount := anTimerCounter;
{ Press space to create a new field. }
if anKeyState[anKeySpace] then
begin
CreateField;
anKeyState[anKeySpace] := False
end;
{ Atraction. }
for Cnt := Low (Atractors) to High (Atractors) do
Ball.Increment := Add (
Ball.Increment,
Normalize (Subs (Atractors[Cnt], Ball.Position))
);
{ Animate. }
Ball.Position := Add (Ball.Position, Ball.Increment);
Inc (Ball.Color, Ball.cInc); if (Ball.Color = 16) or (Ball.Color = 31) then
Ball.cInc := -1 * Ball.cInc;
{ Draw. }
anDrawPixel (
anScreen,
Trunc (Ball.Position.x), Trunc (Ball.Position.y),
Ball.Color
);
{ Whait... }
//repeat until anTimerCounter <> OldCount
until anKeyState[anKeyEscape]
end.
|
program uno;
const
corte = 'fin';
type
empleado = record
numero : integer;
nombre : String;
apellido : String;
edad : integer;
dni : String;
end;
archivoEmpleado = file of empleado;
procedure leerRegistro (var arc : archivoEmpleado; var reg : empleado);
begin
if (not eof(arc)) then
read(arc, reg)
else
reg.apellido := corte;
end;
procedure leerEmpleado (var unEmpleado : empleado);
begin
with unEmpleado do begin
writeln('Ingrese apellido: '); readln(apellido);
if (apellido <> corte) then begin
writeln('Ingrese nombre: '); readln(nombre);
writeln('Ingrese numero de empleado: '); readln(numero);
writeln('Ingrese edad: '); readln(edad);
writeln('Ingrese DNI: '); readln(dni);
end;
end;
end;
procedure cargarArchivo (var archivo : archivoEmpleado);
var
unEmpleado : empleado;
begin
rewrite(archivo);
leerEmpleado(unEmpleado);
while (unEmpleado.apellido <> corte) do begin
write(archivo,unEmpleado);
leerEmpleado(unEmpleado);
end;
close(archivo);
end;
procedure listarPorNombre (var archivo : archivoEmpleado; unNombre, unApellido : String);
var
unEmpleado : empleado;
begin
reset(archivo);
leerRegistro(archivo, unEmpleado);
while (unEmpleado.apellido <> corte) do begin
if ((unEmpleado.nombre = unNombre) or (unEmpleado.apellido = unApellido)) then
with unEmpleado do
writeln('Nombre: ',nombre,' Apellido: ',apellido,' Edad: ',edad,' DNI: ',dni,' Nro de empleado: ',numero);
leerRegistro(archivo, unEmpleado);
end;
close(archivo);
end;
procedure listarEmpleados (var archivo : archivoEmpleado);
var
unEmpleado : empleado;
begin
reset(archivo);
leerRegistro(archivo, unEmpleado);
while (unEmpleado.apellido <> corte) do begin
with unEmpleado do
writeln('Nombre: ',nombre,' Apellido: ',apellido,' Edad: ',edad,' DNI: ',dni,' Nro de empleado: ',numero);
leerRegistro(archivo, unEmpleado);
end;
close(archivo);
end;
procedure listarMayores (var archivo : archivoEmpleado);
var
unEmpleado : empleado;
begin
reset(archivo);
leerRegistro(archivo, unEmpleado);
while (unEmpleado.apellido <> corte) do begin
if (unEmpleado.edad > 70) then
with unEmpleado do
writeln('Nombre: ',nombre,' Apellido: ',apellido,' Edad: ',edad,' DNI: ',dni,' Nro de empleado: ',numero);
leerRegistro(archivo, unEmpleado);
end;
close(archivo);
end;
procedure agregarEmpleado (var archivo : archivoEmpleado);
var
unEmpleado : empleado;
begin
reset(archivo);
seek(archivo, filesize(archivo));
leerEmpleado(unEmpleado);
while (unEmpleado.apellido <> corte) do begin
write(archivo,unEmpleado);
leerEmpleado(unEmpleado);
end;
close(archivo);
end;
//el proceso modifica la edad del empleado cuyo numero de empleado se corresponde con una variable
procedure modificarEdad (var archivo : archivoEmpleado; unNumero : integer);
var
unEmpleado : empleado;
begin
reset(archivo);
while (not eof(archivo)) do begin
read(archivo,unEmpleado);
if (unEmpleado.numero = unNumero) then begin
writeln('Ingrese una nueva edad: '); readln(unEmpleado.edad);
seek(archivo,filepos(archivo) - 1);
write(archivo,unEmpleado);
end;
end;
close(archivo);
end;
procedure exportarContenido (var archivo : archivoEmpleado; var carga : Text);
var
unEmpleado : empleado;
begin
Rewrite(carga);
reset(archivo);
while (not eof(archivo)) do begin
read(archivo,unEmpleado);
with unEmpleado do begin
writeln('Nombre: ',nombre,' Apellido: ',apellido,' Edad: ',edad,' DNI: ',dni,' Nro de empleado: ',numero);
writeln(carga,' ',nombre,' ',apellido,' ',edad,' ',dni,' ',numero);
end;
end;
close(archivo); close(carga);
end;
procedure exportarEmpleadosSinDNI (var archivo : archivoEmpleado; var empleadosSinDNI : Text);
var
unEmpleado : empleado;
begin
reset(archivo);
rewrite(empleadosSinDNI);
while (not eof(archivo)) do begin
read(archivo,unEmpleado);
if (unEmpleado.dni = '00') then begin
with unEmpleado do begin
writeln('Nombre: ',nombre,' Apellido: ',apellido,' Edad: ',edad,' DNI: ',dni,' Nro de empleado: ',numero);
writeln(empleadosSinDNI,' ',nombre,' ',apellido,' ',edad,' ',dni,' ',numero);
end;
end;
end;
close(archivo); close(empleadosSinDNI);
end;
//El registro que quiero eliminar puede no estar en el archivo
procedure darBajaPorDNI (var archivo : archivoEmpleado);
var
unEmpleado : empleado;
dniEliminar : String;
pos : integer;
begin
reset(archivo);
writeln('Ingrese DNI a eliminar: '); readln(dniEliminar);
leerRegistro(archivo, unEmpleado);
while ((unEmpleado.apellido <> corte) and (unEmpleado.dni <> dniEliminar)) do
leerRegistro(archivo, unEmpleado);
if (unEmpleado.dni = dniEliminar) then begin
//guardo la posicion donde se encontro el registro a eliminar
pos := filepos(archivo) - 1;
//voy al ultimo registro
seek(archivo, filesize(archivo) - 1);
//leo el ultimo registro
read(archivo, unEmpleado);
//me paro en la posicion donde estaba el registro a eliminar y lo piso
seek(archivo, pos);
write(archivo, unEmpleado);
//trunco el archivo (desplazo la marca eof)
seek(archivo, filesize(archivo) - 1);
truncate(archivo);
end
else
writeln('No se encontro al DNI ',dniEliminar);
end;
procedure subMenu (var archivo : archivoEmpleado; var carga, empleadosSinDNI : Text);
var
op : char;
unNombre, unApellido : String;
unNumero : integer;
begin
writeln('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$');
writeln('Usted eligio la opcion 2');
writeln(' a.- Listar empleados por nombre/apellido determinados');
writeln(' b.- Listar empleados');
writeln(' c.- Listar empleados mayores de 70');
writeln(' d.- Añadir empleado/s');
writeln(' e.- Modificar edad');
writeln(' f.- Exportar el contenido del archivo a un .txt');
writeln(' g.- Exportar aquellos empleados cuyos dni sea 00 en un .txt');
writeln(' h.- Dar de baja registros');
writeln('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$');
readln(op);
case op of
'a' :begin
writeln('Ingrese un nombre');
readln(unNombre); readln(unApellido);
listarPorNombre(archivo,unNombre,unApellido);
end;
'b' :listarEmpleados(archivo);
'c' :listarMayores(archivo);
'd' :agregarEmpleado(archivo);
'e' :begin
writeln('Ingrese un numero de empleado: ');
readln(unNumero);
modificarEdad(archivo,unNumero);
end;
'f' :exportarContenido(archivo,carga);
'g' :exportarEmpleadosSinDNI(archivo,empleadosSinDNI);
'h' :darBajaPorDNI(archivo);
end;
end;
var
archivo : archivoEmpleado;
op : integer;
carga, empleadosSinDNI : Text;
begin
assign(archivo,'archivoEmpleados');
assign(carga,'todos_empleados');
assign(empleadosSinDNI,'faltaDNIEmpleado');
repeat
writeln('********************************************');
writeln('Menu de opciones: ');
writeln(' 0.- Salir del programa');
writeln(' 1.- Cargar el archivo');
writeln(' 2.- Abrir el archivo');
writeln('********************************************');
readln(op);
case op of
1 : cargarArchivo(archivo);
2 : subMenu(archivo,carga,empleadosSinDNI);
else
writeln('Saliendo.');
end;
until (op = 0);
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.EntityComponentSystem.RecordBased;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses {$ifdef Windows}Windows,{$endif}SysUtils,Classes,Math,Variants,TypInfo,
PasMP,
PUCU,
PasDblStrUtils,
PasJSON,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Base64,
PasVulkan.Collections,
PasVulkan.DataStructures.LinkedList,
PasVulkan.Value;
type TpvEntityComponentSystem=class
public
type ESystemCircularDependency=class(Exception);
ESystemSerialization=class(Exception);
ESystemUnserialization=class(Exception);
EDuplicateComponentInEntity=class(Exception);
PComponentID=^TComponentID;
TComponentID=type TpvSizeUInt;
TComponentIDDynamicArray=array of TComponentID;
TWorld=class;
TSystem=class;
TSystemList=class(TpvObjectGenericList<TSystem>)
end;
PEntityID=^TEntityID;
TEntityID=type TpvUInt32;
TEntityIDDynamicArray=array of TEntityID;
TEntityIDList=class(TpvGenericList<TEntityID>)
end;
TEntityIDHelper=record helper for TEntityID
private // first 24 bits then 8 bits, so that it is still sortable by entity index
const IndexBits=24; // when all these bits set, then => -1
GenerationBits=8;
IndexBitsMinusOne=TpvUInt32(IndexBits-1);
IndexSignBitMask=TpvUInt32(1 shl IndexBitsMinusOne);
IndexMask=TpvUInt32((TpvUInt32(1) shl IndexBits)-1);
GenerationMask=TpvUInt32((TpvUInt32(1) shl GenerationBits)-1);
function GetIndex:TpvInt32; inline;
procedure SetIndex(const aIndex:TpvInt32); inline;
function GetGeneration:TpvUInt8; inline;
procedure SetGeneration(const aGeneration:TpvUInt8); inline;
public
property Index:TpvInt32 read GetIndex write SetIndex;
property Generation:TpvUInt8 read GetGeneration write SetGeneration;
end;
PWorldID=^TWorldID;
TWorldID=type TpvInt32;
PEventID=^TEventID;
TEventID=type TpvInt32;
ERegisteredComponentType=class(Exception);
TRegisteredComponentType=class
public
type TPath=array of TpvUTF8String;
TField=record
public
type TElementType=
(
EntityID,
Enumeration,
Flags,
Boolean,
SignedInteger,
UnsignedInteger,
FloatingPoint,
LengthPrefixedString,
ZeroTerminatedString,
Blob
);
PElementType=^TElementType;
TEnumerationOrFlag=record
Value:TpvUInt64;
Name:TpvUTF8String;
DisplayName:TpvUTF8String;
constructor Create(const aValue:TpvUInt64;
const aName:TpvUTF8String;
const aDisplayName:TpvUTF8String);
end;
TEnumerationsOrFlags=array of TEnumerationOrFlag;
public
Name:TpvUTF8String;
DisplayName:TpvUTF8String;
ElementType:TElementType;
ElementSize:TpvSizeInt;
ElementCount:TpvSizeInt;
Offset:TpvSizeInt;
Size:TpvSizeInt;
EnumerationsOrFlags:TEnumerationsOrFlags;
end;
PField=^TField;
TFields=array of TField;
private
fID:TComponentID;
fName:TpvUTF8String;
fDisplayName:TpvUTF8String;
fPath:TPath;
fSize:TpvSizeInt;
fFields:TFields;
fCountFields:TpvSizeInt;
fDefault:TpvUInt8DynamicArray;
fEditorWidget:TpvPointer;
public
constructor Create(const aName:TpvUTF8String;
const aDisplayName:TpvUTF8String;
const aPath:array of TpvUTF8String;
const aSize:TpvSizeInt;
const aDefault:TpvPointer); reintroduce;
destructor Destroy; override;
class function GetSetOrdValue(const Info:PTypeInfo;const SetParam):TpvUInt64; static;
procedure Add(const aName:TpvUTF8String;
const aDisplayName:TpvUTF8String;
const aElementType:TField.TElementType;
const aElementSize:TpvSizeInt;
const aElementCount:TpvSizeInt;
const aOffset:TpvSizeInt;
const aSize:TpvSizeInt;
const aEnumerationsOrFlags:array of TField.TEnumerationOrFlag);
procedure Finish;
function SerializeToJSON(const aData:TpvPointer):TPasJSONItemObject;
procedure UnserializeFromJSON(const aJSON:TPasJSONItem;const aData:TpvPointer);
property Fields:TFields read fFields;
property EditorWidget:TpvPointer read fEditorWidget write fEditorWidget;
property Path:TPath read fPath;
published
property ID:TComponentID read fID;
property Size:TpvSizeInt read fSize;
property Default:TpvUInt8DynamicArray read fDefault;
end;
TRegisteredComponentTypeList=class(TpvObjectGenericList<TRegisteredComponentType>)
end;
TRegisteredComponentTypeNameHashMap=class(TpvStringHashMap<TRegisteredComponentType>)
end;
TComponentIDBitmap=array of TpvUInt32;
TComponent=class
public
type TIndexMapArray=array of TpvSizeInt;
TUsedBitmap=array of TpvUInt32;
TPointers=array of TpvPointer;
private
fWorld:TWorld;
fRegisteredComponentType:TRegisteredComponentType;
fComponentPoolIndexToEntityIndex:TIndexMapArray;
fEntityIndexToComponentPoolIndex:TIndexMapArray;
fUsedBitmap:TUsedBitmap;
fSize:TpvSizeInt;
fPoolUnaligned:TpvPointer;
fPool:TpvPointer;
fPoolSize:TpvSizeInt;
fCountPoolItems:TpvSizeInt;
fCapacity:TpvSizeInt;
fPoolIndexCounter:TpvSizeInt;
fMaxEntityIndex:TpvSizeInt;
fCountFrees:TpvSizeInt;
fNeedToDefragment:boolean;
fPointers:TPointers;
fDataPointer:TpvPointer;
procedure FinalizeComponentByPoolIndex(const aPoolIndex:TpvSizeInt);
function GetEntityIndexByPoolIndex(const aPoolIndex:TpvSizeInt):TpvSizeInt; inline;
function GetComponentByPoolIndex(const aPoolIndex:TpvSizeInt):TpvPointer; inline;
function GetComponentByEntityIndex(const aEntityIndex:TpvSizeInt):TpvPointer; inline;
procedure SetMaxEntities(const aCount:TpvSizeInt);
public
constructor Create(const aWorld:TWorld;const aRegisteredComponentType:TRegisteredComponentType); reintroduce;
destructor Destroy; override;
procedure Defragment;
procedure DefragmentIfNeeded;
function IsComponentInEntityIndex(const aEntityIndex:TpvSizeInt):boolean; inline;
function GetComponentPoolIndexForEntityIndex(const aEntityIndex:TpvSizeInt):TpvSizeInt; inline;
function AllocateComponentForEntityIndex(const aEntityIndex:TpvSizeInt):boolean;
function FreeComponentFromEntityIndex(const aEntityIndex:TpvSizeInt):boolean;
public
property Pool:TpvPointer read fPool;
property PoolSize:TpvSizeInt read fPoolSize;
property CountPoolItems:TpvSizeInt read fCountPoolItems;
property EntityIndexByPoolIndex[const aPoolIndex:TpvSizeInt]:TpvSizeInt read GetEntityIndexByPoolIndex;
property ComponentByPoolIndex[const aPoolIndex:TpvSizeInt]:pointer read GetComponentByPoolIndex;
property ComponentByEntityIndex[const aEntityIndex:TpvSizeInt]:pointer read GetComponentByEntityIndex;
property Pointers:TPointers read fPointers;
property DataPointer:pointer read fDataPointer;
published
property RegisteredComponentType:TRegisteredComponentType read fRegisteredComponentType;
end;
TComponentList=TpvObjectGenericList<TpvEntityComponentSystem.TComponent>;
TComponentIDList=class(TpvGenericList<TComponentID>)
end;
TEventParameter=TpvValue;
PEventParameter=^TEventParameter;
TEventParameters=array of TEventParameter;
PEventParameters=^TEventParameters;
TEvent=record
LinkedListHead:TpvLinkedListHead;
TimeStamp:TpvTime;
RemainingTime:TpvTime;
EventID:TEventID;
EntityID:TEntityID;
CountParameters:TpvInt32;
Parameters:TEventParameters;
end;
PEvent=^TEvent;
TEventHandler=procedure(const Event:TEvent) of object;
TEventHandlers=array of TEventHandler;
TEventRegistration=class
private
fEventID:TEventID;
fName:TpvUTF8String;
fActive:longbool;
fLock:TPasMPMultipleReaderSingleWriterLock;
fSystems:TSystemList;
fEventHandlers:TEventHandlers;
fCountEventHandlers:TpvInt32;
public
constructor Create(const aEventID:TEventID;const aName:TpvUTF8String);
destructor Destroy; override;
procedure Clear;
procedure AddSystem(const aSystem:TSystem);
procedure RemoveSystem(const aSystem:TSystem);
procedure AddEventHandler(const aEventHandler:TEventHandler);
procedure RemoveEventHandler(const aEventHandler:TEventHandler);
property EventID:TEventID read fEventID;
property Name:TpvUTF8String read fName;
property Active:longbool read fActive;
property Lock:TPasMPMultipleReaderSingleWriterLock read fLock;
property SystemList:TSystemList read fSystems;
property EventHandlers:TEventHandlers read fEventHandlers;
property CountEventHandlers:TpvInt32 read fCountEventHandlers;
end;
TEventRegistrationList=class(TpvObjectGenericList<TEventRegistration>)
end;
TSystemEvents=array of PEvent;
{ TEntity }
TEntity=record
public
type TEntityFlag=
(
Used,
Active,
Killed
);
TFlag=TEntityFlag;
TFlags=set of TFlag;
private
fWorld:TWorld;
fID:TEntityID;
fUUID:TpvUUID;
fFlags:TFlags;
fCountComponents:TpvInt32;
fComponentsBitmap:TComponentIDBitmap;
fUnknownData:TObject;
function GetActive:boolean; inline;
procedure SetActive(const aActive:boolean); inline;
procedure AddComponentToEntity(const aComponentID:TComponentID);
procedure RemoveComponentFromEntity(const aComponentID:TComponentID);
public
procedure SynchronizeToPrefab;
procedure Activate; inline;
procedure Deactivate; inline;
procedure Kill; inline;
procedure AddComponent(const aComponentID:TComponentID); inline;
procedure RemoveComponent(const aComponentID:TComponentID); inline;
function HasComponent(const aComponentID:TComponentID):boolean; inline;
function GetComponent(const aComponentID:TComponentID):TpvEntityComponentSystem.TComponent; inline;
public
property World:TWorld read fWorld write fWorld;
property ID:TEntityID read fID write fID;
property UUID:TpvUUID read fUUID write fUUID;
property Flags:TFlags read fFlags write fFlags;
property Active:boolean read GetActive write SetActive;
property Components[const aComponentID:TComponentID]:TpvEntityComponentSystem.TComponent read GetComponent;
end;
PEntity=^TEntity;
TEntities=array of TEntity;
{ TSystemChoreography }
TSystemChoreography=class
public
type TSystemChoreographyStepSystems=array of TSystem;
TSystemChoreographyStepJobs=array of PPasMPJob;
PSystemChoreographyStep=^TSystemChoreographyStep;
TSystemChoreographyStep=record
Systems:TSystemChoreographyStepSystems;
Jobs:TSystemChoreographyStepJobs;
Count:TpvInt32;
end;
TSystemChoreographySteps=array of TSystemChoreographyStep;
PSystemChoreographyStepProcessEventsJobData=^TSystemChoreographyStepProcessEventsJobData;
TSystemChoreographyStepProcessEventsJobData=record
ChoreographyStep:PSystemChoreographyStep;
end;
PSystemChoreographyStepUpdateEntitiesJobData=^TSystemChoreographyStepUpdateEntitiesJobData;
TSystemChoreographyStepUpdateEntitiesJobData=record
ChoreographyStep:PSystemChoreographyStep;
end;
private
fWorld:TWorld;
fPasMPInstance:TPasMP;
fChoreographySteps:TSystemChoreographySteps;
fChoreographyStepJobs:TSystemChoreographyStepJobs;
fCountChoreographySteps:TpvInt32;
fSortedSystemList:TSystemList;
function CreateProcessEventsJob(const aSystem:TSystem;const aFirstEventIndex,aLastEventIndex:TPasMPSizeInt;const aParentJob:PPasMPJob):PPasMPJob;
procedure ProcessEventsJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
procedure ChoreographyStepProcessEventsJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
procedure ChoreographyProcessEventsJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
function CreateUpdateEntitiesJob(const aSystem:TSystem;const aFirstEntityIndex,aLastEntityIndex:TPasMPSizeInt;const aParentJob:PPasMPJob):PPasMPJob;
procedure UpdateEntitiesJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
procedure ChoreographyStepUpdateEntitiesJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
procedure ChoreographyUpdateEntitiesJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
public
constructor Create(const aWorld:TWorld);
destructor Destroy; override;
procedure Build;
procedure ProcessEvents;
procedure InitializeUpdate;
procedure Update;
procedure FinalizeUpdate;
end;
{ TSystem }
TSystem=class
public
type TSystemFlag=
(
ParallelProcessing,
Secluded,
OwnUpdate
);
TFlag=TSystemFlag;
TFlags=set of TFlag;
private
fWorld:TWorld;
fFlags:TFlags;
fEntities:TEntityIDList;
fRequiredComponents:TComponentIDList;
fExcludedComponents:TComponentIDList;
fRequiresSystems:TSystemList;
fConflictsWithSystems:TSystemList;
fNeedToSort:boolean;
fEventsCanBeParallelProcessed:boolean;
fEventGranularity:TpvInt32;
fEntityGranularity:TpvInt32;
fCountEntities:TpvInt32;
fEvents:TSystemEvents;
fCountEvents:TpvInt32;
fDeltaTime:TpvTime;
protected
function HaveDependencyOnSystem(const aOtherSystem:TSystem):boolean;
function HaveDependencyOnSystemOrViceVersa(const aOtherSystem:TSystem):boolean;
function HaveCircularDependencyWithSystem(const aOtherSystem:TSystem):boolean;
function HaveConflictWithSystem(const aOtherSystem:TSystem):boolean;
function HaveConflictWithSystemOrViceVersa(const aOtherSystem:TSystem):boolean;
public
constructor Create(const aWorld:TWorld); virtual;
destructor Destroy; override;
procedure Added; virtual;
procedure Removed; virtual;
procedure SubscribeToEvent(const aEventID:TEventID);
procedure UnsubscribeFromEvent(const aEventID:TEventID);
procedure RequiresSystem(const aSystem:TSystem);
procedure ConflictsWithSystem(const aSystem:TSystem);
procedure AddRequiredComponent(const aComponentID:TComponentID);
procedure AddExcludedComponent(const aComponentID:TComponentID);
function FitsEntityToSystem(const aEntityID:TEntityID):boolean; virtual;
function AddEntityToSystem(const aEntityID:TEntityID):boolean; virtual;
function RemoveEntityFromSystem(const aEntityID:TEntityID):boolean; virtual;
procedure SortEntities; virtual;
procedure Finish; virtual;
procedure ProcessEvent(const aEvent:TEvent); virtual;
procedure ProcessEvents(const aFirstEventIndex,aLastEventIndex:TpvSizeInt); virtual;
procedure InitializeUpdate; virtual;
procedure Update; virtual;
procedure UpdateEntities(const aFirstEntityIndex,aLastEntityIndex:TpvSizeInt); virtual;
procedure FinalizeUpdate; virtual;
property World:TWorld read fWorld;
property Flags:TFlags read fFlags write fFlags;
property Entities:TEntityIDList read fEntities;
property CountEntities:TpvInt32 read fCountEntities;
property EventsCanBeParallelProcessed:boolean read fEventsCanBeParallelProcessed write fEventsCanBeParallelProcessed;
property EventGranularity:TpvInt32 read fEventGranularity write fEventGranularity;
property EntityGranularity:TpvInt32 read fEntityGranularity write fEntityGranularity;
property Events:TSystemEvents read fEvents;
property CountEvents:TpvInt32 read fCountEvents;
property DeltaTime:TpvTime read fDeltaTime;
end;
TDelayedManagementEventType=(
None,
CreateEntity,
ActivateEntity,
DeactivateEntity,
KillEntity,
AddComponentToEntity,
RemoveComponentFromEntity,
AddSystem,
RemoveSystem,
SortSystem
);
PDelayedManagementEventType=^TDelayedManagementEventType;
TDelayedManagementEventData=array of TpvUInt8;
TDelayedManagementEvent=record
EventType:TDelayedManagementEventType;
EntityID:TEntityID;
ComponentID:TComponentID;
System:TSystem;
UUID:TpvUUID;
Data:TDelayedManagementEventData;
DataSize:TpvInt32;
DataString:TpvRawByteString;
end;
PDelayedManagementEvent=^TDelayedManagementEvent;
TDelayedManagementEvents=array of TDelayedManagementEvent;
TDelayedManagementEventQueue=TpvDynamicQueue<TDelayedManagementEvent>;
TWorld=class
public
type TEntityIndexFreeList=TpvGenericList<TpvSizeInt>;
TEntityGenerationList=array of TpvUInt8;
TUsedBitmap=array of TpvUInt32;
TOnEvent=procedure(const aWorld:TWorld;const aEvent:TEvent) of object;
TEventRegistrationStringIntegerPairHashMap=class(TpvStringHashMap<TpvSizeInt>);
TUUIDEntityIDPairHashMap=class(TpvHashMap<TpvUUID,TpvEntityComponentSystem.TEntityID>);
TSystemBooleanPairHashMap=class(TpvHashMap<TpvEntityComponentSystem.TSystem,longbool>);
private
fUUID:TpvUUID;
fActive:longbool;
fPasMPInstance:TPasMP;
fLock:TPasMPMultipleReaderSingleWriterLock;
fComponents:TComponentList;
fEntities:TEntities;
fSystems:TSystemList;
fSystemUsedMap:TSystemBooleanPairHashMap;
fSystemChoreography:TSystemChoreography;
fSystemChoreographyNeedToRebuild:TPasMPInt32;
fEntityLock:TPasMPMultipleReaderSingleWriterLock;
fEntityIndexFreeList:TEntityIndexFreeList;
fEntityGenerationList:TEntityGenerationList;
fEntityUsedBitmap:TUsedBitmap;
fEntityIndexCounter:TpvSizeInt;
fMaxEntityIndex:TpvSizeInt;
fEntityUUIDHashMap:TUUIDEntityIDPairHashMap;
fReservedEntityHashMapLock:TPasMPMultipleReaderSingleWriterLock;
fReservedEntityUUIDHashMap:TUUIDEntityIDPairHashMap;
fEventInProcessing:longbool;
fEventRegistrationLock:TPasMPMultipleReaderSingleWriterLock;
fEventRegistrationList:TEventRegistrationList;
fFreeEventRegistrationList:TEventRegistrationList;
fEventRegistrationStringIntegerPairHashMap:TEventRegistrationStringIntegerPairHashMap;
fOnEvent:TOnEvent;
fEventListLock:TPasMPMultipleReaderSingleWriterLock;
fEventList:TList;
fDelayedEventQueueLock:TPasMPMultipleReaderSingleWriterLock;
fDelayedEventQueue:TpvLinkedListHead;
fEventQueueLock:TPasMPMultipleReaderSingleWriterLock;
fEventQueue:TpvLinkedListHead;
fDelayedFreeEventQueue:TpvLinkedListHead;
fFreeEventQueueLock:TPasMPMultipleReaderSingleWriterLock;
fFreeEventQueue:TpvLinkedListHead;
fCurrentTime:TpvTime;
fDelayedManagementEventLock:TPasMPMultipleReaderSingleWriterLock;
fDelayedManagementEvents:TDelayedManagementEvents;
fCountDelayedManagementEvents:TpvSizeInt;
procedure AddDelayedManagementEvent(const aDelayedManagementEvent:TDelayedManagementEvent);
function GetEntityByID(const aEntityID:TEntityID):PEntity;
function GetEntityByUUID(const aEntityUUID:TpvUUID):PEntity;
function DoCreateEntity(const aEntityID:TEntityID;const aEntityUUID:TpvUUID):boolean;
function DoDestroyEntity(const aEntityID:TEntityID):boolean;
procedure ProcessEvent(const aEvent:PEvent);
procedure ProcessEvents;
procedure ProcessDelayedEvents(const aDeltaTime:TTime);
function CreateEntity(const aEntityID:TEntityID;const aEntityUUID:TpvUUID):TEntityID; overload;
public
constructor Create(const aPasMPInstance:TPasMP=nil); reintroduce;
destructor Destroy; override;
procedure Kill;
function CreateEvent(const aName:TpvUTF8String):TEventID;
procedure DestroyEvent(const aEventID:TEventID);
function FindEvent(const aName:TpvUTF8String):TEventID;
procedure SubscribeToEvent(const aEventID:TEventID;const aEventHandler:TEventHandler);
procedure UnsubscribeFromEvent(const aEventID:TEventID;const aEventHandler:TEventHandler);
function CreateEntity(const aEntityUUID:TpvUUID):TEntityID; overload;
function CreateEntity:TEntityID; overload;
function HasEntity(const aEntityID:TEntityID):boolean; {$ifdef caninline}inline;{$endif}
function IsEntityActive(const aEntityID:TEntityID):boolean; {$ifdef caninline}inline;{$endif}
procedure ActivateEntity(const aEntityID:TEntityID); {$ifdef caninline}inline;{$endif}
procedure DeactivateEntity(const aEntityID:TEntityID); {$ifdef caninline}inline;{$endif}
procedure KillEntity(const aEntityID:TEntityID); {$ifdef caninline}inline;{$endif}
procedure AddComponentToEntity(const aEntityID:TEntityID;const aComponentID:TComponentID);
procedure RemoveComponentFromEntity(const aEntityID:TEntityID;const aComponentID:TComponentID);
function HasEntityComponent(const aEntityID:TEntityID;const aComponentID:TComponentID):boolean;
procedure AddSystem(const aSystem:TSystem);
procedure RemoveSystem(const aSystem:TSystem);
procedure SortSystem(const aSystem:TSystem);
procedure Defragment;
procedure Refresh;
procedure QueueEvent(const aEventToQueue:TEvent;const aDeltaTime:TpvTime); overload;
procedure QueueEvent(const aEventToQueue:TEvent); overload;
procedure Update(const aDeltaTime:TpvTime);
procedure Clear;
procedure ClearEntities;
procedure Activate;
procedure Deactivate;
procedure MementoSerialize(const aStream:TStream);
procedure MementoUnserialize(const aStream:TStream);
public
property UUID:TpvUUID read fUUID write fUUID;
property Active:longbool read fActive write fActive;
property Components:TComponentList read fComponents;
property CurrentTime:TpvTime read fCurrentTime;
property OnEvent:TOnEvent read fOnEvent write fOnEvent;
end;
end;
var RegisteredComponentTypeList:TpvEntityComponentSystem.TRegisteredComponentTypeList=nil;
RegisteredComponentTypeNameHashMap:TpvEntityComponentSystem.TRegisteredComponentTypeNameHashMap=nil;
procedure InitializeEntityComponentSystemGlobals;
implementation
uses PasVulkan.Components.Name,
PasVulkan.Components.Parent,
PasVulkan.Components.Renderer,
PasVulkan.Components.SortKey,
PasVulkan.Components.Transform;
{ TpvEntityComponentSystem.TpvEntityIDHelper }
function TpvEntityComponentSystem.TEntityIDHelper.GetIndex:TpvInt32;
begin
result:=(self shr GenerationBits) and IndexMask;
result:=result or (-(ord(result=IndexMask) and 1));
end;
procedure TpvEntityComponentSystem.TEntityIDHelper.SetIndex(const aIndex:TpvInt32);
begin
self:=(self and GenerationMask) or ((TpvUInt32(aIndex) and IndexMask) shl GenerationBits);
end;
function TpvEntityComponentSystem.TEntityIDHelper.GetGeneration:TpvUInt8;
begin
result:=self and GenerationMask;
end;
procedure TpvEntityComponentSystem.TEntityIDHelper.SetGeneration(const aGeneration:TpvUInt8);
begin
self:=(self and not GenerationMask) or (aGeneration and GenerationMask);
end;
{ TpvEntityComponentSystem.TpvRegisteredComponentType.TField.TEnumerationOrFlag }
constructor TpvEntityComponentSystem.TRegisteredComponentType.TField.TEnumerationOrFlag.Create(const aValue:TpvUInt64;
const aName:TpvUTF8String;
const aDisplayName:TpvUTF8String);
begin
Value:=aValue;
Name:=aName;
DisplayName:=aDisplayName;
end;
{ TpvEntityComponentSystem.TRegisteredComponent }
constructor TpvEntityComponentSystem.TRegisteredComponentType.Create(const aName:TpvUTF8String;
const aDisplayName:TpvUTF8String;
const aPath:array of TpvUTF8String;
const aSize:TpvSizeInt;
const aDefault:TpvPointer);
var Index:TpvSizeInt;
begin
inherited Create;
InitializeEntityComponentSystemGlobals;
fID:=RegisteredComponentTypeList.Add(self);
RegisteredComponentTypeNameHashMap.Add(aName,self);
fName:=aName;
fDisplayName:=aDisplayName;
SetLength(fPath,length(aPath));
for Index:=0 to length(aPath)-1 do begin
fPath[Index]:=aPath[Index];
end;
fSize:=aSize;
fFields:=nil;
fCountFields:=0;
fEditorWidget:=nil;
SetLength(fDefault,fSize);
if assigned(aDefault) then begin
Move(aDefault^,fDefault[0],fSize);
end else begin
FillChar(fDefault[0],fSize,#0);
end;
end;
destructor TpvEntityComponentSystem.TRegisteredComponentType.Destroy;
begin
fFields:=nil;
fDefault:=nil;
inherited Destroy;
end;
class function TpvEntityComponentSystem.TRegisteredComponentType.GetSetOrdValue(const Info:PTypeInfo;const SetParam):TpvUInt64;
begin
result:=0;
case GetTypeData(Info)^.OrdType of
otSByte,otUByte:begin
result:=TpvUInt8(SetParam);
end;
otSWord,otUWord:begin
result:=TpvUInt16(SetParam);
end;
otSLong,otULong:begin
result:=TpvUInt32(SetParam);
end;
end;
end;
procedure TpvEntityComponentSystem.TRegisteredComponentType.Add(const aName:TpvUTF8String;
const aDisplayName:TpvUTF8String;
const aElementType:TField.TElementType;
const aElementSize:TpvSizeInt;
const aElementCount:TpvSizeInt;
const aOffset:TpvSizeInt;
const aSize:TpvSizeInt;
const aEnumerationsOrFlags:array of TField.TEnumerationOrFlag);
var Index:TpvSizeInt;
Field:TRegisteredComponentType.PField;
begin
Index:=fCountFields;
inc(fCountFields);
if length(fFields)<fCountFields then begin
SetLength(fFields,fCountFields+((fCountFields+1) shr 1));
end;
Field:=@fFields[Index];
Field^.Name:=aName;
Field^.DisplayName:=aDisplayName;
Field^.ElementType:=aElementType;
Field^.Offset:=aOffset;
Field^.ElementSize:=aElementSize;
Field^.ElementCount:=aElementCount;
Field^.Size:=aSize;
SetLength(Field^.EnumerationsOrFlags,length(aEnumerationsOrFlags));
for Index:=0 to length(aEnumerationsOrFlags)-1 do begin
Field^.EnumerationsOrFlags[Index]:=aEnumerationsOrFlags[Index];
end;
end;
procedure TpvEntityComponentSystem.TRegisteredComponentType.Finish;
begin
SetLength(fFields,fCountFields);
end;
function TpvEntityComponentSystem.TRegisteredComponentType.SerializeToJSON(const aData:TpvPointer):TPasJSONItemObject;
function GetElementValue(const aField:PField;
const aValueData:TpvPointer):TPasJSONItem;
var Data:TpvPointer;
EnumerationFlagIndex:TpvSizeInt;
SignedInteger:TpvInt64;
UnsignedInteger:TpvUInt64;
FloatValue:TpvDouble;
StringValue:TpvUTF8String;
begin
result:=nil;
Data:=aValueData;
case aField^.ElementType of
TRegisteredComponentType.TField.TElementType.EntityID:begin
case aField^.ElementSize of
1:begin
UnsignedInteger:=PpvUInt8(Data)^;
end;
2:begin
UnsignedInteger:=PpvUInt16(Data)^;
end;
4:begin
UnsignedInteger:=PpvUInt32(Data)^;
end;
8:begin
UnsignedInteger:=PpvUInt64(Data)^;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-04-23-58-0000');
end;
end;
if UnsignedInteger<TpvUInt64($0010000000000000) then begin
result:=TPasJSONItemNumber.Create(UnsignedInteger);
end else begin
result:=TPasJSONItemString.Create(IntToStr(UnsignedInteger));
end;
end;
TRegisteredComponentType.TField.TElementType.Enumeration:begin
case aField^.ElementSize of
1:begin
UnsignedInteger:=PpvUInt8(Data)^;
end;
2:begin
UnsignedInteger:=PpvUInt16(Data)^;
end;
4:begin
UnsignedInteger:=PpvUInt32(Data)^;
end;
8:begin
UnsignedInteger:=PpvUInt64(Data)^;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-04-23-36-0000');
end;
end;
EnumerationFlagIndex:=0;
while EnumerationFlagIndex<length(aField^.EnumerationsOrFlags) do begin
if aField^.EnumerationsOrFlags[EnumerationFlagIndex].Value=UnsignedInteger then begin
result:=TPasJSONItemString.Create(aField^.EnumerationsOrFlags[EnumerationFlagIndex].Name);
break;
end;
inc(EnumerationFlagIndex);
end;
if EnumerationFlagIndex>=length(aField^.EnumerationsOrFlags) then begin
result:=TPasJSONItemString.Create('');
end;
end;
TRegisteredComponentType.TField.TElementType.Flags:begin
case aField^.ElementSize of
1:begin
UnsignedInteger:=PpvUInt8(Data)^;
end;
2:begin
UnsignedInteger:=PpvUInt16(Data)^;
end;
4:begin
UnsignedInteger:=PpvUInt32(Data)^;
end;
8:begin
UnsignedInteger:=PpvUInt64(Data)^;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-04-23-36-0000');
end;
end;
result:=TPasJSONItemArray.Create;
for EnumerationFlagIndex:=0 to length(aField^.EnumerationsOrFlags)-1 do begin
if (aField^.EnumerationsOrFlags[EnumerationFlagIndex].Value and UnsignedInteger)<>0 then begin
TPasJSONItemArray(result).Add(TPasJSONItemString.Create(aField^.EnumerationsOrFlags[EnumerationFlagIndex].Name));
end;
end;
end;
TRegisteredComponentType.TField.TElementType.Boolean:begin
case aField^.ElementSize of
1:begin
UnsignedInteger:=PpvUInt8(Data)^;
end;
2:begin
UnsignedInteger:=PpvUInt16(Data)^;
end;
4:begin
UnsignedInteger:=PpvUInt32(Data)^;
end;
8:begin
UnsignedInteger:=PpvUInt64(Data)^;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-00-25-0000');
end;
end;
result:=TPasJSONItemBoolean.Create(UnsignedInteger<>0);
end;
TRegisteredComponentType.TField.TElementType.SignedInteger:begin
case aField^.ElementSize of
1:begin
SignedInteger:=PpvInt8(Data)^;
end;
2:begin
SignedInteger:=PpvInt16(Data)^;
end;
4:begin
SignedInteger:=PpvInt32(Data)^;
end;
8:begin
SignedInteger:=PpvInt64(Data)^;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-00-15-0001');
end;
end;
if abs(SignedInteger)<TpvUInt64($0010000000000000) then begin
result:=TPasJSONItemNumber.Create(SignedInteger);
end else begin
result:=TPasJSONItemString.Create(IntToStr(SignedInteger));
end;
end;
TRegisteredComponentType.TField.TElementType.UnsignedInteger:begin
case aField^.ElementSize of
1:begin
UnsignedInteger:=PpvUInt8(Data)^;
end;
2:begin
UnsignedInteger:=PpvUInt16(Data)^;
end;
4:begin
UnsignedInteger:=PpvUInt32(Data)^;
end;
8:begin
UnsignedInteger:=PpvUInt64(Data)^;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-00-15-0000');
end;
end;
if UnsignedInteger<TpvUInt64($0010000000000000) then begin
result:=TPasJSONItemNumber.Create(UnsignedInteger);
end else begin
result:=TPasJSONItemString.Create(IntToStr(UnsignedInteger));
end;
end;
TRegisteredComponentType.TField.TElementType.FloatingPoint:begin
case aField^.ElementSize of
2:begin
FloatValue:=PpvHalfFloat(Data)^.ToFloat;
end;
4:begin
FloatValue:=PpvFloat(Data)^;
end;
8:begin
FloatValue:=PpvDouble(Data)^;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-00-22-0000');
end;
end;
result:=TPasJSONItemNumber.Create(FloatValue);
end;
TRegisteredComponentType.TField.TElementType.LengthPrefixedString:begin
UnsignedInteger:=PpvUInt8(Data)^;
StringValue:='';
if UnsignedInteger>0 then begin
SetLength(StringValue,UnsignedInteger);
Move(PAnsiChar(Data)[1],StringValue[1],UnsignedInteger);
end;
result:=TPasJSONItemString.Create(StringValue);
end;
TRegisteredComponentType.TField.TElementType.ZeroTerminatedString:begin
StringValue:=PAnsiChar(Data);
result:=TPasJSONItemString.Create(StringValue);
end;
TRegisteredComponentType.TField.TElementType.Blob:begin
result:=TPasJSONItemString.Create(TpvBase64.Encode(Data^,aField^.ElementSize));
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-00-11-0000');
end;
end;
end;
function GetFieldValue(const aField:PField;
const aData:TpvPointer):TPasJSONItem;
var ElementIndex:TpvSizeInt;
begin
if aField^.ElementCount>1 then begin
result:=TPasJSONItemArray.Create;
for ElementIndex:=0 to aField^.ElementCount-1 do begin
TPasJSONItemArray(result).Add(GetElementValue(aField,@PpvUInt8Array(aData)^[aField^.Offset+(ElementIndex*aField^.ElementSize)]));
end;
end else begin
result:=GetElementValue(aField,@PpvUInt8Array(aData)^[aField^.Offset]);
end;
end;
var FieldIndex:TpvSizeInt;
Field:PField;
begin
result:=TPasJSONItemObject.Create;
try
for FieldIndex:=0 to fCountFields-1 do begin
Field:=@fFields[FieldIndex];
result.Add(Field^.Name,GetFieldValue(Field,aData));
end;
except
FreeAndNil(result);
raise;
end;
end;
procedure TpvEntityComponentSystem.TRegisteredComponentType.UnserializeFromJSON(const aJSON:TPasJSONItem;const aData:TpvPointer);
procedure SetField(const aField:PField;
const aData:TpvPointer;
const aJSONItemValue:TPasJSONItem);
var EnumerationFlagIndex,ArrayItemIndex:TpvSizeInt;
Code:TpvInt32;
ArrayJSONItemValue:TPasJSONItem;
SignedInteger:TpvInt64;
UnsignedInteger:TpvUInt64;
FloatValue:TpvDouble;
StringValue:TpvUTF8String;
Stream:TMemoryStream;
begin
case aField^.ElementType of
TRegisteredComponentType.TField.TElementType.EntityID:begin
if aJSONItemValue is TPasJSONItemNumber then begin
UnsignedInteger:=trunc(TPasJSONItemNumber(aJSONItemValue).Value);
end else if aJSONItemValue is TPasJSONItemString then begin
UnsignedInteger:=StrToIntDef(TPasJSONItemString(aJSONItemValue).Value,0);
end else if aJSONItemValue is TPasJSONItemBoolean then begin
UnsignedInteger:=ord(TPasJSONItemBoolean(aJSONItemValue).Value) and 1;
end else begin
UnsignedInteger:=$ffffffff;
end;
case aField^.ElementSize of
1:begin
PpvUInt8(aData)^:=UnsignedInteger;
end;
2:begin
PpvUInt16(aData)^:=UnsignedInteger;
end;
4:begin
PpvUInt32(aData)^:=UnsignedInteger;
end;
8:begin
PpvUInt64(aData)^:=UnsignedInteger;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-01-24-0000');
end;
end;
end;
TRegisteredComponentType.TField.TElementType.Enumeration:begin
if aJSONItemValue is TPasJSONItemString then begin
StringValue:=TPasJSONItemString(aJSONItemValue).Value;
end else begin
StringValue:='';
end;
UnsignedInteger:=0;
for EnumerationFlagIndex:=0 to length(aField^.EnumerationsOrFlags)-1 do begin
if aField^.EnumerationsOrFlags[EnumerationFlagIndex].Name=StringValue then begin
UnsignedInteger:=aField^.EnumerationsOrFlags[EnumerationFlagIndex].Value;
break;
end;
end;
case aField^.ElementSize of
1:begin
PpvUInt8(aData)^:=UnsignedInteger;
end;
2:begin
PpvUInt16(aData)^:=UnsignedInteger;
end;
4:begin
PpvUInt32(aData)^:=UnsignedInteger;
end;
8:begin
PpvUInt64(aData)^:=UnsignedInteger;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-01-29-0000');
end;
end;
end;
TRegisteredComponentType.TField.TElementType.Flags:begin
UnsignedInteger:=0;
if aJSONItemValue is TPasJSONItemArray then begin
for ArrayItemIndex:=0 to TPasJSONItemArray(aJSONItemValue).Count-1 do begin
ArrayJSONItemValue:=TPasJSONItemArray(aJSONItemValue).Items[ArrayItemIndex];
if assigned(ArrayJSONItemValue) then begin
if ArrayJSONItemValue is TPasJSONItemString then begin
StringValue:=TPasJSONItemString(ArrayJSONItemValue).Value;
end else begin
StringValue:='';
end;
for EnumerationFlagIndex:=0 to length(aField^.EnumerationsOrFlags)-1 do begin
if aField^.EnumerationsOrFlags[EnumerationFlagIndex].Name=StringValue then begin
UnsignedInteger:=UnsignedInteger or aField^.EnumerationsOrFlags[EnumerationFlagIndex].Value;
end;
end;
end;
end;
end;
case aField^.ElementSize of
1:begin
PpvUInt8(aData)^:=UnsignedInteger;
end;
2:begin
PpvUInt16(aData)^:=UnsignedInteger;
end;
4:begin
PpvUInt32(aData)^:=UnsignedInteger;
end;
8:begin
PpvUInt64(aData)^:=UnsignedInteger;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-01-33-0000');
end;
end;
end;
TRegisteredComponentType.TField.TElementType.Boolean:begin
if aJSONItemValue is TPasJSONItemNumber then begin
UnsignedInteger:=trunc(TPasJSONItemNumber(aJSONItemValue).Value) and 1;
end else if aJSONItemValue is TPasJSONItemString then begin
UnsignedInteger:=StrToIntDef(TPasJSONItemString(aJSONItemValue).Value,0) and 1;
end else if aJSONItemValue is TPasJSONItemBoolean then begin
UnsignedInteger:=ord(TPasJSONItemBoolean(aJSONItemValue).Value) and 1;
end else begin
UnsignedInteger:=0;
end;
case aField^.ElementSize of
1:begin
PpvUInt8(aData)^:=UnsignedInteger;
end;
2:begin
PpvUInt16(aData)^:=UnsignedInteger;
end;
4:begin
PpvUInt32(aData)^:=UnsignedInteger;
end;
8:begin
PpvUInt64(aData)^:=UnsignedInteger;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-01-37-0000');
end;
end;
end;
TRegisteredComponentType.TField.TElementType.SignedInteger:begin
if aJSONItemValue is TPasJSONItemNumber then begin
SignedInteger:=trunc(TPasJSONItemNumber(aJSONItemValue).Value);
end else if aJSONItemValue is TPasJSONItemString then begin
SignedInteger:=StrToIntDef(TPasJSONItemString(aJSONItemValue).Value,0);
end else if aJSONItemValue is TPasJSONItemBoolean then begin
SignedInteger:=ord(TPasJSONItemBoolean(aJSONItemValue).Value) and 1;
end else begin
SignedInteger:=0;
end;
case aField^.ElementSize of
1:begin
PpvInt8(aData)^:=SignedInteger;
end;
2:begin
PpvInt16(aData)^:=SignedInteger;
end;
4:begin
PpvInt32(aData)^:=SignedInteger;
end;
8:begin
PpvInt64(aData)^:=SignedInteger;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-01-38-0000');
end;
end;
end;
TRegisteredComponentType.TField.TElementType.UnsignedInteger:begin
if aJSONItemValue is TPasJSONItemNumber then begin
UnsignedInteger:=trunc(TPasJSONItemNumber(aJSONItemValue).Value);
end else if aJSONItemValue is TPasJSONItemString then begin
UnsignedInteger:=StrToIntDef(TPasJSONItemString(aJSONItemValue).Value,0);
end else if aJSONItemValue is TPasJSONItemBoolean then begin
UnsignedInteger:=ord(TPasJSONItemBoolean(aJSONItemValue).Value) and 1;
end else begin
UnsignedInteger:=0;
end;
case aField^.ElementSize of
1:begin
PpvUInt8(aData)^:=UnsignedInteger;
end;
2:begin
PpvUInt16(aData)^:=UnsignedInteger;
end;
4:begin
PpvUInt32(aData)^:=UnsignedInteger;
end;
8:begin
PpvUInt64(aData)^:=UnsignedInteger;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-01-38-0001');
end;
end;
end;
TRegisteredComponentType.TField.TElementType.FloatingPoint:begin
if aJSONItemValue is TPasJSONItemNumber then begin
FloatValue:=TPasJSONItemNumber(aJSONItemValue).Value;
end else if aJSONItemValue is TPasJSONItemString then begin
FloatValue:=0.0;
Val(TPasJSONItemString(aJSONItemValue).Value,FloatValue,Code);
if Code<>0 then begin
end;
end else if aJSONItemValue is TPasJSONItemBoolean then begin
FloatValue:=ord(TPasJSONItemBoolean(aJSONItemValue).Value) and 1;
end else begin
FloatValue:=0.0;
end;
case aField^.ElementSize of
2:begin
PpvHalfFloat(aData)^:=FloatValue;
end;
4:begin
PpvFloat(aData)^:=FloatValue;
end;
8:begin
PpvDouble(aData)^:=FloatValue;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-01-38-0002');
end;
end;
end;
TRegisteredComponentType.TField.TElementType.LengthPrefixedString:begin
if aJSONItemValue is TPasJSONItemString then begin
StringValue:=TPasJSONItemString(aJSONItemValue).Value;
end else begin
StringValue:='';
end;
if length(StringValue)>(aField^.ElementSize-1) then begin
SetLength(StringValue,aField^.ElementSize-1);
end;
PpvUInt8(aData)^:=length(StringValue);
if length(StringValue)>0 then begin
Move(StringValue[1],PAnsiChar(aData)[1],length(StringValue));
end;
end;
TRegisteredComponentType.TField.TElementType.ZeroTerminatedString:begin
if aJSONItemValue is TPasJSONItemString then begin
StringValue:=TPasJSONItemString(aJSONItemValue).Value;
end else begin
StringValue:='';
end;
if length(StringValue)>(aField^.ElementSize-1) then begin
SetLength(StringValue,aField^.ElementSize-1);
end;
if length(StringValue)>0 then begin
Move(StringValue[1],PAnsiChar(aData)[0],length(StringValue));
end;
PAnsiChar(aData)[length(StringValue)]:=#0;
end;
TRegisteredComponentType.TField.TElementType.Blob:begin
if aJSONItemValue is TPasJSONItemString then begin
StringValue:=TPasJSONItemString(aJSONItemValue).Value;
end else begin
StringValue:='';
end;
Stream:=TMemoryStream.Create;
try
if TpvBase64.Decode(TpvRawByteString(StringValue),Stream) then begin
FillChar(aData^,Min(Stream.Size,aField^.ElementSize),#0);
if Stream.Size>0 then begin
Move(Stream.Memory^,aData^,Min(Stream.Size,aField^.ElementSize));
end;
end else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-00-53-0001');
end;
finally
FreeAndNil(Stream);
end;
end;
else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-00-53-0000');
end;
end;
end;
var FieldIndex,ElementIndex:TpvSizeInt;
Field:PField;
Data:TpvPointer;
JSONItemObject:TPasJSONItemObject;
ValueJSONItem:TPasJSONItem;
ValueJSONItemArray:TPasJSONItemArray;
begin
if assigned(aJSON) and (aJSON is TPasJSONItemObject) then begin
JSONItemObject:=TPasJSONItemObject(aJSON);
for FieldIndex:=0 to fCountFields-1 do begin
Field:=@fFields[FieldIndex];
Data:=@PpvUInt8Array(aData)^[Field^.Offset];
ValueJSONItem:=JSONItemObject.Properties[Field^.Name];
if assigned(ValueJSONItem) then begin
if Field^.ElementCount>1 then begin
if ValueJSONItem is TPasJSONItemArray then begin
ValueJSONItemArray:=TPasJSONItemArray(ValueJSONItem);
end else begin
ValueJSONItemArray:=TPasJSONItemArray.Create;
ValueJSONItemArray.Add(ValueJSONItem);
end;
try
for ElementIndex:=0 to Min(Field^.ElementCount,ValueJSONItemArray.Count)-1 do begin
SetField(Field,@PpvUInt8Array(Data)^[ElementIndex*Field^.ElementSize],ValueJSONItemArray.Items[ElementIndex]);
end;
for ElementIndex:=ValueJSONItemArray.Count to Field^.ElementCount-1 do begin
FillChar(PpvUInt8Array(Data)^[ElementIndex*Field^.ElementSize],Field^.ElementSize,#0);
end;
finally
if ValueJSONItemArray<>ValueJSONItem then begin
FreeAndNil(ValueJSONItemArray);
end;
end;
end else begin
SetField(Field,Data,ValueJSONItem);
end;
end else begin
if Field^.ElementType=TRegisteredComponentType.TField.TElementType.EntityID then begin
FillChar(Data^,Field^.Size,#$ff);
end else begin
FillChar(Data^,Field^.Size,#0);
end;
end;
end;
end else begin
raise ERegisteredComponentType.Create('Internal error 2018-09-05-01-08-0000');
end;
end;
{ TpvEntityComponentSystem.TComponent }
constructor TpvEntityComponentSystem.TComponent.Create(const aWorld:TWorld;const aRegisteredComponentType:TRegisteredComponentType);
begin
inherited Create;
fWorld:=aWorld;
fRegisteredComponentType:=aRegisteredComponentType;
fSize:=fRegisteredComponentType.fSize;
fPoolUnaligned:=nil;
fPool:=nil;
fPoolSize:=0;
fCountPoolItems:=0;
fCapacity:=0;
fPoolIndexCounter:=0;
fMaxEntityIndex:=-1;
fCountFrees:=0;
fNeedToDefragment:=false;
fEntityIndexToComponentPoolIndex:=nil;
fComponentPoolIndexToEntityIndex:=nil;
fPointers:=nil;
fDataPointer:=nil;
fUsedBitmap:=nil;
end;
destructor TpvEntityComponentSystem.TComponent.Destroy;
begin
if assigned(fPoolUnaligned) then begin
FreeMem(fPoolUnaligned);
end;
fPointers:=nil;
fEntityIndexToComponentPoolIndex:=nil;
fComponentPoolIndexToEntityIndex:=nil;
fPointers:=nil;
fUsedBitmap:=nil;
inherited Destroy;
end;
procedure TpvEntityComponentSystem.TComponent.FinalizeComponentByPoolIndex(const aPoolIndex:TpvSizeInt);
begin
end;
procedure TpvEntityComponentSystem.TComponent.SetMaxEntities(const aCount:TpvSizeInt);
var OldCount:TpvSizeInt;
begin
OldCount:=length(fPointers);
if OldCount<aCount then begin
SetLength(fPointers,aCount+((aCount+1) shr 1));
FillChar(fPointers[OldCount],(length(fPointers)-OldCount)*SizeOf(TpvPointer),#0);
fDataPointer:=@fPointers[0];
end;
end;
procedure TpvEntityComponentSystem.TComponent.Defragment;
function CompareFunction(const a,b:TpvSizeInt):TpvSizeInt;
begin
if (a>=0) and (b>=0) then begin
result:=a-b;
end else if a<>b then begin
if a<0 then begin
result:=1;
end else begin
result:=-1;
end;
end else begin
result:=0;
end;
end;
procedure IntroSort(Left,Right:TpvSizeInt);
type PByteArray=^TByteArray;
TByteArray=array[0..$3fffffff] of byte;
PStackItem=^TStackItem;
TStackItem=record
Left,Right,Depth:TpvSizeInt;
end;
var Depth,i,j,Middle,Size,Parent,Child,TempPoolIndex,PivotPoolIndex:TpvSizeInt;
Items,Pivot,Temp:TpvPointer;
StackItem:PStackItem;
Stack:array[0..31] of TStackItem;
begin
if Left<Right then begin
GetMem(Temp,fSize);
GetMem(Pivot,fSize);
try
Items:=fPool;
StackItem:=@Stack[0];
StackItem^.Left:=Left;
StackItem^.Right:=Right;
StackItem^.Depth:=IntLog2((Right-Left)+1) shl 1;
inc(StackItem);
while TpvPtrUInt(TpvPointer(StackItem))>TpvPtrUInt(TpvPointer(@Stack[0])) do begin
dec(StackItem);
Left:=StackItem^.Left;
Right:=StackItem^.Right;
Depth:=StackItem^.Depth;
if (Right-Left)<16 then begin
// Insertion sort
for i:=Left+1 to Right do begin
j:=i-1;
if (j>=Left) and (CompareFunction(fComponentPoolIndexToEntityIndex[j],fComponentPoolIndexToEntityIndex[i])>0) then begin
Move(PByteArray(Items)^[i*fSize],Temp^,fSize);
TempPoolIndex:=fComponentPoolIndexToEntityIndex[i];
repeat
Move(PByteArray(Items)^[j*fSize],PByteArray(Items)^[(j+1)*fSize],fSize);
fComponentPoolIndexToEntityIndex[j+1]:=fComponentPoolIndexToEntityIndex[j];
dec(j);
until not ((j>=Left) and (CompareFunction(fComponentPoolIndexToEntityIndex[j],TempPoolIndex)>0));
Move(Temp^,PByteArray(Items)^[(j+1)*fSize],fSize);
fComponentPoolIndexToEntityIndex[j+1]:=TempPoolIndex;
end;
end;
end else begin
if (Depth=0) or (TpvPtrUInt(TpvPointer(StackItem))>=TpvPtrUInt(TpvPointer(@Stack[high(Stack)-1]))) then begin
// Heap sort
Size:=(Right-Left)+1;
i:=Size div 2;
TempPoolIndex:=0;
repeat
if i>Left then begin
dec(i);
Move(PByteArray(Items)^[(Left+i)*fSize],Temp^,fSize);
TempPoolIndex:=fComponentPoolIndexToEntityIndex[Left+i];
end else begin
if Size=0 then begin
break;
end else begin
dec(Size);
Move(PByteArray(Items)^[(Left+Size)*fSize],Temp^,fSize);
Move(PByteArray(Items)^[Left*fSize],PByteArray(Items)^[(Left+Size)*fSize],fSize);
TempPoolIndex:=fComponentPoolIndexToEntityIndex[Left+Size];
fComponentPoolIndexToEntityIndex[Left+Size]:=fComponentPoolIndexToEntityIndex[Left];
end;
end;
Parent:=i;
Child:=(i*2)+1;
while Child<Size do begin
if ((Child+1)<Size) and (CompareFunction(fComponentPoolIndexToEntityIndex[(Left+Child)+1],fComponentPoolIndexToEntityIndex[Left+Child])>0) then begin
inc(Child);
end;
if CompareFunction(fComponentPoolIndexToEntityIndex[Left+Child],TempPoolIndex)>0 then begin
Move(PByteArray(Items)^[(Left+Child)*fSize],PByteArray(Items)^[(Left+Parent)*fSize],fSize);
fComponentPoolIndexToEntityIndex[Left+Parent]:=fComponentPoolIndexToEntityIndex[Left+Child];
Parent:=Child;
Child:=(Parent*2)+1;
end else begin
break;
end;
end;
Move(Temp^,PByteArray(fPool)^[(Left+Parent)*fSize],fSize);
fComponentPoolIndexToEntityIndex[Left+Parent]:=TempPoolIndex;
until false;
end else begin
// Quick sort width median-of-three optimization
Middle:=Left+((Right-Left) shr 1);
if (Right-Left)>3 then begin
if CompareFunction(fComponentPoolIndexToEntityIndex[Left],fComponentPoolIndexToEntityIndex[Middle])>0 then begin
Move(PByteArray(Items)^[Left*fSize],Temp^,fSize);
Move(PByteArray(Items)^[Middle*fSize],PByteArray(Items)^[Left*fSize],fSize);
Move(Temp^,PByteArray(Items)^[Middle*fSize],fSize);
TempPoolIndex:=fComponentPoolIndexToEntityIndex[Left];
fComponentPoolIndexToEntityIndex[Left]:=fComponentPoolIndexToEntityIndex[Middle];
fComponentPoolIndexToEntityIndex[Middle]:=TempPoolIndex;
end;
if CompareFunction(fComponentPoolIndexToEntityIndex[Left],fComponentPoolIndexToEntityIndex[Right])>0 then begin
Move(PByteArray(Items)^[Left*fSize],Temp^,fSize);
Move(PByteArray(Items)^[Right*fSize],PByteArray(Items)^[Left*fSize],fSize);
Move(Temp^,PByteArray(Items)^[Right*fSize],fSize);
TempPoolIndex:=fComponentPoolIndexToEntityIndex[Left];
fComponentPoolIndexToEntityIndex[Left]:=fComponentPoolIndexToEntityIndex[Right];
fComponentPoolIndexToEntityIndex[Right]:=TempPoolIndex;
end;
if CompareFunction(fComponentPoolIndexToEntityIndex[Middle],fComponentPoolIndexToEntityIndex[Right])>0 then begin
Move(PByteArray(Items)^[Middle*fSize],Temp^,fSize);
Move(PByteArray(Items)^[Right*fSize],PByteArray(Items)^[Middle*fSize],fSize);
Move(Temp^,PByteArray(Items)^[Right*fSize],fSize);
TempPoolIndex:=fComponentPoolIndexToEntityIndex[Middle];
fComponentPoolIndexToEntityIndex[Middle]:=fComponentPoolIndexToEntityIndex[Right];
fComponentPoolIndexToEntityIndex[Right]:=TempPoolIndex;
end;
end;
Move(PByteArray(Items)^[Middle*fSize],Pivot^,fSize);
PivotPoolIndex:=fComponentPoolIndexToEntityIndex[Middle];
i:=Left;
j:=Right;
repeat
while (i<Right) and (CompareFunction(fComponentPoolIndexToEntityIndex[i],PivotPoolIndex)<0) do begin
inc(i);
end;
while (j>=i) and (CompareFunction(fComponentPoolIndexToEntityIndex[j],PivotPoolIndex)>0) do begin
dec(j);
end;
if i>j then begin
break;
end else begin
if i<>j then begin
Move(PByteArray(Items)^[i*fSize],Temp^,fSize);
Move(PByteArray(Items)^[j*fSize],PByteArray(Items)^[i*fSize],fSize);
Move(Temp^,PByteArray(Items)^[j*fSize],fSize);
TempPoolIndex:=fComponentPoolIndexToEntityIndex[i];
fComponentPoolIndexToEntityIndex[i]:=fComponentPoolIndexToEntityIndex[j];
fComponentPoolIndexToEntityIndex[j]:=TempPoolIndex;
end;
inc(i);
dec(j);
end;
until false;
if i<Right then begin
StackItem^.Left:=i;
StackItem^.Right:=Right;
StackItem^.Depth:=Depth-1;
inc(StackItem);
end;
if Left<j then begin
StackItem^.Left:=Left;
StackItem^.Right:=j;
StackItem^.Depth:=Depth-1;
inc(StackItem);
end;
end;
end;
end;
finally
FreeMem(Pivot);
FreeMem(Temp);
end;
end;
end;
var Index,OtherIndex:TpvSizeInt;
NeedToSort:boolean;
begin
NeedToSort:=false;
for Index:=0 to fPoolIndexCounter-2 do begin
if fComponentPoolIndexToEntityIndex[Index]>fComponentPoolIndexToEntityIndex[Index+1] then begin
NeedToSort:=true;
break;
end;
end;
if NeedToSort then begin
IntroSort(0,fPoolIndexCounter-1);
for Index:=0 to fMaxEntityIndex do begin
fEntityIndexToComponentPoolIndex[Index]:=-1;
end;
for Index:=0 to fPoolIndexCounter-1 do begin
OtherIndex:=fComponentPoolIndexToEntityIndex[Index];
if OtherIndex>=0 then begin
fEntityIndexToComponentPoolIndex[OtherIndex]:=Index;
end;
end;
for Index:=0 to fMaxEntityIndex do begin
OtherIndex:=fEntityIndexToComponentPoolIndex[Index];
if OtherIndex>=0 then begin
fPointers[Index]:=TpvPointer(TpvPtrUInt(TpvPtrUInt(fPool)+TpvPtrUInt(TpvPtrUInt(OtherIndex)*TpvPtrUInt(fSize))));
end else begin
fPointers[Index]:=nil;
end;
end;
fCountFrees:=0;
fNeedToDefragment:=false;
end;
end;
procedure TpvEntityComponentSystem.TComponent.DefragmentIfNeeded;
begin
if fNeedToDefragment then begin
fNeedToDefragment:=false;
Defragment;
end;
end;
function TpvEntityComponentSystem.TComponent.GetComponentPoolIndexForEntityIndex(const aEntityIndex:TpvSizeInt):TpvSizeInt;
begin
if (aEntityIndex>=0) and
(aEntityIndex<=fMaxEntityIndex) and
((fUsedBitmap[aEntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(aEntityIndex and 31)))<>0) then begin
result:=fEntityIndexToComponentPoolIndex[aEntityIndex];
end else begin
result:=-1;
end;
end;
function TpvEntityComponentSystem.TComponent.IsComponentInEntityIndex(const aEntityIndex:TpvSizeInt):boolean;
begin
result:=(aEntityIndex>=0) and
(aEntityIndex<=fMaxEntityIndex) and
((fUsedBitmap[aEntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(aEntityIndex and 31)))<>0) and
(fEntityIndexToComponentPoolIndex[aEntityIndex]>=0);
end;
function TpvEntityComponentSystem.TComponent.GetEntityIndexByPoolIndex(const aPoolIndex:TpvSizeInt):TpvSizeInt;
begin
if (aPoolIndex>=0) and
(aPoolIndex<fPoolIndexCounter) then begin
result:=fComponentPoolIndexToEntityIndex[aPoolIndex];
end else begin
result:=-1;
end;
end;
function TpvEntityComponentSystem.TComponent.GetComponentByPoolIndex(const aPoolIndex:TpvSizeInt):TpvPointer;
begin
if (aPoolIndex>=0) and
(aPoolIndex<fPoolIndexCounter) then begin
result:=TpvPointer(TpvPtrUInt(TpvPtrUInt(fPool)+TpvPtrUInt(TpvPtrUInt(aPoolIndex)*TpvPtrUInt(fSize))));
end else begin
result:=nil;
end;
end;
function TpvEntityComponentSystem.TComponent.GetComponentByEntityIndex(const aEntityIndex:TpvSizeInt):TpvPointer;
var PoolIndex:TpvSizeInt;
begin
result:=nil;
if (aEntityIndex>=0) and
(aEntityIndex<=fMaxEntityIndex) and
((fUsedBitmap[aEntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(aEntityIndex and 31)))<>0) then begin
PoolIndex:=fComponentPoolIndexToEntityIndex[aEntityIndex];
if (PoolIndex>=0) and
(PoolIndex<fPoolIndexCounter) then begin
result:=TpvPointer(TpvPtrUInt(TpvPtrUInt(fPool)+TpvPtrUInt(TpvPtrUInt(PoolIndex)*TpvPtrUInt(fSize))));
end;
end;
end;
function TpvEntityComponentSystem.TComponent.AllocateComponentForEntityIndex(const aEntityIndex:TpvSizeInt):boolean;
var Index,PoolIndex,NewMaxEntityIndex,OldCapacity,OldCount,Count,OtherIndex,
OldPoolSize,NewPoolSize:TpvSizeInt;
Bitmap:PpvUInt32;
OldPoolAlignmentOffset:TpvPtrUInt;
begin
result:=false;
if (aEntityIndex>=0) and
not ((aEntityIndex<=fMaxEntityIndex) and
(fEntityIndexToComponentPoolIndex[aEntityIndex]>=0)) then begin
if fMaxEntityIndex<aEntityIndex then begin
NewMaxEntityIndex:=(aEntityIndex+1)*2;
SetLength(fEntityIndexToComponentPoolIndex,NewMaxEntityIndex+1);
for Index:=fMaxEntityIndex+1 to NewMaxEntityIndex do begin
fEntityIndexToComponentPoolIndex[Index]:=-1;
end;
fMaxEntityIndex:=NewMaxEntityIndex;
end;
PoolIndex:=fPoolIndexCounter;
inc(fPoolIndexCounter);
if fCapacity<fPoolIndexCounter then begin
OldCapacity:=fCapacity;
fCapacity:=fPoolIndexCounter*2;
SetLength(fComponentPoolIndexToEntityIndex,fCapacity);
for Index:=OldCapacity to fCapacity-1 do begin
fComponentPoolIndexToEntityIndex[Index]:=-1;
end;
end;
NewPoolSize:=TpvSizeInt(fCapacity)*TpvSizeInt(fSize);
if fPoolSize<NewPoolSize then begin
OldPoolSize:=fPoolSize;
fPoolSize:=NewPoolSize*2;
if assigned(fPoolUnaligned) then begin
OldPoolAlignmentOffset:=TpvPtrUInt(TpvPtrUInt(fPool)-TpvPtrUInt(fPoolUnaligned));
ReallocMem(fPoolUnaligned,fPoolSize+(4096*2));
fPool:=TpvPointer(TpvPtrUInt(TpvPtrUInt(TpvPtrUInt(fPoolUnaligned)+4095) and not 4095));
if OldPoolAlignmentOffset<>TpvPtrUInt(TpvPtrUInt(fPool)-TpvPtrUInt(fPoolUnaligned)) then begin
// Move the old existent data to the new alignment offset
Move(TpvPointer(TpvPtrUInt(TpvPtrUInt(fPoolUnaligned)+TpvPtrUInt(OldPoolAlignmentOffset)))^,fPool^,fPoolSize);
end;
if OldPoolSize<fPoolSize then begin
FillChar(TpvPointer(TpvPtrUInt(TpvPtrUInt(fPool)+TpvPtrUInt(OldPoolSize)))^,fPoolSize-OldPoolSize,#0);
end;
for Index:=0 to fMaxEntityIndex do begin
OtherIndex:=fEntityIndexToComponentPoolIndex[Index];
if OtherIndex>=0 then begin
fPointers[Index]:=TpvPointer(TpvPtrUInt(TpvPtrUInt(fPool)+TpvPtrUInt(TpvPtrUInt(OtherIndex)*TpvPtrUInt(fSize))));
end else begin
fPointers[Index]:=nil;
end;
end;
end else begin
GetMem(fPoolUnaligned,fPoolSize+(4096*2));
fPool:=TpvPointer(TpvPtrUInt(TpvPtrUInt(TpvPtrUInt(fPoolUnaligned)+4095) and not 4095));
FillChar(fPool^,fPoolSize,#0);
end;
end;
OldCount:=length(fUsedBitmap);
Count:=((fMaxEntityIndex+1)+31) shr 5;
if OldCount<Count then begin
SetLength(fUsedBitmap,Count+((Count+1) shr 1));
for Index:=OldCount to length(fUsedBitmap)-1 do begin
fUsedBitmap[Index]:=0;
end;
end;
OldCount:=length(fPointers);
Count:=fMaxEntityIndex+1;
if OldCount<Count then begin
SetLength(fPointers,Count+((Count+1) shr 1));
for Index:=OldCount to length(fPointers)-1 do begin
fPointers[Index]:=nil;
end;
fDataPointer:=@fPointers[0];
end;
fEntityIndexToComponentPoolIndex[aEntityIndex]:=PoolIndex;
fComponentPoolIndexToEntityIndex[PoolIndex]:=aEntityIndex;
fPointers[aEntityIndex]:=TpvPointer(TpvPtrUInt(TpvPtrUInt(fPool)+TpvPtrUInt(TpvPtrUInt(PoolIndex)*TpvPtrUInt(fSize))));
//FillChar(TpvPointer(TpvPtrUInt(TpvPtrUInt(fPool)+TpvPtrUInt(TpvPtrUInt(PoolIndex)*TpvPtrUInt(fSize))))^,fSize,#0);
Bitmap:=@fUsedBitmap[aEntityIndex shr 5];
Bitmap^:=Bitmap^ or TpvUInt32(TpvUInt32(1) shl TpvUInt32(aEntityIndex and 31));
result:=true;
end;
end;
function TpvEntityComponentSystem.TComponent.FreeComponentFromEntityIndex(const aEntityIndex:TpvSizeInt):boolean;
var PoolIndex,OtherPoolIndex,OtherEntityID:longint;
Mask:TpvUInt32;
Bitmap:PpvUInt32;
begin
result:=false;
Bitmap:=@fUsedBitmap[aEntityIndex shr 5];
Mask:=TpvUInt32(TpvUInt32(1) shl TpvUInt32(aEntityIndex and 31));
if (aEntityIndex>=0) and
(aEntityIndex<=fMaxEntityIndex) and
((Bitmap^ and Mask)<>0) and
(fEntityIndexToComponentPoolIndex[aEntityIndex]>=0) then begin
Bitmap^:=Bitmap^ and not Mask;
PoolIndex:=fEntityIndexToComponentPoolIndex[aEntityIndex];
FinalizeComponentByPoolIndex(PoolIndex);
fPointers[aEntityIndex]:=nil;
dec(fPoolIndexCounter);
if fPoolIndexCounter>0 then begin
OtherPoolIndex:=fPoolIndexCounter;
OtherEntityID:=fComponentPoolIndexToEntityIndex[OtherPoolIndex];
fEntityIndexToComponentPoolIndex[OtherEntityID]:=PoolIndex;
fComponentPoolIndexToEntityIndex[PoolIndex]:=OtherEntityID;
fComponentPoolIndexToEntityIndex[OtherPoolIndex]:=-1;
Move(TpvPointer(TpvPtrUInt(TpvPtrUInt(fPool)+TpvPtrUInt(TpvPtrUInt(OtherPoolIndex)*TpvPtrUInt(fSize))))^,
TpvPointer(TpvPtrUInt(TpvPtrUInt(fPool)+TpvPtrUInt(TpvPtrUInt(PoolIndex)*TpvPtrUInt(fSize))))^,
fSize);
fPointers[OtherEntityID]:=TpvPointer(TpvPtrUInt(TpvPtrUInt(fPool)+TpvPtrUInt(TpvPtrUInt(PoolIndex)*TpvPtrUInt(fSize))));
end else begin
fComponentPoolIndexToEntityIndex[PoolIndex]:=-1;
end;
fEntityIndexToComponentPoolIndex[aEntityIndex]:=-1;
inc(fCountFrees);
if fCountFrees>(fPoolIndexCounter shr 2) then begin
fNeedToDefragment:=true;
end;
result:=true;
end;
end;
{ TpvEntityComponentSystem.TEntity }
function TpvEntityComponentSystem.TEntity.GetActive:boolean;
begin
result:=TFlag.Active in fFlags;
end;
procedure TpvEntityComponentSystem.TEntity.SetActive(const aActive:boolean);
begin
if aActive<>(TFlag.Active in fFlags) then begin
if aActive then begin
Include(fFlags,TFlag.Active);
end else begin
Exclude(fFlags,TFlag.Active);
end;
end;
end;
procedure TpvEntityComponentSystem.TEntity.AddComponentToEntity(const aComponentID:TComponentID);
var Index,BitmapIndex,BitIndex,OldCount:TpvSizeInt;
begin
BitmapIndex:=aComponentID shr 5;
BitIndex:=aComponentID and 31;
fCountComponents:=Max(fCountComponents,aComponentID+1);
if length(fComponentsBitmap)<=BitmapIndex then begin
OldCount:=length(fComponentsBitmap);
SetLength(fComponentsBitmap,(BitmapIndex+1)+((BitmapIndex+2) shr 1));
FillChar(fComponentsBitmap[OldCount],(length(fComponentsBitmap)-OldCount)*SizeOf(UInt32),#0);
end;
fComponentsBitmap[BitIndex]:=fComponentsBitmap[BitIndex] or (TpvUInt32(1) shl BitIndex);
end;
procedure TpvEntityComponentSystem.TEntity.RemoveComponentFromEntity(const aComponentID:TComponentID);
var Index,BitmapIndex,BitIndex,OldCount:TpvSizeInt;
begin
BitmapIndex:=aComponentID shr 5;
BitIndex:=aComponentID and 31;
fCountComponents:=Max(fCountComponents,aComponentID+1);
if length(fComponentsBitmap)<=BitmapIndex then begin
OldCount:=length(fComponentsBitmap);
SetLength(fComponentsBitmap,(BitmapIndex+1)+((BitmapIndex+2) shr 1));
FillChar(fComponentsBitmap[OldCount],(length(fComponentsBitmap)-OldCount)*SizeOf(UInt32),#0);
end;
fComponentsBitmap[BitIndex]:=fComponentsBitmap[BitIndex] and not (TpvUInt32(1) shl BitIndex);
end;
procedure TpvEntityComponentSystem.TEntity.SynchronizeToPrefab;
begin
end;
procedure TpvEntityComponentSystem.TEntity.Activate;
begin
if assigned(fWorld) then begin
fWorld.ActivateEntity(fID);
end;
end;
procedure TpvEntityComponentSystem.TEntity.Deactivate;
begin
if assigned(fWorld) then begin
fWorld.DeactivateEntity(fID);
end;
end;
procedure TpvEntityComponentSystem.TEntity.Kill;
begin
if assigned(fWorld) then begin
fWorld.KillEntity(fID);
end;
end;
procedure TpvEntityComponentSystem.TEntity.AddComponent(const aComponentID:TComponentID);
begin
if assigned(fWorld) then begin
fWorld.AddComponentToEntity(fID,aComponentID);
end;
end;
procedure TpvEntityComponentSystem.TEntity.RemoveComponent(const aComponentID:TComponentID);
begin
if assigned(fWorld) then begin
fWorld.RemoveComponentFromEntity(fID,aComponentID);
end;
end;
function TpvEntityComponentSystem.TEntity.HasComponent(const aComponentID:TComponentID):boolean;
begin
result:=assigned(fWorld) and World.HasEntityComponent(fID,aComponentID);
end;
function TpvEntityComponentSystem.TEntity.GetComponent(const aComponentID:TComponentID):TpvEntityComponentSystem.TComponent;
begin
if assigned(fWorld) and World.HasEntityComponent(fID,aComponentID) then begin
result:=fWorld.fComponents[aComponentID];
end else begin
result:=nil;
end;
end;
{ TpvEntityComponentSystem.TEventRegistration }
constructor TpvEntityComponentSystem.TEventRegistration.Create(const aEventID:TpvEntityComponentSystem.TEventID;const aName:TpvUTF8String);
begin
inherited Create;
fEventID:=aEventID;
fName:=aName;
fActive:=false;
fLock:=TPasMPMultipleReaderSingleWriterLock.Create;
fSystems:=TSystemList.Create;
fSystems.OwnsObjects:=false;
fEventHandlers:=nil;
fCountEventHandlers:=0;
end;
destructor TpvEntityComponentSystem.TEventRegistration.Destroy;
begin
fName:='';
fEventHandlers:=nil;
FreeAndNil(fSystems);
FreeAndNil(fLock);
inherited Destroy;
end;
procedure TpvEntityComponentSystem.TEventRegistration.Clear;
begin
fLock.AcquireWrite;
try
fName:='';
fActive:=false;
fSystems.Clear;
fEventHandlers:=nil;
fCountEventHandlers:=0;
finally
fLock.ReleaseWrite;
end;
end;
procedure TpvEntityComponentSystem.TEventRegistration.AddSystem(const aSystem:TSystem);
begin
fLock.AcquireRead;
try
if fSystems.IndexOf(aSystem)<0 then begin
fLock.ReadToWrite;
try
fSystems.Add(aSystem);
finally
fLock.WriteToRead;
end;
end;
finally
fLock.ReleaseRead;
end;
end;
procedure TpvEntityComponentSystem.TEventRegistration.RemoveSystem(const aSystem:TSystem);
var Index:TpvSizeInt;
begin
fLock.AcquireRead;
try
Index:=fSystems.IndexOf(aSystem);
if Index>=0 then begin
fLock.ReadToWrite;
try
fSystems.Delete(Index);
finally
fLock.WriteToRead;
end;
end;
finally
fLock.ReleaseRead;
end;
end;
procedure TpvEntityComponentSystem.TEventRegistration.AddEventHandler(const aEventHandler:TEventHandler);
var Index:TpvSizeInt;
Found:boolean;
begin
Found:=false;
fLock.AcquireRead;
try
for Index:=0 to fCountEventHandlers-1 do begin
if (TMethod(fEventHandlers[Index]).Code=TMethod(aEventHandler).Code) and
(TMethod(fEventHandlers[Index]).Data=TMethod(aEventHandler).Data) then begin
Found:=true;
break;
end;
end;
if not Found then begin
fLock.ReadToWrite;
try
Index:=fCountEventHandlers;
inc(fCountEventHandlers);
if length(fEventHandlers)<fCountEventHandlers then begin
SetLength(fEventHandlers,fCountEventHandlers+((fCountEventHandlers+1) shr 1));
end;
fEventHandlers[Index]:=aEventHandler;
finally
fLock.WriteToRead;
end;
end;
finally
fLock.ReleaseRead;
end;
end;
procedure TpvEntityComponentSystem.TEventRegistration.RemoveEventHandler(const aEventHandler:TEventHandler);
var Index:TpvSizeInt;
begin
fLock.AcquireRead;
try
for Index:=0 to fCountEventHandlers-1 do begin
if (TMethod(fEventHandlers[Index]).Code=TMethod(aEventHandler).Code) and
(TMethod(fEventHandlers[Index]).Data=TMethod(aEventHandler).Data) then begin
fLock.ReadToWrite;
try
dec(fCountEventHandlers);
if fCountEventHandlers>0 then begin
Move(fEventHandlers[Index+1],fEventHandlers[Index],fCountEventHandlers*SizeOf(TEventHandler)); // for to be keep the ordering
// fEventHandlers[Index]:=fEventHandlers[fCountEventHandlers]; // for to be faster, but with changing the ordering of the last item to the deleted item position
end;
finally
fLock.WriteToRead;
end;
break;
end;
end;
finally
fLock.ReleaseRead;
end;
end;
{ TpvEntityComponentSystem.TSystemChoreography }
constructor TpvEntityComponentSystem.TSystemChoreography.Create(const aWorld:TWorld);
begin
inherited Create;
fWorld:=aWorld;
fPasMPInstance:=fWorld.fPasMPInstance;
fChoreographySteps:=nil;
fChoreographyStepJobs:=nil;
fCountChoreographySteps:=0;
fSortedSystemList:=TSystemList.Create;
fSortedSystemList.OwnsObjects:=false;
end;
destructor TpvEntityComponentSystem.TSystemChoreography.Destroy;
begin
fChoreographySteps:=nil;
fChoreographyStepJobs:=nil;
FreeAndNil(fSortedSystemList);
inherited Destroy;
end;
procedure TpvEntityComponentSystem.TSystemChoreography.Build;
var Systems:TSystemList;
Index,OtherIndex,SystemIndex:TpvInt32;
Done,Stop:boolean;
System,OtherSystem:TSystem;
ChoreographyStep:PSystemChoreographyStep;
begin
Systems:=fSortedSystemList;
Systems.Clear;
// Fill in
for Index:=0 to fWorld.fSystems.Count-1 do begin
Systems.Add(fWorld.fSystems.Items[Index]);
end;
// Resolve dependencies with "stable" topological sorting a la naive bubble sort with a bad
// execution time (but that fact does not matter at so few systems), and not with Kahn's or
// Tarjan's algorithms, because the result must be in a stable sort order
repeat
Done:=true;
for Index:=0 to Systems.Count-1 do begin
System:=Systems.Items[Index];
for OtherIndex:=0 to Index-1 do begin
OtherSystem:=Systems.Items[OtherIndex];
if OtherSystem.HaveDependencyOnSystem(System) then begin
if OtherSystem.HaveCircularDependencyWithSystem(System) then begin
raise ESystemCircularDependency.Create(System.ClassName+' have circular dependency with '+OtherSystem.ClassName);
end else begin
Systems.Exchange(Index,OtherIndex);
Done:=false;
break;
end;
end;
end;
if not Done then begin
break;
end;
end;
until Done;
// Construct dependency conflict-free choreography
fCountChoreographySteps:=0;
Index:=0;
while Index<Systems.Count do begin
System:=Systems.Items[Index];
inc(Index);
inc(fCountChoreographySteps);
if fCountChoreographySteps>length(fChoreographySteps) then begin
SetLength(fChoreographySteps,fCountChoreographySteps*2);
end;
ChoreographyStep:=@fChoreographySteps[fCountChoreographySteps-1];
ChoreographyStep^.Count:=1;
SetLength(ChoreographyStep^.Systems,ChoreographyStep^.Count);
SetLength(ChoreographyStep^.Jobs,ChoreographyStep^.Count);
ChoreographyStep^.Systems[0]:=System;
while Index<Systems.Count do begin
OtherSystem:=Systems.Items[Index];
Stop:=TpvEntityComponentSystem.TSystem.TFlag.Secluded in OtherSystem.fFlags;
if not Stop then begin
for SystemIndex:=0 to ChoreographyStep^.Count-1 do begin
System:=ChoreographyStep^.Systems[SystemIndex];
if System.HaveDependencyOnSystemOrViceVersa(OtherSystem) or
System.HaveConflictWithSystemOrViceVersa(OtherSystem) then begin
Stop:=true;
break;
end;
end;
end;
if Stop then begin
break;
end else begin
inc(Index);
inc(ChoreographyStep^.Count);
if ChoreographyStep^.Count>length(ChoreographyStep^.Systems) then begin
SetLength(ChoreographyStep^.Systems,ChoreographyStep^.Count*2);
end;
ChoreographyStep^.Systems[ChoreographyStep^.Count-1]:=OtherSystem;
end;
end;
end;
SetLength(fChoreographyStepJobs,fCountChoreographySteps);
end;
type PSystemChoreographyProcessEventsJobData=^TSystemChoreographyProcessEventsJobData;
TSystemChoreographyProcessEventsJobData=record
System:TpvEntityComponentSystem.TSystem;
FirstEventIndex:TPasMPSizeInt;
LastEventIndex:TPasMPSizeInt;
end;
function TpvEntityComponentSystem.TSystemChoreography.CreateProcessEventsJob(const aSystem:TSystem;const aFirstEventIndex,aLastEventIndex:TPasMPSizeInt;const aParentJob:PPasMPJob):PPasMPJob;
var Data:PSystemChoreographyProcessEventsJobData;
begin
result:=fPasMPInstance.Acquire(ProcessEventsJobFunction,nil,nil);
Data:=PSystemChoreographyProcessEventsJobData(pointer(@result^.Data));
Data^.System:=aSystem;
Data^.FirstEventIndex:=aFirstEventIndex;
Data^.LastEventIndex:=aFirstEventIndex;
end;
procedure TpvEntityComponentSystem.TSystemChoreography.ProcessEventsJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
var Data:PSystemChoreographyProcessEventsJobData;
MidEventIndex,Count:TpvSizeInt;
begin
Data:=@aJob^.Data;
if Data^.FirstEventIndex<=Data^.LastEventIndex then begin
Count:=Data^.LastEventIndex-Data^.FirstEventIndex;
if (fPasMPInstance.CountJobWorkerThreads<2) or
(not (TpvEntityComponentSystem.TSystem.TFlag.ParallelProcessing in Data.System.fFlags)) or
((Count<=Data^.System.fEventGranularity) or (Count<4)) then begin
Data^.System.ProcessEvents(Data^.FirstEventIndex,Data^.LastEventIndex);
end else begin
MidEventIndex:=Data^.FirstEventIndex+((Data^.LastEventIndex-Data^.FirstEventIndex) shr 1);
fPasMPInstance.Invoke([CreateProcessEventsJob(Data^.System,Data^.FirstEventIndex,MidEventIndex-1,aJob),
CreateProcessEventsJob(Data^.System,MidEventIndex,Data^.LastEventIndex,aJob)]);
end;
end;
end;
procedure TpvEntityComponentSystem.TSystemChoreography.ChoreographyStepProcessEventsJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
var Data:PSystemChoreographyStepProcessEventsJobData;
ChoreographyStep:PSystemChoreographyStep;
SystemIndex:TpvSizeInt;
System:TpvEntityComponentSystem.TSystem;
begin
Data:=@aJob^.Data;
ChoreographyStep:=Data^.ChoreographyStep;
for SystemIndex:=0 to ChoreographyStep^.Count-1 do begin
System:=ChoreographyStep^.Systems[SystemIndex];
if System.fEventsCanBeParallelProcessed then begin
ChoreographyStep^.Jobs[SystemIndex]:=CreateProcessEventsJob(System,0,System.fCountEvents-1,aJob);
end else begin
ChoreographyStep^.Jobs[SystemIndex]:=nil;
end;
end;
fPasMPInstance.Invoke(ChoreographyStep^.Jobs);
end;
procedure TpvEntityComponentSystem.TSystemChoreography.ChoreographyProcessEventsJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
var ChoreographyStepJob:PPasMPJob;
ChoreographyStepJobData:PSystemChoreographyStepProcessEventsJobData;
StepIndex:TpvSizeInt;
ChoreographyStep:PSystemChoreographyStep;
begin
for StepIndex:=0 to fCountChoreographySteps-1 do begin
ChoreographyStep:=@fChoreographySteps[StepIndex];
ChoreographyStepJob:=fPasMPInstance.Acquire(ChoreographyStepProcessEventsJobFunction,nil,nil);
ChoreographyStepJobData:=PSystemChoreographyStepProcessEventsJobData(pointer(@ChoreographyStepJob^.Data));
ChoreographyStepJobData^.ChoreographyStep:=ChoreographyStep;
fChoreographyStepJobs[StepIndex]:=ChoreographyStepJob;
fPasMPInstance.Invoke(fChoreographyStepJobs[StepIndex]);
end;
end;
procedure TpvEntityComponentSystem.TSystemChoreography.ProcessEvents;
begin
fPasMPInstance.Invoke(fPasMPInstance.Acquire(ChoreographyProcessEventsJobFunction,nil,nil));
end;
procedure TpvEntityComponentSystem.TSystemChoreography.InitializeUpdate;
var StepIndex,SystemIndex:TpvSizeInt;
ChoreographyStep:PSystemChoreographyStep;
System:TSystem;
begin
for StepIndex:=0 to fCountChoreographySteps-1 do begin
ChoreographyStep:=@fChoreographySteps[StepIndex];
for SystemIndex:=0 to ChoreographyStep^.Count-1 do begin
System:=ChoreographyStep^.Systems[SystemIndex];
System.InitializeUpdate;
end;
end;
end;
type PSystemChoreographyUpdateEntitiesJobData=^TSystemChoreographyUpdateEntitiesJobData;
TSystemChoreographyUpdateEntitiesJobData=record
System:TpvEntityComponentSystem.TSystem;
FirstEntityIndex:TpvSizeInt;
LastEntityIndex:TpvSizeInt;
end;
function TpvEntityComponentSystem.TSystemChoreography.CreateUpdateEntitiesJob(const aSystem:TSystem;const aFirstEntityIndex,aLastEntityIndex:TPasMPSizeInt;const aParentJob:PPasMPJob):PPasMPJob;
var Data:PSystemChoreographyUpdateEntitiesJobData;
begin
result:=fPasMPInstance.Acquire(UpdateEntitiesJobFunction,nil,nil);
Data:=PSystemChoreographyUpdateEntitiesJobData(pointer(@result^.Data));
Data^.System:=aSystem;
Data^.FirstEntityIndex:=aFirstEntityIndex;
Data^.LastEntityIndex:=aLastEntityIndex;
end;
procedure TpvEntityComponentSystem.TSystemChoreography.UpdateEntitiesJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
var Data:PSystemChoreographyUpdateEntitiesJobData;
MidEntityIndex,Count:TpvSizeInt;
begin
Data:=@aJob^.Data;
if Data^.FirstEntityIndex<=Data^.LastEntityIndex then begin
Count:=Data^.LastEntityIndex-Data^.FirstEntityIndex;
if (TpvEntityComponentSystem.TSystem.TFlag.OwnUpdate in Data.System.fFlags) or
(not (TpvEntityComponentSystem.TSystem.TFlag.ParallelProcessing in Data.System.fFlags)) or
(fPasMPInstance.CountJobWorkerThreads<2) or
((Count<=Data^.System.fEntityGranularity) or (Count<4)) then begin
if TpvEntityComponentSystem.TSystem.TFlag.OwnUpdate in Data.System.fFlags then begin
Data^.System.Update;
end else begin
Data^.System.UpdateEntities(Data^.FirstEntityIndex,Data^.LastEntityIndex);
end;
end else begin
MidEntityIndex:=Data^.FirstEntityIndex+((Data^.LastEntityIndex-Data^.FirstEntityIndex) shr 1);
fPasMPInstance.Invoke([CreateUpdateEntitiesJob(Data^.System,Data^.FirstEntityIndex,MidEntityIndex-1,aJob),
CreateUpdateEntitiesJob(Data^.System,MidEntityIndex,Data^.LastEntityIndex,aJob)]);
end;
end;
end;
procedure TpvEntityComponentSystem.TSystemChoreography.ChoreographyStepUpdateEntitiesJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
var Data:PSystemChoreographyStepUpdateEntitiesJobData;
ChoreographyStep:PSystemChoreographyStep;
SystemIndex:TpvSizeInt;
System:TSystem;
begin
Data:=@aJob^.Data;
ChoreographyStep:=Data^.ChoreographyStep;
for SystemIndex:=0 to ChoreographyStep^.Count-1 do begin
System:=ChoreographyStep^.Systems[SystemIndex];
ChoreographyStep^.Jobs[SystemIndex]:=CreateUpdateEntitiesJob(System,0,System.fCountEntities-1,aJob);
end;
fPasMPInstance.Invoke(ChoreographyStep^.Jobs);
end;
procedure TpvEntityComponentSystem.TSystemChoreography.ChoreographyUpdateEntitiesJobFunction(const aJob:PPasMPJob;const aThreadIndex:TpvInt32);
var ChoreographyStepJob:PPasMPJob;
ChoreographyStepJobData:PSystemChoreographyStepUpdateEntitiesJobData;
StepIndex:TpvSizeInt;
ChoreographyStep:PSystemChoreographyStep;
begin
for StepIndex:=0 to fCountChoreographySteps-1 do begin
ChoreographyStep:=@fChoreographySteps[StepIndex];
ChoreographyStepJob:=fPasMPInstance.Acquire(ChoreographyStepUpdateEntitiesJobFunction,nil,nil);
ChoreographyStepJobData:=PSystemChoreographyStepUpdateEntitiesJobData(pointer(@ChoreographyStepJob^.Data));
ChoreographyStepJobData^.ChoreographyStep:=ChoreographyStep;
fChoreographyStepJobs[StepIndex]:=ChoreographyStepJob;
fPasMPInstance.Invoke(fChoreographyStepJobs[StepIndex]);
end;
end;
procedure TpvEntityComponentSystem.TSystemChoreography.Update;
begin
fPasMPInstance.Invoke(fPasMPInstance.Acquire(ChoreographyUpdateEntitiesJobFunction,nil,nil));
end;
procedure TpvEntityComponentSystem.TSystemChoreography.FinalizeUpdate;
var StepIndex,SystemIndex:TpvSizeInt;
ChoreographyStep:PSystemChoreographyStep;
System:TSystem;
begin
for StepIndex:=0 to fCountChoreographySteps-1 do begin
ChoreographyStep:=@fChoreographySteps[StepIndex];
for SystemIndex:=0 to ChoreographyStep^.Count-1 do begin
System:=ChoreographyStep^.Systems[SystemIndex];
System.FinalizeUpdate;
end;
end;
end;
{ TpvEntityComponentSystem.TSystem }
constructor TpvEntityComponentSystem.TSystem.Create(const aWorld:TWorld);
begin
inherited Create;
fWorld:=aWorld;
fFlags:=[];
fEntities:=TEntityIDList.Create;
fRequiredComponents:=TComponentIDList.Create;
fExcludedComponents:=TComponentIDList.Create;
fRequiresSystems:=TSystemList.Create;
fRequiresSystems.OwnsObjects:=false;
fConflictsWithSystems:=TSystemList.Create;
fConflictsWithSystems.OwnsObjects:=false;
fNeedToSort:=true;
fEventsCanBeParallelProcessed:=false;
fEventGranularity:=256;
fEntityGranularity:=256;
fCountEntities:=0;
fEvents:=nil;
fCountEvents:=0;
end;
destructor TpvEntityComponentSystem.TSystem.Destroy;
begin
FreeAndNil(fExcludedComponents);
FreeAndNil(fRequiredComponents);
FreeAndNil(fRequiresSystems);
FreeAndNil(fConflictsWithSystems);
FreeAndNil(fEntities);
fEvents:=nil;
inherited Destroy;
end;
procedure TpvEntityComponentSystem.TSystem.Added;
begin
end;
procedure TpvEntityComponentSystem.TSystem.Removed;
begin
end;
procedure TpvEntityComponentSystem.TSystem.SubscribeToEvent(const aEventID:TEventID);
var EventRegistration:TEventRegistration;
begin
fWorld.fEventRegistrationLock.AcquireWrite;
try
if (aEventID>=0) and (aEventID<fWorld.fEventRegistrationList.Count) then begin
EventRegistration:=fWorld.fEventRegistrationList.Items[aEventID];
if EventRegistration.fActive then begin
EventRegistration.AddSystem(self);
end;
end;
finally
fWorld.fEventRegistrationLock.ReleaseWrite;
end;
end;
procedure TpvEntityComponentSystem.TSystem.UnsubscribeFromEvent(const aEventID:TEventID);
var EventRegistration:TEventRegistration;
begin
fWorld.fEventRegistrationLock.AcquireWrite;
try
if (aEventID>=0) and (aEventID<fWorld.fEventRegistrationList.Count) then begin
EventRegistration:=fWorld.fEventRegistrationList.Items[aEventID];
if EventRegistration.fActive then begin
EventRegistration.RemoveSystem(self);
end;
end;
finally
fWorld.fEventRegistrationLock.ReleaseWrite;
end;
end;
function TpvEntityComponentSystem.TSystem.HaveDependencyOnSystem(const aOtherSystem:TSystem):boolean;
begin
result:=assigned(aOtherSystem) and (fRequiresSystems.IndexOf(aOtherSystem)>=0);
end;
function TpvEntityComponentSystem.TSystem.HaveDependencyOnSystemOrViceVersa(const aOtherSystem:TSystem):boolean;
begin
result:=assigned(aOtherSystem) and ((fRequiresSystems.IndexOf(aOtherSystem)>=0) or (aOtherSystem.fRequiresSystems.IndexOf(self)>=0));
end;
function TpvEntityComponentSystem.TSystem.HaveCircularDependencyWithSystem(const aOtherSystem:TSystem):boolean;
var VisitedList,StackList:TList;
Index:TpvSizeInt;
System,RequiredSystem:TSystem;
begin
result:=false;
if assigned(aOtherSystem) then begin
VisitedList:=TList.Create;
try
StackList:=TList.Create;
try
StackList.Add(aOtherSystem);
while (StackList.Count>0) and not result do begin
System:=StackList.Items[StackList.Count-1];
StackList.Delete(StackList.Count-1);
VisitedList.Add(System);
for Index:=0 to System.fRequiresSystems.Count-1 do begin
RequiredSystem:=System.fRequiresSystems.Items[Index];
if RequiredSystem=self then begin
result:=true;
break;
end else if VisitedList.IndexOf(RequiredSystem)<0 then begin
StackList.Add(RequiredSystem);
end;
end;
end;
finally
StackList.Free;
end;
finally
VisitedList.Free;
end;
end;
end;
function TpvEntityComponentSystem.TSystem.HaveConflictWithSystem(const aOtherSystem:TSystem):boolean;
begin
result:=assigned(aOtherSystem) and (fConflictsWithSystems.IndexOf(aOtherSystem)>=0);
end;
function TpvEntityComponentSystem.TSystem.HaveConflictWithSystemOrViceVersa(const aOtherSystem:TSystem):boolean;
begin
result:=assigned(aOtherSystem) and ((fConflictsWithSystems.IndexOf(aOtherSystem)>=0) or (aOtherSystem.fConflictsWithSystems.IndexOf(self)>=0));
end;
procedure TpvEntityComponentSystem.TSystem.RequiresSystem(const aSystem:TSystem);
begin
if fRequiresSystems.IndexOf(aSystem)<0 then begin
fRequiresSystems.Add(aSystem);
end;
end;
procedure TpvEntityComponentSystem.TSystem.ConflictsWithSystem(const aSystem:TSystem);
begin
if fConflictsWithSystems.IndexOf(aSystem)<0 then begin
fConflictsWithSystems.Add(aSystem);
end;
end;
procedure TpvEntityComponentSystem.TSystem.AddRequiredComponent(const aComponentID:TComponentID);
begin
if fRequiredComponents.IndexOf(aComponentID)<0 then begin
fRequiredComponents.Add(aComponentID);
end;
end;
procedure TpvEntityComponentSystem.TSystem.AddExcludedComponent(const aComponentID:TComponentID);
begin
if fExcludedComponents.IndexOf(aComponentID)<0 then begin
fExcludedComponents.Add(aComponentID);
end;
end;
function TpvEntityComponentSystem.TSystem.FitsEntityToSystem(const aEntityID:TEntityID):boolean;
var Index:TpvSizeInt;
begin
result:=fWorld.HasEntity(aEntityID);
if result then begin
for Index:=0 to fExcludedComponents.Count-1 do begin
if fWorld.HasEntityComponent(aEntityID,fExcludedComponents.Items[Index]) then begin
result:=false;
exit;
end;
end;
for Index:=0 to fRequiredComponents.Count-1 do begin
if not fWorld.HasEntityComponent(aEntityID,fRequiredComponents.Items[Index]) then begin
result:=false;
exit;
end;
end;
end;
end;
function TpvEntityComponentSystem.TSystem.AddEntityToSystem(const aEntityID:TEntityID):boolean;
begin
if fEntities.IndexOf(aEntityID)<0 then begin
fEntities.Add(aEntityID);
inc(fCountEntities);
fNeedToSort:=true;
result:=true;
end else begin
result:=false;
end;
end;
function TpvEntityComponentSystem.TSystem.RemoveEntityFromSystem(const aEntityID:TEntityID):boolean;
var Index:TpvSizeInt;
begin
Index:=fEntities.IndexOf(aEntityID);
if Index>=0 then begin
fEntities.Delete(Index);
dec(fCountEntities);
result:=true;
end else begin
result:=false;
end;
end;
procedure TpvEntityComponentSystem.TSystem.SortEntities;
begin
if fNeedToSort then begin
fNeedToSort:=false;
fEntities.Sort;
end;
end;
procedure TpvEntityComponentSystem.TSystem.Finish;
begin
end;
procedure TpvEntityComponentSystem.TSystem.ProcessEvent(const aEvent:TpvEntityComponentSystem.TEvent);
begin
end;
procedure TpvEntityComponentSystem.TSystem.ProcessEvents(const aFirstEventIndex,aLastEventIndex:TpvSizeInt);
var EntityIndex:TpvSizeInt;
Event:TpvEntityComponentSystem.PEvent;
begin
for EntityIndex:=aFirstEventIndex to aLastEventIndex do begin
Event:=fEvents[EntityIndex];
if assigned(Event) then begin
ProcessEvent(Event^);
end;
end;
end;
procedure TpvEntityComponentSystem.TSystem.InitializeUpdate;
begin
end;
procedure TpvEntityComponentSystem.TSystem.Update;
begin
end;
procedure TpvEntityComponentSystem.TSystem.UpdateEntities(const aFirstEntityIndex,aLastEntityIndex:TpvSizeInt);
begin
end;
procedure TpvEntityComponentSystem.TSystem.FinalizeUpdate;
begin
end;
{ TpvEntityComponentSystem.TWorld }
constructor TpvEntityComponentSystem.TWorld.Create(const aPasMPInstance:TPasMP);
var Index:TpvSizeInt;
begin
inherited Create;
fUUID:=TpvUUID.Create;
if assigned(aPasMPInstance) then begin
fPasMPInstance:=aPasMPInstance;
end else begin
fPasMPInstance:=TPasMP.GetGlobalInstance;
end;
fActive:=false;
fLock:=TPasMPMultipleReaderSingleWriterLock.Create;
fEntityUUIDHashMap:=TpvEntityComponentSystem.TWorld.TUUIDEntityIDPairHashMap.Create(0);
fReservedEntityHashMapLock:=TPasMPMultipleReaderSingleWriterLock.Create;
fReservedEntityUUIDHashMap:=TpvEntityComponentSystem.TWorld.TUUIDEntityIDPairHashMap.Create(0);
fComponents:=TComponentList.Create;
fComponents.OwnsObjects:=true;
for Index:=0 to RegisteredComponentTypeList.Count-1 do begin
fComponents.Add(TpvEntityComponentSystem.TComponent.Create(self,RegisteredComponentTypeList.Items[Index]));
end;
fEntities:=nil;
fEntityLock:=TPasMPMultipleReaderSingleWriterLock.Create;
fEntityIndexFreeList:=TEntityIndexFreeList.Create;
fEntityGenerationList:=nil;
fEntityUsedBitmap:=nil;
fEntityIndexCounter:=1;
fMaxEntityIndex:=-1;
fEventListLock:=TPasMPMultipleReaderSingleWriterLock.Create;
fEventList:=TList.Create;
fDelayedEventQueueLock:=TPasMPMultipleReaderSingleWriterLock.Create;
LinkedListInitialize(@fDelayedEventQueue);
fEventQueueLock:=TPasMPMultipleReaderSingleWriterLock.Create;
LinkedListInitialize(@fEventQueue);
LinkedListInitialize(@fDelayedFreeEventQueue);
fFreeEventQueueLock:=TPasMPMultipleReaderSingleWriterLock.Create;
LinkedListInitialize(@fFreeEventQueue);
fCurrentTime:=0.0;
fSystems:=TSystemList.Create;
fSystems.OwnsObjects:=false;
fSystemUsedMap:=TSystemBooleanPairHashMap.Create(false);
fSystemChoreography:=TSystemChoreography.Create(self);
fSystemChoreographyNeedToRebuild:=0;
fEventInProcessing:=false;
fEventRegistrationLock:=TPasMPMultipleReaderSingleWriterLock.Create;
fEventRegistrationList:=TEventRegistrationList.Create;
fEventRegistrationList.OwnsObjects:=false;
fFreeEventRegistrationList:=TEventRegistrationList.Create;
fFreeEventRegistrationList.OwnsObjects:=false;
fEventRegistrationStringIntegerPairHashMap:=TEventRegistrationStringIntegerPairHashMap.Create(-1);
fOnEvent:=nil;
fDelayedManagementEventLock:=TPasMPMultipleReaderSingleWriterLock.Create;
fDelayedManagementEvents:=nil;
fCountDelayedManagementEvents:=0;
end;
destructor TpvEntityComponentSystem.TWorld.Destroy;
var Index:TpvSizeInt;
Event:TpvEntityComponentSystem.PEvent;
begin
fEventRegistrationList.OwnsObjects:=true;
FreeAndNil(fEventRegistrationList);
fFreeEventRegistrationList.OwnsObjects:=true;
FreeAndNil(fFreeEventRegistrationList);
FreeAndNil(fEventRegistrationLock);
FreeAndNil(fEventRegistrationStringIntegerPairHashMap);
FreeAndNil(fSystemChoreography);
FreeAndNil(fSystemUsedMap);
FreeAndNil(fSystems);
FreeAndNil(fComponents);
fEntities:=nil;
FreeAndNil(fEntityIndexFreeList);
fEntityGenerationList:=nil;
fEntityUsedBitmap:=nil;
FreeAndNil(fDelayedManagementEventLock);
fDelayedManagementEvents:=nil;
for Index:=0 to fEventList.Count-1 do begin
Event:=fEventList.Items[Index];
if assigned(Event) then begin
Finalize(Event^);
FreeMem(Event);
end;
end;
fEventList.Free;
fEventListLock.Free;
fDelayedEventQueueLock.Free;
fEventQueueLock.Free;
fFreeEventQueueLock.Free;
FreeAndNil(fEntityUUIDHashMap);
FreeAndNil(fReservedEntityUUIDHashMap);
FreeAndNil(fReservedEntityHashMapLock);
FreeAndNil(fEntityLock);
FreeAndNil(fLock);
inherited Destroy;
end;
procedure TpvEntityComponentSystem.TWorld.AddDelayedManagementEvent(const aDelayedManagementEvent:TDelayedManagementEvent);
var DelayedManagementEventIndex:TpvSizeInt;
begin
fDelayedManagementEventLock.AcquireWrite;
try
DelayedManagementEventIndex:=fCountDelayedManagementEvents;
inc(fCountDelayedManagementEvents);
if length(fDelayedManagementEvents)<fCountDelayedManagementEvents then begin
SetLength(fDelayedManagementEvents,fCountDelayedManagementEvents+((fCountDelayedManagementEvents+1) shr 1));
end;
fDelayedManagementEvents[DelayedManagementEventIndex]:=aDelayedManagementEvent;
finally
fDelayedManagementEventLock.ReleaseWrite;
end;
end;
function TpvEntityComponentSystem.TWorld.GetEntityByID(const aEntityID:TpvEntityComponentSystem.TEntityID):TpvEntityComponentSystem.PEntity;
var EntityIndex:TpvInt32;
begin
EntityIndex:=aEntityID.Index;
if (EntityIndex>=0) and
(EntityIndex<=fMaxEntityIndex) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) then begin
result:=@fEntities[EntityIndex];
if result^.fID<>aEntityID then begin
result:=nil;
end;
end else begin
result:=nil;
end;
end;
function TpvEntityComponentSystem.TWorld.GetEntityByUUID(const aEntityUUID:TpvUUID):TpvEntityComponentSystem.PEntity;
begin
result:=nil;
end;
function TpvEntityComponentSystem.TWorld.DoCreateEntity(const aEntityID:TEntityID;const aEntityUUID:TpvUUID):boolean;
var EntityIndex,Index,OldCount,Count:TpvInt32;
Bitmap:PpvInt32;
Entity:PEntity;
begin
result:=false;
fLock.AcquireRead;
try
fLock.ReadToWrite;
try
EntityIndex:=aEntityID.Index;
if fMaxEntityIndex<EntityIndex then begin
fMaxEntityIndex:=EntityIndex;
for Index:=0 to fComponents.Count-1 do begin
fComponents[Index].SetMaxEntities(fMaxEntityIndex);
end;
OldCount:=length(fEntities);
Count:=fEntityIndexCounter;
if OldCount<Count then begin
SetLength(fEntities,Count+((Count+1) shr 1));
for Index:=OldCount to length(fEntities)-1 do begin
Entity:=@fEntities[Index];
Entity^.fWorld:=self;
Entity^.fID:=0;
Entity^.fFlags:=[];
Entity^.fUUID:=TpvUUID.Null;
Entity^.fUnknownData:=nil;
Entity^.fCountComponents:=0;
Entity^.fComponentsBitmap:=nil;
end;
end;
OldCount:=length(fEntityGenerationList);
Count:=fEntityIndexCounter;
if OldCount<Count then begin
SetLength(fEntityGenerationList,Count+((Count+1) shr 1));
for Index:=OldCount to length(fEntityGenerationList)-1 do begin
fEntityGenerationList[Index]:=0;
end;
end;
OldCount:=length(fEntityUsedBitmap);
Count:=(fEntityIndexCounter+31) shr 5;
if OldCount<Count then begin
SetLength(fEntityUsedBitmap,Count+((Count+1) shr 1));
for Index:=OldCount to length(fEntityUsedBitmap)-1 do begin
fEntityUsedBitmap[Index]:=0;
end;
end;
end;
Bitmap:=@fEntityUsedBitmap[EntityIndex shr 5];
Bitmap^:=Bitmap^ or TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31));
Entity:=@fEntities[EntityIndex];
Entity^.fWorld:=self;
Entity^.fID:=aEntityID;
Entity^.fFlags:=[TEntity.TFlag.Used];
Entity^.fUUID:=aEntityUUID;
Entity^.fUnknownData:=nil;
Entity^.fCountComponents:=0;
Entity^.fComponentsBitmap:=nil;
fEntityUUIDHashMap.Add(aEntityUUID,aEntityID);
result:=true;
finally
fLock.WriteToRead;
end;
finally
fLock.ReleaseRead;
end;
end;
function TpvEntityComponentSystem.TWorld.DoDestroyEntity(const aEntityID:TEntityID):boolean;
var EntityIndex:TpvInt32;
Index:TpvSizeInt;
Bitmap:PpvUInt32;
Mask:TpvUInt32;
Entity:PEntity;
begin
fLock.AcquireRead;
try
EntityIndex:=aEntityID.Index;
Bitmap:=@fEntityUsedBitmap[EntityIndex shr 5];
Mask:=TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31));
if (EntityIndex>=0) and (EntityIndex<fEntityIndexCounter) and ((Bitmap^ and Mask)<>0) then begin
fLock.ReadToWrite;
try
Bitmap:=@fEntityUsedBitmap[EntityIndex shr 5]; // the pointer of fEntityIDUsedBitmap could be changed already here by an another CPU thread, so reload it
Bitmap^:=Bitmap^ and not Mask;
for Index:=0 to fComponents.Count-1 do begin
fComponents[Index].FreeComponentFromEntityIndex(EntityIndex);
end;
Entity:=@fEntities[EntityIndex];
fEntityUUIDHashMap.Delete(Entity^.UUID);
fReservedEntityHashMapLock.AcquireWrite;
try
fReservedEntityUUIDHashMap.Delete(Entity^.UUID);
finally
fReservedEntityHashMapLock.ReleaseWrite;
end;
Entity^.Flags:=[];
FreeAndNil(Entity^.fUnknownData);
Entity^.fCountComponents:=0;
Entity^.fComponentsBitmap:=nil;
fEntityLock.AcquireWrite;
try
fEntityIndexFreeList.Add(EntityIndex);
inc(fEntityGenerationList[EntityIndex]);
finally
fEntityLock.ReleaseWrite;
end;
finally
fLock.WriteToRead;
end;
result:=true;
end else begin
result:=false;
end;
finally
fLock.ReleaseRead;
end;
end;
procedure TpvEntityComponentSystem.TWorld.ProcessEvent(const aEvent:PEvent);
begin
end;
procedure TpvEntityComponentSystem.TWorld.ProcessEvents;
begin
end;
procedure TpvEntityComponentSystem.TWorld.ProcessDelayedEvents(const aDeltaTime:TTime);
begin
end;
procedure TpvEntityComponentSystem.TWorld.Kill;
begin
end;
function TpvEntityComponentSystem.TWorld.CreateEvent(const aName:TpvUTF8String):TEventID;
var EventRegistration:TEventRegistration;
begin
fEventRegistrationLock.AcquireWrite;
try
result:=fEventRegistrationStringIntegerPairHashMap.Values[aName];
if result<0 then begin
if fFreeEventRegistrationList.Count>0 then begin
EventRegistration:=fFreeEventRegistrationList[fFreeEventRegistrationList.Count-1];
fFreeEventRegistrationList.Delete(fFreeEventRegistrationList.Count-1);
EventRegistration.Clear;
EventRegistration.fName:=aName;
end else begin
EventRegistration:=TEventRegistration.Create(fEventRegistrationList.Count,aName);
fEventRegistrationList.Add(EventRegistration);
end;
EventRegistration.fActive:=true;
result:=EventRegistration.fEventID;
fEventRegistrationStringIntegerPairHashMap.Add(aName,result);
end;
finally
fEventRegistrationLock.ReleaseWrite;
end;
end;
procedure TpvEntityComponentSystem.TWorld.DestroyEvent(const aEventID:TEventID);
var EventRegistration:TEventRegistration;
begin
fEventRegistrationLock.AcquireWrite;
try
if (aEventID>=0) and (aEventID<fEventRegistrationList.Count) then begin
EventRegistration:=fEventRegistrationList.Items[aEventID];
if EventRegistration.fActive then begin
fEventRegistrationStringIntegerPairHashMap.Delete(EventRegistration.fName);
EventRegistration.fActive:=false;
EventRegistration.fName:='';
EventRegistration.Clear;
fFreeEventRegistrationList.Add(EventRegistration);
end;
end;
finally
fEventRegistrationLock.ReleaseWrite;
end;
end;
function TpvEntityComponentSystem.TWorld.FindEvent(const aName:TpvUTF8String):TEventID;
begin
fEventRegistrationLock.AcquireRead;
try
result:=fEventRegistrationStringIntegerPairHashMap.Values[aName];
finally
fEventRegistrationLock.ReleaseRead;
end;
end;
procedure TpvEntityComponentSystem.TWorld.SubscribeToEvent(const aEventID:TEventID;const aEventHandler:TEventHandler);
var EventRegistration:TEventRegistration;
begin
fEventRegistrationLock.AcquireWrite;
try
if (aEventID>=0) and (aEventID<fEventRegistrationList.Count) then begin
EventRegistration:=fEventRegistrationList.Items[aEventID];
if EventRegistration.fActive then begin
EventRegistration.AddEventHandler(aEventHandler);
end;
end;
finally
fEventRegistrationLock.ReleaseWrite;
end;
end;
procedure TpvEntityComponentSystem.TWorld.UnsubscribeFromEvent(const aEventID:TEventID;const aEventHandler:TEventHandler);
var EventRegistration:TEventRegistration;
begin
fEventRegistrationLock.AcquireWrite;
try
if (aEventID>=0) and (aEventID<fEventRegistrationList.Count) then begin
EventRegistration:=fEventRegistrationList.Items[aEventID];
if EventRegistration.fActive then begin
EventRegistration.RemoveEventHandler(aEventHandler);
end;
end;
finally
fEventRegistrationLock.ReleaseWrite;
end;
end;
function TpvEntityComponentSystem.TWorld.CreateEntity(const aEntityID:TpvEntityComponentSystem.TEntityID;const aEntityUUID:TpvUUID):TpvEntityComponentSystem.TEntityID;
var DelayedManagementEvent:TDelayedManagementEvent;
Index,OldCount,Count:TpvSizeInt;
EntityUUID:PpvUUID;
AutoGeneratedUUID:TpvUUID;
UUIDIsUnused:boolean;
begin
result:=0;
fReservedEntityHashMapLock.AcquireRead;
try
if UUID=TpvUUID.Null then begin
repeat
AutoGeneratedUUID:=TpvUUID.Create;
until not fReservedEntityUUIDHashMap.ExistKey(AutoGeneratedUUID);
EntityUUID:=@AutoGeneratedUUID;
UUIDIsUnused:=true;
end else begin
EntityUUID:=@UUID;
UUIDIsUnused:=not fReservedEntityUUIDHashMap.ExistKey(EntityUUID^);
end;
if UUIDIsUnused then begin
result:=aEntityID;
if aEntityID.Index<=0 then begin
fReservedEntityHashMapLock.ReadToWrite;
try
fEntityLock.AcquireWrite;
try
if fEntityIndexFreeList.Count>0 then begin
result.Index:=fEntityIndexFreeList.Items[fEntityIndexFreeList.Count-1];
fEntityIndexFreeList.Delete(fEntityIndexFreeList.Count-1);
end else begin
result.Index:=fEntityIndexCounter;
inc(fEntityIndexCounter);
end;
OldCount:=length(fEntityGenerationList);
Count:=fEntityIndexCounter;
if OldCount<Count then begin
SetLength(fEntityGenerationList,Count+((Count+1) shr 1));
for Index:=OldCount to length(fEntityGenerationList)-1 do begin
fEntityGenerationList[Index]:=0;
end;
end;
result.Generation:=fEntityGenerationList[Index] and $ff;
finally
fEntityLock.ReleaseWrite;
end;
fReservedEntityUUIDHashMap.Add(EntityUUID^,result);
finally
fReservedEntityHashMapLock.WriteToRead;
end;
end else begin
fReservedEntityHashMapLock.ReadToWrite;
try
fEntityLock.AcquireWrite;
try
if fEntityIndexFreeList.IndexOf(result.Index)>=0 then begin
fEntityIndexFreeList.Remove(result.Index);
end;
fEntityIndexCounter:=Max(fEntityIndexCounter,result.Index+1);
finally
fEntityLock.ReleaseWrite;
end;
fReservedEntityUUIDHashMap.Add(EntityUUID^,result);
finally
fReservedEntityHashMapLock.WriteToRead;
end;
end;
end;
finally
fReservedEntityHashMapLock.ReleaseRead;
end;
if result.Index>=0 then begin
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.CreateEntity;
DelayedManagementEvent.EntityID:=result;
DelayedManagementEvent.UUID:=EntityUUID^;
AddDelayedManagementEvent(DelayedManagementEvent);
end;
end;
function TpvEntityComponentSystem.TWorld.CreateEntity(const aEntityUUID:TpvUUID):TpvEntityComponentSystem.TEntityID;
var DelayedManagementEvent:TDelayedManagementEvent;
Index,OldCount,Count:TpvSizeInt;
EntityUUID:PpvUUID;
UUID,AutoGeneratedUUID:TpvUUID;
UUIDIsUnused:boolean;
begin
result:=0;
fReservedEntityHashMapLock.AcquireRead;
try
UUID:=aEntityUUID;
if UUID=TpvUUID.Null then begin
repeat
AutoGeneratedUUID:=TpvUUID.Create;
until not fReservedEntityUUIDHashMap.ExistKey(AutoGeneratedUUID);
EntityUUID:=@AutoGeneratedUUID;
UUIDIsUnused:=true;
end else begin
EntityUUID:=@UUID;
UUIDIsUnused:=not fReservedEntityUUIDHashMap.ExistKey(EntityUUID^);
end;
if UUIDIsUnused then begin
fReservedEntityHashMapLock.ReadToWrite;
try
fEntityLock.AcquireWrite;
try
if fEntityIndexFreeList.Count>0 then begin
result.Index:=fEntityIndexFreeList.Items[fEntityIndexFreeList.Count-1];
fEntityIndexFreeList.Delete(fEntityIndexFreeList.Count-1);
end else begin
result.Index:=fEntityIndexCounter;
inc(fEntityIndexCounter);
end;
OldCount:=length(fEntityGenerationList);
Count:=fEntityIndexCounter;
if OldCount<Count then begin
SetLength(fEntityGenerationList,Count+((Count+1) shr 1));
for Index:=OldCount to length(fEntityGenerationList)-1 do begin
fEntityGenerationList[Index]:=0;
end;
end;
result.Generation:=fEntityGenerationList[Index] and $ff;
finally
fEntityLock.ReleaseWrite;
end;
fReservedEntityUUIDHashMap.Add(EntityUUID^,result);
finally
fReservedEntityHashMapLock.WriteToRead;
end;
end;
finally
fReservedEntityHashMapLock.ReleaseRead;
end;
if result<>0 then begin
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.CreateEntity;
DelayedManagementEvent.EntityID:=result;
DelayedManagementEvent.UUID:=EntityUUID^;
AddDelayedManagementEvent(DelayedManagementEvent);
end;
end;
function TpvEntityComponentSystem.TWorld.CreateEntity:TEntityID; overload;
begin
result:=CreateEntity(TpvUUID.Null);
end;
function TpvEntityComponentSystem.TWorld.HasEntity(const aEntityID:TpvEntityComponentSystem.TEntityID):boolean;
var EntityIndex:TpvInt32;
begin
EntityIndex:=aEntityID.Index;
fLock.AcquireRead;
try
result:=(EntityIndex>=0) and
(EntityIndex<=fMaxEntityIndex) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) and
(fEntities[EntityIndex].fID=aEntityID);
finally
fLock.ReleaseRead;
end;
end;
function TpvEntityComponentSystem.TWorld.IsEntityActive(const aEntityID:TpvEntityComponentSystem.TEntityID):boolean;
var EntityIndex:TpvInt32;
begin
EntityIndex:=aEntityID.Index;
fLock.AcquireRead;
try
result:=(EntityIndex>=0) and
(EntityIndex<=fMaxEntityIndex) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) and
(fEntities[EntityIndex].fID=aEntityID) and
(TpvEntityComponentSystem.TEntity.TFlag.Active in fEntities[EntityIndex].fFlags);
finally
fLock.ReleaseRead;
end;
end;
procedure TpvEntityComponentSystem.TWorld.ActivateEntity(const aEntityID:TEntityID);
var DelayedManagementEvent:TDelayedManagementEvent;
begin
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.ActivateEntity;
DelayedManagementEvent.EntityID:=aEntityID;
AddDelayedManagementEvent(DelayedManagementEvent);
end;
procedure TpvEntityComponentSystem.TWorld.DeactivateEntity(const aEntityID:TEntityID);
var DelayedManagementEvent:TDelayedManagementEvent;
begin
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.DeactivateEntity;
DelayedManagementEvent.EntityID:=aEntityID;
AddDelayedManagementEvent(DelayedManagementEvent);
end;
procedure TpvEntityComponentSystem.TWorld.KillEntity(const aEntityID:TEntityID);
var DelayedManagementEvent:TDelayedManagementEvent;
begin
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.DeactivateEntity;
DelayedManagementEvent.EntityID:=aEntityID;
AddDelayedManagementEvent(DelayedManagementEvent);
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.KillEntity;
AddDelayedManagementEvent(DelayedManagementEvent);
end;
procedure TpvEntityComponentSystem.TWorld.AddComponentToEntity(const aEntityID:TEntityID;const aComponentID:TComponentID);
var DelayedManagementEvent:TDelayedManagementEvent;
begin
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.AddComponentToEntity;
DelayedManagementEvent.EntityID:=aEntityID;
DelayedManagementEvent.ComponentID:=aComponentID;
AddDelayedManagementEvent(DelayedManagementEvent);
end;
procedure TpvEntityComponentSystem.TWorld.RemoveComponentFromEntity(const aEntityID:TEntityID;const aComponentID:TComponentID);
var DelayedManagementEvent:TDelayedManagementEvent;
begin
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.RemoveComponentFromEntity;
DelayedManagementEvent.EntityID:=aEntityID;
DelayedManagementEvent.ComponentID:=aComponentID;
AddDelayedManagementEvent(DelayedManagementEvent);
end;
function TpvEntityComponentSystem.TWorld.HasEntityComponent(const aEntityID:TEntityID;const aComponentID:TComponentID):boolean;
var EntityIndex:TpvInt32;
begin
EntityIndex:=aEntityID.Index;
fLock.AcquireRead;
try
result:=(EntityIndex>=0) and
(EntityIndex<=fMaxEntityIndex) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) and
(fEntities[EntityIndex].fID=aEntityID) and
fComponents[aComponentID].IsComponentInEntityIndex(EntityIndex);
finally
fLock.ReleaseRead;
end;
end;
procedure TpvEntityComponentSystem.TWorld.AddSystem(const aSystem:TSystem);
var DelayedManagementEvent:TDelayedManagementEvent;
begin
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.AddSystem;
DelayedManagementEvent.System:=aSystem;
AddDelayedManagementEvent(DelayedManagementEvent);
end;
procedure TpvEntityComponentSystem.TWorld.RemoveSystem(const aSystem:TSystem);
var DelayedManagementEvent:TDelayedManagementEvent;
begin
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.RemoveSystem;
DelayedManagementEvent.System:=aSystem;
AddDelayedManagementEvent(DelayedManagementEvent);
end;
procedure TpvEntityComponentSystem.TWorld.SortSystem(const aSystem:TSystem);
var DelayedManagementEvent:TDelayedManagementEvent;
begin
DelayedManagementEvent.EventType:=TpvEntityComponentSystem.TDelayedManagementEventType.SortSystem;
DelayedManagementEvent.System:=aSystem;
AddDelayedManagementEvent(DelayedManagementEvent);
end;
procedure TpvEntityComponentSystem.TWorld.Defragment;
begin
end;
procedure TpvEntityComponentSystem.TWorld.Refresh;
var DelayedManagementEventIndex,Index,EntityIndex:TpvSizeInt;
DelayedManagementEvent:PDelayedManagementEvent;
EntityID:TEntityID;
Entity:PEntity;
Component:TpvEntityComponentSystem.TComponent;
System:TpvEntityComponentSystem.TSystem;
EntitiesWereAdded,EntitiesWereRemoved,WasActive:boolean;
begin
EntitiesWereAdded:=false;
EntitiesWereRemoved:=false;
fDelayedManagementEventLock.AcquireRead;
try
DelayedManagementEventIndex:=0;
while DelayedManagementEventIndex<fCountDelayedManagementEvents do begin
DelayedManagementEvent:=@fDelayedManagementEvents[DelayedManagementEventIndex];
inc(DelayedManagementEventIndex);
case DelayedManagementEvent^.EventType of
TpvEntityComponentSystem.TDelayedManagementEventType.CreateEntity:begin
EntityID:=DelayedManagementEvent^.EntityID;
EntityIndex:=EntityID.Index;
if (EntityIndex>=0) and (EntityIndex<fEntityIndexCounter) then begin
DoCreateEntity(EntityID,DelayedManagementEvent^.UUID);
end;
end;
TpvEntityComponentSystem.TDelayedManagementEventType.ActivateEntity:begin
EntityID:=DelayedManagementEvent^.EntityID;
EntityIndex:=EntityID.Index;
if (EntityIndex>=0) and
(EntityIndex<fEntityIndexCounter) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) and
not (TpvEntityComponentSystem.TEntity.TFlag.Active in fEntities[EntityIndex].Flags) then begin
for Index:=0 to fSystems.Count-1 do begin
System:=fSystems.Items[Index];
if System.FitsEntityToSystem(EntityID) then begin
System.AddEntityToSystem(EntityID);
EntitiesWereAdded:=true;
end;
end;
Include(fEntities[EntityID].fFlags,TpvEntityComponentSystem.TEntity.TFlag.Active);
end;
end;
TpvEntityComponentSystem.TDelayedManagementEventType.DeactivateEntity:begin
EntityID:=DelayedManagementEvent^.EntityID;
EntityIndex:=EntityID.Index;
if (EntityIndex>=0) and
(EntityIndex<fEntityIndexCounter) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) and
(TpvEntityComponentSystem.TEntity.TFlag.Active in fEntities[EntityIndex].Flags) then begin
Exclude(fEntities[EntityID].fFlags,TpvEntityComponentSystem.TEntity.TFlag.Active);
for Index:=0 to fSystems.Count-1 do begin
System:=fSystems.Items[Index];
System.RemoveEntityFromSystem(EntityID);
EntitiesWereRemoved:=true;
end;
end;
end;
TpvEntityComponentSystem.TDelayedManagementEventType.KillEntity:begin
EntityID:=DelayedManagementEvent^.EntityID;
EntityIndex:=EntityID.Index;
if (EntityIndex>=0) and
(EntityIndex<fEntityIndexCounter) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) then begin
for Index:=0 to fSystems.Count-1 do begin
System:=fSystems.Items[Index];
System.RemoveEntityFromSystem(EntityID);
EntitiesWereRemoved:=true;
end;
fDelayedManagementEventLock.ReleaseRead;
try
DoDestroyEntity(EntityID);
finally
fDelayedManagementEventLock.AcquireRead;
end;
end;
end;
TpvEntityComponentSystem.TDelayedManagementEventType.AddComponentToEntity:begin
EntityID:=DelayedManagementEvent^.EntityID;
EntityIndex:=EntityID.Index;
if (EntityIndex>=0) and
(EntityIndex<fEntityIndexCounter) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) then begin
if{(DelayedManagementEvent^.ComponentID>=0) and}(DelayedManagementEvent^.ComponentID<fComponents.Count) then begin
Component:=fComponents[DelayedManagementEvent^.ComponentID];
end else begin
Component:=nil;
end;
if assigned(Component) and (not Component.IsComponentInEntityIndex(EntityIndex)) and Component.AllocateComponentForEntityIndex(EntityIndex) then begin
WasActive:=TpvEntityComponentSystem.TEntity.TFlag.Active in fEntities[EntityIndex].Flags;
if WasActive then begin
for Index:=0 to fSystems.Count-1 do begin
System:=fSystems.Items[Index];
System.RemoveEntityFromSystem(EntityID);
EntitiesWereRemoved:=true;
end;
end;
Entity:=@fEntities[EntityIndex];
Entity^.AddComponentToEntity(DelayedManagementEvent^.ComponentID);
if WasActive then begin
for Index:=0 to fSystems.Count-1 do begin
System:=TSystem(fSystems.Items[Index]);
if System.FitsEntityToSystem(EntityID) then begin
System.AddEntityToSystem(EntityID);
EntitiesWereAdded:=true;
end;
end;
end;
end;
end;
end;
TpvEntityComponentSystem.TDelayedManagementEventType.RemoveComponentFromEntity:begin
EntityID:=DelayedManagementEvent^.EntityID;
EntityIndex:=EntityID.Index;
if (EntityIndex>=0) and
(EntityIndex<fEntityIndexCounter) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) then begin
if{(DelayedManagementEvent^.ComponentID>=0) and}(DelayedManagementEvent^.ComponentID<fComponents.Count) then begin
Component:=fComponents[DelayedManagementEvent^.ComponentID];
end else begin
Component:=nil;
end;
if assigned(Component) and Component.IsComponentInEntityIndex(EntityIndex) and Component.FreeComponentFromEntityIndex(EntityIndex) then begin
WasActive:=TpvEntityComponentSystem.TEntity.TFlag.Active in fEntities[EntityIndex].Flags;
if WasActive then begin
for Index:=0 to fSystems.Count-1 do begin
System:=fSystems.Items[Index];
System.RemoveEntityFromSystem(EntityID);
EntitiesWereRemoved:=true;
end;
end;
Entity:=@fEntities[EntityIndex];
Entity^.RemoveComponentFromEntity(DelayedManagementEvent^.ComponentID);
if WasActive then begin
for Index:=0 to fSystems.Count-1 do begin
System:=TSystem(fSystems.Items[Index]);
if System.FitsEntityToSystem(EntityID) then begin
System.AddEntityToSystem(EntityID);
EntitiesWereAdded:=true;
end;
end;
end;
end;
end;
end;
TpvEntityComponentSystem.TDelayedManagementEventType.AddSystem:begin
System:=DelayedManagementEvent^.System;
if not fSystemUsedMap.Values[System] then begin
fSystemUsedMap.Add(System,true);
fSystems.Add(System);
InterlockedExchange(fSystemChoreographyNeedToRebuild,-1);
for EntityIndex:=0 to fEntityIndexCounter-1 do begin
if (EntityIndex>=0) and
(EntityIndex<fEntityIndexCounter) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl longword(EntityIndex and 31)))<>0) and
(TpvEntityComponentSystem.TEntity.TFlag.Active in fEntities[EntityIndex].Flags) and
System.FitsEntityToSystem(fEntities[EntityIndex].fID) then begin
System.AddEntityToSystem(fEntities[EntityIndex].fID);
EntitiesWereAdded:=true;
end;
end;
System.Added;
end;
end;
TpvEntityComponentSystem.TDelayedManagementEventType.RemoveSystem:begin
System:=DelayedManagementEvent^.System;
if fSystemUsedMap.Values[System] then begin
System.Removed;
fSystemUsedMap.Delete(System);
fSystems.Remove(System);
InterlockedExchange(fSystemChoreographyNeedToRebuild,-1);
end;
end;
TpvEntityComponentSystem.TDelayedManagementEventType.SortSystem:begin
System:=DelayedManagementEvent^.System;
if fSystemUsedMap.Values[System] then begin
System.SortEntities;
end;
end;
end;
end;
fDelayedManagementEventLock.ReadToWrite;
try
fCountDelayedManagementEvents:=0;
finally
fDelayedManagementEventLock.WriteToRead;
end;
finally
fDelayedManagementEventLock.ReleaseRead;
end;
if EntitiesWereAdded then begin
end;
if EntitiesWereRemoved then begin
end;
end;
procedure TpvEntityComponentSystem.TWorld.QueueEvent(const aEventToQueue:TpvEntityComponentSystem.TEvent;const aDeltaTime:TpvTime);
var ParameterIndex:TpvSizeInt;
Event:TpvEntityComponentSystem.PEvent;
begin
fFreeEventQueueLock.AcquireWrite;
try
Event:=LinkedListPopFront(@fFreeEventQueue);
finally
fFreeEventQueueLock.ReleaseWrite;
end;
if not assigned(Event) then begin
GetMem(Event,SizeOf(TEvent));
FillChar(Event^,SizeOf(TEvent),#0);
fEventListLock.AcquireWrite;
try
fEventList.Add(Event);
finally
fEventListLock.ReleaseWrite;
end;
end;
LinkedListInitialize(pointer(Event));
if aDeltaTime>0 then begin
fDelayedEventQueueLock.AcquireWrite;
try
LinkedListPushBack(@fDelayedEventQueue,pointer(Event));
finally
fDelayedEventQueueLock.ReleaseWrite;
end;
end else begin
fEventQueueLock.AcquireWrite;
try
LinkedListPushBack(@fEventQueue,pointer(Event));
finally
fEventQueueLock.ReleaseWrite;
end;
end;
Event^.TimeStamp:=fCurrentTime+aDeltaTime;
Event^.RemainingTime:=aDeltaTime;
Event^.EventID:=aEventToQueue.EventID;
Event^.EntityID:=aEventToQueue.EntityID;
Event^.CountParameters:=aEventToQueue.CountParameters;
if length(Event^.Parameters)<Event^.CountParameters then begin
SetLength(Event^.Parameters,Event^.CountParameters*2);
end;
for ParameterIndex:=0 to Event^.CountParameters-1 do begin
Event^.Parameters[ParameterIndex]:=aEventToQueue.Parameters[ParameterIndex];
end;
if assigned(fOnEvent) then begin
fOnEvent(self,Event^);
end;
end;
procedure TpvEntityComponentSystem.TWorld.QueueEvent(const aEventToQueue:TpvEntityComponentSystem.TEvent);
begin
QueueEvent(aEventToQueue,1.0e-18); // one femtosecond
end;
procedure TpvEntityComponentSystem.TWorld.Update(const aDeltaTime:TpvTime);
var SystemIndex:TpvSizeInt;
System:TSystem;
begin
for SystemIndex:=0 to fSystems.Count-1 do begin
System:=fSystems.Items[SystemIndex];
System.fCountEvents:=0;
System.fDeltaTime:=aDeltaTime;
end;
ProcessEvents;
if InterlockedCompareExchange(fSystemChoreographyNeedToRebuild,0,-1)<0 then begin
fSystemChoreography.Build;
end;
fSystemChoreography.ProcessEvents;
fSystemChoreography.InitializeUpdate;
fSystemChoreography.Update;
fSystemChoreography.FinalizeUpdate;
fCurrentTime:=fCurrentTime+aDeltaTime;
ProcessDelayedEvents(aDeltaTime);
Refresh;
end;
procedure TpvEntityComponentSystem.TWorld.Clear;
var EntityIndex,SystemIndex:TpvSizeInt;
begin
fLock.AcquireRead;
try
if fEntityIndexCounter>0 then begin
fLock.ReleaseRead;
try
for EntityIndex:=0 to fEntityIndexCounter-1 do begin
if (fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0 then begin
KillEntity(fEntities[EntityIndex].fID);
end;
end;
Refresh;
finally
fLock.AcquireRead;
end;
end;
if fSystems.Count>0 then begin
fLock.ReleaseRead;
try
for SystemIndex:=0 to fSystems.Count-1 do begin
RemoveSystem(fSystems.Items[SystemIndex]);
end;
Refresh;
finally
fLock.AcquireRead;
end;
end;
finally
fLock.ReleaseRead;
end;
fEntityIndexCounter:=0;
fEntityUUIDHashMap.Clear;
fReservedEntityUUIDHashMap.Clear;
fEntityIndexFreeList.Clear;
end;
procedure TpvEntityComponentSystem.TWorld.ClearEntities;
var EntityIndex:TpvSizeInt;
begin
fLock.AcquireRead;
try
if fEntityIndexCounter>0 then begin
fLock.ReleaseRead;
try
for EntityIndex:=0 to fEntityIndexCounter-1 do begin
if (fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0 then begin
KillEntity(fEntities[EntityIndex].fID);
end;
end;
Refresh;
finally
fLock.AcquireRead;
end;
end;
finally
fLock.ReleaseRead;
end;
fEntityIndexCounter:=0;
fEntityUUIDHashMap.Clear;
fReservedEntityUUIDHashMap.Clear;
fEntityIndexFreeList.Clear;
end;
procedure TpvEntityComponentSystem.TWorld.Activate;
begin
fActive:=true;
end;
procedure TpvEntityComponentSystem.TWorld.Deactivate;
begin
fActive:=false;
end;
procedure TpvEntityComponentSystem.TWorld.MementoSerialize(const aStream:TStream);
var EntityIndex,ComponentIndex:TpvInt32;
ComponentID:TComponentID;
BitCounter:TpvInt32;
BitTag:TpvUInt8;
BitPosition:TpvInt64;
EntityID:TEntityID;
Entity:PEntity;
Component:TpvEntityComponentSystem.TComponent;
BufferedStream:TStream;
procedure WriteBit(const aValue:boolean);
var OldPosition:TpvInt64;
begin
if BitCounter>=8 then begin
if BitPosition>=0 then begin
OldPosition:=BufferedStream.Position;
if BufferedStream.Seek(BitPosition,soBeginning)<>BitPosition then begin
raise EInOutError.Create('Stream seek error');
end;
if BufferedStream.Write(BitTag,SizeOf(TpvUInt8))<>SizeOf(TpvUInt8) then begin
raise EInOutError.Create('Stream write error');
end;
if BufferedStream.Seek(OldPosition,soBeginning)<>OldPosition then begin
raise EInOutError.Create('Stream seek error');
end;
end;
BitTag:=0;
BitCounter:=0;
BitPosition:=BufferedStream.Position;
if BufferedStream.Write(BitTag,SizeOf(TpvUInt8))<>SizeOf(TpvUInt8) then begin
raise EInOutError.Create('Stream write error');
end;
end;
if aValue then begin
BitTag:=BitTag or (TpvUInt8(1) shl BitCounter);
end else begin
BitTag:=BitTag and not (TpvUInt8(1) shl BitCounter);
end;
inc(BitCounter);
end;
procedure FlushBits;
var OldPosition:TpvInt64;
begin
if BitPosition>=0 then begin
OldPosition:=BufferedStream.Position;
if BufferedStream.Seek(BitPosition,soBeginning)<>BitPosition then begin
raise EInOutError.Create('Stream seek error');
end;
if BufferedStream.Write(BitTag,SizeOf(TpvUInt8))<>SizeOf(TpvUInt8) then begin
raise EInOutError.Create('Stream write error');
end;
if BufferedStream.Seek(OldPosition,soBeginning)<>OldPosition then begin
raise EInOutError.Create('Stream seek error');
end;
end;
end;
procedure WriteUInt8(const aValue:TpvUInt8);
begin
if BufferedStream.Write(aValue,SizeOf(TpvUInt8))<>SizeOf(TpvUInt8) then begin
raise EInOutError.Create('Stream write error');
end;
end;
procedure WriteInt32(const aValue:TpvInt32);
begin
if BufferedStream.Write(aValue,SizeOf(TpvInt32))<>SizeOf(TpvInt32) then begin
raise EInOutError.Create('Stream write error');
end;
end;
begin
Refresh;
BufferedStream:=TMemoryStream.Create;
try
BitTag:=0;
BitCounter:=8;
BitPosition:=-1;
if BufferedStream.Write(fUUID,SizeOf(TpvUUID))<>SizeOf(TpvUUID) then begin
raise EInOutError.Create('Stream write error');
end;
WriteInt32(fEntityIndexCounter);
for EntityIndex:=0 to fEntityIndexCounter-1 do begin
if (EntityIndex>=0) and
(EntityIndex<=fMaxEntityIndex) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) then begin
EntityID:=fEntities[EntityIndex].fID;
WriteBit(true);
Entity:=@fEntities[EntityID];
WriteUInt8(EntityID.Generation);
WriteBit(Entity^.Active);
BufferedStream.Write(Entity^.fUUID,SizeOf(TpvUUID));
WriteInt32(Entity^.fCountComponents);
for ComponentIndex:=0 to Entity^.fCountComponents-1 do begin
ComponentID:=ComponentIndex;
if{(DelayedManagementEvent^.ComponentID>=0) and}(ComponentID<fComponents.Count) then begin
Component:=fComponents[ComponentID];
end else begin
Component:=nil;
end;
if assigned(Component) then begin
WriteBit(true);
BufferedStream.Write(Component.ComponentByEntityIndex[EntityIndex]^,Component.fSize);
end else begin
WriteBit(false);
end;
end;
end else begin
WriteBit(false);
end;
end;
FlushBits;
BufferedStream.Seek(0,soBeginning);
aStream.CopyFrom(BufferedStream,BufferedStream.Size);
finally
BufferedStream.Free;
end;
end;
procedure TpvEntityComponentSystem.TWorld.MementoUnserialize(const aStream:TStream);
var ComponentID:TComponentID;
EntityIndex,LocalEntityCounter,CountEntityComponents,
EntityComponentIndex,BitCounter:TpvInt32;
BitTag,Generation:TpvUInt8;
EntityID:TEntityID;
Entity:PEntity;
Component:TpvEntityComponentSystem.TComponent;
BufferedStream:TStream;
TempUUID:TpvUUID;
HasNewEntity,IsActive,HasNewComponent:boolean;
function ReadBit:boolean;
begin
if BitCounter>=8 then begin
BitTag:=0;
BitCounter:=0;
if BufferedStream.Read(BitTag,SizeOf(TpvUInt8))<>SizeOf(TpvUInt8) then begin
raise EInOutError.Create('Stream write error');
end;
end;
result:=(BitTag and (TpvUInt8(1) shl BitCounter))<>0;
inc(BitCounter);
end;
function ReadUInt8:TpvUInt8;
begin
if BufferedStream.Read(result,SizeOf(TpvUInt8))<>SizeOf(TpvUInt8) then begin
raise EInOutError.Create('Stream read error');
end;
end;
function ReadInt32:TpvInt32;
begin
if BufferedStream.Read(result,SizeOf(TpvInt32))<>SizeOf(TpvInt32) then begin
raise EInOutError.Create('Stream read error');
end;
end;
begin
Refresh;
aStream.Seek(0,soBeginning);
BufferedStream:=TMemoryStream.Create;
try
BufferedStream.CopyFrom(aStream,aStream.Size);
BufferedStream.Seek(0,soBeginning);
BitTag:=0;
BitCounter:=8;
if BufferedStream.Read(TempUUID,SizeOf(TpvUUID))<>SizeOf(TpvUUID) then begin
raise EInOutError.Create('Stream read error');
end;
LocalEntityCounter:=ReadInt32;
for EntityIndex:=0 to Max(LocalEntityCounter,fEntityIndexCounter)-1 do begin
if EntityIndex<LocalEntityCounter then begin
HasNewEntity:=ReadBit;
end else begin
HasNewEntity:=false;
end;
if HasNewEntity then begin
Generation:=ReadUInt8;
IsActive:=ReadBit;
if BufferedStream.Read(TempUUID,SizeOf(TpvUUID))<>SizeOf(TpvUUID) then begin
raise EInOutError.Create('Stream read error');
end;
if (EntityIndex>=0) and
(EntityIndex<=fMaxEntityIndex) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) then begin
Entity:=@fEntities[EntityIndex];
EntityID:=Entity^.ID;
if Generation<>EntityID.Generation then begin
fEntityUUIDHashMap.Delete(Entity.fUUID);
Entity.fUUID:=TempUUID;
fEntityUUIDHashMap.Add(Entity.fUUID,EntityID);
Entity^.ID.Generation:=Generation;
EntityID:=Entity^.ID;
end;
if TempUUID<>Entity.fUUID then begin
fEntityUUIDHashMap.Delete(Entity.fUUID);
Entity.fUUID:=TempUUID;
fEntityUUIDHashMap.Add(Entity.fUUID,EntityID);
end;
end else begin
EntityID.Index:=EntityIndex;
EntityID.Generation:=Generation;
EntityID:=CreateEntity(EntityID,TempUUID);
Refresh;
Entity:=@fEntities[EntityIndex];
end;
CountEntityComponents:=ReadInt32;
for EntityComponentIndex:=0 to Max(CountEntityComponents,Entity.fCountComponents)-1 do begin
if EntityComponentIndex<CountEntityComponents then begin
HasNewComponent:=ReadBit;
end else begin
HasNewComponent:=false;
end;
if HasNewComponent then begin
ComponentID:=EntityComponentIndex;
if{(ComponentID>=0) and}(ComponentID<fComponents.Count) then begin
Component:=fComponents[ComponentID];
end else begin
Component:=nil;
end;
if assigned(Component) then begin
if not Component.IsComponentInEntityIndex(EntityIndex) then begin
AddComponentToEntity(EntityID,ComponentID);
Refresh;
end;
BufferedStream.Read(Component.ComponentByEntityIndex[EntityIndex]^,Component.fSize);
end;
end else if EntityComponentIndex<Entity.fCountComponents then begin
ComponentID:=EntityComponentIndex;
if{(ComponentID>=0) and}(ComponentID<fComponents.Count) then begin
Component:=fComponents[ComponentID];
end else begin
Component:=nil;
end;
if assigned(Component) then begin
if Component.IsComponentInEntityIndex(EntityIndex) then begin
RemoveComponentFromEntity(EntityID,ComponentID);
Refresh;
end;
end;
end;
end;
if IsActive then begin
ActivateEntity(EntityID);
end else begin
DeactivateEntity(EntityID);
end;
Refresh;
end else begin
if (EntityIndex>=0) and
(EntityIndex<=fMaxEntityIndex) and
((fEntityUsedBitmap[EntityIndex shr 5] and TpvUInt32(TpvUInt32(1) shl TpvUInt32(EntityIndex and 31)))<>0) then begin
Entity:=@fEntities[EntityIndex];
EntityID:=Entity^.ID;
KillEntity(EntityID);
Refresh;
end;
end;
end;
Refresh;
finally
BufferedStream.Free;
end;
end;
procedure InitializeEntityComponentSystemGlobals;
begin
if not assigned(RegisteredComponentTypeList) then begin
RegisteredComponentTypeList:=TpvEntityComponentSystem.TRegisteredComponentTypeList.Create;
RegisteredComponentTypeList.OwnsObjects:=true;
end;
if not assigned(RegisteredComponentTypeNameHashMap) then begin
RegisteredComponentTypeNameHashMap:=TpvEntityComponentSystem.TRegisteredComponentTypeNameHashMap.Create(nil);
end;
end;
initialization
InitializeEntityComponentSystemGlobals;
finalization
FreeAndNil(RegisteredComponentTypeList);
FreeAndNil(RegisteredComponentTypeNameHashMap);
end.
|
{$INCLUDE switches}
unit UnitProcessing;
interface
uses
Protocol, Database;
type
TMoveType = (mtInvalid, mtMove, mtCapture, mtSpyMission, mtAttack, mtBombard, mtExpel);
TMoveInfo=record
MoveType: TMoveType;
Cost,
ToMaster,
EndHealth,
Defender,
Dcix,
Duix,
EndHealthDef: integer;
MountainDelay: boolean;
end;
var
uixSelectedTransport: integer;
Worked: array[0..nPl-1] of integer; {settler work statistics}
//Moving/Combat
function HostileDamage(p, mix, Loc, MP: integer): integer;
function CalculateMove(p,uix,ToLoc,MoveLength: integer; TestOnly: boolean;
var MoveInfo: TMoveInfo): integer;
function GetBattleForecast(Loc: integer; var BattleForecast: TBattleForecast;
var Duix,Dcix,AStr,DStr,ABaseDamage,DBaseDamage: integer): integer;
function LoadUnit(p,uix: integer; TestOnly: boolean): integer;
function UnloadUnit(p,uix: integer; TestOnly: boolean): integer;
procedure Recover(p,uix: integer);
function GetMoveAdvice(p,uix: integer; var a: TMoveAdviceData): integer;
function CanPlaneReturn(p,uix: integer; PlaneReturnData: TPlaneReturnData): boolean;
// Terrain Improvement
function StartJob(p,uix,NewJob: integer; TestOnly: boolean): integer;
function Work(p,uix: integer): boolean;
function GetJobProgress(p,Loc: integer; var JobProgressData: TJobProgressData): integer;
// Start/End Game
procedure InitGame;
procedure ReleaseGame;
implementation
uses
IPQ;
const
eMountains=$6000FFFF; // additional return code for server internal use
// tile control flags
coKnown=$02; coTrue=$04;
ContraJobs: array[0..nJob-1] of Set of 0..nJob-1=
([], //jNone
[jCity], //jRoad
[jCity], //jRR
[jCity,jTrans], //jClear
[jCity,jFarm,jAfforest,jMine,jBase,jFort], //jIrr
[jCity,jIrr,jAfforest,jMine,jBase,jFort], //jFarm
[jCity,jIrr,jFarm,jTrans], //jAfforest
[jCity,jTrans,jIrr,jFarm,jBase,jFort], //jMine
[jCity,jTrans], //jCanal
[jCity,jClear,jAfforest,jMine,jCanal], //jTrans
[jCity,jIrr,jFarm,jMine,jBase], //jFort
[jCity], //jPoll
[jCity,jIrr,jFarm,jMine,jFort], //jBase
[jCity], //jPillage
[jRoad..jPillage]); //jCity
type
TToWorkList = array[0..INFIN,0..nJob-1] of word;
var
ToWork: ^TToWorkList; {work left for each tile and job}
{
Moving/Combat
____________________________________________________________________
}
function HostileDamage(p, mix, Loc, MP: integer): integer;
var
Tile: integer;
begin
Tile:=RealMap[Loc];
if (RW[p].Model[mix].Domain>=dSea)
or (RW[p].Model[mix].Kind=mkSettler) and (RW[p].Model[mix].Speed>=200)
or (Tile and (fCity or fRiver or fCanal)<>0)
or (Tile and fTerImp=tiBase)
or (GWonder[woGardens].EffectiveOwner=p) then
result:=0
else if (Tile and fTerrain=fDesert)
and (Tile and fSpecial<>fSpecial1{Oasis}) then
begin
assert((Tile and fTerImp<>tiIrrigation) and (Tile and fTerImp<>tiFarm));
result:=(DesertThurst*MP-1) div RW[p].Model[mix].Speed +1
end
else if Tile and fTerrain=fArctic then
begin
assert((Tile and fTerImp<>tiIrrigation) and (Tile and fTerImp<>tiFarm));
result:=(ArcticThurst*MP-1) div RW[p].Model[mix].Speed +1
end
else result:=0
end;
function Controlled(p,Loc: integer; IsDest: boolean): integer;
{whether tile at Loc is in control zone of enemy unit
returns combination of tile control flags}
var
Loc1,V8: integer;
Adjacent: TVicinity8Loc;
begin
result:=0;
if IsDest and (Occupant[Loc]=p) and (ZoCMap[Loc]>0) then exit;
// destination tile, not controlled if already occupied
if (RealMap[Loc] and fCity=0)
or (integer(RealMap[Loc] shr 27)<>p) and (ServerVersion[p]>=$000EF0) then
begin // not own city
V8_to_Loc(Loc,Adjacent);
for V8:=0 to 7 do
begin
Loc1:=Adjacent[V8];
if (Loc1>=0) and (Loc1<MapSize)
and (ZoCMap[Loc1]>0)
and (Occupant[Loc1]>=0) and (Occupant[Loc1]<>p)
and (RW[p].Treaty[Occupant[Loc1]]<trAlliance) then
if ObserveLevel[Loc1] and (3 shl (p*2))>0 then
begin // p observes tile
result:=coKnown or coTrue;
exit
end
else result:=coTrue; // p does not observe tile
end;
end
end;
function GetMoveCost(p,mix,FromLoc,ToLoc,MoveLength: integer; var MoveCost: integer): integer;
// MoveLength - 2 for short move, 3 for long move
var
FromTile,ToTile: integer;
begin
result:=eOK;
FromTile:=RealMap[FromLoc];
ToTile:=RealMap[ToLoc];
with RW[p].Model[mix] do
begin
case Domain of
dGround:
if (ToTile and fTerrain>=fGrass) then {domain ok}
// if (Flags and mdCivil<>0) and (ToTile and fDeadLands<>0) then result:=eEerie
// else
begin {valid move}
if (FromTile and (fRR or fCity)<>0)
and (ToTile and (fRR or fCity)<>0) then
if GWonder[woShinkansen].EffectiveOwner=p then MoveCost:=0
else MoveCost:=Speed*(4*1311) shr 17 //move along railroad
else if (FromTile and (fRoad or fRR or fCity)<>0)
and (ToTile and (fRoad or fRR or fCity)<>0)
or (FromTile and ToTile and (fRiver or fCanal)<>0)
or (Cap[mcAlpine]>0) then
//move along road, river or canal
if Cap[mcOver]>0 then MoveCost:=40
else MoveCost:=20
else if Cap[mcOver]>0 then result:=eNoRoad
else case Terrain[ToTile and fTerrain].MoveCost of
1: MoveCost:=50; // plain terrain
2:
begin
assert(Speed-150<=600);
MoveCost:=50+(Speed-150)*13 shr 7; // heavy terrain
end;
3:
begin
MoveCost:=Speed;
result:=eMountains;
exit
end;
end;
MoveCost:=MoveCost*MoveLength;
end
else result:=eDomainMismatch;
dSea:
if (ToTile and (fCity or fCanal)<>0)
or (ToTile and fTerrain<fGrass) then {domain ok}
if (ToTile and fTerrain<>fOcean) or (Cap[mcNav]>0) then
MoveCost:=50*MoveLength {valid move}
else result:=eNoNav {navigation required for open sea}
else result:=eDomainMismatch;
dAir:
MoveCost:=50*MoveLength; {always valid move}
end
end
end;
function CalculateMove(p,uix,ToLoc,MoveLength: integer; TestOnly: boolean;
var MoveInfo: TMoveInfo): integer;
var
uix1,p1,FromLoc,DestControlled,AStr,DStr,ABaseDamage,DBaseDamage: integer;
PModel: ^TModel;
BattleForecast: TBattleForecast;
begin
with RW[p],Un[uix] do
begin
PModel:=@Model[mix];
FromLoc:=Loc;
BattleForecast.pAtt:=p;
BattleForecast.mixAtt:=mix;
BattleForecast.HealthAtt:=Health;
BattleForecast.ExpAtt:=Exp;
BattleForecast.FlagsAtt:=Flags;
BattleForecast.Movement:=Movement;
result:=GetBattleForecast(ToLoc,BattleForecast,MoveInfo.Duix,MoveInfo.Dcix,AStr,DStr,ABaseDamage,DBaseDamage);
if result=eHiddenUnit then
if TestOnly then result:=eOK // behave just like unit was moving
else if Mode>moLoading_Fast then
Map[ToLoc]:=Map[ToLoc] or fHiddenUnit;
if result=eStealthUnit then
if TestOnly then result:=eOK // behave just like unit was moving
else if Mode>moLoading_Fast then
Map[ToLoc]:=Map[ToLoc] or fStealthUnit;
if result<rExecuted then exit;
case result of
eOk: MoveInfo.MoveType:=mtMove;
eExpelled: MoveInfo.MoveType:=mtExpel;
else MoveInfo.MoveType:=mtAttack;
end;
if MoveInfo.MoveType=mtMove then
begin
if Mode=moPlaying then
begin
p1:=RealMap[ToLoc] shr 27;
if (p1<nPl) and (p1<>p)
and ((RealMap[Loc] shr 27<>Cardinal(p1))
and (PModel.Kind<>mkDiplomat)
and (Treaty[p1]>=trPeace) and (Treaty[p1]<trAlliance)
or (RealMap[ToLoc] and fCity<>0) and (Treaty[p1]>=trPeace)) then
begin result:=eTreaty; exit end; // keep peace treaty!
end;
if (RealMap[ToLoc] and fCity<>0)
and (RealMap[ToLoc] shr 27<>Cardinal(p)) then // empty enemy city
if PModel.Kind=mkDiplomat then
begin
MoveInfo.MoveType:=mtSpyMission;
end
else if PModel.Domain=dGround then
begin
if PModel.Flags and mdCivil<>0 then
begin result:=eNoCapturer; exit end;
MoveInfo.MoveType:=mtCapture;
end
else
begin
if (PModel.Domain=dSea) and (PModel.Cap[mcArtillery]=0) then
begin result:=eDomainMismatch; exit end
else if (PModel.Attack=0)
and not ((PModel.Cap[mcBombs]>0) and (Flags and unBombsLoaded<>0)) then
begin result:=eNoBombarder; exit end
else if Movement<100 then
begin result:=eNoTime_Bombard; exit end;
MoveInfo.MoveType:=mtBombard;
result:=eBombarded;
end
end;
MoveInfo.MountainDelay:=false;
if MoveInfo.MoveType in [mtAttack,mtBombard,mtExpel] then
begin
if (Master>=0)
or (PModel.Domain=dSea) and (RealMap[Loc] and fTerrain>=fGrass)
or (PModel.Domain=dAir) and ((RealMap[Loc] and fCity<>0)
or (RealMap[Loc] and fTerImp=tiBase)) then
begin result:=eViolation; exit end;
if MoveInfo.MoveType=mtBombard then
begin
MoveInfo.EndHealth:=Health;
MoveInfo.EndHealthDef:=-1;
end
else
begin
MoveInfo.EndHealth:=BattleForecast.EndHealthAtt;
MoveInfo.EndHealthDef:=BattleForecast.EndHealthDef;
end
end
else // if MoveInfo.MoveType in [mtMove,mtCapture,mtSpyMission] then
begin
if (Master>=0) and (PModel.Domain<dSea) then
begin // transport unload
MoveInfo.Cost:=PModel.Speed;
if RealMap[ToLoc] and fTerrain<fGrass then
result:=eDomainMismatch;
end
else
begin
result:=GetMoveCost(p,mix,FromLoc,ToLoc,MoveLength,MoveInfo.Cost);
if result=eMountains then
begin result:=eOk; MoveInfo.MountainDelay:=true end;
end;
if (result>=rExecuted) and (MoveInfo.MoveType=mtSpyMission) then
result:=eMissionDone;
MoveInfo.ToMaster:=-1;
if (result=eDomainMismatch) and (PModel.Domain<dSea)
and (PModel.Cap[mcOver]=0) then
begin
for uix1:=0 to nUn-1 do with Un[uix1] do // check load to transport
if (Loc=ToLoc)
and (TroopLoad<Model[mix].MTrans*Model[mix].Cap[mcSeaTrans]) then
begin
result:=eLoaded;
MoveInfo.Cost:=PModel.Speed;
MoveInfo.ToMaster:=uix1;
if (uixSelectedTransport>=0) and (uix1=uixSelectedTransport) then
Break;
end;
end
else if (PModel.Domain=dAir) and (PModel.Cap[mcAirTrans]=0)
and (RealMap[ToLoc] and fCity=0) and (RealMap[ToLoc] and fTerImp<>tiBase) then
begin
for uix1:=0 to nUn-1 do with Un[uix1] do
if (Loc=ToLoc)
and (AirLoad<Model[mix].MTrans*Model[mix].Cap[mcCarrier]) then
begin// load plane to ship
result:=eLoaded;
MoveInfo.ToMaster:=uix1;
if (uixSelectedTransport>=0) and (uix1=uixSelectedTransport) then
Break;
end
end;
if result<rExecuted then exit;
if (Master<0) and (MoveInfo.ToMaster<0) then
MoveInfo.EndHealth:=Health-HostileDamage(p,mix,ToLoc,MoveInfo.Cost)
else MoveInfo.EndHealth:=Health;
if (Mode=moPlaying)
and (PModel.Flags and mdZOC<>0)
and (Master<0) and (MoveInfo.ToMaster<0)
and (Controlled(p,FromLoc,false)>=coTrue) then
begin
DestControlled:=Controlled(p,ToLoc,true);
if DestControlled>=coTrue+coKnown then
begin result:=eZOC; exit end
else if not TestOnly and (DestControlled>=coTrue) then
begin result:=eZOC_EnemySpotted; exit end
end;
if (Movement=0) and (ServerVersion[p]>=$0100F1) or (MoveInfo.Cost>Movement) then
if (Master>=0) or (MoveInfo.ToMaster>=0) then
begin result:=eNoTime_Load; exit end
else begin result:=eNoTime_Move; exit end;
if (MoveInfo.EndHealth<=0) or (MoveInfo.MoveType=mtSpyMission) then
result:=result or rUnitRemoved; // spy mission or victim of HostileDamage
end; // if MoveInfo.MoveType in [mtMove,mtCapture,mtSpyMission]
if MoveInfo.MoveType in [mtAttack,mtExpel] then
MoveInfo.Defender:=Occupant[ToLoc]
else if RealMap[ToLoc] and fCity<>0 then
begin // MoveInfo.Dcix not set yet
MoveInfo.Defender:=RealMap[ToLoc] shr 27;
SearchCity(ToLoc,MoveInfo.Defender,MoveInfo.Dcix);
end
end
end; //CalculateMove
function GetBattleForecast(Loc: integer; var BattleForecast: TBattleForecast;
var Duix,Dcix,AStr,DStr,ABaseDamage,DBaseDamage: integer): integer;
var
Time,Defender,ABon,DBon,DCnt,MultiDamage: integer;
PModel,DModel: ^TModel;
begin
with BattleForecast do
begin
Defender:=Occupant[Loc];
if (Defender<0) or (Defender=pAtt) then
begin result:=eOK; exit end; // no attack, simple move
PModel:=@RW[pAtt].Model[mixAtt];
Strongest(Loc,Duix,DStr,DBon,DCnt); {get defense strength and bonus}
if (PModel.Kind=mkDiplomat) and (RealMap[Loc] and fCity<>0) then
begin // spy mission -- return as if move was possible
EndHealthAtt:=HealthAtt;
EndHealthDef:=RW[Defender].Un[Duix].Health;
result:=eOk;
exit
end;
DModel:=@RW[Defender].Model[RW[Defender].Un[Duix].mix];
if (RealMap[Loc] and fCity=0) and (RealMap[Loc] and fTerImp<>tiBase) then
begin
if (DModel.Cap[mcSub]>0)
and (RealMap[Loc] and fTerrain<fGrass)
and (ObserveLevel[Loc] shr (2*pAtt) and 3<lObserveAll) then
begin result:=eHiddenUnit; exit; end; //attacking submarine not allowed
if (DModel.Cap[mcStealth]>0)
and (ObserveLevel[Loc] shr (2*pAtt) and 3<>lObserveSuper) then
begin result:=eStealthUnit; exit; end; //attacking stealth aircraft not allowed
if (DModel.Domain=dAir) and (DModel.Kind<>mkSpecial_Glider)
and (PModel.Domain<>dAir) then
begin result:=eDomainMismatch; exit end; //can't attack plane
end;
if ((PModel.Cap[mcArtillery]=0)
or ((ServerVersion[pAtt]>=$010200) and (RealMap[Loc] and fTerrain<fGrass)
and (DModel.Cap[mcSub]>0))) // ground units can't attack submarines
and ((PModel.Domain=dGround) and (RealMap[Loc] and fTerrain<fGrass)
or (PModel.Domain=dSea) and (RealMap[Loc] and fTerrain>=fGrass)) then
begin result:=eDomainMismatch; exit end;
if (PModel.Attack=0)
and not ((PModel.Cap[mcBombs]>0) and (FlagsAtt and unBombsLoaded<>0)
and (DModel.Domain<dAir)) then
begin result:=eInvalid; exit end;
if Movement=0 then
begin result:=eNoTime_Attack; exit end;
{$IFOPT O-}assert(InvalidTreatyMap=0);{$ENDIF}
if RW[pAtt].Treaty[Defender]>=trPeace then
begin
if (PModel.Domain<>dAir)
and (PModel.Attack>0) and (integer(RealMap[Loc] shr 27)=pAtt) then
if Movement>=100 then
begin // expel friendly unit
EndHealthDef:=RW[Defender].Un[Duix].Health;
EndHealthAtt:=HealthAtt;
result:=eExpelled
end
else result:=eNoTime_Expel
else result:=eTreaty;
exit;
end;
// calculate defender strength
if RealMap[Loc] and fCity<>0 then
begin // consider city improvements
SearchCity(Loc,Defender,Dcix);
if (PModel.Domain<dSea) and (PModel.Cap[mcArtillery]=0)
and ((RW[Defender].City[Dcix].Built[imWalls]=1)
or (Continent[RW[Defender].City[Dcix].Loc]=GrWallContinent[Defender])) then
inc(DBon,8)
else if (PModel.Domain=dSea)
and (RW[Defender].City[Dcix].Built[imCoastalFort]=1) then
inc(DBon,4)
else if (PModel.Domain=dAir)
and (RW[Defender].City[Dcix].Built[imMissileBat]=1) then
inc(DBon,4);
if RW[Defender].City[Dcix].Built[imBunker]=1 then
inc(DBon,4)
end;
if (PModel.Domain=dAir) and (DModel.Cap[mcAirDef]>0) then
inc(DBon,4);
DStr:=DModel.Defense*DBon*100;
if (DModel.Domain=dAir) and ((RealMap[Loc] and fCity<>0)
or (RealMap[Loc] and fTerImp=tiBase)) then
DStr:=0;
if (DModel.Domain=dSea) and (RealMap[Loc] and fTerrain>=fGrass) then
DStr:=DStr shr 1;
// calculate attacker strength
if PModel.Cap[mcWill]>0 then Time:=100
else begin Time:=Movement; if Time>100 then Time:=100; end;
ABon:=4+ExpAtt div ExpCost;
AStr:=PModel.Attack;
if (FlagsAtt and unBombsLoaded<>0) and (DModel.Domain<dAir) then // use bombs
AStr:=AStr+PModel.Cap[mcBombs]*PModel.MStrength*2;
AStr:=Time*AStr*ABon;
// calculate base damage for defender
if DStr=0 then
DBaseDamage:=RW[Defender].Un[Duix].Health
else
begin
DBaseDamage:=HealthAtt*AStr div DStr;
if DBaseDamage=0 then
DBaseDamage:=1;
if DBaseDamage>RW[Defender].Un[Duix].Health then
DBaseDamage:=RW[Defender].Un[Duix].Health
end;
// calculate base damage for attacker
if AStr=0 then
ABaseDamage:=HealthAtt
else
begin
ABaseDamage:=RW[Defender].Un[Duix].Health*DStr div AStr;
if ABaseDamage=0 then
ABaseDamage:=1;
if ABaseDamage>HealthAtt then
ABaseDamage:=HealthAtt
end;
// calculate final damage for defender
MultiDamage:=2;
if (ABaseDamage=HealthAtt) and (PModel.Cap[mcFanatic]>0)
and not (RW[pAtt].Government in [gRepublic,gDemocracy,gFuture]) then
MultiDamage:=MultiDamage*2; // fanatic attacker died
EndHealthDef:=RW[Defender].Un[Duix].Health-MultiDamage*DBaseDamage div 2;
if EndHealthDef<0 then EndHealthDef:=0;
// calculate final damage for attacker
MultiDamage:=2;
if DBaseDamage=RW[Defender].Un[Duix].Health then
begin
if (DModel.Cap[mcFanatic]>0)
and not (RW[Defender].Government in [gRepublic,gDemocracy,gFuture]) then
MultiDamage:=MultiDamage*2; // fanatic defender died
if PModel.Cap[mcFirst]>0 then
MultiDamage:=MultiDamage shr 1; // first strike unit wins
end;
Time:=Movement; if Time>100 then Time:=100;
EndHealthAtt:=HealthAtt-MultiDamage*ABaseDamage div 2-HostileDamage(pAtt,mixAtt,Loc,Time);
if EndHealthAtt<0 then EndHealthAtt:=0;
if EndHealthDef>0 then result:=eLost
else if EndHealthAtt>0 then result:=eWon
else result:=eBloody
end
end; //GetBattleForecast
function LoadUnit(p,uix: integer; TestOnly: boolean): integer;
var
uix1,d,Cost,ToMaster: integer;
begin
result:=eOk;
with RW[p].Un[uix] do
begin
d:=RW[p].Model[mix].Domain;
if (Master>=0) or (d=dSea)
or (RW[p].Model[mix].Cap[mcAirTrans]
+RW[p].Model[mix].Cap[mcOver]>0) then
result:=eViolation
else
begin
ToMaster:=-1;
for uix1:=0 to RW[p].nUn-1 do if RW[p].Un[uix1].Loc=Loc then
with RW[p].Un[uix1], RW[p].Model[mix] do
if (d<dSea) and (TroopLoad<MTrans*(Cap[mcSeaTrans]+Cap[mcAirTrans]))
or (d=dAir) and (AirLoad<MTrans*Cap[mcCarrier]) then
begin {load onto unit uix1}
if (uixSelectedTransport<0) or (uix1=uixSelectedTransport) then
begin ToMaster:=uix1; Break end
else if ToMaster<0 then
ToMaster:=uix1;
end;
if ToMaster<0 then result:=eNoLoadCapacity
else
begin
if d=dAir then Cost:=100
else Cost:=RW[p].Model[mix].Speed;
if Movement<Cost then result:=eNoTime_Load
else if not TestOnly then
begin
FreeUnit(p,uix);
dec(Movement,Cost);
if d=dAir then inc(RW[p].Un[ToMaster].AirLoad)
else inc(RW[p].Un[ToMaster].TroopLoad);
Master:=ToMaster;
UpdateUnitMap(Loc);
end
end
end
end
end;
function UnloadUnit(p,uix: integer; TestOnly: boolean): integer;
var
Cost: integer;
begin
result:=eOk;
with RW[p].Un[uix] do
if Master<0 then result:=eNotChanged
else if (RW[p].Model[mix].Domain<dSea)
and (RealMap[Loc] and fTerrain<fGrass) then result:=eDomainMismatch
// else if (RW[p].Model[mix].Domain<dSea)
// and (RW[p].Model[mix].Flags and mdCivil<>0)
// and (RealMap[Loc] and fDeadLands<>0) then result:=eEerie
else
begin
if RW[p].Model[mix].Domain=dAir then Cost:=100
else Cost:=RW[p].Model[mix].Speed;
if Movement<Cost then result:=eNoTime_Load
else if not TestOnly then
begin
dec(Movement,Cost);
if RW[p].Model[mix].Domain=dAir then
dec(RW[p].Un[Master].AirLoad)
else
begin
dec(RW[p].Un[Master].TroopLoad);
// Movement:=0 // no more movement after unload
end;
Master:=-1;
PlaceUnit(p,uix);
UpdateUnitMap(Loc);
end;
end
end;
procedure Recover(p,uix: integer);
var
cix,Recovery: integer;
begin
with RW[p],Un[uix] do
begin
if (Master>=0) and (Model[Un[Master].mix].Cap[mcSupplyShip]>0) then
Recovery:=FastRecovery {hospital ship}
else if RealMap[Loc] and fTerImp=tiBase then
Recovery:=CityRecovery
else if RealMap[Loc] and fCity<>0 then
begin {unit in city}
cix:=nCity-1;
while (cix>=0) and (City[cix].Loc<>Loc) do dec(cix);
if City[cix].Flags and chDisorder<>0 then
Recovery:=NoCityRecovery
else if (Model[mix].Domain=dGround)
and (City[cix].Built[imBarracks]+City[cix].Built[imElite]>0)
or (Model[mix].Domain=dSea) and (City[cix].Built[imDockyard]=1)
or (Model[mix].Domain=dAir) and (City[cix].Built[imAirport]=1) then
Recovery:=FastRecovery {city has baracks/shipyard/airport}
else Recovery:=CityRecovery
end
else if (RealMap[Loc] and fTerrain>=fGrass) and (Model[mix].Domain<>dAir) then
Recovery:=NoCityRecovery
else Recovery:=0;
Recovery:=Recovery*Movement div Model[mix].Speed; {recovery depends on movement unused}
if Recovery>Health then Recovery:=Health; // health max. doubled each turn
if Recovery>100-Health then Recovery:=100-Health;
inc(Health,Recovery);
end;
end;
function GetMoveAdvice(p,uix: integer; var a: TMoveAdviceData): integer;
const
//domains
gmaAir=0; gmaSea=1; gmaGround_NoZoC=2; gmaGround_ZoC=3;
//flags
gmaNav=4; gmaOver=4; gmaAlpine=8;
var
i,FromLoc,EndLoc,T,T1,maxmov,initmov,Loc,Loc1,FromTile,ToTile,V8,
MoveInfo,HeavyCost,RailCost,MoveCost,AddDamage,MaxDamage,MovementLeft: integer;
Map: ^TTileList;
Q: TIPQ;
Adjacent: TVicinity8Loc;
From: array[0..lxmax*lymax-1] of integer;
Time: array[0..lxmax*lymax-1] of integer;
Damage: array[0..lxmax*lymax-1] of integer;
MountainDelay, Resistant: boolean;
// tt,tt0: int64;
begin
// QueryPerformanceCounter(tt0);
MaxDamage:=RW[p].Un[uix].Health-1;
if MaxDamage>a.MaxHostile_MovementLeft then
if a.MaxHostile_MovementLeft>=0 then
MaxDamage:=a.MaxHostile_MovementLeft
else MaxDamage:=0;
Map:=@(RW[p].Map^);
if (a.ToLoc<>maNextCity) and ((a.ToLoc<0) or (a.ToLoc>=MapSize)) then
begin result:=eInvalid; exit end;
if (a.ToLoc<>maNextCity) and (Map[a.ToLoc] and fTerrain=fUNKNOWN) then
begin result:=eNoWay; exit end;
with RW[p].Model[RW[p].Un[uix].mix] do
case Domain of
dGround:
if (a.ToLoc<>maNextCity) and (Map[a.ToLoc] and fTerrain=fOcean) then
begin result:=eDomainMismatch; exit end
else
begin
if Flags and mdZOC<>0 then MoveInfo:=gmaGround_ZoC
else MoveInfo:=gmaGround_NoZoC;
if Cap[mcOver]>0 then inc(MoveInfo,gmaOver);
if Cap[mcAlpine]>0 then inc(MoveInfo,gmaAlpine);
HeavyCost:=50+(Speed-150)*13 shr 7;
if GWonder[woShinkansen].EffectiveOwner=p then RailCost:=0
else RailCost:=Speed*(4*1311) shr 17;
maxmov:=Speed;
initmov:=0;
Resistant:= (GWonder[woGardens].EffectiveOwner=p) or
(Kind=mkSettler) and (Speed>=200);
end;
dSea:
if (a.ToLoc<>maNextCity) and (Map[a.ToLoc] and fTerrain>=fGrass)
and (Map[a.ToLoc] and (fCity or fUnit or fCanal)=0) then
begin result:=eDomainMismatch; exit end
else
begin
MoveInfo:=gmaSea;
if Cap[mcNav]>0 then inc(MoveInfo,gmaNav);
maxmov:=UnitSpeed(p,RW[p].Un[uix].mix,100);
initmov:=maxmov-UnitSpeed(p,RW[p].Un[uix].mix,
RW[p].Un[uix].Health);
end;
dAir:
begin
MoveInfo:=gmaAir;
maxmov:=Speed;
initmov:=0;
end
else
begin
MoveInfo:=gmaGround_NoZoC;
maxmov:=Speed;
end
end;
FromLoc:=RW[p].Un[uix].Loc;
FillChar(Time,SizeOf(Time),255); {-1}
Damage[FromLoc]:=0;
Q:=TIPQ.Create(MapSize);
Q.Put(FromLoc,(maxmov-RW[p].Un[uix].Movement) shl 8);
while Q.Get(Loc,T) do
begin
Time[Loc]:=T;
if T>=(a.MoreTurns+1) shl 20 then begin Loc:=-1; Break end;
FromTile:=Map[Loc];
if (Loc=a.ToLoc) or (a.ToLoc=maNextCity) and (FromTile and fCity<>0) then
Break;
if T and $FFF00=$FFF00 then inc(T,$100000); // indicates mountain delay
V8_to_Loc(Loc,Adjacent);
for V8:=0 to 7 do
begin
Loc1:=Adjacent[V8];
if (Loc1>=0) and (Loc1<MapSize) and (Time[Loc1]<0) then
begin
ToTile:=Map[Loc1];
if (Loc1=a.ToLoc) and (ToTile and (fUnit or fOwned)=fUnit)
and not ((MoveInfo and 3=gmaSea) and (FromTile and fTerrain>=fGrass))
and not ((MoveInfo and 3=gmaAir) and ((FromTile and fCity<>0)
or (FromTile and fTerImp=tiBase))) then
begin // attack position found
if Q.Put(Loc1,T+1) then From[Loc1]:=Loc;
end
else if (ToTile and fTerrain<>fUNKNOWN)
and ((Loc1=a.ToLoc) or (ToTile and (fCity or fOwned)<>fCity)) // don't move through enemy cities
and ((Loc1=a.ToLoc) or (ToTile and (fUnit or fOwned)<>fUnit)) // way is blocked
and (ToTile and not FromTile and fPeace=0)
and ((MoveInfo and 3<gmaGround_ZoC)
or (ToTile and FromTile and fInEnemyZoc=0)
or (ToTile and fOwnZoCUnit<>0)
or (FromTile and fCity<>0)
or (ToTile and (fCity or fOwned)=fCity or fOwned)) then
begin
// calculate move cost, must be identic to GetMoveCost function
AddDamage:=0;
MountainDelay:=false;
case MoveInfo of
gmaAir:
MoveCost:=50; {always valid move}
gmaSea:
if (ToTile and (fCity or fCanal)<>0)
or (ToTile and fTerrain=fShore) then {domain ok}
MoveCost:=50 {valid move}
else MoveCost:=-1;
gmaSea+gmaNav:
if (ToTile and (fCity or fCanal)<>0)
or (ToTile and fTerrain<fGrass) then {domain ok}
MoveCost:=50 {valid move}
else MoveCost:=-1;
else // ground unit
MoveCost:=-1;
if (ToTile and fTerrain>=fGrass) then {domain ok}
begin {valid move}
if (FromTile and (fRR or fCity)<>0)
and (ToTile and (fRR or fCity)<>0) then
MoveCost:=RailCost //move along railroad
else if (FromTile and (fRoad or fRR or fCity)<>0)
and (ToTile and (fRoad or fRR or fCity)<>0)
or (FromTile and ToTile and (fRiver or fCanal)<>0)
or (MoveInfo and gmaAlpine<>0) then
//move along road, river or canal
if MoveInfo and gmaOver<>0 then MoveCost:=40
else MoveCost:=20
else if MoveInfo and gmaOver<>0 then MoveCost:=-1
else case Terrain[ToTile and fTerrain].MoveCost of
1: MoveCost:=50; // plain terrain
2: MoveCost:=HeavyCost; // heavy terrain
3:
begin
MoveCost:=maxmov;
MountainDelay:=true;
end;
end;
// calculate HostileDamage
if not resistant and (ToTile and fTerImp<>tiBase) then
if ToTile and (fTerrain or fCity or fRiver or fCanal or fSpecial1{Oasis})=fDesert then
begin
if V8 and 1<>0 then
AddDamage:=((DesertThurst*3)*MoveCost-1) div maxmov +1
else AddDamage:=((DesertThurst*2)*MoveCost-1) div maxmov +1
end
else if ToTile and (fTerrain or fCity or fRiver or fCanal)=fArctic then
begin
if V8 and 1<>0 then
AddDamage:=((ArcticThurst*3)*MoveCost-1) div maxmov +1
else AddDamage:=((ArcticThurst*2)*MoveCost-1) div maxmov +1
end;
end
else MoveCost:=-1;
end;
if (MoveCost>0) and not MountainDelay then
if V8 and 1<>0 then inc(MoveCost,MoveCost*2)
else inc(MoveCost,MoveCost);
if (MoveInfo and 2<>0) // ground unit, check transport load/unload
and ((MoveCost<0)
and (ToTile and (fUnit or fOwned)=fUnit or fOwned) // assume ship/airplane is transport -- load!
or (MoveCost>=0) and (FromTile and fTerrain<fGrass)) then
MoveCost:=maxmov; // transport load or unload
if MoveCost>=0 then
begin {valid move}
MovementLeft:=maxmov-T shr 8 and $FFF-MoveCost;
if (MovementLeft<0) or ((MoveCost=0) and (MovementLeft=0)) then
begin // must wait for next turn
// calculate HostileDamage
if (MoveInfo and 2<>0){ground unit}
and not resistant and (FromTile and fTerImp<>tiBase) then
if FromTile and (fTerrain or fCity or fRiver or fCanal or fSpecial1{Oasis})=fDesert then
inc(AddDamage, (DesertThurst*(maxmov-T shr 8 and $FFF)-1) div maxmov +1)
else if FromTile and (fTerrain or fCity or fRiver or fCanal)=fArctic then
inc(AddDamage, (ArcticThurst*(maxmov-T shr 8 and $FFF)-1) div maxmov +1);
T1:=T and $7FF000FF +$100000+(initmov+MoveCost) shl 8;
end
else T1:=T+MoveCost shl 8+1;
if MountainDelay then T1:=T1 or $FFF00;
if (Damage[Loc]+AddDamage<=MaxDamage) and (T1 and $FF<$FF) then
if Q.Put(Loc1,T1) then
begin
From[Loc1]:=Loc;
Damage[Loc1]:=Damage[Loc]+AddDamage;
end
end
end
end
end
end;
Q.Free;
if (Loc=a.ToLoc) or (a.ToLoc=maNextCity) and (Loc>=0)
and (Map[Loc] and fCity<>0) then
begin
a.MoreTurns:=T shr 20;
EndLoc:=Loc;
a.nStep:=0;
while Loc<>FromLoc do
begin
if Time[Loc]<$100000 then inc(a.nStep);
Loc:=From[Loc];
end;
Loc:=EndLoc;
i:=a.nStep;
while Loc<>FromLoc do
begin
if Time[Loc]<$100000 then
begin
dec(i);
if i<25 then
begin
a.dx[i]:=((Loc mod lx *2 +Loc div lx and 1)
-(From[Loc] mod lx *2 +From[Loc] div lx and 1)+3*lx) mod (2*lx) -lx;
a.dy[i]:=Loc div lx-From[Loc] div lx;
end
end;
Loc:=From[Loc];
end;
a.MaxHostile_MovementLeft:=maxmov-Time[EndLoc] shr 8 and $FFF;
if a.nStep>25 then a.nStep:=25;
result:=eOK
end
else result:=eNoWay;
// QueryPerformanceCounter(tt);{time in s is: (tt-tt0)/PerfFreq}
end; // GetMoveAdvice
function CanPlaneReturn(p,uix: integer; PlaneReturnData: TPlaneReturnData): boolean;
const
mfEnd=1; mfReached=2;
var
uix1,T,T1,Loc,Loc1,FromTile,ToTile,V8,MoveCost,maxmov: integer;
Map: ^TTileList;
Q: TIPQ;
Adjacent: TVicinity8Loc;
MapFlags: array[0..lxmax*lymax-1] of byte;
begin
Map:=@(RW[p].Map^);
// calculate possible return points
FillChar(MapFlags,SizeOf(MapFlags),0);
if RW[p].Model[RW[p].Un[uix].mix].Kind=mkSpecial_Glider then
begin
for Loc:=0 to MapSize-1 do
if Map[Loc] and fTerrain>=fGrass then
MapFlags[Loc]:=MapFlags[Loc] or mfEnd;
end
else
begin
for Loc:=0 to MapSize-1 do
if (Map[Loc] and (fCity or fOwned)=fCity or fOwned)
or (Map[Loc] and fTerImp=tiBase) and (Map[Loc] and fObserved<>0)
and (Map[Loc] and (fUnit or fOwned)<>fUnit) then
MapFlags[Loc]:=MapFlags[Loc] or mfEnd;
if RW[p].Model[RW[p].Un[uix].mix].Cap[mcAirTrans]=0 then // plane can land on carriers
for uix1:=0 to RW[p].nUn-1 do
with RW[p].Un[uix1], RW[p].Model[mix] do
if AirLoad<MTrans*Cap[mcCarrier] then
MapFlags[Loc]:=MapFlags[Loc] or mfEnd;
end;
with RW[p].Un[uix] do
begin
if Master>=0 then // can return to same carrier, even if full now
MapFlags[Loc]:=MapFlags[Loc] or mfEnd;
maxmov:=RW[p].Model[mix].Speed;
end;
result:=false;
Q:=TIPQ.Create(MapSize);
Q.Put(PlaneReturnData.Loc,(maxmov-PlaneReturnData.Movement) shl 8);
while Q.Get(Loc,T) do
begin
MapFlags[Loc]:=MapFlags[Loc] or mfReached;
if T>=(PlaneReturnData.Fuel+1) shl 20 then
begin result:=false; break end;
if MapFlags[Loc] and mfEnd<>0 then
begin result:=true; break end;
FromTile:=Map[Loc];
V8_to_Loc(Loc,Adjacent);
for V8:=0 to 7 do
begin
Loc1:=Adjacent[V8];
if (Loc1>=0) and (Loc1<MapSize) and (MapFlags[Loc1] and mfReached=0) then
begin
ToTile:=Map[Loc1];
if (ToTile and fTerrain<>fUNKNOWN)
and (ToTile and (fCity or fOwned)<>fCity) // don't move through enemy cities
and (ToTile and (fUnit or fOwned)<>fUnit) // way is blocked
and (ToTile and not FromTile and fPeace=0) then
begin
if V8 and 1<>0 then MoveCost:=150
else MoveCost:=100;
if MoveCost+T shr 8 and $FFF>maxmov then // must wait for next turn
T1:=T and $7FF000FF +$100000+MoveCost shl 8
else T1:=T+MoveCost shl 8;
Q.Put(Loc1,T1);
end
end
end
end;
Q.Free;
end; // CanPlaneReturn
{
Terrain Improvement
____________________________________________________________________
}
function CalculateJobWork(p,Loc,Job: integer; var JobWork: integer): integer;
var
TerrType: integer;
begin
result:=eOK;
TerrType:=RealMap[Loc] and fTerrain;
with Terrain[TerrType] do case Job of
jCity:
if RealMap[Loc] and fCity<>0 then result:=eInvalid
else if IrrEff=0 then result:=eNoCityTerrain
else JobWork:=CityWork;
jRoad:
if RealMap[Loc] and (fRoad or fRR)=0 then
begin
JobWork:=MoveCost*RoadWork;
if RealMap[Loc] and fRiver<>0 then
if RW[p].Tech[adBridgeBuilding]>=tsApplicable then
inc(JobWork,RoadBridgeWork) {across river}
else result:=eNoBridgeBuilding
end
else result:=eInvalid;
jRR:
if RealMap[Loc] and fRoad=0 then result:=eNoPreq
else if RealMap[Loc] and fRR<>0 then result:=eInvalid
else
begin
JobWork:=MoveCost*RRWork;
if RealMap[Loc] and fRiver<>0 then
inc(JobWork,RRBridgeWork); {across river}
end;
jClear:
if (TerrType=fDesert)
and (GWonder[woGardens].EffectiveOwner<>p) then
result:=eInvalid
else if ClearTerrain>=0 then
JobWork:=IrrClearWork
else result:=eInvalid;
jIrr:
begin
JobWork:=IrrClearWork;
if (IrrEff=0)
or (RealMap[Loc] and fTerImp=tiIrrigation)
or (RealMap[Loc] and fTerImp=tiFarm) then
result:=eInvalid
end;
jFarm:
if RealMap[Loc] and fTerImp<>tiIrrigation then result:=eNoPreq
else
begin
JobWork:=IrrClearWork*FarmWork;
if (JobWork<=0) or (RealMap[Loc] and fTerImp=tiFarm) then
result:=eInvalid
end;
jAfforest:
if AfforestTerrain>=0 then
JobWork:=MineAfforestWork
else result:=eInvalid;
jMine:
begin
JobWork:=MineAfforestWork;
if (MineEff=0)
or (RealMap[Loc] and fTerImp=tiMine) then
result:=eInvalid
end;
jFort:
if RealMap[Loc] and fTerImp<>tiFort then
JobWork:=MoveCost*FortWork
else result:=eInvalid;
jCanal:
if (RealMap[Loc] and fCanal=0) and (TerrType in TerrType_Canalable) then
JobWork:=CanalWork
else result:=eInvalid;
jTrans:
begin
JobWork:=TransWork;
if JobWork<=0 then result:=eInvalid
end;
jPoll:
if RealMap[Loc] and fPoll<>0 then JobWork:=PollWork
else result:=eInvalid;
jBase:
if RealMap[Loc] and fTerImp<>tiBase then
JobWork:=MoveCost*BaseWork
else result:=eInvalid;
jPillage:
if RealMap[Loc] and (fRoad or fRR or fCanal or fTerImp)<>0 then
JobWork:=PillageWork
else result:=eInvalid;
end;
end; //CalculateJobWork
function StartJob(p,uix,NewJob: integer; TestOnly: boolean): integer;
var
JobWork, Loc0, p1, uix1, TerrType: integer;
begin
{$IFOPT O-}assert(1 shl p and InvalidTreatyMap=0);{$ENDIF}
result:=eOK;
with RW[p].Un[uix] do
begin
if NewJob=Job then
begin result:=eNotChanged; exit end;
if NewJob=jNone then
begin if not TestOnly then Job:=jNone; exit end;
Loc0:=Loc;
if (RealMap[Loc0] and fDeadLands<>0) and (NewJob<>jRoad) and (NewJob<>jRR) then
begin result:=eDeadLands; exit end;
TerrType:=RealMap[Loc0] and fTerrain;
if (RealMap[Loc0] and fCity<>0) or (TerrType<fGrass)
or (Master>=0)
or not ((NewJob=jPillage) and (RW[p].Model[mix].Domain=dGround)
or (RW[p].Model[mix].Kind=mkSettler)
or (NewJob<>jCity) and (RW[p].Model[mix].Kind=mkSlaves)
and (GWonder[woPyramids].EffectiveOwner>=0)) then
begin result:=eInvalid; exit end;
if (JobPreq[NewJob]<>preNone)
and (RW[p].Tech[JobPreq[NewJob]]<tsApplicable) then
begin result:=eNoPreq; exit end;
result:=CalculateJobWork(p,Loc0,NewJob,JobWork);
if (Mode=moPlaying) and (result=eOk) and (NewJob<>jPoll) then
begin // not allowed in territory of friendly nation
p1:=RealMap[Loc0] shr 27; // owner of territory
if (p1<nPl) and (p1<>p) and (RW[p].Treaty[p1]>=trPeace) then
result:=eTreaty; // keep peace treaty!
end;
if TestOnly or (result<rExecuted) then exit;
if (ToWork[Loc0,NewJob]=0) or (ToWork[Loc0,NewJob]>JobWork) then
ToWork[Loc0,NewJob]:=JobWork;
Job:=NewJob;
Flags:=Flags and not unFortified;
for uix1:=0 to RW[p].nUn-1 do
if (RW[p].Un[uix1].Loc=Loc)
and (RW[p].Un[uix1].Job in ContraJobs[NewJob]) then
RW[p].Un[uix1].Job:=jNone; // stop contradictive jobs
if ServerVersion[p]<$000EF0 then
if Work(p,uix) then result:=eJobDone;
if (NewJob=jCity) and (result=eJobDone) then
begin
RemoveUnit_UpdateMap(p,uix);
result:=eCity
end
else if Health<=0 then
begin // victim of HostileDamage
RemoveUnit_UpdateMap(p,uix);
result:=result or rUnitRemoved;
end;
if Mode>moLoading_Fast then
begin
if result=eCity then
begin
ObserveLevel[Loc0]:=ObserveLevel[Loc0] and not (3 shl (2*p));
Discover21(Loc0,p,lObserveUnhidden,true,true);
// CheckContact;
end
end
end; // with
end; //StartJob
function Work(p,uix: integer): boolean;
var
uix1,j0: integer;
begin
result:=false;
with RW[p].Un[uix] do if Movement>=100 then
begin
assert(ToWork[Loc,Job]<$FFFF); // should have been set by StartJob
if Job>=jRoad then
if integer(Movement)>=integer(ToWork[Loc,Job]) then {work complete}
begin
result:=true;
if Job<>jIrr then
Health:=Health-HostileDamage(p,mix,Loc,ToWork[Loc,Job]);
dec(Movement,ToWork[Loc,Job]);
if not (Job in [jCity,jPillage,jPoll]) then
inc(Worked[p],ToWork[Loc,Job]);
if Job=jCity then
begin // found new city
FoundCity(p,Loc);
inc(Founded[p]);
with RW[p].City[RW[p].nCity-1] do
begin
ID:=p shl 12+Founded[p]-1;
Flags:=chFounded;
end;
if Mode=moPlaying then
begin
LogCheckBorders(p,RW[p].nCity-1);
RecalcPeaceMap(p);
end;
{$IFOPT O-}if Mode<moPlaying then InvalidTreatyMap:=not(1 shl p);{$ENDIF}
// territory should not be considered for the rest of the command
// execution, because during loading a game it's incorrect before
// subsequent sIntExpandTerritory is processed
RW[p].Un[uix].Health:=0; // causes unit to be removed later
end
else CompleteJob(p,Loc,Job);
ToWork[Loc,Job]:=0;
j0:=Job;
for uix1:=0 to RW[p].nUn-1 do
if (RW[p].Un[uix1].Loc=Loc) and (RW[p].Un[uix1].Job=j0) then
RW[p].Un[uix1].Job:=jNone
end
else
begin
dec(ToWork[Loc,Job],Movement);
if not (Job in [jCity,jPillage,jPoll]) then
inc(Worked[p],Movement);
Health:=Health-HostileDamage(p,mix,Loc,Movement);
Movement:=0;
end
end
end; // work
function GetJobProgress(p,Loc: integer; var JobProgressData: TJobProgressData): integer;
var
Job,JobResult,uix: integer;
begin
for Job:=0 to nJob-1 do
begin
JobResult:=CalculateJobWork(p,Loc,Job,JobProgressData[Job].Required);
if JobResult=eOk then
begin
if ToWork[Loc,Job]=$FFFF then // not calculated yet
JobProgressData[Job].Done:=0
else JobProgressData[Job].Done:=JobProgressData[Job].Required-ToWork[Loc,Job]
end
else
begin
JobProgressData[Job].Required:=0;
JobProgressData[Job].Done:=0;
end;
JobProgressData[Job].NextTurnPlus:=0;
end;
for uix:=0 to RW[p].nUn-1 do
if (RW[p].Un[uix].Loc=Loc) and (RW[p].Un[uix].Movement>=100) then
inc(JobProgressData[RW[p].Un[uix].Job].NextTurnPlus, RW[p].Un[uix].Movement);
result:=eOk;
end;
{
Start/End Game
____________________________________________________________________
}
procedure InitGame;
begin
GetMem(ToWork,2*MapSize*nJob);
FillChar(ToWork^,2*MapSize*nJob,$FF);
end;
procedure ReleaseGame;
begin
FreeMem(ToWork);
end;
end.
|
unit RootUnit;
interface
uses
Pkg.Json.DTO;
{$M+}
type
TMenuitemDTO = class
private
FOnclick: string;
FValue: string;
published
property Onclick: string read FOnclick write FOnclick;
property Value: string read FValue write FValue;
end;
TPopupDTO = class
private
FMenuitem: TArray<TMenuitemDTO>;
published
property Menuitem: TArray<TMenuitemDTO> read FMenuitem write FMenuitem;
destructor Destroy; override;
end;
TMenuDTO = class
private
FId: string;
FPopup: TPopupDTO;
FValue: string;
published
property Id: string read FId write FId;
property Popup: TPopupDTO read FPopup write FPopup;
property Value: string read FValue write FValue;
public
constructor Create;
destructor Destroy; override;
end;
TRootDTO = class(TJsonDTO)
private
FMenu: TMenuDTO;
published
property Menu: TMenuDTO read FMenu write FMenu;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
{ TPopupDTO }
destructor TPopupDTO.Destroy;
var
Element: TObject;
begin
for Element in FMenuitem do
Element.Free;
inherited;
end;
{ TMenuDTO }
constructor TMenuDTO.Create;
begin
inherited;
FPopup := TPopupDTO.Create;
end;
destructor TMenuDTO.Destroy;
begin
FPopup.Free;
inherited;
end;
{ TRootDTO }
constructor TRootDTO.Create;
begin
inherited;
FMenu := TMenuDTO.Create;
end;
destructor TRootDTO.Destroy;
begin
FMenu.Free;
inherited;
end;
end.
|
unit xxmAutoUpdate;
interface
uses xxm, xxmPReg;
function AutoUpdate(pce:TXxmProjectCacheEntry;
Context:IXxmContext; ProjectName:WideString):boolean;
implementation
uses Windows, SysUtils;
var
UpdateLock:TRTLCriticalSection;
function AutoUpdate(pce:TXxmProjectCacheEntry;
Context:IXxmContext; ProjectName:WideString):boolean;
var
fn,fn1:string;
tc:cardinal;
i:integer;
const
NoNextUpdateAfter=1000;//TODO: setting!
begin
Result:=true;//default
tc:=GetTickCount;
if (tc-pce.LastCheck)>NoNextUpdateAfter then
begin
fn:=pce.ModulePath;//force get from registry outside of lock
EnterCriticalSection(UpdateLock);
try
//again for those that waited on lock
if (GetTickCount-pce.LastCheck)>NoNextUpdateAfter then
begin
i:=Length(fn);
while not(i=0) and not(fn[i]='.') do dec(i);
fn1:=Copy(fn,1,i-1)+'.xxu';
if FileExists(fn1) then
begin
pce.Release;
if not(DeleteFile(PChar(fn))) then MoveFile(PChar(fn),PChar(fn+'.bak'));
if not(MoveFile(PChar(fn1),PChar(fn))) then
begin
Result:=false;
Context.Send('AutoUpdate failed "'+fn1+'"'#13#10+
SysErrorMessage(GetLastError));
end;
end;
pce.LastCheck:=GetTickCount;
end;
finally
LeaveCriticalSection(UpdateLock);
end;
end;
end;
initialization
InitializeCriticalSection(UpdateLock);
finalization
DeleteCriticalSection(UpdateLock);
end.
|
{AUTEUR : FRANCKY23012301 - 2008 ------- Gratuit pour une utilisation non commerciale}
unit PianoGrid;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms,
Graphics, DuringTime, MMSystem, Math,Dialogs;
type
TDirection=(PlToRight,PlToLeft);
TMode = (MdNone, MdAddNote, MdSelectNote, MdMoveNote);
{>>TKnMdTimer : piqué à Kénavo}
TKnMdTimer = class(TComponent)
private
fwTimerID : DWord;
FInterval: Integer;
fEnabled: boolean;
fwTimerRes : Word;
FOnTimer: TNotifyEvent;
FCountTime:Integer;
protected
procedure setEnabled( b: boolean );
procedure SetInterval(value : Integer);
procedure Start;
procedure Stop;
public
constructor Create( AOwner: TComponent ); override;
destructor Destroy; override;
Property CountTime : Integer Read FCountTime Write FCountTime;
published
property Enabled: boolean read FEnabled write setEnabled default false;
property Interval: Integer read FInterval write SetInterval;
property OnTimer: TNotifyEvent read FOnTimer write FOnTimer;
end;
{>>TNote}
TNote = class(TCollectionItem)
private
fBytes: array[0..15] of Byte;
fBeginTime:Integer;
fEndTime:Integer;
fOnChange: TNotifyEvent;
protected
procedure AssignTo(Dest : TPersistent); override;
procedure Change; virtual;
function GetDisplayName : string; override;
public
Selected:Boolean;
function GetByte(index: Integer): Byte;
procedure SetByte(index: Integer; value: Byte);
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source : TPersistent); override;
published
Property Note : Byte index 0 Read GetByte write SetByte;
Property Instr : Byte index 1 Read GetByte write SetByte;
Property Channel : Byte index 2 Read GetByte write SetByte;
Property Volume : Byte index 3 Read GetByte write SetByte;
Property Velocity : Byte index 4 Read GetByte write SetByte;
Property PitchBend : Byte index 5 Read GetByte write SetByte;
Property ChannelPressure : Byte index 6 Read GetByte write SetByte;
Property Modulation : Byte index 7 Read GetByte write SetByte;
Property PortamentoTime : Byte index 8 Read GetByte write SetByte;
Property PortamentoSwitch : Byte index 9 Read GetByte write SetByte;
Property PortamentoNote : Byte index 10 Read GetByte write SetByte;
Property Resonance : Byte index 11 Read GetByte write SetByte;
Property Pan : Byte index 12 Read GetByte write SetByte;
Property Sustain : Byte index 13 Read GetByte write SetByte;
Property Vibrato : Byte index 14 Read GetByte write SetByte;
Property Expression : Byte index 15 Read GetByte write SetByte;
Property BeginTime :Integer Read fBeginTime write fBeginTime;
Property EndTime :Integer Read fEndTime write fEndTime;
property OnChange :TNotifyEvent read fOnChange write fOnChange;
end;
{>>TNoteCnt}
TNoteCnt = class(TOwnedCollection)
protected
function GetItem(Index: Integer): TNote;
procedure SetItem(Index: Integer; Value: TNote);
public
ItemIndex:Integer;
constructor Create(AOwner: TPersistent);
function Add: TNote;
property Items[Index: Integer]: TNote Read GetItem Write SetItem;
end;
TOnNote_Event = procedure(const Note: TNote) of object;
TNote_On_Event = procedure(Sender: TObject;Note:TNote) of object;
TNote_Off_Event = procedure(Sender: TObject;Note:TNote) of object;
TPlaying_Event=TNotifyEvent;
{>>TPianoGrid}
TPianoGrid = class(TCustomControl)
private
fColorNote: TColor;
fColorSelected: TColor;
fOctave:Integer;
fNoteCnt:TNoteCnt;
fInstrumentSelected:Byte;
fNoteSelected:Byte;
fTempo: Integer;
fDuringOfTime: TDuringOfTime;
fMin:Integer;
fMax:Integer;
fPos: real;
fTime:Integer;
fMode: TMode;
fUnityTime:Integer;
XOld:Integer;
YOld:Integer;
RectSelection:TRect;
DrawRectSelection:Boolean;
fOnAddNote:TOnNote_Event;
fOnNote_On: TNote_On_Event;
fOnNote_Off: TNote_Off_Event;
fOnPlaying:TPlaying_Event;
fStart:Boolean;
PlayingCursor:Integer;
procedure Set_ColorNote(Value: TColor);
Procedure Set_ColorSelected(Value: TColor);
Procedure Set_Octave(Value:Integer);
Procedure Set_InstrumentSelected(Value:Byte);
Procedure Set_NoteSelected(Value:Byte);
procedure Set_Tempo(Value: Integer);
procedure Set_DuringOfTime(Value: TDuringOfTime);
Procedure Set_Min(Value:Integer);
Procedure Set_Max(Value:Integer);
procedure Set_Pos(Value: real);
procedure Set_Time(Value:Integer);
procedure Timing(Sender: TObject);
Procedure Set_Mode(Value:TMode);
Procedure Set_Start(Value:Boolean);
protected
Procedure AddNote(X,Y:Integer);
Procedure ResizeNote(X,Y:Integer);
Procedure SelectNote(X,Y:Integer);
Procedure SelectNotes;
Procedure MoveNote(X,Y:Integer);
Procedure DrawSelection(X,Y:Integer);
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
TempNoteCnt:TNoteCnt;
PlayDirection:TDirection;
PlayingTime:TTime;
Timer:TKnMdTimer;
Function CoordToTime(Const X:Integer):Integer;
Function TimeToCoord(Const ATime:Integer):Integer;
Function CoordToNote(Const Y:Integer):Byte;
Function PosToCoord:Integer;
Property Start:Boolean Read fStart Write Set_Start;
Procedure Stop;
Procedure DelNote;
Procedure CopyNote;
Procedure PastNote;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
Property UnityTime:Integer Read fUnityTime Write fUnityTime;
published
property ColorNote: TColor Read FColorNote Write Set_ColorNote;
property ColorSelected: TColor Read FColorSelected Write Set_ColorSelected;
Property Octave:Integer Read fOctave Write Set_Octave;
Property InstrumentSelected:Byte Read fInstrumentSelected Write Set_InstrumentSelected;
Property NoteSelected:Byte Read fNoteSelected Write Set_NoteSelected;
Property NoteCnt:TNoteCnt Read fNoteCnt Write fNoteCnt;
property Tempo: Integer Read fTempo Write Set_Tempo;
property DuringOfTime: TDuringOfTime Read fDuringOfTime Write Set_DuringOfTime;
Property Min:Integer Read fMin Write Set_Min;
Property Max:Integer Read fMax Write Set_Max;
property Pos: real Read fPos Write Set_Pos;
property Time: Integer Read fTime Write Set_Time;
property Mode: TMode Read fMode Write Set_Mode;
Property OnAddNote:TOnNote_Event Read fOnAddNote Write fOnAddNote;
property Note_On_Event: TNote_On_Event Read fOnNote_On Write fOnNote_On;
property Note_Off_Event: TNote_Off_Event Read fOnNote_Off Write fOnNote_Off;
Property Playing_Event:TPlaying_Event Read fOnPlaying Write fOnPlaying;
Property Color;
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property ShowHint;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('MUSIC_PRO', [TPianoGrid]);
end;
procedure TimerCallback(wTimerID : UInt; msg : UInt; dwUser, dw1, dw2 : dword); stdcall;
begin
if ((TObject(dwUser) is TKnMdTimer)) Then
With TKnMdTimer(dwUser) Do
Begin
If (fwTimerID <> wTimerID) then exit;
If assigned(fOnTimer) then OnTimer(TObject(dwUser));
If (Owner As TPianoGrid).PlayDirection=PlToRight Then CountTime:=CountTime+Interval
Else CountTime:=CountTime-Interval;
End;
end;
{>>TKnMdTimer : piqué à Kénavo}
constructor TKnMdTimer.Create( AOwner: TComponent );
var
tc : TimeCaps;
begin
Inherited Create(Aowner);
if (timeGetDevCaps(@tc, sizeof(TIMECAPS)) <> TIMERR_NOERROR) then exit;
fwTimerRes := min(max(tc.wPeriodMin, 1), tc.wPeriodMax);
timeBeginPeriod(fwTimerRes);
fInterval :=10;
fEnabled := False;
FCountTime:=0;
end;
destructor TKnMdTimer.Destroy;
begin
if fEnabled then Stop;
inherited Destroy;
end;
procedure TKnMdTimer.SetEnabled( b: boolean );
begin
if b <>fEnabled then
begin
fEnabled := b;
if fEnabled then Start
else Stop;
end;
end;
procedure TKnMdTimer.SetInterval(value : Integer);
begin
if (Value <>fInterval) and (value >= fwTimerRes) then
begin
Stop;
fInterval := Value;
if fEnabled then Start;
end;
end;
procedure TKnMdTimer.Start;
begin
fwTimerID := timeSetEvent(fInterval,fwTimerRes,@TimerCallback,DWord(Self),1);
end;
procedure TKnMdTimer.Stop;
begin
timeKillEvent(fwTimerID);
end;
{>>TPianoGrid}
constructor TPianoGrid.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Color:=ClWhite;
fNoteCnt:=TNoteCnt.Create(Self);
TempNoteCnt:=TNoteCnt.Create(Self);
Timer := TKnMdTimer.Create(Self);
Timer.Interval:=10;
Timer.OnTimer := Timing;
fUnityTime:=0;
fTempo := 60;
fDuringOfTime := QuarterNote;
fMin:=0;
fMax:=10;
fPos:=0;
fTime:=4;
fOctave:=0;
DrawRectSelection:=False;
DoubleBuffered:=True;
end;
destructor TPianoGrid.Destroy;
begin
Timer.Free;
TempNoteCnt.Free;
fNoteCnt.Free;
inherited;
end;
procedure TPianoGrid.Set_Octave(Value:Integer);
Begin
fOctave:=Value;
If (fOctave>10) Then fOctave:=10;
If (fOctave<0) Then fOctave:=0;
Invalidate;
End;
procedure TPianoGrid.Set_InstrumentSelected(Value: Byte);
begin
If Value<128 Then
Begin
fInstrumentSelected:= Value;
Invalidate;
End;
end;
procedure TPianoGrid.Set_NoteSelected(Value: Byte);
begin
If Value<128 Then
Begin
fNoteSelected:= Value;
Invalidate;
End;
end;
procedure TPianoGrid.Set_ColorNote(Value: TColor);
begin
FColorNote := Value;
Invalidate;
end;
procedure TPianoGrid.Set_ColorSelected(Value: TColor);
begin
FColorSelected := Value;
Invalidate;
end;
procedure TPianoGrid.Set_Tempo(Value: Integer);
begin
fTempo := Value;
Set_DuringOfTime(fDuringOfTime);
end;
procedure TPianoGrid.Set_DuringOfTime(Value: TDuringOfTime);
var
DuringCoef: real;
IndexNote,OldUnity:Integer;
begin
OldUnity:=fUnityTime;
fDuringOfTime := Value;
DuringCoef := 4;
case fDuringOfTime of
WholeNote: DuringCoef := 4;
HalfNote: DuringCoef := 2;
QuarterNote: DuringCoef := 1;
Quavers: DuringCoef := 0.5;
SixteenthNote: DuringCoef := 0.25;
DemiSemiQuavers: DuringCoef := 0.125;
end;
fUnityTime := (Round(60 * DuringCoef * 1000)) div fTempo;
If fNoteCnt.Count>0 Then
For IndexNote:=0 To fNoteCnt.Count-1 Do
With fNoteCnt.Items[IndexNote] Do
Begin
BeginTime:=Round(BeginTime*fUnityTime / OldUnity);
EndTime:=Round(EndTime*fUnityTime / OldUnity);
End;
Invalidate;
end;
Procedure TPianoGrid.Set_Min(Value:Integer);
begin
fMin:= Value;
Invalidate;
end;
Procedure TPianoGrid.Set_Max(Value:Integer);
begin
fMax:= Value;
Invalidate;
end;
procedure TPianoGrid.Set_Pos(Value: real);
begin
fPos := Value;
if fPos < fMin then fPos := fMin;
if fPos > fMax then fPos := fMax;
Invalidate;
end;
procedure TPianoGrid.Set_Time(Value:Integer);
begin
fTime:=Value;
Invalidate;
end;
procedure TPianoGrid.Timing(Sender: TObject);
Var
DecPrg,IndexNote,FistTime,LastTime:Integer;
begin
PlayingTime:=PlayingTime+EncodeTime(00,00,fUnityTime Div 1000 ,fUnityTime Mod 1000);
If Assigned(fOnPlaying) then fOnPlaying(Sender);
DecPrg:=fMax-fMin;
If PlayDirection=PlToRight Then FPos:=FPos+10/(FTime*fUnityTime)
Else FPos :=FPos-10/(FTime*fUnityTime);
if fPos >= fMax then
Begin
Inc(fMin,DecPrg);
Inc(fMax,DecPrg);
End;
if fPos <= fMin then
Begin
Dec(fMin,DecPrg);
Dec(fMax,DecPrg);
End;
Invalidate;
If fNoteCnt.Count>0 Then
For IndexNote:=0 To (fNoteCnt.Count-1) Do
With fNoteCnt.Items[IndexNote] Do
Begin
If PlayDirection=PlToRight Then
Begin
FistTime:=fBeginTime;
LastTime:=fEndTime;
End
Else
Begin
FistTime:=fEndTime;
LastTime:=fBeginTime;
End;
If (FistTime>Timer.CountTime-5) And (FistTime<=Timer.CountTime+5) And (Assigned(fOnNote_On)) Then
fOnNote_On(Sender,fNoteCnt.Items[IndexNote]);
If (LastTime>Timer.CountTime-5) And (LastTime<=Timer.CountTime+5) And (Assigned(fOnNote_Off)) Then
fOnNote_Off(Sender,fNoteCnt.Items[IndexNote]);
End;
end;
Procedure TPianoGrid.Set_Mode(Value:TMode);
Begin
If Value<>fMode Then
Begin
fMode:=Value;
If fMode=MdSelectNote Then TempNoteCnt.Clear;
End;
End;
procedure TPianoGrid.Set_Start(Value:Boolean);
begin
Timer.Enabled := Value;
Set_DuringOfTime(fDuringOfTime);
fStart:=Value;
end;
Procedure TPianoGrid.Stop;
begin
Timer.Enabled :=False;
PlayingCursor:=0;
PlayingTime:=0;
Timer.CountTime:=0;
end;
Function TPianoGrid.CoordToTime(Const X:Integer):Integer;
begin
Result:=Trunc(fUnityTime*(fMin*Time+X / 20));
end;
Function TPianoGrid.TimeToCoord(Const ATime:Integer):Integer;
begin
Result:=Trunc((ATime/fUnityTime-fMin*Time)*20);
end;
Function TPianoGrid.CoordToNote(Const Y:Integer):Byte;
Var
NmCase:Integer;
Begin
NmCase:=Trunc(Y / 14) ;
Result:=(NmCase+fOctave*12);
End;
Function TPianoGrid.PosToCoord:Integer;
Begin
Result:=Round((Width-60)*(fPos-fMin) / (fMax-fMin));
End;
procedure TPianoGrid.Paint;
Const
WidthCol=20;
HeightRow=14;
NotesName: Array [0..23] Of String =
('C','C#','D','D#','E','F','F#','G','G#','A','A#','B',
'C','C#','D','D#','E','F','F#','G','G#','A','A#','B');
var
NmCol,IndexCol,NmRow,IndexRow,TopText,IndexNote,NmCase:Integer;
NoteName:String;
NoteRect,NotesRect:TRect;
begin
inherited;
With Canvas Do
Begin
Brush.Style:=BsClear;
Pen.Color:=ClBlack;
Pen.Style:=psSolid;
NmCol:=(fMax-fMin)*fTime;
Width:=20*NmCol+60;
For IndexCol:=0 To NmCol Do
Begin
MoveTo(Round(WidthCol*IndexCol),0);
LineTo(Round(WidthCol*IndexCol),Height);
End;
Brush.Color := $00EAFFFF;
With NotesRect Do
Begin
Left:=Width-60;
Right:=Width;
Top:=0;
Bottom:=Height;
End;
Rectangle(NotesRect);
Font.Style:=[fsBold];
If fOctave=10 Then NmRow:=20 Else NmRow:=24;
Height:=HeightRow * NmRow;
For IndexRow:=0 To NmRow Do
Begin
MoveTo(0,Round(IndexRow*HeightRow));
LineTo(Width,Round(IndexRow*HeightRow));
If IndexRow<24 Then
Begin
NoteName:=NotesName[IndexRow]+'--'+IntToStr(fOctave+IndexRow Div 12);
TopText :=Round(HeightRow*(1+IndexRow*2) / 2)-TextHeight(NoteName) Div 2;
TextOut(Width-50, TopText, NoteName);
End;
End;
If fNoteCnt.Count>0 Then
For IndexNote:=0 To fNoteCnt.Count-1 Do
With fNoteCnt.Items[IndexNote] Do
Begin
If Instr<>fInstrumentSelected Then Continue;
If (Trunc(Note / 12) In [fOctave,fOctave+1]) And
(TimeToCoord(fEndTime)<Width-60 ) And
(TimeToCoord(fBeginTime)>0) Then
With NoteRect Do
Begin
NmCase:=((Note-12*fOctave) Mod 24);
If Selected Then Brush.Color:=ColorSelected
Else Brush.Color:=Self.FColorNote;
Left:=TimeToCoord(fBeginTime);
If Left<0 Then Left:=0;
Right:=TimeToCoord(fEndTime);
If Right>20*NmCol Then Right:=20*NmCol;
Top:=Round(NmCase*HeightRow );
Bottom:=Round(Top+HeightRow)+1;
Rectangle(NoteRect);
End;
End;
Pen.Color:=ClRed;
MoveTo(PosToCoord,0);
LineTo(PosToCoord,Height);
Pen.Color:=ClBlack;
Brush.Style:=BsClear;
Rectangle(ClientRect);
If DrawRectSelection Then
Begin
Pen.Color:=ClBlue;
Pen.Style:=psDash;
Brush.Style:=BsClear;
Rectangle(RectSelection);
End;
End;
end;
Procedure TPianoGrid.AddNote(X,Y:Integer);
Var
IndexNote,ATime:Integer;
NewNote:TNote;
NoteAdd:Byte;
Begin
If (X>Round((fMax-fMin)*fTime*20)) Then Exit;
ATime:=CoordToTime(X);
NoteAdd:=CoordToNote(Y);
If fNoteCnt.Count>0 Then
Begin
For IndexNote:=0 To (fNoteCnt.Count-1) Do
With fNoteCnt.Items[IndexNote] Do
If (fBeginTime<=ATime) And (fEndTime>=ATime) And (Note=NoteAdd) Then Exit;
End;
NewNote:=fNoteCnt.Add;
With NewNote Do
Begin
Note:=NoteAdd;
fBeginTime:=CoordToTime(X);
fEndTime:=CoordToTime(X+20);
End;
If Assigned(fOnAddNote) Then fOnAddNote(NewNote);
Invalidate;
End;
Procedure TPianoGrid.DelNote;
Var
IndexNote:Integer;
Begin
If fNoteCnt.Count>0 Then
For IndexNote:=(fNoteCnt.Count-1) DownTo 0 Do
Begin
If fNoteCnt.Items[IndexNote].Selected Then
fNoteCnt.Delete(IndexNote);
End;
Invalidate;
End;
Procedure TPianoGrid.ResizeNote(X,Y:Integer);
Var
IndexNote,ATime:Integer;
NoteAdd:Byte;
Begin
If (Round(X)>(fMax-fMin)*fTime*20+20) Then Exit;
ATime:=CoordToTime(X);
NoteAdd:=CoordToNote(Y);
If fNoteCnt.Count>0 Then
Begin
For IndexNote:=0 To (fNoteCnt.Count-1) Do
With fNoteCnt.Items[IndexNote] Do
If (fBeginTime<=ATime) And (fEndTime>=ATime) And (Note=NoteAdd) Then
fEndTime:=CoordToTime(X+5);
Invalidate;
End;
End;
Procedure TPianoGrid.SelectNote(X,Y:Integer);
Var
IndexNote,ATime:Integer;
ANote:Byte;
Begin
If (Round(X)>(fMax-fMin)*fTime*20) Then Exit;
ATime:=CoordToTime(X);
ANote:=CoordToNote(Y);
If fNoteCnt.Count>0 Then
Begin
For IndexNote:=0 To (fNoteCnt.Count-1) Do
With fNoteCnt.Items[IndexNote] Do
Begin
If (ATime>=fBeginTime) And (ATime<=fEndTime) And (ANote=Note) Then
Selected:=Not Selected;
End;
Invalidate;
End;
End;
Procedure TPianoGrid.SelectNotes;
Var
LeftTime,RightTime,TopNote,BottomNote,IndexNote:Integer;
Begin
With RectSelection Do
Begin
LeftTime:=CoordToTime(Left);
RightTime:=CoordToTime(Right);
TopNote:=CoordToNote(Top);
BottomNote:=CoordToNote(Bottom);
If fNoteCnt.Count>0 Then
Begin
For IndexNote:=0 To (fNoteCnt.Count-1) Do
With fNoteCnt.Items[IndexNote] Do
Begin
If (LeftTime<=fBeginTime) And (RightTime>=fEndTime)
And (TopNote<=Note) And (BottomNote>=Note) Then
Selected:=Not Selected;
End;
End;
DrawRectSelection:=False;
Invalidate;
End;
End;
Procedure TPianoGrid.CopyNote;
Var
IndexNote:Integer;
TempNote:TNote;
Begin
If fNoteCnt.Count>0 Then
For IndexNote:=0 To (fNoteCnt.Count-1) Do
Begin
If fNoteCnt.Items[IndexNote].Selected Then
Begin
TempNote:=TempNoteCnt.Add;
fNoteCnt.Items[IndexNote].AssignTo(TempNote);
fNoteCnt.Items[IndexNote].Selected:=False;
End;
End;
Invalidate;
End;
Procedure TPianoGrid.PastNote;
Var
IndexNote:Integer;
NewNote:TNote;
Begin
If TempNoteCnt.Count>0 Then
For IndexNote:=0 To (TempNoteCnt.Count-1) Do
Begin
NewNote:=fNoteCnt.Add;
TempNoteCnt.Items[IndexNote].AssignTo(NewNote);
TempNoteCnt.Items[IndexNote].Selected:=False;
NewNote.Instr:=fInstrumentSelected;
End;
fMode:=MdMoveNote;
TempNoteCnt.Clear;
Invalidate;
End;
Procedure TPianoGrid.MoveNote(X,Y:Integer);
Var
IndexNote,DecNote,DecTime:Integer;
Begin
DecNote:=CoordToNote(Y)-CoordToNote(Yold);
DecTime:=CoordToTime(X-Xold);
For IndexNote:=0 To (fNoteCnt.Count-1) Do
With fNoteCnt.Items[IndexNote] Do
Begin
If Selected Then
Begin
Inc(fBeginTime,DecTime);
Inc(fEndTime,DecTime);
Note:=Note+DecNote;
End;
End;
XOld:=X;
YOld:=Y;
Invalidate;
End;
Procedure TPianoGrid.DrawSelection(X,Y:Integer);
Begin
If Not DrawRectSelection Then DrawRectSelection:=True;
With RectSelection Do
Begin
Left:=XOld;
Top:=YOld;
Right:=X;
Bottom:=Y;
Invalidate;
End;
End;
procedure TPianoGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
fNoteCnt.ItemIndex:=Trunc(Y / 14) ;
fNoteSelected:=Self.CoordToNote(Y);
If (SSLeft In Shift) Then
Case fMode Of
MdAddNote : AddNote(X,Y);
MdSelectNote : If Not (ssShift In Shift) Then SelectNote(X,Y)
Else Begin XOld:=X; YOld:=Y; End;
MdMoveNote : Begin XOld:=X; YOld:=Y; End;
End;
end;
procedure TPianoGrid.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
If (SSLeft In Shift) Then
Case fMode Of
MdAddNote : ResizeNote(X,Y);
MdSelectNote : If (ssShift In Shift) Then DrawSelection(X,Y);
MdMoveNote : MoveNote(X,Y);
End;
end;
procedure TPianoGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
If (fMode=MdSelectNote) And (ssShift In Shift) Then
SelectNotes;
end;
{>>TNoteCnt}
constructor TNoteCnt.Create(AOwner: TPersistent);
begin
inherited Create(AOwner,TNote);
ItemIndex:=-1;
end;
function TNoteCnt.Add:TNote;
begin
Result := TNote(inherited Add);
end;
function TNoteCnt.GetItem(Index: Integer):TNote;
begin
Result := TNote(inherited Items[Index]);
end;
procedure TNoteCnt.SetItem(Index: Integer; Value:TNote);
begin
inherited SetItem(Index, Value);
end;
{>>TNote}
constructor TNote.Create;
begin
inherited Create(ACollection);
end;
destructor TNote.Destroy;
begin
inherited Destroy;
end;
procedure TNote.AssignTo(Dest: TPersistent);
begin
if Dest is TNote then
with TNote(Dest) do begin
fOnChange := self.fOnChange;
fBytes := Self.fBytes;
fBeginTime:=Self.fBeginTime;
fEndTime:=Self.fEndTime;
Selected:=Self.Selected;
Change;
end
else
inherited AssignTo(Dest);
end;
procedure TNote.Assign(Source : TPersistent);
begin
if source is TNote then
with TNote(Source) do
AssignTo(Self)
else
inherited Assign(source);
end;
function TNote.GetByte(index: Integer): Byte;
begin
result := fBytes[index];
end;
procedure TNote.SetByte(index: Integer; value: Byte);
begin
if fBytes[index] <> value then
begin
fBytes[index] := value;
change;
end;
end;
procedure TNote.Change;
begin
if Assigned(fOnChange) then
fOnChange(Self);
end;
function TNote.GetDisplayName: string;
begin
result := '<'+IntToStr(Self.Index)+'>';
end;
End. |
unit UBunker;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
UEmbedForm, ExtCtrls, StdCtrls,
tc;
type
TFBunker = class(TEmbedForm)
Label1: TLabel;
Panel1: TPanel;
Label2: TLabel;
Panel2: TPanel;
Label5: TLabel;
LineBox: TComboBox;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure RefreshLineBox;
procedure Load(Bunker : TBunker);
procedure Save(Bunker : TBunker);
procedure SetCapacity(value : massa);
function GetCapacity : massa;
procedure SetCurAmount(Value : massa);
function GetCurAmount : massa;
procedure SetLine(value : integer);
function GetLine : integer;
property Capacity : massa read GetCapacity write SetCapacity;
property CurAmount : massa read GetCurAmount write SetCurAmount;
property Line : integer read GetLine write SetLine;
end;
var
FBunker: TFBunker;
implementation
uses UMassa, UModel;
var
FCapacity,
FCurAmount : TFMassa;
{$R *.DFM}
procedure TFBunker.FormCreate(Sender: TObject);
begin
inherited;
Panel1.BorderStyle := bsNone;
Panel2.BorderStyle := bsNone;
FCapacity := TFMassa.CreateEmbedded(self, Panel1);
FCurAmount := TFMassa.CreateEmbedded(self, Panel2);
FCapacity.Show;
FCurAmount.Show;
end;
function TFBunker.GetCapacity: massa;
begin
result := FCapacity.Number;
end;
function TFBunker.GetCurAmount: massa;
begin
result := FCurAmount.Number;
end;
function TFBunker.GetLine: integer;
begin
with LineBox do
if ItemIndex = -1 then result := -1
else
result := (Items.Objects[ItemIndex] as TAssembleLine).Number;
end;
procedure TFBunker.Load(Bunker: TBunker);
begin
Capacity := Bunker.Capacity;
CurAmount := Bunker.CurAmount;
Line := Bunker.Line;
end;
procedure TFBunker.RefreshLineBox;
var
i : integer;
begin
LineBox.Clear;
with FModel.Model.Lines do
for i := Low(List) to high(List) do
LineBox.Items.AddObject(List[i].Name, List[i]);
end;
procedure TFBunker.Save(Bunker: TBunker);
begin
Bunker.Capacity := Capacity;
Bunker.CurAmount := CurAmount;
Bunker.Line := Line;
end;
procedure TFBunker.SetCapacity(value: massa);
begin
FCapacity.Number := value;
end;
procedure TFBunker.SetCurAmount(Value: massa);
begin
FCurAmount.Number := value;
end;
procedure TFBunker.SetLine(value: integer);
begin
RefreshLineBox;
LineBox.ItemIndex := FModel.Model.Lines.FindByNumber(value);
end;
end.
|
unit TestuOrderEntry;
interface
uses
TestFramework,
uOrderInterfaces;
type
TestTOrderEntry = class(TTestCase)
public
procedure SetUp; override;
published
procedure TestEnterOrderIntoDatabase;
procedure TestOrderEntryIsMock_ServiceLocator_TOrderEntryMockServiceName();
procedure TestOrderEntryIsRegular_ServiceLocator();
end;
implementation
uses
uOrder,
Spring.Services,
Spring.Container,
uSpringTestCaseHelper,
uOrderEntryMock,
uRegisterMocks;
const
SOrderEntry = 'OrderEntry';
procedure TestTOrderEntry.SetUp;
begin
GlobalContainer.Build();
end;
procedure TestTOrderEntry.TestEnterOrderIntoDatabase;
var
Order: TOrder;
OrderEntry: IOrderEntry;
ResultValue: Boolean;
begin
Order := TOrder.Create();
try
OrderEntry := ServiceLocator.GetService<IOrderEntry>();
ResultValue := OrderEntry.EnterOrderIntoDatabase(Order);
Check(ResultValue);
finally
Order.Free;
end;
end;
procedure TestTOrderEntry.TestOrderEntryIsMock_ServiceLocator_TOrderEntryMockServiceName();
var
OrderEntry: IOrderEntry;
begin
// Retrieving the instances with the unique service names gives back the Mock classes:
OrderEntry := ServiceLocator.GetService<IOrderEntry>(RegisterMocks.TOrderEntryMockServiceName);
TestInterfaceImplementedByClass(OrderEntry, TOrderEntryMock, SOrderEntry);
end;
procedure TestTOrderEntry.TestOrderEntryIsRegular_ServiceLocator();
var
OrderEntry: IOrderEntry;
begin
// Note that going through the ServiceLocator without the names will give you the regular implementations,
// which you want for the normal business code still to work:
OrderEntry := ServiceLocator.GetService<IOrderEntry>();
TestInterfaceNotImplementedByClass(OrderEntry, TOrderEntryMock, SOrderEntry);
end;
initialization
RegisterTest(TestTOrderEntry.Suite);
end. |
unit FastcodeLowerCaseUnit;
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Fastcode
*
* The Initial Developer of the Original Code is Fastcode
*
* Portions created by the Initial Developer are Copyright (C) 2002-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Charalabos Michael <chmichael@creationpower.com>
* John O'Harrow <john@elmcrest.demon.co.uk>
* Aleksandr Sharahov
*
* BV Version: 3.51
* ***** END LICENSE BLOCK ***** *)
interface
{$I Fastcode.inc}
type
FastcodeLowerCaseFunction = function(const s: string): string;
{Functions shared between Targets}
function LowerCase_JOH_MMX_2(const S: string): string;
function LowerCase_JOH_IA32_5(const S: string): string;
function LowerCase_Sha_Pas_2_a(const s: string): string;
{Functions not shared between Targets}
function LowerCase_JOH_IA32_4(const S: string): string;
const
Version = '0.5 beta 2';
FastcodeLowerCaseP4R: FastcodeLowerCaseFunction = LowerCase_JOH_MMX_2;
FastcodeLowerCaseP4N: FastcodeLowerCaseFunction = LowerCase_JOH_IA32_5;
FastcodeLowerCasePMY: FastcodeLowerCaseFunction = LowerCase_JOH_MMX_2;
FastcodeLowerCasePMD: FastcodeLowerCaseFunction = LowerCase_JOH_MMX_2;
FastcodeLowerCaseAMD64: FastcodeLowerCaseFunction = LowerCase_JOH_IA32_5;
FastcodeLowerCaseAMD64_SSE3: FastcodeLowerCaseFunction = LowerCase_JOH_IA32_4;
FastCodeLowerCaseIA32SizePenalty: FastCodeLowerCaseFunction = LowerCase_JOH_IA32_5;
FastcodeLowerCaseIA32: FastcodeLowerCaseFunction = LowerCase_JOH_IA32_5;
FastcodeLowerCaseMMX: FastcodeLowerCaseFunction = LowerCase_JOH_MMX_2;
FastCodeLowerCaseSSESizePenalty: FastCodeLowerCaseFunction = LowerCase_JOH_IA32_5;
FastcodeLowerCaseSSE: FastcodeLowerCaseFunction = LowerCase_JOH_MMX_2;
FastcodeLowerCaseSSE2: FastcodeLowerCaseFunction = LowerCase_JOH_MMX_2;
FastCodeLowerCasePascalSizePenalty: FastCodeLowerCaseFunction = LowerCase_Sha_Pas_2_a;
FastCodeLowerCasePascal: FastCodeLowerCaseFunction = LowerCase_Sha_Pas_2_a;
procedure LowerCaseStub;
implementation
uses
SysUtils;
var
AsciiLowerCase : array[Char] of Char = (
#$00,#$01,#$02,#$03,#$04,#$05,#$06,#$07,#$08,#$09,#$0A,#$0B,#$0C,#$0D,#$0E,#$0F,
#$10,#$11,#$12,#$13,#$14,#$15,#$16,#$17,#$18,#$19,#$1A,#$1B,#$1C,#$1D,#$1E,#$1F,
#$20,#$21,#$22,#$23,#$24,#$25,#$26,#$27,#$28,#$29,#$2A,#$2B,#$2C,#$2D,#$2E,#$2F,
#$30,#$31,#$32,#$33,#$34,#$35,#$36,#$37,#$38,#$39,#$3A,#$3B,#$3C,#$3D,#$3E,#$3F,
#$40,#$61,#$62,#$63,#$64,#$65,#$66,#$67,#$68,#$69,#$6A,#$6B,#$6C,#$6D,#$6E,#$6F,
#$70,#$71,#$72,#$73,#$74,#$75,#$76,#$77,#$78,#$79,#$7A,#$5B,#$5C,#$5D,#$5E,#$5F,
#$60,#$61,#$62,#$63,#$64,#$65,#$66,#$67,#$68,#$69,#$6A,#$6B,#$6C,#$6D,#$6E,#$6F,
#$70,#$71,#$72,#$73,#$74,#$75,#$76,#$77,#$78,#$79,#$7A,#$7B,#$7C,#$7D,#$7E,#$7F,
#$80,#$81,#$82,#$83,#$84,#$85,#$86,#$87,#$88,#$89,#$8A,#$8B,#$8C,#$8D,#$8E,#$8F,
#$90,#$91,#$92,#$93,#$94,#$95,#$96,#$97,#$98,#$99,#$9A,#$9B,#$9C,#$9D,#$9E,#$9F,
#$A0,#$A1,#$A2,#$A3,#$A4,#$A5,#$A6,#$A7,#$A8,#$A9,#$AA,#$AB,#$AC,#$AD,#$AE,#$AF,
#$B0,#$B1,#$B2,#$B3,#$B4,#$B5,#$B6,#$B7,#$B8,#$B9,#$BA,#$BB,#$BC,#$BD,#$BE,#$BF,
#$C0,#$C1,#$C2,#$C3,#$C4,#$C5,#$C6,#$C7,#$C8,#$C9,#$CA,#$CB,#$CC,#$CD,#$CE,#$CF,
#$D0,#$D1,#$D2,#$D3,#$D4,#$D5,#$D6,#$D7,#$D8,#$D9,#$DA,#$DB,#$DC,#$DD,#$DE,#$DF,
#$E0,#$E1,#$E2,#$E3,#$E4,#$E5,#$E6,#$E7,#$E8,#$E9,#$EA,#$EB,#$EC,#$ED,#$EE,#$EF,
#$F0,#$F1,#$F2,#$F3,#$F4,#$F5,#$F6,#$F7,#$F8,#$F9,#$FA,#$FB,#$FC,#$FD,#$FE,#$FF);
function LowerCase_JOH_MMX_2(const S: string): string;
const
B25 : Int64 = $2525252525252525;
B65 : Int64 = $6565656565656565;
B20 : Int64 = $2020202020202020;
asm
xchg eax, edx
test edx, edx {Test for S = ''}
jz system.@LStrSetLength {Return Empty String}
mov ecx, edx {Addr(S)}
mov edx, [edx-4]
push ebx
push edi
push esi
mov edi, ecx {Addr(S)}
mov esi, edx {Length}
mov ebx, eax {Addr(Result)}
call system.@LStrSetLength {Create Result String}
mov ecx, esi {Length}
mov eax, edi {Addr(S)}
sub ecx, 16
mov edx, [ebx] {Result}
jl @@Small
movq mm4, B25
movq mm5, B65
movq mm6, B20
add eax, ecx
add edx, ecx
neg ecx
@@LargeLoop:
movq mm0, [eax+ecx ]
movq mm1, [eax+ecx+8]
movq mm2, mm0
movq mm3, mm1
paddb mm2, mm4
paddb mm3, mm4
pcmpgtb mm2, mm5
pcmpgtb mm3, mm5
pand mm2, mm6
pand mm3, mm6
paddb mm0, mm2
paddb mm1, mm3
movq [edx+ecx ], mm0
movq [edx+ecx+8], mm1
add ecx, 16
jle @@LargeLoop
emms
neg ecx
sub eax, ecx
sub edx, ecx
@@Small:
add ecx, 16
lea edi, AsciiLowerCase
jz @@Done
@@SmallLoop:
sub ecx, 1
movzx esi, [eax+ecx]
movzx ebx, [edi+esi]
mov [edx+ecx], bl
jg @@SmallLoop
@@Done:
pop esi
pop edi
pop ebx
end;
function LowerCase_JOH_IA32_5(const S: string): string;
asm {Size = 134 Bytes}
push ebx
push edi
push esi
test eax, eax {Test for S = NIL}
mov esi, eax {@S}
mov edi, edx {@Result}
mov eax, edx {@Result}
jz @@Null {S = NIL}
mov edx, [esi-4] {Length(S)}
test edx, edx
je @@Null {Length(S) = 0}
mov ebx, edx
call system.@LStrSetLength {Create Result String}
mov edi, [edi] {@Result}
mov eax, [esi+ebx-4] {Convert the Last 4 Characters of String}
mov ecx, eax {4 Original Bytes}
or eax, $80808080 {Set High Bit of each Byte}
mov edx, eax {Comments Below apply to each Byte...}
sub eax, $5B5B5B5B {Set High Bit if Original <= Ord('Z')}
xor edx, ecx {80h if Original < 128 else 00h}
or eax, $80808080 {Set High Bit}
sub eax, $66666666 {Set High Bit if Original >= Ord('A')}
and eax, edx {80h if Orig in 'A'..'Z' else 00h}
shr eax, 2 {80h > 20h ('a'-'A')}
add ecx, eax {Set Bit 5 if Original in 'A'..'Z'}
mov [edi+ebx-4], ecx
sub ebx, 1
and ebx, -4
jmp @@CheckDone
@@Null:
pop esi
pop edi
pop ebx
jmp System.@LStrClr
@@Loop: {Loop converting 4 Character per Loop}
mov eax, [esi+ebx]
mov ecx, eax {4 Original Bytes}
or eax, $80808080 {Set High Bit of each Byte}
mov edx, eax {Comments Below apply to each Byte...}
sub eax, $5B5B5B5B {Set High Bit if Original <= Ord('Z')}
xor edx, ecx {80h if Original < 128 else 00h}
or eax, $80808080 {Set High Bit}
sub eax, $66666666 {Set High Bit if Original >= Ord('A')}
and eax, edx {80h if Orig in 'A'..'Z' else 00h}
shr eax, 2 {80h > 20h ('a'-'A')}
add ecx, eax {Set Bit 5 if Original in 'A'..'Z'}
mov [edi+ebx], ecx
@@CheckDone:
sub ebx, 4
jnc @@Loop
pop esi
pop edi
pop ebx
end;
function LowerCase_JOH_IA32_4(const S: string): string;
asm {Size = 125 Bytes}
push edi
push esi
push ebx
mov esi, eax {@S}
mov edi, edx {@Result}
mov eax, edx {@Result}
xor edx, edx
test esi, esi {Test for S = NIL}
jz @@Setlen {S = NIL}
mov edx, [esi-4] {Length(S)}
@@SetLen:
lea ebx, [edx-4] {Length(S) - 4}
call system.@LStrSetLength {Create Result String}
mov edi, [edi] {@Result}
add esi, ebx
add edi, ebx
neg ebx
jg @@Remainder {Length(S) < 4}
@@Loop: {Loop converting 4 Characters per Loop}
mov eax, [esi+ebx]
mov ecx, $7f7f7f7f
mov edx, eax
not edx
and ecx, eax
and edx, $80808080
add ecx, $25252525
and ecx, $7f7f7f7f
add ecx, $1a1a1a1a
and ecx, edx
shr ecx, 2
add eax, ecx
mov [edi+ebx], eax
add ebx, 4
jle @@Loop
@@Remainder:
sub ebx, 4
jz @@Done
@@SmallLoop: {Loop converting 1 Character per Loop}
movzx eax, [esi+ebx+4]
lea edx, [eax-'A']
cmp edx, 'Z'-'A'+1
sbb ecx, ecx
and ecx, $20
add eax, ecx
mov [edi+ebx+4], al
add ebx, 1
jnz @@SmallLoop
@@Done:
pop ebx
pop esi
pop edi
end;
function LowerCase_Sha_Pas_2_a(const s: string): string;
var
ch1, ch2, ch3, dist, term: integer;
p: pchar;
label
loop, last;
begin
if s='' then begin;
Result:=''; exit;
end;
p:=pointer(s);
//If need pure Pascal change the next line to term:=Length(s);
term:=pinteger(@p[-4])^;
SetLength(Result,term);
if term<>0 then begin;
dist:=integer(Result);
term:=integer(p+term);
dist:=dist-integer(p)-4;
loop:
ch1:=pinteger(p)^;
ch3:=$7F7F7F7F;
ch2:=ch1;
ch3:=ch3 and ch1;
ch2:=ch2 xor (-1);
ch3:=ch3 + $25252525;
ch2:=ch2 and $80808080;
ch3:=ch3 and $7F7F7F7F;
ch3:=ch3 + $1A1A1A1A;
inc(p,4);
ch3:=ch3 and ch2;
if cardinal(p)>=cardinal(term) then goto last;
ch3:=ch3 shr 2;
ch1:=ch1 + ch3;
pinteger(p+dist)^:=ch1;
goto loop;
last:
ch3:=ch3 shr 2;
term:=term-integer(p);
p:=p+dist;
ch1:=ch1 + ch3;
if term<-1
then pword(p)^:=word(ch1)
else pinteger(p)^:=ch1;
end;
end;
procedure LowerCaseStub;
asm
call SysUtils.LowerCase;
end;
end.
|
unit ListMediaFiles;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, ExtCtrls, Grids, MediaFile, BaseForm,
MediaFilesController;
type
TfrmListMediaFiles = class(TBaseForm)
PanelTop: TPanel;
BevelTop: TBevel;
MainPanel: TPanel;
BevelBottom: TBevel;
PanelBottom: TPanel;
btNewSong: TButton;
btExit: TButton;
Grid: TStringGrid;
btNewVideo: TButton;
btEdit: TButton;
btDelete: TButton;
procedure FormCreate(Sender: TObject);
procedure btNewSongClick(Sender: TObject);
procedure btEditClick(Sender: TObject);
procedure btDeleteClick(Sender: TObject);
procedure btNewVideoClick(Sender: TObject);
procedure GridDblClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FController: TMediaFilesController;
procedure LoadMediaFiles;
function GetSelectedMediaFile: TMediaFile;
end;
implementation
uses
Generics.Collections,
Song, Video,
EditAlbum, EditSong, EditVideo;
{$R *.dfm}
procedure TfrmListMediaFiles.btEditClick(Sender: TObject);
var
MediaFile: TMediaFile;
frmEditSong: TfrmEditSong;
frmEditVideo: TfrmEditVideo;
begin
MediaFile := GetSelectedMediaFile;
if MediaFile is TSong then
begin
frmEditSong := TfrmEditSong.Create(Self);
try
frmEditSong.SetSong(TSong(MediaFile).Id);
frmEditSong.ShowModal;
if frmEditSong.ModalResult = mrOk then
LoadMediaFiles;
finally
frmEditSong.Free;
end;
end
else if MediaFile is TVideo then
begin
frmEditVideo := TfrmEditVideo.Create(Self);
try
frmEditVideo.SetVideo(TVideo(MediaFile).Id);
frmEditVideo.ShowModal;
if frmEditVideo.ModalResult = mrOk then
LoadMediaFiles;
finally
frmEditVideo.Free;
end;
end;
end;
procedure TfrmListMediaFiles.btDeleteClick(Sender: TObject);
var
MediaFile: TMediaFile;
Msg: string;
begin
MediaFile := GetSelectedMediaFile;
Msg := 'Are you sure you want to delete Media File "' + MediaFile.MediaName + '"?';
if MessageDlg(Msg, mtWarning, mbYesNo, 0) = mrYes then
begin
FController.DeleteMediaFile(MediaFile);
LoadMediaFiles;
end;
end;
procedure TfrmListMediaFiles.btNewSongClick(Sender: TObject);
var
frmEditSong: TfrmEditSong;
begin
frmEditSong := TfrmEditSong.Create(Self);
try
frmEditSong.ShowModal;
if frmEditSong.ModalResult = mrOk then
LoadMediaFiles;
finally
frmEditSong.Free;
end;
end;
procedure TfrmListMediaFiles.btNewVideoClick(Sender: TObject);
var
frmEditVideo: TfrmEditVideo;
begin
frmEditVideo := TfrmEditVideo.Create(Self);
try
frmEditVideo.ShowModal;
if frmEditVideo.ModalResult = mrOk then
LoadMediaFiles;
finally
frmEditVideo.Free;
end;
end;
procedure TfrmListMediaFiles.LoadMediaFiles;
var
MediaFiles: TList<TMediaFile>;
MediaFile: TMediaFile;
I, J: Integer;
begin
for I := 0 to Grid.RowCount - 1 do
for J := 0 to Grid.ColCount - 1 do
Grid.Cells[J, I] := '';
Grid.RowCount := 2;
Grid.Cells[0, 0] := 'Type';
Grid.Cells[1, 0] := 'Name';
Grid.Cells[2, 0] := 'Artist';
Grid.Cells[3, 0] := 'Album';
Grid.Cells[4, 0] := 'Duration';
Grid.Cells[5, 0] := 'File Location';
MediaFiles := FController.GetAllMediaFiles;
try
if MediaFiles.Count > 0 then
begin
Grid.RowCount := 1 + MediaFiles.Count;
for I := 0 to MediaFiles.Count - 1 do
begin
MediaFile := MediaFiles[I];
Grid.Cols[0].Objects[I + 1] := MediaFile;
if MediaFile is TSong then
Grid.Cells[0, I + 1] := 'Song'
else
Grid.Cells[0, I + 1] := 'Video';
Grid.Cells[1, I + 1] := MediaFile.MediaName;
if MediaFile.Artist <> nil then
Grid.Cells[2, I + 1] := MediaFile.Artist.ArtistName;
if MediaFile.Album <> nil then
Grid.Cells[3, I + 1] := MediaFile.Album.AlbumName;
if MediaFile.Duration.HasValue then
Grid.Cells[4, I + 1] := Format(
'%s:%s',
[FormatFloat('#0', MediaFile.Duration.Value div 60),
FormatFloat('00', MediaFile.Duration.Value mod 60)
]);
Grid.Cells[5, I + 1] := MediaFile.FileLocation;
end;
end;
finally
MediaFiles.Free;
end;
end;
procedure TfrmListMediaFiles.FormCreate(Sender: TObject);
begin
FController := TMediaFilesController.Create;
LoadMediaFiles;
end;
procedure TfrmListMediaFiles.FormDestroy(Sender: TObject);
begin
FController.Free;
end;
function TfrmListMediaFiles.GetSelectedMediaFile: TMediaFile;
begin
Result := TMediaFile(Grid.Cols[0].Objects[Grid.Row]);
end;
procedure TfrmListMediaFiles.GridDblClick(Sender: TObject);
begin
BtEditClick(Sender);
end;
end.
|
unit Bounce;
interface
type
HCkEmail = Pointer;
HCkBounce = Pointer;
HCkString = Pointer;
function CkBounce_Create: HCkBounce; stdcall;
procedure CkBounce_Dispose(handle: HCkBounce); stdcall;
procedure CkBounce_getBounceAddress(objHandle: HCkBounce; outPropVal: HCkString); stdcall;
function CkBounce__bounceAddress(objHandle: HCkBounce): PWideChar; stdcall;
procedure CkBounce_getBounceData(objHandle: HCkBounce; outPropVal: HCkString); stdcall;
function CkBounce__bounceData(objHandle: HCkBounce): PWideChar; stdcall;
function CkBounce_getBounceType(objHandle: HCkBounce): Integer; stdcall;
procedure CkBounce_getDebugLogFilePath(objHandle: HCkBounce; outPropVal: HCkString); stdcall;
procedure CkBounce_putDebugLogFilePath(objHandle: HCkBounce; newPropVal: PWideChar); stdcall;
function CkBounce__debugLogFilePath(objHandle: HCkBounce): PWideChar; stdcall;
procedure CkBounce_getLastErrorHtml(objHandle: HCkBounce; outPropVal: HCkString); stdcall;
function CkBounce__lastErrorHtml(objHandle: HCkBounce): PWideChar; stdcall;
procedure CkBounce_getLastErrorText(objHandle: HCkBounce; outPropVal: HCkString); stdcall;
function CkBounce__lastErrorText(objHandle: HCkBounce): PWideChar; stdcall;
procedure CkBounce_getLastErrorXml(objHandle: HCkBounce; outPropVal: HCkString); stdcall;
function CkBounce__lastErrorXml(objHandle: HCkBounce): PWideChar; stdcall;
function CkBounce_getLastMethodSuccess(objHandle: HCkBounce): wordbool; stdcall;
procedure CkBounce_putLastMethodSuccess(objHandle: HCkBounce; newPropVal: wordbool); stdcall;
function CkBounce_getVerboseLogging(objHandle: HCkBounce): wordbool; stdcall;
procedure CkBounce_putVerboseLogging(objHandle: HCkBounce; newPropVal: wordbool); stdcall;
procedure CkBounce_getVersion(objHandle: HCkBounce; outPropVal: HCkString); stdcall;
function CkBounce__version(objHandle: HCkBounce): PWideChar; stdcall;
function CkBounce_ExamineEmail(objHandle: HCkBounce; email: HCkEmail): wordbool; stdcall;
function CkBounce_ExamineEml(objHandle: HCkBounce; emlFilename: PWideChar): wordbool; stdcall;
function CkBounce_ExamineMime(objHandle: HCkBounce; mimeText: PWideChar): wordbool; stdcall;
function CkBounce_SaveLastError(objHandle: HCkBounce; path: PWideChar): wordbool; stdcall;
function CkBounce_UnlockComponent(objHandle: HCkBounce; unlockCode: PWideChar): wordbool; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkBounce_Create; external DLLName;
procedure CkBounce_Dispose; external DLLName;
procedure CkBounce_getBounceAddress; external DLLName;
function CkBounce__bounceAddress; external DLLName;
procedure CkBounce_getBounceData; external DLLName;
function CkBounce__bounceData; external DLLName;
function CkBounce_getBounceType; external DLLName;
procedure CkBounce_getDebugLogFilePath; external DLLName;
procedure CkBounce_putDebugLogFilePath; external DLLName;
function CkBounce__debugLogFilePath; external DLLName;
procedure CkBounce_getLastErrorHtml; external DLLName;
function CkBounce__lastErrorHtml; external DLLName;
procedure CkBounce_getLastErrorText; external DLLName;
function CkBounce__lastErrorText; external DLLName;
procedure CkBounce_getLastErrorXml; external DLLName;
function CkBounce__lastErrorXml; external DLLName;
function CkBounce_getLastMethodSuccess; external DLLName;
procedure CkBounce_putLastMethodSuccess; external DLLName;
function CkBounce_getVerboseLogging; external DLLName;
procedure CkBounce_putVerboseLogging; external DLLName;
procedure CkBounce_getVersion; external DLLName;
function CkBounce__version; external DLLName;
function CkBounce_ExamineEmail; external DLLName;
function CkBounce_ExamineEml; external DLLName;
function CkBounce_ExamineMime; external DLLName;
function CkBounce_SaveLastError; external DLLName;
function CkBounce_UnlockComponent; external DLLName;
end.
|
unit Thread.PopulaOcorrenciasJornal;
interface
uses
System.Classes, System.Generics.Collections, System.SysUtils, Model.OcorrenciasJornal, DAO.OcorrenciasJornal, Vcl.Forms,
System.UITypes;
type
TThread_PopulaOcorrenciasJornal = class(TThread)
private
{ Private declarations }
FFiltro: String;
FData1: TDate;
FData2: TDate;
FOpcao: Integer;
FdPos: Double;
ocorrencia : TOcorrenciasJornal;
ocorrencias : TObjectList<TOcorrenciasJornal>;
ocorrenciaDAO : TOcorrenciasJornalDAO;
protected
procedure Execute; override;
procedure IniciaProcesso;
procedure AtualizaProcesso;
procedure TerminaProcesso;
public
property Filtro: String read FFiltro write FFiltro;
property Opcao: Integer read FOpcao write FOpcao;
property Data1: TDate read FData1 write FData1;
property Data2: TDate read FData2 write FData2;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TThread_PopulaOcorrencias.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
uses View.OcorrenciasJornal;
{ TThread_PopulaOcorrencias }
procedure TThread_PopulaOcorrenciasJornal.Execute;
var
ocorrenciaTMP: TOcorrenciasJornal;
iTotal : Integer;
iPos : Integer;
begin
try
Synchronize(IniciaProcesso);
Screen.Cursor := crHourGlass;
ocorrenciaDAO := TOcorrenciasJornalDAO.Create();
case Self.Opcao of
0 : ocorrencias := ocorrenciaDAO.FindByStatus(StrToIntDef(Self.Filtro,0));
1 : ocorrencias := ocorrenciaDAO.FindByNumero(StrToIntDef(Self.Filtro,0));
2 : ocorrencias := ocorrenciaDAO.FindByPeriodo(FormatDateTime('yyyy-mm-dd',Self.Data1),
FormatDateTime('yyyy-mm-dd',Self.Data2), StrToIntDef(Self.Filtro,0));
3 : ocorrencias := ocorrenciaDAO.FindByAssinatura(Self.Filtro);
4 : ocorrencias := ocorrenciaDAO.FindByNome(Self.Filtro);
5 : ocorrencias := ocorrenciaDAO.FindByRoteiro(Self.Filtro);
6 : ocorrencias := ocorrenciaDAO.FindByProduto(Copy(Self.Filtro,0,Pos('-',Self.Filtro) - 1));
7 : ocorrencias := ocorrenciaDAO.FindByTipo(StrToIntDef(Copy(Self.Filtro,0,Pos('-',Self.Filtro) - 1), 0));
8 : ocorrencias := ocorrenciaDAO.FindByEndereco(Self.Filtro);
end;
iTotal := ocorrencias.Count;
iPos := 0;
if view_OcorrenciasJornal.tbPlanilha.Active then view_OcorrenciasJornal.tbPlanilha.Close;
view_OcorrenciasJornal.tbPlanilha.Open;
for ocorrenciaTMP in ocorrencias do
begin
view_OcorrenciasJornal.tbPlanilha.Insert;
view_OcorrenciasJornal.tbPlanilhaNUM_OCORRENCIA.AsInteger := ocorrenciaTMP.Numero;
view_OcorrenciasJornal.tbPlanilhaDAT_OCORRENCIA.AsDateTime := ocorrenciaTMP.DataOcorrencia;
view_OcorrenciasJornal.tbPlanilhaCOD_ASSINATURA.AsString := ocorrenciaTMP.CodigoAssinstura;
view_OcorrenciasJornal.tbPlanilhaNOM_ASSINANTE.AsString := ocorrenciaTMP.Nome;
view_OcorrenciasJornal.tbPlanilhaDES_ROTEIRO.AsString := ocorrenciaTMP.Roteiro;
view_OcorrenciasJornal.tbPlanilhaCOD_ENTREGADOR.AsInteger := ocorrenciaTMP.Entregador;
view_OcorrenciasJornal.tbPlanilhaCOD_PRODUTO.AsString := ocorrenciaTMP.Produto;
view_OcorrenciasJornal.tbPlanilhaCOD_OCORRENCIA.AsInteger := ocorrenciaTMP.CodigoOcorrencia;
view_OcorrenciasJornal.tbPlanilhaDOM_REINCIDENTE.AsString := ocorrenciaTMP.Reincidente;
view_OcorrenciasJornal.tbPlanilhaDES_DESCRICAO.AsString := ocorrenciaTMP.Descricao;
view_OcorrenciasJornal.tbPlanilhaDES_ENDERECO.AsString := ocorrenciaTMP.Endereco;
view_OcorrenciasJornal.tbPlanilhaDES_RETORNO.AsString := ocorrenciaTMP.Retorno;
view_OcorrenciasJornal.tbPlanilhaCOD_RESULTADO.AsInteger := ocorrenciaTMP.Resultado;
view_OcorrenciasJornal.tbPlanilhaCOD_ORIGEM.AsInteger := ocorrenciaTMP.Origem;
view_OcorrenciasJornal.tbPlanilhaDES_OBS.AsString := ocorrenciaTMP.Obs;
view_OcorrenciasJornal.tbPlanilhaCOD_STATUS.AsInteger := ocorrenciaTMP.Status;
view_OcorrenciasJornal.tbPlanilhaDES_APURACAO.Text := ocorrenciaTMP.Apuracao;
view_OcorrenciasJornal.tbPlanilhaDOM_PROCESSADO.AsString := ocorrenciaTMP.Processado;
view_OcorrenciasJornal.tbPlanilhaQTD_OCORRENCIAS.AsInteger := ocorrenciaTMP.Qtde;
view_OcorrenciasJornal.tbPlanilhaVAL_OCORRENCIA.AsFloat := ocorrenciaTMP.Valor;
view_OcorrenciasJornal.tbPlanilhaDAT_DESCONTO.AsDateTime := ocorrenciaTMP.DataDesconto;
view_OcorrenciasJornal.tbPlanilhaDES_LOG.Text := ocorrenciaTMP.Log;
view_OcorrenciasJornal.tbPlanilhaDES_CHAVE.AsString := '';
view_OcorrenciasJornal.tbPlanilhaDOM_FINALIZAR.AsBoolean := False;
view_OcorrenciasJornal.tbPlanilhaDES_ROTEIRO_NOVO.AsString := '';
view_OcorrenciasJornal.tbPlanilhaDOM_IMPRESSAO.AsString := ocorrenciaTMP.Impressao;
view_OcorrenciasJornal.tbPlanilhaDES_ANEXO.AsString := ocorrenciaTMP.Anexo;
view_OcorrenciasJornal.tbPlanilha.Post;
iPos := iPos + 1;
FdPos := (iPos / iTotal) * 100;
Synchronize(AtualizaProcesso);
end;
finally
Synchronize(TerminaProcesso);
Screen.Cursor := crDefault;
ocorrenciaDAO.Free;
end;
end;
procedure TThread_PopulaOcorrenciasJornal.IniciaProcesso;
begin
view_OcorrenciasJornal.pbOcorrencias.Visible := True;
view_OcorrenciasJornal.ds.Enabled := False;
view_OcorrenciasJornal.tbPlanilha.IsLoading := True;
view_OcorrenciasJornal.pbOcorrencias.Position := 0;
view_OcorrenciasJornal.pbOcorrencias.Refresh;
end;
procedure TThread_PopulaOcorrenciasJornal.AtualizaProcesso;
begin
view_OcorrenciasJornal.pbOcorrencias.Position := FdPos;
view_OcorrenciasJornal.pbOcorrencias.Properties.Text := FormatFloat('0.00%',FdPos);
view_OcorrenciasJornal.pbOcorrencias.Refresh;
end;
procedure TThread_PopulaOcorrenciasJornal.TerminaProcesso;
begin
view_OcorrenciasJornal.pbOcorrencias.Position := 0;
view_OcorrenciasJornal.pbOcorrencias.Properties.Text := '';
view_OcorrenciasJornal.pbOcorrencias.Refresh;
view_OcorrenciasJornal.tbPlanilha.IsLoading := False;
view_OcorrenciasJornal.ds.Enabled := True;
view_OcorrenciasJornal.pbOcorrencias.Visible := False;
end;
end.
|
unit DbGridColumnsUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, DBGridEh, DbGridUnit, DB, DBClient, ExtCtrls,
Menus;
type
{ TListItemData }
TListItemData = class(TObject)
Index: Integer;
Data: Pointer;
constructor Create(AIndex: Integer; AData: Pointer);
end;
{ TDbGridColumnSetupForm }
TDbGridColumnSetupForm = class(TForm)
ColumnsDataSet: TClientDataSet;
ColumnsDataSetVISIBLE: TBooleanField;
ColumnsDataSetTITLE: TStringField;
ColumnsDataSetFIELD_NAME: TStringField;
ColumnsFrame: TDbGridFrame;
ColumnsDataSetORDER_ID: TIntegerField;
ColumnsDataSetCOLUMN_REF: TIntegerField;
Panel1: TPanel;
ResetBtn: TButton;
DownBtn: TButton;
UpBtn: TButton;
CancelBtn: TButton;
OKBtn: TButton;
ColumnsDataSetALIGNMENT: TIntegerField;
procedure UpBtnClick(Sender: TObject);
procedure DownBtnClick(Sender: TObject);
procedure ResetBtnClick(Sender: TObject);
procedure ColumnsFrameGridSortMarkingChanged(Sender: TObject);
procedure ColumnsDataSetVISIBLEChange(Sender: TField);
private
procedure ResetSortMarker;
public
class function AdjustColumns(Grid: TDBGridEh): Boolean;
class function AdjustGridPanel(Grid: TDBGridEh; Lst : TStrings): Boolean;
end;
var
DbGridColumnSetupForm: TDbGridColumnSetupForm;
implementation
uses
Grids;
{$R *.dfm}
{ TListItemData }
constructor TListItemData.Create(AIndex: Integer; AData: Pointer);
begin
inherited Create;
Index := AIndex;
Data := AData;
end;
{ TDbGridColumnSetupForm }
class function TDbGridColumnSetupForm.AdjustColumns(Grid: TDBGridEh): Boolean;
var
Form: TDbGridColumnSetupForm;
I: Integer;
Column: TColumnEh;
begin
Form := TDbGridColumnSetupForm.Create(nil);
try
Form.ColumnsDataSet.CreateDataSet;
Column := Form.ColumnsFrame.Grid.Columns[1];
Column.ImageList := Grid.TitleImages;
for I := 0 to Grid.Columns.Count - 1 do
begin
Column := Grid.Columns[I];
Form.ColumnsDataSet.Append;
Form.ColumnsDataSetORDER_ID.AsInteger := I;
Form.ColumnsDataSetVISIBLE.AsBoolean := Column.Visible;
Form.ColumnsDataSetTITLE.AsString := Column.Title.Caption;
Form.ColumnsDataSetFIELD_NAME.AsString := Column.FieldName;
Form.ColumnsDataSetCOLUMN_REF.AsInteger := Integer(Column);
Form.ColumnsDataSetALIGNMENT.AsInteger := Integer(Column.Alignment);
Form.ColumnsDataSet.Post;
end;
Form.ColumnsDataSet.First;
Result := Form.ShowModal = mrOK;
if Result then
begin
Form.ColumnsDataSet.First;
while not Form.ColumnsDataSet.Eof do
begin
Column := TColumnEh(Form.ColumnsDataSetCOLUMN_REF.AsInteger);
Column.Index := Form.ColumnsDataSetORDER_ID.AsInteger;
Column.Visible := Form.ColumnsDataSetVISIBLE.AsBoolean;
Column.Alignment := TAlignment(Form.ColumnsDataSetALIGNMENT.AsInteger);
Form.ColumnsDataSet.Next;
end;
end;
finally
Form.Free;
end;
end;
class function TDbGridColumnSetupForm.AdjustGridPanel(Grid: TDBGridEh; Lst : TStrings): Boolean;
var
Form: TDbGridColumnSetupForm;
I: Integer;
Column: TColumnEh;
begin
if Lst = nil then Exit;
Form := TDbGridColumnSetupForm.Create(nil);
try
Form.ColumnsDataSet.CreateDataSet;
Column := Form.ColumnsFrame.Grid.Columns[1];
Column.ImageList := Grid.TitleImages;
// Grid['ALIGNMENT'].Visible := False;
for I := 0 to Lst.Count -1 do
begin
Column := Grid[Lst[I]];
Form.ColumnsDataSet.Append;
Form.ColumnsDataSetORDER_ID.AsInteger := I;
Form.ColumnsDataSetVISIBLE.AsBoolean := True;
Form.ColumnsDataSetTITLE.AsString := Column.Title.Caption;
Form.ColumnsDataSetFIELD_NAME.AsString := Column.FieldName;
Form.ColumnsDataSetCOLUMN_REF.AsInteger := Integer(Column);
Form.ColumnsDataSetALIGNMENT.AsInteger := Integer(Column.Alignment);
Form.ColumnsDataSet.Post;
end;
for I := 0 to Grid.Columns.Count - 1 do
begin
Column := Grid.Columns[I];
if Lst.IndexOf(Column.FieldName) > -1 then continue;
Form.ColumnsDataSet.Append;
Form.ColumnsDataSetORDER_ID.AsInteger := I;
Form.ColumnsDataSetVISIBLE.AsBoolean := False;
Form.ColumnsDataSetTITLE.AsString := Column.Title.Caption;
Form.ColumnsDataSetFIELD_NAME.AsString := Column.FieldName;
Form.ColumnsDataSetCOLUMN_REF.AsInteger := Integer(Column);
Form.ColumnsDataSetALIGNMENT.AsInteger := Integer(Column.Alignment);
Form.ColumnsDataSet.Post;
end;
Form.ColumnsDataSet.First;
Result := Form.ShowModal = mrOK;
if Result then
begin
Lst.Clear;
Form.ColumnsDataSet.First;
while not Form.ColumnsDataSet.Eof do
begin
if Form.ColumnsDataSetVISIBLE.AsBoolean then
Lst.Add(TColumnEh(Form.ColumnsDataSetCOLUMN_REF.AsInteger).FieldName);
Form.ColumnsDataSet.Next;
end;
end;
finally
Form.Free;
end;
end;
procedure TDbGridColumnSetupForm.UpBtnClick(Sender: TObject);
var
Title: string;
OrderId, Delta: Integer;
Rect: TGridRect;
Rectangled: Boolean;
begin
Title := ColumnsDataSetTITLE.AsString;
Rectangled := ColumnsFrame.Grid.Selection.SelectionType = gstRectangle;
if Rectangled then
begin
Rect := ColumnsFrame.Grid.Selection.SelectionToGridRect;
Delta := Rect.Bottom - Rect.Top + 1;
ColumnsDataSet.Bookmark := ColumnsFrame.Grid.Selection.Rect.TopRow;
end else Delta := 1;
OrderId := ColumnsDataSetORDER_ID.AsInteger;
if OrderId = 0 then Exit;
ColumnsDataSet.DisableControls;
try
ColumnsDataSet.IndexName := '';
ColumnsDataSet.First;
while not ColumnsDataSet.Eof do
begin
if ColumnsDataSetORDER_ID.AsInteger = OrderId - 1 then
begin
ColumnsDataSet.Edit;
ColumnsDataSetORDER_ID.AsInteger := ColumnsDataSetORDER_ID.AsInteger + Delta;
ColumnsDataSet.Post;
end else if (ColumnsDataSetORDER_ID.AsInteger >= OrderId) and
(ColumnsDataSetORDER_ID.AsInteger < OrderId + Delta) then
begin
ColumnsDataSet.Edit;
ColumnsDataSetORDER_ID.AsInteger := ColumnsDataSetORDER_ID.AsInteger - 1;
ColumnsDataSet.Post;
end;
ColumnsDataSet.Next;
end;
ColumnsDataSet.IndexName := 'ORDER_ID_A';
ColumnsFrame.Grid.Selection.Clear;
if Rectangled then
begin
ColumnsDataSet.First;
ColumnsDataSet.MoveBy(OrderId - 1);
ColumnsFrame.Grid.Selection.Rect.Select(Rect.Left, ColumnsDataSet.Bookmark, True);
ColumnsDataSet.MoveBy(Delta - 1);
ColumnsFrame.Grid.Selection.Rect.Select(Rect.Right, ColumnsDataSet.Bookmark, True);
end;
ColumnsDataSet.Locate('TITLE', Title, []);
ResetSortMarker;
finally
ColumnsDataSet.EnableControls;
end;
end;
procedure TDbGridColumnSetupForm.DownBtnClick(Sender: TObject);
var
Title: string;
OrderId, Delta: Integer;
Rect: TGridRect;
Rectangled: Boolean;
begin
Title := ColumnsDataSetTITLE.AsString;
Rectangled := ColumnsFrame.Grid.Selection.SelectionType = gstRectangle;
if Rectangled then
begin
Rect := ColumnsFrame.Grid.Selection.SelectionToGridRect;
Delta := Rect.Bottom - Rect.Top + 1;
ColumnsDataSet.Bookmark := ColumnsFrame.Grid.Selection.Rect.BottomRow;
end else Delta := 1;
OrderId := ColumnsDataSetORDER_ID.AsInteger;
if OrderId = ColumnsDataSet.RecordCount - 1 then Exit;
ColumnsDataSet.DisableControls;
try
ColumnsDataSet.IndexName := '';
ColumnsDataSet.First;
while not ColumnsDataSet.Eof do
begin
if ColumnsDataSetORDER_ID.AsInteger = OrderId + 1 then
begin
ColumnsDataSet.Edit;
ColumnsDataSetORDER_ID.AsInteger := ColumnsDataSetORDER_ID.AsInteger - Delta;
ColumnsDataSet.Post;
end else if (ColumnsDataSetORDER_ID.AsInteger <= OrderId) and
(ColumnsDataSetORDER_ID.AsInteger > OrderId - Delta) then
begin
ColumnsDataSet.Edit;
ColumnsDataSetORDER_ID.AsInteger := ColumnsDataSetORDER_ID.AsInteger + 1;
ColumnsDataSet.Post;
end;
ColumnsDataSet.Next;
end;
ColumnsDataSet.IndexName := 'ORDER_ID_A';
ColumnsFrame.Grid.Selection.Clear;
if Rectangled then
begin
ColumnsDataSet.First;
ColumnsDataSet.MoveBy(OrderId - Delta + 2);
ColumnsFrame.Grid.Selection.Rect.Select(Rect.Left, ColumnsDataSet.Bookmark, True);
ColumnsDataSet.MoveBy(Delta - 1);
ColumnsFrame.Grid.Selection.Rect.Select(Rect.Right, ColumnsDataSet.Bookmark, True);
end;
ColumnsDataSet.Locate('TITLE', Title, []);
ResetSortMarker;
finally
ColumnsDataSet.EnableControls;
end;
end;
procedure TDbGridColumnSetupForm.ResetSortMarker;
var
I: Integer;
begin
for I := 0 to ColumnsFrame.Grid.Columns.Count - 1 do
ColumnsFrame.Grid.Columns[I].Title.SortMarker := smNoneEh;
end;
procedure TDbGridColumnSetupForm.ResetBtnClick(Sender: TObject);
begin
ColumnsDataSet.IndexName := '';
ColumnsFrame.Grid.Selection.Clear;
ColumnsDataSet.DisableControls;
try
ColumnsDataSet.First;
while not ColumnsDataSet.Eof do
begin
ColumnsDataSet.Edit;
ColumnsDataSetORDER_ID.AsInteger := TColumnEh(ColumnsDataSetCOLUMN_REF.AsInteger).ID;
ColumnsDataSetVISIBLE.AsBoolean := True;
ColumnsDataSet.Post;
ColumnsDataSet.Next;
end;
ColumnsDataSet.IndexName := 'ORDER_ID_A';
ColumnsDataSet.First;
finally
ColumnsDataSet.EnableControls;
end;
ResetSortMarker;
end;
procedure TDbGridColumnSetupForm.ColumnsFrameGridSortMarkingChanged(Sender: TObject);
var
I: Integer;
Ref: Integer;
begin
ColumnsFrame.GridSortMarkingChanged(Sender);
I := 0;
ColumnsDataSet.DisableControls;
try
Ref := ColumnsDataSetCOLUMN_REF.AsInteger;
ColumnsDataSet.First;
while not ColumnsDataSet.Eof do
begin
ColumnsDataSet.Edit;
ColumnsDataSetORDER_ID.AsInteger := I;
ColumnsDataSet.Post;
Inc(I);
ColumnsDataSet.Next;
end;
ColumnsDataSet.Locate('COLUMN_REF', Ref, []);
finally
ColumnsDataSet.EnableControls;
end;
end;
procedure TDbGridColumnSetupForm.ColumnsDataSetVISIBLEChange(
Sender: TField);
begin
if ColumnsDataSetVISIBLE.IsNull then ColumnsDataSetVISIBLE.AsBoolean := False;
end;
end.
|
// ***************************************************************************
// ************************** VECTORS UNIT ***********************************
// ********************** Juan Josť Montero *******************************
// ******************* juanjo.montero@telefonica.net *************************
// *********************** Release 19/11/2003 ********************************
// ***************************************************************************
unit Vectors;
interface
uses Windows;
type
TVector2D = record
X, Y:Single;
end;
TVector3D = record
X, Y, Z:Single;
end;
TByteColor = record
Red,
Green,
Blue: Byte;
end;
PVector4f = ^TVector4f;
TVector4f = record
Red:Single;
Green:Single;
Blue:Single;
Alpha:Single;
end;
TMatrix4D=array[0..3, 0..3] of Single;
function VectorSetValue(Value:Single): TVector3D; overload;
function VectorSetValue(X, Y, Z: Single): TVector3D; overload;
procedure VectorClear(var Vector:TVector3D); overload;
procedure VectorClear(var Vector:TVector2D); overload;
procedure VectorInvert(var Vector:TVector3D);
function VectorSize(const Vector:TVector3D) : Single;
function VectorNormalize(var Vector:TVector3D) : Single;
function VectorSquareNorm(const Vector:TVector3D) : Single;
function VectorAdd(const Vector1, Vector2:TVector3D):TVector3D; overload;
procedure VectorAdd(var Vector:TVector3D; Value : Single); overload;
function VectorSub(const Vector1, Vector2:TVector3D) : TVector3D; overload;
procedure VectorSub(var Vector:TVector3D; Value : Single); overload;
function VectorDivide(const Vector1, Vector2:TVector3D):TVector3D;overload;
function VectorDivide(const Vector:TVector3D; Value:Single):TVector3D;overload;
function VectorMultiply(const Vector1, Vector2:TVector3D):TVector3D; overload;
function VectorMultiply(const Vector1: TVector3D; Value: Single):TVector3D; overload;
procedure VectorScale(var Vector:TVector3D; Value:Single);
function VectorCrossProduct(const Vector1, Vector2:TVector3D):TVector3D;
function VectorDotProduct(const Vector1, Vector2:TVector3D):Single;
procedure VectorRotateX(Angle:Single; var Vector:TVector3D);
procedure VectorRotateY(Angle:Single; var Vector:TVector3D);
procedure VectorRotateZ(Angle:Single; var Vector:TVector3D);
function VectorIsEqual(const Vector1, Vector2:TVector3D):Boolean;
function VectorIsGreater(const Vector1, Vector2:TVector3D):Boolean;
function VectorIsGreaterEqual(const Vector1, Vector2:TVector3D):Boolean;
function VectorIsLess(const Vector1, Vector2:TVector3D):Boolean;
function VectorIsLessEqual(const Vector1, Vector2:TVector3D):Boolean;
function ByteColorTo4f(const BytesToWrap:TByteColor):TVector4f;
function Color4fToByte(const BytesToWrap:TVector4f):TByteColor;
function TriangleNormal(Vert1, Vert2, Vert3: TVector3D): TVector3D;
function TriangleAngle(Vert1, Vert2, Vert3: TVector3D): Single;
implementation
uses Math;
function VectorSetValue(Value:Single):TVector3D;
begin
Result.X:=Value;
Result.Y:=Value;
Result.Z:=Value;
end;
function VectorSetValue(X, Y, Z: Single): TVector3D;
begin
Result.X:=X;
Result.Y:=Y;
Result.Z:=Z;
end;
procedure VectorClear(var Vector:TVector3D);
begin
ZeroMemory(@Vector, SizeOf(TVector3D));
end;
procedure VectorClear(var Vector:TVector2D);
begin
ZeroMemory(@Vector, SizeOf(TVector2D));
end;
procedure VectorInvert(var Vector:TVector3D);
begin
Vector.X := -Vector.X;
Vector.Y := -Vector.Y;
Vector.Z := -Vector.Z;
end;
function VectorSize(const Vector:TVector3D):Single;
begin
Result:=Sqrt((Vector.X * Vector.X) + (Vector.Y * Vector.Y) + (Vector.Z * Vector.Z));
end;
{function VectorNormalize(var Vector:TVector3D):Single;
var ScaleFactor:Single;
begin
Result:=VectorSize(Vector);
if (Result=0.0) then
Exit;
ScaleFactor:=1.0/Result;
Vector.X := Vector.X * ScaleFactor;
Vector.Y := Vector.Y * ScaleFactor;
Vector.Z := Vector.Z * ScaleFactor;
end;}
function VectorNormalize(var Vector:TVector3D):Single;
begin
Result:=VectorSize(Vector);
if (Result=0.0) then
Exit;
Vector.X := Vector.X / Result;
Vector.Y := Vector.Y / Result;
Vector.Z := Vector.Z / Result;
end;
function VectorSquareNorm(const Vector:TVector3D):Single;
begin
Result := Vector.X * Vector.X;
Result := Result + (Vector.Y * Vector.Y);
Result := Result + (Vector.Z * Vector.Z);
end;
function VectorAdd(const Vector1, Vector2:TVector3D):TVector3D; overload;
begin
Result.X := Vector1.X + Vector2.X;
Result.Y := Vector1.Y + Vector2.Y;
Result.Z := Vector1.Z + Vector2.Z;
end;
procedure VectorAdd(var Vector:TVector3D; Value : Single);overload;
begin
Vector.X := Vector.X + Value;
Vector.Y := Vector.Y + Value;
Vector.Z := Vector.Z + Value;
end;
function VectorSub(const Vector1, Vector2:TVector3D) : TVector3D; overload;
begin
Result.X := Vector1.X - Vector2.X;
Result.Y := Vector1.Y - Vector2.Y;
Result.Z := Vector1.Z - Vector2.Z;
end;
procedure VectorSub(var Vector:TVector3D; Value : Single); overload;
begin
Vector.X := Vector.X - Value;
Vector.Y := Vector.Y - Value;
Vector.Z := Vector.Z - Value;
end;
function VectorDivide(const Vector1, Vector2:TVector3D):TVector3D;overload
begin
Result.X := Vector1.X / Vector2.X;
Result.Y := Vector1.Y / Vector2.Y;
Result.Z := Vector1.Z / Vector2.Z;
end;
function VectorDivide(const Vector:TVector3D; Value:Single):TVector3D;overload;
begin
Result.X := Vector.X / Value;
Result.Y := Vector.Y / Value;
Result.Z := Vector.Z / Value;
end;
function VectorMultiply(const Vector1, Vector2:TVector3D):TVector3D; overload;
begin
Result.X := Vector1.X * Vector2.X;
Result.Y := Vector1.Y * Vector2.Y;
Result.Z := Vector1.Z * Vector2.Z;
end;
function VectorMultiply(const Vector1: TVector3D; Value: Single):TVector3D;
begin
Result.X := Vector1.X * Value;
Result.Y := Vector1.Y * Value;
Result.Z := Vector1.Z * Value;
end;
procedure VectorScale(var Vector:TVector3D; Value:Single);
begin
Vector.X := Vector.X * Value;
Vector.Y := Vector.Y * Value;
Vector.Z := Vector.Z * Value;
end;
function VectorCrossProduct(const Vector1, Vector2:TVector3D):TVector3D;
begin
Result.X := (Vector1.Y * Vector2.Z) - (Vector1.Z * Vector2.Y);
Result.Y := (Vector1.Z * Vector2.X) - (Vector1.X * Vector2.Z);
Result.Z := (Vector1.X * Vector2.Y) - (Vector1.Y * Vector2.X);
end;
function VectorDotProduct(const Vector1, Vector2:TVector3D):Single;
begin
Result := (Vector1.X * Vector2.X) + (Vector1.Y * Vector2.Y) + (Vector1.Z * Vector2.Z);
end;
procedure VectorRotateX(Angle:Single; var Vector:TVector3D);
var Y0, Z0 : Single;
Radians : Single;
begin
Y0 := Vector.Y;
Z0 := Vector.Z;
Radians := DegToRad(Angle);
Vector.Y := (Y0 * Cos(Radians)) - (Z0 * Sin(Radians));
Vector.Z := (Y0 * Sin(Radians)) + (Z0 * Cos(Radians));
end;
procedure VectorRotateY(Angle:Single; var Vector:TVector3D);
var X0, Z0 : Single;
Radians : Single;
begin
X0 := Vector.X;
Z0 := Vector.Z;
Radians := DegToRad(Angle);
Vector.X := (X0 * Cos(Radians)) - (Z0 * Sin(Radians));
Vector.Z := (X0 * Sin(Radians)) + (Z0 * Cos(Radians));
end;
procedure VectorRotateZ(Angle:Single; var Vector:TVector3D);
var X0, Y0 : Single;
Radians : Single;
begin
X0 := Vector.X;
Y0 := Vector.Y;
Radians := DegToRad(Angle);
Vector.X := (X0 * Cos(Radians)) - (Y0 * Sin(Radians));
Vector.Y := (X0 * Sin(Radians)) + (Y0 * Cos(Radians));
end;
function VectorIsEqual(const Vector1, Vector2:TVector3D):Boolean;
begin
Result:=(Vector1.X=Vector2.X) and (Vector1.Y=Vector2.Y) and (Vector1.Z=Vector2.Z);
end;
function VectorIsGreater(const Vector1, Vector2:TVector3D):Boolean;
begin
Result:=(Vector1.X>Vector2.X) and (Vector1.Y>Vector2.Y) and (Vector1.Z>Vector2.Z);
end;
function VectorIsGreaterEqual(const Vector1, Vector2:TVector3D):Boolean;
begin
Result:=(Vector1.X>=Vector2.X) and (Vector1.Y>=Vector2.Y) and (Vector1.Z>=Vector2.Z);
end;
function VectorIsLess(const Vector1, Vector2:TVector3D):Boolean;
begin
Result:=(Vector1.X<Vector2.X) and (Vector1.Y<Vector2.Y) and (Vector1.Z<Vector2.Z);
end;
function VectorIsLessEqual(const Vector1, Vector2:TVector3D):Boolean;
begin
Result:=(Vector1.X<=Vector2.X) and (Vector1.Y<=Vector2.Y) and (Vector1.Z<=Vector2.Z);
end;
function ByteColorTo4f(const BytesToWrap:TByteColor):TVector4f;
const Scaler:Single = 1.0/255.0;
begin
Result.Red:=BytesToWrap.Red * Scaler;
Result.Green:=BytesToWrap.Green * Scaler;
Result.Blue:=BytesToWrap.Blue * Scaler;
Result.Alpha:=1.0;
end;
function Color4fToByte(const BytesToWrap:TVector4f):TByteColor;
begin
Result.Red:=Trunc(BytesToWrap.Red * 255);
Result.Green:=Trunc(BytesToWrap.Green * 255);
Result.Blue:=Trunc(BytesToWrap.Blue * 255);
end;
function TriangleNormal(Vert1, Vert2, Vert3: TVector3D): TVector3D;
begin
Vert2:=VectorSub(Vert1, Vert2);
Vert3:=VectorSub(Vert1, Vert3);
Result:=VectorCrossProduct(Vert2, Vert3);
VectorNormalize(Result);
end;
function TriangleAngle(Vert1, Vert2, Vert3: TVector3D): Single;
begin
Vert2:=VectorSub(Vert1, Vert2);
Vert3:=VectorSub(Vert1, Vert3);
Result:=arccos(VectorDotProduct(Vert2, Vert3)/(VectorSize(Vert2)*VectorSize(Vert3)));
end;
end.
|
{
wzsTools components
(c) Protasov Serg
wzonnet.blogspot.com
wzff.livejournal.com
wzonnet@kemcity.ru
}
unit u_wzsToolsEditors;
interface
uses
Windows, Messages, SysUtils {$ifdef ver150}, Variants {$endif}, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Contnrs
{$ifdef ver150}, DesignEditors, DesignIntf {$else}, DsgnIntf {$endif};
type
TwzsApplyProc = procedure(var Component: TComponent) of object;
TwzsToolsEditor = class(TComponentEditor)
private
protected
procedure ShowDesignerForm; virtual;
public
Version: string;
SelectedComponents: TComponentList;
procedure Edit; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
function GetSelectionByClass(ClassType: TClass): TComponentList;
procedure ApplyProcOnList(Proc: TwzsApplyProc);
end;
TwzsAboutInfoProperty = class(TStringProperty)
protected
procedure ShowAboutForm; virtual;
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
function GetValue: string; override;
end;
procedure Register;
procedure RegAboutProp(ComponentClass: TClass);
implementation
uses u_wzsToolsCommon, u_wzsToolsDesForm, u_wzsStyler;
procedure RegAboutProp(ComponentClass: TClass);
begin
RegisterPropertyEditor(TypeInfo(TwzsAboutInfo),
ComponentClass, 'About', TwzsAboutInfoProperty);
end;
procedure Register;
begin
RegisterComponentEditor(TwzsStyler, TwzsToolsEditor);
RegAboutProp(TwzsStyler);
end;
{ TwzsToolsEditor }
procedure TwzsToolsEditor.ShowDesignerForm;
var
DesignerForm: TwzsToolsDesForm;
begin
SelectedComponents:=GetSelectionByClass(Component.ClassType);
DesignerForm:=TwzsToolsDesForm.Create(nil);
DesignerForm.Editor:=self;
DesignerForm.ShowModal;
Designer.Modified;
end;
procedure TwzsToolsEditor.Edit;
begin
ShowDesignerForm;
end;
procedure TwzsToolsEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: Edit;
end;
end;
function TwzsToolsEditor.GetVerb(Index: Integer): string;
begin
case index of
0: result:='Edit...';
end;
end;
function TwzsToolsEditor.GetVerbCount: Integer;
begin
result:=1;
end;
{ TwzsAboutInfoProperty }
procedure TwzsAboutInfoProperty.Edit;
begin
{$ifdef ver150}
Designer.Edit(GetComponent(0) as TComponent);
{$else}
ShowAboutForm;
{$endif}
end;
function TwzsAboutInfoProperty.GetAttributes: TPropertyAttributes;
begin
result:=[paReadOnly, paDialog];
end;
function TwzsAboutInfoProperty.GetValue: string;
begin
result:=authTitle+' ['+urlFirst+', '+urlMail+']';
end;
function TwzsToolsEditor.GetSelectionByClass(
ClassType: TClass): TComponentList;
var
{$ifdef ver150}
sel: IDesignerSelections;
{$else}
sel: TDesignerSelectionList;
{$endif}
list: TComponentList;
c: TComponent;
i: integer;
begin
{$ifdef ver150}
sel:=TDesignerSelections.Create;
{$else}
sel:=TDesignerSelectionList.create;
{$endif}
list:=TComponentList.Create;
Designer.GetSelections(sel);
for i:=0 to sel.Count-1 do
begin
c:=sel.Items[i] as TComponent;
if c is ClassType then
list.Add(c);
end;
result:=list;
end;
procedure TwzsToolsEditor.ApplyProcOnList(Proc: TwzsApplyProc);
var
i: integer;
component: TComponent;
begin
if SelectedComponents<>nil then
for i:=0 to SelectedComponents.Count-1 do
begin
component:=SelectedComponents[i];
Proc(component);
end;
end;
procedure TwzsAboutInfoProperty.ShowAboutForm;
var
DesignerForm: TwzsToolsDesForm;
begin
DesignerForm:=TwzsToolsDesForm.Create(nil);
DesignerForm.Component:=GetComponent(0) as TComponent;
DesignerForm.ShowModal;
end;
end.
|
unit OperType;
interface
Uses Classes,SysUtils,TSQLCls;
Type TName=string[128];
Type TGUIObject=class(TObject)
public
DisplayLabel : TName;
PhysicalName : TName;
end;
Type TGUILogicOperation=class(TGUIObject)
public
DisplayLabel : TName;
PhysicalName : TName;
constructor Create(dPhysicalName,dDisplayLabel:TName);
end;
{==================== Field Type ====================}
Type TGUIFieldType=class(TGUIObject)
public
procedure GetOpers(var sl:TStringList); virtual;
function ValueToStr(Value:string):string; virtual;
function CheckValue(Value:string):boolean; virtual;
function DefaultValue:string; virtual;
function GetField(FieldName:TName):string; virtual;
end;
Type TGUIInteger=class(TGUIFieldType)
constructor Create;
function CheckValue(Value:string):boolean; override;
function DefaultValue:string; override;
end;
Type TGUIString=class(TGUIFieldType)
constructor Create;
procedure GetOpers(var sl:TStringList); override;
function ValueToStr(Value:string):string; override;
function GetField(FieldName:TName):string; override;
end;
Type TGUIDate=class(TGUIFieldType)
constructor Create;
function CheckValue(Value:string):boolean; override;
function ValueToStr(Value:string):string; override;
function DefaultValue:string; override;
end;
Type TGUITime=class(TGUIFieldType)
constructor Create;
function CheckValue(Value:string):boolean; override;
function ValueToStr(Value:string):string; override;
function DefaultValue:string; override;
end;
Type TGUIMultiString=class(TGUIString)
constructor Create;
procedure GetOpers(var sl:TStringList); override;
end;
Type TGUIFloat=class(TGUIFieldType)
constructor Create;
function CheckValue(Value:string):boolean; override;
function DefaultValue:string; override;
end;
{==================== Operations ====================}
Type TGUIOperation=class(TGUIObject)
public
function OperToStr(LeftField:TName;LeftFieldType:TGUIFieldType;Value:string;
RightField:TName;SymbolCount:longint):string; virtual;
function RightPartPresent:boolean; virtual;
function RightPartCanBeField:boolean; virtual;
end;
Type TGUIEqu=class(TGUIOperation)
public
constructor Create;
end;
Type TGUIBelow=class(TGUIOperation)
public
constructor Create;
end;
Type TGUIAbove=class(TGUIOperation)
public
constructor Create;
end;
Type TGUIBelowEqu=class(TGUIOperation)
public
constructor Create;
end;
Type TGUIAboveEqu=class(TGUIOperation)
public
constructor Create;
end;
Type TGUINotEqu=class(TGUIOperation)
public
constructor Create;
end;
Type TGUIUnaryOperation=class(TGUIOperation)
public
function RightPartPresent:boolean; override;
function RightPartCanBeField:boolean; override;
end;
Type TGUIRightPartCanNotBeField=class(TGUIOperation)
public
function RightPartPresent:boolean; override;
function RightPartCanBeField:boolean; override;
end;
Type TGUIIsNull=class(TGUIUnaryOperation)
public
constructor Create;
end;
Type TGUIIsNotNull=class(TGUIUnaryOperation)
public
constructor Create;
end;
Type TGUIBegin=class(TGUIRightPartCanNotBeField)
public
constructor Create;
function OperToStr(LeftField:TName;LeftFieldType:TGUIFieldType;Value:string;
RightField:TName;SymbolCount:longint):string; override;
end;
Type TGUISubStr=class(TGUIRightPartCanNotBeField)
public
constructor Create;
function OperToStr(LeftField:TName;LeftFieldType:TGUIFieldType;Value:string;
RightField:TName;SymbolCount:longint):string; override;
end;
Procedure CreateOpers;
Procedure DestroyOpers;
function LogOperByLabel(lb:string):TGUILogicOperation;
function RelOperByLabel(lb:string):TGUIOperation;
function LTrim(s:string):string;
Const OpersCount=10;
LogOpersCount=2;
FieldsTypesCount=6;
MainOpers=2;
NullOpers=8;
Var
RequestsCount : integer;
LogOpers : array [0..LogOpersCount-1] of TGUILogicOperation;
Opers : array [0..OpersCount-1] of TGUIOperation;
FieldsTypes : array [0..FieldsTypesCount-1] of TGUIFieldType;
implementation
constructor TGUILogicOperation.Create(dPhysicalName,dDisplayLabel:TName);
begin
PhysicalName:=dPhysicalName;
DisplayLabel:=dDisplayLabel
end;
{=================== Fields Types ===================}
procedure TGUIFieldType.GetOpers(var sl:TStringList);
var i:integer;
begin
for i:=MainOpers to OpersCount-1 do
sl.AddObject(Opers[i].DisplayLabel,Opers[i]);
end;
function TGUIFieldType.ValueToStr(Value:string):string;
begin
ValueToStr:=Value;
end;
function TGUIFieldType.CheckValue(Value:string):boolean;
begin
CheckValue:=TRUE;
end;
function TGUIFieldType.DefaultValue:string;
begin
DefaultValue:='';
end;
function TGUIFieldType.GetField(FieldName:TName):string;
begin
GetField:=sql.Keyword(FieldName);
end;
constructor TGUIInteger.Create;
begin
DisplayLabel:='целое';
PhysicalName:='INTEGER'
end;
function TGUIInteger.CheckValue(Value:string):boolean;
begin
try
StrToInt(Value);
CheckValue:=TRUE;
except
CheckValue:=FALSE;
end;
end;
function TGUIInteger.DefaultValue:string;
begin
DefaultValue:='0';
end;
constructor TGUIFloat.Create;
begin
DisplayLabel:='дробное';
PhysicalName:='Float'
end;
function TGUIFloat.CheckValue(Value:string):boolean;
begin
try
StrToFloat(Value);
CheckValue:=TRUE;
except
CheckValue:=FALSE;
end;
end;
function TGUIFloat.DefaultValue:string;
begin
DefaultValue:='0.0';
end;
constructor TGUIString.Create;
begin
DisplayLabel:='строка';
PhysicalName:='CHAR'
end;
procedure TGUIString.GetOpers(var sl:TStringList);
var i:integer;
begin
inherited GetOpers(sl);
for i:=0 to MainOpers-1 do
sl.AddObject(Opers[i].DisplayLabel,Opers[i]);
end;
function TGUIString.ValueToStr(Value:string):string;
begin
ValueToStr:=sql.UpperCase(sql.MakeStr(Value));
end;
function TGUIString.GetField(FieldName:TName):string;
begin
GetField:=sql.UpperCase(sql.Keyword(FieldName))
end;
constructor TGUIDate.Create;
begin
DisplayLabel:='дата';
PhysicalName:='DATE'
end;
function TGUIDate.CheckValue(Value:string):boolean;
begin
try
StrToDate(Value);
CheckValue:=TRUE;
except
CheckValue:=FALSE;
end;
end;
function TGUIDate.DefaultValue:string;
begin
DefaultValue:=DateToStr(Now);
end;
function TGUIDate.ValueToStr(Value:string):string;
begin
ValueToStr:=sql.ConvertToDate(sql.MakeStr(FormatDateTime('yyyy-mm-dd',
StrToDateTime(Value))));
end;
constructor TGUITime.Create;
begin
DisplayLabel:='время';
PhysicalName:='TIME'
end;
function TGUITime.CheckValue(Value:string):boolean;
begin
try
StrToTime(Value);
CheckValue:=TRUE;
except
CheckValue:=FALSE;
end;
end;
function TGUITime.DefaultValue:string;
begin
DefaultValue:=FormatDateTime('hh:mm',Now);
end;
function TGUITime.ValueToStr(Value:string):string;
begin
ValueToStr:=sql.TimePart(sql.MakeStr(Value));
end;
constructor TGUIMultiString.Create;
begin
DisplayLabel:='много строк';
PhysicalName:='TEXT'
end;
procedure TGUIMultiString.GetOpers(var sl:TStringList);
var i:integer;
begin
for i:=0 to MainOpers-1 do
sl.AddObject(Opers[i].DisplayLabel,Opers[i]);
for i:=NullOpers to OpersCount-1 do
sl.AddObject(Opers[i].DisplayLabel,Opers[i]);
end;
{=================== Operations ===================}
function TGUIOperation.RightPartPresent:boolean;
begin
RightPartPresent:=TRUE;
end;
function TGUIOperation.RightPartCanBeField:boolean;
begin
RightPartCanBeField:=TRUE;
end;
function TGUIUnaryOperation.RightPartPresent:boolean;
begin
RightPartPresent:=FALSE;
end;
function TGUIUnaryOperation.RightPartCanBeField:boolean;
begin
RightPartCanBeField:=FALSE;
end;
constructor TGUIBelow.Create;
begin
DisplayLabel:='<';
PhysicalName:='<'
end;
constructor TGUINotEqu.Create;
begin
DisplayLabel:='<>';
PhysicalName:='<>'
end;
constructor TGUIEqu.Create;
begin
DisplayLabel:='=';
PhysicalName:='='
end;
constructor TGUIBelowEqu.Create;
begin
DisplayLabel:='<=';
PhysicalName:='<=';
end;
constructor TGUIAboveEqu.Create;
begin
DisplayLabel:='>=';
PhysicalName:='>=';
end;
constructor TGUIAbove.Create;
begin
DisplayLabel:='>';
PhysicalName:='>';
end;
constructor TGUIIsNull.Create;
begin
DisplayLabel:='пусто';
PhysicalName:='IS NULL';
end;
constructor TGUIIsNotNull.Create;
begin
DisplayLabel:='не пусто';
PhysicalName:='IS NOT NULL';
end;
function TGUIRightPartCanNotBeField.RightPartPresent:boolean;
begin
RightPartPresent:=TRUE;
end;
function TGUIRightPartCanNotBeField.RightPartCanBeField:boolean;
begin
RightPartCanBeField:=FALSE;
end;
constructor TGUIBegin.Create;
begin
DisplayLabel:='|->';
PhysicalName:='LIKE';
end;
function TGUIBegin.OperToStr(LeftField:TName;LeftFieldType:TGUIFieldType;Value:string;
RightField:TName;SymbolCount:longint):string;
begin
OperToStr:=LeftFieldType.GetField(LeftField)+' '+PhysicalName+' '+
LeftFieldType.ValueToStr(Value+'%');
end;
constructor TGUISubStr.Create;
begin
DisplayLabel:='[ ]';
PhysicalName:='LIKE';
end;
function TGUISubStr.OperToStr(LeftField:TName;LeftFieldType:TGUIFieldType;Value:string;
RightField:TName;SymbolCount:longint):string;
begin
OperToStr:=LeftFieldType.GetField(LeftField)+' '+PhysicalName+' '+
LeftFieldType.ValueToStr('%'+Value+'%');
end;
function RightShiftString(s:string;SymbolCount:integer):string;
begin
while length(s)<SymbolCount do
s:=' '+s;
RightShiftString:=s;
end;
function TGUIOperation.OperToStr(LeftField:TName;LeftFieldType:TGUIFieldType;Value:string;
RightField:TName;SymbolCount:longint):string;
var s:string;
begin
s:=LeftFieldType.GetField(LeftField)+' '+PhysicalName;
if RightPartPresent then
begin
s:=s+' ';
if RightField='' then
s:=s+LeftFieldType.ValueToStr(RightShiftString(Value,SymbolCount))
else
s:=s+LeftFieldType.GetField(RightField)
end;
OperToStr:=s
end;
Procedure CreateOpers;
begin
if RequestsCount=0 then
begin
LogOpers[0]:=TGUILogicOperation.Create('AND','И');
LogOpers[1]:=TGUILogicOperation.Create('OR','ИЛИ');
Opers[0]:=TGUIBegin.Create;
Opers[1]:=TGUISubStr.Create;
Opers[2]:=TGUIEqu.Create;
Opers[3]:=TGUIBelow.Create;
Opers[4]:=TGUIAbove.Create;
Opers[5]:=TGUIBelowEqu.Create;
Opers[6]:=TGUIAboveEqu.Create;
Opers[7]:=TGUINotEqu.Create;
Opers[8]:=TGUIIsNull.Create;
Opers[9]:=TGUIIsNotNull.Create;
FieldsTypes[0]:=TGUIInteger.Create;
FieldsTypes[1]:=TGUIString.Create;
FieldsTypes[2]:=TGUIDate.Create;
FieldsTypes[3]:=TGUITime.Create;
FieldsTypes[4]:=TGUIMultiString.Create;
FieldsTypes[5]:=TGUIFloat.Create;
end;
inc(RequestsCount);
end;
Procedure DestroyOpers;
var i: integer;
begin
if RequestsCount<>0 then
begin
dec(RequestsCount);
if RequestsCount=0 then
begin
for i:=0 to LogOpersCount-1 do
LogOpers[i].Free;
for i:=0 to OpersCount-1 do
Opers[i].Free;
for i:=0 to FieldsTypesCount-1 do
FieldsTypes[i].Free;
end
end;
end;
function RelOperByLabel(lb:string):TGUIOperation;
var i:integer;
begin
RelOperByLabel:=NIL;
for i:=0 to OpersCount-1 do
if Opers[i].DisplayLabel=lb then
begin
RelOperByLabel:=Opers[i];
break;
end;
end;
function LogOperByLabel(lb:string):TGUILogicOperation;
var i:integer;
begin
LogOperByLabel:=NIL;
for i:=0 to OpersCount-1 do
if LogOpers[i].DisplayLabel=lb then
begin
LogOperByLabel:=LogOpers[i];
break;
end;
end;
function LTrim(s:string):string;
var i,k:integer;
begin
for i:=1 to length(s) do
if s[i]<>' ' then
begin
k:=i;
break;
end;
Delete(s,1,k-1);
LTrim:=s
end;
begin
RequestsCount:=0;
end.
|
unit TeraWMSTools;
{$writeableconst on}
interface
uses
Windows,
capabilities_1_1_1, ShareTools, IniFilesConstants, AbstractHTTPRequestHandler,
SysUtils, Classes, Graphics, URLMon, xmldoc, XMLIntf;
type
TLayerProcessor = procedure(Layer: IXMLLayerType) of object;
TRequestInfo = AbstractHTTPRequestHandler.TRequestInfo;
TSupportedVersion = (wmsVersion_1_1_1, wmsVersion_Unknown);
TWMSImageFormat = (wms_JPEG, wms_GIF, wms_PNG, wms_PNG24);
TRequestType = (rt_None, rt_GetCapabilities, rt_GetMap, rt_RebuildCapabilities, rt_BuildCapabilities);
TREPClientLevel = (rcl_Default, rcl_User, rcl_GIS, rcl_Administrator);
TREPLayerType = (
rlt_None, rlt_Map, rlt_Imagery, rlt_Overlay, rlt_ImageryOverlay, rlt_MapOverlay, rlt_Terrain, rlt_ElevationTints, rlt_ShadedTerrain,
rlt_OverlayGroup, rlt_CtP, rlt_CascadedServer, rlt_FusedLayer
);
TREPLayerTypeSet = set of TREPLayerType;
TREPKeywordInfo = record LayerType : TREPLayerTypeSet; end;
const
clWMSTRANSCOLOR = $123456;
CAPABILITIES_EXTENSION = '.xml';
GETCAPABILITIES_REQUSETSET = [rt_GetCapabilities, rt_RebuildCapabilities, rt_BuildCapabilities];
CLIENTLEVEL_PARAM = 'CLIENTLEVEL';
REPClientLevel_Captions : array[TREPClientLevel] of string = ('Default', 'User', 'GIS', 'Administrator');
REPClientLevel_Descs : array[TREPClientLevel] of string = ('Podklady', 'Uživatel', 'GIS Aplikace', 'Administrator');
RequestTypeCaptions : array[TRequestType] of string = ('NONE', 'GETCAPABILITIES', 'GETMAP', 'REBUILDCAPABILITIES', 'BUILDCAPABILITIES');
IMAGEFORMATCAPTIONS : array[TWMSImageFormat] of string = ('image/jpeg', 'image/gif', 'image/png', 'image/png; mode=24bit');
SUPPORTEDIMAGEFORMATS = 'image/jpeg,image/png';
REPLayerTypeCaptions : array[TREPLayerType] of string = (
'',
'REP_rlt_Map', // Mapa
'REP_rlt_Imagery', // Snímek
'REP_rlt_Overlay', // Oleáta
'REP_rlt_ImageryOverlay', // Oleáta na snímek, je automaticky oleátou
'REP_rlt_MapOverlay', // Oleáta na mapu, je automaticky oleátou
'REP_rlt_Terrain',
'REP_rlt_ElevationTints', // Hypsometrie
'REP_rlt_ShadedTerrain', // Stínovaný terén
'REP_rlt_OverlayGroup', // Skupina oleát
'REP_rlt_CtP', // Skupina computer to plate
'REP_rlt_CascadedServer',
'REP_rlt_FusedLayer'
);
REPLayerTypeTitles : array[TREPLayerType] of string = (
'',
'Mapy', // Mapa
'Snímky', // Snímek
'Oleáty', // Oleáta
'Oleáty na snímek', // Oleáta na snímek, je automaticky oleátou
'Oleáty na mapu', // Oleáta na mapu, je automaticky oleátou
'Terén',
'Hypsometrie', // Hypsometrie
'Stínovaný terén', // Stínovaný terén
'Skupina oleát', // Skupina oleát
'Tiskové podklady',
'Kaskádovaný server',
'FusedLayer'
);
REPLayerTypeNames : array[TREPLayerType] of string = (
'',
'Map', // Mapa
'Imagery', // Snímek
'Overlay', // Oleáta
'ImageryOverlay', // Oleáta na snímek, je automaticky oleátou
'MapOverlay', // Oleáta na mapu, je automaticky oleátou
'Terrain',
'ElevationTints', // Hypsometrie
'ShadedTerrain', // Stínovaný terén
'OverlayGroup', // Skupina oleát
'CtPGroup',
'',
'FusedLayer'
);
type
TWMSGetMapRequest = class
private
fRequest: TRequestInfo;
procedure SetRequest(v : TRequestInfo);
public
QueryFields : TStrings;
property Request: TRequestInfo read fRequest write SetRequest;
function FirstLayer : string;
function Layers : string;
function Width : integer;
function Height : integer;
function Format : string;
function SRS : string;
end;
function RequestToFormatStr(Request: TRequestInfo) : string;
function GetCapabilities(const sVersion: WideString): WideString;
function GetCapabilitiesFileName(Version : TSupportedVersion) : string;
function GetXMLFile(FileName : string) : string;
function SubstCzechCharsInXML(s : string) : string;
function GetCapabilitiesTemplateFileName(Version : TSupportedVersion) : string;
procedure AssignOnlineResource(c : IXMLWMT_MS_CapabilitiesType; HREF : string);
function DummyHTTPCall(HTTP : string) : boolean;
function KeywordsToREPKeywordInfo(Keywords : IXMLKeywordListType) : TREPKeywordInfo;
procedure AddREPKeywordInfoToKeywords(Info : TREPKeywordInfo; Keywords : IXMLKeywordListType);
procedure AddLayerTypeToKeywords(LayerType : TREPLayerTypeSet; Keywords : IXMLKeywordListType);
function ServerDataPath : string;
function IsLeafNode(Layer : IXMLLayerType) : boolean;
function FindPath(Node : IXMLLayerType; Path : string; CreateIfNotExists : boolean = true) : IXMLLayerType;
function GetPath(Node : IXMLLayerType; IncludingRootNode : boolean) : string; overload;
function GetPath(Node : IXMLLayerType) : string; overload;
const
REP_GENERATEDGROUPS_OWNER : array[TREPLayerType] of TREPLayerType = (
rlt_None, rlt_None, rlt_None, rlt_None, rlt_Overlay, rlt_Overlay, rlt_None, rlt_Terrain, rlt_Terrain, rlt_None, rlt_None, rlt_None, rlt_None
);
REP_GENERATEDGROUPS : array[TREPClientLevel] of TREPLayerTypeSet = (
{ rcl_Default } [],
{ rcl_User } [rlt_Overlay, rlt_ImageryOverlay, rlt_MapOverlay, rlt_OverlayGroup],
{ rcl_GIS } [rlt_None, rlt_Map, rlt_Imagery, rlt_Overlay, rlt_ImageryOverlay, rlt_MapOverlay, rlt_Terrain, rlt_ElevationTints, rlt_ShadedTerrain, rlt_CtP],
{ rcl_Administrator } [rlt_None, rlt_Map, rlt_Imagery, rlt_Overlay, rlt_ImageryOverlay, rlt_MapOverlay, rlt_Terrain, rlt_ElevationTints, rlt_ShadedTerrain, rlt_CtP]
);
WMS_VersionCaptions : array[TSupportedVersion] of string = ('1.1.1', 'Unknown');
WIDTHPARAM_ID = 'WIDTH';
SRSPARAM_ID = 'SRS';
SRSPARAM_AUTO_VALUE = 'AUTO'; // automatic
HEIGHTPARAM_ID = 'HEIGHT';
FORMAT_ID = 'FORMAT';
LAYERSPARAM_ID = 'LAYERS';
BBOXPARAM_ID = 'BBOX';
REQUESTPARAM_ID = 'REQUEST';
GETMAP_REQUESTVALUE = 'GETMAP';
VERSION_PARAM = 'VERSION';
SERVICE_PARAM = 'SERVICE';
WMS_SERVICEPARAMVALUE = 'WMS';
STYLESPARAM_ID = 'STYLES';
LayersHTML_FileName = 'Layers.htm';
DefaultPageTemplate_FileName = 'DefaultPageTemplate.htm';
function EncodeQueryAndFileName(Query, TempFileName: string) : string;
function DecodeQueryAndFileName(s : string; var Query, FileName: string) : boolean;
function PrepareURLforQuery(URL : string) : string;
function AddTokenToURLQuery(Token, URL : string) : string; overload;
function AddTokenToURLQuery(TokenID, TokenValue, URL : string) : string; overload;
procedure DeleteTokenFromURLQuery(Token : string; var URL : string);
procedure NormalizeURL(var URL : string);
function BuildURLQueryToken(TokenID, TokenValue : string) : string;
// Obsolete, for backward compatibility only
procedure AddQueryToURL(QueryToken : string; var URL : string);
// Edit server properties
procedure WMSServerPropertiesToStrings(c : IXMLWMT_MS_CapabilitiesType; s : TStrings);
procedure StringsToWMSServerProperties(s : TStrings; c : IXMLWMT_MS_CapabilitiesType);
procedure AssignWMSServerProperties(s : TStrings);
function FindLayer(c : IXMLWMT_MS_CapabilitiesType; LayerName : string) : IXMLLayerType;
procedure WMSLayerPropertiesToStrings(l : IXMLLayerType; s : TStringList; SortAfter : boolean = true);
function IXMLKeywordListTypeToStr(v : IXMLKeywordListType; Delimeter : string = ',') : string;
function IXMLSRSTypeListToStr(v : IXMLSRSTypeList; Delimeter : string = ',') : string;
function IXMLBoundingBoxTypeListNamesToStr(v : IXMLBoundingBoxTypeList; Delimeter : string = ',') : string;
function IXMLStyleTypeListNamesToStr(v : IXMLStyleTypeList; Delimeter : string = ',') : string;
function FormatGetCapabilitiesRequest(url : string) : string;
function FormatGetMapRequest(WMSUrl : string; Layers, Format, SRS : string; MinX, MinY, MaxX, MaxY : Double; Width, Height : integer) : string;
function DeleteGetCapabilitiesTokens(url : string) : string;
procedure ParseURL(url : string; var Protocol, Host, ScriptName, PathInfo, Query : string);
procedure RegisterSupportedGetMapFormats(c : capabilities_1_1_1.IXMLWMT_MS_CapabilitiesType);
function WMSStreamtoGraphic(s : TStream; Format : TWMSImageFormat) : TGraphic; overload;
function WMSStreamtoGraphic(s : TStream; Format : string) : TGraphic; overload;
function BMPtoWMSStream(bmp : TBitmap; Format : String) : TStream; overload;
function BMPtoWMSStream(bmp : TBitmap; Format : TWMSImageFormat) : TStream; overload;
procedure SaveBMPtoWMSStream(bmp : TBitmap; Format : TWMSImageFormat; s : TStream);
procedure DrawGraphicToCanvas(g : TGraphic; c : TCanvas; x, y : integer);
procedure SetBitmapTransparency(Request: TRequestInfo; var bmp : TBitmap);
function qStr(Request: TRequestInfo; Id : string; DefValue : String) : String; overload;
function qStr(QueryFields: TStrings; Id : string; DefValue : String) : String; overload;
function qInt(Request: TRequestInfo; Id : string; DefValue : integer) : integer; overload;
function qInt(QueryFields: TStrings; Id : string; DefValue : integer) : integer; overload;
function qDouble(Request: TRequestInfo; Id : string; DefValue : Double) : Double; overload;
function qDouble(QueryFields: TStrings; Id : string; DefValue : Double) : Double; overload;
function DownloadURLToFile(const URL : string; TurnOffCache : boolean = false) : string; overload;
function DownloadURLToFile(const URL : string; FileName : string; TurnOffCache : boolean = false) : boolean; overload;
function DownloadURLtoStream(const aUrl: string; s: TStream; TurnOffCache : boolean = false): Boolean;
function DownloadURLtoString(const aUrl: string; var s : String; TurnOffCache : boolean = false): Boolean;
//function WebRequestToURL(r : TRequestInfo) : string;
//function WebRequestToScriptURL(r : TRequestInfo) : string;
function BuildResponseBitmap(Request: TRequestInfo) : Graphics.TBitmap; overload;
function REPClientLevelToStr(v : TREPClientLevel) : string;
function StrToREPClientLevel(s : string) : TREPClientLevel;
function StrToRequestType(s : string) : TRequestType;
function BuildServiceExceptionXML(Msg : string) : string;
function SafeLoadCapabilities(urlorfilename : string) : IXMLWMT_MS_CapabilitiesType;
function TransformCapabilities130to111(Source : IXMLDocument) : IXMLDocument;
function BuildGetMapRequest(WMSUrl : string; Layers, Format, SRS : string; MinX, MinY, MaxX, MaxY : Double; Width, Height : integer) : string;
function PingToURL(url : string) : boolean;
procedure ProcessLayers(Capabilities : IXMLWMT_MS_CapabilitiesType; Processor : TLayerProcessor);
procedure ProcessLayer(Layer : IXMLLayerType; Processor : TLayerProcessor);
implementation
uses
PngFunctions,
Console, PngImage, GIFImage, Jpeg, DelphiDabblerSnippets,
IdURI, ActiveX, WinInet, IdIcmpClient, StrUtils;
function RequestToFormatStr(Request: TRequestInfo) : string;
begin
Result := qStr(Request.QueryFields, FORMAT_ID, IMAGEFORMATCAPTIONS[wms_JPEG]);
end;
function TransformCapabilities130to111(Source : IXMLDocument) : IXMLDocument;
var
XSL : IXMLDocument;
NewXML, s : WideString;
i : integer;
StoredNS : array of string;
begin
Result := Source;
try
if Source.DocumentElement.AttributeNodes.Nodes['version'].Text = '1.3.0' then begin
Console.DefConsole.OpenSection('Konvertuji Capabilities 1.3.0 na 1.1.0');
try
// Načteme seznam namespaců a vymažeme je z deklarací v hlavičce
for i := Source.DocumentElement.AttributeNodes.Count - 1 downto 0 do begin
s := Source.DocumentElement.AttributeNodes.Nodes[i].NodeName;
if AnsiStartsText('xmlns:', s) then begin
SetLength(StoredNS, Length(StoredNS) + 1);
StoredNS[High(StoredNS)] := Copy(s, 7, Length(s)) + ':';
Source.DocumentElement.AttributeNodes.Delete(i);
end
else if (Pos(':', s) > 0) { TODO : precist NS definice a upravit aby tohle bylo obecne }
then Source.DocumentElement.AttributeNodes.Delete(i);
end;
// Vylejeme XML do textu a vymažeme deklaraci o použití namespaců
NewXML := Source.documentelement.xml;
for i := Low(StoredNS) to High(StoredNS) do begin
s := StoredNS[i];
NewXML := StringReplace(NewXML, '<' + s, '<', [rfReplaceAll]);
NewXML := StringReplace(NewXML, '</' + s, '</', [rfReplaceAll]);
end;
NewXML := StringReplace(NewXML, 'xmlns="http://www.opengis.net/wms"', '', [rfReplaceAll]);
// Vytvoříme znovu XML dokument, tentokrát již bez namespaců
Source := LoadXMLData(NewXML);
// Provedeme konverzi
Console.DisplayMsg('Načítám konverzní schéma GetCapabilities130to111Convertor.xsl');
XSL := LoadXMLDocument('GetCapabilities130to111Convertor.xsl');
Source.DocumentElement.TransformNode(XSL.DocumentElement, NewXML);
XSL := nil;
Source := nil;
// Vytvoříme výsledný XML dokument
Result := LoadXMLData(NewXML);
SaveStrToFile('__convertedCapabilities.xml', FormatXMLData(NewXML));
finally
Console.DefConsole.CloseSection;
end;
end;
except
end;
end;
function SafeLoadCapabilities(urlorfilename : string) : IXMLWMT_MS_CapabilitiesType;
var
xmldoc : IXMLDocument;
i, iPos : integer;
sDocType, sXMLnoDocType, sXML : string;
begin
Result := nil;
CoInitialize(nil);
try
sXML := '';
if FileExists(urlorfilename)
then sXML := FileToStr(urlorfilename)
else if IsValidURLProtocol(urlorfilename) then DownloadURLtoString(urlorfilename, sXML, true);
if sXML <> '' then begin
xmldoc := LoadXMLData(sXML);
xmldoc := TransformCapabilities130to111(xmldoc);
sDocType := '';
for i := 0 to xmldoc.ChildNodes.Count - 1 do
if xmldoc.ChildNodes[i].NodeType = ntDocType then begin
sDocType := xmldoc.ChildNodes[i].xml;
Break;
end;
if sDocType <> '' then begin
sXMLnoDocType := xmldoc.XML.Text;
iPos := Pos(sDocType, sXMLnoDocType);
sXMLnoDocType := Copy(sXMLnoDocType, 1, iPos - 1) + Copy(sXMLnoDocType, iPos + Length(sDocType), Length(sXMLnoDocType));
xmldoc.LoadFromXML(sXMLnoDocType);
Console.DisplayDebugMsg('Odstranen DOCTYPE tag' + sDocType);
end;
Result := GetWMT_MS_Capabilities(xmldoc);
end;
finally
CoUnInitialize;
end;
end;
function REPClientLevelToStr(v : TREPClientLevel) : string;
begin
Result := REPClientLevel_Captions[v];
end;
function StrToRequestType(s : string) : TRequestType;
begin
Result := TRequestType(SafeStrToStringIndex(s, RequestTypeCaptions));
end;
function StrToREPClientLevel(s : string) : TREPClientLevel;
begin
Result := TREPClientLevel(SafeStrToStringIndex(s, REPClientLevel_Captions));
end;
function qStr(Request: TRequestInfo; Id : string; DefValue : String) : String;
begin
if Request.QueryFields.Values[Id] = ''
then Result := DefValue
else Result := Request.QueryFields.Values[Id];
end;
function qStr(QueryFields: TStrings; Id : string; DefValue : String) : String;
begin
if QueryFields.Values[Id] = ''
then Result := DefValue
else Result := QueryFields.Values[Id];
end;
function qInt(Request: TRequestInfo; Id : string; DefValue : integer) : integer;
begin
if Request.QueryFields.Values[Id] = ''
then Result := DefValue
else Result := StrToInt(Request.QueryFields.Values[Id]);
end;
function qInt(QueryFields: TStrings; Id : string; DefValue : integer) : integer;
begin
if QueryFields.Values[Id] = ''
then Result := DefValue
else Result := StrToInt(QueryFields.Values[Id]);
end;
function qDouble(Request: TRequestInfo; Id : string; DefValue : Double) : Double;
begin
if Request.QueryFields.Values[Id] = ''
then Result := DefValue
else Result := StrToFloat(Request.QueryFields.Values[Id]);
end;
function qDouble(QueryFields: TStrings; Id : string; DefValue : Double) : Double;
begin
if QueryFields.Values[Id] = ''
then Result := DefValue
else Result := StrToFloat(QueryFields.Values[Id]);
end;
procedure AddQueryToURL(QueryToken : string; var URL : string);
begin
URL := AddTokenToURLQuery(QueryToken, URL);
end;
procedure NormalizeURL(var URL : string);
begin
URL := StringReplace(URL, #13, '&', [rfReplaceAll]);
URL := StringReplace(URL, #10, '', [rfReplaceAll]);
URL := StringReplace(URL, '??', '?', [rfReplaceAll]);
URL := StringReplace(URL, '&&', '&', [rfReplaceAll]);
if (URL <> '') and (URL[Length(URL)] = '&') then SetLength(URL, Length(URL) - 1);
end;
procedure DeleteTokenFromURLQuery(Token : string; var URL : string);
// Vymaze parametr z query, pokud ho v URL najde
var
StartI : integer;
UpperURL, TokenID, Rest : string;
begin
Console.DisplayDebugMsg('DeleteTokenFromURLQuery(%s,%s)', [Token, URL]);
if (Token = '') or (URL = '') then Exit;
StartI := Pos('=', Token);
if StartI > 0
then TokenID := Copy(Token, 1, StartI)
else TokenID := Token + '=';
TokenID := UpperCase(TokenID);
UpperURL := UpperCase(URL);
StartI := Pos(TokenID, UpperURL);
if StartI > 0 then begin // Token byl nalezen
Rest := Copy(URL, StartI + Length(TokenID), Length(URL));
URL := Copy(URL, 1, StartI - 1); // Pred tokenem
if (URL <> '') and (URL[Length(URL)] = '&')
then SetLength(URL, Length(URL) - 1);
StartI := Pos('&', Rest);
if StartI > 0
then URL := URL + Copy(Rest, StartI, Length(Rest));
end;
end;
function BuildURLQueryToken(TokenID, TokenValue : string) : string;
begin
Result := TokenID + '=' + TokenValue;
end;
function PrepareURLforQuery(URL : string) : string;
begin
if Pos('?', URL) = 0
then URL := URL + '?'
else if not (URL[Length(URL)] in ['?', '&'])
then URL := URL + '&';
Result := URL;
end;
function AddTokenToURLQuery(Token, URL : string) : string;
// Prida jedno query do URL, napr. service=wms
begin
DeleteTokenFromURLQuery(Token, URL);
URL := PrepareURLforQuery(URL);
{
if Pos('?', URL) = 0
then URL := URL + '?'
else if not (URL[Length(URL)] in ['?', '&'])
then URL := URL + '&';
}
Result := URL + Token;
end;
function AddTokenToURLQuery(TokenID, TokenValue, URL : string) : string; overload;
begin
Result := AddTokenToURLQuery(BuildURLQueryToken(TokenID, TokenValue), URL);
end;
// ############################################################################
// Edit server properties routines
// ############################################################################
const
WMSSP_NAMECAPTION = 'Name';
WMSSP_TITLECAPTION = 'Title';
WMSSP_ABSTRACTCAPTION = 'Abstract';
WMSSP_KEYWORDSCAPTION = 'Keywords';
WMSSP_CONTACTPERSONCAPTION = 'Contact Person';
WMSSP_POSITIONCAPTION = 'Position';
WMSSP_ORGANIZATIONCAPTION = 'Organization';
WMSSP_STREETCAPTION = 'Street';
WMSSP_CITYCAPTION = 'City';
WMSSP_PROVINCECAPTION = 'Province';
WMSSP_POSTCODECAPTION = 'PostCode';
WMSSP_COUNTRYCAPTION = 'Country';
WMSSP_TELEPHONECAPTION = 'Telephone';
WMSSP_FAXCAPTION = 'Fax';
WMSSP_EMAILCAPTION = 'E-mail';
WMSSP_ONLINERESOURCECAPTION = 'Online Resource';
procedure WMSServerPropertiesToStrings(c : IXMLWMT_MS_CapabilitiesType; s : TStrings);
procedure SetValue(Caption, Value : string);
begin
if Value <> '' then s.Values[Caption] := Value;
end;
var
i : integer;
KeyWords : string;
begin
if Assigned(c) and Assigned(s) then begin
SetValue(WMSSP_NAMECAPTION , c.Service.Name);
SetValue(WMSSP_TITLECAPTION , c.Service.Title);
SetValue(WMSSP_ABSTRACTCAPTION , c.Service.Abstract);
SetValue(WMSSP_CONTACTPERSONCAPTION , c.Service.ContactInformation.ContactPersonPrimary.ContactPerson);
SetValue(WMSSP_POSITIONCAPTION , c.Service.ContactInformation.ContactPosition);
SetValue(WMSSP_ORGANIZATIONCAPTION , c.Service.ContactInformation.ContactPersonPrimary.ContactOrganization);
SetValue(WMSSP_STREETCAPTION , c.Service.ContactInformation.ContactAddress.Address);
SetValue(WMSSP_CITYCAPTION , c.Service.ContactInformation.ContactAddress.City);
SetValue(WMSSP_PROVINCECAPTION , c.Service.ContactInformation.ContactAddress.StateOrProvince);
SetValue(WMSSP_POSTCODECAPTION , c.Service.ContactInformation.ContactAddress.PostCode);
SetValue(WMSSP_COUNTRYCAPTION , c.Service.ContactInformation.ContactAddress.Country);
SetValue(WMSSP_TELEPHONECAPTION , c.Service.ContactInformation.ContactVoiceTelephone);
SetValue(WMSSP_FAXCAPTION , c.Service.ContactInformation.ContactFacsimileTelephone);
SetValue(WMSSP_EMAILCAPTION , c.Service.ContactInformation.ContactElectronicMailAddress);
SetValue(WMSSP_ONLINERESOURCECAPTION , c.Service.OnlineResource.Href);
KeyWords := '';
for i := 0 to c.Capability.Layer.KeywordList.Count - 1 do begin
if KeyWords <> '' then KeyWords := KeyWords + ';';
KeyWords := KeyWords + c.Capability.Layer.KeywordList.Keyword[i];
end;
SetValue(WMSSP_KEYWORDSCAPTION, KeyWords);
end;
end;
procedure StringsToWMSServerProperties(s : TStrings; c : IXMLWMT_MS_CapabilitiesType);
var
KeywordList : TStringList;
i : integer;
begin
if Assigned(c) and Assigned(s) then begin
c.Service.Name := StringReplace(s.Values[WMSSP_NAMECAPTION], ' ', '_', [rfReplaceAll]);
c.Service.Title := s.Values[WMSSP_TITLECAPTION];
c.Service.Abstract := s.Values[WMSSP_ABSTRACTCAPTION];
c.Service.ContactInformation.ContactPersonPrimary.ContactPerson := s.Values[WMSSP_CONTACTPERSONCAPTION];
c.Service.ContactInformation.ContactPosition := s.Values[WMSSP_POSITIONCAPTION];
c.Service.ContactInformation.ContactPersonPrimary.ContactOrganization := s.Values[WMSSP_ORGANIZATIONCAPTION];
c.Service.ContactInformation.ContactAddress.Address := s.Values[WMSSP_STREETCAPTION];
c.Service.ContactInformation.ContactAddress.City := s.Values[WMSSP_CITYCAPTION];
c.Service.ContactInformation.ContactAddress.StateOrProvince := s.Values[WMSSP_PROVINCECAPTION];
c.Service.ContactInformation.ContactAddress.PostCode := s.Values[WMSSP_POSTCODECAPTION];
c.Service.ContactInformation.ContactAddress.Country := s.Values[WMSSP_COUNTRYCAPTION];
c.Service.ContactInformation.ContactVoiceTelephone := s.Values[WMSSP_TELEPHONECAPTION];
c.Service.ContactInformation.ContactFacsimileTelephone := s.Values[WMSSP_FAXCAPTION];
c.Service.ContactInformation.ContactElectronicMailAddress := s.Values[WMSSP_EMAILCAPTION];
c.Service.OnlineResource.Href := s.Values[WMSSP_ONLINERESOURCECAPTION];
c.Capability.Layer.Name := StringReplace(s.Values[WMSSP_NAMECAPTION], ' ', '_', [rfReplaceAll]);
c.Capability.Layer.Title := s.Values[WMSSP_TITLECAPTION];
c.Capability.Layer.Abstract := s.Values[WMSSP_ABSTRACTCAPTION];
c.Capability.Request.GetMap.DCPType[0].HTTP.Get[0].OnlineResource.Href := s.Values[WMSSP_ONLINERESOURCECAPTION];
c.Capability.Request.GetCapabilities.DCPType[0].HTTP.Get[0].OnlineResource.Href := s.Values[WMSSP_ONLINERESOURCECAPTION];
KeywordList := TStringList.Create;
try
KeywordList.Delimiter := ';';
KeywordList.DelimitedText := s.Values[WMSSP_KEYWORDSCAPTION];
c.Capability.Layer.KeywordList.Clear;
for i := 0 to KeywordList.Count - 1 do
c.Capability.Layer.KeywordList.Add(KeywordList[i]);
finally
KeywordList.Free;
end;
end;
end;
procedure AssignOnlineResource(c : IXMLWMT_MS_CapabilitiesType; HREF : string);
begin
c.Service.OnlineResource.Href := HREF;
if Assigned(c.Capability.Request.GetMap.DCPType[0].HTTP.Post) and
(c.Capability.Request.GetMap.DCPType[0].HTTP.Post.Count > 0) then
c.Capability.Request.GetMap.DCPType[0].HTTP.Post[0].OnlineResource.Href := HREF;
if Assigned(c.Capability.Request.GetCapabilities.DCPType[0].HTTP.Post) and
(c.Capability.Request.GetCapabilities.DCPType[0].HTTP.Post.Count > 0) then
c.Capability.Request.GetCapabilities.DCPType[0].HTTP.Post[0].OnlineResource.Href := HREF;
c.Capability.Request.GetMap.DCPType[0].HTTP.Get[0].OnlineResource.Href := HREF;
c.Capability.Request.GetCapabilities.DCPType[0].HTTP.Get[0].OnlineResource.Href := HREF;
end;
procedure AssignWMSServerProperties(s : TStrings);
procedure Add(ss : string);
begin
s.Add(ss + '=');
end;
begin
if Assigned(s) then begin
s.Clear;
Add(WMSSP_NAMECAPTION);
Add(WMSSP_TITLECAPTION);
Add(WMSSP_ABSTRACTCAPTION);
Add(WMSSP_KEYWORDSCAPTION);
Add(WMSSP_CONTACTPERSONCAPTION);
Add(WMSSP_POSITIONCAPTION);
Add(WMSSP_ORGANIZATIONCAPTION);
Add(WMSSP_STREETCAPTION);
Add(WMSSP_CITYCAPTION);
Add(WMSSP_PROVINCECAPTION);
Add(WMSSP_POSTCODECAPTION);
Add(WMSSP_COUNTRYCAPTION);
Add(WMSSP_TELEPHONECAPTION);
Add(WMSSP_FAXCAPTION);
Add(WMSSP_EMAILCAPTION);
Add(WMSSP_ONLINERESOURCECAPTION);
end;
end;
// ############################################################################
// END - Edit server properties routines
// ############################################################################
function EncodeQueryAndFileName(Query, TempFileName: string) : string;
begin
Result := Query + '###' + TempFileName;
end;
function DecodeQueryAndFileName(s : string; var Query, FileName: string) : boolean;
var
i : integer;
begin
i := Pos('###', s);
Result := i <> 0;
if Result then begin
Query := Copy(s, 1, i - 1);
FileName := Copy(s, i + 3, length(s));
end;
end;
function ServerDataPath : string;
begin
Result := ConfigDir + 'TeraWMS\';
end;
// ###############################################################################################
// Other routines
// ###############################################################################################
function GetCapabilitiesTemplateFileName(Version : TSupportedVersion) : string;
begin
Result := ServerDataPath + '\Capabilities_' + WMS_VersionCaptions[Version] + '_Template.xml';
end;
function GetCapabilitiesFileName(Version : TSupportedVersion) : string;
begin
Result := ServerDataPath + '\Capabilities_' + WMS_VersionCaptions[Version] + '.xml';
end;
function SubstCzechCharsInXML(s : string) : string;
const
CZSet = 'ěščřžýáíéůňĚŠČŘŽÝÁÍÉŮŇ';
XMLSet = 'escrzyaieunESCRZYAIEUN';
var
i : integer;
begin
for i := 1 to Length(CZSet) do
s := StringReplace(s, CZSet[i], XMLSet[i], [rfReplaceAll]);
Result := s;
end;
function GetXMLFile(FileName : string) : string;
var
f : TextFile;
s : string;
begin
Result := '';
AssignFile(f, FileName);
Reset(f);
try
while not eof(f) do begin
ReadLn(f, s);
if Result = '' then Result := s
else Result := Result + #13#10 + s;
end;
finally
CloseFile(f);
end;
end;
function GetCapabilities(const sVersion: WideString): WideString;
begin
Result := GetXMLFile(GetCapabilitiesFileName(wmsVersion_1_1_1));
end;
procedure WMSLayerPropertiesToStrings;
begin
s.Add('Symbolický název=' + l.Name);
s.Add('Popis=' + l.Abstract);
s.Add('Kaskádován=' + l.Cascaded);
s.Add('Opaque=' + l.Opaque);
s.Add('FixedWidth=' + l.FixedWidth);
s.Add('FixedHeight=' + l.FixedHeight);
s.Add('Klíčová slova=' + IXMLKeywordListTypeToStr(l.KeywordList));
s.Add('SRS=' + IXMLSRSTypeListToStr(l.SRS));
s.Add('Min Lat=' + l.LatLonBoundingBox.Minx);
s.Add('Max Lat=' + l.LatLonBoundingBox.Maxx);
s.Add('Min Lon=' + l.LatLonBoundingBox.Miny);
s.Add('Max Lon=' + l.LatLonBoundingBox.Maxy);
if l.BoundingBox.Count > 1
then s.Add('Systems=' + IXMLBoundingBoxTypeListNamesToStr(l.BoundingBox));
if l.Dimension.Count <> 0
then s.Add('Rozměry=' + IntToStr(l.Dimension.Count))
else s.Add('Rozměry=');
if l.Extent.Count <> 0
then s.Add('Rozsah=' + IntToStr(l.Extent.Count))
else s.Add('Rozsah=');
s.Add('Scale-min=' + l.ScaleHint.Min);
s.Add('Scale-max=' + l.ScaleHint.Max);
s.Add('Styly=' + IXMLStyleTypeListNamesToStr(l.style));
if SortAfter then s.Sort;
end;
function IXMLKeywordListTypeToStr(v : IXMLKeywordListType; Delimeter : string = ',') : string;
var
i : integer;
begin
Result := '';
for i := 0 to v.Count - 1 do begin
if Result <> '' then Result := Result + Delimeter;
Result := Result + v.Keyword[i];
end;
end;
function IXMLSRSTypeListToStr(v : IXMLSRSTypeList; Delimeter : string = ',') : string;
var
i : integer;
begin
Result := '';
for i := 0 to v.Count - 1 do begin
if Result <> '' then Result := Result + Delimeter;
Result := Result + v.Items[i];
end;
end;
function IXMLBoundingBoxTypeListNamesToStr(v : IXMLBoundingBoxTypeList; Delimeter : string = ',') : string;
var
i : integer;
begin
Result := '';
for i := 0 to v.Count - 1 do begin
if Result <> '' then Result := Result + Delimeter;
Result := Result + v.Items[i].SRS;
end;
end;
function IXMLStyleTypeListNamesToStr(v : IXMLStyleTypeList; Delimeter : string = ',') : string;
var
i : integer;
begin
Result := '';
for i := 0 to v.Count - 1 do begin
if Result <> '' then Result := Result + Delimeter;
Result := Result + v.Items[i].Name;
end;
end;
function DeleteGetCapabilitiesTokens(url : string) : string;
begin
DeleteTokenFromURLQuery(REQUESTPARAM_ID, url);
DeleteTokenFromURLQuery(VERSION_PARAM, url);
DeleteTokenFromURLQuery(SERVICE_PARAM, url);
Result := url;
end;
function FormatGetCapabilitiesRequest(url : string) : string;
begin
url := AddTokenToURLQuery(BuildURLQueryToken(REQUESTPARAM_ID, 'GetCapabilities'), url);
url := AddTokenToURLQuery(BuildURLQueryToken(VERSION_PARAM, '1.1.1'), url);
url := AddTokenToURLQuery(BuildURLQueryToken(SERVICE_PARAM, 'wms'), url);
url := AddTokenToURLQuery(BuildURLQueryToken('TimeStamp', StringReplace(DateTimeToStr(Now), ' ', '', [rfReplaceAll])), url);
Result := url;
end;
procedure ParseURL(url : string; var Protocol, Host, ScriptName, PathInfo, Query : string);
var
uri : TIdURI;
begin
uri := TIdURI.Create(url);
try
Protocol := uri.Protocol;
Host := uri.Host;
PathInfo := uri.Path;
ScriptName := uri.Document;
Query := uri.Params;
finally
uri.Free;
end;
end;
function DummyHTTPCall(HTTP : string) : boolean;
var
tmpFileName : string;
begin
tmpFileName := GetTempFileName;
Result := URLDownloadToFile(nil, pchar(HTTP), pchar(tmpFileName), 0, nil) = 0;
if Result and FileExists(tmpFileName)
then DeleteFile(tmpFileName);
end;
procedure SetBitmapTransparency(Request: TRequestInfo; var bmp : TBitmap);
begin
bmp.TransparentColor := clWhite; { TODO : cist parametry transparent a transparentcolor }
bmp.Transparent := true;
bmp.TransparentMode := tmFixed;
end;
procedure RegisterSupportedGetMapFormats(c : capabilities_1_1_1.IXMLWMT_MS_CapabilitiesType);
begin
c.Capability.Request.GetMap.Format.Clear;
c.Capability.Request.GetMap.Format.Add('image/gif');
c.Capability.Request.GetMap.Format.Add('image/jpeg');
c.Capability.Request.GetMap.Format.Add('image/png');
c.Capability.Request.GetMap.Format.Add('image/png; mode=24bit');
end;
function WMSStreamtoGraphic(s : TStream; Format : TWMSImageFormat) : TGraphic;
var
Png : TPngObject;
jpeg : TJPEGImage;
gif : GIFImage.TGIFImage;
x, y : integer;
Line: pngimage.PByteArray;
begin
Result := nil;
if s.Size = 0 then Exit;
case Format of
wms_PNG, wms_PNG24:begin
Console.DisplayDebugMsg('Loading to PNG file');
Png := TPngObject.Create;
{
Png.CreateAlpha;
for Y := 0 to Png.Height - 1 do begin
Line := Png.AlphaScanline[Y];
for X := 0 to Png.Width - 1 do
Line^[X] := $FF;
end;
}
Png.LoadFromStream(s);
Result := Png;
end;
wms_GIF:begin
Console.DisplayDebugMsg('Loading to GIF file');
gif := TGIFImage.Create;
gif.LoadFromStream(s);
Result := gif;
end;
else // IMAGEJPEG
Console.DisplayDebugMsg('Loading to JPEG file');
jpeg := TJPEGImage.Create;
jpeg.LoadFromStream(s);
Result := jpeg;
end;
end;
procedure DrawGraphicToCanvas(g : TGraphic; c : TCanvas; x, y : integer);
begin
if g is TPNGObject
then (g as TPngObject).Draw(c, Rect(x, y, x + g.Width, y + g.Height))
else c.Draw(0, 0, g);
end;
function WMSStreamtoGraphic(s : TStream; Format : string) : TGraphic;
var
ImageFormat : TWMSImageFormat;
begin
Console.DisplayDebugMsg('WMSStreamtoBMP from ' + Format);
ImageFormat := TWMSImageFormat(SafeStrToStringIndex(Format, IMAGEFORMATCAPTIONS));
Result := WMSStreamtoGraphic(s, ImageFormat);
end;
procedure SaveBMPtoWMSStream(bmp : TBitmap; Format : TWMSImageFormat; s : TStream);
var
Png : TPngObject;
jpeg : TJPEGImage;
gif : GIFImage.TGIFImage;
begin
case Format of
wms_PNG, wms_PNG24:begin
Console.DisplayDebugMsg('Saving to PNG file');
if bmp.Transparent
then CreatePNGMasked(bmp, clWMSTRANSCOLOR{bmp.TransparentColor}, png)
else begin
Png := TPngObject.Create;
Png.Assign(bmp);
end;
try
png.SaveToStream(s);
finally
Png.Free;
end;
end;
wms_GIF:begin
Console.DisplayDebugMsg('Saving to GIF file');
gif := TGIFImage.Create;
try
gif.Assign(bmp);
gif.SaveToStream(s);
finally
gif.Free;
end;
end;
else // IMAGEJPEG
Console.DisplayDebugMsg('Saving to JPEG file');
jpeg := TJPEGImage.Create;
try
jpeg.Assign(bmp);
jpeg.SaveToStream(s);
finally
jpeg.Free;
end;
end;
end;
function BMPtoWMSStream(bmp : TBitmap; Format : TWMSImageFormat) : TStream; overload;
begin
Result := TMemoryStream.Create;
SaveBMPtoWMSStream(bmp, Format, Result);
Result.Position := 0;
end;
function BMPtoWMSStream(bmp : TBitmap; Format : string) : TStream;
var
ImageFormat : TWMSImageFormat;
begin
Console.DisplayDebugMsg('BMPtoWMSStream to ' + Format);
ImageFormat := TWMSImageFormat(SafeStrToStringIndex(Format, IMAGEFORMATCAPTIONS));
Result := BMPtoWMSStream(bmp, ImageFormat);
end;
{
function WebRequestToScriptURL(r : TRequestInfo) : string;
begin
Result := 'http://' + r.Host + r.ScriptName;
end;
}
{
function WebRequestToURL(r : TRequestInfo) : string;
var
p : string;
begin
Result := r.URL;
Result := 'http://' + r.Host + r.ScriptName;
p := r.PathInfo;
if Pos(r.ScriptName, p) = 1 then Delete(p, 1, Length(r.ScriptName));
Result := Result + p;
if r.Query <> ''
then Result := Result + '?' + r.QueryFields.Text; // Query
NormalizeURL(Result);
end;
}
function BuildResponseBitmap(Request: TRequestInfo) : Graphics.TBitmap;
begin
Result := Graphics.TBitmap.Create;
Result.Width := SafeStrToInt(Request.QueryFields.Values[WIDTHPARAM_ID], 100);
Result.Height := SafeStrToInt(Request.QueryFields.Values[HEIGHTPARAM_ID], 100);
SetBitmapTransparency(Request, Result);
end;
// --------------------------------------------
function FindLayer(c : IXMLWMT_MS_CapabilitiesType; LayerName : string) : IXMLLayerType;
procedure SearchList(l : IXMLLayerTypeList);
var
i : integer;
begin
if l = nil then Exit;
for i := 0 to l.Count - 1 do
if l.Items[i].Name = LayerName then begin
Result := l.Items[i];
Exit;
end
else begin
SearchList(l.Items[i].Layer);
if Result <> nil then Exit;
end;
end;
begin
Result := nil;
if (LayerName = '') or (c = nil) then Exit;
if c.Capability.Layer.Name = LayerName
then Result := c.Capability.Layer
else SearchList(c.Capability.Layer.Layer);
end;
// ##########################################################
// TGetMapRequest
// ##########################################################
function TWMSGetMapRequest.Format : string;
begin
Result := qStr(QueryFields, FORMAT_ID, IMAGEFORMATCAPTIONS[wms_JPEG]);
end;
procedure TWMSGetMapRequest.SetRequest(v : TRequestInfo);
begin
fRequest := v;
if fRequest = nil
then QueryFields := nil
else QueryFields := fRequest.QueryFields;
end;
function TWMSGetMapRequest.FirstLayer : string;
var
s : string;
begin
s := Layers;
Result := GetAndDeleteStrItem(s, ',');
end;
function TWMSGetMapRequest.SRS : string;
begin
Result := qStr(QueryFields, SRSPARAM_ID, 'EPSG:4326');
end;
function TWMSGetMapRequest.Layers : string;
begin
if QueryFields = nil then Exit;
Result := qStr(QueryFields, LAYERSPARAM_ID, '');
end;
function TWMSGetMapRequest.Width : integer;
begin
Result := qInt(QueryFields, WIDTHPARAM_ID, 100);
end;
function TWMSGetMapRequest.Height : integer;
begin
Result := qInt(QueryFields, HEIGHTPARAM_ID, 100);
end;
function KeywordsToREPKeywordInfo(Keywords : IXMLKeywordListType) : TREPKeywordInfo;
var
i : integer;
j : TREPLayerType;
s : string;
begin
Result.LayerType := [];
for i := 0 to Keywords.Count - 1 do begin
for j := Low(j) to High(j) do begin
if (Keywords.Keyword[i] = REPLayerTypeCaptions[j]) or
(Pos(REPLayerTypeCaptions[j] + ',', Keywords.Keyword[i]) > 0) or
(Pos(REPLayerTypeCaptions[j] + ';', Keywords.Keyword[i]) > 0)
then Result.LayerType := Result.LayerType + [j];
end;
end;
// Postprocessing
end;
procedure AddLayerTypeToKeywords(LayerType : TREPLayerTypeSet; Keywords : IXMLKeywordListType);
var
Info : TREPKeywordInfo;
begin
Info.LayerType := LayerType;
AddREPKeywordInfoToKeywords(Info, Keywords);
end;
procedure AddREPKeywordInfoToKeywords(Info : TREPKeywordInfo; Keywords : IXMLKeywordListType);
var
i : TREPLayerType;
j : integer;
NeedAdd : boolean;
begin
for i := Low(i) to High(i) do
if i in Info.LayerType then begin
NeedAdd := true;
j := 0;
while (j < Keywords.Count) and NeedAdd do begin
NeedAdd := REPLayerTypeCaptions[i] <> Keywords[j];
Inc(j);
end;
if NeedAdd then Keywords.Add(REPLayerTypeCaptions[i]);
end;
end;
function BuildServiceExceptionXML(Msg : string) : string;
begin
Result := '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' +
'<!DOCTYPE ServiceExceptionReport SYSTEM "http://schemas.opengis.net/wms/1.1.1/exception_1_1_1.dtd">' +
'<ServiceExceptionReport version="1.1.1">' +
'<ServiceException>' +
Msg +
'</ServiceException>' +
'</ServiceExceptionReport>';
end;
function DownloadURLToFile(const URL : string; FileName : string; TurnOffCache : boolean = false) : boolean;
var
OutS : TFileStream;
begin
OutS := TFileStream.Create(FileName, fmCreate);
try
Result := DownloadURLtoStream(URL, OutS, TurnOffCache);
finally
OutS.Free;
end;
end;
function DownloadURLToFile(const URL : string; TurnOffCache : boolean = false) : string;
var
OutS : TFileStream;
begin
Result := GetTempFileName;
OutS := TFileStream.Create(Result, fmCreate);
try
if not DownloadURLtoStream(URL, OutS, TurnOffCache) then Result := '';
finally
OutS.Free;
end;
end;
function DownloadURLtoStream(const aUrl: string; s: TStream; TurnOffCache : boolean = false): Boolean;
var
hSession: HINTERNET;
hService: HINTERNET;
lpBuffer: array[0..1024 + 1] of Char;
dwBytesRead: DWORD;
dwFlags: DWORD;
begin
Result := False;
if s = nil then Exit;
// hSession := InternetOpen( 'MyApp', INTERNET_OPEN_TYPE_DIRECT, nil, nil, 0);
hSession := InternetOpen('MyApp', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
try
if Assigned(hSession) then
begin
if TurnOffCache
then dwFlags := INTERNET_FLAG_RELOAD
else dwFlags := 0;
hService := InternetOpenUrl(hSession, PChar(aUrl), nil, 0, dwFlags, 0);
if Assigned(hService) then
try
while True do
begin
dwBytesRead := 1024;
InternetReadFile(hService, @lpBuffer, 1024, dwBytesRead);
if dwBytesRead = 0 then break;
lpBuffer[dwBytesRead] := #0;
s.Write(lpBuffer, dwBytesRead);
end;
Result := True;
finally
InternetCloseHandle(hService);
end;
end;
finally
InternetCloseHandle(hSession);
end;
end;
function DownloadURLtoString(const aUrl: string; var s: string; TurnOffCache : boolean = false) : Boolean;
var
ms : TMemoryStream;
buffer : pchar;
begin
ms := TMemoryStream.Create;
try
Result := DownloadURLtoStream(aURL, ms, TurnOffCache);
if Result then begin
GetMem(buffer, ms.Size + 1);
try
FillChar(Buffer^, ms.Size + 1, 0);
ms.Position := 0;
ms.Read(buffer^, ms.Size);
s := StrPas(buffer);
finally
FreeMem(buffer);
end;
end;
finally
ms.Free;
end;
end;
function FormatGetMapRequest(WMSUrl : string; Layers, Format, SRS : string; MinX, MinY, MaxX, MaxY : Double; Width, Height : integer) : string;
begin
Result := BuildGetMapRequest(WMSUrl, Layers, Format, SRS, MinX, MinY, MaxX, MaxY, Width, Height);
end;
function BuildGetMapRequest(WMSUrl : string; Layers, Format, SRS : string; MinX, MinY, MaxX, MaxY : Double; Width, Height : integer) : string;
begin
Result := AddTokenToURLQuery(REQUESTPARAM_ID, GETMAP_REQUESTVALUE, WMSUrl);
Result := AddTokenToURLQuery(SERVICE_PARAM, WMS_SERVICEPARAMVALUE, Result);
Result := AddTokenToURLQuery(VERSION_PARAM, WMS_VersionCaptions[wmsVersion_1_1_1], Result);
Result := AddTokenToURLQuery(WIDTHPARAM_ID, IntToStr(Width), Result);
Result := AddTokenToURLQuery(HEIGHTPARAM_ID, IntToStr(Height), Result);
Result := AddTokenToURLQuery(FORMAT_ID, Format, Result);
Result := AddTokenToURLQuery(SRSPARAM_ID, SRS, Result);
Result := AddTokenToURLQuery(LAYERSPARAM_ID, Layers, Result);
Result := AddTokenToURLQuery(BBOXPARAM_ID, FloatToStr(MinX) + ',' + FloatToStr(MinY) + ',' + FloatToStr(MaxX) + ',' + FloatToStr(MaxY), Result);
end;
function PingToURL(url : string) : boolean;
var
idICMPClient1 : TIdIcmpClient;
begin
Result := false;
idICMPClient1 := TIdIcmpClient.Create(nil);
try
idICMPClient1.Host:= 'localhost';
idICMPClient1.Port := 8030;
idICMPClient1.Ping;
Result := idICMPClient1.ReplyStatus.ReplyStatusType = rsEcho;
finally
idICMPClient1.Free;
end;
end;
function IsLeafNode(Layer : IXMLLayerType) : boolean;
begin
Result := (Layer.Layer.Count = 0); // and (Layer.Style.Count <> 0);
end;
const
PATH_DELIMETER = '\';
function GetPath(Node : IXMLLayerType; IncludingRootNode : boolean) : string;
begin
Result := GetPath(Node);
end;
function GetPath(Node : IXMLLayerType) : string;
var
IsRootNode : boolean;
ParentLayer : IXMLLayerType;
begin
Result := '';
if Node <> nil then begin
IsRootNode := (Node.Cascaded = '1') or ((Node.ParentNode <> nil) and (Node.ParentNode.NodeName <> 'Layer'));
if not IsRootNode
then ParentLayer := Node.ParentNode as IXMLLayerType;
if ParentLayer <> nil then
Result := GetPath(ParentLayer) + PATH_DELIMETER + ParentLayer.Title;
end;
end;
function __FindPath(Node : IXMLLayerType; Path : string; CreateIfNotExists : boolean = true) : IXMLLayerType;
const
UniqueIndex : integer = 0;
// stejne jako FindPath, ale predpoklada, ze v textu jsou jenom lomitka "\" a prvni znak neni "\"
var
i : integer;
s : string;
FoundNode : IXMLLayerType;
begin
s := GetAndDeleteStrItem(Path, PATH_DELIMETER);
FoundNode := nil;
for i := 0 to Node.Layer.Count - 1 do
if AnsiSameText(Node.Layer[i].Title, s) then begin
FoundNode := Node.Layer[i];
Break;
end;
if (FoundNode = nil) and CreateIfNotExists then begin
FoundNode := Node.Layer.Add;
FoundNode.Title := s;
FoundNode.Name := 'VirtualGroup_' + IntToStr(UniqueIndex);
AddLayerTypeToKeywords([rlt_OverlayGroup], FoundNode.KeywordList);
Inc(UniqueIndex);
end;
if (FoundNode <> nil) and (Path <> '')
then Result := __FindPath(FoundNode, Path, CreateIfNotExists)
else Result := FoundNode;
end;
function FindPath(Node : IXMLLayerType; Path : string; CreateIfNotExists : boolean = true) : IXMLLayerType;
begin
if Path = '' then Result := nil
else begin
Path := StringReplace(Path, '/', PATH_DELIMETER, [rfReplaceAll]);
if AnsiStartsText(PATH_DELIMETER, Path) then Delete(Path, 1, 1); // Odstranime uvodni lomitko, pokud tam se
Result := __FindPath(Node, Path, CreateIfNotExists);
end;
end;
procedure ProcessLayers(Capabilities : IXMLWMT_MS_CapabilitiesType; Processor : TLayerProcessor);
begin
if Assigned(Capabilities)
then ProcessLayer(Capabilities.Capability.Layer, Processor);
end;
procedure ProcessLayer(Layer : IXMLLayerType; Processor : TLayerProcessor);
var
i : integer;
begin
if Assigned(Layer) then begin
Processor(Layer);
for i := 0 to Layer.Layer.Count - 1 do
ProcessLayer(Layer.Layer.Items[i], Processor);
end;
end;
end.
|
unit CommonIDObjectListFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, BaseGUI, UniButtonsFrame, ComCtrls, BaseObjects, Registrator,
BaseActions, ActnList, CommonObjectSelector;
type
TfrmIDObjectListFrame = class(TFrame, IGUIAdapter, IObjectSelector)
frmButtons1: TfrmButtons;
lwObjects: TListView;
procedure lwObjectsDblClick(Sender: TObject);
procedure frmButtons1btnAddClick(Sender: TObject);
procedure lwObjectsCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure lwObjectsColumnClick(Sender: TObject; Column: TListColumn);
private
{ Private declarations }
FObjectList: TIDObjects;
FOnRegisterSubscribers: TNotifyEvent;
FShowShortName: boolean;
FEditActionClass: TBaseActionClass;
FDeleteActionClass: TBaseActionClass;
FAddActionClass: TBaseActionClass;
FMultiSelect: boolean;
FShowID: boolean;
FSelectedObjects: TIDObjects;
FShowNavigationButtons: boolean;
FIsEditable: boolean;
FColClicked: Boolean;
function IndexOfObject(AObject: TIDObject): integer;
procedure SetObjectList(const Value: TIDObjects);
procedure SetShowShortName(const Value: boolean);
procedure SetAddActionClass(const Value: TBaseActionClass);
procedure SetDeleteActionClass(const Value: TBaseActionClass);
procedure SetEditActionClass(const Value: TBaseActionClass);
procedure DeselectAll;
procedure SetShowID(const Value: boolean);
procedure SetShowNavigationButtons(const Value: boolean);
procedure SetIsEditable(const Value: boolean);
protected
FGUIAdapter: TGUIAdapter;
procedure SetMultiSelect(const Value: boolean);
function GetMultiSelect: boolean;
procedure SetSelectedObject(AValue: TIDObject);
function GetSelectedObject: TIDObject;
function GetSelectedObjects: TIDObjects;
procedure SetSelectedObjects(AValue: TIDObjects);
function GetOwnerObjectList: TIDObjects; virtual;
public
{ Public declarations }
property MultiSelect: boolean read FMultiSelect write SetMultiSelect;
property ShowShortName: boolean read FShowShortName write SetShowShortName;
property ShowID: boolean read FShowID write SetShowID;
property ShowNavigationButtons: boolean read FShowNavigationButtons write SetShowNavigationButtons;
property GUIAdapter: TGUIAdapter read FGUIAdapter implements IGUIAdapter;
property ObjectList: TIDObjects read FObjectList write SetObjectList;
property OwnerObjectList: TIDObjects read GetOwnerObjectList;
procedure ReloadList; virtual;
property SelectedObject: TIDObject read GetSelectedObject write SetSelectedObject;
property SelectedObjects: TIDObjects read GetSelectedObjects write SetSelectedObjects;
procedure ReadSelectedObjects;
property IsEditable: boolean read FIsEditable write SetIsEditable;
property AddActionClass: TBaseActionClass read FAddActionClass write SetAddActionClass;
property EditActionClass: TBaseActionClass read FEditActionClass write SetEditActionClass;
property DeleteActionClass: TBaseActionClass read FDeleteActionClass write SetDeleteActionClass;
property OnRegisterSubscribers: TNotifyEvent read FOnRegisterSubscribers write FOnRegisterSubscribers;
constructor Create(AOwner: TComponent); override;
end;
TIDObjectsGUIAdapter = class(TCollectionGUIAdapter)
protected
function GetCanAdd: boolean; override;
function GetCanDelete: boolean; override;
function GetCanEdit: boolean; override;
function GetCanFind: boolean; override;
function GetCanSort: boolean; override;
public
procedure Clear; override;
procedure SelectAll; override;
function Save: integer; override;
procedure Reload; override;
function Add (): integer; override;
function Edit: integer; override;
procedure AddGroup; override;
function Delete: integer; override;
function StartFind: integer; override;
end;
implementation
{$R *.dfm}
uses Facade, IDObjectBaseActions;
{ TfrmIDObjectList }
constructor TfrmIDObjectListFrame.Create(AOwner: TComponent);
begin
inherited;
FGUIAdapter := TIDObjectsGUIAdapter.Create(Self);
FGUIAdapter.Buttons := [abReload, abAdd, abDelete, abFind, abSort, abSelectAll, abEdit];
FShowShortName := false;
AddActionClass := TIDObjectAddAction;
EditActionClass := TIDObjectEditAction;
DeleteActionClass := TIDObjectDeleteAction;
FIsEditable := true;
frmButtons1.GUIAdapter := FGUIAdapter;
end;
procedure TfrmIDObjectListFrame.ReloadList;
begin
if ObjectList is TRegisteredIDObjects then
(ObjectList as TRegisteredIDObjects).MakeList(lwObjects.Items, true, true);
end;
procedure TfrmIDObjectListFrame.SetObjectList(const Value: TIDObjects);
begin
FObjectList := Value;
ReloadList;
end;
{ TIDObjectsGUIAdapter }
function TIDObjectsGUIAdapter.Add: integer;
var actn: TBaseAction;
begin
Result := 0;
actn := TMainFacade.GetInstance.ActionByClassType[(Frame as TfrmIDObjectListFrame).AddActionClass] as TBaseAction;
actn.Execute((Frame as TfrmIDObjectListFrame).OwnerObjectList);
(Frame as TfrmIDObjectListFrame).ReloadList;
end;
procedure TIDObjectsGUIAdapter.AddGroup;
begin
inherited;
end;
procedure TIDObjectsGUIAdapter.Clear;
begin
inherited;
end;
function TIDObjectsGUIAdapter.Delete: integer;
begin
Result := 0;
(TMainFacade.GetInstance.ActionByClassType[(Frame as TfrmIDObjectListFrame).DeleteActionClass] as TBaseAction).Execute(TIDObject((Frame as TfrmIDObjectListFrame).SelectedObject));
(Frame as TfrmIDObjectListFrame).ReloadList;
end;
function TIDObjectsGUIAdapter.Edit: integer;
var actn: TBaseAction;
begin
Result := 0;
actn := TMainFacade.GetInstance.ActionByClassType[(Frame as TfrmIDObjectListFrame).AddActionClass] as TBaseAction;
actn.Execute((Frame as TfrmIDObjectListFrame).SelectedObject);
(Frame as TfrmIDObjectListFrame).ReloadList;
end;
function TIDObjectsGUIAdapter.GetCanAdd: boolean;
begin
Result := Assigned((Frame as TfrmIDObjectListFrame).ObjectList);
end;
function TIDObjectsGUIAdapter.GetCanDelete: boolean;
begin
Result := Assigned((Frame as TfrmIDObjectListFrame).SelectedObject);
end;
function TIDObjectsGUIAdapter.GetCanEdit: boolean;
begin
Result := Assigned((Frame as TfrmIDObjectListFrame).SelectedObject);
end;
function TIDObjectsGUIAdapter.GetCanFind: boolean;
begin
Result := Assigned((Frame as TfrmIDObjectListFrame).ObjectList) and
((Frame as TfrmIDObjectListFrame).ObjectList.Count > 1);
end;
function TIDObjectsGUIAdapter.GetCanSort: boolean;
begin
Result := inherited GetCanSort and
Assigned((Frame as TfrmIDObjectListFrame).ObjectList) and
((Frame as TfrmIDObjectListFrame).ObjectList.Count > 1);
end;
procedure TIDObjectsGUIAdapter.Reload;
begin
inherited;
end;
function TIDObjectsGUIAdapter.Save: integer;
begin
Result := 0;
end;
procedure TIDObjectsGUIAdapter.SelectAll;
begin
inherited;
end;
function TIDObjectsGUIAdapter.StartFind: integer;
begin
Result := 0;
end;
procedure TfrmIDObjectListFrame.lwObjectsDblClick(Sender: TObject);
begin
if GUIAdapter.CanEdit then GUIAdapter.Edit;
end;
procedure TfrmIDObjectListFrame.SetShowShortName(const Value: boolean);
begin
FShowShortName := Value;
if FShowShortName then lwObjects.Columns[2].Width := -2
else lwObjects.Columns[2].Width := 0;
end;
procedure TfrmIDObjectListFrame.SetAddActionClass(
const Value: TBaseActionClass);
begin
FAddActionClass := Value;
end;
procedure TfrmIDObjectListFrame.SetDeleteActionClass(
const Value: TBaseActionClass);
begin
FDeleteActionClass := Value;
end;
procedure TfrmIDObjectListFrame.SetEditActionClass(
const Value: TBaseActionClass);
begin
FEditActionClass := Value;
end;
procedure TfrmIDObjectListFrame.SetMultiSelect(const Value: boolean);
begin
FMultiSelect := Value;
lwObjects.Checkboxes := FMultiSelect;
end;
function TfrmIDObjectListFrame.GetMultiSelect: boolean;
begin
Result := FMultiSelect;
end;
function TfrmIDObjectListFrame.GetSelectedObject: TIDObject;
begin
Result := nil;
if Assigned(lwObjects.Selected) then
Result := TIDObject(lwObjects.Selected.Data);
end;
function TfrmIDObjectListFrame.GetSelectedObjects: TIDObjects;
begin
ReadSelectedObjects;
Result := FSelectedObjects;
end;
procedure TfrmIDObjectListFrame.SetSelectedObject(AValue: TIDObject);
var i: integer;
begin
i := IndexOfObject(AValue);
if i > -1 then
lwObjects.ItemIndex := i;
end;
procedure TfrmIDObjectListFrame.SetSelectedObjects(AValue: TIDObjects);
var i, iIndex: integer;
begin
if not Assigned(FSelectedObjects) then
begin
FSelectedObjects := TIDObjects.Create;
FSelectedObjects.OwnsObjects := false;
end;
FSelectedObjects.Clear;
FSelectedObjects.AddObjects(AValue, false, False);
DeselectAll;
if MultiSelect then
begin
for i := 0 to FSelectedObjects.Count - 1 do
begin
iIndex := IndexOfObject(FSelectedObjects.Items[i]);
if iIndex > -1 then
lwObjects.Items[iIndex].Checked := true;
end;
end
else if FSelectedObjects.Count = 1 then
begin
iIndex := IndexOfObject(FSelectedObjects.Items[0]);
if iIndex > -1 then
lwObjects.Items[iIndex].Selected := true;
end;
end;
function TfrmIDObjectListFrame.IndexOfObject(AObject: TIDObject): integer;
var i: integer;
begin
Result := -1;
for i := 0 to lwObjects.Items.Count - 1 do
if TIDObject(lwObjects.Items[i].Data) = AObject then
begin
Result := i;
break;
end;
end;
procedure TfrmIDObjectListFrame.DeselectAll;
var i: integer;
begin
for i := 0 to lwObjects.Items.Count - 1 do
lwObjects.Items[i].Checked := false;
end;
procedure TfrmIDObjectListFrame.SetShowID(const Value: boolean);
begin
FShowID := Value;
if FShowID then lwObjects.Columns[0].Width := -2
else
begin
if MultiSelect then lwObjects.Columns[0].Width := 21
else lwObjects.Columns[0].Width := 0;
end;
end;
procedure TfrmIDObjectListFrame.ReadSelectedObjects;
var i: integer;
begin
if not Assigned(FSelectedObjects) then
begin
FSelectedObjects := TIDObjects.Create;
FSelectedObjects.OwnsObjects := false;
end;
FSelectedObjects.Clear;
if MultiSelect then
begin
for i := 0 to lwObjects.Items.Count - 1 do
if lwObjects.Items[i].Checked then
FSelectedObjects.Add(TIDObject(lwObjects.Items[i].Data), false, false);
end
else
begin
for i := 0 to lwObjects.Items.Count - 1 do
if lwObjects.Items[i].Selected then
FSelectedObjects.Add(TIDObject(lwObjects.Items[i].Data), false, false);
end;
if FSelectedObjects.Count = 0 then
begin
if Assigned(SelectedObject) then
FSelectedObjects.Add(SelectedObject, false, false);
end;
end;
procedure TfrmIDObjectListFrame.SetShowNavigationButtons(
const Value: boolean);
begin
FShowNavigationButtons := Value;
end;
procedure TfrmIDObjectListFrame.frmButtons1btnAddClick(Sender: TObject);
begin
frmButtons1.actnAddExecute(Sender);
end;
procedure TfrmIDObjectListFrame.SetIsEditable(const Value: boolean);
begin
FIsEditable := Value;
if not FIsEditable then
frmButtons1.Visible := False
else
frmButtons1.Visible := true;
end;
procedure TfrmIDObjectListFrame.lwObjectsCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
begin
//
end;
procedure TfrmIDObjectListFrame.lwObjectsColumnClick(Sender: TObject;
Column: TListColumn);
begin
FColClicked := not FColClicked;
if Column.Index = 0 then
ObjectList.SortByID(FColClicked)
else if Column.Index = 1 then
ObjectList.SortByName(FColClicked);
ReloadList;
end;
function TfrmIDObjectListFrame.GetOwnerObjectList: TIDObjects;
begin
if FObjectList.OwnsObjects then
Result := FObjectList
else
Result := nil;
end;
end.
|
unit uMunicipioModel;
interface
uses
System.SysUtils, FireDAC.Comp.Client, Data.DB, FireDAC.DApt, FireDAC.Comp.UI,
FireDAC.Comp.DataSet, uMunicipioDto, uClassSingletonConexao, System.Generics.Collections;
type
TMunicipioModel = class
private
oQueryListarMunicipios: TFDQuery;
public
function BuscarID: Integer;
function Alterar(var AMunicipio: TMunicipioDto): Boolean;
function Inserir(var AMunicipio: TMunicipioDto): Boolean;
procedure ListarMunicipios(var DsEstado: TDataSource);
function Deletar(const AIDMunicipio: Integer): Boolean;
function Pesquisar(ANome: String): Boolean;
function VerificarMunicipio(AMunicipio: TMunicipioDto; out AId: integer): Boolean;
function VerificarExcluir(AId: integer): Boolean;
function ADDListaHash(var oMunicipio: TObjectDictionary<string,
TMunicipioDto>): Boolean;
constructor Create;
destructor Destroy; override;
end;
implementation
{ TMunicipioModel }
function TMunicipioModel.ADDListaHash(
var oMunicipio: TObjectDictionary<string, TMunicipioDto>): Boolean;
var
oMunicipioDTO: TMunicipioDto;
oQuery: TFDQuery;
begin
Result := False;
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TSingletonConexao.GetInstancia;
oQuery.Open('select * from municipio');
if (not(oQuery.IsEmpty)) then
begin
oQuery.First;
while (not(oQuery.Eof)) do
begin
// Instancia do objeto
oMunicipioDTO := TMunicipioDto.Create;
// Atribui os valores
oMunicipioDTO.idMunicipio := oQuery.FieldByName('idMunicipio').AsInteger;
oMunicipioDTO.Nome := oQuery.FieldByName('Nome').AsString;
oMunicipioDTO.oEstado.IdUF := oQuery.FieldByName('Municipio_idUF').AsInteger;
// Adiciona o objeto na lista hash
oMunicipio.Add(oMunicipioDTO.Nome, oMunicipioDTO);
// Vai para o próximo registro
oQuery.Next;
end;
Result := True;
end;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
function TMunicipioModel.Alterar(var AMunicipio: TMunicipioDto): Boolean;
var
sSql: String;
begin
sSql := 'update municipio set nome = ' + QuotedStr(AMunicipio.Nome) +
' , municipio_idUf = ' + IntToStr(AMunicipio.oEstado.IdUF) +
' where idMunicipio = ' + IntToStr(AMunicipio.idMunicipio);
Result := TSingletonConexao.GetInstancia.ExecSQL(sSql) > 0;
end;
function TMunicipioModel.BuscarID: Integer;
var
oQuery: TFDQuery;
begin
Result := 1;
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TSingletonConexao.GetInstancia;
oQuery.Open('select max(IdMunicipio) as ID' + ' from Municipio');
if (not(oQuery.IsEmpty)) then
Result := oQuery.FieldByName('ID').AsInteger + 1;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
constructor TMunicipioModel.Create;
begin
oQueryListarMunicipios := TFDQuery.Create(nil);
end;
function TMunicipioModel.Deletar(const AIDMunicipio: Integer): Boolean;
begin
Result := TSingletonConexao.GetInstancia.ExecSQL
('delete from municipio where idmunicipio = ' + IntToStr(AIDMunicipio)) > 0;
end;
destructor TMunicipioModel.Destroy;
begin
oQueryListarMunicipios.Close;
if Assigned(oQueryListarMunicipios) then
FreeAndNil(oQueryListarMunicipios);
inherited;
end;
function TMunicipioModel.Inserir(var AMunicipio: TMunicipioDto): Boolean;
var
sSql: String;
begin
sSql := 'insert into municipio (idMunicipio, Nome, Municipio_idUF) values (' +
IntToStr(AMunicipio.idMunicipio) + ', ' + QuotedStr(AMunicipio.Nome) + ', '
+ IntToStr(AMunicipio.oEstado.IdUF) + ')';
Result := TSingletonConexao.GetInstancia.ExecSQL(sSql) > 0;
end;
procedure TMunicipioModel.ListarMunicipios(var DsEstado: TDataSource);
begin
oQueryListarMunicipios.Connection := TSingletonConexao.GetInstancia;
oQueryListarMunicipios.Open
('select m.idMunicipio, m.Nome,u.nome as estado from municipio as m inner join uf as u on m.Municipio_idUF=u.iduf');
DsEstado.DataSet := oQueryListarMunicipios;
end;
function TMunicipioModel.Pesquisar(ANome: String): Boolean;
begin
oQueryListarMunicipios.Open
('select m.idMunicipio, m.Nome,u.nome as estado from municipio as m inner join uf as u on m.Municipio_idUF=u.iduf WHERE m.Nome LIKE "%'
+ ANome + '%"');
if (not(oQueryListarMunicipios.IsEmpty)) then
begin
Result := True;
end
else
begin
Result := False;
oQueryListarMunicipios.Open
('select m.idMunicipio, m.Nome,u.nome as estado from municipio as m inner join uf as u on m.Municipio_idUF=u.iduf');
end;
end;
function TMunicipioModel.VerificarExcluir(AId: integer): Boolean;
var
oQuery: TFDQuery;
begin
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TSingletonConexao.GetInstancia;
oQuery.Open('select idBairro from bairro where bairro_idMunicipio = ' + IntToStr(AId));
if (oQuery.IsEmpty) then
Result := True
else
Result := False;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
function TMunicipioModel.VerificarMunicipio(AMunicipio: TMunicipioDto; out AId: integer): Boolean;
var
oQuery: TFDQuery;
begin
oQuery := TFDQuery.Create(nil);
try
oQuery.Connection := TSingletonConexao.GetInstancia;
oQuery.Open('select IdMunicipio from Municipio where Nome=' +
QuotedStr(AMunicipio.Nome) + ' AND Municipio_idUF='+IntToStr(AMunicipio.oEstado.IdUF));
if (not(oQuery.IsEmpty)) then
begin
AId := oQuery.FieldByName('IdMunicipio').AsInteger;
Result := True;
end
else
Result := False;
finally
if Assigned(oQuery) then
FreeAndNil(oQuery);
end;
end;
end.
|
unit LuaTrackbar;
{$mode delphi}
interface
uses
Classes, SysUtils, controls, comctrls, lua, lualib, lauxlib, betterControls;
procedure initializeLuaTrackbar;
implementation
uses luahandler, luaclass, luacaller, LuaWinControl;
//trackbar
function createTrackBar(L: Plua_State): integer; cdecl;
var
TrackBar: TTrackBar;
parameters: integer;
owner: TWincontrol;
begin
result:=0;
parameters:=lua_gettop(L);
if parameters>=1 then
owner:=lua_toceuserdata(L, -parameters)
else
owner:=nil;
lua_pop(L, lua_gettop(L));
TrackBar:=TTrackBar.Create(owner);
if owner<>nil then
TrackBar.Parent:=owner;
luaclass_newClass(L, TrackBar);
result:=1;
end;
function trackbar_getMax(L: PLua_State): integer; cdecl;
var
trackbar: Tcustomtrackbar;
begin
trackbar:=luaclass_getClassObject(L);
lua_pushinteger(L, trackbar.max);
result:=1;
end;
function trackbar_setMax(L: PLua_State): integer; cdecl;
var
trackbar: Tcustomtrackbar;
begin
result:=0;
trackbar:=luaclass_getClassObject(L);
if lua_gettop(L)>=1 then
trackbar.max:=lua_tointeger(L,-1);
end;
function trackbar_getMin(L: PLua_State): integer; cdecl;
var
trackbar: Tcustomtrackbar;
begin
trackbar:=luaclass_getClassObject(L);
lua_pushinteger(L, trackbar.Min);
result:=1;
end;
function trackbar_setMin(L: PLua_State): integer; cdecl;
var
trackbar: Tcustomtrackbar;
begin
result:=0;
trackbar:=luaclass_getClassObject(L);
if lua_gettop(L)>=1 then
trackbar.Min:=lua_tointeger(L,-1);
end;
function trackbar_getPosition(L: PLua_State): integer; cdecl;
var
trackbar: Tcustomtrackbar;
begin
trackbar:=luaclass_getClassObject(L);
lua_pushinteger(L, trackbar.Position);
result:=1;
end;
function trackbar_setPosition(L: PLua_State): integer; cdecl;
var
trackbar: Tcustomtrackbar;
begin
result:=0;
trackbar:=luaclass_getClassObject(L);
if lua_gettop(L)>=1 then
trackbar.Position:=lua_tointeger(L,-1);
end;
function trackbar_getonChange(L: PLua_State): integer; cdecl;
var
c: TCustomTrackBar;
begin
c:=luaclass_getClassObject(L);
LuaCaller_pushMethodProperty(L, TMethod(c.OnChange), 'TNotifyEvent');
result:=1;
end;
function trackbar_setonChange(L: PLua_State): integer; cdecl;
var
control: TCustomTrackBar;
f: integer;
routine: string;
lc: TLuaCaller;
begin
result:=0;
control:=luaclass_getClassObject(L);
if lua_gettop(L)>=1 then
begin
CleanupLuaCall(tmethod(control.onChange));
control.onChange:=nil;
if lua_isfunction(L,-1) then
begin
routine:=Lua_ToString(L,-1);
f:=luaL_ref(L,LUA_REGISTRYINDEX);
lc:=TLuaCaller.create;
lc.luaroutineIndex:=f;
control.OnChange:=lc.NotifyEvent;
end
else
if lua_isstring(L,-1) then
begin
routine:=lua_tostring(L,-1);
lc:=TLuaCaller.create;
lc.luaroutine:=routine;
control.OnChange:=lc.NotifyEvent;
end;
end;
end;
procedure trackbar_addMetaData(L: PLua_state; metatable: integer; userdata: integer );
begin
wincontrol_addMetaData(L, metatable, userdata);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getMax', trackbar_getMax);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setMax', trackbar_setMax);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getMin', trackbar_getMin);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setMin', trackbar_setMin);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getPosition', trackbar_getPosition);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setPosition', trackbar_setPosition);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setOnChange', trackbar_setonChange);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getOnChange', trackbar_getonChange);
luaclass_addPropertyToTable(L, metatable, userdata, 'Max', trackbar_getMax, trackbar_setMax);
luaclass_addPropertyToTable(L, metatable, userdata, 'Min', trackbar_getMin, trackbar_setMin);
luaclass_addPropertyToTable(L, metatable, userdata, 'Position', trackbar_getPosition, trackbar_setPosition);
luaclass_addPropertyToTable(L, metatable, userdata, 'OnChange', trackbar_getonChange, trackbar_setonChange);
end;
procedure initializeLuaTrackbar;
begin
lua_register(LuaVM, 'createTrackBar', createTrackBar);
lua_register(LuaVM, 'trackbar_getMax', trackbar_getMax);
lua_register(LuaVM, 'trackbar_setMax', trackbar_setMax);
lua_register(LuaVM, 'trackbar_getMin', trackbar_getMin);
lua_register(LuaVM, 'trackbar_setMin', trackbar_setMin);
lua_register(LuaVM, 'trackbar_getPosition', trackbar_getPosition);
lua_register(LuaVM, 'trackbar_setPosition', trackbar_setPosition);
lua_register(LuaVM, 'trackbar_onChange', trackbar_setonChange);
end;
initialization
luaclass_register(TCustomTrackbar, trackbar_addMetaData);
end.
|
(*
Copyright 2016 Michael Justin
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 Log4DLogger;
interface
uses
Log4D,
djLogAPI, SysUtils;
type
TLog4DLogger = class(TInterfacedObject, ILogger)
private
Delegate: TLogLogger;
procedure Log(const ALevel: TLogLevel; const AMsg: string); overload;
procedure Log(const ALevel: TLogLevel; const AFormat: string; const AArgs: array of const); overload;
public
constructor Create(const AName: string);
procedure Debug(const AMsg: string); overload;
procedure Debug(const AFormat: string; const AArgs: array of const); overload;
procedure Debug(const AMsg: string; const AException: Exception); overload;
procedure Error(const AMsg: string); overload;
procedure Error(const AFormat: string; const AArgs: array of const); overload;
procedure Error(const AMsg: string; const AException: Exception); overload;
procedure Info(const AMsg: string); overload;
procedure Info(const AFormat: string; const AArgs: array of const); overload;
procedure Info(const AMsg: string; const AException: Exception); overload;
procedure Warn(const AMsg: string); overload;
procedure Warn(const AFormat: string; const AArgs: array of const); overload;
procedure Warn(const AMsg: string; const AException: Exception); overload;
procedure Trace(const AMsg: string); overload;
procedure Trace(const AFormat: string; const AArgs: array of const); overload;
procedure Trace(const AMsg: string; const AException: Exception); overload;
function Name: string;
function IsDebugEnabled: Boolean;
function IsErrorEnabled: Boolean;
function IsInfoEnabled: Boolean;
function IsWarnEnabled: Boolean;
function IsTraceEnabled: Boolean;
end;
TLog4DLoggerFactory = class(TInterfacedObject, ILoggerFactory)
public
function GetLogger(const AName: string): ILogger;
end;
implementation
{ TLog4DLogger }
constructor TLog4DLogger.Create(const AName: string);
begin
inherited Create;
Delegate := TLogLogger.GetLogger(AName);
end;
procedure TLog4DLogger.Log(const ALevel: TLogLevel; const AMsg: string);
begin
Delegate.Log(ALevel, AMsg);
end;
procedure TLog4DLogger.Log(const ALevel: TLogLevel; const AFormat: string;
const AArgs: array of const);
begin
if Delegate.IsEnabledFor(ALevel) then
Delegate.Log(ALevel, Format(AFormat, AArgs));
end;
procedure TLog4DLogger.Debug(const AMsg: string);
begin
Log(Log4D.Debug, AMsg);
end;
procedure TLog4DLogger.Debug(const AFormat: string; const AArgs: array of const);
begin
Log(Log4D.Debug, AFormat, AArgs);
end;
procedure TLog4DLogger.Debug(const AMsg: string; const AException: Exception);
begin
Delegate.Debug(AMsg, AException);
end;
procedure TLog4DLogger.Trace(const AMsg: string; const AException: Exception);
begin
Delegate.Trace(AMsg, AException);
end;
procedure TLog4DLogger.Trace(const AFormat: string;
const AArgs: array of const);
begin
Log(Log4D.Trace, AFormat, AArgs);
end;
procedure TLog4DLogger.Trace(const AMsg: string);
begin
Log(Log4D.Trace, AMsg);
end;
procedure TLog4DLogger.Warn(const AMsg: string; const AException: Exception);
begin
Delegate.Warn(AMsg, AException);
end;
procedure TLog4DLogger.Warn(const AFormat: string; const AArgs: array of const);
begin
Log(Log4D.Warn, AFormat, AArgs);
end;
procedure TLog4DLogger.Warn(const AMsg: string);
begin
Log(Log4D.Warn, AMsg);
end;
procedure TLog4DLogger.Error(const AFormat: string;
const AArgs: array of const);
begin
Log(Log4D.Error, AFormat, AArgs);
end;
procedure TLog4DLogger.Error(const AMsg: string);
begin
Log(Log4D.Error, AMsg);
end;
procedure TLog4DLogger.Error(const AMsg: string; const AException: Exception);
begin
Delegate.Error(AMsg, AException);
end;
function TLog4DLogger.Name: string;
begin
Result := Delegate.Name;
end;
procedure TLog4DLogger.Info(const AMsg: string; const AException: Exception);
begin
Delegate.Info(AMsg, AException);
end;
function TLog4DLogger.IsDebugEnabled: Boolean;
begin
Result := Delegate.IsDebugEnabled;
end;
function TLog4DLogger.IsErrorEnabled: Boolean;
begin
Result := Delegate.IsErrorEnabled;
end;
function TLog4DLogger.IsInfoEnabled: Boolean;
begin
Result := Delegate.IsInfoEnabled;
end;
function TLog4DLogger.IsTraceEnabled: Boolean;
begin
Result := Delegate.IsTraceEnabled;
end;
function TLog4DLogger.IsWarnEnabled: Boolean;
begin
Result := Delegate.IsWarnEnabled;
end;
procedure TLog4DLogger.Info(const AFormat: string; const AArgs: array of const);
begin
Log(Log4D.Info, AFormat, AArgs);
end;
procedure TLog4DLogger.Info(const AMsg: string);
begin
Log(Log4D.Info, AMsg);
end;
{ TLog4DLoggerFactory }
function TLog4DLoggerFactory.GetLogger(const AName: string): ILogger;
begin
Result := TLog4DLogger.Create(AName);
end;
end.
|
unit MainView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus, Vcl.ComCtrls,
Security.Sessions.IUserSession;
type
TfrmMainView = class(TForm)
MainMenu1: TMainMenu;
miFile: TMenuItem;
miExit: TMenuItem;
miList: TMenuItem;
miCustomers: TMenuItem;
miItems: TMenuItem;
miOrders: TMenuItem;
miDB: TMenuItem;
miUpdateSchema: TMenuItem;
StatusBarBottom: TStatusBar;
procedure miExitClick(Sender: TObject);
procedure miCustomersClick(Sender: TObject);
procedure miItemsClick(Sender: TObject);
procedure miOrdersClick(Sender: TObject);
procedure miUpdateSchemaClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FUserSession : IUserSession;
public
{ Public declarations }
end;
var
frmMainView: TfrmMainView;
implementation
uses
CustomersView,
ItemsView,
OrdersView,
LoginView,
Aurelius.Engine.DatabaseManager,
Aurelius.Drivers.Interfaces,
Aurelius.SQL.SQLite,
Aurelius.Schema.SQLite,
Spring.Services;
{$R *.dfm}
procedure TfrmMainView.FormCreate(Sender: TObject);
begin
frmLoginView := TfrmLoginView.Create(Self);
if (frmLoginView.ShowModal <> mrOK) then
begin
Application.Terminate;
end;
FUserSession := ServiceLocator.GetService<IUserSession>;
StatusBarBottom.Panels[0].Text := IntToStr(FUserSession.getUserId());
end;
procedure TfrmMainView.miCustomersClick(Sender: TObject);
begin
frmCustomersView := TfrmCustomersView.Create(Self);
frmCustomersView.Show();
end;
procedure TfrmMainView.miExitClick(Sender: TObject);
begin
Close();
end;
procedure TfrmMainView.miItemsClick(Sender: TObject);
begin
frmItemsView := TfrmItemsView.Create(Self);
frmItemsView.Show();
end;
procedure TfrmMainView.miOrdersClick(Sender: TObject);
begin
frmOrdersView := TfrmOrdersView.Create(Self);
frmOrdersView.Show();
end;
procedure TfrmMainView.miUpdateSchemaClick(Sender: TObject);
var
DatabaseManager: TDatabaseManager;
ConnFac : IDBConnectionFactory;
begin
ConnFac := ServiceLocator.GetService<IDBConnectionFactory>;
DatabaseManager := TDatabaseManager.Create(ConnFac.CreateConnection);
try
//DatabaseManager.BuildDatabase;
DatabaseManager.UpdateDatabase;
ShowMessage('Database schema updated succesfully.');
finally
DatabaseManager.Free;
end;
end;
end.
|
unit UdmProcesadorResponse;
interface
uses
System.SysUtils, System.Classes, System.Variants, MSXML, RegularExpressions, System.StrUtils,
IdBaseComponent, IdCoder, IdCoder3to4, IdCoderMIME;
type
TdmProcesadorResponse = class(TDataModule)
Base64Encoder : TIdEncoderMIME;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
XMLDoc : IXMLDOMDocument;
FLstResponse : TStringList;
FStrParamsRespuesta : String;
FStrRespuesta : String;
FlagRespuestaExitosa : Boolean;
function buscarParametro(strNodeName : String) : String;
procedure procesarJSON(JSON : String);
public
{ Public declarations }
function init(AResponse, AParamsRespuesta : String) : String;
function mapearResponse : String;
end;
const
NO_ENCUENTRA_VALOR = '';
PREFIJO_NODO = '//';
RESPUESTA_EXITOSA = 'respuesta_exitosa';
RESPUESTA_FALLIDA = 'respuesta_fallida';
REGEX_NAMESPACE = '(</?)(\w+:)(.*?>)';
POSICIONES_1_Y_3_REGEX = '$1$3';
REGEX_HTML_XML_TAG = '(<)(.*?)(>)';
REGEX_XML_TAG = '<$2>';
REGEX_XML_HEADER = '<\?xml .*?\?>';
REGEX_VACIO = '';
BASE_64 = 'b64_';
implementation
uses System.JSON, System.JSON.Readers, System.JSON.Builders, System.Rtti;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TdmProcesadorResponse }
procedure TdmProcesadorResponse.DataModuleCreate(Sender: TObject);
begin
XMLDoc := CoDOMDocument.Create;
FLstResponse := TStringList.Create;
FlagRespuestaExitosa := False;
end;
function TdmProcesadorResponse.init(AResponse, AParamsRespuesta: String): String;
var
regex : TRegEx;
begin
regex.Create(REGEX_NAMESPACE);
FStrRespuesta := AResponse;
FStrParamsRespuesta := AParamsRespuesta;
FStrRespuesta := regex.Replace(FStrRespuesta, POSICIONES_1_Y_3_REGEX);
FStrRespuesta := regex.Replace(FStrRespuesta, REGEX_HTML_XML_TAG, REGEX_XML_TAG);
FStrRespuesta := regex.Replace(FStrRespuesta, REGEX_XML_HEADER, REGEX_VACIO);
XMLDoc.loadXML(FStrRespuesta);
end;
function TdmProcesadorResponse.mapearResponse : String;
var
RespuestaJSON : TJSONValue;
strResult : String;
begin
try
RespuestaJSON := TJSONObject.ParseJSONValue(FStrParamsRespuesta);
procesarJSON(RespuestaJSON.GetValue<TJSONObject>(RESPUESTA_EXITOSA).ToString);
if not FlagRespuestaExitosa then
procesarJSON(RespuestaJSON.GetValue<TJSONObject>(RESPUESTA_FALLIDA).ToString);
if FLstResponse.Text = '' then
begin
FLstResponse.Values['status_code'] := 'X';
FLstResponse.Values['status_desc'] := 'Response no mapeado - Respuesta no contenida';
end;
strResult := FLstResponse.Text;
finally
FLstResponse.Clear;
end;
result := strResult;
end;
procedure TdmProcesadorResponse.procesarJSON(JSON : String);
var
strKey : String;
strFindValue : String;
strValue : String;
LStringReader : TStringReader;
LJsonTextReader : TJsonTextReader;
LIterator : TJSONIterator;
begin
LStringReader := TStringReader.Create(JSON);
LJsonTextReader := TJsonTextReader.Create(LStringReader);
LIterator := TJSONIterator.Create(LJsonTextReader);
while LIterator.Next do
begin
strKey := LIterator.Key;
strFindValue := LIterator.AsString;
strValue := buscarParametro(strFindValue);
if LeftStr(strKey, 4) = BASE_64 then
FLstResponse.Values[strKey] := Base64Encoder.EncodeString(strValue)
else
FLstResponse.Values[strKey] := strValue;
end;
end;
function TdmProcesadorResponse.buscarParametro(strNodeName: String): String;
var
node : IXMLDOMNode;
strValue : String;
begin
strValue := NO_ENCUENTRA_VALOR;
node := XMLDoc.selectSingleNode(PREFIJO_NODO + strNodeName);
if Assigned(Node) then
begin
try
strValue := node.text;
except on e : exception do
strValue := NO_ENCUENTRA_VALOR;
end;
FlagRespuestaExitosa := True;
end;
result := strValue;
end;
end.
|
unit uConexao;
interface
uses
Data.SqlExpr, System.Classes, System.Generics.Collections, FMX.Dialogs,
System.RegularExpressions, System.SysUtils, dmuPrincipal;
type
TConexaoEstabelecida = reference to procedure(ipConexao: TSQLConnection);
TConexaoServidor = class(TThread)
private
FConexao: TSQLConnection;
FLoginIncorreto: Boolean;
public
property LoginIncorreto: Boolean read FLoginIncorreto;
property Conexao: TSQLConnection read FConexao;
constructor Create(ipParametrosConexao: TStrings);
procedure Execute; override;
end;
TGerenciadorConexao = class
private
FThreadsProcessadas: Integer;
FTotalThreads: Integer;
FConexaoEstabelecida: Boolean;
FOnEstabeleceuConexao: TConexaoEstabelecida;
procedure ppvOnTerminateThread(ipSender: TObject);
public
procedure ppuConectarServidor(ipOnEstabeleceuConexao: TConexaoEstabelecida);
end;
implementation
{ TConexaoServidor }
constructor TConexaoServidor.Create(ipParametrosConexao: TStrings);
begin
inherited Create(true);
FConexao := TSQLConnection.Create(nil);
FConexao.DriverName := 'DataSnap';
FConexao.Params.Assign(ipParametrosConexao);
end;
procedure TConexaoServidor.Execute;
begin
inherited;
FLoginIncorreto := false;
try
FConexao.Open;
except
on e: Exception do
begin
if TRegEx.IsMatch(e.message, 'Authentication manager rejected user credentials', [roIgnoreCase]) then
begin
FLoginIncorreto := true;
end
else
raise;
end;
end;
end;
{ TGerenciadorConexao }
procedure TGerenciadorConexao.ppuConectarServidor(ipOnEstabeleceuConexao: TConexaoEstabelecida);
var
vaThread: TConexaoServidor;
vaListaParametros: TObjectList<TStrings>;
vaParametros: TStrings;
begin
FOnEstabeleceuConexao := ipOnEstabeleceuConexao;
FConexaoEstabelecida := false;
FThreadsProcessadas := 0;
dmPrincipal.ppuAbrirConfig;
vaListaParametros := TObjectList<TStrings>.Create;
try
if dmPrincipal.qConfigHOST_SERVIDOR_INTERNO.AsString <> '' then
begin
vaParametros := TStringList.Create;
vaParametros.Assign(dmPrincipal.SongServerCon.Params);
dmPrincipal.ppuConfigurarConexaoServidor(dmPrincipal.qConfigHOST_SERVIDOR_INTERNO.AsString, vaParametros);
vaListaParametros.Add(vaParametros);
end;
if dmPrincipal.qConfigHOST_SERVIDOR_EXTERNO.AsString <> '' then
begin
vaParametros := TStringList.Create;
vaParametros.Assign(dmPrincipal.SongServerCon.Params);
dmPrincipal.ppuConfigurarConexaoServidor(dmPrincipal.qConfigHOST_SERVIDOR_EXTERNO.AsString, vaParametros);
vaListaParametros.Add(vaParametros);
end;
FTotalThreads := vaListaParametros.Count;
for vaParametros in vaListaParametros do
begin
vaThread := TConexaoServidor.Create(vaParametros);
vaThread.FreeOnTerminate := true;
vaThread.OnTerminate := ppvOnTerminateThread;
vaThread.Start;
end;
finally
vaListaParametros.Free;
end;
end;
procedure TGerenciadorConexao.ppvOnTerminateThread(ipSender: TObject);
begin
Inc(FThreadsProcessadas);
if not FConexaoEstabelecida then
begin
if Assigned(TConexaoServidor(ipSender).FatalException) then
begin
if (FThreadsProcessadas = FTotalThreads) then
begin
FOnEstabeleceuConexao(nil);
showMessage('Não foi possível se conectar ao servidor');
end;
end
else
begin
FConexaoEstabelecida := true;
if TConexaoServidor(ipSender).LoginIncorreto then
begin
FOnEstabeleceuConexao(nil);
showMessage('Usuário e/ou Senha de acesso ao SONG incorreto.');
end
else
begin
FOnEstabeleceuConexao(TConexaoServidor(ipSender).Conexao);
Exit;
end;
end;
end;
// se chegar aqui é pq ou deu erro ou a conexao ja foi estabelecida por outra thread
TConexaoServidor(ipSender).Conexao.Free;
end;
end.
|
unit LineMapping;
interface
uses
Classes, Types;
type
TLineMapping = class(TPersistent)
private
FMemoryAddress: Integer;
FASMLine: Integer;
FD16UnitName: string;
FUnitLine: Integer;
protected
FIsPossibleBreakPoint: Boolean;
procedure ReadFromArray(AInput: TStringDynArray); virtual;
function GetText: string; virtual;
public
constructor Create();
procedure Clear();
procedure ReadFromLine(ALine: string); virtual;
procedure Assign(ASource: TPersistent); override;
property D16UnitName: string read FD16UnitName write FD16UnitName;
property UnitLine: Integer read FUnitLine write FUnitLine;
property ASMLine: Integer read FASMLine write FASMLine;
property MemoryAddress: Integer read FMemoryAddress write FMemoryAddress;
property AsText: string read GetText;
property IsPossibleBreakPoint: Boolean read FIsPossibleBreakPoint;
end;
implementation
uses
SysUtils, StrUtils;
{ TLineMapping }
procedure TLineMapping.Assign(ASource: TPersistent);
var
LSource: TLineMapping;
begin
if ASource.InheritsFrom(TLineMapping) then
begin
LSource := TLineMapping(ASource);
FD16UnitName := LSource.D16UnitName;
FUnitLine := LSource.UnitLine;
FASMLine := LSource.ASMLine;
FMemoryAddress := LSource.MemoryAddress;
FIsPossibleBreakPoint := LSource.IsPossibleBreakPoint;
end;
end;
procedure TLineMapping.Clear;
begin
FD16UnitName := '';
FUnitLine := -1;
FASMLine := -1;
FMemoryAddress := -1;
end;
constructor TLineMapping.Create;
begin
Clear();
FIsPossibleBreakPoint := True;
end;
function TLineMapping.GetText: string;
begin
Result := D16UnitName + ',' + IntToStr(FUnitLine) + ',' + IntToStr(FASMLine) + ',$' + IntToHex(FMemoryAddress, 4);
end;
procedure TLineMapping.ReadFromArray(AInput: TStringDynArray);
begin
D16UnitName := AInput[0];
UnitLine := StrToInt(AInput[1]);
ASMLine := StrToInt(AInput[2]);
MemoryAddress := StrToInt(AInput[3]);
end;
procedure TLineMapping.ReadFromLine(ALine: string);
var
LElements: TStringDynArray;
begin
LElements := SplitString(Trim(ALine), ',');
if Length(LElements) = 4 then
begin
ReadFromArray(LElements);
end
else
begin
raise Exception.Create('Expected 4 elements, but found ' + IntToStr(Length(LElements)) + ' in ' + QuotedStr(ALine));
end;
end;
end.
|
unit roShell;
interface
uses
SysUtils, StrUtils, Classes, Windows;
function PathRemoveExtension(const Path: string): string;
function PathExtractFileNameNoExt(const Path: string): string;
// ║═IncludeTrailingPathDelimiter¤Ó═Č
function DisposePath(const Path: string): string;
function GetWindowsDir: string;
function GetSystemDir: string;
function GetCurrentDir: string;
function SetCurrentDir(const DirName: string): Boolean;
function DeleteFile(const FileName: string): Boolean;
function CopyFile(const ExistingFileName, NewFileName: string; bFailIfExists:
Boolean): Boolean;
function GetAppName: string;
function GetAppPath: string;
function RunAsAdmin(const Handle: Hwnd; const Path, Params: string): Boolean;
implementation
uses
ShellApi;
const
DirDelimiter = '\';
function PathRemoveExtension(const Path: string): string;
var
I: Integer;
begin
I := LastDelimiter(':.' + DirDelimiter, Path);
if (I > 0) and (Path[I] = '.') then
Result := Copy(Path, 1, I - 1)
else
Result := Path;
end;
function PathExtractFileNameNoExt(const Path: string): string;
begin
Result := PathRemoveExtension(ExtractFileName(Path));
end;
function DisposePath(const path: string): string;
begin
Result := IncludeTrailingPathDelimiter(Path);
end;
//------------------------------------------------------------------------------
// GetWindowsDir
//
// Wrapper around the GetWindowsDirectory Windows API function
//------------------------------------------------------------------------------
function GetWindowsDir: string;
var
lBuf: array[0..MAX_PATH] of Char;
begin
Result := '';
if GetWindowsDirectory(@lBuf[0], MAX_PATH + 1) <> 0 then
Result := ExcludeTrailingPathDelimiter(lBuf);
if Result = '' then
Result := 'C:\Windows';
end;
//------------------------------------------------------------------------------
// GetSystemDir
//
// Wrapper around the GetSystemDirectory Windows API function
//------------------------------------------------------------------------------
function GetSystemDir: string;
var
lBuf: array[0..MAX_PATH] of Char;
begin
Result := '';
if GetSystemDirectory(@lBuf[0], MAX_PATH + 1) <> 0 then
Result := ExcludeTrailingPathDelimiter(lBuf);
if Result = '' then
Result := 'C:\Windows\System32';
end;
function SetCurrentDir(const DirName: string): Boolean;
begin
Result := SetCurrentDirectoryW(PWideChar(DirName));
end;
function GetCurrentDir: string;
var
Buf: array[0..MAX_PATH] of WideChar;
begin
GetCurrentDirectoryW(MAX_PATH, Buf);
Result := Buf;
end;
function DeleteFile(const FileName: string): Boolean;
begin
Result := DeleteFileW(PWideChar(FileName));
end;
function CopyFile(const ExistingFileName, NewFileName: string; bFailIfExists:
Boolean): Boolean;
begin
Result := CopyFileW(PWideChar(ExistingFileName), PWideChar(NewFileName), bFailIfExists);
end;
function GetAppName: string;
begin
Result := LowerCase(ChangeFileExt( ExtractFileName(ParamStr(0)), ''));
end;
function GetAppPath: string;
begin
Result := ExtractFilePath(ParamStr(0));
end;
function RunAsAdmin(const Handle: Hwnd; const Path, Params: string): Boolean;
var
sei: TShellExecuteInfo;
begin
FillChar(sei, SizeOf(sei), 0);
sei.cbSize := SizeOf(sei);
sei.Wnd := Handle;
sei.fMask := SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI;
sei.lpVerb := 'runas';
sei.lpFile := PChar(Path);
sei.lpParameters := PChar(Params);
sei.nShow := SW_SHOWNORMAL;
Result := ShellExecuteExA(@sei);
end;
end.
|
//*******************************************************
//
// Delphi DataSnap Framework
//
// Copyright(c) 1995-2012 Embarcadero Technologies, Inc.
//
//*******************************************************
unit DBXValue;
{$IFDEF FPC}
{$mode DELPHI}
{$ENDIF}
interface
uses
DSRestTypes, Classes, SysUtils, DBXFPCJSON;
type
{ TDBXValue }
TDBXValue = class
private
FCurrentDBXType: TDBXDataTypes;
FisSimpleValueType: boolean;
function GetDBXType: TDBXDataTypes;
protected
FobjectValue: TObject;
procedure SetDBXType(const Value: TDBXDataTypes);
function GetAsInt8: Int8; virtual;
procedure SetAsInt8(const Value: Int8); virtual;
function GetAsInt16: Int16; virtual;
procedure SetAsInt16(const Value: Int16); virtual;
function GetAsInt32: Int32; virtual;
procedure SetAsInt32(const Value: Int32); virtual;
function GetAsInt64: int64; virtual;
procedure SetAsInt64(const Value: int64); virtual;
function GetAsBoolean: boolean; virtual;
procedure SetAsBoolean(const Value: boolean); virtual;
function GetAsUInt8: UInt8; virtual;
procedure SetAsUInt8(const Value: UInt8); virtual;
function GetAsUInt16: UInt16; virtual;
procedure SetAsUInt16(const Value: UInt16); virtual;
function GetAsUInt32: UInt32; virtual;
procedure SetAsUInt32(const Value: UInt32); virtual;
function GetAsUInt64: UInt64; virtual;
procedure SetAsUInt64(const Value: UInt64); virtual;
function GetAsString: string; virtual;
procedure SetAsString(const Value: string); virtual;
function GetAsAnsiString: ansistring; virtual;
procedure SetAsAnsiString(const Value: ansistring); virtual;
function GetAsWideString: WideString; virtual;
procedure SetAsWideString(const Value: WideString); virtual;
function GetAsDateTime: TDateTime; virtual;
procedure SetAsDateTime(const Value: TDateTime); virtual;
function GetAsTimeStamp: TDateTime; virtual;
procedure SetAsTimeStamp(const Value: TDateTime); virtual;
function GetAsSingle: single; virtual;
procedure SetAsSingle(const Value: single); virtual;
function GetAsStream: TStream; virtual;
function GetAsTDBXDate: longint; virtual;
function GetAsTDBXTime: longint; virtual;
procedure SetAsStream(const Value: TStream); virtual;
procedure SetAsTDBXDate(const Value: integer); virtual;
procedure SetAsTDBXTime(const Value: integer); virtual;
function GetAsCurrency: currency; virtual;
procedure SetAsCurrency(const Value: currency); virtual;
function GetASDBXValue: TDBXValue; virtual;
procedure SetAsDBXValue(const Value: TDBXValue); virtual;
function GetAsBcd: double; virtual;
procedure SetAsBcd(const Value: double); virtual;
function GetAsDouble: double; virtual;
procedure SetAsDouble(const Value: double); virtual;
function GetAsJSONValue: TJSONValue; virtual;
procedure SetAsJSONValue(const Value: TJSONValue); virtual;
function GetAsBlob: TStream; virtual;
procedure SetAsBlob(const Value: TStream); virtual;
function GetAsTable: TObject; virtual;
procedure SetAsTable(const Value: TObject); virtual;
function checkCurrentDBXType(Value: TDBXDataTypes): boolean;
function containsASimpleValueType: boolean;
public
constructor Create; virtual;
procedure Clear; virtual;
function IsNull: boolean;
procedure SetNull; virtual;
function ToString: string;override;
procedure SetTDBXNull(TypeName: String); virtual;
procedure AppendTo(json: TJSONArray);
property DBXType: TDBXDataTypes read GetDBXType write SetDBXType;
property AsInt8: Int8 read GetAsInt8 write SetAsInt8;
property AsInt16: Int16 read GetAsInt16 write SetAsInt16;
property AsInt32: Int32 read GetAsInt32 write SetAsInt32;
property AsInt64: int64 read GetAsInt64 write SetAsInt64;
property AsUInt8: UInt8 read GetAsUInt8 write SetAsUInt8;
property AsUInt16: UInt16 read GetAsUInt16 write SetAsUInt16;
property AsUInt32: UInt32 read GetAsUInt32 write SetAsUInt32;
property AsUInt64: UInt64 read GetAsUInt64 write SetAsUInt64;
property AsBoolean: boolean read GetAsBoolean write SetAsBoolean;
property AsString: string read GetAsString write SetAsString;
property AsAnsiString: ansistring read GetAsAnsiString
write SetAsAnsiString;
property AsWideString: WideString read GetAsWideString
write SetAsWideString;
property AsDateTime: TDateTime read GetAsDateTime write SetAsDateTime;
property AsTimeStamp: TDateTime read GetAsTimeStamp write SetAsTimeStamp;
property AsSingle: single read GetAsSingle write SetAsSingle;
property AsCurrency: currency read GetAsCurrency write SetAsCurrency;
property AsTDBXDate: integer read GetASTDBXDate write SetAsTDBXDate;
property AsTDBXTime: integer read GetASTDBXTime write SetAsTDBXTime;
property AsDBXValue: TDBXValue read GetASDBXValue write SetAsDBXValue;
property AsStream: TStream read GetAsStream write SetAsStream;
property AsBcd: double read GetAsBcd write SetAsBcd;
property AsDouble: double read GetAsDouble write SetAsDouble;
property AsJsonValue: TJSONValue read GetAsJSONValue write SetAsJSONValue;
property AsBlob: TStream read GetAsBlob write SetAsBlob;
property AsTable: TObject read GetAsTable write SetAsTable;
end;
TDBXValueType = class
private
FChildPosition: integer;
FHidden: boolean;
FLiteral: boolean;
FName: string;
FCaption: string;
FNullable: boolean;
FOrdinal: integer;
FParameterDirection: integer;
FPrecision: longint;
FScale: integer;
FSize: longint;
FSubType: integer;
FValueParameter: boolean;
function GetCaption: string;
function GetChildPosition: integer;
function GetHidden: boolean;
function GetLiteral: boolean;
function GetName: string;
function GetNullable: boolean;
function GetOrdinal: integer;
function GetParameterDirection: integer;
function GetPrecision: longint;
function GetScale: integer;
function GetSize: longint;
function GetSubType: integer;
function GetValueParameter: boolean;
procedure SetChildPosition(const AValue: integer);
procedure SetHidden(const AValue: boolean);
procedure SetLiteral(const AValue: boolean);
procedure SetName(const AValue: string);
procedure SetCaption(const AValue: string);
procedure SetNullable(const AValue: boolean);
procedure SetOrdinal(const AValue: integer);
procedure SetParameterDirection(const AValue: integer);
procedure SetPrecision(const AValue: longint);
procedure SetScale(const AValue: integer);
procedure SetSize(const AValue: longint);
procedure SetSubType(const AValue: integer);
procedure SetValueParameter(const AValue: boolean);
public
property Name: string read GetName write SetName;
property Caption: string read GetCaption write SetCaption;
property Ordinal: integer read GetOrdinal write SetOrdinal;
property SubType: integer read GetSubType write SetSubType;
property Size: longint read GetSize write SetSize;
property Precision: longint read GetPrecision write SetPrecision;
property Scale: integer read GetScale write SetScale;
property ChildPosition: integer read GetChildPosition
write SetChildPosition;
property Nullable: boolean read GetNullable write SetNullable;
property ParameterDirection: integer read GetParameterDirection
write SetParameterDirection;
property Hidden: boolean read GetHidden write SetHidden;
property ValueParameter: boolean read GetValueParameter
write SetValueParameter;
property Literal: boolean read GetLiteral write SetLiteral;
procedure setDataType(dataType: TDBXDataTypes); virtual;
function getDataType: integer; virtual;
end;
{ TDBXWritableValue }
TDBXWritableValue = class(TDBXValue)
protected
FBooleanValue: boolean;
FINT32Value: Int32;
FUINT32Value: longint;
FINT64Value: int64;
FUINT64Value: longint;
FStringValue: string;
FSingleValue: double;
FDoubleValue: double;
FDateTimeValue: TDateTime;
FstreamValue: TStream;
FobjectValue: TObject;
FJsonValueValue: TJSONValue;
FDBXValueValue: TDBXValue;
FBcdValue: double;
FTimeStampValue: TDateTime;
procedure throwInvalidValue;
public
destructor Destroy; override;
procedure SetTDBXNull(TypeName: String); override;
function GetAsInt8: Int8; override;
procedure SetAsInt8(const Value: Int8); override;
function GetAsInt32: integer; override;
procedure SetAsInt32(const Value: Int32); override;
function GetAsInt16: Int16; override;
procedure SetAsInt16(const Value: Int16); override;
function GetAsInt64: int64; override;
procedure SetAsInt64(const Value: int64); override;
function GetAsBoolean: boolean; override;
procedure SetAsBoolean(const Value: boolean); override;
function GetAsUInt8: UInt8; override;
procedure SetAsUInt8(const Value: UInt8); override;
function GetAsUInt16: UInt16; override;
procedure SetAsUInt16(const Value: UInt16); override;
function GetAsUInt32: UInt32; override;
procedure SetAsUInt32(const Value: UInt32); override;
function GetAsUInt64: UInt64; override;
procedure SetAsUInt64(const Value: UInt64); override;
function GetAsString: string; override;
procedure SetAsString(const Value: string); override;
function GetAsAnsiString: ansistring; override;
procedure SetAsAnsiString(const Value: ansistring); override;
function GetAsWideString: WideString; override;
procedure SetAsWideString(const Value: WideString); override;
function GetAsDateTime: TDateTime; override;
procedure SetAsDateTime(const Value: TDateTime); override;
function GetAsTimeStamp: TDateTime; override;
procedure SetAsTimeStamp(const Value: TDateTime); override;
function GetAsSingle: single; override;
procedure SetAsSingle(const Value: single); override;
function GetAsStream: TStream; override;
function GetAsTDBXDate: longint; override;
function GetAsTDBXTime: longint; override;
procedure SetAsStream(const Value: TStream); override;
procedure SetAsTDBXDate(const Value: integer); override;
procedure SetAsTDBXTime(const Value: integer); override;
function GetAsCurrency: currency; override;
procedure SetAsCurrency(const Value: currency); override;
function GetASDBXValue: TDBXValue; override;
procedure SetAsDBXValue(const Value: TDBXValue); override;
function GetAsBcd: double; override;
procedure SetAsBcd(const Value: double); override;
function GetAsDouble: double; override;
procedure SetAsDouble(const Value: double); override;
function GetAsJSONValue: TJSONValue; override;
procedure SetAsJSONValue(const Value: TJSONValue); override;
function GetAsBlob: TStream; override;
procedure SetAsBlob(const Value: TStream); override;
function GetAsTable: TObject; override;
procedure SetAsTable(const Value: TObject); override;
procedure Clear; override;
end;
function TypeIsDBXValue(Value: string): boolean;
implementation
{ TDBXValue }
uses DBXDefaultFormatter, DBXJsonTools, DBXFPCCommon, FPCStrings;
function TypeIsDBXValue(Value: string): boolean;
begin
Result := (pos('TDBX', Value) = 1) and
(pos('Value', Value) = length(Value) - 4);
end;
procedure TDBXValue.AppendTo(json: TJSONArray);
var
jvaluec, jvalue: TJSONValue;
begin
try
if containsASimpleValueType then
begin
if GetASDBXValue.IsNull then
json.Add(TJSONNull.Create)
else
GetASDBXValue.AppendTo(json);
Exit;
end;
case FCurrentDBXType of
BooleanType:
json.Add(AsBoolean);
Int8Type:
json.Add(AsInt8);
Int16Type:
json.Add(AsInt16);
Int32Type:
json.Add(AsInt32);
Int64Type:
json.Add(AsInt64);
UInt8Type:
json.Add(AsUInt8);
UInt16Type:
json.Add(AsUInt16);
UInt32Type:
json.Add(AsUInt32);
UInt64Type:
json.Add(AsUInt64);
AnsiStringType, WideStringType:
json.Add(AsString);
DateTimeType:
json.Add(TDBXDefaultFormatter.GetInstance.DateTimeToString(AsDateTime));
TimeStampType:
json.Add(TDBXDefaultFormatter.GetInstance.DateTimeToString
(AsTimeStamp));
DateType:
json.Add(TDBXDefaultFormatter.GetInstance.DBXDateToString(AsTDBXDate));
TimeType:
json.Add(TDBXDefaultFormatter.GetInstance.DBXTimeToString(AsTDBXTime));
JsonValueType:
begin
jvaluec:= nil;
jvalue := AsJsonValue;
if assigned(jvalue) then
jvaluec := jvalue.clone;
if assigned(json) and assigned(jvaluec) then
json.Add(jvaluec);
end;
TableType:
json.Add(TDBXJsonTools.SerializeTableType(AsTable));
CurrencyType:
json.Add(AsCurrency);
DoubleType:
json.Add(AsDouble);
SingleType:
json.Add(AsSingle);
BinaryBlobType:
json.Add(TDBXJsonTools.StreamToJSONArray(AsStream));
BlobType:
json.Add(TDBXJsonTools.StreamToJSONArray(AsBlob));
else
raise DBXException.Create('Cannot convert this type to string');
end;
except
on e: DBXException do
Exit;
end;
end;
function TDBXValue.checkCurrentDBXType(Value: TDBXDataTypes): boolean;
begin
result:= false;
if FCurrentDBXType <> Value then
raise DBXException.Create('Incorrect type in DBXValue');
end;
procedure TDBXValue.Clear;
begin
SetDBXType(UnknownType);
end;
function TDBXValue.containsASimpleValueType: boolean;
begin
Result := FisSimpleValueType;
end;
constructor TDBXValue.Create;
begin
inherited Create;
DBXType := UnknownType;
end;
function TDBXValue.GetAsAnsiString: ansistring;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsBcd: double;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsBoolean: boolean;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsCurrency: currency;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsDateTime: TDateTime;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetASDBXValue: TDBXValue;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsDouble: double;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsInt16: Int16;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsInt32: Int32;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsInt64: int64;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsInt8: Int8;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsSingle: single;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsStream: TStream;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsString: string;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetASTDBXDate: longint;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetASTDBXTime: longint;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsTimeStamp: TDateTime;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsUInt16: UInt16;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsUInt32: UInt32;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsUInt64: UInt64;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsUInt8: UInt8;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsWideString: WideString;
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetDBXType: TDBXDataTypes;
begin
Result := FCurrentDBXType;
end;
function TDBXValue.GetAsTable: TObject;
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsTable(const Value: TObject);
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsBlob: TStream;
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsBlob(const Value: TStream);
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.GetAsJSONValue: TJSONValue;
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsJSONValue(const Value: TJSONValue);
begin
raise DBXException.Create('Invalid Type Access');
end;
function TDBXValue.IsNull: boolean;
begin
Result := FCurrentDBXType = UnknownType;
end;
procedure TDBXValue.SetNull;
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsAnsiString(const Value: ansistring);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsBcd(const Value: double);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsBoolean(const Value: boolean);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsCurrency(const Value: currency);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsDateTime(const Value: TDateTime);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsDBXValue(const Value: TDBXValue);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsDouble(const Value: double);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsInt16(const Value: Int16);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsInt32(const Value: Int32);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsInt64(const Value: int64);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsInt8(const Value: Int8);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsSingle(const Value: single);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsStream(const Value: TStream);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsTDBXDate(const Value: integer);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsTDBXTime(const Value: integer);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsString(const Value: string);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsTimeStamp(const Value: TDateTime);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsUInt16(const Value: UInt16);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsUInt32(const Value: UInt32);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsUInt64(const Value: UInt64);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsUInt8(const Value: UInt8);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetAsWideString(const Value: WideString);
begin
raise DBXException.Create('Invalid Type Access');
end;
procedure TDBXValue.SetDBXType(const Value: TDBXDataTypes);
begin
FCurrentDBXType := Value;
FisSimpleValueType := False;
end;
function TDBXValue.ToString: string;
begin
Result := '<CANNOT CONVERT TO STRING>';
if containsASimpleValueType then
begin
if GetASDBXValue.IsNull then
begin
with TJSONNull.Create do
begin
Result := asJSONString;
Free;
end;
end
else
Result := GetASDBXValue.ToString;
end
else
begin
case FCurrentDBXType of
Int8Type:
Result := TDBXDefaultFormatter.GetInstance.Int8ToString(GetAsInt8);
Int16Type:
Result := TDBXDefaultFormatter.GetInstance.Int16ToString(GetAsInt16);
Int32Type:
Result := TDBXDefaultFormatter.GetInstance.Int32ToString(GetAsInt32);
Int64Type:
Result := TDBXDefaultFormatter.GetInstance.Int64ToString(GetAsInt64);
UInt8Type:
Result := TDBXDefaultFormatter.GetInstance.UInt8ToString(GetAsUInt8);
UInt16Type:
Result := TDBXDefaultFormatter.GetInstance.UInt16ToString(GetAsUInt16);
UInt32Type:
Result := TDBXDefaultFormatter.GetInstance.UInt32ToString(GetAsUInt32);
UInt64Type:
Result := TDBXDefaultFormatter.GetInstance.UInt64ToString(GetAsUInt64);
AnsiStringType:
Result := TDBXDefaultFormatter.GetInstance.AnsiStringToString
(GetAsAnsiString);
WideStringType:
Result := TDBXDefaultFormatter.GetInstance.WideStringToString
(GetAsString);
DateTimeType:
Result := TDBXDefaultFormatter.GetInstance.DateTimeToString
(GetAsDateTime);
CurrencyType:
Result := TDBXDefaultFormatter.GetInstance.CurrencyToString
(GetAsCurrency);
DoubleType:
Result := TDBXDefaultFormatter.GetInstance.DoubleToString(GetAsDouble);
SingleType:
Result := TDBXDefaultFormatter.GetInstance.SingleToString(GetAsSingle);
DateType:
Result := TDBXDefaultFormatter.GetInstance.DBXDateToString
(GetASTDBXDate);
TimeType:
Result := TDBXDefaultFormatter.GetInstance.DBXTimeToString
(GetASTDBXTime);
TimeStampType:
Result := TDBXDefaultFormatter.GetInstance.DateTimeToString
(GetAsTimeStamp);
BooleanType:
Result := TDBXDefaultFormatter.GetInstance.BooleanToString
(GetAsBoolean);
BcdType:
Result := TDBXDefaultFormatter.GetInstance.DoubleToString(GetAsBcd);
else
DBXException.Create('Cannot convert this type to string');
end;
end;
end;
procedure TDBXValue.SetTDBXNull(TypeName: String);
begin
raise DBXException.Create('Invalid Type Access');
end;
{ TDBXWritableValue }
procedure TDBXWritableValue.Clear;
begin
FBooleanValue := False;
FINT32Value := 0;
FUINT32Value := 0;
FINT64Value := 0;
FUINT64Value := 0;
FStringValue := '';
FSingleValue := 0;
FDoubleValue := 0;
FDateTimeValue := 0;
if assigned(FstreamValue) then
FreeAndNil(FstreamValue);
if assigned(FobjectValue) then
FreeAndNil(FobjectValue);
if assigned(FJsonValueValue) then
FreeAndNil(FJsonValueValue);
if assigned(FDBXValueValue) then
FreeAndNil(FDBXValueValue);
FBcdValue := 0;
FTimeStampValue := 0;
end;
function TDBXWritableValue.GetAsAnsiString: ansistring;
begin
try
{$WARNINGS OFF}
Result := GetAsString;
{$WARNINGS ON}
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsBcd: double;
begin
try
checkCurrentDBXType(BcdType);
Result := FBcdValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsBoolean: boolean;
begin
try
checkCurrentDBXType(BooleanType);
Result := FBooleanValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsCurrency: currency;
begin
try
checkCurrentDBXType(CurrencyType);
Result := FDoubleValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsDateTime: TDateTime;
begin
try
checkCurrentDBXType(DateTimeType);
Result := FDateTimeValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetASDBXValue: TDBXValue;
begin
if not FisSimpleValueType then
raise DBXException.Create('Invalid DBX type');
Result := FDBXValueValue;
end;
function TDBXWritableValue.GetAsDouble: double;
begin
try
checkCurrentDBXType(DoubleType);
Result := FDoubleValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsInt16: Int16;
begin
try
checkCurrentDBXType(Int16Type);
Result := FINT32Value;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsInt32: integer;
begin
try
checkCurrentDBXType(Int32Type);
Result := FINT32Value;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsInt64: int64;
begin
try
checkCurrentDBXType(Int64Type);
Result := FINT64Value;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsInt8: Int8;
begin
try
checkCurrentDBXType(Int8Type);
Result := FINT32Value;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsSingle: single;
begin
try
checkCurrentDBXType(SingleType);
Result := FSingleValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsStream: TStream;
begin
try
checkCurrentDBXType(BinaryBlobType);
FstreamValue.Position := 0;
Result := FstreamValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsString: string;
begin
try
checkCurrentDBXType(WideStringType);
Result := FStringValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetASTDBXDate: longint;
begin
try
checkCurrentDBXType(DateType);
Result := FINT32Value;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetASTDBXTime: longint;
begin
try
checkCurrentDBXType(TimeType);
Result := FINT32Value;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsTimeStamp: TDateTime;
begin
try
checkCurrentDBXType(TimeStampType);
Result := FTimeStampValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsUInt16: UInt16;
begin
try
checkCurrentDBXType(UInt16Type);
Result := FINT32Value;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsUInt32: UInt32;
begin
try
checkCurrentDBXType(UInt32Type);
Result := FUINT32Value;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsUInt64: UInt64;
begin
try
checkCurrentDBXType(UInt64Type);
Result := FUINT64Value;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsUInt8: UInt8;
begin
try
checkCurrentDBXType(UInt8Type);
Result := FINT32Value;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
function TDBXWritableValue.GetAsWideString: WideString;
begin
try
checkCurrentDBXType(WideStringType);
Result := FStringValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
procedure TDBXWritableValue.SetAsAnsiString(const Value: ansistring);
begin
SetAsString(String(Value));
end;
procedure TDBXWritableValue.SetAsBcd(const Value: double);
begin
try
FBcdValue := Value;
DBXType := BcdType;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsBoolean(const Value: boolean);
begin
try
FBooleanValue := Value;
DBXType := BooleanType;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsCurrency(const Value: currency);
begin
try
FDoubleValue := Value;
DBXType := CurrencyType;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsDateTime(const Value: TDateTime);
begin
try
FDateTimeValue := Value;
DBXType := DateTimeType;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsDBXValue(const Value: TDBXValue);
begin
try
SetDBXType(Value.GetDBXType);
FisSimpleValueType := True;
FDBXValueValue := Value;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsDouble(const Value: double);
begin
try
FDoubleValue := Value;
DBXType := DoubleType;
except
throwInvalidValue;
end;
end;
function TDBXWritableValue.GetAsJSONValue: TJSONValue;
begin
try
checkCurrentDBXType(JsonValueType);
Result := FJsonValueValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
procedure TDBXWritableValue.SetAsJSONValue(const Value: TJSONValue);
begin
try
Clear();
FJsonValueValue := Value;
DBXType := JsonValueType;
except
throwInvalidValue;
end;
end;
function TDBXWritableValue.GetAsBlob: TStream;
begin
try
checkCurrentDBXType(BlobType);
Result := TStream(FobjectValue);
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
procedure TDBXWritableValue.SetAsBlob(const Value: TStream);
begin
try
Clear();
FobjectValue := Value;
DBXType := BlobType;
except
throwInvalidValue;
end;
end;
function TDBXWritableValue.GetAsTable: TObject;
begin
try
checkCurrentDBXType(TableType);
Result := FobjectValue;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
procedure TDBXWritableValue.SetAsTable(const Value: TObject);
begin
try
Clear();
DBXType := TableType;
FobjectValue := Value;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsInt16(const Value: Int16);
begin
try
FINT32Value := Value;
DBXType := Int16Type;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsInt32(const Value: Int32);
begin
try
FINT32Value := Value;
DBXType := Int32Type;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsInt64(const Value: int64);
begin
try
FINT64Value := Value;
DBXType := Int64Type;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsInt8(const Value: Int8);
begin
try
FINT32Value := Value;
DBXType := Int8Type;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsSingle(const Value: single);
begin
try
FSingleValue := Value;
DBXType := SingleType;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsStream(const Value: TStream);
begin
try
Clear;
Value.Position := 0;
FstreamValue := TMemoryStream.Create;
FstreamValue.Position := 0;
FstreamValue.CopyFrom(Value, Value.Size);
FstreamValue.Position := 0;
DBXType := BinaryBlobType;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsString(const Value: string);
begin
try
FStringValue := Value;
DBXType := WideStringType;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsTDBXDate(const Value: integer);
begin
try
FINT32Value := Value;
DBXType := DateType;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsTDBXTime(const Value: integer);
begin
try
FINT32Value := Value;
DBXType := TimeType;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsTimeStamp(const Value: TDateTime);
begin
try
FTimeStampValue := Value;
DBXType := TimeStampType;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsUInt16(const Value: UInt16);
begin
try
FINT32Value := Value;
DBXType := UInt16Type;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsUInt32(const Value: UInt32);
begin
try
FUINT32Value := Value;
DBXType := UInt32Type;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsUInt64(const Value: UInt64);
begin
try
FUINT64Value := Value;
DBXType := UInt64Type;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsUInt8(const Value: UInt8);
begin
try
FINT32Value := Value;
DBXType := UInt8Type;
except
throwInvalidValue;
end;
end;
procedure TDBXWritableValue.SetAsWideString(const Value: WideString);
begin
SetAsString(Value);
end;
procedure TDBXWritableValue.throwInvalidValue;
begin
raise DBXException.Create('Invalid value for param');
end;
destructor TDBXWritableValue.Destroy;
begin
// FreeAndNil(FstreamValue);
// FreeAndNil(FobjectValue);
// FreeAndNil(FJsonValueValue);
// FreeAndNil(FDBXValueValue);
inherited Destroy;
end;
procedure TDBXWritableValue.SetTDBXNull(TypeName: String);
var
v: TDBXValue;
begin
v:= nil;
try
if TypeName = 'TDBXStringValue' then
begin
v := TDBXStringValue.Create;
v.SetNull;
end
else if TypeName = 'TDBXAnsiCharsValue' then
begin
v := TDBXAnsiCharsValue.Create;
v.SetNull;
end
else if TypeName = 'TDBXAnsiStringValue' then
begin
v := TDBXAnsiStringValue.Create;
v.SetNull;
end
else if TypeName = 'TDBXWideStringValue' then
begin
v := TDBXWideStringValue.Create;
v.SetNull;
end
else if TypeName = 'TDBXSingleValue' then
begin
v := TDBXSingleValue.Create;
v.SetNull;
end
else if TypeName = 'TDBXDateValue' then
begin
v := TDBXDateValue.Create;
v.SetNull;
end
else if TypeName = 'TDBXTimeValue' then
begin
v := TDBXTimeValue.Create;
v.SetNull;
end
else if TypeName = 'TDBXBooleanValue' then
begin
v := TDBXBooleanValue.Create;
v.SetNull;
end
else if TypeName = 'TDBXDoubleValue' then
begin
v := TDBXDoubleValue.Create;
v.SetNull;
end
else if TypeName = 'TDBXInt64Value' then
begin
v := TDBXInt64Value.Create;
v.SetNull;
end
else if TypeName = 'TDBXInt32Value' then
begin
v := TDBXInt32Value.Create;
v.SetNull;
end
else if TypeName = 'TDBXInt16Value' then
begin
v := TDBXInt16Value.Create;
v.SetNull;
end
else if TypeName = 'TDBXInt8Value' then
begin
v := TDBXInt8Value.Create;
v.SetNull;
end
else if TypeName = 'TDBXStreamValue' then
begin
v := TDBXStreamValue.Create;
v.SetNull;
end
else if TypeName = 'TDBXReaderValue' then
begin
v := TDBXReaderValue.Create;
v.SetNull;
end;
if assigned(v) then
AsDBXValue := v;
except
on e: Exception do
raise DBXException.Create(e.Message);
end;
end;
{ TDBXValueType }
procedure TDBXValueType.SetName(const AValue: string);
begin
if FName = AValue then
Exit;
FName := AValue;
end;
procedure TDBXValueType.SetChildPosition(const AValue: integer);
begin
if FChildPosition = AValue then
Exit;
FChildPosition := AValue;
end;
function TDBXValueType.GetCaption: string;
begin
Result := FCaption;
end;
function TDBXValueType.GetChildPosition: integer;
begin
Result := FChildPosition;
end;
function TDBXValueType.GetHidden: boolean;
begin
Result := FHidden;
end;
function TDBXValueType.GetLiteral: boolean;
begin
Result := FLiteral;
end;
function TDBXValueType.GetName: string;
begin
Result := FName;
end;
function TDBXValueType.GetNullable: boolean;
begin
Result := FNullable;
end;
function TDBXValueType.GetOrdinal: integer;
begin
Result := FOrdinal;
end;
function TDBXValueType.GetParameterDirection: integer;
begin
Result := FParameterDirection;
end;
function TDBXValueType.GetPrecision: longint;
begin
Result := FPrecision;
end;
function TDBXValueType.GetScale: integer;
begin
Result := FScale;
end;
function TDBXValueType.GetSize: longint;
begin
Result := FSize;
end;
function TDBXValueType.GetSubType: integer;
begin
Result := FSubType;
end;
function TDBXValueType.GetValueParameter: boolean;
begin
Result := FValueParameter;
end;
procedure TDBXValueType.SetHidden(const AValue: boolean);
begin
if FHidden = AValue then
Exit;
FHidden := AValue;
end;
procedure TDBXValueType.SetLiteral(const AValue: boolean);
begin
if FLiteral = AValue then
Exit;
FLiteral := AValue;
end;
procedure TDBXValueType.SetCaption(const AValue: string);
begin
if FCaption = AValue then
Exit;
FCaption := AValue;
end;
procedure TDBXValueType.SetNullable(const AValue: boolean);
begin
if FNullable = AValue then
Exit;
FNullable := AValue;
end;
procedure TDBXValueType.SetOrdinal(const AValue: integer);
begin
if FOrdinal = AValue then
Exit;
FOrdinal := AValue;
end;
procedure TDBXValueType.SetParameterDirection(const AValue: integer);
begin
if FParameterDirection = AValue then
Exit;
FParameterDirection := AValue;
end;
procedure TDBXValueType.SetPrecision(const AValue: longint);
begin
if FPrecision = AValue then
Exit;
FPrecision := AValue;
end;
procedure TDBXValueType.SetScale(const AValue: integer);
begin
if FScale = AValue then
Exit;
FScale := AValue;
end;
procedure TDBXValueType.SetSize(const AValue: longint);
begin
if FSize = AValue then
Exit;
FSize := AValue;
end;
procedure TDBXValueType.SetSubType(const AValue: integer);
begin
if FSubType = AValue then
Exit;
FSubType := AValue;
end;
procedure TDBXValueType.SetValueParameter(const AValue: boolean);
begin
if FValueParameter = AValue then
Exit;
FValueParameter := AValue;
end;
procedure TDBXValueType.setDataType(dataType: TDBXDataTypes);
begin
raise DBXException.Create('Must be overridden in the descendant classes');
end;
function TDBXValueType.getDataType: integer;
begin
raise DBXException.Create('Must be overridden in the descendant classes');
end;
end.
|
unit Cedio;
{ =================================================================
WinWCP - CED 1401 Interface Library V1.0
(c) John Dempster, University of Strathclyde, All Rights Reserved
12/2/97
=================================================================}
interface
uses WinTypes,Dialogs, SysUtils, WinProcs,global, shared ;
procedure CED_LoadLibrary ;
Procedure CED_GetADCVoltageRangeOptions( var RangeOptions : array of TADCRange ;
var NumOptions : Integer) ;
procedure CED_GetSamplingIntervalRange( var MinInterval,MaxInterval : single ) ;
procedure CED_InitialiseBoard ;
procedure SendCommand( const CommandString : string ) ;
procedure CED_ADCToMemory( var ADCBuf : array of integer ;
nChannels : LongInt ;
nSamples : LongInt ;
var dt : Single ;
ADCVoltageRange : Single ;
WaitForExtTrigger : Boolean ;
CircularBuffer : Boolean ) ;
procedure CED_StopADC ;
procedure CED_MemoryToDAC( var DACBuf : array of integer ;
nChannels : LongInt ;
nPoints : LongInt ;
dt : Single ;
NumRepeats : LongInt ) ;
procedure CED_ConvertToDACCodes( var DACBuf : Array of Integer ;
nChannels : LongInt ;
nPoints : LongInt ) ;
procedure CED_StopDAC ;
procedure CED_GetLabInterfaceInfo( Supplier, Model : String ) ;
procedure CED_ClockTicks( var dt : single ; var PreScale,Ticks : Word ) ;
{ Function CED_ReadADC( Channel : Integer ; ADCVoltageRange : Single ) : Integer ;
procedure CED_CheckError( Err : Integer ) ;
procedure CED_WriteToDigitalOutPutPort( Pattern : LongInt ) ; }
function CED_GetMaxDACVolts : single ;
procedure CED_GetChannelOffsets( var Offsets : Array of LongInt ; NumChannels : LongInt ) ;
{procedure CED_ReportFailure( const ProcName : string ) ;}
function CED_IsLabInterfaceAvailable : boolean ;
implementation
const
ClockPeriod = 1E-6 ; { 1MHz clock }
var
DeviceNumber : Integer ; { Lab. interface board in use }
ADCVoltageRangeMax : single ; { Max. positive A/D input voltage range}
DACVoltageRangeMax : single ;
MinSamplingInterval : single ;
MaxSamplingInterval : single ;
LibraryLoaded : boolean ; { True if CED 1401 procedures loaded }
DeviceInitialised : boolean ; { True if hardware has been initialised }
Device : Integer ;
procedure CED_LoadLibrary ;
{ ----------------------------------
Load USE1401.DLL library into memory
----------------------------------}
var
Hnd : THandle ;
DLLName0 : array[0..79] of char ;
begin
{ Load library }
StrPCopy( DLLName0,'USE1401.DLL');
Hnd := LoadLibrary(DLLName0);
{ Get addresses of procedure NI_s used }
if Hnd > HINSTANCE_ERROR then begin
end
else begin
MessageDlg( 'USE1401.DLL library not found', mtWarning, [mbOK], 0 ) ;
LibraryLoaded := False ;
end ;
end ;
procedure CED_GetLabInterfaceInfo( Supplier, Model : String ) ;
var
Ver : LongInt ;
begin
if not DeviceInitialised then CED_InitialiseBoard ;
Supplier := 'Cambridge Electronic Design Ltd.' ;
{ Get the 1401 model }
{ case U14TypeOf1401( Device ) of
U14TYPE1401 : Model := 'CED 1401 ';
U14TYPEPLUS : Model := 'CED 1401-plus ';
U14TYPEUNKNOWN : Model := 'CED 1401? ';
else Model := 'CED 1401? ' ;
end ; }
{ Add the CED1401.SYS driver version number }
{Ver := U14DriverVersion ;}
Model := Model + format('Driver V%d.%d',[Ver/$10000,Ver and $FFFF]) ;
{ Cancel all commands and reset 1401 }
SendCommand( 'CLEAR;' ) ;
end ;
Procedure CED_GetADCVoltageRangeOptions( var RangeOptions : array of TADCRange ;
var NumOptions : Integer) ;
begin
RangeOptions[0] := ' ±5V ' ;
NumOptions := 1 ;
end ;
function CED_GetMaxDACVolts : single ;
{ -----------------------------------------------------------------
Return the maximum positive value of the D/A output voltage range
-----------------------------------------------------------------}
begin
Result := DACVoltageRangeMax ;
end ;
procedure CED_GetSamplingIntervalRange( var MinInterval,MaxInterval : single ) ;
begin
MinInterval := 4E-6 ;
maxInterval := 1000. ;
end ;
function CED_IsLabInterfaceAvailable : boolean ;
begin
if not DeviceInitialised then CED_InitialiseBoard ;
Result := DeviceInitialised ;
end ;
procedure CED_InitialiseBoard ;
{ -------------------------------------------
Initialise CED 1401 interface hardware
-------------------------------------------}
var
RetValue : DWORD ;
Err : Integer ;
begin
DeviceInitialised := False ;
{ Open 1401 }
{ Device := U14Open(0) ;}
if Device > 0 then begin
{ Load required commands }
{ RetValue := U14Ld(Device,' ','ADCMEM,MEMDAC') ;
Err := RetValue and $FFFF ;
CheckError(Err)
if Err = U14ERR_NOERROR then DeviceInitialised := True ;
end
else CheckError(Device) ;}
end ;
end ;
procedure CED_ADCToMemory( var ADCBuf : array of integer ;
nChannels : LongInt ;
nSamples : LongInt ;
var dt : Single ;
ADCVoltageRange : Single ;
WaitForExtTrigger : Boolean ;
CircularBuffer : Boolean ) ;
var
ch : Integer ;
dt1 : single ;
NumSamples : LongInt ;
PreScale,Ticks : Word ;
CommandString : string ;
begin
if not DeviceInitialised then CED_InitialiseBoard ;
{ Kill any A/D conversions in progress }
SendCommand( 'ADCMEM,K;') ;
{ Create ADCMEM command string }
NumSamples := nChannels*nSamples ;
CommandString := format('ADCMEM,I,2,0,%d,',[NumSamples]) ;
{ Add channel list }
for ch := 0 to nChannels do
CommandString := CommandString + format('%d ',[ch]);
{ Select single-sweep or circular transfer }
if CircularBuffer then CommandString := CommandString + ',0,'
else CommandString := CommandString + ',1,' ;
{ Select immediate sweep or wait for ext. trigger pulse }
if WaitForExtTrigger then CommandString := CommandString + 'CT,'
else CommandString := CommandString + 'C,' ;
{ Set sampling clock }
dt1 := dt / nChannels ;
CED_ClockTicks( dt1, PreScale, Ticks ) ;
dt := dt * nChannels ;
CommandString := CommandString + format('%d,%d;',[PreScale,Ticks] );
SendCommand( CommandString ) ;
end ;
procedure CED_ClockTicks( var dt : single ; var PreScale,Ticks : Word ) ;
var
fTicks : single ;
begin
PreScale := 0 ;
repeat
Inc(PreScale) ;
fTicks := dt / (ClockPeriod*PreScale) ;
until fTicks < 65535. ;
Ticks := Trunc( fTicks ) ;
dt := Ticks*PreScale*ClockPeriod ;
end ;
procedure CED_StopADC ;
begin
{ Kill any A/D conversions in progress }
SendCommand( 'ADCMEM,K;') ;
end ;
procedure CED_MemoryToDAC( var DACBuf : array of integer ;
nChannels : LongInt ;
nPoints : LongInt ;
dt : Single ;
NumRepeats : LongInt ) ;
begin
end ;
procedure CED_ConvertToDACCodes( var DACBuf : Array of Integer ;
nChannels : LongInt ;
nPoints : LongInt ) ;
begin
end ;
procedure CED_StopDAC ;
begin
end ;
procedure SendCommand( const CommandString : string ) ;
{ -------------------------------
Send a command to the CED 1401
------------------------------}
var
Command : string ;
begin
Command := CommandString + chr(0) ;
{ CheckError( U14sendstring( Device, @Command[1] ) ;}
end ;
procedure CED_GetChannelOffsets( var Offsets : Array of LongInt ;
NumChannels : LongInt ) ;
{ --------------------------------------------------------
Returns the order in which analog channels are acquired
and stored in the A/D data buffers
--------------------------------------------------------}
var
ch : Integer ;
begin
for ch := 0 to NumChannels-1 do Offsets[ch] := ch ;
end ;
initialization
DeviceNumber := -1 ;
LibraryLoaded := False ;
DeviceInitialised := False ;
MinSamplingInterval := 4E-6 ;
MaxSamplingInterval := 1000. ;
DACVoltageRangeMax := 5. ;
end.
|
{
Add shadow bias to light references to avoid shadow striping.
}
unit ShadowBias;
function Process(e: IInterface): integer;
begin
if Signature(e) <> 'REFR' then
Exit;
if Signature(LinksTo(ElementBySignature(e, 'NAME'))) <> 'LIGH' then
Exit;
Add(e, 'XLIG', True);
if (GetElementNativeValues(e, 'XLIG\Shadow Depth Bias') = 0) or
(GetElementNativeValues(e, 'XLIG\Shadow Depth Bias') = 1)
then
SetElementNativeValues(e, 'XLIG\Shadow Depth Bias', 23.76);
end;
end.
|
library libCV;
{$mode objfpc}{$H+}
uses
Classes, SysUtils,
libCV.Core, libCV.Types;
// Lape Wrappers \\
procedure Lape_OpenCV_Load(const Params: PParamArray; const Result: Pointer); cdecl;
begin
PBoolean(Result)^ := OpenCV.Load(PString(Params^[0])^);
end;
procedure Lape_OpenCV_CreateImage(const Params: PParamArray; const Result: Pointer); cdecl;
begin
PPointer(Result)^ := OpenCV.CreateImage(PInt32(Params^[0])^, PInt32(Params^[1])^, PInt32(Params^[2])^, PInt32(Params^[3])^);
end;
procedure Lape_OpenCV_CreateImageEx(const Params: PParamArray; const Result: Pointer); cdecl;
begin
PPointer(Result)^ := OpenCV.CreateImage(PIntegerMatrix(Params^[0])^);
end;
procedure Lape_OpenCV_ReleaseImage(const Params: PParamArray); cdecl;
begin
OpenCV.ReleaseImage(PPointer(Params^[0])^);
end;
procedure Lape_OpenCV_MatchTemplate(const Params: PParamArray; const Result: Pointer); cdecl;
begin
PFloatMatrix(Result)^ := OpenCV.MatchTemplate(PIplImage(PPointer(Params^[0])^), PIplImage(PPointer(Params^[1])^), PIplImage(PPointer(Params^[2])^), PInt32(Params^[3])^);
end;
procedure Lape_OpenCV_MatchTemplateEx(const Params: PParamArray; const Result: Pointer); cdecl;
begin
PFloatMatrix(Result)^ := OpenCV.MatchTemplate(PIntegerMatrix(Params^[0])^, PIntegerMatrix(Params^[1])^, PIntegerMatrix(Params^[2])^, PInt32(Params^[3])^);
end;
procedure Lape_OpenCV_Max(const Params: PParamArray; const Result: Pointer); cdecl;
type
PPoint = ^TPoint;
begin
PPoint(Result)^ := PFloatMatrix(Params^[0])^.Max;
end;
// Plugin Exports \\
function GetPluginABIVersion: Int32; cdecl; export;
begin
Result := 2;
end;
function GetFunctionCount(): Int32; cdecl; export;
begin
Result := 7;
end;
function GetFunctionInfo(Index: Int32; var Addr: Pointer; var Decl: PChar): Int32; cdecl; export;
begin
case Index of
0:
begin
Addr := @Lape_OpenCV_Load;
StrPCopy(Decl, 'function cv_Load(Path: String): Boolean; native;');
end;
1:
begin
Addr := @Lape_OpenCV_CreateImage;
StrPCopy(Decl, 'function cv_CreateImage(Width, Height, Depth, Channels: Int32): Pointer; overload; native;');
end;
2:
begin
Addr := @Lape_OpenCV_CreateImageEx;
StrPCopy(Decl, 'function cv_CreateImage(constref Matrix: TIntegerMatrix): Pointer; overload; native;');
end;
3:
begin
Addr := @Lape_OpenCV_ReleaseImage;
StrPCopy(Decl, 'procedure cv_ReleaseImage(var Image: Pointer); native;');
end;
4:
begin
Addr := @Lape_OpenCV_MatchTemplate;
StrPCopy(Decl, 'function cv_MatchTemplate(Image, Template, Mask: Pointer; Method: Int32): TFloatMatrix; overload; native;');
end;
5:
begin
Addr := @Lape_OpenCV_MatchTemplateEx;
StrPCopy(Decl, 'function cv_MatchTemplate(constref Image, Template, Mask: TIntegerMatrix; Method: Int32): TFloatMatrix; overload; native;');
end;
6:
begin
Addr := @Lape_OpenCV_Max;
StrPCopy(Decl, 'function cv_Max(constref Matrix: TFloatMatrix): TPoint; native');
end;
end;
Result := Index;
end;
function GetTypeCount(): Int32; cdecl; export;
begin
Result := 2;
end;
function GetTypeInfo(Index: Int32; var Name, Def: PChar): Int32; cdecl; export;
begin
case Index of
0:
begin
StrPCopy(Name, 'TIntegerMatrix');
StrPCopy(Def, 'array of array of Int32');
end;
1:
begin
StrPCopy(Name, 'TFloatMatrix');
StrPCopy(Def, 'array of array of Single');
end;
end;
Result := Index;
end;
procedure SetPluginMemManager(NewMemoryManager: TMemoryManager); cdecl; export;
begin
SetMemoryManager(NewMemoryManager);
end;
exports GetPluginABIVersion;
exports GetFunctionCount;
exports GetFunctionInfo;
exports GetTypeCount;
exports GetTypeInfo;
exports SetPluginMemManager;
begin
end.
|
unit LUX.GPU.OpenGL.Scener;
interface //#################################################################### ■
uses System.Generics.Collections,
Winapi.OpenGL, Winapi.OpenGLext,
LUX, LUX.D2, LUX.D3, LUX.M4, LUX.Tree,
LUX.GPU.OpenGL,
LUX.GPU.OpenGL.Buffer.Unifor;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
TGLScener = class;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLNode
IGLNode = interface
['{049DB60C-9F5D-45B9-89D8-E4AC58C807E3}']
{protected}
///// アクセス
function GetScener :TGLScener;
function GetPose :TSingleM4;
procedure SetPose( const Move_:TSingleM4 );
{public}
///// プロパティ
property Scener :TGLScener read GetScener ;
property Pose :TSingleM4 read GetPose write SetPose;
///// メソッド
procedure Draw;
end;
TGLNode = class( TTreeNode<TGLNode>, IGLNode )
private
protected
_Pose :TGLUnifor<TSingleM4>;
///// アクセス
function GetScener :TGLScener;
function GetPose :TSingleM4;
procedure SetPose( const Move_:TSingleM4 ); virtual;
///// メソッド
procedure BeginDraw; virtual;
procedure DrawCore; virtual;
procedure EndDraw; virtual;
public
constructor Create; override;
destructor Destroy; override;
///// プロパティ
property Scener :TGLScener read GetScener ;
property Pose :TSingleM4 read GetPose write SetPose;
///// メソッド
procedure Draw; virtual;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLScener
IGLCamera = interface( IGLNode )
['{648646AC-975D-464E-BD83-C39EA3EB4E1E}']
{protected}
{public}
end;
IGLShaper = interface( IGLNode )
['{8045CCEA-8FC4-4D0A-A6CE-A97FF6972A7F}']
{protected}
{public}
end;
IGLScener = interface( IGLNode )
['{600C6A00-B748-4A1B-A841-A7135257ABCA}']
{protected}
{public}
end;
//-------------------------------------------------------------------------
TGLScener = class( TGLNode, IGLScener )
private
protected
public
constructor Create; override;
destructor Destroy; override;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
uses System.SysUtils, System.Classes,
LUX.GPU.OpenGL.Camera,
LUX.GPU.OpenGL.Shaper;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLNode
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TGLNode.GetScener :TGLScener;
begin
Result := RootNode as TGLScener;
end;
//------------------------------------------------------------------------------
function TGLNode.GetPose :TSingleM4;
begin
Result := _Pose[ 0 ];
end;
procedure TGLNode.SetPose( const Move_:TSingleM4 );
begin
_Pose[ 0 ] := Move_;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TGLNode.BeginDraw;
begin
_Pose.Use( 3{BinP} );
end;
procedure TGLNode.DrawCore;
begin
end;
procedure TGLNode.EndDraw;
begin
_Pose.Unuse( 3{BinP} );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TGLNode.Create;
begin
inherited;
_Pose := TGLUnifor<TSingleM4>.Create( GL_DYNAMIC_DRAW );
_Pose.Count := 1;
Pose := TSingleM4.Identify;
end;
destructor TGLNode.Destroy;
begin
_Pose.DisposeOf;
inherited;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TGLNode.Draw;
var
I :Integer;
begin
BeginDraw;
DrawCore;
EndDraw;
for I := 0 to ChildsN-1 do Childs[ I ].Draw;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLScener
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TGLScener.Create;
begin
inherited;
end;
destructor TGLScener.Destroy;
begin
inherited;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■
|
unit Data.Persistance.SQLiteConnectionFactory;
interface
uses
Aurelius.Drivers.Interfaces;
type
TSQLiteConnectionFactory = class (TInterfacedObject, IDBConnectionFactory)
public
function CreateConnection(): IDBConnection;
end;
implementation
uses
Aurelius.Drivers.SQLite,
Spring.Container;
{ TSQLiteConnectionFactory }
function TSQLiteConnectionFactory.CreateConnection: IDBConnection;
begin
Result := TSQLiteNativeConnectionAdapter.Create('../../data/demowithdelphi.sqlite');
end;
initialization
GlobalContainer.RegisterType<TSQLiteConnectionFactory>.Implements<IDBConnectionFactory>.AsSingleton;
end.
|
uses Math;
type
node = record
i: integer;
left: ^node; // pointer to left child, or nil if none
right: ^node; // pointer to right child, or nil if none
end;
pnode = ^node;
lsnode=record
i:integer;
next:^lsnode;
end;
linked_list=^lsnode;
function prepend(var p:linked_list; i:integer):linked_list;
var
t:linked_list;
begin
writeln('prepending ', i, '...');
if p = nil then begin
new(t);
t^.i:=i;
t^.next:=nil;
exit(t);
end;
new(t);
t^.i:=i;
t^.next:=p;
exit(t);
end;
procedure append(var p:linked_list; i:integer);
var
r,q:^lsnode;
begin
new(q);
q^.i:=i;
q^.next:=nil;
if p = nil then begin
p:=q;
exit;
end;
r:=p;
while r^.next <> nil do
r:=r^.next;
r^.next:=q;
end;
procedure displayList(p:linked_list);
var
t:^lsnode;
begin
t:=p;
if p = nil then write('list is empty');
while t<>nil do begin
write(t^.i, ',');
t:=t^.next;
end;
end;
function get_height(p:pnode):integer;
begin
if p = nil then exit(0);
exit(1 + max(get_height(p^.left), get_height(p^.right)));
end;
procedure display_tree_helper(p:pnode; var a:array of linked_list; level:integer);
begin
if p = nil then exit;
append(a[level], p^.i);
display_tree_helper(p^.left, a, level+1);
display_tree_helper(p^.right, a, level+1);
end;
procedure display_tree(p:pnode);
var
a:array of linked_list;
i:integer;
list:linked_list;
begin
setLength(a, get_height(p));
for i:= 0 to high(a) do begin //initialize all entries in array of linked lists
a[i]:= nil;
end;
display_tree_helper(p,a,0);
for i:=0 to high(a) do begin
displayList(a[i]);
writeln;
end;
end;
function randomTree(h:integer):pnode;
var
new_node:pnode;
begin
if h = -1 then exit(nil);
new(new_node);
new_node^.i:=random(999);
new_node^.left:=randomTree(h-1);
new_node^.right:=randomTree(h-1);
exit(new_node);
end;
function completeTree(h:integer):pnode;
function helper(curr,h:integer):pnode;
var
new_node:pnode;
begin
if curr = h then begin
new(new_node);
new_node^.i:=curr;
new_node^.left:=nil;
new_node^.right:=nil;
exit(new_node);
end
else begin
new(new_node);
new_node^.i:=curr;
new_node^.left:=helper(curr+1,h);
new_node^.right:=helper(curr+1,h);
exit(new_node);
end;
end;
begin
exit(helper(0,h));
end;
procedure destroy(p:pnode);
begin
if p = nil then exit;
destroy(p^.left);
destroy(p^.right);
dispose(p);
end;
procedure mirror(var p:pnode);
var
t:pnode;
begin
if p = nil then exit;
t:=p^.right;
p^.right:=p^.left;
p^.left:=t;
mirror(p^.left);
mirror(p^.right);
end;
function equal(q,p:pnode):boolean;
begin
if (q = nil) and (p = nil) then exit(true);
if (q = nil) and (p <> nil) then exit(false);
if (q <> nil) and (p = nil) then exit(false);
if q^.i <> p^.i then exit(false)
else exit(equal(q^.left, p^.left) and equal(q^.right, p^.right));
end;
function create_binary_search_tree(h:integer; lo,hi:integer):pnode;
var
p:pnode;
mid:integer;
begin
if h = -1 then exit(nil);
mid := (hi+lo) div 2;
new(p);
p^.i:=mid;
p^.left:=create_binary_search_tree(h-1, lo, mid);
p^.right:=create_binary_search_tree(h-1, mid, hi);
exit(p);
end;
procedure tree_walk(p:pnode);
begin
if p = nil then exit();
tree_walk(p^.left);
write(p^.i,', ');
tree_walk(p^.right);
end;
function isAncestor(p,q:pnode):boolean;
begin
if p = nil then exit(false);
if p^.i = q^.i then exit(true);
exit(isAncestor(p^.left, q) or isAncestor(p^.right, q));
end;
function arrayToTree(a:array of integer):pnode;
function helper_right(lo,hi:integer):pnode; forward;
function helper_left(lo,hi:integer):pnode;
var
mid:integer;
p:pnode;
begin
if hi-lo <= 1 then begin
new(p);
p^.i:=a[lo];
p^.left:=nil;
p^.right:=nil;
exit(p);
end;
mid:=(hi+lo) div 2;
new(p);
p^.i:=a[mid];
p^.left:=helper_left(lo, mid);
p^.right:=helper_right(mid, hi);
exit(p);
end;
function helper_right(lo,hi:integer):pnode;
var
mid:integer;
p:pnode;
begin
if hi-lo <= 1 then begin
new(p);
p^.i:=a[hi];
p^.left:=nil;
p^.right:=nil;
exit(p);
end;
mid:=(hi+lo) div 2;
new(p);
p^.i:=a[mid];
p^.left:=helper_left(lo, mid);
p^.right:=helper_right(mid, hi);
exit(p);
end;
function helper(lo,hi:integer):pnode;
var
mid:integer;
p:pnode;
begin
if hi-lo <= 0 then begin
new(p);
p^.i:=a[lo];
p^.left:=nil;
p^.right:=nil;
exit(p);
end;
mid:=(hi+lo) div 2;
new(p);
p^.i:=a[mid];
p^.left:=helper(lo, mid-1);
p^.right:=helper(mid+1, hi);
exit(p);
end;
begin
exit(helper(low(a), high(a)));
end;
var
t,p:pnode;
i:integer;
digit:integer;
a:array[0..7] of integer= (10, 14, 17, 25, 34, 51, 78, 90);
begin
p:=arrayToTree(a);
display_tree(p);
end. |
unit uDoOrderProcessing;
interface
procedure DoOrderProcessing;
implementation
uses
uOrder, uOrderValidator, uOrderEntry, uOrderProcessor;
procedure DoOrderProcessing;
var
Order: TOrder;
OrderProcessor: TOrderProcessor;
begin
Order := TOrder.Create;
try
OrderProcessor := TOrderProcessor.Create;
try
if OrderProcessor.ProcessOrder(Order) then
begin
WriteLn('Order successfully processed....');
end;
finally
OrderProcessor.Free;
end;
finally
Order.Free;
end;
end;
end.
|
namespace Sugar.Test;
interface
uses
Sugar,
Sugar.IO,
Sugar.TestFramework;
type
FileUtilsTest = public class (Testcase)
private
const NAME: String = "sugar.testcase.txt";
private
FileName: String;
CopyName: String;
public
method Setup; override;
method TearDown; override;
method CopyTest;
method Create;
method Delete;
method Exists;
method Move;
method AppendText;
method AppendBytes;
method AppendBinary;
method ReadText;
method ReadBytes;
method ReadBinary;
method WriteBytes;
method WriteText;
method WriteBinary;
end;
implementation
method FileUtilsTest.Setup;
begin
var aFile := Folder.UserLocal.CreateFile(NAME, false);
FileUtils.WriteText(aFile.Path, "");
FileName := aFile.Path;
CopyName := FileName+".copy";
end;
method FileUtilsTest.TearDown;
begin
if FileUtils.Exists(FileName) then
FileUtils.Delete(FileName);
if FileUtils.Exists(CopyName) then
FileUtils.Delete(CopyName);
end;
method FileUtilsTest.CopyTest;
begin
Assert.CheckBool(true, FileUtils.Exists(FileName));
Assert.CheckBool(false, FileUtils.Exists(CopyName));
FileUtils.Copy(FileName, CopyName);
Assert.CheckBool(true, FileUtils.Exists(FileName));
Assert.CheckBool(true, FileUtils.Exists(CopyName));
Assert.IsException(->FileUtils.Copy(FileName, CopyName));
Assert.IsException(->FileUtils.Copy(nil, CopyName));
Assert.IsException(->FileUtils.Copy(FileName, nil));
Assert.IsException(->FileUtils.Copy(FileName+"doesnotexists", CopyName));
end;
method FileUtilsTest.Create;
begin
Assert.CheckBool(false, FileUtils.Exists(CopyName));
FileUtils.Create(CopyName);
Assert.CheckBool(true, FileUtils.Exists(CopyName));
Assert.IsException(->FileUtils.Create(CopyName));
Assert.IsException(->FileUtils.Create(nil));
end;
method FileUtilsTest.Delete;
begin
Assert.CheckBool(false, FileUtils.Exists(CopyName));
Assert.IsException(->FileUtils.Delete(CopyName));
Assert.IsException(->FileUtils.Delete(nil));
Assert.CheckBool(true, FileUtils.Exists(FileName));
FileUtils.Delete(FileName);
Assert.CheckBool(false, FileUtils.Exists(FileName));
end;
method FileUtilsTest.Exists;
begin
Assert.CheckBool(true, FileUtils.Exists(FileName));
Assert.CheckBool(false, FileUtils.Exists(CopyName));
FileUtils.Create(CopyName);
Assert.CheckBool(true, FileUtils.Exists(CopyName));
FileUtils.Delete(FileName);
Assert.CheckBool(false, FileUtils.Exists(FileName));
end;
method FileUtilsTest.Move;
begin
Assert.CheckBool(true, FileUtils.Exists(FileName));
Assert.CheckBool(false, FileUtils.Exists(CopyName));
FileUtils.Move(FileName, CopyName);
Assert.CheckBool(false, FileUtils.Exists(FileName));
Assert.CheckBool(true, FileUtils.Exists(CopyName));
Assert.IsException(->FileUtils.Move(CopyName, CopyName));
Assert.IsException(->FileUtils.Move(nil, CopyName));
Assert.IsException(->FileUtils.Move(FileName, nil));
Assert.IsException(->FileUtils.Move(CopyName+"doesnotexists", FileName));
end;
method FileUtilsTest.AppendText;
begin
Assert.CheckString("", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.AppendText(FileName, "Hello");
Assert.CheckString("Hello", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.AppendText(FileName, " World");
Assert.CheckString("Hello World", FileUtils.ReadText(FileName, Encoding.UTF8));
Assert.IsException(->FileUtils.AppendText(CopyName, ""));
Assert.IsException(->FileUtils.AppendText(FileName, nil));
Assert.IsException(->FileUtils.AppendText(nil, ""));
end;
method FileUtilsTest.AppendBytes;
begin
Assert.CheckString("", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.AppendBytes(FileName, String("Hello").ToByteArray);
Assert.CheckString("Hello", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.AppendBytes(FileName, String(" World").ToByteArray);
Assert.CheckString("Hello World", FileUtils.ReadText(FileName, Encoding.UTF8));
Assert.IsException(->FileUtils.AppendBytes(CopyName, []));
Assert.IsException(->FileUtils.AppendBytes(FileName, nil));
Assert.IsException(->FileUtils.AppendBytes(nil, []));
end;
method FileUtilsTest.AppendBinary;
begin
Assert.CheckString("", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.AppendBinary(FileName, new Binary(String("Hello").ToByteArray));
Assert.CheckString("Hello", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.AppendBinary(FileName, new Binary(String(" World").ToByteArray));
Assert.CheckString("Hello World", FileUtils.ReadText(FileName, Encoding.UTF8));
Assert.IsException(->FileUtils.AppendBinary(CopyName, new Binary));
Assert.IsException(->FileUtils.AppendBinary(FileName, nil));
Assert.IsException(->FileUtils.AppendBinary(nil, new Binary));
end;
method FileUtilsTest.ReadText;
begin
Assert.CheckString("", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.WriteText(FileName, "Hello");
Assert.CheckString("Hello", FileUtils.ReadText(FileName, Encoding.UTF8));
Assert.IsException(->FileUtils.ReadText(nil, Encoding.UTF8));
Assert.IsException(->FileUtils.ReadText(CopyName, Encoding.UTF8));
end;
method FileUtilsTest.ReadBytes;
begin
Assert.CheckInt(0, length(FileUtils.ReadBytes(FileName)));
var Expected: array of Byte := [4, 8, 15, 16, 23, 42];
FileUtils.WriteBytes(FileName, Expected);
var Actual := FileUtils.ReadBytes(FileName);
Assert.CheckBool(true, Actual <> nil);
Assert.CheckInt(length(Expected), length(Actual));
for i: Int32 := 0 to length(Expected) - 1 do
Assert.CheckInt(Expected[i], Actual[i]);
Assert.IsException(->FileUtils.ReadBytes(nil));
Assert.IsException(->FileUtils.ReadBytes(CopyName));
end;
method FileUtilsTest.ReadBinary;
begin
var Actual: Binary := FileUtils.ReadBinary(FileName);
Assert.IsNotNull(Actual);
Assert.CheckInt(0, Actual.Length);
var Expected: array of Byte := [4, 8, 15, 16, 23, 42];
FileUtils.WriteBytes(FileName, Expected);
Actual := FileUtils.ReadBinary(FileName);
Assert.IsNotNull(Actual);
Assert.CheckInt(length(Expected), Actual.Length);
var Temp := Actual.ToArray;
for i: Int32 := 0 to length(Expected) - 1 do
Assert.CheckInt(Expected[i], Temp[i]);
Assert.IsException(->FileUtils.ReadBinary(nil));
Assert.IsException(->FileUtils.ReadBinary(CopyName));
end;
method FileUtilsTest.WriteBytes;
begin
Assert.CheckString("", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.WriteBytes(FileName, String("Hello").ToByteArray);
Assert.CheckString("Hello", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.WriteBytes(FileName, String("World").ToByteArray);
Assert.CheckString("World", FileUtils.ReadText(FileName, Encoding.UTF8));
Assert.IsException(->FileUtils.WriteBytes(FileName, nil));
Assert.IsException(->FileUtils.WriteBytes(nil, []));
Assert.IsException(->FileUtils.WriteBytes(CopyName, []));
end;
method FileUtilsTest.WriteText;
begin
Assert.CheckString("", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.WriteText(FileName, "Hello");
Assert.CheckString("Hello", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.WriteText(FileName, "World");
Assert.CheckString("World", FileUtils.ReadText(FileName, Encoding.UTF8));
Assert.IsException(->FileUtils.WriteText(FileName, nil));
Assert.IsException(->FileUtils.WriteText(nil, ""));
Assert.IsException(->FileUtils.WriteText(CopyName, ""));
end;
method FileUtilsTest.WriteBinary;
begin
Assert.CheckString("", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.WriteBinary(FileName, new Binary(String("Hello").ToByteArray));
Assert.CheckString("Hello", FileUtils.ReadText(FileName, Encoding.UTF8));
FileUtils.WriteBinary(FileName, new Binary(String("World").ToByteArray));
Assert.CheckString("World", FileUtils.ReadText(FileName, Encoding.UTF8));
Assert.IsException(->FileUtils.WriteBinary(FileName, nil));
Assert.IsException(->FileUtils.WriteBinary(nil, new Binary));
Assert.IsException(->FileUtils.WriteBinary(CopyName, new Binary));
end;
end. |
unit UCommPanels;
interface
uses Windows, UxlClasses, UxlList, UxlDialog, UxlStdCtrls, UxlListView, UxlDragControl;
type
TSelectPanel = class
private
FListView: TxlListView;
FCb_Up, FCb_Down: TxlButton;
FChk_SelectAll: TxlCheckBox;
procedure f_OnItemSelEvent (index: integer; sel: boolean);
procedure f_MoveItem (Sender: TObject);
procedure f_SelectAll (Sender: TObject);
procedure f_OnDropEvent (o_dragsource: IDragSource; hidxTarget: integer; b_copy: boolean);
public
constructor Create (AOwner: TxlDialogSuper; h_listview, h_button_up, h_button_down, h_checkbox_selall: HWND; const s_coltitle: widestring = '');
Destructor Destroy (); override;
procedure Initialize (o_sellist: TxlIntList; o_alllist: TxlStrList);
procedure Retrieve (o_sellist: TxlIntList; o_alllist: TxlIntList = nil);
end;
TFontColorPanel = class
private
FOwner: TxlDialogSuper;
FDemo: TxlStaticText;
FCbSetFont, FCbSetColor: TxlButton;
FOnFontChange: TNotifyEvent;
FOnColorChange: TNotifyEvent;
procedure SetFont (value: TxlFont);
procedure SetColor (value: TColor);
function GetFont (): TxlFont;
function GetColor (): TColor;
procedure f_OnSetFont (Sender: TObject);
procedure f_OnSetColor (Sender: TObject);
public
constructor Create (AOwner: TxlDialogSuper; h_demo, h_setfont, h_setcolor: HWND);
Destructor Destroy (); override;
property Font: TxlFont read GetFont write SetFont;
property Color: TColor read GetColor write SetColor;
property OnFontChange: TNotifyEvent read FOnFontChange write FOnFontChange;
property OnColorChange: TNotifyEvent read FOnColorChange write FOnColorChange;
end;
implementation
uses CommCtrl, UxlWinControl, UxlFunctions, UxlCommDlgs;
constructor TSelectPanel.Create (AOwner: TxlDialogSuper; h_listview, h_button_up, h_button_down, h_checkbox_selall: HWND; const s_coltitle: widestring = '');
var lvs: TListViewStyle;
begin
InitCommonControl (ICC_LISTVIEW_CLASSES);
with lvs do
begin
ViewStyle := lvsReport;
MultiSelect := false;
FullRowSelect := false;
GridLines := false;
EditLabels := false;
ShowHeader := true;
HeaderDragDrop := false;
CheckBoxes := true;
end;
FListView := TxlListView.Create (AOwner, h_listview);
with FListView do
begin
CanDrag := true;
CanDrop := true;
// SetWndStyle (LVS_SHOWSELALWAYS, true);
SetStyle (lvs);
OnDropEvent := f_OnDropEvent;
Items.OnSelect := f_OnItemSelEvent;
Cols.Add (IfThen(s_coltitle <> '', s_coltitle, '可选项目'), Pos.Width - 20, alLeft);
end;
FCb_Up := TxlButton.Create (AOwner, h_button_up);
FCb_Up.OnClick := f_MoveItem;
FCb_Down := TxlButton.Create (AOwner, h_button_down);
FCb_Down.OnClick := f_MoveItem;
FChk_SelectAll := TxlCheckBox.Create (AOwner, h_checkbox_selall);
FChk_SelectAll.OnClick := f_SelectAll;
end;
Destructor TSelectPanel.Destroy ();
begin
// FListView.free; // 会引起再次进入对话框时列表拖放无响应。原因不明。
FCb_Up.free;
FCb_Down.free;
FChk_SelectAll.free;
inherited;
end;
procedure TSelectPanel.Initialize (o_sellist: TxlIntList; o_alllist: TxlStrList);
var o_item: TListViewItem;
b_allsel: boolean;
i: integer;
begin
o_item.image := 0;
o_item.state := 0;
FListView.Items.Clear;
for i := o_sellist.Low to o_sellist.High do
begin
o_item.data := o_sellist[i];
o_item.text := o_alllist.ItemsByIndex[o_sellist[i]];
o_item.checked := true;
FListView.Items.Add (o_item);
b_allsel := true;
end;
for i := o_alllist.Low to o_alllist.High do
begin
if o_sellist.ItemExists(o_alllist.Indexes[i]) then continue;
o_item.data := o_alllist.Indexes[i];
o_item.text := o_alllist[i];
o_item.checked := false;
FListView.Items.Add (o_item);
b_allsel := false;
end;
Fchk_selectall.Checked := b_allsel;
end;
procedure TSelectPanel.Retrieve (o_sellist: TxlIntList; o_alllist: TxlIntList = nil);
var i: integer;
begin
o_sellist.Clear;
if o_alllist <> nil then o_alllist.Clear;
with FListView.Items do
for i := Low to High do
begin
if o_alllist <> nil then
o_alllist.Add (Items[i].data);
if Items[i].checked then
o_sellist.Add (Items[i].data);
end;
end;
procedure TSelectPanel.f_OnItemSelEvent (index: integer; sel: boolean);
begin
FCb_up.Enabled := (index > FListView.Items.Low);
Fcb_down.Enabled := (index < FListView.Items.High);
end;
procedure TSelectPanel.f_MoveItem (Sender: TObject);
var i, j, i_dir: integer;
begin
if Sender = FCb_Up then
i_dir := -1
else
i_dir := 1;
with FListView.Items do
begin
i := SelIndex;
j := i + i_dir;
if Move (i, j) then
Select (j);
end;
end;
procedure TSelectPanel.f_SelectAll (Sender: TObject);
begin
FListView.Items.CheckAll (FChk_SelectAll.Checked);
end;
procedure TSelectPanel.f_OnDropEvent (o_dragsource: IDragSource; hidxTarget: integer; b_copy: boolean);
begin
with FListView.Items do
begin
if Move (SelIndex, hidxTarget) then
Select (hidxTarget);
end;
end;
//----------------------
constructor TFontColorPanel.Create (AOwner: TxlDialogSuper; h_demo, h_setfont, h_setcolor: HWND);
begin
FOwner := AOwner;
FDemo := TxlStaticText.Create (AOwner, h_demo);
if h_setfont <> 0 then
begin
FCbSetFont := TxlButton.Create (AOwner, h_setfont);
FCbSetFont.OnClick := f_OnsetFont;
end;
if h_setcolor <> 0 then
begin
FCbSetColor := TxlButton.Create (AOwner, h_setcolor);
FCbSetColor.OnClick := f_OnSetColor;
end;
end;
Destructor TFontColorPanel.Destroy ();
begin
FDemo.Free;
FCbSetFont.Free;
FCbSetColor.Free;
inherited;
end;
procedure TFontColorPanel.SetFont (value: TxlFont);
begin
FDemo.Text := value.name + ', ' + IntToStr (value.size);
FDemo.Font.assign (value);
end;
procedure TFontColorPanel.SetColor (value: TColor);
begin
FDemo.Color := value;
end;
function TFontColorPanel.GetFont (): TxlFont;
begin
result := FDemo.Font;
end;
function TFontColorPanel.GetColor (): TColor;
begin
result := FDemo.Color;
end;
procedure TFontColorPanel.f_OnSetFont (Sender: TObject);
var o_fontbox: TxlFontDialog;
begin
o_fontbox := TxlFontDialog.Create (FOwner);
o_fontbox.Font := Font;
if o_fontbox.Execute() then
begin
Font := o_fontbox.Font;
if assigned (FOnFontChange) then
FOnFontChange (self);
end;
o_fontbox.free;
end;
procedure TFontColorPanel.f_OnSetColor (Sender: TObject);
var o_box: TxlColorDialog;
begin
o_box := TxlColorDialog.create (FOwner);
o_box.Color := Color;
if o_box.Execute () then
begin
Color := o_box.Color;
if assigned (FOnColorChange) then
FOnColorChange (self);
end;
o_box.Free;
end;
end.
//Tip_Box DIALOG 6, 15, 120, 12
//STYLE DS_SETFONT | WS_VISIBLE | WS_BORDER | WS_POPUP
//FONT 9, "Arial"
//BEGIN
// CONTROL "", st_tip, WC_STATIC, NOT WS_GROUP | SS_LEFTNOWORDWRAP, 0, 0, 120, 12
//END
//type
// _TTipBox = class (TxlDialogML)
// protected
// procedure OnInitialize (); override;
// procedure SetTip (const s_text: widestring; i_width: cardinal = 0);
// end;
//
// TTipBox = class
// private
// FTipBox: _TTipBox;
// public
// constructor Create (AOwner: TxlWinControl; const s_text: widestring; i_width: cardinal = 0);
// destructor Destroy (); override;
// end;
//----------------------
//procedure _TTipBox.OnInitialize ();
//begin
// SetTemplate (Tip_Box);
//end;
//
//procedure _TTipBox.SetTip (const s_text: widestring; i_width: cardinal = 0);
//begin
// if i_width <= 0 then i_width := length(s_text) * 14;
//
// Move (-1, -1, i_Width, -1);
//
// with TxlStaticText.create(self, ItemHandle[st_tip]) do
// begin
// Text := s_text;
// Move (0, 0, i_Width, self.Pos.Height);
// Color := rgb(255, 255, 128);
// free;
// end;
//end;
//
//constructor TTipBox.Create (AOwner: TxlWinControl; const s_text: widestring; i_width: cardinal = 0);
//begin
// FTipBox := _TTipBox.Create (AOwner);
// with FTipBox do
// begin
// Open (false);
// SetTip (s_text, i_width);
// Show;
// end;
//end;
//
//destructor TTipBox.Destroy ();
//begin
// FTipBox.Close;
// FTipBox.Free;
//end;
|
unit fMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Memo.Types,
FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses uReleaseClientLib;
procedure TForm1.Button1Click(Sender: TObject);
begin
TReleaseClientLib.checkNewReleaseURL(TReleaseClientLib.getProgramName,
TReleaseClientLib.getProgramDate,
procedure(DownloadURL: string)
begin
Memo1.Lines.Add('Nouvelle version dispo. Télécharger sur ' + DownloadURL);
end,
procedure
begin
Memo1.Lines.Add('Pas de nouvelle version.');
end,
procedure(statuscode: integer; statustext: string)
begin
Memo1.Lines.Add('Problème réseau : ' + statuscode.ToString);
Memo1.Lines.Add('=> ' + statustext);
end);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Button1.setfocus;
Memo1.Lines.clear;
Memo1.Lines.Add('Programme: ' + TReleaseClientLib.getProgramName);
Memo1.Lines.Add('Plateforme: ' + TReleaseClientLib.getPlateformeName);
Memo1.Lines.Add('Version: ' + TReleaseClientLib.getProgramDate);
end;
initialization
TReleaseClientLib.setServeurURL('http://127.0.0.7:8080');
end.
|
(*
* Copyright (c) 2008-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 DeHL.Defines.inc}
unit DeHL.Exceptions;
interface
uses SysUtils;
type
/// <summary>Represents all exceptions that are thrown when the type system is involved.</summary>
ETypeException = class(Exception);
/// <summary>Represents all exceptions that are thrown when the type extension system is involved.</summary>
ETypeExtensionException = class(Exception);
/// <summary>Thrown when the type conversion is impossible.</summary>
ETypeConversionNotSupported = class(ETypeException);
/// <summary>Thrown when a Variant array cannot be created from a dynamic array of a given type.</summary>
ETypeIncompatibleWithVariantArray = class(ETypeException);
/// <summary>Thrown when an attempt to call an unsupported default parameterless constructor is made.</summary>
EDefaultConstructorNotAllowed = class(Exception);
/// <summary>Thrown when attempting to access a <c>NULL</c> nullable value.</summary>
ENullValueException = class(Exception);
/// <summary>Thrown when attempting to access a <c>NULL</c> box value.</summary>
EEmptyBoxException = class(Exception);
/// <summary>Thrown when a required argument is <c>nil</c> (but should not be).</summary>
ENilArgumentException = class(EArgumentException);
/// <summary>Thrown when a given argument combination specifies a smaller range than required.</summary>
/// <remarks>This exception is usually used by collections. The exception is thrown when there is not enough
/// space in an array to copy the values to.</remarks>
EArgumentOutOfSpaceException = class(EArgumentOutOfRangeException);
/// <summary>Thrown when attempting to compare two objects of different classes.</summary>
ENotSameTypeArgumentException = class(EArgumentException);
/// <summary>Thrown when a <see cref="DeHL.Base|TRefCountedObject">DeHL.Base.TRefCountedObject</see> tries to keep itself alive.</summary>
ECannotSelfReferenceException = class(Exception);
/// <summary>Represents all exceptions that are thrown when collections are involved.</summary>
ECollectionException = class(Exception);
/// <summary>Thrown when an enumerator detects that the enumerated collection was changed.</summary>
ECollectionChangedException = class(ECollectionException);
/// <summary>Thrown when a collection was identified to be empty (and it shouldn't have been).</summary>
ECollectionEmptyException = class(ECollectionException);
/// <summary>Thrown when a collection was expected to have only one exception.</summary>
ECollectionNotOneException = class(ECollectionException);
/// <summary>Thrown when a predicated applied to a collection generates a void collection.</summary>
ECollectionFilteredEmptyException = class(ECollectionException);
/// <summary>Thrown when trying to add a key-value pair into a collection that already has that key
/// in it.</summary>
EDuplicateKeyException = class(ECollectionException);
/// <summary>Thrown when the key (of a pair) is not found in the collection.</summary>
EKeyNotFoundException = class(ECollectionException);
/// <summary>Thrown when trying to operate on an element that is not a part of the parent collection.</summary>
EElementNotPartOfCollection = class(ECollectionException);
/// <summary>Thrown when trying to add an element to a collection that already has it.</summary>
EElementAlreadyInACollection = class(ECollectionException);
/// <summary>Thrown when trying to set the element to a collection's occupied position.</summary>
EPositionOccupiedException = class(ECollectionException);
/// <summary>Thrown when an argument is not in the desired format.</summary>
EArgumentFormatException = class(Exception);
/// <summary>Represents all exceptions that are thrown when the serialization system is involved.</summary>
ESerializationException = class(Exception);
/// <summary>Thrown when the value of a given field cannot be deserialized.</summary>
EFieldMissingException = class(ESerializationException);
/// <summary>Thrown when a value cannot be properly serialized.</summary>
ESerializationValueException = class(ESerializationException);
/// <summary>Thrown when reference serialization errors occur.</summary>
ESerializationReferenceException = class(ESerializationException);
/// <summary>A static class that offers methods for throwing DeHL exceptions.</summary>
/// <remarks><see cref="DeHL.Exceptions|ExceptionHelper">DeHL.Exceptions.ExceptionHelper</see> is used internally in DeHL to
/// throw all kinds of exceptions. This class is useful because it separates the exceptions
/// (including the messages) from the rest of the code.</remarks>
ExceptionHelper = class sealed
public
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_NoDefaultTypeError(const TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_CustomTypeHasNoRTTI();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_RuntimeTypeRestrictionFailed(const TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_CustomTypeAlreadyRegistered(const TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_CustomTypeNotYetRegistered(const TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ConversionNotSupported(const ToTypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_TypeIncompatibleWithVariantArray(const TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_MissingFieldError(const TypeName, FieldName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_Unserializable(const EntityName, TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_MarkedUnserializable(const EntityName, TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_WrongOrMissingRTTI(const EntityName, TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_InvalidSerializationIdentifier(const IdName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ValueSerializationFailed(const TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_UnexpectedDeserializationEntity(const EntityName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_InvalidDeserializationValue(const EntityName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_BinaryValueSizeMismatch(const EntityName, TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_UnexpectedReferencedType(const EntityName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ExpectedReferencedType(const EntityName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_BadSerializationContext(const EntityName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_MissingCompositeType();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_InvalidArray(const EntityName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_DeserializationReadError(const EntityName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ReferencePointNotYetDeserialized(const EntityName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_RefRegisteredOrIsNil(const EntityName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ClassNotFound(const EntityName, ClassName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_NullValueRequested();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_TheBoxIsEmpty();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_TypeExtensionAlreadyRegistered(const TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_TypeExtensionNotYetRegistered(const TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_InvalidFloatParam(const ArgName: string);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_NeedsRounding();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_OverflowError();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_DivByZeroError();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_NoMathExtensionForType(const TypeName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_DefaultConstructorNotAllowedError();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_CannotSelfReferenceError();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ArgumentNotSameTypeError(const ArgName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ArgumentNilError(const ArgName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ArgumentOutOfRangeError(const ArgName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ArgumentOutOfSpaceError(const ArgName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_InvalidArgumentFormatError(const ArgName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ArgumentConverError(const ArgName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_CollectionChangedError();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_CollectionEmptyError();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_CollectionHasMoreThanOneElement();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_CollectionHasNoFilteredElements();
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_DuplicateKeyError(const ArgName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_KeyNotFoundError(const ArgName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ElementNotPartOfCollectionError(const ArgName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_ElementAlreadyPartOfCollectionError(const ArgName: String);
/// <summary>Internal method. Do not call directly!</summary>
/// <remarks>The interface of this function may change in the future.</remarks>
class procedure Throw_PositionOccupiedError();
end;
implementation
uses
DeHL.StrConsts;
{ ExceptionHelper }
class procedure ExceptionHelper.Throw_ArgumentNilError(const ArgName: String);
begin
raise ENilArgumentException.CreateFmt(SNilArgument, [ArgName]);
end;
class procedure ExceptionHelper.Throw_ArgumentNotSameTypeError(const ArgName: String);
begin
raise ENotSameTypeArgumentException.CreateFmt(SNotSameTypeArgument, [ArgName]);
end;
class procedure ExceptionHelper.Throw_ArgumentOutOfRangeError(const ArgName: String);
begin
raise EArgumentOutOfRangeException.CreateFmt(SOutOfRangeArgument, [ArgName]);
end;
class procedure ExceptionHelper.Throw_ArgumentOutOfSpaceError(const ArgName: String);
begin
raise EArgumentOutOfSpaceException.CreateFmt(SOutOfSpaceArgument, [ArgName]);
end;
class procedure ExceptionHelper.Throw_BadSerializationContext(const EntityName: String);
begin
raise ESerializationException.CreateFmt(SBadSerializationContext, [EntityName]);
end;
class procedure ExceptionHelper.Throw_CannotSelfReferenceError;
begin
raise ECannotSelfReferenceException.Create(SCannotSelfReference);
end;
class procedure ExceptionHelper.Throw_ClassNotFound(const EntityName, ClassName: String);
begin
raise ESerializationReferenceException.CreateFmt(SClassNotFound, [EntityName, ClassName]);
end;
class procedure ExceptionHelper.Throw_CollectionChangedError;
begin
raise ECollectionChangedException.Create(SParentCollectionChanged);
end;
class procedure ExceptionHelper.Throw_CollectionEmptyError;
begin
raise ECollectionEmptyException.Create(SEmptyCollection);
end;
class procedure ExceptionHelper.Throw_CollectionHasMoreThanOneElement;
begin
raise ECollectionNotOneException.Create(SCollectionHasMoreThanOneElements);
end;
class procedure ExceptionHelper.Throw_CollectionHasNoFilteredElements;
begin
raise ECollectionFilteredEmptyException.Create(SCollectionHasNoFilteredElements);
end;
class procedure ExceptionHelper.Throw_ConversionNotSupported(const ToTypeName: String);
begin
raise ETypeConversionNotSupported.CreateFmt(STypeConversionNotSupported, [ToTypeName]);
end;
class procedure ExceptionHelper.Throw_CustomTypeAlreadyRegistered(const TypeName: String);
begin
raise ETypeException.CreateFmt(SCustomTypeAlreadyRegistered, [TypeName]);
end;
class procedure ExceptionHelper.Throw_CustomTypeHasNoRTTI;
begin
raise ETypeException.Create(SCustomTypeHasNoRTTI);
end;
class procedure ExceptionHelper.Throw_CustomTypeNotYetRegistered(const TypeName: String);
begin
raise ETypeException.CreateFmt(SCustomTypeNotYetRegistered, [TypeName]);
end;
class procedure ExceptionHelper.Throw_ArgumentConverError(const ArgName: String);
begin
raise EConvertError.CreateFmt(SConvertProblemArgument, [ArgName]);
end;
class procedure ExceptionHelper.Throw_DefaultConstructorNotAllowedError;
begin
raise EDefaultConstructorNotAllowed.Create(SDefaultParameterlessCtorNotAllowed);
end;
class procedure ExceptionHelper.Throw_DeserializationReadError(const EntityName: String);
begin
raise ESerializationException.CreateFmt(SDeserializationReadError, [EntityName]);
end;
class procedure ExceptionHelper.Throw_DivByZeroError();
begin
raise EDivByZero.Create(SDivisionByZero);
end;
class procedure ExceptionHelper.Throw_DuplicateKeyError(const ArgName: String);
begin
raise EDuplicateKeyException.CreateFmt(SDuplicateKey, [ArgName]);
end;
class procedure ExceptionHelper.Throw_ElementAlreadyPartOfCollectionError(const ArgName: String);
begin
raise EElementAlreadyInACollection.CreateFmt(SElementAlreadyInAnotherCollection, [ArgName]);
end;
class procedure ExceptionHelper.Throw_ElementNotPartOfCollectionError(const ArgName: String);
begin
raise EElementNotPartOfCollection.CreateFmt(SElementNotInCollection, [ArgName]);
end;
class procedure ExceptionHelper.Throw_ExpectedReferencedType(const EntityName: String);
begin
raise ESerializationException.CreateFmt(SExpectedReferencedType, [EntityName]);
end;
class procedure ExceptionHelper.Throw_InvalidArgumentFormatError(const ArgName: String);
begin
raise EArgumentFormatException.CreateFmt(SBrokenFormatArgument, [ArgName]);
end;
class procedure ExceptionHelper.Throw_InvalidArray(const EntityName: String);
begin
raise ESerializationException.CreateFmt(SInvalidArray, [EntityName]);
end;
class procedure ExceptionHelper.Throw_InvalidDeserializationValue(const EntityName: String);
begin
raise ESerializationValueException.CreateFmt(SInvalidDeserializationValue, [EntityName]);
end;
class procedure ExceptionHelper.Throw_InvalidFloatParam(const ArgName: string);
begin
raise EInvalidOp.CreateFmt(SInvalidFloatParam, [ArgName]);
end;
class procedure ExceptionHelper.Throw_InvalidSerializationIdentifier(const IdName: String);
begin
raise ESerializationException.CreateFmt(SInvalidSerializationIdentifier, [IdName]);
end;
class procedure ExceptionHelper.Throw_KeyNotFoundError(const ArgName: String);
begin
raise EKeyNotFoundException.CreateFmt(SKeyNotFound, [ArgName]);
end;
class procedure ExceptionHelper.Throw_MissingCompositeType;
begin
raise EFieldMissingException.Create(SMissingCompositeType);
end;
class procedure ExceptionHelper.Throw_MissingFieldError(const TypeName, FieldName: String);
begin
raise EFieldMissingException.CreateFmt(SNoSuchField, [TypeName, FieldName]);
end;
class procedure ExceptionHelper.Throw_NeedsRounding;
begin
raise EInvalidOp.Create(SNeedsRounding);
end;
class procedure ExceptionHelper.Throw_NoDefaultTypeError(const TypeName: String);
begin
raise ETypeException.CreateFmt(SNoDefaultType, [TypeName]);
end;
class procedure ExceptionHelper.Throw_UnexpectedDeserializationEntity(const EntityName: String);
begin
raise ESerializationValueException.CreateFmt(SUnexpectedDeserializationEntity, [EntityName]);
end;
class procedure ExceptionHelper.Throw_NoMathExtensionForType(const TypeName: String);
begin
raise ETypeExtensionException.CreateFmt(SNoMathExtensionForType, [TypeName]);
end;
class procedure ExceptionHelper.Throw_MarkedUnserializable(const EntityName, TypeName: String);
begin
raise ESerializationException.CreateFmt(SMarkedUnserializable, [EntityName, TypeName]);
end;
class procedure ExceptionHelper.Throw_NullValueRequested;
begin
raise ENullValueException.Create(SNullValueRequested);
end;
class procedure ExceptionHelper.Throw_OverflowError();
begin
raise EOverflow.Create(SArithmeticOverflow);
end;
class procedure ExceptionHelper.Throw_PositionOccupiedError;
begin
raise EPositionOccupiedException.Create(SRequestedPositionIsOccupied);
end;
class procedure ExceptionHelper.Throw_ReferencePointNotYetDeserialized(const EntityName: String);
begin
raise ESerializationReferenceException.CreateFmt(SReferencePointNotYetDeserialized, [EntityName]);
end;
class procedure ExceptionHelper.Throw_RefRegisteredOrIsNil(const EntityName: String);
begin
raise ESerializationReferenceException.CreateFmt(SRefRegisteredOrIsNil, [EntityName]);
end;
class procedure ExceptionHelper.Throw_RuntimeTypeRestrictionFailed(const TypeName: String);
begin
raise ETypeException.CreateFmt(SRuntimeTypeRestrictionFailed, [TypeName]);
end;
class procedure ExceptionHelper.Throw_TheBoxIsEmpty;
begin
raise EEmptyBoxException.Create(STheBoxIsEmpty);
end;
class procedure ExceptionHelper.Throw_TypeExtensionAlreadyRegistered(const TypeName: String);
begin
raise ETypeExtensionException.CreateFmt(SExtensionTypeAlreadyRegistered, [TypeName]);
end;
class procedure ExceptionHelper.Throw_TypeExtensionNotYetRegistered(const TypeName: String);
begin
raise ETypeExtensionException.CreateFmt(SExtensionTypeNotYetRegistered, [TypeName]);
end;
class procedure ExceptionHelper.Throw_TypeIncompatibleWithVariantArray(const TypeName: String);
begin
raise ETypeIncompatibleWithVariantArray.CreateFmt(STypeIncompatibleWithVariantArray, [TypeName]);
end;
class procedure ExceptionHelper.Throw_UnexpectedReferencedType(const EntityName: String);
begin
raise ESerializationException.CreateFmt(SUnexpectedReferencedType, [EntityName]);
end;
class procedure ExceptionHelper.Throw_Unserializable(const EntityName, TypeName: String);
begin
raise ESerializationException.CreateFmt(SUnserializable, [EntityName, TypeName]);
end;
class procedure ExceptionHelper.Throw_ValueSerializationFailed(const TypeName: String);
begin
raise ESerializationException.CreateFmt(SValueSerializationFailed, [TypeName]);
end;
class procedure ExceptionHelper.Throw_WrongOrMissingRTTI(const EntityName, TypeName: String);
begin
raise ESerializationException.CreateFmt(SWrongOrMissingRTTI, [EntityName, TypeName]);
end;
class procedure ExceptionHelper.Throw_BinaryValueSizeMismatch(const EntityName, TypeName: String);
begin
raise ESerializationValueException.CreateFmt(SBinaryValueSizeMismatch, [EntityName, TypeName]);
end;
end.
|
unit GenesisUnit;
interface
uses
Classes, Types, SysUtils, Windows, Generics.Collections,GenesisClass,
GenesisConsts, GenSourceObject,
SiAuto, SmartInspect;
type
TUnitState = (usCompiling, usFinished);
TGenesisUnit = class(TGenSourceObject)
private
FGenesisUnitName: String;
FSourceCode: string;
FPosition: Integer;
FUnitState: TUnitState;
procedure BuildMethodBindFunctions();
procedure BuildConstructor();
procedure BuildDestructor();
function GetEOF: Boolean;
procedure SetSourceCode(const Value: string);
public
constructor Create(); reintroduce;
destructor Destroy(); override;
property GenesisUnitName: String read FGenesisUnitName write FGenesisUnitName;
procedure Finalize();
procedure ExpectChar(AChar: Char; AMessage: string = '');
procedure ExpectCharSet(ACharSet: TAnsiCharSet; AMessage: string = '');
procedure ExpectClassType(AClass: string; AMessage: string = '');
procedure ExpectClassAccessSpecifier(AWord: string);
procedure AddInclude(AFile: string);
procedure AddIncludeAtTop(AFile: string);
procedure DropNextVisibleChar();
procedure InsertSource(ASource: string; APosition: Integer);
function GetNextWord(): string;
function GetNextIdentifier(): string;
function GetNextVisibleChar(): Char;
function IsNextVisibleChar(AChar: Char): Boolean;
function IsNextVisibleCharSet(ASet: TAnsiCharSet): Boolean;
function GetLiteCSource(): String; override;
function IsClass(AWord: String): Boolean;
function GetCharsInRow(AChar: Char): string;
function GetCurrentLine(): Integer;
function GetCurrentPosInLine(): Integer;
function GetClassByName(AName: string): TGenesisClass;
function GetMethodByName(AName: string): TGenMethodDeclaration;
function RequiresBaseInclude(): Boolean;
function GetLineCountOfString(ASource: string): Integer;
function GetGenLineForLCLine(AErrObject: string; ALine: Integer): Integer;
property SourceCode: string read FSourceCode write SetSourceCode;
property Position: Integer read FPosition write FPosition;
property IsEOF: Boolean read GetEOF;
property UnitState: TUnitState read FUnitState write FUnitState;
end;
implementation
{ TGenesisUnit }
uses
StrUtils;
procedure TGenesisUnit.AddInclude(AFile: string);
var
LInclude: TGenInclude;
begin
LInclude := TGenInclude.Create();
LInclude.Identifier := AFile;
AddElement(LInclude);
end;
procedure TGenesisUnit.AddIncludeAtTop(AFile: string);
var
LInclude: TGenInclude;
begin
LInclude := TGenInclude.Create();
LInclude.Identifier := AFile;
AddElementAtTop(LInclude);
end;
procedure TGenesisUnit.BuildConstructor;
var
LClass: TGenesisClass;
LElement, LElementB: TGenSourceObject;
LGenType: TGenType;
LConstructor, LMethod: TGenMethodDeclaration;
i: Integer;
begin
for LElement in Elements do
begin
if LElement.ClassType = TGenesisClass then
begin
LClass := TGenesisClass(LElement);
LConstructor := TGenMethodDeclaration.Create();
LConstructor.NeedsPrefix := False;
LConstructor.NeedsThis := False;
LConstructor.GenType.Identifier := LClass.Identifier;
LConstructor.GenType.PostChars := '*';
LConstructor.Parent := nil;//LClass;
LConstructor.Identifier := '_' + LClass.Identifier;
LConstructor.Source := LClass.Identifier + '* LObject;' + sLineBreak +
'LObject = sys_malloc(sizeof(' + LClass.Identifier + '));' + sLineBreak +
GenesisPrefix + LClass.Identifier + 'BindMethods(LObject);' + sLineBreak +
'LObject.ClassName = "' + LClass.Identifier + '";' + sLineBreak;
if Assigned(LClass.Parent) then
begin
LConstructor.Source := LConstructor.Source + 'LObject.ClassParentName = "' +
LClass.Parent.Identifier +'";' + sLineBreak;
end
else
begin
LConstructor.Source := LConstructor.Source + 'LObject.ClassParentName = "";' + sLineBreak;
end;
if LClass.HasMethodDummy('Constructor') then
begin
LConstructor.Source := LConstructor.Source + 'LObject.Constructor(LObject';
LMethod := GetMethodByName('Constructor');
if Assigned(LMethod) then
begin
for LElementB in LMethod.Elements do
begin
if TGenType(LElementB).Identifier <> 'this' then
begin
LGenType := TGenType.Create();
LGenType.Identifier := TGenType(LElementB).Identifier;
LGenType.PostChars := TGenType(LElementB).PostChars;
LConstructor.AddElement(LGenType);
end;
end;
//LConstructor.ParameterList.Assign(LMethod.ParameterList);
for i := 0 to LMethod.Elements.Count - 1 do
begin
if LMethod.Elements.Items[i].Identifier <> 'this' then
begin
LConstructor.Source := LConstructor.Source + ', ' + LMethod.Elements.Items[i].GetLiteCSource();
end;
end;
end;
LConstructor.Source := LConstructor.Source + ');' + sLineBreak;
end;
LConstructor.Source := LConstructor.Source + 'return(LObject);' + sLineBreak;
Self.AddElement(LConstructor);
end;
end;
end;
procedure TGenesisUnit.BuildDestructor;
//var
// LClass: TGenesisClass;
// LDestructor: TGenesisMethod;
begin
// SiMain.EnterMethod(Self, 'BuildDestructor');
// for LClass in FClassList do
// begin
// LDestructor := TGenesisMethod.Create();
// LDestructor.NeedsPrefix := False;
// LDestructor.GenesisMethodName := 'Free';
// LDestructor.MethodParentClass := LClass;
// LDestructor.DataType := 'void';
// LDestructor.SourceCode := '';
// if LClass.HasMethodDummy('Destructor') then
// begin
// LDestructor.SourceCode := 'This.Destructor(This);' + sLineBreak;
// end;
// LDestructor.SourceCode := LDestructor.SourceCode + 'sys_free(This);' + sLineBreak;
// FMethodList.Add(LDestructor);
// end;
// SiMain.LeaveMethod(Self, 'BuildDestructor');
end;
procedure TGenesisUnit.BuildMethodBindFunctions;
var
LClass: TGenesisClass;
LMethod: TGenMethodDeclaration;
LBindMethod: TGenMethodDeclaration;
LElement, LElementB: TGenSourceObject;
begin
for LElement in Elements do
begin
if LElement.ClassType = TGenesisClass then
begin
LClass := TGenesisClass(LElement);
LBindMethod := TGenMethodDeclaration.Create();
LBindMethod.GenType.Identifier := 'void';
LBindMethod.Identifier := 'BindMethods';
LBindMethod.NeedsThis := True;
LBindMethod.NeedsPrefix := True;
LBindMethod.Parent := LClass;
LBindMethod.AddVarDec('this', LClass.Identifier, '*');
if Assigned(LClass.Parent) then
begin
LBindMethod.Source := LBindMethod.Source + GenesisPrefix + LClass.Parent.Identifier +
LBindMethod.Identifier + '(this);' + sLineBreak;
end;
//LBindMethod.SourceCode := LBindMethod.SourceCode;
for LElementB in Elements do
begin
if LElementB.ClassType = TGenMethodDeclaration then
begin
LMethod := TGenMethodDeclaration(LElementB);
if Assigned(LMethod.Parent)
and (LMethod.Parent.Identifier = LClass.Identifier)
and (LClass.HasMethodDummy(LMethod.Identifier)) then
begin
LBindMethod.Source := LBindMethod.Source + 'this.' +
LMethod.Identifier + ' = ' + GenesisPrefix + LMethod.Parent.Identifier +
LMethod.Identifier + ';' + sLineBreak;
end;
end;
end;
//LBindMethod.SourceCode := LBindMethod.SourceCode;
Self.AddElement(LBindMethod);
end;
end;
end;
constructor TGenesisUnit.Create;
begin
inherited;
FUnitState := usCompiling;
end;
destructor TGenesisUnit.Destroy;
begin
inherited;
end;
procedure TGenesisUnit.DropNextVisibleChar;
begin
GetNextVisibleChar();
end;
procedure TGenesisUnit.ExpectChar(AChar: Char; AMessage: string = '');
begin
if not IsNextVisibleChar(AChar) then
begin
if AMessage = '' then
begin
raise Exception.Create('Unexpected Char "' + GetNextVisibleChar() + '" expected "' + AChar + '"');
end
else
begin
raise Exception.Create(AMessage);
end;
end;
end;
procedure TGenesisUnit.ExpectCharSet(ACharSet: TAnsiCharSet; AMessage: string = '');
var
LChar: Char;
begin
LChar := GetNextVisibleChar();
Position := Position -1;
if not CharInSet(LChar, ACharSet) then
begin
if AMessage = '' then
begin
raise Exception.Create('Unexpected Char "' + LChar + '"');
end
else
begin
raise Exception.Create(AMessage);
end;
end;
end;
procedure TGenesisUnit.ExpectClassAccessSpecifier(AWord: string);
begin
if not (SameText(AWord, 'private') or SameText(AWord, 'public') or SameText(AWord, 'protected')) then
begin
raise Exception.Create('Expected Class access specifier, but found ' + QuotedStr(AWord));
end;
end;
procedure TGenesisUnit.ExpectClassType(AClass: string; AMessage: string = '');
begin
if not IsClass(AClass) then
begin
if AMessage = '' then
begin
raise Exception.Create('Expected Classtype of current unit but found "' + AClass + '"');
end
else
begin
raise Exception.Create(AMessage);
end;
end;
end;
procedure TGenesisUnit.Finalize;
begin
BuildMethodBindFunctions();
BuildConstructor();
//BuildDestructor();
end;
function TGenesisUnit.GetCharsInRow(AChar: Char): string;
begin
Result := '';
while(IsNextVisibleChar(AChar)) do
begin
Result := Result + GetNextVisibleChar();
end;
end;
function TGenesisUnit.GetClassByName(AName: string): TGenesisClass;
var
LElement: TGenSourceObject;
begin
Result := nil;
LElement := GetElement(AName, TGenesisClass);
if Assigned(LElement) then
begin
Result := LElement as TGenesisClass;
end;
end;
function TGenesisUnit.GetCurrentLine: Integer;
var
LPos: Integer;
begin
Result := 1;
LPos := 1;
while (LPos < Position) and (LPos >= 1) do
begin
LPos := PosEx(sLineBreak, SourceCode, LPos+2);
if LPos < Position then
begin
Inc(Result);
end;
end;
end;
function TGenesisUnit.GetCurrentPosInLine: Integer;
var
LMaxLine, LPos, i: Integer;
LLines: TStringList;
begin
LMaxLine := GetCurrentLine();
LLines := TStringList.Create();
LLines.Text := FSourceCode;
Result := 1;
LPos := 0;
if LLines.Count >= LMaxLine then
begin
for i := 0 to LMaxLine - 2 do
begin
LPos := LPos + Length(LLines.Strings[i]);
end;
Result := Position - LPos - (LMaxLine*2);//including SLinebreake which is removed by stringlist
end;
end;
function TGenesisUnit.GetEOF: Boolean;
begin
Result := False;
if (FPosition > Length(FSourceCode) - 1) then
begin
Result := True;
end;
end;
function TGenesisUnit.GetGenLineForLCLine(AErrObject: string; ALine: Integer): Integer;
var
LMethod: TGenMethodDeclaration;
i, k, LFixLine: Integer;
LLines: TStringList;
begin
Result := 1;
for i := ELements.Count - 1 downto 0 do
begin
if ELements.Items[i].ClassType = TGenMethodDeclaration then
begin
LMethod := TGenMethodDeclaration(Elements.Items[i]);
if LMethod.LiteCLineStart <= ALine then
begin
SiMain.LogString('Method', LMethod.Identifier);
SiMain.LogInteger('GenStart', LMethod.GenesisLineStart);
SiMain.LogInteger('GenEnd', LMethod.GenesisLineEnd);
SiMain.LogInteger('LCStart', LMethod.LiteCLineStart);
SIMain.LogInteger('LCEnd', LMethod.LiteCLineEnd);
Result := ALine - (LMethod.LiteCLineStart - LMethod.GenesisLineStart);
Result := Result -
((LMethod.LiteCLineEnd - LMethod.LiteCLineStart) - (LMethod.GenesisLineEnd-LMethod.GenesisLineStart));
if (AErrObject <> '') then
begin
LFixLine := ALine;
LLines := TStringList.Create;
LLines.Text := FSourceCode;
for k := ALine downto 0 do //used Result-1 before
begin
if Pos(AErrObject, LLines.Strings[k]) >= 1 then
begin
LFixLine := k+1;
Break;
end;
end;
Result := Result - (Result-LFixLine);
LLines.Free;
end;
Break;
end;
end;
end;
end;
function TGenesisUnit.GetLineCountOfString(ASource: string): Integer;
var
// LPos: Integer;
LList: TStringList;
begin
Result := 1;
LList := TStringList.Create();
LLIst.Text := ASource;
Result := LList.Count;
LList.Free;
// LPos := 1;
// LPos := PosEx(sLineBreak, ASource, LPos);
// while(LPos >= 1) do
// begin
// Inc(Result);
// LPos := PosEx(sLineBreak, ASource, LPos+1);
// end;
end;
function TGenesisUnit.GetLiteCSource: String;
var
LELement: TGenSourceObject;
begin
Result := '#ifndef ' + GenesisPrefix + ChangeFileExt(FGenesisUnitName, '_class') +
sLineBreak + '#define ' + GenesisPrefix + ChangeFileExt(FGenesisUnitName, '_class') + sLineBreak;
for LElement in Elements do
begin
if LELement.ClassType = TGenMethodDeclaration then
begin
Result := Result + sLineBreak + sLineBreak;
TGenMethodDeclaration(LElement).LiteCLineStart := GetLineCountOfString(Result);
Result := Result + TGenMethodDeclaration(LElement).GetLiteCSource;
TGenMethodDeclaration(LElement).LiteCLineEnd := GetLineCountOfString(Result);
Result := Result + sLineBreak;
end
else
begin
Result := Result + LELement.GetLiteCSource();
end;
end;
Result := Result+ sLineBreak + '#endif';
end;
function TGenesisUnit.GetMethodByName(AName: string): TGenMethodDeclaration;
begin
Result := TGenMethodDeclaration(GetElement(AName, TGenMethodDeclaration));
end;
function TGenesisUnit.GetNextIdentifier: string;
begin
ExpectCharSet(CAlphaChars+CUnderScore);
Result := GetNextWord();
end;
function TGenesisUnit.GetNextVisibleChar: Char;
var
i: Integer;
LRestrictedChars: TAnsiCharSet;
begin
Result := Char(1);
LRestrictedChars := [Char(10), Char(13), ' '];
for i := FPosition to Length(FSourceCode) do
begin
if not CharInSet(FSourceCode[i], LRestrictedChars) then
begin
Result := FSourceCode[i];
break;
end;
end;
FPosition := i + 1;
end;
function TGenesisUnit.GetNextWord: string;
var
i: Integer;
begin
Result := '';
for i := FPosition to Length(FSourceCode) do
begin
if not CharInSet(FSourceCode[i], CWordDelimiters) then
begin
Result := Result + FSourceCode[i];
end
else
begin
if not (Result = '') then
begin
break;
end;
end;
end;
FPosition := i;
end;
procedure TGenesisUnit.InsertSource(ASource: string; APosition: Integer);
begin
Insert(ASource, FSourceCode, APosition);
end;
function TGenesisUnit.IsClass(AWord: String): Boolean;
begin
Result := Assigned(GetElement(AWord, TGenesisClass));
end;
function TGenesisUnit.IsNextVisibleChar(AChar: Char): Boolean;
var
LPosition: Cardinal;
begin
LPosition := FPosition;
Result := False;
if GetNextVisibleChar() = AChar then
begin
Result := True;
end;
FPosition := LPosition;
end;
function TGenesisUnit.IsNextVisibleCharSet(ASet: TAnsiCharSet): Boolean;
var
LPosition: Cardinal;
begin
LPosition := FPosition;
Result := False;
if CharInSet(GetNextVisibleChar(), ASet) then
begin
Result := True;
end;
FPosition := LPosition;
end;
function TGenesisUnit.RequiresBaseInclude: Boolean;
var
LClass: TGenesisClass;
LElement: TGenSourceObject;
begin
Result := False;
for LElement in Elements do
begin
if LElement.ClassType = TGenesisClass then
begin
LClass := TGenesisClass(LElement);
if Assigned(LClass.Parent) and (LClass.Parent.Identifier = 'CBaseClass')
and (not Assigned(GetElement('BaseClass.c', TGenInclude))) then
begin
Result := True;
Break;
end;
end;
end;
end;
procedure TGenesisUnit.SetSourceCode(const Value: string);
begin
FSourceCode := TrimRight(Value);
FSourceCode := StringReplace(FSourceCode, Char(9),' ', [rfReplaceAll]);//remove tab and replace with double space
FPosition := 1;
end;
end.
|
unit JPL.Binary.Types;
interface
uses
SysUtils
//, Dialogs
;
type
TBitsInfo = record
B1, B2, B3, B4: BYTE;
BitsStr: string;
end;
const
MAGIC_STR_MZ = 'MZ'; // Marek Żbikowski - https://en.wikipedia.org/wiki/Mark_Zbikowski
MAGIS_STR_ELF = 'ELF';
// WIndows & DOS
BIN_WIN32 = 0;
BIN_WIN64 = 6;
BIN_DOS = 1;
BIN_WIN16 = 2;
// Unix & Linux
BIN_UNIX16 = 102;
BIN_UNIX32 = 100;
BIN_UNIX64 = 106;
BIN_MACH_FAT = 201; // CA FE BA BE
// Mach objects
BIN_MACHO_32_LITTLE_ENDIAN = 210;
BIN_MACHO_32_BIG_ENDIAN = 220;
BIN_MACHO_64_LITTLE_ENDIAN = 230;
BIN_MACHO_64_BIG_ENDIAN = 240;
BIN_MACHO_FAT_MULTIARCH = 300; // Big endian
//BIN_MACHO_FAT_MULTIARCH_BE = 310;
BIN_UNKNOWN = -1;
UNKNOWN_EXECUTABLE = 'Unknown executable format!';
BIN_INVALID_OFFSET = -1;
implementation
end.
|
unit UdmConfiguracion;
interface
uses
System.SysUtils, System.Classes, uROBaseConnection, uROTransportChannel, uROIndyUDPChannel,
uROMessage, uROBinMessage, uROComponent, uROChannelAwareComponent, uRORemoteService,
System.SyncObjs, System.TypInfo, uROClientIntf, uROAsync, uROServerLocator;
type
TdmConfiguracion = class(TDataModule)
RORemoteService : TRORemoteService;
ROMessage : TROBinMessage;
ROChannel : TROIndyUDPChannel;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
CriticalSection : TCriticalSection;
public
{ Public declarations }
FEstadoConfiguracion : String;
FLstParametros : TStringList;
public function getConfiguration : Boolean;
end;
const
EXITOSO = '0';
ZERO_SERVICE_HOST = '127.0.0.1';
ZERO_SERVICE_PORT = 21035;
CONFIGURACION_POR_DEFECTO = 'DEFAULT';
CONFIGURACION_EN_LINEA = 'ON_LINE';
CONFIGURACION_EN_ARCHIVO = 'ON_FILE';
DELIMITADOR = '_';
UUID_PROCESO_DEFAULT = '00000000-0000-0000-0000-000000000000';
INICIALIZACION = 'Inicialización Servicio';
var
dmConfiguracion : TdmConfiguracion;
strApplication : String;
strNombreBD : String;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses LGenericServiceTool_Intf, UUtilidades, System.IOUtils, System.StrUtils;
{$R *.dfm}
{ TdmConfiguracion }
procedure TdmConfiguracion.DataModuleCreate(Sender: TObject);
begin
ROChannel.Host := ZERO_SERVICE_HOST;
ROChannel.Port := ZERO_SERVICE_PORT;
FLstParametros := TStringList.Create();
CriticalSection := TCriticalSection.Create;
end;
procedure TdmConfiguracion.DataModuleDestroy(Sender: TObject);
begin
FLstParametros.Clear;
FreeAndNil(FLstParametros);
FreeAndNil(CriticalSection);
end;
function TdmConfiguracion.getConfiguration : Boolean;
var
RequestGeneric : GenericRequest_;
ResponseGeneric : GenericResponse_;
strStatusCode : String;
StrPath : String;
transaccionExitosa : Boolean;
begin
transaccionExitosa := false;
RequestGeneric := GenericRequest_.Create;
ResponseGeneric := GenericResponse_.Create;
strApplication := TPath.GetFileNameWithoutExtension(ParamStr(0));
strNombreBD := MidStr(strApplication, 2, LastDelimiter(DELIMITADOR, strApplication) - 2);
StrPath := ExtractFilePath(ParamStr(0)) + strApplication + '.INI';
RequestGeneric.RequestMessage := AnsiString(strApplication);
try
(RORemoteService as ISGenericServiceTool).GenericOperation(RequestGeneric, ResponseGeneric);
strStatusCode := String(ResponseGeneric.Status.StatusCode);
if strStatusCode = EXITOSO then
begin
FLstParametros.Text := TUtilidades.base64Decode(String(ResponseGeneric.ResponseMessage));
FLstParametros.SaveToFile(StrPath);
FEstadoConfiguracion := CONFIGURACION_EN_LINEA;
transaccionExitosa := true;
end
else
begin
if FileExists(StrPath) then
begin
FLstParametros.LoadFromFile(StrPath);
FEstadoConfiguracion := CONFIGURACION_EN_ARCHIVO;
transaccionExitosa := true;
end;
end;
except on e:exception do
begin
TMonitor.sendErrorMessage(UUID_PROCESO_DEFAULT, INICIALIZACION, 'Consumo servicio configuración', 'Error al obtener configuración: ' + e.Message);
TUtilidades.reportLogError('Error al obtener configuración: ' + e.Message);
if FileExists(StrPath) then
begin
FLstParametros.LoadFromFile(StrPath);
FEstadoConfiguracion := CONFIGURACION_EN_ARCHIVO;
transaccionExitosa := true;
end
else
TMonitor.sendErrorMessage(UUID_PROCESO_DEFAULT, INICIALIZACION, 'Consumo servicio configuración', 'No existe archivo de configuración.');
end;
end;
result := transaccionExitosa;
end;
end.
|
unit Debug;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, Buttons;
type
TfrmDebug = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Splitter1: TSplitter;
lstSourceCode: TListBox;
sbCallStack: TSpeedButton;
sbExecEnd: TSpeedButton;
sbStepOver: TSpeedButton;
Label1: TLabel;
lblNumLine: TLabel;
sbWatches: TSpeedButton;
sbBreakPoint: TSpeedButton;
procedure sbStepOverClick(Sender: TObject);
procedure sbExecEndClick(Sender: TObject);
procedure sbCallStackClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure sbWatchesClick(Sender: TObject);
procedure lstSourceCodeDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure sbBreakPointClick(Sender: TObject);
private
// Будет обрабатывать пресс. по F8
procedure WMKeyDown(var Msg: TMsg; var Handled: Boolean);
public
end;
function BreakPoint(Index : Word) : Word;
procedure DebugerInit;
procedure MoveItemIndex;
var
frmDebug: TfrmDebug;
F8_Pressed : Boolean;
fRunToEnd : Boolean;
BreakPoints : Array [1..50] Of Word;
CountBreaks : Word;
implementation
{$R *.DFM}
uses Krnl, frmFile, frmCStack, frmWatch, frmMsg;
function BreakPoint(Index : Word) : Word;
var
i : Word;
begin
Result := 0;
for i := 1 to CountBreaks do
if BreakPoints[i] = Index then
begin
Result := i;
Exit;
end;
end;
procedure TfrmDebug.WMKeyDown(var Msg: TMsg; var Handled: Boolean);
begin
Handled := False;
If Not fDebugMode then
Exit;
If (Msg.Message = WM_KEYDOWN) And (Msg.wParam = VK_F8) then
Begin
F8_Pressed := True;
Handled := True;
End;
end;
procedure MoveItemIndex;
begin
frmDebug.lstSourceCode.ItemIndex := CurLine - 1;
frmDebug.lblNumLine.Caption := IntToStr(CurLine);
end;
procedure DebugerInit;
var
i : Word;
begin
fRunToEnd := False;
frmDebug.lstSourceCode.Clear;
frmCallStack.lstCallStack.Clear;
frmWatches.lstWatches.Clear;
CountWatches := 0;
CountBreaks := 0;
for i := 1 to CountLines do
begin
frmDebug.lstSourceCode.Items.Add(SourceCode[i]^);
end;
//frmDebug.lstSourceCode.ItemIndex := 0;
F8_Pressed := False;
Application.OnMessage := frmDebug.WMKeyDown;
fAddingWatch := False;
frmDebug.Show;
end;
procedure TfrmDebug.sbStepOverClick(Sender: TObject);
begin
If fDebugMode then
PostMessage(frmDebug.Handle, WM_KEYDOWN, VK_F8, 0);
end;
procedure TfrmDebug.sbExecEndClick(Sender: TObject);
begin
F8_Pressed := True;
//fDebugMode := False;
fRunToEnd := True;
//lstSourceCode.ItemIndex := 0;
end;
procedure TfrmDebug.sbCallStackClick(Sender: TObject);
begin
frmCallStack.Show;
end;
procedure TfrmDebug.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
If fDebugMode And (Not F8_Pressed) then
Begin
frmMessage.ShowMsg('Закончите выполнение программы');
CanClose := False;
End
Else
frmFileMenu.N15Click(Self);
end;
procedure TfrmDebug.sbWatchesClick(Sender: TObject);
begin
frmWatches.Show;
end;
procedure TfrmDebug.lstSourceCodeDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
tmpBrush : TBrush;
begin
with (Control as TListBox).Canvas do
begin
tmpBrush := Brush;
If BreakPoint(Index) > 0 then
Brush.Color := clGreen;
FillRect(Rect);
Brush := tmpBrush;
TextOut(Rect.Left,Rect.Top,lstSourceCode.Items[Index]);
end;
end;
procedure TfrmDebug.sbBreakPointClick(Sender: TObject);
var
i : Word;
begin
If Assigned(lstSourceCode.Items) And (lstSourceCode.ItemIndex > -1) then
Begin
If BreakPoint(lstSourceCode.ItemIndex) > 0 then
begin
for i := BreakPoint(lstSourceCode.ItemIndex) to CountBreaks - 1 do
BreakPoints[i] := BreakPoints[i + 1];
Dec(CountBreaks);
end
else begin
Inc(CountBreaks);
BreakPoints[CountBreaks] := lstSourceCode.ItemIndex;
end;
lstSourceCode.Repaint;
End;
end;
end.
|
program countdown;
var
i: integer;
begin
for i := 10 downto 1 do
write(i, '... ');
writeln('start!')
end.
|
(**
* $Id: dco.transport.Connection.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.transport.Connection;
interface
uses
System.Types,
superobject { An universal object serialization framework with Json support };
type
/// <summary>This interface defines the obligation of a tranport connection.</summary>
IConnection = interface
/// <summary>Returns the uri of the connection.</summary>
function GetId: string;
/// <summary>Sends an outbound message and waits for it is actually sent out.</summary>
function WriteEnsured(const Message_: string): Boolean;
/// <summary>Sends an outbound message and waits for it is actually sent out.</summary>
procedure Write(const Message_: string);
///
procedure HandleRead(const Message_: string);
end;
implementation
end.
|
unit crpZeeMapperDefault;
{written by Charles Richard Peterson, 2007; You can reach me at
www.houseofdexter.com or houseofdexter@gmail.com; The code is released under
Mozilla Public License 1.1 (MPL 1.1); }
interface
uses
SysUtils;
const
cDefaultRule = 'Rule';
cDefaultName = 'zeeMapper';
cMapText = 'Map';
cMapDelimiter = '-';
cRuleDelimiter = '-';
cRuleFldDelimiter = ',';
cRuleAscii = '#';
cDefaultExt = '.crp';
cDefaultTxtExt = '.txt';
cSecMain = 'Main';
cSecOptions = 'Option';
cDefaultTransLocKey = 'DefaultTransLoc';
cDefaultSaveLocKey = 'DefaultSaveLoc';
cDefaultExtKey = 'DefaultExt';
cUseFileExtKey = 'FileExt';
//Rules
{if you add more Rules add to crpRule SetRuleIndex and }
cRIgnoreSet = ['%'];
cRIgnoreUntilSet = ['@'];
cRIgnoreAfterSet = ['%'];
cRApplyMultiSet = ['%', '^', '$'];
cRApplyUntilSet = ['%','!', '@'];
cRConvertSet= ['%', '!'];
cRAsOneRuleSet = ['^'];
cRIgnore = 'Ignore When %';
cRIgnoreUntil = 'Ignore Until @';
cRIgnoreAfter ='Ignore After When %';
cRApplyMulti = 'When %, Apply ^ Times $';
cRApplyUntil = 'When % Convert To ! Until @';
cRConvert = 'When % Convert To !';
cRAsOneRule = 'Combine Next ^ Rules as One';
//Status State
cStateLoading = 'Loading';
cStateLoaded = 'Loaded';
cStateSaving = 'Saving';
cStateSaved = 'Saved';
cStateDrag= 'Dragging';
cStateDropped = 'Dropped';
cStateImporting = 'Importing';
cStateImported = 'Imported';
cStateTranslating = 'Translating';
cStateTranslated = 'Translated';
cStateStarted = 'Started';
cStateFinished = 'Finished';
cStateExporting = 'Exporting';
cStateExported = 'Exported';
cStartDragError = 'You can not drag a Map that does not exist or is in a different branch!';
cExportMapNotSel = 'Export Map not selected';
cBaseMapNotSel = 'Base Map not selected';
cDupeMapName = 'Duplicate Map Name';
cSaveChange = 'Save Changes?';
cRenameError = 'Unable to rename Map';
//error messages
implementation
end.
|
{*******************************************************}
{ }
{ Fixing an annoying bug in Win Vista and later, where }
{ Controls (like Buttons) are disappearing when the ALT }
{ key is pressed. }
{ }
{*******************************************************}
unit ControlHideFix;
interface
uses Classes, Controls;
type
TButtonEvent = class
procedure KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
end;
procedure RepaintControls(C: TComponent);
implementation
procedure TButtonEvent.KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = 18 then // alt
RepaintControls((Sender as TComponent));
end;
procedure RepaintControls(C: TComponent);
var
I : Integer;
begin
try
(C as TControl).Invalidate;
except
//
end;
for I := 0 to C.ComponentCount - 1 do
RepaintControls(C.Components[I]);
end;
end.
|
{**************************************************************}
{**** Модуль для работы с реестром Windows. ****}
{**** ****}
{**** Автор модуля: Наумов Александр ****}
{**** ****}
{**** naumov_@mail.ru ****}
{**** http://www.mgclt.h16.ru ****}
{**** Май 2006 ****}
{**************************************************************}
unit Regedit;
interface
uses
windows;
{ Запись }
//Добавление строковой записи [RootKey\SubKey] "Name"="Value"
Procedure RegWriteString(RootKey: cardinal; Subkey: PAnsiChar; Name: PChar; Value: PChar);
//Добавление DWORD записи [RootKey\SubKey] "Name"=dword:Value
Procedure RegWriteInteger(RootKey: cardinal; Subkey: PAnsiChar; Name: PChar; Value: DWord);
//Добавление двоичной записи [RootKey\SubKey] "Name"=hex:Value
Procedure RegWriteBinary(RootKey: cardinal; Subkey: PAnsiChar; Name: PChar; Value: DWord; const ValueSize: integer);
{ Чтение }
//Чтение строкового значения
function GetRegistryString(const RootKey: HKEY; const Key, Name: String): String;
//Чтение двоичного значения
function GetRegistryBinary(const RootKey: HKEY; const Key, Name: String): Integer;
//Чтение значения DWORD
function GetRegistryDWord(const RootKey: HKEY; const Key, Name: String): Word;
{ Удаление }
//Удаление ключа [-HKLM\Software\Microsoft]
//RootKey:HKLM SubKey:Software Name:Microsoft
Procedure RegDelKey(RootKey: cardinal; Subkey: PAnsiChar; Name: PChar);
//Удаление параметра [-HKLM\Software\Microsoft] -"Name"
//RootKey:HKLM SubKey:Software\Microsoft Name:"Name"
Procedure RegDelValue(RootKey: cardinal; Subkey: PAnsiChar; Name: PChar);
{ Проверка }
//Существует ли ключ в реестре?
Function RegKeyExists(const RootKey: HKEY; const Key: String): bool;
//Существует ли параметр в реестре?
function RegValueExists(const RootKey: HKEY; const Key, Name: String): Boolean;
function RegGetValue(const RootKey: HKEY; const Key, Name: String;
const ValueType: Cardinal; var RegValueType: Cardinal;
var ValueBuf: Pointer; var ValueSize: Integer): Boolean;
implementation
Procedure RegWriteString(RootKey: cardinal; Subkey: PAnsiChar; Name: PChar; Value: PChar);
var
key: hkey;
begin
if RegCreateKey(RootKey,
SubKey,
key) = ERROR_SUCCESS then
begin
RegSetValueEx(key, Name, 0, REG_SZ, Value, Length(Value) + 1);
RegCloseKey(key);
end;
end;
Procedure RegWriteInteger(RootKey: cardinal; Subkey: PAnsiChar; Name: PChar; Value: DWord);
var
key: hkey;
begin
if RegCreateKey(RootKey,
SubKey,
key) = ERROR_SUCCESS then
begin
RegSetValueEx(key, Name, 0, REG_DWORD, @Value, SizeOf(Value));
RegCloseKey(key);
end;
end;
Procedure RegWriteBinary(RootKey: cardinal; Subkey: PAnsiChar; Name: PChar; Value: DWord; const ValueSize: integer);
var
key: hkey;
begin
if RegCreateKey(RootKey,
SubKey,
key) = ERROR_SUCCESS then
begin
RegSetValueEx(key, Name, 0, REG_BINARY, @Value, ValueSize);
RegCloseKey(key);
end;
end;
Procedure RegDelKey(RootKey: cardinal; Subkey: PAnsiChar; Name: PChar);
var
key: hkey;
begin
if RegCreateKey(RootKey,
SubKey,
key) = ERROR_SUCCESS then
begin
RegDeleteKey(key, Name);
RegCloseKey(key);
end;
end;
Procedure RegDelValue(RootKey: cardinal; Subkey: PAnsiChar; Name: PChar);
var
key: hkey;
begin
if RegCreateKey(RootKey,
SubKey,
key) = ERROR_SUCCESS then
begin
RegDeleteValue(key, Pointer(Name));
RegCloseKey(key);
end;
end;
Function RegKeyExists(const RootKey: HKEY; const Key: String): bool;
var Handle : HKEY;
begin
if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_READ, Handle) = ERROR_SUCCESS then
begin
Result := True;
RegCloseKey(Handle);
end else
Result := False;
end;
function RegValueExists(const RootKey: HKEY; const Key, Name: String): Boolean;
var Handle : HKEY;
begin
if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_READ, Handle) = ERROR_SUCCESS then
begin
Result := RegQueryValueEx(Handle, Pointer(Name), nil, nil, nil, nil) = ERROR_SUCCESS;
RegCloseKey(Handle);
end else
Result := False;
end;
function GetRegistryString(const RootKey: HKEY; const Key, Name: String): String;
var
Handle: HKEY;
DataType, DataSize: DWORD;
begin
if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_QUERY_VALUE, Handle) <> ERROR_SUCCESS then Exit;
if (RegQueryValueEx(Handle, PChar(Name), nil, @DataType, nil, @DataSize) <> ERROR_SUCCESS)
or (DataType <> REG_SZ) then begin
RegCloseKey(Handle);
Exit;
end;
SetString(Result, nil, DataSize-1);
RegQueryValueEx(Handle, PChar(Name), nil, @DataType, PByte(@Result[1]), @DataSize);
RegCloseKey(Handle);
end;
function GetRegistryBinary(const RootKey: HKEY; const Key, Name: String): Integer;
var Buf : Pointer;
Size : Integer;
VType : Cardinal;
begin
Result := 0;
if not RegGetValue(RootKey, Key, Name, REG_BINARY, VType, Buf, Size) then
exit;
if (VType = REG_BINARY) and (Size >= Sizeof(Word)) then
Result := PWord(Buf)^;
FreeMem(Buf);
end;
function GetRegistryDWord(const RootKey: HKEY; const Key, Name: String): Word;
var Buf : Pointer;
Size : Integer;
VType : Cardinal;
begin
Result := 0;
if not RegGetValue(RootKey, Key, Name, REG_DWORD, VType, Buf, Size) then
exit;
if (VType = REG_DWORD) and (Size >= Sizeof(Word)) then
Result := PWord(Buf)^;
FreeMem(Buf);
end;
function RegGetValue(const RootKey: HKEY; const Key, Name: String;
const ValueType: Cardinal; var RegValueType: Cardinal;
var ValueBuf: Pointer; var ValueSize: Integer): Boolean;
var Handle : HKEY;
Buf : Pointer;
BufSize : Cardinal;
begin
Result := False;
ValueSize := 0;
ValueBuf := nil;
if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_READ, Handle) <> ERROR_SUCCESS then
exit;
BufSize := 0;
RegQueryValueEx(Handle, Pointer(Name), nil, @RegValueType, nil, @BufSize);
if BufSize <= 0 then
exit;
GetMem(Buf, BufSize);
if RegQueryValueEx(Handle, Pointer(Name), nil, @RegValueType, Buf, @BufSize) = ERROR_SUCCESS then
begin
ValueBuf := Buf;
ValueSize := Integer(BufSize);
Result := True;
end;
if not Result then
FreeMem(Buf);
RegCloseKey(Handle);
end;
end.
|
unit UImagen;
interface
type
TImagen = class
private
FIdFolio : int64; {ID DEL FOLIO AL QUE PERTENECE}
FRutaLocal : string; {RUTA COMPLETA DESDE DONDE SE PUBLICO LA IMAGEN}
FServidorFtp : string; {DIRECCION IP DEL FTP}
FRutaFtp : string; {DIRECTORIO DE LA IMAGEN EN EL FTP}
FNombreImagen : string; {NOMBRE DEL ARCHIVO CON EXTENSION}
FVersion : integer; {NUERO DE VERSION DE LA IMAGEN}
FTamanoBytes : Int64; {TAMAŅO DEL ARCHIVO EN BYTES}
FAncho : integer; {ANCHO EN PIXELES }
FAlto : integer; {ALTO EN PIXELES}
FDensidad : integer; {DENSIDAD DE LA IMAGEN EN DPI}
FIpPublicacion : string; {DIRECCION DE LA MAQUINA DESDE DONDE SE PUBLICO}
{GETTERS AND SETTERS}
public
{CONSTRUCTORES}
constructor Create;
destructor Destroy;
property IdFolio : int64 read FIdFolio write FIdFolio;
property RutaLocal : string read FRutaLocal write FRutaLocal;
property ServidorFtp : string read FServidorFtp write FServidorFtp;
property RutaFtp : string read FRutaFtp write FRutaFtp;
property NombreImagen : string read FNombreImagen write FNombreImagen;
property Version : integer read FVersion write FVersion;
property TamanoBytes : Int64 read FTamanoBytes write FTamanoBytes;
property Ancho : integer read FAncho write FAncho;
property Alto : integer read FAlto write FAlto;
property Densidad : integer read FDensidad write FDensidad;
property IpPublicacion : string read FIpPublicacion write FIpPublicacion;
end;
implementation
{ TImagen }
{$REGION 'CONSTRUTOR AND DESTRUCTOR'}
constructor TImagen.Create;
begin
inherited;
end;
destructor TImagen.Destroy;
begin
inherited;
end;
{$ENDREGION}
{$REGION 'GETTERS AND SETTERS'}
{$ENDREGION}
end.
|
unit Main;
interface
type
TCity = class
Country: String;
Latitude: Double;
Longitude: Double;
end;
implementation
uses
Math,
types,
System.generics.collections,
SysUtils;
const
EPSILON = 0.0000001;
var
Dictionary: TDictionary<String, TCity>;
City, Value: TCity;
Key: String;
begin
{ Create the dictionary. }
Dictionary := TDictionary<String, TCity>.Create;
City := TCity.Create;
{ Add some key-value pairs to the dictionary. }
City.Country := 'Romania';
City.Latitude := 47.16;
City.Longitude := 27.58;
Dictionary.Add('Iasi', City);
City := TCity.Create;
City.Country := 'United Kingdom';
City.Latitude := 51.5;
City.Longitude := -0.17;
Dictionary.Add('London', City);
City := TCity.Create;
City.Country := 'Argentina';
{ Notice the wrong coordinates }
City.Latitude := 0;
City.Longitude := 0;
Dictionary.Add('Buenos Aires', City);
{ Display the current number of key-value entries. }
writeln('Number of pairs in the dictionary: ' +
IntToStr(Dictionary.Count));
// Try looking up "Iasi".
if (Dictionary.TryGetValue('Iasi', City) = True) then
begin
writeln(
'Iasi is located in ' + City.Country +
' with latitude = ' + FloatToStrF(City.Latitude, ffFixed, 4, 2) +
' and longitude = ' + FloatToStrF(City.Longitude, ffFixed, 4, 2)
);
end
else
writeln('Could not find Iasi in the dictionary');
{ Remove the "Iasi" key from dictionary. }
Dictionary.Remove('Iasi');
{ Make sure the dictionary's capacity is set to the number of entries. }
Dictionary.TrimExcess;
{ Test if "Iasi" is a key in the dictionary. }
if Dictionary.ContainsKey('Iasi') then
writeln('The key "Iasi" is in the dictionary.')
else
writeln('The key "Iasi" is not in the dictionary.');
{ Test how (United Kingdom, 51.5, -0.17) is a value in the dictionary but
ContainsValue returns False if passed a different instance of TCity with the
same data, as different instances have different references. }
if Dictionary.ContainsKey('London') then
begin
Dictionary.TryGetValue('London', City);
if (City.Country = 'United Kingdom') and (CompareValue(City.Latitude, 51.5, EPSILON) = EqualsValue) and (CompareValue(City.Longitude, -0.17, EPSILON) = EqualsValue) then
writeln('The value (United Kingdom, 51.5, -0.17) is in the dictionary.')
else
writeln('Error: The value (United Kingdom, 51.5, -0.17) is not in the dictionary.');
City := TCity.Create;
City.Country := 'United Kingdom';
City.Latitude := 51.5;
City.Longitude := -0.17;
if Dictionary.ContainsValue(City) then
writeln('Error: A new instance of TCity with values (United Kingdom, 51.5, -0.17) matches an existing instance in the dictionary.')
else
writeln('A new instance of TCity with values (United Kingdom, 51.5, -0.17) does not match any existing instance in the dictionary.');
City.Free;
end
else
writeln('Error: The key "London" is not in the dictionary.');
{ Update the coordinates to the correct ones. }
City := TCity.Create;
City.Country := 'Argentina';
City.Latitude := -34.6;
City.Longitude := -58.45;
Dictionary.AddOrSetValue('Buenos Aires', City);
{ Generate the exception "Duplicates not allowed". }
try
Dictionary.Add('Buenos Aires', City);
except
on Exception do
writeln('Could not add entry. Duplicates are not allowed.');
end;
{ Display all countries. }
writeln('All countries:');
for Value in Dictionary.Values do
writeln(Value.Country);
{ Iterate through all keys in the dictionary and display their coordinates. }
writeln('All cities and their coordinates:');
for Key in Dictionary.Keys do
begin
writeln(Key + ': ' + FloatToStrF(Dictionary.Items[Key].Latitude, ffFixed, 4, 2) + ', ' +
FloatToStrF(Dictionary.Items[Key].Longitude, ffFixed, 4, 2));
end;
{ Clear all entries in the dictionary. }
Dictionary.Clear;
{ There should be no entries at this point. }
writeln('Number of key-value pairs in the dictionary after cleaning: ' + IntToStr(Dictionary.Count));
{ Free the memory allocated for the dictionary. }
Dictionary.Free;
City.Free;
readln;
end.
|
unit OSXUtils;
{
Copyright (c) 2017+, 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
{
other code to fix:
- FileSupport
- AdvFiles
GetExtForMimeType
}
{$IFDEF MACOS}
uses
Posix.Unistd, Posix.Pthread, Posix.Wctype,
MacApi.CoreServices, Macapi.Mach,
Math, SysUtils;
const
ERROR_SUCCESS = 0;
FILE_ATTRIBUTE_NORMAL = 0;
type
DWord = UInt32;
LargeUInt = UInt64;
TRTLCriticalSection = class (TObject);
TSystemTime = record
end;
procedure EnterCriticalSection(var cs : TRTLCriticalSection);
function TryEnterCriticalSection(var cs : TRTLCriticalSection) : boolean;
procedure LeaveCriticalSection(var cs : TRTLCriticalSection);
procedure InitializeCriticalSection(var cs : TRTLCriticalSection);
procedure DeleteCriticalSection(var cs : TRTLCriticalSection);
function InterlockedDecrement(var i : integer) :integer;
function InterlockedIncrement(var i : integer) :integer;
procedure Sleep(iTime : cardinal);
function GetCurrentThreadID : Cardinal;
procedure QueryPerformanceFrequency(var freq : Int64);
procedure QueryPerformanceCounter(var count : Int64);
function GetTickCount : cardinal;
{$ENDIF}
implementation
{$IFDEF MACOS}
procedure InitializeCriticalSection(var cs : TRTLCriticalSection);
begin
cs := TRTLCriticalSection.Create;
end;
procedure EnterCriticalSection(var cs : TRTLCriticalSection);
begin
TMonitor.Enter(cs);
end;
function TryEnterCriticalSection(var cs : TRTLCriticalSection) : boolean;
begin
result := TMonitor.TryEnter(cs);
end;
procedure LeaveCriticalSection(var cs : TRTLCriticalSection);
begin
TMonitor.Exit(cs);
end;
procedure DeleteCriticalSection(var cs : TRTLCriticalSection);
begin
cs.Free;
end;
function InterlockedDecrement(var i : integer) :integer;
begin
AtomicDecrement(i);
result := i;
end;
function InterlockedIncrement(var i : integer) :integer;
begin
AtomicIncrement(i);
result := i;
end;
procedure Sleep(iTime : cardinal);
begin
usleep(iTime * 1000);
end;
function GetCurrentThreadID : Cardinal;
begin
result := Posix.Pthread.GetCurrentThreadID;
end;
procedure QueryPerformanceFrequency(var freq : Int64);
begin
freq := 1000000000; // nano seconds
end;
procedure QueryPerformanceCounter(var count : Int64);
begin
count := AbsoluteToNanoseconds(mach_absolute_time);
end;
function GetTickCount : cardinal;
begin
result := AbsoluteToNanoseconds(mach_absolute_time) div 1000000;
end;
{$ENDIF}
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/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: JvContextProvider.pas, released on 2003-07-18.
The Initial Developer of the Original Code is Marcel Bestebroer
Portions created by Marcel Bestebroer are Copyright (C) 2002 - 2003 Marcel
Bestebroer
All Rights Reserved.
Contributor(s):
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.delphi-jedi.org
Known Issues:
-----------------------------------------------------------------------------}
// $Id: JvContextProvider.pas 13104 2011-09-07 06:50:43Z obones $
unit JvContextProvider;
{$I jvcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
Classes,
JvDataProvider, JvDataProviderIntf;
type
{ Context provider related interfaces. }
IJvDataContextProvider = interface
['{78EB1037-11A5-4871-8115-4AE1AC60B59C}']
function Get_ClientProvider: IJvDataProvider;
procedure Set_ClientProvider(Value: IJvDataProvider);
property ClientProvider: IJvDataProvider read Get_ClientProvider write Set_ClientProvider;
end;
IJvDataContextSearch = interface
['{C8513B84-FAA0-4794-A4A9-B2899797F52B}']
function Find(Context: IJvDataContext; const Recursive: Boolean = False): IJvDataItem;
function FindByName(Name: string; const Recursive: Boolean = False): IJvDataItem;
end;
IJvDataContextItems = interface
['{3303276D-2596-4FDB-BA1C-CE6E043BEB7A}']
function GetContexts: IJvDataContexts;
end;
IJvDataContextItem = interface
['{7156CAC8-0DB9-43B7-96C5-5A56723C5158}']
function GetContext: IJvDataContext;
end;
{$IFDEF RTL230_UP}
[ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32)]
{$ENDIF RTL230_UP}
TJvContextProvider = class(TJvCustomDataProvider, IJvDataContextProvider)
function IJvDataContextProvider.Get_ClientProvider = GetProviderIntf;
procedure IJvDataContextProvider.Set_ClientProvider = SetProviderIntf;
private
function GetProviderIntf: IJvDataProvider;
procedure SetProviderIntf(Value: IJvDataProvider);
function GetProviderComp: TComponent;
procedure SetProviderComp(Value: TComponent);
protected
class function ItemsClass: TJvDataItemsClass; override;
function ConsumerClasses: TClassArray; override;
public
property ProviderComp: TComponent read GetProviderComp write SetProviderComp;
property ProviderIntf: IJvDataProvider read GetProviderIntf write SetProviderIntf;
published
property Provider: IJvDataProvider read GetProviderIntf write SetProviderIntf;
end;
TJvContextProviderServerNotify = class(TJvDataConsumerServerNotify)
protected
procedure ItemSelected(Value: IJvDataItem); override;
function IsValidClient(Client: IJvDataConsumerClientNotify): Boolean; override;
end;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvContextProvider.pas $';
Revision: '$Revision: 13104 $';
Date: '$Date: 2011-09-07 08:50:43 +0200 (mer. 07 sept. 2011) $';
LogPath: 'JVCL\run'
);
{$ENDIF UNITVERSIONING}
implementation
uses
SysUtils,
JvTypes, JvResources;
type
TContextItems = class;
TContextRootItems = class;
TContextItem = class;
TContextItemsManager = class;
TContextItems = class(TJvBaseDataItems, IJvDataContextItems, IJvDataContextSearch)
protected
function GetContexts: IJvDataContexts; virtual;
function Find(Context: IJvDataContext; const Recursive: Boolean = False): IJvDataItem;
function FindByName(Name: string; const Recursive: Boolean = False): IJvDataItem;
procedure InitImplementers; override;
function GetCount: Integer; override;
function GetItem(I: Integer): IJvDataItem; override;
end;
TContextRootItems = class(TContextItems)
private
FClientProvider: IJvDataProvider;
FNotifier: TJvProviderNotification;
procedure SetClientProvider(Value: IJvDataProvider);
procedure DataProviderChanging(ADataProvider: IJvDataProvider;
AReason: TDataProviderChangeReason; Source: IUnknown);
procedure DataProviderChanged(ADataProvider: IJvDataProvider;
AReason: TDataProviderChangeReason; Source: IUnknown);
protected
function GetContexts: IJvDataContexts; override;
public
constructor Create; override;
destructor Destroy; override;
property ClientProvider: IJvDataProvider read FClientProvider write SetClientProvider;
end;
TContextItem = class(TJvBaseDataItem, IJvDataItemText, IJvDataContextItem)
private
FContext: IJvDataContext;
{ IContextItem methods }
function GetContext: IJvDataContext;
{ IJvDataItemText methods }
function GetText: string;
procedure SetText(const Value: string);
function Editable: Boolean;
protected
procedure InitID; override;
function IsDeletable: Boolean; override;
constructor CreateCtx(AOwner: IJvDataItems; AContext: IJvDataContext);
public
property Context: IJvDataContext read GetContext;
end;
TContextItemsManager = class(TJvBaseDataItemsManagement)
protected
function GetContexts: IJvDataContexts;
{ IJvDataItemManagement methods }
function Add(Item: IJvDataItem): IJvDataItem; override;
function New: IJvDataItem; override;
procedure Clear; override;
procedure Delete(Index: Integer); override;
procedure Remove(var Item: IJvDataItem); override;
end;
//=== { TContextItems } ======================================================
function TContextItems.GetContexts: IJvDataContexts;
var
ParentCtx: IJvDataContext;
begin
if GetParent <> nil then
begin
if Supports(GetParent, IJvDataContext, ParentCtx) then
Supports(ParentCtx, IJvDataContexts, Result);
end
else
Result := nil;
end;
function TContextItems.Find(Context: IJvDataContext; const Recursive: Boolean = False): IJvDataItem;
var
CtxStack: array of IJvDataContext;
CtxIdx: Integer;
begin
if Context <> nil then
begin
if Context.Contexts = GetContexts then
Result := TContextItem.CreateCtx(Self, Context)
else
if Recursive then
begin
SetLength(CtxStack, 128); // reserve some space; should be enough for most situations
CtxIdx := 0;
while (Context <> nil) and (Context.Contexts <> GetContexts) do
begin
if CtxIdx = Length(CtxStack) then
SetLength(CtxStack, CtxIdx + 128);
CtxStack[CtxIdx] := Context;
Inc(CtxIdx);
Context := Context.Contexts.Ancestor;
end;
if Context <> nil then
begin
// unwind the stack to create the actual data item
Result := TContextItem.CreateCtx(Self, Context);
Dec(CtxIdx);
while (CtxIdx >= 0) do
begin
Result := TContextItem.CreateCtx(Result.GetItems, CtxStack[CtxIdx]);
Dec(CtxIdx);
end;
end;
end;
end;
end;
function TContextItems.FindByName(Name: string; const Recursive: Boolean = False): IJvDataItem;
var
CtxList: IJvDataContexts;
Ctx: IJvDataContext;
I: Integer;
CtxSubList: IJvDataContexts;
begin
//TODO: Recursive only checks one level deep!!
CtxList := GetContexts;
if CtxList <> nil then
begin
Ctx := CtxList.GetContextByName(Name);
if (Ctx = nil) and (Recursive) then
begin
I := 0;
while I <= CtxList.GetCount do
begin
Ctx := CtxList.GetContext(I);
if Supports(Ctx, IJvDataContexts, CtxSubList) then
begin
Ctx := CtxSubList.GetContextByName(Name);
if Ctx <> nil then
Break;
end
else
Ctx := nil;
Inc(I);
end;
end;
if Ctx <> nil then
Result := TContextItem.CreateCtx(Self, Ctx);
end;
end;
procedure TContextItems.InitImplementers;
var
CtxList: IJvDataContexts;
CtxMan: IJvDataContextsManager;
begin
CtxList := GetContexts;
if (CtxList <> nil) and Supports(CtxList, IJvDataContextsManager, CtxMan) then
TContextItemsManager.Create(Self);
end;
function TContextItems.GetCount: Integer;
var
ParentCtxList: IJvDataContexts;
begin
ParentCtxList := GetContexts;
if ParentCtxList <> nil then
Result := ParentCtxList.GetCount
else
Result := 0;
end;
function TContextItems.GetItem(I: Integer): IJvDataItem;
var
CtxList: IJvDataContexts;
begin
CtxList := GetContexts;
if CtxList <> nil then
Result := TContextItem.CreateCtx(Self, CtxList.GetContext(I));
end;
//=== { TContextRootItems } ==================================================
constructor TContextRootItems.Create;
begin
inherited Create;
FNotifier := TJvProviderNotification.Create;
FNotifier.OnChanging := DataProviderChanging;
FNotifier.OnChanged := DataProviderChanged;
end;
destructor TContextRootItems.Destroy;
begin
FreeAndNil(FNotifier);
inherited Destroy;
end;
procedure TContextRootItems.SetClientProvider(Value: IJvDataProvider);
begin
if Value <> FClientProvider then
begin
GetProvider.Changing(pcrFullRefresh, nil);
FClientProvider := Value;
FNotifier.Provider := Value;
ClearIntfImpl;
if Value <> nil then
InitImplementers;
GetProvider.Changed(pcrFullRefresh, nil);
end;
end;
procedure TContextRootItems.DataProviderChanging(ADataProvider: IJvDataProvider;
AReason: TDataProviderChangeReason; Source: IUnknown);
var
CtxItem: IJvDataItem;
ParentList: IJvDataItems;
begin
case AReason of
pcrDestroy:
ClientProvider := nil;
pcrContextAdd:
begin
{ Source contains the IJvDataContext where the context is added to or nil if the new
context is added to the root. }
if Source <> nil then
begin
CtxItem := Find(IJvDataContext(Source), True);
if CtxItem <> nil then
begin
if not Supports(CtxItem, IJvDataItems, ParentList) then
ParentList := Self;
end
else
ParentList := Self;
end
else
ParentList := Self;
GetProvider.Changing(pcrAdd, ParentList);
end;
pcrContextDelete:
begin
{ Source is the IJvDataContext that is about to be destroyed. }
CtxItem := Find(IJvDataContext(Source), True);
GetProvider.Changing(pcrDelete, CtxItem);
end;
pcrContextUpdate:
begin
{ Source is the IJvDataContext that is about to be changed. }
CtxItem := Find(IJvDataContext(Source), True);
GetProvider.Changing(pcrUpdateItem, CtxItem);
end;
end;
end;
procedure TContextRootItems.DataProviderChanged(ADataProvider: IJvDataProvider;
AReason: TDataProviderChangeReason; Source: IUnknown);
var
CtxItem: IJvDataItem;
ParentList: IJvDataItems;
begin
case AReason of
pcrContextAdd:
begin
{ Source contains the IJvDataContext that was just added. }
CtxItem := Find(IJvDataContext(Source), True);
GetProvider.Changed(pcrAdd, CtxItem);
end;
pcrContextDelete:
begin
{ Source is the IJvDataContext from which the item was just removed or nil if the removed
context was at the root. }
if Source <> nil then
begin
CtxItem := Find(IJvDataContext(Source), True);
if CtxItem <> nil then
begin
if not Supports(CtxItem, IJvDataItems, ParentList) then
ParentList := Self;
end
else
ParentList := Self;
end
else
ParentList := Self;
GetProvider.Changed(pcrDelete, ParentList);
end;
pcrContextUpdate:
begin
{ Source is the IJvDataContext that has changed. }
CtxItem := Find(IJvDataContext(Source), True);
GetProvider.Changed(pcrUpdateItem, CtxItem);
end;
end;
end;
function TContextRootItems.GetContexts: IJvDataContexts;
var
ParentCtx: IJvDataContext;
begin
if GetParent <> nil then
begin
if Supports(GetParent, IJvDataContext, ParentCtx) then
Supports(ParentCtx, IJvDataContexts, Result);
end
else
Supports(ClientProvider, IJvDataContexts, Result);
end;
//=== { TContextItem } =======================================================
constructor TContextItem.CreateCtx(AOwner: IJvDataItems; AContext: IJvDataContext);
begin
Create(AOwner);
FContext := AContext;
end;
function TContextItem.GetContext: IJvDataContext;
begin
Result := FContext;
end;
function TContextItem.GetText: string;
begin
if Context <> nil then
Result := Context.Name
else
Result := RsContextItemEmptyCaption;
end;
procedure TContextItem.SetText(const Value: string);
var
CtxMan: IJvDataContextManager;
begin
if Context <> nil then
begin
if Supports(Context, IJvDataContextManager, CtxMan) then
begin
if Context.Name <> Value then
begin
GetItems.GetProvider.Changing(pcrUpdateItem, Self as IJvDataItem);
CtxMan.SetName(Value);
GetItems.GetProvider.Changed(pcrUpdateItem, Self as IJvDataItem);
end;
end;
end
else
raise EJVCLException.CreateRes(@RsENoContextAssigned);
end;
function TContextItem.Editable: Boolean;
begin
Result := True;
end;
procedure TContextItem.InitID;
var
S: string;
Ctx: IJvDataContext;
begin
S := GetContext.Name;
Ctx := GetContext.Contexts.Ancestor;
while Ctx <> nil do
begin
S := Ctx.Name + '\' + S;
Ctx := Ctx.Contexts.Ancestor;
end;
SetID('CTX:' + S);
end;
function TContextItem.IsDeletable: Boolean;
begin
if GetContext <> nil then
Result := GetContext.IsDeletable
else
Result := True;
end;
//=== { TContextItemsManager } ===============================================
function TContextItemsManager.GetContexts: IJvDataContexts;
var
ICI: IJvDataContextItems;
begin
if Supports(Items, IJvDataContextItems, ICI) then
Result := ICI.GetContexts
else
Result := nil;
end;
function TContextItemsManager.Add(Item: IJvDataItem): IJvDataItem;
var
Contexts: IJvDataContexts;
Mngr: IJvDataContextsManager;
CtxItem: IJvDataContextItem;
begin
Contexts := GetContexts;
if (Contexts <> nil) and Supports(Contexts, IJvDataContextsManager, Mngr) then
begin
if Supports(Item, IJvDataContextItem, CtxItem) then
Result := Item
else
raise EJVCLException.CreateRes(@RsENoContextItem);
end;
end;
function TContextItemsManager.New: IJvDataItem;
var
Contexts: IJvDataContexts;
Mngr: IJvDataContextsManager;
begin
Contexts := GetContexts;
if (Contexts <> nil) and Supports(Contexts, IJvDataContextsManager, Mngr) then
Result := Add(TContextItem.CreateCtx(Items, Mngr.New));
end;
procedure TContextItemsManager.Clear;
var
Contexts: IJvDataContexts;
Mngr: IJvDataContextsManager;
begin
Contexts := GetContexts;
if (Contexts <> nil) and Supports(Contexts, IJvDataContextsManager, Mngr) then
Mngr.Clear;
end;
procedure TContextItemsManager.Delete(Index: Integer);
var
Item: IJvDataItem;
begin
Item := Items.GetItem(Index);
if Item <> nil then
Remove(Item);
end;
procedure TContextItemsManager.Remove(var Item: IJvDataItem);
var
Contexts: IJvDataContexts;
Mngr: IJvDataContextsManager;
CtxItem: IJvDataContextItem;
Ctx: IJvDataContext;
begin
Contexts := GetContexts;
if (Contexts <> nil) and Supports(Contexts, IJvDataContextsManager, Mngr) then
begin
if Supports(Item, IJvDataContextItem, CtxItem) then
begin
Ctx := CtxItem.GetContext;
Item := nil;
CtxItem := nil;
Mngr.Delete(Ctx);
end;
end;
end;
//=== { TJvContextProvider } =================================================
function TJvContextProvider.GetProviderIntf: IJvDataProvider;
begin
Result := TContextRootItems(DataItemsImpl).ClientProvider;
end;
procedure TJvContextProvider.SetProviderIntf(Value: IJvDataProvider);
begin
if Value <> ProviderIntf then
TContextRootItems(DataItemsImpl).ClientProvider := Value;
end;
function TJvContextProvider.GetProviderComp: TComponent;
var
ICR: IInterfaceComponentReference;
begin
if Supports(ProviderIntf, IInterfaceComponentReference, ICR) then
Result := ICR.GetComponent
else
Result := nil;
end;
procedure TJvContextProvider.SetProviderComp(Value: TComponent);
var
PI: IJvDataProvider;
ICR: IInterfaceComponentReference;
begin
if (Value = nil) or Supports(Value, IJvDataProvider, PI) then
begin
if (Value = nil) or Supports(Value, IInterfaceComponentReference, ICR) then
ProviderIntf := PI
else
raise EJVCLException.CreateRes(@RsENotSupportedIInterfaceComponentReference);
end
else
raise EJVCLException.CreateRes(@RsENotSupportedIJvDataProvider);
end;
class function TJvContextProvider.ItemsClass: TJvDataItemsClass;
begin
Result := TContextRootItems;
end;
function TJvContextProvider.ConsumerClasses: TClassArray;
begin
Result := inherited ConsumerClasses;
AddToArray(Result, TJvContextProviderServerNotify);
end;
//=== { TJvContextProviderServerNotify } =====================================
procedure TJvContextProviderServerNotify.ItemSelected(Value: IJvDataItem);
var
CtxItem: IJvDataContextItem;
Ctx: IJvDataContext;
I: Integer;
ConCtx: IJvDataConsumerContext;
begin
// First we allow the default behavior to take place
inherited ItemSelected(Value);
// Now we find out which context is selected and update the linked client consumers accordingly.
if Supports(Value, IJvDataContextItem, CtxItem) then
Ctx := CtxItem.GetContext
else
Ctx := nil;
for I := 0 to Clients.Count - 1 do
if Supports(Clients[I], IJvDataConsumerContext, ConCtx) then
ConCtx.SetContext(Ctx);
end;
function TJvContextProviderServerNotify.IsValidClient(Client: IJvDataConsumerClientNotify): Boolean;
var
ClientProv: IJvDataProvider;
ConsumerProv: IJvDataConsumerProvider;
begin
{ Only allow client consumers whose Provider points to the ClientProvider of the context
provider this consumer is linked to. }
ClientProv := (ConsumerImpl.ProviderIntf as IJvDataContextProvider).ClientProvider;
Result := Supports(Client, IJvDataConsumerProvider, ConsumerProv) and
(ConsumerProv.GetProvider = ClientProv);
end;
initialization
{$IFDEF UNITVERSIONING}
RegisterUnitVersion(HInstance, UnitVersioning);
{$ENDIF UNITVERSIONING}
RegisterClasses([TJvContextProviderServerNotify]);
{$IFDEF UNITVERSIONING}
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end. |
unit artPageNameEditFrm;
interface
uses
Forms, cxLookAndFeelPainters, cxDBEdit, cxControls, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, StdCtrls, cxButtons, Controls, ExtCtrls, Classes,
cxCheckBox, ActnList;
type
TPageNameEditForm = class(TForm)
Panel2: TPanel;
Cancel: TcxButton;
OK: TcxButton;
Label1: TLabel;
Label7: TLabel;
name: TcxDBMaskEdit;
ReSetName: TcxButton;
title: TcxDBTextEdit;
is_visible: TcxDBCheckBox;
ActionList: TActionList;
ActionOK: TAction;
procedure ReSetNameClick(Sender: TObject);
procedure titlePropertiesEditValueChanged(Sender: TObject);
procedure ActionOKExecute(Sender: TObject);
end;
function GetPageNameEditForm: Integer;
implementation
uses SysUtils, artDataModule, DeviumLib;
{$R *.dfm}
function GetPageNameEditForm: Integer;
var
Form: TPageNameEditForm;
begin
Form := TPageNameEditForm.Create(Application);
try
Result := Form.ShowModal;
finally
Form.Free;
end;
end;
procedure TPageNameEditForm.ReSetNameClick(Sender: TObject);
begin
name.DataBinding.Field.Value := TransLiterStr(Trim(title.Text));
end;
procedure TPageNameEditForm.titlePropertiesEditValueChanged(
Sender: TObject);
begin
if Length(name.Text) = 0 then
ReSetNameClick(nil);
end;
procedure TPageNameEditForm.ActionOKExecute(Sender: TObject);
begin
OK.SetFocus;
ModalResult := mrOK;
end;
end.
|
unit funcionalidad;
interface
uses listas2, tipos;
type
tAgenda = record
lista:tLista;
end;
function buscarContacto(agenda:tAgenda; buscar:string; var contacto:tContacto):boolean;
function agregarContacto(var agenda:tAgenda; contacto:tContacto):boolean;
procedure listarContactos(agenda:tAgenda);
function eliminarContacto(var agenda:tAgenda; buscar:string; var x:tContacto):boolean;
procedure limpiar(var contacto:tContacto);
implementation
procedure inicializarContacto(var contacto:tContacto);
begin
contacto.idPersona := 0;
contacto.nombre := '';
contacto.telefono := 0;
contacto.domicilio := '';
end;
procedure listarContactos(var agenda:tAgenda);
begin
with agenda do
primerolista(lista);
while not finlista(lista)
begin
mostrarContacto(lista.actual^.info);
siguientelista(lista);
end;
end;
end;
procedure mostrarContacto(var contacto:tContacto);
begin
writeln('idPersona: ', contacto.idPersona);
writeln('nombre: ', contacto.nombre);
writeln('telefono: ', contacto.telefono);
writeln('domicilio: ', contacto.domicilio);
end;
function buscarContacto(agenda:tAgenda; buscar:string; var contacto:tContacto):boolean;
var
item:pNodo;
begin
if not buscarLista(agenda.lista, buscar, item) then
buscarContacto := false
else
begin
contacto := leerLista(agenda.lista, item);
buscarContacto := true;
end;
end;
procedure cargarContacto(var contacto:tContacto);
var
aux:tContacto;
begin
write('Ingrese apellido y nombre (', contacto.nombre , '): ');
readln(aux.nombre);
write('Ingrese telefono (', contacto.telefono, '): ');
readln(aux.telefono);
write('Ingrese domicilio (', contacto.domicilio, '): ');
readln(aux.domicilio);
if aux.nombre <> '' then contacto.nombre := aux.nombre;
if aux.telefono <> 0 then contacto.telefono := aux.telefono;
if aux.domicilio <> '' then contacto.domicilio := aux.domicilio;
end;
function agregarContacto(var agenda:tAgenda; contacto:tContacto):boolean;
begin
agregarContacto := agregarLista(agenda.lista, contacto);
end;
function eliminarContacto(var agenda:tAgenda; buscar:string; var x:tContacto):boolean;
var
exito:boolean;
begin
removerLista(agenda.lista, buscar, x, exito);
eliminarContacto := exito;
end;
procedure opcionAgregarContacto(var agenda:tAgenda);
var
contacto:tContacto;
begin
inicializarContacto(contacto);
cargarContacto(contacto);
if agregarContacto(agenda, contacto) then
writeln('Contacto agregado correctamente')
else
writeln('Error al agregar contacto');
end;
procedure opcionListarContactos(agenda:tAgenda);
begin
listarContactos(agenda)
end;
procedure opcionBuscarContacto(agenda:tAgenda);
var
nombre:string;
contacto:tContacto;
begin
writeln('Ingrese el nombre de la persona que desea buscar: ');
read(nombre);
if buscarContacto(agenda, nombre, contacto) then
mostrarContacto(contacto)
else
writeln('Error, contacto no encontrado');
end;
procedure opcionModificarContacto(var agenda:tAgenda);
var
contacto, x:tContacto;
nombre:string;
begin
writeln('Ingrese el nombre de la persona que desea buscar: ');
readln(nombre);
if buscarContacto(agenda, nombre, contacto) then
begin
cargarContacto(contacto);
if eliminarContacto(agenda, nombre, x) then
agregarContacto(agenda, contacto)
end
else
writeln('Error, contacto no encontrado');
end;
procedure opcionRemoverContacto(var agenda:tAgenda);
var
contacto:tContacto;
nombre:string;
begin
writeln('Ingrese el nombre de la persona que desea buscar: ');
readln(nombre);
if eliminarContacto(agenda, nombre, contacto) then
begin
mostrarContacto(contacto);
writeln('Contacto eliminado correctamente');
end
else
writeln('Error, contacto no encontrado');
end;
end. |
unit LogManager;
{$mode objfpc}{$H+}
{$INTERFACES CORBA}
interface
uses
Classes, SysUtils,
LogWriter, LogItem, JobThread;
type
{
TLogManager
After creation it is necessary to assign StandardLogTagToString property.
}
TLogManager = class(TComponent)
public
constructor Create(const aOwner: TComponent); reintroduce;
private
fDeferredWriters: TFPList;
fImmediateWriters: TFPList;
fJobThread: TJobThread;
fStandardLogTagToString: IStandardLogTagToString;
fItemCounter: integer;
procedure Initialize;
procedure WriteDeferred(const aItem: PLogItem);
procedure WriteImmediate(const aItem: PLogItem);
procedure Finalize;
public
property DeferredWriters: TFPList read fDeferredWriters;
property ImmediateWriters: TFPList read fImmediateWriters;
property JobThread: TJobThread read fJobThread;
property StandardLogTagToString: IStandardLogTagToString
read fStandardLogTagToString write fStandardLogTagToString;
property ItemCounter: integer read fItemCounter;
procedure Write(const aItem: PLogItem);
destructor Destroy; override;
end;
implementation
type
{ TWriteLogItemJob }
TWriteLogItemJob = class(TInterfacedObject, IThreadJob)
public
constructor Create(const aItem: PLogItem; const aWriters: TFPList);
private
fItem: PLogItem;
fWriters: TFPList;
public
property Item: PLogItem read fItem;
property Writers: TFPList read fWriters;
procedure Execute(const aThread: TJobThread);
end;
{ TWriteLogItemJob }
constructor TWriteLogItemJob.Create(const aItem: PLogItem; const aWriters: TFPList);
begin
inherited Create;
fItem := aItem;
fWriters := aWriters;
end;
procedure TWriteLogItemJob.Execute(const aThread: TJobThread);
var
p: pointer;
writer: ILogWriter;
begin
for p in Writers do
begin
writer := ILogWriter(p);
writer.Write(aThread, Item);
end;
dispose(Item, Done);
end;
{ TLogManager }
constructor TLogManager.Create(const aOwner: TComponent);
begin
inherited Create(aOwner);
Initialize;
end;
procedure TLogManager.Initialize;
begin
fDeferredWriters := TFPList.Create;
fImmediateWriters := TFPList.Create;
fJobThread := TJobThread.Create;
JobThread.Start; // Why no? We can start it right now. Idea: make deferred start.
fItemCounter := 0;
end;
procedure TLogManager.WriteDeferred(const aItem: PLogItem);
var
job: IThreadJob;
begin
job := TWriteLogItemJob.Create(aItem, DeferredWriters);
JobThread.Add(job);
end;
procedure TLogManager.WriteImmediate(const aItem: PLogItem);
var
p: pointer;
writer: ILogWriter;
begin
for p in ImmediateWriters do
begin
writer := ILogWriter(p);
writer.Write(nil, aItem);
end;
end;
procedure TLogManager.Finalize;
begin
JobThread.Terminate;
JobThread.WaitFor;
FreeAndNil(fJobThread);
FreeAndNil(fDeferredWriters);
FreeAndNil(fImmediateWriters);
end;
procedure TLogManager.Write(const aItem: PLogItem);
begin
inc(fItemCounter);
aItem^.Number := ItemCounter;
WriteImmediate(aItem);
WriteDeferred(aItem);
end;
destructor TLogManager.Destroy;
begin
Finalize;
inherited Destroy;
end;
end.
|
unit untDatabaseParameters;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, untUtils;
type
{ TDatabaseParameters }
TDatabaseParameters = class
type
ParameterType = (ptInt32, ptInt64, ptBool, ptWStr, ptByteArray,ptString);
type
{ ValueStore }
{ DBParameter }
DBParameter = class
PArray: Pointer;
PType: ParameterType;
PSize: integer;
PName: string;
constructor Create(ParameterName: string; PValue: Pointer; ParameterSize: integer;
TypeOfParameter: ParameterType);
function GetInt32:Int32;
function GetInt64:Int64;
function GetBool:Boolean;
function GetWideString:WideString;
function GetByteArray:ByteArray;
function GetAnsiString:string;
end;
private
Parameters: array of DBParameter;
function AddValue(Parameter: DBParameter): boolean;overload;
public
constructor Create;
destructor Destroy;
function AddValue(ParameterName: string; PValue: Pointer; ParameterSize: integer;
TypeOfParameter: ParameterType): boolean; overload;
function GetItem(Index:integer):DBParameter;
end;
implementation
{ TDatabaseParameters }
constructor TDatabaseParameters.Create;
begin
SetLength(Parameters, 0);
end;
destructor TDatabaseParameters.Destroy;
begin
SetLength(Parameters, 0);
end;
//function TDatabaseParameters.AddValue(ParameterName: string; PValue: Pointer; ParameterSize: integer;
// TypeOfParameter: ParameterType): boolean;
//begin
// SetLength(Parameters, Length(Parameters)+1);
// Parameters[Length(Parameters)-1]:=DBParameter.Create(ParameterName, PValue,
// ParameterSize, TypeOfParameter);
//end;
function TDatabaseParameters.AddValue(Parameter: DBParameter): boolean;
begin
SetLength(Parameters, Length(Parameters)+1);
Parameters[Length(Parameters)-1]:=Parameter;
end;
function TDatabaseParameters.GetItem(Index: integer): DBParameter;
begin
if((Length(Parameters)=0) or (Index >(Length(Parameters)-1))) then Result:=nil
else Result:=Parameters[Index];
end;
function TDatabaseParameters.AddValue(ParameterName: string; PValue: Pointer;
ParameterSize: integer; TypeOfParameter: ParameterType): boolean;
begin
SetLength(Parameters, Length(Parameters)+1);
Parameters[Length(Parameters)-1]:=DBParameter.Create(ParameterName, PValue, ParameterSize, TypeOfParameter);
end;
{ TDatabaseParameters.DBParameter }
constructor TDatabaseParameters.DBParameter.Create(ParameterName: string;
PValue: Pointer; ParameterSize: integer; TypeOfParameter: ParameterType);
begin
PName:=ParameterName;
PArray:=PValue;
PSize:=ParameterSize;
end;
function TDatabaseParameters.DBParameter.GetInt32: Int32;
begin
Result:=Unaligned(pInt32(PArray)^);
end;
function TDatabaseParameters.DBParameter.GetInt64: Int64;
begin
Result:=Unaligned(PInt64(PArray)^);
end;
function TDatabaseParameters.DBParameter.GetBool: Boolean;
begin
Result:=Unaligned(PBoolean(PArray)^);
end;
function TDatabaseParameters.DBParameter.GetWideString: WideString;
begin
SetLength(Result, PSize);
Move(PWideChar(PArray)^, Result, sizeof(WideChar)* PSize);
end;
function TDatabaseParameters.DBParameter.GetByteArray: ByteArray;
begin
SetLength(Result, PSize);
Copy(PChar(PArray), Result[0], Sizeof(byte)* PSize);
end;
function TDatabaseParameters.DBParameter.GetAnsiString: string;
begin
SetLength(Result, PSize);
Move(PArray, Result[1], sizeof(Char)* PSize);
end;
end.
|
unit ImageRis;
interface
uses
Graphics;
var
ColrBack: Tcolor;
Type
Tviz=class(TObject)
ColrLine: Tcolor;
Canvas: Tcanvas;
x,y,r,r1,r2,l: word;
Procedure Ris; virtual; abstract;
Procedure Draw(bl:boolean);
Procedure Show;
Procedure Hide;
end;
Tkrug=class(Tviz)
x1,y1,x2,y2:word;
Constructor Create(x0,y0,r0:word; ColrLine0:TColor; canvas0:TCanvas);
Procedure Ris;override;
end;
Tkvad=class(Tkrug)
Procedure Ris; override;
end;
TKrPr=class(Tkrug)
dy1: word;
Constructor Create(x0,y0,r0,dy0:word; ColrLine0:TColor; canvas0:TCanvas);
Procedure Ris; override;
end;
TShar=class(Tkrug)
x10,y10: word;
Constructor Create(x0,y0,r10,r20,l0:word; ColrLine0:TColor; canvas0:TCanvas);
Procedure Ris; override;
end;
implementation
Procedure Tviz.Draw;
begin
with Canvas do
begin
if bl then
begin
pen.Color:=colrLine;
brush.Color:=clYellow;
end
else
begin
pen.Color:=ColrBack;
Brush.Color:=ColrBack;
end;
Ris;
end;
end;
Procedure Tviz.Show;
begin
Draw(true);
end;
Procedure Tviz.Hide;
begin
Draw(False);
end;
//TKrug
Constructor Tkrug.Create;
begin
colrLine:=colrLine0;
canvas:=canvas0;
x:=x0; y:=y0; r:=r0;
end;
Procedure Tkrug.Ris;
begin
x1:=x-r; x2:=x+r; y1:=y-r; y2:=y+r;
Canvas.Ellipse(x1,y1,x2,y2);
end;
//TKvad
Procedure Tkvad.Ris;
begin
x1:=x-r; x2:=x+r; y1:=y-r; y2:=y+r;
Canvas.Rectangle(x1,y1,x2,y2);
end;
//TShar
Constructor TShar.Create;
begin
colrLine:=colrLine0;
canvas:=canvas0;
x:=x0;
y:=y0;
x10:=x0;
y10:=y0;
r1:=r10;
r2:=r20;
l:=l0;
end;
Procedure Tshar.Ris;
begin
x1:=x-r1; x2:=x+r1; y1:=y-r2; y2:=y+r2;
with canvas do
begin
Ellipse(x1,y1,x2,y2);
MoveTo(x,y2);
LineTo(x,y2+l);
end;
end;
//TKrPr
Constructor TKrPr.Create;
begin
dy1:=dy0;
Inherited Create(x0,y0,r0,colrLine0,canvas0);
end;
Procedure TkrPr.Ris;
begin
Inherited ris;
Canvas.Rectangle(x1,y2,x2,y2+dy1);
end;
end.
|
UNIT constants;
INTERFACE
CONST
// CONSTANTES DU MOTEUR DAFFICHAGE
FOR_TAB : ARRAY [0..12] OF STRING = (' ','{}','**','++', ')(','[]','##', '<>', '><', 'OO', '||', '/\', '@@');
NUMBERED_COLS = FALSE;
TAILLE_GRILLE = 75;
// CONSTANTES DU MOTEUR DE JEU
COULEUR_ROUGE = 1;
COULEUR_VERT = 2;
COULEUR_ORANGE = 3;
COULEUR_CYAN = 4;
COULEUR_VIOLET = 5;
COULEUR_BLEU = 6;
COULEUR_NULL = 0;
FORME_ROND = 1; // {}
FORME_TREFLE = 2; // **
FORME_ETOILE = 3; // ++
FORME_CROIX = 4; // )(
FORME_CARRE = 5; // []
FORME_LOSANGE = 6; // ##
FORME_NULL = 0; //
COL_BLACK = 0;
COL_BLUE = 1;
COL_GREEN = 2;
COL_CYAN = 3;
COL_RED = 4;
COL_MAGENTA = 5;
COL_BROWN = 6;
COL_LGRAY = 7;
COL_DGRAY = 8;
COL_LBLUE = 9;
COL_LGREEN = 10;
COL_LCYAN = 11;
COL_LRED = 12;
COL_LMAGENTA = 13;
COL_YELLOW = 14;
COL_WHITE = 15;
IMPLEMENTATION
END.
|
unit ModelBroker;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ModelDataModel, fgl, syncobjs;
type
TObserverList = specialize TFPGInterfacedObjectList<IObserver>;
TModelBroker = class;
{ TBrokerThread
is a thread that is used in TModelBroker and notifies all observers }
TBrokerThread = class(TThread)
private
FBroker: TModelBroker;
procedure SetBroker(AValue: TModelBroker);
protected
procedure Execute; override;
public
{ A broker that owns this thread }
property Broker: TModelBroker read FBroker write SetBroker;
end;
{ TModelBroker
is a default implementation of IBroker }
TModelBroker = class(TInterfacedObject, IBroker)
private
{ List of subscribed observers }
FSubscribedObservers: TObserverList;
{ This flag indicates whether observers should be notified }
FNotify: boolean;
{ Critical section for access to other fields }
FCS: TCriticalSection;
{ A thread that notifies all observers }
FInternalThread: TBrokerThread;
public
constructor Create;
procedure Subscribe(AObserver: IObserver);
procedure Unsubscribe(AObserver: IObserver);
procedure NotifyAllObservers;
destructor Destroy; override;
end;
TBrokerList = specialize TFPGInterfacedObjectList<IBroker>;
{ TModelObserver
is a default implementation of IObserver}
TModelObserver = class(TInterfacedObject, IObserver)
private
{List of brokers for which this observer is subscribed
WARNING: if you subscribe observer vie IBroker.Subscribe,
this list will not be filled}
FBrokerList: TBrokerList;
FNotify: TVKCMNotifyEvent;
public
constructor Create;
function GetNotify: TVKCMNotifyEvent;
procedure SetNotify(AValue: TVKCMNotifyEvent);
property Notify: TVKCMNotifyEvent read FNotify write SetNotify;
procedure Subscribe(ABroker: IBroker);
procedure Unsubscribe(ABroker: IBroker);
procedure MessageToBrokers;
procedure UnsubscribeFromAll;
destructor Destroy; override;
end;
{Instance of global broker for model}
function ModelBroker: IBroker;
implementation
var
gBroker: IBroker;
function ModelBroker: IBroker;
begin
if not Assigned(gBroker) then
gBroker := TModelBroker.Create;
Result := gBroker;
end;
{ TModelObserver }
constructor TModelObserver.Create;
begin
FBrokerList := TBrokerList.Create;
end;
function TModelObserver.GetNotify: TVKCMNotifyEvent;
begin
Result := FNotify;
end;
procedure TModelObserver.SetNotify(AValue: TVKCMNotifyEvent);
begin
FNotify := AValue;
end;
procedure TModelObserver.Subscribe(ABroker: IBroker);
begin
ABroker.Subscribe(Self);
FBrokerList.Add(ABroker);
end;
procedure TModelObserver.Unsubscribe(ABroker: IBroker);
begin
ABroker.Unsubscribe(Self);
FBrokerList.Remove(ABroker);
end;
procedure TModelObserver.MessageToBrokers;
var
i: integer;
begin
for i := 0 to FBrokerList.Count - 1 do
begin
FBrokerList[i].NotifyAllObservers;
end;
end;
procedure TModelObserver.UnsubscribeFromAll;
var
i: integer;
begin
for i := 0 to FBrokerList.Count - 1 do
begin
Unsubscribe(FBrokerList[i]);
end;
end;
destructor TModelObserver.Destroy;
begin
FreeAndNil(FBrokerList);
inherited Destroy;
end;
{ TBrokerThread }
procedure TBrokerThread.SetBroker(AValue: TModelBroker);
begin
if FBroker = AValue then
Exit;
FBroker := AValue;
end;
procedure TBrokerThread.Execute;
var
i: integer;
begin
if not Assigned(FBroker) then
raise Exception.Create('Thread started with no broker');
while not Terminated do
begin
FBroker.FCS.Acquire;
try
if FBroker.FNotify then
begin
FBroker.FNotify := False;
for i := 0 to FBroker.FSubscribedObservers.Count - 1 do
begin
if Assigned(FBroker.FSubscribedObservers[i].Notify) then
FBroker.FSubscribedObservers[i].Notify();
end;
end;
finally
FBroker.FCS.Release;
end;
end;
end;
{ TModelBroker }
constructor TModelBroker.Create;
begin
FNotify := False;
FCS := TCriticalSection.Create;
FSubscribedObservers := TObserverList.Create;
FInternalThread := TBrokerThread.Create(True);
FInternalThread.Broker := Self;
FInternalThread.FreeOnTerminate := False;
FInternalThread.Start;
end;
procedure TModelBroker.Subscribe(AObserver: IObserver);
begin
FCS.Enter;
try
if FSubscribedObservers.IndexOf(AObserver) <> -1 then
raise Exception.Create(
'Trying to subscribe an observer that is currently subscribed');
FSubscribedObservers.Add(AObserver);
finally
FCS.Leave;
end;
end;
procedure TModelBroker.Unsubscribe(AObserver: IObserver);
begin
FCS.Enter;
try
FSubscribedObservers.Remove(AObserver);
finally
FCS.Leave;
end;
end;
procedure TModelBroker.NotifyAllObservers;
begin
FCS.Enter;
try
FNotify := True;
finally
FCS.Leave;
end;
end;
destructor TModelBroker.Destroy;
begin
FInternalThread.Terminate;
FInternalThread.WaitFor;
FreeAndNil(FInternalThread);
FreeAndNil(FSubscribedObservers);
FreeAndNil(FCS);
end;
end.
|
unit Server.Models.Movimentos.CampanhasClientes;
interface
uses
System.Classes,
DB,
System.SysUtils,
Generics.Collections,
/// orm
dbcbr.mapping.attributes,
dbcbr.types.mapping,
ormbr.types.lazy,
ormbr.types.nullable,
dbcbr.mapping.register,
Server.Models.Base.TabelaBase;
type
[Entity]
[Table('campanhas_clientes','')]
[PrimaryKey('CODIGO', TableInc, NoSort, False, 'Chave primária')]
TCampanhasClientes = class(TTabelaBase)
private
fMANUAL: String;
fTELEFONE_LIGADO: String;
fDESC_FONE2: String;
fDESC_FONE3: String;
fFIDELIZA: String;
fDESC_FONE1: String;
fCampanha: Integer;
fCliente: Integer;
fCONCLUIDO: String;
fOPERADOR: Integer;
fDT_AGENDAMENTO: TDateTime;
fDT_RESULTADO: String;
fFONE2: String;
fFONE3: String;
fRESULTADO: Integer;
fFONE1: String;
fOPERADOR_LIGACAO: Integer;
fORDEM: Integer;
fAGENDA: Integer;
fDATA_HORA_FIM: TDateTime;
fDATA_HORA_LIG: TDateTime;
function Getid: Integer;
procedure Setid(const Value: Integer);
{ Private declarations }
// function Getid: Integer;
// procedure Setid(const Value: Integer);
public
constructor create;
destructor destroy; override;
{ Public declarations }
[Restrictions([NotNull, Unique])]
[Column('CODIGO', ftInteger)]
[Dictionary('CODIGO','','','','',taCenter)]
property id: Integer read Getid write Setid;
[Column('CLIENTE', ftInteger)]
property Cliente: Integer read fCliente write fCliente;
[Column('CAMPANHA', ftInteger)]
property Campanha: Integer read fCampanha write fCampanha;
[Column('DT_RESULTADO', ftString)]
property DT_RESULTADO: String read fDT_RESULTADO write fDT_RESULTADO;
[Column('DT_AGENDAMENTO', ftDateTime)]
property DT_AGENDAMENTO: TDateTime read fDT_AGENDAMENTO write fDT_AGENDAMENTO;
[Column('RESULTADO', ftInteger)]
property RESULTADO: Integer read fRESULTADO write fRESULTADO;
[Column('CONCLUIDO', ftString)]
property CONCLUIDO: String read fCONCLUIDO write fCONCLUIDO;
[Column('FONE1', ftString)]
property FONE1: String read fFONE1 write fFONE1;
[Column('FONE2', ftString)]
property FONE2: String read fFONE2 write fFONE2;
[Column('FONE3', ftString)]
property FONE3: String read fFONE3 write fFONE3;
[Column('ORDEM', ftInteger)]
property ORDEM: Integer read fORDEM write fORDEM;
[Column('OPERADOR', ftInteger)]
property OPERADOR: Integer read fOPERADOR write fOPERADOR;
[Column('OPERADOR_LIGACAO', ftInteger)]
property OPERADOR_LIGACAO: Integer read fOPERADOR_LIGACAO write fOPERADOR_LIGACAO;
[Column('DATA_HORA_LIG', ftDateTime)]
property DATA_HORA_LIG: TDateTime read fDATA_HORA_LIG write fDATA_HORA_LIG;
[Column('TELEFONE_LIGADO', ftString)]
property TELEFONE_LIGADO: String read fTELEFONE_LIGADO write fTELEFONE_LIGADO;
[Column('DATA_HORA_FIM', ftDateTime)]
property DATA_HORA_FIM: TDateTime read fDATA_HORA_FIM write fDATA_HORA_FIM;
[Column('AGENDA', ftInteger)]
property AGENDA: Integer read fAGENDA write fAGENDA;
[Column('DESC_FONE1', ftString)]
property DESC_FONE1: String read fDESC_FONE1 write fDESC_FONE1;
[Column('DESC_FONE2', ftString)]
property DESC_FONE2: String read fDESC_FONE2 write fDESC_FONE2;
[Column('DESC_FONE3', ftString)]
property DESC_FONE3: String read fDESC_FONE3 write fDESC_FONE3;
[Column('FIDELIZA', ftString)]
property FIDELIZA: String read fFIDELIZA write fFIDELIZA;
[Column('MANUAL', ftString)]
property MANUAL: String read fMANUAL write fMANUAL;
end;
implementation
{ TCampanhasClientes }
constructor TCampanhasClientes.create;
begin
//
end;
destructor TCampanhasClientes.destroy;
begin
//
inherited;
end;
function TCampanhasClientes.Getid: Integer;
begin
Result := fid;
end;
procedure TCampanhasClientes.Setid(const Value: Integer);
begin
fid := Value;
end;
initialization
TRegisterClass.RegisterEntity(TCampanhasClientes);
end.
|
{$include kode.inc}
unit kode_canvas_gdi;
{.$define KODE_DEFAULTPENWIDTH := 0}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
KODE_WINDOWS_UNIT,
kode_bitmap,
kode_array,
kode_color,
//kode_debug,
kode_rect,
kode_surface;
//kode_win32;
const
KODE_DEFAULTPENWIDTH = 0;
type
KClipStack = specialize KArray<KRect>;
KCanvas_Gdi = class //(KBaseCanvas)
private
FDC : HDC;
//FOldBitmap : HGDIOBJ;
FPenColor : COLORREF;
FBrushColor : COLORREF;
FTextColor : COLORREF;
REC : RECT;
FFont : HFONT;
FPen : HPEN;
FOldPen : HPEN;
FNullPen : HPEN;
FBrush : HBRUSH;
FOldBrush : HBRUSH;
FNullBrush : HBRUSH;
FBlendFunc : BLENDFUNCTION;
//FVisibleRect: KRect;
FClipRect : KRect;
FClipStack : KClipStack;
public
property _dc : HDC read FDC;
property _cliprect : KRect read FClipRect write FClipRect;
//property _visiblerect : KRect read FVisibleRect write FVisibleRect;
public
constructor create(ASurface:KSurface);
destructor destroy; override;
private
procedure _moveTo(AX,AY:longint);
procedure _clearPen;
procedure _resetPen;
procedure _clearBrush;
procedure _resetBrush;
procedure _setPen(AColor:LongWord; AWidth:LongWord=KODE_DEFAULTPENWIDTH);
procedure _setPenWidth(AWidth:LongWord);
procedure _setPenStyle({%H-}AStyle:LongWord);
procedure _setBrush(AColor:LongWord);
procedure _setBrushStyle({%H-}AStyle:LongWord);
public
procedure setDrawColor(AColor:KColor);
procedure setFillColor(AColor:KColor);
procedure setTextColor(AColor:KColor);
procedure setTextSize(ASize:LongWord);
function getTextWidth(AText:PChar) : LongWord;
function getTextHeight(AText:PChar) : LongWord;
procedure drawPoint(AX,AY:LongInt);
procedure drawLine(AX1,AY1,AX2,AY2:LongInt);
procedure drawRect(AX1,AY1,AX2,AY2:LongInt);
procedure drawEllipse(AX1,AY1,AX2,AY2:LongInt);
procedure drawArc(AX1,AY1,AX2,AY2:LongInt; AAngle1,AAngle2:Single);
procedure drawText(AX,AY:LongInt; AText:PChar);
procedure drawText(AX1,AY1,AX2,AY2:LongInt; AText:PChar; AAlign:LongWord);
procedure fillRect(AX1,AY1,AX2,AY2:LongInt);
procedure fillEllipse(AX1,AY1,AX2,AY2:LongInt);
procedure fillArc(AX1,AY1,AX2,AY2:LongInt; AAngle1,AAngle2:Single);
procedure drawSurface(ADstX,ADstY:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
procedure blendSurface(ADstX,ADstY:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
procedure stretchSurface(ADstX,ADstY,ADstW,ADstH:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
procedure tileSurface(ADstX,ADstY,ADstW,ADstH:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
//procedure clip(AX1,AY1,AX2,AY2:LongInt);
procedure clip(ARect:KRect);
procedure noClip;
procedure pushClip(ARect:KRect);
procedure popClip;
function clipIntersection(ARect:KRect) : KRect;
//function visibleIntersection(ARect:KRect) : KRect;
end;
//----------
KCanvas_Implementation = KCanvas_Gdi;
//----------------------------------------------------------------------
{
this gave me an error (linking error) when i moved it into another
unit (kode_win32.pas), so it's included here..
}
{$ifdef KODE_64BIT}
{
these are not defined in the Windows unit..
for 32-bit we use JwaWindows, which defines them..
}
const
DC_BRUSH = 18;
DC_PEN = 19;
function SetDCPenColor(dc:HDC; col:COLORREF) : COLORREF; external 'gdi32' name 'SetDCPenColor';
function SetDCBrushColor(dc:HDC; col:COLORREF) : COLORREF; external 'gdi32' name 'SetDCBrushColor';
function AlphaBlend(dst:HDC;dx,dy,dw,dh:longint; src:HDC; sx,sy,sw,sh:longint; bf:BLENDFUNCTION) : BOOL; external 'msimg32' name 'AlphaBlend';
{$endif KODE_64BIT}
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
Math,
//kode_const,
kode_flags,
kode_math,
kode_memory,
kode_string;//,
//kode_win32;
//----------
constructor KCanvas_Gdi.create(ASurface:KSurface);
var
tempdc : HDC;
LFont : LOGFONT;
lbrush : LOGBRUSH;
begin
inherited create;
tempdc := KODE_WINDOWS_UNIT.GetDC(0);
FDC := KODE_WINDOWS_UNIT.CreateCompatibleDC(tempdc);
//
FPenColor := RGB(255,255,255);
FBrushColor := RGB(192,192,192);
FTextColor := RGB(0,0,0);
// FClipStack := KClipStack.create;
// FClipRect.setup(0,0,ASurface._width,ASurface._height);
//self.noClip;
//FCurrentPen := 0;
//FCurrentBrush := 0;
{ font }
KMemset(@LFont,0,sizeof(LFont));
KStrcpy(LFont.lfFaceName,'Arial');
LFont.lfHeight := -MulDiv(8,GetDeviceCaps(tempdc,LOGPIXELSY),72);
FFont := KODE_WINDOWS_UNIT.CreateFontIndirect(LFont);
KODE_WINDOWS_UNIT.SelectObject(FDC,FFont);
{ }
KODE_WINDOWS_UNIT.ReleaseDC(0,tempdc);
{ pen }
FNullPen := KODE_WINDOWS_UNIT.CreatePen(PS_NULL,0,0);
FPen := KODE_WINDOWS_UNIT.GetStockObject(DC_PEN);
KODE_WINDOWS_UNIT.SelectObject(FDC,FPen);
{ brush }
// http://msdn.microsoft.com/en-us/library/dd145035%28v=VS.85%29.aspx
lbrush.lbStyle := BS_NULL; // BS_HATCHED, BS_HOLLOW, BS_NULL, BS_SOLID, ++
lbrush.lbColor := 0; // ignored if null
lbrush.lbHatch := 0; // if BS_HATCHED: HS_BDIAGONAL, HS_CROSS, HS_DIAGCROSS, HS_FDIAGONAL, HS_HORIZONTAL, HS_VERTICAL
FNullBrush := KODE_WINDOWS_UNIT.CreateBrushIndirect(lbrush);
FBrush := KODE_WINDOWS_UNIT.GetStockObject(DC_BRUSH);
KODE_WINDOWS_UNIT.SelectObject(FDC,FBrush);
{ surface }
{FOldBitmap := }KODE_WINDOWS_UNIT.SelectObject(FDC,ASurface.bitmap);
{ blending }
FBlendFunc.BlendOp := AC_SRC_OVER;
FBlendFunc.BlendFlags := 0;
FBlendFunc.SourceConstantAlpha := 255;//128;//0x7f;
FBlendFunc.AlphaFormat := AC_SRC_ALPHA; // 0 = ignore source alpha channel
{ clip }
//KTrace('creating clip stack');
FClipStack := KClipStack.create;
FClipRect.setup(0,0,ASurface.width,ASurface.height);
//FVisibleRect := FClipRect;
//pushClip(FClipRect);
end;
{
FBlendFunc:
from wingdi.h:
#define AC_SRC_OVER 0x00
#define AC_SRC_ALPHA 0x01
#define AC_SRC_NO_PREMULT_ALPHA 0x01
#define AC_SRC_NO_ALPHA 0x02
#define AC_DST_NO_PREMULT_ALPHA 0x10
#define AC_DST_NO_ALPHA 0x20
}
//----------
destructor KCanvas_Gdi.destroy;
begin
//self..noClip;
FClipStack.destroy;
KODE_WINDOWS_UNIT.DeleteObject(FNullPen);
KODE_WINDOWS_UNIT.DeleteObject(FNullBrush);
KODE_WINDOWS_UNIT.DeleteObject(FFont);
//KODE_WINDOWS_UNIT.SelectObject(FDC,FOldBitmap);
KODE_WINDOWS_UNIT.DeleteDC(FDC);
inherited;
end;
//----------------------------------------
// internal
//----------------------------------------
procedure KCanvas_Gdi._moveTo(AX,AY:longint);
begin
KODE_WINDOWS_UNIT.MoveToEx(FDC,AX,AY,nil);
//FXpos := x;
//FYpos := y;
end;
//----------
procedure KCanvas_Gdi._clearPen;
begin
FOldPen := KODE_WINDOWS_UNIT.SelectObject(FDC,FNullPen);
end;
//----------
procedure KCanvas_Gdi._resetPen;
var
prev : HPEN;
begin
prev := KODE_WINDOWS_UNIT.SelectObject(FDC,FOldPen);
KODE_WINDOWS_UNIT.DeleteObject(prev);
end;
//----------
procedure KCanvas_Gdi._clearBrush;
begin
FOldBrush := KODE_WINDOWS_UNIT.SelectObject(FDC,FNullBrush);
end;
//----------
procedure KCanvas_Gdi._resetBrush;
var
prev : HBRUSH;
begin
prev := KODE_WINDOWS_UNIT.SelectObject(FDC,FOldBrush);
KODE_WINDOWS_UNIT.DeleteObject(prev);
end;
//----------
procedure KCanvas_Gdi._setPen(AColor:LongWord; AWidth:LongWord=KODE_DEFAULTPENWIDTH);
var
pen : HPEN;
begin
pen := KODE_WINDOWS_UNIT.CreatePen(PS_SOLID,aWidth,aColor);
FOldPen := KODE_WINDOWS_UNIT.SelectObject(FDC,pen);
end;
//----------
procedure KCanvas_Gdi._setBrush(AColor:LongWord);
begin
if FBrush <> 0 then
begin
KODE_WINDOWS_UNIT.SelectObject(FDC,FOldBrush);
KODE_WINDOWS_UNIT.DeleteObject(FBrush);
end;
FBrush := KODE_WINDOWS_UNIT.CreateSolidBrush(AColor);
FOldBrush := KODE_WINDOWS_UNIT.SelectObject(FDC,FBrush);
end;
//----------
procedure KCanvas_Gdi._setPenWidth(AWidth:LongWord);
begin
//FPenWidth = aWidth;
_setPen(FPenColor,AWidth);
end;
//----------
procedure KCanvas_Gdi._setPenStyle(AStyle:LongWord);
begin
end;
//----------
procedure KCanvas_Gdi._setBrushStyle(AStyle:LongWord);
begin
end;
//------------------------------
{ internal }
function _rgb(r,g,b:single) : COLORREF; inline;
begin
result := RGB(trunc(r*255),trunc(g*255),trunc(b*255));
end;
//----------
function _rgb(AColor:KColor) : COLORREF; inline;
begin
result := _rgb(AColor.r,AColor.g,AColor.b);
end;
//----------------------------------------
// get/set
//----------------------------------------
procedure KCanvas_Gdi.setDrawColor(AColor:KColor);
begin
FPenColor := _rgb(AColor);
SetDCPenColor(FDC,FPenColor);
end;
//----------
procedure KCanvas_Gdi.setFillColor(AColor:KColor);
begin
FBrushColor := _rgb(AColor);
SetDCBrushColor(FDC,FBrushColor);
end;
//----------
procedure KCanvas_Gdi.setTextColor(AColor:KColor);
begin
FTextColor := _rgb(AColor);
KODE_WINDOWS_UNIT.setTextColor(FDC,FTextColor);
end;
//----------
procedure KCanvas_Gdi.setTextSize(ASize:LongWord);
var
lfont : LOGFONT;
font : HFONT;
begin
//mFont = CreateFontIndirect(&LFont);
//SelectObject(mDC,mFont);
font := {(HFONT)}KODE_WINDOWS_UNIT.GetCurrentObject(FDC,OBJ_FONT);
KODE_WINDOWS_UNIT.GetObject(font,sizeof(LOGFONT),@lfont);
lfont.lfHeight := -KODE_WINDOWS_UNIT.MulDiv(aSize,KODE_WINDOWS_UNIT.GetDeviceCaps(FDC,LOGPIXELSY),72);
if FFont <> 0 then KODE_WINDOWS_UNIT.DeleteObject(FFont);
FFont := KODE_WINDOWS_UNIT.CreateFontIndirect(&lfont);
KODE_WINDOWS_UNIT.SelectObject(FDC,FFont);
end;
//----------
function KCanvas_Gdi.getTextWidth(AText:PChar) : LongWord;
var
S : SIZE;
begin
KODE_WINDOWS_UNIT.GetTextExtentPoint32(FDC,AText, KStrlen(AText),S{%H-});
result := S.cx;
end;
//----------
function KCanvas_Gdi.getTextHeight(AText:PChar) : LongWord;
var
S : SIZE;
begin
KODE_WINDOWS_UNIT.GetTextExtentPoint32(FDC,AText,KStrlen(AText),S{%H-});
result := S.cy;
end;
//----------------------------------------
// shapes
//----------------------------------------
procedure KCanvas_Gdi.drawPoint(AX,AY:LongInt);
begin
KODE_WINDOWS_UNIT.SetPixel(FDC,AX,AY,FPenColor);
end;
//----------
procedure KCanvas_Gdi.drawLine(AX1,AY1,AX2,AY2:LongInt);
begin
//KODE_WINDOWS_UNIT.MoveToEx(FDC,x1,y1,nil);
_moveTo(AX1,AY1);
KODE_WINDOWS_UNIT.LineTo(FDC,AX2,AY2);
KODE_WINDOWS_UNIT.SetPixel(FDC,AX2,AY2,FPenColor); //
end;
//----------
procedure KCanvas_Gdi.drawRect(AX1,AY1,AX2,AY2:LongInt);
begin
//KODE_WINDOWS_UNIT.MoveToEx(FDC,x1,y1,nil);
_moveTo(AX1,AY1);
KODE_WINDOWS_UNIT.LineTo(FDC,AX2,AY1);
KODE_WINDOWS_UNIT.LineTo(FDC,AX2,AY2);
KODE_WINDOWS_UNIT.LineTo(FDC,AX1,AY2);
KODE_WINDOWS_UNIT.LineTo(FDC,AX1,AY1);
end;
//----------
procedure KCanvas_Gdi.drawEllipse(AX1,AY1,AX2,AY2:LongInt);
begin
//Ellipse(mDC, aX1,aY1,aX2,aY2 );
KODE_WINDOWS_UNIT.Arc( FDC,AX1,AY1,AX2+1,AY2+1,0,0,0,0);
end;
//----------
{
angle 1 = start angle, relative to 3 o'clock
angle 2 = 'distance' 0..1, counter-clockwise
}
procedure KCanvas_Gdi.drawArc(AX1,AY1,AX2,AY2:LongInt; AAngle1,AAngle2:Single);
var
a1,a2 : Single;
temp : Single;
x,y,w,h : single;
size : Single;
x1,y1,x2,y2 : single;
begin
if abs(AAngle2) >= 0.01 {/*EPSILON} then
begin
a1 := AAngle1 - 0.25;
a2 := a1 + AAngle2;
if aAngle2 > 0 then
begin
temp := a1;
a1 := a2;
a2 := temp;
end;
w := AX2-AX1;
h := AY2-AY1;
x := AX1 + w*0.5;
y := AY1 + h*0.5;
size := max(w,h);
x1 := x + cos(A1*PI*2) * size;
y1 := y + sin(A1*PI*2) * size;
x2 := x + cos(A2*PI*2) * size;
y2 := y + sin(A2*PI*2) * size;
Arc(FDC,AX1,AY1,AX2,AY2,trunc(x1),trunc(y1),trunc(x2),trunc(y2));
end;
end;
//----------------------------------------
// text
//----------------------------------------
// hack alert!
// draw to a rect size 1000x1000, and align to upper left
procedure KCanvas_Gdi.drawText(AX,AY:LongInt; AText:PChar);
begin
//SetBkMode(mDC,TRANSPARENT);
//TextOut(mDC,aX,aY,aText.ptr(), aText.length() );
drawText( AX,AY, AX+1000,AY+1000, AText, kta_Left or kta_Top);
end;
//----------
procedure KCanvas_Gdi.drawText(AX1,AY1,AX2,AY2:LongInt; AText:PChar; AAlign:LongWord);
var
flags : LongWord;
oldfont : HFONT;
begin
KODE_WINDOWS_UNIT.SetBkMode(FDC,TRANSPARENT);
REC.left := AX1;
REC.top := AY1;
REC.right := AX2;
REC.bottom := AY2;
flags := 0;
if (AAlign and kta_Left) <> 0 then flags := flags or DT_LEFT
else if (AAlign and kta_Right) <> 0 then flags := flags or DT_RIGHT
else flags := flags or DT_CENTER;
if (AAlign and kta_Top) <> 0 then flags := flags or DT_TOP
else if (AAlign and kta_Bottom) <> 0 then flags := flags or DT_BOTTOM
else flags := flags or DT_VCENTER;
oldfont := KODE_WINDOWS_UNIT.SelectObject(FDC,FFont);
KODE_WINDOWS_UNIT.DrawText(FDC,AText,-1,REC,flags {or DT_NOCLIP} or DT_SINGLELINE or DT_NOPREFIX);
KODE_WINDOWS_UNIT.SelectObject(FDC,oldfont);
end;
//----------------------------------------
// filled shapes
//----------------------------------------
{
The FillRect function fills a rectangle by using the specified brush.
This function includes the left and top borders,
but excludes the right and bottom borders of the rectangle.
}
procedure KCanvas_Gdi.fillRect(AX1,AY1,AX2,AY2:LongInt);
begin
REC.left := AX1;
REC.top := AY1;
REC.right := AX2+1; // !!!
REC.bottom := AY2+1; // !!!
KODE_WINDOWS_UNIT.FillRect(FDC,REC,FBrush);
end;
//----------
// The Ellipse function draws an ellipse. The center of the ellipse is the
// center of the specified bounding rectangle. The ellipse is outlined by
// using the current pen and is filled by using the current brush.
procedure KCanvas_Gdi.fillEllipse(AX1,AY1,AX2,AY2:LongInt);
begin
_clearPen;
KODE_WINDOWS_UNIT.Ellipse( FDC,AX1,AY1,AX2,AY2);
_resetPen;
end;
//----------
// angle 1 = start angle, relative to 3 o'clock
// angle 2 = 'distance' 0..1, counter-clockwise
procedure KCanvas_Gdi.fillArc(AX1,AY1,AX2,AY2:LongInt; AAngle1,AAngle2:Single);
var
a1,a2 : Single;
temp : Single;
x,y,w,h : single;
size : Single;
x1,y1,x2,y2 : single;
begin
if Abs(AAngle2) >= 0.01 {EPSILON} then
begin
_clearPen;
a1 := AAngle1 - 0.25;
a2 := a1 + AAngle2;
if AAngle2 > 0 then
begin
temp := a1;
a1 := a2;
a2 := temp;
end;
w := AX2-AX1;
h := AY2-AY1;
x := AX1 + w*0.5;
y := AY1 + h*0.5;
size := Max(w,h);
x1 := x + cos(a1*PI*2) * size;
y1 := y + sin(a1*PI*2) * size;
x2 := x + cos(a2*PI*2) * size;
y2 := y + sin(a2*PI*2) * size;
KODE_WINDOWS_UNIT.Pie(FDC,AX1,AY1,AX2,AY2,trunc(x1),trunc(y1),trunc(x2),trunc(y2));
_resetPen;
end;
end;
//----------------------------------------
// bitmaps
//----------------------------------------
(*
BOOL BitBlt(
HDC hdcDest, // Handle to the destination device context.
int nXDest, // logical x-coordinate of the upper-left corner of the destination rectangle.
int nYDest, // logical y-coordinate of the upper-left corner of the destination rectangle.
int nWidth, // logical width of the source and destination rectangles.
int nHeight, // logical height of the source and the destination rectangles.
HDC hdcSrc, // Handle to the source device context.
int nXSrc, // logical x-coordinate of the upper-left corner of the source rectangle.
int nYSrc, // logical y-coordinate of the upper-left corner of the source rectangle.
DWORD dwRop // raster-operation code.
);
*)
{
constructor:
tempdc := KODE_WINDOWS_UNIT.GetDC(0);
FDC := KODE_WINDOWS_UNIT.CreateCompatibleDC(tempdc);
}
procedure KCanvas_Gdi.drawSurface(ADstX,ADstY:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
var
tempdc : HDC;
begin
tempdc := KODE_WINDOWS_UNIT.CreateCompatibleDC(FDC);
KODE_WINDOWS_UNIT.SelectObject(tempdc,ASurface.bitmap);
KODE_WINDOWS_UNIT.BitBlt(FDC,ADstX,ADstY,ASrcW,ASrcH,tempdc,ASrcX,ASrcY,SRCCOPY);
KODE_WINDOWS_UNIT.DeleteDC(tempdc);
end;
//----------
(*
typedef struct _BLENDFUNCTION {
BYTE BlendOp;
BYTE BlendFlags;
BYTE SourceConstantAlpha;
BYTE AlphaFormat;
} BLENDFUNCTION, *PBLENDFUNCTION, *LPBLENDFUNCTION;
*)
procedure KCanvas_Gdi.blendSurface(ADstX,ADstY:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
var
tempdc : HDC;
begin
//HDC tempdc = (HDC)aImage->getHandle();
//HDC tempdc = (HDC)aSurface->getHandle();
tempdc := KODE_WINDOWS_UNIT.CreateCompatibleDC(FDC);
KODE_WINDOWS_UNIT.SelectObject(tempdc,ASurface.bitmap);
{KODE_WINDOWS_UNIT.}AlphaBlend(FDC,ADstX,ADstY,ASrcW,ASrcH,tempdc,ASrcX,ASrcY,ASrcW,ASrcH,FBlendFunc);
KODE_WINDOWS_UNIT.DeleteDC(tempdc);
// link with: libmsimg32
end;
//----------
{
BOOL AlphaBlend(
_In_ HDC hdcDest,
_In_ int xoriginDest,
_In_ int yoriginDest,
_In_ int wDest,
_In_ int hDest,
_In_ HDC hdcSrc,
_In_ int xoriginSrc,
_In_ int yoriginSrc,
_In_ int wSrc,
_In_ int hSrc,
_In_ BLENDFUNCTION ftn
);
}
procedure KCanvas_Gdi.stretchSurface(ADstX,ADstY,ADstW,ADstH:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
var
tempdc : HDC;
begin
//HDC tempdc = (HDC)aImage->getHandle();
//HDC tempdc = (HDC)aSurface->getHandle();
tempdc := KODE_WINDOWS_UNIT.CreateCompatibleDC(FDC);
KODE_WINDOWS_UNIT.SelectObject(tempdc,ASurface.bitmap);
{KODE_WINDOWS_UNIT.}AlphaBlend(FDC,ADstX,ADstY,ADstW,ADstH,tempdc,ASrcX,ASrcY,ASrcW,ASrcH,FBlendFunc);
KODE_WINDOWS_UNIT.DeleteDC(tempdc);
// link with: libmsimg32
end;
//----------
procedure KCanvas_Gdi.tileSurface(ADstX,ADstY,ADstW,ADstH:LongInt; ASurface:KSurface; ASrcX,ASrcY,ASrcW,ASrcH:LongInt);
var
x,y,w,h : longint;
ww,hh : longint;
begin
//KTrace(['tiled surface: ',ADst.w,',',ADst.h, KODE_CR]);
y := ADstY;
h := ADstH;
while h > 0 do
begin
hh := KMinI(h,ASrcH);
x := ADstX;
w := ADstW;
while w > 0 do
begin
ww := KMinI(w,ASrcW);
//KTrace(['drawing: ',ww,',',hh, KODE_CR]);
drawSurface(x,y,ASurface,ASrcX,ASrcY,ww,hh);
x += ASrcW;
w -= ASrcW;
end;
y += ASrcH;
h -= ASrcH;
end;
end;
//----------------------------------------
// clipping
//----------------------------------------
// http://www.codeproject.com/Articles/2095/A-Guide-to-WIN32-Clipping-Regions
{
CreateRectRgn
http://msdn.microsoft.com/en-us/library/windows/desktop/dd183514%28v=vs.85%29.aspx
Regions created by the Create<shape>Rgn methods (such as CreateRectRgn and
CreatePolygonRgn) only include the interior of the shape; the shape's outline
is excluded from the region. This means that any point on a line between two
sequential vertices is not included in the region. If you were to call
PtInRegion for such a point, it would return zero as the result.
When you no longer need the HRGN object, call the DeleteObject function to
delete it.
SelectClipRgn
http://msdn.microsoft.com/en-us/library/windows/desktop/dd162955%28v=vs.85%29.aspx
The SelectClipRgn function selects a region as the current clipping region for
the specified device context.
To remove a device-context's clipping region, specify a NULL region handle.
Only a copy of the selected region is used. The region itself can be selected
for any number of other device contexts or it can be deleted.
"When you call SelectClipRgn() within a BeginPaint()/EndPaint() block in an
application's WM_PAINT case, the maximum size to which you can set your
clipping region is the size of the update region of your paint structure. In
other words you can use SelectClipRgn() to shrink your update region but not
to grow it".
The BeginPaint function automatically sets the clipping region of the device
context to exclude any area outside the update region.
http://books.google.no/books?id=-O92IIF1Bj4C&pg=PA427&lpg=PA427&dq=SelectClipRgn&source=bl&ots=Sx2GC35hp7&sig=NFtTCTcuzrcBMoHaTJYY998CJww&hl=no&sa=X&ei=3ZvrUpOgJ4bhywOH74DAAg&redir_esc=y#v=onepage&q=SelectClipRgn&f=false
For a device context returned by BeginPaint, GetDC, or CreateDC, the clipping
region is NULL
--------------------------------------------------
http://msdn.microsoft.com/en-us/library/windows/desktop/dd183439%28v=vs.85%29.aspx
if you obtain a device context handle from the BeginPaint function, the DC
contains a predefined rectangular clipping region that corresponds to the
invalid rectangle that requires repainting. However, when you obtain a device
context handle by calling the GetDC function with a NULLhWnd parameter, or by
calling the CreateDC function, the DC does not contain a default clipping
region.
ExcludeClipRect
IntersectClipRect
invalidate -> GetUpdateRect
}
procedure KCanvas_Gdi.clip(ARect:KRect);
var
rgn : HRGN;
begin
//self.noClip;
//rgn := KODE_WINDOWS_UNIT.CreateRectRgn( ARect.x-1, ARect.y-1, ARect.x2+1, ARect.y2+1 );
rgn := KODE_WINDOWS_UNIT.CreateRectRgn( ARect.x-0{1}, ARect.y-0{1}, ARect.x2+1, ARect.y2+1 );
KODE_WINDOWS_UNIT.SelectClipRgn(FDC,rgn);
KODE_WINDOWS_UNIT.DeleteObject(rgn);
//FClipRect := ARect;
//KODE_WINDOWS_UNIT.IntersectClipRect(FDC,ARect.x-0{1}, ARect.y-0{1}, ARect.x2+1, ARect.y2+1 );
end;
//----------
// To remove a device-context's clipping region, specify a NULL region handle.
procedure KCanvas_Gdi.noClip;
begin
KODE_WINDOWS_UNIT.SelectClipRgn(FDC,0);
//FClipRect.setup(0,0,0,0);
end;
//----------
//----------
procedure KCanvas_Gdi.pushClip(ARect:KRect);
//var
// r : KRect;
begin
//self.noClip;
FClipStack.push(FClipRect);
self.clip(ARect);
FClipRect := ARect;
//r := FClipRect.intersection(ARect);
//self.clip(r);
//FClipRect := r;
end;
//----------
procedure KCanvas_Gdi.popClip;
var
r : KRect;
begin
r := FClipStack.pop;
//self.noClip;
self.clip(r);
FClipRect := r;
end;
//----------
function KCanvas_Gdi.clipIntersection(ARect:KRect) : KRect;
begin
result := FClipRect.intersection(ARect);
end;
//----------
{function KCanvas_Gdi.visibleIntersection(ARect:KRect) : KRect;
begin
result := FVisibleRect.intersection(ARect);
end;}
//----------------------------------------------------------------------
end.
|
unit RRManagerEditMainSubstructureInfoFrame;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
RRmanagerBaseObjects, RRManagerObjects, StdCtrls, CommonComplexCombo,
ClientCommon, ExtCtrls, RRManagerBaseGUI;
type
// TfrmMainSubstructureInfo = class(TFrame)
TfrmMainSubstructureInfo = class(TBaseFrame)
gbxAll: TGroupBox;
cmplxTectonicBlock: TfrmComplexCombo;
cmplxLitology: TfrmComplexCombo;
edtSubstructureName: TEdit;
Label1: TLabel;
cmplxBedType: TfrmComplexCombo;
cmplxCollectorType: TfrmComplexCombo;
Label2: TLabel;
cmbxSubstrucureNumber: TComboBox;
cmplxNGK: TfrmComplexCombo;
Bevel1: TBevel;
procedure cmplxTectonicBlockcmbxNameChange(Sender: TObject);
private
function GetSubstructure: TOldSubstructure;
function GetHorizon: TOldHorizon;
{ Private declarations }
protected
procedure FillControls(ABaseObject: TBaseObject); override;
procedure FillParentControls; override;
procedure ClearControls; override;
procedure RegisterInspector; override;
public
{ Public declarations }
property Horizon: TOldHorizon read GetHorizon;
property Substructure: TOldSubstructure read GetSubstructure;
constructor Create(AOwner: TComponent); override;
procedure Save; override;
end;
implementation
uses Facade;
{$R *.DFM}
{ TfrmMainSubstructureInfo }
procedure TfrmMainSubstructureInfo.ClearControls;
begin
cmplxNGK.Clear;
cmplxTectonicBlock.Clear;
edtSubstructureName.Clear;
cmbxSubstrucureNumber.Text := '';
cmplxBedType.Clear;
cmplxCollectorType.Clear;
cmplxLitology.Clear;
if Assigned(Horizon) then
FEditingObject := Horizon.Substructures.Add;
end;
constructor TfrmMainSubstructureInfo.Create(AOwner: TComponent);
begin
inherited;
EditingClass := TOldSubstructure;
ParentClass := TOldHorizon;
cmplxTectonicBlock.Caption := 'Блок, купол';
cmplxTectonicBlock.FullLoad := true;
cmplxTectonicBlock.DictName := 'TBL_STRUCTURE_TECTONIC_ELEMENT';
cmplxBedType.Caption := 'Тип залежи';
cmplxBedType.FullLoad := true;
cmplxBedType.DictName := 'TBL_BED_TYPE_DICT';
cmplxCollectorType.Caption := 'Тип коллектора';
cmplxCollectorType.FullLoad := true;
cmplxCollectorType.DictName := 'TBL_COLLECTOR_TYPE_DICT';
cmplxLitology.Caption := 'Литология коллектора';
cmplxLitology.FullLoad := false;
cmplxLitology.DictName := 'TBL_LITHOLOGY_DICT';
cmplxNGK.Caption := 'Нефтегазоносный комплекс';
cmplxNGK.FullLoad := true;
cmplxNGK.DictName := 'TBL_OIL_COMPLEX_DICT';
Label2.Visible := false;
cmbxSubstrucureNumber.Visible := false;
cmbxSubstrucureNumber.Text := '1';
end;
procedure TfrmMainSubstructureInfo.FillControls(ABaseObject: TBaseObject);
var S: TOldSubstructure;
begin
if not Assigned(ABaseObject) then S := Substructure
else S := ABaseObject as TOldSubstructure;
cmplxTectonicBlock.AddItem(S.StructureElementID, S.StructureElement);
edtSubstructureName.Text := S.RealName;
cmbxSubstrucureNumber.Text := IntToStr(S.Order);
cmplxBedType.AddItem(S.BedTypeID, S.BedType);
cmplxCollectorType.AddItem(S.CollectorTypeID, S.CollectorType);
cmplxLitology.AddItem(S.RockID, S.RockName);
cmplxNGK.AddItem(S.SubComplexID, S.SubComplex);
end;
function TfrmMainSubstructureInfo.GetHorizon: TOldHorizon;
begin
Result := nil;
if EditingObject is TOldHorizon then
Result := EditingObject as TOldHorizon
else if EditingObject is TOldSubstructure then
Result := (EditingObject as TOldSubstructure).Horizon;
end;
function TfrmMainSubstructureInfo.GetSubstructure: TOldSubstructure;
begin
Result := nil;
if EditingObject is TOldSubstructure then
Result := EditingObject as TOldSubstructure
end;
procedure TfrmMainSubstructureInfo.Save;
begin
inherited;
if EditingObject is TOldHorizon then
FEditingObject := Horizon.Substructures.Add;
Substructure.RealName := edtSubstructureName.Text;
if cmbxSubstrucureNumber.Text <> '' then
Substructure.Order := StrToInt(cmbxSubstrucureNumber.Text);
Substructure.SubComplexID := cmplxNGK.SelectedElementID;
Substructure.SubComplex := cmplxNGK.SelectedElementName;
Substructure.StructureElementID := cmplxTectonicBlock.SelectedElementID;
Substructure.StructureElement := cmplxTectonicBlock.SelectedElementName;
Substructure.StructureElementTypeID := GetObjectName((TMainFacade.GetInstance as TMainFacade).AllDicts.DictByName['TBL_STRUCTURE_TECTONIC_ELEMENT'].Dict, Substructure.StructureElementID, 2);
Substructure.StructureElementType := GetObjectName((TMainFacade.GetInstance as TMainFacade).AllDicts.DictByName['TBL_SUBSTRUCTURE_TYPE_DICT'].Dict, Substructure.StructureElementTypeID);
Substructure.BedTypeID := cmplxBedType.SelectedElementID;
Substructure.BedType := cmplxBedType.SelectedElementName;
Substructure.CollectorTypeID := cmplxCollectorType.SelectedElementID;
Substructure.CollectorType := cmplxCollectorType.SelectedElementName;
Substructure.RockID := cmplxLitology.SelectedElementID;
Substructure.RockName := cmplxLitology.SelectedElementName;
end;
procedure TfrmMainSubstructureInfo.cmplxTectonicBlockcmbxNameChange(
Sender: TObject);
begin
cmplxTectonicBlock.cmbxNameChange(Sender);
edtSubstructureName.Text := cmplxTectonicBlock.cmbxName.Text;
end;
procedure TfrmMainSubstructureInfo.FillParentControls;
begin
inherited;
ClearControls;
if Assigned(Horizon) then
cmplxNGK.AddItem(Horizon.ComplexID, Horizon.Complex);
if Assigned(Horizon) and (not Assigned(Substructure)) then
FEditingObject := Horizon.Substructures.Add;
end;
procedure TfrmMainSubstructureInfo.RegisterInspector;
begin
inherited;
Inspector.Add(cmplxTectonicBlock.cmbxName, nil, ptString, 'блок, купол', false);
Inspector.Add(edtSubstructureName, nil, ptString, 'наименование подструктуры', false);
Inspector.Add(cmplxNGK.cmbxName, nil, ptString, 'НГК', false);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.