text stringlengths 14 6.51M |
|---|
unit uMainDM;
// EMS Resource Module
interface
uses
System.SysUtils, System.Classes, System.JSON,
EMS.Services, EMS.ResourceAPI, EMS.ResourceTypes, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys,
FireDAC.Phys.IB, FireDAC.Phys.IBDef, FireDAC.ConsoleUI.Wait, FireDAC.Comp.UI,
FireDAC.Comp.Client, Data.DB, FireDAC.Comp.DataSet, FireDAC.Stan.StorageJSON;
type
[ResourceName('CustomerSync')]
TCustomerSyncResource1 = class(TDataModule)
qryCustomer: TFDQuery;
qryCustomerCUSTNO: TFloatField;
qryCustomerCOMPANY: TStringField;
qryCustomerADDR1: TStringField;
qryCustomerADDR2: TStringField;
qryCustomerCITY: TStringField;
qryCustomerSTATE: TStringField;
qryCustomerZIP: TStringField;
qryCustomerCOUNTRY: TStringField;
qryCustomerPHONE: TStringField;
qryCustomerFAX: TStringField;
qryCustomerTAXRATE: TFloatField;
qryCustomerCONTACT: TStringField;
qryCustomerLASTINVOICEDATE: TSQLTimeStampField;
cnnMastSQL: TFDConnection;
FDTransDefault: TFDTransaction;
FDTransSnapshot: TFDTransaction;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
memCustomerChanges: TFDMemTable;
memCustomerChangesCUSTNO: TFloatField;
memCustomerChangesCOMPANY: TStringField;
memCustomerChangesADDR1: TStringField;
memCustomerChangesADDR2: TStringField;
memCustomerChangesCITY: TStringField;
memCustomerChangesSTATE: TStringField;
memCustomerChangesZIP: TStringField;
memCustomerChangesCOUNTRY: TStringField;
memCustomerChangesPHONE: TStringField;
memCustomerChangesFAX: TStringField;
memCustomerChangesTAXRATE: TFloatField;
memCustomerChangesCONTACT: TStringField;
memCustomerChangesLASTINVOICEDATE: TSQLTimeStampField;
published
procedure Get(const AContext: TEndpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
procedure Post(const AContext: TEndpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
end;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
procedure TCustomerSyncResource1.Get(const AContext: TEndpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
fMemoryStream: TMemoryStream;
sDeviceName, sDBUser, sDBPass: string;
begin
if (not ARequest.Params.TryGetValue('DeviceName', sDeviceName)) or
(not ARequest.Params.TryGetValue('DBUser', sDBUser)) or
(not ARequest.Params.TryGetValue('DBPass', sDBPass)) then
begin
AResponse.Body.SetValue
(TJSONString.Create('All parameters are mandatory!'), True);
exit;
end;
try
cnnMastSQL.Close;
cnnMastSQL.Params.UserName := sDBUser;
cnnMastSQL.Params.Password := sDBPass;
cnnMastSQL.Open;
cnnMastSQL.StartTransaction;
cnnMastSQL.ExecSQL('SET SUBSCRIPTION CUSTOMER_SUB AT ' +
QuotedSTR(sDeviceName) + ' ACTIVE');
qryCustomer.Open;
fMemoryStream := TMemoryStream.Create;
qryCustomer.SaveToStream(fMemoryStream, TFDStorageFormat.sfJSON);
AResponse.Body.SetStream(fMemoryStream, 'application/json', True);
cnnMastSQL.Commit;
except
on E: Exception do
begin
cnnMastSQL.Rollback;
raise Exception.Create('Get error:' + E.Message);
end;
end;
end;
procedure TCustomerSyncResource1.Post(const AContext: TEndpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
fMemoryStream: TStream;
sDeviceName, sDBUser, sDBPass: string;
begin
if (not ARequest.Body.TryGetStream(fMemoryStream)) or
(not ARequest.Params.TryGetValue('DeviceName', sDeviceName)) or
(not ARequest.Params.TryGetValue('DBUser', sDBUser)) or
(not ARequest.Params.TryGetValue('DBPass', sDBPass)) then
begin
AResponse.Body.SetValue
(TJSONString.Create('All parameters are mandatory!'), True);
exit;
end;
try
memCustomerChanges.LoadFromStream(fMemoryStream, TFDStorageFormat.sfJSON);
cnnMastSQL.Close;
cnnMastSQL.Params.UserName := sDBUser;
cnnMastSQL.Params.Password := sDBPass;
cnnMastSQL.Open;
cnnMastSQL.StartTransaction;
qryCustomer.Open;
qryCustomer.MergeDataSet(memCustomerChanges, TFDMergeDataMode.dmDeltaMerge,
TFDMergeMetaMode.mmUpdate);
if qryCustomer.ChangeCount > 0 then
qryCustomer.ApplyUpdates(-1);
cnnMastSQL.Commit;
except
on E: Exception do
begin
cnnMastSQL.Rollback;
raise Exception.Create('Post error:' + E.Message);
end;
end;
end;
procedure Register;
begin
RegisterResource(TypeInfo(TCustomerSyncResource1));
end;
initialization
Register;
end.
|
program abundant;
const
max = 20;
var
count, j: integer;
function is_abundant(n: integer): boolean;
var
sum, i: integer;
begin
sum := 0;
for i := 2 to round(n/2) do
begin
if ( n mod i = 0) then
sum := sum + i;
if (sum > n) then
exit(true);
end;
exit(false);
end;
begin
count := 0;
j := 1;
while ( count < max ) do
begin
if (is_abundant(j)) then
begin
write(j, ' ');
count := count + 1;
end;
j := j + 2;
end;
end.
|
unit fFileProperties;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cMegaROM, iNESImage;
type
TfrmFileProperties = class(TForm)
lblFilename: TLabel;
txtFilename: TEdit;
lblMemoryMapper: TLabel;
lblPRGCount: TLabel;
lblCHRCount: TLabel;
lblFileSize: TLabel;
cmdOK: TButton;
cmdRestoreHeaderToDefault: TButton;
procedure FormShow(Sender: TObject);
procedure cmdRestoreHeaderToDefaultClick(Sender: TObject);
private
_ROMData : TMegamanROM;
procedure Load;
{ Private declarations }
public
property ROMData : TMegamanROM read _ROMData write _ROMData;
{ Public declarations }
end;
var
frmFileProperties: TfrmFileProperties;
implementation
{$R *.dfm}
uses uglobal, inifiles;
procedure TfrmFileProperties.FormShow(Sender: TObject);
begin
Load;
end;
procedure TfrmFileProperties.Load;
begin
txtFilename.Text := ROMData.Filename;
{ lblCHRCount.Caption := 'CHR Count: ' + IntToStr(_ROMdata.ROM.CHRCount);
lblPRGCount.Caption := 'PRG Count: ' + IntToStr(_ROMdata.ROM.PRGCount);
lblMemoryMapper.Caption := 'Memory Mapper: ' + IntToStr(_ROMdata.ROM.MapperNumber) + ' (' + _ROMdata.ROM.MapperName + ')';
if _ROMdata.ROM.DiskDudePresent = True then
lblMemoryMapper.Caption := lblMemoryMapper.Caption + ' (Diskdude Tag Present)';
lblFilesize.Caption := 'File Size: ' + IntToStr(_ROMdata.ROM.ROMSize) + ' bytes';}
end;
procedure TfrmFileProperties.cmdRestoreHeaderToDefaultClick(
Sender: TObject);
begin
ROMData.RestoreDefaultiNESHeader;
Load;
showmessage('Header restored.');
end;
end.
|
unit uLicencaItensVO;
interface
uses
uTableName, uKeyField, System.SysUtils, System.Generics.Collections;
type
[TableName('Licenca_Itens')]
TLicencaItensVO = class
private
FDataLcto: TDate;
FCNPJCPF: string;
FId: Integer;
FDataUtilizacao: TDate;
FLicenca: string;
FSituacao: string;
FLicencaUtilizada: string;
FCodigo: Integer;
FIdCliente: Integer;
procedure SetCNPJCPF(const Value: string);
procedure SetDataLcto(const Value: TDate);
procedure SetDataUtilizacao(const Value: TDate);
procedure SetId(const Value: Integer);
procedure SetLicenca(const Value: string);
procedure SetSituacao(const Value: string);
procedure SetLicencaUtilizada(const Value: string);
procedure SetCodigo(const Value: Integer);
procedure SetIdCliente(const Value: Integer);
public
[KeyField('LicIte_Id')]
property Id: Integer read FId write SetId;
[FieldName('LicIte_Codigo')]
property Codigo: Integer read FCodigo write SetCodigo;
[FieldName('LicIte_CNPJCPF')]
property CNPJCPF: string read FCNPJCPF write SetCNPJCPF;
[FieldDate('LicIte_DataLcto')]
property DataLcto: TDate read FDataLcto write SetDataLcto;
[FieldName('LicIte_Licenca')]
property Licenca: string read FLicenca write SetLicenca;
[FieldDate('LicIte_DataUtilizacao')]
property DataUtilizacao: TDate read FDataUtilizacao write SetDataUtilizacao;
[FieldName('LicIte_Situacao')]
property Situacao: string read FSituacao write SetSituacao;
[FieldName('LicIte_Utilizada')]
property LicencaUtilizada: string read FLicencaUtilizada write SetLicencaUtilizada;
[FieldNull('LicIte_Cliente')]
property IdCliente: Integer read FIdCliente write SetIdCliente;
end;
TListaLicencaItens = TObjectList<TLicencaItensVO>;
implementation
{ TLicencaItensVO }
procedure TLicencaItensVO.SetCNPJCPF(const Value: string);
begin
FCNPJCPF := Value;
end;
procedure TLicencaItensVO.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TLicencaItensVO.SetDataLcto(const Value: TDate);
begin
FDataLcto := Value;
end;
procedure TLicencaItensVO.SetDataUtilizacao(const Value: TDate);
begin
FDataUtilizacao := Value;
end;
procedure TLicencaItensVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TLicencaItensVO.SetIdCliente(const Value: Integer);
begin
FIdCliente := Value;
end;
procedure TLicencaItensVO.SetLicenca(const Value: string);
begin
FLicenca := Value;
end;
procedure TLicencaItensVO.SetLicencaUtilizada(const Value: string);
begin
FLicencaUtilizada := Value;
end;
procedure TLicencaItensVO.SetSituacao(const Value: string);
begin
FSituacao := Value;
end;
end.
|
{
TODO: Resolution change handling -> 163
Loading Cut <> Reverse caption
}
unit MenuFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Cnst, OmSpBtn, MainButtons;
type
TMenuForm = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BtnsOnClick(Sender: TObject);
private
FSize: TPercent;
FFit: TFit;
FDaddysHandle: THandle;
FFullScreen: Boolean;
FCutCaption,
FReverseCaption: String;
{ Resolution which has been fitted }
FitResolution: Integer;
{ Calculating by increasing bits the Resolution }
function Resolution: Integer;
{ Checking if the resolution has ben changed }
function ChangedResolution: Boolean;
{ Creating buttons }
procedure CreateButtons;
public
Buttons: TButtonsHandler;
procedure SetButtons;
{ Calculating & setting the size of MenuForm }
procedure FormSize(FullScreen: Boolean);
{ Calculating & setting the position of MenuForm }
procedure FormPosition(FullScreen: Boolean);
procedure FullScreen(Full: Boolean);
{ Storing the Percent size of MenuForm }
property Size: TPercent read FSize write FSize;
{ Storing the Fit of MenuForm }
property Fit: TFit read FFit write FFit;
property DaddysHandle: THandle read FDaddysHandle write FDaddysHandle;
property FullScr: Boolean read FFullScreen;
property CutCaption: String read FCutCaption write FCutCaption;
property ReverseCaption: String read FReverseCaption write FReverseCaption;
end;
var
MenuForm: TMenuForm;
implementation
uses UploadFrm;
{$R *.dfm}
function TMenuForm.Resolution: Integer;
begin
{ Bits increasing }
Result:=Screen.Width or Screen.Height;
end;
function TMenuForm.ChangedResolution: Boolean;
begin
if(Resolution=FitResolution)then
Result:=False
else
Result:=True;
end;
procedure TMenuForm.FormSize;
begin
{ Setting MenuForm size }
if(FullScreen)then begin
// Left:=1;
// Top:=1;
Width:=Screen.Width;
Height:=Screen.Height;
end else begin
if(Fit in[0..1])then begin
{ Horizontal }
Width:=Screen.Width;
Height:=(Size*Screen.Height)div 100;
end else begin
{ Vertical }
Height:=Screen.Height;
Width:=(Size*Screen.Width)div 100;
end;
end;
end;
procedure TMenuForm.FormPosition;
begin
{ Setting the MenuForm position }
if(FullScreen)then begin
Left:=1;
Top:=1;
end else
case FFit of
{ Horizontal, fit bottom }
0: begin
Left:=0;
Top:=Screen.Height-Height;
end;
{ Vertical, fit to the right }
3: begin
Top:=0;
Left:=Screen.Width-Width;
end;
{ Horizontal, fit to the top & Vertical, fit to the left }
else begin
Left:=0;
Top:=0;
end;
end;
end;
procedure TMenuForm.CreateButtons;
var
I: Integer;
begin
for I:=Low(BUTTONS_LIST) to Length(BUTTONS_LIST)-1 do
Buttons.Add(BUTTONS_LIST[I]);
end;
procedure TMenuForm.FormCreate(Sender: TObject);
begin
ShowWindow(Application.Handle, SW_HIDE);
SetWindowLong(Application.Handle, GWL_EXSTYLE,
getWindowLong(Application.Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW);
ShowWindow(Application.Handle, SW_SHOW);
Buttons:=TButtonsHandler.Create(MenuForm);
CreateButtons;
SetButtons;
FFullScreen:=True;
end;
procedure TMenuForm.FormDestroy(Sender: TObject);
begin
Buttons.Free;
end;
procedure TMenuForm.BtnsOnClick(Sender: TObject);
begin
if(Sender is TomSpeedBtn)then begin
if((Sender as TomSpeedBtn).Name=BUTTON_CUT)then
if not(FFullScreen)then
PostMessage(FDaddysHandle, WM_CUT_MODE, 0, 0)
else
PostMessage(FDaddysHandle, WM_REVERSE, 0, 0);
if((Sender as TomSpeedBtn).Name=BUTTON_PAINT)then
PostMessage(FDaddysHandle, WM_PAINT_EDIT, 0, 0);
if((Sender as TomSpeedBtn).Name=BUTTON_CANCEL)then
PostMessage(FDaddysHandle, WM_CANCEL, 0, 0);
if((Sender as TomSpeedBtn).Name=BUTTON_UPLOAD)then
PostMessage(FDaddysHandle, WM_UPLOAD, 0, 0);
if((Sender as TomSpeedBtn).Name=BUTTON_SAVE)then
PostMessage(FDaddysHandle, WM_SAVE, 0, 0);
if((Sender as TomSpeedBtn).Name=BUTTON_COPY)then
PostMessage(FDaddysHandle, WM_COPY_IMAGE, 0, 0);
end;
end;
procedure TMenuForm.SetButtons;
var
I: Integer;
begin
with Buttons.List do
for I:=0 to Count-1 do
TomSpeedBtn(Items[I]).OnClick:=BtnsOnClick;
end;
procedure TMenuForm.FullScreen;
begin
if not(Full)then
TomSpeedBtn(Buttons.Button(BUTTON_CUT)).Caption:=FCutCaption
else
TomSpeedBtn(Buttons.Button(BUTTON_CUT)).Caption:=FReverseCaption;
if(Full<>FFullScreen)or(ChangedResolution)then begin
FormSize(Full);
FormPosition(Full);
if(ChangedResolution)then begin
Buttons.Sizes;
FitResolution:=Resolution;
end;
FFullScreen:=Full;
Buttons.Positions(Full);
end;
end;
end.
|
unit Model.Customer;
interface
uses MVCFramework.ActiveRecord;
type
[MVCTable('customers')]
TCustomer = class(TMVCActiveRecord)
private
[MVCTableField('id', [foPrimaryKey, foAutoGenerated])]
Fid: Integer;
[MVCTableField('note')]
FNote: String;
[MVCTableField('code')]
FCode: String;
[MVCTableField('rating')]
Frating: Integer;
[MVCTableField('description')]
FDescription: String;
[MVCTableField('city')]
FCity: String;
procedure SetCity(const Value: String);
procedure SetCode(const Value: String);
procedure SetDescription(const Value: String);
procedure Setid(const Value: Integer);
procedure SetNote(const Value: String);
procedure Setrating(const Value: Integer);
public
constructor Create;override;
destructor Destroy;override;
property id : Integer read Fid write Setid;
property Code : String read FCode write SetCode;
property Description : String read FDescription write SetDescription;
property City : String read FCity write SetCity;
property Note : String read FNote write SetNote;
property rating : Integer read Frating write Setrating;
end;
implementation
{ TCustomer }
constructor TCustomer.Create;
begin
inherited Create;
end;
destructor TCustomer.Destroy;
begin
inherited;
end;
procedure TCustomer.SetCity(const Value: String);
begin
FCity := Value;
end;
procedure TCustomer.SetCode(const Value: String);
begin
FCode := Value;
end;
procedure TCustomer.SetDescription(const Value: String);
begin
FDescription := Value;
end;
procedure TCustomer.Setid(const Value: Integer);
begin
Fid := Value;
end;
procedure TCustomer.SetNote(const Value: String);
begin
FNote := Value;
end;
procedure TCustomer.Setrating(const Value: Integer);
begin
Frating := Value;
end;
end.
|
unit ddRowProperty;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "dd"
// Модуль: "w:/common/components/rtl/Garant/dd/ddRowProperty.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::dd::ddCommon::TddRowProperty
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
uses
ddBase,
Classes
;
type
TddRowProperty = class(TddPropertyObject)
private
// private fields
f_Gaph : LongInt;
{* Поле для свойства Gaph}
f_Left : LongInt;
{* Поле для свойства Left}
f_Width : LongInt;
{* Поле для свойства Width}
f_AutoFit : Boolean;
{* Поле для свойства AutoFit}
f_Border : TddBorder;
{* Поле для свойства Border}
f_IsLastRow : Boolean;
{* Поле для свойства IsLastRow}
f_RowIndex : LongInt;
{* Поле для свойства RowIndex}
protected
// property methods
procedure pm_SetAutoFit(aValue: Boolean);
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
// overridden public methods
procedure Assign(Source: TPersistent); override;
constructor Create(anOwner: TObject = nil); override;
{* конструктор объекта. Возвращает объект, со счетчиком ссылок равным 1. }
procedure Clear; override;
public
// public properties
property Gaph: LongInt
read f_Gaph
write f_Gaph;
property Left: LongInt
read f_Left
write f_Left;
property Width: LongInt
read f_Width
write f_Width;
property AutoFit: Boolean
read f_AutoFit
write pm_SetAutoFit;
property Border: TddBorder
read f_Border;
property IsLastRow: Boolean
read f_IsLastRow
write f_IsLastRow;
property RowIndex: LongInt
read f_RowIndex
write f_RowIndex;
end;//TddRowProperty
implementation
uses
RTFtypes,
l3Base
;
// start class TddRowProperty
procedure TddRowProperty.pm_SetAutoFit(aValue: Boolean);
//#UC START# *518A11380166_518A10050368set_var*
//#UC END# *518A11380166_518A10050368set_var*
begin
//#UC START# *518A11380166_518A10050368set_impl*
f_AutoFit := aValue;
//#UC END# *518A11380166_518A10050368set_impl*
end;//TddRowProperty.pm_SetAutoFit
procedure TddRowProperty.Assign(Source: TPersistent);
//#UC START# *478CF34E02CE_518A10050368_var*
var
i : Integer;
C, c1 : TddCellProperty;
//#UC END# *478CF34E02CE_518A10050368_var*
begin
//#UC START# *478CF34E02CE_518A10050368_impl*
if (Source is TddRowProperty) then
begin
Left:= TddRowProperty(Source).Left;
Gaph:= TddRowProperty(Source).Gaph;
RowIndex := TddRowProperty(Source).RowIndex;
IsLastRow := TddRowProperty(Source).IsLastRow;
f_Border.Assign(TddRowProperty(Source).Border);
end
else
inherited Assign(Source);
//#UC END# *478CF34E02CE_518A10050368_impl*
end;//TddRowProperty.Assign
constructor TddRowProperty.Create(anOwner: TObject = nil);
//#UC START# *47914F960008_518A10050368_var*
//#UC END# *47914F960008_518A10050368_var*
begin
//#UC START# *47914F960008_518A10050368_impl*
inherited;
f_RowIndex := -1;
f_Gaph:= 108;
f_Left:= -108;
f_Width:= 0;
f_IsLastRow := False;
f_Border:= TddBorder.Create(nil);
f_Border.isFramed:= True;
f_Border.BorderOwner:= boRow;
//#UC END# *47914F960008_518A10050368_impl*
end;//TddRowProperty.Create
procedure TddRowProperty.Cleanup;
//#UC START# *479731C50290_518A10050368_var*
//#UC END# *479731C50290_518A10050368_var*
begin
//#UC START# *479731C50290_518A10050368_impl*
f_IsLastRow := False;
f_RowIndex := -1;
l3Free(f_Border);
inherited;
//#UC END# *479731C50290_518A10050368_impl*
end;//TddRowProperty.Cleanup
procedure TddRowProperty.Clear;
//#UC START# *518A13330058_518A10050368_var*
//#UC END# *518A13330058_518A10050368_var*
begin
//#UC START# *518A13330058_518A10050368_impl*
f_RowIndex := -1;
f_IsLastRow := False;
f_Border.Clear;
Left := -108;
Gaph := 108;
//#UC END# *518A13330058_518A10050368_impl*
end;//TddRowProperty.Clear
end. |
program ejercicio7;
const
dimF = 24; //tamno del vector para las notas de cada alumno
type
str40 = String[40];
rangoMateria = 1..24;
vMateria = array[rangoMateria] of Real;
alumno = record
numAlumno : Integer;
apellido : str40;
nombre : str40;
mail : str40;
anioIngreso : Integer;
anioEgreso : Integer;
notaMateria : vMateria;
end;
lista = ^nodo;
nodo = record
datos : alumno;
sig : lista;
end;
procedure cargarVectorMateria(var vm: vMateria);
var
i: Integer;
begin
for i := 1 to dimF do
begin
write('Ingrese la nota de la MATERIA ', i, ' :' );
readln(vm[i]);
end;
end;
procedure ordenarVector(var vm:vMateria);
var
i,j,p: Integer;
aux: Real;
begin
for i := 1 to dimF-1 do
begin
p:= i;
for j := i+1 to dimF do
begin
if (vm[j] < vm[p]) then
p:= j;
end;
aux:= vm[p];
vm[p]:= vm[i];
vm[i]:= aux;
end;
end;
procedure leerAlumno(var a:alumno);
begin
with a do
begin
write('Ingrese NUMERO DE ALUMNO: ');
readln(numAlumno);
if (numAlumno <> -1) then
begin
write('Ingrese el APELLIDO: ');
readln(apellido);
write('Ingrese el NOMBRE: ');
readln(nombre);
write('Ingres el MAIL: ');
readln(mail);
write('Ingrese ANIO DE INGRESO: ');
readln(anioIngreso);
write('Ingrese ANIO EGRESO: ');
readln(anioEgreso);
cargarVectorMateria(notaMateria);
ordenarVector(notaMateria);
writeln('--------------------------------------------');
end;
end;
end;
procedure agregarAdelante(var l:lista; a:alumno);
var
nue: lista;
begin
new(nue);
nue^.datos:= a;
nue^.sig:= l;
l:= nue;
end;
procedure cargarAlumnos(var l:lista);
var
a: alumno;
begin
leerAlumno(a);
while (a.numAlumno <> -1) do
begin
agregarAdelante(l,a);
leerAlumno(a);
end;
end;
function promedioNotas(nota: vMateria): Real;
var
i: Integer;
sumaNota: Real;
begin
sumaNota:= 0;
for i := 1 to dimF do
begin
sumaNota:= sumaNota + nota[i];
end;
promedioNotas:= sumaNota;
end;
function descomponer(numeroAlumno: Integer): Boolean;
var
dig: Integer;
ok: Boolean;
begin
ok:= true;
while (numeroAlumno <> 0) and (ok) do
begin
dig:= numeroAlumno mod 10;
if (dig mod 2 = 1) then
else
ok:= false;
numeroAlumno:= numeroAlumno div 10;
end;
descomponer:= ok;
end;
procedure masRapisoSeRecibieron(a:alumno; calAnios: Integer; var min1,min2: Integer; var nomMin1,nomMin2: String; var apellMin1,apellMin2: String; var mailMin1, mailMin2: String);
begin
if (calAnios < min1) then
begin
min2:= min1;
apellMin2:= apellMin1;
nomMin2:= nomMin1;
mailMin2:= mailMin2;
min1:= calAnios;
apellMin1:= a.apellido;
nomMin1:= a.nombre;
mailMin1:= a.mail;
end
else
if (calAnios < min2) then
begin
min2:= calAnios;
apellMin2:= a.apellido;
nomMin2:= a.nombre;
mailMin2:= a.mail;
end;
end;
procedure procesarInfo(l:lista);
var
cantC: Integer;
calAnios, min1,min2: Integer;
nomMin1, nomMin2, apellMin1,apellMin2,mailMin1,mailMin2: String;
begin
cantC:= 0;
min1:= 9999;
min2:= 9999;
nomMin1:='';
nomMin2:='';
apellMin1:='';
apellMin2:='';
mailMin1:='';
mailMin2:='';
while (l <> nil) do
begin
writeln('El proemedio para el alumno ', l^.datos.nombre, ' es: ', promedioNotas(l^.datos.notaMateria) / dimF);
if (l^.datos.anioIngreso = 2012) and (descomponer(l^.datos.numAlumno)) then
cantC:= cantC + 1;
calAnios:= l^.datos.anioEgreso - l^.datos.anioIngreso;
masRapisoSeRecibieron(l^.datos,calAnios,min1,min2,nomMin1,nomMin2,apellMin1,apellMin2,mailMin1,mailMin2);
l:= l^.sig;
end;
writeln('La cantidad de alumnos ingresantes 2012 y numoro de alumno es unicamente digitos impares son: ', cantC);
writeln('El alumno mas rapido que se recibio es ', apellMin1,' ', nomMin1, ' con mail: ', mailMin1 );
writeln('El segundo alumnos mas rapido se recibio es ', apellMin2, ' ', nomMin2, ' con mail: ', mailMin2);
end;
procedure eliminar(var l:lista; nAlumno: Integer);
var
ant,act: lista;
begin
if (l <> nil) then
begin
ant:= l;
act:= l;
end;
while ((act <> nil) and (act^.datos.numAlumno <> nAlumno)) do
begin
ant:= act;
act:= act^.sig;
end;
if (act <> nil) then
begin
if (act = l) then
l:= l^.sig;
end
else
ant^.sig:= act^.sig;
dispose(act);
end;
var
l: lista;
nAlumno: Integer;
begin
l:= nil;
cargarAlumnos(l);
procesarInfo(l);
writeln('Ingrese el numero de alumon a eliminar: ');
readln(nAlumno);
eliminar(l,nAlumno);
end. |
{ ----------------------------------------------------------------------------
zbnc - Multi user IRC bouncer
Copyright (c) Michael "Zipplet" Nixon 2009 - 2010.
Licensed under the MIT license, see license.txt in the project trunk.
Unit: globals.pas
Purpose: Project-wide global constants and vars
---------------------------------------------------------------------------- }
unit globals;
interface
{ ----------------------------------------------------------------------------
Global constants
---------------------------------------------------------------------------- }
const
{ Application version }
appversion = '0.1';
{ PID file to write when forking on linux }
pidfile = 'zbnc.pid';
{ ----------------------------------------------------------------------------
Configuration types
---------------------------------------------------------------------------- }
type
{ Run modes - foreground prints the main log to stdout }
eRunMode = (rmForeground, rmBackground, rmService);
{ Settings not stored in the configuration, usually passed on the command
line }
rCmdSettings = record
runMode: eRunMode;
end;
{ ----------------------------------------------------------------------------
Global variables / objects
---------------------------------------------------------------------------- }
implementation
end.
|
namespace Sugar.Test;
interface
uses
Sugar,
RemObjects.Elements.EUnit,
Sugar.Data.JSON;
type
JsonValueTest = public class (Test)
private
method ValueOf(Value: Object): JsonValue;
method Detect(Value: Object; Expected: JsonValueKind): JsonValue;
public
method AutodetectType;
method ToInteger;
method ToDouble;
method ToStr;
method ToObject;
method ToArray;
method ToBoolean;
method IsNull;
end;
implementation
method JsonValueTest.AutodetectType;
begin
Detect(Byte(1), JsonValueKind.Integer);
Detect(Double(1), JsonValueKind.Double);
Detect(UInt16(1), JsonValueKind.Integer);
Detect(Int32(1), JsonValueKind.Integer);
Detect(Single(1), JsonValueKind.Double);
Detect('c', JsonValueKind.Integer);
Detect("c", JsonValueKind.String);
Detect(true, JsonValueKind.Boolean);
Detect(false, JsonValueKind.Boolean);
Detect(nil, JsonValueKind.Null);
Detect(new JsonObject, JsonValueKind.Object);
Detect(new JsonArray, JsonValueKind.Array);
end;
method JsonValueTest.ValueOf(Value: Object): JsonValue;
begin
exit new JsonValue(Value);
end;
method JsonValueTest.Detect(Value: Object; Expected: JsonValueKind): JsonValue;
begin
var JValue := ValueOf(Value);
Assert.IsNotNil(JValue);
Assert.AreEqual(JValue.Kind, Expected);
exit JValue;
end;
method JsonValueTest.ToInteger;
begin
Assert.AreEqual(ValueOf(1).ToInteger, 1);
Assert.AreEqual(ValueOf(Double(1.2)).ToInteger, 1);
Assert.AreEqual(ValueOf("1").ToInteger, 1);
Assert.AreEqual(ValueOf(true).ToInteger, 1);
Assert.AreEqual(ValueOf(false).ToInteger, 0);
Assert.Throws(->ValueOf(Sugar.Consts.MaxDouble).ToInteger);
Assert.Throws(->ValueOf("abc").ToInteger);
Assert.Throws(->ValueOf(nil).ToInteger);
Assert.Throws(->ValueOf("9999999999999999999999").ToInteger);
Assert.Throws(->ValueOf(new JsonObject).ToInteger);
Assert.Throws(->ValueOf(new JsonArray).ToInteger);
end;
method JsonValueTest.ToDouble;
begin
Assert.AreEqual(ValueOf(1).ToDouble, 1);
Assert.AreEqual(ValueOf(Double(1.2)).ToDouble, 1.2);
Assert.AreEqual(ValueOf("1").ToDouble, 1);
Assert.AreEqual(ValueOf(true).ToDouble, 1);
Assert.AreEqual(ValueOf(false).ToDouble, 0);
Assert.Throws(->ValueOf("abc").ToDouble);
Assert.Throws(->ValueOf(nil).ToDouble);
Assert.Throws(->ValueOf("9.9.9").ToDouble);
Assert.Throws(->ValueOf(new JsonObject).ToDouble);
Assert.Throws(->ValueOf(new JsonArray).ToDouble);
end;
method JsonValueTest.ToStr;
begin
Assert.AreEqual(ValueOf(1).ToStr, "1");
Assert.AreEqual(ValueOf(Double(1.2)).ToStr, "1.2");
Assert.AreEqual(ValueOf("1").ToStr, "1");
Assert.AreEqual(ValueOf(true).ToStr, Consts.TrueString);
Assert.AreEqual(ValueOf(false).ToStr, Consts.FalseString);
Assert.AreEqual(ValueOf(nil).ToStr, nil);
Assert.AreEqual(ValueOf(new JsonObject).ToStr, "[object]: 0 items");
Assert.AreEqual(ValueOf(new JsonArray).ToStr, "[array]: 0 items");
end;
method JsonValueTest.ToObject;
begin
var Obj := new JsonObject;
Assert.AreEqual(ValueOf(Obj).ToObject, Obj);
Assert.AreEqual(ValueOf(nil).ToObject, nil);
Assert.Throws(->ValueOf("abc").ToObject);
Assert.Throws(->ValueOf(1).ToObject);
Assert.Throws(->ValueOf(1.1).ToObject);
Assert.Throws(->ValueOf(true).ToObject);
Assert.Throws(->ValueOf(new JsonArray).ToObject);
end;
method JsonValueTest.ToArray;
begin
var Obj := new JsonArray;
Assert.AreEqual(ValueOf(Obj).ToArray, Obj);
Assert.AreEqual(ValueOf(nil).ToArray, nil);
Assert.Throws(->ValueOf("abc").ToArray);
Assert.Throws(->ValueOf(1).ToArray);
Assert.Throws(->ValueOf(1.1).ToArray);
Assert.Throws(->ValueOf(true).ToArray);
Assert.Throws(->ValueOf(new JsonObject).ToArray);
end;
method JsonValueTest.ToBoolean;
begin
Assert.AreEqual(ValueOf(true).ToBoolean, true);
Assert.AreEqual(ValueOf(false).ToBoolean, false);
Assert.AreEqual(ValueOf(Consts.TrueString).ToBoolean, true);
Assert.AreEqual(ValueOf(Consts.FalseString).ToBoolean, false);
Assert.AreEqual(ValueOf(0).ToBoolean, false);
Assert.AreEqual(ValueOf(1).ToBoolean, true);
Assert.Throws(->ValueOf("yes").ToBoolean);
Assert.Throws(->ValueOf(nil).ToBoolean);
Assert.Throws(->ValueOf(new JsonObject).ToBoolean);
Assert.Throws(->ValueOf(new JsonArray).ToObject);
end;
method JsonValueTest.IsNull;
begin
Assert.AreEqual(ValueOf(nil).IsNull, true);
Assert.AreEqual(ValueOf(true).IsNull, false);
Assert.AreEqual(ValueOf(false).IsNull, false);
Assert.AreEqual(ValueOf("").IsNull, false);
Assert.AreEqual(ValueOf(0).IsNull, false);
Assert.AreEqual(ValueOf(1.1).IsNull, false);
Assert.AreEqual(ValueOf(new JsonArray).IsNull, false);
Assert.AreEqual(ValueOf(new JsonObject).IsNull, false);
end;
end.
|
{-----------------------------------------------------------------------------
GlobalSearch (historypp project)
Version: 1.0
Created: 05.08.2004
Author: Oxygen
[ Description ]
Here we have the form and UI for global searching. Curious
can go to hpp_searchthread for internals of searching.
[ History ]
1.5 (05.08.2004)
First version
[ Modifications ]
none
[ Known Issues ]
* When doing HotSearch, and then backspacing to empty search string
grid doesn't return to the first iteam HotSearch started from
unlike in HistoryForm. Probably shouldn'be done, because too much checking
to reset LastHotIdx should be done, considering how much filtering &
sorting is performed.
Copyright (c) Art Fedorov, 2004
-----------------------------------------------------------------------------}
unit GlobalSearch;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ComCtrls, Menus,
TntForms, TntComCtrls, TntExtCtrls, TntStdCtrls,
HistoryGrid,
m_globaldefs, m_api,
hpp_global, hpp_events, hpp_services, hpp_contacts, hpp_database, hpp_searchthread,
ImgList, PasswordEditControl, Buttons, TntButtons;
const
HM_EVENTDELETED = WM_APP + 100;
HM_CONTACTDELETED = WM_APP + 101;
HM_CONTACTICONCHANGED = WM_APP + 102;
type
TSearchItem = record
hDBEvent: THandle;
hContact: THandle;
Proto: String;
ContactName: WideString;
ProfileName: WideString;
end;
TContactInfo = class(TObject)
private
FHandle: Integer;
public
property Handle: Integer read FHandle write FHandle;
end;
TfmGlobalSearch = class(TTntForm)
Panel1: TPanel;
paSearch: TPanel;
Label1: TLabel;
edSearch: TtntEdit;
bnSearch: TButton;
paCommand: TPanel;
paHistory: TPanel;
hg: THistoryGrid;
sb: TStatusBar;
paProgress: TPanel;
pb: TProgressBar;
laProgress: TTntLabel;
bnClose: TButton;
pmGrid: TPopupMenu;
Open1: TMenuItem;
Copy1: TMenuItem;
CopyText1: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
Button2: TButton;
bnAdvanced: TButton;
gbAdvanced: TGroupBox;
rbAny: TRadioButton;
rbAll: TRadioButton;
rbExact: TRadioButton;
spContacts: TTntSplitter;
paPassword: TPanel;
edPass: TPasswordEdit;
cbPass: TTntCheckBox;
laPass: TTntLabel;
ilContacts: TImageList;
paContacts: TTntPanel;
lvContacts: TTntListView;
SendMessage1: TMenuItem;
ReplyQuoted1: TMenuItem;
SaveSelected1: TMenuItem;
SaveDialog: TSaveDialog;
paFilter: TPanel;
Image1: TImage;
edFilter: TTntEdit;
sbClearFilter: TTntSpeedButton;
procedure sbClearFilterClick(Sender: TObject);
procedure edPassKeyPress(Sender: TObject; var Key: Char);
procedure edFilterKeyPress(Sender: TObject; var Key: Char);
procedure edSearchKeyPress(Sender: TObject; var Key: Char);
procedure hgItemDelete(Sender: TObject; Index: Integer);
procedure OnCNChar(var Message: TWMChar); message WM_CHAR;
procedure PrepareSaveDialog(SaveDialog: TSaveDialog; SaveFormat: TSaveFormat; AllFormats: Boolean = False);
procedure SaveSelected1Click(Sender: TObject);
procedure hgPopup(Sender: TObject);
procedure ReplyQuoted1Click(Sender: TObject);
procedure SendMessage1Click(Sender: TObject);
procedure edFilterKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure hgItemFilter(Sender: TObject; Index: Integer; var Show: Boolean);
procedure edFilterChange(Sender: TObject);
procedure TntFormDestroy(Sender: TObject);
procedure edSearchChange(Sender: TObject);
procedure hgKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure hgState(Sender: TObject; State: TGridState);
procedure hgSearchFinished(Sender: TObject; Text: WideString;
Found: Boolean);
procedure hgSearchItem(Sender: TObject; Item, ID: Integer;
var Found: Boolean);
//procedure TntFormHide(Sender: TObject);
procedure TntFormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure cbPassClick(Sender: TObject);
procedure lvContactsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
procedure hgNameData(Sender: TObject; Index: Integer; var Name: WideString);
procedure hgTranslateTime(Sender: TObject; Time: Cardinal; var Text: WideString);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure bnSearchClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure hgItemData(Sender: TObject; Index: Integer; var Item: THistoryItem);
procedure hgDblClick(Sender: TObject);
procedure edSearchEnter(Sender: TObject);
procedure edSearchKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure bnCloseClick(Sender: TObject);
procedure hgProcessRichText(Sender: TObject; Handle: Cardinal; Item: Integer);
procedure FormShow(Sender: TObject);
procedure hgKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure hgUrlClick(Sender: TObject; Item: Integer; Url: String);
procedure edPassKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure bnAdvancedClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure hgSelect(Sender: TObject; Item, OldItem: Integer);
private
WasReturnPressed: Boolean;
LastUpdateTime: DWord;
CloseAfterThreadFinish: Boolean;
HotString: WideString;
hHookContactIconChanged, hHookContactDeleted, hHookEventDeleted: THandle;
FContactFilter: Integer;
FFiltered: Boolean;
IsSearching: Boolean;
History: array of TSearchItem;
FilterHistory: array of Integer;
CurContact: THandle;
CurContactName: WideString;
CurProfileName: WideString;
CurProto: String;
st: TSearchThread;
stime: DWord;
ContactsFound: Integer;
AllItems: Integer;
AllContacts: Integer;
procedure SMPrepare(var M: TMessage); message SM_PREPARE;
procedure SMProgress(var M: TMessage); message SM_PROGRESS;
procedure SMItemFound(var M: TMessage); message SM_ITEMFOUND; // OBSOLETE
procedure SMItemsFound(var M: TMessage); message SM_ITEMSFOUND;
procedure SMNextContact(var M: TMessage); message SM_NEXTCONTACT;
procedure SMFinished(var M: TMessage); message SM_FINISHED;
procedure HMEventDeleted(var M: TMessage); message HM_EVENTDELETED;
function FindHistoryItemByHandle(hDBEvent: THandle): Integer;
procedure DeleteEventFromLists(Item: Integer);
procedure HMContactDeleted(var M: TMessage); message HM_CONTACTDELETED;
procedure HMContactIconChanged(var M: TMessage); message HM_CONTACTICONCHANGED;
procedure TranslateForm;
procedure HookEvents;
procedure UnhookEvents;
procedure ShowAdvancedPanel(Show: Boolean);
procedure ShowContacts(Show: Boolean);
procedure SearchNext(Rev: Boolean; Warp: Boolean = True);
procedure ReplyQuoted(Item: Integer);
protected
procedure LoadWindowPosition;
procedure SaveWindowPosition;
published
// fix for splitter baug:
procedure AlignControls(Control: TControl; var ARect: TRect); override;
function GetSearchItem(GridIndex: Integer): TSearchItem;
procedure DisableFilter;
procedure FilterOnContact(hContact: Integer);
public
{ Public declarations }
end;
var
fmGlobalSearch: TfmGlobalSearch;
implementation
uses hpp_options, PassForm, hpp_itemprocess, hpp_forms, hpp_messages,
HistoryForm;
{$I m_langpack.inc}
{$I m_database.inc}
{$I m_icq.inc}
{$I m_clist.inc}
{$I m_historypp.inc}
{$R *.DFM}
// fix for infamous splitter bug!
// thanks to Greg Chapman
// http://groups.google.com/group/borland.public.delphi.objectpascal/browse_thread/thread/218a7511123851c3/5ada76e08038a75b%235ada76e08038a75b?sa=X&oi=groupsr&start=2&num=3
procedure TfmGlobalSearch.AlignControls(Control: TControl; var ARect: TRect);
{AlignControls is virtual}
begin
inherited;
if paContacts.Width = 0 then
paContacts.Left := spContacts.Left;
end;
procedure TfmGlobalSearch.FormCreate(Sender: TObject);
//var
// NonClientMetrics: TNonClientMetrics;
begin
// Setting different system font different way. For me works the same
// but some said it produces better results than DesktopFont
// Leave it here for possible future use.
//
// NonClientMetrics.cbSize := SizeOf(NonClientMetrics);
// SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @NonClientMetrics, 0);
// Font.Handle := CreateFontIndirect(NonClientMetrics.lfMessageFont);
// if Scaled then begin
// Font.Height := NonClientMetrics.lfMessageFont.lfHeight;
// end;
DesktopFont := True;
MakeFontsParent(Self);
end;
procedure TfmGlobalSearch.SMFinished(var M: TMessage);
var
sbt: String;
begin
stime := st.SearchTime;
AllContacts := st.AllContacts;
AllItems := st.AllEvents;
// if change, change also in hg.State:
sbt := Format('%.0n items in %.0n contacts found. Searched for %.1f sec in %.0n items.',[Length(History)/1, ContactsFound/1, stime/1000, AllItems/1, AllContacts/1]);
st.WaitFor;
st.Free;
IsSearching := False;
paProgress.Hide;
//paFilter.Show;
sb.SimpleText := sbt;
bnSearch.Enabled := True;
if Length(History) = 0 then
ShowContacts(False);
if CloseAfterThreadFinish then begin
Close;
end;
end;
// OBSOLETE:
procedure TfmGlobalSearch.SMItemFound(var M: TMessage);
var
li: TtntListItem;
begin
// wParam - hDBEvent, lParam - 0
SetLength(History,Length(History)+1);
History[High(History)].hDBEvent := m.wParam;
History[High(History)].hContact := CurContact;
History[High(History)].ContactName := CurContactName;
History[High(History)].ProfileName := CurProfileName;
History[High(History)].Proto := CurProto;
if (lvContacts.Items.Count = 0) or (Integer(lvContacts.Items.Item[lvContacts.Items.Count-1].Data) <> CurContact) then begin
li := lvContacts.Items.Add;
li.Caption := CurContactName;
li.Data := Pointer(CurContact);
end;
hg.Allocate(Length(History));
if hg.Count = 1 then begin
hg.Selected := 0;
hg.SetFocus;
end;
Application.ProcessMessages;
end;
procedure TfmGlobalSearch.SMItemsFound(var M: TMessage);
var
li: TtntListItem;
ci: TContactInfo;
Buffer: PDBArray;
FiltOldSize,OldSize,i,BufCount: Integer;
begin
// wParam - array of hDBEvent, lParam - array size
Buffer := PDBArray(m.wParam);
BufCount := Integer(m.LParam);
OldSize := Length(History);
SetLength(History,OldSize+BufCount);
for i := 0 to BufCount - 1 do begin
History[OldSize + i].hDBEvent := Buffer^[i];
History[OldSize + i].hContact := CurContact;
History[OldSize + i].ContactName := CurContactName;
History[OldSize + i].ProfileName := CurProfileName;
History[OldSize + i].Proto := CurProto;
end;
FreeMem(Buffer,SizeOf(Buffer));
if (lvContacts.Items.Count = 0) or (Integer(lvContacts.Items.Item[lvContacts.Items.Count-1].Data) <> CurContact) then begin
if lvContacts.Items.Count = 0 then begin
li := lvContacts.Items.Add;
li.Caption := 'All Results';
li.StateIndex := -1;
li.Selected := True;
end;
li := lvContacts.Items.Add;
if CurContact = 0 then
li.Caption := 'System History'
else
li.Caption := CurContactName;
li.ImageIndex := PluginLink.CallService(MS_CLIST_GETCONTACTICON,CurContact,0);
//meTest.Lines.Add(CurContactName+' icon is '+IntToStr(PluginLink.CallService(MS_CLIST_GETCONTACTICON,CurContact,0)));
li.Data := Pointer(CurContact);
end;
if FFiltered then begin
if CurContact = FContactFilter then begin
FiltOldSize := Length(FilterHistory);
for i := 0 to BufCount - 1 do
FilterHistory[FiltOldSize+i] := OldSize + i;
end;
hg.Allocate(Length(FilterHistory));
end
else
hg.Allocate(Length(History));
paFilter.Visible := True;
if not paContacts.Visible then begin
ShowContacts(True);
hg.Selected := 0;
hg.SetFocus;
end;
// dirty hack: readjust scrollbars
hg.Perform(WM_SIZE,SIZE_RESTORED,MakeLParam(hg.ClientWidth,hg.ClientHeight));
hg.Repaint;
//Application.ProcessMessages;
end;
procedure TfmGlobalSearch.SMNextContact(var M: TMessage);
begin
// wParam - hContact, lParam - 0
CurContact := m.wParam;
if CurContact <> 0 then Inc(ContactsFound);
if CurContact = 0 then CurProto := 'ICQ'
else CurProto := GetContactProto(CurContact);
CurContactName := GetContactDisplayName(CurContact,CurProto,true);
CurProfileName := GetContactDisplayName(0, CurProto);
laProgress.Caption := WideFormat(AnsiToWideString(Translate('Searching "%s"...'),hppCodepage),[CurContactName]);
//Application.ProcessMessages;
end;
procedure TfmGlobalSearch.SMPrepare(var M: TMessage);
begin
CloseAfterThreadFinish := False;
LastUpdateTime := 0;
ContactsFound := 0;
AllItems := 0;
AllContacts := 0;
FFiltered := False;
hg.Selected := -1;
hg.Allocate(0);
SetLength(FilterHistory,0);
SetLength(History,0);
bnSearch.Enabled := False;
sb.SimpleText := 'Searching... Please wait.';
IsSearching := True;
laProgress.Caption := AnsiToWideString(Translate('Preparing search...'),hppCodepage);
pb.Position := 0;
paProgress.Show;
paFilter.Visible := False;
//ShowContacts(False);
lvContacts.Items.Clear;
end;
procedure TfmGlobalSearch.SMProgress(var M: TMessage);
begin
// wParam - progress; lParam - max
if (GetTickCount - LastUpdateTime) < 100 then exit;
LastUpdateTime := GetTickCount;
pb.Max := m.LParam;
pb.Position := m.Wparam;
//Application.ProcessMessages;
// if change, change also in hg.OnState
sb.SimpleText := Format('Searching... %.0n items in %.0n contacts found',[Length(History)/1, ContactsFound/1]);
end;
procedure TfmGlobalSearch.edFilterChange(Sender: TObject);
begin
hg.UpdateFilter;
end;
procedure TfmGlobalSearch.edFilterKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
i: Integer;
begin
inherited;
if Key in [VK_UP,VK_DOWN,VK_NEXT, VK_PRIOR] then begin
SendMessage(hg.Handle,WM_KEYDOWN,Key,0);
Key := 0;
end;
if Key = VK_RETURN then begin
//edFilter.Text := '';
hg.SetFocus;
key := 0;
end;
end;
procedure TfmGlobalSearch.edFilterKeyPress(Sender: TObject; var Key: Char);
begin
if (key = Chr(VK_RETURN)) or (key = Chr(VK_TAB)) or (key = Chr(VK_ESCAPE)) then
key := #0;
end;
procedure TfmGlobalSearch.TntFormDestroy(Sender: TObject);
begin
fmGlobalSearch := nil;
end;
procedure TfmGlobalSearch.TntFormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
Handled := True;
if Assigned(ControlAtPos(MousePos,False,True)) then
//if ControlAtPos(MousePos,False,True,True) is TListView then begin
if ControlAtPos(MousePos,False,True) is TListView then begin
{$RANGECHECKS OFF}
TListView(ControlAtPos(MousePos,False,True)).Perform(WM_MOUSEWHEEL,MakeLong(MK_CONTROL,WheelDelta),0);
{$RANGECHECKS ON}
exit;
end;
(* we can get range check error (???) here
it looks that without range check it works ok
so turn it off *)
{$RANGECHECKS OFF}
hg.perform(WM_MOUSEWHEEL,MakeLong(MK_CONTROL,WheelDelta),0);
{$RANGECHECKS ON}
end;
procedure TfmGlobalSearch.sbClearFilterClick(Sender: TObject);
begin
edFilter.Text := '';
hg.SetFocus;
end;
procedure TfmGlobalSearch.TranslateForm;
begin
{TODO: Translate form}
end;
procedure TfmGlobalSearch.FilterOnContact(hContact: Integer);
var
i: Integer;
begin
if FFiltered and (FContactFilter = hContact) then exit;
FFiltered := True;
FContactFilter := hContact;
SetLength(FilterHistory,0);
for i := 0 to Length(History)-1 do begin
if History[i].hContact = hContact then begin
SetLength(FilterHistory,Length(FilterHistory)+1);
FilterHistory[High(FilterHistory)] := i;
end;
end;
hg.Allocate(0);
hg.Allocate(Length(FilterHistory));
if hg.Count > 0 then begin
hg.Selected := 0;
// dirty hack: readjust scrollbars
hg.Perform(WM_SIZE,SIZE_RESTORED,MakeLParam(hg.ClientWidth,hg.ClientHeight));
end;
end;
function TfmGlobalSearch.FindHistoryItemByHandle(hDBEvent: THandle): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to Length(History) - 1 do begin
if History[i].hDBEvent = hDBEvent then begin
Result := i;
break;
end;
end;
end;
procedure TfmGlobalSearch.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
SaveWindowPosition;
UnhookEvents;
end;
procedure TfmGlobalSearch.bnSearchClick(Sender: TObject);
begin
{TODO: Text}
if edSearch.Text = '' then
raise Exception.Create('Enter text to search');
if edPass.Enabled then begin
if edPass.Text = '' then begin
MessageBox(Handle, PChar(String(Translate('Enter the history password to search.'))),
Translate('History++ Password Protection'), MB_OK or MB_DEFBUTTON1 or MB_ICONSTOP);
edPass.SetFocus;
edPass.SelectAll;
exit;
end;
if not CheckPassword(edPass.Text) then begin
MessageBox(Handle, PChar(String(Translate('You have entered the wrong password.'))+
#10#13+String(Translate('Make sure you have CAPS LOCK turned off.'))),
Translate('History++ Password Protection'), MB_OK or MB_DEFBUTTON1 or MB_ICONSTOP);
edPass.SetFocus;
edPass.SelectAll;
exit;
end;
end;
st := TSearchThread.Create(True);
if rbAny.Checked then
st.SearchMethod := smAnyWord
else if rbAll.Checked then
st.SearchMethod := smAllWords
else
st.SearchMethod := smExact;
st.Priority := tpLower;
st.ParentHandle := Self.Handle;
st.SearchText := edSearch.text;
st.SearchProtectedContacts := edPass.Enabled;
st.Resume;
end;
procedure TfmGlobalSearch.cbPassClick(Sender: TObject);
begin
laPass.Enabled := cbPass.Enabled and cbPass.Checked;
edPass.Enabled := cbPass.Enabled and cbPass.Checked;
end;
// takes index from *History* array as parameter
procedure TfmGlobalSearch.DeleteEventFromLists(Item: Integer);
var
DelIdx,i: Integer;
EventDeleted: Boolean;
begin
if Item = -1 then exit;
for i := Item to Length(History) - 2 do begin
History[i] := History[i+1];
end;
SetLength(History,Length(History)-1);
if not FFiltered then exit;
EventDeleted := False;
for i := 0 to Length(FilterHistory) - 1 do begin
if FilterHistory[i] = Item then EventDeleted := True;
if (EventDeleted) and (i < Length(FilterHistory)-1) then FilterHistory[i] := FilterHistory[i+1];
if EventDeleted then Dec(FilterHistory[i]);
end;
if EventDeleted then SetLength(FilterHistory,Length(FilterHistory)-1);
end;
procedure TfmGlobalSearch.DisableFilter;
begin
if not FFiltered then exit;
FFiltered := False;
SetLength(FilterHistory,0);
hg.Allocate(0);
hg.Allocate(Length(History));
hg.Selected := 0;
// dirty hack: readjust scrollbars
hg.Perform(WM_SIZE,SIZE_RESTORED,MakeLParam(hg.ClientWidth,hg.ClientHeight));
end;
procedure TfmGlobalSearch.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if IsSearching then begin
// put before Terminate;
CanClose := False;
CloseAfterThreadFinish := True;
st.Terminate;
laProgress.Caption := 'Please wait while closing the window...';
laProgress.Font.Style := [fsBold];
pb.Visible := False;
//Application.ProcessMessages;
//st.WaitFor;
end;
end;
procedure TfmGlobalSearch.hgItemData(Sender: TObject; Index: Integer;
var Item: THistoryItem);
begin
Item := ReadEvent(GetSearchItem(Index).hDBEvent);
Item.Proto := GetSearchItem(Index).Proto;
end;
procedure TfmGlobalSearch.hgItemDelete(Sender: TObject; Index: Integer);
var
idx: Integer;
begin
if FFiltered then
Index := FilterHistory[Index];
DeleteEventFromLists(Index);
end;
procedure TfmGlobalSearch.hgItemFilter(Sender: TObject; Index: Integer;
var Show: Boolean);
begin
if edFilter.Text = '' then exit;
if Pos(WideUpperCase(edFilter.Text),WideUpperCase(hg.Items[Index].Text)) = 0 then
Show := False;
end;
procedure TfmGlobalSearch.hgDblClick(Sender: TObject);
begin
if hg.Selected = -1 then exit;
PluginLink.CallService(MS_HPP_OPENHISTORYEVENT,GetSearchItem(hg.Selected).hDBEvent,GetSearchItem(hg.Selected).hContact);
end;
procedure TfmGlobalSearch.edSearchChange(Sender: TObject);
begin
bnSearch.Enabled := (edSearch.Text <> '');
end;
procedure TfmGlobalSearch.edSearchEnter(Sender: TObject);
begin
//edSearch.SelectAll;
end;
procedure TfmGlobalSearch.LoadWindowPosition;
var
n: Integer;
AdvancedOptions: Integer;
begin
if Utils_RestoreWindowPosition(Self.Handle,0,0,hppDBName,'GlobalSearchWindow.') <> 0 then begin
Self.Left := (Screen.Width-Self.Width) div 2;
Self.Top := (Screen.Height - Self.Height) div 2;
end;
// if we are passord-protected (cbPass.Enabled) and
// have PROTSEL (not (cbPass.Checked)) then load
// checkbox from DB
if (cbPass.Enabled) and not (cbPass.Checked) then begin
cbPass.Checked := GetDBBool(hppDBName,'GlobalSearchWindow.PassChecked',False);
cbPassClick(cbPass);
end;
n := GetDBInt(hppDBName,'GlobalSearchWindow.ContactListWidth',-1);
if n <> -1 then begin
paContacts.Width := n;
end;
spContacts.Left := paContacts.Left + paContacts.Width + 1;
edFilter.Width := paFilter.Width - edFilter.Left - 2;
hg.Reversed := (GetDBInt(hppDBName,'SortOrder',0) = 0);
ShowAdvancedPanel(GetDBBool(hppDBName,'GlobalSearchWindow.ShowAdvanced',False));
case GetDBInt(hppDBName,'GlobalSearchWindow.AdvancedOptions',0) of
0: rbAny.Checked := True;
1: rbAll.Checked := True;
2: rbExact.Checked := True
else
rbAny.Checked := True;
end;
edSearch.Text := AnsiToWideString(GetDBStr(hppDBName,'GlobalSearchWindow.LastSearch',''),hppCodepage);
end;
procedure TfmGlobalSearch.lvContactsSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
var
i,hCont,Index: Integer;
begin
if not Selected then exit;
{Index := -1;
hCont := Integer(Item.Data);
for i := 0 to Length(History) - 1 do
if History[i].hContact = hCont then begin
Index := i;
break;
end;
if Index = -1 then exit;
hg.Selected := Index;}
// OXY: try to make selected item the topmost
//while hg.GetFirstVisible <> Index do begin
// if hg.VertScrollBar.Position = hg.VertScrollBar.Range then break;
// hg.VertScrollBar.Position := hg.VertScrollBar.Position + 1;
//end;
if Item.Index = 0 then
DisableFilter
else begin
hCont := Integer(Item.Data);
FilterOnContact(hCont);
end;
end;
procedure TfmGlobalSearch.OnCNChar(var Message: TWMChar);
//make tabs work!
begin
if not (csDesigning in ComponentState) then
with Message do
begin
Result := 1;
if (Perform(WM_GETDLGCODE, 0, 0) and DLGC_WANTCHARS = 0) and
(GetParentForm(Self).Perform(CM_DIALOGCHAR,
CharCode, KeyData) <> 0) then Exit;
Result := 0;
end;
end;
procedure TfmGlobalSearch.ReplyQuoted(Item: Integer);
var
Txt: WideString;
begin
if GetSearchItem(Item).hContact = 0 then exit;
if (item < 0) or (item > hg.Count-1) then exit;
if mtIncoming in hg.Items[Item].MessageType then
Txt := GetSearchItem(Item).ContactName
else
Txt := GetSearchItem(Item).ProfileName;
Txt := Txt+', '+TimestampToString(hg.Items[item].Time)+' :';
Txt := Txt+#13#10+QuoteText(hg.Items[item].Text);
SendMessageTo(GetSearchItem(Item).hContact,Txt);
end;
procedure TfmGlobalSearch.ReplyQuoted1Click(Sender: TObject);
begin
if hg.Selected <> -1 then begin
if GetSearchItem(hg.Selected).hContact = 0 then exit;
ReplyQuoted(hg.Selected);
end;
end;
var
HtmlFilter: String = 'HTML file (*.html; *.htm)|*.html;*.htm';
XmlFilter: String = 'XML file (*.xml)|*.xml';
UnicodeFilter: String = 'Unicode text file (*.txt)|*.txt';
TextFilter: String = 'Text file (*.txt)|*.txt';
AllFilter: String = 'All files (*.*)|*.*';
HtmlDef: String = '.html';
XmlDef: String = '.xml';
TextDef: String = '.txt';
procedure TfmGlobalSearch.PrepareSaveDialog(SaveDialog: TSaveDialog; SaveFormat: TSaveFormat; AllFormats: Boolean = False);
begin
if AllFormats then begin
SaveDialog.Filter := HtmlFilter+'|'+XmlFilter+'|'+UnicodeFilter+'|'+TextFilter+'|'+AllFilter;
case SaveFormat of
sfHTML: SaveDialog.FilterIndex := 1;
sfXML: SaveDialog.FilterIndex := 2;
sfUnicode: SaveDialog.FilterIndex := 3;
sfText: SaveDialog.FilterIndex := 4;
end;
end else begin
case SaveFormat of
sfHTML: begin SaveDialog.Filter := HtmlFilter; SaveDialog.FilterIndex := 1; end;
sfXML: begin SaveDialog.Filter := XmlFilter; SaveDialog.FilterIndex := 1; end;
sfUnicode: begin SaveDialog.Filter := UnicodeFilter+'|'+TextFilter; SaveDialog.FilterIndex := 1; end;
sfText: begin SaveDialog.Filter := UnicodeFilter+'|'+TextFilter; SaveDialog.FilterIndex := 2; end;
end;
SaveDialog.Filter := SaveDialog.Filter + '|' + AllFilter;
end;
case SaveFormat of
sfHTML: SaveDialog.DefaultExt := HtmlDef;
sfXML: SaveDialog.DefaultExt := XmlDef;
sfUnicode: SaveDialog.DefaultExt := TextDef;
sfText: SaveDialog.DefaultExt := TextDef;
end;
end;
procedure TfmGlobalSearch.SaveSelected1Click(Sender: TObject);
var
t: String;
SaveFormat: TSaveFormat;
RecentFormat: TSaveFormat;
begin
RecentFormat := TSaveFormat(GetDBInt(hppDBName,'ExportFormat',0));
SaveFormat := RecentFormat;
PrepareSaveDialog(SaveDialog,SaveFormat,True);
t := Translate('Partial History [%s] - [%s]');
t := Format(t,[WideToAnsiString(hg.ProfileName,CP_ACP),WideToAnsiString(hg.ContactName,CP_ACP)]);
t := MakeFileName(t);
SaveDialog.FileName := t;
if not SaveDialog.Execute then exit;
case SaveDialog.FilterIndex of
1: SaveFormat := sfHtml;
2: SaveFormat := sfXml;
3: SaveFormat := sfUnicode;
4: SaveFormat := sfText;
end;
RecentFormat := SaveFormat;
hg.SaveSelected(SaveDialog.Files[0],SaveFormat);
WriteDBInt(hppDBName,'ExportFormat',Integer(RecentFormat));
end;
procedure TfmGlobalSearch.SaveWindowPosition;
var
LastSearch: WideString;
begin
Utils_SaveWindowPosition(Self.Handle,0,'HistoryPlusPlus','GlobalSearchWindow.');
// if we are passord-protected (cbPass.Enabled) and
// have PROTSEL (GetPassMode = PASSMODE_PROTSEL) then save
// checkbox to DB
if (cbPass.Enabled) and (GetPassMode = PASSMODE_PROTSEL) then
WriteDBBool(hppDBName,'GlobalSearchWindow.PassChecked',cbPass.Checked);
WriteDBInt(hppDBName,'GlobalSearchWindow.ContactListWidth',paContacts.Width);
WriteDBBool(hppDBName,'GlobalSearchWindow.ShowAdvanced',gbAdvanced.Visible);
if rbAny.Checked then
WriteDBInt(hppDBName,'GlobalSearchWindow.AdvancedOptions',0)
else if rbAll.Checked then
WriteDBInt(hppDBName,'GlobalSearchWindow.AdvancedOptions',1)
else
WriteDBInt(hppDBName,'GlobalSearchWindow.AdvancedOptions',2);
LastSearch := WideToAnsiString(edSearch.Text,hppCodepage);
WriteDBStr(hppDBName,'GlobalSearchWindow.LastSearch',LastSearch);
end;
procedure TfmGlobalSearch.edSearchKeyPress(Sender: TObject; var Key: Char);
begin
if (key = Chr(VK_RETURN)) or (key = Chr(VK_TAB)) or (key = Chr(VK_ESCAPE)) then
key := #0;
end;
procedure TfmGlobalSearch.edSearchKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_RETURN) and bnSearch.Enabled then
bnSearch.Click;
end;
procedure TfmGlobalSearch.bnCloseClick(Sender: TObject);
begin
close;
end;
var
ItemRenderDetails: TItemRenderDetails;
procedure TfmGlobalSearch.hgPopup(Sender: TObject);
begin
//SaveSelected1.Visible := False;
if hg.Selected <> -1 then begin
if GetSearchItem(hg.Selected).hContact = 0 then begin
SendMessage1.Visible := False;
ReplyQuoted1.Visible := False;
end;
//Delete1.Visible := True;
//if hg.SelCount > 1 then
// SaveSelected1.Visible := True;
//AddMenu(Options1,pmAdd,pmGrid,-1);
//AddMenu(ANSICodepage1,pmAdd,pmGrid,-1);
//AddMenu(ContactRTLmode1,pmAdd,pmGrid,-1);
pmGrid.Popup(Mouse.CursorPos.x,Mouse.CursorPos.y);
end;
end;
procedure TfmGlobalSearch.hgProcessRichText(Sender: TObject;
Handle: Cardinal; Item: Integer);
begin
ZeroMemory(@ItemRenderDetails,SizeOf(ItemRenderDetails));
ItemRenderDetails.hContact := GetSearchItem(Item).hContact;
ItemRenderDetails.hDBEvent := GetSearchItem(Item).hDBEvent;
ItemRenderDetails.pProto := Pointer(hg.Items[Item].Proto);
ItemRenderDetails.pModule := Pointer(hg.Items[Item].Module);
ItemRenderDetails.dwEventTime := hg.Items[Item].Time;
ItemRenderDetails.wEventType := hg.Items[Item].EventType;
ItemRenderDetails.IsEventSent := (mtOutgoing in hg.Items[Item].MessageType);
if Handle = hg.InlineRichEdit.Handle then
ItemRenderDetails.dwFlags := ItemRenderDetails.dwFlags or IRDF_INLINE;
if hg.IsSelected(Item) then
ItemRenderDetails.dwFlags := ItemRenderDetails.dwFlags or IRDF_SELECTED;
ItemRenderDetails.bHistoryWindow := IRDHW_GLOBALSEARCH;
PluginLink.NotifyEventHooks(hHppRichEditItemProcess,Handle,Integer(@ItemRenderDetails));
end;
procedure TfmGlobalSearch.hgTranslateTime(Sender: TObject; Time: Cardinal; var Text: WideString);
begin
Text := TimestampToString(Time);
end;
procedure TfmGlobalSearch.HookEvents;
begin
hHookEventDeleted := PluginLink.HookEventMessage(ME_DB_EVENT_DELETED,Self.Handle,HM_EVENTDELETED);
hHookContactDeleted := PluginLink.HookEventMessage(ME_DB_CONTACT_DELETED,Self.Handle,HM_CONTACTDELETED);
hHookContactIconChanged :=PluginLink.HookEventMessage(ME_CLIST_CONTACTICONCHANGED,Self.Handle,HM_CONTACTICONCHANGED);
end;
procedure TfmGlobalSearch.UnhookEvents;
begin
PluginLink.UnhookEvent(hHookEventDeleted);
PluginLink.UnhookEvent(hHookContactDeleted);
PluginLink.UnhookEvent(hHookContactIconChanged);
end;
procedure TfmGlobalSearch.FormShow(Sender: TObject);
var
PassMode: Byte;
begin
paFilter.Visible := False;
ShowAdvancedPanel(False);
ShowContacts(False);
IsSearching := False;
Icon.Handle := CopyIcon(hppIcons[1].handle);
hg.Options := GridOptions;
hg.TxtStartup := Translate('Ready to search'#10#13#10#13'Click Search button to start');
HG.TxtNoItems := Translate('No items found');
PassMode := GetPassMode;
cbPass.Enabled := (PassMode <> PASSMODE_PROTNONE);
cbPass.Checked := (PassMode = PASSMODE_PROTALL) and (cbPass.Enabled);
laPass.Enabled := cbPass.Checked and cbPass.Enabled;
edPass.Enabled := cbPass.Checked and cbPass.Enabled;
TranslateForm;
LoadWindowPosition;
ilContacts.Handle := PluginLink.CallService(MS_CLIST_GETICONSIMAGELIST,0,0);
HookEvents;
edSearch.SetFocus;
edSearch.SelectAll;
bnSearch.Enabled := (edSearch.Text <> '');
end;
function TfmGlobalSearch.GetSearchItem(GridIndex: Integer): TSearchItem;
begin
if not FFiltered then
Result := History[GridIndex]
else
Result := History[FilterHistory[GridIndex]];
end;
procedure TfmGlobalSearch.HMContactDeleted(var M: TMessage);
begin
{wParam - hContact; lParam - zero}
// do here something because the contact is deleted
if IsSearching then exit;
end;
procedure TfmGlobalSearch.HMContactIconChanged(var M: TMessage);
var
i: Integer;
begin
{wParam - hContact; lParam - IconID}
// contact icon has changed
//meTest.Lines.Add(GetContactDisplayName(M.wParam)+' changed icon to '+IntToStr(m.LParam));
if not paContacts.Visible then exit;
for i := 0 to lvContacts.Items.Count - 1 do begin
if Integer(m.wParam) = Integer(lvContacts.Items[i].Data) then begin
lvContacts.Items[i].ImageIndex := Integer(m.lParam);
break;
end;
end;
end;
procedure TfmGlobalSearch.HMEventDeleted(var M: TMessage);
var
i: Integer;
begin
{wParam - hContact; lParam - hDBEvent}
// event is deleted
for i := 0 to hg.Count - 1 do begin
if (GetSearchItem(i).hDBEvent = M.lParam) then begin
hg.Delete(i);
exit;
end;
end;
// exit if we searched all
if not FFiltered then exit;
// if event is not in filter, we must search the overall array
i := FindHistoryItemByHandle(m.LParam);
if i <> -1 then
DeleteEventFromLists(i);
end;
procedure TfmGlobalSearch.hgKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
WasReturnPressed := (Key = VK_RETURN);
end;
procedure TfmGlobalSearch.hgKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if not WasReturnPressed then exit;
if (Key = VK_RETURN) and (Shift = []) then begin
if hg.Selected <> -1 then
hg.EditInline(hg.Selected);
end;
if (Key = VK_RETURN) and (Shift = [ssCtrl]) then begin
hgDblClick(hg);
end;
end;
procedure TfmGlobalSearch.hgNameData(Sender: TObject; Index: Integer; var Name: WideString);
var
Mes: WideString;
si: TSearchItem;
begin
si := GetSearchItem(Index);
if FFiltered then begin
if mtIncoming in hg.Items[Index].MessageType then
Name := si.ContactName+':'
else
Name := si.ProfileName+':';
end else begin
if mtIncoming in hg.Items[Index].MessageType then
Name := 'From '+si.ContactName+':'
else
Name := 'To '+si.ContactName+':';
//Name := WideFormat(AnsiToWideString(Translate('%s''s history'),hppCodepage),[si.ContactName]);
end;
end;
procedure TfmGlobalSearch.hgUrlClick(Sender: TObject; Item: Integer; Url: String);
var
bNewWindow: Integer;
begin
bNewWindow := 1; // yes, use existing
PluginLink.CallService(MS_UTILS_OPENURL,bNewWindow,Integer(Pointer(Url)));
end;
procedure TfmGlobalSearch.edPassKeyPress(Sender: TObject; var Key: Char);
begin
if (key = Chr(VK_RETURN)) or (key = Chr(VK_TAB)) or (key = Chr(VK_ESCAPE)) then
key := #0;
end;
procedure TfmGlobalSearch.edPassKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then begin
bnSearch.Click;
Key := 0;
end;
end;
procedure TfmGlobalSearch.ShowAdvancedPanel(Show: Boolean);
begin
if Show then begin
if not gbAdvanced.Visible then
paSearch.Height := paSearch.Height + gbAdvanced.Height + 8;
gbAdvanced.Show;
end
else begin
if gbAdvanced.Visible then
paSearch.Height := paSearch.Height - gbAdvanced.Height - 8;
gbAdvanced.Hide;
end;
if gbAdvanced.Visible then
bnAdvanced.Caption := Translate('Advanced <<')
else
bnAdvanced.Caption := Translate('Advanced >>');
end;
procedure TfmGlobalSearch.ShowContacts(Show: Boolean);
begin
paContacts.Visible := Show;
spContacts.Visible := Show;
if (Show) and (paContacts.Width > 0) then
spContacts.LEft := paContacts.Width + paContacts.Left + 1;
end;
procedure TfmGlobalSearch.bnAdvancedClick(Sender: TObject);
begin
ShowAdvancedPanel(not gbAdvanced.Visible);
end;
procedure TfmGlobalSearch.SearchNext(Rev: Boolean; Warp: Boolean = True);
var
stext: WideString;
t,tCap: string;
res: Integer;
mcase,down: Boolean;
WndHandle: HWND;
begin
stext := HotString;
mcase := False;
if stext = '' then exit;
down := not hg.reversed;
if Rev then Down := not Down;
res := hg.Search(stext, mcase, not Warp, False, Warp, Down);
if res <> -1 then begin
// found
hg.Selected := res;
t := Translate('HotSearch: %s (F3 to find next)');
sb.SimpleText := WideFormat(AnsiToWideString(t,hppCodepage),[stext]);
end else begin
WndHandle := Handle;
tCap := Translate('History++ Search');
// not found
if Warp and (down = not hg.Reversed) then begin
// do warp?
if MessageBox(WndHandle, PChar(String(Translate('You have reached the end of the history.'))+
#10#13+String(Translate('Do you want to continue searching at the beginning?'))),
PChar(tCap), MB_YESNO or MB_DEFBUTTON1 or MB_ICONQUESTION) = ID_YES then
SearchNext(Rev,False);
end else begin
// not warped
hgState(Self,gsIdle);
t := Translate('"%s" not found');
if hppOSUnicode then
MessageBoxW(WndHandle, PWideChar(WideFormat(AnsiToWideString(t,hppCodepage),[stext])),
PWideChar(AnsiToWideString(tCap,hppCodepage)), MB_OK or MB_DEFBUTTON1 or 0)
else
MessageBox(WndHandle, PChar(Format(t,[stext])),
PChar(tCap), MB_OK or MB_DEFBUTTON1 or 0);
end;
end;
end;
procedure TfmGlobalSearch.SendMessage1Click(Sender: TObject);
begin
if hg.Selected <> -1 then begin
if GetSearchItem(hg.Selected).hContact = 0 then exit;
if GetSearchItem(hg.Selected).hContact <> 0 then SendMessageTo(GetSearchItem(hg.Selected).hContact);
end;
end;
procedure TfmGlobalSearch.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
Mask: Integer;
begin
if (key = VK_F3) and ((Shift=[]) or (Shift=[ssShift])) and (Length(History) > 0) then begin
SearchNext(ssShift in Shift,True);
key := 0;
end;
if (Key = VK_ESCAPE) then close;
if hg.State = gsInline then begin
exit;
end;
if (ssCtrl in Shift) then begin
if (key=Ord('R')) then begin
if hg.Selected <> -1 then ReplyQuoted(hg.Selected);
key:=0;
end;
if (key=Ord('M')) then begin
if hg.Selected <> -1 then SendMessage1.Click;
key:=0;
end;
if key=VK_RETURN then begin
if hg.Selected <> -1 then hgDblClick(Sender);
key:=0;
end;
end;
with Sender as TWinControl do
begin
if Perform(CM_CHILDKEY, Key, Integer(Sender)) <> 0 then
Exit;
Mask := 0;
case Key of
VK_TAB:
Mask := DLGC_WANTTAB;
VK_RETURN, VK_EXECUTE, VK_ESCAPE, VK_CANCEL:
Mask := DLGC_WANTALLKEYS;
end;
if (Mask <> 0)
and (Perform(CM_WANTSPECIALKEY, Key, 0) = 0)
and (Perform(WM_GETDLGCODE, 0, 0) and Mask = 0)
and (Self.Perform(CM_DIALOGKEY, Key, 0) <> 0)
then Exit;
end;
end;
procedure TfmGlobalSearch.hgSearchFinished(Sender: TObject; Text: WideString;
Found: Boolean);
var
t: WideString;
begin
//if LastSearch <> lsHotSearch then
// LastHotIdx := hg.Selected;
//LastSearch := lsHotSearch;
if Text = '' then begin
//if (LastHotIdx <> -1) and (HotString <> '') then
// hg.Selected := LastHotIdx;
//LastSearch := lsNone;
HotString := Text;
hgState(Self,gsIdle);
exit;
end;
HotString := Text;
{
if Found then t := 'Search: "'+Text+'" (Ctrl+Enter to search again)'
else t := 'Search: "'+Text+'" (not found)';
sb.SimpleText := t;
}
if not Found then t := HotString
else t := Text;
sb.SimpleText := WideFormat(AnsiToWideString(Translate('HotSearch: %s (F3 to find next)'),hppCodepage),[t]);
//if Found then HotString := Text;
end;
procedure TfmGlobalSearch.hgSearchItem(Sender: TObject; Item, ID: Integer;
var Found: Boolean);
begin
Found := (ID = GetSearchItem(Item).hDBEvent);
end;
procedure TfmGlobalSearch.hgSelect(Sender: TObject; Item, OldItem: Integer);
var
i,hCont,Index: Integer;
begin
if hg.HotString = '' then begin
hgState(hg,gsIdle);
end;
{ if Item = -1 then exit;
index := -1;
hCont := History[Item].hContact;
for i := 0 to lvContacts.Items.Count-1 do
if integer(lvContacts.Items.Item[i].Data) = hCont then begin
Index := i;
break;
end;
if Index = -1 then exit;
lvContacts.OnSelectItem := nil;
lvContacts.Items.Item[index].MakeVisible(false);
lvContacts.Items.Item[index].Selected := true;
lvContacts.OnSelectItem := self.lvContactsSelectItem;}
end;
procedure TfmGlobalSearch.hgState(Sender: TObject; State: TGridState);
var
Idle: Boolean;
t: String;
begin
if csDestroying in ComponentState then
exit;
Idle := (State <> gsDelete);
case State of
// if change, change also in SMFinished:
gsIdle: t := Format('%.0n items in %.0n contacts found. Searched for %.1f sec in %.0n items.',[Length(History)/1, ContactsFound/1, stime/1000, AllItems/1, AllContacts/1]);
gsLoad: t := Translate('Loading...');
gsSave: t := Translate('Saving...');
gsSearch: t := Translate('Searching...');
gsDelete: t := Translate('Deleting...');
end;
if IsSearching then
// if change, change also in SMProgress
sb.SimpleText := Format('Searching... %.0n items in %.0n contacts found',[Length(History)/1, ContactsFound/1]);
sb.SimpleText := AnsiToWideString(t,hppCodepage);
end;
initialization
fmGlobalSearch := nil;
end.
|
unit TTSUTLSCANTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSUTLSCANRecord = record
PLenderNum: String[4];
PUtlNumber: String[20];
PCifFlag: String[1];
PLoanNumber: String[20];
PCollNum: SmallInt;
PCategory: String[8];
PSubNumber: Integer;
PRank: SmallInt;
PItemMatch: Boolean;
PCollMatch: Boolean;
PNameMatch: Boolean;
PLoanMatch: Boolean;
End;
TTTSUTLSCANBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSUTLSCANRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSUTLSCAN = (TTSUTLSCANPrimaryKey, TTSUTLSCANByRank, TTSUTLSCANByRankOnly);
TTTSUTLSCANTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFUtlNumber: TStringField;
FDFCifFlag: TStringField;
FDFLoanNumber: TStringField;
FDFCollNum: TSmallIntField;
FDFCategory: TStringField;
FDFSubNumber: TIntegerField;
FDFRank: TSmallIntField;
FDFItemMatch: TBooleanField;
FDFCollMatch: TBooleanField;
FDFNameMatch: TBooleanField;
FDFLoanMatch: TBooleanField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPUtlNumber(const Value: String);
function GetPUtlNumber:String;
procedure SetPCifFlag(const Value: String);
function GetPCifFlag:String;
procedure SetPLoanNumber(const Value: String);
function GetPLoanNumber:String;
procedure SetPCollNum(const Value: SmallInt);
function GetPCollNum:SmallInt;
procedure SetPCategory(const Value: String);
function GetPCategory:String;
procedure SetPSubNumber(const Value: Integer);
function GetPSubNumber:Integer;
procedure SetPRank(const Value: SmallInt);
function GetPRank:SmallInt;
procedure SetPItemMatch(const Value: Boolean);
function GetPItemMatch:Boolean;
procedure SetPCollMatch(const Value: Boolean);
function GetPCollMatch:Boolean;
procedure SetPNameMatch(const Value: Boolean);
function GetPNameMatch:Boolean;
procedure SetPLoanMatch(const Value: Boolean);
function GetPLoanMatch:Boolean;
procedure SetEnumIndex(Value: TEITTSUTLSCAN);
function GetEnumIndex: TEITTSUTLSCAN;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSUTLSCANRecord;
procedure StoreDataBuffer(ABuffer:TTTSUTLSCANRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFUtlNumber: TStringField read FDFUtlNumber;
property DFCifFlag: TStringField read FDFCifFlag;
property DFLoanNumber: TStringField read FDFLoanNumber;
property DFCollNum: TSmallIntField read FDFCollNum;
property DFCategory: TStringField read FDFCategory;
property DFSubNumber: TIntegerField read FDFSubNumber;
property DFRank: TSmallIntField read FDFRank;
property DFItemMatch: TBooleanField read FDFItemMatch;
property DFCollMatch: TBooleanField read FDFCollMatch;
property DFNameMatch: TBooleanField read FDFNameMatch;
property DFLoanMatch: TBooleanField read FDFLoanMatch;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PUtlNumber: String read GetPUtlNumber write SetPUtlNumber;
property PCifFlag: String read GetPCifFlag write SetPCifFlag;
property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber;
property PCollNum: SmallInt read GetPCollNum write SetPCollNum;
property PCategory: String read GetPCategory write SetPCategory;
property PSubNumber: Integer read GetPSubNumber write SetPSubNumber;
property PRank: SmallInt read GetPRank write SetPRank;
property PItemMatch: Boolean read GetPItemMatch write SetPItemMatch;
property PCollMatch: Boolean read GetPCollMatch write SetPCollMatch;
property PNameMatch: Boolean read GetPNameMatch write SetPNameMatch;
property PLoanMatch: Boolean read GetPLoanMatch write SetPLoanMatch;
published
property Active write SetActive;
property EnumIndex: TEITTSUTLSCAN read GetEnumIndex write SetEnumIndex;
end; { TTTSUTLSCANTable }
procedure Register;
implementation
procedure TTTSUTLSCANTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFUtlNumber := CreateField( 'UtlNumber' ) as TStringField;
FDFCifFlag := CreateField( 'CifFlag' ) as TStringField;
FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField;
FDFCollNum := CreateField( 'CollNum' ) as TSmallIntField;
FDFCategory := CreateField( 'Category' ) as TStringField;
FDFSubNumber := CreateField( 'SubNumber' ) as TIntegerField;
FDFRank := CreateField( 'Rank' ) as TSmallIntField;
FDFItemMatch := CreateField( 'ItemMatch' ) as TBooleanField;
FDFCollMatch := CreateField( 'CollMatch' ) as TBooleanField;
FDFNameMatch := CreateField( 'NameMatch' ) as TBooleanField;
FDFLoanMatch := CreateField( 'LoanMatch' ) as TBooleanField;
end; { TTTSUTLSCANTable.CreateFields }
procedure TTTSUTLSCANTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSUTLSCANTable.SetActive }
procedure TTTSUTLSCANTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSUTLSCANTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSUTLSCANTable.SetPUtlNumber(const Value: String);
begin
DFUtlNumber.Value := Value;
end;
function TTTSUTLSCANTable.GetPUtlNumber:String;
begin
result := DFUtlNumber.Value;
end;
procedure TTTSUTLSCANTable.SetPCifFlag(const Value: String);
begin
DFCifFlag.Value := Value;
end;
function TTTSUTLSCANTable.GetPCifFlag:String;
begin
result := DFCifFlag.Value;
end;
procedure TTTSUTLSCANTable.SetPLoanNumber(const Value: String);
begin
DFLoanNumber.Value := Value;
end;
function TTTSUTLSCANTable.GetPLoanNumber:String;
begin
result := DFLoanNumber.Value;
end;
procedure TTTSUTLSCANTable.SetPCollNum(const Value: SmallInt);
begin
DFCollNum.Value := Value;
end;
function TTTSUTLSCANTable.GetPCollNum:SmallInt;
begin
result := DFCollNum.Value;
end;
procedure TTTSUTLSCANTable.SetPCategory(const Value: String);
begin
DFCategory.Value := Value;
end;
function TTTSUTLSCANTable.GetPCategory:String;
begin
result := DFCategory.Value;
end;
procedure TTTSUTLSCANTable.SetPSubNumber(const Value: Integer);
begin
DFSubNumber.Value := Value;
end;
function TTTSUTLSCANTable.GetPSubNumber:Integer;
begin
result := DFSubNumber.Value;
end;
procedure TTTSUTLSCANTable.SetPRank(const Value: SmallInt);
begin
DFRank.Value := Value;
end;
function TTTSUTLSCANTable.GetPRank:SmallInt;
begin
result := DFRank.Value;
end;
procedure TTTSUTLSCANTable.SetPItemMatch(const Value: Boolean);
begin
DFItemMatch.Value := Value;
end;
function TTTSUTLSCANTable.GetPItemMatch:Boolean;
begin
result := DFItemMatch.Value;
end;
procedure TTTSUTLSCANTable.SetPCollMatch(const Value: Boolean);
begin
DFCollMatch.Value := Value;
end;
function TTTSUTLSCANTable.GetPCollMatch:Boolean;
begin
result := DFCollMatch.Value;
end;
procedure TTTSUTLSCANTable.SetPNameMatch(const Value: Boolean);
begin
DFNameMatch.Value := Value;
end;
function TTTSUTLSCANTable.GetPNameMatch:Boolean;
begin
result := DFNameMatch.Value;
end;
procedure TTTSUTLSCANTable.SetPLoanMatch(const Value: Boolean);
begin
DFLoanMatch.Value := Value;
end;
function TTTSUTLSCANTable.GetPLoanMatch:Boolean;
begin
result := DFLoanMatch.Value;
end;
procedure TTTSUTLSCANTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('UtlNumber, String, 20, N');
Add('CifFlag, String, 1, N');
Add('LoanNumber, String, 20, N');
Add('CollNum, SmallInt, 0, N');
Add('Category, String, 8, N');
Add('SubNumber, Integer, 0, N');
Add('Rank, SmallInt, 0, N');
Add('ItemMatch, Boolean, 0, N');
Add('CollMatch, Boolean, 0, N');
Add('NameMatch, Boolean, 0, N');
Add('LoanMatch, Boolean, 0, N');
end;
end;
procedure TTTSUTLSCANTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;UtlNumber;CifFlag;LoanNumber;CollNum;Category;SubNumber, Y, N, N, N');
Add('ByRank, LenderNum;UtlNumber;Rank, N, N, N, Y');
Add('ByRankOnly, SubNumber, N, N, N, N');
end;
end;
procedure TTTSUTLSCANTable.SetEnumIndex(Value: TEITTSUTLSCAN);
begin
case Value of
TTSUTLSCANPrimaryKey : IndexName := '';
TTSUTLSCANByRank : IndexName := 'ByRank';
TTSUTLSCANByRankOnly: IndexName := 'ByRankOnly';
end;
end;
function TTTSUTLSCANTable.GetDataBuffer:TTTSUTLSCANRecord;
var buf: TTTSUTLSCANRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PUtlNumber := DFUtlNumber.Value;
buf.PCifFlag := DFCifFlag.Value;
buf.PLoanNumber := DFLoanNumber.Value;
buf.PCollNum := DFCollNum.Value;
buf.PCategory := DFCategory.Value;
buf.PSubNumber := DFSubNumber.Value;
buf.PRank := DFRank.Value;
buf.PItemMatch := DFItemMatch.Value;
buf.PCollMatch := DFCollMatch.Value;
buf.PNameMatch := DFNameMatch.Value;
buf.PLoanMatch := DFLoanMatch.Value;
result := buf;
end;
procedure TTTSUTLSCANTable.StoreDataBuffer(ABuffer:TTTSUTLSCANRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFUtlNumber.Value := ABuffer.PUtlNumber;
DFCifFlag.Value := ABuffer.PCifFlag;
DFLoanNumber.Value := ABuffer.PLoanNumber;
DFCollNum.Value := ABuffer.PCollNum;
DFCategory.Value := ABuffer.PCategory;
DFSubNumber.Value := ABuffer.PSubNumber;
DFRank.Value := ABuffer.PRank;
DFItemMatch.Value := ABuffer.PItemMatch;
DFCollMatch.Value := ABuffer.PCollMatch;
DFNameMatch.Value := ABuffer.PNameMatch;
DFLoanMatch.Value := ABuffer.PLoanMatch;
end;
function TTTSUTLSCANTable.GetEnumIndex: TEITTSUTLSCAN;
var iname : string;
begin
result := TTSUTLSCANPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSUTLSCANPrimaryKey;
if iname = 'BYRANK' then result := TTSUTLSCANByRank;
if iname = 'BYRANKONLY' then result := TTSUTLSCANByRankOnly;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSUTLSCANTable, TTTSUTLSCANBuffer ] );
end; { Register }
function TTTSUTLSCANBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..12] of string = ('LENDERNUM','UTLNUMBER','CIFFLAG','LOANNUMBER','COLLNUM','CATEGORY'
,'SUBNUMBER','RANK','ITEMMATCH','COLLMATCH','NAMEMATCH'
,'LOANMATCH' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 12) and (flist[x] <> s) do inc(x);
if x <= 12 then result := x else result := 0;
end;
function TTTSUTLSCANBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftSmallInt;
6 : result := ftString;
7 : result := ftInteger;
8 : result := ftSmallInt;
9 : result := ftBoolean;
10 : result := ftBoolean;
11 : result := ftBoolean;
12 : result := ftBoolean;
end;
end;
function TTTSUTLSCANBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PUtlNumber;
3 : result := @Data.PCifFlag;
4 : result := @Data.PLoanNumber;
5 : result := @Data.PCollNum;
6 : result := @Data.PCategory;
7 : result := @Data.PSubNumber;
8 : result := @Data.PRank;
9 : result := @Data.PItemMatch;
10 : result := @Data.PCollMatch;
11 : result := @Data.PNameMatch;
12 : result := @Data.PLoanMatch;
end;
end;
end.
|
unit MailUtils;
interface
uses
SysUtils;
const
csInvalidMailAddrChars = ['\', '/', ':', '*', '?', '"', '<', '>', '|'];
function RemoveFullPath(const Path : string) : boolean;
function GenMessageId(Date : TDateTime) : string;
procedure TranslateChars(var str : string; fCh, tCh : char);
function GetAccountPath(const World, Account : string) : string;
function ValidMailAddress(const Addr : string) : boolean;
function ExtractAddressAccount(const Addr : string) : string;
function ExistsAccountPath(const World, Addr : string) : boolean;
implementation
uses
Windows, FileCtrl, IniFiles, MailData, ShellAPI, CompStringsParser,
BaseUtils;
// Remove a full path
function RemoveFullPath(const Path : string) : boolean;
var
FileOp : TSHFileOpStruct;
tmp : array[0..MAX_PATH] of char;
begin
fillchar(tmp, sizeof(tmp), 0);
strpcopy(tmp, Path);
// If Path is a folder the last '\' must be removed.
if Path[length(Path)] = '\'
then tmp[length(Path)-1] := #0;
with FileOp do
begin
wFunc := FO_DELETE;
Wnd := 0;
pFrom := tmp;
pTo := nil;
fFlags := FOF_NOCONFIRMATION or FOF_SILENT;
hNameMappings := nil;
end;
try
if DirectoryExists(Path)
then result := SHFileOperation( FileOp ) = 0
else result := true;
except
result := false;
end;
end;
function GenMessageId(Date : TDateTime) : string;
begin
result := DateTimeToAbc(EncodeDate(9999, 12, 31) - Date) + IntToAbc(random(25), 1);
end;
procedure TranslateChars(var str : string; fCh, tCh : char);
var
i : integer;
begin
for i := 1 to length(str) do
if str[i] = fCh
then str[i] := tCh;
end;
function GetAccountPath(const World, Account : string) : string;
var
aux : string;
begin
aux := Account;
if pos('@', aux) = 0
then result := GetMailRoot + 'Worlds\' + World + '\' + aux + '.' + World + '.net\'
else
begin
TranslateChars(aux, '@', '.');
result := GetMailRoot + 'Worlds\' + World + '\' + aux + '\';
end;
end;
function ValidMailAddress(const Addr : string) : boolean;
var
len : integer;
i : integer;
begin
len := length(Addr);
i := 1;
while (i <= len) and not (Addr[i] in csInvalidMailAddrChars) do
inc(i);
result := i > len;
end;
function ExtractAddressAccount(const Addr : string) : string;
var
p : integer;
begin
p := 1;
result := GetNextStringUpTo(Addr, p, '@');
end;
function ExistsAccountPath(const World, Addr : string) : boolean;
begin
result := FileCtrl.DirectoryExists(GetAccountPath(World, Addr));
end;
end.
|
program rle;
uses sysutils;
function fileExists(fromFileName : string) : boolean;
var
f : TEXT;
begin
(*$I-*)
assign(f, fromFileName);
Reset(f); //Creates error
if IOResult <> 0 then begin
fileExists := FALSE;
end else
fileExists := TRUE;
(*$I+*)
end;
function isNumber(character : char) : boolean;
begin
if(ord(character) < 48) or (ord(character) > 57)then
isNumber := FALSE
else
isNumber := TRUE;
end;
function addCharCountAtEnd(previousChar : char; charOccurances : integer; compressedLine : string) : string;
var
charOccurancesString : string;
begin
if(charOccurances > 2) then begin
str(charOccurances, charOccurancesString);
compressedLine := compressedLine + previousChar + charOccurancesString;
end else
compressedLine := compressedLine + stringOfChar(previousChar, charOccurances);
addCharCountAtEnd := compressedLine;
end;
function compressLine(line : string) : string;
var
i, lineLength : integer;
previousChar, currentChar : char;
charOccurances : integer;
compressedLine : string;
begin
i := 1;
lineLength := length(line);
charOccurances := 1;
compressedLine := '';
while (i <= lineLength) do begin
currentChar := line[i];
if(isNumber(currentChar)) then begin
writeln('Can''t compress text with numbers in it!');
halt;
end;
if(currentChar = previousChar) then begin
inc(charOccurances);
end else if (i = 1) then
previousChar := currentChar // there is no prev character so just set cur char to prev.
else begin
compressedLine := addCharCountAtEnd(previousChar, charOccurances, compressedLine);
previousChar := currentChar;
charOccurances := 1;
end;
inc(i);
end;
compressedLine := addCharCountAtEnd(previousChar, charOccurances, compressedLine);
compressLine := compressedLine;
end;
procedure compress(fromFileName, toFileName : string);
var
inFile, outFile : TEXT;
line : string;
begin
assign(inFile, fromFileName);
assign(outFile, toFileName);
reset(inFile);
rewrite(outFile); // overwrite if file exists
while not eof(inFile) do begin
readln(inFile, line);
line := compressLine(line);
writeln(outFile, line);
end;
close(inFile);
close(outFile);
end;
function decompressLine(line : string) : string;
var
i, lineLength : integer;
decompressedLine : string;
begin
decompressedLine := '';
i := 1;
lineLength := length(line);
while (i <= lineLength) do begin
if(isNumber(line[i])) then begin
decompressedLine := decompressedLine + stringOfChar(line[i-1], strToInt(line[i])-1);
end else
decompressedLine := decompressedLine + line[i];
inc(i);
end;
decompressLine := decompressedLine;
end;
procedure decompress(fromFileName, toFileName : string);
var
inFile, outFile : TEXT;
line : string;
begin
assign(inFile, fromFileName);
assign(outFile, toFileName);
reset(inFile);
rewrite(outFile); // overwrite if file exists
while not eof(inFile) do begin
readln(inFile, line);
line := decompressLine(line);
writeln(outFile, line);
end;
close(inFile);
close(outFile);
end;
var
option : string;
fromFileName, toFileName : string;
begin
option := '';
fromFileName := '';
toFileName := '';
case paramCount of
0: begin
end;
1: begin
if(paramStr(1)[1] = '-') then
option := paramStr(1)
else
fromFileName := paramStr(1);
end;
2: begin
if paramStr(1)[1] = '-' then begin
option := paramStr(1);
fromFileName := paramStr(2);
end else begin
fromFileName := paramStr(1);
toFileName := paramStr(2);
end;
end;
3: begin
option := paramStr(1);
fromFileName := paramStr(2);
toFileName := paramStr(3);
end;
else begin
writeLn('Usage: rle [ -c | -d ] [ inFile [ outFileName ] ]');
halt;
end;
end;
if not fileExists(fromFileName) then begin
writeLn('inFile does not exist! Unable to complete operation');
halt;
end;
if (option = '-c') or (option = '') then // default -b
compress(fromFileName, toFileName)
else if (option = '-d') then
decompress(fromFileName, toFileName)
else begin
writeLn('Unknown option ', option);
halt;
end;
end.
|
Program analyzer;
type AIterator = class
public
constructor Create();
destructor Destroy(); virtual;
function GetChar() : char; virtual;
end;
constructor AIterator.Create(); begin end;
destructor AIterator.Destroy(); begin end;
function AIterator.GetChar() : char;
begin
end;
type Iterator = class(AIterator)
source : string;
position, lengthStr : integer;
public
constructor Create(_source : string);
destructor Destroy(); override;
function CurrentPosition() : integer;
function GetChar() : char; override;
procedure Next();
function isEnd() : boolean;
end;
constructor Iterator.Create(_source : string);
begin
self.source := _source;
self.position := 1;
self.lengthStr := length(source);
end;
destructor Iterator.Destroy(); begin end;
function Iterator.CurrentPosition() : integer;
begin
if(position <= lengthStr) then CurrentPosition := position;
end;
function Iterator.GetChar() : char;
begin
if(position <= lengthStr) then GetChar := source[CurrentPosition()];
end;
procedure Iterator.Next();
begin
if(position <= lengthStr) then inc(position);
end;
procedure Iterator.isEnd();
begin
if(position = lengthStr) then isEnd := true
else isEnd := false;
end;
{LexTools}
type LexTools = class
public
class function isLetter(symbol : char) : boolean;
class function isDigit(symbol : char) : boolean;
class function isSpace(symbol : char) : boolean;
end;
class function LexTools.isLetter(symbol : char) : boolean;
begin
if((symbol in ['A'..'Z']) or (symbol in ['a'..'z'])) then isLetter := true
else isLetter := false;
end;
class function LexTools.isDigit(symbol : char) : boolean;
begin
if(symbol in ['0'..'9']) then isDigit := true
else isDigit := false;
end;
class function LexTools.isSpace(symbol : char) : boolean;
begin
if(symbol = ' ') then isSpace := true
else isSpace := false;
end;
{/LexTools}
type LAnalyzator = class
private
operations : set of char;
source : Iterator;
function isOperations(symbol : char) : boolean;
public
constructor Create(_source : Iterator);
destructor Destroy();
function GetLexem() : string;
end;
constructor LAnalyzator.Create(_source : Iterator);
begin
self.source := _source;
operations := ['+', '-', '/', '*'];
end;
function LAnalyzator.GetLexem() : string;
var lexem : string;
s : char;
begin
while(not source.isEnd()) do
begin
s := source.GetChar();
if(LexTools.isLetter(s)) then
begin
while(LexTools.isLetter(s) or LexTools.isDigit(s)) do
begin
writeln('letter');
source.Next();
writeln(source.CurrentPosition());
end;
end;
if(LexTools.isDigit(s)) then
begin
writeln('digit');
end;
source.Next();
end;
GetLexem := '';
end;
destructor LAnalyzator.Destroy(); begin end;
function LAnalyzator.isOperations(symbol : char) : boolean;
begin
if(symbol in operations) then isOperations := true
else isOperations := false;
end;
{-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-}
var it : Iterator;
la : LAnalyzator;
Begin
it := Iterator.Create('string12312');
la := LAnalyzator.Create(it);
while(la.GetLexem <> '') do writeln(la.GetLexem());
it.Destroy();
End. |
unit MVC_Blog.Model.Entity;
interface
uses
Data.DB, MVC_Blog.Model.Conexao;
type
iModelEntidade = interface
function DataSet ( aValue : TDataSource ) : iModelEntidade;
procedure Open;
end;
iModelEntidadeFactory = interface
function Produto : iModelEntidade;
end;
Type
TModelEntidadeProduto = class(TInterfacedObject, iModelEntidade)
private
FQuery : iModelQuery;
public
constructor Create;
destructor Destroy; override;
class function New : iModelEntidade;
function DataSet ( aValue : TDataSource ) : iModelEntidade;
procedure Open;
end;
type
TModelEntidadesFactory = class(TInterfacedObject, iModelEntidadeFactory)
private
FProduto : iModelEntidade;
public
constructor Create;
destructor Destroy; override;
class function New : iModelEntidadeFactory;
function Produto : iModelEntidade;
end;
implementation
{ TModelEntidadeProduto }
constructor TModelEntidadeProduto.Create;
begin
FQuery := TModelConexaoFactory.New.Query;
end;
function TModelEntidadeProduto.DataSet(aValue: TDataSource): iModelEntidade;
begin
Result := Self;
aValue.DataSet := TDataSet(FQuery.Query);
end;
destructor TModelEntidadeProduto.Destroy;
begin
inherited;
end;
class function TModelEntidadeProduto.New: iModelEntidade;
begin
Result := Self.Create;
end;
procedure TModelEntidadeProduto.Open;
begin
FQuery.Open('SELECT * FROM PRODUTO');
end;
{ TModelEntidadesFactory }
constructor TModelEntidadesFactory.Create;
begin
inherited;
end;
destructor TModelEntidadesFactory.Destroy;
begin
inherited;
end;
class function TModelEntidadesFactory.New: iModelEntidadeFactory;
begin
Result := Self.Create;
end;
function TModelEntidadesFactory.Produto: iModelEntidade;
begin
if not Assigned(FProduto) then
FProduto := TModelEntidadeProduto.New;
Result := FProduto;
end;
end.
|
{ CSI 1101-X, Winter, 1999 }
{ Assignment 7 }
{ Identification: Mark Sattolo, student# 428500 }
{ tutorial group DGD-4, t.a. = Jensen Boire }
program a7 (input,output) ;
type
bits = 0..1 ;
nodeptr = ^node ;
node = record
bit: bits ;
next: nodeptr
end ;
number = nodeptr ;
markfile = text ;
var
memory_count: integer;
{ *************** MEMORY MANAGEMENT ************************* }
procedure get_node( var P: nodeptr );
BEGIN
memory_count := memory_count + 1 ;
new( P )
END ;
procedure return_node(var P: nodeptr) ;
BEGIN
memory_count := memory_count - 1 ;
P^.bit := 1 - P^.bit ; {* note: there is no bogus bit value so to try to make *}
P^.next := nil ; {* bugs visible I flip the bit when the node is freed. *}
dispose( P ) ;
P := nil
END ;
{ ******************************************************* }
procedure destroy(var N:number) ;
BEGIN
if N <> nil then
BEGIN
destroy(N^.next) ;
return_node(N)
END
END; { proc destroy }
procedure insert_at_front(var L: number; V: bits) ;
var
p: nodeptr ;
BEGIN
get_node(p) ;
p^.bit := V ;
p^.next := L ;
L := p ;
END; { proc insert_at_front }
procedure insert_at_end(var L:number; V: bits) ;
BEGIN
if L = nil then
BEGIN
get_node(L) ;
L^.bit := V ;
L^.next := nil ;
END { if }
else
insert_at_end(L^.next, V) ;
END; { proc insert_at_end }
procedure read_number(var L, T: markfile; var N:number ) ;
var
b: char ;
BEGIN
N := Nil ; { runtime error if N not initialized }
while not eoln(L) do
BEGIN
read(L, b) ;
case b of
'1' : insert_at_front(N, 1) ;
'0' : insert_at_front(N, 0) ;
else
BEGIN
writeln(T, 'Error: improper input value: converting to 0.') ;
insert_at_front(N, 0) ;
END { else }
end { case }
END; { while }
readln(L) ;
if N = Nil then
insert_at_front(N, 0) ;
END; { proc read_number }
procedure write_number(var T: markfile; N: number) ;
BEGIN
if N <> Nil then
BEGIN
write_number(T, N^.next) ;
write(T, N^.bit)
END
END; { proc write_number }
procedure add (N1, N2: number; var Sum: number) ;
var
tempsum: integer ;
inbit, carry: bits ;
p1, p2: number ;
BEGIN
carry := 0 ;
p1 := N1 ;
p2 := N2 ;
Sum := Nil ; { runtime error if Sum not initialized }
while ((p1 <> Nil) or (p2 <> Nil)) do
BEGIN
if (p1 = Nil) then
tempsum := p2^.bit + carry
else
if (p2 = Nil) then
tempsum := p1^.bit + carry
else
tempsum := p1^.bit + p2^.bit + carry ;
if (tempsum < 2) then
BEGIN
inbit := tempsum ;
carry := 0 ;
END
else
BEGIN
inbit := (tempsum - 2) ;
carry := 1 ;
END ;
insert_at_end(SUM, inbit) ;
if p1 <> Nil then
p1 := p1^.next ;
if p2 <> Nil then
p2 := p2^.next ;
END; { while }
if (carry = 1) then
insert_at_end(SUM, carry) ;
END; { proc add }
{ ******************************************************* }
procedure multiply (N1, N2: number; var shift, prod: number) ;
var
count, i: integer ;
mult, tempProd: number ;
BEGIN
{ initialize count - keeps track of the number of places to shift in N1 }
count := 0 ;
{ use pointers shift and mult to step through N1 and N2 respectively }
shift := N1 ;
mult := N2 ;
{ initialize prod - ?runtime error if prod not initialized? }
prod := Nil ;
{ continue loop as long as N2 is not Nil }
while mult <> Nil do
BEGIN
{ process only if the current bit of N2 is 1 }
if (mult^.bit = 1) then
BEGIN
{ shift N1 the required number of places - i.e. the number in 'count' }
for i := 1 to count do
insert_at_front(shift, 0) ;
{ add the shifted N1 to the current prod and store the total in tempProd }
add(prod, shift, tempProd) ;
{ destroy the old prod to release the nodes }
destroy(prod) ;
{ prod gets the new total }
prod := tempProd ;
{ reset count - next loop will add zero's, if needed, to the existing 'shift' }
count := 0 ;
END; { if }
{ increment 'count' so the next loop will add one more zero to 'shift', if necessary }
inc(count) ;
{ if not at Nil, move to the next node of N2 }
if mult <> Nil then
mult := mult^.next ;
END; { while }
{ if N2 was Nil or all zero's and prod stayed at Nil, then prod gets zero }
if (prod = Nil) then
insert_at_front(prod, 0) ;
END; { proc multiply }
{ =========== TESTING PROCEDURES ============= }
procedure assignment7;
var
N1, N2, shift, prod: number ;
Louise, Thomas: markfile ;
BEGIN
{ open and set the output file }
assign(Thomas, 'A7.run') ; { <<<<<<<<<<<< CHANGE TO A7.OUT <<<<<<<<<< }
rewrite(Thomas) ;
{ open and set the input file }
assign(Louise, 'A7.dat') ;
reset(Louise) ;
writeln('Opened text files.') ;
writeln('==================================') ;
{ continue reading numbers from input file until end-of-file }
while not EOF(Louise) do
BEGIN
writeln('Reading numbers from file ''A7.dat''') ;
writeln(Thomas) ;
{ get first number - N1 }
read_number(Louise, Thomas, N1);
write(Thomas, 'N1 = ');
write_number(Thomas, N1);
writeln(Thomas) ;
{ get second number - N2 }
read_number(Louise, Thomas, N2);
write(Thomas, 'N2 = ');
write_number(Thomas, N2);
writeln(Thomas) ;
{ multiply the two numbers and return the product and last shifted value of N1 }
multiply(N1, N2, shift, prod);
write(Thomas, 'Product = ');
write_number(Thomas, Prod);
writeln(Thomas) ;
writeln(Thomas) ;
writeln(Thomas, '---------------------------------------------------') ;
writeln('Multiplied the given numbers and wrote product to file ''A7.run''') ;
{ return all nodes - need to destroy shift vice N1 to return the extra nodes shifted in }
destroy(shift) ;
destroy(N2) ;
destroy(Prod) ;
writeln('Returned dynamic memory.') ;
writeln ;
END ;
{ close the input and output files }
close(Louise) ;
close(Thomas) ;
writeln('====================================================') ;
writeln('Closed text files. Procedure assignment7 ended.') ;
END; { proc assignment7 }
{***** YOU MUST CHANGE THIS PROCEDURE TO DESCRIBE YOURSELF *****}
procedure identify_myself ;
BEGIN
writeln ;
writeln('CSI 1101-X (winter,1999). Assignment #7.') ;
writeln('Mark Sattolo, student# 428500.') ;
writeln('tutorial section DGD-4, t.a. = Jensen Boire');
writeln
END ;
BEGIN { main program }
identify_myself ;
memory_count := 0 ;
assignment7 ;
writeln('Amount of dynamic memory allocated but not returned (should be 0) ',
memory_count:0) ;
writeln('PROGRAM ENDED. See file ''A7.run'' for the output.') ;
END.
|
unit InfoBSOATable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoBSOARecord = record
PLenderID: String[4];
PTranDate: String[8];
PTranType: String[3];
PTranID: String[5];
PModCount: SmallInt;
PAmount: Currency;
PBalance: Currency;
PComment: String[20];
PYrMo: String[6];
PTranCategory: String[1];
PUserId: String[10];
PTimeStamp: String[20];
End;
TInfoBSOAClass2 = class
public
PLenderID: String[4];
PTranDate: String[8];
PTranType: String[3];
PTranID: String[5];
PModCount: SmallInt;
PAmount: Currency;
PBalance: Currency;
PComment: String[20];
PYrMo: String[6];
PTranCategory: String[1];
PUserId: String[10];
PTimeStamp: String[20];
End;
// function CtoRInfoBSOA(AClass:TInfoBSOAClass):TInfoBSOARecord;
// procedure RtoCInfoBSOA(ARecord:TInfoBSOARecord;AClass:TInfoBSOAClass);
TInfoBSOABuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoBSOARecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoBSOA = (InfoBSOAPrimaryKey);
TInfoBSOATable = class( TDBISAMTableAU )
private
FDFLenderID: TStringField;
FDFTranDate: TStringField;
FDFTranType: TStringField;
FDFTranID: TStringField;
FDFModCount: TSmallIntField;
FDFAmount: TCurrencyField;
FDFBalance: TCurrencyField;
FDFComment: TStringField;
FDFYrMo: TStringField;
FDFTranCategory: TStringField;
FDFUserId: TStringField;
FDFTimeStamp: TStringField;
procedure SetPLenderID(const Value: String);
function GetPLenderID:String;
procedure SetPTranDate(const Value: String);
function GetPTranDate:String;
procedure SetPTranType(const Value: String);
function GetPTranType:String;
procedure SetPTranID(const Value: String);
function GetPTranID:String;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
procedure SetPAmount(const Value: Currency);
function GetPAmount:Currency;
procedure SetPBalance(const Value: Currency);
function GetPBalance:Currency;
procedure SetPComment(const Value: String);
function GetPComment:String;
procedure SetPYrMo(const Value: String);
function GetPYrMo:String;
procedure SetPTranCategory(const Value: String);
function GetPTranCategory:String;
procedure SetPUserId(const Value: String);
function GetPUserId:String;
procedure SetPTimeStamp(const Value: String);
function GetPTimeStamp:String;
procedure SetEnumIndex(Value: TEIInfoBSOA);
function GetEnumIndex: TEIInfoBSOA;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoBSOARecord;
procedure StoreDataBuffer(ABuffer:TInfoBSOARecord);
property DFLenderID: TStringField read FDFLenderID;
property DFTranDate: TStringField read FDFTranDate;
property DFTranType: TStringField read FDFTranType;
property DFTranID: TStringField read FDFTranID;
property DFModCount: TSmallIntField read FDFModCount;
property DFAmount: TCurrencyField read FDFAmount;
property DFBalance: TCurrencyField read FDFBalance;
property DFComment: TStringField read FDFComment;
property DFYrMo: TStringField read FDFYrMo;
property DFTranCategory: TStringField read FDFTranCategory;
property DFUserId: TStringField read FDFUserId;
property DFTimeStamp: TStringField read FDFTimeStamp;
property PLenderID: String read GetPLenderID write SetPLenderID;
property PTranDate: String read GetPTranDate write SetPTranDate;
property PTranType: String read GetPTranType write SetPTranType;
property PTranID: String read GetPTranID write SetPTranID;
property PModCount: SmallInt read GetPModCount write SetPModCount;
property PAmount: Currency read GetPAmount write SetPAmount;
property PBalance: Currency read GetPBalance write SetPBalance;
property PComment: String read GetPComment write SetPComment;
property PYrMo: String read GetPYrMo write SetPYrMo;
property PTranCategory: String read GetPTranCategory write SetPTranCategory;
property PUserId: String read GetPUserId write SetPUserId;
property PTimeStamp: String read GetPTimeStamp write SetPTimeStamp;
published
property Active write SetActive;
property EnumIndex: TEIInfoBSOA read GetEnumIndex write SetEnumIndex;
end; { TInfoBSOATable }
TInfoBSOAQuery = class( TDBISAMQueryAU )
private
FDFLenderID: TStringField;
FDFTranDate: TStringField;
FDFTranType: TStringField;
FDFTranID: TStringField;
FDFModCount: TSmallIntField;
FDFAmount: TCurrencyField;
FDFBalance: TCurrencyField;
FDFComment: TStringField;
FDFYrMo: TStringField;
FDFTranCategory: TStringField;
FDFUserId: TStringField;
FDFTimeStamp: TStringField;
procedure SetPLenderID(const Value: String);
function GetPLenderID:String;
procedure SetPTranDate(const Value: String);
function GetPTranDate:String;
procedure SetPTranType(const Value: String);
function GetPTranType:String;
procedure SetPTranID(const Value: String);
function GetPTranID:String;
procedure SetPModCount(const Value: SmallInt);
function GetPModCount:SmallInt;
procedure SetPAmount(const Value: Currency);
function GetPAmount:Currency;
procedure SetPBalance(const Value: Currency);
function GetPBalance:Currency;
procedure SetPComment(const Value: String);
function GetPComment:String;
procedure SetPYrMo(const Value: String);
function GetPYrMo:String;
procedure SetPTranCategory(const Value: String);
function GetPTranCategory:String;
procedure SetPUserId(const Value: String);
function GetPUserId:String;
procedure SetPTimeStamp(const Value: String);
function GetPTimeStamp:String;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
public
function GetDataBuffer:TInfoBSOARecord;
procedure StoreDataBuffer(ABuffer:TInfoBSOARecord);
property DFLenderID: TStringField read FDFLenderID;
property DFTranDate: TStringField read FDFTranDate;
property DFTranType: TStringField read FDFTranType;
property DFTranID: TStringField read FDFTranID;
property DFModCount: TSmallIntField read FDFModCount;
property DFAmount: TCurrencyField read FDFAmount;
property DFBalance: TCurrencyField read FDFBalance;
property DFComment: TStringField read FDFComment;
property DFYrMo: TStringField read FDFYrMo;
property DFTranCategory: TStringField read FDFTranCategory;
property DFUserId: TStringField read FDFUserId;
property DFTimeStamp: TStringField read FDFTimeStamp;
property PLenderID: String read GetPLenderID write SetPLenderID;
property PTranDate: String read GetPTranDate write SetPTranDate;
property PTranType: String read GetPTranType write SetPTranType;
property PTranID: String read GetPTranID write SetPTranID;
property PModCount: SmallInt read GetPModCount write SetPModCount;
property PAmount: Currency read GetPAmount write SetPAmount;
property PBalance: Currency read GetPBalance write SetPBalance;
property PComment: String read GetPComment write SetPComment;
property PYrMo: String read GetPYrMo write SetPYrMo;
property PTranCategory: String read GetPTranCategory write SetPTranCategory;
property PUserId: String read GetPUserId write SetPUserId;
property PTimeStamp: String read GetPTimeStamp write SetPTimeStamp;
published
property Active write SetActive;
end; { TInfoBSOATable }
procedure Register;
implementation
procedure TInfoBSOATable.CreateFields;
begin
FDFLenderID := CreateField( 'LenderID' ) as TStringField;
FDFTranDate := CreateField( 'TranDate' ) as TStringField;
FDFTranType := CreateField( 'TranType' ) as TStringField;
FDFTranID := CreateField( 'TranID' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
FDFAmount := CreateField( 'Amount' ) as TCurrencyField;
FDFBalance := CreateField( 'Balance' ) as TCurrencyField;
FDFComment := CreateField( 'Comment' ) as TStringField;
FDFYrMo := CreateField( 'YrMo' ) as TStringField;
FDFTranCategory := CreateField( 'TranCategory' ) as TStringField;
FDFUserId := CreateField( 'UserId' ) as TStringField;
FDFTimeStamp := CreateField( 'TimeStamp' ) as TStringField;
end; { TInfoBSOATable.CreateFields }
procedure TInfoBSOATable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoBSOATable.SetActive }
procedure TInfoBSOATable.SetPLenderID(const Value: String);
begin
DFLenderID.Value := Value;
end;
function TInfoBSOATable.GetPLenderID:String;
begin
result := DFLenderID.Value;
end;
procedure TInfoBSOATable.SetPTranDate(const Value: String);
begin
DFTranDate.Value := Value;
end;
function TInfoBSOATable.GetPTranDate:String;
begin
result := DFTranDate.Value;
end;
procedure TInfoBSOATable.SetPTranType(const Value: String);
begin
DFTranType.Value := Value;
end;
function TInfoBSOATable.GetPTranType:String;
begin
result := DFTranType.Value;
end;
procedure TInfoBSOATable.SetPTranID(const Value: String);
begin
DFTranID.Value := Value;
end;
function TInfoBSOATable.GetPTranID:String;
begin
result := DFTranID.Value;
end;
procedure TInfoBSOATable.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoBSOATable.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
procedure TInfoBSOATable.SetPAmount(const Value: Currency);
begin
DFAmount.Value := Value;
end;
function TInfoBSOATable.GetPAmount:Currency;
begin
result := DFAmount.Value;
end;
procedure TInfoBSOATable.SetPBalance(const Value: Currency);
begin
DFBalance.Value := Value;
end;
function TInfoBSOATable.GetPBalance:Currency;
begin
result := DFBalance.Value;
end;
procedure TInfoBSOATable.SetPComment(const Value: String);
begin
DFComment.Value := Value;
end;
function TInfoBSOATable.GetPComment:String;
begin
result := DFComment.Value;
end;
procedure TInfoBSOATable.SetPYrMo(const Value: String);
begin
DFYrMo.Value := Value;
end;
function TInfoBSOATable.GetPYrMo:String;
begin
result := DFYrMo.Value;
end;
procedure TInfoBSOATable.SetPTranCategory(const Value: String);
begin
DFTranCategory.Value := Value;
end;
function TInfoBSOATable.GetPTranCategory:String;
begin
result := DFTranCategory.Value;
end;
procedure TInfoBSOATable.SetPUserId(const Value: String);
begin
DFUserId.Value := Value;
end;
function TInfoBSOATable.GetPUserId:String;
begin
result := DFUserId.Value;
end;
procedure TInfoBSOATable.SetPTimeStamp(const Value: String);
begin
DFTimeStamp.Value := Value;
end;
function TInfoBSOATable.GetPTimeStamp:String;
begin
result := DFTimeStamp.Value;
end;
procedure TInfoBSOATable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderID, String, 4, N');
Add('TranDate, String, 8, N');
Add('TranType, String, 3, N');
Add('TranID, String, 5, N');
Add('ModCount, SmallInt, 0, N');
Add('Amount, Currency, 0, N');
Add('Balance, Currency, 0, N');
Add('Comment, String, 20, N');
Add('YrMo, String, 6, N');
Add('TranCategory, String, 1, N');
Add('UserId, String, 10, N');
Add('TimeStamp, String, 20, N');
end;
end;
procedure TInfoBSOATable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderID;TranDate;TranType;TranID, Y, Y, N, N');
end;
end;
procedure TInfoBSOATable.SetEnumIndex(Value: TEIInfoBSOA);
begin
case Value of
InfoBSOAPrimaryKey : IndexName := '';
end;
end;
function TInfoBSOATable.GetDataBuffer:TInfoBSOARecord;
var buf: TInfoBSOARecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderID := DFLenderID.Value;
buf.PTranDate := DFTranDate.Value;
buf.PTranType := DFTranType.Value;
buf.PTranID := DFTranID.Value;
buf.PModCount := DFModCount.Value;
buf.PAmount := DFAmount.Value;
buf.PBalance := DFBalance.Value;
buf.PComment := DFComment.Value;
buf.PYrMo := DFYrMo.Value;
buf.PTranCategory := DFTranCategory.Value;
buf.PUserId := DFUserId.Value;
buf.PTimeStamp := DFTimeStamp.Value;
result := buf;
end;
procedure TInfoBSOATable.StoreDataBuffer(ABuffer:TInfoBSOARecord);
begin
DFLenderID.Value := ABuffer.PLenderID;
DFTranDate.Value := ABuffer.PTranDate;
DFTranType.Value := ABuffer.PTranType;
DFTranID.Value := ABuffer.PTranID;
DFModCount.Value := ABuffer.PModCount;
DFAmount.Value := ABuffer.PAmount;
DFBalance.Value := ABuffer.PBalance;
DFComment.Value := ABuffer.PComment;
DFYrMo.Value := ABuffer.PYrMo;
DFTranCategory.Value := ABuffer.PTranCategory;
DFUserId.Value := ABuffer.PUserId;
DFTimeStamp.Value := ABuffer.PTimeStamp;
end;
function TInfoBSOATable.GetEnumIndex: TEIInfoBSOA;
var iname : string;
begin
result := InfoBSOAPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoBSOAPrimaryKey;
end;
procedure TInfoBSOAQuery.CreateFields;
begin
FDFLenderID := CreateField( 'LenderID' ) as TStringField;
FDFTranDate := CreateField( 'TranDate' ) as TStringField;
FDFTranType := CreateField( 'TranType' ) as TStringField;
FDFTranID := CreateField( 'TranID' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TSmallIntField;
FDFAmount := CreateField( 'Amount' ) as TCurrencyField;
FDFBalance := CreateField( 'Balance' ) as TCurrencyField;
FDFComment := CreateField( 'Comment' ) as TStringField;
FDFYrMo := CreateField( 'YrMo' ) as TStringField;
FDFTranCategory := CreateField( 'TranCategory' ) as TStringField;
FDFUserId := CreateField( 'UserId' ) as TStringField;
FDFTimeStamp := CreateField( 'TimeStamp' ) as TStringField;
end; { TInfoBSOAQuery.CreateFields }
procedure TInfoBSOAQuery.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoBSOAQuery.SetActive }
procedure TInfoBSOAQuery.SetPLenderID(const Value: String);
begin
DFLenderID.Value := Value;
end;
function TInfoBSOAQuery.GetPLenderID:String;
begin
result := DFLenderID.Value;
end;
procedure TInfoBSOAQuery.SetPTranDate(const Value: String);
begin
DFTranDate.Value := Value;
end;
function TInfoBSOAQuery.GetPTranDate:String;
begin
result := DFTranDate.Value;
end;
procedure TInfoBSOAQuery.SetPTranType(const Value: String);
begin
DFTranType.Value := Value;
end;
function TInfoBSOAQuery.GetPTranType:String;
begin
result := DFTranType.Value;
end;
procedure TInfoBSOAQuery.SetPTranID(const Value: String);
begin
DFTranID.Value := Value;
end;
function TInfoBSOAQuery.GetPTranID:String;
begin
result := DFTranID.Value;
end;
procedure TInfoBSOAQuery.SetPModCount(const Value: SmallInt);
begin
DFModCount.Value := Value;
end;
function TInfoBSOAQuery.GetPModCount:SmallInt;
begin
result := DFModCount.Value;
end;
procedure TInfoBSOAQuery.SetPAmount(const Value: Currency);
begin
DFAmount.Value := Value;
end;
function TInfoBSOAQuery.GetPAmount:Currency;
begin
result := DFAmount.Value;
end;
procedure TInfoBSOAQuery.SetPBalance(const Value: Currency);
begin
DFBalance.Value := Value;
end;
function TInfoBSOAQuery.GetPBalance:Currency;
begin
result := DFBalance.Value;
end;
procedure TInfoBSOAQuery.SetPComment(const Value: String);
begin
DFComment.Value := Value;
end;
function TInfoBSOAQuery.GetPComment:String;
begin
result := DFComment.Value;
end;
procedure TInfoBSOAQuery.SetPYrMo(const Value: String);
begin
DFYrMo.Value := Value;
end;
function TInfoBSOAQuery.GetPYrMo:String;
begin
result := DFYrMo.Value;
end;
procedure TInfoBSOAQuery.SetPTranCategory(const Value: String);
begin
DFTranCategory.Value := Value;
end;
function TInfoBSOAQuery.GetPTranCategory:String;
begin
result := DFTranCategory.Value;
end;
procedure TInfoBSOAQuery.SetPUserId(const Value: String);
begin
DFUserId.Value := Value;
end;
function TInfoBSOAQuery.GetPUserId:String;
begin
result := DFUserId.Value;
end;
procedure TInfoBSOAQuery.SetPTimeStamp(const Value: String);
begin
DFTimeStamp.Value := Value;
end;
function TInfoBSOAQuery.GetPTimeStamp:String;
begin
result := DFTimeStamp.Value;
end;
function TInfoBSOAQuery.GetDataBuffer:TInfoBSOARecord;
var buf: TInfoBSOARecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderID := DFLenderID.Value;
buf.PTranDate := DFTranDate.Value;
buf.PTranType := DFTranType.Value;
buf.PTranID := DFTranID.Value;
buf.PModCount := DFModCount.Value;
buf.PAmount := DFAmount.Value;
buf.PBalance := DFBalance.Value;
buf.PComment := DFComment.Value;
buf.PYrMo := DFYrMo.Value;
buf.PTranCategory := DFTranCategory.Value;
buf.PUserId := DFUserId.Value;
buf.PTimeStamp := DFTimeStamp.Value;
result := buf;
end;
procedure TInfoBSOAQuery.StoreDataBuffer(ABuffer:TInfoBSOARecord);
begin
DFLenderID.Value := ABuffer.PLenderID;
DFTranDate.Value := ABuffer.PTranDate;
DFTranType.Value := ABuffer.PTranType;
DFTranID.Value := ABuffer.PTranID;
DFModCount.Value := ABuffer.PModCount;
DFAmount.Value := ABuffer.PAmount;
DFBalance.Value := ABuffer.PBalance;
DFComment.Value := ABuffer.PComment;
DFYrMo.Value := ABuffer.PYrMo;
DFTranCategory.Value := ABuffer.PTranCategory;
DFUserId.Value := ABuffer.PUserId;
DFTimeStamp.Value := ABuffer.PTimeStamp;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoBSOATable, TInfoBSOAQuery, TInfoBSOABuffer ] );
end; { Register }
function TInfoBSOABuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..12] of string = ('LENDERID','TRANDATE','TRANTYPE','TRANID','MODCOUNT','AMOUNT'
,'BALANCE','COMMENT','YRMO','TRANCATEGORY','USERID'
,'TIMESTAMP' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 12) and (flist[x] <> s) do inc(x);
if x <= 12 then result := x else result := 0;
end;
function TInfoBSOABuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftSmallInt;
6 : result := ftCurrency;
7 : result := ftCurrency;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
11 : result := ftString;
12 : result := ftString;
end;
end;
function TInfoBSOABuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderID;
2 : result := @Data.PTranDate;
3 : result := @Data.PTranType;
4 : result := @Data.PTranID;
5 : result := @Data.PModCount;
6 : result := @Data.PAmount;
7 : result := @Data.PBalance;
8 : result := @Data.PComment;
9 : result := @Data.PYrMo;
10 : result := @Data.PTranCategory;
11 : result := @Data.PUserId;
12 : result := @Data.PTimeStamp;
end;
end;
end.
|
unit StockInstantDataAccess;
interface
uses
BaseApp,
BaseDataSet,
QuickList_int,
Define_DealItem,
define_stock_quotes_instant,
DB_DealItem;
type
TDBStockInstant = class(TBaseDataSetAccess)
protected
fStockList: TALIntegerList;
function GetRecordCount: Integer; override;
function GetRecordItem(AIndex: integer): Pointer; override;
public
constructor Create(ADataSrcId: integer); reintroduce;
destructor Destroy; override;
function FindRecordByKey(AKey: Integer): Pointer; override;
function AddItem(AStockItem: PRT_DealItem): PRT_InstantQuote;
function FindItem(AStockItem: PRT_DealItem): PRT_InstantQuote;
end;
function SaveDBStockInstant(App: TBaseApp; ADB: TDBStockInstant): Boolean;
procedure LoadDBStockInstant(AStockItemDB: TDBDealItem; AInstantDB: TDBStockInstant; AFileUrl: string);
implementation
uses
Windows,
SysUtils,
BaseWinFile,
Define_DealStore_File,
Define_Price,
Define_DealStore_Header;
procedure LoadDBStockInstantFromBuffer(AStockItemDB: TDBDealItem; AInstantDB: TDBStockInstant; AMemory: Pointer);
var
tmpStockItem: PRT_DealItem;
tmpRTInstantQuote: PRT_InstantQuote;
tmpHead: PStore_InstantQuoteHeaderRec;
tmpItemRec: PStore_InstantQuoteRec;
tmpStockCode: AnsiString;
tmpCount: integer;
i: integer;
begin
if nil = AMemory then
Exit;
tmpHead := AMemory;
if (7784 = tmpHead.Header.Signature.Signature) and
(1 = tmpHead.Header.Signature.DataVer1) and
(0 = tmpHead.Header.Signature.DataVer2) and
(0 = tmpHead.Header.Signature.DataVer3) and
(DataType_Stock = tmpHead.Header.DataType) and // 2 -- 10
(DataMode_DayInstant = tmpHead.Header.DataMode) then // 1 -- 11
begin
tmpCount := tmpHead.Header.RecordCount;
Inc(tmpHead);
tmpItemRec := PStore_InstantQuoteRec(tmpHead);
for i := 0 to tmpCount - 1 do
begin
tmpStockItem := nil;
if nil <> tmpItemRec then
begin
tmpStockCode := getStockCodeByPackCode(tmpItemRec.Data.StockCode);
tmpStockItem := AStockItemDB.FindDealItemByCode(tmpStockCode);
end;
if nil <> tmpStockItem then
begin
tmpRTInstantQuote := AInstantDB.AddItem(tmpStockItem);
if nil <> tmpRTInstantQuote then
begin
StorePriceRange2RTPricePackRange(@tmpRTInstantQuote.PriceRange, @tmpItemRec.Data.PriceRange);
tmpRTInstantQuote.Amount := tmpItemRec.Data.Amount; // 8 -- 28
tmpRTInstantQuote.Volume := tmpItemRec.Data.Volume; // 36
end;
end;
Inc(tmpItemRec);
end;
end;
end;
procedure SaveDBStockInstantToBuffer(App: TBaseApp; ADB: TDBStockInstant; AMemory: Pointer);
var
tmpHead: PStore_InstantQuoteHeaderRec;
tmpItemRec: PStore_InstantQuoteRec;
tmpRTItem: PRT_InstantQuote;
i: integer;
begin
tmpHead := AMemory;
tmpHead.Header.Signature.Signature := 7784; // 6
tmpHead.Header.Signature.DataVer1 := 1;
tmpHead.Header.Signature.DataVer2 := 0;
tmpHead.Header.Signature.DataVer3 := 0;
// 字节存储顺序 java 和 delphi 不同
// 00
// 01
tmpHead.Header.Signature.BytesOrder:= 1;
tmpHead.Header.HeadSize := SizeOf(TStore_InstantQuoteHeaderRec); // 1 -- 7
tmpHead.Header.StoreSizeMode.Value := 16; // 1 -- 8 page size mode
{ 表明是什么数据 }
tmpHead.Header.DataType := DataType_Stock; // 2 -- 10
tmpHead.Header.DataMode := DataMode_DayInstant; // 1 -- 11
tmpHead.Header.RecordSizeMode.Value:= 6; // 1 -- 12
tmpHead.Header.RecordCount := ADB.RecordCount; // 4 -- 16
tmpHead.Header.CompressFlag := 0; // 1 -- 17
tmpHead.Header.EncryptFlag := 0; // 1 -- 18
tmpHead.Header.DataSourceId := 0; // 2 -- 20
Inc(tmpHead);
tmpItemRec := PStore_InstantQuoteRec(tmpHead);
for i := 0 to ADB.RecordCount - 1 do
begin
tmpRTItem := ADB.RecordItem[i];
tmpItemRec.Data.StockCode := getStockCodePack(tmpRTItem.Item.sCode); // 4
RTPricePackRange2StorePriceRange(@tmpItemRec.Data.PriceRange, @tmpRTItem.PriceRange);
tmpItemRec.Data.Amount := tmpRTItem.Amount; // 8 -- 28
tmpItemRec.Data.Volume := tmpRTItem.Volume; // 36
Inc(tmpItemRec);
end;
end;
function SaveDBStockInstant(App: TBaseApp; ADB: TDBStockInstant): Boolean;
var
tmpPathUrl: string;
tmpFileUrl: string;
tmpWinFile: TWinFile;
tmpFileNewSize: integer;
tmpFileContentBuffer: Pointer;
tmpBytesWrite: DWORD;
begin
Result := false;
tmpPathUrl := App.Path.DataBasePath[ADB.DBType, ADB.DataType, 0];
tmpFileUrl := tmpPathUrl + Copy(FormatDateTime('yyyymmdd', now()), 5, MaxInt) + '.' + FileExt_StockInstant;
//tmpFileUrl := tmpPathUrl + Copy(FormatDateTime('yyyymmdd', now()), 7, MaxInt) + '.' + FileExt_StockInstant;
tmpWinFile := TWinFile.Create;
try
if tmpWinFile.OpenFile(tmpFileUrl, true) then
begin
tmpFileNewSize := SizeOf(TStore_InstantQuoteHeaderRec) + ADB.RecordCount * SizeOf(TStore_InstantQuoteRec); //400k
tmpFileNewSize := ((tmpFileNewSize div (1 * 1024)) + 1) * 1 * 1024;
tmpWinFile.FileSize := tmpFileNewSize;
GetMem(tmpFileContentBuffer, tmpWinFile.FileSize);
if nil <> tmpFileContentBuffer then
begin
try
SaveDBStockInstantToBuffer(App, ADB, tmpFileContentBuffer);
if Windows.WriteFile(tmpWinFile.FileHandle,
tmpFileContentBuffer^, tmpWinFile.FileSize, tmpBytesWrite, nil) then
begin
Result := true;
end;
finally
FreeMem(tmpFileContentBuffer);
end;
end;
end;
finally
tmpWinFile.Free;
end;
end;
procedure LoadDBStockInstant(AStockItemDB: TDBDealItem; AInstantDB: TDBStockInstant; AFileUrl: string);
var
tmpWinFile: TWinFile;
tmpFileContentBuffer: Pointer;
begin
tmpWinFile := TWinFile.Create;
try
if tmpWinFile.OpenFile(AFileUrl, false) then
begin
tmpFileContentBuffer := tmpWinFile.OpenFileMap;
if nil <> tmpFileContentBuffer then
begin
LoadDBStockInstantFromBuffer(AStockItemDB, AInstantDB, tmpFileContentBuffer);
end;
end;
finally
tmpWinFile.Free;
end;
end;
{ TDBStockInstant }
constructor TDBStockInstant.Create(ADataSrcId: integer);
begin
inherited Create(DBType_Unknown, FilePath_DataType_InstantData, ADataSrcId);
fStockList := TALIntegerList.Create;
end;
destructor TDBStockInstant.Destroy;
begin
fStockList.Free;
inherited;
end;
function TDBStockInstant.GetRecordCount: Integer;
begin
Result := fStockList.Count;
end;
function TDBStockInstant.GetRecordItem(AIndex: integer): Pointer;
begin
Result := fStockList.Objects[AIndex];
end;
function TDBStockInstant.AddItem(AStockItem: PRT_DealItem): PRT_InstantQuote;
begin
Result := System.New(PRT_InstantQuote);
FillChar(Result^, SizeOf(TRT_InstantQuote), 0);
Result.Item := AStockItem;
fStockList.AddObject(getStockCodePack(AStockItem.sCode), TObject(Result));
end;
function TDBStockInstant.FindItem(AStockItem: PRT_DealItem): PRT_InstantQuote;
begin
Result := FindRecordByKey(getStockCodePack(AStockItem.sCode));
end;
function TDBStockInstant.FindRecordByKey(AKey: Integer): Pointer;
var
tmpPos: integer;
begin
Result := nil;
tmpPos := fStockList.IndexOf(AKey);
if 0 <= tmpPos then
begin
Result := fStockList.Objects[tmpPos];
end;
end;
end.
|
unit TownHallJobsSheet;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit,
GradientBox, FramedButton, SheetHandlers, ExtCtrls,
InternationalizerComponent;
const
tidCurrBlock = 'CurrBlock';
tidExtSecurityId = 'ExtraSecurityId';
tidSecurityId = 'SecurityId';
tidhiActualMinSalary = 'hiActualMinSalary';
tidmidActualMinSalary = 'midActualMinSalary';
tidloActualMinSalary = 'loActualMinSalary';
const
facStoppedByTycoon = $04;
type
TTownJobsSheetHandler = class;
TTownHallJobsSheetViewer = class(TVisualControl)
pnLow: TPanel;
pnMiddle: TPanel;
pnHigh: TPanel;
Panel4: TPanel;
FirstLabel: TLabel;
Label2: TLabel;
lbHiTitle: TLabel;
lbMiTitle: TLabel;
lbLoTitle: TLabel;
Label6: TLabel;
xfer_hiWorkDemand: TLabel;
xfer_hiSalary: TLabel;
xfer_hiSalaryValue: TLabel;
xfer_hiMinSalary: TPercentEdit;
xfer_midMinSalary: TPercentEdit;
xfer_loMinSalary: TPercentEdit;
Label1: TLabel;
Label3: TLabel;
xfer_hiPrivateWorkDemand: TLabel;
xfer_midWorkDemand: TLabel;
xfer_midPrivateWorkDemand: TLabel;
xfer_midSalary: TLabel;
xfer_midSalaryValue: TLabel;
xfer_loWorkDemand: TLabel;
xfer_loPrivateWorkDemand: TLabel;
xfer_loSalary: TLabel;
xfer_loSalaryValue: TLabel;
lbHiPerc: TLabel;
lbMidPerc: TLabel;
lbLowPerc: TLabel;
Label4: TLabel;
Label5: TLabel;
Label7: TLabel;
Label8: TLabel;
Label10: TLabel;
Label11: TLabel;
InternationalizerComponent1: TInternationalizerComponent;
procedure xfer_hiMinSalaryChange(Sender: TObject);
private
procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND;
private
fHandler : TTownJobsSheetHandler;
end;
TTownJobsSheetHandler =
class(TSheetHandler, IPropertySheetHandler)
private
fControl : TTownHallJobsSheetViewer;
fCurrBlock : integer;
fOwnsFacility : boolean;
private
function CreateControl(Owner : TControl) : TControl; override;
function GetControl : TControl; override;
procedure RenderProperties(Properties : TStringList); override;
procedure SetFocus; override;
procedure Clear; override;
private
procedure threadedGetProperties(const parms : array of const);
procedure threadedRenderProperties(const parms : array of const);
procedure threadedChangeSalary(const parms : array of const);
end;
var
TownHallJobsSheetViewer: TTownHallJobsSheetViewer;
function TownJobsSheetHandlerCreator : IPropertySheetHandler; stdcall;
implementation
uses
Threads, SheetHandlerRegistry, FiveViewUtils, Protocol, SheetUtils;
{$R *.DFM}
function CvtToInt(str : string) : integer;
begin
if str <> ''
then
try
result := StrToInt(str);
except
result := 0;
end
else result := 0;
end;
// TTownJobsSheetHandler
function TTownJobsSheetHandler.CreateControl(Owner : TControl) : TControl;
begin
fControl := TTownHallJobsSheetViewer.Create(Owner);
fControl.fHandler := self;
result := fControl;
end;
function TTownJobsSheetHandler.GetControl : TControl;
begin
result := fControl;
end;
procedure TTownJobsSheetHandler.RenderProperties(Properties : TStringList);
var
aux : string;
begin
try
aux := Properties.Values[tidCurrBlock];
try
if aux = ''
then fCurrBlock := 0
else fCurrBlock := StrToInt(aux);
except
fCurrBlock := 0;
end;
fControl.xfer_hiMinSalary.Enabled := false;
fControl.xfer_midMinSalary.Enabled := false;
fControl.xfer_loMinSalary.Enabled := false;
aux := Properties.Values[tidExtSecurityId];
if aux = ''
then aux := Properties.Values[tidSecurityId];
fOwnsFacility := GrantAccess(fContainer.GetClientView.getSecurityId, aux);
fControl.xfer_hiMinSalary.Enabled := fOwnsFacility;
fControl.xfer_midMinSalary.Enabled := fOwnsFacility;
fControl.xfer_loMinSalary.Enabled := fOwnsFacility;
fControl.xfer_hiMinSalary.MidValue := CvtToInt( Properties.Values[tidhiActualMinSalary] );
fControl.xfer_midMinSalary.MidValue := CvtToInt( Properties.Values[tidmidActualMinSalary] );
fControl.xfer_loMinSalary.MidValue := CvtToInt( Properties.Values[tidloActualMinSalary] );
FiveViewUtils.SetViewProp(fControl, Properties);
except
end;
end;
procedure TTownJobsSheetHandler.SetFocus;
var
Names : TStringList;
begin
if not fLoaded
then
begin
inherited;
Names := TStringList.Create;
FiveViewUtils.GetViewPropNames(fControl, Names);
Names.Add(tidCurrBlock);
Names.Add(tidSecurityId);
Names.Add(tidExtSecurityId);
Names.Add(tidhiActualMinSalary);
Names.Add(tidmidActualMinSalary);
Names.Add(tidloActualMinSalary);
Threads.Fork(threadedGetProperties, priHigher, [Names, fLastUpdate]);
end;
end;
procedure TTownJobsSheetHandler.Clear;
begin
inherited;
fControl.xfer_hiWorkDemand.Caption := NA;
fControl.xfer_hiPrivateWorkDemand.Caption := NA;
fControl.xfer_hiSalary.Caption := '0';
fControl.xfer_hiSalaryValue.Caption := '0';
fControl.xfer_midWorkDemand.Caption := NA;
fControl.xfer_midPrivateWorkDemand.Caption := NA;
fControl.xfer_midSalary.Caption := '0';
fControl.xfer_midSalaryValue.Caption := '0';
fControl.xfer_loWorkDemand.Caption := NA;
fControl.xfer_loPrivateWorkDemand.Caption := NA;
fControl.xfer_loSalary.Caption := '0';
fControl.xfer_loSalaryValue.Caption := '0';
fControl.xfer_hiMinSalary.Value := 0;
fControl.xfer_hiMinSalary.MidValue := 0;
fControl.xfer_hiMinSalary.Enabled := false;
fControl.xfer_midMinSalary.Value := 0;
fControl.xfer_midMinSalary.MidValue := 0;
fControl.xfer_midMinSalary.Enabled := false;
fControl.xfer_loMinSalary.Value := 0;
fControl.xfer_loMinSalary.MidValue := 0;
fControl.xfer_loMinSalary.Enabled := false;
fControl.lbHiPerc.Caption := NA;
fControl.lbMidPerc.Caption := NA;
fControl.lbLowPerc.Caption := NA;
end;
procedure TTownJobsSheetHandler.threadedGetProperties(const parms : array of const);
var
Names : TStringList absolute parms[0].vInteger;
Update : integer;
Prop : TStringList;
begin
try
Update := parms[1].vInteger;
try
Prop := fContainer.GetProperties(Names);
if Update = fLastUpdate
then Join(threadedRenderProperties, [Prop, Update])
else Prop.Free;
finally
Names.Free;
end;
except
end;
end;
procedure TTownJobsSheetHandler.threadedRenderProperties(const parms : array of const);
var
Prop : TStringList absolute parms[0].vPointer;
begin
try
try
if parms[1].vInteger = fLastUpdate
then RenderProperties(Prop);
finally
Prop.Free;
end;
except
end;
end;
procedure TTownJobsSheetHandler.threadedChangeSalary(const parms : array of const);
var
Proxy : OleVariant;
block : integer;
begin
block := parms[0].vInteger;
if block <> 0
then
try
Proxy := fContainer.GetMSProxy;
Proxy.BindTo(block);
Proxy.WaitForAnswer := false;
Proxy.RDOSetMinSalaryValue(parms[1].vInteger, parms[2].vInteger);
except
end;
end;
// TWorkforceSheetViewer
procedure TTownHallJobsSheetViewer.WMEraseBkgnd(var Message: TMessage);
begin
Message.Result := 1;
end;
// TownJobsSheetHandlerCreator
function TownJobsSheetHandlerCreator : IPropertySheetHandler;
begin
result := TTownJobsSheetHandler.Create;
end;
procedure TTownHallJobsSheetViewer.xfer_hiMinSalaryChange(Sender: TObject);
begin
if fHandler.fOwnsFacility and (fHandler.fCurrBlock <> 0)
then Threads.Fork(fHandler.threadedChangeSalary, priNormal, [fHandler.fCurrBlock, TPercentEdit(Sender).Tag, integer(TPercentEdit(Sender).Value)]);
end;
initialization
SheetHandlerRegistry.RegisterSheetHandler('townJobs', TownJobsSheetHandlerCreator);
end.
|
unit CalcF;
interface
uses
SysUtils, Windows, Classes, Graphics, Controls,
StdCtrls, Forms, DBCtrls, DB, DBGrids, DBTables, Grids, ExtCtrls,
DBClient;
type
TCalcForm = class(TForm)
DBGrid1: TDBGrid;
DBNavigator: TDBNavigator;
Panel1: TPanel;
Panel2: TPanel;
DataSource1: TDataSource;
cds: TClientDataSet;
cdsName: TStringField;
cdsCapital: TStringField;
cdsContinent: TStringField;
cdsArea: TFloatField;
cdsPopulation: TFloatField;
cdsPopulationDensity: TFloatField;
procedure FormCreate(Sender: TObject);
procedure cdsCalcFields(DataSet: TDataset);
procedure DBGrid1EditButtonClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
CalcForm: TCalcForm;
implementation
uses Dialogs;
{$R *.dfm}
procedure TCalcForm.FormCreate(Sender: TObject);
begin
cds.Open;
end;
procedure TCalcForm.cdsCalcFields(DataSet: TDataset);
begin
// plain version (very dangerous)
{ cdsPopulationDensity.Value :=
cdsPopulation.Value / cdsArea.Value;}
// version based on exceptions (ok)
{ try
cdsPopulationDensity.Value :=
cdsPopulation.Value / cdsArea.Value;
except
on Exception do
cdsPopulationDensity.Value := 0;
end;}
// definitive version
if not cdsArea.IsNull and
(cdsArea.Value <> 0) then
cdsPopulationDensity.Value :=
cdsPopulation.Value / cdsArea.Value
else
cdsPopulationDensity.Value := 0;
end;
procedure TCalcForm.DBGrid1EditButtonClick(Sender: TObject);
begin
MessageDlg (Format (
'The population density (%.2n)'#13 +
'is the Population (%.0n)'#13 +
'devided by the Area (%.0n).'#13#13 +
'Edit these two fields to change it.',
[cdsPopulationDensity.AsFloat,
cdsPopulation.AsFloat,
cdsArea.AsFloat]),
mtInformation, [mbOK], 0);
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
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 3 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, see <http://www.gnu.org/licenses/>.
}
unit OraMaterializedViewLog;
interface
uses Classes, SysUtils, Ora, OraStorage, OraGrants, OraSynonym, DB,DBQuery,
Forms, Dialogs, VirtualTable;
type
TMaterializedViewLog = class(TObject)
private
FOWNER,
FTABLE_NAME,
FPARALLEL: string;
FCACHE : boolean;
FLOGGING: TLoggingType;
FENABLE_ROW_MOVEMENT: boolean;
FNEW_VALUES: TMVNewValues;
FROW_ID,
FOBJECT_ID,
FPRIMARY_KEY,
FSEQUENCE: Boolean;
FCOLUMNS: TStringList;
FPhsicalAttributes : TPhsicalAttributes;
FOraSession: TOraSession;
function GetTablesList: TVirtualTable;
function GetTableColumnsList: TVirtualTable;
public
property OWNER: string read FOWNER write FOWNER;
property TABLE_NAME: string read FTABLE_NAME write FTABLE_NAME;
property PARALLEL: string read FPARALLEL write FPARALLEL;
property CACHE : boolean read FCACHE write FCACHE;
property LOGGING: TLoggingType read FLOGGING write FLOGGING;
property ENABLE_ROW_MOVEMENT: boolean read FENABLE_ROW_MOVEMENT write FENABLE_ROW_MOVEMENT;
property NEW_VALUES: TMVNewValues read FNEW_VALUES write FNEW_VALUES;
property ROW_ID: boolean read FROW_ID write FROW_ID;
property OBJECT_ID: boolean read FOBJECT_ID write FOBJECT_ID;
property PRIMARY_KEY: boolean read FPRIMARY_KEY write FPRIMARY_KEY;
property SEQUENCE: boolean read FSEQUENCE write FSEQUENCE;
property COLUMNS: TStringList read FCOLUMNS write FCOLUMNS;
property PhsicalAttributes : TPhsicalAttributes read FPhsicalAttributes write FPhsicalAttributes;
property TablesList: TVirtualTable read GetTablesList;
property TableColumnsList: TVirtualTable read GetTableColumnsList;
property OraSession: TOraSession read FOraSession write FOraSession;
constructor Create;
destructor Destroy; override;
function GetDDL: string;
function CreateViewLog(ViewLogScript: string) : boolean;
end;
implementation
uses Util, frmSchemaBrowser, OraScripts, oraTable, Languages;
resourcestring
strMaterializedViewLogCreated = 'Matetialized View Log %s has been created.';
constructor TMaterializedViewLog.Create;
begin
inherited;
FCOLUMNS := TStringList.Create;
end;
destructor TMaterializedViewLog.destroy;
begin
inherited;
FreeAndNil(FCOLUMNS);
end;
function TMaterializedViewLog.GetDDL: string;
var
s,s1: string;
i: integer;
begin
result := '';
with self do
begin
result := 'CREATE MATERIALIZED VIEW LOG ON '+FOWNER+'.'+FTABLE_NAME;
result := result + ln + GenerateStorage(FPhsicalAttributes);
if FLOGGING = ltLogging then
result := result + ln +' LOGGING';
if FLOGGING = ltNoLogging then
result := result +ln + ' NOLOGGING';
if FENABLE_ROW_MOVEMENT then
result := result + ln + ' ENABLE ROW MOVEMENT';
if FCACHE then
result := result + ln +' CACHE'
else
result := result + ln +' NOCACHE';
if isNullorZero(FPARALLEL,'0') then
result := result + ln +' PARALLEL '+FPARALLEL
else
result := result + ln +' NOPARALLEL ';
s := '';
if FROW_ID then s := s +'ROWID,';
if FOBJECT_ID then s := s +'OBJECT ID,';
if FPRIMARY_KEY then s := s +'PRIMARY KEY,';
if FSEQUENCE then s := s +'SEQUENCE,';
if length(s) > 0 then delete(s,length(s),1);
s1 := '';
for i := 0 to FCOLUMNS.Count -1 do
begin
s1 := s1 + FCOLUMNS[i];
if i <> FCOLUMNS.Count-1 then s1 := s1 + ',';
end;
if length(s1) > 0 then s1 := ln + ' ('+s1+')';
if (length(s)> 0) or (length(s1)>0) then
result := result + ln + ' WITH '
+s
+s1;
if FNEW_VALUES = nvIncluding then
result := result + ln + ' INCLUDING NEW VALUES';
if FNEW_VALUES = nvExcluding then
result := result + ln + ' EXCLUDING NEW VALUES';
end; //self
end; //GetDDL
function TMaterializedViewLog.CreateViewLog(ViewLogScript: string) : boolean;
begin
result := false;
if FTABLE_NAME = '' then exit;
result := ExecSQL(ViewLogScript, Format(ChangeSentence('strMaterializedViewLogCreated',strMaterializedViewLogCreated),[FTABLE_NAME]), FOraSession);
end;
function TMaterializedViewLog.GetTablesList: TVirtualTable;
var
q1: TOraQuery;
begin
result := TVirtualTable.Create(nil);
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetTables(FOWNER);
q1.Open;
CopyDataSet(q1, result);
q1.Close;
end;
function TMaterializedViewLog.GetTableColumnsList: TVirtualTable;
var
q1: TOraQuery;
begin
result := TVirtualTable.Create(nil);
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetTableColumns;
q1.ParamByName('pTable').AsString := FTABLE_NAME;
q1.ParamByName('pOwner').AsString := FOWNER;
q1.Open;
CopyDataSet(q1, result);
q1.Close;
end;
end.
|
unit atUserWorkContext;
// Модуль: "w:\quality\test\garant6x\AdapterTest\OperationsFramework\atUserWorkContext.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TatUserWorkContext" MUID: (4808672500A0)
interface
uses
l3IntfUses
, DocumentUnit
, DynamicDocListUnit
, atDocumentHistory
, atListHistory
, FoldersUnit
;
type
TatUserWorkContext = class(TObject)
private
f_DocumentHistory: TatDocumentHistory;
f_ListHistory: TatListHistory;
f_CurrFolder: IFoldersNode;
{* Текущая папка. Например, операция создания папки будет ее устанавливать, а операция сохранения закладки сможет туда сохранить закладку. }
protected
function pm_GetDocHistoryLength: Integer;
procedure pm_SetDocHistoryLength(aValue: Integer);
function pm_GetListHistoryLength: Integer;
procedure pm_SetListHistoryLength(aValue: Integer);
function pm_GetCurrDoc: IDocument;
function pm_GetCurrList: IDynList;
procedure pm_SetCurrFolder(const aValue: IFoldersNode); virtual;
public
constructor Create; reintroduce;
procedure AddDocToHistory(const document: IDocument);
procedure Clear;
procedure AddListToHistory(const list: IDynList); virtual;
destructor Destroy; override;
public
property DocHistoryLength: Integer
read pm_GetDocHistoryLength
write pm_SetDocHistoryLength;
property ListHistoryLength: Integer
read pm_GetListHistoryLength
write pm_SetListHistoryLength;
property CurrDoc: IDocument
read pm_GetCurrDoc;
{* Текущий (последний в истории) документ. Например, операция открытия документа его устанавливает. Сюда мы устанавливаем закладку, добавляем комментарии и вообще когда нам понадобится документ мы его берем отсюда. }
property CurrList: IDynList
read pm_GetCurrList;
{* Текущий (последний в истории) список. Если какая-то операция получает список, то она его ложит сюда, чтобы те операции которым нужен список пользовались. }
property CurrFolder: IFoldersNode
read f_CurrFolder
write pm_SetCurrFolder;
{* Текущая папка. Например, операция создания папки будет ее устанавливать, а операция сохранения закладки сможет туда сохранить закладку. }
end;//TatUserWorkContext
implementation
uses
l3ImplUses
, SysUtils
//#UC START# *4808672500A0impl_uses*
//#UC END# *4808672500A0impl_uses*
;
function TatUserWorkContext.pm_GetDocHistoryLength: Integer;
//#UC START# *4808679100E8_4808672500A0get_var*
//#UC END# *4808679100E8_4808672500A0get_var*
begin
//#UC START# *4808679100E8_4808672500A0get_impl*
Result := f_DocumentHistory.HistoryLength;
//#UC END# *4808679100E8_4808672500A0get_impl*
end;//TatUserWorkContext.pm_GetDocHistoryLength
procedure TatUserWorkContext.pm_SetDocHistoryLength(aValue: Integer);
//#UC START# *4808679100E8_4808672500A0set_var*
//#UC END# *4808679100E8_4808672500A0set_var*
begin
//#UC START# *4808679100E8_4808672500A0set_impl*
f_DocumentHistory.HistoryLength := aValue;
//#UC END# *4808679100E8_4808672500A0set_impl*
end;//TatUserWorkContext.pm_SetDocHistoryLength
function TatUserWorkContext.pm_GetListHistoryLength: Integer;
//#UC START# *483A884E0115_4808672500A0get_var*
//#UC END# *483A884E0115_4808672500A0get_var*
begin
//#UC START# *483A884E0115_4808672500A0get_impl*
Result := f_ListHistory.HistoryLength;
//#UC END# *483A884E0115_4808672500A0get_impl*
end;//TatUserWorkContext.pm_GetListHistoryLength
procedure TatUserWorkContext.pm_SetListHistoryLength(aValue: Integer);
//#UC START# *483A884E0115_4808672500A0set_var*
//#UC END# *483A884E0115_4808672500A0set_var*
begin
//#UC START# *483A884E0115_4808672500A0set_impl*
f_ListHistory.HistoryLength := aValue
//#UC END# *483A884E0115_4808672500A0set_impl*
end;//TatUserWorkContext.pm_SetListHistoryLength
function TatUserWorkContext.pm_GetCurrDoc: IDocument;
//#UC START# *480867F10278_4808672500A0get_var*
//#UC END# *480867F10278_4808672500A0get_var*
begin
//#UC START# *480867F10278_4808672500A0get_impl*
Result := f_DocumentHistory.Current;
//#UC END# *480867F10278_4808672500A0get_impl*
end;//TatUserWorkContext.pm_GetCurrDoc
function TatUserWorkContext.pm_GetCurrList: IDynList;
//#UC START# *483A85FB0088_4808672500A0get_var*
//#UC END# *483A85FB0088_4808672500A0get_var*
begin
//#UC START# *483A85FB0088_4808672500A0get_impl*
Result := f_ListHistory.Current;
//#UC END# *483A85FB0088_4808672500A0get_impl*
end;//TatUserWorkContext.pm_GetCurrList
procedure TatUserWorkContext.pm_SetCurrFolder(const aValue: IFoldersNode);
//#UC START# *484AA281000E_4808672500A0set_var*
//#UC END# *484AA281000E_4808672500A0set_var*
begin
//#UC START# *484AA281000E_4808672500A0set_impl*
Assert(aValue <> nil, 'aValue <> nil');
f_CurrFolder := aValue;
//#UC END# *484AA281000E_4808672500A0set_impl*
end;//TatUserWorkContext.pm_SetCurrFolder
constructor TatUserWorkContext.Create;
//#UC START# *4808681E00D9_4808672500A0_var*
//#UC END# *4808681E00D9_4808672500A0_var*
begin
//#UC START# *4808681E00D9_4808672500A0_impl*
inherited;
f_DocumentHistory := TatDocumentHistory.Create;
f_DocumentHistory.HistoryLength := 1;
f_ListHistory := TatListHistory.Create;
f_ListHistory.HistoryLength := 1;
//#UC END# *4808681E00D9_4808672500A0_impl*
end;//TatUserWorkContext.Create
procedure TatUserWorkContext.AddDocToHistory(const document: IDocument);
//#UC START# *480868380180_4808672500A0_var*
//#UC END# *480868380180_4808672500A0_var*
begin
//#UC START# *480868380180_4808672500A0_impl*
f_DocumentHistory.AddToHistory(document);
//#UC END# *480868380180_4808672500A0_impl*
end;//TatUserWorkContext.AddDocToHistory
procedure TatUserWorkContext.Clear;
//#UC START# *4808684A0084_4808672500A0_var*
//#UC END# *4808684A0084_4808672500A0_var*
begin
//#UC START# *4808684A0084_4808672500A0_impl*
f_DocumentHistory.Clear;
f_ListHistory.Clear;
//#UC END# *4808684A0084_4808672500A0_impl*
end;//TatUserWorkContext.Clear
procedure TatUserWorkContext.AddListToHistory(const list: IDynList);
//#UC START# *483A88650069_4808672500A0_var*
//#UC END# *483A88650069_4808672500A0_var*
begin
//#UC START# *483A88650069_4808672500A0_impl*
f_ListHistory.AddToHistory(list);
//#UC END# *483A88650069_4808672500A0_impl*
end;//TatUserWorkContext.AddListToHistory
destructor TatUserWorkContext.Destroy;
//#UC START# *48077504027E_4808672500A0_var*
//#UC END# *48077504027E_4808672500A0_var*
begin
//#UC START# *48077504027E_4808672500A0_impl*
FreeAndNil(f_DocumentHistory);
FreeAndNil(f_ListHistory);
inherited;
//#UC END# *48077504027E_4808672500A0_impl*
end;//TatUserWorkContext.Destroy
end.
|
unit NLDTXDOMUtils;
{
:: NLDTXDOMUtils contains some convenience functions for use with OpenXML.
:: Most noticeably, it provides the ability to translate characters into
:: valid XML entities and back.
:$
:$
:$ NLDTranslate is released under the zlib/libpng OSI-approved license.
:$ For more information: http://www.opensource.org/
:$ /n/n
:$ /n/n
:$ Copyright (c) 2002 M. van Renswoude
:$ /n/n
:$ 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.
:$ /n/n
:$ 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:
:$ /n/n
:$ 1. The origin of this software must not be misrepresented; you must not
:$ claim that you wrote the original software. If you use this software in a
:$ product, an acknowledgment in the product documentation would be
:$ appreciated but is not required.
:$ /n/n
:$ 2. Altered source versions must be plainly marked as such, and must not be
:$ misrepresented as being the original software.
:$ /n/n
:$ 3. This notice may not be removed or altered from any source distribution.
}
{$I NLDTDefines.inc}
interface
uses
XDOM_2_3;
type
{
:$ Buffers writing operations to a string
:: TNLDTStringBuffer can be used to add characters to a string without
:: sacrificing too much speed. It uses a buffer which is increased only
:: when needed.
}
TNLDTStringBuffer = class(TObject)
private
FActualLen: Integer;
FCapacity: Integer;
FContent: String;
protected
function GetChar(AIndex: Integer): Char; virtual;
function GetValue(): String; virtual;
procedure SetChar(AIndex: Integer; const Value: Char); virtual;
public
//:$ Initializes the TNLDTStringBuffer instance
constructor Create();
//:$ Clears the internal buffer
//:: Clear cleans up the current string data and restores the buffr
procedure Clear(); virtual;
//:$ Writes a single character
//:: Call WriteChar to write a single character in buffered mode to
//:: the internal string.
procedure WriteChar(const AChar: Char); virtual;
//:$ Writes a string
//:: Call WriteString to write a string in buffered mode to
//:: the internal string.
procedure WriteString(const AString: String); virtual;
//:$ Provides indexed access to the individual characters
//:: Use the Chars property to get fast access to the individual characters.
property Chars[AIndex: Integer]: Char read GetChar write SetChar;
//:$ Returns the length of the string
//:: Length returns the actual length of the string, not of the buffer.
property Length: Integer read FActualLen;
//:$ Returns the internal string
//:: Returns the internal string without any remaining buffer.
//:! If you want to access the characters, use the Chars property instead,
//:! since retrieving Value requires some memory allocations to get the
//:! correct data from the internal buffer.
property Value: String read GetValue;
end;
{
:$ Converts entities to characters
:: XDOMEntityToChar converts entities (such as &) to their
:: corresponding characters (such as &).
}
function XDOMEntityToChar(const ASource: String): String;
{
:$ Converts characters to entities
:: XDOMCharToEntity converts all illegal characters (such as &) to their
:: corresponding entities (such as &), which prevents errors while
:: saving XML encoded files.
}
function XDOMCharToEntity(const ASource: String): String;
{
:$ Returns the value of the specified attribute
:: XDOMGetAttribute returns the value of the specified attribute for the
:: specified node. It calls XDOMEntityToChar on the value to return the
:: character representation of the encoded string. If the attribute is not
:: found, an empty string is returned.
}
function XDOMGetAttribute(const ANode: TDomNode;
const AName: String): String;
{
:$ Returns the value of the specified attribute
:: XDOMGetAttribute returns the value of the specified attribute for the
:: specified node. It calls XDOMEntityToChar on the value to return the
:: character representation of the encoded string. If the attribute index
:: is not found, an exception is raised.
}
function XDOMGetAttributeByIndex(const ANode: TDomNode;
const AIndex: Integer): String;
{
:$ Sets the value for the specified attribute
:: XDOMSetAttribute sets the specified attribute to the specified value.
:: XDOMCharToEntity is automatically called before setting the actual value.
}
procedure XDOMSetAttribute(const ANode: TDomNode; const AName,
AValue: String);
implementation
uses
Windows,
SysUtils,
{$IFDEF NLDT_FASTSTRINGS}
FastStrings,
{$ENDIF}
NLDTXDOMEntities;
{********************* TNLDTStringBuffer
Initialization
****************************************}
constructor TNLDTStringBuffer.Create;
begin
inherited;
Clear();
end;
procedure TNLDTStringBuffer.Clear;
begin
FCapacity := 64;
SetLength(FContent, FCapacity);
FActualLen := 0;
end;
{********************* TNLDTStringBuffer
Write functions
****************************************}
procedure TNLDTStringBuffer.WriteChar;
begin
if FActualLen = FCapacity then begin
// Expand buffer
Inc(FCapacity, FCapacity div 4);
SetLength(FContent, FCapacity);
end;
Inc(FActualLen);
FContent[FActualLen] := AChar;
end;
procedure TNLDTStringBuffer.WriteString;
var
iLength: Integer;
iNeeded: Integer;
begin
iLength := System.Length(AString);
iNeeded := FActualLen + iLength;
if iNeeded > FCapacity then begin
while iNeeded > FCapacity do
// Expand buffer
Inc(FCapacity, FCapacity div 4);
SetLength(FContent, FCapacity);
end;
CopyMemory(@FContent[FActualLen + 1], @AString[1], iLength);
Inc(FActualLen, iLength);
end;
{********************* TNLDTStringBuffer
Properties
****************************************}
function TNLDTStringBuffer.GetChar;
begin
Result := FContent[AIndex];
end;
procedure TNLDTStringBuffer.SetChar;
begin
FContent[AIndex] := Value;
end;
function TNLDTStringBuffer.GetValue: String;
begin
SetLength(Result, FActualLen);
CopyMemory(@Result[1], @FContent[1], FActualLen);
end;
function FastReplacePart(const ASource: String; const AStart, ALength: Integer;
const AReplace: String): String;
var
iSrcLength: Integer;
iLength: Integer;
iDiff: Integer;
iDest: Integer;
begin
iSrcLength := Length(ASource);
iLength := Length(AReplace);
iDiff := iLength - ALength;
iDest := 1;
SetLength(Result, iSrcLength + iDiff);
// Write first part
CopyMemory(@Result[iDest], @ASource[1], AStart - 1);
Inc(iDest, AStart - 1);
// Write replacement
CopyMemory(@Result[iDest], @AReplace[1], iLength);
Inc(iDest, iLength);
// Write last part
CopyMemory(@Result[iDest], @ASource[AStart + ALength],
iSrcLength - AStart - (ALength - 1));
end;
{****************************************
Convert entities to characters
****************************************}
function XDOMEntityToChar;
var
{$IFNDEF NLDT_FASTSTRINGS}
sTemp: String;
iOffset: Integer;
{$ELSE}
iLength: Integer;
{$ENDIF}
iStart: Integer;
iEnd: Integer;
iEntLength: Integer;
sEntity: String;
iEntity: Integer;
cReplacement: Char;
begin
Result := ASource;
{$IFNDEF NLDT_FASTSTRINGS}
sTemp := ASource;
iOffset := 0;
{$ELSE}
iLength := Length(Result);
iStart := 1;
{$ENDIF}
repeat
// Find '&'
{$IFDEF NLDT_FASTSTRINGS}
iStart := FastPos(Result, '&', iLength, 1, iStart);
{$ELSE}
iStart := AnsiPos('&', sTemp);
{$ENDIF}
if iStart > 0 then begin
{$IFNDEF NLDT_FASTSTRINGS}
Delete(sTemp, 1, iStart);
Inc(iStart, iOffset);
Inc(iOffset, iStart - iOffset);
{$ENDIF}
// Find ';'
{$IFDEF NLDT_FASTSTRINGS}
iEnd := FastPos(Result, ';', iLength, 1, iStart + 1);
{$ELSE}
iEnd := AnsiPos(';', sTemp);
{$ENDIF}
if iEnd > 0 then begin
{$IFNDEF NLDT_FASTSTRINGS}
Delete(sTemp, 1, iEnd);
Inc(iEnd, iOffset);
Inc(iOffset, iEnd - iOffset);
{$ENDIF}
iEntLength := iEnd - iStart - 1;
// Quick check: make sure it does not exceed the maximum length
if iEntLength <= XDOMEntityMaxLen then begin
sEntity := LowerCase(Copy(Result, iStart + 1, iEntLength));
cReplacement := ' ';
if sEntity[1] = '#' then begin
// Try to replace numeric entity
Delete(sEntity, 1, 1);
cReplacement := Chr(StrToIntDef(sEntity, Ord(' ')));
end else
// Check for entity in reference table
for iEntity := 0 to XDOMEntityCount - 1 do
if sEntity = XDOMEntityNames[iEntity] then begin
cReplacement := XDOMEntityValues[iEntity];
break;
end;
Result := FastReplacePart(Result, iStart, iEntLength + 2, cReplacement);
{$IFDEF NLDT_FASTSTRINGS}
Inc(iStart, 2);
iLength := Length(Result);
{$ELSE}
Dec(iOffset, iEntLength + 1);
{$ENDIF}
end{$IFDEF NLDT_FASTSTRINGS} else
iStart := iEnd + 1{$ENDIF};
end{$IFDEF NLDT_FASTSTRINGS} else
Inc(iStart){$ENDIF};
end else
break;
until False;
end;
{****************************************
Convert characters to entities
****************************************}
function XDOMCharToEntity;
const
CInvalidChars = [#0..#31, #38, #60, #62, #127..#255];
var
iChar: Integer;
cChar: Char;
iEntity: Integer;
pBuffer: TNLDTStringBuffer;
bFound: Boolean;
begin
pBuffer := TNLDTStringBuffer.Create();
try
for iChar := 1 to Length(ASource) do begin
cChar := ASource[iChar];
if cChar in CInvalidChars then begin
// Check if the character is found in the lookup table
bFound := False;
for iEntity := 0 to XDOMEntityCount - 1 do
if cChar = XDOMEntityValues[iEntity] then begin
pBuffer.WriteString('&' + XDOMEntityNames[iEntity] + ';');
bFound := True;
break;
end;
if not bFound then
pBuffer.WriteChar(cChar);
end else
pBuffer.WriteChar(cChar);
end;
finally
Result := pBuffer.Value;
FreeAndNil(pBuffer);
end;
end;
{****************************************
Get attribute
****************************************}
function XDOMGetAttribute;
var
xmlAttr: TDomNode;
begin
Result := '';
xmlAttr := ANode.attributes.getNamedItem(AName);
if Assigned(xmlAttr) then
Result := XDOMEntityToChar(xmlAttr.nodeValue);
end;
function XDOMGetAttributeByIndex;
var
xmlAttr: TDomNode;
begin
Result := '';
xmlAttr := ANode.attributes.item(AIndex);
if Assigned(xmlAttr) then
Result := XDOMEntityToChar(xmlAttr.nodeValue);
end;
{****************************************
Set attribute
****************************************}
procedure XDOMSetAttribute;
var
xmlAttr: TDomNode;
begin
xmlAttr := ANode.ownerDocument.createAttribute(AName);
xmlAttr.nodeValue := XDOMCharToEntity(AValue);
ANode.attributes.setNamedItem(xmlAttr);
end;
end.
|
unit UserPropertyKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы UserProperty }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Admin\UserPropertyKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "UserPropertyKeywordsPack" MUID: (1E34DCC9548E)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If Defined(Admin) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, vtPanel
, vtLabel
{$If Defined(Nemesis)}
, nscComboBox
{$IfEnd} // Defined(Nemesis)
, vtComboBoxQS
, vtCheckBox
;
{$IfEnd} // Defined(Admin) AND NOT Defined(NoScripts)
implementation
{$If Defined(Admin) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, UserProperty_Form
, tfwControlString
{$If NOT Defined(NoVCL)}
, kwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
, tfwScriptingInterfaces
, tfwPropertyLike
, TypInfo
, tfwTypeInfo
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
;
type
Tkw_Form_UserProperty = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы UserProperty
----
*Пример использования*:
[code]
'aControl' форма::UserProperty TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_UserProperty
Tkw_UserProperty_Control_pnMainData = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола pnMainData
----
*Пример использования*:
[code]
контрол::pnMainData TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_pnMainData
Tkw_UserProperty_Control_pnMainData_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола pnMainData
----
*Пример использования*:
[code]
контрол::pnMainData:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_pnMainData_Push
Tkw_UserProperty_Control_f_TopPanel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола f_TopPanel
----
*Пример использования*:
[code]
контрол::f_TopPanel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_f_TopPanel
Tkw_UserProperty_Control_f_TopPanel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола f_TopPanel
----
*Пример использования*:
[code]
контрол::f_TopPanel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_f_TopPanel_Push
Tkw_UserProperty_Control_UserNameLabel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола UserNameLabel
----
*Пример использования*:
[code]
контрол::UserNameLabel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_UserNameLabel
Tkw_UserProperty_Control_UserNameLabel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола UserNameLabel
----
*Пример использования*:
[code]
контрол::UserNameLabel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_UserNameLabel_Push
Tkw_UserProperty_Control_PasswordLabel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола PasswordLabel
----
*Пример использования*:
[code]
контрол::PasswordLabel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_PasswordLabel
Tkw_UserProperty_Control_PasswordLabel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола PasswordLabel
----
*Пример использования*:
[code]
контрол::PasswordLabel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_PasswordLabel_Push
Tkw_UserProperty_Control_LoginLabel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола LoginLabel
----
*Пример использования*:
[code]
контрол::LoginLabel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_LoginLabel
Tkw_UserProperty_Control_LoginLabel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола LoginLabel
----
*Пример использования*:
[code]
контрол::LoginLabel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_LoginLabel_Push
Tkw_UserProperty_Control_EMailLabel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола EMailLabel
----
*Пример использования*:
[code]
контрол::EMailLabel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_EMailLabel
Tkw_UserProperty_Control_EMailLabel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола EMailLabel
----
*Пример использования*:
[code]
контрол::EMailLabel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_EMailLabel_Push
Tkw_UserProperty_Control_ConfirmPasswordLabel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола ConfirmPasswordLabel
----
*Пример использования*:
[code]
контрол::ConfirmPasswordLabel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_ConfirmPasswordLabel
Tkw_UserProperty_Control_ConfirmPasswordLabel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола ConfirmPasswordLabel
----
*Пример использования*:
[code]
контрол::ConfirmPasswordLabel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_ConfirmPasswordLabel_Push
Tkw_UserProperty_Control_GroupLabel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола GroupLabel
----
*Пример использования*:
[code]
контрол::GroupLabel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_GroupLabel
Tkw_UserProperty_Control_GroupLabel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола GroupLabel
----
*Пример использования*:
[code]
контрол::GroupLabel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_GroupLabel_Push
Tkw_UserProperty_Control_edPassword = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edPassword
----
*Пример использования*:
[code]
контрол::edPassword TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edPassword
Tkw_UserProperty_Control_edPassword_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edPassword
----
*Пример использования*:
[code]
контрол::edPassword:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edPassword_Push
Tkw_UserProperty_Control_edUserName = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edUserName
----
*Пример использования*:
[code]
контрол::edUserName TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edUserName
Tkw_UserProperty_Control_edUserName_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edUserName
----
*Пример использования*:
[code]
контрол::edUserName:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edUserName_Push
Tkw_UserProperty_Control_edLogin = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edLogin
----
*Пример использования*:
[code]
контрол::edLogin TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edLogin
Tkw_UserProperty_Control_edLogin_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edLogin
----
*Пример использования*:
[code]
контрол::edLogin:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edLogin_Push
Tkw_UserProperty_Control_edEmail = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edEmail
----
*Пример использования*:
[code]
контрол::edEmail TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edEmail
Tkw_UserProperty_Control_edEmail_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edEmail
----
*Пример использования*:
[code]
контрол::edEmail:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edEmail_Push
Tkw_UserProperty_Control_edConfirm = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edConfirm
----
*Пример использования*:
[code]
контрол::edConfirm TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edConfirm
Tkw_UserProperty_Control_edConfirm_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edConfirm
----
*Пример использования*:
[code]
контрол::edConfirm:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edConfirm_Push
Tkw_UserProperty_Control_edGroup = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edGroup
----
*Пример использования*:
[code]
контрол::edGroup TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edGroup
Tkw_UserProperty_Control_edGroup_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edGroup
----
*Пример использования*:
[code]
контрол::edGroup:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edGroup_Push
Tkw_UserProperty_Control_f_MiddlePanel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола f_MiddlePanel
----
*Пример использования*:
[code]
контрол::f_MiddlePanel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_f_MiddlePanel
Tkw_UserProperty_Control_f_MiddlePanel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола f_MiddlePanel
----
*Пример использования*:
[code]
контрол::f_MiddlePanel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_f_MiddlePanel_Push
Tkw_UserProperty_Control_edPrivilegedUser = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edPrivilegedUser
----
*Пример использования*:
[code]
контрол::edPrivilegedUser TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edPrivilegedUser
Tkw_UserProperty_Control_edPrivilegedUser_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edPrivilegedUser
----
*Пример использования*:
[code]
контрол::edPrivilegedUser:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edPrivilegedUser_Push
Tkw_UserProperty_Control_edBuyConsulting = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edBuyConsulting
----
*Пример использования*:
[code]
контрол::edBuyConsulting TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edBuyConsulting
Tkw_UserProperty_Control_edBuyConsulting_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edBuyConsulting
----
*Пример использования*:
[code]
контрол::edBuyConsulting:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edBuyConsulting_Push
Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола f_DontDeleteIdleUserPanel
----
*Пример использования*:
[code]
контрол::f_DontDeleteIdleUserPanel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel
Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола f_DontDeleteIdleUserPanel
----
*Пример использования*:
[code]
контрол::f_DontDeleteIdleUserPanel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel_Push
Tkw_UserProperty_Control_edDontDeleteIdleUser = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edDontDeleteIdleUser
----
*Пример использования*:
[code]
контрол::edDontDeleteIdleUser TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edDontDeleteIdleUser
Tkw_UserProperty_Control_edDontDeleteIdleUser_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edDontDeleteIdleUser
----
*Пример использования*:
[code]
контрол::edDontDeleteIdleUser:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edDontDeleteIdleUser_Push
Tkw_UserProperty_Control_f_BottomPanel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола f_BottomPanel
----
*Пример использования*:
[code]
контрол::f_BottomPanel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_f_BottomPanel
Tkw_UserProperty_Control_f_BottomPanel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола f_BottomPanel
----
*Пример использования*:
[code]
контрол::f_BottomPanel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_f_BottomPanel_Push
Tkw_UserProperty_Control_InfoLabel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола InfoLabel
----
*Пример использования*:
[code]
контрол::InfoLabel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_InfoLabel
Tkw_UserProperty_Control_InfoLabel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола InfoLabel
----
*Пример использования*:
[code]
контрол::InfoLabel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_InfoLabel_Push
Tkw_UserProperty_Control_edHasSharedFilters = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edHasSharedFilters
----
*Пример использования*:
[code]
контрол::edHasSharedFilters TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edHasSharedFilters
Tkw_UserProperty_Control_edHasSharedFilters_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edHasSharedFilters
----
*Пример использования*:
[code]
контрол::edHasSharedFilters:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_UserProperty_Control_edHasSharedFilters_Push
TkwEfUserPropertyPnMainData = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.pnMainData }
private
function pnMainData(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtPanel;
{* Реализация слова скрипта .TefUserProperty.pnMainData }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyPnMainData
TkwEfUserPropertyFTopPanel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.f_TopPanel }
private
function f_TopPanel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtPanel;
{* Реализация слова скрипта .TefUserProperty.f_TopPanel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyFTopPanel
TkwEfUserPropertyUserNameLabel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.UserNameLabel }
private
function UserNameLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.UserNameLabel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyUserNameLabel
TkwEfUserPropertyPasswordLabel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.PasswordLabel }
private
function PasswordLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.PasswordLabel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyPasswordLabel
TkwEfUserPropertyLoginLabel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.LoginLabel }
private
function LoginLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.LoginLabel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyLoginLabel
TkwEfUserPropertyEMailLabel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.EMailLabel }
private
function EMailLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.EMailLabel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEMailLabel
TkwEfUserPropertyConfirmPasswordLabel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.ConfirmPasswordLabel }
private
function ConfirmPasswordLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.ConfirmPasswordLabel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyConfirmPasswordLabel
TkwEfUserPropertyGroupLabel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.GroupLabel }
private
function GroupLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.GroupLabel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyGroupLabel
TkwEfUserPropertyEdPassword = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.edPassword }
private
function edPassword(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TnscComboBoxWithPwdChar;
{* Реализация слова скрипта .TefUserProperty.edPassword }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEdPassword
TkwEfUserPropertyEdUserName = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.edUserName }
private
function edUserName(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TnscEdit;
{* Реализация слова скрипта .TefUserProperty.edUserName }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEdUserName
TkwEfUserPropertyEdLogin = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.edLogin }
private
function edLogin(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TnscEdit;
{* Реализация слова скрипта .TefUserProperty.edLogin }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEdLogin
TkwEfUserPropertyEdEmail = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.edEmail }
private
function edEmail(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TnscEdit;
{* Реализация слова скрипта .TefUserProperty.edEmail }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEdEmail
TkwEfUserPropertyEdConfirm = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.edConfirm }
private
function edConfirm(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TnscComboBoxWithPwdChar;
{* Реализация слова скрипта .TefUserProperty.edConfirm }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEdConfirm
TkwEfUserPropertyEdGroup = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.edGroup }
private
function edGroup(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtComboBoxQS;
{* Реализация слова скрипта .TefUserProperty.edGroup }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEdGroup
TkwEfUserPropertyFMiddlePanel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.f_MiddlePanel }
private
function f_MiddlePanel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtPanel;
{* Реализация слова скрипта .TefUserProperty.f_MiddlePanel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyFMiddlePanel
TkwEfUserPropertyEdPrivilegedUser = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.edPrivilegedUser }
private
function edPrivilegedUser(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtCheckBox;
{* Реализация слова скрипта .TefUserProperty.edPrivilegedUser }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEdPrivilegedUser
TkwEfUserPropertyEdBuyConsulting = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.edBuyConsulting }
private
function edBuyConsulting(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtCheckBox;
{* Реализация слова скрипта .TefUserProperty.edBuyConsulting }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEdBuyConsulting
TkwEfUserPropertyFDontDeleteIdleUserPanel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.f_DontDeleteIdleUserPanel }
private
function f_DontDeleteIdleUserPanel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtPanel;
{* Реализация слова скрипта .TefUserProperty.f_DontDeleteIdleUserPanel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyFDontDeleteIdleUserPanel
TkwEfUserPropertyEdDontDeleteIdleUser = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.edDontDeleteIdleUser }
private
function edDontDeleteIdleUser(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtCheckBox;
{* Реализация слова скрипта .TefUserProperty.edDontDeleteIdleUser }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEdDontDeleteIdleUser
TkwEfUserPropertyFBottomPanel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.f_BottomPanel }
private
function f_BottomPanel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtPanel;
{* Реализация слова скрипта .TefUserProperty.f_BottomPanel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyFBottomPanel
TkwEfUserPropertyInfoLabel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.InfoLabel }
private
function InfoLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.InfoLabel }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyInfoLabel
TkwEfUserPropertyEdHasSharedFilters = {final} class(TtfwPropertyLike)
{* Слово скрипта .TefUserProperty.edHasSharedFilters }
private
function edHasSharedFilters(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtCheckBox;
{* Реализация слова скрипта .TefUserProperty.edHasSharedFilters }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEfUserPropertyEdHasSharedFilters
function Tkw_Form_UserProperty.GetString: AnsiString;
begin
Result := 'efUserProperty';
end;//Tkw_Form_UserProperty.GetString
class function Tkw_Form_UserProperty.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::UserProperty';
end;//Tkw_Form_UserProperty.GetWordNameForRegister
function Tkw_UserProperty_Control_pnMainData.GetString: AnsiString;
begin
Result := 'pnMainData';
end;//Tkw_UserProperty_Control_pnMainData.GetString
class procedure Tkw_UserProperty_Control_pnMainData.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_UserProperty_Control_pnMainData.RegisterInEngine
class function Tkw_UserProperty_Control_pnMainData.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::pnMainData';
end;//Tkw_UserProperty_Control_pnMainData.GetWordNameForRegister
procedure Tkw_UserProperty_Control_pnMainData_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('pnMainData');
inherited;
end;//Tkw_UserProperty_Control_pnMainData_Push.DoDoIt
class function Tkw_UserProperty_Control_pnMainData_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::pnMainData:push';
end;//Tkw_UserProperty_Control_pnMainData_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_f_TopPanel.GetString: AnsiString;
begin
Result := 'f_TopPanel';
end;//Tkw_UserProperty_Control_f_TopPanel.GetString
class procedure Tkw_UserProperty_Control_f_TopPanel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_UserProperty_Control_f_TopPanel.RegisterInEngine
class function Tkw_UserProperty_Control_f_TopPanel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::f_TopPanel';
end;//Tkw_UserProperty_Control_f_TopPanel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_f_TopPanel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('f_TopPanel');
inherited;
end;//Tkw_UserProperty_Control_f_TopPanel_Push.DoDoIt
class function Tkw_UserProperty_Control_f_TopPanel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::f_TopPanel:push';
end;//Tkw_UserProperty_Control_f_TopPanel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_UserNameLabel.GetString: AnsiString;
begin
Result := 'UserNameLabel';
end;//Tkw_UserProperty_Control_UserNameLabel.GetString
class procedure Tkw_UserProperty_Control_UserNameLabel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLabel);
end;//Tkw_UserProperty_Control_UserNameLabel.RegisterInEngine
class function Tkw_UserProperty_Control_UserNameLabel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::UserNameLabel';
end;//Tkw_UserProperty_Control_UserNameLabel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_UserNameLabel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('UserNameLabel');
inherited;
end;//Tkw_UserProperty_Control_UserNameLabel_Push.DoDoIt
class function Tkw_UserProperty_Control_UserNameLabel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::UserNameLabel:push';
end;//Tkw_UserProperty_Control_UserNameLabel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_PasswordLabel.GetString: AnsiString;
begin
Result := 'PasswordLabel';
end;//Tkw_UserProperty_Control_PasswordLabel.GetString
class procedure Tkw_UserProperty_Control_PasswordLabel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLabel);
end;//Tkw_UserProperty_Control_PasswordLabel.RegisterInEngine
class function Tkw_UserProperty_Control_PasswordLabel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::PasswordLabel';
end;//Tkw_UserProperty_Control_PasswordLabel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_PasswordLabel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('PasswordLabel');
inherited;
end;//Tkw_UserProperty_Control_PasswordLabel_Push.DoDoIt
class function Tkw_UserProperty_Control_PasswordLabel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::PasswordLabel:push';
end;//Tkw_UserProperty_Control_PasswordLabel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_LoginLabel.GetString: AnsiString;
begin
Result := 'LoginLabel';
end;//Tkw_UserProperty_Control_LoginLabel.GetString
class procedure Tkw_UserProperty_Control_LoginLabel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLabel);
end;//Tkw_UserProperty_Control_LoginLabel.RegisterInEngine
class function Tkw_UserProperty_Control_LoginLabel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::LoginLabel';
end;//Tkw_UserProperty_Control_LoginLabel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_LoginLabel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('LoginLabel');
inherited;
end;//Tkw_UserProperty_Control_LoginLabel_Push.DoDoIt
class function Tkw_UserProperty_Control_LoginLabel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::LoginLabel:push';
end;//Tkw_UserProperty_Control_LoginLabel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_EMailLabel.GetString: AnsiString;
begin
Result := 'EMailLabel';
end;//Tkw_UserProperty_Control_EMailLabel.GetString
class procedure Tkw_UserProperty_Control_EMailLabel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLabel);
end;//Tkw_UserProperty_Control_EMailLabel.RegisterInEngine
class function Tkw_UserProperty_Control_EMailLabel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::EMailLabel';
end;//Tkw_UserProperty_Control_EMailLabel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_EMailLabel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('EMailLabel');
inherited;
end;//Tkw_UserProperty_Control_EMailLabel_Push.DoDoIt
class function Tkw_UserProperty_Control_EMailLabel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::EMailLabel:push';
end;//Tkw_UserProperty_Control_EMailLabel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_ConfirmPasswordLabel.GetString: AnsiString;
begin
Result := 'ConfirmPasswordLabel';
end;//Tkw_UserProperty_Control_ConfirmPasswordLabel.GetString
class procedure Tkw_UserProperty_Control_ConfirmPasswordLabel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLabel);
end;//Tkw_UserProperty_Control_ConfirmPasswordLabel.RegisterInEngine
class function Tkw_UserProperty_Control_ConfirmPasswordLabel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::ConfirmPasswordLabel';
end;//Tkw_UserProperty_Control_ConfirmPasswordLabel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_ConfirmPasswordLabel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('ConfirmPasswordLabel');
inherited;
end;//Tkw_UserProperty_Control_ConfirmPasswordLabel_Push.DoDoIt
class function Tkw_UserProperty_Control_ConfirmPasswordLabel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::ConfirmPasswordLabel:push';
end;//Tkw_UserProperty_Control_ConfirmPasswordLabel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_GroupLabel.GetString: AnsiString;
begin
Result := 'GroupLabel';
end;//Tkw_UserProperty_Control_GroupLabel.GetString
class procedure Tkw_UserProperty_Control_GroupLabel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLabel);
end;//Tkw_UserProperty_Control_GroupLabel.RegisterInEngine
class function Tkw_UserProperty_Control_GroupLabel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::GroupLabel';
end;//Tkw_UserProperty_Control_GroupLabel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_GroupLabel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('GroupLabel');
inherited;
end;//Tkw_UserProperty_Control_GroupLabel_Push.DoDoIt
class function Tkw_UserProperty_Control_GroupLabel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::GroupLabel:push';
end;//Tkw_UserProperty_Control_GroupLabel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_edPassword.GetString: AnsiString;
begin
Result := 'edPassword';
end;//Tkw_UserProperty_Control_edPassword.GetString
class procedure Tkw_UserProperty_Control_edPassword.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscComboBoxWithPwdChar);
end;//Tkw_UserProperty_Control_edPassword.RegisterInEngine
class function Tkw_UserProperty_Control_edPassword.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edPassword';
end;//Tkw_UserProperty_Control_edPassword.GetWordNameForRegister
procedure Tkw_UserProperty_Control_edPassword_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edPassword');
inherited;
end;//Tkw_UserProperty_Control_edPassword_Push.DoDoIt
class function Tkw_UserProperty_Control_edPassword_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edPassword:push';
end;//Tkw_UserProperty_Control_edPassword_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_edUserName.GetString: AnsiString;
begin
Result := 'edUserName';
end;//Tkw_UserProperty_Control_edUserName.GetString
class procedure Tkw_UserProperty_Control_edUserName.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscEdit);
end;//Tkw_UserProperty_Control_edUserName.RegisterInEngine
class function Tkw_UserProperty_Control_edUserName.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edUserName';
end;//Tkw_UserProperty_Control_edUserName.GetWordNameForRegister
procedure Tkw_UserProperty_Control_edUserName_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edUserName');
inherited;
end;//Tkw_UserProperty_Control_edUserName_Push.DoDoIt
class function Tkw_UserProperty_Control_edUserName_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edUserName:push';
end;//Tkw_UserProperty_Control_edUserName_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_edLogin.GetString: AnsiString;
begin
Result := 'edLogin';
end;//Tkw_UserProperty_Control_edLogin.GetString
class procedure Tkw_UserProperty_Control_edLogin.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscEdit);
end;//Tkw_UserProperty_Control_edLogin.RegisterInEngine
class function Tkw_UserProperty_Control_edLogin.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edLogin';
end;//Tkw_UserProperty_Control_edLogin.GetWordNameForRegister
procedure Tkw_UserProperty_Control_edLogin_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edLogin');
inherited;
end;//Tkw_UserProperty_Control_edLogin_Push.DoDoIt
class function Tkw_UserProperty_Control_edLogin_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edLogin:push';
end;//Tkw_UserProperty_Control_edLogin_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_edEmail.GetString: AnsiString;
begin
Result := 'edEmail';
end;//Tkw_UserProperty_Control_edEmail.GetString
class procedure Tkw_UserProperty_Control_edEmail.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscEdit);
end;//Tkw_UserProperty_Control_edEmail.RegisterInEngine
class function Tkw_UserProperty_Control_edEmail.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edEmail';
end;//Tkw_UserProperty_Control_edEmail.GetWordNameForRegister
procedure Tkw_UserProperty_Control_edEmail_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edEmail');
inherited;
end;//Tkw_UserProperty_Control_edEmail_Push.DoDoIt
class function Tkw_UserProperty_Control_edEmail_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edEmail:push';
end;//Tkw_UserProperty_Control_edEmail_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_edConfirm.GetString: AnsiString;
begin
Result := 'edConfirm';
end;//Tkw_UserProperty_Control_edConfirm.GetString
class procedure Tkw_UserProperty_Control_edConfirm.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscComboBoxWithPwdChar);
end;//Tkw_UserProperty_Control_edConfirm.RegisterInEngine
class function Tkw_UserProperty_Control_edConfirm.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edConfirm';
end;//Tkw_UserProperty_Control_edConfirm.GetWordNameForRegister
procedure Tkw_UserProperty_Control_edConfirm_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edConfirm');
inherited;
end;//Tkw_UserProperty_Control_edConfirm_Push.DoDoIt
class function Tkw_UserProperty_Control_edConfirm_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edConfirm:push';
end;//Tkw_UserProperty_Control_edConfirm_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_edGroup.GetString: AnsiString;
begin
Result := 'edGroup';
end;//Tkw_UserProperty_Control_edGroup.GetString
class procedure Tkw_UserProperty_Control_edGroup.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtComboBoxQS);
end;//Tkw_UserProperty_Control_edGroup.RegisterInEngine
class function Tkw_UserProperty_Control_edGroup.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edGroup';
end;//Tkw_UserProperty_Control_edGroup.GetWordNameForRegister
procedure Tkw_UserProperty_Control_edGroup_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edGroup');
inherited;
end;//Tkw_UserProperty_Control_edGroup_Push.DoDoIt
class function Tkw_UserProperty_Control_edGroup_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edGroup:push';
end;//Tkw_UserProperty_Control_edGroup_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_f_MiddlePanel.GetString: AnsiString;
begin
Result := 'f_MiddlePanel';
end;//Tkw_UserProperty_Control_f_MiddlePanel.GetString
class procedure Tkw_UserProperty_Control_f_MiddlePanel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_UserProperty_Control_f_MiddlePanel.RegisterInEngine
class function Tkw_UserProperty_Control_f_MiddlePanel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::f_MiddlePanel';
end;//Tkw_UserProperty_Control_f_MiddlePanel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_f_MiddlePanel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('f_MiddlePanel');
inherited;
end;//Tkw_UserProperty_Control_f_MiddlePanel_Push.DoDoIt
class function Tkw_UserProperty_Control_f_MiddlePanel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::f_MiddlePanel:push';
end;//Tkw_UserProperty_Control_f_MiddlePanel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_edPrivilegedUser.GetString: AnsiString;
begin
Result := 'edPrivilegedUser';
end;//Tkw_UserProperty_Control_edPrivilegedUser.GetString
class procedure Tkw_UserProperty_Control_edPrivilegedUser.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtCheckBox);
end;//Tkw_UserProperty_Control_edPrivilegedUser.RegisterInEngine
class function Tkw_UserProperty_Control_edPrivilegedUser.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edPrivilegedUser';
end;//Tkw_UserProperty_Control_edPrivilegedUser.GetWordNameForRegister
procedure Tkw_UserProperty_Control_edPrivilegedUser_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edPrivilegedUser');
inherited;
end;//Tkw_UserProperty_Control_edPrivilegedUser_Push.DoDoIt
class function Tkw_UserProperty_Control_edPrivilegedUser_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edPrivilegedUser:push';
end;//Tkw_UserProperty_Control_edPrivilegedUser_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_edBuyConsulting.GetString: AnsiString;
begin
Result := 'edBuyConsulting';
end;//Tkw_UserProperty_Control_edBuyConsulting.GetString
class procedure Tkw_UserProperty_Control_edBuyConsulting.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtCheckBox);
end;//Tkw_UserProperty_Control_edBuyConsulting.RegisterInEngine
class function Tkw_UserProperty_Control_edBuyConsulting.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edBuyConsulting';
end;//Tkw_UserProperty_Control_edBuyConsulting.GetWordNameForRegister
procedure Tkw_UserProperty_Control_edBuyConsulting_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edBuyConsulting');
inherited;
end;//Tkw_UserProperty_Control_edBuyConsulting_Push.DoDoIt
class function Tkw_UserProperty_Control_edBuyConsulting_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edBuyConsulting:push';
end;//Tkw_UserProperty_Control_edBuyConsulting_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel.GetString: AnsiString;
begin
Result := 'f_DontDeleteIdleUserPanel';
end;//Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel.GetString
class procedure Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel.RegisterInEngine
class function Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::f_DontDeleteIdleUserPanel';
end;//Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('f_DontDeleteIdleUserPanel');
inherited;
end;//Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel_Push.DoDoIt
class function Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::f_DontDeleteIdleUserPanel:push';
end;//Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_edDontDeleteIdleUser.GetString: AnsiString;
begin
Result := 'edDontDeleteIdleUser';
end;//Tkw_UserProperty_Control_edDontDeleteIdleUser.GetString
class procedure Tkw_UserProperty_Control_edDontDeleteIdleUser.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtCheckBox);
end;//Tkw_UserProperty_Control_edDontDeleteIdleUser.RegisterInEngine
class function Tkw_UserProperty_Control_edDontDeleteIdleUser.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edDontDeleteIdleUser';
end;//Tkw_UserProperty_Control_edDontDeleteIdleUser.GetWordNameForRegister
procedure Tkw_UserProperty_Control_edDontDeleteIdleUser_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edDontDeleteIdleUser');
inherited;
end;//Tkw_UserProperty_Control_edDontDeleteIdleUser_Push.DoDoIt
class function Tkw_UserProperty_Control_edDontDeleteIdleUser_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edDontDeleteIdleUser:push';
end;//Tkw_UserProperty_Control_edDontDeleteIdleUser_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_f_BottomPanel.GetString: AnsiString;
begin
Result := 'f_BottomPanel';
end;//Tkw_UserProperty_Control_f_BottomPanel.GetString
class procedure Tkw_UserProperty_Control_f_BottomPanel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_UserProperty_Control_f_BottomPanel.RegisterInEngine
class function Tkw_UserProperty_Control_f_BottomPanel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::f_BottomPanel';
end;//Tkw_UserProperty_Control_f_BottomPanel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_f_BottomPanel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('f_BottomPanel');
inherited;
end;//Tkw_UserProperty_Control_f_BottomPanel_Push.DoDoIt
class function Tkw_UserProperty_Control_f_BottomPanel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::f_BottomPanel:push';
end;//Tkw_UserProperty_Control_f_BottomPanel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_InfoLabel.GetString: AnsiString;
begin
Result := 'InfoLabel';
end;//Tkw_UserProperty_Control_InfoLabel.GetString
class procedure Tkw_UserProperty_Control_InfoLabel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtLabel);
end;//Tkw_UserProperty_Control_InfoLabel.RegisterInEngine
class function Tkw_UserProperty_Control_InfoLabel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::InfoLabel';
end;//Tkw_UserProperty_Control_InfoLabel.GetWordNameForRegister
procedure Tkw_UserProperty_Control_InfoLabel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('InfoLabel');
inherited;
end;//Tkw_UserProperty_Control_InfoLabel_Push.DoDoIt
class function Tkw_UserProperty_Control_InfoLabel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::InfoLabel:push';
end;//Tkw_UserProperty_Control_InfoLabel_Push.GetWordNameForRegister
function Tkw_UserProperty_Control_edHasSharedFilters.GetString: AnsiString;
begin
Result := 'edHasSharedFilters';
end;//Tkw_UserProperty_Control_edHasSharedFilters.GetString
class procedure Tkw_UserProperty_Control_edHasSharedFilters.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtCheckBox);
end;//Tkw_UserProperty_Control_edHasSharedFilters.RegisterInEngine
class function Tkw_UserProperty_Control_edHasSharedFilters.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edHasSharedFilters';
end;//Tkw_UserProperty_Control_edHasSharedFilters.GetWordNameForRegister
procedure Tkw_UserProperty_Control_edHasSharedFilters_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edHasSharedFilters');
inherited;
end;//Tkw_UserProperty_Control_edHasSharedFilters_Push.DoDoIt
class function Tkw_UserProperty_Control_edHasSharedFilters_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edHasSharedFilters:push';
end;//Tkw_UserProperty_Control_edHasSharedFilters_Push.GetWordNameForRegister
function TkwEfUserPropertyPnMainData.pnMainData(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtPanel;
{* Реализация слова скрипта .TefUserProperty.pnMainData }
begin
Result := aefUserProperty.pnMainData;
end;//TkwEfUserPropertyPnMainData.pnMainData
class function TkwEfUserPropertyPnMainData.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.pnMainData';
end;//TkwEfUserPropertyPnMainData.GetWordNameForRegister
function TkwEfUserPropertyPnMainData.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwEfUserPropertyPnMainData.GetResultTypeInfo
function TkwEfUserPropertyPnMainData.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyPnMainData.GetAllParamsCount
function TkwEfUserPropertyPnMainData.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyPnMainData.ParamsTypes
procedure TkwEfUserPropertyPnMainData.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству pnMainData', aCtx);
end;//TkwEfUserPropertyPnMainData.SetValuePrim
procedure TkwEfUserPropertyPnMainData.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(pnMainData(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyPnMainData.DoDoIt
function TkwEfUserPropertyFTopPanel.f_TopPanel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtPanel;
{* Реализация слова скрипта .TefUserProperty.f_TopPanel }
begin
Result := aefUserProperty.f_TopPanel;
end;//TkwEfUserPropertyFTopPanel.f_TopPanel
class function TkwEfUserPropertyFTopPanel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.f_TopPanel';
end;//TkwEfUserPropertyFTopPanel.GetWordNameForRegister
function TkwEfUserPropertyFTopPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwEfUserPropertyFTopPanel.GetResultTypeInfo
function TkwEfUserPropertyFTopPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyFTopPanel.GetAllParamsCount
function TkwEfUserPropertyFTopPanel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyFTopPanel.ParamsTypes
procedure TkwEfUserPropertyFTopPanel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству f_TopPanel', aCtx);
end;//TkwEfUserPropertyFTopPanel.SetValuePrim
procedure TkwEfUserPropertyFTopPanel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(f_TopPanel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyFTopPanel.DoDoIt
function TkwEfUserPropertyUserNameLabel.UserNameLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.UserNameLabel }
begin
Result := aefUserProperty.UserNameLabel;
end;//TkwEfUserPropertyUserNameLabel.UserNameLabel
class function TkwEfUserPropertyUserNameLabel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.UserNameLabel';
end;//TkwEfUserPropertyUserNameLabel.GetWordNameForRegister
function TkwEfUserPropertyUserNameLabel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLabel);
end;//TkwEfUserPropertyUserNameLabel.GetResultTypeInfo
function TkwEfUserPropertyUserNameLabel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyUserNameLabel.GetAllParamsCount
function TkwEfUserPropertyUserNameLabel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyUserNameLabel.ParamsTypes
procedure TkwEfUserPropertyUserNameLabel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству UserNameLabel', aCtx);
end;//TkwEfUserPropertyUserNameLabel.SetValuePrim
procedure TkwEfUserPropertyUserNameLabel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(UserNameLabel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyUserNameLabel.DoDoIt
function TkwEfUserPropertyPasswordLabel.PasswordLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.PasswordLabel }
begin
Result := aefUserProperty.PasswordLabel;
end;//TkwEfUserPropertyPasswordLabel.PasswordLabel
class function TkwEfUserPropertyPasswordLabel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.PasswordLabel';
end;//TkwEfUserPropertyPasswordLabel.GetWordNameForRegister
function TkwEfUserPropertyPasswordLabel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLabel);
end;//TkwEfUserPropertyPasswordLabel.GetResultTypeInfo
function TkwEfUserPropertyPasswordLabel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyPasswordLabel.GetAllParamsCount
function TkwEfUserPropertyPasswordLabel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyPasswordLabel.ParamsTypes
procedure TkwEfUserPropertyPasswordLabel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству PasswordLabel', aCtx);
end;//TkwEfUserPropertyPasswordLabel.SetValuePrim
procedure TkwEfUserPropertyPasswordLabel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(PasswordLabel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyPasswordLabel.DoDoIt
function TkwEfUserPropertyLoginLabel.LoginLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.LoginLabel }
begin
Result := aefUserProperty.LoginLabel;
end;//TkwEfUserPropertyLoginLabel.LoginLabel
class function TkwEfUserPropertyLoginLabel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.LoginLabel';
end;//TkwEfUserPropertyLoginLabel.GetWordNameForRegister
function TkwEfUserPropertyLoginLabel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLabel);
end;//TkwEfUserPropertyLoginLabel.GetResultTypeInfo
function TkwEfUserPropertyLoginLabel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyLoginLabel.GetAllParamsCount
function TkwEfUserPropertyLoginLabel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyLoginLabel.ParamsTypes
procedure TkwEfUserPropertyLoginLabel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству LoginLabel', aCtx);
end;//TkwEfUserPropertyLoginLabel.SetValuePrim
procedure TkwEfUserPropertyLoginLabel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(LoginLabel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyLoginLabel.DoDoIt
function TkwEfUserPropertyEMailLabel.EMailLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.EMailLabel }
begin
Result := aefUserProperty.EMailLabel;
end;//TkwEfUserPropertyEMailLabel.EMailLabel
class function TkwEfUserPropertyEMailLabel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.EMailLabel';
end;//TkwEfUserPropertyEMailLabel.GetWordNameForRegister
function TkwEfUserPropertyEMailLabel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLabel);
end;//TkwEfUserPropertyEMailLabel.GetResultTypeInfo
function TkwEfUserPropertyEMailLabel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEMailLabel.GetAllParamsCount
function TkwEfUserPropertyEMailLabel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEMailLabel.ParamsTypes
procedure TkwEfUserPropertyEMailLabel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству EMailLabel', aCtx);
end;//TkwEfUserPropertyEMailLabel.SetValuePrim
procedure TkwEfUserPropertyEMailLabel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(EMailLabel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEMailLabel.DoDoIt
function TkwEfUserPropertyConfirmPasswordLabel.ConfirmPasswordLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.ConfirmPasswordLabel }
begin
Result := aefUserProperty.ConfirmPasswordLabel;
end;//TkwEfUserPropertyConfirmPasswordLabel.ConfirmPasswordLabel
class function TkwEfUserPropertyConfirmPasswordLabel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.ConfirmPasswordLabel';
end;//TkwEfUserPropertyConfirmPasswordLabel.GetWordNameForRegister
function TkwEfUserPropertyConfirmPasswordLabel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLabel);
end;//TkwEfUserPropertyConfirmPasswordLabel.GetResultTypeInfo
function TkwEfUserPropertyConfirmPasswordLabel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyConfirmPasswordLabel.GetAllParamsCount
function TkwEfUserPropertyConfirmPasswordLabel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyConfirmPasswordLabel.ParamsTypes
procedure TkwEfUserPropertyConfirmPasswordLabel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству ConfirmPasswordLabel', aCtx);
end;//TkwEfUserPropertyConfirmPasswordLabel.SetValuePrim
procedure TkwEfUserPropertyConfirmPasswordLabel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(ConfirmPasswordLabel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyConfirmPasswordLabel.DoDoIt
function TkwEfUserPropertyGroupLabel.GroupLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.GroupLabel }
begin
Result := aefUserProperty.GroupLabel;
end;//TkwEfUserPropertyGroupLabel.GroupLabel
class function TkwEfUserPropertyGroupLabel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.GroupLabel';
end;//TkwEfUserPropertyGroupLabel.GetWordNameForRegister
function TkwEfUserPropertyGroupLabel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLabel);
end;//TkwEfUserPropertyGroupLabel.GetResultTypeInfo
function TkwEfUserPropertyGroupLabel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyGroupLabel.GetAllParamsCount
function TkwEfUserPropertyGroupLabel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyGroupLabel.ParamsTypes
procedure TkwEfUserPropertyGroupLabel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству GroupLabel', aCtx);
end;//TkwEfUserPropertyGroupLabel.SetValuePrim
procedure TkwEfUserPropertyGroupLabel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(GroupLabel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyGroupLabel.DoDoIt
function TkwEfUserPropertyEdPassword.edPassword(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TnscComboBoxWithPwdChar;
{* Реализация слова скрипта .TefUserProperty.edPassword }
begin
Result := aefUserProperty.edPassword;
end;//TkwEfUserPropertyEdPassword.edPassword
class function TkwEfUserPropertyEdPassword.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.edPassword';
end;//TkwEfUserPropertyEdPassword.GetWordNameForRegister
function TkwEfUserPropertyEdPassword.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscComboBoxWithPwdChar);
end;//TkwEfUserPropertyEdPassword.GetResultTypeInfo
function TkwEfUserPropertyEdPassword.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEdPassword.GetAllParamsCount
function TkwEfUserPropertyEdPassword.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEdPassword.ParamsTypes
procedure TkwEfUserPropertyEdPassword.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edPassword', aCtx);
end;//TkwEfUserPropertyEdPassword.SetValuePrim
procedure TkwEfUserPropertyEdPassword.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edPassword(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEdPassword.DoDoIt
function TkwEfUserPropertyEdUserName.edUserName(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TnscEdit;
{* Реализация слова скрипта .TefUserProperty.edUserName }
begin
Result := aefUserProperty.edUserName;
end;//TkwEfUserPropertyEdUserName.edUserName
class function TkwEfUserPropertyEdUserName.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.edUserName';
end;//TkwEfUserPropertyEdUserName.GetWordNameForRegister
function TkwEfUserPropertyEdUserName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscEdit);
end;//TkwEfUserPropertyEdUserName.GetResultTypeInfo
function TkwEfUserPropertyEdUserName.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEdUserName.GetAllParamsCount
function TkwEfUserPropertyEdUserName.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEdUserName.ParamsTypes
procedure TkwEfUserPropertyEdUserName.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edUserName', aCtx);
end;//TkwEfUserPropertyEdUserName.SetValuePrim
procedure TkwEfUserPropertyEdUserName.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edUserName(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEdUserName.DoDoIt
function TkwEfUserPropertyEdLogin.edLogin(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TnscEdit;
{* Реализация слова скрипта .TefUserProperty.edLogin }
begin
Result := aefUserProperty.edLogin;
end;//TkwEfUserPropertyEdLogin.edLogin
class function TkwEfUserPropertyEdLogin.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.edLogin';
end;//TkwEfUserPropertyEdLogin.GetWordNameForRegister
function TkwEfUserPropertyEdLogin.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscEdit);
end;//TkwEfUserPropertyEdLogin.GetResultTypeInfo
function TkwEfUserPropertyEdLogin.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEdLogin.GetAllParamsCount
function TkwEfUserPropertyEdLogin.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEdLogin.ParamsTypes
procedure TkwEfUserPropertyEdLogin.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edLogin', aCtx);
end;//TkwEfUserPropertyEdLogin.SetValuePrim
procedure TkwEfUserPropertyEdLogin.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edLogin(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEdLogin.DoDoIt
function TkwEfUserPropertyEdEmail.edEmail(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TnscEdit;
{* Реализация слова скрипта .TefUserProperty.edEmail }
begin
Result := aefUserProperty.edEmail;
end;//TkwEfUserPropertyEdEmail.edEmail
class function TkwEfUserPropertyEdEmail.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.edEmail';
end;//TkwEfUserPropertyEdEmail.GetWordNameForRegister
function TkwEfUserPropertyEdEmail.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscEdit);
end;//TkwEfUserPropertyEdEmail.GetResultTypeInfo
function TkwEfUserPropertyEdEmail.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEdEmail.GetAllParamsCount
function TkwEfUserPropertyEdEmail.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEdEmail.ParamsTypes
procedure TkwEfUserPropertyEdEmail.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edEmail', aCtx);
end;//TkwEfUserPropertyEdEmail.SetValuePrim
procedure TkwEfUserPropertyEdEmail.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edEmail(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEdEmail.DoDoIt
function TkwEfUserPropertyEdConfirm.edConfirm(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TnscComboBoxWithPwdChar;
{* Реализация слова скрипта .TefUserProperty.edConfirm }
begin
Result := aefUserProperty.edConfirm;
end;//TkwEfUserPropertyEdConfirm.edConfirm
class function TkwEfUserPropertyEdConfirm.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.edConfirm';
end;//TkwEfUserPropertyEdConfirm.GetWordNameForRegister
function TkwEfUserPropertyEdConfirm.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscComboBoxWithPwdChar);
end;//TkwEfUserPropertyEdConfirm.GetResultTypeInfo
function TkwEfUserPropertyEdConfirm.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEdConfirm.GetAllParamsCount
function TkwEfUserPropertyEdConfirm.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEdConfirm.ParamsTypes
procedure TkwEfUserPropertyEdConfirm.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edConfirm', aCtx);
end;//TkwEfUserPropertyEdConfirm.SetValuePrim
procedure TkwEfUserPropertyEdConfirm.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edConfirm(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEdConfirm.DoDoIt
function TkwEfUserPropertyEdGroup.edGroup(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtComboBoxQS;
{* Реализация слова скрипта .TefUserProperty.edGroup }
begin
Result := aefUserProperty.edGroup;
end;//TkwEfUserPropertyEdGroup.edGroup
class function TkwEfUserPropertyEdGroup.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.edGroup';
end;//TkwEfUserPropertyEdGroup.GetWordNameForRegister
function TkwEfUserPropertyEdGroup.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtComboBoxQS);
end;//TkwEfUserPropertyEdGroup.GetResultTypeInfo
function TkwEfUserPropertyEdGroup.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEdGroup.GetAllParamsCount
function TkwEfUserPropertyEdGroup.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEdGroup.ParamsTypes
procedure TkwEfUserPropertyEdGroup.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edGroup', aCtx);
end;//TkwEfUserPropertyEdGroup.SetValuePrim
procedure TkwEfUserPropertyEdGroup.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edGroup(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEdGroup.DoDoIt
function TkwEfUserPropertyFMiddlePanel.f_MiddlePanel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtPanel;
{* Реализация слова скрипта .TefUserProperty.f_MiddlePanel }
begin
Result := aefUserProperty.f_MiddlePanel;
end;//TkwEfUserPropertyFMiddlePanel.f_MiddlePanel
class function TkwEfUserPropertyFMiddlePanel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.f_MiddlePanel';
end;//TkwEfUserPropertyFMiddlePanel.GetWordNameForRegister
function TkwEfUserPropertyFMiddlePanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwEfUserPropertyFMiddlePanel.GetResultTypeInfo
function TkwEfUserPropertyFMiddlePanel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyFMiddlePanel.GetAllParamsCount
function TkwEfUserPropertyFMiddlePanel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyFMiddlePanel.ParamsTypes
procedure TkwEfUserPropertyFMiddlePanel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству f_MiddlePanel', aCtx);
end;//TkwEfUserPropertyFMiddlePanel.SetValuePrim
procedure TkwEfUserPropertyFMiddlePanel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(f_MiddlePanel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyFMiddlePanel.DoDoIt
function TkwEfUserPropertyEdPrivilegedUser.edPrivilegedUser(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtCheckBox;
{* Реализация слова скрипта .TefUserProperty.edPrivilegedUser }
begin
Result := aefUserProperty.edPrivilegedUser;
end;//TkwEfUserPropertyEdPrivilegedUser.edPrivilegedUser
class function TkwEfUserPropertyEdPrivilegedUser.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.edPrivilegedUser';
end;//TkwEfUserPropertyEdPrivilegedUser.GetWordNameForRegister
function TkwEfUserPropertyEdPrivilegedUser.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtCheckBox);
end;//TkwEfUserPropertyEdPrivilegedUser.GetResultTypeInfo
function TkwEfUserPropertyEdPrivilegedUser.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEdPrivilegedUser.GetAllParamsCount
function TkwEfUserPropertyEdPrivilegedUser.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEdPrivilegedUser.ParamsTypes
procedure TkwEfUserPropertyEdPrivilegedUser.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edPrivilegedUser', aCtx);
end;//TkwEfUserPropertyEdPrivilegedUser.SetValuePrim
procedure TkwEfUserPropertyEdPrivilegedUser.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edPrivilegedUser(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEdPrivilegedUser.DoDoIt
function TkwEfUserPropertyEdBuyConsulting.edBuyConsulting(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtCheckBox;
{* Реализация слова скрипта .TefUserProperty.edBuyConsulting }
begin
Result := aefUserProperty.edBuyConsulting;
end;//TkwEfUserPropertyEdBuyConsulting.edBuyConsulting
class function TkwEfUserPropertyEdBuyConsulting.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.edBuyConsulting';
end;//TkwEfUserPropertyEdBuyConsulting.GetWordNameForRegister
function TkwEfUserPropertyEdBuyConsulting.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtCheckBox);
end;//TkwEfUserPropertyEdBuyConsulting.GetResultTypeInfo
function TkwEfUserPropertyEdBuyConsulting.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEdBuyConsulting.GetAllParamsCount
function TkwEfUserPropertyEdBuyConsulting.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEdBuyConsulting.ParamsTypes
procedure TkwEfUserPropertyEdBuyConsulting.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edBuyConsulting', aCtx);
end;//TkwEfUserPropertyEdBuyConsulting.SetValuePrim
procedure TkwEfUserPropertyEdBuyConsulting.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edBuyConsulting(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEdBuyConsulting.DoDoIt
function TkwEfUserPropertyFDontDeleteIdleUserPanel.f_DontDeleteIdleUserPanel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtPanel;
{* Реализация слова скрипта .TefUserProperty.f_DontDeleteIdleUserPanel }
begin
Result := aefUserProperty.f_DontDeleteIdleUserPanel;
end;//TkwEfUserPropertyFDontDeleteIdleUserPanel.f_DontDeleteIdleUserPanel
class function TkwEfUserPropertyFDontDeleteIdleUserPanel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.f_DontDeleteIdleUserPanel';
end;//TkwEfUserPropertyFDontDeleteIdleUserPanel.GetWordNameForRegister
function TkwEfUserPropertyFDontDeleteIdleUserPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwEfUserPropertyFDontDeleteIdleUserPanel.GetResultTypeInfo
function TkwEfUserPropertyFDontDeleteIdleUserPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyFDontDeleteIdleUserPanel.GetAllParamsCount
function TkwEfUserPropertyFDontDeleteIdleUserPanel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyFDontDeleteIdleUserPanel.ParamsTypes
procedure TkwEfUserPropertyFDontDeleteIdleUserPanel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству f_DontDeleteIdleUserPanel', aCtx);
end;//TkwEfUserPropertyFDontDeleteIdleUserPanel.SetValuePrim
procedure TkwEfUserPropertyFDontDeleteIdleUserPanel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(f_DontDeleteIdleUserPanel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyFDontDeleteIdleUserPanel.DoDoIt
function TkwEfUserPropertyEdDontDeleteIdleUser.edDontDeleteIdleUser(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtCheckBox;
{* Реализация слова скрипта .TefUserProperty.edDontDeleteIdleUser }
begin
Result := aefUserProperty.edDontDeleteIdleUser;
end;//TkwEfUserPropertyEdDontDeleteIdleUser.edDontDeleteIdleUser
class function TkwEfUserPropertyEdDontDeleteIdleUser.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.edDontDeleteIdleUser';
end;//TkwEfUserPropertyEdDontDeleteIdleUser.GetWordNameForRegister
function TkwEfUserPropertyEdDontDeleteIdleUser.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtCheckBox);
end;//TkwEfUserPropertyEdDontDeleteIdleUser.GetResultTypeInfo
function TkwEfUserPropertyEdDontDeleteIdleUser.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEdDontDeleteIdleUser.GetAllParamsCount
function TkwEfUserPropertyEdDontDeleteIdleUser.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEdDontDeleteIdleUser.ParamsTypes
procedure TkwEfUserPropertyEdDontDeleteIdleUser.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edDontDeleteIdleUser', aCtx);
end;//TkwEfUserPropertyEdDontDeleteIdleUser.SetValuePrim
procedure TkwEfUserPropertyEdDontDeleteIdleUser.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edDontDeleteIdleUser(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEdDontDeleteIdleUser.DoDoIt
function TkwEfUserPropertyFBottomPanel.f_BottomPanel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtPanel;
{* Реализация слова скрипта .TefUserProperty.f_BottomPanel }
begin
Result := aefUserProperty.f_BottomPanel;
end;//TkwEfUserPropertyFBottomPanel.f_BottomPanel
class function TkwEfUserPropertyFBottomPanel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.f_BottomPanel';
end;//TkwEfUserPropertyFBottomPanel.GetWordNameForRegister
function TkwEfUserPropertyFBottomPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwEfUserPropertyFBottomPanel.GetResultTypeInfo
function TkwEfUserPropertyFBottomPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyFBottomPanel.GetAllParamsCount
function TkwEfUserPropertyFBottomPanel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyFBottomPanel.ParamsTypes
procedure TkwEfUserPropertyFBottomPanel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству f_BottomPanel', aCtx);
end;//TkwEfUserPropertyFBottomPanel.SetValuePrim
procedure TkwEfUserPropertyFBottomPanel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(f_BottomPanel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyFBottomPanel.DoDoIt
function TkwEfUserPropertyInfoLabel.InfoLabel(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtLabel;
{* Реализация слова скрипта .TefUserProperty.InfoLabel }
begin
Result := aefUserProperty.InfoLabel;
end;//TkwEfUserPropertyInfoLabel.InfoLabel
class function TkwEfUserPropertyInfoLabel.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.InfoLabel';
end;//TkwEfUserPropertyInfoLabel.GetWordNameForRegister
function TkwEfUserPropertyInfoLabel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtLabel);
end;//TkwEfUserPropertyInfoLabel.GetResultTypeInfo
function TkwEfUserPropertyInfoLabel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyInfoLabel.GetAllParamsCount
function TkwEfUserPropertyInfoLabel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyInfoLabel.ParamsTypes
procedure TkwEfUserPropertyInfoLabel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству InfoLabel', aCtx);
end;//TkwEfUserPropertyInfoLabel.SetValuePrim
procedure TkwEfUserPropertyInfoLabel.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(InfoLabel(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyInfoLabel.DoDoIt
function TkwEfUserPropertyEdHasSharedFilters.edHasSharedFilters(const aCtx: TtfwContext;
aefUserProperty: TefUserProperty): TvtCheckBox;
{* Реализация слова скрипта .TefUserProperty.edHasSharedFilters }
begin
Result := aefUserProperty.edHasSharedFilters;
end;//TkwEfUserPropertyEdHasSharedFilters.edHasSharedFilters
class function TkwEfUserPropertyEdHasSharedFilters.GetWordNameForRegister: AnsiString;
begin
Result := '.TefUserProperty.edHasSharedFilters';
end;//TkwEfUserPropertyEdHasSharedFilters.GetWordNameForRegister
function TkwEfUserPropertyEdHasSharedFilters.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtCheckBox);
end;//TkwEfUserPropertyEdHasSharedFilters.GetResultTypeInfo
function TkwEfUserPropertyEdHasSharedFilters.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEfUserPropertyEdHasSharedFilters.GetAllParamsCount
function TkwEfUserPropertyEdHasSharedFilters.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TefUserProperty)]);
end;//TkwEfUserPropertyEdHasSharedFilters.ParamsTypes
procedure TkwEfUserPropertyEdHasSharedFilters.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edHasSharedFilters', aCtx);
end;//TkwEfUserPropertyEdHasSharedFilters.SetValuePrim
procedure TkwEfUserPropertyEdHasSharedFilters.DoDoIt(const aCtx: TtfwContext);
var l_aefUserProperty: TefUserProperty;
begin
try
l_aefUserProperty := TefUserProperty(aCtx.rEngine.PopObjAs(TefUserProperty));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aefUserProperty: TefUserProperty : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edHasSharedFilters(aCtx, l_aefUserProperty));
end;//TkwEfUserPropertyEdHasSharedFilters.DoDoIt
initialization
Tkw_Form_UserProperty.RegisterInEngine;
{* Регистрация Tkw_Form_UserProperty }
Tkw_UserProperty_Control_pnMainData.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_pnMainData }
Tkw_UserProperty_Control_pnMainData_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_pnMainData_Push }
Tkw_UserProperty_Control_f_TopPanel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_f_TopPanel }
Tkw_UserProperty_Control_f_TopPanel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_f_TopPanel_Push }
Tkw_UserProperty_Control_UserNameLabel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_UserNameLabel }
Tkw_UserProperty_Control_UserNameLabel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_UserNameLabel_Push }
Tkw_UserProperty_Control_PasswordLabel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_PasswordLabel }
Tkw_UserProperty_Control_PasswordLabel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_PasswordLabel_Push }
Tkw_UserProperty_Control_LoginLabel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_LoginLabel }
Tkw_UserProperty_Control_LoginLabel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_LoginLabel_Push }
Tkw_UserProperty_Control_EMailLabel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_EMailLabel }
Tkw_UserProperty_Control_EMailLabel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_EMailLabel_Push }
Tkw_UserProperty_Control_ConfirmPasswordLabel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_ConfirmPasswordLabel }
Tkw_UserProperty_Control_ConfirmPasswordLabel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_ConfirmPasswordLabel_Push }
Tkw_UserProperty_Control_GroupLabel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_GroupLabel }
Tkw_UserProperty_Control_GroupLabel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_GroupLabel_Push }
Tkw_UserProperty_Control_edPassword.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edPassword }
Tkw_UserProperty_Control_edPassword_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edPassword_Push }
Tkw_UserProperty_Control_edUserName.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edUserName }
Tkw_UserProperty_Control_edUserName_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edUserName_Push }
Tkw_UserProperty_Control_edLogin.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edLogin }
Tkw_UserProperty_Control_edLogin_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edLogin_Push }
Tkw_UserProperty_Control_edEmail.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edEmail }
Tkw_UserProperty_Control_edEmail_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edEmail_Push }
Tkw_UserProperty_Control_edConfirm.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edConfirm }
Tkw_UserProperty_Control_edConfirm_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edConfirm_Push }
Tkw_UserProperty_Control_edGroup.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edGroup }
Tkw_UserProperty_Control_edGroup_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edGroup_Push }
Tkw_UserProperty_Control_f_MiddlePanel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_f_MiddlePanel }
Tkw_UserProperty_Control_f_MiddlePanel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_f_MiddlePanel_Push }
Tkw_UserProperty_Control_edPrivilegedUser.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edPrivilegedUser }
Tkw_UserProperty_Control_edPrivilegedUser_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edPrivilegedUser_Push }
Tkw_UserProperty_Control_edBuyConsulting.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edBuyConsulting }
Tkw_UserProperty_Control_edBuyConsulting_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edBuyConsulting_Push }
Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel }
Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_f_DontDeleteIdleUserPanel_Push }
Tkw_UserProperty_Control_edDontDeleteIdleUser.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edDontDeleteIdleUser }
Tkw_UserProperty_Control_edDontDeleteIdleUser_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edDontDeleteIdleUser_Push }
Tkw_UserProperty_Control_f_BottomPanel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_f_BottomPanel }
Tkw_UserProperty_Control_f_BottomPanel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_f_BottomPanel_Push }
Tkw_UserProperty_Control_InfoLabel.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_InfoLabel }
Tkw_UserProperty_Control_InfoLabel_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_InfoLabel_Push }
Tkw_UserProperty_Control_edHasSharedFilters.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edHasSharedFilters }
Tkw_UserProperty_Control_edHasSharedFilters_Push.RegisterInEngine;
{* Регистрация Tkw_UserProperty_Control_edHasSharedFilters_Push }
TkwEfUserPropertyPnMainData.RegisterInEngine;
{* Регистрация efUserProperty_pnMainData }
TkwEfUserPropertyFTopPanel.RegisterInEngine;
{* Регистрация efUserProperty_f_TopPanel }
TkwEfUserPropertyUserNameLabel.RegisterInEngine;
{* Регистрация efUserProperty_UserNameLabel }
TkwEfUserPropertyPasswordLabel.RegisterInEngine;
{* Регистрация efUserProperty_PasswordLabel }
TkwEfUserPropertyLoginLabel.RegisterInEngine;
{* Регистрация efUserProperty_LoginLabel }
TkwEfUserPropertyEMailLabel.RegisterInEngine;
{* Регистрация efUserProperty_EMailLabel }
TkwEfUserPropertyConfirmPasswordLabel.RegisterInEngine;
{* Регистрация efUserProperty_ConfirmPasswordLabel }
TkwEfUserPropertyGroupLabel.RegisterInEngine;
{* Регистрация efUserProperty_GroupLabel }
TkwEfUserPropertyEdPassword.RegisterInEngine;
{* Регистрация efUserProperty_edPassword }
TkwEfUserPropertyEdUserName.RegisterInEngine;
{* Регистрация efUserProperty_edUserName }
TkwEfUserPropertyEdLogin.RegisterInEngine;
{* Регистрация efUserProperty_edLogin }
TkwEfUserPropertyEdEmail.RegisterInEngine;
{* Регистрация efUserProperty_edEmail }
TkwEfUserPropertyEdConfirm.RegisterInEngine;
{* Регистрация efUserProperty_edConfirm }
TkwEfUserPropertyEdGroup.RegisterInEngine;
{* Регистрация efUserProperty_edGroup }
TkwEfUserPropertyFMiddlePanel.RegisterInEngine;
{* Регистрация efUserProperty_f_MiddlePanel }
TkwEfUserPropertyEdPrivilegedUser.RegisterInEngine;
{* Регистрация efUserProperty_edPrivilegedUser }
TkwEfUserPropertyEdBuyConsulting.RegisterInEngine;
{* Регистрация efUserProperty_edBuyConsulting }
TkwEfUserPropertyFDontDeleteIdleUserPanel.RegisterInEngine;
{* Регистрация efUserProperty_f_DontDeleteIdleUserPanel }
TkwEfUserPropertyEdDontDeleteIdleUser.RegisterInEngine;
{* Регистрация efUserProperty_edDontDeleteIdleUser }
TkwEfUserPropertyFBottomPanel.RegisterInEngine;
{* Регистрация efUserProperty_f_BottomPanel }
TkwEfUserPropertyInfoLabel.RegisterInEngine;
{* Регистрация efUserProperty_InfoLabel }
TkwEfUserPropertyEdHasSharedFilters.RegisterInEngine;
{* Регистрация efUserProperty_edHasSharedFilters }
TtfwTypeRegistrator.RegisterType(TypeInfo(TefUserProperty));
{* Регистрация типа TefUserProperty }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel));
{* Регистрация типа TvtPanel }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel));
{* Регистрация типа TvtLabel }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscComboBoxWithPwdChar));
{* Регистрация типа TnscComboBoxWithPwdChar }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscEdit));
{* Регистрация типа TnscEdit }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtComboBoxQS));
{* Регистрация типа TvtComboBoxQS }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtCheckBox));
{* Регистрация типа TvtCheckBox }
{$IfEnd} // Defined(Admin) AND NOT Defined(NoScripts)
end.
|
{*******************************************************************************
作者: dmzn@163.com 2008-08-07
描述: 系统数据库常量定义
备注:
*.自动创建SQL语句,支持变量:$Inc,自增;$Float,浮点;$Integer=sFlag_Integer;
$Decimal=sFlag_Decimal;$Image,二进制流
*******************************************************************************}
unit USysDB;
{$I Link.inc}
interface
uses
SysUtils, Classes;
const
cSysDatabaseName: array[0..4] of String = (
'Access', 'SQL', 'MySQL', 'Oracle', 'DB2');
//db names
type
TSysDatabaseType = (dtAccess, dtSQLServer, dtMySQL, dtOracle, dtDB2);
//db types
PSysTableItem = ^TSysTableItem;
TSysTableItem = record
FTable: string;
FNewSQL: string;
end;
//系统表项
var
gSysTableList: TList = nil; //系统表数组
gSysDBType: TSysDatabaseType = dtSQLServer; //系统数据类型
//------------------------------------------------------------------------------
const
//自增字段
sField_Access_AutoInc = 'Counter';
sField_SQLServer_AutoInc = 'Integer IDENTITY (1,1) PRIMARY KEY';
//小数字段
sField_Access_Decimal = 'Float';
sField_SQLServer_Decimal = 'Decimal(15, 5)';
//图片字段
sField_Access_Image = 'OLEObject';
sField_SQLServer_Image = 'Image';
//日期相关
sField_SQLServer_Now = 'getDate()';
ResourceString
{*权限项*}
sPopedom_Read = 'A'; //浏览
sPopedom_Add = 'B'; //添加
sPopedom_Edit = 'C'; //修改
sPopedom_Delete = 'D'; //删除
sPopedom_Preview = 'E'; //预览
sPopedom_Print = 'F'; //打印
sPopedom_Export = 'G'; //导出
{*相关标记*}
sFlag_Yes = 'Y'; //是
sFlag_No = 'N'; //否
sFlag_Enabled = 'Y'; //启用
sFlag_Disabled = 'N'; //禁用
sFlag_Man = 'A'; //男士
sFlag_Woman = 'B'; //女士
sFlag_Integer = 'I'; //整数
sFlag_Decimal = 'D'; //小数
sFlag_MemberItem = 'MemberItem'; //会员信息项
sFlag_RelationItem = 'RelationItem'; //关系信息项
sFlag_RemindItem = 'RemindItem'; //提醒信息项
sFlag_Beautician = 'Beautician'; //美容师信息
sFlag_ProductType = 'ProductType'; //产品分类
sFlag_PlantItem = 'PlantItem'; //厂商信息项
sFlag_ProviderItem = 'ProviderItem'; //供应商信息项
sFlag_ProductItem = 'ProductItem'; //产品信息项
sFlag_SkinPart = 'SkinPartItem'; //皮肤部位信息项
sFlag_SkinType = 'SkinTypeItem'; //皮肤状况信息项
sFlag_PlanItem = 'PlanItem'; //方案类型
sFlag_Hardware = 'HardwareItem'; //硬件信息
{*数据表*}
sTable_Group = 'Sys_Group'; //用户组
sTable_User = 'Sys_User'; //用户表
sTable_Menu = 'Sys_Menu'; //菜单表
sTable_Popedom = 'Sys_Popedom'; //权限表
sTable_PopItem = 'Sys_PopItem'; //权限项
sTable_Entity = 'Sys_Entity'; //字典实体
sTable_DictItem = 'Sys_DataDict'; //字典明细
sTable_SysDict = 'Sys_Dict'; //系统字典
sTable_ExtInfo = 'Sys_ExtInfo'; //附加信息
sTable_SysLog = 'Sys_EventLog'; //系统日志
sTable_SyncItem = 'Sys_SyncItem'; //同步临时表
sTable_BaseInfo = 'Sys_BaseInfo'; //基础信息
sTable_MemberType = 'Sys_MemberType'; //会员类型
sTable_Member = 'Sys_Member'; //会员
sTable_MemberExt = 'Sys_MemberExt'; //会员扩展
sTable_BeautiType = 'Sys_BeautiType'; //美容师类型
sTable_Remind = 'Sys_Remind'; //提醒服务
sTable_Beautician = 'Sys_Beautician'; //美容师
sTable_BeauticianExt= 'Sys_BeauticianExt'; //相关证书
sTable_ProductType = 'Sys_ProductType'; //产品分类
sTable_Plant = 'Sys_Plant'; //生产厂
sTable_Product = 'Sys_Product'; //产品
sTable_SkinType = 'Sys_SkinType'; //皮肤状况
sTable_Plan = 'Sys_Plan'; //方案
sTable_PlanExt = 'Sys_PlanExt'; //方案扩展
sTable_Provider = 'Sys_Provider'; //供应商
sTable_Hardware = 'Sys_Hardware'; //硬件信息
sTable_PlanUsed = 'Sys_PlanUsed'; //方案采用
sTable_ProductUsed = 'Sys_ProductUsed'; //产品使用
sTable_PickImage = 'Sys_PickImage'; //采集图像
sTable_PlanReport = 'Sys_PlanReport'; //方案报告
sTable_JiFenRule = 'Sys_JiFenRule'; //积分规则
sTable_JiFen = 'Sys_JiFen'; //积分表
sTable_TuPu = 'Sys_TuPu'; //皮肤图谱
{*新建表*}
sSQL_NewSysDict = 'Create Table $Table(D_ID $Inc, D_Name varChar(15),' +
'D_Desc varChar(30), D_Value varChar(50), D_Memo varChar(20),' +
'D_ParamA $Float, D_ParamB varChar(50), D_Index Integer Default 0)';
{-----------------------------------------------------------------------------
系统字典: SysDict
*.D_ID: 编号
*.D_Name: 名称
*.D_Desc: 描述
*.D_Value: 取值
*.D_Memo: 相关信息
-----------------------------------------------------------------------------}
sSQL_NewExtInfo = 'Create Table $Table(I_ID $Inc, I_Group varChar(20),' +
'I_ItemID varChar(20), I_Item varChar(30), I_Info varChar(500),' +
'I_ParamA $Float, I_ParamB varChar(50), I_Index Integer Default 0)';
{-----------------------------------------------------------------------------
扩展信息表: ExtInfo
*.I_ID: 编号
*.I_Group: 信息分组
*.I_ItemID: 信息标识
*.I_Item: 信息项
*.I_Info: 信息内容
*.I_ParamA: 浮点参数
*.I_ParamB: 字符参数
*.I_Memo: 备注信息
*.I_Index: 显示索引
-----------------------------------------------------------------------------}
sSQL_NewSysLog = 'Create Table $Table(L_ID $Inc, L_Date DateTime,' +
'L_Man varChar(32),L_Group varChar(20), L_ItemID varChar(20),' +
'L_KeyID varChar(20), L_Event varChar(50))';
{-----------------------------------------------------------------------------
系统日志: SysLog
*.L_ID: 编号
*.L_Date: 操作日期
*.L_Man: 操作人
*.L_Group: 信息分组
*.L_ItemID: 信息标识
*.L_KeyID: 辅助标识
*.L_Event: 事件
-----------------------------------------------------------------------------}
sSQL_NewSyncItem = 'Create Table $Table(S_ID $Inc, S_Table varChar(50),' +
'S_Field varChar(50), S_Value varChar(50), S_ExtField varChar(50),' +
'S_ExtValue varChar(50))';
{-----------------------------------------------------------------------------
同步临时表: SyncItem
*.S_Table: 表名
*.S_Field: 字段
*.S_Value: 字段值
*.S_ExtField: 扩展字段
*.S_ExtValue: 扩展值
-----------------------------------------------------------------------------}
sSQL_NewBaseInfo = 'Create Table $Table(B_ID $Inc, B_Group varChar(15),' +
'B_Text varChar(50), B_Py varChar(25), B_Memo varChar(25),' +
'B_PID Integer, B_Index Float)';
{-----------------------------------------------------------------------------
基本信息表: BaseInfo
*.B_ID: 编号
*.B_Group: 分组
*.B_Text: 内容
*.B_Py: 拼音简写
*.B_Memo: 备注信息
*.B_PID: 上级节点
*.B_Index: 创建顺序
-----------------------------------------------------------------------------}
sSQL_NewMemberType = 'Create Table $Table(T_ID $Inc, T_Name varChar(20),' +
'T_Memo varChar(50))';
{-----------------------------------------------------------------------------
会员类型: MemberType
*.T_ID: 编号
*.T_Name: 名称
*.T_Memo: 备注
-----------------------------------------------------------------------------}
sSQL_NewBeautiType = 'Create Table $Table(T_ID $Inc, T_Name varChar(20),' +
'T_Memo varChar(50))';
{-----------------------------------------------------------------------------
美容师类型: BeautiType
*.T_ID: 编号
*.T_Name: 名称
*.T_Memo: 备注
-----------------------------------------------------------------------------}
sSQL_NewMember = 'Create Table $Table(M_ID varChar(15), M_Name varChar(30),' +
'M_Type varChar(20), M_Sex Char(1), M_Age Integer,' +
'M_BirthDay varChar(10), M_Height $Float,M_Weight $Float, ' +
'M_Phone varChar(20), M_Beautician varChar(15),M_CDate DateTime,' +
'M_Addr varChar(50), M_Memo varChar(50), M_Image $Image)';
{-----------------------------------------------------------------------------
会员类型: Member
*.M_ID: 编号
*.M_Name: 名称
*.M_Type: 类别
*.M_Sex: 性别
*.M_Age: 年龄
*.M_BirthDay: 生日
*.M_Height: 身高
*.M_Weight: 体重
*.M_Phone: 联系方式
*.M_Beautician: 美容师
*.M_CDate: 建档日期
*.M_Addr: 地址
*.M_Memo: 备注
*.M_Image: 头像
-----------------------------------------------------------------------------}
sSQL_NewMemberExt = 'Create Table $Table(E_ID $Inc, E_FID varChar(15),' +
'E_Relation varChar(20), E_BID varChar(15))';
{-----------------------------------------------------------------------------
会员类型: Member
*.E_ID: 编号
*.E_FID: 前置会员号,主动关系(Front Member)
*.E_Relation: 关系名
*.E_BID: 后置会员名,被动关系(Back Member)
-----------------------------------------------------------------------------}
sSQL_NewRemin = 'Create Table $Table(R_ID $Inc, R_Date DateTime,' +
'R_Title varChar(50), R_Type varChar(32), R_Memo varChar(200))';
{-----------------------------------------------------------------------------
提醒服务: Remin
*.R_ID: 编号
*.R_Date: 日期
*.R_Title: 标题
*.R_Type: 类型
*.R_Memo: 内容
-----------------------------------------------------------------------------}
sSQL_NewBeautician = 'Create Table $Table(B_ID varChar(15), B_Name varChar(32),' +
'B_Sex Char(1), B_Age Integer, B_Birthday varChar(10),B_Phone varChar(20),' +
'B_Level varChar(20), B_Memo varChar(50), B_Image $Image)';
{-----------------------------------------------------------------------------
美容师: Beautician
*.B_ID: 编号
*.B_Name: 姓名
*.B_Sex: 性别
*.B_Age: 年龄
*.B_Birthday: 生日
*.B_Phone: 联系方式
*.B_Level: 级别
*.B_Memo: 备注
*.B_Image: 照片
-----------------------------------------------------------------------------}
sSQL_NewBeauticianExt = 'Create Table $Table(E_ID $Inc, E_BID varChar(15),' +
'E_Title Char(1), E_Memo varChar(50), E_Image $Image)';
{-----------------------------------------------------------------------------
美容师证件: BeauticianExt
*.E_ID: 编号
*.E_BID: 美容师编号
*.E_Title: 标题
*.E_Memo: 备注
*.E_Image: 图像
-----------------------------------------------------------------------------}
sSQL_NewProductType = 'Create Table $Table(P_ID $Inc, P_Name varChar(32),' +
'P_Py varChar(16), P_Memo varChar(50), P_PID Integer, P_Index Integer)';
{-----------------------------------------------------------------------------
产品类别: ProductType
*.P_ID: 编号
*.P_Name: 名称
*.P_Py: 拼音
*.P_Memo: 备注
*.P_PID: 上级
*.P_Index: 索引
-----------------------------------------------------------------------------}
sSQL_NewPlant = 'Create Table $Table(P_ID varChar(15), P_Name varChar(32),' +
'P_Addr varChar(50), P_Phone varChar(20), P_Memo varChar(50),' +
'P_Image $Image)';
{-----------------------------------------------------------------------------
生产厂商: Plant
*.P_ID: 编号
*.P_Name: 名称
*.P_Addr: 地址
*.P_Phone: 联系方式
*.P_Memo: 备注
*.P_Image: 商标
-----------------------------------------------------------------------------}
sSQL_NewProvider = 'Create Table $Table(P_ID varChar(15), P_Name varChar(32),' +
'P_Addr varChar(50), P_Phone varChar(20), P_Memo varChar(50),' +
'P_Image $Image)';
{-----------------------------------------------------------------------------
供应商: Privider
*.P_ID: 编号
*.P_Name: 名称
*.P_Addr: 地址
*.P_Phone: 联系方式
*.P_Memo: 备注
*.P_Image: 商标
-----------------------------------------------------------------------------}
sSQL_NewProduct = 'Create Table $Table(P_ID varChar(15), P_Name varChar(32),' +
'P_Type Integer, P_Plant varChar(15), P_Provider varChar(15),' +
'P_Price $Float, P_Memo varChar(50), P_Image $Image)';
{-----------------------------------------------------------------------------
产品: Product
*.P_ID: 编号
*.P_Name: 品名
*.P_Type: 类别
*.P_Plant: 厂商
*.P_Provider: 供应商
*.P_Price: 价格
*.P_Memo: 备注
*.P_Image: 图像
-----------------------------------------------------------------------------}
sSQL_NewProductUsed = 'Create Table $Table(U_ID $Inc, U_PID varChar(15),' +
'U_MID varChar(15), U_BID varChar(15), U_Date DateTime)';
{-----------------------------------------------------------------------------
产品: ProductUsed
*.U_ID: 编号
*.U_PID: 产品编号
*.U_MID: 会员编号
*.U_BID: 美容师编号
*.U_Date: 推荐日期
-----------------------------------------------------------------------------}
sSQL_NewSkinType = 'Create Table $Table(T_ID varChar(15), T_Name varChar(32),' +
'T_Part Integer, T_Memo varChar(50), T_MID varChar(15),' +
'T_BID varChar(15), T_Date DateTime, T_Image $Image)';
{-----------------------------------------------------------------------------
皮肤类型: SkinType
*.T_ID: 编号
*.T_Name: 名称
*.T_Part: 部位
*.T_MID: 会员
*.T_BID: 美容师
*.T_Date: 日期
*.T_Memo: 备注
*.T_Image: 图像
-----------------------------------------------------------------------------}
sSQL_NewPlan = 'Create Table $Table(P_ID varChar(15), P_Name varChar(32),' +
'P_PlanType Integer, P_SkinType varChar(15), P_Memo varChar(50),' +
'P_MID varChar(15), P_Man varChar(32), P_Date varChar(20))';
{-----------------------------------------------------------------------------
方案: Plan
*.P_ID: 编号
*.P_Name: 名称
*.P_PlanType: 方案分类
*.P_SkinType: 皮肤类型
*.P_MID: 会员编号
*.P_Man: 创建人
*.P_Date: 创建日期
*.P_Memo: 备注
-----------------------------------------------------------------------------}
sSQL_NewPlanExt = 'Create Table $Table(E_ID $Inc, E_Plan varChar(15),' +
'E_Skin varChar(32), E_Product varChar(15), E_Memo varChar(255),' +
'E_Index Integer Default 0)';
{-----------------------------------------------------------------------------
扩展信息表: ExtInfo
*.E_ID: 编号
*.E_Plan: 方案
*.E_Skin: 皮肤特征
*.E_Product: 产品
*.E_Memo: 备注信息
*.E_Index: 显示索引
-----------------------------------------------------------------------------}
sSQL_NewPlanReport = 'Create Table $Table(R_ID $Inc, R_PID varChar(15),' +
'R_Skin varChar(250), R_Plan varChar(250), R_Memo varchar(250), R_Date DateTime)';
{-----------------------------------------------------------------------------
报告记录: PlanReport
*.R_ID: 编号
*.R_PID: 方案编号
*.R_Skin: 皮肤特征
*.R_Plan: 方案
*.R_Memo: 描述
*.R_Date: 日期
-----------------------------------------------------------------------------}
sSQL_NewPlanUsed = 'Create Table $Table(U_ID $Inc, U_PID varChar(15),' +
'U_MID varChar(15), U_BID varChar(15), U_Date DateTime)';
{-----------------------------------------------------------------------------
方案采用表: PlanUsed
*.U_ID: 编号
*.U_PID: 方案编号
*.U_MID: 会员编号
*.U_BID: 美容师编号
*.U_Date: 采用时间
-----------------------------------------------------------------------------}
sSQL_NewHardware = 'Create Table $Table(H_ID varChar(15), H_Dev varChar(100),' +
'H_Size varChar(100))';
{-----------------------------------------------------------------------------
硬件信息表: Hardware
*.H_ID: 编号
*.H_Dev: 设备名
*.H_Size: 画面比例
-----------------------------------------------------------------------------}
sSQL_NewPickImage = 'Create Table $Table(P_ID $Inc, P_MID varChar(15),' +
'P_Part Integer, P_Date DateTime, P_Desc varChar(50), P_Image $Image)';
{-----------------------------------------------------------------------------
图像采集表: PicImage
*.P_ID: 编号
*.P_MID: 会员编号
*.P_Part: 采集部位
*.P_Date: 采集时间
*.P_Desc: 描述信息
*.P_Image: 图像
-----------------------------------------------------------------------------}
sSQL_NewJiFenRule = 'Create Table $Table(R_ID $Inc, R_Money $Float,' +
'R_JiFen $Float)';
{-----------------------------------------------------------------------------
积分规则表: JiFenRule
*.R_ID: 编号
*.R_Money: 消费金额
*.R_JiFen: 积分
-----------------------------------------------------------------------------}
sSQL_NewJiFen = 'Create Table $Table(F_ID $Inc, F_MID varChar(15),' +
'F_Product varChar(50), F_Money $Float, F_Rule $Float, F_JiFen $Float,' +
'F_Date DateTime)';
{-----------------------------------------------------------------------------
积分表: JiFen
*.F_ID: 编号
*.F_MID: 会员编号
*.F_Product: 产品名称
*.F_Money: 消费金额
*.F_Rule: 积分标准
*.F_JiFen: 积分
*.F_Date: 消费日期
-----------------------------------------------------------------------------}
sSQL_NewTuPu = 'Create Table $Table(T_ID $Inc, T_LevelA varChar(50),' +
'T_PYA varChar(50), T_LevelB varChar(50), T_PYB varChar(50),' +
'T_TuPu $Image, T_Small $Image, T_Memo varChar(50),' +
'T_Man varChar(32), T_Date DateTime)';
{-----------------------------------------------------------------------------
图谱表: TuPu
*.T_ID: 编号
*.T_LevelA: 一级标识
*.T_LevelB: 二级标识
*.T_PYA,T_PYB: 拼音
*.T_TuPu: 图谱
*.T_Small: 微缩图谱
*.T_Memo: 备注
*.T_Man: 操作人
*.T_Date: 操作日期
-----------------------------------------------------------------------------}
//------------------------------------------------------------------------------
// 数据查询
//------------------------------------------------------------------------------
sQuery_SysDict = 'Select D_ID, D_Value, D_Memo From $Table ' +
'Where D_Name=''$Name'' Order By D_Index Desc';
{-----------------------------------------------------------------------------
从数据字典读取数据
*.$Table: 数据字典表
*.$Name: 字典项名称
-----------------------------------------------------------------------------}
sQuery_ExtInfo = 'Select I_ID, I_Item, I_Info From $Table Where ' +
'I_Group=''$Group'' and I_ItemID=''$ID'' Order By I_Index Desc';
{-----------------------------------------------------------------------------
从扩展信息表读取数据
*.$Table: 扩展信息表
*.$Group: 分组名称
*.$ID: 信息标识
-----------------------------------------------------------------------------}
implementation
//------------------------------------------------------------------------------
//Desc: 添加系统表项
procedure AddSysTableItem(const nTable,nNewSQL: string);
var nP: PSysTableItem;
begin
New(nP);
gSysTableList.Add(nP);
nP.FTable := nTable;
nP.FNewSQL := nNewSQL;
end;
//Desc: 系统表数组
procedure InitSysTableList;
begin
gSysTableList := TList.Create;
AddSysTableItem(sTable_SysDict, sSQL_NewSysDict);
AddSysTableItem(sTable_ExtInfo, sSQL_NewExtInfo);
AddSysTableItem(sTable_SysLog, sSQL_NewSysLog);
AddSysTableItem(sTable_SyncItem, sSQL_NewSyncItem);
AddSysTableItem(sTable_BaseInfo, sSQL_NewBaseInfo);
AddSysTableItem(sTable_MemberType, sSQL_NewMemberType);
AddSysTableItem(sTable_ExtInfo, sSQL_NewExtInfo);
AddSysTableItem(sTable_BeautiType, sSQL_NewBeautiType);
AddSysTableItem(sTable_Member, sSQL_NewMember);
AddSysTableItem(sTable_MemberExt, sSQL_NewMemberExt);
AddSysTableItem(sTable_Remind, sSQL_NewRemin);
AddSysTableItem(sTable_Beautician, sSQL_NewBeautician);
AddSysTableItem(sTable_BeauticianExt, sSQL_NewBeauticianExt);
AddSysTableItem(sTable_ProductType, sSQL_NewProductType);
AddSysTableItem(sTable_Plant, sSQL_NewPlant);
AddSysTableItem(sTable_Provider, sSQL_NewProvider);
AddSysTableItem(sTable_Product, sSQL_NewProduct);
AddSysTableItem(sTable_SkinType, sSQL_NewSkinType);
AddSysTableItem(sTable_Plan, sSQL_NewPlan);
AddSysTableItem(sTable_PlanExt, sSQL_NewPlanExt);
AddSysTableItem(sTable_Hardware, sSQL_NewHardware);
AddSysTableItem(sTable_PlanUsed, sSQL_NewPlanUsed);
AddSysTableItem(sTable_ProductUsed, sSQL_NewProductUsed);
AddSysTableItem(sTable_PickImage, sSQL_NewPickImage);
AddSysTableItem(sTable_PlanReport, sSQL_NewPlanReport);
AddSysTableItem(sTable_JiFenRule, sSQL_NewJiFenRule);
AddSysTableItem(sTable_JiFen, sSQL_NewJiFen);
AddSysTableItem(sTable_TuPu, sSQL_NewTuPu);
end;
//Desc: 清理系统表
procedure ClearSysTableList;
var nIdx: integer;
begin
for nIdx:= gSysTableList.Count - 1 downto 0 do
begin
Dispose(PSysTableItem(gSysTableList[nIdx]));
gSysTableList.Delete(nIdx);
end;
FreeAndNil(gSysTableList);
end;
initialization
InitSysTableList;
finalization
ClearSysTableList;
end.
|
unit Form;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Rtti,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
EvalLib;
type
TEvalForm = class(TForm)
ExpressionLabel: TLabel;
ExpressionEdit: TComboBox;
Label2: TLabel;
OutputMemo: TMemo;
EvalButton: TButton;
ClearButton: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure EvalButtonClick(Sender: TObject);
procedure ClearButtonClick(Sender: TObject);
private
Evaluator: TEvaluator;
Variables: TVariableStore;
ClassFactory: TClassFactory;
public
{ Public declarations }
end;
var
EvalForm: TEvalForm;
implementation
{$R *.dfm}
procedure TEvalForm.FormCreate(Sender: TObject);
begin
Evaluator := TEvaluator.Create;
Variables := TVariableStore.Create;
Variables.AutoDeclare := True;
Variables.Declare('Window', TObject(Self));
Variables.Declare('Globals', TObject(Variables));
Variables.Declare('True', True);
Variables.Declare('False', False);
Evaluator.Push(Variables);
ClassFactory := TClassFactory.Create;
Evaluator.Declare('ClassFactory', ClassFactory);
end;
procedure TEvalForm.FormDestroy(Sender: TObject);
begin
{}
end;
procedure TEvalForm.FormActivate(Sender: TObject);
begin
ExpressionEdit.SetFocus;
end;
procedure TEvalForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
if not ExpressionEdit.Focused then
begin
ExpressionEdit.SetFocus;
ExpressionEdit.SelText := Key;
end;
end;
procedure TEvalForm.EvalButtonClick(Sender: TObject);
var
ResultValue: TValue;
ResultString: String;
begin
ExpressionEdit.SelectAll;
try
ResultValue := Evaluator.Eval(ExpressionEdit.Text);
ResultString := ExpressionEdit.Text + ': ' + ResultValue.HumanReadable;
if Length(ResultString) > 0 then
Variables.Declare('Result', ResultValue);
except on E:Exception do
ResultString := E.ToString;
end;
if Length(ResultString) > 0 then
OutputMemo.Lines.Add(ResultString);
OutputMemo.SelStart := Length(OutputMemo.Lines.Text);
end;
procedure TEvalForm.ClearButtonClick(Sender: TObject);
begin
OutputMemo.Lines.Clear;
end;
end.
|
unit Percent;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, EditableObjects, Editors;
type
TPercentEditor =
class(TInPlaceVisualControl)
tbValue: TTrackBar;
procedure tbValueChange(Sender: TObject);
public
procedure UpdateObject; override;
protected
procedure setEditableObject( aEditableObject : TEditableObject; options : integer ); override;
end;
implementation
{$R *.DFM}
procedure TPercentEditor.UpdateObject;
begin
EditableObject.Value := FloatToStr( tbValue.Position/100 );
end;
procedure TPercentEditor.setEditableObject( aEditableObject : TEditableObject; options : integer );
begin
inherited;
try
tbValue.Position := trunc(100*StrToFloat(EditableObject.Value));
except
tbValue.Position := 50;
end;
tbValue.Hint := IntToStr(tbValue.Position) + '%';
end;
procedure TPercentEditor.tbValueChange(Sender: TObject);
begin
tbValue.Hint := IntToStr(tbValue.Position) + '%';
UpdateObject;
end;
end.
|
unit SendEmail;
interface
uses SysUtils, Classes, OverbyteIcsWSocket, OverbyteIcsSmtpProt;
type
TEmailClient = class(TComponent)
private
fSslContext: TSslContext;
fSslSmtpClient: TSslSmtpCli;
FAllInOneFlag: Boolean;
FEhloCount: Integer;
FAnswer: String;
FSmtpHost: string;
FSmtpPort: String;
FSmtpLogin: string;
FSmtpPassword: string;
FFromEmail: string;
FToEmail: string;
FCcEmail: string;
FSubject: string;
FBody: string;
FAttachments: TStrings;
FConfirm: Boolean;
FSmtpAuthType: TSmtpAuthType;
FSslType: TSmtpSslType;
FFinish: Boolean;
procedure SslSmtpClientBeforeFileOpen(Sender: TObject; Idx: Integer; FileName: String;
var Action: TSmtpBeforeOpenFileAction);
procedure SslSmtpClientRequestDone(Sender: TObject; RqType: TSmtpRequest; Error: Word);
procedure SetAnswer(const text: string);
procedure SetAuthType(const Value: string);
procedure SetSslType(const Value: string);
public
property SmtpHost: string read FSmtpHost write FSmtpHost;
property SmtpPort: String read FSmtpPort write FSmtpPort;
property SmtpLogin: string read FSmtpLogin write FSmtpLogin;
property SmtpPassword: string read FSmtpPassword write FSmtpPassword;
property FromEmail: string read FFromEmail write FFromEmail;
property CcEmail: string read FCcEmail write FCcEmail;
property ToEmail: string read FToEmail write FToEmail;
property Confirm: Boolean read FConfirm write FConfirm;
property AuthType: string write SetAuthType;
property SslType: string write SetSslType;
property Subject: string read FSubject write FSubject;
property Body: string read FBody write FBody;
procedure AddAttachment(const FileName: String);
function SendEmail: String;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
constructor TEmailClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fSslContext := TSslContext.Create(self);
fSslSmtpClient := TSslSmtpCli.Create(self);
FAttachments := TStringList.Create;
with fSslContext do begin
Name := 'SslContext';
SslVerifyPeer := False;
SslVerifyDepth := 9;
SslVerifyFlags := [];
SslOptions := [sslOpt_NO_SSLv2];
SslVerifyPeerModes := [SslVerifyMode_PEER];
SslSessionCacheModes := [sslSESS_CACHE_CLIENT];
SslCipherList := 'ALL:!ADH:RC4+RSA:+SSLv2:@STRENGTH';
SslVersionMethod := sslV23_CLIENT;
SslECDHMethod := sslECDHNone;
SslSessionTimeout := 300000;
SslSessionCacheSize := 20480;
end;
with fSslSmtpClient do begin
Name := 'SslSmtpClient';
XMailer := 'A4ON.TV SMTP Client';
AuthType := smtpAuthPlain;
CharSet := 'utf-8';
DefaultEncoding := smtpEnc8bit;
Allow8bitChars := False;
ContentType := smtpPlainText;
OnRequestDone := SslSmtpClientRequestDone;
OnBeforeFileOpen := SslSmtpClientBeforeFileOpen;
SslContext := fSslContext;
end;
FAllInOneFlag := True;
FConfirm := False;
FCcEmail := '';
FSmtpAuthType := smtpAuthPlain;
FSslType := smtpTlsImplicit;
end;
destructor TEmailClient.Destroy;
begin
FreeAndNil(fSslContext);
FreeAndNil(fSslSmtpClient);
FreeAndNil(FAttachments);
inherited;
end;
procedure TEmailClient.SslSmtpClientBeforeFileOpen(Sender: TObject; Idx: Integer; FileName: String;
var Action: TSmtpBeforeOpenFileAction);
begin
Action := smtpBeforeOpenFileNone;
end;
procedure TEmailClient.SetAuthType(const Value: string);
begin
if Value = 'Plain'
then FSmtpAuthType := smtpAuthPlain
else if Value = 'Login'
then FSmtpAuthType := smtpAuthLogin
else if Value = 'CramMD5'
then FSmtpAuthType := smtpAuthCramMD5
else if Value = 'CramSHA1'
then FSmtpAuthType := smtpAuthCramSha1
else if Value = 'NTLM'
then FSmtpAuthType := smtpAuthNtlm
else if Value = 'AutoSelect'
then FSmtpAuthType := smtpAuthAutoSelect
else FSmtpAuthType := smtpAuthNone;
end;
procedure TEmailClient.SetSslType(const Value: string);
begin
if Value = 'TLS'
then FSslType := smtpTlsImplicit
else if Value = 'STARTTLS'
then FSslType := smtpTlsExplicit
else FSslType := smtpTlsNone;
end;
procedure TEmailClient.SslSmtpClientRequestDone(Sender: TObject; RqType: TSmtpRequest; Error: Word);
begin
{ For every operation, we display the status }
if (Error > 0) and (Error < 10000)
then SetAnswer('RequestDone Rq=' + IntToStr(Ord(RqType)) + ' Error=' + fSslSmtpClient.ErrorMessage);
{ Check if the user has asked for "All-In-One" demo }
if not FAllInOneFlag
then begin
fSslSmtpClient.PostQuitMessage;
Exit;
end;
if Error <> 0
then begin
FAllInOneFlag := False; { Terminate All-In-One demo }
FFinish := True;
fSslSmtpClient.PostQuitMessage;
Exit;
end;
case RqType of
smtpConnect: begin
if fSslSmtpClient.AuthType = smtpAuthNone
then fSslSmtpClient.Helo
else fSslSmtpClient.Ehlo;
end;
smtpHelo: fSslSmtpClient.MailFrom;
smtpEhlo: if fSslSmtpClient.SslType = smtpTlsExplicit then begin
Inc(FEhloCount);
if FEhloCount = 1
then fSslSmtpClient.StartTls
else if FEhloCount > 1
then fSslSmtpClient.Auth;
end
else fSslSmtpClient.Auth;
smtpStartTls: fSslSmtpClient.Ehlo; // We need to re-issue the Ehlo command
smtpAuth: fSslSmtpClient.MailFrom;
smtpMailFrom: fSslSmtpClient.RcptTo;
smtpRcptTo: fSslSmtpClient.Data;
smtpData: fSslSmtpClient.Quit;
smtpQuit: begin
FFinish := True;
SetAnswer('OK');
end;
end;
if FFinish
then fSslSmtpClient.PostQuitMessage;
end;
procedure TEmailClient.SetAnswer(const text: string);
begin
FAnswer := text;
end;
procedure TEmailClient.AddAttachment(const FileName: String);
begin
if FileName <> ''
then FAttachments.Add(FileName);
end;
function TEmailClient.SendEmail: String;
begin
if fSslSmtpClient.Connected
then begin
Result := 'Connected';
Exit;
end;
FAnswer := '';
FAllInOneFlag := True;
FFinish := False;
FEhloCount := 0;
{ Initialize all SMTP component properties from our GUI }
fSslSmtpClient.Host := FSmtpHost;
fSslSmtpClient.Port := FSmtpPort;
fSslSmtpClient.FromName := FFromEmail;
fSslSmtpClient.HdrFrom := FFromEmail;
//fSslSmtpClient.HdrTo := ToEmail;
if FCcEmail <> '' then
fSslSmtpClient.HdrCc := FCcEmail;
fSslSmtpClient.HdrSubject := FSubject;
fSslSmtpClient.EmailFiles := FAttachments;
fSslSmtpClient.ConfirmReceipt := FConfirm;
fSslSmtpClient.AuthType := FSmtpAuthType;
fSslSmtpClient.ContentType := smtpPlainText;
fSslSmtpClient.MailMessage.Clear;
fSslSmtpClient.MailMessage.Add(FBody);
fSslSmtpClient.SslType := FSslType;
if fSslSmtpClient.SslType <> smtpTlsNone
then begin
fSslContext.SslVerifyPeer := False;
fSslSmtpClient.OnSslVerifyPeer := nil;
fSslSmtpClient.OnSslHandshakeDone := nil;
end;
fSslSmtpClient.Username := FSmtpLogin;
fSslSmtpClient.Password := FSmtpPassword;
fSslSmtpClient.HdrPriority := TSmtpPriority(0);
{ Recipient list is computed from To, Cc and Bcc fields }
fSslSmtpClient.RcptName.Clear;
fSslSmtpClient.RcptName.Delimiter := ',';
if FCcEmail <> '' then
fSslSmtpClient.RcptName.CommaText := FCcEmail+','+ToEmail.Trim
else
fSslSmtpClient.RcptName.CommaText := ToEmail.Trim;
fSslSmtpClient.HdrTo := ToEmail.Trim;
fSslSmtpClient.Connect;
fSslSmtpClient.MessageLoop;
FAttachments.Clear;
Result := FAnswer;
end;
end.
|
unit WeightScaleForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Ani, FMX.StdCtrls, System.Bluetooth, FMX.Layouts,
FMX.Memo, FMX.Controls.Presentation, FMX.Edit, FMX.Objects, IPPeerClient, IPPeerServer,
System.Tether.Manager, System.Bluetooth.Components;
type
TSensorContactStatus = (NonSupported, NonDetected, Detected);
THRMFlags = record
HRValue16bits: boolean;
SensorContactStatus: TSensorContactStatus;
EnergyExpended: boolean;
RRInterval: boolean;
end;
TfrmWeightMonitor = class(TForm)
btnConnect: TButton;
lblDevice: TLabel;
pnlMain: TPanel;
pnlLog: TPanel;
Splitter1: TSplitter;
Memo1: TMemo;
lblWeight: TLabel;
BluetoothLE1: TBluetoothLE;
btnDisconnect: TButton;
procedure btnConnectClick(Sender: TObject);
procedure BluetoothLE1EndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList);
procedure BluetoothLE1CharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic;
AGattStatus: TBluetoothGattStatus);
procedure btnDisconnectClick(Sender: TObject);
private
{ Private declarations }
FBLEDevice: TBluetoothLEDevice;
FWeightGattService: TBluetoothGattService;
FWeightMeasurementGattCharacteristic: TBluetoothGattCharacteristic;
procedure GetServiceAndCharacteristics;
public
{ Public declarations }
end;
const
ScaleDeviceName = 'Wahoo Scale';
ServiceUUID = '';
CharactUUID = '';
// 0x1901 is the weight service
// 0x2B01 is the live weight characteristic readings 0x84ae0000 0001 - 38 lbs 17kg
// 0b 10000100101011100000000000000000
Weight_Device: TBluetoothUUID = '{00001901-0000-1000-8000-00805F9B34FB}';
Weight_Service: TBluetoothUUID = '{00001901-0000-1000-8000-00805F9B34FB}';
Weight_Characteristic: TBluetoothUUID = '{00002B01-0000-1000-8000-00805F9B34FB}';
var
frmWeightMonitor: TfrmWeightMonitor;
implementation
{$R *.fmx}
{$R *.iPad.fmx IOS}
{$R *.iPhone.fmx IOS}
procedure TfrmWeightMonitor.btnConnectClick(Sender: TObject);
begin
lblWeight.Text := 'Weight: 0.0';
lblDevice.Text := '';
Memo1.Lines.Clear;
BluetoothLE1.DiscoverDevices(3500, [Weight_Device]);
end;
procedure TfrmWeightMonitor.btnDisconnectClick(Sender: TObject);
begin
if FWeightMeasurementGattCharacteristic <> nil then
BluetoothLE1.UnSubscribeToCharacteristic(FBLEDevice, FWeightMeasurementGattCharacteristic);
btnDisconnect.Enabled := false; // disable disconnect from subscribe scale button
btnConnect.Enabled := true; // enable connect to scale button
end;
procedure TfrmWeightMonitor.BluetoothLE1EndDiscoverDevices(const Sender: TObject;
const ADeviceList: TBluetoothLEDeviceList);
var
I: Integer;
begin
// log
Memo1.Lines.Add(ADeviceList.Count.ToString + ' devices discovered:');
for I := 0 to ADeviceList.Count - 1 do Memo1.Lines.Add(ADeviceList[I].DeviceName);
if BluetoothLE1.DiscoveredDevices.Count > 0 then
begin
FBLEDevice := BluetoothLE1.DiscoveredDevices.First; //assume first is the scale
lblDevice.Text := ScaleDeviceName;
if BluetoothLE1.GetServices(FBLEDevice).Count = 0 then
begin
Memo1.Lines.Add('No Weight services found!');
lblWeight.Text := 'No Weight services found!';
end
else begin
Memo1.Lines.Add('Wahoo Services Found: '+ IntToStr(BluetoothLE1.GetServices(FBLEDevice).Count));
btnDisconnect.Enabled := true; // enable disconnect button - from subscribe scale
btnConnect.Enabled := false; //disable button - connect to scale
// get Weight Service and Characteristic
GetServiceAndCharacteristics;
end;
end
else
lblDevice.Text := 'Weight Device not found';
end;
procedure TfrmWeightMonitor.GetServiceAndCharacteristics;
{
var
I, J, K: Integer;
}
begin
{
for I := 0 to FBLEDevice.Services.Count - 1 do
begin
Memo1.Lines.Add(FBLEDevice.Services[I].UUIDName + ' : ' + FBLEDevice.Services[I].UUID.ToString);
for J := 0 to FBLEDevice.Services[I].Characteristics.Count - 1 do begin
Memo1.Lines.Add('--> ' + FBLEDevice.Services[I].Characteristics[J].UUIDName + ' : ' +
FBLEDevice.Services[I].Characteristics[J].UUID.ToString);
for K := 0 to FBLEDevice.Services[I].Characteristics[J].Descriptors.Count - 1 do begin
Memo1.Lines.Add('----> ' + FBLEDevice.Services[I].Characteristics[J].Descriptors[K].UUIDName + ' : ' +
FBLEDevice.Services[I].Characteristics[J].Descriptors[K].UUID.ToString);
end;
end;
end;
}
FWeightGattService := nil;
FWeightMeasurementGattCharacteristic := nil;
// RTL source code says to call DiscoverServices
// first before GetServices, but not needed
// FBLEDevice.DiscoverServices();
// get Weight Service by UUID
FWeightGattService := BluetoothLE1.GetService(FBLEDevice, Weight_SERVICE);
if FWeightGattService <> nil then begin
memo1.Lines.Add('Service: '+FWeightGattService.UUID.ToString);
// get Weight Characteristic
Memo1.Lines.Add('Looking Char: '+Weight_CHARACTERISTIC.ToString);
BluetoothLE1.GetCharacteristics(FWeightGattService);
FWeightMeasurementGattCharacteristic := BluetoothLE1.GetCharacteristic(FWeightGattService,Weight_CHARACTERISTIC);
if FWeightMeasurementGattCharacteristic <> nil then begin
Memo1.Lines.Add('Char: '+FWeightMeasurementGattCharacteristic.UUID.ToString);
// subscribe to the weight service
// FBLEDevice.SetCharacteristicNotification(FWeightMeasurementGattCharact, True);
BluetoothLE1.SubscribeToCharacteristic(FBLEDevice, FWeightMeasurementGattCharacteristic);
Memo1.Lines.Add('Subscribed to Weight Measurement Characteristic');
end
else begin
Memo1.Lines.Add('Weight Char not found');
lblWeight.Text := 'Weight Char not found';
end
end
else begin
Memo1.Lines.Add('Weight Service not found');
lblWeight.Text := 'Weight Service not found';
end;
end;
procedure TfrmWeightMonitor.BluetoothLE1CharacteristicRead(const Sender: TObject;
const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus);
var
LSValue: string;
WeightPounds : double;
begin
if AGattStatus <> TBluetoothGattStatus.Success then
Memo1.Lines.Add('Error reading Characteristic ' + ACharacteristic.UUIDName + ': ' + Ord(AGattStatus).ToString)
else
begin
LSValue := IntToStr(ACharacteristic.GetValueAsInteger);
Memo1.Lines.Add(ACharacteristic.UUID.ToString + ' String: ' + LSValue);
// calculate weight - characteristic is in hectograms
// ignore last two bytes, take first 6 bytes - that is hectograms
WeightPounds := (ACharacteristic.GetValueAsInteger shr 8) * 0.2205;
Memo1.Lines.Add('Weight (pounds): '+Format('%8.2f',[WeightPounds]));
lblWeight.Text := 'Weight: '+ Format('%8.2f',[WeightPounds]);
end;
end;
end.
|
unit CRCCALC;
//--------------------------------------------------------------------
// Модуль вычисления циклических контрольных сумм CRC8, CRC16 и CRC32
//--------------------------------------------------------------------
//CRC-CCITT-32 X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^4+X^2+X+1
//CRC-CCITT X^16+X^12+X^5+1
//CRC-8 X^8+x^2+X+1 ууу
interface
type
crc8_t = BYTE;
crc16_t = WORD;
crc32_t = LONGWORD;
function CalculateCRC8(const pData : pchar; dataLen : integer) : crc8_t;
function CalculateCRC16(const pData : pchar; dataLen : integer) : crc16_t;
function CalculateCRC32(const pData : pchar; dataLen : integer) : crc32_t;
const
crc32_table : array[0..255] of crc32_t =(
$00000000, $77073096, $ee0e612c, $990951ba, $076dc419, $706af48f, $e963a535, $9e6495a3,
$0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988, $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91,
$1db71064, $6ab020f2, $f3b97148, $84be41de, $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7,
$136c9856, $646ba8c0, $fd62f97a, $8a65c9ec, $14015c4f, $63066cd9, $fa0f3d63, $8d080df5,
$3b6e20c8, $4c69105e, $d56041e4, $a2677172, $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b,
$35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940, $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59,
$26d930ac, $51de003a, $c8d75180, $bfd06116, $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f,
$2802b89e, $5f058808, $c60cd9b2, $b10be924, $2f6f7c87, $58684c11, $c1611dab, $b6662d3d,
$76dc4190, $01db7106, $98d220bc, $efd5102a, $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433,
$7807c9a2, $0f00f934, $9609a88e, $e10e9818, $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01,
$6b6b51f4, $1c6c6162, $856530d8, $f262004e, $6c0695ed, $1b01a57b, $8208f4c1, $f50fc457,
$65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c, $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65,
$4db26158, $3ab551ce, $a3bc0074, $d4bb30e2, $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb,
$4369e96a, $346ed9fc, $ad678846, $da60b8d0, $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9,
$5005713c, $270241aa, $be0b1010, $c90c2086, $5768b525, $206f85b3, $b966d409, $ce61e49f,
$5edef90e, $29d9c998, $b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad,
$edb88320, $9abfb3b6, $03b6e20c, $74b1d29a, $ead54739, $9dd277af, $04db2615, $73dc1683,
$e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8, $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1,
$f00f9344, $8708a3d2, $1e01f268, $6906c2fe, $f762575d, $806567cb, $196c3671, $6e6b06e7,
$fed41b76, $89d32be0, $10da7a5a, $67dd4acc, $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5,
$d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b,
$d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55, $316e8eef, $4669be79,
$cb61b38c, $bc66831a, $256fd2a0, $5268e236, $cc0c7795, $bb0b4703, $220216b9, $5505262f,
$c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04, $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d,
$9b64c2b0, $ec63f226, $756aa39c, $026d930a, $9c0906a9, $eb0e363f, $72076785, $05005713,
$95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38, $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21,
$86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e, $81be16cd, $f6b9265b, $6fb077e1, $18b74777,
$88085ae6, $ff0f6a70, $66063bca, $11010b5c, $8f659eff, $f862ae69, $616bffd3, $166ccf45,
$a00ae278, $d70dd2ee, $4e048354, $3903b3c2, $a7672661, $d06016f7, $4969474d, $3e6e77db,
$aed16a4a, $d9d65adc, $40df0b66, $37d83bf0, $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9,
$bdbdf21c, $cabac28a, $53b39330, $24b4a3a6, $bad03605, $cdd70693, $54de5729, $23d967bf,
$b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94, $b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d
);
crc16_table : array[0..255] of crc16_t =(
$0000, $1021, $2042, $3063, $4084, $50A5, $60C6, $70E7,
$8108, $9129, $A14A, $B16B, $C18C, $D1AD, $E1CE, $F1EF,
$1231, $0210, $3273, $2252, $52B5, $4294, $72F7, $62D6,
$9339, $8318, $B37B, $A35A, $D3BD, $C39C, $F3FF, $E3DE,
$2462, $3443, $0420, $1401, $64E6, $74C7, $44A4, $5485,
$A56A, $B54B, $8528, $9509, $E5EE, $F5CF, $C5AC, $D58D,
$3653, $2672, $1611, $0630, $76D7, $66F6, $5695, $46B4,
$B75B, $A77A, $9719, $8738, $F7DF, $E7FE, $D79D, $C7BC,
$48C4, $58E5, $6886, $78A7, $0840, $1861, $2802, $3823,
$C9CC, $D9ED, $E98E, $F9AF, $8948, $9969, $A90A, $B92B,
$5AF5, $4AD4, $7AB7, $6A96, $1A71, $0A50, $3A33, $2A12,
$DBFD, $CBDC, $FBBF, $EB9E, $9B79, $8B58, $BB3B, $AB1A,
$6CA6, $7C87, $4CE4, $5CC5, $2C22, $3C03, $0C60, $1C41,
$EDAE, $FD8F, $CDEC, $DDCD, $AD2A, $BD0B, $8D68, $9D49,
$7E97, $6EB6, $5ED5, $4EF4, $3E13, $2E32, $1E51, $0E70,
$FF9F, $EFBE, $DFDD, $CFFC, $BF1B, $AF3A, $9F59, $8F78,
$9188, $81A9, $B1CA, $A1EB, $D10C, $C12D, $F14E, $E16F,
$1080, $00A1, $30C2, $20E3, $5004, $4025, $7046, $6067,
$83B9, $9398, $A3FB, $B3DA, $C33D, $D31C, $E37F, $F35E,
$02B1, $1290, $22F3, $32D2, $4235, $5214, $6277, $7256,
$B5EA, $A5CB, $95A8, $8589, $F56E, $E54F, $D52C, $C50D,
$34E2, $24C3, $14A0, $0481, $7466, $6447, $5424, $4405,
$A7DB, $B7FA, $8799, $97B8, $E75F, $F77E, $C71D, $D73C,
$26D3, $36F2, $0691, $16B0, $6657, $7676, $4615, $5634,
$D94C, $C96D, $F90E, $E92F, $99C8, $89E9, $B98A, $A9AB,
$5844, $4865, $7806, $6827, $18C0, $08E1, $3882, $28A3,
$CB7D, $DB5C, $EB3F, $FB1E, $8BF9, $9BD8, $ABBB, $BB9A,
$4A75, $5A54, $6A37, $7A16, $0AF1, $1AD0, $2AB3, $3A92,
$FD2E, $ED0F, $DD6C, $CD4D, $BDAA, $AD8B, $9DE8, $8DC9,
$7C26, $6C07, $5C64, $4C45, $3CA2, $2C83, $1CE0, $0CC1,
$EF1F, $FF3E, $CF5D, $DF7C, $AF9B, $BFBA, $8FD9, $9FF8,
$6E17, $7E36, $4E55, $5E74, $2E93, $3EB2, $0ED1, $1EF0
);
crc8_table : array[0..255] of crc8_t =(
$00, $5e, $bc, $e2, $61, $3f, $dd, $83,
$c2, $9c, $7e, $20, $a3, $fd, $1f, $41,
$9d, $c3, $21, $7f, $fc, $a2, $40, $1e,
$5f, $01, $e3, $bd, $3e, $60, $82, $dc,
$23, $7d, $9f, $c1, $42, $1c, $fe, $a0,
$e1, $bf, $5d, $03, $80, $de, $3c, $62,
$be, $e0, $02, $5c, $df, $81, $63, $3d,
$7c, $22, $c0, $9e, $1d, $43, $a1, $ff,
$46, $18, $fa, $a4, $27, $79, $9b, $c5,
$84, $da, $38, $66, $e5, $bb, $59, $07,
$db, $85, $67, $39, $ba, $e4, $06, $58,
$19, $47, $a5, $fb, $78, $26, $c4, $9a,
$65, $3b, $d9, $87, $04, $5a, $b8, $e6,
$a7, $f9, $1b, $45, $c6, $98, $7a, $24,
$f8, $a6, $44, $1a, $99, $c7, $25, $7b,
$3a, $64, $86, $d8, $5b, $05, $e7, $b9,
$8c, $d2, $30, $6e, $ed, $b3, $51, $0f,
$4e, $10, $f2, $ac, $2f, $71, $93, $cd,
$11, $4f, $ad, $f3, $70, $2e, $cc, $92,
$d3, $8d, $6f, $31, $b2, $ec, $0e, $50,
$af, $f1, $13, $4d, $ce, $90, $72, $2c,
$6d, $33, $d1, $8f, $0c, $52, $b0, $ee,
$32, $6c, $8e, $d0, $53, $0d, $ef, $b1,
$f0, $ae, $4c, $12, $91, $cf, $2d, $73,
$ca, $94, $76, $28, $ab, $f5, $17, $49,
$08, $56, $b4, $ea, $69, $37, $d5, $8b,
$57, $09, $eb, $b5, $36, $68, $8a, $d4,
$95, $cb, $29, $77, $f4, $aa, $48, $16,
$e9, $b7, $55, $0b, $88, $d6, $34, $6a,
$2b, $75, $97, $c9, $4a, $14, $f6, $a8,
$74, $2a, $c8, $96, $15, $4b, $a9, $f7,
$b6, $e8, $0a, $54, $d7, $89, $6b, $35
);
implementation
//========================================================================================
//------------------------------------------- Вычислить циклическую контрольную сумму CRC8
function CalculateCRC8(const pData : pchar; dataLen : integer) : crc8_t;
var
n : integer;
c : crc8_t;
begin
c := $ff;
for n := 0 to dataLen-1 do
c := crc8_table[ byte(pData[n]) xor c ];
result := c xor $ff;
end;
//========================================================================================
//------------------------------------------ Вычислить циклическую контрольную сумму CRC16
function CalculateCRC16(const pData : pchar; dataLen : integer) : crc16_t;
var
n : integer;
c,d,m : crc16_t;
p : byte;
r : char;
begin
c := $ffff;
for n := 0 to dataLen-1 do
begin
d := c shr 8;
r := pData[n];
p := byte(r) xor d;
m := crc16_table[ p ];
d := crc16_t(c shl 8);
c := d xor m;
end;
result := c xor $ffff;
end;
//========================================================================================
//------------------------------------------ Вычислить циклическую контрольную сумму CRC32
function CalculateCRC32(const pData : pchar; dataLen : integer) : crc32_t;
var
n : integer;
c,m : crc32_t;
p : byte;
r : char;
begin
c := $ffffffff;
for n := 0 to dataLen-1 do
begin
r := pData[n];
p := (c xor byte(r)) and $ff;
m := crc32_table[ p ];
c := c shr 8;
c := c xor m;
end;
result := c xor $ffffffff;
end;
end.
|
// **************************************************************************************************
//
// Unit uPreviewContainer
// unit for the Delphi Preview Handler https://github.com/RRUZ/delphi-preview-handler
//
// 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 uPreviewContainer.pas.
//
// The Initial Developer of the Original Code is Rodrigo Ruz V.
// Portions created by Rodrigo Ruz V. are Copyright (C) 2011-2023 Rodrigo Ruz V.
// All Rights Reserved.
//
// *************************************************************************************************
unit uPreviewContainer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TPreviewContainer = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FPreview: TObject;
public
procedure SetFocusTabFirst;
procedure SetFocusTabLast;
procedure SetBackgroundColor(color: TColorRef);
procedure SetBoundsRect(const ARect: TRect);
procedure SetTextColor(color: TColorRef);
procedure SetTextFont(const plf: TLogFont);
property Preview: TObject read FPreview write FPreview;
end;
implementation
uses
SynEdit,
Vcl.Styles.Ext,
Vcl.Styles,
Vcl.Themes,
uSettings, uLogExcept;
{$R *.dfm}
procedure TPreviewContainer.SetFocusTabFirst;
begin
SelectNext(nil, True, True);
end;
procedure TPreviewContainer.SetFocusTabLast;
begin
SelectNext(nil, False, True);
end;
procedure TPreviewContainer.FormCreate(Sender: TObject);
var
LSettings: TSettings;
begin
TLogPreview.Add('TPreviewContainer.FormCreate');
LSettings := TSettings.Create;
try
if not IsStyleHookRegistered(TCustomSynEdit, TScrollingStyleHook) then
TStyleManager.Engine.RegisterStyleHook(TCustomSynEdit, TScrollingStyleHook);
if (Trim(LSettings.StyleName) <> '') and not SameText('Windows', LSettings.StyleName) then
TStyleManager.TrySetStyle(LSettings.StyleName, False);
finally
LSettings.Free;
end;
TLogPreview.Add('TPreviewContainer.FormCreate Done');
end;
procedure TPreviewContainer.FormDestroy(Sender: TObject);
begin
TLogPreview.Add('TPreviewContainer.FormDestroy');
end;
procedure TPreviewContainer.SetBackgroundColor(color: TColorRef);
begin
end;
procedure TPreviewContainer.SetBoundsRect(const ARect: TRect);
begin
SetBounds(ARect.Left, ARect.Top, ARect.Right - ARect.Left, ARect.Bottom - ARect.Top);
end;
procedure TPreviewContainer.SetTextColor(color: TColorRef);
begin
end;
procedure TPreviewContainer.SetTextFont(const plf: TLogFont);
begin
end;
end.
|
unit l3VCLStrings;
{ Библиотека "L3 (Low Level Library)" }
{ Автор: Люлин А.В. © }
{ Модуль: l3VCLStrings - }
{ Начат: 29.12.2006 13:48 }
{ $Id: l3VCLStrings.pas,v 1.26 2013/03/28 17:25:05 lulin Exp $ }
// $Log: l3VCLStrings.pas,v $
// Revision 1.26 2013/03/28 17:25:05 lulin
// - портируем.
//
// Revision 1.25 2008/07/08 09:48:51 lulin
// - не перекладываем строки в ноды, а просто реализуем интерфейс ноды.
//
// Revision 1.24 2008/02/20 17:23:09 lulin
// - упрощаем строки.
//
// Revision 1.23 2008/02/12 19:32:36 lulin
// - избавляемся от универсальности списков.
//
// Revision 1.22 2008/02/06 11:44:42 lulin
// - список строк переехал в отдельный файл.
//
// Revision 1.21 2007/07/24 19:21:13 lulin
// - скомпилировался F1 с модулем l3Interfaces, сгенерированным с модели.
//
// Revision 1.20 2007/04/05 11:16:58 lulin
// - cleanup.
//
// Revision 1.19 2007/03/28 19:43:00 lulin
// - ЭлПаковский редактор переводим на строки с кодировкой.
//
// Revision 1.18 2007/03/27 14:27:39 lulin
// - используем кошерный список строк.
//
// Revision 1.17 2007/03/16 12:21:28 lulin
// - переводим на строки с кодировкой.
//
// Revision 1.16 2007/03/01 08:53:59 lulin
// - cleanup.
//
// Revision 1.15 2007/03/01 08:39:52 lulin
// - не копируем данные строки, если их держит интерфейс строки.
//
// Revision 1.14 2007/02/28 18:50:55 lulin
// - используем полиморфизм базового класса строки, вместо приведения типа.
//
// Revision 1.13 2007/02/16 19:19:15 lulin
// - в выпадающих списках используем родной список строк.
//
// Revision 1.12 2007/02/13 14:46:11 lulin
// - cleanup.
//
// Revision 1.11 2007/02/13 09:34:42 lulin
// - переводим на строки с кодировкой.
//
// Revision 1.10 2007/02/06 15:21:20 lulin
// - переводим на строки с кодировкой.
//
// Revision 1.9 2007/02/05 15:02:32 lulin
// - добавляем возможность работать с элементами с кодировкой.
//
// Revision 1.8 2007/02/02 08:39:24 lulin
// - переводим на строки с кодировкой.
//
// Revision 1.7 2006/12/29 14:35:00 lulin
// - копируем объект при копировании строки.
//
// Revision 1.6 2006/12/29 13:58:02 lulin
// - используем собственную реализацию списка строк.
//
// Revision 1.5 2006/12/29 13:09:27 lulin
// - реализуем интерфейс расширенного списка строк.
//
// Revision 1.4 2006/12/29 12:11:00 lulin
// - реализуем хранение объектов, связанных со строками.
//
// Revision 1.3 2006/12/29 12:03:46 lulin
// - реализуем интерфейс списка строк.
//
// Revision 1.2 2006/12/29 11:52:32 lulin
// - выделена базовая реализация списка VCL-ных строк.
//
// Revision 1.1 2006/12/29 10:57:59 lulin
// - начал работать над "родной" реализацией VCL-ных строк.
//
{$Include l3Define.inc }
interface
uses
Classes,
l3Interfaces,
l3Base,
l3StringList,
l3VCLStringsItems
;
type
Tl3CustomStrings = class;
Tl3StringsItems = class(Tl3VCLStringsItems)
private
// property fields
f_Strings : Tl3CustomStrings;
protected
// internal methods
procedure Clear;
override;
{-}
procedure Insert(Index: Integer; const S: String);
override;
{-}
function Get(Index: Integer): String;
override;
{-}
procedure Put(Index: Integer; const S: String);
override;
{-}
function GetCount: Integer;
override;
{-}
function GetObject(Index: Integer): TObject;
override;
{-}
procedure PutObject(Index: Integer; aObject: TObject);
override;
{-}
procedure Cleanup;
override;
{-}
public
// public methods
constructor Create(aStrings: Tl3CustomStrings);
reintroduce;
{-}
end;//Tl3StringsItems
Rl3StringsItems = class of Tl3StringsItems;
Tl3CustomStrings = class(Tl3StringList, Il3Strings, Il3StringsEx)
protected
// interface methods
// Il3Strings
function Get_Items: TStrings;
virtual;
{-}
// Il3StringsEx
procedure Set_Items(aValue: TStrings);
{-}
function Get_Count: Integer;
{-}
function Get_Item(Index: Integer): AnsiString;
{-}
procedure Set_Item(Index: Integer; const S: AnsiString);
{-}
function Get_Objects(anIndex: Integer): TObject;
{-}
procedure Set_Objects(anIndex: Integer; anObject: TObject);
{-}
function EQ(const aStrings: Il3StringsEx): Boolean;
{-}
procedure Assign(aStrings: TStrings);
reintroduce;
overload;
{-}
protected
// internal methods
//function pm_GetDuplicates: TDuplicates;
procedure pm_SetDuplicates(Value: TDuplicates);
reintroduce;
{-}
function ItemsClass: Rl3StringsItems;
virtual;
{-}
function StringItemClass: Rl3String;
override;
{-}
function CStrToItem(const aStr: Il3CString): Tl3CustomString;
override;
{-}
procedure ReadData(Reader: TReader);
{-}
procedure WriteData(Writer: TWriter);
{-}
procedure DefineProperties(Filer: TFiler);
override;
{-}
public
// public methods
class function Make: Il3StringsEx;
reintroduce;
{-}
procedure BeginUpdate;
{-}
procedure EndUpdate;
{-}
procedure Assign(const aStrings: Il3StringsEx);
reintroduce;
overload;
{-}
function AddObject(const aStr: AnsiString; anObject: TObject): Integer;
overload;
function AddObject(const aStr: Il3CString; anObject: TObject): Integer;
overload;
{-}
{$IfDef XE2}
function Add(const aStr: AnsiString): Integer; overload;
function IndexOf(const aSt: AnsiString): Integer; overload;
procedure Insert(aIndex: Integer;
const aStr: AnsiString); overload;
{$EndIf XE2}
procedure SetText(const aString: String);
{-}
public
// public properties
property Duplicates: TDuplicates
//read pm_GetDuplicates
write pm_SetDuplicates;
{-}
end;//Tl3CustomStrings
Tl3Strings = class(Tl3CustomStrings)
private
// internal fields
f_Items : Tl3StringsItems;
protected
// internal methods
function Get_Items: TStrings;
override;
{-}
procedure Cleanup;
override;
{-}
end;//Tl3Strings
implementation
uses
l3Types,
l3String
;
// start class Tl3StringsItems
constructor Tl3StringsItems.Create(aStrings: Tl3CustomStrings);
//reintroduce;
{-}
begin
inherited Create;
f_Strings := aStrings;
end;
procedure Tl3StringsItems.Cleanup;
{override;}
{-}
begin
f_Strings := nil;
inherited;
end;
procedure Tl3StringsItems.Clear;
//override;
{-}
begin
f_Strings.Clear;
end;
procedure Tl3StringsItems.Insert(Index: Integer; const S: string);
//override;
{-}
begin
f_Strings.Insert(Index, S);
end;
function Tl3StringsItems.Get(Index: Integer): string;
{override;}
{-}
begin
Result := f_Strings.Get_Item(Index);
end;
procedure Tl3StringsItems.Put(Index: Integer; const S: string);
{override;}
{-}
begin
f_Strings.Set_Item(Index, S);
end;
function Tl3StringsItems.GetCount: Integer;
{override;}
{-}
begin
Result := f_Strings.Count;
end;
function Tl3StringsItems.GetObject(Index: Integer): TObject;
{override;}
{-}
begin
Result := f_Strings.Get_Objects(Index);
end;
procedure Tl3StringsItems.PutObject(Index: Integer; aObject: TObject);
//override;
{-}
begin
f_Strings.Set_Objects(Index, aObject);
end;
// start class Tl3CustomStrings
class function Tl3CustomStrings.Make: Il3StringsEx;
//reintroduce;
{-}
var
l_L : Tl3CustomStrings;
begin
l_L := Create;
try
Result := l_L;
finally
l3Free(l_L);
end;//try..finally
end;
function Tl3CustomStrings.Get_Items: TStrings;
{-}
begin
Result := nil;
end;
procedure Tl3CustomStrings.Set_Items(aValue: TStrings);
{-}
begin
Assign(aValue);
end;
function Tl3CustomStrings.Get_Count: Integer;
{-}
begin
Result := Count;
end;
function Tl3CustomStrings.Get_Item(Index: Integer): AnsiString;
{-}
begin
Result := Items[Index].AsString;
end;
procedure Tl3CustomStrings.Set_Item(Index: Integer; const S: AnsiString);
{-}
begin
Items[Index].AsString := S;
end;
function Tl3CustomStrings.Get_Objects(anIndex: Integer): TObject;
{-}
begin
Result := Items[anIndex].LinkedObject;
end;
procedure Tl3CustomStrings.Set_Objects(anIndex: Integer; anObject: TObject);
{-}
begin
Items[anIndex].LinkedObject := anObject;
end;
procedure Tl3CustomStrings.Assign(const aStrings: Il3StringsEx);
//reintroduce;
//overload;
{-}
begin
if (aStrings = nil) then
Clear
else
inherited Assign(aStrings.Items);
end;
procedure Tl3CustomStrings.Assign(aStrings: TStrings);
//reintroduce;
//overload;
{-}
begin
if (aStrings = nil) then
Clear
else
inherited Assign(aStrings);
end;
function Tl3CustomStrings.EQ(const aStrings: Il3StringsEx): Boolean;
{-}
var
l_Index : Integer;
l_Item : Tl3CustomString;
begin
// количество одинаковое
Result := (Count = aStrings.Count);
// сравним
if Result then
for l_Index := 0 to Pred(Count) do
// нашли не одинаковые
begin
l_Item := Tl3CustomString(Items[l_Index]);
if not l3Same(l_Item.AsWStr, aStrings.ItemC[l_Index]) then
begin
Result := false;
break;
end;//not l3Same(l_Item.AsWStr, aStrings.ItemC[l_Index])
if (l_Item.LinkedObject <> aStrings.Objects[l_Index]) then
begin
Result := false;
break;
end;//l_Item.LinkedObject <> aStrings.Objects[l_Index]
end;//for l_Index
end;
function Tl3CustomStrings.AddObject(const aStr: AnsiString; anObject: TObject): Integer;
{-}
begin
Result := Add(aStr);
Set_Objects(Result, anObject);
end;
function Tl3CustomStrings.AddObject(const aStr: Il3CString; anObject: TObject): Integer;
//overload;
{-}
begin
Result := Add(aStr);
Set_Objects(Result, anObject);
end;
{$IfDef XE2}
function Tl3CustomStrings.Add(const aStr: AnsiString): Integer;
begin
Result := inherited Add(String(aStr));
end;
function Tl3CustomStrings.IndexOf(const aSt: AnsiString): Integer;
begin
Result := inherited IndexOf(String(aSt));
end;
procedure Tl3CustomStrings.Insert(aIndex: Integer;
const aStr: AnsiString);
begin
inherited Insert(aIndex, String(aStr));
end;
{$EndIf XE2}
procedure Tl3CustomStrings.SetText(const aString: String);
{-}
begin
Get_Items.Text := aString;
end;
procedure Tl3CustomStrings.BeginUpdate;
{-}
begin
Changing;
end;
procedure Tl3CustomStrings.EndUpdate;
{-}
begin
Changed;
end;
procedure Tl3CustomStrings.pm_SetDuplicates(Value: TDuplicates);
{-}
begin
Case Value of
dupIgnore :
inherited Duplicates := l3_dupIgnore;
dupAccept :
inherited Duplicates := l3_dupAccept;
dupError :
inherited Duplicates := l3_dupError;
end;//Case Value
end;
function Tl3CustomStrings.ItemsClass: Rl3StringsItems;
//virtual;
{-}
begin
Result := Tl3StringsItems;
end;
function Tl3CustomStrings.StringItemClass: Rl3String;
//override;
{-}
begin
Result := Tl3ObjPtrString;
end;
function Tl3CustomStrings.CStrToItem(const aStr: Il3CString): Tl3CustomString;
//override;
{-}
begin
Result := Tl3ObjPtrIntfString.Make(aStr);
end;
procedure Tl3CustomStrings.DefineProperties(Filer: TFiler);
//override;
{-}
function DoWrite: Boolean;
begin//DoWrite
if (Filer.Ancestor <> nil) then
begin
Result := True;
if (Filer.Ancestor is Tl3CustomStrings) then
Result := not EQ(Tl3CustomStrings(Filer.Ancestor))
end//Filer.Ancestor <> nil
else
Result := Count > 0;
end;//DoWrite
begin
Filer.DefineProperty('Strings', ReadData, WriteData, DoWrite);
end;
procedure Tl3CustomStrings.ReadData(Reader: TReader);
begin
Reader.ReadListBegin;
BeginUpdate;
try
Clear;
while not Reader.EndOfList do
Add(Reader.ReadString);
finally
EndUpdate;
end;
Reader.ReadListEnd;
end;
procedure Tl3CustomStrings.WriteData(Writer: TWriter);
var
I: Integer;
begin
Writer.WriteListBegin;
for I := 0 to Count - 1 do
Writer.WriteString(Get_Item(I));
Writer.WriteListEnd;
end;
// start class Tl3Strings
procedure Tl3Strings.Cleanup;
//override;
{-}
begin
if (f_Items <> nil) then
f_Items.f_Strings := nil;
l3Free(f_Items);
inherited;
end;
function Tl3Strings.Get_Items: TStrings;
{-}
begin
if (f_Items = nil) then
f_Items := ItemsClass.Create(Self);
Result := f_Items;
end;
end.
|
unit AdminDomainInterfaces;
{* Администрирование }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Model\AdminDomainInterfaces.pas"
// Стереотип: "Interfaces"
// Элемент модели: "AdminDomainInterfaces" MUID: (49903C95009E)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
l3IntfUses
, l3Interfaces
, SysUtils
;
type
EdsMaxLengthExceed = class(Exception)
{* Превышена допустимая длинна строки }
private
f_MaxLength: Integer;
public
constructor Create(aMaxLength: Integer); reintroduce;
public
property MaxLength: Integer
read f_MaxLength;
end;//EdsMaxLengthExceed
InsAdminInfo = interface
{* Информация об администраторе }
['{61BE9766-54B8-4A29-A794-8E08259285B1}']
function pm_GetHasEmail: Boolean;
function pm_GetHasPhone: Boolean;
function pm_GetPhone: Il3CString;
procedure pm_SetPhone(const aValue: Il3CString); { can raise EdsMaxLengthExceed }
function pm_GetEmail: Il3CString;
procedure pm_SetEmail(const aValue: Il3CString); { can raise EdsMaxLengthExceed }
property HasEmail: Boolean
read pm_GetHasEmail;
property HasPhone: Boolean
read pm_GetHasPhone;
property Phone: Il3CString
read pm_GetPhone
write pm_SetPhone;
property Email: Il3CString
read pm_GetEmail
write pm_SetEmail;
end;//InsAdminInfo
(*
nsUserProperty = interface
function Get_UID: Integer;
function Get_GroupUID: Integer;
function Get_Login: Il3CString;
function Get_Name: Il3CString;
function Get_Mail: Il3CString;
function Get_IsChanged: Boolean;
procedure Set_IsChanged(aValue: Boolean);
function Get_IsNewUser: Boolean;
function Get_CanBuyConsulting: Boolean;
function Get_IsSystem: Boolean;
function Get_IsPrivileged: Boolean;
function Get_DontDeleteIdle: Boolean;
function HasUserProfile: Boolean;
function HasPassword: Boolean;
procedure SaveUserProfile(const aName: Tl3WString;
const aMail: Tl3WString;
aCanBuyConsulting: Boolean;
aIsPrivileged: Boolean;
aDontDeleteIdle: Boolean;
const aPassword: Tl3WString;
aGroupUID: Integer;
IsPasswordChanged: Boolean = False);
procedure SaveUserInfo(const aName: Tl3WString;
const aMail: Tl3WString;
const aPassword: Tl3WString;
IsPasswordChanged: Boolean = False);
property UID: Integer
read Get_UID;
property GroupUID: Integer
read Get_GroupUID;
property Login: Il3CString
read Get_Login;
property Name: Il3CString
read Get_Name;
property Mail: Il3CString
read Get_Mail;
property IsChanged: Boolean
read Get_IsChanged
write Set_IsChanged;
property IsNewUser: Boolean
read Get_IsNewUser;
property CanBuyConsulting: Boolean
read Get_CanBuyConsulting;
property IsSystem: Boolean
read Get_IsSystem;
property IsPrivileged: Boolean
read Get_IsPrivileged;
property DontDeleteIdle: Boolean
read Get_DontDeleteIdle;
end;//nsUserProperty
*)
InsUserProperty = interface
['{1DD2D30F-4FAB-4F0C-B591-CB76CADDB345}']
function Get_UID: Integer;
function Get_GroupUID: Integer;
function Get_Login: Il3CString;
function Get_Name: Il3CString;
function Get_Mail: Il3CString;
function Get_IsChanged: Boolean;
procedure Set_IsChanged(aValue: Boolean);
function Get_IsNewUser: Boolean;
function Get_CanBuyConsulting: Boolean;
function Get_IsSystem: Boolean;
function Get_IsPrivileged: Boolean;
function Get_DontDeleteIdle: Boolean;
function HasUserProfile: Boolean;
function HasPassword: Boolean;
procedure SaveUserProfile(const aName: Tl3WString;
const aMail: Tl3WString;
aCanBuyConsulting: Boolean;
aIsPrivileged: Boolean;
aDontDeleteIdle: Boolean;
const aPassword: Tl3WString;
aGroupUID: Integer;
IsPasswordChanged: Boolean = False);
procedure SaveUserInfo(const aName: Tl3WString;
const aMail: Tl3WString;
const aPassword: Tl3WString;
IsPasswordChanged: Boolean = False);
property UID: Integer
read Get_UID;
property GroupUID: Integer
read Get_GroupUID;
property Login: Il3CString
read Get_Login;
property Name: Il3CString
read Get_Name;
property Mail: Il3CString
read Get_Mail;
property IsChanged: Boolean
read Get_IsChanged
write Set_IsChanged;
property IsNewUser: Boolean
read Get_IsNewUser;
property CanBuyConsulting: Boolean
read Get_CanBuyConsulting;
property IsSystem: Boolean
read Get_IsSystem;
property IsPrivileged: Boolean
read Get_IsPrivileged;
property DontDeleteIdle: Boolean
read Get_DontDeleteIdle;
end;//InsUserProperty
implementation
uses
l3ImplUses
{$If NOT Defined(NoScripts)}
, TtfwTypeRegistrator_Proxy
{$IfEnd} // NOT Defined(NoScripts)
;
constructor EdsMaxLengthExceed.Create(aMaxLength: Integer);
//#UC START# *491D987C0028_491D982203CD_var*
//#UC END# *491D987C0028_491D982203CD_var*
begin
//#UC START# *491D987C0028_491D982203CD_impl*
inherited Create('');
f_MaxLength := aMaxLength;
//#UC END# *491D987C0028_491D982203CD_impl*
end;//EdsMaxLengthExceed.Create
initialization
{$If NOT Defined(NoScripts)}
TtfwTypeRegistrator.RegisterType(TypeInfo(EdsMaxLengthExceed));
{* Регистрация типа EdsMaxLengthExceed }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1996 AO ROSNO }
{ Copyright (c) 1997, 1998 Master-Bank }
{ }
{ Patched by Polaris Software }
{*******************************************************}
unit RxTimer;
interface
{$I RX.INC}
{$IFDEF RX_D6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
uses{$IFNDEF VER80}Windows, {$ELSE}WinTypes, WinProcs, {$ENDIF}
Messages, SysUtils, Classes, Controls;
type
{ TRxTimer }
TRxTimer = class(TComponent)
private
FEnabled: Boolean;
FInterval: Cardinal;
FOnTimer: TNotifyEvent;
FWindowHandle: HWND;
{$IFNDEF VER80}
FSyncEvent: Boolean;
FThreaded: Boolean;
FTimerThread: TThread;
FThreadPriority: TThreadPriority;
procedure SetThreaded(Value: Boolean);
procedure SetThreadPriority(Value: TThreadPriority);
{$ENDIF}
procedure SetEnabled(Value: Boolean);
procedure SetInterval(Value: Cardinal);
procedure SetOnTimer(Value: TNotifyEvent);
procedure UpdateTimer;
procedure WndProc(var Msg: TMessage);
protected
procedure Timer; dynamic;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{$IFNDEF VER80}
procedure Synchronize(Method: TThreadMethod);
{$ENDIF}
published
property Enabled: Boolean read FEnabled write SetEnabled default True;
property Interval: Cardinal read FInterval write SetInterval default 1000;
{$IFNDEF VER80}
property SyncEvent: Boolean read FSyncEvent write FSyncEvent default True;
property Threaded: Boolean read FThreaded write SetThreaded default True;
property ThreadPriority: TThreadPriority read FThreadPriority write
SetThreadPriority default tpNormal;
{$ENDIF}
property OnTimer: TNotifyEvent read FOnTimer write SetOnTimer;
end;
{ TCustomThread }
TCustomThread = class(TThread)
private
FOnExecute: TNotifyEvent;
protected
procedure Execute; override;
public
property OnExecute: TNotifyEvent read FOnExecute write FOnExecute;
property Terminated;
end;
{ TRxThread }
TRxThread = class(TComponent)
private
FThread: TCustomThread;
FSyncMethod: TNotifyEvent;
FSyncParams: Pointer;
FStreamedSuspended, FCycled: Boolean;
FOnExecute, FOnException: TNotifyEvent;
FInterval: Integer;
procedure InternalSynchronize;
function GetHandle: THandle;
function GetThreadID: THandle;
function GetOnTerminate: TNotifyEvent;
procedure SetOnTerminate(Value: TNotifyEvent);
function GetPriority: TThreadPriority;
procedure SetPriority(Value: TThreadPriority);
function GetReturnValue: Integer;
procedure SetReturnValue(Value: Integer);
function GetSuspended: Boolean;
procedure SetSuspended(Value: Boolean);
function GetTerminated: boolean;
protected
procedure DoExecute(Sender: TObject); virtual;
procedure DoException(Sender: TObject); virtual;
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Execute;
procedure Synchronize(Method: TThreadMethod);
procedure SynchronizeEx(Method: TNotifyEvent; Params: Pointer);
procedure Suspend;
procedure Resume;
procedure Terminate;
function TerminateWaitFor: Integer;
procedure TerminateHard;
function WaitFor: Integer;
property ReturnValue: Integer read GetReturnValue write SetReturnValue;
property Handle: THandle read GetHandle;
property ThreadID: THandle read GetThreadID;
property Terminated: Boolean read GetTerminated;
procedure Delay(MSecs: Longint);
published
property OnTerminate: TNotifyEvent read GetOnTerminate write SetOnTerminate;
property Priority: TThreadPriority read GetPriority write SetPriority;
property Suspended: Boolean read GetSuspended write SetSuspended default True;
property OnExecute: TNotifyEvent read FOnExecute write FOnExecute;
property OnException: TNotifyEvent read FOnException write FOnException;
property Interval: Integer read FInterval write FInterval;
property Cycled: Boolean read FCycled write FCycled;
end;
implementation
uses Forms, Consts, RxVCLUtils;
{$IFNDEF VER80}
{ TTimerThread }
type
TTimerThread = class(TThread)
private
FOwner: TRxTimer;
FInterval: Cardinal;
FException: Exception;
procedure HandleException;
protected
procedure Execute; override;
public
constructor Create(Timer: TRxTimer; Enabled: Boolean);
end;
constructor TTimerThread.Create(Timer: TRxTimer; Enabled: Boolean);
begin
FOwner := Timer;
inherited Create(not Enabled);
FInterval := 1000;
FreeOnTerminate := True;
end;
procedure TTimerThread.HandleException;
begin
if not (FException is EAbort) then
begin
if Assigned(Application.OnException) then
Application.OnException(Self, FException)
else
Application.ShowException(FException);
end;
end;
procedure TTimerThread.Execute;
function ThreadClosed: Boolean;
begin
Result := Terminated or Application.Terminated or (FOwner = nil);
end;
begin
repeat
if not ThreadClosed then
if SleepEx(FInterval, False) = 0 then
begin
if not ThreadClosed and FOwner.FEnabled then
with FOwner do
if SyncEvent then Synchronize(Timer)
else
try
Timer;
except
on E: Exception do
begin
FException := E;
HandleException;
end;
end;
end;
until Terminated;
end;
{$ENDIF}
{ TRxTimer }
constructor TRxTimer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEnabled := True;
FInterval := 1000;
{$IFNDEF VER80}
FSyncEvent := True;
FThreaded := True;
FThreadPriority := tpNormal;
FTimerThread := TTimerThread.Create(Self, False);
{$ELSE}
FWindowHandle := AllocateHWnd(WndProc);
{$ENDIF}
end;
destructor TRxTimer.Destroy;
begin
Destroying;
FEnabled := False;
FOnTimer := nil;
{$IFNDEF VER80}
{TTimerThread(FTimerThread).FOwner := nil;}
while FTimerThread.Suspended do
FTimerThread.Resume;//{$IFDEF RX_D14}Start{$ELSE}Resume{$ENDIF};
FTimerThread.Terminate;
{if not SyncEvent then FTimerThread.WaitFor;}
if FWindowHandle <> 0 then
begin
{$ENDIF}
KillTimer(FWindowHandle, 1);
{$IFDEF RX_D6}Classes.{$ENDIF}DeallocateHWnd(FWindowHandle); // Polaris
{$IFNDEF VER80}
end;
{$ENDIF}
inherited Destroy;
end;
procedure TRxTimer.WndProc(var Msg: TMessage);
begin
with Msg do
if Msg = WM_TIMER then
try
Timer;
except
Application.HandleException(Self);
end
else Result := DefWindowProc(FWindowHandle, Msg, wParam, lParam);
end;
procedure TRxTimer.UpdateTimer;
begin
{$IFNDEF VER80}
if FThreaded then
begin
if FWindowHandle <> 0 then
begin
KillTimer(FWindowHandle, 1);
{$IFDEF RX_D6}Classes.{$ENDIF}DeallocateHWnd(FWindowHandle); // Polaris
FWindowHandle := 0;
end;
if not FTimerThread.Suspended then FTimerThread.Suspend;
TTimerThread(FTimerThread).FInterval := FInterval;
if (FInterval <> 0) and FEnabled and Assigned(FOnTimer) then
begin
FTimerThread.Priority := FThreadPriority;
while FTimerThread.Suspended do
FTimerThread.Resume; //{$IFDEF RX_D14}Start{$ELSE}Resume{$ENDIF};
end;
end
else
begin
if not FTimerThread.Suspended then FTimerThread.Suspend;
if FWindowHandle = 0 then FWindowHandle := {$IFDEF RX_D6}Classes.{$ENDIF}AllocateHWnd(WndProc) // Polaris
else KillTimer(FWindowHandle, 1);
if (FInterval <> 0) and FEnabled and Assigned(FOnTimer) then
if SetTimer(FWindowHandle, 1, FInterval, nil) = 0 then
raise EOutOfResources.Create(ResStr(SNoTimers));
end;
{$ELSE}
KillTimer(FWindowHandle, 1);
if (FInterval <> 0) and FEnabled and Assigned(FOnTimer) then
if SetTimer(FWindowHandle, 1, FInterval, nil) = 0 then
raise EOutOfResources.Create(ResStr(SNoTimers));
{$ENDIF}
end;
procedure TRxTimer.SetEnabled(Value: Boolean);
begin
if Value <> FEnabled then
begin
FEnabled := Value;
UpdateTimer;
end;
end;
procedure TRxTimer.SetInterval(Value: Cardinal);
begin
if Value <> FInterval then
begin
FInterval := Value;
UpdateTimer;
end;
end;
{$IFNDEF VER80}
procedure TRxTimer.SetThreaded(Value: Boolean);
begin
if Value <> FThreaded then
begin
FThreaded := Value;
UpdateTimer;
end;
end;
procedure TRxTimer.SetThreadPriority(Value: TThreadPriority);
begin
if Value <> FThreadPriority then
begin
FThreadPriority := Value;
if FThreaded then UpdateTimer;
end;
end;
procedure TRxTimer.Synchronize(Method: TThreadMethod);
begin
if (FTimerThread <> nil) then
begin
with TTimerThread(FTimerThread) do
begin
if Suspended or Terminated then Method
else TTimerThread(FTimerThread).Synchronize(Method);
end;
end
else Method;
end;
{$ENDIF}
procedure TRxTimer.SetOnTimer(Value: TNotifyEvent);
begin
if Assigned(FOnTimer) <> Assigned(Value) then
begin
FOnTimer := Value;
UpdateTimer;
end
else
FOnTimer := Value;
end;
procedure TRxTimer.Timer;
begin
if FEnabled and not (csDestroying in ComponentState) and Assigned(FOnTimer) then
FOnTimer(Self);
end;
{ TCustomThread }
procedure TCustomThread.Execute;
begin
if Assigned(FOnExecute) then FOnExecute(Self);
end;
{ TThreadHack }
type TThreadHack = class(TCustomThread);
{ TRxThread }
constructor TRxThread.Create(AOwner: TComponent);
begin
inherited;
FStreamedSuspended := True;
FThread := TCustomThread.Create(True);
FThread.OnExecute := DoExecute;
FInterval := 0;
FCycled := False;
end;
destructor TRxThread.Destroy;
begin
if not FStreamedSuspended then
FThread.Suspend;
FThread.Free;
inherited;
end;
procedure TRxThread.DoExecute(Sender: TObject);
begin
repeat
Delay(FInterval);
if FThread.Terminated then Break;
try
if Assigned(FOnExecute) then FOnExecute(Self);
except
SynchronizeEx(DoException, ExceptObject);
end;
until FThread.Terminated or not (Cycled);
end;
procedure TRxThread.DoException(Sender: TObject);
var
s: string;
begin
if Assigned(FOnException) then
FOnException(Sender)
else
begin
s := Format('Thread %s raised exception class %s with message ''%s''.',
[Name, Exception(Sender).ClassName, Exception(Sender).Message]);
Application.MessageBox(PChar(s), PChar(Application.Title),
MB_ICONERROR or MB_SETFOREGROUND or MB_APPLMODAL);
end;
end;
function TRxThread.GetHandle: THandle;
begin
Result := FThread.Handle;
end;
function TRxThread.GetOnTerminate: TNotifyEvent;
begin
Result := FThread.OnTerminate;
end;
function TRxThread.GetPriority: TThreadPriority;
begin
Result := FThread.Priority;
end;
function TRxThread.GetReturnValue: Integer;
begin
Result := TThreadHack(FThread).ReturnValue;
end;
function TRxThread.GetSuspended: Boolean;
begin
if not (csDesigning in ComponentState) then
Result := FThread.Suspended
else
Result := FStreamedSuspended;
end;
procedure TRxThread.Execute;
begin
TerminateHard;
FThread.Resume; //{$IFDEF RX_D14}Start{$ELSE}Resume{$ENDIF};
end;
procedure TRxThread.Loaded;
begin
inherited;
SetSuspended(FStreamedSuspended);
end;
procedure TRxThread.SetOnTerminate(Value: TNotifyEvent);
begin
FThread.OnTerminate := Value;
end;
procedure TRxThread.SetPriority(Value: TThreadPriority);
begin
FThread.Priority := Value;
end;
procedure TRxThread.SetReturnValue(Value: Integer);
begin
TThreadHack(FThread).ReturnValue := Value;
end;
procedure TRxThread.SetSuspended(Value: Boolean);
begin
if not (csDesigning in ComponentState) then
begin
if (csLoading in ComponentState) then
FStreamedSuspended := Value
else
FThread.Suspended := Value;
end
else
FStreamedSuspended := Value;
end;
procedure TRxThread.Suspend;
begin
FThread.Suspend;
end;
procedure TRxThread.Synchronize(Method: TThreadMethod);
begin
TThreadHack(FThread).Synchronize(Method);
end;
procedure TRxThread.InternalSynchronize;
begin
FSyncMethod(FSyncParams);
end;
procedure TRxThread.SynchronizeEx(Method: TNotifyEvent; Params: Pointer);
begin
if not Assigned(FSyncMethod) then
begin
FSyncMethod := Method; FSyncParams := Params;
try
TThreadHack(FThread).Synchronize(InternalSynchronize);
finally
FSyncMethod := nil; FSyncParams := nil;
end;
end;
end;
procedure TRxThread.Resume;
begin
FThread.Resume; //{$IFDEF RX_D14}Start{$ELSE}Resume{$ENDIF};
end;
procedure TRxThread.Terminate;
begin
FThread.Terminate;
end;
function TRxThread.TerminateWaitFor: Integer;
begin
Terminate;
Result := WaitFor;
end;
procedure TRxThread.TerminateHard;
var
FTmp: TCustomThread;
begin
TerminateThread(FThread.Handle, 0);
FTmp := TCustomThread.Create(True);
try
FTmp.Priority := Self.Priority;
FTmp.OnExecute := DoExecute;
FTmp.OnTerminate := Self.OnTerminate;
except
FTmp.Free;
raise;
end;
FThread.Free;
FThread := FTmp;
end;
function TRxThread.WaitFor: Integer;
begin
Result := FThread.WaitFor;
end;
function TRxThread.GetTerminated: boolean;
begin
Result := FThread.Terminated;
end;
function TRxThread.GetThreadID: THandle;
begin
Result := FThread.ThreadID;
end;
procedure TRxThread.Delay(MSecs: Longint);
var
FirstTickCount, Now: Longint;
begin
if MSecs < 0 then exit;
FirstTickCount := GetTickCount;
repeat
Sleep(1);
Now := GetTickCount;
until (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount) or Terminated;
end;
end.
|
program MakeVer;
{
Makes INI-style version file from Delphi .dof file.
Author: Phil Hess.
Copyright: Copyright (C) 2007 Phil Hess. All rights reserved.
License: Modified LGPL.
}
{$IFDEF FPC}
{$MODE Delphi}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
{$R+,Q+}
uses
SysUtils,
Classes,
IniFiles;
const
ProgramName = 'MakeVer';
ProgramVersion = '0.02';
DofFileExt = '.dof'; {Delphi project options file extension}
VerFileExt = '.version'; {Linux/Mac version info file extension}
VersionSection = 'Version Info Keys';
var
DofFileName : string;
VerFileName : string;
DofIniFile : TIniFile;
VerIniFile : TIniFile;
VerStrList : TStringList;
{$IFNDEF FPC}
MatchFound : TFilenameCaseMatch;
{$ENDIF}
ItemNum : Integer;
begin
if ParamCount = 0 then {List program useage?}
begin
WriteLn(ProgramName, ', version ', ProgramVersion,
' - makes INI-style version file from Delphi .dof file.');
WriteLn('Usage: ', ProgramName, ' filename', DofFileExt);
Halt;
end;
{Get name of Delphi project options file from command line}
DofFileName := ParamStr(1);
if ExtractFileExt(DofFileName) = '' then
DofFileName := DofFileName + DofFileExt;
{$IFNDEF FPC}
DofFileName := ExpandFileNameCase(DofFileName, MatchFound);
{$ELSE}
DofFileName := ExpandFileName(DofFileName);
{$ENDIF}
VerFileName := ChangeFileExt(DofFileName, VerFileExt);
if not FileExists(DofFileName) then
begin
WriteLn(DofFileName, ' does not exist');
Halt;
end;
DofIniFile := TIniFile.Create(DofFileName);
VerStrList := TStringList.Create;
DofIniFile.ReadSectionValues(VersionSection, VerStrList); {Load vers strings}
VerIniFile := TIniFile.Create(VerFileName);
for ItemNum := 0 to Pred(VerStrList.Count) do {Write to version file}
begin
VerIniFile.WriteString(VersionSection, VerStrList.Names[ItemNum],
VerStrList.Values[VerStrList.Names[ItemNum]]);
end;
VerIniFile.UpdateFile; {Save to file}
VerIniFile.Free;
DofIniFile.Free;
WriteLn(VerFileName, ' successfully created');
end.
|
unit Rule_CORREL;
interface
uses
BaseRule,
BaseRuleData;
(*//
CORREL
含义:两样本的相关系数。
用法:CORREL(X,Y,N)为X与Y的N周期相关系数,其有效值范围在-1 ~ 1之间
例如:CORREL(CLOSE,INDEXC,10)表示收盘价与大盘指数之间的10周期相关系数
//*)
type
TRule_CORREL = class(TBaseRule)
protected
fParamN: Word;
fParamM: Word;
fInt64Ret: PArrayInt64;
fFloatRet: PArrayDouble;
function Get_CORREL_ValueF(AIndex: integer): double;
function Get_CORREL_ValueI(AIndex: integer): Int64;
function GetParamN: Word;
procedure SetParamN(const Value: Word);
function GetParamM: Word;
procedure SetParamM(const Value: Word);
procedure ComputeInt64;
procedure ComputeFloat;
public
constructor Create(ADataType: TRuleDataType = dtDouble); override;
destructor Destroy; override;
procedure Execute; override;
procedure Clear; override;
property ValueF[AIndex: integer]: double read Get_CORREL_ValueF;
property ValueI[AIndex: integer]: int64 read Get_CORREL_ValueI;
property ParamN: Word read GetParamN write SetParamN;
property ParamM: Word read GetParamM write SetParamM;
end;
implementation
{ TRule_CORREL }
constructor TRule_CORREL.Create(ADataType: TRuleDataType = dtDouble);
begin
inherited;
fParamN := 20;
fFloatRet := nil;
fInt64Ret := nil;
end;
destructor TRule_CORREL.Destroy;
begin
Clear;
inherited;
end;
procedure TRule_CORREL.Execute;
begin
Clear;
if Assigned(OnGetDataLength) then
begin
fBaseRuleData.DataLength := OnGetDataLength;
if fBaseRuleData.DataLength > 0 then
begin
case fBaseRuleData.DataType of
dtInt64: begin
ComputeInt64;
end;
dtDouble: begin
ComputeFloat;
end;
end;
end;
end;
end;
procedure TRule_CORREL.Clear;
begin
CheckInArrayInt64(fInt64Ret);
CheckInArrayDouble(fFloatRet);
fBaseRuleData.DataLength := 0;
end;
procedure TRule_CORREL.ComputeInt64;
var
tmpInt64_Meta: array of Int64;
i: integer;
tmpCounter: integer;
tmpValue: Int64;
begin
if Assigned(OnGetDataI) then
begin
if fInt64Ret = nil then
fInt64Ret := CheckOutArrayInt64;
SetArrayInt64Length(fInt64Ret, fBaseRuleData.DataLength);
SetLength(tmpInt64_Meta, fBaseRuleData.DataLength);
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpInt64_Meta[i] := OnGetDataI(i);
tmpValue := tmpInt64_Meta[i];
tmpCounter := fParamN - 1;
while tmpCounter > 0 do
begin
if i > tmpCounter - 1 then
begin
tmpValue := tmpValue + tmpInt64_Meta[i - tmpCounter];
end;
Dec(tmpCounter);
end;
if 1 < fParamN then
begin
if i > fParamN - 1 then
begin
tmpValue := tmpValue div fParamN;
end else
begin
tmpValue := tmpValue div (i + 1);
end;
end;
SetArrayInt64Value(fInt64Ret, i, tmpValue);
end;
end;
end;
procedure TRule_CORREL.ComputeFloat;
var
tmpFloat_Meta: array of double;
i: integer;
tmpCounter: integer;
tmpDouble: Double;
begin
if Assigned(OnGetDataF) then
begin
if fFloatRet = nil then
fFloatRet := CheckOutArrayDouble;
SetArrayDoubleLength(fFloatRet, fBaseRuleData.DataLength);
SetLength(tmpFloat_Meta, fBaseRuleData.DataLength);
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpFloat_Meta[i] := OnGetDataF(i);
tmpDouble := tmpFloat_Meta[i];
tmpCounter := fParamN - 1;
while tmpCounter > 0 do
begin
if i > tmpCounter - 1 then
begin
tmpDouble := tmpDouble + tmpFloat_Meta[i - tmpCounter];
end;
Dec(tmpCounter);
end;
if fParamN > 1 then
begin
if i > fParamN - 1 then
begin
tmpDouble := tmpDouble / fParamN;
end else
begin
tmpDouble := tmpDouble / (i + 1);
end;
end;
SetArrayDoubleValue(fFloatRet, i, tmpDouble);
end;
end;
end;
function TRule_CORREL.GetParamM: Word;
begin
Result := fParamM;
end;
procedure TRule_CORREL.SetParamM(const Value: Word);
begin
if Value > 0 then
fParamM := Value;
end;
function TRule_CORREL.GetParamN: Word;
begin
Result := fParamN;
end;
procedure TRule_CORREL.SetParamN(const Value: Word);
begin
if Value > 0 then
fParamN := Value;
end;
function TRule_CORREL.Get_CORREL_ValueF(AIndex: integer): double;
begin
Result := 0;
if fBaseRuleData.DataType = dtDouble then
begin
if fFloatRet <> nil then
begin
Result := GetArrayDoubleValue(fFloatRet, AIndex);
end;
end;
end;
function TRule_CORREL.Get_CORREL_ValueI(AIndex: integer): Int64;
begin
Result := 0;
if fBaseRuleData.DataType = dtInt64 then
begin
if fInt64Ret <> nil then
begin
Result := GetArrayInt64Value(fInt64Ret, AIndex);
end;
end;
end;
end.
|
{
Unified Optional Header.
Represents both 32 and 64 bit.
Directories not included.
}
unit PE.Headers;
interface
uses
System.Classes;
type
{ **********************************************************************************************************************
* Comparision of optional headers
**********************************************************************************************************************
* TImageOptionalHeader32 = packed record TImageOptionalHeader64 = packed record
*
* // Standard fields. // Standard fields.
* Magic : uint16; Magic : uint16;
*
* MajorLinkerVersion : uint8; MajorLinkerVersion : uint8;
* MinorLinkerVersion : uint8; MinorLinkerVersion : uint8;
* SizeOfCode : uint32; SizeOfCode : uint32;
* SizeOfInitializedData : uint32; SizeOfInitializedData : uint32;
* SizeOfUninitializedData : uint32; SizeOfUninitializedData : uint32;
* AddressOfEntryPoint : uint32; AddressOfEntryPoint : uint32;
* BaseOfCode : uint32; BaseOfCode : uint32;
*
* BaseOfData : uint32; // PE32 only
*
* // NT additional fields. // NT additional fields.
* ImageBase : uint32; ImageBase : uint64;
*
* SectionAlignment : uint32; SectionAlignment : uint32;
* FileAlignment : uint32; FileAlignment : uint32;
* MajorOperatingSystemVersion : uint16; MajorOperatingSystemVersion : uint16;
* MinorOperatingSystemVersion : uint16; MinorOperatingSystemVersion : uint16;
* MajorImageVersion : uint16; MajorImageVersion : uint16;
* MinorImageVersion : uint16; MinorImageVersion : uint16;
* MajorSubsystemVersion : uint16; MajorSubsystemVersion : uint16;
* MinorSubsystemVersion : uint16; MinorSubsystemVersion : uint16;
* Win32VersionValue : uint32; Win32VersionValue : uint32;
* SizeOfImage : uint32; SizeOfImage : uint32;
* SizeOfHeaders : uint32; SizeOfHeaders : uint32;
* CheckSum : uint32; CheckSum : uint32;
* Subsystem : uint16; Subsystem : uint16;
* DllCharacteristics : uint16; DllCharacteristics : uint16;
*
* SizeOfStackReserve : uint32; SizeOfStackReserve : uint64;
* SizeOfStackCommit : uint32; SizeOfStackCommit : uint64;
* SizeOfHeapReserve : uint32; SizeOfHeapReserve : uint64;
* SizeOfHeapCommit : uint32; SizeOfHeapCommit : uint64;
*
* LoaderFlags : uint32; LoaderFlags : uint32;
* NumberOfRvaAndSizes : uint32; NumberOfRvaAndSizes : uint32;
*
* DataDirectories : TImageDataDirectories; DataDirectories : TImageDataDirectories;
* end; end;
**********************************************************************************************************************
}
UIntCommon = uint64;
TPEOptionalHeader = packed record
// Standard fields.
Magic: uint16;
MajorLinkerVersion: uint8;
MinorLinkerVersion: uint8;
SizeOfCode: uint32;
SizeOfInitializedData: uint32;
SizeOfUninitializedData: uint32;
AddressOfEntryPoint: uint32;
BaseOfCode: uint32;
// PE32 only
BaseOfData: uint32;
// NT additional fields.
ImageBase: UIntCommon;
SectionAlignment: uint32;
FileAlignment: uint32;
MajorOperatingSystemVersion: uint16;
MinorOperatingSystemVersion: uint16;
MajorImageVersion: uint16;
MinorImageVersion: uint16;
MajorSubsystemVersion: uint16;
MinorSubsystemVersion: uint16;
Win32VersionValue: uint32;
SizeOfImage: uint32;
SizeOfHeaders: uint32;
CheckSum: uint32;
Subsystem: uint16;
DllCharacteristics: uint16;
SizeOfStackReserve: UIntCommon;
SizeOfStackCommit: UIntCommon;
SizeOfHeapReserve: UIntCommon;
SizeOfHeapCommit: UIntCommon;
LoaderFlags: uint32;
NumberOfRvaAndSizes: uint32;
// Return number of bytes read.
function ReadFromStream(Stream: TStream; ImageBits: uint32; MaxSize: integer): uint32;
// Return number of bytes written.
function WriteToStream(Stream: TStream; ImageBits: uint32; MaxSize: integer): uint32;
// Calcualte size of normal optional header.
function CalcSize(ImageBits: uint32): uint32;
end;
PPEOptionalHeader = ^TPEOptionalHeader;
implementation
uses
System.SysUtils,
PE.RTTI;
const
RF_SIZE8 = 1 shl 0;
RF_SIZE16 = 1 shl 1;
RF_SIZE32 = 1 shl 2;
RF_SIZE64 = 1 shl 3;
RF_SIZEMACHINE = 1 shl 4; // Size is (32 or 64) in 64 bit slot.
RF_PE32 = 1 shl 5; // Present in 32-bit image.
RF_PE64 = 1 shl 6; // Present in 64-bit image.
RF_PE3264 = RF_PE32 or RF_PE64;
COMMON_08 = RF_SIZE8 or RF_PE3264;
COMMON_16 = RF_SIZE16 or RF_PE3264;
COMMON_32 = RF_SIZE32 or RF_PE3264;
COMMON_MACHINE = RF_SIZEMACHINE or RF_PE3264;
const
MACHINE_DWORD_SIZE = -1;
OptionalHeaderFieldDesc: packed array [0 .. 29] of TRecordFieldDesc =
(
(Flags: COMMON_16; FieldName: 'Magic'),
(Flags: COMMON_08; FieldName: 'MajorLinkerVersion'),
(Flags: COMMON_08; FieldName: 'MinorLinkerVersion'),
(Flags: COMMON_32; FieldName: 'SizeOfCode'),
(Flags: COMMON_32; FieldName: 'SizeOfInitializedData'),
(Flags: COMMON_32; FieldName: 'SizeOfUninitializedData'),
(Flags: COMMON_32; FieldName: 'AddressOfEntryPoint'),
(Flags: COMMON_32; FieldName: 'BaseOfCode'),
(Flags: RF_SIZE32 or RF_PE32; FieldName: 'BaseOfData'),
(Flags: COMMON_MACHINE; FieldName: 'ImageBase'),
(Flags: COMMON_32; FieldName: 'SectionAlignment'),
(Flags: COMMON_32; FieldName: 'FileAlignment'),
(Flags: COMMON_16; FieldName: 'MajorOperatingSystemVersion'),
(Flags: COMMON_16; FieldName: 'MinorOperatingSystemVersion'),
(Flags: COMMON_16; FieldName: 'MajorImageVersion'),
(Flags: COMMON_16; FieldName: 'MinorImageVersion'),
(Flags: COMMON_16; FieldName: 'MajorSubsystemVersion'),
(Flags: COMMON_16; FieldName: 'MinorSubsystemVersion'),
(Flags: COMMON_32; FieldName: 'Win32VersionValue'),
(Flags: COMMON_32; FieldName: 'SizeOfImage'),
(Flags: COMMON_32; FieldName: 'SizeOfHeaders'),
(Flags: COMMON_32; FieldName: 'CheckSum'),
(Flags: COMMON_16; FieldName: 'Subsystem'),
(Flags: COMMON_16; FieldName: 'DllCharacteristics'),
(Flags: COMMON_MACHINE; FieldName: 'SizeOfStackReserve'),
(Flags: COMMON_MACHINE; FieldName: 'SizeOfStackCommit'),
(Flags: COMMON_MACHINE; FieldName: 'SizeOfHeapReserve'),
(Flags: COMMON_MACHINE; FieldName: 'SizeOfHeapCommit'),
(Flags: COMMON_32; FieldName: 'LoaderFlags'),
(Flags: COMMON_32; FieldName: 'NumberOfRvaAndSizes')
);
type
TPECtx = record
ImageBits: uint32;
end;
PPECtx = ^TPECtx;
procedure ResolveProc(Desc: PRecordFieldDesc; OutFieldSize, OutEffectiveSize: PInteger; ud: pointer);
begin
OutFieldSize^ := 0;
OutEffectiveSize^ := 0;
// OutFieldSize (mandatory)
if ((Desc^.Flags and RF_SIZE8) <> 0) then
OutFieldSize^ := 1
else if ((Desc^.Flags and RF_SIZE16) <> 0) then
OutFieldSize^ := 2
else if ((Desc^.Flags and RF_SIZE32) <> 0) then
OutFieldSize^ := 4
else if ((Desc^.Flags and RF_SIZE64) <> 0) then
OutFieldSize^ := 8
else if ((Desc^.Flags and RF_SIZEMACHINE) <> 0) then
OutFieldSize^ := SizeOf(UIntCommon)
else
raise Exception.Create('Unsupported image.');
if ((Desc^.Flags and RF_PE3264) = RF_PE32) and (PPECtx(ud)^.ImageBits <> 32) then
exit;
if ((Desc^.Flags and RF_PE3264) = RF_PE64) and (PPECtx(ud)^.ImageBits <> 64) then
exit;
// OutEffectiveSize
if ((Desc^.Flags and RF_SIZE8) <> 0) then
OutEffectiveSize^ := 1
else if ((Desc^.Flags and RF_SIZE16) <> 0) then
OutEffectiveSize^ := 2
else if ((Desc^.Flags and RF_SIZE32) <> 0) then
OutEffectiveSize^ := 4
else if ((Desc^.Flags and RF_SIZE64) <> 0) then
OutEffectiveSize^ := 8
else if ((Desc^.Flags and RF_SIZEMACHINE) <> 0) then
OutEffectiveSize^ := PPECtx(ud)^.ImageBits div 8
else
raise Exception.Create('Unsupported image.');
end;
{ TPEOptionalHeader }
function TPEOptionalHeader.CalcSize(ImageBits: uint32): uint32;
var
ctx: TPECtx;
begin
ctx.ImageBits := ImageBits;
Result := RTTI_Process(nil, RttiCalcSize, @Self,
@OptionalHeaderFieldDesc[0], Length(OptionalHeaderFieldDesc),
-1,
ResolveProc,
@ctx);
end;
function TPEOptionalHeader.ReadFromStream;
var
ctx: TPECtx;
begin
// Not all fields can be read, so must clear whole structure.
FillChar(Self, SizeOf(Self), 0);
ctx.ImageBits := ImageBits;
Result := RTTI_Process(Stream, RttiRead, @Self,
@OptionalHeaderFieldDesc[0], Length(OptionalHeaderFieldDesc),
MaxSize,
ResolveProc,
@ctx);
end;
function TPEOptionalHeader.WriteToStream;
var
ctx: TPECtx;
begin
ctx.ImageBits := ImageBits;
Result := RTTI_Process(Stream, RttiWrite, @Self,
@OptionalHeaderFieldDesc[0], Length(OptionalHeaderFieldDesc),
MaxSize,
ResolveProc,
@ctx);
end;
end.
|
unit ResConvertMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm5 = class(TForm)
edtDesignY: TEdit;
edtDesignX: TEdit;
edtScreenHeight: TEdit;
edtScreenWidth: TEdit;
lbl1: TLabel;
lbl2: TLabel;
lbl3: TLabel;
lbl4: TLabel;
edtDesignHeight: TEdit;
edtDesignWidth: TEdit;
lbl5: TLabel;
lbl6: TLabel;
edtConvertedY: TEdit;
edtConvertedX: TEdit;
lbl7: TLabel;
lbl8: TLabel;
procedure edtDesignXChange(Sender: TObject);
procedure edtDesignYChange(Sender: TObject);
private
{ Private declarations }
FDesignWidth, FDesignHeight, FScreenWidth, FScreenHeight: Integer;
function GetParameters: Boolean;
public
{ Public declarations }
end;
var
Form5: TForm5;
implementation
{$R *.dfm}
procedure TForm5.edtDesignXChange(Sender: TObject);
var
X: Integer;
CX: Double;
begin
if GetParameters then
begin
try
X := StrToInt(edtDesignX.Text);
CX := X * FScreenWidth / FDesignWidth;
edtConvertedX.Text := FloatToStr(CX);
except
end;
end;
end;
procedure TForm5.edtDesignYChange(Sender: TObject);
var
Y: Integer;
CY: Double;
begin
if GetParameters then
begin
try
Y := StrToInt(edtDesignY.Text);
CY := Y * FScreenHeight / FDesignHeight;
edtConvertedY.Text := FloatToStr(CY);
except
end;
end;
end;
function TForm5.GetParameters: Boolean;
begin
try
FDesignWidth := StrToInt(edtDesignWidth.Text);
FDesignHeight := StrToInt(edtDesignHeight.Text);
FScreenWidth := StrToInt(edtScreenWidth.Text);
FScreenHeight := StrToInt(edtScreenHeight.Text);
Result := True;
except
Result := False;
end;
end;
end.
|
{ *************************************************************************** }
{ }
{ }
{ Copyright (C) Amarildo Lacerda }
{ }
{ https://github.com/amarildolacerda }
{ }
{ }
{ *************************************************************************** }
{ }
{ 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. }
{ }
{ *************************************************************************** }
{
Amarildo Lacerda
03/10/2016
pluginService - Utilizado no plugin a ser consumido pelo Manager.
}
{$D+}
unit Plugin.Service;
interface
uses WinApi.Windows, System.Classes, System.SysUtils, WinApi.Messages,
{$IFDEF FMX} FMX.Forms, FMX.Controls, System.UITypes, {$ELSE} VCL.Forms,
VCL.Controls, {$ENDIF}
Plugin.Interf,
System.Generics.collections;
Type
// List of plugins
TPluginItemsInterfacedClass = class of TPluginItemsInterfaced;
TPluginItemsInterfaced = class(TInterfacedObject, IPluginItems)
protected
FItems: TInterfaceList; // <IPluginInfo>;
public
constructor Create;
destructor Destroy; override;
procedure Connection(const AConnectionString: string); virtual;
function Count: integer;
function GetItem(idx: integer): IPluginInfo;
procedure Add(APlugin: IPluginInfo);
procedure Install; virtual;
procedure UnInstall; virtual;
end;
// plugin base
TPluginService = class(TComponent, IPluginInfo)
private
FTypeID: Int64;
FParentHandle: THandle;
protected
FForm: TForm;
FOwned: boolean;
function GetTypeID: Int64; virtual;
procedure SetTypeID(const Value: Int64); virtual;
procedure Perform(AMsg: Cardinal; WParam: NativeUInt; LParam: NativeUInt);
procedure SetPosition(ATop, ALeft, AWidth, AHeight: integer); virtual;
procedure InitEmbedded;
public
function GetVersion: integer;
constructor Create; overload;
destructor Destroy; override;
function GetAuthor: string; virtual;
procedure DoStart; virtual;
function GetInterface: IPluginExecuteBase; virtual;
function PluginName: string; virtual;
procedure Embedded(const AParent: THandle); overload; virtual;
function CanClose: boolean; virtual;
{$IFDEF FMX}
{$ELSE}
function GetControl: TControl; virtual;
{$ENDIF}
{$IFNDEF DLL}
{$IFDEF FMX}
{$ELSE}
function EmbeddedControl(const FParent: TWinControl): boolean;
overload; virtual;
{$ENDIF}
{$ENDIF}
class function OwnedComponents: TComponent;
published
property TypeID: Int64 read GetTypeID write SetTypeID;
end;
// register one plugin to list of plugins
procedure RegisterPlugin(AInfo: IPluginInfo);
procedure RegisterPluginClass(AClass: TPluginItemsInterfacedClass);
// exported plugins from DLL
// return list of plugins in DLL
function LoadPlugin(AAplication: IPluginApplication): IPluginItems;
// exported unload plugins
procedure UnloadPlugin;
function GetPluginItems: IPluginItems;
var
PluginExitProc: TProc;
PluginEnterProc: TProc;
implementation
var
LPlugin: IPluginItems;
LPluginClass: TPluginItemsInterfacedClass;
FOwnedComponents: TComponent;
procedure RegisterPluginClass(AClass: TPluginItemsInterfacedClass);
begin
LPluginClass := AClass;
end;
function GetPluginItems: IPluginItems;
begin
result := LPlugin;
end;
{ TPluginService<T> }
function TPluginService.GetAuthor: string;
begin
result := 'storeware';
end;
{$IFDEF FMX}
{$ELSE}
function TPluginService.GetControl: TControl;
begin
result := nil;
{$IFNDEF DLL}
result := FForm;
{$ENDIF}
end;
{$ENDIF}
function TPluginService.GetInterface: IPluginExecuteBase;
begin
if Supports(FForm, IPluginExecuteBase) then
result := FForm as IPluginExecuteBase;
end;
destructor TPluginService.Destroy;
begin
FreeAndNil(FForm);
inherited;
end;
procedure TPluginService.DoStart;
begin
end;
{$IFDEF FMX}
{$ELSE}
{$IFNDEF DLL}
function TPluginService.EmbeddedControl(const FParent: TWinControl): boolean;
begin
result := false;
{$IFNDEF DLL}
InitEmbedded;
if assigned(FForm) then
begin
FForm.parent := FParent;
FForm.show;
result := true;
end;
{$ENDIF}
end;
{$ENDIF}
{$ENDIF}
function TPluginService.PluginName: string;
begin
if assigned(FForm) then
result := FForm.Caption
else
result := self.Name;
end;
procedure TPluginService.Perform(AMsg: Cardinal; WParam, LParam: NativeUInt);
var
WindRect: TRect;
begin
if assigned(FForm) then
begin
{$IFDEF FMX}
{$ELSE}
FForm.Perform(AMsg, WParam, LParam);
{$ENDIF}
end;
end;
procedure TPluginService.SetPosition(ATop, ALeft, AWidth, AHeight: integer);
begin
if assigned(FForm) then
begin
FForm.Left := ALeft;
FForm.Top := ATop;
{$IFDEF FMX}
{$ELSE}
FForm.Align := alClient;
FForm.AlignWithMargins := true;
FForm.Constraints.MaxHeight := AHeight - (ALeft);
FForm.Constraints.MinHeight := AHeight - (ALeft);
FForm.Constraints.MaxWidth := AWidth - (ATop);
FForm.Constraints.MinWidth := AWidth - (ATop);
{$ENDIF}
FForm.Invalidate;
end;
end;
procedure TPluginService.SetTypeID(const Value: Int64);
begin
FTypeID := Value;
end;
function TPluginService.GetTypeID: Int64;
begin
result := FTypeID;
end;
function TPluginService.GetVersion: integer;
begin
result := constPluginInterfaceVersion;
end;
procedure TPluginService.InitEmbedded;
begin
if not assigned(FForm) then
exit;
// ShowWindowAsync(FForm.Handle, SW_MAXIMIZE);
FForm.Left := 0;
FForm.Top := 0;
FForm.BorderIcons := [];
{$IFDEF FMX}
FForm.WindowState := TWindowState.wsMaximized;
{$ELSE}
FForm.BorderStyle := bsNone;
FForm.Align := alClient;
{$ENDIF}
end;
class function TPluginService.OwnedComponents: TComponent;
begin
result := FOwnedComponents;
end;
function TPluginService.CanClose: boolean;
begin
result := true;
if not assigned(FForm) then
exit;
if Supports(FForm, IPluginExecuteBase) then
result := (FForm as IPluginExecuteBase).CanClose
else
begin
result := FForm.CloseQuery;
end;
end;
constructor TPluginService.Create;
begin
inherited Create(nil);
// PluginService := self;
end;
procedure TPluginService.Embedded(const AParent: THandle);
begin
FParentHandle := AParent;
InitEmbedded;
if assigned(FForm) then
begin
WinApi.Windows.SetParent(HWND(FForm.Handle), AParent);
FForm.show;
end;
end;
function LoadPlugin(AAplication: IPluginApplication): IPluginItems;
var
i: integer;
begin
PluginApplication := AAplication;
result := LPlugin;
for i := 0 to result.Count - 1 do
result.GetItem(i).DoStart;
if assigned(PluginEnterProc) then
PluginEnterProc;
end;
procedure UnloadPlugin;
var
i: integer;
begin
{$IFDEF DLL}
PluginApplication := nil;
{$ELSE}
{$ENDIF}
if assigned(PluginExitProc) then
PluginExitProc;
Application.ProcessMessages;
end;
procedure RegisterPlugin(AInfo: IPluginInfo);
begin
if not assigned(LPlugin) then
LPlugin := LPluginClass.Create;
LPlugin.Add(AInfo);
end;
{ TPluginInterfaced }
procedure TPluginItemsInterfaced.Add(APlugin: IPluginInfo);
begin
FItems.Add(APlugin);
end;
procedure TPluginItemsInterfaced.Connection(const AConnectionString: string);
begin
end;
function TPluginItemsInterfaced.Count: integer;
begin
result := FItems.Count;
end;
constructor TPluginItemsInterfaced.Create;
begin
inherited;
FItems := { TList<IPluginInfo> } TInterfaceList.Create;
end;
destructor TPluginItemsInterfaced.Destroy;
var
i: IPluginInfo;
x: IInterface;
ob: TObject;
begin
while FItems.Count > 0 do
begin
try
i := FItems.Items[0] as IPluginInfo;
// x := i.GetInterface;
// x := nil;
i := nil;
FItems.delete(0);
except
end;
end;
FItems.Free;
inherited;
end;
function TPluginItemsInterfaced.GetItem(idx: integer): IPluginInfo;
begin
result := FItems.Items[idx] as IPluginInfo;
end;
procedure TPluginItemsInterfaced.Install;
begin
end;
procedure TPluginItemsInterfaced.UnInstall;
begin
end;
exports LoadPlugin, UnloadPlugin;
initialization
RegisterPluginClass(TPluginItemsInterfaced);
FOwnedComponents := TComponent.Create(nil);
finalization
{$IFDEF DLL}
// LPlugin := nil;
{$ENDIF}
FOwnedComponents.DisposeOf;
end.
|
unit Unit1;
{
Dieses kleine Demo soll demonstrieren, wie man eine Paintbox richtig benützt.
Es darf kostenlos kopiert und verändert (bitte nur verbessern) werden.
Author: shmia@DelphiPraxis.net
}
interface
uses
Windows, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ComCtrls;
type
TLights = 1..3;
TForm1 = class(TForm)
PaintBox1: TPaintBox;
Panel1: TPanel;
RgpColor: TRadioGroup;
TrackBarHor: TTrackBar;
procedure PaintBox1Paint(Sender: TObject);
procedure RgpColorClick(Sender: TObject);
procedure TrackBarHorChange(Sender: TObject);
private
{ Private-Deklarationen }
function GetColor(IdxLight:TLights):TColor;
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
// Farbe für den 1. , 2. oder 3. Kreis zurückliefern
function TForm1.GetColor(IdxLight: TLights): TColor;
var
RIndex : Integer; // Index der Radio-Group
begin
RIndex := RgpColor.ItemIndex;
case IdxLight of
1:
begin
if (RIndex = 0) or (RIndex=3) then
Result := clRed
else
Result := clDkGray;
end;
2:
begin
if (RIndex = 1) or (RIndex=3) then
Result := clYellow
else
Result := clDkGray;
end;
3:
begin
if RIndex = 2 then
Result := clGreen
else
Result := clDkGray;
end;
end;
end;
// Das OnPaint-Event ist die zentrale Stelle, an der auf die Paintbox
// gezeichnet werden darf
// Man darf die Paintbox nur innerhalb dieses Eventhandlers ansprechen
// Zeichnet man ausserhalb diese Methode, dann verschwindet das
// was man gezeichnet hat, sobald ein neue WM_PAINT Event eintrifft.
procedure TForm1.PaintBox1Paint(Sender: TObject);
const
DURCHMESSER = 40;
var
canvas : TCanvas;
r2 : TRect;
x, y : Integer;
begin
// Wichtig: wir besorgen uns zuerst den Canvas der Paintbox
// das spart viel Schreibarbeit und vereinfacht den Code
canvas := (Sender as TPaintBox).Canvas;
x := TrackBarHor.Position;
y := 10;
// rotes Licht
r2 := Rect(x, y, x+DURCHMESSER, y+DURCHMESSER);
canvas.Brush.Color := GetColor(1);
canvas.Ellipse(r2);
// gelbes Licht
OffsetRect(r2, 0, 50);
canvas.Brush.Color := GetColor(2);
canvas.Ellipse(r2);
// grünes Licht
OffsetRect(r2, 0, 50);
canvas.Brush.Color := GetColor(3);
canvas.Ellipse(r2);
// Uhrzeit ausgeben
canvas.Brush.Color := clWhite;
canvas.TextOut(PaintBox1.Width div 2 - 25, 70, FormatDateTime('hh:nn:ss.zzz',now));
end;
procedure TForm1.RgpColorClick(Sender: TObject);
begin
// Nachdem die Aktive Checkbox geändert wurde
// müssen wir noch dafür sorgen, dass die Paintbox neu gezeichnet wird
PaintBox1.Invalidate;
end;
procedure TForm1.TrackBarHorChange(Sender: TObject);
begin
// Paintbox neu zeichnen, wenn Hor. Position sich ändert
PaintBox1.Invalidate;
end;
end.
|
unit csServerTaskTypes;
interface
uses
csProcessTask,
Classes, ActnList,
CsDataPipe,
dt_Types,
l3ObjectRefList, l3Date, CsNotification, csCommandsTypes, ddProgressObj;
type
TDictRec = record
Family : Integer;
DictType : Integer;
Operation : Integer;
ID,
ParentID,
NextID : LongInt;
end;
TDictEditQuery = class(TddProcessTask)
public
constructor Create(aOwner: TObject; aUserID: TUserID); override;
procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override;
procedure SaveTo(aStream: TStream; aIsPipe: Boolean); override;
public
DictInfo: TDictRec;
end;
TGetDictEditQuery = class(TDictEditQuery)
public
procedure SaveToPipe(aPipe: TCsDataPipe); override;
end;
TUserEditQuery = class(TddProcessTask)
private
f_ID: TUserID;
f_IsGroup: Boolean;
public
constructor Create(aOwner: TObject; aUserID: TUserID); override;
procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override;
procedure SaveTo(aStream: TStream; aIsPipe: Boolean); override;
property ID: TUserID read f_ID write f_ID;
property IsGroup: Boolean read f_IsGroup write f_IsGroup;
end;
TRemoteDictEditQuery = class(TddProcessTask)
private
f_Data: PAnsiChar;
f_FreeData: Boolean;
procedure pm_SetData(const aValue: PAnsiChar);
protected
procedure Cleanup; override;
function DataSize: Word;
public
constructor Create(aOwner: TObject; aUserID: TUserID);
function _GetName: AnsiString;
procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override;
procedure SaveTo(aStream: TStream; aIsPipe: Boolean); override;
public
Family : Integer;
DictType : Integer;
Operation : Integer;
ID,
ParentID,
NextID : TDictID;
NameCyr, NameShort, NameLat: AnsiString;
IsPrivate : TIsPrivate;
IsNonPeriodic: TIsNonperiodic;
DateToDelete : TstDate;
property Data: PAnsiChar read f_Data write pm_SetData;
end;
TDocArray = array of Longint;
TDeleteDocsQuery = class(TddProcessTask)
private
procedure pm_SetDocs(const Value: TDocArray);
public
constructor Create(aOwner: TObject; aUserID: TUserID); override;
property Docs: TDocArray write pm_SetDocs;
end;
TddRunCommandTask = class(TddProcessTask)
private
f_Command: TcsCommand;
protected
procedure DoRun(aProgressor: TddProgressObject); override;
public
constructor Create(aOwner: TObject; aUserID: TUserID); override;
property Command: TcsCommand read f_Command write f_Command;
end;
TalcuFNSExport = class(TddProcessTask)
protected
function GetDescription: AnsiString; override;
public
constructor Create(aOwner: TObject; aUserID: TUserID); override;
end;
TddAutoExportTask = class(TddProcessTask)
protected
function GetDescription: AnsiString; override;
procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override;
public
constructor Create(aOwner: TObject; aUserID: TUserID); override;
end;
TalcuAnnotationTaskItem = class(TddProcessTask)
protected
function GetDescription: AnsiString; override;
procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override;
public
constructor Create(aOwner: TObject; aUserID: TUserID); override;
end;
implementation
uses
CsTaskTypes, DT_Const, dt_AttrSchema, l3TempMemoryStream, l3Base, SysUtils, ddUtils, l3FileUtils,
dt_DictConst, dt_DictTypes, DT_UserConst, l3Memory, StrUtils, DateUtils,
ddServerTask;
procedure TGetDictEditQuery.SaveToPipe(aPipe: TCsDataPipe);
begin
aPipe.Write(Index);
with aPipe, DictInfo do
begin
Family := ReadInteger;
DictType := ReadInteger;
Operation := ReadInteger;
ID := ReadInteger;
ParentID := ReadInteger;
NextID := ReadInteger;
end;
end;
{
******************************** TddProcessTask ********************************
}
constructor TDictEditQuery.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
TaskType := cs_ttDictEdit;
end;
procedure TDictEditQuery.LoadFrom(aStream: TStream; aIsPipe: Boolean);
begin
inherited;
with aStream, DictInfo do
begin
Read(Family, SizeOf(Family));
Read(DictType, SizeOf(Integer));
Read(Operation, SizeOf(Integer));
Read(ID, SizeOf(Integer));
Read(ParentID, SizeOf(Integer));
Read(NextID, SizeOf(Integer));
end;
end;
procedure TDictEditQuery.SaveTo(aStream: TStream; aIsPipe: Boolean);
begin
inherited;
with aStream, DictInfo do
begin
Write(Family, SizeOf(Family));
Write(DictType, SizeOf(Integer));
Write(Operation, SizeOf(Integer));
Write(ID, SizeOf(Integer));
Write(ParentID, SizeOf(Integer));
Write(NextID, SizeOf(Integer));
end;
end;
constructor TUserEditQuery.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
TaskType := cs_ttUserEdit;
end;
procedure TUserEditQuery.LoadFrom(aStream: TStream; aIsPipe: Boolean);
begin
inherited;
aStream.Read(f_IsGroup, SizeOf(f_IsGroup));
aStream.Read(f_ID, SizeOf(f_ID));
end;
procedure TUserEditQuery.SaveTo(aStream: TStream; aIsPipe: Boolean);
begin
inherited;
aStream.Write(f_IsGroup, SizeOf(f_IsGroup));
aStream.Write(f_ID, SizeOf(f_ID));
end;
{
******************************** TddProcessTask ********************************
}
constructor TRemoteDictEditQuery.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
TaskType := cs_ttRemoteDictEdit;
ID:= cUndefDictID;
ParentID:= cUndefDictID;
NextID:= cUndefDictID;
IsNonPeriodic:= cEmptyByte;
IsPrivate:= cEmptyByte;
f_FreeData:= False;
end;
procedure TRemoteDictEditQuery.Cleanup;
begin
inherited;
if f_FreeData then
FreeMem(Data);
end;
function TRemoteDictEditQuery.DataSize: Word;
begin
case TDLType(DictType) of
(*
dlDateNums: l_DataSize:= SizeOf(TDNDictRec);
TCorrectDictRec = record
TPublishedDictRec = packed record
TPublishedUniqueKeyRec = packed record
*)
dlPublisheds: Result:= SizeOf(TPublishedDictRec);
dlSources: Result:= SizeOf(TSourDictRec);
dlNewClasses: Result:= SizeOf(TNewClassDictRec);
else
Result:= SizeOF(TDictMessageRec)
end;
end;
function TRemoteDictEditQuery._GetName: AnsiString;
begin
(*
if Data = nil then
begin
if ID = cUndefDictID then
Result := NameCyr
else
Result:= Result:= IfThen(NameCyr <> '', NameCyr, DictServer.Dict[TDLType(DictType)].DictTbl.getNameR(ID));
end
else
case TDLType(DictType) of
{ TODO -oДмитрий Дудко -cЕдиный КВ : Расширить }
dlsources: Result:= TrimRight(PSourDictRec(Data)^.FNameR);
else
Result:= ''
end;
*)
end;
procedure TRemoteDictEditQuery.LoadFrom(aStream: TStream; aIsPipe: Boolean);
var
l_DataSize: Integer;
begin
inherited;
with aStream do
begin
Read(Family, SizeOf(Family));
Read(DictType, SizeOf(Integer));
Read(Operation, SizeOf(Integer));
Read(ID, SizeOf(ID));
Read(ParentID, SizeOf(ParentID));
Read(NextID, SizeOf(NextID));
ReadString(aStream, NameCyr);
ReadString(aStream, NameShort);
ReadString(aStream, NameLat);
Read(IsPrivate, SizeOf(IsPrivate));
Read(IsNonPeriodic, SizeOf(IsNonPeriodic));
Read(DateToDelete, SizeOf(TstDate));
Read(l_DataSize, SizeOF(l_DataSize));
f_FreeData:= True;
GetMem(f_Data, l_DataSize);
Read(f_Data[0], l_DataSize);
end; // with aStream
end;
procedure TRemoteDictEditQuery.pm_SetData(const aValue: PAnsiChar);
var
l_DataSize: Word;
begin
f_FreeData:= True;
l_DataSize:= DataSize;
GetMem(f_Data, l_DataSize);
l3Move(aValue[0], f_Data[0], l_DataSize);
end;
procedure TRemoteDictEditQuery.SaveTo(aStream: TStream; aIsPipe: Boolean);
var
l_DataSize: Integer;
begin
inherited;
with aStream do
begin
Write(Family, SizeOf(Family));
Write(DictType, SizeOf(Integer));
Write(Operation, SizeOf(Integer));
Write(ID, SizeOf(ID));
Write(ParentID, SizeOf(ParentID));
Write(NextID, SizeOf(NextID));
WriteString(aStream, NameCyr);
WriteString(aStream, NameShort);
WriteString(aStream, NameLat);
Write(IsPrivate, SizeOf(IsPrivate));
write(IsNonPeriodic, SizeOf(IsNonPeriodic));
Write(DateToDelete, SizeOf(TstDate));
if Data <> nil then
begin
l_DataSize:= DataSize;
Write(l_DataSize, SizeOF(l_DataSize));
Write(Data[0], l_DataSize);
end;
end; // with aStream
end;
{
******************************** TddProcessTask ********************************
}
constructor TDeleteDocsQuery.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
TaskType := cs_ttDeleteDocs;
end;
procedure TDeleteDocsQuery.pm_SetDocs(const Value: TDocArray);
var
index: Integer;
begin
DocumentIDList.Clear;
for index := 0 to pred(Length(Value)) do
DocumentIDList.Add(Value[index]);
end;
constructor TddRunCommandTask.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
TaskType := cs_ttRunCommand;
end;
procedure TddRunCommandTask.DoRun(aProgressor: TddProgressObject);
begin
f_Command.Execute(Self);
end;
constructor TalcuFNSExport.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
TaskType := cs_ttFNSExport;
USerID := usServerService;
end;
function TalcuFNSExport.GetDescription: AnsiString;
begin
Result:= 'Экспорт документов для ФНС России'
end;
constructor TddAutoExportTask.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
TaskType := cs_ttAExportDoc;
end;
function TddAutoExportTask.GetDescription: AnsiString;
begin
Result:= 'Автоматический экспорт документов и аннотаций'
end;
procedure TddAutoExportTask.LoadFrom(aStream: TStream; aIsPipe: Boolean);
begin
inherited;
if aIsPipe then
UserID := usServerService;
end;
constructor TalcuAnnotationTaskItem.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
TaskType := cs_ttAnnoExport;
end;
function TalcuAnnotationTaskItem.GetDescription: AnsiString;
begin
Result:= 'Экспорт аннотаций конечным пользователям'
end;
procedure TalcuAnnotationTaskItem.LoadFrom(aStream: TStream; aIsPipe: Boolean);
begin
inherited;
if aIsPipe then
UserID := usServerService;
end;
initialization
{!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\cs\csServerTaskTypes.pas initialization enter'); {$EndIf}
RegisterTaskClass(cs_ttAutoClass, TddProcessTask, 'автоклассификация документов');
RegisterTaskClass(cs_ttAnnoExport, TalcuAnnotationTaskItem, 'экспорт специальных аннотаций');
RegisterTaskClass(cs_ttDictEdit, TDictEditQuery, 'изменение словаря');
RegisterTaskClass(cs_ttFNSExport, TalcuFNSExport, 'экпорт для ФНС');
RegisterTaskClass(cs_ttUserEdit, TUserEditQuery, 'изменения данных пользователей');
RegisterTaskClass(cs_ttDeleteDocs, TDeleteDocsQuery, 'Удаление документов');
RegisterTaskClass(cs_ttAExportDoc, TddAutoExportTask, 'Автоматический экспорт документов');
RegisterTaskClass(cs_ttRemoteDictEdit, TRemoteDictEditQuery, 'Удаленное редактирование словарей');
RegisterTaskClass(cs_ttRunCommand, TddRunCommandTask, 'Выполнение команды на сервере');
{!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\cs\csServerTaskTypes.pas initialization leave'); {$EndIf}
end.
|
Unit Spline;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
interface
uses
CoreTypes, Math, SysUtils;
function __Tangent(const p0,p1:TFPoint; T:Extended): TFPoint; Inline;
function Tangents(const Points:TFPointArray; Tension:Extended): TFPointArray; Inline;
function Interpolate(t:Extended; const p0,m0,p1,m1:TFPoint): TFPoint; Inline;
function CSPlinePoints(const p0,m0,p1,m1:TFPoint): TFPointArray; Inline;
function CSplineTFPA(const Pts:TFPointArray; Tension:Extended): TFPointArray;
function CSpline(TPA:TPointArray; Tension:Extended; Connect:Boolean): TPointArray;
//--------------------------------------------------
implementation
uses
PointTools;
function __Tangent(const p0,p1:TFPoint; T:Extended): TFPoint; Inline;
begin
Result := FPoint(T * (p1.x - p0.x), T * (p1.y - p0.y));
end;
function Tangents(const Points:TFPointArray; Tension:Extended): TFPointArray; Inline;
var
L,i: Integer;
begin
L := Length(points);
if L = 0 then Exit;
if L = 1 then
begin
SetLength(Result, 1);
Result[0] := Points[0];
Exit;
end;
SetLength(Result, L);
Result[0] := __Tangent(points[0], points[1], tension);
for i:=1 to L-2 do
Result[i] := __Tangent(points[i-1], points[i+1], tension);
Result[L-1] := __Tangent(points[L-2], points[L-1], tension);
end;
function Interpolate(t:Extended; const p0,m0,p1,m1:TFPoint): TFPoint; Inline;
var
fa,fb,fc,fd:Extended;
begin
fA := ((1 + 2 * t) * Sqr(1 - t));
fB := (t * Sqr(1 - t));
fC := (Sqr(t) * (3 - 2 * t));
fD := (Sqr(t) * (t - 1));
Result.x := (p0.x*fA) + (m0.x*fB) + (p1.x*fC) + (m1.x*fD);
Result.y := (p0.y*fA) + (m0.y*fB) + (p1.y*fC) + (m1.y*fD);
end;
function CSPlinePoints(const p0,m0,p1,m1:TFPoint): TFPointArray; Inline;
var
L,i: Integer;
domain, delta, t:Extended;
Pt,Last: TFPoint;
begin
Domain := Max(Abs(p0.x - p1.x), Abs(p0.y - p1.y));
Delta := 1.0 / Domain;
Last := Interpolate(0, p0, m0, p1, m1);
SetLength(Result, 1);
Result[0] := Last;
L := 1;
T := Delta;
i := 0;
while (T < 1) do
begin
Pt := Interpolate(T, p0, m0, p1, m1);
if ((pt.x <> Last.x) and (pt.y <> Last.y)) then
begin
if (i mod 3 = 0) then
begin
SetLength(Result, L+1);
Result[L] := Pt;
Inc(L);
end;
Inc(i);
Last := Pt;
end;
T := T + Delta
end;
end;
function CSplineTFPA(const Pts:TFPointArray; Tension:Extended): TFPointArray;
var
Tngs,Fpts: TFPointArray;
i,j,l,h:Integer;
begin
if Length(Pts) < 2 then
begin
Result := Pts;
Exit;
end;
Tngs := Tangents(Pts, Tension);
L := 0;
for i:=0 to High(Pts)-1 do
begin
FPts := CSPlinePoints(Pts[i], Tngs[i], Pts[i + 1], Tngs[i + 1]);
H := High(FPts);
SetLength(Result, L + H + 1);
for j:=0 to H do
begin
Result[L+j] := FPts[j];
end;
L := (L + H);
SetLength(FPts, 0);
end;
SetLength(Result, L+1);
Result[L] := Pts[High(Pts)];
SetLength(Tngs, 0);
end;
function CSpline(TPA:TPointArray; Tension:Extended; Connect:Boolean): TPointArray;
var
FPts: TFPointArray;
TMP: TPointArray;
i,j,h: Integer;
f,t:TPoint;
begin
TPARemoveDupes(TPA);
FPts := CSplineTFPA(TPAToTFPA(TPA), Tension);
case Connect of
False: Result := TFPAToTPA(FPts);
True:
begin
TMP := TFPAToTPA(FPts);
H := High(TMP);
for i:=0 to H-1 do
begin
j := i+1;
f := TMP[i];
t := TMP[j];
if not(SamePoints(f, t)) then
TPALine(Result, f, t)
else begin
SetLength(Result, Length(Result)+1);
Result[High(Result)] := f;
end;
end;
SetLength(TMP, 0);
end;
end;
SetLength(FPts, 0);
end;
end.
|
unit PHPProcessor;
{$mode objfpc}{$H+}
{**
*
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*}
{
http://flatdev.republika.pl/php-functions-lastest.zip
}
interface
uses
Classes, SysUtils,
SynEdit, SynEditTypes,
SynEditHighlighter, SynHighlighterHashEntries, mnSynHighlighterMultiProc;
type
TPHPRangeState = (rsphpUnknown, rsphpComment, rsphpDocument, rsphpStringSQ, rsphpStringDQ, rsphpVarExpansion);
{ TPHPProcessor }
TPHPProcessor = class(TSynProcessor)
protected
FRange: TPHPRangeState;
//LastRange: Bad Idea but let us try
LastRange: TPHPRangeState;
function GetIdentChars: TSynIdentChars; override;
procedure ResetRange; override;
function GetRange: Byte; override;
procedure SetRange(Value: Byte); override;
procedure SetRange(Value: TPHPRangeState); overload;
procedure InternalCommentProc;
function GetEndOfLineAttribute: TSynHighlighterAttributes; override;
public
procedure QuestionProc;
procedure AndSymbolProc;
procedure HashLineCommentProc;
procedure CommentProc;
procedure DocumentProc;
procedure SlashProc;
procedure StringProc;
procedure StringSQProc;
procedure StringDQProc;
procedure VarExpansionProc;
procedure EqualProc;
procedure CRProc;
procedure LFProc;
procedure GreaterProc;
procedure LowerProc;
procedure MinusProc;
procedure NullProc;
procedure NumberProc;
procedure OrSymbolProc;
procedure PlusProc;
procedure SpaceProc;
procedure SymbolProc;
procedure SymbolAssignProc;
procedure VariableProc;
procedure SetLine(const NewValue: string; LineNumber: integer); override;
procedure Next; override;
property Range: TPHPRangeState read FRange;
procedure Prepare; override;
procedure MakeProcTable; override;
end;
const
{$INCLUDE 'PHPKeywords.inc'}
implementation
uses
mnUtils;
procedure TPHPProcessor.AndSymbolProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] in ['=', '&'] then
Inc(Parent.Run);
end;
procedure TPHPProcessor.HashLineCommentProc;
begin
Parent.FTokenID := tkComment;
repeat
Inc(Parent.Run);
until Parent.FLine[Parent.Run] in [#0, #10, #13];
end;
procedure TPHPProcessor.StringProc;
function IsEscaped: boolean;
var
iFirstSlashPos: integer;
begin
iFirstSlashPos := Parent.Run - 1;
while (iFirstSlashPos > 0) and (Parent.FLine[iFirstSlashPos] = '\') do
Dec(iFirstSlashPos);
Result := (Parent.Run - iFirstSlashPos + 1) mod 2 <> 0;
end;
var
iCloseChar: char;
begin
Parent.FTokenID := tkString;
if Range = rsphpStringSQ then
iCloseChar := ''''
else
iCloseChar := '"';
while not (Parent.FLine[Parent.Run] in [#0, #10, #13]) do
begin
if (Parent.FLine[Parent.Run] = iCloseChar) and (not IsEscaped) then
begin
SetRange(rsphpUnKnown);
inc(Parent.Run);
break;
end;
if (iCloseChar = '"') and (Parent.FLine[Parent.Run] = '$') and
((Parent.FLine[Parent.Run + 1] = '{') or IdentTable[Parent.FLine[Parent.Run + 1]]) then
begin
if (Parent.Run > 1) and (Parent.FLine[Parent.Run - 1] = '{') then { complex syntax }
Dec(Parent.Run);
if not IsEscaped then
begin
{ break the token to process the variable }
SetRange(rsphpVarExpansion);
break;
end
else if Parent.FLine[Parent.Run] = '{' then
Inc(Parent.Run); { restore Run if we previously deincremented it }
end;
Inc(Parent.Run);
end;
end;
procedure TPHPProcessor.CRProc;
begin
Parent.FTokenID := tkSpace;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = #10 then
Inc(Parent.Run);
end;
procedure TPHPProcessor.EqualProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] in ['=', '>'] then
Inc(Parent.Run);
end;
procedure TPHPProcessor.GreaterProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] in ['=', '>'] then
Inc(Parent.Run);
end;
procedure TPHPProcessor.LFProc;
begin
Parent.FTokenID := tkSpace;
inc(Parent.Run);
end;
procedure TPHPProcessor.LowerProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'=': Inc(Parent.Run);
'<':
begin
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = '=' then
Inc(Parent.Run);
end;
end;
end;
procedure TPHPProcessor.MinusProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] in ['=', '-'] then
Inc(Parent.Run);
end;
procedure TPHPProcessor.NullProc;
begin
Parent.FTokenID := tkNull;
end;
procedure TPHPProcessor.NumberProc;
begin
inc(Parent.Run);
Parent.FTokenID := tkNumber;
while Parent.FLine[Parent.Run] in ['0'..'9', '.', '-'] do
begin
case Parent.FLine[Parent.Run] of
'.':
if Parent.FLine[Parent.Run + 1] = '.' then
break;
end;
inc(Parent.Run);
end;
end;
procedure TPHPProcessor.OrSymbolProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] in ['=', '|'] then
Inc(Parent.Run);
end;
procedure TPHPProcessor.PlusProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] in ['=', '+'] then
Inc(Parent.Run);
end;
procedure TPHPProcessor.SlashProc;
begin
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'/':
begin
Parent.FTokenID := tkComment;
repeat
Inc(Parent.Run);
until Parent.FLine[Parent.Run] in [#0, #10, #13];
end;
'*':
begin
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = '*' then
DocumentProc
else
CommentProc;
end;
'=':
begin
Inc(Parent.Run);
Parent.FTokenID := tkSymbol;
end;
else
Parent.FTokenID := tkSymbol;
end;
end;
procedure TPHPProcessor.SpaceProc;
begin
Parent.FTokenID := tkSpace;
repeat
Inc(Parent.Run);
until (Parent.FLine[Parent.Run] > #32) or (Parent.FLine[Parent.Run] in [#0, #10, #13]);
end;
procedure TPHPProcessor.SymbolProc;
begin
Inc(Parent.Run);
Parent.FTokenID := tkSymbol;
end;
procedure TPHPProcessor.SymbolAssignProc;
begin
Parent.FTokenID := tkSymbol;
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = '=' then
Inc(Parent.Run);
end;
procedure TPHPProcessor.VariableProc;
var
i: integer;
begin
Parent.FTokenID := tkVariable;
i := Parent.Run;
repeat
Inc(i);
until not (IdentTable[Parent.FLine[i]]);
Parent.Run := i;
end;
procedure TPHPProcessor.SetLine(const NewValue: string; LineNumber: integer);
begin
inherited;
LastRange := rsphpUnknown;
end;
procedure TPHPProcessor.CommentProc;
begin
Parent.FTokenID := tkComment;
SetRange(rsphpComment);
InternalCommentProc;
end;
procedure TPHPProcessor.DocumentProc;
begin
Parent.FTokenID := tkDocument;
SetRange(rsphpDocument);
InternalCommentProc;
end;
procedure TPHPProcessor.MakeProcTable;
var
I: Char;
begin
for I := #0 to #255 do
case I of
#0: ProcTable[I] := @NullProc;
#10: ProcTable[I] := @LFProc;
#13: ProcTable[I] := @CRProc;
'?': ProcTable[I] := @QuestionProc;
'''': ProcTable[I] := @StringSQProc;
'"': ProcTable[I] := @StringDQProc;
'#': ProcTable[I] := @HashLineCommentProc;
'/': ProcTable[I] := @SlashProc;
'=': ProcTable[I] := @EqualProc;
'>': ProcTable[I] := @GreaterProc;
'<': ProcTable[I] := @LowerProc;
'-': ProcTable[I] := @MinusProc;
'|': ProcTable[I] := @OrSymbolProc;
'+': ProcTable[I] := @PlusProc;
'&': ProcTable[I] := @AndSymbolProc;
'$': ProcTable[I] := @VariableProc;
'A'..'Z', 'a'..'z', '_':
ProcTable[I] := @IdentProc;
'0'..'9':
ProcTable[I] := @NumberProc;
#1..#9, #11, #12, #14..#32:
ProcTable[I] := @SpaceProc;
'^', '%', '*', '!':
ProcTable[I] := @SymbolAssignProc;
'{', '}', '.', ',', ';', '(', ')', '[', ']', '~':
ProcTable[I] := @SymbolProc;
else
ProcTable[I] := @UnknownProc;
end;
end;
procedure TPHPProcessor.QuestionProc;
begin
Inc(Parent.Run);
case Parent.FLine[Parent.Run] of
'>':
begin
Parent.Processors.Switch(Parent.Processors.MainProcessor);
Inc(Parent.Run);
Parent.FTokenID := tkProcessor;
end
else
Parent.FTokenID := tkSymbol;
end;
end;
procedure TPHPProcessor.Next;
begin
Parent.FTokenPos := Parent.Run;
case Range of
rsphpComment:
begin
if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then
ProcTable[Parent.FLine[Parent.Run]]
else
CommentProc;
end;
rsphpDocument:
begin
if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then
ProcTable[Parent.FLine[Parent.Run]]
else
DocumentProc;
end;
rsphpStringSQ, rsphpStringDQ:
if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then
ProcTable[Parent.FLine[Parent.Run]]
else
StringProc;
rsphpVarExpansion:
VarExpansionProc;
else
ProcTable[Parent.FLine[Parent.Run]];
end;
end;
procedure TPHPProcessor.VarExpansionProc;
type
TExpansionSyntax = (esNormal, esComplex, esBrace);
var
iSyntax: TExpansionSyntax;
iOpenBraces: integer;
iOpenBrackets: integer;
iTempRun: integer;
begin
SetRange(rsphpStringDQ); { var expansion only occurs in double quoted strings }
Parent.FTokenID := tkVariable;
if Parent.FLine[Parent.Run] = '{' then
begin
iSyntax := esComplex;
Inc(Parent.Run, 2); // skips '{$'
end
else
begin
Inc(Parent.Run);
if Parent.FLine[Parent.Run] = '{' then
begin
iSyntax := esBrace;
Inc(Parent.Run);
end
else
iSyntax := esNormal;
end;
if iSyntax in [esBrace, esComplex] then
begin
iOpenBraces := 1;
while Parent.FLine[Parent.Run] <> #0 do
begin
if Parent.FLine[Parent.Run] = '}' then
begin
Dec(iOpenBraces);
if iOpenBraces = 0 then
begin
Inc(Parent.Run);
break;
end;
end;
if Parent.FLine[Parent.Run] = '{' then
Inc(iOpenBraces);
Inc(Parent.Run);
end;
end
else
begin
while IdentTable[Parent.FLine[Parent.Run]] do
Inc(Parent.Run);
iOpenBrackets := 0;
iTempRun := Parent.Run;
{ process arrays and objects }
while Parent.FLine[iTempRun] <> #0 do
begin
if Parent.FLine[iTempRun] = '[' then
begin
Inc(iTempRun);
if Parent.FLine[iTempRun] = '''' then
begin
Inc(iTempRun);
while (Parent.FLine[iTempRun] <> '''') and (Parent.FLine[iTempRun] <> #0) do
Inc(iTempRun);
if (Parent.FLine[iTempRun] = '''') and (Parent.fLine[iTempRun + 1] = ']') then
begin
Inc(iTempRun, 2);
Parent.Run := iTempRun;
continue;
end
else
break;
end
else
Inc(iOpenBrackets);
end
else if (Parent.FLine[iTempRun] = '-') and (Parent.FLine[iTempRun + 1] = '>') then
Inc(iTempRun, 2)
else
break;
if not IdentTable[Parent.FLine[iTempRun]] then
break
else
repeat
Inc(iTempRun);
until not IdentTable[Parent.FLine[iTempRun]];
while Parent.FLine[iTempRun] = ']' do
begin
if iOpenBrackets = 0 then
break;
Dec(iOpenBrackets);
Inc(iTempRun);
end;
if iOpenBrackets = 0 then
Parent.Run := iTempRun;
end;
end;
end;
procedure TPHPProcessor.StringDQProc;
begin
SetRange(rsphpStringDQ);
Inc(Parent.Run);
StringProc;
end;
procedure TPHPProcessor.StringSQProc;
begin
SetRange(rsphpStringSQ);
Inc(Parent.Run);
StringProc;
end;
function TPHPProcessor.GetRange: Byte;
begin
Result := Byte(Range);
end;
procedure TPHPProcessor.ResetRange;
begin
inherited;
SetRange(rsphpUnknown);
LastRange := rsphpUnknown;
end;
procedure TPHPProcessor.SetRange(Value: Byte);
begin
SetRange(TPHPRangeState(Value));
end;
procedure TPHPProcessor.SetRange(Value: TPHPRangeState);
begin
if FRange <> Value then
LastRange := FRange;
FRange := Value;
end;
procedure TPHPProcessor.Prepare;
begin
inherited;
EnumerateKeywords(Ord(tkKeyword), sPHPControls, TSynValidStringChars, @DoAddKeyword);
EnumerateKeywords(Ord(tkKeyword), sPHPKeywords, TSynValidStringChars, @DoAddKeyword);
EnumerateKeywords(Ord(tkFunction), sPHPFunctions, TSynValidStringChars, @DoAddKeyword);
EnumerateKeywords(Ord(tkFunction), sPHPConstants, TSynValidStringChars, @DoAddKeyword);
EnumerateKeywords(Ord(tkVariable), sPHPVariables, TSynValidStringChars, @DoAddKeyword);
SetRange(rsphpUnknown);
end;
procedure TPHPProcessor.InternalCommentProc;
begin
while not (Parent.FLine[Parent.Run] in [#0, #10, #13]) do
begin
if (Parent.FLine[Parent.Run] = '*') and (Parent.FLine[Parent.Run + 1] = '/') then
begin
SetRange(rsphpUnKnown);
Inc(Parent.Run, 2);
break;
end;
Inc(Parent.Run);
end;
end;
function TPHPProcessor.GetEndOfLineAttribute: TSynHighlighterAttributes;
begin
if (Range = rsphpDocument) or (LastRange = rsphpDocument) then
Result := Parent.DocumentAttri
else
Result := inherited GetEndOfLineAttribute;
end;
function TPHPProcessor.GetIdentChars: TSynIdentChars;
begin
Result := TSynValidStringChars + ['$'];
end;
end.
|
unit uNewParser;
interface
uses
Classes
,SysUtils
,l3Parser
,uTypes
;
Const
cQuote = #39;
cTab = #9;
cSpace = #32;
cCRLF = #13#10;
cWhiteSpace = [cSpace, cTab];
cDoubleQuote = '"';
cMinus = '-';
cSlash = '/';
cAsterics = '*';
cLeftBracket = '{';
cRightBracket = '}';
type
EUnknownToken = Class(Exception);
// TTokenType = (ttUnknown,
// ttString,
// ttToken,
// ttBoolean,
// ttNumber,
// ttIdentifier,
// ttEOF);
{type
TTokenType = (l3_ttUnknown,
l3_ttString,
l3_ttSymbol,
//ttBoolean,
l3_ttInteger,
l3_ttDoubleQuotedString,
l3_ttEOF); }
// Tl3TokenType = (
// l3_ttBOF, {- начало файла}
// l3_ttEOF, {- конец файла}
// l3_ttEOL, {- конец строки}
// l3_ttSingleChar, {- единичный (управляющий) символ}
// l3_ttSymbol, {- идентификатор}
// l3_ttKeyWord, {- ключевое слово}
// l3_ttString, {- строка (в кавычках)}
// l3_ttInteger, {- целое число}
// l3_ttFloat, {- вещественное число}
// l3_ttComment, {- комментарий}
// l3_ttDoubleQuotedString // - строка в двойных кавычках
// );
type
TNewParser = class
private
f_Stream: TStream;
f_EOF: Boolean;
f_UnknownToken: String;
f_PosInUnknown: Integer;
f_Token: String;
f_TokenType: Tl3TokenType;
procedure NextChar;
// Увеличивает f_PosInCurrentToken на 1
procedure PrevChar;
// Уменьшает f_PosInCurrentToken на 1
procedure GetPrevChar(out aChar: AnsiChar);
// Возвращает предыдущий символ в aChar
function CurrentChar : Char;
protected
function ReadUnknownToken: String;
protected
function GetChar(out aChar: AnsiChar): Boolean;
public
constructor Create(const aStream: TStream); overload;
constructor Create(const aFileName: String); overload;
destructor Destroy; override;
function EOF: Boolean;
{ * - Достигнут конец входного потока. }
procedure NextToken;
{ * - Выбрать следующий токен из входного потока. }
public
property TokenString: String read f_Token;
{ * - текущий токен. }
property TokenType: Tl3TokenType read f_TokenType;
{ * - тип текущего токена. }
end; // TscriptParser
implementation
uses
System.Character
;
{ TScriptParser }
constructor TNewParser.Create(const aStream: TStream);
begin
inherited Create;
f_PosInUnknown := 1;
f_EOF := false;
f_Stream := aStream;
end;
constructor TNewParser.Create(const aFileName: String);
var
l_FileName: String;
begin
l_FileName := aFileName;
if (ExtractFilePath(l_FileName) = '') then
l_FileName := ExtractFilePath(ParamStr(0)) + '\' + l_FileName;
Create(TFileStream.Create(l_FileName, fmOpenRead));
end;
function TNewParser.CurrentChar: Char;
begin
Result := f_UnknownToken[f_PosInUnknown];
end;
destructor TNewParser.Destroy;
begin
FreeAndNil(f_Stream);
inherited;
end;
function TNewParser.EOF: Boolean;
begin
Result := f_EOF AND (f_UnknownToken = '');
end;
function TNewParser.GetChar(out aChar: AnsiChar): Boolean;
begin
if (f_Stream.Read(aChar, SizeOf(aChar)) = SizeOf(aChar)) then
begin
Result := true;
end
else
Result := false;
end;
procedure TNewParser.GetPrevChar(out aChar: AnsiChar);
begin
// Надо ли тут делать проверку на то что это возможно первый символ?
f_Stream.Position := f_Stream.Position - SizeOf(aChar) - SizeOf(aChar);
GetChar(aChar);
end;
procedure TNewParser.NextChar;
begin
Inc(f_PosInUnknown);
end;
procedure TNewParser.PrevChar;
begin
Dec(f_PosInUnknown);
end;
procedure TNewParser.NextToken;
var
l_Token : String;
procedure AnalyzeToken;
var
l_IsQuoteOpen : Boolean;
f_IsSymbol : Boolean;
l_SymbBuffer : String;
l_QuoteCount : Integer;
l_Number : Integer;
l_IsDoubleQuote : Boolean;
function ValidStringChar : Boolean;
begin
Result := ((CurrentChar = '#') or
(CurrentChar = cQuote) or
(CurrentChar = #0));
end;
function IsQuoteClose : Boolean;
begin
Result := not l_IsQuoteOpen;
end;
procedure AddBufferToToken;
var
l_Num : Integer;
begin
if TryStrToInt(l_SymbBuffer, l_Num) then
f_Token := f_Token + (Chr(l_Num))
else
begin
l_SymbBuffer := '';
raise EUnknownToken.Create('Error Message');
end;
end;
procedure AddCharToBuffer(aChar : Char);
begin
l_SymbBuffer := l_SymbBuffer + aChar;
end;
function IsNumBegin : Boolean;
begin
Result := (CurrentChar.IsDigit or (CurrentChar = cMinus) or (CurrentChar = '$')) and
(f_Token = '');
end;
begin
l_IsQuoteOpen := False;
l_IsDoubleQuote := False;
// Проверка на Boolean, и другие зарезервированные слова
if (f_UnknownToken = 'false') or (f_UnknownToken = 'true') then
begin
f_Token := f_UnknownToken;
//f_TokenType := ttBoolean;
f_TokenType := l3_ttSymbol;
Exit;
end;
try
while f_PosInUnknown <= Length(f_UnknownToken) do
begin
// Начало символов
if (CurrentChar = '#') and (not l_IsQuoteOpen) then
begin
f_IsSymbol := True;
l_SymbBuffer := '';
f_TokenType := l3_ttString;
NextChar;
while not ValidStringChar do
begin
AddCharToBuffer(CurrentChar);
NextChar;
end;
AddBufferToToken;
f_IsSymbol := False;
Continue;
end;
// Начало String
if CurrentChar = cQuote then
begin
l_IsQuoteOpen := not l_IsQuoteOpen;
f_TokenType := l3_ttString;
l_QuoteCount := 1;
NextChar;
// Проверка на символ полсле строки
if IsQuoteClose and (not ValidStringChar) then
raise EUnknownToken.Create('Error Message');
while CurrentChar = cQuote do
begin
l_IsQuoteOpen := not l_IsQuoteOpen;
Inc(l_QuoteCount);
// Делим на три, так как ''' дают '
if (l_QuoteCount div 3) = 1 then
begin
NextChar;
Break;
end;
NextChar;
end;
// '''' and '''
if ((l_QuoteCount div 4) = 1) or ((l_QuoteCount div 3) = 1)then
f_Token := f_Token + cQuote;
Continue;
end;
// Цифры
if IsNumBegin then
begin
if TryStrToInt(f_UnknownToken, l_Number) then
begin
f_Token := f_UnknownToken;
// Приведение числа в dec форму
if (l_Number = 0) or (CurrentChar = '$') then
f_Token := IntToStr(l_Number);
// Если число отрицательное Hex
if CurrentChar = cMinus then
begin
NextChar;
if CurrentChar = '$' then
raise EUnknownToken.Create('Error Message');
end;
f_TokenType := l3_ttInteger;
Exit;
end
else
raise EUnknownToken.Create('Error Message')
end;
// Идентификатор
if (CurrentChar = cDoubleQuote) and (not l_IsQuoteOpen) then
begin
l_IsDoubleQuote := not l_IsDoubleQuote;
if not l_IsDoubleQuote then
begin
f_TokenType := l3_ttDoubleQuotedString;
end;
end;
// не включаем конец строки в токен
if (CurrentChar <> #0) then
f_Token := f_Token + CurrentChar;
// Проверка на невалидный идентификатор
if (f_TokenType = l3_ttDoubleQuotedString) and
(f_Token <> f_UnknownToken) then
raise EUnknownToken.Create('Error Message');
NextChar;
end;
except
f_TokenType := l3_ttUnknown;
Exit;
end;
// Если кавычка не закрыта то это ttUnknown
if l_IsQuoteOpen then
begin
f_TokenType := l3_ttUnknown;
Exit
end;
// Финальная проверка
if not (TokenType in [l3_ttString, l3_ttDoubleQuotedString, l3_ttInteger]) then
f_TokenType := l3_ttSymbol;
end; // AnalyzeToken
begin
f_TokenType := l3_ttUnknown;
f_UnknownToken := ReadUnknownToken;
f_PosInUnknown := 1;
f_Token := '';
AnalyzeToken;
if (f_Token <> f_UnknownToken) and
(TokenType <> l3_ttString) and
(TokenType <> l3_ttInteger) and
(TokenType <> l3_ttDoubleQuotedString) then
begin
f_Token := f_UnknownToken;
f_TokenType := l3_ttUnknown;
end;
if f_EOF then
if f_UnknownToken = '' then
f_TokenType := l3_ttEOF;
end;
function TNewParser.ReadUnknownToken: String;
var
l_Buffer : String;
l_Char : AnsiChar;
l_IsOpenQuote,
l_IsLineComment,
l_IsDoubleQuoteOpen,
l_IsBlockComment : Boolean;
begin
l_Buffer := '';
l_IsOpenQuote := False;
l_IsDoubleQuoteOpen := False;
l_IsLineComment := False;
l_IsBlockComment := False;
while GetChar(l_Char) do
begin
if (not l_IsOpenQuote) and (not l_IsDoubleQuoteOpen) then
begin
if l_Char = #13 then
if GetChar(l_Char) then
if l_Char = #10 then
begin
if l_IsLineComment then
l_IsLineComment := False;
if (Length(l_Buffer) > 0) then
Break
else // (Length(l_Buffer) > 0)
Continue
end
else // l_Char = #10
Assert(false, 'Not character LF after character CR')
else // GetChar(l_Char)
Assert(false, 'End of file, after character CR');
if l_IsBlockComment then
begin
if (l_Char = cAsterics) then
if GetChar(l_Char) then
if (l_Char = cSlash) then
begin
l_IsBlockComment := False;
Continue;
end
else // (l_Char = cSlash)
begin
GetPrevChar(l_Char);
Continue;
end
else // GetChar(l_Char)
Continue
else // (l_Char = cAsterics)
Continue;
end;
if l_IsLineComment then
Continue;
if l_Char in cWhiteSpace then
if (Length(l_Buffer) > 0) then
Break
else // (Length(l_Buffer) > 0)
Continue;
end; // not l_IsOpenQute
// Кавычка '
if l_Char = cQuote then
l_IsOpenQuote := not l_IsOpenQuote;
// Двойная кавычка "
if l_Char = cDoubleQuote then
l_IsDoubleQuoteOpen := not l_IsDoubleQuoteOpen;
// // and /*
if (not l_IsOpenQuote) and (not l_IsDoubleQuoteOpen) then
begin
if (l_Char = cSlash) then
begin
if GetChar(l_Char) then
if l_Char = cSlash then
begin
l_IsLineComment := True;
Continue;
end
else if l_Char = cAsterics then
begin
l_IsBlockComment := True;
Continue;
end // l_Char = cAsterics
else
GetPrevChar(l_Char);
end; // (l_Char = cSlash)
end; // (not l_IsOpenQuote)
l_Buffer := l_Buffer + l_Char;
end;
f_EOF := True;
Result := l_Buffer;
end;
end.
|
unit RoomHiden;
{$mode objfpc}{$H+}
interface
Type TRoom=object
private {скрытые компоненты класса}
length,width:real; {поля: длина и ширина комнаты}
public {общие компоненты класса}
function Square:real; {метод определения площади}
procedure Init(l,w:real); {инициализирующий метод}
end;
implementation
Function TRoom.Square; {метод определения площади}
begin
Square:=length*width;
end;
Procedure TRoom.Init; {инициализирующий метод}
begin
length:=l;
width:=w;
end;
end.
|
namespace Sugar;
interface
type
{$IF COOPER}
Math = public class mapped to java.lang.Math
public
class method Abs(d: Double): Double; mapped to abs(d);
class method Abs(i: Int64): Int64;
class method Abs(i: Integer): Integer;
class method Acos(d: Double): Double; mapped to acos(d);
class method Asin(d: Double): Double; mapped to asin(d);
class method Atan(d: Double): Double; mapped to atan(d);
class method Atan2(x,y: Double): Double;
class method Ceiling(a: Double): Double; mapped to ceil(a);
class method Cos(d: Double): Double; mapped to cos(d);
class method Cosh(d: Double): Double; mapped to cosh(d);
class method Exp(d: Double): Double; mapped to exp(d);
class method Floor(d: Double): Double; mapped to floor(d);
class method IEEERemainder(x, y: Double): Double; mapped to IEEEremainder(x, y);
class method Log(d: Double): Double; mapped to log(d);
class method Log10(d: Double): Double; mapped to log10(d);
class method Max(a,b: Double): Double; mapped to max(a,b);
class method Max(a,b: Integer): Integer; mapped to max(a,b);
class method Max(a,b: Int64): Int64; mapped to max(a,b);
class method Min(a,b: Double): Double; mapped to min(a,b);
class method Min(a,b: Integer): Integer; mapped to min(a,b);
class method Min(a,b: Int64): Int64; mapped to min(a,b);
class method Pow(x, y: Double): Double;
class method Round(a: Double): Int64;
class method Sign(d: Double): Integer;
class method Sin(d: Double): Double; mapped to sin(d);
class method Sinh(d: Double): Double; mapped to sinh(d);
class method Sqrt(d: Double): Double; mapped to sqrt(d);
class method Tan(d: Double): Double; mapped to tan(d);
class method Tanh(d: Double): Double; mapped to tanh(d);
class method Truncate(d: Double): Double;
{$ENDIF}
{$IF ECHOES}
Math = public class mapped to System.Math
public
class method Abs(d: Double): Double; mapped to Abs(d);
class method Abs(i: Int64): Int64; mapped to Abs(i);
class method Abs(i: Integer): Integer; mapped to Abs(i);
class method Acos(d: Double): Double; mapped to Acos(d);
class method Asin(d: Double): Double; mapped to Asin(d);
class method Atan(d: Double): Double; mapped to Atan(d);
class method Atan2(x,y: Double): Double; mapped to Atan2(x,y);
class method Ceiling(d: Double): Double; mapped to Ceiling(d);
class method Cos(d: Double): Double; mapped to Cos(d);
class method Cosh(d: Double): Double; mapped to Cosh(d);
class method Exp(d: Double): Double; mapped to Exp(d);
class method Floor(d: Double): Double; mapped to Floor(d);
class method IEEERemainder(x, y: Double): Double; mapped to IEEERemainder(x, y);
class method Log(d: Double): Double; mapped to Log(d);
class method Log10(d: Double): Double; mapped to Log10(d);
class method Max(a,b: Double): Double; mapped to Max(a,b);
class method Max(a,b: Integer): Integer; mapped to Max(a,b);
class method Max(a,b: Int64): Int64; mapped to Max(a,b);
class method Min(a,b: Double): Double; mapped to Min(a,b);
class method Min(a,b: Integer): Integer; mapped to Min(a,b);
class method Min(a,b: Int64): Int64; mapped to Min(a,b);
class method Pow(x, y: Double): Double; mapped to Pow(x,y);
class method Round(a: Double): Int64;
class method Sign(d: Double): Integer; mapped to Sign(d);
class method Sin(d: Double): Double; mapped to Sin(d);
class method Sinh(d: Double): Double; mapped to Sinh(d);
class method Sqrt(d: Double): Double; mapped to Sqrt(d);
class method Tan(d: Double): Double; mapped to Tan(d);
class method Tanh(d: Double): Double; mapped to Tanh(d);
class method Truncate(d: Double): Double; mapped to Truncate(d);
{$ENDIF}
{$IF TOFFEE}
Math = public class mapped to Object
public
class method Abs(value: Double): Double;
class method Abs(i: Int64): Int64;
class method Abs(i: Integer): Integer;
class method Acos(d: Double): Double;
class method Asin(d: Double): Double;
class method Atan(d: Double): Double;
class method Atan2(x,y: Double): Double;
class method Ceiling(d: Double): Double;
class method Cos(d: Double): Double;
class method Cosh(d: Double): Double;
class method Exp(d: Double): Double;
class method Floor(d: Double): Double;
class method IEEERemainder(x, y: Double): Double;
class method Log(a: Double): Double;
class method Log10(a: Double): Double;
class method Max(a,b: Double): Double;
class method Max(a,b: Integer): Integer;
class method Max(a,b: Int64): Int64;
class method Min(a,b: Double): Double;
class method Min(a,b: Integer): Integer;
class method Min(a,b: Int64): Int64;
class method Pow(x, y: Double): Double;
class method Round(a: Double): Int64;
class method Sign(d: Double): Integer;
class method Sin(x: Double): Double;
class method Sinh(x: Double): Double;
class method Sqrt(d: Double): Double;
class method Tan(d: Double): Double;
class method Tanh(d: Double): Double;
class method Truncate(d: Double): Double;
{$ENDIF}
end;
implementation
{$IF COOPER}
class method Math.Truncate(d: Double): Double;
begin
exit iif(d < 0, mapped.ceil(d), mapped.floor(d));
end;
class method Math.Abs(i: Int64): Int64;
begin
if i = Consts.MinInt64 then
raise new SugarArgumentException("Value can not equals minimum value of Int64");
exit mapped.abs(i);
end;
class method Math.Abs(i: Integer): Integer;
begin
if i = Consts.MinInteger then
raise new SugarArgumentException("Value can not equals minimum value of Int32");
exit mapped.abs(i);
end;
class method Math.Atan2(x: Double; y: Double): Double;
begin
if Consts.IsInfinity(x) and Consts.IsInfinity(y) then
exit Consts.NaN;
exit mapped.atan2(x,y);
end;
class method Math.Pow(x: Double; y: Double): Double;
begin
{$IF ANDROID}
if (x = -1) and Consts.IsInfinity(y) then
exit Consts.NaN;
exit mapped.pow(x, y);
{$ELSE}
exit mapped.pow(x, y);
{$ENDIF}
end;
{$ENDIF}
class method Math.Round(a: Double): Int64;
begin
if Consts.IsNaN(a) or Consts.IsInfinity(a) then
raise new SugarArgumentException("Value can not be rounded to Int64");
exit Int64(Floor(a + 0.499999999999999999));
end;
{$IF COOPER or TOFFEE}
class method Math.Sign(d: Double): Integer;
begin
if Consts.IsNaN(d) then
raise new SugarArgumentException("Value can not be NaN");
if d > 0 then exit 1;
if d < 0 then exit -1;
exit 0;
end;
{$ENDIF}
{$IF TOFFEE}
class method Math.Pow(x, y: Double): Double;
begin
if (x = -1) and Consts.IsInfinity(y) then
exit Consts.NaN;
exit rtl.pow(x,y);
end;
class method Math.Acos(d: Double): Double;
begin
exit rtl.acos(d);
end;
class method Math.Cos(d: Double): Double;
begin
exit rtl.cos(d);
end;
class method Math.Ceiling(d: Double): Double;
begin
exit rtl.ceil(d);
end;
class method Math.Cosh(d: Double): Double;
begin
exit rtl.cosh(d);
end;
class method Math.Asin(d: Double): Double;
begin
exit rtl.asin(d);
end;
class method Math.Atan(d: Double): Double;
begin
exit rtl.atan(d);
end;
class method Math.Atan2(x,y: Double): Double;
begin
if Consts.IsInfinity(x) and Consts.IsInfinity(y) then
exit Consts.NaN;
exit rtl.atan2(x,y);
end;
class method Math.Abs(value: Double): Double;
begin
exit rtl.fabs(value);
end;
class method Math.Exp(d: Double): Double;
begin
exit rtl.exp(d);
end;
class method Math.Floor(d: Double): Double;
begin
exit rtl.floor(d);
end;
class method Math.IEEERemainder(x,y: Double): Double;
begin
exit rtl.remainder(x,y);
end;
class method Math.Log(a: Double): Double;
begin
exit rtl.log(a);
end;
class method Math.Log10(a: Double): Double;
begin
exit rtl.log10(a);
end;
class method Math.Max(a,b: Int64): Int64;
begin
exit iif(a > b, a, b);
end;
class method Math.Min(a,b: Int64): Int64;
begin
exit iif(a < b, a, b);
end;
class method Math.Sin(x: Double): Double;
begin
exit rtl.sin(x);
end;
class method Math.Sinh(x: Double): Double;
begin
exit rtl.sinh(x);
end;
class method Math.Sqrt(d: Double): Double;
begin
exit rtl.sqrt(d);
end;
class method Math.Tan(d: Double): Double;
begin
exit rtl.tan(d);
end;
class method Math.Tanh(d: Double): Double;
begin
exit rtl.tanh(d);
end;
class method Math.Truncate(d: Double): Double;
begin
exit rtl.trunc(d);
end;
class method Math.Abs(i: Int64): Int64;
begin
if i = Consts.MinInt64 then
raise new SugarArgumentException("Value can not equals minimum value of Int64");
exit rtl.llabs(i);
end;
class method Math.Abs(i: Integer): Integer;
begin
if i = Consts.MinInteger then
raise new SugarArgumentException("Value can not equals minimum value of Int32");
exit rtl.abs(i);
end;
class method Math.Max(a: Double; b: Double): Double;
begin
if Consts.IsNaN(a) or Consts.IsNaN(b) then
exit Consts.NaN;
exit iif(a > b, a, b);
end;
class method Math.Max(a: Integer; b: Integer): Integer;
begin
exit iif(a > b, a, b);
end;
class method Math.Min(a: Double; b: Double): Double;
begin
if Consts.IsNaN(a) or Consts.IsNaN(b) then
exit Consts.NaN;
exit iif(a < b, a, b);
end;
class method Math.Min(a: Integer; b: Integer): Integer;
begin
exit iif(a < b, a, b);
end;
{$ENDIF}
end. |
unit Control.VerbasExpressas;
interface
uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Control.Sistema, Model.VerbasExpressas, Common.Utils;
type
TVerbasExpressasControl = class
private
FVerbas : TVerbasExpressas;
public
constructor Create();
destructor Destroy(); override;
property Verbas: TVerbasExpressas read FVerbas write FVerbas;
function GetID(): Integer;
function ValidaCampos(): Boolean;
function Localizar(aParam: array of variant): TFDQuery;
function LocalizarExato(aParam: array of variant): Boolean;
procedure ClearModel;
function Gravar(): Boolean;
function SetupModal(FDQuery: TFDQuery): Boolean;
function RetornaVerba(): double;
function RetornaListaSimples(iTabela: integer; memTable: TFDMemTable): boolean;
function RetornaValorFaixa(iCliente, iTabela, iFaixa: integer): string;
end;
implementation
{ TVerbasExpressasControl }
procedure TVerbasExpressasControl.ClearModel;
begin
FVerbas.ClearModel;
end;
constructor TVerbasExpressasControl.Create;
begin
FVerbas := TVerbasExpressas.Create;
end;
destructor TVerbasExpressasControl.Destroy;
begin
FVerbas.Free;
inherited;
end;
function TVerbasExpressasControl.GetID: Integer;
begin
Result := FVerbas.GetID;
end;
function TVerbasExpressasControl.Gravar: Boolean;
begin
Result := FVerbas.Gravar;
end;
function TVerbasExpressasControl.Localizar(aParam: array of variant): TFDQuery;
begin
Result := FVerbas.Localizar(aParam);
end;
function TVerbasExpressasControl.LocalizarExato(aParam: array of variant): Boolean;
begin
Result := FVerbas.LocalizarExato(aParam);
end;
function TVerbasExpressasControl.RetornaListaSimples(iTabela: integer; memTable: TFDMemTable): boolean;
begin
Result := FVerbas.RetornaListaSimples(iTabela,memTable);
end;
function TVerbasExpressasControl.RetornaValorFaixa(iCliente, iTabela, iFaixa: integer): string;
begin
Result := FVerbas.RetornaValorFaixa(iCliente, iTabela, iFaixa);
end;
function TVerbasExpressasControl.RetornaVerba(): double;
begin
Result := FVerbas.RetornaVerba();
end;
function TVerbasExpressasControl.SetupModal(FDQuery: TFDQuery): Boolean;
begin
Result := FVerbas.SetupModel(FDQuery);
end;
function TVerbasExpressasControl.ValidaCampos: Boolean;
var
FDQuery : TFDQuery;
aParam: Array of variant;
begin
try
Result := False;
if FVerbas.Acao <> tacIncluir then
begin
if FVerbas.ID = 0 then
begin
Application.MessageBox('ID do registro de verba inválido!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
end;
if FVerbas.Tipo = 0 then
begin
Application.MessageBox('Informe o tipo de verba!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if FVerbas.Grupo = 0 then
begin
Application.MessageBox('Informe o grupo da verba!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if FVerbas.Vigencia = 0 then
begin
Application.MessageBox('Informe a data de inicio de vigência de verba!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if FVerbas.Verba = 0 then
begin
Application.MessageBox('Informe o valor da verba!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if FVerbas.Tipo = 4 then
begin
if FVerbas.Performance = 0 then
begin
Application.MessageBox('Informe o percentual de performance da verba!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
end;
if (FVerbas.Tipo = 2) or (FVerbas.Tipo = 5) then
begin
FVerbas.CEPInicial := Common.Utils.TUtils.ReplaceStr(FVerbas.CEPInicial,'-','');
FVerbas.CEPFinal := Common.Utils.TUtils.ReplaceStr(FVerbas.CEPFinal,'-','');
if FVerbas.CEPInicial.IsEmpty then
begin
Application.MessageBox('Informe o CEP inicial!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if FVerbas.CEPFinal.IsEmpty then
begin
Application.MessageBox('Informe o CEP final!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if FVerbas.CEPInicial.Length < 8 then
begin
Application.MessageBox('Informe o CEP inicial completo (8 dígitos)!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if FVerbas.CEPFinal.Length < 8 then
begin
Application.MessageBox('Informe o CEP final completo (8 dígitos)!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if StrToIntDef(FVerbas.CEPFinal,0) < StrToIntDef(FVerbas.CEPInicial,0) then
begin
Application.MessageBox('CEP final menor que o CEP inicial!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
end;
if FVerbas.Tipo = 5 then
begin
if FVerbas.PesoInicial = 0 then
begin
Application.MessageBox('Informe o peso inicial!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if FVerbas.PesoFinal = 0 then
begin
Application.MessageBox('Informe o peso final!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
if FVerbas.PesoFinal < FVerbas.PesoInicial then
begin
Application.MessageBox('Peso final menor que o peso inicial!', 'Atenção!', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
end;
Result := True;
finally
FDQuery.Free;
end;
end;
end.
|
{ Mark Sattolo 428500
CSI-1100A DGD-1 TA: Chris Lankester
Assignment 8, Challenge question }
program CrosstheRiver (input,output);
{ ****************************************************************************** }
procedure Cross_River(Short, Long:integer; var River:string; var Success:boolean);
{ Determine if River can be crossed ('-' is the water) by passing from one stone ('O')
to another by a combination of Long and Short "steps". }
{ Data Dictionary
Givens: River - a string consisting of O's and -'s, that starts and ends with an O.
Short, Long - positive integers, with Short < Long.
Results: Success - a boolean which is true if River can be "crossed" by a
combination of Long's and Short's, and false otherwise.
Intermediates: W - the length of River. }
var
W : integer;
begin { procedure Cross_River }
W := length(River);
Success := false;
if (W = Short+1) OR (W = Long+1) then
Success := true
else
if River[Long+1] = 'O' then
Cross_River(Short, Long, copy(River, Long+1, W-Long), Success);
if not Success then
if River[Short+1] = 'O' then
Cross_River(Short, Long, copy(River, Short+1, W-Short), Success);
end; { procedure Cross_River }
{ ****************************************************************************** }
{ program CrosstheRiver: provide input and output and call procedure Cross_River. }
{ Data Dictionary
Givens: River - a string of O's and -'s.
Long, Short - positive integers where Short < Long.
Results: Success - a boolean which is true if River can be "crossed", and false
otherwise.
Uses: Cross_River }
var
River : string;
Long, Short : integer;
Success : boolean;
begin
{ start the loop }
repeat
{ Read in the program's givens. }
write('Please enter a string for the "River": ');
readln(River);
write('Please enter a value for "Long": ');
readln(Long);
write('Please enter a value (66 to exit) for "Short": ');
readln(Short);
{ call the procedure }
Cross_River(Short, Long, River, Success);
{ write out the results }
writeln;
writeln('****************************************************');
writeln(' Mark Sattolo 428500');
writeln(' CSI-1100A DGD-1 TA: Chris Lankester');
writeln(' Assignment 8, Challenge question');
writeln('****************************************************');
writeln;
if Success then
writeln('Congratulations - You crossed the river!')
else
writeln('Sorry, you are stuck on the other side!');
writeln;
writeln('***************************************');
until Short = 66; { finish the loop }
end.
|
namespace Sugar.IO;
interface
uses
Sugar;
type
Path = public static class
public
method ChangeExtension(FileName: not nullable String; NewExtension: nullable String): not nullable String;
method Combine(BasePath: not nullable String; Path: not nullable String): not nullable String;
method Combine(BasePath: not nullable String; Path1: not nullable String; Path2: not nullable String): not nullable String;
method GetParentDirectory(FileName: not nullable String): nullable String;
method GetExtension(FileName: not nullable String): not nullable String;
method GetFileName(FileName: not nullable String): not nullable String;
method GetFileNameWithoutExtension(FileName: not nullable String): not nullable String;
method GetFullPath(RelativePath: not nullable String): not nullable String;
property DirectorySeparatorChar: Char read Folder.Separator;
end;
implementation
method Path.ChangeExtension(FileName: not nullable String; NewExtension: nullable String): not nullable String;
begin
if length(NewExtension) = 0 then
exit GetFileNameWithoutExtension(FileName);
var lIndex := FileName.LastIndexOf(".");
if lIndex <> -1 then
FileName := FileName.Substring(0, lIndex);
if NewExtension[0] = '.' then
result := FileName + NewExtension
else
result := FileName + "." + NewExtension as not nullable;
end;
method Path.Combine(BasePath: not nullable String; Path: not nullable String): not nullable String;
begin
if String.IsNullOrEmpty(BasePath) and String.IsNullOrEmpty(Path) then
raise new SugarArgumentException("Invalid arguments");
if String.IsNullOrEmpty(BasePath) then
exit Path;
if String.IsNullOrEmpty(Path) then
exit BasePath;
var LastChar := BasePath[BasePath.Length - 1];
if LastChar = Folder.Separator then
result := BasePath + Path
else
result := BasePath + Folder.Separator + Path; // 74540: Bogus nullability wanring, Nougat only
end;
method Path.Combine(BasePath: not nullable String; Path1: not nullable String; Path2: not nullable String): not nullable String;
begin
exit Combine(Combine(BasePath, Path1), Path2);
end;
method Path.GetParentDirectory(FileName: not nullable String): nullable String;
begin
if length(FileName) = 0 then
raise new SugarArgumentException("Invalid arguments");
var LastChar := FileName[FileName.Length - 1];
if LastChar = Folder.Separator then
FileName := FileName.Substring(0, FileName.Length - 1);
if (FileName = Folder.Separator) or ((length(FileName) = 2) and (FileName[1] = ':')) then
exit nil; // root folder has no parent
var lIndex := FileName.LastIndexOf(Folder.Separator);
if FileName.StartsWith('\\') then begin
if lIndex > 1 then
result := FileName.Substring(0, lIndex)
else
result := nil; // network share has no parent folder
end
else begin
if lIndex > -1 then
result := FileName.Substring(0, lIndex)
else
result := ""
end;
end;
method Path.GetExtension(FileName: not nullable String): not nullable String;
begin
FileName := GetFileName(FileName);
var lIndex := FileName.LastIndexOf(".");
if (lIndex <> -1) and (lIndex < FileName.Length - 1) then
exit FileName.Substring(lIndex);
exit "";
end;
method Path.GetFileName(FileName: not nullable String): not nullable String;
begin
if FileName.Length = 0 then
exit "";
var LastChar: Char := FileName[FileName.Length - 1];
if LastChar = Folder.Separator then
FileName := FileName.Substring(0, FileName.Length - 1);
var lIndex := FileName.LastIndexOf(Folder.Separator);
if (lIndex <> -1) and (lIndex < FileName.Length - 1) then
exit FileName.Substring(lIndex + 1);
exit FileName;
end;
method Path.GetFileNameWithoutExtension(FileName: not nullable String): not nullable String;
begin
FileName := GetFileName(FileName);
var lIndex := FileName.LastIndexOf(".");
if lIndex <> -1 then
exit FileName.Substring(0, lIndex);
exit FileName;
end;
method Path.GetFullPath(RelativePath: not nullable String): not nullable String;
begin
{$IF COOPER}
exit new java.io.File(RelativePath).AbsolutePath as not nullable;
{$ELSEIF NETFX_CORE}
exit RelativePath; //api has no such function
{$ELSEIF WINDOWS_PHONE}
exit System.IO.Path.GetFullPath(RelativePath) as not nullable;
{$ELSEIF ECHOES}
exit System.IO.Path.GetFullPath(RelativePath) as not nullable;
{$ELSEIF TOFFEE}
exit (RelativePath as NSString).stringByStandardizingPath;
{$ENDIF}
end;
end. |
unit frmInIOCPHttpServer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, iocp_sockets, iocp_managers, iocp_server,
http_base, http_objects, fmIOCPSvrInfo;
type
TFormInIOCPHttpServer = class(TForm)
Memo1: TMemo;
InIOCPServer1: TInIOCPServer;
InHttpDataProvider1: TInHttpDataProvider;
btnStart: TButton;
btnStop: TButton;
FrameIOCPSvrInfo1: TFrameIOCPSvrInfo;
InDatabaseManager1: TInDatabaseManager;
procedure FormCreate(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure InHttpDataProvider1Get(Sender: TObject; Request: THttpRequest;
Response: THttpResponse);
procedure InHttpDataProvider1Post(Sender: TObject;
Request: THttpRequest; Response: THttpResponse);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure InHttpDataProvider1Accept(Sender: TObject; Request: THttpRequest;
var Accept: Boolean);
procedure InHttpDataProvider1ReceiveFile(Sender: TObject;
Request: THttpRequest; const FileName: string; Data: PAnsiChar;
DataLength: Integer; State: THttpPostState);
procedure InIOCPServer1AfterOpen(Sender: TObject);
procedure InIOCPServer1AfterClose(Sender: TObject);
private
{ Private declarations }
FAppDir: String;
public
{ Public declarations }
end;
var
FormInIOCPHttpServer: TFormInIOCPHttpServer;
implementation
uses
iocp_log, iocp_utils, iocp_msgPacks, http_utils, dm_iniocp_test;
{$R *.dfm}
procedure TFormInIOCPHttpServer.btnStartClick(Sender: TObject);
begin
Memo1.Lines.Clear;
iocp_log.TLogThread.InitLog; // 开启日志
// 注册数模类名到 InDatabaseManager1
// 测试:用不同说明,注册两次 TdmInIOCPTest
InDatabaseManager1.AddDataModule(TdmInIOCPTest, 'http_dataModule');
InDatabaseManager1.AddDataModule(TdmInIOCPTest, 'http_dataModule2');
InIOCPServer1.Active := True; // 开启服务
FrameIOCPSvrInfo1.Start(InIOCPServer1); // 开始统计
end;
procedure TFormInIOCPHttpServer.btnStopClick(Sender: TObject);
begin
InIOCPServer1.Active := False; // 停止服务
FrameIOCPSvrInfo1.Stop; // 停止统计
iocp_log.TLogThread.StopLog; // 停止日志
end;
procedure TFormInIOCPHttpServer.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
btnStopClick(nil);
end;
procedure TFormInIOCPHttpServer.FormCreate(Sender: TObject);
var
WebSite: String;
begin
// 本地路径
FAppDir := ExtractFilePath(Application.ExeName);
WebSite := AddBackslash(InHttpDataProvider1.RootDirectory);
MyCreateDir(FAppDir + 'log');
MyCreateDir(WebSite + 'downloads');
MyCreateDir(WebSite + 'uploads');
end;
procedure TFormInIOCPHttpServer.InHttpDataProvider1Accept(Sender: TObject;
Request: THttpRequest; var Accept: Boolean);
begin
// 参数表有调整!
// 在此判断是否接受请求:
// Request.Method: 方法
// Request.URI:路径/资源
case Request.Method of
hmGet:
Accept := True; // (Request.URI = '/') or (Request.URI = '/a') or (Request.URI = '/t');
hmPost:
Accept := True; // (Request.URI = '/') or (Request.URI = '/a') or (Request.URI = '/t');
else // 测试其他方法
Accept := True;
end;
end;
procedure TFormInIOCPHttpServer.InHttpDataProvider1Get(Sender: TObject;
Request: THttpRequest; Response: THttpResponse);
var
Stream: TStream;
FileName: string;
begin
// Get: 检查请求命令,反馈数据
// 系统的全部服务端管理组件的事件中,类型为 TObject 的 Sender
// 都是任务执行者实例(Worker),其中的 TBusiWorker(Sender).DataModule
// 是数模实例(要加入数据库管理组件),可以用来操作数据库,如:
// TBusiWorker(Sender).DataModule.HttpExecSQL(Request, Response);
// TBusiWorker(Sender).DataModule.HttpExecQuery(Request, Response);
// TBusiWorker(Sender).DataModules[1].HttpExecSQL(Request, Response);
// TBusiWorker(Sender).DataModules[1].HttpExecQuery(Request, Response);
// 用 iocp_utils.DataSetToJSON() 把数据集快速转为 JSON。
// 详细请看数模基类单元 iocp_datModuleIB.pas。
// 本例子的数模是 mdTestDatabase.TInIOCPDataModuleTest 的实例。
// 1. 下载文件 ==============================
// InHttpDataProvider1.RootDirectory 是网站路径
if Pos('/downloads', Request.URI) > 0 then
begin
FileName := FAppDir + Request.URI;
if Request.URI = '/web_site/downloads/中文-A09.txt' then
Response.TransmitFile(FileName) // IE浏览器自动显示
else
if Request.URI = '/web_site/downloads/httptest.exe' then
Response.TransmitFile(FileName)
else
if Request.URI = '/web_site/downloads/InIOCP技术要点.doc' then
begin
Stream := TIOCPDocument.Create(AdjustFileName(FileName));
Response.SendStream(Stream); // 发送文件流(自动释放)
end else
if Request.URI = '/web_site/downloads/InIOCP技术要点2.doc' then
begin
FileName := FAppDir + '/web_site/downloads/InIOCP技术要点.doc';
Stream := TIOCPDocument.Create(AdjustFileName(FileName));
Response.SendStream(Stream, True); // 压缩文件流(自动释放)
end else
if Request.URI = '/web_site/downloads/jdk-8u77-windows-i586.exe' then
begin
// 测试大文件下载(支持断点续传)
Response.TransmitFile('F:\Backup\jdk-8u77-windows-i586.exe');
end else
if Request.URI = '/web_site/downloads/test.jpg' then
begin
Response.TransmitFile('web_site\downloads\test.jpg');
end else
begin // 测试 chunk,分块发送
Stream := TIOCPDocument.Create(AdjustFileName(FileName));
try
Response.SendChunk(Stream); // 立刻发送,不释放(改进,内部自动发送结束标志)
finally
Stream.Free;
end;
end;
end else
// 2. ajax 动态页面,参考网页文件 login.htm、ajax.htm
if Pos('/ajax', Request.URI) > 0 then
begin
// 放在前面,不检查 Session,方便 ab.exe 大并发测试
if Request.URI = '/ajax/query_xzqh.pas' then
begin
// AJAX 查询数据表,方法:
// 1. 使用默认数模:TBusiWorker(Sender).DataModule.HttpExecQuery(Request, Respone)
// 2. 指定数模:TBusiWorker(Sender).DataModules[1].HttpExecQuery(Request, Respone)
// 测试大并发查询数据库
// 使用工具 ab.exe,URL 用:
// /ajax/query_xzqh.pas?SQL=Select_tbl_xzqh2
// 使用 Select_tbl_xzqh2 对应的 SQL 命令查询数据
TBusiWorker(Sender).DataModule.HttpExecQuery(Request, Response);
// 有多个数模时,使用 DataModules[x]
{ if Respone.HasSession then
TBusiWorker(Sender).DataModules[1].HttpExecQuery(Request, Respone)
else
Respone.SetContent(HTTP_INVALID_SESSION); }
end else
if (Request.URI = '/ajax/login') then // 登录
Response.TransmitFile('web_site\ajax\login.htm')
else
// 退出登录 或 Session 无效
if (Request.URI = '/ajax/quit') or not Response.HasSession then
begin
// 客户端的 ajax 代码内部不能监测重定位 302
// 调整:InvalidSession 改为 RemoveSession,不直接发送 HTTP_INVALID_SESSION
Response.RemoveSession; // 删除、返回无效的 Cookie, 安全退出
Response.SetContent(HTTP_INVALID_SESSION); // 客户端重定位到登录页面
end else
if Request.URI = '/ajax/ajax_text.txt' then
// AJAX 请求文本,IE 可能乱码,chrome 正常
Response.TransmitFile('web_site\ajax\ajax_text.txt')
else
if Request.URI = '/ajax/server_time.pas' then
// AJAX 取服务器时间
Response.SetContent('<p>服务器时间:' + GetHttpGMTDateTime + '</p>');
end else
begin
// 3. 普通页面 ==============================
// 三种类型的表单,POST 的参数编码不同,解码不同
if Request.URI = '/test_a.htm' then // 上传文件,表单类型:multipart/form-data
Response.TransmitFile('web_site\html\test_a.htm')
else
if Request.URI = '/test_b.htm' then // 表单类型:application/x-www-form-urlencoded
Response.TransmitFile('web_site\html\test_b.htm')
else
if Request.URI = '/test_c.htm' then // 表单类型:text/plain
Response.TransmitFile('web_site\html\test_c.htm')
else // 首页
if (Request.URI = '/favicon.ico') then
Response.StatusCode := 204 // 没有东西
else
Response.TransmitFile('web_site\html\index.htm');
end;
end;
procedure TFormInIOCPHttpServer.InHttpDataProvider1Post(Sender: TObject;
Request: THttpRequest; Response: THttpResponse);
begin
// Post:已经接收完毕,调用此事件
// 此时:Request.Complete = True
if Request.URI = '/ajax/login' then // 动态页面
begin
with memo1.Lines do
begin
Add('登录信息:');
Add(' userName=' + Request.Params.AsString['user_name']);
Add(' password=' + Request.Params.AsString['user_password']);
end;
if (Request.Params.AsString['user_name'] <> '') and
(Request.Params.AsString['user_password'] <> '') then // 登录成功
begin
Response.CreateSession; // 生成 Session!
Response.TransmitFile('web_site\ajax\ajax.htm');
end else
Response.Redirect('/ajax/login'); // 重定位到登录页面
end else
begin
with memo1.Lines do
begin
Add('HTTP 服务:');
Add(' textline=' + Request.Params.AsString['textline']);
Add(' textline2=' + Request.Params.AsString['textline2']);
Add(' onefile=' + Request.Params.AsString['onefile']);
Add(' morefiles=' + Request.Params.AsString['morefiles']);
end;
Response.SetContent('<html><body>In-IOCP HTTP 服务!<br>提交成功!<br>');
Response.AddContent('<a href="' + Request.URI + '">返回</a><br></body></html>');
end;
end;
procedure TFormInIOCPHttpServer.InHttpDataProvider1ReceiveFile(Sender: TObject;
Request: THttpRequest; const FileName: string; Data: PAnsiChar;
DataLength: Integer; State: THttpPostState);
var
S: String;
begin
// 参数表有调整!
// Post: 已经接收完毕,收到上传的文件,保存到文件流
case State of
hpsRequest: begin // 请求状态
S := ExtractFileName(FileName);
if not FileExists('web_site\uploads\' + S) then
THttpSocket(Request.Owner).CreateStream('web_site\uploads\' + S);
end;
hpsRecvData: begin // 保存、关闭文件流
THttpSocket(Request.Owner).WriteStream(Data, DataLength);
THttpSocket(Request.Owner).CloseStream;
end;
end;
end;
procedure TFormInIOCPHttpServer.InIOCPServer1AfterClose(Sender: TObject);
begin
btnStart.Enabled := not InIOCPServer1.Active;
btnStop.Enabled := InIOCPServer1.Active;
end;
procedure TFormInIOCPHttpServer.InIOCPServer1AfterOpen(Sender: TObject);
begin
btnStart.Enabled := not InIOCPServer1.Active;
btnStop.Enabled := InIOCPServer1.Active;
Memo1.Lines.Add('ip: ' + InIOCPServer1.ServerAddr);
Memo1.Lines.Add('port: ' + IntToStr(InIOCPServer1.ServerPort));
end;
end.
|
program trigonometri;
// Global Variable
var
i,j,n: integer;
x,h,y: real;
// Power
function power(y: real; n: integer): real;
begin
power:=1;
for i:=1 to n do
begin
power:=power*y;
end;
end;
// Factorial
function factorial(a: integer): longint;
begin
factorial:=1;
for j:=1 to a do
begin
factorial:=factorial*j;
end;
end;
// Sinus
function sinus(x: real): real;
begin
sinus:=0;
n:=0;
y:=3.1415926535897932384626433832795;
x:=x*y/180;
repeat
h:=power(-1,n)*power(x,(2*n)+1)/factorial((2*n)+1);
sinus:=sinus+h;
n:=n+1
until (h<= 0.01)
end;
// Cosinus
function cosinus(x: real): real;
begin
cosinus:=0;
n:=0;
y:=3.1415926535897932384626433832795;
x:=x*y/180;
repeat
h:=power(-1,n)*power(x,2*n)/factorial(2*n);
cosinus:=cosinus+h;
n:=n+1
until (h<= 0.01)
end;
// Tangent
function tangent(x: real): real;
begin
tangent:=0;
y:=3.1415926535897932384626433832795;
x:=x*y/180;
h:=sinus(x)/cosinus(x);
tangent:=tangent+h;
end;
// Procedure Trigonometry
procedure trigonometry;
begin
write('x = ');
readln(x);
writeln('sin x = ', sinus(x):0:16);
writeln('cos x = ', cosinus(x):0:16);
writeln('tan x = ', tangent(x):0:16);
end;
// Summoning Trigonometry Program
begin
trigonometry;
readln;
end.
|
unit LanderTypes;
interface
uses
Windows, Graphics, GameTypes;
const
idNone = -1;
type
TLandOption = (loGrated, loGlassed, loShaded, loRedShaded, loColorShaded, loBlackShaded, loUpProjected, loNoClip, loReddened, loColorTinted, loGrayed, loRedded, loGreened, loDarkened);
TLandOptions = set of TLandOption;
TLandState = (lsFocusable, lsGrounded, lsOverlayedGround, lsOverlayed, lsDoubleOverlayed, lsHighLand);
TLandStates = set of TLandState;
type
TObjInfo =
object
id : integer;
angle : TAngle;
frame : integer;
Options : TLandOptions;
Caption : string;
shadeid : integer;
end;
type
TOffsetedObjInfo =
object(TObjInfo)
x, y : integer;
end;
const
cMaxItemOverlays = 10;
type
TItemOverlayInfo =
record
count : integer;
objects : array [1..cMaxItemOverlays] of TOffsetedObjInfo;
end;
type
TItemInfo =
object(TObjInfo)
r, c : integer;
Size : integer;
States : TLandStates;
Overlays : TItemOverlayInfo;
end;
const
cMaxAirObjs = 20;
type
TAirObjInfo =
object(TOffsetedObjInfo)
r, c : integer;
end;
type
TAirObjsInfo =
record
count : integer;
objects : array [0..pred(cMaxAirObjs)] of TAirObjInfo;
end;
{$IFDEF SHOWCNXS}
type
TCnxKind = (cnxkNone, cnxkOutputs, cnxkInputs);
type
TCnxInfo =
record
r, c : integer;
color : TColor;
end;
type
PCnxInfoArray = ^TCnxInfoArray;
TCnxInfoArray = array [0..0] of TCnxInfo;
type
TCnxsInfo =
record
cnxkind : TCnxKind;
r, c : integer;
cnxcount : integer;
cnxs : PCnxInfoArray;
end;
{$ENDIF}
type
ICoordinateConverter =
interface
function ObjectToMap(const view : IGameView; x, y : integer; out i, j : integer; checkbase : boolean) : boolean;
function ScreenToMap(const view : IGameView; x, y : integer; out i, j : integer) : boolean;
function MapToScreen(const view : IGameView; i, j : integer; out x, y : integer) : boolean;
procedure GetViewRegion(const view : IGameView; out imin, jmin, imax, jmax : integer);
end;
type
ILanderMap =
interface
function GetRows : integer;
function GetColumns : integer;
function GetGroundInfo(i, j : integer; const focus : IGameFocus; out which : TObjInfo) : boolean;
function GetGroundOverlayInfo(i, j : integer; const focus : IGameFocus; out which : TItemInfo) : boolean;
function GetItemInfo(i, j : integer; const focus : IGameFocus; out which : TItemInfo) : boolean;
function GetItemOverlayInfo(i, j : integer; const focus : IGameFocus; out which : TItemOverlayInfo) : boolean;
{$IFDEF SHOWCNXS}
function GetCnxsInfo(const focus : IGameFocus; out which : TCnxsInfo) : boolean;
{$ENDIF}
function GetFocusObjectInfo(const focus : IGameFocus; const R : TRect; out which : TOffsetedObjInfo) : boolean;
function GetSurfaceInfo(i, j : integer; const focus : IGameFocus; out which : TObjInfo) : boolean;
function GetAirInfo(const focus : IGameFocus; const R : TRect; out which : TAirObjsInfo) : boolean;
function CreateFocus(const view : IGameView) : IGameFocus;
function GetImager(const focus : IGameFocus) : IImager;
procedure SetImageSuit( ImageSuit : integer );
function GetImageSuit : integer;
end;
implementation
end.
|
unit MainData;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBTables, IBQuery, IBCustomDataSet, IBTable, IBDatabase;
type
TDmMain = class(TDataModule)
IBDatabase1: TIBDatabase;
QueryId: TIBQuery;
IBTransaction2: TIBTransaction;
public
function GetNewId: Integer;
end;
var
DmMain: TDmMain;
implementation
{$R *.DFM}
function TDmMain.GetNewId: Integer;
begin
// return the next value of the generator
QueryId.Open;
try
Result := QueryId.Fields[0].AsInteger;
finally
QueryId.Close;
end;
end;
end.
|
unit NtUtils.Tokens.Impersonate;
interface
uses
NtUtils.Exceptions;
// Save current impersonation token before operations that can alter it
function NtxBackupImpersonation(hThread: THandle): THandle;
procedure NtxRestoreImpersonation(hThread: THandle; hToken: THandle);
// Set thread token
function NtxSetThreadToken(hThread: THandle; hToken: THandle): TNtxStatus;
function NtxSetThreadTokenById(TID: NativeUInt; hToken: THandle): TNtxStatus;
// Set thread token and make sure it was not duplicated to Identification level
function NtxSafeSetThreadToken(hThread: THandle; hToken: THandle): TNtxStatus;
function NtxSafeSetThreadTokenById(TID: NativeUInt; hToken: THandle): TNtxStatus;
// Impersonate the token of any type on the current thread
function NtxImpersonateAnyToken(hToken: THandle): TNtxStatus;
// Assign primary token to a process
function NtxAssignPrimaryToken(hProcess: THandle; hToken: THandle): TNtxStatus;
function NtxAssignPrimaryTokenById(PID: NativeUInt; hToken: THandle): TNtxStatus;
implementation
uses
Winapi.WinNt, Ntapi.ntdef, Ntapi.ntstatus, Ntapi.ntpsapi, Ntapi.ntseapi,
NtUtils.Objects, NtUtils.Tokens, NtUtils.Ldr, NtUtils.Processes,
NtUtils.Threads, NtUtils.Objects.Compare;
{ Impersonation }
function NtxBackupImpersonation(hThread: THandle): THandle;
var
Status: NTSTATUS;
begin
// Open the thread's token
Status := NtxOpenThreadToken(Result, hThread, TOKEN_IMPERSONATE).Status;
if Status = STATUS_NO_TOKEN then
Result := 0
else if not NT_SUCCESS(Status) then
begin
// Most likely the token is here, but we can't access it. Although we can
// make a copy via direct impersonation, I am not sure we should do it.
// Currently, just clear the token as most of Winapi functions do in this
// situation
Result := 0;
if hThread = NtCurrentThread then
ENtError.Report(Status, 'NtxBackupImpersonation');
end;
end;
procedure NtxRestoreImpersonation(hThread: THandle; hToken: THandle);
var
Status: NTSTATUS;
begin
// Try to establish the previous token
Status := NtxSetThreadToken(hThread, hToken).Status;
if not NT_SUCCESS(Status) then
begin
// On failure clear the token (if it's still here)
if hToken <> 0 then
NtxSetThreadToken(hThread, 0);
if hThread = NtCurrentThread then
ENtError.Report(Status, 'NtxRestoreImpersonation');
end;
end;
function NtxSetThreadToken(hThread: THandle; hToken: THandle): TNtxStatus;
begin
Result := NtxThread.SetInfo<THandle>(hThread, ThreadImpersonationToken,
hToken);
// TODO: what about inconsistency with NtCurrentTeb.IsImpersonating ?
end;
function NtxSetThreadTokenById(TID: NativeUInt; hToken: THandle): TNtxStatus;
var
hThread: THandle;
begin
Result := NtxOpenThread(hThread, TID, THREAD_SET_THREAD_TOKEN);
if not Result.IsSuccess then
Exit;
Result := NtxSetThreadToken(hThread, hToken);
NtxSafeClose(hThread);
end;
{ Some notes about safe impersonation...
In case of absence of SeImpersonatePrivilege some security contexts
might cause the system to duplicate the token to Identification level
which fails all access checks. The result of NtSetInformationThread
does not provide information whether it happened.
The goal is to detect and avoid such situations.
NtxSafeSetThreadToken sets the token, queries it back, and compares these
two. Anything but success causes the routine to undo the work.
NOTE: The secutity context of the target thread is not guaranteed to return
to its previous state. It might happen if the target thread is impersonating
a token that the caller can't open. In this case after the failed call the
target thread will have no token.
To address this issue the caller can make a copy of the target thread's
security context by using NtImpersonateThread. See implementation of
NtxOpenEffectiveToken for more details.
Other possible implementations:
* NtImpersonateThread fails with BAD_IMPERSONATION_LEVEL when we request
Impersonation-level token while the thread's token is Identification or less.
}
function NtxSafeSetThreadToken(hThread: THandle; hToken: THandle): TNtxStatus;
var
hOldStateToken, hActuallySetToken: THandle;
begin
// No need to use safe impersonation to revoke tokens
if hToken = 0 then
Exit(NtxSetThreadToken(hThread, hToken));
// Backup old state
hOldStateToken := NtxBackupImpersonation(hThread);
// Set the token
Result := NtxSetThreadToken(hThread, hToken);
if not Result.IsSuccess then
begin
if hOldStateToken <> 0 then
NtxSafeClose(hOldStateToken);
Exit;
end;
// Read it back for comparison. Any access works for us.
Result := NtxOpenThreadToken(hActuallySetToken, hThread, MAXIMUM_ALLOWED);
if not Result.IsSuccess then
begin
// Reset and exit
NtxRestoreImpersonation(hThread, hOldStateToken);
if hOldStateToken <> 0 then
NtxSafeClose(hOldStateToken);
Exit;
end;
// Revert the current thread (if it's the target) to perform comparison
if hThread = NtCurrentThread then
NtxRestoreImpersonation(hThread, hOldStateToken);
// Compare the one we were trying to set with the one actually set
Result.Location := 'NtxCompareObjects';
Result.Status := NtxCompareObjects(hToken, hActuallySetToken, 'Token');
NtxSafeClose(hActuallySetToken);
// STATUS_SUCCESS => Impersonation works fine, use it.
// STATUS_NOT_SAME_OBJECT => Duplication happened, reset and exit
// Oher errors => Reset and exit
// SeImpersonatePrivilege on the target process can help
if Result.Status = STATUS_NOT_SAME_OBJECT then
begin
Result.Location := 'NtxSafeSetThreadToken';
Result.LastCall.ExpectedPrivilege := SE_IMPERSONATE_PRIVILEGE;
Result.Status := STATUS_PRIVILEGE_NOT_HELD;
end;
if Result.Status = STATUS_SUCCESS then
begin
// Repeat in case of the current thread (we reverted it for comparison)
if hThread = NtCurrentThread then
Result := NtxSetThreadToken(hThread, hToken);
end
else
begin
// Failed, reset the security context if we haven't done it yet
if hThread <> NtCurrentThread then
NtxRestoreImpersonation(hThread, hOldStateToken);
end;
if hOldStateToken <> 0 then
NtxSafeClose(hOldStateToken);
end;
function NtxSafeSetThreadTokenById(TID: NativeUInt; hToken: THandle):
TNtxStatus;
var
hThread: THandle;
begin
Result := NtxOpenThread(hThread, TID, THREAD_QUERY_LIMITED_INFORMATION or
THREAD_SET_THREAD_TOKEN);
if not Result.IsSuccess then
Exit;
Result := NtxSafeSetThreadToken(hThread, hToken);
NtxSafeClose(hThread);
end;
function NtxImpersonateAnyToken(hToken: THandle): TNtxStatus;
var
hImpToken: THandle;
begin
// Try to impersonate (in case it is an impersonation-type token)
Result := NtxSetThreadToken(NtCurrentThread, hToken);
if Result.Matches(STATUS_BAD_TOKEN_TYPE, 'NtSetInformationThread') then
begin
// Nope, it is a primary token, duplicate it
Result := NtxDuplicateToken(hImpToken, hToken, TOKEN_IMPERSONATE,
TokenImpersonation, SecurityImpersonation);
if Result.IsSuccess then
begin
// Impersonate, second attempt
Result := NtxSetThreadToken(NtCurrentThread, hImpToken);
NtxSafeClose(hImpToken);
end;
end;
end;
function NtxAssignPrimaryToken(hProcess: THandle;
hToken: THandle): TNtxStatus;
var
AccessToken: TProcessAccessToken;
begin
AccessToken.Thread := 0; // Looks like the call ignores it
AccessToken.Token := hToken;
Result := NtxProcess.SetInfo<TProcessAccessToken>(hProcess,
ProcessAccessToken, AccessToken);
end;
function NtxAssignPrimaryTokenById(PID: NativeUInt;
hToken: THandle): TNtxStatus;
var
hProcess: THandle;
begin
Result := NtxOpenProcess(hProcess, PID, PROCESS_SET_INFORMATION);
if not Result.IsSuccess then
Exit;
Result := NtxAssignPrimaryToken(hProcess, hToken);
NtxSafeClose(hProcess);
end;
end.
|
unit PrintDialogKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы PrintDialog }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Search\PrintDialogKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "PrintDialogKeywordsPack" MUID: (1127EF0E219F)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, vtRadioButton
{$If Defined(Nemesis)}
, nscComboBox
{$IfEnd} // Defined(Nemesis)
, vtSpinEdit
, vtCheckBox
, vtComboBoxQS
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(NoScripts)
implementation
{$If NOT Defined(Admin) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, PrintDialog_Form
, tfwControlString
{$If NOT Defined(NoVCL)}
, kwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
, tfwScriptingInterfaces
, tfwPropertyLike
, TypInfo
, tfwTypeInfo
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
;
type
Tkw_Form_PrintDialog = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы PrintDialog
----
*Пример использования*:
[code]
'aControl' форма::PrintDialog TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_PrintDialog
Tkw_PrintDialog_Control_poDocumentNames = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола poDocumentNames
----
*Пример использования*:
[code]
контрол::poDocumentNames TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_poDocumentNames
Tkw_PrintDialog_Control_poDocumentNames_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола poDocumentNames
----
*Пример использования*:
[code]
контрол::poDocumentNames:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_poDocumentNames_Push
Tkw_PrintDialog_Control_rbPrintSelected = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола rbPrintSelected
----
*Пример использования*:
[code]
контрол::rbPrintSelected TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_rbPrintSelected
Tkw_PrintDialog_Control_rbPrintSelected_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола rbPrintSelected
----
*Пример использования*:
[code]
контрол::rbPrintSelected:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_rbPrintSelected_Push
Tkw_PrintDialog_Control_rbPrintCurrent = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола rbPrintCurrent
----
*Пример использования*:
[code]
контрол::rbPrintCurrent TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_rbPrintCurrent
Tkw_PrintDialog_Control_rbPrintCurrent_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола rbPrintCurrent
----
*Пример использования*:
[code]
контрол::rbPrintCurrent:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_rbPrintCurrent_Push
Tkw_PrintDialog_Control_edPrintInterval = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edPrintInterval
----
*Пример использования*:
[code]
контрол::edPrintInterval TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_edPrintInterval
Tkw_PrintDialog_Control_edPrintInterval_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edPrintInterval
----
*Пример использования*:
[code]
контрол::edPrintInterval:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_edPrintInterval_Push
Tkw_PrintDialog_Control_edCopyCount = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола edCopyCount
----
*Пример использования*:
[code]
контрол::edCopyCount TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_edCopyCount
Tkw_PrintDialog_Control_edCopyCount_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола edCopyCount
----
*Пример использования*:
[code]
контрол::edCopyCount:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_edCopyCount_Push
Tkw_PrintDialog_Control_CollateCheckBox = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола CollateCheckBox
----
*Пример использования*:
[code]
контрол::CollateCheckBox TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_CollateCheckBox
Tkw_PrintDialog_Control_CollateCheckBox_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола CollateCheckBox
----
*Пример использования*:
[code]
контрол::CollateCheckBox:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_CollateCheckBox_Push
Tkw_PrintDialog_Control_cbOddEven = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола cbOddEven
----
*Пример использования*:
[code]
контрол::cbOddEven TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_cbOddEven
Tkw_PrintDialog_Control_cbOddEven_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола cbOddEven
----
*Пример использования*:
[code]
контрол::cbOddEven:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_cbOddEven_Push
Tkw_PrintDialog_Control_poDocumentTexts = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола poDocumentTexts
----
*Пример использования*:
[code]
контрол::poDocumentTexts TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_poDocumentTexts
Tkw_PrintDialog_Control_poDocumentTexts_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола poDocumentTexts
----
*Пример использования*:
[code]
контрол::poDocumentTexts:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_poDocumentTexts_Push
Tkw_PrintDialog_Control_rbPrintAll = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола rbPrintAll
----
*Пример использования*:
[code]
контрол::rbPrintAll TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_rbPrintAll
Tkw_PrintDialog_Control_rbPrintAll_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола rbPrintAll
----
*Пример использования*:
[code]
контрол::rbPrintAll:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_rbPrintAll_Push
Tkw_PrintDialog_Control_rbPrintInterval = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола rbPrintInterval
----
*Пример использования*:
[code]
контрол::rbPrintInterval TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_rbPrintInterval
Tkw_PrintDialog_Control_rbPrintInterval_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола rbPrintInterval
----
*Пример использования*:
[code]
контрол::rbPrintInterval:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_rbPrintInterval_Push
Tkw_PrintDialog_Control_cbPrinter = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола cbPrinter
----
*Пример использования*:
[code]
контрол::cbPrinter TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_cbPrinter
Tkw_PrintDialog_Control_cbPrinter_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола cbPrinter
----
*Пример использования*:
[code]
контрол::cbPrinter:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_cbPrinter_Push
Tkw_PrintDialog_Control_cbPrintInfo = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола cbPrintInfo
----
*Пример использования*:
[code]
контрол::cbPrintInfo TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_cbPrintInfo
Tkw_PrintDialog_Control_cbPrintInfo_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола cbPrintInfo
----
*Пример использования*:
[code]
контрол::cbPrintInfo:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_PrintDialog_Control_cbPrintInfo_Push
TkwEnPrintDialogPoDocumentNames = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.poDocumentNames }
private
function poDocumentNames(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.poDocumentNames }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogPoDocumentNames
TkwEnPrintDialogRbPrintSelected = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.rbPrintSelected }
private
function rbPrintSelected(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.rbPrintSelected }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogRbPrintSelected
TkwEnPrintDialogRbPrintCurrent = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.rbPrintCurrent }
private
function rbPrintCurrent(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.rbPrintCurrent }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogRbPrintCurrent
TkwEnPrintDialogEdPrintInterval = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.edPrintInterval }
private
function edPrintInterval(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TnscEditWithoutPlusMinusShortcut;
{* Реализация слова скрипта .Ten_PrintDialog.edPrintInterval }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogEdPrintInterval
TkwEnPrintDialogEdCopyCount = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.edCopyCount }
private
function edCopyCount(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtSpinEdit;
{* Реализация слова скрипта .Ten_PrintDialog.edCopyCount }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogEdCopyCount
TkwEnPrintDialogCollateCheckBox = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.CollateCheckBox }
private
function CollateCheckBox(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtCheckBox;
{* Реализация слова скрипта .Ten_PrintDialog.CollateCheckBox }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogCollateCheckBox
TkwEnPrintDialogCbOddEven = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.cbOddEven }
private
function cbOddEven(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtComboBoxQS;
{* Реализация слова скрипта .Ten_PrintDialog.cbOddEven }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogCbOddEven
TkwEnPrintDialogPoDocumentTexts = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.poDocumentTexts }
private
function poDocumentTexts(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.poDocumentTexts }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogPoDocumentTexts
TkwEnPrintDialogRbPrintAll = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.rbPrintAll }
private
function rbPrintAll(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.rbPrintAll }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogRbPrintAll
TkwEnPrintDialogRbPrintInterval = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.rbPrintInterval }
private
function rbPrintInterval(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.rbPrintInterval }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogRbPrintInterval
TkwEnPrintDialogCbPrinter = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.cbPrinter }
private
function cbPrinter(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtComboBoxQS;
{* Реализация слова скрипта .Ten_PrintDialog.cbPrinter }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogCbPrinter
TkwEnPrintDialogCbPrintInfo = {final} class(TtfwPropertyLike)
{* Слово скрипта .Ten_PrintDialog.cbPrintInfo }
private
function cbPrintInfo(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtCheckBox;
{* Реализация слова скрипта .Ten_PrintDialog.cbPrintInfo }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwEnPrintDialogCbPrintInfo
function Tkw_Form_PrintDialog.GetString: AnsiString;
begin
Result := 'en_PrintDialog';
end;//Tkw_Form_PrintDialog.GetString
class procedure Tkw_Form_PrintDialog.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(Ten_PrintDialog);
end;//Tkw_Form_PrintDialog.RegisterInEngine
class function Tkw_Form_PrintDialog.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::PrintDialog';
end;//Tkw_Form_PrintDialog.GetWordNameForRegister
function Tkw_PrintDialog_Control_poDocumentNames.GetString: AnsiString;
begin
Result := 'poDocumentNames';
end;//Tkw_PrintDialog_Control_poDocumentNames.GetString
class procedure Tkw_PrintDialog_Control_poDocumentNames.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtRadioButton);
end;//Tkw_PrintDialog_Control_poDocumentNames.RegisterInEngine
class function Tkw_PrintDialog_Control_poDocumentNames.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::poDocumentNames';
end;//Tkw_PrintDialog_Control_poDocumentNames.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_poDocumentNames_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('poDocumentNames');
inherited;
end;//Tkw_PrintDialog_Control_poDocumentNames_Push.DoDoIt
class function Tkw_PrintDialog_Control_poDocumentNames_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::poDocumentNames:push';
end;//Tkw_PrintDialog_Control_poDocumentNames_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_rbPrintSelected.GetString: AnsiString;
begin
Result := 'rbPrintSelected';
end;//Tkw_PrintDialog_Control_rbPrintSelected.GetString
class procedure Tkw_PrintDialog_Control_rbPrintSelected.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtRadioButton);
end;//Tkw_PrintDialog_Control_rbPrintSelected.RegisterInEngine
class function Tkw_PrintDialog_Control_rbPrintSelected.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::rbPrintSelected';
end;//Tkw_PrintDialog_Control_rbPrintSelected.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_rbPrintSelected_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('rbPrintSelected');
inherited;
end;//Tkw_PrintDialog_Control_rbPrintSelected_Push.DoDoIt
class function Tkw_PrintDialog_Control_rbPrintSelected_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::rbPrintSelected:push';
end;//Tkw_PrintDialog_Control_rbPrintSelected_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_rbPrintCurrent.GetString: AnsiString;
begin
Result := 'rbPrintCurrent';
end;//Tkw_PrintDialog_Control_rbPrintCurrent.GetString
class procedure Tkw_PrintDialog_Control_rbPrintCurrent.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtRadioButton);
end;//Tkw_PrintDialog_Control_rbPrintCurrent.RegisterInEngine
class function Tkw_PrintDialog_Control_rbPrintCurrent.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::rbPrintCurrent';
end;//Tkw_PrintDialog_Control_rbPrintCurrent.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_rbPrintCurrent_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('rbPrintCurrent');
inherited;
end;//Tkw_PrintDialog_Control_rbPrintCurrent_Push.DoDoIt
class function Tkw_PrintDialog_Control_rbPrintCurrent_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::rbPrintCurrent:push';
end;//Tkw_PrintDialog_Control_rbPrintCurrent_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_edPrintInterval.GetString: AnsiString;
begin
Result := 'edPrintInterval';
end;//Tkw_PrintDialog_Control_edPrintInterval.GetString
class procedure Tkw_PrintDialog_Control_edPrintInterval.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscEditWithoutPlusMinusShortcut);
end;//Tkw_PrintDialog_Control_edPrintInterval.RegisterInEngine
class function Tkw_PrintDialog_Control_edPrintInterval.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edPrintInterval';
end;//Tkw_PrintDialog_Control_edPrintInterval.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_edPrintInterval_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edPrintInterval');
inherited;
end;//Tkw_PrintDialog_Control_edPrintInterval_Push.DoDoIt
class function Tkw_PrintDialog_Control_edPrintInterval_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edPrintInterval:push';
end;//Tkw_PrintDialog_Control_edPrintInterval_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_edCopyCount.GetString: AnsiString;
begin
Result := 'edCopyCount';
end;//Tkw_PrintDialog_Control_edCopyCount.GetString
class procedure Tkw_PrintDialog_Control_edCopyCount.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtSpinEdit);
end;//Tkw_PrintDialog_Control_edCopyCount.RegisterInEngine
class function Tkw_PrintDialog_Control_edCopyCount.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edCopyCount';
end;//Tkw_PrintDialog_Control_edCopyCount.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_edCopyCount_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('edCopyCount');
inherited;
end;//Tkw_PrintDialog_Control_edCopyCount_Push.DoDoIt
class function Tkw_PrintDialog_Control_edCopyCount_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::edCopyCount:push';
end;//Tkw_PrintDialog_Control_edCopyCount_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_CollateCheckBox.GetString: AnsiString;
begin
Result := 'CollateCheckBox';
end;//Tkw_PrintDialog_Control_CollateCheckBox.GetString
class procedure Tkw_PrintDialog_Control_CollateCheckBox.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtCheckBox);
end;//Tkw_PrintDialog_Control_CollateCheckBox.RegisterInEngine
class function Tkw_PrintDialog_Control_CollateCheckBox.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::CollateCheckBox';
end;//Tkw_PrintDialog_Control_CollateCheckBox.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_CollateCheckBox_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('CollateCheckBox');
inherited;
end;//Tkw_PrintDialog_Control_CollateCheckBox_Push.DoDoIt
class function Tkw_PrintDialog_Control_CollateCheckBox_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::CollateCheckBox:push';
end;//Tkw_PrintDialog_Control_CollateCheckBox_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_cbOddEven.GetString: AnsiString;
begin
Result := 'cbOddEven';
end;//Tkw_PrintDialog_Control_cbOddEven.GetString
class procedure Tkw_PrintDialog_Control_cbOddEven.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtComboBoxQS);
end;//Tkw_PrintDialog_Control_cbOddEven.RegisterInEngine
class function Tkw_PrintDialog_Control_cbOddEven.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::cbOddEven';
end;//Tkw_PrintDialog_Control_cbOddEven.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_cbOddEven_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('cbOddEven');
inherited;
end;//Tkw_PrintDialog_Control_cbOddEven_Push.DoDoIt
class function Tkw_PrintDialog_Control_cbOddEven_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::cbOddEven:push';
end;//Tkw_PrintDialog_Control_cbOddEven_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_poDocumentTexts.GetString: AnsiString;
begin
Result := 'poDocumentTexts';
end;//Tkw_PrintDialog_Control_poDocumentTexts.GetString
class procedure Tkw_PrintDialog_Control_poDocumentTexts.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtRadioButton);
end;//Tkw_PrintDialog_Control_poDocumentTexts.RegisterInEngine
class function Tkw_PrintDialog_Control_poDocumentTexts.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::poDocumentTexts';
end;//Tkw_PrintDialog_Control_poDocumentTexts.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_poDocumentTexts_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('poDocumentTexts');
inherited;
end;//Tkw_PrintDialog_Control_poDocumentTexts_Push.DoDoIt
class function Tkw_PrintDialog_Control_poDocumentTexts_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::poDocumentTexts:push';
end;//Tkw_PrintDialog_Control_poDocumentTexts_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_rbPrintAll.GetString: AnsiString;
begin
Result := 'rbPrintAll';
end;//Tkw_PrintDialog_Control_rbPrintAll.GetString
class procedure Tkw_PrintDialog_Control_rbPrintAll.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtRadioButton);
end;//Tkw_PrintDialog_Control_rbPrintAll.RegisterInEngine
class function Tkw_PrintDialog_Control_rbPrintAll.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::rbPrintAll';
end;//Tkw_PrintDialog_Control_rbPrintAll.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_rbPrintAll_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('rbPrintAll');
inherited;
end;//Tkw_PrintDialog_Control_rbPrintAll_Push.DoDoIt
class function Tkw_PrintDialog_Control_rbPrintAll_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::rbPrintAll:push';
end;//Tkw_PrintDialog_Control_rbPrintAll_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_rbPrintInterval.GetString: AnsiString;
begin
Result := 'rbPrintInterval';
end;//Tkw_PrintDialog_Control_rbPrintInterval.GetString
class procedure Tkw_PrintDialog_Control_rbPrintInterval.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtRadioButton);
end;//Tkw_PrintDialog_Control_rbPrintInterval.RegisterInEngine
class function Tkw_PrintDialog_Control_rbPrintInterval.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::rbPrintInterval';
end;//Tkw_PrintDialog_Control_rbPrintInterval.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_rbPrintInterval_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('rbPrintInterval');
inherited;
end;//Tkw_PrintDialog_Control_rbPrintInterval_Push.DoDoIt
class function Tkw_PrintDialog_Control_rbPrintInterval_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::rbPrintInterval:push';
end;//Tkw_PrintDialog_Control_rbPrintInterval_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_cbPrinter.GetString: AnsiString;
begin
Result := 'cbPrinter';
end;//Tkw_PrintDialog_Control_cbPrinter.GetString
class procedure Tkw_PrintDialog_Control_cbPrinter.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtComboBoxQS);
end;//Tkw_PrintDialog_Control_cbPrinter.RegisterInEngine
class function Tkw_PrintDialog_Control_cbPrinter.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::cbPrinter';
end;//Tkw_PrintDialog_Control_cbPrinter.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_cbPrinter_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('cbPrinter');
inherited;
end;//Tkw_PrintDialog_Control_cbPrinter_Push.DoDoIt
class function Tkw_PrintDialog_Control_cbPrinter_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::cbPrinter:push';
end;//Tkw_PrintDialog_Control_cbPrinter_Push.GetWordNameForRegister
function Tkw_PrintDialog_Control_cbPrintInfo.GetString: AnsiString;
begin
Result := 'cbPrintInfo';
end;//Tkw_PrintDialog_Control_cbPrintInfo.GetString
class procedure Tkw_PrintDialog_Control_cbPrintInfo.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtCheckBox);
end;//Tkw_PrintDialog_Control_cbPrintInfo.RegisterInEngine
class function Tkw_PrintDialog_Control_cbPrintInfo.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::cbPrintInfo';
end;//Tkw_PrintDialog_Control_cbPrintInfo.GetWordNameForRegister
procedure Tkw_PrintDialog_Control_cbPrintInfo_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('cbPrintInfo');
inherited;
end;//Tkw_PrintDialog_Control_cbPrintInfo_Push.DoDoIt
class function Tkw_PrintDialog_Control_cbPrintInfo_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::cbPrintInfo:push';
end;//Tkw_PrintDialog_Control_cbPrintInfo_Push.GetWordNameForRegister
function TkwEnPrintDialogPoDocumentNames.poDocumentNames(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.poDocumentNames }
begin
Result := aen_PrintDialog.poDocumentNames;
end;//TkwEnPrintDialogPoDocumentNames.poDocumentNames
class function TkwEnPrintDialogPoDocumentNames.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.poDocumentNames';
end;//TkwEnPrintDialogPoDocumentNames.GetWordNameForRegister
function TkwEnPrintDialogPoDocumentNames.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtRadioButton);
end;//TkwEnPrintDialogPoDocumentNames.GetResultTypeInfo
function TkwEnPrintDialogPoDocumentNames.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogPoDocumentNames.GetAllParamsCount
function TkwEnPrintDialogPoDocumentNames.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogPoDocumentNames.ParamsTypes
procedure TkwEnPrintDialogPoDocumentNames.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству poDocumentNames', aCtx);
end;//TkwEnPrintDialogPoDocumentNames.SetValuePrim
procedure TkwEnPrintDialogPoDocumentNames.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(poDocumentNames(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogPoDocumentNames.DoDoIt
function TkwEnPrintDialogRbPrintSelected.rbPrintSelected(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.rbPrintSelected }
begin
Result := aen_PrintDialog.rbPrintSelected;
end;//TkwEnPrintDialogRbPrintSelected.rbPrintSelected
class function TkwEnPrintDialogRbPrintSelected.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.rbPrintSelected';
end;//TkwEnPrintDialogRbPrintSelected.GetWordNameForRegister
function TkwEnPrintDialogRbPrintSelected.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtRadioButton);
end;//TkwEnPrintDialogRbPrintSelected.GetResultTypeInfo
function TkwEnPrintDialogRbPrintSelected.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogRbPrintSelected.GetAllParamsCount
function TkwEnPrintDialogRbPrintSelected.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogRbPrintSelected.ParamsTypes
procedure TkwEnPrintDialogRbPrintSelected.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству rbPrintSelected', aCtx);
end;//TkwEnPrintDialogRbPrintSelected.SetValuePrim
procedure TkwEnPrintDialogRbPrintSelected.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(rbPrintSelected(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogRbPrintSelected.DoDoIt
function TkwEnPrintDialogRbPrintCurrent.rbPrintCurrent(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.rbPrintCurrent }
begin
Result := aen_PrintDialog.rbPrintCurrent;
end;//TkwEnPrintDialogRbPrintCurrent.rbPrintCurrent
class function TkwEnPrintDialogRbPrintCurrent.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.rbPrintCurrent';
end;//TkwEnPrintDialogRbPrintCurrent.GetWordNameForRegister
function TkwEnPrintDialogRbPrintCurrent.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtRadioButton);
end;//TkwEnPrintDialogRbPrintCurrent.GetResultTypeInfo
function TkwEnPrintDialogRbPrintCurrent.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogRbPrintCurrent.GetAllParamsCount
function TkwEnPrintDialogRbPrintCurrent.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogRbPrintCurrent.ParamsTypes
procedure TkwEnPrintDialogRbPrintCurrent.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству rbPrintCurrent', aCtx);
end;//TkwEnPrintDialogRbPrintCurrent.SetValuePrim
procedure TkwEnPrintDialogRbPrintCurrent.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(rbPrintCurrent(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogRbPrintCurrent.DoDoIt
function TkwEnPrintDialogEdPrintInterval.edPrintInterval(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TnscEditWithoutPlusMinusShortcut;
{* Реализация слова скрипта .Ten_PrintDialog.edPrintInterval }
begin
Result := aen_PrintDialog.edPrintInterval;
end;//TkwEnPrintDialogEdPrintInterval.edPrintInterval
class function TkwEnPrintDialogEdPrintInterval.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.edPrintInterval';
end;//TkwEnPrintDialogEdPrintInterval.GetWordNameForRegister
function TkwEnPrintDialogEdPrintInterval.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscEditWithoutPlusMinusShortcut);
end;//TkwEnPrintDialogEdPrintInterval.GetResultTypeInfo
function TkwEnPrintDialogEdPrintInterval.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogEdPrintInterval.GetAllParamsCount
function TkwEnPrintDialogEdPrintInterval.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogEdPrintInterval.ParamsTypes
procedure TkwEnPrintDialogEdPrintInterval.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edPrintInterval', aCtx);
end;//TkwEnPrintDialogEdPrintInterval.SetValuePrim
procedure TkwEnPrintDialogEdPrintInterval.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edPrintInterval(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogEdPrintInterval.DoDoIt
function TkwEnPrintDialogEdCopyCount.edCopyCount(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtSpinEdit;
{* Реализация слова скрипта .Ten_PrintDialog.edCopyCount }
begin
Result := aen_PrintDialog.edCopyCount;
end;//TkwEnPrintDialogEdCopyCount.edCopyCount
class function TkwEnPrintDialogEdCopyCount.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.edCopyCount';
end;//TkwEnPrintDialogEdCopyCount.GetWordNameForRegister
function TkwEnPrintDialogEdCopyCount.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtSpinEdit);
end;//TkwEnPrintDialogEdCopyCount.GetResultTypeInfo
function TkwEnPrintDialogEdCopyCount.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogEdCopyCount.GetAllParamsCount
function TkwEnPrintDialogEdCopyCount.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogEdCopyCount.ParamsTypes
procedure TkwEnPrintDialogEdCopyCount.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству edCopyCount', aCtx);
end;//TkwEnPrintDialogEdCopyCount.SetValuePrim
procedure TkwEnPrintDialogEdCopyCount.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(edCopyCount(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogEdCopyCount.DoDoIt
function TkwEnPrintDialogCollateCheckBox.CollateCheckBox(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtCheckBox;
{* Реализация слова скрипта .Ten_PrintDialog.CollateCheckBox }
begin
Result := aen_PrintDialog.CollateCheckBox;
end;//TkwEnPrintDialogCollateCheckBox.CollateCheckBox
class function TkwEnPrintDialogCollateCheckBox.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.CollateCheckBox';
end;//TkwEnPrintDialogCollateCheckBox.GetWordNameForRegister
function TkwEnPrintDialogCollateCheckBox.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtCheckBox);
end;//TkwEnPrintDialogCollateCheckBox.GetResultTypeInfo
function TkwEnPrintDialogCollateCheckBox.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogCollateCheckBox.GetAllParamsCount
function TkwEnPrintDialogCollateCheckBox.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogCollateCheckBox.ParamsTypes
procedure TkwEnPrintDialogCollateCheckBox.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству CollateCheckBox', aCtx);
end;//TkwEnPrintDialogCollateCheckBox.SetValuePrim
procedure TkwEnPrintDialogCollateCheckBox.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(CollateCheckBox(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogCollateCheckBox.DoDoIt
function TkwEnPrintDialogCbOddEven.cbOddEven(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtComboBoxQS;
{* Реализация слова скрипта .Ten_PrintDialog.cbOddEven }
begin
Result := aen_PrintDialog.cbOddEven;
end;//TkwEnPrintDialogCbOddEven.cbOddEven
class function TkwEnPrintDialogCbOddEven.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.cbOddEven';
end;//TkwEnPrintDialogCbOddEven.GetWordNameForRegister
function TkwEnPrintDialogCbOddEven.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtComboBoxQS);
end;//TkwEnPrintDialogCbOddEven.GetResultTypeInfo
function TkwEnPrintDialogCbOddEven.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogCbOddEven.GetAllParamsCount
function TkwEnPrintDialogCbOddEven.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogCbOddEven.ParamsTypes
procedure TkwEnPrintDialogCbOddEven.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству cbOddEven', aCtx);
end;//TkwEnPrintDialogCbOddEven.SetValuePrim
procedure TkwEnPrintDialogCbOddEven.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(cbOddEven(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogCbOddEven.DoDoIt
function TkwEnPrintDialogPoDocumentTexts.poDocumentTexts(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.poDocumentTexts }
begin
Result := aen_PrintDialog.poDocumentTexts;
end;//TkwEnPrintDialogPoDocumentTexts.poDocumentTexts
class function TkwEnPrintDialogPoDocumentTexts.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.poDocumentTexts';
end;//TkwEnPrintDialogPoDocumentTexts.GetWordNameForRegister
function TkwEnPrintDialogPoDocumentTexts.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtRadioButton);
end;//TkwEnPrintDialogPoDocumentTexts.GetResultTypeInfo
function TkwEnPrintDialogPoDocumentTexts.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogPoDocumentTexts.GetAllParamsCount
function TkwEnPrintDialogPoDocumentTexts.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogPoDocumentTexts.ParamsTypes
procedure TkwEnPrintDialogPoDocumentTexts.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству poDocumentTexts', aCtx);
end;//TkwEnPrintDialogPoDocumentTexts.SetValuePrim
procedure TkwEnPrintDialogPoDocumentTexts.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(poDocumentTexts(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogPoDocumentTexts.DoDoIt
function TkwEnPrintDialogRbPrintAll.rbPrintAll(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.rbPrintAll }
begin
Result := aen_PrintDialog.rbPrintAll;
end;//TkwEnPrintDialogRbPrintAll.rbPrintAll
class function TkwEnPrintDialogRbPrintAll.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.rbPrintAll';
end;//TkwEnPrintDialogRbPrintAll.GetWordNameForRegister
function TkwEnPrintDialogRbPrintAll.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtRadioButton);
end;//TkwEnPrintDialogRbPrintAll.GetResultTypeInfo
function TkwEnPrintDialogRbPrintAll.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogRbPrintAll.GetAllParamsCount
function TkwEnPrintDialogRbPrintAll.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogRbPrintAll.ParamsTypes
procedure TkwEnPrintDialogRbPrintAll.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству rbPrintAll', aCtx);
end;//TkwEnPrintDialogRbPrintAll.SetValuePrim
procedure TkwEnPrintDialogRbPrintAll.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(rbPrintAll(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogRbPrintAll.DoDoIt
function TkwEnPrintDialogRbPrintInterval.rbPrintInterval(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtRadioButton;
{* Реализация слова скрипта .Ten_PrintDialog.rbPrintInterval }
begin
Result := aen_PrintDialog.rbPrintInterval;
end;//TkwEnPrintDialogRbPrintInterval.rbPrintInterval
class function TkwEnPrintDialogRbPrintInterval.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.rbPrintInterval';
end;//TkwEnPrintDialogRbPrintInterval.GetWordNameForRegister
function TkwEnPrintDialogRbPrintInterval.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtRadioButton);
end;//TkwEnPrintDialogRbPrintInterval.GetResultTypeInfo
function TkwEnPrintDialogRbPrintInterval.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogRbPrintInterval.GetAllParamsCount
function TkwEnPrintDialogRbPrintInterval.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogRbPrintInterval.ParamsTypes
procedure TkwEnPrintDialogRbPrintInterval.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству rbPrintInterval', aCtx);
end;//TkwEnPrintDialogRbPrintInterval.SetValuePrim
procedure TkwEnPrintDialogRbPrintInterval.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(rbPrintInterval(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogRbPrintInterval.DoDoIt
function TkwEnPrintDialogCbPrinter.cbPrinter(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtComboBoxQS;
{* Реализация слова скрипта .Ten_PrintDialog.cbPrinter }
begin
Result := aen_PrintDialog.cbPrinter;
end;//TkwEnPrintDialogCbPrinter.cbPrinter
class function TkwEnPrintDialogCbPrinter.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.cbPrinter';
end;//TkwEnPrintDialogCbPrinter.GetWordNameForRegister
function TkwEnPrintDialogCbPrinter.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtComboBoxQS);
end;//TkwEnPrintDialogCbPrinter.GetResultTypeInfo
function TkwEnPrintDialogCbPrinter.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogCbPrinter.GetAllParamsCount
function TkwEnPrintDialogCbPrinter.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogCbPrinter.ParamsTypes
procedure TkwEnPrintDialogCbPrinter.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству cbPrinter', aCtx);
end;//TkwEnPrintDialogCbPrinter.SetValuePrim
procedure TkwEnPrintDialogCbPrinter.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(cbPrinter(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogCbPrinter.DoDoIt
function TkwEnPrintDialogCbPrintInfo.cbPrintInfo(const aCtx: TtfwContext;
aen_PrintDialog: Ten_PrintDialog): TvtCheckBox;
{* Реализация слова скрипта .Ten_PrintDialog.cbPrintInfo }
begin
Result := aen_PrintDialog.cbPrintInfo;
end;//TkwEnPrintDialogCbPrintInfo.cbPrintInfo
class function TkwEnPrintDialogCbPrintInfo.GetWordNameForRegister: AnsiString;
begin
Result := '.Ten_PrintDialog.cbPrintInfo';
end;//TkwEnPrintDialogCbPrintInfo.GetWordNameForRegister
function TkwEnPrintDialogCbPrintInfo.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtCheckBox);
end;//TkwEnPrintDialogCbPrintInfo.GetResultTypeInfo
function TkwEnPrintDialogCbPrintInfo.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwEnPrintDialogCbPrintInfo.GetAllParamsCount
function TkwEnPrintDialogCbPrintInfo.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(Ten_PrintDialog)]);
end;//TkwEnPrintDialogCbPrintInfo.ParamsTypes
procedure TkwEnPrintDialogCbPrintInfo.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству cbPrintInfo', aCtx);
end;//TkwEnPrintDialogCbPrintInfo.SetValuePrim
procedure TkwEnPrintDialogCbPrintInfo.DoDoIt(const aCtx: TtfwContext);
var l_aen_PrintDialog: Ten_PrintDialog;
begin
try
l_aen_PrintDialog := Ten_PrintDialog(aCtx.rEngine.PopObjAs(Ten_PrintDialog));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aen_PrintDialog: Ten_PrintDialog : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(cbPrintInfo(aCtx, l_aen_PrintDialog));
end;//TkwEnPrintDialogCbPrintInfo.DoDoIt
initialization
Tkw_Form_PrintDialog.RegisterInEngine;
{* Регистрация Tkw_Form_PrintDialog }
Tkw_PrintDialog_Control_poDocumentNames.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_poDocumentNames }
Tkw_PrintDialog_Control_poDocumentNames_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_poDocumentNames_Push }
Tkw_PrintDialog_Control_rbPrintSelected.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_rbPrintSelected }
Tkw_PrintDialog_Control_rbPrintSelected_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_rbPrintSelected_Push }
Tkw_PrintDialog_Control_rbPrintCurrent.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_rbPrintCurrent }
Tkw_PrintDialog_Control_rbPrintCurrent_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_rbPrintCurrent_Push }
Tkw_PrintDialog_Control_edPrintInterval.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_edPrintInterval }
Tkw_PrintDialog_Control_edPrintInterval_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_edPrintInterval_Push }
Tkw_PrintDialog_Control_edCopyCount.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_edCopyCount }
Tkw_PrintDialog_Control_edCopyCount_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_edCopyCount_Push }
Tkw_PrintDialog_Control_CollateCheckBox.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_CollateCheckBox }
Tkw_PrintDialog_Control_CollateCheckBox_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_CollateCheckBox_Push }
Tkw_PrintDialog_Control_cbOddEven.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_cbOddEven }
Tkw_PrintDialog_Control_cbOddEven_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_cbOddEven_Push }
Tkw_PrintDialog_Control_poDocumentTexts.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_poDocumentTexts }
Tkw_PrintDialog_Control_poDocumentTexts_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_poDocumentTexts_Push }
Tkw_PrintDialog_Control_rbPrintAll.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_rbPrintAll }
Tkw_PrintDialog_Control_rbPrintAll_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_rbPrintAll_Push }
Tkw_PrintDialog_Control_rbPrintInterval.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_rbPrintInterval }
Tkw_PrintDialog_Control_rbPrintInterval_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_rbPrintInterval_Push }
Tkw_PrintDialog_Control_cbPrinter.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_cbPrinter }
Tkw_PrintDialog_Control_cbPrinter_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_cbPrinter_Push }
Tkw_PrintDialog_Control_cbPrintInfo.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_cbPrintInfo }
Tkw_PrintDialog_Control_cbPrintInfo_Push.RegisterInEngine;
{* Регистрация Tkw_PrintDialog_Control_cbPrintInfo_Push }
TkwEnPrintDialogPoDocumentNames.RegisterInEngine;
{* Регистрация en_PrintDialog_poDocumentNames }
TkwEnPrintDialogRbPrintSelected.RegisterInEngine;
{* Регистрация en_PrintDialog_rbPrintSelected }
TkwEnPrintDialogRbPrintCurrent.RegisterInEngine;
{* Регистрация en_PrintDialog_rbPrintCurrent }
TkwEnPrintDialogEdPrintInterval.RegisterInEngine;
{* Регистрация en_PrintDialog_edPrintInterval }
TkwEnPrintDialogEdCopyCount.RegisterInEngine;
{* Регистрация en_PrintDialog_edCopyCount }
TkwEnPrintDialogCollateCheckBox.RegisterInEngine;
{* Регистрация en_PrintDialog_CollateCheckBox }
TkwEnPrintDialogCbOddEven.RegisterInEngine;
{* Регистрация en_PrintDialog_cbOddEven }
TkwEnPrintDialogPoDocumentTexts.RegisterInEngine;
{* Регистрация en_PrintDialog_poDocumentTexts }
TkwEnPrintDialogRbPrintAll.RegisterInEngine;
{* Регистрация en_PrintDialog_rbPrintAll }
TkwEnPrintDialogRbPrintInterval.RegisterInEngine;
{* Регистрация en_PrintDialog_rbPrintInterval }
TkwEnPrintDialogCbPrinter.RegisterInEngine;
{* Регистрация en_PrintDialog_cbPrinter }
TkwEnPrintDialogCbPrintInfo.RegisterInEngine;
{* Регистрация en_PrintDialog_cbPrintInfo }
TtfwTypeRegistrator.RegisterType(TypeInfo(Ten_PrintDialog));
{* Регистрация типа Ten_PrintDialog }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtRadioButton));
{* Регистрация типа TvtRadioButton }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscEditWithoutPlusMinusShortcut));
{* Регистрация типа TnscEditWithoutPlusMinusShortcut }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtSpinEdit));
{* Регистрация типа TvtSpinEdit }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtCheckBox));
{* Регистрация типа TvtCheckBox }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtComboBoxQS));
{* Регистрация типа TvtComboBoxQS }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(NoScripts)
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uEditRecordParameters.pas }
{ Описание: Параметры для работы редактора записи }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uEditRecordParameters;
interface
uses
SysUtils, Classes, uKeyValue;
type
IEditRecordParameters = interface(IInterface)
['{B9730CA2-9F8F-4940-8778-212CFF6D0526}']
procedure AddDefaultValue(AFieldName: String; AValue: Variant); stdcall;
function GetCount: Integer;
function GetDefaultValues(Index: Integer): IKeyValue;
function GetRecordId: Variant; stdcall;
procedure SetRecordId(Value: Variant); stdcall;
property Count: Integer read GetCount;
property DefaultValues[Index: Integer]: IKeyValue read GetDefaultValues;
property RecordId: Variant read GetRecordId write SetRecordId;
end;
implementation
end.
|
unit Inventions;
interface
uses
Collection, Classes, MetaInstances, Accounts, CacheAgent, Languages;
// Inventions are developed by companies to improve production in general.
// Each invention has an identifier (byte) that is unique within a
// FacilityKind.
const
tidInvTag_Invention = 'invention';
tidInvTag_InventionSet = 'inventionset';
tidInvTag_Class = 'class';
tidInvTag_Link = 'link';
tidInvElement_Props = 'properties';
tidInvAttr_Kind = 'kind';
tidInvAttr_Id = 'id';
tidInvAttr_Name = 'name';
tidInvAttr_Category = 'category';
tidInvAttr_Parent = 'parent';
tidInvAttr_Location = 'location';
tidInvAttr_Price = 'price';
tidInvAttr_Effic = 'effic';
tidInvAttr_Q = 'Q';
tidInvAttr_Blocks = 'blocks';
tidInvAttr_Host = 'host';
tidInvAttr_FacId = 'facs';
tidInvAttr_Prestige = 'prestige';
tidInvElement_Requires = 'requires';
tidInvElement_Desc = 'description';
tidInvElement_Time = 'time';
tidInvElement_Cache = 'cache';
tidInvElement_Basic = 'basic';
tidInvElement_Applies = 'applies';
tidInvAttr_Class = 'class';
tidInvAttr_Enables = 'enables';
tidInvAttr_Technology = 'tech';
tidInvAttr_Value = 'value';
tidInvAttr_Tier = 'tier';
tidInvAttr_LicLevel = 'lclevel';
tidInvAttr_Volatile = 'volatile';
tidInvElement_Tiers = 'tiers';
tidInvAttr_Override = 'override';
tidInvAttr_Cluster = 'cluster';
tidInvAttr_Nobility = 'nob';
tidInvAttr_CatPos = 'catpos';
tidInvAttr_Obsolete = 'obsolete';
const
BitCount = 8;
const
StdHourlyCost = 0.5; //%
type
TCollection = Collection.TCollection;
type
Bits = 0..BitCount-1;
TBitSet = set of Bits;
PInventionIdArray = ^TInventionIdArray;
TInventionIdArray = array[0..$FFFF div BitCount] of TBitSet;
TInventionNumId = integer;
TInventionSet =
class
public
constructor Create(IniCount : integer);
destructor Destroy; override;
private
fCapacity : word;
fSets : PInventionIdArray;
private
function CountToSets(count : integer) : integer;
procedure Decompose(Elem : TInventionNumId; var Index : integer; var Value : Bits);
public
function Include(Elem : TInventionNumId) : boolean;
function Exclude(Elem : TInventionNumId) : boolean;
function Included(Elem : TInventionNumId) : boolean;
function IsEmpty : boolean;
procedure Clear;
end;
TInvention = class;
CInvention = class of TInvention;
TInvention =
class( TMetaInstance )
public
constructor Create( anId, aName, aKind, aResp : string );
constructor Load(xmlObj : OleVariant); virtual;
destructor Destroy; override;
private
fId : string;
fOldId : integer;
fNumId : TInventionNumId;
fName : string;
fKind : string;
fDesc : string;
fParent : string;
fName_MLS : TMultiString;
fDesc_MLS : TMultiString;
fResp_MLS : TMultiString;
fParent_MLS : TMultiString;
fPrice : TMoney;
fTime : integer;
fBasic : boolean;
fPrestige : integer;
fResp : string;
fLevel : integer;
fTier : integer;
fTierInfo : TStringList;
fReq : TCollection;
fReqIds : TStringList;
fLicLevel : single;
fVolatile : boolean;
fCache : boolean;
fEnablesTech : boolean;
fNobility : integer;
fCatPos : integer;
fObsolete : boolean;
private
procedure SetLicLevel(value : single);
published
property Id : string read fId;
property OldId : integer read fOldId; // >> temp
property NumId : TInventionNumId read fNumId;
property Name : string read fName;
property Kind : string read fKind;
property Desc : string read fDesc write fDesc;
property Name_MLS : TMultiString read fName_MLS;
property Desc_MLS : TMultiString read fDesc_MLS;
property Resp_MLS : TMultiString read fResp_MLS;
property Parent_MLS : TMultiString read fParent_MLS;
property Price : TMoney read fPrice write fPrice;
property Time : integer read fTime write fTime;
property Basic : boolean read fBasic write fBasic;
property Prestige : integer read fPrestige write fPrestige;
property Resp : string read fResp write fResp;
property Tier : integer read fTier;
property Level : integer read fLevel write fLevel;
property LicLevel : single read fLicLevel write SetLicLevel;
property Volatile : boolean read fVolatile write fVolatile;
property EnablesTech : boolean read fEnablesTech;
property Nobility : integer read fNobility;
property CatPos : integer read fCatPos;
property Obsolete : boolean read fObsolete;
public
property Req : TCollection read fReq;
private
procedure SetRequired(xmlObj : OleVariant);
procedure DoLinkInvention(cluster, blocks, host : string);
procedure LinkInvention(Appls : OleVariant);
procedure EnableFacilities(Obj : OleVariant);
procedure ApplyToFacilities(facs, cluster : string);
protected
procedure FixDeps;
public
function Enabled(Company : TObject) : boolean; virtual;
function GetFeePrice(Company : TObject) : TMoney; virtual;
function GetProperties(Company : TObject; LangId : TLanguageId) : string; virtual;
procedure StoreToCache(Cache : TObjectCache; kind : string; index : integer); virtual;
function GetFullDesc( LangId : TLanguageId ) : string;
function GetTierOf( var Comp ) : integer;
public
procedure RetrieveTexts( Container : TDictionary ); override;
procedure StoreTexts ( Container : TDictionary ); override;
public
procedure StoreClientInfo( Dest : TStream; LangId : TLanguageId );
public
function GetClientProps(Company : TObject; LangId : TLanguageId ) : string; virtual;
private
fImplementable : boolean;
public
property Implementable : boolean read fImplementable write fImplementable;
end;
TInventionRecord =
class
public
constructor Create(aInvention : TInvention; aCost : TMoney);
private
fInvention : TInvention;
fTotalCost : TMoney;
fSubsidy : TMoney;
fUsage : integer;
public
property Invention : TInvention read fInvention write fInvention;
property TotalCost : TMoney read fTotalCost write fTotalCost;
property Subsidy : TMoney read fSubsidy write fSubsidy;
property Usage : integer read fUsage write fUsage;
public
function HourlyCostPerFac(Perc : single) : TMoney;
function HourlyCost(Perc : single) : TMoney;
function YearCost(Perc : single) : TMoney;
end;
TInventionClass =
class
public
constructor Create(aClass : CInvention);
private
fClass : CInvention;
end;
function GetInventionById(id : string) : TInvention;
procedure CreateInventions(path : string);
procedure CreateInventionsFromFile(path : string);
function FindInvention(id : string) : TInvention;
function GetProperty(ppObj : OleVariant; name : string) : OleVariant;
function FormatDelta( points : integer ) : string;
implementation
uses
SysUtils, ComObj, Kernel, Headquarters, ClassStorage, CompStringsParser, Protocol, SimHints,
FacIds, Math, MathUtils, DelphiStreamUtils, TycoonLevels;
const
tidMSXML = 'msxml';
const
isDelta = 5;
var
LastInvention : integer = 0;
InventionList : TCollection = nil;
function GetLevelOf( tier : integer; langId : TLanguageId ) : string;
var
Level : TTycoonLevel;
begin
Level := GetLevelOfTier( tier );
if Level <> nil
then result := Level.Name_MLS.Values[langId]
else result := '';
{
case tier of
0: result := 'Apprentice';
1: result := 'Entrepreneur';
2: result := 'Tycoon';
3: result := 'Master';
4: result := 'Paradigm';
5: result := 'Legend';
else result := '?';
end;
}
end;
function GetInventionById(id : string) : TInvention;
begin
result := TInvention(TheClassStorage.ClassById[tidClassFamily_Inventions, id]);
end;
type
pinteger = ^integer;
// TInventionSet
constructor TInventionSet.Create(IniCount : integer);
begin
inherited Create;
fCapacity := CountToSets(IniCount);
ReallocMem(fSets, fCapacity*sizeof(fSets[0]));
if fSets <> nil
then FillChar(fSets[0], fCapacity*sizeof(fSets[0]), 0);
end;
destructor TInventionSet.Destroy;
begin
ReallocMem(fSets, 0);
inherited;
end;
function TInventionSet.CountToSets(count : integer) : integer;
begin
result := succ(count div BitCount);
end;
procedure TInventionSet.Decompose(Elem : TInventionNumId; var Index : integer; var Value : Bits);
begin
Index := Elem div BitCount;
Value := Elem mod BitCount;
end;
function TInventionSet.Include(Elem : TInventionNumId) : boolean;
var
idx : integer;
val : Bits;
OldCap : integer;
NewCap : integer;
begin
Decompose(Elem, idx, val);
if idx >= fCapacity
then
begin
OldCap := fCapacity;
fCapacity := idx + 5;
ReallocMem(fSets, fCapacity*sizeof(fSets[0]));
NewCap := fCapacity;
FillChar(fSets[OldCap], (NewCap - OldCap)*sizeof(fSets[0]), 0);
end;
if val in fSets[idx]
then result := false
else
begin
System.Include(fSets[idx], val);
result := true;
end;
end;
function TInventionSet.Exclude(Elem : TInventionNumId) : boolean;
var
idx : integer;
val : Bits;
begin
Decompose(Elem, idx, val);
if idx < fCapacity
then
begin
result := val in fSets[idx];
System.Exclude(fSets[idx], val);
end
else result := false;
end;
function TInventionSet.Included(Elem : TInventionNumId) : boolean;
var
idx : integer;
val : Bits;
begin
Decompose(Elem, idx, val);
if idx < fCapacity
then result := val in fSets[idx]
else result := false;
end;
function TInventionSet.IsEmpty : boolean;
var
cap : integer;
i : integer;
begin
cap := fCapacity;
i := 0;
while (i < cap) and (fSets[i] = []) do
inc(i);
result := i = cap;
end;
procedure TInventionSet.Clear;
begin
fCapacity := 0;
ReallocMem(fSets, 0);
end;
// TInvention
constructor TInvention.Create( anId, aName, aKind, aResp : string );
begin
inherited Create( anId );
fName := aName;
fKind := aKind;
fResp := aResp;
fName_MLS := TMultiString.Create;
fDesc_MLS := TMultiString.Create;
fResp_MLS := TMultiString.Create;
fParent_MLS := TMultiString.Create;
fReq := TCollection.Create( 0, rkUse );
end;
constructor TInvention.Load(xmlObj : OleVariant);
procedure OverrideTiers( Tiers : olevariant );
var
coll : olevariant;
item : olevariant;
i : integer;
cluster : string;
value : integer;
begin
coll := Tiers.Children;
for i := 0 to pred(StrToInt(coll.Length)) do
begin
item := coll.item( i, Unassigned );
if not VarIsEmpty(item)
then
begin
cluster := Item.getAttribute( tidInvAttr_Cluster );
value := StrToInt(Item.getAttribute( tidInvAttr_Value ));
fTierInfo.AddObject( cluster, TObject(value) );
end;
end;
end;
var
theId : string;
Aux : OleVariant;
begin
Aux := xmlObj.children.item(tidInvElement_Props, Unassigned);
theId := GetProperty(Aux, tidInvAttr_Id);
inherited Create( theId );
fId := theId;
// General stuff
fOldId := GetProperty(Aux, 'oldid'); // >> temp
fName := GetProperty(Aux, tidInvAttr_Name);
fKind := GetProperty(Aux, tidInvAttr_Kind);
fPrice := GetProperty(Aux, tidInvAttr_Price);
fPrestige := GetProperty(Aux, tidInvAttr_Prestige);
fTime := GetProperty(Aux, tidInvElement_Time);
fBasic := lowercase(GetProperty(Aux, tidInvElement_Basic)) = 'true';
fCache := lowercase(GetProperty(Aux, tidInvElement_Cache)) <> 'no';
fParent := GetProperty(Aux, tidInvAttr_Parent);
fResp := GetProperty(Aux, tidInvAttr_Location);
fTier := GetProperty(Aux, tidInvAttr_Tier);
fLicLevel := GetProperty(Aux, tidInvAttr_LicLevel);
if StrToInt(TheGlobalConfigHandler.GetConfigParm('TornamentLength', '0')) = 0
then fNobility := GetProperty(Aux, tidInvAttr_Nobility)
else fNobility := 0;
fCatPos := GetProperty(Aux, tidInvAttr_CatPos);
fObsolete := GetProperty(Aux, tidInvAttr_Obsolete);
Aux := GetProperty(Aux, tidInvAttr_Volatile);
fVolatile := not VarIsEmpty(Aux) and (lowercase(Aux) = 'true') or (fLicLevel > 0);
// Required to start
fReq := TCollection.Create(0, rkUse);
SetRequired(xmlObj);
Aux := xmlObj.children.item(tidInvElement_Desc, Unassigned);
if not VarIsEmpty(Aux)
then fDesc := Aux.text;
// Enable facilities
try
Aux := xmlObj.children.item(tidInvAttr_Enables, Unassigned);
except
Aux := Unassigned;
end;
if not VarIsEmpty(Aux)
then
begin
EnableFacilities(Aux);
fEnablesTech := true;
end;
// Tier overriding
fTierInfo := TStringList.Create;
try
Aux := xmlObj.children.item(tidInvElement_Tiers, Unassigned);
except
Aux := Unassigned;
end;
if not VarIsEmpty(Aux)
then OverrideTiers( Aux );
fName_MLS := TMultiString.Create;
fDesc_MLS := TMultiString.Create;
fResp_MLS := TMultiString.Create;
fParent_MLS := TMultiString.Create;
end;
destructor TInvention.Destroy;
begin
fName_MLS.Free;
fDesc_MLS.Free;
fResp_MLS.Free;
fParent_MLS.Free;
fReq.Free;
fTierInfo.Free;
inherited;
end;
procedure TInvention.SetLicLevel(value : single);
begin
fLicLevel := value;
fVolatile := fVolatile or (value <> 0);
end;
procedure TInvention.SetRequired(xmlObj : OleVariant);
var
Req : OleVariant;
Item : OleVariant;
i : integer;
begin
if not VarIsEmpty(xmlObj.children)
then
begin
try
Req := xmlObj.children.item(tidInvElement_Requires, Unassigned);
except
Req := Unassigned;
end;
if not VarIsEmpty(Req)
then
begin
fReqIds := TStringList.Create;
Req := Req.children;
i := 0;
while i < Req.Length do
begin
Item := Req.item(i, Unassigned);
fReqIds.Add(Item.getAttribute(tidInvAttr_Id));
inc(i);
end;
end;
end;
end;
procedure TInvention.DoLinkInvention(cluster, blocks, host : string);
var
p : integer;
aux : string;
MetaBlk : TMetaBlock;
begin
p := 1;
aux := GetNextStringUpTo(blocks, p, ',');
while aux <> '' do
begin
inc(p);
MetaBlk := TMetaBlock(TheClassStorage.ClassById[tidClassFamily_Blocks, cluster + aux]);
if MetaBlk <> nil
then MetaBlk.DeclareInvention(self);
//else raise Exception.Create('Unknown block ' + aux + ' in cluster ' + cluster);
aux := Trim(GetNextStringUpTo(blocks, p, ','));
end;
p := 1;
aux := GetNextStringUpTo(host, p, ',');
while aux <> '' do
begin
MetaBlk := TMetaBlock(TheClassStorage.ClassById[tidClassFamily_Blocks, cluster + aux{host}]);
if MetaBlk <> nil
then TMetaHeadquarterBlock(MetaBlk).RegisterInvention(self);
//else raise Exception.Create('Unknown headquarter ' + aux{host} + ' in cluster ' + cluster);
inc(p);
aux := GetNextStringUpTo(host, p, ',');
end;
end;
procedure TInvention.LinkInvention(Appls : OleVariant);
var
Elems : OleVariant;
Cluster : OleVariant;
i, len : integer;
clName : string;
blocks : string;
facs : string;
host : string;
clId : string;
begin
if not VarIsEmpty(Appls)
then
try // <cluster name="Diss" blocks="Farm, FoodProc" host="IndHeadquarter"/>
Elems := Appls.children;
len := Elems.Length;
i := 0;
while i < len do
begin
Cluster := Elems.item(i, Unassigned);
clName := Cluster.getAttribute(tidInvAttr_Name);
clId := Cluster.getAttribute(tidInvAttr_Id);
blocks := Cluster.getAttribute(tidInvAttr_Blocks);
host := Cluster.getAttribute(tidInvAttr_Host);
facs := Cluster.getAttribute(tidInvAttr_FacId);
DoLinkInvention(clName, blocks, host);
if clId <> ''
then ApplyToFacilities(facs, clId)
else ApplyToFacilities(facs, clName);
inc(i);
end;
except
end;
end;
procedure TInvention.EnableFacilities(Obj : OleVariant);
var
tech : string;
i : integer;
Fac : TMetaFacility;
begin
tech := Obj.getAttribute(tidInvAttr_Technology);
if tech <> ''
then
for i := 0 to pred(TheClassStorage.ClassCount[tidClassFamily_Facilities]) do
begin
Fac := TMetaFacility(TheClassStorage.ClassByIdx[tidClassFamily_Facilities, i]);
if Fac.TechnologyKind = tech
then Fac.RequiresInvention(self);
end;
end;
procedure TInvention.ApplyToFacilities(facs, cluster : string);
var
ids : array[0..127] of TFacId;
cnt : integer;
p : integer;
i : integer;
aux : string;
Fac : TMetaFacility;
begin
if facs <> ''
then
begin
cnt := 0;
p := 1;
CompStringsParser.SkipChars(facs, p, Spaces);
aux := CompStringsParser.GetNextStringUpTo(facs, p, ',');
while aux <> '' do
begin
ids[cnt] := StrToInt(aux);
inc(cnt);
inc(p);
CompStringsParser.SkipChars(facs, p, Spaces);
aux := CompStringsParser.GetNextStringUpTo(facs, p, ',');
end;
if cnt > 0
then
for i := 0 to pred(TheClassStorage.ClassCount[tidClassFamily_Facilities]) do
begin
Fac := TMetaFacility(TheClassStorage.ClassByIdx[tidClassFamily_Facilities, i]);
if FacIds.Contains(slice(ids, cnt), Fac.FacId) and (Fac.ClusterName = cluster)
then Fac.TypicalStage.MetaBlock.DeclareInvention(self);
end;
end;
end;
procedure TInvention.FixDeps;
var
Inv : TInvention;
i : integer;
begin
if fReqIds <> nil
then
for i := 0 to pred(fReqIds.Count) do
if fReqIds[i] <> ''
then
begin
Inv := GetInventionById(fReqIds[i]);
if Inv <> nil
then
begin
fReq.Insert(Inv);
fTier := max(fTier, Inv.Tier);
end
else raise Exception.Create('Unknown invention ' + fReqIds[i]);
end;
fReqIds.Free;
fReqIds := nil;
end;
function TInvention.Enabled(Company : TObject) : boolean;
function TierAndNobilityMatches(Company : TCompany) : boolean;
var
Tycoon : TTycoon;
begin
if (Company <> nil) and (Company.Owner <> nil) and (Company.Owner.Level <> nil) and (Company.Owner.Level.Tier >= GetTierOf(Company))
then
begin
if Nobility <= 0
then result := true
else
begin
Tycoon := Company.Owner;
if Tycoon.NobPoints < 0
then Tycoon.UpdateNobility;
result := Tycoon.NobPoints >= Nobility
end;
end
else result := false;
end;
var
i : integer;
begin
if TierAndNobilityMatches( TCompany(Company) )
then
if Req.Count = 0
then result := true
else
begin
i := 0;
while (i < Req.Count) and TCompany(Company).HasInvention[TInvention(Req[i]).NumId] do
inc(i);
result := i = Req.Count;
end
else result := false;
end;
function TInvention.GetFeePrice(Company : TObject) : TMoney;
begin
{
if (fLicLevel > 0) and (Company <> nil) and (TCompany(Company).Owner <> nil) and (TCompany(Company).Owner.LicenceLevel > 0)
then result := 1000000*power(2, TCompany(Company).Owner.LicenceLevel)
else result := 0;
}
if (fLicLevel > 0) and (Company <> nil) and (TCompany(Company).Owner <> nil) and (TCompany(Company).Owner.LicenceLevel > 0)
then result := 1000000*power(2, TCompany(Company).Owner.LicenceLevel + fLicLevel - 1)
else result := 0;
end;
function TInvention.GetProperties(Company : TObject; LangId : TLanguageId) : string;
var
lic : TMoney;
Rec : TInventionRecord;
begin
// Price
if fPrice > 0
then result := SimHints.GetHintText(mtidInvPrice.Values[LangId], [FormatMoney(fPrice)]) + LineBreak //'Price: ' + FormatMoney(fPrice) + ^M^J
else result := '';
// Licence
if Company <> nil
then
begin
Rec := TCompany(Company).FindInventionRecord(self);
if Rec <> nil //TCompany(Company).HasInvention[fNumId]
then lic := Rec.TotalCost - fPrice
else lic := GetFeePrice(Company);
if lic > 0
then result := result + SimHints.GetHintText(mtidInvLicense.Values[LangId], [FormatMoney(lic)]) + LineBreak;//'Licence: ' + FormatMoney(lic) + ^M^J;
if fImplementable
then
if Rec <> nil
then
begin
result := result + SimHints.GetHintText(mtidInvImpCostHour.Values[LangId], [FormatMoney(Rec.HourlyCost(StdHourlyCost))]) + LineBreak;
result := result + SimHints.GetHintText(mtidInvUsage.Values[LangId], [Rec.Usage]) + LineBreak;
end
else result := result + SimHints.GetHintText(mtidInvImpCostYear.Values[LangId], [FormatMoney((StdHourlyCost/100)*fPrice)]) + LineBreak;
end;
// Prestige
if Prestige <> 0
then result := result + SimHints.GetHintText(mtidInvPrestige.Values[LangId], [FormatDelta(Prestige)]) + LineBreak;
// Tier
if (Company <> nil) and (TCompany(Company).Owner <> nil) and (TCompany(Company).Owner.Level <> nil) and (TCompany(Company).Owner.Level.Tier < fTier)
then result := result + SimHints.GetHintText(mtidInvLevel.Values[LangId], [GetLevelOf(GetTierOf(Company), LangId)]) + LineBreak //'Level: ' + GetLevelOf(GetTierOf(Company), LangId) + ^M^J
else result := result + SimHints.GetHintText(mtidInvLevel.Values[LangId], [GetLevelOf(fTier, LangId)]) + LineBreak;
// Nobility
if fNobility > 0
then result := result + SimHints.GetHintText(mtidInvNobPoints.Values[LangId], [IntToStr(fNobility)]) + LineBreak
end;
procedure TInvention.StoreToCache(Cache : TObjectCache; kind : string; index : integer);
var
iStr : string;
begin
iStr := IntToStr(index);
Cache.WriteString(kind + 'RsId' + iStr, Id);
if fVolatile
then
begin
Cache.WriteString(kind + 'RsName' + iStr, Name);
Cache.WriteString(kind + 'RsDyn' + iStr, 'yes');
if fParent <> ''
then Cache.WriteString(kind + 'RsParent' + iStr, fParent)
end;
end;
function TInvention.GetFullDesc( LangId : TLanguageId ) : string;
var
i : integer;
Inv : TInvention;
begin
result := Desc_MLS.Values[LangId];
if fReq.Count > 0
then result := result + ^M^J + mtidDescFactoryReq.Values[langId] + ': ';
for i := 0 to pred(fReq.Count) do
begin
Inv := TInvention(fReq[i]);
if i < pred(fReq.Count)
then result := result + Inv.Name_MLS.Values[LangId] + ', '
else result := result + Inv.Name_MLS.Values[LangId] + '.';
end;
end;
function TInvention.GetTierOf( var Comp ) : integer;
var
Company : TCompany absolute Comp;
begin
if (Company <> nil) and (Company.Cluster <> nil) and (fTierInfo.IndexOf( Company.Cluster.Id ) <> NoIndex)
then result := integer(fTierInfo.Objects[fTierInfo.IndexOf( Company.Cluster.Id )])
else result := fTier
end;
procedure TInvention.RetrieveTexts( Container : TDictionary );
var
aux : string;
begin
inherited;
// Assign multi strings
fName_MLS.Values[Container.LangId] := Container.Values[Family + '.' + Id + '.' + 'Name'];
fDesc_MLS.Values[Container.LangId] := Container.Values[Family + '.' + Id + '.' + 'Desc'];
fResp_MLS.Values[Container.LangId] := Container.Values[Family + '.' + Id + '.' + 'Resp'];
aux := Container.Values[Family + '.Category.' + fParent];
if aux <> ''
then fParent_MLS.Values[Container.LangId] := Container.Values[Family + '.Category.' + fParent]
else fParent_MLS.Values[Container.LangId] := Container.Values[Family + '.Category.General'];
end;
procedure TInvention.StoreTexts( Container : TDictionary );
begin
inherited;
Container.Values[Family + '.' + Id + '.' + 'Name'] := fName;
Container.Values[Family + '.' + Id + '.' + 'Desc'] := fDesc;
Container.Values[Family + '.' + Id + '.' + 'Resp'] := fResp;
Container.Values[Family + '.Category.' + fParent] := fParent;
end;
procedure TInvention.StoreClientInfo( Dest : TStream; LangId : TLanguageId );
begin
WriteString( Dest, fId );
WriteString( Dest, Name_MLS.Values[LangId] + '|' + Resp_MLS.Values[LangId]);
WriteString( Dest, GetFullDesc( LangId ) );
if Parent_MLS.Values[LangId] <> ''
then WriteString( Dest, Parent_MLS.Values[LangId] )
else WriteString( Dest, fParent );
Dest.WriteBuffer( fCache, sizeof(fCache) );
WriteString(Dest, GetClientProps(nil, LangId));
end;
function TInvention.GetClientProps(Company : TObject; LangId : TLanguageId ) : string;
begin
result := GetProperties(Company, LangId);
end;
// TInventionRecord
constructor TInventionRecord.Create(aInvention : TInvention; aCost : TMoney);
begin
inherited Create;
fInvention := aInvention;
fTotalCost := aCost;
end;
function TInventionRecord.HourlyCostPerFac(Perc : single) : TMoney;
const
HoursAYear = 365*24;
begin
result := (Perc/100)*fInvention.Price/HoursAYear;
end;
function TInventionRecord.HourlyCost(Perc : single) : TMoney;
begin
result := fUsage*HourlyCostPerFac(Perc);
end;
function TInventionRecord.YearCost(Perc : single) : TMoney;
begin
result := (Perc/100)*fInvention.Price;
end;
// TInventionClass
constructor TInventionClass.Create(aClass : CInvention);
begin
inherited Create;
fClass := aClass;
end;
function CreateInvention(InvObj, Appls : OleVariant) : TInvention;
var
ClassId : string;
InvClass : CInvention;
Aux : OleVariant;
begin
ClassId := InvObj.getAttribute(tidInvAttr_Class);
if ClassId <> ''
then InvClass := TInventionClass(TheClassStorage.ClassById[tidClassFamily_InvClasses, ClassId]).fClass
else InvClass := TInvention;
result := InvClass.Load(InvObj);
result.fNumId := LastInvention;
inc(LastInvention);
try
Aux := InvObj.children.item(tidInvElement_Applies, Unassigned);
if VarIsEmpty(Aux)
then Aux := Appls;
except
Aux := Appls;
end;
if not result.Obsolete
then result.LinkInvention(Aux);
result.Register(tidClassFamily_Inventions);
InventionList.Insert(result);
end;
procedure ListInventionFileElements(Elems, Appls : OleVariant);
var
i, len : integer;
Elem : OleVariant;
Aux : OleVariant;
begin
i := 0;
len := Elems.Length;
while i < len do
begin
Elem := Elems.item(i, Unassigned);
if lowercase(Elem.tagName) = tidInvTag_Invention
then CreateInvention(Elem, Appls)
else
if lowercase(Elem.tagName) = tidInvTag_InventionSet
then
begin
try
Aux := Elem.children.item(tidInvElement_Applies, Unassigned);
except
Aux := Unassigned;
end;
if VarIsEmpty(Aux)
then ListInventionFileElements(Elem.children, Appls)
else ListInventionFileElements(Elem.children, Aux);
end;
inc(i);
end;
end;
procedure CreateInventionsFromFile(path : string);
var
InvFile : OleVariant;
Root : OleVariant;
Appls : OleVariant;
begin
try
InvFile := CreateOLEObject(tidMSXML);
InvFile.url := path;
Root := InvFile.root;
try
Appls := Root.children.item(tidInvElement_Applies, Unassigned);
except
Appls := Unassigned;
end;
ListInventionFileElements(Root.children, Appls);
except
raise Exception.Create('Error reading the invention file: ' + ExtractFileName(path));
end;
end;
procedure CreateInventions(path : string);
var
Search : TSearchRec;
found : integer;
i : integer;
begin
InventionList := TCollection.Create(0, rkUse);
try
found := FindFirst(path + '*.xml', faArchive, Search);
while found = 0 do
begin
CreateInventionsFromFile(path + Search.Name);
found := FindNext(Search);
end;
finally
FindClose(Search);
end;
for i := 0 to pred(InventionList.Count) do
TInvention(InventionList[i]).FixDeps;
end;
function FindInvention(id : string) : TInvention;
var
i : integer;
begin
i := pred(InventionList.Count);
while (i >= 0) and ((TInvention(InventionList[i]).kind + IntToStr(TInvention(InventionList[i]).fOldId) <> id)) do
dec(i);
if i < 0
then result := nil
else result := TInvention(InventionList[i]);
end;
function GetProperty(ppObj : OleVariant; name : string) : OleVariant;
var
Aux : OleVariant;
begin
Aux := ppObj.children.item(UpperCase(name), Unassigned);
if not VarIsEmpty(Aux)
then result := Aux.getAttribute(tidInvAttr_Value)
else result := ppObj.getAttribute(tidInvAttr_Value);
end;
function FormatDelta( points : integer ) : string;
begin
result := IntToStr( points );
if points > 0
then result := '+' + result;
end;
initialization
InventionList := nil;
finalization
InventionList.Free;
end.
|
unit CacheAgent;
interface
uses
CacheCommon, Classes;
const
noKind = -1;
noInfo = -1;
okSubObj = 0;
recLinks = -2;
type
TObjectCache = class;
TCacheAgent = class;
// TCacheAgent (CA) is a template for a class that knows how and where
// to cache a particular class. CA should calculate the data that has been
// request.
CCacheAgent = class of TCacheAgent;
TCacheAgent =
class
public
class function GetPath (Obj : TObject; kind, info : integer) : string; virtual;
class function GetCache (Obj : TObject; kind, info : integer; update : boolean) : TObjectCache; virtual;
class function UpdateCache(Obj : TObject; kind, info : integer; update : boolean) : TObjectCache; virtual;
end;
// TObjectCache is the class of the objects that store temporarily the
// cached data of an object, these data will be sent to the Web Server Cache.
TObjectCache =
class
public
constructor Create;
destructor Destroy; override;
private
fProperties : TStringList;
fAction : TCacheAction;
fRecLinks : boolean;
fUpdate : boolean;
fPath : string;
fLinks : string;
fDelPaths : string;
public
procedure WriteString(const Name : string; const data : string);
procedure WriteInteger(const Name : string; const data : integer);
procedure WriteFloat(const Name : string; const data : double);
procedure WriteCurrency(const Name : string; const data : double);
procedure WriteBoolean(const Name : string; const data : boolean);
private
procedure SetProperty(const Name, Value : string);
function GetProperty(const Name : string) : string;
function GetPath : string;
procedure SetPath(aPath : string);
public
property PropertyList : TStringList read fProperties write fProperties;
property Properties[const name : string] : string read GetProperty write SetProperty; default;
property Path : string read GetPath write SetPath;
property Action : TCacheAction read fAction write fAction;
property RecLinks : boolean read fRecLinks;
property Update : boolean read fUpdate;
public
procedure Prepare;
procedure AddLink(const aPath : string);
procedure AddDelPath(const aPath : string);
end;
implementation
uses
SysUtils, SpecialChars;
// TCacheAgent
class function TCacheAgent.GetPath(Obj : TObject; kind, info : integer) : string;
begin
result := '';
end;
class function TCacheAgent.GetCache(Obj : TObject; kind, info : integer; update : boolean) : TObjectCache;
begin
result := TObjectCache.Create;
result.fUpdate := update;
result.Path := GetPath(Obj, kind, info);
result.WriteInteger(ppObjId, integer(Obj));
result.WriteString(ppTTL, NULLTTL);
result.WriteInteger(ppKind, kind);
result.fRecLinks := info = recLinks;
if result.fRecLinks
then result.WriteInteger(ppInfo, noInfo)
else result.WriteInteger(ppInfo, info);
end;
class function TCacheAgent.UpdateCache(Obj : TObject; kind, info : integer; update : boolean) : TObjectCache;
begin
result := GetCache(Obj, kind, info, update);
end;
// TObjectCache
constructor TObjectCache.Create;
begin
inherited;
fProperties := TStringList.Create;
end;
destructor TObjectCache.Destroy;
begin
fProperties.Free;
inherited;
end;
procedure TObjectCache.WriteString(const Name : string; const data : string);
begin
//fProperties.Values[Name] := data;
if data <> ''
then fProperties.Insert(0, Name + '=' + data);
end;
procedure TObjectCache.WriteInteger(const Name : string; const data : integer);
begin
//fProperties.Values[Name] := IntToStr(data);
fProperties.Insert(0, Name + '=' + IntToStr(data));
end;
procedure TObjectCache.WriteFloat(const Name : string; const data : double);
begin
//fProperties.Values[Name] := FloatToStr(data);
fProperties.Insert(0, Name + '=' + FloatToStr(data));
end;
procedure TObjectCache.WriteCurrency(const Name : string; const data : double);
begin
//fProperties.Values[Name] := CurrToStr(data);
fProperties.Insert(0, Name + '=' + CurrToStr(data));
end;
procedure TObjectCache.WriteBoolean(const Name : string; const data : boolean);
begin
{
if data
then fProperties.Values[Name] := '1'
else fProperties.Values[Name] := '0';
}
if data
then fProperties.Insert(0, Name + '=1')
else fProperties.Insert(0, Name + '=0');
end;
procedure TObjectCache.SetProperty(const Name, Value : string);
begin
//fProperties.Values[Name] := Value;
fProperties.Insert(0, Name + '=' + Value);
end;
function TObjectCache.GetProperty(const Name : string) : string;
begin
result := fProperties.Values[Name];
end;
function TObjectCache.GetPath : string;
begin
result := fPath;
end;
procedure TObjectCache.SetPath(aPath : string);
begin
fPath := aPath;
end;
procedure TObjectCache.Prepare;
begin
WriteString(PathName, fPath);
WriteString(LinkName, fLinks);
if fDelPaths = ''
then WriteString(DelPName, LinkSep)
else WriteString(DelPName, fDelPaths);
end;
procedure TObjectCache.AddLink(const aPath : string);
begin
if aPath <> ''
then
if fLinks <> ''
then fLinks := fLinks + LinkSep + aPath
else fLinks := aPath;
end;
procedure TObjectCache.AddDelPath(const aPath : string);
begin
if aPath <> ''
then
if fDelPaths <> ''
then fDelPaths := fDelPaths + LinkSep + aPath
else fDelPaths := aPath;
end;
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_SoundStreamer
* Implements a generic Sound Streamer, that can be used to stream audio to a sound source
***********************************************************************************************************************
}
Unit TERRA_SoundStreamer;
{$I terra.inc}
Interface
Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF}
TERRA_Utils, TERRA_Math, TERRA_Collections, TERRA_Application, TERRA_Stream, TERRA_FileStream,
TERRA_Sound, TERRA_AL;
Const
StreamBufferSize = 1024 * 1024; //16Kb for streaming buffers, change if necessary
Type
SoundStreamClass = Class Of SoundStream;
SoundStream = Class(TERRAObject)
Protected
_Source:Stream;
_Handle:Cardinal;
_Buffers:Array[0..1] Of Cardinal;
_Channels:Cardinal;
_Frequency:Cardinal;
_BitsPerSample:Cardinal;
_Data:Pointer;
_BufferSize:Cardinal;
_StartTime:Cardinal;
_Volume:Single;
_Status:Integer;
Procedure SetVolume(Value:Single);
Procedure UpdateSettings;
Procedure AllocBuffer(Channels, BitsPerSample, Frequency:Cardinal);
Procedure InitStream; Virtual; Abstract;
Procedure Stream(Buffer:Cardinal); Virtual;
Class Function Validate(Source:Stream):Boolean; Virtual; Abstract;
Public
Constructor Create(Source:Stream);
Procedure Release; Override;
Procedure Update;
Procedure Play;
Procedure Pause;
Procedure Stop;
Property StartTime:Cardinal Read _StartTime;
Property Volume:Single Read _Volume Write SetVolume;
End;
NullSoundStreamer = Class(SoundStream)
Protected
Procedure InitStream; Override;
Procedure Stream(Buffer:Cardinal); Override;
Class Function Validate(Source:Stream):Boolean; Override;
Public
End;
Procedure RegisterSoundStreamFormat(MyClass:SoundStreamClass);
Function CreateSoundStream(Source:Stream):SoundStream;
Implementation
Uses TERRA_OS, TERRA_GraphicsManager, TERRA_SoundManager, TERRA_SoundAmbience, TERRA_Log;
Var
_SoundStreamClassList:Array Of SoundStreamClass;
_SoundStreamClassCount:Integer = 0;
Procedure RegisterSoundStreamFormat(MyClass:SoundStreamClass);
Begin
Inc(_SoundStreamClassCount);
SetLength(_SoundStreamClassList, _SoundStreamClassCount);
_SoundStreamClassList[Pred(_SoundStreamClassCount)] := MyClass;
End;
Function CreateSoundStream(Source:Stream):SoundStream;
Var
I:Integer;
Ofs:Cardinal;
Begin
Result := Nil;
Ofs := Source.Position;
For I:=0 To Pred(_SoundStreamClassCount) Do
Begin
If _SoundStreamClassList[I].Validate(Source) Then
Begin
Source.Seek(Ofs);
Result := _SoundStreamClassList[I].Create(Source);
Exit;
End;
Source.Seek(Ofs);
End;
End;
Procedure NullSoundStreamer.InitStream;
Begin
End;
Procedure NullSoundStreamer.Stream(Buffer:Cardinal);
Begin
End;
Class Function NullSoundStreamer.Validate(Source:Stream):Boolean;
Begin
Result := True;
End;
// SoundStreamer
Constructor SoundStream.Create(Source:Stream);
Begin
_Handle := 0;
_Buffers[0] := 0;
_Buffers[1] := 0;
_Volume := 1.0;
_Status := sndStopped;
_Source := Source;
_BufferSize := StreamBufferSize;
Self.InitStream;
End;
Procedure SoundStream.Release;
Var
Buffer:Cardinal;
Queued:Integer;
Begin
Stop;
If Assigned(_Data) Then
FreeMem(_Data);
If (_Handle<>0) Then
Begin
alGetSourcei(_Handle, AL_BUFFERS_QUEUED, @queued); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
While (Queued>0) Do
Begin
alSourceUnqueueBuffers(_Handle, 1, @buffer); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
Dec(Queued);
End;
alDeleteBuffers(2, @_Buffers[0]); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alDeleteSources(1, @_Handle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
_Handle := 0;
End;
ReleaseObject(_Source);
End;
Procedure SoundStream.AllocBuffer(Channels, BitsPerSample, Frequency:Cardinal);
Begin
If Assigned(_Data) Then
FreeMem(_Data);
_Channels := Channels;
_Frequency := Frequency;
_BitsPerSample := BitsPerSample;
GetMem(_Data, StreamBufferSize);
End;
Var
F:Stream;
Procedure SoundStream.Stream(Buffer:Cardinal);
Begin
alBufferData(Buffer, AL_FORMAT_STEREO16, _Data, _BufferSize, _Frequency); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
{If F=Nil Then
F := FileStream.Create('raw');
F.Write(_Data^, _Buffersize)}
End;
Procedure SoundStream.UpdateSettings;
Begin
If (_Handle<=0) Then
Exit;
alSourcei(_Handle, AL_LOOPING, 0); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alSourcef(_Handle, AL_PITCH, 1.0); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alSourcef(_Handle, AL_GAIN, _Volume); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
End;
Procedure SoundStream.SetVolume(Value:Single);
Begin
If (_Volume = Value) Then
Exit;
_Volume := Value;
UpdateSettings;
End;
Procedure SoundStream.Update;
Var
Processed:Integer;
State, Buffer:Cardinal;
Begin
If _Status <> sndPlaying Then
Exit;
alGetSourcei(_Handle, AL_SOURCE_STATE, @state);
If (State <> AL_PLAYING) Then
Begin
Stream(_Buffers[0]);
Stream(_Buffers[1]);
alSourceQueueBuffers(_Handle, 2, @(_Buffers[0]));
alSourcePlay(_Handle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
Exit;
End;
alGetSourcei(_Handle, AL_BUFFERS_PROCESSED, @Processed); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
If Processed>0 Then
Repeat
alSourceUnqueueBuffers(_Handle, 1, @Buffer); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
Stream(Buffer);
alSourceQueueBuffers(_Handle, 1, @Buffer); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
Dec(Processed);
Until Processed<=0;
End;
Procedure SoundStream.Play;
Begin
If (_Status = sndStopped) Then
_StartTime := Application.GetTime;
_Status := sndPlaying;
If (_Handle <=0) Then
Begin
alGenSources(1, @_Handle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alGenBuffers(2, @_Buffers[0]); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
End;
UpdateSettings;
End;
Procedure SoundStream.Pause;
Begin
If _Status = sndStopped Then
Exit;
If _Status = sndPlaying Then
_Status := sndPaused
Else
_Status := sndPlaying;
If _Status = sndPaused Then
alSourcePause(_Handle)
Else
Play;
End;
Procedure SoundStream.Stop;
Begin
If (_Status = sndStopped) Then
Exit;
_Status := sndStopped;
alSourceStop(_Handle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
alSource3i(_Handle, AL_AUXILIARY_SEND_FILTER, AL_EFFECTSLOT_NULL, 0, AL_FILTER_NULL);
End;
End.
|
unit Atributos;
interface
uses
Base, Rtti, System.Classes;
type
TResultArray = array of string;
TCamposAnoni = record
NomeTabela: string;
Sep: string;
PKs: TResultArray;
TipoRtti: TRttiType;
end;
TFuncReflexao = reference to function(ACampos: TCamposAnoni): Integer;
type
TTipoCampo = (tcPK, tcNormal, tcRequerido);
TNomeTabela = class(TCustomAttribute)
private
FNomeTabela: string;
public
constructor Create(ANomeTabela: string);
property NomeTabela: string read FNomeTabela write FNomeTabela;
end;
TCampo = class(TCustomAttribute)
private
FDescricao: string;
FTipoCampo: TTipoCampo;
procedure SetDescricao(const Value: string);
procedure SetTipoCampo(const Value: TTipoCampo);
public
constructor Create(ANome: string; ATipo: TTipoCampo = tcNormal);
property Descricao: string read FDescricao write SetDescricao;
property TipoCampo: TTipoCampo read FTipoCampo write SetTipoCampo;
end;
//Reflection para os comandos Sql
function ReflexaoSQL(ATabela: TTabela; AnoniComando: TFuncReflexao): Integer;
function PegaNomeTab(ATabela : TTabela): string;
function PegaPks(ATabela : TTabela): TResultArray;
function ValidaTabela(ATabela : TTabela): Boolean;
implementation
uses
System.TypInfo, System.SysUtils, Forms, Winapi.Windows;
function ReflexaoSQL(ATabela: TTabela; AnoniComando: TFuncReflexao): Integer;
var
ACampos: TCamposAnoni;
Contexto: TRttiContext;
begin
ACampos.NomeTabela := PegaNomeTab(ATabela);
if ACampos.NomeTabela = EmptyStr then
raise Exception.Create('Informe o Atributo NomeTabela na classe ' +
ATabela.ClassName);
ACampos.PKs := PegaPks(ATabela);
if Length(ACampos.PKs) = 0 then
raise Exception.Create('Informe campos da chave primária na classe ' +
ATabela.ClassName);
Contexto := TRttiContext.Create;
try
ACampos.TipoRtti := Contexto.GetType(ATabela.ClassType);
// executamos os comandos Sql através do método anônimo
ACampos.Sep := '';
Result := AnoniComando(ACampos);
finally
Contexto.free;
end;
end;
function PegaNomeTab(ATabela : TTabela): string;
var
Contexto : TRttiContext;
TipoRtti : TRttiType;
AtribRtti : TCustomAttribute;
begin
Contexto := TRttiContext.Create;
TipoRtti := Contexto.GetType(ATabela.ClassType);
try
for AtribRtti in TipoRtti.GetAttributes do
if AtribRtti Is TNomeTabela then
begin
Result := (AtribRtti as TNomeTabela).NomeTabela;
Break;
end;
finally
Contexto.Free;
end;
end;
function PegaPks(ATabela : TTabela): TResultArray;
var
Contexto : TRttiContext;
TipoRtti : TRttiType;
PropRtti : TRttiProperty;
AtribRtti : TCustomAttribute;
i: Integer;
begin
Contexto := TRttiContext.Create;
TipoRtti := Contexto.GetType(ATabela.ClassType);
try
i:=0;
for PropRtti in TipoRtti.GetProperties do
for AtribRtti in PropRtti.GetAttributes do
begin
if AtribRtti Is TCampo then
if (AtribRtti as TCampo).TipoCampo=tcPK then
begin
SetLength(Result, i+1);
Result[i] := PropRtti.Name;
inc(i);
end;
end;
finally
Contexto.Free;
end;
end;
function ValidaTabela(ATabela : TTabela): Boolean;
var
Contexto : TRttiContext;
TipoRtti : TRttiType;
PropRtti : TRttiProperty;
AtribRtti : TCustomAttribute;
ValorNulo : Boolean;
Erro : TStringList;
begin
Result := True;
ValorNulo := false;
Erro := TStringList.Create;
try
Contexto := TRttiContext.Create;
try
TipoRtti := Contexto.GetType(ATabela.ClassType);
for PropRtti in TipoRtti.GetProperties do
begin
case PropRtti.PropertyType.TypeKind of
tkInt64, tkInteger: ValorNulo := PropRtti.GetValue(ATabela).AsInteger <= 0;
tkChar, tkString, tkUString: ValorNulo := Trim(PropRtti.GetValue(ATabela).AsString) = '';
tkFloat : ValorNulo := PropRtti.GetValue(ATabela).AsCurrency <= 0;
end;
for AtribRtti in PropRtti.GetAttributes do
begin
if AtribRtti Is TCampo then
begin
if ((AtribRtti as TCampo).TipoCampo in [tcPK, tcRequerido]) and (ValorNulo) then
begin
Erro.Add('Campo ' + (AtribRtti as TCampo).Descricao + ' não informado.');
end;
end;
end;
end;
finally
Contexto.Free;
end;
if Erro.Count>0 then
begin
Result := False;
Application.MessageBox(PChar(Erro.Text),'Erros foram detectados:',
mb_ok+MB_ICONERROR);
Exit;
end;
finally
Erro.Free;
end;
end;
{ TCampo }
constructor TCampo.Create(ANome: string; ATipo: TTipoCampo);
begin
FDescricao := ANome;
FTipoCampo := ATipo;
end;
procedure TCampo.SetDescricao(const Value: string);
begin
FDescricao := Value;
end;
procedure TCampo.SetTipoCampo(const Value: TTipoCampo);
begin
FTipoCampo := Value;
end;
{ TNomeTabela }
constructor TNomeTabela.Create(ANomeTabela: string);
begin
FNomeTabela := ANomeTabela;
end;
end.
|
unit MdiChilds.ElementEditor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, Vcl.StdCtrls,
Vcl.ExtCtrls, Vcl.ComCtrls, GsDocument, CommCtrl, System.Actions, Vcl.ActnList, Vcl.Mask, FmWorksListEditor;
type
IDataRowIterator = interface
procedure Next;
procedure Prev;
end;
TFmElementEditor = class(TForm)
pcMain: TPageControl;
tsContainer: TTabSheet;
tsChapter: TTabSheet;
tsIndex: TTabSheet;
tsPrice: TTabSheet;
tsRow: TTabSheet;
tsResource: TTabSheet;
edtContainerCaption: TLabeledEdit;
edtChapterCode: TLabeledEdit;
edtChapterCaption: TLabeledEdit;
chkIncludeInRowCode: TCheckBox;
chkIncludeInRowCaptions: TCheckBox;
rgChapterType: TRadioGroup;
edtIndexCode: TLabeledEdit;
edtIndexCaption: TLabeledEdit;
edtOZ: TLabeledEdit;
edtZM: TLabeledEdit;
edtEM: TLabeledEdit;
edtMT: TLabeledEdit;
edtSMR: TLabeledEdit;
edtPriceCode: TLabeledEdit;
edtPriceCaption: TLabeledEdit;
edtPriceMeasure: TLabeledEdit;
edtPriceCE: TLabeledEdit;
edtPriceCT: TLabeledEdit;
edtPriceBE: TLabeledEdit;
edtPriceBT: TLabeledEdit;
edtPriceWorkerClass: TLabeledEdit;
edtPriceMass: TLabeledEdit;
edtPriceCargoClass: TLabeledEdit;
edtPriceBaseComment: TLabeledEdit;
edtPriceCurrComment: TLabeledEdit;
edtRowCode: TLabeledEdit;
edtRowCaption: TLabeledEdit;
edtRowMeasure: TLabeledEdit;
edtWorkCode: TLabeledEdit;
lvPrices: TListView;
edtRowComment: TLabeledEdit;
edtResourceCode: TLabeledEdit;
edtResourceCaption: TLabeledEdit;
edtResourceMeasure: TLabeledEdit;
btnOK: TButton;
btnCancel: TButton;
Button1: TButton;
Button2: TButton;
al: TActionList;
acPrev: TAction;
acNext: TAction;
WorksList: TLinkLabel;
edtResourceCount: TLabeledEdit;
gbOutlayOptions: TGroupBox;
cbNotCount: TCheckBox;
cbProject: TCheckBox;
cbReturn: TCheckBox;
Label1: TLabel;
edtOKPCode: TLabeledEdit;
edtCode2001: TLabeledEdit;
edtOKPD2: TLabeledEdit;
procedure btnCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnOKClick(Sender: TObject);
procedure lvPricesMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SetEditText;
procedure acPrevExecute(Sender: TObject);
procedure acNextExecute(Sender: TObject);
procedure WorksListLinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType);
private
FItem: TGsAbstractItem;
FEdit: TEdit;
FSub: Integer;
ListItem: TListItem;
FRowIterator: IDataRowIterator;
procedure SetItem(AItem: TGsAbstractItem);
procedure UpdateContent(Row: TGsRow); overload;
procedure UpdateContent(Index: TGsIndexElement); overload;
procedure UpdateContent(Price: TGsPriceElement); overload;
procedure UpdateContent(Chapter: TGsChapter); overload;
procedure UpdateContent(Resource: TGsResource); overload;
procedure UpdateContent(Container: TGsAbstractContainer); overload;
procedure editExit(Sender: TObject);
procedure UpdateData(Row: TGsRow); overload;
procedure UpdateData(Index: TGsIndexElement); overload;
procedure UpdateData(Price: TGsPriceElement); overload;
procedure UpdateData(Chapter: TGsChapter); overload;
procedure UpdateData(Resource: TGsResource); overload;
procedure UpdateData(Container: TGsAbstractContainer); overload;
procedure EditKeyPress(Sender: TObject; var Key: Char);
function ConvertToFloat(Edit: TCustomEdit): Real;
procedure CreateColumns(DocumentType: TGsDocumentBaseDataType);
public
procedure UpdateData(Item: TGsAbstractItem); overload;
procedure UpdateContent(Item: TGsAbstractItem); overload;
property Item: TGsAbstractItem read FItem write SetItem;
property RowIterator: IDataRowIterator read FRowIterator write FRowIterator;
end;
{
var
FmElementEditor: TFmElementEditor;
}
implementation
uses GlobalData;
{$R *.dfm}
{ TFmElementEditor }
procedure TFmElementEditor.UpdateData(Price: TGsPriceElement);
begin
Price.Code := Trim(edtPriceCode.Text);
Price.Caption := Trim(edtPriceCaption.Text);
Price.Measure := Trim(edtPriceMeasure.Text);
Price.PriceCE := ConvertToFloat(edtPriceCE);
Price.PriceCT := ConvertToFloat(edtPriceCT);
Price.PriceBE := ConvertToFloat(edtPriceBE);
Price.PriceBT := ConvertToFloat(edtPriceBT);
Price.CurrPriceComment := Trim(edtPriceCurrComment.Text);
Price.BasePriceComment := Trim(edtPriceBaseComment.Text);
if edtPriceWorkerClass.Text = '' then
Price.Attributes[Ord(paWorkClass)] := Unassigned
else
Price.Attributes[Ord(paWorkClass)] := edtPriceWorkerClass.Text;
if edtPriceMass.Text = '' then
Price.Attributes[Ord(paMass)] := Unassigned
else
Price.Attributes[Ord(paMass)] := GlobalData.ConvertToFloat(Trim(edtPriceMass.Text));
if edtPriceCargoClass.Text = '' then
Price.Attributes[Ord(paCargo)] := Unassigned
else
Price.Attributes[Ord(paCargo)] := StrToInt(edtPriceCargoClass.Text);
end;
procedure TFmElementEditor.UpdateData(Index: TGsIndexElement);
begin
Index.Code := Trim(edtIndexCode.Text);
Index.Caption := Trim(edtIndexCaption.Text);
Index.OZ := ConvertToFloat(edtOZ);
Index.ZM := ConvertToFloat(edtZM);
Index.SMR := ConvertToFloat(edtSMR);
Index.MAT := ConvertToFloat(edtMT);
Index.EM := ConvertToFloat(edtEM);
end;
procedure TFmElementEditor.UpdateData(Row: TGsRow);
var
I: Integer;
begin
Row.Code := Trim(edtRowCode.Text);
Row.Caption := Trim(edtRowCaption.Text);
Row.Measure := Trim(edtRowMeasure.Text);
if edtWorkCode.Text = '' then
Row.Attributes[Ord(eaWorkCode)] := Unassigned
else
Row.Attributes[Ord(eaWorkCode)] := StrToInt(edtWorkCode.Text);
if edtRowComment.Text = '' then
Row.Attributes[Ord(eaComment)] := Unassigned
else
Row.Attributes[Ord(eaComment)] := Trim(edtRowComment.Text);
if edtOKPCode.Text = '' then
Row.Attributes[Ord(eaOKP)] := Unassigned
else
Row.Attributes[Ord(eaOKP)] := Trim(edtOKPCode.Text);
if edtCode2001.Text = '' then
Row.Attributes[Ord(eaCode2001)] := Unassigned
else
Row.Attributes[Ord(eaCode2001)] := Trim(edtCode2001.Text);
if edtOKPD2.Text = '' then
Row.Attributes[Ord(eaCodeOKPD2)] := Unassigned
else
Row.Attributes[Ord(eaCodeOKPD2)] := Trim(edtOKPD2.Text);
for I := 0 to lvPrices.Items.Count - 1 do
begin
case Row.Document.BaseDataType of
bdtMachine:
begin
Row.SetCostValue(cstPrice,
StrToFloat(lvPrices.Items[I].SubItems[1]), I + 1);
Row.SetCostValue(cstZM,
StrToFloat(lvPrices.Items[I].SubItems[2]), I + 1);
end;
bdtMaterial:
begin
Row.SetCostValue(cstPrice,
StrToFloat(lvPrices.Items[I].SubItems[1]), I + 1);
Row.SetCostValue(cstPriceBT,
StrToFloat(lvPrices.Items[I].SubItems[2]), I + 1);
end;
bdtERs, bdtRows:
begin
Row.SetCostValue(cstPZ,
StrToFloat(lvPrices.Items[I].SubItems[1]), I + 1);
Row.SetCostValue(cstOZ,
StrToFloat(lvPrices.Items[I].SubItems[2]), I + 1);
Row.SetCostValue(cstEM,
StrToFloat(lvPrices.Items[I].SubItems[3]), I + 1);
Row.SetCostValue(cstZM,
StrToFloat(lvPrices.Items[I].SubItems[4]), I + 1);
Row.SetCostValue(cstMT,
StrToFloat(lvPrices.Items[I].SubItems[5]), I + 1);
Row.SetCostValue(cstTZ,
StrToFloat(lvPrices.Items[I].SubItems[6]), I + 1);
Row.SetCostValue(cstTZM,
StrToFloat(lvPrices.Items[I].SubItems[7]), I + 1);
end;
bdtESNs:
begin
Row.SetCostValue(cstTZ,
StrToFloat(lvPrices.Items[I].SubItems[1]), I + 1);
Row.SetCostValue(cstTZM,
StrToFloat(lvPrices.Items[I].SubItems[2]), I + 1);
end;
bdtWorkerScale:
begin
Row.SetCostValue(cstPrice,
StrToFloat(lvPrices.Items[I].SubItems[1]), I + 1);
end;
bdtCargo:
begin
Row.SetCostValue(cstPrice,
StrToFloat(lvPrices.Items[I].SubItems[1]), I + 1);
Row.SetCostValue(cstEM,
StrToFloat(lvPrices.Items[I].SubItems[2]), I + 1);
end;
bdtProject:
begin
Row.SetCostValue(cstPriceA,
StrToFloat(lvPrices.Items[I].SubItems[1]), I + 1);
Row.SetCostValue(cstPriceB,
StrToFloat(lvPrices.Items[I].SubItems[2]), I + 1);
end;
end;
end;
end;
procedure TFmElementEditor.UpdateData(Chapter: TGsChapter);
begin
Chapter.Code := Trim(edtChapterCode.Text);
Chapter.Caption := Trim(edtChapterCaption.Text);
Chapter.NumberFormative := chkIncludeInRowCode.Checked;
Chapter.TitleFormative := chkIncludeInRowCaptions.Checked;
case rgChapterType.ItemIndex of
0:
Chapter.ChapterType := ctChapter;
1:
Chapter.ChapterType := ctTable;
2:
Chapter.ChapterType := ctSharedTitle;
end;
end;
procedure TFmElementEditor.UpdateContent(Index: TGsIndexElement);
begin
pcMain.ActivePage := tsIndex;
edtIndexCode.Text := Index.Code;
edtIndexCaption.Text := Index.Caption;
edtOZ.Text := FloatToStr(Index.OZ);
edtZM.Text := FloatToStr(Index.ZM);
edtEM.Text := FloatToStr(Index.EM);
edtMT.Text := FloatToStr(Index.MAT);
edtSMR.Text := FloatToStr(Index.SMR);
end;
procedure TFmElementEditor.UpdateContent(Row: TGsRow);
var
I: Integer;
Item: TListItem;
begin
pcMain.ActivePage := tsRow;
CreateColumns(Row.Document.BaseDataType);
edtRowCode.Text := Row.Code;
edtRowCaption.Text := Row.Caption;
edtRowMeasure.Text := Row.Measure;
edtRowComment.Text := VarToStr(Row.Attributes[Ord(eaComment)]);
edtWorkCode.Text := VarToStr(Row.Attributes[Ord(eaWorkCode)]);
edtOKPCode.Text := VarToStr(Row.Attributes[Ord(eaOKP)]);
edtCode2001.Text := VarToStr(Row.Attributes[Ord(eaCode2001)]);
edtOKPD2.Text := VarToStr(Row.Attributes[Ord(eaCodeOKPD2)]);
for I := 0 to Row.Document.Zones.Count - 1 do
begin
Item := lvPrices.Items.Add;
Item.Caption := TGsZone(Row.Document.Zones[I]).Code;
Item.SubItems.Add(TGsZone(Row.Document.Zones[I]).Caption);
case Row.Document.BaseDataType of
bdtMachine:
begin
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstPrice, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstZM, I + 1)));
end;
bdtMaterial:
begin
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstPrice, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstPriceBT, I + 1)));
end;
bdtERs, bdtRows:
begin
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstPZ, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstOZ, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstEM, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstZM, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstMT, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstTZ, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstTZM, I + 1)));
end;
bdtESNs:
begin
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstTZ, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstTZM, I + 1)));
end;
bdtWorkerScale:
begin
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstPrice, I + 1)));
end;
bdtCargo:
begin
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstPrice, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstEM, I + 1)));
end;
bdtProject:
begin
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstPriceA, I + 1)));
Item.SubItems.Add(FloatToStr(Row.GetCostValue(cstPriceB, I + 1)));
end;
end;
end;
end;
procedure TFmElementEditor.UpdateContent(Item: TGsAbstractItem);
begin
if Item = nil then
exit;
if Item.ClassType = TGsPriceElement then
UpdateContent(TGsPriceElement(Item))
else
if Item.ClassType = TGsIndexElement then
UpdateContent(TGsIndexElement(Item))
else
if Item.ClassType = TGsRow then
UpdateContent(TGsRow(Item))
else
if Item.ClassType = TGsResource then
UpdateContent(TGsResource(Item))
else
if Item.ClassType = TGsAbstractContainer then
UpdateContent(TGsAbstractContainer(Item))
else
if Item.ClassType = TGsChapter then
UpdateContent(TGsChapter(Item));
end;
procedure TFmElementEditor.UpdateContent(Price: TGsPriceElement);
begin
pcMain.ActivePage := tsPrice;
edtPriceCode.Text := Price.Code;
edtPriceCaption.Text := Price.Caption;
edtPriceMeasure.Text := Price.Measure;
edtPriceCE.Text := FloatToStr(Price.PriceCE);
edtPriceCT.Text := FloatToStr(Price.PriceCT);
edtPriceBE.Text := FloatToStr(Price.PriceBE);
edtPriceBT.Text := FloatToStr(Price.PriceBT);
edtPriceWorkerClass.Text := VarToStr(Price.Attributes[Ord(paWorkClass)]);
edtPriceMass.Text := VarToStr(Price.Attributes[Ord(paMass)]);
edtPriceCargoClass.Text := VarToStr(Price.Attributes[Ord(paCargo)]);
edtPriceBaseComment.Text :=
VarToStr(Price.Attributes[Ord(paPriceBaseComment)]);
edtPriceCurrComment.Text :=
VarToStr(Price.Attributes[Ord(paPriceCurrComment)]);
end;
procedure TFmElementEditor.acNextExecute(Sender: TObject);
begin
FRowIterator.Next;
end;
procedure TFmElementEditor.acPrevExecute(Sender: TObject);
begin
FRowIterator.Prev;
end;
procedure TFmElementEditor.btnCancelClick(Sender: TObject);
begin
Hide;
end;
procedure TFmElementEditor.btnOKClick(Sender: TObject);
begin
if FItem <> nil then
UpdateData(Item);
Close;
end;
function TFmElementEditor.ConvertToFloat(Edit: TCustomEdit): Real;
var
Value: string;
begin
Value := Trim(Edit.Text);
if Value = '' then
Value := '0';
Value := StringReplace(Value, '.', ',', []);
Result := StrToFloatDef(Value, -666);
if Result = -666 then
begin
raise Exception.Create('Îøèáêà ïðåîáðàçîâàíèÿ â ÷èñëî: ' + Value);
end;
end;
procedure TFmElementEditor.CreateColumns(DocumentType: TGsDocumentBaseDataType);
var
Column: TListColumn;
begin
lvPrices.Clear;
lvPrices.Columns.Clear;
Column := lvPrices.Columns.Add;
Column.Caption := '¹';
Column.Width := 25;
Column := lvPrices.Columns.Add;
Column.Caption := 'Çîíû';
Column.Width := 225;
case DocumentType of
bdtMachine:
begin
Column := lvPrices.Columns.Add;
Column.Caption := 'ÏÇ';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'ÇÌ';
Column.Width := 75;
end;
bdtMaterial:
begin
Column := lvPrices.Columns.Add;
Column.Caption := 'Ñìåòíàÿ';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'Îïòîâàÿ';
Column.Width := 75;
end;
bdtERs, bdtRows:
begin
Column := lvPrices.Columns.Add;
Column.Caption := 'ÏÇ';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'ÎÇ';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'ÝÌ';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'ÇÌ';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'ÌÀÒ';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'ÒÇ';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'ÒÇÌ';
Column.Width := 75;
end;
bdtESNs:
begin
Column := lvPrices.Columns.Add;
Column.Caption := 'ÒÇ';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'ÒÇÌ';
Column.Width := 75;
end;
bdtWorkerScale:
begin
Column := lvPrices.Columns.Add;
Column.Caption := 'ÏÇ';
Column.Width := 75;
end;
bdtCargo:
begin
Column := lvPrices.Columns.Add;
Column.Caption := 'ÏÇ';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'ÝÌ';
Column.Width := 75;
end;
bdtProject:
begin
Column := lvPrices.Columns.Add;
Column.Caption := 'A';
Column.Width := 75;
Column := lvPrices.Columns.Add;
Column.Caption := 'B';
Column.Width := 75;
end;
end;
end;
procedure TFmElementEditor.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TFmElementEditor.FormCreate(Sender: TObject);
begin
FEdit := TEdit.Create(Self);
FEdit.Parent := lvPrices;
FEdit.OnKeyPress := EditKeyPress;
FEdit.OnExit := editExit;
FEdit.Visible := false;
end;
procedure TFmElementEditor.FormDestroy(Sender: TObject);
begin
FRowIterator := nil;
FEdit.Free;
end;
procedure TFmElementEditor.WorksListLinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType);
var
F: TFmWorksEditor;
begin
F := TFmWorksEditor.Create(Self);
try
F.Row := Self.Item as TGsRow;
F.ShowModal;
finally
F.Free;
end;
end;
procedure TFmElementEditor.lvPricesMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
R: TRect;
ht: TLVHitTestInfo;
begin
ListItem := TListView(Sender).GetItemAt(2, Y);
if ListItem = nil then
exit;
FillChar(ht, SizeOf(ht), 0);
ht.pt.X := X;
ht.pt.Y := Y;
SendMessage(TListView(Sender).Handle, LVM_SUBITEMHITTEST, 0, Integer(@ht));
FSub := ht.iSubItem;
// Caption := inttostr(FSub);
if FSub > 0 then
begin
ListView_GetSubItemRect(TListView(Sender).Handle, ListItem.Index, FSub,
LVIR_BOUNDS, @R);
// Offsetrect(R, TListView(Sender).Left, TListView(Sender).Top);
FEdit.SetBounds(R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top);
Dec(FSub);
FEdit.Text := ListItem.SubItems[FSub];
FEdit.Visible := True;
FEdit.SetFocus;
end;
end;
procedure TFmElementEditor.EditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
SetEditText;
Key := #0;
end;
end;
procedure TFmElementEditor.editExit(Sender: TObject);
begin
SetEditText;
end;
procedure TFmElementEditor.SetEditText;
begin
if FSub > 1 then
ListItem.SubItems[FSub] := FloatToStr(ConvertToFloat(FEdit))
else
ListItem.SubItems[FSub] := FEdit.Text;
FEdit.Visible := false;
end;
procedure TFmElementEditor.SetItem(AItem: TGsAbstractItem);
begin
if FItem <> AItem then
begin
FItem := AItem;
UpdateContent(FItem);
end;
end;
procedure TFmElementEditor.UpdateContent(Container: TGsAbstractContainer);
begin
pcMain.ActivePage := Self.tsContainer;
edtContainerCaption.Text := Container.Caption;
end;
procedure TFmElementEditor.UpdateContent(Resource: TGsResource);
begin
pcMain.ActivePage := tsResource;
edtResourceCode.Text := Resource.Code;
edtResourceCaption.Text := Resource.Caption;
edtResourceMeasure.Text := Resource.Measure;
if Resource.Outlay.Count.IsCommon then
edtResourceCount.Text := FloatToStr(Resource.Outlay.Count.CommonValue);
cbNotCount.Checked := ooNotCount in Resource.Outlay.Options;
cbProject.Checked := ooProjekt in Resource.Outlay.Options;
cbReturn.Checked := ooReturn in Resource.Outlay.Options;
end;
procedure TFmElementEditor.UpdateContent(Chapter: TGsChapter);
begin
pcMain.ActivePage := tsChapter;
edtChapterCode.Text := Chapter.Code;
edtChapterCaption.Text := Chapter.Caption;
chkIncludeInRowCode.Checked := Chapter.NumberFormative;
chkIncludeInRowCaptions.Checked := Chapter.TitleFormative;
case Chapter.ChapterType of
ctChapter:
rgChapterType.ItemIndex := 0;
ctTable:
rgChapterType.ItemIndex := 1;
ctSharedTitle:
rgChapterType.ItemIndex := 2;
end;
end;
procedure TFmElementEditor.UpdateData(Item: TGsAbstractItem);
begin
if Item.ClassType = TGsPriceElement then
UpdateData(TGsPriceElement(Item))
else
if Item.ClassType = TGsIndexElement then
UpdateData(TGsIndexElement(Item))
else
if Item.ClassType = TGsRow then
UpdateData(TGsRow(Item))
else
if Item.ClassType = TGsResource then
UpdateData(TGsResource(Item))
else
if Item.ClassType = TGsAbstractContainer then
UpdateData(TGsAbstractContainer(Item))
else
if Item.ClassType = TGsChapter then
UpdateData(TGsChapter(Item));
end;
procedure TFmElementEditor.UpdateData(Container: TGsAbstractContainer);
begin
Container.Caption := Trim(edtContainerCaption.Text);
end;
procedure TFmElementEditor.UpdateData(Resource: TGsResource);
begin
Resource.Code := Trim(edtResourceCode.Text);
Resource.Caption := Trim(edtResourceCaption.Text);
Resource.Measure := Trim(edtResourceMeasure.Text);
Resource.Outlay.Count.CommonValue := ConvertToFloat(edtResourceCount);
Resource.Outlay.Options := [];
if cbNotCount.Checked then
Resource.Outlay.Options := Resource.Outlay.Options + [GsDocument.ooNotCount];
if cbProject.Checked then
Resource.Outlay.Options := Resource.Outlay.Options + [GsDocument.ooProjekt];
if cbReturn.Checked then
Resource.Outlay.Options := Resource.Outlay.Options + [GsDocument.ooReturn];
end;
end.
|
unit uDV_PenezniPolozky;
interface
uses
Data.Win.ADODB, System.Classes, uMainDataSet, uDV_Stavy;
type
TDV_PenezniPolozky = class
private
class function GetId: string; static;
class function GetPopis: string; static;
class function GetIdStav: string; static;
class function GetDatumObdrzeni: string; static;
class function GetDatumVyplaceni: string; static;
class function GetCastka: string; static;
class function GetMena: string; static;
public
class function CreateDV_PenezniPolozky(AOwner: TComponent): TMainDataSet; static;
class function GetTabName: string;
class property Id: string read GetId;
class property Popis: string read GetPopis;
class property IdStav: string read GetIdStav;
class property DatumObdrzeni: string read GetDatumObdrzeni;
class property DatumVyplaceni: string read GetDatumVyplaceni;
class property Castka: string read GetCastka;
class property Mena: string read GetMena;
end;
implementation
{ TDV_PenezniPolozky }
class function TDV_PenezniPolozky.CreateDV_PenezniPolozky(AOwner: TComponent): TMainDataSet;
begin
Result := TMainDataSet.Create(AOwner);
Result.CommandText :=
'SELECT '
+TDV_PenezniPolozky.Id+','
+TDV_PenezniPolozky.Popis+','
// +TDV_Stavy.Stav+','
+TDV_PenezniPolozky.DatumObdrzeni+','
+TDV_PenezniPolozky.DatumVyplaceni+','
+TDV_PenezniPolozky.Castka+','
+TDV_PenezniPolozky.Mena
+' FROM '
+TDV_PenezniPolozky.GetTabName
// +' LEFT JOIN '
// +TDV_Stavy.GetTabName
// +' ON '
// +TDV_Faktury.idStav+'='
// +TDV_Stavy.Id
;
end;
class function TDV_PenezniPolozky.GetCastka: string;
begin
Result := 'castka';
end;
class function TDV_PenezniPolozky.GetDatumObdrzeni: string;
begin
Result := 'datum_obdrzeni';
end;
class function TDV_PenezniPolozky.GetDatumVyplaceni: string;
begin
Result := 'datum_vyplaceni';
end;
class function TDV_PenezniPolozky.GetId: string;
begin
Result := 'id';
end;
class function TDV_PenezniPolozky.GetIdStav: string;
begin
Result := 'idStav';
end;
class function TDV_PenezniPolozky.GetMena: string;
begin
Result := 'mena';
end;
class function TDV_PenezniPolozky.GetPopis: string;
begin
Result := 'popis';
end;
class function TDV_PenezniPolozky.GetTabName: string;
begin
Result := 'tabPenezniPolozky';
end;
end.
|
unit uMQTTServer;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils, GlobalTypes, Winsock2, uMQTT, Threads, Platform, SyncObjs;
const
MinVersion = 3;
stInit = 0;
stClosed = 1;
stConnecting = 2;
stConnected = 3;
stClosing = 4;
stError = 5;
stQuitting = 6;
type
TMQTTClient = class;
TMQTTThread = class;
TMQTTPacketStore = class;
TMQTTMessageStore = class;
TMQTTServer = class;
TTimerRec = record
Owner : TObject;
No : LongWord;
Handle : TTimerHandle;
end;
PTimerRec = ^TTimerRec;
TMQTTPacket = class
ID : Word;
Stamp : TDateTime;
Counter : cardinal;
Retries : integer;
Publishing : Boolean;
Msg : TMemoryStream;
procedure Assign (From : TMQTTPacket);
constructor Create;
destructor Destroy; override;
end;
TMQTTMessage = class
ID : Word;
Stamp : TDateTime;
LastUsed : TDateTime;
Qos : TMQTTQOSType;
Retained : boolean;
Counter : cardinal;
Retries : integer;
Topic : UTF8String;
Message : string;
procedure Assign (From : TMQTTMessage);
constructor Create;
destructor Destroy; override;
end;
TMQTTSession = class
ClientID : UTF8String;
Stamp : TDateTime;
InFlight : TMQTTPacketStore;
Releasables : TMQTTMessageStore;
constructor Create;
destructor Destroy; override;
end;
TMQTTSessionStore = class
List : TList;
Stamp : TDateTime;
function GetItem (Index: Integer): TMQTTSession;
procedure SetItem (Index: Integer; const Value: TMQTTSession);
property Items [Index: Integer]: TMQTTSession read GetItem write SetItem; default;
function Count : integer;
procedure Clear;
function GetSession (ClientID : UTF8String) : TMQTTSession;
procedure StoreSession (ClientID : UTF8String; aClient : TMQTTThread); overload;
procedure StoreSession (ClientID : UTF8String; aClient : TMQTTClient); overload;
procedure DeleteSession (ClientID : UTF8String);
procedure RestoreSession (ClientID : UTF8String; aClient : TMQTTThread); overload;
procedure RestoreSession (ClientID : UTF8String; aClient : TMQTTClient); overload;
constructor Create;
destructor Destroy; override;
end;
TMQTTPacketStore = class
List : TList;
Stamp : TDateTime;
function GetItem (Index: Integer): TMQTTPacket;
procedure SetItem (Index: Integer; const Value: TMQTTPacket);
property Items [Index: Integer]: TMQTTPacket read GetItem write SetItem; default;
function Count : integer;
procedure Clear;
procedure Assign (From : TMQTTPacketStore);
function AddPacket (anID : Word; aMsg : TMemoryStream; aRetry : cardinal; aCount : cardinal) : TMQTTPacket;
procedure DelPacket (anID : Word);
function GetPacket (anID : Word) : TMQTTPacket;
procedure Remove (aPacket : TMQTTPacket);
constructor Create;
destructor Destroy; override;
end;
TMQTTMessageStore = class
List : TList;
Stamp : TDateTime;
function GetItem (Index: Integer): TMQTTMessage;
procedure SetItem (Index: Integer; const Value: TMQTTMessage);
property Items [Index: Integer]: TMQTTMessage read GetItem write SetItem; default;
function Count : integer;
procedure Clear;
procedure Assign (From : TMQTTMessageStore);
function AddMsg (anID : Word; aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType; aRetry : cardinal; aCount : cardinal; aRetained : Boolean = false) : TMQTTMessage;
procedure DelMsg (anID : Word);
function GetMsg (anID : Word) : TMQTTMessage;
procedure Remove (aMsg : TMQTTMessage);
constructor Create;
destructor Destroy; override;
end;
TMQTTThread = class (TWinsock2TCPServerThread)
private
FOnMon : TMQTTMonEvent;
Owner : TMQTTServer;
FGraceful : boolean;
FBroker : Boolean; // non standard
FOnSubscriptionChange: TNotifyEvent;
procedure DoSend (Sender : TObject; anID : Word; aRetry : integer; aStream : TMemoryStream);
procedure RxSubscribe (Sender : TObject; anID : Word; Topics : TStringList);
procedure RxUnsubscribe (Sender : TObject; anID : Word; Topics : TStringList);
procedure RxPubAck (Sender : TObject; anID : Word);
procedure RxPubRec (Sender : TObject; anID : Word);
procedure RxPubRel (Sender : TObject; anID : Word);
procedure RxPubComp (Sender : TObject; anID : Word);
public
Subscriptions : TStringList;
Parser : TMQTTParser;
InFlight : TMQTTPacketStore;
Releasables : TMQTTMessageStore;
procedure DoSetWill (Sender : TObject; aTopic, aMessage : UTF8String; aQOS : TMQTTQOSType; aRetain : boolean);
constructor Create (aServer : TWinsock2TCPServer);
destructor Destroy; override;
property OnSubscriptionChange : TNotifyEvent read FOnSubscriptionChange write FOnSubscriptionChange;
property OnMon : TMQTTMonEvent read FOnMon write FOnMon;
end;
{ TMQTTClient }
TMQTTClient = class (TThread)
private
Timers : array [1 .. 3] of TTimerRec;
FUsername, FPassword : UTF8String;
FMessageID : Word;
FHost : string;
FPort : integer;
FState : integer;
FEnable, FOnline : Boolean;
FGraceful : Boolean;
FOnOnline: TNotifyEvent;
FOnOffline: TMQTTDisconnectEvent;
FOnEnableChange: TNotifyEvent;
FOnMsg: TMQTTMsgEvent;
FOnFailure: TMQTTFailureEvent;
FLocalBounce: Boolean;
FAutoSubscribe: Boolean;
FOnClientID : TMQTTClientIDEvent;
FBroker: Boolean; // non standard
FEvent : TEvent;
procedure DoSend (Sender : TObject; anID : Word; aRetry : integer; aStream : TMemoryStream);
procedure RxConnAck (Sender : TObject; aCode : byte);
procedure RxSubAck (Sender : TObject; anID : Word; Qoss : array of TMQTTQosType);
procedure RxPubAck (Sender : TObject; anID : Word);
procedure RxPubRec (Sender : TObject; anID : Word);
procedure RxPubRel (Sender : TObject; anID : Word);
procedure RxPubComp (Sender : TObject; anID : Word);
procedure RxPublish (Sender : TObject; anID : Word; aTopic : UTF8String; aMessage : string);
procedure RxUnsubAck (Sender : TObject; anID : Word);
function GetClientID: UTF8String;
procedure SetClientID (const Value: UTF8String);
function GetKeepAlive: Word;
procedure SetKeepAlive (const Value: Word);
function GetMaxRetries : integer;
procedure SetMaxRetries (const Value: integer);
function GetRetryTime : cardinal;
procedure SetRetryTime (const Value : cardinal);
function GetClean: Boolean;
procedure SetClean (const Value: Boolean);
function GetPassword: UTF8String;
function GetUsername: UTF8String;
procedure SetPassword (const Value: UTF8String);
procedure SetUsername (const Value: UTF8String);
protected
procedure SetState (NewState : integer);
procedure Execute; override;
public
Link : TWinsock2TCPClient;
Parser : TMQTTParser;
InFlight : TMQTTPacketStore;
Releasables : TMQTTMessageStore;
Subscriptions : TStringList;
procedure SetTimer (No, Interval : LongWord; Once : boolean);
procedure KillTimer (No : Longword);
function Enabled : boolean;
function Online : boolean;
function NextMessageID : Word;
procedure Subscribe (aTopic : UTF8String; aQos : TMQTTQOSType); overload;
procedure Subscribe (Topics : TStringList); overload;
procedure Unsubscribe (aTopic : UTF8String); overload;
procedure Unsubscribe (Topics : TStringList); overload;
procedure Ping;
procedure Publish (aTopic : UTF8String; aMessage : string; aQos : TMQTTQOSType; aRetain : Boolean = false);
procedure SetWill (aTopic, aMessage : UTF8String; aQos : TMQTTQOSType; aRetain : Boolean = false);
procedure Activate (Enable : Boolean);
constructor Create;
destructor Destroy; override;
published
property ClientID : UTF8String read GetClientID write SetClientID;
property KeepAlive : Word read GetKeepAlive write SetKeepAlive;
property MaxRetries : integer read GetMaxRetries write SetMaxRetries;
property RetryTime : cardinal read GetRetryTime write SetRetryTime;
property Clean : Boolean read GetClean write SetClean;
property Broker : Boolean read FBroker write FBroker; // no standard
property AutoSubscribe : Boolean read FAutoSubscribe write FAutoSubscribe;
property Username : UTF8String read GetUsername write SetUsername;
property Password : UTF8String read GetPassword write SetPassword;
property Host : string read FHost write FHost;
property Port : integer read FPort write FPort;
property LocalBounce : Boolean read FLocalBounce write FLocalBounce;
property OnClientID : TMQTTClientIDEvent read FOnClientID write FOnClientID;
property OnOnline : TNotifyEvent read FOnOnline write FOnOnline;
property OnOffline : TMQTTDisconnectEvent read FOnOffline write FOnOffline;
property OnEnableChange : TNotifyEvent read FOnEnableChange write FOnEnableChange;
property OnFailure : TMQTTFailureEvent read FOnFailure write FOnFailure;
property OnMsg : TMQTTMsgEvent read FOnMsg write FOnMsg;
end;
{ TMQTTServer }
TMQTTServer = class (TWinsock2TCPListener)
protected
procedure DoConnect (aThread : TWinsock2TCPServerThread); override;
procedure DoDisconnect (aThread : TWinsock2TCPServerThread); override;
function DoExecute (aThread : TWinsock2TCPServerThread) : Boolean; override;
private
FOnMon : TMQTTMonEvent;
FOnClientsChange: TMQTTIDEvent;
FOnCheckUser: TMQTTCheckUserEvent;
FPort : integer;
FEnable : boolean;
FOnBrokerOffline: TMQTTDisconnectEvent;
FOnBrokerOnline: TNotifyEvent;
FOnBrokerEnableChange: TNotifyEvent;
FOnObituary: TMQTTObituaryEvent;
FOnEnableChange: TNotifyEvent;
FLocalBounce: Boolean;
FOnSubscription: TMQTTSubscriptionEvent;
FOnFailure: TMQTTFailureEvent;
FMaxRetries: integer;
FRetryTime: cardinal;
FOnStoreSession: TMQTTSessionEvent;
FOnRestoreSession: TMQTTSessionEvent;
FOnDeleteSession: TMQTTSessionEvent;
// FOnRetain: TMQTTRetainEvent;
// FOnGetRetained: TMQTTRetainedEvent;
// broker events
procedure BkrOnline (Sender : TObject);
procedure BkrOffline (Sender : TObject; Graceful : boolean);
procedure BkrEnableChanged (Sender : TObject);
procedure BkrSubscriptionChange (Sender : TObject);
procedure BkrMsg (Sender : TObject; aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType; aRetained : boolean);
// socket events
procedure DoCreateThread (aServer : TWinsock2TCPServer; var aThread : TWinsock2TCPServerThread);
// procedure DoClientConnect (Sender: TObject; Client: TWSocketClient; Error: Word);
// procedure DoClientDisconnect (Sender: TObject; Client: TWSocketClient; Error: Word);
// procedure DoClientCreate (Sender: TObject; Client: TWSocketClient);
// parser events
procedure RxDisconnect (Sender : TObject);
procedure RxPing (Sender : TObject);
procedure RxPublish (Sender : TObject; anID : Word; aTopic : UTF8String; aMessage : AnsiString);
procedure RxHeader (Sender : TObject; MsgType: TMQTTMessageType; Dup: Boolean;
Qos: TMQTTQOSType; Retain: Boolean);
procedure RxConnect (Sender : TObject;
aProtocol : UTF8String;
aVersion : byte;
aClientID,
aUserName, aPassword : UTF8String;
aKeepAlive : Word; aClean : Boolean);
procedure RxBrokerConnect (Sender : TObject; // non standard
aProtocol : UTF8String;
aVersion : byte;
aClientID,
aUserName, aPassword : UTF8String;
aKeepAlive : Word; aClean : Boolean);
procedure SetMaxRetries (const Value: integer);
procedure SetRetryTime (const Value: cardinal);
public
FOnMonHdr : TMQTTHeaderEvent;
Timers : array [1 .. 3] of TTimerRec;
MessageID : Word;
Brokers : TList;
Sessions : TMQTTSessionStore;
Retained : TMQTTMessageStore;
procedure SetTimer (No, Interval : LongWord; Once : boolean);
procedure KillTimer (No : Longword);
function NextMessageID : Word;
procedure Activate (Enable : boolean);
procedure LoadBrokers (anIniFile : string);
procedure StoreBrokers (anIniFile : string);
function GetClient (aParser : TMQTTParser) : TMQTTThread; overload;
function GetClient (aClientID : UTF8String) : TMQTTThread; overload;
procedure PublishToAll (From : TObject; aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType; wasRetained : boolean = false);
function Enabled : boolean;
function AddBroker (aHost : string; aPort : integer) : TMQTTClient;
procedure SyncBrokerSubscriptions (aBroker : TMQTTClient);
constructor Create;
destructor Destroy; override;
published
property MaxRetries : integer read FMaxRetries write SetMaxRetries;
property RetryTime : cardinal read FRetryTime write SetRetryTime; // in secs
property Port : integer read FPort write FPort;
property LocalBounce : Boolean read FLocalBounce write FLocalBounce;
property OnFailure : TMQTTFailureEvent read FOnFailure write FOnFailure;
property OnStoreSession : TMQTTSessionEvent read FOnStoreSession write FOnStoreSession;
property OnRestoreSession : TMQTTSessionEvent read FOnRestoreSession write FOnRestoreSession;
property OnDeleteSession : TMQTTSessionEvent read FOnDeleteSession write FOnDeleteSession;
// property OnRetain : TMQTTRetainEvent read FOnRetain write FOnRetain;
// property OnGetRetained : TMQTTRetainedEvent read FOnGetRetained write FOnGetRetained;
property OnBrokerOnline : TNotifyEvent read FOnBrokerOnline write FOnBrokerOnline;
property OnBrokerOffline : TMQTTDisconnectEvent read FOnBrokerOffline write FOnBrokerOffline;
property OnBrokerEnableChange : TNotifyEvent read FOnBrokerEnableChange write FOnBrokerEnableChange;
property OnEnableChange : TNotifyEvent read FOnEnableChange write FOnEnableChange;
property OnSubscription : TMQTTSubscriptionEvent read FOnSubscription write FOnSubscription;
property OnClientsChange : TMQTTIDEvent read FOnClientsChange write FOnClientsChange;
property OnCheckUser : TMQTTCheckUserEvent read FOnCheckUser write FOnCheckUser;
property OnObituary : TMQTTObituaryEvent read FOnObituary write FOnObituary;
property OnMon : TMQTTMonEvent read FOnMon write FOnMon;
end;
function SubTopics (aTopic : UTF8String) : TStringList;
function IsSubscribed (aSubscription, aTopic : UTF8String) : boolean;
implementation
uses
IniFiles, uLog, GlobalConst;
function StateToStr (s : integer) : string;
begin
case s of
stInit : Result := 'Init';
stClosed : Result := 'Closed';
stConnecting : Result := 'Connecting';
stConnected : Result := 'Connected';
stClosing : Result := 'Closing';
stError : Result := 'Error';
stQuitting : Result := 'Quitting';
else Result := 'Unknown ' + IntToStr (s);
end;
end;
function SubTopics (aTopic : UTF8String) : TStringList;
var
i : integer;
begin
Result := TStringList.Create;
Result.Add ('');
for i := 1 to length (aTopic) do
begin
if aTopic[i] = '/' then
Result.Add ('')
else
Result[Result.Count - 1] := Result[Result.Count - 1] + Char (aTopic[i]);
end;
end;
function IsSubscribed (aSubscription, aTopic : UTF8String) : boolean;
var
s, t : TStringList;
i : integer;
MultiLevel : Boolean;
begin
s := SubTopics (aSubscription);
t := SubTopics (aTopic);
MultiLevel := (s[s.Count - 1] = '#'); // last field is #
if not MultiLevel then
Result := (s.Count = t.Count)
else
Result := (s.Count <= t.Count + 1);
if Result then
begin
for i := 0 to s.Count - 1 do
begin
if (i >= t.Count) then Result := MultiLevel
else if (i = s.Count - 1) and (s[i] = '#') then break
else if s[i] = '+' then continue // they match
else
Result := Result and (s[i] = t[i]);
if not Result then break;
end;
end;
s.Free;
t.Free;
end;
procedure SetDup (aStream : TMemoryStream; aState : boolean);
var
x : byte;
begin
if aStream.Size = 0 then exit;
aStream.Seek (0, soFromBeginning);
x := 0;
aStream.Read (x, 1);
x := (x and $F7) or (ord (aState) * $08);
aStream.Seek (0, soFromBeginning);
aStream.Write (x, 1);
end;
{ TMQTTThread }
constructor TMQTTThread.Create (aServer : TWinsock2TCPServer);
begin
inherited Create (aServer);
FBroker := false; // non standard
Parser := TMQTTParser.Create;
Parser.OnSend := DoSend;
Parser.OnSetWill := DoSetWill;
Parser.OnSubscribe := RxSubscribe;
Parser.OnUnsubscribe := RxUnsubscribe;
Parser.OnPubAck := RxPubAck;
Parser.OnPubRel := RxPubRel;
Parser.OnPubRec := RxPubRec;
Parser.OnPubComp := RxPubComp;
InFlight := TMQTTPacketStore.Create;
Releasables := TMQTTMessageStore.Create;
Subscriptions := TStringList.Create;
end;
destructor TMQTTThread.Destroy;
begin
InFlight.Clear;
InFlight.Free;
Releasables.Clear;
Releasables.Free;
Parser.Free;
Subscriptions.Free;
inherited;
end;
procedure TMQTTThread.DoSend (Sender: TObject; anID : Word; aRetry : integer; aStream: TMemoryStream);
var
x : byte;
begin
// if FState = stConnected then
// begin
x := 0;
aStream.Seek (0, soFromBeginning);
aStream.Read (x, 1);
if (TMQTTQOSType ((x and $06) shr 1) in [qtAT_LEAST_ONCE, qtEXACTLY_ONCE]) and
(TMQTTMessageType ((x and $f0) shr 4) in [{mtPUBREL,} mtPUBLISH, mtSUBSCRIBE, mtUNSUBSCRIBE]) and
(anID > 0) then
begin
InFlight.AddPacket (anID, aStream, aRetry, Parser.RetryTime); // start disabled
Log (Parser.ClientID + ' Message ' + IntToStr (anID) + ' created.');
end;
Server.WriteData (aStream.Memory, aStream.Size);
// end;
end;
procedure TMQTTThread.DoSetWill (Sender: TObject; aTopic, aMessage: UTF8String;
aQos : TMQTTQOSType; aRetain: boolean);
begin
Parser.WillTopic := aTopic;
Parser.WillMessage := aMessage;
Parser.WillQos := aQos;
Parser.WillRetain := aRetain;
end;
procedure TMQTTThread.RxPubAck (Sender: TObject; anID: Word);
begin
InFlight.DelPacket (anID);
Log (Parser.ClientID + ' ACK Message ' + IntToStr (anID) + ' disposed of.');
end;
procedure TMQTTThread.RxPubComp (Sender: TObject; anID: Word);
begin
InFlight.DelPacket (anID);
Log (Parser.ClientID + ' COMP Message ' + IntToStr (anID) + ' disposed of.');
end;
procedure TMQTTThread.RxPubRec (Sender: TObject; anID: Word);
var
aPacket : TMQTTPacket;
begin
aPacket := InFlight.GetPacket (anID);
if aPacket <> nil then
begin
aPacket.Counter := Parser.RetryTime;
if aPacket.Publishing then
begin
aPacket.Publishing := false;
Log (Parser.ClientID + ' REC Message ' + IntToStr (anID) + ' recorded.');
end
else
Log (Parser.ClientID + ' REC Message ' + IntToStr (anID) + ' already recorded.');
end
else
Log (Parser.ClientID + ' REC Message ' + IntToStr (anID) + ' not found.');
Parser.SendPubRel (anID);
end;
procedure TMQTTThread.RxPubRel (Sender: TObject; anID: Word);
var
aMsg : TMQTTMessage;
begin
aMsg := Releasables.GetMsg (anID);
if aMsg <> nil then
begin
Log (Parser.ClientID + ' REL Message ' + IntToStr (anID) + ' publishing @ ' + QOSNames[aMsg.Qos]);
Owner.PublishToAll (Self, aMsg.Topic, aMsg.Message, aMsg.Qos);
Releasables.Remove (aMsg);
aMsg.Free;
Log (Parser.ClientID + ' REL Message ' + IntToStr (anID) + ' removed from storage.');
end
else
Log (Parser.ClientID + ' REL Message ' + IntToStr (anID) + ' has been already removed from storage.');
Parser.SendPubComp (anID);
end;
procedure TMQTTThread.RxSubscribe (Sender: TObject; anID: Word; Topics: TStringList);
var
x : cardinal;
q : TMQTTQOSType;
i, j : integer;
found : boolean;
Qoss : array of TMQTTQOSType;
bMsg : TMQTTMessage;
aQos : TMQTTQOSType;
begin
SetLength (Qoss, Topics.Count);
for i := 0 to Topics.Count - 1 do
begin
found := false;
x := cardinal (Topics.Objects[i]) and $03;
q := TMQTTQOSType (x);
if Assigned (Owner.FOnSubscription) then
Owner.FOnSubscription (Self, UTF8String (Topics[i]), q);
for j := 0 to Subscriptions.Count - 1 do
if Subscriptions[j] = Topics[i] then
begin
found := true;
Subscriptions.Objects[j] := TObject (q);
break;
end;
if not found then
begin
Subscriptions.AddObject (Topics[i], TObject (q));
end;
Qoss[i] := q;
for j := 0 to Owner.Retained.Count - 1 do // set retained
begin
bMsg := Owner.Retained[j];
if IsSubscribed (UTF8String (Topics[i]), bMsg.Topic) then
begin
aQos := bMsg.Qos;
if q < aQos then aQos := q;
bMsg.LastUsed := Now;
Parser.SendPublish (Owner.NextMessageID, bMsg.Topic, bMsg.Message, aQos, false, true);
end;
end;
end;
if Parser.RxQos = qtAT_LEAST_ONCE then Parser.SendSubAck (anID, Qoss);
if Assigned (FOnSubscriptionChange) then FOnSubscriptionChange (Self);
end;
procedure TMQTTThread.RxUnsubscribe (Sender: TObject; anID: Word; Topics: TStringList);
var
i, j : integer;
changed : boolean;
begin
changed := false;
for i := 0 to Topics.Count - 1 do
begin
for j := Subscriptions.Count - 1 downto 0 do
begin
if Subscriptions[j] = Topics[i] then
begin
Subscriptions.Delete (j);
changed := true;
end;
end;
end;
if changed and Assigned (FOnSubscriptionChange) then
FOnSubscriptionChange (Self);
if Parser.RxQos = qtAT_LEAST_ONCE then Parser.SendUnSubAck (anID);
end;
{ TMQTTServer }
procedure TMQTTServer.Activate (Enable: boolean);
begin
if FEnable = Enable then exit;
if (Enable) then
begin
BoundPort := FPort;
try
Active := true;
FEnable := true;
except
FEnable := false;
end;
if FEnable then SetTimer (3, 100, true);
end
else
begin
FEnable := false;
Active := false;
KillTimer (1);
KillTimer (2);
KillTimer (3);
end;
if Assigned (FOnEnableChange) then FOnEnableChange (Self);
end;
function TMQTTServer.AddBroker (aHost: string; aPort: integer): TMQTTClient;
begin
Result := TMQTTClient.Create;
Result.Host := aHost;
Result.Port := aPort;
Result.Broker := true;
Result.LocalBounce := false;
Result.OnOnline := BkrOnline;
Result.OnOffline := BkrOffline;
Result.OnEnableChange := BkrEnableChanged;
Result.OnMsg := BkrMsg;
Brokers.Add (Result);
end;
procedure TMQTTServer.BkrEnableChanged (Sender: TObject);
begin
if Assigned (FOnBrokerEnableChange) then FOnBrokerEnableChange (Sender);
end;
procedure TMQTTServer.BkrOffline (Sender: TObject; Graceful: boolean);
begin
TMQTTClient (Sender).Subscriptions.Clear;
if Assigned (FOnBrokerOffline) then FOnBrokerOffline (Sender, Graceful);
end;
procedure TMQTTServer.BkrOnline (Sender: TObject);
begin
SyncBrokerSubscriptions (TMQTTClient (Sender));
if Assigned (FOnBrokerOnline) then FOnBrokerOnline (Sender);
end;
procedure TMQTTServer.BkrMsg (Sender: TObject; aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType; aRetained : boolean);
var
aBroker : TMQTTClient;
i : integer;
aMsg : TMQTTMessage;
begin
aBroker := TMQTTClient (Sender);
Log ('Received Retained Message from a Broker - Retained ' + ny[aRetained]);
if aRetained then
begin
Log ('Retaining "' + string (aTopic) + '" @ ' + QOSNames[aQos]);
for i := Retained.Count - 1 downto 0 do
begin
aMsg := Retained[i];
if aMsg.Topic = aTopic then
begin
Retained.Remove (aMsg);
aMsg.Free;
break;
end;
end;
Retained.AddMsg (0, aTopic, aMessage, aQos, 0, 0);
end
else
Log ('Received Message from a Broker - Publishing..');
PublishToAll (Sender, aTopic, aMessage, aBroker.Parser.RxQos, aRetained);
end;
procedure TMQTTServer.DoCreateThread (aServer: TWinsock2TCPServer;
var aThread: TWinsock2TCPServerThread);
begin
Log ('Thread Created');
aThread := TMQTTThread.Create (aServer);
with TMQTTThread (aThread) do
begin
Owner := Self;
Parser.OnPing := RxPing;
Parser.OnDisconnect := RxDisconnect;
Parser.OnPublish := RxPublish;
Parser.OnPubRec := RxPubRec;
Parser.OnConnect := RxConnect;
Parser.OnBrokerConnect := RxBrokerConnect; // non standard
Parser.OnHeader := RxHeader;
Parser.MaxRetries := FMaxRetries;
Parser.RetryTime := FRetryTime;
OnSubscriptionChange := BkrSubscriptionChange;
end;
end;
procedure TMQTTServer.DoConnect (aThread: TWinsock2TCPServerThread);
begin
inherited DoConnect (aThread);
Log ('Connect');
// if Assigned (
end;
procedure TMQTTServer.DoDisconnect (aThread: TWinsock2TCPServerThread);
var
aTopic, aMessage : UTF8String;
aQos : TMQTTQOSType;
aClient : TMQTTThread;
begin
aClient := TMQTTThread (aThread);
with aClient do
begin
Log ('Client Disconnected. Graceful ' + ny[FGraceful]);
if (InFlight.Count > 0) or (Releasables.Count > 0) then
begin
if Assigned (FOnStoreSession) then
FOnStoreSession (aClient, Parser.ClientID)
else
Sessions.StoreSession (Parser.ClientID, aClient);
end;
if not FGraceful then
begin
aTopic := Parser.WillTopic;
aMessage := Parser.WillMessage;
aQos := Parser.WillQos;
if Assigned (FOnObituary) then FOnObituary (aClient, aTopic, aMessage, aQos);
PublishToAll (nil, aTopic, aMessage, aQos);
end;
end;
if Assigned (FOnClientsChange) then FOnClientsChange (Self, Threads.Count - 1);
inherited DoDisconnect (aThread);
end;
function TMQTTServer.DoExecute (aThread: TWinsock2TCPServerThread): Boolean;
var
aClient : TMQTTThread;
d : boolean;
b : array [0..255] of byte;
c : integer;
closed : boolean;
begin
Result := inherited DoExecute (aThread);
aClient := TMQTTThread (aThread);
c := 256;
closed := false;
d := aThread.Server.ReadAvailable (@b[0], 255, c, closed);
if closed or not d then Result := false;
if (c = 0) or closed then exit;
aClient.Parser.Parse (@b[0], c);
end;
procedure TMQTTServer.BkrSubscriptionChange (Sender: TObject);
var
i : integer;
begin
Log ('Subscriptions changed...');
for i := 0 to Brokers.Count - 1 do
SyncBrokerSubscriptions (TMQTTClient (Brokers[i]));
end;
constructor TMQTTServer.Create;
var
i : integer;
begin
inherited;
for i := 1 to 3 do
begin
Timers[i].Handle := INVALID_HANDLE_VALUE;
Timers[i].No := i;
Timers[i].Owner := Self;
end;
MessageID := 1000;
FOnMonHdr := nil;
FPort := 18830;
FMaxRetries := DefMaxRetries;
FRetryTime := DefRetryTime;
Brokers := TList.Create;
Sessions := TMQTTSessionStore.Create;
Retained := TMQTTMessageStore.Create;
OnCreateThread := DoCreateThread;
end;
destructor TMQTTServer.Destroy;
var
i : integer;
begin
for i := 1 to 3 do KillTimer (i);
for i := 0 to Brokers.Count - 1 do TMQTTClient (Brokers[i]).Free;
Brokers.Free;
Retained.Free;
Sessions.Free;
Activate (false);
inherited;
end;
procedure TMQTTServer.RxPing (Sender: TObject);
begin
if not (Sender is TMQTTParser) then exit;
TMQTTParser (Sender).SendPingResp;
end;
procedure TMQTTServer.RxPublish (Sender: TObject; anID: Word; aTopic : UTF8String;
aMessage: AnsiString);
var
aParser : TMQTTParser;
aClient : TMQTTThread;
aMsg : TMQTTMessage;
i : integer;
begin
if not (Sender is TMQTTParser) then exit;
aParser := TMQTTParser (Sender);
aClient := GetClient (aParser);
if aClient = nil then exit;
if aParser.RxRetain then
begin
Log ('Retaining "' + string (aTopic) + '" @ ' + QOSNames[aParser.RxQos]);
for i := Retained.Count - 1 downto 0 do
begin
aMsg := Retained[i];
if aMsg.Topic = aTopic then
begin
Retained.Remove (aMsg);
aMsg.Free;
break;
end;
end;
Retained.AddMsg (0, aTopic, aMessage, aParser.RxQos, 0, 0);
end;
case aParser.RxQos of
qtAT_MOST_ONCE :
PublishToAll (aClient, aTopic, aMessage, aParser.RxQos, aParser.RxRetain);
qtAT_LEAST_ONCE :
begin
aParser.SendPubAck (anID);
PublishToAll (aClient, aTopic, aMessage, aParser.RxQos, aParser.RxRetain);
end;
qtEXACTLY_ONCE :
begin
aMsg := aClient.Releasables.GetMsg (anID);
if aMsg = nil then
begin
aClient.Releasables.AddMsg (anID, aTopic, aMessage, aParser.RxQos, 0, 0);
Log (aClient.Parser.ClientID + ' Message ' + IntToStr (anID) + ' stored and idle.');
end
else
Log (aClient.Parser.ClientID + ' Message ' + IntToStr (anID) + ' already stored.');
aParser.SendPubRec (anID);
end;
end;
end;
procedure TMQTTServer.LoadBrokers (anIniFile: string);
var
i : integer;
Sections : TStringList;
aBroker : TMQTTClient;
EnFlag : Boolean;
begin
for i := 0 to Brokers.Count - 1 do TMQTTClient (Brokers[i]).Free;
Brokers.Clear;
Sections := TStringList.Create;
with TIniFile.Create (anIniFile) do
begin
ReadSections (Sections);
for i := 0 to Sections.Count - 1 do
begin
if Copy (Sections[i], 1, 6) = 'BROKER' then
begin
aBroker := AddBroker ('', 0);
aBroker.Host := ReadString (Sections[i], 'Prim Host', '');
aBroker.Port := ReadInteger (Sections[i], 'Port', 18830);
EnFlag := ReadBool (Sections[i], 'Enabled', false);
if EnFlag then aBroker.Activate (true);
end;
end;
Free;
end;
Sections.Free;
end;
procedure TMQTTServer.SetMaxRetries (const Value: integer);
var
i : integer;
aClient : TMQTTThread;
begin
FMaxRetries := Value;
aClient := TMQTTThread (Threads.First);
while aClient <> nil do
begin
aClient.Parser.MaxRetries := Value;
aClient := TMQTTThread (aClient.Next);
end;
for i := 0 to Brokers.Count - 1 do
TMQTTClient (Brokers[i]).Parser.MaxRetries := Value;
end;
procedure TMQTTServer.SetRetryTime (const Value: cardinal);
var
i : integer;
aClient : TMQTTThread;
begin
FRetryTime := Value;
aClient := TMQTTThread (Threads.First);
while aClient <> nil do
begin
aClient.Parser.KeepAlive := Value;
aClient := TMQTTThread (aClient.Next);
end;
for i := 0 to Brokers.Count - 1 do
TMQTTClient (Brokers[i]).Parser.KeepAlive := Value;
end;
procedure ServerTimerTask (Data : Pointer);
var
j : integer;
bPacket : TMQTTPacket;
aClient : TMQTTThread;
aServer : TMQTTServer;
WillClose : Boolean;
begin
with PTimerRec (Data)^ do
begin
aServer := TMQTTServer (Owner);
log ('timer ' + No.ToString + ' triggered');
case No of
3 : begin
aClient := TMQTTThread (aServer.Threads.First);
while aClient <> nil do
begin
if not aClient.Parser.CheckKeepAlive then
begin
WillClose := true;
if Assigned (aServer.FOnFailure) then aServer.FOnFailure (aClient, frKEEPALIVE, WillClose);
if WillClose then aClient.Server.Disconnect;
end
else
begin
for j := aClient.InFlight.Count - 1 downto 0 do
begin
bPacket := aClient.InFlight[j];
if bPacket.Counter > 0 then
begin
bPacket.Counter := bPacket.Counter - 1;
if bPacket.Counter = 0 then
begin
bPacket.Retries := bPacket.Retries + 1;
if bPacket.Retries <= aClient.Parser.MaxRetries then
begin
if bPacket.Publishing then
begin
aClient.InFlight.List.Remove (bPacket);
Log ('Message ' + IntToStr (bPacket.ID) + ' disposed of..');
Log ('Re-issuing Message ' + inttostr (bPacket.ID) + ' Retry ' + inttostr (bPacket.Retries));
SetDup (bPacket.Msg, true);
aClient.DoSend (aClient.Parser, bPacket.ID, bPacket.Retries, bPacket.Msg);
bPacket.Free;
end
else
begin
Log ('Re-issuing PUBREL Message ' + inttostr (bPacket.ID) + ' Retry ' + inttostr (bPacket.Retries));
aClient.Parser.SendPubRel (bPacket.ID, true);
bPacket.Counter := aClient.Parser.RetryTime;
end;
end
else
begin
WillClose := true;
if Assigned (aServer.FOnFailure) then aServer.FOnFailure (aServer, frMAXRETRIES, WillClose);
if WillClose then aClient.Server.Disconnect;
end;
end;
end;
end;
end;
aClient := TMQTTThread (aClient.Next);
end;
end;
end;
end;
end;
procedure TMQTTServer.SetTimer (No, Interval: LongWord; Once : boolean);
var
Flags : Longword;
begin
if not (No in [1 .. 3]) then exit;
if Timers[No].Handle <> INVALID_HANDLE_VALUE then TimerDestroy (Timers[No].Handle);
if Once then Flags := TIMER_FLAG_NONE else Flags := TIMER_FLAG_RESCHEDULE;
Timers[No].Handle := TimerCreateEx (Interval, TIMER_STATE_ENABLED, Flags, ServerTimerTask, @Timers[No]);
end;
procedure TMQTTServer.KillTimer (No: Longword);
begin
if not (No in [1 .. 3]) then exit;
if Timers[No].Handle = INVALID_HANDLE_VALUE then exit;
TimerDestroy (Timers[No].Handle);
Timers[No].Handle := INVALID_HANDLE_VALUE;
end;
procedure TMQTTServer.StoreBrokers (anIniFile: string);
var
i : integer;
aBroker : TMQTTClient;
Sections : TStringList;
begin
Sections := TStringList.Create;
with TIniFile.Create (anIniFile) do
begin
ReadSections (Sections);
for i := 0 to Sections.Count - 1 do
if Copy (Sections[i], 1, 6) = 'BROKER' then
EraseSection (Sections[i]);
for i := 0 to Brokers.Count - 1 do
begin
aBroker := Brokers[i];
WriteString (format ('BROKER%.3d', [i]), 'Prim Host', aBroker.Host);
WriteInteger (format ('BROKER%.3d', [i]), 'Port', aBroker.Port);
WriteBool (format ('BROKER%.3d', [i]), 'Enabled', aBroker.Enabled);
end;
Free;
end;
Sections.Free;
end;
procedure TMQTTServer.SyncBrokerSubscriptions (aBroker: TMQTTClient);
var
i, j, k : integer;
x : cardinal;
ToSub, ToUnsub : TStringList;
aClient : TMQTTThread;
found : boolean;
begin
ToSub := TStringList.Create;
ToUnsub := TStringList.Create;
aClient := TMQTTThread (Threads.First);
while aClient <> nil do
begin
for j := 0 to aClient.Subscriptions.Count - 1 do
begin
found := false;
for k := 0 to ToSub.Count - 1 do
begin
if aClient.Subscriptions[j] = ToSub[k] then
begin
found := true;
break;
end;
end;
if not found then ToSub.AddObject (aClient.Subscriptions[j], aClient.Subscriptions.Objects[j]);
end;
aClient := TMQTTThread (aClient.Next);
end;
// add no longer used to unsubscribe
for i := aBroker.Subscriptions.Count - 1 downto 0 do
begin
found := false;
for j := 0 to ToSub.Count - 1 do
begin
if aBroker.Subscriptions[i] = ToSub[j] then
begin
x := cardinal (aBroker.Subscriptions.Objects[i]) and $03; // change to highest
if x > (cardinal (ToSub.Objects[j]) and $03) then
ToSub.Objects[j] := TObject (x);
found := true;
break;
end;
end;
if not found then
ToUnsub.AddObject (aBroker.Subscriptions[i], aBroker.Subscriptions.Objects[i]);
end;
// remove those already subscribed to
for i := 0 to aBroker.Subscriptions.Count - 1 do
begin
for j := ToSub.Count - 1 downto 0 do
begin
if aBroker.Subscriptions[i] = ToSub[j] then
ToSub.Delete (j); // already subscribed
end;
end;
for i := 0 to ToSub.Count - 1 do
aBroker.Subscribe (UTF8String (ToSub[i]), TMQTTQOSType (cardinal (ToSub.Objects[i]) and $03));
for i := 0 to ToUnsub.Count - 1 do
aBroker.Unsubscribe (UTF8String (ToUnsub[i]));
ToSub.Free;
ToUnsub.Free;
end;
function TMQTTServer.NextMessageID: Word;
var
j : integer;
Unused : boolean;
aMsg : TMQTTPacket;
aClient : TMQTTThread;
begin
repeat
Unused := true;
MessageID := MessageID + 1;
if MessageID = 0 then MessageID := 1; // exclude 0
aClient := TMQTTThread (Threads.First);
while aClient <> nil do
begin
for j := 0 to aClient.InFlight.Count - 1 do
begin
aMsg := aClient.InFlight[j];
if aMsg.ID = MessageID then
begin
Unused := false;
break;
end;
end;
if not Unused then break
else aClient := TMQTTThread (aClient.Next);
end;
until Unused;
Result := MessageID;
end;
procedure TMQTTServer.PublishToAll (From : TObject; aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType; wasRetained : boolean);
var
i, j : integer;
sent : boolean;
aClient : TMQTTThread;
aBroker : TMQTTClient;
bQos : TMQTTQOSType;
begin
Log ('Publishing -- Was Retained ' + ny[wasRetained]);
aClient := TMQTTThread (Threads.First);
while aClient <> nil do
begin
if (aClient = From) and (aClient.FBroker) then continue; // don't send back to self if broker - non standard
//not LocalBounce then continue;
sent := false;
for j := 0 to aClient.Subscriptions.Count - 1 do
begin
if IsSubscribed (UTF8String (aClient.Subscriptions[j]), aTopic) then
begin
bQos := TMQTTQOSType (cardinal (aClient.Subscriptions.Objects[j]) and $03);
if aClient.FBroker then
Log ('Publishing to Broker ' + aClient.Parser.ClientID + ' "' + aTopic + '" Retained ' + ny[wasRetained and aClient.FBroker])
else
Log ('Publishing to Client ' + aClient.Parser.ClientID + ' "' + aTopic + '"');
if bQos > aQos then bQos := aQos;
aClient.Parser.SendPublish (NextMessageID, aTopic, aMessage, bQos, false, wasRetained and aClient.FBroker);
sent := true;
break; // only do first
end;
end;
if (not sent) and (wasRetained) and (aClient.FBroker) then
begin
Log ('Forwarding Retained message to broker');
aClient.Parser.SendPublish (NextMessageID, aTopic, aMessage, qtAT_LEAST_ONCE, false, true);
end;
aClient := TMQTTThread (aClient.Next);
end;
for i := 0 to Brokers.Count - 1 do // brokers get all messages -> downstream
begin
aBroker := TMQTTClient (Brokers[i]);
if aBroker = From then continue;
if not aBroker.Enabled then continue;
// if aBroker then
Log ('Publishing to Broker ' + string (aBroker.ClientID) + ' "' + string (aTopic) + '" @ ' + QOSNames[aQos] + ' Retained ' + ny[wasretained]);
aBroker.Publish (aTopic, aMessage, aQos, wasRetained);
end;
end;
(*
procedure TMQTTServer.DoClientCreate (Sender: TObject; Client: TWSocketClient);
begin
with TClient (Client) do
begin
Parser.OnPing := RxPing;
Parser.OnDisconnect := RxDisconnect;
Parser.OnPublish := RxPublish;
Parser.OnPubRec := RxPubRec;
Parser.OnConnect := RxConnect;
Parser.OnBrokerConnect := RxBrokerConnect; // non standard
Parser.OnHeader := RxHeader;
Parser.MaxRetries := FMaxRetries;
Parser.RetryTime := FRetryTime;
OnMon := DoMon;
OnSubscriptionChange := BkrSubscriptionChange;
end;
end; *)
(*
procedure TMQTTServer.DoClientDisconnect (Sender: TObject;
Client: TWSocketClient; Error: Word);
var
aTopic, aMessage : UTF8String;
aQos : TMQTTQOSType;
begin
with TClient (Client) do
begin
Mon ('Client Disconnected. Graceful ' + ny[TClient (Client).FGraceful]);
if (InFlight.Count > 0) or (Releasables.Count > 0) then
begin
if Assigned (FOnStoreSession) then
FOnStoreSession (Client, Parser.ClientID)
else
Sessions.StoreSession (Parser.ClientID, TClient (Client));
end;
if not FGraceful then
begin
aTopic := Parser.WillTopic;
aMessage := Parser.WillMessage;
aQos := Parser.WillQos;
if Assigned (FOnObituary) then
FOnObituary (Client, aTopic, aMessage, aQos);
PublishToAll (nil, aTopic, AnsiString (aMessage), aQos);
end;
end;
if Assigned (FOnClientsChange) then
FOnClientsChange (Server, Server.ClientCount - 1);
end;
*)
function TMQTTServer.Enabled: boolean;
begin
Result := FEnable;
end;
function TMQTTServer.GetClient (aClientID: UTF8String): TMQTTThread;
begin
Result := TMQTTThread (Threads.First);
while Result <> nil do
begin
if Result.Parser.ClientID = aClientID then exit;
Result := TMQTTThread (Result.Next);
end;
Result := nil;
end;
function TMQTTServer.GetClient (aParser: TMQTTParser): TMQTTThread;
begin
Result := TMQTTThread (Threads.First);
while Result <> nil do
begin
if Result.Parser = aParser then exit;
Result := TMQTTThread (Result.Next);
end;
Result := nil;
end;
procedure TMQTTServer.RxBrokerConnect (Sender: TObject; aProtocol: UTF8String;
aVersion: byte; aClientID, aUserName, aPassword: UTF8String; aKeepAlive: Word;
aClean: Boolean);
var
aClient : TMQTTThread;
begin
if not (Sender is TMQTTParser) then exit;
aClient := GetClient (TMQTTParser (Sender));
if aClient = nil then exit;
aClient.FBroker := true;
RxConnect (Sender, aProtocol, aVersion, aClientID, aUserName, aPassword, aKeepAlive, aClean);
end;
procedure TMQTTServer.RxConnect (Sender: TObject; aProtocol: UTF8String;
aVersion: byte; aClientID, aUserName, aPassword: UTF8String; aKeepAlive: Word;
aClean: Boolean);
var
aClient : TMQTTThread;
Allowed : Boolean;
begin
Allowed := false;
if not (Sender is TMQTTParser) then exit;
aClient := GetClient (TMQTTParser (Sender));
if aClient = nil then exit;
aClient.FGraceful := true;
if Assigned (FOnCheckUser) then FOnCheckUser (Self, aUserName, aPassword, Allowed);
if Allowed then
begin
if aVersion < MinVersion then
begin
aClient.Parser.SendConnAck (rcPROTOCOL); // identifier rejected
aClient.Server.Disconnect;
end
else if (length (aClientID) < 1) or (length (aClientID) > 23) then
begin
aClient.Parser.SendConnAck (rcIDENTIFIER); // identifier rejected
aClient.Server.Disconnect;
end
else if GetClient (aClientID) <> nil then
begin
aClient.Parser.SendConnAck (rcIDENTIFIER); // identifier rejected
aClient.Server.Disconnect;
end
else
begin
// mon ('Client ID ' + ClientID + ' User ' + striUserName + ' Pass ' + PassWord);
aClient.Parser.Username := aUserName;
aClient.Parser.Password := aPassword;
aClient.Parser.ClientID := aClientID;
aClient.Parser.KeepAlive := aKeepAlive;
aClient.Parser.Clean := aClean;
Log ('Clean ' + ny[aClean]);
if not aClean then
begin
if Assigned (FOnRestoreSession) then
FOnRestoreSession (aClient, aClientID)
else
Sessions.RestoreSession (aClientID, aClient);
end;
if Assigned (FOnDeleteSession) then
FOnDeleteSession (aClient, aClientID)
else
Sessions.DeleteSession (aClientID);
aClient.Parser.SendConnAck (rcACCEPTED);
aClient.FGraceful := false;
Log ('Accepted. Is Broker ' + ny[aClient.FBroker]);
if Assigned (FOnClientsChange) then FOnClientsChange (Self, Threads.Count);
end;
end
else
begin
aClient.Parser.SendConnAck (rcUSER);
aClient.Server.Disconnect;
end;
end;
procedure TMQTTServer.RxDisconnect (Sender: TObject);
var
aClient : TMQTTThread;
begin
if not (Sender is TMQTTParser) then exit;
aClient := GetClient (TMQTTParser (Sender));
if aClient = nil then exit;
aClient.FGraceful := true;
end;
procedure TMQTTServer.RxHeader (Sender: TObject; MsgType: TMQTTMessageType;
Dup: Boolean; Qos: TMQTTQOSType; Retain: Boolean);
begin
if Assigned (FOnMonHdr) then FOnMonHdr (Self, MsgType, Dup, Qos, Retain);
end;
{ TMQTTClient }
procedure TMQTTClient.Activate (Enable: Boolean);
begin
if Enable = FEnable then exit;
FEnable := Enable;
try
if FState = stConnected then
begin
Parser.SendDisconnect;
FGraceful := true;
Link.Disconnect;
end;
except
end;
if Enable then
SetTimer (1, 100, true)
else
begin
KillTimer (1);
KillTimer (2);
KillTimer (3);
end;
if Assigned (FOnEnableChange) then FOnEnableChange (Self);
end;
constructor TMQTTClient.Create;
var
i : integer;
begin
inherited Create (false);
FreeOnTerminate := true;
Link := TWinsock2TCPClient.Create;
for i := 1 to 3 do
begin
Timers[i].Handle := INVALID_HANDLE_VALUE;
Timers[i].No := i;
Timers[i].Owner := Self;
end;
FEvent := TEvent.Create (nil, true, false, '');
FState := stInit;
FHost := '';
FUsername := '';
FPassword := '';
FPort := 18830;
FEnable := false;
FGraceful := false;
FOnline := false;
FBroker := false; // non standard
FLocalBounce := false;
FAutoSubscribe := false;
FMessageID := 0;
Subscriptions := TStringList.Create;
Releasables := TMQTTMessageStore.Create;
Parser := TMQTTParser.Create;
Parser.OnSend := DoSend;
Parser.OnConnAck := RxConnAck;
Parser.OnPublish := RxPublish;
Parser.OnSubAck := RxSubAck;
Parser.OnUnsubAck := RxUnsubAck;
Parser.OnPubAck := RxPubAck;
Parser.OnPubRel := RxPubRel;
Parser.OnPubRec := RxPubRec;
Parser.OnPubComp := RxPubComp;
Parser.KeepAlive := 10;
InFlight := TMQTTPacketStore.Create;
end;
destructor TMQTTClient.Destroy;
begin
FEvent.SetEvent;
FEvent.Free;
Releasables.Clear;
Releasables.Free;
Subscriptions.Free;
InFlight.Clear;
InFlight.Free;
KillTimer (1);
KillTimer (2);
KillTimer (3);
Link.Free;
Link := nil;
(* try
Link.Close;
finally
Link.Free;
end; *)
Parser.Free;
inherited;
end;
procedure TMQTTClient.RxConnAck (Sender: TObject; aCode: byte);
var
i : integer;
x : cardinal;
begin
Log ('Connection ' + codenames (aCode));
if aCode = rcACCEPTED then
begin
FOnline := true;
FGraceful := false;
SetTimer (3, 100, true); // start retry counters
if Assigned (FOnOnline) then FOnOnline (Self);
if (FAutoSubscribe) and (Subscriptions.Count > 0) then
begin
for i := 0 to Subscriptions.Count - 1 do
begin
x := cardinal (Subscriptions.Objects[i]) and $03;
Parser.SendSubscribe (NextMessageID, UTF8String (Subscriptions[i]), TMQTTQOSType (x));
end;
end;
end
else
Activate (false); // not going to connect
end;
// publishing
procedure TMQTTClient.RxPublish (Sender: TObject; anID: Word; aTopic : UTF8String;
aMessage : string);
var
aMsg : TMQTTMessage;
begin
case Parser.RxQos of
qtAT_MOST_ONCE :
if Assigned (FOnMsg) then FOnMsg (Self, aTopic, aMessage, Parser.RxQos, Parser.RxRetain);
qtAT_LEAST_ONCE :
begin
Parser.SendPubAck (anID);
if Assigned (FOnMsg) then FOnMsg (Self, aTopic, aMessage, Parser.RxQos, Parser.RxRetain);
end;
qtEXACTLY_ONCE :
begin
Parser.SendPubRec (anID);
aMsg := Releasables.GetMsg (anID);
if aMsg = nil then
begin
Releasables.AddMsg (anID, aTopic, aMessage, Parser.RxQos, 0, 0, Parser.RxRetain);
Log ('Message ' + IntToStr (anID) + ' stored and idle.');
end
else
Log ('Message ' + IntToStr (anID) + ' already stored.');
end;
end;
end;
procedure TMQTTClient.RxPubAck (Sender: TObject; anID: Word);
begin
InFlight.DelPacket (anID);
Log ('ACK Message ' + IntToStr (anID) + ' disposed of.');
end;
procedure TMQTTClient.RxPubComp (Sender: TObject; anID: Word);
begin
InFlight.DelPacket (anID);
Log ('COMP Message ' + IntToStr (anID) + ' disposed of.');
end;
procedure TMQTTClient.RxPubRec (Sender: TObject; anID: Word);
var
aPacket : TMQTTPacket;
begin
aPacket := InFlight.GetPacket (anID);
if aPacket <> nil then
begin
aPacket.Counter := Parser.RetryTime;
if aPacket.Publishing then
begin
aPacket.Publishing := false;
Log ('REC Message ' + IntToStr (anID) + ' recorded.');
end
else
Log ('REC Message ' + IntToStr (anID) + ' already recorded.');
end
else
Log ('REC Message ' + IntToStr (anID) + ' not found.');
Parser.SendPubRel (anID);
end;
procedure TMQTTClient.RxPubRel (Sender: TObject; anID: Word);
var
aMsg : TMQTTMessage;
begin
aMsg := Releasables.GetMsg (anID);
if aMsg <> nil then
begin
Log ('REL Message ' + IntToStr (anID) + ' publishing @ ' + QOSNames[aMsg.Qos]);
if Assigned (FOnMsg) then FOnMsg (Self, aMsg.Topic, aMsg.Message, aMsg.Qos, aMsg.Retained);
Releasables.Remove (aMsg);
aMsg.Free;
Log ('REL Message ' + IntToStr (anID) + ' removed from storage.');
end
else
Log ('REL Message ' + IntToStr (anID) + ' has been already removed from storage.');
Parser.SendPubComp (anID);
end;
procedure TMQTTClient.SetClean (const Value: Boolean);
begin
Parser.Clean := Value;
end;
procedure TMQTTClient.SetClientID (const Value: UTF8String);
begin
Parser.ClientID := Value;
end;
procedure TMQTTClient.SetKeepAlive (const Value: Word);
begin
Parser.KeepAlive := Value;
end;
procedure TMQTTClient.SetMaxRetries (const Value: integer);
begin
Parser.MaxRetries := Value;
end;
procedure TMQTTClient.SetPassword (const Value: UTF8String);
begin
Parser.Password := Value;
end;
procedure TMQTTClient.SetRetryTime (const Value: cardinal);
begin
Parser.RetryTime := Value;
end;
procedure TMQTTClient.SetUsername (const Value: UTF8String);
begin
Parser.UserName := Value;
end;
procedure TMQTTClient.SetState (NewState: integer);
var
aClientID : UTF8String;
function TimeString : UTF8string;
begin // 86400 secs
Result := UTF8String (IntToHex (Trunc (Date), 5) + IntToHex (Trunc (Frac (Time) * 864000), 7));
end;
begin
if (FState <> NewState) then
begin
Log (StateToStr (FState) + ' to ' + StateToStr (NewState) + '.');
FState := NewState;
case NewState of
stClosed :
begin
KillTimer (2);
KillTimer (3);
if Assigned (FOnOffline) and (FOnline) then FOnOffline (Self, FGraceful);
FOnline := false;
if FEnable then SetTimer (1, 6000, true);
end;
stConnected :
begin
FGraceful := false; // still haven't connected but expect to
Parser.Reset;
// mon ('Time String : ' + Timestring);
//= mon ('xaddr ' + Link.GetXAddr);
aClientID := ClientID;
if aClientID = '' then
aClientID := 'CID' + UTF8String (Link.RemotePort.ToString); // + TimeString;
if Assigned (FOnClientID) then FOnClientID (Self, aClientID);
ClientID := aClientID;
if Parser.Clean then
begin
InFlight.Clear;
Releasables.Clear;
end;
if FBroker then
Parser.SendBrokerConnect (aClientID, Parser.UserName, Parser.Password, KeepAlive, Parser.Clean)
else
Parser.SendConnect (aClientID, Parser.UserName, Parser.Password, KeepAlive, Parser.Clean);
end;
end; // connected
end; // case
if not (FState in [stClosed]) then FEvent.SetEvent;
end;
procedure ClientTimerTask (Data : Pointer);
var
i : integer;
bPacket : TMQTTPacket;
aClient : TMQTTClient;
WillClose : Boolean;
begin
with PTimerRec (Data)^ do
begin
aClient := TMQTTClient (Owner);
// log ('Client timer ' + No.ToString + ' triggered');
aClient.KillTimer (No);
case No of
1 : if aClient.FState in [stClosed, stInit] then aClient.SetState (stConnecting);
2 : aClient.Ping;
3 : begin // send duplicates
for i := aClient.InFlight.Count - 1 downto 0 do
begin
bPacket := aClient.InFlight.List[i];
if bPacket.Counter > 0 then
begin
bPacket.Counter := bPacket.Counter - 1;
if bPacket.Counter = 0 then
begin
bPacket.Retries := bPacket.Retries + 1;
if bPacket.Retries <= aClient.MaxRetries then
begin
if bPacket.Publishing then
begin
aClient.InFlight.List.Remove (bPacket);
Log ('Message ' + IntToStr (bPacket.ID) + ' disposed of..');
Log ('Re-issuing Message ' + inttostr (bPacket.ID) + ' Retry ' + inttostr (bPacket.Retries));
SetDup (bPacket.Msg, true);
aClient.DoSend (aClient.Parser, bPacket.ID, bPacket.Retries, bPacket.Msg);
bPacket.Free;
end
else
begin
Log ('Re-issuing PUBREL Message ' + inttostr (bPacket.ID) + ' Retry ' + inttostr (bPacket.Retries));
aClient.Parser.SendPubRel (bPacket.ID, true);
bPacket.Counter := aClient.Parser.RetryTime;
end;
end
else
begin
WillClose := true;
if Assigned (aClient.FOnFailure) then aClient.FOnFailure (aClient, frMAXRETRIES, WillClose);
// if WillClose then Link.CloseDelayed;
end;
end;
end;
end;
aClient.SetTimer (3, 100, true);
end;
end;
end;
end;
procedure TMQTTClient.SetTimer (No, Interval: LongWord; Once: boolean);
var
Flags : Longword;
begin
if not (No in [1 .. 3]) then exit;
if Timers[No].Handle <> INVALID_HANDLE_VALUE then TimerDestroy (Timers[No].Handle);
if Once then Flags := TIMER_FLAG_NONE else Flags := TIMER_FLAG_RESCHEDULE;
Timers[No].Handle := TimerCreateEx (Interval, TIMER_STATE_ENABLED, Flags, ClientTimerTask, @Timers[No]);
end;
procedure TMQTTClient.KillTimer (No: Longword);
begin
if not (No in [1 .. 3]) then exit;
if Timers[No].Handle = INVALID_HANDLE_VALUE then exit;
TimerDestroy (Timers[No].Handle);
Timers[No].Handle := INVALID_HANDLE_VALUE;
end;
procedure TMQTTClient.SetWill (aTopic, aMessage : UTF8String; aQos: TMQTTQOSType;
aRetain: Boolean);
begin
Parser.SetWill (aTopic, aMessage, aQos, aRetain);
end;
procedure TMQTTClient.Subscribe (Topics: TStringList);
var
j : integer;
i, x : cardinal;
anID : Word;
found : boolean;
begin
if Topics = nil then exit;
anID := NextMessageID;
for i := 0 to Topics.Count - 1 do
begin
found := false;
// 255 denotes acked
if i > 254 then
x := (cardinal (Topics.Objects[i]) and $03)
else
x := (cardinal (Topics.Objects[i]) and $03) + (anID shl 16) + (i shl 8) ;
for j := 0 to Subscriptions.Count - 1 do
if Subscriptions[j] = Topics[i] then
begin
found := true;
Subscriptions.Objects[j] := TObject (x);
break;
end;
if not found then
Subscriptions.AddObject (Topics[i], TObject (x));
end;
Parser.SendSubscribe (anID, Topics);
end;
procedure TMQTTClient.Subscribe (aTopic: UTF8String; aQos: TMQTTQOSType);
var
i : integer;
x : cardinal;
found : boolean;
anID : Word;
begin
if aTopic = '' then exit;
found := false;
anID := NextMessageID;
x := (ord (aQos) and $ff) + (anID shl 16);
for i := 0 to Subscriptions.Count - 1 do
if Subscriptions[i] = string (aTopic) then
begin
found := true;
Subscriptions.Objects[i] := TObject (x);
break;
end;
if not found then
Subscriptions.AddObject (string (aTopic), TObject (x));
Parser.SendSubscribe (anID, aTopic, aQos);
end;
procedure TMQTTClient.Execute;
var
Buff : array [0..255] of byte;
closed : boolean;
count : integer;
res : boolean;
begin
while not Terminated do
begin
if Link = nil then Terminate;
case FState of
stClosed :
begin
FEvent.ResetEvent;
FEvent.WaitFor (INFINITE); // park thread
end;
stConnecting :
begin
Link.RemotePort := Port;
Link.RemoteAddress := Host;
Log ('Connecting to ' + Host + ' on Port ' + IntToStr (Port));
if Link.Connect then SetState (stConnected) else SetState (stClosed);
end;
stConnected :
begin
count := 0;
closed := false;
res := Link.ReadAvailable (@Buff[0], 256, count, closed);
if res then Parser.Parse (@Buff[0], count);
if not res or closed then SetState (stClosed);
end;
stQuitting : Terminate;
end; // case
end;
end;
procedure TMQTTClient.DoSend (Sender: TObject; anID : Word; aRetry : integer; aStream: TMemoryStream);
var
x : byte;
begin
if (FState = stConnected) and (aStream.Size > 0) then
begin
KillTimer (2); // 75% of keep alive
if KeepAlive > 0 then SetTimer (2, KeepAlive * 750, true);
aStream.Seek (0, soFromBeginning);
x := 0;
aStream.Read (x, 1);
if (TMQTTQOSType ((x and $06) shr 1) in [qtAT_LEAST_ONCE, qtEXACTLY_ONCE]) and
(TMQTTMessageType ((x and $f0) shr 4) in [{mtPUBREL,} mtPUBLISH, mtSUBSCRIBE, mtUNSUBSCRIBE]) and
(anID > 0) then
begin
InFlight.AddPacket (anID, aStream, aRetry, Parser.RetryTime);
Log ('Message ' + IntToStr (anID) + ' created.');
end;
Link.WriteData (aStream.Memory, aStream.Size);
// Sleep (0);
end;
end;
function TMQTTClient.Enabled: boolean;
begin
Result := FEnable;
end;
function TMQTTClient.GetClean: Boolean;
begin
Result := Parser.Clean;
end;
function TMQTTClient.GetClientID: UTF8String;
begin
Result := Parser.ClientID;
end;
function TMQTTClient.GetKeepAlive: Word;
begin
Result := Parser.KeepAlive;
end;
function TMQTTClient.GetMaxRetries: integer;
begin
Result := Parser.MaxRetries;
end;
function TMQTTClient.GetPassword: UTF8String;
begin
Result := Parser.Password;
end;
function TMQTTClient.GetRetryTime: cardinal;
begin
Result := Parser.RetryTime;
end;
function TMQTTClient.GetUsername: UTF8String;
begin
Result := Parser.UserName;
end;
procedure TMQTTClient.RxSubAck (Sender: TObject; anID: Word; Qoss : array of TMQTTQosType);
var
j : integer;
i, x : cardinal;
begin
InFlight.DelPacket (anID);
Log ('Message ' + IntToStr (anID) + ' disposed of.');
for i := low (Qoss) to high (Qoss) do
begin
if i > 254 then break; // only valid for first 254
for j := 0 to Subscriptions.Count - 1 do
begin
x := cardinal (Subscriptions.Objects[j]);
if (High (x) = anID) and ((x and $0000ff00) shr 8 = i) then
Subscriptions.Objects[j] := TObject ($ff00 + ord (Qoss[i]));
end;
end;
end;
procedure TMQTTClient.RxUnsubAck (Sender: TObject; anID: Word);
begin
InFlight.DelPacket (anID);
Log ('Message ' + IntToStr (anID) + ' disposed of.');
end;
function TMQTTClient.NextMessageID: Word;
var
i : integer;
Unused : boolean;
aMsg : TMQTTPacket;
begin
repeat
Unused := true;
FMessageID := FMessageID + 1;
if FMessageID = 0 then FMessageID := 1; // exclude 0
for i := 0 to InFlight.Count - 1 do
begin
aMsg := InFlight.List[i];
if aMsg.ID = FMessageID then
begin
Unused := false;
break;
end;
end;
until Unused;
Result := FMessageID;
end;
function TMQTTClient.Online: boolean;
begin
Result := FOnline;
end;
procedure TMQTTClient.Ping;
begin
Parser.SendPing;
end;
procedure TMQTTClient.Publish (aTopic : UTF8String; aMessage : string; aQos : TMQTTQOSType; aRetain : Boolean);
var
i : integer;
found : boolean;
begin
if FLocalBounce and Assigned (FOnMsg) then
begin
found := false;
for i := 0 to Subscriptions.Count - 1 do
if IsSubscribed (UTF8String (Subscriptions[i]), aTopic) then
begin
found := true;
break;
end;
if found then
begin
Parser.RxQos := aQos;
FOnMsg (Self, aTopic, aMessage, aQos, false);
end;
end;
Parser.SendPublish (NextMessageID, aTopic, aMessage, aQos, false, aRetain);
end;
(*
procedure TMQTTClient.TimerProc (var aMsg: TMessage);
var
i : integer;
bPacket : TMQTTPacket;
WillClose : Boolean;
begin
if aMsg.Msg = WM_TIMER then
begin
KillTimer (Timers, aMsg.WParam);
case aMsg.WParam of
1 : begin
Mon ('Connecting to ' + Host + ' on Port ' + IntToStr (Port));
Link.Addr := Host;
Link.Port := IntToStr (Port);
Link.Proto := 'tcp';
try
Link.Connect;
except
end;
end;
2 : Ping;
3 : begin // send duplicates
for i := InFlight.Count - 1 downto 0 do
begin
bPacket := InFlight.List[i];
if bPacket.Counter > 0 then
begin
bPacket.Counter := bPacket.Counter - 1;
if bPacket.Counter = 0 then
begin
bPacket.Retries := bPacket.Retries + 1;
if bPacket.Retries <= MaxRetries then
begin
if bPacket.Publishing then
begin
InFlight.List.Remove (bPacket);
mon ('Message ' + IntToStr (bPacket.ID) + ' disposed of..');
mon ('Re-issuing Message ' + inttostr (bPacket.ID) + ' Retry ' + inttostr (bPacket.Retries));
SetDup (bPacket.Msg, true);
DoSend (Parser, bPacket.ID, bPacket.Retries, bPacket.Msg);
bPacket.Free;
end
else
begin
mon ('Re-issuing PUBREL Message ' + inttostr (bPacket.ID) + ' Retry ' + inttostr (bPacket.Retries));
Parser.SendPubRel (bPacket.ID, true);
bPacket.Counter := Parser.RetryTime;
end;
end
else
begin
WillClose := true;
if Assigned (FOnFailure) then FOnFailure (Self, frMAXRETRIES, WillClose);
if WillClose then Link.CloseDelayed;
end;
end;
end;
end;
SetTimer (Timers, 3, 100, nil);
end;
end;
end;
end; *)
procedure TMQTTClient.Unsubscribe (Topics: TStringList);
var
i, J : integer;
begin
if Topics = nil then exit;
for i := 0 to Topics.Count - 1 do
begin
for j := Subscriptions.Count - 1 downto 0 do
if Subscriptions[j] = Topics[i] then
begin
Subscriptions.Delete (j);
break;
end;
end;
Parser.SendUnsubscribe (NextMessageID, Topics);
end;
procedure TMQTTClient.Unsubscribe (aTopic: UTF8String);
var
i : integer;
begin
if aTopic = '' then exit;
for i := Subscriptions.Count - 1 downto 0 do
if Subscriptions[i] = string (aTopic) then
begin
Subscriptions.Delete (i);
break;
end;
Parser.SendUnsubscribe (NextMessageID, aTopic);
end;
(*
procedure TMQTTClient.LinkClosed (Sender: TObject; ErrCode: Word);
begin
// Mon ('Link Closed...');
KillTimer (2);
KillTimer (3);
if Assigned (FOnOffline) and (FOnline) then FOnOffline (Self, FGraceful);
FOnline := false;
if FEnable then SetTimer (1, 6000, true);
end; *)
{ TMQTTPacketStore }
function TMQTTPacketStore.AddPacket (anID : Word; aMsg : TMemoryStream; aRetry : cardinal; aCount : cardinal) : TMQTTPacket;
begin
Result := TMQTTPacket.Create;
Result.ID := anID;
Result.Counter := aCount;
Result.Retries := aRetry;
aMsg.Seek (0, soFromBeginning);
Result.Msg.CopyFrom (aMsg, aMsg.Size);
List.Add (Result);
end;
procedure TMQTTPacketStore.Assign (From : TMQTTPacketStore);
var
i : integer;
aPacket, bPacket : TMQTTPacket;
begin
Clear;
for i := 0 to From.Count - 1 do
begin
aPacket := From[i];
bPacket := TMQTTPacket.Create;
bPacket.Assign (aPacket);
List.Add (bPacket);
end;
end;
procedure TMQTTPacketStore.Clear;
var
i : integer;
begin
for i := 0 to List.Count - 1 do
TMQTTPacket (List[i]).Free;
List.Clear;
end;
function TMQTTPacketStore.Count: integer;
begin
Result := List.Count;
end;
constructor TMQTTPacketStore.Create;
begin
Stamp := Now;
List := TList.Create;
end;
procedure TMQTTPacketStore.DelPacket (anID: Word);
var
i : integer;
aPacket : TMQTTPacket;
begin
for i := List.Count - 1 downto 0 do
begin
aPacket := List[i];
if aPacket.ID = anID then
begin
List.Remove (aPacket);
aPacket.Free;
exit;
end;
end;
end;
destructor TMQTTPacketStore.Destroy;
begin
Clear;
List.Free;
inherited;
end;
function TMQTTPacketStore.GetItem (Index: Integer): TMQTTPacket;
begin
if (Index >= 0) and (Index < Count) then
Result := List[Index]
else
Result := nil;
end;
function TMQTTPacketStore.GetPacket (anID: Word): TMQTTPacket;
var
i : integer;
begin
for i := 0 to List.Count - 1 do
begin
Result := List[i];
if Result.ID = anID then exit;
end;
Result := nil;
end;
procedure TMQTTPacketStore.Remove (aPacket : TMQTTPacket);
begin
List.Remove (aPacket);
end;
procedure TMQTTPacketStore.SetItem (Index: Integer; const Value: TMQTTPacket);
begin
if (Index >= 0) and (Index < Count) then
List[Index] := Value;
end;
{ TMQTTPacket }
procedure TMQTTPacket.Assign (From: TMQTTPacket);
begin
ID := From.ID;
Stamp := From.Stamp;
Counter := From.Counter;
Retries := From.Retries;
Msg.Clear;
From.Msg.Seek (0, soFromBeginning);
Msg.CopyFrom (From.Msg, From.Msg.Size);
Publishing := From.Publishing;
end;
constructor TMQTTPacket.Create;
begin
ID := 0;
Stamp := Now;
Publishing := true;
Counter := 0;
Retries := 0;
Msg := TMemoryStream.Create;
end;
destructor TMQTTPacket.Destroy;
begin
Msg.Free;
inherited;
end;
{ TMQTTMessage }
procedure TMQTTMessage.Assign (From: TMQTTMessage);
begin
ID := From.ID;
Stamp := From.Stamp;
LastUsed := From.LastUsed;
Retained := From.Retained;
Counter := From.Counter;
Retries := From.Retries;
Topic := From.Topic;
Message := From.Message;
Qos := From.Qos;
end;
constructor TMQTTMessage.Create;
begin
ID := 0;
Stamp := Now;
LastUsed := Stamp;
Retained := false;
Counter := 0;
Retries := 0;
Qos := qtAT_MOST_ONCE;
Topic := '';
Message := '';
end;
destructor TMQTTMessage.Destroy;
begin
inherited;
end;
{ TMQTTMessageStore }
function TMQTTMessageStore.AddMsg (anID: Word; aTopic : UTF8String; aMessage : AnsiString; aQos : TMQTTQOSType;
aRetry, aCount: cardinal; aRetained : Boolean) : TMQTTMessage;
begin
Result := TMQTTMessage.Create;
Result.ID := anID;
Result.Topic := aTopic;
Result.Message := aMessage;
Result.Qos := aQos;
Result.Counter := aCount;
Result.Retries := aRetry;
Result.Retained := aRetained;
List.Add (Result);
end;
procedure TMQTTMessageStore.Assign (From: TMQTTMessageStore);
var
i : integer;
aMsg, bMsg : TMQTTMessage;
begin
Clear;
for i := 0 to From.Count - 1 do
begin
aMsg := From[i];
bMsg := TMQTTMessage.Create;
bMsg.Assign (aMsg);
List.Add (bMsg);
end;
end;
procedure TMQTTMessageStore.Clear;
var
i : integer;
begin
for i := 0 to List.Count - 1 do
TMQTTMessage (List[i]).Free;
List.Clear;
end;
function TMQTTMessageStore.Count: integer;
begin
Result := List.Count;
end;
constructor TMQTTMessageStore.Create;
begin
Stamp := Now;
List := TList.Create;
end;
procedure TMQTTMessageStore.DelMsg (anID: Word);
var
i : integer;
aMsg : TMQTTMessage;
begin
for i := List.Count - 1 downto 0 do
begin
aMsg := List[i];
if aMsg.ID = anID then
begin
List.Remove (aMsg);
aMsg.Free;
exit;
end;
end;
end;
destructor TMQTTMessageStore.Destroy;
begin
Clear;
List.Free;
inherited;
end;
function TMQTTMessageStore.GetItem (Index: Integer): TMQTTMessage;
begin
if (Index >= 0) and (Index < Count) then
Result := List[Index]
else
Result := nil;
end;
function TMQTTMessageStore.GetMsg (anID: Word): TMQTTMessage;
var
i : integer;
begin
for i := 0 to List.Count - 1 do
begin
Result := List[i];
if Result.ID = anID then exit;
end;
Result := nil;
end;
procedure TMQTTMessageStore.Remove (aMsg: TMQTTMessage);
begin
List.Remove (aMsg);
end;
procedure TMQTTMessageStore.SetItem (Index: Integer; const Value: TMQTTMessage);
begin
if (Index >= 0) and (Index < Count) then
List[Index] := Value;
end;
{ TMQTTSession }
constructor TMQTTSession.Create;
begin
ClientID := '';
Stamp := Now;
InFlight := TMQTTPacketStore.Create;
Releasables := TMQTTMessageStore.Create;
end;
destructor TMQTTSession.Destroy;
begin
InFlight.Clear;
InFlight.Free;
Releasables.Clear;
Releasables.Free;
inherited;
end;
{ TMQTTSessionStore }
procedure TMQTTSessionStore.Clear;
var
i : integer;
begin
for i := 0 to List.Count - 1 do
TMQTTSession (List[i]).Free;
List.Clear;
end;
function TMQTTSessionStore.Count: integer;
begin
Result := List.Count;
end;
constructor TMQTTSessionStore.Create;
begin
Stamp := Now;
List := TList.Create;
end;
procedure TMQTTSessionStore.DeleteSession (ClientID: UTF8String);
var
aSession : TMQTTSession;
begin
aSession := GetSession (ClientID);
if aSession <> nil then
begin
List.Remove (aSession);
aSession.Free;
end;
end;
destructor TMQTTSessionStore.Destroy;
begin
Clear;
List.Free;
inherited;
end;
function TMQTTSessionStore.GetItem (Index: Integer): TMQTTSession;
begin
if (Index >= 0) and (Index < Count) then
Result := List[Index]
else
Result := nil;
end;
function TMQTTSessionStore.GetSession (ClientID: UTF8String): TMQTTSession;
var
i : integer;
begin
for i := 0 to List.Count - 1 do
begin
Result := List[i];
if Result.ClientID = ClientID then exit;
end;
Result := nil;
end;
procedure TMQTTSessionStore.RestoreSession (ClientID: UTF8String;
aClient: TMQTTThread);
var
aSession : TMQTTSession;
begin
aClient.InFlight.Clear;
aClient.Releasables.Clear;
aSession := GetSession (ClientID);
if aSession <> nil then
begin
aClient.InFlight.Assign (aSession.InFlight);
aClient.Releasables.Assign (aSession.Releasables);
end;
end;
procedure TMQTTSessionStore.RestoreSession (ClientID: UTF8String;
aClient: TMQTTClient);
var
aSession : TMQTTSession;
begin
aClient.InFlight.Clear;
aClient.Releasables.Clear;
aSession := GetSession (ClientID);
if aSession <> nil then
begin
aClient.InFlight.Assign (aSession.InFlight);
aClient.Releasables.Assign (aSession.Releasables);
end;
end;
procedure TMQTTSessionStore.StoreSession (ClientID: UTF8String;
aClient: TMQTTClient);
var
aSession : TMQTTSession;
begin
aSession := GetSession (ClientID);
if aSession <> nil then
begin
aSession := TMQTTSession.Create;
aSession.ClientID := ClientID;
List.Add (aSession);
end;
aSession.InFlight.Assign (aClient.InFlight);
aSession.Releasables.Assign (aClient.Releasables);
end;
procedure TMQTTSessionStore.StoreSession (ClientID: UTF8String;
aClient: TMQTTThread);
var
aSession : TMQTTSession;
begin
aClient.InFlight.Clear;
aClient.Releasables.Clear;
aSession := GetSession (ClientID);
if aSession <> nil then
begin
aSession := TMQTTSession.Create;
aSession.ClientID := ClientID;
List.Add (aSession);
end;
aSession.InFlight.Assign (aClient.InFlight);
aSession.Releasables.Assign (aClient.Releasables);
end;
procedure TMQTTSessionStore.SetItem (Index: Integer; const Value: TMQTTSession);
begin
if (Index >= 0) and (Index < Count) then
List[Index] := Value;
end;
end.
|
unit fmEventEditor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls,
System.RegularExpressions, System.DateUtils, ADC.Types;
type
TForm_EventEditor = class(TForm)
DateTimePicker: TDateTimePicker;
Memo_Description: TMemo;
Button_Cancel: TButton;
Button_OK: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Button_OKClick(Sender: TObject);
procedure Button_CancelClick(Sender: TObject);
private
FCallingForm: TForm;
FEvent: TADEvent;
FMode: Byte;
FOnEventChange: TChangeEventProc;
procedure SetCallingForm(const Value: TForm);
procedure ClearTextFields;
procedure SetMode(const Value: Byte);
procedure SetViewMode;
procedure SetEvent(const Value: TADEvent);
public
property CallingForm: TForm write SetCallingForm;
property OnEventChange: TChangeEventProc read FOnEventChange write FOnEventChange;
property Mode: Byte read FMode write SetMode;
property ControlEvent: TADEvent read FEvent write SetEvent;
end;
var
Form_EventEditor: TForm_EventEditor;
implementation
{$R *.dfm}
{ TForm_EventEditor }
procedure TForm_EventEditor.Button_CancelClick(Sender: TObject);
begin
Close;
end;
procedure TForm_EventEditor.Button_OKClick(Sender: TObject);
var
s: string;
begin
s := Memo_Description.Text;
s := TRegEx.Replace(s, '[\r\n]', ' ');
s := TRegEx.Replace(s, '\s{2,}', ' ');
s := Trim(s);
FEvent.Date := DateTimePicker.Date;
FEvent.Description := s;
if Assigned(Self.FOnEventChange)
then Self.FOnEventChange(Self, FMode, FEvent);
Close;
end;
procedure TForm_EventEditor.ClearTextFields;
begin
DateTimePicker.DateTime := DateOf(Now);
Memo_Description.Clear;
end;
procedure TForm_EventEditor.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
SetMode(ADC_EDIT_MODE_CREATE);
FEvent.Clear;
if FCallingForm <> nil then
begin
FCallingForm.Enabled := True;
FCallingForm.Show;
FCallingForm := nil;
end;
end;
procedure TForm_EventEditor.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_ESCAPE: begin
Close;
end;
end;
end;
procedure TForm_EventEditor.SetCallingForm(const Value: TForm);
begin
FCallingForm := Value;
end;
procedure TForm_EventEditor.SetEvent(const Value: TADEvent);
begin
FEvent := Value;
SetMode(FMode);
end;
procedure TForm_EventEditor.SetMode(const Value: Byte);
begin
FMode := Value;
if FMode = ADC_EDIT_MODE_CREATE then ClearTextFields
else begin
DateTimePicker.DateTime := DateOf(FEvent.Date);
Memo_Description.Text := FEvent.Description;
end;
SetViewMode;
end;
procedure TForm_EventEditor.SetViewMode;
var
i: Integer;
ctrl: TControl;
aEdit: Boolean;
begin
aEdit := FMode in[ADC_EDIT_MODE_CREATE, ADC_EDIT_MODE_CHANGE];
for i := 0 to Self.ControlCount - 1 do
begin
ctrl := Self.Controls[i];
if ctrl is TDateTimePicker then
begin
TDateTimePicker(ctrl).Enabled := AEdit;
end;
if ctrl is TEdit then
begin
TEdit(ctrl).ReadOnly := not AEdit;
if AEdit
then TEdit(ctrl).Color := clWindow
else TEdit(ctrl).Color := clBtnFace;
end;
if ctrl is TMemo then
begin
TMemo(ctrl).ReadOnly := not AEdit;
if AEdit
then TMemo(ctrl).Color := clWindow
else TMemo(ctrl).Color := clBtnFace;
end;
end;
case FMode of
ADC_EDIT_MODE_CREATE: Button_OK.Caption := 'Сохранить';
ADC_EDIT_MODE_CHANGE: Button_OK.Caption := 'Сохранить';
ADC_EDIT_MODE_DELETE: Button_OK.Caption := 'Удалить';
end;
end;
end.
|
unit FuncList;
interface
uses
System.Generics.Collections;
type
TTypeDescInf = (tdNone, tdFn, tdProc);
DescInf = record
private
FParams: string;
FInParams: string;
procedure SetParams(const Value: string);
public
fullStr: string;
fn: TTypeDescInf;
Start: string;
Name: string;
Result: string;
CommentRes: string;
DLL: string;
ExtName: string;
Tail: string;
Replacer: string;
procedure Reset;
function TypeStr: string;
function ResStr: string;
property Params: string read FParams write SetParams;
property InParams: string read FInParams;
end;
TDescInfList = TList<DescInf>;
implementation
uses
System.RegularExpressions;
procedure DescInf.Reset;
begin
fullStr := '';
fn := tdNone;
Name := '';
FParams := '';
FInParams := '';
Result := '';
CommentRes := '';
dll := '';
extname := '';
tail := '';
replacer := '';
end;
function DescInf.ResStr: string;
begin
case fn of
tdNone: Result := '';
tdFn: Result := ': ' + self.Result;
tdProc: Result := '';
else Result := '';
end;
end;
procedure DescInf.SetParams(const Value: string);
var
rx: TRegEx;
mc: TMatchCollection;
i: integer;
begin
FParams := Value;
rx := TRegEx.Create('(\w*)[\,\:]', [roIgnoreCase, roMultiLine, roCompiled]);
mc := rx.Matches(FParams);
FInParams := '';
for i := 0 to mc.Count - 1 do
begin
FInParams := FInParams + mc.Item[i].Groups.Item[1].Value;
if i < (mc.Count - 1) then
FInParams := FInParams + ', ';
end;
end;
function DescInf.TypeStr: string;
begin
case fn of
tdNone: Result := '';
tdFn: Result := 'function';
tdProc: Result := 'procedure';
else Result := '';
end;
end;
end.
|
unit lastduel_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,m68000,main_engine,controls_engine,gfx_engine,ym_2203,rom_engine,
pal_engine,sound_engine,timer_engine,oki6295;
function iniciar_lastduel:boolean;
implementation
const
lastduel_rom:array[0..3] of tipo_roms=(
(n:'ldu_06b.13k';l:$20000;p:0;crc:$0e71acaf),(n:'ldu_05b.12k';l:$20000;p:$1;crc:$47a85bea),
(n:'ldu_04b.11k';l:$10000;p:$40000;crc:$aa4bf001),(n:'ldu_03b.9k';l:$10000;p:$40001;crc:$bbaac8ab));
lastduel_sound:tipo_roms=(n:'ld_02.16h';l:$10000;p:0;crc:$91834d0c);
lastduel_char:tipo_roms=(n:'ld_01.12f';l:$8000;p:0;crc:$ad3c6f87);
lastduel_sprites:array[0..3] of tipo_roms=(
(n:'ld-09.12a';l:$20000;p:0;crc:$6efadb74),(n:'ld-10.17a';l:$20000;p:$1;crc:$b8d3b2e3),
(n:'ld-11.12b';l:$20000;p:$2;crc:$49d4dbbd),(n:'ld-12.17b';l:$20000;p:$3;crc:$313e5338));
lastduel_tiles:array[0..1] of tipo_roms=(
(n:'ld-15.6p';l:$20000;p:0;crc:$d977a175),(n:'ld-13.6m';l:$20000;p:$1;crc:$bc25729f));
lastduel_tiles2:tipo_roms=(n:'ld-14.15n';l:$80000;p:0;crc:$d0653739);
lastduel_dip:array [0..10] of def_dip=(
(mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'3'),(dip_val:$2;dip_name:'4'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'6'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Bonus Life';number:4;dip:((dip_val:$c;dip_name:'20K 60K+'),(dip_val:$8;dip_name:'30K 70K+'),(dip_val:$4;dip_name:'40K 80K+'),(dip_val:$0;dip_name:'50K 90K+'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$10;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$10;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$20;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$300;name:'Coin A';number:4;dip:((dip_val:$100;dip_name:'2C 1C'),(dip_val:$300;dip_name:'1C 1C'),(dip_val:$200;dip_name:'1C 2C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c00;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$400;dip_name:'2C 3C'),(dip_val:$c00;dip_name:'1C 3C'),(dip_val:$800;dip_name:'1C 6C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$1000;name:'Difficulty';number:2;dip:((dip_val:$1000;dip_name:'Easy'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2000;name:'Flip Screen';number:2;dip:((dip_val:$2000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4000;name:'Complete Invulnerability';number:2;dip:((dip_val:$4000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8000;name:'Base Ship Invulnerability';number:2;dip:((dip_val:$8000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
madgear_rom:array[0..3] of tipo_roms=(
(n:'mg_04.8b';l:$20000;p:0;crc:$b112257d),(n:'mg_03.7b';l:$20000;p:$1;crc:$b2672465),
(n:'mg_02.6b';l:$20000;p:$40000;crc:$9f5ebe16),(n:'mg_01.5b';l:$20000;p:$40001;crc:$1cea2af0));
madgear_sound:tipo_roms=(n:'mg_05.14j';l:$10000;p:0;crc:$2fbfc945);
madgear_char:tipo_roms=(n:'mg_06.10k';l:$8000;p:0;crc:$382ee59b);
madgear_sprites:array[0..7] of tipo_roms=(
(n:'mg_m11.rom0';l:$10000;p:$2;crc:$ee319a64),(n:'mg_m07.rom2';l:$10000;p:$40002;crc:$e5c0b211),
(n:'mg_m12.rom1';l:$10000;p:$0;crc:$887ef120),(n:'mg_m08.rom3';l:$10000;p:$40000;crc:$59709aa3),
(n:'mg_m13.rom0';l:$10000;p:$3;crc:$eae07db4),(n:'mg_m09.rom2';l:$10000;p:$40003;crc:$40ee83eb),
(n:'mg_m14.rom1';l:$10000;p:$1;crc:$21e5424c),(n:'mg_m10.rom3';l:$10000;p:$40001;crc:$b64afb54));
madgear_tiles:tipo_roms=(n:'ls-12.7l';l:$40000;p:0;crc:$6c1b2c6c);
madgear_tiles2:tipo_roms=(n:'ls-11.2l';l:$80000;p:0;crc:$6bf81c64);
madgear_oki:array[0..1] of tipo_roms=(
(n:'ls-06.10e';l:$20000;p:0;crc:$88d39a5b),(n:'ls-05.12e';l:$20000;p:$20000;crc:$b06e03b5));
leds2011_rom:array[0..3] of tipo_roms=(
(n:'lse_04.8b';l:$20000;p:0;crc:$166c0576),(n:'lse_03.7b';l:$20000;p:$1;crc:$0c8647b6),
(n:'ls-02.6b';l:$20000;p:$40000;crc:$05c0285e),(n:'ls-01.5b';l:$20000;p:$40001;crc:$8bf934dd));
leds2011_sound:tipo_roms=(n:'ls-07.14j';l:$10000;p:0;crc:$98af7838);
leds2011_char:tipo_roms=(n:'ls-08.10k';l:$8000;p:0;crc:$8803cf49);
leds2011_sprites:array[0..1] of tipo_roms=(
(n:'ls-10.13a';l:$40000;p:$0;crc:$db2c5883),(n:'ls-09.5a';l:$40000;p:$1;crc:$89949efb));
leds2011_tiles:tipo_roms=(n:'ls-12.7l';l:$40000;p:0;crc:$6c1b2c6c);
leds2011_tiles2:tipo_roms=(n:'ls-11.2l';l:$80000;p:0;crc:$6bf81c64);
leds2011_oki:array[0..1] of tipo_roms=(
(n:'ls-06.10e';l:$20000;p:0;crc:$88d39a5b),(n:'ls-05.12e';l:$20000;p:$20000;crc:$b06e03b5));
var
lastduel_hw_update_video,lastduel_event:procedure;
scroll_x0,scroll_y0,scroll_x1,scroll_y1:word;
rom:array[0..$3ffff] of word;
ram:array[0..$ffff] of word;
ram_txt:array[0..$fff] of word;
ram_video:array[0..$5fff] of word;
sprite_ram:array[0..$3ff] of word;
sound_rom:array[0..1,0..$3fff] of byte;
sprite_x_mask,sound_bank,video_pri,sound_latch:byte;
procedure draw_sprites(pri:byte);
var
atrib,color,nchar,x,y,f:word;
flip_x,flip_y:boolean;
begin
for f:=$fe downto 0 do begin
atrib:=buffer_sprites_w[(f*4)+1];
if pri=((atrib and $10) shr 4) then continue;
nchar:=buffer_sprites_w[f*4] and $fff;
y:=buffer_sprites_w[(f*4)+3] and $1ff;
x:=buffer_sprites_w[(f*4)+2] and $1ff;
flip_x:=(atrib and sprite_x_mask)<>0;
flip_y:=(atrib and $20)<>0;
color:=(atrib and $f) shl 4;
put_gfx_sprite(nchar,color+$200,flip_x,flip_y,3);
actualiza_gfx_sprite(x,496-y,5,3);
end;
end;
procedure update_video_lastduel;
var
f,color,x,y,nchar,atrib:word;
begin
for f:=$0 to $fff do begin
//bg
atrib:=ram_video[$2001+(f*2)];
color:=atrib and $f;
if (gfx[1].buffer[f+$1000] or buffer_color[color+$10]) then begin
x:=f div 64;
y:=63-(f mod 64);
nchar:=(ram_video[$2000+(f*2)]) and $7ff;
put_gfx_flip(x*16,y*16,nchar,color shl 4,2,1,(atrib and $40)<>0,(atrib and $20)<>0);
gfx[1].buffer[f+$1000]:=false;
end;
//fg
atrib:=ram_video[$1+(f*2)];
color:=atrib and $f;
if (gfx[1].buffer[f] or buffer_color[color+$20]) then begin
x:=f div 64;
y:=63-(f mod 64);
nchar:=(ram_video[f*2]) and $fff;
put_gfx_trans_flip(x*16,y*16,nchar,(color shl 4)+$100,3,2,(atrib and $40)<>0,(atrib and $20)<>0);
if (atrib and $80)<>0 then put_gfx_trans_flip_alt(x*16,y*16,nchar,(color shl 4)+$100,4,2,(atrib and $40)<>0,(atrib and $20)<>0,0)
else put_gfx_block_trans(x*16,y*16,4,16,16);
gfx[1].buffer[f]:=false;
end;
end;
for f:=$0 to $7ff do begin
atrib:=ram_txt[f];
color:=atrib shr 12;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
x:=f div 64;
y:=63-(f mod 64);
nchar:=atrib and $7ff;
put_gfx_trans_flip(x*8,y*8,nchar,(color shl 2)+$300,1,0,(atrib and $800)<>0,false);
gfx[0].buffer[f]:=false;
end;
end;
scroll_x_y(2,5,scroll_x1,scroll_y1);
scroll_x_y(3,5,scroll_x0,scroll_y0);
draw_sprites(2); //Todos los sprites
scroll_x_y(4,5,scroll_x0,scroll_y0);
actualiza_trozo(0,0,256,512,1,0,0,256,512,5);
actualiza_trozo_final(8,64,240,384,5);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
m68000_0.irq[2]:=HOLD_LINE;
end;
procedure update_video_madgear;
var
f,color,x,y,nchar,atrib:word;
begin
for f:=$0 to $7ff do begin
//bg
atrib:=ram_video[$2800+f];
color:=atrib and $f;
if (gfx[1].buffer[f+$1000] or buffer_color[color+$10]) then begin
x:=f mod 32;
y:=63-(f div 32);
nchar:=(ram_video[$2000+f]) and $7ff;
put_gfx_trans_flip(x*16,y*16,nchar,color shl 4,2,1,(atrib and $40)<>0,(atrib and $20)<>0);
gfx[1].buffer[f+$1000]:=false;
end;
//fg
atrib:=ram_video[f+$800];
color:=atrib and $f;
if (gfx[1].buffer[f] or buffer_color[color+$20]) then begin
x:=f mod 32;
y:=63-(f div 32);
nchar:=(ram_video[f]) and $fff;
put_gfx_trans_flip(x*16,y*16,nchar,(color shl 4)+$100,3,2,(atrib and $40)<>0,(atrib and $20)<>0);
if (atrib and $10)<>0 then put_gfx_trans_flip_alt(x*16,y*16,nchar,(color shl 4)+$100,4,2,(atrib and $40)<>0,(atrib and $20)<>0,0)
else put_gfx_block_trans(x*16,y*16,4,16,16);
gfx[1].buffer[f]:=false;
end;
atrib:=ram_txt[f];
color:=atrib shr 12;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
x:=f div 64;
y:=63-(f mod 64);
nchar:=atrib and $7ff;
put_gfx_trans_flip(x*8,y*8,nchar,(color shl 2)+$300,1,0,(atrib and $800)<>0,false);
gfx[0].buffer[f]:=false;
end;
end;
fill_full_screen(5,$400);
if video_pri<>0 then begin
scroll_x_y(3,5,scroll_x0,scroll_y0);
draw_sprites(0);
scroll_x_y(4,5,scroll_x0,scroll_y0);
scroll_x_y(2,5,scroll_x1,scroll_y1);
draw_sprites(1);
end else begin
scroll_x_y(2,5,scroll_x1,scroll_y1);
scroll_x_y(3,5,scroll_x0,scroll_y0);
draw_sprites(0);
scroll_x_y(4,5,scroll_x0,scroll_y0);
draw_sprites(1);
end;
actualiza_trozo(0,0,256,512,1,0,0,256,512,5);
actualiza_trozo_final(8,64,240,384,5);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
m68000_0.irq[5]:=HOLD_LINE;
end;
procedure eventos_lastduel;
begin
if event.arcade then begin
//P1+P2
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or 1);
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or 2);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fffb) else marcade.in1:=(marcade.in1 or 4);
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fff7) else marcade.in1:=(marcade.in1 or 8);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $ffdf) else marcade.in1:=(marcade.in1 or $20);
if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $feff) else marcade.in1:=(marcade.in1 or $100);
if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fdff) else marcade.in1:=(marcade.in1 or $200);
if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $fbff) else marcade.in1:=(marcade.in1 or $400);
if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $f7ff) else marcade.in1:=(marcade.in1 or $800);
if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $efff) else marcade.in1:=(marcade.in1 or $1000);
if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $dfff) else marcade.in1:=(marcade.in1 or $2000);
//SYSTEM
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or 1);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or 2);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $ffbf) else marcade.in0:=(marcade.in0 or $40);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $ff7f) else marcade.in0:=(marcade.in0 or $80);
end;
end;
procedure eventos_madgear;
begin
if event.arcade then begin
//P1+P2
if arcade_input.but2[1] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or 2);
if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $fffb) else marcade.in1:=(marcade.in1 or 4);
if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $fff7) else marcade.in1:=(marcade.in1 or 8);
if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $ffdf) else marcade.in1:=(marcade.in1 or $20);
if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $ffbf) else marcade.in1:=(marcade.in1 or $40);
if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $ff7f) else marcade.in1:=(marcade.in1 or $80);
if arcade_input.but2[0] then marcade.in1:=(marcade.in1 and $fdff) else marcade.in1:=(marcade.in1 or $200);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $fbff) else marcade.in1:=(marcade.in1 or $400);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $f7ff) else marcade.in1:=(marcade.in1 or $800);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $efff) else marcade.in1:=(marcade.in1 or $1000);
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $dfff) else marcade.in1:=(marcade.in1 or $2000);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $bfff) else marcade.in1:=(marcade.in1 or $4000);
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $7fff) else marcade.in1:=(marcade.in1 or $8000);
//SYSTEM
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $200);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $400);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $f7ff) else marcade.in0:=(marcade.in0 or $800);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $efff) else marcade.in0:=(marcade.in0 or $1000);
end;
end;
procedure lastduel_principal;
var
frame_m,frame_s:single;
f:byte;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to $ff do begin
//main
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//sound
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
if f=248 then begin
//La IRQ de VBLANK esta en la funcion de video!!
lastduel_hw_update_video;
copymemory(@buffer_sprites_w,@sprite_ram,$400*2);
end;
end;
lastduel_event;
video_sync;
end;
end;
function lastduel_getword(direccion:dword):word;
begin
case direccion of
0..$5ffff:lastduel_getword:=rom[direccion shr 1];
$fc0800..$fc0fff:lastduel_getword:=sprite_ram[(direccion and $7ff) shr 1];
$fc4000:lastduel_getword:=marcade.in1; //P1_P2
$fc4002:lastduel_getword:=marcade.in0; //SYSTEM
$fc4004:lastduel_getword:=$ffff; //DSW1
$fc4006:lastduel_getword:=$ff; //DSW2
$fcc000..$fcdfff:lastduel_getword:=ram_txt[(direccion and $1fff) shr 1];
$fd8000..$fd87ff:lastduel_getword:=buffer_paleta[(direccion and $7ff) shr 1];
$fd0000..$fd7fff:lastduel_getword:=ram_video[(direccion and $7fff) shr 1];
$fe0000..$ffffff:lastduel_getword:=ram[(direccion and $1ffff) shr 1];
end;
end;
procedure cambiar_color(dir:word);
var
col_val:word;
bright:byte;
color:tcolor;
begin
col_val:=buffer_paleta[dir];
bright:=$10+(col_val and $f);
color.r:=((col_val shr 12) and $f)*bright*$11 div $1f;
color.g:=((col_val shr 8) and $f)*bright*$11 div $1f;
color.b:=((col_val shr 4) and $f)*bright*$11 div $1f;
set_pal_color(color,dir);
case dir of
$0..$ff:buffer_color[(dir shr 4)+$10]:=true;
$100..$1ff:buffer_color[((dir shr 4) and $f)+$20]:=true;
$300..$33f:buffer_color[(dir shr 2) and $f]:=true;
end;
end;
procedure lastduel_putword(direccion:dword;valor:word);
begin
case direccion of
0..$5ffff:;
$fc0800..$fc0fff:sprite_ram[(direccion and $7ff) shr 1]:=valor;
$fc4000:; //flipscreen
$fc4002:sound_latch:=valor and $ff;
$fc8000:scroll_x0:=valor and $3ff;
$fc8002:scroll_y0:=(512-valor) and $3ff;
$fc8004:scroll_x1:=valor and $3ff;
$fc8006:scroll_y1:=(512-valor) and $3ff;
$fcc000..$fcdfff:if ram_txt[(direccion and $1fff) shr 1]<>valor then begin
ram_txt[(direccion and $1fff) shr 1]:=valor;
gfx[0].buffer[(direccion and $1fff) shr 1]:=true;
end;
$fd0000..$fd7fff:if ram_video[(direccion and $7fff) shr 1]<>valor then begin
ram_video[(direccion and $7fff) shr 1]:=valor;
gfx[1].buffer[(direccion and $7fff) shr 2]:=true;
end;
$fd8000..$fd87ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin
buffer_paleta[(direccion and $7ff) shr 1]:=valor;
cambiar_color((direccion and $7ff) shr 1);
end;
$fe0000..$ffffff:ram[(direccion and $1ffff) shr 1]:=valor;
end;
end;
function lastduel_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$e7ff:lastduel_snd_getbyte:=mem_snd[direccion];
$e800:lastduel_snd_getbyte:=ym2203_0.status;
$f000:lastduel_snd_getbyte:=ym2203_1.status;
$f800:lastduel_snd_getbyte:=sound_latch;
end;
end;
procedure lastduel_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$dfff:;
$e000..$e7ff:mem_snd[direccion]:=valor;
$e800:ym2203_0.Control(valor);
$e801:ym2203_0.write(valor);
$f000:ym2203_1.Control(valor);
$f001:ym2203_1.write(valor);
end;
end;
procedure lastduel_sound_update;
begin
ym2203_0.update;
ym2203_1.update;
end;
procedure lastduel_snd_timer;
begin
m68000_0.irq[4]:=HOLD_LINE;
end;
procedure snd_irq(irqstate:byte);
begin
z80_0.change_irq(irqstate);
end;
function madgear_getword(direccion:dword):word;
begin
case direccion of
0..$7ffff:madgear_getword:=rom[direccion shr 1];
$fc1800..$fc1fff:madgear_getword:=sprite_ram[(direccion and $7ff) shr 1];
$fc4000:madgear_getword:=$ffff; //DSW1
$fc4002:madgear_getword:=$ff; //DSW2
$fc4004:madgear_getword:=marcade.in1; //P1_P2
$fc4006:madgear_getword:=marcade.in0; //SYSTEM
$fc8000..$fc9fff:madgear_getword:=ram_txt[(direccion and $1fff) shr 1];
$fcc000..$fcc7ff:madgear_getword:=buffer_paleta[(direccion and $7ff) shr 1];
$fd4000..$fdffff:madgear_getword:=ram_video[(direccion-$fd4000) shr 1];
$ff0000..$ffffff:madgear_getword:=ram[(direccion and $ffff) shr 1];
end;
end;
procedure madgear_putword(direccion:dword;valor:word);
var
tempw:word;
begin
case direccion of
0..$7ffff:;
$fc1800..$fc1fff:sprite_ram[(direccion and $7ff) shr 1]:=valor;
$fc4000:; //flipscreen
$fc4002:sound_latch:=valor and $ff;
$fd0000:scroll_x0:=valor and $3ff;
$fd0002:scroll_y0:=(512-valor) and $3ff;
$fd0004:scroll_x1:=valor and $3ff;
$fd0006:scroll_y1:=(512-valor) and $3ff;
$fd000e:video_pri:=valor;
$fc8000..$fc9fff:if ram_txt[(direccion and $1fff) shr 1]<>valor then begin
ram_txt[(direccion and $1fff) shr 1]:=valor;
gfx[0].buffer[(direccion and $1fff) shr 1]:=true;
end;
$fcc000..$fcc7ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin
buffer_paleta[(direccion and $7ff) shr 1]:=valor;
cambiar_color((direccion and $7ff) shr 1);
end;
$fd4000..$fdffff:if ram_video[(direccion-$fd4000) shr 1]<>valor then begin
tempw:=(direccion-$fd4000) shr 1;
ram_video[tempw]:=valor;
case tempw of
0..$7ff:gfx[1].buffer[tempw]:=true;
$800..$fff:gfx[1].buffer[tempw-$800]:=true;
$2000..$27ff:gfx[1].buffer[tempw-$1000]:=true;
$2800..$2fff:gfx[1].buffer[tempw-$1800]:=true;
end;
end;
$ff0000..$ffffff:ram[(direccion and $ffff) shr 1]:=valor;
end;
end;
function madgear_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$7fff,$d000..$d7ff:madgear_snd_getbyte:=mem_snd[direccion];
$8000..$cfff:madgear_snd_getbyte:=sound_rom[sound_bank,direccion and $3fff];
$f000:madgear_snd_getbyte:=ym2203_0.status;
$f002:madgear_snd_getbyte:=ym2203_1.status;
$f006:madgear_snd_getbyte:=sound_latch;
end;
end;
procedure madgear_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$cfff:;
$d000..$d7ff:mem_snd[direccion]:=valor;
$f000:ym2203_0.Control(valor);
$f001:ym2203_0.write(valor);
$f002:ym2203_1.Control(valor);
$f003:ym2203_1.write(valor);
$f004:oki_6295_0.write(valor);
$f00a:sound_bank:=valor and 1;
end;
end;
procedure madgear_sound_update;
begin
ym2203_0.update;
ym2203_1.update;
oki_6295_0.update;
end;
procedure madgear_snd_timer;
begin
m68000_0.irq[6]:=HOLD_LINE;
end;
//Main
procedure reset_lastduel;
begin
m68000_0.reset;
z80_0.reset;
ym2203_0.reset;
ym2203_1.reset;
if main_vars.tipo_maquina<>268 then oki_6295_0.reset;
reset_audio;
marcade.in0:=$ffff;
marcade.in1:=$ffff;
scroll_x0:=0;
scroll_y0:=0;
scroll_x1:=0;
scroll_y1:=0;
sound_latch:=0;
video_pri:=0;
sound_bank:=0;
end;
function iniciar_lastduel:boolean;
var
memoria_temp:array[0..$7ffff] of byte;
x_size:word;
f:byte;
const
pc_x:array[0..7] of dword=(0, 1, 2, 3, 4*2+0, 4*2+1, 4*2+2, 4*2+3);
pc_y:array[0..7] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16);
pt_x:array[0..15] of dword=(0, 1, 2, 3, 4*4+0, 4*4+1, 4*4+2, 4*4+3,
(8*4*16)+0,(8*4*16)+1,(8*4*16)+2,(8*4*16)+3,8*4*16+4*4+0,8*4*16+4*4+1,8*4*16+4*4+2,8*4*16+4*4+3);
pt_y:array[0..15] of dword=(0*8*4, 1*8*4, 2*8*4, 3*8*4, 4*8*4, 5*8*4, 6*8*4, 7*8*4,
8*8*4,9*8*4,10*8*4,11*8*4,12*8*4,13*8*4,14*8*4,15*8*4);
ps_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7,
(8*4*16)+0,(8*4*16)+1,(8*4*16)+2,(8*4*16)+3,(8*4*16)+4,(8*4*16)+5,(8*4*16)+6,(8*4*16)+7);
procedure convert_chars;
begin
init_gfx(0,8,8,$800);
gfx[0].trans[3]:=true;
gfx_set_desc_data(2,0,16*8,4,0);
convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,true);
end;
procedure convert_tiles(g,num:word);
begin
init_gfx(g,16,16,num);
gfx_set_desc_data(4,0,64*16,3*4,2*4,1*4,0*4);
convert_gfx(g,0,@memoria_temp,@pt_x,@pt_y,false,true);
end;
procedure convert_sprites;
begin
init_gfx(3,16,16,$1000);
gfx[3].trans[15]:=true;
gfx_set_desc_data(4,0,128*8,16,0,24,8);
convert_gfx(3,0,@memoria_temp,@ps_x,@pt_y,false,true);
end;
begin
llamadas_maquina.bucle_general:=lastduel_principal;
llamadas_maquina.reset:=reset_lastduel;
iniciar_lastduel:=false;
iniciar_audio(false);
screen_init(1,512,512,true);
if main_vars.tipo_maquina=268 then x_size:=1024
else x_size:=512;
screen_init(2,x_size,1024,true);
screen_mod_scroll(2,x_size,512,x_size-1,1024,512,1023);
screen_init(3,x_size,1024,true);
screen_mod_scroll(3,x_size,512,x_size-1,1024,512,1023);
screen_init(4,x_size,1024,true);
screen_mod_scroll(4,x_size,512,x_size-1,1024,512,1023);
screen_init(5,512,512,false,true);
iniciar_video(240,384);
//Main CPU
m68000_0:=cpu_m68000.create(10000000,256);
//Sound CPU
z80_0:=cpu_z80.create(3579545,256);
case main_vars.tipo_maquina of
268:begin //Last Duel
lastduel_hw_update_video:=update_video_lastduel;
lastduel_event:=eventos_lastduel;
sprite_x_mask:=$40;
//cargar roms
if not(roms_load16w(@rom,lastduel_rom)) then exit;
m68000_0.change_ram16_calls(lastduel_getword,lastduel_putword);
timers.init(m68000_0.numero_cpu,10000000/120,lastduel_snd_timer,nil,true);
//cargar sonido
if not(roms_load(@mem_snd,lastduel_sound)) then exit;
z80_0.change_ram_calls(lastduel_snd_getbyte,lastduel_snd_putbyte);
z80_0.init_sound(lastduel_sound_update);
//convertir chars
if not(roms_load(@memoria_temp,lastduel_char)) then exit;
convert_chars;
if not(roms_load16w(@memoria_temp,lastduel_tiles)) then exit;
convert_tiles(1,$800);
if not(roms_load(@memoria_temp,lastduel_tiles2)) then exit;
convert_tiles(2,$1000);
gfx[2].trans[0]:=true;
for f:=0 to 6 do gfx[2].trans_alt[0,f]:=true;
for f:=12 to 15 do gfx[2].trans_alt[0,f]:=true;
if not(roms_load32b_b(@memoria_temp,lastduel_sprites)) then exit;
convert_sprites;
end;
269:begin //Mad Gear
lastduel_hw_update_video:=update_video_madgear;
lastduel_event:=eventos_madgear;
sprite_x_mask:=$80;
//cargar roms
if not(roms_load16w(@rom,madgear_rom)) then exit;
m68000_0.change_ram16_calls(madgear_getword,madgear_putword);
timers.init(m68000_0.numero_cpu,10000000/120,madgear_snd_timer,nil,true);
//cargar sonido
if not(roms_load(@memoria_temp,madgear_sound)) then exit;
copymemory(@mem_snd[0],@memoria_temp[0],$8000);
copymemory(@sound_rom[0,0],@memoria_temp[$8000],$4000);
copymemory(@sound_rom[1,0],@memoria_temp[$c000],$4000);
z80_0.change_ram_calls(madgear_snd_getbyte,madgear_snd_putbyte);
z80_0.init_sound(madgear_sound_update);
//OKI
oki_6295_0:=snd_okim6295.Create(1000000,OKIM6295_PIN7_HIGH,2);
if not(roms_load(oki_6295_0.get_rom_addr,madgear_oki)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,madgear_char)) then exit;
convert_chars;
if not(roms_load(@memoria_temp,madgear_tiles)) then exit;
convert_tiles(1,$800);
gfx[1].trans[15]:=true;
if not(roms_load_swap_word(@memoria_temp,madgear_tiles2)) then exit;
convert_tiles(2,$1000);
gfx[2].trans[15]:=true;
for f:=0 to 7 do gfx[2].trans_alt[0,f]:=true;
gfx[2].trans_alt[0,15]:=true;
if not(roms_load32b_b(@memoria_temp,madgear_sprites)) then exit;
convert_sprites;
end;
270:begin //Led Storm 2011
lastduel_hw_update_video:=update_video_madgear;
lastduel_event:=eventos_madgear;
sprite_x_mask:=$80;
//cargar roms
if not(roms_load16w(@rom,leds2011_rom)) then exit;
m68000_0.change_ram16_calls(madgear_getword,madgear_putword);
timers.init(m68000_0.numero_cpu,10000000/120,madgear_snd_timer,nil,true);
//cargar sonido
if not(roms_load(@memoria_temp,leds2011_sound)) then exit;
copymemory(@mem_snd[0],@memoria_temp[0],$8000);
copymemory(@sound_rom[0,0],@memoria_temp[$8000],$4000);
copymemory(@sound_rom[1,0],@memoria_temp[$c000],$4000);
z80_0.change_ram_calls(madgear_snd_getbyte,madgear_snd_putbyte);
z80_0.init_sound(madgear_sound_update);
//OKI
oki_6295_0:=snd_okim6295.Create(1000000,OKIM6295_PIN7_HIGH,2);
if not(roms_load(oki_6295_0.get_rom_addr,leds2011_oki)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,leds2011_char)) then exit;
convert_chars;
if not(roms_load(@memoria_temp,leds2011_tiles)) then exit;
convert_tiles(1,$800);
gfx[1].trans[15]:=true;
if not(roms_load_swap_word(@memoria_temp,leds2011_tiles2)) then exit;
convert_tiles(2,$1000);
gfx[2].trans[15]:=true;
for f:=0 to 7 do gfx[2].trans_alt[0,f]:=true;
gfx[2].trans_alt[0,15]:=true;
if not(roms_load16w(@memoria_temp,leds2011_sprites)) then exit;
convert_sprites;
end;
end;
//Sound Chips
ym2203_0:=ym2203_chip.create(3579545);
ym2203_0.change_irq_calls(snd_irq);
ym2203_1:=ym2203_chip.create(3579545);
//final
reset_lastduel;
iniciar_lastduel:=true;
end;
end.
|
unit ExcelUtils;
(*************************************************************
Copyright © 2012 Toby Allen (https://github.com/tobya)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sub-license, 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 every other copyright notice found in this software, and all the attributions in every file, 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 NON-INFRINGEMENT.
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.
****************************************************************)
interface
uses Classes,Sysutils, MainUtils, ResourceUtils, ActiveX, ComObj, WinINet, Variants, Excel_TLB_Constants,StrUtils;
type
TExcelXLSConverter = Class(TDocumentConverter)
Private
ExcelApp : OleVariant;
FExcelVersion : String;
public
constructor Create() ;
function CreateOfficeApp() : boolean; override;
function DestroyOfficeApp() : boolean; override;
function ExecuteConversion(fileToConvert: String; OutputFilename: String; OutputFileFormat : Integer): TConversionInfo; override;
function AvailableFormats() : TStringList; override;
function FormatsExtensions(): TStringList; override;
function OfficeAppVersion() : String; override;
End;
const
xlTypePDF=50000 ;
xlpdf=50000 ;
xlTypeXPS=50001 ;
xlXPS=50001 ;
implementation
function TExcelXLSConverter.AvailableFormats() : TStringList;
begin
Formats := TResourceStrings.Create('EXCELFORMATS');
result := Formats;
end;
{ TWordDocConverter }
constructor TExcelXLSConverter.Create;
begin
inherited;
//setup defaults
InputExtension := '.xls*';
OfficeAppName := 'Excel';
end;
function TExcelXLSConverter.CreateOfficeApp: boolean;
begin
ExcelApp := CreateOleObject('Excel.Application');
// ExcelApp.Visible := false;
result := true;
end;
function TExcelXLSConverter.DestroyOfficeApp: boolean;
begin
if not VarIsEmpty(ExcelApp) then
begin
ExcelApp.Quit;
end;
Result := true;
end;
//Useful Links:
// https://docs.microsoft.com/en-us/office/vba/api/excel.workbooks.open
// https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.exportasfixedformat
function TExcelXLSConverter.ExecuteConversion(fileToConvert: String; OutputFilename: String; OutputFileFormat : Integer): TConversionInfo;
var
NonsensePassword :OleVariant;
FromPage, ToPage : OleVariant;
ExitAction :TExitAction;
begin
//Excel is particuarily sensitive to having \\ at end of filename, eg it won't create file.
//so we remove any double \\
OutputFilename := stringreplace(OutputFilename, '\\', '\', [rfReplaceAll]);
log(OutputFilename, verbose);
ExitAction := aSave;
Result.InputFile := fileToConvert;
Result.Successful := false;
NonsensePassword := 'tfm554!ghAGWRDD';
try
ExcelApp.Workbooks.Open( FileToConvert, //FileName ,
EmptyParam, //UpdateLinks ,
False, //ReadOnly ,
EmptyParam, //Format ,
NonsensePassword //Password ,
);
//WriteResPassword ,
//IgnoreReadOnlyRecommended,
//Origin ,
//Delimiter ,
//Editable ,
//,
//Notify ,
//Converter ,
//AddToMru ,
//Local ,
Except on E : Exception do
begin
// if Error contains EOleException The password is incorrect.
// then it is password protected and should be skipped.
if ContainsStr(E.Message, 'The password you supplied is not correct' ) then
begin
log('Error Occured:' + E.Message + ' ' + E.ClassName, Verbose);
log('SKIPPED - Password Protected:' + fileToConvert, STANDARD);
Result.Successful := false;
Result.Error := 'SKIPPED - Password Protected:';
ExitAction := aExit;
end
else
begin
// fallback error log
logerror(ConvertErrorText(E.ClassName) + ' ' + ConvertErrorText(E.Message));
Result.Successful := false;
Result.OutputFile := '';
Result.Error := E.Message;
ExitAction := aExit;
end;
end;
end;
case exitAction of
aExit: // exit without Closing. (usually because no file is open)
begin
Result.Successful := false;
Result.OutputFile := '';
end;
aClose: // Just Close
begin
ExcelApp.ActiveWorkbook.Close();
end;
aSave: // Go ahead and save
begin
logdebug('PrintFromPage: ' + inttostr(pdfPrintFromPage),debug);
logdebug('PrintFromPage: ' + inttostr(pdfPrintToPage),debug);
//Unlike Word, in Excel you must call a different function to save a pdf and XPS.
if OutputFileFormat = xlTypePDF then
begin
if pdfPrintToPage > 0 then
begin
FromPage := pdfPrintFromPage;
ToPage := pdfPrintToPage;
end else
begin
FromPage := EmptyParam;
ToPage := EmptyParam;
end ;
ExcelApp.Application.DisplayAlerts := False ;
ExcelApp.activeWorkbook.ExportAsFixedFormat(XlFixedFormatType_xlTypePDF,
OutputFilename,
EmptyParam, //Quality
IncludeDocProps, // IncludeDocProperties,
False,// IgnorePrintAreas,
FromPage , // From,
ToPage, // To,
pdfOpenAfterExport, // OpenAfterPublish, (default false);
EmptyParam// FixedFormatExtClassPtr
) ;
ExcelApp.ActiveWorkBook.save;
end
else if OutputFileFormat = xlTypeXPS then
begin
ExcelApp.Application.DisplayAlerts := False ;
ExcelApp.activeWorkbook.ExportAsFixedFormat(XlFixedFormatType_xlTypeXPS, OutputFilename );
ExcelApp.ActiveWorkBook.save;
end
else if OutputFileFormat = xlCSV then
begin
//CSV pops up alert. must be hidden for automation
ExcelApp.Application.DisplayAlerts := False ;
ExcelApp.activeWorkbook.SaveAs( OutputFilename, OutputFileFormat);
ExcelApp.ActiveWorkBook.save;
end
else
begin
//Excel has a tendency to popup alerts so we don't want that.
ExcelApp.Application.DisplayAlerts := False ;
ExcelApp.activeWorkbook.SaveAs( OutputFilename, OutputFileFormat);
ExcelApp.ActiveWorkBook.Save;
end;
Result.Successful := true;
Result.OutputFile := OutputFilename;
ExcelApp.ActiveWorkbook.Close();
end;
end;
end;
function TExcelXLSConverter.FormatsExtensions: TStringList;
var
Extensions : TResourceStrings;
begin
Extensions := TResourceStrings.Create('XLSEXTENSIONS');
result := Extensions;
end;
function TExcelXLSConverter.OfficeAppVersion(): String;
begin
FExcelVersion := ReadOfficeAppVersion;
if FExcelVersion = '' then
begin
CreateOfficeApp();
FExcelVersion := ExcelApp.Version;
WriteOfficeAppVersion(FExcelVersion);
end;
result := FExcelVersion;
end;
end.
|
unit Tab2TableGen;
interface
uses
ddDocument, ddBase,
evTextFormatter
;
type
TddTab2TableGenerator = class(TddDocumentGenerator)
private
FCharPerLine: Integer;
f_TableStarted: Boolean;
procedure CheckPara(Para: TddTextParagraph);
procedure Tab2Table(Para: TddTextParagraph);
procedure AddCell(aWidth: Integer);
procedure AddRow(Duplicate: Boolean = False);
protected
f_Table: TddTable;
f_Formatter : TevTextFormatter;
f_TextGen : TevPlainTextGenerator;
public
procedure Write2Filer; override;
property CharPerLine: Integer read FCharPerLine write FCharPerLine;
end;
implementation
Uses
l3String, l3Base, l3InternalInterfaces, l3Chars,
k2Tags,
RTFTypes
;
const
minBefore = 10;
{ TddTab2TableGenerator }
procedure TddTab2TableGenerator.Write2Filer;
var
i: Integer;
l_A: TddDocumentAtom;
l_Skip: Integer;
begin
f_Formatter:= TevTextFormatter.Create(nil);
try
f_Formatter.CharsInLine:= CharPerLine;
f_Formatter.FormatOrdinalParas:= False;
f_Formatter.CodePage:= cp_OEMLite;
f_TextGen:= TevPlainTextGenerator.Create(nil);
try
f_Formatter.Generator:= f_TextGen;
f_TextGen.Filer:= Filer;
f_Table:= TddTable.Create(nil);
try
AddRow;
f_Formatter.Start;
try
f_Formatter.StartChild(k2_idDocument);
try
l_Skip:= 0;
f_TableStarted:= False;
for i:= 0 to Document.Paragraphs.Hi do
begin
if l_Skip = 0 then
begin
l_A:= TddDocumentAtom(Document.Paragraphs.Items[i]);
if l_A.AtomType = dd_docTextParagraph then
CheckPara(TddTextParagraph(l_A))
else
if l_A.AtomType = dd_docBreak then
l_Skip:= 3;
end
else
Dec(l_Skip);
end; // for i
f_Table.Write2Generator(f_Formatter);
finally
f_Formatter.Finish;
end;
finally
f_Formatter.Finish;
end;
finally
l3Free(f_Table);
end;
finally
l3Free(f_TextGen);
end;
finally
l3Free(f_Formatter);
end;
end;
procedure TddTab2TableGenerator.CheckPara(Para: TddTextParagraph);
var
j: Integer;
begin
if (f_TableStarted and (Para.PAP.TabList.Count > 0)) or ((Para.PAP.TabList.Count > 1) or
((Para.PAP.TabList.Count = 1) and (TddTab(Para.PAP.TabList.Items[0]).TabPos > 500))) then
begin
f_TableStarted:= True;
for j:= 0 to Pred(Para.Text.Len) do
if Para.Text.Ch[j] = #9 then
begin
Tab2Table(Para);
break;
end; //Text.Ch[i] = #9
end
else
begin
Para.Text.Insert(l3PCharLen('>'), 0, 1);
f_Formatter.StartChild(k2_idTextPara);
try
f_Formatter.AddStringAtom(k2_tiText, Para.Text);
finally
f_Formatter.Finish;
end;
end;
end;
procedure TddTab2TableGenerator.Tab2Table(Para: TddTextParagraph);
var
i: Integer;
l_TabIndex: Integer;
l_Text: String;
l_Create: Boolean;
l_Cell, l_PrevCell: TddtableCell;
l_tab, l_PrevTab: TddTab;
function _GetTextSize(aTabIndex: Integer): Integer;
var
IC : Il3InfoCanvas;
l_Seg : TddTextSegment;
begin
IC:= evCrtIC;
with IC.Font do
begin
l_Seg:= Para.AnySegmentByCharIndex(Pred(i));
if (l_Seg = nil) or (l_Seg.CHP.FontName = '') then
begin
Name:= 'Arial';//'Courier New Cyr';
Size:= 8; //CHP.FontSize div 2;
end
else
begin
Name:= l_Seg.CHP.FontName;
Size:= l_Seg.CHP.FontSize div 2;
end;
Result:= IC.TextExtent(l3PCharLen(l_Text)).X;
end; { with IC.Font }
IC:= nil;
end;
function CellOverTab(aTabIndex: Integer): TddTableCell;
var
IC : Il3InfoCanvas;
l_Seg : TddTextSegment;
l_Pos : Integer;
begin
if TddTab(Para.PAP.TabList.Items[aTabIndex]).Kind <> tkLeft then
begin
l_Pos:= _GetTextSize(aTabIndex);
end
else
l_Pos:= TddTab(Para.PAP.TabList.Items[aTabIndex]).TabPos;
Result:= f_Table.LastRow.CellByPos[l_Pos];
end;
begin
l_TabIndex:= 0;
l_Text:= '';
l_Create:= False;
if (Para.PAP.Before <> propUndefined) and (Para.PAP.Before > MinBefore) then
AddRow(True);
AddRow;
l_Create:= f_Table.LastRow.CellCount = 0;
for i:= 0 to Pred(Para.Text.Len) do
begin
if Para.Text.Ch[i] = #9 then
begin
l_PrevCell:= f_Table.LastRow.LastCell;
l_Tab:= TddTab(Para.PAP.TabList.Items[l_TabIndex]);
if l_TabIndex > 0 then
l_PrevTab:= TddTab(Para.PAP.TabList.Items[Pred(l_TabIndex)])
else
l_PrevTab:= nil;
if l_Create{ and (l_Text <> '')} then
begin
if (l_PrevTab <> nil) and (l_PrevTab.Kind <> tkLeft) then
begin
l_prevCell.LastPara.AddText(l_Text);
l_PrevCell.LastPara.PAP.JUST:= justR;
l_Text:= ''
end;
if l_tab.Kind = tkLeft then
begin
AddCell(l_Tab.TabPos);
f_Table.LastRow.LastCell.LastPara.AddText(l_Text);
l_Text:= ''
end
else
begin
if l_PrevTab = nil then
AddCell(_GetTextSize(l_TabIndex))
else
begin
AddCell(l_PrevTab.TabPos + _GetTextSize(l_TabIndex));
f_Table.LastRow.LastCell.LastPara.AddText(l_Text);
l_Text:= ''
end;
AddCell(l_tab.TabPos);
end;
end;
//if l_Text <> '' then
begin
if (l_PrevTab <> nil) and (l_PrevTab.Kind <> tkLeft) then
begin
l_prevCell.LastPara.AddText(l_Text);
l_Text:= ''
end
else
begin
f_Table.LastRow.LastCell.LastPara.AddText(l_Text);
l_Text:= ''
end;
(*
if l_Tab.Kind = tkLeft then
begin
if l_Create then
begin
f_Table.LastRow.LastCell.LastPara.AddText(l_Text);
l_Text:= '';
end
else
begin
l_Cell:= CellOverTab(l_TabIndex);
if l_Cell <> nil then
l_Cell.LastPara.AddText(l_Text);
end
end
else
begin
if l_Create then
begin
if l_PrevCell <> nil then
begin
//l_PrevCell.LastPara.AddText(l_Text);
f_Table.LastRow.LastCell.LastPara.AddText(l_Text);
l_Text:= '';
end;
end
else
begin
l_Cell:= CellOverTab(l_TabIndex);
if l_Cell <> nil then
l_Cell.LastPara.AddText(l_Text);
end;
end;
*)
(*
l_Cell:= CellOverTab(l_TabIndex);
if l_TabIndex > 0 then
l_PrevCell:= CellOverTab(Pred(l_TabIndex))
else
l_PrevCell:= l_Cell;
l_Cell.LastPara.AddText(l_Text);
*)
// l_Text:= '';
end;
Inc(l_TabIndex);
end
else
begin
l_Text:= l_Text + Para.Text.Ch[i];
end;
end; // for i
l_Tab:= TddTab(Para.PAP.TabList.Items[Pred(l_TabIndex)]);
if l_Tab.Kind = tkLeft then
AddCell(l_Tab.TabPos+_GetTextSize(l_TabIndex));
f_Table.LastRow.LastCell.LastPara.AddText(l_Text);
if l_Tab.Kind <> tkLeft then
f_Table.LastRow.LastCell.LastPara.PAP.JUST:= justR;
end;
procedure TddTab2TableGenerator.AddCell(aWidth: Integer);
var
l_R: TddTableRow;
begin
l_R:= f_Table.LastRow;
if l_R <> nil then
begin
l_R.AddCellAndPara;
l_R.LastCellProperty.Width:= aWidth;
end; // l_R <> nil
end;
procedure TddTab2TableGenerator.AddRow(Duplicate: Boolean = False);
var
l_R, l_LR: TddTableRow;
l_C: TddTableCell;
i: Integer;
begin
l_R:= TddTableRow.Create(nil);
try
if Duplicate then
begin
l_LR:= f_Table.LastRow;
if l_LR <> nil then
begin
l_R.TAP:= l_LR.TAP;
for i:= 0 to Pred(l_LR.CellCount) do
l_R.AddCellAndPara;
end; // f_Table.LastRow <> nil
end; // Duplicate
f_Table.AddRow(l_R);
finally
l3Free(l_R);
end;
end;
end.
procedure Tab2Table;
l_TabIndex:= 0;
l_PrevTabLen:= 0;
l_PrevTextLen:= 0;
var
l_SegIndex : Integer;
l_ParaText : Tl3String;
l_CharIndex : Integer;
l_Seg : TddTextSegment;
l_WidthDelta: Integer;
l_Tab, l_NextTab : TddTab;
IC : Il3InfoCanvas;
l_Spec : Boolean;
l_IsCell : Boolean;
procedure MakeColumn(Index: Integer);
var
l_CHP : TddCharacterProperty;
l_IC : Il3InfoCanvas;
l_MinWidth : Longint;
begin
(*
Generator.StartChild(k2_idTableCell);
try
Generator.AddIntegerAtom(k2_tiLeftIndent, 0);
Generator.AddIntegerAtom(k2_tiRightIndent, 0);
if Index <> -1 then
begin
if (l_ParaText.Ch[0] = #9) and (Index > 0) then
l_CHP:= Segments[Pred(Index)].CHP
else
l_CHP:= Segments[Pred(Index)].CHP
end
else
l_CHP:= nil;
l_MinWidth:= 0;
if l_PrevTabLen < 0 then
l_PrevTabLen:= evChar2Inch(l_ParaText.Len+3) - l_PrevTabLen;
if l_Spec then
Generator.AddIntegerAtom(k2_tiWidth, l_Tab.TabPos - l_PrevTabLen)
else
begin
if l_WidthDelta > l_PrevTabLen then
begin
IC:= evCrtIC;
try
with IC.Font do
begin
if (l_CHP = nil) or (l_CHP.FontName = '') then
Name:= 'Courier New Cyr'
else
Name:= l_CHP.FontName;
Size:= l_CHP.FontSize div 2;
l_PrevTabLen:= IC.TextExtent(l3PCharLen(l_ParaText.St+l_Seg.Start,
l_Seg.Stop-l_Seg.Start)).X
+l_WidthDelta+30;
end; // with IC.Font
finally
IC:= nil;
end; // IC
end; //if l_WidthDelta > l_PrevTabLen
Generator.AddIntegerAtom(k2_tiWidth, l3MulDiv(l_PrevTabLen-l_WidthDelta, evInchMul, rtfTwip));
end; // not l_Spec
if (PAP.Before > 0) and (PAP.Before <> propUndefined) then
begin
Generator.StartChild(k2_idTextPara);
Generator.Finish;
end;
Generator.StartChild(k2_idTextPara);
try
Generator.AddIntegerAtom(k2_tiStyle, ev_saNormalTable);
if l_Spec then
Generator.AddIntegerAtom(k2_tiJustification, Ord(ev_itRight));
if l_CHP <> nil then
l_CHP.Write2Generator(Generator);
l_ParaText.DeleteDoubleSpace;
if PAP.TrimText then
l_ParaText.Trim;
Generator.AddStringAtom(k2_tiText, l_ParaText);
finally
Generator.Finish;
end; // k2_idTextPara
{
if PAP.After > 100 then
begin
Generator.StartChild(k2_idTextPara);
Generator.Finish;
end; // PAP.After > 100
}
finally
Generator.Finish;
end;
*)
end; // MakeColumn
var
l_CreateTable: Boolean;
l_TabIndex: Integer;
l_PrevTabLen: Integer;
begin // Tab2Table
l_CreateTable:= f_Table.LastRow = nil;
l_WidthDelta:= 0;
l_Spec:= False;
l_ParaText:= Tl3String.Create(nil);
try
try
l_tab:= TddTab(Para.PAP.TabList.Items[l_TabIndex]);
l_PrevTabLen:= l_Tab.TabPos
except
l_PrevTabLen:= 720;
end; // try..except
if Para.PAP.TabList.Hi > l_TabIndex then
l_NextTab:= TddTab(Para.PAP.TabList.Items[Succ(l_TabIndex)])
else
l_NextTab:= nil;
{ Перебор сегментов и текста, для определения границ ячеек таблицы }
for l_CharIndex:= 0 to Pred(Para.Text.Len) do
begin
if Para.Text.Ch[l_CharIndex] = #9 then
begin
l_Seg:= Para.AnySegmentByCharIndex(l_CharIndex);
l_SegIndex:= Para.SegmentList.IndexOf(l_Seg);
if not l_Spec then
begin
if (l_Tab.Kind <> tkLeft) then // было - = tkRight
begin
l_Spec:= True;
//if l_TabIndex > 0 then
// l_PrevTabLen:= TddTab(Para.PAP.TabList.Items[Pred(l_TabIndex)]).TabPos
//else
begin
IC:= evCrtIC;
with IC.Font do
begin
if (l_Seg = nil) or (l_Seg.CHP.FontName = '') then
begin
Name:= 'Arial';//'Courier New Cyr';
Size:= 8; //CHP.FontSize div 2;
end
else
begin
Name:= l_Seg.CHP.FontName;
Size:= l_Seg.CHP.FontSize div 2;
end;
l_PrevTabLen:= (IC.TextExtent(l_ParaText.AsPCharLen).X+l_WidthDelta);
end; { with IC.Font }
IC:= nil;
end;
end; // (l_Tab.Kind <> tkLeft)
if l_CreateTable then
MakeColumn(l_SegIndex);
l_WidthDelta:= l_PrevTabLen;
l_Spec:= l_Tab.Kind <> tkLeft;//= tkRight;
end
else { l_Spec = True}
begin
if l_CreateTable then
MakeColumn(l_SegIndex);
if l_TabIndex = 0 then
l_WidthDelta:= l_Tab.TabPos-l_PrevTabLen
else
l_WidthDelta:= l_Tab.TabPos;
l3Free(l_ParaText); // - ???
l_ParaText:= Tl3String.Create(nil); // - ????
l_Spec:= False;
Inc(l_TabIndex);
try
l_tab:= TddTab(Para.PAP.TabList.Items[l_TabIndex]);
l_PrevTabLen:= l_Tab.TabPos
except
l_PrevTabLen:= 720;
end; // try..except
//MakeColumn(l_SegIndex); - ???
end; // l_Spec
l3Free(l_ParaText); // ???
l_ParaText:= Tl3String.Create(nil);// ???
l_WidthDelta:= l_PrevTabLen;
if not l_Spec then
begin
Inc(l_TabIndex);
if (l_TabIndex >=0) and (l_TabIndex < Para.PAP.TabList.Count) then
begin
l_tab:= TddTab(Para.PAP.TabList.Items[l_TabIndex]);
l_PrevTabLen:= l_Tab.TabPos;
end
else
l_PrevTabLen:= -l_PrevTabLen;
end; // not l_Spec
end { l_Seg.Ch = #9 }
else
l_ParaText.Append(Text.Ch[l_CharIndex]);
end; // for l_CharIndex
if not l_ParaText.Empty and l_CreateTable then
MakeColumn(SegmentList.Hi);
finally
l3Free(l_ParaText);
end; // l_ParaText
end; // Tab2Table
|
(**********************************************)
(* Sim68k, CSI 2111, November 1999. *)
(* Please identify yourselves here. *)
(**********************************************)
(* Skeleton of the simulator for the Sim68k processor *)
program Sim68k (input, output) ;
uses // Crt,
SimUnit; (* Library containing useful functions/procedures *)
const
(* List of OpCode or OpNames to create *)
iADD = 0; (* Regular binary integer addition *)
iADDQ = 1; (* Quick binary integer addition *)
iSUB = 2; (* Regular binary integer subtraction *)
iSUBQ = 3; (* Quick binary integer subtraction *)
iMULS = 4; (* Signed binary multiplication *)
iDIVS = 5; (* Signed binary division *)
iNEG = 6; (* Signed binary negation *)
iCLR = 7; (* Clear (set to 0) *)
iNOT = 8; (* Logical NOT *)
iAND = 9; (* Logical AND *)
iOR = 10; (* Logical OR *)
iEOR = 11; (* Logical EXCLUSIVE-OR *)
iLSL = 12; (* Logical Shift Left *)
iLSR = 13; (* Logical Shift Right *)
iROL = 14; (* Rotate Left *)
iROR = 15; (* Rotate Right *)
iCMP = 16; (* Compare (to adjust CVNZH according to D - S) *)
iTST = 17; (* Test (to adjust CVNZH according to D) *)
iBRA = 18; (* Unconditional branch to the given address *)
iBVS = 19; (* Branch to the given address if overflow *)
iBEQ = 20; (* Branch to the given address if equal *)
iBCS = 21; (* Branch to the given address if carry *)
iBGE = 22; (* Branch to the given address if greater or equal *)
iBLE = 23; (* Branch to the given address if less or equal *)
iMOVE = 24; (* Regular move *)
iMOVEQ= 25; (* Quick move *)
iEXG = 26; (* Exchange 2 registers *)
iMOVEA= 27; (* Move the given address into A[i] *)
iINP = 28; (* Read from keyboard (input) *)
iDSP = 29; (* Display the name, the source and the contents *)
iDSR = 30; (* Display the contents of the Status bits *)
iHLT = 31; (* HALT *)
(* Types already defined in SimUnit.pas. DO NOT REDEFINE *)
(* bit = boolean; * True = 1, False = 0 *)
(* twobits = 0..3; *)
(* byte = $00..$FF; * $80...$7F, in 2's CF *)
(* word = $0000..$FFFF; * $8000...$7FFF, in 2's CF *)
(* long = $00000000..$FFFFFFFF; * $80000000..$7FFFFFFF, in 2's CF *)
(* Size of Data to manipulate *)
(* byteSize = 0; *)
(* wordSize = 1; *)
(* longSize = 2; *)
type memorySize = $0000..$1000; (* Memory *)
var
program_name: string ;
option: char ; (* Option chosen from the menu by the user *)
Mnemo: array[0..31] of string ; (* Mnemonics *)
memory: array[memorySize] of byte ; (* 4097 bytes of memory *)
(* The CPU's registers *)
PC: word ; (* Program Counter *)
TMPS, TMPD, TMPR: long ; (* Temporary Registers *)
OpCode: word ; (* OPCODE of the current instruction *)
OpAddr1, OpAddr2: word ; (* Operand Addresses *)
C: bit ; (* Status bit Carry *)
V: bit ; (* Status bit Overflow *)
Z: bit ; (* Status bit Zero *)
N: bit ; (* Status bit Negative *)
H: bit ; (* Status bit Halt *)
D: array[0..1] of long ; (* Data Registers *)
A: array[0..1] of word ; (* Address Registers *)
MAR: word ; (* Memory Address Register *)
MDR: long ; (* Memory Data Register *)
RW: bit ; (* Read/Write Bit: READ = True; WRITE = False *)
DS: twobits; (* Twobits Data Size : ByteSize=0, WordSize=1, LongSize=2 *)
(* Procedures and functions to help you manipulate instruction formats *)
(*------------------------------------------------------------------------------------------------------------*)
function FormatF1 (OpName:byte): boolean;
(* Determines the format of the instruction. F1 = true, F2 = false *)
var
check : boolean;
begin
if (OpName = 1) OR (OpName = 3) OR (OpName = 25) OR
((OpName >= 12) AND (OpName <= 15))
then check := false
else check := true ;
FormatF1 := check ;
end;
procedure MnemoInit;
(* Initializes Mnemo with mnemonic codes corresponding to *)
(* each instruction according to OpName (0..31) *)
(* Used by the translation procedure to determine the OpCode. *)
begin
Mnemo[iADD] := 'ADD';
Mnemo[iADDQ] := 'ADDQ';
Mnemo[iSUB] := 'SUB';
Mnemo[iSUBQ] := 'SUBQ';
Mnemo[iMULS] := 'MULS';
Mnemo[iDIVS] := 'DIVS';
Mnemo[iNEG] := 'NEG';
Mnemo[iCLR] := 'CLR';
Mnemo[iNOT] := 'NOT';
Mnemo[iAND] := 'AND';
Mnemo[iOR] := 'OR';
Mnemo[iEOR] := 'EOR';
Mnemo[iLSL] := 'LSL';
Mnemo[iLSR] := 'LSR';
Mnemo[iROL] := 'ROL';
Mnemo[iROR] := 'ROR';
Mnemo[iCMP] := 'CMP';
Mnemo[iTST] := 'TST';
Mnemo[iBRA] := 'BRA';
Mnemo[iBVS] := 'BVS';
Mnemo[iBEQ] := 'BEQ';
Mnemo[iBCS] := 'BCS';
Mnemo[iBGE] := 'BGE';
Mnemo[iBLE] := 'BLE';
Mnemo[iMOVE] := 'MOVE';
Mnemo[iMOVEQ] := 'MOVEQ';
Mnemo[iEXG] := 'EXG';
Mnemo[iMOVEA] := 'MOVEA';
Mnemo[iINP] := 'INP';
Mnemo[iDSP] := 'DSP';
Mnemo[iDSR] := 'DSR';
Mnemo[iHLT] := 'HLT';
end;
(* Procedure Loader, to load machine language programs in memory. *)
(*------------------------------------------------------------------------------------------------------------*)
procedure Loader(name: string);
(* Read into memory a machine language program contained in a file *)
var
address: word;
convertHS : integer ;
first_character, ch, hexc, hexb, hexa: char;
file_68b: text;
hexString: string ; (* Your program in machine language *)
begin
assign(file_68b, name);
reset(file_68b);
address := $0000;
while (not eof(file_68b))
do begin
read(file_68b,first_character);
if first_character = '/' (* Beginning of comment *)
then repeat (* Skip the comment *)
read(file_68b, ch)
until (ch = first_character) or eoln(file_68b);
while (not eoln(file_68b))
do begin
repeat
read(file_68b, hexc);
until hexc = '$' ;
read(file_68b, hexb);
read(file_68b, hexa);
hexString := hexb + hexa ;
(* writeln('Memory[address]: ', Memory[address]) ;
writeln('hexString read: ', hexString) ; *)
convertHS := hex2dec(hexString) ;
(* writeln('convertHS: ', convertHS) ; *)
Memory[address] := convertHS ;
address := address + $0001
end;
readln(file_68b)
end;
writeln ('Program loaded. ', address,' bytes in memory.');
close(file_68b);
end;
(* Procedure Access_Memory, for reading and writing from and to memory. *)
(*------------------------------------------------------------------------------------------------------------*)
procedure Access_Memory;
(* Copies an element (Byte, Word, Long) from memory{\CPU} to CPU{\memory} *)
(* Uses DS (byteSize, wordSize, longSize) and RW (read or write). *)
(* Verifies if we are trying to access an address outside the range *)
(* allowed for addressing [$0000..$1000]. *)
begin
if ( (MAR >= $0000) AND (MAR <= $1000) )
then (* Valid Memory Address. *)
if RW
then begin
(* TRUE = Read = copy an element from memory to CPU *)
case DS of
byteSize:
MDR := memory[MAR];
wordSize:
MDR := memory[MAR] * $100 + memory[MAR+1];
longSize:
MDR := ((memory[MAR] * $1000000) AND $FF000000) OR
((memory[MAR+1] * $10000) AND $00FF0000) OR
((memory[MAR+2] * $100) AND $0000FF00) OR
( memory[MAR+3] AND $000000FF);
end;
end
else begin
(* FALSE = Write = copy an element from the CPU to memory *)
if DS = byteSize
then memory[MAR] := MDR mod $100 (* LSB: 8 last bits *)
else
if DS = wordSize
then
begin (* wordSize *)
memory[MAR] := (MDR div $100) mod $100;
(* MSB: 8 first bits *)
memory[MAR+1] := MDR mod $100;(* LSB: 8 last bits *)
end
else
begin (* longSize *)
memory[MAR] := (MDR SHR 24) AND $000000FF;
(* MSB: 8 first bits *)
memory[MAR+1] := (MDR SHR 16) AND $000000FF;
memory[MAR+2] := (MDR SHR 8) AND $000000FF;
memory[MAR+3] := MDR mod $100
end
end
else (* Invalid Memory Address. *)
begin
writeln('*** ERROR *** AccessMemory uses the invalid address $', Word2Hex(MAR));
writeln('PC Address = ', Word2Hex(PC-2));
H:=True; (* End of simulation...! *)
end;
end;
(* Procedure Controller (simulator) + local procedures and functions *)
(*------------------------------------------------------------------------------------------------------------*)
procedure Controller ;
(* Fetch-Execute Cycle simulated by the simulator *)
var
OpName : Byte;
Size : twobits; (* byteSize/wordSize/longSize *)
NbOper : Byte; (* Number of necessary operands (P+1) *)
M1, N1 ,
M2, N2 ,
Data : Byte;
Sm, Dm, Rm: boolean; (* Most Significant Bits of TMPS, TMPD, and TMPR *)
procedure Init;
(* Initialize the simulator (PC and status bits). *)
begin
PC := $0000;
C := False;
V := False;
Z := False;
N := False;
H := False;
end;
procedure FetchOpCode;
(* Fetch the OpCode from memory *)
begin
RW := true;
DS := wordSize;
MAR := PC;
PC := PC + 2;
Access_Memory;
Opcode := GetWord(MDR, false);
end;
procedure DecodeInstr;
(* Update the fields (OpName, Size, NbOper, M1, N1, M2, N2, Data) *)
(* according to given format. Uses GetBits. *)
begin
(* Fields according to formats available *)
OpName := GetBits(OpCode, 11, 15);
Size := GetBits(OpCode, 9, 10);
NbOper := GetBits(OpCode, 8, 8) + 1;
if (NbOper > 0) then
begin
if not(FormatF1(OpName))
then begin
Data := GetBits(OpCode, 4, 7);
M2 := GetBits(OpCode, 1, 3);
N2 := GetBits(OpCode, 0, 0)
end
else begin
if not(OpName = 30) or not(OpName = 31)
then begin
M1 := GetBits(OpCode, 5, 7);
N1 := GetBits(OpCode, 4, 4);
M2 := GetBits(OpCode, 1, 3);
N2 := GetBits(OpCode, 0, 0);
end
end;
end;
end;
procedure FetchOperands;
(* Fetch the operands, according to their number (NbOper) and *)
(* addressing modes (M1 et M2) *)
begin
if (NbOper > $0)
then begin
(* There are operands *)
if (FormatF1(OpName)) and (M1=$3)
then
(* Fetch the address of first operand (in OpAddr1) *)
begin
RW := True;
DS := wordSize;
MAR := PC;
PC := PC + 2;
Access_Memory;
OpAddr1 := GetWord(MDR, false);
end;
(* Fetch the address of second operand, if F1 and 2 operands. *)
(* 2nd operand of an instruction with format F2 is in OpAddr2 *)
if (M2 = $3)
then
begin
RW := True;
DS := wordSize;
MAR := PC;
Access_Memory;
PC := PC + 2;
OpAddr2 := GetWord(MDR, false);
end;
(* Check invalid number of operands. *)
if (NbOper = 2) and (not(FormatF1(OpName)))
then
begin
write('*** ERROR *** Invalid number of operands for (', Mnemo[Opname]);
writeln(') at address PC = ', Word2Hex(PC-2));
H := true;
end
end
end;
function NOB(Size:twobits):byte;
(* return the "number of bytes" *)
begin
if Size = 2
then NOB := 4
else NOB := Ord(Size)+1;
end;
(******************************************************************************)
(* Since many instructions will make local fetches between temporary registers*)
(* (TMPS,TMPDM TMPR) and the memory or the Dn and An registers it would be *)
(* useful to create procedures to transfer the words/bytes between them. *)
(* Here are 2 suggestions of procedures to do this. *)
(******************************************************************************)
procedure FillTMP(var TmpReg: long; (* Register to modify: TMPS, TMPD or TMPR *)
OpAddrNo: word; (* Address of operand (OpAddr1 or 2), for mode $3 *)
Size: twobits; (* Data Size *)
ModeAdr, (* Required Addressing Mode *)
RegNo: byte); (* Register number for An & Dn *)
(* Transfer data in the required temporary register *)
begin
(* Depends on Addressing Mode *)
case ModeAdr of
$0: (* Data Register Direct *)
begin
TmpReg := D[RegNo];
if (Size = byteSize)
then begin
SetByteL(TmpReg, 1, $00);
SetWord(TmpReg, true, $0000)
end
else
if (Size = wordSize)
then SetWord(TmpReg, true, $0000);
end;
$1: (* Address Register Direct *)
begin
TmpReg := A[RegNo];
end;
$3: (* Relative/Absolute Addressing *)
(* We need to access memory, except for branching and MOVEA. *)
begin
DS := Size;
RW := true;
MAR := OpAddrNo;
Access_Memory;
TmpReg := MDR;
end;
$4: (* Address Register Indirect *)
(* We need to access memory. *)
begin
DS := Size;
RW := true;
MAR := A[RegNo];
Access_Memory;
TmpReg := MDR;
end;
$6: (* Address Register Indirect with Post-Increment *)
(* We need to access memory. *)
begin
DS := Size;
RW := true;
MAR := A[RegNo];
Access_Memory;
TmpReg := MDR;
A[RegNo] := A[RegNo] + NOB(Size);
end;
$7: (* Address Register Indirect with Pre-Decrement *)
(* We need to access memory. *)
begin
A[RegNo] := A[RegNo] - NOB(Size);
DS := Size;
RW := true;
MAR := A[RegNo];
Access_Memory;
TmpReg := MDR;
end;
else begin
(* This error should never occur, but just in case...! *)
write('*** ERROR *** Invalid addressing mode (', ModeAdr);
writeln(') at address PC = ', Word2Hex(PC-2));
H := true;
end
end; (* case *)
end; (* FillTMP *)
procedure SetResult(TmpReg: long; (* Source Register(TMPD...) *)
OpAddrNo: word; (* Operand Address(OpAddr1...) *)
Size: twobits; (* Data Size *)
ModeAdr, (* Required Addressing Mode *)
RegNo: byte); (* Register Number for An & Dn *)
(* Transfer the contents of temporary register to Register or Memory *)
begin
(* Depends on Addressing Mode *)
case ModeAdr of
$0: (* Data Register Direct *)
begin
case Size of
byteSize: SetBitsL(D[RegNo], 0, 7, TmpReg);
wordSize: SetWord(D[RegNo], false, GetWord(TmpReg, false));
longSize: D[RegNo] := TmpReg;
end;
end;
$1: (* Address Register Direct *)
begin
A[RegNo]:= GetWord(TmpReg, false);
end;
$3: (* Relative/Absolute Addressing *)
(* We need to access memory, except for branching and MOVEA. *)
begin
DS := Size;
RW := false;
MAR := OpAddrNo;
MDR := TmpReg;
Access_Memory;
end;
$4: (* Address Register Indirect *)
(* We need to access memory. *)
begin
DS := Size;
RW := false;
MAR := A[RegNo];
MDR := TmpReg;
Access_Memory;
end;
$6: (* Address Register Indirect with Post-Increment *)
(* We need to access memory. *)
(* ATTENTION: for some instructions, the address register *)
(* has already been incremented by FillTMP *)
(* DO NOT increment it a 2nd time here *)
begin
MAR := A[RegNo] - NOB(Size);
DS := Size;
RW := false;
MDR := TmpReg;
Access_Memory;
end;
$7: (* Address Register Indirect with Pre-Decrement *)
(* We need to access memory. *)
(* ATTENTION: for some instructions, the address register *)
(* has already been decremented by FillTMP *)
(* DO NOT decrement it a 2nd time here *)
begin
DS := Size;
RW := false;
MAR := A[RegNo];
MDR := TmpReg;
Access_Memory;
end;
else begin
write('*** ERROR *** Invalid Addressing Mode (', ModeAdr);
writeln(') at address PC = ', Word2Hex(PC-2));
H := true;
end;
end; (* case *)
end; (* SetResult *)
function CheckCond(Cond: boolean; Message: string):boolean;
(* Generic error verification function, with message display, *)
(* if Cond is false, display an error message (including the OpName) *)
(* The Halt Status bit will also be set to false if there is an Error. *)
begin
if Cond
then CheckCond := True
else
begin
writeln('*** ERROR *** ', Message, ' for ',
Mnemo[OpName], ' at address $', Word2Hex(PC-2));
(* Set the H bit to True *)
H := true;
CheckCond := False
end
end;
procedure SetZN(TmpNo:long);
(* Since Status bits Z and N are often set the same way in many *)
(* instructions. A procedure would be useful to do this. *)
begin
(* Set Z *)
case Size of
byteSize: Z := ((GetBits(GetWord(TmpNo, false), 0, 7) OR $00) = $0);
wordSize: Z := ((GetBits(GetWord(TmpNo, false), 0, 15) OR $0000) = $0);
longsize: Z := ((TmpNo OR $00000000) = $0);
end;
(* Set N *)
case Size of
byteSize: N := (GetBits(GetWord(TmpNo, false), 7, 7) = $1);
wordSize: N := (GetBits(GetWord(TmpNo, false), 15, 15) = $1);
longsize: N := (GetBits(GetWord(TmpNo, true), 15, 15) = $1);
end;
end;
procedure SetSmDmRm(TSrc, TDest, TRes: long);
(* The calculations to find V and C are more complex but are simplified *)
(* by the use of Sm, Dm, Rm. It would be a good Idea to make a procedure*)
(* to find these values *)
var
mostSignBit : byte;
begin
case size of
byteSize: mostSignBit := 7;
wordSize: mostSignBit := 15;
longSize: mostSignBit := 31;
end;
Sm := (GetBitsL(TSrc, mostSignBit, mostSignBit) = $1);
Dm := (GetBitsL(TDest, mostSignBit, mostSignBit) = $1);
Rm := (GetBitsL(TRes, mostSignBit, mostSignBit) = $1);
end;
(* The execution of each instruction is done via its micro-program *)
(*-----------------------------------------------------------------------------------------------*)
procedure ExecInstr;
(* Execute the instruction according to opCode. *)
(* Use a CASE structure where each case corresponds to *)
(* an instruction and its micro-program. *)
var
i: byte; (* Counter *)
tmpA: word;
begin
case OpName of
iADD: begin
(* EXAMPLE micro-program according to step 2.4.1 in section 3*)
(* 1. Fill TMPS if necessary *)
FillTMP(TMPS, OpAddr1, Size, M1, N1);
(* 2. Fill TMPD if necessary *)
FillTMP(TMPD, OpAddr2, Size, M2, N2);
(* 3. Compute TMPR using TMPS and TMPD *)
TMPR := TMPS + TMPD;
(* 4. Update status bits HZNVC if necessary *)
SetZN(TMPR);
SetSmDmRm (TMPS, TMPD, TMPR);
V := (Sm AND Dm AND NOT(Rm)) OR (NOT(Sm) AND NOT(Dm) AND Rm);
C := (Sm AND Dm) OR (NOT(Rm) AND Dm) OR (Sm AND NOT(Rm));
(* 5. Store the result in the destination if necessary *)
SetResult(TMPR, OpAddr2, Size, M2, N2);
end;
iADDQ: begin
FillTMP(TMPD, OpAddr2, Size, M2, N2);
TMPS := $0 ;
SetByteL(TMPS, 0, Data) ;
{Sign extension if W or L ??}
TMPR := TMPD + TMPS;
SetZN(TMPR);
SetSmDmRm (TMPS, TMPD, TMPR) ;
V := (Sm and Dm and NOT(Rm)) or (NOT(Sm) and NOT(Dm) and Rm);
C := (Sm and Dm) or (NOT(Rm) and Dm) or (Sm and NOT(Rm));
SetResult(TMPR, OpAddr2, Size, M2, N2);
end;
iSUB: begin
FillTMP(TMPS, OpAddr1, Size, M1, N1);
FillTMP(TMPD, OpAddr2, Size, M2, N2);
TMPR := TMPD - TMPS;
SetZN(TMPR);
SetSmDmRm (TMPS, TMPD, TMPR);
V := (NOT(Sm) and Dm and NOT(Rm)) or (Sm and NOT(Dm) and Rm);
C := (Sm and NOT(Dm)) or (Rm and NOT(Dm)) or (Sm and Rm);
SetResult(TMPR, OpAddr2, Size, M2, N2) ;
end;
iSUBQ: begin
FillTMP(TMPD, OpAddr2, Size, M2, N2);
TMPS := $0;
SetByteL(TMPS, 0, Data);
{Sign extension if W or L ??}
TMPR := TMPD - TMPS;
SetZN(TMPR);
SetSmDmRm (TMPS, TMPD, TMPR);
V := (NOT(Sm) and Dm and NOT(Rm)) or (Sm and NOT(Dm) and Rm);
C := (Sm and NOT(Dm)) or (Rm and NOT(Dm)) or (Sm and Rm);
SetResult(TMPR, OpAddr2, Size, M2, N2);
end;
iMULS: begin
if CheckCond( (Size = wordSize), 'Invalid Data Size' )
then
begin
FillTMP(TMPS, OpAddr1, Size, M1, N1);
FillTMP(TMPD, OpAddr2, Size, M2, N2);
if (GetBitsL(TMPS,15,15) = $1)
then TMPS := TMPS or $FFFF0000;
if (GetBitsL(TMPD,15,15) = $1)
then TMPD := TMPD or $FFFF0000;
TMPR := TMPD * TMPS;
SetZN(TMPR);
V := false;
C := false;
SetResult(TMPR, OpAddr2, longSize, M2, N2);
end { if size = 1 }
end;
iDIVS: begin
if CheckCond( (Size = 2), 'Invalid Data Size' )
then begin
FillTMP(TMPS, OpAddr1, wordSize, M1, N1) ;
if CheckCond( (TMPS <> $0), 'Division by Zero' )
then begin
FillTMP(TMPD, OpAddr2, Size, M2, N2);
V := ((TMPD div TMPS) < -32768) OR ((TMPD div TMPS) > 32767);
if TMPS > $8000 then begin
i := $1;
TMPS := (TMPS xor $FFFF) + 1;
TMPD := (TMPD xor $FFFFFFFF) + 1
end;
if ((TMPD div TMPS) = 0) and (i = $1)
then begin
SetWord(TMPR, false, $0000);
TMPD := (TMPD xor $FFFFFFFF) + 1;
SetWord(TMPR, true, TMPD mod TMPS)
end
else begin
TMPR := TMPD div GetWord(TMPS, false) ;
SetWord(TMPR, true, (TMPD mod GetWord(TMPS, false)))
end;
SetZN(TMPR) ;
C := false ;
SetResult(TMPR, OpAddr2, Size, M2, N2) ;
end { if div by 0 }
end { if size = 2 }
end;
iNEG: begin
FillTMP(TMPD, OpAddr1, Size, M1, N1);
TMPR := - TMPD;
SetZN(TMPR);
SetSmDmRm (TMPS, TMPD, TMPR);
V := Dm and Rm;
C := Dm or Rm;
SetResult(TMPR, OpAddr1, Size, M1, N1);
end;
iCLR: begin
TMPD := $0;
SetZN(TMPD);
V := false;
C := false;
SetResult(TMPD, OpAddr1, Size, M1, N1);
end;
iNOT: begin
FillTMP(TMPD, OpAddr1, Size, M1, N1);
TMPR := not(TMPD);
SetZN(TMPR);
V := false;
C := false;
SetResult(TMPR, OpAddr1, Size, M1, N1);
end;
iAND: begin
FillTMP(TMPS, OpAddr1, Size, M1, N1);
FillTMP(TMPD, OpAddr2, Size, M2, N2);
TMPR := TMPD and TMPS;
SetZN(TMPR);
V := false;
C := false;
SetResult(TMPR, OpAddr2, Size, M2, N2);
end;
iOR: begin
FillTMP(TMPS, OpAddr1, Size, M1, N1);
FillTMP(TMPD, OpAddr2, Size, M2, N2);
TMPR := TMPD or TMPS;
SetZN(TMPR);
V := false;
C := false;
SetResult(TMPR, OpAddr2, Size, M2, N2);
end;
iEOR: begin
FillTMP(TMPS, OpAddr1, Size, M1, N1);
FillTMP(TMPD, OpAddr2, Size, M2, N2);
TMPR := TMPD xor TMPS;
SetZN(TMPR);
V := false;
C := false;
SetResult(TMPR, OpAddr2, Size, M2, N2);
end;
iLSL: begin
FillTMP(TMPD, OpAddr2, Size, M2, N2);
TMPR := TMPD SHL Data;
SetZN(TMPR);
V := False;
if (Data > 0)
then begin
if GetBitsL(TMPD, NOB(Size)*8-Data, NOB(Size)*8-Data) = 1
then C:= true
else C:= false
end
else C := false;
SetResult(TMPR, OpAddr2, Size, M2, N2);
end;
iLSR: begin
FillTMP(TMPD, OpAddr2, Size, M2, N2);
TMPR := TMPD shr Data;
SetZN(TMPR) ;
V := false;
if Data > 0 then
C := ( GetBitsL(TMPD, Data-1, Data-1) = 1 )
else C := false;
SetResult(TMPR, OpAddr2, Size, M2, N2);
end;
iROL: begin
FillTMP(TMPD, OpAddr2, Size, M2, N2);
Data := Data mod 8*NOB(Size);
TMPR := TMPD shl Data;
TMPS := TMPD shr 8*NOB(Size)-Data;
SetBitsL( TMPR, 0, Data-1, TMPS );
SetZN(TMPR);
V := false;
if Data > 0 then
C := ( GetBitsL(TMPD, NOB(Size)*8-Data, NOB(Size)*8-Data) = 1 )
else C := false;
SetResult(TMPR, OpAddr2, Size, M2, N2);
end;
iROR: begin
FillTMP(TMPD, OpAddr2, Size, M2, N2);
Data := Data mod 8*NOB(Size);
TMPR := TMPD shr Data;
SetBitsL( TMPR, 8*NOB(Size)-Data, 8*NOB(Size)-1, TMPD );
SetZN(TMPR);
V := false;
if Data > 0 then
C := ( GetBitsL(TMPD, Data-1, Data-1) = 1 )
else C := false ;
SetResult(TMPR, OpAddr2, Size, M2, N2);
end;
iCMP: begin
FillTMP(TMPS, OpAddr1, Size, M1, N1);
FillTMP(TMPD, OpAddr2, Size, M2, N2);
TMPR := TMPD - TMPS;
SetZN(TMPR);
SetSmDmRm (TMPS, TMPD, TMPR);
V := ( NOT(Sm) and Dm and NOT(Rm) ) or ( Sm and NOT(Dm) and Rm );
C := ( Sm and NOT(Dm) ) or ( Rm and NOT(Dm) ) or ( Sm and Rm );
end;
iTST: begin
FillTMP(TMPD, OpAddr1, Size, M1, N1);
SetZN(TMPD);
V := false;
C := false;
end;
iBRA: begin
if CheckCond( (M1 = $3), 'Invalid Addressing Mode')
then
if CheckCond ( (Size = wordSize), 'Invalid Data Size')
then
PC := OpAddr1
end;
iBVS: begin
if CheckCond( (M1 = $3), 'Invalid Addressing Mode')
then
if CheckCond ( (Size = wordSize), 'Invalid Data Size')
then
if V then PC := OpAddr1
end;
iBEQ: begin
if CheckCond( (M1 = $3), 'Invalid Addressing Mode')
then
if CheckCond ( (Size = wordSize), 'Invalid Data Size')
then
if Z then PC := OpAddr1
end;
iBCS: begin
if CheckCond( (M1 = $3), 'Invalid Addressing Mode')
then
if CheckCond ( (Size = wordSize), 'Invalid Data Size')
then
if C then PC := OpAddr1
end;
iBGE: begin
if CheckCond( (M1 = $3), 'Invalid Addressing Mode')
then
if CheckCond ( (Size = wordSize), 'Invalid Data Size')
then
if not( N xor V ) then PC := OpAddr1
end;
iBLE: begin
if CheckCond( (M1 = $3), 'Invalid Addressing Mode')
then
if CheckCond ( (Size = wordSize), 'Invalid Data Size')
then
if ( N xor V ) then PC := OpAddr1
end;
iMOVE: begin
FillTMP(TMPS, OpAddr1, Size, M1, N1);
SetResult(TMPS, OpAddr2, Size, M2, N2);
end;
iMOVEQ: begin
FillTMP(TMPD, OpAddr2, Size, M2, N2);
SetByteL(TMPD, 0, Data);
{ Sign extension if W or L ?? }
SetZN(TMPD);
V := false;
C := false;
SetResult(TMPD, OpAddr2, Size, M2, N2);
end;
iEXG: begin
if CheckCond((((M1=$0) or (M1=$1)) and ((M2=$0) or (M2=$1))), 'Invalid Addressing Mode')
then begin
FillTMP(TMPS, OpAddr1, Size, M1, N1);
FillTMP(TMPD, OpAddr2, Size, M2, N2);
SetResult(TMPS, OpAddr1, Size, M2, N2);
SetResult(TMPD, OpAddr2, Size, M1, N1);
V := false;
C := false;
end { if valid address }
end;
iMOVEA: begin
if CheckCond( (Size=wordSize), 'Invalid Data Size')
then
if CheckCond( ((M1=$3) AND (M2=$1)), 'Invalid Addressing Mode')
then
SetResult(OpAddr1, OpAddr2, Size, M2, N2)
end;
iINP: begin
write('Enter a value ');
case Size of
byteSize: write('(byte) for ');
wordSize: write('(word) for ');
longSize: write('(long) for ');
end;
case M1 of
$0: write('the register D', N1);
$1: write('the register A', N1);
$4: write('the memory address $',Word2Hex(A[N1]):4);
$6: write('the memory address $',Word2Hex(A[N1]):4);
$7: write('the memory address $',Word2Hex(A[N1]):4);
$3: write('the memory address $',Word2Hex(OpAddr1));
end;
write(': ');
readln(TMPD);
SetZN(TMPD);
C:= false;
V:= false;
SetResult(TMPD, OpAddr1, Size, M1, N1)
end;
iDSP: begin
FillTMP(TMPS, OpAddr1, Size, M1, N1);
case M1 of
$0: write('[ D', N1,' ] = $');
$1: write('[ A', N1,' ] = $');
$4: write('[$',Word2Hex(A[N1]),'] = $');
$6: begin
(* NOB(Size) subtracted to compensate post-incrementation *)
tmpA := A[N1] - NOB(Size);
write('[$',Word2Hex(tmpA),'] = $');
end;
$7: write('[$',Word2Hex(A[N1]),'] = $');
$3: write('[$',Word2Hex(OpAddr1):4,'] = $');
end;
case Size of
byteSize: writeln(Byte2Hex(TMPS), ' (byte)');
wordSize: writeln(Word2Hex(TMPS), ' (word)');
longSize: writeln(Long2Hex(TMPS), ' (long)');
end
end;
iDSR: begin
writeln ('Status Bits: H:', H, ' N:', N, ' Z:', Z, ' V:', V, ' C:', C);
end;
iHLT: H := true ; (* Set the Halt Status Bit to 1 (stops program) *)
end; (* case *)
end; (* ExecInstr *)
begin (* Controller *)
Init;
repeat
FetchOpCode;
DecodeInstr;
FetchOperands;
if NOT(H)
then
ExecInstr;
until H;
(* Repeat the Fetch-Execute Cycle until the H bit becomes 1. *)
writeln;
writeln ('End of program Execution.');
end; (* Controller *)
(***************************************************************************)
procedure Identification ;
(**** TO BE MODIFIED ACCORDING TO YOUR NEEDS ****)
begin
// clrscr;
writeln('*** Sim68k ***') ;
writeln ;
writeln('Project CSI 2111 (November 1999).') ;
(* Insert your names and student numbers *)
writeln('FirstName LastName: #StudentNumber');
writeln('-------------------------------------');
writeln('Tu Nguyen 555104 ');
writeln('Mark Sattolo 428500 ');
writeln('Thuy Nguyen 1768590 ');
writeln('-------------------------------------');
writeln;
writeln('Menu: ');
writeln('(e)xecute <file.68b>');
writeln('(q)uit the simulator');
writeln;
writeln;
end ;
(* Main program. Menu with 2 options. *)
(*------------------------------------------------------------------------------------------------------------*)
begin { Main program }
program_name := '';
option := ' ';
MnemoInit;
(* Menu *)
while (option <> 'q') do
begin
identification;
write('Your Option : ');
readln(option);
case option of
'e' : begin
(* Execution on the simulator *)
write('Name of the 68k binary program (".68b" will be added automatically): ');
readln(program_name);
Loader( concat(program_name,'.68b') );
Controller; (* Start the simulator *)
end;
'q' : writeln('Bye! and come again');
else
writeln('Invalid Option. Please enter e or q.');
end; (* case *)
writeln;
writeln('Press <Enter>.');
readln;
end; (* while *)
end.
|
unit SampleClasses;
interface
type
TSampleFoo = class(TObject)
private class var
FNextId: Integer;
private
FId: Integer;
public
constructor Create;
function ToString: String; override;
procedure SomeMethod;
end;
TSampleBar = class(TSampleFoo)
public
function ToString: String; override;
end;
procedure SomeProcedure;
implementation
uses
System.SysUtils,
Grijjy.CloudLogging;
procedure SomeProcedure;
begin
GrijjyLog.EnterMethod('SomeProcedure');
GrijjyLog.Send('Inside SomeProcedure', TgoLogLevel.Error);
GrijjyLog.ExitMethod('SomeProcedure');
end;
{ TSampleFoo }
constructor TSampleFoo.Create;
begin
inherited;
FId := FNextId;
Inc(FNextId);
end;
procedure TSampleFoo.SomeMethod;
begin
GrijjyLog.EnterMethod(Self, 'SomeMethod');
GrijjyLog.Send('Inside TSampleFoo.SomeMethod', TgoLogLevel.Warning);
SomeProcedure;
GrijjyLog.ExitMethod(Self, 'SomeMethod');
end;
function TSampleFoo.ToString: String;
begin
Result := Format('Foo #%d', [FId]);
end;
{ TSampleBar }
function TSampleBar.ToString: String;
begin
Result := Format('Bar #%d', [FId]);
end;
end.
|
unit Palettes;
// Copyright (c) 1996 Jorge Romero Gomez, Merchise.
// Check NumberOfEntries, so tasks don't work on non-used entries
interface
uses
SysUtils, Classes, Windows,
MemUtils, GDI, ColorTrans;
type
TBufferPaletteTask = class;
// TBufferPalette
CBufferPalette = class of TBufferPalette;
TBufferPalette =
class( TPersistent )
protected
fPalette : T256LogPalette;
fOriginal : T256PalEntries;
fHandle : HPALETTE;
function GetHandle : HPALETTE; virtual;
procedure SetHandle( aHandle : HPALETTE ); virtual;
public
property Palette : T256LogPalette read fPalette;
property Original : T256PalEntries read fOriginal;
property Handle : HPALETTE read GetHandle write SetHandle;
public
destructor Destroy; override;
constructor Create; virtual;
procedure Assign( Source : TPersistent ); override;
procedure Release;
procedure HandleNeeded;
function ReleaseHandle : HPALETTE;
constructor CreateFromHandle( Handle : HPALETTE ); virtual;
constructor CreateFromLogPalette( const LogEntries; Count : integer ); virtual;
constructor CreateFromRgbPalette( const RgbQuads; Count : integer ); virtual;
procedure ForceIdentity; virtual;
procedure ReserveEntriesForAnimation( Indx, Count : integer; Reserved : boolean ); virtual;
procedure AssignLogEntries( Indx, Count : integer; const LogEntries ); virtual;
procedure AssignRgbEntries( Indx, Count : integer; const RgbQuads ); virtual;
public
procedure DoStep; virtual;
public
procedure SaveToFile( const FileName : string ); virtual;
procedure LoadFromFile( const FileName : string ); virtual;
procedure SaveToStream( Stream : TStream ); virtual;
procedure LoadFromStream( Stream : TStream ); virtual;
// F/Xs
procedure ChangeLogEntries( Indx, Count : integer; const LogEntries ); virtual;
procedure ChangeRgbEntries( Indx, Count : integer; const RgbQuads ); virtual;
procedure Restore; virtual;
procedure Update; virtual;
function Animating : boolean;
procedure Convert( const GoalLogPalette; Indx, Count : integer; Steps : integer ); virtual;
procedure Cycle( Reversed : boolean; Indx, Count : integer;
CyclingStep, Steps : integer ); virtual;
procedure FadeIn( Indx, Count : integer; Steps : integer ); virtual;
procedure FadeOut( Indx, Count : integer; Steps : integer ); virtual;
procedure Blackout; virtual;
public
function NearestIndex( Color : TColorRef ) : integer; virtual;
protected
Tasks : TList;
function NewTask( TaskType : integer;
Indx, Count, Steps, Tag : integer; Info : pointer ) : TBufferPaletteTask; virtual;
end;
// Palette F/X Tasks
TPaletteDelta =
record
Red : integer;
Green : integer;
Blue : integer;
end;
TPaletteDeltas = array[0..255] of TPaletteDelta;
TBufferPaletteTask =
class
protected
fOwner : TBufferPalette;
fIndx, fCount : integer;
fSteps : integer;
fTag : integer;
fTaskType : integer;
fCurrentStep : integer;
fCurrent, fDelta : TPaletteDeltas;
protected
constructor Create( Indx, Count, Steps, Tag : integer; Owner : TBufferPalette );
procedure DoStep; virtual;
procedure Cycle;
procedure Convert( const GoalLogPalette );
end;
// Helper functions
function SetCanvasPalette( Handle : HDC; Palette : TBufferPalette ) : HPALETTE;
implementation
uses
StreamUtils;
// Helper functions
function SetCanvasPalette( Handle : HDC; Palette : TBufferPalette ) : HPALETTE;
begin
Palette.Update;
Result := SelectPalette( Handle, Palette.Handle, false );
end;
// Palette F/X Task Types
const
ttNone = 0;
ttCycle = 10;
ttConvert = 20;
// TBufferPalette
procedure TBufferPalette.Release;
var
indx : integer;
begin
for indx := Tasks.Count - 1 downto 0 do
TBufferPaletteTask( Tasks[indx] ).Free;
Tasks.Clear;
if fHandle <> 0
then
begin
DeleteObject( fHandle );
fHandle := 0;
end;
end;
destructor TBufferPalette.Destroy;
begin
Release;
Tasks.Free;
inherited;
end;
constructor TBufferPalette.Create;
begin
inherited Create;
with Palette do
begin
Version := LogPaletteVersion;
NumberOfEntries := 256;
end;
Tasks := TList.Create;
end;
constructor TBufferPalette.CreateFromLogPalette( const LogEntries; Count : integer );
begin
Create;
with fPalette do
begin
assert( Count <= 256, 'Count too big in Palettes.TBufferPalette.CreateFromLogPalette!!' );
NumberOfEntries := Count;
Move( LogEntries, Entries, sizeof( Entries[0] )* Count );
Move( Entries, fOriginal, sizeof( fOriginal ) );
end;
end;
constructor TBufferPalette.CreateFromRgbPalette( const RgbQuads; Count : integer );
var
RgbPalette : TRgbPalette absolute RgbQuads;
begin
Create;
with fPalette do
begin
NumberOfEntries := Count;
RgbToLogEntries( 0, Count, RgbPalette, Entries );
MarkNoCollapse( 0, Count, Entries );
Move( Entries, fOriginal, sizeof( fOriginal ) );
end;
end;
constructor TBufferPalette.CreateFromHandle( Handle : HPALETTE );
begin
Create;
SetHandle( Handle );
end;
procedure TBufferPalette.Assign( Source : TPersistent );
begin
if Source is TBufferPalette
then
with TBufferPalette( Source ) do
begin
Self.Release;
Move( fPalette, Self.fPalette, sizeof( fPalette ) + sizeof( fOriginal ) );
end
else inherited;
end;
procedure TBufferPalette.HandleNeeded;
begin
if fHandle <> 0
then GetHandle;
end;
function TBufferPalette.ReleaseHandle : HPALETTE;
begin
Result := Handle;
fHandle := 0;
end;
function TBufferPalette.GetHandle : HPALETTE;
begin
if fHandle = 0
then fHandle := PaletteHandle( Palette );
Result := fHandle;
end;
procedure TBufferPalette.SetHandle( aHandle : HPALETTE );
var
First, Last, Count : integer;
begin
Release;
with fPalette do
begin
fHandle := aHandle;
Update;
GetColorAvailInfo( First, Last, Count );
MarkNoCollapse( First, Count, fOriginal );
end;
end;
procedure TBufferPalette.Update;
begin
if fHandle <> 0
then
begin
GetLogPalette( fHandle, 0, 256, fOriginal, true );
with fPalette do
Move( fOriginal, Entries, sizeof( Entries ) );
end;
end;
procedure TBufferPalette.Restore;
begin
ChangeLogEntries( 0, 256, Original );
end;
procedure TBufferPalette.ReserveEntriesForAnimation( Indx, Count : integer; Reserved : boolean );
begin
if Reserved
then MarkReserved( Indx, Count, fOriginal )
else MarkNoCollapse( Indx, Count, fOriginal );
Update;
if fHandle <> 0
then SetPaletteEntries( Handle, 0, 256, fOriginal );
end;
procedure TBufferPalette.ForceIdentity;
var
ScreenDC : HDC;
begin
if AvailableColors < 256
then
begin
with fPalette do
begin
ScreenDC := GetDC( 0 );
GetSystemPaletteEntries( ScreenDC, 0, FirstAvailColor, Entries );
GetSystemPaletteEntries( ScreenDC, succ( LastAvailColor ), FirstAvailColor, Entries );
ReleaseDC( 0, ScreenDC );
Move( Entries, fOriginal, sizeof( fOriginal ) );
end;
if fHandle <> 0
then SetPaletteEntries( Handle, 0, 256, fPalette.Entries );
end;
end;
procedure TBufferPalette.AssignLogEntries( Indx, Count : integer; const LogEntries );
begin
ChangeLogEntries( Indx, Count, LogEntries );
if @LogEntries <> @fOriginal
then Move( LogEntries, fOriginal[Indx], Count * sizeof( fOriginal[0] ) );
end;
procedure TBufferPalette.AssignRgbEntries( Indx, Count : integer; const RgbQuads );
begin
ChangeRgbEntries( Indx, Count, RgbQuads );
if @RgbQuads <> @fPalette.Entries
then Move( fPalette.Entries[Indx], fOriginal[Indx], Count * sizeof( fPalette.Entries[0] ) );
end;
procedure TBufferPalette.ChangeRgbEntries( Indx, Count : integer; const RgbQuads );
var
Rgb : TRgbPalette absolute RgbQuads;
i : integer;
begin
assert( Count <= 256, 'Count too big in Palettes.TBufferPalette.ChangeRgbEntries!!' );
for i := Indx to Indx + pred( Count ) do
with fPalette.Entries[i], Rgb[i] do
begin
peRed := rgbRed;
peGreen := rgbGreen;
peBlue := rgbBlue;
end;
if fHandle <> 0
then SetPaletteEntries( fHandle, 0, 256, fPalette.Entries );
end;
procedure TBufferPalette.ChangeLogEntries( Indx, Count : integer; const LogEntries );
begin
assert( Count <= 256, 'Count too big in Palettes.TBufferPalette.ChangeLogEntries!!' );
if @LogEntries <> @fPalette.Entries
then Move( LogEntries, fPalette.Entries[Indx], Count * sizeof( fPalette.Entries[0] ) );
if fHandle <> 0
then SetPaletteEntries( fHandle, 0, 256, fPalette.Entries );
end;
function TBufferPalette.NewTask( TaskType : integer; Indx, Count, Steps, Tag : integer; Info : pointer ) : TBufferPaletteTask;
begin
Result := TBufferPaletteTask.Create( Indx, Count, Steps, Tag, Self );
case TaskType of
ttCycle :
Result.Cycle;
ttConvert :
Result.Convert( Info^ );
else FreeObject( Result );
end;
end;
procedure TBufferPalette.DoStep;
var
Indx : integer;
CurrTask : TBufferPaletteTask;
begin
for Indx := Tasks.Count - 1 downto 0 do
begin
CurrTask := TBufferPaletteTask( Tasks[ Indx ] );
with CurrTask do
begin
DoStep;
if fSteps <> -1
then
begin
inc( fCurrentStep );
if fCurrentStep >= fSteps
then
begin
Tasks.Remove( CurrTask );
CurrTask.Free;
end;
end;
end;
end;
Tasks.Pack;
end;
function TBufferPalette.Animating : boolean;
begin
Result := ( Tasks.Count > 0 );
end;
procedure TBufferPalette.Convert( const GoalLogPalette; Indx, Count, Steps : integer );
begin
assert( Count <= 256, 'Count too big in Palettes.TBufferPalette.Convert!!' );
assert( Steps > 0, 'Invalid step count in Palettes.TBufferPalette.Convert!!' );
Tasks.Add( NewTask( ttConvert, Indx, Count, Steps, 0, @GoalLogPalette ) );
end;
procedure TBufferPalette.Cycle( Reversed : boolean; Indx, Count, CyclingStep, Steps : integer );
begin
assert( Count <= 256, 'Count too big in Palettes.TBufferPalette.Cycle!!' );
assert( (Steps > 0) or (Steps = -1), 'Invalid step count in Palettes.TBufferPalette.Cycle!!' );
assert( (CyclingStep > 0), 'Invalid cycling step in Palettes.TBufferPalette.Cycle!!' );
if Reversed
then CyclingStep := -CyclingStep;
Tasks.Add( NewTask( ttCycle, Indx, Count, Steps, CyclingStep, nil ) )
end;
procedure TBufferPalette.FadeIn( Indx, Count, Steps : integer );
begin
assert( Count <= 256, 'Count too big in Palettes.TBufferPalette.FadeIn!!' );
assert( Steps > 0, 'Invalid step count in Palettes.TBufferPalette.FadeIn!!' );
Convert( Original, Indx, Count, Steps );
end;
procedure TBufferPalette.FadeOut( Indx, Count, Steps : integer );
begin
assert( Count <= 256, 'Count too big in Palettes.TBufferPalette.FadeOut!!' );
assert( Steps > 0, 'Invalid step count in Palettes.TBufferPalette.FadeOut!!' );
Convert( LogBlackPalette.Entries, Indx, Count, Steps );
end;
procedure TBufferPalette.Blackout;
begin
ChangeLogEntries( 0, 256, LogBlackPalette.Entries );
end;
function TBufferPalette.NearestIndex( Color : TColorRef ) : integer;
begin
Result := GetNearestPaletteIndex( Handle, Color );
end;
procedure TBufferPalette.LoadFromStream( Stream : TStream );
begin
Release;
Stream.ReadBuffer( fPalette, sizeof( fPalette ) );
AssignLogEntries( 0, 256, fPalette.Entries );
end;
procedure TBufferPalette.SaveToStream( Stream : TStream );
begin
Stream.WriteBuffer( fPalette, sizeof( fPalette ) );
end;
procedure TBufferPalette.LoadFromFile( const FileName : string );
begin
StreamObject( TFileStream.Create( FileName, fmOpenRead or fmShareDenyWrite ), LoadFromStream );
end;
procedure TBufferPalette.SaveToFile( const FileName : string );
begin
StreamObject( TFileStream.Create( FileName, fmCreate ), SaveToStream );
end;
// -----------------
// Palette F/X Tasks
// -----------------
constructor TBufferPaletteTask.Create( Indx, Count, Steps, Tag : integer; Owner : TBufferPalette );
begin
inherited Create;
fOwner := Owner;
fIndx := Indx;
fCount := Count;
fSteps := Steps;
fTag := Tag;
end;
procedure CycleElements( Step, Count : integer; var Elements; ElementSize : integer );
var
Buffer : array[0..2048] of char;
begin
assert( ElementSize < sizeof(Buffer), 'ElementSize too big in Palettes.CycleElements!!' );
assert( ElementSize > 0, 'ElementSize invalid in Palettes.CycleElements!!' );
assert( Step <> 0, 'Step invalid in Palettes.CycleElements!!' );
if Step > 0
then
begin
Move( Elements, Buffer, Step * ElementSize );
Move( ( pchar(@Elements) + Step * ElementSize )^, Elements, ( Count - Step ) * ElementSize );
Move( Buffer, ( pchar(@Elements) + ( Count - Step ) * ElementSize )^, Step * ElementSize );
end
else
begin
Move( ( pchar(@Elements) + ( Count + Step ) * ElementSize )^, Buffer, -Step * ElementSize );
Move( Elements, ( pchar(@Elements) - Step * ElementSize )^, ( Count + Step ) * ElementSize );
Move( Buffer, Elements, -Step * ElementSize );
end;
end;
procedure TBufferPaletteTask.DoStep;
var
i : integer;
cTask : TBufferPaletteTask;
cFlag : boolean;
begin
case fTaskType of
ttCycle :
with fOwner, fPalette do
begin
cFlag := false; // Set if we are cycling and converting the same entries
for i := 0 to Tasks.Count - 1 do
begin
cTask := Tasks[i];
if ( cTask.fTaskType = ttConvert )
then
begin
assert( ( (fIndx >= cTask.fIndx) and (fIndx + fCount <= cTask.fIndx + cTask.fCount) )
or ( fIndx + fCount < cTask.fIndx )
or ( fIndx > cTask.fIndx + cTask.fCount ),
'Entries are being cycled and converted in an unsupported way in Palettes.TBufferPalette.DoStep!!' );
if (fIndx >= cTask.fIndx) and (fIndx + fCount <= cTask.fIndx + cTask.fCount)
then
begin
cFlag := true;
CycleElements( fTag, fCount, cTask.fDelta[fIndx], sizeof( fDelta[0] ) );
CycleElements( fTag, fCount, cTask.fCurrent[fIndx], sizeof( fCurrent[0] ) );
end;
end;
end;
if not cFlag
then
begin
CycleElements( fTag, fCount, Entries[fIndx], sizeof( Entries[0] ) );
AnimatePalette( Handle, fIndx, fCount, @Entries[fIndx] );
end;
end;
ttConvert :
with fOwner, fPalette do
begin
for i := fIndx to fIndx + fCount - 1 do
with Entries[i], fCurrent[i] do
begin
inc( Red, fDelta[i].Red );
inc( Green, fDelta[i].Green );
inc( Blue, fDelta[i].Blue );
peRed := Red div 1024;
peGreen := Green div 1024;
peBlue := Blue div 1024;
end;
AnimatePalette( Handle, fIndx, fCount, @Entries[fIndx] );
end;
end;
end;
procedure TBufferPaletteTask.Cycle;
begin
fTaskType := ttCycle;
end;
procedure TBufferPaletteTask.Convert( const GoalLogPalette );
var
Goal : T256PalEntries absolute GoalLogPalette;
i : integer;
begin
assert( ( fSteps > 0 ), 'fSteps <= 0 in Palettes.TBufferPaletteTask.Convert!!' );
fTaskType := ttConvert;
for i := fIndx to fIndx + fCount - 1 do
begin
with fCurrent[i], fOwner.Palette.Entries[i] do
begin
Red := 1024 * peRed;
Green := 1024 * peGreen;
Blue := 1024 * peBlue;
end;
with fDelta[i], Goal[i], fOwner.Palette do
begin
Red := ( peRed - Entries[i].peRed ) * 1024 div fSteps;
Green := ( peGreen - Entries[i].peGreen ) * 1024 div fSteps;
Blue := ( peBlue - Entries[i].peBlue ) * 1024 div fSteps;
end;
end;
end;
end.
|
unit USistema;
interface
uses
UUsuario;
type TSistema = class
private
FUsuarioLogado: TUsuario;
constructor create;
procedure SetUsuarioLogado(const Value: TUsuario);
class procedure ReleaseInstance();
class var Instancia : TSistema;
protected
public
class function ObterInstancia: TSistema;
published
property UsuarioLogado: TUsuario read FUsuarioLogado write SetUsuarioLogado;
end;
implementation
{ TSistema }
constructor TSistema.create;
begin
inherited;
end;
class function TSistema.ObterInstancia: TSistema;
begin
if not Assigned(Self.Instancia) then
Self.Instancia := TSistema.create;
result := Self.Instancia;
end;
class procedure TSistema.ReleaseInstance;
begin
if Assigned(Self.Instancia) then
Begin
Self.Instancia.UsuarioLogado.Free;
Self.Instancia.Free;
End;
end;
procedure TSistema.SetUsuarioLogado(const Value: TUsuario);
begin
FUsuarioLogado := Value;
end;
initialization
finalization
TSistema.ReleaseInstance();
end.
|
{***************************************}
{ }
{ ATPrintPreview Component }
{ Copyright (C) Alexey Torgashin }
{ http://uvviewsoft.com }
{ }
{***************************************}
unit ATPrintPreview;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons,
ATxPrintProc, ATxUpEdit, ATImageBox;
type
TATPreviewCallback = procedure(
ACanvas: TCanvas;
AOptPosition: TATPrintPosition;
AOptFit: TATPrintFitMode;
AOptFitSize: TFloatSize;
const AOptMargins: TFloatRect;
const AOptGamma: Double;
const AOptFooter: TATPrintFooter) of object;
type
TFormATPreview = class(TForm)
boxOptions: TGroupBox;
boxPreview: TGroupBox;
btnOK: TButton;
btnCancel: TButton;
btnPrintSetup: TButton;
boxPosition: TGroupBox;
PrinterSetupDialog1: TPrinterSetupDialog;
boxMargins: TGroupBox;
edMarginTop: TUpEdit;
labMarginTop: TLabel;
labMarginBottom: TLabel;
edMarginBottom: TUpEdit;
labMarginLeft: TLabel;
edMarginLeft: TUpEdit;
labMarginRight: TLabel;
edMarginRight: TUpEdit;
Panel2: TPanel;
btnPos1: TSpeedButton;
btnPos2: TSpeedButton;
btnPos3: TSpeedButton;
btnPos4: TSpeedButton;
btnPos5: TSpeedButton;
btnPos6: TSpeedButton;
btnPos7: TSpeedButton;
btnPos8: TSpeedButton;
btnPos9: TSpeedButton;
boxGamma: TGroupBox;
labGamma: TLabel;
edGamma: TUpEdit;
FontDialog1: TFontDialog;
panFit: TPanel;
labFit: TLabel;
labSizeX: TLabel;
labSizeY: TLabel;
labMm2: TLabel;
labMm1: TLabel;
edFit: TComboBox;
edSizeX: TUpEdit;
edSizeY: TUpEdit;
chkFitProp: TCheckBox;
panFooter: TPanel;
chkFooter: TCheckBox;
btnFont: TButton;
V: TATImageBox;
labHint: TLabel;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnPrintSetupClick(Sender: TObject);
procedure btnPos1Click(Sender: TObject);
procedure edMarginTopChange(Sender: TObject);
procedure edFitChange(Sender: TObject);
procedure edSizeXChange(Sender: TObject);
procedure edSizeYChange(Sender: TObject);
procedure chkFitPropClick(Sender: TObject);
procedure btnFontClick(Sender: TObject);
procedure chkFooterClick(Sender: TObject);
private
{ Private declarations }
FBitmap: TBitmap;
FBitmapSizeX: Integer;
FBitmapSizeY: Integer;
FPreview: TATPreviewCallback;
FEnabled: Boolean;
FFitting: Boolean;
FUnit: TATPrintUnit;
FFooterCaption: WideString;
FFooterLine: Boolean;
function GetPosition: TATPrintPosition;
function GetFitSize: TFloatSize;
function InitBitmap: Boolean;
procedure DoPreview;
procedure FitChange;
procedure FooterChange;
function GetFitMode: TATPrintFitMode;
function GetMargins: TFloatRect;
function GetGamma: Double;
function GetFooter: TATPrintFooter;
procedure FitSizeY;
procedure FitSizeX;
public
{ Public declarations }
end;
//-----------------------------------------------------
var
//Captions:
MsgPreviewDlgCaption: string = 'Print preview';
MsgPreviewDlgPrintSetup: string = '&Print setup...';
MsgPreviewDlgPrint: string = 'Print';
MsgPreviewDlgCancel: string = 'Cancel';
MsgPreviewDlgOptions: string = ' Options ';
MsgPreviewDlgPosition: string = ' Position ';
MsgPreviewDlgPreview: string = ' Preview ';
MsgPreviewDlgMargins: string = ' Margins ';
MsgPreviewDlgGamma: string = ' Gamma ';
MsgPreviewDlgMarginLeft: string = '&Left:';
MsgPreviewDlgMarginTop: string = '&Top:';
MsgPreviewDlgMarginRight: string = '&Right:';
MsgPreviewDlgMarginBottom: string = '&Bottom:';
MsgPreviewDlgOptFitMode: string = '&Fit mode:';
MsgPreviewDlgOptFitSizeX: string = '&Width:';
MsgPreviewDlgOptFitSizeY: string = '&Height:';
MsgPreviewDlgOptFitSizeProp: string = 'Proportio&nal';
MsgPreviewDlgOptFooter: string = 'F&ooter text';
MsgPreviewDlgOptFooterFont: string = 'Font...';
MsgPreviewDlgOptGamma: string = '&Gamma value:';
MsgPreviewDlgUnit: array[TATPrintUnit] of string =
('mm', 'cm', 'inches');
MsgPreviewDlgFitModes: array[TATPrintFitMode] of string =
('Normal', 'Best fit to page', 'Stretch to page', 'Custom size');
MsgPreviewDlgPos: array[TATPrintPosition] of string =
('Top-Left', 'Top', 'Top-Right',
'Left', 'Center', 'Right',
'Bottom-Left', 'Bottom', 'Bottom-Right');
//Error messages:
MsgPreviewDlgCannotAllocateMemory: string = 'Cannot allocate temporary bitmap, not enougth memory.';
//Font:
MsgPreviewDlgFontName: string = 'Tahoma';
MsgPreviewDlgFontSize: Integer = 8;
//-----------------------------------------------------
function ShowImagePreviewDialog(
ACallback: TATPreviewCallback;
var AOptions: TATPrintOptions;
ABitmapSizeX,
ABitmapSizeY: Integer): Boolean;
function ShowTextPreviewDialog(
ACallback: TATPreviewCallback;
AFailOnErrors: Boolean): Boolean;
function PreviewPageWidth(APixelsPerInch: Integer): Integer;
function PreviewPageHeight(APixelsPerInch: Integer): Integer;
var PreviewParentWnd: integer = 0;
implementation
uses
Printers;
{$R *.dfm}
//-------------------------------------------------------------------
function ShowImagePreviewDialog(
ACallback: TATPreviewCallback;
var AOptions: TATPrintOptions;
ABitmapSizeX,
ABitmapSizeY: Integer): Boolean;
const
cInc: array[TATPrintUnit] of Double =
(1.0, 0.5, 0.2);
begin
with TFormATPreview.Create(nil) do
try
if not InitBitmap then
begin
Result := not AOptions.FailOnErrors;
Exit;
end;
FPreview := ACallback;
FBitmapSizeX := ABitmapSizeX;
FBitmapSizeY := ABitmapSizeY;
FUnit := AOptions.OptUnit;
edSizeX.Inc := cInc[FUnit];
edSizeY.Inc := cInc[FUnit];
edSizeX.Min := cInc[FUnit];
edSizeY.Min := cInc[FUnit];
edMarginLeft.Inc := cInc[FUnit];
edMarginRight.Inc := cInc[FUnit];
edMarginTop.Inc := cInc[FUnit];
edMarginBottom.Inc := cInc[FUnit];
boxMargins.Caption := Format('%s(%s) ', [MsgPreviewDlgMargins, MsgPreviewDlgUnit[FUnit]]);
labMm1.Caption := MsgPreviewDlgUnit[FUnit];
labMm2.Caption := MsgPreviewDlgUnit[FUnit];
case AOptions.OptPosition of
pPosTopLeft : btnPos1.Down := True;
pPosTop : btnPos2.Down := True;
pPosTopRight : btnPos3.Down := True;
pPosLeft : btnPos4.Down := True;
pPosCenter : btnPos5.Down := True;
pPosRight : btnPos6.Down := True;
pPosBottomLeft: btnPos7.Down := True;
pPosBottom : btnPos8.Down := True;
else btnPos9.Down := True;
end;
edFit.ItemIndex := Ord(AOptions.OptFit);
edGamma.Value := AOptions.OptGamma;
FFooterCaption := AOptions.OptFooter.Caption;
FFooterLine := AOptions.OptFooter.EnableLine;
chkFooter.Checked := AOptions.OptFooter.Enabled;
with AOptions.OptFooter, FontDialog1 do
begin
Font.Name := FontName;
Font.Size := FontSize;
Font.Style := FontStyle;
Font.Color := FontColor;
Font.Charset := FontCharset;
end;
with AOptions.OptMargins do
begin
edMarginLeft.Value := Left;
edMarginTop.Value := Top;
edMarginRight.Value := Right;
edMarginBottom.Value := Bottom;
end;
edSizeX.Value := AOptions.OptFitSize.X;
chkFitProp.Checked := True;
Result := ShowModal = mrOk;
if Result then
begin
AOptions.OptFit := GetFitMode;
AOptions.OptFitSize := GetFitSize;
AOptions.OptPosition := GetPosition;
AOptions.OptMargins := GetMargins;
AOptions.OptGamma := GetGamma;
AOptions.OptFooter := GetFooter;
end;
finally
Release;
end;
end;
//-------------------------------------------------------------------
function ShowTextPreviewDialog(
ACallback: TATPreviewCallback;
AFailOnErrors: Boolean): Boolean;
begin
with TFormATPreview.Create(nil) do
try
if not InitBitmap then
begin
Result := not AFailOnErrors;
Exit;
end;
//Hide image options
boxOptions.Visible := False;
boxMargins.Visible := False;
boxPosition.Visible := False;
boxGamma.Visible := False;
Width := Width - boxGamma.Width - boxGamma.Left;
//Width := Width - boxGamma.Width - boxOptions.Left;
//panFit.Visible := False;
//panFooter.Top := 80;
FPreview := ACallback;
Result := ShowModal = mrOk;
finally
Release;
end;
end;
//-------------------------------------------------------------------
function TFormATPreview.GetPosition: TATPrintPosition;
begin
if btnPos1.Down then Result := pPosTopLeft else
if btnPos2.Down then Result := pPosTop else
if btnPos3.Down then Result := pPosTopRight else
if btnPos4.Down then Result := pPosLeft else
if btnPos5.Down then Result := pPosCenter else
if btnPos6.Down then Result := pPosRight else
if btnPos7.Down then Result := pPosBottomLeft else
if btnPos8.Down then Result := pPosBottom else
Result := pPosBottomRight;
end;
//-------------------------------------------------------------------
function TFormATPreview.GetFitSize: TFloatSize;
begin
Result.x := edSizeX.Value;
Result.y := edSizeY.Value;
end;
//-------------------------------------------------------------------
function TFormATPreview.GetMargins: TFloatRect;
begin
Result.Left := edMarginLeft.Value;
Result.Top := edMarginTop.Value;
Result.Right := edMarginRight.Value;
Result.Bottom := edMarginBottom.Value;
end;
//-------------------------------------------------------------------
function TFormATPreview.GetGamma: Double;
begin
Result := edGamma.Value;
end;
function TFormATPreview.GetFooter: TATPrintFooter;
begin
with Result do
begin
Enabled := chkFooter.Checked;
EnableLine := FFooterLine;
Caption := FFooterCaption;
with FontDialog1 do
begin
FontName := Font.Name;
FontSize := Font.Size;
FontStyle := Font.Style;
FontColor := Font.Color;
FontCharset := Font.Charset;
end;
end;
end;
//-------------------------------------------------------------------
function TFormATPreview.GetFitMode: TATPrintFitMode;
begin
Result := TATPrintFitMode(edFit.ItemIndex);
end;
//-------------------------------------------------------------------
procedure TFormATPreview.DoPreview;
begin
if not FEnabled then Exit;
Assert(Assigned(FPreview), 'Callback not assigned');
Screen.Cursor := crHourGlass;
try
with FBitmap do
begin
Canvas.Brush.Color := clWhite;
Canvas.FillRect(Rect(0, 0, Width, Height));
end;
FPreview(
FBitmap.Canvas,
GetPosition,
GetFitMode,
GetFitSize,
GetMargins,
GetGamma,
GetFooter);
V.LoadBitmap(FBitmap, False);
V.Image.Resample := True;
V.ImageFitToWindow := True;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TFormATPreview.FormCreate(Sender: TObject);
var
i: TATPrintFitMode;
begin
Font.Name := MsgPreviewDlgFontName;
Font.Size := MsgPreviewDlgFontSize;
Caption := MsgPreviewDlgCaption;
btnPrintSetup.Caption := MsgPreviewDlgPrintSetup;
btnOK.Caption := MsgPreviewDlgPrint;
btnCancel.Caption := MsgPreviewDlgCancel;
boxOptions.Caption := MsgPreviewDlgOptions;
boxPosition.Caption := MsgPreviewDlgPosition;
boxMargins.Caption := MsgPreviewDlgMargins;
labMarginLeft.Caption := MsgPreviewDlgMarginLeft;
labMarginTop.Caption := MsgPreviewDlgMarginTop;
labMarginRight.Caption := MsgPreviewDlgMarginRight;
labMarginBottom.Caption := MsgPreviewDlgMarginBottom;
boxGamma.Caption := MsgPreviewDlgGamma;
labGamma.Caption := MsgPreviewDlgOptGamma;
boxPreview.Caption := MsgPreviewDlgPreview;
labFit.Caption := MsgPreviewDlgOptFitMode;
labSizeX.Caption := MsgPreviewDlgOptFitSizeX;
labSizeY.Caption := MsgPreviewDlgOptFitSizeY;
chkFitProp.Caption := MsgPreviewDlgOptFitSizeProp;
chkFooter.Caption := MsgPreviewDlgOptFooter;
btnFont.Caption := MsgPreviewDlgOptFooterFont;
with edFit.Items do
begin
BeginUpdate;
Clear;
for i := Low(TATPrintFitMode) to High(TATPrintFitMode) do
Add(MsgPreviewDlgFitModes[i]);
EndUpdate;
end;
btnPos1.Hint := MsgPreviewDlgPos[pPosTopLeft];
btnPos2.Hint := MsgPreviewDlgPos[pPosTop];
btnPos3.Hint := MsgPreviewDlgPos[pPosTopRight];
btnPos4.Hint := MsgPreviewDlgPos[pPosLeft];
btnPos5.Hint := MsgPreviewDlgPos[pPosCenter];
btnPos6.Hint := MsgPreviewDlgPos[pPosRight];
btnPos7.Hint := MsgPreviewDlgPos[pPosBottomLeft];
btnPos8.Hint := MsgPreviewDlgPos[pPosBottom];
btnPos9.Hint := MsgPreviewDlgPos[pPosBottomRight];
FBitmap := TBitmap.Create;
with FBitmap do
begin
PixelFormat := pf24bit;
Width := 100;
Height := 100;
end;
with edGamma do
begin
Min := 0.1;
Max := 7.0;
Inc := 0.1;
end;
FPreview := nil;
FFitting := False;
FEnabled := False;
end;
procedure TFormATPreview.FormDestroy(Sender: TObject);
begin
FBitmap.Free;
end;
procedure TFormATPreview.FormShow(Sender: TObject);
begin
FitChange;
FEnabled := True;
DoPreview;
end;
//-------------------------------------------------------------------
// Helper class to implement callback function for preview form
type
TATImagePreviewHelper = class
public
FBitmap: TBitmap;
FOptUnit: TATPrintUnit;
FPixelsPerInch: Integer;
procedure Callback(
ACanvas: TCanvas;
AOptPosition: TATPrintPosition;
AOptFit: TATPrintFitMode;
AOptFitSize: TFloatSize;
const AOptMargins: TFloatRect;
const AOptGamma: Double;
const AOptFooter: TATPrintFooter);
end;
procedure TATImagePreviewHelper.Callback;
begin
BitmapPrintAction(
FBitmap,
ACanvas,
PreviewPageWidth(FPixelsPerInch), //ATargetWidth
PreviewPageHeight(FPixelsPerInch), //ATargetHeight
FPixelsPerInch, //ATargetPPIX
FPixelsPerInch, //ATargetPPIY
AOptFit,
AOptFitSize,
AOptPosition,
AOptMargins,
FOptUnit,
AOptGamma,
AOptFooter,
True, //AOptPreviewMode
FPixelsPerInch);
end;
//-------------------------------------------------------------------
function BitmapPreview(
ABitmap: TBitmap;
var AOptions: TATPrintOptions): Boolean;
begin
with TATImagePreviewHelper.Create do
try
FBitmap := ABitmap;
FOptUnit := AOptions.OptUnit;
FPixelsPerInch := AOptions.PixelsPerInch;
Result := ShowImagePreviewDialog(
Callback,
AOptions,
ABitmap.Width,
ABitmap.Height);
finally
Free;
end;
end;
//-------------------------------------------------------------------
function PreviewPageWidth(APixelsPerInch: Integer): Integer;
begin
Result := Trunc(Printer.PageWidth / (GetDeviceCaps(Printer.Handle, LOGPIXELSX) / APixelsPerInch));
end;
function PreviewPageHeight(APixelsPerInch: Integer): Integer;
begin
Result := Trunc(Printer.PageHeight / (GetDeviceCaps(Printer.Handle, LOGPIXELSY) / APixelsPerInch));
end;
//-------------------------------------------------------------------
function TFormATPreview.InitBitmap: Boolean;
begin
try
FBitmap.Width := PreviewPageWidth(Screen.PixelsPerInch);
FBitmap.Height := PreviewPageHeight(Screen.PixelsPerInch);
Result := True;
except
Application.MessageBox(
PChar(MsgPreviewDlgCannotAllocateMemory),
PChar(MsgPreviewDlgCaption),
MB_OK or MB_ICONERROR);
Result := False;
end;
end;
//-------------------------------------------------------------------
procedure TFormATPreview.btnPrintSetupClick(Sender: TObject);
begin
if PrinterSetupDialog1.Execute then
begin
InitBitmap;
DoPreview;
end;
end;
//-------------------------------------------------------------------
procedure TFormATPreview.btnPos1Click(Sender: TObject);
begin
DoPreview;
end;
procedure TFormATPreview.edMarginTopChange(Sender: TObject);
begin
DoPreview;
end;
procedure TFormATPreview.FitChange;
var
En: Boolean;
begin
En := GetFitMode = pFitSize;
edSizeX.Enabled := En;
edSizeY.Enabled := En;
labSizeX.Enabled := En;
labSizeY.Enabled := En;
labMm1.Enabled := En;
labMm2.Enabled := En;
chkFitProp.Enabled := En;
end;
procedure TFormATPreview.edFitChange(Sender: TObject);
begin
FitChange;
DoPreview;
end;
procedure TFormATPreview.FitSizeY;
begin
edSizeY.Value :=
edSizeX.Value / FBitmapSizeX * FBitmapSizeY;
end;
procedure TFormATPreview.FitSizeX;
begin
edSizeX.Value :=
edSizeY.Value / FBitmapSizeY * FBitmapSizeX;
end;
procedure TFormATPreview.edSizeXChange(Sender: TObject);
begin
if FFitting then Exit;
if chkFitProp.Checked then
try
FFitting := True;
FitSizeY;
finally
FFitting := False;
end;
DoPreview;
end;
procedure TFormATPreview.edSizeYChange(Sender: TObject);
begin
if FFitting then Exit;
if chkFitProp.Checked then
try
FFitting := True;
FitSizeX;
finally
FFitting := False;
end;
DoPreview;
end;
procedure TFormATPreview.chkFitPropClick(Sender: TObject);
begin
if chkFitProp.Checked then
FitSizeY;
end;
procedure TFormATPreview.btnFontClick(Sender: TObject);
begin
if FontDialog1.Execute then
DoPreview;
end;
procedure TFormATPreview.chkFooterClick(Sender: TObject);
begin
FooterChange;
DoPreview;
end;
procedure TFormATPreview.FooterChange;
begin
btnFont.Enabled := chkFooter.Checked;
end;
initialization
//Use the BitmapPreview code:
ATxPrintProc.ATBitmapPreview := BitmapPreview;
end.
|
{ Version 1.0 - Author jasc2v8 at yahoo dot com
This is free and unencumbered software released into the public domain.
For more information, please refer to <http://unlicense.org> }
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, StdCtrls, LclIntf,
EventLogUnit;
type
{ TForm1 }
TForm1 = class(TForm)
ButtonWrite: TButton;
ButtonOpen: TButton;
Memo1: TMemo;
procedure ButtonOpenClick(Sender: TObject);
procedure ButtonWriteClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FLog: TEventLogCustom;
public
end;
const
DS=DirectorySeparator;
LE=LineEnding;
LOGFILE = 'demo.log';
var
Form1: TForm1;
implementation
{$R *.lfm}
procedure Memoln(Fmt: String; Args: array of Const);begin
Form1.Memo1.Append(Format(Fmt, Args));
end;
{ TForm1 }
procedure TForm1.ButtonWriteClick(Sender: TObject);
begin
FLog.Info('Demo Started');
FLog.Debug('Debug message');
FLog.Error('Error message');
FLog.Warning('Warning message');
FLog.Message(etInfo, 'Demo Completed');
FLog.Message(''); //DefaultEventType is etDebug
Memo1.Append('Messages written to log file');
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FLog.Free;
end;
procedure TForm1.ButtonOpenClick(Sender: TObject);
begin
if FileExists(LOGFILE) then
OpenDocument(LOGFILE)
else
Memo1.Append('Log file doesn''t exist');
end;
procedure TForm1.FormShow(Sender: TObject);
begin
FLog:=TEventLogCustom.Create(LOGFILE, true);
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clTcpClientTls;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils,
{$ELSE}
System.Classes, System.SysUtils,
{$ENDIF}
clTcpClient, clTlsSocket, clSocket, clCertificate, clCertificateStore, clSspi, clSspiTls, clSocketUtils;
type
TclClientTlsMode = (ctNone, ctAutomatic, ctImplicit, ctExplicit);
TclTcpClientTls = class(TclTcpClient)
private
FUseTLS: TclClientTlsMode;
FCertificateFlags: TclCertificateVerifyFlags;
FTLSFlags: TclTlsFlags;
FOnGetCertificate: TclGetCertificateEvent;
FOnVerifyServer: TclVerifyPeerEvent;
FCSP: string;
procedure SetCertificateFlags(const Value: TclCertificateVerifyFlags);
procedure SetTLSFlags(const Value: TclTlsFlags);
function GetIsTls: Boolean;
procedure SetCSP(const Value: string);
protected
function GetNetworkStream: TclNetworkStream; override;
procedure GetCertificate(Sender: TObject; var ACertificate: TclCertificate;
AExtraCerts: TclCertificateList; var Handled: Boolean);
procedure VerifyServer(Sender: TObject; ACertificate: TclCertificate;
const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean);
function GetTlsStream: TclTlsNetworkStream;
procedure SetUseTLS(const Value: TclClientTlsMode); virtual;
procedure DoGetCertificate(var ACertificate: TclCertificate;
AExtraCerts: TclCertificateList; var Handled: Boolean); dynamic;
procedure DoVerifyServer(ACertificate: TclCertificate;
const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean); dynamic;
public
constructor Create(AOwner: TComponent); override;
procedure StartTls; virtual;
function ExplicitStartTls: Boolean;
property IsTls: Boolean read GetIsTls;
published
property UseTLS: TclClientTlsMode read FUseTLS write SetUseTLS default ctNone;
property CertificateFlags: TclCertificateVerifyFlags read FCertificateFlags
write SetCertificateFlags default [];
property TLSFlags: TclTlsFlags read FTLSFlags write SetTLSFlags default [tfUseTLS];
property CSP: string read FCSP write SetCSP;
property OnGetCertificate: TclGetCertificateEvent read FOnGetCertificate write FOnGetCertificate;
property OnVerifyServer: TclVerifyPeerEvent read FOnVerifyServer write FOnVerifyServer;
end;
implementation
{$IFDEF LOGGER}
uses
clLogger;
{$ENDIF}
{ TclTcpClientTls }
constructor TclTcpClientTls.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FUseTLS := ctNone;
FTLSFlags := [tfUseTLS];
end;
procedure TclTcpClientTls.SetUseTLS(const Value: TclClientTlsMode);
begin
if (FUseTLS <> Value) then
begin
FUseTLS := Value;
Changed();
end;
end;
function TclTcpClientTls.GetTlsStream: TclTlsNetworkStream;
begin
Result := TclTlsNetworkStream.Create();
Result.CertificateFlags := CertificateFlags;
Result.TLSFlags := TLSFlags;
Result.TargetName := Server;
Result.CSP := CSP;
Result.OnGetCertificate := GetCertificate;
Result.OnVerifyPeer := VerifyServer;
end;
procedure TclTcpClientTls.DoGetCertificate(var ACertificate: TclCertificate;
AExtraCerts: TclCertificateList; var Handled: Boolean);
begin
if Assigned(OnGetCertificate) then
begin
OnGetCertificate(Self, ACertificate, AExtraCerts, Handled);
end;
end;
procedure TclTcpClientTls.GetCertificate(Sender: TObject;
var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean);
begin
DoGetCertificate(ACertificate, AExtraCerts, Handled);
end;
function TclTcpClientTls.GetIsTls: Boolean;
begin
Result := (Connection.NetworkStream is TclTlsNetworkStream);
end;
function TclTcpClientTls.GetNetworkStream: TclNetworkStream;
begin
if ((UseTLS = ctAutomatic) and (Port <> GetDefaultPort())) or (UseTLS = ctImplicit) then
begin
Result := GetTlsStream();
end else
begin
Result := inherited GetNetworkStream();
end;
end;
function TclTcpClientTls.ExplicitStartTls: Boolean;
begin
Result := ((UseTLS = ctAutomatic) and (Port = GetDefaultPort()))
or (UseTLS = ctExplicit);
if Result then
begin
StartTls();
end;
end;
procedure TclTcpClientTls.StartTls;
begin
if (UseTLS = ctNone) then
begin
UseTLS := ctExplicit;
end;
try
Connection.NetworkStream := GetTlsStream();
Connection.OpenSession();
except
InProgress := True;
try
Close();
except
on EclSocketError do ;
end;
InProgress := False;
raise;
end;
end;
procedure TclTcpClientTls.DoVerifyServer(ACertificate: TclCertificate;
const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean);
begin
if Assigned(OnVerifyServer) then
begin
OnVerifyServer(Self, ACertificate, AStatusText, AStatusCode, AVerified);
end;
end;
procedure TclTcpClientTls.VerifyServer(Sender: TObject; ACertificate: TclCertificate;
const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean);
begin
DoVerifyServer(ACertificate, AStatusText, AStatusCode, AVerified);
end;
procedure TclTcpClientTls.SetCertificateFlags(const Value: TclCertificateVerifyFlags);
begin
if (FCertificateFlags <> Value) then
begin
FCertificateFlags := Value;
Changed();
end;
end;
procedure TclTcpClientTls.SetCSP(const Value: string);
begin
if (FCSP <> Value) then
begin
FCSP := Value;
Changed();
end;
end;
procedure TclTcpClientTls.SetTLSFlags(const Value: TclTlsFlags);
begin
if (FTLSFlags <> Value) then
begin
FTLSFlags := Value;
Changed();
end;
end;
end.
|
{$MODE OBJFPC}
unit renderer;
interface
uses
gl;
type
TRenderer=class
private
Textured,Colored:boolean;
Vertexes,vp,tp,cp:longint;
VertexArray,TexcoordArray,ColorArray:^GLFloat;
TexcoordX,TexcoordY:GLFloat;
ColorR,ColorG,ColorB:GLFloat;
public
procedure Init;
procedure Vertex3f(x,y,z:GLFloat);
procedure TexCoord2f(x,y:GLFloat);
procedure Color3f(r,g,b:GLFloat);
procedure Flush;
end;
implementation
procedure TRenderer.Init;
begin
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnable(GL_COLOR_MATERIAL);
Freemem(VertexArray);vp:=0;
Freemem(TexcoordArray);tp:=0;
Freemem(ColorArray);cp:=0;
VertexArray:=Getmem($1000*3*sizeof(GLFloat));
TexcoordArray:=Getmem($1000*2*sizeof(GLFloat));
ColorArray:=Getmem($1000*3*sizeof(GLFloat));
Vertexes:=0;
Textured:=FALSE;
Colored:=FALSE;
end;
procedure TRenderer.Vertex3f(x,y,z:GLFloat);
begin
if Textured=TRUE then begin
TexCoordArray[tp]:=texcoordX;tp:=tp+1;
TexCoordArray[tp]:=texcoordY;tp:=tp+1;
end;
if Colored=TRUE then begin
ColorArray[cp]:=colorR;cp:=cp+1;
ColorArray[cp]:=colorG;cp:=cp+1;
ColorArray[cp]:=colorB;cp:=cp+1;
end;
Vertexes:=Vertexes+1;
VertexArray[vp]:=x;vp:=vp+1;
VertexArray[vp]:=y;vp:=vp+1;
VertexArray[vp]:=z;vp:=vp+1;
end;
procedure TRenderer.TexCoord2f(x,y:GLFloat);
begin
TexcoordX:=x;
TexcoordY:=y;
Textured:=TRUE;
end;
procedure TRenderer.Color3f(r,g,b:GLFloat);
begin
colorR:=r;
colorG:=g;
colorB:=b;
Colored:=TRUE;
end;
procedure TRenderer.Flush;
begin
if vertexes>0 then begin
if Textured=TRUE then
glTexcoordPointer(2,GL_FLOAT,0,TexcoordArray);
if colored=TRUE then
glColorPointer(3,GL_FLOAT,0,ColorArray);
glVertexPointer(3,GL_FLOAT,0,VertexArray);
glDrawArrays(GL_TRIANGLE_FAN,0,vertexes);
Init();
end;
end;
end. |
unit Main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Spin, Menus, Output, AddRule, EditRule, flRuleStore;
type
{ TfrmMain }
TfrmMain = class(TForm)
btnAddRule: TButton;
btnDropRule: TButton;
btnStart: TButton;
cbDelimiter: TComboBox;
lblCDelimiter: TLabel;
lblCLoops: TLabel;
lblCInput: TLabel;
lblCRules: TLabel;
lbxRules: TListBox;
MainMenu: TMainMenu;
meIn: TMemo;
miSep2: TMenuItem;
miSep1: TMenuItem;
miExit: TMenuItem;
miSave: TMenuItem;
miSaveAs: TMenuItem;
miOpen: TMenuItem;
miNew: TMenuItem;
miFile: TMenuItem;
nudLoops: TSpinEdit;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
procedure btnAddRuleClick(Sender: TObject);
procedure btnDropRuleClick(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure cbDelimiterChange(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure lbxRulesDblClick(Sender: TObject);
procedure miExitClick(Sender: TObject);
procedure miNewClick(Sender: TObject);
procedure miOpenClick(Sender: TObject);
procedure miSaveAsClick(Sender: TObject);
procedure miSaveClick(Sender: TObject);
procedure save(path: String);
procedure refillLbxRules();
private
{ private declarations }
public
{ public declarations }
end;
var
frmMain: TfrmMain;
frmOut: TfrmOut;
ruleStore: TRuleStore;
filePath: String;
implementation
{$R *.lfm}
{ TfrmMain }
procedure TfrmMain.FormCreate(Sender: TObject);
begin
frmOut := TfrmOut.Create(self);
frmOut.Left := frmMain.Left;
frmOut.Top := frmMain.Top + frmMain.Height + 42;
frmOut.Show;
ruleStore := TRuleStore.Create;
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
meIn.Height := self.Height - meIn.Top - 32;
lbxRules.Width := self.Width - 16;
meIn.Width := self.Width - 16;
btnStart.Left := lbxRules.Left + lbxRules.Width - btnStart.Width;
btnStart.Top := lbxRules.Top + lbxRules.Height;
btnAddRule.Top := lbxRules.Top + lbxRules.Height;
btnDropRule.Top := lbxRules.Top + lbxRules.Height;
lblCLoops.Top := lbxRules.Top + lbxRules.Height + 4;
nudLoops.Top := lbxRules.Top + lbxRules.Height + 2;
lblCDelimiter.Top := lbxRules.Top + lbxRules.Height + 4;
cbDelimiter.Top := lbxRules.Top + lbxRules.Height + 2;
lblCInput.Top := lbxRules.Top + lbxRules.Height + 32;
meIn.Top := lbxRules.Top + lbxRules.Height + 48;
end;
procedure TfrmMain.lbxRulesDblClick(Sender: TObject);
var
frmEditRule: TfrmEditRule;
over: Integer;
begin
if lbxRules.ItemIndex > -1 then
begin
frmEditRule := TfrmEditRule.Create(self);
frmEditRule.Top := Round((self.Top + (self.Height / 2)) - (frmEditRule.Height / 2));
over := Round((frmEditRule.Width - self.Width)/2);
if self.Left < over then
frmEditRule.Left := self.Left
else if (self.Left + self.Width + over) > Monitor.Width then
frmEditRule.Left := Round((self.Left - over * 2))
else
frmEditRule.Left := Round((self.Left - over));
frmEditRule.recvData(ruleStore, lbxRules.ItemIndex);
frmEditRule.ShowModal;
refillLbxRules();
end;
end;
procedure TfrmMain.miExitClick(Sender: TObject);
begin
self.close;
end;
procedure TfrmMain.miNewClick(Sender: TObject);
begin
ruleStore.clear;
refillLbxRules();
meIn.Clear;
frmOut.meOut.Clear;
miSave.Enabled := False;
miSave.ShortCut := 0;
miSaveAs.ShortCut := 16467;
self.Caption := 'b+X [Main Window]';
filePath := '';
nudLoops.Value := 10;
cbDelimiter.ItemIndex := 0;
end;
procedure TfrmMain.miOpenClick(Sender: TObject);
var
list: TStringList;
splitList: TStringList;
path: String;
delimiter: String;
rule: String;
i: Integer;
i2: Integer;
begin
OpenDialog.Execute;
path := OpenDialog.FileName;
if path <> '' then
begin
filePath := path;
list := TStringList.Create;
list.LoadFromFile(path);
nudLoops.Value := StrToInt(list[1]);
delimiter := list[2];
if (delimiter <> 'New line') and (delimiter <> 'Space') then
cbDelimiter.ItemIndex := cbDelimiter.Items.Add(delimiter);
i := 4;
rule := list[4];
splitList := TStringList.Create;
while rule <> '[In]' do
begin
splitList.Delimiter := '|';
splitList.DelimitedText := rule;
ruleStore.addRule(splitList[1], StrToFloat(splitList[2]), StrToFloat(splitList[3]));
i := i + 1;
rule := list[i];
end;
for i2 := i + 1 to list.Count - 1 do
meIn.Lines.Add(list[i2]);
meIn.Text := TrimRight(meIn.Text);
list.Free;
splitList.Free;
refillLbxRules();
miSave.Enabled := True;
miSave.ShortCut := 16467;
miSaveAs.ShortCut := 0;
self.Caption := 'b+X [Main Window] - ' + filePath;
end;
end;
procedure TfrmMain.miSaveAsClick(Sender: TObject);
var
path: String;
begin
SaveDialog.Execute;
path := SaveDialog.FileName;
save(path);
end;
procedure TfrmMain.miSaveClick(Sender: TObject);
begin
save(filePath);
end;
procedure TfrmMain.save(path: String);
var
list: TStringList;
i: Integer;
begin
if path <> '""' then
filePath := path;
list := TStringList.Create;
try
list.Add('[Settings]');
list.Add(IntToStr(nudLoops.Value));
list.Add(cbDelimiter.Text);
list.Add('[Rules]');
for i := 0 to ruleStore.getLength() - 1 do
begin
list.Add(IntToStr(i) + '|' + ruleStore.getKeyword(i) +
'|' + FloatToStr(ruleStore.getSeed(i)) +
'|' + FloatToStr(ruleStore.getIncrement(i)));
end;
list.add('[In]');
list.Add(meIn.Text);
list.SaveToFile(filePath);
self.Caption := 'b+X [Main Window] - ' + filePath;
miSave.Enabled := True;
miSave.ShortCut := 16467;
miSaveAs.ShortCut := 0;
finally
end;
end;
procedure TfrmMain.btnAddRuleClick(Sender: TObject);
var
frmAddRule: TfrmAddRule;
over: Integer;
begin
frmAddRule := TfrmAddRule.Create(self);
frmAddRule.Top := Round((self.Top + (self.Height / 2)) - (frmAddRule.Height / 2));
over := Round((frmAddRule.Width - self.Width)/2);
if self.Left < over then
frmAddRule.Left := self.Left
else if (self.Left + self.Width + over) > Monitor.Width then
frmAddRule.Left := Round((self.Left - over * 2))
else
frmAddRule.Left := Round((self.Left - over));
frmAddRule.recvRuleStore(ruleStore);
frmAddRule.ShowModal;
refillLbxRules();
end;
procedure TfrmMain.btnDropRuleClick(Sender: TObject);
begin
ruleStore.deleteRule(lbxRules.ItemIndex);
refillLbxRules();
end;
procedure TfrmMain.btnStartClick(Sender: TObject);
var
i: Integer;
i2: Integer;
tmpStr: String;
delimiter: String;
begin
frmOut.meOut.Lines.Clear;
tmpStr := meIn.Text;
for i := 1 to nudLoops.Value do
begin
tmpStr := meIn.Text;
for i2 := 0 to ruleStore.getLength() - 1 do
begin
tmpStr := StringReplace(tmpStr, '{' + ruleStore.getKeyword(i2) + '}',
FloatToStr((i + ruleStore.getSeed(i2) - 1) * ruleStore.getIncrement(i2)),
[rfReplaceAll]);
end;
if cbDelimiter.ItemIndex = 0 then
delimiter := sLineBreak
else if cbDelimiter.ItemIndex = 1 then
delimiter := ' '
else if cbDelimiter.ItemIndex > 2 then
delimiter := StringReplace(cbDelimiter.Text, '{newline}', sLineBreak, [rfReplaceAll]);
frmOut.meOut.Text := frmOut.meOut.Text + tmpStr + delimiter;
end;
frmOut.meOut.Text := LeftStr(frmOut.meOut.Text, Length(frmOut.meOut.Text) - Length(delimiter));
end;
procedure TfrmMain.cbDelimiterChange(Sender: TObject);
var
input: String;
begin
if cbDelimiter.ItemIndex = 2 then
begin
input := InputBox('b+X [Custom Delimiter]', '{newline} creates a new line.', '');
if input <> '' then
cbDelimiter.ItemIndex := cbDelimiter.Items.Add(input)
else
cbDelimiter.ItemIndex := 0
end;
end;
procedure TfrmMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
if filePath <> '' then
begin
if Application.MessageBox('Save changes?', 'b+X [Message]', 36) = 6 then
save(filePath);
end;
end;
procedure TfrmMain.refillLbxRules();
var
i: Integer;
begin
lbxRules.Items.Clear;
for i := 0 to ruleStore.getLength() - 1 do
lbxRules.Items.Add('{' + ruleStore.getKeyword(i) + '} | Seed: ' +
FloatToStr(ruleStore.getSeed(i)) + ' | Increment: ' +
FloatToStr(ruleStore.getIncrement(i)));
end;
end.
|
unit kwRaise;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwRaise.pas"
// Начат: 29.04.2011 20:25
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::TkwRaise
//
// Зарезервированное слово RAISE. Аналогично raise из Delphi. Если не было исключения, то
// генерируется EtfwScriptException.
// Пример:
// {code}
// TRY
// 'Тестовое исключение' RAISE
// EXCEPT
// true >>> WasException
// END
// {code}
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
tfwScriptingInterfaces
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas}
TkwRaise = class(_tfwAutoregisteringWord_)
{* Зарезервированное слово RAISE. Аналогично raise из Delphi. Если не было исключения, то генерируется EtfwScriptException.
Пример:
[code]
TRY
'Тестовое исключение' RAISE
EXCEPT
true >>> WasException
END
[code] }
protected
// realized methods
procedure DoDoIt(const aCtx: TtfwContext); override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwRaise
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
SysUtils,
tfwAutoregisteredDiction,
tfwScriptEngine
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwRaise;
{$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas}
// start class TkwRaise
procedure TkwRaise.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_4DBAE64F02F7_var*
type
RException = class of Exception;
//#UC END# *4DAEEDE10285_4DBAE64F02F7_var*
begin
//#UC START# *4DAEEDE10285_4DBAE64F02F7_impl*
if (aCtx.rException <> nil) then
raise RException(aCtx.rException.ClassType).Create(aCtx.rException.Message)
else
raise EtfwScriptException.Create(aCtx.rEngine.PopDelphiString);
//#UC END# *4DAEEDE10285_4DBAE64F02F7_impl*
end;//TkwRaise.DoDoIt
class function TkwRaise.GetWordNameForRegister: AnsiString;
//#UC START# *4DB0614603C8_4DBAE64F02F7_var*
//#UC END# *4DB0614603C8_4DBAE64F02F7_var*
begin
//#UC START# *4DB0614603C8_4DBAE64F02F7_impl*
Result := 'RAISE';
//#UC END# *4DB0614603C8_4DBAE64F02F7_impl*
end;//TkwRaise.GetWordNameForRegister
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas}
{$IfEnd} //not NoScripts
end. |
{$IFDEF DeclarationPart}
{==============================================================================}
{------------------------------------------------------------------------------}
{ Muticast events managers }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TMulticastLogEvent // Class declaration }
{==============================================================================}
{
@abstract(Class used to manage multicast event called when recipient writes
to game log.)
@member(IndexOf
Returns index at which the handler is stored in internal list of handlers.
@param Handler Handler routine whose index is requested.
@returns Index of passed handler in the list, -1 when not found..)
@member(Add
Adds passed handler to internal list of handlers. When @code(AllowDuplicity)
is set to @true, the handler is added to the list even when it is already
stored, when set to @false, no new list item is added and result contains
index of previous occurrence of passed handler routine in the list.
@param Handler New handler routine to be added.
@param(AllowDuplicity Denotes whether passed routine can be stored in
internal list when already in it.)
@returns(Index at which the added routine is stored. -1 when storing has
failed.))
@member(Remove
Removes first or all occurrences, depending on @code(RemoveAll) value, of
passed routine from internal list of handlers.
@param Handler Routine to be removed from the list.
@param(RemoveAll Determines whether to @noAutoLink(remove) only first
occurence of passed handler or all of them.)
@returns(Index at which the removed item was stored in the list, -1 when
passed routine was not found.))
@member(Call
Calls all stored handler routines with the same parameters as passed to this
method.)
}
TMulticastLogEvent = class(TMulticastEvent)
public
Function IndexOf(const Handler: TLogEvent): Integer; reintroduce;
Function Add(const Handler: TLogEvent; AllowDuplicity: Boolean = False): Integer; reintroduce;
Function Remove(const Handler: TLogEvent; RemoveAll: Boolean = True): Integer; reintroduce;
procedure Call(Sender: TObject; LogType: scs_log_type_t; const LogText: String); reintroduce;
end;
{==============================================================================}
{ TMulticastEventRegisterEvent // Class declaration }
{==============================================================================}
{
@abstract(Class used to manage multicast event called when telemetry event is
registered or unregistered.)
@member(IndexOf
Returns index at which the handler is stored in internal list of handlers.
@param Handler Handler routine whose index is requested.
@returns Index of passed handler in the list, -1 when not found..)
@member(Add
Adds passed handler to internal list of handlers. When @code(AllowDuplicity)
is set to @true, the handler is added to the list even when it is already
stored, when set to @false, no new list item is added and result contains
index of previous occurrence of passed handler routine in the list.
@param Handler New handler routine to be added.
@param(AllowDuplicity Denotes whether passed routine can be stored in
internal list when already in it.)
@returns(Index at which the added routine is stored. -1 when storing has
failed.))
@member(Remove
Removes first or all occurrences, depending on @code(RemoveAll) value, of
passed routine from internal list of handlers.
@param Handler Routine to be removed from the list.
@param(RemoveAll Determines whether to @noAutoLink(remove) only first
occurence of passed handler or all of them.)
@returns(Index at which the removed item was stored in the list, -1 when
passed routine was not found.))
@member(Call
Calls all stored handler routines with the same parameters as passed to this
method.)
}
TMulticastEventRegisterEvent = class(TMulticastEvent)
public
Function IndexOf(const Handler: TEventRegisterEvent): Integer; reintroduce;
Function Add(const Handler: TEventRegisterEvent; AllowDuplicity: Boolean = False): Integer; reintroduce;
Function Remove(const Handler: TEventRegisterEvent; RemoveAll: Boolean = True): Integer; reintroduce;
procedure Call(Sender: TObject; Event: scs_event_t); reintroduce;
end;
{==============================================================================}
{ TMulticastEventEvent // Class declaration }
{==============================================================================}
{
@abstract(Class used to manage multicast event called when telemetry when
telemetery event occurs.)
@member(IndexOf
Returns index at which the handler is stored in internal list of handlers.
@param Handler Handler routine whose index is requested.
@returns Index of passed handler in the list, -1 when not found..)
@member(Add
Adds passed handler to internal list of handlers. When @code(AllowDuplicity)
is set to @true, the handler is added to the list even when it is already
stored, when set to @false, no new list item is added and result contains
index of previous occurrence of passed handler routine in the list.
@param Handler New handler routine to be added.
@param(AllowDuplicity Denotes whether passed routine can be stored in
internal list when already in it.)
@returns(Index at which the added routine is stored. -1 when storing has
failed.))
@member(Remove
Removes first or all occurrences, depending on @code(RemoveAll) value, of
passed routine from internal list of handlers.
@param Handler Routine to be removed from the list.
@param(RemoveAll Determines whether to @noAutoLink(remove) only first
occurence of passed handler or all of them.)
@returns(Index at which the removed item was stored in the list, -1 when
passed routine was not found.))
@member(Call
Calls all stored handler routines with the same parameters as passed to this
method.)
}
TMulticastEventEvent = class(TMulticastEvent)
public
Function IndexOf(const Handler: TEventEvent): Integer; reintroduce;
Function Add(const Handler: TEventEvent; AllowDuplicity: Boolean = False): Integer; reintroduce;
Function Remove(const Handler: TEventEvent; RemoveAll: Boolean = True): Integer; reintroduce;
procedure Call(Sender: TObject; Event: scs_event_t; Data: Pointer); reintroduce;
end;
{==============================================================================}
{ TMulticastChannelRegisterEvent // Class declaration }
{==============================================================================}
{
@abstract(Class used to manage multicast event called when telemetry channel
is registered.)
@member(IndexOf
Returns index at which the handler is stored in internal list of handlers.
@param Handler Handler routine whose index is requested.
@returns Index of passed handler in the list, -1 when not found..)
@member(Add
Adds passed handler to internal list of handlers. When @code(AllowDuplicity)
is set to @true, the handler is added to the list even when it is already
stored, when set to @false, no new list item is added and result contains
index of previous occurrence of passed handler routine in the list.
@param Handler New handler routine to be added.
@param(AllowDuplicity Denotes whether passed routine can be stored in
internal list when already in it.)
@returns(Index at which the added routine is stored. -1 when storing has
failed.))
@member(Remove
Removes first or all occurrences, depending on @code(RemoveAll) value, of
passed routine from internal list of handlers.
@param Handler Routine to be removed from the list.
@param(RemoveAll Determines whether to @noAutoLink(remove) only first
occurence of passed handler or all of them.)
@returns(Index at which the removed item was stored in the list, -1 when
passed routine was not found.))
@member(Call
Calls all stored handler routines with the same parameters as passed to this
method.)
}
TMulticastChannelRegisterEvent = class(TMulticastEvent)
public
Function IndexOf(const Handler: TChannelRegisterEvent): Integer; reintroduce;
Function Add(const Handler: TChannelRegisterEvent; AllowDuplicity: Boolean = False): Integer; reintroduce;
Function Remove(const Handler: TChannelRegisterEvent; RemoveAll: Boolean = True): Integer; reintroduce;
procedure Call(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t); reintroduce;
end;
{==============================================================================}
{ TMulticastChannelUnregisterEvent // Class declaration }
{==============================================================================}
{
@abstract(Class used to manage multicast event called when telemetry channel
is unregistered.)
@member(IndexOf
Returns index at which the handler is stored in internal list of handlers.
@param Handler Handler routine whose index is requested.
@returns Index of passed handler in the list, -1 when not found..)
@member(Add
Adds passed handler to internal list of handlers. When @code(AllowDuplicity)
is set to @true, the handler is added to the list even when it is already
stored, when set to @false, no new list item is added and result contains
index of previous occurrence of passed handler routine in the list.
@param Handler New handler routine to be added.
@param(AllowDuplicity Denotes whether passed routine can be stored in
internal list when already in it.)
@returns(Index at which the added routine is stored. -1 when storing has
failed.))
@member(Remove
Removes first or all occurrences, depending on @code(RemoveAll) value, of
passed routine from internal list of handlers.
@param Handler Routine to be removed from the list.
@param(RemoveAll Determines whether to @noAutoLink(remove) only first
occurence of passed handler or all of them.)
@returns(Index at which the removed item was stored in the list, -1 when
passed routine was not found.))
@member(Call
Calls all stored handler routines with the same parameters as passed to this
method.)
}
TMulticastChannelUnregisterEvent = class(TMulticastEvent)
public
Function IndexOf(const Handler: TChannelUnregisterEvent): Integer; reintroduce;
Function Add(const Handler: TChannelUnregisterEvent; AllowDuplicity: Boolean = False): Integer; reintroduce;
Function Remove(const Handler: TChannelUnregisterEvent; RemoveAll: Boolean = True): Integer; reintroduce;
procedure Call(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t); reintroduce;
end;
{==============================================================================}
{ TMulticastChannelEvent // Class declaration }
{==============================================================================}
{
@abstract(Class used to manage multicast event called when telemetery channel
callback occurs.)
@member(IndexOf
Returns index at which the handler is stored in internal list of handlers.
@param Handler Handler routine whose index is requested.
@returns Index of passed handler in the list, -1 when not found..)
@member(Add
Adds passed handler to internal list of handlers. When @code(AllowDuplicity)
is set to @true, the handler is added to the list even when it is already
stored, when set to @false, no new list item is added and result contains
index of previous occurrence of passed handler routine in the list.
@param Handler New handler routine to be added.
@param(AllowDuplicity Denotes whether passed routine can be stored in
internal list when already in it.)
@returns(Index at which the added routine is stored. -1 when storing has
failed.))
@member(Remove
Removes first or all occurrences, depending on @code(RemoveAll) value, of
passed routine from internal list of handlers.
@param Handler Routine to be removed from the list.
@param(RemoveAll Determines whether to @noAutoLink(remove) only first
occurence of passed handler or all of them.)
@returns(Index at which the removed item was stored in the list, -1 when
passed routine was not found.))
@member(Call
Calls all stored handler routines with the same parameters as passed to this
method.)
}
TMulticastChannelEvent = class(TMulticastEvent)
public
Function IndexOf(const Handler: TChannelEvent): Integer; reintroduce;
Function Add(const Handler: TChannelEvent; AllowDuplicity: Boolean = False): Integer; reintroduce;
Function Remove(const Handler: TChannelEvent; RemoveAll: Boolean = True): Integer; reintroduce;
procedure Call(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t); reintroduce;
end;
{==============================================================================}
{ TMulticastConfigEvent // Class declaration }
{==============================================================================}
{
@abstract(Class used to manage multicast event called when config is parsed
from configuration telemetry event.)
@member(IndexOf
Returns index at which the handler is stored in internal list of handlers.
@param Handler Handler routine whose index is requested.
@returns Index of passed handler in the list, -1 when not found..)
@member(Add
Adds passed handler to internal list of handlers. When @code(AllowDuplicity)
is set to @true, the handler is added to the list even when it is already
stored, when set to @false, no new list item is added and result contains
index of previous occurrence of passed handler routine in the list.
@param Handler New handler routine to be added.
@param(AllowDuplicity Denotes whether passed routine can be stored in
internal list when already in it.)
@returns(Index at which the added routine is stored. -1 when storing has
failed.))
@member(Remove
Removes first or all occurrences, depending on @code(RemoveAll) value, of
passed routine from internal list of handlers.
@param Handler Routine to be removed from the list.
@param(RemoveAll Determines whether to @noAutoLink(remove) only first
occurence of passed handler or all of them.)
@returns(Index at which the removed item was stored in the list, -1 when
passed routine was not found.))
@member(Call
Calls all stored handler routines with the same parameters as passed to this
method.)
}
TMulticastConfigEvent = class(TMulticastEvent)
public
Function IndexOf(const Handler: TConfigEvent): Integer; reintroduce;
Function Add(const Handler: TConfigEvent; AllowDuplicity: Boolean = False): Integer; reintroduce;
Function Remove(const Handler: TConfigEvent; RemoveAll: Boolean = True): Integer; reintroduce;
procedure Call(Sender: TObject; const Name: TelemetryString; ID: TConfigID; Index: scs_u32_t; Value: scs_value_localized_t); reintroduce;
end;
{$ENDIF}
{$IFDEF ImplementationPart}
{==============================================================================}
{------------------------------------------------------------------------------}
{ Muticast events managers }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TMulticastLogEvent // Class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMulticastLogEvent // Public methods }
{------------------------------------------------------------------------------}
Function TMulticastLogEvent.IndexOf(const Handler: TLogEvent): Integer;
begin
Result := inherited IndexOf(TEvent(Handler));
end;
//------------------------------------------------------------------------------
Function TMulticastLogEvent.Add(const Handler: TLogEvent; AllowDuplicity: Boolean = False): Integer;
begin
Result := inherited Add(TEvent(Handler),AllowDuplicity);
end;
//------------------------------------------------------------------------------
Function TMulticastLogEvent.Remove(const Handler: TLogEvent; RemoveAll: Boolean = True): Integer;
begin
Result := inherited Remove(TEvent(Handler),RemoveAll);
end;
//------------------------------------------------------------------------------
procedure TMulticastLogEvent.Call(Sender: TObject; LogType: scs_log_type_t; const LogText: String);
var
i: Integer;
begin
For i := 0 to Pred(Count) do TLogEvent(Methods[i])(Sender,LogType,LogText);
end;
{==============================================================================}
{ TMulticastEventRegisterEvent // Class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMulticastEventRegisterEvent // Public methods }
{------------------------------------------------------------------------------}
Function TMulticastEventRegisterEvent.IndexOf(const Handler: TEventRegisterEvent): Integer;
begin
Result := inherited IndexOf(TEvent(Handler));
end;
//------------------------------------------------------------------------------
Function TMulticastEventRegisterEvent.Add(const Handler: TEventRegisterEvent; AllowDuplicity: Boolean = False): Integer;
begin
Result := inherited Add(TEvent(Handler),AllowDuplicity);
end;
//------------------------------------------------------------------------------
Function TMulticastEventRegisterEvent.Remove(const Handler: TEventRegisterEvent; RemoveAll: Boolean = True): Integer;
begin
Result := inherited Remove(TEvent(Handler),RemoveAll);
end;
//------------------------------------------------------------------------------
procedure TMulticastEventRegisterEvent.Call(Sender: TObject; Event: scs_event_t);
var
i: Integer;
begin
For i := 0 to Pred(Count) do TEventRegisterEvent(Methods[i])(Sender,Event);
end;
{==============================================================================}
{ TMulticastEventEvent // Class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMulticastEventEvent // Public methods }
{------------------------------------------------------------------------------}
Function TMulticastEventEvent.IndexOf(const Handler: TEventEvent): Integer;
begin
Result := inherited IndexOf(TEvent(Handler));
end;
//------------------------------------------------------------------------------
Function TMulticastEventEvent.Add(const Handler: TEventEvent; AllowDuplicity: Boolean = False): Integer;
begin
Result := inherited Add(TEvent(Handler),AllowDuplicity);
end;
//------------------------------------------------------------------------------
Function TMulticastEventEvent.Remove(const Handler: TEventEvent; RemoveAll: Boolean = True): Integer;
begin
Result := inherited Remove(TEvent(Handler),RemoveAll);
end;
//------------------------------------------------------------------------------
procedure TMulticastEventEvent.Call(Sender: TObject; Event: scs_event_t; Data: Pointer);
var
i: Integer;
begin
For i := 0 to Pred(Count) do TEventEvent(Methods[i])(Sender,Event,Data);
end;
{==============================================================================}
{ TMulticastChannelRegisterEvent // Class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMulticastChannelRegisterEvent // Public methods }
{------------------------------------------------------------------------------}
Function TMulticastChannelRegisterEvent.IndexOf(const Handler: TChannelRegisterEvent): Integer;
begin
Result := inherited IndexOf(TEvent(Handler));
end;
//------------------------------------------------------------------------------
Function TMulticastChannelRegisterEvent.Add(const Handler: TChannelRegisterEvent; AllowDuplicity: Boolean = False): Integer;
begin
Result := inherited Add(TEvent(Handler),AllowDuplicity);
end;
//------------------------------------------------------------------------------
Function TMulticastChannelRegisterEvent.Remove(const Handler: TChannelRegisterEvent; RemoveAll: Boolean = True): Integer;
begin
Result := inherited Remove(TEvent(Handler),RemoveAll);
end;
//------------------------------------------------------------------------------
procedure TMulticastChannelRegisterEvent.Call(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t);
var
i: Integer;
begin
For i := 0 to Pred(Count) do TChannelRegisterEvent(Methods[i])(Sender,Name,ID,Index,ValueType,Flags);
end;
{==============================================================================}
{ TMulticastChannelUnregisterEvent // Class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMulticastChannelUnregisterEvent // Public methods }
{------------------------------------------------------------------------------}
Function TMulticastChannelUnregisterEvent.IndexOf(const Handler: TChannelUnregisterEvent): Integer;
begin
Result := inherited IndexOf(TEvent(Handler));
end;
//------------------------------------------------------------------------------
Function TMulticastChannelUnregisterEvent.Add(const Handler: TChannelUnregisterEvent; AllowDuplicity: Boolean = False): Integer;
begin
Result := inherited Add(TEvent(Handler),AllowDuplicity);
end;
//------------------------------------------------------------------------------
Function TMulticastChannelUnregisterEvent.Remove(const Handler: TChannelUnregisterEvent; RemoveAll: Boolean = True): Integer;
begin
Result := inherited Remove(TEvent(Handler),RemoveAll);
end;
//------------------------------------------------------------------------------
procedure TMulticastChannelUnregisterEvent.Call(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t);
var
i: Integer;
begin
For i := 0 to Pred(Count) do TChannelUnregisterEvent(Methods[i])(Sender,Name,ID,Index,ValueType);
end;
{==============================================================================}
{ TMulticastChannelEvent // Class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMulticastChannelEvent // Public methods }
{------------------------------------------------------------------------------}
Function TMulticastChannelEvent.IndexOf(const Handler: TChannelEvent): Integer;
begin
Result := inherited IndexOf(TEvent(Handler));
end;
//------------------------------------------------------------------------------
Function TMulticastChannelEvent.Add(const Handler: TChannelEvent; AllowDuplicity: Boolean = False): Integer;
begin
Result := inherited Add(TEvent(Handler),AllowDuplicity);
end;
//------------------------------------------------------------------------------
Function TMulticastChannelEvent.Remove(const Handler: TChannelEvent; RemoveAll: Boolean = True): Integer;
begin
Result := inherited Remove(TEvent(Handler),RemoveAll);
end;
//------------------------------------------------------------------------------
procedure TMulticastChannelEvent.Call(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t);
var
i: Integer;
begin
For i := 0 to Pred(Count) do TChannelEvent(Methods[i])(Sender,Name,ID,Index,Value);
end;
{==============================================================================}
{ TMulticastConfigEvent // Class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TMulticastConfigEvent // Public methods }
{------------------------------------------------------------------------------}
Function TMulticastConfigEvent.IndexOf(const Handler: TConfigEvent): Integer;
begin
Result := inherited IndexOf(TEvent(Handler));
end;
//------------------------------------------------------------------------------
Function TMulticastConfigEvent.Add(const Handler: TConfigEvent; AllowDuplicity: Boolean = False): Integer;
begin
Result := inherited Add(TEvent(Handler),AllowDuplicity);
end;
//------------------------------------------------------------------------------
Function TMulticastConfigEvent.Remove(const Handler: TConfigEvent; RemoveAll: Boolean = True): Integer;
begin
Result := inherited Remove(TEvent(Handler),RemoveAll);
end;
//------------------------------------------------------------------------------
procedure TMulticastConfigEvent.Call(Sender: TObject; const Name: TelemetryString; ID: TConfigID; Index: scs_u32_t; Value: scs_value_localized_t);
var
i: Integer;
begin
For i := 0 to Pred(Count) do TConfigEvent(Methods[i])(Sender,Name,ID,Index,Value);
end;
{$ENDIF}
|
unit uCadastroForncedor;
interface
uses System.Classes,
Vcl.Controls,
Vcl.ExtCtrls,
Vcl.Dialogs,
ZAbstractConnection,
ZConnection,
ZAbstractRODataset,
ZAbstractDataset,
ZDataset,
System.SysUtils;
type
TFornecedor = class
private
ConexaoDB:TZConnection;
F_clienteId:Integer; //Int
F_nome:String; //VarChar
F_endereco: string;
F_cidade:String;
F_bairro: String;
F_estado: string;
F_cep: String;
F_telefone1: string;
F_email: string;
F_telefone2: string;
F_CNPJ: string;
F_RazaoSocial: string;
F_Fantasia: string;
F_CodEmpresa: Integer;
F_Numero :Integer;
public
constructor Create(aConexao:TZConnection);
destructor Destroy; override;
function Inserir:Boolean;
function Atualizar:Boolean;
function Apagar:Boolean;
function Selecionar(id:Integer):Boolean;
published
property CodFornecedor :Integer read F_CodEmpresa write F_CodEmpresa;
property CNPJ :string read F_CNPJ write F_CNPJ;
property RazaoSocial :string read F_RazaoSocial write F_RazaoSocial;
property Fantasia :string read F_Fantasia write F_Fantasia;
property endereco :string read F_endereco write F_endereco;
property cidade :string read F_cidade write F_cidade;
property bairro :string read F_bairro write F_bairro;
property estado :string read F_estado write F_Estado;
property cep :string read F_cep write F_Cep;
property telefone1 :string read F_telefone1 write F_telefone1;
property telefone2 :string read F_telefone2 write F_telefone2;
property Numero :Integer read F_Numero write F_Numero;
property Nome :string read F_nome write F_nome;
property Email :string read F_email write F_email;
end;
implementation
{ TCategoria }
{$region 'Constructor and Destructor'}
constructor TFornecedor.Create(aConexao:TZConnection);
begin
ConexaoDB:=aConexao;
end;
destructor TFornecedor.Destroy;
begin
inherited;
end;
{$endRegion}
{$region 'CRUD'}
function TFornecedor.Apagar: Boolean;
var Qry:TZQuery;
begin
if MessageDlg('Apagar o Registro: '+#13+#13+
'Código: '+IntToStr(F_CodEmpresa)+#13+
'Descrição: '+F_nome,mtConfirmation,[mbYes, mbNo],0)=mrNo then begin
Result:=false;
abort;
end;
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM FORNECEDOR '+
' WHERE FORN_cod=:FORN_Cod ');
Qry.ParamByName('FORN_Cod').AsInteger :=CodFornecedor;
Try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
Except
ConexaoDB.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TFornecedor.Atualizar: Boolean;
var Qry:TZQuery;
begin
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE FORNECEDOR '+
' SET Forn_RAZAOSOCIAL =:RAZAO '+
' ,FORN_FANTASIA =:FANTASIA '+
' ,FORN_ENDERECO =:endereco '+
' ,FORN_Cidade =:cidade '+
' ,FORN_Bairro =:bairro '+
' ,FORN_UF =:estado '+
' ,FORN_Cep =:cep '+
' ,FORN_Telefone1 =:telefone1 '+
' ,FORN_Telefone2 =:telefone2 '+
' ,FORN_Numero =:Numero '+
' ,FORN_Nome =:Nome '+
' ,Forn_Email =:Email '+
' ,Forn_Cnpj =:Cnpj '+
' WHERE FORN_Cod=:FORN_Cod ');
Qry.ParamByName('FORN_COD').AsInteger :=Self.F_CodEmpresa;
Qry.ParamByName('RAZAO').AsString :=Self.F_RazaoSocial;
Qry.ParamByName('FANTASIA').AsString :=Self.Fantasia;
Qry.ParamByName('endereco').AsString :=Self.F_endereco;
Qry.ParamByName('cidade').AsString :=Self.F_cidade;
Qry.ParamByName('bairro').AsString :=Self.F_bairro;
Qry.ParamByName('estado').AsString :=Self.F_estado;
Qry.ParamByName('cep').AsString :=Self.F_cep;
Qry.ParamByName('telefone1').AsString :=Self.F_telefone1;
Qry.ParamByName('telefone2').AsString :=Self.F_telefone2;
Qry.ParamByName('email').AsString :=Self.F_email;
Qry.ParamByName('numero').AsInteger :=Self.F_Numero;
Qry.ParamByName('nome').AsString :=Self.F_Nome;
Qry.ParamByName('Email').AsString :=Self.Email;
Qry.ParamByName('Cnpj').AsString :=Self.Cnpj;
Try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
Except
ConexaoDB.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TFornecedor.Inserir: Boolean;
var Qry:TZQuery;
begin
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO FORNECEDOR ( '+
' Forn_RAZAOSOCIAL '+
' ,FORN_FANTASIA '+
' ,FORN_ENDERECO '+
' ,FORN_Cidade '+
' ,FORN_Bairro '+
' ,FORN_UF '+
' ,FORN_Cep '+
' ,FORN_Telefone1 '+
' ,FORN_Telefone2 '+
' ,FORN_Nome '+
' ,FORN_NUMERO '+
' ,FORN_EMAIL '+
' ,FORN_CNPJ) '+
'values( '+
' :RAZAO, '+
' :FANTASIA, '+
' :endereco, '+
' :cidade, '+
' :bairro, '+
' :estado, '+
' :cep, '+
' :telefone1, '+
' :telefone2, '+
' :Nome, '+
' :numero, '+
' :email, '+
' :cnpj) ');
Qry.ParamByName('Razao').AsString :=Self.F_RazaoSocial;
Qry.ParamByName('Fantasia').AsString :=Self.F_Fantasia;
Qry.ParamByName('endereco').AsString :=Self.F_endereco;
Qry.ParamByName('cidade').AsString :=Self.F_cidade;
Qry.ParamByName('bairro').AsString :=Self.F_bairro;
Qry.ParamByName('estado').AsString :=Self.F_estado;
Qry.ParamByName('cep').AsString :=Self.F_cep;
Qry.ParamByName('telefone1').AsString :=Self.F_telefone1;
Qry.ParamByName('Telefone2').AsString := Self.F_telefone2;
Qry.ParamByName('Nome').AsString :=Self.F_Nome;
Qry.ParamByName('Numero').AsInteger :=Self.F_Numero;
Qry.ParamByName('email').AsString :=Self.F_email;
Qry.ParamByname('cnpj').AsString :=Self.CNPJ;
Try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
Except
ConexaoDB.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TFornecedor.Selecionar(id: Integer): Boolean;
var Qry:TZQuery;
begin
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT FORN_Cod,'+
' Forn_RAZAOSOCIAL, '+
' FORN_FANTASIA, '+
' FORN_Endereco, '+
' FORN_Cidade, '+
' FORN_Bairro, '+
' FORN_UF, '+
' FORN_Cep, '+
' FORN_Telefone1, '+
' FORN_Telefone2, '+
' FORN_Nome, '+
' FORN_Numero,'+
' FORN_Email' +
' FROM FORNECEDOR '+
' WHERE FORN_Cod=:FORN_Cod');
Qry.ParamByName('FORN_Cod').AsInteger:=id;
Try
Qry.Open;
Self.F_CodEmpresa := Qry.FieldByName('FORN_Cod').AsInteger;
Self.F_RazaoSocial := Qry.FieldByName('Forn_RAZAOSOCIAL').AsString;
Self.F_Fantasia := Qry.FieldByName('FORN_FANTASIA').AsString;
Self.F_endereco := Qry.FieldByName('FORN_Endereco').AsString;
Self.F_cidade := Qry.FieldByName('FORN_Cidade').AsString;
Self.F_bairro := Qry.FieldByName('FORN_Bairro').AsString;
Self.F_estado := Qry.FieldByName('FORN_UF').AsString;
Self.F_cep := Qry.FieldByName('FORN_Cep').AsString;
Self.F_telefone1 := Qry.FieldByName('FORN_Telefone1').AsString;
Self.F_telefone2 := Qry.FieldByName('FORN_Telefone2').AsString;
Self.F_nome := Qry.FieldByName('FORN_Nome').AsString;
Self.F_Numero := Qry.FieldByName('FORN_Numero').AsInteger;
Self.F_email := Qry.FieldByName('FORN_Email').AsString;
Except
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
{$endregion}
end.
|
unit UCM;
interface
uses
System.SysUtils, System.Classes, proxy, IPPeerClient,
Datasnap.DSClientRest, USistema;
type
TFCM = class(TDataModule)
DSRestConnection1: TDSRestConnection;
private
FInstanceOwner: Boolean;
FMetodosClienteClient: TMetodosClienteClient;
FMetodosGeraisClient: TMetodosGeraisClient;
function GetMetodosClienteClient: TMetodosClienteClient;
function GetMetodosGeraisClient: TMetodosGeraisClient;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property InstanceOwner: Boolean read FInstanceOwner write FInstanceOwner;
property MetodosClienteClient: TMetodosClienteClient read GetMetodosClienteClient write FMetodosClienteClient;
property MetodosGeraisClient: TMetodosGeraisClient read GetMetodosGeraisClient write FMetodosGeraisClient;
end;
var
FCM: TFCM;
implementation
uses
Vcl.Dialogs;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
constructor TFCM.Create(AOwner: TComponent);
begin
inherited;
FInstanceOwner := True;
end;
destructor TFCM.Destroy;
begin
Try
FMetodosClienteClient.Free;
Except on E:Exception Do
Begin
Showmessage('Erro ao liberar FMetodosCliente'+#13+E.Message);
End;
End;
Try
FMetodosGeraisClient.Free;
Except on E:Exception Do
Begin
Showmessage('Erro ao liberar FMetodosGerais'+#13+E.Message);
End;
End;
inherited;
end;
function TFCM.GetMetodosClienteClient: TMetodosClienteClient;
begin
if FMetodosClienteClient = nil then
FMetodosClienteClient:= TMetodosClienteClient.Create(DSRestConnection1, FInstanceOwner);
Result := FMetodosClienteClient;
end;
function TFCM.GetMetodosGeraisClient: TMetodosGeraisClient;
begin
if FMetodosGeraisClient = nil then
FMetodosGeraisClient:= TMetodosGeraisClient.Create(DSRestConnection1, FInstanceOwner);
Result := FMetodosGeraisClient;
end;
end.
|
unit EncodStr;
interface
uses
Classes;
type
TEncodedStream = class (TFileStream)
private
FKey: Char;
public
constructor Create(const FileName: string; Mode: Word);
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
property Key: Char read FKey write FKey default 'A';
end;
implementation
constructor TEncodedStream.Create(
const FileName: string; Mode: Word);
begin
inherited Create (FileName, Mode);
FKey := 'A';
end;
function TEncodedStream.Write(const Buffer;
Count: Longint): Longint;
var
pBuf, pEnc: PChar;
I, EncVal: Integer;
begin
// allocate memory for the encoded buffer
GetMem (pEnc, Count);
try
// use the buffer as an array of characters
pBuf := PChar (@Buffer);
// for every character of the buffer
for I := 0 to Count - 1 do
begin
// encode the value and store it
EncVal := ( Ord (pBuf[I]) + Ord(Key) ) mod 256;
pEnc [I] := Chr (EncVal);
end;
// write the encoded buffer to the file
Result := inherited Write (pEnc^, Count);
finally
FreeMem (pEnc, Count);
end;
end;
function TEncodedStream.Read(var Buffer; Count: Longint): Longint;
var
pBuf, pEnc: PChar;
I, CountRead, EncVal: Integer;
begin
// allocate memory for the encoded buffer
GetMem (pEnc, Count);
try
// read the encoded buffer from the file
CountRead := inherited Read (pEnc^, Count);
// use the output buffer as a string
pBuf := PChar (@Buffer);
// for every character actually read
for I := 0 to CountRead - 1 do
begin
// decode the value and store it
EncVal := ( Ord (pEnc[I]) - Ord(Key) ) mod 256;
pBuf [I] := Chr (EncVal);
end;
finally
FreeMem (pEnc, Count);
end;
// return the number of characters read
Result := CountRead;
end;
end.
|
unit Automaton;
interface
uses
Classes, ActorTypes, ActorPool, StateEngine, DistributedStates;
type
IAutomationEngine =
interface
procedure LaunchState( Launcher, State : TStateId; aCPL : integer; Frequency : integer; LauncherBehavior : TLauncherBehaviour );
procedure ThrowEvent ( anEvent : TDistributedEvent );
end;
IAutomatable =
interface
procedure Act( State : TStateId; Mode : TActMode );
function HandleEvent( anEvent : TDistributedEvent ) : boolean;
procedure Dispatch( var Msg );
end;
IServerAutomatable =
interface( IAutomatable )
procedure SetAutomationEngine( anEngine : IAutomationEngine );
procedure SetActor( anActor : IServerActor );
function GetActor : IServerActor;
procedure Store( Stream : TStream );
end;
IClientAutomatable =
interface( IAutomatable )
procedure Load( Stream : TStream );
procedure Deleted;
end;
type
TMetaAutomaton = class;
TAutomaton = class;
TServerAutomaton = class;
TClientAutomaton = class;
CAutomaton = class of TAutomaton;
CServerAutomaton = class of TServerAutomaton;
CClientAutomaton = class of TClientAutomaton;
TServerAutomatableFactory = function( Kind : TActorKind; const Context ) : IServerAutomatable;
TClientAutomatableFactory = function( Kind : TActorKind; const Context ) : IClientAutomatable;
TMetaAutomaton =
class
public
constructor Create( aKind : TActorKind;
aPoolId : TActorPoolId;
aAutomatonClass : CAutomaton;
aBehavior : TMetaStatePool );
private
fKind : TActorKind;
fPoolId : TActorPoolId;
fAutomatonClass : CAutomaton;
fBehavior : TMetaStatePool;
public
property Kind : TActorKind read fKind;
property PoolId : TActorPoolId read fPoolId;
property AutomatonClass : CAutomaton read fAutomatonClass;
property Behavior : TMetaStatePool read fBehavior;
public
function Instantiate( AutomatonId : TActorId ) : TAutomaton;
public
procedure Register;
end;
TMetaServerAutomaton =
class( TMetaAutomaton )
public
constructor Create( aKind : TActorKind;
aPoolId : TActorPoolId;
aAutomatonClass : CServerAutomaton;
aBehavior : TMetaStatePool;
aAutomatableFactory : TServerAutomatableFactory );
private
fAutomatableFactory : TServerAutomatableFactory;
public
function Instantiate( AutomatonId : TActorId; const Context ) : TServerAutomaton;
function InstantiateAutomatable( const Context ) : IServerAutomatable;
end;
TMetaClientAutomaton =
class( TMetaAutomaton )
public
constructor Create( aKind : TActorKind;
aPoolId : TActorPoolId;
aAutomatonClass : CClientAutomaton;
aBehavior : TMetaStatePool;
aAutomatableFactory : TClientAutomatableFactory );
private
fAutomatableFactory : TClientAutomatableFactory;
public
function Instantiate( AutomatonId : TActorId; const Context ) : TClientAutomaton;
function InstantiateAutomatable( const Context ) : IClientAutomatable;
end;
TAutomaton =
class( TInterfacedObject, IActor )
protected
constructor Create( aMetaAutomaton : TMetaAutomaton; anId : TActorId ); virtual;
private
fMetaAutomaton : TMetaAutomaton;
fId : TActorId;
protected
function GetAutomatable : IAutomatable; virtual; abstract;
public
property MetaAutomaton : TMetaAutomaton read fMetaAutomaton;
property Id : TActorId read fId;
property Automatable : IAutomatable read GetAutomatable;
protected
procedure Act( State : TStateId; Mode : TActMode ); virtual; abstract;
// IActor
private
function getId : TActorId;
function getKind : TActorKind;
// Pool events
private
procedure StateModified( State : TState; Modification : TStateModification );
end;
TServerAutomaton =
class( TAutomaton, IServerActor, IAutomationEngine )
protected
constructor Create( aMetaAutomaton : TMetaAutomaton; anId : TActorId ); override;
public
destructor Destroy; override;
private
fAutomatable : IServerAutomatable;
fStatePool : TServerStatePool;
protected
function GetAutomatable : IAutomatable; override;
public
property Automatable : IServerAutomatable read fAutomatable write fAutomatable;
protected
procedure Act( State : TStateId; Mode : TActMode ); override;
// IAutomationEngine
protected
procedure LaunchState( Launcher, State : TStateId; aCPL : integer; Frequency : integer; LauncherBehavior : TLauncherBehaviour );
procedure ThrowEvent ( anEvent : TDistributedEvent );
// IServerActor
private
function getStatePool : TServerStatePool;
function getContext : pointer;
protected
procedure Store( Stream : TStream ); virtual;
public
procedure DefaultHandler( var Message ); override;
end;
TAutomationOperation = (aopInserted, aopDeleted);
TOnClientAutomatonModified = procedure( Automaton : TClientAutomaton; Operation : TAutomationOperation ) of object;
TClientAutomaton =
class( TAutomaton, IClientActor )
public
destructor Destroy; override;
private
fAutomatable : IClientAutomatable;
fStatePool : TClientStatePool;
protected
function GetAutomatable : IAutomatable; override;
public
property Automatable : IClientAutomatable read fAutomatable write fAutomatable;
protected
procedure Act( State : TStateId; Mode : TActMode ); override;
// IClientActor
private
function getStatePool : TClientStatePool;
procedure setStatePool( aStatePool : TClientStatePool );
procedure Inserted;
procedure Deleted;
protected
procedure Load( Stream : TStream ); virtual;
// Events to pool
private
fOnAutomatonModified : TOnClientAutomatonModified;
public
property OnAutomatonModified : TOnClientAutomatonModified read fOnAutomatonModified write fOnAutomatonModified;
end;
type
TAutomatedState =
class( TDistributedState )
private
fAutomaton : TAutomaton;
public
procedure Act( Mode : TActMode ); override;
function HandleEvent( anEvent : TEvent ) : boolean; override;
end;
implementation
uses
ClassStorage, SysUtils;
// TMetaAutomaton
constructor TMetaAutomaton.Create( aKind : TActorKind; aPoolId : TActorPoolId; aAutomatonClass : CAutomaton; aBehavior : TMetaStatePool );
begin
inherited Create;
fKind := aKind;
fPoolId := aPoolId;
fAutomatonClass := aAutomatonClass;
fBehavior := aBehavior;
end;
function TMetaAutomaton.Instantiate( AutomatonId : TActorId ) : TAutomaton;
begin
result := fAutomatonClass.Create( self, AutomatonId );
end;
procedure TMetaAutomaton.Register;
begin
TheClassStorage.RegisterClass( IntToStr(PoolId), IntToStr(Kind), self );
end;
// TMetaServerAutomaton
constructor TMetaServerAutomaton.Create( aKind : TActorKind;
aPoolId : TActorPoolId;
aAutomatonClass : CServerAutomaton;
aBehavior : TMetaStatePool;
aAutomatableFactory : TServerAutomatableFactory );
begin
inherited Create( aKind, aPoolId, aAutomatonClass, aBehavior );
fAutomatableFactory := aAutomatableFactory;
end;
function TMetaServerAutomaton.Instantiate( AutomatonId : TActorId; const Context ) : TServerAutomaton;
begin
result := TServerAutomaton(inherited Instantiate( AutomatonId ));
result.Automatable := InstantiateAutomatable( Context );
if result.Automatable <> nil
then result.Automatable.SetAutomationEngine( result );
end;
function TMetaServerAutomaton.InstantiateAutomatable( const Context ) : IServerAutomatable;
begin
if assigned(fAutomatableFactory)
then result := fAutomatableFactory( Kind, Context );
end;
// TMetaClientAutomaton
constructor TMetaClientAutomaton.Create( aKind : TActorKind;
aPoolId : TActorPoolId;
aAutomatonClass : CClientAutomaton;
aBehavior : TMetaStatePool;
aAutomatableFactory : TClientAutomatableFactory );
begin
inherited Create( aKind, aPoolId, aAutomatonClass, aBehavior );
fAutomatableFactory := aAutomatableFactory;
end;
function TMetaClientAutomaton.Instantiate( AutomatonId : TActorId; const Context ) : TClientAutomaton;
begin
result := TClientAutomaton(inherited Instantiate( AutomatonId ));
result.Automatable := InstantiateAutomatable( Context );
end;
function TMetaClientAutomaton.InstantiateAutomatable( const Context ) : IClientAutomatable;
begin
if assigned(fAutomatableFactory)
then result := fAutomatableFactory( Kind, Context );
end;
// TAutomaton
constructor TAutomaton.Create( aMetaAutomaton : TMetaAutomaton; anId : TActorId );
begin
inherited Create;
fMetaAutomaton := aMetaAutomaton;
fId := anId;
end;
function TAutomaton.getId : TActorId;
begin
result := fId;
end;
function TAutomaton.getKind : TActorKind;
begin
result := fMetaAutomaton.fKind;
end;
procedure TAutomaton.StateModified( State : TState; Modification : TStateModification );
begin
if Modification = stmdCreation
then TAutomatedState(State).fAutomaton := self;
end;
// TServerAutomaton
constructor TServerAutomaton.Create( aMetaAutomaton : TMetaAutomaton; anId : TActorId );
begin
inherited;
fStatePool := TServerStatePool.Create( MetaAutomaton.Behavior, 1 ); //>> puse el 1
fStatePool.OnStateModified := StateModified;
end;
destructor TServerAutomaton.Destroy;
begin
fStatePool.Free;
inherited;
end;
function TServerAutomaton.GetAutomatable : IAutomatable;
begin
result := fAutomatable;
end;
procedure TServerAutomaton.Act( State : TStateId; Mode : TActMode );
begin
Automatable.Act( state, Mode );
end;
procedure TServerAutomaton.LaunchState( Launcher, State : TStateId; aCPL : integer; Frequency : integer; LauncherBehavior : TLauncherBehaviour );
var
LauncherState : TState;
begin
LauncherState := fStatePool.FindState( Launcher, soBreadthFirst );
if LauncherState <> nil
then LauncherState.TransitToStateId( State, aCPL, Frequency, self, LauncherBehavior );
end;
procedure TServerAutomaton.ThrowEvent( anEvent : TDistributedEvent );
begin
TServerStatePool(fStatePool).DistributeEvent( anEvent );
end;
function TServerAutomaton.getStatePool : TServerStatePool;
begin
result := fStatePool;
end;
function TServerAutomaton.getContext : pointer;
begin
result := self;
end;
procedure TServerAutomaton.Store( Stream : TStream );
begin
Automatable.Store( Stream );
end;
procedure TServerAutomaton.DefaultHandler( var Message );
begin
Automatable.Dispatch( Message );
end;
// TClientAutomaton
destructor TClientAutomaton.Destroy;
begin
fStatePool.Free;
inherited;
end;
function TClientAutomaton.GetAutomatable : IAutomatable;
begin
result := fAutomatable;
end;
procedure TClientAutomaton.Act( State : TStateId; Mode : TActMode );
begin
Automatable.Act( state, Mode );
end;
function TClientAutomaton.getStatePool : TClientStatePool;
begin
result := fStatePool;
end;
procedure TClientAutomaton.setStatePool( aStatePool : TClientStatePool );
var
i : integer;
begin
fStatePool := aStatePool;
for i := 0 to pred(aStatePool.InitialStateCount) do
if aStatePool.InitialStates[i] is TAutomatedState
then TAutomatedState(aStatePool.InitialStates[i]).fAutomaton := self;
fStatePool.OnStateModified := StateModified;
end;
procedure TClientAutomaton.Inserted;
begin
if assigned(OnAutomatonModified)
then OnAutomatonModified( self, aopInserted );
end;
procedure TClientAutomaton.Deleted;
begin
Automatable.Deleted;
if assigned(OnAutomatonModified)
then OnAutomatonModified( self, aopDeleted );
end;
procedure TClientAutomaton.Load( Stream : TStream );
begin
Automatable.Load( Stream );
end;
// TAutomatedState
procedure TAutomatedState.Act( Mode : TActMode );
begin
fAutomaton.Act( MetaState.Id, Mode );
end;
function TAutomatedState.HandleEvent( anEvent : TEvent ) : boolean;
begin
result := fAutomaton.Automatable.HandleEvent( TDistributedEvent(anEvent) );
end;
end.
|
unit K620665614_H11400224;
{* [RequestLink:620665614] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K620665614_H11400224.pas"
// Стереотип: "TestCase"
// Элемент модели: "K620665614_H11400224" MUID: (56FA6D4303C3)
// Имя типа: "TK620665614_H11400224"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, EVDtoBothNSRCWriterTest
;
type
TK620665614_H11400224 = class(TEVDtoBothNSRCWriterTest)
{* [RequestLink:620665614] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK620665614_H11400224
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *56FA6D4303C3impl_uses*
//#UC END# *56FA6D4303C3impl_uses*
;
function TK620665614_H11400224.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'CrossSegments';
end;//TK620665614_H11400224.GetFolder
function TK620665614_H11400224.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '56FA6D4303C3';
end;//TK620665614_H11400224.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK620665614_H11400224.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
unit NtUtils.Registry.HKCU;
interface
uses
Winapi.WinNt, NtUtils.Exceptions, NtUtils.Registry;
// Get current user's hive path
function RtlxFormatCurrentUserKeyPath(out Path: String): TNtxStatus;
// Open a handle to the HKCU part of the registry
function RtlxOpenCurrentUserKey(out hKey: THandle; DesiredAccess: TAccessMask;
OpenOptions: Cardinal = 0; Attributes: Cardinal = 0) : TNtxStatus;
implementation
uses
Ntapi.ntseapi, Ntapi.ntpsapi, Ntapi.ntstatus, Ntapi.ntregapi,
NtUtils.Tokens, NtUtils.Lsa, NtUtils.Security.Sid, NtUtils.Objects;
function RtlxFormatCurrentUserKeyPath(out Path: String): TNtxStatus;
var
hToken: THandle;
User: TGroup;
UserName: String;
begin
// Check the thread's token
Result := NtxOpenThreadToken(hToken, NtCurrentThread, TOKEN_QUERY);
// Fall back to process' token
if Result.Status = STATUS_NO_TOKEN then
Result := NtxOpenProcessToken(hToken, NtCurrentProcess, TOKEN_QUERY);
if Result.IsSuccess then
begin
// Query the SID and convert it to string
Result := NtxQueryGroupToken(hToken, TokenUser, User);
if Result.IsSuccess then
Path := User.SecurityIdentifier.SDDL;
NtxSafeClose(hToken);
end
else
begin
// Ask LSA for help since we can't open our security context
if LsaxGetUserName(UserName).IsSuccess then
if LsaxLookupUserName(UserName, User.SecurityIdentifier).IsSuccess then
begin
Path := User.SecurityIdentifier.SDDL;
Result.Status := STATUS_SUCCESS;
end;
end;
if Result.IsSuccess then
Path := REG_PATH_USER + '\' + Path;
end;
function RtlxOpenCurrentUserKey(out hKey: THandle; DesiredAccess: TAccessMask;
OpenOptions: Cardinal; Attributes: Cardinal) : TNtxStatus;
var
HKCU: String;
begin
Result := RtlxFormatCurrentUserKeyPath(HKCU);
if not Result.IsSuccess then
Exit;
Result := NtxOpenKey(hKey, HKCU, DesiredAccess, 0, OpenOptions, Attributes);
// Redirect to HKU\.Default if the user's profile is not loaded
if Result.Status = STATUS_OBJECT_NAME_NOT_FOUND then
Result := NtxOpenKey(hKey, REG_PATH_USER_DEFAULT, DesiredAccess, 0,
OpenOptions, Attributes);
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpBerTaggedObject;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
SysUtils,
Generics.Collections,
ClpCryptoLibTypes,
{$IFDEF DELPHI}
ClpAsn1TaggedObject,
ClpIBerSequence,
{$ENDIF DELPHI}
ClpAsn1Tags,
ClpBerSequence,
ClpAsn1OutputStream,
ClpBerOutputStream,
ClpDerOutputStream,
ClpIAsn1OctetString,
ClpAsn1Encodable,
ClpBerOctetString,
ClpIBerOctetString,
ClpIDerOctetString,
ClpIAsn1Set,
ClpIAsn1Sequence,
ClpIProxiedInterface,
ClpDerTaggedObject,
ClpIBerTaggedObject;
resourcestring
SNotImplemented = 'Not Implemented %s';
type
/// <summary>
/// BER TaggedObject - in ASN.1 notation this is any object preceded by <br />
/// a [n] where n is some number - these are assumed to follow the
/// construction <br />rules (as with sequences). <br />
/// </summary>
TBerTaggedObject = class(TDerTaggedObject, IBerTaggedObject)
public
/// <param name="tagNo">
/// the tag number for this object.
/// </param>
/// <param name="obj">
/// the tagged object.
/// </param>
constructor Create(tagNo: Int32; const obj: IAsn1Encodable); overload;
/// <param name="explicitly">
/// true if an explicitly tagged object.
/// </param>
/// <param name="tagNo">
/// the tag number for this object.
/// </param>
/// <param name="obj">
/// the tagged object.
/// </param>
constructor Create(explicitly: Boolean; tagNo: Int32;
const obj: IAsn1Encodable); overload;
/// <summary>
/// create an implicitly tagged object that contains a zero length
/// sequence.
/// </summary>
/// <param name="tagNo">
/// the tag number for this object.
/// </param>
constructor Create(tagNo: Int32); overload;
procedure Encode(const derOut: TStream); override;
end;
implementation
{ TBerTaggedObject }
constructor TBerTaggedObject.Create(tagNo: Int32; const obj: IAsn1Encodable);
begin
Inherited Create(tagNo, obj);
end;
constructor TBerTaggedObject.Create(explicitly: Boolean; tagNo: Int32;
const obj: IAsn1Encodable);
begin
Inherited Create(explicitly, tagNo, obj)
end;
constructor TBerTaggedObject.Create(tagNo: Int32);
begin
Inherited Create(false, tagNo, TBerSequence.Empty)
end;
procedure TBerTaggedObject.Encode(const derOut: TStream);
var
eObj: TList<IAsn1Encodable>;
LListIDerOctetString: TCryptoLibGenericArray<IDerOctetString>;
LListIAsn1Encodable: TCryptoLibGenericArray<IAsn1Encodable>;
asn1OctetString: IAsn1OctetString;
berOctetString: IBerOctetString;
derOctetString: IDerOctetString;
asn1Sequence: IAsn1Sequence;
asn1Set: IAsn1Set;
o: IAsn1Encodable;
begin
eObj := TList<IAsn1Encodable>.Create();
try
if ((derOut is TAsn1OutputStream) or (derOut is TBerOutputStream)) then
begin
(derOut as TDerOutputStream)
.WriteTag(Byte(TAsn1Tags.Constructed or TAsn1Tags.Tagged), tagNo);
(derOut as TDerOutputStream).WriteByte($80);
if (not IsEmpty()) then
begin
if (not explicitly) then
begin
if (Supports(obj, IAsn1OctetString, asn1OctetString)) then
begin
if (Supports(asn1OctetString, IBerOctetString, berOctetString)) then
begin
LListIDerOctetString := berOctetString.GetEnumerable;
for derOctetString in LListIDerOctetString do
begin
eObj.Add(derOctetString as IAsn1Encodable);
end;
end
else
begin
berOctetString := TBerOctetString.Create
(asn1OctetString.GetOctets());
LListIDerOctetString := berOctetString.GetEnumerable;
for derOctetString in LListIDerOctetString do
begin
eObj.Add(derOctetString as IAsn1Encodable);
end;
end
end
else if Supports(obj, IAsn1Sequence, asn1Sequence) then
begin
LListIAsn1Encodable := asn1Sequence.GetEnumerable;
for o in LListIAsn1Encodable do
begin
eObj.Add(o);
end;
end
else if Supports(obj, IAsn1Set, asn1Set) then
begin
LListIAsn1Encodable := asn1Set.GetEnumerable;
for o in LListIAsn1Encodable do
begin
eObj.Add(o);
end;
end
else
begin
raise ENotImplementedCryptoLibException.CreateResFmt
(@SNotImplemented, [(obj as TAsn1Encodable).ClassName]);
end;
for o in eObj do
begin
(derOut as TDerOutputStream).WriteObject(o);
end;
end
else
begin
(derOut as TDerOutputStream).WriteObject(obj);
end;
end;
(derOut as TDerOutputStream).WriteByte($00);
(derOut as TDerOutputStream).WriteByte($00);
end
else
begin
(Inherited Encode(derOut));
end
finally
eObj.Free;
end;
end;
end.
|
unit DijkstraUnit;
Interface
uses AlgorithmUnit;
Type
DijkstraCell = class
public
coords : Point;
distance : integer;
from : Point;
end;
Dijkstra = class(Algorithm)
private
_dijkstraGrid : Dictionary<(integer, integer), DijkstraCell>;
_openSet : List<DijkstraCell>;
_closedSet : List<DijkstraCell>;
_path : List<DijkstraCell>;
function GetNeighbours(cell : DijkstraCell) : List<DijkstraCell>;
public
constructor Create(gridSize : integer; start, finish : Point);
begin
Inherited Create(gridSize, start, finish);
_dijkstraGrid := new Dictionary<(integer, integer), DijkstraCell>;
for var x := 0 to _gridSize - 1 do
for var y := 0 to _gridSize - 1 do
begin
var tempCell := new DijkstraCell;
tempCell.coords.x := x;
tempCell.coords.y := y;
tempCell.distance := MaxInt;
_dijkstraGrid.Add((x, y), tempCell);
end;
var startCell := _dijkstraGrid [(_start.x, _start.y)];
startCell.distance := 0;
_openSet := new List<DijkstraCell>;
_openSet.Add(startCell);
_closedSet := new List<DijkstraCell>;
_path := new List<DijkstraCell>;
end;
procedure Step(); override;
function GetGridLayout() : Grid; override;
function GetPathLength() : integer; override;
end;
Implementation
procedure Dijkstra.Step();
var cell : DijkstraCell;
found : boolean;
begin
found := false;
if(_openSet <> nil) and (_openSet.Count > 0) then begin
//Находим минимальную временную метку
cell := _openSet[0];
for var i := 1 to _openSet.Count-1 do
if(_openSet[i].distance < cell.distance) then
cell := _openSet[i];
_openSet.Remove(cell);
_closedSet.Add(cell);
if(cell.coords = _end) then
found := true
else begin
var neighbours := GetNeighbours(cell);
foreach var neighbour in neighbours do begin
var newDistance := cell.distance + Distance(cell.coords.x, cell.coords.y,
neighbour.coords.x, neighbour.coords.y);
if(newDistance < neighbour.distance)then begin
neighbour.distance := newDistance;
neighbour.from := cell.coords;
end;
if not(_closedSet.Contains(neighbour)) and not(_openSet.Contains(neighbour)) then
_openSet.Add(neighbour);
end;
end;
end else
if(_onFinish <> nil) and not(found) then begin
_onFinish();
exit;
end;
if(found)then
begin
var tempCell := _dijkstraGrid[(_end.x, _end.y)];
while(tempCell.coords <> _start) do begin
_path.Add(tempCell);
tempCell := _dijkstraGrid[(tempCell.from.x, tempCell.from.y)];
end;
_path.Add(tempCell);
end;
if(_onStep <> nil) then
_onStep();
if(found) then
if(_onFinish <> nil) then
_onFinish();
end;
function Dijkstra.GetNeighbours(cell : DijkstraCell) : List<DijkstraCell>;
var neighbours : List<DijkstraCell>;
neighbour : DijkstraCell;
begin
neighbours := new List<DijkstraCell>;
for var x := -1 to 1 do
for var y := -1 to 1 do
if(x <> 0) or (y <> 0) then
if(_dijkstraGrid.TryGetValue((cell.coords.x + x, cell.coords.y + y), neighbour)
and IsWalkable(cell.coords.x + x, cell.coords.y + y)) then
neighbours.Add(neighbour);
GetNeighbours := neighbours;
end;
function Dijkstra.GetGridLayout() : Grid;
begin
var temp := new intArray[_gridSize];
for var i := 0 to _gridSize-1 do
temp[i] := new integer[_gridSize];
foreach var cell in _openSet do
temp[cell.coords.x][cell.coords.y] := 3;
foreach var cell in _closedSet do
temp[cell.coords.x][cell.coords.y] := 2;
foreach var cell in _path do
temp[cell.coords.x][cell.coords.y] := 4;
GetGridLayout := temp;
end;
function Dijkstra.GetPathLength() : integer;
begin
var length := 0;
for var i := 0 to _path.Count-2 do
length += Distance(_path[i].coords.x, _path[i].coords.y,
_path[i+1].coords.x, _path[i+1].coords.y);
GetPathLength := length;
end;
end. |
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.LinkedLabel.iOS;
interface
uses
System.Classes, FMX.Platform, FGX.LinkedLabel;
type
{ TiOSLaunchService }
TiOSLaunchService = class sealed (TInterfacedObject, IFGXLaunchService)
public
{ IFMXLaunchService }
function OpenURL(const AUrl: string): Boolean;
end;
procedure RegisterService;
procedure UnregisterService;
implementation
uses
iOSapi.Foundation, Macapi.Helpers, FMX.Helpers.iOS;
{ TiOSLaunchService }
function TiOSLaunchService.OpenURL(const AUrl: string): Boolean;
var
Url: NSURL;
begin
Url := TNSUrl.Wrap(TNSUrl.OCClass.URLWithString(StrToNSStr(AUrl)));
Result := SharedApplication.openUrl(Url);
end;
procedure RegisterService;
begin
TPlatformServices.Current.AddPlatformService(IFGXLaunchService, TiOSLaunchService.Create);
end;
procedure UnregisterService;
begin
TPlatformServices.Current.RemovePlatformService(IFGXLaunchService);
end;
end.
|
unit DAO.FaixaVerba;
interface
uses DAO.Base, Model.FaixaVerba, Generics.Collections, System.Classes;
type
TFaixaVerbaDAO = class(TDAO)
public
function Insert(aFaixas: Model.FaixaVerba.TFaixaVerba): Boolean;
function Update(aFaixas: Model.FaixaVerba.TFaixaVerba): Boolean;
function Delete(sFiltro: String): Boolean;
function FindFaixa(sFiltro: String): TObjectList<Model.FaixaVerba.TFaixaVerba>;
end;
const
TABLENAME = 'tbfaixaverba';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
function TFaixaVerbaDAO.Insert(aFaixas: TFaixaVerba): Boolean;
var
sSQL : System.string;
begin
Result := False;
aFaixas.ID := GetKeyValue(TABLENAME,'ID_VERBA');
sSQL := 'INSERT INTO ' + TABLENAME + ' '+
'(ID_VERBA, ID_FAIXA, VAL_VERBA, DES_LOG) ' +
'VALUES ' +
'(:ID, :FAIXA, :VALOR, :LOG);';
Connection.ExecSQL(sSQL,[aFaixas.ID, aFaixas.Faixa, aFaixas.Verba, aFaixas.Log],
[ftInteger, ftInteger, ftFloat, ftString]);
Result := True;
end;
function TFaixaVerbaDAO.Update(aFaixas: TFaixaVerba): Boolean;
var
sSQL: System.string;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'val_verba = :FINAL, DES_LOG = :LOG ' +
'WHERE ID_VERBA = :ID AND ID_FAIXA = :FAIXA;';
Connection.ExecSQL(sSQL,[aFaixas.Verba, aFaixas.Log, aFaixas.ID, aFaixas.Faixa],
[ftFloat, ftString, ftInteger, ftInteger]);
Result := True;
end;
function TFaixaVerbaDAO.Delete(sFiltro: string): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'DELETE FROM ' + TABLENAME + ' ';
if not sFiltro.IsEmpty then
begin
sSQl := sSQL + sFiltro;
end
else
begin
Exit;
end;
Connection.ExecSQL(sSQL);
Result := True;
end;
function TFaixaVerbaDAO.FindFaixa(sFiltro: string): TObjectList<Model.FaixaVerba.TFaixaVerba>;
var
FDQuery: TFDQuery;
faixas: TObjectList<TFaixaVerba>;
begin
FDQuery := TFDQuery.Create(nil);
try
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if not sFiltro.IsEmpty then
begin
FDQuery.SQL.Add(sFiltro);
end;
FDQuery.Open();
faixas := TObjectList<TFaixaVerba>.Create();
while not FDQuery.Eof do
begin
faixas.Add(TFaixaVerba.Create(FDQuery.FieldByName('ID_VERBA').AsInteger, FDQuery.FieldByName('ID_FAIXA').AsInteger,
FDQuery.FieldByName('VAL_VERBA').AsFloat, FDQuery.FieldByName('DES_LOG').AsString));
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := faixas;
end;
end.
|
Unit H2ImageList;
Interface
Uses
Windows, Classes,Controls, SysUtils,GR32_Image,GR32,
gr32_layers,Graphics,generalprocedures;
Type
PIRecord=^TIrecord;
TIRecord=Record
dir:String;
filename:String;
size:Integer;
folder:Boolean;
End;
TH2ImageList = Class(TControl)
Private
fsrx,
fsry,
fwrx,
fwry,
fsrf,
fwrf,
fx,
fy,
fwidth,
fheight,
fcount,
findent,
ffirst,
findex,
fitemheight,
fthumbwidth,
fthumbheight:Integer;
fstate:Boolean;
fvisible:Boolean;
ftitle,
fdir,
ffile: String;
ffont: tfont;
ftitleheight:Integer;
fbitmap:tbitmaplayer;
fselect:tbitmap32;
ffolder:tbitmap32;
fimage:tbitmap32;
fdrawmode:tdrawmode;
falpha:Cardinal;
fitems:tlist;
Procedure SetFont(value:tfont);
Procedure SetItems(value:tlist);
Procedure Setvisible(value:Boolean);
Procedure SetItemindex(value:Integer);
Procedure Setx(value:Integer);
Procedure Sety(value:Integer);
Procedure SetWidth(value:Integer);
Procedure SetHeight(value:Integer);
Procedure SetDir(value:String);
Procedure Findfiles(FilesList: TList; StartDir, FileMask: String);
Procedure FindImages(FilesList: TList; StartDir:String);
Procedure FindDir(DirList:tlist;startdir,filemask:String);
Public
Constructor Create(AOwner: TComponent); Override;
Destructor Destroy; Override;
Procedure MouseDown(Sender: TObject; Buttons: TMouseButton; Shift: TShiftState; X, Y: Integer);
Published
Procedure LoadSelection(Filename:String);
Procedure LoadFolderICO(Filename:String);
Procedure Files;
Procedure Select;
Procedure FolderUP;
Procedure ScrollDown;
Procedure ScrollUp;
Procedure Clear;
Procedure UpdateLV;
Property State:Boolean Read fstate Write fstate;
Property Font:tfont Read ffont Write setfont;
Property Alpha:Cardinal Read falpha Write falpha;
Property DrawMode:tdrawmode Read fdrawmode Write fdrawmode;
Property X:Integer Read fx Write setx;
Property Y:Integer Read fy Write sety;
Property Width:Integer Read fwidth Write setwidth;
Property Title:String Read ftitle Write ftitle;
Property Filename:String Read ffile Write ffile;
Property Dir:String Read fdir Write setdir;
Property Height:Integer Read fheight Write setheight;
Property ThumbHeight:Integer Read fthumbheight Write fthumbheight;
Property TitleHeight:Integer Read ftitleheight Write ftitleheight;
Property Bitmap:tbitmaplayer Read fbitmap Write fbitmap;
Property Items:tlist Read fitems Write Setitems;
Property Visible:Boolean Read fvisible Write setvisible;
Property ItemIndex:Integer Read findex Write setitemindex;
Property ThumbWidth:Integer Read fthumbwidth Write fthumbwidth;
Property Indent:Integer Read findent Write findent;
Property ItemHeight:Integer Read fitemheight Write fitemheight;
Property MaxItems:Integer Read fcount Write fcount;
Property SizeRx:Integer Read fsrx Write fsrx;
Property SizeRy:Integer Read fsry Write fsry;
Property WidthRx:Integer Read fwrx Write fwrx;
Property WidthRy:Integer Read fwry Write fwry;
Property SizeRFont:Integer Read fsrf Write fsrf;
Property WidthRFont:Integer Read fwrf Write fwrf;
End;
Implementation
Uses unit1;
{ TH2ImageList }
Procedure TH2ImageList.Select;
Begin
If findex<0 Then exit;
If pirecord(fitems[findex]).folder=False Then
Begin
fstate:=Not fstate;
updatelv;
End Else
Begin
fdir:=fdir+pirecord(fitems[findex]).filename;
fdir:=IncludeTrailingPathDelimiter(fdir);
clear;
fstate:=False;
finddir(fitems,fdir,'*.*');
findimages(fitems,fdir);
updatelv;
End;
End;
Procedure TH2ImageList.Clear;
Var i:Integer;
Begin
For i:=fitems.Count-1 Downto 0 Do dispose(pirecord(fitems[i]));
fitems.Clear;
ffirst:=0;
findex:=-1;
fbitmap.Bitmap.Clear($000000);
End;
Constructor TH2ImageList.Create(AOwner: TComponent);
Var
L: TFloatRect;
alayer:tbitmaplayer;
Begin
Inherited Create(AOwner);
fbitmap:=TBitmapLayer.Create((aowner As timage32).Layers);
fbitmap.OnMouseUp:=mousedown;
fimage :=tbitmap32.Create;
fimage.DrawMode:=fdrawmode;
fimage.MasterAlpha:=falpha;
ftitleheight:=15;
fthumbwidth:=64;
ffont:=tfont.Create;
fstate:=False;
fdrawmode:=dmblend;
falpha:=255;
fvisible:=True;
fitems:=tlist.Create;
ftitle:='';
fdir:='c:\';
ffile:='';
fx:=0;
fy:=0;
fwidth:=100;
fheight:=100;
fbitmap.Bitmap.Width:=fwidth;
fbitmap.Bitmap.Height:=fheight;
l.Left:=fx;
l.Top:=fy;
l.Right:=fx+fwidth;
l.Bottom:=fy+fheight;
fbitmap.Location:=l;
fbitmap.Tag:=0;
fbitmap.Bitmap.DrawMode:=fdrawmode;
fbitmap.Bitmap.MasterAlpha:=falpha;
fselect:=tbitmap32.Create;
fselect.DrawMode:=fdrawmode;
fselect.MasterAlpha:=falpha;
ffolder:=tbitmap32.create;
ffolder.DrawMode:=fdrawmode;
ffolder.MasterAlpha:=falpha;
fcount:=5;
findent:=0;
ffirst:=0;
findex:=-1;
fitemheight:=20;
End;
Destructor TH2ImageList.Destroy;
Begin
//here
ffont.Free;
fbitmap.Free;
ffolder.Free;
fitems.Destroy;
fimage.Free;
fselect.Free;
Inherited Destroy;
End;
Procedure TH2ImageList.FindDir(DirList: tlist; startdir,
filemask: String);
Var
SR: TSearchRec;
IsFound: Boolean;
i: Integer;
v:pirecord;
Begin
// Build a list of subdirectories
IsFound := FindFirst(StartDir+'*.*', faAnyFile, SR) = 0;
While IsFound Do
Begin
If ((SR.Attr And faDirectory) <> 0) And
(SR.Name[1] <> '.') Then
Begin
v:=new(pirecord);
v.dir:=startdir;
v.filename:=SR.Name;
v.size:=sr.Size;
v.folder:=True;
DirList.Add(v);
End;
IsFound := FindNext(SR) = 0;
End;
FindClose(SR);
End;
Procedure TH2ImageList.Findfiles(FilesList: TList; StartDir,
FileMask: String);
Var
SR: TSearchRec;
IsFound: Boolean;
i: Integer;
v:pirecord;
Begin
If StartDir[length(StartDir)] <> '\' Then
StartDir := StartDir + '\';
{ Build a list of the files in directory StartDir
(not the directories!) }
IsFound :=
FindFirst(StartDir+FileMask, faAnyFile-faDirectory, SR) = 0;
While IsFound Do
Begin
v:=new(pirecord);
v.dir:=startdir;
v.filename:=SR.Name;
v.size:=sr.Size;
v.folder:=False;
FilesList.Add(v);
IsFound := FindNext(SR) = 0;
End;
FindClose(SR);
End;
Procedure TH2ImageList.files;
Begin
clear;
finddir(fitems,fdir,'*.*');
findimages(fitems,fdir);
updatelv;
End;
Procedure TH2ImageList.FindImages(FilesList: TList; StartDir:String);
Begin
findfiles(fileslist,fdir,'*.jpg');
findfiles(fileslist,fdir,'*.jpeg');
findfiles(fileslist,fdir,'*.pcx');
findfiles(fileslist,fdir,'*.bmp');
findfiles(fileslist,fdir,'*.ico');
findfiles(fileslist,fdir,'*.png');
End;
Procedure TH2ImageList.LoadFolderICO(Filename: String);
Var au:Boolean;
Begin
If fileexists(filename) Then
Begin
Try
LoadPNGintoBitmap32(ffolder,filename,au);
Except
End;
End;
End;
Procedure TH2ImageList.LoadSelection(Filename: String);
Var au:Boolean;
L: TFloatRect;
Begin
If fileexists(filename) Then
Begin
Try
LoadPNGintoBitmap32(fselect,filename,au);
Except
End;
End;
End;
Procedure TH2ImageList.MouseDown(Sender: TObject; Buttons: TMouseButton;
Shift: TShiftState; X, Y: Integer);
Var i,c:Integer;
Begin
If ffirst+fcount>fitems.Count-1 Then c:=fitems.Count-1 Else c:=ffirst+fcount;
For i:=ffirst To c Do
Begin
If (x>=fx+findent) And (x<=fx+fwidth) And (y>=ftitleheight+fy+(fitemheight*(i-ffirst))) And (y<=ftitleheight+fy+(fitemheight*(i-ffirst)+fitemheight)) Then
findex:=i;
End;
updatelv;
End;
Procedure TH2ImageList.ScrollDown;
Var i,d:Integer;
Begin
If fstate=False Then
Begin
If ffirst+fcount>fitems.Count-1 Then exit;
ffirst:=ffirst+fcount;
updatelv;
End Else
Begin
If findex<0 Then
Begin
For i:=0 To fitems.Count-1 Do If pirecord(fitems[i]).folder Then findex:=i;
End Else
For i:=findex To fitems.Count-1 Do
Begin
If i+1>fitems.Count-1 Then d:=i Else d:=i+1;
If pirecord(fitems[d]).folder=False Then
Begin findex:=d;updatelv;break;End;
End;
End;
End;
Procedure TH2ImageList.ScrollUp;
Var i,d:Integer;
Begin
If fstate=False Then
Begin
If ffirst-fcount<=0 Then ffirst:=0 Else ffirst:=ffirst-fcount;
updatelv;
End Else
Begin
If findex<0 Then
Begin
For i:=fitems.Count-1 Downto 0 Do If pirecord(fitems[i]).folder Then findex:=i;
End Else
For i:=findex Downto 0 Do
Begin
If i-1<0 Then d:=0 Else d:=i-1;
If pirecord(fitems[d]).folder=False Then
Begin findex:=d;updatelv;break End;
End;
End;
End;
Procedure TH2ImageList.SetDir(value: String);
Var
i:Integer;
Begin
i:=fbitmap.Bitmap.TextWidth(inttostr(findex)+'/'+inttostr(fitems.count));
fdir:=value;
ftitle:=mince(value,fwidth-i,fbitmap.Bitmap);
End;
Procedure TH2ImageList.SetFont(value: tfont);
Var
Color: Longint;
r, g, b: Byte;
Begin
ffont.Assign(value);
Color := ColorToRGB(ffont.Color);
r := Color;
g := Color Shr 8;
b := Color Shr 16;
fbitmap.Bitmap.Font.assign(ffont);
End;
Procedure TH2ImageList.SetHeight(value: Integer);
Var
L: TFloatRect;
Begin
fheight:=value;
l.Left:=fx;
l.Top:=fy;
l.Right:=fx+fwidth;
l.Bottom:=fy+fheight;
fbitmap.Location:=l;
fbitmap.Bitmap.Height:=fheight;
End;
Procedure TH2ImageList.SetItemindex(value: Integer);
Begin
findex:=value;
updatelv;
End;
Procedure TH2ImageList.SetItems(value: tlist);
Begin
fitems.Assign(value);
findex:=fitems.Count-1;
updatelv;
End;
Procedure TH2ImageList.Setvisible(value: Boolean);
Begin
fbitmap.Visible:=value;
End;
Procedure TH2ImageList.SetWidth(value: Integer);
Var
L: TFloatRect;
Begin
fwidth:=value;
l.Left:=fx;
l.Top :=fy;
l.Right:=fx+fwidth;
l.Bottom:=fy+fheight;
fbitmap.Location:=l;
fbitmap.Bitmap.Width:=fwidth;
End;
Procedure TH2ImageList.Setx(value: Integer);
Var
L: TFloatRect;
Begin
fx:=value;
l.Left:=fx;
l.Top:=fy;
l.Right:=fx+fwidth;
l.Bottom:=fy+fheight;
fbitmap.Location:=l;
End;
Procedure TH2ImageList.Sety(value: Integer);
Var
L: TFloatRect;
Begin
fy:=value;
l.Left:=fx;
l.Top:=fy;
l.Right:=fx+fwidth;
l.Bottom:=fy+fheight;
fbitmap.Location:=l;
End;
Procedure TH2ImageList.UpdateLV;
Var i,c,h:Integer;
a:Real;
Color: Longint;
r, g, b: Byte;
s:String;
Begin
fbitmap.Bitmap.Clear($000000);
Color := ColorToRGB(ffont.Color);
r := Color;
g := Color Shr 8;
b := Color Shr 16;
fbitmap.Bitmap.Font.Assign(ffont);
If fstate=False Then
Begin //Display Folder
h:=(ftitleheight Div 2)-(fbitmap.bitmap.TextHeight(inttostr(findex+1)+'/'+inttostr(fitems.Count)) Div 2);
c:=fbitmap.bitmap.Textwidth(inttostr(findex+1)+'/'+inttostr(fitems.Count));
fbitmap.Bitmap.Rendertext(fwidth-c,h,inttostr(findex+1)+'/'+inttostr(fitems.Count),0,color32(r,g,b,falpha));
ftitle:=mince(fdir,fwidth-c,fbitmap.Bitmap);
h:=(ftitleheight Div 2)-(fbitmap.bitmap.TextHeight(ftitle) Div 2);
fbitmap.Bitmap.Rendertext(2,h,ftitle,0,color32(r,g,b,falpha));
If fitems.Count=0 Then exit;
If ffirst+fcount>fitems.Count-1 Then c:=fitems.Count-1 Else c:=ffirst+fcount;
For i:=ffirst To c Do
Begin
If i=findex Then
Begin
fselect.DrawTo(fbitmap.Bitmap,0,ftitleheight+fitemheight*(i-ffirst));
End;
If pirecord(fitems[i]).folder=True Then
Begin
ffolder.DrawTo(fbitmap.Bitmap,0,2+ftitleheight+fitemheight*(i-ffirst));
h:=2;
fbitmap.Bitmap.Rendertext(findent,(fitemheight*(i-ffirst))+h+ftitleheight,pirecord(fitems[i]).filename,0,color32(r,g,b,falpha));
fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size+fwrf;
fbitmap.Bitmap.Rendertext(findent+fwrx,(fitemheight*(i-ffirst))+fwry+ftitleheight,'<Folder>',0,color32(r,g,b,falpha));
fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size-fwrf;
End Else
Begin
If fileexists(pirecord(fitems[i]).dir+pirecord(fitems[i]).filename) Then
Begin
fimage.Clear;
fimage.DrawMode:=dmopaque;
fimage.masteralpha:=255;
fimage.LoadFromFile(pirecord(fitems[i]).dir+pirecord(fitems[i]).filename);
s:=inttostr(fimage.Width)+' x '+inttostr(fimage.Height);
// fimage.Width:=fthumbwidth;
// fimage.Height:=fthumbheight;
fimage.DrawTo(fbitmap.Bitmap,
rect(1,ftitleheight+fitemheight*(i-ffirst)+(fitemheight Div 2)-(fthumbheight Div 2),1+fthumbwidth,ftitleheight+fitemheight*(i-ffirst)+(fitemheight Div 2)-(fthumbheight Div 2)+fthumbheight));
h:=2;
fbitmap.Bitmap.Rendertext(findent,(fitemheight*(i-ffirst))+h+ftitleheight,pirecord(fitems[i]).filename,0,color32(r,g,b,falpha));
fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size+fwrf;
fbitmap.Bitmap.Rendertext(findent+fwrx,(fitemheight*(i-ffirst))+fwry+ftitleheight,s,0,color32(r,g,b,falpha));
fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size-fwrf;
fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size+fsrf;
s:=floattostrf(pirecord(fitems[i]).size / 1024,ffnumber,7,2)+' KB';
fbitmap.Bitmap.Rendertext(findent+fsrx,(fitemheight*(i-ffirst))+fsry+ftitleheight,s,0,color32(r,g,b,falpha));
fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size-fsrf;
End;
End;
End;
End Else
If findex>=0 Then
Begin //Display Single Image
fimage.LoadFromFile(pirecord(fitems[findex]).dir+pirecord(fitems[findex]).filename);
{for i:=0 to 1 do begin
if (fimage.Width>fwidth) and (fimage.height<fheight) then a:=fwidth / fimage.Width;
if (fimage.Width<fwidth) and (fimage.height<fheight) then a:=1;
if (fimage.Width<fwidth) and (fimage.height>fheight) then a:=fheight / fimage.height;
if (fimage.Width>fwidth) and (fimage.height>fheight) then a:=fwidth / fimage.Width;
fimage.Width:=trunc(fimage.Width*a);
fimage.Height:=trunc(fimage.Height*a);
end;
c:=(fwidth div 2) - (fimage.Width div 2);
h:=(fheight div 2) - (fimage.height div 2);
}
//fimage.DrawTo(fbitmap.Bitmap,c,h);
fimage.DrawTo(fbitmap.Bitmap,rect(0,0,fwidth,fheight));
End;
End;
Procedure TH2ImageList.FolderUP;
Var
s:String;
MyStr: Pchar;
i, Len: Integer;
SectPerCls,
BytesPerCls,
FreeCls,
TotCls : DWord;
v:pirecord;
Const
Size: Integer = 200;
Begin
fstate:=False;
s:=IncludeTrailingPathDelimiter(fdir);
setcurrentdir(s);
If length(s)=3 Then
Begin
clear;
GetMem(MyStr, Size);
Len:=GetLogicalDriveStrings(Size, MyStr);
For i:=0 To Len-1 Do
Begin
If (ord(MyStr[i])>=65)And(ord(MyStr[i])<=90) Or (ord(MyStr[i])>=97)And(ord(MyStr[i])<=122) Then
Begin
v:=new(pirecord);
v.dir:='';
v.filename:=uppercase(MyStr[i]+':\');
v.size:=0;
v.folder:=True;
fitems.Add(v);
End;
End;
FreeMem(MyStr);
fdir:='';
updatelv;
End Else
Begin
chdir('..');
If IOResult <> 0 Then
Begin
End Else
Begin s:=getcurrentdir;
fdir:=IncludeTrailingPathDelimiter(s);
files;
End;
End;
End;
End.
|
{ Graphic functions for pyramidtiff.
Copyright (C) 2008 Mattias Gaertner mattias@freepascal.org
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 with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your 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 PyTiGraphics;
{$mode objfpc}{$H+}
{$inline on}
interface
uses
Math, sysutils, Classes, FPimage,
LazLogger, FPCanvas, FPWriteTiff, FPTiffCmn;
type
TCreateCompatibleMemImgEvent = procedure(Sender: TObject; Img: TFPCustomImage;
NewWidth, NewHeight: integer; out NewImage: TFPCustomImage) of object;
{ TLinearInterpolation }
TLinearInterpolation = class(TFPCustomInterpolation)
private
procedure CreatePixelWeights(OldSize, NewSize: integer;
out Entries: Pointer; out EntrySize: integer; out Support: integer);
protected
procedure Execute(x,y,w,h: integer); override;
function Filter(x: double): double; virtual;
function MaxSupport: double; virtual;
end;
procedure SetFPImgExtraTiff(const Desc: TFPCompactImgDesc; Img: TFPCustomImage;
ClearTiffExtras: boolean);
function dbgs(const Desc: TFPCompactImgDesc): string; overload;
implementation
procedure SetFPImgExtraTiff(const Desc: TFPCompactImgDesc; Img: TFPCustomImage;
ClearTiffExtras: boolean);
begin
if ClearTiffExtras then
FPTiffCmn.ClearTiffExtras(Img);
if Desc.Gray then begin
Img.Extra[TiffPhotoMetric]:='1';
Img.Extra[TiffGrayBits]:=IntToStr(Desc.Depth);
end else begin
Img.Extra[TiffPhotoMetric]:='2';
Img.Extra[TiffRedBits]:=IntToStr(Desc.Depth);
Img.Extra[TiffGreenBits]:=IntToStr(Desc.Depth);
Img.Extra[TiffBlueBits]:=IntToStr(Desc.Depth);
end;
if Desc.HasAlpha then
Img.Extra[TiffAlphaBits]:=IntToStr(Desc.Depth)
else
Img.Extra[TiffAlphaBits]:='0';
end;
function dbgs(const Desc: TFPCompactImgDesc): string;
begin
Result:='Depth='+dbgs(Desc.Depth)
+',Gray='+dbgs(Desc.Gray)
+',HasAlpha='+dbgs(Desc.HasAlpha);
end;
function ColorRound (c : double) : word;
begin
if c > $FFFF then
result := $FFFF
else if c < 0.0 then
result := 0
else
result := round(c);
end;
{ TLinearInterpolation }
procedure TLinearInterpolation.CreatePixelWeights(OldSize, NewSize: integer;
out Entries: Pointer; out EntrySize: integer; out Support: integer);
// create an array of #NewSize entries. Each entry starts with an integer
// for the StartIndex, followed by #Support singles for the pixel weights.
// The sum of weights for each entry is 1.
var
Entry: Pointer;
procedure SetSupport(NewSupport: integer);
begin
Support:=NewSupport;
EntrySize:=SizeOf(integer)+SizeOf(Single)*Support;
Getmem(Entries,EntrySize*NewSize);
Entry:=Entries;
end;
var
i: Integer;
Factor: double;
StartPos: Double;
StartIndex: Integer;
j: Integer;
FirstValue: Double;
//Sum: double;
begin
if NewSize=OldSize then begin
SetSupport(1);
for i:=0 to NewSize-1 do begin
// 1:1
PInteger(Entry)^:=i;
inc(Entry,SizeOf(Integer));
PSingle(Entry)^:=1.0;
inc(Entry,SizeOf(Single));
end;
end else if NewSize<OldSize then begin
// shrink
SetSupport(Max(2,(OldSize+NewSize-1) div NewSize));
Factor:=double(OldSize)/double(NewSize);
for i:=0 to NewSize-1 do begin
StartPos:=Factor*i;
StartIndex:=Floor(StartPos);
PInteger(Entry)^:=StartIndex;
inc(Entry,SizeOf(Integer));
// first pixel
FirstValue:=(1.0-(StartPos-double(StartIndex)));
PSingle(Entry)^:=FirstValue/Factor;
inc(Entry,SizeOf(Single));
// middle pixel
for j:=1 to Support-2 do begin
PSingle(Entry)^:=1.0/Factor;
inc(Entry,SizeOf(Single));
end;
// last pixel
PSingle(Entry)^:=(Factor-FirstValue-(Support-2))/Factor;
inc(Entry,SizeOf(Single));
end;
end else begin
// enlarge
if OldSize=1 then begin
SetSupport(1);
for i:=0 to NewSize-1 do begin
// nothing to interpolate
PInteger(Entry)^:=0;
inc(Entry,SizeOf(Integer));
PSingle(Entry)^:=1.0;
inc(Entry,SizeOf(Single));
end;
end else begin
SetSupport(2);
Factor:=double(OldSize-1)/double(NewSize);
for i:=0 to NewSize-1 do begin
StartPos:=Factor*i+Factor/2;
StartIndex:=Floor(StartPos);
PInteger(Entry)^:=StartIndex;
inc(Entry,SizeOf(Integer));
// first pixel
FirstValue:=(1.0-(StartPos-double(StartIndex)));
// convert linear distribution
FirstValue:=Min(1.0,Max(0.0,Filter(FirstValue/MaxSupport)));
PSingle(Entry)^:=FirstValue;
inc(Entry,SizeOf(Single));
// last pixel
PSingle(Entry)^:=1.0-FirstValue;
inc(Entry,SizeOf(Single));
end;
end;
end;
if Entry<>Entries+EntrySize*NewSize then
raise Exception.Create('TSimpleInterpolation.Execute inconsistency');
{WriteLn('CreatePixelWeights Old=',OldSize,' New=',NewSize,' Support=',Support,' EntrySize=',EntrySize,' Factor=',FloatToStr(Factor));
Entry:=Entries;
for i:=0 to NewSize-1 do begin
StartIndex:=PInteger(Entry)^;
inc(Entry,SizeOf(Integer));
write(i,' Start=',StartIndex);
Sum:=0;
for j:=0 to Support-1 do begin
FirstValue:=PSingle(Entry)^;
inc(Entry,SizeOf(Single));
write(' ',FloatToStr(FirstValue));
Sum:=Sum+FirstValue;
end;
writeln(' Sum=',FloatToStr(Sum));
end;}
end;
procedure TLinearInterpolation.Execute(x, y, w, h: integer);
// paint Image on Canvas at x,y,w*h
var
dy: Integer;
dx: Integer;
HorzResized: PFPColor;
xEntries: Pointer; // size:integer,weight1:single,weight2:single,...
xEntrySize: integer;
xSupport: integer;// how many horizontal pixel are needed to created one new pixel
yEntries: Pointer; // size:integer,weight1:single,weight2:single,...
yEntrySize: integer;
ySupport: integer;// how many vertizontal pixel are needed to created one new pixel
NewSupportLines: LongInt;
yEntry: Pointer;
SrcStartY: LongInt;
LastSrcStartY: LongInt;
sy: Integer;
xEntry: Pointer;
sx: LongInt;
cx: Integer;
f: Single;
NewCol: TFPColor;
Col: TFPColor;
CurEntry: Pointer;
NewRed, NewGreen, NewBlue, NewAlpha: Single;
begin
//WriteLn('TSimpleInterpolation.Execute Src=',image.width,'x',image.Height,' Dest=',x,',',y,',',w,'x',h);
if (w<=0) or (h<=0) or (image.Width=0) or (image.Height=0) then exit;
xEntries:=nil;
yEntries:=nil;
HorzResized:=nil;
try
CreatePixelWeights(image.Width,w,xEntries,xEntrySize,xSupport);
CreatePixelWeights(image.Height,h,yEntries,yEntrySize,ySupport);
//WriteLn('TSimpleInterpolation.Execute xSupport=',xSupport,' ySupport=',ySupport);
// create temporary buffer for the horizontally resized pixel for the current
// y line
GetMem(HorzResized,w*ySupport*SizeOf(TFPColor));
SrcStartY:=0;
for dy:=0 to h-1 do begin
if dy=0 then begin
yEntry:=yEntries;
SrcStartY:=PInteger(yEntry)^;
NewSupportLines:=ySupport;
end else begin
LastSrcStartY:=SrcStartY;
inc(yEntry,yEntrySize);
SrcStartY:=PInteger(yEntry)^;
NewSupportLines:=SrcStartY-LastSrcStartY;
//WriteLn('TSimpleInterpolation.Execute dy=',dy,' SrcStartY=',SrcStartY,' LastSrcStartY=',LastSrcStartY,' NewSupportLines=',NewSupportLines);
// move lines up
if (NewSupportLines>0) and (ySupport>NewSupportLines) then
System.Move(HorzResized[NewSupportLines*w],
HorzResized[0],
(ySupport-NewSupportLines)*w*SizeOf(TFPColor));
end;
// compute new horizontally resized line(s)
for sy:=ySupport-NewSupportLines to ySupport-1 do begin
xEntry:=xEntries;
for dx:=0 to w-1 do begin
sx:=PInteger(xEntry)^;
inc(xEntry,SizeOf(integer));
NewRed:=0.0;
NewGreen:=0.0;
NewBlue:=0.0;
NewAlpha:=0.0;
for cx:=sx to sx+xSupport-1 do begin
f:=PSingle(xEntry)^;
inc(xEntry,SizeOf(Single));
Col:=image.Colors[cx,SrcStartY+sy];
NewRed:=NewRed+Col.red*f;
NewGreen:=NewGreen+Col.green*f;
NewBlue:=NewBlue+Col.blue*f;
NewAlpha:=NewAlpha+Col.alpha*f;
end;
NewCol.red:=Min(round(NewRed),$ffff);
NewCol.green:=Min(round(NewGreen),$ffff);
NewCol.blue:=Min(round(NewBlue),$ffff);
NewCol.alpha:=Min(round(NewAlpha),$ffff);
HorzResized[dx+sy*w]:=NewCol;
end;
end;
// compute new vertically resized line
for dx:=0 to w-1 do begin
CurEntry:=yEntry+SizeOf(integer);
NewRed:=0.0;
NewGreen:=0.0;
NewBlue:=0.0;
NewAlpha:=0.0;
for sy:=0 to ySupport-1 do begin
f:=PSingle(CurEntry)^;
inc(CurEntry,SizeOf(Single));
Col:=HorzResized[dx+sy*w];
NewRed:=NewRed+Col.red*f;
NewGreen:=NewGreen+Col.green*f;
NewBlue:=NewBlue+Col.blue*f;
NewAlpha:=NewAlpha+Col.alpha*f;
end;
NewCol.red:=Min(round(NewRed),$ffff);
NewCol.green:=Min(round(NewGreen),$ffff);
NewCol.blue:=Min(round(NewBlue),$ffff);
NewCol.alpha:=Min(round(NewAlpha),$ffff);
Canvas.Colors[x+dx,y+dy]:=NewCol;
end;
end;
finally
if xEntries<>nil then FreeMem(xEntries);
if yEntries<>nil then FreeMem(yEntries);
if HorzResized<>nil then FreeMem(HorzResized);
end;
end;
function TLinearInterpolation.Filter(x: double): double;
begin
Result:=x;
end;
function TLinearInterpolation.MaxSupport: double;
begin
Result:=1.0;
end;
end.
|
program github;
type
participante = record
pais :string;
codigoProyecto :integer;
nombreProyecto :string;
rol :1..5;
horas :real;
monto :real;
end;
proyecto = record
codigo :integer;
montoTotal :real;
cantidadArqs :integer;
end;
proyectos = array[1..1000] of proyecto;
roles = array[1..5] of real;
procedure leerParticipante(var p:participante);
begin
write('Ingrese el país del participante: ');
readln(p.pais);
write('Ingrese el código del proyecto: ');
readln(p.codigoProyecto);
write('Ingrese el nombre del proyecto: ');
readln(p.nombreProyecto);
writeln('Ingrese el rol del participante [1-Analista Funcional / 2-Programador / 3-Administrador de bases de datos / 4-Arquitecto de software / 5-Administrador de redes y seguridad]: ');
readln(p.rol);
write('Ingrese la cantidad de horas dedicadas: ');
readln(p.horas);
end;
procedure calcularMonto(var p:participante; r:roles);
begin
p.monto := p.horas * r[p.rol];
end;
function esArgentino(pais:string):boolean;
begin
esArgentino := pais = 'Argentina';
end;
function esAdminDB(rol:integer):boolean;
begin
esAdminDB := rol = 3;
end;
procedure acumularMontoProyecto(var proy:proyectos; part:participante);
var
montoProyecto :real;
begin
montoProyecto := proy[part.codigoProyecto].montoTotal;
montoProyecto := montoProyecto + part.monto;
proy[part.codigoProyecto].montoTotal := montoProyecto;
end;
procedure comprobarMinMonto(var minimo:proyecto; p:proyecto);
begin
if (p.montoTotal <= minimo.montoTotal) then
begin
minimo.montoTotal := p.montoTotal;
minimo.codigo := p.codigo;
end;
end;
procedure incrementarCantArqs(var proy:proyectos; part:participante);
var
cantArqs :integer;
begin
if (part.rol = 4) then
begin
cantArqs := proy[part.codigoProyecto].cantidadArqs;
cantArqs := cantArqs + 1;
proy[part.codigoProyecto].cantidadArqs := cantArqs;
end;
end;
procedure informarArqs(p:proyectos);
var
i:integer;
begin
for i:=1 to 1000 do
writeln(
'La cantidad de arquitectos de software en el proyecto ',
i, 'es: ', p[i].cantidadArqs
);
end;
var
p :participante;
proy :proyectos;
r :roles;
minimo :proyecto;
montoTotalArg, horasTotalAdminDB :real;
i :integer;
begin
montoTotalArg := 0;
horasTotalAdminDB := 0;
minimo.montoTotal := 99999;
r[1] := 35.2;
r[2] := 27.45;
r[3] := 31.03;
r[4] := 44.28;
r[5] := 39.87;
leerParticipante(p);
while (p.codigoProyecto <> -1) do
begin
calcularMonto(p,r);
if (esArgentino(p.pais)) then
montoTotalArg := montoTotalArg + p.monto;
if (esAdminDB(p.rol)) then
horasTotalAdminDB := horasTotalAdminDB + p.horas;
acumularMontoProyecto(proy,p);
incrementarCantArqs(proy,p);
leerParticipante(p);
end;
for i:=1 to 1000 do
begin
writeln(
'La cantidad de arquitectos de software para el proyecto ', i,
' es: ', proy[i].cantidadArqs
);
comprobarMinMonto(minimo, proy[i]);
end;
writeln(
'El monto total invertido en desarrolladores con residenciaen Argentina es :',
montoTotalArg
);
writeln(
'La cantidad total de horas trabajadas por Administradoresde bases de datos es: ',
horasTotalAdminDB
);
writeln(
'El código del proyecto con menor monto invertido es: ', minimo.codigo
);
end. |
unit DelphiUp.View.Components.Cards.Attributes;
interface
uses
DelphiUp.View.Components.Cards.Interfaces, System.UITypes;
type
TCardsAttributes<T : class> = class(TInterfacedObject, iComponentCardAttributes<T>)
private
[weak]
FParent : T;
FTitle : String;
FFontTitleSize : Integer;
FFontTitleColor : TAlphaColor;
FBackground : TAlphaColor;
FDestBackground : TAlphaColor;
public
constructor Create(Parent : T);
destructor Destroy; override;
class function New (Parent : T) : iComponentCardAttributes<T>;
function Title ( aValue : String ) : iComponentCardAttributes<T>; overload;
function Title : String; overload;
function FontTitleSize ( aValue : Integer ) : iComponentCardAttributes<T>; overload;
function FontTitleSize : Integer; overload;
function FontTitleColor ( aValue : TAlphaColor ) : iComponentCardAttributes<T>; overload;
function FontTitleColor : TAlphaColor; overload;
function Background ( aValue : TAlphaColor ) : iComponentCardAttributes<T>; overload;
function Background : TAlphaColor; overload;
function DestBackground ( aValue : TAlphaColor ) : iComponentCardAttributes<T>; overload;
function DestBackground : TAlphaColor; overload;
function &End : T;
end;
implementation
{ TCardsAttributes<T> }
function TCardsAttributes<T>.Background(
aValue: TAlphaColor): iComponentCardAttributes<T>;
begin
Result := Self;
FBackground := aValue;
end;
function TCardsAttributes<T>.Background: TAlphaColor;
begin
Result := FBackground;
end;
function TCardsAttributes<T>.&End: T;
begin
Result := FParent;
end;
constructor TCardsAttributes<T>.Create(Parent: T);
begin
FParent := Parent;
end;
function TCardsAttributes<T>.DestBackground(
aValue: TAlphaColor): iComponentCardAttributes<T>;
begin
Result := Self;
FDestBackground := aValue;
end;
function TCardsAttributes<T>.DestBackground: TAlphaColor;
begin
Result := FDestBackground;
end;
destructor TCardsAttributes<T>.Destroy;
begin
inherited;
end;
function TCardsAttributes<T>.FontTitleColor: TAlphaColor;
begin
Result := FFontTitleColor;
end;
function TCardsAttributes<T>.FontTitleColor(
aValue: TAlphaColor): iComponentCardAttributes<T>;
begin
Result := Self;
FFontTitleColor := aValue;
end;
function TCardsAttributes<T>.FontTitleSize(
aValue: Integer): iComponentCardAttributes<T>;
begin
Result := Self;
FFontTitleSize := aValue;
end;
function TCardsAttributes<T>.FontTitleSize: Integer;
begin
Result := FFontTitleSize;
end;
class function TCardsAttributes<T>.New(
Parent: T): iComponentCardAttributes<T>;
begin
Result := Self.Create(Parent);
end;
function TCardsAttributes<T>.Title(aValue: String): iComponentCardAttributes<T>;
begin
Result := Self;
FTitle := aValue;
end;
function TCardsAttributes<T>.Title: String;
begin
Result := FTitle;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpTeleTrusTObjectIdentifiers;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
ClpDerObjectIdentifier,
ClpIDerObjectIdentifier;
type
TTeleTrusTObjectIdentifiers = class sealed(TObject)
strict private
class var
FIsBooted: Boolean;
FTeleTrusTAlgorithm, FRipeMD160, FRipeMD128, FRipeMD256, FECSign,
FECSignWithSha1, FECSignWithRipeMD160: IDerObjectIdentifier;
class function GetRipeMD128: IDerObjectIdentifier; static; inline;
class function GetRipeMD160: IDerObjectIdentifier; static; inline;
class function GetRipeMD256: IDerObjectIdentifier; static; inline;
class function GetTeleTrusTAlgorithm: IDerObjectIdentifier; static; inline;
class function GetECSign: IDerObjectIdentifier; static; inline;
class function GetECSignWithRipeMD160: IDerObjectIdentifier; static; inline;
class function GetECSignWithSha1: IDerObjectIdentifier; static; inline;
class constructor TeleTrusTObjectIdentifiers();
public
class property RipeMD160: IDerObjectIdentifier read GetRipeMD160;
class property RipeMD128: IDerObjectIdentifier read GetRipeMD128;
class property RipeMD256: IDerObjectIdentifier read GetRipeMD256;
class property TeleTrusTAlgorithm: IDerObjectIdentifier
read GetTeleTrusTAlgorithm;
class property ECSign: IDerObjectIdentifier read GetECSign;
class property ECSignWithSha1: IDerObjectIdentifier read GetECSignWithSha1;
class property ECSignWithRipeMD160: IDerObjectIdentifier
read GetECSignWithRipeMD160;
class procedure Boot(); static;
end;
implementation
{ TTeleTrusTObjectIdentifiers }
class function TTeleTrusTObjectIdentifiers.GetTeleTrusTAlgorithm
: IDerObjectIdentifier;
begin
result := FTeleTrusTAlgorithm;
end;
class function TTeleTrusTObjectIdentifiers.GetECSign: IDerObjectIdentifier;
begin
result := FECSign;
end;
class function TTeleTrusTObjectIdentifiers.GetECSignWithRipeMD160
: IDerObjectIdentifier;
begin
result := FECSignWithRipeMD160;
end;
class function TTeleTrusTObjectIdentifiers.GetECSignWithSha1
: IDerObjectIdentifier;
begin
result := FECSignWithSha1;
end;
class function TTeleTrusTObjectIdentifiers.GetRipeMD128: IDerObjectIdentifier;
begin
result := FRipeMD128;
end;
class function TTeleTrusTObjectIdentifiers.GetRipeMD160: IDerObjectIdentifier;
begin
result := FRipeMD160;
end;
class function TTeleTrusTObjectIdentifiers.GetRipeMD256: IDerObjectIdentifier;
begin
result := FRipeMD256;
end;
class procedure TTeleTrusTObjectIdentifiers.Boot;
begin
if not FIsBooted then
begin
FTeleTrusTAlgorithm := TDerObjectIdentifier.Create('1.3.36.3');
FRipeMD160 := TDerObjectIdentifier.Create(TeleTrusTAlgorithm.ID + '.2.1');
FRipeMD128 := TDerObjectIdentifier.Create(TeleTrusTAlgorithm.ID + '.2.2');
FRipeMD256 := TDerObjectIdentifier.Create(TeleTrusTAlgorithm.ID + '.2.3');
FECSign := TDerObjectIdentifier.Create(TeleTrusTAlgorithm.ID + '.3.2');
FECSignWithSha1 := TDerObjectIdentifier.Create(ECSign.ID + '.1');
FECSignWithRipeMD160 := TDerObjectIdentifier.Create(ECSign.ID + '.2');
FIsBooted := True;
end;
end;
class constructor TTeleTrusTObjectIdentifiers.TeleTrusTObjectIdentifiers;
begin
TTeleTrusTObjectIdentifiers.Boot;
end;
end.
|
{.$DEFINE CAPTURE_WRITE_BUF}
unit np.core;
interface
uses np.common, np.winsock, sysutils,Classes, np.libuv, generics.collections, np.buffer,
np.eventEmitter, np.value;
type
PBufferRef = np.buffer.PBufferRef;
IQueueItem = interface
['{49B198FA-6AA5-43C4-9F04-574E0411EA76}']
procedure Invoke;
procedure Cancel;
end;
TSetImmediate = function (p: Tproc): IQueueItem of object;
TWatchCallBack = TProc<TFS_Event,UTF8String>;
TQueueItem = class(TInterfacedObject, IQueueItem)
private
proc: TProc;
constructor Create(p: TProc);
procedure Cancel;
procedure Invoke;
destructor Destroy; override;
end;
IRWLock = Interface
['{AA6012BF-B585-47B7-B090-40264F725D19}']
procedure beginRead;
procedure endRead;
procedure beginWrite;
procedure endWrite;
end;
TProcQueue = class
strict private
type
PLinked = ^TLinked;
TLinked = record
Item: IQueueItem;
Next: PLinked;
end;
var
lock: IRWLock;
head,tail : PLinked;
public
function add(p: TProc) : IQueueItem;
constructor Create();
function isEmpty: Boolean;
function emit : Boolean;
destructor Destroy;override;
end;
INPHandle = interface
['{DF9B5DC7-B447-45A5-9A36-C69C49214C08}']
procedure ref;
procedure unref;
function hasRef : Boolean;
procedure setOnClose(OnClose: TProc);
procedure Clear;
function is_closing : boolean;
function is_active : Boolean;
function _uv_handle : puv_handle_t;
end;
INPCheck = Interface(INPHandle)
['{AB0D7CEF-4CDD-4E2A-9194-B36A682F1814}']
end;
INPPrepare = Interface(INPHandle)
['{2D29D734-8265-4419-A6CC-AF979C249C0E}']
end;
INPIdle = Interface(INPHandle)
['{360B04B1-FDAF-415C-BD85-54BDEBE2A5B5}']
end;
INPAsync = interface(INPHandle)
['{55C45C90-701B-4709-810F-FF746AC2AB8C}']
procedure send;
end;
INPWatch = interface(INPHandle)
['{00C99155-9FE6-4E58-AEF3-F80B20CC1233}']
function getpath: String;
property path : String read getpath;
end;
INPTimer = Interface(INPHandle)
['{A76DFCB7-01F9-460B-97D5-6D9A05A23C03}']
procedure SetRepeat(Arepeat: uint64);
function GetRepeat : uint64;
procedure Again;
end;
PNPError = ^TNPError;
TNPError = record
code : integer;
codestr : string;
msg : string;
procedure Init(ACode : integer);
function ToString : String;
end;
INPStream = interface(INPHandle)
['{DAF6338E-B124-403E-B4C9-BF5B3556697C}']
procedure shutdown(Acallback : TProc=nil);
function is_readable : Boolean;
function is_writable: Boolean;
procedure setOnData(onData: TProc<PBufferRef>);
procedure setOnEnd(onEnd: TProc);
procedure setOnClose(onCloce: Tproc);
procedure setOnError(OnError: TProc<PNPError>);
procedure write(const data: BufferRef; Acallback: TProc=nil); overload;
procedure write(const data: UTF8String; Acallback: TProc=nil); overload;
end;
INPTCPStream = Interface(INPStream)
['{F335DEB6-E890-4D64-90D4-A23E1A78ADD8}']
procedure bind(const Aaddr: UTF8String; Aport: word);
procedure bind6(const Aaddr: UTF8String; Aport: word; tcp6Only: Boolean=false);
function getpeername : Utf8string;
procedure getpeername_port(out name: Utf8string; out port: word);
function getsockname : Utf8string;
procedure getsockname_port(out name: Utf8string; out port: word);
procedure set_nodelay(enable:Boolean);
procedure set_simultaneous_accepts(enable:Boolean);
procedure set_keepalive(enable:Boolean; delay:cardinal);
end;
INPTCPConnect = interface (INPTCPStream)
['{8F00A812-AFA9-4313-969E-88AD2935C5B0}']
procedure connect(const address: TSockAddr_in_any; ACallBack: TProc=nil); overload;
procedure connect(const address: Utf8String; port: word); overload;
procedure setOnConnect(onConnect : TProc);
end;
INPTCPServer = interface;
INPPipe = interface;
TOnTCPClient = reference to procedure(server: INPTCPServer);
TOnPipeClient = reference to procedure(server: INPPipe);
INPTCPServer = interface(INPHandle)
['{E20EB1A4-7A85-4C09-9FA5-FF821C68CEEE}']
procedure setOnClient(OnClose: TOnTCPClient);
procedure setOnError(OnError: TProc<PNPError>);
procedure setOnClose(OnClose: TProc);
procedure bind(const Aaddr: UTF8String; Aport: word);
procedure bind6(const Aaddr: UTF8String; Aport: word; tcp6Only: Boolean=false);
procedure set_nodelay(enable:Boolean);
procedure set_simultaneous_accepts(enable:Boolean);
procedure set_keepalive(enable:Boolean; delay:cardinal);
procedure listen(backlog: integer=UV_DEFAULT_BACKLOG);
end;
INPPipe = interface(INPStream)
['{28E78BEF-400B-4553-AC80-55417B9D94B5}']
procedure connect(const AName: UTF8String);
procedure bind(const AName: UTF8String);
procedure open( fd : uv_file );
procedure accept(server: INPPipe);
procedure setOnConnect(onConnect : TProc);
function getsockname : UTF8String;
function getpeername: UTF8String;
procedure set_pending_instances(acount: integer);
function get_pending_count : integer;
function get_pending_type : uv_handle_type;
procedure set_chmod(flags: integer);
procedure setOnClient(OnClient : TOnPipeClient);
// procedure write2(send_handle: INPStream; cb : TProc);
procedure write2(const data: BufferRef; send_handle: INPStream; Acallback: TProc=nil); overload;
procedure write2(const data: UTF8String;send_handle: INPStream; Acallback: TProc=nil); overload;
procedure listen(backlog: integer=128);
property sockname : UTF8String read getsockname;
property peername : UTF8String read getpeername;
end;
INPSpawn = interface(INPHandle)
['{D756C9DD-76D0-4597-81B4-8E813360B8B5}']
function GetStdio(inx:integer) : puv_stdio_container_t;
function getArgs : TStringList;
procedure spawn;
function getFlags : uv_process_flags_set;
procedure setFlags( flags : uv_process_flags_set);
procedure setOnExit(ACallBack: TProc<int64,integer>);
procedure kill(signnum: integer);
procedure setCWD(const cwd : String);
function getCWD : String;
function getPID : integer;
property args : TStringList read getArgs;
property stdio[ inx:integer ] : puv_stdio_container_t read GetStdio;
property flags : uv_process_flags_set read getFlags write setFlags;
property PID: integer read getPid;
property CWD : String read getCWD write setCWD;
end;
TNPBaseHandle = class(TInterfacedObject, INPHandle)
protected
FHandle : puv_handle_t;
HandleType: uv_handle_type;
FActiveRef : INPHandle;
FOnClose : TProc;
procedure ref;
procedure unref;
function hasRef : Boolean;
procedure Clear;
function is_closing : Boolean;
function is_active : Boolean;
procedure onClose; virtual; //async close handle to keep sync Object with uv_handle
function _uv_handle : puv_handle_t;
procedure setOnClose(OnClose: TProc);
procedure before_closing; virtual; //sync call by Clear
public
constructor Create(AHandleType: uv_handle_type);
destructor Destroy; override;
end;
TNPStream = class(TNPBaseHandle, INPStream, INPHandle)
private
type
PWriteData = ^TWriteData;
TWriteData = record
req : uv_write_t;
{$IFDEF CAPTURE_WRITE_BUF}
buf: uv_buf_t;
{$ENDIF}
callback: TProc;
streamRef: INPHandle;
// {$IFDEF DEBUG}
// debugInfo: Integer;
// {$ENDIF}
end;
private
__buf: TBytes;
FStream: puv_stream_t;
FRead: Boolean;
FListen : Boolean;
FError : Boolean;
FShutdown: Boolean;
FShutdownReq: uv_shutdown_t;
FShutdownRef : INPStream;
FOnError : TProc<PNPError>;
FOnEnd : TProc;
FOnData : TProc<PBufferRef>;
FOnShutdown: TProc;
FOnConnect : TProc;
FConnect : Boolean;
FConnected: Boolean;
FConnectReq: uv_connect_t;
FConnectRef: INPStream;
procedure _writecb(wd: PWriteData; status: integer);
private
procedure _onRead(data: Pbyte; nread: size_t);
procedure _onEnd;
procedure _onError(status: integer);
protected
procedure writeInternal(data: PByte; len: Cardinal; ACallBack: TProc; send_handle: INPStream=nil);
procedure __onError(status: integer);
procedure setOnError(OnError: TProc<PNPError>);
procedure setOnData(onData: TProc<PBufferRef>);
procedure setOnEnd(onEnd: TProc);
procedure setOnConnect(onConnect : TProc);
procedure onClose; override;
procedure tcp_connect(const address: TSockaddr_in_any);
procedure pipe_connect(const name: UTF8String);
procedure pipe_bind(const name: UTF8String);
procedure _onConnect; virtual;
procedure _onConnection; virtual;
procedure write(const data:BufferRef; ACallBack: TProc = nil); overload;
procedure write(const data : UTF8String; ACallBack: TProc = nil); overload;
procedure shutdown(ACallBack: TProc);
procedure listen(backlog:integer);
procedure read_start;
procedure read_stop;
function is_readable : Boolean;
function is_writable: Boolean;
property is_shutdown: Boolean read FShutdown;
public
constructor Create(AHandleType: uv_handle_type);
end;
TNPTCPHandle = class(TNPStream)
procedure bind(const Aaddr: UTF8String; Aport: word);
procedure bind6(const Aaddr: UTF8String; Aport: word; tcp6Only: Boolean=false);
function getpeername : UTF8String;
procedure getpeername_port(out name: UTF8String; out port: word);
function getsockname : UTF8String;
procedure getsockname_port(out name: UTF8String; out port: word);
procedure set_nodelay(enable:Boolean);
procedure set_simultaneous_accepts(enable:Boolean);
procedure set_keepalive(enable:Boolean; delay:cardinal);
constructor Create();
end;
TNPTCPServer = class(TNPTCPHandle, INPTCPServer)
private
FOnClient : TOnTCPClient;
protected
procedure setOnClient(AOnClient: TOnTCPClient);
procedure _onConnection; override;
end;
TNPTCPStream = class(TNPTCPHandle, INPTCPStream, INPTCPConnect)
protected
procedure connect(const address: TSockAddr_in_any; ACallBack: TProc=nil);overload;
procedure connect(const address: UTF8String; port: word); overload;
public
constructor CreateClient( Server : INPTCPServer );
constructor CreateConnect();
constructor CreateSocket( fd : uv_os_sock_t );
constructor CreateFromIPC( PipeIPC: INPPipe );
destructor Destroy; override;
end;
TNPPipe = class(TNPStream, INPPipe)
private
FOnClient: TOnPipeClient;
procedure connect(const AName: UTF8String);
procedure bind(const AName: UTF8String);
function getsockname : UTF8String;
function getpeername: UTF8String;
procedure open( fd : uv_file );
procedure set_pending_instances(acount: integer);
function get_pending_count : integer;
function get_pending_type : uv_handle_type;
procedure set_chmod(flags: integer);
procedure setOnClient(OnClient : TOnPipeClient);
procedure accept(server: INPPipe);
procedure write2(const data: BufferRef; send_handle: INPStream; Acallback: TProc=nil); overload;
procedure write2(const data: UTF8String;send_handle: INPStream; Acallback: TProc=nil); overload;
protected
procedure _onConnection; override;
public
constructor Create();
constructor CreateIPC();
end;
TLoop = class(TEventEmitterComponent)
private
check: INPCheck;
localRef : IValue<TAnyArray>;
public
Fuvloop: puv_loop_t;
embededTasks: INPAsync;
checkQueue: TProcQueue;
nextTickQueue: TProcQueue;
taskCount: integer;
isTerminated: Boolean;
loopThread: uv_thread_t;
procedure ref(const value: IValue);
procedure addTask;
procedure removeTask;
function now: uint64;
procedure terminate;
procedure newThread(p: TProc; onJoin: TProc = nil);
function setImmediate(p: Tproc): IQueueItem;
function NextTick(p: Tproc): IQueueItem;
procedure afterConstruction; override;
function uvloop: puv_loop_t;
destructor Destroy; override;
procedure run_nowait();
procedure run();
end;
INPTTY = interface(INPStream)
['{FA890477-2F37-4A17-84B0-7A7C47994000}']
procedure get_winsize(out width: integer; out height:integer);
end;
INPSTDOUT = interface
['{59FDA766-1C20-4A9F-98F8-10E2B814AD10}']
function stdout_type : uv_handle_type;
function is_file : Boolean;
function is_pipe : Boolean;
function is_tty : Boolean;
function get_tty: INPTTY;
function get_file: uv_file;
function get_pipe: INPPipe;
procedure Print(const s: UTF8String);
procedure PrintLn(const s: UTF8String);
procedure MoveTo(x, y: integer);
procedure MoveTo1x1;
procedure MoveToX(x: integer);
procedure MoveToY(y: integer);
procedure beginPrint;
procedure endPrint;
end;
TNPSpawn = class(TNPBaseHandle, INPSpawn)
private
FProcess: puv_process_t;
FSpawn : Boolean;
Fstdio : array [0..2] of uv_stdio_container_t;
Fargs : TStringList;
Fcurrent_args : TArray<UTF8String>;
Foptions : uv_process_options_t;
FOnExit: TProc<int64, integer>;
FCWD : UTF8String;
private
function GetStdio(inx:integer) : puv_stdio_container_t;
function getArgs : TStringList;
function getFlags : uv_process_flags_set;
procedure setFlags( flags : uv_process_flags_set);
procedure setOnExit(ACallBack: TProc<int64,integer>);
function getCWD : String;
procedure setCWD(const cwd : String);
function getPID : integer;
procedure spawn;
procedure kill(signnum: integer);
procedure _onExit(exit_status: Int64; term_signal: Integer);
public
constructor Create();
destructor Destroy; override;
end;
TUDPSendCallBack = TProc<PNPError>;
TUDPBindFlag = ( ubf_REUSEADDR, ubf_IPV6ONLY );
TUDPBindFlags = set of TUDPBindFlag;
TUDPRcvFlag = ( urf_PARTIAL );
TUDPRcvFlags = set of TUDPRcvFlag;
PUDPData = ^TUDPData;
TUDPData = record
from : uv_sockAddr;
data : BufferRef;
flags : TUDPRcvFlags;
end;
TUDPOnData = TProc<PNPError,PUDPData>;
INPUDP = Interface(INPHandle)
['{DA49CDDE-3610-444A-A7D3-44590073E018}']
procedure open( sock: uv_os_sock_t );
procedure bind(const AAddr : uv_sockAddr; flags : TUDPBindFlags);
function getpeername : uv_sockAddr;
function getsockname : uv_sockAddr;
procedure connect(const sa: uv_sockAddr);
procedure set_membership(const multicast_addr: UTF8String; const interface_addr: UTF8String; membership : uv_membership);
procedure set_multicast_loop(enable : Boolean);
procedure set_multicast_ttl(ttl: integer);
procedure set_multicast_interface(const interface_addr: UTF8String);
procedure set_broadcast(enable : Boolean);
procedure set_ttl(ttl:integer);
// procedure send(const buf: BufferRef; addr: puv_sockAddr; const callback: TUDPSendCallBack);overload;
procedure send(const buf: BufferRef; const callback: TUDPSendCallBack); overload;
procedure send(const buf: BufferRef; const addr: uv_sockAddr; const callback: TUDPSendCallBack); overload;
procedure try_send(const buf: BufferRef; const addr: uv_sockAddr); overload;
procedure try_send(const buf: BufferRef); overload;
procedure setOnData(const onData: TUDPOnData);
function get_send_queue_size : size_t;
function get_send_queue_count : size_t;
end;
TNPUDP = class(TNPBaseHandle, INPUDP)
private
FOnData: TUDPOnData;
__buf: TBytes;
protected
procedure open( sock: uv_os_sock_t );
function uvudp : puv_udp_t; inline;
procedure bind(const Aaddr: uv_sockAddr; flags : TUDPBindFlags);
function getpeername : uv_sockAddr;
function getsockname : uv_sockAddr;
procedure connect(const sa: uv_sockAddr);
procedure set_membership(const multicast_addr: UTF8String; const interface_addr: UTF8String; membership : uv_membership);
procedure set_multicast_loop(enable : Boolean);
procedure set_multicast_ttl(ttl: integer);
procedure set_multicast_interface(const interface_addr: UTF8String);
procedure before_closing; override;
procedure OnClose; override;
procedure set_broadcast(enable : Boolean);
procedure set_ttl(ttl:integer);
procedure send(const buf: BufferRef; const callback: TUDPSendCallBack); overload;
procedure send(const buf: BufferRef; const addr: uv_sockAddr; const callback: TUDPSendCallBack); overload;
procedure send(const buf: BufferRef; addr: puv_sockAddr; const callback: TUDPSendCallBack); overload;
procedure try_send(const buf: BufferRef;const addr: uv_sockAddr); overload;
procedure try_send(const buf: BufferRef); overload;
procedure setOnData(const onData: TUDPOnData);
function get_send_queue_size : size_t;
function get_send_queue_count : size_t;
public
constructor Create();
destructor Destroy(); override;
end;
function newRWLock : IRWLock;
function SetCheck(cb:TProc) : INPCheck;
function SetPrepare(cb:TProc) : INPPrepare;
function SetIdle(cb:TProc) : INPIdle;
function SetAsync(cb:TProc) : INPAsync;
function SetTimer(cb:TProc; Atimeout,Arepeat:uint64) : INPTimer;
procedure Cleartimer(var handle: INPTimer);
procedure ClearInterval(var handle: INPTimer); inline;
procedure ClearTimeout(var handle: INPTimer); inline;
function SetInterval(p: Tproc; AInterval: Uint64): INPTimer;
function SetTimeout(p: Tproc; ATimeout: Uint64): INPTimer;
function setFSWatch(p: TWatchCallBack; const Path: String; flag:Integer=0) : INPWatch;
function thread_create(p : TProc) : uv_thread_t;
procedure thread_join(tid: uv_thread_t);
function NextTick(p: TProc) : IQueueItem;
function setImmediate(p: Tproc): IQueueItem;
procedure LoopHere;
function loop: TLoop;
function stdOut : INPSTDOUT;
function stdErr : INPSTDOUT;
function stdIn : INPStream;
function stdInRaw : INPStream;
procedure dns_resolve(const addr: UTF8String; const onResolved: TProc<integer,UTF8String>);
function newArray(values: array of const) : TAnyArray;
function np_const : Pnodepas_constants;
type
TNPBarrier = record
uvbarrier: uv_barrier_t;
procedure Init( ACount : integer );
procedure wait;
end;
const
ev_loop_shutdown = 1;
ev_loop_beforeTerminate = 2;
{$IFDEF DEBUG}
threadvar
debugInfoValue : integer;
{$ENDIF}
implementation
{$IFDEF MSWINDOWS}
uses WinApi.Windows, np.fs;
{$ELSE}
uses np.fs;
{$ENDIF}
type
P_tty_w_req = ^TNPTTY_w_req;
TNPTTY_w_req = record
wr: uv_write_t;
msg: UTF8String;
end;
TNPTTY = class( TNPStream, INPTTY )
private
Ftty: puv_tty_t;
procedure get_winsize(out width: integer; out height:integer);
public
constructor Create(fd:uv_os_fd_t=UV_STDOUT_FD);
destructor Destroy; override;
end;
TNPSTDOUT = class( TInterfacedObject, INPSTDOUT )
private
FHandleType: uv_handle_type;
FStream: INPStream;
FUVFile: uv_file;
pbuf: UTF8String;
pcount: integer;
procedure PrintLn(const s: UTF8String);
procedure Print(const s: UTF8String);
procedure MoveTo(x, y: integer);
procedure MoveTo1x1;
procedure MoveToX(x: integer);
procedure MoveToY(y: integer);
procedure beginPrint;
procedure endPrint;
procedure flush;
function stdout_type : uv_handle_type;
function is_file : Boolean;
function is_pipe : Boolean;
function is_tty : Boolean;
function get_tty: INPTTY;
function get_file: uv_file;
function get_pipe: INPPipe;
public
constructor Create(fd:uv_os_fd_t=UV_STDOUT_FD);
destructor Destroy; override;
end;
TNPTTY_INPUT = class( TNPStream )
constructor Create(raw:Boolean=false);
end;
threadvar
tv_loop : TLoop;
tv_stdout: INPSTDOUT;
tv_stderr: INPSTDOUT;
tv_stdin : INPStream;
{$IFDEF MSWINDOWS}
function uv_dup( fd: uv_os_fd_t) : uv_os_fd_t;
begin
if not DuplicateHandle(GetCurrentProcess, fd, GetCurrentProcess, @result,0, false, DUPLICATE_SAME_ACCESS) then
result := INVALID_HANDLE_VALUE;
end;
{$ENDIF}
function loop : TLoop;
begin
if not assigned(tv_loop) then
TLoop.Create(nil);
assert(assigned(tv_loop));
result := tv_loop;
end;
procedure LoopHere;
begin
if not assigned(tv_loop) then
tv_loop := TLoop.Create(nil);
tv_loop.run;
tv_stdin := nil;
tv_stdout := nil;
end;
function TProcQueue.add(p: TProc) : IQueueItem;
var
tmp : PLinked;
begin
if not assigned(p) then
exit(nil);
new(tmp);
tmp.Item := TQueueItem.Create(p);
tmp.Next := nil;
lock.beginWrite;
if head = nil then
begin
assert(tail = nil);
head := tmp;
tail := tmp;
end
else
begin
assert(tail <> nil);
tail.Next := tmp;
tail := tmp;
end;
//inc(count);
lock.endWrite;
result := tmp.Item;
end;
constructor TProcQueue.Create;
begin
lock := newRWLock;
end;
destructor TProcQueue.Destroy;
var
tmp : PLinked;
begin
Lock.beginWrite;
while head <> nil do
begin
tmp := head;
head := tmp.Next;
tmp.Item := nil;
Dispose(tmp);
end;
Lock.endWrite;
inherited;
end;
function TProcQueue.emit : Boolean;
var
tmp : PLinked;
begin
if isEmpty then
exit(false);
lock.BeginWrite;
tmp := head;
head := tmp.Next;
if head = nil then
begin
assert(tail = tmp);
tail := nil;
end;
//dec(count);
//assert(count >= 0);
lock.endWrite;
try
tmp.Item.invoke;
except
//TODO: unhandled exception
// on E:Exception do
// application.log_warn('Unhandled exception: '+E.Message);
end;
tmp.Item := nil;
Dispose(tmp);
exit(not IsEmpty);
end;
function TProcQueue.isEmpty: Boolean;
begin
lock.beginRead;
result := not assigned(head);
lock.endRead;
end;
{ TQueueItem }
procedure TQueueItem.Cancel;
begin
proc := nil;
end;
constructor TQueueItem.Create(p: TProc);
begin
proc := p;
end;
destructor TQueueItem.Destroy;
begin
inherited;
end;
procedure TQueueItem.Invoke;
var
p : TProc;
begin
p := Proc;
proc := nil;
if assigned(p) then
p();
p := nil;
end;
{ TLoop }
procedure TLoop.addTask;
begin
inc(taskCount);
if taskCount = 1 then
embededTasks.ref;
end;
procedure TLoop.afterconstruction;
begin
inherited;
tv_loop := self;
loopThread := uv_thread_self;
New(Fuvloop);
np_ok( uv_loop_init(Fuvloop) );
assert( assigned(Fuvloop));
checkQueue := TProcQueue.Create;
nextTickQueue := TProcQueue.Create;
embededTasks := SetAsync(nil);
embededTasks.unref;
embededTasks.setOnClose(
procedure
begin
emit(ev_loop_shutdown,self);
while nextTickQueue.emit do;
while checkQueue.emit do
while nextTickQueue.emit do;
end);
check := SetCheck(
procedure
begin
checkQueue.emit;
end);
check.unref;
end;
destructor TLoop.Destroy;
begin
FreeAndNil(checkQueue);
FreeAndNil(nextTickQueue);
dispose(uvloop);
Fuvloop := nil;
tv_loop := nil;
inherited;
end;
procedure TLoop.newThread(p: TProc; onJoin: TProc);
var
thd : uv_thread_t;
async: INPAsync;
begin
if not assigned(p) then
exit;
async := SetAsync(
procedure
begin
if assigned(onJoin) then
begin
thread_join( thd );
onJoin();
onJoin := nil;
async.Clear;
async := nil;
end;
end
);
thd := thread_create(
procedure
begin
try
p();
except
end;
p := nil;
async.send;
end);
end;
function TLoop.NextTick(p: Tproc): IQueueItem;
begin
result := nil;
if assigned(nextTickQueue) and (assigned(p)) then
begin
result := nextTickQueue.add(p);
end;
end;
function TLoop.now: uint64;
begin
result := uv_now(uvloop);
end;
procedure TLoop.ref(const value: IValue);
begin
if not assigned(localRef) then
localRef := TAnyArray.Create();
localRef.this.Push(value)
end;
procedure TLoop.removeTask;
begin
dec( taskCount );
if taskCount = 0 then
embededTasks.unref;
end;
procedure __cbWalk(handle: puv_handle_t; arg: pinteger); cdecl;
//var
// ht : uv_handle_type;
begin
// ht := uv_get_handle_type(handle);
if uv_is_closing(handle) = 0 then
begin
uv_close(handle, uv_get_close_cb(handle) );
end;
end;
procedure TLoop.run_nowait();
begin
loopThread := uv_thread_self;
while nextTickQueue.emit do;
if checkQueue.isEmpty then
check.unref
else
check.ref;
uv_run(uvloop, UV_RUN_NOWAIT);
end;
procedure TLoop.run();
begin
try
repeat
while nextTickQueue.emit do;
if assigned(localRef) then
localRef.this.Length := 0;
if not checkQueue.isEmpty then
begin
check.ref;
uv_run(uvloop, UV_RUN_NOWAIT);
end
else
begin
check.unref;
uv_run(uvloop, UV_RUN_ONCE);
end;
if isTerminated then
break;
until (uv_loop_alive(uvloop) = 0) and (checkQueue.isEmpty);
uv_walk(uvloop, @__cbWalk, nil);
uv_run(uvloop, UV_RUN_DEFAULT);
np_ok( uv_loop_close(uvloop) );
check := nil;
embededTasks := nil;
finally
Free;
end;
end;
function TLoop.setImmediate(p: Tproc): IQueueItem;
begin
result := nil;
if assigned(checkQueue) and (assigned(p)) then
begin
result := checkQueue.add(p);
if uv_thread_self <> loopThread then
embededTasks.send;
end;
end;
function SetInterval(p: Tproc; AInterval: Uint64): INPTimer;
begin
result := SetTimer(p, AInterval, AInterval);
end;
function SetTimeout(p: Tproc; ATimeout: Uint64): INPTimer;
begin
result := SetTimer(p, ATimeout, 0);
end;
procedure TLoop.terminate;
begin
if not isTerminated then
begin
isTerminated := true;
emit(ev_Loop_beforeTerminate);
uv_stop(uvloop); //break run_default loop to check isTerminated
end;
end;
function TLoop.uvloop: puv_loop_t;
begin
result := Fuvloop;
end;
type
TNPCBHandle = class(TNPBaseHandle)
private
FCallBack: TProc;
protected
procedure onClose; override;
public
constructor Create(AHandleType: uv_handle_type; ACallBack: TProc);
end;
TNPCheck = Class(TNPCBHandle, INPCheck)
constructor Create(ACallBack: TProc);
public
destructor Destroy; override;
end;
TNPPrepare = class(TNPCBHandle, INPPrepare)
constructor Create(ACallBack: TProc);
public
destructor Destroy; override;
end;
TNPIdle = class(TNPCBHandle, INPIdle)
constructor Create(ACallBack: TProc);
public
destructor Destroy; override;
end;
TNPAsync = class(TNPCBHandle, INPASync)
constructor Create(ACallBack: TProc);
procedure send;
destructor Destroy; override;
end;
procedure __cb(handle: puv_handle_t); cdecl;
var
ud : TNPCBHandle;
begin
ud := uv_get_user_data(handle);
assert(assigned(ud));
if assigned( ud.FCallBack ) then
ud.FCallBack();
end;
function SetCheck(cb:TProc) : INPCheck;
begin
result := TNPCheck.Create(cb);
end;
function SetPrepare(cb:TProc) : INPPrepare;
begin
result := TNPPrepare.Create(cb);
end;
function SetIdle(cb:TProc) : INPIdle;
begin
result := TNPIdle.Create(cb);
end;
function SetAsync(cb:TProc) : INPAsync;
begin
result := TNPAsync.Create(cb);
end;
{ TNPCheck }
constructor TNPCheck.Create(ACallBack: TProc);
begin
inherited Create(UV_CHECK, ACallBack);
np_ok(uv_check_init(loop.uvloop , puv_check_t( Fhandle) ));
np_ok(uv_check_start(puv_check_t(Fhandle), @__cb));
FActiveRef := self;
end;
destructor TNPCheck.Destroy;
begin
//OutputdebugString('TNPCheck.Destroy');
inherited;
end;
{ TNPPrepare }
constructor TNPPrepare.Create(ACallBack: TProc);
begin
inherited Create(UV_PREPARE, ACallBack);
uv_prepare_init(loop.uvloop, puv_prepare_t(Fhandle));
np_ok(uv_prepare_start(puv_prepare_t(Fhandle), @__cb));
FActiveRef := self;
end;
destructor TNPPrepare.Destroy;
begin
//OutputdebugString('TNPPrepare.Destroy');
inherited;
end;
{ TNPIdle }
constructor TNPIdle.Create(ACallBack: TProc);
begin
inherited Create(UV_IDLE,ACallBack);
uv_idle_init(loop.uvloop, puv_idle_t(FHandle));
np_ok( uv_idle_start(puv_idle_t(FHandle), @__cb) );
FActiveRef := self;
end;
destructor TNPIdle.Destroy;
begin
//OutputdebugString('TNPIdle.Destroy');
inherited;
end;
constructor TNPAsync.Create(ACallBack: TProc);
begin
inherited Create(UV_ASYNC,ACallBack);
uv_async_init(loop.uvloop, puv_async_t(FHandle), @__cb);
FActiveRef := self;
end;
constructor TNPCBHandle.Create(AHandleType: uv_handle_type; ACallBack: TProc);
begin
inherited Create(AHandleType);
FCallBack := ACallBack;
end;
procedure TNPCBHandle.onClose;
begin
inherited;
FCallBack := nil;
end;
destructor TNPAsync.Destroy;
begin
// WriteLn('TNPAsync.Destroy');
inherited;
end;
procedure TNPAsync.send;
begin
np_ok( uv_async_send(puv_async_t(FHandle)) );
end;
type
TRWLock = class(TInterfacedObject,IRWLock)
strict private
rwlock: uv_rwlock_t;
procedure beginRead;
procedure endRead;
procedure beginWrite;
procedure endWrite;
public
constructor Create;
destructor Destroy; override;
end;
function newRWLock : IRWLock;
begin
result := TRWLock.Create;
end;
{ TRWLock }
constructor TRWLock.Create;
begin
uv_rwlock_init(@rwlock);
end;
destructor TRWLock.Destroy;
begin
inherited;
uv_rwlock_destroy(@rwlock);
end;
procedure TRWLock.beginRead;
begin
uv_rwlock_rdlock(@rwlock);
end;
procedure TRWLock.endRead;
begin
uv_rwlock_rdunlock(@rwlock);
end;
procedure TRWLock.beginWrite;
begin
uv_rwlock_wrlock(@rwlock);
end;
procedure TRWLock.endWrite;
begin
uv_rwlock_wrunlock(@rwlock);
end;
{ TNPTCPHandle }
constructor TNPTCPHandle.Create();
begin
inherited Create(UV_TCP);
np_ok( uv_tcp_init(loop.uvloop, puv_tcp_t( FHandle )) );
FActiveRef := self as INPHandle;
end;
procedure TNPTCPHandle.bind(const Aaddr: UTF8String; Aport: word);
var
addr: Tsockaddr_in_any;
begin
try
np_ok( uv_ip4_addr(PUTF8Char(Aaddr),APort,addr.ip4) );
except
np_ok( uv_ip6_addr(PUTF8Char(Aaddr),APort,addr.ip6) );
end;
np_ok( uv_tcp_bind(puv_tcp_t(FHandle),addr,0) );
end;
procedure TNPTCPHandle.bind6(const Aaddr: UTF8String; Aport: word;
tcp6Only: Boolean);
var
addr: Tsockaddr_in_any;
begin
np_ok( uv_ip6_addr(@Aaddr[1],APort,addr.ip6) );
np_ok( uv_tcp_bind(puv_tcp_t(FHandle),addr,ord(tcp6Only)) );
end;
function TNPTCPHandle.getpeername: UTF8String;
var
port : word;
begin
result := '';
getpeername_port(result,port);
end;
procedure TNPTCPHandle.getpeername_port(out name: UTF8String; out port: word);
var
sa: Tsockaddr_in_any;
len : integer;
nameBuf : array [0..128] of UTF8Char;
begin
len := sizeof(sa);
np_ok( uv_tcp_getpeername(puv_tcp_t(FHandle),sa,len) );
case sa.ip4.sin_family of
UV_AF_INET:
begin
np_ok( uv_ip4_name(PSockAddr_In(@sa), @nameBuf, sizeof(nameBuf) ) );
name := UTF8String(PUTF8Char( @nameBuf ));
end;
UV_AF_INET6:
begin
np_ok( uv_ip6_name(PSockAddr_In6(@sa), @nameBuf, sizeof(nameBuf) ) );
name := UTF8String(PUTF8Char( @nameBuf ));
end;
else
assert(false);
end;
port := uv_get_ip_port( Psockaddr_in(@sa) );
end;
function TNPTCPHandle.getsockname: Utf8string;
var
port : word;
begin
getsockname_port(result, port);
end;
procedure TNPTCPHandle.getsockname_port(out name: UTF8String; out port: word);
var
sa: Tsockaddr_in_any;
len : integer;
nameBuf : array [0..128] of UTF8Char;
begin
len := sizeof(sa);
np_ok( uv_tcp_getsockname(puv_tcp_t(FHandle),sa,len) );
case sa.ip4.sin_family of
UV_AF_INET:
begin
np_ok( uv_ip4_name(PSockAddr_In(@sa), @nameBuf, sizeof(nameBuf) ) );
name := UTF8String(PUTF8Char( @nameBuf ));
end;
UV_AF_INET6:
begin
np_ok( uv_ip6_name(PSockAddr_In6(@sa), @nameBuf, sizeof(nameBuf) ) );
name := UTF8String(PUTF8Char( @nameBuf ));
end;
else
assert(false);
end;
port := uv_get_ip_port( Psockaddr_in(@sa) );
end;
procedure TNPTCPHandle.set_keepalive(enable: Boolean; delay: cardinal);
begin
np_ok( uv_tcp_keepalive(puv_tcp_t( FHandle ),ord(enable),delay) );
end;
procedure TNPTCPHandle.set_nodelay(enable: Boolean);
begin
np_ok( uv_tcp_nodelay(puv_tcp_t( FHandle ),ord(enable)) );
end;
procedure TNPTCPHandle.set_simultaneous_accepts(enable: Boolean);
begin
np_ok( uv_tcp_simultaneous_accepts(puv_tcp_t( FHandle ),ord(enable)) );
end;
{ TNPTCPServer }
//procedure TNPTCPServer.listen(backlog: integer);
//begin
// _listen(backlog);
//end;
procedure TNPTCPServer.setOnClient(AOnClient: TOnTCPClient);
begin
FOnClient := AOnClient;
end;
procedure TNPTCPServer._onConnection;
begin
if assigned(FOnClient) then
FOnClient(self);
end;
procedure __connect_cb(req: puv_connect_t; status: integer);cdecl;
var
ud : TNPStream;
begin
ud := uv_get_user_data(req);
assert(assigned(ud));
if status = 0 then
begin
ud.FConnected := true;
if assigned(ud.FOnConnect) then
try
ud.FOnConnect();
except
end;
ud.FOnConnect := nil;
end
else
ud.__onError(status);
ud.FConnectRef := nil;
end;
procedure __shutdown_cb(req: puv_shutdown_t; status: integer); cdecl;
var
ud : TNPStream;
begin
{TODO: move to class}
ud := uv_get_user_data(req);
try
// if status = 0 then
// begin
if assigned( ud.FOnShutdown ) then
ud.FOnShutdown();
ud.FOnShutdown := nil;
// if not ud.FRead then
ud.Clear;
// end
// else
// ud.__onError(status);
except
end;
ud.FShutdownRef := nil;
end;
procedure __connection_cb(server : puv_stream_t; status: integer); cdecl;
var
ud : TNPStream;
begin
ud := uv_get_user_data(server);
try
if status = 0 then
ud._onConnection
else
begin
ud.__onError(status);
end;
except
end;
end;
procedure __alloc_cb(handle:puv_handle_t;suggested_size:size_t; var buf:uv_buf_t );cdecl;
var
ud : TNPStream;
begin
ud := uv_get_user_data(handle);
assert(assigned(ud));
if suggested_size > length(ud.__buf) then
begin
Setlength(ud.__buf, (suggested_size + $4000) and (not $3FFF));
end;
buf.len := suggested_size;
buf.base := @ud.__buf[0];
end;
procedure __read_cb(stream: puv_stream_t; nread:ssize_t; const buf: uv_buf_t);cdecl;
var
ud : TNPStream;
begin
if nread = 0 then
exit;
{TODO: move to class}
ud := uv_get_user_data(stream);
assert(assigned(ud));
if (nread < 0) then
begin
ud.read_stop;
if (nread = UV_EOF) then
begin
try
ud._onEnd;
except
end;
ud.Clear;
end
else
ud.__onError(nread);
exit;
end;
try
ud._OnRead(@ud.__buf[0], nread)
except
end;
end;
procedure __write_cb(req : puv_write_t; status : integer);cdecl;
var
ud : TNPStream;
wd : TNPStream.PWriteData;
begin
ud := uv_get_user_data(req);
assert(assigned(ud));
wd := TNPStream.PWriteData(req);
ud._writecb(wd,status);
end;
{ TNPStream }
constructor TNPStream.Create(AHandleType: uv_handle_type);
begin
assert( AHandleType in [UV_NAMED_PIPE, UV_TCP, UV_TTY] );
inherited Create(AHandleType);
FStream := puv_stream_t( FHandle );
end;
function TNPStream.is_readable: Boolean;
begin
result := uv_is_writable(Fstream) <> 0;
end;
procedure TNPStream.listen(backlog: integer);
begin
if not FListen then
begin
FListen := true;
np_ok( uv_listen(Fstream,backlog,@__connection_cb) );
end;
end;
procedure TNPStream._onConnect;
begin
end;
procedure TNPStream._onConnection;
begin
end;
procedure TNPStream._onEnd;
begin
if assigned(FOnEnd) then
FOnEnd();
FOnEnd := nil;
end;
procedure TNPStream._onError(status: integer);
var
err: TNPError;
begin
FOnData := nil;
FOnEnd := nil;
if assigned(FOnError) then
begin
err.Init(status);
FOnError(@err);
end;
FOnError := nil;
end;
procedure TNPStream._onRead(data: Pbyte; nread: size_t);
var
arg: BufferRef;
begin
if assigned(FOnData) then
begin
arg := BufferRef.CreateWeakRef(data,nread);
FOnData(@arg);
end;
end;
procedure TNPStream._writecb(wd: PWriteData; status : integer);
begin
if status <> 0 then
__onError(status)
else
if assigned(wd.callback) then
try
wd.callback();
except
end;
wd.callback := nil;
wd.streamRef := nil;
{$IFDEF CAPTURE_WRITE_BUF}
if (wd.buf.len > 0) then
begin
assert( wd.buf.base <> nil );
FreeMem( wd.buf.base );
end;
{$ENDIF}
dispose(wd);
end;
procedure TNPStream.__onError(status: integer);
begin
if not FError then
begin
FError := true;
try
_onError(status);
except
end;
Clear;
end;
end;
procedure TNPStream.read_start;
begin
if not FRead then
begin
np_ok( uv_read_start(Fstream,@__alloc_cb,@__read_cb) );
FRead := true;
end;
end;
procedure TNPStream.read_stop;
begin
if FRead then
begin
np_ok( uv_read_stop(FStream));
FRead := false;
if FShutdown then
Clear;
end;
end;
procedure TNPStream.setOnConnect(onConnect: TProc);
begin
FOnConnect := onConnect;
end;
procedure TNPStream.setOnData(onData: TProc<PBufferRef>);
var
wasAssigned : Boolean;
begin
wasAssigned := assigned(FOnData);
FOnData := onData;
if assigned(FOnData) and not wasAssigned then
read_start
else
if not assigned(FOnData) and wasAssigned then
read_stop;
end;
procedure TNPStream.setOnEnd(onEnd: TProc);
begin
FOnEnd := onEnd;
end;
procedure TNPStream.setOnError(OnError: TProc<PNPError>);
begin
FOnError := onError;
end;
procedure TNPStream.shutdown(ACallBack:TProc);
begin
if not is_closing and not FError and not FShutdown then
begin
if not FConnected then
Clear
else
begin
try
FOnShutdown := ACallBack;
uv_set_user_data(@FShutdownReq,self);
np_ok( uv_shutdown(@FShutdownReq,FStream,@__shutdown_cb) );
FShutdown := true;
FShutdownRef := self;
except
Clear;
end;
end;
end;
end;
procedure TNPStream.tcp_connect(const address: TSockaddr_in_any);
begin
if not FConnect then
begin
uv_set_user_data(@FConnectReq, self);
np_ok( uv_tcp_connect(@FConnectReq, puv_tcp_t(FHandle), @address, @__connect_cb) );
FConnect := true;
FConnectRef := self;
end;
end;
function TNPStream.is_writable: Boolean;
begin
result := uv_is_writable(FStream) <> 0;
end;
procedure TNPStream.onClose;
begin
if FRead then
read_stop;
FOnData := nil;
FOnEnd := nil;
FOnError := nil;
inherited;
end;
procedure TNPStream.pipe_bind(const name: UTF8String);
begin
np_ok( uv_pipe_bind(puv_pipe_t(FHandle),PUTF8Char(name)));
end;
procedure TNPStream.pipe_connect(const name: UTF8String);
begin
if not FConnect then
begin
FConnect := true;
uv_set_user_data(@FConnectReq, self);
uv_pipe_connect(@FConnectReq,puv_pipe_t(FHandle), PUTF8Char(name),@__connect_cb);
end;
end;
procedure TNPStream.writeInternal(data: PByte; len: Cardinal; ACallBack: TProc; send_handle: INPStream=nil);
var
wd : PWriteData;
status : integer;
{$IFNDEF CAPTURE_WRITE_BUF}
buf : uv_buf_t;
{$ENDIF}
begin
new(wd);
wd.callback := ACallBack;
uv_set_user_data(wd, self);
if len > 0 then
begin
assert(data <> nil);
{$IFDEF CAPTURE_WRITE_BUF}
wd.buf.len := len;
GetMem( wd.buf.base, len );
move( data^, wd.buf.base^, len );
{$ELSE}
buf.len := len;
buf.base := data;
{$ENDIF}
end
else
begin
{$IFDEF CAPTURE_WRITE_BUF}
wd.buf.len := 0;
wd.buf.base := nil;
{$ELSE}
buf.len := 0;
buf.base := nil;
{$ENDIF}
end;
wd.streamRef := self;
if send_handle = nil then
status := uv_write(puv_write_t(wd),FStream, {$IFDEF CAPTURE_WRITE_BUF} @wd.buf {$ELSE} @buf {$ENDIF}, 1, @__write_cb)
else
status := uv_write2(puv_write_t(wd),FStream, {$IFDEF CAPTURE_WRITE_BUF} @wd.buf {$ELSE} @buf {$ENDIF}, 1, puv_stream_t( send_handle._uv_handle ), @__write_cb);
if status <> 0 then
begin
NextTick(
procedure
begin
_writecb(wd, status);
end);
end;
end;
procedure TNPStream.write(const data: UTF8String; ACallBack: TProc);
var
dataRef : UTF8String;
begin
dataRef := data;
if length(data) > 0 then
writeInternal(PByte( @dataRef[1] ),length(data), ACallBack)
else
writeInternal(nil,0, ACallBack)
end;
procedure TNPStream.write(const data: BufferRef; ACallBack: TProc);
begin
writeInternal(data.ref,data.length, ACallBack)
end;
procedure __on_close(handle: puv_handle_t); cdecl;
var
ud : TNPBaseHandle;
begin
ud := uv_get_user_data(handle);
uv_set_close_cb(handle,nil);
assert(assigned(ud));
try
ud.OnClose;
except
end;
ud.FActiveRef := nil;
end;
{ TNPBaseHandle }
procedure TNPBaseHandle.before_closing;
begin
end;
procedure TNPBaseHandle.Clear;
begin
if not is_closing then
begin
before_closing;
uv_close( Fhandle, uv_get_close_cb( Fhandle) );
end;
end;
constructor TNPBaseHandle.Create(AHandleType: uv_handle_type);
var
typeLen : size_t;
begin
inherited Create;
HandleType := AHandleType;
typeLen := uv_handle_size(AHandleType);
GetMem(FHandle, typeLen);
FillChar(FHandle^,typeLen,0);
uv_set_close_cb(Fhandle, @__on_close);
uv_set_user_data(FHandle, self);
end;
destructor TNPBaseHandle.Destroy;
begin
if assigned(Fhandle) then
begin
if not is_closing then
uv_close( Fhandle, nil ); //constructor fail case!
FreeMem(FHandle);
FHandle := nil;
end;
inherited;
end;
function TNPBaseHandle.hasRef: Boolean;
begin
result := uv_has_ref(Fhandle) <> 0;
end;
function TNPBaseHandle.is_active: Boolean;
begin
result := uv_is_active(FHandle) <> 0;
end;
function TNPBaseHandle.is_closing: Boolean;
begin
result := not assigned( FHandle) or not assigned(FActiveRef) or (uv_is_closing(FHandle) <> 0) ;
end;
procedure TNPBaseHandle.onClose;
begin
if assigned(FOnClose) then
begin
FOnClose();
end;
FOnClose := nil;
end;
procedure TNPBaseHandle.ref;
begin
uv_ref(Fhandle);
end;
procedure TNPBaseHandle.setOnClose(OnClose: TProc);
begin
FOnClose := OnClose;
end;
procedure TNPBaseHandle.unref;
begin
uv_unref(Fhandle);
end;
function TNPBaseHandle._uv_handle: puv_handle_t;
begin
result := FHandle;
end;
type
TNPTimer = Class(TNPBaseHandle, INPTimer)
protected
procedure onClose; override;
public
FCallBack : Tproc;
procedure SetRepeat(Arepeat: uint64);
function GetRepeat : uint64;
procedure Again;
constructor Create(ACallBack: TProc; Atimeout,Arepeat:uint64);
destructor Destroy; override;
end;
procedure __cbTimer(handle: puv_timer_t); cdecl;
var
ud : TNPTimer;
ref: INPHandle;
begin
ud := uv_get_user_data(handle);
ref := ud.FActiveRef;
if assigned(ud.FCallBack) then
begin
//this_timer := ud as INPTimer;
try
ud.FCallBack();
except
end;
end;
if (uv_is_closing( puv_handle_t(handle) )=0) and (uv_is_active( puv_handle_t( handle ) ) = 0) then
ref.Clear;
//this_timer := nil;
end;
function Settimer(cb:TProc; Atimeout,Arepeat:uint64) : INPtimer;
begin
result := TNPTimer.Create(cb,ATimeout, ARepeat);
end;
procedure Cleartimer(var handle: INPTimer);
begin
if assigned(handle) then
begin
handle.Clear;
handle := nil;
end;
end;
procedure ClearInterval(var handle: INPTimer);
begin
Cleartimer(handle);
end;
procedure ClearTimeout(var handle: INPTimer);
begin
Cleartimer(handle);
end;
{ TNPTimer }
procedure TNPTimer.Again;
begin
if (GetRepeat > 0) and (uv_is_active(FHandle) <> 0) then
uv_timer_again(puv_timer_t(FHandle));
end;
constructor TNPTimer.Create(ACallBack: TProc; Atimeout,Arepeat:uint64);
begin
FCallBack := ACallBack;
inherited Create(UV_TIMER);
uv_timer_init( loop.uvloop, puv_timer_t(FHandle) );
np_ok( uv_timer_start(puv_timer_t(FHandle),@__cbTimer,Atimeout,Arepeat) );
FActiveRef := self;
end;
destructor TNPTimer.Destroy;
begin
// outputDebugString('TNPTimer.Destroy');
inherited;
end;
function TNPTimer.GetRepeat: uint64;
begin
result := uv_timer_get_repeat(puv_timer_t(FHandle));
end;
procedure TNPTimer.onClose;
begin
inherited;
FCallBack := nil;
end;
procedure TNPTimer.SetRepeat(Arepeat: uint64);
begin
uv_timer_set_repeat(puv_timer_t(FHandle), aRepeat);
end;
function NextTick(p: TProc) : IQueueItem;
begin
result := loop.NextTick(p);
end;
function setImmediate(p: Tproc): IQueueItem;
begin
result := loop.setImmediate(p)
end;
type
TNPWatch = Class(TNPBaseHandle, INPWatch)
private
FPath: UTF8String;
FCallBack : TWatchCallBack;
protected
function getpath: String;
procedure onClose; override;
procedure before_closing; override;
public
constructor Create(const ACallBack: TWatchCallBack; const APath: String; flags : integer);
destructor Destroy; override;
end;
{ TNPTCPStream }
procedure TNPTCPStream.connect(const address: TSockAddr_in_any; ACallBack: TProc);
begin
if assigned( ACallBack ) then
setOnConnect(ACallBack);
tcp_connect( address );
end;
procedure TNPTCPStream.connect(const address: UTF8String; port: word);
var
addr: Tsockaddr_in_any;
ref: INPTCPConnect;
begin
case IsIP(address) of
4:
begin
np_ok( uv_ip4_addr(PUTF8Char(address),Port,addr.ip4) );
connect(addr);
end;
6:
begin
np_ok( uv_ip6_addr(PUTF8Char(address),Port,addr.ip6) );
connect(addr);
end;
else
begin
ref := self;
dns_resolve(address,
procedure (status: integer; resolved_address: UTF8String)
begin
try
if status < 0 then
__onError(status)
else
connect(resolved_address, port);
except
end;
ref := nil;
end);
end;
end;
end;
constructor TNPTCPStream.CreateClient(Server: INPTCPServer);
begin
inherited Create();
np_ok( uv_accept( puv_stream_t(Server._uv_handle), puv_stream_t(FHandle) ) );
end;
constructor TNPTCPStream.CreateConnect();
begin
inherited Create();
end;
constructor TNPTCPStream.CreateFromIPC(PipeIPC: INPPipe);
begin
inherited Create();
np_ok( uv_accept( puv_stream_t(PipeIPC._uv_handle), puv_stream_t(FHandle) ) );
end;
constructor TNPTCPStream.CreateSocket(fd: uv_os_sock_t);
begin
inherited Create();
uv_tcp_open(puv_tcp_t( FHandle ),fd);
end;
destructor TNPTCPStream.Destroy;
begin
// WriteLn('destroy: ',ClassName);
inherited;
end;
type
PResolveReq = ^TResolveReq;
TResolveReq = record
req: uv_getaddrinfo_t;
onResolved: TProc<integer,UTF8String>;
addr : string;
end;
procedure __on_resolved(req: puv_getaddrinfo_t; status:integer; res: _PAddrInfo); cdecl;
var
lreq : PResolveReq;
ip: UTF8String;
// addr: UTF8String;
// onResolved2: TProc<integer,UTF8String>;
begin
lreq := PResolveReq(req);
try
if status >= 0 then
begin
case res.ai_family of
2:
begin
SetLength(ip, 64);
uv_ip4_name(PSockAddr_In(res.ai_addr),PAnsiChar(ip),64);
SetLength(ip, CStrLen( PAnsiChar(ip) ));
//move(res.ai_addr^, addr.ip4, sizeof( addr.ip4 ));
//uv_set_ip_port(@addr.ip4,this.FConnectPort);
end;
23:
begin
// assert(false);
// move(res.ai_addr^, addr.ip6, sizeof( addr.ip6 ));
// uv_set_ip_port(@addr.ip4,this.FConnectPort);
SetLength(ip, 64);
uv_ip6_name(PSockAddr_In6(res.ai_addr),PAnsiChar(ip),64);
SetLength(ip, CStrLen( PAnsiChar(ip) ));
end;
end;
end;
if res <> nil then
uv_freeaddrinfo(res);
// if status >= 0 then
lReq.onResolved(status,ip);
// else
// begin
// onResolved2 := lReq.onResolved;
// addr := lReq.addr;
// loop.newThread(
// procedure
// var
// he : PHostEnt;
// addrIn : TInAddr;
// begin
//
// he := np.winsock.gethostbyname(addr);
// if assigned(he) and (he.h_addrtype = AF_INET) then
// begin
// addrIn.S_addr := PCardinal( he.h_address_list^ )^;
// ip := inet_ntoa(addrIn);
// status := 0;
// end;
// end,
// procedure
// begin
// onResolved2(status,ip);
// end
// );
//
// end;
finally
//lReq.onResolved := nil;
dispose(lreq);
end;
end;
procedure dns_resolve(const addr: UTF8String; const onResolved: TProc<integer,UTF8String>);
var
req: PResolveReq;
begin
if Assigned(onResolved) then
begin
new(req);
req.addr := addr;
req.onResolved := OnResolved;
try
np_ok( uv_getaddrinfo(loop.uvloop,@req.req,@__on_resolved, PAnsiChar( addr ), nil ,nil));
except
req.onResolved := nil;
dispose(req);
raise;
end;
end;
end;
{ TNPPipe }
procedure TNPPipe.accept(server: INPPipe);
begin
np_ok( uv_accept( puv_stream_t(Server._uv_handle), puv_stream_t(FHandle) ) );
end;
procedure TNPPipe.bind(const AName: UTF8String);
begin
pipe_bind(AName);
end;
procedure TNPPipe.connect(const AName: UTF8String);
begin
pipe_connect(AName);
end;
constructor TNPPipe.Create();
begin
inherited Create(UV_NAMED_PIPE);
np_ok( uv_pipe_init(Loop.uvloop,puv_pipe_t(FHandle),0) );
FActiveRef := self;
end;
constructor TNPPipe.CreateIPC();
begin
inherited Create(UV_NAMED_PIPE);
np_ok( uv_pipe_init(Loop.uvloop,puv_pipe_t(FHandle),1) );
FActiveRef := self;
end;
function TNPPipe.getpeername: UTF8String;
var
len : size_t;
begin
len := 1024;
SetLength(result, len );
np_ok( uv_pipe_getsockname( puv_pipe_t(FHandle), @result[1], len) );
if len < 1 then
raise ENPException.Create( UV_ENOBUFS );
setLength(result,len);
end;
function TNPPipe.getsockname: UTF8String;
var
len : size_t;
begin
len := 1024;
SetLength(result, len );
len := uv_pipe_getpeername( puv_pipe_t(FHandle), @result[1], len);
if len < 1 then
raise ENPException.Create( UV_ENOBUFS );
setLength(result,len);
end;
function TNPPipe.get_pending_count: integer;
begin
result := uv_pipe_pending_count(puv_pipe_t(FHandle));
end;
function TNPPipe.get_pending_type: uv_handle_type;
begin
result := uv_pipe_pending_type(puv_pipe_t(FHandle));
end;
procedure TNPPipe.open(fd: uv_file);
begin
np_ok(uv_pipe_open(puv_pipe_t(FHandle), fd));
end;
procedure TNPPipe.setOnClient(OnClient: TOnPipeClient);
begin
FOnClient := OnClient;
end;
procedure TNPPipe.set_chmod(flags: integer);
begin
np_ok( uv_pipe_chmod( puv_pipe_t(FHandle), flags) );
end;
procedure TNPPipe.set_pending_instances(acount: integer);
begin
uv_pipe_pending_instances(puv_pipe_t(FHandle),aCount);
end;
procedure TNPPipe.write2(const data: UTF8String; send_handle: INPStream; Acallback: TProc);
begin
if length(data) > 0 then
writeInternal(@data[1],length(data), ACallBack, send_handle)
else
writeInternal(nil,0, ACallBack, send_handle)
end;
procedure TNPPipe.write2(const data: BufferRef; send_handle: INPStream; Acallback: TProc);
begin
writeInternal(data.ref,data.length, ACallBack);
end;
procedure TNPPipe._onConnection;
begin
if assigned(FOnClient) then
FOnClient(self)
end;
type
PHandler = ^THandler;
THandler = record
execute: TProc;
end;
procedure __cbThread(data: Pointer); cdecl;
var
handler : Phandler;
begin
handler := data;
try
handler.execute();
except
end;
dispose(handler);
end;
function thread_create(p : TProc) : uv_thread_t;
var
handler: PHandler;
begin
if not assigned(p) then
exit( 0 );
new(handler);
handler.execute := p;
result := 0;
if uv_thread_create(@result, @__cbThread, handler) <> 0 then
begin
dispose(handler);
raise Exception.Create('Can not create thread');
end;
end;
procedure thread_join(tid: uv_thread_t);
begin
if tid <> 0 then
uv_thread_join(@tid);
end;
{ TNPTTY }
procedure TNPSTDOUT.beginPrint;
begin
Inc(pcount);
end;
constructor TNPSTDOUT.Create(fd: uv_os_fd_t);
var
ht : uv_handle_type;
fd2 : uv_os_fd_t;
begin
FHandleType := uv_guess_handle(fd);
case FHandleType of
UV_TTY:
begin
//OutputDebugString('stdout => tty');
FStream := TNPTTY.Create(fd);
end;
UV_NAMED_PIPE:
begin
//OutputDebugString('try => pipe');
INPPipe( FStream ):= TNPPipe.Create;
INPPipe( FStream ).open(fd);
//raise Exception.Create('Can not create tty!');
end;
UV_FILE_:
begin
//OutputDebugString('stdout => file');
FUVFile := uv_get_osfhandle( fd );
assert(FUVFile <> INVALID_HANDLE_VALUE);
end
else
begin
//OutputDebugString(PChar(Format('stdout => type(%d)',[ord(ht)])));
raise Exception.Create('Init stdout failed!');
end;
end;
end;
destructor TNPSTDOUT.Destroy;
begin
inherited;
end;
procedure TNPSTDOUT.endPrint;
begin
dec(pcount);
if pcount = 0 then
flush;
end;
procedure TNPSTDOUT.flush;
var
buf: TBytes;
buf2: BufferRef;
begin
if pBuf = '' then
exit;
if is_pipe then
begin
FStream.write(pbuf);
//BUG WA
// buf2 := Buffer.Create(pBuf);
// FStream.write(buf2,
// procedure
// begin
// buf2 := Buffer.Null;
// end);
end
else
if is_tty then
FStream.write(pbuf)
else
if is_file then
begin
SetLength(buf,length(pbuf));
move(pbuf[1],buf[0], length(pbuf));
fs.write(FUVFile,buf,nil);
end;
pbuf := '';
end;
function TNPSTDOUT.get_file: uv_file;
begin
result := FUVFile;
end;
function TNPSTDOUT.get_pipe: INPPipe;
begin
result := FStream as INPPipe;
end;
function TNPSTDOUT.get_tty: INPTTY;
begin
result := FStream as INPTTY;
end;
function TNPSTDOUT.is_file: Boolean;
begin
result := FHandleType = UV_FILE_;
end;
function TNPSTDOUT.is_pipe: Boolean;
begin
result := FHandleType = UV_NAMED_PIPE;
end;
function TNPSTDOUT.is_tty: Boolean;
begin
result := FHandleType = UV_TTY;
end;
procedure TNPSTDOUT.MoveTo(x, y: integer);
begin
Print(Format(#27'[%d;%dH', [y, x]));
end;
procedure TNPSTDOUT.MoveTo1x1;
begin
Print(#27'[H');
end;
procedure TNPSTDOUT.MoveToY(y: integer);
begin
Print(Format(#27'[%dd', [y]));
end;
procedure TNPSTDOUT.MoveToX(x: integer);
begin
Print(Format(#27'[%dG', [x]));
end;
procedure TNPSTDOUT.Print(const s: UTF8String);
begin
if length(s) > 0 then
begin
beginPrint;
pbuf := pbuf + s ;
endPrint;
end;
end;
procedure TNPSTDOUT.PrintLn(const s: UTF8String);
begin
beginPrint;
print(s);
print(#13#10);
endPrint;
end;
function TNPSTDOUT.stdout_type: uv_handle_type;
begin
result := FHandleType;
end;
{ TNPTTY }
constructor TNPTTY.Create(fd: uv_os_fd_t);
begin
assert(uv_guess_handle(fd) = UV_TTY);
inherited Create(UV_TTY);
FTTY := puv_tty_t(FHandle);
np_ok( uv_tty_init( loop.uvloop,FTTY, fd, 0) );
FActiveRef := self;
end;
destructor TNPTTY.Destroy;
begin
inherited;
end;
{ TNPTTY_INPUT }
constructor TNPTTY_INPUT.Create(raw:Boolean);
begin
inherited Create(UV_TTY);
np_ok( uv_tty_init( loop.uvloop,puv_tty_t(FHandle), UV_STDIN_FD, 1) );
if raw then
uv_tty_set_mode(puv_tty_t(FHandle), UV_TTY_MODE_RAW);
FActiveRef := self;
end;
procedure TNPTTY.get_winsize(out width, height: integer);
begin
width := 0;
height := 0;
if Ftty <> nil then
begin
np_ok( uv_tty_get_winsize(Ftty,width,height) );
end;
if (width = 0) or (height = 0) then
begin
width := 80;
height := 25;
end;
end;
procedure __exit_cb(process: puv_process_t; exit_status: Int64;
term_signal: Integer); cdecl;
var
ud : TNPSpawn;
begin
ud := uv_get_user_data( process );
ud._onExit(exit_status, term_signal);
// uv_close(puv_handle_t(process), nil);
end;
{ TNPSpawn }
constructor TNPSpawn.Create();
begin
inherited Create(UV_PROCESS);
FProcess := puv_process_t(FHandle);
Fargs := TStringList.Create;
Fargs.Delimiter := ' ';
Fargs.QuoteChar := '"';
end;
destructor TNPSpawn.Destroy;
begin
freeAndNil(Fargs);
if Foptions.args <> nil then
FreeMem( Foptions.args );
Foptions.args := nil;
inherited;
end;
function TNPSpawn.getArgs: TStringList;
begin
result := FArgs;
end;
function TNPSpawn.getCWD: String;
begin
result := FCWD;
end;
function TNPSpawn.getFlags: uv_process_flags_set;
begin
result := Foptions.flags;
end;
function TNPSpawn.getPID: integer;
begin
result := uv_get_process_pid(FProcess);
end;
function TNPSpawn.GetStdio(inx: integer): puv_stdio_container_t;
begin
if (inx >= Low(FStdio) ) and (inx <= High(FStdio)) then
begin
result := @Fstdio[inx];
if inx >= Foptions.stdio_count then
Foptions.stdio_count := inx+1;
end
else
raise ERangeError.CreateFmt('Stdio num=%d!',[inx]);
end;
procedure TNPSpawn.kill(signnum: integer);
begin
if FSpawn then
begin
np_ok(uv_process_kill(@FProcess,signnum));
end;
end;
procedure TNPSpawn.setCWD(const cwd: String);
begin
if not FSpawn then
FCWD := cwd;
end;
procedure TNPSpawn.setFlags(flags: uv_process_flags_set);
begin
Foptions.flags := flags;
end;
procedure TNPSpawn.setOnExit(ACallBack: TProc<int64, integer>);
begin
FOnExit := ACallBack;
end;
procedure TNPSpawn.spawn;
var
i : integer;
argsCount : integer;
begin
if FSpawn then
exit;
FSpawn := true;
argsCount := Fargs.Count;
if argsCount = 0 then
raise EArgumentException.Create('empty spawn.args');
SetLength( Fcurrent_args, argsCount);
for i := 0 to argsCount-1 do
begin
Fcurrent_args[i] := Fargs[i];
assert(StringCodePage(Fcurrent_args[i]) = 65001);
end;
// fillchar( Foptions, sizeof(Foptions), 0);
GetMem(Foptions.args, (argsCount+1)* sizeof(PUTF8Char));
// Fillchar(Foptions.args^, (argsCount+1)* sizeof(PUTF8Char), 0);
for i := 0 to argsCount-1 do
Foptions.args[i] := PUTF8Char(Fcurrent_args[i]);
Foptions.args[argsCount] := nil;
Foptions.&file := PUTF8Char(Foptions.args[0]);
Foptions.exit_cb := @__exit_cb;
if length(FCWD) > 0 then
Foptions.cwd := PUTF8Char(FCWD);
if FOptions.stdio_count > 0 then
FOptions.stdio := @Fstdio;
np_ok( uv_spawn(Loop.uvloop,FProcess,@FOptions) );
FActiveRef := self;
end;
procedure TNPSpawn._onExit(exit_status: Int64; term_signal: Integer);
begin
if assigned(FOnExit) then
try
FOnExit(exit_status, term_signal);
except
end;
Clear;
end;
function stdOut : INPSTDOUT;
begin
if not assigned(tv_stdOut) then
begin
tv_stdOut := TNPSTDOUT.Create(UV_STDOUT_FD);
end;
result := tv_stdOut;
end;
function stdErr : INPSTDOUT;
var
fd : uv_os_fd_t;
begin
if not assigned(tv_stdErr) then
begin
tv_stdErr := TNPSTDOUT.Create(UV_STDERR_FD);
end;
result := tv_stdErr;
end;
function stdIn : INPStream;
begin
if not assigned(tv_stdin) then
tv_stdin := TNPTTY_INPUT.Create(false);
result := tv_stdIn;
end;
function stdInRaw : INPStream;
begin
if not assigned(tv_stdin) then
tv_stdin := TNPTTY_INPUT.Create(true);
result := tv_stdIn;
end;
{ TNPBarrier }
procedure TNPBarrier.Init(ACount: integer);
begin
uv_barrier_init(@uvbarrier,Acount);
end;
procedure TNPBarrier.wait;
begin
if uv_barrier_wait(@uvbarrier) > 0 then
begin
uv_barrier_destroy(@uvbarrier);
end;
end;
{ TNPError }
procedure TNPError.Init(ACode: integer);
begin
code := ACode;
codestr := CStrUtf8( uv_err_name(Acode) );
msg := CStrUtf8( uv_strerror(Acode) );
end;
function TNPError.ToString: String;
begin
result := Format('%s (%d) : "%s"',[codestr, code, msg] );
end;
procedure __event_cb(handle : puv_fs_event_t; const filename: PUTF8Char; events:integer;status : integer); cdecl;
var
ev : TFS_Event;
ud : TNPWatch;
begin
if status = 0 then
begin
ev := [];
if (events and UV_RENAME) <> 0 then
include(ev,feRename);
if (events and UV_CHANGE) <> 0 then
include(ev,feChange);
ud := uv_get_user_data(puv_handle_t( handle) );
if assigned(ud) and assigned(ud.FCallBack) then
begin
ud.FCallBack( ev, CStrUtf8(filename) );
end;
end;
end;
{ TNPWatch }
procedure TNPWatch.before_closing;
begin
if is_active then
uv_fs_event_stop( puv_fs_event_t( FHandle ) );
end;
constructor TNPWatch.Create(const ACallBack: TWatchCallBack; const APath: string;
flags: integer);
begin
inherited Create(UV_FS_EVENT_);
{$IFDEF MSWINDOWS}
FPath := StringReplace(APath,'/','\',[rfReplaceAll]);
{$ENDIF}
while (Length(FPath)>0) and (FPath[Length(FPath)] = PathDelim) do
SetLength(FPath,Length(FPath)-1);
np_ok( uv_fs_event_init(loop.uvloop,puv_fs_event_t( FHandle) ) );
np_ok( uv_fs_event_start(puv_fs_event_t( FHandle), @__event_cb, PUTF8Char( UTF8String(FPath) ), flags ) );
FCallBack := ACallBack;
FActiveRef := self;
end;
destructor TNPWatch.Destroy;
begin
// OutputDebugString('TNPWatch.Destroy');
inherited;
end;
function TNPWatch.getpath: String;
//var
// sz : size_t;
begin
// sz := 1024;
// setLength(result,sz);
// if uv_fs_event_getpath( puv_fs_event_t( FHandle ), @result[1], sz ) < 0 then
// SetLength(result,0)
// else
// SetLength(result, sz);
result := FPath;
end;
procedure TNPWatch.onClose;
begin
FCallBack := nil;
inherited;
if is_active then
uv_fs_event_stop( puv_fs_event_t( FHandle ) );
end;
function setFSWatch(p: TWatchCallBack; const Path: String; flag:Integer) : INPWatch;
begin
result := TNPWatch.Create(p,path,flag);
end;
{ TNPUDP }
procedure TNPUDP.before_closing;
begin
setOnData(nil);
end;
procedure TNPUDP.bind(const Aaddr: uv_sockAddr; flags: TUDPBindFlags);
var
lflags : Cardinal;
begin
lflags := 0;
if ubf_REUSEADDR in flags then
lflags := lflags or UV_UDP_REUSEADDR;
if ubf_IPV6ONLY in flags then
lflags := lflags or UV_UDP_IPV6ONLY;
np_ok( uv_udp_bind(uvudp,AAddr.sa, lflags ) );
end;
procedure TNPUDP.connect(const sa: uv_sockAddr);
begin
np_ok( uv_udp_connect(uvudp, sa.sa ) );
end;
constructor TNPUDP.Create;
begin
inherited Create(UV_UDP);
np_ok( uv_udp_init(loop.uvloop, puv_udp_t( FHandle ) ));
FActiveRef := self;
end;
destructor TNPUDP.Destroy;
begin
// OutputDebugString( 'TNPUDP.Destroy' );
inherited;
end;
function TNPUDP.getpeername: uv_sockAddr;
var
len : integer;
begin
len := sizeof(result);
np_ok( uv_udp_getpeername( uvudp, @result.sa, len ));
end;
function TNPUDP.getsockname: uv_sockAddr;
var
len : integer;
begin
len := sizeof(result);
np_ok( uv_udp_getsockname( uvudp, @result.sa, len ) );
end;
function TNPUDP.get_send_queue_count: size_t;
begin
result := uv_udp_get_send_queue_count(uvudp);
end;
function TNPUDP.get_send_queue_size: size_t;
begin
result := uv_udp_get_send_queue_size(uvudp);
end;
procedure TNPUDP.OnClose;
begin
inherited;
setOnData(nil);
end;
procedure TNPUDP.open(sock: uv_os_sock_t);
begin
np_ok( uv_udp_open( uvudp, sock ) );
end;
procedure __alloc_udp_cb(handle:puv_handle_t;suggested_size:size_t; var buf:uv_buf_t );cdecl;
var
udpImpl : TNPUDP;
begin
udpImpl := uv_get_user_data(handle);
assert(assigned(udpImpl));
if suggested_size > length(udpImpl.__buf) then
begin
Setlength(udpImpl.__buf, suggested_size);
end;
buf.len := suggested_size;
buf.base := @udpImpl.__buf[0];
end;
procedure __rcv_udp_cb(handle: puv_udp_t; nread:ssize_t; buf: uv_buf_t; sockaddr: PSockAddr_in_any; flags: Cardinal);cdecl;
var
udpImpl : TNPUDP;
res : TUDPData;
err: TNPError;
begin
udpImpl := uv_get_user_data(handle);
assert(assigned(udpImpl));
res := default(TUDPData);
if assigned(sockaddr) and (nread >=0) then
begin
res.from.Assign(sockaddr);
res.data := BufferRef.CreateWeakRef(buf.base, nread);
if (flags and UV_UDP_PARTIAL) <> 0 then
include( res.flags, urf_PARTIAL );
if assigned(udpImpl.FOnData) then
udpImpl.FOnData(nil,@res);
end
else
if nread < 0 then
begin
err.Init(nread);
if assigned(udpImpl.FOnData) then
udpImpl.FOnData(@err,nil);
end;
end;
procedure TNPUDP.setOnData(const onData: TUDPOnData);
var
res: Integer;
begin
if assigned(FOnData) then
begin
FOnData := onData;
if not assigned( FOnData ) then
begin
uv_udp_recv_stop(uvudp);
end;
end
else
begin
if assigned(onData) then
begin
res := uv_udp_recv_start(uvudp, @__alloc_udp_cb,@__rcv_udp_cb);
if res <> 0 then
begin
if CStrUtf8( uv_err_name(res) ) <> 'EALREADY' then
np_ok(res);
end;
FOnData := onData;
end;
end;
end;
type
PUdpSendData = ^TUdpSendData;
TUdpSendData = record
send_req : TBytes;
callback : TUDPSendCallBack;
this_ref : INPUDP;
end;
procedure __send_udp_cb(req : puv_udp_send_t; status : integer);cdecl;
var
cast : PUdpSendData;
error : TNPError;
begin
cast := PUdpSendData(uv_req_get_data(puv_req_t(req)));
assert( assigned(cast) );
assert( assigned(cast.callback) );
assert( assigned(cast.this_ref ));
try
if status = 0 then
cast.callback(nil)
else
begin
error.Init(status);
cast.callback(@error);
end;
finally
Dispose(cast);
end;
end;
procedure TNPUDP.send(const buf: BufferRef; const callback: TUDPSendCallBack);
begin
send(buf,nil,callback);
end;
procedure TNPUDP.send(const buf: BufferRef; const addr: uv_sockAddr; const callback: TUDPSendCallBack);
begin
send(buf,puv_sockAddr(@addr),callback);
end;
procedure TNPUDP.send(const buf: BufferRef; addr: puv_sockAddr; const callback: TUDPSendCallBack);
var
lbuf : uv_buf_t;
send_req_data: PUdpSendData; //self captured record
send_req : puv_udp_send_t;
res : Integer;
begin
lbuf.len := buf.length;
lbuf.base := buf.ref;
// GetMem(send_req, uv_req_size(UV_UDP_SEND_) );
if assigned(callback) then
begin
new( send_req_data );
SetLength( send_req_data.send_req , uv_req_size(UV_UDP_SEND_) );
send_req := puv_udp_send_t( @send_req_data.send_req[0] );
send_req_data.callback := callback;
send_req_data.this_ref := self;
uv_req_set_data(puv_req_t(send_req), send_req_data);
res := uv_udp_send(send_req,uvudp ,@lbuf,1,psockaddr( addr ),@__send_udp_cb ) ;
if res <> 0 then
NextTick(
procedure
begin
__send_udp_cb(send_req,res);
end);
end
else
uv_udp_try_send(uvudp,@lbuf,1,psockaddr( addr ) );
end;
procedure TNPUDP.try_send(const buf: BufferRef; const addr: uv_sockAddr);
begin
send(buf,addr,nil);
end;
procedure TNPUDP.try_send(const buf: BufferRef);
begin
send(buf,nil,nil);
end;
procedure TNPUDP.set_broadcast(enable: Boolean);
begin
np_ok( uv_udp_set_broadcast(uvudp, ord(enable) ) );
end;
procedure TNPUDP.set_membership(const multicast_addr,
interface_addr: UTF8String; membership: uv_membership);
begin
np_ok( uv_udp_set_membership(uvudp,PUTF8Char( multicast_addr ),PUTF8Char(interface_addr), membership) );
end;
procedure TNPUDP.set_multicast_interface(const interface_addr: UTF8String);
begin
np_ok( uv_udp_set_multicast_interface(uvudp, PUTF8Char(interface_addr)) );
end;
procedure TNPUDP.set_multicast_loop(enable: Boolean);
begin
np_ok( uv_udp_set_multicast_loop(uvudp, ord(enable)) );
end;
procedure TNPUDP.set_multicast_ttl(ttl: integer);
begin
np_ok( uv_udp_set_multicast_ttl(uvudp, ttl) );
end;
procedure TNPUDP.set_ttl(ttl: integer);
begin
np_ok( uv_udp_set_ttl(uvudp, ttl) );
end;
function TNPUDP.uvudp: puv_udp_t;
begin
result := puv_udp_t( FHandle );
end;
function newArray(values: array of const) : TAnyArray;
begin
result := TAnyArray.Create(values);
loop.ref(result);
end;
function np_const : Pnodepas_constants;
begin
result := uv_get_constants;
end;
end.
|
unit dmController;
interface
uses
SysUtils, Classes, uEventAgg, uModel, uEvents;
type
TdtmController = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FItemIndex: Integer;
FReportCards: TReportCardList;
function GetCurrent: TReportCard;
procedure SetItemIndex(const Value: Integer);
public
procedure Next;
procedure Prev;
property Current: TReportCard read GetCurrent;
property ReportCards: TReportCardList read FReportCards;
property ItemIndex: Integer read FItemIndex write SetItemIndex;
end;
var
dtmController: TdtmController;
implementation
{$R *.dfm}
procedure TdtmController.DataModuleCreate(Sender: TObject);
begin
FReportCards := TReportCardList.Create;
FReportCards.Add(TReportCard.Create('Tom', 20, 50, 40));
FReportCards.Add(TReportCard.Create('Peter', 15, 35, 25));
FReportCards.Add(TReportCard.Create('Mary', 30, 60, 90));
FReportCards.Add(TReportCard.Create('Jane', 10, 20, 40));
FItemIndex := 0;
end;
procedure TdtmController.DataModuleDestroy(Sender: TObject);
begin
FReportCards.Free;
end;
function TdtmController.GetCurrent: TReportCard;
begin
Result := FReportCards[FItemIndex];
end;
procedure TdtmController.Next;
begin
if FItemIndex < FReportCards.Count - 1 then
ItemIndex := FItemIndex + 1
else
ItemIndex := 0;
end;
procedure TdtmController.Prev;
begin
if FItemIndex = 0 then
ItemIndex := FReportCards.Count - 1
else
ItemIndex := FItemIndex - 1;
EA.Publish(Self.Current, TReportCardPrev);
end;
procedure TdtmController.SetItemIndex(const Value: Integer);
begin
if FItemIndex <> Value then
begin
FItemIndex := Value;
EA.Publish(Self.Current, TReportCardNav);
end;
end;
end.
|
unit uNotas;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBase, Data.DB, Vcl.Grids, Vcl.DBGrids,
Vcl.Buttons, Vcl.ExtCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls;
type
TfrmLancamentoNotas = class(TfrmCadastroBase)
Label4: TLabel;
cbProfessores: TComboBox;
Label1: TLabel;
cbDisciplina: TComboBox;
Label2: TLabel;
edtAluno: TEdit;
Label3: TLabel;
edtN1: TEdit;
Label5: TLabel;
edtN2: TEdit;
Label6: TLabel;
edtNotaTrabalho: TEdit;
qrDiscip_Prof: TFDQuery;
qrDisciplina: TFDQuery;
qrDados: TFDQuery;
dsDados: TDataSource;
qrDadosID: TIntegerField;
qrDadosNOME: TStringField;
qrDadosNOTA_PERIODO_1: TCurrencyField;
qrDadosNOTA_PERIODO_2: TCurrencyField;
qrDadosNOTA_TRABALHO: TCurrencyField;
procedure cbDisciplinaClick(Sender: TObject);
procedure cbProfessoresClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dbCellClick(Column: TColumn);
procedure sbSalvarClick(Sender: TObject);
procedure sbEditarClick(Sender: TObject);
procedure sbExcluirClick(Sender: TObject);
procedure sbNovoClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edtN1KeyPress(Sender: TObject; var Key: Char);
procedure edtN2KeyPress(Sender: TObject; var Key: Char);
procedure edtNotaTrabalhoKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
procedure CarregarProfessores;
procedure CarregarDisciplinas;
procedure ExibirRegistros;
end;
var
frmLancamentoNotas: TfrmLancamentoNotas;
id_matricula : integer;
codigo_aluno : integer;
codigo_disciplina : integer;
codigo_professor : integer;
implementation
{$R *.dfm}
uses uModulo, uSystemUtils;
procedure TfrmLancamentoNotas.CarregarDisciplinas;
begin
ExibirRegistros;
cbDisciplina.Items.Clear;
qrDisciplina.Close;
qrDisciplina.SQL.Clear;
qrDisciplina.SQL.Add('SELECT * FROM disciplinas');
qrDisciplina.Open();
while not qrDisciplina.Eof do
begin
cbDisciplina.Items.AddObject(qrDisciplina.FieldByName('descricao').AsString, TObject(qrDisciplina.FieldByName('id').AsInteger));
qrDisciplina.Next;
end;
qrDisciplina.Open();
end;
procedure TfrmLancamentoNotas.CarregarProfessores;
begin
qrDiscip_Prof.Close;
qrDiscip_Prof.SQL.Clear;
qrDiscip_Prof.SQL.Add('SELECT * FROM professor');
qrDiscip_Prof.SQL.Add(' WHERE id = :id');
qrDiscip_Prof.ParamByName('id').AsInteger := Integer(cbProfessores.Items.Objects[cbProfessores.ItemIndex]);
qrDiscip_Prof.Open();
codigo_professor := qrDiscip_Prof.FieldByName('id').AsInteger;
end;
procedure TfrmLancamentoNotas.cbDisciplinaClick(Sender: TObject);
begin
inherited;
qrDisciplina.Close;
qrDisciplina.SQL.Clear;
qrDisciplina.SQL.Add('SELECT * FROM disciplinas');
qrDisciplina.SQL.Add(' WHERE id = :id');
qrDisciplina.ParamByName('id').AsInteger := Integer(cbDisciplina.Items.Objects[cbDisciplina.ItemIndex]);
qrDisciplina.Open();
codigo_disciplina := qrDisciplina.FieldByName('id').AsInteger;
cbProfessores.Items.Clear;
qrDiscip_Prof.Close;
qrDiscip_Prof.SQL.Clear;
qrDiscip_Prof.SQL.Add('SELECT p.id, p.nome ');
qrDiscip_Prof.SQL.Add(' FROM professor p ');
qrDiscip_Prof.SQL.Add(' INNER JOIN disciplina_professor dp ');
qrDiscip_Prof.SQL.Add(' ON p.id = dp.codigo_professor ');
qrDiscip_Prof.SQL.Add(' WHERE dp.codigo_disciplina = :codigo_disciplina');
qrDiscip_Prof.ParamByName('codigo_disciplina').AsInteger := codigo_disciplina;
qrDiscip_Prof.Open();
qrDiscip_Prof.First;
while not qrDiscip_Prof.Eof do
begin
cbProfessores.Items.AddObject(qrDiscip_Prof.FieldByName('nome').AsString, TObject(qrDiscip_Prof.FieldByName('id').AsInteger));
cbProfessores.ItemIndex := 0;
qrDiscip_Prof.Next;
end;
qrDiscip_Prof.Open();
if qrDiscip_Prof.FieldByName('nome').AsString <> '' then
begin
CarregarProfessores;
ExibirRegistros;
end
else
begin
ShowMessage('Disciplina não possui professor cadastrado.');
exit
end;
end;
procedure TfrmLancamentoNotas.cbProfessoresClick(Sender: TObject);
begin
inherited;
CarregarProfessores;
ExibirRegistros
end;
procedure TfrmLancamentoNotas.dbCellClick(Column: TColumn);
begin
inherited;
if qrDados.FieldByName('id').AsString <> null then
begin
id_matricula := qrDados.FieldByName('id').AsInteger;
edtAluno.Text := qrDados.FieldByName('nome').AsString;
edtN1.Text := qrDados.FieldByName('nota_periodo_1').AsString;
edtN2.Text := qrDados.FieldByName('nota_periodo_2').AsString;
edtNotaTrabalho.Text := qrDados.FieldByName('nota_trabalho').AsString;
end;
end;
procedure TfrmLancamentoNotas.edtN1KeyPress(Sender: TObject; var Key: Char);
begin
inherited;
if not IsNumber(Key) then
Key := #0;
end;
procedure TfrmLancamentoNotas.edtN2KeyPress(Sender: TObject; var Key: Char);
begin
inherited;
if not IsNumber(Key) then
Key := #0;
end;
procedure TfrmLancamentoNotas.edtNotaTrabalhoKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if not IsNumber(Key) then
Key := #0;
end;
procedure TfrmLancamentoNotas.ExibirRegistros;
begin
qrDados.Close;
qrDados.SQL.Clear;
qrDados.SQL.Add('SELECT da.id ');
qrDados.SQL.Add(' ,a.nome ');
qrDados.SQL.Add(' ,da.nota_periodo_1 ');
qrDados.SQL.Add(' ,da.nota_periodo_2 ');
qrDados.SQL.Add(' ,da.nota_trabalho ');
qrDados.SQL.Add(' FROM disciplina_aluno da ');
qrDados.SQL.Add(' INNER JOIN disciplinas d ');
qrDados.SQL.Add(' ON d.id = da.codigo_disciplina ');
qrDados.SQL.Add(' INNER JOIN professor p ');
qrDados.SQL.Add(' ON p.id = da.codigo_professor ');
qrDados.SQL.Add(' INNER JOIN aluno a ');
qrDados.SQL.Add(' ON a.id = da.codigo_aluno ');
qrDados.SQL.Add(' WHERE da.codigo_disciplina = :codigo_disciplina');
qrDados.SQL.Add(' AND da.codigo_professor = :codigo_professor ');
qrDados.SQL.Add(' ORDER BY id ASC ');
qrDados.ParamByName('codigo_professor').AsInteger := codigo_professor;
qrDados.ParamByName('codigo_disciplina').AsInteger := codigo_disciplina;
qrDados.Open();
end;
procedure TfrmLancamentoNotas.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
frmLancamentoNotas := nil;
end;
procedure TfrmLancamentoNotas.FormShow(Sender: TObject);
begin
inherited;
CarregarDisciplinas;
end;
procedure TfrmLancamentoNotas.sbEditarClick(Sender: TObject);
begin
inherited;
if cbDisciplina.ItemIndex = -1 then
begin
ShowMessage('Selecione um registro para atualização.');
db.SetFocus;
Exit;
end;
if id_matricula = 0 then
begin
ShowMessage('Selecione um registro para atualização.');
db.SetFocus;
Exit;
end;
qrDados.Close;
qrDados.SQL.Clear;
qrDados.SQL.Add('UPDATE disciplina_aluno');
qrDados.SQL.Add(' SET nota_periodo_1 = :nota_periodo_1');
qrDados.SQL.Add(' ,nota_periodo_2 = :nota_periodo_2 ');
qrDados.SQL.Add(' ,nota_trabalho = :nota_trabalho ');
qrDados.SQL.Add(' WHERE id = :id');
qrDados.ParamByName('id').AsInteger := id_matricula;
if edtN1.Text <> '' then
qrDados.ParamByName('nota_periodo_1').AsFloat := StrToFloat(edtN1.Text)
else
qrDados.ParamByName('nota_periodo_1').Value := null;
if edtN2.Text <> '' then
qrDados.ParamByName('nota_periodo_2').AsFloat := StrToFloat(edtN2.Text)
else
qrDados.ParamByName('nota_periodo_2').Value := null;
if edtNotaTrabalho.Text <> '' then
qrDados.ParamByName('nota_trabalho').AsFloat := StrToFloat(edtNotaTrabalho.Text)
else
qrDados.ParamByName('nota_trabalho').Value := null;
qrDados.ExecSQL;
ShowMessage('Nota atualizado com sucesso.');
ExibirRegistros;
end;
procedure TfrmLancamentoNotas.sbExcluirClick(Sender: TObject);
begin
inherited;
ShowMessage('Funcionalidade não habilitada para esta tela.');
end;
procedure TfrmLancamentoNotas.sbNovoClick(Sender: TObject);
begin
inherited;
cbDisciplina.ItemIndex := -1;
cbProfessores.ItemIndex := -1;
edtAluno.Text := '';
edtN1.Text := '';
edtN2.Text := '';
edtNotaTrabalho.Text := '';
qrDados.Close;
end;
procedure TfrmLancamentoNotas.sbSalvarClick(Sender: TObject);
begin
inherited;
if cbDisciplina.ItemIndex = -1 then
begin
ShowMessage('Selecione um registro para atualização.');
db.SetFocus;
Exit;
end;
if id_matricula = 0 then
begin
ShowMessage('Selecione um registro para atualização.');
db.SetFocus;
Exit;
end;
qrDados.Close;
qrDados.SQL.Clear;
qrDados.SQL.Add('UPDATE disciplina_aluno');
qrDados.SQL.Add(' SET nota_periodo_1 = :nota_periodo_1');
qrDados.SQL.Add(' ,nota_periodo_2 = :nota_periodo_2 ');
qrDados.SQL.Add(' ,nota_trabalho = :nota_trabalho ');
qrDados.SQL.Add(' WHERE id = :id');
qrDados.ParamByName('id').AsInteger := id_matricula;
if edtN1.Text <> '' then
qrDados.ParamByName('nota_periodo_1').AsFloat := StrToFloat(edtN1.Text)
else
qrDados.ParamByName('nota_periodo_1').Value := null;
if edtN2.Text <> '' then
qrDados.ParamByName('nota_periodo_2').AsFloat := StrToFloat(edtN2.Text)
else
qrDados.ParamByName('nota_periodo_2').Value := null;
if edtNotaTrabalho.Text <> '' then
qrDados.ParamByName('nota_trabalho').AsFloat := StrToFloat(edtNotaTrabalho.Text)
else
qrDados.ParamByName('nota_trabalho').Value := null;
qrDados.ExecSQL;
ShowMessage('Nota lançada com sucesso.');
ExibirRegistros;
end;
end.
|
unit ServerHorse.Routers.Cities;
interface
uses
System.JSON,
Horse,
Horse.Jhonson,
Horse.CORS,
ServerHorse.Controller;
procedure Registry;
implementation
uses
System.Classes,
ServerHorse.Controller.Interfaces,
ServerHorse.Model.Entity.CITIES,
System.SysUtils,
ServerHorse.Utils,
Horse.Paginate;
procedure Registry;
begin
THorse
.Use(Paginate)
.Use(Jhonson)
.Use(CORS)
.Get('/cities',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
iController : iControllerEntity<TCITIES>;
begin
iController := TController.New.CITIES;
iController.This
.DAO
.SQL
.Fields('CITIES.*, ')
.Fields('STATES.STATE AS STATE, ')
.Fields('COUNTRIES.COUNTRY AS COUNTRY ')
.Join('LEFT JOIN STATES ON STATES.GUUID = CITIES.IDSTATE ')
.Join('LEFT JOIN COUNTRIES ON COUNTRIES.GUUID = STATES.IDCOUNTRY ')
.Where(TServerUtils.New.LikeFind(Req))
.OrderBy(TServerUtils.New.OrderByFind(Req))
.&End
.Find(False);
Res.Send<TJsonArray>(iController.This.DataSetAsJsonArray);
end)
.Get('/cities/:ID',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
iController : iControllerEntity<TCITIES>;
begin
iController := TController.New.CITIES;
iController.This
.DAO
.SQL
.Fields('CITIES.*, ')
.Fields('STATES.STATE AS STATE, ')
.Fields('COUNTRIES.COUNTRY AS COUNTRY ')
.Join('LEFT JOIN STATES ON STATES.GUUID = CITIES.IDSTATE ')
.Join('LEFT JOIN COUNTRIES ON COUNTRIES.GUUID = STATES.IDCOUNTRY ')
.Where('CITIES.GUUID = ' + QuotedStr('{' + Req.Params['ID'] + '}' ))
.&End
.Find(False);
Res.Send<TJsonArray>(iController.This.DataSetAsJsonArray);
end)
.Post('/cities',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
vBody : TJsonObject;
aGuuid: string;
begin
vBody := TJSONObject.ParseJSONValue(Req.Body) as TJSONObject;
try
if not vBody.TryGetValue<String>('guuid', aGuuid) then
vBody.AddPair('guuid', TServerUtils.New.AdjustGuuid(TGUID.NewGuid.ToString()));
TController.New.CITIES.This.Insert(vBody);
Res.Status(200).Send<TJsonObject>(vBody);
except
Res.Status(500).Send('');
end;
end)
.Put('/cities/:ID',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
var
vBody : TJsonObject;
aGuuid: string;
begin
vBody := TJSONObject.ParseJSONValue(Req.Body) as TJSONObject;
try
if not vBody.TryGetValue<String>('guuid', aGuuid) then
vBody.AddPair('guuid', Req.Params['ID']);
TController.New.CITIES.This.Update(vBody);
Res.Status(200).Send<TJsonObject>(vBody);
except
Res.Status(500).Send('');
end;
end)
.Delete('/cities/:id',
procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc)
begin
try
TController.New.CITIES.This.Delete('guuid', QuotedStr(Req.Params['id']));
Res.Status(200).Send('');
except
Res.Status(500).Send('');
end;
end);
end;
end.
|
unit DAO.PlanilhaEntradaDIRECT;
interface
uses Generics.Collections, System.Classes, System.SysUtils, Forms, Windows, Model.PlanilhaEntradaDIRECT;
type
TPlanilhaEntradaDIRECTDAO = class
public
function GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaDIRECT>;
end;
implementation
{ TPlanilhaEntradaDIRECTDAO }
uses Common.Utils;
function TPlanilhaEntradaDIRECTDAO.GetPlanilha(sFile: String): TObjectList<TPlanilhaEntradaDIRECT>;
var
ArquivoCSV: TextFile;
sLinha: String;
sDetalhe: TStringList;
entradas : TObjectList<TPlanilhaEntradaDIRECT>;
i : Integer;
sValor : String;
lstRemessa: TStringList;
iIndex: Integer;
begin
try
entradas := TObjectList<TPlanilhaEntradaDIRECT>.Create;
if not FileExists(sFile) then
begin
Application.MessageBox(PChar('Arquivo ' + sFile + ' não foi encontrado!'), 'Atenção', MB_ICONWARNING + MB_OK);
Exit;
end;
AssignFile(ArquivoCSV, sFile);
if sFile.IsEmpty then Exit;
sDetalhe := TStringList.Create;
sDetalhe.StrictDelimiter := True;
sDetalhe.Delimiter := ';';
Reset(ArquivoCSV);
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha + ';';
lstRemessa := TStringList.Create;
if Pos('REMESSA',sLinha) = 0 then
begin
Application.MessageBox('Arquivo informado não foi identificado como a Planilha de Entrada da DIRECT!', 'Atenção', MB_ICONWARNING + MB_OK);
Exit;
end;
i := 0;
while not Eoln(ArquivoCSV) do
begin
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha + ';';
if TUtils.ENumero(sDetalhe[0]) then
begin
if not lstRemessa.Find(sDetalhe[0], iIndex) then
begin
lstRemessa.Add(sDetalhe[0]);
lstRemessa.Sort;
sValor := '0';
entradas.Add(TPlanilhaEntradaDIRECT.Create);
i := entradas.Count - 1;
entradas[i].Remessa := sDetalhe[0];
entradas[i].Pedido := sDetalhe[1];
entradas[i].DataRegistro := StrToDateDef(sDetalhe[2], 0);
entradas[i].HoraRegistro := StrToTimeDef(sDetalhe[3], 0);
entradas[i].CodigoEmbarcador := StrToIntDef(sDetalhe[4], 0);
entradas[i].NomeEmbarcador := sDetalhe[5];
entradas[i].NomeConsumidor := sDetalhe[6];
entradas[i].Municipio := sDetalhe[7];
entradas[i].UF := sDetalhe[8];
entradas[i].CEP := sDetalhe[9];
entradas[i].Bairro := sDetalhe[10];
entradas[i].Situacao := sDetalhe[11];
entradas[i].DataAlteracao := StrToDateDef(sDetalhe[12], 0);
entradas[i].HoraAlteracao := StrToTimeDef(sDetalhe[13], 0);
entradas[i].Volumes := StrToIntDef(sDetalhe[14], 0);
entradas[i].Tipo := sDetalhe[15];
entradas[i].PakingList := sDetalhe[16];
entradas[i].NF := sDetalhe[17];
entradas[i].Serie := sDetalhe[18];
entradas[i].Emissao := StrToDateDef(sDetalhe[19], 0);
sValor := StringReplace(sDetalhe[20], '.', ',', [rfReplaceAll, rfIgnoreCase]);
entradas[i].Valor := StrToFloatDef(sValor, 0);
entradas[i].Chave := sDetalhe[21];
entradas[i].Operacao := sDetalhe[22];
entradas[i].TomadorNome := sDetalhe[23];
entradas[i].CNPJTomador := sDetalhe[24];
entradas[i].Base := sDetalhe[25];
entradas[i].BaseSigla := sDetalhe[26];
sValor := StringReplace(sDetalhe[27], '.', ',', [rfReplaceAll, rfIgnoreCase]);
entradas[i].PesoCubado := StrToFloatDef(sValor, 0);
sValor := StringReplace(sDetalhe[28], '.', ',', [rfReplaceAll, rfIgnoreCase]);
entradas[i].PesoNominal := StrToFloatDef(sValor, 0);
entradas[i].UltimaOcorrencia := sDetalhe[29];
entradas[i].QtdeOcorrencia := StrToIntDef(sDetalhe[30], 0);
entradas[i].DataAgendamento := sDetalhe[31];
entradas[i].Devolucao := sDetalhe[32];
entradas[i].UltimaViagem := sDetalhe[33];
entradas[i].UltimoMotorista := sDetalhe[34];
entradas[i].Produto := sDetalhe[35];
entradas[i].AWB1 := sDetalhe[36];
entradas[i].AWB2 := sDetalhe[37];
entradas[i].DataChegada := StrToDateDef(sDetalhe[38], 0);
entradas[i].HoraChegada := StrToTimeDef(sDetalhe[39], 0);
entradas[i].DataChegadaLM := StrToDateDef(sDetalhe[40], 0);
entradas[i].HoraChegadaLM := StrToTimeDef(sDetalhe[41], 0);
end;
end;
end;
Result := entradas;
finally
CloseFile(ArquivoCSV);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.