text stringlengths 14 6.51M |
|---|
unit MFichas.Model.Usuario.Funcoes.Buscar;
interface
uses
System.SysUtils,
MFichas.Model.Usuario.Interfaces,
MFichas.Controller.Types,
FireDAC.Comp.Client,
FireDAC.Comp.DataSet;
type
TModelUsuarioFuncoesBuscar = class(TInterfacedObject, iModelUsuarioFuncoesBuscar)
private
[weak]
FParent : iModelUsuario;
FFDMemTable: TFDMemTable;
constructor Create(AParent: iModelUsuario);
procedure CopiarDataSet;
procedure Validacao;
public
destructor Destroy; override;
class function New(AParent: iModelUsuario): iModelUsuarioFuncoesBuscar;
function FDMemTable(AFDMemTable: TFDMemTable): iModelUsuarioFuncoesBuscar;
function BuscarTodos : iModelUsuarioFuncoesBuscar;
function BuscarTodosAtivos : iModelUsuarioFuncoesBuscar;
function BuscarCaixas : iModelUsuarioFuncoesBuscar;
function BuscarFiscais : iModelUsuarioFuncoesBuscar;
function BuscarProprietarios : iModelUsuarioFuncoesBuscar;
function BuscarPorCodigo(AGUUID: String) : iModelUsuarioFuncoesBuscar;
function &End : iModelUsuarioFuncoes;
end;
implementation
{ TModelUsuarioFuncoesBuscar }
function TModelUsuarioFuncoesBuscar.BuscarCaixas: iModelUsuarioFuncoesBuscar;
begin
Result := Self;
FParent.DAODataSet.OpenWhere(
' STATUS = ' + Integer(saiAtivo).ToString + ' AND ' +
' TIPO = ' + Integer(tuCaixa).ToString
);
Validacao;
CopiarDataSet;
end;
function TModelUsuarioFuncoesBuscar.BuscarFiscais: iModelUsuarioFuncoesBuscar;
begin
Result := Self;
FParent.DAODataSet.OpenWhere(
' STATUS = ' + Integer(saiAtivo).ToString + ' AND ' +
' TIPO >= ' + Integer(tuFiscal).ToString
);
Validacao;
CopiarDataSet;
end;
function TModelUsuarioFuncoesBuscar.BuscarPorCodigo(AGUUID: String): iModelUsuarioFuncoesBuscar;
begin
Result := Self;
FParent.DAODataSet.OpenWhere(
' GUUID = ' + QuotedStr(AGUUID) + ' AND ' +
' STATUS = ' + Integer(saiAtivo).ToString + ' AND ' +
' TIPO < ' + Integer(tuGerente).ToString
);
Validacao;
CopiarDataSet;
end;
function TModelUsuarioFuncoesBuscar.BuscarProprietarios: iModelUsuarioFuncoesBuscar;
begin
Result := Self;
FParent.DAODataSet.OpenWhere(
' STATUS = ' + Integer(saiAtivo).ToString + ' AND ' +
' TIPO = ' + Integer(tuGerente).ToString
);
Validacao;
CopiarDataSet;
end;
function TModelUsuarioFuncoesBuscar.BuscarTodos: iModelUsuarioFuncoesBuscar;
begin
Result := Self;
FParent.DAODataSet.OpenWhere(
' TIPO < 2'
);
Validacao;
CopiarDataSet;
end;
function TModelUsuarioFuncoesBuscar.BuscarTodosAtivos: iModelUsuarioFuncoesBuscar;
begin
Result := Self;
FParent.DAODataSet.OpenWhere(
' STATUS = ' + Integer(saiAtivo).ToString + ' AND ' +
' TIPO < 2'
);
Validacao;
CopiarDataSet;
end;
function TModelUsuarioFuncoesBuscar.&End: iModelUsuarioFuncoes;
begin
Result := FParent.Funcoes;
end;
function TModelUsuarioFuncoesBuscar.FDMemTable(
AFDMemTable: TFDMemTable): iModelUsuarioFuncoesBuscar;
begin
Result := Self;
FFDMemTable := AFDMemTable;
end;
procedure TModelUsuarioFuncoesBuscar.CopiarDataSet;
begin
FFDMemTable.CopyDataSet(FParent.DAODataSet.DataSet, [coStructure, coRestart, coAppend]);
FFDMemTable.IndexFieldNames := 'NOME';
end;
constructor TModelUsuarioFuncoesBuscar.Create(AParent: iModelUsuario);
begin
FParent := AParent;
end;
destructor TModelUsuarioFuncoesBuscar.Destroy;
begin
inherited;
end;
class function TModelUsuarioFuncoesBuscar.New(AParent: iModelUsuario): iModelUsuarioFuncoesBuscar;
begin
Result := Self.Create(AParent);
end;
procedure TModelUsuarioFuncoesBuscar.Validacao;
begin
if not Assigned(FFDMemTable) then
raise Exception.Create(
'Para prosseguir, você deve vincular um FDMemTable ao encadeamento' +
' de funcões do método de Usuarios.Funcoes.Buscar .'
);
end;
end.
|
unit copiarCtas;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons;
const
ctRubros = 'SELECT * FROM CO_RUBROS';
ctGrupos = 'SELECT * FROM CO_GRUPO';
ctCuentas = 'SELECT * FROM CO_CUENTAS';
type
TFCopiarCtas = class(TForm)
btnCopiar: TBitBtn;
mlineas: TMemo;
procedure btnCopiarClick(Sender: TObject);
private
{ Private declarations }
function copiarCtas( const qry: string ): integer;
public
{ Public declarations }
end;
var
FCopiarCtas: TFCopiarCtas;
implementation
uses
DmIng;
{$R *.dfm}
procedure TFCopiarCtas.btnCopiarClick(Sender: TObject);
var
aQry: array[1..3] of string;
i, j: Integer;
begin
if ( MessageDlg( 'Confirma copia de cuentas?', mtConfirmation, mbYesNo, 9 ) <> mrYes ) then
exit;
screen.Cursor:= crHourglass;
aQry[1] := ctRubros;
aQry[2] := ctGrupos;
aQry[3] := ctCuentas;
j := 0;
try
for I := 1 to 3 do
j := j + copiarCtas( aQry[i] );
finally
showmessage( 'Cuentas actualizadas ('+inttostr(j)+')');
screen.Cursor := crDefault;
end;
end;
function TFCopiarCtas.copiarCtas(const qry: string): integer;
var
j, i: Integer;
begin
with TDMIng do
try
Origen.commandtext := qry;
Destino.commandText := qry;
Origen.Open;
Destino.Open;
j:= 0;
while not Origen.eof do
begin
if not (Destino.locate( Origen.Fields[0].FieldName, Origen.Fields[0].value, [])) then
Destino.Append
else
Destino.edit;
for I := 0 to Origen.FieldCount- 1 do
if Origen.Fields[i].FieldName <> 'SALDO' then
Destino.fields[i].value := Origen.fields[i].value;
Destino.post;
Inc(j );
Origen.next;
end;
finally
Origen.close;
Destino.close;
Result := j;
end;
end;
end.
|
unit TTSNOTCTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSNOTCRecord = record
PLenderNum: String[4];
PCategory: String[8];
PStage: String[1];
PModCount: Integer;
End;
TTTSNOTCBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSNOTCRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSNOTC = (TTSNOTCPrimaryKey);
TTTSNOTCTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFCategory: TStringField;
FDFStage: TStringField;
FDFModCount: TIntegerField;
FDFNoticeText: TBlobField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPCategory(const Value: String);
function GetPCategory:String;
procedure SetPStage(const Value: String);
function GetPStage:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEITTSNOTC);
function GetEnumIndex: TEITTSNOTC;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSNOTCRecord;
procedure StoreDataBuffer(ABuffer:TTTSNOTCRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFCategory: TStringField read FDFCategory;
property DFStage: TStringField read FDFStage;
property DFModCount: TIntegerField read FDFModCount;
property DFNoticeText: TBlobField read FDFNoticeText;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PCategory: String read GetPCategory write SetPCategory;
property PStage: String read GetPStage write SetPStage;
property PModCount: Integer read GetPModCount write SetPModCount;
published
property Active write SetActive;
property EnumIndex: TEITTSNOTC read GetEnumIndex write SetEnumIndex;
end; { TTTSNOTCTable }
procedure Register;
implementation
function TTTSNOTCTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TTTSNOTCTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TTTSNOTCTable.GenerateNewFieldName }
function TTTSNOTCTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TTTSNOTCTable.CreateField }
procedure TTTSNOTCTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFCategory := CreateField( 'Category' ) as TStringField;
FDFStage := CreateField( 'Stage' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFNoticeText := CreateField( 'NoticeText' ) as TBlobField;
end; { TTTSNOTCTable.CreateFields }
procedure TTTSNOTCTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSNOTCTable.SetActive }
procedure TTTSNOTCTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSNOTCTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSNOTCTable.SetPCategory(const Value: String);
begin
DFCategory.Value := Value;
end;
function TTTSNOTCTable.GetPCategory:String;
begin
result := DFCategory.Value;
end;
procedure TTTSNOTCTable.SetPStage(const Value: String);
begin
DFStage.Value := Value;
end;
function TTTSNOTCTable.GetPStage:String;
begin
result := DFStage.Value;
end;
procedure TTTSNOTCTable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TTTSNOTCTable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TTTSNOTCTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('Category, String, 8, N');
Add('Stage, String, 1, N');
Add('ModCount, Integer, 0, N');
Add('NoticeText, Memo, 0, N');
end;
end;
procedure TTTSNOTCTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;Category;Stage, Y, Y, N, N');
end;
end;
procedure TTTSNOTCTable.SetEnumIndex(Value: TEITTSNOTC);
begin
case Value of
TTSNOTCPrimaryKey : IndexName := '';
end;
end;
function TTTSNOTCTable.GetDataBuffer:TTTSNOTCRecord;
var buf: TTTSNOTCRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PCategory := DFCategory.Value;
buf.PStage := DFStage.Value;
buf.PModCount := DFModCount.Value;
result := buf;
end;
procedure TTTSNOTCTable.StoreDataBuffer(ABuffer:TTTSNOTCRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFCategory.Value := ABuffer.PCategory;
DFStage.Value := ABuffer.PStage;
DFModCount.Value := ABuffer.PModCount;
end;
function TTTSNOTCTable.GetEnumIndex: TEITTSNOTC;
var iname : string;
begin
result := TTSNOTCPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSNOTCPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSNOTCTable, TTTSNOTCBuffer ] );
end; { Register }
function TTTSNOTCBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..4] of string = ('LENDERNUM','CATEGORY','STAGE','MODCOUNT' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 4) and (flist[x] <> s) do inc(x);
if x <= 4 then result := x else result := 0;
end;
function TTTSNOTCBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftInteger;
end;
end;
function TTTSNOTCBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PCategory;
3 : result := @Data.PStage;
4 : result := @Data.PModCount;
end;
end;
end.
|
unit SimpleTrainView;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, Vehicles, StdCtrls, InternationalizerComponent;
type
TSimpleTrains = class(TForm)
Image: TImage;
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
xVal: TLabel;
yVal: TLabel;
Count: TLabel;
Cnt: TLabel;
Label3: TLabel;
Angle: TLabel;
InternationalizerComponent1: TInternationalizerComponent;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
public
procedure OnVehicleArrayChanged( VehicleArray : IVehicleArray );
end;
var
SimpleTrains: TSimpleTrains;
implementation
{$R *.DFM}
procedure TSimpleTrains.FormCreate(Sender: TObject);
begin
Image.Picture.Bitmap := TBitmap.Create;
Image.Picture.Bitmap.Width := Image.Width;
Image.Picture.Bitmap.Height := Image.Height;
with Image.Canvas do
begin
Pen.Color := clBlack;
Brush.Color := clBlack;
Rectangle( 0, 0, Image.Width, Image.Height );
end;
end;
procedure TSimpleTrains.OnVehicleArrayChanged( VehicleArray : IVehicleArray );
const
x1 = 385;
y1 = 360;
x2 = 433;
y2 = 395;
function ConvertX( x : single ) : integer;
begin
result := trunc(Image.Width*(x - x1)/(x2 - x1))
end;
function ConvertY( y : single ) : integer;
begin
result := trunc(Image.Height*(y - y1)/(y2 - y1))
end;
var
i : integer;
v : IVehicle;
x, y : integer;
dx, dy : integer;
rad : integer;
begin
Image.Picture.Bitmap.Width := Image.Width;
Image.Picture.Bitmap.Height := Image.Height;
with Image.Canvas do
begin
Pen.Color := clBlack;
Brush.Color := clBlack;
Rectangle( 0, 0, Image.Width, Image.Height );
Pen.Width := 1;
Pen.Style := psSolid;
Pen.Color := clGray;
Rectangle( ConvertX(387), ConvertY(363), ConvertX(399), ConvertY(381) );
MoveTo( ConvertX(399), ConvertY(381) );
LineTo( ConvertX(425), ConvertY(381) );
Rectangle( ConvertX(425), ConvertY(381), ConvertX(429), ConvertY(390) );
Pen.Color := clGreen;
Brush.Color := clYellow;
Cnt.Caption := IntToStr(VehicleArray.getVehicleCount);
rad := ConvertX(241) - ConvertX(240.5);
for i := 0 to pred(VehicleArray.getVehicleCount) do
begin
v := VehicleArray.getVehicle( i );
x := ConvertX( v.getX );
y := ConvertY( v.getY );
dx := round(cos( v.getAngle )*rad);
dy := round(sin( v.getAngle )*rad);
if i = 0
then
begin
Pen.Color := clwhite;
Brush.Color := clwhite;
end
else
begin
Pen.Color := clYellow;
Brush.Color := clYellow;
end;
//Ellipse( x - rad, y - rad, x + rad, y + rad );
Pen.Width := 3;
MoveTo( x, y );
LineTo( x - dx, y - dy );
MoveTo( x, y );
LineTo( x + dx, y + dy );
if i = 0
then
begin
xVal.Caption := IntToStr( trunc(v.getX) );
yVal.Caption := IntToStr( trunc(v.getY) );
Angle.Caption := IntToStr( round(180*v.getAngle/pi) );
end;
end;
end;
end;
procedure TSimpleTrains.FormResize(Sender: TObject);
begin
//
end;
end.
|
unit vcmItems;
{ Библиотека "vcm" }
{ Автор: Люлин А.В. © }
{ Модуль: vcmItems - }
{ Начат: 15.01.2007 17:15 }
{ $Id: vcmItems.pas,v 1.14 2010/02/24 17:39:51 lulin Exp $ }
// $Log: vcmItems.pas,v $
// Revision 1.14 2010/02/24 17:39:51 lulin
// - удаляем излишнюю виртуальность.
//
// Revision 1.13 2008/02/12 19:32:28 lulin
// - избавляемся от универсальности списков.
//
// Revision 1.12 2007/08/14 19:31:38 lulin
// - оптимизируем очистку памяти.
//
// Revision 1.11 2007/07/24 19:43:39 lulin
// - bug fix: не компилировались библиотеки.
//
// Revision 1.10 2007/07/24 19:21:09 lulin
// - скомпилировался F1 с модулем l3Interfaces, сгенерированным с модели.
//
// Revision 1.9 2007/04/03 13:34:24 mmorozov
// - bugfix: проверям типы класса элементов списка перед использованием;
//
// Revision 1.8 2007/03/01 08:39:50 lulin
// - не копируем данные строки, если их держит интерфейс строки.
//
// Revision 1.7 2007/02/28 13:15:32 lulin
// - переводим на строки с кодировкой.
//
// Revision 1.6 2007/01/26 13:11:12 lulin
// - не требуем обязательного указания заголовка операции.
//
// Revision 1.5 2007/01/15 17:34:20 lulin
// - расширяем интерфейс списка нод.
//
// Revision 1.4 2007/01/15 14:56:48 lulin
// - при построении меню используем операции модуля из списка строк.
//
// Revision 1.3 2007/01/15 14:17:51 lulin
// - добавлен еще один метод назначения кода операции.
//
// Revision 1.2 2007/01/15 14:03:03 lulin
// - добавлена возможность добавлять коды операций к строкам.
//
// Revision 1.1 2007/01/15 13:26:26 lulin
// - расширен интерфейс элементов операции.
//
{$Include vcmDefine.inc }
interface
// <no_string>
uses
{$IfDef vcmNeedL3}
l3Base,
{$EndIf vcmNeedL3}
vcmExternalInterfaces,
vcmStringList
;
type
TvcmItems = class(TvcmStringList, IvcmItems)
protected
// interface methods
// IvcmItems
{$IfNDef vcmNeedL3}
function IvcmItems.Get_Count = GetCount;
{-}
function IvcmItems.Get_Item = Get;
procedure IvcmItems.Set_Item = Put;
{-}
function IvcmItems.Get_Objects = GetObject;
procedure IvcmItems.Set_Objects = PutObject;
{-}
{$EndIf vcmNeedL3}
function pm_GetOp(anIndex: Integer): TvcmOpSelector;
{-}
function AddOp(const anOp : TvcmOpSelector;
const aCap : IvcmCString = nil;
anObj : TObject = nil): Integer;
overload;
{-}
function AddOp(const anOp : TvcmOPID;
const aCap : IvcmCString = nil;
anObj : TObject = nil): Integer;
overload;
{-}
function AddOp(const anOp : TvcmMOPID;
const aCap : IvcmCString = nil;
anObj : TObject = nil): Integer;
overload;
{-}
protected
// internal methods
{$IfDef vcmNeedL3}
function CStrToItem(const aStr: IvcmCString): Tl3CustomString;
override;
{-}
function StringItemClass: Rl3String;
override;
{-}
{$EndIf vcmNeedL3}
public
// public methods
class function Make: IvcmItems;
reintroduce;
{-}
end;//TvcmItems
implementation
uses
{$IfDef vcmNeedL3}
l3VCLStrings,
{$EndIf vcmNeedL3}
vcmBase
;
{$IfDef vcmNeedL3}
type
TvcmItemsString = class(Tl3ObjPtrString)
private
// internal fields
f_Op : TvcmOpSelector;
public
// public methods
procedure InitFields;
override;
{-}
end;//TvcmItemsString
procedure TvcmItemsString.InitFields;
//override;
{-}
begin
inherited;
l3FillChar(f_Op, SizeOf(f_Op), 0);
end;
type
TvcmItemsIntfString = class(Tl3ObjPtrIntfString)
private
// internal fields
f_Op : TvcmOpSelector;
public
// public methods
procedure InitFields;
override;
{-}
end;//TvcmItemsString
procedure TvcmItemsIntfString.InitFields;
//override;
{-}
begin
inherited;
l3FillChar(f_Op, SizeOf(f_Op), 0);
end;
{$EndIf vcmNeedL3}
// start class TvcmItems
class function TvcmItems.Make: IvcmItems;
//reintroduce;
{-}
var
l_Items : TvcmItems;
begin
l_Items := Create;
try
Result := l_Items;
finally
vcmFree(l_Items);
end;//try..finally
end;
function TvcmItems.pm_GetOp(anIndex: Integer): TvcmOpSelector;
{-}
{$IfDef vcmNeedL3}
var
l_Item : Tl3PrimString;
{$EndIf vcmNeedL3}
begin
{$IfDef vcmNeedL3}
l_Item := Items[anIndex];
if (l_Item Is TvcmItemsIntfString) then
Result := TvcmItemsIntfString(l_Item).f_Op
else
if (l_Item Is TvcmItemsString) then
Result := TvcmItemsString(l_Item).f_Op
else
l3FillChar(Result, SizeOf(TvcmOpSelector), 0);
{$Else vcmNeedL3}
FillChar(Result, SizeOf(Result), 0);
{$EndIf vcmNeedL3}
end;
function TvcmItems.AddOp(const anOp : TvcmOpSelector;
const aCap : IvcmCString = nil;
anObj : TObject = nil): Integer;
//overload;
{-}
{$IfDef vcmNeedL3}
var
l_Item : Tl3PrimString;
{$EndIf vcmNeedL3}
begin
Result := Add(aCap);
if (anObj <> nil) then
{$IfDef vcmNeedL3}
Set_Objects(Result, anObj);
{$Else vcmNeedL3}
PutObject(Result, anObj);
{$EndIf vcmNeedL3}
{$IfDef vcmNeedL3}
l_Item := Items[Result];
if (l_Item Is TvcmItemsIntfString) then
TvcmItemsIntfString(l_Item).f_Op := anOp
else
if (l_Item Is TvcmItemsString) then
TvcmItemsString(l_Item).f_Op := anOp
else
Assert(False);
{$EndIf vcmNeedL3}
end;
function TvcmItems.AddOp(const anOp : TvcmOPID;
const aCap : IvcmCString = nil;
anObj : TObject = nil): Integer;
//overload;
{-}
var
l_Op : TvcmOpSelector;
begin
l_Op.rKind := vcm_okEntity;
l_Op.rID := anOp;
Result := AddOp(l_Op, aCap, anObj);
end;
function TvcmItems.AddOp(const anOp : TvcmMOPID;
const aCap : IvcmCString = nil;
anObj : TObject = nil): Integer;
//overload;
{-}
var
l_Op : TvcmOpSelector;
begin
l_Op.rKind := vcm_okModule;
l_Op.rMID := anOp;
Result := AddOp(l_Op, aCap, anObj);
end;
{$IfDef vcmNeedL3}
function TvcmItems.CStrToItem(const aStr: IvcmCString): Tl3CustomString;
//override;
{-}
begin
Result := TvcmItemsIntfString.Make(aStr);
end;
function TvcmItems.StringItemClass: Rl3String;
//override;
{-}
begin
Result := TvcmItemsString;
end;
{$EndIf vcmNeedL3}
end.
|
unit WWChart;
interface
uses
//
XMLFlowChartUnit,
XMLNSChartUnit,
SysRecords,
SysConsts,
//
XMLDoc,XMLIntf, Graphics,
SysUtils, Classes, Controls;
type
TWWChartMode = (cmFlowChart, cmNSChart);
TWWChart = class(TCustomControl)
private
XML : TXMLDocument; //用于保存所有节点信息
FocusedNode : IXMLNode;
FChartMode: TWWChartMode;
FSpaceVert: Word;
FBaseHeight: Word;
FSpaceHorz: Word;
FBaseWidth: Word;
FSelectedColor: TColor;
FIFColor: TColor;
FLineColor: TColor;
FScale: Single;
FFont: TFont;
procedure SetChartMode(const Value: TWWChartMode);
procedure SetBaseHeight(const Value: Word);
procedure SetBaseWidth(const Value: Word);
procedure SetSpaceHorz(const Value: Word);
procedure SetSpaceVert(const Value: Word);
procedure SetIFColor(const Value: TColor);
procedure SetLineColor(const Value: TColor);
procedure SetSelectedColor(const Value: TColor);
procedure SetScale(const Value: Single);
procedure SetFont(const Value: TFont); //当前XML节点
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent);override;
destructor Destory;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);override;
procedure MouseMove(Shift: TShiftState; X,Y: Integer); override;
procedure LoadFromFile(FileName:string);
procedure SaveToFile(FileName:string);
published
property ChartMode : TWWChartMode read FChartMode write SetChartMode;
property BaseWidth : Word read FBaseWidth write SetBaseWidth default 50;
property BaseHeight : Word read FBaseHeight write SetBaseHeight default 30;
property SpaceHorz : Word read FSpaceHorz write SetSpaceHorz default 20;
property SpaceVert : Word read FSpaceVert write SetSpaceVert default 20;
property LineColor : TColor read FLineColor write SetLineColor default clBlack;
property IFColor : TColor read FIFColor write SetIFColor default clLime;
property SelectedColor : TColor read FSelectedColor write SetSelectedColor default clAqua;
property Scale : Single read FScale write SetScale;
property Font:TFont read FFont write SetFont;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('WestWind', [TWWChart]);
end;
{ TWWChart }
constructor TWWChart.Create(AOwner: TComponent);
var
xnRoot : IXMLNode;
xnNew : IXMLNode;
begin
inherited;
//默认ChartMode
FChartMode := cmFlowChart;
FBaseWidth := 50;
FBaseHeight := 30;
FSpaceVert := 20;
FSpaceHorz := 20;
FLineColor := clBlack;
FIFColor := clLime;
FSelectedColor := clAqua;
FScale := 1;
//
FFont := TFont.Create;
FFont.Name := 'MS Sans Serif';
FFont.Size := 10;
//创建XML对象
XML := TXMLDocument.Create(self);
XML.Active := True;
XML.Version := '1.0';
XML.Encoding := 'UTF-8';
//
xnRoot := XML.AddChild('Root');
xnNew := xnRoot.AddChild('RT_CODE');
xnNew.Attributes['Mode'] := rtBlock_Code;
xnNew.Attributes['Expanded'] := True;
//
end;
destructor TWWChart.Destory;
begin
//释放XML
if XML<>nil then begin
XML.Destroy;
end;
end;
procedure TWWChart.LoadFromFile(FileName: string);
begin
//
XML.LoadFromFile(FileName);
end;
procedure TWWChart.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
end;
procedure TWWChart.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
end;
procedure TWWChart.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
end;
procedure TWWChart.Paint;
var
rConfig : TWWConfig;
begin
inherited;
//
rConfig.BaseWidth := FBaseWidth;
rConfig.BaseHeight := FBaseHeight;
rConfig.SpaceVert := FSpaceVert;
rConfig.SpaceHorz := FSpaceHorz;
rConfig.LineColor := FLineColor;
rConfig.IFColor := FIFColor;
rConfig.Scale := FScale;
rConfig.FontName := FFont.Name;
rConfig.FontSize := FFont.Size;
rConfig.FontColor := FFont.Color;
//
if FChartMode=cmFlowchart then begin
DrawXmlToFlowChart(XML.DocumentElement.ChildNodes[0],Canvas,rConfig);
end else begin
DrawXmlToNSChart(XML.DocumentElement.ChildNodes[0],Canvas,rConfig);
end;
end;
procedure TWWChart.SaveToFile(FileName: string);
begin
XML.SaveToFile(FileName);
end;
procedure TWWChart.SetBaseHeight(const Value: Word);
begin
FBaseHeight := Value;
end;
procedure TWWChart.SetBaseWidth(const Value: Word);
begin
FBaseWidth := Value;
end;
procedure TWWChart.SetChartMode(const Value: TWWChartMode);
begin
FChartMode := Value;
end;
procedure TWWChart.SetFont(const Value: TFont);
begin
FFont := Value;
end;
procedure TWWChart.SetIFColor(const Value: TColor);
begin
FIFColor := Value;
end;
procedure TWWChart.SetLineColor(const Value: TColor);
begin
FLineColor := Value;
end;
procedure TWWChart.SetScale(const Value: Single);
begin
FScale := Value;
end;
procedure TWWChart.SetSelectedColor(const Value: TColor);
begin
FSelectedColor := Value;
end;
procedure TWWChart.SetSpaceHorz(const Value: Word);
begin
FSpaceHorz := Value;
end;
procedure TWWChart.SetSpaceVert(const Value: Word);
begin
FSpaceVert := Value;
end;
end.
|
unit NtUtils.Transactions.Remote;
interface
uses
NtUtils.Exceptions;
// Get a handle value of the current transaction on a remote thread
function RtlxGetTransactionThread(hProcess: THandle; hThread: THandle;
out HandleValue: THandle): TNtxStatus;
// Set a handle value of the current transaction on a remote thread
function RtlxSetTransactionThread(hProcess: THandle; hThread: THandle;
HandleValue: THandle): TNtxStatus;
implementation
uses
Ntapi.ntpsapi, Ntapi.ntwow64, NtUtils.Threads, NtUtils.Processes,
NtUtils.Processes.Memory;
function RtlxGetTransactionThread(hProcess: THandle; hThread: THandle;
out HandleValue: THandle): TNtxStatus;
var
ThreadInfo: TThreadBasicInformation;
begin
// Although under WoW64 we can still work with other WoW64 processes we
// won't because we still need to update 64-bit TEB, and it is complicated.
Result := NtxAssertNotWoW64;
if not Result.IsSuccess then
Exit;
// Query TEB location for the thread
Result := NtxThread.Query<TThreadBasicInformation>(hThread,
ThreadBasicInformation, ThreadInfo);
if not Result.IsSuccess then
Exit;
// Read the handle value from thread's TEB.
// In case of a WoW64 target it has two TEBs, and both of them should
// store the same handle value. However 64-bit TEB has precendence, so
// the following code also works for WoW64 processes.
Result := NtxReadMemoryProcess(hProcess,
@ThreadInfo.TebBaseAddress.CurrentTransactionHandle,
@HandleValue, SizeOf(HandleValue));
end;
function RtlxSetTransactionThread(hProcess: THandle; hThread: THandle;
HandleValue: THandle): TNtxStatus;
var
ThreadInfo: TThreadBasicInformation;
{$IFDEF Win64}
IsWow64Target: NativeUInt;
Teb32Offset: Integer;
Teb32: PTeb32;
HandleValue32: Cardinal;
{$ENDIF}
begin
// Although under WoW64 we can still work with other WoW64 processes we
// won't because we still need to update 64-bit TEB, and it is complicated.
Result := NtxAssertNotWoW64;
if not Result.IsSuccess then
Exit;
// Query TEB location for the thread
Result := NtxThread.Query<TThreadBasicInformation>(hThread,
ThreadBasicInformation, ThreadInfo);
if not Result.IsSuccess then
Exit;
// Write the handle value to thread's TEB
Result := NtxWriteMemoryProcess(hProcess,
@ThreadInfo.TebBaseAddress.CurrentTransactionHandle,
@HandleValue, SizeOf(HandleValue));
if not Result.IsSuccess then
Exit;
// Threads in WoW64 processes have two TEBs, so we should update both of them.
// However, this operation is optional since 64-bit TEB has precedence,
// therefore we ignore errors in the following code.
{$IFDEF Win64}
if NtxProcess.Query<NativeUInt>(hProcess, ProcessWow64Information,
IsWow64Target).IsSuccess and (IsWow64Target <> 0) then
begin
// 64-bit TEB stores an offset to a 32-bit TEB, read it
if not NtxReadMemoryProcess(hProcess,
@ThreadInfo.TebBaseAddress.WowTebOffset,
@Teb32Offset, SizeOf(Teb32Offset)).IsSuccess then
Exit;
if Teb32Offset = 0 then
Exit;
HandleValue32 := Cardinal(HandleValue);
Teb32 := PTeb32(NativeInt(ThreadInfo.TebBaseAddress) + Teb32Offset);
// Write the handle to the 32-bit TEB
NtxWriteMemoryProcess(hProcess, @Teb32.CurrentTransactionHandle,
@HandleValue32, SizeOf(HandleValue32));
end;
{$ENDIF}
end;
end.
|
unit np.dirmon;
interface
uses sysUtils, np.common, np.core, np.fs, np.promise, np.libuv, np.value, np.EventEmitter;
const
RefreshDelayDefault = 2000;
evScanComplete = 1;
evResourceChanged = 2;
evResourceInitialized = 3;
evScanProgress = 4;
type
TResourceStat = class;
PResourceChanged = ^TResourceChanged;
TResourceHash = class;
IResourceStat = IValue<TResourceStat>;
IResourceHash = IValue<TResourceHash>;
TResourceChanged = record
name: string;
error: PNPError;
status: TResourceStat;
end;
PScanComplete = ^IResourceHash;
TResourceStat = Class(TSelfValue,IResourceStat)
private
Flink : IResourceHash;
Fid : string;
Fversion : integer;
FchangeTime : Double;
Fcontent_type: string;
Fcontent : TBytes;
Fcontent_version: integer;
Fdelay: INPTimer;
FupdateMode: Boolean;
Fupdate: record
version : integer;
changeTime : Double;
content: TBytes;
prevent_destroy_while_update_self_link : IResourceStat;
end;
procedure LoadVersion;
procedure LoadVersionBegin;
procedure LoadVersionDo;
procedure LoadVersionDoAgain;
procedure LoadVersionEnd(Error: PNPError);
function this : TResourceStat;
constructor Create(const ADirHash:IResourceHash; const resId:string);
public
property name : String read FId;
property content : TBytes read Fcontent;
property version: integer read Fcontent_version;
property last_modified : Double read FchangeTime;
property RSRCHash: IResourceHash read Flink;
end;
TResourceHash = Class(TEventEmitterAnyObject, IResourceHash )
private
Fdir : String;
FRefreshDelay: integer;
FWatchLink : IResourceHash;
FScanLink : IResourceHash;
FScanComplete : Boolean;
function this: TResourceHash;
procedure runScan;
procedure runWatch;
protected
function _add(id: integer; p: TProc; once: Boolean; hasArg: Boolean) : IEventHandler; override;
public
constructor Create(const ADirectory: String; ARefreshDelay:integer = RefreshDelayDefault);
function GetStat(const resourceId : string; ACreate:Boolean = false) : IResourceStat;
property Dir : string read FDir;
end;
implementation
{ TResourceStat }
constructor TResourceStat.Create(const ADirHash:IResourceHash; const resId:string);
begin
inherited Create();
Flink := ADirHash;
Fid := resId;
end;
{ TResourceHash }
constructor TResourceHash.Create(const ADirectory: String;
ARefreshDelay: integer);
begin
inherited Create();
Fdir := ADirectory;
FRefreshDelay := ARefreshDelay;
FScanLink := self;
FWatchLink := self;
NextTick(
procedure
begin
RunScan;
end);
once(evScanComplete,
procedure
begin
FScanComplete := true;
end);
end;
function TResourceHash.GetStat(const resourceId: string; ACreate: Boolean): IResourceStat;
var
tmp : IValue;
begin
tmp := getValue(resourceId);
if not (tmp is TResourceStat) then
begin
if not ACreate then
exit(nil);
tmp := TResourceStat.Create(self, resourceId);
SetValue(resourceId, tmp);
end;
result := tmp as IResourceStat;
if not ACreate and (result.this.version = 0) then
result := nil;
end;
procedure TResourceHash.runWatch;
begin
setFSWatch(
procedure(event: TFS_Event; Afile:UTF8String)
begin
GetStat(AFile, true).this.LoadVersion;
end, FDir);
end;
procedure TResourceHash.runScan;
var
scaning_count : integer;
begin
scaning_count := 0;
fs.readdir(
Fdir,
procedure (error: PNPError; list: fs.TDirentWithTypesArray)
var
i : integer;
this : IResourceHash;
begin
if error <> nil then
begin
raise ENPException.Create(error.code);
end;
for i := low(list) to high(list) do
begin
if list[i].type_ = UV_DIRENT_FILE then
begin
with GetStat(list[i].name, true ).this do
begin
inc( scaning_count );
LoadVersionBegin;
end;
end;
end;
FScanLink := nil;
if scaning_count = 0 then
begin
this := self;
emit(evScanComplete, @this );
this := nil;
end;
runWatch;
end
);
on_(evResourceInitialized,
procedure
var
this : IResourceHash;
begin
dec( scaning_count );
if scaning_count = 0 then
begin
this := self;
emit(evScanComplete, @this );
this := nil;
end;
end);
end;
procedure TResourceStat.LoadVersionEnd(error: PNPError);
var
arg : TResourceChanged;
begin
FupdateMode := false;
arg.name := FId;
arg.error := error;
arg.status := self;
if assigned(Flink) then
begin
if error <> nil then
begin
//stderr.PrintLn(Format('%s error "%s"',[Fid, error.msg] ));
Fversion := 0;
Flink.this.DeleteKey(Fid);
Flink.this.emit(evResourceChanged, @arg );
Flink := nil;
end
else
begin
//stdout.PrintLn(Format('%s updated! (ver. %d)',[Fid,Fversion] ));
Flink.this.emit(evResourceChanged, @arg );
end;
end;
Fupdate.prevent_destroy_while_update_self_link := nil;
end;
function TResourceStat.this: TResourceStat;
begin
result := Self;
end;
procedure TResourceStat.LoadVersion;
begin
if assigned( Fdelay ) then
Cleartimer(Fdelay);
Fdelay := SetTimeout(
procedure
begin
Fdelay := nil;
LoadVersionBegin;
end,Flink.this.FRefreshDelay);
end;
procedure TResourceStat.LoadVersionBegin;
begin
inc(Fversion);
//stdout.PrintLn(Format('%s updating... (ver. %d->%d)',[Fid,Fversion-1,Fversion] ));
if FupdateMode then
exit;
FupdateMode := true;
LoadVersionDo;
end;
procedure TResourceStat.LoadVersionDo;
var
path : string;
begin
assert(FupdateMode);
Fupdate.prevent_destroy_while_update_self_link := self;
Fupdate.version := Fversion;
path := Flink.this.Fdir + PathDelim + Fid;
fs.stat(path,
procedure (error: PNPError; stat1 : puv_stat_t )
begin
if assigned(error) then
begin
LoadVersionEnd(error);
exit;
end;
Fupdate.changeTime := stat1.st_mtim.toTimeStamp;
SetLength( Fupdate.content, stat1.st_size );
fs.open(path,np_const.uv_fs_o_rdonly,oct666,
procedure (error: PNPError; fd : uv_file)
begin
if assigned(error) then
begin
LoadVersionEnd(error);
exit;
end;
fs.read(fd, Fupdate.content,
procedure (error:PNPError; num: size_t; buf: TBytes )
begin
if assigned(error) then
begin
LoadVersionEnd(error);
exit;
end;
if length(buf) <> num then
begin
LoadVersionDoAgain;
end;
fs.fstat(fd,
procedure(error:PNPError; stat1: puv_stat_t)
begin
fs.close(fd,nil);
if assigned(error) then
begin
LoadVersionEnd(error);
exit;
end;
if (Fupdate.changeTime = stat1.st_mtim.toTimeStamp) and
(length(Fupdate.content) = stat1.st_size) then
begin
Fcontent := Fupdate.content;
Fcontent_version := Fupdate.version;
FchangeTime := Fupdate.changeTime;
if Fupdate.version = 1 then
FLink.this.emit(evResourceInitialized);
FupdateMode := Fupdate.version <> Fversion;
if FupdateMode then
begin
LoadVersionDoAgain;
end
else
begin
LoadVersionEnd(nil);
end;
end
else
begin
LoadVersionDoAgain;
end;
end);
end);
end);
end);
end;
procedure TResourceStat.LoadVersionDoAgain;
begin
SetTimeout(
procedure
begin
LoadVersionDo;
end, 1000);
end;
function TResourceHash.this: TResourceHash;
begin
result := self;
end;
function TResourceHash._add(id: integer; p: TProc; once,
hasArg: Boolean): IEventHandler;
var
imd : IEventHandler;
this : IResourceHash;
begin
result := inherited _add(id,p,once,hasArg);
if (id = evScanComplete) and (FScanComplete) then
begin
imd := result;
this := self;
NextTick(
procedure
begin
imd.invoke(@this);
end);
end;
end;
end.
|
unit uAR;
interface
uses
uModel, System.SysUtils,System.Classes, uSupplier;
type
TAR = class(TAppObject)
private
FCabang: TCabang;
FCustomer: TSupplier;
FIDTransaksi: string;
FNoBukti: string;
FNominal: Double;
FPembayaranTerakhir: TDatetime;
FTerBayar: Double;
FTransaksi: string;
FJatuhTempo: TDateTime;
FNoBuktiTransaksi: string;
FTglBukti: TDatetime;
public
destructor Destroy; override;
published
property Cabang: TCabang read FCabang write FCabang;
property Customer: TSupplier read FCustomer write FCustomer;
property IDTransaksi: string read FIDTransaksi write FIDTransaksi;
property NoBukti: string read FNoBukti write FNoBukti;
property Nominal: Double read FNominal write FNominal;
property PembayaranTerakhir: TDatetime read FPembayaranTerakhir write
FPembayaranTerakhir;
property TerBayar: Double read FTerBayar write FTerBayar;
property Transaksi: string read FTransaksi write FTransaksi;
property JatuhTempo: TDateTime read FJatuhTempo write FJatuhTempo;
property NoBuktiTransaksi: string read FNoBuktiTransaksi write
FNoBuktiTransaksi;
property TglBukti: TDatetime read FTglBukti write FTglBukti;
end;
TAP = class(TAppObject)
private
FCabang: TCabang;
FSupplier: TSupplier;
FIDTransaksi: string;
FNoBukti: string;
FNominal: Double;
FPembayaranTerakhir: TDatetime;
FTerBayar: Double;
FTransaksi: string;
FJatuhTempo: TDateTime;
FNoBuktiTransaksi: string;
FTglBukti: TDatetime;
public
destructor Destroy; override;
published
property Cabang: TCabang read FCabang write FCabang;
property Supplier: TSupplier read FSupplier write FSupplier;
property IDTransaksi: string read FIDTransaksi write FIDTransaksi;
property NoBukti: string read FNoBukti write FNoBukti;
property Nominal: Double read FNominal write FNominal;
property PembayaranTerakhir: TDatetime read FPembayaranTerakhir write
FPembayaranTerakhir;
property TerBayar: Double read FTerBayar write FTerBayar;
property Transaksi: string read FTransaksi write FTransaksi;
property JatuhTempo: TDateTime read FJatuhTempo write FJatuhTempo;
property NoBuktiTransaksi: string read FNoBuktiTransaksi write
FNoBuktiTransaksi;
property TglBukti: TDatetime read FTglBukti write FTglBukti;
end;
implementation
destructor TAR.Destroy;
begin
inherited;
FreeAndNil(FCabang);
FreeAndNil(FCustomer);
end;
destructor TAP.Destroy;
begin
inherited;
FreeAndNil(FCabang);
FreeAndNil(FSupplier);
end;
end.
|
unit MediaNameHistory;
interface
uses
Classes, SysUtils, Persistent, BackupInterfaces;
type
TMediaNameHistory =
class(TPersistent)
public
constructor Create;
destructor Destroy; override;
private
fHistory : TStringList;
public
procedure Add(name : string);
function AddNumber(name, sep : string) : string;
private
function IncAt(index : integer) : integer;
protected
procedure LoadFromBackup( Reader : IBackupReader ); override;
procedure StoreToBackup ( Writer : IBackupWriter ); override;
end;
procedure RegisterBackup;
implementation
// TMediaNameHistory
constructor TMediaNameHistory.Create;
begin
inherited;
fHistory := TStringList.Create;
end;
destructor TMediaNameHistory.Destroy;
begin
fHistory.Free;
inherited;
end;
procedure TMediaNameHistory.Add(name : string);
var
idx : integer;
aux : string;
begin
aux := LowerCase(name);
idx := fHistory.IndexOf(aux);
if idx < 0
then fHistory.Add(aux)
else IncAt(idx);
end;
function TMediaNameHistory.AddNumber(name, sep : string) : string;
var
idx : integer;
aux : string;
begin
aux := LowerCase(name);
idx := fHistory.IndexOf(aux);
if idx < 0
then
begin
fHistory.Add(aux);
result := name;
end
else result := name + sep + IntToStr(IncAt(idx));
end;
function TMediaNameHistory.IncAt(index : integer) : integer;
begin
result := integer(fHistory.Objects[index]);
inc(result);
fHistory.Objects[index] := TObject(result);
end;
procedure TMediaNameHistory.LoadFromBackup(Reader : IBackupReader);
begin
inherited;
fHistory := TStringList.Create;
end;
procedure TMediaNameHistory.StoreToBackup(Writer : IBackupWriter);
var
i : integer;
begin
inherited;
Writer.WriteInteger('cnt', fHistory.Count);
for i := 0 to pred(fHistory.Count) do
begin
Writer.WriteString('fn', fHistory[i]);
Writer.WriteInteger('val', integer(fHistory.Objects[i]));
end;
end;
procedure RegisterBackup;
begin
BackupInterfaces.RegisterClass( TMediaNameHistory );
end;
end.
|
unit Unit_CustomXMLWriter;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, XMLRead, DOM;
type
{ TCustomXMLWriter }
TCustomXMLWriter = class(TObject)
FLines: TStringList;
FLineBuffer: String;
FLevel: Integer;
constructor Create();
procedure AddLine(Line: String);
procedure WriteElement(Node: TDOMNode);
procedure WriteText(Node: TDOMNode);
procedure WriteComment(Node: TDOMNode);
procedure WriteDocument(Node: TDOMNode);
procedure WriteNode(Node: TDOMNode);
function GetLines(): TStringList;
end;
implementation
{ TCustomXMLWriter }
constructor TCustomXMLWriter.Create;
begin
FLines := TStringList.Create;
FLevel := 0;
end;
procedure TCustomXMLWriter.WriteElement(Node: TDOMNode);
var
NodeName: String;
Child: TDOMNode;
begin
NodeName := Node.NodeName;
FLineBuffer := Format('<%s', [NodeName]);
Child := Node.FirstChild;
if Child = nil then
AddLine('/>')
else begin
FLineBuffer := FLineBuffer + '>';
if FLevel = 0 then
AddLine('');
Inc(FLevel);
repeat
WriteNode(Child);
Child := Child.NextSibling;
until Child = nil;
Dec(FLevel);
AddLine(Format('</%s>', [NodeName]));
if Node.ParentNode.LastChild <> Node then begin
AddLine('');
AddLine('');
end;
end;
end;
procedure TCustomXMLWriter.WriteText(Node: TDOMNode);
begin
FLineBuffer := FLineBuffer + Node.NodeValue;
end;
procedure TCustomXMLWriter.WriteComment(Node: TDOMNode);
begin
AddLine(Format('<!--%s-->', [Node.NodeValue]));
end;
procedure TCustomXMLWriter.WriteDocument(Node: TDOMNode);
var
Child: TDOMNode;
begin
Child := Node.FirstChild;
while Assigned(Child) do begin
WriteNode(Child);
Child := Child.NextSibling;
end;
end;
procedure TCustomXMLWriter.WriteNode(Node: TDOMNode);
begin
case Node.NodeType of
ELEMENT_NODE: WriteElement(Node);
COMMENT_NODE: WriteComment(Node);
DOCUMENT_NODE: WriteDocument(Node);
TEXT_NODE: WriteText(node);
end;
end;
function TCustomXMLWriter.GetLines: TStringList;
begin
Result := FLines;
end;
procedure TCustomXMLWriter.AddLine(Line: String);
var
Indent: String;
i: Integer;
begin
Indent := '';
for i := 1 to FLevel*4 do
Indent := Indent + ' ';
FLines.Add(UTF8Encode(Indent + FLineBuffer + Line));
FLineBuffer := '';
end;
end.
|
unit MultEditPropertyEditor;
interface
uses
DesignIntf,
DesignEditors,
System.Classes,
System.SysUtils,
VCL.Dialogs,
System.TypInfo,
MultEdit;
type
TMultEditPropertyEditor = class(TComponentEditor)
private
function Instance: TMultEdit;
public
function GetVerbCount: Integer; override;
function GetVerb(Index: Integer): String; override;
procedure ExecuteVerb(Index: Integer); override;
procedure Edit; override;
procedure SetDefault;
procedure TestValidation;
procedure TestValidationInput;
end;
procedure Register;
implementation
procedure register;
begin
RegisterComponentEditor(TMultEdit, TMultEditPropertyEditor);
end;
procedure TMultEditPropertyEditor.Edit;
begin
ExecuteVerb(0);
end;
procedure TMultEditPropertyEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: MessageDlg('Component Mult Editor ' + Instance.Version, mtInformation, [mbOk], 0);
1: SetDefault;
2: TestValidation;
3: TestValidationInput;
end;
Designer.Modified;
inherited;
end;
function TMultEditPropertyEditor.GetVerb(Index: Integer): String;
begin
case Index of
0: Result := 'About MultEditor...';
1: Result := 'Reset Default Properties';
2: Result := 'Test Validation';
3: Result := 'Test Validation Input';
end;
end;
function TMultEditPropertyEditor.GetVerbCount: Integer;
begin
Result := 4;
end;
function TMultEditPropertyEditor.Instance: TMultEdit;
begin
Result := (Component as TMultEdit);
end;
procedure TMultEditPropertyEditor.SetDefault;
begin
if MessageDlg('Reset Default Properties?', mtConfirmation, [mbYes, mbNo], 0) = 6 then
Instance.ResetDefaults;
end;
procedure TMultEditPropertyEditor.TestValidation;
begin
Instance.Test;
end;
procedure TMultEditPropertyEditor.TestValidationInput;
begin
Instance.TestInput;
end;
end.
|
{ Date Created: 5/30/00 3:28:18 PM }
unit InfoGRUPEVNTTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoGRUPEVNTRecord = record
PGroup: String[6];
PEventCode: String[6];
End;
TInfoGRUPEVNTBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoGRUPEVNTRecord
end;
TEIInfoGRUPEVNT = (InfoGRUPEVNTPrimaryKey);
TInfoGRUPEVNTTable = class( TDBISAMTableAU )
private
FDFGroup: TStringField;
FDFEventCode: TStringField;
procedure SetPGroup(const Value: String);
function GetPGroup:String;
procedure SetPEventCode(const Value: String);
function GetPEventCode:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIInfoGRUPEVNT);
function GetEnumIndex: TEIInfoGRUPEVNT;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoGRUPEVNTRecord;
procedure StoreDataBuffer(ABuffer:TInfoGRUPEVNTRecord);
property DFGroup: TStringField read FDFGroup;
property DFEventCode: TStringField read FDFEventCode;
property PGroup: String read GetPGroup write SetPGroup;
property PEventCode: String read GetPEventCode write SetPEventCode;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoGRUPEVNT read GetEnumIndex write SetEnumIndex;
end; { TInfoGRUPEVNTTable }
procedure Register;
implementation
function TInfoGRUPEVNTTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TInfoGRUPEVNTTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TInfoGRUPEVNTTable.GenerateNewFieldName }
function TInfoGRUPEVNTTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TInfoGRUPEVNTTable.CreateField }
procedure TInfoGRUPEVNTTable.CreateFields;
begin
FDFGroup := CreateField( 'Group' ) as TStringField;
FDFEventCode := CreateField( 'EventCode' ) as TStringField;
end; { TInfoGRUPEVNTTable.CreateFields }
procedure TInfoGRUPEVNTTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoGRUPEVNTTable.SetActive }
procedure TInfoGRUPEVNTTable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoGRUPEVNTTable.Validate }
procedure TInfoGRUPEVNTTable.SetPGroup(const Value: String);
begin
DFGroup.Value := Value;
end;
function TInfoGRUPEVNTTable.GetPGroup:String;
begin
result := DFGroup.Value;
end;
procedure TInfoGRUPEVNTTable.SetPEventCode(const Value: String);
begin
DFEventCode.Value := Value;
end;
function TInfoGRUPEVNTTable.GetPEventCode:String;
begin
result := DFEventCode.Value;
end;
procedure TInfoGRUPEVNTTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Group, String, 6, N');
Add('EventCode, String, 6, N');
end;
end;
procedure TInfoGRUPEVNTTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Group, Y, Y, N, N');
end;
end;
procedure TInfoGRUPEVNTTable.SetEnumIndex(Value: TEIInfoGRUPEVNT);
begin
case Value of
InfoGRUPEVNTPrimaryKey : IndexName := '';
end;
end;
function TInfoGRUPEVNTTable.GetDataBuffer:TInfoGRUPEVNTRecord;
var buf: TInfoGRUPEVNTRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PGroup := DFGroup.Value;
buf.PEventCode := DFEventCode.Value;
result := buf;
end;
procedure TInfoGRUPEVNTTable.StoreDataBuffer(ABuffer:TInfoGRUPEVNTRecord);
begin
DFGroup.Value := ABuffer.PGroup;
DFEventCode.Value := ABuffer.PEventCode;
end;
function TInfoGRUPEVNTTable.GetEnumIndex: TEIInfoGRUPEVNT;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoGRUPEVNTPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoGRUPEVNTTable, TInfoGRUPEVNTBuffer ] );
end; { Register }
function TInfoGRUPEVNTBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PGroup;
2 : result := @Data.PEventCode;
end;
end;
end. { InfoGRUPEVNTTable }
|
unit EuroForm;
// ************************************************************************ //
// WARNING
// -------
// The code declared in this file was generated from data read from a
// a *.DFM file using Dfm2Pas 1.0. This tool was meant to help you
// with the conversion of Delphi forms into Morpheus until we have an
// IDE and a Form designer.
// Keep in mind that we do not expect it to give you a 100% conversion
// but significantly reduce the amount of work you'd have to do.
// For now we expect to achieve between 90 and 99% of the necessary conversion.
//
// For a list of known issues check the README file (readme.txt).
//
// If you have any problems or suggestions please let us know.
// ************************************************************************ //
interface
uses
{$IFDEF CLR}Borland.Win32.Windows{$ELSE}Windows{$ENDIF},
{$IFDEF CLR}Borland.Win32.Messages{$ELSE}Messages{$ENDIF},
{$IFDEF CLR}Borland.Delphi.SysUtils{$ELSE}SysUtils{$ENDIF},
{$IFDEF CLR}Borland.Delphi.Variants{$ELSE}Variants{$ENDIF},
{$IFDEF CLR}Borland.Delphi.Classes{$ELSE}Classes{$ENDIF},
{$IFDEF CLR}Borland.Vcl.Graphics{$ELSE}Graphics{$ENDIF},
{$IFDEF CLR}Borland.Vcl.Controls{$ELSE}Controls{$ENDIF},
{$IFDEF CLR}Borland.Vcl.Forms{$ELSE}Forms{$ENDIF},
{$IFDEF CLR}Borland.Vcl.Dialogs{$ELSE}Dialogs{$ENDIF},
{$IFDEF CLR}Borland.Vcl.StdCtrls{$ELSE}StdCtrls{$ENDIF};
type
TForm1 = class(TForm)
Button1: TButton;
EditValue: TEdit;
EditResult: TEdit;
ListTypes: TListBox;
ListTypes2: TListBox;
Label1: TLabel;
Label2: TLabel;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
{$IFDEF CLR}
procedure InitializeControls;
{$ENDIF}
public
{ Public declarations }
{$IFDEF CLR}
constructor Create(AOwner: TComponent); override;
{$ENDIF}
end;
var
Form1: TForm1;
implementation
uses
EuroConvConst,
{$IFDEF CLR}Borland.Delphi.ConvUtils{$ELSE}ConvUtils{$ENDIF},
{$IFDEF CLR}Borland.Delphi.Math{$ELSE}Math{$ENDIF};
procedure TForm1.Button1Click(Sender: TObject);
var
nConverted: Double;
BaseType, DestType: TConvType;
begin
// simple conversions (test)
{EditResult.Text := FloatToStrF (
Convert (StrToFloat (EditValue.Text),
cuDEM, cuITL), ffNumber, 15, 3)}
DescriptionToConvType(cbEuroCurrency,
ListTypes.Items [ListTypes.ItemIndex], BaseType);
DescriptionToConvType(cbEuroCurrency,
ListTypes2.Items [ListTypes2.ItemIndex], DestType);
// plain conversions
{nConverted := Convert (StrToFloat (EditValue.Text),
BaseType, DestType);
EditResult.Text := FloatToStrF (nConverted, ffNumber, 15, 4);}
// Euro "rounding" conversion
nConverted := EuroConvert (StrToFloat (EditValue.Text),
BaseType, DestType, 4);
EditResult.Text := FloatToStrF (nConverted, ffNumber, 15, 4);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
ATypes: TConvTypeArray;
i: Integer;
begin
GetConvTypes(cbEuroCurrency, ATypes);
for i := Low(aTypes) to High(aTypes) do
ListTypes.Items.Add (
ConvTypeToDescription (aTypes[i]));
// copy items to the second list
ListTypes2.Items := ListTypes.Items;
// select first of each list
ListTypes.ItemIndex := 0;
ListTypes2.ItemIndex := 0;
end;
{$IFDEF CLR}
constructor TForm1.Create(AOwner: TComponent);
begin
inherited;
InitializeControls;
FormCreate (self);
end;
{$ENDIF}
{$IFDEF CLR}
procedure TForm1.InitializeControls;
begin
// Initalizing all controls...
Label1:= TLabel.Create(Self);
Label2:= TLabel.Create(Self);
Button1:= TButton.Create(Self);
EditValue:= TEdit.Create(Self);
EditResult:= TEdit.Create(Self);
ListTypes:= TListBox.Create(Self);
ListTypes2:= TListBox.Create(Self);
// Form's PMEs'
Left:= 195;
Top:= 108;
Width:= 414;
Height:= 250;
Caption:= 'Euro Conversion';
Color:= clBtnFace;
Font.Charset:= DEFAULT_CHARSET;
Font.Color:= clWindowText;
Font.Height:= -11;
Font.Name:= 'MS Sans Serif';
Font.Style:= [];
OnCreate:= FormCreate;
with Label1 do
begin
Parent:= Self;
Left:= 8;
Top:= 196;
Width:= 30;
Height:= 13;
Caption:= 'Value:';
end;
with Label2 do
begin
Parent:= Self;
Left:= 214;
Top:= 196;
Width:= 33;
Height:= 13;
Caption:= 'Result:';
end;
with Button1 do
begin
Parent:= Self;
Left:= 168;
Top:= 8;
Width:= 75;
Height:= 177;
Caption:= 'Convert';
TabOrder:= 0;
OnClick:= Button1Click;
end;
with EditValue do
begin
Parent:= Self;
Left:= 40;
Top:= 192;
Width:= 145;
Height:= 21;
TabOrder:= 1;
Text:= '120';
end;
with EditResult do
begin
Parent:= Self;
Left:= 256;
Top:= 192;
Width:= 145;
Height:= 21;
TabOrder:= 2;
end;
with ListTypes do
begin
Parent:= Self;
Left:= 8;
Top:= 8;
Width:= 153;
Height:= 177;
ItemHeight:= 13;
TabOrder:= 3;
end;
with ListTypes2 do
begin
Parent:= Self;
Left:= 248;
Top:= 5;
Width:= 153;
Height:= 180;
ItemHeight:= 13;
TabOrder:= 4;
end;
end;
{$ENDIF}
end.
|
unit DAO.ExtratosExpressas;
interface
uses FireDAC.Comp.Client, DAO.Conexao, Control.Sistema, System.DateUtils, System.Classes, Model.ExtratosExpressas;
type
TExtratosExpressasDAO = class
private
FConexao : TConexao;
public
constructor Create;
function GetID(): Integer;
function Insert(aExtrato: TExtratosExpressas): Boolean;
function Update(aExtrato: TExtratosExpressas): Boolean;
function Delete(aExtrato: TExtratosExpressas): Boolean;
function CancelaExtrato(aParam: array of Variant): Boolean;
function FindExtrato(aParam: array of Variant): TFDQuery;
function DatasPagamentos(iBase: Integer): TStringList;
end;
const
TABLENAME = 'fin_extrato_expressas';
implementation
uses System.SysUtils, Data.DB;
{ TExtratosExpressasDAO }
function TExtratosExpressasDAO.CancelaExtrato(aParam: array of Variant): Boolean;
var
sSQL : String;
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE DAT_INICIO <= :DATA1 AND DAT_FINAL <= :DATA2 AND DOM_FECHADO = :FECHADO';
FDQuery.ExecSQL(sSQL,[aParam[0], aParam[1], aParam[2]]);
Result := True;
finally
FDQuery.Free;
end;
end;
constructor TExtratosExpressasDAO.Create;
begin
FConexao := TSistemaControl.GetInstance().Conexao;
end;
function TExtratosExpressasDAO.DatasPagamentos(iBase: Integer): TStringList;
var
sSQL : String;
FDQuery : TFDQuery;
sLista: TStringList;
begin
try
sLista := TStringList.Create;
FDQuery := FConexao.ReturnQuery;
sSQL := 'select distinct(dat_pagamento) from ' + TABLENAME + ' where cod_agente = :base and dom_fechado = :fechado order by dat_pagamento desc';
FDQuery.SQL.Add(sSQL);
FDQuery.ParamByName('base').AsInteger := iBase;
FDQuery.ParamByName('fechado').AsInteger := 1;
FDQuery.Open();
if not FDQuery.IsEmpty then FDQuery.First;
while not FDQuery.Eof do
begin
sLista.Add(FormatDateTime('dd/mm/yyyy', FDQuery.Fields[0].Value));
FDQuery.Next;
end;
Result := sLista;
finally
FDQuery.Free;
end;
end;
function TExtratosExpressasDAO.Delete(aExtrato: TExtratosExpressas): Boolean;
var
sSQL : String;
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE ID_EXTRATO = :ID';
FDQuery.ExecSQL(sSQL,[aExtrato.Id]);
Result := True;
finally
FDQuery.Free;
end;
end;
function TExtratosExpressasDAO.FindExtrato(aParam: array of Variant): TFDQuery;
var
FdQuery : TFDQuery;
begin
FdQuery := FConexao.ReturnQuery;
if Length(aParam) = 0 then Exit;
FdQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FdQuery.SQL.Add('WHERE ID_EXTRATO = :ID');
FdQuery.ParamByName('ID').AsInteger := aParam[1];
end
else if aParam[0] = 'AGENTE' then
begin
FdQuery.SQL.Add('WHERE COD_AGENTE = :AGENTE');
FdQuery.ParamByName('AGENTE').AsInteger := aParam[1];
end
else if aParam[0] = 'ENTREGADOR' then
begin
FdQuery.SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR');
FdQuery.ParamByName('ENTREGADOR').AsInteger := aParam[1];
end
else if aParam[0] = 'EXTRATO' then
begin
FdQuery.SQL.Add('WHERE num_extrato = :extrato');
FdQuery.ParamByName('extrato').AsString := aParam[1];
end
else if aParam[0] = 'REFERENCIA' then
begin
FdQuery.SQL.Add('WHERE DAT_INICIO >= :INICIO AND DAT_FINAL <= :FINAL AND COD_ENTREGADOR = :ENTREGADOR');
FdQuery.ParamByName('INICIO').AsDate := aParam[1];
FdQuery.ParamByName('FINAL').AsDate := aParam[2];
FdQuery.ParamByName('ENTREGADOR').AsInteger := aParam[3];
end
else if aParam[0] = 'CLIENTE' then
begin
FdQuery.SQL.Add('WHERE DAT_INICIO >= :INICIO AND DAT_FINAL <= :FINAL AND COD_CLIENTE_EMPRESA = :CLIENTE');
FdQuery.ParamByName('INICIO').AsDate := aParam[1];
FdQuery.ParamByName('FINAL').AsDate := aParam[2];
FdQuery.ParamByName('CLIENTE').AsInteger := aParam[3];
end
else if aParam[0] = 'REFERENCIAAG' then
begin
FdQuery.SQL.Add('WHERE DAT_INICIO >= :INICIO AND DAT_FINAL <= :FINAL AND COD_AGENTE = :AGENTE');
FdQuery.ParamByName('INICIO').AsDate := aParam[1];
FdQuery.ParamByName('FINAL').AsDate := aParam[2];
FdQuery.ParamByName('AGENTE').AsInteger := aParam[3];
end
else if aParam[0] = 'DATA' then
begin
FdQuery.SQL.Add('WHERE DAT_INICIO >= :INICIO AND DAT_FINAL <= :FINAL');
FdQuery.ParamByName('INICIO').AsDate := aParam[1];
FdQuery.ParamByName('FINAL').AsDate := aParam[2];
end
else if aParam[0] = 'PGTOAGENTE' then
begin
FdQuery.SQL.Add('WHERE DAT_PAGAMENTO = :DATA AND COD_AGENTE = :AGENTE AND DOM_FECHADO = 1');
FdQuery.ParamByName('DATA').AsDate := aParam[1];
FdQuery.ParamByName('AGENTE').AsInteger := aParam[2];
end
else if aParam[0] = 'PERIODO' then
begin
FdQuery.SQL.Add('WHERE DAT_INICIO >= :INICIO AND DAT_FINAL <= :FINAL AND DOM_FECHADO = :FECHADO');
FdQuery.ParamByName('INICIO').AsDate := aParam[1];
FdQuery.ParamByName('FINAL').AsDate := aParam[2];
FdQuery.ParamByName('FECHADO').AsInteger := aParam[3];
end
else if aParam[0] = 'PAGAMENTO' then
begin
if Length(aParam) = 2 then
begin
FdQuery.SQL.Add('WHERE DAT_PAGAMENTO BETWEEN :INICIO AND :FINAL AND DOM_FECHADO = :FECHADO');
FdQuery.ParamByName('INICIO').AsDate := aParam[1];
FdQuery.ParamByName('FINAL').AsDate := aParam[2];
FdQuery.ParamByName('FECHADO').AsInteger := 1;
end
else
begin
FdQuery.SQL.Add('WHERE DAT_PAGAMENTO = :DATA');
FdQuery.ParamByName('DATA').AsDate := aParam[1];
end;
end
else if aParam[0] = 'FILTRO' then
begin
FdQuery.SQL.Add('WHERE ' + aParam[1]);
end;
FdQuery.Open();
Result := FDQuery;
end;
function TExtratosExpressasDAO.GetID: Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(ID_EXTRATO),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Free;
end;
end;
function TExtratosExpressasDAO.Insert(aExtrato: TExtratosExpressas): Boolean;
var
sSQL: String;
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
aExtrato.Id := GetID();
sSQL := 'INSERT INTO ' + TABLENAME +
'(ID_EXTRATO, COD_AGENTE, COD_ENTREGADOR, DAT_INICIO, DAT_FINAL, DAT_PAGAMENTO, QTD_VOLUMES, QTD_ENTREGAS, QTD_ITENS_ATRASO, QTD_VOLUMES_EXTRA, ' +
'VAL_PERCENTUAL_SLA, VAL_VERBA, VAL_ENTREGAS, VAL_VOLUMES_EXTRA, VAL_PRODUCAO, VAL_CREDITOS, VAL_RESTRICAO, VAL_EXTRAVIOS, VAL_DEBITOS, VAL_TOTAL_CREDITOS, ' +
'VAL_TOTAL_DEBITOS, VAL_TOTAL_GERAL, DOM_FECHADO, TOT_VERBA_FRANQUIA, QTD_PFP, DES_LOG, num_extrato, nom_agente, nom_entregador) ' +
'VALUE ' +
'(:PID_EXTRATO, :PCOD_AGENTE, :PCOD_ENTREGADOR, :PDAT_INICIO, :PDAT_FINAL, :PDAT_PAGAMENTO, :PQTD_VOLUMES, :PQTD_ENTREGAS, :PQTD_ITENS_ATRASO, ' +
':PQTD_VOLUMES_EXTRA, :PVAL_PERCENTUAL_SLA, :PVAL_VERBA, :PVAL_ENTREGAS, :PVAL_VOLUMES_EXTRA, :PVAL_PRODUCAO, :PVAL_CREDITOS, :PVAL_RESTRICAO, :PVAL_EXTRAVIOS, ' +
':PVAL_DEBITOS, :PVAL_TOTAL_CREDITOS, :PVAL_TOTAL_DEBITOS, :PVAL_TOTAL_GERAL, :PDOM_FECHADO, :PTOT_VERBA_FRANQUIA, :PQTD_PFP, :PDES_LOG, :num_extrato, '+
':nom_agente, :nom_entregador)';
FDQuery.ExecSQL(sSQL, [aExtrato.Id, aExtrato.Agente, aExtrato.Entregador, aExtrato.DataInicio, aExtrato.DataFinal, aExtrato.DataPagamento,
aExtrato.Volumes, aExtrato.Entregas, aExtrato.Atrasos, aExtrato.VolumesExtra, aExtrato.SLA, aExtrato.Verba, aExtrato.ValorEntregas,
aExtrato.ValorVolumesExtra, aExtrato.ValorProducao, aExtrato.ValorCreditos, aExtrato.ValorRestricao, aExtrato.ValorExtravio, aExtrato.ValorDebitos,
aExtrato.ValorTotalCreditos, aExtrato.ValorTotalDebitos, aExtrato.ValorTotalGeral, aExtrato.Fechado, aExtrato.TotalVerbaFranquia, AeXTRATO.PFP,
aExtrato.Log, aExtrato.Extrato, aExtrato.NomeAgente, aExtrato.NomeEntregador]);
Result := True;
finally
FDQuery.Free;
end;
end;
function TExtratosExpressasDAO.Update(aExtrato: TExtratosExpressas): Boolean;
var
sSQL: String;
FDQuery : TFDQuery;
begin
Try
Result := False;
FDQuery := FConexao.ReturnQuery;
sSQL := 'UPDATE ' + TABLENAME + ' SET ' +
'COD_AGENTE = :PCOD_AGENTE, COD_ENTREGADOR = :PCOD_ENTREGADOR, DAT_INICIO = :PDAT_INICIO, DAT_FINAL = :PDAT_FINAL, DAT_PAGAMENTO = :PDAT_PAGAMENTO, ' +
'QTD_VOLUMES = :PQTD_VOLUMES, QTD_ENTREGAS = :PQTD_ENTREGAS, QTD_ITENS_ATRASO = :PQTD_ITENS_ATRASO, QTD_VOLUMES_EXTRA = :PQTD_VOLUMES_EXTRA, ' +
'VAL_PERCENTUAL_SLA = :PVAL_PERCENTUAL_SLA, VAL_VERBA = :PVAL_VERBA, VAL_ENTREGAS = :PVAL_ENTREGAS, VAL_VOLUMES_EXTRA = :PVAL_VOLUMES_EXTRA, ' +
'VAL_PRODUCAO = :PVAL_PRODUCAO, VAL_CREDITOS = :PVAL_CREDITOS, VAL_RESTRICAO = :PVAL_RESTRICAO, VAL_EXTRAVIOS = :PVAL_EXTRAVIOS, ' +
'VAL_DEBITOS = :PVAL_DEBITOS, VAL_TOTAL_CREDITOS = :PVAL_TOTAL_CREDITOS, VAL_TOTAL_DEBITOS = :PVAL_TOTAL_DEBITOS, VAL_TOTAL_GERAL = :PVAL_TOTAL_GERAL, ' +
'DOM_FECHADO = :PDOM_FECHADO, TOT_VERBA_FRANQUIA = :PTOT_VERBA_FRANQUIA, QTD_PFP = :pQTD_PFP, DES_LOG = :PDES_LOG, num_extrato = :num_extrato, ' +
'nom_agente = :nom_agente, nom_entregador = :nom_entregador' +
'WHERE ID_EXTRATO = :PID_EXTRATO';
FDQuery.ExecSQL(sSQL,[aExtrato.Agente, aExtrato.Entregador, aExtrato.DataInicio, aExtrato.DataFinal, aExtrato.DataPagamento,
aExtrato.Volumes, aExtrato.Entregas, aExtrato.Atrasos, aExtrato.VolumesExtra, aExtrato.SLA, aExtrato.Verba, aExtrato.ValorEntregas,
aExtrato.ValorVolumesExtra, aExtrato.ValorProducao, aExtrato.ValorCreditos, aExtrato.ValorRestricao, aExtrato.ValorExtravio, aExtrato.ValorDebitos,
aExtrato.ValorTotalCreditos, aExtrato.ValorTotalDebitos, aExtrato.ValorTotalGeral, aExtrato.Fechado, aExtrato.TotalVerbaFranquia, aExtrato.PFP, aExtrato.Log,
aExtrato.Extrato, aExtrato.NomeAgente, aExtrato.NomeEntregador, aExtrato.Id]);
Result := True;
Finally
FDQuery.Free;
End;
end;
end.
|
unit Unbound.Shaders;
interface
uses
Pengine.Vector,
Pengine.Color,
Pengine.GLProgram,
Pengine.Skybox;
type
TSkyboxShader = class(TSkyboxGLProgramBase)
protected
class procedure GetData(out AName: string; out AResource: Boolean); override;
end;
TTerrainShader = class(TGLProgramResource)
public type
TData = packed record
Pos: TVector3;
Color: TColorRGB;
end;
protected
class function GetAttributeOrder: TGLProgram.TAttributeOrder; override;
class procedure GetData(out AName: string; out AResource: Boolean); override;
end;
TDesignShader = class(TGLProgramResource)
protected
class function GetAttributeOrder: TGLProgram.TAttributeOrder; override;
class procedure GetData(out AName: string; out AResource: Boolean); override;
end;
TEntityShader = class(TGLProgramResource)
protected
class function GetAttributeOrder: TGLProgram.TAttributeOrder; override;
class procedure GetData(out AName: string; out AResource: Boolean); override;
end;
implementation
{ TSkyboxShader }
class procedure TSkyboxShader.GetData(out AName: string; out AResource: Boolean);
begin
AResource := False;
if AResource then
AName := 'SKYBOX'
else
AName := 'Data/Shader/skybox';
end;
{ TTerrainShader }
class function TTerrainShader.GetAttributeOrder: TGLProgram.TAttributeOrder;
begin
Result := [
'vpos',
'vcolor'
];
end;
class procedure TTerrainShader.GetData(out AName: string; out AResource: Boolean);
begin
AResource := False;
if AResource then
AName := 'TERRAIN'
else
AName := 'Data/Shader/terrain';
end;
{ TDesignShader }
class function TDesignShader.GetAttributeOrder: TGLProgram.TAttributeOrder;
begin
Result := [];
end;
class procedure TDesignShader.GetData(out AName: string; out AResource: Boolean);
begin
AResource := False;
if AResource then
AName := 'DESIGN'
else
AName := 'Data/Shader/design';
end;
{ TEntityShader }
class function TEntityShader.GetAttributeOrder: TGLProgram.TAttributeOrder;
begin
Result := [];
end;
class procedure TEntityShader.GetData(out AName: string; out AResource: Boolean);
begin
AResource := False;
if AResource then
AName := 'ENTITY'
else
AName := 'Data/Shader/entity';
end;
end.
|
unit App;
{ Based on 016_cartoon_torus.cpp example from oglplus (http://oglplus.org/) }
{$INCLUDE 'Sample.inc'}
interface
uses
System.Classes,
Neslib.Ooogles,
Neslib.FastMath,
Sample.App,
Sample.Geometry;
type
TCartoonTorusApp = class(TApplication)
private
FProgram: TGLProgram;
FVerts: TGLBuffer;
FNormals: TGLBuffer;
FIndices: TGLBuffer;
FUniProjectionMatrix: TGLUniform;
FUniCameraMatrix: TGLUniform;
FUniModelMatrix: TGLUniform;
FTorus: TTorusGeometry;
public
procedure Initialize; override;
procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override;
procedure Shutdown; override;
procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override;
procedure Resize(const AWidth, AHeight: Integer); override;
end;
implementation
uses
{$INCLUDE 'OpenGL.inc'}
System.UITypes,
Sample.Math;
{ TCartoonTorusApp }
procedure TCartoonTorusApp.Initialize;
var
VertexShader, FragmentShader: TGLShader;
VertAttr: TGLVertexAttrib;
Uniform: TGLUniform;
begin
VertexShader.New(TGLShaderType.Vertex,
'uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;'#10+
'attribute vec3 Position;'#10+
'attribute vec3 Normal;'#10+
'varying vec3 vertNormal;'#10+
'void main(void)'#10+
'{'#10+
' vertNormal = mat3(ModelMatrix) * Normal;'#10+
' gl_Position = '#10+
' ProjectionMatrix *'#10+
' CameraMatrix *'#10+
' ModelMatrix *'#10+
' vec4(Position, 1.0);'#10+
'}');
VertexShader.Compile;
FragmentShader.New(TGLShaderType.Fragment,
'precision mediump float;'#10+
'varying vec3 vertNormal;'#10+
'uniform vec3 LightPos;'#10+
'void main(void)'#10+
'{'#10+
' float intensity = 2.0 * max('#10+
' dot(vertNormal, LightPos)/'#10+
' length(LightPos),'#10+
' 0.0);'#10+
' if (!gl_FrontFacing)'#10+
' {'#10+
' gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);'#10+
' }'#10+
' else if (intensity > 0.9)'#10+
' {'#10+
' gl_FragColor = vec4(1.0, 0.9, 0.8, 1.0);'#10+
' }'#10+
' else if (intensity > 0.1)'#10+
' {'#10+
' gl_FragColor = vec4(0.7, 0.6, 0.4, 1.0);'#10+
' }'#10+
' else'#10+
' {'#10+
' gl_FragColor = vec4(0.3, 0.2, 0.1, 1.0);'#10+
' }'#10+
'}');
FragmentShader.Compile;
FProgram.New(VertexShader, FragmentShader);
FProgram.Link;
VertexShader.Delete;
FragmentShader.Delete;
FProgram.Use;
FTorus.Generate(72, 48, 1.0, 0.5);
{ Positions }
FVerts.New(TGLBufferType.Vertex);
FVerts.Bind;
FVerts.Data<TVector3>(FTorus.Positions);
VertAttr.Init(FProgram, 'Position');
VertAttr.SetConfig<TVector3>;
VertAttr.Enable;
{ Normals }
FNormals.New(TGLBufferType.Vertex);
FNormals.Bind;
FNormals.Data<TVector3>(FTorus.Normals);
VertAttr.Init(FProgram, 'Normal');
VertAttr.SetConfig<TVector3>;
VertAttr.Enable;
{ Indices }
FIndices.New(TGLBufferType.Index);
FIndices.Bind;
FIndices.Data<UInt16>(FTorus.Indices);
{ Don't need data anymore }
FTorus.Clear;
{ Uniforms }
Uniform.Init(FProgram, 'LightPos');
Uniform.SetValue(4.0, 4.0, -8.0);
FUniProjectionMatrix.Init(FProgram, 'ProjectionMatrix');
FUniCameraMatrix.Init(FProgram, 'CameraMatrix');
FUniModelMatrix.Init(FProgram, 'ModelMatrix');
gl.ClearColor(0.8, 0.8, 0.7, 0);
gl.ClearDepth(1);
gl.Enable(TGLCapability.DepthTest);
gl.Enable(TGLCapability.CullFace);
gl.FrontFace(TGLFaceOrientation.CounterClockwise);
gl.CullFace(TGLFace.Back);
end;
procedure TCartoonTorusApp.KeyDown(const AKey: Integer; const AShift: TShiftState);
begin
{ Terminate app when Esc key is pressed }
if (AKey = vkEscape) then
Terminate;
end;
procedure TCartoonTorusApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double);
var
RotationX, RotationY, CameraMatrix, ModelMatrix: TMatrix4;
begin
{ Clear the color and depth buffer }
gl.Clear([TGLClear.Color, TGLClear.Depth]);
{ Use the program }
FProgram.Use;
{ Set the matrix for camera orbiting the origin }
OrbitCameraMatrix(TVector3.Zero, 3.5, Radians(ATotalTimeSec * 35),
Radians(FastSin(Pi * ATotalTimeSec / 10) * 60), CameraMatrix);
FUniCameraMatrix.SetValue(CameraMatrix);
{ Update and render the torus }
RotationY.InitRotationY(ATotalTimeSec * Pi * 0.5);
RotationX.InitRotationX(Pi * 0.5);
ModelMatrix := RotationY * RotationX;
FUniModelMatrix.SetValue(ModelMatrix);
FTorus.DrawWithBoundIndexBuffer;
end;
procedure TCartoonTorusApp.Resize(const AWidth, AHeight: Integer);
var
ProjectionMatrix: TMatrix4;
begin
inherited;
ProjectionMatrix.InitPerspectiveFovRH(Radians(70), AWidth / AHeight, 1, 30);
FProgram.Use;
FUniProjectionMatrix.SetValue(ProjectionMatrix);
end;
procedure TCartoonTorusApp.Shutdown;
begin
{ Release resources }
FIndices.Delete;
FNormals.Delete;
FVerts.Delete;
FProgram.Delete;
end;
end.
|
{
* CGDirectDisplay.h
* CoreGraphics
*
* Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
*
}
{ Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, August 2005 }
{
Modified for use with Free Pascal
Version 210
Please report any bugs to <gpc@microbizz.nl>
}
{$mode macpas}
{$packenum 1}
{$macro on}
{$inline on}
{$calling mwpascal}
unit CGDirectDisplay;
interface
{$setc UNIVERSAL_INTERFACES_VERSION := $0342}
{$setc GAP_INTERFACES_VERSION := $0210}
{$ifc not defined USE_CFSTR_CONSTANT_MACROS}
{$setc USE_CFSTR_CONSTANT_MACROS := TRUE}
{$endc}
{$ifc defined CPUPOWERPC and defined CPUI386}
{$error Conflicting initial definitions for CPUPOWERPC and CPUI386}
{$endc}
{$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN}
{$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN}
{$endc}
{$ifc not defined __ppc__ and defined CPUPOWERPC}
{$setc __ppc__ := 1}
{$elsec}
{$setc __ppc__ := 0}
{$endc}
{$ifc not defined __i386__ and defined CPUI386}
{$setc __i386__ := 1}
{$elsec}
{$setc __i386__ := 0}
{$endc}
{$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__}
{$error Conflicting definitions for __ppc__ and __i386__}
{$endc}
{$ifc defined __ppc__ and __ppc__}
{$setc TARGET_CPU_PPC := TRUE}
{$setc TARGET_CPU_X86 := FALSE}
{$elifc defined __i386__ and __i386__}
{$setc TARGET_CPU_PPC := FALSE}
{$setc TARGET_CPU_X86 := TRUE}
{$elsec}
{$error Neither __ppc__ nor __i386__ is defined.}
{$endc}
{$setc TARGET_CPU_PPC_64 := FALSE}
{$ifc defined FPC_BIG_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := TRUE}
{$setc TARGET_RT_LITTLE_ENDIAN := FALSE}
{$elifc defined FPC_LITTLE_ENDIAN}
{$setc TARGET_RT_BIG_ENDIAN := FALSE}
{$setc TARGET_RT_LITTLE_ENDIAN := TRUE}
{$elsec}
{$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.}
{$endc}
{$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE}
{$setc CALL_NOT_IN_CARBON := FALSE}
{$setc OLDROUTINENAMES := FALSE}
{$setc OPAQUE_TOOLBOX_STRUCTS := TRUE}
{$setc OPAQUE_UPP_TYPES := TRUE}
{$setc OTCARBONAPPLICATION := TRUE}
{$setc OTKERNEL := FALSE}
{$setc PM_USE_SESSION_APIS := TRUE}
{$setc TARGET_API_MAC_CARBON := TRUE}
{$setc TARGET_API_MAC_OS8 := FALSE}
{$setc TARGET_API_MAC_OSX := TRUE}
{$setc TARGET_CARBON := TRUE}
{$setc TARGET_CPU_68K := FALSE}
{$setc TARGET_CPU_MIPS := FALSE}
{$setc TARGET_CPU_SPARC := FALSE}
{$setc TARGET_OS_MAC := TRUE}
{$setc TARGET_OS_UNIX := FALSE}
{$setc TARGET_OS_WIN32 := FALSE}
{$setc TARGET_RT_MAC_68881 := FALSE}
{$setc TARGET_RT_MAC_CFM := FALSE}
{$setc TARGET_RT_MAC_MACHO := TRUE}
{$setc TYPED_FUNCTION_POINTERS := TRUE}
{$setc TYPE_BOOL := FALSE}
{$setc TYPE_EXTENDED := FALSE}
{$setc TYPE_LONGLONG := TRUE}
uses MacTypes,CFBase,CFArray,CFDictionary,CGContext,CGBase,CGGeometry,CGErrors;
{$ALIGN POWER}
{
* The following construct is present to avoid problems with some Apple tools.
* API in this module is not available in Mac OS Classic variations!
}
type
CGDirectDisplayID = ^SInt32; { an opaque 32-bit type }
CGDirectDisplayIDPtr = ^CGDirectDisplayID; { when a var xx:CGDirectDisplayID parameter can be nil, it is changed to xx: CGDirectDisplayIDPtr }
type
CGDirectPaletteRef = ^SInt32; { an opaque 32-bit type }
CGDirectPaletteRefPtr = ^CGDirectPaletteRef; { when a var xx:CGDirectPaletteRef parameter can be nil, it is changed to xx: CGDirectPaletteRefPtr }
type
CGDisplayCount = UInt32;
type
CGTableCount = UInt32;
type
CGDisplayCoord = SInt32;
type
CGByteValue = SInt8;
CGByteValuePtr = ^CGByteValue;
type
CGOpenGLDisplayMask = UInt32;
type
CGBeamPosition = UInt32;
type
CGMouseDelta = SInt32;
type
CGRefreshRate = double;
type
CGCaptureOptions = UInt32;
type
CGDisplayErr = CGError;
const
CGDisplayNoErr = kCGErrorSuccess;
kCGDirectMainDisplay = nil;
{ Returns the display ID of the current main display }
function CGMainDisplayID: CGDirectDisplayID; external name '_CGMainDisplayID';
{
* Mechanisms used to find screen IDs
* An array length (maxDisplays) and array of CGDirectDisplayIDs are passed in.
* Up to maxDisplays of the array are filled in with the displays meeting the
* specified criteria. The actual number of displays filled in is returned in
* dspyCnt.
*
* If the dspys array is NULL, maxDisplays is ignored, and *dspyCnt is filled
* in with the number of displays meeting the function's requirements.
}
function CGGetDisplaysWithPoint( point: CGPoint; maxDisplays: CGDisplayCount; dspys: CGDirectDisplayIDPtr; var dspyCnt: CGDisplayCount ): CGDisplayErr; external name '_CGGetDisplaysWithPoint';
function CGGetDisplaysWithRect( rect: CGRect; maxDisplays: CGDisplayCount; dspys: CGDirectDisplayIDPtr; var dspyCnt: CGDisplayCount ): CGDisplayErr; external name '_CGGetDisplaysWithRect';
function CGGetDisplaysWithOpenGLDisplayMask( mask: CGOpenGLDisplayMask; maxDisplays: CGDisplayCount; dspys: CGDirectDisplayIDPtr; var dspyCnt: CGDisplayCount ): CGDisplayErr; external name '_CGGetDisplaysWithOpenGLDisplayMask';
{
* Get lists of displays. Use this to determine display IDs
*
* If the activeDspys array is NULL, maxDisplays is ignored, and *dspyCnt is filled
* in with the number of displays meeting the function's requirements.
*
* The first display returned in the list is the main display,
* the one with the menu bar.
* When mirroring, this will be the largest drawable display in the mirror,
* set, or if all are the same size, the one with the deepest pixel depth.
}
function CGGetActiveDisplayList( maxDisplays: CGDisplayCount; activeDspys: CGDirectDisplayIDPtr; var dspyCnt: CGDisplayCount ): CGDisplayErr; external name '_CGGetActiveDisplayList';
{
* With hardware mirroring, a display may be on-line,
* but not necessarily active, or drawable.
* Programs which manipulate display settings such as the
* palette or gamma tables need access to all displays in use,
* including hardware mirrors which are not drawable.
}
function CGGetOnlineDisplayList( maxDisplays: CGDisplayCount; onlineDspys: CGDirectDisplayIDPtr; var dspyCnt: CGDisplayCount ): CGDisplayErr; external name '_CGGetOnlineDisplayList';
{ Map a display to an OpenGL display mask; returns 0 on invalid display }
function CGDisplayIDToOpenGLDisplayMask( display: CGDirectDisplayID ): CGOpenGLDisplayMask; external name '_CGDisplayIDToOpenGLDisplayMask';
{
* Map an OpenGL display mask to a display.
* Returns kCGNullDirectDisplay if a bit doesn't
* match a display.
* Passing in multiple bits results in an arbitrary match.
}
function CGOpenGLDisplayMaskToDisplayID( mask: CGOpenGLDisplayMask ): CGDirectDisplayID; external name '_CGOpenGLDisplayMaskToDisplayID';
{ Return screen size and origin in global coords; Empty rect if display is invalid }
function CGDisplayBounds( display: CGDirectDisplayID ): CGRect; external name '_CGDisplayBounds';
function CGDisplayPixelsWide( display: CGDirectDisplayID ): size_t; external name '_CGDisplayPixelsWide';
function CGDisplayPixelsHigh( display: CGDirectDisplayID ): size_t; external name '_CGDisplayPixelsHigh';
{
* Display mode selection
* Display modes are represented as CFDictionaries
* All dictionaries and arrays returned via these mechanisms are
* owned by the framework and should not be released. The framework
* will not release them out from under your application.
*
* Values associated with the following keys are CFNumber types.
* With CFNumberGetValue(), use kCFNumberLongType for best results.
* kCGDisplayRefreshRate encodes a double value, so to get the fractional
* refresh rate use kCFNumberDoubleType.
}
{
* Keys used in mode dictionaries. Source C strings shown won't change.
* Some CFM environments cannot import data variables, and so
* the definitions are provided directly.
*
* These keys are used only within the scope of the mode dictionaries,
* so further uniquing, as by prefix, of the source string is not needed.
}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayWidth CFSTRP('Width')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayHeight CFSTRP('Height')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayMode CFSTRP('Mode')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayBitsPerPixel CFSTRP('BitsPerPixel')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayBitsPerSample CFSTRP('BitsPerSample')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplaySamplesPerPixel CFSTRP('SamplesPerPixel')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayRefreshRate CFSTRP('RefreshRate')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayModeUsableForDesktopGUI CFSTRP('UsableForDesktopGUI')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayIOFlags CFSTRP('IOFlags')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayBytesPerRow CFSTRP('kCGDisplayBytesPerRow')}
{$endc}
{
* Keys to describe optional properties of display modes.
*
* The key will only be present if the property applies,
* and will be associated with a value of kCFBooleanTrue.
* Keys not relevant to a particular display mode will not
* appear in the mode dictionary.
*
* These strings must remain unchanged in future releases, of course.
}
{ Set if display mode doesn't need a confirmation dialog to be set }
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayModeIsSafeForHardware CFSTRP('kCGDisplayModeIsSafeForHardware')}
{$endc}
{ The following keys reflect interesting bits of the IOKit display mode flags }
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayModeIsInterlaced CFSTRP('kCGDisplayModeIsInterlaced')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayModeIsStretched CFSTRP('kCGDisplayModeIsStretched')}
{$endc}
{$ifc USE_CFSTR_CONSTANT_MACROS}
{$definec kCGDisplayModeIsTelevisionOutput CFSTRP('kCGDisplayModeIsTelevisionOutput')}
{$endc}
{
* Return a CFArray of CFDictionaries describing all display modes.
* Returns NULL if the display is invalid.
}
function CGDisplayAvailableModes( display: CGDirectDisplayID ): CFArrayRef; external name '_CGDisplayAvailableModes';
{
* Try to find a display mode of specified depth with dimensions equal or greater than
* specified.
* If no depth match is found, try for the next larger depth with dimensions equal or greater
* than specified. If no luck, then just return the current mode.
*
* exactmatch, if not NULL, is set to 'true' if an exact match in width, height, and depth is found,
* and 'false' otherwise.
*
* CGDisplayBestModeForParametersAndRefreshRateWithProperty searches the list, looking for
* display modes with the specified property. The property should be one of:
* kCGDisplayModeIsSafeForHardware;
* kCGDisplayModeIsInterlaced;
* kCGDisplayModeIsStretched;
* kCGDisplayModeIsTelevisionOutput
*
* Returns NULL if display is invalid.
}
function CGDisplayBestModeForParameters( display: CGDirectDisplayID; bitsPerPixel: size_t; width: size_t; height: size_t; var exactMatch: boolean_t ): CFDictionaryRef; external name '_CGDisplayBestModeForParameters';
function CGDisplayBestModeForParametersAndRefreshRate( display: CGDirectDisplayID; bitsPerPixel: size_t; width: size_t; height: size_t; refresh: CGRefreshRate; var exactMatch: boolean_t ): CFDictionaryRef; external name '_CGDisplayBestModeForParametersAndRefreshRate';
function CGDisplayBestModeForParametersAndRefreshRateWithProperty( display: CGDirectDisplayID; bitsPerPixel: size_t; width: size_t; height: size_t; refresh: CGRefreshRate; property: CFStringRef; var exactMatch: boolean_t ): CFDictionaryRef; external name '_CGDisplayBestModeForParametersAndRefreshRateWithProperty';
{
* Return a CFDictionary describing the current display mode.
* Returns NULL if display is invalid.
}
function CGDisplayCurrentMode( display: CGDirectDisplayID ): CFDictionaryRef; external name '_CGDisplayCurrentMode';
{
* Switch display mode. Note that after switching,
* display parameters and addresses may change.
* The selected display mode persists for the life of the program, and automatically
* reverts to the permanent setting made by Preferences when the program terminates.
* The mode dictionary passed in must be a dictionary vended by other CGDirectDisplay
* APIs such as CGDisplayBestModeForParameters() and CGDisplayAvailableModes().
*
* The mode dictionary passed in must be a dictionary vended by other CGDirectDisplay
* APIs such as CGDisplayBestModeForParameters() and CGDisplayAvailableModes().
*
* When changing display modes of displays in a mirroring set, other displays in
* the mirroring set will be set to a display mode capable of mirroring the bounds
* of the largest display being explicitly set.
}
function CGDisplaySwitchToMode( display: CGDirectDisplayID; mode: CFDictionaryRef ): CGDisplayErr; external name '_CGDisplaySwitchToMode';
{ Query parameters for current mode }
function CGDisplayBitsPerPixel( display: CGDirectDisplayID ): size_t; external name '_CGDisplayBitsPerPixel';
function CGDisplayBitsPerSample( display: CGDirectDisplayID ): size_t; external name '_CGDisplayBitsPerSample';
function CGDisplaySamplesPerPixel( display: CGDirectDisplayID ): size_t; external name '_CGDisplaySamplesPerPixel';
function CGDisplayBytesPerRow( display: CGDirectDisplayID ): size_t; external name '_CGDisplayBytesPerRow';
{
* Set a display gamma/transfer function from a formula specifying
* min and max values and a gamma for each channel.
* Gamma values must be greater than 0.0.
* To get an antigamma of 1.6, one would specify a value of (1.0 / 1.6)
* Min values must be greater than or equal to 0.0 and less than 1.0.
* Max values must be greater than 0.0 and less than or equal to 1.0.
* Out of range values, or Max greater than or equal to Min result
* in a kCGSRangeCheck error.
*
* Values are computed by sampling a function for a range of indices from 0 through 1:
* value = Min + ((Max - Min) * pow(index, Gamma))
* The resulting values are converted to a machine specific format
* and loaded into hardware.
}
type
CGGammaValue = Float32;
CGGammaValuePtr = ^CGGammaValue;
function CGSetDisplayTransferByFormula( display: CGDirectDisplayID; redMin: CGGammaValue; redMax: CGGammaValue; redGamma: CGGammaValue; greenMin: CGGammaValue; greenMax: CGGammaValue; greenGamma: CGGammaValue; blueMin: CGGammaValue; blueMax: CGGammaValue; blueGamma: CGGammaValue ): CGDisplayErr; external name '_CGSetDisplayTransferByFormula';
function CGGetDisplayTransferByFormula( display: CGDirectDisplayID; var redMin: CGGammaValue; var redMax: CGGammaValue; var redGamma: CGGammaValue; var greenMin: CGGammaValue; var greenMax: CGGammaValue; var greenGamma: CGGammaValue; var blueMin: CGGammaValue; var blueMax: CGGammaValue; var blueGamma: CGGammaValue ): CGDisplayErr; external name '_CGGetDisplayTransferByFormula';
{
* Returns the capacity, or nunber of entries, in the camma table for the specified
* display. If 'display' is invalid, returns 0.
}
function CGDisplayGammaTableCapacity( display: CGDirectDisplayID ): CGTableCount; external name '_CGDisplayGammaTableCapacity'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *)
{
* Set a display gamma/transfer function using tables of data for each channel.
* Values within each table should have values in the range of 0.0 through 1.0.
* The same table may be passed in for red, green, and blue channels. 'tableSize'
* indicates the number of entries in each table.
* The tables are interpolated as needed to generate the number of samples needed
* by hardware.
}
function CGSetDisplayTransferByTable( display: CGDirectDisplayID; tableSize: CGTableCount; redTable: {const} CGGammaValuePtr; greenTable: {const} CGGammaValuePtr; blueTable: {const} CGGammaValuePtr ): CGDisplayErr; external name '_CGSetDisplayTransferByTable';
{
* Get transfer tables. Capacity should contain the number of samples each
* array can hold, and *sampleCount is filled in with the number of samples
* actually copied in.
}
function CGGetDisplayTransferByTable( display: CGDirectDisplayID; capacity: CGTableCount; redTable: CGGammaValuePtr; greenTable: CGGammaValuePtr; blueTable: CGGammaValuePtr; var sampleCount: CGTableCount ): CGDisplayErr; external name '_CGGetDisplayTransferByTable';
{ As a convenience, allow setting of the gamma table by byte values }
function CGSetDisplayTransferByByteTable( display: CGDirectDisplayID; tableSize: CGTableCount; redTable: {const} CGByteValuePtr; greenTable: {const} CGByteValuePtr; blueTable: {const} CGByteValuePtr ): CGDisplayErr; external name '_CGSetDisplayTransferByByteTable';
{ Restore gamma tables of system displays to the user's ColorSync specified values }
procedure CGDisplayRestoreColorSyncSettings; external name '_CGDisplayRestoreColorSyncSettings';
{
* Options used with CGDisplayCaptureWithOptions and CGCaptureAllDisplaysWithOptions
}
const
kCGCaptureNoOptions = 0; { Default behavior }
kCGCaptureNoFill = 1 shl 0; { Disables fill with black on display capture }
{ Display capture and release }
function CGDisplayIsCaptured( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayIsCaptured';
function CGDisplayCapture( display: CGDirectDisplayID ): CGDisplayErr; external name '_CGDisplayCapture';
function CGDisplayCaptureWithOptions( display: CGDirectDisplayID; options: CGCaptureOptions ): CGDisplayErr; external name '_CGDisplayCaptureWithOptions'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *)
function CGDisplayRelease( display: CGDirectDisplayID ): CGDisplayErr; external name '_CGDisplayRelease';
{
* Capture all displays; this has the nice effect of providing an immersive
* environment, and preventing other apps from trying to adjust themselves
* to display changes only needed by your app.
}
function CGCaptureAllDisplays: CGDisplayErr; external name '_CGCaptureAllDisplays';
function CGCaptureAllDisplaysWithOptions( options: CGCaptureOptions ): CGDisplayErr; external name '_CGCaptureAllDisplaysWithOptions'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *)
{
* Release all captured displays, and restore the display modes to the
* user's preferences. May be used in conjunction with CGDisplayCapture()
* or CGCaptureAllDisplays().
}
function CGReleaseAllDisplays: CGDisplayErr; external name '_CGReleaseAllDisplays';
{
* Returns CoreGraphics raw shield window ID or NULL if not shielded
* This value may be used with drawing surface APIs.
}
function CGShieldingWindowID( display: CGDirectDisplayID ): UnivPtr; external name '_CGShieldingWindowID';
{
* Returns the window level used for the shield window.
* This value may be used with Cocoa windows to position the
* Cocoa window in the same window level as the shield window.
}
function CGShieldingWindowLevel: SInt32; external name '_CGShieldingWindowLevel';
{
* Returns base address of display or NULL for an invalid display.
* If the display has not been captured, the returned address may refer
* to read-only memory.
}
function CGDisplayBaseAddress( display: CGDirectDisplayID ): UnivPtr; external name '_CGDisplayBaseAddress';
{
* return address for X,Y in global coordinates;
* (0,0) represents the upper left corner of the main display.
* returns NULL for an invalid display or out of bounds coordinates
* If the display has not been captured, the returned address may refer
* to read-only memory.
}
function CGDisplayAddressForPosition( display: CGDirectDisplayID; x: CGDisplayCoord; y: CGDisplayCoord ): UnivPtr; external name '_CGDisplayAddressForPosition';
{ Mouse Cursor controls }
function CGDisplayHideCursor( display: CGDirectDisplayID ): CGDisplayErr; external name '_CGDisplayHideCursor'; { increments hide cursor count }
function CGDisplayShowCursor( display: CGDirectDisplayID ): CGDisplayErr; external name '_CGDisplayShowCursor'; { decrements hide cursor count }
{
* Move the cursor to the specified point relative to the display origin
* (the upper left corner of the display). Returns CGDisplayNoErr on success.
* No events are generated as a result of this move.
* Points that would lie outside the desktop are clipped to the desktop.
}
function CGDisplayMoveCursorToPoint( display: CGDirectDisplayID; point: CGPoint ): CGDisplayErr; external name '_CGDisplayMoveCursorToPoint';
{
* Report the mouse position change associated with the last mouse move event
* recieved by this application.
}
procedure CGGetLastMouseDelta( var deltaX: CGMouseDelta; var deltaY: CGMouseDelta ); external name '_CGGetLastMouseDelta';
{ Palette controls (8 bit pseudocolor only) }
{
* Returns TRUE if the current display mode supports palettes.
* Display must not be a hardware mirror of another, and should
* have a depth of 8 bits per pixel for this to return TRUE.
}
function CGDisplayCanSetPalette( display: CGDirectDisplayID ): boolean_t; external name '_CGDisplayCanSetPalette';
{
* Set a palette. The current gamma function is applied to the palette
* elements before being loaded into hardware. The display must not be
* a hardware mirror of another, and should have a depth of 8 bits per pixel.
* Setting the palette on the active, or primary display in a hardware
* mirroring set affects all displays in that set.
}
function CGDisplaySetPalette( display: CGDirectDisplayID; palette: CGDirectPaletteRef ): CGDisplayErr; external name '_CGDisplaySetPalette';
{
* Wait until the beam position is outside the range specified by upperScanLine and lowerScanLine.
* Note that if upperScanLine and lowerScanLine encompass the entire display height,
* the function returns an error.
* lowerScanLine must be greater than or equal to upperScanLine.
*
* Some display systems may not conventional video vertical and horizontal sweep in painting.
* These displays report a kCGDisplayRefreshRate of 0 in the CFDictionaryRef returned by
* CGDisplayCurrentMode(). On such displays, this function returns at once.
*
* Some drivers may not implement support for this mechanism.
* On such displays, this function returns at once.
*
* Returns CGDisplayNoErr on success, and an error if display or upperScanLine and
* lowerScanLine are invalid.
*
* The app should set the values of upperScanLine and lowerScanLine to allow enough lead time
* for the drawing operation to complete. A common strategy is to wait for the beam to pass
* the bottom of the drawing area, allowing almost a full vertical sweep period to perform drawing.
* To do this, set upperScanLine to 0, and set lowerScanLine to the bottom of the bounding box:
* lowerScanLine = (CGBeamPosition)(cgrect.origin.y + cgrect.size.height);
*
* IOKit may implement this as a spin-loop on the beam position call used for CGDisplayBeamPosition().
* On such system the function is CPU bound, and subject to all the usual scheduling pre-emption.
* In particular, attempting to wait for the beam to hit a specific scanline may be an exercise in frustration.
*
* These functions are advisary in nature, and depend on IOKit and hardware specific drivers to implement
* support. If you need extremely precise timing, or access to vertical blanking interrupts,
* you should consider writing a device driver to tie into hardware-specific capabilities.
}
function CGDisplayWaitForBeamPositionOutsideLines( display: CGDirectDisplayID; upperScanLine: CGBeamPosition; lowerScanLine: CGBeamPosition ): CGDisplayErr; external name '_CGDisplayWaitForBeamPositionOutsideLines';
{
* Returns the current beam position on the display. If display is invalid,
* or the display does not implement conventional video vertical and horizontal
* sweep in painting, or the driver does not implement this functionality, 0 is returned.
}
function CGDisplayBeamPosition( display: CGDirectDisplayID ): CGBeamPosition; external name '_CGDisplayBeamPosition';
{
* Obtain a CGContextRef suitable for drawing to a captured display.
*
* Returns a drawing context suitable for use on the display device.
* The context is owned by the device, and should not be released by
* the caller.
*
* The context remains valid while the display is captured, and the
* display configuration is unchanged. Releasing the captured display
* or reconfiguring the display invalidates the drawing context.
*
* An application may register a display reconfiguration callback to determine
* when the display configuration is changing via CGRegisterDisplayReconfigurationProc().
*
* After a display configuration change, or on capturing a display, call this
* function to obtain a current drawing context.
*
* If the display has not been captured, this function returns NULL.
}
function CGDisplayGetDrawingContext( display: CGDirectDisplayID ): CGContextRef; external name '_CGDisplayGetDrawingContext'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *)
end.
|
unit vcmFormSet;
// Модуль: "w:\common\components\gui\Garant\VCM\implementation\vcmFormSet.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TvcmFormSet" MUID: (5087BD37023E)
{$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc}
interface
{$If NOT Defined(NoVCM)}
uses
l3IntfUses
, vcmAggregate
, vcmInterfaces
, vcmFormSetRefreshDataParamsList
, vcmFormSetFormItemList
, vcmExternalInterfaces
, vcmBaseTypes
;
type
RvcmFormSet = class of TvcmFormSet;
TvcmFormSet = class(TvcmAggregate, IvcmFormSet)
private
f_Factory: IvcmFormSetFactory;
f_Container: Pointer;
f_CanRefresh: Boolean;
f_DataSource: Integer;
f_RefreshStack: TvcmFormSetRefreshDataParamsList;
f_Forms: TvcmFormSetFormList;
protected
function pm_GetRefreshStack: TvcmFormSetRefreshDataParamsList;
function pm_GetForms: TvcmFormSetFormList;
procedure FormListAssigned; virtual;
function DoGetFormSetCaption: IvcmCString; virtual;
function DoGetFormSetTabCaption: IvcmCString; virtual;
function DoGetFormSetTabHint: IvcmCString; virtual;
function DoGetCanBeCloned: Boolean; virtual;
function DoGetCanBeSavedToHistory: Boolean; virtual;
function DoGetCanBeMain: Boolean; virtual;
procedure Refresh(const aParams: IvcmFormSetRefreshDataParams);
{* обновляет представление сборки }
procedure SaveHistory;
{* сохраняет сборку в историю }
function IsMainInFormSet(const aForm: IvcmEntityForm): Boolean;
{* является ли форма главной в сборке }
function FindStatusInfoForm: IvcmEntityForm;
{* найти форму отвечающую за вывод статуса }
procedure PopToHistory;
{* сборка помещена в историю }
procedure PushFromHistory;
{* сборка выгружена из истории }
function pm_GetContainer: IvcmContainer;
procedure pm_SetContainer(const aValue: IvcmContainer);
function pm_GetFactory: IvcmFormSetFactory;
procedure pm_SetFactory(const aValue: IvcmFormSetFactory);
function pm_GetCanRefresh: Boolean;
function pm_GetDataSource: IvcmFormSetDataSource;
procedure pm_SetDataSource(const aValue: IvcmFormSetDataSource);
procedure AssignFormList(aFormList: TvcmFormSetFormList);
{* Заполнить мапу форм / флажков в сборке }
function GetFormNeedMakeDS(const aFormDescr: TvcmFormSetFormItemDescr): TvcmNeedMakeDS;
procedure SetFormNeedMakeDS(const aFormDescr: TvcmFormSetFormItemDescr;
aNeedMakeDS: TvcmNeedMakeDS);
function CastFS(const aGUID: TGUID;
out theObj): Boolean;
procedure SetFormClosed(const aForm: IvcmEntityForm);
{* Установить признак того, что форма была закрыта }
procedure SetIfNeedMakeNo(const aFormDescr: TvcmFormSetFormItemDescr;
aNeedMake: TvcmNeedMakeDS);
procedure SaveFormList(aFormList: TvcmFormSetFormList);
function pm_GetFormSetImageIndex: Integer;
function pm_GetFormSetCaption: IvcmCString;
function pm_GetFormSetTabCaption: IvcmCString;
function pm_GetFormSetTabHint: IvcmCString;
function MakeClone(const aContainer: IvcmContainer): IvcmFormSet;
function pm_GetCanBeCloned: Boolean;
function pm_GetCanBeSavedToHistory: Boolean;
function pm_GetCanBeMain: Boolean;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
class function Make(const aContainer: IvcmContainer;
const aFactory: IvcmFormSetFactory): IvcmFormSet;
constructor Create(const aContainer: IvcmContainer;
const aFactory: IvcmFormSetFactory); reintroduce; virtual;
protected
property RefreshStack: TvcmFormSetRefreshDataParamsList
read pm_GetRefreshStack;
property Forms: TvcmFormSetFormList
read pm_GetForms;
end;//TvcmFormSet
{$IfEnd} // NOT Defined(NoVCM)
implementation
{$If NOT Defined(NoVCM)}
uses
l3ImplUses
, SysUtils
, vcmFormSetRefreshParams
, vcmFormSetContainerRegistry
//#UC START# *5087BD37023Eimpl_uses*
//#UC END# *5087BD37023Eimpl_uses*
;
function TvcmFormSet.pm_GetRefreshStack: TvcmFormSetRefreshDataParamsList;
//#UC START# *5286081A00D0_5087BD37023Eget_var*
//#UC END# *5286081A00D0_5087BD37023Eget_var*
begin
//#UC START# *5286081A00D0_5087BD37023Eget_impl*
if f_RefreshStack = nil then
f_RefreshStack := TvcmFormSetRefreshDataParamsList.Make;
Result := f_RefreshStack;
//#UC END# *5286081A00D0_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetRefreshStack
function TvcmFormSet.pm_GetForms: TvcmFormSetFormList;
//#UC START# *528B259002B0_5087BD37023Eget_var*
//#UC END# *528B259002B0_5087BD37023Eget_var*
begin
//#UC START# *528B259002B0_5087BD37023Eget_impl*
if (f_Forms = nil) then
f_Forms := TvcmFormSetFormList.Create;
Result := f_Forms;
//#UC END# *528B259002B0_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetForms
class function TvcmFormSet.Make(const aContainer: IvcmContainer;
const aFactory: IvcmFormSetFactory): IvcmFormSet;
//#UC START# *5286089601AD_5087BD37023E_var*
var
l_Class : TvcmFormSet;
//#UC END# *5286089601AD_5087BD37023E_var*
begin
//#UC START# *5286089601AD_5087BD37023E_impl*
l_Class := Create(aContainer, aFactory);
try
Result := l_Class;
finally
FreeAndNil(l_Class);
end;//try..finally
//#UC END# *5286089601AD_5087BD37023E_impl*
end;//TvcmFormSet.Make
constructor TvcmFormSet.Create(const aContainer: IvcmContainer;
const aFactory: IvcmFormSetFactory);
//#UC START# *528609A20025_5087BD37023E_var*
//#UC END# *528609A20025_5087BD37023E_var*
begin
//#UC START# *528609A20025_5087BD37023E_impl*
inherited Create;
f_Container := Pointer(aContainer);
f_Factory := aFactory;
f_CanRefresh := True;
TvcmFormSetContainerRegistry.Instance.RegisterFormSet(Self, aContainer);
//#UC END# *528609A20025_5087BD37023E_impl*
end;//TvcmFormSet.Create
procedure TvcmFormSet.FormListAssigned;
//#UC START# *53034BFF0015_5087BD37023E_var*
//#UC END# *53034BFF0015_5087BD37023E_var*
begin
//#UC START# *53034BFF0015_5087BD37023E_impl*
//
//#UC END# *53034BFF0015_5087BD37023E_impl*
end;//TvcmFormSet.FormListAssigned
function TvcmFormSet.DoGetFormSetCaption: IvcmCString;
//#UC START# *54B352340122_5087BD37023E_var*
//#UC END# *54B352340122_5087BD37023E_var*
begin
//#UC START# *54B352340122_5087BD37023E_impl*
Result := pm_GetFactory.MakeFormSetCaption(pm_GetDataSource);
//#UC END# *54B352340122_5087BD37023E_impl*
end;//TvcmFormSet.DoGetFormSetCaption
function TvcmFormSet.DoGetFormSetTabCaption: IvcmCString;
//#UC START# *54B3525201F6_5087BD37023E_var*
//#UC END# *54B3525201F6_5087BD37023E_var*
begin
//#UC START# *54B3525201F6_5087BD37023E_impl*
Result := pm_GetFactory.MakeFormSetTabCaption(pm_GetDataSource);
if (Result = nil) and
(f_DataSource <> 0) then
Result := IvcmFormSetDataSource(f_DataSource).TabCaption;
//#UC END# *54B3525201F6_5087BD37023E_impl*
end;//TvcmFormSet.DoGetFormSetTabCaption
function TvcmFormSet.DoGetFormSetTabHint: IvcmCString;
//#UC START# *54B3526E020F_5087BD37023E_var*
//#UC END# *54B3526E020F_5087BD37023E_var*
begin
//#UC START# *54B3526E020F_5087BD37023E_impl*
Result := pm_GetFactory.MakeFormSetTabHint(pm_GetDataSource);
if (Result = nil) and
(f_DataSource <> 0) then
Result := IvcmFormSetDataSource(f_DataSource).TabHint;
//#UC END# *54B3526E020F_5087BD37023E_impl*
end;//TvcmFormSet.DoGetFormSetTabHint
function TvcmFormSet.DoGetCanBeCloned: Boolean;
//#UC START# *555D6A1000F5_5087BD37023E_var*
//#UC END# *555D6A1000F5_5087BD37023E_var*
begin
//#UC START# *555D6A1000F5_5087BD37023E_impl*
Result := f_Factory.CanCloneFormSet(Self);
//#UC END# *555D6A1000F5_5087BD37023E_impl*
end;//TvcmFormSet.DoGetCanBeCloned
function TvcmFormSet.DoGetCanBeSavedToHistory: Boolean;
//#UC START# *55E019130227_5087BD37023E_var*
//#UC END# *55E019130227_5087BD37023E_var*
begin
//#UC START# *55E019130227_5087BD37023E_impl*
Result := f_Factory.CanSaveFormSetToHistory(Self);
//#UC END# *55E019130227_5087BD37023E_impl*
end;//TvcmFormSet.DoGetCanBeSavedToHistory
function TvcmFormSet.DoGetCanBeMain: Boolean;
//#UC START# *57EB9D32008D_5087BD37023E_var*
//#UC END# *57EB9D32008D_5087BD37023E_var*
begin
//#UC START# *57EB9D32008D_5087BD37023E_impl*
Result := pm_GetFactory.CanFormsetBeMain;
//#UC END# *57EB9D32008D_5087BD37023E_impl*
end;//TvcmFormSet.DoGetCanBeMain
procedure TvcmFormSet.Refresh(const aParams: IvcmFormSetRefreshDataParams);
{* обновляет представление сборки }
//#UC START# *4995750900DB_5087BD37023E_var*
//#UC END# *4995750900DB_5087BD37023E_var*
begin
//#UC START# *4995750900DB_5087BD37023E_impl*
Assert(pm_GetDataSource <> nil, 'FormSetDataSource undefined!');
if Assigned(f_Factory) then
if pm_GetCanRefresh then
f_Factory.Refresh(vcmMakeRefreshParams(aParams, pm_GetDataSource, Self))
else
RefreshStack.Add(aParams);
//#UC END# *4995750900DB_5087BD37023E_impl*
end;//TvcmFormSet.Refresh
procedure TvcmFormSet.SaveHistory;
{* сохраняет сборку в историю }
//#UC START# *4995752D00BE_5087BD37023E_var*
//#UC END# *4995752D00BE_5087BD37023E_var*
begin
//#UC START# *4995752D00BE_5087BD37023E_impl*
if Assigned(f_Factory) then
f_Factory.SaveHistory(pm_GetContainer, false);
//#UC END# *4995752D00BE_5087BD37023E_impl*
end;//TvcmFormSet.SaveHistory
function TvcmFormSet.IsMainInFormSet(const aForm: IvcmEntityForm): Boolean;
{* является ли форма главной в сборке }
//#UC START# *499575D60157_5087BD37023E_var*
//#UC END# *499575D60157_5087BD37023E_var*
begin
//#UC START# *499575D60157_5087BD37023E_impl*
Result := pm_GetFactory.IsMainInFormSet(aForm);
//#UC END# *499575D60157_5087BD37023E_impl*
end;//TvcmFormSet.IsMainInFormSet
function TvcmFormSet.FindStatusInfoForm: IvcmEntityForm;
{* найти форму отвечающую за вывод статуса }
//#UC START# *499575E601E5_5087BD37023E_var*
var
l_Index : Integer;
l_Form : IvcmEntityForm;
//#UC END# *499575E601E5_5087BD37023E_var*
begin
//#UC START# *499575E601E5_5087BD37023E_impl*
Result := nil;
for l_Index := 0 to Pred(Get_EntitiesCount) do
if Supports(Get_Entity(l_Index), IvcmEntityForm, l_Form) AND
pm_GetFactory.IsDefaultStatusForm(l_Form) then
begin
Result := l_Form;
break;
end;//Supports..
//#UC END# *499575E601E5_5087BD37023E_impl*
end;//TvcmFormSet.FindStatusInfoForm
procedure TvcmFormSet.PopToHistory;
{* сборка помещена в историю }
//#UC START# *499575F40009_5087BD37023E_var*
//#UC END# *499575F40009_5087BD37023E_var*
begin
//#UC START# *499575F40009_5087BD37023E_impl*
f_CanRefresh := False;
TvcmFormSetContainerRegistry.Instance.UnregisterFormSet(Self);
//#UC END# *499575F40009_5087BD37023E_impl*
end;//TvcmFormSet.PopToHistory
procedure TvcmFormSet.PushFromHistory;
{* сборка выгружена из истории }
//#UC START# *499575FF0015_5087BD37023E_var*
//#UC END# *499575FF0015_5087BD37023E_var*
begin
//#UC START# *499575FF0015_5087BD37023E_impl*
TvcmFormSetContainerRegistry.Instance.RegisterFormSet(Self, pm_GetContainer);
f_CanRefresh := True;
pm_GetDataSource.PushFromHistory;
//#UC END# *499575FF0015_5087BD37023E_impl*
end;//TvcmFormSet.PushFromHistory
function TvcmFormSet.pm_GetContainer: IvcmContainer;
//#UC START# *4995761C018F_5087BD37023Eget_var*
//#UC END# *4995761C018F_5087BD37023Eget_var*
begin
//#UC START# *4995761C018F_5087BD37023Eget_impl*
Result := IvcmContainer(f_Container);
//#UC END# *4995761C018F_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetContainer
procedure TvcmFormSet.pm_SetContainer(const aValue: IvcmContainer);
//#UC START# *4995761C018F_5087BD37023Eset_var*
//#UC END# *4995761C018F_5087BD37023Eset_var*
begin
//#UC START# *4995761C018F_5087BD37023Eset_impl*
f_Container := Pointer(aValue);
TvcmFormSetContainerRegistry.Instance.RegisterFormSet(Self, aValue);
//#UC END# *4995761C018F_5087BD37023Eset_impl*
end;//TvcmFormSet.pm_SetContainer
function TvcmFormSet.pm_GetFactory: IvcmFormSetFactory;
//#UC START# *4995762F039E_5087BD37023Eget_var*
//#UC END# *4995762F039E_5087BD37023Eget_var*
begin
//#UC START# *4995762F039E_5087BD37023Eget_impl*
Result := f_Factory;
//#UC END# *4995762F039E_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetFactory
procedure TvcmFormSet.pm_SetFactory(const aValue: IvcmFormSetFactory);
//#UC START# *4995762F039E_5087BD37023Eset_var*
//#UC END# *4995762F039E_5087BD37023Eset_var*
begin
//#UC START# *4995762F039E_5087BD37023Eset_impl*
f_Factory := aValue;
//#UC END# *4995762F039E_5087BD37023Eset_impl*
end;//TvcmFormSet.pm_SetFactory
function TvcmFormSet.pm_GetCanRefresh: Boolean;
//#UC START# *4995764602B6_5087BD37023Eget_var*
//#UC END# *4995764602B6_5087BD37023Eget_var*
begin
//#UC START# *4995764602B6_5087BD37023Eget_impl*
Result := f_CanRefresh;
//#UC END# *4995764602B6_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetCanRefresh
function TvcmFormSet.pm_GetDataSource: IvcmFormSetDataSource;
//#UC START# *49957658008F_5087BD37023Eget_var*
//#UC END# *49957658008F_5087BD37023Eget_var*
begin
//#UC START# *49957658008F_5087BD37023Eget_impl*
Result := IvcmFormSetDataSource(f_DataSource);
//#UC END# *49957658008F_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetDataSource
procedure TvcmFormSet.pm_SetDataSource(const aValue: IvcmFormSetDataSource);
//#UC START# *49957658008F_5087BD37023Eset_var*
//#UC END# *49957658008F_5087BD37023Eset_var*
begin
//#UC START# *49957658008F_5087BD37023Eset_impl*
Assert(f_DataSource = 0, 'FormSetDataSource already exists!');
f_DataSource := Integer(aValue);
//#UC END# *49957658008F_5087BD37023Eset_impl*
end;//TvcmFormSet.pm_SetDataSource
procedure TvcmFormSet.AssignFormList(aFormList: TvcmFormSetFormList);
{* Заполнить мапу форм / флажков в сборке }
//#UC START# *528DA6D00396_5087BD37023E_var*
//#UC END# *528DA6D00396_5087BD37023E_var*
begin
//#UC START# *528DA6D00396_5087BD37023E_impl*
Assert(aFormList <> nil);
Forms.Assign(aFormList);
FormListAssigned;
//#UC END# *528DA6D00396_5087BD37023E_impl*
end;//TvcmFormSet.AssignFormList
function TvcmFormSet.GetFormNeedMakeDS(const aFormDescr: TvcmFormSetFormItemDescr): TvcmNeedMakeDS;
//#UC START# *528DAD93029F_5087BD37023E_var*
//#UC END# *528DAD93029F_5087BD37023E_var*
begin
//#UC START# *528DAD93029F_5087BD37023E_impl*
Result := Forms.NeedMakeDS[aFormDescr];
//#UC END# *528DAD93029F_5087BD37023E_impl*
end;//TvcmFormSet.GetFormNeedMakeDS
procedure TvcmFormSet.SetFormNeedMakeDS(const aFormDescr: TvcmFormSetFormItemDescr;
aNeedMakeDS: TvcmNeedMakeDS);
//#UC START# *528DB1F80281_5087BD37023E_var*
//#UC END# *528DB1F80281_5087BD37023E_var*
begin
//#UC START# *528DB1F80281_5087BD37023E_impl*
Forms.NeedMakeDS[aFormDescr] := aNeedMakeDS;
//#UC END# *528DB1F80281_5087BD37023E_impl*
end;//TvcmFormSet.SetFormNeedMakeDS
function TvcmFormSet.CastFS(const aGUID: TGUID;
out theObj): Boolean;
//#UC START# *529D991A02D3_5087BD37023E_var*
//#UC END# *529D991A02D3_5087BD37023E_var*
begin
//#UC START# *529D991A02D3_5087BD37023E_impl*
Result := Supports(Self, aGUID, theObj);
//#UC END# *529D991A02D3_5087BD37023E_impl*
end;//TvcmFormSet.CastFS
procedure TvcmFormSet.SetFormClosed(const aForm: IvcmEntityForm);
{* Установить признак того, что форма была закрыта }
//#UC START# *52A56B30012F_5087BD37023E_var*
//#UC END# *52A56B30012F_5087BD37023E_var*
begin
//#UC START# *52A56B30012F_5087BD37023E_impl*
SetFormNeedMakeDS(aForm.KeyInFormSet, vcm_nmNo);
//#UC END# *52A56B30012F_5087BD37023E_impl*
end;//TvcmFormSet.SetFormClosed
procedure TvcmFormSet.SetIfNeedMakeNo(const aFormDescr: TvcmFormSetFormItemDescr;
aNeedMake: TvcmNeedMakeDS);
//#UC START# *52E8E6420272_5087BD37023E_var*
//#UC END# *52E8E6420272_5087BD37023E_var*
begin
//#UC START# *52E8E6420272_5087BD37023E_impl*
Forms.SetIfNeedMakeNo(aFormDescr, aNeedmake);
//#UC END# *52E8E6420272_5087BD37023E_impl*
end;//TvcmFormSet.SetIfNeedMakeNo
procedure TvcmFormSet.SaveFormList(aFormList: TvcmFormSetFormList);
//#UC START# *52EF7041000D_5087BD37023E_var*
//#UC END# *52EF7041000D_5087BD37023E_var*
begin
//#UC START# *52EF7041000D_5087BD37023E_impl*
Assert(aFormList <> nil);
aFormList.Assign(Forms);
//#UC END# *52EF7041000D_5087BD37023E_impl*
end;//TvcmFormSet.SaveFormList
function TvcmFormSet.pm_GetFormSetImageIndex: Integer;
//#UC START# *53B3B3C60264_5087BD37023Eget_var*
//#UC END# *53B3B3C60264_5087BD37023Eget_var*
begin
//#UC START# *53B3B3C60264_5087BD37023Eget_impl*
if (f_DataSource <> 0) then
Result := pm_GetDataSource.FormSetImageIndex
else
Result := -1;
//#UC END# *53B3B3C60264_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetFormSetImageIndex
function TvcmFormSet.pm_GetFormSetCaption: IvcmCString;
//#UC START# *54B350C10230_5087BD37023Eget_var*
//#UC END# *54B350C10230_5087BD37023Eget_var*
begin
//#UC START# *54B350C10230_5087BD37023Eget_impl*
Result := DoGetFormSetCaption;
//#UC END# *54B350C10230_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetFormSetCaption
function TvcmFormSet.pm_GetFormSetTabCaption: IvcmCString;
//#UC START# *54B350DD005E_5087BD37023Eget_var*
//#UC END# *54B350DD005E_5087BD37023Eget_var*
begin
//#UC START# *54B350DD005E_5087BD37023Eget_impl*
Result := DoGetFormSetTabCaption;
//#UC END# *54B350DD005E_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetFormSetTabCaption
function TvcmFormSet.pm_GetFormSetTabHint: IvcmCString;
//#UC START# *54B350EC00E5_5087BD37023Eget_var*
//#UC END# *54B350EC00E5_5087BD37023Eget_var*
begin
//#UC START# *54B350EC00E5_5087BD37023Eget_impl*
Result := DoGetFormSetTabHint;
//#UC END# *54B350EC00E5_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetFormSetTabHint
function TvcmFormSet.MakeClone(const aContainer: IvcmContainer): IvcmFormSet;
//#UC START# *555B21DA0384_5087BD37023E_var*
//#UC END# *555B21DA0384_5087BD37023E_var*
begin
//#UC START# *555B21DA0384_5087BD37023E_impl*
Result := pm_GetFactory.CloneFormSet(Self, aContainer);
//#UC END# *555B21DA0384_5087BD37023E_impl*
end;//TvcmFormSet.MakeClone
function TvcmFormSet.pm_GetCanBeCloned: Boolean;
//#UC START# *555D5CF4019C_5087BD37023Eget_var*
//#UC END# *555D5CF4019C_5087BD37023Eget_var*
begin
//#UC START# *555D5CF4019C_5087BD37023Eget_impl*
Result := DoGetCanBeCloned;
//#UC END# *555D5CF4019C_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetCanBeCloned
function TvcmFormSet.pm_GetCanBeSavedToHistory: Boolean;
//#UC START# *55E012ED0134_5087BD37023Eget_var*
//#UC END# *55E012ED0134_5087BD37023Eget_var*
begin
//#UC START# *55E012ED0134_5087BD37023Eget_impl*
Result := DoGetCanBeSavedToHistory;
//#UC END# *55E012ED0134_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetCanBeSavedToHistory
function TvcmFormSet.pm_GetCanBeMain: Boolean;
//#UC START# *57EB9AFB026D_5087BD37023Eget_var*
//#UC END# *57EB9AFB026D_5087BD37023Eget_var*
begin
//#UC START# *57EB9AFB026D_5087BD37023Eget_impl*
Result := DoGetCanBeMain;
//#UC END# *57EB9AFB026D_5087BD37023Eget_impl*
end;//TvcmFormSet.pm_GetCanBeMain
procedure TvcmFormSet.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_5087BD37023E_var*
//#UC END# *479731C50290_5087BD37023E_var*
begin
//#UC START# *479731C50290_5087BD37023E_impl*
f_DataSource := 0;
FreeAndNil(f_RefreshStack);
f_Factory := nil;
f_Container := nil;
FreeAndNil(f_Forms);
TvcmFormSetContainerRegistry.Instance.UnregisterFormSet(Self);
inherited;
//#UC END# *479731C50290_5087BD37023E_impl*
end;//TvcmFormSet.Cleanup
{$IfEnd} // NOT Defined(NoVCM)
end.
|
unit pbxcontainer;
(*-------------------------------------------------------------------------------
* by Dmitry Boyarintsev - Oct 2014 *
* *
* license: free for use, but please leave a note to the origin of the library *
* *
* PBXcontainer unit is a library to read/write the pbx formatter file as a *
* whole The file structure is made to keep the reference in a complex objects *
* struture. Hierarchial trees, lists, cycles and so on. *
* *
* It's achieved by giving a full list of objects. With each object having an *
* "id" assigned. Later in the description, the reference is specifeid by the *
* object's id. *
* *
* Currently PBXContainer would read and try to build a structure based of *
* Object Pascal RTTI. (Not sure if Delphi compatible) *
* Following rules are used *
* read/write objects are going to join the list of objects (for the futher *
* reference) *
* read-only objects should be allocated in the constructor of the parent *
* they're "inlined" in the file *
* for array of objects TPBXObjectsList must be used *
* for array of strings TPBXStringArray must be used *
* for key-value set use TPBXKeyValue class *
* string and integer properties are supported... anything else? *
* booleans are (always) written as 0 or 1 to the file
*
* *
* todo: add more documentions *
* *
* todo: memoty allocation and release. ObjC is using ref-counted structure. *
* do the same? similar? *
-------------------------------------------------------------------------------*)
interface
{$ifdef fpc}{$mode delphi}{$endif}
uses
Classes, SysUtils, typinfo, pbxfile, contnrs;
type
{ TPBXObject }
{ PBXObject }
PBXObject = class(TObject)
private
_id : string;
_fheaderComment : string;
protected
// collects the name of string properties that should be written out
// even if their values is an empty string.
// if property value is an empty string, it would not be written to the file
class procedure _WriteEmpty(propnames: TStrings); virtual;
public
property __id: string read _id;
property _headerComment: string read _fheaderComment write _fheaderComment;
constructor Create; virtual;
end;
PBXObjectClass = class of PBXObject;
TPBXObjectsList = class(TObjectList);
TPBXStringArray = class(TStringList);
TPBXKeyValue = class;
TPBXValueType = (vtString, vtArrayOfStr, vtKeyVal);
{ TPBXValue }
TPBXValue = class(TObject)
public
valType : TPBXValueType;
str : string;
arr : TPBXStringArray;
keyval : TPBXKeyValue;
destructor Destroy; override;
end;
{ TPBXKeyValue }
TPBXKeyValue = class(TFPHashObjectList)
protected
function AddVal(const name: string; atype: TPBXValueType): TPBXValue;
public
function AddStr(const name: string; const avalue: string = ''): TPBXValue;
function AddStrArray(const name: string): TPBXValue;
function AddKeyVal(const name: string): TPBXValue;
end;
TPBXFileInfo = record
archiveVersion : string;
objectVersion : string;
rootObject : PBXObject;
end;
{ TPBXReref }
TPBXReref = class(TObject)
instance : TObject;
propname : string;
_id : string;
constructor Create(ainstance: TObject; const apropname, aref: string);
end;
{ TPBXContainer }
TObjHashList = TFPHashObjectList;
TPBXContainer = class(TObject)
protected
procedure ReadObjects(p: TPBXParser; objs: TObjHashList);
function AllocObject(const nm: string): PBXObject;
public
function ReadFile(s: TStream; var AFileInfo: TPBXFileInfo): Boolean;
end;
procedure TestContainer(const buf: string);
procedure PBXRegisterClass(aclass: PBXObjectClass);
function PBXFindClass(const aclassname: string): PBXObjectClass;
function PBXReadObjectsListRef(p: TPBXParser; obj: PBXObject; propName: string; refs: TList): Boolean;
function PBXReadStringArray(p: TPBXParser; arr: TPBXStringArray): Boolean;
function PBXReadKeyValue(p: TPBXParser; kv: TPBXKeyValue): Boolean;
function PBXReadClass(p: TPBXParser; obj: PBXObject; refs: TList): Boolean;
procedure PBXReref(objs: TObjHashList; refs: TList);
function PBXWriteContainer(const FileInfo: TPBXFileInfo; AssignRef: Boolean = true): string;
procedure PBXWriteObjArray( w: TPBXWriter; list: TPBXObjectsList );
procedure PBXWriteStrArray( w: TPBXWriter; list: TPBXStringArray );
procedure PBXWriteKeyValue( w: TPBXWriter; kv: TPBXKeyValue );
procedure PBXWriteObj(pbx: PBXObject; w: TPBXWriter; WriteEmpty: TStrings);
procedure PBXAssignRef(list: TList);
procedure PBXGatherObjects(obj: TObject; srz: TList);
implementation
var
pbxClassList : TStringList;
function PBXReadKeyValue(p: TPBXParser; kv: TPBXKeyValue): Boolean;
var
et : TPBXEntity;
v : TPBXValue;
begin
et:=p.FetchNextEntity;
while et<>etCloseObject do begin
case et of
etValue: kv.AddStr(p.Name, p.Value);
etOpenArray: begin
v:=kv.AddStrArray(p.Name);
PBXReadStringArray(p, v.arr);
end;
etOpenObject: begin
v:=kv.AddKeyVal(p.Name);
PBXReadKeyValue(p, v.keyval);
end;
else
Result:=false;
Exit;
end;
et:=p.FetchNextEntity;
end;
Result:=True;
end;
procedure TestContainer(const buf: string);
var
c : TPBXContainer;
st : TStringStream;
info : TPBXFileInfo;
begin
c:= TPBXContainer.Create;
st := TStringStream.Create(buf);
try
c.ReadFile(st, info);
writeln('arch ver: ',info.archiveVersion);
writeln(' obj ver: ',info.objectVersion);
writeln('root obj: ', PtrUInt( info.rootObject ));
finally
st.Free;
c.Free;
end;
end;
procedure PBXRegisterClass(aclass: PBXObjectClass);
begin
pbxClassList.AddObject(aclass.ClassName, TObject(aclass));
end;
function PBXFindClass(const aclassname: string): PBXObjectClass;
var
i : integer;
begin
i:=pbxClassList.IndexOf(aclassname);
if i<0 then Result:=nil
else Result:=PBXObjectClass(pbxClassList.Objects[i]);
end;
{ TPBXValue }
destructor TPBXValue.Destroy;
begin
arr.Free;
keyval.Free;
inherited Destroy;
end;
{ TPBXKeyValue }
function TPBXKeyValue.AddVal(const name: string; atype: TPBXValueType): TPBXValue;
begin
Result:=TPBXValue.Create;
Result.valType:=atype;
case atype of
vtKeyVal: Result.keyval:=TPBXKeyValue.Create(true);
vtArrayOfStr: Result.arr:=TPBXStringArray.Create;
end;
Add(name, Result);
end;
function TPBXKeyValue.AddStr(const name: string; const avalue: string): TPBXValue;
begin
Result:=AddVal(name, vtString);
Result.str:=avalue;
end;
function TPBXKeyValue.AddStrArray(const name: string): TPBXValue;
begin
Result:=AddVal(name, vtArrayOfStr);
end;
function TPBXKeyValue.AddKeyVal(const name: string): TPBXValue;
begin
Result:=AddVal(name, vtKeyVal);
end;
{ TPBXReref }
constructor TPBXReref.Create(ainstance: TObject; const apropname, aref: string);
begin
inherited Create;
instance := ainstance;
propname := apropname;
_id := aref;
end;
{ TPBXObject }
class procedure PBXObject._WriteEmpty(propnames: TStrings);
begin
end;
constructor PBXObject.Create;
begin
end;
{ TPBXContainer }
procedure PBXReref(objs: TObjHashList; refs: TList);
var
i : integer;
refobj : TObject;
r : TPBXReref;
prp : PPropInfo;
pcls : TObject;
begin
for i:=0 to refs.Count-1 do begin
r := TPBXReref(refs[i]);
refobj:=objs.Find(r._id);
if Assigned(refobj) then begin
prp:=GetPropInfo(r.instance, r.propname);
if prp^.PropType^.Kind=tkClass then begin
pcls:=GetObjectProp(r.instance, r.propname);
if pcls is TPBXObjectsList then begin
TPBXObjectsList(pcls).Add(refobj);
end else begin
//writeln('setting prop: ', r.propname,' ');
SetObjectProp(r.instance, r.propname, refobj);
end;
end;
end;
//else writeln('no object found! ', r._id);
end;
end;
procedure TPBXContainer.ReadObjects(p: TPBXParser; objs: TObjHashList);
var
tk : TPBXEntity;
id : string;
cls : string;
obj : PBXObject;
i : Integer;
refs : TList;
cmt : string;
begin
tk:=p.FetchNextEntity;
refs:=TList.Create;
try
while tk<>etCloseObject do begin
if tk=etOpenObject then begin
id:=p.Name;
cmt:=p.LastComment;
cls:='';
p.FetchNextEntity;
if (p.CurEntity = etValue) and (p.Name = 'isa') then begin
cls:=p.Value;
obj:=AllocObject(cls);
if Assigned(obj) then begin
obj._headerComment:=cmt;
obj._id:=id;
PBXReadClass(p, obj, refs);
objs.Add(id, obj);
end else
PBXParserSkipLevel(p);
end else
PBXParserSkipLevel(p);
end;
tk:=p.FetchNextEntity;
end;
PBXReref(objs, refs);
finally
for i:=0 to refs.Count-1 do TObject(refs[i]).Free;
refs.Free;
end;
end;
function TPBXContainer.AllocObject(const nm: string): PBXObject;
var
cls : PBXObjectClass;
begin
cls:=PBXFindClass(nm);
if not Assigned(cls) then Result:=nil
else Result:=cls.Create;
end;
function TPBXContainer.ReadFile(s: TStream; var AFileInfo: TPBXFileInfo): Boolean;
var
p : TPBXParser;
buf : string;
tk : TPBXEntity;
root : string;
objs : TObjHashList;
rt : TObject;
begin
Result:=false;
AFileInfo.archiveVersion:='';
AFileInfo.objectVersion:='';
AFileInfo.rootObject:=nil;
if not Assigned(s) then Exit;
SetLength(buf, s.Size);
s.Read(buf[1], length(buf));
objs:=TObjHashList.Create(False);
p:=TPBXParser.Create;
try
p.scanner.SetBuf(buf);
if p.FetchNextEntity <> etOpenObject then Exit;
tk:=p.FetchNextEntity;
while tk <> etEOF do begin
if tk = etValue then begin
if p.Name='archiveVersion' then AFileInfo.archiveVersion:=p.Value
else if p.Name='objectVersion' then AFileInfo.objectVersion:=p.Value
else if p.Name='rootObject' then root:=p.Value;
end else if (tk=etOpenObject) and (p.Name = 'objects') then begin
ReadObjects(p, objs);
end;
tk:=p.FetchNextEntity;
end;
rt:=objs.Find(root);
if Assigned(rt) and (rt is PBXObject) then
AFileInfo.rootObject:=PBXObject(rt);
Result:=true;
finally
objs.Free;
p.Free;
end;
end;
function PBXReadObjectsListRef(p: TPBXParser; obj: PBXObject; propName: string; refs: TList): Boolean;
begin
Result:=true;
p.FetchNextEntity;
while not (p.CurEntity in [etCloseArray, etEOF, etError]) do begin
if p.CurEntity <> etValue then begin
Result:=false;
Exit;
end;
if p.Value<>'' then
refs.Add ( TPBXReref.Create( obj, propName, p.Value ));
p.FetchNextEntity;
end;
end;
function PBXReadStringArray(p: TPBXParser; arr: TPBXStringArray): Boolean;
begin
Result:=true;
p.FetchNextEntity;
while not (p.CurEntity in [etCloseArray, etEOF, etError]) do begin
if p.CurEntity <> etValue then begin
Result:=false;
Exit;
end;
arr.Add(p.Value);
p.FetchNextEntity;
end;
end;
function PBXReadClass(p: TPBXParser; obj: PBXObject; refs: TList): Boolean;
var
tk : TPBXEntity;
lvl : Integer;
prp : PPropInfo;
pobj : TObject;
pk : TTypeKind;
begin
lvl:=p.Level;
tk:=p.FetchNextEntity;
while p.Level>=lvl {tk<>tkCurlyBraceClose} do begin
prp:=GetPropInfo(obj, p.Name);
if Assigned(prp) then begin
pk:=prp^.PropType^.Kind;
if pk=tkClass then
pobj:=GetObjectProp(obj, prp)
else
pobj:=nil;
if tk=etValue then begin
case pk of
tkClass: begin
//writeln('ref for: ',p.Name,' to ', p.Value);
refs.Add( TPBXReref.Create(obj, p.Name, p.Value))
end;
tkInteger, tkInt64, tkQWord: begin
SetInt64Prop(obj, p.Name, StrToIntDef(p.Value, GetInt64Prop(obj, p.Name)) );
end;
tkBool: begin
SetOrdProp(obj, p.Name, StrToIntDef(p.Value, GetInt64Prop(obj, p.Name)) );
end;
else
SetStrProp(obj, p.Name, p.Value);
end;
end else begin
{write( p.CurEntity,' ',p.Name,' ',PtrUInt(pobj));
if Assigned(pobj) then write(' ', pobj.ClassName);
writeln;}
if (pobj is TPBXObjectsList) and (tk = etOpenArray) then begin
Result:=PBXReadObjectsListRef(p, obj, p.Name, refs);
if not Result then Exit;
end else if (pobj is TPBXStringArray) and (tk = etOpenArray) then begin
Result:=PBXReadStringArray(p, TPBXStringArray(pobj) );
if not Result then Exit;
end else if (pobj is TPBXKeyValue) and (tk = etOpenObject) then begin
Result:=PBXReadKeyValue(p, TPBXKeyValue(pobj) );
if not Result then Exit;
end else
// array of object
PBXParserSkipLevel(p);
end;
end else begin
writeln(obj.ClassName, ': property not found: ', p.Name);
if tk <> etValue then
PBXParserSkipLevel(p);
end;
tk:=p.FetchNextEntity;
end;
Result:=true;
end;
procedure PBXGatherObjects(obj: TObject; srz: TList);
var
plist : PPropList;
cnt : Integer;
i : Integer;
j : Integer;
k : Integer;
arr : TPBXObjectsList;
ch : TObject;
ach : TObject;
kind : TTypeKind;
const
FlagGet = 3; // 1 + 2 //ptField = 0;
FlagSet = 12; // 4 + 8 , 16 + 32 //ptStatic = 1;
FlagSP = 16 + 32; //ptVirtual = 2;
FlagIdx = 64; //ptConst = 3; }
begin
if (not Assigned(obj)) or (not Assigned(srz)) then Exit;
srz.Add(obj);
j:=0;
while j<srz.Count do begin
obj:=TObject(srz[j]);
plist:=nil;
cnt:=GetPropList(obj, plist);
if Assigned(plist) then begin
for i:=0 to cnt-1 do begin
kind := plist^[i]^.PropType^.Kind;
if (kind<>tkClass) then Continue;
ch:=GetObjectProp(obj, plist^[i] );
if not Assigned(ch) then Continue;
if (plist^[i]^.PropProcs and FlagSet <> FlagSet) then begin
if srz.IndexOf(ch)<0 then
srz.Add ( ch );
end else if ch is TPBXObjectsList then begin
arr:=TPBXObjectsList(ch);
for k:=0 to arr.Count-1 do begin
ach:=arr[k];
if srz.IndexOf(ach)<0 then srz.Add(ach);
end;
end;
end;
Freemem(plist);
end;
inc(j);
end;
end;
procedure PBXAssignRef(list: TList);
var
i : Integer;
p : PBXObject;
id: Int64;
begin
if not Assigned(list) then Exit;
id:=2; // root! :)
for i:=0 to list.Count-1 do begin
p:=PBXObject(list[i]);
if not Assigned(p) then Continue;
if (p._id='') then begin
p._id:=IntToHex(id, 24);
inc(id);
end;
end;
// 0AFA6EA519F60EFD004C8FD9
// 123456789012345678901234
end;
procedure PBXWriteStrArray( w: TPBXWriter; list: TPBXStringArray );
var
i : Integer;
begin
w.OpenBlock('(');
for i:=0 to list.Count-1 do
w.WriteArrValue(list.Strings[i]);
w.CloseBlock(')');
end;
procedure PBXWriteObjArray( w: TPBXWriter; list: TPBXObjectsList );
var
i : Integer;
pbx : PBXObject;
begin
for i:=0 to list.Count-1 do begin
pbx:=PBXObject(list[i]);
w.WriteArrValue(pbx._id, pbx._headerComment);
end;
end;
procedure PBXWriteKeyValue( w: TPBXWriter; kv: TPBXKeyValue );
var
i : Integer;
v : TPBXValue;
nm : string;
begin
w.OpenBlock( '{' );
for i:=0 to kv.Count-1 do begin
v:=TPBXValue(kv.Items[i]);
nm:=kv.NameOfIndex(i);
w.WriteName(nm);
case v.valType of
vtString: w.WriteValue(v.str);
vtArrayOfStr: PBXWriteStrArray(w, v.arr);
vtKeyVal: PBXWriteKeyValue(w, v.keyval);
end;
end;
w.CloseBlock( '}' );
end;
procedure PBXWriteObj(pbx: PBXObject; w: TPBXWriter; WriteEmpty: TStrings);
var
p : PPropList;
cnt : Integer;
i,j : Integer;
isMan : Boolean;
vl : string;
sobj : TObject;
nm : string;
vcmt : string;
isstr : Boolean;
// used for sorting. todo: find a better way for sort by names!
names : TStringList;
begin
w.WriteName(pbx._id, pbx._headerComment);
isMan:=(pbx.ClassName='PBXFileReference') or (pbx.ClassName='PBXBuildFile');
if isMan then w.ManualLineBreak:=true;
w.OpenBlock('{');
w.WriteNamedValue('isa', pbx.ClassName);
p:=nil;
cnt:=GetPropList(pbx, p);
//todo: I don't like this soritng at all!
// but it appears to be the most common available
names:=TStringList.Create;
try
for i:=0 to cnt-1 do names.AddObject(p^[i].Name, TObject(PtrUInt(i)));
names.Sort;
for j:=0 to names.Count-1 do begin
i:=Integer(PtrUInt(names.Objects[j]));
vl:='';
vcmt:='';
isstr:=false;
nm:=p^[i].Name;
if p^[i].PropType.Kind=tkClass then begin
sobj:=GetObjectProp(pbx, p^[i]);
if sobj is PBXObject then begin
vl:=PBXObject(sobj)._id;
vcmt:=PBXObject(sobj)._headerComment;
isstr:=vl<>'';
end else if sobj is TPBXObjectsList then begin
w.WriteName(nm); w.OpenBlock('(');
PBXWriteObjArray( w, TPBXObjectsList(sobj) );
w.CloseBlock(')');
end else if sobj is TPBXStringArray then begin
w.WriteName(nm);
PBXWriteStrArray( w, TPBXStringArray(sobj) );
end else if sobj is TPBXKeyValue then begin
w.WriteName(nm);
PBXWriteKeyValue(w, TPBXKeyValue(sobj));
end;
end else if p^[i].PropType.Kind in [tkAString, tkString] then begin
vl:=GetStrProp(pbx,p^[i]);
isstr:=(vl<>'') or (WriteEmpty.indexOf(nm)>=0);
end else if p^[i].PropType.Kind in [tkInteger, tkInt64, tkQWord] then begin
vl:=IntToStr(GetInt64Prop(pbx, p^[i]));
isstr:=(vl<>'') or (WriteEmpty.indexOf(nm)>=0);
end else if p^[i].PropType.Kind = tkBool then begin
vl:=IntToStr(GetOrdProp(pbx, p^[i]));
isstr:=true;
end;
if isstr then begin
w.WriteName(nm);
w.WriteValue(vl,vcmt);
end;
end;
if isMan then w.ManualLineBreak:=false;
w.CloseBlock('}');
finally
names.Free;
if Assigned(p) then Freemem(p);
end;
end;
function PBXWriteContainer(const FileInfo: TPBXFileInfo; AssignRef: Boolean = true): string;
var
lst : TList;
st : TStringList;
i : Integer;
w : TPBXWriter;
sc : string;
pbx : PBXObject;
emp : TStringList;
begin
lst:=TList.Create;
st:=TStringList.Create;
emp:=TStringList.Create;
try
PBXGatherObjects(fileInfo.rootObject, lst);
if AssignRef then PBXAssignRef(lst);
for i:=0 to lst.Count-1 do begin
st.AddObject( PBXObject(lst[i]).ClassName+' '+PBXObject(lst[i])._id, PBXObject(lst[i]));
end;
st.Sort;
w:=TPBXWriter.Create;
try
sc:='';
w.WriteRaw('// !$*UTF8*$!');
w.WriteLineBreak;
w.OpenBlock('{');
w.WriteNamedValue('archiveVersion', FileInfo.archiveVersion);
w.WriteName('classes'); w.OpenBlock('{'); w.CloseBlock('}');
w.WriteNamedValue('objectVersion', FileInfo.objectVersion);
w.WriteName('objects'); w.OpenBlock('{');
for i:=0 to st.Count-1 do begin
pbx:=PBXObject(st.Objects[i]);
if sc<>pbx.ClassName then begin
if sc<>'' then begin
w.WriteLineComment('End '+sc+' section');
end;
sc:=pbx.ClassName;
w.WriteLineBreak();
w.WriteLineComment('Begin '+sc+' section');
emp.Clear;
pbx._WriteEmpty(emp);
end;
PBXWriteObj(pbx, w, emp);
end;
if sc<>'' then w.WriteLineComment('End '+sc+' section');
w.CloseBlock('}');
w.WriteNamedValue('rootObject', FileInfo.rootObject._id, FileInfo.rootObject._headerComment);
w.CloseBlock('}');
Result:=w.Buffer;
finally
w.Free;
end;
finally
st.Free;
lst.Free;
emp.Free;
end;
end;
initialization
pbxClassList := TStringList.Create;
finalization
pbxClassList.Free;
end.
|
unit ddCustomRTFReader;
{* Попытка разделить TddRTFReader на две части, чтобы используемые в нем классы могли знать об нем. }
// Модуль: "w:\common\components\rtl\Garant\dd\ddCustomRTFReader.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TddCustomRTFReader" MUID: (51E7BF4200C0)
{$Include w:\common\components\rtl\Garant\dd\ddDefine.inc}
interface
uses
l3IntfUses
, ddLowLevelRTF
, rtfListTable
, Graphics
, ddRTFProperties
, RTFtypes
, ddDocumentAtom
, ddPicture
;
type
TddCustomRTFReader = {final} class(TddRTFParser)
{* Попытка разделить TddRTFReader на две части, чтобы используемые в нем классы могли знать об нем. }
private
f_SkipPicture: Boolean;
{* Флаг для пропуска картинки в процессе чтения. }
f_EnablePictures: Boolean;
{* Читать картинки. }
f_ReadWMFIfExists: Boolean;
{* Читать WMF-файлы, вместо растровых картинок (если такое возможно) }
f_NextFootnoteNumber: Integer;
f_MinPicWidth: Integer;
{* Если у картники меньше ширина, то такая картинка не добавляется в документ. }
f_MinPicHeight: Integer;
{* Если у картники меньше высота, то такая картинка не добавляется в документ. }
f_IdenticalRowWidths: Boolean;
{* Делать ширину ячеек одинаковой (дополняя справа ячейками без границ). Для вставки в комментарии. }
f_ReadURL: Boolean;
{* Читать гиперссылки. Ссылка добавляется в поле URL. }
protected
procedure pm_SetMinPicWidth(aValue: Integer); virtual;
procedure pm_SetMinPicHeight(aValue: Integer);
procedure pm_SetIdenticalRowWidths(aValue: Boolean);
procedure pm_SetReadURL(aValue: Boolean);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure InitFields; override;
public
function ListByID(aID: Integer;
out aWasRestart: Boolean): TrtfList; virtual;
function ColorByIndex(anIndex: Integer): TColor; virtual;
function StyleByNumber(aNumber: Integer): TddStyleEntry; virtual;
function GetFonts(anID: Integer): TddFontEntry; virtual;
procedure BeforeClosePara(const aPara: TddDocumentAtom;
var aNewStyle: Integer); virtual; abstract;
function NeedSkip(aPicture: TddPicture): TRTFPictureSkip;
procedure IncNextFootnoteNumber;
procedure AddFooterHyperlink; virtual; abstract;
procedure FootNoteSymbol; virtual; abstract;
public
property SkipPicture: Boolean
read f_SkipPicture
write f_SkipPicture;
{* Флаг для пропуска картинки в процессе чтения. }
property EnablePictures: Boolean
read f_EnablePictures
write f_EnablePictures;
{* Читать картинки. }
property ReadWMFIfExists: Boolean
read f_ReadWMFIfExists
write f_ReadWMFIfExists;
{* Читать WMF-файлы, вместо растровых картинок (если такое возможно) }
property NextFootnoteNumber: Integer
read f_NextFootnoteNumber
write f_NextFootnoteNumber;
property MinPicWidth: Integer
read f_MinPicWidth
write pm_SetMinPicWidth;
{* Если у картники меньше ширина, то такая картинка не добавляется в документ. }
property MinPicHeight: Integer
read f_MinPicHeight
write pm_SetMinPicHeight;
{* Если у картники меньше высота, то такая картинка не добавляется в документ. }
property IdenticalRowWidths: Boolean
read f_IdenticalRowWidths
write pm_SetIdenticalRowWidths;
{* Делать ширину ячеек одинаковой (дополняя справа ячейками без границ). Для вставки в комментарии. }
property ReadURL: Boolean
read f_ReadURL
write pm_SetReadURL;
{* Читать гиперссылки. Ссылка добавляется в поле URL. }
end;//TddCustomRTFReader
implementation
uses
l3ImplUses
, ddConst
//#UC START# *51E7BF4200C0impl_uses*
//#UC END# *51E7BF4200C0impl_uses*
;
procedure TddCustomRTFReader.pm_SetMinPicWidth(aValue: Integer);
//#UC START# *56023F490306_51E7BF4200C0set_var*
//#UC END# *56023F490306_51E7BF4200C0set_var*
begin
//#UC START# *56023F490306_51E7BF4200C0set_impl*
f_MinPicWidth := aValue;
//#UC END# *56023F490306_51E7BF4200C0set_impl*
end;//TddCustomRTFReader.pm_SetMinPicWidth
procedure TddCustomRTFReader.pm_SetMinPicHeight(aValue: Integer);
//#UC START# *56023F7A0028_51E7BF4200C0set_var*
//#UC END# *56023F7A0028_51E7BF4200C0set_var*
begin
//#UC START# *56023F7A0028_51E7BF4200C0set_impl*
f_MinPicHeight := aValue;
//#UC END# *56023F7A0028_51E7BF4200C0set_impl*
end;//TddCustomRTFReader.pm_SetMinPicHeight
procedure TddCustomRTFReader.pm_SetIdenticalRowWidths(aValue: Boolean);
//#UC START# *56162C9F01E8_51E7BF4200C0set_var*
//#UC END# *56162C9F01E8_51E7BF4200C0set_var*
begin
//#UC START# *56162C9F01E8_51E7BF4200C0set_impl*
f_IdenticalRowWidths := aValue;
//#UC END# *56162C9F01E8_51E7BF4200C0set_impl*
end;//TddCustomRTFReader.pm_SetIdenticalRowWidths
procedure TddCustomRTFReader.pm_SetReadURL(aValue: Boolean);
//#UC START# *56A86CFB0055_51E7BF4200C0set_var*
//#UC END# *56A86CFB0055_51E7BF4200C0set_var*
begin
//#UC START# *56A86CFB0055_51E7BF4200C0set_impl*
f_ReadURL := aValue;
//#UC END# *56A86CFB0055_51E7BF4200C0set_impl*
end;//TddCustomRTFReader.pm_SetReadURL
function TddCustomRTFReader.ListByID(aID: Integer;
out aWasRestart: Boolean): TrtfList;
//#UC START# *51E7C1E90092_51E7BF4200C0_var*
//#UC END# *51E7C1E90092_51E7BF4200C0_var*
begin
//#UC START# *51E7C1E90092_51E7BF4200C0_impl*
aWasRestart := False;
Result := nil;
//#UC END# *51E7C1E90092_51E7BF4200C0_impl*
end;//TddCustomRTFReader.ListByID
function TddCustomRTFReader.ColorByIndex(anIndex: Integer): TColor;
//#UC START# *51E7CF130368_51E7BF4200C0_var*
//#UC END# *51E7CF130368_51E7BF4200C0_var*
begin
//#UC START# *51E7CF130368_51E7BF4200C0_impl*
Result := 0;
//#UC END# *51E7CF130368_51E7BF4200C0_impl*
end;//TddCustomRTFReader.ColorByIndex
function TddCustomRTFReader.StyleByNumber(aNumber: Integer): TddStyleEntry;
//#UC START# *51E7CF89008F_51E7BF4200C0_var*
//#UC END# *51E7CF89008F_51E7BF4200C0_var*
begin
//#UC START# *51E7CF89008F_51E7BF4200C0_impl*
Result := nil;
//#UC END# *51E7CF89008F_51E7BF4200C0_impl*
end;//TddCustomRTFReader.StyleByNumber
function TddCustomRTFReader.GetFonts(anID: Integer): TddFontEntry;
//#UC START# *51E7CFC002AA_51E7BF4200C0_var*
//#UC END# *51E7CFC002AA_51E7BF4200C0_var*
begin
//#UC START# *51E7CFC002AA_51E7BF4200C0_impl*
Result := nil;
//#UC END# *51E7CFC002AA_51E7BF4200C0_impl*
end;//TddCustomRTFReader.GetFonts
function TddCustomRTFReader.NeedSkip(aPicture: TddPicture): TRTFPictureSkip;
//#UC START# *54E32B7D034A_51E7BF4200C0_var*
var
l_Format: Integer;
//#UC END# *54E32B7D034A_51E7BF4200C0_var*
begin
//#UC START# *54E32B7D034A_51E7BF4200C0_impl*
l_Format := aPicture.Format;
if not f_SkipPicture and (aPicture.Format > 0) and f_EnablePictures then
Result := rtf_psNo
else
if f_EnablePictures and f_SkipPicture then
if (l_Format = pictWMF) and f_ReadWMFIfExists then
Result := rtf_psWMF
else
Result := rtf_psYes
else
Result := rtf_psYes;
//#UC END# *54E32B7D034A_51E7BF4200C0_impl*
end;//TddCustomRTFReader.NeedSkip
procedure TddCustomRTFReader.IncNextFootnoteNumber;
//#UC START# *55012D100317_51E7BF4200C0_var*
//#UC END# *55012D100317_51E7BF4200C0_var*
begin
//#UC START# *55012D100317_51E7BF4200C0_impl*
Inc(f_NextFootnoteNumber);
//#UC END# *55012D100317_51E7BF4200C0_impl*
end;//TddCustomRTFReader.IncNextFootnoteNumber
procedure TddCustomRTFReader.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_51E7BF4200C0_var*
//#UC END# *479731C50290_51E7BF4200C0_var*
begin
//#UC START# *479731C50290_51E7BF4200C0_impl*
inherited;
f_SkipPicture := False;
f_EnablePictures := False;
f_ReadWMFIfExists := False;
f_IdenticalRowWidths := False;
f_MinPicWidth := ddDefMinimumPicWidth;
f_MinPicHeight := ddDefMinimumPicHeight;
//#UC END# *479731C50290_51E7BF4200C0_impl*
end;//TddCustomRTFReader.Cleanup
procedure TddCustomRTFReader.InitFields;
//#UC START# *47A042E100E2_51E7BF4200C0_var*
//#UC END# *47A042E100E2_51E7BF4200C0_var*
begin
//#UC START# *47A042E100E2_51E7BF4200C0_impl*
f_SkipPicture := False;
f_EnablePictures := False;
f_ReadWMFIfExists := False;
f_IdenticalRowWidths := False;
f_MinPicWidth := ddDefMinimumPicWidth;
f_MinPicHeight := ddDefMinimumPicHeight;
inherited;
//#UC END# *47A042E100E2_51E7BF4200C0_impl*
end;//TddCustomRTFReader.InitFields
end.
|
unit fmComputerInfo;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
System.StrUtils, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Winapi.ActiveX, ActiveDs_TLB, ADC.ADObject, ADC.Types, ADC.Common, ADC.AD, ADC.LDAP,
ADC.GlobalVar, ADC.ComputerEdit;
type
TForm_ComputerInfo = class(TForm)
Label_Name: TLabel;
Label_IPAddress: TLabel;
Edit_Name: TEdit;
Edit_IPv4_Address: TEdit;
Label_MACAddress: TLabel;
Edit_MAC_Address: TEdit;
Label_DHCP_Server: TLabel;
Edit_DHCP_Server: TEdit;
Button_Close: TButton;
Bevel1: TBevel;
Label_InvNumber: TLabel;
Edit_InvNumber: TEdit;
Button_Apply: TButton;
Button_OK: TButton;
Label_OS: TLabel;
Edit_OS: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button_CloseClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure Button_OKClick(Sender: TObject);
procedure Button_ApplyClick(Sender: TObject);
private
FCallingForm: TForm;
FObj: TADObject;
FCanClose: Boolean;
FObjEdit: TComputerEdit;
FOnComputerChange: TChangeComputerProc;
procedure SetCallingForm(const Value: TForm);
procedure SetObject(const Value: TADObject);
function SaveComputerInfo: Boolean;
public
property CallingForm: TForm write SetCallingForm;
property ComputerObject: TADObject read FObj write SetObject;
property OnComputerChange: TChangeComputerProc read FOnComputerChange write FOnComputerChange;
end;
var
Form_ComputerInfo: TForm_ComputerInfo;
implementation
{$R *.dfm}
{ TForm_ComputerInfo }
procedure TForm_ComputerInfo.Button_ApplyClick(Sender: TObject);
var
MsgBoxParam: TMsgBoxParams;
begin
with FObjEdit do
begin
employeeID := Edit_InvNumber.Text;
end;
try
FCanClose := SaveComputerInfo;
except
on E: Exception do
begin
with MsgBoxParam do
begin
cbSize := SizeOf(MsgBoxParam);
hwndOwner := Self.Handle;
hInstance := 0;
case apAPI of
ADC_API_LDAP: lpszCaption := PChar('LDAP Exception');
ADC_API_ADSI: lpszCaption := PChar('ADSI Exception');
end;
lpszIcon := MAKEINTRESOURCE(32513);
dwStyle := MB_OK or MB_ICONHAND;
dwContextHelpId := 0;
lpfnMsgBoxCallback := nil;
dwLanguageId := LANG_NEUTRAL;
lpszText := PChar(E.Message);
end;
MessageBoxIndirect(MsgBoxParam);
end;
end;
end;
procedure TForm_ComputerInfo.Button_CloseClick(Sender: TObject);
begin
Close;
end;
procedure TForm_ComputerInfo.Button_OKClick(Sender: TObject);
begin
Button_ApplyClick(Self);
if FCanClose then Close;
end;
procedure TForm_ComputerInfo.FormClose(Sender: TObject;
var Action: TCloseAction);
var
i: Integer;
begin
for i := 0 to Self.ControlCount - 1 do
if Self.Controls[i] is TEdit
then TEdit(Self.Controls[i]).Clear;
FObj := nil;
FCanClose := False;
if FCallingForm <> nil then
begin
FCallingForm.Enabled := True;
FCallingForm.Show;
FCallingForm := nil;
end;
end;
procedure TForm_ComputerInfo.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_F5: begin
SetObject(FObj);
end;
VK_UP: begin
if ActiveControl <> nil then
begin
if ActiveControl.ClassNameIs(TEdit.ClassName)
then SelectNext(ActiveControl, False, True);
end;
end;
VK_DOWN: begin
if ActiveControl <> nil then
begin
if ActiveControl.ClassNameIs(TEdit.ClassName)
then SelectNext(ActiveControl, True, True);
end;
end;
VK_ESCAPE: begin
Close;
end;
end;
end;
procedure TForm_ComputerInfo.FormShow(Sender: TObject);
begin
Button_Close.SetFocus;
end;
function TForm_ComputerInfo.SaveComputerInfo: Boolean;
begin
Result := False;
with FObjEdit do
begin
Clear;
employeeID := Edit_InvNumber.Text;
end;
try
case apAPI of
ADC_API_LDAP: FObjEdit.SetInfo(LDAPBinding, FObj.distinguishedName);
// ADC_API_ADSI: FObjEdit.SetInfo(ADSIBinding, FObj.distinguishedName);
ADC_API_ADSI: FObjEdit.SetInfoDS(ADSIBinding, FObj.distinguishedName);
end;
Result := True;
if Assigned(FOnComputerChange)
then FOnComputerChange(FObj);
finally
end;
end;
procedure TForm_ComputerInfo.SetCallingForm(const Value: TForm);
begin
FCallingForm := Value;
if FCallingForm <> nil
then FCallingForm.Enabled := False;
end;
procedure TForm_ComputerInfo.SetObject(const Value: TADObject);
var
infoIP: PIPAddr;
infoDHCP: PDHCPInfo;
sFormat: string;
sSrvName: string;
begin
FObj := Value;
if FObj <> nil then
begin
case apAPI of
ADC_API_LDAP: FObjEdit.GetInfo(LDAPBinding, FObj.distinguishedName);
ADC_API_ADSI: FObjEdit.GetInfo(ADSIBinding, FObj.distinguishedName);
end;
FObjEdit.GetExtendedInfo;
Edit_Name.Text := FObjEdit.dNSHostName;
Edit_IPv4_Address.Text := FObjEdit.IPv4;
if Length(FObjEdit.MAC_Address) > 0
then Edit_MAC_Address.Text := Format(
'%s | %s', [
FObjEdit.MAC_Address.Format(gfSixOfTwo, gsColon, True),
FObjEdit.MAC_Address.Format(gfThreeOfFour, gsDot)
]
);
Edit_DHCP_Server.Text := FObjEdit.DHCP_Server;
Edit_OS.Text := FObjEdit.operatingSystem + ' ' + FObjEdit.operatingSystemServicePack;
Edit_InvNumber.Text := FObjEdit.employeeID;
end;
end;
end.
|
program numberScales(input, output);
const
MAX_RADIX = 10;
MAX_LEN = 32;
type
radix = 2 .. MAX_RADIX;
var
datum : integer;
scale : radix;
procedure writenumber(num : integer; rad : radix);
var
jp, kp : 0 .. MAX_LEN;
buffer : array[1 .. MAX_LEN] of char;
begin
if num < 0 then begin
write('-');
num := abs(num)
end;
kp := 0;
repeat
kp := kp + 1;
buffer[kp] := chr(num mod rad + ord('0'));
num := num div rad
until num = 0;
for jp := kp downto 1 do write(buffer[jp])
end;
begin
read(datum);
writeln;
for scale := 2 to MAX_RADIX do begin
writenumber(datum, scale);
writeln();
end;
writeln
end. |
unit HashedStringList;
interface
uses
classes;
type
PPHashItem = ^PHashItem;
PHashItem = ^THashItem;
THashItem = record
Next: PHashItem;
Key: string;
Value: Integer;
end;
TStringHash = class
private
Buckets: array of PHashItem;
protected
function Find(const Key: string): PPHashItem;
function HashOf(const Key: string): Cardinal; virtual;
public
constructor Create(Size: Integer = 256);
destructor Destroy; override;
procedure Add(const Key: string; Value: Integer);
procedure Clear;
procedure Remove(const Key: string);
function Modify(const Key: string; Value: Integer): Boolean;
function ValueOf(const Key: string): Integer;
end;
{ THashedStringList - A TStringList that uses TStringHash to improve the
speed of Find }
THashedStringList = class(TStringList)
private
FValueHash: TStringHash;
FNameHash: TStringHash;
FValueHashValid: Boolean;
FNameHashValid: Boolean;
procedure UpdateValueHash;
procedure UpdateNameHash;
function GetValue(const Name: string): string;
procedure SetValue(const Name, Value: string);
protected
procedure Changed; override;
public
constructor Create;
destructor Destroy; override;
function IndexOf(const S: string): Integer; override;
function IndexOfName(const Name: string): Integer; //override;
property Values[const Name: string]: string read GetValue write SetValue;
end;
implementation
uses
sysutils;
{ TStringHash }
procedure TStringHash.Add(const Key: string; Value: Integer);
var
Hash: Integer;
Bucket: PHashItem;
begin
Hash := HashOf(Key) mod Cardinal(Length(Buckets));
New(Bucket);
Bucket^.Key := Key;
Bucket^.Value := Value;
Bucket^.Next := Buckets[Hash];
Buckets[Hash] := Bucket;
end;
procedure TStringHash.Clear;
var
I: Integer;
P, N: PHashItem;
begin
for I := 0 to Length(Buckets) - 1 do
begin
P := Buckets[I];
while P <> nil do
begin
N := P^.Next;
Dispose(P);
P := N;
end;
Buckets[I] := nil;
end;
end;
constructor TStringHash.Create(Size: Integer);
begin
inherited Create;
SetLength(Buckets, Size);
end;
destructor TStringHash.Destroy;
begin
Clear;
inherited;
end;
function TStringHash.Find(const Key: string): PPHashItem;
var
Hash: Integer;
begin
Hash := HashOf(Key) mod Cardinal(Length(Buckets));
Result := @Buckets[Hash];
while Result^ <> nil do
begin
if Result^.Key = Key then
Exit
else
Result := @Result^.Next;
end;
end;
function TStringHash.HashOf(const Key: string): Cardinal;
var
I: Integer;
begin
Result := 0;
for I := 1 to Length(Key) do
Result := ((Result shl 2) or (Result shr (SizeOf(Result) * 8 - 2))) xor
Ord(Key[I]);
end;
function TStringHash.Modify(const Key: string; Value: Integer): Boolean;
var
P: PHashItem;
begin
P := Find(Key)^;
if P <> nil then
begin
Result := True;
P^.Value := Value;
end
else
Result := False;
end;
procedure TStringHash.Remove(const Key: string);
var
P: PHashItem;
Prev: PPHashItem;
begin
Prev := Find(Key);
P := Prev^;
if P <> nil then
begin
Prev^ := P^.Next;
Dispose(P);
end;
end;
function TStringHash.ValueOf(const Key: string): Integer;
var
P: PHashItem;
begin
P := Find(Key)^;
if P <> nil then
Result := P^.Value else
Result := -1;
end;
{ THashedStringList }
function THashedStringList.GetValue(const Name: string): string;
var
I: Integer;
begin
I := IndexOfName(Name);
if I >= 0 then
Result := Copy(Get(I), Length(Name) + 2, MaxInt) else
Result := '';
end;
procedure THashedStringList.SetValue(const Name, Value: string);
var
I: Integer;
begin
I := IndexOfName(Name);
if Value <> '' then
begin
if I < 0 then I := Add('');
Put(I, Name + '=' + Value);
end else
begin
if I >= 0 then Delete(I);
end;
end;
procedure THashedStringList.Changed;
begin
inherited;
FValueHashValid := False;
FNameHashValid := False;
end;
constructor THashedStringList.Create;
begin
inherited;
Duplicates := dupIgnore;
end;
destructor THashedStringList.Destroy;
begin
FValueHash.Free;
FNameHash.Free;
inherited;
end;
function THashedStringList.IndexOf(const S: string): Integer;
begin
UpdateValueHash;
// if not CaseSensitive then
Result := FValueHash.ValueOf({AnsiUpperCase}(S))
// else
// Result := FValueHash.ValueOf(S);
end;
function THashedStringList.IndexOfName(const Name: string): Integer;
begin
UpdateNameHash;
// if not CaseSensitive then
Result := FNameHash.ValueOf({AnsiUpperCase}(Name))
// else
// Result := FNameHash.ValueOf(Name);
end;
procedure THashedStringList.UpdateNameHash;
var
I: Integer;
P: Integer;
Key: string;
begin
if FNameHashValid then Exit;
if FNameHash = nil then
FNameHash := TStringHash.Create
else
FNameHash.Clear;
for I := 0 to Count - 1 do
begin
Key := Get(I);
P := AnsiPos('=', Key);
if P <> 0 then
begin
// if not CaseSensitive then
Key := {AnsiUpperCase}(Copy(Key, 1, P - 1));
// else
// Key := Copy(Key, 1, P - 1);
FNameHash.Add(Key, I);
end;
end;
FNameHashValid := True;
end;
procedure THashedStringList.UpdateValueHash;
var
I: Integer;
begin
if FValueHashValid then Exit;
if FValueHash = nil then
FValueHash := TStringHash.Create
else
FValueHash.Clear;
for I := 0 to Count - 1 do
// if not CaseSensitive then
FValueHash.Add({AnsiUpperCase}(Self[I]), I);
// else
// FValueHash.Add(Self[I], I);
FValueHashValid := True;
end;
end.
|
unit enet_peer;
(**
@file peer.c
@brief ENet peer management functions
freepascal
1.3.14
*)
{$GOTO ON}
interface
uses enet_consts, enet_socket, enet_list, enet_packet;
procedure enet_peer_disconnect (peer : pENetPeer; data : enet_uint32);
procedure enet_peer_disconnect_later (peer : pENetPeer;data : enet_uint32);
procedure enet_peer_disconnect_now (peer : pENetPeer;data : enet_uint32);
procedure enet_peer_ping (peer : pENetPeer);
function enet_peer_queue_acknowledgement (peer : pENetPeer; command : pENetProtocol; sentTime : enet_uint16):pENetAcknowledgement;
function enet_peer_queue_incoming_command (peer:pENetPeer; command: pENetProtocol; data:Pointer; dataLength: sizeint; flags, fragmentCount: enet_uint32):pENetIncomingCommand;
function enet_peer_queue_outgoing_command (peer : pENetPeer;command : pENetProtocol;packet : pENetPacket;offset : enet_uint32;length : enet_uint16):pENetOutgoingCommand;
function enet_peer_receive (peer : pENetPeer; channelID : penet_uint8):pENetPacket;
procedure enet_peer_reset (peer : pENetPeer);
procedure enet_peer_reset_incoming_commands (queue : pENetList);
procedure enet_peer_reset_outgoing_commands (queue : pENetList);
procedure enet_peer_reset_queues (peer : pENetPeer);
function enet_peer_send (peer : pENetPeer;channelID : enet_uint8;packet : pENetPacket):integer;
function enet_peer_throttle (peer : pENetPeer;rtt : enet_uint32):integer;
procedure enet_peer_throttle_configure (peer : pENetPeer;interval : enet_uint32;acceleration : enet_uint32;deceleration : enet_uint32);
procedure enet_peer_dispatch_incoming_reliable_commands (peer:pENetPeer; channel:pENetChannel);
procedure enet_peer_dispatch_incoming_unreliable_commands (peer:pENetPeer; channel:pENetChannel);
procedure enet_peer_setup_outgoing_command (peer:pENetPeer; outgoingCommand:pENetOutgoingCommand);
procedure enet_peer_on_connect (peer:pENetPeer);
procedure enet_peer_on_disconnect (peer:pENetPeer);
implementation
uses enet_host, enet_protocol, enet_callbacks;
(** @defgroup peer ENet peer functions
@{
*)
(** Configures throttle parameter for a peer.
Unreliable packets are dropped by ENet in response to the varying conditions
of the Internet connection to the peer. The throttle represents a probability
that an unreliable packet should not be dropped and thus sent by ENet to the peer.
The lowest mean round trip time from the sending of a reliable packet to the
receipt of its acknowledgement is measured over an amount of time specified by
the interval parameter in milliseconds. If a measured round trip time happens to
be significantly less than the mean round trip time measured over the interval,
then the throttle probability is increased to allow more traffic by an amount
specified in the acceleration parameter, which is a ratio to the ENET_PEER_PACKET_THROTTLE_SCALE
constant. If a measured round trip time happens to be significantly greater than
the mean round trip time measured over the interval, then the throttle probability
is decreased to limit traffic by an amount specified in the deceleration parameter, which
is a ratio to the ENET_PEER_PACKET_THROTTLE_SCALE constant. When the throttle has
a value of ENET_PEER_PACKET_THROTTLE_SCALE, on unreliable packets are dropped by
ENet, and so 100% of all unreliable packets will be sent. When the throttle has a
value of 0, all unreliable packets are dropped by ENet, and so 0% of all unreliable
packets will be sent. Intermediate values for the throttle represent intermediate
probabilities between 0% and 100% of unreliable packets being sent. The bandwidth
limits of the local and foreign hosts are taken into account to determine a
sensible limit for the throttle probability above which it should not raise even in
the best of conditions.
@param peer peer to configure
@param interval interval, in milliseconds, over which to measure lowest mean RTT; the default value is ENET_PEER_PACKET_THROTTLE_INTERVAL.
@param acceleration rate at which to increase the throttle probability as mean RTT declines
@param deceleration rate at which to decrease the throttle probability as mean RTT increases
*)
procedure enet_peer_throttle_configure (peer : pENetPeer;interval : enet_uint32;acceleration : enet_uint32;deceleration : enet_uint32);
var
command : ENetProtocol;
begin
peer^. packetThrottleInterval := interval;
peer^. packetThrottleAcceleration := acceleration;
peer^. packetThrottleDeceleration := deceleration;
command.header.command := ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE or ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
command.header.channelID := $FF;
command.throttleConfigure.packetThrottleInterval := ENET_HOST_TO_NET_32 (interval);
command.throttleConfigure.packetThrottleAcceleration := ENET_HOST_TO_NET_32 (acceleration);
command.throttleConfigure.packetThrottleDeceleration := ENET_HOST_TO_NET_32 (deceleration);
enet_peer_queue_outgoing_command (peer, @command, nil, 0, 0);
end;
function enet_peer_throttle (peer : pENetPeer;rtt : enet_uint32):integer;
begin
if (peer^. lastRoundTripTime <= peer^. lastRoundTripTimeVariance) then
begin
peer^. packetThrottle := peer^. packetThrottleLimit;
end
else
if (rtt < peer^. lastRoundTripTime) then
begin
inc(peer^. packetThrottle , peer^. packetThrottleAcceleration);
if (peer^. packetThrottle > peer^. packetThrottleLimit) then
peer^. packetThrottle := peer^. packetThrottleLimit;
result := 1; exit;
end
else
if rtt > (peer^. lastRoundTripTime + 2 * peer^. lastRoundTripTimeVariance) then
begin
if (peer^. packetThrottle > peer^. packetThrottleDeceleration) then
dec(peer^. packetThrottle, peer^. packetThrottleDeceleration)
else
peer^. packetThrottle := 0;
result := -1; exit;
end;
result := 0;
end;
(** Queues a packet to be sent.
@param peer destination for the packet
@param channelID channel on which to send
@param packet packet to send
@retval 0 on success
@retval < 0 on failure
*)
function enet_peer_send (peer : pENetPeer;channelID : enet_uint8;packet : pENetPacket):integer;
var
channel : pENetChannel;
command : ENetProtocol;
fragmentLength : enet_size_t;
startSequenceNumber : enet_uint16;
fragmentCount, fragmentNumber, fragmentOffset : enet_uint32;
commandNumber : enet_uint8;
fragments : ENetList;
fragment : pENetOutgoingCommand;
begin
channel := pENetChannel( @ pENetChannelArray(peer^. channels)^[channelID]);
if (peer^. state <> ENET_PEER_STATE_CONNECTED) or
(channelID >= peer ^. channelCount) or
(packet ^. dataLength > peer ^. host ^. maximumPacketSize) then
begin result := -1; exit; end;
fragmentLength := peer^. mtu - sizeof (ENetProtocolHeader) - sizeof (ENetProtocolSendFragment);
if (peer ^. host ^. checksumfunc <> nil) then
fragmentLength := fragmentLength - sizeof(enet_uint32);
if (packet^. dataLength > fragmentLength) then
begin
fragmentCount := (packet ^. dataLength + fragmentLength - 1) div fragmentLength;
if (fragmentCount > ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT) then
begin
Result:=-1; exit;
end;
if (packet ^. flags and (ENET_PACKET_FLAG_RELIABLE or ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) = ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) and
(channel ^. outgoingUnreliableSequenceNumber < $0FFFF) then
begin
commandNumber := ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT;
startSequenceNumber := ENET_HOST_TO_NET_16 (channel ^. outgoingUnreliableSequenceNumber + 1);
end
else
begin
commandNumber := ENET_PROTOCOL_COMMAND_SEND_FRAGMENT or ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
startSequenceNumber := ENET_HOST_TO_NET_16 (channel ^. outgoingReliableSequenceNumber + 1);
end;
enet_list_clear (@ fragments);
fragmentNumber := 0;
fragmentOffset := 0;
while fragmentOffset < packet ^. dataLength do
begin
if (packet ^. dataLength - fragmentOffset < fragmentLength) then
fragmentLength := packet ^. dataLength - fragmentOffset;
fragment := pENetOutgoingCommand (enet_malloc (sizeof (ENetOutgoingCommand)));
if (fragment = nil ) then
begin
while (not enet_list_empty (@ fragments)) do
begin
fragment := pENetOutgoingCommand ( enet_list_remove (enet_list_begin (@ fragments)));
enet_free (fragment);
end;
result := -1; exit;
end;
fragment ^. fragmentOffset := fragmentOffset;
fragment ^. fragmentLength := fragmentLength;
fragment ^. packet := packet;
fragment ^. command.header.command := commandNumber;
fragment ^. command.header.channelID := channelID;
fragment ^. command.sendFragment.startSequenceNumber := startSequenceNumber;
fragment ^. command.sendFragment.dataLength := ENET_HOST_TO_NET_16 (fragmentLength);
fragment ^. command.sendFragment.fragmentCount := ENET_HOST_TO_NET_32 (fragmentCount);
fragment ^. command.sendFragment.fragmentNumber := ENET_HOST_TO_NET_32 (fragmentNumber);
fragment ^. command.sendFragment.totalLength := ENET_HOST_TO_NET_32 (packet ^. dataLength);
fragment ^. command.sendFragment.fragmentOffset := ENET_NET_TO_HOST_32 (fragmentOffset);
enet_list_insert (enet_list_end (@ fragments), fragment);
inc(fragmentNumber);
inc(fragmentOffset, fragmentLength);
end;
Inc(packet ^. referenceCount, fragmentNumber);
while (not enet_list_empty (@ fragments)) do
begin
fragment := pENetOutgoingCommand ( enet_list_remove (enet_list_begin (@ fragments)));
enet_peer_setup_outgoing_command (peer, fragment);
end;
Result:=0; exit;
end;
command.header.channelID := channelID;
if ((packet ^. flags and (ENET_PACKET_FLAG_RELIABLE or ENET_PACKET_FLAG_UNSEQUENCED)) = ENET_PACKET_FLAG_UNSEQUENCED) then
begin
command.header.command := ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED or ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
command.sendUnsequenced.dataLength := ENET_HOST_TO_NET_16 (packet^. dataLength);
end
else
if (packet ^. flags and ENET_PACKET_FLAG_RELIABLE<>0) or (channel ^. outgoingUnreliableSequenceNumber >= $0FFFF) then
begin
command.header.command := ENET_PROTOCOL_COMMAND_SEND_RELIABLE or ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
command.sendReliable.dataLength := ENET_HOST_TO_NET_16 (packet ^. dataLength);
end
else
begin
command.header.command := ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE;
command.sendUnreliable.dataLength := ENET_HOST_TO_NET_16 (packet^. dataLength);
end;
if (enet_peer_queue_outgoing_command (peer, @ command, packet, 0, packet ^. dataLength) = nil) then
begin
Result:=-1; exit;
end;
result := 0;
end;
(** Attempts to dequeue any incoming queued packet.
@param peer peer to dequeue packets from
@param channelID holds the channel ID of the channel the packet was received on success
@returns a pointer to the packet, or NULL if there are no available incoming queued packets
*)
function enet_peer_receive (peer : pENetPeer; channelID : penet_uint8):pENetPacket;
var
incomingCommand : pENetIncomingCommand;
begin
Result:=nil;
if (enet_list_empty (@ peer ^. dispatchedCommands)) then
exit;
incomingCommand := pENetIncomingCommand (enet_list_remove (enet_list_begin (@ peer ^. dispatchedCommands)));
if (channelID <> nil) then
channelID^ := incomingCommand ^. command.header.channelID;
Result := incomingCommand^. packet;
Dec(Result ^. referenceCount);
if (incomingCommand^. fragments <> nil) then
enet_free (incomingCommand^. fragments);
enet_free (incomingCommand);
Dec(peer ^. totalWaitingData , Result ^. dataLength);
end;
procedure enet_peer_reset_outgoing_commands (queue : pENetList);
var
outgoingCommand : pENetOutgoingCommand;
begin
while (not enet_list_empty (queue)) do
begin
outgoingCommand := pENetOutgoingCommand (enet_list_remove (ENetListIterator(enet_list_begin (queue))));
if (outgoingCommand^. packet <> nil) then
begin
Dec(outgoingCommand^. packet^. referenceCount);
if (outgoingCommand^. packet^. referenceCount = 0) then
enet_packet_destroy (outgoingCommand^. packet);
end;
enet_free (outgoingCommand);
end;
end;
procedure enet_peer_remove_incoming_commands (queue : pENetList; startCommand, endCommand : ENetListIterator);
var
currentCommand : ENetListIterator;
incomingCommand : pENetIncomingCommand;
begin
currentCommand:=startCommand;
while (PChar(currentCommand)<>PChar(endCommand)) do
begin
incomingCommand := pENetIncomingCommand (currentCommand);
currentCommand := enet_list_next (currentCommand);
enet_list_remove (@ incomingCommand ^. incomingCommandList);
if (incomingCommand^. packet <> nil) then
begin
Dec(incomingCommand^. packet^. referenceCount);
if (incomingCommand^. packet^. referenceCount = 0) then
enet_packet_destroy (incomingCommand^. packet);
end;
if (incomingCommand^. fragments <> nil) then
enet_free (incomingCommand^. fragments);
enet_free (incomingCommand);
end;
end;
procedure enet_peer_reset_incoming_commands (queue:pENetList);
begin
enet_peer_remove_incoming_commands(queue, enet_list_begin (queue), enet_list_end (queue));
end;
procedure enet_peer_reset_queues (peer : pENetPeer);
var
channel : pENetChannel;
begin
if (peer ^. needsDispatch <> 0) then
begin
enet_list_remove (@ peer ^. dispatchList);
peer ^. needsDispatch := 0;
end;
while (not enet_list_empty (@peer^. acknowledgements)) do
enet_free (enet_list_remove (ENetListIterator(enet_list_begin (@ peer^. acknowledgements))));
enet_peer_reset_outgoing_commands (@peer ^. sentReliableCommands);
enet_peer_reset_outgoing_commands (@peer ^. sentUnreliableCommands);
enet_peer_reset_outgoing_commands (@peer ^. outgoingReliableCommands);
enet_peer_reset_outgoing_commands (@peer ^. outgoingUnreliableCommands);
enet_peer_reset_incoming_commands (@peer ^. dispatchedCommands);
if (peer^. channels <> nil) and (peer^. channelCount > 0) then
begin
channel := peer^. channels;
while PChar(channel) < PChar(@ pENetChannelArray(peer^. channels)^[peer^. channelCount]) do
begin
enet_peer_reset_incoming_commands (@ channel^. incomingReliableCommands);
enet_peer_reset_incoming_commands (@ channel^. incomingUnreliableCommands);
inc(channel);
end;
enet_free (peer^. channels);
end;
peer^. channels := nil;
peer^. channelCount := 0;
end;
procedure enet_peer_on_connect (peer:pENetPeer);
begin
if ((peer ^. state <> ENET_PEER_STATE_CONNECTED) and (peer ^. state <> ENET_PEER_STATE_DISCONNECT_LATER)) then
begin
if (peer ^. incomingBandwidth <> 0) then
Inc(peer ^. host ^. bandwidthLimitedPeers);
Inc(peer ^. host ^. connectedPeers);
end;
end;
procedure enet_peer_on_disconnect (peer:pENetPeer);
begin
if ((peer ^. state = ENET_PEER_STATE_CONNECTED) or (peer ^. state = ENET_PEER_STATE_DISCONNECT_LATER)) then
begin
if (peer ^. incomingBandwidth <> 0) then
Dec(peer ^. host ^. bandwidthLimitedPeers);
Dec(peer ^. host ^. connectedPeers);
end;
end;
(** Forcefully disconnects a peer.
@param peer peer to forcefully disconnect
@remarks The foreign host represented by the peer is not notified of the disconnection and will timeout
on its connection to the local host.
*)
procedure enet_peer_reset (peer : pENetPeer);
begin
enet_peer_on_disconnect (peer);
peer^. outgoingPeerID := ENET_PROTOCOL_MAXIMUM_PEER_ID;
peer^. connectID := 0;
peer^. state := ENET_PEER_STATE_DISCONNECTED;
peer^. incomingBandwidth := 0;
peer^. outgoingBandwidth := 0;
peer^. incomingBandwidthThrottleEpoch := 0;
peer^. outgoingBandwidthThrottleEpoch := 0;
peer^. incomingDataTotal := 0;
peer^. outgoingDataTotal := 0;
peer^. lastSendTime := 0;
peer^. lastReceiveTime := 0;
peer^. nextTimeout := 0;
peer^. earliestTimeout := 0;
peer^. packetLossEpoch := 0;
peer^. packetsSent := 0;
peer^. packetsLost := 0;
peer^. packetLoss := 0;
peer^. packetLossVariance := 0;
peer^. packetThrottle := ENET_PEER_DEFAULT_PACKET_THROTTLE;
peer^. packetThrottleLimit := ENET_PEER_PACKET_THROTTLE_SCALE;
peer^. packetThrottleCounter := 0;
peer^. packetThrottleEpoch := 0;
peer^. packetThrottleAcceleration := ENET_PEER_PACKET_THROTTLE_ACCELERATION;
peer^. packetThrottleDeceleration := ENET_PEER_PACKET_THROTTLE_DECELERATION;
peer^. packetThrottleInterval := ENET_PEER_PACKET_THROTTLE_INTERVAL;
peer^. pingInterval := ENET_PEER_PING_INTERVAL_;
peer^. timeoutLimit := ENET_PEER_TIMEOUT_LIMIT;
peer^. timeoutMinimum := ENET_PEER_TIMEOUT_MINIMUM;
peer^. timeoutMaximum := ENET_PEER_TIMEOUT_MAXIMUM;
peer^. lastRoundTripTime := ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
peer^. lowestRoundTripTime := ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
peer^. lastRoundTripTimeVariance := 0;
peer^. highestRoundTripTimeVariance := 0;
peer^. roundTripTime := ENET_PEER_DEFAULT_ROUND_TRIP_TIME;
peer^. roundTripTimeVariance := 0;
peer^. mtu := peer^. host^. mtu;
peer^. reliableDataInTransit := 0;
peer^. outgoingReliableSequenceNumber := 0;
peer^. windowSize := ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
peer^. incomingUnsequencedGroup := 0;
peer^. outgoingUnsequencedGroup := 0;
peer^. eventData := 0;
peer^. totalWaitingData := 0;
fillchar (peer^. unsequencedWindow[0], sizeof (peer^. unsequencedWindow), 0);
enet_peer_reset_queues (peer);
end;
(** Sends a ping request to a peer.
@param peer destination for the ping request
@remarks ping requests factor into the mean round trip time as designated by the
roundTripTime field in the ENetPeer structure. Enet automatically pings all connected
peers at regular intervals, however, this function may be called to ensure more
frequent ping requests.
*)
procedure enet_peer_ping (peer : pENetPeer);
var
command : ENetProtocol;
begin
if (peer^. state <> ENET_PEER_STATE_CONNECTED) then
exit;
command.header.command := ENET_PROTOCOL_COMMAND_PING or ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
command.header.channelID := $FF;
enet_peer_queue_outgoing_command (peer, @ command, nil, 0, 0);
end;
(** Sets the interval at which pings will be sent to a peer.
Pings are used both to monitor the liveness of the connection and also to dynamically
adjust the throttle during periods of low traffic so that the throttle has reasonable
responsiveness during traffic spikes.
@param peer the peer to adjust
@param pingInterval the interval at which to send pings; defaults to ENET_PEER_PING_INTERVAL if 0
*)
procedure enet_peer_ping_interval (peer:pENetPeer; pingInterval : enet_uint32 );
begin
if pingInterval<>0 then
peer^. pingInterval := pingInterval
else peer^. pingInterval := ENET_PEER_PING_INTERVAL_;
end;
(** Sets the timeout parameters for a peer.
The timeout parameter control how and when a peer will timeout from a failure to acknowledge
reliable traffic. Timeout values use an exponential backoff mechanism, where if a reliable
packet is not acknowledge within some multiple of the average RTT plus a variance tolerance,
the timeout will be doubled until it reaches a set limit. If the timeout is thus at this
limit and reliable packets have been sent but not acknowledged within a certain minimum time
period, the peer will be disconnected. Alternatively, if reliable packets have been sent
but not acknowledged for a certain maximum time period, the peer will be disconnected regardless
of the current timeout limit value.
@param peer the peer to adjust
@param timeoutLimit the timeout limit; defaults to ENET_PEER_TIMEOUT_LIMIT if 0
@param timeoutMinimum the timeout minimum; defaults to ENET_PEER_TIMEOUT_MINIMUM if 0
@param timeoutMaximum the timeout maximum; defaults to ENET_PEER_TIMEOUT_MAXIMUM if 0
*)
procedure enet_peer_timeout (peer:pENetPeer; timeoutLimit, timeoutMinimum, timeoutMaximum : enet_uint32);
begin
if timeoutLimit<>0 then
peer^. timeoutLimit := timeoutLimit
else peer^. timeoutLimit := ENET_PEER_TIMEOUT_LIMIT;
if timeoutMinimum<>0 then
peer^. timeoutMinimum := timeoutMinimum
else peer^. timeoutMinimum := ENET_PEER_TIMEOUT_MINIMUM;
if timeoutMaximum<>0 then
peer^. timeoutMaximum := timeoutMaximum
else peer^. timeoutMaximum := ENET_PEER_TIMEOUT_MAXIMUM;
end;
(** Force an immediate disconnection from a peer.
@param peer peer to disconnect
@param data data describing the disconnection
@remarks No ENET_EVENT_DISCONNECT event will be generated. The foreign peer is not
guarenteed to receive the disconnect notification, and is reset immediately upon
return from this function.
*)
procedure enet_peer_disconnect_now (peer : pENetPeer;data : enet_uint32);
var
command : ENetProtocol;
begin
if (peer^. state = ENET_PEER_STATE_DISCONNECTED) then
exit;
if (peer^. state <> ENET_PEER_STATE_ZOMBIE) and
(peer^. state <> ENET_PEER_STATE_DISCONNECTING) then
begin
enet_peer_reset_queues (peer);
command.header.command := ENET_PROTOCOL_COMMAND_DISCONNECT or ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
command.header.channelID := $FF;
command.disconnect.data := ENET_HOST_TO_NET_32 (data);
enet_peer_queue_outgoing_command (peer, @ command, nil, 0, 0);
enet_host_flush (peer^. host);
end;
enet_peer_reset (peer);
end;
(** Request a disconnection from a peer.
@param peer peer to request a disconnection
@param data data describing the disconnection
@remarks An ENET_EVENT_DISCONNECT event will be generated by enet_host_service()
once the disconnection is complete.
*)
procedure enet_peer_disconnect (peer : pENetPeer; data : enet_uint32);
var
command : ENetProtocol;
begin
if (peer^. state = ENET_PEER_STATE_DISCONNECTING) or
(peer^. state = ENET_PEER_STATE_DISCONNECTED) or
(peer^. state = ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT) or
(peer^. state = ENET_PEER_STATE_ZOMBIE) then
exit;
enet_peer_reset_queues (peer);
command.header.command := ENET_PROTOCOL_COMMAND_DISCONNECT;
command.header.channelID := $FF;
command.disconnect.data := ENET_HOST_TO_NET_32 (data);
if (peer^. state = ENET_PEER_STATE_CONNECTED) or (peer^. state = ENET_PEER_STATE_DISCONNECT_LATER) then
command.header.command := command.header.command or ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE
else
command.header.command := command.header.command or ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED;
enet_peer_queue_outgoing_command (peer, @ command, nil, 0, 0);
if (peer^. state = ENET_PEER_STATE_CONNECTED) or (peer^. state = ENET_PEER_STATE_DISCONNECT_LATER) then
begin
enet_peer_on_disconnect (peer);
peer ^. state := ENET_PEER_STATE_DISCONNECTING;
end
else
begin
enet_host_flush (peer^. host);
enet_peer_reset (peer);
end;
end;
(** Request a disconnection from a peer, but only after all queued outgoing packets are sent.
@param peer peer to request a disconnection
@param data data describing the disconnection
@remarks An ENET_EVENT_DISCONNECT event will be generated by enet_host_service()
once the disconnection is complete.
*)
procedure enet_peer_disconnect_later (peer : pENetPeer;data : enet_uint32);
begin
if ((peer^. state = ENET_PEER_STATE_CONNECTED) or (peer^. state = ENET_PEER_STATE_DISCONNECT_LATER)) and
(not (enet_list_empty (@ peer^. outgoingReliableCommands) and
enet_list_empty (@ peer^. outgoingUnreliableCommands) and
enet_list_empty (@ peer^. sentReliableCommands))) then
begin
peer^. state := ENET_PEER_STATE_DISCONNECT_LATER;
peer^. eventData := data;
end
else
enet_peer_disconnect (peer, data);
end;
function enet_peer_queue_acknowledgement (peer : pENetPeer; command : pENetProtocol; sentTime : enet_uint16):pENetAcknowledgement;
var
//acknowledgement : pENetAcknowledgement;
channel : pENetChannel;
reliableWindow, currentWindow : enet_uint16;
begin
Result:=nil;
if (command^. header.channelID < peer^. channelCount) then
begin
channel := @(pENetChannelArray(peer^. channels)^[command^. header.channelID]);
reliableWindow := command^. header.reliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE;
currentWindow := channel^. incomingReliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE;
if (command^. header.reliableSequenceNumber < channel^. incomingReliableSequenceNumber) then
inc(reliableWindow , ENET_PEER_RELIABLE_WINDOWS);
if (reliableWindow >= (currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)) and (reliableWindow <= (currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS)) then // 2007/10/22
begin result := nil; exit; end;
end;
Result := pENetAcknowledgement( enet_malloc (sizeof (ENetAcknowledgement)));
if (Result = nil) then
exit;
Inc(peer^. outgoingDataTotal , sizeof (ENetProtocolAcknowledge));
Result^. sentTime := sentTime;
Result^. command := command^;
enet_list_insert (enet_list_end (@ peer^. acknowledgements), pENetListNode(Result));
end;
procedure enet_peer_setup_outgoing_command (peer:pENetPeer; outgoingCommand:pENetOutgoingCommand);
var
channel : pENetChannel;
begin
channel := @ (pENetChannelArray(peer^. channels)^[outgoingCommand^. command.header.channelID]);
Inc(peer^. outgoingDataTotal , enet_protocol_command_size (outgoingCommand^. command.header.command) + outgoingCommand^. fragmentLength);
if (outgoingCommand^. command.header.channelID = $0FF) then
begin
inc( peer^. outgoingReliableSequenceNumber);
outgoingCommand^. reliableSequenceNumber := peer^. outgoingReliableSequenceNumber;
outgoingCommand^. unreliableSequenceNumber := 0;
end
else
if (outgoingCommand^. command.header.command and ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE <> 0) then
begin
inc( channel^. outgoingReliableSequenceNumber);
channel^. outgoingUnreliableSequenceNumber := 0;
outgoingCommand^. reliableSequenceNumber := channel^. outgoingReliableSequenceNumber;
outgoingCommand^. unreliableSequenceNumber := 0;
end
else
if (outgoingCommand^. command.header.command and ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED <> 0) then
begin
inc( peer^. outgoingUnsequencedGroup);
outgoingCommand^. reliableSequenceNumber := 0;
outgoingCommand^. unreliableSequenceNumber := 0;
end
else
begin
if (outgoingCommand^. fragmentOffset = 0) then
inc( channel^. outgoingUnreliableSequenceNumber);
outgoingCommand^. reliableSequenceNumber := channel^. outgoingReliableSequenceNumber;
outgoingCommand^. unreliableSequenceNumber := channel^. outgoingUnreliableSequenceNumber;
end;
outgoingCommand^. sendAttempts := 0;
outgoingCommand^. sentTime := 0;
outgoingCommand^. roundTripTimeout := 0;
outgoingCommand^. roundTripTimeoutLimit := 0;
outgoingCommand^. command.header.reliableSequenceNumber := ENET_HOST_TO_NET_16 (outgoingCommand^. reliableSequenceNumber);
case (outgoingCommand^. command.header.command and ENET_PROTOCOL_COMMAND_MASK) of
ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE:
outgoingCommand^. command.sendUnreliable.unreliableSequenceNumber := ENET_HOST_TO_NET_16 (outgoingCommand^. unreliableSequenceNumber);
ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED:
outgoingCommand^. command.sendUnsequenced.unsequencedGroup := ENET_HOST_TO_NET_16 (peer^. outgoingUnsequencedGroup);
end;
if (outgoingCommand^. command.header.command and ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE <> 0) then
enet_list_insert (enet_list_end (@ peer^. outgoingReliableCommands), pENetListNode(outgoingCommand))
else
enet_list_insert (enet_list_end (@ peer^. outgoingUnreliableCommands), pENetListNode(outgoingCommand));
end;
function enet_peer_queue_outgoing_command (peer:pENetPeer; command:pENetProtocol; packet:pENetPacket; offset:enet_uint32; length:enet_uint16):pENetOutgoingCommand;
begin
Result := pENetOutgoingCommand ( enet_malloc (sizeof (ENetOutgoingCommand)));
if (Result = nil) then
exit;
Result^. command := command^;
Result^. fragmentOffset := offset;
Result^. fragmentLength := length;
Result^. packet := packet;
if (packet <> nil) then
Inc(packet^. referenceCount);
enet_peer_setup_outgoing_command (peer, Result);
end;
procedure enet_peer_dispatch_incoming_unreliable_commands (peer:pENetPeer; channel:pENetChannel);
var
droppedCommand, startCommand, currentCommand : ENetListIterator;
incomingCommand : pENetIncomingCommand;
reliableWindow, currentWindow : enet_uint16;
label
continue1;
begin
droppedCommand:=enet_list_begin (@ channel^. incomingUnreliableCommands);
startCommand:=droppedCommand;
currentCommand:=droppedCommand;
while currentCommand <> enet_list_end (@ channel^. incomingUnreliableCommands) do
begin
incomingCommand := pENetIncomingCommand (currentCommand);
if ((incomingCommand^. command.header.command and ENET_PROTOCOL_COMMAND_MASK) = ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) then
goto continue1;
if (incomingCommand^. reliableSequenceNumber = channel^. incomingReliableSequenceNumber) then
begin
if (incomingCommand^. fragmentsRemaining <= 0) then
begin
channel^. incomingUnreliableSequenceNumber := incomingCommand^. unreliableSequenceNumber;
goto continue1;
end;
if (startCommand <> currentCommand) then
begin
enet_list_move (enet_list_end (@ peer^. dispatchedCommands), startCommand, enet_list_previous (currentCommand));
if (peer^. needsDispatch=0) then
begin
enet_list_insert (enet_list_end (@ peer^. host^. dispatchQueue), @ peer^. dispatchList);
peer^. needsDispatch := 1;
end;
droppedCommand := currentCommand;
end
else
if (droppedCommand <> currentCommand) then
droppedCommand := enet_list_previous (currentCommand);
end
else
begin
reliableWindow := incomingCommand^. reliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE;
currentWindow := channel^. incomingReliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE;
if (incomingCommand^. reliableSequenceNumber < channel^. incomingReliableSequenceNumber) then
Inc(reliableWindow ,ENET_PEER_RELIABLE_WINDOWS);
if (reliableWindow >= currentWindow) and (reliableWindow < currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1) then
break;
droppedCommand := enet_list_next (currentCommand);
if (startCommand <> currentCommand) then
begin
enet_list_move (enet_list_end (@ peer^. dispatchedCommands), startCommand, enet_list_previous (currentCommand));
if (peer^. needsDispatch=0) then
begin
enet_list_insert (enet_list_end (@ peer^. host^. dispatchQueue), @ peer^. dispatchList);
peer^. needsDispatch := 1;
end;
end;
end;
startCommand := enet_list_next (currentCommand);
continue1:
currentCommand := enet_list_next (currentCommand);
end;
if (startCommand <> currentCommand) then
begin
enet_list_move (enet_list_end (@ peer^. dispatchedCommands), startCommand, enet_list_previous (currentCommand));
if (peer^. needsDispatch=0) then
begin
enet_list_insert (enet_list_end (@ peer^. host^. dispatchQueue), @ peer^. dispatchList);
peer^. needsDispatch := 1;
end;
droppedCommand := currentCommand;
end;
enet_peer_remove_incoming_commands (@channel^. incomingUnreliableCommands, enet_list_begin (@ channel^. incomingUnreliableCommands), droppedCommand);
end;
procedure enet_peer_dispatch_incoming_reliable_commands (peer:pENetPeer; channel:pENetChannel);
var
currentCommand : ENetListIterator;
incomingCommand : pENetIncomingCommand;
begin
currentCommand:=enet_list_begin (@ channel^. incomingReliableCommands);
while currentCommand <> enet_list_end (@ channel^. incomingReliableCommands) do
begin
incomingCommand := pENetIncomingCommand ( currentCommand );
if (incomingCommand^. fragmentsRemaining > 0) or
(incomingCommand^. reliableSequenceNumber <> enet_uint16 ((channel^. incomingReliableSequenceNumber + 1))) then
break;
channel^. incomingReliableSequenceNumber := incomingCommand^. reliableSequenceNumber;
if (incomingCommand^. fragmentCount > 0) then
Inc(channel^. incomingReliableSequenceNumber , incomingCommand^. fragmentCount - 1);
currentCommand := enet_list_next (currentCommand);
end;
if (currentCommand = enet_list_begin (@ channel^. incomingReliableCommands)) then
exit;
channel^. incomingUnreliableSequenceNumber := 0;
enet_list_move (enet_list_end (@ peer^. dispatchedCommands), enet_list_begin (@ channel^. incomingReliableCommands), enet_list_previous (currentCommand));
if (peer^. needsDispatch=0) then
begin
enet_list_insert (enet_list_end (@ peer^. host^. dispatchQueue), @ peer^. dispatchList);
peer^. needsDispatch := 1;
end;
if (not enet_list_empty (@ channel^. incomingUnreliableCommands)) then
enet_peer_dispatch_incoming_unreliable_commands (peer, channel);
end;
var
dummyCommand : ENetIncomingCommand; // static
function enet_peer_queue_incoming_command (peer:pENetPeer; command: pENetProtocol; data:Pointer; dataLength: sizeint; flags, fragmentCount: enet_uint32):pENetIncomingCommand;
var
channel : pENetChannel;
unreliableSequenceNumber, reliableSequenceNumber : enet_uint32;
reliableWindow, currentWindow : enet_uint16;
incomingCommand : pENetIncomingCommand;
currentCommand : ENetListIterator;
packet : pENetPacket;
label discardCommand, continuework1, continuework2, NotifyError;
begin
channel := @ pENetChannelArray(peer^. channels)^[command^. header.channelID];
unreliableSequenceNumber := 0;
reliableSequenceNumber:=0;
packet := nil;
if (peer^. state = ENET_PEER_STATE_DISCONNECT_LATER) then
goto discardCommand;
if ((command^. header.command and ENET_PROTOCOL_COMMAND_MASK) <> ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) then
begin
reliableSequenceNumber := command^. header.reliableSequenceNumber;
reliableWindow := reliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE;
currentWindow := channel^. incomingReliableSequenceNumber div ENET_PEER_RELIABLE_WINDOW_SIZE;
if (reliableSequenceNumber < channel^. incomingReliableSequenceNumber) then
inc(reliableWindow , ENET_PEER_RELIABLE_WINDOWS);
if (reliableWindow < currentWindow) or (reliableWindow >= (currentWindow + ENET_PEER_FREE_RELIABLE_WINDOWS - 1)) then
goto discardCommand;
end;
case (command^. header.command and ENET_PROTOCOL_COMMAND_MASK) of
ENET_PROTOCOL_COMMAND_SEND_FRAGMENT,
ENET_PROTOCOL_COMMAND_SEND_RELIABLE: begin
if (reliableSequenceNumber = channel^. incomingReliableSequenceNumber) then
goto discardCommand;
currentCommand := enet_list_previous (enet_list_end (@ channel^. incomingReliableCommands));
while PChar(currentCommand) <> PChar( enet_list_end (@ channel^. incomingReliableCommands)) do
begin
incomingCommand := pENetIncomingCommand (currentCommand);
if (reliableSequenceNumber >= channel^. incomingReliableSequenceNumber) then
begin
if (incomingCommand^. reliableSequenceNumber < channel^. incomingReliableSequenceNumber) then
goto continuework2;
end
else
if (incomingCommand^. reliableSequenceNumber >= channel^. incomingReliableSequenceNumber) then
break;
if (incomingCommand^. reliableSequenceNumber <= reliableSequenceNumber) then
begin
if (incomingCommand^. reliableSequenceNumber < reliableSequenceNumber) then
break;
goto discardCommand;
end;
continuework2:
currentCommand := enet_list_previous (currentCommand);
end;
end; // case break;
ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE,
ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT:
begin
unreliableSequenceNumber := ENET_NET_TO_HOST_16 (command^. sendUnreliable.unreliableSequenceNumber);
if (reliableSequenceNumber = channel^. incomingReliableSequenceNumber) and
(unreliableSequenceNumber <= channel^. incomingUnreliableSequenceNumber) then
goto discardCommand;
currentCommand := enet_list_previous (enet_list_end (@ channel^. incomingUnreliableCommands));
while PChar(currentCommand) <> PChar(enet_list_end (@ channel^. incomingUnreliableCommands)) do
begin
incomingCommand := pENetIncomingCommand( currentCommand);
if ((command^. header.command and ENET_PROTOCOL_COMMAND_MASK) = ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED) then
goto continuework1;
if (reliableSequenceNumber >= channel^. incomingReliableSequenceNumber) then
begin
if (incomingCommand^. reliableSequenceNumber < channel^. incomingReliableSequenceNumber) then
goto continuework1;
end
else
if (incomingCommand^. reliableSequenceNumber >= channel^. incomingReliableSequenceNumber) then
break;
if (incomingCommand^. reliableSequenceNumber < reliableSequenceNumber) then
break;
if (incomingCommand^. reliableSequenceNumber > reliableSequenceNumber) then
goto continuework1;
if (incomingCommand^. unreliableSequenceNumber <= unreliableSequenceNumber) then
begin
if (incomingCommand^. unreliableSequenceNumber < unreliableSequenceNumber) then
break;
goto discardCommand;
end;
continuework1:
currentCommand := enet_list_previous (currentCommand);
end;
end; // break;
ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED: begin
currentCommand := enet_list_end (@ channel^. incomingUnreliableCommands);
end; // break;
else goto discardCommand;
end; // end case
if (peer ^. totalWaitingData >= peer ^. host ^. maximumWaitingData) then
goto notifyError;
packet := enet_packet_create (data, dataLength, flags);
if (packet = nil) then
goto notifyError;
incomingCommand := pENetIncomingCommand(enet_malloc (sizeof (ENetIncomingCommand)));
if (incomingCommand = nil) then
goto notifyError;
incomingCommand^. reliableSequenceNumber := command^. header.reliableSequenceNumber;
incomingCommand^. unreliableSequenceNumber := unreliableSequenceNumber and $FFFF;
incomingCommand^. command := command^;
incomingCommand^. fragmentCount := fragmentCount;
incomingCommand^. fragmentsRemaining := fragmentCount;
incomingCommand^. packet := packet;
incomingCommand^. fragments := nil;
if (fragmentCount > 0) then
begin
if (fragmentCount <= ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT) then
incomingCommand^. fragments := penet_uint32(enet_malloc ((fragmentCount + 31) div 32 * sizeof (enet_uint32)));
if (incomingCommand^. fragments = nil) then
begin
enet_free (incomingCommand);
goto notifyError;
end;
fillchar (incomingCommand^. fragments^, (fragmentCount + 31) div 32 * sizeof (enet_uint32), 0);
end;
if (packet <> nil) then
begin
Inc(packet ^. referenceCount);
Inc(peer ^. totalWaitingData, packet ^. dataLength);
end;
enet_list_insert (enet_list_next (currentCommand), pENetListNode(incomingCommand));
case (command^. header.command and ENET_PROTOCOL_COMMAND_MASK) of
ENET_PROTOCOL_COMMAND_SEND_FRAGMENT,
ENET_PROTOCOL_COMMAND_SEND_RELIABLE:
enet_peer_dispatch_incoming_reliable_commands (peer, channel);
else
enet_peer_dispatch_incoming_unreliable_commands (peer, channel);
end;
result := incomingCommand; exit;
discardCommand:
if (fragmentCount > 0) then goto notifyError;
if (packet <> nil ) and (packet^. referenceCount = 0) then
enet_packet_destroy (packet);
Result := @dummyCommand; exit;
notifyError:
if (packet <> nil) and (packet^. referenceCount = 0) then
enet_packet_destroy (packet);
result := nil;
end;
(** @} *)
end.
|
unit MarkAddressAsDetectedAsVisitedUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TMarkAddressAsDetectedAsVisited = class(TBaseExample)
public
procedure Execute(RouteId: String; RouteDestinationId: integer;
IsVisited: boolean);
end;
implementation
procedure TMarkAddressAsDetectedAsVisited.Execute(RouteId: String;
RouteDestinationId: integer; IsVisited: boolean);
var
ErrorString: String;
begin
Route4MeManager.Address.MarkAsDetectedAsVisited(
RouteId, RouteDestinationId, IsVisited, ErrorString);
WriteLn('');
if (ErrorString = EmptyStr) then
WriteLn('MarkAddressAsDetectedAsVisited executed successfully')
else
WriteLn(Format('MarkAddressAsDetectedAsVisited error: "%s"', [ErrorString]));
end;
end.
|
unit SeverUpdateForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, Synchro, ExtCtrls;
type
TForm1 = class(TForm)
Source: TEdit;
Label1: TLabel;
Label2: TLabel;
Dest: TEdit;
Button1: TButton;
OverallStatus: TLabel;
TotalProgress: TProgressBar;
TaskProgress: TProgressBar;
Status: TLabel;
Panel1: TPanel;
Image1: TImage;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure Notify( SyncTask : TSyncTask; EventId : TSyncEventId; TaskDesc : string; Progress, OverallProgress : integer; out Cancel : boolean );
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
AsyncSynchronize( Source.Text, Dest.Text, Notify, 0 );
end;
procedure TForm1.Notify( SyncTask : TSyncTask; EventId : TSyncEventId; TaskDesc : string; Progress, OverallProgress : integer; out Cancel : boolean );
begin
try
OverallStatus.Caption := 'Overall Progress. ';
if SyncTask.MaxSize > 0
then
begin
OverallStatus.Caption :=
OverallStatus.Caption +
Format( '%.0n', [int(SyncTask.CurrSize/1024)] ) + ' KBytes (of ' + Format( '%.0n', [int(SyncTask.MaxSize/1024)] ) + ') ';
end;
{
if (SyncTask.EstHours > 0) or (SyncTask.EstMins > 0)
then
begin
OverallStatus.Caption := OverallStatus.Caption + 'Estimated Time: ';
if SyncTask.EstHours > 0
then
if SyncTask.EstHours > 1
then OverallStatus.Caption := OverallStatus.Caption + IntToStr(SyncTask.EstHours) + ' hours. '
else OverallStatus.Caption := OverallStatus.Caption + IntToStr(SyncTask.EstHours) + ' hour. ';
if SyncTask.EstMins > 0
then
if SyncTask.EstMins > 1
then OverallStatus.Caption := OverallStatus.Caption + IntToStr(SyncTask.EstMins) + ' minutes. '
else OverallStatus.Caption := OverallStatus.Caption + IntToStr(SyncTask.EstMins) + ' minute. ';
end;
}
Status.Caption := TaskDesc;
if EventId <> syncEvnFileDone
then
begin
TotalProgress.Position := OverallProgress;
end;
{if Progress mod 10 = 0
then }TaskProgress.Position := Progress;
{
if EventId = syncEvnDone
then
if (SyncTask = fNecessaryFiles)
then
begin
ErrorCode := fNecessaryFiles.ErrorCode;
if ErrorCode = SYNC_NOERROR
then
begin
fOptionalFiles := AsyncSynchronize( fSource + 'client/cache/BuildingImages/', fPath + 'cache\BuildingImages\', Notify, 0 );
PlayNow.Visible := true;
OverallPages.PageIndex := 1;
end
else ReportError( ErrorCode, SyncTask.ErrorInfo );
end
else
begin
ErrorCode := fOptionalFiles.ErrorCode;
if ErrorCode = SYNC_NOERROR
then FinishUpdate
else ReportError( ErrorCode, SyncTask.ErrorInfo );
end;
}
Application.ProcessMessages;
cancel := false;
except
cancel := true;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
InitSynchro( 1 );
end;
end.
|
unit ULocationManager;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.TMSNativeCLLocationManager, FMX.TMSNativeUIBaseControl,
FMX.TMSNativeMKMapView, FMX.TMSNativeUICore;
type
TForm1185 = class(TForm)
TMSFMXNativeMKMapView1: TTMSFMXNativeMKMapView;
TMSFMXNativeCLLocationManager1: TTMSFMXNativeCLLocationManager;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure TMSFMXNativeCLLocationManager1DidChangeAuthorizationStatus(
Sender: TObject;
AAuthorizationStatus: TTMSFMXNativeCLLocationManagerAuthorizationStatus);
procedure TMSFMXNativeCLLocationManager1DidUpdateLocations(Sender: TObject;
ALocations: TArray<FMX.TMSNativeUICore.TTMSFMXNativeCLLocation>);
private
{ Private declarations }
public
{ Public declarations }
procedure StartLocationUpdates;
end;
var
Form1185: TForm1185;
implementation
{$R *.fmx}
procedure TForm1185.Button1Click(Sender: TObject);
begin
if TMSFMXNativeCLLocationManager1.LocationServicesEnabled then
begin
if TMSFMXNativeCLLocationManager1.AuthorizationStatus = asAuthorizationStatusNotDetermined then
TMSFMXNativeCLLocationManager1.RequestAlwaysAuthorization
else
StartLocationUpdates;
end;
end;
procedure TForm1185.StartLocationUpdates;
begin
TMSFMXNativeCLLocationManager1.StartUpdatingLocation;
end;
procedure TForm1185.TMSFMXNativeCLLocationManager1DidChangeAuthorizationStatus(
Sender: TObject;
AAuthorizationStatus: TTMSFMXNativeCLLocationManagerAuthorizationStatus);
begin
if AAuthorizationStatus = asAuthorizationStatusAuthorizedAlways then
StartLocationUpdates;
end;
procedure TForm1185.TMSFMXNativeCLLocationManager1DidUpdateLocations(
Sender: TObject;
ALocations: TArray<FMX.TMSNativeUICore.TTMSFMXNativeCLLocation>);
var
ann: TTMSFMXNativeMKAnnotation;
begin
if Length(ALocations) > 0 then
begin
TMSFMXNativeMKMapView1.BeginUpdate;
if TMSFMXNativeMKMapView1.Annotations.Count = 0 then
ann := TMSFMXNativeMKMapView1.Annotations.Add
else
ann := TMSFMXNativeMKMapView1.Annotations[0];
ann.Location := MakeMapLocation(ALocations[0].Coordinate.Latitude, ALocations[0].Coordinate.Longitude);
TMSFMXNativeMKMapView1.SetCenterLocation(ann.Location, True);
TMSFMXNativeMKMapView1.EndUpdate;
end;
end;
end.
|
unit nsRedactionCurrentPara;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Editions"
// Автор: Люлин А.В.
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Editions/nsRedactionCurrentPara.pas"
// Начат: 10.08.2009 14:25
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> F1 Пользовательские сервисы::CompareEditions::Editions::CommonObjects::TnsRedactionCurrentPara
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If not defined(Admin) AND not defined(Monitorings)}
uses
eeInterfaces,
l3ProtoObject,
EditionsInterfaces
;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
type
TnsRedactionCurrentPara = class(Tl3ProtoObject)
private
// private fields
f_Para : IeeLeafPara;
{* Параграф для синхронизации}
protected
// realized methods
function Get_RedactionCurrentPara: IeeLeafPara;
protected
// overridden protected methods
procedure ClearFields; override;
public
// public methods
constructor Create(const aPara: IeeLeafPara); reintroduce;
end;//TnsRedactionCurrentPara
{$IfEnd} //not Admin AND not Monitorings
implementation
{$If not defined(Admin) AND not defined(Monitorings)}
// start class TnsRedactionCurrentPara
constructor TnsRedactionCurrentPara.Create(const aPara: IeeLeafPara);
//#UC START# *4B5853E10268_4A7FF2C901C8_var*
//#UC END# *4B5853E10268_4A7FF2C901C8_var*
begin
//#UC START# *4B5853E10268_4A7FF2C901C8_impl*
inherited Create;
f_Para := aPara;
//#UC END# *4B5853E10268_4A7FF2C901C8_impl*
end;//TnsRedactionCurrentPara.Create
function TnsRedactionCurrentPara.Get_RedactionCurrentPara: IeeLeafPara;
//#UC START# *4A7FF1AC035C_4A7FF2C901C8get_var*
//#UC END# *4A7FF1AC035C_4A7FF2C901C8get_var*
begin
//#UC START# *4A7FF1AC035C_4A7FF2C901C8get_impl*
Result := f_Para;
//#UC END# *4A7FF1AC035C_4A7FF2C901C8get_impl*
end;//TnsRedactionCurrentPara.Get_RedactionCurrentPara
procedure TnsRedactionCurrentPara.ClearFields;
{-}
begin
f_Para := nil;
inherited;
end;//TnsRedactionCurrentPara.ClearFields
{$IfEnd} //not Admin AND not Monitorings
end. |
{***************************************************************************}
{ }
{ ICollections - Copyright (C) 2013 - Víctor de Souza Faria }
{ }
{ victor@victorfaria.com }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit ICollections.List.Test;
interface
uses
DUnitX.TestFramework;
type
[TestFixture]
TIListTest = class
public
[Test]
procedure ListInitialization;
[Test]
procedure AddElements;
[Test]
procedure AddRangeElements;
[Test]
procedure AppendElements;
[Test]
procedure FindElements;
[Test]
procedure RemoveLastElement;
[Test]
procedure RemoveFirstElement;
[Test]
procedure RemoveMiddleElement;
[Test]
procedure RemoveNonExistingElement;
[Test]
procedure AccessByIndex;
[Test]
procedure IndexOf;
[Test]
procedure Iterator;
[Test]
procedure IsEmpty;
[Test]
procedure FindAll;
end;
implementation
{ TIListTest }
uses
ICollections.List,
SysUtils;
procedure TIListTest.AccessByIndex;
var
list: IList<String>;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
list.Add('!!!');
Assert.AreEqual<String>(list[0], 'hello');
Assert.AreEqual<String>(list[1], 'world');
Assert.AreEqual<String>(list[2], '!!!');
end;
procedure TIListTest.AddElements;
var
list: IList<String>;
begin
list := TIntList<String>.Create;
Assert.AreEqual<Integer>(0, list.Add('hello'));
Assert.AreEqual<Integer>(1, list.Add('world'));
Assert.AreEqual<Integer>(2, list.Count);
Assert.AreEqual<String>(list[0], 'hello');
end;
procedure TIListTest.AddRangeElements;
var
list: IList<String>;
newList: IList<String>;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
newList := TIntList<String>.Create;
newList.AddRange(list);
Assert.AreEqual<Integer>(list.Count, newList.Count);
end;
procedure TIListTest.AppendElements;
var
list: IList<String>;
newList: IList<String>;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
newList := TIntList<String>.Create;
newList.Append(list);
Assert.AreEqual<Integer>(list.Count, newList.Count);
end;
procedure TIListTest.FindAll;
var
list: IList<String>;
resultList: IList<String>;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
list.Add('!!!');
resultList := list.FindAll(
function(value: String): Boolean
begin
Result := value = '!!!';
end);
Assert.AreEqual(1, resultList.Count);
resultList := list.FindAll(
function(value: String): Boolean
begin
Result := value = 'fail';
end);
Assert.AreEqual(0, resultList.Count);
end;
procedure TIListTest.FindElements;
var
list: IList<String>;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
list.Add('!!!');
Assert.AreEqual<Boolean>(list.Contains('!!!'), True);
Assert.AreEqual<String>(list.First, 'hello');
Assert.AreEqual<String>(list.Last, '!!!');
end;
procedure TIListTest.IndexOf;
var
list: IList<String>;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
list.Add('!!!');
Assert.AreEqual<Integer>(list.IndexOf('hello'), 0);
Assert.AreEqual<Integer>(list.IndexOf('world'), 1);
Assert.AreEqual<Integer>(list.IndexOf('!!!'), 2);
end;
procedure TIListTest.IsEmpty;
var
list: IList<String>;
begin
list := TIntList<String>.Create;
Assert.IsTrue(list.IsEmpty);
list.Add('hello');
Assert.IsFalse(list.IsEmpty);
end;
procedure TIListTest.Iterator;
var
list: IList<String>;
item: String;
i: Integer;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
i := 0;
for item in list do begin
Inc(i);
end;
Assert.AreEqual<Integer>(2, i);
end;
procedure TIListTest.ListInitialization;
var
list: IList<String>;
begin
list := TIntList<String>.Create;
Assert.AreEqual<Integer>(0, list.Count);
Assert.AreEqual<Integer>(0, list.Capacity);
// using the gorwth algorithm
list := TIntList<String>.Create(5);
Assert.AreEqual<Integer>(0, list.Count);
Assert.AreEqual<Integer>(8, list.Capacity);
end;
procedure TIListTest.RemoveFirstElement;
var
list: IList<String>;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
list.Remove('hello');
Assert.AreEqual<Integer>(1, list.Count);
end;
procedure TIListTest.RemoveLastElement;
var
list: IList<String>;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
list.Remove('world');
Assert.AreEqual<Integer>(1, list.Count);
end;
procedure TIListTest.RemoveMiddleElement;
var
list: IList<String>;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
list.Add('!!!');
list.Remove('world');
Assert.AreEqual<Integer>(2, list.Count);
end;
procedure TIListTest.RemoveNonExistingElement;
var
list: IList<String>;
begin
list := TIntList<String>.Create;
list.Add('hello');
list.Add('world');
list.Add('!!!');
list.Remove('word');
Assert.AreEqual<Integer>(3, list.Count);
end;
initialization
TDUnitX.RegisterTestFixture(TIListTest);
end.
|
unit MdiChilds.FmResourcesUpdate;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.StdCtrls, Vcl.ExtCtrls, MdiChilds.ProgressForm,
GsDocument, ActionHandler;
type
TFmResourcesUpdate = class(TFmProcess)
edtMaterials: TLabeledEdit;
btnOpenMat: TButton;
edtMachines: TLabeledEdit;
btnOpenMash: TButton;
lbDocs: TListBox;
OpenDialog: TOpenDialog;
JvDragDrop: TJvDragDrop;
cbFullMatCode: TCheckBox;
cbFullMashCode: TCheckBox;
procedure JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings);
procedure btnOpenMatClick(Sender: TObject);
procedure btnOpenMashClick(Sender: TObject);
private
FLog: TStringList;
procedure UpdateMaterials(Doc: TGsDocument);
procedure UpdateMashines(Doc: TGsDocument);
protected
procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override;
public
procedure ExecuteDoc(AFileName: string);
end;
TResourceUpdateActionHandler = class(TAbstractActionHandler)
public
procedure ExecuteAction(UserData: Pointer = nil); override;
end;
var
FmResourcesUpdate: TFmResourcesUpdate;
implementation
uses
Generics.Collections;
{$R *.dfm}
procedure TFmResourcesUpdate.btnOpenMashClick(Sender: TObject);
begin
if OpenDialog.Execute then
edtMachines.Text := OpenDialog.FileName;
end;
procedure TFmResourcesUpdate.btnOpenMatClick(Sender: TObject);
begin
if OpenDialog.Execute then
edtMaterials.Text := OpenDialog.FileName;
end;
procedure TFmResourcesUpdate.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean);
var
I: Integer;
begin
FLog := TStringList.Create;
try
ShowMessage := True;
ProgressForm.InitPB(lbDocs.Count);
ProgressForm.Show;
for I := 0 to lbDocs.Count - 1 do
begin
if not ProgressForm.InProcess then
Break;
ExecuteDoc(lbDocs.Items[I]);
ProgressForm.StepIt(lbDocs.Items[I]);
end;
FLog.SaveToFile(UnitName + '.' + ClassName + '.log');
finally
FLog.Free;
end;
end;
procedure TFmResourcesUpdate.ExecuteDoc(AFileName: string);
var
Doc: TGsDocument;
begin
Doc := TGsDocument.Create;
try
Doc.LoadFromFile(AFileName);
UpdateMaterials(Doc);
UpdateMashines(Doc);
Doc.Save;
finally
Doc.Free;
end;
end;
procedure TFmResourcesUpdate.JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings);
begin
lbDocs.Items.Assign(Value);
end;
procedure TFmResourcesUpdate.UpdateMashines(Doc: TGsDocument);
var
Mt: TGsDocument;
L: TList<TGsRow>;
S: TStringList;
Row: TGsRow;
ResList: TList<TGsResource>;
Resource: TGsResource;
Index: Integer;
I: Integer;
Code: string;
begin
Mt := TGsDocument.Create;
try
Mt.LoadFromFile(edtMachines.Text);
L := Mt.GetAll<TGsRow>;
S := TStringList.Create;
try
try
for Row in L do
begin
if cbFullMashCode.Checked then
begin
if Mt.Flags = 5 then
begin
Code := Row.Number(True);
Code := System.Copy(Code, Pos('-', Code) + 1, 255);
S.AddObject(Code, Row);
end
else
S.AddObject(Row.Number(True), Row);
end
else
S.AddObject(Row.Code, Row);
end;
finally
L.Free;
end;
ResList := TGsAbstractItem(Doc.Chapters).Iterate<TGsResource>();
try
for Resource in ResList do
begin
if Resource.Kind = rkMashine then
begin
Index := S.IndexOf(Resource.Code);
if Index <> -1 then
begin
Resource.Caption := TGsRow(S.Objects[Index]).FullCaption;
Resource.Measure := TGsRow(S.Objects[Index]).Measure;
for I := 1 to Doc.Zones.Count do
begin
Resource.SetCostValue(cstPrice, TGsRow(S.Objects[Index]).GetCostValue(cstPrice, I), I);
Resource.SetCostValue(cstZM, TGsRow(S.Objects[Index]).GetCostValue(cstZM, I), I);
end;
end
else
FLog.Add(Resource.Code);
end;
end;
finally
ResList.Free;
end;
finally
S.Free;
end;
finally
Mt.Free;
end;
end;
procedure TFmResourcesUpdate.UpdateMaterials(Doc: TGsDocument);
var
Mt: TGsDocument;
L: TList<TGsRow>;
S: TStringList;
Row: TGsRow;
ResList: TList<TGsResource>;
Resource: TGsResource;
Index, I: Integer;
Code: string;
begin
Mt := TGsDocument.Create;
try
Mt.LoadFromFile(edtMaterials.Text);
L := Mt.GetAll<TGsRow>;
S := TStringList.Create;
try
try
for Row in L do
begin
if cbFullMatCode.Checked then
begin
if Mt.Flags = 5 then
begin
Code := Row.Number(True);
Code := System.Copy(Code, Pos('-', Code) + 1, 255);
S.AddObject(Code, Row);
end
else
S.AddObject(Row.Number(True), Row);
end
else
S.AddObject(Row.Code, Row);
end;
finally
L.Free;
end;
ResList := TGsAbstractItem(Doc.Chapters).Iterate<TGsResource>();
try
for Resource in ResList do
begin
if Resource.Kind = rkMaterial then
begin
Index := S.IndexOf(Resource.Code);
if Index <> -1 then
begin
Resource.Caption := TGsRow(S.Objects[Index]).FullCaption;
Resource.Measure := TGsRow(S.Objects[Index]).Measure;
for I := 1 to Doc.Zones.Count do
begin
Resource.SetCostValue(cstPrice, TGsRow(S.Objects[Index]).GetCostValue(cstPrice, I), I);
Resource.SetCostValue(cstWSP, TGsRow(S.Objects[Index]).GetCostValue(cstPriceBT, I), I);
end;
end
else
FLog.Add(Resource.Code);
end;
end;
finally
ResList.Free;
end;
finally
S.Free;
end;
finally
Mt.Free;
end;
end;
{ TResourceUpdateActionHandler }
procedure TResourceUpdateActionHandler.ExecuteAction;
begin
TFmResourcesUpdate.Create(Application).Show;
end;
begin
ActionHandlerManager.RegisterActionHandler('Обновление ресурсов в сборниках', hkDefault, TResourceUpdateActionHandler);
end.
|
unit GBMatrixOperations;
interface
uses
math, Util;
const
UA_RandomSeed = 123;
type
T1DArray = array of double;
T2DArray = array of array of double;
T3DArray = array of array of array of double;
T4DArray = array of array of array of array of double;
T1DBoolean = array of boolean;
T2DBoolean = array of array of boolean;
Matrix1DRec = Record
data : T1DArray;
class operator Multiply(a: Matrix1DRec; b: Matrix1DRec) : Matrix1DRec;
class operator Multiply(a: Matrix1DRec; b: double) : Matrix1DRec;
class operator Multiply(b: double;a: Matrix1DRec) : Matrix1DRec;
class operator Add(a: Matrix1DRec; b: Matrix1DRec) : Matrix1DRec;
class operator Add(a: Matrix1DRec; b: double) : Matrix1DRec;
class operator Add(b: double; a: Matrix1DRec) : Matrix1DRec;
class operator Subtract(a: Matrix1DRec; b: Matrix1DRec) : Matrix1DRec;
class operator Subtract(a: Matrix1DRec; b: double) : Matrix1DRec;
class operator Subtract(b: double; a: Matrix1DRec) : Matrix1DRec;
class operator Divide(a: Matrix1DRec; b: Matrix1DRec) : Matrix1DRec;
class operator Divide(a: Matrix1DRec; b: double) : Matrix1DRec;
class operator Divide(b: double; a: Matrix1DRec) : Matrix1DRec;
class operator Implicit(a: T1DArray): Matrix1DRec;
class operator Implicit(a: Matrix1DRec): T1DArray;
class operator Explicit(a:Matrix1DRec): T1Darray;
procedure setDimension(x:integer);
procedure init(x:integer;val:double);
procedure SetDefaultValues(x:double);
function Max : double;
procedure RandG(m,v:double);
procedure TriangInv(a,b,c:double);
procedure RandBeta(a,b : integer);
End;
Matrix2DRec = Record
mult : boolean;
data : T2DArray;
class operator Multiply(a: Matrix2DRec; b: Matrix2DRec) : Matrix2DRec;
class operator Multiply(a: T1DArray; b : Matrix2DRec):Matrix2DRec;
class operator Multiply(b : Matrix2DRec;a: T1DArray):Matrix2DRec;
class operator Multiply(a: Matrix2DRec; b: double) : Matrix2DRec;
class operator Multiply(b: double;a: Matrix2DRec) : Matrix2DRec;
class operator Add(a: Matrix2DRec; b: Matrix2DRec) : Matrix2DRec;
class operator Add(a: Matrix2DRec; b: double) : Matrix2DRec;
class operator Add(b: double; a: Matrix2DRec) : Matrix2DRec;
class operator Subtract(a: Matrix2DRec; b: Matrix2DRec) : Matrix2DRec;
class operator Subtract(a: Matrix2DRec; b: double) : Matrix2DRec;
class operator Subtract(b: double; a: Matrix2DRec) : Matrix2DRec;
class operator Divide(a: Matrix2DRec; b: Matrix2DRec) : Matrix2DRec;
class operator Divide(a: Matrix2DRec; b: double) : Matrix2DRec;
class operator Divide(b: double; a: Matrix2DRec) : Matrix2DRec;
class operator Implicit(a: T2DArray): Matrix2DRec;
class operator Implicit(a: Matrix2DRec): T2DArray;
class operator Implicit(a: Matrix1DRec):Matrix2DRec;
class operator Explicit(a:Matrix2DRec): T2Darray;
procedure setDimension(x,y:integer);
procedure SetDefaultValues(x:double);
procedure init(x,y:integer;val:double);
procedure RandG(m,v:double);overload;
procedure TriangInv(a,b,c:double);overload;
procedure RandBeta(a,b : T1DArray);overload;
procedure RandG(m,v:double;height,width:integer);overload;
procedure TriangInv(a,b,c:double;height,width:integer);overload;
procedure RandBeta(a,b : T1DArray;height,width:integer);overload;
procedure RepMat(a : T1DArray; n : integer);
procedure Upperbound(x:double);
procedure LowerBound(x:double);
function Transpose():Matrix2DRec;
function Identity():Matrix2DRec;
function DotProduct(Val1, Val2: Matrix2DRec):double;
function Size():integer;
function GetNumCols():integer;
function GetNumRows():integer;
Function Percentile(p : double):Matrix1DRec; (*returns a single array*)
End;
implementation
class operator Matrix2DRec.Multiply(a: Matrix2DRec; b: Matrix2DRec):Matrix2DRec;
var
r,c :integer;
res : Matrix2DRec;
begin
setLength(res.data,length(a.data),length(a.data[0]));
for r := 0 to length(a.data)-1 do
for c := 0 to length(a.data[r])-1 do
res.data[r,c] := a.data[r,c]*b.data[r,c];
result := res;
end;
class operator Matrix2DRec.Multiply(a: Matrix2DRec; b: double) : Matrix2DRec;
var
r,c:integer;
res : Matrix2DRec;
begin
setLength(res.data,length(a.data),length(a.data[0]));
for r := 0 to length(a.data)-1 do
for c := 0 to length(a.data[r])-1 do
res.data[r,c] := a.data[r,c]*b;
result := res;
end;
class operator Matrix2DRec.Multiply(b: double;a: Matrix2DRec) : Matrix2DRec;
begin
result := a*b;
end;
class operator Matrix2DRec.Multiply(a: T1DArray; b : Matrix2DRec):Matrix2DRec;
var
r,c :integer;
res : Matrix2DRec;
begin
setLength(res.data,length(b.data),length(b.data[0]));
for r := 0 to length(b.data)-1 do
for c := 0 to length(b.data[r])-1 do
res.data[r,c] := b.data[r,c]+a[c];
result := res;
end;
class operator Matrix2DRec.Multiply(b : Matrix2DRec;a: T1DArray):Matrix2DRec;
begin
result := a*b;
end;
class operator Matrix2DRec.Add(a: Matrix2DRec; b: Matrix2DRec) : Matrix2DRec;
var
r,c :integer;
res : Matrix2DRec;
begin
setLength(res.data,length(a.data),length(a.data[0]));
for r := 0 to length(a.data)-1 do
for c := 0 to length(a.data[r])-1 do
res.data[r,c] := a.data[r,c]+b.data[r,c];
result := res;
end;
class operator Matrix2DRec.Add(a: Matrix2DRec; b: double) : Matrix2DRec;
var
r,c :integer;
res : Matrix2DRec;
begin
setLength(res.data,length(a.data),length(a.data[0]));
for r := 0 to length(a.data)-1 do
for c := 0 to length(a.data[r])-1 do
res.data[r,c] := a.data[r,c]+b;
result := res;
end;
class operator Matrix2DRec.Add(b: double; a: Matrix2DRec) : Matrix2DRec;
begin
result := a+b;
end;
class operator Matrix2DRec.Subtract(a: Matrix2DRec; b: Matrix2DRec) : Matrix2DRec;
var
r,c:integer;
res : Matrix2DRec;
begin
setLength(res.data,length(a.data),length(a.data[0]));
for r := 0 to length(a.data)-1 do
for c := 0 to length(a.data[r])-1 do
res.data[r,c] := a.data[r,c]-b.data[r,c];
result := res;
end;
class operator Matrix2DRec.Subtract(a: Matrix2DRec; b: double) : Matrix2DRec;
var
r,c:integer;
res : Matrix2DRec;
begin
setLength(res.data,length(a.data),length(a.data[0]));
for r := 0 to length(a.data)-1 do
for c := 0 to length(a.data[r])-1 do
res.data[r,c] := a.data[r,c]-b;
result := res;
end;
class operator Matrix2DRec.Subtract(b: double; a: Matrix2DRec) : Matrix2DRec;
var
r,c:integer;
res : Matrix2DRec;
begin
setLength(res.data,length(a.data),length(a.data[0]));
for r := 0 to length(a.data)-1 do
for c := 0 to length(a.data[r])-1 do
res.data[r,c] := b-a.data[r,c];
result := res;
end;
class operator Matrix2DRec.Divide(a: Matrix2DRec; b: Matrix2DRec) : Matrix2DRec;
var
r,c:integer;
res : Matrix2DRec;
begin
setLength(res.data,length(a.data),length(a.data[0]));
for r := 0 to length(a.data)-1 do
for c := 0 to length(a.data[r])-1 do
if b.data[r,c]<>0 then
res.data[r,c] := a.data[r,c]/b.data[r,c]
else
res.data[r,c] := 0;
result := res;
end;
class operator Matrix2DRec.Divide(a: Matrix2DRec; b: double) : Matrix2DRec;
var
r,c:integer;
res : Matrix2DRec;
begin
setLength(res.data,length(a.data),length(a.data[0]));
for r := 0 to length(a.data)-1 do
for c := 0 to length(a.data[r])-1 do
if b<>0 then
res.data[r,c] := a.data[r,c]/b
else
res.data[r,c] := 0;
result := res;
end;
class operator Matrix2DRec.Divide(b: double; a: Matrix2DRec) : Matrix2DRec;
var
r,c:integer;
res : Matrix2DRec;
begin
setLength(res.data,length(a.data),length(a.data[0]));
for r := 0 to length(a.data)-1 do
for c := 0 to length(a.data[r])-1 do
if a.data[r,c] <> 0 then
res.data[r,c] := b/a.data[r,c]
else
res.data[r,c] := 0;
result := res;
end;
class operator Matrix2DRec.Implicit(a: T2DArray): Matrix2DRec;
begin
result.data := a;
end;
class operator Matrix2DRec.Implicit(a: Matrix2DRec):T2DArray;
begin
result := a.data;
end;
class operator Matrix2DRec.Implicit(a: Matrix1DRec):Matrix2DRec;
var
r,c : integer;
begin
for r := 0 to length(result.data)-1 do
for c := 0 to length(result.data[r])-1 do
result.data[r,c] := a.data[c];
end;
class operator Matrix2DRec.Explicit(a:Matrix2DRec): T2Darray;
begin
result := a.data;
end;
procedure Matrix2DRec.setDimension(x: Integer; y: Integer);
begin
System.SetLength(data,x,y);
end;
procedure Matrix2DRec.init(x,y:integer;val:double);
begin
System.SetLength(data,x,y);
SetDefaultValues(val);
end;
procedure Matrix2DRec.SetDefaultValues(x:double);
var
r,c : integer;
begin
for r := 0 to length(data)-1 do
for c := 0 to length(data[r])-1 do
data[r,c] := x;
end;
procedure Matrix2DRec.RandG(m,v:double);
var
r,c : integer;
begin
for r := 0 to length(data)-1 do
for c := 0 to length(data[r])-1 do
data[r,c] := Math.RandG(m,v);
end;
procedure Matrix2DRec.RandG(m,v:double;height,width:integer);
begin
SetDimension(height,width);
RandG(m,v);
end;
procedure Matrix2DRec.TriangInv(a,b,c:double;height,width:integer);
begin
SetDimension(height,width);
TriangInv(a,b,c);
end;
procedure Matrix2DRec.RandBeta(a,b : T1DArray;height,width:integer);
begin
SetDimension(height,width);
RandBeta(a,b);
end;
procedure Matrix2DRec.TriangInv(a,b,c:double);
var
rw,cl : integer;
begin
for rw := 0 to length(data)-1 do
for cl := 0 to length(data[rw])-1 do
data[rw,cl] := GBTriangInv(a,b,c);
end;
procedure Matrix2DRec.RandBeta(a,b : T1DArray);
var
r,c : integer;
begin
for c := 0 to length(data[0])-1 do
begin
randSeed := UA_RandomSeed;
for r := 0 to length(data)-1 do
begin
// randGamma1 := GBRandomBetaV2(a[c],1);
// randGamma2 := GBRandomBetaV2(b[c],1);
data[r,c] := GBRandomBeta(a[c],b[c]);//randGamma1/(randGamma1+randGamma2);
end;
end;
end;
procedure Matrix2DRec.RepMat(a : T1DArray; n : integer);
var
r,c : integer;
begin
for r := 0 to length(data)-1 do
for c := 0 to length(data[r])-1 do
data[r,c] := a[c];
end;
procedure Matrix2DRec.Upperbound(x:double);
var
r,c : integer;
begin
for r := 0 to length(data)-1 do
for c := 0 to length(data[r])-1 do
if data[r,c]>x then
data[r,c] := x;
end;
procedure Matrix2DRec.LowerBound(x:double);
var
r,c : integer;
begin
for r := 0 to length(data)-1 do
for c := 0 to length(data[r])-1 do
if data[r,c]<x then
data[r,c] := x;
end;
function Matrix2DRec.Transpose():Matrix2DRec;
var
r,c : integer;
begin
result.init(length(data),length(data),0);
for r := 0 to length(data)-1 do
for c := 0 to length(data[r])-1 do
result.data[r,c] := data[c,r];
end;
function Matrix2DRec.Identity():Matrix2DRec;
var
size : integer;
begin
result.init(length(data),length(data),0);
for size := 0 to length(data)-1 do
result.data[size,size] := 1;
end;
function Matrix2DRec.DotProduct(Val1, Val2: Matrix2DRec):double;
function ToPackagedArray(pack: Matrix2Drec):Matrix1DRec;
var
index, r, c : integer;
begin
result.init(pack.Size,0);
index := 0;
for r := 0 to length(pack.data)-1 do
for c := 0 to length(pack.data[r])-1 do
begin
result.data[index] := pack.data[r,c];
inc(index);
end;
end;
var
size : integer;
a,b : Matrix1DRec;
begin
result := 0;
a := ToPackagedArray(Val1);
b := ToPackagedArray(Val2);
for size := 0 to length(a.data)-1 do
result := result+ a.data[size]*b.data[size];
end;
function Matrix2DRec.Size():integer;
begin
result := (length(data))*(length(data));
end;
function Matrix2DRec.GetNumCols():integer;
begin
result := length(data[0])-1;
end;
function Matrix2DRec.GetNumRows():integer;
begin
result := length(data)-1;
end;
(*assumes a square matrix*)
Function Matrix2DRec.Percentile(p : double):Matrix1DRec;
var
res,curr : Matrix1DRec;
r,c : integer;
begin
(*initialize arrays*)
setLength(curr.data,length(data));
setLength(res.data, length(data[0]));
(*typically will loop through years*)
for c := 0 to length(data[0])-1 do
begin
(*obtain sample data for year c *)
for r := 0 to length(data)-1 do
curr.data[r] := data[r,c];
(*set year data according to percentile*)
res.data[c] := GBPercentile(p,curr.data);
end;
(*send result back*)
result := res;
end;
(******************************************************************************)
(***************************** 1D Matrix Operations *************************)
(******************************************************************************)
class operator Matrix1DRec.Multiply(a: Matrix1DRec; b: Matrix1DRec):Matrix1DRec;
var
r : integer;
res : Matrix1DRec;
begin
setLength(res.data,length(a.data));
for r := 0 to length(a.data)-1 do
res.data[r] := a.data[r]*b.data[r];
result := res;
end;
class operator Matrix1DRec.Multiply(a: Matrix1DRec; b: double) : Matrix1DRec;
var
r : integer;
res : Matrix1DRec;
begin
setLength(res.data,length(a.data));
for r := 0 to length(a.data)-1 do
res.data[r] := a.data[r]*b;
result := res;
end;
(*
void quickSort(int arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
/* partition */
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
/* recursion */
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
} *)
class operator Matrix1DRec.Multiply(b: double;a: Matrix1DRec) : Matrix1DRec;
begin
result := a*b;
end;
class operator Matrix1DRec.Add(a: Matrix1DRec; b: Matrix1DRec) : Matrix1DRec;
var
r : integer;
res : Matrix1DRec;
begin
setLength(res.data,length(a.data));
for r := 0 to length(a.data)-1 do
res.data[r] := a.data[r]+b.data[r];
result := res;
end;
class operator Matrix1DRec.Add(a: Matrix1DRec; b: double) : Matrix1DRec;
var
r : integer;
res : Matrix1DRec;
begin
setLength(res.data,length(a.data));
for r := 0 to length(a.data)-1 do
res.data[r] := a.data[r]+b;
result := res;
end;
class operator Matrix1DRec.Add(b: double; a: Matrix1DRec) : Matrix1DRec;
begin
result := a+b;
end;
class operator Matrix1DRec.Subtract(a: Matrix1DRec; b: Matrix1DRec) : Matrix1DRec;
var
r : integer;
res : Matrix1DRec;
begin
setLength(res.data,length(a.data));
for r := 0 to length(a.data)-1 do
res.data[r] := a.data[r]-b.data[r];
result := res;
end;
class operator Matrix1DRec.Subtract(a: Matrix1DRec; b: double) : Matrix1DRec;
var
r : integer;
res : Matrix1DRec;
begin
setLength(res.data,length(a.data));
for r := 0 to length(a.data)-1 do
res.data[r] := a.data[r]-b;
result := res;
end;
class operator Matrix1DRec.Subtract(b: double; a: Matrix1DRec) : Matrix1DRec;
var
r : integer;
res : Matrix1DRec;
begin
setLength(res.data,length(a.data));
for r := 0 to length(a.data)-1 do
res.data[r] := b-a.data[r];
result := res;
end;
class operator Matrix1DRec.Divide(a: Matrix1DRec; b: Matrix1DRec) : Matrix1DRec;
var
r : integer;
res : Matrix1DRec;
begin
setLength(res.data,length(a.data));
for r := 0 to length(a.data)-1 do
if b.data[r]<>0 then
res.data[r] := a.data[r]/b.data[r]
else
res.data[r] := 0;
result := res;
end;
class operator Matrix1DRec.Divide(a: Matrix1DRec; b: double) : Matrix1DRec;
var
r :integer;
res : Matrix1DRec;
begin
setLength(res.data,length(a.data));
for r := 0 to length(a.data)-1 do
if b <> 0 then
res.data[r] := a.data[r]/b
else
res.data[r] := 0;
result := res;
end;
class operator Matrix1DRec.Divide(b: double; a: Matrix1DRec) : Matrix1DRec;
var
r : integer;
res : Matrix1DRec;
begin
setLength(res.data,length(a.data));
for r := 0 to length(a.data)-1 do
if a.data[r]<>0 then
res.data[r] := b/a.data[r]
else
res.data[r] := 0;
result := res;
end;
class operator Matrix1DRec.Implicit(a: T1DArray): Matrix1DRec;
begin
result.data := a;
end;
class operator Matrix1DRec.Implicit(a: Matrix1DRec):T1DArray;
begin
result := a.data;
end;
class operator Matrix1DRec.Explicit(a:Matrix1DRec): T1Darray;
begin
result := a.data;
end;
procedure Matrix1DRec.setDimension(x: Integer);
begin
System.SetLength(data,x);
end;
procedure Matrix1DRec.init(x:integer;val:double);
begin
setDimension(x);
SetDefaultValues(val);
end;
procedure Matrix1DRec.SetDefaultValues(x:double);
var
r : integer;
begin
for r := 0 to length(data)-1 do
data[r] := x;
end;
function Matrix1DRec.Max : double;
var
r : integer;
begin
result := data[0];
for r := 1 to length(data)-1 do
if result<data[r] then
result := data[r];
end;
procedure Matrix1DRec.RandG(m,v:double);
var
r : integer;
begin
for r := 0 to length(data)-1 do
data[r] := Math.RandG(m,v);
end;
procedure Matrix1DRec.TriangInv(a,b,c:double);
var
r : integer;
begin
for r := 0 to length(data)-1 do
data[r] := GBTriangInv(a,b,c);
end;
procedure Matrix1DRec.RandBeta(a,b : integer);
var
r : integer;
begin
for r := 0 to length(data)-1 do
data[r] := GBRandomBeta(a,b);
end;
end.
|
unit uMlSearch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Ora, DB, Grids, DBGrids, uSupportLib,
Buttons, DBGridAux;
type
TfmMlSearch = class(TForm)
pnTools: TPanel;
grSearch: TDBGridAux;
dsSearch: TDataSource;
bbOk: TBitBtn;
bbCancel: TBitBtn;
bbInsert: TBitBtn;
sbFilter: TSpeedButton;
sbSearch: TSpeedButton;
procedure grSearchDblClick(Sender: TObject);
procedure bbOkClick(Sender: TObject);
procedure sbSearchClick(Sender: TObject);
procedure sbFilterClick(Sender: TObject);
procedure grSearchGetCellParams(Sender: TObject; Field: TField;
AFont: TFont; var Background: TColor; State: TGridDrawState;
StateEx: TGridDrawStateEx);
procedure grSearchKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
FhRes: Variant;
FhArrFields: TStringList;
FhTag : integer;
public
{ Public declarations }
procedure Search(ACaption: String; AQy: TOraQuery; ResList: String; ATag: Integer);
procedure SetSearchResult;
property hRes : Variant read FhRes write FhRes;
end;
var
fmMlSearch: TfmMlSearch;
implementation
{$R *.dfm}
{ TfmMlSearch }
procedure TfmMlSearch.Search(ACaption: String; AQy: TOraQuery; ResList: String; ATag: integer);
procedure Split(StrBuf,Delimiter: string; var MyStrList: TStringList);
var
TmpBuf: string;
LoopCount: integer;
begin
LoopCount := 0;
repeat
if StrBuf[LoopCount] = Delimiter then
begin
MyStrList.Add(TmpBuf);
TmpBuf := '';
end;
TmpBuf := TmpBuf + StrBuf[LoopCount];
inc(LoopCount);
until LoopCount > Length(StrBuf);
MyStrList.Add(Copy(TmpBuf,2,Length(TmpBuf)));
end;
begin
FhTag := ATag;
AQy.Close;
FhArrFields := TStringList.Create;
Split(ResList, ';', FhArrFields);
FhRes := VarArrayCreate([0, FhArrFields.Count -1], varVariant);
Self.Caption := Self.Caption + ' ' + ACaption;
dsSearch.DataSet := AQy;
dsSearch.DataSet.Open;
grSearch.Filtered := sbFilter.Down;
Self.ShowModal;
end;
procedure TfmMlSearch.grSearchDblClick(Sender: TObject);
begin
SetSearchResult;
end;
procedure TfmMlSearch.SetSearchResult;
var
i : integer;
begin
for i := 0 to FhArrFields.Count - 1 do
FhRes[i] := dsSearch.DataSet.FieldByName(StringReplace(FhArrFields[i], ';', '', [rfReplaceAll])).Value;
Self.ModalResult := mrOk;
end;
procedure TfmMlSearch.bbOkClick(Sender: TObject);
begin
SetSearchResult;
end;
procedure TfmMlSearch.sbSearchClick(Sender: TObject);
begin
grSearch.SetFocus;
if sbSearch.Down then
begin
grSearch.OptionsEx := grSearch.OptionsEx + [dgeSearchBar];
sbFilterClick(nil);
end
else
grSearch.OptionsEx := grSearch.OptionsEx - [dgeSearchBar];
end;
procedure TfmMlSearch.sbFilterClick(Sender: TObject);
begin
grSearch.SetFocus;
grSearch.Filtered := sbFilter.Down;
if sbFilter.Down then
begin
grSearch.OptionsEx := grSearch.OptionsEx + [dgeFilterBar];
sbSearchClick(nil);
end
else
grSearch.OptionsEx := grSearch.OptionsEx - [dgeFilterBar];
end;
procedure TfmMlSearch.grSearchGetCellParams(Sender: TObject; Field: TField;
AFont: TFont; var Background: TColor; State: TGridDrawState;
StateEx: TGridDrawStateEx);
begin
if (geActiveRow in StateEx) and
sbSearch.Down and
(not grSearch.Focused) then
Background := clMoneyGreen;
end;
procedure TfmMlSearch.grSearchKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
SetSearchResult;
end;
procedure TfmMlSearch.FormActivate(Sender: TObject);
begin
sbFilter.Down := True;
sbFilterClick(nil);
end;
end.
|
unit UtInputHelper;
interface
uses Windows,Controls,Messages,SysUtils;
type TInputHelper = class
private
public
class procedure KeyPress(Handle:THandle;Key:Char); overload;
class procedure KeyDown(Handle:THandle;Key:Word); overload;
class procedure KeyInputString(Handle:THandle;AString:String); //忽略中文字符
class procedure KeyDown(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);overload;
class procedure KEYUP(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure KEYCHAR(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure KeyDEADCHAR(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure KeySYSKEYDOWN(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure KeySYSKEYUP(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure KeySYSCHAR(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure KeySYSDEADCHAR(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
//X:WParam,y:lParam
//最后一个参数表示:是否为异步线程发送消息
class procedure MouseLButtonDown(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseLButtonUp(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseLButtonDbClick(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseMButtonDown(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseMButtonUp(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseMButtonDbClick(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseRButtonDown(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseRButtonUp(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseRButtonDbClick(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseMove(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseNCMouseMove(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseWHEEL(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseNCHITTEST(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseNCLBUTTONDOWN(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseNCLBUTTONUP(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseNCLBUTTONDBLCLK(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseNCRBUTTONDOWN(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseNCRBUTTONUP(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
class procedure MouseNCRBUTTONDBLCLK(Handle:THandle;Wp:WPARAM;Lp:LPARAM;Thread:Boolean=False);
end;
implementation
{ TInputHelper }
//keypress包含了keyDown和keyUp,处理数字键和字母键
//keyDown 处理任何键
class procedure TInputHelper.KeyDown(Handle: THandle; Key: Word);
begin
SendMessage(Handle,WM_KEYDOWN,Key,$000f0001);
end;
class procedure TInputHelper.KeyPress(Handle: THandle; Key: Char);
begin
SendMessage(Handle,WM_CHAR,Ord(Key),$000f0001);
end;
class procedure TInputHelper.KeyInputString(Handle: THandle; AString: String);
var
i,cs:Integer;
begin
cs:=Length(AString);
for i := 1 to cs do
begin
if ByteType(AString,i)= mbSingleByte then
SendMessage(Handle,WM_CHAR,Ord(AString[i]),0);
end;
end;
class procedure TInputHelper.MouseLButtonDown(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
SetCursorPos(WORD(Lp),HiWord(Lp));
if Thread then PostMessage(Handle,WM_LBUTTONDOWN,Wp,Lp)
else
begin
SendMessage(Handle,WM_LBUTTONDOWN,Wp,Lp);
end;
end;
class procedure TInputHelper.MouseRButtonDown(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_RBUTTONDOWN,Wp,Lp)
else SendMessage(Handle,WM_RBUTTONDOWN,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseLButtonDbClick(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_LBUTTONDBLCLK,Wp,Lp)
else SendMessage(Handle,WM_LBUTTONDBLCLK,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseLButtonUp(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_LBUTTONUP,Wp,Lp)
else SendMessage(Handle,WM_LBUTTONUP,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseMButtonDown(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_MBUTTONDOWN,Wp,Lp)
else SendMessage(Handle,WM_MBUTTONDOWN,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseMButtonUp(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_MBUTTONUP,Wp,Lp)
else SendMessage(Handle,WM_MBUTTONUP,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseMButtonDbClick(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_MBUTTONDBLCLK,Wp,Lp)
else SendMessage(Handle,WM_MBUTTONDBLCLK,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseRButtonDbClick(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_RBUTTONDBLCLK,Wp,Lp)
else SendMessage(Handle,WM_RBUTTONDBLCLK,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseRButtonUp(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_RBUTTONUP,Wp,Lp)
else SendMessage(Handle,WM_RBUTTONUP,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseMove(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_MOUSEMOVE,Wp,Lp)
else SendMessage(Handle,WM_MOUSEMOVE,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseNCHITTEST(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_NCHITTEST,Wp,Lp)
else SendMessage(Handle,WM_NCHITTEST,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseNCMouseMove(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_NCMOUSEMOVE,Wp,Lp)
else SendMessage(Handle,WM_NCMOUSEMOVE,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseWHEEL(Handle: THandle;Wp:WPARAM;Lp:LPARAM ; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_MouseWHEEL,Wp,Lp)
else SendMessage(Handle,WM_MouseWHEEL,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.KEYCHAR(Handle: THandle; Wp: WPARAM;
Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_CHAR,wp,lp)
else SendMessage(Handle,WM_CHAR,wp,lp);
end;
class procedure TInputHelper.KeyDEADCHAR(Handle: THandle; Wp: WPARAM;
Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_DEADCHAR,wp,lp)
else SendMessage(Handle,WM_DEADCHAR,wp,lp);
end;
class procedure TInputHelper.KeyDown(Handle: THandle; Wp: WPARAM;
Lp: LPARAM; Thread: Boolean);
begin
if Thread then
begin
// PostMessage(Handle,WM_KEYDOWN,wp,lp)
keybd_event(Wp,MapVirtualKey(WP,0),0,0);
end
else SendMessage(Handle,WM_KEYDOWN,wp,lp);
end;
class procedure TInputHelper.KeySYSCHAR(Handle: THandle; Wp: WPARAM;
Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_SYSCHAR,wp,lp)
else SendMessage(Handle,WM_SYSCHAR,wp,lp);
end;
class procedure TInputHelper.KeySYSDEADCHAR(Handle: THandle; Wp: WPARAM;
Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_SYSDEADCHAR,wp,lp)
else SendMessage(Handle,WM_SYSDEADCHAR,wp,lp);
end;
class procedure TInputHelper.KeySYSKEYDOWN(Handle: THandle; Wp: WPARAM;
Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_SYSKEYDOWN,wp,lp)
else SendMessage(Handle,WM_SYSKEYDOWN,wp,lp);
end;
class procedure TInputHelper.KeySYSKEYUP(Handle: THandle; Wp: WPARAM;
Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_SYSKEYUP,wp,lp)
else SendMessage(Handle,WM_SYSKEYUP,wp,lp);
end;
class procedure TInputHelper.KEYUP(Handle: THandle; Wp: WPARAM; Lp: LPARAM;
Thread: Boolean);
begin
if Thread then
BEGIN
// PostMessage(Handle,WM_KEYUP,wp,lp)
keybd_event(Wp,MapVirtualKey(WP,0),KEYEVENTF_KEYUP,0);
end
else SendMessage(Handle,WM_KEYUP,wp,lp);
end;
class procedure TInputHelper.MouseNCLBUTTONDBLCLK(Handle: THandle; Wp: WPARAM; Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_NCLBUTTONDBLCLK,Wp,Lp)
else SendMessage(Handle,WM_NCLBUTTONDOWN,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseNCLBUTTONDOWN(Handle: THandle; Wp: WPARAM; Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_NCLBUTTONDOWN,Wp,Lp)
else SendMessage(Handle,WM_NCLBUTTONDOWN,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseNCLBUTTONUP(Handle: THandle; Wp: WPARAM; Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_NCLBUTTONUP,Wp,Lp)
else SendMessage(Handle,WM_NCLBUTTONUP,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseNCRBUTTONDBLCLK(Handle: THandle; Wp: WPARAM; Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_NCRBUTTONDBLCLK,Wp,Lp)
else SendMessage(Handle,WM_NCRBUTTONDBLCLK,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseNCRBUTTONDOWN(Handle: THandle; Wp: WPARAM; Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_NCRBUTTONDOWN,Wp,Lp)
else SendMessage(Handle,WM_NCRBUTTONDOWN,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
class procedure TInputHelper.MouseNCRBUTTONUP(Handle: THandle; Wp: WPARAM; Lp: LPARAM; Thread: Boolean);
begin
if Thread then PostMessage(Handle,WM_NCRBUTTONUP,Wp,Lp)
else SendMessage(Handle,WM_NCRBUTTONUP,Wp,Lp);
SetCursorPos(WORD(Lp),HiWord(Lp));
end;
end.
|
unit AnonCommand;
interface
{x$DEFINE ANON_SYNC_EXEC}
uses
debug, System.Classes, System.SysUtils, System.Generics.Collections, better_collections, typex, systemx, managedthread, commandprocessor;
type
EAnonymousThreadException = class(Exception);
Tcmd_Test = class(TCommand)
public
procedure DoExecute;override;
end;
TAnonymousCommand<T> = class(TCommand)
private
Err: Exception;
FThreadFunc: TFunc<T>;
FOnErrorProc: TProc<Exception>;
FOnFinishedProc: TProc<T>;
FResult: T;
FStartSuspended: Boolean;
FSynchronizeFinish: boolean;
FSynchronizeExecute: boolean;
strict private
procedure SyncFinished;
procedure SyncExecute;
procedure SyncError;
protected
procedure DoExecute; override;
public
procedure InitExpense; override;
procedure Detach; override;
property SynchronizeFinish: boolean read FSynchronizeFinish write FSynchronizeFinish;
property SynchronizeExecute: boolean read FSynchronizeExecute write FSynchronizeExecute;
constructor CreateAndTrackX(tracker: TCommandList<TCommand>; AThreadFunc: TFunc<T>; AOnFinishedProc: TProc<T>;AOnErrorProc: TProc<Exception>; ACreateSuspended: Boolean = False);virtual;
constructor Create(AThreadFunc: TFunc<T>; AOnFinishedProc: TProc<T>;AOnErrorProc: TProc<Exception>; ACreateSuspended: Boolean = False;
FreeOnComplete: Boolean = True);reintroduce;
destructor Destroy;override;
// class constructor Create;
// class destructor Destroy;
end;
TAnonymousGUICommand<T> = class(TAnonymousCommand<T>)
//THIS is an ANONYMOUs COMMAND that uses SYNCHRONIZE in OnFinish
//by default. You can choose to synchronize Execution and Finish of any anonymous
//command. This derivative simply has a different default for SynchronizeFinish
public
constructor Create(AThreadFunc: TFunc<T>; AOnFinishedProc: TProc<T>;AOnErrorProc: TProc<Exception>; ACreateSuspended: Boolean = False;
FreeOnComplete: Boolean = True);reintroduce;
end;
TAnonymousIteratorCommand = class(TCommand)
protected
procedure DoExecute; override;
public
iteration: ni;
count: ni;
proc: TProc<ni>;
end;
TAnonymousFunctionCommand = class(TAnonymousCommand<boolean>)
public
constructor CreateInline(AThreadFunc: TProc; ACreateSuspended: Boolean = False;
FreeOnComplete: Boolean = false);reintroduce;
constructor CreateInlineWithGui(AThreadFunc, GuiFunc: TProc; ACreateSuspended: Boolean = False; FreeOnComplete: Boolean = false);reintroduce;
constructor CreateInlineWithGuiEx(AThreadFunc, GuiFunc: TProc; exProc: TProc<string>; ACreateSuspended: Boolean = False; FreeOnComplete: Boolean = false);reintroduce;
end;
TAnonTimerProc = reference to procedure();
TAnonymousTimer = class(TAnonymousCommand<boolean>)
public
timerproc: TAnonTimerProc;
procedure InitExpense;override;
end;
{ TAnonymousTimer }
function InlineProc(proc: TProc): TAnonymousCommand<boolean>;
function InlineIteratorProc(idx: ni; proc: TProc<ni>): TAnonymousIteratorCommand;
function InlineIteratorGroupProc(idx: ni; count: ni; proc: TProc<ni>): TAnonymousIteratorCommand;
function InlineProcWithGui(proc, guiproc: TProc): TAnonymousCommand<boolean>;
function InlineProcWithGuiEx(proc, guiproc: TProc; exProc:TProc<string>): TAnonymousCommand<boolean>;
//function InlineProc<T>(proc: TProc): TAnonymousCommand<T,boolean>;
function SetTimer(interval: ni; ontimerproc: TAnonTimerProc): TAnonymousTimer;
function SetTimerGUI(interval: ni; ontimerproc: TAnonTimerProc): TAnonymousTimer;
implementation
{$IFDEF MACOS}
uses
{$IFDEF IOS}
iOSapi.Foundation
{$ELSE}
MacApi.Foundation
{$ENDIF IOS}
;
{$ENDIF MACOS}
{ TAnonymousCommand }
//class constructor TAnonymousCommand<T>.Create;
//begin
// inherited;
//end;
//class destructor TAnonymousCommand<T>.Destroy;
//begin
// inherited;
//end;
procedure TAnonymousCommand<T>.Detach;
begin
Debug.log(self, 'Detaching');
if detached then exit;
inherited;
end;
function InlineProc(proc: TProc): TAnonymousCommand<boolean>;
var
res: TAnonymousCommand<boolean>;
begin
res := TAnonymousFunctionCommand.createinline(proc, false, false);
res.SynchronizeFinish := false;
result := res;
end;
function InlineIteratorProc(idx: ni; proc: TProc<ni>): TAnonymousIteratorCommand;
begin
result := TAnonymousIteratorCommand.create;
result.iteration := idx;
result.count := 1;
result.proc := proc;
// result.CPUExpense := 1.0;
result.start;
end;
function InlineIteratorGroupProc(idx: ni; count: ni; proc: TProc<ni>): TAnonymousIteratorCommand;
begin
result := TAnonymousIteratorCommand.create;
result.iteration := idx;
result.count := count;
result.proc := proc;
// result.CPUExpense := 1.0;
result.start;
end;
function InlineProcWithGui(proc, guiproc: TProc): TAnonymousCommand<boolean>;
var
res: TAnonymousCommand<boolean>;
begin
res := TAnonymousFunctionCommand.createinlinewithgui(proc, guiproc, false, false);
result := res;
result.start;
end;
function InlineProcWithGuiEx(proc, guiproc: TProc; exProc:TProc<string>): TAnonymousCommand<boolean>;
var
res: TAnonymousCommand<boolean>;
begin
res := TAnonymousFunctionCommand.createinlinewithguiex(proc, guiproc, exProc, false, false);
result := res;
result.start;
end;
constructor TAnonymousCommand<T>.Create(AThreadFunc: TFunc<T>; AOnFinishedProc: TProc<T>;
AOnErrorProc: TProc<Exception>; ACreateSuspended: Boolean = False; FreeOnComplete: Boolean = True);
begin
// Debug.Log('Creating '+self.GetObjectDebug);
FOnFinishedProc := AOnFinishedProc;
FOnErrorProc := AOnErrorProc;
FThreadFunc := AThreadFunc;
FireForget := FreeOnComplete;
FStartSuspended := ACreateSuspended;
FSynchronizeFinish := true;
{$IFDEF ANON_SYNC_EXEC}
FSynchronizeExecute := true;
{$ENDIF}
inherited Create();
if not ACreateSuspended then
Start;
end;
constructor TAnonymousCommand<T>.CreateAndTrackX(tracker: TCommandList<TCommand>;
AThreadFunc: TFunc<T>; AOnFinishedProc: TProc<T>;
AOnErrorProc: TProc<Exception>; ACreateSuspended: Boolean);
begin
Create(AthreadFunc, AonFinishedProc, AOnErrorProc, ACreateSuspended, false);
tracker.Add(self);
end;
destructor TAnonymousCommand<T>.Destroy;
begin
// Debug.Log('Destroying Inherited '+self.GetObjectDebug);
inherited;
// Debug.Log('Destroying '+self.GetObjectDebug);
end;
procedure TAnonymousCommand<T>.DoExecute;
{$IFDEF MACOS}
var
lPool: NSAutoreleasePool;
{$ENDIF}
begin
inherited;
// Debug.Log(self, 'Executing '+self.GetObjectDebug);
{$IFDEF MACOS}
//Need to create an autorelease pool, otherwise any autorelease objects
//may leak.
//See https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-CJBFBEDI
lPool := TNSAutoreleasePool.Create;
try
{$ENDIF}
try
// raise ECritical.Create('fuck you');
if FSynchronizeExecute then begin
TThread.Synchronize(self.Thread.realthread, SyncExecute)
end else
FResult := FThreadFunc;
if assigned(FonFinishedProc) then begin
try
if FSynchronizeFinish then
TThread.Synchronize(self.Thread.realthread, SyncFinished)
else
FOnFinishedProc(FResult);
except
on E:Exception do begin
Debug.Log('Exception during synchronized anon finish: '+e.message);
end;
end;
end;
except
on E: Exception do begin
Err := e;
ErrorMessage := e.message;
Error := true;
{$IFNDEF CONSOLE}
if FSynchronizeFinish then
TThread.Synchronize(self.Thread.realthread, SyncError)
else
{$ENDIF}
if assigned(FOnErrorProc) then
FOnErrorProc(E);
end;
end;
{$IFDEF MACOS}
finally
lPool.drain;
end;
{$ENDIF}
end;
procedure TAnonymousCommand<T>.InitExpense;
begin
inherited;
// self.Resources.SetResourceUsage('CTO_Anonymous', 1.0);
cpuExpense := 0.0;
end;
procedure TAnonymousCommand<T>.SyncError;
begin
FOnErrorProc(Err);
end;
procedure TAnonymousCommand<T>.SyncExecute;
begin
FResult := FThreadFunc;
end;
procedure TAnonymousCommand<T>.SyncFinished;
begin
FOnFinishedProc(fResult);
end;
{ Tcmd_Test }
procedure Tcmd_Test.DoExecute;
begin
inherited;
sleep(4000);
end;
procedure TAnonymousTimer.InitExpense;
begin
inherited;
CPuExpense := 0;
end;
function SetTimerGUI(interval: ni; ontimerproc: TAnonTimerProc): TAnonymousTimer;
begin
result := TAnonymousTimer.create(
function : boolean
begin
sleep(interval);
exit(true);
end,
procedure (b: boolean)
begin
ontimerproc();
end,
procedure (e: exception)
begin
end
);
result.SynchronizeFinish := true;
result.FireForget := true;
result.start;
end;
function SetTimer(interval: ni; ontimerproc: TAnonTimerProc): TAnonymousTimer;
begin
result := TAnonymousTimer.create(
function : boolean
begin
sleep(interval);
exit(true);
end,
procedure (b: boolean)
begin
ontimerproc();
end,
procedure (e: exception)
begin
end
);
result.SynchronizeFinish := false;
result.FireForget := true;
result.start;
end;
{ TAnonymousGUICommand<T> }
constructor TAnonymousGUICommand<T>.Create(AThreadFunc: TFunc<T>;
AOnFinishedProc: TProc<T>; AOnErrorProc: TProc<Exception>; ACreateSuspended,
FreeOnComplete: Boolean);
begin
inherited;
SynchronizeFinish := true;
end;
{ TAnonymousFunctionCommand }
constructor TAnonymousFunctionCommand.CreateInline(AThreadFunc: TProc;
ACreateSuspended, FreeOnComplete: Boolean);
var
funct: TFunc<boolean>;
begin
funct:= function (): boolean
begin
AthreadFunc();
result := true;
end;
Create(funct, procedure (b: boolean) begin end, procedure (e: exception) begin end);
end;
constructor TAnonymousFunctionCommand.CreateInlineWithGui(AThreadFunc, GuiFunc: TProc;
ACreateSuspended, FreeOnComplete: Boolean);
var
func1: TFunc<boolean>;
func2: TProc<boolean>;
begin
func1:= function (): boolean
begin
AthreadFunc();
result := true;
end;
func2:= procedure (b: boolean)
begin
if assigned(GuiFunc) then
GuiFunc();
end;
Create(func1, func2, procedure (e: exception) begin end, true, false);
SynchronizeFinish := true;
Start;
end;
constructor TAnonymousFunctionCommand.CreateInlineWithGuiEx(AThreadFunc,
GuiFunc: TProc; exProc: TProc<string>; ACreateSuspended,
FreeOnComplete: Boolean);
var
func1: TFunc<boolean>;
func2: TProc<boolean>;
func3: TProc<string>;
begin
func1:= function (): boolean
begin
AthreadFunc();
result := true;
end;
func2:= procedure (b: boolean)
begin
GuiFunc();
end;
func3 := procedure (s: string)
begin
ExProc(s);
end;
Create(func1, func2, procedure (e: exception) begin func3(e.message) end, true, false);
SynchronizeFinish := true;
Start;
end;
{ TAnonymousIteratorCommand }
procedure TAnonymousIteratorCommand.DoExecute;
begin
inherited;
if count = 0 then
count := 1;
for var t:= 0 to count-1 do begin
proc(iteration+t);
end;
end;
end.
|
unit uEnviarEmail;
interface
uses
IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL,
IdSSLOpenSSL, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP, IdMessage,
IdAttachmentFile, System.SysUtils, System.Generics.Collections, uEmailBase;
type
TEmail = class(TEmailBase)
private
public
function EnviarEmail: Boolean; override;
end;
implementation
{ TEmail }
function TEmail.EnviarEmail: Boolean;
var
IdSSLIOHandlerSocket: TIdSSLIOHandlerSocketOpenSSL;
IdSMTP: TIdSMTP;
IdMessage: TIdMessage;
CaminhoAnexo: string;
Lista: TList<string>;
I: Integer;
sNomeArquivoAnexo: string;
begin
{
HOTMAIL:
Porta: 587
Host: smtp.live.com
YAHOO:
Porta: 587
Host: smtp.mail.yahoo.com
SERVIDOR PRÓPRIO:
Porta: 587
Host: smtp.servidorproprio.inf.br
GMAIL:
Porta: 465
Host: smtp.gmail.com
}
Result := False;
IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
IdSMTP := TIdSMTP.Create(nil);
IdMessage := TIdMessage.Create(nil);
Validacao;
try
// Configuração do SSL
IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23;
IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient;
// Configuração do SMTP
IdSMTP.IOHandler := IdSSLIOHandlerSocket;
if Porta = 465 then
IdSMTP.UseTLS := utUseImplicitTLS
else
IdSMTP.UseTLS := utUseExplicitTLS;
// IdSMTP.AuthType := satDefault;
IdSMTP.Port := Porta; // 587;
IdSMTP.Host := Host; //'smtp.mail.yahoo.com';
IdSMTP.Username := UserName;
IdSMTP.Password := Password;
if Autenticar then
IdSMTP.AuthType := satDefault
else
IdSMTP.AuthType := satNone;
// Tentativa de conexão e autenticação no maximo 60 segundos
try
IdSMTP.Connect;
if AutenticarSSL then
IdSMTP.Authenticate;
except
on E: Exception do
begin
raise Exception.Create('Erro na conexão e/ou autenticação: ' + E.Message + sLineBreak + ClassName);
end;
end;
case NivelPrioridade of
0: IdMessage.Priority := mpLow;
1: IdMessage.Priority := mpNormal;
2: IdMessage.Priority := mpHigh;
end;
// Configuração da mensagem
IdMessage.From.Address := MeuEmail; // meu email
IdMessage.From.Name := MeuNome; // meu nome
IdMessage.ReplyTo.EMailAddresses := IdMessage.From.Address;
IdMessage.Recipients.EMailAddresses := Destinatario; // destinatario
if Copia.Trim <> '' then
IdMessage.CCList.EMailAddresses := Copia;
if CopiaOculta.Trim <> '' then
IdMessage.BccList.EMailAddresses := CopiaOculta;
IdMessage.Subject := Assunto; // assunto do email
IdMessage.Body.Text := Texto; // corpo do email
IdMessage.Encoding := meMIME;
// auto resposta
if ConfirmarLeitura then
IdMessage.ReceiptRecipient.Text := IdMessage.From.Text;
if ArquivoAnexo = '' then
IdMessage.ContentType := 'text/html' // sem anexo quebrar textos com <br>
else
IdMessage.ContentType := 'multipart/mixed'; //com anexo quebrar textos com #13
IdMessage.CharSet := 'ISO-8859-1';
// Anexo da mensagem (opcional)
if ArquivoAnexo.Trim() <> '' then
begin
Lista := RetornarAnexos(ArquivoAnexo);
for I := 0 to Lista.Count -1 do
begin
sNomeArquivoAnexo := Lista.Items[i];
if not (FileExists(sNomeArquivoAnexo)) then
raise Exception.Create('Arquivo Anexo não Encontrado para enviar!');
TIdAttachmentFile.Create(IdMessage.MessageParts, sNomeArquivoAnexo);
end;
FreeAndNil(Lista);
end;
// Envio da mensagem
try
IdSMTP.Send(IdMessage);
Result := True;
// MessageDlg('Mensagem enviada com sucesso.', mtInformation, [mbOK], 0);
except
On E:Exception do
raise Exception.Create('Erro ao enviar a mensagem: ' + e.Message + sLineBreak + ClassName);
end;
finally
// liberação dos objetos da memória
if IdSMTP.Connected then
IdSMTP.Disconnect();
FreeAndNil(IdMessage);
FreeAndNil(IdSSLIOHandlerSocket);
FreeAndNil(IdSMTP);
end;
end;
end.
|
PROGRAM Hello_World (INPUT,OUTPUT);
BEGIN
WRITELN('Hello World :)')
END.
|
unit DW.FirebaseApp.Android;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
type
TPlatformFirebaseApp = class(TObject)
private
class var FStarted: Boolean;
public
class procedure Start;
end;
implementation
uses
// Android
Androidapi.Helpers,
// DW
DW.Androidapi.JNI.Firebase;
{ TPlatformFirebaseApp }
class procedure TPlatformFirebaseApp.Start;
begin
if not FStarted then
begin
TJFirebaseApp.JavaClass.initializeApp(TAndroidHelper.Context);
FStarted := True;
end;
end;
end.
|
unit iOSIdeIntf;
{$mode objfpc}{$H+}
interface
uses
Classes, Forms, ProjectIntf, iPhoneExtOptions, ComponentEditors;
type
{ TiOSApplicationDescriptor }
TiOSApplicationDescriptor = class(TProjectDescriptor)
public
constructor Create; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function InitProject(AProject: TLazProject): TModalResult; override;
function CreateStartFiles(AProject: TLazProject): TModalResult; override;
end;
{ TiOSObjectDelegateWindowFileDesc }
TiOSObjectDelegateWindowFileDesc = class(TFileDescPascalUnitWithResource)
protected
function GetDelegateProtocols: string; virtual;
public
constructor Create; override;
function GetInterfaceUsesSection: string; override;
function GetImplementationSource(const Filename, SourceName, ResourceName: string): string;override;
function GetInterfaceSource(const Filename, SourceName, ResourceName: string): string; override;
function GetUnitDirectives: string; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
end;
{ TiOSAppDelegateWindowFileDesc }
TiOSAppDelegateWindowFileDesc = class(TiOSObjectDelegateWindowFileDesc)
protected
function GetDelegateProtocols: string; override;
public
constructor Create; override;
end;
{ TiOSShowInXCode }
TiOSShowInXCode = Class(TComponentEditor)
private
FStartIndex : Integer;
Public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
var
GiOSApplicationDescriptor: TiOSApplicationDescriptor;
GiOSAppDelegateWindowFileDesc: TiOSAppDelegateWindowFileDesc;
GiOSObjectDelegateWindowFileDesc: TiOSObjectDelegateWindowFileDesc;
resourcestring
SShowInXCode = 'Show in XCode';
procedure register;
implementation
uses
LazIDEIntf, Controls, iOS_Views, iOSXIBResource, UnitResources,
LazFilesUtils,
sysutils,
FileUtil;
procedure register;
begin
GiOSApplicationDescriptor:=TiOSApplicationDescriptor.Create;
RegisterProjectDescriptor(GiOSApplicationDescriptor);
GiOSAppDelegateWindowFileDesc:=TiOSAppDelegateWindowFileDesc.Create;
RegisterProjectFileDescriptor(GiOSAppDelegateWindowFileDesc);
GiOSObjectDelegateWindowFileDesc:=TiOSObjectDelegateWindowFileDesc.Create;
RegisterProjectFileDescriptor(GiOSObjectDelegateWindowFileDesc);
RegisterComponentEditor(NSObject, TiOSShowInXCode);
RegisterUnitResourcefileFormat(TXIBResourcefileFormat);
end;
{ TiOSShowInXCode }
procedure TiOSShowInXCode.ExecuteVerb(Index: Integer);
var
s: string;
ProjFile: TLazProjectFile;
begin
If Index<FStartIndex then
inherited ExecuteVerb(Index)
else
case (Index-FstartIndex) of
0 : begin
ProjFile := LazarusIDE.GetProjectFileWithRootComponent(Component);
s := ChangeFileExt(ProjFile.Filename,'.xib');
if FileExistsUTF8(s) then ExecCmdLineNoWait('open "'+s+'"');
end;
end;
end;
function TiOSShowInXCode.GetVerb(Index: Integer): string;
begin
If Index<FStartIndex then
Result:=inherited GetVerb(Index)
else
case (Index-FstartIndex) of
0 : Result:=SShowInXCode;
end;
end;
function TiOSShowInXCode.GetVerbCount: Integer;
begin
FStartIndex:=inherited GetVerbCount;
Result:=FStartIndex+1;
end;
{ TiOSObjectDelegateWindowFileDesc }
function TiOSObjectDelegateWindowFileDesc.GetDelegateProtocols: string;
begin
result := '';
end;
constructor TiOSObjectDelegateWindowFileDesc.Create;
begin
inherited Create;
Name:='iOS NIB-Delegate';
ResourceClass:=NSObject;
DefaultResFileExt:='.xib';
UseCreateFormStatements:=false;
VisibleInNewDialog:=true;
end;
function TiOSObjectDelegateWindowFileDesc.GetInterfaceUsesSection: string;
begin
Result:='iPhoneAll';
end;
function TiOSObjectDelegateWindowFileDesc.GetImplementationSource(
const Filename, SourceName, ResourceName: string): string;
begin
Result:='procedure T'+ResourceName+'.dealloc;' + LineEnding +
'begin' + LineEnding +
' inherited dealloc;' + LineEnding +
'end;' + LineEnding +
LineEnding +
'{$FakeResource *.xib}' + LineEnding + LineEnding;
end;
function TiOSObjectDelegateWindowFileDesc.GetInterfaceSource(const Filename, SourceName, ResourceName: string): string;
var
DelegateProtocol: string;
begin
DelegateProtocol:=GetDelegateProtocols;
if DelegateProtocol<>'' then
DelegateProtocol:=','+DelegateProtocol;
Result:=
'type'+LineEnding
+' T'+ResourceName+' = objcclass('+ResourceClass.ClassName+DelegateProtocol+')'+LineEnding
+' private'+LineEnding
+' { private declarations }'+LineEnding
+' public'+LineEnding
+' procedure dealloc; override;'+LineEnding
+' end;'+LineEnding
+LineEnding;
end;
function TiOSObjectDelegateWindowFileDesc.GetUnitDirectives: string;
begin
Result:='{$modeswitch ObjectiveC1}';
end;
function TiOSObjectDelegateWindowFileDesc.GetLocalizedName: string;
begin
Result:='iOS NIB Delegate';
end;
function TiOSObjectDelegateWindowFileDesc.GetLocalizedDescription: string;
begin
Result:='Create a new iOS-NIB file with a delegate to handle it''s contents. '+
'The contents of the NIB can be changed with the designer.';
end;
{ TiOSAppDelegateWindowFileDesc }
function TiOSAppDelegateWindowFileDesc.GetDelegateProtocols: string;
begin
Result:='UIApplicationDelegateProtocol';
end;
constructor TiOSAppDelegateWindowFileDesc.Create;
begin
inherited Create;
Name:='iOS UIApplicationDelegate';
VisibleInNewDialog:=false;
end;
{ TiOSApplicationDescriptor }
constructor TiOSApplicationDescriptor.Create;
begin
inherited Create;
Name := 'iOS application';
end;
function TiOSApplicationDescriptor.GetLocalizedName: string;
begin
Result := 'iOS application';
end;
function TiOSApplicationDescriptor.GetLocalizedDescription: string;
begin
Result:='iOS application'#13#13'An iOS program '
+'designed in Lazarus without using the LCL. The program file is '
+'automatically maintained by Lazarus.';
end;
function TiOSApplicationDescriptor.InitProject(AProject: TLazProject): TModalResult;
var
NewSource: String;
MainFile: TLazProjectFile;
begin
inherited InitProject(AProject);
MainFile:=AProject.CreateProjectFile('iosapp.lpr');
MainFile.IsPartOfProject:=true;
AProject.AddFile(MainFile,false);
AProject.MainFileID:=0;
// create program source
NewSource:='program iosapp;' + LineEnding +
LineEnding +
'{$modeswitch ObjectiveC1}' + LineEnding +
LineEnding +
'uses' + LineEnding +
' iPhoneAll, AppDelegate_iPhoneU;' + LineEnding +
LineEnding +
'var' + LineEnding +
' pool : NSAutoreleasePool;' + LineEnding +
'begin' + LineEnding +
' pool := NSAutoreleasePool.alloc.init;' + LineEnding +
' UIApplicationMain(argc, argv, nil, nil);' + LineEnding +
' pool.release;' + LineEnding +
'end.' + LineEnding + LineEnding;
AProject.MainFile.SetSourceText(NewSource);
// add
AProject.AddPackageDependency('FCL');
// compiler options
AProject.LazCompilerOptions.Win32GraphicApp:=false;
//AProject.LazCompilerOptions.CustomOptions:='-XR/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk';
AProject.LazCompilerOptions.TargetOS:='iphonesim';
AProject.Flags := AProject.Flags - [pfMainUnitHasCreateFormStatements];
Result:= mrOK;
end;
function TiOSApplicationDescriptor.CreateStartFiles(AProject: TLazProject): TModalResult;
begin
//LazarusIDE.DoSaveAll([sfProjectSaving]);
GiOSAppDelegateWindowFileDesc.DefaultResourceName:='AppDelegate_iPhone';
LazarusIDE.DoNewEditorFile(GiOSAppDelegateWindowFileDesc,'appdelegate_iphoneu.pas','',[nfIsPartOfProject,nfOpenInEditor,nfCreateDefaultSrc]);
result := mrOK;
ProjOptions.Reset;
ProjOptions.isIPhoneApp:=true;
ProjOptions.MainNib:='appdelegate_iphoneu';
ProjOptions.Save;
end;
end.
|
unit MusiPlayer;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
MMSystem, stdctrls;
type
TMusiPlayer = class(TCustomControl)
private
{ Private-Deklarationen }
Sounds : array of Word;
ii : integer;
procedure CloseDevice(nr: Integer);
protected
{ Protected-Deklarationen }
public
Silent: Boolean;
Function PlayFile(Filename : string): Boolean;
procedure CloseFreeFiles;
procedure CloseAllFiles;
// How to awoid this warning?
constructor Create(AParent: TWinControl); reintroduce;
destructor Destroy; override;
{ Public-Deklarationen }
published
{ Published-Deklarationen }
end;
implementation
procedure TMusiPlayer.CloseAllFiles;
begin
while length(Sounds) > 0 do
begin
CloseDevice(0);
end;
end;
procedure TMusiPlayer.CloseDevice(nr: Integer);
var GenParm: TMCI_Generic_Parms;
i : integer;
begin
GenParm.dwCallback := Application.Handle;
mciSendCommand(Sounds[nr], mci_Close, 0, Longint(@GenParm));
for i := nr to length(sounds)-2 do
Sounds[i] := Sounds[i+1];
Setlength(Sounds,length(sounds)-1);
end;
procedure TMusiPlayer.CloseFreeFiles;
var i : integer;
StatusParm: TMCI_Status_Parms;
Len, Pos : integer;
begin
i := 0;
while i < length(Sounds) do
begin
StatusParm.dwItem := mci_Status_Length;
mciSendCommand(Sounds[i], mci_Status, mci_Wait or mci_Status_Item, Longint(@StatusParm));
Len := StatusParm.dwReturn;
StatusParm.dwItem := MCI_STATUS_POSITION;
mciSendCommand(Sounds[i], mci_Status, mci_Wait or mci_Status_Item, Longint(@StatusParm));
Pos := StatusParm.dwReturn;
if Pos >= Len then
CloseDevice(i)
else
inc(i);
end;
end;
constructor TMusiPlayer.Create(AParent: TWinControl);
begin
inherited Create(AParent);
Parent := AParent;
ii := 0;
Silent := false;
end;
destructor TMusiPlayer.Destroy;
begin
CloseAllFiles;
inherited;
end;
Function TMusiPlayer.PlayFile(Filename : string): Boolean;
var DeviceID: Word;
OpenParm: TMCI_Open_Parms;
FFlags: Longint;
PlayParm: TMCI_Play_Parms;
begin
Result := false;
if Silent then
Exit;
inc(ii);
if ii = high(ii) then
ii := 0;
FillChar(OpenParm, SizeOf(TMCI_Open_Parms), 0);
OpenParm.dwCallback := 0;
OpenParm.lpstrDeviceType := '';
OpenParm.lpstrElementName := PChar(FileName);
FFlags := MCI_OPEN_ELEMENT{ or MCI_OPEN_SHAREABLE }or MCI_OPEN_ALIAS;
OpenParm.dwCallback := Handle;
OpenParm.lpstrAlias := Pchar('MusiPlayerNR' + inttostr(ii) + ExtractFileName(filename));
if (mciSendCommand(0, mci_Open, FFlags, Longint(@OpenParm)) = 0) then
begin
DeviceID := OpenParm.wDeviceID;
PlayParm.dwCallback := Handle;
PlayParm.dwFrom := 0;
PlayParm.dwTo := 0;
FFlags := 0;
if mciSendCommand(DeviceID, mci_Play, FFlags, Longint(@PlayParm)) = 0 then
begin
Result := true;
setlength(sounds,length(sounds)+1);
Sounds[length(Sounds)-1] := DeviceID;
end;
end;
end;
end.
|
{$include lem_directives.inc}
unit LemLevelLoad;
interface
uses
Classes, SysUtils,
LemLevel;
type
// tlevelloadinfo = style, file etc.
TLevelLoader = class
private
protected
public
class procedure LoadLevelFromFile(const aFileName: string; aLevel: TLevel);
class procedure SaveLevelToFile(aLevel: TLevel; const aFileName: string);
class procedure LoadLevelFromStream(aStream: TStream; aLevel: TLevel; OddLoad: Boolean = false); virtual; abstract;
class procedure StoreLevelInStream(aLevel: TLevel; aStream: TStream); virtual; abstract;
// class procedure LoadLevel(LoadInfo: ILevelLoadInfo); virtual;
published
end;
implementation
{ TLevelLoader }
class procedure TLevelLoader.LoadLevelFromFile(const aFileName: string; aLevel: TLevel);
var
F: TFileStream;
begin
F := TFileStream.Create(aFileName, fmOpenRead);
try
LoadLevelFromStream(F, aLevel);
finally
F.Free;
end;
end;
class procedure TLevelLoader.SaveLevelToFile(aLevel: TLevel; const aFileName: string);
var
F: TFileStream;
begin
F := TFileStream.Create(aFileName, fmCreate);
try
StoreLevelInStream(aLevel, F);
finally
F.Free;
end;
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 ClpAsn1TaggedObject;
{$I ..\Include\CryptoLib.inc}
interface
uses
SysUtils,
ClpCryptoLibTypes,
ClpIAsn1Sequence,
ClpAsn1Tags,
ClpAsn1Set,
ClpIAsn1Set,
ClpIAsn1Choice,
ClpAsn1Encodable,
ClpAsn1Object,
ClpIProxiedInterface,
ClpIAsn1TaggedObject,
ClpIAsn1TaggedObjectParser;
resourcestring
SImplicitObject = 'Implicitly Tagged Object';
SUnknownObject = 'Unknown object in GetInstance: %s "obj"';
SImplicitTag = 'Implicit Tagging for Tag: %d';
type
/// **
// * ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by
// * a [n] where n is some number - these are assumed to follow the construction
// * rules (as with sequences).
// */
TAsn1TaggedObject = class abstract(TAsn1Object, IAsn1TaggedObject,
IAsn1TaggedObjectParser)
strict private
FtagNo: Int32;
Fexplicitly: Boolean;
Fobj: IAsn1Encodable;
function GetTagNo: Int32; inline;
function Getexplicitly: Boolean; inline;
function Getobj: IAsn1Encodable; inline;
strict protected
// /**
// * @param tagNo the tag number for this object.
// * @param obj the tagged object.
// */
constructor Create(tagNo: Int32; const obj: IAsn1Encodable); overload;
// /**
// * @param explicitly true if the object is explicitly tagged.
// * @param tagNo the tag number for this object.
// * @param obj the tagged object.
// */
constructor Create(explicitly: Boolean; tagNo: Int32;
const obj: IAsn1Encodable); overload;
function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override;
function Asn1GetHashCode(): Int32; override;
public
class function IsConstructed(isExplicit: Boolean; const obj: IAsn1Object)
: Boolean; static;
class function GetInstance(const obj: IAsn1TaggedObject;
explicitly: Boolean): IAsn1TaggedObject; overload; static; inline;
class function GetInstance(obj: TObject): IAsn1TaggedObject; overload;
static; inline;
property tagNo: Int32 read GetTagNo;
property explicitly: Boolean read Getexplicitly;
property obj: IAsn1Encodable read Getobj;
// /**
// * return whether or not the object may be explicitly tagged.
// * <p>
// * Note: if the object has been read from an input stream, the only
// * time you can be sure if isExplicit is returning the true state of
// * affairs is if it returns false. An implicitly tagged object may appear
// * to be explicitly tagged, so you need to understand the context under
// * which the reading was done as well, see GetObject below.</p>
// */
function isExplicit(): Boolean; inline;
function IsEmpty(): Boolean; inline;
// /**
// * return whatever was following the tag.
// * <p>
// * Note: tagged objects are generally context dependent if you're
// * trying to extract a tagged object you should be going via the
// * appropriate GetInstance method.</p>
// */
function GetObject(): IAsn1Object; inline;
// /**
// * Return the object held in this tagged object as a parser assuming it has
// * the type of the passed in tag. If the object doesn't have a parser
// * associated with it, the base object is returned.
// */
function GetObjectParser(tag: Int32; isExplicit: Boolean): IAsn1Convertible;
function ToString(): String; override;
end;
implementation
uses
// included here to avoid circular dependency :)
ClpAsn1Sequence,
ClpAsn1OctetString;
{ TAsn1TaggedObject }
function TAsn1TaggedObject.GetObject: IAsn1Object;
begin
if (Fobj <> Nil) then
begin
result := Fobj.ToAsn1Object();
Exit;
end;
result := Nil;
end;
function TAsn1TaggedObject.GetTagNo: Int32;
begin
result := FtagNo;
end;
function TAsn1TaggedObject.Getexplicitly: Boolean;
begin
result := Fexplicitly;
end;
function TAsn1TaggedObject.Asn1Equals(const asn1Object: IAsn1Object): Boolean;
var
other: IAsn1TaggedObject;
begin
if (not Supports(asn1Object, IAsn1TaggedObject, other)) then
begin
result := false;
Exit;
end;
result := ((tagNo = other.tagNo) and
// TODO Should this be part of equality?
(explicitly = other.explicitly)) and
(GetObject().Equals(other.GetObject()));
end;
function TAsn1TaggedObject.Asn1GetHashCode: Int32;
var
code: Int32;
begin
code := Abs(tagNo);
// TODO: actually this is wrong - the problem is that a re-encoded
// object may end up with a different hashCode due to implicit
// tagging. As implicit tagging is ambiguous if a sequence is involved
// it seems the only correct method for both equals and hashCode is to
// compare the encodings...
// code := code xor explicitly.GetHashCode();
if (Fobj <> Nil) then
begin
code := code xor Fobj.GetHashCode();
end;
result := code;
end;
constructor TAsn1TaggedObject.Create(tagNo: Int32; const obj: IAsn1Encodable);
begin
Inherited Create();
Fexplicitly := true;
FtagNo := tagNo;
Fobj := obj;
end;
constructor TAsn1TaggedObject.Create(explicitly: Boolean; tagNo: Int32;
const obj: IAsn1Encodable);
begin
Inherited Create();
// IAsn1Choice marker interface 'insists' on explicit tagging
Fexplicitly := explicitly or (Supports(obj, IAsn1Choice));
FtagNo := tagNo;
Fobj := obj;
end;
class function TAsn1TaggedObject.GetInstance(obj: TObject): IAsn1TaggedObject;
begin
if ((obj = Nil) or (obj is TAsn1TaggedObject)) then
begin
result := obj as TAsn1TaggedObject;
Exit;
end;
raise EArgumentCryptoLibException.CreateResFmt(@SUnknownObject,
[obj.ClassName]);
end;
function TAsn1TaggedObject.Getobj: IAsn1Encodable;
begin
result := Fobj;
end;
class function TAsn1TaggedObject.GetInstance(const obj: IAsn1TaggedObject;
explicitly: Boolean): IAsn1TaggedObject;
begin
if (explicitly) then
begin
result := obj.GetObject() as IAsn1TaggedObject;
Exit;
end;
raise EArgumentCryptoLibException.CreateRes(@SImplicitObject);
end;
function TAsn1TaggedObject.GetObjectParser(tag: Int32; isExplicit: Boolean)
: IAsn1Convertible;
begin
case tag of
TAsn1Tags.&Set:
begin
result := TAsn1Set.GetInstance(Self as IAsn1TaggedObject,
isExplicit).Parser;
Exit;
end;
TAsn1Tags.Sequence:
begin
result := TAsn1Sequence.GetInstance(Self as IAsn1TaggedObject,
isExplicit).Parser;
Exit;
end;
TAsn1Tags.OctetString:
begin
result := TAsn1OctetString.GetInstance(Self as IAsn1TaggedObject,
isExplicit).Parser;
Exit;
end;
end;
if (isExplicit) then
begin
result := GetObject();
Exit;
end;
raise ENotImplementedCryptoLibException.CreateResFmt(@SImplicitTag, [tag]);
end;
class function TAsn1TaggedObject.IsConstructed(isExplicit: Boolean;
const obj: IAsn1Object): Boolean;
var
tagged: IAsn1TaggedObject;
begin
if ((isExplicit) or (Supports(obj, IAsn1Sequence)) or
(Supports(obj, IAsn1Set))) then
begin
result := true;
Exit;
end;
if (not Supports(obj, IAsn1TaggedObject, tagged)) then
begin
result := false;
Exit;
end;
result := IsConstructed(tagged.isExplicit(), tagged.GetObject());
end;
function TAsn1TaggedObject.IsEmpty: Boolean;
begin
result := false; // empty;
end;
function TAsn1TaggedObject.isExplicit: Boolean;
begin
result := Fexplicitly;
end;
function TAsn1TaggedObject.ToString: String;
begin
result := '[' + IntToStr(tagNo) + ']' + (Fobj as TAsn1Encodable).ClassName;
end;
end.
|
unit UDaoImagemDSClient;
interface
uses
Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy,
System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXJSONReflect,
UConstante;
type
TdaoImagemDSClient = class(TDSAdminClient)
private
FImagemCommand: TDBXCommand;
FAlteraImagemCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function Imagem: OleVariant;
function AlteraImagem(O: TJSONValue): Boolean;
end;
implementation
{ TdaoImagemClient }
function TdaoImagemDSClient.AlteraImagem(O: TJSONValue): Boolean;
begin
if FAlteraImagemCommand = nil then
begin
FAlteraImagemCommand := FDBXConnection.CreateCommand;
FAlteraImagemCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FAlteraImagemCommand.Text := _srv00021;
FAlteraImagemCommand.Prepare;
end;
FAlteraImagemCommand.Parameters[0].Value.SetJSONValue(O, FInstanceOwner);
FAlteraImagemCommand.ExecuteUpdate;
Result := FAlteraImagemCommand.Parameters[1].Value.GetBoolean;
end;
constructor TdaoImagemDSClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
constructor TdaoImagemDSClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
destructor TdaoImagemDSClient.Destroy;
begin
FreeAndNil(FImagemCommand);
FreeAndNil(FAlteraImagemCommand);
inherited;
end;
function TdaoImagemDSClient.Imagem: OleVariant;
begin
if FImagemCommand = nil then
begin
FImagemCommand := FDBXConnection.CreateCommand;
FImagemCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FImagemCommand.Text := _srv00022;
FImagemCommand.Prepare;
end;
FImagemCommand.ExecuteUpdate;
Result := FImagemCommand.Parameters[0].Value.AsVariant;
end;
end.
|
unit ev;
{ Библиотека "Эверест" }
{ Начал: Люлин А.В. }
{ Модуль: ev - }
{ Начат: 28.09.1999 10:18 }
{ $Id: ev.pas,v 1.1 2008/04/16 08:40:37 lulin Exp $ }
// $Log: ev.pas,v $
// Revision 1.1 2008/04/16 08:40:37 lulin
// - выделяем фасад для скрытия различий старого и нового редакторов.
//
// Revision 1.6 2005/05/30 14:48:01 lulin
// - объединил с веткой.
//
// Revision 1.5.6.1 2005/05/18 12:42:45 lulin
// - отвел новую ветку.
//
// Revision 1.4.4.1 2005/04/28 09:18:28 lulin
// - объединил с веткой B_Tag_Box.
//
// Revision 1.5 2005/04/12 09:58:31 lulin
// - вставлена более правильная директива - чтобы было удобнее искать.
//
// Revision 1.4 2004/11/02 12:47:30 lulin
// - поправлен заголовок об авторстве, т.к. оно у нас давно очень размыто.
//
// Revision 1.3 2000/12/15 15:10:33 law
// - вставлены директивы Log.
//
{$Include evDefine.inc }
interface
implementation
end.
|
{$R+}
{$B+}
program TesteSortiereListe(input, output);
{ sortiert eine Liste durch Einfügen }
type
tNatZahl = 0..maxint;
tRefListe = ^tListe;
tListe = record
wert : tNatZahl;
next : tRefListe;
end;
var
RefListe : tRefListe;
inSuchwert : tNatZahl;
gefunden: boolean;
procedure moveToFront (
inSuchwert : integer;
var ioAnfang : tRefListe;
var outGefunden : boolean);
{ bestimmt in einer linearen Liste das erste Element mit dem
Wert inSuchwert und positioniert es als erstes Listen-
element }
var
ZuletztGeprueftesElement,
UmhaengeHilfe : tRefListe;
gefunden : boolean;
begin
gefunden := false;
if ioAnfang <> nil then { Liste ist nicht leer }
if ioAnfang^.wert = inSuchwert then
{ gefundenes Element ist schon das erste Element }
gefunden := true
else
begin
ZuletztGeprueftesElement := ioAnfang;
while (ZuletztGeprueftesElement^.next <> nil) and not gefunden do
if ZuletztGeprueftesElement^.next^.wert = inSuchwert then
begin { Suchwert ist gefunden }
gefunden := true;
{ **Umhaengen** }
UmhaengeHilfe := ZuletztGeprueftesElement^.next;
UmhaengeHilfe^.next := ZuletztGeprueftesElement^.next;
ZuletztGeprueftesElement^.next := ioAnfang;
ioAnfang := ZuletztGeprueftesElement;
end
else
ZuletztGeprueftesElement := ZuletztGeprueftesElement^.next
end; { else }
outGefunden := gefunden
end; { moveToFront }
procedure Anhaengen(inZahl : tNatZahl; var ioListe : tRefListe);
{ Haengt inZahl an ioListe an }
var
Zeiger : tRefListe;
begin
Zeiger := ioListe;
if Zeiger = nil then
begin
new(ioListe);
ioListe^.wert := inZahl;
ioListe^.next := nil;
end
else
begin
while Zeiger^.next <> nil do
Zeiger := Zeiger^.next;
new(Zeiger^.next);
Zeiger := Zeiger^.next;
Zeiger^.wert := inZahl;
Zeiger^.next := nil;
end;
end;
procedure ListeEinlesen(var outListe:tRefListe; var outSuchwert:tNatZahl);
{ liest eine Folge von Zahlen ein }
var
Liste : tRefListe;
Zahl,
Zahl2: integer;
begin
Liste := nil;
read(Zahl);
while Zahl<>-1 do
begin
Anhaengen(Zahl, Liste);
read(Zahl)
end;
writeln('Bitte SUchzahl angeben');
read(Zahl2);
outListe := Liste;
outSuchwert:= Zahl2
end;
procedure GibListeAus(inListe : tRefListe);
{ Gibt die eine nicht-leere Liste aus }
var
Zeiger : tRefListe;
begin
Zeiger := inListe;
write(Zeiger^.wert);
Zeiger := Zeiger^.next;
while Zeiger <> nil do
begin
write(', ');
write(Zeiger^.wert);
Zeiger := Zeiger^.next;
end;
writeln('')
end;
begin
ListeEinlesen(RefListe,inSuchwert);
moveToFront(inSuchwert,RefListe,gefunden);
GibListeAus(RefListe)
end.
end;
{leider war mir der Sinn des boolean istEingefügt schleierhaft, ich habe daher auf Verwendung verzichtet}
|
{
mksymbian.pas
Main program file
Copyright (C) 2006-2007 Felipe Monteiro de Carvalho
This file is part of MkSymbian build tool.
MkSymbian is free software;
you can redistribute it and/or modify it under the
terms of the GNU General Public License version 2
as published by the Free Software Foundation.
MkSymbian 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.
Please note that the General Public License version 2 does not permit
incorporating MkSymbian into proprietary programs.
}
program mksymbian;
{$ifdef fpc}
{$mode delphi}{$H+}
{$endif}
{$apptype console}
uses
Classes, SysUtils,
cmdline, constants, cfgfile, sdkutil, compiler, projectparser;
var
opts: TMkSymbianOptions;
begin
vProject := TProject.Create;
vSDKUtil := TSDKUtil.Create;
vCmdLine := TCmdLine.Create;
vCompiler := TCompiler.Create;
try
vCmdLine.ParseCmdLineOptions(opts);
vCompiler.opts := opts;
vProject.opts := opts;
case opts.task of
stBuildApp:
begin
vProject.ParseFile;
{ compilation }
if CompareText(vProject.Language, STR_OPT_Cpp) = 0 then
vCompiler.MakeBuildCpp
else
vCompiler.MakeBuildPascal;
if vSDKUtil.SDKVersion = sdkUIQ3 then
begin
{ Main resource file }
vCompiler.BuildResource(vProject.MainResource);
vCompiler.InstallResource(vProject.MainResource);
{ Registration resource file }
vCompiler.BuildResource(vProject.RegResource);
vCompiler.RegisterInEmulator;
end;
end;
stBuildBindings:
begin
vProject.ParseFile;
vCompiler.MakeBuildBindings;
end;
end;
finally
vCmdLine.Free;
vSDKUtil.Free;
vCompiler.Free;
vProject.Free;
end;
end.
|
//-----------------------------------------------------------------+
// Global Function
// 파일이나 문자열 처리시에 간편하게 쓰고자 만든 함수들의 모음.
//-----------------------------------------------------------------+
unit Unit_GlobalFunction;
interface
uses
Classes, SysUtils, iniFiles, DB, Variants, HashMap, DCL_intf;
function CreateTextFile(filePath: string): Boolean;
{Global Function}
procedure TextFileAppend(filePath, msg: String);
function CreateAllDir(directory: String): Boolean;
function GetParentDir(const Directory: String): String;
function StringSplit(const Delimiter: Char; Input: string): TStrings;
function CopyFile(oldFile, newFile: String): Boolean;
function MoveFile(oldFile, newFile: String): Boolean;
function GetDataFromIniFile(filePath, section: string; keyValue: array of String):
TStringList; overload;
function GetDataFromIniFile(filePath, section: string; sKey: String ): string;
overload;
function TrimSpace(S: String): String;
function StrFind(const S: String; Sub: Char; var Index: Integer): String;
function StrScanf(ScanStr: String; FmtStr: string; ValArr: array of Pointer)
: integer;
function CalcDBNameByPath(strPath : string): string;
implementation
uses
Windows;
{Global Function}
//-----------------------------------------------------------------+
// 텍스트 파일의 기존 내용에 새로이 추가 해 준다.
// 만약 지정한 경로에 파일이 없을 경우 새로 생성 한다.
// filePath: 내용을 추가 할 텍스트 파일의 경로.
// msg: 추가할 내용.
//-----------------------------------------------------------------+
procedure TextFileAppend(filePath, msg: String);
var
targetFile: TextFile;
begin
CreateTextFile(filePath);
AssignFile(targetFile, filePath);
Append(targetFile);
Writeln(targetFile, msg);
CloseFile(targetFile);
end;
//-----------------------------------------------------------------+
// 지정한 경로에 텍스트 파일을 만든다.
// 만약 그 경로에 해당되는 부모 폴더가 없다면 스스로 만든다.
// filePath: 텍스트 파일을 만들 경로.
//-----------------------------------------------------------------+
function CreateTextFile(filePath: string): Boolean;
var
iFileHandlerId: Integer;
begin
try
CreateAllDir(GetParentDir(filePath));
if FileExists(filePath) = false then
begin
iFileHandlerId := FileCreate(filePath);
SysUtils.FileClose(iFileHandlerId);
end;
result := true;
except
result := false;
end;
end;
//-----------------------------------------------------------------+
// 설정한 경로의 폴더를 만든다.
// 만약 상위 폴더가 없다면 그것도 함께 만든다. (재귀 호출 사용)
// directory: 폴더를 만들 경로./
//-----------------------------------------------------------------+
function CreateAllDir(directory: String): Boolean;
var
targetFile: TextFile;
parentPath: String;
iFileHandlerId: Integer;
begin
parentPath := GetParentDir(directory);
try
if DirectoryExists(parentPath) = false then
begin
CreateAllDir(parentPath);
end;
CreateDir(directory);
result := true;
except
result := false;
end;
end;
//-----------------------------------------------------------------+
// 지정한 경로를 통해 부모 폴더의 경로를 얻는다.
// Directory: 부모 폴더의 경로를 얻고 싶은 전체 경로.
//-----------------------------------------------------------------+
function GetParentDir(const Directory: String): String;
var
TempStr: String;
begin
TempStr := Directory;
if (TempStr[Length(Result)] = '\') then
begin
Delete(TempStr, Length(TempStr), 1);
end;
Result := Copy(TempStr, 1, LastDelimiter('\', TempStr) - 1);
end;
//-----------------------------------------------------------------+
// 입력한 문자열을 지정한 문자를 기준으로 쪼개어 준다.
// Delimiter: 쪼갤 기준이 될 문자.
// Input: 쪼갤 대상 문자열.
// 출처 : http://delphi.about.com/cs/adptips2002/a/bltip1102_5.htm
//-----------------------------------------------------------------+
function StringSplit(const Delimiter: Char; Input: string): TStrings;
var
Strings: TStrings;
begin
Strings := TStrings.Create;
//Assert(Assigned(Strings));
//Strings.Clear;
Strings.Delimiter := Delimiter;
Strings.DelimitedText := Input;
result := @Strings;
end;
function CopyFile(oldFile, newFile: String): Boolean;
begin
Windows.CopyFile(PChar(oldFile), PChar(newFile), true);
end;
function MoveFile(oldFile, newFile: String): Boolean;
begin
Windows.MoveFile(PChar(oldFile), PChar(newFile));
end;
function GetDataFromIniFile(filePath, section: string; keyValue: array of String):
TStringList;
var
sList: TStringList;
iniFile: TIniFile;
i: Integer;
iLength: Integer;
begin
sList := TStringList.Create;
iniFile := TIniFile.Create( filePath );
iLength := High(KeyValue);
for i := 0 to iLength do
begin
sList.Add( iniFile.ReadString( section, keyValue[ i ], '' ) );
end;
iniFile.Free;
result := sList;
end;
function GetDataFromIniFile(filePath, section: string; sKey: String ): string;
overload;
var
sValue : string;
iniFile: TIniFile;
begin
Result := '';
try
iniFile := TIniFile.Create( filePath );
sValue := iniFile.ReadString( section, sKey, '' );
iniFile.Free;
finally
result := sValue;
end;
end;
function TrimSpace(S: String): String;
var
Prev: Boolean;
Count, i: Integer;
begin
S := Trim(S);
SetLength(Result, Length(S));
Prev := False;
Count := 1;
for i:=1 to Length(S) do
begin
if S[i] = ' ' then
begin
if Prev = True then
begin
Result[Count] := S[i];
inc(Count);
Prev := False;
end;
end
else begin
Result[Count] := S[i];
inc(Count);
Prev := True;
end;
end;
SetLength(Result, Count-1);
end;
function StrFind(const S: String; Sub: Char; var Index: Integer): String;
var
i, len: Integer;
begin
Result := '';
len := Length(S);
if (Index < 1) or (index > len) then
begin
Assert(False, 'StrFind()::String['+IntToStr(Index)+'] Index 오류');
Exit;
end;
for i:=index to len do
begin
if s[i] = Sub then
begin
Result := Copy(S, Index, i-Index);
Index := i+1;
Exit;
end;
end;
Result := Copy(S, Index, len-Index+1);
Index := len+1;
end;
function StrScanf(ScanStr: String; FmtStr: string; ValArr: array of Pointer) : integer;
var
FmtN, ScanN, vtype, valArrIndex: Integer;
CurS: String;
ch: Char;
begin
Result := 0;
ch := ' ';
vType := 0;
FmtN := 1;
ScanN := 1;
valArrIndex := 0;
ScanStr := TrimSpace(ScanStr);
FmtStr := TrimSpace(FmtStr);
while (FmtN <= Length(FmtStr)) and (ScanN <= Length(ScanStr)) do
begin
if FmtStr[FmtN] = '%' then
begin
if FmtStr[FmtN+1] = 'd' then vType := 1
else if FmtStr[FmtN+1] = 'f' then vType := 2
else if FmtStr[FmtN+1] = 's' then vType := 3
else begin
//vType := 0;
Assert(False, '%'+FmtStr[FmtN+1]+' 타입 오류');
Exit;
end;
inc(FmtN, 2);
if (FmtN <= Length(FmtStr)) then
ch := FmtStr[FmtN];
end
else if FmtStr[FmtN]<>ScanStr[ScanN] then break;
if (vType <> 0) then
begin
CurS := StrFind(ScanStr, ch, ScanN);
if (CurS <> '') then
begin
if (ValArr[valArrIndex] <> nil) then
begin
case vType of
1: Integer(ValArr[valArrIndex]^) := StrToInt(CurS);
2: Single(ValArr[valArrIndex]^) := StrToFloat(CurS);
3: String(ValArr[valArrIndex]^) := CurS;
end;
end;
inc(valArrIndex);
inc(Result);
vType := 0;
end;
end
else Inc(ScanN);
Inc(FmtN);
end;
end;
function CalcDBNameByPath(strPath : string): string;
var
sDBName : string;
iPos : Integer;
begin
sDBName := strPath;
iPos := LastDelimiter('\', sDBName );
sDBName := copy( sDBName, iPos + 1, length(sDBName) - iPos );
iPos := LastDelimiter('.', sDBName );
sDBName := copy( sDBName, 0, iPos - 1 );
sDBName := UpperCase( sDBName );
sDBName := StringReplace( sDBName, '.', '_', [] );
sDBName := StringReplace( sDBName, '-', '_', [] );
result := sDBName;
end;
end.
|
{====================================================}
{ }
{ EldoS Visual Components }
{ }
{ Copyright (c) 1998-2003, EldoS Corporation }
{ }
{====================================================}
{$I ..\ElPack.inc}
unit FormCtlProp;
interface
uses
{$ifdef VCL_6_USED}
DesignIntf, DesignEditors, DesignWindows, DsnConst,
{$else}
DsgnIntf,
{$endif}
ToolIntf, EditIntf, ExptIntf, Windows, Dialogs, TypInfo, Classes, SysUtils,
Consts, Forms;
type
TFormCtlProperty = class(TComponentProperty)
public
procedure GetValues(Proc : TGetStrProc); override;
procedure SetValue(const Value : string); override;
end;
type
TFormProperty = class(TEnumProperty)
private
List : TStringList;
FormName,
FileName : String;
{$IFDEF VCL_4_USED}
procedure EnumProc(const FileName, UnitName, FormName, DesignClass: string; CoClasses: TStrings);
procedure FNProc(const FileName, UnitName, FormName, DesignClass: string; CoClasses: TStrings);
{$ENDIF}
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
implementation
procedure TFormCtlProperty.GetValues(Proc : TGetStrProc);
begin
inherited;
if (Designer.Form is GetTypeData(GetPropType)^.ClassType) and
(Designer.Form.Name <> '') then Proc(Designer.Form.Name);
end;
procedure TFormCtlProperty.SetValue(const Value : string);
var
Comp : TComponent;
begin
Comp := Designer.GetComponent(Value);
if ((Comp = nil) or not (Comp is GetTypeData(GetPropType)^.ClassType))
and (CompareText(Designer.Form.Name, Value) = 0) then
begin
if not (Designer.Form is GetTypeData(GetPropType)^.ClassType) then
begin
MessageDlg(Format('Invalid property value: %s expected, %s found',
[Designer.Form.ClassName, GetTypeData(GetPropType)^.ClassType.ClassName]),
mtError, [mbOk], 0);
raise
EPropertyError.Create(SInvalidPropertyValue);
end;
SetOrdValue(Longint(Designer.Form));
end
else
inherited;
end;
function TFormProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList];
end;
function TFormProperty.GetValue: string;
begin
Result := GetStrValue;
end;
{$IFDEF VCL_4_USED}
procedure TFormProperty.EnumProc(const FileName, UnitName, FormName, DesignClass: string; CoClasses: TStrings);
begin
if FormName <> '' then
List.Add(FormName);
end;
procedure TFormProperty.FNProc(const FileName, UnitName, FormName, DesignClass: string; CoClasses: TStrings);
begin
if Self.FormName = FormName then
begin
Self.FileName := FormName;
end;
end;
{$ENDIF}
procedure TFormProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
begin
List := TStringList.Create;
try
{$IFDEF VCL_4_USED}
Designer.GetProjectModules(EnumProc);
{$ENDIF}
for i := 0 to List.Count - 1 do Proc(List[i]);
finally
List.Free;
end;
end;
procedure TFormProperty.SetValue(const Value: string);
begin
if Value = '' then SetStrValue('') else
begin
FormName := Value;
FileName := '';
{$IFDEF VCL_4_USED}
Designer.GetProjectModules(FNProc);
SetStrValue(FileName);
{$ELSE}
SetStrValue(FormName);
{$ENDIF}
end;
end;
end.
|
unit Providers.Mascara.Data;
interface
uses
Providers.Mascaras.Intf, System.MaskUtils, System.SysUtils;
type
TMascaraData = class(TInterfacedObject, IMascaras)
private
procedure RemoveBarras(var Value: string);
public
function ExecMask(Value: string): string;
end;
implementation
{ TMascaraData }
function TMascaraData.ExecMask(Value: string): string;
begin
RemoveBarras(Value);
Result := FormatMaskText('00\/00\/0000;0;', Value);
end;
procedure TMascaraData.RemoveBarras(var Value: string);
begin
Delete(Value, AnsiPos('/', Value), 1);
Delete(Value, AnsiPos('/', Value), 1);
end;
end.
|
unit GridForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Db, DBTables, Grids, DBGrids, ExtCtrls, MdDbGrid;
type
TForm1 = class(TForm)
MdDbGrid1: TMdDbGrid;
DataSource1: TDataSource;
Table1: TTable;
Panel1: TPanel;
Button1: TButton;
Label1: TLabel;
Button2: TButton;
Button3: TButton;
Button4: TButton;
FontDialog1: TFontDialog;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
MdDbGrid1.LinesPerRow :=
MdDbGrid1.LinesPerRow + 1;
Label1.Caption := 'Rows: ' +
IntToStr (MdDbGrid1.LinesPerRow)
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
MdDbGrid1.LinesPerRow :=
MdDbGrid1.LinesPerRow - 1;
Label1.Caption := 'Rows: ' +
IntToStr (MdDbGrid1.LinesPerRow)
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
FontDialog1.Font := MdDbGrid1.Font;
if FontDialog1.Execute then
MdDbGrid1.Font := FontDialog1.Font;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
FontDialog1.Font := MdDbGrid1.TitleFont;
if FontDialog1.Execute then
MdDbGrid1.TitleFont := FontDialog1.Font;
end;
end.
|
program ejercicio1;
type
str40 = String[40];
planta = record
nomCientifico : str40;
tiempoVida : Integer;
tipoPlanta : str40;
clima : str40;
pais : str40;
end;
procedure leerPlanta(var p:planta);
begin
with p do
begin
write('Ingrese el nombre CIENTIFICO: ');
readln(nomCientifico);
write('Ingrese el TIEMPO DE VIDA (en meses): ');
readln(tiempoVida);
write('Ingrese el TIPO DE PLANTA: ');
readln(tipoPlanta);
write('Ingrese tipo de CLIMA: ');
readln(clima);
write('Ingrese nombre del PAIS donde se encuentra: ');
readln(pais);
end;
end;
procedure menorCantidadPlantas(tipoPlanta: str40; contTipoPlanta: Integer; var min1:Integer; var nomMin1:str40); //inciso A
begin
if (contTipoPlanta <= min1) then
begin
min1:= contTipoPlanta;
nomMin1:= tipoPlanta;
end;
end;
procedure tiempoPromedioVida (contTipoPlanta:Integer; sumaMes:Integer; var promedio: Real); //inciso B
begin
promedio:= sumaMes / contTipoPlanta;
end;
procedure masLongevas(p:planta; var max1,max2: Integer; var nomMax1, nomMax2: str40); //inciso C
begin
if (p.tiempoVida >= max1) then
begin
max2:= max1;
nomMax2:= nomMax1;
max1:= p.tiempoVida;
nomMax1:= p.nomCientifico;
end
else
if (p.tiempoVida >= max2) then
begin
max2:= p.tiempoVida;
nomMax2:= p.nomCientifico;
end;
end;
procedure plantasNativasArgentina(p:planta); //inciso D
begin
if (p.pais = 'argentina') and (p.clima = 'subtropical') then
begin
writeln('Esto es una planta nativa de Argentina ', p.nomCientifico, ' y se encuentra en clima subtropical');
end;
end;
procedure plantaMasPaises(nomCientifico: str40 ; contPlantaPais: Integer; var max: Integer; var nomMax: str40); //inciso E
begin
if (contPlantaPais >= max) then
begin
max:=contPlantaPais;
nomMax:= nomCientifico;
end;
end;
var
p: planta;
contTipoPlanta, contPlantaPais, min1, max1, max2, max, contWhile,i: Integer;
sumaMes: Integer;
nomMax,nomMax1,nomMax2, nomMin1, tipoActual: str40;
promedio: Real;
begin
min1:= 9999;
max:= -1;
max1:= -1;
max2:= -1;
nomMax:= '';
nomMax1:= '';
nomMax1:= '';
nomMin1:= '';
tipoActual:= '';
promedio:= 0;
contWhile:= 0;
while (contWhile <= 320) do
begin
contWhile:= contWhile + 1;
leerPlanta(p);
contTipoPlanta:=0;
contPlantaPais:=0;
sumaMes:= 0;
tipoActual:= p.tipoPlanta;
while (tipoActual = p.tipoPlanta) and (p.pais <> 'zzz') do //se estan ingresando ordenadado por TIPO
begin
contTipoPlanta:= contTipoPlanta + 1; //contador para el inciso A
sumaMes:= sumaMes + p.tiempoVida; // sumo los meses para poder realizar el proemdio del inciso B
masLongevas(p,max1,max2,nomMax1,nomMax2); // llamo al inciso C
while (p.pais <> 'zzz') do
begin
plantasNativasArgentina(p); //llamo inciso D
contPlantaPais:= contPlantaPais + 1;
write('Ingrese nombre del PAIS donde se encuentra: ');
readln(p.pais);
end;
writeln('--------------------------------------------');
plantaMasPaises(p.nomCientifico, contPlantaPais, max, nomMax);// llamo al inciso E
leerPlanta(p);
tipoActual:= p.tipoPlanta;
end;
menorCantidadPlantas(p.tipoPlanta,contTipoPlanta,min1,nomMin1); // llamo al proceso del inciso A
tiempoPromedioVida(contTipoPlanta,sumaMes,promedio); //llamo al inciso B
writeln('El tiempo promedio de la planta del tipo: ', p.tipoPlanta, ' es: ', promedio );
end;
writeln('El tipo de planta con menor cantidad de plantas es: ', nomMin1);
writeln('El nombre cientifico de las dos plantas mas longevas son: ',nomMax1, ' y ', nomMax1 );
writeln('El nombre de la planta que se encuentra en mas paises es: ', max);
readln();
end.
|
unit uDSRestLib;
interface
uses
uAppUtils;
const
_PANJANG_NOBUKTI_ANGKA : Integer = 10;
type
TDSRestLib = class(TObject)
public
class function FormatNoBukti(APrefix : String; ACounter : Integer): string;
end;
implementation
class function TDSRestLib.FormatNoBukti(APrefix : String; ACounter : Integer):
string;
begin
Result := APrefix + '.' + TAppUtils.TambahkanKarakterNol(ACounter, _PANJANG_NOBUKTI_ANGKA);
end;
end.
|
unit ThostFtdcMdApiDataType;
interface
uses
ThostFtdcBaseDataType;
type
TThostFtdcDirectionType = AnsiChar;
TThostFtdcExchangeIDType = array[0..8] of AnsiChar;
TThostFtdcExchangeInstIDType = array[0..30] of AnsiChar;
PhostFtdcDepthMarketDataField = ^ThostFtdcDepthMarketDataField;
ThostFtdcDepthMarketDataField = packed record
///交易日
TradingDay: TThostFtdcDateType;
///合约代码
InstrumentID: TThostFtdcInstrumentIDType;
///交易所代码
ExchangeID: TThostFtdcExchangeIDType ;
///合约在交易所的代码
ExchangeInstID: TThostFtdcExchangeInstIDType;
///最新价
LastPrice: TThostFtdcPriceType;
///上次结算价
PreSettlementPrice: TThostFtdcPriceType ;
///昨收盘
PreClosePrice: TThostFtdcPriceType;
///昨持仓量
PreOpenInterest: TThostFtdcLargeVolumeType ;
///今开盘
OpenPrice: TThostFtdcPriceType ;
///最高价
HighestPrice: TThostFtdcPriceType ;
///最低价
LowestPrice: TThostFtdcPriceType;
///数量
Volume: TThostFtdcVolumeType ;
///成交金额
Turnover: TThostFtdcMoneyType ;
///持仓量
OpenInterest: TThostFtdcLargeVolumeType;
///今收盘
ClosePrice: TThostFtdcPriceType ;
///本次结算价
SettlementPrice: TThostFtdcPriceType ;
///涨停板价
UpperLimitPrice: TThostFtdcPriceType ;
///跌停板价
LowerLimitPrice: TThostFtdcPriceType ;
///昨虚实度
PreDelta: TThostFtdcRatioType ;
///今虚实度
CurrDelta: TThostFtdcRatioType ;
///最后修改时间
UpdateTime: TThostFtdcTimeType ;
///最后修改毫秒
UpdateMillisec: TThostFtdcMillisecType ;
///申买价一
BidPrice1: TThostFtdcPriceType ;
///申买量一
BidVolume1: TThostFtdcVolumeType ;
///申卖价一
AskPrice1: TThostFtdcPriceType ;
///申卖量一
AskVolume1: TThostFtdcVolumeType ;
///申买价二
BidPrice2: TThostFtdcPriceType ;
///申买量二
BidVolume2: TThostFtdcVolumeType ;
///申卖价二
AskPrice2: TThostFtdcPriceType ;
///申卖量二
AskVolume2: TThostFtdcVolumeType ;
///申买价三
BidPrice3: TThostFtdcPriceType ;
///申买量三
BidVolume3: TThostFtdcVolumeType ;
///申卖价三
AskPrice3: TThostFtdcPriceType ;
///申卖量三
AskVolume3: TThostFtdcVolumeType ;
///申买价四
BidPrice4: TThostFtdcPriceType ;
///申买量四
BidVolume4: TThostFtdcVolumeType ;
///申卖价四
AskPrice4: TThostFtdcPriceType ;
///申卖量四
AskVolume4: TThostFtdcVolumeType ;
///申买价五
BidPrice5: TThostFtdcPriceType ;
///申买量五
BidVolume5: TThostFtdcVolumeType ;
///申卖价五
AskPrice5: TThostFtdcPriceType ;
///申卖量五
AskVolume5: TThostFtdcVolumeType ;
///当日均价
AveragePrice: TThostFtdcPriceType ;
///业务日期
ActionDay: TThostFtdcDateType;
end;
implementation
end.
|
unit SMCheck;
interface
uses
ShareMem;
const
LeadingBytes = 34;
TrailingBytes = 25;
function PrevBlock(pp: pointer): pointer;
function IsObject(a: pointer): boolean;
implementation
uses
SysUtils, windows;
type
PInteger = ^integer;
const
Magic = (ord('A') shl 24) or (ord('B') shl 16) or (ord('C') shl 8) or ord('D');
cAlign = 4;
var
OldMemMgr: TMemoryManager;
function SysGetMemCheck(Size: Integer): Pointer;
var
p : pchar;
begin
inc(Size, 8+LeadingBytes+TrailingBytes);
result := OldMemMgr.GetMem(size);
if result<>nil
then
begin
Size := PInteger(integer(result)-4)^ and (not 3);
PInteger(result)^ := Size;
p := pchar(result)+Size-8;
PInteger(p)^ := Magic;
inc(pchar(result), 4+LeadingBytes);
end;
end;
function SysFreeMemCheck(P: Pointer): Integer;
var
q : pchar;
begin
if p<>nil
then
begin
dec(pchar(p), 4+LeadingBytes);
if pinteger(p)^ <> (pinteger(integer(p)-4)^ and (not 3))
then raise Exception.create(format('SF Before overwrite, or free pointer = %x', [integer(p)]));
q := pchar(p)+ PInteger(p)^-8;
if PInteger(q)^=Magic
then result := OldMemMgr.FreeMem(P)
else raise Exception.create(format('SF After = %x',[integer(p)]));
end
else result := 0;
end;
function SysReallocMemCheck(P: Pointer; Size: Integer): Pointer;
var
q : pchar;
begin
if p<>nil
then
begin
dec(pchar(p), 4+LeadingBytes);
if pinteger(p)^ <> (pinteger(integer(p)-4)^ and (not 3))
then raise Exception.create(format('RM Before overwrite, or free pointer = %x', [integer(p)]));
q := pchar(p)+ PInteger(p)^-8;
if PInteger(q)^=Magic
then
begin
if size>0
then inc(size, 8+LeadingBytes+TrailingBytes);
result := OldMemMgr.ReallocMem(P, size);
end
else raise Exception.create(format('RM After = %x', [integer(p)]));
if result<>nil
then
begin
Size := PInteger(integer(result)-4)^ and (not 3);
PInteger(result)^ := Size;
q := pchar(result)+Size-8;
PInteger(q)^ := Magic;
inc(pchar(result), 4+LeadingBytes);
end;
end
else result := nil;
end;
procedure InitMemoryManager;
var
SharedMemoryManager: TMemoryManager;
begin
SharedMemoryManager.GetMem := SysGetMemCheck;
SharedMemoryManager.FreeMem := SysFreeMemCheck;
SharedMemoryManager.ReallocMem := SysReallocMemCheck;
GetMemoryManager(OldMemMgr);
SetMemoryManager(SharedMemoryManager);
end;
////////////////////////////////////////////////////////////////////////
type
PPointer = ^pointer;
PBlockDesc = ^TBlockDesc;
TBlockDesc =
packed record
next: PBlockDesc;
prev: PBlockDesc;
addr: PChar;
size: Integer;
end;
PBlockDescBlock = ^TBlockDescBlock;
TBlockDescBlock =
packed record
next: PBlockDescBlock;
data: array [0..99] of TBlockDesc;
end;
PFree = ^TFree;
TFree =
packed record
prev: PFree;
next: PFree;
size: Integer;
end;
PUsed = ^TUsed;
TUsed =
packed record
sizeFlags: Integer;
end;
const
cThisUsedFlag = 2;
cPrevFreeFlag = 1;
cFillerFlag = Integer($80000000);
cFlags = cThisUsedFlag or cPrevFreeFlag or cFillerFlag;
cSmallSize = 4*1024;
function IsObject(a: pointer): boolean;
var
AObject: TObject;
AClass: TClass;
type
PPointer = ^Pointer;
begin
try
AObject := TObject(a);
AClass := AObject.ClassType;
result := (Integer(AClass) >= 64*1024) and (PPointer(PChar(AClass) + vmtSelfPtr)^ = Pointer(AClass));
except
result := false
end;
end;
function PrevBlock(pp: pointer): pointer;
var
P : pointer absolute OldMemMgr;
avail : PFree;
rover : PFree;
remBytes : PInteger;
curAlloc : PChar;
smallTab : pointer;
committedRoot: PBlockDesc;
AllocMemCount: PInteger;
heapLock : ^TRTLCriticalSection;
function SearchPrev: pointer;
var
a, e: PChar;
b: PBlockDesc;
f : PFree;
prevFree: Boolean;
size : integer;
freeSize : integer;
tmp: pointer;
begin
b := committedRoot.next;
FreeSize := 0;
prevFree := False;
result := nil;
if (b<>nil)
then
begin
while b <> committedRoot do
begin
a := b.addr;
e := a + b.size;
while a < e do
begin
if (a = curAlloc) and (remBytes^ > 0)
then
begin
size := remBytes^;
Inc(freeSize, size);
if prevFree
then ;// 'Bad Cur Alloc';
prevFree := False;
end
else
begin
if prevFree <> ((PUsed(a).sizeFlags and cPrevFreeFlag) <> 0)
then ;// 'Bad Cur Alloc';
if (PUsed(a).sizeFlags and cThisUsedFlag) = 0
then
begin
f := PFree(a);
if (f.prev.next <> f) or (f.next.prev <> f) or (f.size < sizeof(TFree))
then ;// 'Bad Free Block';
size := f.size;
Inc(freeSize, size);
prevFree := True;
end
else
begin
size := PUsed(a).sizeFlags and not cFlags;
if (PUsed(a).sizeFlags and cFillerFlag) <> 0
then
begin
if (a > b.addr) and (a + size < e)
then ;// 'Bad Used Block';
end
else
begin
tmp := pchar(a+sizeof(TUsed)+4+LeadingBytes);
if (integer(tmp)<integer(pp)) and (integer(tmp)>integer(result))
then result := tmp;
end;
prevFree := False;
end;
end;
inc(a, size);
end;
b := b.next;
end;
end;
end;
begin
avail := pointer(integer(P) + $2BAC);
rover := avail;
inc(pchar(rover), sizeof(TFree));
remBytes := pointer(rover);
inc(pchar(remBytes), sizeof(PFree));
curAlloc := pointer(remBytes);
inc(pchar(curAlloc), sizeof(integer));
smallTab := pointer(curAlloc);
inc(pchar(smallTab), sizeof(pointer));
committedRoot := pointer(smallTab);
inc(pchar(committedRoot), sizeof(pointer));
heapLock := pointer(integer(P) + $2B6C);
avail := PPointer(avail)^;
rover := PPointer(rover)^;
curAlloc := PPointer(curAlloc)^;
smallTab := PPointer(smallTab)^;
try
EnterCriticalSection(heapLock^);
result := SearchPrev
finally
LeaveCriticalSection(heapLock^);
end;
end;
initialization
InitMemoryManager;
finalization
SetMemoryManager(OldMemMgr);
end.
|
unit Logging;
{
Inno Setup
Copyright (C) 1997-2007 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Logging functions
$jrsoftware: issrc/Projects/Logging.pas,v 1.12 2009/03/23 23:27:14 mlaan Exp $
}
interface
procedure Log(const S: String);
procedure LogFmt(const S: String; const Args: array of const);
procedure StartLogging(const Prefix: String);
procedure StartLoggingWithFixedFilename(const Filename: String);
function GetLogFileName: String;
const
SYesNo: array[Boolean] of String = ('No', 'Yes');
implementation
uses
Windows, SysUtils, Int64Em, CmnFunc2, FileClass, DebugClient;
var
LogFile: TTextFileWriter;
LogFileName: String;
LocalTimeBias: Integer64;
procedure InitLocalTimeBias;
var
UTCTime, LocalTime: Integer64;
begin
GetSystemTimeAsFileTime(TFileTime(UTCTime));
if FileTimeToLocalFileTime(TFileTime(UTCTime), TFileTime(LocalTime)) then begin
Dec6464(LocalTime, UTCTime);
LocalTimeBias := LocalTime;
end;
end;
procedure GetFixedLocalTime(var ST: TSystemTime);
{ Like GetLocalTime, but uses our LocalTimeBias as the offset, which cannot
change while the program is running }
var
FT: Integer64;
begin
GetSystemTimeAsFileTime(TFileTime(FT));
Inc6464(FT, LocalTimeBias);
FileTimeToSystemTime(TFileTime(FT), ST);
end;
procedure LogLogOpened;
var
Offset: Integer64;
PlusOrMinus: Char;
begin
Offset := LocalTimeBias;
if Longint(Offset.Hi) >= 0 then
PlusOrMinus := '+'
else begin
PlusOrMinus := '-';
{ Negate it }
Offset.Lo := not Offset.Lo;
Offset.Hi := not Offset.Hi;
Inc64(Offset, 1);
end;
Div64(Offset, 60 * 10000000);
LogFmt('Log opened. (Time zone: UTC%s%.2u:%.2u)', [PlusOrMinus,
Offset.Lo div 60, Offset.Lo mod 60]);
end;
procedure StartLogging(const Prefix: String);
var
Dir, DateStr, Filename: String;
I: Cardinal;
ST: TSystemTime;
F: TTextFileWriter;
begin
if Assigned(LogFile) then
Exit; { logging was already started }
Dir := GetTempDir;
GetFixedLocalTime(ST);
DateStr := Format('%.4u-%.2u-%.2u', [ST.wYear, ST.wMonth, ST.wDay]);
I := 1;
while True do begin
Filename := Dir + Format('%s Log %s #%.3u.txt', [Prefix, DateStr, I]);
if not FileOrDirExists(Filename) then begin
F := nil;
try
F := TTextFileWriter.Create(Filename, fdCreateNew, faWrite, fsRead);
except
on E: EFileError do begin
{ Don't propogate ERROR_FILE_EXISTS errors; just try again.
(Yes, we already checked if the file existed first, but this helps
to make it race-proof.) }
if E.ErrorCode <> ERROR_FILE_EXISTS then
raise;
end;
end;
if Assigned(F) then begin
LogFile := F;
LogFileName := FileName;
Break;
end;
end;
Inc(I);
end;
LogLogOpened;
end;
procedure StartLoggingWithFixedFilename(const Filename: String);
begin
if Assigned(LogFile) then
Exit; { logging was already started }
LogFile := TTextFileWriter.Create(Filename, fdCreateAlways, faWrite, fsRead);
LogFileName := FileName;
LogLogOpened;
end;
function GetLogFileName: String;
begin
Result := LogFileName;
end;
procedure Log(const S: String);
procedure WriteStr(const S: String);
begin
LogFile.Write(S);
end;
var
ST: TSystemTime;
LineStart, I: Integer;
begin
if Assigned(LogFile) then begin
GetFixedLocalTime(ST);
try
WriteStr(Format('%.4u-%.2u-%.2u %.2u:%.2u:%.2u.%.3u ',
[ST.wYear, ST.wMonth, ST.wDay, ST.wHour, ST.wMinute, ST.wSecond,
ST.wMilliseconds]));
LineStart := 1;
{ Lines except for last line }
for I := 1 to Length(S) do begin
if S[I] = #10 then begin
WriteStr(Copy(S, LineStart, I - LineStart + 1));
LineStart := I + 1;
{ Indent }
WriteStr(' ');
end;
end;
{ Last line }
if LineStart <= Length(S) then
WriteStr(Copy(S, LineStart, Length(S) - LineStart + 1));
WriteStr(#13#10);
except
{ Failed to write? Close the file and don't log anything further. }
try
FreeAndNil(LogFile);
except
end;
end;
end;
if Debugging then
DebugNotifyLogMessage(S);
end;
procedure LogFmt(const S: String; const Args: array of const);
begin
if Assigned(LogFile) or Debugging then
Log(Format(S, Args));
end;
initialization
InitLocalTimeBias;
finalization
if Assigned(LogFile) then begin
Log('Log closed.');
FreeAndNil(LogFile);
end;
end.
|
unit sThirdParty;
{$I sDefs.inc}
interface
uses
SysUtils, Classes, Windows, Graphics, Controls, imglist, comctrls, StdCtrls,
{$IFNDEF ALITE} sToolBar, {$ENDIF}
{$IFDEF USEPNG} PngImageList, PngFunctions, PngImage, {$ENDIF}
acntTypes, sSkinManager, sCommonData, sConst, sBitBtn, sSpeedButton;
var
ThirdPartySkipForms: TStringList;
InitDevEx: procedure (const Active: boolean);
CheckDevEx: function (const Control: TControl): boolean;
RefreshDevEx: procedure;
type
TacDrawGlyphData = record
Blend,
SkinIndex,
NumGlyphs,
ImageIndex,
CurrentState: integer;
Down,
Grayed,
Enabled,
Reflected: boolean;
Glyph,
DstBmp: TBitmap;
ImgRect: TRect;
Canvas: TCanvas;
BGColor: TColor;
Images: TCustomImageList;
PPI: integer;
CommonSkinData: TacSkinData;
DisabledGlyphKind: TsDisabledGlyphKind;
end;
{$IFDEF FPC}
TTBCustomDrawFlags = set of (tbNoEdges, tbHiliteHotTrack, tbNoOffset, tbNoMark, tbNoEtchedEffect);
{$ENDIF}
function GetImageCount(ImgList: TCustomImageList): integer;
function GetImageWidth (ImgList: TCustomImageList; ImageIndex: integer = -1; PPI: integer = 96; UseAngle: boolean = False): integer;
function GetImageHeight(ImgList: TCustomImageList; ImageIndex: integer = -1; PPI: integer = 96; UseAngle: boolean = False): integer;
procedure DrawBtnGlyph(Button: TControl; Canvas: TCanvas; ColorTone: TColor);
procedure CopyToolBtnGlyph(ToolBar: TToolBar; Button: TToolButton; State: TCustomDrawState; Stage: TCustomDrawStage; var Flags: TTBCustomDrawFlags; BtnBmp: TBitmap);
procedure acDrawGlyphEx(DrawData: TacDrawGlyphData);
implementation
uses
math,
{$IFDEF DEVEX2011} acLFPainter, {$ENDIF}
{$IFDEF DEVEX6} acLFPainter6, {$ENDIF} // for projects which uses the DEVEX key
sDefaults, sGraphUtils, acAlphaImageList, acntUtils, sButton, sMessages, sStyleSimply, sVCLUtils;
function GetImageCount(ImgList: TCustomImageList): integer;
begin
if ImgList <> nil then
if ImgList is TacImageList then
Result := TacImageList(ImgList).Count
else
{$IFDEF USEPNG}
if ImgList is TPngImageList then
Result := TPngImageList(ImgList).PngImages.Count
else
{$ENDIF}
if ImgList is TsVirtualImageList then
Result := TsVirtualImageList(ImgList).Count
else
Result := ImgList.Count
else
Result := 0;
end;
type
TAccessCharImageList = class(TsCharImageList);
function GetImageWidth(ImgList: TCustomImageList; ImageIndex: integer = -1; PPI: integer = 96; UseAngle: boolean = False): integer;
var
vil: TsVirtualImageList;
cil: TAccessCharImageList;
begin
if ImgList <> nil then
if ImgList is TsAlphaImageList then
Result := TsAlphaImageList(ImgList).Width
else
if ImgList is TsCharImageList then begin
cil := TAccessCharImageList(ImgList);
if IsValidIndex(ImageIndex, cil.Count) then
Result := cil.Items[ImageIndex].ActualWidth(False)
else
Result := cil.SavedWidth;
if Result = 0 then // SavedWidth not initialized yet
Result := cil.Width;
if not TAccessCharImageList(ImgList).AllowScale then
Exit;
end
else
if ImgList is TsVirtualImageList then
if TsVirtualImageList(ImgList).AlphaImageList is TsCharImageList then begin
vil := TsVirtualImageList(ImgList);
cil := TAccessCharImageList(TsCharImageList(vil.AlphaImageList));
Result := vil.Width;
if IsValidIndex(ImageIndex, cil.Count) then
Result := Round(Result * cil.Items[ImageIndex].ScalingFactor);
end
else
Result := TsVirtualImageList(ImgList).Width
else begin
Result := ImgList.Width;
Exit;
end
else
Result := 0;
Result := Result * PPI div 96;
end;
function GetImageHeight(ImgList: TCustomImageList; ImageIndex: integer = -1; PPI: integer = 96; UseAngle: boolean = False): integer;
var
vil: TsVirtualImageList;
cil: TAccessCharImageList;
begin
if ImgList is TsAlphaImageList then
Result := TsAlphaImageList(ImgList).Height
else
if ImgList is TsCharImageList then begin
cil := TAccessCharImageList(ImgList);
Result := cil.SavedHeight;
if Result = 0 then // SavedHeight not initialized yet
Result := cil.Height;
if IsValidIndex(ImageIndex, cil.Count) then begin
inc(Result, abs(cil.Items[ImageIndex].OffsetY));
Result := Round(Result * cil.Items[ImageIndex].ScalingFactor);
end;
end
else
if ImgList is TsVirtualImageList then
if TsVirtualImageList(ImgList).AlphaImageList is TsCharImageList then begin
vil := TsVirtualImageList(ImgList);
cil := TAccessCharImageList(TsCharImageList(vil.AlphaImageList));
Result := vil.Height;
if IsValidIndex(ImageIndex, cil.Count) then begin
inc(Result, abs(cil.Items[ImageIndex].OffsetY));
Result := Round(Result * cil.Items[ImageIndex].ScalingFactor);
end;
end
else
Result := TsVirtualImageList(ImgList).Height
else
if ImgList <> nil then begin
Result := ImgList.Height;
Exit;
end
else
Result := 0;
Result := Result * PPI div 96;
end;
procedure acDrawGlyphEx(DrawData: TacDrawGlyphData);
var
b: boolean;
GrayColor: TColor;
S0, S: PRGBAArray_;
MaskColor: TsColor;
TmpBmp, Bmp: TBitmap;
nEvent: TNotifyEvent;
IRect, SrcRect: TRect;
DeltaS, X, Y, ActBlend: integer;
{$IFDEF USEPNG}
PngCopy: TPNGObject;
{$ENDIF}
procedure PrepareGlyph;
begin
with DrawData do begin
Bmp.Width := GetImageWidth (Images, -1, PPI);
Bmp.Height := GetImageHeight(Images, -1, PPI);
Bmp.PixelFormat := pf32bit;
if Images.BkColor <> clNone then
MaskColor.C := Images.BkColor
else
MaskColor.C := clFuchsia;
Bmp.Canvas.Brush.Color := MaskColor.C;
Bmp.Canvas.FillRect(MkRect(Bmp));
Images.GetBitmap(ImageIndex, Bmp);
end;
end;
begin
with DrawData do begin
if Grayed then
GrayColor := acColorToRGB(DrawData.BGColor)
else
GrayColor := clNone;
if (DefaultManager <> nil) and DefaultManager.Options.StdGlyphsOrder then begin
case CurrentState of
0:
if not Enabled then
DrawData.CurrentState := 1;
1: DrawData.CurrentState := 0
else
if NumGlyphs < 3 then
DrawData.CurrentState := 0;
end;
end;
if Assigned(Images) and IsValidIndex(ImageIndex, GetImageCount(Images)) then begin
IRect := ImgRect;
{$IFDEF USEPNG}
if (Images is TPngImageList) and (TPngImageCollectionItem(TPngImageList(Images).PngImages.Items[ImageIndex]).PngImage <> nil) then begin
PngCopy := nil;
if Enabled then
if (CurrentState > 0) or ((Blend = 0) and not Grayed) then begin
PngCopy := TPngImageCollectionItem(TPngImageList(Images).PngImages.Items[ImageIndex]).PngImage;
if DstBmp <> nil then
PngCopy.Draw(DstBmp.Canvas, IRect)
else
if Canvas <> nil then
PngCopy.Draw(Canvas, IRect);
end
else begin
if Blend > 0 then begin
PngCopy := TPNGObject.Create;
PngCopy.Assign(TPngImageCollectionItem(TPngImageList(Images).PngImages.Items[ImageIndex]).PngImage);
MakeImageBlended(PngCopy);
end;
if Grayed then begin
if PngCopy = nil then begin
PngCopy := TPNGObject.Create;
PngCopy.Assign(TPngImageCollectionItem(TPngImageList(Images).PngImages.Items[ImageIndex]).PngImage);
end;
MakeImageGrayscale(PngCopy);
end;
if PngCopy = nil then
PngCopy := TPngImageCollectionItem(TPngImageList(Images).PngImages.Items[ImageIndex]).PngImage;
if DstBmp <> nil then
PngCopy.Draw(DstBmp.Canvas, IRect)
else
if Canvas <> nil then
PngCopy.Draw(Canvas, IRect);
FreeAndNil(PngCopy);
end
else begin
if dgBlended in DisabledGlyphKind then begin
PngCopy := TPNGObject.Create;
PngCopy.Assign(TPngImageCollectionItem(TPngImageList(Images).PngImages.Items[ImageIndex]).PngImage);
MakeImageBlended(PngCopy);
end;
if DrawData.Grayed then begin
if PngCopy = nil then begin
PngCopy := TPNGObject.Create;
PngCopy.Assign(TPngImageCollectionItem(TPngImageList(Images).PngImages.Items[ImageIndex]).PngImage);
end;
MakeImageGrayscale(PngCopy);
end;
if PngCopy = nil then begin
PngCopy := TPNGObject.Create;
PngCopy.Assign(TPngImageCollectionItem(TPngImageList(Images).PngImages.Items[ImageIndex]).PngImage);
end;
if DstBmp <> nil then
PngCopy.Draw(DstBmp.Canvas, IRect)
else
if Canvas <> nil then
PngCopy.Draw(Canvas, IRect);
FreeAndNil(PngCopy);
end;
end
else
{$ENDIF}
if (Images is TsAlphaImageList) or (Images is TsVirtualImageList) then begin
if DstBmp <> nil then begin
DrawAlphaImgList(Images, DstBmp, IRect.Left, IRect.Top, ImageIndex,
max(iff((CurrentState = 0), Blend, 0), iff(not Enabled and (dgBlended in DisabledGlyphKind), 50, 0)), GrayColor,
CurrentState + integer(Down), NumGlyphs, Reflected, DrawData.PPI);
end
else
if Canvas <> nil then begin
if Images is TsVirtualImageList then
TsVirtualImageList(Images).SetCharColor(acColorToRGB(Canvas.Font.Color), ImageIndex, Canvas.Font.Size = 0)
else
if Images is TsCharImageList then
TsCharImageList(Images).SetCharColor(acColorToRGB(Canvas.Font.Color), ImageIndex, Canvas.Font.Size = 0);
DrawAlphaImgListDC(Images, DrawData.Canvas.Handle, IRect.Left, IRect.Top, ImageIndex,
max(iff((CurrentState = 0), Blend, 0), iff(not Enabled and (dgBlended in DisabledGlyphKind), 50, 0)), GrayColor,
CurrentState + integer(Down), NumGlyphs, Reflected, DrawData.PPI);
if Images is TsVirtualImageList then
TsVirtualImageList(Images).SetCharColor(clNone, ImageIndex, True)
else
if Images is TsCharImageList then
TsCharImageList(Images).SetCharColor(clNone, ImageIndex, True);
end;
end
else
if Images is TsCharImageList then begin
if (Blend <> 0) or (TsCharImageList(Images).BlendValue = MAXBYTE) then
ActBlend := iff((CurrentState = 0), Blend, 0)
else
ActBlend := 0;
if DstBmp <> nil then
DrawAlphaImgList(Images, DstBmp, IRect.Left, IRect.Top, ImageIndex,
max(ActBlend, iff(not DrawData.Enabled and (dgBlended in DrawData.DisabledGlyphKind), 50, 0)), GrayColor,
DrawData.CurrentState + integer(DrawData.Down), NumGlyphs, Reflected, DrawData.PPI)
else
if Canvas <> nil then begin
if Images is TsVirtualImageList then
TsVirtualImageList(Images).SetCharColor(acColorToRGB(Canvas.Font.Color), ImageIndex, Canvas.Font.Size = 0)
else
if Images is TsCharImageList then
TsCharImageList(Images).SetCharColor(acColorToRGB(Canvas.Font.Color), ImageIndex, Canvas.Font.Size = 0);
DrawAlphaImgListDC(Images, DrawData.Canvas.Handle, IRect.Left, IRect.Top, ImageIndex,
max(ActBlend, iff(not Enabled and (dgBlended in DisabledGlyphKind), 50, 0)), GrayColor,
CurrentState + integer(Down), NumGlyphs, Reflected, DrawData.PPI);
if Images is TsVirtualImageList then
TsVirtualImageList(Images).SetCharColor(clNone, ImageIndex, True)
else
if Images is TsCharImageList then
TsCharImageList(Images).SetCharColor(clNone, ImageIndex, True);
end;
end
else
if (DstBmp <> nil) {$IFDEF DELPHI_XE} and not ((Images is TCustomImageList) and (Images.ColorDepth = cd32Bit)) {$ENDIF} then begin
Bmp := CreateBmp32;
try
PrepareGlyph;
if not Enabled then begin
if DrawData.Grayed then
GrayScaleTrans(Bmp, TsColor(Bmp.Canvas.Pixels[0, 0]));
if dgBlended in DisabledGlyphKind then
BlendTransRectangle(DstBmp, IRect.Left, IRect.Top, Bmp, MkRect(Bmp), 127)
else
CopyTransBitmaps(DstBmp, Bmp, IRect.Left, IRect.Top, MaskColor);
end
else begin
if (CurrentState = 0) and Grayed then
GrayScaleTrans(Bmp, TsColor(Bmp.Canvas.Pixels[0, 0]));
if (CurrentState = 0) and (Blend > 0) then
BlendTransRectangle(DstBmp, IRect.Left, IRect.Top, Bmp, MkRect(Bmp), byte(Blend))
else
CopyTransBitmaps(DstBmp, Bmp, IRect.Left, IRect.Top, MaskColor);
end;
finally
FreeAndNil(Bmp);
end;
end
else
if Canvas <> nil then
Images.Draw(DrawData.Canvas, IRect.Left, IRect.Top, ImageIndex);
end
else
if Assigned(Glyph) and not Glyph.Empty then begin
if (Glyph.PixelFormat = pfDevice) or not Enabled or (Glyph.PixelFormat = pf32bit) and ((DefaultManager = nil) or (SkinIndex < 0) or DefaultManager.Options.CheckEmptyAlpha) then begin
nEvent := Glyph.OnChange;
Glyph.OnChange := nil;
Glyph.HandleType := bmDIB;
if (Glyph.Handle <> 0) and (Glyph.PixelFormat = pf32bit) then begin // Checking for an empty alpha-channel
b := False;
if InitLine(Glyph, Pointer(S0), DeltaS) then
for Y := 0 to Glyph.Height - 1 do begin
S := Pointer(PAnsiChar(S0) + DeltaS * Y);
for X := 0 to Glyph.Width - 1 do
if S[X].A <> 0 then begin
b := True;
Break;
end;
end;
if not b then
Glyph.PixelFormat := pf24bit;
end;
Glyph.OnChange := nEvent;
end;
if Glyph.PixelFormat = pf32bit then begin // Patch if Png, dosn't work in std. mode
SrcRect.Left := WidthOf(ImgRect, True) * min(CurrentState, NumGlyphs - 1);
SrcRect.Top := 0;
SrcRect.Right := SrcRect.Left + WidthOf(ImgRect, True);
SrcRect.Bottom := Glyph.Height;
if DstBmp <> nil then begin
Glyph.Handle;
CopyBmp32(ImgRect, SrcRect, DstBmp, Glyph, EmptyCI, False, GrayColor, iff(CurrentState = 0, Blend, 0), Reflected);
end
else begin
TmpBmp := CreateBmp32(ImgRect);
BitBlt(TmpBmp.Canvas.Handle, 0, 0, TmpBmp.Width, Glyph.Height, Glyph.Canvas.Handle, SrcRect.Left, SrcRect.Top, SRCCOPY);
if not Enabled and (dgBlended in DisabledGlyphKind) then
ActBlend := max(50, Blend)
else
ActBlend := Blend;
if (CurrentState = 0) and (ActBlend <> 0) then
if InitLine(TmpBmp, Pointer(S0), DeltaS) then
for Y := 0 to TmpBmp.Height - 1 do begin
S := Pointer(PAnsiChar(S0) + DeltaS * Y);
for X := 0 to TmpBmp.Width - 1 do
with S[X] do
A := (A * ActBlend) div 100;
end;
if not Enabled and (dgGrayed in DisabledGlyphKind) or (CurrentState = 0) and Grayed then
GrayScale(TmpBmp);
Bmp := CreateBmp32(ImgRect);
BitBlt(Bmp.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, Canvas.Handle, ImgRect.Left, ImgRect.Top, SRCCOPY);
DrawBmp(Canvas, TmpBmp, ImgRect, Reflected);
FreeAndNil(Bmp);
FreeAndNil(TmpBmp);
end;
end
else
if DstBmp = nil then begin
Bmp := CreateBmp32(ImgRect);
BitBlt(Bmp.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, Canvas.Handle, ImgRect.Left, ImgRect.Top, SRCCOPY);
sGraphUtils.DrawGlyphEx(Glyph, Bmp, MkRect(Bmp), NumGlyphs, Enabled, DisabledGlyphKind, CurrentState, Blend, Down, Reflected);
BitBlt(Canvas.Handle, ImgRect.Left, ImgRect.Top, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
FreeAndNil(Bmp);
end
else
sGraphUtils.DrawGlyphEx(Glyph, DstBmp, ImgRect, NumGlyphs, Enabled, DisabledGlyphKind, CurrentState, Blend, Down, Reflected);
end
end;
end;
procedure DrawBtnGlyph;
var
DrawData: TacDrawGlyphData;
procedure GetCommonData(SkinData: TsCtrlSkinData);
begin
DrawData.CommonSkinData := SkinData.CommonSkinData;
DrawData.PPI := DrawData.CommonSkinData.PPI;
if SkinData.Skinned then
DrawData.DstBmp := SkinData.FCacheBmp
else
DrawData.DstBmp := nil;
if (DrawData.CurrentState = 0) and
(SkinData.FOwnerControl.Parent <> nil) and
(SkinData.SkinManager <> nil) and SkinData.SkinManager.IsValidSkinIndex(SkinData.SkinIndex) and
(SkinData.CommonSkinData.gd[SkinData.SkinIndex].Props[0].Transparency = 100) then
DrawData.SkinIndex := GetFontIndex(Button, SkinData.SkinIndex, SkinData.SkinManager)
else
DrawData.SkinIndex := SkinData.SkinIndex;
if SkinData.CustomColor then
DrawData.BGColor := TacAccessControl(Button).Color
else
if (SkinData.SkinManager <> nil) and SkinData.SkinManager.IsValidSkinIndex(DrawData.SkinIndex) then
DrawData.BGColor := GetControlColor(Button)
else
DrawData.BGColor := $FFFFFF;
if SkinData.HUEOffset <> 0 then
DrawData.BGColor := ChangeHue(SkinData.HUEOffset, DrawData.BGColor);
if (DrawData.Images is TsCharImageList) or (DrawData.Images is TsVirtualImageList) then
if SkinData.Skinned then
DrawData.Canvas.Font.Color := GetFontColor(Button, SkinData.SkinIndex, DrawData.CommonSkinData.FOwner, DrawData.CurrentState, SkinData)
else
DrawData.Canvas.Font.Color := clBtnText;
end;
begin
DrawData.DstBmp := nil;
DrawData.Canvas := Canvas;
if Button is TsButton then
with TsButton(Button) do begin
DrawData.Images := GetImages;
DrawData.Glyph := nil;
DrawData.ImageIndex := CurrentImageIndex;
DrawData.ImgRect := GlyphRect;
DrawData.NumGlyphs := 1;
DrawData.Enabled := Enabled;
DrawData.Blend := 0;
DrawData.Down := CurrentState = 2;
if CurrentState <> 0 then
DrawData.Grayed := False
else
DrawData.Grayed := SkinData.Skinned and (SkinData.SkinManager <> nil) and SkinData.SkinManager.Effects.DiscoloredGlyphs;
DrawData.CurrentState := CurrentState;
DrawData.DisabledGlyphKind := DefDisabledGlyphKind;
DrawData.Reflected := Reflected;
GetCommonData(SkinData);
end
else
if Button is TsBitBtn then
with TsBitBtn(Button) do begin
DrawData.Images := GetImages;
DrawData.Glyph := Glyph;
DrawData.ImageIndex := CurrentImageIndex;
DrawData.ImgRect := ImgRect;
DrawData.NumGlyphs := NumGlyphs;
DrawData.Enabled := Enabled;
DrawData.Blend := Blend;
DrawData.Down := Down;
if CurrentState <> 0 then
DrawData.Grayed := False
else
if SkinData.SkinManager <> nil then
DrawData.Grayed := Grayed or SkinData.SkinManager.Effects.DiscoloredGlyphs or (not Enabled and (dkGrayed in DisabledKind))
else
DrawData.Grayed := Grayed or (not Enabled and (dkGrayed in DisabledKind));
if not Enabled and (dgGrayed in DisabledGlyphKind) then
DrawData.Grayed := True;
DrawData.CurrentState := CurrentState;
DrawData.DisabledGlyphKind := DisabledGlyphKind;
DrawData.Reflected := Reflected;
GetCommonData(SkinData);
if ColorTone <> TColor(clNone) then
if (DrawData.Images is TsCharImageList) or ((DrawData.Images is TsVirtualImageList) and (TsVirtualImageList(DrawData.Images).AlphaImageList is TsCharImageList)) then begin
DrawData.Grayed := False;
DrawData.Canvas.Font.Color := ColorTone;
DrawData.Canvas.Font.Size := 0; // Default color is not allowed
end
else begin
DrawData.Grayed := True;
DrawData.BGColor := ColorTone;
end;
end
else
if Button is TsSpeedButton then
with TsSpeedButton(Button) do begin
DrawData.Images := GetImages;
DrawData.Glyph := Glyph;
DrawData.ImageIndex := CurrentImageIndex;
DrawData.CurrentState := CurrentState;
DrawData.ImgRect := ImgRect;
DrawData.NumGlyphs := NumGlyphs;
DrawData.Enabled := Enabled;
DrawData.Blend := Blend;
DrawData.Down := Down;
if SkinData.SkinManager <> nil then
DrawData.Grayed := (GrayedMode = gmAlways) or (Grayed or SkinData.SkinManager.Effects.DiscoloredGlyphs) and (CurrentState = 0) or (not Enabled and (dkGrayed in DisabledKind))
else
DrawData.Grayed := Grayed or (not Enabled and (dkGrayed in DisabledKind));
if not Enabled and (dgGrayed in DisabledGlyphKind) then
DrawData.Grayed := True;
DrawData.DisabledGlyphKind := DisabledGlyphKind;
DrawData.Reflected := Reflected;
GetCommonData(SkinData);
if ColorTone <> clNone then
if (DrawData.Images is TsCharImageList) or ((DrawData.Images is TsVirtualImageList) and (TsVirtualImageList(DrawData.Images).AlphaImageList is TsCharImageList)) then begin
DrawData.Grayed := False;
DrawData.Canvas.Font.Color := ColorTone;
DrawData.Canvas.Font.Size := 0; // Default color is not allowed
end
else begin
DrawData.Grayed := True;
DrawData.BGColor := ColorTone;
end;
end
else
Exit;
acDrawGlyphEx(DrawData);
end;
procedure CopyToolBtnGlyph(ToolBar: TToolBar; Button: TToolButton; State: TCustomDrawState; Stage: TCustomDrawStage; var Flags: TTBCustomDrawFlags; BtnBmp: TBitmap);
var
DrawData: TacDrawGlyphData;
pInfo: TacPaintInfo;
sd: TsCommonData;
PPI: integer;
C: TColor;
function AddedWidth: integer;
begin
Result := integer(Button.Style = tbsDropDown) * 8;
end;
function ImgRect: TRect;
var
w, h: integer;
begin
with ToolBar do begin
w := GetImageWidth(Images, DrawData.ImageIndex, PPI);
h := GetImageHeight(Images, DrawData.ImageIndex, PPI);
if not List then begin
Result.Left := (Button.Width - w) div 2 + 1 - AddedWidth;
Result.Top := (Button.Height - h - integer(ShowCaptions) * (BtnBmp.Canvas.TextHeight(s_Yy) + 3)) div 2;
Result.Right := Result.Left + w;
Result.Bottom := Result.Top + h;
end
else begin
Result.Left := 5;
Result.Top := (Button.Height - Images.Height) div 2;
Result.Right := Result.Left + w;
Result.Bottom := Result.Top + h;
end;
end;
end;
function GetImages: TCustomImageList;
begin
with ToolBar do
if (DrawData.CurrentState <> 0) and Assigned(HotImages) and (Button.ImageIndex < GetImageCount(HotImages)) then
Result := HotImages
else
if not Button.Enabled and Assigned(DisabledImages) then
Result := DisabledImages
else
Result := Images;
end;
begin
DrawData.Grayed := False;
with ToolBar do begin
if cdsSelected in State then
DrawData.CurrentState := 2
else
if cdsHot in State then
DrawData.CurrentState := 1
else
DrawData.CurrentState := integer(cdsChecked in State) * 2;
{$IFNDEF ALITE}
if ToolBar is TsToolBar then begin
sd := TsToolBar(ToolBar).SkinData;
DrawData.Grayed := dkGrayed in TsToolBar(ToolBar).BtnDisabledKind;
end
else
{$ENDIF}
sd := TsCommonData(SendMessage(Handle, SM_ALPHACMD, AC_GETSKINDATA_HI, 0));
if (sd <> nil) and sd.Skinned then begin
PPI := sd.CommonSkinData.PPI;
DrawData.Grayed := DrawData.Grayed or (DrawData.CurrentState = 0) and (sd.SkinManager <> nil) and sd.SkinManager.Effects.DiscoloredGlyphs;
DrawData.CommonSkinData := sd.CommonSkinData;
pInfo.State := DrawData.CurrentState;
pInfo.R := ToolBar.BoundsRect;
pInfo.SkinManager := sd.SkinManager;
if not ToolBar.Flat or (DrawData.CurrentState <> 0) then begin
pInfo.FontIndex := DrawData.CommonSkinData.FOwner.SkinCommonInfo.Sections[ssToolButton];
GetFontIndex(Button, @pInfo);
end
else begin
pInfo.FontIndex := sd.SkinIndex; // Index of ToolBar section
GetFontIndex(ToolBar, @pInfo);
end;
DrawData.SkinIndex := pInfo.FontIndex;
end
else begin
PPI := 96;
DrawData.Grayed := False;
DrawData.CommonSkinData := nil;
DrawData.SkinIndex := -1;
end;
if sd <> nil then begin
DrawData.CommonSkinData := sd.CommonSkinData;
DrawData.PPI := DrawData.CommonSkinData.PPI;
end
else begin
DrawData.CommonSkinData := nil;
DrawData.PPI := GetControlPPI(ToolBar);
end;
if (cdsDisabled in State) and (DisabledImages <> nil) then
DrawData.Images := DisabledImages
else
if (DrawData.CurrentState = 1) and (HotImages <> nil) then
DrawData.Images := HotImages
else
DrawData.Images := Images;
DrawData.Glyph := nil;
DrawData.ImageIndex := Button.ImageIndex;
DrawData.ImgRect := ImgRect;
DrawData.NumGlyphs := 1;
DrawData.Enabled := Enabled;
DrawData.Blend := 0;
DrawData.Down := DrawData.CurrentState = 2;
{$IFNDEF ALITE}
if DrawData.Grayed then begin
DrawData.DisabledGlyphKind := [dgGrayed];
if (sd <> nil) and sd.Skinned and (DrawData.CommonSkinData <> nil) then
DrawData.BGColor := DrawData.CommonSkinData.gd[DrawData.SkinIndex].Props[0].Color
end
else
{$ENDIF}
DrawData.DisabledGlyphKind := [];
DrawData.Reflected := False;
DrawData.DstBmp := BtnBmp;
DrawData.Canvas := BtnBmp.Canvas;
if (DrawData.Images is TsCharImageList) or (DrawData.Images is TsVirtualImageList) then begin
C := GetFontColor(nil, DrawData.SkinIndex, DrawData.CommonSkinData.FOwner, DrawData.CurrentState);
if DrawData.Canvas <> nil then
DrawData.Canvas.Font.Color := C;
if DrawData.DstBmp <> nil then
DrawData.DstBmp.Canvas.Font.Color := C;
end;
end;
if (DrawData.CurrentState = 2) and CanClickShift(DrawData.SkinIndex, DrawData.CommonSkinData) then
OffsetRect(DrawData.ImgRect, 1, 1);
acDrawGlyphEx(DrawData);
end;
initialization
// Create a list of form types which will be excluded from skinning
ThirdPartySkipForms := TStringList.Create;
with ThirdPartySkipForms do begin
Sorted := True;
Add('TApplication');
// Add('TQRStandardPreview');
Add('TAdvSmoothMessageDialogForm');
Add('TSynBaseCompletionProposalForm');
Add('TPopupListboxFormEh');
// FastCube popup
Add('TfcPopup');
Add('TfcxSliceFieldsPopup');
Add('TfcxMeasurePopup');
Add('TfcxFilterPopup');
// DevExpress
//{$IFDEF DEVEX2011}
Add('TcxDateEditPopupWindow');
Add('TcxPopupEditPopupWindow');
Add('TdxPopupEditForm');
Add('TcxComboBoxPopupWindow');
Add('TcxDateEditPopupWindow');
Add('TcxGridFilterPopup');
Add('TPopupDBTreeView');
//{$ENDIF}
end;
finalization
ThirdPartySkipForms.Free;
end.
|
unit BaseUtils;
interface
// ABC is the numerical base which figures are A,B,C,...,Z
function IntToAbc(value, digits : integer) : string;
function DateToAbc(date : TDateTime) : string;
function TimeToAbc(date : TDateTime) : string;
function DateTimeToAbc(date : TDateTime) : string;
implementation
uses
SysUtils;
const
abcBase = ord('Z') - ord('A') + 1;
abcZero = 'A';
function IntToAbc(value, digits : integer) : string;
var
m : integer;
a : array[0..32] of char;
i : integer;
begin
fillchar(a, sizeof(a), 0);
i := 0;
repeat
m := value mod abcBase;
value := value div abcBase;
a[i] := char(ord('A') + m);
inc(i);
until value = 0;
if i < digits
then
begin
move(a[0], a[digits-i], i);
fillchar(a, digits-i, abcZero);
end;
result := a;
end;
function DateToAbc(date : TDateTime) : string;
var
Year, Month, Day : Word;
begin
DecodeDate(Date, Year, Month, Day);
result := IntToHex(Year, 4) + IntToHex(Month, 1) + IntToHex(Day, 2);
end;
function TimeToAbc(date : TDateTime) : string;
var
Hour, Min, Sec, MSec : Word;
begin
DecodeTime(Date, Hour, Min, Sec, MSec);
result := IntToHex(Hour, 2) + IntToHex(Min, 2) + IntToHex(Sec, 2) + IntToHex(MSec, 2);
end;
function DateTimeToAbc(date : TDateTime) : string;
begin
result := DateToAbc(date) + TimeToAbc(date);
end;
end.
|
unit DelphiUp.View.Pages.Menu.Generic;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts,
DelphiUp.View.Components.Button001, DelphiUp.View.Styles;
type
TPageMenuGeneric = class(TForm)
Layout1: TLayout;
Layout2: TLayout;
Layout3: TLayout;
Label1: TLabel;
Rectangle1: TRectangle;
private
{ Private declarations }
FTitle : String;
FBackground : TAlphaColor;
FFontColor : TAlphaColor;
public
{ Public declarations }
function Component : TFMXObject;
function Title ( aValue : String ) : TPageMenuGeneric;
function Background ( aValue : TAlphaColor ) : TPageMenuGeneric;
function FontColor ( aValue : TAlphaColor ) : TPageMenuGeneric;
function AddButton ( aValue : TFmxObject ) : TPageMenuGeneric;
end;
var
PageMenuGeneric: TPageMenuGeneric;
implementation
{$R *.fmx}
{ TPageMenuGeneric }
function TPageMenuGeneric.AddButton(aValue: TFmxObject): TPageMenuGeneric;
begin
Result := Self;
Layout3.AddObject(aValue);
end;
function TPageMenuGeneric.Background(aValue: TAlphaColor): TPageMenuGeneric;
begin
Result := Self;
FBackground := aValue;
Rectangle1.Fill.Color := aValue;
end;
function TPageMenuGeneric.Component: TFMXObject;
begin
Result := Layout1;
Label1.TextSettings.Font.Size := FONT_SIZE_H1;
end;
function TPageMenuGeneric.FontColor(aValue: TAlphaColor): TPageMenuGeneric;
begin
Result := Self;
FFontColor := aValue;
Label1.TextSettings.FontColor := aValue;
end;
function TPageMenuGeneric.Title(aValue: String): TPageMenuGeneric;
begin
Result := Self;
FTitle := aValue;
Label1.Text := aValue;
end;
end.
|
unit SafeDLLPath;
{
Inno Setup
Copyright (C) 1997-2016 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
To provide protection against "DLL preloading" attacks, this unit calls
SetDefaultDllDirectories. SetDefaultDllDirectories is available on Windows 8
and newer, and on previous versions that have the KB2533623 update installed.
If SetDefaultDllDirectories is not available:
-It calls SetDllDirectory('') to prevent LoadLibrary from searching the current
directory for DLLs. (Has no effect on Windows versions prior to XP SP1.)
-It then preloads a list of system DLLs which are known to be loaded unsafely
by older or unpatched versions of Windows.
Also see:
-http://wixtoolset.org/development/wips/5184-burn-clean-room/
-https://github.com/firegiant/wix3/blob/master/src/libs/dutil/apputil.cpp
-https://github.com/firegiant/wix3/blob/master/src/burn/stub/stub.cpp
-https://sourceforge.net/p/nsis/code/HEAD/tree/NSIS/trunk/Source/exehead/Main.c
It also calls SetSearchPathMode to enable "safe search mode", which causes
SearchPath, and callers of SearchPath such as CreateProcess, to search the
current directory after the system directories (rather than before).
SetSearchPathMode is available in Windows 7 and newer, and on previous
versions that have the KB959426 update installed.
Finally, it calls SetProcessDEPPolicy (where available) to enable DEP for
the lifetime of the process. (This has nothing to do with search paths;
it's just convenient to put the call here.)
This unit should be listed at the top of the program's "uses" clause to
ensure that it runs prior to any LoadLibrary calls that other units might
make during their initialization. (The System unit will always initialize
first, though.)
}
interface
implementation
{$IF DEFINED(MSWINDOWS)}
uses
Windows;
const
LOAD_LIBRARY_SEARCH_SYSTEM32 = $00000800;
BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE = $00000001;
BASE_SEARCH_PATH_PERMANENT = $00008000;
PROCESS_DEP_ENABLE = $00000001;
var
KernelModule: HMODULE;
WinVer: WORD;
SystemDir: String;
SetDefaultDllDirectoriesFunc: function(DirectoryFlags: DWORD): BOOL; stdcall;
DidSetDefaultDllDirectories: Boolean;
SetDllDirectoryFunc: function(lpPathName: PWideChar): BOOL; stdcall;
SetSearchPathModeFunc: function(Flags: DWORD): BOOL; stdcall;
SetProcessDEPPolicyFunc: function(dwFlags: DWORD): BOOL; stdcall;
function StrPas(Str: PChar): string;
begin
Result := Str;
end;
function GetSystemDir: String;
var
Buf: array [0 .. MAX_PATH - 1] of Char;
begin
GetSystemDirectory(Buf, SizeOf(Buf) div SizeOf(Buf[0]));
Result := StrPas(Buf);
end;
function SafeLoadLibrary(const Filename: String): HMODULE;
var
SaveErrorMode: UINT;
SaveFPUControlWord: WORD;
begin
SaveErrorMode := SetErrorMode(SEM_NOOPENFILEERRORBOX);
try
Result := LoadLibrary(PChar(Filename));
finally
SetErrorMode(SaveErrorMode);
end;
end;
initialization
KernelModule := GetModuleHandle(kernel32);
WinVer := Swap(WORD(GetVersion()));
DidSetDefaultDllDirectories := False;
if WinVer <> $0600 then
begin // see NSIS link above: CoCreateInstance(CLSID_ShellLink, ...) fails on Vista if SetDefaultDllDirectories is called
SetDefaultDllDirectoriesFunc := GetProcAddress(KernelModule,
PAnsiChar('SetDefaultDllDirectories'));
if Assigned(SetDefaultDllDirectoriesFunc) then
DidSetDefaultDllDirectories := SetDefaultDllDirectoriesFunc
(LOAD_LIBRARY_SEARCH_SYSTEM32);
end;
if not DidSetDefaultDllDirectories then
begin
SetDllDirectoryFunc := GetProcAddress(KernelModule,
PAnsiChar('SetDllDirectoryW'));
if Assigned(SetDllDirectoryFunc) then
SetDllDirectoryFunc('');
SystemDir := GetSystemDir;
if SystemDir <> '' then
begin
if SystemDir[Length(SystemDir)] <> '\' then
SystemDir := SystemDir + '\';
// list of system dlls to preload including source:
// NSIS: Vista: OleInitialize calls NtUserCreateWindowEx and that pulls in UXTheme.dll
SafeLoadLibrary(SystemDir + 'uxtheme.dll');
// NSIS: Vista: SHGetFileInfo ends up in SHELL32.kfapi::GetUserProfileDir and that pulls in UserEnv.dll
SafeLoadLibrary(SystemDir + 'userenv.dll');
// NSIS: XP: SHGetFileInfo ends up in CMountPoint::_InitLocalDriveHelper and that pulls in SetupAPI.dll
SafeLoadLibrary(SystemDir + 'setupapi.dll');
// NSIS: Vista: SHGetFileInfo ... SHELL32.SHILAliasTranslate ... SHELL32.ApphelpCheckShellObject;
SafeLoadLibrary(SystemDir + 'apphelp.dll');
// NSIS: Vista: SHGetFileInfo ... SHELL32.SHILAliasTranslate ... SHLWAPI.#187 ... SHLWAPI.#505/SHPropertyBag_ReadGUID
SafeLoadLibrary(SystemDir + 'propsys.dll');
// NSIS: Win7 without KB2533623: UXTheme pulls in DWMAPI.dll
// Mail: Windows 7 SP1: combase.dll -> ole32.dll -> shell32.dll -> dwmapi.dll
SafeLoadLibrary(SystemDir + 'dwmapi.dll');
// NSIS: Win7 without KB2533623: OleInitialize ... RPCRT4.UuidCreate ... RPCRT4.GenerateRandomNumber
// Mail: oleaut32.dll -> rpcrt4.dll -> cryptbase.dll
SafeLoadLibrary(SystemDir + 'cryptbase.dll');
// NSIS: Vista: SHFileOperation ... SHELL32.CProgressDialogUI::_Setup ... SHELL32.GetRoleTextW
SafeLoadLibrary(SystemDir + 'oleacc.dll');
// Mail: Windows 7 SP1: oleaut32.dll -> ole32.dll -> crypt32.dll -> version.dll
// WIX3: required by Burn
SafeLoadLibrary(SystemDir + 'version.dll');
// Mail: Windows 7 SP1: oleaut32.dll -> ole32.dll -> crypt32.dll -> profapi.dll
SafeLoadLibrary(SystemDir + 'profapi.dll');
// WIX3: required by CLSIDFromProgID() when loading clbcatq.dll
SafeLoadLibrary(SystemDir + 'comres.dll');
// WIX3: required by CLSIDFromProgID() when loading msxml?.dll
// NSIS: XP.SP2&SP3: SHAutoComplete ... OLE32!InitializeCatalogIfNecessary ... OLE32!CComCatalog::TryToLoadCLB
SafeLoadLibrary(SystemDir + 'clbcatq.dll');
{
// WIX3: required by Burn
SafeLoadLibrary(SystemDir + 'cabinet.dll');
// WIX3: required by Burn
SafeLoadLibrary(SystemDir + 'msi.dll');
// WIX3: required by Burn
SafeLoadLibrary(SystemDir + 'wininet.dll');
// WIX3: required by DecryptFile() when loading crypt32.dll
SafeLoadLibrary(SystemDir + 'msasn1.dll');
// WIX3: required by DecryptFile() when loading feclient.dll
SafeLoadLibrary(SystemDir + 'crypt32.dll');
// WIX3: unsafely loaded by DecryptFile()
SafeLoadLibrary(SystemDir + 'feclient.dll');
}
end;
end;
SetSearchPathModeFunc := GetProcAddress(KernelModule,
PAnsiChar('SetSearchPathMode'));
if Assigned(SetSearchPathModeFunc) then
SetSearchPathModeFunc(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE or
BASE_SEARCH_PATH_PERMANENT);
SetProcessDEPPolicyFunc := GetProcAddress(KernelModule,
PAnsiChar('SetProcessDEPPolicy'));
if Assigned(SetProcessDEPPolicyFunc) then
SetProcessDEPPolicyFunc(PROCESS_DEP_ENABLE);
{$ENDIF}
end.
|
unit Portal;
interface
uses
Protocol, Kernel, Environmental;
type
TPortal =
class( TEnvironmentalBlock )
published
function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override;
public
function Evaluate : TEvaluationResult; override;
protected
function GetVisualClassId : TVisualClassId; override;
private
fLastPop : TFluidValue;
fPopFlow : TFluidValue;
end;
procedure RegisterBackup;
implementation
uses
World, Population, BackupInterfaces;
// TPortal
function TPortal.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string;
var
TH : TTownHall;
begin
if kind = sttSecondary
then
begin
TH := TTownHall(TInhabitedTown(Facility.Town).TownHall.CurrBlock);
result := TH.GetStatusText( kind, ToTycoon );
end
else result := inherited GetStatusText( kind, ToTycoon );
end;
function TPortal.Evaluate : TEvaluationResult;
var
TH : TTownHall;
//CurrPop : TFluidValue;
begin
result := inherited Evaluate;
TH := TTownHall(TInhabitedTown(Facility.Town).TownHall.CurrBlock);
fPopFlow := TH.TotalPopulation - fLastPop;
fLastPop := TH.TotalPopulation;
end;
function TPortal.GetVisualClassId : TVisualClassId;
begin
if fPopFlow > 0
then result := 0
else result := 1;
end;
// RegisterBackup
procedure RegisterBackup;
begin
BackupInterfaces.RegisterClass( TPortal );
end;
end.
|
unit config;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
IniFiles;
const
DefaultConfigFile = 'config.ini';
type
{ TIRCConfig }
TIRCConfig = class
private
FHost: string;
FPort: integer;
FUsername: string;
FNickname: string;
FRealName: string;
FAltNickname: string;
FChannels: TStrings;
FIni: TIniFile;
public
procedure Save;
procedure Load;
property Host: string read FHost write FHost;
property Port: integer read FPort write FPort;
property Username: string read FUsername write FUsername;
property Nickname: string read FNickname write FNickname;
property RealName: string read FRealName write FRealName;
property AltNickname: string read FAltNickname write FAltNickname;
property Channels: TStrings read FChannels;
constructor Create;
destructor Destroy; override;
end;
implementation
const
SectionServer = 'Server';
SectionUser = 'User';
SectionChannels = 'Channels';
{ TIRCConfig }
procedure TIRCConfig.Save;
begin
FIni.WriteString(SectionServer, 'Host', FHost);
FIni.WriteInteger(SectionServer, 'Port', FPort);
FIni.WriteString(SectionUser, 'Username', FUsername);
FIni.WriteString(SectionUser, 'Nickname', FNickname);
FIni.WriteString(SectionUser, 'RealName', FRealName);
FIni.WriteString(SectionUser, 'AltNickname', FAltNickname);
FIni.WriteString(SectionChannels, 'AutoJoin', FChannels.CommaText);
FIni.UpdateFile;
end;
procedure TIRCConfig.Load;
begin
FHost := FIni.ReadString(SectionServer, 'Host', '');
FPort := FIni.ReadInteger(SectionServer, 'Port', 6667);
FUsername := FIni.ReadString(SectionUser, 'Username', '');
FNickname := FIni.ReadString(SectionUser, 'Nickname', '');
FRealName := FIni.ReadString(SectionUser, 'RealName', '');
FAltNickname := FIni.ReadString(SectionUser, 'AltNickname', '');
FChannels.CommaText := FIni.ReadString(SectionChannels, 'AutoJoin', '');
end;
constructor TIRCConfig.Create;
begin
FChannels := TStringList.Create;
Fini := TIniFile.Create('config.ini');
end;
destructor TIRCConfig.Destroy;
begin
FChannels.Free;
FIni.Free;
inherited Destroy;
end;
end.
|
unit undmsrv;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Win.Registry,
System.IOUtils,
System.Classes, Vcl.Graphics, Vcl.Controls,
Vcl.SvcMgr, Vcl.Dialogs, uConsts, inifiles;
type
TRestDWsrv = class(TService)
procedure ServiceAfterInstall(Sender: TService);
procedure ServiceCreate(Sender: TObject);
private
{ Private declarations }
public
function GetServiceController: TServiceController; override;
end;
var
RestDWsrv: TRestDWsrv;
implementation
uses
uDmService;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ Tdmsrv }
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
RestDWsrv.Controller(CtrlCode);
end;
function TRestDWsrv.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TRestDWsrv.ServiceAfterInstall(Sender: TService);
// Var
// Reg : TRegistry;
Begin
{ Reg := TRegistry.Create(KEY_READ or KEY_WRITE);
Try
Reg.RootKey := HKEY_LOCAL_MACHINE;
If Reg.OpenKey('\SYSTEM\CurrentControlSet\Services\' + Name, false) Then
Begin
Reg.WriteString('Description', 'RestDataware Server Service Application.');
Reg.CloseKey;
End;
Finally
Reg.Free;
End; }
end;
procedure TRestDWsrv.ServiceCreate(Sender: TObject);
var
ArqIni: TIniFile;
LPort: Integer;
begin
try
try
ArqIni := TIniFile.Create(CPathIniFile + '\cfg.ini');
LPort := ArqIni.ReadInteger('Dados', 'Porta', 0);
RESTServicePooler.ServerMethodClass := TServerMethodDM;
RESTServicePooler.ServerParams.UserName := vUsername;
RESTServicePooler.ServerParams.Password := vPassword;
RESTServicePooler.ServicePort := LPort;
RESTServicePooler.SSLPrivateKeyFile := SSLPrivateKeyFile;
RESTServicePooler.SSLPrivateKeyPassword := SSLPrivateKeyPassword;
RESTServicePooler.SSLCertFile := SSLCertFile;
RESTServicePooler.Active := True;
{$IFDEF DEBUG}
WriteLn('Conectado na porta: ' + LPort.ToString);
{$ENDIF}
except
{$IFDEF DEBUG}
on e: exception do
WriteLn('Erro:' + inttostr(LPort) + #13 + 'Ocorreu o seguinte erro: ' +
e.message);
{$ENDIF}
end;
finally
ArqIni.Free;
end;
end;
end.
|
unit uMultiTaskQueue;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
uCS;
type
tMultiTaskQueue = class;
tTaskProc = procedure;
tTaskMethod = procedure of object;
tOn_New_Task = procedure of object;
tTaskPriority = (tpFirst, tpHigh, tpNormal, tpLow, tpLast);
tMultitaskEnQueueFlag = (teUnique, teFirst, teHighPriority, teNormalPriority,
teLowPriority, teLast);
tMultitaskEnQueueFlags = set of tMultitaskEnQueueFlag;
{ tMultiTaskItem }
tMultiTaskItem = class
private
fName: string;
fParamsAsPascalString: string;
fTaskMethod: tTaskMethod;
fDestObj : tObject;
fTaskProc: tTaskProc;
function getAnsiString(const i: integer): ansistring;
function getboolean(const i: integer): boolean;
function getchar(const i: integer): char;
function getCurrency(const i: integer): currency;
function getExtended(const i: integer): extended;
function getInt64(const i: integer): int64;
function getInteger(const i: integer): integer;
function getinterface(const id: integer): pointer;
function getnextAnsiString: ansistring;
function getnextB: boolean;
function getnextchar: char;
function getnextClass: tClass;
function getnextCurrency: currency;
function getnextExtended: extended;
function getnextI: integer;
function getnextInt64: int64;
function getnextO: TObject;
function getnextPChar: PChar;
function getnextS: string;
function getnextVariant: variant;
function getPChar(const i: integer): PChar;
function getString(const i: integer): string;
function gettClass(const i: integer): tClass;
function gettObject(const i: integer): TObject;
function getVariant(const i: integer): variant;
protected
fPriority: tTaskPriority;
fInteger: array of integer;
fBoolean: array of boolean;
fChar: array of char;
fExtended: array of extended;
fString: array of string;
fPChar: array of PChar;
ftObject: array of TObject;
ftClass: array of tClass;
fAnsiString: array of ansistring;
fCurrency: array of currency;
fVariant: array of variant;
fInt64: array of int64;
fInterface: array of IUnknown;
fBeforeRun, fAfterRun: tMultiTaskItem;
fparamid: integer;
public
constructor Create; overload;
constructor Create(const proc: tTaskProc; const method: tTaskMethod;
const params: array of const; const proc_before: tTaskProc = nil;
const method_before: tTaskMethod = nil; const params_before: array of const;
const proc_after: tTaskProc = nil; const method_after: tTaskMethod = nil;
const params_after: array of const; const obj : tObject = nil); overload;
constructor Create(const proc: tTaskProc; const method: tTaskMethod;
const params: array of const; const obj : tObject = nil); overload;
destructor Destroy; override;
procedure SetParams(const Data: array of const);
function AsPascalSourceString: string;
property Method: tTaskMethod read fTaskMethod;
property DestinationObject : tObject read fDestObj;
property Proc: tTaskProc read fTaskProc;
property nextI: integer read getnextI;
property nextB: boolean read getnextB;
property nextChar: char read getnextchar;
property nextExtended: extended read getnextExtended;
property nextS: string read getnextS;
property nextPChar: PChar read getnextPChar;
property nextO: TObject read getnextO;
property nextClass: tClass read getnextClass;
property nextAnsiString: ansistring read getnextAnsiString;
property nextCurrency: currency read getnextCurrency;
property nextVariant: variant read getnextVariant;
property nextI64: int64 read getnextInt64;
property I[const id: integer]: integer read getInteger;
property B[const id: integer]: boolean read getboolean;
property S[const id: integer]: string read getString;
property O[const id: integer]: TObject read gettObject;
property E[const id: integer]: extended read getExtended;
property I64[const id: integer]: int64 read getInt64;
property int[const id: integer]: pointer read getinterface;
property ParChar[const id: integer]: char read getchar;
property ParPChar[const id: integer]: PChar read getPChar;
property ParClass[const id: integer]: tClass read gettClass;
property ParAnsiString[const id: integer]: ansistring read getAnsiString;
property ParCurrency[const id: integer]: currency read getCurrency;
property ParVariant[const id: integer]: variant read getVariant;
published
property Name: string read fName write fName;
property Priority: tTaskPriority read fPriority;
end;
{ tMultiTaskQueue }
tMultiTaskQueue = class
type
pQueueItem = ^tQueueItem;
tQueueItem = record
Item: tMultiTaskItem;
Next: pQueueItem;
end;
private
fFirst, fLast: pQueueItem;
fCount: integer;
CS: tCS;
fOn_New_Task: tOn_New_Task;
procedure Enqueue(const Data: tMultiTaskItem; const flags: tMultitaskEnQueueFlags);
procedure EnqueueFirst(const Data: tMultiTaskItem; const OnlyUnique: boolean);
procedure EnqueuePriority(const Data: tMultiTaskItem; const tp: tTaskPriority; const OnlyUnique: boolean);
procedure EnqueueLast(const Data: tMultiTaskItem; const OnlyUnique: boolean);
procedure setOn_New_Task(AValue: tOn_New_Task);
function _Exists(const Data: tMultiTaskItem): boolean;
function _Exists_Or_Running(const Data: tMultiTaskItem): boolean;
function _FindFirstTaskWithPriority(const tp: tTaskPriority): pQueueItem;
protected
fMultiTask: TObject;
public
constructor Create(MultiTask: TObject);
destructor Destroy; override;
procedure Enqueue(const proc: tTaskProc; const method: tTaskMethod; const params: array of const; const proc_before: tTaskProc;
const method_before: tTaskMethod; const params_before: array of const; const proc_after: tTaskProc; const method_after: tTaskMethod;
const params_after: array of const; const flags: tMultitaskEnQueueFlags; const obj : tObject = nil);
procedure Enqueue(const proc: tTaskProc; const params: array of const;
const flags: tMultitaskEnQueueFlags = [teLast]);
procedure Enqueue(const method: tTaskMethod; const params: array of const;
const flags: tMultitaskEnQueueFlags = [teLast]; const obj : tObject = nil);
procedure Clear;
function DeQueue(const thrd : tObject): tMultiTaskItem;
function Length: integer;
function Exists(const Data: tMultiTaskItem): boolean;
function HaveWork: boolean;
property MultiTask: TObject read fMultiTask;
property On_New_Task: tOn_New_Task read fOn_New_Task write setOn_New_Task;
end;
implementation
uses TypInfo,
uMultiTask
{$IFDEF MemoryLimitPossibility}
,uMemory
{$ENDIF}
;
{ tMultiTaskItem }
constructor tMultiTaskItem.Create(const proc: tTaskProc; const method: tTaskMethod; const params: array of const; const obj: tObject);
begin
Create(proc, method, params, nil, nil, [], nil, nil, [],obj);
end;
constructor tMultiTaskItem.Create(const proc: tTaskProc; const method: tTaskMethod; const params: array of const; const proc_before: tTaskProc;
const method_before: tTaskMethod; const params_before: array of const; const proc_after: tTaskProc; const method_after: tTaskMethod;
const params_after: array of const; const obj: tObject);
var
before, after: tMultiTaskItem;
_class: tClass;
begin
Create;
fTaskProc := Proc;
fTaskMethod := Method;
fDestObj := obj;
if method <> nil then
begin
_class := TObject(tMethod(fTaskMethod).Data).ClassType;
fName := lowercase(_class.MethodName(tMethod(fTaskMethod).Code));
end
else
fName := '';
SetParams(params);
if (proc_before <> nil) or (method_before <> nil) then
before := tMultiTaskItem.Create(proc_before, method_before,
params_before, nil, nil, [], nil, nil, [])
else
before := nil;
if (proc_after <> nil) or (method_after <> nil) then
after := tMultiTaskItem.Create(proc_after, method_after, params_after,
nil, nil, [], nil, nil, [])
else
after := nil;
fBeforeRun := before;
fAfterRun := after;
end;
constructor tMultiTaskItem.Create;
begin
inherited;
fTaskProc := nil;
fTaskMethod := nil;
fPriority := tpLast;
end;
function tMultiTaskItem.AsPascalSourceString: string;
begin
Result := fName + '(' + fParamsAsPascalString + ');';
end;
destructor tMultiTaskItem.Destroy;
begin
SetLength(fInteger, 0);
SetLength(fBoolean, 0);
SetLength(fChar, 0);
SetLength(fExtended, 0);
SetLength(fString, 0);
SetLength(fPChar, 0);
SetLength(ftObject, 0);
SetLength(ftClass, 0);
SetLength(fString, 0);
SetLength(fCurrency, 0);
SetLength(fVariant, 0);
SetLength(fInt64, 0);
SetLength(fInterface, 0);
inherited Destroy;
end;
function tMultiTaskItem.getAnsiString(const i: integer): ansistring;
begin
Result := default(ansistring);
if i <= Length(fAnsiString) then
Result := fAnsiString[i - 1];
end;
function tMultiTaskItem.getboolean(const i: integer): boolean;
begin
Result := default(boolean);
if i <= Length(fboolean) then
Result := fboolean[i - 1];
end;
function tMultiTaskItem.getchar(const i: integer): char;
begin
Result := default(char);
if i <= Length(fChar) then
Result := fChar[i - 1];
end;
function tMultiTaskItem.getCurrency(const i: integer): currency;
begin
Result := default(currency);
if i <= Length(fCurrency) then
Result := fCurrency[i - 1];
end;
function tMultiTaskItem.getExtended(const i: integer): extended;
begin
Result := default(extended);
if i <= Length(fExtended) then
Result := fExtended[i - 1];
end;
function tMultiTaskItem.getInt64(const i: integer): int64;
begin
Result := default(int64);
if i <= Length(fInt64) then
Result := fInt64[i - 1];
end;
function tMultiTaskItem.getInteger(const i: integer): integer;
begin
Result := default(integer);
if i <= Length(finteger) then
Result := finteger[i - 1];
end;
function tMultiTaskItem.getinterface(const id: integer): pointer;
begin
Result := default(Pointer);
if id <= Length(finterface) then
Result := finterface[id - 1];
end;
function tMultiTaskItem.getnextAnsiString: ansistring;
begin
Result := self.ParAnsiString[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextB: boolean;
begin
Result := self.B[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextchar: char;
begin
Result := self.ParChar[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextClass: tClass;
begin
Result := self.ParClass[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextCurrency: currency;
begin
Result := self.ParCurrency[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextExtended: extended;
begin
Result := self.E[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextI: integer;
begin
Result := self.I[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextInt64: int64;
begin
Result := self.I64[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextO: TObject;
begin
Result := self.O[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextPChar: PChar;
begin
Result := self.ParPChar[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextS: string;
begin
Result := self.S[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getnextVariant: variant;
begin
Result := self.ParVariant[fparamid];
Inc(fparamid);
end;
function tMultiTaskItem.getPChar(const i: integer): PChar;
begin
Result := default(PChar);
if i <= Length(fPChar) then
Result := fPChar[i - 1];
end;
function tMultiTaskItem.getString(const i: integer): string;
begin
Result := default(string);
if i <= Length(fString) then
Result := fString[i - 1];
end;
function tMultiTaskItem.gettClass(const i: integer): tClass;
begin
Result := default(tClass);
if i <= Length(ftClass) then
Result := ftClass[i - 1];
end;
function tMultiTaskItem.gettObject(const i: integer): TObject;
begin
Result := default(TObject);
if i <= Length(ftObject) then
Result := ftObject[i - 1];
end;
function tMultiTaskItem.getVariant(const i: integer): variant;
begin
Result := default(variant);
if i <= Length(fVariant) then
Result := fVariant[i - 1];
end;
procedure tMultiTaskItem.SetParams(const Data: array of const);
var
p: integer;
begin
p := length(Data);
SetLength(fInteger, p);
SetLength(fBoolean, p);
SetLength(fChar, p);
SetLength(fExtended, p);
SetLength(fString, p);
SetLength(fPChar, p);
SetLength(ftObject, p);
SetLength(ftClass, p);
SetLength(fString, p);
SetLength(fCurrency, p);
SetLength(fVariant, p);
SetLength(fInt64, p);
SetLength(fInterface, p);
fParamsAsPascalString := '';
for p := low(Data) to high(Data) do
begin
case Data[p].VType of
vtInteger:
begin
fInteger[p] := Data[p].VInteger;
fParamsAsPascalString += IntToStr(fInteger[p]) + ',';
end;
vtBoolean:
begin
fBoolean[p] := Data[p].VBoolean;
if fBoolean[p] then
fParamsAsPascalString += 'true,'
else
fParamsAsPascalString += 'false,';
end;
vtChar:
begin
fChar[p] := Data[p].VChar;
fParamsAsPascalString += '''' + fChar[p] + ''',';
end;
vtExtended:
begin
fExtended[p] := Data[p].VExtended^;
fParamsAsPascalString += FloatToStr(fExtended[p]) + ',';
end;
vtString:
begin
fString[p] := Data[p].VString^;
fParamsAsPascalString += '''' + fString[p] + ''',';
end;
vtPChar:
begin
fPChar[p] := Data[p].VPChar;
fParamsAsPascalString += '''' + fPChar[p] + ''',';
end;
vtObject:
begin
ftObject[p] := Data[p].VObject;
if ftObject[p] = nil then
fParamsAsPascalString += 'object:nil,'
else
fParamsAsPascalString += 'object:' + ftObject[p].ClassName + ',';
end;
vtClass:
begin
ftClass[p] := Data[p].VClass;
if ftClass[p] = nil then
fParamsAsPascalString += 'class:nil,'
else
fParamsAsPascalString += 'class:' + ftClass[p].ClassName + ',';
end;
vtAnsiString:
begin
fString[p] := ansistring(Data[p].VAnsiString);
fParamsAsPascalString += '''' + fString[p] + ''',';
end;
vtCurrency:
begin
fCurrency[p] := Data[p].VCurrency^;
fParamsAsPascalString += FloatToStr(fCurrency[p]) + ',';
end;
vtVariant:
begin
fVariant[p] := Data[p].VVariant^;
fParamsAsPascalString += fVariant[p] + ',';
end;
vtInt64:
begin
fInt64[p] := Data[p].VInt64^;
fParamsAsPascalString += IntToStr(fInt64[p]) + ',';
end;
vtInterface:
begin
fInterface[p] := IUnknown(Data[p].VInterface);
if fInterface[p] = nil then
fParamsAsPascalString += 'interface:nil,'
else
fParamsAsPascalString += 'interface,';
end;
end;
end;
fParamsAsPascalString := copy(fParamsAsPascalString, 1,
length(fParamsAsPascalString) - 1);
fparamid := 1;
end;
constructor tMultiTaskQueue.Create(MultiTask: TObject);
begin
inherited Create;
fFirst := nil;
fLast := nil;
fCount := 0;
CS := InitCS;
fMultiTask := MultiTask;
end;
destructor tMultiTaskQueue.Destroy;
begin
DoneCS(CS);
inherited Destroy;
end;
function tMultiTaskQueue._FindFirstTaskWithPriority(
const tp: tTaskPriority): pQueueItem;
var
tmp: pQueueItem;
begin
tmp := fFirst;
while tmp^.Next <> nil do
begin
if (tmp^.Next <> nil) and (tmp^.Next^.Item.Priority > tp) then
Exit;
tmp := tmp^.Next;
end;
Result := tmp;
end;
procedure tMultiTaskQueue.EnqueuePriority(const Data: tMultiTaskItem; const tp: tTaskPriority; const OnlyUnique: boolean);
var
QueueItem, tmpItem, after : pQueueItem;
begin
New(QueueItem);
QueueItem^.Item := Data;
QueueItem^.Next := nil;
EnterCS(CS, 'Enqueue task item');
try
if OnlyUnique and _Exists_Or_Running(Data) then
begin
Dispose(QueueItem);
Exit;
end;
fCount += 1;
if (fFirst = nil) then
begin
fFirst := QueueItem;
fLast := QueueItem;
end
else
if (fLast = nil) then
begin
raise Exception.Create(
'EnqueuePriority - Queue.fLast is nil and fFirst not - this should not be !! ');
Halt;
end
else
begin
if fFirst^.Item.Priority > tp then
begin
tmpItem := fFirst;
QueueItem^.Next := tmpItem;
fFirst := QueueItem;
end
else
begin
after := _FindFirstTaskWithPriority(tp);
if after = nil then
begin
fLast^.Next := QueueItem;
fLast := QueueItem;
end
else
if after^.Next = nil then
begin
fLast^.Next := QueueItem;
fLast := QueueItem;
end
else
begin
tmpItem := after^.Next;
after^.Next := QueueItem;
QueueItem^.Next := tmpItem;
end;
end;
end;
finally
LeaveCS(CS);
if Assigned(fOn_New_Task) then
fOn_New_Task();
end;
end;
procedure tMultiTaskQueue.EnqueueFirst(const Data: tMultiTaskItem; const OnlyUnique: boolean);
var
QueueItem, before: pQueueItem;
begin
New(QueueItem);
QueueItem^.Item := Data;
QueueItem^.Next := nil;
EnterCS(CS, 'Enqueue task item');
try
if OnlyUnique and _Exists_Or_Running(Data) then
begin
Dispose(QueueItem);
Exit;
end;
fCount += 1;
if (fFirst = nil) then
begin
fFirst := QueueItem;
fLast := QueueItem;
end
else
if (fLast = nil) then
begin
raise Exception.Create(
'EnqueueFirst - Queue.fLast is nil and fFirst not - this should not be !! ');
Halt;
end
else
begin
before := fFirst;
QueueItem^.Next := before;
fFirst := QueueItem;
if fFirst^.Next = nil then
fLast := fFirst;
end;
finally
LeaveCS(CS);
if Assigned(fOn_New_Task) then
fOn_New_Task();
end;
end;
procedure tMultiTaskQueue.EnqueueLast(const Data: tMultiTaskItem; const OnlyUnique: boolean);
var
QueueItem: pQueueItem;
begin
New(QueueItem);
QueueItem^.Item := Data;
QueueItem^.Next := nil;
EnterCS(CS, 'Enqueue task item');
try
if OnlyUnique and _Exists_Or_Running(Data) then
begin
Dispose(QueueItem);
Exit;
end;
fCount += 1;
if (fFirst = nil) then
begin
fFirst := QueueItem;
fLast := QueueItem;
end
else
if (fLast = nil) then
begin
raise Exception.Create(
'EnqueueLast - Queue.fLast is nil and fFirst not - this should not be !! ');
Halt;
end
else
begin
fLast^.Next := QueueItem;
fLast := QueueItem;
end;
finally
LeaveCS(CS);
if Assigned(fOn_New_Task) then
fOn_New_Task();
end;
end;
procedure tMultiTaskQueue.Enqueue(const Data: tMultiTaskItem; const flags: tMultitaskEnQueueFlags);
begin
if teFirst in flags then
begin
Data.fPriority := tpFirst;
EnqueueFirst(Data, teUnique in flags);
end
else
if teHighPriority in flags then
begin
Data.fPriority := tpHigh;
EnqueuePriority(Data, tpHigh, teUnique in flags);
end
else
if teNormalPriority in flags then
begin
Data.fPriority := tpNormal;
EnqueuePriority(Data, tpNormal, teUnique in flags);
end
else
if teLowPriority in flags then
begin
Data.fPriority := tpLow;
EnqueuePriority(Data, tpLow, teUnique in flags);
end
else
EnqueueLast(Data, teUnique in flags);
end;
procedure tMultiTaskQueue.Enqueue(const proc: tTaskProc; const method: tTaskMethod; const params: array of const; const proc_before: tTaskProc;
const method_before: tTaskMethod; const params_before: array of const; const proc_after: tTaskProc; const method_after: tTaskMethod;
const params_after: array of const; const flags: tMultitaskEnQueueFlags; const obj: tObject);
var
i: integer;
Data: tMultiTaskItem;
begin
try
Data := tMultiTaskItem.Create(proc, method, params, proc_before,
method_before, params_before, proc_after, method_after, params_after, obj);
Enqueue(Data, flags);
except
on E: Exception do
begin
raise Exception.Create(E.Message + ' on Enqueue ' + Data.AsPascalSourceString);
end;
end;
end;
procedure tMultiTaskQueue.Enqueue(const method: tTaskMethod; const params: array of const; const flags: tMultitaskEnQueueFlags;
const obj: tObject);
begin
Enqueue(nil, method, params, nil, nil, [], nil, nil, [], flags,obj);
end;
procedure tMultiTaskQueue.Enqueue(const proc: tTaskProc; const params: array of const; const flags: tMultitaskEnQueueFlags);
begin
Enqueue(proc, nil, params, nil, nil, [], nil, nil, [], flags);
end;
function tMultiTaskQueue.DeQueue(const thrd: tObject): tMultiTaskItem;
var
QueueItem: pQueueItem;
begin
Result := Default(tMultiTaskItem);
EnterCS(CS, 'Dequeue');
try
if fFirst <> nil then
begin
Result := tMultiTaskItem(fFirst^.Item);
QueueItem := fFirst^.Next;
Dispose(fFirst);
fFirst := QueueItem;
if fFirst = nil then
fLast := nil;
fCount -= 1;
// if (result.fMinimumAvailableMemoryGb = -1) or (result.fMinimumAvailableMemoryGb > uMemory.GetAvailableMemoryGb)
// then
// begin
tMultiTaskThread(thrd).Task := result;
// end else
// begin
// self.Enqueue(result,result.fflags);
// result := nil;
// end;
end;
finally
LeaveCS(CS);
end;
end;
procedure tMultiTaskQueue.Clear;
var
QueueItem, i: pQueueItem;
begin
EnterCS(CS, 'Clear Queue');
try
QueueItem := fFirst;
fFirst := nil;
fLast := nil;
finally
LeaveCS(CS);
end;
while QueueItem <> nil do
begin
QueueItem^.Item := nil;
// QueueItem^.Data^.Originator := nil;
// QueueItem^.Data^.OriginatorName := '';
i := QueueItem;
QueueItem := QueueItem^.Next;
Dispose(i);
end;
end;
function tMultiTaskQueue.Length: integer;
begin
EnterCS(CS, 'Queue Length');
try
Result := fCount;
finally
LeaveCS(CS);
end;
end;
function tMultiTaskQueue.Exists(const Data: tMultiTaskItem): boolean;
begin
EnterCS(CS, 'Exist in queue : ' + Data.Name);
try
Result := _Exists(Data);
finally
LeaveCS(CS);
end;
end;
function tMultiTaskQueue._Exists(const Data: tMultiTaskItem): boolean;
var
QI: pQueueItem;
begin
if fFirst = nil then
Exit(False);
QI := fFirst;
repeat
if QI^.Item.AsPascalSourceString = Data.AsPascalSourceString then
begin
Exit(True);
end;
QI := QI^.Next;
until QI = nil;
Result := False;
end;
function tMultiTaskQueue._Exists_Or_Running(const Data: tMultiTaskItem): boolean;
begin
Result := _Exists(Data) or tMultiTask(MultiTask).isTaskRunning(Data);
end;
function tMultiTaskQueue.HaveWork: boolean;
begin
EnterCS(CS, 'Queue - Have Work');
try
Result := fFirst <> nil;
finally
LeaveCS(CS);
end;
end;
procedure tMultiTaskQueue.setOn_New_Task(AValue: tOn_New_Task);
begin
if fOn_New_Task = AValue then
Exit;
fOn_New_Task := AValue;
end;
end.
|
unit GX_OpenFile;
{$I GX_CondDefine.inc}
interface
uses
Classes, Controls, Forms, Actions, ActnList, Dialogs, StdCtrls,
ComCtrls, ExtCtrls, GX_GenericUtils, ToolWin, Messages,
GX_OpenFileConfig, GX_BaseForm;
const
UM_REFRESHLIST = WM_USER + 746;
UM_NEXTFILTERBLOCK = WM_USER + 747;
type
TOpenType = (otOpenMenu, otViewUnit, otViewForm, otOpenProject);
TAvailableFiles = class(TObject)
private
FProjectFiles: TStringList;
FCommonDCUFiles: TStringList;
FCommonFiles: TStringList;
FSearchPathFiles: TStringList;
FOnFindComplete: TThreadMethod;
FSearchPathThread: TFileFindThread;
FCommonThread: TFileFindThread;
FFileMasks: TStringList;
FCommonFileMask: string;
FFileExtensions: string;
FSearchPaths: TStrings;
FRecursiveDirSearch: Boolean;
FCommonSearchDone: Boolean;
FSearchPathDone: Boolean;
procedure PathSearchComplete;
procedure CommonSearchComplete;
procedure GetCommonDCUFiles;
procedure AddCurrentProjectFiles(PathUnits: TStringList);
protected
procedure GetSearchPath(Paths: TStrings); virtual;
public
procedure Execute;
constructor Create;
destructor Destroy; override;
property ProjectFiles: TStringList read FProjectFiles write FProjectFiles;
procedure Terminate;
property CommonFiles: TStringList read FCommonFiles write FCommonFiles;
property CommonDCUFiles: TStringList read FCommonDCUFiles write FCommonDCUFiles;
property SearchPathFiles: TStringList read FSearchPathFiles write FSearchPathFiles;
property OnFindComplete: TThreadMethod read FOnFindComplete write FOnFindComplete;
property FileExtension: string read FFileExtensions write FFileExtensions;
property SearchPaths: TStrings read FSearchPaths write FSearchPaths;
property RecursiveDirSearch: Boolean read FRecursiveDirSearch write FRecursiveDirSearch;
procedure HaltThreads;
end;
TfmOpenFile = class(TfmBaseForm)
pnlUnits: TPanel;
pcUnits: TPageControl;
tabSearchPath: TTabSheet;
pnlSearchPathFooter: TPanel;
pnlSearchPath: TPanel;
tabProject: TTabSheet;
pnlProject: TPanel;
pnlProjFooter: TPanel;
tabCommon: TTabSheet;
pnlCommon: TPanel;
pnlCommonFooter: TPanel;
tabFavorite: TTabSheet;
pnlFavorite: TPanel;
pnlFavFooter: TPanel;
btnFavoriteDeleteFromFavorites: TButton;
pnlAvailableHeader: TPanel;
lblFilter: TLabel;
edtFilter: TEdit;
pnlOKCancel: TPanel;
btnCommonAddToFavorites: TButton;
btnProjectAddToFavorites: TButton;
btnSearchAddToFavorites: TButton;
ToolBar: TToolBar;
tbnMatchFromStart: TToolButton;
tbnMatchAnywhere: TToolButton;
tbnSep1: TToolButton;
tbnHelp: TToolButton;
lvSearchPath: TListView;
lvFavorite: TListView;
lvCommon: TListView;
lvProjects: TListView;
lblExtension: TLabel;
cbxType: TComboBox;
tabRecent: TTabSheet;
tbnConfig: TToolButton;
tbnSep3: TToolButton;
pnlRecentFooter: TPanel;
btnClearRecent: TButton;
chkDefault: TCheckBox;
tbnOpenFile: TToolButton;
tbnSep2: TToolButton;
pnlRecent: TPanel;
lvRecent: TListView;
btnFavoriteAddToFavorites: TButton;
OpenDialog: TOpenDialog;
btnRecentAddToFavorites: TButton;
ActionList: TActionList;
actAddToFavorites: TAction;
actMatchPrefix: TAction;
actMatchAnywhere: TAction;
actConfig: TAction;
actHelp: TAction;
actOpenFile: TAction;
actFavAddToFavorites: TAction;
actFavDeleteFromFavorites: TAction;
actClearRecentList: TAction;
tmrFilter: TTimer;
pnlButtonsRight: TPanel;
btnOK: TButton;
btnCancel: TButton;
procedure tmrFilterTimer(Sender: TObject);
procedure actHelpExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure edtFilterKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edtFilterChange(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure actMatchAnywhereExecute(Sender: TObject);
procedure actMatchPrefixExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FileListDoubleClick(Sender: TObject);
procedure pcUnitsChange(Sender: TObject);
procedure cbxTypeChange(Sender: TObject);
procedure actConfigExecute(Sender: TObject);
procedure tabSearchPathShow(Sender: TObject);
procedure tabProjectShow(Sender: TObject);
procedure tabCommonShow(Sender: TObject);
procedure tabFavoriteShow(Sender: TObject);
procedure tabRecentShow(Sender: TObject);
procedure actOpenFileExecute(Sender: TObject);
procedure actAddToFavoritesExecute(Sender: TObject);
procedure actFavAddToFavoritesExecute(Sender: TObject);
procedure actFavDeleteFromFavoritesExecute(Sender: TObject);
procedure actClearRecentListExecute(Sender: TObject);
procedure pcUnitsResize(Sender: TObject);
private
FAvailableFiles: TAvailableFiles;
FInitialFileType: string;
FCurrentListView: TListView;
FCurrentFilePaths: TStringList;
FFileColumnWidth: Integer;
FCurrentFilterIndex: Integer;
procedure SearchPathReady;
procedure FilterVisibleUnits;
procedure FilterVisibleUnitsBlockwise(const TimeoutMS: Cardinal);
procedure UMFilterNextBlock(var Msg: TMessage); message UM_NEXTFILTERBLOCK;
procedure SelectMatchingItemInList;
procedure DeleteFromFavorites(Item: TListItem);
function GetActivePageIndex: Integer;
procedure SetActivePageIndex(Value: Integer);
procedure DoOpenFile(const AFileName: string);
function CurrentFileType: TFileType;
procedure UMRefreshList(var Msg: TMessage); message UM_REFRESHLIST;
procedure AddFavoriteFile(const AFileName: string);
function MakeFileName(Item: TListItem): string;
function GetMatchAnywhere: Boolean;
procedure SetMatchAnywhere(Value: Boolean);
function Settings: TOpenFileSettings;
function FileTypes: TFileTypes;
function FileType(Index: Integer): TFileType;
procedure InitializeFromSettings;
procedure InitializeFileTypes(const SelectType: string);
procedure LoadSettings;
procedure SaveSettings;
function ConfigurationKey: string;
procedure CopyColumns(Source: TListView);
procedure ResizeListViewColumns;
procedure SetCurrentListView(const Value: TListView);
procedure lvFavoriteFilesDropped(Sender: TObject; Files: TStrings);
property CurrentListView: TListView read FCurrentListView write SetCurrentListView;
public
property ActivePageIndex: Integer read GetActivePageIndex write SetActivePageIndex;
property AvailableFiles: TAvailableFiles read FAvailableFiles write FAvailableFiles;
property InitialFileType: string read FInitialFileType write FInitialFileType;
property MatchAnywhere: Boolean read GetMatchAnywhere write SetMatchAnywhere;
end;
implementation
{$R *.dfm}
uses
SysUtils, Menus, Graphics, Windows, ToolsAPI,
GX_IdeUtils, GX_SharedImages, GX_Experts, GX_ConfigurationInfo, GX_OtaUtils,
GX_GxUtils, GX_dzVclUtils;
resourcestring
SOpenUnitMenuName = 'OpenFile';
const
ViewUnitAction = 'ViewUnitCommand';
ViewFormAction = 'ViewFormCommand';
OpenProjectAction = 'FileOpenProjectCommand';
type
TOpenFileNotifier = class(TBaseIdeNotifier)
public
procedure FileNotification(NotifyCode: TOTAFileNotification;
const FileName: string; var Cancel: Boolean); override;
end;
TOpenFileExpert = class(TGX_Expert)
private
FOpenFileIDEOnClick: TNotifyEvent;
FOpenFormIDEOnClick: TNotifyEvent;
FOpenProjectIDEOnClick: TNotifyEvent;
FNotifier: TOpenFileNotifier;
procedure OpenExpert(const OpenFileType: TOpenType);
procedure OpenFile(Sender: TObject);
procedure OpenForm(Sender: TObject);
procedure OpenProject(Sender: TObject);
procedure HijackIDEActions;
procedure HijackIDEAction(const ActionName: string; var OriginalIDEAction: TNotifyEvent; NewIDEAction: TNotifyEvent);
procedure ResetIDEAction(const ActionName: string; IDEHandler: TNotifyEvent);
public
Settings: TOpenFileSettings;
constructor Create; override;
destructor Destroy; override;
function HasConfigOptions: Boolean; override;
function HasMenuItem: Boolean; override;
procedure InternalLoadSettings(ASettings: TExpertSettings); override;
procedure InternalSaveSettings(ASettings: TExpertSettings); override;
procedure Execute(Sender: TObject); override;
function GetActionCaption: string; override;
class function GetName: string; override;
procedure Configure; override;
procedure AfterIDEInitialized; override;
end;
var
OpenFileExpert: TOpenFileExpert;
{ TOpenFileExpert }
procedure TOpenFileExpert.OpenExpert(const OpenFileType: TOpenType);
var
Form: TfmOpenFile;
begin
Form := TfmOpenFile.Create(nil);
try
Form.ActivePageIndex := Settings.LastTabIndex;
Form.Caption := 'GExperts ' + StripHotkey(GetActionCaption);
Form.LoadSettings;
case OpenFileType of
otOpenMenu: Form.InitialFileType := Settings.DefaultFileType;
otOpenProject: Form.InitialFileType := Settings.IDEOverride.OpenProjectDefaultType;
otViewUnit: Form.InitialFileType := Settings.IDEOverride.OpenUnitDefaultType;
otViewForm: Form.InitialFileType := Settings.IDEOverride.OpenFormDefaultType;
end;
SetFormIcon(Form);
if (Form.ShowModal = mrOk) or (Form.chkDefault.Checked) then begin
SaveSettings;
Form.SaveSettings;
end;
finally
FreeAndNil(Form);
end;
end;
constructor TOpenFileExpert.Create;
begin
inherited;
Settings := TOpenFileSettings.Create;
Settings.ConfigurationKey := ConfigurationKey;
OpenFileExpert := Self;
FNotifier := TOpenFileNotifier.Create;
FNotifier.AddNotifierToIDE;
end;
destructor TOpenFileExpert.Destroy;
begin
ResetIDEAction(ViewUnitAction, FOpenFileIDEOnClick);
ResetIDEAction(ViewFormAction, FOpenFormIDEOnClick);
ResetIDEAction(OpenProjectAction, FOpenProjectIDEOnClick);
FNotifier.RemoveNotifierFromIDE;
FNotifier := nil; // Free is done by the IDE for us
FreeAndNil(Settings);
OpenFileExpert := nil;
inherited;
end;
function TOpenFileExpert.HasConfigOptions: Boolean;
begin
Result := True;
end;
function TOpenFileExpert.HasMenuItem: Boolean;
begin
Result := True;
end;
procedure TOpenFileExpert.InternalLoadSettings(ASettings: TExpertSettings);
begin
inherited;
Settings.InternalLoadSettings(ASettings);
end;
procedure TOpenFileExpert.InternalSaveSettings(ASettings: TExpertSettings);
begin
inherited;
Settings.InternalSaveSettings(ASettings);
HijackIDEActions;
end;
procedure TOpenFileExpert.HijackIDEAction(const ActionName: string; var OriginalIDEAction: TNotifyEvent; NewIDEAction: TNotifyEvent);
var
Action: TContainedAction;
begin
Action := GxOtaGetIdeActionByName(ActionName);
if (Action <> nil) and (Action is TCustomAction) then
begin
OriginalIDEAction := (Action as TCustomAction).OnExecute;
(Action as TCustomAction).OnExecute := NewIDEAction;
end;
end;
procedure TOpenFileExpert.Execute(Sender: TObject);
begin
OpenExpert(otOpenMenu);
end;
procedure TOpenFileExpert.OpenFile(Sender: TObject);
begin
OpenExpert(otViewUnit);
end;
procedure TOpenFileExpert.OpenForm(Sender: TObject);
begin
OpenExpert(otViewForm);
end;
function TOpenFileExpert.GetActionCaption: string;
resourcestring
SViewUnitMenuCaption = 'Open File';
begin
Result := SViewUnitMenuCaption;
end;
class function TOpenFileExpert.GetName: string;
begin
Result := SOpenUnitMenuName;
end;
procedure TOpenFileExpert.OpenProject(Sender: TObject);
begin
OpenExpert(otOpenProject);
end;
procedure TOpenFileExpert.Configure;
begin
TfmOpenFileConfig.ExecuteWithSettings(Settings);
end;
procedure TOpenFileExpert.HijackIDEActions;
begin
if Self.Settings.IDEOverride.OverrideOpenUnit then
begin
if not Assigned(FOpenFileIDEOnClick) then
HijackIDEAction(ViewUnitAction, FOpenFileIDEOnClick, OpenFile);
end
else if Assigned(FOpenFileIDEOnClick) then
ResetIDEAction(ViewUnitAction, FOpenFileIDEOnClick);
if Self.Settings.IDEOverride.OverrideOpenForm then
begin
if not Assigned(FOpenFormIDEOnClick) then
HijackIDEAction(ViewFormAction, FOpenFormIDEOnClick, OpenForm);
end
else if Assigned(FOpenFormIDEOnClick) then
ResetIDEAction(ViewFormAction, FOpenFormIDEOnClick);
if Self.Settings.IDEOverride.OverrideOpenProject then
begin
if not Assigned(FOpenProjectIDEOnClick) then
HijackIDEAction(OpenProjectAction, FOpenProjectIDEOnClick, OpenProject);
end
else if Assigned(FOpenProjectIDEOnClick) then
ResetIDEAction(ViewFormAction, FOpenProjectIDEOnClick);
end;
procedure TOpenFileExpert.AfterIDEInitialized;
begin
inherited;
HijackIDEActions;
end;
procedure TOpenFileExpert.ResetIDEAction(const ActionName: string; IDEHandler: TNotifyEvent);
var
Action: TContainedAction;
begin
if not Assigned(IDEHandler) then
Exit;
Action := GxOtaGetIdeActionByName(ActionName);
if Assigned(Action) then
Action.OnExecute := IDEHandler;
end;
{ TAvailableFiles }
constructor TAvailableFiles.Create;
begin
inherited;
FFileMasks := TStringList.Create;
FCommonFiles := TStringList.Create;
FCommonDCUFiles := TStringList.Create;
FProjectFiles := TStringList.Create;
FSearchPathFiles := TStringList.Create;
end;
destructor TAvailableFiles.Destroy;
begin
OnFindComplete := nil;
HaltThreads;
FreeAndNil(FFileMasks);
FreeAndNil(FCommonFiles);
FreeAndNil(FCommonDCUFiles);
FreeAndNil(FProjectFiles);
FreeAndNil(FSearchPathFiles);
FreeAndNil(FSearchPathThread);
FreeAndNil(FCommonThread);
inherited;
end;
procedure TAvailableFiles.Execute;
var
PathsToUse: TStringList;
begin
FCommonFiles.Clear;
FCommonDCUFiles.Clear;
FProjectFiles.Clear;
FSearchPathFiles.Clear;
FSearchPathDone := False;
FCommonSearchDone := False;
FreeAndNil(FSearchPathThread);
FSearchPathThread := TFileFindThread.Create;
// This will allow semi-colon separated lists at the user GUI level
// D5 has no way to separate ; using TStrings.
FSearchPathThread.FileMasks.CommaText := StringReplace(FFileExtensions, ';', ',', [rfReplaceAll]);
if FRecursiveDirSearch then
PathsToUse := FSearchPathThread.RecursiveSearchDirs
else
PathsToUse := FSearchPathThread.SearchDirs;
GetSearchPath(PathsToUse);
AppendStrings(PathsToUse, FSearchPaths);
FSearchPathThread.OnFindComplete := PathSearchComplete;
FSearchPathThread.StartFind;
FreeAndNil(FCommonThread);
FCommonThread := TFileFindThread.Create;
FCommonThread.RecursiveSearchDirs.Add(ExtractFilePath(GetIdeRootDirectory) + AddSlash('Source'));
FCommonThread.FileMasks.CommaText := '*.pas,*.cpp,*.cs,*.inc,*.dfm';
FCommonThread.OnFindComplete := CommonSearchComplete;
FCommonThread.StartFind;
FCommonFileMask := FFileExtensions;
if False then // Not needed yet (only needed for uses clause manager?)
GetCommonDCUFiles;
AddCurrentProjectFiles(FProjectFiles);
end;
procedure TAvailableFiles.PathSearchComplete;
var
PathFiles: TStringList;
PathUnits: TStringList;
i: Integer;
begin
PathUnits := nil;
PathFiles := TStringList.Create;
try
FSearchPathThread.LockResults;
try
PathFiles.Assign(FSearchPathThread.Results);
finally
FSearchPathThread.ReleaseResults;
end;
PathUnits := TStringList.Create;
PathUnits.Sorted := True;
PathUnits.Duplicates := dupIgnore;
for i := 0 to PathFiles.Count - 1 do
PathUnits.Add(ExpandFileName(PathFiles[i]));
AddCurrentProjectFiles(PathUnits);
FSearchPathFiles.Assign(PathUnits);
FSearchPathDone := True;
finally
FreeAndNil(PathFiles);
FreeAndNil(PathUnits);
end;
if FCommonSearchDone and Assigned(FOnFindComplete) then
FOnFindComplete;
end;
procedure TAvailableFiles.CommonSearchComplete;
begin
FCommonThread.LockResults;
try
CommonFiles.Assign(FCommonThread.Results);
FCommonSearchDone := True;
finally
FCommonThread.ReleaseResults;
end;
if FSearchPathDone and Assigned(FOnFindComplete) then
FOnFindComplete;
end;
procedure TAvailableFiles.GetCommonDCUFiles;
var
Found: Integer;
SearchRec: TSearchRec;
FileSpec: string;
begin
//TODO 3 -cFeature -oAnyone: Make this threaded before using it
FileSpec := GetIdeRootDirectory + AddSlash('lib') + '*.dcu';
Found := SysUtils.FindFirst(FileSpec, faAnyFile, SearchRec);
try
while Found = 0 do
begin
if not ((SearchRec.Attr and faDirectory) = faDirectory) then
FCommonDCUFiles.Add(ExtractPureFileName(SearchRec.Name));
Found := SysUtils.FindNext(SearchRec);
end;
finally
SysUtils.FindClose(SearchRec);
end;
end;
procedure TAvailableFiles.AddCurrentProjectFiles(PathUnits: TStringList);
var
ExtensionIndex: Integer;
Project: IOTAProject;
i: Integer;
CurrentProjectFiles, FileExtensions: TStringList;
FileName: string;
begin
Project := GxOtaGetCurrentProject;
if Assigned(Project) then
begin
FileExtensions := nil;
CurrentProjectFiles := TStringList.Create;
try
FileExtensions := TStringList.Create;
// This will allow semi-colon separated lists at the user GUI level
// D5 has no way to separate ; into TStrings.
FileExtensions.CommaText := StringReplace(FFileExtensions, ';', ',', [rfReplaceAll]);
GxOtaGetProjectFileNames(Project, CurrentProjectFiles);
for i := 0 to CurrentProjectFiles.Count - 1 do
for ExtensionIndex := 0 to FileExtensions.Count - 1 do
begin
FileName := ChangeFileExt(CurrentProjectFiles[i], ExtractFileExt(FileExtensions[ExtensionIndex]));
if FileExists(FileName) then
PathUnits.Add(ExpandFileName(FileName));
end;
finally
FreeAndNil(CurrentProjectFiles);
FreeAndNil(FileExtensions);
end;
end;
end;
procedure TAvailableFiles.GetSearchPath(Paths: TStrings);
begin
GxOtaGetEffectiveLibraryPath(Paths);
end;
procedure TAvailableFiles.HaltThreads;
procedure StopThread(Thread: TFileFindThread);
begin
if Assigned(Thread) then
begin
Thread.OnFindComplete := nil;
Thread.Terminate;
Thread.WaitFor;
end;
end;
var
Cursor: IInterface;
begin
Cursor := TempHourGlassCursor;
StopThread(FSearchPathThread);
StopThread(FCommonThread);
end;
{ TOpenFileNotifier }
procedure TOpenFileNotifier.FileNotification(NotifyCode: TOTAFileNotification;
const FileName: string; var Cancel: Boolean);
var
i: Integer;
FType: TFileType;
FileExt: string;
FilePath: string;
begin
case NotifyCode of
ofnFileOpened:
begin
try
FileExt := LowerCase(ExtractFileExt(FileName));
FilePath := ExtractFilePath(FileName);
if StrBeginsWith('.', FileExt) then
FileExt := Copy(FileExt, 2, Length(FileExt));
if FileExt = '' then // Unknown files
Exit;
if FilePath = '' then // Temporary unsaved files, SQL in the editor, etc.
Exit;
for i := 0 to OpenFileExpert.Settings.FileTypes.Count - 1 do
begin
FType := TFileType(OpenFileExpert.Settings.FileTypes.Items[i]);
if StrContains('*.' + FileExt, FType.Extensions, False) then
FType.RecentFiles.Add(FileName);
end;
except
on E: Exception do // Nothing should keep the file from opening
MessageDlg('Error storing value in GExperts Open File MRU list.' + sLineBreak + E.Message, mtError, [mbOK], 0);
end;
end;
end;
end;
{ TfmOpenFile }
procedure TfmOpenFile.FormCreate(Sender: TObject);
begin
SetToolbarGradient(ToolBar);
lvSearchPath.Color := clBtnFace;
lvSearchPath.Enabled := False;
lvCommon.Color := clBtnFace;
lvCommon.Enabled := False;
FAvailableFiles := TAvailableFiles.Create;
AvailableFiles.OnFindComplete := SearchPathReady;
lvSearchPath.DoubleBuffered := True;
lvFavorite.DoubleBuffered := True;
lvCommon.DoubleBuffered := True;
lvProjects.DoubleBuffered := True;
lvRecent.DoubleBuffered := True;
TWinControl_ActivateDropFiles(lvFavorite, lvFavoriteFilesDropped);
end;
procedure TfmOpenFile.lvFavoriteFilesDropped(Sender: TObject; Files: TStrings);
var
i: Integer;
fn: string;
begin
for i := 0 to Files.Count - 1 do begin
fn := Files[i];
if FileExists(fn) then
AddFavoriteFile(fn);
end;
FilterVisibleUnits;
end;
procedure TfmOpenFile.SearchPathReady;
begin
FilterVisibleUnits;
lvSearchPath.HandleNeeded;
lvSearchPath.Color := clWindow;
lvSearchPath.Enabled := True;
lvCommon.HandleNeeded;
lvCommon.Color := clWindow;
lvCommon.Enabled := True;
end;
procedure TfmOpenFile.FilterVisibleUnits;
begin
FCurrentFilterIndex := 0; // Restart Filtering
PostMessage(Self.Handle, UM_NEXTFILTERBLOCK, 0, 0); // Queue first block for filtering
end;
procedure TfmOpenFile.FilterVisibleUnitsBlockwise(const TimeoutMS: Cardinal);
procedure AddListItem(FileListView: TListView; UnitFileName: string);
var
ListItem: TListItem;
begin
ListItem := FileListView.Items.Add;
ListItem.Caption := ExtractPureFileName(UnitFileName);
ListItem.SubItems.Add(RemoveSlash(ExtractFilePath(UnitFileName)));
ListItem.SubItems.Add(LowerCase(ExtractFileExt(UnitFileName)));
end;
function IsTimedOut(const StartTime: Cardinal): Boolean;
begin
Result := Cardinal(GetTickCount - StartTime) >= TimeoutMS;
end;
var
SearchValue: string;
StartTime: Cardinal;
ListComplete: Boolean;
begin
if FCurrentFilterIndex = 0 then
begin // start of filtering
pcUnits.ActivePage.OnShow(pcUnits.ActivePage);
end;
CurrentListView.Items.BeginUpdate;
try
if FCurrentFilterIndex = 0 then
begin
CurrentListView.Items.Clear;
CurrentListView.SortType := stNone;
end;
StartTime := GetTickCount;
while (FCurrentFilterIndex <= FCurrentFilePaths.Count - 1) and not IsTimedOut(StartTime) do
begin
SearchValue := ExtractPureFileName(FCurrentFilePaths[FCurrentFilterIndex]);
if Length(edtFilter.Text) = 0 then
AddListItem(CurrentListView, FCurrentFilePaths[FCurrentFilterIndex])
else
if tbnMatchAnywhere.Down then
begin
if StrContains(edtFilter.Text, SearchValue, False) then
AddListItem(CurrentListView, FCurrentFilePaths[FCurrentFilterIndex]);
end
else
if StrBeginsWith(edtFilter.Text, SearchValue, False) then
AddListItem(CurrentListView, FCurrentFilePaths[FCurrentFilterIndex]);
Inc(FCurrentFilterIndex);
end;
ListComplete := FCurrentFilterIndex >= FCurrentFilePaths.Count - 1;
if ListComplete then
begin // Filtering complete
CurrentListView.SortType := stText;
SelectMatchingItemInList;
end;
finally
CurrentListView.Items.EndUpdate;
end;
if not ListComplete then
begin
Application.ProcessMessages;
// Application.ProcessMessages may have initiiated new filtering. Only
// continue our current run if FCurrentFilterIndex was not touched.
if FCurrentFilterIndex > 0 then
PostMessage(Self.Handle, UM_NEXTFILTERBLOCK, 0, 0); // Queue next block for filtering
end else
ResizeListViewColumns;
end;
procedure TfmOpenFile.SelectMatchingItemInList;
var
i, SelIndex: Integer;
FilterText: string;
ListItem: TListItem;
begin
if CurrentListView.Items.Count > 0 then
begin
SelIndex := 0;
FilterText := edtFilter.Text;
for i := 0 to CurrentListView.Items.Count - 1 do
begin
ListItem := CurrentListView.Items[i];
if StrBeginsWith(FilterText, ListItem.Caption, False) then
begin
SelIndex := i;
Break;
end;
end;
ListItem := CurrentListView.Items[SelIndex];
ListItem.Selected := True;
CurrentListView.ItemFocused := ListItem;
ListItem.MakeVisible(False);
end;
end;
procedure TfmOpenFile.edtFilterKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
ListBox: TListView;
begin
if (Key in [VK_DOWN, VK_UP, VK_NEXT, VK_PRIOR]) then
begin
ListBox := CurrentListView;
if ListBox.Items.Count > 1 then
ListBox.Perform(WM_KEYDOWN, Key, 0)
else
if ListBox.Items.Count = 1 then
ListBox.Items[0].Selected := True;
Key := 0;
end;
end;
procedure TfmOpenFile.edtFilterChange(Sender: TObject);
begin
tmrFilter.Enabled := False;
tmrFilter.Enabled := True; //FI:W508 - stop and restart timer on key press
end;
procedure TfmOpenFile.tmrFilterTimer(Sender: TObject);
begin
FilterVisibleUnits;
tmrFilter.Enabled := False;
end;
procedure TfmOpenFile.btnOKClick(Sender: TObject);
var
i: Integer;
Src: TListView;
FileName: string;
begin
FAvailableFiles.Terminate;
Src := CurrentListView;
if Src.SelCount > 0 then
for i := 0 to Src.Items.Count - 1 do
if Src.Items[i].Selected then
begin
FileName := MakeFileName(Src.Items[i]);
DoOpenFile(FileName);
// TODO 4 -oAnyone -cFeature: Add support for focusing the editor to the last file
//if i = Src.Items.Count - 1 then
// Focus last editor/form
end;
end;
procedure TfmOpenFile.DeleteFromFavorites(Item: TListItem);
begin
DeleteStringFromList(CurrentFileType.Favorites, MakeFileName(Item));
Item.Delete;
end;
procedure TfmOpenFile.FormDestroy(Sender: TObject);
begin
FreeAndNil(FAvailableFiles);
end;
procedure TfmOpenFile.actMatchAnywhereExecute(Sender: TObject);
begin
FilterVisibleUnits;
end;
procedure TAvailableFiles.Terminate;
begin
FSearchPathThread.Terminate;
FCommonThread.Terminate;
end;
procedure TfmOpenFile.actMatchPrefixExecute(Sender: TObject);
begin
FilterVisibleUnits;
end;
function TfmOpenFile.GetMatchAnywhere: Boolean;
begin
Result := tbnMatchAnywhere.Down;
end;
procedure TfmOpenFile.SetMatchAnywhere(Value: Boolean);
begin
tbnMatchAnywhere.Down := Value;
tbnMatchFromStart.Down := not Value;
end;
function TfmOpenFile.GetActivePageIndex: Integer;
begin
Result := pcUnits.ActivePageIndex;
end;
procedure TfmOpenFile.SetActivePageIndex(Value: Integer);
begin
if (Value >= 0) and (Value < pcUnits.PageCount) then
pcUnits.ActivePageIndex := Value;
end;
procedure TfmOpenFile.SetCurrentListView(const Value: TListView);
begin
FCurrentListView := Value;
if Assigned(CurrentListView) then
CurrentListView.HandleNeeded;
end;
procedure TfmOpenFile.FormShow(Sender: TObject);
begin
lvSearchPath.Columns[0].Width := FFileColumnWidth;
CopyColumns(lvSearchPath);
ResizeListViewColumns;
tabSearchPathShow(tabSearchPath);
InitializeFileTypes(FInitialFileType);
PostMessage(Handle, UM_REFRESHLIST, 0, 0);
end;
procedure TfmOpenFile.FileListDoubleClick(Sender: TObject);
begin
btnOK.Click;
end;
procedure TfmOpenFile.pcUnitsChange(Sender: TObject);
begin
Settings.LastTabIndex := pcUnits.ActivePageIndex;
FilterVisibleUnits;
PostMessage(Handle, UM_REFRESHLIST, 0, 0);
end;
procedure TfmOpenFile.pcUnitsResize(Sender: TObject);
begin
ResizeListViewColumns;
end;
procedure TfmOpenFile.ResizeListViewColumns;
begin
if Assigned(CurrentListView) then
ListViewResizeColumn(CurrentListView, 1);
end;
procedure TfmOpenFile.cbxTypeChange(Sender: TObject);
begin
AvailableFiles.FileExtension := CurrentFileType.Extensions;
AvailableFiles.SearchPaths := CurrentFileType.Paths;
if not CurrentFileType.CustomDirectories then
AvailableFiles.SearchPaths.Clear;
AvailableFiles.RecursiveDirSearch := CurrentFileType.Recursive;
AvailableFiles.Execute;
FilterVisibleUnits;
end;
procedure TfmOpenFile.actConfigExecute(Sender: TObject);
begin
if TfmOpenFileConfig.ExecuteWithSettings(Settings) then
InitializeFromSettings;
end;
procedure TfmOpenFile.tabSearchPathShow(Sender: TObject);
begin
CurrentListView := lvSearchPath;
FCurrentFilePaths := AvailableFiles.SearchPathFiles;
end;
procedure TfmOpenFile.tabProjectShow(Sender: TObject);
begin
CurrentListView := lvProjects;
FCurrentFilePaths := AvailableFiles.ProjectFiles;
end;
procedure TfmOpenFile.tabCommonShow(Sender: TObject);
begin
CurrentListView := lvCommon;
FCurrentFilePaths := AvailableFiles.CommonFiles;
end;
procedure TfmOpenFile.tabFavoriteShow(Sender: TObject);
begin
CurrentListView := lvFavorite;
if cbxType.ItemIndex = -1 then
FCurrentFilePaths := nil
else
FCurrentFilePaths := CurrentFileType.Favorites;
end;
procedure TfmOpenFile.tabRecentShow(Sender: TObject);
begin
CurrentListView := lvRecent;
if cbxType.ItemIndex = -1 then
FCurrentFilePaths := nil
else
FCurrentFilePaths := CurrentFileType.RecentFiles;
end;
procedure TfmOpenFile.actOpenFileExecute(Sender: TObject);
var
i: Integer;
Dlg: TOpenDialog;
FType: TFileType;
begin
Dlg := TOpenDialog.Create(nil);
try
for i := 0 to cbxType.Items.Count - 1 do
begin
FType := FileType(i);
Dlg.Filter := Dlg.Filter + FType.FileTypeName + ' (' + FType.Extensions + ')|' + FType.Extensions + '|';
end;
Dlg.Filter := Dlg.Filter + 'All Files(' +AllFilesWildCard+ ')|' + AllFilesWildCard;
Dlg.FilterIndex := cbxType.ItemIndex + 1;
if Dlg.Execute then
DoOpenFile(Dlg.FileName);
finally
FreeAndNil(Dlg);
end;
end;
procedure TfmOpenFile.DoOpenFile(const AFileName: string);
begin
Self.Hide;
GxOtaOpenFileOrForm(AFileName);
ModalResult := mrOK;
end;
function TfmOpenFile.ConfigurationKey: string;
begin
Result := 'OpenFile';
end;
procedure TfmOpenFile.CopyColumns(Source: TListView);
begin
Assert(Assigned(Source));
if Source <> lvSearchPath then
lvSearchPath.Columns.Assign(Source.Columns);
if Source <> lvFavorite then
lvFavorite.Columns.Assign(Source.Columns);
if Source <> lvCommon then
lvCommon.Columns.Assign(Source.Columns);
if Source <> lvProjects then
lvProjects.Columns.Assign(Source.Columns);
if Source <> lvRecent then
lvRecent.Columns.Assign(Source.Columns);
end;
function TfmOpenFile.CurrentFileType: TFileType;
begin
Result := nil;
if cbxType.ItemIndex >= 0 then
Result := FileType(cbxType.ItemIndex);
end;
procedure TfmOpenFile.UMFilterNextBlock(var Msg: TMessage);
begin
FilterVisibleUnitsBlockwise(250); // Do Filtering in 250ms Chunks to keep form useable
end;
// This is a hack to force the column 0 headers on hidden tabs to repaint
procedure TfmOpenFile.UMRefreshList(var Msg: TMessage);
begin
if Assigned(CurrentListView) then
CurrentListView.Width := CurrentListView.Width - 1;
end;
procedure TfmOpenFile.AddFavoriteFile(const AFileName: string);
begin
if Trim(AFileName) <> '' then
EnsureStringInList(CurrentFileType.Favorites, AFileName);
end;
procedure TfmOpenFile.actHelpExecute(Sender: TObject);
begin
GxContextHelp(Self, 46);
end;
function TfmOpenFile.MakeFileName(Item: TListItem): string;
begin
Assert(Assigned(Item));
Result := AddSlash(Item.SubItems[0]) + Item.Caption + Item.SubItems[1];
end;
procedure TfmOpenFile.actAddToFavoritesExecute(Sender: TObject);
var
i: Integer;
begin
for i := 0 to CurrentListView.Items.Count - 1 do
if CurrentListView.Items[i].Selected then
AddFavoriteFile(MakeFileName(CurrentListView.Items[i]));
end;
procedure TfmOpenFile.actFavAddToFavoritesExecute(Sender: TObject);
var
i: Integer;
begin
if OpenDialog.Execute then
begin
for i := 0 to OpenDialog.Files.Count - 1 do
AddFavoriteFile(OpenDialog.Files[i]);
end;
FilterVisibleUnits;
end;
procedure TfmOpenFile.actFavDeleteFromFavoritesExecute(Sender: TObject);
var
i: Integer;
begin
for i := lvFavorite.Items.Count - 1 downto 0 do
if lvFavorite.Items[i].Selected then
DeleteFromFavorites(lvFavorite.Items[i]);
end;
procedure TfmOpenFile.actClearRecentListExecute(Sender: TObject);
begin
CurrentFileType.RecentFiles.Clear;
lvRecent.Items.Clear;
end;
function TfmOpenFile.Settings: TOpenFileSettings;
begin
Assert(Assigned(OpenFileExpert));
Assert(Assigned(OpenFileExpert.Settings));
Result := OpenFileExpert.Settings;
end;
procedure TfmOpenFile.InitializeFromSettings;
var
SelectedFileType: string;
begin
SelectedFileType := '';
if cbxType.ItemIndex > -1 then
SelectedFileType := cbxType.Items[cbxType.ItemIndex];
InitializeFileTypes(SelectedFileType);
MatchAnywhere := Settings.MatchAnywhere;
end;
procedure TfmOpenFile.LoadSettings;
var
GExSettings: TGExpertsSettings;
begin
// do not localize
GExSettings := TGExpertsSettings.Create;
try
GExSettings.LoadForm(Self, ConfigurationKey + '\Window');
FFileColumnWidth := GExSettings.ReadInteger(ConfigurationKey, 'FileColumnWidth', lvSearchPath.Columns[0].Width);
finally
FreeAndNil(GExSettings);
end;
EnsureFormVisible(Self);
end;
procedure TfmOpenFile.SaveSettings;
var
GExSettings: TGExpertsSettings;
begin
// do not localize
GExSettings := TGExpertsSettings.Create;
try
GExSettings.SaveForm(Self, ConfigurationKey + '\Window');
if Assigned(CurrentListView) then
GExSettings.WriteInteger(ConfigurationKey, 'FileColumnWidth', CurrentListView.Columns[0].Width);
finally
FreeAndNil(GExSettings);
end;
end;
procedure TfmOpenFile.InitializeFileTypes(const SelectType: string);
var
TypeIndex: Integer;
i: Integer;
begin
cbxType.Items.Clear;
for i := 0 to Settings.FileTypes.Count - 1 do
cbxType.Items.Add(TFileType(Settings.FileTypes.Items[i]).FileTypeName);
TypeIndex := cbxType.Items.IndexOf(SelectType);
if TypeIndex > -1 then
cbxType.ItemIndex := TypeIndex
else if cbxType.Items.Count > 0 then
cbxType.ItemIndex := 0;
cbxType.OnChange(cbxType);
end;
function TfmOpenFile.FileTypes: TFileTypes;
begin
Assert(Assigned(Settings.FileTypes));
Result := Settings.FileTypes;
end;
function TfmOpenFile.FileType(Index: Integer): TFileType;
begin
Result := FileTypes.Items[Index];
end;
initialization
RegisterGX_Expert(TOpenFileExpert);
end.
|
unit wwUtils;
interface
Uses
Types,
wwTypes;
function Equal(A, B: TPoint): Boolean;
{ Проверяет, совпадают ли координаты переданных точек }
procedure IncPoint(var APoint: TPoint; ADir: TwwDirection);
{ Перемещает переданную точку в указанном направлении }
procedure MovePoint(FromPoint: TPoint; Dir: TwwDirection; var ToPoint: TPoint); overload;
{ Перемещает переданную точку в указанном направлении }
function MovePoint(FromPoint: TPoint; Dir: TwwDirection): TPoint; overload
{ Перемещает переданную точку в указанном направлении }
function ShiftDir(ADir: TwwDirection): TwwDirection;
{ Сдвигает направление вправо }
function ShiftDirLeft(ADir: TwwDirection): TwwDirection;
{ Сдвигает направление влево }
function InvertDir(ADir: TwwDirection): TwwDirection;
{ Возвращает направление противоположное переданному }
function CalcDir(FromPoint, ToPoint: TPoint; FavoriteDir: TwwFavoriteType):
TwwDirection;
{ Вычисляет направление от точки FromPoint на точку ToPoint с учетом приоритетного направления }
function BodySegment(FromPoint, ToPoint, ZeroPoint: TPoint): TCurve;
function CalcDistance(A, B: TPoint): Integer;
{ Вычисляет расстояние между двумя точками }
function IsTurn(A, B: TPoint): Boolean;
{ Находятся ли переданные точки на повороте }
function InvertFavorite(aFavorite: TwwFavoriteType): TwwFavoriteType;
{ Инвертирует приоритетное направление }
implementation
const
(*
Addition : array [TwwDirection, ..aY] of Integer = (
(0, 0), (0, 0), (-1, 0), (0, -1), (1, 0), (0, 1));
*)
AddPoint : array[TwwDirection] of TPoint = (
(X:0; Y:0), // dtNone,
(X:0;Y:0), // dtStop,
(X:-1; Y:0),// dtLeft,
(X:0; Y:-1),// dtUp,
(X:1; Y:0), // dtRight,
(X:0; Y:1));// dtDown
function BodySegment(FromPoint, ToPoint, ZeroPoint: TPoint): TCurve;
var
P1, P2: TPoint;
begin
if Equal(FromPoint, ToPoint) then
Result:= ctNone
else
if FromPoint.X = ToPoint.X then
begin
if FromPoint.Y > ToPoint.Y then
Result:= ctUp
else
Result:= ctDown
end
else
if FromPoint.Y = ToPoint.Y then
begin
if FromPoint.X > ToPoint.X then
Result:= ctLeft
else
Result:= ctRight
end
else
if (FromPoint.X < ToPoint.X) and (FromPoint.Y > ToPoint.Y) and
(ZeroPoint.X = ToPoint.X) and (ZeroPoint.Y = FromPoint.Y) then
Result:= ctLeftUp
else
if (FromPoint.X > ToPoint.X) and (FromPoint.Y < ToPoint.Y) and
(ZeroPoint.X = FromPoint.X) and (ZeroPoint.Y = ToPoint.Y) then
Result:= ctLeftUp
else
if (FromPoint.X < ToPoint.X) and (FromPoint.Y < ToPoint.Y) and
(ZeroPoint.X = FromPoint.X) and (ZeroPoint.Y = ToPoint.Y) then
Result:= ctRightUp
else
if (FromPoint.X > ToPoint.X) and (FromPoint.Y > ToPoint.Y) and
(ZeroPoint.X = ToPoint.X) and (ZeroPoint.Y = FromPoint.Y) then
Result:= ctRightUp
else
if (FromPoint.X < ToPoint.X) and (FromPoint.Y > ToPoint.Y) and
(ZeroPoint.X = FromPoint.X) and (ZeroPoint.Y = ToPoint.Y) then
Result:= ctRightDown
else
if (FromPoint.X > ToPoint.X) and (FromPoint.Y < ToPoint.Y) and
(ZeroPoint.X = ToPoint.X) and (ZeroPoint.Y = FromPoint.Y) then
Result:= ctRightDown
else
REsult:= ctLeftDown
end;
function Equal(A, B: TPoint): Boolean;
begin
Equal:= (A.X = B.X) and (A.Y = B.Y);
end;
function ShiftDir(ADir: TwwDirection): TwwDirection;
begin
case ADir of
dtUp: ShiftDir:= dtRight;
dtRight: ShiftDir:= dtDown;
dtDown: ShiftDir:= dtLeft;
dtLeft: ShiftDir:= dtUp;
else
ShiftDir:= ADir;
end;
end;
function ShiftDirLeft(ADir: TwwDirection): TwwDirection;
begin
case ADir of
dtUp: ShiftDirLeft:= dtLeft;
dtRight: ShiftDirLeft:= dtUp;
dtDown: ShiftDirLeft:= dtRight;
dtLeft: ShiftDirLeft:= dtDown;
else
ShiftDirLeft:= ADir;
end;
end;
function InvertDir(ADir: TwwDirection): TwwDirection;
begin
case ADir of
dtUp : InvertDir:= dtDown;
dtRight: InvertDir:= dtLeft;
dtDown : InvertDir:= dtUp;
dtLeft : InvertDir:= dtRight;
else
InvertDir:= ADir;
end;
end;
function CalcDir(FromPoint, ToPoint: TPoint; FavoriteDir: TwwFavoriteType):
TwwDirection;
var
Delta: TPoint;
i: Integer;
begin
Delta.X:= FromPoint.X - ToPoint.X;
Delta.Y:= FromPoint.Y - ToPoint.Y;
if (Delta.X <> 0) and (Delta.Y <> 0) then
begin
if FavoriteDir = ftVertical then
Delta.X:= 0
else
Delta.Y:= 0;
end; // (Delta.X <> 0) and (Delta.Y <> 0)
if Delta.X > 0 then
Delta.X:= -1
else
if Delta.X < 0 then
Delta.X:= 1;
if Delta.Y > 0 then
Delta.Y:= -1
else
if Delta.Y < 0 then
Delta.Y:= 1;
Result:= dtStop;
for i:= Ord(dtStop) to Ord(High(TwwDirection)) do
if Equal(AddPoint[TwwDirection(i)], Delta) then
begin
Result:= TwwDirection(i);
break;
end;
end;
procedure IncPoint(var APoint: TPoint; ADir: TwwDirection);
begin
APoint.X:= APoint.X + AddPoint[ADir].X;
APoint.Y:= APoint.Y + AddPoint[ADir].Y;
end;
procedure MovePoint(FromPoint: TPoint; Dir: TwwDirection; var ToPoint: TPoint);
begin
ToPoint:= FromPoint;
IncPoint(ToPoint, Dir);
end;
function MovePoint(FromPoint: TPoint; Dir: TwwDirection): TPoint;
begin
Result:= FromPoint;
IncPoint(Result, Dir);
end;
function CalcDistance(A, B: TPoint): Integer;
begin
Result:= Abs(A.X - B.X) + Abs(A.Y - B.Y);
end;
function IsTurn(A, B: TPoint): Boolean;
begin
Result:= Abs(A.X - B.X) + Abs(A.Y - B.Y) > 1;
end;
function InvertFavorite(aFavorite: TwwFavoriteType): TwwFavoriteType;
begin
if aFavorite = ftVertical then
Result:= ftHorizontal
else
Result:= ftVertical;
end;
end.
|
//******************************************************************************
//*** COMMON DELPHI FUNCTIONS ***
//*** ***
//*** (c) Massimo Magnano 11-11-2004. ***
//*** ***
//*** ***
//******************************************************************************
//
// File : MGSignals.pas REV. 1.1 (22-06-2005)
//
// Description : Implementazione di un dispatcher di messaggi (svincolato dalla VCL)
// verso delle classi registrate.
// Implements a message dispatcher (disengaged from VCL)
// to registered classes.
//
//******************************************************************************
// WARNING -TO TEST IN ExtFind (compare of method is different under Lazarus?)
unit MGSignals;
{$mode delphi}{$H+}
interface
uses MGTree16, MGList,
{$ifdef WINDOWS}
Windows,
{$endif}
Messages, Forms, Classes;
Type
TSignalMethod = function (var aMessage: TMessage):Boolean of object;
//necessario xchè TSignalMethod è una coppia di puntatori...
//necessary because TSignalMethod is a pair of pointers
PSignalMethod =^TSignalMethod;
{ TMGSignalsManager }
TMGSignalsManager = class
protected
rClients : TMGTree16;
procedure FreeClassOnList(Tag :Integer; wMessageID :Integer; wMessageList :TObject);
procedure FreeLists(Tag :Integer; wMessageID :Integer; wMessageList :TObject);
public
constructor Create;
destructor Destroy; override;
procedure Connect(ClassMethod :TSignalMethod; MessageID :Integer);
procedure Disconnect(ClassMethod :TSignalMethod; MessageID :Integer); overload;
procedure Disconnect(ClassPointer :TObject); overload;
function Signal(MessageID :Cardinal; WParam, LParam :Integer; var Handled :Boolean) :Integer; overload;
function Signal(var aMessage: TMessage) :Boolean; overload;
end;
{ TMessagesList }
PMessage =^TMessage;
TMessagesList = class (TMGList)
protected
function allocData :Pointer; override;
procedure deallocData(pData :Pointer); override;
public
function Add(aMessage :TMessage) :PMessage; overload;
end;
{ TSignalsAsyncThread }
TSignalsAsyncThread = class(TThread)
private
curMsg :PMessage;
protected
msgSignals : TMGSignalsManager;
msgList : TMessagesList;
procedure _Signal;
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
procedure Connect(ClassMethod :TSignalMethod; MessageID :Integer; Priority :Integer=0); //Priority for future use
procedure Disconnect(ClassMethod :TSignalMethod; MessageID :Integer); overload;
procedure Disconnect(ClassPointer :TObject); overload;
procedure Signal(MessageID :Cardinal; WParam, LParam :Integer); overload;
procedure Signal(aMessage: TMessage); overload;
end;
{ TMGSignals }
TMGSignals = class
protected
signals_async :TSignalsAsyncThread;
signals_sync :TMGSignalsManager;
public
constructor Create;
destructor Destroy; override;
procedure Connect(ClassMethod :TSignalMethod; MessageID :Integer);
procedure Disconnect(ClassMethod :TSignalMethod; MessageID :Integer); overload;
procedure Disconnect(ClassPointer :TObject); overload;
procedure ConnectAsync(ClassMethod :TSignalMethod; MessageID :Integer; Priority :Integer=0); //Priority for future use
procedure DisconnectAsync(ClassMethod :TSignalMethod; MessageID :Integer); overload;
procedure DisconnectAsync(ClassPointer :TObject); overload;
function Signal(MessageID :Cardinal; WParam, LParam :Integer; var Handled :Boolean) :Integer; overload;
function Signal(var aMessage: TMessage) :Boolean; overload;
end;
implementation
Type
TSignalMethodsList = class (TMGList)
protected
function allocData :Pointer; override;
procedure deallocData(pData :Pointer); override;
function CompBySignalMethod(xTag :Pointer; ptData1, ptData2 :Pointer) :Boolean;
public
function Add(AMethod :TSignalMethod) :PSignalMethod; overload;
function Find(AMethod :TSignalMethod) : Integer; overload;
function ExtFind(AMethod :TSignalMethod) : Pointer; overload;
function Delete(AMethod :TSignalMethod) :Boolean; overload;
function DeleteByClassMethod(AMethod :TSignalMethod) :Boolean;
procedure DeleteByClass(ClassPointer :TObject);
function CallAllMethods(var aMessage: TMessage) :Boolean;
end;
{ TMessagesList }
function TMessagesList.allocData: Pointer;
begin
GetMem(Result, sizeOf(TSignalMethod));
end;
procedure TMessagesList.deallocData(pData: Pointer);
begin
FreeMem(pData, sizeOf(TSignalMethod));
end;
function TMessagesList.Add(aMessage: TMessage): PMessage;
begin
Result :=Add;
Result^ :=aMessage;
end;
{ TSignalsAsyncThread }
procedure TSignalsAsyncThread._Signal;
begin
Self.msgSignals.Signal(curMsg^);
end;
procedure TSignalsAsyncThread.Execute;
begin
//Get the Message from the First Position (Head)
curMsg :=msgList.GetFirst;
while (curMsg<>Nil) do
begin
//Process the Message
//maxm: For Future use may be 3 msgSignals owned by priority
Synchronize(_Signal);
msgList.DeleteFirst;
curMsg :=msgList.GetFirst;
end;
end;
constructor TSignalsAsyncThread.Create;
begin
inherited Create(true);
msgList :=TMessagesList.Create;
end;
destructor TSignalsAsyncThread.Destroy;
begin
msgList.Free;
inherited Destroy;
end;
procedure TSignalsAsyncThread.Connect(ClassMethod: TSignalMethod; MessageID: Integer; Priority :Integer=0);
begin
Self.msgSignals.Connect(ClassMethod, MessageID);
end;
procedure TSignalsAsyncThread.Disconnect(ClassMethod: TSignalMethod; MessageID: Integer);
begin
Self.msgSignals.Disconnect(ClassMethod, MessageID);
end;
procedure TSignalsAsyncThread.Disconnect(ClassPointer: TObject);
begin
Self.msgSignals.Disconnect(ClassPointer);
end;
procedure TSignalsAsyncThread.Signal(MessageID: Cardinal; WParam, LParam: Integer);
Var
aMessage :TMessage;
begin
aMessage.Msg :=MessageID;
aMessage.WParam :=WParam;
aMessage.LParam :=LParam;
Signal(aMessage);
end;
procedure TSignalsAsyncThread.Signal(aMessage: TMessage);
begin
//Add the Message to Last Position (Tail)
msgList.Add(aMessage);
//Wakeup
Self.Resume;
end;
// =============================================================================
function TSignalMethodsList.allocData :Pointer;
begin
GetMem(Result, sizeOf(TSignalMethod));
end;
procedure TSignalMethodsList.deallocData(pData :Pointer);
begin
FreeMem(pData, sizeOf(TSignalMethod));
end;
function TSignalMethodsList.CompBySignalMethod(xTag :Pointer; ptData1, ptData2 :Pointer) :Boolean;
Var
m1,
m2 :TSignalMethod;
Message1: TMessage;
begin
m1 :=PSignalMethod(ptData1)^;
m2 :=PSignalMethod(ptData2)^;
Result := (TMethod(m1).Data = TMethod(m2).Data) and //Stessa Classe (Instanza) Same Instance
(TMethod(m1).Code = TMethod(m2).Code); //Stesso Metodo Same Method
//(@m1 = @m2); dovrebbe essere così, ma un metodo di due classi
//dello stesso tipo viene sempre considerato uguale...
//EN
//(@m1 = @m2); should be so, but a method of the same class type
//is always considered the same...
//esempio (example):
// Classe1, Classe2 :TForm;
// Classe1.func = Classe2.func because
// TForm.func = TForm.func but Classe1 is not the same of Class2
end;
function TSignalMethodsList.Add(AMethod :TSignalMethod) :PSignalMethod;
begin
Result :=ExtFind(AMethod);
if (Result=Nil)
then begin
Result :=Add;
Result^ :=AMethod;
end;
end;
function TSignalMethodsList.Find(AMethod :TSignalMethod) : Integer;
Var
auxPointer :PSignalMethod;
begin
GetMem(auxPointer, sizeOf(TSignalMethod));
auxPointer^ :=AMethod;
Result :=Find(auxPointer, 0, CompBySignalMethod);
FreeMem(auxPointer);
end;
function TSignalMethodsList.ExtFind(AMethod :TSignalMethod) : Pointer;
Var
auxPointer :PSignalMethod;
begin
GetMem(auxPointer, sizeOf(TSignalMethod));
auxPointer^ :=AMethod;
Result :=ExtFind(auxPointer, 0, CompBySignalMethod);
FreeMem(auxPointer);
end;
function TSignalMethodsList.Delete(AMethod :TSignalMethod) :Boolean;
begin
Result :=DeleteByClassMethod(AMethod);
end;
function TSignalMethodsList.DeleteByClassMethod(AMethod :TSignalMethod) :Boolean;
Var
auxPointer :PSignalMethod;
begin
GetMem(auxPointer, sizeOf(TSignalMethod));
auxPointer^ :=AMethod;
Result :=Delete(auxPointer, 0, CompBySignalMethod);
FreeMem(auxPointer);
end;
procedure TSignalMethodsList.DeleteByClass(ClassPointer :TObject);
Var
Pt :PSignalMethod;
begin
Pt :=FindFirst;
while (Pt<>Nil) do
begin
if (TMethod(Pt^).Data = ClassPointer)
then DeleteCurrent;
Pt :=FindNext;
end;
FindClose;
end;
function TSignalMethodsList.CallAllMethods(var aMessage: TMessage) :Boolean;
Var
Pt :PSignalMethod;
begin
Result :=False;
Pt :=FindFirst;
while (Pt<>Nil) do
begin
if Assigned(Pt^)
then Result :=Pt^(aMessage)
else Result :=False;
if Result
then Pt :=FindNext
else Pt :=Nil;
end;
FindClose;
end;
// =============================================================================
constructor TMGSignalsManager.Create;
begin
inherited Create;
rClients :=TMGTree16.Create;
end;
procedure TMGSignalsManager.FreeLists(Tag :Integer; wMessageID :Integer; wMessageList :TObject);
begin
if (wMessageList<>Nil)
then TSignalMethodsList(wMessageList).Free;
end;
destructor TMGSignalsManager.Destroy;
begin
rClients.Clear(0, FreeLists);
rClients.Free;
inherited Destroy;
end;
procedure TMGSignalsManager.Connect(ClassMethod :TSignalMethod; MessageID :Integer);
Var
TreeData :PMGTree16Data;
theList :TSignalMethodsList;
begin
TreeData :=rClients.Add(MessageID);
if (TreeData<>Nil) then
begin
theList :=TSignalMethodsList(TreeData^.UData);
if (theList=nil) //La Lista non esiste...
then begin
theList :=TSignalMethodsList.Create;
TreeData^.UData :=theList;
end;
theList.Add(ClassMethod);
end;
end;
procedure TMGSignalsManager.Disconnect(ClassMethod :TSignalMethod; MessageID :Integer);
Var
uMessageID :Integer;
uMessageList :TObject;
begin
if Assigned(ClassMethod) then
begin
if rClients.Find(MessageID, uMessageID, uMessageList)
then if (uMessageList<>Nil)
then begin
TSignalMethodsList(uMessageList).DeleteByClassMethod(ClassMethod);
if (TSignalMethodsList(uMessageList).Count=0)
then rClients.Del(MessageID);
end;
end;
end;
procedure TMGSignalsManager.FreeClassOnList(Tag :Integer; wMessageID :Integer; wMessageList :TObject);
Var
ClassPointer :TObject;
begin
ClassPointer :=TObject(Tag);
if (ClassPointer<>Nil) and (wMessageList<>Nil) then
begin
TSignalMethodsList(wMessageList).DeleteByClass(ClassPointer);
end;
end;
procedure TMGSignalsManager.Disconnect(ClassPointer :TObject);
begin
rClients.WalkOnTree(Integer(ClassPointer), FreeClassOnList);
end;
function TMGSignalsManager.Signal(MessageID :Cardinal; WParam, LParam :Integer; var Handled :Boolean) :Integer;
Var
aMessage :TMessage;
begin
aMessage.Msg :=MessageID;
aMessage.WParam :=WParam;
aMessage.LParam :=LParam;
Handled :=Signal(aMessage);
Result :=aMessage.Result;
end;
function TMGSignalsManager.Signal(var aMessage: TMessage):Boolean;
Var
uMessageID :Integer;
uMessageList :TObject;
begin
Result :=False;
if rClients.Find(aMessage.Msg, uMessageID, uMessageList)
then if (uMessageList<>Nil)
then Result :=TSignalMethodsList(uMessageList).CallAllMethods(aMessage);
end;
{ TMGSignals }
constructor TMGSignals.Create;
begin
signals_async :=TSignalsAsyncThread.Create;
signals_sync :=TMGSignalsManager.Create;
end;
destructor TMGSignals.Destroy;
begin
signals_async.Free;
signals_sync.Free;
inherited Destroy;
end;
procedure TMGSignals.Connect(ClassMethod: TSignalMethod; MessageID: Integer);
begin
signals_sync.Connect(ClassMethod, MessageID);
end;
procedure TMGSignals.Disconnect(ClassMethod: TSignalMethod; MessageID: Integer);
begin
signals_sync.Disconnect(ClassMethod, MessageID);
end;
procedure TMGSignals.Disconnect(ClassPointer: TObject);
begin
signals_sync.Disconnect(ClassPointer);
end;
procedure TMGSignals.ConnectAsync(ClassMethod: TSignalMethod; MessageID: Integer; Priority :Integer=0);
begin
signals_async.Connect(ClassMethod, MessageID, Priority);
end;
procedure TMGSignals.DisconnectAsync(ClassMethod: TSignalMethod; MessageID: Integer);
begin
signals_async.Disconnect(ClassMethod, MessageID);
end;
procedure TMGSignals.DisconnectAsync(ClassPointer: TObject);
begin
signals_async.Disconnect(ClassPointer);
end;
function TMGSignals.Signal(MessageID: Cardinal; WParam, LParam: Integer;
var Handled: Boolean): Integer;
begin
Result :=signals_sync.Signal(MessageID, WParam, LParam, Handled);
signals_async.Signal(MessageID, WParam, LParam);
end;
function TMGSignals.Signal(var aMessage: TMessage): Boolean;
begin
Result :=signals_sync.Signal(aMessage);
signals_async.Signal(aMessage);
end;
end.
|
// --------------------------------------------------------------
//
// For Background Playing:
//
// 1) Goto Project->Options->Version Info:
// 2) Add this key in your version list:
// Key: DPFAudioKey1
// Value: </string><key>UIBackgroundModes</key><array><string>audio</string></array><key>DPFAudioKey2</key><string>
// --------------------------------------------------------------
unit uMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
System.Math,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, DPF.iOS.BaseControl,
FMX.Platform,
iOSapi.UIKit,
Macapi.ObjectiveC,
iOSapi.CocoaTypes,
DPF.iOS.Common,
DPF.iOS.UIView,
DPF.iOS.UIToolbar,
DPF.iOS.MPVolume,
DPF.iOS.UILabel,
DPF.iOS.AVPlayer,
DPF.iOS.UISlider,
DPF.iOS.UIProgressView,
DPF.iOS.UIButton,
DPF.iOS.ApplicationManager;
type
TFAVAudioPlayer = class( TForm )
DPFUIView1: TDPFUIView;
DPFToolbar1: TDPFToolbar;
DPFMPVolume1: TDPFMPVolume;
DPFLabel1: TDPFLabel;
DPFAVPlayer1: TDPFAVPlayer;
DPFProgress1: TDPFProgress;
DPFButton1: TDPFButton;
DPFButton2: TDPFButton;
DPFButton3: TDPFButton;
DPFButton4: TDPFButton;
DPFButton5: TDPFButton;
DPFButton6: TDPFButton;
DPFButton7: TDPFButton;
procedure DPFToolbar1BarItems1Click( Sender: TObject );
procedure DPFToolbar1BarItems0Click( Sender: TObject );
procedure DPFAVPlayer1Playing( sender: TObject; currentTime: Int64; duration: int64 );
procedure FormShow( Sender: TObject );
procedure DPFButton1Click( Sender: TObject );
procedure DPFButton2Click( Sender: TObject );
procedure DPFButton3Click( Sender: TObject );
procedure DPFButton4Click( Sender: TObject );
procedure DPFButton5Click( Sender: TObject );
procedure DPFButton6Click( Sender: TObject );
procedure DPFButton7Click( Sender: TObject );
procedure DPFAVPlayer1FinishPlaying( sender: TObject; var ContinuePlayList: Boolean );
procedure DPFAVPlayer1OpenStatus( sender: TObject; const Status: Integer );
private
{ Private declarations }
protected
procedure PaintRects( const UpdateRects: array of TRectF ); override;
public
{ Public declarations }
end;
var
FAVAudioPlayer: TFAVAudioPlayer;
implementation
{$R *.fmx}
procedure TFAVAudioPlayer.DPFAVPlayer1FinishPlaying( sender: TObject; var ContinuePlayList: Boolean );
begin
DPFLabel1.Text := ' Finished Playing ';
end;
procedure TFAVAudioPlayer.DPFAVPlayer1OpenStatus( sender: TObject; const Status: Integer );
begin
DPFLabel1.Text := 'Open File Status: ' + Status.ToString( );
end;
procedure TFAVAudioPlayer.DPFAVPlayer1Playing( sender: TObject; currentTime: Int64; duration: int64 );
var
minutes1: int64;
seconds1: int64;
minutes2: int64;
seconds2: int64;
begin
minutes1 := floor( currentTime / 60 );
seconds1 := floor( currentTime - minutes1 * 60 );
minutes2 := 0;
seconds2 := 0;
if duration > 0 then
begin
minutes2 := floor( ( duration - currentTime ) / 60 );
seconds2 := floor( duration - currentTime - minutes2 * 60 );
DPFProgress1.Progress := currentTime / duration;
end
else
DPFProgress1.Progress := 0;
DPFLabel1.Text := Format( 'Time: %d:%d - Remain: %d:%d', [minutes1, seconds1, minutes2, seconds2] );
end;
procedure TFAVAudioPlayer.DPFButton1Click( Sender: TObject );
begin
PlaySystemSound( );
end;
procedure TFAVAudioPlayer.DPFButton2Click( Sender: TObject );
begin
PlaySystemSound( 1151 );
end;
procedure TFAVAudioPlayer.DPFButton3Click( Sender: TObject );
var
isPlaying, isPaused, isStopped: Boolean;
begin
DPFAVPlayer1.Open( '', '', '', '', GetAppFolder + 'Documents/music.mp3', true );
isPlaying := DPFAVPlayer1.isPlaying;
isPaused := DPFAVPlayer1.isPaused;
isStopped := DPFAVPlayer1.isStopped;
end;
procedure TFAVAudioPlayer.DPFButton4Click( Sender: TObject );
var
isPlaying, isPaused, isStopped: Boolean;
begin
DPFAVPlayer1.Pause;
isPlaying := DPFAVPlayer1.isPlaying;
isPaused := DPFAVPlayer1.isPaused;
isStopped := DPFAVPlayer1.isStopped;
end;
procedure TFAVAudioPlayer.DPFButton5Click( Sender: TObject );
var
isPlaying, isPaused, isStopped: Boolean;
begin
DPFAVPlayer1.Stop;
isPlaying := DPFAVPlayer1.isPlaying;
isPaused := DPFAVPlayer1.isPaused;
isStopped := DPFAVPlayer1.isStopped;
end;
procedure TFAVAudioPlayer.DPFButton6Click( Sender: TObject );
begin
DPFAVPlayer1.Play;
end;
procedure TFAVAudioPlayer.DPFButton7Click( Sender: TObject );
begin
DPFAVPlayer1.Close;
end;
procedure TFAVAudioPlayer.DPFToolbar1BarItems0Click( Sender: TObject );
begin
DPFAVPlayer1.Open( '', '', '', '', GetAppFolder + 'Documents/music.mp3', true );
DPFAVPlayer1.isPlaying;
end;
procedure TFAVAudioPlayer.DPFToolbar1BarItems1Click( Sender: TObject );
begin
// DPFAVPlayer1.Open('', '', '', '', 'http://webradio.antennevorarlberg.at:80/classicrock', true );
DPFAVPlayer1.Open( '', '', '', '', 'http://www.ifilmtv.ir//Media/20131104/1311040715557500_.mp3', true );
end;
procedure TFAVAudioPlayer.FormShow( Sender: TObject );
begin
{ }
end;
procedure TFAVAudioPlayer.PaintRects( const UpdateRects: array of TRectF );
begin
{ }
end;
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StEclpse.pas 4.04 *}
{*********************************************************}
{* SysTools: Lunar/Solar Eclipses *}
{*********************************************************}
{$I StDefine.inc}
{ ************************************************************** }
{ Sources: }
{ 1. Astronomical Algorithms, Jean Meeus, Willmann-Bell, 1991. }
{ }
{ 2. Planetary and Lunar Coordinates (1984-2000), U.S. Govt, }
{ 1983. }
{ }
{ 3. Supplement to the American Ephemeris and Nautical Almanac,}
{ U.S. Govt, 1964. }
{ }
{ 4. MPO96-98 source files, Brian D. Warner, 1995-98. }
{ }
{ ************************************************************** }
unit StEclpse;
interface
uses
Math, StBase, StList, StDate, StAstro, StMath;
type
TStEclipseType = (etLunarPenumbral, etLunarPartial, etLunarTotal,
etSolarPartial, etSolarAnnular, etSolarTotal,
etSolarAnnularTotal);
TStHemisphereType = (htNone, htNorthern, htSouthern);
TStContactTimes = packed record
UT1, {start of lunar penumbral phase}
UT2, {end of lunar penumbral phase}
FirstContact, {start of partial eclipse}
SecondContact, {start of totality}
MidEclipse, {mid-eclipse}
ThirdContact, {end of totality}
FourthContact : TDateTime; {end of partial phase}
end;
TStLongLat = packed record
JD : TDateTime;
Longitude,
Latitude,
Duration : Double;
end;
PStLongLat = ^TStLongLat;
TStEclipseRecord = packed record
EType : TStEclipseType; {type of Eclipse}
Magnitude : Double; {magnitude of eclipse}
Hemisphere : TStHemisphereType; {favored hemisphere - solar}
LContacts : TStContactTimes; {Universal Times of critical points}
{ in lunar eclipses}
Path : TStList; {longitude/latitude of moon's shadow}
end; { during solar eclipse}
PStEclipseRecord = ^TStEclipseRecord;
TStBesselianRecord = packed record
JD : TDateTime;
Delta,
Angle,
XAxis,
YAxis,
L1,
L2 : Double;
end;
TStEclipses = class(TStList)
{.Z+}
protected {private}
FBesselianElements : array[1..25] of TStBesselianRecord;
F0,
FUPrime,
FDPrime : Double;
function GetEclipse(Idx : Integer) : PStEclipseRecord;
procedure CentralEclipseTime(JD, K, J2,
SunAnom, MoonAnom,
ArgLat, AscNode, EFac : Double;
var F1, A1, CentralTime : Double);
procedure CheckForEclipse(K : Double);
procedure TotalLunarEclipse(CentralJD, MoonAnom, Mu,
PMag, UMag, Gamma : Double);
procedure PartialLunarEclipse(CentralJD, MoonAnom, Mu,
PMag, UMag, Gamma : Double);
procedure PenumbralLunarEclipse(CentralJD, MoonAnom, Mu,
PMag, UMag, Gamma : Double);
procedure GetBesselianElements(CentralJD : Double);
procedure GetShadowPath(I1, I2 : Integer; Path : TStList);
procedure NonPartialSolarEclipse(CentralJD, Mu, Gamma : Double);
procedure PartialSolarEclipse(CentralJD, Mu, Gamma : Double);
{.Z-}
public
constructor Create(NodeClass : TStNodeClass);
override;
procedure FindEclipses(Year : integer);
property Eclipses[Idx : Integer] : PStEclipseRecord
read GetEclipse;
end;
implementation
procedure DisposePathData(Data : Pointer); far;
begin
Dispose(PStLongLat(Data));
end;
procedure DisposeEclipseRecord(Data : Pointer); far;
var
EcData : TStEclipseRecord;
begin
EcData := TStEclipseRecord(Data^);
if (Assigned(EcData.Path)) then
EcData.Path.Free;
Dispose(PStEclipseRecord(Data));
end;
constructor TStEclipses.Create(NodeClass : TStNodeClass);
begin
inherited Create(NodeClass);
DisposeData := DisposeEclipseRecord;
end;
function TStEclipses.GetEclipse(Idx : Integer) : PStEclipseRecord;
begin
if (Idx < 0) or (Idx > pred(Count)) then
Result := nil
else
Result := PStEclipseRecord(Items[Idx].Data);
end;
procedure TStEclipses.FindEclipses(Year : integer);
var
K,
MeanJD,
JDofFirst,
JDofLast : Double;
begin
JDofFirst := AstJulianDatePrim(Year, 1, 1, 0);
JDofLast := AstJulianDatePrim(Year, 12, 31, pred(SecondsInDay));
K := Int((Year - 2000) * 12.3685 - 1);
repeat
MeanJD := 2451550.09765 + 29.530588853 * K;
if (MeanJD < JDofFirst) then
K := K + 0.5;
until (MeanJD >= JDofFirst);
while (MeanJD < JDofLast) do begin
CheckForEclipse(K);
K := K + 0.5;
MeanJD := 2451550.09765 + 29.530588853 * K;
end;
end;
procedure TStEclipses.CentralEclipseTime(JD, K, J2,
SunAnom, MoonAnom,
ArgLat, AscNode, EFac : Double;
var F1, A1, CentralTime : Double);
{the mean error of this routine is 0.36 minutes in a test between}
{1951 through 2050 with a maximum of 1.1 - Meeus}
begin
F1 := ArgLat - (0.02665/radcor) * sin(AscNode);
A1 := (299.77/radcor)
+ (0.107408/radcor) * K
- (0.009173/radcor) * J2;
if (Frac(K) > 0.1) then
{correction at Full Moon - Lunar eclipse}
CentralTime := JD
- 0.4065 * sin(MoonAnom)
+ 0.1727 * EFac * sin(SunAnom)
else
{correction at New Moon - solar eclipse}
CentralTime := JD
- 0.4075 * sin(MoonAnom)
+ 0.1721 * EFac * sin(SunAnom);
CentralTime := CentralTime
+ 0.0161 * sin(2 * MoonAnom)
- 0.0097 * sin(2 * F1)
+ 0.0073 * sin(MoonAnom - SunAnom) * EFac
- 0.0050 * sin(MoonAnom + SunAnom) * EFac
- 0.0023 * sin(MoonAnom - 2*F1)
+ 0.0021 * sin(2*SunAnom) * EFac
+ 0.0012 * sin(MoonAnom + 2*F1)
+ 0.0006 * sin(2*MoonAnom + SunAnom) * EFac
- 0.0004 * sin(3*MoonAnom)
- 0.0003 * sin(SunAnom + 2*F1) * EFac
+ 0.0003 * sin(A1)
- 0.0002 * sin(SunAnom - 2*F1) * EFac
- 0.0002 * sin(2*MoonAnom - SunAnom) * EFac
- 0.0002 * sin(AscNode);
end;
procedure TStEclipses.CheckForEclipse(K : Double);
var
MeanJD,
J1, J2, J3,
PMag, UMag,
CentralJD,
SunAnom,
MoonAnom,
ArgLat,
AscNode,
EFac,
DeltaT,
F1, A1,
P, Q, W,
Gamma, Mu : Double;
begin
{compute Julian Centuries}
J1 := K / 1236.85;
J2 := Sqr(J1);
J3 := J2 * J1;
{mean Julian Date for phase}
MeanJD := 2451550.09765
+ 29.530588853 * K
+ 0.0001337 * J2
- 0.000000150 * J3
+ 0.00000000073 * J2 * J2;
{solar mean anomaly}
SunAnom := 2.5534
+ 29.1053569 * K
- 0.0000218 * J2
- 0.00000011 * J3;
SunAnom := Frac(SunAnom / 360.0) * 360;
if (SunAnom < 0) then
SunAnom := SunAnom + 360.0;
{lunar mean anomaly}
MoonAnom := 201.5643
+ 385.81693528 * K
+ 0.0107438 * J2
+ 0.00001239 * J3
- 0.000000058 * J2 * J2;
MoonAnom := Frac(MoonAnom / 360.0) * 360;
if (MoonAnom < 0) then
MoonAnom := MoonAnom + 360.0;
{lunar argument of latitude}
ArgLat := 160.7108
+ 390.67050274 * K
- 0.0016341 * J2
- 0.00000227 * J3
+ 0.000000011 * J2 * J2;
ArgLat := Frac(ArgLat / 360.0) * 360;
if (ArgLat < 0) then
ArgLat := ArgLat + 360.0;
{lunar ascending node}
AscNode := 124.7746
- 1.56375580 * K
+ 0.0020691 * J2
+ 0.00000215 * J3;
AscNode := Frac(AscNode / 360.0) * 360;
if (AscNode < 0) then
AscNode := AscNode + 360.0;
{convert to radians}
SunAnom := SunAnom/radcor;
MoonAnom := MoonAnom/radcor;
ArgLat := ArgLat/radcor;
AscNode := AscNode/radcor;
{correction factor}
EFac := 1.0 - 0.002516 * J1 - 0.0000074 * J2;
{if AscNode > 21 deg. from 0 or 180 then no eclipse}
if (abs(sin(ArgLat)) > (sin(21.0/radcor))) then Exit;
{there is probably an eclipse - what kind? when?}
CentralEclipseTime(MeanJD, K, J2, SunAnom, MoonAnom,
ArgLat, AscNode, EFac,
F1, A1, CentralJD);
{Central JD is in Dynamical Time. Sun/Moon Positions are based on UT}
{An APPROXIMATE conversion is made to UT. This has limited accuracy}
DeltaT := (-15 + (sqr(CentralJD - 2382148) / 41048480)) / 86400;
CentralJD := CentralJD - DeltaT;
P := 0.2070 * sin(SunAnom) * EFac
+ 0.0024 * sin(2*SunAnom) * EFac
- 0.0392 * sin(MoonAnom)
+ 0.0116 * sin(2*MoonAnom)
- 0.0073 * sin(SunAnom + MoonAnom) * EFac
+ 0.0067 * sin(MoonAnom - SunAnom) * EFac
+ 0.0118 * sin(2*F1);
Q := 5.2207
- 0.0048 * cos(SunAnom) * EFac
+ 0.0020 * cos(2*SunAnom) * EFac
- 0.3299 * cos(MoonAnom)
- 0.0060 * cos(SunAnom + MoonAnom) * EFac
+ 0.0041 * cos(MoonAnom - SunAnom) * EFac;
W := abs(cos(F1));
Gamma := (P * cos(F1) + Q * sin(F1)) * (1 - 0.0048 * W);
Mu := 0.0059
+ 0.0046 * cos(SunAnom) * EFac
- 0.0182 * cos(MoonAnom)
+ 0.0004 * cos(2*MoonAnom)
- 0.0005 * cos(SunAnom + MoonAnom);
if (Frac(abs(K)) > 0.1) then begin
{Check for Lunar Eclipse possibilities}
PMag := (1.5573 + Mu - abs(Gamma)) / 0.5450;
UMag := (1.0128 - Mu - abs(Gamma)) / 0.5450;
if (UMag >= 1.0) then
TotalLunarEclipse(CentralJD, MoonAnom, Mu, PMag, UMag, Gamma)
else if (UMag > 0) then
PartialLunarEclipse(CentralJD, MoonAnom, Mu, PMag, UMag, Gamma)
else if ((UMag < 0) and (PMag > 0)) then
PenumbralLunarEclipse(CentralJD, MoonAnom, Mu, PMag, UMag, Gamma);
end else begin
{Check for Solar Eclipse possibilities}
{
Non-partial eclipses
--------------------
central Axis of moon's umbral shadow touches earth's surface
Can be total, annular, or both
non-central Axis of moon's umbral shadow does not touch earth's surface
Eclipse is usually partial but can be one of possibilities
for central eclipse if very near one of the earth's poles
Partial eclipses
----------------
partial None of the moon's umbral shadow touches the earth's surface
}
if (abs(Gamma) <= (0.9972 + abs(Mu))) then
NonPartialSolarEclipse(CentralJD, Mu, Gamma)
else begin
if (abs(Gamma) < 1.5433 + Mu) then
PartialSolarEclipse(CentralJD, Mu, Gamma);
end;
end;
end;
procedure TStEclipses.TotalLunarEclipse(CentralJD, MoonAnom, Mu,
PMag, UMag, Gamma : Double);
var
TLE : PStEclipseRecord;
PartialSemiDur,
TotalSemiDur,
Dbl1 : Double;
begin
New(TLE);
TLE^.Magnitude := UMag;
TLE^.Hemisphere := htNone;
TLE^.EType := etLunarTotal;
TLE^.Path := nil;
CentralJD := AJDToDateTime(CentralJD);
PartialSemiDur := 1.0128 - Mu;
TotalSemiDur := 0.4678 - Mu;
Dbl1 := 0.5458 + 0.0400 * cos(MoonAnom);
PartialSemiDur := 60/Dbl1 * sqrt(sqr(PartialSemiDur) - sqr(Gamma)) / 1440;
TotalSemiDur := 60/Dbl1 * sqrt(sqr(TotalSemiDur) - sqr(Gamma)) / 1440;
TLE^.LContacts.FirstContact := CentralJD - PartialSemiDur;
TLE^.LContacts.SecondContact := CentralJD - TotalSemiDur;
TLE^.LContacts.MidEclipse := CentralJD;
TLE^.LContacts.ThirdContact := CentralJD + TotalSemiDur;
TLE^.LContacts.FourthContact := CentralJD + PartialSemiDur;
PartialSemiDur := 60/Dbl1 * sqrt(sqr(1.5573 + Mu) - sqr(Gamma)) / 1440;
TLE^.LContacts.UT1 := CentralJD - PartialSemiDur;
TLE^.LContacts.UT2 := CentralJD + PartialSemiDur;
Self.Append(TLE);
end;
procedure TStEclipses.PartialLunarEclipse(CentralJD, MoonAnom, Mu,
PMag, UMag, Gamma : Double);
var
TLE : PStEclipseRecord;
PartialSemiDur,
Dbl1 : Double;
begin
New(TLE);
TLE^.Magnitude := UMag;
TLE^.Hemisphere := htNone;
TLE^.EType := etLunarPartial;
TLE^.Path := nil;
CentralJD := AJDToDateTime(CentralJD);
PartialSemiDur := 1.0128 - Mu;
Dbl1 := 0.5458 + 0.0400 * cos(MoonAnom);
PartialSemiDur := 60/Dbl1 * sqrt(sqr(PartialSemiDur) - sqr(Gamma)) / 1440;
TLE^.LContacts.FirstContact := CentralJD - PartialSemiDur;
TLE^.LContacts.SecondContact := 0;
TLE^.LContacts.MidEclipse := CentralJD;
TLE^.LContacts.ThirdContact := 0;
TLE^.LContacts.FourthContact := CentralJD + PartialSemiDur;
PartialSemiDur := 60/Dbl1 * sqrt(sqr(1.5573 + Mu) - sqr(Gamma)) / 1440;
TLE^.LContacts.UT1 := CentralJD - PartialSemiDur;
TLE^.LContacts.UT2 := CentralJD + PartialSemiDur;
Self.Append(TLE);
end;
procedure TStEclipses.PenumbralLunarEclipse(CentralJD, MoonAnom, Mu,
PMag, UMag, Gamma : Double);
var
TLE : PStEclipseRecord;
PartialSemiDur,
Dbl1 : Double;
begin
New(TLE);
TLE^.Magnitude := PMag;
TLE^.Hemisphere := htNone;
TLE^.EType := etLunarPenumbral;
TLE^.Path := nil;
CentralJD := AJDToDateTime(CentralJD);
TLE^.LContacts.FirstContact := 0;
TLE^.LContacts.SecondContact := 0;
TLE^.LContacts.MidEclipse := CentralJD;
TLE^.LContacts.ThirdContact := 0;
TLE^.LContacts.FourthContact := 0;
Dbl1 := 0.5458 + 0.0400 * cos(MoonAnom);
PartialSemiDur := 60/Dbl1 * sqrt(sqr(1.5573 + Mu) - sqr(Gamma)) / 1440;
TLE^.LContacts.UT1 := CentralJD - PartialSemiDur;
TLE^.LContacts.UT2 := CentralJD + PartialSemiDur;
Self.Append(TLE);
end;
procedure TStEclipses.GetBesselianElements(CentralJD : Double);
var
I,
Mins : Integer;
CurJD,
SidTime,
SunDist,
MoonDist,
DistRatio,
Alpha,
Theta,
Sun1,
Sun2,
Moon1,
Moon2,
Dbl3,
F1, F2 : Double;
DTRec : TStDateTimeRec;
SunXYZ : TStSunXYZRec;
Sun : TStPosRec;
Moon : TStMoonPosRec;
begin
{compute BesselianElements every 10 minutes starting 2 hours prior to CentralJD}
{but forcing positions to be at multiple of ten minutes}
for I := 1 to 25 do begin
CurJD := CentralJD + ((I-13) * (10/1440));
DTRec.D := AstJulianDateToStDate(CurJD, True);
if ((Frac(CurJD) + 0.5) >= 1) then
Mins := Trunc(((Frac(CurJD) + 0.5)-1) * 1440)
else
Mins := Trunc((Frac(CurJD) + 0.5) * 1440);
{changed because, for example, both 25 and 35 rounded to 30}
Mins := ((Mins + 5) div 10) * 10;
if (Mins = 1440) then
Mins := 0;
DTRec.T := Mins * 60;
SidTime := SiderealTime(DTRec) / radcor;
SunXYZ := SunPosPrim(DTRec);
Sun := SunPos(DTRec);
Moon := MoonPos(DTRec);
Sun1 := Sun.RA/radcor;
Sun2 := Sun.DC/radcor;
Moon1 := Moon.RA/radcor;
Moon2 := Moon.DC/radcor;
FBesselianElements[I].JD := StDateToDateTime(DTRec.D)
+ StTimeToDateTime(DTRec.T);
SunDist := 1.0 / sin(8.794/SunXYZ.RV/3600.0/radcor);
MoonDist := 1.0 / sin(Moon.Plx/radcor);
DistRatio := MoonDist / SunDist;
Theta := DistRatio/cos(Sun2) * cos(Moon2) * (Moon1 - Sun1);
Theta := Theta/(1.0-DistRatio);
Alpha := Sun1 - Theta;
Theta := DistRatio/(1.0 - DistRatio) * (Moon2 - Sun2);
FBesselianElements[I].Delta := Sun2 - Theta;
FBesselianElements[I].Angle := SidTime - Alpha;
FBesselianElements[I].XAxis := MoonDist * cos(Moon2) * (sin(Moon1 - Alpha));
Dbl3 := FBesselianElements[I].Delta;
FBesselianElements[I].YAxis := MoonDist * (sin(Moon2) * cos(Dbl3)
- cos(Moon2) * sin(Dbl3) * cos(Moon1 - Alpha));
Theta := DistRatio * SunXYZ.RV;
Theta := SunXYZ.RV - Theta;
F1 := StInvSin(0.004664012/Theta);
F2 := StInvSin(0.004640787/Theta);
Theta := MoonDist * (sin(Moon2) * sin(Dbl3) + cos(Moon2)
* cos(Dbl3) * cos(Moon1 - Alpha));
FBesselianElements[I].L1 := (Theta + 0.272453/sin(F1)) * StTan(F1);
FBesselianElements[I].L2 := (Theta - 0.272453/sin(F2)) * StTan(F2);
if (I = 13) then
F0 := StTan(F2);
if (I = 16) then begin
FUPrime := FBesselianElements[16].Angle - FBesselianElements[10].Angle;
FDPrime := FBesselianElements[16].Delta - FBesselianElements[10].Delta;
end;
end;
end;
procedure TStEclipses.GetShadowPath(I1, I2 : Integer; Path : TStList);
var
J,
I3, I4,
I5, I6 : integer;
Delta,
Dbl1,
Dbl2,
P1,
XAxis,
YAxis,
Eta,
R1, R2,
D1, D2,
D3, D4,
V3, V4,
V5, V6, V7,
XPrime,
YPrime : Double;
Position : PStLongLat;
begin
for J := I1 to I2 do begin
Eta := 0.00669454;
Delta := FBesselianElements[J].Delta;
XAxis := FBesselianElements[J].XAxis;
YAxis := FBesselianElements[J].YAxis;
R1 := sqrt(1.0 - Eta * sqr(cos(Delta)));
R2 := sqrt(1.0 - Eta * sqr(sin(Delta)));
D1 := sin(Delta) / R1;
D2 := sqrt(1.0 - Eta) * cos(Delta) / R1;
D3 := Eta * sin(Delta) * cos(Delta) / R1 / R2;
D4 := sqrt(1.0 - Eta) / R1 / R2;
V3 := YAxis / R1;
V4 := sqrt(1.0 - sqr(XAxis) - sqr(V3));
V5 := R2 * (V4 * D4 - V3 * D3);
V6 := FUPrime * (-YAxis * sin(Delta) + V5 * cos(Delta));
V7 := FUPrime * XAxis * sin(Delta) - FDPrime * V5;
if ((I2-I1) div 2) >= 4 then begin
I3 := (I2-I1) div 2;
I4 := I1 + I3;
I5 := I4 - 3;
I6 := I4 + 3;
XPrime := FBesselianElements[I6].XAxis
- FBesselianElements[I5].XAxis;
YPrime := FBesselianElements[I6].YAxis
- FBesselianElements[I5].YAxis;
end else begin
XPrime := (FBesselianElements[J+1].XAxis -
FBesselianElements[J-1].XAxis) * 3;
YPrime := (FBesselianElements[J+1].YAxis -
FBesselianElements[J-1].YAxis) * 3;
end;
New(Position);
Dbl1 := sqrt(sqr(XPrime - V6) + sqr(YPrime - V7));
Position^.JD := FBesselianElements[J].JD;
Dbl2 := (FBesselianElements[J].L2 - V5 * F0) / Dbl1;
Dbl2 := abs(Dbl2 * 120);
Position^.Duration := int(Dbl2) + frac(Dbl2) * 0.6;
Dbl1 := -V3 * D1 + V4 * D2;
P1 := StInvTan2(Dbl1, XAxis);
Dbl2 := (FBesselianElements[J].Angle - P1) * radcor;
Dbl2 := frac(Dbl2 / 360.0) * 360;
if (Dbl2 < 0) then
Dbl2 := Dbl2 + 360.0;
if (Dbl2 > 180.0) and (Dbl2 < 360.0) then
Dbl2 := Dbl2 - 360.0;
Position^.Longitude := Dbl2;
Dbl1 := StInvSin(V3 * D2 + V4 * D1);
Dbl2 := ArcTan(1.003364 * StTan(Dbl1)) * radcor;
Position^.Latitude := Dbl2;
Path.Append(Position);
end;
end;
procedure TStEclipses.NonPartialSolarEclipse(CentralJD, Mu, Gamma : Double);
var
SolEc : PStEclipseRecord;
I1, I2 : Integer;
begin
New(SolEc);
if (Mu < 0) then
SolEc^.EType := etSolarTotal
else if (Mu > 0.0047) then
SolEc^.EType := etSolarAnnular
else begin
if (Mu < (0.00464 * sqrt(1 - sqr(Gamma)))) then
SolEc^.EType := etSolarAnnularTotal
else
SolEc^.EType := etSolarTotal;
end;
SolEc^.Magnitude := -1;
if (Gamma > 0) then
SolEc^.Hemisphere := htNorthern
else
SolEc^.Hemisphere := htSouthern;
FillChar(SolEc^.LContacts, SizeOf(TStContactTimes), #0);
SolEc^.LContacts.MidEclipse := AJDtoDateTime(CentralJD);
GetBesselianElements(CentralJD);
{find limits - then go one step inside at each end}
I1 := 1;
while (sqr(FBesselianElements[I1].XAxis) +
sqr(FBesselianElements[I1].YAxis) >= 1.0) and (I1 < 25) do
Inc(I1);
Inc(I1);
I2 := I1;
repeat
if (I2 < 25) then begin
if (sqr(FBesselianElements[I2+1].XAxis) +
sqr(FBesselianElements[I2+1].YAxis) < 1) then
Inc(I2)
else
break;
end;
until (sqr(FBesselianElements[I2].XAxis) +
sqr(FBesselianElements[I2].YAxis) >= 1) or (I2 >= 25);
Dec(I2);
{this test accounts for non-central eclipses, i.e., those that are total}
{and/or annular but the axis of the moon's shadow does not touch the earth}
if (I1 <> I2) and (I1 < 26) and (I2 < 26) then begin
SolEc^.Path := TStList.Create(TStListNode);
SolEc^.Path.DisposeData := DisposePathData;
GetShadowPath(I1, I2, SolEc^.Path);
end else
SolEc^.Path := nil;
Self.Append(SolEc);
end;
procedure TStEclipses.PartialSolarEclipse(CentralJD, Mu, Gamma : Double);
var
SolEc : PStEclipseRecord;
begin
New(SolEc);
SolEc^.EType := etSolarPartial;
SolEc^.Magnitude := (1.5433 + Mu - abs(Gamma)) / (0.5461 + 2*Mu);
if (Gamma > 0) then
SolEc^.Hemisphere := htNorthern
else
SolEc^.Hemisphere := htSouthern;
FillChar(SolEc^.LContacts, SizeOf(TStContactTimes), #0);
SolEc^.LContacts.MidEclipse := AJDToDateTime(CentralJD);
SolEc^.Path := nil;
Self.Append(SolEc);
end;
end.
|
unit Timers;
interface
uses
Windows, Classes, Messages, TimerTypes;
type
TWindowsTicker =
class(TInterfacedObject, ITicker)
public
constructor Create;
destructor Destroy; override;
private // ITicker
function GetEnabled : boolean;
procedure SetEnabled(which : boolean);
function Count : integer;
function GetTickeable(idx : integer) : ITickeable;
procedure Attach(const which : ITickeable);
procedure Detach(const which : ITickeable);
private
fTickeables : TList;
fHandle : HWnd;
fCreated : boolean;
fEnabled : boolean;
fInterval : integer;
fCurrent : integer;
procedure AdjustInterval;
procedure CheckState;
procedure TimerProc(var msg : TMessage);
procedure CreateWndHandle(const which : array of const);
procedure CloseWndHandle(const which : array of const);
end;
implementation
uses
Threads, Forms; // >>>> Donot use forms
// TWindowsTicker
constructor TWindowsTicker.Create;
begin
inherited;
Join(CreateWndHandle, [nil]);
fTickeables := TList.Create;
end;
destructor TWindowsTicker.Destroy;
begin
SetEnabled(false);
assert(fTickeables.Count = 0);
fTickeables.Free;
Join(CloseWndHandle, [nil]);
inherited;
end;
function TWindowsTicker.GetEnabled : boolean;
begin
Result := fEnabled;
end;
procedure TWindowsTicker.SetEnabled(which : boolean);
begin
if which <> fEnabled
then
begin
fEnabled := which;
CheckState;
end;
end;
function TWindowsTicker.Count : integer;
begin
Result := fTickeables.Count;
end;
function TWindowsTicker.GetTickeable(idx : integer) : ITickeable;
begin
Result := ITickeable(fTickeables[idx]);
end;
procedure TWindowsTicker.Attach(const which : ITickeable);
begin
assert(fTickeables.IndexOf(pointer(which)) = -1);
which._AddRef;
fTickeables.Add(pointer(which));
AdjustInterval;
CheckState;
end;
procedure TWindowsTicker.Detach(const which : ITickeable);
var
idx : integer;
begin
idx := fTickeables.IndexOf(pointer(which));
assert(idx <> -1);
fTickeables.Delete(idx);
which._Release;
AdjustInterval;
CheckState;
end;
procedure TWindowsTicker.AdjustInterval; // >>>> Generalize
var
aux : integer;
i : integer;
begin
assert(fTickeables.Count > 0);
fInterval := ITickeable(fTickeables[0]).Interval;
for i := 1 to pred(fTickeables.Count) do
begin
aux := ITickeable(fTickeables[i]).Interval;
if aux < fInterval
then
begin
assert(fInterval mod aux = 0, 'Wrong interval');
fInterval := aux;
end
else assert(aux mod fInterval = 0, 'Wrong interval');
end;
end;
procedure TWindowsTicker.CheckState;
const
cResolution = 55; // >>>>
var
aux : boolean;
begin
aux := fEnabled and (fInterval > 0);
if aux <> fCreated
then
if not fCreated
then
begin
SetTimer(fHandle, integer(Self), fInterval, nil);
fCreated := true;
fCurrent := 0;
end
else
begin
KillTimer(fHandle, integer(Self));
fCreated := false;
end;
end;
procedure TWindowsTicker.TimerProc(var msg : TMessage);
var
i : integer;
aux : ITickeable;
begin
inc(fCurrent, fInterval);
for i := 0 to pred(fTickeables.Count) do
begin
aux := ITickeable(fTickeables[i]);
if fCurrent mod aux.Interval = 0
then aux.Tick(fInterval);
end;
end;
procedure TWindowsTicker.CreateWndHandle(const which : array of const);
begin
fHandle := AllocateHWnd(TimerProc);
end;
procedure TWindowsTicker.CloseWndHandle(const which : array of const);
begin
DeallocateHWnd(fHandle);
end;
end.
|
{$REGION 'Copyright (C) CMC Development Team'}
{ **************************************************************************
Copyright (C) 2015 CMC Development Team
CMC is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
CMC 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 CMC. If not, see <http://www.gnu.org/licenses/>.
************************************************************************** }
{ **************************************************************************
Additional Copyright (C) for this modul:
Chromaprint: Audio fingerprinting toolkit
Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com>
Lomont FFT: Fast Fourier Transformation
Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/
************************************************************************** }
{$ENDREGION}
{$REGION 'Notes'}
{ **************************************************************************
See CP.Chromaprint.pas for more information
************************************************************************** }
unit CP.SilenceRemover;
{$IFDEF FPC}
{$MODE delphi}
{$ENDIF}
interface
uses
Classes, SysUtils,
CP.AudioConsumer, CP.Def;
const
kSilenceWindow = SmallInt(55); // 5 ms as 11025 Hz
type
{ TMovingAverage }
TMovingAverage = class(TObject)
private
FBuffer: array of SmallInt;
FSize: integer;
FOffset: integer;
FSum: integer;
FCount: integer;
public
constructor Create(Size: integer);
destructor Destroy; override;
procedure AddValue(const x: SmallInt);
function GetAverage: SmallInt;
end;
{ TSilenceRemover }
TSilenceRemover = class(TAudioConsumer)
private
FThreshold: integer;
FStart: boolean;
FConsumer: TAudioConsumer;
FAverage: TMovingAverage;
public
property Threshold: integer read FThreshold write FThreshold;
property Consumer: TAudioConsumer read FConsumer write FConsumer;
public
constructor Create(Consumer: TAudioConsumer; Threshold: integer = 0);
destructor Destroy; override;
function Reset(Sample_Rate, NumChannels: integer): boolean;
procedure Flush;
procedure Consume(Input: TSmallintArray; AOffset: integer; Length: integer); override;
end;
implementation
{ TMovingAverage }
constructor TMovingAverage.Create(Size: integer);
var
i: integer;
begin
FSize := Size;
FOffset := 0;
FSum := 0;
FCount := 0;
SetLength(FBuffer, FSize);
for i := 0 to FSize - 1 do
begin
FBuffer[i] := 0;
end;
end;
destructor TMovingAverage.Destroy;
begin
SetLength(FBuffer, 0);
inherited Destroy;
end;
procedure TMovingAverage.AddValue(const x: SmallInt);
begin
FSum := FSum + x;
FSum := FSum - FBuffer[FOffset];
if (FCount < FSize) then
begin
Inc(FCount);
end;
FBuffer[FOffset] := x;
FOffset := (FOffset + 1) mod FSize;
end;
function TMovingAverage.GetAverage: SmallInt;
begin
if (FCount = 0) then
begin
Result := 0;
Exit;
end;
Result := FSum div FCount;
end;
{ TSilenceRemover }
constructor TSilenceRemover.Create(Consumer: TAudioConsumer; Threshold: integer);
begin
FStart := True;
FThreshold := Threshold;
FAverage := TMovingAverage.Create(kSilenceWindow);
FConsumer := Consumer;
end;
destructor TSilenceRemover.Destroy;
begin
FAverage.Free;
inherited;
end;
function TSilenceRemover.Reset(Sample_Rate, NumChannels: integer): boolean;
begin
if NumChannels <> 1 then
begin
Result := False;
Exit;
end;
FStart := True;
Result := True;
end;
procedure TSilenceRemover.Flush;
begin
{ nothing to do }
end;
procedure TSilenceRemover.Consume(Input: TSmallintArray; AOffset: integer; Length: integer);
var
offset, n: integer;
begin
offset := 0;
n := Length;
if (FStart) then
begin
while (n > 0) do
begin
FAverage.AddValue(abs(Input[offset]));
if (FAverage.GetAverage() > FThreshold) then
begin
FStart := False;
break;
end;
Inc(offset);
Dec(n);
end;
end;
if (n > 0) then
begin
FConsumer.Consume(Input, offset, Length);
end;
end;
end.
|
unit UPRT_UDP;
interface
uses
Classes, NMUDP, UPRT, UTime;
const
UDPLinkTimeout = toTypeSec or 65;
type
TPRT_UDP = class(TPRT_ABSTRACT)
protected
IP:String;
Port:Integer;
UDP:TNMUDP;
RxQue:TStringList;
toutLink:TTIMEOUTOBJ;
public
constructor Create(UDP:TNMUDP; IP:String; Port:Integer);
destructor Destroy;override;
procedure AddToRxQue(Packet:String);
function LinkTimeout:Boolean;
public // interface
function Open:HRESULT;override;
procedure Close;override;
function RxSize():Integer;override;
function Rx(var Data; MaxSize:Integer):Integer;override;
procedure Tx(const Data; DataSize:Integer);override;
function ProcessIO:Integer;override;
end;
implementation
uses
Windows;
{ TPRT_UDP }
constructor TPRT_UDP.Create(UDP: TNMUDP; IP: String; Port: Integer);
begin
Self.UDP:=UDP;
Self.IP:=IP;
Self.Port:=Port;
RxQue:=TStringList.Create;
toutLink.start(UDPLinkTimeout);
end;
destructor TPRT_UDP.Destroy;
begin
RxQue.Free;
inherited;
end;
function TPRT_UDP.Open: HRESULT;
begin
// dododo
Result:=S_OK;
end;
procedure TPRT_UDP.Close;
begin
// dododo
end;
function TPRT_UDP.ProcessIO: Integer;
begin
Result:=IO_UP or IO_TX;
if RxQue.Count>0
then Result:=Result or IO_RX;
end;
function TPRT_UDP.Rx(var Data; MaxSize: Integer): Integer;
var
S:String;
begin
Result:=0;
if RxQue.Count=0 then exit;
if @Data<>nil then
begin
S:=RxQue[0];
Result:=Length(S);
if MaxSize<Result then Result:=MaxSize;
Move(S[1],Data,Result);
end;
RxQue.Delete(0);
toutLink.start(UDPLinkTimeout);
end;
function TPRT_UDP.RxSize: Integer;
begin
if RxQue.Count>0
then Result:=Length(RxQue[0])
else Result:=0;
end;
procedure TPRT_UDP.Tx(const Data; DataSize: Integer);
var
Buf:array[0..1023] of Char;
begin
UDP.RemoteHost:=IP;
UDP.RemotePort:=Port;
if DataSize>High(Buf)+1 then DataSize:=High(Buf)+1;
Move(Data,Buf,DataSize);
UDP.SendBuffer(Buf,DataSize);
end;
procedure TPRT_UDP.AddToRxQue(Packet: String);
begin
RxQue.Add(Packet);
end;
function TPRT_UDP.LinkTimeout: Boolean;
begin
Result:=toutLink.IsSignaled();
end;
end.
|
unit PluginDefinition;
{$I Notpad_Plugin.inc}
interface
uses
Windows, Classes, Messages, SysUtils, NppPluginClass, NppPluginInc, Scintilla,
Dialogs, System.Generics.Collections, Vcl.Menus, System.Variants, IdHTTP;
type
TNppPluginEx = class(TNppPlugin)
private
FPm: TPopupMenu;
procedure AddNewMenu(ACaption: string; AFunc: Pointer);
procedure OnMenuItemClick(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
procedure commandMenuInit; override;
procedure beNotified(var notifyCode: TSCNotification);override;
end;
var
MyNppPlugin: TNppPluginEx;
implementation
uses
NppMacro, uConvOptions, IdURI, HttpSession, System.JSON;
var
uTypeConvList: TDictionary<string, string>;
function ConvType(AType: string): string;
begin
if AType = '' then
Result := '';
if not uTypeConvList.TryGetValue(AType, Result) then
Result := AType;
end;
function GetCurrentNppText: string;
var
LhWd: HWND;
LBytes: TBytes;
begin
Result := '';
LhWd := Npp_GetCurrentScintillaHandle(MyNppPlugin.NppData);
if not IsWindow(LhWd) then
Exit;
LBytes := Npp_SciGetText(LhWd);
if Length(LBytes) > 0 then
Result := TEncoding.UTF8.GetString(LBytes);
end;
procedure SetNewPageNppText(AText: string);
var
LStream: TStringStream;
begin
LStream := TStringStream.Create(AText+#0, TEncoding.UTF8);
try
Npp_FileNew(MyNppPlugin.NppHandle);
Npp_SciSetText(Npp_GetCurrentScintillaHandle(MyNppPlugin.NppData), LStream.Bytes);
finally
LStream.Free;
end;
end;
function GetCurrentNppSelectText: string;
var
LhWd: HWND;
LBytes: TBytes;
begin
Result := '';
LhWd := Npp_GetCurrentScintillaHandle(MyNppPlugin.NppData);
if not IsWindow(LhWd) then
Exit;
LBytes := Npp_SciGetSelText(LhWd);
if Length(LBytes) > 0 then
Result := TEncoding.UTF8.GetString(LBytes);
end;
procedure AppendToCurrentNppText(AText: string);
var
LStream: TStringStream;
begin
LStream := TStringStream.Create(AText+#0, TEncoding.UTF8);
try
// Npp_FileNew(MyNppPlugin.NppHandle);
Npp_SciAppedText(Npp_GetCurrentScintillaHandle(MyNppPlugin.NppData), LStream.Bytes);
finally
LStream.Free;
end;
end;
procedure DbgS(fmt: string; Args: array of const);
begin
OutputDebugString(PChar(Format(fmt, Args)));
end;
procedure DelphiConnstToGolang; cdecl;
var
LStrs, LResult: TStringList;
I: Integer;
LLine, LTempStr: string;
begin
// 新建的文件默认就是utf8
LStrs := TStringList.Create;
LResult := TStringList.Create;
try
LStrs.Text := GetCurrentNppText;
for I := 0 to LStrs.Count - 1 do
begin
LLine := LStrs[I].Trim;
if LLine.StartsWith('{$') then
Continue;
LResult.Add(LStrs[I]);
end;
LTempStr := LResult.Text.Replace('{', '/*')
.Replace('}', '*/')
.Replace('$', '0x')
.Replace(';', '');
DbgS('%s', [LTempStr]);
SetNewPageNppText(LTempStr);
finally
LResult.Free;
LStrs.Free;
end;
end;
procedure ShowPopupMenu; cdecl;
var
LP: TPoint;
begin
if Assigned(MyNppPlugin.FPm) then
begin
GetCursorPos(LP);
MyNppPlugin.FPm.Popup(LP.X, LP.Y);
end;
end;
procedure WinApiTransparentToGo; cdecl;
type
TParam = record
Name: string;
&Type: string;
var_Const: string;
end;
var
LLine: string;
function IsFunc: Boolean;
begin
Result := LLine.StartsWith('function', True);
end;
function IsProc: Boolean;
begin
Result := LLine.StartsWith('procedure', True);
end;
function CopyFuncName: string;
var
LStartIndex, LP: Integer;
begin
Result := '';
LStartIndex := -1;
if IsFunc then
LStartIndex := 8
else if IsProc then
LStartIndex := 9;
if LStartIndex = -1 then
Exit;
LP := Pos('(', LLine, LStartIndex + 1);
// 这种情况是没有参数的
if LP = 0 then
LP := Pos(';', LLine, LStartIndex + 1);
if LP > 0 then
Result := Trim(Copy(LLine, LStartIndex + 1, LP - LStartIndex - 1));
end;
function HaveParam: Boolean;
begin
Result := (LLine.IndexOf('(') > 0) and (LLine.IndexOf(')') > 0);
end;
function ParseParam: TArray<TParam>;
var
LParams: string;
LStart: Integer;
LSubPs, LSub, LSub3: TArray<string>;
LItem: TParam;
I: Integer;
begin
Result := nil;
LStart := LLine.IndexOf('(');
if LStart = -1 then
Exit;
LParams := Trim(LLine.Substring(LStart+1, LLine.IndexOf(')') - LStart - 1));
if Length(LParams) > 0 then
begin
LSubPs := LParams.Split([';']);
for I := 0 to High(LSubPs) do
begin
LItem.Name := '';
LItem.&Type := '';
LItem.var_Const := '';
LSub := Trim(LSubPs[I]).Split([':']);
if Length(LSub) >= 1 then
begin
Litem.Name := LSub[0].Trim;
LSub3 := LItem.Name.Split([' ']);
if Length(LSub3) >= 2 then
begin
LItem.Name := Trim(LSub3[1]);
LItem.var_Const := Trim(LSub3[0]);
end;
end;
if Length(LSub) >= 2 then
Litem.&Type := LSub[1].Trim;
SetLength(Result, Length(Result)+1);
if LItem.Name <> '' then
begin
if CharInSet(LItem.Name[1], ['A'..'Z']) then
LItem.Name[1] := LowerCase(LItem.Name[1])[1];
end;
Result[High(Result)] := LItem;
end;
end;
end;
function GetReturnType: string;
var
LRetP: Integer;
begin
Result := '';
if IsFunc then
begin
if HaveParam then
LRetP := Pos(')', LLine)
else LRetP := Pos(';', LLine);
if LRetP = 0 then
Exit;
Result := Copy(LLine, LRetP + 1, Pos(';', LLine, LRetP + 1) - LRetP - 1);
Result := Trim(Result.Replace(':', ''));
end;
end;
function GetDllName: string;
var
LP, LP2: Integer;
begin
Result := '';
LP := Pos('external', LLine);
if LP > 0 then
begin
Inc(LP, 8);
LP2 := Pos('name', LLine, LP + 1);
if LP2 > 0 then
Result := Trim(Copy(LLine, LP + 1, LP2 - LP - 1));
if not Result.StartsWith('''') then
Result := Result.Replace('''', '') + 'dll' //补上一个
else
Result := Result.Replace('.', '');
if Length(Result) > 0 then
if CharInSet(Result[1], ['A'..'Z']) then
Result[1] := LowerCase(Result[1])[1]
end;
end;
function GetExportRealName: string;
var
LP: Integer;
begin
Result := '';
if Pos('external', LLine) > 0 then
begin
LP := LLine.LastIndexOf('name');
if LP > 0 then
Inc(LP, 5);
Result := Trim(LLine.Substring(LP, Length(LLine) - LP - 1));
Result := Result.Replace('''', '');
end;
end;
function GetGoCodeParam(AParams: TArray<TParam>): string;
var
LItem: TParam;
I: Integer;
LCVType: string;
begin
Result := '';
if HaveParam then
begin
for I := 0 to High(AParams) do
begin
LItem := AParams[I];
if I > 0 then
Result := Result + ', ';
LCVType := ConvType(LItem.&Type);
Result := Result + LItem.Name + ' ';
if (LItem.var_Const = 'var') or (LItem.var_Const = 'const') then
Result := Result + '*';
Result := Result + LCVType;
end;
Result := Trim(Result);
end;
end;
var
LStrs: TStringList;
I, J: Integer;
LFName, LRetType, LCvRetType, LCvPType: string;
LImports, LCodeList: TStringList;
LCodeBody: string;
LItem: TParam;
LParams: TArray<TParam>;
begin
LStrs := TStringList.Create;
LImports := TStringList.Create;
LCodeList := TStringList.Create;
try
LStrs.Text := GetCurrentNppText;
for I := 0 to LStrs.Count - 1 do
begin
LLine := LStrs[I].Trim;
if LLine.StartsWith('{') or LLine.StartsWith('//') or LLine.StartsWith('}') then
Continue;
LFName := CopyFuncName;
if LFName = '' then
Continue;
DbgS('FuncName: %s', [LFName]);
LRetType := GetReturnType;
LCvRetType := ConvType(LRetType);
LParams := ParseParam;
LImports.Add(Format('_%s = %s.NewProc("%s")', [LFName, GetDllName, GetExportRealName]));
LCodeBody := Format('func %s(%s) %s', [LFName, GetGoCodeParam(LParams), LCvRetType]);
if LRetType <> '' then
LCodeBody := LCodeBody + ' ';
LCodeBody := LCodeBody + '{'#13#10;
LCodeBody := LCodeBody + ' ';
if LRetType <> '' then
LCodeBody := LCodeBody + 'r, _, _ := ';
LCodeBody := LCodeBody + '_' + LFName + '.Call(';
for J := 0 to High(LParams) do
begin
LItem := LParams[J];
if J > 0 then
LCodeBody := LCodeBody + ', ';
LCvPType := ConvType(LItem.&Type);
if LCvPType <> 'uintptr' then
begin
// pointer
if LCvPType[1] = '*' then
LCodeBody := LCodeBody + 'uintptr(unsafe.Pointer(' + LItem.Name + '))'
else
if LCvPType = 'string' then
LCodeBody := LCodeBody + 'CStr(' + LItem.Name + ')'
else if LCvPType = 'bool' then
LCodeBody := LCodeBody + 'CBool(' + LItem.Name + ')'
else LCodeBody := LCodeBody + 'uintptr(' + LItem.Name + ')';
end
else
LCodeBody := LCodeBody + LItem.Name;
end;
LCodeBody := LCodeBody + ')'#13#10;
if LRetType <> '' then
begin
LCodeBody := LCodeBody + ' return ';
if LCvRetType <> 'uintptr' then
begin
if LCvRetType = 'bool' then
LCodeBody := LCodeBody + 'r != 0'
else if LCvRetType = 'string' then
LCodeBody := LCodeBody + 'GoStr(r)'
else
LCodeBody := LCodeBody + LCvRetType + '(r)';
end
else LCodeBody := LCodeBody + 'r';
LCodeBody := LCodeBody + #13#10;
end;
LCodeBody := LCodeBody + '}';
LCodeList.Add(LCodeBody);
LCodeList.Add('');
end;
{$IFDEF DEBUG}
DbgS('Imports: %s', [LImports.Text]);
DbgS('-------------code------------', []);
DbgS('Code:%s', [LCodeList.Text]);
{$ENDIF}
SetNewPageNppText(LImports.Text + sLineBreak + LCodeList.Text);
finally
LCodeList.Free;
LImports.Free;
LStrs.Free;
end;
end;
procedure DelphiRecordToGoStruct; cdecl;
var
LStrs, LResult: TStringList;
LLine: string;
I, LP: Integer;
LStrcutName: string;
LArr: TArray<string>;
LCVType: string;
LFName, LFType: string;
LArrLen: string;
LIsArr: Boolean;
begin
LStrs := TStringList.Create;
try
LResult := TStringList.Create;
try
LStrs.Text := GetCurrentNppText;
I := 0;
while I < LStrs.Count do
begin
LLine := Trim(LStrs[I]);
if LLine.IndexOf('record') <> -1 then
begin
LStrcutName := Trim(LLine.Substring(0, LLine.IndexOf('=')));
LResult.Add(Format('type %s struct {', [LStrcutName]));
repeat
Inc(I);
LLine := Trim(LStrs[I]);
LArr := LLine.Split([':']);
if Length(LArr) >= 2 then
begin
LFName := Trim(LArr[0]);
LFType := Trim(LArr[1].Replace(';', ''));
if (LFName[1] = '_') then
LFName := Copy(LFName, 2, Length(LFName) - 1);
LFName[1] := UpCase(LFName[1]);
LArrLen := '';
// 是数组
LIsArr := LFType.StartsWith('array', True);
if LIsArr then
begin
// 静太数组
LP := LFType.IndexOf('[');
if LP > 0 then
begin
LP := LFType.LastIndexOf('.');
if LP > 0 then
begin
Inc(LP);
LArrLen := LFType.Substring(LP, LFType.IndexOfAny([' ', '-', '+']) - LP);
end;
end;
LFType := Trim(LFType.Substring(LFType.LastIndexOf('of')+3));
end;
LCVType := ConvType(LFType);
if LCVType = 'string' then
LCVType := LFType;
if LIsArr then
begin
// 静态数组
if LArrLen <> '' then
LResult.Add(Format(' %s [%s]%s', [LFName, LArrLen, LCVType]))
else
LResult.Add(Format(' %s []%s', [LFName, LCVType]));
end else
LResult.Add(Format(' %s %s', [LFName, LCVType]));
end;
until LLine.StartsWith('end', True);
LResult.Add('}');
LResult.Add('');
end;
Inc(I);
end;
SetNewPageNppText(LResult.Text);
finally
LResult.Free;
end;
finally
LStrs.Free;
end;
end;
procedure DelphiEnumToGo; cdecl;
var
LResult: TStringList;
LText, LLine: string;
LP1, LP2, I: Integer;
LName, LBody: string;
begin
LText := GetCurrentNppText;
if LText = '' then
Exit;
LResult := TStringList.Create;
try
LName := '';
LP1 := Pos('=', LText);
if LP1 > 0 then
LName := Trim(Copy(LText, 1, LP1-1));
if LName = '' then
Exit;
LP1 := Pos('(', LText);
if LP1 > 0 then
begin
LP2 := Pos(')', LText, LP1);
if LP2 > 0 then
begin
LBody := Trim(Copy(LText, LP1 + 1, LP2 - LP1 - 1));
LBody := LBody.Replace(',', sLineBreak);
LResult.Text := LBody;
for I := LResult.Count - 1 downto 0 do
begin
LLine := LResult[I].Trim;
if LLine = '' then
begin
LResult.Delete(I);
Continue;
end;
LLine[1] := UpCase(LLine[1]);
// DbgS('Line:%s', [LLine]);
LLine := ' ' + LLine;
if I = 0 then
LResult[I] := LLine + ' = iota + 0'
else
LResult[I] := LLine;
end;
LText := 'type ' + LName + ' int32' + sLineBreak + sLineBreak;
LText := LText + 'const (' + sLineBreak;
LText := LText + LResult.Text;
LText := LText + ')' + sLineBreak;
SetNewPageNppText(LText);
end;
end;
finally
LResult.Free;
end;
end;
procedure TrimSpaceAndAddDoubleQuotes; cdecl;
var
LStr, LResult: TStringList;
I: Integer;
LLine: string;
begin
LStr := TStringList.Create;
LResult := TStringList.Create;
try
LStr.Text := GetCurrentNppText;
for I := 0 to LStr.Count - 1 do
begin
LLine := Trim(LStr[I]);
if LLine = '' then
Continue;
LResult.Add('"' + LLine + '"');
end;
SetNewPageNppText(LResult.Text);
finally
LResult.Free;
LStr.Free;
end;
end;
procedure TrimSpaceAndAddSingleQuotes; cdecl;
var
LStr, LResult: TStringList;
I: Integer;
LLine: string;
begin
LStr := TStringList.Create;
LResult := TStringList.Create;
try
LStr.Text := GetCurrentNppText;
for I := 0 to LStr.Count - 1 do
begin
LLine := Trim(LStr[I]);
if LLine = '' then
Continue;
LResult.Add('''' + LLine + '''');
end;
SetNewPageNppText(LResult.Text);
finally
LResult.Free;
LStr.Free;
end;
end;
procedure StringProcess; cdecl;
var
LCurText: string;
begin
LCurText := GetCurrentNppText;
if ShowConvOptions(LCurText) then
SetNewPageNppText(LCurText);
end;
procedure GoogleTransparent; cdecl;
var
// HttpReq: IXMLHTTPRequest;
LGetURL: string;
LText, LRet: string;
LJson: TJSONValue;
begin
LText := GetCurrentNppSelectText;
if LText = '' then
Exit;
LGetURL := TIdURI.URLEncode(Format('https://translate.google.cn/translate_a/single?client=webapp' +
'&sl=zh-CN&tl=en&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt' +
'=rw&dt=rm&dt=ss&dt=t&source=bh&ssel=0&tsel=0&kc=1&tk=745385.909105&' +
'q=%s', [LText]));
try
OutputDebugString(PChar('URL:' + LGetURL));
with THttpSession.Create do
begin
try
LJson := TJSONObject.ParseJSONValue(GetText(LGetURL, []));
if Assigned(LJson) then
begin
OutputDebugString(PChar(LJson.ToString));
try
// if LJson.TryGetValue<string>('[0].[0].[0].[0]', LRet) then
// begin
// AppendToCurrentNppText(LRet);
// end;
finally
LJson.Free;
end;
end;
finally
Free;
end;
end;
// HttpReq.setRequestHeader('User-Agent', '');
// HttpReq.setRequestHeader('If-Modified-Since', '0');
// HttpReq.setRequestHeader('Accept', 'application/json');
// HttpReq.setRequestHeader('Content-Type', 'application/json');
// HttpReq.setRequestHeader('Charset', 'utf-8');
// HttpReq.setRequestHeader('Referer', 'https://translate.google.cn/m/translate?hl=zh-CN');
// HttpReq.send(EmptyStr);
// AppendToCurrentNppText(HttpReq.ResponseBody);
except
on E:Exception do
OutputDebugString(PChar('GoogleTransparent Error:' + E.message));
end;
// HttpReq := nil;
// https://translate.google.cn/translate_a/single?client=webapp&sl=zh-CN&tl=en&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&source=bh&ssel=0&tsel=0&kc=1&tk=745385.909105&q=%E9%A1%B9%E7%9B%AE%E6%80%BB%E6%95%B0
// https://translate.google.cn/translate_a/single
// client=webapp
// sl=zh-CN
// hl=zh-CN
// dt=at
end;
{ TNppPluginEx }
constructor TNppPluginEx.Create;
begin
inherited;
PluginName := '我的一些处理工具';
FPm := TPopupMenu.Create(nil);
end;
destructor TNppPluginEx.Destroy;
begin
FPm.Free;
inherited;
end;
procedure TNppPluginEx.OnMenuItemClick(Sender: TObject);
var
LProc: procedure; cdecl;
begin
@LProc := Pointer(TMenuItem(Sender).Tag);
if Assigned(@LProc) then
LProc();
end;
procedure TNppPluginEx.commandMenuInit;
begin
inherited;
AddNewMenu('Delphi常量转Go', @DelphiConnstToGolang);
AddNewMenu('Delphi Winapi翻译至Go', @WinApiTransparentToGo);
AddNewMenu('Delphi结构转Go', @DelphiRecordToGoStruct);
AddNewMenu('Delphi枚举转Go', @DelphiEnumToGo);
AddNppPluginFunc('---', nil);
// AddNewMenu('移除空行-删首尾空-添加双引号', @TrimSpaceAndAddDoubleQuotes);
// AddNewMenu('移除空行-删首尾空-添加单引号', @TrimSpaceAndAddSingleQuotes);
AddNewMenu('字符串处理', @StringProcess);
AddNppPluginFunc('----', nil);
AddNppPluginFunc('Delphi转Go工具集合', @ShowPopupMenu);
AddNewMenu('Google翻译选择文本并附加结果', @GoogleTransparent);
end;
procedure TNppPluginEx.AddNewMenu(ACaption: string; AFunc: Pointer);
var
LItem: TMenuItem;
begin
LItem := TMenuItem.Create(FPm);
LItem.Caption := ACaption;
LItem.Tag := NativeInt(AFunc);
LItem.OnClick := OnMenuItemClick;
FPm.Items.Add(LItem);
AddNppPluginFunc(PTCHAR(ACaption), AFunc);
end;
procedure TNppPluginEx.beNotified(var notifyCode: TSCNotification);
begin
inherited;
case notifyCode._nmhdr.code of
SCN_CHARADDED :;
NPPN_TBMODIFICATION :
begin
AddToolBtnOf(ShowPopupMenu, 'TOOL_SHOWDOCK');
end;
end;
end;
procedure InitConvTypeList;
begin
with uTypeConvList do
begin
Add('BOOL', 'bool');
Add('Boolean', 'bool');
Add('Integer', 'int32');
Add('Cardinal', 'uint32');
Add('DWORD', 'uint32');
Add('Pointer', 'uintptr');
Add('UINT', 'uint32');
Add('UIntPtr', 'uintptr');
Add('Longint', 'uint32');
Add('THandle', 'uintptr');
Add('Word', 'uint16');
Add('Byte', 'uint8');
Add('LPCWSTR', 'string');
Add('COLORREF', 'uint32');
Add('LPARAM', 'uintptr');
Add('WPARAM', 'uintptr');
Add('NativeInt', 'int');
Add('NativeUInt', 'uint');
Add('HINST', 'uintptr');
// Add('Int64', 'int64');
// Add('UInt64', 'uint64');
Add('PRect', '*TRect');
Add('PPoint', '*Point');
Add('PInteger', '*int32');
Add('PDWORD', '*uint32');
Add('PUINT_PTR', '*uintptr');
end;
end;
initialization
MyNppPlugin := TNppPluginEx.Create;
uTypeConvList := TDictionary<string, string>.Create;
InitConvTypeList;
finalization
uTypeConvList.Free;
MyNppPlugin.Free;
end.
|
unit uJurnal;
interface
uses
uModel, uAccount, System.Classes, System.SysUtils, System.Generics.Collections;
type
TJurnalItem = class;
TJurnal = class(TAppObject)
private
FCabang: TCabang;
FDebet: Double;
FIDTransaksi: string;
FIsPosted: Integer;
FJurnalItems: TObjectList<TJurnalItem>;
FKeterangan: string;
FKredit: Double;
FNoBukti: string;
FNoReferensi: string;
FTglBukti: TDatetime;
FTransaksi: string;
function GetDebet: Double;
function GetJurnalItems: TObjectList<TJurnalItem>;
function GetKredit: Double;
published
property Cabang: TCabang read FCabang write FCabang;
property Debet: Double read GetDebet write FDebet;
property IDTransaksi: string read FIDTransaksi write FIDTransaksi;
property IsPosted: Integer read FIsPosted write FIsPosted;
property JurnalItems: TObjectList<TJurnalItem> read GetJurnalItems write
FJurnalItems;
property Keterangan: string read FKeterangan write FKeterangan;
property Kredit: Double read GetKredit write FKredit;
property NoBukti: string read FNoBukti write FNoBukti;
property NoReferensi: string read FNoReferensi write FNoReferensi;
property TglBukti: TDatetime read FTglBukti write FTglBukti;
property Transaksi: string read FTransaksi write FTransaksi;
end;
TJurnalItem = class(TAppObjectItem)
private
FAccount: TAccount;
FDebet: Double;
FJurnal: TJurnal;
FKeterangan: string;
FKredit: Double;
public
function GetHeaderField: string; override;
procedure SetHeaderProperty(AHeaderProperty : TAppObject); override;
published
property Account: TAccount read FAccount write FAccount;
property Debet: Double read FDebet write FDebet;
property Jurnal: TJurnal read FJurnal write FJurnal;
property Kredit: Double read FKredit write FKredit;
property Keterangan: string read FKeterangan write FKeterangan;
end;
implementation
function TJurnal.GetDebet: Double;
var
I: Integer;
begin
FDebet := 0;
for I := 0 to JurnalItems.Count - 1 do
begin
FDebet := FDebet + JurnalItems[i].Debet;
end;
Result := FDebet;
end;
function TJurnal.GetJurnalItems: TObjectList<TJurnalItem>;
begin
if FJurnalItems = nil then
FJurnalItems := TObjectList<TJurnalItem>.Create;
Result := FJurnalItems;
end;
function TJurnal.GetKredit: Double;
var
I: Integer;
begin
FKredit := 0;
for I := 0 to JurnalItems.Count - 1 do
begin
FKredit := FKredit + JurnalItems[i].Kredit;
end;
Result := FKredit;
end;
function TJurnalItem.GetHeaderField: string;
begin
Result := 'Jurnal';
end;
procedure TJurnalItem.SetHeaderProperty(AHeaderProperty : TAppObject);
begin
Self.Jurnal := TJurnal(AHeaderProperty);
end;
end.
|
(**
This module contains a class to provide a key binding wizard to capture the F1 keypress
in the IDE and if unhandled do an internet search.
@Version 1.0
@Author David Hoyle
@Date 07 Apr 2016
**)
Unit KeyboardBindingInterface;
Interface
Uses
ToolsAPI,
Classes;
{$INCLUDE CompilerDefinitions.inc}
Type
(** This class imlpements the IOTAKeyboardbinding interface for handling the F1 key
press. **)
TKeybindingTemplate = Class(TNotifierObject, IOTAKeyboardBinding)
{$IFDEF D2005} Strict {$ENDIF} Private
{$IFDEF D2005} Strict {$ENDIF} Protected
Procedure ProcessKeyBinding(Const Context: IOTAKeyContext;
KeyCode: TShortcut; Var BindingResult: TKeyBindingResult);
Function GetWordAtCursor : String;
Public
Procedure BindKeyboard(Const BindingServices: IOTAKeyBindingServices);
Function GetBindingType: TBindingType;
Function GetDisplayName: String;
Function GetName: String;
End;
Implementation
Uses
SysUtils,
Dialogs,
Menus,
UtilityFunctions,
ShellAPI,
Windows,
DockableBrowserForm,
ApplicationsOptions;
{ TKeybindingTemplate }
(**
This method is an interface method of the IOTAKeyboardBinding interface and is called by
the IDE when the wizard is created and is used to add a keybinding for the F1 keypress.
@precon None.
@postcon The F1 key press is bound and provided a handler in ProcessKeyBinding.
@param BindingServices as an IOTAKeyBindingServices as a constant
**)
Procedure TKeybindingTemplate.BindKeyboard(Const BindingServices: IOTAKeyBindingServices);
Begin
BindingServices.AddKeyBinding([TextToShortcut('F1')], ProcessKeyBinding, Nil);
End;
(**
This method intercepts the F1 key and asks the IDE whether it understands the word at
the cursor. If so then the event does nothing else as the IDE will display the
IDEs help however if the IDE says it does not unstand the word at the cursor then
the search URL is used to search for help on the word in the dockable browser.
@precon None.
@postcon Either the IDe dislpays its help if it knows the word at the cursor of else
the dockable browser is displayed with a search for the word.
@param Context as an IOTAKeyContext as a constant
@param KeyCode as a TShortcut
@param BindingResult as a TKeyBindingResult as a reference
**)
Procedure TKeybindingTemplate.ProcessKeyBinding(Const Context: IOTAKeyContext;
KeyCode: TShortcut; Var BindingResult: TKeyBindingResult);
Const
strMsg = 'Your search URLs are misconfigured. Ensure there is a Search URL and that ' +
'it is checked in the list in the configuration dialogue.';
Var
strWordAtCursor : String;
boolHandled: Boolean;
Begin
strWordAtCursor := GetWordAtCursor;
If strWordAtCursor <> '' Then
Begin
boolHandled :=
(BorlandIDEServices As IOTAHelpServices).UnderstandsKeyword(strWordAtCursor);
If boolHandled Then
BindingResult := krUnhandled
Else
Begin
BindingResult := krHandled;
If (AppOptions.SearchURLIndex <= AppOptions.SearchURLs.Count - 1) And
(AppOptions.SearchURLIndex >= 0) Then
TfrmDockableBrowser.Execute(
Format(AppOptions.SearchURLs[AppOptions.SearchURLIndex], [strWordAtCursor]))
Else
MessageDlg(strMsg, mtError, [mbOK], 0);
End;
End Else
BindingResult := krUnhandled;
End;
(**
This is the GetBindingType implementation for the IOTAKeyboardBinding interface.
@precon None.
@postcon Returns that this is a partial keybinding, i.e. adds to the main keybindings.
@return a TBindingType
**)
Function TKeybindingTemplate.GetBindingType: TBindingType;
Begin
Result := btPartial;
End;
(**
This is the getDisplayName method for the IOTAKeyboardBinding interface.
@precon None.
@postcon Provides the display name for the keyboard binding which is displayed in the
options dialogue.
@return a String
**)
Function TKeybindingTemplate.GetDisplayName: String;
Begin
Result := 'IDE Help Helper Partial Keybindings';
End;
(**
This is the GetName method for the IOTAKeyboardBinding interface.
@precon None.
@postcon Provides a name of the wizard interface.
@return a String
**)
Function TKeybindingTemplate.GetName: String;
Begin
Result := 'IDE Help Helper Partial Keyboard Bindings';
End;
(**
This method returns the word underneatht the cursor position in the active editor.
This method gets the text from the editor using the utility function EditorAsString,
gets the cursor position, places the text in a string list and then checks for thr word
under the cursor position.
@precon None.
@postcon The word underneatht he cursor in the editor is returned else an empty string
is returned if the cursor is not under a word.
@return a String
**)
Function TKeybindingTemplate.GetWordAtCursor: String;
Const
strIdentChars = ['a'..'z', 'A'..'Z', '_', '0'..'9'];
Var
SE: IOTASourceEditor;
EP: TOTAEditPos;
iPosition: Integer;
sl: TStringList;
Begin
Result := '';
SE := ActiveSourceEditor;
EP := SE.EditViews[0].CursorPos;
sl := TStringList.Create;
Try
sl.Text := EditorAsString(SE);
Result := sl[Pred(EP.Line)];
iPosition := EP.Col;
If (iPosition > 0) And (Length(Result) >= iPosition) And
{$IFDEF D2009}
CharInSet(Result[iPosition], strIdentChars)
{$ELSE}
(Result[iPosition] In strIdentChars)
{$ENDIF} Then
Begin
While (iPosition > 1) And
{$IFDEF D2009}
(CharInSet(Result[Pred(iPosition)], strIdentChars))
{$ELSE}
(Result[iPosition] In strIdentChars)
{$ENDIF}
Do
Dec(iPosition);
Delete(Result, 1, Pred(iPosition));
iPosition := 1;
While {$IFDEF D2009} CharInSet(Result[iPosition], strIdentChars) {$ELSE}
Result[iPosition] In strIdentChars {$ENDIF} Do
Inc(iPosition);
Delete(Result, iPosition, Length(Result) - iPosition + 1);
If {$IFDEF D2009} CharInSet(Result[1], ['0'..'9']) {$ELSE}
Result[1] In ['0'..'9'] {$ENDIF} Then
Result := '';
End Else
Result := '';
Finally
sl.Free;
End;
End;
End.
|
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, Buttons;
type
TForm2 = class(TForm)
StringGrid1: TStringGrid;
SpeedButton1: TSpeedButton;
procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
s : String;
drawRect : TRect;
begin
if ACol = 1 then
begin
StringGrid1.Canvas.FillRect(Rect);
s := StringGrid1.Cells[ACol, ARow]; //the text in the cell
if Length(s) > 0 then //is there any text needing to be formatted?
begin
drawRect := Rect;
DrawText(StringGrid1.canvas.handle, //See http://msdn.microsoft.com/en-us/libr...(v=vs.85).aspx
Pchar(s), Length(s), drawRect,
DT_CALCRECT OR DT_WORDBREAK OR DT_LEFT ); //format the text as required, then use drawRect later as per DT_CALCRECT
if (drawRect.bottom - drawRect.top) > StringGrid1.RowHeights[ARow] then //Does the row need to be adjusted?
StringGrid1.RowHeights[ARow] := (drawRect.bottom - drawRect.top) //adjust row height
else
begin //fits in one line
drawRect.Right := Rect.Right;
StringGrid1.canvas.fillrect(drawRect);
DrawText(StringGrid1.canvas.handle,
Pchar(s), Length(s), drawRect,
DT_WORDBREAK); //how to format the text
end;
end;
end;
//DrawText(StringGrid1.Canvas.Handle, PChar(StringGrid1.Cells[aCol, aRow]), Length(StringGrid1.Cells[aCol, aRow]), Rect, DT_WORDBREAK);
end;
procedure TForm2.SpeedButton1Click(Sender: TObject);
var
i : Integer;
begin
for i := 1 to 10 do begin
StringGrid1.Cells[1,i] := 'CPF:99999999999999 Nome:asdadasdadsasdasdsadas';
StringGrid1.RowCount := i+1;
end;
end;
end.
|
unit flListView;
interface
uses
SysUtils, Classes, Controls, StdCtrls, flLabel, messages, Types;
type
TflListView = class(TflLabel)
private
FItems: TStrings;
FRowInterval: Integer;
FMaxRowCount: Integer;
FMoveInterval: Integer;
FMargin: Cardinal;
procedure SetItems(const Value: TStrings);
procedure SetRowInterval(const Value: Integer);
procedure CMTextChanged(var M: TMessage); message CM_TEXTCHANGED;
procedure SetMaxRowCount(const Value: Integer);
procedure MoveCanvas;
procedure SetMoveInterval(const Value: Integer);
function GetPaintStatus: Boolean;
procedure SetMargin(const Value: Cardinal);
protected
InMove: Boolean;
FFillBk: Boolean;
procedure Paint; override;
procedure DoTimer(Sender: TObject); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Add(const AStr: string);
procedure Clear;
procedure RepaintBk;
property InPainting: Boolean read GetPaintStatus;
published
property Items: TStrings read FItems write SetItems;
property Margin: Cardinal read FMargin write SetMargin default 0;
property MaxRowCount: Integer read FMaxRowCount write SetMaxRowCount
default 10;
property MoveInterval: Integer read FMoveInterval write SetMoveInterval
default 3;
property RowInterval: Integer read FRowInterval write SetRowInterval
default 0;
end;
implementation
uses Graphics;
procedure TflListView.Add(const AStr: string);
begin
if FItems.Count = FMaxRowCount then begin
MoveCanvas;
FItems.Clear;
end;
FItems.Add(AStr);
StartDelayDraw;
Invalidate;
end;
procedure TflListView.Clear;
begin
FItems.Clear;
FFillBk := True;
Invalidate;
end;
procedure TflListView.CMTextChanged(var M: TMessage);
begin
inherited;
FTimer.Enabled := False;
end;
constructor TflListView.Create(AOwner: TComponent);
begin
inherited;
Color := clBlack;
Width := 300;
Height := 300;
FItems := TStringList.Create;
FMaxRowCount := 10;
FMoveInterval := 3;
end;
destructor TflListView.Destroy;
begin
FItems.Free;
inherited;
end;
procedure TflListView.DoTimer(Sender: TObject);
var
S: string;
begin
S := FItems[FItems.Count - 1];
if FTmpIndex = Length(S) then begin
FTimer.Enabled := False;
Exit;
end;
Inc(FTmpIndex);
FTmpCaption := FTmpCaption + S[FTmpIndex];
Invalidate;
end;
function TflListView.GetPaintStatus: Boolean;
begin
Result := FTimer.Enabled;
end;
procedure TflListView.MoveCanvas;
var
R: TRect;
begin
with Canvas do begin
InMove := True;
Invalidate;
end;
end;
procedure TflListView.Paint;
var
i, j, X, W, Y: Integer;
S: string;
Bmp: TBitmap;
NeedTrunc: Boolean;
R, R1: TRect;
begin
if InMove then begin
//R.Top := 0; R.Bottom := 50; R.Right := 50; R.Left := 0;
R := ClientRect; R.Bottom := FMargin + MaxRowCount * 11 + FRowInterval * (MaxRowCount - 1);
R1 := R;
R.Top := R.Top - 1;
R.Bottom := R.Bottom - 1;
//Canvas.CopyMode := cmPatPaint;
for i := 1 to R.Bottom do begin
Sleep(FMoveInterval);
Canvas.CopyRect(R, Self.Canvas, R1);
end;
InMove := False;
end;
Bmp := TBitmap.Create;
Bmp.Transparent := True;
with Canvas do begin
Brush.Color := Self.Color;
//ClipRect
//if not FTimer.Enabled or (FTmpIndex = 1) or (FSmartTruncate and NeedTrunc) then
if not FTimer.Enabled or FFillBk then begin
FillRect(ClientRect);
FFillBk := False;
end;
Y := FMargin;
if not Assigned(ImageList) then Exit;
for j := 0 to FItems.Count - 1 do begin
if FTimer.Enabled and (j = FItems.Count - 1)
then S := FTmpCaption
else S := FItems[j];
W := CalcTextWidth(S);
NeedTrunc := W > Self.Width;
if SmartTruncate and NeedTrunc then begin
S := GetHoldString(S, Self.Width - CalcTextWidth('...')) + '...';
end;
X := FMargin;
if (FTimer.Enabled and ((j = FItems.Count - 1)) or (Length(FTmpCaption) = 1)) or not FTimer.Enabled then begin
for i := 1 to Length(S) do begin
Bmp.Width := 0;
Bmp.Height := 0;
ImageList.GetBitmap(Imgs[S[i]], Bmp);
Draw(X, Y, Bmp);
Inc(X, StrToInt(ImageList.Widths[Imgs[S[i]]]));
//FImageList.Draw(Canvas, FImageList.Width*i, 0, Imgs[S[i]]);
end;
end;
Inc(Y, 11 + FRowInterval);
end;
end;
Bmp.Free;
end;
procedure TflListView.RepaintBk;
begin
FFillBk := True;
Invalidate;
end;
procedure TflListView.SetItems(const Value: TStrings);
begin
FItems.Assign(Value);
end;
procedure TflListView.SetMargin(const Value: Cardinal);
begin
FMargin := Value;
Invalidate;
end;
procedure TflListView.SetMaxRowCount(const Value: Integer);
begin
FMaxRowCount := Value;
end;
procedure TflListView.SetMoveInterval(const Value: Integer);
begin
FMoveInterval := Value;
end;
procedure TflListView.SetRowInterval(const Value: Integer);
begin
FRowInterval := Value;
Invalidate;
end;
end.
|
unit LogUtils;
interface
procedure Log(AFilename: String; ALine: String); overload;
procedure Log(ALine: String); overload;
implementation
uses SysUtils;
procedure Log(ALine: String); overload;
begin
Log(ChangeFileExt(ParamStr(0), '.log'), Aline);
end;
procedure Log(AFilename: String; ALine: String);
var
f: TextFile;
begin
{$IFNDEF DEBUG}
if not FileExists(AFilename) then Exit;
{$ENDIF}
AssignFile(F, AFilename);
{$I-}
Append(F);
if IOResult <> 0 then Rewrite(F);
WriteLn(F, ALine);
{$I+}
CloseFIle(F);
end;
end.
|
constructor _COLLECTION_.Create (const aOwner : TComponent);
begin
inherited Create (aOwner, _COLLECTION_ITEM_);
end;
function _COLLECTION_.Add : _COLLECTION_ITEM_;
begin
Result := _COLLECTION_ITEM_ (inherited Add);
end;
function _COLLECTION_.FindItemID (const aID : Integer) : _COLLECTION_ITEM_;
begin
Result := _COLLECTION_ITEM_ (inherited FindItemID (aID));
end;
function _COLLECTION_.GetItem (const aIndex : Integer) : _COLLECTION_ITEM_;
begin
Result := _COLLECTION_ITEM_ (inherited GetItem (aIndex));
end;
function _COLLECTION_.Insert (const aIndex : Integer) : _COLLECTION_ITEM_;
begin
Result := _COLLECTION_ITEM_ (inherited Insert (aIndex));
end;
procedure _COLLECTION_.SetItem (const aIndex : Integer;
const aValue : _COLLECTION_ITEM_);
begin
inherited SetItem (aIndex, aValue);
end;
|
unit Frame.Tracking;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
System.Generics.Collections,
FMX.Types,
FMX.Graphics,
FMX.Controls,
FMX.Forms,
FMX.Dialogs,
FMX.StdCtrls,
FMX.Controls.Presentation;
type
TFrameTracking = class(TFrame)
ButtonDeallocateMem: TButton;
ButtonAllocateMem: TButton;
ButtonDeallocateObjects: TButton;
ButtonAllocateObjects: TButton;
LabelInstructions1: TLabel;
LabelInstructions2: TLabel;
LabelInstructions3: TLabel;
procedure ButtonAllocateObjectsClick(Sender: TObject);
procedure ButtonDeallocateObjectsClick(Sender: TObject);
procedure ButtonAllocateMemClick(Sender: TObject);
procedure ButtonDeallocateMemClick(Sender: TObject);
private
{ Private declarations }
FObjects: TObjectList<TObject>;
FMemoryBlocks: TArray<TBytes>;
procedure UpdateControls;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
{$R *.fmx}
uses
SampleClasses;
procedure TFrameTracking.ButtonAllocateMemClick(Sender: TObject);
var
Block: TBytes;
begin
SetLength(Block, 10 * 1024 * 1024);
FMemoryBlocks := FMemoryBlocks + [Block];
UpdateControls;
end;
procedure TFrameTracking.ButtonAllocateObjectsClick(Sender: TObject);
var
I, Count: Integer;
Obj: TObject;
begin
if (FObjects.Count = 0) then
begin
FObjects.Add(TSampleFoo.Create);
FObjects.Add(TSampleBar.Create);
end;
Count := Random(10) + 2;
for I := 0 to Count - 1 do
begin
if (Random(2) = 0) then
Obj := TSampleFoo.Create
else
Obj := TSampleBar.Create;
FObjects.Add(Obj)
end;
UpdateControls;
end;
procedure TFrameTracking.ButtonDeallocateMemClick(Sender: TObject);
begin
if (Length(FMemoryBlocks) > 0) then
SetLength(FMemoryBlocks, Length(FMemoryBlocks) - 1);
UpdateControls;
end;
procedure TFrameTracking.ButtonDeallocateObjectsClick(Sender: TObject);
var
Count: Integer;
begin
Count := FObjects.Count div 2;
if (Count = 0) then
Count := FObjects.Count;
while (Count > 0) do
begin
FObjects.Delete(0);
Dec(Count);
end;
UpdateControls;
end;
constructor TFrameTracking.Create(AOwner: TComponent);
begin
inherited;
FObjects := TObjectList<TObject>.Create;
end;
destructor TFrameTracking.Destroy;
begin
FObjects.Free;
inherited;
end;
procedure TFrameTracking.UpdateControls;
begin
ButtonDeallocateObjects.Enabled := (FObjects.Count > 0);
ButtonDeallocateMem.Enabled := (FMemoryBlocks <> nil);
end;
end.
|
unit UMyShape;
interface
uses
System.Classes, System.Types, System.Rtti, System.UITypes, System.UIConsts,
FMX.Types,FMX.Objects, FMX.Controls, FMX.TextLayout, FMX.Text, FMX.Messages,
FMX.Platform,FMX.Graphics;
{$SCOPEDENUMS ON}
Type
TMyEllipse = class(TEllipse)
private
FText :String;
FFont :TFont;
FTextColor:TAlphaColor;
protected
procedure Paint; override;
published
property Text:string read FText write FText;
property TextColor: TAlphaColor write FTextColor;
property Font : TFont write FFont;
end;
TMyRectAngle = class(TRectAngle)
private
FText :String;
FFont :TFont;
FTextColor:TAlphaColor;
protected
procedure Paint; override;
published
property Text:string read FText write FText;
property TextColor: TAlphaColor write FTextColor;
property Font : TFont write FFont;
end;
implementation
{$Region 'TMyEllipse'}
procedure TMyEllipse.Paint;
begin
inherited Paint;
Canvas.Fill.Color := self.FTextColor;
Canvas.Font.Size := FFont.Size;
Canvas.Font.Family := FFont.Family;
Canvas.Font.Style := FFont.Style;
Canvas.FillText(GetShapeRect,FText,True,1,[TFillTextFlag.ftRightToLeft],
TTextAlign.taCenter,TTextAlign.taCenter);
end;
{$EndRegion}
{$Region 'TMyRectAngle'}
procedure TMyRectAngle.Paint;
begin
inherited Paint;
Canvas.Fill.Color := FTextColor;
Canvas.Font.Size := FFont.Size;
Canvas.Font.Family := FFont.Family;
Canvas.Font.Style := FFont.Style;
Canvas.FillText(GetShapeRect,FText,True,1,[TFillTextFlag.ftRightToLeft],
TTextAlign.taCenter,TTextAlign.taCenter);
end;
{$EndRegion}
end.
|
unit fmExportProgress;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ADC.ExcelEnum, ADC.Types, ADC.GlobalVar,
ADC.Common, ADC.ADObject, ADC.ADObjectList, tdDataExport, Vcl.StdCtrls, Vcl.ComCtrls;
type
TForm_ExportProgress = class(TForm)
ProgressBar: TProgressBar;
Label_Desription: TLabel;
Label_Percentage: TLabel;
Button_Cancel: TButton;
Label_FileName: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button_CancelClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
FCallingForm: TForm;
function ConfirmCancellation: Boolean;
procedure OnDataExportProgress(AItem: TObject; AProgress: Integer);
procedure OnDataExportException(AMsg: string; ACode: ULONG);
procedure OnDataExportComplete(Sender: TObject);
procedure SetCallingForm(const Value: TForm);
public
procedure Execute(AFileName: TFileName; AFormat: TADCExportFormat);
property CallingForm: TForm write SetCallingForm;
end;
var
Form_ExportProgress: TForm_ExportProgress;
implementation
{$R *.dfm}
{ TForm_ExportProgress }
procedure TForm_ExportProgress.Button_CancelClick(Sender: TObject);
begin
Close;
end;
function TForm_ExportProgress.ConfirmCancellation: Boolean;
var
MsgBoxParam: TMsgBoxParams;
begin
if not csExport.TryEnter then
begin
ObjExport.Paused := True;
with MsgBoxParam do
begin
cbSize := SizeOf(MsgBoxParam);
hwndOwner := Self.Handle;
hInstance := 0;
lpszCaption := PChar(APP_TITLE);
lpszIcon := MAKEINTRESOURCE(32514);
dwStyle := MB_YESNO or MB_ICONQUESTION;
dwContextHelpId := 0;
lpfnMsgBoxCallback := nil;
dwLanguageId := LANG_NEUTRAL;
MsgBoxParam.lpszText := PChar('Отменить экспорт данных?');
end;
Result := MessageBoxIndirect(MsgBoxParam) = mrYes;
if Result
then ObjExport.Terminate;
ObjExport.Paused := False;
end else
begin
csExport.Leave;
Result := True;
end;
end;
procedure TForm_ExportProgress.Execute(AFileName: TFileName; AFormat: TADCExportFormat);
begin
Label_FileName.Caption := AFileName;
case apAPI of
ADC_API_LDAP: ObjExport := TADCExporter.Create(
Self.Handle,
LDAPBinding,
List_Obj,
List_Attributes,
AFormat,
AFileName,
csExport,
OnDataExportProgress,
OnDataExportException,
True
);
ADC_API_ADSI: ObjExport := TADCExporter.Create(
Self.Handle,
ADSIBinding,
List_Obj,
List_Attributes,
AFormat,
AFileName,
csExport,
OnDataExportProgress,
OnDataExportException,
True
);
end;
ObjExport.OnTerminate := OnDataExportComplete;
ObjExport.FreeOnTerminate := True;
ObjExport.Priority := tpNormal;
ObjExport.Start;
end;
procedure TForm_ExportProgress.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Label_Percentage.Caption := '0%';
ProgressBar.Position := 0;
Label_FileName.Caption := '';
if FCallingForm <> nil then
begin
FCallingForm.Enabled := True;
FCallingForm.Show;
FCallingForm := nil;
end;
end;
procedure TForm_ExportProgress.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose := ConfirmCancellation;
end;
procedure TForm_ExportProgress.OnDataExportComplete(Sender: TObject);
begin
Self.Close;
end;
procedure TForm_ExportProgress.OnDataExportException(AMsg: string;
ACode: ULONG);
var
MsgBoxParam: TMsgBoxParams;
begin
with MsgBoxParam do
begin
cbSize := SizeOf(MsgBoxParam);
hwndOwner := Self.Handle;
hInstance := 0;
lpszCaption := PChar(APP_TITLE);
lpszIcon := MAKEINTRESOURCE(32513);
dwStyle := MB_OK or MB_ICONHAND;
dwContextHelpId := 0;
lpfnMsgBoxCallback := nil;
dwLanguageId := LANG_NEUTRAL;
MsgBoxParam.lpszText := PChar(AMsg);
end;
MessageBoxIndirect(MsgBoxParam);
end;
procedure TForm_ExportProgress.OnDataExportProgress(AItem: TObject;
AProgress: Integer);
begin
Label_Percentage.Caption := Format('%d%%', [AProgress]);
ProgressBar.Position := AProgress;
end;
procedure TForm_ExportProgress.SetCallingForm(const Value: TForm);
begin
FCallingForm := Value;
if FCallingForm <> nil
then FCallingForm.Enabled := False;
end;
end.
|
unit _3DCameraView;
interface
uses _Types, Types, Math;
type
///////////////////////////////////////////////////////////////////////////////
// //
// TCamera3DView - виртуальная камера в пространстве //
// //
// фактически выполняет функции калькулятора: //
// перевод координат 3D - 2D, для получения перспективного изображения //
// //
///////////////////////////////////////////////////////////////////////////////
T3DCameraViewAnaglyph = class
private
{ см. property }
fLookPoint : T2DPoint;
fDistToLookPoint : RealType;
fAngleSlope : RealType;
fAngleTurn : RealType;
fViewAngle : RealType;
fCoordCamera : T3DPoint;
fLeftCam,fRightCam: T3DPoint;
fDistLeftRight : RealType;
{ промежуточные переменные для расчетов }
Xaxis,Yaxis,Zaxis: T3DPoint; // еденичные вектора, характеризующие ориентацию плоскости проецирования в пространстве
DistToScreen : RealType; // растояние от камеры до плоскости для проецирования перспективного изображения
HalfWidthScr : RealType; // половина ширины экрана
HalfHeightScr : RealType; // половина высоты экрана
HalfDiagonal : RealType; // половина диагонали экрана
{ специальные методы }
procedure CalcCoordOfCamera; // вычисление координаты камеры
procedure CalcDistToScreen; // вычисление расстояния от каммеры до плоскости проецирования изображения
procedure CalcOrientation; // вычисление еденичных векторов Xaxis, Yaxis и Zaxis
{ см. property }
procedure SetLookPoint(LP: T2DPoint);
procedure SetDistToLookPoint(DistToLP: RealType);
procedure SetAngleSlope(AngSlopeInDeg: RealType);
procedure SetAngleTurn(AngTurnInDeg: RealType);
procedure SetViewAngle(ViewAngInDeg: RealType);
procedure SetDistLeftRight(DistLeftRight: RealType);
function GetAngleSlope: RealType;
function GetAngleTurn: RealType;
function GetViewAngle: RealType;
public
{ СВОЙСТВА для пользователя }
property LookPoint: T2DPoint read fLookPoint write SetLookPoint; // точка в плоскости XY мирового пространства, на которую смотрит камера
property DistToLookPoint: RealType read fDistToLookPoint write SetDistToLookPoint; // расстояние между камерой и точкой LookPoint
property AngleSlopeCamera: RealType read GetAngleSlope write SetAngleSlope; // угол наклона камеры
property AngleTurnCamera: RealType read GetAngleTurn write SetAngleTurn; // угол поворота камеры в плоскости XY морового пространства
property ViewAngle: RealType read GetViewAngle write SetViewAngle; // угол зрения камеры (определяет DistToScreen через габариты экрана)
property CoordCamera: T3DPoint read fCoordCamera; // координаты камеры (обычной)
property CoordLeftCamera: T3DPoint read fLeftCam; // координаты левой камеры
property CoordRightCamera: T3DPoint read fRightCam; // координаты правой камеры
property DistLeftRightCamera: RealType read fDistLeftRight write SetDistLeftRight; // расстояние между левой и правыми камерами
{ МЕТОДЫ для пользователя }
constructor Create(_LookPoint: T2DPoint; _DistToLookPoint, _AngleSlope, _AngleTurn, // инициализация камеры
_ViewAngle, _DistLeftRightCamera: RealType; WidthScreen, HeightScreen: Integer); //
procedure SetBoundsToScreen(WidthScreen, HeightScreen: Integer); // устанавливает размеры области вывода изображения
function GetPixelCoord(const X,Y,Z: RealType): TPoint; // вычисляет координаты точки на области вывода с учетом всех параметров камеры
procedure GetLRPixelCoord(const X,Y,Z: RealType; var LeftP,RightP: TPoint); // --//-- для левой и правой камер
function GetWorldPlanCoord(PixelPoint: TPoint): T2DPoint; // вычисляет координаты точки плоскости XY пространства через экранные координаты
procedure MoveCameraByMouse(FromMousePos, ToMousePos: TPoint); // сдвигает камеру относительно координат курсора FromMousePos и ToMousePos
procedure ChangeDistFromCameraByCurrentPoint(MousePos: TPoint; Koef: RealType); // приближает либо отдаляет камеру относительно точки MousePos
end;
implementation
uses _Utils;
procedure T3DCameraViewAnaglyph.SetLookPoint(LP: T2DPoint);
begin
fCoordCamera := VectorAddition3D(fCoordCamera, _3DPoint(LP.X - fLookPoint.X, LP.Y - fLookPoint.Y, 0));
fLookPoint := LP;
end;
procedure T3DCameraViewAnaglyph.CalcCoordOfCamera;
begin
fCoordCamera := VectorAddition3D(ScaleVector(Zaxis, fDistToLookPoint), _3DPoint(fLookPoint.X, fLookPoint.Y, 0));
fLeftCam := VectorAddition3D(ScaleVector(Xaxis, -fDistLeftRight/2), fCoordCamera);
fRightCam := VectorAddition3D(ScaleVector(Xaxis, fDistLeftRight/2), fCoordCamera);
end;
procedure T3DCameraViewAnaglyph.CalcDistToScreen;
begin
DistToScreen := HalfDiagonal/Tan(fViewAngle/2);
end;
procedure T3DCameraViewAnaglyph.CalcOrientation;
begin
Xaxis := _3DPoint(1,0,0);
Yaxis := _3DPoint(0, Cos(fAngleSlope), Sin(fAngleSlope));
RotatePointInPlan(Xaxis, fAngleTurn);
RotatePointInPlan(Yaxis, fAngleTurn);
Zaxis := VectorProduct(Xaxis, Yaxis);
end;
procedure T3DCameraViewAnaglyph.SetDistToLookPoint(DistToLP: RealType);
begin
fDistToLookPoint := DistToLP;
CalcCoordOfCamera;
end;
procedure T3DCameraViewAnaglyph.SetDistLeftRight(DistLeftRight: RealType);
begin
fDistLeftRight := DistLeftRight;
CalcCoordOfCamera;
end;
function T3DCameraViewAnaglyph.GetAngleSlope: RealType;
begin
Result := RadToDeg(fAngleSlope);
end;
function T3DCameraViewAnaglyph.GetAngleTurn: RealType;
begin
Result := RadToDeg(fAngleTurn);
end;
procedure T3DCameraViewAnaglyph.SetAngleSlope(AngSlopeInDeg: RealType);
begin
fAngleSlope := DegToRad(AngSlopeInDeg);
CalcOrientation;
CalcCoordOfCamera;
end;
procedure T3DCameraViewAnaglyph.SetAngleTurn(AngTurnInDeg: RealType);
begin
fAngleTurn := DegToRad(AngTurnInDeg);
CalcOrientation;
CalcCoordOfCamera;
end;
function T3DCameraViewAnaglyph.GetViewAngle: RealType;
begin
Result := RadToDeg(fViewAngle);
end;
procedure T3DCameraViewAnaglyph.SetViewAngle(ViewAngInDeg: RealType);
begin
fViewAngle := DegToRad(ViewAngInDeg);
CalcDistToScreen;
end;
procedure T3DCameraViewAnaglyph.SetBoundsToScreen(WidthScreen, HeightScreen: Integer);
begin
HalfWidthScr := WidthScreen/2;
HalfHeightScr := HeightScreen/2;
HalfDiagonal := Sqrt(Sqr(HalfWidthScr) + Sqr(HalfHeightScr));
CalcDistToScreen;
end;
constructor T3DCameraViewAnaglyph.Create(_LookPoint: T2DPoint; _DistToLookPoint, _AngleSlope, _AngleTurn,
_ViewAngle, _DistLeftRightCamera: RealType; WidthScreen, HeightScreen: Integer);
begin
inherited Create;
fLookPoint := _LookPoint;
fAngleSlope := DegToRad(_AngleSlope);
fAngleTurn := DegToRad(_AngleTurn);
fViewAngle := DegToRad(_ViewAngle);
fDistLeftRight := _DistLeftRightCamera;
CalcOrientation;
SetDistToLookPoint(_DistToLookPoint);
SetBoundsToScreen(WidthScreen, HeightScreen);
end;
function T3DCameraViewAnaglyph.GetPixelCoord(const X,Y,Z: RealType): TPoint;
var
Vector: T3DPoint;
E,D: RealType;
begin
(*
Vector := CreateVector(fCoordCamera, _3DPoint(X, Y, Z)); // получим вектор: камера -> точка мира
E := ScalarProduct(Zaxis, Vector);
{ по идее тут нужна проверка деления на ноль /E }
Vector := ScaleVector(Vector, -DistToScreen/E); // получим вектор: камера -> точка пересечения с плоскостью проецирования
// а вот и результат:
Result.X := Round(HalfWidthScr + ScalarProduct(Xaxis, Vector));
Result.Y := Round(HalfHeightScr - ScalarProduct(Yaxis, Vector));
*)
// ТАК БЫСТРЕЕ чем код (* ... *):
{ получим вектор: камера -> точка мира }
Vector.X := X - fCoordCamera.X;
Vector.Y := Y - fCoordCamera.Y;
Vector.Z := Z - fCoordCamera.Z;
E := Zaxis.X*Vector.X + Zaxis.Y*Vector.Y + Zaxis.Z*Vector.Z;
if E = 0 then D := 0 else D := -DistToScreen/E;
{ получим вектор: камера -> точка пересечения с плоскостью проецирования }
Vector.X := Vector.X*D;
Vector.Y := Vector.Y*D;
Vector.Z := Vector.Z*D;
// а вот и результат:
Result.X := Round(HalfWidthScr + Xaxis.X*Vector.X + Xaxis.Y*Vector.Y + Xaxis.Z*Vector.Z);
Result.Y := Round(HalfHeightScr - Yaxis.X*Vector.X - Yaxis.Y*Vector.Y - Yaxis.Z*Vector.Z);
end;
procedure T3DCameraViewAnaglyph.GetLRPixelCoord(const X,Y,Z: RealType; var LeftP,RightP: TPoint);
var
Vector: T3DPoint;
E,D: RealType;
begin
{ получим вектор: левая камера -> точка мира }
Vector.X := X - fLeftCam.X;
Vector.Y := Y - fLeftCam.Y;
Vector.Z := Z - fLeftCam.Z;
E := Zaxis.X*Vector.X + Zaxis.Y*Vector.Y + Zaxis.Z*Vector.Z;
if E = 0 then D := 0 else D := -DistToScreen/E;
{ получим вектор: камера -> точка пересечения с плоскостью проецирования }
Vector.X := Vector.X*D;
Vector.Y := Vector.Y*D;
Vector.Z := Vector.Z*D;
// а вот и результат для левой точки:
LeftP.X := Round(HalfWidthScr + Xaxis.X*Vector.X + Xaxis.Y*Vector.Y + Xaxis.Z*Vector.Z);
LeftP.Y := Round(HalfHeightScr - Yaxis.X*Vector.X - Yaxis.Y*Vector.Y - Yaxis.Z*Vector.Z);
{ получим вектор: правая камера -> точка мира }
Vector.X := X - fRightCam.X;
Vector.Y := Y - fRightCam.Y;
Vector.Z := Z - fRightCam.Z;
E := Zaxis.X*Vector.X + Zaxis.Y*Vector.Y + Zaxis.Z*Vector.Z;
if E = 0 then D := 0 else D := -DistToScreen/E;
{ получим вектор: камера -> точка пересечения с плоскостью проецирования }
Vector.X := Vector.X*D;
Vector.Y := Vector.Y*D;
Vector.Z := Vector.Z*D;
// а вот и результат для правой точки:
RightP.X := Round(HalfWidthScr + Xaxis.X*Vector.X + Xaxis.Y*Vector.Y + Xaxis.Z*Vector.Z);
RightP.Y := Round(HalfHeightScr - Yaxis.X*Vector.X - Yaxis.Y*Vector.Y - Yaxis.Z*Vector.Z);
end;
function T3DCameraViewAnaglyph.GetWorldPlanCoord(PixelPoint: TPoint): T2DPoint;
var
A: T3DPoint; // точка PixelPoint в мировых координатах на плоскости проецирования
begin
A := VectorAddition3D(VectorAddition3D(ScaleVector(Zaxis, fDistToLookPoint - DistToScreen), _3DPoint(fLookPoint.X, fLookPoint.Y, 0)), // координата центральной точки плоскости проецирования в пространстве
VectorAddition3D(ScaleVector(Xaxis, PixelPoint.X - HalfWidthScr), ScaleVector(Yaxis, HalfHeightScr - PixelPoint.Y))); // вектор смещения центральной точки плоскости проецирования для PixelPoint в пространстве
// результат:
Result.X := A.Z*(A.X - fCoordCamera.X)/(fCoordCamera.Z - A.Z) + A.X;
Result.Y := A.Z*(A.Y - fCoordCamera.Y)/(fCoordCamera.Z - A.Z) + A.Y;
end;
procedure T3DCameraViewAnaglyph.MoveCameraByMouse(FromMousePos, ToMousePos: TPoint);
var
P1,P2: T2DPoint;
begin
P1 := GetWorldPlanCoord(FromMousePos);
P2 := GetWorldPlanCoord(ToMousePos);
SetLookPoint(VectorAddition2D(fLookPoint, _2DPoint(P1.X - P2.X, P1.Y - P2.Y)));
end;
procedure T3DCameraViewAnaglyph.ChangeDistFromCameraByCurrentPoint(MousePos: TPoint; Koef: RealType);
var
P1,P2: T2DPoint;
begin
P1 := GetWorldPlanCoord(MousePos);
SetDistToLookPoint(fDistToLookPoint*Koef);
P2 := GetWorldPlanCoord(MousePos);
SetLookPoint(VectorAddition2D(fLookPoint, _2DPoint(P1.X - P2.X, P1.Y - P2.Y)));
end;
end.
|
unit destListTable;
// Модуль: "w:\common\components\rtl\Garant\dd\destListTable.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TdestListTable" MUID: (51DD4CDC0343)
{$Include w:\common\components\rtl\Garant\dd\ddDefine.inc}
interface
uses
l3IntfUses
, ddRTFdestination
, rtfListTable
, destList
, ddCustomRTFReader
, ddRTFState
, RTFtypes
, l3Base
;
type
TdestListTable = class(TddRTFDestination)
private
f_Lists: TrtfListTable;
protected
function pm_GetItems(anIndex: Integer): TrtfList;
function pm_GetCount: Integer;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
procedure AddList(aList: TdestList);
procedure Close(aState: TddRTFState;
aNewDest: TddRTFDestination); override;
procedure WriteText(aRDS: TRDS;
aText: Tl3String;
aState: TddRTFState); override;
constructor Create(aRTFReader: TddCustomRTFReader); override;
public
property Items[anIndex: Integer]: TrtfList
read pm_GetItems;
default;
property Count: Integer
read pm_GetCount;
end;//TdestListTable
implementation
uses
l3ImplUses
, SysUtils
//#UC START# *51DD4CDC0343impl_uses*
//#UC END# *51DD4CDC0343impl_uses*
;
function TdestListTable.pm_GetItems(anIndex: Integer): TrtfList;
//#UC START# *51DD525200F4_51DD4CDC0343get_var*
var
i: Integer;
//#UC END# *51DD525200F4_51DD4CDC0343get_var*
begin
//#UC START# *51DD525200F4_51DD4CDC0343get_impl*
Result := nil;
for i:= 0 to f_Lists.Hi do
if TrtfList(f_Lists[i]).ID = anIndex then
begin
Result:= TrtfList(f_Lists[i]);
Break;
end;
//#UC END# *51DD525200F4_51DD4CDC0343get_impl*
end;//TdestListTable.pm_GetItems
function TdestListTable.pm_GetCount: Integer;
//#UC START# *51DD5310001B_51DD4CDC0343get_var*
//#UC END# *51DD5310001B_51DD4CDC0343get_var*
begin
//#UC START# *51DD5310001B_51DD4CDC0343get_impl*
Result := f_Lists.Count;
//#UC END# *51DD5310001B_51DD4CDC0343get_impl*
end;//TdestListTable.pm_GetCount
procedure TdestListTable.AddList(aList: TdestList);
//#UC START# *51DD52C10041_51DD4CDC0343_var*
//#UC END# *51DD52C10041_51DD4CDC0343_var*
begin
//#UC START# *51DD52C10041_51DD4CDC0343_impl*
f_Lists.AddList(aList.List);
//#UC END# *51DD52C10041_51DD4CDC0343_impl*
end;//TdestListTable.AddList
procedure TdestListTable.Close(aState: TddRTFState;
aNewDest: TddRTFDestination);
//#UC START# *5461BEC2017D_51DD4CDC0343_var*
//#UC END# *5461BEC2017D_51DD4CDC0343_var*
begin
//#UC START# *5461BEC2017D_51DD4CDC0343_impl*
//#UC END# *5461BEC2017D_51DD4CDC0343_impl*
end;//TdestListTable.Close
procedure TdestListTable.WriteText(aRDS: TRDS;
aText: Tl3String;
aState: TddRTFState);
//#UC START# *54E1F08400F9_51DD4CDC0343_var*
//#UC END# *54E1F08400F9_51DD4CDC0343_var*
begin
//#UC START# *54E1F08400F9_51DD4CDC0343_impl*
Assert(False);
//#UC END# *54E1F08400F9_51DD4CDC0343_impl*
end;//TdestListTable.WriteText
procedure TdestListTable.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_51DD4CDC0343_var*
//#UC END# *479731C50290_51DD4CDC0343_var*
begin
//#UC START# *479731C50290_51DD4CDC0343_impl*
inherited Cleanup;
FreeAndNil(f_Lists);
//#UC END# *479731C50290_51DD4CDC0343_impl*
end;//TdestListTable.Cleanup
constructor TdestListTable.Create(aRTFReader: TddCustomRTFReader);
//#UC START# *51E7C9DB0213_51DD4CDC0343_var*
//#UC END# *51E7C9DB0213_51DD4CDC0343_var*
begin
//#UC START# *51E7C9DB0213_51DD4CDC0343_impl*
inherited Create(aRTFReader);
f_Lists := TrtfListTable.Make;
//#UC END# *51E7C9DB0213_51DD4CDC0343_impl*
end;//TdestListTable.Create
end.
|
unit valida;
interface
uses
Controls, Dialogs, SysUtils, variants;
resourcestring
rsConfElimina = 'Confirma Eliminación de dato ?';
rsConfGrabar = 'Confirma Grabación de dato ?';
rsConfOpera = 'Confirma Operacion ?';
type
DlgTipo = ( dialElim, dialGrabar, dialOpera );
stringArray = array of array of string;
function Confirma( Tipo: DlgTipo ):boolean;
function CadenaVacia( const a: array of string ):Boolean;
function ContieneCadena( const a: array of string; const valor: string ):Boolean;
implementation
function Confirma( Tipo: DlgTipo ):boolean;
var
FConf: string;
begin
case Tipo of
dialElim: FConf := rsConfElimina;
dialGrabar: FConf := rsConfGrabar;
dialOpera: FConf := rsConfOpera;
end;
Result := MessageDlg( FConf, mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes;
end;
function CadenaVacia( const a: array of string ):Boolean;
var
i: Integer;
begin
for I := Low(a) to High(a) do
if a[i] = '' then
begin
result := true;
Exit;
end;
result := false;
end;
function ContieneCadena( const a: array of string; const valor: string ):Boolean;
var
i: Integer;
begin
for I := Low(a) to High(a) do
if a[i] = valor then
begin
result := true;
Exit;
end;
result := false;
end;
end.
|
unit uModeloRelatorioVO;
interface
uses
System.SysUtils, uKeyField, uTableName;
type
[TableName('Modelo_Relatorio')]
TModeloRelatorioVO = class
private
FDescricao: string;
FCodigo: Integer;
FId: Integer;
FArquivo: string;
FIdRevenda: Integer;
procedure SetArquivo(const Value: string);
procedure SetCodigo(const Value: Integer);
procedure SetDescricao(const Value: string);
procedure SetId(const Value: Integer);
procedure SetIdRevenda(const Value: Integer);
public
[KeyField('ModR_Id')]
property Id: Integer read FId write SetId;
[FieldName('ModR_Codigo')]
property Codigo: Integer read FCodigo write SetCodigo;
[FieldName('ModR_Descricao')]
property Descricao: string read FDescricao write SetDescricao;
[FieldName('ModR_Arquivo')]
property Arquivo: string read FArquivo write SetArquivo;
[FieldNull('ModR_Revenda')]
property IdRevenda: Integer read FIdRevenda write SetIdRevenda;
end;
implementation
{ TModeloRelatorio }
procedure TModeloRelatorioVO.SetArquivo(const Value: string);
begin
if Value.Trim = '' then
raise Exception.Create('Infome o Nome do Arquivo!');
FArquivo := Value;
end;
procedure TModeloRelatorioVO.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TModeloRelatorioVO.SetDescricao(const Value: string);
begin
if Value.Trim = '' then
raise Exception.Create('Informe a Descrição do Modelo!');
FDescricao := Value;
end;
procedure TModeloRelatorioVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TModeloRelatorioVO.SetIdRevenda(const Value: Integer);
begin
FIdRevenda := Value;
end;
end.
|
unit udmConfiguracoes;
interface
uses
Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS,
LibGeral, LibSatwin;
type
TdmConfiguracoes = class(TdmPadrao)
qryManutencaoMODULO: TStringField;
qryManutencaoCLAUSULA: TStringField;
qryManutencaoTPO_CLAUSULA: TStringField;
qryManutencaoVLR_CLAUSULA: TStringField;
qryManutencaoOPERADOR: TStringField;
qryManutencaoDT_ALTERACAO: TDateTimeField;
qryManutencaoVISUALIZACAO: TStringField;
qryLocalizacaoMODULO: TStringField;
qryLocalizacaoCLAUSULA: TStringField;
qryLocalizacaoTPO_CLAUSULA: TStringField;
qryLocalizacaoVLR_CLAUSULA: TStringField;
qryLocalizacaoOPERADOR: TStringField;
qryLocalizacaoDT_ALTERACAO: TDateTimeField;
qryLocalizacaoVISUALIZACAO: TStringField;
procedure qryManutencaoVISUALIZACAOGetText(Sender: TField;
var Text: String; DisplayText: Boolean);
protected
procedure MontaSQLBusca(DataSet: TDataSet = nil); override;
procedure MontaSQLRefresh; override;
private
FModulo: string;
FClausula: string;
function RetornarWhere(AModulos: string): string;
function getSQLDefault: string;
public
procedure Atualizar(AFiltrarMes: Boolean = False); override;
property Modulo: string read FModulo write FModulo;
property Clausula: string read FClausula write FClausula;
property SQLPadrao: string read getSQLDefault;
end;
const
SQL_DEFAULT =
' SELECT ' +
' CF.MODULO, ' +
' CF.CLAUSULA, ' +
' CF.TPO_CLAUSULA, ' +
' CF.VLR_CLAUSULA, ' +
' CF.OPERADOR, ' +
' CF.DT_ALTERACAO, ' +
' CASE CF.TPO_CLAUSULA ' +
' WHEN ''L'' THEN ' +
' CASE CF.VLR_CLAUSULA ' +
' WHEN ''T'' THEN ''SIM'' ' +
' ELSE ''NÃO'' ' +
' END ' +
' WHEN ''P'' THEN ''********'' ' +
' ELSE CF.VLR_CLAUSULA ' +
' END VISUALIZACAO ' +
' FROM CONFIGURACOES CF ';
var
dmConfiguracoes: TdmConfiguracoes;
implementation
{$R *.dfm}
{ TdmConfiguracoes }
procedure TdmConfiguracoes.Atualizar(AFiltrarMes: Boolean);
begin
inherited;
end;
function TdmConfiguracoes.getSQLDefault: string;
begin
result := SQL_DEFAULT;
end;
procedure TdmConfiguracoes.MontaSQLBusca(DataSet: TDataSet);
begin
inherited;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add(RetornarWhere(FModulo));
SQL.Add(' AND (CF.CLAUSULA = :CLAUSULA)');
SQL.Add('ORDER BY CF.MODULO, CF.CLAUSULA');
//ParamByName('MODULO').AsString := sModulo;
ParamByName('CLAUSULA').AsString := FClausula;
end;
end;
procedure TdmConfiguracoes.MontaSQLRefresh;
begin
inherited;
with qryManutencao do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add(RetornarWhere(FModulo));
//SQL.Add(' WHERE MODULO = ' + QuotedStr(Modulo));
if TemValor(Clausula) then
SQL.Add(' AND CLAUSULA CONTAINING ' + QuotedStr(Clausula));
SQL.Add('ORDER BY MODULO, CLAUSULA');
end;
end;
function TdmConfiguracoes.RetornarWhere(AModulos: string): string;
var
I : Integer;
Ini : Integer;
Cont : Integer;
Str : TStrings;
Aux : string;
begin
Ini := 1;
Cont := 0;
Str := TStringList.Create;
for I := 1 to Length(AModulos) do
begin
Inc(Cont);
if AModulos[I] = ';' then
begin
Str.Add(Copy(AModulos, Ini, Cont - 1));
Cont := 0;
Ini := I+1;
end;
end;
if Str.Count = 0 then
Aux := 'WHERE (CF.MODULO = ' + QuotedStr(AModulos) +')'
else
begin
for I := 0 to Str.Count - 1 do
if I = 0 then
Aux := 'WHERE (CF.MODULO IN (' + QuotedStr(Str[I])
else
Aux := Aux + ',' + QuotedStr(Str[I]);
Aux := Aux + '))';
end;
Result := Aux;
Str.Free;
end;
procedure TdmConfiguracoes.qryManutencaoVISUALIZACAOGetText(Sender: TField;
var Text: String; DisplayText: Boolean);
begin
inherited;
case qryManutencaoTPO_CLAUSULA.AsString[1] of
'L':
begin
if qryManutencaoVLR_CLAUSULA.AsString = 'T' then
Text := 'SIM'
else
Text := 'NAO';
end;
'P': Text := '********';
else
Text := qryManutencaoVLR_CLAUSULA.AsString;
end;
(*
' CASE CF.TPO_CLAUSULA ' +
' WHEN ''L'' THEN ' +
' CASE CF.VLR_CLAUSULA ' +
' WHEN ''T'' THEN ''SIM'' ' +
' ELSE ''NÃO'' ' +
' END ' +
' WHEN ''P'' THEN ''********'' ' +
' ELSE CF.VLR_CLAUSULA ' +
' END VISUALIZACAO ' + *)
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons;
type
//conjunto de variáveis
TDADOS = Record
id:Integer;
nome, email, sexo:String;
end;
type
//conjunto de variáveis
TDADOS_CLIENTE = Record
id:Integer;
nome, email, sexo:String;
end;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Button2: TButton;
Label1: TLabel;
SpeedButton1: TSpeedButton;
BitBtn1: TBitBtn;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
//adicionar dados
procedure AdicionarDados(d : TDADOS);
private
{ Private declarations }
//declara a variável com o tipo do record
//neste caso grava sempre o último registro
Dados :TDADOS;
CLIENTE :TDADOS_CLIENTE;
//array para adicionar os dados
//neste caso grava vários registros
arDados : Array of TDADOS;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.AdicionarDados(d: TDADOS);
begin
SetLength(arDados,Length(arDados)+1);
arDados[Length(arDados)-1] := D;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
//gravando record
Dados.id := Dados.id + 1;
Dados.nome := Edit1.Text;
Dados.email:= Edit2.Text;
Dados.sexo := Edit3.Text;
AdicionarDados(Dados);
//limpar campos
Edit1.Text := '';
Edit2.Text := '';
Edit3.Text := '';
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
//leitura do record (neste caso o último)
Label1.Caption := IntToStr(Dados.id);
Edit1.Text := Dados.nome;
Edit2.Text := Dados.email;
Edit3.Text := Dados.sexo;
end;
procedure TForm1.BitBtn1Click(Sender: TObject);
var
s:TStringList;
i:Integer;
begin
//leitura de vários registros inseridos no record
for i:= 0 to Pred(length(arDados)) do
begin
Memo1.Lines.Add(IntToStr(arDados[i].id) + '-' + arDados[i].nome +
'-' + arDados[i].sexo +
'-' + arDados[i].email);
end;
end;
end.
|
unit location;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, And_jni_Bridge, Laz_And_Controls, AndroidWidget;
type
TLocationChanged = procedure(Sender: TObject; latitude: double; longitude: double; altitude: double; address: string) of object;
TLocationStatusChanged = procedure(Sender: TObject; status: integer; provider: string; msgStatus: string) of object;
TLocationProviderEnabled = procedure(Sender: TObject; provider: string) of object;
TLocationProviderDisabled = procedure(Sender: TObject; provider: string) of object;
TCriteriaAccuracy = (crCoarse, crFine);
TMapType=(mtRoadmap, mtSatellite, mtTerrain, mtHybrid);
{Draft Component code by "Lazarus Android Module Wizard" [8/11/2014 19:15:07]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jControl template}
jLocation = class(jControl)
private
FCriteriaAccuracy: TCriteriaAccuracy;
FTimeForUpdates: int64; // millsecs
FDistanceForUpdates: int64; //meters
FMapType: TMapType;
FMapZoom: integer;
FMapWidth: integer;
FMapHeight: integer;
FOnLocationChanged: TLocationChanged;
FOnLocationStatusChanged: TLocationStatusChanged;
FOnLocationProviderEnabled: TLocationProviderEnabled;
FOnLocationProviderDisabled: TLocationProviderDisabled;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init(refApp: jApp); override;
function jCreate( _TimeForUpdates: int64; _DistanceForUpdates: int64; _CriteriaAccuracy: integer; _MapType: integer): jObject;
procedure jFree();
function StartTracker(): boolean;
procedure ShowLocationSouceSettings();
procedure RequestLocationUpdates();
procedure StopTracker();
procedure SetCriteriaAccuracy(_accuracy: TCriteriaAccuracy);
function IsGPSProvider(): boolean;
function IsNetProvider(): boolean;
procedure SetTimeForUpdates(_time: int64);
procedure SetDistanceForUpdates(_distance: int64);
function GetLatitude(): double;
function GetLongitude(): double;
function GetAltitude(): double;
function IsWifiEnabled(): boolean;
procedure SetWifiEnabled(_status: boolean);
function GetGoogleMapsUrl(_latitude: double; _longitude: double): string;
procedure SetMapWidth(_mapwidth: integer);
procedure SetMapHeight(_mapheight: integer);
procedure SetMapZoom(_mapzoom: integer);
procedure SetMapType(_maptype: TMapType);
function GetAddress(): string; overload;
function GetAddress(_latitude: double; _longitude: double): string; overload;
procedure GenEvent_OnLocationChanged(Obj: TObject; latitude: double; longitude: double; altitude: double; address: string);
procedure GenEvent_OnLocationStatusChanged(Obj: TObject; status: integer; provider: string; msgStatus: string);
procedure GenEvent_OnLocationProviderEnabled(Obj: TObject; provider: string);
procedure GenEvent_OnLocationProviderDisabled(Obj: TObject; provider: string);
property MapZoom: integer read FMapZoom write SetMapZoom;
property MapWidth: integer read FMapWidth write SetMapWidth;
property MapHeight: integer read FMapHeight write SetMapHeight;
published
property MapType: TMapType read FMapType write SetMapType;
property CriteriaAccuracy: TCriteriaAccuracy read FCriteriaAccuracy write SetCriteriaAccuracy;
property TimeForUpdates: int64 read FTimeForUpdates write SetTimeForUpdates; // millsecs
property DistanceForUpdates: int64 read FDistanceForUpdates write SetDistanceForUpdates; //meters
property OnLocationChanged: TLocationChanged read FOnLocationChanged write FOnLocationChanged;
property OnLocationStatusChanged: TLocationStatusChanged read FOnLocationStatusChanged write FOnLocationStatusChanged;
property OnLocationProviderEnabled: TLocationProviderEnabled read FOnLocationProviderEnabled write FOnLocationProviderEnabled;
property OnLocationProviderDisabled: TLocationProviderDisabled read FOnLocationProviderDisabled write FOnLocationProviderDisabled;
end;
function jLocation_jCreate(env: PJNIEnv; this: JObject;_Self: int64; _TimeForUpdates: int64; _DistanceForUpdates: int64; _CriteriaAccuracy: integer; _MapType: integer): jObject;
procedure jLocation_jFree(env: PJNIEnv; _jlocation: JObject);
function jLocation_StartTracker(env: PJNIEnv; _jlocation: JObject): boolean;
procedure jLocation_ShowLocationSouceSettings(env: PJNIEnv; _jlocation: JObject);
procedure jLocation_RequestLocationUpdates(env: PJNIEnv; _jlocation: JObject);
procedure jLocation_StopTracker(env: PJNIEnv; _jlocation: JObject);
procedure jLocation_SetCriteriaAccuracy(env: PJNIEnv; _jlocation: JObject; _accuracy: integer);
function jLocation_IsGPSProvider(env: PJNIEnv; _jlocation: JObject): boolean;
function jLocation_IsNetProvider(env: PJNIEnv; _jlocation: JObject): boolean;
procedure jLocation_SetTimeForUpdates(env: PJNIEnv; _jlocation: JObject; _time: int64);
procedure jLocation_SetDistanceForUpdades(env: PJNIEnv; _jlocation: JObject; _distance: int64);
function jLocation_GetLatitude(env: PJNIEnv; _jlocation: JObject): double;
function jLocation_GetLongitude(env: PJNIEnv; _jlocation: JObject): double;
function jLocation_GetAltitude(env: PJNIEnv; _jlocation: JObject): double;
function jLocation_IsWifiEnabled(env: PJNIEnv; _jlocation: JObject): boolean;
procedure jLocation_SetWifiEnabled(env: PJNIEnv; _jlocation: JObject; _status: boolean);
function jLocation_GetGoogleMapsUrl(env: PJNIEnv; _jlocation: JObject; _latitude: double; _longitude: double): string;
procedure jLocation_SetMapWidth(env: PJNIEnv; _jlocation: JObject; _mapwidth: integer);
procedure jLocation_SetMapHeight(env: PJNIEnv; _jlocation: JObject; _mapheight: integer);
procedure jLocation_SetMapZoom(env: PJNIEnv; _jlocation: JObject; _mapzoom: integer);
procedure jLocation_SetMapType(env: PJNIEnv; _jlocation: JObject; _maptype: integer);
function jLocation_GetAddress(env: PJNIEnv; _jlocation: JObject): string; overload;
function jLocation_GetAddress(env: PJNIEnv; _jlocation: JObject; _latitude: double; _longitude: double): string; overload;
implementation
{--------- jLocation --------------}
constructor jLocation.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//your code here....
FCriteriaAccuracy:= crCoarse;
FMapType:= mtRoadmap;
FTimeForUpdates:= Trunc((1000 * 60 * 1)/4); // millsecs {default = 1/4 minute};
FDistanceForUpdates:= 1; //meters
end;
destructor jLocation.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject := nil;
end;
end;
//you others free code here...
inherited Destroy;
end;
procedure jLocation.Init(refApp: jApp);
begin
if FInitialized then Exit;
inherited Init(refApp);
//your code here: set/initialize create params....
FjObject := jCreate(FTimeForUpdates ,FDistanceForUpdates ,Ord(FCriteriaAccuracy) ,Ord(FMapType));
FInitialized:= True;
end;
function jLocation.jCreate( _TimeForUpdates: int64; _DistanceForUpdates: int64; _CriteriaAccuracy: integer; _MapType: integer): jObject;
begin
Result:= jLocation_jCreate(FjEnv, FjThis , int64(Self) ,_TimeForUpdates ,_DistanceForUpdates ,_CriteriaAccuracy ,_MapType);
end;
procedure jLocation.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jLocation_jFree(FjEnv, FjObject );
end;
function jLocation.StartTracker(): boolean;
begin
//in designing component state: result value here...
Result:= False;
if FInitialized then
Result:= jLocation_StartTracker(FjEnv, FjObject );
end;
procedure jLocation.ShowLocationSouceSettings();
begin
//in designing component state: set value here...
if FInitialized then
jLocation_ShowLocationSouceSettings(FjEnv, FjObject );
end;
procedure jLocation.RequestLocationUpdates();
begin
//in designing component state: set value here...
if FInitialized then
jLocation_RequestLocationUpdates(FjEnv, FjObject );
end;
procedure jLocation.StopTracker();
begin
//in designing component state: set value here...
if FInitialized then
jLocation_StopTracker(FjEnv, FjObject );
end;
procedure jLocation.SetCriteriaAccuracy(_accuracy: TCriteriaAccuracy);
begin
//in designing component state: set value here...
FCriteriaAccuracy:= _accuracy;
if FInitialized then
jLocation_SetCriteriaAccuracy(FjEnv, FjObject , Ord(_accuracy));
end;
function jLocation.IsGPSProvider(): boolean;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jLocation_IsGPSProvider(FjEnv, FjObject );
end;
function jLocation.IsNetProvider(): boolean;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jLocation_IsNetProvider(FjEnv, FjObject );
end;
procedure jLocation.SetTimeForUpdates(_time: int64);
begin
//in designing component state: set value here...
FTimeForUpdates:= _time;
if FInitialized then
jLocation_SetTimeForUpdates(FjEnv, FjObject , _time);
end;
procedure jLocation.SetDistanceForUpdates(_distance: int64);
begin
//in designing component state: set value here...
FDistanceForUpdates:= _distance;
if FInitialized then
jLocation_SetDistanceForUpdades(FjEnv, FjObject , _distance);
end;
function jLocation.GetLatitude(): double;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jLocation_GetLatitude(FjEnv, FjObject );
end;
function jLocation.GetLongitude(): double;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jLocation_GetLongitude(FjEnv, FjObject );
end;
function jLocation.GetAltitude(): double;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jLocation_GetAltitude(FjEnv, FjObject );
end;
function jLocation.IsWifiEnabled(): boolean;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jLocation_IsWifiEnabled(FjEnv, FjObject );
end;
procedure jLocation.SetWifiEnabled(_status: boolean);
begin
//in designing component state: set value here...
if FInitialized then
jLocation_SetWifiEnabled(FjEnv, FjObject , _status);
end;
function jLocation.GetGoogleMapsUrl(_latitude: double; _longitude: double): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jLocation_GetGoogleMapsUrl(FjEnv, FjObject , _latitude ,_longitude);
end;
procedure jLocation.SetMapWidth(_mapwidth: integer);
begin
//in designing component state: set value here...
FMapWidth:= _mapwidth;
if FInitialized then
jLocation_SetMapWidth(FjEnv, FjObject , _mapwidth);
end;
procedure jLocation.SetMapHeight(_mapheight: integer);
begin
//in designing component state: set value here...
FMapHeight:=_mapheight;
if FInitialized then
jLocation_SetMapHeight(FjEnv, FjObject , _mapheight);
end;
procedure jLocation.SetMapZoom(_mapzoom: integer);
begin
//in designing component state: set value here...
FMapZoom:= _mapzoom;
if FInitialized then
jLocation_SetMapZoom(FjEnv, FjObject , _mapzoom);
end;
procedure jLocation.SetMapType(_maptype: TMapType);
begin
//in designing component state: set value here...
FMapType:= _maptype;
if FInitialized then
jLocation_SetMapType(FjEnv, FjObject , Ord(_maptype));
end;
function jLocation.GetAddress(): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jLocation_GetAddress(FjEnv, FjObject );
end;
function jLocation.GetAddress(_latitude: double; _longitude: double): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jLocation_GetAddress(FjEnv, FjObject , _latitude ,_longitude);
end;
procedure jLocation.GenEvent_OnLocationChanged(Obj: TObject; latitude: double; longitude: double; altitude: double; address: string);
begin
if Assigned(FOnLocationChanged) then FOnLocationChanged(Obj, latitude, longitude, altitude, address);
end;
procedure jLocation.GenEvent_OnLocationStatusChanged(Obj: TObject; status: integer; provider: string; msgStatus: string);
begin
if Assigned(FOnLocationStatusChanged) then FOnLocationStatusChanged(Obj, status, provider, msgStatus);
end;
procedure jLocation.GenEvent_OnLocationProviderEnabled(Obj: TObject; provider: string);
begin
if Assigned(FOnLocationProviderEnabled) then FOnLocationProviderEnabled(Obj, provider);
end;
procedure jLocation.GenEvent_OnLocationProviderDisabled(Obj: TObject; provider: string);
begin
if Assigned(FOnLocationProviderDisabled) then FOnLocationProviderDisabled(Obj, provider);
end;
{-------- jLocation_JNI_Bridge ----------}
function jLocation_jCreate(env: PJNIEnv; this: JObject;_Self: int64; _TimeForUpdates: int64; _DistanceForUpdates: int64; _CriteriaAccuracy: integer; _MapType: integer): jObject;
var
jParams: array[0..4] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _Self;
jParams[1].j:= _TimeForUpdates;
jParams[2].j:= _DistanceForUpdates;
jParams[3].i:= _CriteriaAccuracy;
jParams[4].i:= _MapType;
jCls:= Get_gjClass(env);
jMethod:= env^.GetMethodID(env, jCls, 'jLocation_jCreate', '(JJJII)Ljava/lang/Object;');
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
end;
(*
//Please, you need insert:
public java.lang.Object jLocation_jCreate(long _Self, long _TimeForUpdates, long _DistanceForUpdates, int _CriteriaAccuracy, int _MapType) {
return (java.lang.Object)(new jLocation(this,_Self,_TimeForUpdates,_DistanceForUpdates,_CriteriaAccuracy,_MapType));
}
//to end of "public class Controls" in "Controls.java"
*)
procedure jLocation_jFree(env: PJNIEnv; _jlocation: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
env^.CallVoidMethod(env, _jlocation, jMethod);
env^.DeleteLocalRef(env, jCls);
env^.DeleteLocalRef(env, jCls);
end;
function jLocation_StartTracker(env: PJNIEnv; _jlocation: JObject): boolean;
var
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'StartTracker', '()Z');
jBoo:= env^.CallBooleanMethod(env, _jlocation, jMethod);
Result:= boolean(jBoo);
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_ShowLocationSouceSettings(env: PJNIEnv; _jlocation: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'ShowLocationSouceSettings', '()V');
env^.CallVoidMethod(env, _jlocation, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_RequestLocationUpdates(env: PJNIEnv; _jlocation: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'RequestLocationUpdates', '()V');
env^.CallVoidMethod(env, _jlocation, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_StopTracker(env: PJNIEnv; _jlocation: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'StopTracker', '()V');
env^.CallVoidMethod(env, _jlocation, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_SetCriteriaAccuracy(env: PJNIEnv; _jlocation: JObject; _accuracy: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _accuracy;
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'SetCriteriaAccuracy', '(I)V');
env^.CallVoidMethodA(env, _jlocation, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jLocation_IsGPSProvider(env: PJNIEnv; _jlocation: JObject): boolean;
var
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'IsGPSProvider', '()Z');
jBoo:= env^.CallBooleanMethod(env, _jlocation, jMethod);
Result:= boolean(jBoo);
env^.DeleteLocalRef(env, jCls);
end;
function jLocation_IsNetProvider(env: PJNIEnv; _jlocation: JObject): boolean;
var
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'IsNetProvider', '()Z');
jBoo:= env^.CallBooleanMethod(env, _jlocation, jMethod);
Result:= boolean(jBoo);
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_SetTimeForUpdates(env: PJNIEnv; _jlocation: JObject; _time: int64);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _time;
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'SetTimeForUpdates', '(J)V');
env^.CallVoidMethodA(env, _jlocation, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_SetDistanceForUpdades(env: PJNIEnv; _jlocation: JObject; _distance: int64);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _distance;
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'SetDistanceForUpdates', '(J)V');
env^.CallVoidMethodA(env, _jlocation, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jLocation_GetLatitude(env: PJNIEnv; _jlocation: JObject): double;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'GetLatitude', '()D');
Result:= env^.CallDoubleMethod(env, _jlocation, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jLocation_GetLongitude(env: PJNIEnv; _jlocation: JObject): double;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'GetLongitude', '()D');
Result:= env^.CallDoubleMethod(env, _jlocation, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jLocation_GetAltitude(env: PJNIEnv; _jlocation: JObject): double;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'GetAltitude', '()D');
Result:= env^.CallDoubleMethod(env, _jlocation, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jLocation_IsWifiEnabled(env: PJNIEnv; _jlocation: JObject): boolean;
var
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'IsWifiEnabled', '()Z');
jBoo:= env^.CallBooleanMethod(env, _jlocation, jMethod);
Result:= boolean(jBoo);
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_SetWifiEnabled(env: PJNIEnv; _jlocation: JObject; _status: boolean);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].z:= JBool(_status);
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'SetWifiEnabled', '(Z)V');
env^.CallVoidMethodA(env, _jlocation, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jLocation_GetGoogleMapsUrl(env: PJNIEnv; _jlocation: JObject; _latitude: double; _longitude: double): string;
var
jStr: JString;
jBoo: JBoolean;
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].d:= _latitude;
jParams[1].d:= _longitude;
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'GetGoogleMapsUrl', '(DD)Ljava/lang/String;');
jStr:= env^.CallObjectMethodA(env, _jlocation, jMethod, @jParams);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_SetMapWidth(env: PJNIEnv; _jlocation: JObject; _mapwidth: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _mapwidth;
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'SetMapWidth', '(I)V');
env^.CallVoidMethodA(env, _jlocation, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_SetMapHeight(env: PJNIEnv; _jlocation: JObject; _mapheight: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _mapheight;
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'SetMapHeight', '(I)V');
env^.CallVoidMethodA(env, _jlocation, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_SetMapZoom(env: PJNIEnv; _jlocation: JObject; _mapzoom: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _mapzoom;
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'SetMapZoom', '(I)V');
env^.CallVoidMethodA(env, _jlocation, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jLocation_SetMapType(env: PJNIEnv; _jlocation: JObject; _maptype: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _maptype;
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'SetMapType', '(I)V');
env^.CallVoidMethodA(env, _jlocation, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jLocation_GetAddress(env: PJNIEnv; _jlocation: JObject): string;
var
jStr: JString;
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'GetAddress', '()Ljava/lang/String;');
jStr:= env^.CallObjectMethod(env, _jlocation, jMethod);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
function jLocation_GetAddress(env: PJNIEnv; _jlocation: JObject; _latitude: double; _longitude: double): string;
var
jStr: JString;
jBoo: JBoolean;
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].d:= _latitude;
jParams[1].d:= _longitude;
jCls:= env^.GetObjectClass(env, _jlocation);
jMethod:= env^.GetMethodID(env, jCls, 'GetAddress', '(DD)Ljava/lang/String;');
jStr:= env^.CallObjectMethodA(env, _jlocation, jMethod, @jParams);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
end.
|
{$MODE OBJFPC}
program BodyGuards;
const
InputFile = 'GUARDS.INP';
OutputFile = 'GUARDS.OUT';
maxN = 100000;
type
TGuard = record
s, f: Integer;
id: Integer;
Selected: Boolean;
end;
PGuard = ^TGuard;
TCmpFunc = function (x, y: PGuard): Integer;
THeap = record
nItems: Integer;
Items: array[1..maxN] of PGuard;
Compare: TCmpFunc;
end;
var
temp: array[1..maxN] of TGuard;
Guard: array[1..maxN] of PGuard;
n, k, A, B: Integer;
MinHeap, MaxHeap: THeap;
Sentinel: TGuard;
res: Integer;
procedure Enter;
var
fi: TextFile;
i: Integer;
begin
AssignFile(fi, InputFile); Reset(fi);
try
ReadLn(fi, n, k, A, B);
for i := 1 to n do
begin
Guard[i] := @temp[i];
with Guard[i]^ do
begin
ReadLn(fi, s, f);
id := i;
Selected := False;
end;
end;
finally
CloseFile(fi);
end;
end;
procedure Sort(L, H: Integer);
var
i, j: Integer;
Pivot: PGuard;
begin
if L >= H then Exit;
i := L + Random(H - L + 1);
Pivot := Guard[i]; Guard[i] := Guard[L];
i := L; j := H;
repeat
while (Guard[j]^.s > Pivot^.s) and (i < j) do Dec(j);
if i < j then
begin
Guard[i] := Guard[j]; Inc(i);
end
else Break;
while (Guard[i]^.s < Pivot^.s) and (i < j) do Inc(i);
if i < j then
begin
Guard[j] := Guard[i]; Dec(j);
end
else Break;
until i = j;
Guard[i] := Pivot;
Sort(L, i - 1); Sort(i + 1, H);
end;
function MinHeapCompare(x, y: PGuard): Integer;
begin
if x^.f < y^.f then Result := 1
else
if x^.f = y^.f then Result := 0
else Result:= -1;
end;
function MaxHeapCompare(x, y: PGuard): Integer;
begin
if x^.f > y^.f then Result := 1
else
if x^.f = y^.f then Result := 0
else Result := -1;
end;
procedure Init;
var
i: Integer;
begin
MinHeap.Compare := @MinHeapCompare;
MaxHeap.Compare := @MaxHeapCompare;
Sentinel.f := A;
MinHeap.nItems := k;
for i := 1 to k do
MinHeap.Items[i] := @Sentinel;
MaxHeap.nItems := 0;
end;
procedure UpHeap(var Heap: THeap; c: Integer);
var
p: Integer;
temp: PGuard;
begin
with Heap do
begin
temp := Items[c];
repeat
p := c div 2;
if (p = 0) or (Compare(Items[p], temp) >= 0) then Break;
Items[c] := Items[p];
c := p;
until False;
Items[c] := temp;
end;
end;
procedure DownHeap(var Heap: THeap; p: Integer);
var
c: Integer;
temp: PGuard;
begin
with Heap do
begin
temp := Items[p];
repeat
c := p * 2;
if (c < nItems) and (Compare(Items[c], Items[c + 1]) < 0) then
Inc(c);
if (c > nItems) or (Compare(Items[c], temp) <= 0) then Break;
Items[p] := Items[c];
p := c;
until False;
Items[p] := temp;
end;
end;
function Get(const Heap: THeap): PGuard;
begin
Result := Heap.Items[1];
end;
procedure Insert(var Heap: THeap; Guard: PGuard);
begin
with Heap do
begin
Inc(nItems);
Items[nItems] := Guard;
UpHeap(Heap, nItems);
end;end;
function Extract(var Heap: THeap): PGuard;
begin
Result := Get(Heap);
with Heap do
begin
Items[1] := Items[nItems];
Dec(nItems);
DownHeap(Heap, 1);
end;
end;
procedure Solve;
var
G: PGuard;
Time: Integer;
i: Integer;
begin
i := 1;
res := 0;
repeat
G := Get(MinHeap); Time := G^.f;
if (Time >= b) and (res >= k) then
Break;
while (i <= n) and (Guard[i]^.s <= Time) do
begin
Insert(MaxHeap, Guard[i]);
Inc(i);
end;
if MaxHeap.nItems = 0 then Break;
G := Extract(MaxHeap);
G^.Selected := True;
Inc(res);
MinHeap.Items[1] := G;
DownHeap(MinHeap, 1);
until False;
if (Time < b) or (res < k) then res := -1;
end;
procedure PrintResult;
var
f: TextFile;
i: Integer;
begin
AssignFile(f, OutputFile); Rewrite(f);
try
WriteLn(f, res);
if res >= 0 then
for i := 1 to n do
if Guard[i]^.Selected then Write(f, Guard[i]^.id, ' ');
finally
CloseFile(f);
end;
end;
begin
Enter;
Sort(1, n);
Init;
Solve;
PrintResult;
end.
5 2 1 9
1 5
4 9
1 3
1 7
5 9
|
{$I ATViewerOptions.inc}
unit ATxREProc;
interface
uses
Windows, Classes, ComCtrls, Graphics;
function RE_CurrentLine(Edit: TRichEdit): Integer;
function RE_LineFromPos(Edit: TRichEdit; Pos: Integer): Integer;
function RE_PosFromLine(Edit: TRichEdit; Line: Integer): Integer;
procedure RE_ScrollToStart(Edit: TRichEdit);
procedure RE_ScrollToEnd(Edit: TRichEdit);
procedure RE_ScrollToPos(Edit: TRichEdit; Pos, IndentVert, IndentHorz: Integer);
procedure RE_ScrollToLine(Edit: TRichEdit; Line, Indent: Integer);
procedure RE_ScrollToPercent(Edit: TRichEdit; N: Integer);
procedure RE_LoadStream(Edit: TRichEdit;
AStream: TStream;
ASelStart, ASelLength: Integer);
procedure RE_LoadFile(Edit: TRichEdit;
const AFileName: WideString;
ASelStart, ASelLength: Integer);
procedure RE_Print(Edit: TRichEdit;
AOnlySel: Boolean;
ACopies: Integer;
const ACaption: string);
type
TRELastSearch = record
ResultStart,
ResultLength: Integer;
SavedText: string;
SavedOptions: TSearchTypes;
end;
procedure RE_HiAll(
AEdit: TRichEdit;
AC: TColor);
procedure RE_Hi(
AEdit: TRichEdit;
const AText: string;
AOptions: TSearchTypes;
AC: TColor);
function RE_FindFirst(
AEdit: TRichEdit;
const AText: string;
AStartPos: Integer;
AOptions: TSearchTypes;
AIndentVert,
AIndentHorz: Integer;
var ALastSearch: TRELastSearch): Boolean;
function RE_FindNext(
AEdit: TRichEdit;
AIndentVert,
AIndentHorz: Integer;
var ALastSearch: TRELastSearch): Boolean;
implementation
uses
SysUtils, Messages,
{$ifdef TNT} TntClasses, {$endif}
Printers, RichEdit,
ATxSProc, ATxFProc, ATViewerMsg;
function RE_CurrentLine(Edit: TRichEdit): Integer;
begin
Result := Edit.Perform(EM_GETFIRSTVISIBLELINE, 0, 0);
end;
function RE_LineFromPos(Edit: TRichEdit; Pos: Integer): Integer;
begin
Result := Edit.Perform(EM_EXLINEFROMCHAR, 0, Pos);
end;
function RE_PosFromLine(Edit: TRichEdit; Line: Integer): Integer;
begin
Result := Edit.Perform(EM_LINEINDEX, Line, 0);
end;
procedure RE_HScroll(Edit: TRichEdit; HPos: Integer);
begin
Edit.Perform(WM_HSCROLL, SB_THUMBPOSITION + (HPos shl 16), 0);
end;
function RE_HPos(Edit: TRichEdit; Pos: Integer): Integer;
var
Pnt: TPoint;
begin
FillChar(Pnt, SizeOf(Pnt), 0);
Edit.Perform(EM_POSFROMCHAR, Integer(@Pnt), Pos);
Result := Pnt.X;
end;
procedure RE_ScrollToStart(Edit: TRichEdit);
var
n: DWORD;
begin
repeat
n := Edit.Perform(EM_SCROLL, SB_PAGEUP, 0);
until (n and $FFFF) = 0;
RE_HScroll(Edit, 0);
end;
procedure RE_ScrollToEnd(Edit: TRichEdit);
var
n: DWORD;
begin
repeat
n := Edit.Perform(EM_SCROLL, SB_PAGEDOWN, 0);
until (n and $FFFF) = 0;
RE_HScroll(Edit, 0);
end;
procedure RE_ScrollToPos(Edit: TRichEdit; Pos, IndentVert, IndentHorz: Integer);
var
LineNum,
LineStart,
Pos2: Integer;
begin
RE_ScrollToStart(Edit);
LineNum := RE_LineFromPos(Edit, Pos);
LineStart := RE_PosFromLine(Edit, LineNum);
Dec(LineNum, IndentVert);
if LineNum < 0 then LineNum := 0;
Edit.Perform(EM_LINESCROLL, 0, LineNum);
//Horz scroll
if RE_HPos(Edit, Pos) >= Edit.ClientWidth then
begin
Pos2 := Pos - IndentHorz;
if Pos2 < LineStart then Pos2 := LineStart;
RE_HScroll(Edit, RE_HPos(Edit, Pos2));
end;
//Caret
Edit.SelStart := LineStart;
Edit.SelLength := 0;
end;
procedure RE_ScrollToLine(Edit: TRichEdit; Line, Indent: Integer);
begin
RE_ScrollToStart(Edit);
Dec(Line, Indent);
if Line < 0 then Line := 0;
Edit.Perform(EM_LINESCROLL, 0, Line);
//Caret
Edit.SelStart := RE_PosFromLine(Edit, Line);
Edit.SelLength := 0;
end;
procedure RE_ScrollToPercent(Edit: TRichEdit; N: Integer);
var
Num: Integer;
begin
if N <= 0 then
begin
RE_ScrollToStart(Edit);
Edit.SelStart := 0;
Edit.SelLength := 0;
end
else
if N >= 100 then
begin
RE_ScrollToEnd(Edit);
Edit.SelStart := RE_PosFromLine(Edit, Edit.Lines.Count - 1);
Edit.SelLength := 0;
end
else
begin
Num := (Edit.Lines.Count - 1) * N div 100;
if Num > 0 then
begin
RE_ScrollToLine(Edit, Num, 0);
Edit.SelStart := RE_PosFromLine(Edit, Num);
Edit.SelLength := 0;
end;
end;
end;
procedure RE_LoadStream(Edit: TRichEdit; AStream: TStream; ASelStart, ASelLength: Integer);
begin
AStream.Position := 0;
with Edit do
begin
MaxLength := MaxInt - 2; //fix to load 70K file
Lines.Clear;
Lines.LoadFromStream(AStream);
RE_ScrollToStart(Edit);
SelStart := ASelStart;
SelLength := ASelLength;
end;
end;
procedure RE_LoadFile(Edit: TRichEdit; const AFileName: WideString; ASelStart, ASelLength: Integer);
const
Sign: array[0 .. 2] of AnsiChar = #$EF#$BB#$BF;
var
IsRTF, IsUTF8: Boolean;
StreamFile, StreamData: TStream;
begin
IsFileRTFAndUTF8(AFileName, IsRTF, IsUTF8);
Edit.PlainText := not IsRTF;
with Edit do
if (Win32Platform = VER_PLATFORM_WIN32_NT) and
(not IsRTF) and (not IsUTF8) then
//Treat file as UTF8 and add missing UTF8 signature
begin
StreamFile := {$ifdef TNT}TTntFileStream{$else}TFileStream{$endif}.Create(AFileName, fmOpenRead or fmShareDenyNone);
StreamData := TMemoryStream.Create;
try
StreamData.WriteBuffer(Sign, Length(Sign));
StreamData.CopyFrom(StreamFile, 0);
RE_LoadStream(Edit, StreamData, 0, 0);
finally
FreeAndNil(StreamFile);
FreeAndNil(StreamData);
end;
end
else
//Treat file as is, RTF of UTF8 (UTF8 signature is present)
begin
StreamFile := {$ifdef TNT}TTntFileStream{$else}TFileStream{$endif}.Create(AFileName, fmOpenRead or fmShareDenyNone);
try
RE_LoadStream(Edit, StreamFile, 0, 0);
finally
FreeAndNil(StreamFile);
end;
end;
RE_ScrollToStart(Edit);
Edit.SelStart := ASelStart;
Edit.SelLength := ASelLength;
end;
procedure RE_Print(Edit: TRichEdit;
AOnlySel: Boolean;
ACopies: Integer;
const ACaption: string);
var
ASelStart, ASelLength: Integer;
begin
if ACopies <= 0 then
ACopies := 1;
Printer.Copies := ACopies;
Printer.Canvas.Font := Edit.Font;
if AOnlySel then
begin
ASelStart := Edit.SelStart;
ASelLength := Edit.SelLength;
Edit.SelStart := ASelStart + ASelLength;
Edit.SelLength := MaxInt;
Edit.SelText := '';
Edit.SelStart := 0;
Edit.SelLength := ASelStart;
Edit.SelText := '';
end;
Edit.Print(ACaption);
end;
function RE_FindText(
AEdit: TRichEdit;
const AText: string;
AStartPos: Integer;
AOptions: TSearchTypes;
AIndentVert, AIndentHorz: Integer;
var ALastSearch: TRELastSearch): Boolean;
var
Pos: Integer;
begin
with ALastSearch do
begin
ResultStart := -1;
ResultLength := 0;
SavedText := AText;
SavedOptions := AOptions;
end;
Pos := AEdit.FindText(AText, AStartPos, MaxInt - AStartPos, AOptions);
Result := Pos >= 0;
if Result then
begin
ALastSearch.ResultStart := Pos;
ALastSearch.ResultLength := Length(AText);
AEdit.Lines.BeginUpdate;
//We select text *after* scrolling
AEdit.SelStart := ALastSearch.ResultStart;
RE_ScrollToPos(AEdit, ALastSearch.ResultStart, AIndentVert, AIndentHorz);
AEdit.SelStart := ALastSearch.ResultStart;
AEdit.SelLength := ALastSearch.ResultLength;
AEdit.Lines.EndUpdate;
end;
end;
function CCor(C: TColor): TColor;
var
b: TBitmap;
begin
b := TBitmap.Create;
b.Width := 1;
b.Height := 1;
b.PixelFormat := pf24bit;
b.Canvas.Pixels[0, 0] := C;
Result := b.Canvas.Pixels[0, 0];
b.Free;
end;
procedure RE_HiAll(
AEdit: TRichEdit;
AC: TColor);
var
F: TCharFormat2;
begin
FillChar(F, SizeOf(F), 0);
F.cbSize := SizeOf(F);
F.crBackColor := CCor(AC);
F.dwMask := CFM_BACKCOLOR;
AEdit.Perform(EM_SETCHARFORMAT, SCF_ALL, Integer(@F));
end;
procedure RE_Hi(
AEdit: TRichEdit;
const AText: string;
AOptions: TSearchTypes;
AC: TColor);
var
S: TRELastSearch;
F: TCharFormat2;
p, pp: Integer;
begin
p := AEdit.SelStart;
pp := AEdit.SelLength;
FillChar(F, SizeOf(F), 0);
F.cbSize := SizeOf(F);
F.crBackColor := AC;
F.dwMask := CFM_BACKCOLOR;
if RE_FindFirst(AEdit, AText, 0, AOptions, 0, 0, S) then
repeat
AEdit.Perform(EM_SETCHARFORMAT, SCF_SELECTION, Integer(@F));
until not RE_FindNext(AEdit, 0, 0, S);
AEdit.SelStart := p;
AEdit.SelLength := pp;
end;
function RE_FindFirst(
AEdit: TRichEdit;
const AText: string;
AStartPos: Integer;
AOptions: TSearchTypes;
AIndentVert, AIndentHorz: Integer;
var ALastSearch: TRELastSearch): Boolean;
begin
Result := RE_FindText(
AEdit,
AText,
AStartPos,
AOptions,
AIndentVert,
AIndentHorz,
ALastSearch);
end;
function RE_FindNext(
AEdit: TRichEdit;
AIndentVert, AIndentHorz: Integer;
var ALastSearch: TRELastSearch): Boolean;
begin
with ALastSearch do
begin
Assert(SavedText <> '', 'Search text is empty');
Result := RE_FindText(
AEdit,
SavedText,
ResultStart + 1,
SavedOptions,
AIndentVert,
AIndentHorz,
ALastSearch);
end;
end;
end.
|
unit dcMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, ToolEdit,
evSCSub, evSCSubAttr, evSubCompareInterfaces, evSCSubAttrList, evSCSubList, evSCCollectFilter;
type
TForm1 = class(TForm)
fnFile1: TFilenameEdit;
fnFile2: TFilenameEdit;
btnDoJob: TButton;
Label1: TLabel;
memResult: TMemo;
procedure btnDoJobClick(Sender: TObject);
private
f_Differs: Boolean;
procedure OutString(const aStr: AnsiString; const aArgs: array of const);
procedure CompareAttrs(const aSub1, aSub2: IevSCSub);
procedure DoJob;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
k2TagGen,
k2Reader,
evdReader,
l3Filer,
l3Diff,
l3DiffSupport,
ddNSRC_r;
{$R *.dfm}
type
TFileType = (ftEVD, ftNSRC);
procedure TForm1.btnDoJobClick(Sender: TObject);
begin
DoJob;
end;
procedure TForm1.CompareAttrs(const aSub1, aSub2: IevSCSub);
function CompareAttr(I1: Integer; I2: Integer): Boolean;
var
l_A1, l_A2: IevSCAttrElement;
begin
l_A1 := aSub1.Attr[I1];
l_A2 := aSub2.Attr[I2];
Result := (l_A1.AttrType = l_A2.AttrType) and (l_A1.ID = l_A2.ID) and (l_A1.SubID = l_A2.SubID);
end;
procedure ReportAttr(const aARR: Tl3DiffReportRec);
var
l_AttrStr: AnsiString;
l_Attr: IevSCAttrElement;
begin
if aARR.rOp = l3diffSame then
Exit;
if aARR.rOp = l3diffDeleted then
l_Attr := aSub1.Attr[aARR.rLeftIdx]
else
l_Attr := aSub2.Attr[aARR.rRightIdx];
if l_Attr.AttrType = sca_Link then
l_AttrStr := Format('%s на документ %d.%d', [cSCAttrTypeName[l_Attr.AttrType], l_Attr.ID, l_Attr.SubID])
else
l_AttrStr := Format('%s (%d)', [cSCAttrTypeName[l_Attr.AttrType], l_Attr.ID]);
case aARR.rOp of
l3diffDeleted: OutString('Второй документ, %s с номером %d: отсутствует %s', [
cSCSubTypeName[aSub1.SubType],
aSub1.Handle,
l_AttrStr
]);
l3diffAdded : OutString('Первый документ, %s с номером %d: отсутствует %s', [
cSCSubTypeName[aSub1.SubType],
aSub1.Handle,
l_AttrStr
]);
end;
f_Differs := True;
end;
var
l_AttrCF: Tl3DiffCompareFunc;
l_AttrRP: Tl3DiffReportProc;
begin
l_AttrCF := l3L2CF(@CompareAttr);
try
l_AttrRP := l3L2RP(@ReportAttr);
try
L3DoDiff(aSub1.AttrCount, aSub2.AttrCount, l_AttrCF, l_AttrRP);
finally
l3FreeRP(l_AttrRP);
end;
finally
l3FreeCF(l_AttrCF);
end;
end;
procedure TForm1.OutString(const aStr: AnsiString; const aArgs: array of const);
begin
memResult.Lines.Insert(0, Format(aStr, aArgs));
end;
procedure TForm1.DoJob;
var
l_SubList1, l_SubList2: TevSCSubList;
l_Gen: Tk2TagGenerator;
l_CollectList: TevSCSubList;
l_Filer: Tl3DOSFiler;
I : Integer;
l_Ext1: AnsiString;
l_Ext2: AnsiString;
l_FT: TFileType;
l_SubCF: Tl3DiffCompareFunc;
l_SubRP: Tl3DiffReportProc;
function CompareSub(I: Integer; J: Integer): Boolean;
var
l_S1, l_S2: IevSCSub;
begin
l_S1 := l_SubList1.Items[I];
l_S2 := l_SubList2.Items[J];
Result := {(l_S1.SubType = l_S2.SubType) and} (l_S1.Handle = l_S2.Handle);
end;
procedure ReportSub(const aSRR: Tl3DiffReportRec);
var
l_Sub1, l_Sub2: IevSCSub;
begin
case aSRR.rOp of
l3diffSame:
begin
l_Sub1 := l_SubList1.Items[aSRR.rLeftIdx];
l_Sub2 := l_SubList2.Items[aSRR.rRightIdx];
if l_Sub1.SubType <> l_Sub2.SubType then
begin
OutString('В первом документе есть %s с номером %d, а во втором с этим номером - %s.', [
cSCSubTypeName[l_Sub1.SubType], l_Sub1.Handle, cSCSubTypeName[l_Sub2.SubType]
]);
f_Differs := True;
end
else
CompareAttrs(l_Sub1, l_Sub2);
end;
l3diffDeleted:
begin
l_Sub1 := l_SubList1.Items[aSRR.rLeftIdx];
OutString('Во втором документе отсутствует %s с номером %d', [cSCSubTypeName[l_Sub1.SubType], l_Sub1.Handle]);
f_Differs := True;
end;
l3diffAdded:
begin
l_Sub2 := l_SubList2.Items[aSRR.rRightIdx];
OutString('В первом документе отсутствует %s с номером %d', [cSCSubTypeName[l_Sub2.SubType], l_Sub2.Handle]);
f_Differs := True;
end;
end;
end;
begin
if not FileExists(fnFile1.FileName) then
begin
MessageDlg('Не найден файл первого документа!', mtError, [mbOk], 0);
Exit;
end;
if not FileExists(fnFile2.FileName) then
begin
MessageDlg('Не найден файл второго документа!', mtError, [mbOk], 0);
Exit;
end;
l_Ext1 := AnsiUpperCase(ExtractFileExt(fnFile1.FileName));
l_Ext2 := AnsiUpperCase(ExtractFileExt(fnFile2.FileName));
if l_Ext1 <> l_Ext2 then
begin
MessageDlg('Я не умею сравнивать файлы разных типов. Извините.', mtError, [mbOk], 0);
Exit;
end;
if (l_Ext1 = '.EVD') or (l_Ext1 = '.EVT') then
l_FT := ftEVD
else
{
if l_Ext1 = '.NSR' then
l_FT := ftNSRC
else }
begin
MessageDlg('Я умею сравнивать только файлы формата EVD.', mtError, [mbOk], 0);
Exit;
end;
l_SubList1 := TevSCSubList.Make;
l_SubList2 := TevSCSubList.Make;
f_Differs := False;
try
l_Gen := nil;
try
TevSCCollectFilter.SetTo(l_Gen);
l_CollectList := TevSCCollectFilter(l_Gen).SubList;
case l_FT of
ftEVD : TevdNativeReader.SetTo(l_Gen);
ftNSRC : TCustomNSRCReader.SetTo(l_Gen);
end;
l_Filer := Tl3DOSFiler.Make(fnFile1.FileName);
try
l_Filer.Open;
TevdNativeReader(l_Gen).Filer := l_Filer;
TevdNativeReader(l_Gen).Execute;
for I := 0 to l_CollectList.Count - 1 do
l_SubList1.Add(l_CollectList.Items[I]);
l_Filer.Close;
l_Filer.FileName := fnFile2.FileName;
l_Filer.Open;
Tk2CustomFileReader(l_Gen).Execute;
for I := 0 to l_CollectList.Count - 1 do
l_SubList2.Add(l_CollectList.Items[I]);
finally
FreeAndNil(l_Filer);
end;
finally
FreeAndNil(l_Gen);
end;
// данные набрали, теперь будем сравнивать
memResult.Clear;
l_SubCF := l3L2CF(@CompareSub);
try
l_SubRP := l3L2RP(@ReportSub);
try
L3DoDiff(l_SubList1.Count, l_SubList2.Count, l_SubCF, l_SubRP);
finally
l3FreeRP(l_SubRP);
end;
finally
l3FreeCF(l_SubCF);
end;
if not f_Differs then
OutString('Различий в документах не найдено.',[]);
finally
FreeAndNil(l_SubList1);
FreeAndNil(l_SubList2);
end;
end;
end.
|
unit csDeliveryProfileTask;
// Модуль: "w:\common\components\rtl\Garant\cs\csDeliveryProfileTask.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TcsDeliveryProfileTask" MUID: (57F4DAED0254)
{$Include w:\common\components\rtl\Garant\cs\CsDefine.inc}
interface
{$If NOT Defined(Nemesis)}
uses
l3IntfUses
, csProcessTask
, k2Base
;
type
TcsDeliveryProfileTask = class(TddProcessTask)
protected
function pm_GetTargetFolder: AnsiString;
procedure pm_SetTargetFolder(const aValue: AnsiString);
function pm_GetSourceFolder: AnsiString;
procedure pm_SetSourceFolder(const aValue: AnsiString);
function RequireDelivery: Boolean; override;
public
function DeliverySourceFolder: AnsiString; override;
function DeliveryTargetFolder: AnsiString; override;
function GetDescription: AnsiString; override;
class function GetTaggedDataType: Tk2Type; override;
public
property TargetFolder: AnsiString
read pm_GetTargetFolder
write pm_SetTargetFolder;
property SourceFolder: AnsiString
read pm_GetSourceFolder
write pm_SetSourceFolder;
end;//TcsDeliveryProfileTask
{$IfEnd} // NOT Defined(Nemesis)
implementation
{$If NOT Defined(Nemesis)}
uses
l3ImplUses
, DeliveryProfile_Const
//#UC START# *57F4DAED0254impl_uses*
//#UC END# *57F4DAED0254impl_uses*
;
function TcsDeliveryProfileTask.pm_GetTargetFolder: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrTargetFolder]);
end;//TcsDeliveryProfileTask.pm_GetTargetFolder
procedure TcsDeliveryProfileTask.pm_SetTargetFolder(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrTargetFolder, nil] := (aValue);
end;//TcsDeliveryProfileTask.pm_SetTargetFolder
function TcsDeliveryProfileTask.pm_GetSourceFolder: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrSourceFolder]);
end;//TcsDeliveryProfileTask.pm_GetSourceFolder
procedure TcsDeliveryProfileTask.pm_SetSourceFolder(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrSourceFolder, nil] := (aValue);
end;//TcsDeliveryProfileTask.pm_SetSourceFolder
function TcsDeliveryProfileTask.RequireDelivery: Boolean;
//#UC START# *57F603C6018A_57F4DAED0254_var*
//#UC END# *57F603C6018A_57F4DAED0254_var*
begin
//#UC START# *57F603C6018A_57F4DAED0254_impl*
Result := True;
//#UC END# *57F603C6018A_57F4DAED0254_impl*
end;//TcsDeliveryProfileTask.RequireDelivery
function TcsDeliveryProfileTask.DeliverySourceFolder: AnsiString;
//#UC START# *57F603E20074_57F4DAED0254_var*
//#UC END# *57F603E20074_57F4DAED0254_var*
begin
//#UC START# *57F603E20074_57F4DAED0254_impl*
Result := SourceFolder;
//#UC END# *57F603E20074_57F4DAED0254_impl*
end;//TcsDeliveryProfileTask.DeliverySourceFolder
function TcsDeliveryProfileTask.DeliveryTargetFolder: AnsiString;
//#UC START# *57F6040302FE_57F4DAED0254_var*
//#UC END# *57F6040302FE_57F4DAED0254_var*
begin
//#UC START# *57F6040302FE_57F4DAED0254_impl*
Result := TargetFolder;
//#UC END# *57F6040302FE_57F4DAED0254_impl*
end;//TcsDeliveryProfileTask.DeliveryTargetFolder
function TcsDeliveryProfileTask.GetDescription: AnsiString;
//#UC START# *57F639C2025B_57F4DAED0254_var*
//#UC END# *57F639C2025B_57F4DAED0254_var*
begin
//#UC START# *57F639C2025B_57F4DAED0254_impl*
Result := 'Проверка достваки папка: ' + TargetFolder;
//#UC END# *57F639C2025B_57F4DAED0254_impl*
end;//TcsDeliveryProfileTask.GetDescription
class function TcsDeliveryProfileTask.GetTaggedDataType: Tk2Type;
begin
Result := k2_typDeliveryProfile;
end;//TcsDeliveryProfileTask.GetTaggedDataType
{$IfEnd} // NOT Defined(Nemesis)
end.
|
unit DW.Form.Contents;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.Classes,
// FMX
FMX.Forms;
type
/// <summary>
/// Interposer class for TForm that allows the contents to be displayed in a control (such as TTabItem)
/// </summary>
/// <remarks>
/// Expects a TLayout to exist on the form called RootLayout
/// </remarks>
TForm = class(FMX.Forms.TForm)
private
FIsShown: Boolean;
procedure ReparentRootLayout(AOwner: TComponent);
protected
procedure FirstShow; virtual;
property IsShown: Boolean read FIsShown;
public
constructor Create(AOwner: TComponent); override;
/// <summary>
/// Sets IsShown to true. Used internally in Delphi Worlds projects
/// </summary>
procedure Shown;
end;
implementation
uses
FMX.Types, FMX.Controls;
{ TForm }
constructor TForm.Create(AOwner: TComponent);
begin
// Passing Application to the inherited Create works around a problem on (at least) Android
inherited Create(Application);
ReparentRootLayout(AOwner);
end;
procedure TForm.ReparentRootLayout(AOwner: TComponent);
var
LControl: TControl;
begin
LControl := TControl(FindComponent('RootLayout'));
if LControl <> nil then
begin
LControl.Align := TAlignLayout.Contents;
LControl.Parent := TFmxObject(AOwner);
end;
end;
procedure TForm.Shown;
begin
if not FIsShown then
FirstShow;
FIsShown := True;
end;
procedure TForm.FirstShow;
begin
//
end;
end.
|
unit DDrawPaletteFilters;
interface
uses
Classes, DirectDraw;
type
TPaletteFilter = (pfReddenPalette, pfTintPalette, pfColorToGray, pfRedFilter, pfGreenFilter);
function FilterPalette(const OrgPalette : IDirectDrawPalette; Filter : TPaletteFilter; Data : array of const) : IDirectDrawPalette;
implementation
uses
Windows;
type
TFilterRoutine = function (const Palette : IDirectDrawPalette; Data : array of const) : IDirectDrawPalette;
type
TFilterInfo =
record
FilterRoutine : TFilterRoutine;
end;
{
function ReddenPalette(const Palette : IDirectDrawPalette; Data : array of const) : IDirectDrawPalette;
var
ReddedPalette : IDirectDrawPalette;
i : integer;
begin
getmem(ReddedPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(ReddedPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
ReddedPalette[i].rgbRed := $FF;
ReddedPalette[i].rgbGreen := Palette.RGBPalette[i].rgbGreen;
ReddedPalette[i].rgbBlue := Palette.RGBPalette[i].rgbBlue;
end;
Result := ReddedPalette;
end;
function TintPalette(const Palette : IDirectDrawPalette; Data : array of const) : IDirectDrawPalette;
var
TintedPalette : IDirectDrawPalette;
i : integer;
red, green, blue : byte;
tintweight : extended;
begin
red := Data[0].VInteger;
green := Data[1].VInteger;
blue := Data[2].VInteger;
tintweight := Data[3].VExtended^;
getmem(TintedPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(TintedPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
TintedPalette[i].rgbRed := round(Palette.RGBPalette[i].rgbRed*(1 - tintweight) + red*tintweight);
TintedPalette[i].rgbGreen := round(Palette.RGBPalette[i].rgbGreen*(1 - tintweight) + green*tintweight);
TintedPalette[i].rgbBlue := round(Palette.RGBPalette[i].rgbBlue*(1 - tintweight) + blue*tintweight);
end;
Result := TintedPalette;
end;
function ColorToGray(const Palette : IDirectDrawPalette; Data : array of const) : IDirectDrawPalette;
var
GrayPalette : IDirectDrawPalette;
i : integer;
gray : integer;
begin
getmem(GrayPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(GrayPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
gray := (30*Palette.RGBPalette[i].rgbRed + 59*Palette.RGBPalette[i].rgbGreen + 11*Palette.RGBPalette[i].rgbBlue) div 100;
GrayPalette[i].rgbRed := gray;
GrayPalette[i].rgbGreen := gray;
GrayPalette[i].rgbBlue := gray;
end;
Result := GrayPalette;
end;
function RedFilter(const Palette : IDirectDrawPalette; Data : array of const) : IDirectDrawPalette;
var
RedPalette : IDirectDrawPalette;
i : integer;
begin
getmem(RedPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(RedPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
RedPalette[i].rgbRed := (30*Palette.RGBPalette[i].rgbRed + 59*Palette.RGBPalette[i].rgbGreen + 11*Palette.RGBPalette[i].rgbBlue) div 100;
RedPalette[i].rgbGreen := 0;
RedPalette[i].rgbBlue := 0;
end;
Result := RedPalette;
end;
function GreenFilter(const Palette : IDirectDrawPalette; Data : array of const) : IDirectDrawPalette;
var
GreenPalette : IDirectDrawPalette;
i : integer;
begin
getmem(GreenPalette, Palette.Count*sizeof(TRGBQuad));
fillchar(GreenPalette^, Palette.Count*sizeof(TRGBQuad), 0);
for i := 0 to pred(Palette.Count) do
begin
GreenPalette[i].rgbRed := 0;
GreenPalette[i].rgbGreen := (30*Palette.RGBPalette[i].rgbRed + 59*Palette.RGBPalette[i].rgbGreen + 11*Palette.RGBPalette[i].rgbBlue) div 100;
GreenPalette[i].rgbBlue := 0;
end;
Result := GreenPalette;
end;
const
AvailableFilters : array[TPaletteFilter] of TFilterInfo =
(
(FilterRoutine : ReddenPalette),
(FilterRoutine : TintPalette),
(FilterRoutine : ColorToGray),
(FilterRoutine : RedFilter),
(FilterRoutine : GreenFilter)
);
}
function FilterPalette(const OrgPalette : IDirectDrawPalette; Filter : TPaletteFilter; Data : array of const) : IDirectDrawPalette;
begin
//Result := OrgPalette.FilteredPalette(AvailableFilters[Filter].FilterRoutine, Data);
Result := nil;
end;
end.
|
unit TestStUtils;
interface
uses
SysUtils, TestFramework;
type
TTestStUtils = class(TTestCase)
strict private type
TStruct = record
Left: Integer;
Right: Integer;
end;
TWordStruct = record
Left: Word;
Right: Word;
end;
published
procedure TestExchangeLongInts;
procedure TestExchangeStructs;
procedure TestFillWord;
end;
implementation
uses
StUtils;
{ TTestStUtils }
procedure TTestStUtils.TestExchangeLongInts;
var
iLeft, iRight: Integer;
begin
iLeft := 2;
iRight := 3;
ExchangeLongInts(iLeft, iRight);
Check(iLeft = 3);
Check(iRight = 2);
end;
procedure TTestStUtils.TestExchangeStructs;
var
pLeft: TStruct;
pRight: TStruct;
begin
pLeft.Left := 1;
pLeft.Right := 2;
pRight.Left := 3;
pRight.Right := 4;
ExchangeStructs(pLeft, pRight, SizeOf(TStruct));
Check(pLeft.Left = 3);
Check(pLeft.Right = 4);
Check(pRight.Left = 1);
Check(pRight.Right = 2);
end;
procedure TTestStUtils.TestFillWord;
var
pStruct: TWordStruct;
iWord: Word;
begin
pStruct.Left := 1;
pStruct.Right := 2;
iWord := 3;
// FillWord(pStruct, SizeOf(pStruct), iWord);
FillWord(pStruct, 2, iWord);
Check(pStruct.Left = 3);
Check(pStruct.Right = 3);
end;
initialization
RegisterTest(TTestStUtils.Suite);
end.
|
program primitiveCalculator;
var
sign : char;
a, b, ans : integer;
{}
begin
write('Please enter a sign (+, -, *, /, %): ');
read(sign);
write('Enter two values: ');
read(a, b);
case sign of
'+':
ans := a + b;
'-':
ans := a - b;
'*':
ans := a * b;
'/':
ans := a div b;
'%':
ans := a mod b;
else
begin
sign := 'a';
writeln('Wrong sign.')
end;
end;
if sign <> 'a' then
writeln(a, ' ', sign, ' ', b, ' = ', ans);
end.
|
unit MainExpress;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, MainLiteExpress, StdActns, ActnList, evAction, dxBar,
l3InternalInterfaces, l3Base,
l3ProgressComponent, l3Filer, k2Reader, evEvdRd, k2TagGen, k2DocumentGenerator,
evdWriter, ImgList, OvcBase, evSubPn, l3InterfacedComponent,
evSaveDocumentManager, evLoadDocumentManager, dxBarExtItems, StdCtrls,
vtCtrls;
type
TMainExpressForm = class(TMainLiteExpressForm)
acBold: TevAction;
acItalic: TevAction;
acUnderline: TevAction;
acStrikeout: TevAction;
acSubscript: TevAction;
acSuperscript: TevAction;
btBold: TdxBarButton;
btItalic: TdxBarButton;
btUnderline: TdxBarButton;
btStrikeout: TdxBarButton;
btSubscript: TdxBarButton;
btSuperscript: TdxBarButton;
cbFontName: TdxBarFontNameCombo;
ccFontSize: TdxBarControlContainerItem;
cbFontSize: TFontSizeComboBox;
procedure cbFontNameChange(Sender: TObject);
procedure cbFontSizeChange(Sender: TObject);
private
{ Private declarations }
f_FreezeFont : Boolean;
public
{ Public declarations }
procedure EditorWindowFontChange(const Font: Il3Font);
override;
{-}
procedure UpdateItems;
override;
{-}
procedure CloseMDIChild(Form: TForm);
override;
{-}
end;
implementation
uses
l3Draw_TLB
;
{$R *.dfm}
procedure TMainExpressForm.EditorWindowFontChange(const Font: Il3Font);
var
F : Il3FontInfo;
begin
inherited;
f_FreezeFont := true;
try
if l3IOk(Font.QueryInterface(Il3FontInfo, F)) then
try
cbFontName.Text := F.Name;
// ColorComboBox.Selected := F.ForeColor;
// BackColorComboBox.Selected := F.BackColor;
cbFontSize.FontSize := F.Size;
finally
F := nil;
end;{try..finally}
finally
f_FreezeFont := false;
end;{try..finally}
end;
procedure TMainExpressForm.cbFontNameChange(Sender: TObject);
//var
// ActChild : TForm;
begin
if not f_FreezeFont then begin
// ActChild := ActiveMDIChild;
// if (ActChild <> nil) then Windows.SetFocus(ActChild.Handle);
if (ActiveEditor <> nil) then begin
cbFontSize.FontName:= cbFontName.Text;
ActiveEditor.Editor.TextPara.Font.Name := cbFontName.Text;
end;{ActiveEditor <> nil}
end;//not f_FreezeFont
end;
procedure TMainExpressForm.cbFontSizeChange(Sender: TObject);
var
ActChild : TForm;
begin
if not f_FreezeFont then begin
ActChild := ActiveMDIChild;
if ActChild <> nil then Windows.SetFocus(ActChild.Handle);
if (ActiveEditor <> nil) then
try
ActiveEditor.Editor.TextPara.Font.Size := cbFontSize.FontSize;
except
EditorWindowFontChange(ActiveEditor.Editor.TextPara.Font);
end;
end;//not f_FreezeFont
end;
procedure TMainExpressForm.UpdateItems;
//override;
{-}
begin
inherited;
cbFontName.Enabled := true;
ccFontSize.Enabled := true;
cbFontSize.Enabled := true;
end;
procedure TMainExpressForm.CloseMDIChild(Form: TForm);
//override;
{-}
begin
inherited;
with liMDIChildren.Items do begin
cbFontName.Enabled := (Count > 0);
ccFontSize.Enabled := (Count > 0);
cbFontSize.Enabled := (Count > 0);
end;//with liMDIChildren.Items
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.2 7/6/2004 4:53:52 PM DSiders
Corrected spelling of Challenge in properties, methods, types.
Rev 1.1 4/12/2003 10:24:10 PM GGrieve
Fix to Compile
Rev 1.0 11/13/2002 08:04:22 AM JPMugaas
}
{*******************************************************}
{ }
{ Indy OTP User Account Manager }
{ }
{ Copyright (C) 2000 Winshoes Working Group }
{ Original author J. Peter Mugaas }
{ 2002-Nov-2 }
{ Based on RFC 2289 }
{ }
{*******************************************************}
{
Note: One vulnerability in OTP is a race condition where
a user connects to a server, gets a Challenge, then a hacker
connects to the system and then the hacker guesses the OTP password.
To prevent this, servers should not allow a user to connect to the server
during the authentication process.
}
{2002-Nov-3 J. Peter Mugaas
-Renamed units and classes from SKey to OTP. SKey is a
trademark of BellCore. One Time Only (OTP is a more accurate description anyway.
-Made properties less prone to entry errors
-Now disregards white space with OTP
-Will now accept the OTP Password as Hexidecimal
-Will now accept the OTP Password in either lower or uppercase }
unit IdUserAccountsOTP;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdBaseComponent,
IdComponent,
IdException,
IdUserAccounts,
IdGlobal, SysUtils;
const
DEF_MAXCount = 900;
type
TIdOTPUserManager = class;
TIdOTPUserAccounts = class;
TIdOTPPassword = (IdPW_NoEncryption, IdPW_OTP_MD4, IdPW_OTP_MD5, IdPW_OTP_SHA1);
TIdOTPUserAccount = class(TIdUserAccount)
protected
FPasswordType : TIdOTPPassword;
FCurrentCount : LongWord;
FSeed : String;
FAuthenticating : Boolean;
FNoReenter : TCriticalSection;
procedure SetSeed(const AValue : String);
procedure SetPassword(const AValue: String); override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
function CheckPassword(const APassword: String): Boolean; override;
published
property CurrentCount : LongWord read FCurrentCount write FCurrentCount;
property Seed : String read FSeed write SetSeed;
property PasswordType : TIdOTPPassword read FPasswordType write FPasswordType;
property Authenticating : Boolean read FAuthenticating write FAuthenticating;
end;
TIdOTPUserAccounts = class(TOwnedCollection)
protected
//
function GetAccount(const AIndex: Integer): TIdOTPUserAccount;
function GetByUsername(const AUsername: String): TIdOTPUserAccount;
procedure SetAccount(const AIndex: Integer; AAccountValue: TIdOTPUserAccount);
public
function Add: TIdOTPUserAccount; reintroduce;
constructor Create(AOwner: TIdOTPUserManager); reintroduce;
//
property UserNames[const AUserName: String]: TIdOTPUserAccount read GetByUsername; default;
property Items[const AIndex: Integer]: TIdOTPUserAccount read GetAccount write SetAccount;
end;//TIdOTPUserAccounts
TIdOTPUserManager = class(TIdCustomUserManager)
protected
FMaxCount : LongWord;
FAccounts : TIdOTPUserAccounts;
FDefaultPassword : String;
procedure DoAuthentication(const AUsername: String; var VPassword: String;
var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess); override;
procedure SetMaxCount(const AValue: LongWord);
procedure SetDefaultPassword(const AValue : String);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure UserDisconnected(const AUser : String); override;
function SendsChallange : Boolean; override;
property Accounts : TIdOTPUserAccounts read FAccounts;
published
property DefaultPassword : String read FDefaultPassword write SetDefaultPassword;
property MaxCount : LongWord read FMaxCount write SetMaxCount default DEF_MAXCount;
end;
EIdOTPException = class(EIdException);
EIdOTPInvalidSeed = class(EIdOTPException);
EIdOTPInvalidCount = class(EIdOTPException);
EIdOTPInvalidPassword = class(EIdOTPException);
function GenerateSeed : String;
implementation
uses
IdOTPCalculator;
resourcestring
RSOTP_Challenge = 'Response to %s required for OTP.';
RSOTP_SeedBadFormat = 'The seed must be alphanumeric and it must at least 1 character but no more than 16 characters.';
RSOTP_InvalidCount = 'The count must be greater than 1.';
RSOTP_InvalidPassword = 'The password must be longer than 10 characters but no more than 63 characters.';
//This must be longer than 9 characters but no more than 63 characters in length
RSOTP_DefaultPassword = 'PleaseChangeMeNow';
const
CharMap = 'abcdefghijklmnopqrstuvwxyz1234567890'; {Do not Localize}
function GetRandomString(NumChar: LongWord): string;
var
i: Integer;
MaxChar: LongWord;
begin
randomize;
MaxChar := Length(CharMap) - 1;
for i := 1 to NumChar do begin
// Add one because CharMap is 1-based
Result := Result + CharMap[Random(maxChar) + 1];
end;
end;
function IsValidPassword(const AValue : String): Boolean;
begin
Result := (Length(AValue) > 9) and (Length(AValue) < 64);
end;
function IsValidSeed(const ASeed : String) : Boolean;
var
i : Integer;
begin
Result := (ASeed <> '') and (Length(ASeed) < 17);
if Result then begin
for i := 1 to Length(ASeed) do begin
if not CharIsInSet(ASeed, i, CharMap) then begin
Result := False;
Break;
end;
end;
end;
end;
function GenerateSeed : String;
begin
Randomize;
Result := GetRandomString(Random(15)+1);
end;
function LowStripWhiteSpace(const AString : String): String;
var
i : Integer;
begin
Result := '';
for i := 1 to Length(AString) do begin
if not (AString[i] in LWS) then begin
Result := Result + LowerCase(AString[i]);
end;
end;
end;
{ TIdOTPUserManager }
function TIdOTPUserManager.ChallengeUser(var VIsSafe: Boolean; const AUserName: String): String;
var
LUser : TIdOTPUserAccount;
begin
Result := '';
LUser := FAccounts.UserNames[AUserName];
if (not Assigned(LUser)) or (LUser.PasswordType = IdPW_NoEncryption) then begin
Exit;
end;
VIsSafe := not LUser.Authenticating;
if VIsSafe then begin
//Note that we want to block any attempts to access the server after the challanage
//is given. This is required to prevent a race condition that a hacker can
//exploit.
LUser.FNoReenter.Acquire;
try
LUser.Authenticating := True;
Result := 'otp-'; {Do not translate}
case LUser.PasswordType of
IdPW_OTP_MD4 : Result := Result + 'md4 '; {Do not translate}
IdPW_OTP_MD5 : Result := Result + 'md5 '; {Do not translate}
IdPW_OTP_SHA1 : Result := Result + 'sha1 '; {Do not translate}
end;
Result := Result + IntToStr(LUser.CurrentCount) + ' ' + LUser.Seed;
Result := IndyFormat(RSOTP_Challenge, [Result]);
finally
LUser.FNoReenter.Release;
end;
end;
end;
constructor TIdOTPUserManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAccounts := TIdOTPUserAccounts.Create(Self);
FMaxCount := DEF_MAXCount;
FDefaultPassword := RSOTP_DefaultPassword;
end;
destructor TIdOTPUserManager.Destroy;
begin
FreeAndNil(FAccounts);
inherited Destroy;;
end;
procedure TIdOTPUserManager.DoAuthentication(const AUsername: String;
var VPassword: String; var VUserHandle: TIdUserHandle; var VUserAccess: TIdUserAccess);
var
LUser: TIdUserAccount;
begin
inherited DoAuthentication(AUsername, VPassword, VUserHandle, VUserAccess);
VUserHandle := IdUserHandleNone;
VUserAccess := IdUserAccessDenied;
LUser := FAccounts[AUsername];
if Assigned(LUser) then begin
if LUser.CheckPassword(VPassword) then begin
VUserHandle := LUser.ID;
VUserAccess := LUser.Access;
end;
end;
end;
procedure TIdOTPUserManager.LoadUserAccounts(const AIniFile: String);
begin
end;
procedure TIdOTPUserManager.SaveUserAccounts(const AIniFile: String);
begin
end;
procedure TIdOTPUserManager.SetDefaultPassword(const AValue: String);
begin
if not IsValidPassword(AValue) then begin
EIdOTPInvalidPassword.Toss(RSOTP_InvalidPassword);
end;
FDefaultPassword := AValue;
end;
procedure TIdOTPUserManager.SetMaxCount(const AValue: LongWord);
begin
if AValue <= 1 then begin
EIdOTPInvalidCount.Toss(RSOTP_InvalidCount);
end;
FMaxCount := AValue;
end;
procedure TIdOTPUserManager.UserDisconnected(const AUser: String);
var
LUser : TIdOTPUserAccount;
begin
inherited UserDisconnected(AUser);
LUser := FAccounts.UserNames[AUserName];
if Assigned(LUser) then begin
LUser.Authenticating := False;
end;
end;
{ TIdOTPUserAccounts }
function TIdOTPUserAccounts.Add: TIdOTPUserAccount;
begin
Result := inherited Add as TIdOTPUserAccount;
Result.Seed := GenerateSeed;
Result.CurrentCount := TIdOTPUserManager(GetOwner).MaxCount;
Result.Password := TIdOTPUserManager(GetOwner).DefaultPassword;
end;
constructor TIdOTPUserAccounts.Create(AOwner: TIdOTPUserManager);
begin
inherited Create(AOwner, TIdOTPUserAccount);
end;
function TIdOTPUserAccounts.GetAccount(const AIndex: Integer): TIdOTPUserAccount;
begin
Result := TIdOTPUserAccount(inherited Items[AIndex]);
end;
function TIdOTPUserAccounts.GetByUsername(const AUsername: String): TIdOTPUserAccount;
var
i: Integer;
begin
Result := nil;
for i := 0 to Count - 1 do begin
if AUsername = Items[i].UserName then begin
Result := Items[i];
Break;
end;
end;
end;
procedure TIdOTPUserAccounts.SetAccount(const AIndex: Integer; AAccountValue: TIdOTPUserAccount);
begin
inherited SetItem(AIndex, AAccountValue);
end;
{ TIdOTPUserAccount }
function TIdOTPUserAccount.CheckPassword(const APassword: String): Boolean;
var
LWordOTP : String;
LHashSum : Int64;
LRecPass : String;
LHexOTP : String;
begin
LHexOTP := '';
LRecPass := APassword;
case FPasswordType of
IdPW_NoEncryption :
begin
LWordOTP := Password;
end;
IdPW_OTP_MD4 :
begin
LRecPass := LowStripWhiteSpace(APassword);
LHashSum := TIdOTPCalculator.GenerateKeyMD4(FSeed, Password, FCurrentCount);
LWordOTP := LowStripWhiteSpace(TIdOTPCalculator.ToSixWordFormat(LHashSum));
LHexOTP := LowStripWhiteSpace(TIdOTPCalculator.ToHex(LHashSum));
end;
IdPW_OTP_MD5 :
begin
LRecPass := LowStripWhiteSpace(APassword);
LHashSum := TIdOTPCalculator.GenerateKeyMD5(FSeed, Password, FCurrentCount);
LWordOTP := LowStripWhiteSpace(TIdOTPCalculator.ToSixWordFormat(LHashSum));
LHexOTP := LowStripWhiteSpace(TIdOTPCalculator.ToHex(LHashSum));
end;
IdPW_OTP_SHA1 :
begin
LRecPass := LowStripWhiteSpace(APassword);
LHashSum := TIdOTPCalculator.GenerateKeySHA1(FSeed, Password, FCurrentCount);
LWordOTP := LowStripWhiteSpace(TIdOTPCalculator.ToSixWordFormat(LHashSum));
LHexOTP := LowStripWhiteSpace(TIdOTPCalculator.ToHex(LHashSum));
end;
end;
Result := (LRecPass = LWordOTP);
if (not Result) and (LHexOTP <> '') then begin
Result := (LRecPass = LHexOTP);
end;
if Result then begin
FNoReenter.Acquire;
try
if CurrentCount = 0 then begin
Seed := GenerateSeed;
end else begin
Dec(FCurrentCount);
end;
Authenticating := False;
finally
FNoReenter.Release;
end;
end;
end;
constructor TIdOTPUserAccount.Create(Collection: TIdCollection);
begin
inherited Create(Collection);
FNoReenter := TCriticalSection.Create;
end;
destructor TIdOTPUserAccount.Destroy;
begin
FreeAndNil(FNoReenter);
inherited Destroy;
end;
procedure TIdOTPUserAccount.SetPassword(const AValue: String);
begin
if not IsValidPassword(AValue) then begin
EIdOTPInvalidPassword.Toss(RSOTP_InvalidPassword);
end;
inherited SetPassword(AValue);
end;
procedure TIdOTPUserAccount.SetSeed(const AValue: String);
begin
if not IsValidSeed(LowerCase(AValue)) then begin
EIdOTPInvalidSeed.Toss(RSOTP_SeedBadFormat);
end;
FSeed := LowerCase(AValue);
FCurrentCount := TIdOTPUserManager(TIdOTPUserAccounts(Collection).GetOwner).MaxCount;
end;
function TIdOTPUserAccount.SendsChallange : Boolean;
begin
Result := True;
end;
end.
|
unit uMainDM;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.IB,
FireDAC.Phys.IBDef, FireDAC.FMXUI.Wait, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, FireDAC.Phys.IBBase, FireDAC.Comp.UI,
REST.Backend.EMSServices, REST.Backend.EMSFireDAC, REST.Backend.EMSProvider,
FireDAC.Stan.StorageJSON, REST.Types, REST.Client, REST.Response.Adapter,
Data.Bind.Components, Data.Bind.ObjectScope;
type
TMainDM = class(TDataModule)
cnnMastSQL: TFDConnection;
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;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDPhysIBDriverLink1: TFDPhysIBDriverLink;
memRemoteChanges: TFDMemTable;
memRemoteChangesCUSTNO: TFloatField;
memRemoteChangesCOMPANY: TStringField;
memRemoteChangesADDR1: TStringField;
memRemoteChangesADDR2: TStringField;
memRemoteChangesCITY: TStringField;
memRemoteChangesSTATE: TStringField;
memRemoteChangesZIP: TStringField;
memRemoteChangesCOUNTRY: TStringField;
memRemoteChangesPHONE: TStringField;
memRemoteChangesFAX: TStringField;
memRemoteChangesTAXRATE: TFloatField;
memRemoteChangesCONTACT: TStringField;
memRemoteChangesLASTINVOICEDATE: TSQLTimeStampField;
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
qryLocalChanges: TFDQuery;
qryLocalChangesCUSTNO: TFloatField;
qryLocalChangesCOMPANY: TStringField;
qryLocalChangesADDR1: TStringField;
qryLocalChangesADDR2: TStringField;
qryLocalChangesCITY: TStringField;
qryLocalChangesSTATE: TStringField;
qryLocalChangesZIP: TStringField;
qryLocalChangesCOUNTRY: TStringField;
qryLocalChangesPHONE: TStringField;
qryLocalChangesFAX: TStringField;
qryLocalChangesTAXRATE: TFloatField;
qryLocalChangesCONTACT: TStringField;
qryLocalChangesLASTINVOICEDATE: TSQLTimeStampField;
FDTransSnapshot: TFDTransaction;
cnnMastSQLDelta: TFDConnection;
RESTClientSync: TRESTClient;
RESTRequestGET: TRESTRequest;
RESTResponseGET: TRESTResponse;
RESTRequestPOST: TRESTRequest;
RESTResponsePOST: TRESTResponse;
procedure qryCustomerAfterDelete(DataSet: TDataSet);
procedure qryCustomerAfterPost(DataSet: TDataSet);
procedure qryCustomerAfterCancel(DataSet: TDataSet);
procedure cnnMastSQLBeforeConnect(Sender: TObject);
procedure RESTRequestGETAfterExecute(Sender: TCustomRESTRequest);
private
{ Private declarations }
fDeviceName: string;
public
{ Public declarations }
property DeviceName: string read fDeviceName write fDeviceName;
procedure GetRemoteChanges;
procedure GetLocalChanges;
procedure ApplyAllChanges;
end;
var
MainDM: TMainDM;
const
fSyncUser: string = 'USER3';
fSyncPass: string = '123';
fLocalUser: string = 'SYSDBA';
fLocalPass: string = 'masterkey';
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
uses System.IOUtils;
procedure TMainDM.cnnMastSQLBeforeConnect(Sender: TObject);
procedure SetupDatabase(fCnn: TFDConnection; fUser, fPass: string);
begin
fCnn.Params.UserName := fUser;
fCnn.Params.Password := fPass;
fCnn.Params.Database := TPath.GetDocumentsPath + PathDelim +
'MASTSQL2020MOB.IB';
fCnn.Params.Values['Protocol'] := 'local';
fCnn.Params.Values['Server'] := '';
end;
begin
{$IFDEF MSWINDOWS}
//
{$ELSE}
SetupDatabase(cnnMastSQL, fLocalUser, fLocalPass);
SetupDatabase(cnnMastSQLDelta, fSyncUser, fSyncPass);
{$ENDIF}
end;
procedure TMainDM.GetRemoteChanges;
begin
try
RESTRequestGET.Params.Clear;
RESTRequestGET.AddParameter('DeviceName', fDeviceName, pkGETorPOST);
RESTRequestGET.AddParameter('DBUser', fSyncUser, pkGETorPOST);
RESTRequestGET.AddParameter('DBPass', fSyncPass, pkGETorPOST);
RESTRequestGET.Execute;
except
on E: Exception do
raise Exception.Create('Error Message:' + E.Message);
end;
end;
procedure TMainDM.GetLocalChanges;
begin
try
cnnMastSQLDelta.Open;
cnnMastSQLDelta.StartTransaction;
cnnMastSQLDelta.ExecSQL('SET SUBSCRIPTION CUSTOMER_SUB AT ' +
QuotedSTR(fDeviceName) + ' ACTIVE');
qryLocalChanges.Open;
if qryLocalChanges.RecordCount > 0 then
cnnMastSQLDelta.Rollback;
except
on E: Exception do
raise Exception.Create('Error Message:' + E.Message);
end;
end;
procedure TMainDM.ApplyAllChanges;
var
fMemoryStream: TMemoryStream;
begin
// sending local changes to the remote database
if qryLocalChanges.Active and (qryLocalChanges.RecordCount > 0) then
begin
try
fMemoryStream := TMemoryStream.Create;
try
qryLocalChanges.SaveToStream(fMemoryStream, TFDStorageFormat.sfJSON);
RESTRequestPOST.Body.ClearBody;
RESTRequestPOST.Body.Add(fMemoryStream,
TRESTContentType.ctAPPLICATION_JSON);
RESTRequestPOST.Params.Clear;
RESTRequestPOST.AddParameter('DeviceName', fDeviceName, pkGETorPOST);
RESTRequestPOST.AddParameter('DBUser', fSyncUser, pkGETorPOST);
RESTRequestPOST.AddParameter('DBPass', fSyncPass, pkGETorPOST);
RESTRequestPOST.Execute;
if RESTResponsePOST.StatusCode = 200 then
begin
if cnnMastSQLDelta.InTransaction then
cnnMastSQLDelta.Commit;
end
else
raise Exception.Create('Response status code/message: ' +
RESTResponsePOST.StatusCode.ToString + '/' +
RESTResponsePOST.StatusText);
except
on E: Exception do
raise Exception.Create('Post error:' + E.Message);
end;
finally
if Assigned(fMemoryStream) then
FreeAndNil(fMemoryStream);
end;
end;
// applying remote changes in the local database
if memRemoteChanges.Active and (memRemoteChanges.RecordCount > 0) then
begin
try
qryCustomer.DisableControls;
qryLocalChanges.DisableControls;
try
qryCustomer.Open;
qryCustomer.MergeDataSet(memRemoteChanges,
TFDMergeDataMode.dmDeltaMerge, TFDMergeMetaMode.mmUpdate);
if qryCustomer.ChangeCount > 0 then
qryCustomer.ApplyUpdates(-1);
// defining the local check point
cnnMastSQLDelta.Open;
cnnMastSQLDelta.StartTransaction;
cnnMastSQLDelta.ExecSQL('SET SUBSCRIPTION CUSTOMER_SUB AT ' +
QuotedSTR(fDeviceName) + ' ACTIVE');
qryLocalChanges.Open;
cnnMastSQLDelta.Commit;
except
on E: Exception do
begin
cnnMastSQL.Rollback;
raise Exception.Create('Error Message:' + E.Message);
end;
end;
finally
qryCustomer.Close;
qryCustomer.EnableControls;
qryLocalChanges.Close;
qryLocalChanges.EnableControls;
end;
end;
end;
procedure TMainDM.qryCustomerAfterCancel(DataSet: TDataSet);
begin
TFDQuery(DataSet).CancelUpdates;
end;
procedure TMainDM.qryCustomerAfterDelete(DataSet: TDataSet);
begin
TFDQuery(DataSet).ApplyUpdates(-1);
end;
procedure TMainDM.qryCustomerAfterPost(DataSet: TDataSet);
begin
TFDQuery(DataSet).ApplyUpdates(-1);
end;
procedure TMainDM.RESTRequestGETAfterExecute(Sender: TCustomRESTRequest);
var
fStringStream: TStringStream;
begin
fStringStream := TStringStream.Create(RESTResponseGET.Content);
try
fStringStream.Position := 0;
memRemoteChanges.LoadFromStream(fStringStream, TFDStorageFormat.sfJSON);
finally
fStringStream.Free;
end;
end;
end.
|
{
This file is part of the Free Pascal run time library.
Copyright (c) 1999-2014 by Maciej Izak aka hnb (NewPascal project)
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
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.
**********************************************************************}
unit Nullable;
{$MODE DELPHI}
interface
uses
SysUtils;
type
TNullable<T: record> = record
public type
PT = ^T;
strict private
Instance: ^T default;
function GetValue: T;
public
property Value: T read GetValue;
function HasValue: Boolean; inline;
function GetValueOrDefault: T;
class operator Implicit(A: T): TNullable<T>;
class operator Implicit(A: TNullable<T>): T;
class operator Implicit(A: PT): TNullable<T>;
class operator Equal(A: TNullable<T>; B: PT): Boolean;
class operator Equal(A: TNullable<T>; B: T): Boolean;
class operator Initialize(var A: TNullable<T>);
class operator Finalize(var A: TNullable<T>);
class operator Copy(constref Src: TNullable<T>; var Dest: TNullable<T>);
class operator AddRef(var Rec: TNullable<T>);
end;
implementation
function TNullable<T>.GetValue: T;
begin
Result := Instance^;
end;
function TNullable<T>.HasValue: Boolean;
begin
Result := Instance <> nil;
end;
function TNullable<T>.GetValueOrDefault: T;
begin
if Instance <> nil then
Result := Instance^
else
Result := Default(T);
end;
class operator TNullable<T>.Equal(A: TNullable<T>; B: T): Boolean;
begin
Result := Assigned(A.Instance);
if Result then
Result := A.Instance^ = B
end;
class operator TNullable<T>.Equal(A: TNullable<T>; B: PT): Boolean;
begin
if Assigned(A.Instance) and Assigned(B) then
Result := A.Instance^ = B^
else
Result := not Assigned(A.Instance) and not Assigned(B);
end;
class operator TNullable<T>.Implicit(A: T): TNullable<T>;
begin
New(Result.Instance);
Result.Instance^ := A;
end;
class operator TNullable<T>.Implicit(A: TNullable<T>): T;
begin
Result := A.GetValueOrDefault;
end;
class operator TNullable<T>.Implicit(A: PT): TNullable<T>;
begin
if Assigned(A) then
begin
New(Result.Instance);
Result.Instance^ := PT((@A)^)^;
end;
end;
class operator TNullable<T>.Initialize(var A: TNullable<T>);
begin
A.Instance := nil;
end;
class operator TNullable<T>.Finalize(var A: TNullable<T>);
begin
if Assigned(A.Instance) then
Dispose(A.Instance);
end;
class operator TNullable<T>.Copy(constref Src: TNullable<T>; var Dest: TNullable<T>);
begin
if Assigned(Dest.Instance) and Assigned(Src.Instance) then
Dest.Instance^ := Src.Instance^
else
if Assigned(Dest.Instance) and not Assigned(Src.Instance) then
begin
Dispose(Dest.Instance);
Dest.Instance := nil;
end
else
if not Assigned(Dest.Instance) and Assigned(Src.Instance) then
begin
New(Dest.Instance);
Dest.Instance^ := Src.Instance^;
end;
end;
class operator TNullable<T>.AddRef(var Rec: TNullable<T>);
var
Tmp: T;
begin
if Rec.Instance <> nil then
begin
Tmp := Rec.Instance^;
New(Rec.Instance);
Rec.Instance^ := Tmp;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.