text stringlengths 14 6.51M |
|---|
unit DivOpNewtonTest;
interface
uses
DUnitX.TestFramework,
Math,
TestHelper,
uEnums,
uIntXLibTypes,
uIntX;
type
[TestFixture]
TDivOpNewtonTest = class(TObject)
private
F_length: Integer;
const
StartLength = Integer(1024);
LengthIncrement = Integer(101);
RepeatCount = Integer(10);
RandomStartLength = Integer(1024);
RandomEndLength = Integer(2048);
RandomRepeatCount = Integer(25);
function GetAllOneDigits(mlength: Integer): TIntXLibUInt32Array;
function GetRandomDigits(out digits2: TIntXLibUInt32Array)
: TIntXLibUInt32Array;
procedure NextBytes(var bytes: TArray<Byte>);
public
[Setup]
procedure Setup;
[Test]
procedure CompareWithClassic();
[Test]
procedure CompareWithClassicRandom();
end;
implementation
procedure TDivOpNewtonTest.Setup;
begin
F_length := StartLength;
Randomize;
end;
function TDivOpNewtonTest.GetAllOneDigits(mlength: Integer)
: TIntXLibUInt32Array;
var
i: Integer;
begin
SetLength(result, mlength);
for i := 0 to Pred(Length(result)) do
begin
result[i] := $FFFFFFFF;
end;
end;
function TDivOpNewtonTest.GetRandomDigits(out digits2: TIntXLibUInt32Array)
: TIntXLibUInt32Array;
var
bytes: TArray<Byte>;
i: Integer;
begin
SetLength(result, RandomRange(RandomStartLength, RandomEndLength));
SetLength(digits2, Length(result) div 2);
SetLength(bytes, 4);
for i := 0 to Pred(Length(result)) do
begin
NextBytes(bytes);
result[i] := PCardinal(@bytes[0])^;
if (i < Length(digits2)) then
begin
NextBytes(bytes);
digits2[i] := PCardinal(@bytes[0])^;
end;
end;
end;
procedure TDivOpNewtonTest.NextBytes(var bytes: TArray<Byte>);
var
i, randValue: Integer;
begin
for i := 0 to Pred(Length(bytes)) do
begin
randValue := RandomRange(2, 30);
if (randValue and 1) <> 0 then
bytes[i] := Byte((randValue shr 1) xor $25)
else
bytes[i] := Byte(randValue shr 1);
end;
end;
[Test]
procedure TDivOpNewtonTest.CompareWithClassic();
var
x, x2, classicMod, fastMod, classic, fast: TIntX;
begin
TTestHelper.Repeater(RepeatCount,
procedure
begin
x := TIntX.Create(GetAllOneDigits(F_length), True);
x2 := TIntX.Create(GetAllOneDigits(F_length div 2), True);
classic := TIntX.DivideModulo(x, x2, classicMod, TDivideMode.dmClassic);
fast := TIntX.DivideModulo(x, x2, fastMod, TDivideMode.dmAutoNewton);
Assert.IsTrue(classic = fast);
Assert.IsTrue(classicMod = fastMod);
F_length := F_length + LengthIncrement;
end);
end;
[Test]
procedure TDivOpNewtonTest.CompareWithClassicRandom();
var
x, x2, classicMod, fastMod, classic, fast: TIntX;
digits2: TIntXLibUInt32Array;
begin
TTestHelper.Repeater(RandomRepeatCount,
procedure
begin
x := TIntX.Create(GetRandomDigits(digits2), False);
x2 := TIntX.Create(digits2, False);
classic := TIntX.DivideModulo(x, x2, classicMod, TDivideMode.dmClassic);
fast := TIntX.DivideModulo(x, x2, fastMod, TDivideMode.dmAutoNewton);
Assert.IsTrue(classic = fast);
Assert.IsTrue(classicMod = fastMod);
end);
end;
initialization
TDUnitX.RegisterTestFixture(TDivOpNewtonTest);
end.
|
unit MultiInspector;
interface
uses
SysUtils, Classes, Dialogs, ExtDlgs, Forms, Graphics, TypInfo,
JvInspector;
type
TJvInspectorMultiClassItem = class(TJvInspectorClassItem)
protected
procedure CreateMembers; override;
end;
//
TJvPropList = class(TList)
private
FLastMatch: PPropInfo;
FMerged: TList;
protected
function GetProps(inIndex: Integer): PPropInfo;
function CompareProp(inPropA, inPropB: PPropInfo): Boolean;
public
constructor Create;
destructor Destroy; override;
function FindMatch(inProp: PPropInfo): Boolean;
procedure AssignMerged;
procedure MergeLastMatch;
property Props[inIndex: Integer]: PPropInfo read GetProps; default;
end;
//
TInstanceArray = array of TObject;
//
TJvInspectorMultiPropData = class(TJvInspectorPropData)
class function ItemRegister: TJvInspectorRegister; override;
class function New(const AParent: TJvCustomInspectorItem;
const Instances: TList;
const TypeKinds: TTypeKinds = tkProperties): TJvInspectorItemInstances;
protected
FInstances: TInstanceArray;
FProps: array of PPropInfo;
protected
procedure SetAsFloat(const Value: Extended); override;
procedure SetAsInt64(const Value: Int64); override;
procedure SetAsMethod(const Value: TMethod); override;
procedure SetAsOrdinal(const Value: Int64); override;
procedure SetAsString(const Value: string); override;
public
function CreateInstanceList: TList;
end;
//
TJvInspectorMultiPropDataFactory = class
class function GetJvPropList(const AInstance: TObject;
const TypeKinds: TTypeKinds = tkProperties): TJvPropList;
class procedure ManufactureItems(const AParent: TJvCustomInspectorItem;
const Instances: TList);
private
FInstances: TInstanceArray;
FPropLists: array of TJvPropList;
protected
function CreateItem(const AParent: TJvCustomInspectorItem;
inPropIndex: Integer): TJvCustomInspectorItem;
procedure MergeProps;
procedure SetObjects(inList: TList);
public
procedure CreateItems(const AParent: TJvCustomInspectorItem);
end;
implementation
uses
JvResources;
var
GlobalMultiPropItemReg: TJvInspectorRegister = nil;
procedure RegisterMultiPropDataTypeKinds;
begin
if TJvCustomInspectorData.ItemRegister = nil then
raise EJvInspectorReg.CreateRes(@RsEJvInspNoGenReg);
with TJvInspectorMultiPropData.ItemRegister do
Add(
TJvInspectorTypeKindRegItem.Create(TJvInspectorMultiClassItem, tkClass));
end;
{ TJvInspectorMultiClassItem }
procedure TJvInspectorMultiClassItem.CreateMembers;
begin
if Data.IsInitialized and (Data.AsOrdinal <> 0) then
begin
Inspector.BeginUpdate;
try
DeleteMembers;
TJvInspectorMultiPropData.New(Self,
TJvInspectorMultiPropData(Data).CreateInstanceList
);
FLastMemberInstance := TObject(Data.AsOrdinal);
finally
Inspector.EndUpdate;
end;
end;
end;
{ TJvPropList }
constructor TJvPropList.Create;
begin
FMerged := TList.Create;
end;
destructor TJvPropList.Destroy;
begin
FMerged.Free;
inherited;
end;
function TJvPropList.GetProps(inIndex: Integer): PPropInfo;
begin
Result := PPropInfo(Items[inIndex]);
end;
function TJvPropList.CompareProp(inPropA, inPropB: PPropInfo): Boolean;
begin
Result := (inPropA.Name = inPropB.Name)
and (inPropA.PropType^ = inPropB.PropType^);
end;
function TJvPropList.FindMatch(inProp: PPropInfo): Boolean;
var
i: Integer;
begin
Result := false;
for i := 0 to Pred(Count) do
begin
Result := CompareProp(inProp, Props[i]);
if Result then
begin
FLastMatch := Props[i];
break;
end;
end;
end;
procedure TJvPropList.MergeLastMatch;
begin
FMerged.Add(FLastMatch);
end;
procedure TJvPropList.AssignMerged;
begin
Assign(FMerged);
FMerged.Clear;
end;
{ TJvInspectorMultiPropData }
class function TJvInspectorMultiPropData.ItemRegister: TJvInspectorRegister;
begin
if GlobalMultiPropItemReg = nil then
begin
GlobalMultiPropItemReg :=
TJvInspectorRegister.Create(TJvInspectorMultiPropData);
// register
RegisterMultiPropDataTypeKinds;
end;
Result := GlobalMultiPropItemReg;
end;
procedure TJvInspectorMultiPropData.SetAsFloat(const Value: Extended);
var
i: Integer;
begin
CheckWriteAccess;
if Prop.PropType^.Kind = tkFloat then
for i := 0 to Pred(Length(FInstances)) do
SetFloatProp(FInstances[i], FProps[i], Value)
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorFloat]);
InvalidateData;
Invalidate;
end;
procedure TJvInspectorMultiPropData.SetAsInt64(const Value: Int64);
var
i: Integer;
begin
CheckWriteAccess;
if Prop.PropType^.Kind = tkInt64 then
for i := 0 to Pred(Length(FInstances)) do
SetInt64Prop(FInstances[i], FProps[i], Value)
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorInt64]);
InvalidateData;
Invalidate;
end;
procedure TJvInspectorMultiPropData.SetAsMethod(const Value: TMethod);
var
i: Integer;
begin
CheckWriteAccess;
if Prop.PropType^.Kind = tkMethod then
for i := 0 to Pred(Length(FInstances)) do
SetMethodProp(FInstances[i], FProps[i], Value)
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorTMethod]);
InvalidateData;
Invalidate;
end;
procedure TJvInspectorMultiPropData.SetAsOrdinal(const Value: Int64);
var
i: Integer;
begin
CheckWriteAccess;
if Prop.PropType^.Kind in [tkInteger, tkChar, tkEnumeration, tkSet,
tkWChar, tkClass] then
begin
if GetTypeData(Prop.PropType^).OrdType = otULong then
for i := 0 to Pred(Length(FInstances)) do
SetOrdProp(FInstances[i], FProps[i], Cardinal(Value))
else
for i := 0 to Pred(Length(FInstances)) do
SetOrdProp(FInstances[i], FProps[i], Value)
end
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorOrdinal]);
InvalidateData;
Invalidate;
end;
procedure TJvInspectorMultiPropData.SetAsString(const Value: string);
var
i: Integer;
begin
CheckWriteAccess;
if Prop.PropType^.Kind in [tkString, tkLString, tkWString] then
for i := 0 to Pred(Length(FInstances)) do
SetStrProp(FInstances[i], FProps[i], Value)
else
raise EJvInspectorData.CreateResFmt(@RsEJvInspDataNoAccessAs, [cJvInspectorString]);
InvalidateData;
Invalidate;
end;
function TJvInspectorMultiPropData.CreateInstanceList: TList;
var
i: Integer;
begin
Result := TList.Create;
for i := 0 to Pred(Length(FInstances)) do
Result.Add(TObject(GetOrdProp(FInstances[i], FProps[i])));
end;
class function TJvInspectorMultiPropData.New(
const AParent: TJvCustomInspectorItem; const Instances: TList;
const TypeKinds: TTypeKinds): TJvInspectorItemInstances;
begin
TJvInspectorMultiPropDataFactory.ManufactureItems(AParent, Instances);
Result := nil;
Instances.Free;
end;
{ TJvInspectorMultiPropDataFactory }
class procedure TJvInspectorMultiPropDataFactory.ManufactureItems(
const AParent: TJvCustomInspectorItem; const Instances: TList);
begin
with TJvInspectorMultiPropDataFactory.Create do
try
SetObjects(Instances);
CreateItems(AParent);
finally
Free;
end;
end;
class function TJvInspectorMultiPropDataFactory.GetJvPropList(
const AInstance: TObject; const TypeKinds: TTypeKinds): TJvPropList;
var
i: Integer;
propCount: Integer;
propList: PPropList;
begin
Result := TJvPropList.Create;
propCount := GetPropList(AInstance.ClassInfo, TypeKinds, nil);
GetMem(propList, propCount * SizeOf(PPropInfo));
try
GetPropList(AInstance.ClassInfo, TypeKinds, propList);
for i := 0 to Pred(propCount) do
Result.Add(propList[i]);
finally
FreeMem(propList);
end;
end;
procedure TJvInspectorMultiPropDataFactory.SetObjects(inList: TList);
var
i: Integer;
p: TJvPropList;
begin
SetLength(FPropLists, inList.Count);
SetLength(FInstances, inList.Count);
for i := 0 to Pred(inList.Count) do
begin
FInstances[i] := inList[i];
p := GetJvPropList(FInstances[i]);
FPropLists[i] := p;
end;
if inList.Count > 1 then
MergeProps;
end;
procedure TJvInspectorMultiPropDataFactory.MergeProps;
var
c, i, j: Integer;
p: TJvPropList;
match: Boolean;
begin
c := Length(FPropLists);
p := FPropLists[0];
for i := 0 to Pred(p.Count) do
begin
match := true;
p.FLastMatch := p.Props[i];
for j := 1 to Pred(c) do
begin
match := FPropLists[j].FindMatch(p.Props[i]);
if not match then
break;
end;
if match then
for j := 0 to Pred(c) do
FPropLists[j].MergeLastMatch;
end;
for i := 0 to Pred(c) do
FPropLists[i].AssignMerged;
end;
function TJvInspectorMultiPropDataFactory.CreateItem(
const AParent: TJvCustomInspectorItem;
inPropIndex: Integer): TJvCustomInspectorItem;
var
pprop: PPropInfo;
data: TJvInspectorMultiPropData;
i, c: Integer;
regItem: TJvCustomInspectorRegItem;
begin
c := Length(FPropLists);
if (c < 1) or (inPropIndex > FPropLists[0].Count) or (inPropIndex < 0) then
raise EJvInspectorData.CreateRes(@RsEJvAssertPropInfo);
//
pprop := FPropLists[0][inPropIndex];
if pprop = nil then
raise EJvInspectorData.CreateRes(@RsEJvAssertPropInfo);
//
data := TJvInspectorMultiPropData.CreatePrim(pprop.Name, pprop.PropType^);
data.Instance := FInstances[0];
data.Prop := pprop;
//
data.FInstances := FInstances;
//
c := Length(FPropLists);
SetLength(Data.FProps, c);
for i := 0 to Pred(c) do
data.FProps[i] := FPropLists[i][inPropIndex];
//
//Data := TJvInspectorPropData(DataRegister.Add(Data));
//
if data <> nil then
begin
regItem := TJvInspectorPropData.TypeInfoMapRegister.FindMatch(Data);
if (RegItem <> nil) and (RegItem is TJvInspectorTypeInfoMapperRegItem) then
data.TypeInfo := TJvInspectorTypeInfoMapperRegItem(RegItem).NewTypeInfo;
Result := data.NewItem(AParent);
end
else
Result := nil;
end;
procedure TJvInspectorMultiPropDataFactory.CreateItems(
const AParent: TJvCustomInspectorItem);
var
i: Integer;
p: TJvPropList;
begin
if Length(FPropLists) > 0 then
begin
p := FPropLists[0];
if p.Count = 0 then
p.Free
else for i := 0 to Pred(p.Count) do
CreateItem(AParent, i)
end;
end;
initialization
finalization
FreeAndNil(GlobalMultiPropItemReg);
end.
|
unit F_About;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, NppForms, StdCtrls, ExtCtrls;
type
TAboutForm = class(TNppForm)
btnOK: TButton;
lblBasedOn: TLabel;
lblTribute: TLinkLabel;
lblPlugin: TLabel;
lblAuthor: TLinkLabel;
lblVersion: TLabel;
lblURL: TLinkLabel;
lblIEVersion: TLinkLabel;
procedure FormCreate(Sender: TObject);
procedure lblLinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AboutForm: TAboutForm;
implementation
uses
ShellAPI, StrUtils,
IdURI,
L_VersionInfoW, L_SpecialFolders, WebBrowser,
NppPlugin;
{$R *.dfm}
{ ------------------------------------------------------------------------------------------------ }
procedure TAboutForm.FormCreate(Sender: TObject);
var
WR, BR: TRect;
begin
// Position the form centered on Notepad++
if GetWindowRect(Npp.NppData.NppHandle, WR) then begin
BR.Left := WR.Left + (WR.Width div 2) - (Self.Width div 2);
BR.Width := Self.Width;
BR.Top := WR.Top + (WR.Height div 2) - (Self.Height div 2);
BR.Height := Self.Height;
Self.BoundsRect := BR;
end;
with TFileVersionInfo.Create(TSpecialFolders.DLLFullName) do begin
lblVersion.Caption := Format('v%s (%d.%d.%d.%d)', [FileVersion, MajorVersion, MinorVersion, Revision, Build]);
Free;
end;
lblIEVersion.Caption := Format(lblIEVersion.Caption, [GetIEVersion]);
end {TAboutForm.FormCreate};
{ ------------------------------------------------------------------------------------------------ }
procedure TAboutForm.lblLinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType);
var
URL, Subject: string;
begin
if LinkType = sltURL then begin
URL := Link;
if StartsText('http', URL) then begin
with TFileVersionInfo.Create(TSpecialFolders.DLLFullName) do begin
URL := URL + '?client=' + TIdURI.ParamsEncode(Format('%s/%s', [Internalname, FileVersion])) +
'&version=' + TIdURI.ParamsEncode(Format('%d.%d.%d.%d', [MajorVersion, MinorVersion, Revision, Build]));
Free;
end;
end else if StartsText('mailto:', URL) then begin
with TFileVersionInfo.Create(TSpecialFolders.DLLFullName) do begin
Subject := Self.Caption + Format(' v%s (%d.%d.%d.%d)', [FileVersion, MajorVersion, MinorVersion, Revision, Build]);
Free;
end;
URL := URL + '?subject=' + TIdURI.ParamsEncode(Subject);
end;
ShellExecute(Self.Handle, nil, PChar(URL), nil, nil, SW_SHOWDEFAULT);
end;
end {TAboutForm.lblLinkClick};
end.
|
unit SpVidOplZarplataControl;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxCheckBox,
cxTextEdit, cxMaskEdit, cxContainer, cxEdit, cxLabel, ExtCtrls,
cxControls, cxGroupBox, Unit_Sp_VidOpl_Consts, cxButtonEdit, cxDropDownEdit,
cxCalendar, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, FIBDatabase,
pFIBDatabase, DB, FIBDataSet, pFIBDataSet, PackageLoad, ZTypes, IBase,
ActnList;
type
TZFVidOplControl = class(TForm)
IdentificationBox: TcxGroupBox;
Bevel1: TBevel;
KodLabel: TcxLabel;
NameLabel: TcxLabel;
KodEdit: TcxMaskEdit;
NameEdit: TcxMaskEdit;
OptionsBox: TcxGroupBox;
Bevel2: TBevel;
TypeNachislLabel: TcxLabel;
CheckCash: TcxCheckBox;
TypeFundLabel: TcxLabel;
YesBtn: TcxButton;
CancelBtn: TcxButton;
CheckNachisl: TcxCheckBox;
PeriodBox: TcxGroupBox;
DateEnd: TcxDateEdit;
DateBeg: TcxDateEdit;
DateBegLabel: TcxLabel;
DateEndLabel: TcxLabel;
Bevel3: TBevel;
GroupEdit: TcxButtonEdit;
GroupLabel: TcxLabel;
TypeNachislEdit: TcxLookupComboBox;
TypeFundEdit: TcxLookupComboBox;
DSourceFund: TDataSource;
DSourceNachisl: TDataSource;
DataBase: TpFIBDatabase;
DSetNachisl: TpFIBDataSet;
DSetFund: TpFIBDataSet;
DefaultTransaction: TpFIBTransaction;
ActionList1: TActionList;
Action1: TAction;
Kod1DFLabel: TcxLabel;
Kod1DFEdit: TcxMaskEdit;
cxLabel2: TcxLabel;
shifr: TcxMaskEdit;
TypeBox: TcxGroupBox;
TypeEdit: TcxButtonEdit;
TypeLabel: TcxLabel;
procedure CancelBtnClick(Sender: TObject);
procedure GroupEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure Action1Execute(Sender: TObject);
procedure TypeEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
Ins_Id_VOpl_Group:LongWord;
Ins_Id_VOpl_Type:LongWord;
public
constructor Create(AOwner: TComponent;ComeDB:TISC_DB_HANDLE);reintroduce;
property Id_VOPl_Group:LongWord read Ins_Id_VOpl_Group write Ins_Id_VOpl_Group;
property Id_VOPl_Type:LongWord read Ins_Id_VOpl_Type write Ins_Id_VOpl_Type;
end;
implementation
{$R *.dfm}
constructor TZFVidOplControl.Create(AOwner: TComponent;ComeDB:TISC_DB_HANDLE);
begin
inherited Create(Aowner);
self.IdentificationBox.Caption := ZFVidOplControl_IdentificatonBox_Caption;
self.OptionsBox.Caption := ZFVidOplControl_OptionsBox_Caption;
self.NameLabel.Caption := ZFVidOplControl_NameLabel_Caption;
self.KodLabel.Caption := ZFVidOplControl_KodLabel_Caption;
self.Kod1DFLabel.Caption := ZFVidOplControl_Kod1dfLabel_Caption;
self.CheckCash.Properties.Caption := ZFVidOplControl_CheckCash_Caption;
self.CheckNachisl.Properties.Caption := 'Нарахування:'; //ZFVidOplControl_CheckNachisl_Caption;
self.TypeNachislLabel.Caption := 'Тип нарахування:'; //ZFVidOplControl_TypeNachislLabel_Caption;
self.TypeFundLabel.Caption := ZFVidOplControl_TypeFundLabel_Caption;
self.YesBtn.Caption := YesBtn_Caption;
self.CancelBtn.Caption := CancelBtn_Caption;
self.PeriodBox.Caption := ZFVidOplControl_PeriodBox_Caption;
self.DateEndLabel.Caption := 'Закінчення:'; //ZFVidOplControl_DateEndLabel_Caption;
self.DateBegLabel.Caption := ZFVidOplControl_DateBegLabel_Caption;
self.GroupLabel.Caption := ZFVidOplControl_LabelGroup_Caption;
self.NameEdit.Text := '';
self.KodEdit.Text := '';
self.TypeNachislEdit.Text := '';
self.TypeFundEdit.Text := '';
//self.DateEnd.Date := 31/12/2099;
self.DateBeg.Date := Date;
self.Ins_Id_VOpl_Group := 0;
self.TypeLabel.Caption := 'Тип вида оплат для друку';
self.TypeBox.Caption := '';
//******************************************************************************
TypeNachislEdit.Properties.ListSource := DSourceNachisl;
TypeNachislEdit.Properties.ListFieldNames := 'NAME_TIP_NACH';
TypeNachislEdit.Properties.KeyFieldNames := 'ID_TIP_NACH';
DSetNachisl.SQLs.SelectSQL.Text := 'SELECT * FROM INI_TIP_NACH';
//******************************************************************************
TypeFundEdit.Properties.ListSource := DSourceFund;
TypeFundEdit.Properties.ListFieldNames := 'NAME_TIP_FUND';
TypeFundEdit.Properties.KeyFieldNames := 'ID_TIP_FUND';
DSetFund.SQLs.SelectSQL.Text := 'SELECT * FROM INI_TIP_FUND';
//******************************************************************************
DataBase.Handle := ComeDB;
DefaultTransaction.StartTransaction;
DSetNachisl.Open;
DSetFund.Open;
end;
procedure TZFVidOplControl.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TZFVidOplControl.GroupEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var VoplGroup:variant;
begin
VoplGroup:=LoadVOplFilter(self,DataBase.Handle,zfsModal);
if VarArrayDimCount(VoplGroup)> 0 then
if VoplGroup[0]<> NULL then
begin
GroupEdit.Text := VoplGroup[1];
Ins_Id_VOpl_Group := VOplGroup[0];
end;
end;
procedure TZFVidOplControl.Action1Execute(Sender: TObject);
begin
If NameEdit.Text<>'' then
// if TypeNachislEdit.Text<>'' then
if TypeFundEdit.Text<>'' then
if DateBeg.Text<>'' then
if DateEnd.Text<>'' then
if DateBeg.Date<=DateEnd.Date then
begin
ModalResult:=mrYes;
end
else DateBeg.SetFocus
else DateEnd.SetFocus
else DateBeg.SetFocus
else TypeFundEdit.SetFocus
// else TypeNachislEdit.SetFocus
else NameEdit.SetFocus;
end;
procedure TZFVidOplControl.TypeEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var VoplType:variant;
begin
VoplType:=LoadVOplType(self,DataBase.Handle,zfsModal);
if VarArrayDimCount(VoplType)> 0 then
if VoplType[0]<> NULL then
begin
TypeEdit.Text := VoplType[1];
Ins_Id_VOpl_Type := VOplType[0];
end;
end;
end.
|
{$OPTIMIZATION LEVEL3, FASTMATH}
program auction;
uses math;
var n, m: longint;
P: array[1..1000] of longint;
procedure ReadInput;
var i: longint;
begin
ReadLn(n, m);
for i := 1 to m do Read(P[i]);
end;
procedure Sort(l, r: longint);
var i, j, mid, tmp: longint;
begin
i := l; j := r;
mid := P[(l + r) div 2];
repeat
while P[i] < mid do Inc(i);
while mid < P[j] do Dec(j);
if not(i > j) then
begin
tmp := P[i];
P[i] := P[j];
P[j] := tmp;
Inc(i); Dec(j);
end;
until i > j;
if l < j then Sort(l, j);
if i < r then Sort(i, r);
end;
procedure Solve;
var i, j, k, sum, price: longint;
maxAmount: longint = Low(longint);
begin
if m > n then k := m - n + 1
else k := 1;
price := 0;
for i := k to m do
begin
sum := P[i] * (m - i + 1);
maxAmount := Max(maxAmount, sum);
if maxAmount = sum then price := P[i];
end;
WriteLn(price, ' ', maxAmount);
end;
begin
ReadInput;
Sort(1, m);
Solve;
end. |
unit Dmitry.Controls.DBLoading;
interface
uses
System.SysUtils,
System.Classes,
System.Math,
Winapi.Windows,
Winapi.Messages,
Vcl.Controls,
Vcl.Graphics,
Vcl.ExtCtrls,
Dmitry.Graphics.Types;
type
TDBLoadingDrawBackground = procedure(Sender: TObject; Buffer : TBitmap) of object;
TDBLoading = class(TWinControl)
private
FCanvas: TCanvas;
FTimer: TTimer;
FBuffer: TBitmap;
FLineColor: TColor;
FActive: Boolean;
FAngle: Integer;
FLoadingStaticImage: TBitmap;
FOnDrawBackground: TDBLoadingDrawBackground;
procedure SetActive(const Value: Boolean);
{ Private declarations }
protected
procedure Paint(var msg: TMessage); message WM_PAINT;
procedure OnChangeSize(var msg: TMessage); message WM_SIZE;
procedure RecteateImage;
procedure OnTimer(Sender : TObject);
{ Protected declarations }
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
{ Public declarations }
published
{ Published declarations }
property Align;
property Anchors;
property LineColor: TColor read FLineColor write FLineColor;
property Active: Boolean read FActive write SetActive;
property OnDrawBackground: TDBLoadingDrawBackground read FOnDrawBackground write FOnDrawBackground;
property Visible;
end;
procedure Register;
{$R Dmitry.Controls.DBLOADING.RES}
implementation
procedure Register;
begin
RegisterComponents('Dm', [TDBLoading]);
end;
procedure AALine(X1, Y1, X2, Y2: Single; Color: Tcolor; Canvas: Tcanvas);
function CrossFadeColor(FromColor, ToColor: TColor; Rate: Single): TColor;
var
R, G, B: Byte;
begin
R := Round(GetRValue(FromColor) * Rate + GetRValue(ToColor) * (1 - Rate));
G := Round(GetGValue(FromColor) * Rate + GetGValue(ToColor) * (1 - Rate));
B := Round(GetBValue(FromColor) * Rate + GetBValue(ToColor) * (1 - Rate));
Result := RGB(R, G, B);
end;
procedure Hpixel(X: Single; Y: Integer);
var
FadeRate: Single;
begin
FadeRate := Sqrt(X - Trunc(X));
with Canvas do
begin
Pixels[Trunc(X), Y] := CrossFadeColor(Color, Pixels[Trunc(X), Y], 1 - FadeRate);
Pixels[Trunc(X) + 1, Y] := CrossFadeColor(Color, Pixels[Trunc(X) + 1, Y], FadeRate);
end;
end;
procedure Vpixel(X: Integer; Y: Single);
var
FadeRate: Single;
begin
FadeRate := Sqrt(Y - Trunc(Y));
with Canvas do
begin
Pixels[X, Trunc(Y)] := CrossFadeColor(Color, Pixels[X, Trunc(Y)], 1 - FadeRate);
Pixels[X, Trunc(Y) + 1] := CrossFadeColor(Color, Pixels[X, Trunc(Y) + 1], FadeRate);
end;
end;
var
I: Integer;
Ly, Lx, Currentx, Currenty, Deltax, Deltay, L, Skipl: Single;
begin
if (X1 <> X2) or (Y1 <> Y2) then
begin
Currentx := X1;
Currenty := Y1;
Lx := Abs(X2 - X1);
Ly := Abs(Y2 - Y1);
if Lx > Ly then
begin
L := Trunc(Lx);
Deltay := (Y2 - Y1) / L;
if X1 > X2 then
begin
Deltax := -1;
Skipl := (Currentx - Trunc(Currentx));
end
else
begin
Deltax := 1;
Skipl := 1 - (Currentx - Trunc(Currentx));
end;
end
else
begin
L := Trunc(Ly);
Deltax := (X2 - X1) / L;
if Y1 > Y2 then
begin
Deltay := -1;
Skipl := (Currenty - Trunc(Currenty));
end
else
begin
Deltay := 1;
Skipl := 1 - (Currenty - Trunc(Currenty));
end;
end;
Currentx := Currentx + Deltax * Skipl;
Currenty := Currenty + Deltay * Skipl; { }
for I := 1 to Trunc(L) do
begin
if Lx > Ly then
Vpixel(Trunc(Currentx), Currenty)
else
Hpixel(Currentx, Trunc(Currenty));
Currentx := Currentx + Deltax;
Currenty := Currenty + Deltay;
end;
end;
end;
{ TDBLoading }
constructor TDBLoading.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBuffer := TBitmap.Create;
FBuffer.PixelFormat := pf24bit;
FLoadingStaticImage := TBitmap.Create;
FLoadingStaticImage.Handle := LoadImage(HInstance, 'DBLOADING', IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);
FLoadingStaticImage.PixelFormat := pf32bit;
Width := FLoadingStaticImage.Width;
Height := FLoadingStaticImage.Height;
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FTimer := TTimer.Create(Self);
FTimer.Interval := 55;
FTimer.Enabled := False;
FTimer.OnTimer := OnTimer;
RecteateImage;
end;
destructor TDBLoading.Destroy;
begin
FCanvas.Free;
FBuffer.Free;
FTimer.Free;
FLoadingStaticImage.Free;
inherited;
end;
procedure TDBLoading.OnChangeSize(var msg: Tmessage);
begin
Width := FLoadingStaticImage.Width;
Height := FLoadingStaticImage.Height;
RecteateImage;
end;
procedure TDBLoading.OnTimer(Sender: TObject);
begin
if not Visible then
Exit;
RecteateImage;
if HandleAllocated then
SendMessage(Handle, WM_PAINT, 0, 0);
end;
procedure TDBLoading.Paint(var msg: TMessage);
begin
inherited;
FCanvas.Draw(0, 0, FBuffer);
end;
procedure TDBLoading.RecteateImage;
var
X1, Y1, X2, Y2: Integer;
H, W, W1, W2: Integer;
G: Integer;
PS: PARGB32;
PD: PARGB;
I, J: Integer;
procedure DrawAngle(Angle1, Angle2 : Extended; Color : TColor; Size : Integer);
var
DAngle1, DAngle2 : Extended;
begin
DAngle1 := Angle1 * pi / 180;
DAngle2 := Angle2 * pi / 180;
H := FBuffer.Height div 2;
W := FBuffer.Width div 2;
X1:=Round(w + Size * Sin(DAngle1));
Y1:=Round(h - Size * Cos(DAngle1));
X2:=Round(w + 2.5 * Sin(DAngle2));
Y2:=Round(h - 2.5 * Cos(DAngle2));
AALine(X1, Y1, X2, Y2, Color, FBuffer.Canvas);
end;
begin
FBuffer.Width := Width;
FBuffer.Height := Height;
if Assigned(FOnDrawBackground) then
FOnDrawBackground(Self, FBuffer);
for I := 0 to Height - 1 do
begin
PS := FLoadingStaticImage.ScanLine[I];
PD := FBuffer.ScanLine[I];
for J := 0 to Width - 1 do
begin
W1 := PS[J].L;
W2 := 255 - W1;
PD[J].R := (PD[J].R * W2 + PS[J].R * W1 + 127) div 255;
PD[J].G := (PD[J].G * W2 + PS[J].G * W1 + 127) div 255;
PD[J].B := (PD[J].B * W2 + PS[J].B * W1 + 127) div 255;
end;
end;
G := FAngle * 20;
DrawAngle(G, G + 10, $8080BD, 15);
DrawAngle(G, G - 10, $8080BD, 15);
DrawAngle(G, G, $0101BD, 15);
G := G div 10;
DrawAngle(G, G + 25, $8080BD, 10);
DrawAngle(G, G - 25, $8080BD, 10);
DrawAngle(G, G, $0101BD, 10);
Inc(FAngle);
if FAngle > 360 then
FAngle := 0;
end;
procedure TDBLoading.SetActive(const Value: Boolean);
begin
FActive := Value;
FTimer.Enabled := Value;
RecteateImage;
end;
end.
|
unit UUnAce;
(*====================================================================
ACE files decompression
======================================================================*)
interface
uses
{$ifdef mswindows}
Windows
{$ELSE}
LCLIntf, LCLType, LMessages, TTTypes ,
{$ENDIF}
SysUtils;
////////////////////////////////////////////////////////////////////////
// ACE constants
////////////////////////////////////////////////////////////////////////
const
// Constants for the tACECommentStruc.State field, which tells about
// the result of the last comment extraction.
ACE_COMMENT_OK = 0; // comment extraction went fine
ACE_COMMENT_SMALLBUF = 1; // comment buffer too small to
// store the whole comment in
ACE_COMMENT_NONE = 255; // No comment present
// Flag constants for tACEArchiveDataStruc.Flags field.
ACE_ARCFLAG_MAINCOMMENT = 2;
ACE_ARCFLAG_SFX = 512;
ACE_ARCFLAG_LIMITSFXJR = 1024; // is an SFX archive
// that supports 256k
// dictionary only
ACE_ARCFLAG_MULTIVOLUME = 2048;
ACE_ARCFLAG_AV = 4096; // not used in ACL
ACE_ARCFLAG_RECOVERYREC = 8192;
ACE_ARCFLAG_LOCK = 16384;
ACE_ARCFLAG_SOLID = 32768;
// Host system used to create an archive. Used at
// tACEArchiveDataStruc.HostCreated field.
ACE_HOST_MSDOS = 0; // archive created by
// MSDOS ACE archiver
ACE_HOST_OS2 = 1; // created by OS2 ACE
ACE_HOST_WIN32 = 2; // created by Win32 ACE
// Flag constants for the tACEFileData.Flags field.
ACE_FILEFLAG_FILECOMMENT = 2; // file has comment
ACE_FILEFLAG_SPLITBEFORE = 4096; // continued from
// previous volume
ACE_FILEFLAG_SPLITAFTER = 8192; // continued on
// next volume
ACE_FILEFLAG_PASSWORD = 16384; // is encrypted
ACE_FILEFLAG_SOLID = 32768; // uses data of previous
// files (solid mode)
// Tells the Dll which compression level to use. (ACE only)
ACE_LEVEL_STORE = 0; // save file only; do not compress
ACE_LEVEL_FASTEST = 1; // compress very fast
ACE_LEVEL_FAST = 2; // compress fast
ACE_LEVEL_NORMAL = 3; // good compromise between speed and
// compression rate
ACE_LEVEL_GOOD = 4; // achieves good compression
ACE_LEVEL_BEST = 5; // best compression; bit slow
////////////////////////////////////////////////////////////////////////
// Part 2.1: operation codes
//
// Passed to callback functions indicating the current operation.
ACE_CALLBACK_OPERATION_LIST = 0;
ACE_CALLBACK_OPERATION_TEST = 1;
ACE_CALLBACK_OPERATION_ANALYZE = 2;
ACE_CALLBACK_OPERATION_EXTRACT = 3;
ACE_CALLBACK_OPERATION_ADD = 4;
ACE_CALLBACK_OPERATION_REPACK = 5;
ACE_CALLBACK_OPERATION_DELETE = 6;
ACE_CALLBACK_OPERATION_REPAIR = 7; // repair without
// recovery record
ACE_CALLBACK_OPERATION_SETCMT = 8;
ACE_CALLBACK_OPERATION_ENCRYPT = 9;
ACE_CALLBACK_OPERATION_KEEP = 10; // file is to be
// taken along
// without recompress
ACE_CALLBACK_OPERATION_RECOVER = 11; // begin of
// recovering archive
// by recovery record
ACE_CALLBACK_OPERATION_HEADSEARCH = 12; // begin of searching
// for file headers
ACE_CALLBACK_OPERATION_RECRECSEARCH = 13; // begin of searching
// for recovery record
ACE_CALLBACK_OPERATION_ADDSFX = 14;
ACE_CALLBACK_OPERATION_LOCK = 15;
ACE_CALLBACK_OPERATION_ADDAV = 16; // not used in ACL
ACE_CALLBACK_OPERATION_ADDRECOVREC = 17;
ACE_CALLBACK_OPERATION_REGISTER = 18; // not used in ACL
////////////////////////////////////////////////////////////////////////
// Part 2.2: callback function return codes
// One of these result codes has to be returned by the application-based
// callback functions.
ACE_CALLBACK_RETURN_OK = 0; // also "yes" at
// requests
ACE_CALLBACK_RETURN_NO = 1; // no, do not/
// do not retry
ACE_CALLBACK_RETURN_CANCEL = 2; // abort operation
////////////////////////////////////////////////////////////////////////
// Part 2.3: callback structure types
// States of which type the passed structure is when a callback function
// is called. The type is written to the StructureType field.
ACE_CALLBACK_TYPE_GLOBAL = 0;
// type of structure is
// tACECallbackGlobalStruc
//-------------------------------------------------------------
// callback function | codes using this structure
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// InfoCallbackProc | ACE_CALLBACK_INFO_GENERALKEY // not used in ACL
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ErrorCallbackProc | ACE_CALLBACK_ERROR_MEMORY // fr ManyFilesError und ExtractMem andere Codes verwenden!?
// | ACE_CALLBACK_ERROR_REGISTER // not used in ACL
// | ACE_CALLBACK_ERROR_READKEY // not used in ACL
// | ACE_CALLBACK_ERROR_WRITEKEY // not used in ACL
// | ACE_CALLBACK_ERROR_NOWINACEKEY // not used in ACL
// | ACE_CALLBACK_ERROR_NOACTIVEACEKEY // not used in ACL
// | ACE_CALLBACK_ERROR_UNCSPACE // wird noch nicht verwendet!
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// RequestCallbackProc | ACE_CALLBACK_REQUEST_REGISTER // not used in ACL
//
ACE_CALLBACK_TYPE_ARCHIVE = 1;
// type of structure is
// tACECallbackArchiveStruc
//-------------------------------------------------------------
// callback function | codes using this structure
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// InfoCallbackProc | ACE_CALLBACK_INFO_TMPARCCREATE
// | ACE_CALLBACK_INFO_TMPARCCREATEEND
// | ACE_CALLBACK_INFO_ADDRECREC
// | ACE_CALLBACK_INFO_ADDRECRECEND
// | ACE_CALLBACK_INFO_RECREC
// | ACE_CALLBACK_INFO_NORECREC
// | ACE_CALLBACK_INFO_RECOVERED
// | ACE_CALLBACK_INFO_NODAMAGE
// | ACE_CALLBACK_INFO_FNDMAINHEAD
// | ACE_CALLBACK_INFO_FILELISTCREATE
// | ACE_CALLBACK_INFO_FILELISTCREATEEND
// | ACE_CALLBACK_INFO_FILESORT
// | ACE_CALLBACK_INFO_FILESORTEND
// | ACE_CALLBACK_INFO_COPYEND
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ErrorCallbackProc | ACE_CALLBACK_ERROR_MODIFYVOLUME
// | ACE_CALLBACK_ERROR_MODIFYLOCKEDARCHIVE
// | ACE_CALLBACK_ERROR_AV // not used in ACL
// | ACE_CALLBACK_ERROR_TOODAMAGED
// | ACE_CALLBACK_ERROR_ARCHIVEEXISTS
// | ACE_CALLBACK_ERROR_OPENREPAIRARCHIVE
// | ACE_CALLBACK_ERROR_OPENARCHIVEREAD
// | ACE_CALLBACK_ERROR_OPENARCHIVEWRITE
// | ACE_CALLBACK_ERROR_READARCHIVE
// | ACE_CALLBACK_ERROR_WRITEARCHIVE
// | ACE_CALLBACK_ERROR_ALREADYSFX
// | ACE_CALLBACK_ERROR_ADDSFXTOVOLUME
// | ACE_CALLBACK_ERROR_ARCHIVEBROKEN
// | ACE_CALLBACK_ERROR_ARCHIVESAVE
// | ACE_CALLBACK_ERROR_NOFILES
// | ACE_CALLBACK_ERROR_ISNOTANARCHIVE
// | ACE_CALLBACK_ERROR_TEMPDIRCREATE
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// RequestCallbackProc | ACE_CALLBACK_REQUEST_MARKASSOLID
// | ACE_CALLBACK_REQUEST_CHANGEVOLUME
// | ACE_CALLBACK_REQUEST_ARCHIVEEXISTS
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// StateCallbackProc | ACE_CALLBACK_STATE_STARTARCHIVE
//
ACE_CALLBACK_TYPE_ARCHIVEDFILE = 2;
// type of structure is
// tACECallbackArchivedFileStruc
//-------------------------------------------------------------
// callback function | codes using this structure
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// InfoCallbackProc | ACE_CALLBACK_INFO_TMPARCCREATE
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ErrorCallbackProc | ACE_CALLBACK_ERROR_CREATIONNAMEINUSE
// | ACE_CALLBACK_ERROR_HIGHERVERSION
// | ACE_CALLBACK_ERROR_ENCRYPTIONCRC
// | ACE_CALLBACK_ERROR_WRITE
// | ACE_CALLBACK_ERROR_READ
// | ACE_CALLBACK_ERROR_OPENREAD
// | ACE_CALLBACK_ERROR_OPENWRITE //wird noch gar nich benutzt?? sollte aber - bei extract!
// | ACE_CALLBACK_ERROR_FILENAMETOOLONG
// | ACE_CALLBACK_ERROR_REPACKCRC
// | ACE_CALLBACK_ERROR_EXCLUDEPATH
// | ACE_CALLBACK_ERROR_METHOD
// | ACE_CALLBACK_ERROR_EXTRACTSPACE
// | ACE_CALLBACK_ERROR_CREATION
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// RequestCallbackProc | ACE_CALLBACK_REQUEST_OVERWRITE
// | ACE_CALLBACK_REQUEST_DELETEARCHIVEDSYSFILE
// | ACE_CALLBACK_REQUEST_ADDBROKENFILE
// | ACE_CALLBACK_REQUEST_PASSWORD
// | ACE_CALLBACK_REQUEST_OVERWRITESYSFILE
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// StateCallbackProc | ACE_CALLBACK_STATE_STARTFILE
// | ACE_CALLBACK_STATE_ENDNOCRCCHECK
//
ACE_CALLBACK_TYPE_REALFILE = 3;
// type of structure is
// tACECallbackRealFileStruc
//-------------------------------------------------------------
// callback function | codes using this structure
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// InfoCallbackProc | ACE_CALLBACK_INFO_FILELISTADD
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ErrorCallbackProc | ACE_CALLBACK_ERROR_MOVEDELETE
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// RequestCallbackProc | ACE_CALLBACK_REQUEST_MOVEDELETEREALSYSFILE
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// StateCallbackProc | ACE_CALLBACK_STATE_STARTFILE
//
ACE_CALLBACK_TYPE_SPACE = 4;
// type of structure is
// tACECallbackSpaceStruc
//-------------------------------------------------------------
// callback function | codes using this structure
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// ErrorCallbackProc | ACE_CALLBACK_ERROR_TEMPDIRSPACE
// | ACE_CALLBACK_ERROR_ARCHIVESPACE
//
ACE_CALLBACK_TYPE_SFXFILE = 5;
// type of structure is
// tACECallbackSFXFileStruc
//-------------------------------------------------------------
// callback function | codes using this structure
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// ErrorCallbackProc | ACE_CALLBACK_ERROR_READINGSFXFILE
//
ACE_CALLBACK_TYPE_COPY = 6;
// type of structure is
// tACECallbackCopyStruc
//-------------------------------------------------------------
// callback function | codes using this structure
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// InfoCallbackProc | ACE_CALLBACK_INFO_COPY
//
ACE_CALLBACK_TYPE_PROGRESS = 7;
// type of structure is
// tACECallbackProgressStruc
//-------------------------------------------------------------
// callback function | codes using this structure
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// StateCallbackProc | ACE_CALLBACK_STATE_PROGRESS
//
ACE_CALLBACK_TYPE_CRCCHECK = 8;
// type of structure is
// tACECallbackCRCCheckStruc
//-------------------------------------------------------------
// callback function | codes using this structure
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// StateCallbackProc | ACE_CALLBACK_STATE_ENDCRCCHECK
//
//-----------------------------------------------------------------------
// These values are passed to the ACEInfoCallbackProc callback function
// to inform the application about actions (smaller parts of operations)
// which may take some time or other things that might be of interest.
//-----------------------------------------------------------------------
ACE_CALLBACK_INFO_GENERALKEY = $100;
// key is a general one (no own AV; own key
// is obtainable for a special price!?)
// not used in ACL
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_GLOBAL
// operations:
// ACERegister
ACE_CALLBACK_INFO_TMPARCCREATE = $110;
// creating temporary archive for changes
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACERepair
ACE_CALLBACK_INFO_TMPARCCREATEEND = $111;
// finished creating temporary archive
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACERepair
ACE_CALLBACK_INFO_ADDRECREC = $112;
// adding recovery record
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACEAddRecoveryRecord
// ACERepair
ACE_CALLBACK_INFO_ADDRECRECEND = $113;
// finished adding recovery record
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACEAddRecoveryRecord
// ACERepair
ACE_CALLBACK_INFO_RECREC = $114;
// trying to recover files by recovery
// record; end indicated by
// ACE_CALLBACK_INFO_RECOVERED or
// ACE_CALLBACK_INFO_NODAMAGE
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACERepair
ACE_CALLBACK_INFO_NORECREC = $115;
// found no recovery record
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACERepair
ACE_CALLBACK_INFO_RECOVERED = $116;
// archive has been fully recovered
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACERepair
ACE_CALLBACK_INFO_NODAMAGE = $117;
// ACERepair detected by recovery record that
// the archive is not damaged
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACERepair
ACE_CALLBACK_INFO_FNDMAINHEAD = $118;
// found archive header
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACERepair
ACE_CALLBACK_INFO_FILELISTCREATE = $119;
// creating a file list of specified files
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEList
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACESetComments
// ACEEncryptFiles
ACE_CALLBACK_INFO_FILELISTCREATEEND = $11a;
// sent when creating the list of files
// is finished
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEList
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACESetComments
// ACEEncryptFiles
ACE_CALLBACK_INFO_FILESORT = $11b;
// sorting files (for solid compression)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
ACE_CALLBACK_INFO_FILESORTEND = $11c;
// sorting files (for solid compression)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
ACE_CALLBACK_INFO_COPYEND = $11d;
// copying a file finished
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACERepair
ACE_CALLBACK_INFO_FILELISTADD = $140;
// called at creation of file list; the name
// of the file just added to file list is
// passed in tACECallbackRealFileStruc
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_REALFILE
// operations:
// ACEList
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACESetComments
// ACEEncryptFiles
ACE_CALLBACK_INFO_COPY = $150;
// copying a file; file name, file size and
// copied bytes are passed via
// tACECallbackCopyStruc
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_COPY
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACERepair
ACE_CALLBACK_ERROR_MEMORY = $200;
// not enough memory to perform operation
// (dictionary too large?)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_GLOBAL
// operations:
// all
ACE_CALLBACK_ERROR_REGISTER = $201;
// registration key is invalid (or wrong
// format?); not used in ACL
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_GLOBAL
// operations:
// ACERegister
ACE_CALLBACK_ERROR_READKEY = $202;
// key could not be read (does not exist or
// is invalid); not used in ACL
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_GLOBAL
// operations:
// ACEInitDll
ACE_CALLBACK_ERROR_WRITEKEY = $203;
// could not write key; not used in ACL
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_GLOBAL
// operations:
// ACERegister
ACE_CALLBACK_ERROR_NOWINACEKEY = $204;
// key not valid for WinACE; not used in ACL
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_GLOBAL
// operations:
// ACERegister
ACE_CALLBACK_ERROR_NOACTIVEACEKEY = $205;
// key not valid for ActiveACE; not used in ACL
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_GLOBAL
// operations:
// ACERegister
ACE_CALLBACK_ERROR_UNCSPACE = $206;
// Win95_OSR1-bug: it is impossible to
// get available space of network drives by
// an UNC name; ACE will not stop but
// assumes there are 4Gb free
// --> the operation might fail if free
// disk space is low
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_GLOBAL
// operations:
// all
ACE_CALLBACK_ERROR_MODIFYVOLUME = $220;
// modification of volumes not possible
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACEAddRecoveryRecord
ACE_CALLBACK_ERROR_MODIFYLOCKEDARCHIVE = $221;
// modification of locked archive not possible
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACEAddRecoveryRecord
ACE_CALLBACK_ERROR_AV = $222;
// AV of archive is NOT ok or does not match
// to the users AV (not used in ACL)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEReadArchiveData
// ACEList
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACERepair
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACEAddAV
// ACELock
// ACEAddRecoveryRecord
ACE_CALLBACK_ERROR_TOODAMAGED = $223;
// can not repair by recovery record but
// can continue with normal repair
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACERepair
ACE_CALLBACK_ERROR_ARCHIVEEXISTS = $224;
// destination file name already used;
// may occur if at
// ACE_CALLBACK_ERROR_ARCHIVESPACE a
// direcory is specified where a file
// with the same name as the current archive
// already exists
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
ACE_CALLBACK_ERROR_OPENREPAIRARCHIVE = $225;
// could not create archive for repairing
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACERepair
ACE_CALLBACK_ERROR_OPENARCHIVEREAD = $226;
// could not open archive/volume for reading
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEReadArchiveData
// ACEList
// ACETest
// ACEExtract
// ACERepair
ACE_CALLBACK_ERROR_OPENARCHIVEWRITE = $227;
// could not open archive/volume for writing
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEDelete
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACEAddRecoveryRecord
// ACERepair
ACE_CALLBACK_ERROR_READARCHIVE = $228;
// error reading from archive
// (source disk removed?)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEReadArchiveData
// ACEList
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACERepair
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACEAddAV
// ACELock
// ACEAddRecoveryRecord
ACE_CALLBACK_ERROR_WRITEARCHIVE = $229;
// error writing to archive
// (destination disk removed?)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEDelete
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACEAddRecoveryRecord
// ACERepair
ACE_CALLBACK_ERROR_ALREADYSFX = $22a;
// ca not make to SFX: is already SFX
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAddSFX
ACE_CALLBACK_ERROR_ADDSFXTOVOLUME = $22b;
// adding SFX to volumes not possible
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAddSFX
ACE_CALLBACK_ERROR_ARCHIVEBROKEN = $22c;
// archive is broken (damaged)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEReadArchiveData
// ACEList
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACERepair
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACEAddAV
// ACELock
// ACEAddRecoveryRecord
ACE_CALLBACK_ERROR_ARCHIVESAVE = $22d;
// not enough space to save archive;
// but normally
// ACE_CALLBACK_ERROR_ARCHIVESPACE
// should allow to change destination
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACEAddRecoveryRecord
// ACERepair
ACE_CALLBACK_ERROR_NOFILES = $22e;
// no files specified/could not find files
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEList
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACESetComments
// ACEEncryptFiles
ACE_CALLBACK_ERROR_ISNOTANARCHIVE = $22f;
// specified archive file is not an
// ACE archive
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEReadArchiveData
// ACEList
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACERepair
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACEAddAV
// ACELock
// ACEAddRecoveryRecord
ACE_CALLBACK_ERROR_TEMPDIRCREATE = $230;
// could not create file in temp directory
// (write protected or directory does
// not exist)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACEAddRecoveryRecord
// ACERepair
ACE_CALLBACK_ERROR_HIGHERVERSION = $231;
// this Dll version is not able to handle
// the archive
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACEAddRecoveryRecord
ACE_CALLBACK_ERROR_CREATIONNAMEINUSE = $240;
// name used by directory
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEExtract
ACE_CALLBACK_ERROR_ENCRYPTIONCRC = $242;
// encryption failed because of CRC-Error at
// decompression
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEEncryptFiles
ACE_CALLBACK_ERROR_READ = $243;
// error reading file to be added
// (source disk removed?)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEAdd
ACE_CALLBACK_ERROR_WRITE = $244;
// error at extraction
// (destination disk removed?)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEExtract
ACE_CALLBACK_ERROR_OPENREAD = $245;
// error opening file for reading
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEAdd
ACE_CALLBACK_ERROR_OPENWRITE = $246;
// error opening file for writing
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEExtract
ACE_CALLBACK_ERROR_FILENAMETOOLONG = $247;
// resulting file name too long
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEAdd
ACE_CALLBACK_ERROR_REPACKCRC = $248;
// CRC-check error at recompression
// (archive broken or wrong password)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEDelete
// ACEAdd
ACE_CALLBACK_ERROR_EXCLUDEPATH = $249;
// could not exclude path of file names; two
// or more files would have the same name
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEAdd
ACE_CALLBACK_ERROR_METHOD = $24a;
// compression method not known to this
// Dll version
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACEEncryptFiles
ACE_CALLBACK_ERROR_EXTRACTSPACE = $24b;
// not enough space to extract file
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEExtract
ACE_CALLBACK_ERROR_CREATION = $24c;
// creation failed (write-protection?)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEExtract
ACE_CALLBACK_ERROR_OVERWRITEDELETE = $24d;
// could not overwrite because deletion of
// file failed
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEExtract
ACE_CALLBACK_ERROR_MOVEDELETE = $260;
// deletion of file or directory failed
// (move operation)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_REALFILE
// operations:
// ACEAdd
ACE_CALLBACK_ERROR_TEMPDIRSPACE = $270;
// not enough space at current temp directory
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_SPACE
// operations:
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACEAddAV
ACE_CALLBACK_ERROR_ARCHIVESPACE = $271;
// not enough space to save archive
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_SPACE
// operations:
// ACEDelete
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACELock
// ACEAddAV
// ACEAddRecoveryRecord
// ACERepair
ACE_CALLBACK_ERROR_READINGSFXFILE = $280;
// error reading SFX file:
// is no SFX file,
// file does not exist or could not be opened
// for reading
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_SFXFILE
// operations:
// ACEAdd
// ACEAddSFX
ACE_CALLBACK_REQUEST_REGISTER = $300;
// Global.UserAV has to be set
// to continue registration process;
// not used in ACL
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_GLOBAL
// operations:
// ACERegister
ACE_CALLBACK_REQUEST_MARKASSOLID = $320;
// ArchiveHeader damaged,
// set solid flag for the new archive?
// (in case of doubt return yes!)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACERepair
ACE_CALLBACK_REQUEST_CHANGEVOLUME = $321;
// Asks for permission to process next volume.
// If operation is ACE_CALLBACK_OPERATION_ADD
// then a new volume will be created.
// The application may change the name
// of the archive by modifying
// ArchiveData->ArchiveName
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEDelete
// ACEAdd
// ACESetComments
// ACEEncryptFiles
// ACEList
// ACETest
// ACEExtract
ACE_CALLBACK_REQUEST_ARCHIVEEXISTS = $322;
// Asks whether to overwrite a file with
// the same name as the archive.
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEDelete
// ACEAdd
// ACESetComments
// ACEEncryptFiles
ACE_CALLBACK_REQUEST_OVERWRITE = $340;
// Overwrite existing file?
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEAdd
// ACEExtract
ACE_CALLBACK_REQUEST_DELARCHIVEDSYSFILE = $341;
// Delete rdonly/hidden/system file
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEDelete
ACE_CALLBACK_REQUEST_ADDBROKENFILE = $342;
// repair function found file with
// broken header, add file?
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACERepair
ACE_CALLBACK_REQUEST_PASSWORD = $343;
// password required; attention: may be
// decryption _and_ encryption; but passwords
// can be different --> better changing
// passwords at StateCallbackProc
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACEEncryptFiles
ACE_CALLBACK_REQUEST_OVERWRITESYSFILE = $344;
// Overwrite rdonly/hidden/system file
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEAdd
// ACEExtract
ACE_CALLBACK_REQUEST_MOVEDELREALSYSFILE = $360;
// Delete rdonly/hidden/system file
// (move to archive operation)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_REALFILE
// operations:
// ACEAdd
ACE_CALLBACK_STATE_STARTARCHIVE = $400;
// procession of archive is about to begin
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVE
// operations:
// ACEList
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACERepair
// ACESetComments
// ACEEncryptFiles
// ACEAddSFX
// ACEAddAV
// ACELock
// ACEAddRecoveryRecord
ACE_CALLBACK_STATE_STARTFILE = $410;
// procession of file is about to begin
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEList
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACERepair
// ACESetComments
// ACEEncryptFiles
ACE_CALLBACK_STATE_ENDNOCRCCHECK = $411;
// end of file procession
// (no CRC chceck for this operation)
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
// operations:
// ACEList
// ACEDelete
// ACEAdd
// ACERepair
// ACESetComments
// ACEEncryptFiles
ACE_CALLBACK_STATE_PROGRESS = $420;
// informs about the progress of a file
// operation
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_PROGRESS
// operations:
// ACEDelete
// ACETest
// ACEExtract
// ACEAdd
// ACERepair
// ACEEncryptFiles
ACE_CALLBACK_STATE_ENDCRCCHECK = $430;
// end of file procession, CRC-check
// result is passed
//---------------------------------------------
// structure type:
// ACE_CALLBACK_TYPE_CRCCHECK
// operations:
// ACETest
// ACEExtract
// ACEDelete
// ACEAdd
////////////////////////////////////////////////////////////////////////
// PART 3.1: ACE.DLL FUNCTION RETURN CODES
////////////////////////////////////////////////////////////////////////
// These error codes are returned by the ACE.DLL-functions. The meanings
// of the codes are the same, as they are for the exit codes of ACE.EXE.
ACE_ERROR_NOERROR = 0; // no error; operation succesful
ACE_ERROR_MEM = 1; // insufficient memory
ACE_ERROR_FILES = 2; // no files specified
ACE_ERROR_FOUND = 3; // specified archive not found
ACE_ERROR_FULL = 4; // disk full
ACE_ERROR_OPEN = 5; // could not open file
ACE_ERROR_READ = 6; // read error
ACE_ERROR_WRITE = 7; // write error
ACE_ERROR_CLINE = 8; // invalid command line
ACE_ERROR_CRC = 9; // CRC error
ACE_ERROR_OTHER = 10; // other error
ACE_ERROR_EXISTS = 11; // file already exists
ACE_ERROR_USER = 255; // user break (application
// returned cancel code at
// callback function)
// These error codes are returned by the ACE.DLL-functions. They are not
// used by ACE.EXE yet.
ACE_ERROR_PARAM = 128; // might be used later
////////////////////////////////////////////////////////////////////////
// PART 1: DIFFERENT STRUCTURES
////////////////////////////////////////////////////////////////////////
//
// Here in different structures used at callback functions and
// ACE.DLL functions are declared.
//
// Contents:
// Part 1.1: structures used in callback structures
// Part 1.2: structures used in function structures
//
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Part 1.1: structures used in callback structures
////////////////////////////////////////////////////////////////////////
// comment buffer structure
// Used in tACEGlobalDataStruc. Application has to specify where the
// comment is or should be stored.
type
tACECommentStruc = packed record
Buf : PByteArray;
Bufsize : integer;
State : integer;
end;
pACECommentStruc = ^tACECommentStruc;
// Global data structure
// This structure contains information for the Dll being interesting for
// nearly all functions. The Dll has to be initialized with this
// structure passed to tACEInitDll(). This structure is also passed
// by the callback functions.
tACEGlobalDataStruc = packed record
Obj : Pointer;
// ---- reserved for application! ----
// thought to be used as a pointer to
// an object; when a callback-function is
// called, the object pointer can be used to
// handle the callback in a specific way;
// the pointer has to be initialized by
// ACEInitDll()
MaxArchiveTestBytes : ulong; // how many bytes of a file should be
// looked upon at archive header search?
MaxFileBufSize : ulong; // maximum buffer size for buffered
// I/O operations
Comment : tACECommentStruc;
// used to exchange comment data
// between application and Dll
// using callback functions
DecryptPassword : PChar; // the DecryptPassword specified at
// ACEInitDll() is overwritten by the
// DecryptPassword field of tACEAddStruc and
// other function-specific structures;
// but this field can be used to change the
// password at callback function calls
UseVBStructures : LongBool; // passes structures to callback functions
// much better suited for Visual Basic
Reserved1 : array[0..59] of char;
// fields for ACE only
EncryptPassword : PChar; // things stated at the description of the
// DecryptPassword field apply here as well
TempDir : PChar; // directory to save temporary archive
// registration (ACE DLLs only, but not used at ACL)
KeyPath : PChar; // necessary for reading and writing key file
UserAV : PChar; // Dll returns the AV string (if registered)
// in this field
IsGeneralKey : PChar; // DLL returns the key, if it is a general key
OwnerWindow : HWND ; // specifies the applications window to be
// parent of the registration reminder dialog
// fields for ACE only
CompressionLevel : ulong; // contains the currently used compression
// level - may be changed during compression
// operation
Reserved2 : array[0..55] of char;
// has to be filled with zeros
// Callback routine addresses
InfoCallbackProc : Pointer;
ErrorCallbackProc : Pointer;
RequestCallbackProc : Pointer;
StateCallbackProc : Pointer;
// different new fields
Reserved3 : array[0..63] of char; // has to be filled with zeros
end;
pACEGlobalDataStruc = ^tACEGlobalDataStruc;
////////////////////////////////////////////////////////////////////////
// archive data structure
// Informs the callback functions about the current archive, its volume
// number, the archive-flags (see ACE_FLAG constants), the creation host
// system (see ACE_HOST constants) and the AV if present in archive.
// Also used at ACEReadArchiveData().
tACEArchiveDataStruc = packed record
ArchiveName : PChar;
VolumeNumber,
Flags, // see ACE_ARCFLAG defines below
HostCreated, // see ACE_HOST defines below
TimeCreated, // in MS-DOS format
VersionCreated,
VersionExtract: ulong; // version needed to extract files
AV : PChar; // not used in ACL
Reserved : array[0..63] of char; // filled with zeros
end;
pACEArchiveDataStruc = ^tACEArchiveDataStruc;
////////////////////////////////////////////////////////////////////////
// Contains information about an archived file.
tACEFileDataStruc = packed record
SourceFileName : PChar; // relative file name
DestinationFileName : PCHAR; // absolute file name;
// valid for add and extract only!
Flags, // see ACE_FILEFLAG defines below
CRC32,
Method, // 0=stored, 1=LZ77, 2=V20Compression
Dictionary // DictionarySize = 2^Dictionary
: ulong;
CompressedSize,
Size : Int64;
Time,
Attributes : ulong;
Reserved : array[0..63] of char;
// filled with zeros
end;
pACEFileDataStruc = ^tACEFileDataStruc;
////////////////////////////////////////////////////////////////////////
// Is passed to ACEInfoCallbackProc with ACE_CALLBACK_INFO_COPY as code.
// Informs application about the progress of copying either an archive to
// a temporary archive, or a temporary archive back to a normal archive.
tACECopyInfoStruc = packed record
SourceFileName : PChar; // source file
DestinationFileName : PChar; // the file copying the source to
CopiedBytes, // bytes already copied
FileSize : int64; // source file size
Reserved : array[0..63] of char; // filled with zeros
end;
pACECopyInfoStruc = ^tACECopyInfoStruc;
////////////////////////////////////////////////////////////////////////
// operation progress structure
// Used to state the progress of the current operation.
tACEProgressDataStruc = packed record
Addr : PChar; // address of uncompressed data block
Size : ulong; // size of uncompressed data block
TotalProcessedSize : int64; // counted by Dll:
// total uncompressed bytes processed
TotalCompressedSize : int64; // total compressed bytes processed
TotalSize : int64; // total uncompressed bytes to process
// (sum of all original file sizes)
FileProcessedSize : int64; // uncompr. bytes of file processed
FileCompressedSize : int64; // compr. bytes of file processed
FileSize : int64; // uncompressed file size
end;
pACEProgressDataStruc = ^tACEProgressDataStruc;
////////////////////////////////////////////////////////////////////////
// Part 1.2: structures used in function structures
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// file list structure
// This structure is used in the function specific structures.
// The application has to use this structure to indicate which files
// have to be processed by the DLL.
tACEFilesStruc = packed record
SourceDir : PChar; // maybe a real or an archive directory
FileList : PChar; // pointer to list of files to process;
// zero-terminated; files have to be
// separated by carriage-return (0xd);
// FileList may/will be modified by the
// Dll; if nothing is specified, "*"
// will be used
// (attention at ACEDelete!!)
ExcludeList : PChar; // list of files to exclude from process
FullMatch : LongBool; // specifications must fully match
// (no files with the same name in
// subdirs are processed)
RecurseSubDirs: LongBool; // recurse subdirectories
// (valid for add operations only)
Reserved : array[0..59] of char;
// has to be filled with zeros
// for future: possibly in-/excluding
// file attributes and date/time range
end;
pACEFilesStruc = ^tACEFilesStruc;
////////////////////////////////////////////////////////////////////////
// V2.0 compression structure
// Specifies whether to use v2.0 compression or not. If you use v2.0
// compression you can also specify which v2.0 compression techniques
// you want to use. (ACE only)
tACEV20CompressionStruc = packed record
DoUse, // if DoUse=1 and all other fields are
DoUseDelta, // zero, then all v2.0 compression
DoUseExe, // techniques will be used
DoUsePic,
DoUseSound : LongBool;
Reserved : array[0..63] of char; // has to be filled with zeros
end;
////////////////////////////////////////////////////////////////////////
// compression parameter structure
// Used in tACEAddStruc and tACEDeleteStruc. (ACE only)
// typedef struct sACECompressParamsStruc
tACECompressParamsStruc = packed record
Level, // see ACE_LEVEL constants below
Dictionary : ulong; // 15(32k)..22(4Mb)
V20Compression : tACEV20CompressionStruc;
// indicates if (or which) v2.0
// compression techniques shall be used
TestAfter : LongBool; // make a test for CRC check errors
// after compression
Reserved : array[0..63] of char; // has to be filled with zeros
end;
////////////////////////////////////////////////////////////////////////
// PART 2: ACE.DLL CALLBACK DECLARATIONS
////////////////////////////////////////////////////////////////////////
//
// ACE.DLL makes use of four callback functions to exchange data
// with the application:
//
// 1) InfoCallbackProc (pACEInfoCallbackProcStruc Info)
// 2) ErrorCallbackProc (pACEErrorCallbackProcStruc Error)
// 3) RequestCallbackProc(pACERequestCallbackProcStruc Request)
// 4) StateCallbackProc (pACEStateCallbackProcStruc State)
//
// Meaning of different callback types:
// Info - lets the application know about actions that take some
// time but are not essential
// (Code is one of ACE_CALLBACK_INFO constants)
// Error - an error occured; if the reason for this error can
// be solved by the application then the Dll can continue
// the current operation, otherwise the operation has to
// be canceled
// (Code is one of ACE_CALLBACK_ERROR constants)
// Request - the Dll needs some user input
// for ex.: "Overwrite file? (yes/no/cancel)"
// (Code is one of ACE_CALLBACK_REQUEST constants)
// State - Dll informs application about the progress of an operation
// (Code is one of ACE_CALLBACK_STATE constants)
//
// The pointers to the callback functions has to be set by the application
// when calling ACEInitDll(). If the application does not install
// a callback function, is has set the corresponding pointer to NULL.
// If the ACE.DLL has to call the Error or Request callback function
// and they are not installed, the ACE.DLL will cancel the operation.
//
// The application has the possibility to cancel the current operation
// at each callback function call. So if the user clicks on a Cancel-button,
// the application should return ACE_CALLBACK_RETURN_CANCEL at the next
// callback function call.
//
// All callback function parameters are declared as unions.
// The StructureType field contains he type of the structure which is used.
// When the application knows which type of structure it has to use,
// it will have to interpret the Code field to get to know the reason
// for the callback function call.
//
// Contents:
// Part 2.1: operation types
// Part 2.2: callback function return codes
// Part 2.3: callback structure types
// Part 2.4: callback structures
// Part 2.5: info callback function
// Part 2.6: error callback function
// Part 2.7: request callback function
// Part 2.8: state callback function
////////////////////////////////////////////////////////////////////////
// Part 2.4: different callback structures
// These are the declarations of the different structures used in the
// unions passed by the callback functions.
//-----------------------------------------------------------------------
// Only the Dll GlobalData is passed to the application.
//-----------------------------------------------------------------------
tACECallbackGlobalStruc = packed record
//??? StructureType : ulong; // is ACE_CALLBACK_TYPE_GLOBAL
Code : ulong; // see definition of
// ACE_CALLBACK_TYPE_GLOBAL
Operation : ulong; // ACE_CALLBACK_OPERATION constant
GlobalData : pACEGlobalDataStruc; // see tACEGlobalDataStruc
end;
pACECallbackGlobalStruc = ^tACECallbackGlobalStruc;
//-----------------------------------------------------------------------
// The Dll GlobalData and the ArchiveData are passed.
//-----------------------------------------------------------------------
tACECallbackArchiveStruc = packed record
//??? StructureType : ulong; // is ACE_CALLBACK_TYPE_ARCHIVE
Code : ulong; // see definition of
// ACE_CALLBACK_TYPE_ARCHIVE
Operation : ulong; // ACE_CALLBACK_OPERATION constant
GlobalData : pACEGlobalDataStruc; // see tACEGlobalDataStruc
ArchiveData : pACEArchiveDataStruc; // see tACEArchiveDataStruc
end;
pACECallbackArchiveStruc = ^tACECallbackArchiveStruc;
//-----------------------------------------------------------------------
// GlobalData, ArchiveData and FileData are passed.
//-----------------------------------------------------------------------
tACECallbackArchivedFileStruc = packed record
//??? StructureType : ulong; // is ACE_CALLBACK_TYPE_ARCHIVEDFILE
Code : ulong; // see definition of
// ACE_CALLBACK_TYPE_ARCHIVEDFILE
Operation : ulong; // ACE_CALLBACK_OPERATION constant
GlobalData : pACEGlobalDataStruc; // see tACEGlobalDataStruc
ArchiveData : pACEArchiveDataStruc; // see tACEArchiveDataStruc
FileData : pACEFileDataStruc; // see tACEFileDataStruc
end;
pACECallbackArchivedFileStruc = ^tACECallbackArchivedFileStruc;
//-----------------------------------------------------------------------
// GlobalData, ArchiveData and a FileName are passed.
//-----------------------------------------------------------------------
tACECallbackRealFileStruc = packed record
//??? StructureType : ulong; // is ACE_CALLBACK_TYPE_REALFILE
Code : ulong; // see definition of
// ACE_CALLBACK_TYPE_REALFILE
Operation : ulong; // ACE_CALLBACK_OPERATION constant
GlobalData : pACEGlobalDataStruc; // see tACEGlobalDataStruc
ArchiveData : pACEArchiveDataStruc; // see tACEArchiveDataStruc
FileName : PChar; // name of file
end;
pACECallbackRealFileStruc = ^tACECallbackRealFileStruc;
//-----------------------------------------------------------------------
// GlobalData, ArchiveData, the path of temp directory and the
// bytes required in temp directory (archive size) are passed.
//-----------------------------------------------------------------------
tACECallbackSpaceStruc = packed record
//??? StructureType : ulong; // is ACE_CALLBACK_TYPE_SPACE
Code : ulong; // see definition of
// ACE_CALLBACK_TYPE_SPACE
Operation : ulong;
GlobalData : pACEGlobalDataStruc; // see tACEGlobalDataStruc
ArchiveData : pACEArchiveDataStruc; // see tACEArchiveDataStruc
Directory : PChar; // path of directory
ArchiveSize : int64; // bytes required in temp dir
end;
pACECallbackSpaceStruc = ^tACECallbackSpaceStruc;
//-----------------------------------------------------------------------
// GlobalData, ArchiveData and SFXFileName are passed.
//-----------------------------------------------------------------------
tACECallbackSFXFileStruc = packed record
//??? StructureType : ulong; // is ACE_CALLBACK_TYPE_SFXFILE
Code : ulong; // see definition of
// ACE_CALLBACK_TYPE_SFXFILE
Operation : ulong; // ACE_CALLBACK_OPERATION constant
GlobalData : pACEGlobalDataStruc; // see tACEGlobalDataStruc
ArchiveData : pACEArchiveDataStruc; // see tACEArchiveDataStruc
SFXFileName : PChar; // name of SFX
end;
pACECallbackSFXFileStruc = ^tACECallbackSFXFileStruc;
//-----------------------------------------------------------------------
// GlobalData, ArchiveData and CopyData are passed.
//-----------------------------------------------------------------------
tACECallbackCopyStruc = packed record
//??? StructureType : ulong; // is ACE_CALLBACK_TYPE_COPY
Code : ulong; // see definition of
// ACE_CALLBACK_TYPE_COPY
Operation : ulong; // ACE_CALLBACK_OPERATION constant
GlobalData : pACEGlobalDataStruc; // see tACEGlobalDataStruc
ArchiveData : pACEArchiveDataStruc; // see tACEArchiveDataStruc
CopyData : pACECopyInfoStruc; // see tACECopyInfoStruc
end;
pACECallbackCopyStruc = ^tACECallbackCopyStruc;
//-----------------------------------------------------------------------
// GlobalData, ArchiveData, FileData and ProgressData are passed.
//-----------------------------------------------------------------------
tACECallbackProgressStruc = packed record
//??? StructureType : ulong; // is ACE_CALLBACK_TYPE_COPY
Code : ulong; // see definition of
// ACE_CALLBACK_TYPE_COPY
Operation : ulong; // ACE_CALLBACK_OPERATION constant
GlobalData : pACEGlobalDataStruc; // see tACEGlobalDataStruc
ArchiveData : pACEArchiveDataStruc; // see tACEArchiveDataStruc
FileData : pACEFileDataStruc; // see tACEFileDataStruc
ProgressData : pACEProgressDataStruc; // see tACEProgressDataStruc
end;
pACECallbackProgressStruc = ^tACECallbackProgressStruc;
//-----------------------------------------------------------------------
// GlobalData, ArchiveData, FileData and CRC-check result are passed.
//-----------------------------------------------------------------------
tACECallbackCRCCheckStruc = packed record
//??? StructureType : ulong; // is ACE_CALLBACK_TYPE_COPY
Code : ulong; // see definition of
// ACE_CALLBACK_TYPE_COPY
Operation : ulong; // ACE_CALLBACK_OPERATION constant
GlobalData : pACEGlobalDataStruc; // see tACEGlobalDataStruc
ArchiveData : pACEArchiveDataStruc; // see tACEArchiveDataStruc
FileData : pACEFileDataStruc; // see tACEFileDataStruc
CRCOk : LongBool; // CRC-check result
end;
pACECallbackCRCCheckStruc = ^tACECallbackCRCCheckStruc;
////////////////////////////////////////////////////////////////////////
// Part 2.5: info callback function
// Declaration of ACEInfoCallbackProc() parameter and explanation of
// callback info codes.
//-----------------------------------------------------------------------
// Union parameter used at ACEInfoCallbackProc().
//-----------------------------------------------------------------------
tACEInfoCallbackProcStruc = packed record
case StructureType : ulong of
0 : (Global : tACECallbackGlobalStruc);
1 : (Archive : tACECallbackArchiveStruc);
2 : (RealFile : tACECallbackRealFileStruc);
3 : (Copy : tACECallbackCopyStruc);
end;
pACEInfoCallbackProcStruc = ^tACEInfoCallbackProcStruc;
//ΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝ
//=================--- Part 2.6: error callback function ---===============
//ΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝ
// Declaration of ACEErrorCallbackProc() parameter and explanation of
// callback error codes.
//---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// Union parameter used at ACEErrorCallbackProc().
//-----------------------------------------------------------------------
tACEErrorCallbackProcStruc = packed record
case StructureType : ulong of
0 : (Global : tACECallbackGlobalStruc);
1 : (Archive : tACECallbackArchiveStruc);
2 : (ArchivedFile : tACECallbackArchivedFileStruc);
3 : (RealFile : tACECallbackRealFileStruc);
4 : (Space : tACECallbackSpaceStruc);
5 : (SFXFile : tACECallbackSFXFileStruc);
end;
pACEErrorCallbackProcStruc = ^tACEErrorCallbackProcStruc;
//-----------------------------------------------------------------------
// This structure is used by the ACEErrorCallback function to inform
// the application about errors. The Code field of the used structure
// contains an ACE_CALLBACK_ERROR value. At most problems modifications
// to the passed structure can be made to fix it. Other problems can not
// be solved and cause an operation abort immediately.
// ErrorCallbackProc() has to return either ACE_CALLBACK_RETURN_OK or
// ACE_CALLBACK_RETURN_CANCEL.
//-----------------------------------------------------------------------
//ΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝ
//================--- Part 2.7: request callback function ---==============
//ΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝ
// Declaration of ACERequestCallbackProc() parameter and explanation of
// callback request codes.
//---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// Union parameter used at ACERequestCallbackProc().
//-----------------------------------------------------------------------
tACERequestCallbackProcStruc = packed record
case StructureType : ulong of
0 : (Global : tACECallbackGlobalStruc);
1 : (Archive : tACECallbackArchiveStruc);
2 : (ArchivedFile : tACECallbackArchivedFileStruc);
3 : (RealFile : tACECallbackRealFileStruc);
end;
pACERequestCallbackProcStruc = ^tACERequestCallbackProcStruc;
//-----------------------------------------------------------------------
// Question constants are passed to the RequestCallbackProc callback
// function to request further data.
// RequestCallbackProc may return ACE_CALLBACK_RETURN_OK,
// ACE_CALLBACK_RETURN_NO or ACE_CALLBACK_RETURN_CANCEL.
//-----------------------------------------------------------------------
//ΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝ
//=================--- Part 2.8: state callback function ---===============
//ΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝΝ
// Declaration of ACEStateCallbackProc() parameter and explanation of
// callback state codes.
//---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// Union parameter used at ACEStateCallbackProc().
//-----------------------------------------------------------------------
tACEStateCallbackProcStruc = packed record
case StructureType : ulong of
0 : (Archive : tACECallbackArchiveStruc);
1 : (ArchivedFile : tACECallbackArchivedFileStruc);
2 : (RealFile : tACECallbackRealFileStruc);
3 : (Progress : tACECallbackProgressStruc);
4 : (CRCCheck : tACECallbackCRCCheckStruc);
end;
pACEStateCallbackProcStruc = ^tACEStateCallbackProcStruc;
//-----------------------------------------------------------------------
// Calls to (*StateCallbackProc)() with ACE_CALLBACK_STATE values in the
// Code field are made to enable the application to show the progress of
// an operation.
//-----------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////
// Part 3.2: functions and parameter structures
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// ACEInitDll
// Initializes ACE dynamic link library. Has to be called before any
// other function call. May be called more than one time.
// ACEInitDll() parameter structure.
tACEInitDllStruc = packed record
GlobalData : tACEGlobalDataStruc;
Reserved : array[0..63] of char; // has to be filled with zeroes
end;
pACEInitDllStruc = ^tACEInitDllStruc;
// ACEInitDll() function declaration.
TACEInitDllProc = function(DllDate : pACEInitDllStruc) : integer; stdcall;
////////////////////////////////////////////////////////////////////////
// ACEReadArchiveData
// Tests a file whether it is an archive or not and reads out the archive
// data.
// ACEReadArchiveData() parameter structure.
tACEReadArchiveDataStruc = packed record
ArchiveData : tACEArchiveDataStruc; // if this pointer is NULL, the
// file passed to ACEReadArchiveData
// is no archive; otherwise it points
// to a tACEArchiveDataStruc structure
// that contains information about the
// archive
Reserved : array[0..63] of char; // has to be filled with zeroes
end;
pACEReadArchiveDataStruc = ^tACEReadArchiveDataStruc;
// ACEReadArchiveData() function declaration.
TACEReadArchiveDataProc = function(ArchiveName : PChar;
ArchiveData : pACEReadArchiveDataStruc) : integer; stdcall;
////////////////////////////////////////////////////////////////////////
// ACEList
// Passes the specified files in the archive to StateCallbackProc().
// ACEList() parameter structure.
tACEListStruc = packed record
Files : tACEFilesStruc; // specifies files to be listed;
// see tACEFilesStruc structure
Reserved : array[0..63] of char; // has to be filled with zeroes
end;
pACEListStruc = ^tACEListStruc;
// ACEList() function declaration.
TACEListProc = function(ArchiveName : PChar;
List : pACEListStruc) : integer; stdcall;
////////////////////////////////////////////////////////////////////////
// ACETest
// Tests specified files in archive.
// ACETest() parameter structure.
tACETestStruc = packed record
Files : tACEFilesStruc; // specifies files to test;
// see tACEFilesStruc structure
DecryptPassword : PChar; // zero-terminated string,
// case-sensitive (maxlen=56)
Reserved : array[0..63] of char; // has to be filled with zeroes
end;
pACETestStruc = ^tACETestStruc;
// ACETest() function declaration.
TACETestProc = function(ArchiveName : PChar;
List : pACETestStruc) : integer; stdcall;
////////////////////////////////////////////////////////////////////////
// ACEExtract
// Extracts specified files.
// ACEExtract() parameter structure.
tACEExtractStruc = packed record
Files : tACEFilesStruc; // specifies files to extract;
// see tACEFilesStruc structure
DestinationDir : PChar; // directory to extract files to
ExcludePath : LongBool; // extract files without path
DecryptPassword : PChar; // password for decryption (if files
// are encrypted);
// zero-terminated string,
// case-sensitive (maxlen=56)
Reserved : array[0..63] of char; // has to be filled with zeroes
end;
pACEExtractStruc = ^tACEExtractStruc;
// ACEExtract() function declaration.
TACEExtractProc = function(ArchiveName : PChar;
Extract : pACEExtractStruc) : integer; stdcall;
const
FILELISTSIZE = 32768; // pretty much for this this example:
// only the commandline can be used to
// specify files..
COMMENTBUFSIZE = 8192; // comments may be up to 32k in size
// increase it if you want to put that
// large comments to archives, or if
// you want to receive all of these large
// comments (ACE_COMMENT_SMALLBUF returned
// if comment does not fit into buffer)
var
ACEInitDll : TACEInitDllProc;
ACEReadArchiveData : TACEReadArchiveDataProc;
ACEList : TACEListProc;
ACETest : TACETestProc;
ACEExtract : TACEExtractProc;
//==========================================================================
function UnAceDllLoaded(): boolean;
function ExtractAceFile(szArchiveFileName: PChar;
szFileToExtract : PChar;
szTargetFileName : PChar;
iMaxSizeToExtract: longint;
iArchiveOffset : longint): longint;
implementation
uses
{$ifdef mswindows}
Windows
{$ELSE}
{$ENDIF}
UBaseUtils;
var
//FileList : array[0..FILELISTSIZE-1] of char;
//CommentBuf : array[0..COMMENTBUFSIZE-1] of char;
DllHandle: THandle;
DllName : String;
ZString : array[0..256] of char;
iAceDllLoaded: integer;
//DllData : tACEInitDllStruc;
//zTempDir : array[0..255] of char;
//-----------------------------------------------------------------------------
function UnAceDllLoaded(): boolean;
begin
Result := false;
{$ifdef mswindows}
if (iAceDllLoaded = -1) then // we did not try it yet
begin
iAceDllLoaded := 0;
DllName := 'UnAceV2.Dll';
DllHandle := LoadLibrary(StrPCopy(ZString, GetProgramDir + DllName));
if DllHandle <= 32 then exit;
@ACEInitDll :=GetProcAddress(DllHandle,'ACEInitDll');
@ACEReadArchiveData :=GetProcAddress(DllHandle,'ACEReadArchiveData');
@ACEList :=GetProcAddress(DllHandle,'ACEList');
@ACETest :=GetProcAddress(DllHandle,'ACETest');
@ACEExtract :=GetProcAddress(DllHandle,'ACEExtract');
if (@ACEInitDll=nil) or
(@ACEReadArchiveData=nil) or
(@ACEList=nil) or
(@ACETest=nil) or
(@ACEExtract=nil) then
begin
FreeLibrary(DllHandle);
exit;
end;
iAceDllLoaded := 1;
end;
Result := iAceDllLoaded = 1;
{$else}
{$endif}
end;
//-----------------------------------------------------------------------------
var
AceCommentBuf: array[0..COMMENTBUFSIZE-1] of char;
// ACE callback functions
function UnAceInfoProc(Info : pACEInfoCallbackProcStruc) : integer; stdcall;
begin
Result:=ACE_CALLBACK_RETURN_OK;
end;
function UnAceErrorProc(Error : pACEErrorCallbackProcStruc) : integer; stdcall;
begin
Result:=ACE_CALLBACK_RETURN_CANCEL;
end;
function UnAceRequestProc(Request : pACERequestCallbackProcStruc) : integer; stdcall;
begin
Result:=ACE_CALLBACK_RETURN_CANCEL;
end;
function UnAceStateProc(State: pACEStateCallbackProcStruc) : integer; stdcall;
begin
Result:=ACE_CALLBACK_RETURN_OK;
end;
//-----------------------------------------------------------------------------
function ExtractAceFile(szArchiveFileName: PChar;
szFileToExtract : PChar;
szTargetFileName : PChar;
iMaxSizeToExtract: longint;
iArchiveOffset : longint): longint;
var
DllData : tACEInitDllStruc;
//List : tACEListStruc;
zTempDir : array[0..255] of char;
Extract : tACEExtractStruc;
zDestinationDir : array[0..255] of char;
sDestinationDir : ShortString;
zFileName : array[0..255] of char;
begin
Result := 100; // dummy error value
if not UnAceDllLoaded then exit;
FillChar(DllData, SizeOf(DllData), 0);
DllData.GlobalData.MaxArchiveTestBytes := $1ffFF; // search for archive
// header in first 128k
// of file
DllData.GlobalData.MaxFileBufSize := $2ffFF; // read/write buffer size
// is 256k
DllData.GlobalData.Comment.BufSize := SizeOf(AceCommentBuf)-1;
DllData.GlobalData.Comment.Buf := @AceCommentBuf; // set comment bufffer
// to receive comments
// of archive and/or
{$ifdef mswidnows} // set comments
GetTempPath(255, @zTempDir);
DllData.GlobalData.TempDir := @zTempDir;
{$else}
DllData.GlobalData.TempDir := PChar(GetTempDir);
{$endif}
// set callback function pointers
DllData.GlobalData.InfoCallbackProc := @UnAceInfoProc;
DllData.GlobalData.ErrorCallbackProc := @UnAceErrorProc;
DllData.GlobalData.RequestCallbackProc := @UnAceRequestProc;
DllData.GlobalData.StateCallbackProc := @UnAceStateProc;
if (ACEInitDll(@DllData) <> 0) then exit;
FillChar(Extract, SizeOf(Extract), 0); // set all fields to zero
Extract.Files.SourceDir := ''; // archive main directory is
// base dir for FileList
Extract.Files.FileList := szFileToExtract; // set FileList
Extract.Files.ExcludeList := ''; // no files to exclude
Extract.Files.FullMatch := true; // also extract files
// partially matching
sDestinationDir := ExtractFileDir(szTargetFileName);
StrPCopy(zFileName, ExtractFileName(szFileToExtract));
Extract.DestinationDir := StrPCopy(zDestinationDir, sDestinationDir);
// directory to extract to
Extract.ExcludePath := true; // extract files with path - NO
Extract.DecryptPassword := '';
Result := ACEExtract(szArchiveFileName, @Extract);
strcat(@zDestinationDir, '\'#0);
strcat(@zDestinationDir, zFileName);
///MoveFile(@zDestinationDir, szTargetFileName);
end;
//-----------------------------------------------------------------------------
begin
iAceDllLoaded := -1;
end.
|
unit uUsers;
interface
Type
TUser = class
private
Fid: integer;
Fpassword: string;
Flogin: string;
procedure Setid(const Value: integer);
procedure Setlogin(const Value: string);
procedure Setpassword(const Value: string);
published
property id : integer read Fid write Setid;
property login : string read Flogin write Setlogin;
property password : string read Fpassword write Setpassword;
end;
implementation
{ TUser }
procedure TUser.Setid(const Value: integer);
begin
Fid := Value;
end;
procedure TUser.Setlogin(const Value: string);
begin
Flogin := Value;
end;
procedure TUser.Setpassword(const Value: string);
begin
Fpassword := Value;
end;
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit uCodeIntegrator;
{$mode objfpc}{$H+}
interface
uses
uIntegrator, uCodeProvider;
type
TCodeIntegrator = class(TTwowayIntegrator)
private
FCodeProvider: TCodeProvider;
procedure SetCodeProvider(const Value: TCodeProvider);
public
property CodeProvider: TCodeProvider read FCodeProvider write SetCodeProvider;
end;
implementation
procedure TCodeIntegrator.SetCodeProvider(const Value: TCodeProvider);
begin
if Assigned(FCodeProvider) then
begin
FCodeProvider.Free;
FCodeProvider := nil;
end;
FCodeProvider := Value;
end;
end.
|
unit lvl2DData;
interface
type
InvalidLVLFile=class(Exception)
constructor(text: string) :=
inherited Create(text);
end;
TileT=(EmptyTile, WallTile);
lvl2D=class
public tls: array[,] of TileT;
public constructor(fname: string);
end;
implementation
constructor lvl2D.Create(fname: string);
begin
var lns := ReadAllLines(fname);
if lns.Length = 0 then raise new InvalidLVLFile('File can''t be empty');
if lns.Skip(1).Any(s->s.Length<>lns[0].Length) then
raise new InvalidLVLFile('Lines must have the same length');
if lns[0].Length = 0 then raise new InvalidLVLFile('File can''t be empty');
tls := new TileT[lns[0].Length, lns.Length];
for var x := 0 to lns[0].Length-1 do
for var y := 0 to lns.Length-1 do
case lns[y][x+1] of
'-': tls[x,y] := EmptyTile;
'x': tls[x,y] := WallTile;
else raise new InvalidLVLFile($'Invalid char [> {lns[y][x+1]} <]');
end;
end;
end. |
Unit VSockConnector;
Interface
Const
VNCI_VERSION_INVALID = $FFFFFFFF;
Function VSockConn_LocalId:Cardinal; Cdecl;
Function VSockConn_VMCIVersion:Cardinal; Cdecl;
Implementation
Const
LibraryName = 'vsock-connector.dll';
Function VSockConn_LocalId:Cardinal; Cdecl; External LibraryName;
Function VSockConn_VMCIVersion:Cardinal; Cdecl; External LibraryName;
End.
|
unit GlsUvMapFrm;
{ CapeRaven mesh demo.
Changing mesh vertex data, normals and striping redundent data.
Custom cube class declared for vertex point identification.
On moving these vertex modifiers, the apointed vertex follows. }
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
System.Contnrs,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.Menus,
Vcl.ExtDlgs,
Vcl.Dialogs,
Vcl.ComCtrls,
Vcl.Buttons,
OpenGL1x,
GLScene,
GLState,
GLColor,
GLVectorFileObjects,
GLWin32Viewer,
GLVectorLists,
GLVectorGeometry,
GLTexture,
GLObjects,
GLFileOBJ,
GLVectorTypes,
GLMaterial,
GLCoordinates,
GLCrossPlatform,
GLPersistentClasses,
GLMeshUtils,
GLBaseClasses;
type
TDrawingTool = (dtLine, dtRectangle, dtEllipse, dtRoundRect);
type
TModifierCube = class(TGLCube)
public
FVectorIndex: Integer;
FMeshObjIndex: Integer;
constructor Create(AOwner: TComponent); override;
end;
TGLS3dUvForm = class(TForm)
GLScene1: TGLScene;
GLCamera1: TGLCamera;
GLFreeForm1: TGLFreeForm;
ScrollPanel: TPanel;
GLSceneViewer1: TGLSceneViewer;
MainMenu1: TMainMenu;
File1: TMenuItem;
Map1: TMenuItem;
N1: TMenuItem;
ApplyTexture1: TMenuItem;
Open3ds1: TMenuItem;
Save3ds1: TMenuItem;
N2: TMenuItem;
Savemeshasbmp1: TMenuItem;
LoadTexture1: TMenuItem;
Help1: TMenuItem;
Help2: TMenuItem;
About1: TMenuItem;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
OpenPictureDialog1: TOpenPictureDialog;
N256x2561: TMenuItem;
N512x5121: TMenuItem;
StatusBar1: TStatusBar;
N3: TMenuItem;
Mesh1: TMenuItem;
N4: TMenuItem;
Exit1: TMenuItem;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
Panel1: TPanel;
CheckBox1: TCheckBox;
ComboBox2: TComboBox;
ComboBox1: TComboBox;
ScrollBox1: TScrollBox;
Image: TImage;
PenEdit: TEdit;
PenWidth: TUpDown;
MeshSLABtn: TSpeedButton;
BrushColorBtn: TSpeedButton;
ScrollBox2: TScrollBox;
Panel2: TPanel;
btnGroups: TBitBtn;
Button2: TButton;
btnTextcoords: TBitBtn;
btnVertex: TBitBtn;
btnNormals: TBitBtn;
Label1: TLabel;
cbPolygonMode: TComboBox;
chbViewPoints: TCheckBox;
GroupBox1: TGroupBox;
Bevel1: TBevel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
chbShowAxis: TCheckBox;
Label6: TLabel;
tbPos: TTrackBar;
GroupBox2: TGroupBox;
rbXY: TRadioButton;
rbZY: TRadioButton;
MeshDataListBox: TListBox;
Splitter1: TSplitter;
PaintPot1: TMenuItem;
Pen1: TMenuItem;
Brush1: TMenuItem;
SolidPen: TMenuItem;
DashPen: TMenuItem;
DotPen: TMenuItem;
DashDotPen: TMenuItem;
DashDotDotPen: TMenuItem;
ClearPen: TMenuItem;
SolidBrush: TMenuItem;
ClearBrush: TMenuItem;
HorizontalBrush: TMenuItem;
VerticalBrush: TMenuItem;
FDiagonalBrush: TMenuItem;
BDiagonalBrush: TMenuItem;
CrossBrush: TMenuItem;
DiagCrossBrush: TMenuItem;
BrushStyle1: TMenuItem;
Line1: TMenuItem;
Rectangle1: TMenuItem;
Ellipse1: TMenuItem;
RoundRect1: TMenuItem;
BrushColor: TSpeedButton;
PenColor: TSpeedButton;
SaveTexture1: TMenuItem;
SaveAsTexture1: TMenuItem;
N5: TMenuItem;
N1024x10241: TMenuItem;
N128x1281: TMenuItem;
Clear1: TMenuItem;
Image2: TMenuItem;
Cut1: TMenuItem;
Copy1: TMenuItem;
Paste1: TMenuItem;
ColorDialog1: TColorDialog;
dcModifiers: TGLDummyCube;
GLMaterialLibrary1: TGLMaterialLibrary;
procedure FormCreate(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ApplyTexture1Click(Sender: TObject);
procedure Open3ds1Click(Sender: TObject);
procedure Save3ds1Click(Sender: TObject);
procedure LoadTexture1Click(Sender: TObject);
procedure Savemeshasbmp1Click(Sender: TObject);
procedure Help2Click(Sender: TObject);
procedure N256x2561Click(Sender: TObject);
procedure N512x5121Click(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure ComboBox2Change(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure ImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ImageMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure ImageMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PenEditChange(Sender: TObject);
procedure PenColorClick(Sender: TObject);
procedure BrushColorClick(Sender: TObject);
procedure SetBrushStyle(Sender: TObject);
procedure SetPenStyle(Sender: TObject);
procedure SaveStyles;
procedure RestoreStyles;
procedure Line1Click(Sender: TObject);
procedure Rectangle1Click(Sender: TObject);
procedure Ellipse1Click(Sender: TObject);
procedure RoundRect1Click(Sender: TObject);
procedure DrawShape(TopLeft, BottomRight: TPoint; AMode: TPenMode);
procedure SaveTexture1Click(Sender: TObject);
procedure SaveAsTexture1Click(Sender: TObject);
procedure N128x1281Click(Sender: TObject);
procedure N1024x10241Click(Sender: TObject);
procedure Clear1Click(Sender: TObject);
procedure Cut1Click(Sender: TObject);
procedure Copy1Click(Sender: TObject);
procedure Paste1Click(Sender: TObject);
{ Meshedit }
procedure cbPolygonModeChange(Sender: TObject);
procedure SetVertexModifiers;
procedure chbViewPointsClick(Sender: TObject);
procedure ShowModifierStatus(const aObj: TModifierCube);
function MouseWorldPos(X, Y: Integer): TVector;
procedure ChangeMeshVector(const aObj: TModifierCube; const aPos: TVector4f);
procedure GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure chbShowAxisClick(Sender: TObject);
procedure tbPosChange(Sender: TObject);
procedure GLSceneViewer1BeforeRender(Sender: TObject);
procedure btnVertexClick(Sender: TObject);
procedure btnNormalsClick(Sender: TObject);
procedure btnTextcoordsClick(Sender: TObject);
procedure btnGroupsClick(Sender: TObject);
procedure StripAndRecalc;
private
{ Meshedit }
function GetPolygonMode: TPolygonMode;
procedure SetPolygonMode(const Value: TPolygonMode);
property PolygonMode: TPolygonMode read GetPolygonMode write SetPolygonMode;
private
{ Meshedit }
FOldX, FOldY: Integer;
FModifierList: TObjectList;
FSelectedModifier: TModifierCube;
FMoveZ: Boolean;
FOldMouseWorldPos: TVector;
procedure ShowMeshData(const aList: TStringList);
public
{ Painting }
BrushStyle: TBrushStyle;
PenStyle: TPenStyle;
PenWide: Integer;
MeshEditing, Drawing: Boolean;
Origin, MovePt: TPoint;
DrawingTool: TDrawingTool;
CurrentFile: string;
{ Tex Edit }
mx, my: Integer;
procedure GetTexCoordsWireframe;
procedure DisplayHint(Sender: TObject);
end;
TAxis = 0 .. 2;
var
GLS3dUvForm: TGLS3dUvForm;
Filename3DS: String;
procedure UVPlanarMapping(Vertices, TexCoords: TAffineVectorList;
Axis: TAxis = 2);
procedure UVCubicMapping(Vertices, TexCoords: TAffineVectorList;
Axis: TAxis = 2);
procedure UVCylindricalMapping(Vertices, TexCoords: TAffineVectorList;
Axis: TAxis = 2);
procedure UVSphericalMapping(Vertices, TexCoords: TAffineVectorList;
Axis: TAxis = 2);
implementation
uses
Clipbrd,
GlsUvAboutFrm;
{$R *.dfm}
const
{ Default combobox index for startup }
CLinePolyMode = 1;
{ Scale dimention }
CModifierDim = 0.04;
var
{ Modifier colors }
CModColorNormal: TColorVector;
CModColorSelect: TColorVector;
constructor TModifierCube.Create(AOwner: TComponent);
begin
inherited;
{ Set the modifiers initial size and color }
CubeWidth := CModifierDim;
CubeHeight := CModifierDim;
CubeDepth := CModifierDim;
Material.FrontProperties.Diffuse.Color := CModColorNormal;
end;
procedure TGLS3dUvForm.FormCreate(Sender: TObject);
var
s: single;
Bitmap: TBitmap;
begin
MeshEditing := False;
Application.OnHint := DisplayHint;
Bitmap := nil;
try
Bitmap := TBitmap.Create;
Bitmap.Width := 256;
Bitmap.Height := 256;
Bitmap.PixelFormat := pf24bit;
Image.Picture.Graphic := Bitmap;
finally
Bitmap.Free;
end;
Image.Canvas.FillRect(Rect(0, 0, Image.Width, Image.Height));
{ Assertion Error GLVectorFileObjects line 4190 }
{ obj' }
If (not FileExists(ExtractFilePath(ParamStr(0)) + 'cube.3ds')) then
begin
showmessage('cube.3ds file is missing');
Application.Terminate;
end;
GLFreeForm1.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'cube.3ds');
StripAndRecalc;
SetVertexModifiers;
{ GLFreeForm1.LoadFromFile('teapot.3ds'); }
GLFreeForm1.Material.Texture.Image.LoadFromFile('grid.bmp');
GLFreeForm1.Material.Texture.Disabled := False;
GLFreeForm1.Scale.SetVector(0.05, 0.05, 0.05);
s := 4 / (GLFreeForm1.BoundingSphereRadius);
GLFreeForm1.Scale.SetVector(s, s, s);
GLFreeForm1.Pitch(90);
ComboBox2.Itemindex := 0;
ComboBox1.Itemindex := 0;
ComboBox1Change(nil);
FModifierList := TObjectList.Create;
CModColorNormal := clrCoral;
CModColorSelect := clrSkyBlue;
cbPolygonMode.Itemindex := CLinePolyMode;
end;
procedure TGLS3dUvForm.DisplayHint(Sender: TObject);
begin { Both parts if not xx|yyy }
StatusBar1.SimpleText := GetLongHint(Application.Hint);
end;
procedure TGLS3dUvForm.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TGLS3dUvForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ }
end;
procedure TGLS3dUvForm.FormDestroy(Sender: TObject);
begin
FModifierList.Clear;
FreeAndNil(FModifierList);
end;
procedure UVPlanarMapping(Vertices, TexCoords: TAffineVectorList;
Axis: TAxis = 2);
var
i, j: Integer;
P, center, min, max: TAffineVector;
u, v: single;
begin
u := 0;
v := 0; { Compiler shutup }
for i := 0 to Vertices.Count - 1 do
begin
P := Vertices.Items[i];
for j := 0 to 2 do
begin
if i = 0 then
begin
min.V[j] := P.V[j];
max.V[j] := P.V[j];
end
else
begin
if P.V[j] < min.V[j] then
min.V[j] := P.V[j];
if P.V[j] > max.V[j] then
max.V[j] := P.V[j];
end;
end;
end;
center := VectorScale(VectorAdd(max, min), 0.5);
Vertices.Translate(VectorNegate(center));
min := VectorSubtract(min, center);
max := VectorSubtract(max, center);
// Generate texture coordinates
TexCoords.Clear;
for i := 0 to Vertices.Count do
begin
P := Vertices.Items[i];
case Axis of
0:
begin
u := (P.Y / (max.Y - min.Y));
v := (-P.Z / (max.Z - min.Z));
end;
1:
begin
u := (P.X / (max.X - min.X));
v := (-P.Z / (max.Z - min.Z));
end;
2:
begin
u := (P.X / (max.X - min.X));
v := (-P.Y / (max.Y - min.Y));
end;
end;
u := u + 0.5;
v := v + 0.5;
TexCoords.Add(u, v, 0);
end;
end;
procedure UVCubicMapping(Vertices, TexCoords: TAffineVectorList;
Axis: TAxis = 2);
begin
// This one is a little more complicated...I'm working on it
end;
procedure UVCylindricalMapping(Vertices, TexCoords: TAffineVectorList;
Axis: TAxis = 2);
var
i, j: Integer;
P, Pn, center, min, max: TAffineVector;
{ temp, } u, v: single;
begin
u := 0;
v := 0; { Compiler shutup }
// Get the center
for i := 0 to Vertices.Count - 1 do
begin
P := Vertices.Items[i];
for j := 0 to 2 do
begin
if i = 0 then
begin
min.V[j] := P.V[j];
max.V[j] := P.V[j];
end
else
begin
if P.V[j] < min.V[j] then
min.V[j] := P.V[j];
if P.V[j] > max.V[j] then
max.V[j] := P.V[j];
end;
end;
end;
center := VectorScale(VectorAdd(max, min), 0.5);
Vertices.Translate(VectorNegate(center));
min := VectorSubtract(min, center);
max := VectorSubtract(max, center);
// Generate texture coordinates
TexCoords.Clear;
for i := 0 to Vertices.Count do
begin
P := Vertices.Items[i];
Pn := VectorNormalize(P);
case Axis of
0:
begin
u := ArcTan2(Pn.Z, -Pn.Y) / 2;
v := (P.X / (max.X - min.X));
end;
1:
begin
u := arctan2(-Pn.X, Pn.Z) / 2;
v := (P.Y / (max.Y - min.Y));
end;
2:
begin
u := arctan2(-Pn.X, -Pn.Y) / 2;
v := (P.Z / (max.Z - min.Z));
end;
end;
u := 0.5 - u / Pi;
u := u - floor(u);
v := v + 0.5;
TexCoords.Add(u, v, 0);
end;
end;
procedure UVSphericalMapping(Vertices, TexCoords: TAffineVectorList;
Axis: TAxis = 2);
var
i, j: Integer;
P, center, min, max: TAffineVector;
{ radius, }
{ temp, } u, v: single;
begin
u := 0;
v := 0; { Compiler shutup }
// Get the center
for i := 0 to Vertices.Count - 1 do
begin
P := Vertices.Items[i];
for j := 0 to 2 do
begin
if i = 0 then
begin
min.V[j] := P.V[j];
max.V[j] := P.V[j];
end
else
begin
if P.V[j] < min.V[j] then
min.V[j] := P.V[j];
if P.V[j] > max.V[j] then
max.V[j] := P.V[j];
end;
end;
end;
center := VectorScale(VectorAdd(max, min), 0.5);
Vertices.Translate(VectorNegate(center));
// Generate texture coordinates
TexCoords.Clear;
for i := 0 to Vertices.Count do
begin
P := VectorNormalize(Vertices.Items[i]);
case Axis of
0:
begin
u := arctan2(P.Z, -P.Y);
v := arctan(P.X / sqrt(P.Y * P.Y + P.Z * P.Z));
end;
1:
begin
u := arctan2(-P.X, P.Z);
v := arctan(P.Y / sqrt(P.X * P.X + P.Z * P.Z));
end;
2:
begin
u := arctan2(-P.X, -P.Y);
v := arctan(P.Z / sqrt(P.X * P.X + P.Y * P.Y));
end;
end;
u := 1 - u / (2 * Pi);
v := abs(0.5 - v / Pi);
u := u - floor(u);
TexCoords.Add(u, v, 0);
end;
end;
procedure TGLS3dUvForm.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
lCurrentPos: TVector;
lOldV: TVector3f;
lDiff: TVector4f;
begin
If MeshEditing then
begin
{ If ctrl is not in use, move around freeform }
if (ssLeft in Shift) and (not(ssCtrl in Shift)) then
begin
GLCamera1.MoveAroundTarget(FOldY - Y, FOldX - X);
FOldX := X;
FOldY := Y;
Exit;
end;
{ Move modifier and change relevant vertex data }
if (ssLeft in Shift) then
begin
FMoveZ := rbZY.Checked;
lCurrentPos := MouseWorldPos(X, Y);
if Assigned(FSelectedModifier) and (VectorNorm(FOldMouseWorldPos) <> 0)
then
begin
MakeVector(lOldV, FSelectedModifier.Position.X,
FSelectedModifier.Position.Y, FSelectedModifier.Position.Z);
lDiff := VectorSubtract(lCurrentPos, FOldMouseWorldPos);
FSelectedModifier.Position.Translate(lDiff);
ChangeMeshVector(FSelectedModifier, lDiff);
end;
FOldMouseWorldPos := lCurrentPos;
end;
end
else
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my - Y, mx - X);
mx := X;
my := Y;
end;
end;
procedure TGLS3dUvForm.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
lObj: TGLBaseSceneObject;
begin
If MeshEditing then
begin
FOldX := X;
FOldY := Y;
{ If selecting a different modifier, change the last one's color back to default }
if Assigned(FSelectedModifier) then
FSelectedModifier.Material.FrontProperties.Diffuse.Color :=
CModColorNormal;
{ Get selected objects }
if not(ssCtrl in Shift) then
Exit;
{ Check if selected object is a modifier.
If so, change modifiers color as to indicated selected modifier. }
lObj := GLSceneViewer1.Buffer.GetPickedObject(X, Y);
if (lObj is TModifierCube) then
begin
FSelectedModifier := TModifierCube(lObj);
FSelectedModifier.Material.FrontProperties.Diffuse.Color :=
CModColorSelect;
FSelectedModifier.NotifyChange(FSelectedModifier);
ShowModifierStatus(TModifierCube(lObj));
FMoveZ := rbZY.Checked;
FOldMouseWorldPos := MouseWorldPos(X, Y);
end;
end
else
begin
mx := X;
my := Y;
end;
end;
procedure TGLS3dUvForm.GLSceneViewer1MouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
If MeshEditing then
begin
if Assigned(FSelectedModifier) then
begin
FSelectedModifier.Material.FrontProperties.Diffuse.Color :=
CModColorNormal;
FSelectedModifier := nil;
{ Recalculate structure and redraw freeform }
StripAndRecalc;
{ Reset vertex modifiers and their data. }
SetVertexModifiers;
end;
end;
end;
procedure TGLS3dUvForm.GetTexCoordsWireframe;
var
i, j, X, Y, x0, y0: Integer;
fg: TFGVertexIndexList;
begin
x0 := 0;
y0 := 0; { Compiler shut up }
GLS3dUvForm.Image.Canvas.FillRect(Rect(0, 0, GLS3dUvForm.Image.Width,
GLS3dUvForm.Image.Height));
GLS3dUvForm.Image.Canvas.Pen.Color := clBlack;
with GLS3dUvForm.GLFreeForm1.MeshObjects.Items[0] do
begin
for i := 0 to FaceGroups.Count - 1 do
begin
fg := TFGVertexIndexList(FaceGroups.Items[i]);
for j := 0 to fg.VertexIndices.Count - 1 do
begin
if j = 0 then
begin
x0 := round(TexCoords.Items[fg.VertexIndices.Items[j]].X *
GLS3dUvForm.Image.Width);
y0 := round(TexCoords.Items[fg.VertexIndices.Items[j]].Y *
GLS3dUvForm.Image.Height);
Image.Canvas.MoveTo(x0, y0);
end
else
begin
X := round(TexCoords.Items[fg.VertexIndices.Items[j]].X *
GLS3dUvForm.Image.Width);
Y := round(TexCoords.Items[fg.VertexIndices.Items[j]].Y *
GLS3dUvForm.Image.Height);
Image.Canvas.LineTo(X, Y);
end;
end;
Image.Canvas.LineTo(x0, y0);
end;
end;
end;
procedure TGLS3dUvForm.ApplyTexture1Click(Sender: TObject);
begin
ApplyTexture1.Checked := (not ApplyTexture1.Checked);
If ApplyTexture1.Checked then
GLFreeForm1.Material.Texture.Disabled := False
else
GLFreeForm1.Material.Texture.Disabled := True;
end;
procedure TGLS3dUvForm.Open3ds1Click(Sender: TObject);
var
s: single;
begin
If OpenDialog1.Execute then
begin
Image.Canvas.FillRect(Rect(0, 0, Image.Width, Image.Height));
GLFreeForm1.LoadFromFile(OpenDialog1.Filename { 'teapot.3ds' } );
Filename3DS := OpenDialog1.Filename;
{ Need a Autoscale function here
GLFreeForm1.Scale.SetVector(0.05,0.05,0.05); }
s := 4 / (GLFreeForm1.BoundingSphereRadius);
GLFreeForm1.Scale.SetVector(s, s, s);
ComboBox1Change(nil);
GLFreeForm1.Pitch(90);
StripAndRecalc;
SetVertexModifiers;
end;
end;
procedure TGLS3dUvForm.Save3ds1Click(Sender: TObject);
begin
{ Save as WHATEVER GLSCENE USES that has UV Coords... }
{ SaveDialog1.Filter:='*.obj'; }
SaveDialog1.Filename := ChangeFileExt(OpenDialog1.Filename, '.obj');
If SaveDialog1.Execute then
GLFreeForm1.SaveToFile(SaveDialog1.Filename);
end;
procedure TGLS3dUvForm.LoadTexture1Click(Sender: TObject);
begin
If OpenPictureDialog1.Execute then
begin
GLFreeForm1.Material.Texture.Image.LoadFromFile
(OpenPictureDialog1.Filename);
GLFreeForm1.Material.Texture.Disabled := False;
CurrentFile := OpenPictureDialog1.Filename;
SaveStyles;
Image.Picture.LoadFromFile(CurrentFile);
Image.Picture.Bitmap.PixelFormat := pf24bit;
RestoreStyles;
end;
end;
procedure TGLS3dUvForm.SaveTexture1Click(Sender: TObject);
begin
if CurrentFile <> EmptyStr then
Image.Picture.SaveToFile(CurrentFile)
else
SaveAsTexture1Click(Sender);
end;
procedure TGLS3dUvForm.SaveAsTexture1Click(Sender: TObject);
begin
if SaveDialog1.Execute then
begin
CurrentFile := SaveDialog1.Filename;
SaveTexture1Click(Sender);
end;
end;
procedure TGLS3dUvForm.Clear1Click(Sender: TObject);
begin
Image.Canvas.FillRect(Rect(0, 0, Image.Width, Image.Height));
GetTexCoordsWireframe;
end;
procedure TGLS3dUvForm.N128x1281Click(Sender: TObject);
begin
Image.Picture.Bitmap.Width := 128;
Image.Picture.Bitmap.Height := 128;
Image.Canvas.FillRect(Rect(0, 0, Image.Width, Image.Height));
GetTexCoordsWireframe;
end;
procedure TGLS3dUvForm.N256x2561Click(Sender: TObject);
begin
Image.Picture.Bitmap.Width := 256;
Image.Picture.Bitmap.Height := 256;
Image.Canvas.FillRect(Rect(0, 0, Image.Width, Image.Height));
GetTexCoordsWireframe;
end;
procedure TGLS3dUvForm.N512x5121Click(Sender: TObject);
begin
Image.Picture.Bitmap.Width := 512;
Image.Picture.Bitmap.Height := 512;
Image.Canvas.FillRect(Rect(0, 0, Image.Width, Image.Height));
GetTexCoordsWireframe;
end;
procedure TGLS3dUvForm.N1024x10241Click(Sender: TObject);
begin
Image.Picture.Bitmap.Width := 1024;
Image.Picture.Bitmap.Height := 1024;
Image.Canvas.FillRect(Rect(0, 0, Image.Width, Image.Height));
GetTexCoordsWireframe;
end;
procedure TGLS3dUvForm.Savemeshasbmp1Click(Sender: TObject);
begin { ? 32 bit for transparency ? or leave it to them? }
Image.Picture.Bitmap.PixelFormat := pf24bit;
Image.Picture.Bitmap.SaveToFile(ChangeFileExt(Filename3DS, '.bmp'))
end;
procedure TGLS3dUvForm.Help2Click(Sender: TObject);
begin
showmessage('Under Construction');
end;
procedure TGLS3dUvForm.ComboBox1Change(Sender: TObject);
begin
with GLFreeForm1.MeshObjects.Items[0] do
begin
case ComboBox2.Itemindex of
0:
UVPlanarMapping(Vertices, TexCoords, ComboBox1.Itemindex);
1:
UVCubicMapping(Vertices, TexCoords, ComboBox1.Itemindex);
2:
UVCylindricalMapping(Vertices, TexCoords, ComboBox1.Itemindex);
3:
UVSphericalMapping(Vertices, TexCoords, ComboBox1.Itemindex);
end;
end;
GetTexCoordsWireframe;
GLFreeForm1.StructureChanged;
end;
procedure TGLS3dUvForm.ComboBox2Change(Sender: TObject);
begin
ComboBox1Change(nil);
end;
procedure TGLS3dUvForm.CheckBox1Click(Sender: TObject);
begin
if CheckBox1.Checked then
GLFreeForm1.NormalsOrientation := mnoInvert
else
GLFreeForm1.NormalsOrientation := mnoDefault;
end;
procedure TGLS3dUvForm.About1Click(Sender: TObject);
begin
AboutBox.ShowModal;
end;
(* ******************************************** *)
(* ******************************************** *)
(* ******************************************** *)
(* ******************************************** *)
procedure TGLS3dUvForm.ImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Drawing := True;
Image.Canvas.MoveTo(X, Y);
Origin := Point(X, Y);
MovePt := Origin;
StatusBar1.Panels[0].Text := Format('Origin: (%d, %d)', [X, Y]);
end;
procedure TGLS3dUvForm.ImageMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if Drawing then
begin
DrawShape(Origin, MovePt, pmNotXor);
MovePt := Point(X, Y);
DrawShape(Origin, MovePt, pmNotXor);
end;
StatusBar1.Panels[1].Text := Format('Current: (%d, %d)', [X, Y]);
end;
procedure TGLS3dUvForm.ImageMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Drawing then
begin
DrawShape(Origin, Point(X, Y), pmCopy);
Drawing := False;
end;
end;
(* ******************************************** *)
(* ******************************************** *)
procedure TGLS3dUvForm.PenEditChange(Sender: TObject);
begin
Image.Canvas.Pen.Width := PenWidth.Position;
end;
procedure TGLS3dUvForm.PenColorClick(Sender: TObject);
begin
ColorDialog1.Color := Image.Canvas.Pen.Color;
if ColorDialog1.Execute then
Image.Canvas.Pen.Color := ColorDialog1.Color;
end;
procedure TGLS3dUvForm.BrushColorClick(Sender: TObject);
begin
ColorDialog1.Color := Image.Canvas.Brush.Color;
if ColorDialog1.Execute then
Image.Canvas.Brush.Color := ColorDialog1.Color;
end;
procedure TGLS3dUvForm.SetPenStyle(Sender: TObject);
begin
with Image.Canvas.Pen do
begin
if Sender = SolidPen then
Style := psSolid
else if Sender = DashPen then
Style := psDash
else if Sender = DotPen then
Style := psDot
else if Sender = DashDotPen then
Style := psDashDot
else if Sender = DashDotDotPen then
Style := psDashDotDot
else if Sender = ClearPen then
Style := psClear;
end;
end;
procedure TGLS3dUvForm.SetBrushStyle(Sender: TObject);
begin
with Image.Canvas.Brush do
begin
if Sender = SolidBrush then
Style := bsSolid
else if Sender = ClearBrush then
Style := bsClear
else if Sender = HorizontalBrush then
Style := bsHorizontal
else if Sender = VerticalBrush then
Style := bsVertical
else if Sender = FDiagonalBrush then
Style := bsFDiagonal
else if Sender = BDiagonalBrush then
Style := bsBDiagonal
else if Sender = CrossBrush then
Style := bsCross
else if Sender = DiagCrossBrush then
Style := bsDiagCross;
end;
end;
procedure TGLS3dUvForm.SaveStyles;
begin
with Image.Canvas do
begin
BrushStyle := Brush.Style;
PenStyle := Pen.Style;
PenWide := Pen.Width;
end;
end;
procedure TGLS3dUvForm.RestoreStyles;
begin
with Image.Canvas do
begin
Brush.Style := BrushStyle;
Pen.Style := PenStyle;
Pen.Width := PenWide;
end;
end;
procedure TGLS3dUvForm.Line1Click(Sender: TObject);
begin
DrawingTool := dtLine;
end;
procedure TGLS3dUvForm.Rectangle1Click(Sender: TObject);
begin
DrawingTool := dtRectangle;
end;
procedure TGLS3dUvForm.Ellipse1Click(Sender: TObject);
begin
DrawingTool := dtEllipse;
end;
procedure TGLS3dUvForm.RoundRect1Click(Sender: TObject);
begin
DrawingTool := dtRoundRect;
end;
procedure TGLS3dUvForm.DrawShape(TopLeft, BottomRight: TPoint; AMode: TPenMode);
begin
with Image.Canvas do
begin
Pen.Mode := AMode;
case DrawingTool of
dtLine:
begin
Image.Canvas.MoveTo(TopLeft.X, TopLeft.Y);
Image.Canvas.LineTo(BottomRight.X, BottomRight.Y);
end;
dtRectangle:
Image.Canvas.Rectangle(TopLeft.X, TopLeft.Y, BottomRight.X,
BottomRight.Y);
dtEllipse:
Image.Canvas.Ellipse(TopLeft.X, TopLeft.Y, BottomRight.X,
BottomRight.Y);
dtRoundRect:
Image.Canvas.RoundRect(TopLeft.X, TopLeft.Y, BottomRight.X,
BottomRight.Y, (TopLeft.X - BottomRight.X) div 2,
(TopLeft.Y - BottomRight.Y) div 2);
end;
end;
end;
procedure TGLS3dUvForm.Cut1Click(Sender: TObject);
var
ARect: TRect;
begin
Copy1Click(Sender);
with Image.Canvas do
begin
CopyMode := cmWhiteness;
ARect := Rect(0, 0, Image.Width, Image.Height);
CopyRect(ARect, Image.Canvas, ARect);
CopyMode := cmSrcCopy;
end;
end;
procedure TGLS3dUvForm.Copy1Click(Sender: TObject);
begin
Clipboard.Assign(Image.Picture);
end;
procedure TGLS3dUvForm.Paste1Click(Sender: TObject);
var
Bitmap: TBitmap;
begin
if Clipboard.HasFormat(CF_BITMAP) then
begin
Bitmap := TBitmap.Create;
try
Bitmap.Assign(Clipboard);
Image.Canvas.Draw(0, 0, Bitmap);
finally
Bitmap.Free;
end;
end;
end;
(* ******************************************** *)
(* ******************************************** *)
(* ******************************************** *)
(* ******************************************** *)
function TGLS3dUvForm.GetPolygonMode: TPolygonMode;
begin
Result := GLS3dUvForm.GLFreeForm1.Material.PolygonMode;
end;
procedure TGLS3dUvForm.SetPolygonMode(const Value: TPolygonMode);
begin
GLS3dUvForm.GLFreeForm1.Material.PolygonMode := Value;
end;
procedure TGLS3dUvForm.cbPolygonModeChange(Sender: TObject);
begin
PolygonMode := TPolygonMode(cbPolygonMode.Itemindex);
end;
procedure TGLS3dUvForm.SetVertexModifiers;
procedure ScaleVector(var V1, V2: TVector3f);
begin
V1.X := V1.X * V2.X;
V1.Y := V1.Y * V2.Y;
V1.Z := V1.Z * V2.Z;
end;
var
i, j: Integer;
lVector, lScale: TVector3f;
lModifier: TModifierCube;
begin
FModifierList.Clear;
GLScene1.BeginUpdate;
try
with GLFreeForm1.MeshObjects do
begin
for i := 0 to Count - 1 do
for j := 0 to Items[i].Vertices.Count - 1 do
begin
lVector := Items[i].Vertices.Items[j];
lModifier := TModifierCube.Create(nil);
lModifier.FVectorIndex := j;
lModifier.FMeshObjIndex := i;
FModifierList.Add(lModifier);
GLScene1.Objects.AddChild(lModifier);
lScale := GLFreeForm1.Scale.AsAffineVector;
ScaleVector(lVector, lScale);
lModifier.Position.Translate(lVector);
end;
end;
finally
GLScene1.EndUpdate;
end;
end;
procedure TGLS3dUvForm.chbViewPointsClick(Sender: TObject);
var
i: Integer;
begin
GLScene1.BeginUpdate;
try
for i := 0 to FModifierList.Count - 1 do
TModifierCube(FModifierList.Items[i]).Visible := chbViewPoints.Checked;
finally
GLScene1.EndUpdate;
end;
end;
procedure TGLS3dUvForm.ShowModifierStatus(const aObj: TModifierCube);
begin
if aObj = nil then
StatusBar1.Panels[0].Text := ''
else
StatusBar1.Panels[0].Text := Format('Modifier vector index [%d]',
[aObj.FVectorIndex]);
end;
function TGLS3dUvForm.MouseWorldPos(X, Y: Integer): TVector;
var
v: TVector;
begin
Y := GLSceneViewer1.Height - Y;
if Assigned(FSelectedModifier) then
begin
SetVector(v, X, Y, 0);
if FMoveZ then
GLSceneViewer1.Buffer.ScreenVectorIntersectWithPlaneXZ(v,
FSelectedModifier.Position.Y, Result)
else
GLSceneViewer1.Buffer.ScreenVectorIntersectWithPlaneXY(v,
FSelectedModifier.Position.Z, Result);
end
else
SetVector(Result, NullVector);
end;
procedure TGLS3dUvForm.ChangeMeshVector(const aObj: TModifierCube;
const aPos: TVector4f);
var
lVIndex, lMIndex: Integer;
v: TVector3f;
begin
if aObj = nil then
Exit;
lVIndex := aObj.FVectorIndex;
lMIndex := aObj.FMeshObjIndex;
{ Get new vertex position, keep freeform scale in mind and redraw freeform. }
MakeVector(v, aPos.X / CModifierDim, aPos.Y / CModifierDim, aPos.Z / CModifierDim);
GLFreeForm1.MeshObjects.Items[lMIndex].Vertices.TranslateItem(lVIndex, v);
GLFreeForm1.StructureChanged;
end;
procedure TGLS3dUvForm.chbShowAxisClick(Sender: TObject);
begin
dcModifiers.ShowAxes := TCheckBox(Sender).Checked;
end;
procedure TGLS3dUvForm.tbPosChange(Sender: TObject);
begin
GLCamera1.Position.Z := tbPos.Position;
end;
procedure TGLS3dUvForm.GLSceneViewer1BeforeRender(Sender: TObject);
begin
glEnable(GL_NORMALIZE);
end;
procedure TGLS3dUvForm.btnVertexClick(Sender: TObject);
var
i, j: Integer;
lList: TStringList;
lVector: TVector3f;
begin
lList := TStringList.Create;
try
with GLFreeForm1.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
for j := 0 to Items[i].Vertices.Count - 1 do
begin
lVector := Items[i].Vertices.Items[j];
lList.Add(Format('%f %f %f', [lVector.X, lVector.Y, lVector.Z]));
end;
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TGLS3dUvForm.btnNormalsClick(Sender: TObject);
var
i, j: Integer;
lList: TStringList;
lVector: TVector3f;
begin
lList := TStringList.Create;
try
with GLFreeForm1.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
for j := 0 to Items[i].Normals.Count - 1 do
begin
lVector := Items[i].Normals.Items[j];
lList.Add(Format('%f %f %f', [lVector.X, lVector.Y, lVector.Z]));
end;
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TGLS3dUvForm.btnTextcoordsClick(Sender: TObject);
var
i, j: Integer;
lList: TStringList;
lVector: TVector3f;
begin
lList := TStringList.Create;
try
with GLFreeForm1.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
for j := 0 to Items[i].TexCoords.Count - 1 do
begin
lVector := Items[i].TexCoords.Items[j];
lList.Add(Format('%f %f %f', [lVector.X, lVector.Y, lVector.Z]));
end;
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TGLS3dUvForm.btnGroupsClick(Sender: TObject);
var
i: Integer;
lList: TStringList;
begin
lList := TStringList.Create;
try
with GLFreeForm1.MeshObjects do
for i := 0 to Count - 1 do
begin
lList.Add('For mesh object ' + IntToStr(i));
lList.Add(IntToStr(Items[i].TriangleCount));
end;
ShowMeshData(lList);
finally
FreeAndNil(lList);
end;
end;
procedure TGLS3dUvForm.StripAndRecalc;
var
lTrigList, lNormals: TAffineVectorList;
lIndices: TIntegerList;
lObj: TMeshObject;
lStrips: TPersistentObjectList;
lFaceGroup: TFGVertexIndexList;
i: Integer;
begin
// Extract raw triangle data to work with.
lTrigList := GLFreeForm1.MeshObjects.ExtractTriangles;
// Builds a vector-count optimized indices list.
lIndices := BuildVectorCountOptimizedIndices(lTrigList);
// Alter reference/indice pair and removes unused reference values.
RemapAndCleanupReferences(lTrigList, lIndices);
// Calculate normals.
lNormals := BuildNormals(lTrigList, lIndices);
// Strip where posible.
lStrips := StripifyMesh(lIndices, lTrigList.Count, True);
// Clear current mesh object data.
GLFreeForm1.MeshObjects.Clear;
// Setup new mesh object.
lObj := TMeshObject.CreateOwned(GLFreeForm1.MeshObjects);
lObj.Vertices := lTrigList;
lObj.Mode := momFaceGroups;
lObj.Normals := lNormals;
for i := 0 to lStrips.Count - 1 do
begin
lFaceGroup := TFGVertexIndexList.CreateOwned(lObj.FaceGroups);
lFaceGroup.VertexIndices := (lStrips[i] as TIntegerList);
if i > 0 then
lFaceGroup.Mode := fgmmTriangleStrip
else
lFaceGroup.Mode := fgmmTriangles;
lFaceGroup.MaterialName := IntToStr(i and 15);
end;
// Redraw freeform
GLFreeForm1.StructureChanged;
lTrigList.Free;
lNormals.Free;
lIndices.Free;
end;
procedure TGLS3dUvForm.ShowMeshData(const aList: TStringList);
Begin
MeshDataListBox.{ Lines. } Assign(aList);
End;
end.
|
unit EditAlbumController;
interface
uses
Generics.Collections,
Aurelius.Engine.ObjectManager,
MediaFile;
type
TEditAlbumController = class
private
FManager: TObjectManager;
FAlbum: TAlbum;
public
constructor Create;
destructor Destroy; override;
procedure SaveAlbum(Album: TAlbum);
procedure Load(AlbumId: Variant);
property Album: TAlbum read FAlbum;
end;
implementation
uses
DBConnection;
{ TEditAlbumController }
constructor TEditAlbumController.Create;
begin
FAlbum := TAlbum.Create;
FManager := TDBConnection.GetInstance.CreateObjectManager;
end;
destructor TEditAlbumController.Destroy;
begin
if not FManager.IsAttached(FAlbum) then
FAlbum.Free;
FManager.Free;
inherited;
end;
procedure TEditAlbumController.Load(AlbumId: Variant);
begin
if not FManager.IsAttached(FAlbum) then
FAlbum.Free;
FAlbum := FManager.Find<TAlbum>(AlbumId);
end;
procedure TEditAlbumController.SaveAlbum(Album: TAlbum);
begin
if not FManager.IsAttached(Album) then
FManager.SaveOrUpdate(Album);
FManager.Flush;
end;
end.
|
(*ref: https://www.tutorialspoint.com/pascal/pascal_functions.htm*)
(*ref: http://wiki.freepascal.org/Unit *)
unit f1;
interface
function max(num1, num2: integer): integer;
function min(num1, num2: integer): integer;
implementation
function max(num1, num2: integer): integer;
var
(* local variable declaration *)
result: integer;
begin
if (num1 > num2) then
result := num1
else
result := num2;
max := result;
end;
function min(num1, num2: integer): integer;
var
(* local variable declaration *)
result: integer;
begin
if (num1 < num2) then
result := num1
else
result := num2;
min := result;
end;
end.
|
unit ibSHEditorRegistrator;
interface
uses Classes, SysUtils, Contnrs, Dialogs,
SynEdit, SynEditTypes, SynCompletionProposal,
SHDesignIntf, SHOptionsIntf, SHEvents, ibSHDesignIntf, ibSHConsts,
pSHIntf, pSHSynEdit, pSHHighlighter, pSHCompletionProposal,
pSHAutoComplete, pSHParametersHint;
type
TibBTEditorRegistrator = class(TSHComponent, ISHDemon, IibSHEditorRegistrator)
private
FServers: TComponentList;
FKeywordsManagers: TComponentList;
FDefaultObjectNamesManagers: TComponentList;
FEditors: TComponentList;
{Options}
FEditorGeneralOptions: ISHEditorGeneralOptions;
FEditorDisplayOptions: ISHEditorDisplayOptions;
FEditorColorOptions: ISHEditorColorOptions;
FEditorCodeInsightOptions: ISHEditorCodeInsightOptions;
FDatabases: TComponentList;
FObjectNamesManagers: TComponentList;
function ExtractComponent(Carrier: IInterface; var AComponent: TComponent): Boolean;
function GetSubSQLDialect(AServer: IibSHServer): TSQLSubDialect;
procedure CatchDemons;
procedure FreeDemons;
procedure DoApplyEditorOptions(AEditor: TpSHSynEdit);
procedure DoApplyHighlighterOptions(AHighlighter: TpSHHighlighter);
procedure DoApplyCompletionProposalOptions(ACompletionProposal: TpSHCompletionProposal);
procedure DoApplyParametersHintOptions(AParametersHint: TpSHParametersHint);
procedure DoOnOptionsChanged;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
class function GetClassIIDClassFnc: TGUID; override;
function ReceiveEvent(AEvent: TSHEvent): Boolean; override;
function RegisterServer(AServer: IInterface): Integer;
function RegisterDatabase(ADatabase: IInterface): Integer;
{IibSHEditorRegistrator}
procedure AfterChangeServerVersion(Sender: TObject);
procedure RegisterEditor(AEditor: TComponent; AServer, ADatabase: IInterface);
function GetKeywordsManager(AServer: IInterface): IInterface;
function GetObjectNameManager(AServer, ADatabase: IInterface): IInterface;
end;
implementation
uses SynEditHighlighter, ibSHSimpleFieldListRetriever;
procedure Register;
begin
SHRegisterComponents([TibBTEditorRegistrator]);
end;
{ TibBTEditorRegistrator }
constructor TibBTEditorRegistrator.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FServers := TComponentList.Create;
FServers.OwnsObjects := False;
FKeywordsManagers := TComponentList.Create;
FKeywordsManagers.OwnsObjects := True;
FDefaultObjectNamesManagers := TComponentList.Create;
FDefaultObjectNamesManagers.OwnsObjects := True;
FEditors := TComponentList.Create;
FEditors.OwnsObjects := False;
FDatabases := TComponentList.Create;
FDatabases.OwnsObjects := False;
FObjectNamesManagers := TComponentList.Create;
FObjectNamesManagers.OwnsObjects := True;
end;
destructor TibBTEditorRegistrator.Destroy;
begin
FObjectNamesManagers.Free;
FDatabases.Free;
FEditors.Free;
FDefaultObjectNamesManagers.Free;
FKeywordsManagers.Free;
FServers.Free;
inherited;
end;
function TibBTEditorRegistrator.ExtractComponent(Carrier: IInterface;
var AComponent: TComponent): Boolean;
var
ComponentRef: IInterfaceComponentReference;
begin
Result := Assigned(Carrier) and
Supports(Carrier, IInterfaceComponentReference, ComponentRef);
if Result then
AComponent := ComponentRef.GetComponent
else
AComponent := nil;
end;
function TibBTEditorRegistrator.GetSubSQLDialect(AServer: IibSHServer): TSQLSubDialect;
begin
with AServer do
begin
if AnsiSameText(Version, SInterBase4x) then Result := ibdInterBase4 else
if AnsiSameText(Version, SInterBase5x) then Result := ibdInterBase5 else
if AnsiSameText(Version, SInterBase6x) then Result := ibdInterBase6 else
if AnsiSameText(Version, SInterBase65) then Result := ibdInterBase65 else
if AnsiSameText(Version, SInterBase70) then Result := ibdInterBase7 else
if AnsiSameText(Version, SInterBase71) then Result := ibdInterBase7 else
if AnsiSameText(Version, SInterBase75) then Result := ibdInterBase75 else
if AnsiSameText(Version, SFirebird1x) then Result := ibdFirebird1 else
if AnsiSameText(Version, SFirebird15) then Result := ibdFirebird15 else
if AnsiSameText(Version, SFirebird20) then Result := ibdFirebird20 else
if AnsiSameText(Version, SInterBase2007) then Result := ibdInterbase2007 else
if AnsiSameText(Version, SFirebird21) then Result := ibdFirebird21 else
Result := 0;
end;
end;
procedure TibBTEditorRegistrator.CatchDemons;
begin
Supports(Designer.GetDemon(ISHEditorGeneralOptions), ISHEditorGeneralOptions, FEditorGeneralOptions);
Supports(Designer.GetDemon(ISHEditorDisplayOptions), ISHEditorDisplayOptions, FEditorDisplayOptions);
Supports(Designer.GetDemon(ISHEditorColorOptions), ISHEditorColorOptions, FEditorColorOptions);
Supports(Designer.GetDemon(ISHEditorCodeInsightOptions), ISHEditorCodeInsightOptions, FEditorCodeInsightOptions);
end;
procedure TibBTEditorRegistrator.FreeDemons;
begin
if Assigned(FEditorGeneralOptions) then
FEditorGeneralOptions := nil;
if Assigned(FEditorDisplayOptions) then
FEditorDisplayOptions := nil;
if Assigned(FEditorColorOptions) then
FEditorColorOptions := nil;
if Assigned(FEditorCodeInsightOptions) then
FEditorCodeInsightOptions := nil;
end;
procedure TibBTEditorRegistrator.DoApplyEditorOptions(AEditor: TpSHSynEdit);
function CaretTypeConv(AOptionCaret: TSHEditorCaretType): TSynEditCaretType;
begin
case AOptionCaret of
VerticalLine: Result := ctVerticalLine;
HorizontalLine: Result := ctHorizontalLine;
HalfBlock: Result := ctHalfBlock;
Block: Result := ctBlock;
else
Result := ctVerticalLine;
end;
end;
begin
if Assigned(FEditorGeneralOptions) then
begin
if Supports(FEditorCodeInsightOptions,IEditorCodeInsightOptionsExt) then
AEditor.ShowBeginEndRegions:=
(FEditorCodeInsightOptions as IEditorCodeInsightOptionsExt).GetShowBeginEndRegions;
AEditor.HideSelection := FEditorGeneralOptions.HideSelection;
AEditor.InsertCaret := CaretTypeConv(FEditorGeneralOptions.InsertCaret);
AEditor.InsertMode := FEditorGeneralOptions.InsertMode;
AEditor.MaxScrollWidth := FEditorGeneralOptions.MaxLineWidth;
AEditor.MaxUndo := FEditorGeneralOptions.MaxUndo;
case FEditorGeneralOptions.OpenLink of
SingleClick: AEditor.HyperLinkRule := hlrSingleClick;
CtrlClick: AEditor.HyperLinkRule := hlrCtrlClick;
DblClick: AEditor.HyperLinkRule := hlrDblClick;
end;
AEditor.Options := [eoRightMouseMovesCursor];
if FEditorGeneralOptions.Options.AltSetsColumnMode then
AEditor.Options := AEditor.Options + [eoAltSetsColumnMode];
if FEditorGeneralOptions.Options.AutoIndent then
AEditor.Options := AEditor.Options + [eoAutoIndent];
if FEditorGeneralOptions.Options.AutoSizeMaxLeftChar then
AEditor.Options := AEditor.Options + [eoAutoSizeMaxScrollWidth];
if FEditorGeneralOptions.Options.DisableScrollArrows then
AEditor.Options := AEditor.Options + [eoDisableScrollArrows];
if FEditorGeneralOptions.Options.DragDropEditing then
AEditor.Options := AEditor.Options + [eoDragDropEditing];
// if FEditorGeneralOptions.Options.DragDropEditing then
if FEditorGeneralOptions.Options.EnhanceHomeKey then
AEditor.Options := AEditor.Options + [eoEnhanceHomeKey];
if FEditorGeneralOptions.Options.GroupUndo then
AEditor.Options := AEditor.Options + [eoGroupUndo];
if FEditorGeneralOptions.Options.HalfPageScroll then
AEditor.Options := AEditor.Options + [eoHalfPageScroll];
if FEditorGeneralOptions.Options.HideShowScrollbars then
AEditor.Options := AEditor.Options + [eoHideShowScrollbars];
if FEditorGeneralOptions.Options.KeepCaretX then
AEditor.Options := AEditor.Options + [eoKeepCaretX];
if FEditorGeneralOptions.Options.NoCaret then
AEditor.Options := AEditor.Options + [eoNoCaret];
if FEditorGeneralOptions.Options.NoSelection then
AEditor.Options := AEditor.Options + [eoNoSelection];
if FEditorGeneralOptions.Options.ScrollByOneLess then
AEditor.Options := AEditor.Options + [eoScrollByOneLess];
if FEditorGeneralOptions.Options.ScrollHintFollows then
AEditor.Options := AEditor.Options + [eoScrollHintFollows];
if FEditorGeneralOptions.Options.ScrollPastEof then
AEditor.Options := AEditor.Options + [eoScrollPastEof];
if FEditorGeneralOptions.Options.ScrollPastEol then
AEditor.Options := AEditor.Options + [eoScrollPastEol];
if FEditorGeneralOptions.Options.ShowScrollHint then
AEditor.Options := AEditor.Options + [eoShowScrollHint];
//eoShowSpecialChars
if FEditorGeneralOptions.Options.SmartTabDelete then
AEditor.Options := AEditor.Options + [eoSmartTabDelete];
if FEditorGeneralOptions.Options.SmartTabs then
AEditor.Options := AEditor.Options + [eoSmartTabs];
//eoSpecialLineDefaultFg
if FEditorGeneralOptions.Options.TabIndent then
AEditor.Options := AEditor.Options + [eoTabIndent];
if FEditorGeneralOptions.Options.TabsToSpaces then
AEditor.Options := AEditor.Options + [eoTabsToSpaces];
if FEditorGeneralOptions.Options.TrimTrailingSpaces then
AEditor.Options := AEditor.Options + [eoTrimTrailingSpaces];
AEditor.OverwriteCaret := CaretTypeConv(FEditorGeneralOptions.OverwriteCaret);
case FEditorGeneralOptions.ScrollHintFormat of
TopLineOnly: AEditor.ScrollHintFormat := shfTopLineOnly;
TopToBottom: AEditor.ScrollHintFormat := shfTopToBottom;
end;
AEditor.ScrollBars := FEditorGeneralOptions.ScrollBars;
case FEditorGeneralOptions.SelectionMode of
Normal: AEditor.SelectionMode := smNormal;
Line: AEditor.SelectionMode := smLine;
Column: AEditor.SelectionMode := smColumn;
end;
AEditor.TabWidth := FEditorGeneralOptions.TabWidth;
AEditor.WantReturns := FEditorGeneralOptions.WantReturns;
AEditor.WantTabs := FEditorGeneralOptions.WantTabs;
AEditor.WordWrap := FEditorGeneralOptions.WordWrap;
end;
{!!!!!!!!!
// Invisible
OpenedFilesHistory для run-time сохранения
DemoLines для run-time сохранения
}
if Assigned(FEditorDisplayOptions) then
begin
AEditor.Font.Assign(FEditorDisplayOptions.Font);
AEditor.Gutter.AutoSize := FEditorDisplayOptions.Gutter.AutoSize;
AEditor.Gutter.DigitCount := FEditorDisplayOptions.Gutter.DigitCount;
AEditor.Gutter.Font.Assign(FEditorDisplayOptions.Gutter.Font);
AEditor.Gutter.LeadingZeros := FEditorDisplayOptions.Gutter.LeadingZeros;
AEditor.Gutter.LeftOffset := FEditorDisplayOptions.Gutter.LeftOffset;
AEditor.Gutter.RightOffset := FEditorDisplayOptions.Gutter.RightOffset;
AEditor.Gutter.ShowLineNumbers := FEditorDisplayOptions.Gutter.ShowLineNumbers;
AEditor.Gutter.UseFontStyle := FEditorDisplayOptions.Gutter.UseFontStyle;
AEditor.Gutter.Visible := FEditorDisplayOptions.Gutter.Visible;
AEditor.Gutter.Width := FEditorDisplayOptions.Gutter.Width;
AEditor.Gutter.ZeroStart := FEditorDisplayOptions.Gutter.ZeroStart;
if not FEditorDisplayOptions.Margin.RightEdgeVisible then
AEditor.RightEdge := 0
else
AEditor.RightEdge := FEditorDisplayOptions.Margin.RightEdgeWidth;
AEditor.BottomEdgeVisible := FEditorDisplayOptions.Margin.BottomEdgeVisible;
end;
if Assigned(FEditorColorOptions) then
begin
AEditor.Color := FEditorColorOptions.Background;
AEditor.Gutter.Color := FEditorColorOptions.Gutter;
AEditor.RightEdgeColor := FEditorColorOptions.RightEdge;
AEditor.BottomEdgeColor := FEditorColorOptions.BottomEdge;
AEditor.ActiveLineColor := FEditorColorOptions.CurrentLine;
AEditor.ScrollHintColor := FEditorColorOptions.ScrollHint;
AEditor.SelectedColor.Background := FEditorColorOptions.Selected.Background;
AEditor.SelectedColor.Foreground := FEditorColorOptions.Selected.Foreground;
end;
end;
procedure TibBTEditorRegistrator.DoApplyHighlighterOptions(
AHighlighter: TpSHHighlighter);
procedure FontAttrConv(AFontAttr: TSynHighlighterAttributes; AColorAttr: ISHEditorColorAttr);
begin
AFontAttr.Style := AColorAttr.Style;
AFontAttr.Background := AColorAttr.Background;
AFontAttr.Foreground := AColorAttr.Foreground;
end;
begin
if Assigned(FEditorGeneralOptions) then
AHighlighter.Enabled := FEditorGeneralOptions.UseHighlight;
if Assigned(FEditorColorOptions) then
begin
with AHighlighter do
begin
{!!!!!!}
// FEditorColorOptions.
FontAttrConv(CommentAttri, FEditorColorOptions.CommentAttr);
FontAttrConv(CustomStringsAttri, FEditorColorOptions.CustomStringAttr);
FontAttrConv(DataTypeAttri, FEditorColorOptions.DataTypeAttr);
FontAttrConv(IdentifierAttri, FEditorColorOptions.IdentifierAttr);
FontAttrConv(FunctionAttri, FEditorColorOptions.FunctionAttr);
FontAttrConv(TableNameAttri, FEditorColorOptions.LinkAttr);
FontAttrConv(NumberAttri, FEditorColorOptions.NumberAttr);
FontAttrConv(KeyAttri, FEditorColorOptions.SQLKeywordAttr);
FontAttrConv(StringAttri, FEditorColorOptions.StringAttr);
{!!!!!!}
// FontAttrConv(StringDblQuotedAttri, FEditorColorOptions.StringDblQuotedAttr);
FontAttrConv(SymbolAttri, FEditorColorOptions.SymbolAttr);
FontAttrConv(VariableAttri, FEditorColorOptions.VariableAttr);
FontAttrConv(WrongSymbolAttri, FEditorColorOptions.WrongSymbolAttr);
end;
end;
end;
procedure TibBTEditorRegistrator.DoApplyCompletionProposalOptions(
ACompletionProposal: TpSHCompletionProposal);
begin
if Assigned(FEditorCodeInsightOptions) then
begin
ACompletionProposal.TimerInterval := FEditorCodeInsightOptions.Delay;
ACompletionProposal.Form.ClSelect := FEditorColorOptions.Selected.Background;
ACompletionProposal.Form.ClSelectedText := FEditorColorOptions.Selected.Foreground;
end;
{
ISHEditorCodeInsightOptions
CodeParameters для пропозала
}
end;
procedure TibBTEditorRegistrator.DoApplyParametersHintOptions(
AParametersHint: TpSHParametersHint);
begin
if Assigned(FEditorCodeInsightOptions) then
begin
if FEditorCodeInsightOptions.Delay > 0 then
begin
AParametersHint.Options := AParametersHint.Options + [scoUseBuiltInTimer];
AParametersHint.TimerInterval := FEditorCodeInsightOptions.Delay;
end
else
AParametersHint.Options := AParametersHint.Options - [scoUseBuiltInTimer];
end;
end;
function CodeCaseConv(AEditorCaseCode: TSHEditorCaseCode): TpSHCaseCode;
begin
case AEditorCaseCode of
Lower: Result := ccLower;
Upper: Result := ccUpper;
NameCase: Result := ccNameCase;
FirstUpper: Result := ccFirstUpper;
None: Result := ccNone;
Invert: Result := ccInvert;
Toggle: Result := ccToggle;
else
Result := ccUpper;
end;
end;
procedure TibBTEditorRegistrator.DoOnOptionsChanged;
var
I: Integer;
vObjectNamesManager: IpSHObjectNamesManager;
procedure SetOptionsToObjectNameManager(AObjectNamesManager: IpSHObjectNamesManager);
var
vCompletionProposalOptions: IpSHCompletionProposalOptions;
begin
DoApplyHighlighterOptions(TpSHHighlighter(AObjectNamesManager.Highlighter));
DoApplyCompletionProposalOptions(TpSHCompletionProposal(AObjectNamesManager.CompletionProposal));
DoApplyParametersHintOptions(TpSHParametersHint(AObjectNamesManager.ParametersHint));
if Assigned(FEditorCodeInsightOptions) then
begin
AObjectNamesManager.CaseCode := CodeCaseConv(FEditorCodeInsightOptions.CaseCode);
AObjectNamesManager.CaseSQLCode := CodeCaseConv(FEditorCodeInsightOptions.CaseSQLKeywords);
if Supports(AObjectNamesManager, IpSHCompletionProposalOptions, vCompletionProposalOptions) then
begin
vCompletionProposalOptions.Enabled := FEditorCodeInsightOptions.CodeCompletion;
// vCompletionProposalOptions.Extended := FEditorCodeInsightOptions.CodeCompletionExt;
end;
end;
end;
begin
inherited;
CatchDemons;
try
for I := 0 to FEditors.Count - 1 do
DoApplyEditorOptions(TpSHSynEdit(FEditors[I]));
for I := 0 to FObjectNamesManagers.Count - 1 do
if Supports(FObjectNamesManagers[I], IpSHObjectNamesManager, vObjectNamesManager) then
SetOptionsToObjectNameManager(vObjectNamesManager);
for I := 0 to FDefaultObjectNamesManagers.Count - 1 do
if Supports(FDefaultObjectNamesManagers[I], IpSHObjectNamesManager, vObjectNamesManager) then
SetOptionsToObjectNameManager(vObjectNamesManager);
finally
FreeDemons;
end;
end;
procedure TibBTEditorRegistrator.Notification(AComponent: TComponent;
Operation: TOperation);
var
I: Integer;
procedure RemoveEditorLinks;
begin
if AComponent is TpSHSynEdit then
begin
TpSHSynEdit(AComponent).Highlighter := nil;
TpSHSynEdit(AComponent).CompletionProposal := nil;
TpSHSynEdit(AComponent).ParametersHint := nil;
TpSHSynEdit(AComponent).UserInputHistory := nil;
end;
end;
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) then
begin
I := FServers.IndexOf(AComponent);
if I <> -1 then
begin
FServers.Delete(I);
FKeywordsManagers.Delete(I);
FDefaultObjectNamesManagers.Delete(I);
end;
I := FDatabases.IndexOf(AComponent);
if I <> -1 then
begin
FDatabases.Delete(I);
FObjectNamesManagers.Delete(I);
end;
FEditors.Remove(AComponent);
// I := FEditors.IndexOf(AComponent);
// if I <> -1 then
// begin
// RemoveEditorLinks;
// FEditors.Delete(I);
// end;
end;
end;
class function TibBTEditorRegistrator.GetClassIIDClassFnc: TGUID;
begin
Result := IibSHEditorRegistrator;
end;
function TibBTEditorRegistrator.ReceiveEvent(AEvent: TSHEvent): Boolean;
begin
with AEvent do
case Event of
SHE_OPTIONS_CHANGED: DoOnOptionsChanged;
end;
Result := inherited ReceiveEvent(AEvent);
end;
function TibBTEditorRegistrator.RegisterServer(AServer: IInterface): Integer;
var
vComponent: TComponent;
vComponentClass: TSHComponentClass;
vKeywordsManager: IpSHKeywordsManager;
vObjectNamesManager: IpSHObjectNamesManager;
vCompletionProposalOptions: IpSHCompletionProposalOptions;
vBTCLServer: IibSHServer;
begin
// if ExtractComponent(AServer, vComponent) then
// begin
ExtractComponent(AServer, vComponent);
Result := FServers.IndexOf(vComponent);
if Result = -1 then
begin
Result := FServers.Add(vComponent);
if Assigned(vComponent) then
vComponent.FreeNotification(Self);
vComponentClass := Designer.GetComponent(IpSHKeywordsManager);
if Assigned(vComponentClass) then
FKeywordsManagers.Add(vComponentClass.Create(nil))
else
FKeywordsManagers.Add(nil);
vComponentClass := Designer.GetComponent(IpSHObjectNamesManager);
if Assigned(vComponentClass) then
FDefaultObjectNamesManagers.Add(vComponentClass.Create(nil))
else
FDefaultObjectNamesManagers.Add(nil);
if Supports(FDefaultObjectNamesManagers[Result], IpSHObjectNamesManager, vObjectNamesManager) then
begin
CatchDemons;
try
DoApplyHighlighterOptions(TpSHHighlighter(vObjectNamesManager.Highlighter));
DoApplyCompletionProposalOptions(TpSHCompletionProposal(vObjectNamesManager.CompletionProposal));
if Assigned(FEditorCodeInsightOptions) then
begin
vObjectNamesManager.CaseCode := CodeCaseConv(FEditorCodeInsightOptions.CaseCode);
vObjectNamesManager.CaseSQLCode := CodeCaseConv(FEditorCodeInsightOptions.CaseSQLKeywords);
if Supports(FDefaultObjectNamesManagers[Result], IpSHCompletionProposalOptions, vCompletionProposalOptions) then
begin
vCompletionProposalOptions.Enabled := FEditorCodeInsightOptions.CodeCompletion;
// vCompletionProposalOptions.Extended := FEditorCodeInsightOptions.CodeCompletionExt;
end;
end;
finally
FreeDemons;
end;
if Supports(AServer, IibSHServer, vBTCLServer) then
(vObjectNamesManager.Highlighter as TpSHHighlighter).SQLSubDialect := GetSubSQLDialect(vBTCLServer)
else
(vObjectNamesManager.Highlighter as TpSHHighlighter).SQLSubDialect := ibdInterBase5;
if Supports(FKeywordsManagers[Result], IpSHKeywordsManager, vKeywordsManager) then
(vObjectNamesManager.Highlighter as TpSHHighlighter).KeywordsManager := vKeywordsManager;
end;
end;
// end
// else
// Result := -1;
end;
function TibBTEditorRegistrator.RegisterDatabase(ADatabase: IInterface): Integer;
var
vComponent: TComponent;
vComponentClass: TSHComponentClass;
vObjectNamesManager: IpSHObjectNamesManager;
vKeywordsManager: IpSHKeywordsManager;
vCompletionProposalOptions: IpSHCompletionProposalOptions;
vBTCLServer: IibSHServer;
vBTCLDatabase: IibSHDatabase;
begin
// if ExtractComponent(ADatabase, vComponent) then
// begin
ExtractComponent(ADatabase, vComponent);
Result := FDatabases.IndexOf(vComponent);
if Result = -1 then
begin
Result := FDatabases.Add(vComponent);
if Assigned(vComponent) then
vComponent.FreeNotification(Self);
vComponentClass := Designer.GetComponent(IpSHObjectNamesManager);
if Assigned(vComponentClass) then
FObjectNamesManagers.Add(vComponentClass.Create(nil))
else
FObjectNamesManagers.Add(nil);
if Supports(FObjectNamesManagers[Result], IpSHObjectNamesManager, vObjectNamesManager) then
vObjectNamesManager.ObjectNamesRetriever := ADatabase;
// if Supports(vComponent, IibSHDatabase, vBTCLDatabase) and
// Supports(GetKeywordsManager(vBTCLDatabase.BTCLServer),
// IpSHKeywordsManager, vKeywordsManager) and
// Assigned(vObjectNamesManager) then
if Supports(vComponent, IibSHDatabase, vBTCLDatabase) then
Supports(GetKeywordsManager(vBTCLDatabase.BTCLServer), IpSHKeywordsManager, vKeywordsManager)
else
Supports(GetKeywordsManager(nil), IpSHKeywordsManager, vKeywordsManager);
if Assigned(vObjectNamesManager) and Assigned(vKeywordsManager) then
begin
CatchDemons;
try
DoApplyHighlighterOptions(TpSHHighlighter(vObjectNamesManager.Highlighter));
DoApplyCompletionProposalOptions(TpSHCompletionProposal(vObjectNamesManager.CompletionProposal));
if Assigned(FEditorCodeInsightOptions) then
begin
vObjectNamesManager.CaseCode := CodeCaseConv(FEditorCodeInsightOptions.CaseCode);
vObjectNamesManager.CaseSQLCode := CodeCaseConv(FEditorCodeInsightOptions.CaseSQLKeywords);
if Supports(FObjectNamesManagers[Result], IpSHCompletionProposalOptions, vCompletionProposalOptions) then
begin
vCompletionProposalOptions.Enabled := FEditorCodeInsightOptions.CodeCompletion;
// vCompletionProposalOptions.Extended := FEditorCodeInsightOptions.CodeCompletionExt;
end;
end;
finally
FreeDemons;
end;
if Assigned(vBTCLDatabase) and Supports(vBTCLDatabase.BTCLServer, IibSHServer, vBTCLServer) then
(vObjectNamesManager.Highlighter as TpSHHighlighter).SQLSubDialect := GetSubSQLDialect(vBTCLServer)
else
(vObjectNamesManager.Highlighter as TpSHHighlighter).SQLSubDialect := ibdInterBase5;
(vObjectNamesManager.Highlighter as TpSHHighlighter).KeywordsManager := vKeywordsManager;
end;
end;
// end
// else
// Result := -1;
end;
procedure TibBTEditorRegistrator.AfterChangeServerVersion(Sender: TObject);
var
vServer: IibSHServer;
vKeywordsManager: IpSHKeywordsManager;
I: Integer;
begin
//
// В Sender приезжает экземпляр TibSHServer
//
I := FServers.IndexOf(Sender as TComponent);
if (I <> -1) and
Supports(Sender, IibSHServer, vServer) and
Supports(FKeywordsManagers[I], IpSHKeywordsManager, vKeywordsManager) then
vKeywordsManager.ChangeSubSQLDialectTo(GetSubSQLDialect(vServer));
end;
procedure TibBTEditorRegistrator.RegisterEditor(AEditor: TComponent;
AServer, ADatabase: IInterface);
var
vObjectNamesManager: IpSHObjectNamesManager;
vAutoCompleteReplace: IpSHAutoComplete;
I: Integer;
vFieldListRetriever: TibBTSimpleFieldListRetriever;
procedure SetEditorLinks;
var
vUserInputHistory: IpSHUserInputHistory;
vUseHighlight: Boolean;
begin
vUseHighlight := True;
if Supports(Designer.GetDemon(ISHEditorGeneralOptions), ISHEditorGeneralOptions, FEditorGeneralOptions) then
begin
vUseHighlight := FEditorGeneralOptions.UseHighlight;
FreeDemons;
end;
if vUseHighlight then
TpSHSynEdit(AEditor).Highlighter :=
vObjectNamesManager.Highlighter as TpSHHighlighter
else
TpSHSynEdit(AEditor).Highlighter := nil;
TpSHSynEdit(AEditor).CompletionProposal :=
vObjectNamesManager.CompletionProposal as TpSHCompletionProposal;
TpSHSynEdit(AEditor).ParametersHint :=
vObjectNamesManager.ParametersHint as TpSHParametersHint;
if Supports(vObjectNamesManager, IpSHUserInputHistory, vUserInputHistory) then
TpSHSynEdit(AEditor).UserInputHistory := vUserInputHistory;
end;
procedure RemoveEditorLinks;
begin
TpSHSynEdit(AEditor).Highlighter := nil;
TpSHSynEdit(AEditor).CompletionProposal := nil;
TpSHSynEdit(AEditor).ParametersHint := nil;
TpSHSynEdit(AEditor).UserInputHistory := nil;
end;
begin
if Assigned(AEditor) then
begin
if FEditors.IndexOf(AEditor) = -1 then
begin
FEditors.Add(AEditor);
CatchDemons;
try
DoApplyEditorOptions(TpSHSynEdit(AEditor));
finally
FreeDemons;
end;
AEditor.FreeNotification(Self);
end;
if Supports(Designer.GetDemon(IibSHAutoComplete), IpSHAutoComplete, vAutoCompleteReplace) then
begin
vFieldListRetriever := TibBTSimpleFieldListRetriever.Create(nil);
vFieldListRetriever.Database := ADatabase;
TpSHAutoComplete(vAutoCompleteReplace.GetAutoComplete).AddEditor(TpSHSynEdit(AEditor), vFieldListRetriever);
end;
if Supports(Designer.GetDemon(IibSHAutoReplace), IpSHAutoComplete, vAutoCompleteReplace) then
TpSHAutoComplete(vAutoCompleteReplace.GetAutoComplete).AddEditor(TpSHSynEdit(AEditor));
I := RegisterDatabase(ADatabase);
if (I <> -1) and
Supports(FObjectNamesManagers[I], IpSHObjectNamesManager, vObjectNamesManager) then
SetEditorLinks
else
begin
I := RegisterServer(AServer);
if (I <> -1) and
Supports(FDefaultObjectNamesManagers[I], IpSHObjectNamesManager, vObjectNamesManager) then
SetEditorLinks
else
RemoveEditorLinks;
end;
end;
end;
function TibBTEditorRegistrator.GetKeywordsManager(
AServer: IInterface): IInterface;
var
I: Integer;
begin
Result := nil;
I := RegisterServer(AServer);
if I <> -1 then
Supports(FKeywordsManagers[I], IpSHKeywordsManager, Result);
end;
function TibBTEditorRegistrator.GetObjectNameManager(AServer,
ADatabase: IInterface): IInterface;
var
I: Integer;
begin
Result := nil;
I := RegisterDatabase(ADatabase);
if I <> -1 then
Supports(FObjectNamesManagers[I], IpSHObjectNamesManager, Result);
if not Assigned(Result) then
begin
I := RegisterServer(AServer);
if I <> -1 then
Supports(FDefaultObjectNamesManagers[I], IpSHObjectNamesManager, Result);
end;
end;
initialization
Register;
end.
|
unit MudUtil;
interface
uses
Windows, Classes, SysUtils;
type
TQuickList = class(TStringList)
private
GQuickListCriticalSection: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Lock();
procedure UnLock;
function GetIndex(sName: string): Integer;
procedure AddRecord(sCharName: string; dwTickTime: LongWord);
end;
implementation
constructor TQuickList.Create;
begin
inherited Create;
InitializeCriticalSection(GQuickListCriticalSection);
end;
destructor TQuickList.Destroy;
begin
DeleteCriticalSection(GQuickListCriticalSection);
inherited;
end;
procedure TQuickList.Lock; //0x00457EA8
begin
EnterCriticalSection(GQuickListCriticalSection);
end;
procedure TQuickList.UnLock;
begin
LeaveCriticalSection(GQuickListCriticalSection);
end;
{function TQuickList.GetIndex(sName: string): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Self.Count - 1 do begin
if CompareText(sName, Self.Strings[I]) = 0 then begin
Result := I;
end;
end;
end; }
procedure TQuickList.AddRecord(sCharName: string; dwTickTime: LongWord);
begin
AddObject(sCharName, TObject(dwTickTime));
end;
function TQuickList.GetIndex(sName: string): Integer;
var
nIndex: Integer;
begin
Result := -1;
for nIndex := 0 to Self.Count - 1 do begin
if CompareText(sName, Self.Strings[nIndex]) = 0 then begin
Result := nIndex;
end;
end;
end;
{function TQuickList.GetIndex(sName: string): Integer;
var
nLow, nHigh, nMed, nCompareVal: Integer;
begin
Result := -1;
if Self.Count <> 0 then begin
if Self.Sorted then begin
if Self.Count = 1 then begin
if CompareText(sName, Self.Strings[0]) = 0 then Result := 0; // - > 0x0045B71D
end else begin //0x0045B51E
nLow := 0;
nHigh := Self.Count - 1;
nMed := (nHigh - nLow) div 2 + nLow;
while (True) do begin
if (nHigh - nLow) = 1 then begin
if CompareText(sName, Self.Strings[nHigh]) = 0 then Result := nHigh;
if CompareText(sName, Self.Strings[nLow]) = 0 then Result := nLow;
break;
end else begin
nCompareVal := CompareText(sName, Self.Strings[nMed]);
if nCompareVal > 0 then begin
nLow := nMed;
nMed := (nHigh - nLow) div 2 + nLow;
Continue;
end; //0x0045B5DA
if nCompareVal < 0 then begin
nHigh := nMed;
nMed := (nHigh - nLow) div 2 + nLow;
Continue;
end;
Result := nMed;
break;
end; //0x0045B609
end;
end;
end else begin //0x0045B609
if Self.Count = 1 then begin
if CompareText(sName, Self.Strings[0]) = 0 then Result := 0;
end else begin
nLow := 0;
nHigh := Self.Count - 1;
nMed := (nHigh - nLow) div 2 + nLow;
while (True) do begin
if (nHigh - nLow) = 1 then begin
if CompareText(sName, Self.Strings[nHigh]) = 0 then Result := nHigh;
if CompareText(sName, Self.Strings[nLow]) = 0 then Result := nLow;
break;
end else begin //0x0045B6B3
nCompareVal := CompareText(sName, Self.Strings[nMed]);
if nCompareVal > 0 then begin
nLow := nMed;
nMed := (nHigh - nLow) div 2 + nLow;
Continue;
end;
if nCompareVal < 0 then begin
nHigh := nMed;
nMed := (nHigh - nLow) div 2 + nLow;
Continue;
end;
Result := nMed;
break;
end;
end;
end;
end;
end;
end; }
{procedure TQuickList.AddRecord(sCharName: string; dwTickTime: LongWord);
var
ChrList: TList;
nLow, nHigh, nMed, n1C, n20: Integer;
begin
if Count = 0 then begin
ChrList := TList.Create;
ChrList.Add(TObject(dwTickTime));
AddObject(sCharName, ChrList);
end else begin //0x0045B839
if Count = 1 then begin
nMed := CompareText(sCharName, Self.Strings[0]);
if nMed > 0 then begin
ChrList := TList.Create;
ChrList.Add(TObject(dwTickTime));
AddObject(sCharName, ChrList);
end else begin //0x0045B89C
if nMed < 0 then begin
ChrList := TList.Create;
ChrList.Add(TObject(dwTickTime));
InsertObject(0, sCharName, ChrList);
end else begin
ChrList := TList(Self.Objects[0]);
ChrList.Add(TObject(dwTickTime));
end;
end;
end else begin //0x0045B8EF
nLow := 0;
nHigh := Self.Count - 1;
nMed := (nHigh - nLow) div 2 + nLow;
while (True) do begin
if (nHigh - nLow) = 1 then begin
n20 := CompareText(sCharName, Self.Strings[nHigh]);
if n20 > 0 then begin
ChrList := TList.Create;
ChrList.Add(TObject(dwTickTime));
InsertObject(nHigh + 1, sCharName, ChrList);
break;
end else begin
if CompareText(sCharName, Self.Strings[nHigh]) = 0 then begin
ChrList := TList(Self.Objects[nHigh]);
ChrList.Add(TObject(dwTickTime));
break;
end else begin //0x0045B9BB
n20 := CompareText(sCharName, Self.Strings[nLow]);
if n20 > 0 then begin
ChrList := TList.Create;
ChrList.Add(TObject(dwTickTime));
InsertObject(nLow + 1, sCharName, ChrList);
break;
end else begin
if n20 < 0 then begin
ChrList := TList.Create;
ChrList.Add(TObject(dwTickTime));
InsertObject(nLow, sCharName, ChrList);
break;
end else begin
ChrList := TList(Self.Objects[n20]);
ChrList.Add(TObject(dwTickTime));
break;
end;
end;
end;
end;
end else begin //0x0045BA6A
n1C := CompareText(sCharName, Self.Strings[nMed]);
if n1C > 0 then begin
nLow := nMed;
nMed := (nHigh - nLow) div 2 + nLow;
Continue;
end;
if n1C < 0 then begin
nHigh := nMed;
nMed := (nHigh - nLow) div 2 + nLow;
Continue;
end;
ChrList := TList(Self.Objects[nMed]);
ChrList.Add(TObject(dwTickTime));
break;
end;
end;
end;
end;
end; }
initialization
finalization
end.
|
unit DW.UniversalLinks;
interface
type
TOpenApplicationContext = class(TObject)
private
FURL: string;
public
constructor Create(const AURL: string);
property URL: string read FURL;
end;
implementation
{$IF Defined(IOS)}
uses
DW.UniversalLinks.iOS;
{$ENDIF}
{ TOpenApplicationContext }
constructor TOpenApplicationContext.Create(const AURL: string);
begin
inherited Create;
FURL := AURL;
end;
end.
|
unit SnakeData;
interface
uses lvl2DData;
type
SnakeLvl=class;
Position = record
public X,Y: integer;
public constructor(X,Y: integer);
begin
self.X := X;
self.Y := Y;
end;
public static function operator=(p1,p2:Position): boolean :=
(p1.X=p2.X) and (p1.Y=p2.Y);
public static function operator<>(p1,p2:Position): boolean :=
not (p1=p2);
end;
Snake=class
public lvl: SnakeLvl;
public drct: byte;
private last_drct: byte;
public growing := false;
public tail: LinkedList<Position>;
public Color := System.ConsoleColor.Red;
private procedure Init(lvl: SnakeLvl; drct: byte; tail: sequence of Position);
public constructor(lvl: SnakeLvl);
public constructor(lvl: SnakeLvl; drct: byte; tail: sequence of Position) :=
Init(lvl, drct, tail);
public procedure Move;
public procedure ChangeDrct(ndrct: byte);
end;
SnakeLvl=class(lvl2D)
public snakes := new List<Snake>;
public food := new List<Position>;
public constructor(fname: string; fc: integer);
public procedure RestoreFood;
end;
implementation
procedure Snake.Init(lvl: SnakeLvl; drct: byte; tail: sequence of Position);
begin
self.lvl := lvl;
lvl.snakes += self;
self.drct := drct;
self.last_drct := drct;
self.tail := new LinkedList<Position>(tail);
end;
constructor Snake.Create(lvl: SnakeLvl);
begin
var p := new Position((lvl.tls.GetLength(0)-1) div 2, Max(4, (lvl.tls.GetLength(1)-1) div 3));
var tail :=
p.Y.Downto(p.Y-4)
.Select(y->new Position(p.X, y));
Init(lvl, 0, tail);
end;
procedure Snake.Move;
begin
last_drct := drct;
var nh := tail.First.Value;
case drct and $3 of
0: nh.Y += 1;
1: nh.X -= 1;
2: nh.Y -= 1;
3: nh.X += 1;
end;
var w := lvl.tls.GetLength(0);
var h := lvl.tls.GetLength(1);
nh.X := (nh.X + w) mod w;
nh.Y := (nh.Y + h) mod h;
tail.AddFirst(nh);
if growing then
growing := false else
tail.RemoveLast;
end;
procedure Snake.ChangeDrct(ndrct: byte) :=
if (4+last_drct-ndrct) and $3 <> 2 then
drct := ndrct;
constructor SnakeLvl.Create(fname: string; fc: integer);
begin
inherited Create(fname);
food.Capacity := fc;
end;
procedure SnakeLvl.RestoreFood :=
if food.Count<>food.Capacity then
begin
var nf := new Position(Random(tls.GetLength(0)),Random(tls.GetLength(1)));
if tls[nf.X, nf.Y] <> TileT.EmptyTile then exit;
if food.Contains(nf) then exit;
if snakes.SelectMany(snk->snk.tail).Any(t->t=nf) then exit;
food.Add(nf);
end;
end. |
unit htJavaScript;
interface
uses
SysUtils, Classes,
LrDynamicProperties;
type
ThtJavaScriptEventRegistry = class(TStringList)
constructor Create;
end;
//
ThtJavaScriptEvents = class(TLrDynamicProperties)
protected
procedure CreateDefaultEvents;
public
constructor Create(AOwner: TComponent); reintroduce;
function AddEvent: TLrDynamicPropertyItem;
end;
//
{
ThtJavaScriptEventItem = class(TCollectionItem)
private
FEventName: string;
FCode: TStringList;
FFunctionName: string;
protected
function GetTrimmedName: string;
procedure SetCode(const Value: TStringList);
procedure SetEventName(const Value: string);
procedure SetFunctionName(const Value: string);
protected
function GetDisplayName: string; override;
public
constructor Create(inCollection: TCollection); override;
destructor Destroy; override;
published
property FunctionName: string read FFunctionName write SetFunctionName;
property EventName: string read FEventName write SetEventName;
property Code: TStringList read FCode write SetCode;
property TrimmedName: string read GetTrimmedName;
end;
}
//
{
ThtJavaScriptEvents = class(TCollection)
private
FOwner: TComponent;
protected
function GetEvent(inIndex: Integer): ThtJavaScriptEventItem;
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TComponent);
procedure CreateDefaultEvents;
function AddEvent: ThtJavaScriptEventItem;
function FindEvent(inName: string): ThtJavaScriptEventItem;
procedure GenerateFuncs(const inJavaName: string);
//procedure ListAttributes(const inJavaName: string;
// inList: ThtAttributeList; inIndex: Integer = 0);
public
property Event[inIndex: Integer]: ThtJavaScriptEventItem read GetEvent;
default;
end;
}
var
ThJavaScriptEventRegistry: ThtJavaScriptEventRegistry;
implementation
const
cThJsNumEventNames = 22;
cThJsEventNames: array[0..Pred(cThJsNumEventNames)] of string =
(
'onKeyDown', 'onKeyPress', 'onKeyUp',
'onMouseDown', 'onMouseUp', 'onMouseMove', 'onMouseOver', 'onMouseOut',
'onClick', 'onDblClick',
'onLoad', 'onAbort', 'onError',
'onMove','onResize', 'onScroll',
'onReset', 'onSubmit', 'onBlur', 'onChange', 'onFocus',
'onSelect'
);
{ ThtJavaScriptEventRegistry }
constructor ThtJavaScriptEventRegistry.Create;
var
i: Integer;
begin
for i := 0 to Pred(cThJsNumEventNames) do
Add(cThJsEventNames[i]);
end;
{ ThtJavaScriptEvents }
constructor ThtJavaScriptEvents.Create(AOwner: TComponent);
begin
inherited Create(AOwner, true);
CreateDefaultEvents;
end;
procedure ThtJavaScriptEvents.CreateDefaultEvents;
var
i: Integer;
begin
for i := 0 to Pred(ThJavaScriptEventRegistry.Count) do
AddEvent.Name := ThJavaScriptEventRegistry[i];
end;
function ThtJavaScriptEvents.AddEvent: TLrDynamicPropertyItem;
begin
Result := AddProperty(ptEvent);
end;
{ ThtJavaScriptEventItem }
{
constructor ThtJavaScriptEventItem.Create(inCollection: TCollection);
begin
inherited;
FCode := TStringList.Create;
end;
destructor ThtJavaScriptEventItem.Destroy;
begin
FCode.Free;
inherited;
end;
function ThtJavaScriptEventItem.GetDisplayName: string;
begin
Result := EventName;
end;
procedure ThtJavaScriptEventItem.SetEventName(const Value: string);
begin
FEventName := Value;
end;
procedure ThtJavaScriptEventItem.SetCode(const Value: TStringList);
begin
FCode.Assign(Value);
end;
procedure ThtJavaScriptEventItem.SetFunctionName(const Value: string);
begin
FFunctionName := Value;
end;
function ThtJavaScriptEventItem.GetTrimmedName: string;
begin
Result := Copy(EventName, 3, MAXINT);
end;
}
{ ThtJavaScriptEvents }
{
constructor ThtJavaScriptEvents.Create(AOwner: TComponent);
begin
inherited Create(ThtJavaScriptEventItem);
FOwner := AOwner;
CreateDefaultEvents;
end;
function ThtJavaScriptEvents.AddEvent: ThtJavaScriptEventItem;
begin
Result := ThtJavaScriptEventItem(Add);
end;
function ThtJavaScriptEvents.FindEvent(inName: string): ThtJavaScriptEventItem;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
if Event[i].EventName = inName then
begin
Result := Event[i];
exit;
end;
Result := nil;
end;
procedure ThtJavaScriptEvents.CreateDefaultEvents;
var
i: Integer;
begin
for i := 0 to Pred(ThJavaScriptEventRegistry.Count) do
AddEvent.EventName := ThJavaScriptEventRegistry[i];
end;
function ThtJavaScriptEvents.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function ThtJavaScriptEvents.GetEvent(
inIndex: Integer): ThtJavaScriptEventItem;
begin
Result := ThtJavaScriptEventItem(Items[inIndex]);
end;
procedure ThtJavaScriptEvents.GenerateFuncs(const inJavaName: string);
var
i: Integer;
c: string;
begin
for i := 0 to Pred(Count) do
with Event[i] do
if Code.Count > 0 then
begin
if FunctionName <> '' then
c := Format('function %s(inSender, inIndex) {'#10,
[ FunctionName ])
else
c := Format('function %s%s(inSender, inIndex) {'#10,
[ inJavaName, TrimmedName ]);
}
// c := c + Code.Text + '}'#10;
{
end;
end;
}
{
procedure ThtJavaScriptEvents.ListAttributes(const inJavaName: string;
inList: ThtAttributeList; inIndex: Integer = 0);
var
i: Integer;
n: string;
begin
for i := 0 to Count - 1 do
with Event[i] do
if (Code.Text <> '') or (FunctionName <> '') then
begin
if FunctionName <> '' then
n := Format('return %s(this, %d);', [ FunctionName, inIndex ])
else
n := Format('return %s%s(this, %d);',
[ inJavaName, TrimmedName, inIndex ]);
inList.Add(EventName, n);
end;
end;
}
initialization
ThJavaScriptEventRegistry := ThtJavaScriptEventRegistry.Create;
finalization
ThJavaScriptEventRegistry.Free;
end.
|
unit InflatablesList_HTML_Tokenizer;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
AuxTypes,
CountedDynArrayUnicodeChar, CountedDynArrayUnicodeString,
InflatablesList_HTML_UnicodeTagAttributeArray;
type
TILHTMLTokenizerState = (
iltsData,iltsRCDATA,iltsRAWTEXT,iltsScriptData,iltsPLAINTEXT,iltsTagOpen,
iltsEndTagOpen,iltsTagName,iltsRCDATALessThanSign,iltsRCDATAEndTagOpen,
iltsRCDATAEndTagName,iltsRAWTEXTLessThanSign,iltsRAWTEXTEndTagOpen,
iltsRAWTEXTEndTagName,iltsScriptDataLessThanSign,iltsScriptDataEndTagOpen,
iltsScriptDataEndTagName,iltsScriptDataEscapeStart,iltsScriptDataEscapeStartDash,
iltsScriptDataEscaped,iltsScriptDataEscapedDash,iltsScriptDataEscapedDashDash,
iltsScriptDataEscapedLessThanSign,iltsScriptDataEscapedEndTagOpen,
iltsScriptDataEscapedEndTagName,iltsScriptDataDoubleEscapeStart,
iltsScriptDataDoubleEscaped,iltsScriptDataDoubleEscapedDash,
iltsScriptDataDoubleEscapedDashDash,iltsScriptDataDoubleEscapedLessThanSign,
iltsScriptDataDoubleEscapeEnd,iltsBeforeAttributeName,iltsAttributeName,
iltsAfterAttributeName,iltsBeforeAttributeValue,iltsAttributeValue_DoubleQuoted,
iltsAttributeValue_SingleQuoted,iltsAttributeValue_Unquoted,
iltsAfterAttributeValue_Quoted,iltsSelfClosingStartTag,iltsBogusComment,
iltsMarkupDeclarationOpen,iltsCommentStart,iltsCommentStartDash,iltsComment,
iltsCommentLessThanSign,iltsCommentLessThanSignBang,iltsCommentLessThanSignBangDash,
iltsCommentLessThanSignBangDashDash,iltsCommentEndDash,iltsCommentEnd,
iltsCommentEndBang,iltsDOCTYPE,iltsBeforeDOCTYPEName,iltsDOCTYPEName,
iltsAfterDOCTYPEName,iltsAfterDOCTYPEPublicKeyword,iltsBeforeDOCTYPEPublicIdentifier,
iltsDOCTYPEPublicIdentifier_DoubleQuoted,iltsDOCTYPEPublicIdentifier_SingleQuoted,
iltsAfterDOCTYPEPublicIdentifier,iltsBetweenDOCTYPEPublicAndSystemIdentifiers,
iltsAfterDOCTYPESystemKeyword,iltsBeforeDOCTYPESystemIdentifier,
iltsDOCTYPESystemIdentifier_DoubleQuoted,iltsDOCTYPESystemIdentifier_SingleQuoted,
iltsAfterDOCTYPESystemIdentifier,iltsBogusDOCTYPE,iltsCDATASection,
iltsCDATASectionBracket,iltsCDATASectionEnd,iltsCharacterReference,
iltsNumericCharacterReference,iltsHexadecimalCharacterReferenceStart,
iltsDecimalCharacterReferenceStart,iltsHexadecimalCharacterReference,
iltsDecimalCharacterReference,iltsNumericCharacterReferenceEnd,
iltsCharacterReferenceEnd);
TILHTMLTokenType = (ilttDOCTYPE,ilttStartTag,ilttEndTag,ilttComment,
ilttCharacter,ilttEndOfFile);
TILHTMLTokenField = (iltfName,iltfPublicIdent,iltfSystemIdent,iltfTagName,iltfData);
TILHTMLTokenFields = set of TILHTMLTokenField;
TILHTMLToken = record
TokenType: TILHTMLTokenType;
// DOCTYPE fields
PresentFields: TILHTMLTokenFields; // presence of Name, PublicIdentifier and SystemIdentifier
Name: UnicodeString;
PublicIdentifier: UnicodeString;
SystemIdentifier: UnicodeString;
ForceQuirks: Boolean;
// tag fields
TagName: UnicodeString;
SelfClosing: Boolean;
Attributes: TUnicodeTagAttributeCountedDynArray;
// comment and char fields
Data: UnicodeString;
// other info
AppropriateEndTag: Boolean;
end;
procedure IL_UniqueHTMLToken(var Value: TILHTMLToken);
Function IL_ThreadSafeCopy(Value: TILHTMLToken): TILHTMLToken; overload;
type
TILHTMLTokenEvent = procedure(Sender: TObject; Token: TILHTMLToken; var Ack: Boolean) of object;
TILHTMLTokenizer = class(TObject)
private
fData: UnicodeString;
fPosition: Integer;
// state machine
fParserPause: Boolean;
fState: TILHTMLTokenizerState;
fReturnState: TILHTMLTokenizerState;
fTemporaryBuffer: TUnicodeCharCountedDynArray;
fCharRefCode: UInt32;
// helpers
fCurrentToken: TILHTMLToken;
fLastStartTag: TUnicodeStringCountedDynArray;
// others
fRaiseParseErrs: Boolean;
fOnTokenEmit: TILHTMLTokenEvent;
Function GetProgress: Double;
protected
// parsing errors
Function ParseError(const Msg: String): Boolean; overload; virtual;
Function ParseError(const Msg: String; Args: array of const): Boolean; overload; virtual;
Function ParseErrorInvalidChar(Char: UnicodeChar): Boolean; virtual;
// helpers
procedure CreateNewToken(out Token: TILHTMLToken; TokenType: TILHTMLTokenType); overload; virtual;
procedure CreateNewToken(TokenType: TILHTMLTokenType); overload; virtual;
Function IsAppropriateEndTagToken(Token: TILHTMLToken): Boolean; virtual;
Function TemporaryBufferAsStr: UnicodeString; virtual;
Function TemporaryBufferEquals(const Str: UnicodeString; CaseSensitive: Boolean): Boolean; virtual;
Function IsCurrentInputString(const Str: UnicodeString; CaseSensitive: Boolean): Boolean; virtual;
procedure AppendToCurrentToken(TokenField: TILHTMLTokenField; Char: UnicodeChar); virtual;
procedure CreateNewAttribute(const Name,Value: UnicodeString); virtual;
procedure AppendCurrentAttributeName(Char: UnicodeChar); virtual;
procedure AppendCurrentAttributeValue(Char: UnicodeChar); virtual;
// tokens emitting
procedure EmitToken(Token: TILHTMLToken); virtual;
procedure EmitCurrentToken; virtual;
procedure EmitCurrentDOCTYPEToken; virtual;
procedure EmitCurrentTagToken; virtual;
procedure EmitCurrentCommentToken; virtual;
procedure EmitCharToken(Char: UnicodeChar); virtual;
procedure EmitEndOfFileToken; virtual;
// state methods
procedure State_Data; virtual;
procedure State_RCDATA; virtual;
procedure State_RAWTEXT; virtual;
procedure State_ScriptData; virtual;
procedure State_PLAINTEXT; virtual;
procedure State_TagOpen; virtual;
procedure State_EndTagOpen; virtual;
procedure State_TagName; virtual;
procedure State_RCDATALessThanSign; virtual;
procedure State_RCDATAEndTagOpen; virtual;
procedure State_RCDATAEndTagName; virtual;
procedure State_RAWTEXTLessThanSign; virtual;
procedure State_RAWTEXTEndTagOpen; virtual;
procedure State_RAWTEXTEndTagName; virtual;
procedure State_ScriptDataLessThanSign; virtual;
procedure State_ScriptDataEndTagOpen; virtual;
procedure State_ScriptDataEndTagName; virtual;
procedure State_ScriptDataEscapeStart; virtual;
procedure State_ScriptDataEscapeStartDash; virtual;
procedure State_ScriptDataEscaped; virtual;
procedure State_ScriptDataEscapedDash; virtual;
procedure State_ScriptDataEscapedDashDash; virtual;
procedure State_ScriptDataEscapedLessThanSign; virtual;
procedure State_ScriptDataEscapedEndTagOpen; virtual;
procedure State_ScriptDataEscapedEndTagName; virtual;
procedure State_ScriptDataDoubleEscapeStart; virtual;
procedure State_ScriptDataDoubleEscaped; virtual;
procedure State_ScriptDataDoubleEscapedDash; virtual;
procedure State_ScriptDataDoubleEscapedDashDash; virtual;
procedure State_ScriptDataDoubleEscapedLessThanSign; virtual;
procedure State_ScriptDataDoubleEscapeEnd; virtual;
procedure State_BeforeAttributeName; virtual;
procedure State_AttributeName; virtual;
procedure State_AfterAttributeName; virtual;
procedure State_BeforeAttributeValue; virtual;
procedure State_AttributeValue_DoubleQuoted; virtual;
procedure State_AttributeValue_SingleQuoted; virtual;
procedure State_AttributeValue_Unquoted; virtual;
procedure State_AfterAttributeValue_Quoted; virtual;
procedure State_SelfClosingStartTag; virtual;
procedure State_BogusComment; virtual;
procedure State_MarkupDeclarationOpen; virtual;
procedure State_CommentStart; virtual;
procedure State_CommentStartDash; virtual;
procedure State_Comment; virtual;
procedure State_CommentLessThanSign; virtual;
procedure State_CommentLessThanSignBang; virtual;
procedure State_CommentLessThanSignBangDash; virtual;
procedure State_CommentLessThanSignBangDashDash; virtual;
procedure State_CommentEndDash; virtual;
procedure State_CommentEnd; virtual;
procedure State_CommentEndBang; virtual;
procedure State_DOCTYPE; virtual;
procedure State_BeforeDOCTYPEName; virtual;
procedure State_DOCTYPEName; virtual;
procedure State_AfterDOCTYPEName; virtual;
procedure State_AfterDOCTYPEPublicKeyword; virtual;
procedure State_BeforeDOCTYPEPublicIdentifier; virtual;
procedure State_DOCTYPEPublicIdentifier_DoubleQuoted; virtual;
procedure State_DOCTYPEPublicIdentifier_SingleQuoted; virtual;
procedure State_AfterDOCTYPEPublicIdentifier; virtual;
procedure State_BetweenDOCTYPEPublicAndSystemIdentifiers; virtual;
procedure State_AfterDOCTYPESystemKeyword; virtual;
procedure State_BeforeDOCTYPESystemIdentifier; virtual;
procedure State_DOCTYPESystemIdentifier_DoubleQuoted; virtual;
procedure State_DOCTYPESystemIdentifier_SingleQuoted; virtual;
procedure State_AfterDOCTYPESystemIdentifier; virtual;
procedure State_BogusDOCTYPE; virtual;
procedure State_CDATASection; virtual;
procedure State_CDATASectionBracket; virtual;
procedure State_CDATASectionEnd; virtual;
procedure State_CharacterReference_ResolveNamedReference; virtual;
procedure State_CharacterReference; virtual;
procedure State_NumericCharacterReference; virtual;
procedure State_HexadecimalCharacterReferenceStart; virtual;
procedure State_DecimalCharacterReferenceStart; virtual;
procedure State_HexadecimalCharacterReference; virtual;
procedure State_DecimalCharacterReference; virtual;
procedure State_NumericCharacterReferenceEnd; virtual;
procedure State_CharacterReferenceEnd; virtual;
procedure State_Select; virtual;
Function NextInputChar: UnicodeChar; virtual;
Function CurrentInputChar: UnicodeChar; virtual;
Function ConsumeNextInputChar: UnicodeChar; virtual;
procedure ReconsumeInputChar; virtual;
Function EndOfFile: Boolean; virtual;
public
constructor Create;
destructor Destroy; override;
procedure Initialize(const Data: UnicodeString);
Function Run: Boolean; virtual;
property Data: UnicodeString read fData;
property ParserPause: Boolean read fParserPause write fParserPause;
property State: TILHTMLTokenizerState read fState write fState;
property RaiseParseErrors: Boolean read fRaiseParseErrs write fRaiseParseErrs;
property Progress: Double read GetProgress;
property OnTokenEmit: TILHTMLTokenEvent read fOnTokenEmit write fOnTokenEmit;
end;
implementation
uses
SysUtils,
StrRect,
InflatablesList_Utils,
InflatablesList_HTML_Utils,
InflatablesList_HTML_NamedCharRefs;
type
TILCharReplaceEntry = record
OldChar: UnicodeChar;
Replacement: UnicodeChar;
end;
const
IL_TOKENIZER_CHAR_REPLACE: array[0..27] of TILCharReplaceEntry = (
(OldChar: #$0000; Replacement: #$FFFD),(OldChar: #$0080; Replacement: #$20AC),
(OldChar: #$0082; Replacement: #$201A),(OldChar: #$0083; Replacement: #$0192),
(OldChar: #$0084; Replacement: #$201E),(OldChar: #$0085; Replacement: #$2026),
(OldChar: #$0086; Replacement: #$2020),(OldChar: #$0087; Replacement: #$2021),
(OldChar: #$0088; Replacement: #$02C6),(OldChar: #$0089; Replacement: #$3030),
(OldChar: #$008A; Replacement: #$0160),(OldChar: #$008B; Replacement: #$2039),
(OldChar: #$008C; Replacement: #$0152),(OldChar: #$008E; Replacement: #$017D),
(OldChar: #$0091; Replacement: #$2018),(OldChar: #$0092; Replacement: #$2019),
(OldChar: #$0093; Replacement: #$201C),(OldChar: #$0094; Replacement: #$201D),
(OldChar: #$0095; Replacement: #$2022),(OldChar: #$0096; Replacement: #$2013),
(OldChar: #$0097; Replacement: #$2014),(OldChar: #$0098; Replacement: #$02DC),
(OldChar: #$0099; Replacement: #$2122),(OldChar: #$009A; Replacement: #$0161),
(OldChar: #$009B; Replacement: #$203A),(OldChar: #$009C; Replacement: #$0153),
(OldChar: #$009E; Replacement: #$017E),(OldChar: #$009F; Replacement: #$0178));
IL_TOKENIZER_CHAR_FORBIDDEN: array[0..34] of UInt32 = (
$000B, $FFFE, $FFFF, $1FFFE, $1FFFF, $2FFFE, $2FFFF, $3FFFE,
$3FFFF, $4FFFE, $4FFFF, $5FFFE, $5FFFF, $6FFFE, $6FFFF, $7FFFE,
$7FFFF, $8FFFE, $8FFFF, $9FFFE, $9FFFF, $AFFFE, $AFFFF, $BFFFE,
$BFFFF, $CFFFE, $CFFFF, $DFFFE, $DFFFF, $EFFFE, $EFFFF, $FFFFE,
$FFFFF,$10FFFE,$10FFFF);
//==============================================================================
procedure IL_UniqueHTMLToken(var Value: TILHTMLToken);
begin
UniqueString(Value.Name);
UniqueString(Value.PublicIdentifier);
UniqueString(Value.SystemIdentifier);
UniqueString(Value.TagName);
CDA_UniqueArray(Value.Attributes);
UniqueString(Value.Data);
end;
//------------------------------------------------------------------------------
Function IL_ThreadSafeCopy(Value: TILHTMLToken): TILHTMLToken;
begin
Result := Value;
IL_UniqueHTMLToken(Result);
end;
//==============================================================================
Function TILHTMLTokenizer.GetProgress: Double;
begin
If Length(fData) > 0 then
begin
If fPosition <= 1 then
Result := 0.0
else If fPosition >= Length(fData) then
Result := 1.0
else
Result := fPosition / Length(fData);
end
else Result := 0.0;
end;
//==============================================================================
Function TILHTMLTokenizer.ParseError(const Msg: String): Boolean;
begin
Result := fRaiseParseErrs;
If fRaiseParseErrs then
raise EILHTMLParseError.Create(Msg);
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.ParseError(const Msg: String; Args: array of const): Boolean;
begin
Result := ParseError(IL_Format(Msg,Args));
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.ParseErrorInvalidChar(Char: UnicodeChar): Boolean;
begin
Result := ParseError('Invalid character (#0x%.4x) for this state (%d @ %d).',[Ord(Char),Ord(fState),Pred(fPosition)]);
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.CreateNewToken(out Token: TILHTMLToken; TokenType: TILHTMLTokenType);
begin
Token.TokenType := TokenType;
// doctype
Token.PresentFields := [];
Token.Name := '';
Token.PublicIdentifier := '';
Token.SystemIdentifier := '';
Token.ForceQuirks := False;
// tags
Token.TagName := '';
Token.SelfClosing := False;
CDA_Clear(Token.Attributes);
// comment, char
Token.Data := '';
// others
Token.AppropriateEndTag := False;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.CreateNewToken(TokenType: TILHTMLTokenType);
begin
CreateNewToken(fCurrentToken,TokenType);
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.IsAppropriateEndTagToken(Token: TILHTMLToken): Boolean;
begin
If (Token.TokenType = ilttEndTag) and (CDA_Count(fLastStartTag) > 0) then
Result := IL_UnicodeSameString(CDA_Last(fLastStartTag),Token.TagName,False)
else
Result := False;
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.TemporaryBufferAsStr: UnicodeString;
var
i: Integer;
begin
SetLength(Result,CDA_Count(fTemporaryBuffer));
For i := CDA_Low(fTemporaryBuffer) to CDA_High(fTemporaryBuffer) do
Result[i + 1] := CDA_GetItem(fTemporaryBuffer,i);
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.TemporaryBufferEquals(const Str: UnicodeString; CaseSensitive: Boolean): Boolean;
begin
Result := IL_UnicodeSameString(TemporaryBufferAsStr,Str,CaseSensitive)
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.IsCurrentInputString(const Str: UnicodeString; CaseSensitive: Boolean): Boolean;
var
TempStr: String;
begin
TempStr := Copy(fData,fPosition - 1,Length(Str));
Result := IL_UnicodeSameString(TempStr,Str,CaseSensitive);
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.AppendToCurrentToken(TokenField: TILHTMLTokenField; Char: UnicodeChar);
begin
case TokenField of
iltfName: fCurrentToken.Name := fCurrentToken.Name + Char;
iltfPublicIdent: fCurrentToken.PublicIdentifier := fCurrentToken.PublicIdentifier + Char;
iltfSystemIdent: fCurrentToken.SystemIdentifier := fCurrentToken.SystemIdentifier + Char;
iltfTagName: fCurrentToken.TagName := fCurrentToken.TagName + Char;
iltfData: fCurrentToken.Data := fCurrentToken.Data + Char;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.CreateNewAttribute(const Name,Value: UnicodeString);
var
NewItem: TILHTMLUnicodeTagAttribute;
begin
NewItem.Name := Name;
NewItem.Value := Value;
CDA_Add(fCurrentToken.Attributes,NewItem);
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.AppendCurrentAttributeName(Char: UnicodeChar);
begin
If CDA_Count(fCurrentToken.Attributes) > 0 then
CDA_GetItemPtr(fCurrentToken.Attributes,CDA_High(fCurrentToken.Attributes))^.Name :=
CDA_GetItemPtr(fCurrentToken.Attributes,CDA_High(fCurrentToken.Attributes))^.Name + Char
else
ParseError('Cannot append to attribute name, no attribute exists.');
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.AppendCurrentAttributeValue(Char: UnicodeChar);
begin
If CDA_Count(fCurrentToken.Attributes) > 0 then
CDA_GetItemPtr(fCurrentToken.Attributes,CDA_High(fCurrentToken.Attributes))^.Value :=
CDA_GetItemPtr(fCurrentToken.Attributes,CDA_High(fCurrentToken.Attributes))^.Value + Char
else
ParseError('Cannot append to attribute value, no attribute exists.');
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.EmitToken(Token: TILHTMLToken);
var
Acknowledged: Boolean;
i,Index: Integer;
begin
Acknowledged := False;
// remove duplicit attributes
If CDA_Count(Token.Attributes) > 0 then
For i := CDA_High(Token.Attributes) downto CDA_Low(Token.Attributes) do
begin
Index := CDA_IndexOf(Token.Attributes,CDA_GetItem(Token.Attributes,i));
If (Index >= 0) and (Index < i) then
If not ParseError('Duplicit attribute %s',[UnicodeToStr(CDA_GetItem(Token.Attributes,i).Name)]) then
CDA_Delete(Token.Attributes,i);
end;
If Assigned(fOnTokenEmit) then
case Token.TokenType of
ilttStartTag: begin
fOnTokenEmit(Self,IL_ThreadSafeCopy(Token),Acknowledged);
If not Token.SelfClosing then
CDA_Add(fLastStartTag,Token.TagName);
If Token.SelfClosing and not Acknowledged then
ParseError('Self closing start tag not acknowledged.');
end;
ilttEndTag: If CDA_Count(Token.Attributes) <= 0 then
begin
If not Token.SelfClosing then
begin
Token.AppropriateEndTag := IsAppropriateEndTagToken(Token);
fOnTokenEmit(Self,IL_ThreadSafeCopy(Token),Acknowledged);
If Token.AppropriateEndTag then
CDA_Delete(fLastStartTag,CDA_High(fLastStartTag));
end
else ParseError('Emitted end tag token with self-closing flag set.');
end
else ParseError('Emitted end tag token with attributes.');
ilttDOCTYPE: begin
If Length(Token.PublicIdentifier) > 0 then
Include(Token.PresentFields,iltfPublicIdent);
If Length(Token.SystemIdentifier) > 0 then
Include(Token.PresentFields,iltfSystemIdent);
fOnTokenEmit(Self,IL_ThreadSafeCopy(Token),Acknowledged);
end;
else
{Comment,Character,EndOfFile}
fOnTokenEmit(Self,IL_ThreadSafeCopy(Token),Acknowledged);
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.EmitCurrentToken;
begin
EmitToken(fCurrentToken);
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.EmitCurrentDOCTYPEToken;
begin
If fCurrentToken.TokenType = ilttDOCTYPE then
EmitCurrentToken
else
ParseError('Current token (%d) is not of expected type (DOCTYPE).',[Ord(fCurrentToken.TokenType)]);
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.EmitCurrentTagToken;
begin
If fCurrentToken.TokenType in [ilttStartTag,ilttEndTag] then
EmitCurrentToken
else
ParseError('Current token (%d) is not of expected type (tag).',[Ord(fCurrentToken.TokenType)]);
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.EmitCurrentCommentToken;
begin
If fCurrentToken.TokenType = ilttComment then
EmitCurrentToken
else
ParseError('Current token (%d) is not of expected type (comment).',[Ord(fCurrentToken.TokenType)]);
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.EmitCharToken(Char: UnicodeChar);
var
Token: TILHTMLToken;
begin
CreateNewToken(Token,ilttCharacter);
Token.Data := Char;
EmitToken(Token);
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.EmitEndOfFileToken;
var
Token: TILHTMLToken;
begin
CreateNewToken(Token,ilttEndOfFile);
EmitToken(Token);
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_Data;
begin
If not EndOfFile then
begin
case ConsumeNextInputChar of
UnicodeChar('&'): begin
fReturnState := iltsData;
fState := iltsCharacterReference;
end;
UnicodeChar('<'): fState := iltsTagOpen;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
EmitCharToken(CurrentInputChar);
else
EmitCharToken(CurrentInputChar);
end;
end
else EmitEndOfFileToken;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_RCDATA;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('&'): begin
fReturnState := iltsRCDATA;
fState := iltsCharacterReference;
end;
UnicodeChar('<'): fState := iltsRCDATALessThanSign;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
EmitCharToken(#$FFFD);
else
EmitCharToken(CurrentInputChar);
end
else EmitEndOfFileToken;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_RAWTEXT;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('<'): fState := iltsRAWTEXTLessThanSign;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
EmitCharToken(#$FFFD);
else
EmitCharToken(CurrentInputChar);
end
else EmitEndOfFileToken;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptData;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('<'): fState := iltsScriptDataLessThanSign;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
EmitCharToken(#$FFFD);
else
EmitCharToken(CurrentInputChar);
end
else EmitEndOfFileToken;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_PLAINTEXT;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
EmitCharToken(#$FFFD);
else
EmitCharToken(CurrentInputChar);
end
else EmitEndOfFileToken;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_TagOpen;
begin
case ConsumeNextInputChar of
UnicodeChar('!'): fState := iltsMarkupDeclarationOpen;
UnicodeChar('/'): fState := iltsEndTagOpen;
UnicodeChar('a')..
UnicodeChar('z'),
UnicodeChar('A')..
UnicodeChar('Z'): begin
CreateNewToken(ilttStartTag);
ReconsumeInputChar;
fState := iltsTagName;
end;
UnicodeChar('?'): If not ParseErrorInvalidChar(CurrentInputChar) then
begin
CreateNewToken(ilttComment);
ReconsumeInputChar;
fState := iltsBogusComment;
end;
else
If not ParseErrorInvalidChar(CurrentInputChar) then
begin
EmitCharToken(UnicodeChar('<'));
ReconsumeInputChar;
fState := iltsData;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_EndTagOpen;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('a')..
UnicodeChar('z'),
UnicodeChar('A')..
UnicodeChar('Z'): begin
CreateNewToken(ilttEndTag);
ReconsumeInputChar;
fState := iltsTagName;
end;
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputChar) then
fState := iltsData;
else
If not ParseErrorInvalidChar(CurrentInputChar) then
begin
CreateNewToken(ilttComment);
ReconsumeInputChar;
fState := iltsBogusComment;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
EmitCharToken(UnicodeChar('<'));
EmitCharToken(UnicodeChar('/'));
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_TagName;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: fState := iltsBeforeAttributeName;
UnicodeChar('/'): fState := iltsSelfClosingStartTag;
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentTagToken;
end;
UnicodeChar('A')..
UnicodeChar('Z'): AppendToCurrentToken(iltfTagName,UnicodeChar(Ord(CurrentInputChar) + $20));
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
AppendToCurrentToken(iltfTagName,#$FFFD);
else
AppendToCurrentToken(iltfTagName,CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_RCDATALessThanSign;
begin
case ConsumeNextInputChar of
UnicodeChar('/'): begin
CDA_Clear(fTemporaryBuffer);
fState := iltsRCDATAEndTagOpen;
end;
else
EmitCharToken(UnicodeChar('<'));
ReconsumeInputChar;
fState := iltsRCDATA;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_RCDATAEndTagOpen;
begin
case ConsumeNextInputChar of
UnicodeChar('a')..
UnicodeChar('z'),
UnicodeChar('A')..
UnicodeChar('Z'): begin
CreateNewToken(ilttEndTag);
ReconsumeInputChar;
fState := iltsRCDATAEndTagName;
end;
else
EmitCharToken(UnicodeChar('<'));
EmitCharToken(UnicodeChar('/'));
ReconsumeInputChar;
fState := iltsRCDATA;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_RCDATAEndTagName;
procedure DefaultAction;
var
i: Integer;
begin
EmitCharToken(UnicodeChar('<'));
EmitCharToken(UnicodeChar('/'));
For i := CDA_Low(fTemporaryBuffer) to CDA_High(fTemporaryBuffer) do
EmitCharToken(CDA_GetItem(fTemporaryBuffer,i));
ReconsumeInputChar;
fState := iltsRCDATA;
end;
begin
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: If IsAppropriateEndTagToken(fCurrentToken) then
fState := iltsBeforeAttributeName
else
DefaultAction;
UnicodeChar('/'): If IsAppropriateEndTagToken(fCurrentToken) then
fState := iltsSelfClosingStartTag
else
DefaultAction;
UnicodeChar('>'): If IsAppropriateEndTagToken(fCurrentToken) then
begin
fState := iltsData;
EmitCurrentTagToken;
end
else DefaultAction;
UnicodeChar('A')..
UnicodeChar('Z'): begin
AppendToCurrentToken(iltfTagName,UnicodeChar(Ord(CurrentInputChar) + $20));
CDA_Add(fTemporaryBuffer,CurrentInputChar);
end;
UnicodeChar('a')..
UnicodeChar('z'): begin
AppendToCurrentToken(iltfTagName,CurrentInputChar);
CDA_Add(fTemporaryBuffer,CurrentInputChar);
end;
else
DefaultAction;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_RAWTEXTLessThanSign;
begin
case ConsumeNextInputChar of
UnicodeChar('/'): begin
CDA_Clear(fTemporaryBuffer);
fState := iltsRAWTEXTEndTagOpen;
end;
else
EmitCharToken(UnicodeChar('<'));
ReconsumeInputChar;
fState := iltsRAWTEXT;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_RAWTEXTEndTagOpen;
begin
case ConsumeNextInputChar of
UnicodeChar('a')..
UnicodeChar('z'),
UnicodeChar('A')..
UnicodeChar('Z'): begin
CreateNewToken(ilttEndTag);
ReconsumeInputChar;
fState := iltsRAWTEXTEndTagName;
end;
else
EmitCharToken(UnicodeChar('<'));
EmitCharToken(UnicodeChar('/'));
ReconsumeInputChar;
fState := iltsRAWTEXT;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_RAWTEXTEndTagName;
procedure DefaultAction;
var
i: Integer;
begin
EmitCharToken(UnicodeChar('<'));
EmitCharToken(UnicodeChar('/'));
For i := CDA_Low(fTemporaryBuffer) to CDA_High(fTemporaryBuffer) do
EmitCharToken(CDA_GetItem(fTemporaryBuffer,i));
ReconsumeInputChar;
fState := iltsRAWTEXT;
end;
begin
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: If IsAppropriateEndTagToken(fCurrentToken) then
fState := iltsBeforeAttributeName
else
DefaultAction;
UnicodeChar('/'): If IsAppropriateEndTagToken(fCurrentToken) then
fState := iltsSelfClosingStartTag
else
DefaultAction;
UnicodeChar('>'): If IsAppropriateEndTagToken(fCurrentToken) then
begin
fState := iltsData;
EmitCurrentTagToken;
end
else DefaultAction;
UnicodeChar('A')..
UnicodeChar('Z'): begin
AppendToCurrentToken(iltfTagName,UnicodeChar(Ord(CurrentInputChar) + $20));
CDA_Add(fTemporaryBuffer,CurrentInputChar);
end;
UnicodeChar('a')..
UnicodeChar('z'): begin
AppendToCurrentToken(iltfTagName,CurrentInputChar);
CDA_Add(fTemporaryBuffer,CurrentInputChar);
end;
else
DefaultAction;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataLessThanSign;
begin
case ConsumeNextInputChar of
UnicodeChar('/'): begin
CDA_Clear(fTemporaryBuffer);
fState := iltsScriptDataEndTagOpen;
end;
UnicodeChar('!'): begin
fState := iltsScriptDataEscapeStart;
EmitCharToken(UnicodeChar('<'));
EmitCharToken(UnicodeChar('!'));
end;
else
EmitCharToken(UnicodeChar('<'));
ReconsumeInputChar;
fState := iltsScriptData;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataEndTagOpen;
begin
case ConsumeNextInputChar of
UnicodeChar('a')..
UnicodeChar('z'),
UnicodeChar('A')..
UnicodeChar('Z'): begin
CreateNewToken(ilttEndTag);
ReconsumeInputChar;
fState := iltsScriptDataEndTagName;
end;
else
EmitCharToken(UnicodeChar('<'));
EmitCharToken(UnicodeChar('/'));
ReconsumeInputChar;
fState := iltsScriptData;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataEndTagName;
procedure DefaultAction;
var
i: Integer;
begin
EmitCharToken(UnicodeChar('<'));
EmitCharToken(UnicodeChar('/'));
For i := CDA_Low(fTemporaryBuffer) to CDA_High(fTemporaryBuffer) do
EmitCharToken(CDA_GetItem(fTemporaryBuffer,i));
ReconsumeInputChar;
fState := iltsScriptData;
end;
begin
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: If IsAppropriateEndTagToken(fCurrentToken) then
fState := iltsBeforeAttributeName
else
DefaultAction;
UnicodeChar('/'): If IsAppropriateEndTagToken(fCurrentToken) then
fState := iltsSelfClosingStartTag
else
DefaultAction;
UnicodeChar('>'): If IsAppropriateEndTagToken(fCurrentToken) then
begin
fState := iltsData;
EmitCurrentTagToken;
end
else DefaultAction;
UnicodeChar('A')..
UnicodeChar('Z'): begin
AppendToCurrentToken(iltfTagName,UnicodeChar(Ord(CurrentInputChar) + $20));
CDA_Add(fTemporaryBuffer,CurrentInputChar);
end;
UnicodeChar('a')..
UnicodeChar('z'): begin
AppendToCurrentToken(iltfTagName,CurrentInputChar);
CDA_Add(fTemporaryBuffer,CurrentInputChar);
end;
else
DefaultAction;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataEscapeStart;
begin
case ConsumeNextInputChar of
UnicodeChar('-'): begin
fState := iltsScriptDataEscapeStartDash;
EmitCharToken(UnicodeChar('-'));
end;
else
ReconsumeInputChar;
fState := iltsScriptData;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataEscapeStartDash;
begin
case ConsumeNextInputChar of
UnicodeChar('-'): begin
fState := iltsScriptDataEscapedDashDash;
EmitCharToken(UnicodeChar('-'));
end;
else
ReconsumeInputChar;
fState := iltsScriptData;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataEscaped;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('-'): begin
fState := iltsScriptDataEscapedDash;
EmitCharToken(UnicodeChar('-'));
end;
UnicodeChar('<'): fState := iltsScriptDataEscapedLessThanSign;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
EmitCharToken(#$FFFD);
else
EmitCharToken(CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataEscapedDash;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('-'): begin
fState := iltsScriptDataEscapedDashDash;
EmitCharToken(UnicodeChar('-'));
end;
UnicodeChar('<'): fState := iltsScriptDataEscapedLessThanSign;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
begin
fState := iltsScriptDataEscaped;
EmitCharToken(#$FFFD);
end;
else
fState := iltsScriptDataEscaped;
EmitCharToken(CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataEscapedDashDash;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('-'): EmitCharToken(UnicodeChar('-'));
UnicodeChar('<'): fState := iltsScriptDataEscapedLessThanSign;
UnicodeChar('>'): begin
fState := iltsScriptData;
EmitCharToken(UnicodeChar('>'));
end;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
begin
fState := iltsScriptDataEscaped;
EmitCharToken(#$FFFD);
end;
else
fState := iltsScriptDataEscaped;
EmitCharToken(CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataEscapedLessThanSign;
begin
case ConsumeNextInputChar of
UnicodeChar('/'): begin
CDA_Clear(fTemporaryBuffer);
fState := iltsScriptDataEscapedEndTagOpen;
end;
UnicodeChar('a')..
UnicodeChar('z'),
UnicodeChar('A')..
UnicodeChar('Z'): begin
CDA_Clear(fTemporaryBuffer);
EmitCharToken(UnicodeChar('<'));
ReconsumeInputChar;
fState := iltsScriptDataDoubleEscapeStart;
end;
else
EmitCharToken(UnicodeChar('<'));
ReconsumeInputChar;
fState := iltsScriptDataEscaped;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataEscapedEndTagOpen;
begin
case ConsumeNextInputChar of
UnicodeChar('a')..
UnicodeChar('z'),
UnicodeChar('A')..
UnicodeChar('Z'): begin
CreateNewToken(ilttEndTag);
ReconsumeInputChar;
fState := iltsScriptDataEscapedEndTagName;
end;
else
EmitCharToken(UnicodeChar('<'));
EmitCharToken(UnicodeChar('/'));
ReconsumeInputChar;
fState := iltsScriptDataEscaped;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataEscapedEndTagName;
procedure DefaultAction;
var
i: Integer;
begin
EmitCharToken(UnicodeChar('<'));
EmitCharToken(UnicodeChar('/'));
For i := CDA_Low(fTemporaryBuffer) to CDA_High(fTemporaryBuffer) do
EmitCharToken(CDA_GetItem(fTemporaryBuffer,i));
ReconsumeInputChar;
fState := iltsScriptDataEscaped;
end;
begin
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: If IsAppropriateEndTagToken(fCurrentToken) then
fState := iltsBeforeAttributeName
else
DefaultAction;
UnicodeChar('/'): If IsAppropriateEndTagToken(fCurrentToken) then
fState := iltsSelfClosingStartTag
else
DefaultAction;
UnicodeChar('>'): If IsAppropriateEndTagToken(fCurrentToken) then
begin
fState := iltsData;
EmitCurrentTagToken;
end
else DefaultAction;
UnicodeChar('A')..
UnicodeChar('Z'): begin
AppendToCurrentToken(iltfTagName,UnicodeChar(Ord(CurrentInputChar) + $20));
CDA_Add(fTemporaryBuffer,CurrentInputChar);
end;
UnicodeChar('a')..
UnicodeChar('z'): begin
AppendToCurrentToken(iltfTagName,CurrentInputChar);
CDA_Add(fTemporaryBuffer,CurrentInputChar);
end;
else
DefaultAction;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataDoubleEscapeStart;
begin
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020,
UnicodeChar('/'),
UnicodeChar('>'): begin
If TemporaryBufferEquals('script',False) then
fState := iltsScriptDataDoubleEscaped
else
fState := iltsScriptDataEscaped;
EmitCharToken(CurrentInputChar);
end;
UnicodeChar('A')..
UnicodeChar('Z'): begin
CDA_Add(fTemporaryBuffer,UnicodeChar(Ord(CurrentInputChar) + $20));
EmitCharToken(CurrentInputChar);
end;
UnicodeChar('a')..
UnicodeChar('z'): begin
CDA_Add(fTemporaryBuffer,CurrentInputChar);
EmitCharToken(CurrentInputChar);
end;
else
ReconsumeInputChar;
fState := iltsScriptDataEscaped;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataDoubleEscaped;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('-'): begin
fState := iltsScriptDataDoubleEscapedDash;
EmitCharToken(UnicodeChar('-'));
end;
UnicodeChar('<'): begin
fState := iltsScriptDataDoubleEscapedLessThanSign;
EmitCharToken(UnicodeChar('<'));
end;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
EmitCharToken(#$FFFD);
else
EmitCharToken(CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataDoubleEscapedDash;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('-'): begin
fState := iltsScriptDataDoubleEscapedDashDash;
EmitCharToken(UnicodeChar('-'));
end;
UnicodeChar('<'): begin
fState := iltsScriptDataDoubleEscapedLessThanSign;
EmitCharToken(UnicodeChar('<'));
end;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
begin
fState := iltsScriptDataDoubleEscaped;
EmitCharToken(#$FFFD);
end;
else
fState := iltsScriptDataDoubleEscaped;
EmitCharToken(CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataDoubleEscapedDashDash;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('-'): EmitCharToken(UnicodeChar('-'));
UnicodeChar('<'): begin
fState := iltsScriptDataDoubleEscapedLessThanSign;
EmitCharToken(UnicodeChar('<'));
end;
UnicodeChar('>'): begin
fState := iltsScriptData;
EmitCharToken(UnicodeChar('>'));
end;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
begin
fState := iltsScriptDataDoubleEscaped;
EmitCharToken(#$FFFD);
end;
else
fState := iltsScriptDataDoubleEscaped;
EmitCharToken(CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataDoubleEscapedLessThanSign;
begin
case ConsumeNextInputChar of
UnicodeChar('/'): begin
CDA_Clear(fTemporaryBuffer);
fState := iltsScriptDataDoubleEscapeEnd;
EmitCharToken(UnicodeChar('/'));
end;
else
ReconsumeInputChar;
fState := iltsScriptDataDoubleEscaped;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_ScriptDataDoubleEscapeEnd;
begin
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020,
UnicodeChar('/'),
UnicodeChar('>'): begin
If TemporaryBufferEquals('script',False) then
fState := iltsScriptDataEscaped
else
fState := iltsScriptDataDoubleEscaped;
EmitCharToken(CurrentInputChar);
end;
UnicodeChar('A')..
UnicodeChar('Z'): begin
CDA_Add(fTemporaryBuffer,UnicodeChar(Ord(CurrentInputChar) + $20));
EmitCharToken(CurrentInputChar);
end;
UnicodeChar('a')..
UnicodeChar('z'): begin
CDA_Add(fTemporaryBuffer,CurrentInputChar);
EmitCharToken(CurrentInputChar);
end;
else
ReconsumeInputChar;
fState := iltsScriptDataDoubleEscaped;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_BeforeAttributeName;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020:; // ignore the character
UnicodeChar('/'),
UnicodeChar('>'): begin
ReconsumeInputChar;
fState := iltsAfterAttributeName;
end;
UnicodeChar('='): If not ParseErrorInvalidChar(CurrentInputChar) then
begin
CreateNewAttribute(CurrentInputChar,'');
fState := iltsAttributeName;
end;
else
CreateNewAttribute('','');
ReconsumeInputChar;
fState := iltsAttributeName;
end
else
begin
ReconsumeInputChar;
fState := iltsAfterAttributeName;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AttributeName;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020,
UnicodeChar('/'),
UnicodeChar('>'): begin
ReconsumeInputChar;
fState := iltsAfterAttributeName;
end;
UnicodeChar('='): fState := iltsBeforeAttributeValue;
UnicodeChar('A')..
UnicodeChar('Z'): AppendCurrentAttributeName(UnicodeChar(Ord(CurrentInputChar) + $20));
UnicodeChar(#0): AppendCurrentAttributeName(#$FFFD);
UnicodeChar('"'),
UnicodeChar(''''),
UnicodeChar('<'): If not ParseErrorInvalidChar(CurrentInputChar) then
AppendCurrentAttributeName(CurrentInputChar);
else
AppendCurrentAttributeName(CurrentInputChar);
end
else
begin
ReconsumeInputChar;
fState := iltsAfterAttributeName;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AfterAttributeName;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020:;// ignore the character
UnicodeChar('/'): fState := iltsSelfClosingStartTag;
UnicodeChar('='): fState := iltsBeforeAttributeValue;
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentTagToken;
end;
else
CreateNewAttribute('','');
ReconsumeInputChar;
fState := iltsAttributeName;
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_BeforeAttributeValue;
begin
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020:;// ignore the character
UnicodeChar('"'): fState := iltsAttributeValue_DoubleQuoted;
UnicodeChar(''''): fState := iltsAttributeValue_SingleQuoted;
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputChar) then
begin
ReconsumeInputChar;
fState := iltsAttributeValue_Unquoted;
end;
else
ReconsumeInputChar;
fState := iltsAttributeValue_Unquoted;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AttributeValue_DoubleQuoted;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('"'): fState := iltsAfterAttributeValue_Quoted;
UnicodeChar('&'): begin
fReturnState := iltsAttributeValue_DoubleQuoted;
fState := iltsCharacterReference;
end;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputchar) then
AppendCurrentAttributeValue(#$FFFD);
else
AppendCurrentAttributeValue(CurrentInputchar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AttributeValue_SingleQuoted;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar(''''): fState := iltsAfterAttributeValue_Quoted;
UnicodeChar('&'): begin
fReturnState := iltsAttributeValue_SingleQuoted;
fState := iltsCharacterReference;
end;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputchar) then
AppendCurrentAttributeValue(#$FFFD);
else
AppendCurrentAttributeValue(CurrentInputchar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AttributeValue_Unquoted;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: fState := iltsBeforeAttributeName;
UnicodeChar('&'): begin
fReturnState := iltsAttributeValue_Unquoted;
fState := iltsCharacterReference;
end;
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentTagToken;
end;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputChar) then
AppendCurrentAttributeValue(#$FFFD);
UnicodeChar('"'),
UnicodeChar(''''),
UnicodeChar('<'),
UnicodeChar('='),
UnicodeChar('`'): If not ParseErrorInvalidChar(CurrentInputChar) then
AppendCurrentAttributeValue(CurrentInputchar);
else
AppendCurrentAttributeValue(CurrentInputchar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AfterAttributeValue_Quoted;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: fState := iltsBeforeAttributeName;
UnicodeChar('/'): fState := iltsSelfClosingStartTag;
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentTagToken;
end;
else
If not ParseError('Unexpected end of file.') then
begin
ReconsumeInputChar;
fState := iltsBeforeAttributeName;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_SelfClosingStartTag;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('>'): begin
fcurrentToken.SelfClosing := True;
fState := iltsData;
EmitCurrentTagToken;
end;
else
If not ParseError('Unexpected end of file.') then
begin
ReconsumeInputChar;
fState := iltsBeforeAttributeName;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_BogusComment;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentCommentToken;
end;
UnicodeChar(#0): AppendToCurrentToken(iltfData,#$FFFD);
else
AppendToCurrentToken(iltfData,CurrentInputChar);
end
else
begin
EmitCurrentCommentToken;
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_MarkupDeclarationOpen;
begin
ConsumeNextInputChar;
If IsCurrentInputString(UnicodeString('--'),False) then
begin
ConsumeNextInputChar;
CreateNewToken(ilttComment);
fState := iltsCommentStart;
end
else If IsCurrentInputString(UnicodeString('DOCTYPE'),False) then
begin
Inc(fPosition,6);
fState := iltsDOCTYPE;
end
else If IsCurrentInputString(UnicodeString('[CDATA['),False) then
begin
{$IFDEF DevelMsgs}
{$message 'implement CDATA'}
{$ENDIF}
raise Exception.Create('not implemented');
end
else
begin
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
CreateNewToken(ilttComment);
fState := iltsBogusComment;
ReconsumeInputChar;
end;
end
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CommentStart;
begin
case ConsumeNextInputChar of
UnicodeChar('-'): fState := iltsCommentStartDash;
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fState := iltsData;
EmitCurrentCommentToken;
end;
else
ReconsumeInputChar;
fState := iltsComment;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CommentStartDash;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('-'): fState := iltsCommentEnd;
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputChar) then
begin
fState := iltsData;
EmitCurrentCommentToken;
end;
else
AppendToCurrentToken(iltfData,UnicodeChar('-'));
ReconsumeInputChar;
fState := iltsComment;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
EmitCurrentCommentToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_Comment;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('<'): begin
AppendToCurrentToken(iltfData,CurrentInputChar);
fState := iltsCommentLessThanSign;
end;
UnicodeChar('-'): fState := iltsCommentEndDash;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputchar) then
AppendToCurrentToken(iltfData,#$FFFD);
else
AppendToCurrentToken(iltfData,CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
EmitCurrentCommentToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CommentLessThanSign;
begin
case ConsumeNextInputChar of
UnicodeChar('!'): begin
AppendToCurrentToken(iltfData,CurrentInputChar);
fState := iltsCommentLessThanSignBang;
end;
UnicodeChar('<'): AppendToCurrentToken(iltfData,CurrentInputChar);
else
ReconsumeInputChar;
fState := iltsComment;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CommentLessThanSignBang;
begin
case ConsumeNextInputChar of
UnicodeChar('-'): fState := iltsCommentLessThanSignBangDash;
else
ReconsumeInputChar;
fState := iltsComment;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CommentLessThanSignBangDash;
begin
case ConsumeNextInputChar of
UnicodeChar('-'): fState := iltsCommentLessThanSignBangDashDash;
else
ReconsumeInputChar;
fState := iltsCommentEndDash;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CommentLessThanSignBangDashDash;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('>'): begin
ReconsumeInputChar;
fState := iltsCommentEnd;
end;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
ReconsumeInputChar;
fState := iltsCommentEnd;
end;
end
else
begin
ReconsumeInputChar;
fState := iltsCommentEnd;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CommentEndDash;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('-'): fState := iltsCommentEnd;
else
AppendToCurrentToken(iltfData,UnicodeChar('-'));
ReconsumeInputChar;
fState := iltsComment;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
EmitCurrentCommentToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CommentEnd;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentCommentToken;
end;
UnicodeChar('!'): fState := iltsCommentEndBang;
UnicodeChar('-'): AppendToCurrentToken(iltfData,UnicodeChar('-'));
else
AppendToCurrentToken(iltfData,UnicodeChar('-'));
AppendToCurrentToken(iltfData,UnicodeChar('-'));
ReconsumeInputChar;
fState := iltsComment;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
EmitCurrentCommentToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CommentEndBang;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('-'): begin
AppendToCurrentToken(iltfData,UnicodeChar('-'));
AppendToCurrentToken(iltfData,UnicodeChar('-'));
AppendToCurrentToken(iltfData,UnicodeChar('!'));
fState := iltsCommentEndDash;
end;
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fState := iltsData;
EmitCurrentCommentToken;
end;
else
AppendToCurrentToken(iltfData,UnicodeChar('-'));
AppendToCurrentToken(iltfData,UnicodeChar('-'));
AppendToCurrentToken(iltfData,UnicodeChar('!'));
ReconsumeInputChar;
fState := iltsComment;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
EmitCurrentCommentToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_DOCTYPE;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: fState := iltsBeforeDOCTYPEName;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
ReconsumeInputChar;
fState := iltsBeforeDOCTYPEName;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
CreateNewToken(ilttDOCTYPE);
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_BeforeDOCTYPEName;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020:; // ignore the character
UnicodeChar('A')..
UnicodeChar('Z'): begin
CreateNewToken(ilttDOCTYPE);
fCurrentToken.Name := UnicodeChar(Ord(CurrentInputChar) + $20);
fState := iltsDOCTYPEName;
end;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
CreateNewToken(ilttDOCTYPE);
fCurrentToken.Name := #$FFFD;
fState := iltsDOCTYPEName;
end;
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
CreateNewToken(ilttDOCTYPE);
fCurrentToken.ForceQuirks := True;
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
CreateNewToken(ilttDOCTYPE);
fCurrentToken.Name := CurrentInputChar;
fState := iltsDOCTYPEName;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
CreateNewToken(ilttDOCTYPE);
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_DOCTYPEName;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: fState := iltsAfterDOCTYPEName;
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
UnicodeChar('A')..
UnicodeChar('Z'): AppendToCurrentToken(iltfName,UnicodeChar(Ord(CurrentInputChar) + $20));
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputchar) then
AppendToCurrentToken(iltfName,#$FFFD);
else
AppendToCurrentToken(iltfName,CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AfterDOCTYPEName;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020:;// ignore the character
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
If IsCurrentInputString('PUBLIC',False) then
begin
Inc(fPosition,5);
fState := iltsAfterDOCTYPEPublicKeyword;
end
else If IsCurrentInputString('SYSTEM',False) then
begin
Inc(fPosition,5);
fState := iltsAfterDOCTYPESystemKeyword;
end
else
begin
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsBogusDOCTYPE;
end;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AfterDOCTYPEPublicKeyword;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: fState := iltsBeforeDOCTYPEPublicIdentifier;
UnicodeChar('"'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.PublicIdentifier := UnicodeString('');
Include(fCurrentToken.PresentFields,iltfPublicIdent);
fState := iltsDOCTYPEPublicIdentifier_DoubleQuoted;
end;
UnicodeChar(''''): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.PublicIdentifier := UnicodeString('');
Include(fCurrentToken.PresentFields,iltfPublicIdent);
fState := iltsDOCTYPEPublicIdentifier_SingleQuoted;
end;
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsBogusDOCTYPE;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_BeforeDOCTYPEPublicIdentifier;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020:;// ignore the character
UnicodeChar('"'): begin
fCurrentToken.PublicIdentifier := '';
Include(fCurrentToken.PresentFields,iltfPublicIdent);
fState := iltsDOCTYPEPublicIdentifier_DoubleQuoted;
end;
UnicodeChar(''''): begin
fCurrentToken.PublicIdentifier := '';
Include(fCurrentToken.PresentFields,iltfPublicIdent);
fState := iltsDOCTYPEPublicIdentifier_SingleQuoted;
end;
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsBogusDOCTYPE;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_DOCTYPEPublicIdentifier_DoubleQuoted;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('"'): fState := iltsAfterDOCTYPEPublicIdentifier;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputchar) then
AppendToCurrentToken(iltfPublicIdent,#$FFFD);
UnicodeChar('>'): begin
fCurrentToken.ForceQuirks := True;
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
AppendToCurrentToken(iltfPublicIdent,CurrentInputchar);
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_DOCTYPEPublicIdentifier_SingleQuoted;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar(''''): fState := iltsAfterDOCTYPEPublicIdentifier;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputchar) then
AppendToCurrentToken(iltfPublicIdent,#$FFFD);
UnicodeChar('>'): begin
fCurrentToken.ForceQuirks := True;
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
AppendToCurrentToken(iltfPublicIdent,CurrentInputchar);
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AfterDOCTYPEPublicIdentifier;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: fState := iltsBetweenDOCTYPEPublicAndSystemIdentifiers;
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
UnicodeChar('"'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.SystemIdentifier := '';
Include(fCurrentToken.PresentFields,iltfSystemIdent);
fState := iltsDOCTYPESystemIdentifier_DoubleQuoted;
end;
UnicodeChar(''''): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.SystemIdentifier := '';
Include(fCurrentToken.PresentFields,iltfSystemIdent);
fState := iltsDOCTYPESystemIdentifier_SingleQuoted;
end;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsBogusDOCTYPE;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_BetweenDOCTYPEPublicAndSystemIdentifiers;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020:;// ignore the character
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
UnicodeChar('"'): begin
fCurrentToken.SystemIdentifier := '';
Include(fCurrentToken.PresentFields,iltfSystemIdent);
fState := iltsDOCTYPESystemIdentifier_DoubleQuoted;
end;
UnicodeChar(''''): begin
fCurrentToken.SystemIdentifier := '';
Include(fCurrentToken.PresentFields,iltfSystemIdent);
fState := iltsDOCTYPESystemIdentifier_SingleQuoted;
end;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsBogusDOCTYPE;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AfterDOCTYPESystemKeyword;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020: fState := iltsBeforeDOCTYPESystemIdentifier;
UnicodeChar('"'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.SystemIdentifier := '';
Include(fCurrentToken.PresentFields,iltfSystemIdent);
fState := iltsDOCTYPESystemIdentifier_DoubleQuoted;
end;
UnicodeChar(''''): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.SystemIdentifier := '';
Include(fCurrentToken.PresentFields,iltfSystemIdent);
fState := iltsDOCTYPESystemIdentifier_SingleQuoted;
end;
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsBogusDOCTYPE;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_BeforeDOCTYPESystemIdentifier;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020:;// ignore the character
UnicodeChar('"'): begin
fCurrentToken.SystemIdentifier := '';
Include(fCurrentToken.PresentFields,iltfSystemIdent);
fState := iltsDOCTYPESystemIdentifier_DoubleQuoted;
end;
UnicodeChar(''''): begin
fCurrentToken.SystemIdentifier := '';
Include(fCurrentToken.PresentFields,iltfSystemIdent);
fState := iltsDOCTYPESystemIdentifier_SingleQuoted;
end;
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsBogusDOCTYPE;
end;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_DOCTYPESystemIdentifier_DoubleQuoted;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('"'): fState := iltsAfterDOCTYPESystemIdentifier;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputchar) then
AppendToCurrentToken(iltfSystemIdent,#$FFFD);
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
AppendToCurrentToken(iltfSystemIdent,CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_DOCTYPESystemIdentifier_SingleQuoted;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar(''''): fState := iltsAfterDOCTYPESystemIdentifier;
UnicodeChar(#0): If not ParseErrorInvalidChar(CurrentInputchar) then
AppendToCurrentToken(iltfSystemIdent,#$FFFD);
UnicodeChar('>'): If not ParseErrorInvalidChar(CurrentInputchar) then
begin
fCurrentToken.ForceQuirks := True;
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
AppendToCurrentToken(iltfSystemIdent,CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_AfterDOCTYPESystemIdentifier;
begin
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020:; // ignore the character
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
fState := iltsBogusDOCTYPE;
end
else
begin
If not ParseError('Unexpected end of file.') then
begin
fCurrentToken.ForceQuirks := True;
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_BogusDOCTYPE;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar('>'): begin
fState := iltsData;
EmitCurrentDOCTYPEToken;
end;
else
// ignore the character
end
else
begin
EmitCurrentDOCTYPEToken;
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CDATASection;
begin
If not EndOfFile then
case ConsumeNextInputChar of
UnicodeChar(']'): fState := iltsCDATASectionBracket;
else
EmitCharToken(CurrentInputChar);
end
else
begin
If not ParseError('Unexpected end of file.') then
EmitEndOfFileToken;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CDATASectionBracket;
begin
case ConsumeNextInputChar of
UnicodeChar(']'): fState := iltsCDATASectionEnd;
else
EmitCharToken(UnicodeChar(']'));
ReconsumeInputChar;
fState := iltsCDATASection;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CDATASectionEnd;
begin
case ConsumeNextInputChar of
UnicodeChar(']'): EmitCharToken(UnicodeChar(']'));
UnicodeChar('>'): fState := iltsData;
else
EmitCharToken(UnicodeChar(']'));
EmitCharToken(UnicodeChar(']'));
ReconsumeInputChar;
fState := iltsCDATASection;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CharacterReference_ResolveNamedReference;
var
EntryPos: Integer;
PrevIndex: Integer;
Index: Integer;
AttrProc: Boolean;
Function IndexOfNamedRef(const Ref: UnicodeString): Integer;
var
i: Integer;
begin
// find index of named refrence stored in a temporary buffer
// if not found, returns -1
Result := -1;
For i := Low(IL_HTML_NAMED_CHAR_REFS) to High(IL_HTML_NAMED_CHAR_REFS) do
If IL_UnicodeSameString(IL_HTML_NAMED_CHAR_REFS[i].Name,Ref,True) then
begin
If NextInputChar = UnicodeChar(';') then
begin
Result := IndexOfNamedRef(Ref + UnicodeChar(';'));
If Result >= 0 then
CDA_Add(fTemporaryBuffer,ConsumeNextInputChar)
else
Result := i;
end
else Result := i;
Break{For i};
end;
end;
Function CheckTempBuffForValidCharRef: Boolean;
var
i: Integer;
begin
Result := False;
If CDA_Count(fTemporaryBuffer) > 2 then
If (CDA_First(fTemporaryBuffer) = '&') and (CDA_Last(fTemporaryBuffer) = ';') then
begin
Result := True;
For i := Succ(CDA_Low(fTemporaryBuffer)) to Pred(CDA_High(fTemporaryBuffer)) do
If not IL_UTF16CharInSet(CDA_GetItem(fTemporaryBuffer,i),['0'..'9','a'..'z','A'..'Z']) then
begin
Result := False;
Break{For i};
end;
end
end;
begin
// store position in input upon entry (which is position just after ampersand)
EntryPos := fPosition;
PrevIndex := -1;
Index := -1;
// find the LONGEST charref
while not EndOfFile and not fParserPause do
begin
CDA_Add(fTemporaryBuffer,ConsumeNextInputChar);
// search the table only when there is really a chance to find anything
If CDA_Count(fTemporaryBuffer) <= IL_HTML_NAMED_CHAR_REF_MAXLEN then
Index := IndexOfNamedRef(TemporaryBufferAsStr)
else
Index := -1;
If (Index < 0) and (PrevIndex >= 0) then
begin
CDA_Delete(fTemporaryBuffer,CDA_High(fTemporaryBuffer));
ReconsumeInputChar;
Index := PrevIndex;
Break{while...};
end;
PrevIndex := Index;
end;
If Index >= 0 then
begin
// reference was successfuly resolved
// check if it should be processed normally or as an attribute value special
AttrProc := (fReturnState in [iltsAttributeValue_DoubleQuoted,iltsAttributeValue_SingleQuoted,
iltsAttributeValue_Unquoted]) and (CDA_Last(fTemporaryBuffer) <> UnicodeChar(';'));
If AttrProc and (CDA_Count(fTemporaryBuffer) > 1) then
AttrProc := IL_UTF16CharInSet(CDA_GetItem(fTemporaryBuffer,CDA_Low(fTemporaryBuffer) + 1),['=','0'..'9','a'..'Z','A'..'Z'])
else
AttrProc := False;
If not AttrProc then
begin
// process normally
If CDA_Last(fTemporaryBuffer) <> UnicodeChar(';') then
ParseError('Invalid character reference "%s".',[UnicodeToStr(TemporaryBufferAsStr)]);
// put resolved chars to temp. buffer
CDA_Clear(fTemporaryBuffer);
If IL_HTML_NAMED_CHAR_REFS[Index].CodePointA >= $10000 then
begin
CDA_Add(fTemporaryBuffer,IL_UTF16HighSurrogate(IL_HTML_NAMED_CHAR_REFS[Index].CodePointA));
CDA_Add(fTemporaryBuffer,IL_UTF16LowSurrogate(IL_HTML_NAMED_CHAR_REFS[Index].CodePointA));
end
else CDA_Add(fTemporaryBuffer,UnicodeChar(IL_HTML_NAMED_CHAR_REFS[Index].CodePointA));
If IL_HTML_NAMED_CHAR_REFS[Index].CodePointA > 0 then
begin
If IL_HTML_NAMED_CHAR_REFS[Index].CodePointB >= $10000 then
begin
CDA_Add(fTemporaryBuffer,IL_UTF16HighSurrogate(IL_HTML_NAMED_CHAR_REFS[Index].CodePointB));
CDA_Add(fTemporaryBuffer,IL_UTF16LowSurrogate(IL_HTML_NAMED_CHAR_REFS[Index].CodePointB));
end
else CDA_Add(fTemporaryBuffer,UnicodeChar(IL_HTML_NAMED_CHAR_REFS[Index].CodePointB));
end;
fState := iltsCharacterReferenceEnd;
end
else
begin
{
reference is in attribute value, last matched character is NOT an
ampersand and character just after the amp. is equal sign or an
alphanumeric character...
...ignore the reference and pass the characters as they are
}
CDA_Clear(fTemporaryBuffer);
CDA_Add(fTemporaryBuffer,UnicodeChar('&'));
fPosition := EntryPos; // return to position just after the amp
fState := iltsCharacterReferenceEnd;
end
end
else
begin
// reference could not be resolved, temp. buffer by now contains rest of the file
If CheckTempBuffForValidCharRef then
begin
If CDA_Count(fTemporaryBuffer) <= IL_HTML_NAMED_CHAR_REF_MAXLEN then
ParseError('Invalid character reference "%s".',[UnicodeToStr(TemporaryBufferAsStr)])
else
ParseError('Invalid character reference.')
end;
CDA_Clear(fTemporaryBuffer);
CDA_Add(fTemporaryBuffer,UnicodeChar('&'));
fPosition := EntryPos; // return to position just after the amp
fState := iltsCharacterReferenceEnd;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CharacterReference;
begin
CDA_Clear(fTemporaryBuffer);
CDA_Add(fTemporaryBuffer,UnicodeChar('&'));
If not EndOfFile then
case ConsumeNextInputChar of
#$0009,
#$000A,
#$000C,
#$0020,
UnicodeChar('<'),
UnicodeChar('&'): begin
ReconsumeInputChar;
fState := iltsCharacterReferenceEnd;
end;
UnicodeChar('#'): begin
CDA_Add(fTemporaryBuffer,CurrentInputChar);
fState := iltsNumericCharacterReference;
end;
else
ReconsumeInputChar;
State_CharacterReference_ResolveNamedReference;
end
else
begin
ReconsumeInputChar;
fState := iltsCharacterReferenceEnd;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_NumericCharacterReference;
begin
fCharRefCode := 0;
case ConsumeNextInputChar of
UnicodeChar('x'),
UnicodeChar('X'): begin
CDA_Add(fTemporaryBuffer,CurrentInputChar);
fState := iltsHexadecimalCharacterReferenceStart;
end;
else
ReconsumeInputChar;
fState := iltsDecimalCharacterReferenceStart;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_HexadecimalCharacterReferenceStart;
begin
case ConsumeNextInputChar of
UnicodeChar('0')..
UnicodeChar('9'),
UnicodeChar('a')..
UnicodeChar('f'),
UnicodeChar('A')..
UnicodeChar('F'): begin
ReconsumeInputChar;
fState := iltsHexadecimalCharacterReference;
end;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
ReconsumeInputChar;
fState := iltsCharacterReferenceEnd;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_DecimalCharacterReferenceStart;
begin
case ConsumeNextInputChar of
UnicodeChar('0')..
UnicodeChar('9'): begin
ReconsumeInputChar;
fState := iltsDecimalCharacterReference;
end;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
ReconsumeInputChar;
fState := iltsCharacterReferenceEnd;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_HexadecimalCharacterReference;
begin
case ConsumeNextInputChar of
UnicodeChar('0')..
UnicodeChar('9'): begin
fCharRefCode := fCharRefCode * 16;
fCharRefCode := fCharRefCode + UInt32(Ord(CurrentInputchar) - $30);
end;
UnicodeChar('A')..
UnicodeChar('F'): begin
fCharRefCode := fCharRefCode * 16;
fCharRefCode := fCharRefCode + UInt32(Ord(CurrentInputchar) - $37);
end;
UnicodeChar('a')..
UnicodeChar('f'): begin
fCharRefCode := fCharRefCode * 16;
fCharRefCode := fCharRefCode + UInt32(Ord(CurrentInputchar) - $57);
end;
UnicodeChar(';'): fState := iltsNumericCharacterReferenceEnd;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
ReconsumeInputChar;
fState := iltsNumericCharacterReferenceEnd;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_DecimalCharacterReference;
begin
case ConsumeNextInputChar of
UnicodeChar('0')..
UnicodeChar('9'): begin
fCharRefCode := fCharRefCode * 10;
fCharRefCode := fCharRefCode + UInt32(Ord(CurrentInputchar) - $30);
end;
UnicodeChar(';'): fState := iltsNumericCharacterReferenceEnd;
else
If not ParseErrorInvalidChar(CurrentInputchar) then
begin
ReconsumeInputChar;
fState := iltsNumericCharacterReferenceEnd;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_NumericCharacterReferenceEnd;
var
i: Integer;
Function CharIsForbidden(CharRefCode: UInt32): Boolean;
var
ii: Integer;
begin
Result := False;
For ii := Low(IL_TOKENIZER_CHAR_FORBIDDEN) to High(IL_TOKENIZER_CHAR_FORBIDDEN) do
If CharRefCode = IL_TOKENIZER_CHAR_FORBIDDEN[ii] then
begin
Result := True;
Break{For ii};
end;
end;
begin
// replacement table
For i := Low(IL_TOKENIZER_CHAR_REPLACE) to High(IL_TOKENIZER_CHAR_REPLACE) do
If fCharRefCode = Ord(IL_TOKENIZER_CHAR_REPLACE[i].OldChar) then
begin
If not ParseErrorInvalidChar(UnicodeChar(fCharRefCode)) then
fCharRefCode := Ord(IL_TOKENIZER_CHAR_REPLACE[i].Replacement);
Break{For i};
end;
// check ranges
If ((fCharRefCode >= $D800) and (fCharRefCode <= $DFFF)) or (fCharRefCode > $10FFFF) then
If not ParseErrorInvalidChar(UnicodeChar(fCharRefCode)) then
fCharRefCode := $FFFD;
// other checks
If ((fCharRefCode >= $0001) and (fCharRefCode <= $0008)) or ((fCharRefCode >= $000D) and (fCharRefCode <= $001F)) or
((fCharRefCode >= $007F) and (fCharRefCode <= $009F)) or ((fCharRefCode >= $FDD0) and (fCharRefCode <= $FDEF)) or
CharIsForbidden(fCharRefCode) then
ParseErrorInvalidChar(UnicodeChar(fCharRefCode));
// output char
CDA_Clear(fTemporaryBuffer);
If fCharRefCode >= $10000 then
begin
CDA_Add(fTemporaryBuffer,IL_UTF16HighSurrogate(fCharRefCode));
CDA_Add(fTemporaryBuffer,IL_UTF16LowSurrogate(fCharRefCode));
end
else CDA_Add(fTemporaryBuffer,UnicodeChar(fCharRefCode));
fState := iltsCharacterReferenceEnd;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_CharacterReferenceEnd;
var
i: Integer;
begin
ConsumeNextInputChar;
case fReturnState of
iltsAttributeValue_DoubleQuoted,
iltsAttributeValue_SingleQuoted,
iltsAttributeValue_Unquoted:
For i := CDA_Low(fTemporaryBuffer) to CDA_High(fTemporaryBuffer) do
AppendCurrentAttributeValue(CDA_GetItem(fTemporaryBuffer,i));
else
For i := CDA_Low(fTemporaryBuffer) to CDA_High(fTemporaryBuffer) do
EmitCharToken(CDA_GetItem(fTemporaryBuffer,i));
end;
ReconsumeInputChar;
fState := fReturnState;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.State_Select;
begin
case fState of
iltsData: State_Data;
iltsRCDATA: State_RCDATA;
iltsRAWTEXT: State_RAWTEXT;
iltsScriptData: State_ScriptData;
iltsPLAINTEXT: State_PLAINTEXT;
iltsTagOpen: State_TagOpen;
iltsEndTagOpen: State_EndTagOpen;
iltsTagName: State_TagName;
iltsRCDATALessThanSign: State_RCDATALessThanSign;
iltsRCDATAEndTagOpen: State_RCDATAEndTagOpen;
iltsRCDATAEndTagName: State_RCDATAEndTagName;
iltsRAWTEXTLessThanSign: State_RAWTEXTLessThanSign;
iltsRAWTEXTEndTagOpen: State_RAWTEXTEndTagOpen;
iltsRAWTEXTEndTagName: State_RAWTEXTEndTagName;
iltsScriptDataLessThanSign: State_ScriptDataLessThanSign;
iltsScriptDataEndTagOpen: State_ScriptDataEndTagOpen;
iltsScriptDataEndTagName: State_ScriptDataEndTagName;
iltsScriptDataEscapeStart: State_ScriptDataEscapeStart;
iltsScriptDataEscapeStartDash: State_ScriptDataEscapeStartDash;
iltsScriptDataEscaped: State_ScriptDataEscaped;
iltsScriptDataEscapedDash: State_ScriptDataEscapedDash;
iltsScriptDataEscapedDashDash: State_ScriptDataEscapedDashDash;
iltsScriptDataEscapedLessThanSign: State_ScriptDataEscapedLessThanSign;
iltsScriptDataEscapedEndTagOpen: State_ScriptDataEscapedEndTagOpen;
iltsScriptDataEscapedEndTagName: State_ScriptDataEscapedEndTagName;
iltsScriptDataDoubleEscapeStart: State_ScriptDataDoubleEscapeStart;
iltsScriptDataDoubleEscaped: State_ScriptDataDoubleEscaped;
iltsScriptDataDoubleEscapedDash: State_ScriptDataDoubleEscapedDash;
iltsScriptDataDoubleEscapedDashDash: State_ScriptDataDoubleEscapedDashDash;
iltsScriptDataDoubleEscapedLessThanSign: State_ScriptDataDoubleEscapedLessThanSign;
iltsScriptDataDoubleEscapeEnd: State_ScriptDataDoubleEscapeEnd;
iltsBeforeAttributeName: State_BeforeAttributeName;
iltsAttributeName: State_AttributeName;
iltsAfterAttributeName: State_AfterAttributeName;
iltsBeforeAttributeValue: State_BeforeAttributeValue;
iltsAttributeValue_DoubleQuoted: State_AttributeValue_DoubleQuoted;
iltsAttributeValue_SingleQuoted: State_AttributeValue_SingleQuoted;
iltsAttributeValue_Unquoted: State_AttributeValue_Unquoted;
iltsAfterAttributeValue_Quoted: State_AfterAttributeValue_Quoted;
iltsSelfClosingStartTag: State_SelfClosingStartTag;
iltsBogusComment: State_BogusComment;
iltsMarkupDeclarationOpen: State_MarkupDeclarationOpen;
iltsCommentStart: State_CommentStart;
iltsCommentStartDash: State_CommentStartDash;
iltsComment: State_Comment;
iltsCommentLessThanSign: State_CommentLessThanSign;
iltsCommentLessThanSignBang: State_CommentLessThanSignBang;
iltsCommentLessThanSignBangDash: State_CommentLessThanSignBangDash;
iltsCommentLessThanSignBangDashDash: State_CommentLessThanSignBangDashDash;
iltsCommentEndDash: State_CommentEndDash;
iltsCommentEnd: State_CommentEnd;
iltsCommentEndBang: State_CommentEndBang;
iltsDOCTYPE: State_DOCTYPE;
iltsBeforeDOCTYPEName: State_BeforeDOCTYPEName;
iltsDOCTYPEName: State_DOCTYPEName;
iltsAfterDOCTYPEName: State_AfterDOCTYPEName;
iltsAfterDOCTYPEPublicKeyword: State_AfterDOCTYPEPublicKeyword;
iltsBeforeDOCTYPEPublicIdentifier: State_BeforeDOCTYPEPublicIdentifier;
iltsDOCTYPEPublicIdentifier_DoubleQuoted: State_DOCTYPEPublicIdentifier_DoubleQuoted;
iltsDOCTYPEPublicIdentifier_SingleQuoted: State_DOCTYPEPublicIdentifier_SingleQuoted;
iltsAfterDOCTYPEPublicIdentifier: State_AfterDOCTYPEPublicIdentifier;
iltsBetweenDOCTYPEPublicAndSystemIdentifiers: State_BetweenDOCTYPEPublicAndSystemIdentifiers;
iltsAfterDOCTYPESystemKeyword: State_AfterDOCTYPESystemKeyword;
iltsBeforeDOCTYPESystemIdentifier: State_BeforeDOCTYPESystemIdentifier;
iltsDOCTYPESystemIdentifier_DoubleQuoted: State_DOCTYPESystemIdentifier_DoubleQuoted;
iltsDOCTYPESystemIdentifier_SingleQuoted: State_DOCTYPESystemIdentifier_SingleQuoted;
iltsAfterDOCTYPESystemIdentifier: State_AfterDOCTYPESystemIdentifier;
iltsBogusDOCTYPE: State_BogusDOCTYPE;
iltsCDATASection: State_CDATASection;
iltsCDATASectionBracket: State_CDATASectionBracket;
iltsCDATASectionEnd: State_CDATASectionEnd;
iltsCharacterReference: State_CharacterReference;
iltsNumericCharacterReference: State_NumericCharacterReference;
iltsHexadecimalCharacterReferenceStart: State_HexadecimalCharacterReferenceStart;
iltsDecimalCharacterReferenceStart: State_DecimalCharacterReferenceStart;
iltsHexadecimalCharacterReference: State_HexadecimalCharacterReference;
iltsDecimalCharacterReference: State_DecimalCharacterReference;
iltsNumericCharacterReferenceEnd: State_NumericCharacterReferenceEnd;
iltsCharacterReferenceEnd: State_CharacterReferenceEnd;
else
raise Exception.CreateFmt('TILHTMLTokenizer.State_Select: Invalid tokenizer state (%d).',[Ord(fState)]);
end;
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.NextInputChar: UnicodeChar;
begin
If (fPosition >= 1) and (fPosition <= Length(fData)) then
Result := fData[fPosition]
else
Result := #0;
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.CurrentInputChar: UnicodeChar;
begin
If (fPosition > 1) and (fPosition <= Length(fData)) then
Result := fData[fPosition - 1]
else
Result := #0;
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.ConsumeNextInputChar: UnicodeChar;
begin
Result := NextInputChar;
Inc(fPosition);
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.ReconsumeInputChar;
begin
Dec(fPosition);
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.EndOfFile: Boolean;
begin
Result := fPosition > Length(fData);
end;
//==============================================================================
constructor TILHTMLTokenizer.Create;
begin
inherited Create;
fRaiseParseErrs := False;
end;
//------------------------------------------------------------------------------
destructor TILHTMLTokenizer.Destroy;
begin
inherited;
end;
//------------------------------------------------------------------------------
procedure TILHTMLTokenizer.Initialize(const Data: UnicodeString);
begin
// internals
fData := Data;
UniqueString(fData);
fPosition := 1;
// state machine
fParserPause := False;
fState := iltsData;
fReturnState := iltsData;
CDA_Init(fTemporaryBuffer);
fCharRefCode := 0;
// helpers
CDA_Init(fLastStartTag);
CDA_Init(fCurrentToken.Attributes);
CreateNewToken(ilttEndOfFile); // this will initialize current token
end;
//------------------------------------------------------------------------------
Function TILHTMLTokenizer.Run: Boolean;
begin
while not EndOfFile and not fParserPause do
State_Select;
Result := not fParserPause and (fPosition > Length(fData));
end;
end.
|
unit Paths;
{$MODE Delphi}
//
// PHOLIAGE Model, (c) Roelof Oomen, 2006-2007
//
// Model path length calculations
//
interface
// Use table lookup instead of calculating everything every time
// Speeds up program enormously
{$DEFINE TABLES}
uses
Vector, Quadratic, GaussInt;
const
// Constants of leaf angle distribution functions
LACLASSES = 0;
LACONTINUOUS = 1;
LASPHERICAL = 2;
type
//*************** Support classes/records **************************************
TAngleClass = record
Mid : Double;
Width : Double;
fraction : Double;
end;
///Area for leaf area density and distribution
TLeafArea = record
// Angle class array
// Note: Last class includes upper boundary
// E.g. in degrees: [0,30) [30,60) [60,90]
AngleClasses : array of TAngleClass;
// Leaf area density
F : Double;
// Leaf light absorption coefficient
a_L : double;
// Leaf angle distribution function
LADist : byte;
// Azimuthal width of the leaf distribution, normally 2pi
AzWidth : Double;
// Identification for lookup table
id : integer;
// Clear leaf angle list & set up record -- Always call first!
procedure Clear;
// Add a leaf angle class and keeps class list sorted
procedure addclass(Mid, Width, fraction : Double);
// Same but in degrees instead of radians
procedure addclassD(Mid, Width, fraction : Double);
// If numbers of leaves in each class are added instead of fractions
// this calculates fractions for each class adding up to a total of 1
procedure fractionise;
function f_omega(const theta_L: double):double;
end;
//*************** Extinction coefficient calculations **************************
///Integration class of azimuth part of extinction
TExtinctionAz = class(TGaussInt)
strict private
d_L,
d_i: TVectorS;
{$IFDEF TABLES}
Ans : array of Double; // Saves last result
{$ENDIF}
protected
function fuGI(const xGI: Double): Double; override;
public
function AzInt(const _d_L, _d_i: TVectorS; _step: integer): double;
constructor Create;
end;
///Calculates a vegetation extinction coefficient
TExtinction = class (TGaussInt)
strict private
d_L,
d_i : TVectorS;
F : TLeafArea;
// Used for table index
AClass : Integer;
{$IFDEF TABLES}
Kf_table : array[0..1,0..1] of array of array of Double;
{$ENDIF}
private
procedure GP_w(const Value: integer);
function number_N: integer;
protected
function fuGI(const xGI: Double): Double; override;
public
// Class integrating over the azimuth angle
ExtinctionAz : TExtinctionAz;
function Kf(const _d_i : TVectorS; var _F : TLeafArea; stepPol, stepAz, id: integer): double;
// Set both own and ExtinctionAz's GP
property GP : integer read number_N write GP_w;
constructor Create; // Instantiates ExtinctionAz
destructor Destroy; override;
end;
//*************** Pathlength calculations **************************************
TAttenuation = interface
function Attenuation( _p, _d_i : TVectorS; stepPol, stepAz, id: integer): double;
end;
///The surrounding vegetation for a circular gap
TVegetationCircular = class (TQuadratic)
strict private
Extinction : TExtinction;
p, // Intersection of light with the crown ellipsoid
// Should be equal to TCrown.q
q, // Intersection of light with the vegetation
d_i : TVectorC; // Inverse direction of light beam
function veg_path(const side: boolean) : double;
/// Path length through the vegetation
/// _p: Intersection of light with the crown ellipsoid (TCrown.q)
/// _d_i: Inverse direction of light beam
function pathlength( _p, _d_i : TVectorC ) : double;
protected
function alpha : double; override;
function beta : double; override;
function gamma : double; override;
public
r_gap, // Radius of gap
h_t, // Top of TVegetation
h_b : double; // Bottom of TVegetation
F : TLeafArea; // Leaf area density and angle classes
function Attenuation( _p, _d_i : TVectorS; stepPol, stepAz, id: integer): double;
constructor Create;
destructor Destroy; override;
end;
///The tree crown
TCrown = class (TQuadratic)
strict private
Extinction : TExtinction;
d_i, // Inverse direction of light beam
p : TVectorC; // Point for which to calculate pathlengths
function pathlength( _p, _d_i : TVectorC ) : double;
protected
function alpha : double; override;
function beta : double; override;
function gamma : double; override;
public
a,
b,
c : double; // Semi-axes
q : TVectorC; // Intersection of light with crown ellipsoid
// Necessary for TVegetation
F : TLeafArea; // Leaf area density and angle classes
function Attenuation( _p, _d_i : TVectorS; stepPol, stepAz, id: integer): double;
constructor Create;
destructor Destroy; override;
end;
function Deg2Rad (degrees : Double) : Double; //inline;
implementation
uses
SysUtils;
{ *** TExtinctionAz ********************************************************** }
constructor TExtinctionAz.Create;
begin
inherited;
x_min:=0;
x_max:=2*pi;
end;
function TExtinctionAz.fuGI(const xGI: Double): Double;
// xGI is psi_L
begin
d_L.psi:=xGI;
result:=abs(d_L*d_i);
end;
function TExtinctionAz.AzInt(const _d_L, _d_i: TVectorS; _step: integer): double;
begin
{$IFDEF TABLES}
// Check for known result
if (_d_i=d_i) then
if (Length(Ans)>=_step) then
begin
result:=ans[_step-1];
exit;
end;
{$ENDIF}
// * Actual math
d_i:=_d_i;
d_L:=_d_L;
result:=integrate;// Default: (0,2*pi)
{$IFDEF TABLES}
// Save result
SetLength(Ans,_step);
ans[_step-1]:=result;
{$ENDIF}
end;
{ *** TExtinction ************************************************************ }
constructor TExtinction.Create;
begin
inherited Create;
x_min:=0;
x_max:=pi/2;
ExtinctionAz:=TExtinctionAz.Create;
end;
destructor TExtinction.Destroy;
begin
FreeAndNil(ExtinctionAz);
inherited;
end;
function TExtinction.fuGI(const xGI: Double): Double;
// xGI is theta_L
begin
d_L.theta:=xGI;
result:=sin(xGI)*F.f_omega(xGI)*ExtinctionAz.AzInt(d_L, d_i, (AClass*GP)+step);
end;
function TExtinction.Kf(const _d_i : TVectorS; var _F : TLeafArea; stepPol, stepAz, id: integer): double;
var
I : Integer;
begin
{$IFDEF TABLES}
// Check for known result
// First check table dimensions
// Note: _F.id is 0-based, steps are 1-based.
if High(Kf_table[id,_F.id])<(stepPol-1) then
SetLength(Kf_table[id,_F.id],stepPol);
ASSERT(Length(Kf_table[id,_F.id])>=(stepPol));
if High(Kf_table[id,_F.id,stepPol-1])<(stepAz-1) then
SetLength(Kf_table[id,_F.id,stepPol-1],stepAz)
else
begin
// Known result
result:=Kf_table[id,_F.id,stepPol-1,stepAz-1];
exit;
end;
ASSERT(Length(Kf_table[id,_F.id,stepPol-1])>=(stepAz));
{$ENDIF}
// * Actual math
d_i:=_d_i;
d_L.r:=1; // Set length, angles are set by integrations
F:=_F;
// Should integrate over theta_L angles 0 to 1/2 pi
// Integration is divided over the angle classes, as the transition
// between these classes is not continuous.
result:=0;
for I := 0 to High(F.AngleClasses) do
begin
AClass:=I; // For loop control variable must be simple local variable
result:=result+_F.a_L*integrate((F.AngleClasses[AClass].Mid-(0.5*F.AngleClasses[AClass].Width)),(F.AngleClasses[AClass].Mid+(0.5*F.AngleClasses[AClass].Width)));
end;
_F:=F;
{$IFDEF TABLES}
// Save result
Kf_table[id,_F.id,stepPol-1,stepAz-1]:=result;
{$ENDIF}
end;
procedure TExtinction.GP_w(const Value: integer);
begin
// Set both own and ExtinctionAz's GP
inherited GP:=value;
ExtinctionAz.GP:=value;
end;
function TExtinction.number_N: integer;
begin
result:=inherited GP;
end;
{ *** TCrown ***************************************************************** }
function TCrown.alpha: double;
begin
result := sqr(d_i.x) / sqr(a) +
sqr(d_i.y) / sqr(b) +
sqr(d_i.z) / sqr(c);
end;
function TCrown.Attenuation(_p, _d_i: TVectorS; stepPol, stepAz, id: integer): double;
begin
result := - Extinction.Kf(_d_i,F, stepPol, stepAz, id) * pathlength(_p, _d_i);
end;
function TCrown.beta: double;
begin
result := 2 * d_i.x * p.x / sqr(a) +
2 * d_i.y * p.y / sqr(b) +
2 * d_i.z * p.z / sqr(c);
end;
constructor TCrown.Create;
begin
inherited;
F.id := 0;
Extinction := TExtinction.Create;
end;
destructor TCrown.Destroy;
begin
FreeAndNil(Extinction);
inherited;
end;
function TCrown.gamma: double;
begin
result := sqr(p.x) / sqr(a) +
sqr(p.y) / sqr(b) +
sqr(p.z) / sqr(c) - 1;
end;
function TCrown.pathlength( _p, _d_i : TVectorC ) : double;
begin
p := _p;
d_i := _d_i;
// Path length
result := Solve(true);
// Intersection with ellipsoid boundary
q := result * d_i + p;
end;
{ *** TVegetation ************************************************************ }
function TVegetationCircular.alpha: double;
begin
result := sqr(d_i.x)+sqr(d_i.y);
end;
function TVegetationCircular.Attenuation(_p, _d_i: TVectorS; stepPol, stepAz, id: integer): double;
begin
result := - Extinction.Kf(_d_i, F, stepPol, stepAz, id) * pathlength(_p, _d_i);
end;
function TVegetationCircular.beta: double;
begin
result := 2*p.x*d_i.x+2*p.y*d_i.y;
end;
constructor TVegetationCircular.Create;
begin
inherited;
F.id := 1;
Extinction := TExtinction.Create;
end;
destructor TVegetationCircular.Destroy;
begin
FreeAndNil(Extinction);
inherited;
end;
function TVegetationCircular.gamma: double;
begin
result := sqr(p.x)+sqr(p.y)-sqr(r_gap);
end;
function TVegetationCircular.veg_path(const side: boolean): double;
begin
if side then
result := (h_t-p.z)/d_i.z
else // Lower boundary: no need to calculate new p
result := (h_t-h_b)/ d_i.z;
end;
function TVegetationCircular.pathlength( _p, _d_i : TVectorC ) : double;
var
lambda, lambda2 : double;
begin
p := _p; // Define new p as the intersection with the ellipsoid
d_i := _d_i;
if p.z>=h_t then // Above top of veg
result := 0 // No intersection
else
if p.z>=h_b then // Between top and bottom of veg
if sqrt(sqr(p.x)+sqr(p.y))>=r_gap then // Joins veg
result := veg_path(true) // Calc from side, new p is q is old p
else // Does not join
begin
lambda := Solve(true);
// Point on boundary
q := p+lambda*d_i;
if q.z>=h_t then // No intersection
result := 0
else //calc from side
begin
// New p on boundary
p := q;
result := veg_path(true);
end;
end
else // Below veg
if sqrt(sqr(p.x)+sqr(p.y))>=r_gap then // Lower boundary
result := veg_path(false)
else // Lower or side boundary
begin
// Path length through gap to side boundary
lambda := Solve(true);
// Path length through gap to lower boundary
lambda2 := (h_b-p.z)/d_i.z;
if lambda>lambda2 then // Intersects with side boundary
begin
// Point on boundary
q := p+lambda*d_i;
if q.z>=h_t then // No intersection
result := 0
else
begin
// New p on boundary
p := q;
result := veg_path(true); // Calc from side, new p is q is old p
end;
end
else // Intersects with lower boundary
result := veg_path(false);
end;
end;
{ *** TLeafArea ************************************************************** }
procedure TLeafArea.Clear;
begin
SetLength(AngleClasses,0);
LADist := 0;
AzWidth := 2*pi;
end;
procedure TLeafArea.addclass(Mid, Width, fraction : Double);
var
I, J : Integer;
T : TAngleClass;
begin
// Add
SetLength(AngleClasses,Length(AngleClasses)+1);
AngleClasses[High(AngleClasses)].Mid := Mid;
AngleClasses[High(AngleClasses)].Width := Width;
AngleClasses[High(AngleClasses)].fraction := fraction;
// Sort
for I := 0 to High(AngleClasses) - 1 do
for J := I to High(AngleClasses) do
if ( AngleClasses[I].Mid > AngleClasses[J].Mid ) then
begin
// Swap entries
T := AngleClasses[I];
AngleClasses[I] := AngleClasses[J];
AngleClasses[J] := T;
end;
end;
procedure TLeafArea.addclassD(Mid, Width, fraction: Double);
begin
addclass(Deg2Rad(Mid),Deg2Rad(Width),fraction);
end;
procedure TLeafArea.fractionise;
var
I : Integer;
total : Double;
begin
total := 0;
for I := 0 to High(AngleClasses) do
total := total+AngleClasses[I].fraction;
for I := 0 to High(AngleClasses) do
AngleClasses[I].fraction := AngleClasses[I].fraction/total;
end;
function TLeafArea.f_omega(const theta_L: double): double;
var
I: Integer;
AClass: Integer;
Len : Integer;
begin
case LADist of
LACLASSES:
begin
AClass := -1; // -1 indicates nothing found
Len := High(AngleClasses);
// Find the corresponding class
for I := 0 to Len-1 do
// Check if Theta_L is smaller than upper class boundary
if theta_L < (AngleClasses[I].Mid+(0.5*AngleClasses[I].Width)) then
begin
AClass := I;
break;
end;
// Check if it's the upper class (inc. upper boundary)
if AClass=-1 then
if theta_L <= (AngleClasses[Len].Mid+(0.5*AngleClasses[Len].Width)) then
AClass := Len;
ASSERT( AClass <> -1 ); // Should have found a class
//result := (F*AngleClasses[AClass].fraction) /(2*pi*(AngleClasses[AClass].Width));
result := (F*AngleClasses[AClass].fraction) /(AzWidth*
( cos(AngleClasses[AClass].Mid-(0.5*AngleClasses[Len].Width))
-cos(AngleClasses[AClass].Mid+(0.5*AngleClasses[Len].Width))) );
end;
LACONTINUOUS:
begin
result := F*(2/pi)/(2*pi*sin(theta_L));
end;
LASPHERICAL:
begin
result := F*sin((pi/2)-theta_L)/(2*pi*sin(theta_L));
end;
else
begin
ASSERT(false);
result := 0;
end;
end;
end;
// *** Support function ********************************************************
function deg2rad (degrees : Double) : Double;
begin
result := degrees * (pi/180);
end;
end.
|
var x, y : integer;
function gcd(a, b : integer) : integer;
begin
if (a = 0) or (b = 0) then
gcd := a+b
else
if a > b then
gcd := gcd(a mod b, b)
else
gcd := gcd(b mod a, a);
end;
begin
readln(x);
readln(y);
writeln(gcd(x, y));
end.
|
Unit fat_inodes;
{ * Fat_Inodes : *
* *
* Unidad que realiza las funciones de manejo sobre los inodos-fat *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* *
* 27 / 07 / 2005 : Primera Version *
* *
***********************************************************************
}
interface
{$I ../../include/toro/procesos.inc}
{$I ../../include/toro/buffer.inc}
{$I ../../include/toro/mount.inc}
{$I ../../include/head/buffer.h}
{$I ../../include/head/asm.h}
{$I ../../include/head/inodes.h}
{$I ../../include/head/dcache.h}
{$I ../../include/head/open.h}
{$I ../../include/head/procesos.h}
{$I ../../include/head/scheduler.h}
{$I ../../include/head/read_write.h}
{$I ../../include/head/devices.h}
{$I ../../include/head/printk_.h}
{$I ../../include/head/malloc.h}
{$I ../../include/toro/fat12fs/fat12.inc}
{$I ../../include/head/fat12fs/misc.h}
{$I ../../include/head/super.h}
{$define Use_Tail }
{$define nodo_struct := pfat_inode_cache}
{$define next_nodo := next_ino_cache}
{$define prev_nodo := prev_ino_cache}
{$define Push_Inode := Push_Node }
{$define Pop_Inode := Pop_Node }
{define debug}
var fat_inode_op : inode_operations;
implementation
{$I ../../include/head/string.h}
{$I ../../include/head/list.h}
{$I ../../include/head/lock.h}
{ * procedimientos para quitar y poner los inodos en la tabla hash * }
procedure Inode_Hash_Push ( ino : pfat_inode_cache ) ;inline;
var tmp : dword ;
begin
tmp := ino^.ino mod Max_Inode_Hash ;
push_inode (ino,ino^.sb^.hash_ino^[tmp]);
end;
procedure Inode_Hash_Pop ( ino : pfat_inode_cache) ; inline ;
var tmp : dword ;
begin
tmp := ino^.ino mod Max_Inode_hash ;
pop_inode (ino,ino^.sb^.hash_ino^[tmp]);
end;
{ * Alloc_Inode_Fat : *
* *
* entry : Puntero a una estructura directorio fat *
* bh : puntero al buffer head del dir *
* *
* Esta funcion crea la abstraccion entre el vfs y la fat , cada *
* inodo de fatfs posee una entrada aqui , el campo nr_inodo es solo *
* un numero id. la cola ligada del cache de fat-inode *
* *
***********************************************************************
}
function alloc_inode_fat ( sb : psb_fat ; entry : pdirectory_entry ; bh : p_buffer_head ) :pfat_inode_cache;
var tmp : pfat_inode_cache ;
begin
tmp := kmalloc (sizeof(fat_inode_cache));
{no memoria}
if tmp = nil then exit(nil);
{se crea la estructura para el cache}
tmp^.dir_entry := entry ;
tmp^.bh := bh ;
tmp^.ino := entry^.entradafat ; {identificador de inodo}
tmp^.sb := sb ;
inode_hash_push (tmp);
exit(tmp);
end;
{ * quita de la cola ligada un buffer cache de inodo fat * }
procedure remove_inode_fat ( ino : pfat_inode_cache) ;
begin
inode_hash_pop (ino);
put_block (ino^.bh);
kfree_s (ino,sizeof(fat_inode_cache));
end;
{ * Realiza la busqueda de un inodo en el cache de inodos-fat * }
function find_in_cache ( ino : dword ; sb : p_super_block_t ) : pfat_inode_cache ;[public , alias :'FIND_IN_CACHE'];
var ino_cache : pfat_inode_cache ;
tmp : dword ;
sbfat : psb_fat ;
begin
{ubicacion en la tabla hash}
tmp := ino mod Max_Inode_hash ;
sbfat := sb^.driver_space ;
if sbfat^.hash_ino^[tmp]^.ino = ino then exit(sbfat^.hash_ino^[tmp]);
ino_cache := sbfat^.hash_ino^[tmp];
if ino_cache = nil then exit(nil);
{se buscara por toda la cola un inodo con ese id }
repeat
if ino_cache^.ino = ino then exit(ino_cache);
ino_cache := ino_cache^.next_ino_cache ;
until (ino_cache = sbfat^.hash_ino^[tmp]);
exit(nil);
end;
{ * Fat_inode_Lookup : *
* *
* ino : puntero a un inodo *
* dt : entrada buscada *
* *
* Realiza la busqueda de una entrada dentro de un inodo-fat dir *
* *
***********************************************************************
}
function fat_inode_lookup (ino : p_inode_t ; dt : p_dentry ) : p_dentry ;[public , alias :'FAT_INODE_LOOKUP'];
var blk , next_sector: dword ;
bh : p_buffer_head ;
pdir : pdirectory_entry ;
fat_entry : array[1..255] of char;
ino_fat , tmp: pfat_inode_cache;
label _load_ino , find_in_dir ;
begin
fillbyte(@fat_entry,sizeof(fat_entry),32);
memcopy (@dt^.name[1],@fat_entry,byte(dt^.name[0]));
{ esto puede traer problemas }
strupper (@fat_entry[1]);
{se busca en root???}
if ino^.ino = 1 then else goto find_in_dir ;
{se buscara por todo el root}
for blk := 19 to 32 do
begin
{este acceso es rapido puesto que estan en cache}
bh := get_block (ino^.mayor,ino^.menor,blk,512);
if bh = nil then exit(nil);
{se busca dentro del dir}
find_rootdir (bh,@fat_entry,pdir);
{se encontro la entrada??}
if pdir <> nil then goto _load_ino;
put_block (bh);
end;
exit (nil);
{la entrada se encuentra dentro de un dir}
find_in_dir :
tmp := find_in_cache (ino^.ino,ino^.sb) ;
{primer sector en el area de data}
next_sector := tmp^.dir_entry^.entradafat + 31 ;
while (next_sector <> last_sector) do
begin
bh := get_block (ino^.mayor,ino^.menor,next_sector,ino^.blksize);
if bh = nil then exit(nil);
{se realiza la busqueda dentro del dir}
if find_dir (bh,@fat_entry,pdir) = -1 then
begin
{el -1 indica fin de dir y 0 que no se encontro pero no se llego al fin}
{del dir}
put_block (bh);
exit(nil)
end else if pdir <> nil then goto _load_ino;
put_block (bh);
next_sector := get_sector_fat (ino^.sb,next_sector);
end;
exit(nil);
_load_ino :
{se crea la entrada en el cache de inodos-fat}
ino_fat := alloc_inode_fat (ino^.sb^.driver_space,pdir,bh);
{seguro no hay memoria!!!}
if ino_fat = nil then
begin
put_block (bh);
exit(nil);
end;
{se llama al kernel y se devuelve una estructura de inodos que ya}
{habia creado previamente}
dt^.ino := get_inode (ino^.sb,ino_fat^.ino) ;
exit(dt);
end;
{ * Fat_Read_Inode : *
* *
* ino : Puntero a un inodo *
* *
* Realiza la lectura de un inodo del cache de inodos-fat *
* *
************************************************************************
}
procedure fat_read_inode (ino : p_inode_t) ;[public , alias :'FAT_READ_INODE'];
var ino_cache : pfat_inode_cache ;
begin
{el inodo root es tratado de forma especial}
if ino^.ino = 1 then
begin
ino^.blocks := 14 ;
ino^.size := 14 * 512 ;
ino^.flags := I_RO or I_WO or I_XO;
ino^.mode := dt_dir ;
ino^.state := 0 ;
ino^.op := @fat_inode_op;
exit;
end;
{supuestamente un lookup ya cargo una entrada dir para ese inodo}
ino_cache := find_in_cache (ino^.ino , ino^.sb);
if ino_cache = nil then
begin
ino^.state := i_dirty ;
exit;
end;
{los archivos de sistema son especiales}
if (ino_cache^.dir_entry^.atributos and attr_system = attr_system ) then
begin
{ implementacion de los inodos de dispositivos }
{ dev de caracteres }
if (ino_cache^.dir_entry^.atributos and attr_chr = attr_chr) then
ino^.mode := dt_chr
{ dev de bloque }
else if (ino_cache^.dir_entry^.atributos and attr_blk = attr_blk) then
ino^.mode := dt_blk
else
begin
printk('/VVFS/n : inode desconocido \n',[]);
ino^.state := i_dirty ;
exit;
end;
ino^.rmenor := ino_cache^.dir_entry^.size and $ff ;
ino^.rmayor := (ino_cache^.dir_entry^.size shr 16 ) ;
ino^.size := 0 ;
ino^.blocks := 0 ;
ino^.op := nil;
ino^.state := 0 ;
ino^.atime := 0 ;
ino^.ctime := 0 ;
ino^.mtime := date_dos2unix (ino_cache^.dir_entry^.mtime , ino_cache^.dir_entry^.mdate);
ino^.dtime := 0 ;
{ proteccion al nodo de dev }
if (ino_cache^.dir_entry^.atributos and attr_read_only = attr_read_only ) then
ino^.flags := I_RO else ino^.flags := I_RO or I_WO or I_XO ;
exit
end
else
begin
{si hay es un archivo regular }
if (ino_cache^.dir_entry^.atributos and attr_read_only = attr_read_only ) then
ino^.flags := I_RO else ino^.flags := I_RO or I_WO or I_XO ;
{solo existen ficheros y directorio}
if (ino_cache^.dir_entry^.atributos and attr_directory = attr_directory) then
begin
ino^.mode := dt_dir;
ino^.size := 0 ;
{los dir. no poseen tamano}
ino^.blocks := 0 ;
end
else
begin
ino^.mode := dt_reg ;
ino^.size := ino_cache^.dir_entry^.size ;
ino^.blocks := ino^.size div ino^.blksize ;
end;
ino^.op := @fat_inode_op;
ino^.state := 0 ;
ino^.atime := 0 ;
ino^.ctime := 0 ;
ino^.mtime := date_dos2unix (ino_cache^.dir_entry^.mtime , ino_cache^.dir_entry^.mdate);
ino^.dtime := 0 ;
end;
end;
{ * Fat_Write_Inode : *
* *
* ino : puntero a un ino de vfs *
* *
* Realiza la escritura de un inodo de vfs a fat *
* *
***************************************************************************
}
procedure fat_write_inode ( ino : p_inode_t ) ; [public , alias :'FAT_WRITE_INODE'];
var tmp : pfat_inode_cache ;
begin
tmp := find_in_cache (ino^.ino , ino^.sb);
{grave error}
if tmp = nil then Panic ('/VVFS/n : fat12fs se hace write a un buffer no pedido \n');
{los atributos pueden ser modificados con chmod}
if (ino^.flags and I_RO = I_RO ) and (ino^.flags and I_WO <> I_WO) then
tmp^.dir_entry^.atributos := tmp^.dir_entry^.atributos or attr_read_only ;
{es un bloque sucio!!!!}
mark_buffer_dirty (tmp^.bh);
ino^.state := 0 ;
end;
{ * Fat_Delete_Inode : *
* *
* Funcion llamada por el sistema cuando deve quitar del buffer *
* un inodo , la memoria es liberada *
* *
***********************************************************************
}
procedure fat_delete_inode ( ino : p_inode_t ) ; [public ,alias : 'FAT_DELETE_INODE'];
var tmp : pfat_inode_cache ;
begin
tmp := find_in_cache (ino^.ino , ino^.sb) ;
{grave error}
if tmp = nil then Panic ('/VVFS/n : fat12fs se quita un buffer no pedido \n');
{se quita del sitema el inodo}
remove_inode_fat (tmp);
end;
{ * fat_put_inode : funcion no utilizada por fat * }
procedure fat_put_inode (ino : p_inode_t) ; [public , alias :'FAT_PUT_INODE'];
begin
{$IFDEF debug}
printk('/Vfat_put_inode/n : No implementado en fat12fs\n',[]);
{$ENDIF}
end;
{ * Fat_mkdir : *
* *
* ino : puntero a un inodo *
* dentry : solo posee el nombre del nuevo fichero *
* mode: proteccion , igual ino.flags *
* *
* Se encarga de crear un directorio *
* *
****************************************************************************
}
function fat_mkdir (ino : p_inode_t ; dentry : p_dentry ; mode : dword ) : dword ;[public , alias : 'FAT_MKDIR'];
var dent : directory_entry ;
pdir : pdirectory_entry ;
tmp,cluster,ret : dword ;
bh : p_buffer_head ;
inofat : pfat_inode_cache;
label _fault;
begin
if ino^.ino = 1 then inofat := nil else inofat := find_in_cache (ino^.ino , ino^.sb);
fillbyte(@dent.nombre[1],11,32);
fat_name (dentry^.name,@dent.nombre[1]);
for tmp := 1 to 10 do dent.reservado[tmp] := 0 ;
dent.atributos := attr_directory ;
if (mode and I_RO = I_RO ) and (mode and I_WO <> I_WO) then dent.atributos := dent.atributos or attr_read_only ;
cluster := get_free_cluster(ino^.sb) ;
if cluster = 0 then exit(-1) else dent.entradafat := cluster - 31 ;
dent.size := 0 ;
date_unix2dos (get_datetime,dent.mtime,dent.mdate);
if ino^.ino = 1 then ret := add_rootentry (ino,@dent) else ret:= add_direntry (ino,@dent);
if ret = -1 then goto _fault ;
{aca no puedo hacer una add_direntry para las entradas "." y ".." puesto }
{que deveria hacer un get_inode y este no resultaria}
bh := get_block (ino^.mayor,ino^.menor,cluster,ino^.blksize);
if bh = nil then goto _fault;
pdir := bh^.data ;
{directorios obligatorios}
dent.nombre := first_dir ;
pdir^ := dent ;
pdir += 1;
dent.nombre := second_dir ;
{es sobre el root!!!}
if inofat = nil then dent.entradafat := 0
else
begin
dent.entradafat := inofat^.dir_entry^.entradafat;
dent.mtime := inofat^.dir_entry^.mtime;
dent.mdate := inofat^.dir_entry^.mdate ;
end;
pdir^ := dent ;
{final del direc}
pdir += 1;
pdir^.nombre[1] := #0;
mark_buffer_dirty (bh);
put_block (bh);
exit(0);
{ah ocurrido un error grave}
_fault :
free_cluster (ino^.sb,cluster);
exit(-1);
end;
{ * Fat_mknod : Funcion no implementada en fat!!!!!!!!!!!! }
function fat_mknod (ino : p_inode_t ; dentry : p_dentry ; int , mayor , menor : dword ) : dword ; [public , alias :'FAT_MKNOD'];
var dent : directory_entry ;
ret , tmp : dword ;
inofat : pfat_inode_cache;
label _fault;
begin
{ el archivo es sobre root ? }
if ino^.ino = 1 then inofat := nil else inofat := find_in_cache (ino^.ino , ino^.sb);
fat_name (dentry^.name,@dent.nombre[1]);
for tmp := 1 to 10 do dent.reservado[tmp] := 0 ;
{ asi se implementan los archivos de dispositivos }
if (mayor < Nr_blk) then dent.atributos := attr_system or attr_blk
else if (mayor > Nr_blk) and ( mayor < Nr_chr) then dent.atributos := attr_system or attr_chr ;
{ la entrada fat contiene los numero de dev }
dent.size := (mayor shl 16) or menor ;
dent.entradafat := last_sector ;
{ proteccion al archivo }
if (int and I_RO = I_RO ) and (int and I_WO <> I_WO) then dent.atributos := dent.atributos or attr_read_only ;
date_unix2dos (get_datetime,dent.mtime,dent.mdate);
{ es agregada la entrada }
if ino^.ino = 1 then ret := add_rootentry (ino,@dent) else ret:= add_direntry (ino,@dent);
if ret = -1 then goto _fault ;
exit(0);
_fault :
exit(-1);
end;
{ * fat_rmdir : *
* *
* ino : puntero a un inodo *
* dentry : puntero a una dentry del cache *
* *
* funcion que elimina a un archivo ya se este directorio o archivo *
* *
***********************************************************************
}
function fat_rmdir ( ino : p_inode_t ; dentry : p_dentry ) : dword ;[public , alias : 'FAT_RMDIR'];
var tmpd,tmps : pfat_inode_cache ;
next_sector , prev_sector , count : dword ;
dir : pdirectory_entry ;
label _vacio , _novacio , _nada ;
begin
printk('/Vfat_rmdir/n : funcion no implementada \n',[]);
exit(-1);
{ siempre debe ser un dir ino!!! }
if ino^.mode <> dt_dir then exit(-1);
{ archivo que sera eliminado }
tmpd := find_in_cache (dentry^.ino^.ino , dentry^.ino^.sb) ;
{ se debera eliminar uno por uno cada archivos para que el dir sea libre }
if (dentry^.ino^.mode = dt_dir ) and (tmpd^.dir_entry^.entradafat <> last_sector) then
begin
printk('/Vfatfs/n : rmdir en directorio no vacio \n',[]);
exit(-1);
end;
{ comienzo del archivo }
next_sector := tmpd^.dir_entry^.entradafat + 31 ;
if (dentry^.ino^.mode <> dt_dir) then
begin
{ son liberados todos los clusters del archivo }
while (next_sector <> last_sector) do
begin
prev_sector := get_sector_fat (ino^.sb,next_sector);
free_cluster (ino^.sb,next_sector);
next_sector := prev_sector ;
end;
_nada :
dir := tmpd^.bh^.data ;
{sera una entrada libre en el dir}
tmpd^.dir_entry^.nombre[1] := #$e5 ;
{ debera ser escrito!! }
mark_buffer_dirty (tmpd^.bh);
{ el directorio de donde saco la entrada esta vacio ? }
for count := 1 to (512 div (sizeof(directory_entry))) do
begin
{ marca de fin de dir }
if (dir^.nombre[1] = #0 ) then goto _vacio
else if dir^.nombre[1] <> #$e5 then goto _novacio;
dir += 1;
end;
_vacio :
{ inodo donde reside el archivo eliminado }
tmps := find_in_cache (ino^.ino,ino^.sb);
{ el bloque donde esta la entrada del archivo eliminado }
{ es el ultimo sector del dir }
if get_sector_fat (dentry^.ino^.sb,tmpd^.bh^.bloque) = last_sector then
begin
{ si es el unico sector del dir y esta vacio!!}
if (tmps^.dir_entry^.entradafat + 31 = tmpd^.bh^.bloque) then
begin
free_cluster (ino^.sb,tmpd^.bh^.bloque);
tmps^.dir_entry^.entradafat := last_sector ;
mark_buffer_dirty (tmps^.bh);
end
else
begin
next_sector := tmps^.dir_entry^.entradafat + 31;
{ voy al anteultimo sector }
while (next_sector <> tmpd^.bh^.bloque) do
begin
prev_sector := next_sector ;
next_sector := get_sector_fat (ino^.sb,next_sector);
end;
put_sector_fat (dentry^.ino^.sb,prev_sector,last_sector) ;
free_cluster (ino^.sb,prev_sector) ;
end;
end;
_novacio :
remove_inode_fat (tmpd) ;
exit(0);
end
{ es un directorio }
else goto _nada ;
end;
function fat_rename (dentry , ndentry : p_dentry) : dword ; [public , alias : 'FAT_RENAME'];
begin
printk('/Vvfs/n : fat_rename funcion no implementada en fat\n',[]);
exit(-1);
end;
end.
|
unit XLSImportSYLK5;
{-
********************************************************************************
******* XLSReadWriteII V5.00 *******
******* *******
******* Copyright(C) 1999,2013 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressed or implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
{$H+}
{$R-}
{$C-}
{$I AxCompilers.inc}
{$I XLSRWII.inc}
interface
uses Classes, SysUtils,
Xc12Utils5, Xc12DataWorksheet5, Xc12Manager5,
XLSUtils5, XLSFormulaTypes5, XLSEncodeFmla5;
type TXLSImportSYLK = class(TObject)
protected
FManager: TXc12Manager;
FSheet : TXc12DataWorksheet;
FCol : integer;
FRow : integer;
FStream : TStream;
FCurrCol: integer;
FCurrRow: integer;
function StrToVal(const S: AxUCString; const AMin,AMax: integer; out AVal: integer): boolean;
function FirstChar(const S: AxUCString): AxUCChar; {$ifdef DELPHI_2006_OR_LATER} inline; {$endif}
function GetNextStr(var S: AxUCString): boolean;
function DoRef(var S: AxUCString): boolean;
function DoCell(const AText: AxUCString): boolean;
public
constructor Create(AManager: TXc12Manager);
procedure Read(AStream: TStream; const ASheet,ACol,ARow: integer);
end;
implementation
{ TXLSImportSYLK }
constructor TXLSImportSYLK.Create(AManager: TXc12Manager);
begin
FManager := AManager;
end;
function TXLSImportSYLK.DoCell(const AText: AxUCString): boolean;
var
S: AxUCString;
sVal: AxUCString;
Str: AxUCString;
Err: TXc12CellError;
Bool: boolean;
Num: double;
CT: TXLSCellType;
// Ptgs: PXLSPtgs;
// PtgsSz: integer;
begin
S := AText;
SplitAtChar(';',S);
Result := DoRef(S);
if not Result then
Exit;
CT := xctNone;
Err := errUnknown;
Bool := False;
sVal := SplitAtChar(';',S);
if Copy(sVal,1,1) = 'K' then begin
sVal := Copy(sVal,2,MAXINT);
Err := ErrorTextToCellError(sVAL);
if Err <> errUnknown then
CT := xctError
else begin
if Copy(sVal,1,1) = '"' then begin
StripQuotes(sVal);
Str := sVal;
CT := xctString;
end
else if sVal = 'TRUE' then begin
CT := xctBoolean;
Bool := True;
end
else if sVal = 'FALSE' then begin
CT := xctBoolean;
Bool := False;
end
else begin
if TryStrToFloat(sVal,Num) then
CT := xctFloat;
end;
end;
end;
Result := CT <> xctNone;
if not Result then
Exit;
// Formulas don't work. R1C1 mode must be implemented in Tokenizer/Encoder.
// if FirstChar(S) = 'E' then begin
// S := Copy(S,2,MAXINT);
//
// if XLSEncodeFormula(FManager,S,Ptgs,PtgsSz) then begin
// FSheet.Cells.FormulaHelper.Clear;
//
// FSheet.Cells.FormulaHelper.Style := XLS_STYLE_DEFAULT_XF;
//
// FSheet.Cells.FormulaHelper.Col := FCurrCol;
// FSheet.Cells.FormulaHelper.Row := FCurrRow;
//
// FSheet.Cells.FormulaHelper.Ptgs := Ptgs;
// FSheet.Cells.FormulaHelper.PtgsSize := PtgsSz;
//
// case CT of
// xctBoolean: FSheet.Cells.FormulaHelper.AsBoolean := Bool;
// xctError : FSheet.Cells.FormulaHelper.AsError := Err;
// xctString : FSheet.Cells.FormulaHelper.AsString := Str;
// xctFloat : FSheet.Cells.FormulaHelper.AsFloat := Num;
// end;
//
// FSheet.Cells.StoreFormula;
// end;
// end
// else begin F;P0;FG0C;SDLRBSM29;X41
case CT of
xctBoolean: FSheet.Cells.UpdateBoolean(FCurrCol,FCurrRow,Bool);
xctError : FSheet.Cells.UpdateError(FCurrCol,FCurrRow,Err);
xctString : FSheet.Cells.UpdateString(FCurrCol,FCurrRow,Str);
xctFloat : FSheet.Cells.UpdateFloat(FCurrCol,FCurrRow,Num);
end;
// end;
end;
function TXLSImportSYLK.DoRef(var S: AxUCString): boolean;
var
sRef: AxUCString;
begin
Result := False;
if FirstChar(S) = 'X' then begin
sRef := SplitAtChar(';',S);
Result := StrToVal(Copy(sRef,2,MAXINT),0,XLS_MAXCOL,FCurrCol);
if Result then begin
if FirstChar(S) = 'Y' then begin
sRef := SplitAtChar(';',S);
Result := StrToVal(Copy(sRef,2,MAXINT),0,XLS_MAXROW,FCurrRow);
end;
end;
end
else if FirstChar(S) = 'Y' then begin
sRef := SplitAtChar(';',S);
Result := StrToVal(Copy(sRef,2,MAXINT),0,XLS_MAXROW,FCurrRow);
if Result then begin
if FirstChar(S) = 'X' then begin
sRef := SplitAtChar(';',S);
Result := StrToVal(Copy(sRef,2,MAXINT),0,XLS_MAXCOL,FCurrCol);
end;
end;
end;
end;
function TXLSImportSYLK.FirstChar(const S: AxUCString): AxUCChar;
begin
if Length(S) > 0 then
Result := S[1]
else
Result := #0;
end;
function TXLSImportSYLK.GetNextStr(var S: AxUCString): boolean;
var
n: integer;
b: byte;
begin
n := 0;
while FStream.Read(b,SizeOf(byte)) = SizeOf(byte) do begin
Inc(n);
if n > Length(S) then
SetLength(S,Length(S) + 256);
if b = 13 then begin
FStream.Read(b,SizeOf(byte)); // 10
SetLength(S,n - 1);
S := Trim(S);
Result := Length(S) > 0;
Exit;
end;
S[n] := AxUCChar(b);
end;
SetLength(S,n);
Result := n > 0;
end;
procedure TXLSImportSYLK.Read(AStream: TStream; const ASheet,ACol,ARow: integer);
var
S: AxUCString;
w: word;
begin
FStream := AStream;
FSheet := FManager.Worksheets[ASheet];
FCol := ACol;
FRow := ARow;
FStream.Read(w,SizeOf(word));
// ID
if w <> $4449 then
Exit;
FStream.Seek(0,soFromBeginning);
while GetNextStr(S) do begin
case S[1] of
'C': DoCell(S);
end;
end;
end;
function TXLSImportSYLK.StrToVal(const S: AxUCString; const AMin, AMax: integer; out AVal: integer): boolean;
begin
Result := TryStrToInt(S,AVal);
if Result then
Result := (AVal >= AMin) and (AVal <= AMax);
end;
end.
|
unit ContaReceberDAO;
interface
uses
DBXCommon, SqlExpr, BaseDAO, ContaReceber, SysUtils;
type
TContaReceberDAO = class(TBaseDAO)
public
function List: TDBXReader;
function Insert(ContaReceber: TContaReceber): Boolean;
function Update(ContaReceber: TContaReceber): Boolean;
function Delete(ContaReceber: TContaReceber): Boolean;
function BaixarConta(ContaReceber: TContaReceber; Data: TDateTime; Valor: Currency; FormaPagamento: Integer): Boolean;
function Relatorio(DataInicial, DataFinal: TDateTime; ClienteCodigo: string; Situacao: Integer): TDBXReader;
end;
implementation
uses uSCPrincipal, StringUtils;
{ TClienteDAO }
function TContaReceberDAO.List: TDBXReader;
begin
PrepareCommand;
FComm.Text := 'SELECT C.ID, C.CLIENTE_CODIGO, L.NOME, C.NOME_CLIENTE_AVULSO, C.VENCIMENTO, C.VALOR, C.OBSERVACOES, C.BAIXADA, C.RESTANTE '+
'FROM CONTAS_RECEBER C '+
'LEFT JOIN CLIENTES L ON L.CODIGO = C.CLIENTE_CODIGO '+
'WHERE C.BAIXADA = 0 '+
'ORDER BY C.VENCIMENTO, C.CLIENTE_CODIGO';
Result := FComm.ExecuteQuery;
end;
function TContaReceberDAO.Relatorio(DataInicial, DataFinal: TDateTime; ClienteCodigo: string; Situacao: Integer): TDBXReader;
begin
PrepareCommand;
FComm.Text := 'SELECT C.ID, C.CLIENTE_CODIGO, L.NOME, C.NOME_CLIENTE_AVULSO, C.VENCIMENTO, C.VALOR, C.OBSERVACOES, C.BAIXADA, C.RESTANTE '+
'FROM CONTAS_RECEBER C '+
'LEFT JOIN CLIENTES L ON L.CODIGO = C.CLIENTE_CODIGO '+
'WHERE C.ID <> 0 ';
if DataInicial <> 0 then
FComm.Text := FComm.Text + 'AND CONVERT(CHAR(8), C.VENCIMENTO, 112) >= '+FormatDateTime('yyyymmdd', DataInicial)+' ';
if DataFinal <> 0 then
FComm.Text := FComm.Text + 'AND CONVERT(CHAR(8), C.VENCIMENTO, 112) <= '+FormatDateTime('yyyymmdd', DataFinal)+' ';
if ClienteCodigo <> '' then
FComm.Text := FComm.Text + 'AND C.CLIENTE_CODIGO = '''+ClienteCodigo+''' ';
if Situacao = 1 then
FComm.Text := FComm.Text + 'AND C.BAIXADA = 0 ';
if Situacao = 2 then
FComm.Text := FComm.Text + 'AND C.BAIXADA = 1 ';
FComm.Text := FComm.Text + 'ORDER BY C.VENCIMENTO, C.CLIENTE_CODIGO';
Result := FComm.ExecuteQuery;
end;
function TContaReceberDAO.Insert(ContaReceber: TContaReceber): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
if ContaReceber.Cliente <> nil then
begin
query.SQL.Text := 'INSERT INTO CONTAS_RECEBER (CLIENTE_CODIGO, VENCIMENTO, VALOR, OBSERVACOES, BAIXADA, RESTANTE) VALUES (:CLIENTE_CODIGO, :VENCIMENTO, :VALOR, :OBSERVACOES, :BAIXADA, :RESTANTE)';
query.ParamByName('CLIENTE_CODIGO').AsString := ContaReceber.Cliente.Codigo;
end
else
begin
query.SQL.Text := 'INSERT INTO CONTAS_RECEBER (NOME_CLIENTE_AVULSO, VENCIMENTO, VALOR, OBSERVACOES, BAIXADA, RESTANTE) VALUES (:NOME_CLIENTE_AVULSO, :VENCIMENTO, :VALOR, :OBSERVACOES, :BAIXADA, :RESTANTE)';
query.ParamByName('NOME_CLIENTE_AVULSO').AsString := ContaReceber.NomeClienteAvulso;
end;
query.ParamByName('VENCIMENTO').AsDateTime := ContaReceber.Vencimento;
query.ParamByName('VALOR').AsCurrency := ContaReceber.Valor;
query.ParamByName('OBSERVACOES').AsString := ContaReceber.Observacoes;
query.ParamByName('BAIXADA').AsBoolean := ContaReceber.Baixada;
query.ParamByName('RESTANTE').AsCurrency := ContaReceber.Valor;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TContaReceberDAO.Update(ContaReceber: TContaReceber): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
if ContaReceber.Cliente <> nil then
begin
query.SQL.Text := 'UPDATE CONTAS_RECEBER SET CLIENTE_CODIGO = :CLIENTE_CODIGO, VENCIMENTO = :VENCIMENTO, VALOR = :VALOR, OBSERVACOES = :OBSERVACOES, BAIXADA = :BAIXADA '+
'WHERE ID = :ID';
query.ParamByName('CLIENTE_CODIGO').AsString := ContaReceber.Cliente.Codigo;
end
else
begin
query.SQL.Text := 'UPDATE CONTAS_RECEBER SET NOME_CLIENTE_AVULSO = :NOME_CLIENTE_AVULSO, VENCIMENTO = :VENCIMENTO, VALOR = :VALOR, OBSERVACOES = :OBSERVACOES, BAIXADA = :BAIXADA '+
'WHERE ID = :ID';
query.ParamByName('NOME_CLIENTE_AVULSO').AsString := ContaReceber.NomeClienteAvulso;
end;
//
query.ParamByName('VENCIMENTO').AsDateTime := ContaReceber.Vencimento;
query.ParamByName('VALOR').AsCurrency := ContaReceber.Valor;
query.ParamByName('OBSERVACOES').AsString := ContaReceber.Observacoes;
query.ParamByName('BAIXADA').AsBoolean := ContaReceber.Baixada;
query.ParamByName('ID').AsInteger := ContaReceber.Id;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TContaReceberDAO.BaixarConta(ContaReceber: TContaReceber; Data: TDateTime; Valor: Currency; FormaPagamento: Integer): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'INSERT INTO BAIXAS_CONTA_RECEBER (CONTA_RECEBER_ID, DATA, VALOR, FORMA_PAGAMENTO) VALUES (:CONTA_RECEBER_ID, :DATA, :VALOR, :FORMA_PAGAMENTO)';
query.ParamByName('CONTA_RECEBER_ID').AsInteger := ContaReceber.Id;
query.ParamByName('DATA').AsDateTime := Data;
query.ParamByName('VALOR').AsCurrency := Valor;
query.ParamByName('FORMA_PAGAMENTO').AsInteger := FormaPagamento;
query.ExecSQL;
query.SQL.Text := 'SELECT SUM(VALOR) AS TOTAL_PAGO FROM BAIXAS_CONTA_RECEBER WHERE CONTA_RECEBER_ID = :ID';
query.ParamByName('ID').AsInteger := ContaReceber.Id;
query.Open;
Result := False;
if ContaReceber.Valor <= query.FieldByName('TOTAL_PAGO').AsCurrency then
begin
query.SQL.Text := 'UPDATE CONTAS_RECEBER SET BAIXADA = 1 WHERE ID = :ID';
query.ParamByName('ID').AsInteger := ContaReceber.Id;
query.ExecSQL;
Result := True;
end
else
begin
query.SQL.Text := 'UPDATE CONTAS_RECEBER SET RESTANTE = :VALOR WHERE ID = :ID';
query.ParamByName('VALOR').AsCurrency := ContaReceber.Valor - Valor;
query.ParamByName('ID').AsInteger := ContaReceber.Id;
query.ExecSQL;
end;
finally
query.Free;
end;
end;
function TContaReceberDAO.Delete(ContaReceber: TContaReceber): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'DELETE FROM CONTAS_RECEBER WHERE ID = :ID';
//
query.ParamByName('ID').AsInteger := ContaReceber.Id;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit uParseTree;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Contnrs,
uModelEntity;
type
{
Baseclass for a parsetree
}
TParseTree = class(TObject)
private
FOwner: TParseTree;
FEntity: TModelEntity;
FChildren: TObjectList;
FModelEntity: TModelEntity;
FIsImportant: Boolean; // If false the node is 'whitespace'
function GetChildCount: Integer;
function GetChildren(i: Integer): TParseTree;
procedure SetChildren(i: Integer; const Value: TParseTree);
procedure SetOwner(AChild: TParseTree);
public
constructor Create(AOwner: TPArseTree; AEntity: TModelEntity;
IsImportant: Boolean = False);
destructor Destroy; override;
function Add(NewChild: TParseTree): Integer; overload;
procedure Insert(index: Integer; NewChild: TParseTree); overload;
property Parent: TParseTree read FOwner write FOwner;
property ModelEntity: TModelEntity read FModelEntity write FModelEntity;
property Important: Boolean read FIsImportant write FIsImportant;
property ChildCount: Integer read GetChildCount;
property Children[i: Integer]: TParseTree read GetChildren write SetChildren;
end;
TDelphiParseTree = class(TParseTree)
private
FCode: string; // Holds the source att this node
public
constructor Create(AOwner: TDelphiParseTree; AName: string; AEntity: TModelEntity;
IsImportant: Boolean = False);
destructor Destroy; override;
procedure SaveToFile(Name: string);
function IndentAfter: Boolean;
function UndentAfter: Boolean;
function Add(NewCode: string; NewEntity: TModelEntity; IsImportant: Boolean = False): TDelphiParseTree; overload;
procedure Insert(index: Integer; NewCode: string; NewEntity: TModelEntity); overload;
property Code: string read FCode write FCode;
end;
implementation
{ TParseTree }
function TParseTree.Add(NewChild: TParseTree): Integer;
begin
if Self.ClassType <> NewChild.ClassType then
raise Exception.Create('Parsetree can only hold ' + Self.ClassName);
SetOwner(NewChild);
Result := FChildren.Add(NewChild);
end;
constructor TParseTree.Create(AOwner: TPArseTree; AEntity: TModelEntity; IsImportant: Boolean);
begin
inherited Create;
FOwner := AOwner;
FEntity := AEntity;
FIsImportant := IsImportant;
FChildren := TObjectList.Create(True);
end;
destructor TParseTree.Destroy;
begin
inherited;
FreeAndNil(FChildren);
end;
function TParseTree.GetChildCount: Integer;
begin
Result := FChildren.Count;
end;
function TParseTree.GetChildren(i: Integer): TParseTree;
begin
Result := FChildren.Items[i] as TParseTree;
end;
procedure TParseTree.Insert(index: Integer; NewChild: TParseTree);
begin
if Self.ClassType <> NewChild.ClassType then
raise Exception.Create('Parsetree can only hold ' + Self.ClassName);
SetOwner(NewChild);
FChildren.Insert(index, NewChild);
end;
procedure TParseTree.SetChildren(i: Integer; const Value: TParseTree);
begin
if Self.ClassType <> Value.ClassType then
raise Exception.Create('Parsetree can only hold ' + Self.ClassName);
SetOwner(Value);
FChildren.Items[i] := Value;
end;
procedure TParseTree.SetOwner(AChild: TParseTree);
begin
if (AChild.FOwner <> Self) and (AChild.FOwner <> nil) then
FOwner.FChildren.Extract(AChild);
AChild.FOwner := Self;
end;
{ TDelphiParseTree }
function TDelphiParseTree.Add(NewCode: string; NewEntity: TModelEntity; IsImportant: Boolean): TDelphiParseTree;
begin
Result := TDelphiParseTree.Create(nil, NewCode, NewEntity, IsImportant);
inherited Add(Result);
end;
constructor TDelphiParseTree.Create(AOwner: TDelphiParseTree; AName: string; AEntity: TModelEntity;
IsImportant: Boolean);
begin
inherited Create(AOwner, AEntity, IsImportant);
FCode := AName;
end;
destructor TDelphiParseTree.Destroy;
begin
inherited;
end;
function TDelphiParseTree.IndentAfter: Boolean;
var
i: Integer;
begin
Result := False;
if Assigned(FOwner) then
begin
i := FOwner.FChildren.IndexOf(Self);
while (FOwner.FChildren.Count - 1) > i do // Add succeding childs
Add(FOwner.FChildren.Items[i + 1] as TDelphiParseTree); // as children to Self
end;
end;
function TDelphiParseTree.UndentAfter: Boolean;
var
i: Integer;
Target, c: TDelphiParseTree;
begin
Result := False;
if Assigned(FOwner) and Assigned(FOwner.FOwner) then
begin
Target := FOwner.FOwner as TDelphiParseTree;
i := FOwner.FChildren.IndexOf(Self);
while (FOwner.FChildren.Count - 1) > i do // Move children to the level above.
begin
c := FOwner.FChildren.Items[i + 1] as TDelphiParseTree;
FOwner.FChildren.Extract(c);
c.FOwner := nil;
Target.Add(c);
end;
Result := True;
end;
end;
procedure TDelphiParseTree.Insert(index: Integer; NewCode: string; NewEntity: TModelEntity);
begin
inherited Insert(index, TDelphiParseTree.Create(Self, NewCode, NewEntity));
end;
procedure TDelphiParseTree.SaveToFile(Name: string);
var
sl: TStringList;
procedure Build(it: TDelphiParseTree; ind: Integer);
var
i: Integer;
begin
sl.Add(StringOfChar('-', ind) + it.code);
for i := 0 to it.FChildren.Count - 1 do
Build(it.FChildren.Items[i] as TDelphiParseTree, ind + 1);
end;
begin
sl := TStringList.Create;
try
Build(Self, 0);
sl.SaveToFile(Name);
finally
FreeAndNil(sl);
end;
end;
end.
|
unit DPM.Controls.ButtonedEdit;
interface
uses
System.Classes,
Vcl.ExtCtrls,
DPM.Controls.AutoComplete;
//source : https://stackoverflow.com/questions/11615336/is-it-possible-to-add-a-history-list-dropdown-to-delphis-tbuttonededit
type
TACOption = (acAutoAppend, acAutoSuggest, {acUseArrowKey, } acSearch, acFilterPrefixes, acUseTab, acRtlReading, acWordFilter, acNoPrefixFiltering);
TACOptions = set of TACOption;
TACSource = (acsList, acsHistory, acsMRU, acsShell);
TButtonedEdit = class(Vcl.ExtCtrls.TButtonedEdit)
private
FACList : IDelphiEnumString;
FAutoComplete : IAutoComplete;
FACEnabled : boolean;
FACOptions : TACOptions;
FACSource : TACSource;
//history
function GetACStrings : TStringList;
procedure SetACEnabled(const Value : boolean);
procedure SetACOptions(const Value : TACOptions);
procedure SetACSource(const Value : TACSource);
procedure SetACStrings(const Value : TStringList);
protected
procedure CreateWnd; override;
procedure DestroyWnd; override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
published
property ACEnabled : boolean read FACEnabled write SetACEnabled;
property ACOptions : TACOptions read FACOptions write SetACOptions;
property ACSource : TACSource read FACSource write SetACSource;
property ACStrings : TStringList read GetACStrings write SetACStrings;
end;
implementation
uses
System.SysUtils,
System.DateUtils,
WinApi.Windows,
Winapi.ShlObj,
System.Win.ComObj,
WinApi.ActiveX;
constructor TButtonedEdit.Create(AOwner : TComponent);
begin
inherited;
FACList := TEnumString.Create;
FACEnabled := True;
FACOptions := [acAutoAppend, acAutoSuggest{, acUseArrowKey}];
end;
procedure TButtonedEdit.CreateWnd;
var
Dummy : IUnknown;
Strings : IEnumString;
begin
inherited;
if HandleAllocated then
begin
try
Dummy := CreateComObject(CLSID_AutoComplete);
if (Dummy <> nil) and (Dummy.QueryInterface(IID_IAutoComplete, FAutoComplete) = S_OK) then
begin
case FACSource of
acsHistory : Strings := CreateComObject(CLSID_ACLHistory) as IEnumString;
acsMRU : Strings := CreateComObject(CLSID_ACLMRU) as IEnumString;
acsShell : Strings := CreateComObject(CLSID_ACListISF) as IEnumString;
else
Strings := FACList as IEnumString;
end;
if S_OK = FAutoComplete.Init(Handle, Strings, nil, nil) then
begin
SetACEnabled(FACEnabled);
SetACOptions(FACOptions);
end;
end;
except
//CLSID_IAutoComplete is not available
end;
end;
end;
destructor TButtonedEdit.Destroy;
begin
FACList := nil;
inherited;
end;
procedure TButtonedEdit.DestroyWnd;
begin
if (FAutoComplete <> nil) then
begin
FAutoComplete.Enable(False);
FAutoComplete := nil;
end;
inherited;
end;
function TButtonedEdit.GetACStrings : TStringList;
begin
Result := FACList.Strings;
end;
procedure TButtonedEdit.SetACEnabled(const Value : Boolean);
begin
if (FAutoComplete <> nil) then
begin
FAutoComplete.Enable(FACEnabled);
end;
FACEnabled := Value;
end;
procedure TButtonedEdit.SetACOptions(const Value : TACOptions);
const
Options : array[TACOption] of integer = (ACO_AUTOAPPEND,
ACO_AUTOSUGGEST,
//ACO_UPDOWNKEYDROPSLIST,
ACO_SEARCH,
ACO_FILTERPREFIXES,
ACO_USETAB,
ACO_RTLREADING,
ACO_WORD_FILTER,
ACO_NOPREFIXFILTERING);
var
Option : TACOption;
Opt : DWORD;
AC2 : IAutoComplete2;
begin
if (FAutoComplete <> nil) then
begin
if S_OK = FAutoComplete.QueryInterface(IID_IAutoComplete2, AC2) then
begin
Opt := ACO_NONE;
for Option := Low(Options) to High(Options) do
begin
if (Option in FACOptions) then
Opt := Opt or DWORD(Options[Option]);
end;
AC2.SetOptions(Opt);
end;
end;
FACOptions := Value;
end;
procedure TButtonedEdit.SetACSource(const Value : TACSource);
begin
if FACSource <> Value then
begin
FACSource := Value;
RecreateWnd;
end;
end;
procedure TButtonedEdit.SetACStrings(const Value : TStringList);
begin
if Value <> FACList.Strings then
FACList.Strings.Assign(Value);
end;
end.
|
program WhacAMole;
uses
SwinGame, sgTypes, sgUserInterface, SysUtils;
const
// numOfMole = 30;
// Level = 10;
NUM_HOLES = 9;
TIME_PER_ROUND = 120;
MOLE_WIDTH = 245;
MOLE_HEIGHT = 163;
type
GameState = (InMenu, InGame);
HoleState = (Empty, Mole, MoleUp, MoleDown, Wack, Bam);
HoleData = record
moleSprite: Sprite;
kapow: Sprite;
state: HoleState;
end;
HoleTimeData = record
showAt: Integer;
hole: ^HoleData;
end;
GameData = record
state: GameState;
timeComplete: Integer;
score: Integer;
molesRemaining: Integer;
level: Integer;
lives: Integer;
hole: array [0..NUM_HOLES - 1] of HoleData;
holePlan: array of HoleTimeData; // hole plan lays out the order the holes will go in
planIdx: Integer;
roundTime: Integer; // number of milliseconds in the round
timeFactor: Single;
bonus: Integer;
lastUpdateTime: Integer; // time of last update
// Resources
scoreFont: Font;
background: Bitmap;
fullBar: Bitmap;
emptyBar: Bitmap;
lifeBitmap: Bitmap;
gTimer: Timer;
end;
procedure SetupLevel(var data: GameData);
const
START_MOLES = 9;
MIN_TIME = 5000;
START_TIME = 15200;
var
molePct: Single;
i, j: Integer;
avgTimeBetween: Integer;
holeFree: array [0 .. NUM_HOLES - 1] of Integer;
offset: Integer;
timeAccum: Integer;
begin
StopTimer(data.gTimer);
data.bonus := 0;
data.lastUpdateTime := 0;
data.planIdx := 0;
if data.lives < 0 then
begin
data.level := 1;
data.lives := 3;
end;
if data.level = 1 then data.score := 0; // reset score at level 1
data.molesRemaining := START_MOLES + (data.level mod 10); // one more every level
data.roundTime := START_TIME; // - (2500 * data.level div 10);
//if data.roundTime < MIN_TIME then data.roundTime := MIN_TIME;
data.timeFactor := 1 + (data.level div 10);
// generate hole plan
molePct := 2.0 - (1.0 * (((data.level - 1) mod 10) / 10)); // drops to 100% every 10 levels
SetLength(data.holePlan, Round(molePct * data.molesRemaining));
WriteLn('Len ', Length(data.holePlan), ' and ', Length(holeFree));
avgTimeBetween := data.roundTime div Length(data.holePlan);
timeAccum := 0;
for i := 0 to High(holeFree) do
begin
holeFree[i] := -1;
WriteLn('i ', i);
end;
for i := 0 to High(data.holePlan) do
begin
data.holePlan[i].showAt := i * avgTimeBetween;
offset := Rnd(NUM_HOLES);
for j := 0 to High(holeFree) do
begin
if holeFree[(j + offset) mod NUM_HOLES] < data.holePlan[i].showAt then break;
if j = High(holeFree) then WriteLn('CANT FIND');
end;
WriteLn('At ', data.holePlan[i].showAt, ' use ', i, ' = ', (j + offset) mod NUM_HOLES);
data.holePlan[i].hole := @data.hole[(j + offset) mod NUM_HOLES];
holeFree[(j + offset) mod NUM_HOLES] := Round(data.holePlan[i].showAt + (500 * 12));
end;
// reset holes
for i := 0 to NUM_HOLES - 1 do
begin
data.hole[i].state := Empty;
end;
StartTimer(data.gTimer);
end;
procedure EndLevel(var data: GameData);
begin
if data.molesRemaining > 0 then
begin
data.lives -= 1;
end
else
data.level += 1;
data.state := InMenu;
end;
procedure DisplayScore(score: Integer; fnt: Font);
var
scoreTxt: String;
const
TXT_X = 277;
TXT_Y = 152;
begin
scoreTxt := IntToStr(score);
DrawText(scoreTxt, ColorBlack, fnt, TXT_X - TextWidth(fnt, scoreTxt), TXT_Y);
end;
procedure DisplayMolesRemaining(moleRemain: Integer; fnt: Font);
var
moleTxt: String;
const
MOLE_TXT_X = 448;
MOLE_TXT_Y = 152;
begin
moleTxt := IntToStr(moleRemain);
DrawText(moleTxt, ColorBlack, fnt, MOLE_TXT_X - TextWidth(fnt, moleTxt), MOLE_TXT_Y);
end;
procedure DisplayCurrentLevel(level: Integer; fnt: Font);
var
lvlTxt: String;
const
LEVEL_TXT_X = 720;
LEVEL_TXT_Y = 152;
begin
lvlTxt := IntToStr(level);
DrawText(lvlTxt, ColorBlack, fnt, LEVEL_TXT_X - TextWidth(fnt, lvlTxt), LEVEL_TXT_Y);
end;
procedure DrawLife(const gData : GameData);
var
i: Integer;
const
H_GAP = 38;
LIFE_X = 73;
LIFE_Y = 89;
begin
for i := 0 to gData.lives - 1 do
begin
DrawBitmap(gData.lifeBitmap, LIFE_X + H_GAP * i, LIFE_Y);
end;
end;
procedure DrawBackGroundImage();
begin
DrawBitmap ('bgImage', 0, 0);
end;
procedure DrawProgressBar(var gData : GameData);
var
rect: Rectangle;
const
BAR_HEIGHT = 279;
BAR_WIDTH = 34;
BAR_X = 32;
BAR_Y = 439;
begin
rect := RectangleFrom(0, 0, BAR_WIDTH, round(TimerTicks(gData.gTimer) / gData.roundTime * BAR_HEIGHT));
DrawBitmap(gData.fullBar, BAR_X, BAR_Y);
DrawBitmap(gData.emptyBar, BAR_X, BAR_Y, OptionPartBmp(rect));
end;
procedure InitMolesSprite(var gData : GameData);
var
i, y, xM, vGap, hGap : Integer;
begin
xM := 260;
hGap := 0;
vGap := 0;
y := 252;
for i := 0 to NUM_HOLES - 1 do
begin
gData.hole[i].moleSprite := CreateSprite(BitmapNamed('WhacAMole'), AnimationScriptNamed('WhacAMole_temp'));
gData.hole[i].kapow := CreateSprite(BitmapNamed('Kapow'), AnimationScriptNamed('Kapow_temp'));
// if i = 3 then
// begin
// hGap := 0;
// vGap := 170;
// end;
// if i = 6 then
// begin
// hGap := 0;
// vGap := 333;
// end;
hGap := (i mod 3) * 250;
vGap := (i div 3) * 167;
SpriteSetX(gData.hole[i].moleSprite, xM+hGap);
SpriteSetY(gData.hole[i].moleSprite, y+vGap);
SpriteSetX(gData.hole[i].kapow, xM+hGap);
SpriteSetY(gData.hole[i].kapow, y+vGap);
gData.hole[i].state := Empty;
// hGap += 250;
end;
end;
procedure DoHoleWhacked(var gData: GameData; var hole: HoleData);
begin
if gData.molesRemaining > 0 then
gData.molesRemaining -= 1;
// Update bonus and score
gData.bonus += 1;
gData.Score += gData.bonus;
// Update hole state and animations
hole.state := Bam;
SpriteStartAnimation(hole.moleSprite, 'Hide');
SpriteStartAnimation(hole.kapow, 'Kapow');
end;
procedure DoMoleAction(var hole: HoleData);
begin
// If the animation has ended...
if SpriteAnimationHasEnded(hole.moleSprite) then
begin
// Start going down...
hole.state := MoleDown;
SpriteStartAnimation(hole.moleSprite, 'MoleDown');
end;
end;
procedure ShowNextMole(var data: GameData);
var
hole: ^HoleData;
begin
if data.planIdx >= Length(data.holePlan) then exit;
if TimerTicks(data.gTimer) >= data.holePlan[data.planIdx].showAt then
begin
hole := data.holePlan[data.planIdx].hole;
if not (hole^.state = Empty) then WriteLn('Hole not empty!');
hole^.state := MoleUp;
SpriteStartAnimation(hole^.moleSprite, 'MoleUp', true);
data.planIdx += 1;
end;
end;
procedure PlayGame(var gData : GameData);
var
i : Integer;
pct: Single;
timePassed: Integer;
begin
timePassed := TimerTicks(gData.gTimer) - gData.lastUpdateTime;
gData.lastUpdateTime := TimerTicks(gData.gTimer);
pct := timePassed / (500 * gData.timeFactor);
ShowNextMole(gData);
for i := 0 to NUM_HOLES - 1 do
begin
UpdateSprite(gData.hole[i].moleSprite, pct);
UpdateSprite(gData.hole[i].kapow, pct);
case gData.hole[i].state of
MoleUp: if SpriteAnimationHasEnded(gData.hole[i].moleSprite) then gData.hole[i].state := Mole;
MoleDown: if SpriteAnimationHasEnded(gData.hole[i].moleSprite) then gData.hole[i].state := Empty;
Mole: DoMoleAction(gData.hole[i]);
Wack: DoHoleWhacked(gData, gData.hole[i]);
Bam:
begin
if SpriteAnimationHasEnded(gData.hole[i].kapow) then gData.hole[i].state := Empty;
end;
end;
end;
if TimerTicks(gData.gTimer) >= gData.roundTime then
begin
EndLevel(gData);
gData.state := InMenu;
SetupLevel(gData);
end
end;
procedure DrawMoles(const gData: GameData);
var
i: Integer;
begin
for i := 0 to NUM_HOLES - 1 do
begin
if gData.hole[i].state = Bam then
DrawSprite(gData.hole[i].kapow)
else
DrawSprite(gData.hole[i].moleSprite);
end;
end;
procedure DrawGame(var gData : GameData);
begin
DrawBitmap(gData.background, 0, 0);
DrawLife(gData);
DrawProgressBar(gData);
DisplayScore(gData.Score, gData.scoreFont);
DisplayMolesRemaining(gData.molesRemaining, gData.scoreFont);
DisplayCurrentLevel(gData.Level, gData.scoreFont);
DrawMoles(gData);
DrawFramerate(0,0);
RefreshScreen();
end;
procedure HandleInput(var gData : GameData);
var
mousePos : Point2D;
i : Integer;
begin
if MouseClicked(LeftButton) then
begin
mousePos := MousePosition();
for i := 0 to NUM_HOLES - 1 do
begin
if SpriteOnScreenAt(gData.hole[i].moleSprite, mousePos) then
begin
if not (gData.hole[i].state = Bam) then
begin
gData.hole[i].state := Wack;
exit; // skip resetting bonus
end;
break; // exit loop, resetting bonus as if miss
end;
end;
// Missed holes...
gData.bonus := 0;
end;
end;
procedure InitGame(var gData : GameData);
begin
gData.state := InMenu;
gData.score := 0;
gData.lives := 3;
gData.level := 1;
gData.timeComplete := 0;
InitMolesSprite(gData);
end;
procedure LoadResources(var data: GameData);
begin
LoadResourceBundle('WhacAMoleBundle.txt');
InitGame(data);
data.background := BitmapNamed('bgImage');
data.emptyBar := BitmapNamed('progressEmpty');
data.fullBar := BitmapNamed('progressFull');
data.lifeBitmap := BitmapNamed('life');
data.scoreFont := FontNamed('scoreFont');
data.gTimer := CreateTimer();
// LoadSoundEffect('comedy_boing.ogg');
end;
procedure Main();
var
gData : GameData;
i: Integer;
begin
OpenAudio();
OpenGraphicsWindow('Whack a Mole', 1024, 768);
LoadDefaultColors();
LoadResources(gData);
PlayMusic('WhacMusic');
SetupLevel(gData);
repeat // The game loop...
ProcessEvents();
HandleInput(gData);
PlayGame(gData);
DrawGame(gData);
until WindowCloseRequested();
ReleaseAllResources();
end;
begin
Main();
end. |
unit PestControlFileWriterUnit;
interface
uses
CustomModflowWriterUnit, System.SysUtils, PestObsUnit, GoPhastTypes,
PhastModelUnit;
type
TPestControlFileWriter = class(TCustomFileWriter)
private
FNameOfFile: string;
FUsedObservations: TObservationList;
procedure WriteFirstLine;
procedure WriteSectionHeader(const SectionID: String);
procedure WriteControlSection;
procedure WriteSensitivityReuse;
procedure WriteSingularValueDecomposition;
procedure WriteLsqr;
procedure WriteAutomaticUserIntervention;
procedure WriteSVD_Assist;
procedure WriteParameterGroups;
procedure WriteParameters;
procedure WriteObservationGroups;
procedure WriteObservations;
procedure WriteDerivatives;
procedure WriteCommandLine;
procedure WriteModelInputOutput;
procedure WritePriorInformation;
procedure WritePredictiveAnalysis;
procedure WriteRegularisation;
procedure WritePareto;
// NPAR
function NumberOfParameters: Integer;
// NOBS
function NumberOfObservations: integer;
// NPARGP
function NumberOfParameterGroups: Integer;
// NPRIOR
function NumberOfPriorInformation: Integer;
// NOBSGP
function NumberOfObservationGroups: Integer;
protected
class function Extension: string; override;
public
Constructor Create(AModel: TCustomModel; EvaluationType: TEvaluationType); override;
destructor Destroy; override;
procedure WriteFile(const AFileName: string);
end;
implementation
uses
PestPropertiesUnit, ModflowParameterUnit, OrderedCollectionUnit,
PestParamGroupsUnit, PestObsGroupUnit, frmGoPhastUnit,
PestObsExtractorInputWriterUnit, frmErrorsAndWarningsUnit,
ModflowCHD_WriterUnit, ModflowHobUnit, ModflowDRN_WriterUnit,
ModflowRiverWriterUnit, ModflowGHB_WriterUnit, ModflowStrWriterUnit;
resourcestring
StrNoParametersHaveB = 'No parameters have been defined';
StrNoPestParameters = 'No parameters have been defined for use with PEST.';
StrNoParameterGroups = 'No parameter groups defined';
StrNoPESTParameterGr = 'No PEST parameter groups have been defined. Define them in "Model|Manage Parameters".';
StrNoObservationsDefi = 'No observations defined';
StrNoObservationsHave = 'No observations have been defined for PEST.';
StrNoObservationGroup = 'No observation groups defined';
StrNoPESTObservation = 'No PEST observation groups have been defined. "Define them in "Model|Pest Properties".';
StrParameterGroupName = 'Parameter group name not assigned';
StrTheParameterSH = 'The parameter "%s" has not been assigned to a paramet' +
'er group ';
StrObservationGroupNo = 'Observation group not assigned';
StrNoObservationGroupAssigned = 'No observation group has been assigned to %s.';
{ TPestControlFileWriter }
const Mf15ParamType: TParameterTypes = [ptRCH, ptETS, ptHFB, ptPEST, ptCHD,
ptGHB, ptQ, ptRIV, ptDRN];
constructor TPestControlFileWriter.Create(AModel: TCustomModel;
EvaluationType: TEvaluationType);
begin
inherited;
FUsedObservations := TObservationList.Create;
end;
destructor TPestControlFileWriter.Destroy;
begin
FUsedObservations.Free;
inherited;
end;
class function TPestControlFileWriter.Extension: string;
begin
result := '.pst';
end;
function TPestControlFileWriter.NumberOfObservationGroups: Integer;
begin
result := Model.PestProperties.ObservationGroups.Count;
if result = 0 then
begin
frmErrorsAndWarnings.AddError(Model, StrNoObservationGroup,
StrNoPESTObservation);
end;
end;
function TPestControlFileWriter.NumberOfObservations: integer;
var
TempList: TObservationList;
ObsIndex: Integer;
AnObs: TCustomObservationItem;
begin
TempList := TObservationList.Create;
try
frmGoPhast.PhastModel.FillObsItemList(TempList, True);
FUsedObservations.Capacity := TempList.Count;
for ObsIndex := 0 to TempList.Count - 1 do
begin
AnObs := TempList[ObsIndex];
if AnObs.Print then
begin
FUsedObservations.Add(AnObs);
end;
end;
result := FUsedObservations.Count;
if result = 0 then
begin
frmErrorsAndWarnings.AddError(Model, StrNoObservationsDefi,
StrNoObservationsHave);
end;
finally
TempList.Free;
end;
end;
function TPestControlFileWriter.NumberOfParameterGroups: Integer;
begin
result := Model.ParamGroups.Count;
if result = 0 then
begin
frmErrorsAndWarnings.AddError(Model, StrNoParameterGroups,
StrNoPESTParameterGr);
end;
end;
function TPestControlFileWriter.NumberOfParameters: Integer;
var
ParamIndex: Integer;
AParam: TModflowParameter;
UsedTypes: TParameterTypes;
begin
result := 0;
UsedTypes := [];
if Model.ModelSelection = msModflow2015 then
begin
UsedTypes := Mf15ParamType
end
else
begin
Assert(False);
end;
for ParamIndex := 0 to Model.ModflowSteadyParameters.Count - 1 do
begin
AParam := Model.ModflowSteadyParameters[ParamIndex];
if AParam.ParameterType in UsedTypes then
begin
Inc(result);
end;
end;
for ParamIndex := 0 to Model.ModflowTransientParameters.Count - 1 do
begin
AParam := Model.ModflowTransientParameters[ParamIndex];
if AParam.ParameterType in UsedTypes then
begin
Inc(result);
end;
end;
for ParamIndex := 0 to Model.HufParameters.Count - 1 do
begin
AParam := Model.HufParameters[ParamIndex];
if AParam.ParameterType in UsedTypes then
begin
Inc(result);
end;
end;
if result = 0 then
begin
frmErrorsAndWarnings.AddError(Model, StrNoParametersHaveB,
StrNoPestParameters)
end;
end;
function TPestControlFileWriter.NumberOfPriorInformation: Integer;
begin
// prior information will be added by the running ADDREG1 or a program in the
// Groundwater Utility suite,
result := 0;
end;
procedure TPestControlFileWriter.WriteAutomaticUserIntervention;
begin
// The Automatic User Intervention is not currently supported.
end;
procedure TPestControlFileWriter.WriteCommandLine;
begin
WriteSectionHeader('model command line');
WriteString('RunModel.bat');
NewLine;
NewLine;
end;
procedure TPestControlFileWriter.WriteControlSection;
var
PestControlData: TPestControlData;
NINSFLE: Integer;
begin
PestControlData := Model.PestProperties.PestControlData;
// First line 4.2.2.
WriteSectionHeader('control data');
{$REGION 'second line 4.2.3'}
// second line 4.2.3
case PestControlData.PestRestart of
prNoRestart:
begin
WriteString('norestart ');
end;
prRestart:
begin
WriteString('restart ');
end;
else
Assert(False);
end;
case PestControlData.PestMode of
pmEstimation:
begin
WriteString('estimation ');
end;
pmPrediction:
begin
WriteString('prediction ');
end;
pmRegularisation:
begin
WriteString('regularisation ');
end;
pmPareto:
begin
WriteString('pareto ');
end;
else
Assert(False);
end;
WriteString('# RSTFLE PESTMODE');
NewLine;
{$ENDREGION}
{$REGION 'third line 4.2.4'}
// third line 4.2.4
// NPAR
WriteInteger(NumberOfParameters);
// NOBS
WriteInteger(NumberOfObservations);
// NPARGP
WriteInteger(NumberOfParameterGroups);
// NPRIOR
WriteInteger(NumberOfPriorInformation);
// NOBSGP
WriteInteger(NumberOfObservationGroups);
// MAXCOMPRDIM
WriteInteger(PestControlData.MaxCompressionDimension);
if PestControlData.MaxCompressionDimension > 1 then
begin
// DERZEROLIM
WriteFloat(PestControlData.ZeroLimit);
end;
WriteString(' # NPAR NOBS NPARGP, NPRIOR NOBSGP, MAXCOMPRDIM');
if PestControlData.MaxCompressionDimension > 1 then
begin
WriteString(', DERZEROLIM');
end;
NewLine;
{$ENDREGION}
{$REGION 'fourth line 4.2.5'}
// NTPLFLE NINSFLE PRECIS DPOINT [NUMCOM JACFILE MESSFILE] [OBSREREF]
// fourth line 4.2.5
// NTPLFLE
// The pval file will always be the only file PEST writes.
WriteInteger(1);
// NINSFLE
NINSFLE := 0;
case Model.MOdelSelection of
msUndefined, msPhast, msFootPrint:
Assert(False);
msModflow, msModflowLGR, msModflowLGR2, msModflowNWT, msModflowFmp, msModflowCfp:
begin
if Model.ModflowPackages.HobPackage.IsSelected then
begin
Inc(NINSFLE);
end;
if Model.ModflowPackages.ChobPackage.IsSelected then
begin
Inc(NINSFLE);
end;
if Model.ModflowPackages.DrobPackage.IsSelected then
begin
Inc(NINSFLE);
end;
if Model.ModflowPackages.GbobPackage.IsSelected then
begin
Inc(NINSFLE);
end;
if Model.ModflowPackages.RvobPackage.IsSelected then
begin
Inc(NINSFLE);
end;
if Model.ModflowPackages.StobPackage.IsSelected then
begin
Inc(NINSFLE);
end;
if FUsedObservations.Count > 0 then
begin
Inc(NINSFLE);
end;
end;
msSutra22, msSutra30:
begin
NINSFLE := 1;
end;
msModflow2015:
begin
NINSFLE := 1;
end;
else
Assert(False);
end;
// PEST will always read all the simulated values from one file.
WriteInteger(NINSFLE);
// PRECIS
// All data will be writen in double precision
WriteString(' double');
// DPOINT
// The decimal point is never needed because free format is used exclusively.
WriteString(' nopoint');
// NUMCOM, JCFILE, and MESSFILE will be omited in all cases.
// OBSREREF
// observation rereferencing is not supported in ModelMuse.
WriteString(' noobsreref');
WriteString(' # NTPLFLE, NINSFLE, PRECIS, DPOINT, OBSREREF');
NewLine;
{$ENDREGION}
{$REGION 'fifth line 4.2.6'}
// Fifth line 4.2.6
// RLAMBDA1
WriteFloat(PestControlData.InitalLambda);
// RLAMFAC
WriteFloat(PestControlData.LambdaAdjustmentFactor);
// PHIRATSUF
WriteFloat(PestControlData.PhiRatioSufficient);
// PHIREDLAM
WriteFloat(PestControlData.PhiReductionLambda);
// NUMLAM
WriteInteger(PestControlData.NumberOfLambdas);
// JACUPDATE
WriteInteger(PestControlData.JacobianUpdate);
// LAMFORGIVE
case PestControlData.LambdaForgive of
lfForgive:
begin
WriteString(' lamforgive');
end;
lfNoForgive:
begin
WriteString(' nolamforgive');
end;
else
Assert(False);
end;
// DERFORGIVE
case PestControlData.DerivedForgive of
dfForgive:
begin
WriteString(' derforgive');
end;
dNoForgive:
begin
WriteString(' noderforgive');
end;
else
Assert(False);
end;
WriteString(' # RLAMBDA1, RLAMFAC, PHIRATSUF, PHIREDLAM, NUMLAM, JACUPDATE, LAMFORGIVE, DERFORGIVE');
NewLine;
{$ENDREGION}
{$REGION 'sixth line 4.2.7'}
// sixth line 4.2.7
//RELPARMAX
WriteFloat(PestControlData.RelativeMaxParamChange);
//FACPARMAX
WriteFloat(PestControlData.FactorMaxParamChange);
//FACORIG
WriteFloat(PestControlData.FactorOriginal);
// IBOUNDSTICK
WriteInteger(Ord(PestControlData.BoundStick));
// UPVECBEND
WriteInteger(Ord(PestControlData.UpgradeParamVectorBending));
// ABSPARMAX is not currently supported by ModelMuse.
WriteString(' # RELPARMAX, FACPARMAX, FACORIG, IBOUNDSTICK, UPVECBEND');
NewLine;
{$ENDREGION}
{$REGION 'seventh line 4.2.8'}
// seventh line 4.2.8
// PHIREDSWH
WriteFloat(PestControlData.SwitchCriterion);
// NOPTSWITCH
WriteInteger(PestControlData.OptSwitchCount);
// SPLITSWH
WriteFloat(PestControlData.SplitSlopeCriterion);
// DOAUI
case PestControlData.AutomaticUserIntervation of
auiInactive:
begin
WriteString(' noaui');
end;
auiActiveLeastSensitiveFirst:
begin
WriteString(' aui');
end;
auiMostSensitiveFirst:
begin
WriteString(' auid');
end;
else
Assert(False);
end;
// DOSENREUSE
case PestControlData.SensitivityReuse of
srNoReuse:
begin
WriteString(' nosenreuse');
end;
srReuse:
begin
WriteString(' senreuse');
end;
else
Assert(False);
end;
// BOUNDSCALE
if PestControlData.Boundscaling = bsBoundsScaling then
begin
WriteString(' boundscale');
end
else
begin
WriteString(' noboundscale');
end;
WriteString(' # PHIREDSWH, NOPTSWITCH, SPLITSWH, DOAUI, DOSENREUSE, BOUNDSCALE');
NewLine;
{$ENDREGION}
{$REGION 'eighth line 4.2.9'}
// eighth line 4.2.9
// NOPTMAX
WriteInteger(PestControlData.MaxIterations);
// PHIREDSTP
WriteFloat(PestControlData.SlowConvergenceCriterion);
// NPHISTP
WriteInteger(PestControlData.SlowConvergenceCountCriterion);
// NPHINORED
WriteInteger(PestControlData.ConvergenceCountCriterion);
// RELPARSTP
WriteFloat(PestControlData.ParameterChangeConvergenceCriterion);
// NRELPAR
WriteInteger(PestControlData.ParameterChangeConvergenceCount);
// PHISTOPTHRESH
if PestControlData.PestMode in [pmPrediction, pmPareto] then
begin
WriteFloat(0);
end
else
begin
WriteFloat(PestControlData.ObjectiveCriterion);
end;
// LASTRUN
WriteInteger(Ord(PestControlData.MakeFinalRun));
// PHIABANDON
WriteFloat(PestControlData.PhiAbandon);
WriteString(' # NOPTMAX, PHIREDSTP, NPHISTP, NPHINORED, RELPARSTP, NRELPAR, PHISTOPTHRESH, LASTRUN, PHIABANDON');
NewLine;
{$ENDREGION}
{$REGION 'nineth line 4.2.10'}
// ICOV
WriteInteger(Ord(PestControlData.WriteCovariance));
// ICOR
WriteInteger(Ord(PestControlData.WriteCorrelations));
// IEIG
WriteInteger(Ord(PestControlData.WriteEigenVectors));
// IRES
WriteInteger(Ord(PestControlData.SaveResolution));
// JCOSAVE
case PestControlData.SaveJacobian of
sjDontSave:
begin
WriteString(' nojcosave');
end;
sjSave:
begin
WriteString(' jcosave');
end;
else
Assert(False);
end;
// JCOSAVEITN
case PestControlData.SaveJacobianIteration of
sjiDontSave:
begin
WriteString(' nojcosaveitn');
end;
sjiSave:
begin
WriteString(' jcosaveitn');
end;
else
Assert(False);
end;
// VERBOSEREC
case PestControlData.VerboseRecord of
vrNonVerbose:
begin
WriteString(' noverboserec');
end;
vrVerbose:
begin
WriteString(' verboserec');
end;
else
Assert(False);
end;
// RESSAVEITN
case PestControlData.SaveInterimResiduals of
sirDontSave:
begin
WriteString(' noreisaveitn');
end;
sirSave:
begin
WriteString(' reisaveitn');
end;
else
Assert(False);
end;
// PARSAVEITN
case PestControlData.SaveParamIteration of
spiDontSave:
begin
WriteString(' noparsaveitn');
end;
spiSave:
begin
WriteString(' parsaveitn');
end;
else
Assert(False);
end;
// PARSAVERUN
case PestControlData.SaveParamRun of
sprDontSave:
begin
WriteString(' noparsaverun');
end;
sprSave:
begin
WriteString(' parsaverun');
end;
else
Assert(False);
end;
WriteString(' # ICOV, ICOR, IEIG, IRES, JCOSAVE, JCOSAVEITN, VERBOSEREC, RESSAVEITN, PARSAVEITN, PARSAVERUN');
NewLine;
{$ENDREGION}
NewLine;
end;
procedure TPestControlFileWriter.WriteDerivatives;
begin
// The Derivatives is not currently supported.
end;
procedure TPestControlFileWriter.WriteFile(const AFileName: string);
begin
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrNoParametersHaveB);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrNoObservationGroup);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrNoObservationsDefi);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrNoParameterGroups);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrParameterGroupName);
frmErrorsAndWarnings.RemoveErrorGroup(Model, StrObservationGroupNo);
if not Model.PestUsed then
begin
Exit;
end;
if Model.ModelSelection <> msModflow2015 then
begin
Exit;
end;
FNameOfFile := FileName(AFileName);
OpenFile(FNameOfFile);
try
WriteFirstLine;
WriteControlSection;
// The Sensitivity Reuse Section is not currently supported.
WriteSensitivityReuse;
WriteSingularValueDecomposition;
WriteLsqr;
// The Automatic User Intervention Section is not currently supported.
WriteAutomaticUserIntervention;
// Writing the SVD Assist Section is not currently supported.
WriteSVD_Assist;
WriteParameterGroups;
WriteParameters;
WriteObservationGroups;
WriteObservations;
WriteDerivatives;
WriteCommandLine;
WriteModelInputOutput;
WritePriorInformation;
WritePredictiveAnalysis;
WriteRegularisation;
WritePareto;
finally
CloseFile;
end;
end;
procedure TPestControlFileWriter.WriteFirstLine;
begin
WriteString('pcf');
NewLine;
end;
procedure TPestControlFileWriter.WriteLsqr;
var
LsqrProperties: TLsqrProperties;
begin
LsqrProperties := Model.PestProperties.LsqrProperties;
WriteSectionHeader('lsqr');
WriteInteger(Ord(LsqrProperties.Mode));
WriteString(' # LSQRMODE');
NewLine;
WriteFloat(LsqrProperties.MatrixTolerance);
WriteFloat(LsqrProperties.RightHandSideTolerance);
WriteFloat(LsqrProperties.ConditionNumberLimit);
if LsqrProperties.MaxIteration <> 0 then
begin
WriteInteger(LsqrProperties.MaxIteration);
end
else
begin
WriteInteger(NumberOfParameters * 4);
end;
WriteString(' # LSQR_ATOL LSQR_BTOL LSQR_CONLIM LSQR_ITNLIM');
NewLine;
WriteInteger(Ord(LsqrProperties.LsqrWrite));
WriteString(' # LSQRWRITE');
NewLine;
NewLine;
end;
procedure TPestControlFileWriter.WriteModelInputOutput;
var
TEMPFLE: string;
INFLE: string;
INSFLE: string;
OUTFLE: string;
begin
WriteSectionHeader('model input/output');
TEMPFLE := ExtractFileName(ChangeFileExt(FNameOfFile, StrPtf));
INFLE := ExtractFileName(ChangeFileExt(FNameOfFile, StrPvalExt));
WriteString(TEMPFLE);
WriteString(' ' + INFLE);
NewLine;
if Model.ModelSelection in Modflow2005Selection then
begin
if Model.ModflowPackages.HobPackage.IsSelected then
begin
OUTFLE := ExtractFileName(ChangeFileExt(FNameOfFile, StrHobout));
INSFLE := OUTFLE + '.ins';
WriteString(INSFLE);
WriteString(' ' + OUTFLE);
NewLine;
end;
if Model.ModflowPackages.ChobPackage.IsSelected then
begin
OUTFLE := ExtractFileName(ChangeFileExt(FNameOfFile,
TModflowCHD_Writer.ObservationOutputExtension));
INSFLE := OUTFLE + '.ins';
WriteString(INSFLE);
WriteString(' ' + OUTFLE);
NewLine;
end;
if Model.ModflowPackages.DrobPackage.IsSelected then
begin
OUTFLE := ExtractFileName(ChangeFileExt(FNameOfFile,
TModflowDRN_Writer.ObservationOutputExtension));
INSFLE := OUTFLE + '.ins';
WriteString(INSFLE);
WriteString(' ' + OUTFLE);
NewLine;
end;
if Model.ModflowPackages.GbobPackage.IsSelected then
begin
OUTFLE := ExtractFileName(ChangeFileExt(FNameOfFile,
TModflowGHB_Writer.ObservationOutputExtension));
INSFLE := OUTFLE + '.ins';
WriteString(INSFLE);
WriteString(' ' + OUTFLE);
NewLine;
end;
if Model.ModflowPackages.RvobPackage.IsSelected then
begin
OUTFLE := ExtractFileName(ChangeFileExt(FNameOfFile,
TModflowRIV_Writer.ObservationOutputExtension));
INSFLE := OUTFLE + '.ins';
WriteString(INSFLE);
WriteString(' ' + OUTFLE);
NewLine;
end;
if Model.ModflowPackages.StobPackage.IsSelected then
begin
OUTFLE := ExtractFileName(ChangeFileExt(FNameOfFile,
TStrWriter.ObservationOutputExtension));
INSFLE := OUTFLE + '.ins';
WriteString(INSFLE);
WriteString(' ' + OUTFLE);
NewLine;
end;
if FUsedObservations.Count > 0 then
begin
INSFLE := ExtractFileName(ChangeFileExt(FNameOfFile, StrPestIns));
OUTFLE := ExtractFileName(ChangeFileExt(FNameOfFile, StrMf6Values));
WriteString(INSFLE);
WriteString(' ' + OUTFLE);
NewLine;
end;
end
else
begin
INSFLE := ExtractFileName(ChangeFileExt(FNameOfFile, StrPestIns));
OUTFLE := ExtractFileName(ChangeFileExt(FNameOfFile, StrMf6Values));
WriteString(INSFLE);
WriteString(' ' + OUTFLE);
NewLine;
end;
NewLine;
end;
procedure TPestControlFileWriter.WriteObservationGroups;
var
ObservationGroups: TPestObservationGroups;
ObsGrpIndex: Integer;
ObsGroup: TPestObservationGroup;
Mode: TPestMode;
CorrelationFileName: string;
begin
WriteSectionHeader('observation groups');
ObservationGroups := Model.PestProperties.ObservationGroups;
Mode := Model.PestProperties.PestControlData.PestMode;
for ObsGrpIndex := 0 to ObservationGroups.Count - 1 do
begin
ObsGroup := ObservationGroups[ObsGrpIndex];
WriteString(ObsGroup.ObsGroupName);
if Mode = pmRegularisation then
begin
if ObsGroup.UseGroupTarget then
begin
WriteFloat(ObsGroup.GroupTarget);
end;
end;
if ObsGroup. AbsoluteCorrelationFileName <> '' then
begin
CorrelationFileName := ' ' + ExtractRelativePath(FNameOfFile, ObsGroup.AbsoluteCorrelationFileName);
WriteString(CorrelationFileName);
end;
NewLine;
end;
NewLine;
end;
procedure TPestControlFileWriter.WriteObservations;
var
ObsIndex: Integer;
AnObs: TCustomObservationItem;
begin
WriteSectionHeader('observation data');
for ObsIndex := 0 to FUsedObservations.Count - 1 do
begin
AnObs := FUsedObservations[ObsIndex];
if AnObs.ExportedName <> '' then
begin
WriteString(AnObs.ExportedName);
end
else
begin
WriteString(AnObs.Name);
end;
WriteFloat(AnObs.ObservedValue);
WriteFloat(AnObs.Weight);
WriteString(' ' + AnObs.ObservationGroup);
if AnObs.ObservationGroup = '' then
begin
frmErrorsAndWarnings.AddError(Model, StrObservationGroupNo,
Format(StrNoObservationGroupAssigned, [AnObs.Name]));
end;
NewLine;
end;
NewLine;
end;
procedure TPestControlFileWriter.WriteParameterGroups;
var
GroupIndex: Integer;
AGroup: TPestParamGroup;
begin
WriteSectionHeader('parameter groups');
for GroupIndex := 0 to Model.ParamGroups.Count - 1 do
begin
AGroup := Model.ParamGroups[GroupIndex];
// PARGPNME
WriteString(AGroup.ParamGroupName);
// INCTYP
case AGroup.IncrementType of
icRelative:
begin
WriteString(' relative');
end;
icAbsolute:
begin
WriteString(' absolute');
end;
icRelativeToMax:
begin
WriteString(' rel_to_max');
end;
else Assert(False);
end;
// DERINC
WriteFloat(AGroup.ParamIncrement);
// DERINCLB
WriteFloat(AGroup.MinParamIncrement);
// FORCEN
case AGroup.ForceCentral of
fcAlways2:
begin
WriteString(' always_2');
end;
fcAlways3:
begin
WriteString(' always_3');
end;
fcAlways5:
begin
WriteString(' always_5');
end;
fcSwitch:
begin
WriteString(' switch');
end;
fcSwitch5:
begin
WriteString(' switch_5');
end;
else Assert(False);
end;
// DERINCMUL
WriteFloat(AGroup.ParamIncrementMultiplier);
// DERMTHD
case AGroup.ForceCentral of
fcAlways2, fcAlways3, fcSwitch:
begin
case AGroup.DM3 of
dm3Parabolic:
begin
WriteString(' parabolic');
end;
dm3BestFit:
begin
WriteString(' best_fit');
end;
dm3OutsidePoints:
begin
WriteString(' outside_pts');
end;
else Assert(False);
end;
end;
fcAlways5, fcSwitch5:
begin
case AGroup.DM5 of
dm5MinimumVariance:
begin
WriteString(' minvar');
end;
dm5MaxPrecision:
begin
WriteString(' maxprec');
end;
else Assert(False);
end;
end;
else
Assert(False);
end;
if AGroup.UseSplitSlopeAnalysis then
begin
// SPLITTHRESH
WriteFloat(AGroup.SplitThreshold);
// SPLITRELDIFF
WriteFloat(AGroup.RelSlopeDif);
// SPLITACTION
case AGroup.SplitAction of
saSmaller:
begin
WriteString(' smaller');
end;
saZero:
begin
WriteString(' zero');
end;
saPrevious:
begin
WriteString(' previous');
end;
else Assert(False);
end;
end;
NewLine;
end;
NewLine;
end;
procedure TPestControlFileWriter.WriteParameters;
var
UsedTypes: TParameterTypes;
ParamIndex: Integer;
AParam: TModflowParameter;
procedure WriteParameter(AParam: TModflowParameter);
begin
//PARNME
WriteString(AParam.ParameterName);
//PARTRANS
case AParam.Transform of
ptNoTransform:
begin
WriteString(' none');
end;
ptLog:
begin
WriteString(' log');
end;
ptFixed:
begin
WriteString(' fixed');
end;
ptTied:
begin
WriteString(' tied');
end;
else Assert(False);
end;
//PARCHGLIM
case AParam.ChangeLimitation of
pclRelative:
begin
WriteString(' relative');
end;
pclFactor:
begin
WriteString(' factor');
end;
pclAbsolute:
begin
WriteString(' absolute(N)');
end;
else
Assert(False);
end;
//PARVAL1
WriteFloat(AParam.Value);
//PARLBND
WriteFloat(AParam.LowerBound);
//PARUBND
WriteFloat(AParam.UpperBound);
//PARGP
if AParam.ParameterGroup = '' then
begin
WriteString(' none');
frmErrorsAndWarnings.AddError(Model, StrParameterGroupName,
Format(StrTheParameterSH, [AParam.ParameterName]));
end
else
begin
WriteString(' ' + AParam.ParameterGroup);
end;
//SCALE
WriteFloat(AParam.Scale);
//OFFSET
WriteFloat(AParam.Offset);
//DERCOM
// write only in NUMCOM is written in line 4 of the control data section
// WriteInteger(1);
NewLine;
end;
procedure WriteTiedParameter(AParam: TModflowParameter);
begin
if AParam.Transform = ptTied then
begin
// PARNME
WriteString(AParam.ParameterName);
// PARTIED
WriteString(' ' + AParam.TiedParameterName);
NewLine;
end;
end;
begin
UsedTypes := [];
if Model.ModelSelection = msModflow2015 then
begin
UsedTypes := Mf15ParamType
end
else
begin
Assert(False);
end;
WriteSectionHeader('parameter data');
for ParamIndex := 0 to Model.ModflowSteadyParameters.Count - 1 do
begin
AParam := Model.ModflowSteadyParameters[ParamIndex];
if AParam.ParameterType in UsedTypes then
begin
WriteParameter(AParam);
end;
end;
for ParamIndex := 0 to Model.ModflowTransientParameters.Count - 1 do
begin
AParam := Model.ModflowTransientParameters[ParamIndex];
if AParam.ParameterType in UsedTypes then
begin
WriteParameter(AParam);
end;
end;
for ParamIndex := 0 to Model.HufParameters.Count - 1 do
begin
AParam := Model.HufParameters[ParamIndex];
if AParam.ParameterType in UsedTypes then
begin
WriteParameter(AParam);
end;
end;
NewLine;
end;
procedure TPestControlFileWriter.WritePareto;
begin
// The Pareto section is not currently supported.
end;
procedure TPestControlFileWriter.WritePredictiveAnalysis;
begin
// The Predictive Analysis section is not currently supported.
end;
procedure TPestControlFileWriter.WritePriorInformation;
begin
// prior information will be added by the running ADDREG1 or a program in the
// Groundwater Utility suite,
end;
procedure TPestControlFileWriter.WriteRegularisation;
begin
// The Regularisation section is not currently supported.
end;
procedure TPestControlFileWriter.WriteSectionHeader(const SectionID: String);
begin
WriteString('* ');
WriteString(SectionID);
NewLine;
end;
procedure TPestControlFileWriter.WriteSensitivityReuse;
begin
// The sensitivity reuse section is not currently supported.
end;
procedure TPestControlFileWriter.WriteSingularValueDecomposition;
var
SvdProperties: TSingularValueDecompositionProperties;
begin
SvdProperties := Model.PestProperties.SvdProperties;
WriteSectionHeader('singular value decomposition');
WriteInteger(Ord(SvdProperties.Mode));
WriteString(' # SVDMODE');
NewLine;
WriteInteger(SvdProperties.MaxSingularValues);
WriteFloat(SvdProperties.EigenThreshold);
WriteString(' # MAXSING, EIGTHRESH');
NewLine;
WriteInteger(Ord(SvdProperties.EigenWrite));
WriteString(' # EIGWRITE');
NewLine;
NewLine;
end;
procedure TPestControlFileWriter.WriteSVD_Assist;
begin
// Writing the SVD Assist section is not currently supported.
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
GLTriangulation,
GLWin32Viewer, GLCrossPlatform, GLBaseClasses, GLScene;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
procedure FormCreate(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
Z, U, V : Single;
MatIndex : Integer;
TempBuffer: TBitmap;
procedure ClearBackPage;
procedure FlipBackPage;
public
TheMesh: TGLDelaunay2D;
procedure Draw;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
TheMesh := TGLDelaunay2D.Create;
TempBuffer := TBitmap.Create;
Form1.Caption := 'Click on the form!';
end;
procedure TForm1.ClearBackPage;
begin
TempBuffer.Height := Form1.Height;
TempBuffer.Width := Form1.Width;
TempBuffer.Canvas.Brush.Color := clSilver;
TempBuffer.Canvas.FillRect(Rect(0, 0, Form1.Width, Form1.Height));
end;
procedure TForm1.FlipBackPage;
var
ARect: TRect;
begin
ARect := Rect(0, 0, Form1.Width, Form1.Height);
Form1.Canvas.CopyRect(ARect, TempBuffer.Canvas, ARect);
end;
procedure TForm1.Draw;
var
// variable to hold how many triangles are created by the triangulate function
i: Integer;
begin
// Clear the form canvas
ClearBackPage;
TempBuffer.Canvas.Brush.Color := clTeal;
// Draw the created triangles
with TheMesh do
begin
if (TheMesh.HowMany > 0) then
begin
for i := 1 To TheMesh.HowMany do
begin
TempBuffer.Canvas.Polygon([Point(Trunc(Vertex[Triangle[i].vv0].x),
Trunc(Vertex[Triangle[i].vv0].y)),
Point(Trunc(Vertex[Triangle[i].vv1].x),
Trunc(Vertex[Triangle[i].vv1].y)),
Point(Trunc(Vertex[Triangle[i].vv2].x),
Trunc(Vertex[Triangle[i].vv2].y))]);
end;
end;
end;
FlipBackPage;
end;
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
TheMesh.AddPoint(X, Y, Z, U, V, MatIndex); // add a point to the mesh
TheMesh.Mesh(True); // triangulate the mesh
Draw; // draw the mesh on the forms canvas
Form1.Caption := 'Points: ' + IntToStr(TheMesh.tPoints - 1) + ' Triangles: '
+ IntToStr(TheMesh.HowMany);
end;
end.
|
unit NRC_Logger;
interface
uses
SysUtils, Classes, Registry;
const
ErLog_LoadOptions = 1;
ErLog_SaveOptions = 2;
ErLog_CreateFile = 3;
ErLog_OpenFile = 4;
type
TLogFileMode = (lmAppend, lmClear, lmNewFile);
{класс - объект, обеспечивающий ведение лог-файла работы программы
Свойства класса:
- Active - активность ведения лога (установка в true запускает ведение лога,
установка в false останавливает ведение лога)
- FileName - имя (шаблон имени) файла лога
- LastError - код ошибки выполнения последней операции
- LogFileMode - режим работы с лог-файлом
lmAppend - добавление в существующий файл
(при отсутствии будет создан)
lmClear - перезаписывание лог-файла
lmNewFile - создание каждый раз нового лог-файла
(FileName используется в качестве шаблона имени)
- MaxCount - максимальное количество строк, хранимых в буфере
- RegKey - ключ реестра, в котором будут хранится настройки
- Version - версия компонента
Методы класса:
- AddLine - добавление строки в лог
- GetActiveFileName - получение имени файла активного лога (актуально при
режиме lmNewFile)
- OptionsLoadFromRegistry - чтение настроек из реестра
- OptionsSaveToRegistry - сохранение настроек в реестр
- SaveLine - сохранение строк из буфера в файл и очистка буфера
- SetCaptionLogFile - запись заголовка лог-файла}
TNRC_Logger = class(TComponent)
private
{ Private declarations }
fLine: TStringList;
fLog: TFileStream;
fActive: boolean;
fMaxCount: integer;
fLastError: integer;
fFileName: TFileName;
fActiveFileName: TFileName;
fLogFileMode: TLogFileMode;
fChangeActiveFileName: boolean;
fRegKey: string;
fProgramName: string;
procedure SetActive(const Value: boolean);
procedure SetMaxCount(const Value: integer);
function GetLastError: integer;
function GetVersion: string;
protected
{ Protected declarations }
procedure SetCaptionLogFile;
procedure SaveLine;
procedure StartLog;
procedure StopLog;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddLine(const aLine: string);
procedure ChangeActiveFileName(const Suffix: string);
function GetActiveFileName: TFileName;
function LoadOptionsFromRegistry(const RootKey: cardinal): boolean;
function SaveOptionsToRegistry(const RootKey: cardinal): boolean;
property LastError: integer read GetLastError;
published
{ Published declarations }
property Active: boolean read fActive write SetActive default false;
property FileName: TFileName read fFileName write fFileName;
property LogFileMode: TLogFileMode read fLogFileMode write fLogFileMode default lmAppend;
property MaxCount: integer read fMaxCount write SetMaxCount default 500;
property ProgramName: string read fProgramName write fProgramName;
property RegKey: string read fRegKey write fRegKey;
property Version: string read GetVersion;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NRC', [TNRC_Logger]);
end;
{ TNRC_Logger }
procedure TNRC_Logger.AddLine(const aLine: string);
begin
if fLine=nil then
Exit;
if fLine.Count=fMaxCount then
SaveLine;
fLine.Add(aLine);
end;
procedure TNRC_Logger.ChangeActiveFileName(const Suffix: string);
var
n: integer;
begin
n:=Length(ExtractFileExt(fFileName));
fActiveFileName:=Copy(fFileName,1,length(fFileName)-n)+'_'+Suffix+ExtractFileExt(fFileName);
fChangeActiveFileName:=true;
end;
constructor TNRC_Logger.Create(AOwner: TComponent);
begin
inherited;
fLine:=nil;
fLog:=nil;
fActive:=false;
fFileName:='';
fActiveFileName:='';
fLogFileMode:=lmAppend;
fMaxCount:=500;
fLastError:=0;
fRegKey:='';
fChangeActiveFileName:=false;
fProgramName:='';
end;
destructor TNRC_Logger.Destroy;
begin
Active:=false;
inherited;
end;
function TNRC_Logger.GetActiveFileName: TFileName;
begin
Result:=fActiveFileName;
end;
function TNRC_Logger.GetLastError: integer;
begin
Result:=fLastError;
fLastError:=0;
end;
function TNRC_Logger.GetVersion: string;
begin
Result:='version 1.0 (30.11.2007)';
end;
function TNRC_Logger.LoadOptionsFromRegistry(const RootKey: cardinal): boolean;
var
Reg: TRegistry;
begin
fLastError:=0;
Result:=false;
Reg:=TRegistry.Create;
Reg.RootKey:=RootKey;
try
if Reg.OpenKeyReadOnly(fRegKey) then
begin
fFileName:=Reg.ReadString('LogFile');
fLogFileMode:=TLogFileMode(Reg.ReadInteger('LogFileMode'));
fMaxCount:=Reg.ReadInteger('MaxCount');
Reg.CloseKey;
Result:=true;
end;
except
fLastError:=ErLog_LoadOptions;
end;
Reg.Free;
end;
function TNRC_Logger.SaveOptionsToRegistry(const RootKey: cardinal): boolean;
var
Reg: TRegistry;
begin
fLastError:=0;
Result:=true;
Reg:=TRegistry.Create;
Reg.RootKey:=RootKey;
try
if Reg.OpenKey(fRegKey,true) then
begin
Reg.WriteString('LogFile',fFileName);
Reg.WriteInteger('LogFileMode',ord(fLogFileMode));
Reg.WriteInteger('MaxCount',fMaxCount);
Reg.CloseKey;
end;
except
Result:=false;
fLastError:=ErLog_SaveOptions;
end;
Reg.Free;
end;
procedure TNRC_Logger.SaveLine;
begin
fLog.Seek(0,soFromEnd);
fLine.SaveToStream(fLog);
fLine.Clear;
end;
procedure TNRC_Logger.SetActive(const Value: boolean);
var
SR: TSearchRec;
n: integer;
begin
if fActive=Value then
Exit;
fLastError:=0;
if Value then
try
fLine:=TStringList.Create;
case fLogFileMode of
lmAppend:
begin
if not fChangeActiveFileName then
fActiveFileName:=FileName;
if FindFirst(fActiveFileName,faAnyFile,SR)=0 then
try
fLog:=TFileStream.Create(fActiveFileName,fmOpenReadWrite,fmShareExclusive);
StartLog;
except
fLastError:=ErLog_OpenFile;
end
else
begin
fLog:=TFileStream.Create(fActiveFileName,fmCreate,fmShareExclusive);
SetCaptionLogFile;
StartLog;
end;
SysUtils.FindClose(SR);
end;
lmClear:
begin
if not fChangeActiveFileName then
fActiveFileName:=fFileName;
fLog:=TFileStream.Create(fActiveFileName,fmCreate,fmShareExclusive);
SetCaptionLogFile;
StartLog;
end;
lmNewFile:
begin
n:=Length(ExtractFileExt(fFileName));
fActiveFileName:=Copy(fFileName,1,length(fFileName)-n)+'_'+FormatDateTime('yyyy-mm-dd_hh-mm-ss',Now)+ExtractFileExt(fFileName);
fLog:=TFileStream.Create(fActiveFileName,fmCreate,fmShareExclusive);
SetCaptionLogFile;
StartLog;
end;
end;
except
fLastError:=ErLog_CreateFile;
end
else
begin
StopLog;
// if fLine.Count>0 then
SaveLine;
FreeAndNil(fLine);
FreeAndNil(fLog);
end;
fActive:=Value and (fLastError=0);
end;
procedure TNRC_Logger.SetCaptionLogFile;
var
s: string;
i,n1: integer;
begin
AddLine('********* (c)NRCom Software, 2007 *********');
AddLine('*** TNRC_Logger '+Version+' ***');
AddLine('*********************************************');
if length(fProgramName)<45 then
n1:=(45-length(fProgramName)) div 2-1
else
n1:=3;
s:='*';
for i:=1 to n1 do
s:=s+' ';
s:=s+fProgramName+' ';
for i:=1 to n1-1 do
s:=s+' ';
AddLine(s+'*');
AddLine('*********************************************');
end;
procedure TNRC_Logger.SetMaxCount(const Value: integer);
begin
if (Active) and (fLine.Count>=Value) then
SaveLine;
fMaxCount:=Value;
end;
procedure TNRC_Logger.StartLog;
begin
AddLine(DateTimeToStr(Now)+'> Start log...');
end;
procedure TNRC_Logger.StopLog;
begin
AddLine(DateTimeToStr(Now)+'> Stop log.');
AddLine('*********************************************');
end;
end.
|
unit sgSDLUtils;
interface
uses {$IFDEF SWINGAME_SDL13}SDL2{$ELSE}sdl{$ENDIF}, sgTypes;
procedure PutSurfacePixel(surf : PSDL_Surface; clr: Color; x, y: Longint);
function GetSurfacePixel(surface: PSDL_Surface; x, y: Longint): Color;
procedure SetNonAlphaPixels(bmp : Bitmap; surface: PSDL_Surface);
function SDL_Swap32(D: Uint32): Uint32;
implementation
uses sgShared;
procedure PutSurfacePixel(surf : PSDL_Surface; clr: Color; x, y: Longint);
var
p: ^Color;
bpp: Longint;
begin
if not Assigned(surf) then begin RaiseWarning('OpenGL Images Driver - PutPixelProcedure recieved empty Surface'); exit; end;
bpp := surf^.format^.BytesPerPixel;
// Here p is the address to the pixel we want to set
p := surf^.pixels + y * surf^.pitch + x * bpp;
if bpp <> 4 then RaiseException('PutPixel only supported on 32bit images.');
p^ := clr;
end;
function GetSurfacePixel(surface: PSDL_Surface; x, y: Longint) :Color;
var
pixel, pixels: PUint32;
offset: Longword;
{$IFDEF FPC}
pixelAddress: PUint32;
{$ELSE}
pixelAddress: Longword;
{$ENDIF}
begin
//Convert the pixels to 32 bit
pixels := surface^.pixels;
//Get the requested pixel
offset := (( y * surface^.w ) + x) * surface^.format^.BytesPerPixel;
{$IFDEF FPC}
pixelAddress := pixels + (offset div 4);
pixel := PUint32(pixelAddress);
{$ELSE}
pixelAddress := Longword(pixels) + offset;
pixel := Ptr(pixelAddress);
{$ENDIF}
{$IF SDL_BYTEORDER = SDL_BIG_ENDIAN }
case surface^.format^.BytesPerPixel of
1: result := pixel^ and $000000ff;
2: result := pixel^ and $0000ffff;
3: result := pixel^ and $00ffffff;
4: result := pixel^;
else
RaiseException('Unsuported bit format...');
exit;
end;
{$ELSE}
case surface^.format^.BytesPerPixel of
1: result := pixel^ and $ff000000;
2: result := pixel^ and $ffff0000;
3: result := pixel^ and $ffffff00;
4: result := pixel^;
end;
{$IFEND}
end;
procedure SetNonAlphaPixels(bmp : Bitmap; surface: PSDL_Surface);
var
r, c: Longint;
hasAlpha: Boolean;
begin
if not ( Assigned(bmp) and Assigned(surface) ) then exit;
SetLength(bmp^.nonTransparentPixels, bmp^.width, bmp^.height);
hasAlpha := surface^.format^.BytesPerPixel = 4;
for c := 0 to bmp^.width - 1 do
begin
for r := 0 to bmp^.height - 1 do
begin
{$IFDEF SWINGAME_SDL13}
bmp^.nonTransparentPixels[c, r] := (not hasAlpha) or ((GetSurfacePixel(surface, c, r) and SDL_Swap32($000000FF)) > 0);
{$ELSE}
//if (c = 0) and (r = 0) then
//begin
// WriteLn('not hasAlpha = ', not hasAlpha);
// WriteLn('Color is ', GetSurfacePixel(surface, c, r));
// WriteLn('Alpha is ', $000000FF shr surface^.format^.ashift);
// WriteLn('Alpha shift is ', surface^.format^.ashift);
//end;
bmp^.nonTransparentPixels[c, r] := (not hasAlpha) or ((GetSurfacePixel(surface, c, r) and ($FF shl surface^.format^.ashift)) > 0);
{$ENDIF}
end;
end;
end;
function SDL_Swap32(D: Uint32): Uint32;
begin
Result := ((D shl 24) or ((D shl 8) and $00FF0000) or ((D shr 8) and $0000FF00) or (D shr 24));
end;
end. |
//Trabalho de Lucas Hollas de Cairos
unit Email.View;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
IniFiles,
IdComponent,
IdTCPConnection,
IdTCPClient,
IdHTTP,
IdBaseComponent,
IdMessage,
// IdExplicitTLSClientServerBase,
IdMessageClient,
IdSMTPBase,
IdSMTP,
IdIOHandler,
IdIOHandlerSocket,
IdIOHandlerStack,
// IdSSL,
// IdSSLOpenSSL,
IdAttachmentFile,
IdText;
type
TfrmEmail = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label9: TLabel;
Btn_Limpar: TButton;
Button1: TButton;
BtnAnexo: TButton;
Edt_nome: TEdit;
edtAnexo: TEdit;
edtAssunto: TEdit;
EdtPara: TEdit;
memCorpo: TMemo;
BtnDesconecta: TButton;
Panel3: TPanel;
procedure Button1Click(Sender: TObject);
procedure BtnAnexoClick(Sender: TObject);
procedure BtnDesconectaClick(Sender: TObject);
private
{ Private declarations }
function EnviarEmail(const AAssunto, ADestino, AAnexo: String;
ACorpo: TStrings): Boolean;
public
{ Public declarations }
procedure limparcampos;
end;
var
frmEmail: TfrmEmail;
implementation
{$R *.dfm}
uses Main.View;
procedure TfrmEmail.Button1Click(Sender: TObject);
begin
if edtPara.Text = '' then
begin
showmessage('Por Favor, Digite o Destinatário!');
end
else if Edt_nome.Text = '' then
begin
showmessage('Por Favor, Digite a Sua Identificação');
end;
if EnviarEmail(edtAssunto.Text, edtPara.Text, edtAnexo.Text, memCorpo.Lines)
then
showmessage('Enviado com sucesso!')
else
showmessage('Não foi possível enviar o e-mail!');
end;
procedure TfrmEmail.BtnAnexoClick(Sender: TObject);
begin
with TOpenDialog.Create(Self) do
if Execute then
edtAnexo.Text := FileName;
end;
procedure TfrmEmail.BtnDesconectaClick(Sender: TObject);
begin
limparcampos;
frmMain.Edt_Host.Text := '';
frmMain.Edt_Porta.Text := '';
frmMain.Edt_User.Text := '';
frmMain.Edt_Senha.Text := '';
frmMain.Visible := true;
frmEmail.Close;
end;
function TfrmEmail.EnviarEmail(const AAssunto, ADestino, AAnexo: String;
ACorpo: TStrings): Boolean;
var
IniFile: TIniFile;
sFrom: String;
sBccList: String;
sHost: String;
iPort: Integer;
sUserName: String;
sPassword: String;
idMsg: TIdMessage;
IdText: TIdText;
IdSMTP: TIdSMTP;
// idSSLIOHandlerSocket : TIdSSLIOHandlerSocketOpenSSL;
begin
try
try
// Criação e leitura do arquivo INI com as configurações
// IniFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Config.ini');
// sFrom := IniFile.ReadString('Email' , 'From' , sFrom);
// sBccList := IniFile.ReadString('Email' , 'BccList' , sBccList);
// sHost := IniFile.ReadString('Email' , 'Host' , sHost);
// iPort := IniFile.ReadInteger('Email', 'Port' , iPort);
// sUserName := IniFile.ReadString('Email' , 'UserName' , sUserName);
// sPassword := IniFile.ReadString('Email' , 'Password' , sPassword);
sFrom := frmMain.Edt_User.Text;
sBccList := 'acclucash@gmail.com';
sHost := frmMain.Edt_Host.Text;
iPort := strtoint(frmMain.Edt_Porta.Text);
sUserName := frmMain.Edt_User.Text;
sPassword := frmMain.Edt_Senha.Text;
// Configura os parâmetros necessários para SSL
// IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(Self);
// IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23;
// IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient;
// Variável referente a mensagem
idMsg := TIdMessage.Create(Self);
idMsg.CharSet := 'utf-8';
idMsg.Encoding := meMIME;
idMsg.From.Name := Edt_nome.Text;
idMsg.From.Address := sFrom;
idMsg.Priority := mpNormal;
idMsg.Subject := AAssunto;
// Add Destinatário(s)
idMsg.Recipients.Add;
idMsg.Recipients.EMailAddresses := ADestino;
idMsg.CCList.EMailAddresses := 'acclucash@gmail.com';
idMsg.BccList.EMailAddresses := sBccList;
idMsg.BccList.EMailAddresses := 'acclucash@gmail.com'; // Cópia Oculta
// Variável do texto
IdText := TIdText.Create(idMsg.MessageParts);
IdText.Body.Add(ACorpo.Text);
IdText.ContentType := 'text/html; text/plain; charset=iso-8859-1';
// Prepara o Servidor
IdSMTP := TIdSMTP.Create(Self);
// idSMTP.IOHandler := IdSSLIOHandlerSocket;
// idSMTP.UseTLS := utUseImplicitTLS;
IdSMTP.AuthType := satDefault;
IdSMTP.Host := sHost;
IdSMTP.AuthType := satDefault;
IdSMTP.Port := iPort;
IdSMTP.Username := sUserName;
IdSMTP.Password := sPassword;
// Conecta e Autentica
IdSMTP.Connect;
IdSMTP.Authenticate;
if AAnexo <> EmptyStr then
if FileExists(AAnexo) then
TIdAttachmentFile.Create(idMsg.MessageParts, AAnexo);
// Se a conexão foi bem sucedida, envia a mensagem
if IdSMTP.Connected then
begin
try
IdSMTP.Send(idMsg);
except
on E: Exception do
begin
showmessage('Erro ao tentar enviar: ' + E.Message);
end;
end;
end;
// Depois de tudo pronto, desconecta do servidor SMTP
if IdSMTP.Connected then
IdSMTP.Disconnect;
Result := true;
finally
// IniFile.Free;
// UnLoadOpenSSLLibrary;
FreeAndNil(idMsg);
// FreeAndNil(idSSLIOHandlerSocket);
FreeAndNil(IdSMTP);
end;
except
on E: Exception do
begin
Result := False;
end;
end;
end;
procedure TfrmEmail.limparcampos;
begin
Edt_nome.Text := '';
memCorpo.Text := '';
edtPara.Text := '';
edtAssunto.Text := '';
edtAnexo.Text := '';
end;
end.
|
unit ideSHMessages;
interface
resourcestring
SUnderConstruction = 'Sorry,... coming soon' + sLineBreak + 'Under construction';
SNotSupported = 'This version does not support this feature, sorry';
SMustBeDescription = 'Description must be containing string "BlazeTop"';
SLibraryExists = 'Library ''%s'' already registered';
SLibraryRemoveQuestion = 'Remove library ''%s'' ?';
SLibraryRemoveWarning = 'Warning: remove library will come into effect after program has been restarted';
SLibraryCantLoad = 'Can not load library ''%s''';
SPackageExists = 'Package ''%s'' already registered';
SPackageRemoveQuestion = 'Remove package ''%s'' ?';
SPackageRemoveWarning = 'Warning: remove package will come into effect after program has been restarted';
SPackageCantLoad = 'Can not load package ''%s''';
SCantFindComponentFactory = 'Can not find Component Factory for registered class %s,' + sLineBreak + 'ClassID: [%s]';
SInvalidPropValue = '"%s" is invalid property value';
implementation
end.
|
unit WordFreqCoverage_MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, JWBIO, FastArray, Vcl.StdCtrls,
Vcl.ComCtrls, Vcl.ExtCtrls;
type
TWfRecord = record
word: string;
count: int64;
end;
PWfRecord = ^TWfRecord;
TMainForm = class(TForm)
tbWordCount: TTrackBar;
edtWordCount: TEdit;
Label1: TLabel;
Label2: TLabel;
tbCoverage: TTrackBar;
edtCoverage: TEdit;
Label3: TLabel;
Bevel1: TBevel;
edtCutWords: TEdit;
Label4: TLabel;
Label5: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edtWordCountChange(Sender: TObject);
procedure edtCoverageChange(Sender: TObject);
procedure tbWordCountChange(Sender: TObject);
procedure tbCoverageChange(Sender: TObject);
procedure edtWordCountExit(Sender: TObject);
procedure edtCoverageExit(Sender: TObject);
procedure edtCutWordsExit(Sender: TObject);
protected
wf: TArray<TWfRecord>;
TotalCount: int64;
procedure LoadWordFreq(const AFilename: string; AEncoding: CEncoding);
protected
FCutWordCount: integer;
FTotalUncutCount: int64;
procedure SetCutWordCount(AValue: integer);
protected
FCurWordCount: integer;
FCurCoverage: integer;
FIgnoreWordCountChange: integer;
FIgnoreCoverageChange: integer;
procedure SetWordCount(AValue: integer; const ARunTriggers: boolean = true);
procedure SetCoverage(AValue: integer; const ARunTriggers: boolean = true);
procedure UpdateWordCount;
procedure UpdateCoverage;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure TMainForm.FormCreate(Sender: TObject);
begin
LoadWordFreq('wordfreq_ck', TEUCEncoding);
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
tbWordCount.Max := 100;
tbCoverage.Max := 100;
SetCutWordCount(0);
end;
procedure TMainForm.LoadWordFreq(const AFilename: string; AEncoding: CEncoding);
var inp: TStreamDecoder;
ln: string;
i: integer;
begin
inp := OpenTextFile(AFilename, AEncoding);
try
wf.Reset;
TotalCount := 0;
while inp.ReadLn(ln) do begin
// ln := Trim(ln); //do not do, trims some literals erroneously (breaks parsing)
if (ln='') or (ln[1]='#') then continue;
i := ln.IndexOf(#9);
if i<=0 then
raise Exception.Create('Invalid line: '+ln);
with wf.AddNew^ do begin
word := copy(ln, 1, i);
count := StrToInt(copy(ln, i+2, MaxInt));
Inc(TotalCount, count);
end;
end;
finally
FreeAndNil(inp);
end;
if TotalCount<=0 then
TotalCount := 1; //simplify things
end;
procedure TMainForm.edtCutWordsExit(Sender: TObject);
begin
SetCutWordCount(StrToInt(edtCutWords.Text));
end;
procedure TMainForm.SetCutWordCount(AValue: integer);
var i: integer;
begin
if AValue < 0 then
AValue := 0;
if AValue > wf.Count then
AValue := wf.Count;
FCutWordCount := AValue;
FTotalUncutCount := 0;
for i := FCutWordCount to wf.Count-1 do
Inc(FTotalUncutCount, wf[i].count);
if FTotalUncutCount<=0 then
FTotalUncutCount := 1;
SetWordCount(0);
end;
{ Actual values are stored in tbWordCount/tbCoverage.Position because that's
an int.
When editing the text field, values are saved to .Position and applied when
valid, then last valid value is restored to text on control exit. }
procedure TMainForm.SetWordCount(AValue: integer; const ARunTriggers: boolean);
var tmp: integer;
begin
if AValue < 0 then
AValue := 0;
if AValue > wf.Count then
AValue := wf.Count;
FCurWordCount := AValue;
Inc(FIgnoreWordCountChange);
try
if not TryStrToInt(edtWordCount.Text, tmp) or (tmp<>AValue) then
edtWordCount.Text := IntToStr(AValue);
tmp := Trunc(100 * FCurWordCount / (wf.Count-FCutWordCount));
if tbWordCount.Position<>tmp then
tbWordCount.Position := tmp;
finally
Dec(FIgnoreWordCountChange);
end;
if ARunTriggers then
UpdateCoverage;
end;
procedure TMainForm.tbWordCountChange(Sender: TObject);
begin
if FIgnoreWordCountChange>0 then exit;
SetWordCount(Trunc((tbWordCount.Position / 100) * (wf.Count-FCutWordCount)))
end;
procedure TMainForm.edtWordCountChange(Sender: TObject);
var tmp: integer;
begin
if FIgnoreWordCountChange>0 then exit;
if TryStrToInt(edtWordCount.Text, tmp) then
SetWordCount(tmp);
end;
procedure TMainForm.edtWordCountExit(Sender: TObject);
begin
//Restore last working wordcount if broken
SetWordCount(FCurWordCount, false);
end;
//Update Coverage value when WordCount changes
procedure TMainForm.UpdateCoverage;
var cnt: int64;
i: integer;
begin
cnt := 0;
for i := FCutWordCount to FCutWordCount+FCurWordCount-1 do
Inc(cnt, wf[i].count);
SetCoverage(Trunc(cnt*100/FTotalUncutCount), false);
end;
procedure TMainForm.SetCoverage(AValue: integer; const ARunTriggers: boolean);
var tmp: integer;
begin
if AValue < 0 then
AValue := 0;
if AValue > tbCoverage.Max then
AValue := tbCoverage.Max;
FCurCoverage := AValue;
Inc(FIgnoreCoverageChange);
try
if not TryStrToInt(edtCoverage.Text, tmp) or (tmp<>AValue) then
edtCoverage.Text := IntToStr(AValue);
if tbCoverage.Position<>AValue then
tbCoverage.Position := AValue;
finally
Dec(FIgnoreCoverageChange);
end;
if ARunTriggers then
UpdateWordCount;
end;
procedure TMainForm.tbCoverageChange(Sender: TObject);
begin
if FIgnoreCoverageChange>0 then exit;
SetCoverage(tbCoverage.Position);
end;
procedure TMainForm.edtCoverageChange(Sender: TObject);
var tmp: integer;
begin
if FIgnoreCoverageChange>0 then exit;
if TryStrToInt(edtCoverage.Text, tmp) then
SetCoverage(tmp);
end;
procedure TMainForm.edtCoverageExit(Sender: TObject);
begin
//Restore last working coverage if broken
SetCoverage(FCurCoverage, false);
end;
//Update WordCount value when Coverage changes
procedure TMainForm.UpdateWordCount;
var cnt: int64;
i: integer;
begin
cnt := 0;
i := FCutWordCount;
while i<wf.Count do begin
if (cnt * 100 / FTotalUncutCount) >= tbCoverage.Position then
break;
Inc(cnt, wf[i].count);
Inc(i);
end;
SetWordCount(i, false);
end;
end.
|
unit uCopyProgress;
{*******************************************************************************
* *
* Название модуля : *
* *
* uCopyProgress *
* *
* Назначение модуля : *
* *
* Визуализация процесса копирования файлов. *
* *
* Copyright © Год 2005, Автор: Найдёнов Е.А *
* *
*******************************************************************************}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxControls,
cxContainer, cxEdit, cxProgressBar;
type
TfmCopyProgress = class(TForm)
btnCancel : TcxButton;
lblTotal : TLabel;
lblCurrent : TLabel;
prbTotal : TcxProgressBar;
prbCurrent : TcxProgressBar;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
end.
|
unit Design;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
DesignSurface;
type
TDesignForm = class(TForm)
Designer: TDesignSurface;
procedure FormPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure DesignerControlAdded(Sender: TObject; inControl: TControl);
private
{ Private declarations }
protected
procedure SetParent(AParent: TWinControl); override;
public
{ Public declarations }
procedure LoadFromFile(const inFilename: string);
procedure SaveToFile(const inFilename: string);
procedure SetPageSize(inW, inH: Integer);
end;
var
DesignForm: TDesignForm;
implementation
uses
DesignUtils, DesignImp;
{$R *.dfm}
procedure TDesignForm.FormCreate(Sender: TObject);
begin
Designer.MessengerClass := TDesignWinControlHookMessenger;
Left := 12;
Top := 12;
end;
procedure TDesignForm.SetPageSize(inW, inH: Integer);
begin
if Parent <> nil then
begin
Parent.ClientWidth := inW + 12 + 12;
Parent.ClientHeight := inH + 12 + 12;
//SetBounds(12, 12, inW, inH);
end;
end;
procedure TDesignForm.FormPaint(Sender: TObject);
begin
DesignPaintRules(Canvas, ClientRect);
end;
procedure TDesignForm.FormResize(Sender: TObject);
begin
SetPageSize(Width, Height);
end;
procedure TDesignForm.SetParent(AParent: TWinControl);
begin
inherited;
SetPageSize(Width, Height);
end;
procedure TDesignForm.LoadFromFile(const inFilename: string);
begin
Designer := Designer.LoadFromFile(inFilename);
Name := 'DesignSurface';
end;
procedure TDesignForm.SaveToFile(const inFilename: string);
begin
Visible := false;
Designer.SaveToFile(inFilename);
Visible := true;
end;
procedure TDesignForm.DesignerControlAdded(Sender: TObject;
inControl: TControl);
begin
if inControl.Parent = Self then
inControl.Align := alTop;
end;
end.
|
unit Terminal_Settings;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Spin, SpinEx;
type
{ TTerminalSettings }
TTerminalSettings = class(TForm)
checkboxEnableLogging: TCheckBox;
checkboxEnableLocalEcho: TCheckBox;
checkboxEnableCrLf: TCheckBox;
comboboxColorType: TComboBox;
labelUpDownCharacterSize: TLabel;
groupboxColorType: TGroupBox;
groupboxCharacterSize: TGroupBox;
groupboxLogging: TGroupBox;
groupboxLocalEcho: TGroupBox;
groupboxCrLf: TGroupBox;
labelCharacterSize: TLabel;
labelTerminalType: TLabel;
panelLabelUpDown: TPanel;
panelCharacterSize: TPanel;
updownCharacterSize: TUpDown;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormShow(Sender: TObject);
procedure updownCharacterSizeClick(Sender: TObject; Button: TUDBtnType);
private
oldEnableCrLf: boolean;
oldEnableLocalEcho: boolean;
oldEnableLogging: boolean;
oldColorType: integer;
oldCharSize: integer;
public
end;
var
TerminalSettings: TTerminalSettings;
implementation
{$R *.lfm}
uses UscaleDPI, System_Settings, System_Terminal;
{ TTerminalSettings }
// --------------------------------------------------------------------------------
procedure TTerminalSettings.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
SystemSettings.saveFormState(TForm(self));
if (checkboxEnableCrLf.Checked <> oldEnableCrLf) then begin
SystemSettings.WriteBoolean('Terminal', 'UseCRLF', checkboxEnableCrLf.Checked);
SystemTerminal.setCrLF(checkboxEnableCrLf.Checked);
end;
if (checkboxEnableLocalEcho.Checked <> oldEnableLocalEcho) then begin
SystemSettings.WriteBoolean('Terminal', 'LocalEcho', checkboxEnableLocalEcho.Checked);
SystemTerminal.setLocalEcho(checkboxEnableLocalEcho.Checked);
end;
if (checkboxEnableLogging.Checked <> oldEnableLogging) then begin
SystemSettings.WriteBoolean('Terminal', 'Loggin', checkboxEnableLogging.Checked);
SystemTerminal.setLogging(checkboxEnableLogging.Checked);
end;
if (comboboxColorType.ItemIndex <> oldColorType) then begin
SystemSettings.WriteInteger('Terminal', 'ColorType', comboboxColorType.ItemIndex);
SystemTerminal.setColorType(comboboxColorType.ItemIndex);
end;
if (updownCharacterSize.Position <> oldCharSize) then begin
SystemSettings.WriteInteger('Terminal', 'CharacterSize', updownCharacterSize.Position);
SystemTerminal.SetCharSize(updownCharacterSize.Position);
end;
CloseAction := caFree;
end;
// --------------------------------------------------------------------------------
procedure TTerminalSettings.FormShow(Sender: TObject);
begin
SystemSettings.restoreFormState(TForm(self));
ScaleDPI(self, 96);
self.SetAutoSize(True);
Constraints.MinWidth := Width;
Constraints.MaxWidth := Width;
Constraints.MinHeight := Height;
Constraints.MaxHeight := Height;
panelLabelUpDown.Width := ((panelLabelUpDown.Height div 10) * 12);
oldEnableCrLf := SystemSettings.ReadBoolean('Terminal', 'UseCRLF', False);
checkboxEnableCrLf.Checked := oldEnableCrLf;
oldEnableLocalEcho := SystemSettings.ReadBoolean('Terminal', 'LocalEcho', False);
checkboxEnableLocalEcho.Checked := oldEnableLocalEcho;
oldEnableLogging := SystemSettings.ReadBoolean('Terminal', 'Loggin', False);
checkboxEnableLogging.Checked := oldEnableLogging;
oldColorType := SystemSettings.ReadInteger('Terminal', 'ColorType', 0);
comboboxColorType.ItemIndex := oldColorType;
oldCharSize := SystemSettings.ReadInteger('Terminal', 'CharacterSize', 10);
updownCharacterSize.Position := oldCharSize;
labelUpDownCharacterSize.Caption := IntToStr(oldCharSize);
end;
// --------------------------------------------------------------------------------
procedure TTerminalSettings.updownCharacterSizeClick(Sender: TObject; Button: TUDBtnType);
begin
labelUpDownCharacterSize.Caption := IntToStr(updownCharacterSize.Position);
end;
// --------------------------------------------------------------------------------
end.
|
unit Demo.Material.LineChart.DualY;
interface
uses
System.Classes, System.SysUtils, Demo.BaseFrame, cfs.GCharts;
type
TDemo_MaterialLineChart_DualY = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_MaterialLineChart_DualY.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_MATERIAL_LINE_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Month'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Average Temperature'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Average Hours of Daylight')
]);
Chart.Data.AddRow([EncodeDate(2014, 1, 1), -0.5, 5.7]);
Chart.Data.AddRow([EncodeDate(2014, 2, 1), 0.4, 8.7]);
Chart.Data.AddRow([EncodeDate(2014, 3, 1), 0.5, 12]);
Chart.Data.AddRow([EncodeDate(2014, 4, 1), 2.9, 15.3]);
Chart.Data.AddRow([EncodeDate(2014, 5, 1), 6.3, 18.6]);
Chart.Data.AddRow([EncodeDate(2014, 6, 1), 9, 20.9]);
Chart.Data.AddRow([EncodeDate(2014, 7, 1), 10.6, 19.8]);
Chart.Data.AddRow([EncodeDate(2014, 8, 1), 10.3, 16.6]);
Chart.Data.AddRow([EncodeDate(2014, 9, 1), 7.4, 13.3]);
Chart.Data.AddRow([EncodeDate(2014, 10, 1), 4.4, 9.9]);
Chart.Data.AddRow([EncodeDate(2014, 11, 1), 1.1, 6.6]);
Chart.Data.AddRow([EncodeDate(2014, 12, 1), -0.2, 4.5]);
// Options
Chart.Options.Title('Average Temperatures and Daylight in Iceland Throughout the Year');
Chart.Options.Series(['0: {targetAxisIndex: 0}', '1: {targetAxisIndex: 1}']);
Chart.Options.VAxes(['0: {title: ''Temps (Celsius)''}', '1: {title: ''Daylight''}']);
Chart.Options.VAxis('viewWindow', '{max: 30}');
Chart.Options.HAxis('ticks', '['
+ 'new Date(2014, 0), new Date(2014, 1), new Date(2014, 2), new Date(2014, 3),'
+ 'new Date(2014, 4), new Date(2014, 5), new Date(2014, 6), new Date(2014, 7),'
+ 'new Date(2014, 8), new Date(2014, 9), new Date(2014, 10), new Date(2014, 11)'
+ ']'
);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div style="width:80%; height:10%"></div>' +
'<div id="Chart" style="width:80%; height:80%;margin: auto"></div>' +
'<div style="width:80%; height:10%"></div>'
);
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_MaterialLineChart_DualY);
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clUtils;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARNINGS OFF}
{$ENDIF}
uses
Windows, Classes;
type
TCharSet = Set of Char;
TclByteArray = array of Byte;
TclBinaryData = class
private
FData: PByte;
FDataSize: Integer;
procedure Deallocate;
public
destructor Destroy; override;
procedure AssignByStrings(AStrings: TStrings);
procedure Allocate(ASize: Integer);
procedure Reduce(ANewSize: Integer);
property Data: PByte read FData;
property DataSize: Integer read FDataSize;
end;
PWideStringItem = ^TWideStringItem;
TWideStringItem = record
FString: WideString;
FObject: TObject;
end;
PWideStringItemList = ^TWideStringItemList;
TWideStringItemList = array[0..MaxListSize] of TWideStringItem;
TclWideStringList = class
private
FList: PWideStringItemList;
FCount: Integer;
FCapacity: Integer;
FSorted: Boolean;
FDuplicates: TDuplicates;
procedure SetSorted(const Value: Boolean);
procedure QuickSort(L, R: Integer);
procedure ExchangeItems(Index1, Index2: Integer);
procedure Grow;
protected
procedure Error(const Msg: string; Data: Integer);
function Get(Index: Integer): WideString; virtual;
function GetObject(Index: Integer): TObject; virtual;
procedure Put(Index: Integer; const S: WideString); virtual;
procedure PutObject(Index: Integer; AObject: TObject); virtual;
function CompareStrings(const S1, S2: WideString): Integer; virtual;
procedure InsertItem(Index: Integer; const S: WideString; AObject: TObject); virtual;
procedure SetCapacity(NewCapacity: Integer); virtual;
public
destructor Destroy; override;
function Add(const S: WideString): Integer; virtual;
function AddObject(const S: WideString; AObject: TObject): Integer; virtual;
procedure Clear; virtual;
procedure Delete(Index: Integer); virtual;
function Find(const S: WideString; var Index: Integer): Boolean; virtual;
function IndexOf(const S: WideString): Integer; virtual;
function IndexOfObject(AObject: TObject): Integer; virtual;
procedure Insert(Index: Integer; const S: WideString); virtual;
procedure InsertObject(Index: Integer; const S: WideString;
AObject: TObject); virtual;
procedure Move(CurIndex, NewIndex: Integer); virtual;
procedure Sort; virtual;
property Count: Integer read FCount;
property Objects[Index: Integer]: TObject read GetObject write PutObject;
property Strings[Index: Integer]: WideString read Get write Put; default;
property Duplicates: TDuplicates read FDuplicates write FDuplicates;
property Sorted: Boolean read FSorted write SetSorted;
end;
function AddTextStr(AList: TStrings; const Value: string; AddToLastString: Boolean = False): Boolean;
function AddTextStream(AList: TStrings; ASource: TStream;
AddToLastString: Boolean = False; ABatchSize: Integer = 0): Boolean;
function GetTextStr(AList: TStrings; AStartFrom, ACount: Integer): string;
procedure GetTopLines(ASource: TStream; ATopLines: Integer; AMessage: TStrings);
function GetStreamAsString(AStream: TStream; ASize: Integer; DefaultChar: Char): string;
function GetDataAsText(Data: PChar; Size: Integer; DefaultChar: Char): string;
function GetBinTextPos(const ASubStr: string; AData: PChar; ADataPos, ADataSize: Integer): Integer;
procedure ByteArrayWriteWord(AData: Word; var ADestination: TclByteArray; var AIndex: Integer);
function ByteArrayReadWord(const ASource: TclByteArray; var AIndex: Integer): Word;
function ByteArrayReadDWord(const ASource: TclByteArray; var AIndex: Integer): DWORD;
function MakeWord(AByte1, AByte2: Byte): Word;
function GetStringsSize(ALines: TStrings): Integer;
function FindInStrings(AList: TStrings; const Value: string): Integer;
procedure SetLocalFileTime(const AFileName: string; ADate: TDateTime);
function GetFullFileName(const AFileName, AFolder: string): string;
function ForceFileDirectories(const AFilePath: string): Boolean;
function DeleteRecursiveDir(const ARoot: string): Boolean;
function MakeRelativePath(const ABasePath, ARelativePath: string): string;
function GetUniqueFileName(const AFileName: string): string;
function AddTrailingBackSlash(const APath: string): string;
function NormalizeWin32Path(const APath: string; const AReplaceWith: string = '_'): string;
{$IFNDEF DELPHI6}
function DirectoryExists(const Directory: string): Boolean;
{$ENDIF}
function WordCount(const S: string; const WordDelims: TCharSet): Integer;
function WordPosition(const N: Integer; const S: string; const WordDelims: TCharSet): Integer;
function ExtractWord(N: Integer; const S: string; const WordDelims: TCharSet): string;
function ExtractNumeric(const ASource: string; AStartPos: Integer): string;
function ExtractQuotedString(const S: string; const AQuoteBegin: Char; const AQuoteEnd: Char = #0): string;
function GetNormName(const AName: string): string;
function GetDenormName(const AName: string): string;
function TextPos(const SubStr, Str: string; StartPos: Integer = 1): Integer;
function RTextPos(const SubStr, Str: String; StartPos: Integer = -1): Integer;
function ReversedString(const AStr: string): string;
function IndexOfStrArray(const S: string; AStrArray: array of string): Integer;
function GetHeaderFieldList(AStartFrom: Integer; ASource, AFieldList: TStrings): Integer;
function GetHeaderFieldValue(ASource, AFieldList: TStrings; const AName: string): string; overload;
function GetHeaderFieldValue(ASource, AFieldList: TStrings; AIndex: Integer): string; overload;
function GetHeaderFieldValueItem(const ASource, AItemName: string): string;
procedure AddHeaderArrayField(ASource: TStrings; const AValues: array of string;
const AName, ADelimiter: string);
procedure AddHeaderField(ASource: TStrings; const AName, AValue: string);
procedure RemoveHeaderField(ASource, AFieldList: TStrings; const AName: string); overload;
procedure RemoveHeaderField(ASource, AFieldList: TStrings; AIndex: Integer); overload;
procedure InsertHeaderFieldIfNeed(ASource: TStrings; const AName, AValue: string);
function GetCorrectY2k(const AYear : Integer): Integer;
function TimeZoneBiasString: string;
function TimeZoneBiasToDateTime(const ABias: string): TDateTime;
function GlobalTimeToLocalTime(ATime: TDateTime): TDateTime;
function LocalTimeToGlobalTime(ATime: TDateTime): TDateTime;
function ConvertFileTimeToDateTime(AFileTime: TFileTime): TDateTime;
function GetCurrentThreadUser: string;
const
cBatchSize = 8192;
cDays: array[1..7] of string = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
cMonths: array[1..12] of string = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
implementation
uses
SysUtils, {$IFDEF DELPHI6}RTLConsts{$ELSE}Consts{$ENDIF};
{$IFNDEF DELPHI6}
function CurrentYear: Word;
var
SystemTime: TSystemTime;
begin
GetLocalTime(SystemTime);
Result := SystemTime.wYear;
end;
{$ENDIF}
function TimeZoneBiasString: string;
var
TimeZoneInfo: TTimeZoneInformation;
TimeZoneID: DWORD;
Bias: Integer;
Sign: Char;
begin
Bias := 0;
TimeZoneID := GetTimeZoneInformation(TimeZoneInfo);
if (TimeZoneID <> TIME_ZONE_ID_INVALID) then
begin
if (TimeZoneID = TIME_ZONE_ID_DAYLIGHT) then
Bias := TimeZoneInfo.Bias + TimeZoneInfo.DaylightBias else
Bias := TimeZoneInfo.Bias;
end;
if (Bias > 0) then Sign := '-' else Sign := '+';
Result := Format('%s%.2d%.2d', [Sign, Abs(Bias) div 60, Abs(Bias) mod 60]);
end;
function TimeZoneBiasToDateTime(const ABias: string): TDateTime;
var
Sign: Char;
Hour, Min: Word;
begin
if (Length(ABias) > 4) and (ABias[1] in ['-', '+']) then
begin
Sign := ABias[1];
Hour := StrToIntDef(Copy(ABias, 2, 2), 0);
Min := StrToIntDef(Copy(ABias, 4, 2), 0);
{$IFDEF DELPHI6}
if not TryEncodeTime(Hour, Min, 0, 0, Result) then
begin
Result := 0;
end;
{$ELSE}
try
Result := EncodeTime(Hour, Min, 0, 0);
except
Result := 0;
end;
{$ENDIF}
if (Sign = '-') and (Result <> 0) then Result := - Result;
end else
begin
Result := 0;
end;
end;
function GlobalTimeToLocalTime(ATime: TDateTime): TDateTime;
var
ST: TSystemTime;
FT: TFileTime;
begin
DateTimeToSystemTime(ATime, ST);
SystemTimeToFileTime(ST, FT);
FileTimeToLocalFileTime(FT, FT);
FileTimeToSystemTime(FT, ST);
Result := SystemTimeToDateTime(ST);
end;
function LocalTimeToGlobalTime(ATime: TDateTime): TDateTime;
var
ST: TSystemTime;
FT: TFileTime;
begin
DateTimeToSystemTime(ATime, ST);
SystemTimeToFileTime(ST, FT);
LocalFileTimeToFileTime(FT, FT);
FileTimeToSystemTime(FT, ST);
Result := SystemTimeToDateTime(ST);
end;
function ConvertFileTimeToDateTime(AFileTime: TFileTime): TDateTime;
var
lpSystemTime: TSystemTime;
LocalFileTime: TFileTime;
begin
if FileTimeToLocalFileTime(AFileTime, LocalFileTime) then
begin
FileTimeToSystemTime(LocalFileTime, lpSystemTime);
Result := SystemTimeToDateTime(lpSystemTime);
end else
begin
Result := 0;
end;
end;
function GetCorrectY2k(const AYear : Integer): Integer;
begin
Result := AYear;
if (Result >= 100) then Exit;
if TwoDigitYearCenturyWindow > 0 then
begin
if Result > TwoDigitYearCenturyWindow then
begin
Result := Result + (((CurrentYear() div 100) - 1) * 100);
end else
begin
Result := Result + ((CurrentYear() div 100) * 100);
end;
end else
begin
Result := Result + ((CurrentYear() div 100) * 100);
end;
end;
{ TclBinaryData }
procedure TclBinaryData.Allocate(ASize: Integer);
begin
Deallocate();
FDataSize := ASize;
if (FDataSize > 0) then
begin
GetMem(FData, FDataSize);
end;
end;
procedure TclBinaryData.AssignByStrings(AStrings: TStrings);
var
I, L, Size: Integer;
P: PChar;
S, LB: string;
begin
Size := 0;
LB := #13#10;
for I := 0 to AStrings.Count - 1 do
begin
Inc(Size, Length(AStrings[I]) + Length(LB));
end;
if (Size > 0) then
begin
Size := Size - Length(LB);
end;
Allocate(Size);
P := Pointer(Data);
for I := 0 to AStrings.Count - 1 do
begin
S := AStrings[I];
L := Length(S);
if L <> 0 then
begin
System.Move(Pointer(S)^, P^, L);
Inc(P, L);
end;
L := Length(LB);
if (L <> 0) and (I <> AStrings.Count - 1) then
begin
System.Move(Pointer(LB)^, P^, L);
Inc(P, L);
end;
end;
end;
procedure TclBinaryData.Deallocate;
begin
FreeMem(FData);
FData := nil;
FDataSize := 0;
end;
destructor TclBinaryData.Destroy;
begin
Deallocate();
inherited Destroy();
end;
procedure TclBinaryData.Reduce(ANewSize: Integer);
begin
if (FDataSize > ANewSize) then
begin
FDataSize := ANewSize;
end;
end;
function GetDelimitedValue(const ASource, AStartLexem: string): string;
var
i, ind: Integer;
inCommas: Boolean;
commaChar: string;
begin
if (AStartLexem = '') and (ASource <> '') then
begin
ind := 1;
end else
begin
ind := system.Pos(AStartLexem, LowerCase(ASource));
end;
if (ind > 0) then
begin
Result := system.Copy(ASource, ind + Length(AStartLexem), 1000);
inCommas := False;
commaChar := '';
for i := 1 to Length(Result) do
begin
if (commaChar = '') and (Result[i] in ['''', '"']) then
begin
commaChar := Result[i];
inCommas := not inCommas;
end else
if (commaChar <> '') and (Result[i] = commaChar[1]) then
begin
inCommas := not inCommas;
end;
if (not inCommas) and (Result[i] in [';', ',']) then
begin
Result := system.Copy(Result, 1, i - 1);
Break;
end;
end;
end else
begin
Result := '';
end;
end;
function GetHeaderFieldValueItem(const ASource, AItemName: string): string;
var
s: string;
begin
s := Trim(GetDelimitedValue(ASource, AItemName));
if (s <> '') and (s[1] in ['''', '"']) and (s[Length(s)] in ['''', '"']) then
begin
Result := System.Copy(s, 2, Length(s) - 2);
end else
begin
Result := s;
end;
end;
function AddTextStr(AList: TStrings; const Value: string; AddToLastString: Boolean): Boolean;
var
P, Start: PChar;
S: string;
b: Boolean;
begin
b := AddToLastString;
AList.BeginUpdate;
try
P := Pointer(Value);
if P <> nil then
begin
while P^ <> #0 do
begin
Start := P;
while not (P^ in [#0, #10, #13]) do Inc(P);
SetString(S, Start, P - Start);
if b and (AList.Count > 0) then
begin
AList[AList.Count - 1] := AList[AList.Count - 1] + S;
b := False;
end else
begin
AList.Add(S);
end;
if P^ = #13 then Inc(P);
if P^ = #10 then Inc(P);
end;
Result := ((Length(Value) = 1) and (Value[1] <> #10))
or ((Length(Value) > 1) and ((P - 2)^ <> #13) and ((P - 1)^ <> #10));
end else
begin
Result := False;
end;
finally
AList.EndUpdate;
end;
end;
function AddTextStrCount(AList: TStrings; const Value: string;
var AddToLastString: Boolean; var AHeadCount: Integer; ALinesCount: Integer): Boolean;
var
P, Start: PChar;
S: string;
b: Boolean;
begin
b := AddToLastString;
P := Pointer(Value);
AddToLastString := False;
Result := False;
if (P <> nil) then
begin
while (not Result) and (P^ <> #0) do
begin
Start := P;
while not (P^ in [#0, #10, #13]) do Inc(P);
SetString(S, Start, P - Start);
if b and (AList.Count > 0) then
begin
AList[AList.Count - 1] := AList[AList.Count - 1] + S;
b := False;
end else
begin
AList.Add(S);
end;
if (Length(AList[AList.Count - 1]) = 0) and (AHeadCount = 0) then
begin
AHeadCount := AList.Count;
end;
Result := (AHeadCount > 0) and (AList.Count >= AHeadCount + ALinesCount);
if P^ = #13 then Inc(P);
if P^ = #10 then Inc(P);
end;
AddToLastString := (Length(Value) > 1) and ((P - 2)^ <> #13) and ((P - 1)^ <> #10);
end;
end;
procedure GetTopLines(ASource: TStream; ATopLines: Integer; AMessage: TStrings);
var
buf: string;
bufSize, bytesRead, headCount: Integer;
addToLastSring: Boolean;
begin
AMessage.BeginUpdate();
try
AMessage.Clear();
bufSize := ASource.Size - ASource.Position;
if (bufSize > 76) then
begin
bufSize := 76;
end;
headCount := 0;
addToLastSring := False;
repeat
SetString(buf, nil, bufSize);
bytesRead := ASource.Read(Pointer(buf)^, bufSize);
if bytesRead = 0 then Break;
SetLength(buf, bytesRead);
until AddTextStrCount(AMessage, buf, addToLastSring, headCount, ATopLines);
finally
AMessage.EndUpdate();
end;
end;
function AddTextStream(AList: TStrings; ASource: TStream; AddToLastString: Boolean;
ABatchSize: Integer): Boolean;
var
size: Integer;
p: PChar;
i, cnt: Integer;
begin
size := ASource.Size - ASource.Position;
if (size > ABatchSize) and (ABatchSize > 0) then
begin
size := ABatchSize;
end;
GetMem(p, size + 1);
try
Result := AddToLastString;
cnt := ASource.Read(p^, size);
while (cnt > 0) do
begin
for i := 0 to cnt - 1 do
begin
if p[i] = #0 then
begin
p[i] := #32;
end;
end;
p[cnt] := #0;
Result := AddTextStr(AList, string(p), Result);
cnt := ASource.Read(p^, size);
end;
finally
FreeMem(p);
end;
end;
function GetTextStr(AList: TStrings; AStartFrom, ACount: Integer): string;
const
LB = #13#10;
var
I, L, Size, Count: Integer;
P: PChar;
S: string;
begin
Count := ACount;
if (Count > AList.Count - AStartFrom) then
begin
Count := AList.Count - AStartFrom;
end;
Size := 0;
for I := 0 to Count - 1 do Inc(Size, Length(AList[I + AStartFrom]) + Length(LB));
SetString(Result, nil, Size);
P := Pointer(Result);
for I := 0 to Count - 1 do
begin
S := AList[I + AStartFrom];
L := Length(S);
if L <> 0 then
begin
System.Move(Pointer(S)^, P^, L);
Inc(P, L);
end;
L := Length(LB);
if L <> 0 then
begin
System.Move(LB, P^, L);
Inc(P, L);
end;
end;
end;
const
SpecialSymbols = ['\', '"', '(', ')'];
function GetNormName(const AName: string): string;
function GetSymbolsTotalCount(const AValue: String; ASymbolsSet: TCharSet): Integer;
var
i: Integer;
begin
Result := 0;
for i := 1 to Length(AValue) do
begin
if (AValue[i] in ASymbolsSet) then Inc(Result);
end;
end;
var
i, j, SpecialCount: Integer;
begin
SpecialCount := GetSymbolsTotalCount(AName, SpecialSymbols);
if (SpecialCount > 0) then
begin
SetLength(Result, SpecialCount + Length(AName));
j := 0;
for i := 1 to Length(AName) do
begin
Inc(j);
if (AName[i] in SpecialSymbols) then
begin
Result[j] := '\';
Inc(j);
end;
Result[j] := AName[i];
end;
Result := '"' + Result + '"';
end else
begin
Result := AName;
end;
if (system.Pos(' ', Result) > 0)
and (Result[1] <> '"') and (Result[Length(Result)] <> '"') then
begin
Result := '"' + Result + '"';
end;
end;
function GetDenormName(const AName: string): string;
var
i, j: Integer;
Len: Integer;
SpecSymExpect: Boolean;
Sym: Char;
begin
SpecSymExpect := False;
Len := Length(AName);
SetLength(Result, Len);
i := 1;
j := 1;
while (i <= Length(AName)) do
begin
Sym := AName[i];
case Sym of
'\':
begin
if not SpecSymExpect then
begin
SpecSymExpect := True;
Inc(i);
Continue;
end;
end;
'"':
begin
if not SpecSymExpect then
begin
Sym := ' ';
end;
end;
end;
SpecSymExpect := False;
Result[j] := Sym;
Inc(j);
Inc(i);
end;
SetLength(Result, j - 1);
end;
function TextPos(const SubStr, Str: string; StartPos: Integer): Integer;
var
PosRes, StrLen: Integer;
s: string;
begin
Result := 0;
StrLen := Length(Str);
if (StartPos < 1) or (StartPos > StrLen) then Exit;
s := system.Copy(Str, StartPos, StrLen);
PosRes := system.Pos(SubStr, s);
if (PosRes <> 0) then Result := StartPos + PosRes - 1;
end;
function RTextPos(const SubStr, Str: String; StartPos: Integer = -1): Integer;
var
i, len: Integer;
begin
Result := 0;
len := Length(SubStr);
if StartPos = -1 then
begin
StartPos := Length(Str);
end;
if StartPos >= (Length(Str) - len + 1) then
begin
StartPos := (Length(Str) - len + 1);
end;
for i := StartPos downto 1 do
begin
if SameText(Copy(Str, i, len), SubStr) then
begin
Result := i;
Break;
end;
end;
end;
function WordCount(const S: string; const WordDelims: TCharSet): Integer;
var
SLen, I: Cardinal;
begin
Result := 0;
I := 1;
SLen := Length(S);
while I <= SLen do
begin
while (I <= SLen) and (S[I] in WordDelims) do Inc(I);
if I <= SLen then Inc(Result);
while (I <= SLen) and not(S[I] in WordDelims) do Inc(I);
end;
end;
function WordPosition(const N: Integer; const S: string;
const WordDelims: TCharSet): Integer;
var
Count, I: Integer;
begin
Count := 0;
I := 1;
Result := 0;
while (I <= Length(S)) and (Count <> N) do
begin
while (I <= Length(S)) and (S[I] in WordDelims) do Inc(I);
if I <= Length(S) then Inc(Count);
if Count <> N then
while (I <= Length(S)) and not (S[I] in WordDelims) do Inc(I)
else Result := I;
end;
end;
function ExtractWord(N: Integer; const S: string;
const WordDelims: TCharSet): string;
var
I: Word;
Len: Integer;
begin
Len := 0;
I := WordPosition(N, S, WordDelims);
if I <> 0 then
begin
while (I <= Length(S)) and not(S[I] in WordDelims) do
begin
Inc(Len);
SetLength(Result, Len);
Result[Len] := S[I];
Inc(I);
end;
end;
SetLength(Result, Len);
end;
function ExtractQuotedString(const S: string; const AQuoteBegin: Char; const AQuoteEnd: Char): string;
var
q: Char;
begin
Result := S;
if Length(Result) < 2 then Exit;
q := AQuoteEnd;
if (AQuoteEnd = #0) then
begin
q := AQuoteBegin;
end;
if ((Result[1] = AQuoteBegin) and (Result[Length(Result)] = q)) then
begin
Result := System.Copy(Result, 2, Length(Result) - 2);
end;
end;
function ExtractNumeric(const ASource: string; AStartPos: Integer): string;
var
ind: Integer;
begin
ind := AStartPos;
while ((ind <= Length(ASource)) and (ASource[ind] in ['0'..'9'])) do
begin
Inc(ind);
end;
Result := system.Copy(ASource, AStartPos, ind - AStartPos);
end;
function GetStreamAsString(AStream: TStream; ASize: Integer; DefaultChar: Char): string;
var
p: PChar;
StreamPos: Integer;
begin
StreamPos := AStream.Position;
if (ASize = 0) or (ASize > AStream.Size) then
begin
ASize := AStream.Size;
end;
GetMem(p, ASize + 1);
try
AStream.Position := 0;
ZeroMemory(p, ASize + 1);
AStream.Read(p^, ASize);
Result := GetDataAsText(p, ASize, DefaultChar);
finally
FreeMem(p);
AStream.Position := StreamPos;
end;
end;
procedure SetLocalFileTime(const AFileName: string; ADate: TDateTime);
var
hFile: THandle;
filedate: TFileTime;
sysdate: TSystemTime;
begin
hFile := CreateFile(PChar(AFileName), GENERIC_WRITE, FILE_SHARE_READ, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile <> INVALID_HANDLE_VALUE) then
begin
DateTimeToSystemTime(ADate, sysdate);
SystemTimeToFileTime(sysdate, filedate);
LocalFileTimeToFileTime(filedate, filedate);
SetFileTime(hFile, @filedate, @filedate, @filedate);
CloseHandle(hFile);
end;
end;
function GetFullFileName(const AFileName, AFolder: string): string;
begin
Result := AddTrailingBackSlash(AFolder) + ExtractFileName(AFileName);
end;
function GetDataAsText(Data: PChar; Size: Integer; DefaultChar: Char): string;
var
i: Integer;
begin
Result := '';
for i := 0 to Size - 1 do
begin
if (Ord(Data[i]) < 32) and not (Ord(Data[i]) in [9, 10, 13]) then
begin
Result := Result + DefaultChar;
end else
begin
Result := Result + Data[i];
end;
end;
end;
{$IFNDEF DELPHI5}
function ExcludeTrailingBackslash(const S: string): string;
begin
Result := S;
if IsPathDelimiter(Result, Length(Result)) then
SetLength(Result, Length(Result)-1);
end;
{$ENDIF}
function ForceFileDirectories(const AFilePath: string): Boolean;
function ForceDirs(Dir: String): Boolean;
begin
Result := True;
if Length(Dir) = 0 then Exit;
Dir := ExcludeTrailingBackslash(Dir);
if (Length(Dir) < 3) or DirectoryExists(Dir)
or (ExtractFilePath(Dir) = Dir) then Exit; // avoid 'xyz:\' problem.
Result := ForceDirs(ExtractFilePath(Dir)) and CreateDir(Dir);
end;
begin
Result := ForceDirs(ExtractFilePath(AFilePath));
end;
function DeleteRecursiveDir(const ARoot: string): Boolean;
var
root: string;
sr: TSearchRec;
begin
root := ExcludeTrailingBackslash(ARoot);
if FindFirst(root + '\*.*', faAnyFile, sr) = 0 then
begin
repeat
if (sr.Name <> '.') and (sr.Name <> '..') then
begin
if (sr.Attr and faDirectory) > 0 then
begin
DeleteRecursiveDir(root + '\' + sr.Name);
end else
begin
DeleteFile(root + '\' + sr.Name);
end;
end;
until FindNext(sr) <> 0;
FindClose(sr);
end;
Result := RemoveDir(ARoot);
end;
function GetHeaderFieldList(AStartFrom: Integer; ASource, AFieldList: TStrings): Integer;
var
ind: Integer;
begin
Result := AStartFrom;
while (Result < ASource.Count) and (ASource[Result] <> '') do
begin
if not (ASource[Result][1] in [#9, #32]) then
begin
ind := system.Pos(':', ASource[Result]);
if (ind > 0) then
begin
AFieldList.AddObject(LowerCase(system.Copy(ASource[Result], 1, ind - 1)), TObject(Result));
end;
end;
Inc(Result);
end;
end;
function GetHeaderFieldValue(ASource, AFieldList: TStrings; const AName: string): string;
begin
Result := GetHeaderFieldValue(ASource, AFieldList, AFieldList.IndexOf(LowerCase(AName)));
end;
function GetHeaderFieldValue(ASource, AFieldList: TStrings; AIndex: Integer): string;
var
Ind, i: Integer;
begin
if (AIndex > -1) and (AIndex < AFieldList.Count) then
begin
Ind := Integer(AFieldList.Objects[AIndex]);
Result := system.Copy(ASource[Ind], Length(AFieldList[AIndex] + ':') + 1, 1000);
Result := TrimLeft(Result);
for i := Ind + 1 to ASource.Count - 1 do
begin
if not ((ASource[i] <> '') and (ASource[i][1] in [#9, #32])) then
begin
Break;
end;
Result := Result + Trim(ASource[i]);
end;
end else
begin
Result := '';
end;
end;
procedure AddHeaderMultiField(ASource, AValues: TStrings; const AName, ADelimiter: string);
var
i: Integer;
Comma: array[Boolean] of string;
begin
if (AValues.Count > 0) then
begin
Comma[False] := '';
Comma[True] := ADelimiter;
AddHeaderField(ASource, AName, AValues[0] + Comma[AValues.Count > 1]);
for i := 1 to AValues.Count - 1 do
begin
ASource.Add(#9 + AValues[i] + Comma[i < (AValues.Count - 1)]);
end;
end;
end;
procedure AddHeaderArrayField(ASource: TStrings; const AValues: array of string;
const AName, ADelimiter: string);
var
i: Integer;
List: TStrings;
begin
List := TStringList.Create();
try
for i := Low(AValues) to High(AValues) do
begin
List.Add(AValues[i]);
end;
AddHeaderMultiField(ASource, List, AName, ADelimiter);
finally
List.Free();
end;
end;
procedure AddHeaderField(ASource: TStrings; const AName, AValue: string);
var
NormValue: string;
begin
if (AValue <> '') then
begin
NormValue := StringReplace(AValue, #13#10, #13#10#9, [rfReplaceAll]);
if (NormValue <> '') and (NormValue[Length(NormValue)] = #9) then
begin
system.Delete(NormValue, Length(NormValue), 1);
end;
AddTextStr(ASource, Format('%s: %s', [AName, NormValue]));
end;
end;
procedure RemoveHeaderField(ASource, AFieldList: TStrings; const AName: string);
begin
RemoveHeaderField(ASource, AFieldList, AFieldList.IndexOf(LowerCase(AName)));
end;
procedure RemoveHeaderField(ASource, AFieldList: TStrings; AIndex: Integer); overload;
var
i: Integer;
begin
if (AIndex > -1) then
begin
i := Integer(AFieldList.Objects[AIndex]);
ASource.Delete(i);
while (i < ASource.Count) do
begin
if (Length(ASource[i]) > 0) and (ASource[i][1] in [#9, #32]) then
begin
ASource.Delete(i);
end else
begin
Break;
end;
end;
end;
end;
procedure InsertHeaderFieldIfNeed(ASource: TStrings; const AName, AValue: string);
var
ind: Integer;
fieldList: TStrings;
begin
if (AValue = '') then Exit;
fieldList := TStringList.Create();
try
ind := GetHeaderFieldList(0, ASource, fieldList);
if (fieldList.IndexOf(LowerCase(AName)) < 0) then
begin
if (ind < 0) or (ind > ASource.Count) then
begin
ind := ASource.Count;
end;
Assert(system.Pos(#13#10, AValue) < 1);
ASource.Insert(ind, Format('%s: %s', [AName, AValue]));
end;
finally
fieldList.Free();
end;
end;
function IndexOfStrArray(const S: string; AStrArray: array of string): Integer;
begin
for Result := Low(AStrArray) to High(AStrArray) do
begin
if (CompareText(AStrArray[Result], S) = 0) then Exit;
end;
Result := -1;
end;
function ReversedString(const AStr: string): string;
var
I: Integer;
P: PChar;
begin
SetLength(Result, Length(AStr));
P := PChar(Result);
for I := Length(AStr) downto 1 do
begin
P^ := AStr[I];
Inc(P);
end;
end;
function MakeRelativePath(const ABasePath, ARelativePath: string): string;
procedure GetPathList(const APath: string; AList: TStrings);
var
i: Integer;
s: string;
begin
s := '';
AList.Clear();
for i := Length(APath) downto 1 do
begin
if (APath[i] = '\') then
begin
if (s <> '') then
begin
AList.Add(s);
end;
s := '';
end else
begin
s := APath[i] + s;
end;
end;
if (s <> '') then
begin
AList.Add(s);
end;
end;
function MatchPathLists(ABaseList, ARelList: TStrings): string;
var
i, j: Integer;
begin
Result := '';
i := ABaseList.Count - 1;
j := ARelList.Count - 1;
while (i >= 0) and (j >= 0) and (ABaseList[i] = ARelList[j]) do
begin
Dec(i);
Dec(j);
end;
while (i >= 0) do
begin
Result := Result + '..\';
Dec(i);
end;
while (j >= 1) do
begin
Result := Result + ARelList[j] + '\';
Dec(j);
end;
Result := Result + ARelList[j];
end;
var
baseList, relList: TStrings;
begin
Result := '';
baseList := nil;
relList := nil;
try
baseList := TStringList.Create();
relList := TStringList.Create();
GetPathList(ExtractFilePath(ABasePath), baseList);
GetPathList(ARelativePath, relList);
Result := MatchPathLists(baseList, relList);
finally
relList.Free();
baseList.Free();
end;
end;
function GetUniqueFileName(const AFileName: string): string;
var
s: string;
i, ind: Integer;
begin
i := 1;
Result := AFileName;
s := Result;
ind := RTextPos('.', s);
if (ind < 1) then
begin
s := s + '.';
ind := Length(s);
end;
while FileExists(Result) do
begin
Result := system.Copy(s, 1, ind - 1) + Format('%d', [i]) + system.Copy(s, ind, Length(s));
Inc(i);
end;
if (Length(Result) > 0) and (Result[Length(Result)] = '.') then
begin
system.Delete(Result, Length(Result), 1);
end;
end;
function AddTrailingBackSlash(const APath: string): string;
begin
Result := APath;
if (Result <> '') and (Result[Length(Result)] <> '\') then
begin
Result := Result + '\';
end;
end;
function NormalizeWin32Path(const APath: string; const AReplaceWith: string): string;
const
invalidChars: set of Char = ['"', '*', '/', ':', '<', '>', '?', '\', '|', #0];
invalidLastChars: set of Char = [' ', '.'];
var
i: Integer;
begin
Result := '';
for i := 1 to Length(APath) do
begin
if (APath[i] in invalidChars) then
begin
Result := Result + AReplaceWith;
end else
begin
Result := Result + APath[i];
end;
end;
if (Length(Result) > 0) and (Result[Length(Result)] in invalidLastChars) then
begin
Delete(Result, Length(Result), 1);
if (Result = '') then
begin
Result := '_';
end;
end;
end;
{$IFNDEF DELPHI6}
function DirectoryExists(const Directory: string): Boolean;
var
Code: Integer;
begin
Code := GetFileAttributes(PChar(Directory));
Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0);
end;
{$ENDIF}
procedure ByteArrayWriteWord(AData: Word; var ADestination: TclByteArray; var AIndex: Integer);
begin
ADestination[AIndex] := AData div 256;
Inc(AIndex);
ADestination[AIndex] := AData mod 256;
Inc(AIndex);
end;
function ByteArrayReadWord(const ASource: TclByteArray; var AIndex: Integer): Word;
begin
Result := ASource[AIndex] shl 8;
Inc(AIndex);
Result := Result or ASource[AIndex];
Inc(AIndex);
end;
function ByteArrayReadDWord(const ASource: TclByteArray; var AIndex: Integer): DWORD;
begin
Result := ByteArrayReadWord(ASource, AIndex) shl 16;
Result := Result or ByteArrayReadWord(ASource, AIndex);
end;
function MakeWord(AByte1, AByte2: Byte): Word;
var
arr: array[0..1] of Byte;
begin
arr[1] := AByte1;
arr[0] := AByte2;
Result := PWORD(@arr[0])^;
end;
function GetBinTextPos(const ASubStr: string; AData: PChar; ADataPos, ADataSize: Integer): Integer;
var
i, curPos, endPos: Integer;
begin
curPos := 1;
endPos := Length(ASubStr) + 1;
for i := ADataPos to ADataSize - 1 do
begin
if (PChar(Integer(AData) + i)^ = ASubStr[curPos]) then
begin
Inc(curPos);
end else
begin
curPos := 1;
Continue;
end;
if (Curpos = endPos) then
begin
Result := i - endPos + 2;
Exit;
end;
end;
Result := -1;
end;
function GetStringsSize(ALines: TStrings): Integer;
const
cCRLF = #13#10;
var
i: Integer;
begin
Result := 0;
for i := 0 to ALines.Count - 1 do
begin
Result := Result + Length(ALines[i]) + Length(cCRLF);
end;
end;
function FindInStrings(AList: TStrings; const Value: string): Integer;
var
i: Integer;
begin
for i := 0 to AList.Count - 1 do
begin
if SameText(Value, AList[i]) then
begin
Result := i;
Exit;
end;
end;
Result := -1;
end;
function GetCurrentThreadUser: string;
var
p: PChar;
size: DWORD;
begin
Result := '';
size := 0;
GetUserName(nil, size);
if (size < 1) then Exit;
GetMem(p, size + 1);
try
if GetUserName(p, size) then
begin
Result := string(p);
end;
finally
FreeMem(p);
end;
end;
{ TclWideStringList }
function TclWideStringList.Add(const S: WideString): Integer;
begin
Result := AddObject(S, nil);
end;
function TclWideStringList.AddObject(const S: WideString; AObject: TObject): Integer;
begin
if not Sorted then
begin
Result := FCount
end else
if Find(S, Result) then
begin
case Duplicates of
dupIgnore: Exit;
dupError: Error(SDuplicateString, 0);
end;
end;
InsertItem(Result, S, AObject);
end;
procedure TclWideStringList.Clear;
begin
if FCount <> 0 then
begin
Finalize(FList^[0], FCount);
FCount := 0;
SetCapacity(0);
end;
end;
function TclWideStringList.CompareStrings(const S1, S2: WideString): Integer;
begin
if (S1 > S2) then
begin
Result := 1;
end else
if (S1 < S2) then
begin
Result := -1;
end else
begin
Result := 0;
end;
end;
procedure TclWideStringList.Delete(Index: Integer);
begin
if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index);
Finalize(FList^[Index]);
Dec(FCount);
if Index < FCount then
begin
System.Move(FList^[Index + 1], FList^[Index],
(FCount - Index) * SizeOf(TWideStringItem));
end;
end;
destructor TclWideStringList.Destroy;
begin
inherited Destroy();
if FCount <> 0 then Finalize(FList^[0], FCount);
FCount := 0;
SetCapacity(0);
end;
procedure TclWideStringList.Error(const Msg: string; Data: Integer);
function ReturnAddr: Pointer;
asm
MOV EAX,[EBP+4]
end;
begin
raise EStringListError.CreateFmt(Msg, [Data]) at ReturnAddr;
end;
procedure TclWideStringList.ExchangeItems(Index1, Index2: Integer);
var
Temp: Integer;
Item1, Item2: PWideStringItem;
begin
Item1 := @FList^[Index1];
Item2 := @FList^[Index2];
Temp := Integer(Item1^.FString);
Integer(Item1^.FString) := Integer(Item2^.FString);
Integer(Item2^.FString) := Temp;
Temp := Integer(Item1^.FObject);
Integer(Item1^.FObject) := Integer(Item2^.FObject);
Integer(Item2^.FObject) := Temp;
end;
function TclWideStringList.Find(const S: WideString; var Index: Integer): Boolean;
var
L, H, I, C: Integer;
begin
Result := False;
L := 0;
H := FCount - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := CompareStrings(FList^[I].FString, S);
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
if Duplicates <> dupAccept then L := I;
end;
end;
end;
Index := L;
end;
function TclWideStringList.Get(Index: Integer): WideString;
begin
if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index);
Result := FList^[Index].FString;
end;
function TclWideStringList.GetObject(Index: Integer): TObject;
begin
if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index);
Result := FList^[Index].FObject;
end;
procedure TclWideStringList.Grow;
var
Delta: Integer;
begin
if FCapacity > 256 then
begin
Delta := FCapacity div 4;
end else
begin
Delta := 64;
end;
SetCapacity(FCapacity + Delta);
end;
function TclWideStringList.IndexOf(const S: WideString): Integer;
begin
if not Sorted then
begin
for Result := 0 to Count - 1 do
begin
if CompareStrings(Get(Result), S) = 0 then Exit;
end;
Result := -1;
end else
if not Find(S, Result) then
begin
Result := -1;
end;
end;
function TclWideStringList.IndexOfObject(AObject: TObject): Integer;
begin
for Result := 0 to Count - 1 do
begin
if GetObject(Result) = AObject then Exit;
end;
Result := -1;
end;
procedure TclWideStringList.Insert(Index: Integer; const S: WideString);
begin
InsertObject(Index, S, nil);
end;
procedure TclWideStringList.InsertItem(Index: Integer; const S: WideString; AObject: TObject);
begin
if FCount = FCapacity then Grow();
if Index < FCount then
begin
System.Move(FList^[Index], FList^[Index + 1],
(FCount - Index) * SizeOf(TWideStringItem));
end;
with FList^[Index] do
begin
Pointer(FString) := nil;
FObject := AObject;
FString := S;
end;
Inc(FCount);
end;
procedure TclWideStringList.InsertObject(Index: Integer;
const S: WideString; AObject: TObject);
begin
if Sorted then
begin
Error(SSortedListError, 0);
end;
if (Index < 0) or (Index > FCount) then
begin
Error(SListIndexError, Index);
end;
InsertItem(Index, S, AObject);
end;
procedure TclWideStringList.Move(CurIndex, NewIndex: Integer);
var
TempObject: TObject;
TempString: WideString;
begin
if CurIndex <> NewIndex then
begin
TempString := Get(CurIndex);
TempObject := GetObject(CurIndex);
Delete(CurIndex);
InsertObject(NewIndex, TempString, TempObject);
end;
end;
procedure TclWideStringList.Put(Index: Integer; const S: WideString);
begin
if Sorted then Error(SSortedListError, 0);
if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index);
FList^[Index].FString := S;
end;
procedure TclWideStringList.PutObject(Index: Integer; AObject: TObject);
begin
if (Index < 0) or (Index >= FCount) then Error(SListIndexError, Index);
FList^[Index].FObject := AObject;
end;
function WideCompare(List: TclWideStringList; Index1, Index2: Integer): Integer;
begin
Result := List.CompareStrings(List.FList^[Index1].FString,
List.FList^[Index2].FString);
end;
procedure TclWideStringList.QuickSort(L, R: Integer);
var
I, J, P: Integer;
begin
repeat
I := L;
J := R;
P := (L + R) shr 1;
repeat
while WideCompare(Self, I, P) < 0 do Inc(I);
while WideCompare(Self, J, P) > 0 do Dec(J);
if I <= J then
begin
ExchangeItems(I, J);
if P = I then
P := J
else if P = J then
P := I;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then QuickSort(L, J);
L := I;
until I >= R;
end;
procedure TclWideStringList.SetCapacity(NewCapacity: Integer);
begin
ReallocMem(FList, NewCapacity * SizeOf(TWideStringItem));
FCapacity := NewCapacity;
end;
procedure TclWideStringList.SetSorted(const Value: Boolean);
begin
if FSorted <> Value then
begin
if Value then Sort();
FSorted := Value;
end;
end;
procedure TclWideStringList.Sort;
begin
if not Sorted and (FCount > 1) then
begin
QuickSort(0, FCount - 1);
end;
end;
end.
|
unit OpenCLLauncher;
interface
uses Windows, SysUtils, dglOpenGL, CL, cl_platform, oclUtils, BasicDataTypes, Debug;
type
TOpenCLLauncher = class
private
FCurrent_indevice: Integer;
FContext: PCL_context;
FSource: PAnsiChar;
FProgram_: PCL_program;
FCommandQueue: PCL_command_queue;
FIsLoaded: boolean;
FKernel: array of PCL_kernel;
FCurrentKernel: integer;
FDebugFile: TDebugFile;
FHasDebugFile: boolean;
FProgramName: string;
FKernelName: AString;
FMem: array of PCL_mem;
FFlags: array of boolean;
// Constructors and Destructors
procedure InitializeClass;
procedure InitializeContext;
function GetDriver: AnsiString;
procedure ClearContext;
// I/O
procedure ClearProgram;
// Sets
procedure SetCurrentKernel(_value: integer);
// Execute
function VerifyKernelParameters(const _InputData: APointer; const _InputSize,_InputUnitSize: Auint32; var _OutputData: APointer; const _OutputSize,_OutputUnitSize: AUint32; const _OutputSource: aint32; _NumDimensions: TCL_int; const _GlobalWorkSize,_LocalWorkSize: Auint32): boolean;
// Misc
procedure ClearGPUBuffers;
procedure WriteDebug(const _Text: string);
public
// Constructors and Destructors
constructor Create; overload;
constructor Create(const _FileName, _KernelName: string); overload;
destructor Destroy; override;
// I/O
procedure LoadProgram(const _FileName, _KernelName: string); overload;
procedure LoadProgram(const _FileName: string; const _KernelNames: AString); overload;
procedure LoadDataIntoGPU(const _InputData: APointer; const _InputSize,_InputUnitSize: Auint32; var _OutputData: APointer; const _OutputSource: aint32); overload;
procedure LoadDataIntoGPU(_ID: integer; _ReadWrite: boolean; const _InputData: Pointer; const _InputSize,_InputUnitSize: longword; var _OutputData: APointer); overload;
procedure SaveDataFromGPU(const _InputData: APointer; const _InputSize: Auint32; var _OutputData: APointer; const _OutputSize,_OutputUnitSize: AUint32; const _OutputSource: aint32); overload;
procedure SaveDataFromGPU(const _InputData: Pointer; const _InputSize: longword; var _OutputData: Pointer; const _OutputSize,_OutputUnitSize: longword; const _OutputSource: integer); overload;
// Execute
procedure RunKernel(const _InputData: APointer; const _InputSize,_InputUnitSize: Auint32; var _OutputData: APointer; const _OutputSize,_OutputUnitSize: AUint32; const _OutputSource: aint32; _NumDimensions: TCL_int; const _GlobalWorkSize,_LocalWorkSize: Auint32); overload;
procedure RunKernel(const _InputData: APointer; const _InputSize,_InputUnitSize: Auint32; const _OutputSource: aint32; _NumDimensions: TCL_int; const _GlobalWorkSize,_LocalWorkSize: Auint32); overload;
procedure RunKernel(_NumDimensions: TCL_int; const _GlobalWorkSize,_LocalWorkSize: Auint32); overload;
procedure RunKernelSafe(const _InputData: APointer; const _InputSize,_InputUnitSize: Auint32; var _OutputData: APointer; const _OutputSize,_OutputUnitSize: AUint32; const _OutputSource: aint32; _NumDimensions: TCL_int; const _GlobalWorkSize,_LocalWorkSize: Auint32);
// Properties
property CurrentKernel: integer read FCurrentKernel write SetCurrentKernel;
end;
implementation
function TOpenCLLauncher.GetDriver: AnsiString;
const
nvd: AnsiString = 'NVIDIA Corporation';
ati_amdd: AnsiString = 'ATI Technologies Inc.';
NV_DRIVER = 'OpenCL.dll';
ATI_AMD_DRIVER = 'atiocl.dll';//'OpenCL.dll'
var
SysDir: array [0..(MAX_PATH - 1)] of AnsiChar;
l: Cardinal;
begin
Result := '';
l := MAX_PATH;
GetSystemDirectoryA(@SysDir[0], l);
if FileExists(String(String(SysDir) + '\' + NV_DRIVER)) then
Result := NV_DRIVER
else
Result := ATI_AMD_DRIVER;
end;
constructor TOpenCLLauncher.Create;
begin
InitializeClass;
end;
constructor TOpenCLLauncher.Create(const _FileName, _KernelName: string);
begin
InitializeClass;
LoadProgram(_FileName, _KernelName);
end;
destructor TOpenCLLauncher.Destroy;
begin
ClearContext();
ClearGPUBuffers();
SetLength(FMem, 0);
SetLength(FFlags, 0);
if FHasDebugFile then
begin
FDebugFile.Free;
end;
inherited Destroy;
end;
procedure TOpenCLLauncher.InitializeClass;
begin
FIsLoaded := false;
FHasDebugFile := false;
InitializeContext;
end;
procedure TOpenCLLauncher.InitializeContext;
var
CPS: array [0..2] of PCL_context_properties;
Status: TCL_int;
Current_device: PPCL_device_id;
Platform_: PCL_platform_id;
Dev_num: TCL_int;
begin
CPS[0] := pcl_context_properties(cl_context_platform);
CPS[1] := nil;
CPS[2] := nil;
if not InitOpenCL(GetDriver) then Exit;
Status := clGetPlatformIDs(1, @Platform_, nil);
if Status <> CL_SUCCESS then
begin
WriteDebug('clGetPlatformIDs: ' + GetString(Status));
Exit;
end;
CPS[1] := pcl_context_properties(Platform_);
FContext := clCreateContextFromType(@CPS, CL_DEVICE_TYPE_GPU, nil, nil, @Status);
if Status <> CL_SUCCESS then
begin
WriteDebug('clCreateContextFromType: ' + GetString(Status));
Exit;
end;
Status := clGetContextInfo(FContext, CL_CONTEXT_DEVICES, 0, nil, @Dev_num);
if Status <> CL_SUCCESS then
begin
WriteDebug('clGetContextInfo: ' + GetString(Status));
Exit;
end;
if Dev_num <= 0 then
begin
WriteDebug('Invalid Dev_num obtained from clGetContextInfo.');
Exit;
end;
Current_device := oclGetDev(FContext, 0);
FCurrent_indevice := Integer(current_device^);
// Status := clGetDeviceInfo(PCL_device_id(Current_indevice), CL_DEVICE_NAME, SizeOf(FBuf), @FBuf, nil);
// if Status <> CL_SUCCESS then
// begin
// WriteDebug(GetString(Status));
// Exit;
// end;
FCommandQueue := clCreateCommandQueue(FContext, PCL_device_id(FCurrent_indevice), 0, @Status);
if Status <> CL_SUCCESS then
begin
WriteDebug('clCreateCommandQueue: ' + GetString(Status));
Exit;
end;
end;
procedure TOpenCLLauncher.ClearContext;
begin
if FisLoaded then
begin
ClearProgram();
end;
clReleaseCommandQueue(FCommandQueue);
clReleaseContext(FContext);
end;
// I/O
procedure TOpenCLLauncher.LoadProgram(const _FileName, _KernelName: string);
var
program_length: TSize_t;
Status: TCL_int;
Log: AnsiString;
LogSize: Integer;
begin
if FIsLoaded then
begin
ClearProgram();
end;
FProgramName := copy(_Filename,1,Length(_Filename));
FSource := oclLoadProgSource(_Filename, '', @program_length);
FProgram_ := clCreateProgramWithSource(FContext, 1, @FSource, @program_length, @Status);
if Status <> CL_SUCCESS then
begin
WriteDebug('clCreateProgramWithSource[' + _Filename + ']: ' + GetString(Status));
Exit;
end;
Status := clBuildProgram(FProgram_, 0, nil, nil, nil, nil);
if Status <> CL_SUCCESS then
begin
WriteDebug(GetString(Status));
Status := clGetProgramBuildInfo(FProgram_, PCL_device_id(FCurrent_indevice), CL_PROGRAM_BUILD_LOG, 0, nil, @LogSize);
if Status <> CL_SUCCESS then
begin
WriteDebug('clBuildProgram[' + _Filename + ']: ' + GetString(Status));
Exit;
end;
SetLength(Log, LogSize);
Status := clGetProgramBuildInfo(FProgram_, PCL_device_id(FCurrent_indevice), CL_PROGRAM_BUILD_LOG, LogSize, PAnsiChar(Log), nil);
if Status <> CL_SUCCESS then
begin
WriteDebug('clGetProgramBuildInfo[' + _Filename + ']: ' + GetString(Status));
Exit;
end;
WriteDebug(Log);
end;
SetLength(FKernel, 1);
SetLength(FKernelName, 1);
FKernelName[0] := copy(_KernelName,1,Length(_KernelName));
FKernel[0] := clCreateKernel(FProgram_, PAnsiChar(_KernelName), @Status);
if Status <> CL_SUCCESS then
begin
SetLength(FKernel, 0);
FKernelName[0] := '';
SetLength(FKernelName, 0);
clReleaseProgram(FProgram_);
WriteDebug('clCreateKernel[' + _Filename + '::' + _KernelName + ']: ' + GetString(Status));
Exit;
end;
FCurrentKernel := 0;
FIsLoaded := true;
end;
procedure TOpenCLLauncher.LoadProgram(const _FileName: string; const _KernelNames: AString);
var
program_length: TSize_t;
Status: TCL_int;
Log: AnsiString;
i, j, LogSize: Integer;
begin
if FIsLoaded then
begin
ClearProgram();
end;
FProgramName := copy(_Filename,1,Length(_Filename));
FSource := oclLoadProgSource(_Filename, '', @program_length);
FProgram_ := clCreateProgramWithSource(FContext, 1, @FSource, @program_length, @Status);
if Status <> CL_SUCCESS then
begin
WriteDebug('clCreateProgramWithSource[' + _Filename + ']: ' + GetString(Status));
Exit;
end;
Status := clBuildProgram(FProgram_, 0, nil, nil, nil, nil);
if Status <> CL_SUCCESS then
begin
WriteDebug(GetString(Status));
Status := clGetProgramBuildInfo(FProgram_, PCL_device_id(FCurrent_indevice), CL_PROGRAM_BUILD_LOG, 0, nil, @LogSize);
if Status <> CL_SUCCESS then
begin
WriteDebug('clBuildProgram[' + _Filename + ']: ' + GetString(Status));
Exit;
end;
SetLength(Log, LogSize);
Status := clGetProgramBuildInfo(FProgram_, PCL_device_id(FCurrent_indevice), CL_PROGRAM_BUILD_LOG, LogSize, PAnsiChar(Log), nil);
if Status <> CL_SUCCESS then
begin
WriteDebug('clGetProgramBuildInfo[' + _Filename + ']: ' + GetString(Status));
Exit;
end;
WriteDebug(Log);
end;
SetLength(FKernel, High(_KernelNames) + 1);
SetLength(FKernelName, High(_KernelNames) + 1);
for i := Low(FKernel) to High(FKernel) do
begin
FKernelName[i] := copy(_KernelNames[i],1,Length(_KernelNames[i]));
FKernel[i] := clCreateKernel(FProgram_, PAnsiChar(_KernelNames[i]), @Status);
if Status <> CL_SUCCESS then
begin
j := i - 1;
while j >= 0 do
begin
clReleaseKernel(FKernel[j]);
FKernelName[j] := '';
dec(j);
end;
FKernelName[i] := '';
SetLength(FKernel, 0);
SetLength(FKernelName, 0);
clReleaseProgram(FProgram_);
WriteDebug('clCreateKernel[' + _Filename + '::' + _KernelNames[i] + ']: ' + GetString(Status));
Exit;
end;
end;
FCurrentKernel := 0;
FIsLoaded := true;
end;
procedure TOpenCLLauncher.ClearProgram;
var
i: integer;
begin
for i := Low(FKernel) to High(FKernel) do
begin
clReleaseKernel(FKernel[i]);
FKernelName[i] := '';
end;
SetLength(FKernel, 0);
SetLength(FKernelName, 0);
clReleaseProgram(FProgram_);
FisLoaded := false;
end;
procedure TOpenCLLauncher.SetCurrentKernel(_value: integer);
begin
if (_Value >= Low(FKernel)) and (_Value <= High(FKernel)) then
begin
FCurrentKernel := _Value;
end;
end;
procedure TOpenCLLauncher.LoadDataIntoGPU(const _InputData: APointer; const _InputSize,_InputUnitSize: Auint32; var _OutputData: APointer; const _OutputSource: aint32);
var
Status: TCL_int;
i : integer;
begin
if not FIsLoaded then exit;
SetLength(FMem,High(_InputData)+1);
SetLength(FFlags,High(_InputData)+1);
// Determine if the flags used for each variable
for i := Low(FFlags) to High(FFlags) do
begin
FFlags[i] := false; // default to mem_copy_host_ptr.
end;
for i := Low(_OutputData) to High(_OutputData) do
begin
if _OutputSource[i] <> -1 then
begin
FFlags[_OutputSource[i]] := true;
end;
end;
// Now, write parameters to GPU memory.
for i := Low(_InputData) to High(_InputData) do
begin
if (_InputSize[i] > 1) or (FFlags[i]) then
begin
if FFlags[i] then
begin
FMem[i] := clCreateBuffer(FContext, CL_MEM_READ_WRITE or CL_MEM_COPY_HOST_PTR, _InputSize[i] * _InputUnitSize[i], _InputData[i], @Status);
end
else
begin
FMem[i] := clCreateBuffer(FContext, CL_MEM_COPY_HOST_PTR, _InputSize[i] * _InputUnitSize[i], _InputData[i], @Status);
end;
if Status <> CL_SUCCESS then
WriteDebug('clCreateBuffer[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
Status := clSetKernelArg(FKernel[FCurrentKernel], i, SizeOf(pcl_mem), @FMem[i]);
if Status <> CL_SUCCESS then
WriteDebug('clSetKernelArg[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end
else
begin
Status := clSetKernelArg(FKernel[FCurrentKernel], i, _InputUnitSize[i], _InputData[i]);
if Status <> CL_SUCCESS then
WriteDebug('clSetKernelArg[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
end;
end;
procedure TOpenCLLauncher.LoadDataIntoGPU(_ID: integer; _ReadWrite: boolean; const _InputData: Pointer; const _InputSize,_InputUnitSize: longword; var _OutputData: APointer);
var
Status: TCL_int;
begin
if not FIsLoaded then exit;
if (_ID <= 0) or (_ID > High(FMem)) then exit;
// Determine the flags used
FFlags[_ID] := _ReadWrite;
if FMem[_ID] <> nil then
begin
Status := clReleaseMemObject(FMem[_ID]);
if Status <> CL_SUCCESS then
WriteDebug('clReleaseMemObject (' + IntToStr(_ID) + ')[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status))
else
FMem[_ID] := nil;
end;
// Now, write parameters to GPU memory.
if (_InputSize > 1) or (FFlags[_ID]) then
begin
if FFlags[_ID] then
begin
FMem[_ID] := clCreateBuffer(FContext, CL_MEM_READ_WRITE or CL_MEM_COPY_HOST_PTR, _InputSize * _InputUnitSize, _InputData, @Status);
end
else
begin
FMem[_ID] := clCreateBuffer(FContext, CL_MEM_COPY_HOST_PTR, _InputSize * _InputUnitSize, _InputData, @Status);
end;
if Status <> CL_SUCCESS then
WriteDebug('clCreateBuffer[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
Status := clSetKernelArg(FKernel[FCurrentKernel], _ID, SizeOf(pcl_mem), @FMem[_ID]);
if Status <> CL_SUCCESS then
WriteDebug('clSetKernelArg[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end
else
begin
FMem[_ID] := nil;
Status := clSetKernelArg(FKernel[FCurrentKernel], _ID, _InputUnitSize, _InputData);
if Status <> CL_SUCCESS then
WriteDebug('clSetKernelArg[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
end;
procedure TOpenCLLauncher.SaveDataFromGPU(const _InputData: APointer; const _InputSize: Auint32; var _OutputData: APointer; const _OutputSize,_OutputUnitSize: AUint32; const _OutputSource: aint32);
var
Status: TCL_int;
i : integer;
begin
if not FIsLoaded then exit;
for i := Low(_OutputData) to High(_OutputData) do
begin
if _OutputSource[i] <> -1 then
begin
Status := clEnqueueReadBuffer(FCommandQueue, FMem[_OutputSource[i]], CL_TRUE, 0, _OutputSize[i] * _OutputUnitSize[i], _OutputData[i], 0, nil, nil);
if Status <> CL_SUCCESS then
WriteDebug('clEnqueueReadBuffer (' + IntToStr(i) + ')[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
end;
for i := Low(_InputData) to High(_InputData) do
begin
if (_InputSize[i] > 1) or (FFlags[i]) then
begin
Status := clReleaseMemObject(FMem[i]);
if Status <> CL_SUCCESS then
WriteDebug('clReleaseMemObject (' + IntToStr(i) + ')[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status))
else
FMem[i] := nil;
end;
end;
end;
procedure TOpenCLLauncher.SaveDataFromGPU(const _InputData: Pointer; const _InputSize: longword; var _OutputData: Pointer; const _OutputSize,_OutputUnitSize: longword; const _OutputSource: integer);
var
Status: TCL_int;
begin
if not FIsLoaded then exit;
if (_OutputSource >= 0) and (_OutputSource <= High(FMem)) then
begin
Status := clEnqueueReadBuffer(FCommandQueue, FMem[_OutputSource], CL_TRUE, 0, _OutputSize * _OutputUnitSize, _OutputData, 0, nil, nil);
if Status <> CL_SUCCESS then
WriteDebug('clEnqueueReadBuffer (' + IntToStr(_OutputSource) + ')[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
end;
// Execute
procedure TOpenCLLauncher.RunKernel(const _InputData: APointer; const _InputSize,_InputUnitSize: Auint32; var _OutputData: APointer; const _OutputSize,_OutputUnitSize: AUint32; const _OutputSource: aint32; _NumDimensions: TCL_int; const _GlobalWorkSize,_LocalWorkSize: Auint32);
var
Status: TCL_int;
i : integer;
begin
if not FIsLoaded then exit;
SetLength(FMem,High(_InputData)+1);
SetLength(FFlags,High(_InputData)+1);
// Determine if the flags used for each variable
for i := Low(FFlags) to High(FFlags) do
begin
FFlags[i] := false; // default to mem_copy_host_ptr.
end;
for i := Low(_OutputData) to High(_OutputData) do
begin
if _OutputSource[i] <> -1 then
begin
FFlags[_OutputSource[i]] := true;
end;
end;
// Now, write parameters to GPU memory.
for i := Low(_InputData) to High(_InputData) do
begin
if (_InputSize[i] > 1) or (FFlags[i]) then
begin
if FFlags[i] then
begin
FMem[i] := clCreateBuffer(FContext, CL_MEM_READ_WRITE or CL_MEM_COPY_HOST_PTR, _InputSize[i] * _InputUnitSize[i], _InputData[i], @Status);
end
else
begin
FMem[i] := clCreateBuffer(FContext, CL_MEM_COPY_HOST_PTR, _InputSize[i] * _InputUnitSize[i], _InputData[i], @Status);
end;
if Status <> CL_SUCCESS then
WriteDebug('clCreateBuffer[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
Status := clSetKernelArg(FKernel[FCurrentKernel], i, SizeOf(pcl_mem), @FMem[i]);
if Status <> CL_SUCCESS then
WriteDebug('clSetKernelArg[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end
else
begin
FMem[i] := nil;
Status := clSetKernelArg(FKernel[FCurrentKernel], i, _InputUnitSize[i], _InputData[i]);
if Status <> CL_SUCCESS then
WriteDebug('clSetKernelArg[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
end;
if (_GlobalWorkSize <> nil) and (_LocalWorkSize <> nil) then
begin
Status := clEnqueueNDRangeKernel(FCommandQueue, FKernel[FCurrentKernel], _NumDimensions, nil, @(_GlobalWorkSize[0]), @_LocalWorkSize, 0, nil, nil);
if Status <> CL_SUCCESS then
WriteDebug('clEnqueueNDRangeKernel[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end
else if (_GlobalWorkSize <> nil) then
begin
Status := clEnqueueNDRangeKernel(FCommandQueue, FKernel[FCurrentKernel], _NumDimensions, nil, @(_GlobalWorkSize[0]), nil, 0, nil, nil);
if Status <> CL_SUCCESS then
WriteDebug('clEnqueueNDRangeKernel[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
Status:= clFinish(FCommandQueue);
if Status <> CL_SUCCESS then
WriteDebug('clFinish[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
for i := Low(_OutputData) to High(_OutputData) do
begin
if _OutputSource[i] <> -1 then
begin
Status := clEnqueueReadBuffer(FCommandQueue, FMem[_OutputSource[i]], CL_TRUE, 0, _OutputSize[i] * _OutputUnitSize[i], _OutputData[i], 0, nil, nil);
if Status <> CL_SUCCESS then
WriteDebug('clEnqueueReadBuffer (' + IntToStr(i) + ')[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
end;
for i := Low(_InputData) to High(_InputData) do
begin
if (_InputSize[i] > 1) or (FFlags[i]) then
begin
Status := clReleaseMemObject(FMem[i]);
if Status <> CL_SUCCESS then
WriteDebug('clReleaseMemObject (' + IntToStr(i) + ')[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status))
else
FMem[i] := nil;
end;
end;
end;
procedure TOpenCLLauncher.RunKernel(const _InputData: APointer; const _InputSize,_InputUnitSize: Auint32; const _OutputSource: aint32; _NumDimensions: TCL_int; const _GlobalWorkSize,_LocalWorkSize: Auint32);
var
Status: TCL_int;
i : integer;
begin
if not FIsLoaded then exit;
SetLength(FMem,High(_InputData)+1);
SetLength(FFlags,High(_InputData)+1);
// Determine if the flags used for each variable
for i := Low(FFlags) to High(FFlags) do
begin
FFlags[i] := false; // default to mem_copy_host_ptr.
end;
for i := Low(_OutputSource) to High(_OutputSource) do
begin
if _OutputSource[i] <> -1 then
begin
FFlags[_OutputSource[i]] := true;
end;
end;
// Now, write parameters to GPU memory.
for i := Low(_InputData) to High(_InputData) do
begin
if (_InputSize[i] > 1) or (FFlags[i]) then
begin
if FFlags[i] then
begin
FMem[i] := clCreateBuffer(FContext, CL_MEM_READ_WRITE or CL_MEM_COPY_HOST_PTR, _InputSize[i] * _InputUnitSize[i], _InputData[i], @Status);
end
else
begin
FMem[i] := clCreateBuffer(FContext, CL_MEM_COPY_HOST_PTR, _InputSize[i] * _InputUnitSize[i], _InputData[i], @Status);
end;
if Status <> CL_SUCCESS then
WriteDebug('clCreateBuffer[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
Status := clSetKernelArg(FKernel[FCurrentKernel], i, SizeOf(pcl_mem), @FMem[i]);
if Status <> CL_SUCCESS then
WriteDebug('clSetKernelArg[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end
else
begin
FMem[i] := nil;
Status := clSetKernelArg(FKernel[FCurrentKernel], i, _InputUnitSize[i], _InputData[i]);
if Status <> CL_SUCCESS then
WriteDebug('clSetKernelArg[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
end;
if (_GlobalWorkSize <> nil) and (_LocalWorkSize <> nil) then
begin
Status := clEnqueueNDRangeKernel(FCommandQueue, FKernel[FCurrentKernel], _NumDimensions, nil, @(_GlobalWorkSize[0]), @_LocalWorkSize, 0, nil, nil);
if Status <> CL_SUCCESS then
WriteDebug('clEnqueueNDRangeKernel[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end
else if (_GlobalWorkSize <> nil) then
begin
Status := clEnqueueNDRangeKernel(FCommandQueue, FKernel[FCurrentKernel], _NumDimensions, nil, @(_GlobalWorkSize[0]), nil, 0, nil, nil);
if Status <> CL_SUCCESS then
WriteDebug('clEnqueueNDRangeKernel[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
Status:= clFinish(FCommandQueue);
if Status <> CL_SUCCESS then
WriteDebug('clFinish[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
for i := Low(_OutputSource) to High(_OutputSource) do
begin
if _OutputSource[i] <> -1 then
begin
Status := clEnqueueReadBuffer(FCommandQueue, FMem[_OutputSource[i]], CL_TRUE, 0, _InputSize[_OutputSource[i]] * _InputUnitSize[_OutputSource[i]], _InputData[_OutputSource[i]], 0, nil, nil);
if Status <> CL_SUCCESS then
WriteDebug('clEnqueueReadBuffer (' + IntToStr(i) + ')[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
end;
for i := Low(_InputData) to High(_InputData) do
begin
if (_InputSize[i] > 1) or (FFlags[i]) then
begin
Status := clReleaseMemObject(FMem[i]);
if Status <> CL_SUCCESS then
WriteDebug('clReleaseMemObject (' + IntToStr(i) + ')[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status))
else
FMem[i] := nil;
end;
end;
end;
procedure TOpenCLLauncher.RunKernel(_NumDimensions: TCL_int; const _GlobalWorkSize,_LocalWorkSize: Auint32);
var
Status: TCL_int;
begin
if (_GlobalWorkSize <> nil) and (_LocalWorkSize <> nil) then
begin
Status := clEnqueueNDRangeKernel(FCommandQueue, FKernel[FCurrentKernel], _NumDimensions, nil, @(_GlobalWorkSize[0]), @_LocalWorkSize, 0, nil, nil);
if Status <> CL_SUCCESS then
WriteDebug('clEnqueueNDRangeKernel[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end
else if (_GlobalWorkSize <> nil) then
begin
Status := clEnqueueNDRangeKernel(FCommandQueue, FKernel[FCurrentKernel], _NumDimensions, nil, @(_GlobalWorkSize[0]), nil, 0, nil, nil);
if Status <> CL_SUCCESS then
WriteDebug('clEnqueueNDRangeKernel[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
Status:= clFinish(FCommandQueue);
if Status <> CL_SUCCESS then
WriteDebug('clFinish[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status));
end;
function TOpenCLLauncher.VerifyKernelParameters(const _InputData: APointer; const _InputSize,_InputUnitSize: Auint32; var _OutputData: APointer; const _OutputSize,_OutputUnitSize: AUint32; const _OutputSource: aint32; _NumDimensions: TCL_int; const _GlobalWorkSize,_LocalWorkSize: Auint32): boolean;
var
maxDimension: integer;
begin
Result := false;
if FIsLoaded then
begin
if (_InputData <> nil) and (_InputSize <> nil) and (_InputUnitSize <> nil) then
begin
if (High(_InputData) > -1) then
begin
if ((High(_InputData) = High(_InputSize)) and (High(_InputData) = High(_InputUnitSize))) then
begin
if (_InputData <> nil) and (_InputSize <> nil) and (_InputUnitSize <> nil) and (_OutputSource <> nil) then
begin
if ((High(_OutputData) = High(_OutputSize)) and (High(_OutputData) = High(_OutputUnitSize)) and (High(_OutputData) = High(_OutputSource))) then
begin
if _NumDimensions > 0 then
begin
maxDimension := _NumDimensions - 1;
if (maxDimension = High(_GlobalWorkSize)) then
begin
if _LocalWorkSize <> nil then
begin
if (maxDimension = High(_LocalWorkSize)) then
begin
Result := true;
end;
end
else
begin
Result := true;
end;
end;
end;
end;
end;
end;
end;
end;
end;
end;
procedure TOpenCLLauncher.RunKernelSafe(const _InputData: APointer; const _InputSize,_InputUnitSize: Auint32; var _OutputData: APointer; const _OutputSize,_OutputUnitSize: AUint32; const _OutputSource: aint32; _NumDimensions: TCL_int; const _GlobalWorkSize,_LocalWorkSize: Auint32);
begin
if VerifyKernelParameters(_InputData,_InputSize,_InputUnitSize,_OutputData,_OutputSize,_OutputUnitSize,_OutputSource,_NumDimensions,_GlobalWorkSize,_LocalWorkSize) then
begin
RunKernel(_InputData,_InputSize,_InputUnitSize,_OutputData,_OutputSize,_OutputUnitSize,_OutputSource,_NumDimensions,_GlobalWorkSize,_LocalWorkSize);
end;
end;
// Misc
procedure TOpenCLLauncher.ClearGPUBuffers;
var
i: integer;
Status: TCL_int;
begin
for i := Low(FMem) to High(FMem) do
begin
if FMem[i] <> nil then
begin
Status := clReleaseMemObject(FMem[i]);
if Status <> CL_SUCCESS then
WriteDebug('clReleaseMemObject (' + IntToStr(i) + ')[' + FProgramName + '::' + FKernelName[FCurrentKernel] + ']: ' + GetString(Status))
else
FMem[i] := nil;
end;
end;
end;
procedure TOpenCLLauncher.WriteDebug(const _Text: string);
begin
if not FHasDebugFile then
begin
FHasDebugFile := true;
FDebugFile := TDebugFile.Create(ExtractFilePath(ParamStr(0)) + 'ocldebug.txt');
end;
FDebugFile.Add(_Text);
end;
end.
|
unit GLDTube;
interface
uses
Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDObjects;
type
TGLDTube = class(TGLDEditableObject)
private
FInnerRadius: GLfloat;
FOuterRadius: GLfloat;
FHeight: GLfloat;
FHeightSegs: GLushort;
FCapSegs: GLushort;
FSides: GLushort;
FStartAngle: GLfloat;
FSweepAngle: GLfloat;
FOutsidePoints: PGLDVector3fArray;
FInsidePoints: PGLDVector3fArray;
FBasePoints: PGLDVector3fArray;
FTopPoints: PGLDVector3fArray;
FOutsideNormals: PGLDVector3fArray;
FInsideNormals: PGLDVector3fArray;
FBaseNormals: PGLDVector3fArray;
FTopNormals: PGLDVector3fArray;
function GetMode: GLubyte;
function GetOutsidePoint(i, j: GLushort): PGLDVector3f;
function GetInsidePoint(i, j: GLushort): PGLDVector3f;
function GetTopPoint(i, j: GLushort): PGLDVector3f;
function GetBasePoint(i, j: GLushort): PGLDVector3f;
procedure SetInnerRadius(Value: GLfloat);
procedure SetOuterRadius(Value: GLfloat);
procedure SetHeight(Value: GLfloat);
procedure SetHeightSegs(Value: GLushort);
procedure SetCapSegs(Value: GLushort);
procedure SetSides(Value: GLushort);
procedure SetStartAngle(Value: GLfloat);
procedure SetSweepAngle(Value: GLfloat);
function GetParams: TGLDTubeParams;
procedure SetParams(Value: TGLDTubeParams);
protected
procedure CalcBoundingBox; override;
procedure CreateGeometry; override;
procedure DestroyGeometry; override;
procedure DoRender; override;
procedure SimpleRender; override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function RealName: string; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function CanConvertTo(_ClassType: TClass): GLboolean; override;
function ConvertTo(Dest: TPersistent): GLboolean; override;
function ConvertToTriMesh(Dest: TPersistent): GLboolean;
function ConvertToQuadMesh(Dest: TPersistent): GLboolean;
function ConvertToPolyMesh(Dest: TPersistent): GLboolean;
property Params: TGLDTubeParams read GetParams write SetParams;
published
property InnerRadius: GLfloat read FInnerRadius write SetInnerRadius;
property OuterRadius: GLfloat read FOuterRadius write SetOuterRadius;
property Height: GLfloat read FHeight write SetHeight;
property HeightSegs: GLushort read FHeightSegs write SetHeightSegs default GLD_TUBE_HEIGHTSEGS_DEFAULT;
property CapSegs: GLushort read FCapSegs write SetCapSegs default GLD_TUBE_CAPSEGS_DEFAULT;
property Sides: GLushort read FSides write SetSides default GLD_TUBE_SIDES_DEFAULT;
property StartAngle: GLfloat read FStartAngle write SetStartAngle;
property SweepAngle: GLfloat read FSweepAngle write SetSweepAngle;
end;
implementation
uses
SysUtils, GLDGizmos, GLDX, GLDMesh, GLDUtils;
var
vTubeCounter: GLuint = 0;
constructor TGLDTube.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
Inc(vTubeCounter);
FName := GLD_TUBE_STR + IntToStr(vTubeCounter);
FInnerRadius := GLD_STD_TUBEPARAMS.InnerRadius;
FOuterRadius := GLD_STD_TUBEPARAMS.OuterRadius;
FHeight := GLD_STD_TUBEPARAMS.Height;
FHeightSegs := GLD_STD_TUBEPARAMS.HeightSegs;
FCapSegs := GLD_STD_TUBEPARAMS.CapSegs;
FSides := GLD_STD_TUBEPARAMS.Sides;
FStartAngle := GLD_STD_TUBEPARAMS.StartAngle;
FSweepAngle := GLD_STD_TUBEPARAMS.SweepAngle;
FPosition.Vector3f := GLD_STD_TUBEPARAMS.Position;
FRotation.Params := GLD_STD_TUBEPARAMS.Rotation;
CreateGeometry;
end;
destructor TGLDTube.Destroy;
begin
inherited Destroy;
end;
procedure TGLDTube.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDTube) then Exit;
inherited Assign(Source);
SetParams(TGLDTube(Source).GetParams);
end;
procedure TGLDTube.DoRender;
var
iSegs, iP: GLushort;
begin
for iSegs := 0 to FHeightSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FOutsideNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FOutsidePoints^[iSegs * (FSides + 3) + iP]);
glNormal3fv(@FOutsideNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FOutsidePoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FInsideNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FInsidePoints^[(iSegs + 1) * (FSides + 3) + iP]);
glNormal3fv(@FInsideNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FInsidePoints^[iSegs * (FSides + 3) + iP]);
end;
glEnd;
end;
for iSegs := 0 to FCapSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FBaseNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FBasePoints^[(iSegs + 1) * (FSides + 3) + iP]);
glNormal3fv(@FBaseNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FBasePoints^[iSegs * (FSides + 3) + iP]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FTopNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FTopPoints^[iSegs * (FSides + 3) + iP]);
glNormal3fv(@FTopNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FTopPoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
end;
end;
procedure TGLDTube.SimpleRender;
var
iSegs, iP: GLushort;
begin
for iSegs := 0 to FHeightSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FOutsidePoints^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FOutsidePoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FInsidePoints^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FInsidePoints^[iSegs * (FSides + 3) + iP]);
end;
glEnd;
end;
for iSegs := 0 to FCapSegs - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FBasePoints^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FBasePoints^[iSegs * (FSides + 3) + iP]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FTopPoints^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FTopPoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
end;
end;
procedure TGLDTube.CalcBoundingBox;
begin
FBoundingBox := GLDXCalcBoundingBox(
[GLDXVector3fArrayData(FOutsidePoints, (FSides + 3) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FInsidePoints, (FSides + 3) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FBasePoints, (FSides + 3) * (FCapSegs + 1)),
GLDXVector3fArrayData(FTopPoints, (FSides + 3) * (FCapSegs + 1))]);
end;
procedure TGLDTube.CreateGeometry;
var
iSegs, iP: GLushort;
A, R: GLfloat;
begin
if FHeightSegs < 1 then FHeightSegs := 1 else
if FHeightSegs > 1000 then FHeightSegs := 1000;
if FCapSegs < 1 then FCapSegs := 1 else
if FCapSegs > 1000 then FCapSegs := 1000;
if FSides < 1 then FSides := 1 else
if FSides > 1000 then FSides := 1000;
ReallocMem(FOutsidePoints, (FSides + 3) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FOutsideNormals, (FSides + 3) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FInsidePoints, (FSides + 3) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FInsideNormals, (FSides + 3) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FBasePoints, (FSides + 3) * (FCapSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FBaseNormals, (FSides + 3) * (FCapSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FTopPoints, (FSides + 3) * (FCapSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FTopNormals, (FSides + 3) * (FCapSegs + 1) * SizeOf(TGLDVector3f));
A := GLDXGetAngleStep(FStartAngle, FSweepAngle, FSides);
R := (FOuterRadius - FInnerRadius) / FCapSegs;
for iSegs := 0 to FHeightSegs do
for iP := 1 to FSides + 3 do
begin
FOutsidePoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(FStartAngle + (iP - 2) * A) * FOuterRadius,
-(iSegs * (FHeight / FHeightSegs)) + (Height / 2),
-GLDXSinus(FStartAngle + (iP - 2) * A) * FOuterRadius);
FInsidePoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(FStartAngle + (iP - 2) * A) * FInnerRadius,
-(iSegs * (FHeight / FHeightSegs)) + (FHeight / 2),
-GLDXSinus(FStartAngle + (iP - 2) * A) * FInnerRadius);
end;
for iSegs := 0 to FCapSegs do
for iP := 1 to FSides + 3 do
begin
FBasePoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(FStartAngle + (iP - 2) * A) * (FInnerRadius + (iSegs * R)),
-(FHeight / 2),
-GLDXSinus(FStartAngle + (iP - 2) * A) * (FInnerRadius + (iSegs * R)));
FTopPoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(FStartAngle + (iP - 2) * A) * (FInnerRadius + (iSegs * R)),
(FHeight / 2),
-GLDXSinus(FStartAngle + (iP - 2) * A) * (FInnerRadius + (iSegs * R)));
end;
FModifyList.ModifyPoints(
[GLDXVector3fArrayData(FOutsidePoints, (FSides + 3) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FInsidePoints, (FSides + 3) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FBasePoints, (FSides + 3) * (FCapSegs + 1)),
GLDXVector3fArrayData(FTopPoints, (FSides + 3) * (FCapSegs + 1))]);
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FOutsidePoints, (FHeightSegs + 1) * (FSides + 3)),
GLDXVector3fArrayData(FOutsideNormals, (FHeightSegs + 1) * (FSides + 3)),
FHeightSegs, FSides + 2));
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FInsidePoints, (FHeightSegs + 1) * (FSides + 3)),
GLDXVector3fArrayData(FInsideNormals, (FHeightSegs + 1) * (FSides + 3)),
FHeightSegs, FSides + 2));
for iP := 1 to (FHeightSegs + 1) * (FSides + 3) do
FInsideNormals^[iP] := GLDXVectorNeg(FInsideNormals^[iP]);
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FBasePoints, (FCapSegs + 1) * (FSides + 3)),
GLDXVector3fArrayData(FBaseNormals, (FCapSegs + 1) * (FSides + 3)),
FCapSegs, FSides + 2));
for iP := 1 to (FCapSegs + 1) * (FSides + 3) do
FBaseNormals^[iP] := GLDXVectorNeg(FBaseNormals^[iP]);
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FTopPoints, (FCapSegs + 1) * (FSides + 3)),
GLDXVector3fArrayData(FTopNormals, (FCapSegs + 1) * (FSides + 3)),
FCapSegs, FSides + 2));
CalcBoundingBox;
end;
procedure TGLDTube.DestroyGeometry;
begin
if FOutsidePoints <> nil then ReallocMem(FOutsidePoints, 0);
if FInsidePoints <> nil then ReallocMem(FInsidePoints, 0);
if FBasePoints <> nil then ReallocMem(FBasePoints, 0);
if FTopPoints <> nil then ReallocMem(FTopPoints, 0);
if FOutsideNormals <> nil then ReallocMem(FOutsideNormals, 0);
if FInsideNormals <> nil then ReallocMem(FInsideNormals, 0);
if FBaseNormals <> nil then ReallocMem(FBaseNormals, 0);
if FTopNormals <> nil then ReallocMem(FTopNormals, 0);
FOutsidePoints := nil; FInsidePoints := nil;
FBasePoints := nil; FTopPoints := nil;
FOutsideNormals := nil; FInsideNormals := nil;
FBaseNormals := nil; FTopNormals := nil;
end;
class function TGLDTube.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_TUBE;
end;
class function TGLDTube.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDTube;
end;
class function TGLDTube.RealName: string;
begin
Result := GLD_TUBE_STR;
end;
procedure TGLDTube.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
Stream.Read(FInnerRadius, SizeOf(GLfloat));
Stream.Read(FOuterRadius, SizeOf(GLfloat));
Stream.Read(FHeight, SizeOf(GLfloat));
Stream.Read(FHeightSegs, SizeOf(GLushort));
Stream.Read(FCapSegs, SizeOf(GLushort));
Stream.Read(FSides, SizeOf(GLushort));
Stream.Read(FStartAngle, SizeOf(GLfloat));
Stream.Read(FSweepAngle, SizeOf(GLfloat));
CreateGeometry;
end;
procedure TGLDTube.SaveToStream(Stream: TStream);
begin
inherited SaveToStream(Stream);
Stream.Write(FInnerRadius, SizeOf(GLfloat));
Stream.Write(FOuterRadius, SizeOf(GLfloat));
Stream.Write(FHeight, SizeOf(GLfloat));
Stream.Write(FHeightSegs, SizeOf(GLushort));
Stream.Write(FCapSegs, SizeOf(GLushort));
Stream.Write(FSides, SizeOf(GLushort));
Stream.Write(FStartAngle, SizeOf(GLfloat));
Stream.Write(FSweepAngle, SizeOf(GLfloat));
end;
function TGLDTube.CanConvertTo(_ClassType: TClass): GLboolean;
begin
Result := (_ClassType = TGLDTube) or
(_ClassType = TGLDTriMesh) or
(_ClassType = TGLDQuadMesh) or
(_ClassType = TGLDPolyMesh);
end;
function TGLDTube.ConvertTo(Dest: TPersistent): GLboolean;
begin
Result := False;
if not Assigned(Dest) then Exit;
if Dest.ClassType = Self.ClassType then
begin
Dest.Assign(Self);
Result := True;
end else
if Dest is TGLDTriMesh then
Result := ConvertToTriMesh(Dest) else
if Dest is TGLDQuadMesh then
Result := ConvertToQuadMesh(Dest) else
if Dest is TGLDPolyMesh then
Result := ConvertToPolyMesh(Dest);
end;
{$WARNINGS OFF}
function TGLDTube.ConvertToTriMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
ie, Offset: array[0..3] of GLuint;
si, i, j: GLushort;
F: TGLDTriFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDTriMesh) then Exit;
M := GetMode;
with TGLDTriMesh(Dest) do
begin
DeleteVertices;
F.Smoothing := GLD_SMOOTH_ALL;
Offset[0] := 0;
if M = 0 then
begin
VertexCapacity := (FHeightSegs + 1) * FSides + 2 * (1 + FCapSegs * FSides);
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] + 1 + FCapSegs * FSides;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetOutsidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBasePoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBasePoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * FSides + j;
F.Point2 := i * FSides + j;
if j = FSides then
F.Point3 := (i - 1) * FSides + 1
else F.Point3 := (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := i * FSides + j;
if j = FSides then
begin
F.Point1 := (i - 1) * FSides + 1;
F.Point3 := i * FSides + 1;
end else
begin
F.Point1 := (i - 1) * FSides + j + 1;
F.Point3 := i * FSides + j + 1;
end;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + 1 + j;
if j = FSides then
F.Point3 := Offset[si] + 1 + 1
else F.Point3 := Offset[si] + 1 + j + 1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + (i - 1) * FSides + j;
F.Point2 := Offset[si] + 1 + i * FSides + j;
if j = FSides then
F.Point3 := Offset[si] + 1 + (i - 1) * FSides + 1
else F.Point3 := Offset[si] + 1 + (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := Offset[si] + 1 + i * FSides + j;
if j = FSides then
begin
F.Point1 := Offset[si] + 1 + (i - 1) * FSides + 1;
F.Point3 := Offset[si] + 1 + i * FSides + 1;
end else
begin
F.Point1 := Offset[si] + 1 + (i - 1) * FSides + j + 1;
F.Point3 := Offset[si] + 1 + i * FSides + j + 1;
end;
AddFace(F);
end;
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := 2 * ((FHeightSegs + 1) * FSides + (FCapSegs + 1) * FSides);
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] * 2;
Offset[3] := Offset[2] + (FCapSegs + 1) * FSides;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetOutsidePoint(i, j)^, True);
for i := 1 to FHeightSegs + 1 do
for j := FSides downto 1 do
AddVertex(GetInsidePoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := 1 to FSides do
AddVertex(GetTopPoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := FSides downto 1 do
AddVertex(GetBasePoint(i, j)^, True);
ie[0] := FHeightSegs;
ie[1] := FHeightSegs;
ie[2] := FCapSegs;
ie[3] := FCapSegs;
for si := 0 to 3 do
for i := 1 to ie[si] do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + (i - 1) * FSides + j;
F.Point2 := Offset[si] + i * FSides + j;
if j = FSides then
F.Point3 := Offset[si] + (i - 1) * FSides + 1
else F.Point3 := Offset[si] + (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := Offset[si] + i * FSides + j;
if j = FSides then
begin
F.Point1 := Offset[si] + (i - 1) * FSides + 1;
F.Point3 := Offset[si] + i * FSides + 1;
end else
begin
F.Point1 := Offset[si] + (i - 1) * FSides + j + 1;
F.Point3 := Offset[si] + i * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := (FHeightSegs + 1) * (FSides + 1) +
2 * (1 + FCapSegs * (FSides + 1));
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] + 1 + FCapSegs * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetOutsidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBasePoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBasePoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := (i - 1) * (FSides + 1) + j + 1;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := i * (FSides + 1) + j + 1;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + 1 + j;
F.Point3 := Offset[si] + 1 + j + 1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := Offset[si] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[si] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := Offset[si] + 1 + (i - 1) * (FSides + 1) + j + 1;
F.Point2 := Offset[si] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[si] + 1 + i * (FSides + 1) + j + 1;
AddFace(F);
end;
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := 2 * ((FHeightSegs + 1) * (FSides + 1) + (FCapSegs + 1) * (FSides + 1));
Offset[0] := 0;
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] * 2;
Offset[3] := Offset[1] + (FCapSegs + 1) * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetOutsidePoint(i, j)^, True);
for i := 1 to FHeightSegs + 1 do
for j := FSides + 1 downto 1 do
AddVertex(GetInsidePoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := FSides + 1 downto 1 do
AddVertex(GetBasePoint(i, j)^, True);
ie[0] := FHeightSegs;
ie[1] := FHeightSegs;
ie[2] := FCapSegs;
ie[3] := FCapSegs;
for si := 0 to 3 do
for i := 1 to ie[si] do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + (i - 1) * (FSides + 1) + j;
F.Point2 := Offset[si] + i * (FSides + 1) + j;
F.Point3 := Offset[si] + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := Offset[si] + (i - 1) * (FSides + 1) + j + 1;;
F.Point2 := Offset[si] + i * (FSides + 1) + j;
F.Point3 := Offset[si] + i * (FSides + 1) + j + 1;;
AddFace(F);
end;
end; //M = 3
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDTriMesh(Dest).Selected := Self.Selected;
TGLDTriMesh(Dest).Name := Self.Name;
end; //with
Result := True;
end;
function TGLDTube.ConvertToQuadMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
ie, Offset: array[0..3] of GLuint;
si, i, j: GLushort;
F: TGLDQuadFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDQuadMesh) then Exit;
M := GetMode;
with TGLDQuadMesh(Dest) do
begin
DeleteVertices;
F.Smoothing := GLD_SMOOTH_ALL;
Offset[0] := 0;
if M = 0 then
begin
VertexCapacity := (FHeightSegs + 1) * FSides + 2 * (1 + FCapSegs * FSides);
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] + 1 + FCapSegs * FSides;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetOutsidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBasePoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBasePoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * FSides + j;
F.Point2 := i * FSides + j;
if j = FSides then
begin
F.Point3 := i * FSides + 1;
F.Point4 := (i - 1) * FSides + 1;
end else
begin
F.Point3 := i * FSides + j + 1;
F.Point4 := (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + 1 + j;
if j = FSides then
F.Point3 := Offset[si] + 1 + 1
else F.Point3 := Offset[si] + 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + (i - 1) * FSides + j;
F.Point2 := Offset[si] + 1 + i * FSides + j;
if j = FSides then
begin
F.Point3 := Offset[si] + 1 + i * FSides + 1;
F.Point4 := Offset[si] + 1 + (i - 1) * FSides + 1;
end else
begin
F.Point3 := Offset[si] + 1 + i * FSides + j + 1;
F.Point4 := Offset[si] + 1 + (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := 2 * ((FHeightSegs + 1) * FSides + (FCapSegs + 1) * FSides);
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] * 2;
Offset[3] := Offset[2] + (FCapSegs + 1) * FSides;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetOutsidePoint(i, j)^, True);
for i := 1 to FHeightSegs + 1 do
for j := FSides downto 1 do
AddVertex(GetInsidePoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := 1 to FSides do
AddVertex(GetTopPoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := FSides downto 1 do
AddVertex(GetBasePoint(i, j)^, True);
ie[0] := FHeightSegs;
ie[1] := FHeightSegs;
ie[2] := FCapSegs;
ie[3] := FCapSegs;
for si := 0 to 3 do
for i := 1 to ie[si] do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + (i - 1) * FSides + j;
F.Point2 := Offset[si] + i * FSides + j;
if j = FSides then
begin
F.Point3 := Offset[si] + i * FSides + 1;
F.Point4 := Offset[si] + (i - 1) * FSides + 1;
end else
begin
F.Point3 := Offset[si] + i * FSides + j + 1;
F.Point4 := Offset[si] + (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := (FHeightSegs + 1) * (FSides + 1) +
2 * (1 + FCapSegs * (FSides + 1));
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] + 1 + FCapSegs * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetOutsidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBasePoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBasePoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := i * (FSides + 1) + j + 1;
F.Point4 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1;
F.Point2 := Offset[si] + 1 + j;
F.Point3 := Offset[si] + 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := Offset[si] + 1 + i * (FSides + 1) + j;
F.Point3 := Offset[si] + 1 + i * (FSides + 1) + j + 1;
F.Point4 := Offset[si] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := 2 * ((FHeightSegs + 1) * (FSides + 1) + FCapSegs * (FSides + 1));
Offset[0] := 0;
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] * 2;
Offset[3] := Offset[2] + (FCapSegs + 1) * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetOutsidePoint(i, j)^, True);
for i := 1 to FHeightSegs + 1 do
for j := FSides + 1 downto 1 do
AddVertex(GetInsidePoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := FSides + 1 downto 1 do
AddVertex(GetBasePoint(i, j)^, True);
ie[0] := FHeightSegs;
ie[1] := FHeightSegs;
ie[2] := FCapSegs;
ie[3] := FCapSegs;
for si := 0 to 3 do
for i := 1 to ie[si] do
for j := 1 to FSides do
begin
F.Point1 := Offset[si] + (i - 1) * (FSides + 1) + j;
F.Point2 := Offset[si] + i * (FSides + 1) + j;
F.Point3 := Offset[si] + i * (FSides + 1) + j + 1;
F.Point4 := Offset[si] + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
end; //M = 3
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDQuadMesh(Dest).Selected := Self.Selected;
TGLDQuadMesh(Dest).Name := Self.Name;
end; //with
Result := True;
end;
function TGLDTube.ConvertToPolyMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
ie, Offset: array[0..3] of GLuint;
si, i, j: GLushort;
P: TGLDPolygon;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDPolyMesh) then Exit;
M := GetMode;
with TGLDPolyMesh(Dest) do
begin
DeleteVertices;
Offset[0] := 0;
if M = 0 then
begin
VertexCapacity := (FHeightSegs + 1) * FSides + 2 * (1 + FCapSegs * FSides);
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] + 1 + FCapSegs * FSides;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetOutsidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBasePoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides downto 1 do
AddVertex(GetBasePoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := (i - 1) * FSides + j;
P.Data^[2] := i * FSides + j;
if j = FSides then
begin
P.Data^[3] := i * FSides + 1;
P.Data^[4] := (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := i * FSides + j + 1;
P.Data^[4] := (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := Offset[si] + 1;
P.Data^[2] := Offset[si] + 1 + j;
if j = FSides then
P.Data^[3] := Offset[si] + 1 + 1
else P.Data^[3] := Offset[si] + 1 + j + 1;
//F.Point4 := F.Point1;
AddFace(P);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[si] + 1 + (i - 1) * FSides + j;
P.Data^[2] := Offset[si] + 1 + i * FSides + j;
if j = FSides then
begin
P.Data^[3] := Offset[si] + 1 + i * FSides + 1;
P.Data^[4] := Offset[si] + 1 + (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := Offset[si] + 1 + i * FSides + j + 1;
P.Data^[4] := Offset[si] + 1 + (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := 2 * ((FHeightSegs + 1) * FSides + (FCapSegs + 1) * FSides);
Offset[1] := (FHeightSegs + 1) * FSides;
Offset[2] := Offset[1] * 2;
Offset[3] := Offset[2] + (FCapSegs + 1) * FSides;
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides do
AddVertex(GetOutsidePoint(i, j)^, True);
for i := 1 to FHeightSegs + 1 do
for j := FSides downto 1 do
AddVertex(GetInsidePoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := 1 to FSides do
AddVertex(GetTopPoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := FSides downto 1 do
AddVertex(GetBasePoint(i, j)^, True);
ie[0] := FHeightSegs;
ie[1] := FHeightSegs;
ie[2] := FCapSegs;
ie[3] := FCapSegs;
for si := 0 to 3 do
for i := 1 to ie[si] do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[si] + (i - 1) * FSides + j;
P.Data^[2] := Offset[si] + i * FSides + j;
if j = FSides then
begin
P.Data^[3] := Offset[si] + i * FSides + 1;
P.Data^[4] := Offset[si] + (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := Offset[si] + i * FSides + j + 1;
P.Data^[4] := Offset[si] + (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := (FHeightSegs + 1) * (FSides + 1) +
2 * (1 + FCapSegs * (FSides + 1));
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] + 1 + FCapSegs * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetOutsidePoint(i, j)^, True);
AddVertex(GetTopPoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i + 1, j)^, True);
AddVertex(GetBasePoint(1, 1)^, True);
for i := 1 to FCapSegs do
for j := FSides + 1 downto 1 do
AddVertex(GetBasePoint(i + 1, j)^, True);
for i := 1 to FHeightSegs do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := (i - 1) * (FSides + 1) + j;
P.Data^[2] := i * (FSides + 1) + j;
P.Data^[3] := i * (FSides + 1) + j + 1;
P.Data^[4] := (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
for si := 1 to 2 do
begin
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := Offset[si] + 1;
P.Data^[2] := Offset[si] + 1 + j;
P.Data^[3] := Offset[si] + 1 + j + 1;
// P.Data^[4] := F.Point1;
AddFace(P);
end;
if FCapSegs > 1 then
for i := 1 to FCapSegs - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[si] + 1 + (i - 1) * (FSides + 1) + j;
P.Data^[2] := Offset[si] + 1 + i * (FSides + 1) + j;
P.Data^[3] := Offset[si] + 1 + i * (FSides + 1) + j + 1;
P.Data^[4] := Offset[si] + 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := 2 * ((FHeightSegs + 1) * (FSides + 1) + FCapSegs * (FSides + 1));
Offset[0] := 0;
Offset[1] := (FHeightSegs + 1) * (FSides + 1);
Offset[2] := Offset[1] * 2;
Offset[3] := Offset[2] + (FCapSegs + 1) * (FSides + 1);
for i := 1 to FHeightSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetOutsidePoint(i, j)^, True);
for i := 1 to FHeightSegs + 1 do
for j := FSides + 1 downto 1 do
AddVertex(GetInsidePoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetTopPoint(i, j)^, True);
for i := 1 to FCapSegs + 1 do
for j := FSides + 1 downto 1 do
AddVertex(GetBasePoint(i, j)^, True);
ie[0] := FHeightSegs;
ie[1] := FHeightSegs;
ie[2] := FCapSegs;
ie[3] := FCapSegs;
for si := 0 to 3 do
for i := 1 to ie[si] do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := Offset[si] + (i - 1) * (FSides + 1) + j;
P.Data^[2] := Offset[si] + i * (FSides + 1) + j;
P.Data^[3] := Offset[si] + i * (FSides + 1) + j + 1;
P.Data^[4] := Offset[si] + (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
end; //M = 3
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDPolyMesh(Dest).Selected := Self.Selected;
TGLDPolyMesh(Dest).Name := Self.Name;
end; //with
Result := True;
end;
{$WARNINGS ON}
function TGLDTube.GetMode: GLubyte;
begin
if GLDXGetAngle(FStartAngle, FSweepAngle) = 360 then
begin
if InnerRadius = 0 then
Result := 0
else Result := 1;
end else
begin
if InnerRadius = 0 then
Result := 2
else Result := 3;
end;
end;
function TGLDTube.GetOutsidePoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FOutsidePoints^[(i - 1) * (FSides + 3) + j + 1];
end;
function TGLDTube.GetInsidePoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FInsidePoints^[(i - 1) * (FSides + 3) + j + 1];
end;
function TGLDTube.GetTopPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FTopPoints^[(i - 1) * (FSides + 3) + j + 1];
end;
function TGLDTube.GetBasePoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FBasePoints^[(i - 1) * (FSides + 3) + j + 1];
end;
procedure TGLDTube.SetInnerRadius(Value: GLfloat);
begin
if FInnerRadius = Value then Exit;
FInnerRadius := Value;
CreateGeometry;
Change;
end;
procedure TGLDTube.SetOuterRadius(Value: GLfloat);
begin
if FOuterRadius = Value then Exit;
FOuterRadius := Value;
CreateGeometry;
Change;
end;
procedure TGLDTube.SetHeight(Value: GLfloat);
begin
if FHeight = Value then Exit;
FHeight := Value;
CreateGeometry;
Change;
end;
procedure TGLDTube.SetHeightSegs(Value: GLushort);
begin
if FHeightSegs = Value then Exit;
FHeightSegs := Value;
CreateGeometry;
Change;
end;
procedure TGLDTube.SetCapSegs(Value: GLushort);
begin
if FCapSegs = Value then Exit;
FCapSegs := Value;
CreateGeometry;
Change;
end;
procedure TGLDTube.SetSides(Value: GLushort);
begin
if FSides = Value then Exit;
FSides := Value;
CreateGeometry;
Change;
end;
procedure TGLDTube.SetStartAngle(Value: GLfloat);
begin
if FStartAngle = Value then Exit;
FStartAngle := Value;
CreateGeometry;
Change;
end;
procedure TGLDTube.SetSweepAngle(Value: GLfloat);
begin
if FSweepAngle = Value then Exit;
FSweepAngle := Value;
CreateGeometry;
Change;
end;
function TGLDTube.GetParams: TGLDTubeParams;
begin
Result := GLDXTubeParams(FColor.Color3ub, FInnerRadius, FOuterRadius,
FHeight, FHeightSegs, FCapSegs, FSides, FStartAngle, FSweepAngle,
FPosition.Vector3f, FRotation.Params);
end;
procedure TGLDTube.SetParams(Value: TGLDTubeParams);
begin
if GLDXTubeParamsEqual(GetParams, Value) then Exit;
PGLDColor3f(FColor.GetPointer)^ := GLDXColor3f(Value.Color);
FInnerRadius := Value.InnerRadius;
FOuterRadius := Value.OuterRadius;
FHeight := Value.Height;
FHeightSegs := Value.HeightSegs;
FCapSegs := Value.CapSegs;
FSides := Value.Sides;
FStartAngle := Value.StartAngle;
FSweepAngle := Value.SweepAngle;
PGLDVector3f(FPosition.GetPointer)^ := Value.Position;
PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation;
CreateGeometry;
Change;
end;
end.
|
////////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PAXCOMP_BASESYMBOL_TABLE.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
{$O-}
{$R-}
unit PAXCOMP_BASESYMBOL_TABLE;
interface
uses {$I uses.def}
TypInfo,
SysUtils,
Classes,
PAXCOMP_CONSTANTS,
PAXCOMP_TYPES,
PAXCOMP_SYS,
PAXCOMP_VAROBJECT,
PAXCOMP_HEADER_PARSER,
PAXCOMP_MAP,
PAXCOMP_CLASSFACT,
PAXCOMP_SYMBOL_REC;
type
TSaveStateRec = class
public
Id: Integer;
LastShiftValue: Integer;
LastClassIndex: Integer;
LastSubId: Integer;
LastVarId: Integer;
end;
TSaveStateList = class(TTypedList)
private
function GetRecord(I: Integer): TSaveStateRec;
public
function Add: TSaveStateRec;
function Find(Id: Integer): TSaveStateRec;
property Records[I: Integer]: TSaveStateRec read GetRecord;
end;
TBaseSymbolTable = class
private
LastCard: Integer;
SaveStateList: TSaveStateList;
function GetSizeOfPointer: Integer;
function GetSizeOfTMethod: Integer;
procedure CheckMemory(p: Pointer; Size: Cardinal);
procedure UpdateSomeTypeList(const TypeName: String; TypeId: Integer);
procedure CheckError(B: Boolean);
procedure BindDummyType(TypeId, OriginTypeId: Integer);
protected
function GetRecord(I: Integer): TSymbolRec; virtual;
public
st_tag: Integer;
{$IFDEF ARC}
A: TList<TSymbolRec>;
{$ELSE}
A: TList;
{$ENDIF}
Card: Integer;
ResultId: Integer;
TrueId: Integer;
FalseId: Integer;
NilId: Integer;
EventNilId: Integer;
EmptySetId: Integer;
EmptyStringId: Integer;
CurrExceptionObjectId: Integer;
VarObjects: TVarObjectList;
HashArray: THashArray;
HeaderParser: THeaderParser;
GuidList: TGuidList;
SomeTypeList: TSomeTypeList;
ExternList: TExternList;
LastShiftValue: Integer;
LastClassIndex: Integer;
LastSubId: Integer;
LastVarId: Integer;
SR0: TSymbolRec;
TypeHelpers: TAssocIntegers;
constructor Create(NeedHash: Boolean = True);
destructor Destroy; override;
function AddRecord: TSymbolRec; virtual;
procedure RemoveLastRecord;
procedure Reset; virtual;
procedure Discard(OldCard: Integer);
procedure SetPAX64(value: Boolean);
function LookupAnonymousInterface(ClassId: Integer): Integer;
function LookupAnonymousMethod(IntfId: Integer): Integer;
{$IFDEF PAXARM}
function AddPWideCharConst(const Value: String): TSymbolRec;
{$ELSE}
function AddPWideCharConst(const Value: WideString): TSymbolRec;
function AddAnsiCharConst(Value: AnsiChar): TSymbolRec;
function AddPAnsiCharConst(const Value: AnsiString): TSymbolRec;
function AddShortStringConst(const Value: String): TSymbolRec;
{$ENDIF}
function AddWideCharConst(Value: Integer): TSymbolRec;
function AddByteConst(Value: Byte): TSymbolRec;
function AddWordConst(Value: Word): TSymbolRec;
function AddIntegerConst(Value: Integer): TSymbolRec;
function AddInt64Const(Value: Int64): TSymbolRec;
function AddUInt64Const(Value: UInt64): TSymbolRec;
function AddCardinalConst(Value: Cardinal): TSymbolRec;
function AddSmallIntConst(Value: SmallInt): TSymbolRec;
function AddShortIntConst(Value: ShortInt): TSymbolRec;
function AddEnumConst(TypeId, Value: Integer): TSymbolRec;
function AddPointerConst(TypeId: Integer; Value: Pointer): TSymbolRec;
function AddRecordConst(TypeId: Integer; const Value: Variant): TSymbolRec;
function AddArrayConst(TypeId: Integer; const Value: Variant): TSymbolRec;
function AddSetConst(TypeId: Integer; const Value: Variant): TSymbolRec;
function AddClassConst(TypeId: Integer; Value: TObject): TSymbolRec;
function AddClassRefConst(TypeId: Integer; Value: TClass): TSymbolRec;
function AddSetVar(TypeId: Integer; const Value: Variant): TSymbolRec;
function AddDoubleConst(Value: Double): TSymbolRec;
function AddCurrencyConst(Value: Double): TSymbolRec;
function AddSingleConst(Value: Single): TSymbolRec;
function AddExtendedConst(Value: Extended): TSymbolRec;
function AddBooleanConst(Value: Boolean): TSymbolRec;
function AddByteBoolConst(Value: ByteBool): TSymbolRec;
function AddWordBoolConst(Value: WordBool): TSymbolRec;
function AddLongBoolConst(Value: LongBool): TSymbolRec;
function AddVariantConst(const Value: Variant): TSymbolRec;
function AddOleVariantConst(const Value: OleVariant): TSymbolRec;
function AddTMethodVar(Level: Integer): TSymbolRec;
function AddCurrencyVar(Level: Integer): TSymbolRec;
function AddDoubleVar(Level: Integer): TSymbolRec;
function AddSingleVar(Level: Integer): TSymbolRec;
function AddExtendedVar(Level: Integer): TSymbolRec;
function AddInt64Var(Level: Integer): TSymbolRec;
function AddUInt64Var(Level: Integer): TSymbolRec;
{$IFNDEF PAXARM}
function AddStringVar(Level: Integer): TSymbolRec;
function AddWideStringVar(Level: Integer): TSymbolRec;
function AddShortStringVar(Level, TypeId: Integer): TSymbolRec;
function AddAnsiCharVar(Level: Integer): TSymbolRec;
{$ENDIF}
function AddInterfaceVar(Level: Integer): TSymbolRec;
function AddClassVar(Level: Integer): TSymbolRec;
function AddUnicStringVar(Level: Integer): TSymbolRec;
function AddVariantVar(Level: Integer): TSymbolRec;
function AddOleVariantVar(Level: Integer): TSymbolRec;
function AddDynarrayVar(Level, TypeId: Integer): TSymbolRec;
function AddRecordVar(Level, TypeId: Integer): TSymbolRec;
function AddBooleanVar(Level: Integer): TSymbolRec;
function AddByteBoolVar(Level: Integer): TSymbolRec;
function AddWordBoolVar(Level: Integer): TSymbolRec;
function AddLongBoolVar(Level: Integer): TSymbolRec;
function AddIntegerVar(Level: Integer): TSymbolRec;
function AddCardinalVar(Level: Integer): TSymbolRec;
function AddSmallIntVar(Level: Integer): TSymbolRec;
function AddShortIntVar(Level: Integer): TSymbolRec;
function AddByteVar(Level: Integer): TSymbolRec;
function AddWordVar(Level: Integer): TSymbolRec;
function AddPointerVar(Level: Integer): TSymbolRec;
function AddWideCharVar(Level: Integer): TSymbolRec;
function AddVoidVar(Level: Integer; SZ: Integer): TSymbolRec;
function AddClassRefVar(Level: Integer): TSymbolRec;
function AddLabel: TSymbolRec;
function AddPointerType(SourceTypeId: Integer): TSymbolRec;
function AddEndOfClassHeader(ClassId: Integer): TSymbolRec;
function GetDataSize(UpperId: Integer = MaxInt - 1): Integer;
function LookUpEnumItem(const S: String; EnumTypeId: Integer;
UpCase: Boolean): Integer;
function LookupNamespace(const S: String;
i_Level: Integer; UpCase: Boolean): Integer;
function LookupFullName(const S: String; UpCase: Boolean): Integer;
function LookupFullNameEx(const S: String; UpCase: Boolean;
OverCount: Integer): Integer;
function LookUpType(const S: String; i_Level: Integer; UpCase: Boolean): Integer; overload;
function LookUpType(const S: String; UpCase: Boolean): Integer; overload;
function LookupParentMethodBase(SubId: Integer;
UpCase: Boolean;
var BestId: Integer): Integer;
function LookupParentMethod(SubId: Integer;
UpCase: Boolean; HasMethodIndex: Boolean = false): Integer;
function LookupParentMethods(SubId: Integer; Upcase: Boolean): TIntegerList;
function LookupParentConstructor(SubId: Integer): Integer;
function LookupParentConstructors(SubId: Integer): TIntegerList;
function LookUpTypeEx(const S: String;
i_Level: Integer; UpCase: Boolean; LowBound: Integer): Integer;
function LookUp(const S: String; Level: Integer; UpCase: Boolean;
UpperBoundId: Integer = MaxInt; recursive: Boolean = true): Integer;
function LookUpEx(var HelperTypeId: Integer; const S: String; Level: Integer; UpCase: Boolean;
UpperBoundId: Integer = MaxInt; recursive: Boolean = true): Integer;
function LookUps(const S: String; LevelStack: TIntegerStack;
UpCase: Boolean;
UpperBoundId: Integer = MaxInt;
Recursive: Boolean = true): Integer;
function LookUpsEx(const S: String; LevelStack: TIntegerStack; var LevelId: Integer; UpCase: Boolean): Integer;
function LookUpsExcept(const S: String; LevelStack: TIntegerStack; LevelId: Integer; UpCase: Boolean): Integer;
function LookUpAll(const S: String; Level: Integer; UpCase: Boolean): TIntegerList;
function LookUpSub(const S: String; Level: Integer; UpCase: Boolean): TIntegerList;
function LookUpSubs(const S: String; Level: Integer; UsingList: TIntegerList; UpCase: Boolean): TIntegerList;
function LookupAnotherDeclaration(Id: Integer; UpCase: Boolean;
var BestID: Integer): Integer;
function LookupForwardDeclaration(Id: Integer; UpCase: Boolean;
var BestID: Integer): Integer;
function LookupForwardDeclarations(Id: Integer;
UpCase: Boolean): TIntegerList;
function RegisterNamespace(LevelId: Integer;
const NamespaceName: String): Integer;
function RegisterArrayType(LevelId: Integer;
const TypeName: String;
RangeTypeId, ElemTypeId: Integer;
Align: Integer): Integer;
function RegisterDynamicArrayType(LevelId: Integer;
const TypeName: String;
ElemTypeId: Integer): Integer;
function RegisterOpenArrayType(LevelId: Integer;
const TypeName: String;
ElemTypeId: Integer): Integer;
function FindInterfaceTypeId(const GUID: TGUID): Integer;
function RegisterInterfaceType(LevelId: Integer;
const TypeName: String;
const GUID: TGUID): Integer; overload;
function RegisterInterfaceType(LevelId: Integer;
pti: PTypeInfo): Integer; overload;
procedure RegisterSupportedInterface(TypeId: Integer;
const SupportedInterfaceName: String;
const i_GUID: TGUID); overload;
procedure RegisterSupportedInterface(TypeId,
InterfaceTypeId: Integer); overload;
function RegisterClassType(LevelId: Integer;
const TypeName: String; i_AncestorID: Integer): Integer; overload;
function RegisterClassType(LevelId: Integer;
C: TClass;
Reserved: Integer = 0): Integer; overload;
function RegisterClassTypeForImporter(LevelId: Integer;
C: TClass): Integer; overload;
function RegisterClassTypeForImporter(LevelId: Integer;
const TypeName: String): Integer; overload;
procedure RegisterClassTypeInfos(ClassId: Integer;
C: TClass);
function RegisterClassReferenceType(LevelId: Integer;
const TypeName: String;
OriginClassId: Integer): Integer;
function RegisterHelperType(LevelId: Integer;
const TypeName: String;
OriginTypeId: Integer): Integer;
function RegisterProperty(LevelId: Integer; const PropName: String;
PropTypeID, i_ReadId, i_WriteId: Integer;
i_IsDefault: Boolean): Integer;
function RegisterInterfaceProperty(LevelId: Integer;
const PropName: String;
PropTypeID,
ReadIndex,
WriteIndex: Integer): Integer;
function RegisterRecordType(LevelId: Integer;
const TypeName: String;
Align: Integer): Integer;
function RegisterRTTIType(LevelId: Integer;
pti: PTypeInfo): Integer;
function RegisterTypeAlias(LevelId:Integer;
const TypeName: String;
OriginTypeId: Integer;
const OriginTypeName: String = ''): Integer; overload;
function RegisterTypeAlias(LevelId:Integer;
const TypeName, OriginTypeName: String): Integer; overload;
function RegisterTypeAlias(LevelId:Integer;
const Declaration: String): Integer; overload;
function RegisterTypeField(LevelId: Integer; const FieldName: String;
FieldTypeID: Integer;
FieldOffset: Integer = -1;
ACompIndex: Integer = -1): Integer;
function RegisterTypeFieldEx(LevelId: Integer;
const Declaration: String;
FieldOffset: Integer = -1): Integer;
function RegisterVariantRecordTypeField(LevelId: Integer;
const Declaration: String;
VarCnt: Int64): Integer; overload;
function RegisterVariantRecordTypeField(LevelId: Integer;
const FieldName: String;
FieldTypeID: Integer;
VarCnt: Int64): Integer; overload;
function RegisterSubrangeType(LevelId: Integer;
const TypeName: String;
TypeBaseId: Integer;
B1, B2: Integer): Integer;
function RegisterEnumType(LevelId: Integer;
const TypeName: String;
TypeBaseId: Integer): Integer;
function RegisterEnumValue(EnumTypeId: Integer;
const FieldName: String;
const i_Value: Integer): Integer;
function RegisterPointerType(LevelId: Integer;
const TypeName: String;
OriginTypeId: Integer;
const OriginTypeName: String = ''): Integer;
{$IFNDEF PAXARM}
function RegisterShortStringType(LevelId: Integer;
const TypeName: String;
L: Integer): Integer;
{$ENDIF}
function RegisterSetType(LevelId: Integer;
const TypeName: String;
OriginTypeId: Integer): Integer;
function CreateEmptySet: TSymbolRec;
function RegisterProceduralType(LevelId: Integer;
const TypeName: String;
HSub: Integer): Integer;
function RegisterMethodReferenceType(LevelId: Integer;
const TypeName: String;
HSub: Integer): Integer;
function RegisterEventType(LevelId: Integer;
const TypeName: String;
HSub: Integer): Integer;
function RegisterVariable(LevelId: Integer;
const Declaration: String; Address: Pointer): Integer; overload;
function RegisterVariable(LevelId: Integer; const VarName: String;
VarTypeID: Integer; i_Address: Pointer): Integer; overload;
function RegisterObject(LevelId: Integer;
const ObjectName: String;
TypeId: Integer;
i_Address: Pointer): Integer;
function RegisterVirtualObject(LevelId: Integer;
const ObjectName: String): Integer;
function RegisterConstant(LevelId: Integer;
const Declaration: String): Integer; overload;
function RegisterConstant(LevelId: Integer; const i_Name: String; i_TypeID: Integer;
const i_Value: Variant): Integer; overload;
function RegisterConstant(LevelId: Integer; const i_Name: String;
const i_Value: Variant): Integer; overload;
function RegisterPointerConstant(LevelId: Integer; const i_Name: String;
const i_Value: Pointer): Integer; overload;
function RegisterExtendedConstant(LevelId: Integer; const i_Name: String;
const i_Value: Extended): Integer; overload;
function RegisterInt64Constant(LevelId: Integer;
const i_Name: String; const i_Value: Int64): Integer;
function RegisterRoutine(LevelId: Integer;
const SubName: String; ResultTypeID: Integer;
CallConvention: Integer;
i_Address: Pointer;
i_OverCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer; overload;
function RegisterRoutine(LevelId: Integer;
const SubName, ResultType: String;
CallConvention: Integer;
i_Address: Pointer;
i_OverCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer; overload;
function RegisterMethod(LevelId: Integer;
const SubName: String; ResultTypeID: Integer;
CallConvention: Integer;
i_Address: Pointer;
IsShared: Boolean = false;
i_CallMode: Integer = cmNONE;
i_MethodIndex: Integer = 0;
i_OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer; overload;
function RegisterMethod(LevelId: Integer;
const SubName, ResultType: String;
CallConvention: Integer;
i_Address: Pointer;
IsShared: Boolean = false;
i_CallMode: Integer = cmNONE;
i_MethodIndex: Integer = 0;
i_OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer; overload;
function RegisterConstructor(LevelId: Integer;
const SubName: String;
i_Address: Pointer;
IsShared: Boolean = false;
i_CallMode: Integer = cmNONE;
i_MethodIndex: Integer = 0;
i_OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
function RegisterDestructor(LevelId: Integer;
const SubName: String; i_Address: Pointer;
i_CallMode: Integer = cmVIRTUAL): Integer;
function RegisterParameter(HSub: Integer;
const ParameterName: String;
ParamTypeID: Integer;
ParamMod: Integer = 0;
Optional: Boolean = false;
const DefaultValue: String = ''): Integer; overload;
function RegisterParameter(HSub: Integer;
const ParameterName: String;
const ParameterType: String;
ParamMod: Integer = 0;
Optional: Boolean = false;
const DefaultValue: String = ''): Integer; overload;
function RegisterParameter(HSub: Integer; ParamTypeID: Integer;
const DefaultValue: Variant;
InitByRef: Boolean = false;
ParameterName: String = '';
Tag: Integer = 0): Integer; overload;
procedure RegisterRunnerParameter(HSub: Integer);
function RegisterHeader(LevelId: Integer;
const Header: String; Address: Pointer;
AMethodIndex: Integer = 0): Integer;
function RegisterFakeHeader(LevelId: Integer;
const Header: String; Address: Pointer): Integer;
procedure RegisterMember(LevelId: Integer; const MemberName: String;
i_Address: Pointer);
function RegisterTypeDeclaration(LevelId: Integer;
const Declaration: String): Integer;
function RegisterSpace(K: Integer): Integer;
function RestorePositiveIndex(L: Integer): Integer;
function FindMaxMethodIndex(IntfId: Integer): Integer;
procedure SetAncestorEx(ClassId: Integer);
function IsResultId(Id: Integer): Boolean;
function GetResultId(SubId: Integer): Integer;
function GetSelfId(SubId: Integer): Integer;
function GetParamId(SubId, ParamNumber: Integer): Integer;
function GetDL_Id(SubId: Integer): Integer;
function GetRBP_Id(SubId: Integer): Integer;
function GetRBX_Id(SubId: Integer): Integer;
function GetRDI_Id(SubId: Integer): Integer;
function GetSizeOfLocals(SubId: Integer): Integer;
function GetSizeOfLocalsEx(SubId: Integer): Integer;
function GetSubRSPSize(SubId: Integer): Integer;
function GetSizeOfSetType(SetTypeId: Integer): Integer;
function CheckSetTypes(T1, T2: Integer): Boolean;
function GetLowBoundRec(TypeID: Integer): TSymbolRec;
function GetHighBoundRec(TypeID: Integer): TSymbolRec;
procedure GetArrayTypeInfo(ArrayTypeId: Integer; var RangeTypeId: Integer; var ElemTypeId: Integer);
{$IFNDEF PAXARM}
function IsZeroBasedAnsiCharArray(Id: Integer): Boolean;
{$ENDIF}
function IsZeroBasedWideCharArray(Id: Integer): Boolean;
function GetTypeBase(TypeId: Integer): Integer;
function GetPatternSubId(ProcTypeID: Integer): Integer;
function EqualHeaders(SubId1, SubId2: Integer): Boolean;
function GetShiftsOfDynamicFields(ATypeId: Integer): TIntegerList;
function GetTypesOfDynamicFields(ATypeId: Integer): TIntegerList;
function HasDynamicFields(ATypeId: Integer): Boolean;
function TerminalTypeOf(TypeID: Integer): Integer;
function FindDefaultPropertyId(i_TypeId: Integer): Integer;
function FindConstructorId(i_TypeId: Integer): Integer;
function FindConstructorIdEx(i_TypeId: Integer): Integer;
function FindConstructorIds(i_TypeId: Integer): TIntegerList;
function FindDestructorId(i_TypeId: Integer): Integer;
function FindDestructorIdEx(i_TypeId: Integer): Integer;
function Inherits(T1, T2: Integer): Boolean;
function Supports(T1, T2: Integer): Boolean;
function GetFinalAddress(P: Pointer; StackFrameNumber: Integer;
Id: Integer): Pointer;
function GetStrVal(Address: Pointer;
TypeId: Integer;
TypeMapRec: TTypeMapRec = nil;
BriefCls: Boolean = false): String;
function GetVariantVal(Address: Pointer;
TypeId: Integer;
TypeMapRec: TTypeMapRec = nil): Variant;
function GetValueAsString(P: Pointer;
StackFrameNumber: Integer;
Id: Integer;
TypeMapRec: TTypeMapRec = nil;
BriefCls: Boolean = false): String; virtual;
procedure CheckVariantData (const V);
function GetVal(Address: Pointer;
TypeId: Integer): Variant;
function GetValue(P: Pointer; StackFrameNumber: Integer;
Id: Integer): Variant;
procedure PutVal(Address: Pointer;
TypeId: Integer; const Value: Variant);
procedure PutValue(P: Pointer; StackFrameNumber: Integer;
Id: Integer; const Value: Variant);
function GetLocalCount(SubId: Integer): Integer;
function GetLocalId(SubId, LocalVarNumber: Integer): Integer;
function IsLocalOf(Id, SubId: Integer): Boolean;
function GetGlobalCount(NamespaceId: Integer): Integer;
function GetGlobalId(NamespaceId, GlobalVarNumber: Integer): Integer;
function GetFieldCount(Id: Integer; TypeMapRec: TTypeMapRec = nil): Integer;
function GetFieldDescriptorId(Id,
FieldNumber: Integer;
TypeMapRec: TTypeMapRec = nil): Integer;
function GetFieldDescriptorIdByName(Id: Integer; const FieldName: String): Integer;
function GetFieldName(Id, FieldNumber: Integer): String;
function GetFieldAddress(P: Pointer;
StackFrameNumber,
Id,
FieldNumber: Integer;
TypeMapRec: TTypeMapRec = nil
): Pointer;
function GetFieldValueAsString(P: Pointer;
StackFrameNumber: Integer;
Id: Integer;
FieldNumber: Integer;
TypeMapRec: TTypeMapRec = nil;
BriefCls: Boolean = false): String;
function GetPublishedPropCount(Id: Integer): Integer;
function GetPublishedPropDescriptorId(Id, PropNumber: Integer): Integer;
function GetPublishedPropName(Id, PropNumber: Integer): String;
function GetPublishedPropValueAsString(P: Pointer; StackFrameNumber: Integer;
Id, PropNumber: Integer): String;
function GetArrayItemAddress(P: Pointer; StackFrameNumber, Id,
Index: Integer): Pointer;
function GetArrayItemValueAsString(P: Pointer; StackFrameNumber: Integer;
Id, Index: Integer): String;
function GetDynArrayItemAddress(P: Pointer;
StackFrameNumber: Integer;
Id, Index: Integer): Pointer;
function GetDynArrayItemValueAsString(P: Pointer; StackFrameNumber: Integer;
Id, Index: Integer): String;
function IsParam(SubId, Id: Integer): Boolean;
function IsVar(LevelId, Id: Integer): Boolean;
function IsConst(LevelId, Id: Integer): Boolean;
function IsType(LevelId, Id: Integer): Boolean;
function IsProcedure(LevelId, Id: Integer): Boolean;
function IsFunction(LevelId, Id: Integer): Boolean;
function IsConstructor(ClassId, Id: Integer): Boolean;
function IsDestructor(ClassId, Id: Integer): Boolean;
function IsTypeField(LevelId, Id: Integer): Boolean;
function IsEnumMember(LevelId, Id: Integer): Boolean;
function IsProperty(ClassId, Id: Integer): Boolean;
function IsNamespace(LevelId, Id: Integer): Boolean;
function HasAbstractAncestor(ClassId: Integer): Boolean;
{$IFNDEF PAXARM}
function FindPAnsiCharConst(const S: String; LimitId: Integer): Integer;
{$ENDIF}
function FindPWideCharConst(const S: String; LimitId: Integer): Integer;
function RegisterDummyType(LevelId: Integer;
const TypeName: String): Integer;
function RegisterSomeType(LevelId: Integer;
const TypeName: String): Integer;
function GetAlignmentSize(TypeId, DefAlign: Integer): Integer;
procedure SetVisibility(ClassId: integer;
const MemberName: String; value: Integer); overload;
procedure SetVisibility(C: TClass; const MemberName: String; value: Integer); overload;
function FindClassTypeId(Cls: TClass): Integer;
function FindClassTypeIdByPti(Pti: PTypeInfo): Integer;
procedure SaveNamespaceToStream(LevelId: Integer; S: TStream); overload;
procedure SaveNamespaceToStream(const NamespaceName: String; S: TStream); overload;
procedure SaveNamespaceToFile(LevelId: Integer; const FileName: String); overload;
procedure SaveNamespaceToFile(const NamespaceName, FileName: String); overload;
procedure LoadNamespaceFromStream(S: TStream);
procedure LoadNamespaceFromFile(const FileName: String);
procedure ResolveExternList(CheckProc: TCheckProc; Data: Pointer);
procedure AddScriptFields(ClassId: Integer; FieldList: TMapFieldList);
procedure ExtractNamespaces(const Level: Integer; L: TStrings);
procedure ExtractMembers(const Id: Integer; L: TStrings;
Lang: TPaxLang = lngPascal;
SharedOnly: Boolean = false;
VisSet: TMemberVisibilitySet = [cvPublic, cvPublished]);
procedure ExtractParameters(Id: Integer; L: TStrings;
Lang: TPaxLang = lngPascal;
SkipParameters: Integer = 0);
procedure ExtractParametersEx(Id: Integer;
L: TStrings;
Upcase: Boolean;
SkipParameters: Integer = 0);
function ValueStr(I: Integer): String;
procedure AddTypes(const TypeName: String; L: TStrings;
ErrorIndex: Integer; Upcase: Boolean);
procedure AddUndeclaredIdent(const IdentName: String; L: TStrings;
ErrorIndex: Integer; Upcase: Boolean);
procedure CreateInterfaceMethodList(IntfId: Integer;
L: TIntegerList); overload;
procedure CreateInterfaceMethodList(ClassId, IntfId: Integer;
InterfaceMethodIds,
ClassMethodIds: TIntegerList); overload;
procedure ProcessClassFactory(AClassFactory: Pointer;
AProg: Pointer);
procedure HideClass(C: TClass);
function ImportFromTable(st: TBaseSymbolTable;
const FullName: String;
UpCase: Boolean;
DoRaiseError: Boolean = true): Integer;
procedure LoadGlobalSymbolTableFromStream(Stream: TStream);
procedure LoadGlobalSymbolTableFromFile(const FileName: String);
procedure SaveGlobalSymbolTableToStream(Stream: TStream);
procedure SaveGlobalSymbolTableToFile(const FileName: String);
procedure SaveState;
procedure RestoreState(Id: Integer);
function GetOpenArrayHighId(Id: Integer): Integer;
function GetOuterThisId(TypeId: Integer): Integer;
function GetTypeParameters(Id: Integer): TIntegerList;
function ExtractEnumNames(EnumTypeId: Integer): TStringList;
function GetTypeHelpers(TypeId: Integer): TIntegerList;
procedure RaiseError(const Message: string; params: array of const);
property Records[I: Integer]: TSymbolRec read GetRecord; default;
property SizeOfPointer: Integer read GetSizeOfPointer;
property SizeOfTMethod: Integer read GetSizeOfTMethod;
end;
var
RegisterDRTTIProperties: procedure (Level: Integer;
c: TClass;
s: TBaseSymbolTable) = nil;
// Added callback to get namespace of type.
GetNamespaceOfType: function (aSymbolTable: TBaseSymbolTable; aTypeInfo: PTypeInfo): Integer = nil;
GlobalAlignment: Integer = 8;
RaiseE: Boolean = true;
REG_OK: Boolean = true;
REG_ERROR: String;
DllDefined: Boolean = false;
H_TByteSet: Integer = -1;
GlobalCurrExceptionObjectId: Integer = -1;
JS_JavaScriptNamespace: Integer = 1;
JS_GetPropertyId: Integer = 0;
JS_PutPropertyId: Integer = 0;
JS_GetArrPropertyId: Integer = 0;
JS_PutArrPropertyId: Integer = 0;
JS_GetPropertyAsObjectId: Integer = 0;
JS_ObjectClassId: Integer = 0;
JS_BooleanClassId: Integer = 0;
JS_FunctionClassId: Integer = 0;
JS_StringClassId: Integer = 0;
JS_NumberClassId: Integer = 0;
JS_DateClassId: Integer = 0;
JS_ArrayClassId: Integer = 0;
JS_MathClassId: Integer = 0;
JS_RegExpClassId: Integer = 0;
JS_ErrorClassId: Integer = 0;
JS_FunctionCallId: Integer = 0;
JS_TempNamespaceId: Integer = 0;
JS_GetGenericPropertyId: Integer = 0;
JS_PutGenericPropertyId: Integer = 0;
JS_ToObjectId: Integer = 0;
JS_GetNextPropId: Integer = 0;
JS_TypeOfId: Integer = 0;
JS_VoidId: Integer = 0;
JS_FindFuncId: Integer = 0;
JS_AssignProgId: Integer = 0;
JS_ClearReferencesId: Integer = 0;
JS_AlertId: Integer = 0;
JS_Delete: Integer = 0;
type
TGetOleProp =
procedure (const D: Variant; PropName: PChar;
var Result: Variant;
ParamCount: Integer); stdcall;
TPutOleProp =
procedure (const D: Variant; PropName: PChar;
const Value: Variant;
ParamCount: Integer); stdcall;
var
GetOlePropProc: TGetOleProp = nil;
PutOlePropProc: TPutOleProp = nil;
function IsFrameworkTypeId(Id: Integer): Boolean;
implementation
uses
PAXCOMP_BASERUNNER,
PAXCOMP_LOCALSYMBOL_TABLE,
PAXCOMP_GC,
PAXCOMP_STDLIB;
{$IFNDEF UNIX}
{$IFNDEF PAXARM}
{$IFNDEF LINUX}
{$IFNDEF MACOS32}
function GetReadableSize(Address, Size: DWord): DWord;
const
ReadAttributes = [PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, PAGE_EXECUTE,
PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY];
var
MemInfo: TMemoryBasicInformation;
Tmp: DWord;
begin
Result := 0;
if (VirtualQuery(Pointer(Address), MemInfo, SizeOf(MemInfo)) = SizeOf(MemInfo)) and
(MemInfo.State = MEM_COMMIT) and (MemInfo.Protect in ReadAttributes) then
begin
Result := (MemInfo.RegionSize - (Address - DWord(MemInfo.BaseAddress)));
if (Result < Size) then
begin
repeat
Tmp := GetReadableSize((DWord(MemInfo.BaseAddress) + MemInfo.RegionSize), (Size - Result));
if (Tmp > 0) then Inc(Result, Tmp)
else Result := 0;
until (Result >= Size) or (Tmp = 0);
end;
end;
end;
function IsValidBlockAddr(Address, Size: DWord): Boolean;
begin
try
Result := (GetReadableSize(Address, Size) >= Size);
except
Result := false;
end;
end;
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
function TSaveStateList.GetRecord(I: Integer): TSaveStateRec;
begin
result := TSaveStateRec(L[I]);
end;
function TSaveStateList.Add: TSaveStateRec;
begin
result := TSaveStateRec.Create;
L.Add(result);
end;
function TSaveStateList.Find(Id: Integer): TSaveStateRec;
var
I: Integer;
begin
result := nil;
for I := 0 to L.Count - 1 do
if Records[I].Id = Id then
begin
result := Records[I];
Exit;
end;
end;
procedure TBaseSymbolTable.CheckMemory(p: Pointer; Size: Cardinal);
begin
{$IFNDEF UNIX}
{$IFNDEF PAXARM}
{$IFNDEF LINUX}
{$IFNDEF MACOS32}
if not IsValidBlockAddr(Cardinal(p), Size) then
raise EAbort.Create(errMemoryNotInitialized);
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
end;
constructor TBaseSymbolTable.Create(NeedHash: Boolean = True);
begin
inherited Create;
{$IFDEF ARC}
A := TList<TSymbolRec>.Create;
{$ELSE}
A := TList.Create;
{$ENDIF}
HeaderParser := THeaderParser.Create;
Card := -1;
VarObjects := TVarObjectList.Create(Self);
if NeedHash then
HashArray := THashArray.Create
else
HashArray := nil;
GuidList := TGuidList.Create;
SomeTypeList := TSomeTypeList.Create;
ExternList := TExternList.Create;
SaveStateList := TSaveStateList.Create;
TypeHelpers := TAssocIntegers.Create;
LastCard := 0;
end;
destructor TBaseSymbolTable.Destroy;
var
I: Integer;
begin
FreeAndNil(VarObjects);
for I := A.Count - 1 downto 0 do
{$IFDEF ARC}
A[I] := nil;
{$ELSE}
TSymbolRec(A[I]).Free;
{$ENDIF}
FreeAndNil(A);
FreeAndNil(HeaderParser);
if HashArray <> nil then
FreeAndNil(HashArray);
FreeAndNil(GuidList);
FreeAndNil(SomeTypeList);
FreeAndNil(ExternList);
FreeAndNil(SaveStateList);
FreeAndNil(TypeHelpers);
inherited;
end;
procedure TBaseSymbolTable.SaveState;
var
R: TSaveStateRec;
begin
R := SaveStateList.Add;
R.Id := Card;
R.LastShiftValue := LastShiftValue;
R.LastClassIndex := LastClassIndex;
R.LastSubId := LastSubId;
R.LastVarId := LastVarId;
end;
procedure TBaseSymbolTable.RestoreState(Id: Integer);
var
R: TSaveStateRec;
begin
R := SaveStateList.Find(Id);
if R <> nil then
begin
Card := Id;
LastShiftValue := R.LastShiftValue;
LastClassIndex := R.LastClassIndex;
LastSubId := R.LastSubId;
LastVarId := R.LastVarId;
end;
end;
procedure TBaseSymbolTable.Reset;
var
I: Integer;
R: TSymbolRec;
begin
VarObjects.Clear;
ExternList.Clear;
SomeTypeList.Clear;
SaveStateList.Clear;
TypeHelpers.Clear;
for I:=0 to A.Count - 1 do
{$IFDEF ARC}
A[I] := nil;
{$ELSE}
Records[I].Free;
{$ENDIF}
A.Clear;
Card := -1;
for I:=0 to Types.Count - 1 do
begin
R := AddRecord;
R.Name := Types[I].Name;
R.Kind := KindTYPE;
R.Completed := true;
end;
SR0 := Records[0];
{$IFDEF PAXARM}
while Card < typePVOID - 1 do
AddRecord;
{$ELSE}
while Card < typePANSICHAR - 1 do
AddRecord;
{$ENDIF}
{$IFNDEF PAXARM}
RegisterPointerType(0, 'PCHAR', typeANSICHAR);
{$ENDIF}
RegisterPointerType(0, 'PVOID', typeVOID);
RegisterPointerType(0, 'PWIDECHAR', typeWIDECHAR);
with AddRecord do
begin
NilId := Id;
Kind := KindCONST;
TypeId := typePOINTER;
Level := 0;
Value := 0;
end;
with AddBooleanConst(false) do
begin
FalseId := Id;
Name := 'false';
Level := typeBOOLEAN;
end;
with AddBooleanConst(true) do
begin
TrueId := Id;
Name := 'true';
Level := typeBOOLEAN;
end;
with AddByteBoolConst(Low(ByteBool)) do
Level := typeBYTEBOOL;
with AddByteBoolConst(High(ByteBool)) do
Level := typeBYTEBOOL;
with AddWordBoolConst(Low(WordBool)) do
Level := typeWORDBOOL;
with AddWordBoolConst(High(WordBool)) do
Level := typeWORDBOOL;
with AddLongBoolConst(Low(LongBool)) do
Level := typeLONGBOOL;
with AddLongBoolConst(High(LongBool)) do
Level := typeLONGBOOL;
{$IFNDEF PAXARM}
with AddAnsiCharConst(Low(AnsiChar)) do
Level := typeANSICHAR;
with AddAnsiCharConst(High(AnsiChar)) do
Level := typeANSICHAR;
{$ENDIF}
with AddByteConst(Low(Byte)) do
Level := typeBYTE;
with AddByteConst(High(Byte)) do
Level := typeBYTE;
with AddWordConst(Low(Word)) do
Level := typeWORD;
with AddWordConst(High(Word)) do
Level := typeWORD;
with AddIntegerConst(Low(Integer)) do
Level := typeINTEGER;
with AddIntegerConst(High(Integer)) do
Level := typeINTEGER;
with AddInt64Const(Low(Int64)) do
Level := typeINT64;
with AddInt64Const(High(Int64)) do
Level := typeINT64;
with AddUInt64Const(Low(UInt64)) do
Level := typeUINT64;
with AddUInt64Const(High(Int64)) do
Level := typeUINT64;
with AddCardinalConst(Low(Cardinal)) do
Level := typeCARDINAL;
with AddCardinalConst(High(Cardinal)) do
Level := typeCARDINAL;
with AddSmallIntConst(Low(SmallInt)) do
Level := typeSMALLINT;
with AddSmallIntConst(High(SmallInt)) do
Level := typeSMALLINT;
with AddShortIntConst(Low(ShortInt)) do
Level := typeSHORTINT;
with AddShortIntConst(High(ShortInt)) do
Level := typeSHORTINT;
Records[typePOINTER].PatternId := typeVOID;
R := AddRecord;
R.Kind := KindVAR;
ResultID := R.Id;
R := AddRecord;
R.Kind := KindNONE;
R.TypeId := typePOINTER;
R.Shift := H_SelfPtr;
R := AddRecord;
R.Kind := KindVAR;
R.TypeId := typePOINTER;
R.Shift := H_ExceptionPtr;
R.Host := true;
CurrExceptionObjectId := R.Id;
GlobalCurrExceptionObjectId := CurrExceptionObjectId;
R := AddRecord;
R.Kind := KindNONE;
R.TypeId := typeINTEGER;
R.Shift := H_ByteCodePtr;
R := AddRecord;
R.Kind := KindNONE;
R.TypeId := typeINTEGER;
R.Shift := H_Flag;
R := AddRecord;
R.Kind := KindNONE;
R.TypeId := typeINTEGER;
R.Shift := H_SkipPop;
LastShiftValue := H_SkipPop + SizeOf(Integer);
R := CreateEmptySet;
EmptySetId := R.Id;
H_TByteSet := RegisterSetType(0, '$$', typeBYTE);
{$IFDEF PAXARM}
EmptyStringId := AddPWideCharConst('').Id;
{$ELSE}
EmptyStringId := AddPAnsiCharConst('').Id;
{$ENDIF}
with AddRecord do
begin
EventNilId := Id;
Kind := KindVAR;
TypeId := typeEVENT;
Level := 0;
Value := 0;
Shift := LastShiftValue;
Inc(LastShiftValue, SizeOfTMethod);
end;
if LastShiftValue <> FirstShiftValue then
RaiseError(errInternalError, []);
LastClassIndex := -1;
end;
procedure TBaseSymbolTable.Discard(OldCard: Integer);
var
I, Id: Integer;
S: String;
begin
while Card > OldCard do
begin
S := Records[Card].Name;
Id := Records[Card].Id;
HashArray.DeleteName(S, Id);
I := Card - FirstLocalId - 1;
{$IFDEF ARC}
A[I] := nil;
{$ELSE}
TSymbolRec(A[I]).Free;
{$ENDIF}
A.Delete(I);
Dec(Card);
end;
end;
function TBaseSymbolTable.RegisterNamespace(LevelId: Integer;
const NamespaceName: String): Integer;
var
Q: TStringList;
S: String;
I: Integer;
begin
result := LookupNamespace(NamespaceName, LevelId, true);
if result > 0 then
begin
HeaderParser.NamespaceId := result;
Exit;
end;
if PosCh('.', NamespaceName) > 0 then
begin
Q := ExtractNames(NamespaceName);
try
for I := 0 to Q.Count - 1 do
begin
S := Q[I];
if StrEql(S, 'System') then
result := 0
else
result := RegisterNamespace(result, S);
end;
finally
FreeAndNil(Q);
end;
Exit;
end
else
S := NamespaceName;
LastCard := Card;
with AddRecord do
begin
Name := S;
Kind := KindNAMESPACE;
Host := true;
Level := LevelId;
result := Id;
end;
HeaderParser.NamespaceId := result;
end;
function TBaseSymbolTable.RegisterTypeDeclaration(LevelId: Integer;
const Declaration: String): Integer;
begin
HeaderParser.Init(Declaration, Self, LevelId);
HeaderParser.Call_SCANNER;
result := HeaderParser.Register_TypeDeclaration;
end;
procedure TBaseSymbolTable.UpdateSomeTypeList(const TypeName: String; TypeId: Integer);
var
I, Id: Integer;
R: TSymbolRec;
begin
I := SomeTypeList.IndexOf(TypeName);
if I = -1 then
Exit;
Id := SomeTypeList[I].Id;
SomeTypeList.RemoveAt(I);
for I := Card downto StdCard do
begin
R := Records[I];
if R.PatternId = Id then
R.PatternId := TypeId;
end;
Records[Id].Kind := KindNONE;
Records[Id].Name := '';
end;
function TBaseSymbolTable.RegisterSubrangeType(LevelId: Integer;
const TypeName: String;
TypeBaseId: Integer;
B1, B2: Integer): Integer;
begin
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
LastCard := Card;
if not TypeBaseId in OrdinalTypes then
begin
result := 0;
RaiseError(errInternalError, []);
Exit;
end;
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := TypeBaseId;
Host := true;
Shift := 0;
Level := LevelId;
result := Id;
Completed := true;
end;
with AddRecord do
begin
Kind := KindCONST;
TypeID := TypeBaseId;
Host := true;
Shift := 0;
Level := result;
Value := B1;
end;
with AddRecord do
begin
Kind := KindCONST;
TypeID := TypeBaseId;
Host := true;
Shift := 0;
Level := result;
Value := B2;
end;
end;
function TBaseSymbolTable.RegisterEnumType(LevelId: Integer;
const TypeName: String;
TypeBaseId: Integer): Integer;
begin
LastCard := Card;
if TypeName <> '' then
begin
result := LookUpType(TypeName, LevelId, true);
if (result > 0) and (Records [Result].Level = LevelID) then
Exit;
end;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeENUM;
Host := true;
Shift := 0;
Level := LevelId;
PatternId := TypeBaseId;
result := Id;
end;
BindDummyType(result, TypeBaseId);
end;
function TBaseSymbolTable.RegisterEnumValue(EnumTypeId: Integer;
const FieldName: String;
const i_Value: Integer): Integer;
begin
with AddRecord do
begin
Name := FieldName;
Kind := KindCONST;
TypeID := EnumTypeId;
Host := true;
Shift := 0;
Level := Records[EnumTypeId].Level;
OwnerId := TypeId;
Value := i_Value;
result := Id;
end;
if EnumTypeId > 0 then
Records[EnumTypeId].Count := Records[EnumTypeId].Count + 1;
end;
function TBaseSymbolTable.RegisterArrayType(LevelId: Integer;
const TypeName: String;
RangeTypeId, ElemTypeId: Integer;
Align: Integer): Integer;
begin
LastCard := Card;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeARRAY;
Host := true;
Shift := 0;
Level := LevelId;
DefaultAlignment := Align;
result := Id;
Completed := true;
end;
with AddRecord do
begin
Kind := KindTYPE;
TypeID := typeALIAS;
Host := true;
Shift := 0;
Level := result;
PatternId := RangeTypeId;
end;
with AddRecord do
begin
Kind := KindTYPE;
TypeID := typeALIAS;
Host := true;
Shift := 0;
Level := result;
PatternId := ElemTypeId;
end;
end;
function TBaseSymbolTable.RegisterTypeAlias(LevelId:Integer;
const TypeName: String;
OriginTypeId: Integer;
const OriginTypeName: String = ''): Integer;
begin
LastCard := Card;
result := LookupType(TypeName, LevelId, true);
if result > 0 then
begin
if Records[result].Level = LevelId then
if result > OriginTypeId then
Exit;
end;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeALIAS;
Host := true;
Shift := 0;
Level := LevelId;
PatternId := OriginTypeId;
result := Id;
end;
if OriginTypeId = 0 then
if OriginTypeName <> '' then
begin
ExternList.Add(Card,
OriginTypeName,
erPatternId);
end;
BindDummyType(result, OriginTypeId);
end;
function TBaseSymbolTable.RegisterTypeAlias(LevelId:Integer;
const TypeName, OriginTypeName: String): Integer;
var
TypeId: Integer;
begin
TypeId := LookupType(OriginTypeName, true);
result := RegisterTypeAlias(LevelId, TypeName, TypeId, OriginTypeName);
end;
function TBaseSymbolTable.RegisterTypeAlias(LevelId:Integer;
const Declaration: String): Integer;
var
TypeName: String;
begin
HeaderParser.Init(Declaration, Self, LevelId);
HeaderParser.Call_SCANNER;
TypeName := HeaderParser.Parse_Ident;
result := HeaderParser.Register_TypeAlias(TypeName);
end;
function TBaseSymbolTable.RegisterPointerType(LevelId: Integer;
const TypeName: String;
OriginTypeId: Integer;
const OriginTypeName: String = ''): Integer;
begin
LastCard := Card;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typePOINTER;
Host := true;
Shift := 0;
Level := LevelId;
PatternId := OriginTypeId;
result := Id;
Completed := true;
end;
if OriginTypeId = 0 then
if OriginTypeName <> '' then
begin
ExternList.Add(Card,
OriginTypeName,
erPatternId);
end;
end;
function TBaseSymbolTable.RegisterDynamicArrayType(LevelId: Integer;
const TypeName: String;
ElemTypeId: Integer): Integer;
begin
LastCard := Card;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeDYNARRAY;
Host := true;
Shift := 0;
Level := LevelId;
PatternId := ElemTypeId;
result := Id;
Completed := true;
end;
BindDummyType(result, ElemTypeId);
end;
function TBaseSymbolTable.RegisterOpenArrayType(LevelId: Integer;
const TypeName: String;
ElemTypeId: Integer): Integer;
begin
LastCard := Card;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeOPENARRAY;
Host := true;
Shift := 0;
Level := LevelId;
PatternId := ElemTypeId;
result := Id;
Completed := true;
end;
BindDummyType(result, ElemTypeId);
end;
{$IFNDEF PAXARM}
function TBaseSymbolTable.RegisterShortStringType(LevelId: Integer;
const TypeName: String;
L: Integer): Integer;
begin
LastCard := Card;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeSHORTSTRING;
Host := true;
Shift := 0;
Level := LevelId;
Count := L;
result := Id;
Completed := true;
end;
end;
{$ENDIF}
function TBaseSymbolTable.RegisterSetType(LevelId: Integer;
const TypeName: String;
OriginTypeId: Integer): Integer;
begin
LastCard := Card;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeSET;
Host := true;
Shift := 0;
Level := LevelId;
PatternId := OriginTypeId;
result := Id;
Completed := true;
end;
BindDummyType(result, OriginTypeId);
end;
function TBaseSymbolTable.RegisterProceduralType(LevelId: Integer;
const TypeName: String;
HSub: Integer): Integer;
var
I, SubId: Integer;
begin
LastCard := Card;
if HSub < 0 then
SubId := -HSub
else
begin
SubId := -1;
for I:=Card downto 1 do
if Records[I].Shift = HSub then
begin
SubId := I;
Break;
end;
if SubId = -1 then
begin
result := 0;
RaiseError(errInternalError, []);
Exit;
end;
end;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typePROC;
Host := true;
Shift := 0;
Level := LevelId;
PatternId := SubId;
result := Id;
Completed := true;
end;
end;
function TBaseSymbolTable.RegisterMethodReferenceType(LevelId: Integer;
const TypeName: String;
HSub: Integer): Integer;
var
I, SubId: Integer;
begin
LastCard := Card;
SubId := -1;
for I:=Card downto 1 do
if Records[I].Shift = HSub then
begin
SubId := I;
Break;
end;
if SubId = -1 then
begin
result := 0;
RaiseError(errInternalError, []);
Exit;
end;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
result := RegisterInterfaceType(LevelId, TypeName, IUnknown);
Records[SubId].Level := result;
Records[SubId].Name := ANONYMOUS_METHOD_NAME;
Records[SubId].MethodIndex := 4;
end;
function TBaseSymbolTable.RegisterEventType(LevelId: Integer;
const TypeName: String;
HSub: Integer): Integer;
var
I, SubId: Integer;
begin
LastCard := Card;
SubId := -1;
for I:=Card downto 1 do
if Records[I].Shift = HSub then
begin
SubId := I;
Break;
end;
if SubId = -1 then
begin
result := 0;
RaiseError(errInternalError, []);
Exit;
end;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeEVENT;
Host := true;
Shift := 0;
Level := LevelId;
PatternId := SubId;
result := Id;
Completed := true;
end;
end;
function TBaseSymbolTable.FindInterfaceTypeId(const GUID: TGUID): Integer;
var
I: Integer;
begin
I := GuidList.IndexOf(GUID);
if I = -1 then
result := 0
else
result := GuidList[I].Id;
end;
function TBaseSymbolTable.RegisterInterfaceType(LevelId: Integer;
const TypeName: String;
const GUID: TGUID): Integer;
var
D: packed record
D1, D2: Double;
end;
begin
LastCard := Card;
// result := FindInterfaceTypeId(GUID);
result := LookUpType(TypeName, LevelId, true);
if result > 0 then
Exit;
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeINTERFACE;
Host := true;
Shift := 0;
Level := LevelId;
AncestorId := 0;
result := Id;
GuidList.Add(GUID, result, TypeName);
end;
Move(GUID, D, SizeOf(TGUID));
AddDoubleConst(D.D1);
AddDoubleConst(D.D2);
if not GuidsAreEqual(IUnknown, GUID) then
{$IFDEF VARIANTS}
if not GuidsAreEqual(IInterface, GUID) then
{$ENDIF}
RegisterSupportedInterface(result, 'IUnknown', IUnknown);
end;
function TBaseSymbolTable.RegisterInterfaceType(LevelId: Integer;
pti: PTypeInfo): Integer;
var
TypeData: PTypeData;
L: TPtrList;
p: PTypeInfo;
d: PTypeData;
I: Integer;
begin
LastCard := Card;
result := 0;
TypeData := GetTypeData(pti);
if TypeData <> nil then
if ifHasGuid in TypeData^.IntfFlags then
begin
L := TPtrList.Create;
try
p := nil;
{$IFDEF FPC}
p := TypeData^.IntfParent;
{$ELSE}
if TypeData^.IntfParent <> nil then
p := TypeData^.IntfParent^;
{$ENDIF}
while p <> nil do
begin
L.Insert(0, p);
d := GetTypeData(p);
if d <> nil then
begin
{$IFDEF FPC}
p := d^.IntfParent
{$ELSE}
if d^.IntfParent <> nil then
p := d^.IntfParent^
else
p := nil;
{$ENDIF}
end
else
p := nil;
end;
for I := 0 to L.Count - 1 do
RegisterInterfaceType(LevelId, L[I]);
finally
FreeAndNil(L);
end;
result := RegisterInterfaceType(LevelId, PTIName(pti), TypeData^.Guid);
end;
end;
procedure TBaseSymbolTable.RegisterSupportedInterface(TypeId: Integer;
const SupportedInterfaceName: String;
const i_GUID: TGUID);
var
InterfaceTypeId: Integer;
begin
LastCard := Card;
InterfaceTypeId := LookupType(SupportedInterfaceName, true);
if InterfaceTypeId = 0 then
begin
ExternList.Add(TypeId, SupportedInterfaceName, erGUID);
Exit;
end;
with Records[TypeId] do
begin
if SupportedInterfaces = nil then
SupportedInterfaces := TGuidList.Create;
SupportedInterfaces.Add(i_GUID, InterfaceTypeId, SupportedInterfaceName);
end;
end;
procedure TBaseSymbolTable.RegisterSupportedInterface(TypeId,
InterfaceTypeId: Integer);
var
SupportedInterfaceName: String;
GUID: TGUID;
D: record
D1, D2: Double;
end;
begin
if Records[InterfaceTypeId].FinalTypeId <> typeINTERFACE then
Exit;
LastCard := Card;
SupportedInterfaceName := Records[InterfaceTypeId].Name;
D.D1 := Records[InterfaceTypeId + 1].Value;
D.D2 := Records[InterfaceTypeId + 2].Value;
Move(D, GUID, SizeOf(TGUID));
with Records[TypeId] do
begin
if SupportedInterfaces = nil then
SupportedInterfaces := TGuidList.Create;
SupportedInterfaces.Add(GUID, InterfaceTypeId, SupportedInterfaceName);
end;
end;
procedure TBaseSymbolTable.RegisterClassTypeInfos(ClassId: Integer;
C: TClass);
procedure SetAncestor;
var
I: Integer;
S: String;
ParentClass: TClass;
begin
ParentClass := C.ClassParent;
if DllDefined then
S := ParentClass.ClassName
else
S := '';
for I:=ClassId - 1 downto H_TObject do
with Records[I] do
if PClass <> nil then
begin
if DllDefined then
begin
if Kind = KindTYPE then if Name = S then
begin
Records[ClassId].AncestorId := I;
Exit;
end
end
else
if PClass = ParentClass then
begin
Records[ClassId].AncestorId := I;
Exit;
end;
end;
Records[ClassId].AncestorId := H_TObject;
end;
var
UnresolvedPropIds: TIntegerList;
UnresolvedTypes: TPtrList;
procedure RegisterPublishedProperty(Index: Integer; ppi: PPropInfo);
var
TypeData: PTypeData;
pti: PTypeInfo;
T: Integer;
begin
if ppi = nil then
Exit;
{$ifdef fpc}
pti := ppi^.PropType;
{$else}
pti := ppi.PropType^;
{$endif}
T := 0;
case pti^.Kind of
tkInteger: T := typeINTEGER;
tkFloat:
begin
TypeData := GetTypeData(pti);
case TypeData^.FloatType of
ftSingle: T := typeSINGLE;
ftDouble: T := typeDOUBLE;
ftExtended: T := typeEXTENDED;
end;
end;
{$IFNDEF PAXARM}
tkChar: T := typeANSICHAR;
tkString: T := typeSHORTSTRING;
tkLString: T := typeANSISTRING;
{$ENDIF}
{$IFDEF UNIC}
tkUString: T := typeUNICSTRING;
{$ENDIF}
tkVariant: T := typeVARIANT;
else
T := LookupType(PTIName(pti), 0, true);
end;
with AddRecord do
begin
Name := StringFromPShortString(@ppi^.Name);
Kind := KindPROP;
TypeID := T;
Host := true;
Shift := 0;
Level := ClassId;
IsPublished := true;
PropIndex := Index;
end;
if T = 0 then
begin
{
if pti^.Kind = tkClass then
begin
ExternList.Add(Card, pti^.Name, erTypeId);
end
else }
begin
UnresolvedPropIds.Add(Card);
UnresolvedTypes.Add(pti);
end;
end;
end;
function RegisterPublishedProperties: Integer;
var
pti: PTypeInfo;
ptd: PTypeData;
I, nProps: Integer;
pProps: PPropList;
ppi: PPropInfo;
begin
result := 0;
pti := C.ClassInfo;
if pti = nil then Exit;
ptd := GetTypeData(pti);
nProps := ptd^.PropCount;
if nProps > 0 then begin
GetMem(pProps, SizeOf(PPropInfo) * nProps);
GetPropInfos(pti, pProps);
end
else
pProps := nil;
for I:=0 to nProps - 1 do
begin
{$ifdef fpc}
ppi := pProps^[I];
{$else}
ppi := pProps[I];
{$endif}
RegisterPublishedProperty(I, ppi);
end;
if pProps <> nil then
FreeMem(pProps, SizeOf(PPropInfo) * nProps);
result := nProps;
end;
var
I, K, T, LevelId: Integer;
pti: PTypeInfo;
begin
Records[ClassId].PClass := C;
Records[ClassId + 1].Value := Integer(C); // classref var
if C <> TObject then
SetAncestor;
UnresolvedPropIds := TIntegerList.Create;
UnresolvedTypes := TPtrList.Create;
try
RegisterPublishedProperties;
AddEndOfClassHeader(ClassId);
for I:=0 to UnresolvedTypes.Count - 1 do
begin
pti := UnresolvedTypes[I];
K := UnresolvedPropIds[I];
// Call event to get namespace of type.
if Assigned(GetNamespaceOfType) then
LevelId := GetNamespaceOfType(Self, pti)
else
LevelId := 0;
T := RegisterRTTIType(LevelId, pti);
if T = 0 then
begin
Records[K].Name := '';
Records[K].Kind := KindNONE;
end
else
Records[K].TypeID := T;
end;
finally
FreeAndNil(UnresolvedPropIds);
FreeAndNil(UnresolvedTypes);
end;
end;
function TBaseSymbolTable.RegisterClassTypeForImporter(LevelId: Integer;
C: TClass): Integer;
begin
result := RegisterClassType(LevelId, C.ClassName, H_TObject);
AddVoidVar(0, MaxPublishedProps * SizeOfPointer);
end;
function TBaseSymbolTable.RegisterClassTypeForImporter(LevelId: Integer;
const TypeName: String): Integer;
begin
result := RegisterClassType(LevelId, TypeName, H_TObject);
AddVoidVar(0, MaxPublishedProps * SizeOfPointer);
end;
function TBaseSymbolTable.RegisterClassType(LevelId: Integer;
const TypeName: String;
i_AncestorId: Integer): Integer;
var
ClassRefTypeId: Integer;
begin
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
LastCard := Card;
Inc(LastClassIndex);
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeCLASS;
Host := true;
Shift := 0;
Level := LevelId;
ClassIndex := LastClassIndex;
AncestorId := i_AncestorId;
result := Id;
end;
AddClassRefVar(0);
ClassRefTypeId := RegisterClassReferenceType(0, '', result);
Records[result + 1].TypeId := ClassRefTypeId;
end;
procedure TBaseSymbolTable.SetAncestorEx(ClassId: Integer);
var
I: Integer;
S: String;
ParentClass: TClass;
C: TClass;
begin
C := Records[ClassId].PClass;
if C = nil then
Exit;
{$IFDEF FPC}
// ParentClass := PVMT(C).Parent;
ParentClass := C.ClassParent;
{$ELSE}
ParentClass := C.ClassParent;
{$ENDIF}
S := ParentClass.ClassName;
I := LookupType(S, true);
if I > 0 then
Records[ClassId].AncestorId := I;
end;
function TBaseSymbolTable.RegisterClassType(LevelId: Integer;
C: TClass;
Reserved: Integer = 0): Integer;
var
UnresolvedPropIds: TIntegerList;
UnresolvedTypes: TPtrList;
procedure RegisterPublishedProperty(Index: Integer; ppi: PPropInfo);
var
TypeData: PTypeData;
pti: PTypeInfo;
T: Integer;
begin
if ppi = nil then
Exit;
{$ifdef fpc}
pti := ppi^.PropType;
{$else}
pti := ppi.PropType^;
{$endif}
T := 0;
case pti^.Kind of
tkInteger: T := typeINTEGER;
tkFloat:
begin
TypeData := GetTypeData(pti);
case TypeData^.FloatType of
ftSingle: T := typeSINGLE;
ftDouble: T := typeDOUBLE;
ftExtended: T := typeEXTENDED;
end;
end;
{$IFDEF UNIC}
tkUString: T := typeUNICSTRING;
{$ENDIF}
{$IFNDEF PAXARM}
tkChar: T := typeANSICHAR;
tkString: T := typeSHORTSTRING;
tkLString: T := typeANSISTRING;
{$ENDIF}
tkVariant: T := typeVARIANT;
else
T := LookupType(PTIName(pti), 0, true);
end;
with AddRecord do
begin
Name := StringFromPShortString(@ppi^.Name);
Kind := KindPROP;
TypeID := T;
Host := true;
Shift := 0;
Level := result;
IsPublished := true;
PropIndex := Index;
end;
if T = 0 then
begin
{
if pti^.Kind = tkClass then
begin
ExternList.Add(Card, pti^.Name, erTypeId);
end
else }
begin
UnresolvedPropIds.Add(Card);
UnresolvedTypes.Add(pti);
end;
end;
end;
function RegisterPublishedProperties: Integer;
var
pti: PTypeInfo;
ptd: PTypeData;
I, nProps: Integer;
pProps: PPropList;
ppi: PPropInfo;
begin
result := 0;
pti := C.ClassInfo;
if pti = nil then Exit;
ptd := GetTypeData(pti);
nProps := ptd^.PropCount;
if nProps > 0 then begin
GetMem(pProps, SizeOf(PPropInfo) * nProps);
GetPropInfos(pti, pProps);
end
else
pProps := nil;
for I:=0 to nProps - 1 do
begin
{$ifdef fpc}
ppi := pProps^[I];
{$else}
ppi := pProps[I];
{$endif}
RegisterPublishedProperty(I, ppi);
end;
if pProps <> nil then
FreeMem(pProps, SizeOf(PPropInfo) * nProps);
result := nProps;
end;
procedure SetAncestor;
var
I: Integer;
S: String;
ParentClass: TClass;
begin
ParentClass := C.ClassParent;
if DllDefined then
S := ParentClass.ClassName
else
S := '';
for I:=result - 1 downto H_TObject do
with Records[I] do
if PClass <> nil then
begin
if DllDefined then
begin
if Kind = KindTYPE then if Name = S then
begin
Records[result].AncestorId := I;
Exit;
end
end
else if PClass = ParentClass then
begin
Records[result].AncestorId := I;
Exit;
end;
end;
{
if AncestorRequired then
ExternList.Add(result, ParentClass.ClassName, erAncestorId)
else
}
Records[result].AncestorId := H_TObject;
end;
procedure RegisterAncestors(Cls: TClass);
var
ParentClass: TClass;
Id: Integer;
begin
ParentClass := Cls.ClassParent;
if ParentClass = nil then
Exit;
Id := FindClassTypeId(ParentClass);
if Id > 0 then
Exit;
{
if (LevelId > 0) and (ParentClass.ClassInfo <> nil) then
begin
ptd := GetTypeData(ParentClass.ClassInfo);
if ptd = nil then
RegisterClassType(LevelId, ParentClass)
else if StrEql(ptd^.UnitName, Records[LevelId].Name) then
RegisterClassType(LevelId, ParentClass)
else
begin
Exit;
end;
end
else }
RegisterClassType(LevelId, ParentClass);
RegisterAncestors(ParentClass);
end;
var
I, K, T: Integer;
pti: PTypeInfo;
S: String;
R: TSymbolRec;
AlreadyExists: Boolean;
K1, K2, KK: Integer;
begin
HeaderParser.AbstractMethodCount := 0;
LastCard := Card;
AlreadyExists := false;
result := FindClassTypeId(C);
T := result;
if result > 0 then
begin
if result < FirstLocalId then
if Card >= FirstLocalId then
begin
Records[result].Level := LevelId;
Exit;
end;
AlreadyExists := true;
end;
if not AlreadyExists then
begin
if not C.InheritsFrom(TGC_Object) then
RegisterAncestors(C);
end;
S := C.ClassName;
result := RegisterClassType(LevelId, S, 0);
if AlreadyExists then
begin
Records[T].Name := '@@';
Records[T].PClass := nil;
Records[T].ClassIndex := -1;
Records[T + 1].Value := 0;
for KK := 1 to 2 do
begin
if KK = 1 then
begin
K1 := 1;
if Self.st_tag = 0 then
K2 := Card
else
K2 := TLocalSymbolTable(Self).GlobalST.Card;
end
else
begin
K1 := FirstLocalId + 1;
K2 := Card;
end;
for I := K1 to K2 do
begin
R := Records[I];
if R.TypeID = T then
R.TypeID := result;
if R.PatternID = T then
R.PatternID := result;
if R.AncestorID = T then
R.AncestorID := result;
end;
end;
end;
Records[result].PClass := C;
if S <> TObject.ClassName then
SetAncestor;
Records[Result + 1].Value := Integer(C); // classref var
UnresolvedPropIds := TIntegerList.Create;
UnresolvedTypes := TPtrList.Create;
try
K := RegisterPublishedProperties;
for I:=1 to Reserved do // reserve extra space
AddRecord;
for I:=1 to K do // reserve place for ppi
AddPointerVar(0);
for I:=1 to Reserved do // reserve extra space
AddPointerVar(0);
if Assigned(RegisterDRTTIProperties) then
RegisterDRTTIProperties(result, C, Self);
AddEndOfClassHeader(result);
for I:=0 to UnresolvedTypes.Count - 1 do
begin
pti := UnresolvedTypes[I];
K := UnresolvedPropIds[I];
// Call event to get namespace of type.
if Assigned(GetNamespaceOfType) then
LevelId := GetNamespaceOfType(Self, pti)
else
LevelId := 0;
if pti^.Kind = tkClass then
begin
ExternList.Add(K, PTIName(pti), erTypeId);
continue;
end;
T := RegisterRTTIType(LevelId, pti);
if T = 0 then
begin
Records[K].Name := '';
Records[K].Kind := KindNONE;
end
else
Records[K].TypeID := T;
end;
finally
FreeAndNil(UnresolvedPropIds);
FreeAndNil(UnresolvedTypes);
end;
end;
function TBaseSymbolTable.RegisterClassReferenceType(LevelId: Integer;
const TypeName: String;
OriginClassId: Integer): Integer;
begin
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
LastCard := Card;
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeCLASSREF;
Host := true;
Shift := 0;
Level := LevelId;
PatternId := OriginClassId;
result := Id;
Completed := true;
end;
BindDummyType(result, OriginClassId);
end;
function TBaseSymbolTable.RegisterHelperType(LevelId: Integer;
const TypeName: String;
OriginTypeId: Integer): Integer;
begin
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
LastCard := Card;
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeHELPER;
Host := true;
Shift := 0;
Level := LevelId;
PatternId := OriginTypeId;
result := Id;
Completed := true;
end;
BindDummyType(result, OriginTypeId);
TypeHelpers.Add(result, OriginTypeId);
end;
procedure TBaseSymbolTable.BindDummyType(TypeId, OriginTypeId: Integer);
begin
if Records[OriginTypeId].IsDummyType then
begin
ExternList.Add(TypeId,
Records[OriginTypeId].FullName,
erPatternId);
Records[OriginTypeId].Name := '';
Records[OriginTypeId].Kind := KindNONE;
end;
end;
function TBaseSymbolTable.RegisterRecordType(LevelId: Integer;
const TypeName: String;
Align: Integer): Integer;
begin
if SomeTypeList.Count > 0 then
UpdateSomeTypeList(TypeName, Card + 1);
LastCard := Card;
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeRECORD;
Host := true;
Shift := 0;
Level := LevelId;
DefaultAlignment := Align;
result := Id;
end;
end;
function TBaseSymbolTable.RegisterRTTIType(LevelId: Integer;
pti: PTypeInfo): Integer;
var
TypeData, td, ptd: PTypeData;
S, SParamType: String;
I, T, K1, K2: Integer;
pParam: PParamData;
pNameString, pTypeString: ^ShortString;
ParamIds: array[0..20] of Integer;
ParamRef: array[0..20] of Boolean;
ParamNames: array[0..20] of string;
H_Sub: Integer;
begin
LastCard := Card;
S := PTIName(pti);
result := LookupType(S, LevelId, true);
if result > 0 then
Exit;
case pti^.Kind of
{$IFDEF VARIANTS}
tkDynArray:
begin
ptd := GetTypeData(pti);
I := LookupType(StringFromPShortString(@ptd.elType2^.Name), true);
if I > 0 then
result := RegisterDynamicArrayType(LevelId, S, I);
end;
{$ENDIF}
tkInteger:
begin
ptd := GetTypeData(pti);
T := typeINTEGER;
case ptd^.OrdType of
otSByte: T := typeSMALLINT;
otUByte: T := typeBYTE;
otSWord: T := typeSHORTINT;
otUWord: T := typeWORD;
otSLong: T := typeINTEGER;
otULong: T := typeCARDINAL;
end;
result := RegisterSubrangeType(LevelId, S, T, ptd^.MinValue, ptd^.MaxValue);
end;
tkInt64:
begin
result := RegisterTypeAlias(LevelId, PTIName(pti), typeINT64);
end;
tkFloat:
begin
TypeData := GetTypeData(pti);
with TypeData^ do
case FloatType of
ftSingle: result := RegisterTypeAlias(LevelId, PTIName(pti), typeSINGLE);
ftDouble: result := RegisterTypeAlias(LevelId, PTIName(pti), typeDOUBLE);
ftExtended: result := RegisterTypeAlias(LevelId, PTIName(pti), typeEXTENDED);
end
end;
tkEnumeration:
begin
S := PTIName(pti);
K1 := Card;
T := RegisterEnumType(LevelId, S, typeINTEGER);
K2 := Card;
if K1 <> K2 then
begin
TypeData := GetTypeData(pti);
with TypeData^ do
begin
// if (MinValue < 256) and (MaxValue < 256) then
for I:= MinValue to MaxValue do
begin
S := GetEnumName(pti, I);
RegisterEnumValue(T, S, I);
end;
end;
end;
result := T;
end;
tkSet:
begin
TypeData := GetTypeData(pti);
if TypeData = nil then
Exit;
if TypeData^.CompType = nil then
Exit;
S := StringFromPShortString(@TypeData^.CompType^.Name);
case TypeData^.CompType^.Kind of
tkInteger:
begin
result := RegisterSetType(LevelId, PTIName(pti), typeINTEGER);
end;
{$IFNDEF PAXARM}
tkChar:
begin
result := RegisterSetType(LevelId, PTIName(pti), typeANSICHAR);
end;
{$ENDIF}
tkWChar:
begin
result := RegisterSetType(LevelId, PTIName(pti), typeWIDECHAR);
end;
tkEnumeration:
begin
K1 := Card;
if IsValidName(S) then
T := RegisterEnumType(LevelId, S, typeINTEGER)
else
T := RegisterEnumType(LevelId, PTIName(pti) + '_Comp', typeINTEGER);
K2 := Card;
if K1 <> K2 then
begin
{$ifdef fpc}
td := GetTypeData(TypeData^.CompType);
{$else}
td := GetTypeData(TypeData^.CompType^);
{$endif}
with td^ do
if (MinValue < 256) and (MaxValue < 256) then
for I:= MinValue to MaxValue do
begin
{$ifdef fpc}
S := GetEnumName(TypeData^.CompType, I);
{$else}
S := GetEnumName(TypeData^.CompType^, I);
{$endif}
RegisterEnumValue(T, S, I);
end;
end;
result := RegisterSetType(LevelId, PTIName(pti), T);
end;
end;
end;
tkClass:
begin
TypeData := GetTypeData(pti);
if LevelId > 0 then
begin
if StrEql(StringFromPShortString(@TypeData^.UnitName), Records[LevelId].Name) then
result := RegisterClassType(LevelId, TypeData^.ClassType)
else
result := FindClassTypeIdByPti(pti);
end
else
begin
result := FindClassTypeIdByPti(pti);
if result = 0 then
result := RegisterClassType(LevelId, TypeData^.ClassType);
end;
end;
tkInterface:
begin
TypeData := GetTypeData(pti);
if TypeData <> nil then
if ifHasGuid in TypeData^.IntfFlags then
result := RegisterInterfaceType(LevelId, pti);
end;
{$IFNDEF PAXARM}
tkChar:
begin
ptd := GetTypeData(pti);
T := typeANSICHAR;
result := RegisterSubrangeType(LevelId, S, T, ptd^.MinValue, ptd^.MaxValue);
end;
tkString:
begin
result := RegisterTypeAlias(LevelId, PTIName(pti), typeSHORTSTRING);
end;
tkLString:
begin
result := RegisterTypeAlias(LevelId, PTIName(pti), typeANSISTRING);
end;
tkWString:
begin
result := RegisterTypeAlias(LevelId, PTIName(pti), typeWIDESTRING);
end;
{$ENDIF}
tkWChar:
begin
ptd := GetTypeData(pti);
T := typeWIDECHAR;
result := RegisterSubrangeType(LevelId, S, T, ptd^.MinValue, ptd^.MaxValue);
end;
{$IFDEF UNIC}
tkUString:
begin
result := RegisterTypeAlias(LevelId, PTIName(pti), typeUNICSTRING);
end;
{$ENDIF}
tkVariant:
begin
result := RegisterTypeAlias(LevelId, PTIName(pti), typeVARIANT);
end;
tkMethod:
begin
S := PTIName(pti);
result := LookUpType(S, 0, true);
if result > 0 then
Exit;
ptd := GetTypeData(pti);
pParam := PParamData(@(ptd^.ParamList));
I := 0;
while I <= ptd^.ParamCount - 1 do
begin
ParamRef[I] := false;
if pfVar in pParam^.Flags then
begin
ParamRef[I] := true;
end
else if pfConst in pParam^.Flags then
begin
end
else if pfOut in pParam^.Flags then
begin
ParamRef[I] := true;
end;
if pfArray in pParam^.Flags then
begin
result := H_TMethod;
Exit;
end;
pNameString := ShiftPointer(pParam, SizeOf(TParamFlags));
ParamNames[I] := StringFromPShortString(PShortString(pNameString));
pTypeString := ShiftPointer(pParam, SizeOf(TParamFlags) +
Length(pParam^.ParamName) + 1);
SParamType := StringFromPShortString(PShortString(pTypeString));
T := LookUpType(SParamType, 0, true);
if T = 0 then
begin
result := H_TMethod;
Exit;
end;
ParamIds[I] := T;
if Records[T].FinalTypeId in [typeRECORD, typeARRAY] then
ParamRef[I] := true;
pParam := ShiftPointer(pTypeString, Length(pTypeString^) + 1);
Inc(I);
end;
T := typeVOID;
if ptd^.MethodKind = mkFunction then
begin
pTypeString := Pointer(pParam);
T := LookUpType(StringFromPShortString(PShortString(pTypeString)), 0, true);
if T = 0 then
begin
result := H_TMethod;
Exit;
end;
end;
H_Sub := RegisterRoutine(LevelId, '', T, ccREGISTER, nil);
K1 := I;
for I:=0 to K1 - 1 do
RegisterParameter(H_Sub, ParamIds[I], Unassigned, ParamRef[I], ParamNames[I]);
result := RegisterEventType(LevelId, S, H_Sub);
end;
else
begin
Exit;
end;
end;
end;
function TBaseSymbolTable.RegisterProperty(LevelId: Integer; const PropName: String;
PropTypeID, i_ReadId, i_WriteId: Integer;
i_IsDefault: Boolean): Integer;
var
I: Integer;
begin
with AddRecord do
begin
Name := PropName;
Count := 0;
Kind := KindPROP;
TypeID := PropTypeID;
Host := true;
Shift := 0;
Level := LevelId;
if i_ReadId <= 0 then
ReadId := - i_ReadId
else
begin
ReadId := -1;
for I:=Card downto 1 do
if Records[I].Shift = i_ReadId then
begin
ReadId := I;
Break;
end;
if ReadId = -1 then
begin
result := 0;
RaiseError(errInternalError, []);
Exit;
end;
end;
if i_WriteId <= 0 then
WriteId := - i_WriteId
else
begin
WriteId := -1;
for I:=Card downto 1 do
if Records[I].Shift = i_WriteId then
begin
WriteId := I;
Break;
end;
if WriteId = -1 then
begin
result := 0;
RaiseError(errInternalError, []);
Exit;
end;
end;
IsDefault := i_IsDefault;
result := Id;
end;
with AddRecord do
begin
Kind := KindVAR;
TypeID := PropTypeID;
Host := true;
Shift := 0;
Level := result;
end;
end;
function TBaseSymbolTable.RegisterInterfaceProperty(LevelId: Integer;
const PropName: String;
PropTypeID,
ReadIndex,
WriteIndex: Integer): Integer;
var
I: Integer;
R: TSymbolRec;
exists: Boolean;
begin
with AddRecord do
begin
Name := PropName;
Count := 0;
Kind := KindPROP;
TypeID := PropTypeID;
Host := true;
Shift := 0;
Level := LevelId;
result := Id;
if ReadIndex <= 0 then
ReadId := 0
else
begin
exists := false;
for I:=Card downto 1 do
begin
R := Records[I];
if R.Level = LevelId then
if R.MethodIndex = ReadIndex then
begin
ReadId := I;
exists := true;
Break;
end;
end;
if not exists then
begin
result := 0;
RaiseError(errInternalError, []);
Exit;
end;
end;
if WriteIndex <= 0 then
WriteId := 0
else
begin
exists := false;
for I:=Card downto 1 do
begin
R := Records[I];
if R.Level = LevelId then
if R.MethodIndex = WriteIndex then
begin
WriteId := I;
exists := true;
Break;
end;
end;
if not exists then
begin
result := 0;
RaiseError(errInternalError, []);
Exit;
end;
end;
end;
with AddRecord do
begin
Kind := KindVAR;
TypeID := PropTypeID;
Host := true;
Shift := 0;
Level := result;
end;
end;
function TBaseSymbolTable.RegisterTypeFieldEx(LevelId: Integer;
const Declaration: String;
FieldOffset: Integer = -1): Integer;
var
FieldName, FieldTypeName: String;
FieldTypeId: Integer;
begin
HeaderParser.Init(Declaration, Self, LevelId);
HeaderParser.Call_SCANNER;
FieldName := HeaderParser.Parse_Ident;
HeaderParser.Match(':');
FieldTypeName := HeaderParser.CurrToken;
FieldTypeId := HeaderParser.LookupId(FieldTypeName);
result := RegisterTypeField(LevelId, FieldName, FieldTypeId, FieldOffset);
end;
function TBaseSymbolTable.RegisterTypeField(LevelId: Integer;
const FieldName: String;
FieldTypeID: Integer;
FieldOffset: Integer = -1;
ACompIndex: Integer = -1): Integer;
var
J, S: Integer;
DefAlign, CurrAlign, J1, FT, FT1: Integer;
R: TSymbolRec;
begin
with AddRecord do
begin
Name := FieldName;
Kind := KindTYPE_FIELD;
TypeID := FieldTypeId;
Host := true;
Shift := FieldOffset;
Level := LevelId;
result := - Id;
CompIndex := ACompIndex;
end;
Records[FieldTypeId].Completed := true;
if (FieldOffset = -1) and (ACompIndex = -1) then
begin
S := 0;
if Records[LevelId].IsPacked then
begin
for J:=LevelId + 1 to Card do
begin
R := Records[J];
if R = SR0 then
break;
if (R.Kind = KindTYPE_FIELD) and (R.Level = LevelId) then
begin
R.Shift := S;
Inc(S, R.Size);
end;
end;
end
else
begin
DefAlign := Records[LevelId].DefaultAlignment;
J1 := -1;
for J:=LevelId + 1 to Card do
begin
R := Records[J];
if R = SR0 then
break;
if (R.Kind = KindTYPE_FIELD) and (R.Level = LevelId) then
begin
CurrAlign := GetAlignmentSize(R.TypeId, DefAlign);
if J1 > 0 then
begin
FT1 := Records[J-1].FinalTypeId;
FT := R.FinalTypeId;
if FT = FT1 then
begin
CurrAlign := 1;
J1 := -1;
end
else
J1 := J;
end
else
J1 := J;
if CurrAlign > 1 then
while S mod CurrAlign <> 0 do
Inc(S);
R.Shift := S;
Inc(S, R.Size);
end;
end; // for-loop
end;
end;
end;
function TBaseSymbolTable.RegisterVariantRecordTypeField(LevelId: Integer;
const Declaration: String;
VarCnt: Int64): Integer;
var
FieldName: String;
begin
HeaderParser.Init(Declaration, Self, LevelId);
HeaderParser.Call_SCANNER;
FieldName := HeaderParser.Parse_Ident;
result := HeaderParser.Register_VariantRecordTypeField(FieldName, VarCnt);
end;
function TBaseSymbolTable.RegisterVariantRecordTypeField(LevelId: Integer;
const FieldName: String;
FieldTypeID: Integer;
VarCnt: Int64): Integer;
var
J, S: Integer;
DefAlign, CurrAlign, J1, FT, FT1, VJ, VK, VS: Integer;
VarPathList: TVarPathList;
Path: TVarPath;
R: TSymbolRec;
begin
with AddRecord do
begin
Name := FieldName;
Kind := KindTYPE_FIELD;
TypeID := FieldTypeId;
Host := true;
Level := LevelId;
VarCount := VarCnt;
result := - Id;
end;
VarPathList := TVarPathList.Create;
try
for J:=LevelId + 1 to Card do
begin
R := Records[J];
if R = SR0 then
break;
if (R.Kind = KindTYPE_FIELD) and (R.Level = LevelId) then
if R.VarCount > 0 then
VarPathList.Add(J, R.VarCount);
end;
S := 0;
if Records[LevelId].IsPacked then
begin
for J:=LevelId + 1 to Card do
begin
R := Records[J];
if R = SR0 then
break;
if (R.Kind = KindTYPE_FIELD) and (R.Level = LevelId) then
begin
if R.VarCount > 0 then
break;
R.Shift := S;
Inc(S, R.Size);
end;
end;
// process variant part
VS := S;
for VK :=0 to VarPathList.Count - 1 do
begin
Path := VarPathList[VK];
S := VS;
for VJ := 0 to Path.Count - 1 do
begin
J := Path[VJ].Id;
Records[J].Shift := S;
Inc(S, Records[J].Size);
end;
end;
end
else
begin
DefAlign := Records[LevelId].DefaultAlignment;
J1 := -1;
for J:=LevelId + 1 to Card do
begin
R := Records[J];
if R = SR0 then
break;
if (R.Kind = KindTYPE_FIELD) and (R.Level = LevelId) then
begin
if R.VarCount > 0 then
break;
CurrAlign := GetAlignmentSize(R.TypeId, DefAlign);
if J1 > 0 then
begin
FT1 := Records[J-1].FinalTypeId;
FT := R.FinalTypeId;
if FT = FT1 then
begin
CurrAlign := 1;
J1 := -1;
end
else
J1 := J;
end
else
J1 := J;
if CurrAlign > 1 then
while S mod CurrAlign <> 0 do
Inc(S);
R.Shift := S;
Inc(S, R.Size);
end;
end; // for-loop
// process variant part
VS := S;
for VK :=0 to VarPathList.Count - 1 do
begin
S := VS;
Path := VarPathList[VK];
for VJ := 0 to Path.Count - 1 do
begin
J := Path[VJ].Id;
CurrAlign := GetAlignmentSize(Records[J].TypeId, DefAlign);
if J1 > 0 then
begin
FT1 := Records[J-1].FinalTypeId;
FT := Records[J].FinalTypeId;
if FT = FT1 then
begin
CurrAlign := 1;
J1 := -1;
end
else
J1 := J;
end
else
J1 := J;
if CurrAlign > 1 then
while S mod CurrAlign <> 0 do
Inc(S);
Records[J].Shift := S;
Inc(S, Records[J].Size);
end;
end;
end;
finally
FreeAndNil(VarPathList);
end;
end;
function TBaseSymbolTable.RegisterVariable(LevelId: Integer;
const Declaration: String; Address: Pointer): Integer;
var
VarName: String;
begin
HeaderParser.Init(Declaration, Self, LevelId);
HeaderParser.Call_SCANNER;
VarName := HeaderParser.Parse_Ident;
result := HeaderParser.Register_Variable(VarName, Address);
end;
function TBaseSymbolTable.RegisterVariable(LevelId: Integer; const VarName: String;
VarTypeID: Integer; i_Address: Pointer): Integer;
begin
LastCard := Card;
result := LastShiftValue;
with AddRecord do
begin
Name := VarName;
Kind := KindVAR;
TypeID := VarTypeID;
Host := true;
Shift := LastShiftValue;
Level := LevelId;
Address := i_Address;
end;
Inc(LastShiftValue, SizeOfPointer);
LastVarId := Card;
end;
function TBaseSymbolTable.RegisterObject(LevelId: Integer;
const ObjectName: String;
TypeId: Integer;
i_Address: Pointer): Integer;
var
X: TObject;
C: TComponent;
I, Offset: Integer;
S, FieldTypeName: String;
FAddress: Pointer;
FieldTypeId: Integer;
begin
if ObjectName = '' then
begin
result := 0;
if i_Address <> nil then
begin
X := TObject(i_Address^);
if X is TComponent then
begin
C := X as TComponent;
for I := 0 to C.ComponentCount - 1 do
begin
S := C.Components[I].Name;
FieldTypeName := C.Components[I].ClassName;
FieldTypeId := LookupType(FieldTypeName, true);
FAddress := C.FieldAddress(S);
if FieldTypeId > 0 then
RegisterObject(LevelId, S, FieldTypeId, FAddress);
end;
end;
end;
Exit;
end;
result := RegisterVariable(LevelId, ObjectName, TypeId, i_Address);
if i_Address <> nil then
begin
X := TObject(i_Address^);
if X is TComponent then
begin
C := X as TComponent;
for I := 0 to C.ComponentCount - 1 do
begin
S := C.Components[I].Name;
FieldTypeName := C.Components[I].ClassName;
FieldTypeId := LookupType(FieldTypeName, true);
if FieldTypeId > 0 then
begin
FAddress := C.FieldAddress(S);
if FAddress <> nil then
begin
Offset := Integer(FAddress) - Integer(C);
RegisterTypeField(TypeId, S, FieldTypeId, Offset);
end
else
begin
RegisterTypeField(TypeId, S, FieldTypeId, -1, I);
end;
end;
end;
end;
end;
end;
function TBaseSymbolTable.RegisterVirtualObject(LevelId: Integer;
const ObjectName: String): Integer;
begin
result := RegisterVariable(LevelId, ObjectName, typeVOBJECT, nil);
end;
procedure TBaseSymbolTable.RegisterMember(LevelId: Integer; const MemberName: String;
i_Address: Pointer);
begin
RegisterVariable(LevelId, MemberName, typeINTEGER, i_Address);
end;
function TBaseSymbolTable.RegisterConstant(LevelId: Integer;
const Declaration: String): Integer;
var
ConstName: String;
begin
HeaderParser.Init(Declaration, Self, LevelId);
HeaderParser.Call_SCANNER;
ConstName := HeaderParser.Parse_Ident;
result := HeaderParser.Register_Constant(ConstName);
end;
function TBaseSymbolTable.RegisterConstant(LevelId: Integer;
const i_Name: String; i_TypeID: Integer; const i_Value: Variant): Integer;
var
R: TSymbolRec;
FT: Integer;
{$IFDEF PAX64}
VCardinal: UInt64;
{$ELSE}
VCardinal: Cardinal;
{$ENDIF}
VWideChar: WideChar;
{$IFDEF PAXARM}
VWideString: String;
{$ELSE}
VWideString: WideString;
{$ENDIF}
begin
LastCard := Card;
R := nil;
{$IFNDEF PAXARM}
if Records[i_TypeID].HasPAnsiCharType then
FT := typePANSICHAR
else
{$ENDIF}
if Records[i_TypeID].HasPWideCharType then
FT := typePWIDECHAR
else
FT := Records[i_TypeID].FinalTypeId;
{$IFNDEF PAXARM}
if FT = typeANSICHAR then
if Integer(i_Value) > 255 then
begin
FT := -1;
R := AddWideCharConst(Integer(i_Value));
end;
{$ENDIF}
if FT <> - 1 then
case FT of
typeENUM: R := AddEnumConst(i_TypeId, Integer(i_Value));
{$IFNDEF PAXARM}
typeANSICHAR: R := AddAnsiCharConst(AnsiChar(Integer(i_Value)));
typePANSICHAR: R := AddPAnsiCharConst(AnsiString(i_Value));
typeANSISTRING: R := AddPAnsiCharConst(AnsiString(i_Value));
typeSHORTSTRING: R := AddShortStringConst(i_Value);
{$ENDIF}
typeWIDECHAR:
begin
VWideString := i_Value;
VWideChar := VWideString[1];
R := AddWideCharConst(Integer(VWideChar));
end;
typePWIDECHAR: R := AddPWideCharConst(i_Value);
typeUNICSTRING: R := AddPWideCharConst(i_Value);
typeBYTE: R := AddByteConst(i_Value);
typeWORD: R := AddWordConst(i_Value);
typeINTEGER:
begin
if Abs(i_Value) > MaxInt then
begin
R := AddInt64Const({$IfNDef VARIANTS} integer (i_Value) {$Else} i_Value {$EndIf});
R.TypeID := typeINTEGER;
end
else
R := AddIntegerConst(i_Value);
end;
{$IFDEF VARIANTS}
typeINT64: R := AddInt64Const(i_Value);
{$ELSE}
typeINT64: R := AddInt64Const(Integer(i_Value));
{$ENDIF}
typeCARDINAL: R := AddCardinalConst(i_Value);
typeSMALLINT: R := AddSmallIntConst(i_Value);
typeSHORTINT: R := AddShortIntConst(i_Value);
typeDOUBLE: R := AddDoubleConst(i_Value);
typeSINGLE: R := AddSingleConst(i_Value);
typeEXTENDED: R := AddExtendedConst(i_Value);
typeCURRENCY: R := AddCurrencyConst(i_Value);
typeBOOLEAN: R := AddBooleanConst(i_Value);
{$IFDEF UNIX}
typeBYTEBOOL: R := AddBooleanConst(i_Value);
{$ELSE}
typeBYTEBOOL: R := AddByteBoolConst(ByteBool(Byte(i_Value)));
{$ENDIF}
typeWORDBOOL: R := AddWordBoolConst(i_Value);
typeLONGBOOL: R := AddLongBoolConst(i_Value);
typeVARIANT: R := AddVariantConst(i_Value);
typeOLEVARIANT: R := AddOleVariantConst(i_Value);
typeRECORD: R := AddRecordConst(i_TypeId, i_Value);
typeARRAY: R := AddArrayConst(i_TypeId, i_Value);
typeSET: R := AddSetConst(I_TypeId, i_Value);
typeCLASS:
begin
VCardinal := i_Value;
R := AddClassConst(I_TypeId, TObject(VCardinal));
end;
typeCLASSREF:
begin
VCardinal := i_Value;
R := AddClassRefConst(I_TypeId, TClass(VCardinal));
end;
typePOINTER, typeVOID:
begin
VCardinal := i_Value;
R := AddPointerConst(i_TypeId, Pointer(VCardinal));
end;
else
begin
result := 0;
RaiseError(errIncompatibleTypesNoArgs, []);
Exit;
end;
end;
R.Level := LevelId;
R.Name := i_Name;
// R.Host := true;
result := R.Id;
end;
function TBaseSymbolTable.RegisterConstant(LevelId: Integer;
const i_Name: String; const i_Value: Variant): Integer;
var
TypeID: Integer;
VT: Integer;
begin
LastCard := Card;
VT := VarType(i_Value);
case VT of
varEmpty: typeId := typeVARIANT;
varBoolean: TypeId := typeBOOLEAN;
varInteger, varByte, varSmallInt: TypeId := typeINTEGER;
{$IFDEF VARIANTS}
varShortInt, varWord, varLongWord: TypeId := typeINTEGER;
{$ENDIF}
{$IFDEF UNIC}
varUString: typeId := typeUNICSTRING;
{$ENDIF}
{$IFNDEF PAXARM}
varString: TypeId := typeANSISTRING;
{$ENDIF}
varDouble: TypeId := typeDOUBLE;
varCurrency: TypeId := typeCURRENCY;
else
begin
result := 0;
RaiseError(errIncompatibleTypesNoArgs, []);
Exit;
end;
end;
result := RegisterConstant(LevelId, i_Name, TypeId, i_Value);
end;
function TBaseSymbolTable.RegisterPointerConstant(LevelId: Integer;
const i_Name: String; const i_Value: Pointer): Integer;
var
I: IntPax;
begin
I := IntPax(i_Value);
result := RegisterConstant(LevelId, i_Name, typePOINTER, I);
end;
function TBaseSymbolTable.RegisterExtendedConstant(LevelId: Integer;
const i_Name: String; const i_Value: Extended): Integer;
var
D: Double;
begin
if i_Value > MaxDouble then
D := MaxDouble
else if (i_Value > 0) and (i_Value < MinDouble) then
D := MinDouble
else
D := i_Value;
result := RegisterConstant(LevelId, i_Name, typeEXTENDED, D);
end;
function TBaseSymbolTable.RegisterInt64Constant(LevelId: Integer;
const i_Name: String; const i_Value: Int64): Integer;
begin
{$IFDEF VARIANTS}
if Abs(i_Value) >= Abs(MaxInt) then
result := RegisterConstant(LevelId, i_Name, typeINT64, i_Value)
else
result := RegisterConstant(LevelId, i_Name, typeINTEGER, i_Value);
{$ELSE}
result := RegisterConstant(LevelId, i_Name, typeINTEGER, Integer(i_Value));
{$ENDIF}
end;
function TBaseSymbolTable.RegisterRoutine(LevelId: Integer;
const SubName: String; ResultTypeID: Integer;
CallConvention: Integer;
i_Address: Pointer;
i_OverCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
var
SubID: Integer;
begin
{$IFDEF PAX64}
CallConvention := cc64;
{$ENDIF}
result := LastShiftValue;
with AddRecord do
begin
Name := SubName;
Count := 0;
Kind := KindSUB;
TypeID := ResultTypeID;
Host := true;
Shift := LastShiftValue;
Level := LevelId;
CallConv := CallConvention;
IsDeprecated := i_IsDeprecated;
if not (CallConvention in [ccSTDCALL, ccREGISTER, cc64,
ccCDECL, ccPASCAL,
ccSAFECALL, ccMSFASTCALL]) then
begin
RaiseError(errInternalError, []);
Exit;
end;
SubId := Id;
Address := i_Address;
OverCount := i_OverCount;
end;
Inc(LastShiftValue, SizeOfPointer);
with AddRecord do
begin
Kind := KindVAR;
TypeID := ResultTypeID;
Host := true;
Shift := 0;
Level := SubId;
end;
with AddRecord do
begin
Kind := KindNONE;
Host := true;
Shift := 0;
Level := SubId;
end;
LastSubId := SubId;
end;
function TBaseSymbolTable.RegisterRoutine(LevelId: Integer;
const SubName, ResultType: String;
CallConvention: Integer;
i_Address: Pointer;
i_OverCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
var
TypeId: Integer;
begin
TypeId := LookupType(ResultType, true);
if TypeId = 0 then
begin
ExternList.Add(Card + 1,
ResultType,
erTypeId);
end;
result := RegisterRoutine(LevelId, SubName, TypeId,
CallConvention, i_Address, i_OverCount, i_IsDeprecated);
end;
function TBaseSymbolTable.RestorePositiveIndex(L: Integer): Integer;
var
R: TSymbolRec;
SupportedInterfaces: TGuidList;
I, IntfId, temp: Integer;
begin
R := Records[L];
SupportedInterfaces := R.SupportedInterfaces;
result := -1;
if SupportedInterfaces <> nil then
begin
for I:=0 to SupportedInterfaces.Count - 1 do
begin
// Idx := GuidList.IndexOf(SupportedInterfaces[I].GUID);
// if Idx >= 0 then
begin
IntfId := SupportedInterfaces[I].Id;
temp := FindMaxMethodIndex(IntfId);
if temp > result then
result := temp;
end;
end
end
else
result := 3;
end;
function TBaseSymbolTable.FindMaxMethodIndex(IntfId: Integer): Integer;
var
I, temp: Integer;
R: TSymbolRec;
begin
result := -1;
for I:= IntfId + 1 to Card do
begin
R := Records[I];
if R = SR0 then
break;
if R.Kind = KindNAMESPACE then
break;
if R.Level = IntfId then
if R.MethodIndex > 0 then
begin
temp := R.MethodIndex;
if temp > result then
result := temp
end;
end;
if result = -1 then
result := RestorePositiveIndex(IntfId);
end;
function TBaseSymbolTable.RegisterMethod(LevelId: Integer;
const SubName: String; ResultTypeID: Integer;
CallConvention: Integer;
i_Address: Pointer;
IsShared: Boolean = false;
i_CallMode: Integer = cmNONE;
i_MethodIndex: Integer = 0;
i_OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
var
SubID: Integer;
PositiveIndex: Integer;
NegativeIndex: Integer;
MethodIndex: Integer;
C: TClass;
begin
NegativeIndex := 0;
if i_MethodIndex < 0 then
begin
NegativeIndex := i_MethodIndex;
PositiveIndex := RestorePositiveIndex(LevelId);
if PositiveIndex = -1 then
RaiseError(errInternalError, []);
i_MethodIndex := Abs(i_MethodIndex) + PositiveIndex;
end;
result := LastShiftValue;
with AddRecord do
begin
Name := SubName;
Count := 0;
Kind := KindSUB;
TypeID := ResultTypeID;
Host := true;
Shift := LastShiftValue;
Level := LevelId;
CallConv := CallConvention;
{$IFDEF PAX64}
CallConv := cc64;
{$ENDIF}
IsSharedMethod := IsShared;
if not (CallConvention in [ccSTDCALL, ccREGISTER, ccCDECL, cc64,
ccPASCAL, ccSAFECALL, ccMSFASTCALL]) then
begin
RaiseError(errInternalError, []);
Exit;
end;
SubId := Id;
Address := i_Address;
CallMode := i_CallMode;
MethodIndex := i_MethodIndex;
NegativeMethodIndex := NegativeIndex;
OverCount := i_OverCount;
IsDeprecated := i_IsDeprecated;
end;
Inc(LastShiftValue, SizeOfPointer);
with AddRecord do
begin
Kind := KindVAR;
TypeID := ResultTypeID;
Host := true;
Shift := 0;
Level := SubId;
end;
with AddRecord do
begin
Kind := KindNONE;
Host := true;
Shift := 0;
Level := SubId;
end;
LastSubId := SubId;
if i_CallMode = cmNONE then
Exit;
C := Records[LevelId].PClass;
if C <> nil then
begin
MethodIndex := VirtualMethodIndex(C, i_Address) + 1;
if MethodIndex > 0 then
begin
Records[LastSubId].MethodIndex := MethodIndex;
end;
if i_IsAbstract then
begin
Records[LastSubId].CallMode := cmVIRTUAL;
if i_MethodIndex > 0 then
HeaderParser.AbstractMethodCount := i_MethodIndex;
Records[LastSubId].MethodIndex :=
GetAbstractMethodIndex(C, i_AbstractMethodCount, i_Address) + 1;
end;
if i_CallMode in [cmDYNAMIC, cmOVERRIDE] then
Records[LastSubId].DynamicMethodIndex :=
GetDynamicMethodIndexByAddress(C, i_Address);
end;
end;
function TBaseSymbolTable.RegisterMethod(LevelId: Integer;
const SubName, ResultType: String;
CallConvention: Integer;
i_Address: Pointer;
IsShared: Boolean = false;
i_CallMode: Integer = cmNONE;
i_MethodIndex: Integer = 0;
i_OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
var
TypeId: Integer;
begin
TypeId := LookupType(ResultType, true);
if TypeId = 0 then
begin
ExternList.Add(Card + 1,
ResultType,
erTypeId);
end;
result := RegisterMethod(LevelId, SubName, TypeId, CallConvention, i_Address,
IsShared, i_CallMode, i_MethodIndex, i_OverCount,
i_IsAbstract, i_AbstractMethodCount, i_IsDeprecated);
end;
function TBaseSymbolTable.RegisterConstructor(LevelId: Integer;
const SubName: String;
i_Address: Pointer;
IsShared: Boolean = false;
i_CallMode: Integer = cmNONE;
i_MethodIndex: Integer = 0;
i_OverCount: Integer = 0;
i_IsAbstract: Boolean = false;
i_AbstractMethodCount: Integer = 0;
i_IsDeprecated: Boolean = false): Integer;
var
SubID, MethodIndex: Integer;
C: TClass;
begin
result := LastShiftValue;
with AddRecord do
begin
Name := SubName;
Count := 0;
Kind := KindCONSTRUCTOR;
TypeID := LevelID;
Host := true;
Shift := LastShiftValue;
Level := LevelId;
CallConv := ccREGISTER;
IsSharedMethod := IsShared;
{$IFDEF PAX64}
CallConv := cc64;
{$ENDIF}
SubId := Id;
Address := i_Address;
CallMode := i_CallMode;
OverCount := i_OverCount;
IsDeprecated := i_IsDeprecated;
end;
Inc(LastShiftValue, SizeOfPointer);
with AddRecord do
begin
Kind := KindVAR;
TypeID := LevelID;
Host := true;
Shift := 0;
Level := SubId;
end;
with AddRecord do
begin
Kind := KindNONE;
Host := true;
Shift := 0;
Level := SubId;
end;
LastSubId := SubId;
if i_CallMode = cmNONE then
Exit;
C := Records[LevelId].PClass;
if C <> nil then
begin
MethodIndex := VirtualMethodIndex(C, i_Address) + 1;
if MethodIndex > 0 then
Records[LastSubId].MethodIndex := MethodIndex;
if HeaderParser.IsAbstract then
begin
Records[LastSubId].CallMode := cmVIRTUAL;
if i_MethodIndex > 0 then
HeaderParser.AbstractMethodCount := i_MethodIndex;
Records[LastSubId].MethodIndex :=
GetAbstractMethodIndex(C, i_AbstractMethodCount) + 1;
end;
end;
end;
function TBaseSymbolTable.RegisterDestructor(LevelId: Integer;
const SubName: String;
i_Address: Pointer;
i_CallMode: Integer = cmVIRTUAL): Integer;
var
SubID: Integer;
begin
result := LastShiftValue;
with AddRecord do
begin
Name := SubName;
Count := 0;
Kind := KindDESTRUCTOR;
TypeID := typeVOID;
Host := true;
Shift := LastShiftValue;
Level := LevelId;
CallConv := ccREGISTER;
{$IFDEF PAX64}
CallConv := cc64;
{$ENDIF}
SubId := Id;
Address := i_Address;
CallMode := i_CallMode;
end;
Inc(LastShiftValue, SizeOfPointer);
with AddRecord do
begin
Kind := KindVAR;
TypeID := LevelID;
Host := true;
Shift := 0;
Level := SubId;
end;
with AddRecord do
begin
Kind := KindNONE;
Host := true;
Shift := 0;
Level := SubId;
end;
LastSubId := SubId;
end;
function TBaseSymbolTable.RegisterFakeHeader(LevelId: Integer;
const Header: String; Address: Pointer): Integer;
begin
result := RegisterHeader(LevelId, Header, Address);
Records[LastSubId].IsFakeMethod := true;
end;
function TBaseSymbolTable.RegisterHeader(LevelId: Integer;
const Header: String; Address: Pointer;
AMethodIndex: Integer = 0): Integer;
var
TypeId, I, J, L, P, ElemTypeId, SubId, ReadId, WriteId, PropId: Integer;
IsMethod: Boolean;
ParamMod: TParamMod;
S: String;
Tag: Integer;
OverList: TIntegerList;
OpenArray: Boolean;
AncestorId: Integer;
OverCount: Integer;
label
label_params;
begin
LastCard := Card;
result := 0;
HeaderParser.Init(Header, Self, LevelId);
if not HeaderParser.Parse then
begin
if RaiseE then
raise Exception.Create(errSyntaxError);
REG_OK := false;
Exit;
end;
{$IFDEF PAX64}
HeaderParser.CC := cc64;
{$ENDIF}
IsMethod := (LevelId > 0) and (Records[LevelId].Kind = KindTYPE);
if IsMethod then
begin
L := Records[LevelId].Level;
end
else
L := LevelId;
if HeaderParser.IsProperty then
begin
if (HeaderParser.ReadIdent = '') and (HeaderParser.ReadIdent = '') then
if LevelId > 0 then
if Records[LevelId].FinalTypeId = typeCLASS then
begin
AncestorId := Records[LevelId].AncestorId;
while AncestorId > 0 do
begin
PropId := Lookup(HeaderParser.Name, AncestorId, true);
if PropId = 0 then
break;
if Records[PropId].Kind <> KindPROP then
break;
if (Records[PropId].ReadId <> 0) or (Records[PropId].WriteId <> 0) then
begin
HeaderParser.ReadIdent := Records[Records[PropId].ReadId].Name;
HeaderParser.WriteIdent := Records[Records[PropId].WriteId].Name;
break;
end
else
AncestorId := Records[AncestorId].AncestorId;
end;
end;
if HeaderParser.ReadIdent <> '' then
begin
ReadId := Lookup(HeaderParser.ReadIdent, LevelId, true);
if ReadId > 0 then
begin
if Records[ReadId].Kind = KindTYPE_FIELD then
ReadId := - ReadId
else
ReadId := Records[ReadId].Shift;
end
else
RaiseError(errUndeclaredIdentifier, [HeaderParser.ReadIdent]);
end
else
ReadId := 0;
if HeaderParser.WriteIdent <> '' then
begin
WriteId := Lookup(HeaderParser.WriteIdent, LevelId, true);
if WriteId > 0 then
begin
if Records[WriteId].Kind = KindTYPE_FIELD then
WriteId := - WriteId
else
WriteId := Records[WriteId].Shift;
end
else
RaiseError(errUndeclaredIdentifier, [HeaderParser.WriteIdent]);
end
else
WriteId := 0;
{
if HeaderParser.ResType = '' then
begin
PropId := Lookup(HeaderParser.Name, LevelId, true);
if PropId = 0 then
ExternList.Add(0,
Records[LevelId].FullName + '.' + HeaderParser.ResType,
ePropertyInBaseClassId);
Exit;
end;
}
TypeId := LookupType(HeaderParser.ResType, L, true);
if TypeId = 0 then
ExternList.Add(Card + 1,
HeaderParser.ResType,
erTypeId);
if (HeaderParser.ReadIdent <> '') and (ReadId = 0) then
ExternList.Add(Card + 1,
Records[LevelId].FullName + '.' + HeaderParser.ReadIdent,
erReadId);
if (HeaderParser.WriteIdent <> '') and (WriteId = 0) then
ExternList.Add(Card + 1,
Records[LevelId].FullName + '.' + HeaderParser.WriteIdent,
erWriteId);
result := RegisterProperty(LevelId, HeaderParser.Name,
TypeId, ReadId, WriteId, HeaderParser.IsDefault);
{$IFDEF DRTTI}
goto label_Params;
{$ENDIF}
Exit;
end;
if HeaderParser.IsOverloaded then
begin
OverList := LookupAll(HeaderParser.Name, LevelId, true);
OverCount := OverList.Count;
FreeAndNil(OverList);
end
else
OverCount := 0;
case HeaderParser.KS of
ksPROCEDURE:
begin
if IsMethod then
result := RegisterMethod(LevelId,
HeaderParser.Name,
TypeVOID,
HeaderParser.CC,
Address,
HeaderParser.IsShared,
HeaderParser.CallMode,
AMethodIndex,
OverCount,
HeaderParser.IsAbstract,
HeaderParser.AbstractMethodCount,
HeaderParser.IsDeprecated)
else
result := RegisterRoutine(LevelId, HeaderParser.Name, TypeVOID, HeaderParser.CC,
Address, OverCount, HeaderParser.IsDeprecated);
end;
ksFUNCTION:
begin
TypeId := LookupType(HeaderParser.ResType, L, true);
if TypeId = 0 then
begin
ExternList.Add(Card + 1,
HeaderParser.ResType,
erTypeId);
end;
if IsMethod then
result := RegisterMethod(LevelId,
HeaderParser.Name,
TypeId,
HeaderParser.CC,
Address,
HeaderParser.IsShared,
HeaderParser.CallMode,
AMethodIndex,
OverCount,
HeaderParser.IsAbstract,
HeaderParser.AbstractMethodCount,
HeaderParser.IsDeprecated)
else
result := RegisterRoutine(LevelId, HeaderParser.Name, TypeId, HeaderParser.CC,
Address, OverCount, HeaderParser.IsDeprecated);
end;
ksCONSTRUCTOR:
begin
result := RegisterConstructor(LevelId,
HeaderParser.Name,
Address,
HeaderParser.IsShared,
HeaderParser.CallMode,
AMethodIndex,
OverCount,
HeaderParser.IsAbstract,
HeaderParser.AbstractMethodCount,
HeaderParser.IsDeprecated);
end;
ksDESTRUCTOR:
begin
result := RegisterMethod(LevelId,
HeaderParser.Name,
TypeVOID,
HeaderParser.CC,
Address,
false,
HeaderParser.CallMode,
0);
Records[LastSubId].Kind := kindDESTRUCTOR;
end;
end;
Label_Params:
for I:=1 to HeaderParser.NP do
begin
OpenArray := false;
S := HeaderParser.Types[I];
TypeId := LookupType(S, L, true);
if TypeId = 0 then
begin
P := Pos('ARRAY OF ', S);
if P = 1 then
begin
OpenArray := true;
Delete(S, 1, 9);
if StrEql(S, 'CONST') then
ElemTypeId := H_TVarRec
else
ElemTypeId := LookupType(S, L, true);
if ElemTypeId = 0 then
begin
ExternList.Add(Card + 1,
S,
erPatternId);
end;
SubId := -1;
for J:=Card downto 1 do
if Records[J].Shift = result then
begin
SubId := J;
Break;
end;
if SubId = -1 then
begin
RaiseError(errInternalError, []);
Exit;
end;
TypeId := RegisterOpenArrayType(SubId, 'T' + S + 'Array', ElemTypeId);
end
else
begin
ExternList.Add(Card + 1,
S,
erTypeId);
end;
end;
ParamMod := HeaderParser.Mods[I];
Tag := 0;
if HeaderParser.Optionals[I] then
Tag := 1;
if ParamMod in [pmByRef, pmOut] then
begin
RegisterParameter(result, TypeId, HeaderParser.Values[I], true, HeaderParser.Params[I], Tag);
if ParamMod = pmOut then
Records[Card].IsOut := true;
end
else if ParamMod = pmConst then
begin
RegisterParameter(result, TypeId, HeaderParser.Values[I], false, HeaderParser.Params[I], Tag);
Records[Card].IsConst := true;
end
else
begin
RegisterParameter(result, TypeId, HeaderParser.Values[I], false, HeaderParser.Params[I], Tag);
end;
if OpenArray then
Records[Card].IsOpenArray := true;
if HeaderParser.Optionals[I] then
Records[Card].DefVal := HeaderParser.DefVals[I];
end;
end;
procedure TBaseSymbolTable.RegisterRunnerParameter(HSub: Integer);
var
I, SubId: Integer;
R: TSymbolRec;
begin
SubId := -1;
for I:=Card downto 1 do
begin
R := Records[I];
if R.Kind = KindPROP then
begin
SubId := I;
Break;
end;
if R.Kind in KindSUBS then
if R.Shift = HSub then
begin
SubId := I;
Break;
end;
end;
if SubId = -1 then
begin
RaiseError(errInternalError, []);
Exit;
end;
Records[SubId].RunnerParameter := true;
end;
function TBaseSymbolTable.RegisterParameter(HSub: Integer;
const ParameterName: String;
ParamTypeID: Integer;
ParamMod: Integer = 0;
Optional: Boolean = false;
const DefaultValue: String = ''): Integer;
var
pm: TParamMod;
Value: Variant;
Tag: Integer;
OpenArray: Boolean;
ParamTypeName: String;
FT, IntVal, DoubleVal, Code1: Integer;
begin
Tag := 0;
pm := TParamMod(ParamMod);
ParamTypeName := Records[ParamTypeId].Name;
OpenArray := Pos('DYNARRAY_', ParamTypeName) = 1;
if Optional then
begin
Tag := 1;
FT := Records[ParamTypeId].FinalTypeId;
if FT in IntegerTypes then
begin
Val(DefaultValue, IntVal, Code1);
Value := IntVal;
end
else if FT in RealTypes then
begin
Val(DefaultValue, DoubleVal, Code1);
Value := DoubleVal;
end
else
Value := DefaultValue;
end;
if pm in [pmByRef, pmOut] then
begin
result := RegisterParameter(HSub, ParamTypeId, Value, true, ParameterName);
if pm = pmOut then
Records[Card].IsOut := true;
end
else if pm = pmConst then
begin
result := RegisterParameter(HSub, ParamTypeId, Value, false, ParameterName, Tag);
Records[Card].IsConst := true;
end
else
begin
result := RegisterParameter(HSub, ParamTypeId, Value, false, ParameterName, Tag);
end;
if OpenArray then
Records[Card].IsOpenArray := true;
end;
function TBaseSymbolTable.RegisterParameter(HSub: Integer;
const ParameterName: String;
const ParameterType: String;
ParamMod: Integer = 0;
Optional: Boolean = false;
const DefaultValue: String = ''): Integer;
var
ParamTypeId: Integer;
begin
ParamTypeId := LookupType(ParameterType, true);
result := RegisterParameter(Hsub, ParameterName, ParamTypeId, ParamMod, Optional,
DefaultValue);
if ParamTypeId = 0 then
ExternList.Add(Card,
ParameterType,
erTypeId);
end;
function TBaseSymbolTable.RegisterParameter(HSub: Integer; ParamTypeID: Integer;
const DefaultValue: Variant;
InitByRef: Boolean = false;
ParameterName: String = '';
Tag: Integer = 0): Integer;
var
I, SubId: Integer;
R: TSymbolRec;
begin
result := LastShiftValue;
SubId := -1;
for I:=Card downto 1 do
begin
R := Records[I];
if R.Kind = KindPROP then
begin
SubId := I;
Break;
end;
if R.Kind in KindSUBS then
if R.Shift = HSub then
begin
SubId := I;
Break;
end;
end;
if SubId = -1 then
begin
RaiseError(errInternalError, []);
Exit;
end;
Records[SubId].Count := Records[SubId].Count + 1;
with AddRecord do
begin
Kind := KindVAR;
TypeID := ParamTypeId;
Host := true;
Param := true;
Shift := 0;
Level := SubId;
ByRef := InitByRef;
Value := DefaultValue;
Optional := VarType(Value) <> varEmpty;
Name := ParameterName;
if Tag = 1 then
Optional := true;
if InitByRef and Optional then
RaiseError(errDefaultParameterMustBeByValueOrConst, [Name]);
end;
end;
function TBaseSymbolTable.IsResultId(Id: Integer): Boolean;
var
L: Integer;
begin
result := false;
if Id = 0 then
Exit;
L := Records[Id].Level;
if L = 0 then
Exit;
if Records[L].Kind in KindSUBS then
result := GetResultId(L) = Id;
end;
function TBaseSymbolTable.GetResultId(SubId: Integer): Integer;
begin
result := SubId + 1;
end;
function TBaseSymbolTable.GetSelfId(SubId: Integer): Integer;
begin
result := SubId + 2;
end;
function TBaseSymbolTable.GetDl_Id(SubId: Integer): Integer;
var
I: Integer;
begin
result := 0;
for I:=SubId + 3 to Card do
if Records[I].Level = SubId then
if Records[I].Name = '%DL' then
begin
result := I;
Exit;
end;
RaiseError(errInternalError, []);
end;
function TBaseSymbolTable.GetRBP_Id(SubId: Integer): Integer;
var
I: Integer;
begin
result := 0;
for I:=SubId + 3 to Card do
if Records[I].Level = SubId then
if Records[I].Name = '%RBP' then
begin
result := I;
Exit;
end;
RaiseError(errInternalError, []);
end;
function TBaseSymbolTable.GetRBX_Id(SubId: Integer): Integer;
var
I: Integer;
begin
result := 0;
for I:=SubId + 3 to Card do
if Records[I].Level = SubId then
if Records[I].Name = '%RBX' then
begin
result := I;
Exit;
end;
RaiseError(errInternalError, []);
end;
function TBaseSymbolTable.GetRDI_Id(SubId: Integer): Integer;
var
I: Integer;
begin
result := 0;
for I:=SubId + 3 to Card do
if Records[I].Level = SubId then
if Records[I].Name = '%RDI' then
begin
result := I;
Exit;
end;
RaiseError(errInternalError, []);
end;
function TBaseSymbolTable.GetParamId(SubId, ParamNumber: Integer): Integer;
var
I, K, D: Integer;
RI: TSymbolRec;
begin
result := -1;
K := -1;
D := 3;
if Records[SubId].Kind = kindPROP then
D := 1;
for I:=SubId + D to Card do
begin
RI := Records[I];
if RI.Param and (RI.Level = SubId) then
begin
Inc(K);
if K = ParamNumber then
begin
result := I;
Exit;
end;
end;
end;
RaiseError(errInvalidIndex, [ParamNumber]);
end;
function TBaseSymbolTable.GetRecord(I: Integer): TSymbolRec;
begin
result := TSymbolRec(A[I]);
end;
function TBaseSymbolTable.AddRecord: TSymbolRec;
var
AK: Integer;
begin
AK := A.Count;
if (Card = AK - 1) or (Card >= FirstLocalId) then
begin
Inc(Card);
result := TSymbolRec.Create(Self);
result.Id := Card;
A.Add(result);
end
else
begin
Inc(Card);
result := Records[Card];
end;
end;
procedure TBaseSymbolTable.RemoveLastRecord;
var
AK: Integer;
R: TSymbolRec;
S: String;
begin
R := Records[Card];
S := R.Name;
if S <> '' then
HashArray.DeleteName(S, R.Id);
AK := A.Count;
if (Card = AK - 1) or (Card >= FirstLocalId) then
begin
{$IFDEF ARC}
A[AK - 1] := nil;
{$ELSE}
TObject(A[AK - 1]).Free;
{$ENDIF}
A.Delete(AK - 1);
end;
Dec(Card);
end;
function TBaseSymbolTable.CreateEmptySet: TSymbolRec;
var
T: Integer;
begin
T := RegisterSetType(0, '$$', typeVOID);
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := T;
result.Value := 0;
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := 32;
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddIntegerConst(Value: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeINTEGER;
result.Value := Value;
result.Level := 0;
end;
function TBaseSymbolTable.AddCardinalConst(Value: Cardinal): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeCARDINAL;
{$IFDEF VARIANTS}
result.Value := Value;
{$ELSE}
result.Value := Integer(Value);
{$ENDIF}
result.Level := 0;
end;
function TBaseSymbolTable.AddSmallIntConst(Value: SmallInt): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeSMALLINT;
result.Value := Value;
result.Level := 0;
end;
function TBaseSymbolTable.AddShortIntConst(Value: ShortInt): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeSHORTINT;
result.Value := Value;
result.Level := 0;
end;
{$IFDEF VARIANTS}
function TBaseSymbolTable.AddInt64Const(Value: Int64): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeINT64;
result.Value := Value;
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Int64);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddUInt64Const(Value: UInt64): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeUINT64;
result.Value := Value;
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(UInt64);
Inc(LastShiftValue, result.FinSize);
end;
{$ELSE}
function TBaseSymbolTable.AddInt64Const(Value: Int64): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeINT64;
result.Value := Integer(Value);
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Int64);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddUInt64Const(Value: UInt64): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeUINT64;
result.Value := Integer(Value);
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(UInt64);
Inc(LastShiftValue, result.FinSize);
end;
{$ENDIF}
function TBaseSymbolTable.AddEnumConst(TypeId, Value: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := TypeId;
result.Value := Value;
result.Level := 0;
end;
function TBaseSymbolTable.AddPointerConst(TypeId: Integer; Value: Pointer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := TypeId;
{$IFDEF VARIANTS}
result.Value := Cardinal(Value);
{$ELSE}
result.Value := Integer(Value);
{$ENDIF}
result.Level := 0;
end;
function TBaseSymbolTable.AddRecordConst(TypeId: Integer; const Value: Variant): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := TypeId;
result.Value := Value;
result.Level := 0;
end;
function TBaseSymbolTable.AddArrayConst(TypeId: Integer; const Value: Variant): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := TypeId;
result.Value := Value;
result.Level := 0;
end;
function TBaseSymbolTable.AddSetConst(TypeId: Integer; const Value: Variant): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := TypeId;
result.Value := Value;
result.Level := 0;
// result.Shift := LastShiftValue;
// Records[TypeId].Completed := true;
// Inc(LastShiftValue, Records[result.Id].Size);
end;
function TBaseSymbolTable.AddClassConst(TypeId: Integer; Value: TObject): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := TypeId;
result.Value := Integer(Value);
result.Level := 0;
result.MustBeAllocated := true;
end;
function TBaseSymbolTable.AddClassRefConst(TypeId: Integer; Value: TClass): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := TypeId;
result.Value := Integer(Value);
result.Level := 0;
result.MustBeAllocated := true;
end;
function TBaseSymbolTable.AddSetVar(TypeId: Integer; const Value: Variant): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := TypeId;
result.Value := Value;
result.Level := 0;
// result.Shift := LastShiftValue;
// Records[TypeId].Completed := true;
// Inc(LastShiftValue, Records[result.Id].Size);
end;
{$IFNDEF PAXARM}
function TBaseSymbolTable.AddAnsiCharConst(Value: AnsiChar): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeANSICHAR;
result.Value := Ord(Value);
result.Level := 0;
end;
{$ENDIF}
function TBaseSymbolTable.AddWideCharConst(Value: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeWIDECHAR;
result.Value := Value;
result.Level := 0;
end;
{$IFNDEF PAXARM}
function TBaseSymbolTable.AddPAnsiCharConst(const Value: AnsiString): TSymbolRec;
var
SZ: Integer;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typePANSICHAR;
result.Value := Value;
result.Level := 0;
SZ := 0;
Inc(SZ, SizeOfPointer); // pointer to string literal
Inc(SZ, SizeOfPointer); // ref counter
Inc(SZ, SizeOfPointer); // length
// reserve place for literal
Inc(SZ, Length(Value) + 1);
result.Shift := LastShiftValue;
Inc(LastShiftValue, SZ);
end;
function TBaseSymbolTable.AddShortStringConst(const Value: String): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeSHORTSTRING;
result.Value := Value;
result.Level := 0;
end;
{$ENDIF}
{$IFDEF PAXARM}
function TBaseSymbolTable.AddPWideCharConst(const Value: String): TSymbolRec;
{$ELSE}
function TBaseSymbolTable.AddPWideCharConst(const Value: WideString): TSymbolRec;
{$ENDIF}
var
SZ: Integer;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typePWIDECHAR;
result.Value := Value;
result.Level := 0;
SZ := 0;
Inc(SZ, SizeOfPointer); // pointer to string literal
Inc(SZ, SizeOfPointer); // length
// reserve place for literal
Inc(SZ, Length(Value) * 2 + 2);
result.Shift := LastShiftValue;
Inc(LastShiftValue, SZ);
end;
function TBaseSymbolTable.AddByteConst(Value: Byte): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeBYTE;
result.Value := Ord(Value);
result.Level := 0;
end;
function TBaseSymbolTable.AddWordConst(Value: Word): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeWORD;
result.Value := Ord(Value);
result.Level := 0;
end;
function TBaseSymbolTable.AddBooleanConst(Value: Boolean): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeBOOLEAN;
result.Value := Value;
result.Level := 0;
end;
function TBaseSymbolTable.AddByteBoolConst(Value: ByteBool): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeBYTEBOOL;
if Value then
result.Value := $ff
else
result.Value := 0;
result.Level := 0;
end;
function TBaseSymbolTable.AddWordBoolConst(Value: WordBool): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeWORDBOOL;
if Value then
result.Value := $ffff
else
result.Value := 0;
result.Level := 0;
end;
function TBaseSymbolTable.AddLongBoolConst(Value: LongBool): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeLONGBOOL;
if Value then
result.Value := $ffffffff
else
result.Value := 0;
result.Level := 0;
end;
function TBaseSymbolTable.AddDoubleConst(Value: Double): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeDOUBLE;
result.Value := Value;
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Double);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddCurrencyConst(Value: Double): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeCURRENCY;
result.Value := Value;
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Currency);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddSingleConst(Value: Single): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeSINGLE;
result.Value := Value;
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Single);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddExtendedConst(Value: Extended): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeEXTENDED;
result.Value := Value;
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Extended);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddVariantConst(const Value: Variant): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeVARIANT;
result.SetVariantValue(Value);
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Variant);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddOleVariantConst(const Value: OleVariant): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindCONST;
result.TypeId := typeOLEVARIANT;
result.SetVariantValue(Value);
result.Level := 0;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(OleVariant);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddTMethodVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := H_TMethod;
result.Value := 0.0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOfTMethod;
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddDoubleVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeDOUBLE;
result.Value := 0.0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Double);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddCurrencyVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeCURRENCY;
result.Value := 0.0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Currency);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddSingleVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeSINGLE;
result.Value := 0.0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Single);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddExtendedVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeEXTENDED;
result.Value := 0.0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Extended);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddInt64Var(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeINT64;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Int64);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddUInt64Var(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeUINT64;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(UInt64);
Inc(LastShiftValue, result.FinSize);
end;
{$IFNDEF PAXARM}
function TBaseSymbolTable.AddStringVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeANSISTRING;
result.Value := '';
result.Level := Level;
result.Name := '@';
result.Shift := LastShiftValue;
result.FinSize := SizeOf(String);
Inc(LastShiftValue, result.FinSize);
end;
{$ENDIF}
function TBaseSymbolTable.AddInterfaceVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := H_IUnknown;
result.Level := Level;
result.Name := '@';
result.Shift := LastShiftValue;
result.FinSize := SizeOf(IUnknown);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddClassVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeCLASS;
result.Level := Level;
result.Name := '@';
result.Shift := LastShiftValue;
result.FinSize := SizeOfPointer;
Inc(LastShiftValue, result.FinSize);
end;
{$IFNDEF PAXARM}
function TBaseSymbolTable.AddWideStringVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeWIDESTRING;
result.Value := '';
result.Level := Level;
result.Name := '@';
result.Shift := LastShiftValue;
result.FinSize := SizeOf(WideString);
Inc(LastShiftValue, result.FinSize);
end;
{$ENDIF}
function TBaseSymbolTable.AddUnicStringVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeUNICSTRING;
result.Value := '';
result.Level := Level;
result.Name := '@';
result.Shift := LastShiftValue;
result.FinSize := SizeOf(UnicString);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddVariantVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeVARIANT;
// result.Value := '';
result.Level := Level;
result.Name := '@';
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Variant);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddOleVariantVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeOLEVARIANT;
// result.Value := '';
result.Level := Level;
result.Name := '@';
result.Shift := LastShiftValue;
result.FinSize := SizeOf(OleVariant);
Inc(LastShiftValue, result.FinSize);
end;
{$IFNDEF PAXARM}
function TBaseSymbolTable.AddShortStringVar(Level, TypeId: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := TypeId;
result.Value := '';
result.Level := Level;
end;
{$ENDIF}
function TBaseSymbolTable.AddDynarrayVar(Level, TypeId: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := TypeId;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOfPointer;
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddRecordVar(Level, TypeId: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := TypeId;
result.Level := Level;
end;
function TBaseSymbolTable.AddIntegerVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeINTEGER;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(LongInt);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddCardinalVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeCARDINAL;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Cardinal);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddSmallIntVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeSMALLINT;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(SmallInt);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddShortIntVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeSHORTINT;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(ShortInt);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddByteVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeBYTE;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Byte);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddWordVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeWORD;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Word);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddBooleanVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeBOOLEAN;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(Boolean);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddByteBoolVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeBYTEBOOL;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(ByteBool);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddWordBoolVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeWORDBOOL;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(WordBool);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddLongBoolVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeLONGBOOL;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(LongBool);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddPointerVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typePOINTER;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOfPointer;
Inc(LastShiftValue, result.FinSize);
end;
{$IFNDEF PAXARM}
function TBaseSymbolTable.AddAnsiCharVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeANSICHAR;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(AnsiChar);
Inc(LastShiftValue, result.FinSize);
end;
{$ENDIF}
function TBaseSymbolTable.AddWideCharVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeWIDECHAR;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOf(WideChar);
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddVoidVar(Level: Integer; SZ: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeVOID;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SZ;
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddClassRefVar(Level: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindVAR;
result.TypeId := typeCLASSREF;
result.Value := 0;
result.Level := Level;
result.Shift := LastShiftValue;
result.FinSize := SizeOfPointer;
Inc(LastShiftValue, result.FinSize);
end;
function TBaseSymbolTable.AddLabel: TSymbolRec;
begin
result := AddRecord;
result.Kind := kindLABEL;
result.Level := 0;
end;
function TBaseSymbolTable.AddPointerType(SourceTypeId: Integer): TSymbolRec;
begin
result := AddRecord;
result.Kind := kindTYPE;
result.TypeId := typePOINTER;
result.Level := Records[SourceTypeId].Level;
result.PatternId := SourceTypeId;
end;
function TBaseSymbolTable.AddEndOfClassHeader(ClassId: Integer): TSymbolRec;
begin
result := AddRecord;
result.Name := '*' + Records[ClassId].Name;
result.Kind := kindEND_CLASS_HEADER;
result.Level := ClassId;
end;
function TBaseSymbolTable.LookupNamespace(const S: String;
i_Level: Integer; UpCase: Boolean): Integer;
var
I, J: Integer;
ok: Boolean;
List: TIntegerList;
Q: TStringList;
S2: String;
begin
if PosCh('.', S) > 0 then
begin
Q := ExtractNames(S);
try
result := i_Level;
for I := 0 to Q.Count - 1 do
begin
S2 := Q[I];
if StrEql(S, 'System') then
result := 0
else
result := LookupNamespace(S2, result, Upcase);
end;
finally
FreeAndNil(Q);
end;
Exit;
end;
List := HashArray.GetList(S);
result := 0;
for J := List.Count - 1 downto 0 do
begin
I := List[J];
with Records[I] do
if (Kind = KindNAMESPACE) and (Level = i_Level) then
begin
if UpCase then
ok := StrEql(Name, S)
else
ok := Name = S;
if ok then
begin
result := I;
Exit;
end;
end;
end;
end;
function TBaseSymbolTable.LookupFullName(const S: String; UpCase: Boolean): Integer;
var
I, J: Integer;
ok: Boolean;
RI: TSymbolRec;
List: TIntegerList;
begin
result := 0;
if HashArray = nil then
begin
for I := Card downto FirstLocalId + 1 do
begin
RI := Records[I];
begin
if UpCase then
ok := StrEql(RI.FullName, S)
else
ok := RI.FullName = S;
if ok then
begin
result := I;
Exit;
end;
end;
end;
Exit;
end;
List := HashArray.GetList(ExtractName(S));
for J := List.Count - 1 downto 0 do
begin
I := List[J];
RI := Records[I];
begin
if UpCase then
ok := StrEql(RI.FullName, S)
else
ok := RI.FullName = S;
if ok then
begin
result := I;
Exit;
end;
end;
end;
end;
function TBaseSymbolTable.LookupFullNameEx(const S: String; UpCase: Boolean;
OverCount: Integer): Integer;
var
I, J: Integer;
ok: Boolean;
RI: TSymbolRec;
List: TIntegerList;
begin
if OverCount = 0 then
begin
result := LookupFullName(S, Upcase);
Exit;
end;
result := 0;
if HashArray = nil then
begin
for I:= Card downto FirstLocalId + 1 do
begin
RI := Records[I];
begin
if UpCase then
ok := StrEql(RI.FullName, S)
else
ok := RI.FullName = S;
if ok then
if RI.OverCount = OverCount then
begin
result := I;
Exit;
end;
end;
end;
Exit;
end;
List := HashArray.GetList(ExtractName(S));
for J := List.Count - 1 downto 0 do
begin
I := List[J];
RI := Records[I];
begin
if UpCase then
ok := StrEql(RI.FullName, S)
else
ok := RI.FullName = S;
if ok then
if RI.OverCount = OverCount then
begin
result := I;
Exit;
end;
end;
end;
end;
function TBaseSymbolTable.LookUpType(const S: String;
i_Level: Integer; UpCase: Boolean): Integer;
var
I, J: Integer;
ok: Boolean;
List: TIntegerList;
begin
if S = '' then
begin
result := 0;
Exit;
end;
{$IFDEF UNIC}
if StrEql(S, 'Char') then
result := typeWIDECHAR
else if StrEql(S, 'String') then
result := typeUNICSTRING
else if StrEql(S, 'PChar') then
result := typePWIDECHAR
else
result := Types.IndexOf(S);
{$ELSE}
result := Types.IndexOf(S);
{$ENDIF}
if result > 0 then
Exit;
List := HashArray.GetList(S);
result := 0;
for J := List.Count - 1 downto 0 do
begin
I := List[J];
with Records[I] do
if (Kind = KindTYPE) and (Level = i_Level) then
begin
if UpCase then
ok := StrEql(Name, S)
else
ok := Name = S;
if ok then
begin
result := I;
Exit;
end;
end;
end;
for J := List.Count - 1 downto 0 do
begin
I := List[J];
with Records[I] do
if Kind = KindTYPE then
begin
if UpCase then
ok := StrEql(Name, S)
else
ok := Name = S;
if ok then
begin
result := I;
Exit;
end;
end;
end;
end;
function TBaseSymbolTable.LookUpType(const S: String; UpCase: Boolean): Integer;
var
I, J: Integer;
ok: Boolean;
List: TIntegerList;
begin
if S = '' then
begin
result := 0;
Exit;
end;
{$IFDEF UNIC}
if StrEql(S, 'Char') then
result := typeWideCHAR
else if StrEql(S, 'String') then
result := typeUNICSTRING
else if StrEql(S, 'PChar') then
result := typePWIDECHAR
else
result := Types.IndexOf(S);
{$ELSE}
result := Types.IndexOf(S);
{$ENDIF}
if result > 0 then
Exit;
List := HashArray.GetList(S);
result := 0;
for J := List.Count - 1 downto 0 do
begin
I := List[J];
with Records[I] do
if Kind = KindTYPE then
begin
if UpCase then
ok := StrEql(Name, S)
else
ok := Name = S;
if ok then
begin
result := I;
Exit;
end;
end;
end;
end;
function TBaseSymbolTable.LookUpTypeEx(const S: String;
i_Level: Integer; UpCase: Boolean; LowBound: Integer): Integer;
var
I, J: Integer;
ok: Boolean;
List: TIntegerList;
begin
if S = '' then
begin
result := 0;
Exit;
end;
result := Types.IndexOf(S);
if result > 0 then
if result >= LowBound then
Exit;
List := HashArray.GetList(S);
result := 0;
for J := List.Count - 1 downto 0 do
begin
I := List[J];
if I < LowBound then
continue;
with Records[I] do
if (Kind = KindTYPE) and (Level = i_Level) then
begin
if UpCase then
ok := StrEql(Name, S)
else
ok := Name = S;
if ok then
begin
result := I;
Exit;
end;
end;
end;
for J:=List.Count - 1 downto 0 do
begin
I := List[J];
if I < LowBound then
continue;
with Records[I] do
if Kind = KindTYPE then
begin
if UpCase then
ok := StrEql(Name, S)
else
ok := Name = S;
if ok then
begin
result := I;
Exit;
end;
end;
end;
end;
function TBaseSymbolTable.LookupParentMethodBase(SubId: Integer;
UpCase: Boolean;
var BestId: Integer): Integer;
var
I, J, Level, TempLevel: Integer;
ok: Boolean;
List: TIntegerList;
R: TSymbolRec;
Name, Signature: String;
begin
Name := Records[SubId].Name;
Signature := Records[SubId].SignatureBrief;
Level := Records[SubId].Level;
List := HashArray.GetList(Name);
result := 0;
BestId := 0;
for J:=List.Count - 1 downto 0 do
begin
I := List[J];
R := Records[I];
if R.Kind in KindSUBS then
begin
TempLevel := R.Level;
if TempLevel = 0 then
continue;
if Level = TempLevel then
continue;
if Records[TempLevel].ClassIndex = -1 then
continue;
if not Inherits(Level, TempLevel) then
continue;
if UpCase then
ok := StrEql(R.Name, Name)
else
ok := R.Name = Name;
if ok then
begin
BestId := I;
if UpCase then
ok := StrEql(R.SignatureBrief, Signature)
else
ok := R.SignatureBrief = Signature;
if ok then
begin
result := I;
Exit;
end;
end;
end;
end;
end;
function TBaseSymbolTable.LookupParentMethod(SubId: Integer;
UpCase: Boolean;
HasMethodIndex: Boolean = false): Integer;
var
I, J, Level: Integer;
ok: Boolean;
List: TIntegerList;
R: TSymbolRec;
Name, Signature: String;
C, CA: TClass;
label
Again;
begin
Name := Records[SubId].Name;
Signature := Records[SubId].SignatureBrief;
List := HashArray.GetList(Name);
C := Records[Records[SubId].Level].PClass;
result := 0;
Level := Records[SubId].Level;
Again:
if C = nil then
Exit;
for J:=List.Count - 1 downto 0 do
begin
I := List[J];
R := Records[I];
if R.Kind in KindSUBS then
begin
CA := Records[Records[I].Level].PClass;
if CA = nil then
continue;
if C = CA then
continue;
if not C.InheritsFrom(CA) then
begin
if Records[Records[SubId].Level].AncestorId <>
Records[I].Level then
continue;
end;
if UpCase then
ok := StrEql(R.Name, Name)
else
ok := R.Name = Name;
if ok then
begin
if UpCase then
ok := StrEql(R.SignatureBrief, Signature)
else
ok := R.SignatureBrief = Signature;
if ok then
begin
if HasMethodIndex = false then
begin
result := I;
Exit;
end
else
if R.MethodIndex <> 0 then
begin
result := I;
Exit;
end;
end;
end;
end;
end;
if Level > 0 then
if Records[Level].AncestorId > 0 then
begin
Level := Records[Level].AncestorId;
C := Records[Level].PClass;
goto Again;
end;
end;
function TBaseSymbolTable.LookupParentMethods(SubId: Integer; Upcase: Boolean): TIntegerList;
var
Name, Signature: String;
List: TIntegerList;
I, J, L: Integer;
R: TSymbolRec;
b: Boolean;
begin
Name := Records[SubId].Name;
Signature := Records[SubId].SignatureBrief;
L := Records[SubId].Level;
result := TIntegerList.Create;
List := HashArray.GetList(Name);
for J:=List.Count - 1 downto 0 do
begin
I := List[J];
R := Records[I];
if R.Kind in KindSUBS then
begin
if I = SubId then
continue;
if R.Level > 0 then
if Records[R.Level].Kind = KindTYPE then
if Inherits(L, R.Level) then
begin
if Upcase then
b := StrEql(R.Name, Name)
else
b := R.Name = Name;
if not b then
continue;
if Upcase then
b := StrEql(R.SignatureBrief, Signature)
else
b := R.SignatureBrief = Signature;
if b then
begin
result.Add(I);
end;
end;
end;
end;
end;
function TBaseSymbolTable.LookupParentConstructor(SubId: Integer): Integer;
var
I, L, KK, K1, K2, AncestorId: Integer;
R: TSymbolRec;
Signature: String;
begin
result := 0;
Signature := Records[SubId].Signature;
L := Records[SubId].Level;
AncestorId := Records[L].AncestorId;
for KK := 2 downto 1 do
begin
if KK = 1 then
begin
K1 := 1;
if Self.st_tag = 0 then
K2 := Card
else
K2 := TLocalSymbolTable(Self).GlobalST.Card;
end
else
begin
K1 := FirstLocalId + 1;
K2 := Card;
end;
for I := K2 downto K1 do
begin
R := Records[I];
if R.Kind = KindCONSTRUCTOR then
begin
if I = SubId then
continue;
if R.Level > 0 then
if Records[R.Level].Kind = KindTYPE then
if AncestorId = R.Level then
if StrEql(Records[I].Signature, Signature) then
begin
result := I;
end;
end;
end;
end;
end;
function TBaseSymbolTable.LookupParentConstructors(SubId: Integer): TIntegerList;
var
I, L, KK, K1, K2: Integer;
R: TSymbolRec;
Signature: String;
begin
L := Records[SubId].Level;
result := TIntegerList.Create;
Signature := Records[SubId].Signature;
for KK := 2 downto 1 do
begin
if KK = 1 then
begin
K1 := 1;
if Self.st_tag = 0 then
K2 := Card
else
K2 := TLocalSymbolTable(Self).GlobalST.Card;
end
else
begin
K1 := FirstLocalId + 1;
K2 := Card;
end;
for I := K2 downto K1 do
begin
R := Records[I];
if R.Kind = KindCONSTRUCTOR then
begin
if I = SubId then
continue;
if R.Level > 0 then
if Records[R.Level].Kind = KindTYPE then
if Inherits(L, R.Level) then
if StrEql(Records[I].Signature, Signature) then
begin
result.Add(I);
if Records[I].Host then
break;
end;
end;
end;
end;
end;
function TBaseSymbolTable.LookUpEnumItem(const S: String; EnumTypeId: Integer;
UpCase: Boolean): Integer;
var
I: Integer;
R: TSymbolRec;
ok: Boolean;
begin
result := 0;
for I:=EnumTypeId + 1 to Card do
begin
R := Records[I];
if R = SR0 then
Exit;
if R.Kind = KindCONST then
if R.OwnerId = EnumTypeId then
begin
if UpCase then
ok := StrEql(R.Name, S)
else
ok := R.Name = S;
if ok then
begin
result := I;
Exit;
end;
end;
end;
end;
function TBaseSymbolTable.LookUp(const S: String; Level: Integer; UpCase: Boolean;
UpperBoundId: Integer = MaxInt; recursive: Boolean = true): Integer;
var
I, J: Integer;
Ok: Boolean;
InterfaceTypeId: Integer;
R: TSymbolRec;
List: TIntegerList;
begin
List := HashArray.GetList(S);
result := 0;
for J:=List.Count - 1 downto 0 do
begin
I := List[J];
R := Records[I];
if I < UpperBoundId then
if (R.Level = Level) and (not R.InternalField) then
if R.Kind <> KindNONE then
begin
if R.OwnerId > 0 then
if Records[R.OwnerId].Kind <> KindTYPE then
continue;
if UpCase then
ok := StrEql(R.Name, S)
else
ok := R.Name = S;
if ok then
begin
result := I;
Exit;
end;
end;
end;
if Recursive then
if Level > 0 then
begin
if Records[Level].AncestorId > 0 then
begin
result := LookUp(S, Records[Level].AncestorId, Upcase);
if result > 0 then
Exit;
end;
end;
if Assigned(Records[Level].SupportedInterfaces) then
begin
for I := 0 to Records[Level].SupportedInterfaces.Count - 1 do
begin
InterfaceTypeId := Records[Level].SupportedInterfaces[I].Id;
result := LookUp(S, InterfaceTypeId, Upcase);
if result > 0 then
Exit;
end;
end;
end;
function TBaseSymbolTable.LookUpEx(var HelperTypeId: Integer; const S: String; Level: Integer; UpCase: Boolean;
UpperBoundId: Integer = MaxInt; recursive: Boolean = true): Integer;
var
L: TIntegerList;
I: Integer;
begin
HelperTypeId := 0;
result := LookUp(S, Level, UpCase, UpperBoundId, recursive);
if result > 0 then
Exit;
if Level = 0 then
Exit;
if Records[Level].Kind <> KindTYPE then
Exit;
if Records[Level].FinalTypeId = typeHELPER then
begin
I := Records[Level].PatternId;
if I = 0 then
Exit;
result := LookUp(S, I, UpCase, UpperBoundId, recursive);
if result > 0 then
HelperTypeId := Level;
Exit;
end;
L := GetTypeHelpers(Level);
try
for I := 0 to L.Count - 1 do
begin
result := LookUp(S, L[I], UpCase, UpperBoundId, recursive);
if result > 0 then
begin
HelperTypeId := L[I];
Exit;
end;
end;
finally
L.Free;
end;
end;
function TBaseSymbolTable.LookUpAll(const S: String; Level: Integer; UpCase: Boolean): TIntegerList;
var
I, J: Integer;
Ok: Boolean;
R: TSymbolRec;
List: TIntegerList;
begin
List := HashArray.GetList(S);
result := TIntegerList.Create;
for J:=List.Count - 1 downto 0 do
begin
I := List[J];
R := Records[I];
if (R.Level = Level) and (not R.InternalField) then
if R.Kind <> KindNONE then
if R.OwnerId = 0 then
begin
if UpCase then
ok := StrEql(R.Name, S)
else
ok := R.Name = S;
if ok then
result.Insert(0, I);
end;
end;
end;
function TBaseSymbolTable.LookUpSub(const S: String; Level: Integer; UpCase: Boolean): TIntegerList;
function HasAtLevel(const S: String; Level: Integer; UpCase: Boolean): Boolean;
var
I, J: Integer;
Ok: Boolean;
R: TSymbolRec;
List: TIntegerList;
begin
List := HashArray.GetList(S);
result := false;
for J:=List.Count - 1 downto 0 do
begin
I := List[J];
R := Records[I];
if (R.Level = Level) and (R.Kind in kindSUBS) then
begin
if UpCase then
ok := StrEql(R.Name, S)
else
ok := R.Name = S;
if ok then
begin
result := true;
Exit;
end;
end;
end;
end;
procedure DoIt(const S: String; Level: Integer; UpCase: Boolean; Fin: Boolean = false);
var
I, J, I1, K1: Integer;
Ok: Boolean;
R: TSymbolRec;
List: TIntegerList;
Sig: String;
begin
List := HashArray.GetList(S);
K1 := result.Count;
for J:=List.Count - 1 downto 0 do
begin
I := List[J];
R := Records[I];
if (R.Level = Level) and (R.Kind in KindSUBS) then
begin
if UpCase then
ok := StrEql(R.Name, S)
else
ok := R.Name = S;
if ok then
begin
Sig := Records[I].Signature;
for I1 := 0 to K1 - 1 do
if Records[result[I1]].Signature = Sig then
begin
ok := false;
break;
end;
if not ok then
continue;
result.Insert(0, I);
end;
end;
end;
if Fin then
Exit;
Level := Records[Level].AncestorId;
while not ((Level = 0) or (Level = H_TObject) or (Level = JS_ObjectClassId)) do
begin
if HasAtLevel(S, Level, Upcase) then
begin
DoIt(S, Level, upcase, true);
Exit;
end;
Level := Records[Level].AncestorId;
end;
end;
begin
result := TIntegerList.Create;
DoIt(S, Level, Upcase);
end;
function TBaseSymbolTable.LookUpSubs(const S: String; Level: Integer; UsingList: TIntegerList; UpCase: Boolean): TIntegerList;
var
I, J, LevelId, SubId: Integer;
temp: TIntegerList;
begin
result := LookupSub(S, Level, Upcase);
for I := 0 to UsingList.Count - 1 do
begin
LevelId := UsingList[I];
temp := LookupSub(S, LevelId, upcase);
for J := 0 to temp.Count - 1 do
begin
SubId := temp[J];
if result.IndexOf(SubId) = -1 then
result.Add(SubId);
end;
FreeAndNil(temp);
end;
end;
function TBaseSymbolTable.LookUps(const S: String; LevelStack: TIntegerStack;
UpCase: Boolean;
UpperBoundId: Integer = MaxInt;
Recursive: Boolean = true): Integer;
var
I, R: Integer;
begin
for I:=LevelStack.Count - 1 downto 0 do
begin
R := LookUp(S, LevelStack[I], upcase, UpperBoundId, Recursive);
if R > 0 then
begin
result := R;
Exit;
end;
end;
result := 0;
end;
function TBaseSymbolTable.LookUpsEx(const S: String; LevelStack: TIntegerStack; var LevelId: Integer; UpCase: Boolean): Integer;
var
I, R: Integer;
begin
for I:=LevelStack.Count - 1 downto 0 do
begin
R := LookUp(S, LevelStack[I], upcase, MaxInt);
if R > 0 then
begin
result := R;
LevelId := LevelStack[I];
Exit;
end;
end;
result := 0;
end;
function TBaseSymbolTable.LookUpsExcept(const S: String; LevelStack: TIntegerStack; LevelId: Integer; UpCase: Boolean): Integer;
var
I, R: Integer;
begin
for I:=LevelStack.Count - 1 downto 0 do
begin
if LevelId = LevelStack[I] then
continue;
R := LookUp(S, LevelStack[I], upcase, MaxInt);
if R > 0 then
begin
result := R;
Exit;
end;
end;
result := 0;
end;
function TBaseSymbolTable.LookupAnotherDeclaration(Id: Integer; UpCase: Boolean;
var BestID: Integer): Integer;
var
I, J, Level: Integer;
Name, SignatureEx: String;
Ok: Boolean;
RI: TSymbolRec;
List: TIntegerList;
begin
Level := Records[Id].Level;
Name := Records[Id].Name;
SignatureEx := Records[Id].SignatureEx;
BestId := 0;
List := HashArray.GetList(Name);
for J := List.Count - 1 downto 0 do
begin
I := List[J];
if I = Id then
continue;
RI := Records[I];
if (RI.Level = Level) and
(RI.Kind in kindSUBS) then
begin
if UpCase then
ok := StrEql(RI.Name, Name)
else
ok := (RI.Name = Name);
if ok then
begin
BestId := I;
if UpCase then
ok := StrEql(RI.SignatureEx, SignatureEx)
else
ok := RI.SignatureEx = SignatureEx;
end;
if ok then
begin
result := I;
Exit;
end;
end;
end;
result := 0;
end;
function TBaseSymbolTable.LookupForwardDeclaration(Id: Integer; UpCase: Boolean;
var BestID: Integer): Integer;
var
I, J, Level: Integer;
Name, Sig: String;
Ok: Boolean;
RI: TSymbolRec;
List: TIntegerList;
begin
Level := Records[Id].Level;
Name := Records[Id].Name;
Sig := Records[Id].Sig;
BestId := 0;
List := HashArray.GetList(Name);
for J := List.Count - 1 downto 0 do
begin
I := List[J];
RI := Records[I];
if RI.IsForward and (RI.Level = Level) and
(RI.Kind in kindSUBS) then
begin
if UpCase then
ok := StrEql(RI.Name, Name)
else
ok := (RI.Name = Name);
if ok then
begin
BestId := I;
if UpCase then
ok := StrEql(RI.Sig, Sig)
else
ok := RI.Sig = Sig;
end;
if ok then
begin
result := I;
Exit;
end;
end;
end;
result := 0;
end;
function TBaseSymbolTable.LookupForwardDeclarations(Id: Integer;
UpCase: Boolean): TIntegerList;
var
I, J, Level: Integer;
Ok: Boolean;
Name: String;
R: TSymbolRec;
List: TIntegerList;
begin
result := nil;
Level := Records[Id].Level;
Name := Records[Id].Name;
List := HashArray.GetList(Name);
for J := List.Count - 1 downto 0 do
begin
I := List[J];
R := Records[I];
if R.IsForward and (R.Level = Level) and
(R.Kind in KindSUBS) then
begin
if UpCase then
ok := StrEql(R.Name, Name)
else
ok := (R.Name = Name);
if ok then
begin
if result = nil then
result := TIntegerList.Create;
result.Add(I);
end;
end;
end;
end;
function TBaseSymbolTable.GetDataSize(UpperId: Integer = MaxInt - 1): Integer;
var
I: Integer;
R: TSymbolRec;
K1, K2, KK: Integer;
begin
result := FirstShiftValue;
Inc(UpperId);
for KK := 1 to 2 do
begin
if KK = 1 then
begin
K1 := Types.Count;
if Self.st_tag = 0 then
K2 := Card
else
K2 := TLocalSymbolTable(Self).GlobalST.Card;
end
else
begin
K1 := FirstLocalId + 1;
K2 := Card;
end;
for I := K1 to K2 do
begin
if I = UpperId then
break;
R := Records[I];
if R.UnionId <> 0 then
Continue;
if R.Kind in [KindTYPE, KindTYPE_FIELD, KindLABEL] then
Continue;
if R.OverScript then
begin
Inc(result, SizeOfPointer);
continue;
end;
if (R.Shift > 0) and
(not R.Param) and (not R.Local) and (not R.InternalField) then
begin
if R.Kind = kindSUB then
Inc(result, SizeOfPointer)
else if R.Host then
Inc(result, SizeOfPointer)
{$IFNDEF PAXARM}
else if (R.Kind = KindCONST) and R.HasPAnsiCharType then // literal
begin
Inc(result, SizeOfPointer);
Inc(result, SizeOfPointer);
Inc(result, SizeOfPointer);
Inc(result, Length(R.Value) + 1);
end
{$ENDIF}
else if (R.Kind = KindCONST) and R.HasPWideCharType then // literal
begin
Inc(result, SizeOfPointer);
Inc(result, SizeOfPointer);
Inc(result, Length(R.Value) * 2 + 2);
end
else
Inc(result, R.Size);
end;
end;
end;
end;
function TBaseSymbolTable.GetSizeOfLocals(SubId: Integer): Integer;
var
I: Integer;
R: TSymbolRec;
begin
result := 0;
for I := SubId + 1 to Card do
begin
R := Records[I];
if R.UnionId <> 0 then
Continue;
if (R.Kind = KindVAR) and (R.Level = SubId) and R.Local then
begin
if R.FinalTypeId = typeSET then
Inc(result, SizeOf(TByteSet))
else
Inc(result, MPtr(R.Size));
end;
end;
result := Abs(result);
if Records[SubId].ExtraParamNeeded then
begin
if Records[SubId].CallConv in [ccREGISTER, ccMSFASTCALL] then
begin
if Records[GetResultId(SubId)].Register = 0 then
Dec(result, SizeOfPointer);
end
else
Dec(result, SizeOfPointer);
end;
end;
function TBaseSymbolTable.GetSizeOfLocalsEx(SubId: Integer): Integer;
begin
result := GetSizeOfLocals(SubId);
while (result mod 32 <> 0) do
Inc(result);
end;
function TBaseSymbolTable.GetSubRSPSize(SubId: Integer): Integer;
begin
result := GetSizeOfLocalsEx(SubId);
Inc(result, $150);
while result mod 32 <> 0 do
Inc(result);
Inc(result, 8);
end;
function TBaseSymbolTable.GetSizeOfSetType(SetTypeId: Integer): Integer;
var
FT, OriginTypeId: Integer;
B2: TSymbolRec;
I: Cardinal;
begin
OriginTypeId := Records[SetTypeId].PatternId;
if OriginTypeId <= 1 then
begin
result := 32;
Exit;
end;
FT := Records[OriginTypeId].FinalTypeId;
{
if FT = typeENUM then
begin
result := 1;
Exit;
end;
}
if not (FT in OrdinalTypes) then
begin
result := 32;
Exit;
end;
B2 := GetHighBoundRec(OriginTypeId);
I := B2.Value;
if I < 8 then
result := 1
else if I < 16 then
result := 2
else if I < 32 then
result := 4
else if I < 64 then
result := 8
else if I < 128 then
result := 16
else
result := 32;
end;
function TBaseSymbolTable.CheckSetTypes(T1, T2: Integer): Boolean;
var
P1, P2, F1, F2: Integer;
begin
result := true;
if T2 = H_TByteSet then
Exit;
P1 := Records[T1].PatternId;
P2 := Records[T2].PatternId;
if (P1 > 1) and (P2 > 1) then
begin
F1 := Records[P1].FinalTypeId;
F2 := Records[P2].FinalTypeId;
if F1 <> F2 then
begin
if (F1 in IntegerTypes) and (F2 in IntegerTypes) then
begin
// ok
end
else
result := false;
end
else if (F1 = typeENUM) and (F2 = typeENUM)then
begin
if P1 <> P2 then
if Records[T2].Name <> '$$' then
result := false;
end;
end;
end;
function TBaseSymbolTable.GetLowBoundRec(TypeID: Integer): TSymbolRec;
var
I: Integer;
RI: TSymbolRec;
begin
result := nil;
if Records[TypeID].Kind <> kindTYPE then
begin
RaiseError(errInternalError, []);
Exit;
end;
if Records[TypeID].TypeID = typeALIAS then
TypeID := Records[TypeID].TerminalTypeId;
case Records[TypeID].FinalTypeId of
typeBOOLEAN, typeBYTEBOOL, typeWORDBOOL, typeLONGBOOL:
begin
result := Records[FalseId];
Exit;
end;
typeINTEGER,
{$IFNDEF PAXARM}
typeANSICHAR,
{$ENDIF}
typeBYTE, typeWORD, typeCARDINAL,
typeSMALLINT, typeSHORTINT, typeWIDECHAR,
typeINT64:
begin
for I:=TypeID + 1 to Card do
begin
RI := Records[I];
if RI = SR0 then
break;
if RI.Level = TypeID then
begin
result := RI;
Exit;
end;
end;
end;
typeENUM:
begin
if Records[TypeID].IsSubrangeEnumType then
begin
result := Records[TypeID + 1];
Exit;
end;
for I:=TypeID + 1 to Card do
begin
RI := Records[I];
if RI = SR0 then
break;
if RI.OwnerId = TypeID then
begin
result := RI;
Exit;
end;
end;
end;
else
begin
RaiseError(errInternalError, []);
Exit;
end;
end;
RaiseError(errInternalError, []);
end;
function TBaseSymbolTable.GetHighBoundRec(TypeID: Integer): TSymbolRec;
var
I, J: Integer;
RI: TSymbolRec;
begin
result := nil;
if Records[TypeID].TypeID = typeALIAS then
TypeID := Records[TypeID].TerminalTypeId;
case Records[TypeID].FinalTypeId of
typeBOOLEAN, typeBYTEBOOL, typeWORDBOOL, typeLONGBOOL:
begin
result := Records[TrueId];
Exit;
end;
typeINTEGER,
{$IFNDEF PAXARM}
typeANSICHAR,
{$ENDIF}
typeBYTE, typeWORD, typeCARDINAL,
typeSMALLINT, typeSHORTINT, typeWIDECHAR,
typeINT64:
begin
for I:=GetLowBoundRec(TypeID).Id + 1 to Card do
begin
RI := Records[I];
if RI = SR0 then
break;
if RI.Level = TypeID then
begin
result := RI;
Exit;
end;
end;
end;
typeENUM:
begin
if Records[TypeID].IsSubrangeEnumType then
begin
result := Records[TypeID + 2];
Exit;
end;
J := Records[TypeID].Count;
for I:=TypeID + 1 to Card do
begin
RI := Records[I];
if RI = SR0 then
break;
if RI.Kind = KindCONST then
if RI.OwnerId = TypeID then
begin
result := RI;
Dec(J);
if J = 0 then Break;
end;
end;
Exit;
end;
else
begin
RaiseError(errInternalError, []);
Exit;
end;
end;
RaiseError(errInternalError, []);
end;
{$IFNDEF PAXARM}
function TBaseSymbolTable.IsZeroBasedAnsiCharArray(Id: Integer): Boolean;
var
ArrayTypeId, RangeTypeId, ElemTypeId: Integer;
begin
if Records[Id].FinalTypeId <> typeARRAY then
begin
result := false;
Exit;
end;
ArrayTypeId := Records[Id].TerminalTypeId;
GetArrayTypeInfo(ArrayTypeId, RangeTypeId, ElemTypeId);
result := (Records[ElemTypeId].FinalTypeId = typeANSICHAR) and
(GetLowBoundRec(RangeTypeId).Value = 0);
end;
{$ENDIF}
function TBaseSymbolTable.IsZeroBasedWideCharArray(Id: Integer): Boolean;
var
ArrayTypeId, RangeTypeId, ElemTypeId: Integer;
begin
if Records[Id].FinalTypeId <> typeARRAY then
begin
result := false;
Exit;
end;
ArrayTypeId := Records[Id].TerminalTypeId;
GetArrayTypeInfo(ArrayTypeId, RangeTypeId, ElemTypeId);
result := (Records[ElemTypeId].FinalTypeId = typeWIDECHAR) and
(GetLowBoundRec(RangeTypeId).Value = 0);
end;
procedure TBaseSymbolTable.GetArrayTypeInfo(ArrayTypeId: Integer; var RangeTypeId: Integer;
var ElemTypeId: Integer);
var
I, K: Integer;
begin
if Records[ArrayTypeID].TypeID = typeALIAS then
ArrayTypeID := Records[ArrayTypeID].TerminalTypeId;
if Records[ArrayTypeID].ReadId <> 0 then
begin
RangeTypeId := Records[ArrayTypeID].ReadId;
ElemTypeId := Records[ArrayTypeID].WriteId;
Exit;
end;
ElemTypeId := 0;
RangeTypeId := 0;
K := Card;
if Self.st_tag > 0 then
if ArrayTypeId < TLocalSymbolTable(Self).GlobalST.Card then
begin
K := TLocalSymbolTable(Self).GlobalST.Card;
end;
for I:=ArrayTypeId + 1 to K do
if Records[I].Level = ArrayTypeId then
if Records[I].Kind = KindTYPE then
begin
RangeTypeId := I;
break;
end;
for I:=K downto ArrayTypeId + 1 do
if Records[I].Level = ArrayTypeId then
if Records[I].Kind = KindTYPE then
begin
ElemTypeId := I;
break;
end;
if (RangeTypeId = 0) or (ElemTypeId = 0) then
Begin
RaiseError(errInternalError, []);
Exit;
end;
if Records[RangeTypeId].TypeID = typeALIAS then
RangeTypeId := Records[RangeTypeId].TerminalTypeId;
if Records[ElemTypeId].TypeID = typeALIAS then
ElemTypeId := Records[ElemTypeId].TerminalTypeId;
Records[ArrayTypeID].ReadId := RangeTypeId;
Records[ArrayTypeID].WriteId := ElemTypeId;
end;
function TBaseSymbolTable.GetTypeBase(TypeId: Integer): Integer;
begin
result := Records[TypeId].PatternId;
end;
function TBaseSymbolTable.GetPatternSubId(ProcTypeID: Integer): Integer;
begin
result := Records[ProcTypeID].PatternId;
end;
function TBaseSymbolTable.EqualHeaders(SubId1, SubId2: Integer): Boolean;
function CompareTypes(T1, T2: Integer): Boolean;
var
F1, F2: Integer;
begin
result := false;
F1 := Records[T1].FinalTypeId;
F2 := Records[T2].FinalTypeId;
if F1 <> F2 then
Exit;
if F1 = typeDYNARRAY then
begin
T1 := Records[T1].TerminalTypeId;
T2 := Records[T2].TerminalTypeId;
T1 := Records[T1].PatternId;
T2 := Records[T2].PatternId;
result := CompareTypes(T1, T2);
Exit;
end;
result := true;
end;
var
I: Integer;
begin
result := false;
if not CompareTypes(Records[SubId1].TypeId, Records[SubId2].TypeId) then
Exit;
if Records[SubId1].Count <> Records[SubId2].Count then
Exit;
for I:=0 to Records[SubId1].Count - 1 do
if not CompareTypes(Records[GetParamId(SubId1, I)].TypeID, Records[GetParamId(SubId2, I)].TypeID) then
Exit;
result := true;
end;
procedure TBaseSymbolTable.CheckError(B: Boolean);
begin
if B then
RaiseError(errInternalError, []);
end;
procedure TBaseSymbolTable.RaiseError(const Message: string; params: array of Const);
var
I: Integer;
begin
if RaiseE then
begin
raise Exception.Create(Format(Message, params));
end
else
begin
if LastCard > 0 then
for I:= LastCard + 1 to Card do
Records[I].Name := '';
REG_ERROR := Format(Message, params);
REG_OK := false;
if Message = errUndeclaredIdentifier then
REG_ERROR := '';
end;
end;
function TBaseSymbolTable.GetShiftsOfDynamicFields(ATypeId: Integer): TIntegerList;
procedure GetArrayShifts(TypeID: Integer; S: Integer); forward;
procedure GetRecordShifts(TypeID: Integer; S: Integer);
var
I, T, T1: Integer;
RI: TSymbolRec;
begin
for I:=TypeId + 1 to Card do
begin
RI := Records[I];
if RI = SR0 then
break;
if (RI.Kind = KindTYPE_FIELD) and (RI.Level = TypeId) then
begin
T := RI.FinalTypeId;
case T of
{$IFNDEF PAXARM}
typeANSISTRING, typeWIDESTRING,
{$ENDIF}
typeUNICSTRING, typeDYNARRAY, typeVARIANT, typeOLEVARIANT:
result.Add(RI.Shift + S);
typeCLASS:
result.Add(RI.Shift + S);
typeRECORD:
begin
T1 := TerminalTypeOf(RI.TypeID);
GetRecordShifts(T1, RI.Shift);
end;
typeARRAY:
begin
T1 := TerminalTypeOf(RI.TypeID);
GetArrayShifts(T1, RI.Shift);
end;
end;
end;
end;
end;
procedure GetArrayShifts(TypeID: Integer; S: Integer);
var
RangeTypeId, ElemTypeId, H1, H2, T, I, ElemSize, P: Integer;
begin
GetArrayTypeInfo(TypeId, RangeTypeId, ElemTypeId);
H1 := GetLowBoundRec(RangeTypeId).Value;
H2 := GetHighBoundRec(RangeTypeId).Value;
ElemSize := Records[ElemTypeId].Size;
T := Records[ElemTypeId].FinalTypeId;
case T of
{$IFNDEF PAXARM}
typeANSISTRING, typeWIDESTRING,
{$ENDIF}
typeUNICSTRING, typeDYNARRAY, typeVARIANT, typeOLEVARIANT:
begin
P := S;
for I:=0 to H2 - H1 do
begin
result.Add(P);
Inc(P, SizeOfPointer);
end;
end;
typeCLASS:
begin
P := S;
for I:=0 to H2 - H1 do
begin
result.Add(P);
Inc(P, SizeOfPointer);
end;
end;
typeRECORD:
begin
P := S;
for I:=0 to H2 - H1 do
begin
TypeID := TerminalTypeOf(ElemTypeId);
GetRecordShifts(TypeId, P);
Inc(P, ElemSize);
end;
end;
typeARRAY:
begin
P := S;
for I:=0 to H2 - H1 do
begin
TypeID := TerminalTypeOf(ElemTypeId);
GetArrayShifts(TypeId, P);
Inc(P, ElemSize);
end;
end;
end;
end;
var
T: Integer;
begin
result := TIntegerList.Create;
T := Records[ATypeId].FinalTypeId;
case T of
typeRECORD: GetRecordShifts(ATypeId, 0);
typeARRAY: GetArrayShifts(ATypeId, 0);
end;
end;
function TBaseSymbolTable.GetTypesOfDynamicFields(ATypeId: Integer): TIntegerList;
procedure GetArrayTypes(TypeID: Integer); forward;
procedure GetRecordTypes(TypeID: Integer);
var
I, T, T1: Integer;
RI: TSymbolRec;
begin
for I:=TypeId + 1 to Card do
begin
RI := Records[I];
if RI = SR0 then
break;
if (RI.Kind = KindTYPE_FIELD) and (RI.Level = TypeId) then
begin
T := RI.FinalTypeId;
case T of
{$IFNDEF PAXARM}
typeANSISTRING, typeWIDESTRING,
{$ENDIF}
typeUNICSTRING, typeDYNARRAY, typeVARIANT, typeOLEVARIANT:
result.Add(RI.TerminalTypeId);
typeCLASS:
result.Add(RI.TerminalTypeId);
typeRECORD:
begin
T1 := TerminalTypeOf(RI.TypeID);
GetRecordTypes(T1);
end;
typeARRAY:
begin
T1 := TerminalTypeOf(RI.TypeID);
GetArrayTypes(T1);
end;
end;
end;
end;
end;
procedure GetArrayTypes(TypeID: Integer);
var
RangeTypeId, ElemTypeId, H1, H2, T, I: Integer;
begin
GetArrayTypeInfo(TypeId, RangeTypeId, ElemTypeId);
H1 := GetLowBoundRec(RangeTypeId).Value;
H2 := GetHighBoundRec(RangeTypeId).Value;
T := Records[ElemTypeId].FinalTypeId;
case T of
{$IFNDEF PAXARM}
typeANSISTRING, typeWIDESTRING,
{$ENDIF}
typeUNICSTRING, typeDYNARRAY, typeVARIANT, typeOLEVARIANT:
for I:=0 to H2 - H1 do
result.Add(Records[ElemTypeId].TerminalTypeId);
typeRECORD:
begin
for I:=0 to H2 - H1 do
begin
TypeID := TerminalTypeOf(ElemTypeId);
GetRecordTypes(TypeId);
end;
end;
typeCLASS:
begin
for I:=0 to H2 - H1 do
result.Add(Records[ElemTypeId].TerminalTypeId);
end;
typeARRAY:
for I:=0 to H2 - H1 do
begin
TypeID := TerminalTypeOf(ElemTypeId);
GetArrayTypes(TypeId);
end;
end;
end;
begin
result := TIntegerList.Create;
case Records[ATypeId].FinalTypeId of
typeRECORD: GetRecordTypes(ATypeId);
typeARRAY: GetArrayTypes(ATypeId);
end;
end;
function TBaseSymbolTable.HasDynamicFields(ATypeId: Integer): Boolean;
var
L: TIntegerList;
begin
L := GetShiftsOfDynamicFields(ATypeID);
result := L.Count > 0;
FreeAndNil(L);
end;
function TBaseSymbolTable.TerminalTypeOf(TypeID: Integer): Integer;
begin
result := TypeID;
if Records[result].TypeID = typeALIAS then
result := Records[result].TerminalTypeId;
end;
function TBaseSymbolTable.FindDefaultPropertyId(i_TypeId: Integer): Integer;
var
I: Integer;
RI: TSymbolRec;
begin
for I:=i_TypeId + 1 to Card do
begin
RI := Records[I];
if RI = SR0 then
break;
if RI.Kind = KindNAMESPACE then
break;
with RI do
if (Kind = kindPROP) and (Level = i_TypeId) and IsDefault then
begin
result := I;
Exit;
end;
end;
if Records[i_TypeId].AncestorId > 0 then
result := FindDefaultPropertyId(Records[i_TypeId].AncestorId)
else
result := 0;
end;
function TBaseSymbolTable.FindConstructorId(i_TypeId: Integer): Integer;
var
I, temp: Integer;
RI: TSymbolRec;
begin
temp := 0;
for I:=i_TypeId + 1 to Card do
begin
RI := Records[I];
if RI = SR0 then
break;
if RI.Kind = KindNAMESPACE then
break;
with RI do
if (Kind = kindCONSTRUCTOR) and (Level = i_TypeId) then
begin
if StrEql(RI.Name, 'Create') then
begin
result := I;
Exit;
end
else
temp := I;
end;
end;
result := temp;
if result = 0 then
if Records[i_TypeId].Host then
begin
if i_TypeId = H_TObject then
Exit;
i_TypeId := Records[i_TypeId].AncestorId;
if I_typeId = 0 then
Exit;
result := FindConstructorId(i_TypeId);
end;
end;
function TBaseSymbolTable.FindConstructorIdEx(i_TypeId: Integer): Integer;
begin
result := FindConstructorId(I_TypeId);
if result = 0 then
if Records[i_TypeId].AncestorId <> 0 then
result := FindConstructorIdEx(Records[i_TypeId].AncestorId);
end;
function TBaseSymbolTable.FindConstructorIds(i_TypeId: Integer): TIntegerList;
var
I: Integer;
RI: TSymbolRec;
begin
result := TIntegerList.Create;
for I:=i_TypeId + 1 to Card do
begin
RI := Records[I];
if RI = SR0 then
break;
if RI.Kind = KindNAMESPACE then
break;
with RI do
if (Kind = kindCONSTRUCTOR) and (Level = i_TypeId) then
begin
result.Add(I);
end;
end;
end;
function TBaseSymbolTable.FindDestructorId(i_TypeId: Integer): Integer;
var
I: Integer;
RI: TSymbolRec;
begin
for I:=i_TypeId + 1 to Card do
begin
RI := Records[I];
if RI = SR0 then
break;
with RI do
if (Kind = kindDESTRUCTOR) and (Level = i_TypeId) then
begin
result := I;
Exit;
end;
end;
result := 0;
end;
function TBaseSymbolTable.FindDestructorIdEx(i_TypeId: Integer): Integer;
begin
result := FindDestructorId(i_TypeId);
if result = 0 then
if Records[i_TypeId].AncestorId <> 0 then
result := FindDestructorIdEx(Records[i_TypeId].AncestorId);
end;
function TBaseSymbolTable.Inherits(T1, T2: Integer): Boolean;
begin
T1 := Records[T1].TerminalTypeId;
T2 := Records[T2].TerminalTypeId;
result := (T1 = T2);
if not result then
result := Records[T1].Inherits(T2);
end;
function TBaseSymbolTable.Supports(T1, T2: Integer): Boolean;
var
I: Integer;
GuidList: TGuidList;
begin
T1 := Records[T1].TerminalTypeId;
T2 := Records[T2].TerminalTypeId;
result := (T1 = T2);
if result then
Exit;
if T2 = H_IUnknown then
begin
result := true;
Exit;
end;
GuidList := Records[T1].SupportedInterfaces;
if GuidList = nil then
begin
result := false;
Exit;
end;
if GuidList.HasId(T2) then
begin
result := true;
Exit;
end;
for I:=0 to GuidList.Count - 1 do
if Supports(GuidList[I].Id, T2) then
begin
result := true;
Exit;
end;
end;
function TBaseSymbolTable.RegisterDummyType(LevelId: Integer;
const TypeName: String): Integer;
begin
result := LookupType(TypeName, LevelId, true);
if result > 0 then
Exit;
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeVOID;
Host := true;
Shift := 0;
Level := LevelId;
IsDummyType := true;
result := Id;
end;
end;
function TBaseSymbolTable.RegisterSomeType(LevelId: Integer;
const TypeName: String): Integer;
begin
with AddRecord do
begin
Name := TypeName;
Kind := KindTYPE;
TypeID := typeVOID;
Host := true;
Shift := 0;
Level := LevelId;
result := Id;
end;
SomeTypeList.Add(TypeName, result);
end;
function TBaseSymbolTable.GetLocalCount(SubId: Integer): Integer;
var
I, SelfId: Integer;
RI: TSymbolRec;
begin
result := 0;
SelfId := GetSelfId(SubId);
for I:=SubId + 1 to Card do
begin
RI := Self[I];
if RI.Level = SubId then
if RI.Kind = KindVAR then
if RI.OwnerId = 0 then
if RI.PatternId = 0 then
if RI.Local then
begin
if RI.Name <> '' then
if RI.Name <> '@' then
Inc(result);
end
else if I = SelfId then
begin
if RI.Name <> '' then
Inc(result);
end;
if RI.Kind = kindNAMESPACE then
break;
end;
end;
function TBaseSymbolTable.IsLocalOf(Id, SubId: Integer): Boolean;
var
RI: TSymbolRec;
begin
result := false;
RI := Records[Id];
if RI.Param then
Exit;
if RI.Level = SubId then
if RI.Kind = KindVAR then
if RI.OwnerId = 0 then
if RI.PatternId = 0 then
if RI.Local then
begin
if RI.Name <> '' then
if RI.Name <> '@' then
result := true;
end
else if Id = GetSelfId(SubId) then
begin
if RI.Name <> '' then
result := true;
end;
end;
function TBaseSymbolTable.GetLocalId(SubId, LocalVarNumber: Integer): Integer;
var
I, K, SelfId: Integer;
RI: TSymbolRec;
begin
K := -1;
SelfId := GetSelfId(SubId);
for I:=SubId + 1 to Card do
begin
RI := Self[I];
if RI.Level = SubId then
if RI.Kind = KindVAR then
if RI.OwnerId = 0 then
if RI.PatternId = 0 then
if RI.Local then
begin
if RI.Name <> '' then
if RI.Name <> '@' then
begin
Inc(K);
if K = LocalVarNumber then
begin
result := I;
Exit;
end;
end;
end
else if I = SelfId then
begin
if RI.Name <> '' then
begin
Inc(K);
if K = LocalVarNumber then
begin
result := I;
Exit;
end;
end;
end;
end;
result := 0;
RaiseError(errInvalidIndex, [LocalVarNumber]);
end;
function TBaseSymbolTable.IsParam(SubId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := (R.Level = SubId) and
R.Param and
(GetSelfId(SubId) <> Id);
end;
function TBaseSymbolTable.IsVar(LevelId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
if Self[LevelId].Kind = KindSUB then
if GetSelfId(LevelId) = Id then
begin
result := (Self[Id].Name <> '') and (not Self[Id].Param);
Exit;
end;
result := false;
R := Self[Id];
if R.Param then
Exit;
if R.TypedConst then
Exit;
if R.Level = LevelId then
if R.Kind = KindVAR then
if R.OwnerId = 0 then
if R.Name <> '' then
if R.Name <> '@' then
result := true;
end;
function TBaseSymbolTable.IsConst(LevelId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := ((R.Kind = KindCONST) and (R.Level = LevelId) and
(R.Name <> ''))
or
R.TypedConst;
end;
function TBaseSymbolTable.IsType(LevelId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := (R.Kind = KindTYPE) and (R.Level = LevelId) and
(R.Name <> '');
end;
function TBaseSymbolTable.IsNamespace(LevelId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := (R.Kind = KindNAMESPACE) and (R.Level = LevelId);
end;
function TBaseSymbolTable.IsTypeField(LevelId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := (R.Kind = KindTYPE_FIELD) and (R.Level = LevelId);
end;
function TBaseSymbolTable.IsEnumMember(LevelId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := (R.Kind = KindCONST) and (R.OwnerId = LevelId);
end;
function TBaseSymbolTable.IsProperty(ClassId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := (R.Kind = KindPROP) and (R.Level = ClassId);
end;
function TBaseSymbolTable.IsProcedure(LevelId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := (R.Kind = KindSUB) and (R.Level = LevelId) and
(R.FinalTypeId = typeVOID);
if result then
result := Self[Id].Name <> '';
end;
function TBaseSymbolTable.IsFunction(LevelId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := (R.Kind = KindSUB) and (R.Level = LevelId) and
(R.FinalTypeId <> typeVOID);
if result then
result := Self[Id].Name <> '';
end;
function TBaseSymbolTable.IsConstructor(ClassId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := (R.Kind = KindCONSTRUCTOR) and
(R.Level = ClassId);
end;
function TBaseSymbolTable.IsDestructor(ClassId, Id: Integer): Boolean;
var
R: TSymbolRec;
begin
R := Self[Id];
result := (R.Kind = KindDESTRUCTOR) and
(R.Level = ClassId);
end;
function TBaseSymbolTable.GetGlobalCount(NamespaceId: Integer): Integer;
var
I: Integer;
RI: TSymbolRec;
begin
result := 0;
for I:=NamespaceId + 1 to Card do
begin
RI := Self[I];
if RI.Host then
continue;
if RI.Level = NamespaceId then
if RI.OwnerId = 0 then
if RI.IsGlobalVar then
if RI.Name <> '' then
if RI.Name <> '@' then
Inc(result);
end;
end;
function TBaseSymbolTable.GetGlobalId(NamespaceId, GlobalVarNumber: Integer): Integer;
var
I, K: Integer;
RI: TSymbolRec;
begin
K := -1;
for I:=NamespaceId + 1 to Card do
begin
RI := Self[I];
if RI.Host then
continue;
if RI.Level = NamespaceId then
if RI.OwnerId = 0 then
if RI.IsGlobalVar then
if RI.Name <> '' then
if RI.Name <> '@' then
begin
Inc(K);
if K = GlobalVarNumber then
begin
result := I;
Exit;
end;
end;
end;
result := 0;
RaiseError(errInvalidIndex, [GlobalVarNumber]);
end;
function TBaseSymbolTable.GetFieldCount(Id: Integer; TypeMapRec: TTypeMapRec = nil): Integer;
var
T, FinTypeId, I: Integer;
R: TSymbolRec;
begin
result := 0;
if Id = 0 then
Exit;
FinTypeId := Self[Id].FinalTypeId;
if FinTypeId = typeCLASS then
begin
if TypeMapRec <> nil then
if TypeMapRec.Completed then
begin
result := TypeMapRec.Fields.Count;
Exit;
end;
T := Self[Id].TerminalTypeId;
for I:=T + 1 to Card do
begin
R := Self[I];
if (R.Level = T) and (R.Kind = KindTYPE_FIELD) then
begin
Inc(result);
if TypeMapRec <> nil then
TypeMapRec.Fields.Add(I);
end
else if R.Kind = kindNAMESPACE then
break;
end;
Inc(result, GetFieldCount(Self[T].AncestorId, TypeMapRec));
end
else if FinTypeId = typeRECORD then
begin
// Added by Oberon
if TypeMapRec <> nil then
if TypeMapRec.Completed then
begin
result := TypeMapRec.Fields.Count;
Exit;
end;
// end oberon
T := Self[Id].TerminalTypeId;
for I:=T + 1 to Card do
begin
R := Self[I];
if (R.Level = T) and (R.Kind = KindTYPE_FIELD) then
begin
Inc(result);
if TypeMapRec <> nil then
TypeMapRec.Fields.Add(I);
end
else if R.Kind = kindNAMESPACE then
break;
end;
end;
end;
function TBaseSymbolTable.GetPublishedPropCount(Id: Integer): Integer;
var
T, FinTypeId, I: Integer;
R: TSymbolRec;
begin
result := 0;
if Id = 0 then
Exit;
FinTypeId := Self[Id].FinalTypeId;
if FinTypeId = typeCLASS then
begin
T := Self[Id].TerminalTypeId;
while not Self[T].Host do
T := Self[T].AncestorId;
for I:=T + 1 to Card do
begin
R := Self[I];
if (R.Level = T) and (R.Kind = KindPROP) and
R.IsPublished and
(not (R.FinalTypeId in [typeEVENT, typeRECORD])) then
Inc(result)
else if R.Kind = kindNAMESPACE then
break;
end;
end
else
Exit;
end;
function TBaseSymbolTable.GetPublishedPropDescriptorId(Id, PropNumber: Integer): Integer;
var
T, FinTypeId, I: Integer;
R: TSymbolRec;
begin
result := 0;
if Id = 0 then
Exit;
FinTypeId := Self[Id].FinalTypeId;
if FinTypeId = typeCLASS then
begin
T := Self[Id].TerminalTypeId;
while not Self[T].Host do
T := Self[T].AncestorId;
result := -1;
for I:=T + 1 to Card do
begin
R := Self[I];
if (R.Level = T) and (R.Kind = KindPROP) and
R.IsPublished and
(not (R.FinalTypeId in [typeEVENT, typeRECORD])) then
begin
Inc(result);
if result = PropNumber then
begin
result := I;
Exit;
end;
end
else if R.Kind = kindNAMESPACE then
break;
end;
end
else
RaiseError(errClassTypeRequired, []);
end;
function TBaseSymbolTable.GetPublishedPropName(Id, PropNumber: Integer): String;
var
PropDescriptorId: Integer;
begin
PropDescriptorId := GetPublishedPropDescriptorId(Id, PropNumber);
result := Self[PropDescriptorId].Name;
end;
function TBaseSymbolTable.GetPublishedPropValueAsString(P: Pointer; StackFrameNumber: Integer;
Id, PropNumber: Integer): String;
var
OwnerAddress: Pointer;
TypeId, PropDescriptorId: Integer;
X: TObject;
PropName: String;
V: Variant;
begin
try
TypeId := Self[Id].TerminalTypeId;
PropDescriptorId := GetPublishedPropDescriptorId(TypeId, PropNumber);
OwnerAddress := GetFinalAddress(P, StackFrameNumber, Id);
if OwnerAddress = nil then
result := errError
else
begin
X := TObject(OwnerAddress^);
if X = nil then
result := errError
else
begin
if X = nil then
result := errError
else
begin
PropName := Records[PropDescriptorId].Name;
if GetPropInfo(X, PropName) = nil then
result := errError
else
begin
V := GetPropValue(X, PropName, true);
result := VarToStr(V);
end;
end;
end;
end;
except
result := errError;
end;
end;
function TBaseSymbolTable.GetFieldDescriptorId(Id,
FieldNumber: Integer;
TypeMapRec: TTypeMapRec = nil
): Integer;
var
T, FinTypeId, I, J, K: Integer;
R: TSymbolRec;
L: TIntegerList;
begin
result := 0;
FinTypeId := Self[Id].FinalTypeId;
if FinTypeId = typeCLASS then
begin
T := Self[Id].TerminalTypeId;
if TypeMapRec <> nil then
if TypeMapRec.TypeId = T then
if TypeMapRec.Completed then
begin
result := TypeMapRec.Fields[FieldNumber];
Exit;
end;
L := TIntegerList.Create;
try
L.Add(T);
T := Self[T].AncestorId;
while T <> 0 do
begin
L.Insert(0, T);
T := Self[T].AncestorId;
end;
K := -1;
for I:=0 to L.Count - 1 do
begin
T := L[I];
for J:=T + 1 to Card do
begin
R := Self[J];
if (R.Level = T) and (R.Kind = KindTYPE_FIELD) then
begin
Inc(K);
if K = FieldNumber then
begin
result := J;
Exit;
end;
end;
end;
end;
finally
FreeAndNil(L);
end;
end
else if FinTypeId = typeRECORD then
begin
T := Self[Id].TerminalTypeId;
if TypeMapRec <> nil then
if TypeMapRec.TypeId = T then
if TypeMapRec.Completed then
begin
result := TypeMapRec.Fields[FieldNumber];
Exit;
end;
K := -1;
for J:=T + 1 to Card do
begin
R := Self[J];
if (R.Level = T) and (R.Kind = KindTYPE_FIELD) then
begin
Inc(K);
if K = FieldNumber then
begin
result := J;
Exit;
end;
end;
end;
end;
end;
function TBaseSymbolTable.GetFieldDescriptorIdByName(Id: Integer; const FieldName: String): Integer;
var
T, FinTypeId, I, J: Integer;
R: TSymbolRec;
L: TIntegerList;
begin
result := 0;
FinTypeId := Self[Id].FinalTypeId;
if FinTypeId = typeCLASS then
begin
T := Self[Id].TerminalTypeId;
L := TIntegerList.Create;
try
L.Add(T);
T := Self[T].AncestorId;
while T <> 0 do
begin
L.Insert(0, T);
T := Self[T].AncestorId;
end;
for I:=0 to L.Count - 1 do
begin
T := L[I];
for J:=T + 1 to Card do
begin
R := Self[J];
if (R.Level = T) and (R.Kind = KindTYPE_FIELD) then
begin
if StrEql(R.Name, FieldName) then
begin
result := J;
Exit;
end;
end;
end;
end;
finally
FreeAndNil(L);
end;
end
else if FinTypeId = typeRECORD then
begin
T := Self[Id].TerminalTypeId;
for J:=T + 1 to Card do
begin
R := Self[J];
if (R.Level = T) and (R.Kind = KindTYPE_FIELD) then
begin
if StrEql(R.Name, FieldName) then
begin
result := J;
Exit;
end;
end;
end;
end;
end;
function TBaseSymbolTable.GetFieldName(Id, FieldNumber: Integer): String;
var
FieldDescriptorId: Integer;
begin
FieldDescriptorId := GetFieldDescriptorId(Id, FieldNumber);
result := Self[FieldDescriptorId].Name;
end;
function TBaseSymbolTable.GetFieldAddress(P: Pointer;
StackFrameNumber,
Id,
FieldNumber: Integer;
TypeMapRec: TTypeMapRec = nil
): Pointer;
var
FieldDescriptorId, Shift: Integer;
X: TObject;
begin
result := GetFinalAddress(P, StackFrameNumber, Id);
try
CheckMemory(Result, sizeof (TObject));
if Self[Id].FinalTypeId = typeCLASS then
begin
X := TObject(result^);
if X = nil then
begin
result := nil;
Exit;
end;
{$IFNDEF FPC}
CheckMemory (pointer (integer (pointer (X)^) + vmtSelfPtr), - vmtSelfPtr);
if pointer (pointer (integer (pointer (X)^) + vmtSelfPtr)^) <> pointer(pointer (X)^) then
raise EAbort.Create (errNotValidObject);
{$ENDIF}
result := Pointer(X);
end;
except
result := nil;
end;
if result = nil then
Exit;
FieldDescriptorId := GetFieldDescriptorId(Id, FieldNumber, TypeMapRec);
Shift := Self[FieldDescriptorId].Shift;
result := ShiftPointer(result, Shift);
end;
function TBaseSymbolTable.GetStrVal(Address: Pointer;
TypeId: Integer;
TypeMapRec: TTypeMapRec = nil;
BriefCls: Boolean = false): String;
var
B: Byte;
W: Word;
X: TObject;
C: TClass;
P: Pointer;
V: Variant;
FinTypeId: Integer;
I, K: Integer;
FieldAddress: Pointer;
FieldDescriptorId, FieldTypeId, FieldShift: Integer;
RangeTypeId, ElemTypeId, K1, K2: Integer;
ByteSet: TByteSet;
EnumNames: TStringList;
begin
FinTypeId := Self[TypeId].FinalTypeId;
if TypeMapRec <> nil then
if TypeMapRec.TypeId <> TypeId then
TypeMapRec := nil;
try
case FinTypeId of
typeBOOLEAN, typeBYTEBOOL, typeWORDBOOL, typeLONGBOOL:
begin
CheckMemory(Address, sizeof(Byte));
B := Byte(Address^);
if B <> 0 then
result := 'true'
else
result := 'false';
end;
typeBYTE, typeENUM:
begin
CheckMemory(Address, SizeOf(Byte));
B := Byte(Address^);
result := IntToStr(B);
end;
{$IFNDEF PAXARM}
typeANSICHAR:
begin
CheckMemory(Address, SizeOf(Byte));
B := Byte(Address^);
result := String(AnsiChar(B));
end;
typeWIDESTRING:
begin
CheckMemory (Address, sizeof (WideString));
if pointer (Address^) <> nil then
begin
// First check to be able to length if WideString in bytes
CheckMemory(pointer(integer(Address^) - SizeOf(LongInt)), SizeOf(LongInt));
// Let's check if contents are accesible
I := Integer(pointer(integer(Address^) - SizeOf(LongInt))^);
// I contains length of string in bytes
if I = 0 then
begin
result := '';
Exit;
end;
CheckMemory (pointer(Address^), I + SizeOf (WideChar)); // One extra WideChar for #0
result := WideString(Address^);
end
else Result := '';
end;
typeANSISTRING:
begin
// Check pointer to string
CheckMemory (Address, sizeof (AnsiString));
if pointer (Address^) <> nil then
begin
// First check to be able to access length of string and the ref count integer
CheckMemory(pointer(integer(Address^) - SizeOf(LongInt) * 2), SizeOf(LongInt) * 2);
// Let's check if contents are accesible
I := Integer(pointer(integer(Address^) - SizeOf(LongInt))^);
// I contains length of string
if I = 0 then
begin
result := '';
Exit;
end;
CheckMemory (pointer(Address^), I + 1);
result := String(AnsiString(Address^));
end
else
begin
result := '';
Exit;
end;
end;
typeSHORTSTRING:
begin
CheckMemory (Address, sizeof (ShortString));
result := String(ShortString(Address^));
end;
{$ENDIF}
typeSET:
begin
CheckMemory(Address, SizeOf(TByteSet));
TypeId := Self[TypeId].PatternId;
FinTypeId := Self[TypeId].FinalTypeId;
if FinTypeId = typeENUM then
EnumNames := ExtractEnumNames(TypeId)
else
EnumNames := nil;
ByteSet := UpdateSet(TByteSet(Address^), Self[TypeId].Size);
result := ByteSetToString(ByteSet, FinTypeId, EnumNames);
if EnumNames <> nil then
FreeAndNil(EnumNames);
end;
typeINTEGER:
begin
CheckMemory(Address, SizeOf(LongInt));
result := IntToStr(Integer(Address^));
end;
typeCARDINAL:
begin
CheckMemory(Address, SizeOf(Cardinal));
result := IntToStr(Cardinal(Address^));
end;
typeSMALLINT:
begin
CheckMemory (Address, sizeof(SmallInt));
result := IntToStr(SmallInt(Address^));
end;
typeSHORTINT:
begin
CheckMemory (Address, sizeof (ShortInt));
result := IntToStr(ShortInt(Address^));
end;
typeEVENT:
begin
FieldTypeId := typePOINTER;
FieldShift := SizeOfPointer;
FieldAddress := Address;
result := Self[TypeId].Name + '(';
result := result + GetStrVal(FieldAddress, FieldTypeId);
result := result + ',';
FieldAddress := ShiftPointer(Address, FieldShift);
result := result + GetStrVal(FieldAddress, FieldTypeId);
result := result + ')';
end;
typeRECORD:
begin
result := Self[TypeId].Name + '(';
K := GetFieldCount(TypeId, TypeMapRec);
for I:=0 to K - 1 do
begin
FieldDescriptorId := GetFieldDescriptorId(TypeId, I, TypeMapRec);
FieldTypeId := Self[FieldDescriptorId].TypeId;
FieldShift := Self[FieldDescriptorId].Shift;
FieldAddress := ShiftPointer(Address, FieldShift);
result := result + GetStrVal(FieldAddress, FieldTypeId);
if I < K - 1 then
result := result + ',';
end;
result := result + ')';
end;
typeCLASS:
begin
// Check pointer to object
CheckMemory (Address, sizeof (TObject));
X := TObject(Address^);
if Assigned(X) then
begin
if X is TGC_Object then
begin
result := TGC_Object(X).__toString;
Exit;
end;
if BriefCls then
begin
result := Self[TypeId].Name +
'(' + Format('0x%x', [Cardinal(Address^)]) + ')';
Exit;
end;
result := Self[TypeId].Name + '(';
K := GetFieldCount(TypeId, TypeMapRec);
for I:=0 to K - 1 do
begin
FieldDescriptorId := GetFieldDescriptorId(TypeId, I, TypeMapRec);
FieldTypeId := Self[FieldDescriptorId].TypeId;
FieldShift := Self[FieldDescriptorId].Shift;
{$IFNDEF FPC}
// Check VMT for readability and to see if it's a true VMT
CheckMemory (pointer (integer (pointer (X)^) + vmtSelfPtr), - vmtSelfPtr);
if pointer (pointer (integer (pointer (X)^) + vmtSelfPtr)^) <> pointer(pointer (X)^) then
raise EAbort.Create (errNotValidObject);
{$ENDIF}
FieldAddress := ShiftPointer(Pointer(X), FieldShift);
if FieldTypeId = TypeId then
result := result + GetStrVal(FieldAddress, FieldTypeId, nil, true)
else
result := result + GetStrVal(FieldAddress, FieldTypeId);
if I < K - 1 then
result := result + ',';
end;
result := result + ')';
end
else
result := 'nil';
end;
typeCLASSREF:
begin
CheckMemory (Address, sizeof (TClass));
C := TClass(Address^);
if Assigned(C) then
result := Self[TypeId].Name
else
result := 'nil';
end;
typePOINTER:
begin
CheckMemory (Address, sizeof (Cardinal));
result := Format('0x%x', [Cardinal(Address^)]);
end;
typeINTERFACE:
begin
CheckMemory (Address, sizeof (Cardinal));
if Cardinal(Address^) = 0 then
result := 'nil'
else
result := Self[TypeId].Name + '(' +
Format('0x%x', [Cardinal(Address^)]) + ')';
end;
typePROC:
begin
CheckMemory (Address, sizeof (Cardinal));
result := Format('0x%x', [Cardinal(Address^)]);
end;
typeARRAY:
begin
result := Self[TypeId].Name + '(';
GetArrayTypeInfo(TypeId, RangeTypeId, ElemTypeId);
FieldShift := Self[ElemTypeId].Size;
K1 := GetLowBoundRec(RangeTypeId).Value;
K2 := GetHighBoundRec(RangeTypeId).Value;
for I:=K1 to K2 do
begin
FieldAddress := ShiftPointer(Address, (I - K1) * FieldShift);
result := result + GetStrVal(FieldAddress, ElemTypeId);
if I < K2 then
result := result + ',';
end;
result := result + ')';
end;
typeDYNARRAY:
begin
CheckMemory (Address, sizeof (Pointer));
Address := Pointer(Address^);
if Address = nil then
begin
result := 'nil';
Exit;
end;
result := Self[TypeId].Name + '(';
ElemTypeId := Self[TypeId].PatternId;
FieldShift := Self[ElemTypeId].Size;
P := ShiftPointer(Address, - SizeOf(LongInt));
K1 := 0;
K2 := Integer(P^);
for I:=K1 to K2 - 1 do
begin
FieldAddress := ShiftPointer(Address, (I - K1) * FieldShift);
result := result + GetStrVal(FieldAddress, ElemTypeId);
if I < K2 - 1 then
result := result + ',';
end;
result := result + ')';
end;
typeUNICSTRING:
begin
CheckMemory (Address, sizeof (UnicString));
if pointer (Address^) <> nil then
begin
// First check to be able to length if WideString in bytes
CheckMemory(pointer(integer(Address^) - SizeOf(LongInt)), SizeOf(LongInt));
// Let's check if contents are accesible
I := Integer(pointer(integer(Address^) - SizeOf(LongInt))^);
// I contains length of string in bytes
if I = 0 then
begin
result := '';
Exit;
end;
CheckMemory (pointer(Address^), I + SizeOf (WideChar)); // One extra WideChar for #0
result := UnicString(Address^);
end
else Result := '';
end;
typeWIDECHAR:
begin
CheckMemory(Address, sizeof(WideChar));
W := Word(Address^);
result := WideChar(W);
end;
typeWORD:
begin
CheckMemory(Address, sizeof(Word));
W := Word(Address^);
result := IntToStr(W);
end;
typeINT64:
begin
CheckMemory (Address, sizeof (Int64));
result := IntToStr(Int64(Address^));
end;
typeSINGLE:
begin
CheckMemory (Address, sizeof (Single));
result := FloatToStr(Single(Address^));
end;
typeDOUBLE:
begin
CheckMemory (Address, sizeof (Double));
result := FloatToStr(Double(Address^));
end;
typeEXTENDED:
begin
CheckMemory (Address, sizeof (Extended));
result := FloatToStr(Extended(Address^));
end;
typeCURRENCY:
begin
CheckMemory (Address, sizeof (Extended));
result := CurrToStr(Currency(Address^));
end;
typeVARIANT, typeOLEVARIANT:
begin
try
begin
CheckMemory (Address, sizeof (Variant));
CheckVariantData (Address^);
if VarType(Variant(Address^)) = varError then
result := ''
else
result := VarToStr(Variant(Address^));
end
finally
{ Variant is residing within the context of script,
if we don't clean the TVarData before leaving the scope
Delphi code will add cleanup code that will either free
memory it shouldn't or even try to cleanup garbage, causing trouble regardless.
The variant we evaluated was done so for temporary reasons anc copied for memory
residing on the stack, as such, not cleanup is fine. Script should cleanup
when the variant leaves its own scope }
FillChar (V, Sizeof (V), 0);
end;
end
else
result := '';
end;
except
result := errInvalidValue;
end;
end;
function TBaseSymbolTable.GetVariantVal(Address: Pointer;
TypeId: Integer;
TypeMapRec: TTypeMapRec = nil): Variant;
var
B: Byte;
W: Word;
X: TObject;
C: TClass;
P: Pointer;
V: Variant;
FinTypeId: Integer;
I, K: Integer;
FieldAddress: Pointer;
FieldDescriptorId, FieldTypeId, FieldShift: Integer;
RangeTypeId, ElemTypeId, K1, K2: Integer;
begin
FinTypeId := Self[TypeId].FinalTypeId;
if TypeMapRec <> nil then
if TypeMapRec.TypeId <> TypeId then
TypeMapRec := nil;
try
case FinTypeId of
typeBOOLEAN, typeBYTEBOOL, typeWORDBOOL, typeLONGBOOL:
begin
CheckMemory(Address, sizeof(Byte));
B := Byte(Address^);
if B <> 0 then
result := true
else
result := false;
end;
typeBYTE, typeENUM:
begin
CheckMemory(Address, SizeOf(Byte));
B := Byte(Address^);
result := B;
end;
{$IFNDEF PAXARM}
typeANSICHAR:
begin
CheckMemory(Address, SizeOf(Byte));
B := Byte(Address^);
result := String(AnsiChar(B));
end;
{$ENDIF}
typeSET:
begin
CheckMemory(Address, SizeOf(TByteSet));
TypeId := Self[TypeId].PatternId;
FinTypeId := Self[TypeId].FinalTypeId;
result := ByteSetToString(TByteSet(Address^), FinTypeId);
end;
typeINTEGER:
begin
CheckMemory(Address, SizeOf(LongInt));
result := Integer(Address^);
end;
typeCARDINAL:
begin
CheckMemory(Address, SizeOf(Cardinal));
result := Cardinal(Address^);
end;
typeSMALLINT:
begin
CheckMemory (Address, sizeof(SmallInt));
result := SmallInt(Address^);
end;
typeSHORTINT:
begin
CheckMemory (Address, sizeof (ShortInt));
result := ShortInt(Address^);
end;
typeEVENT:
begin
FieldTypeId := typePOINTER;
FieldShift := SizeOfPointer;
FieldAddress := Address;
result := Self[TypeId].Name + '(';
result := result + GetStrVal(FieldAddress, FieldTypeId);
result := result + ',';
FieldAddress := ShiftPointer(Address, FieldShift);
result := result + GetStrVal(FieldAddress, FieldTypeId);
result := result + ')';
end;
typeRECORD:
begin
result := Self[TypeId].Name + '(';
K := GetFieldCount(TypeId, TypeMapRec);
for I:=0 to K - 1 do
begin
FieldDescriptorId := GetFieldDescriptorId(TypeId, I, TypeMapRec);
FieldTypeId := Self[FieldDescriptorId].TypeId;
FieldShift := Self[FieldDescriptorId].Shift;
FieldAddress := ShiftPointer(Address, FieldShift);
result := result + GetStrVal(FieldAddress, FieldTypeId);
if I < K - 1 then
result := result + ',';
end;
result := result + ')';
end;
typeCLASS:
begin
// Check pointer to object
CheckMemory (Address, sizeof (TObject));
X := TObject(Address^);
if Assigned(X) then
begin
result := Self[TypeId].Name + '(';
K := GetFieldCount(TypeId, TypeMapRec);
for I:=0 to K - 1 do
begin
FieldDescriptorId := GetFieldDescriptorId(TypeId, I, TypeMapRec);
FieldTypeId := Self[FieldDescriptorId].TypeId;
FieldShift := Self[FieldDescriptorId].Shift;
{$IFNDEF FPC}
// Check VMT for readability and to see if it's a true VMT
CheckMemory (pointer (integer (pointer (X)^) + vmtSelfPtr), - vmtSelfPtr);
if pointer (pointer (integer (pointer (X)^) + vmtSelfPtr)^) <> pointer(pointer (X)^) then
raise EAbort.Create (errNotValidObject);
{$ENDIF}
FieldAddress := ShiftPointer(Pointer(X), FieldShift);
result := result + GetStrVal(FieldAddress, FieldTypeId);
if I < K - 1 then
result := result + ',';
end;
result := result + ')';
end
else
result := 0;
end;
typeCLASSREF:
begin
CheckMemory (Address, sizeof (TClass));
C := TClass(Address^);
if Assigned(C) then
result := Self[TypeId].Name
else
result := 0;
end;
typePOINTER:
begin
CheckMemory (Address, sizeof (Cardinal));
result := Integer(Address^);
end;
typeINTERFACE:
begin
CheckMemory (Address, sizeof (Cardinal));
if Cardinal(Address^) = 0 then
result := 0
else
result := Self[TypeId].Name + '(' +
Format('0x%x', [Cardinal(Address^)]) + ')';
end;
typePROC:
begin
CheckMemory (Address, sizeof (Cardinal));
result := Integer(Address^);
end;
typeARRAY:
begin
result := Self[TypeId].Name + '(';
GetArrayTypeInfo(TypeId, RangeTypeId, ElemTypeId);
FieldShift := Self[ElemTypeId].Size;
K1 := GetLowBoundRec(RangeTypeId).Value;
K2 := GetHighBoundRec(RangeTypeId).Value;
for I:=K1 to K2 do
begin
FieldAddress := ShiftPointer(Address, (I - K1) * FieldShift);
result := result + GetStrVal(FieldAddress, ElemTypeId);
if I < K2 then
result := result + ',';
end;
result := result + ')';
end;
typeDYNARRAY:
begin
CheckMemory (Address, sizeof (Pointer));
Address := Pointer(Address^);
if Address = nil then
begin
result := 0;
Exit;
end;
result := Self[TypeId].Name + '(';
ElemTypeId := Self[TypeId].PatternId;
FieldShift := Self[ElemTypeId].Size;
P := ShiftPointer(Address, - SizeOf(LongInt));
K1 := 0;
K2 := Integer(P^);
for I:=K1 to K2 - 1 do
begin
FieldAddress := ShiftPointer(Address, (I - K1) * FieldShift);
result := result + GetStrVal(FieldAddress, ElemTypeId);
if I < K2 - 1 then
result := result + ',';
end;
result := result + ')';
end;
{$IFNDEF PAXARM}
typeANSISTRING:
begin
// Check pointer to string
CheckMemory (Address, sizeof (AnsiString));
if pointer (Address^) <> nil then
begin
// First check to be able to access length of string and the ref count integer
CheckMemory(pointer(integer(Address^) - SizeOf(LongInt) * 2), SizeOf(LongInt) * 2);
// Let's check if contents are accesible
I := Integer(pointer(integer(Address^) - SizeOf(LongInt))^);
// I contains length of string
if I = 0 then
begin
result := '';
Exit;
end;
CheckMemory (pointer(Address^), I + 1);
result := String(AnsiString(Address^));
end
else
begin
result := '';
Exit;
end;
end;
typeWIDESTRING:
begin
CheckMemory (Address, sizeof (WideString));
if pointer (Address^) <> nil then
begin
// First check to be able to length if WideString in bytes
CheckMemory(pointer(integer(Address^) - SizeOf(LongInt)), SizeOf(LongInt));
// Let's check if contents are accesible
I := Integer(pointer(integer(Address^) - SizeOf(LongInt))^);
// I contains length of string in bytes
if I = 0 then
begin
result := '';
Exit;
end;
CheckMemory (pointer(Address^), I + SizeOf (WideChar)); // One extra WideChar for #0
result := WideString(Address^);
end
else Result := '';
end;
typeSHORTSTRING:
begin
CheckMemory (Address, sizeof (ShortString));
result := String(ShortString(Address^));
end;
{$ENDIF}
typeUNICSTRING:
begin
CheckMemory (Address, sizeof (UnicString));
if pointer (Address^) <> nil then
begin
// First check to be able to length if WideString in bytes
CheckMemory(pointer(integer(Address^) - SizeOf(LongInt)), SizeOf(LongInt));
// Let's check if contents are accesible
I := Integer(pointer(integer(Address^) - SizeOf(LongInt))^);
// I contains length of string in bytes
if I = 0 then
begin
result := '';
Exit;
end;
CheckMemory (pointer(Address^), I + SizeOf (WideChar)); // One extra WideChar for #0
result := UnicString(Address^);
end
else Result := '';
end;
typeWIDECHAR:
begin
CheckMemory(Address, sizeof(WideChar));
W := Word(Address^);
result := WideChar(W);
end;
typeWORD:
begin
CheckMemory(Address, sizeof(Word));
W := Word(Address^);
result := W;
end;
typeINT64:
begin
CheckMemory (Address, sizeof (Int64));
{$IFDEF VARIANTS}
result := Int64(Address^);
{$ELSE}
result := Integer(Address^);
{$ENDIF}
end;
typeSINGLE:
begin
CheckMemory (Address, sizeof (Single));
result := Single(Address^);
end;
typeDOUBLE:
begin
CheckMemory (Address, sizeof (Double));
result := Double(Address^);
end;
typeEXTENDED:
begin
CheckMemory (Address, sizeof (Extended));
result := Extended(Address^);
end;
typeCURRENCY:
begin
CheckMemory (Address, sizeof (Extended));
result := Currency(Address^);
end;
typeVARIANT, typeOLEVARIANT:
begin
try
begin
CheckMemory (Address, sizeof (Variant));
CheckVariantData (Address^);
result := Variant(Address^);
end
finally
{ Variant is residing within the context of script,
if we don't clean the TVarData before leaving the scope
Delphi code will add cleanup code that will either free
memory it shouldn't or even try to cleanup garbage, causing trouble regardless.
The variant we evaluated was done so for temporary reasons anc copied for memory
residing on the stack, as such, not cleanup is fine. Script should cleanup
when the variant leaves its own scope }
FillChar (V, Sizeof (V), 0);
end;
end
else
result := 0;
end;
except
result := errInvalidValue;
end;
end;
procedure TBaseSymbolTable.CheckVariantData (const V);
var
I: Integer;
begin
if (TVarData (V).VType and varByRef <> 0) or
(TVarData (V).VType and varArray <> 0)
then raise EAbort.Create('varArray of varByRef not supported in debugger');
case TVarData (V).VType and varTypeMask of
varEmpty, varNull,
varSmallInt, varInteger, varSingle,
varDouble, varCurrency, varDate,
varError, varBoolean,
{$IFDEF VARIANTS}
varShortInt, varWord, varLongWord, varInt64,
{$ENDIF}
varByte : { Everything all right, this types won't cause trouble };
varOleStr:
begin
with TVarData (V) do
begin
CheckMemory (pointer (integer (VOleStr) - sizeof (integer)), sizeof (integer));
I := integer (pointer (integer (VOleStr) - sizeof (integer))^);
CheckMemory (VOleStr, I + sizeof (WideChar));
end;
end;
varString, varUString:
begin
with TVarData (V) do
begin
if Assigned(VString) then
begin
CheckMemory (pointer (integer (VString) - sizeof (integer) * 2), sizeof (integer) * 2);
I := integer (pointer (integer (VString) - sizeof (integer))^);
CheckMemory (VString, I + sizeof (Char));
end;
end;
end;
else
RaiseError(errInvalidVariantType, []);
end;
end;
function TBaseSymbolTable.GetVal(Address: Pointer;
TypeId: Integer): Variant;
var
FinTypeId, SZ: Integer;
begin
FinTypeId := Self[TypeId].FinalTypeId;
try
SZ := Types.GetSize(TypeId);
if SZ > 0 then
CheckMemory(Address, SZ);
case FinTypeId of
typeBOOLEAN: result := Boolean(Address^);
typeBYTEBOOL: result := ByteBool(Address^);
{$IFNDEF PAXARM}
typeANSISTRING: result := AnsiString(Address^);
typeWIDESTRING: result := WideString(Address^);
typeSHORTSTRING: result := ShortString(Address^);
typeANSICHAR,
{$ENDIF}
typeBYTE, typeENUM: result := Byte(Address^);
typeINTEGER, typeLONGBOOL: result := Integer(Address^);
{$IFDEF VARIANTS}
typeCARDINAL: result := Cardinal(Address^);
{$ELSE}
typeCARDINAL: result := Integer(Address^);
{$ENDIF}
typeSMALLINT: result := SmallInt(Address^);
typeSHORTINT: result := ShortInt(Address^);
{$IFDEF VARIANTS}
typePOINTER, typeINTERFACE, typeCLASS, typeCLASSREF: result := Cardinal(Address^);
{$ELSE}
typePOINTER, typeINTERFACE, typeCLASS, typeCLASSREF: result := Integer(Address^);
{$ENDIF}
typeUNICSTRING: result := UnicString(Address^);
typeWORD, typeWIDECHAR, typeWORDBOOL: result := Word(Address^);
{$IFDEF VARIANTS}
typeINT64: result := Int64(Address^);
{$ELSE}
typeINT64: result := Integer(Address^);
{$ENDIF}
typeSINGLE: result := Single(Address^);
typeDOUBLE: result := Double(Address^);
typeEXTENDED: result := Extended(Address^);
typeVARIANT, typeOLEVARIANT:
begin
CheckVariantData (Address^);
result := Variant(Address^);
end;
else
RaiseError(errIncompatibleTypesNoArgs, []);
end;
except
result := Unassigned;
end;
end;
procedure TBaseSymbolTable.PutVal(Address: Pointer;
TypeId: Integer; const Value: Variant);
var
B: Byte;
FinTypeId: Integer;
W: Word;
begin
FinTypeId := Self[TypeId].FinalTypeId;
case FinTypeId of
typeBOOLEAN, typeBYTEBOOL:
begin
CheckMemory(Address, SizeOf(Byte));
if Value then
B := 1
else
B := 0;
Byte(Address^) := B;
end;
typeBYTE, typeENUM:
begin
CheckMemory(Address, SizeOf(Byte));
Byte(Address^) := Value;
end;
{$IFNDEF PAXARM}
typeANSICHAR:
begin
CheckMemory(Address, SizeOf(Byte));
Byte(Address^) := Byte(Value);
end;
typeANSISTRING:
begin
// Check pointer to string
CheckMemory (Address, sizeof (AnsiString));
AnsiString(Address^) := AnsiString(Value);
end;
typeWIDESTRING:
begin
CheckMemory (Address, sizeof (WideString));
WideString(Address^) := Value;
end;
typeSHORTSTRING:
begin
CheckMemory (Address, sizeof (ShortString));
ShortString(Address^) := ShortString(Value);
end;
{$ENDIF}
typeINTEGER, typeLONGBOOL:
begin
CheckMemory (Address, sizeof (integer));
Integer(Address^) := Integer(Value);
end;
typeCARDINAL:
begin
CheckMemory (Address, sizeof (Cardinal));
Cardinal(Address^) := Value;
end;
typeSMALLINT:
begin
CheckMemory (Address, sizeof (SmallInt));
SmallInt(Address^) := Value;
end;
typeSHORTINT:
begin
CheckMemory (Address, sizeof (ShortInt));
ShortInt(Address^) := Value;
end;
typePOINTER, typeINTERFACE, typeCLASS, typeCLASSREF:
begin
CheckMemory (Address, sizeof (Cardinal));
Cardinal(Address^) := Value;
end;
typeUNICSTRING:
begin
CheckMemory (Address, sizeof (UnicString));
UnicString(Address^) := Value;
end;
typeWORD, typeWIDECHAR, typeWORDBOOL:
begin
CheckMemory(Address, SizeOf(Word));
W := Word(Value);
Word(Address^) := W;
end;
typeINT64:
begin
CheckMemory (Address, sizeof (Int64));
{$IFDEF VARIANTS}
Int64(Address^) := Value;
{$ELSE}
Int64(Address^) := Integer(Value);
{$ENDIF}
end;
typeSINGLE:
begin
CheckMemory (Address, sizeof (Single));
Single(Address^) := Value;
end;
typeDOUBLE:
begin
CheckMemory (Address, sizeof (Double));
Double(Address^) := Value;
end;
typeEXTENDED:
begin
CheckMemory (Address, sizeof (Extended));
Extended(Address^) := Value;
end;
typeVARIANT, typeOLEVARIANT:
begin
CheckMemory (Address, sizeof (Variant));
CheckVariantData (Address^);
Variant(Address^) := Value;
end;
else
RaiseError(errIncompatibleTypesNoArgs, []);
end;
end;
procedure TBaseSymbolTable.PutValue(P: Pointer; StackFrameNumber: Integer;
Id: Integer; const Value: Variant);
var
Address: Pointer;
TypeId: Integer;
begin
Address := GetFinalAddress(P, StackFrameNumber, Id);
TypeId := Self[Id].TerminalTypeId;
if Address = nil then
Exit;
PutVal(Address, TypeId, Value);
end;
function TBaseSymbolTable.GetValue(P: Pointer; StackFrameNumber: Integer;
Id: Integer): Variant;
var
Address: Pointer;
TypeId: Integer;
begin
Address := GetFinalAddress(P, StackFrameNumber, Id);
TypeId := Self[Id].TerminalTypeId;
if Address = nil then
Exit;
result := GetVal(Address, TypeId);
end;
function TBaseSymbolTable.GetValueAsString(P: Pointer;
StackFrameNumber: Integer;
Id: Integer;
TypeMapRec: TTypeMapRec = nil;
BriefCls: Boolean = false): String;
var
Address: Pointer;
TypeId: Integer;
begin
result := '???';
Address := GetFinalAddress(P, StackFrameNumber, Id);
TypeId := Self[Id].TerminalTypeId;
if Address = nil then
Exit;
result := GetStrVal(Address, TypeId, TypeMapRec);
end;
function TBaseSymbolTable.GetFieldValueAsString(P: Pointer;
StackFrameNumber: Integer;
Id: Integer;
FieldNumber: Integer;
TypeMapRec: TTypeMapRec = nil;
BriefCls: Boolean = false): String;
var
FieldAddress: Pointer;
TypeId, FieldDescriptorId, FieldTypeId: Integer;
begin
TypeId := Self[Id].TerminalTypeId;
FieldDescriptorId := GetFieldDescriptorId(TypeId, FieldNumber, TypeMapRec);
FieldTypeId := Self[FieldDescriptorId].TypeID;
FieldAddress := GetFieldAddress(P, StackFrameNumber, Id, FieldNumber, TypeMapRec);
if FieldAddress = nil then
result := errInvalidValue
else
result := GetStrVal(FieldAddress, FieldTypeId, TypeMapRec, BriefCls);
end;
function TBaseSymbolTable.GetArrayItemAddress(P: Pointer; StackFrameNumber, Id,
Index: Integer): Pointer;
var
TypeId, RangeTypeId, ElemTypeId, Shift, K1: Integer;
begin
result := GetFinalAddress(P, StackFrameNumber, Id);
TypeId := Self[Id].TerminalTypeId;
GetArrayTypeInfo(TypeId, RangeTypeId, ElemTypeId);
Shift := Self[ElemTypeId].Size;
K1 := GetLowBoundRec(RangeTypeId).Value;
result := ShiftPointer(result, (Index - K1) * Shift);
end;
function TBaseSymbolTable.GetArrayItemValueAsString(P: Pointer; StackFrameNumber: Integer;
Id, Index: Integer): String;
var
Address: Pointer;
TypeId, RangeTypeId, ElemTypeId: Integer;
begin
Address := GetArrayItemAddress(P, StackFrameNumber, Id, Index);
TypeId := Self[Id].TerminalTypeId;
GetArrayTypeInfo(TypeId, RangeTypeId, ElemTypeId);
result := GetStrVal(Address, ElemTypeId);
end;
function TBaseSymbolTable.GetDynArrayItemAddress(P: Pointer;
StackFrameNumber: Integer;
Id, Index: Integer): Pointer;
var
TypeId, ElemTypeId, Shift: Integer;
begin
result := GetFinalAddress(P, StackFrameNumber, Id);
result := Pointer(result^);
if result = nil then
Exit;
TypeId := Self[Id].TerminalTypeId;
ElemTypeId := Self[TypeId].PatternId;
Shift := Self[ElemTypeId].Size;
result := ShiftPointer(result, Index * Shift);
end;
function TBaseSymbolTable.GetDynArrayItemValueAsString(P: Pointer; StackFrameNumber: Integer;
Id, Index: Integer): String;
var
Address: Pointer;
TypeId, ElemTypeId: Integer;
begin
Address := GetDynArrayItemAddress(P, StackFrameNumber, Id, Index);
TypeId := Self[Id].TerminalTypeId;
ElemTypeId := Self[TypeId].PatternId;
result := GetStrVal(Address, ElemTypeId);
end;
function TBaseSymbolTable.GetFinalAddress(P: Pointer; StackFrameNumber: Integer;
Id: Integer): Pointer;
var
Shift: Integer;
begin
result := nil;
Shift := Self[Id].Shift;
if Self[Id].Param then
begin
result := TBaseRunner(P).GetParamAddress(StackFrameNumber, Shift);
if Self[Id].ByRef or Self[Id].ByRefEx then
result := Pointer(result^);
end
else if Self[Id].Local then
begin
result := TBaseRunner(P).GetLocalAddress(StackFrameNumber, Shift);
if Self[Id].ByRef or Self[Id].ByRefEx then
result := Pointer(result^);
end
else if Self[Id].IsGlobalVar then
begin
result := TBaseRunner(P).GetAddress(Shift);
if Self[Id].ByRef or Self[Id].ByRefEx or Self[Id].Host then
result := Pointer(result^);
end;
end;
{$IFNDEF PAXARM}
function TBaseSymbolTable.FindPAnsiCharConst(const S: String; LimitId: Integer): Integer;
var
I: Integer;
R: TSymbolRec;
begin
for I:=Types.Count to LimitId do
begin
R := Records[I];
if R.Kind = KindCONST then
if R.HasPAnsiCharType then
if R.Value = S then
begin
result := I;
Exit;
end;
end;
result := 0;
end;
{$ENDIF}
function TBaseSymbolTable.FindPWideCharConst(const S: String; LimitId: Integer): Integer;
var
I: Integer;
R: TSymbolRec;
begin
for I:=Types.Count to LimitId do
begin
R := Records[I];
if R.Kind = KindCONST then
if R.HasPWideCharType then
if R.Value = S then
begin
result := I;
Exit;
end;
end;
result := 0;
end;
function TBaseSymbolTable.GetAlignmentSize(TypeId, DefAlign: Integer): Integer;
var
FT, J, temp,
RangeTypeId, ElemTypeId: Integer;
R: TSymbolRec;
K: Integer;
begin
if DefAlign = 1 then
begin
result := DefAlign;
Exit;
end;
FT := Records[TypeId].FinalTypeId;
if FT in (OrdinalTypes +
[typeCLASS, typeCLASSREF, typePOINTER,
{$IFNDEF PAXARM}
typeANSISTRING, typeWIDESTRING,
{$ENDIF}
typeUNICSTRING, typeDYNARRAY, typeINTERFACE]) then
begin
result := Types.GetSize(FT);
if result > DefAlign then
result := DefAlign;
end
else if FT = typeSET then
begin
result := GetSizeOfSetType(TypeId);
if result > 4 then
result := 1;
end
else if FT = typeSINGLE then
begin
result := 4;
if result > DefAlign then
result := DefAlign;
end
else if FT in [typeDOUBLE, typeCURRENCY, typeEXTENDED] then
begin
result := 8;
if result > DefAlign then
result := DefAlign;
end
{$IFNDEF PAXARM}
else if FT = typeSHORTSTRING then
result := 1
{$ENDIF}
else if FT = typeARRAY then
begin
TypeId := Records[TypeId].TerminalTypeId;
if Records[TypeId].IsPacked then
begin
result := 1;
Exit;
end;
GetArrayTypeInfo(TypeId, RangeTypeId, ElemTypeId);
result := GetAlignmentSize(ElemTypeId, DefAlign);
end
else if FT = typeRECORD then
begin
TypeId := Records[TypeId].TerminalTypeId;
if Records[TypeId].IsPacked then
begin
result := 1;
Exit;
end;
K := Card;
result := 0;
for J:= TypeId + 1 to K do
begin
R := Records[J];
if R = SR0 then
break;
if (R.Kind = KindTYPE_FIELD) and (R.Level = TypeId) then
begin
temp := GetAlignmentSize(R.TypeId, DefAlign);
if temp > result then
result := temp;
end;
end;
end
else
result := DefAlign;
end;
function TBaseSymbolTable.FindClassTypeId(Cls: TClass): Integer;
var
I, J: Integer;
S: String;
R: TSymbolRec;
ok: Boolean;
List: TIntegerList;
begin
if StdCard = 0 then
begin
if DllDefined then
S := Cls.ClassName
else
S := '';
for I:= Card downto 1 do
with Records[I] do
if DllDefined then
begin
if Kind = KindTYPE then if Name = S then
begin
result := I;
Exit;
end;
end
else if PClass = Cls then
begin
result := I;
Exit;
end;
result := 0;
Exit;
end;
S := Cls.ClassName;
List := HashArray.GetList(S);
for J:=List.Count - 1 downto 0 do
begin
I := List[J];
R := Records[I];
if DllDefined then
ok := StrEql(R.Name, S) and (R.Kind = KindTYPE)
else
ok := R.PClass = Cls;
if ok then
begin
result := I;
Exit;
end;
end;
result := 0;
end;
function TBaseSymbolTable.FindClassTypeIdByPti(Pti: PTypeInfo): Integer;
var
I, J: Integer;
S: String;
R: TSymbolRec;
ok: Boolean;
List: TIntegerList;
begin
if StdCard = 0 then
begin
if DllDefined then
S := PTIName(pti)
else
S := '';
for I:= Card downto 1 do
with Records[I] do
if DllDefined then
begin
if Kind = KindTYPE then if Name = S then
begin
result := I;
Exit;
end;
end
else if PClass.ClassInfo = Pti then
begin
result := I;
Exit;
end;
result := 0;
Exit;
end;
S := PTIName(pti);
List := HashArray.GetList(S);
for J:=List.Count - 1 downto 0 do
begin
I := List[J];
R := Records[I];
if DllDefined then
ok := StrEql(R.Name, S) and (R.Kind = KindTYPE)
else if R.PClass <> nil then
ok := R.PClass.ClassInfo = Pti
else
ok := false;
if ok then
begin
result := I;
Exit;
end;
end;
result := 0;
end;
procedure TBaseSymbolTable.SetVisibility(ClassId: integer;
const MemberName: String; value: Integer);
var
Id: Integer;
Vis: TClassVisibility;
begin
Vis := cvNone;
if Value = 0 then
Vis := cvPublic
else if Value = 1 then
Vis := cvProtected
else if Value = 2 then
Vis := cvPrivate
else if Value = 3 then
Vis := cvPublished
else
RaiseError(errIncorrectValue, []);
if ClassId > 0 then
begin
id := Lookup(MemberName, ClassId, true);
if Id > 0 then
Records[Id].Vis := Vis;
end;
end;
procedure TBaseSymbolTable.SetVisibility(C: TClass; const MemberName: String; value: Integer);
begin
SetVisibility(FindClassTypeId(C), MemberName, value);
end;
procedure TBaseSymbolTable.LoadGlobalSymbolTableFromStream(Stream: TStream);
var
Reader: TReader;
I, K: Integer;
R: TSymbolRec;
ClearNextVal: Boolean;
C: TClass;
begin
Reader := TReader.Create(Stream, 4096 * 4);
try
K := Reader.ReadInteger();
ClearNextVal := false;
C := nil;
for I := StdCard + 1 to StdCard + K do
begin
R := AddRecord;
R.LoadFromStream(Reader);
if ClearNextVal then
begin
R.Value := Integer(C);
ClearNextVal := false;
end;
if R.ClassIndex <> -1 then
begin
Inc(LastClassIndex);
R.ClassIndex := LastClassIndex;
C := Classes.GetClass(R.Name);
R.PClass := C;
ClearNextVal := true;
end;
end;
LastShiftValue := Reader.ReadInteger();
LastClassIndex := Reader.ReadInteger();
LastSubId := Reader.ReadInteger();
LastVarId := Reader.ReadInteger();
HashArray.Clear;
HashArray.LoadFromStream(Reader);
SomeTypeList.Clear;
SomeTypeList.LoadFromStream(Reader);
GuidList.Clear;
GuidList.LoadFromStream(Reader);
ExternList.Clear;
ExternList.LoadFromStream(Reader);
finally
FreeAndNil(Reader);
end;
end;
procedure TBaseSymbolTable.LoadGlobalSymbolTableFromFile(const FileName: String);
var
F: TFileStream;
begin
if not FileExists(FileName) then
RaiseError(errFileNotFound, [FileName]);
F := TFileStream.Create(FileName, fmOpenRead);
try
LoadGlobalSymbolTableFromStream(F);
finally
FreeAndNil(F);
end;
end;
procedure TBaseSymbolTable.SaveGlobalSymbolTableToStream(Stream: TStream);
var
Writer: TWriter;
I, K: Integer;
begin
Writer := TWriter.Create(Stream, 4096 * 4);
try
K := Card - StdCard;
Writer.WriteInteger(K);
for I := StdCard + 1 to StdCard + K do
begin
Records[I].SaveToStream(Writer);
end;
Writer.WriteInteger(LastShiftValue);
Writer.WriteInteger(LastClassIndex);
Writer.WriteInteger(LastSubId);
Writer.WriteInteger(LastVarId);
HashArray.SaveToStream(Writer);
SomeTypeList.SaveToStream(Writer);
GuidList.SaveToStream(Writer);
ExternList.SaveToStream(Writer);
finally
FreeAndNil(Writer);
end;
end;
procedure TBaseSymbolTable.SaveGlobalSymbolTableToFile(const FileName: String);
var
F: TFileStream;
begin
F := TFileStream.Create(FileName, fmCreate);
try
SaveGlobalSymbolTableToStream(F);
finally
FreeAndNil(F);
end;
end;
procedure TBaseSymbolTable.SaveNamespaceToStream(LevelId: Integer; S: TStream);
var
BeginId, EndId: Integer;
function IsExternalId(Id: Integer): Boolean;
begin
if Id > EndId then
result := true
else if Id < BeginId then
begin
if Id < StdCard then
result := false
else
result := true;
end
else
result := false;
end;
var
Writer: TWriter;
ExternRec: TExternRec;
R: TSymbolRec;
I: Integer;
CurrOffset: Integer;
GUID: TGUID;
begin
CurrOffset := GetDataSize(LevelId);
Writer := TWriter.Create(S, 4096 * 4);
ExternRec := TExternRec.Create;
try
BeginId := LevelId;
EndId := Card;
for I := LevelId + 1 to Card do
if Records[I].Kind = KindNAMESPACE then
begin
EndId := I - 1;
break;
end;
Writer.Write(StreamVersion, SizeOf(StreamVersion));
Writer.Write(BeginId, SizeOf(LongInt));
Writer.Write(EndId, SizeOf(LongInt));
Writer.Write(CurrOffset, SizeOf(LongInt));
for I := LevelId to EndId do
begin
R := Records[I];
R.SaveToStream(Writer);
if (R.Kind = KindTYPE) and (R.TypeId = typeINTERFACE) then
begin
GUID := GuidList.GetGuidByID(I);
Writer.Write(GUID, SizeOf(GUID));
end;
if IsExternalId(R.TypeId) then
begin
ExternRec.Id := R.Id;
ExternRec.FullName := Records[R.TypeId].FullName;
ExternRec.RecKind := erTypeId;
ExternRec.SaveToStream(Writer);
end;
if IsExternalId(R.PatternId) then
begin
ExternRec.Id := R.Id;
ExternRec.FullName := Records[R.PatternId].FullName;
ExternRec.RecKind := erPatternId;
ExternRec.SaveToStream(Writer);
end;
if IsExternalId(R.AncestorId) then
begin
ExternRec.Id := R.Id;
ExternRec.FullName := Records[R.AncestorId].FullName;
ExternRec.RecKind := erAncestorId;
ExternRec.SaveToStream(Writer);
end;
if IsExternalId(R.ReadId) then
begin
ExternRec.Id := R.Id;
ExternRec.FullName := Records[R.ReadId].FullName;
ExternRec.RecKind := erReadId;
ExternRec.SaveToStream(Writer);
end;
if IsExternalId(R.WriteId) then
begin
ExternRec.Id := R.Id;
ExternRec.FullName := Records[R.WriteId].FullName;
ExternRec.RecKind := erWriteId;
ExternRec.SaveToStream(Writer);
end;
end;
finally
FreeAndNil(Writer);
FreeAndNil(ExternRec);
end;
end;
procedure TBaseSymbolTable.LoadNamespaceFromStream(S: TStream);
var
OldNamespaceId, OldEndId: Integer;
function IsExternalId(Id: Integer): Boolean;
begin
if Id > OldEndId then
result := true
else if Id < OldNamespaceId then
begin
if Id > StdCard then
result := true
else
result := false;
end
else
result := false;
end;
function IsInternalId(Id: Integer): Boolean;
begin
result := (Id >= OldNamespaceId) and (Id <= OldEndId);
end;
var
I, J, NamespaceId, K, Delta: Integer;
R: TSymbolRec;
ClearNextVal: Boolean;
Reader: TReader;
ExternRec: TExternRec;
CurrOffset, OldOffset, DeltaOffset: Integer;
First: Boolean;
CurrStreamVersion: Integer;
GUID: TGUID;
GuidRec: TGuidRec;
C: TClass;
begin
C := nil;
First := true;
CurrOffset := GetDataSize;
Reader := TReader.Create(S, 4096 * 4);
ExternRec := TExternRec.Create;
try
Reader.Read(CurrStreamVersion, SizeOf(StreamVersion));
if CurrStreamVersion <> StreamVersion then
RaiseError(errIncorrectStreamVersion, []);
Reader.Read(OldNamespaceId, SizeOf(LongInt));
Reader.Read(OldEndId, SizeOf(LongInt));
Reader.Read(OldOffset, SizeOf(LongInt));
K := OldEndId - OldNamespaceId + 1;
R := AddRecord;
NamespaceId := R.Id;
Delta := NamespaceId - OldNamespaceId;
DeltaOffset := CurrOffset - OldOffset;
R.LoadFromStream(Reader);
R.Update;
ClearNextVal := false;
for I := 2 to K do
begin
R := AddRecord;
R.LoadFromStream(Reader);
R.Update;
if (R.Kind = KindTYPE) and (R.TypeId = typeINTERFACE) then
begin
Reader.Read(GUID, SizeOf(GUID));
GuidList.Add(GUID, R.Id, R.Name);
if R.SupportedInterfaces <> nil then
for J := R.SupportedInterfaces.Count - 1 downto 0 do
begin
GuidRec := R.SupportedInterfaces[J];
if IsExternalId(GuidRec.Id) then
begin
ExternList.Add(R.Id, GuidRec.Name, erGUID);
R.SupportedInterfaces.RemoveAt(J);
end
else if IsInternalId(GuidRec.Id) then
GuidRec.Id := GuidRec.Id + Delta;
end;
end;
if IsInternalId(R.Level) then
R.Level := R.Level + Delta;
if R.Shift > 0 then
if R.Kind <> kindTYPE_FIELD then
begin
R.Shift := R.Shift + DeltaOffset;
if First then
begin
while R.Shift < CurrOffset do
begin
R.Shift := R.Shift + 1;
Inc(DeltaOffset);
end;
First := false;
end;
end;
if IsInternalId(R.OwnerId) then
R.OwnerId := R.OwnerId + Delta;
if IsExternalId(R.TypeId) then
begin
ExternRec.LoadFromStream(Reader);
J := LookupFullName(ExternRec.FullName, true);
if J > 0 then
R.TypeID := J
else
begin
ExternRec.Id := R.Id;
ExternList.Add(ExternRec.Id, ExternRec.FullName, ExternRec.RecKind);
end;
end
else if IsInternalId(R.TypeID) then
R.TypeId := R.TypeId + Delta;
if IsExternalId(R.PatternId) then
begin
ExternRec.LoadFromStream(Reader);
J := LookupFullName(ExternRec.FullName, true);
if J > 0 then
R.PatternID := J
else
begin
ExternRec.Id := R.Id;
ExternList.Add(ExternRec.Id, ExternRec.FullName, ExternRec.RecKind);
end;
end
else if IsInternalId(R.PatternID) then
R.PatternId := R.PatternId + Delta;
if IsExternalId(R.AncestorId) then
begin
ExternRec.LoadFromStream(Reader);
J := LookupFullName(ExternRec.FullName, true);
if J > 0 then
R.AncestorID := J
else
begin
ExternRec.Id := R.Id;
ExternList.Add(ExternRec.Id, ExternRec.FullName, ExternRec.RecKind);
end;
end
else if IsInternalId(R.AncestorID) then
R.AncestorId := R.AncestorId + Delta;
if IsExternalId(R.ReadId) then
begin
ExternRec.LoadFromStream(Reader);
J := LookupFullName(ExternRec.FullName, true);
if J > 0 then
R.ReadId := J
else
begin
ExternRec.Id := R.Id;
ExternList.Add(ExternRec.Id, ExternRec.FullName, ExternRec.RecKind);
end;
end
else if IsInternalId(R.ReadId) then
R.ReadId := R.ReadId + Delta;
if IsExternalId(R.WriteId) then
begin
ExternRec.LoadFromStream(Reader);
J := LookupFullName(ExternRec.FullName, true);
if J > 0 then
R.WriteId := J
else
begin
ExternRec.Id := R.Id;
ExternList.Add(ExternRec.Id, ExternRec.FullName, ExternRec.RecKind);
end;
end
else if IsInternalId(R.WriteId) then
R.WriteId := R.WriteId + Delta;
if ClearNextVal then
begin
R.Value := Integer(C);
ClearNextVal := false;
end;
if R.ClassIndex <> -1 then
begin
Inc(LastClassIndex);
R.ClassIndex := LastClassIndex;
C := Classes.GetClass(R.Name);
R.PClass := C;
ClearNextVal := true;
end;
end;
finally
FreeAndNil(Reader);
FreeAndNil(ExternRec);
end;
LastShiftValue := GetDataSize;
end;
procedure TBaseSymbolTable.ResolveExternList(CheckProc: TCheckProc; Data: Pointer);
var
I, J, PositiveIndex: Integer;
GD: TGUID;
RJ: TSymbolRec;
begin
for I := 0 to ExternList.Count - 1 do
with ExternList[I] do
begin
if RecKind = erGUID then
begin
J := LookupType(FullName, true);
if J = 0 then
begin
if Assigned(CheckProc) then
if not CheckProc(FullName, Data, erNone) then
continue;
RaiseError(errUndeclaredInterface, [FullName]);
end;
if Records[Id].SupportedInterfaces = nil then
Records[Id].SupportedInterfaces := TGuidList.Create;
GD := GuidList.GetGuidByID(J);
Records[Id].SupportedInterfaces.Add(GD, J, FullName);
// recreate positive method indexes
PositiveIndex := -1;
for J := Id to Card do
begin
RJ := Records[J];
if RJ = SR0 then
break;
if RJ.Kind = kindNAMESPACE then
break;
if (RJ.Level = Id) and (RJ.Kind = kindSUB) and
(RJ.NegativeMethodIndex < 0) then
begin
if PositiveIndex = -1 then
PositiveIndex := RestorePositiveIndex(Id);
if PositiveIndex = -1 then
RaiseError(errInternalError, []);
RJ.MethodIndex := Abs(RJ.NegativeMethodIndex) + PositiveIndex;
end;
end;
continue;
end;
if RecKind = erTypeId then
begin
if PosCh('.', FullName) > 0 then
begin
J := LookupFullName(FullName, true);
if J = 0 then
J := LookupType(FullName, 0, true);
end
else
J := LookupType(FullName, 0, true)
end
else
begin
J := LookupFullName(FullName, true);
if J = 0 then
J := LookupType(FullName, 0, true);
end;
if J > 0 then
begin
case RecKind of
erTypeId: Records[Id].TypeID := J;
erPatternId: Records[Id].PatternID := J;
erAncestorId: Records[Id].AncestorID := J;
erReadId: Records[Id].ReadID := J;
erWriteId: Records[Id].WriteID := J;
end;
end
else
begin
case RecKind of
ePropertyInBaseClassId:
begin
if Assigned(CheckProc) then
if not CheckProc(FullName, Data, RecKind) then
continue;
RaiseError(errPropertyDoesNotExistsInTheBaseClass, [FullName]);
end;
erTypeId:
begin
if Assigned(CheckProc) then
if not CheckProc(FullName, Data, RecKind) then
continue;
// RaiseError(errTypeNotFound, [FullName]);
end
else
begin
if Assigned(CheckProc) then
if not CheckProc(FullName, Data, RecKind) then
continue;
RaiseError(errUndeclaredIdentifier, [FullName]);
end;
end;
end;
end;
if Self.St_Tag > 0 then
TLocalSymbolTable(Self).GlobalST.ResolveExternList(CheckProc, Data);
end;
procedure TBaseSymbolTable.SaveNamespaceToFile(LevelId: Integer; const FileName: String);
var
F: TFileStream;
begin
F := TFileStream.Create(FileName, fmCreate);
try
SaveNamespaceToStream(LevelId, F);
finally
FreeAndNil(F);
end;
end;
procedure TBaseSymbolTable.SaveNamespaceToStream(const NamespaceName: String; S: TStream);
var
Id: Integer;
begin
Id := LookupNamespace(NamespaceName, 0, true);
if Id = 0 then
RaiseError(errUndeclaredIdentifier, [NamespaceName]);
SaveNamespaceToStream(Id, S);
end;
procedure TBaseSymbolTable.SaveNamespaceToFile(const NamespaceName, FileName: String);
var
Id: Integer;
begin
Id := LookupNamespace(NamespaceName, 0, true);
if Id = 0 then
RaiseError(errUndeclaredIdentifier, [NamespaceName]);
SaveNamespaceToFile(Id, FileName);
end;
procedure TBaseSymbolTable.LoadNamespaceFromFile(const FileName: String);
var
F: TFileStream;
begin
if not FileExists(FileName) then
RaiseError(errFileNotFound, [FileName]);
F := TFileStream.Create(FileName, fmOpenRead);
try
LoadNamespaceFromStream(F);
finally
FreeAndNil(F);
end;
end;
procedure TBaseSymbolTable.AddScriptFields(ClassId: Integer; FieldList: TMapFieldList);
var
I, TypeId: Integer;
RI: TSymbolRec;
FieldTypeName: String;
begin
for I := ClassId + 1 to Card do
begin
RI := Records[I];
if RI.Level = ClassId then
if RI.Kind = kindTYPE_FIELD then
begin
TypeId := RI.TypeID;
FieldTypeName := Records[TypeId].Name;
FieldList.Add(RI.Name, RI.Shift, FieldTypeName);
end;
end;
ClassId := Records[ClassId].AncestorId;
if ClassId > 0 then
if not Records[ClassId].Host then
AddScriptFields(ClassId, FieldList);
end;
procedure TBaseSymbolTable.ExtractNamespaces(const Level: Integer; L: TStrings);
var
I, KK, K1, K2: Integer;
RI: TSymbolRec;
S: String;
begin
for KK := 1 to 2 do
begin
if KK = 1 then
begin
K1 := 1;
if Self.st_tag = 0 then
K2 := Card
else
K2 := TLocalSymbolTable(Self).GlobalST.Card;
end
else
begin
K1 := FirstLocalId + 1;
K2 := Card;
end;
for I := K1 to K2 do
begin
RI := Records[I];
if RI.Kind = KindNAMESPACE then
begin
if I = H_PascalNamespace then
continue;
if I = H_BasicNamespace then
continue;
if I = JS_JavaScriptNamespace then
continue;
if I = JS_TempNamespaceId then
continue;
if I = H_PaxCompilerFramework then
continue;
if I = H_PaxCompilerSEH then
continue;
S := RI.Name;
L.AddObject(S, TObject(I));
end;
end;
end;
end;
procedure TBaseSymbolTable.ExtractMembers(const Id: Integer; L: TStrings;
Lang: TPaxLang = lngPascal;
SharedOnly: Boolean = false;
VisSet: TMemberVisibilitySet = [cvPublic, cvPublished]);
function ExtractParams(R: TSymbolRec): String;
var
LP: TStringList;
J: Integer;
begin
if R.Kind = KindPROP then
if R.ReadId <> 0 then
R := Records[R.ReadId];
result := '';
if R.Count > 0 then
begin
LP := TStringList.Create;
try
ExtractParameters(R.Id, LP, Lang);
for J := 0 to LP.Count - 1 do
begin
result := result + LP[J];
if J <> LP.Count - 1 then
case Lang of
lngBasic:
result := result + ', ';
else
result := result + '; ';
end;
end;
finally
FreeAndNil(LP);
end;
end;
end;
function IndexOfEx(List: TStrings;
S: String;
P: Integer): Integer;
var
I: Integer;
begin
result := -1;
S := Copy(S, 1, P);
for I := 0 to List.Count - 1 do
if StrEql(Copy(L[I], 1, P), S) then
begin
result := I;
Exit;
end;
end;
var
T, I, K, K0: Integer;
R: TSymbolRec;
S, P: String;
IsNamespace: Boolean;
PP: Integer;
begin
IsNamespace := false;
if Id = 0 then
begin
T := 0;
IsNamespace := true;
end
else if Records[Id].Kind = kindNAMESPACE then
begin
T := Id;
IsNamespace := true;
end
else
begin
T := Records[Id].TerminalTypeId;
if T in [0, typeVOID] then
Exit;
end;
if T > FirstLocalId then
K := Card
else
K := TLocalSymbolTable(Self).GlobalST.Card;
if Id > 0 then
if Records[T].FinalTypeId = typeCLASSREF then
begin
T := Records[T].PatternId;
SharedOnly := true;
end;
K0 := T;
if Id = 0 then
begin
K0 := FirstLocalId;
K := Card;
end;
for I:= K0 + 1 to K do
begin
R := Records[I];
if R.Kind = KindNAMESPACE then
if not IsNamespace then
break;
if R.Level = T then
begin
if IsNamespace then
if R.InImplementation then
continue;
if not (R.Vis in VisSet) then
// if not (R.Host and (R.Vis = cvNone)) then // backward compatibility only
if R.Vis <> cvNone then // backward compatibility only
continue;
if SharedOnly then
if not R.IsSharedMethod then
continue;
PP := -1;
S := R.Name;
if IsValidName(S) then
case R.Kind of
kindCONSTRUCTOR:
begin
P := ExtractParams(R);
case Lang of
lngBasic:
begin
S := 'Sub ' + R.Name + '(' + P + ')';
end
else
begin
if P = '' then
S := 'constructor ' + R.Name + ';'
else
S := 'constructor ' + R.Name + '(' + P + ');';
end;
end;
if L.IndexOf(S) = -1 then
L.AddObject(S, TObject(R.Id));
end;
kindDESTRUCTOR:
begin
case Lang of
lngBasic:
begin
S := 'Sub ' + R.Name + '()';
end;
else
begin
S := 'destructor ' + R.Name + ';';
end;
end;
if L.IndexOf(S) = -1 then
L.AddObject(S, TObject(R.Id));
end;
kindSUB:
begin
P := ExtractParams(R);
case Lang of
lngBasic:
begin
if R.TypeId in [0, typeVOID] then
S := 'Sub ' + R.Name + '(' + P + ')'
else
S := 'Function ' + R.Name + '(' + P + ') As ' +
Records[R.TypeId].NativeName;
end;
else
begin
if R.TypeId in [0, typeVOID] then
begin
if P = '' then
S := 'procedure ' + R.Name + ';'
else
S := 'procedure ' + R.Name + '(' + P + ');';
end
else
begin
if P = '' then
S := 'function ' + R.Name + ': ' +
Records[R.TypeId].NativeName + ';'
else
S := 'function ' + R.Name + '(' + P + '): ' +
Records[R.TypeId].NativeName + ';';
end;
end;
end;
if L.IndexOf(S) = -1 then
L.AddObject(S, TObject(R.Id));
end;
kindTYPE_FIELD:
begin
case Lang of
lngBasic:
S := 'Dim ' + R.Name + ' As ' + Records[R.TypeId].NativeName;
else
S := 'field ' + R.Name + ': ' + Records[R.TypeId].NativeName + ';';
end;
if L.IndexOf(S) = -1 then
L.AddObject(S, TObject(R.Id));
end;
kindPROP:
begin
P := ExtractParams(R);
case Lang of
lngBasic:
begin
if P = '' then
S := 'Property ' + R.Name +
' As ' + Records[R.TypeId].NativeName
else
begin
S := 'Property ' + R.Name +
'(' + P + ')' +
' As ' + Records[R.TypeId].NativeName;
PP := PosCh('(', S);
end;
end
else
begin
if P = '' then
S := 'property ' + R.Name +
': ' + Records[R.TypeId].NativeName + ';'
else
begin
S := 'property ' + R.Name +
'[' + P + ']' +
': ' + Records[R.TypeId].NativeName + ';';
PP := PosCh('[', S);
end;
end;
end;
if PP = -1 then
begin
if L.IndexOf(S) = -1 then
L.AddObject(S, TObject(R.Id));
end
else
begin
if IndexOfEx(L, S, PP) = -1 then
L.AddObject(S, TObject(R.Id));
end;
end;
kindVAR:
begin
case Lang of
lngBasic:
S := 'Dim ' + R.Name + ' As ' + Records[R.TypeId].NativeName;
else
S := 'var ' + R.Name + ': ' + Records[R.TypeId].NativeName + ';';
end;
if L.IndexOf(S) = -1 then
L.AddObject(S, TObject(R.Id));
end;
kindCONST:
begin
case Lang of
lngBasic:
S := 'Const ' + R.Name + ' As ' +
Records[R.TypeId].NativeName + '= ' +
ValueStr(R.Id);
else
S := 'const ' + R.Name + ': ' +
Records[R.TypeId].NativeName + '= ' +
ValueStr(R.Id) +
';';
end;
if L.IndexOf(S) = -1 then
L.AddObject(S, TObject(R.Id));
end;
kindTYPE:
begin
case Lang of
lngBasic:
S := 'Type ' + R.Name;
else
S := 'type ' + R.Name + ';';
end;
if L.IndexOf(S) = -1 then
L.AddObject(S, TObject(R.Id));
end;
end;
end;
end;
if IsFrameworkTypeId(T) then
Exit;
if Records[T].AncestorId > 0 then
ExtractMembers(Records[T].AncestorId, L, lang, SharedOnly, VisSet);
// if Records[T].FinalTypeId <> typeINTERFACE then
// Exit;
if Records[T].SupportedInterfaces = nil then
Exit;
for I:=0 to Records[T].SupportedInterfaces.Count - 1 do
ExtractMembers(Records[T].SupportedInterfaces[I].Id, L, Lang, SharedOnly, VisSet);
end;
function TBaseSymbolTable.ValueStr(I: Integer): String;
var
VarObject: TVarObject;
B: Integer;
begin
if Records[I].DefVal <> '' then
begin
result := Records[I].DefVal;
if Records[I].FinalTypeId in (CharTypes + StringTypes) then
result := '''' + result + '''';
Exit;
end;
if VarType(Records[I].Value) = varEmpty then
result := ''
else if IsVarObject(Records[I].Value) then
begin
VarObject := VariantToVarObject(Records[I].Value);
if VarObject = nil then
result := 'nil'
else
result := VarObject.ToStr;
end
else if Records[I].FinalTypeId in CharTypes then
begin
B := Records[I].Value;
result := '''' + chr(B) + '''';
end
else
result := VarToStr(Records[I].Value);
result := ReplaceCh(#0, '_', result);
if result = '' then
result := '''' + ''''
else if Records[I].FinalTypeId in [typePOINTER,
typeCLASS,
typeCLASSREF,
typeINTERFACE] then
if result = '0' then
result := 'nil';
end;
procedure TBaseSymbolTable.ExtractParameters(Id: Integer; L: TStrings;
Lang: TPaxLang = lngPascal;
SkipParameters: Integer = 0);
var
I, J, K, Skp: Integer;
R: TSymbolRec;
S: String;
begin
K := Records[Id].Count;
J := 0;
Skp := 0;
for I := Id + 1 to Card do
if IsParam(Id, I) then
begin
Inc(Skp);
if Skp <= SkipParameters then
continue
else
begin
Inc(J);
R := Records[I];
S := R.Name;
if not IsValidName(S) then
begin
S := Copy(Records[R.TypeId].Name, 1, 1);
if L.IndexOf(S) >= 0 then
S := S + Chr(J);
end;
case Lang of
lngBasic:
begin
S := S + ' As ' +
Records[R.TypeId].NativeName;
if R.ByRef then
S := 'ByRef ' + S
else if R.IsConst then
S := 'Const ' + S;
end;
else
begin
S := S + ': ' +
Records[R.TypeId].NativeName;
if R.ByRef then
S := 'var ' + S
else if R.IsConst then
S := 'const ' + S;
end;
end;
if R.Optional then
begin
S := S + '= ' + ValueStr(I);
end;
L.AddObject(S, TObject(R.Id));
if J = K then
break;
end;
end;
end;
procedure TBaseSymbolTable.ExtractParametersEx(Id: Integer;
L: TStrings;
Upcase: Boolean;
SkipParameters: Integer = 0);
var
OverList: TIntegerList;
I: Integer;
begin
OverList := LookUpAll(Records[Id].Name,
Records[Id].Level,
Upcase);
try
for I := 0 to OverList.Count - 1 do
begin
ExtractParameters(OverList[I], L, lngPascal, SkipParameters);
if I <> OverList.Count - 1 then
L.Add(PARAMS_DELIMITER);
end;
finally
FreeAndNil(OverList);
end;
end;
procedure TBaseSymbolTable.AddTypes(const TypeName: String; L: TStrings;
ErrorIndex: Integer; Upcase: Boolean);
var
I, J, K1, K2: Integer;
List: TIntegerList;
RI: TSymbolRec;
ok: Boolean;
R: TUndeclaredTypeRec;
begin
K1 := L.Count;
List := HashArray.GetList(TypeName);
for J := List.Count - 1 downto 0 do
begin
I := List[J];
RI := Records[I];
if RI.Kind = kindTYPE then
begin
if UpCase then
ok := StrEql(RI.Name, TypeName)
else
ok := RI.Name = TypeName;
if ok then
begin
if L.IndexOf(RI.FullName) = -1 then
begin
R := TUndeclaredTypeRec.Create;
R.Id := I;
R.ErrorIndex := ErrorIndex;
L.AddObject(RI.FullName, R);
end;
end;
end;
end;
K2 := L.Count;
if K1 = K2 then
if L.IndexOf(TypeName) = -1 then
begin
R := TUndeclaredTypeRec.Create;
R.Id := 0;
R.ErrorIndex := ErrorIndex;
L.AddObject(TypeName, R);
end;
end;
procedure TBaseSymbolTable.AddUndeclaredIdent(const IdentName: String; L: TStrings;
ErrorIndex: Integer; Upcase: Boolean);
var
I, J, K1, K2, Level: Integer;
List: TIntegerList;
RI: TSymbolRec;
ok: Boolean;
R: TUndeclaredIdentRec;
begin
K1 := L.Count;
List := HashArray.GetList(IdentName);
for J := List.Count - 1 downto 0 do
begin
I := List[J];
RI := Records[I];
if RI.Kind in (KindSUBS + [KindVAR, KindCONST, KindTYPE, KindNAMESPACE]) then
if not RI.Param then
begin
if UpCase then
ok := StrEql(RI.Name, IdentName)
else
ok := RI.Name = IdentName;
if ok then
begin
Level := RI.Level;
if Level > 0 then
ok := Records[Level].Kind = KindNAMESPACE;
end;
if ok then
begin
if L.IndexOf(RI.FullName) = -1 then
begin
R := TUndeclaredIdentRec.Create;
R.Id := I;
R.ErrorIndex := ErrorIndex;
L.AddObject(RI.FullName, R);
end;
end;
end;
end;
K2 := L.Count;
if K1 = K2 then
if L.IndexOf(IdentName) = -1 then
begin
R := TUndeclaredIdentRec.Create;
R.Id := 0;
R.ErrorIndex := ErrorIndex;
L.AddObject(IdentName, R);
end;
end;
procedure TBaseSymbolTable.CreateInterfaceMethodList(IntfId: Integer;
L: TIntegerList);
var
I: Integer;
R: TSymbolRec;
begin
repeat
IntfId := Records[IntfId].TerminalTypeId;
if IntfId = H_IUnknown then
begin
L.Add(H_QueryInterface);
L.Add(H_AddRef);
L.Add(H_Release);
break;
end;
for I:= IntfId + 1 to Card do
begin
R := Records[I];
if R.Level = IntfId then
if R.Kind = kindSUB then
L.Add(I);
end;
if Records[IntfId].SupportedInterfaces = nil then
break;
if Records[IntfId].SupportedInterfaces.Count = 0 then
break;
IntfId := Records[IntfId].SupportedInterfaces[0].Id;
until false;
end;
procedure TBaseSymbolTable.CreateInterfaceMethodList(ClassId, IntfId: Integer;
InterfaceMethodIds,
ClassMethodIds: TIntegerList);
var
I, J, Id, MethodIndex: Integer;
R, RR: TSymbolRec;
Buff: array[0..1000] of Integer;
begin
InterfaceMethodIds.Clear;
ClassMethodIds.Clear;
CreateInterfaceMethodList(IntfId, InterfaceMethodIds);
FillChar(Buff, SizeOf(Buff), 0);
repeat
I := Card;
while I > ClassId do
begin
R := Records[I];
if st_tag > 0 then
if R = SR0 then
begin
I := TLocalSymbolTable(Self).GlobalST.Card;
R := Records[I];
end;
if R.Level = ClassId then
if R.Kind = kindSUB then
begin
for J := InterfaceMethodIds.Count - 1 downto 0 do
begin
Id := InterfaceMethodIds[J];
RR := Records[Id];
if StrEql(R.Name, RR.Name) then
if StrEql(R.Signature, RR.Signature) then
begin
InterfaceMethodIds.RemoveAt(J);
MethodIndex := RR.MethodIndex;
Buff[MethodIndex] := I;
R.PatternId := RR.Id;
break;
end;
end;
end;
Dec(I);
end;
if Records[ClassId].AncestorId = 0 then
break;
if Records[ClassId].AncestorId = H_TObject then
break;
ClassId := Records[ClassId].AncestorId;
until false;
if InterfaceMethodIds.Count > 0 then
Exit;
for I:=1 to 1000 do
begin
Id := Buff[I];
if Id = 0 then
break;
ClassMethodIds.Add(Id);
end;
end;
type
TScriptClassRec = class
public
ClassId: Integer;
AncestorId: Integer;
Processed: Boolean;
PClass: TClass;
VirtualMethodList: TIntegerList;
constructor Create;
destructor Destroy; override;
end;
TScriptClassList = class(TTypedList)
private
function GetRecord(I: Integer): TScriptClassRec;
public
procedure Reset;
function Add: TScriptClassRec;
function FindClass(ClassId: Integer): TScriptClassRec;
property Records[I: Integer]: TScriptClassRec read GetRecord; default;
end;
//-- TScriptClassRec ----------------------------------------------------------
constructor TScriptClassRec.Create;
begin
inherited;
Processed := false;
VirtualMethodList := TIntegerList.Create;
end;
destructor TScriptClassRec.Destroy;
begin
FreeAndNil(VirtualMethodList);
inherited;
end;
//-- TScriptClassList ---------------------------------------------------------
function TScriptClassList.Add: TScriptClassRec;
begin
result := TScriptClassRec.Create;
L.Add(result);
end;
procedure TScriptClassList.Reset;
var
I: Integer;
begin
for I:=0 to Count - 1 do
Records[I].Processed := false;
end;
function TScriptClassList.FindClass(ClassId: Integer): TScriptClassRec;
var
I: Integer;
begin
result := nil;
for I:=0 to Count - 1 do
if Records[I].ClassId = ClassId then
begin
result := Records[I];
Exit;
end;
end;
function TScriptClassList.GetRecord(I: Integer): TScriptClassRec;
begin
result := TScriptClassRec(L[I]);
end;
procedure TBaseSymbolTable.ProcessClassFactory(AClassFactory: Pointer;
AProg: Pointer);
var
ScriptClassList: TScriptClassList;
procedure BuildScriptClassList;
var
I, LevelId: Integer;
R: TSymbolRec;
ScriptClassRec: TScriptClassRec;
begin
for I:=FirstLocalId + 1 to Card do
begin
R := Records[I];
if R.ClassIndex <> -1 then
begin
if R.Host then
continue;
if ScriptClassList.FindClass(R.Id) = nil then
begin
ScriptClassRec := ScriptClassList.Add;
ScriptClassRec.ClassId := R.Id;
ScriptClassRec.PClass := R.PClass;
ScriptClassRec.AncestorId := R.AncestorId;
continue;
end;
end;
if R.Kind in [kindSUB, kindCONSTRUCTOR] then
if (R.CallMode > 0) and (R.DynamicMethodIndex = 0) then
begin
LevelId := R.Level;
if LevelId = 0 then
continue;
if Records[LevelId].Host then
continue;
if Records[LevelId].FinalTypeId <> typeCLASS then
continue;
ScriptClassRec := ScriptClassList.FindClass(LevelId);
if ScriptClassRec = nil then
begin
ScriptClassRec := ScriptClassList.Add;
ScriptClassRec.ClassId := LevelId;
ScriptClassRec.PClass := Records[LevelId].PClass;
ScriptClassRec.AncestorId := Records[LevelId].AncestorId;
end;
ScriptClassRec.VirtualMethodList.Add(R.Id);
end;
end;
end;
var
ClassFactory: TPaxClassFactory;
ClassFactoryRec: TPaxClassFactoryRec;
I, J, SubId, CallMode: Integer;
RR: TSymbolRec;
C, CA: TClass;
ScriptClassRec, AncestorScriptClassRec: TScriptClassRec;
VirtualMethodList: TIntegerList;
b: Boolean;
P, Q: PPointerArray;
MethodIndex: Integer;
Prog: TBaseRunner;
MapRec: TMapRec;
Name, FullName, Signature: String;
Address, Adr: Pointer;
OverCount: Integer;
II, JJ, temp: Integer;
Found: Boolean;
MR, SomeMR: TMapRec;
FileName, ProcName: String;
DestProg: Pointer;
T: Integer;
begin
ClassFactory := TPaxClassFactory(AClassFactory);
Prog := TBaseRunner(AProg);
Prog.ForceMappingEvents;
ClassFactory.SetupParents(Prog, Prog.ClassList);
ClassFactory.AddInheritedMethods;
ScriptClassList := TScriptClassList.Create;
try
BuildScriptClassList;
repeat
b := false;
for I:=0 to ScriptClassList.Count - 1 do
begin
ScriptClassRec := ScriptClassList[I];
if ScriptClassRec.Processed then
continue;
if Records[ScriptClassRec.AncestorId].Host then
begin
ScriptClassRec.Processed := true;
b := true;
end
else
begin
AncestorScriptClassRec := ScriptClassList.FindClass(ScriptClassRec.AncestorId);
if AncestorScriptClassRec.Processed then
begin
ScriptClassRec.Processed := true;
b := true;
end
else
continue;
end;
C := Records[ScriptClassRec.ClassId].PClass;
P := GetVArray(C);
VirtualMethodList := ScriptClassRec.VirtualMethodList;
for J:=0 to VirtualMethodList.Count - 1 do
begin
SubId := VirtualMethodList[J];
CallMode := Records[SubId].CallMode;
Name := Records[SubId].Name;
FullName := Records[SubId].FullName;
Signature := Records[SubId].Signature;
OverCount := Records[SubId].OverCount;
Address := Prog.GetAddressEx(FullName, OverCount, MR);
DestProg := Prog;
if Address = nil then
begin
FileName := ExtractOwner(FullName) + '.' + PCU_FILE_EXT;
ProcName := Copy(FullName, PosCh('.', FullName) + 1, Length(FullName));
Address := Prog.LoadAddressEx(FileName, ProcName, false, OverCount, SomeMR, DestProg);
end;
if CallMode = cmVIRTUAL then
begin
TBaseRunner(DestProg).WrapMethodAddress(Address);
MethodIndex := VirtualMethodIndex(C, Address);
if MethodIndex = -1 then
MethodIndex := GetVirtualMethodCount(C) + 1
else
Inc(MethodIndex); // method index starts from 1, not 0
Records[SubId].MethodIndex := MethodIndex;
P^[MethodIndex - 1] := Address;
MapRec := Prog.ScriptMapTable.LookupEx(FullName, OverCount);
if MapRec <> nil then
MapRec.SubDesc.MethodIndex := MethodIndex;
for II:=0 to ScriptClassList.Count - 1 do
begin
CA := ScriptClassList[II].PClass;
if CA.InheritsFrom(C) and (C <> CA) then
begin
Found := false;
for JJ:=0 to ScriptClassList[II].VirtualMethodList.Count - 1 do
begin
temp := ScriptClassList[II].VirtualMethodList[JJ];
RR := Records[temp];
if RR.MethodIndex = 0 then
if StrEql(Name, RR.Name) then
if StrEql(Signature, RR.Signature) then
begin
Found := true;
RR.MethodIndex := MethodIndex;
Adr := Prog.GetAddress(RR.FullName, MR);
Prog.WrapMethodAddress(Adr);
Q := GetVArray(CA);
Q^[MethodIndex - 1] := Adr;
MapRec := Prog.ScriptMapTable.LookupEx(RR.FullName, RR.OverCount);
if MapRec <> nil then
MapRec.SubDesc.MethodIndex := MethodIndex;
break;
end;
end;
if not Found then
begin
Q := GetVArray(CA);
Q^[MethodIndex - 1] := Address;
end;
end;
end;
end;
end;
end;
if b = false then
break;
until false;
// process overriden methods
ScriptClassList.Reset;
repeat
b := false;
for I:=0 to ScriptClassList.Count - 1 do
begin
ScriptClassRec := ScriptClassList[I];
if ScriptClassRec.Processed then
continue;
if Records[ScriptClassRec.AncestorId].Host then
begin
ScriptClassRec.Processed := true;
b := true;
end
else
begin
AncestorScriptClassRec := ScriptClassList.FindClass(ScriptClassRec.AncestorId);
if AncestorScriptClassRec.Processed then
begin
ScriptClassRec.Processed := true;
b := true;
end
else
continue;
end;
C := Records[ScriptClassRec.ClassId].PClass;
P := GetVArray(C);
VirtualMethodList := ScriptClassRec.VirtualMethodList;
for J:=0 to VirtualMethodList.Count - 1 do
begin
SubId := VirtualMethodList[J];
CallMode := Records[SubId].CallMode;
Name := Records[SubId].Name;
FullName := Records[SubId].FullName;
Signature := Records[SubId].Signature;
OverCount := Records[SubId].OverCount;
Address := Prog.GetAddressEx(FullName, OverCount, MR);
Prog.WrapMethodAddress(Address);
if CallMode = cmOVERRIDE then
begin
MethodIndex := Records[SubId].MethodIndex;
if MethodIndex = 0 then
begin
temp := LookupParentMethod(SubId, true, true);
if temp = 0 then
if Records[SubId].DynamicMethodIndex = 0 then
RaiseError(errInternalError, []);
if Records[temp].MethodIndex = 0 then
begin
{$IFDEF UNIC}
if StrEql(Records[SubId].Name, 'toString') then
begin
T := Records[SubId].Level;
ClassFactoryRec := ClassFactory.FindRecordByFullName(Records[T].FullName);
if ClassFactoryRec = nil then
RaiseError(errInternalError, []);
vmtToStringSlot(ClassFactoryRec.VMTPtr)^ := Address;
continue;
end
else if StrEql(Records[SubId].Name, 'GetHashCode') then
begin
T := Records[SubId].Level;
ClassFactoryRec := ClassFactory.FindRecordByFullName(Records[T].FullName);
if ClassFactoryRec = nil then
RaiseError(errInternalError, []);
vmtGetHashCodeSlot(ClassFactoryRec.VMTPtr)^ := Address;
continue;
end
else if StrEql(Records[SubId].Name, 'Equals') then
begin
T := Records[SubId].Level;
ClassFactoryRec := ClassFactory.FindRecordByFullName(Records[T].FullName);
if ClassFactoryRec = nil then
RaiseError(errInternalError, []);
vmtEqualsSlot(ClassFactoryRec.VMTPtr)^ := Address;
continue;
end;
{$ENDIF}
RaiseError(errInternalError, []);
end;
MethodIndex := Records[temp].MethodIndex;
Records[SubId].MethodIndex := MethodIndex;
end;
P^[MethodIndex - 1] := Address;
MapRec := Prog.ScriptMapTable.LookupEx(FullName, OverCount);
if MapRec <> nil then
MapRec.SubDesc.MethodIndex := MethodIndex;
for II:=0 to ScriptClassList.Count - 1 do
begin
CA := ScriptClassList[II].PClass;
if CA.InheritsFrom(C) and (C <> CA) then
begin
Found := false;
for JJ:=0 to ScriptClassList[II].VirtualMethodList.Count - 1 do
begin
temp := ScriptClassList[II].VirtualMethodList[JJ];
RR := Records[temp];
if RR.MethodIndex = 0 then
if StrEql(Name, RR.Name) then
if StrEql(Signature, RR.Signature) then
begin
Found := true;
RR.MethodIndex := MethodIndex;
Adr := Prog.GetAddress(RR.FullName, MR);
Prog.WrapMethodAddress(Adr);
Q := GetVArray(CA);
Q^[MethodIndex - 1] := Adr;
MapRec := Prog.ScriptMapTable.LookupEx(RR.FullName, RR.OverCount);
if MapRec <> nil then
MapRec.SubDesc.MethodIndex := MethodIndex;
break;
end;
end;
if not Found then
begin
Q := GetVArray(CA);
Q^[MethodIndex - 1] := Address;
end;
end;
end;
end;
end;
end;
if b = false then
break;
until false;
finally
FreeAndNil(ScriptClassList);
end;
end;
function TBaseSymbolTable.RegisterSpace(K: Integer): Integer;
var
I: Integer;
begin
result := Card;
for I:=1 to K do
AddRecord;
end;
procedure TBaseSymbolTable.HideClass(C: TClass);
var
I: Integer;
R: TSymbolRec;
begin
for I := 1 to Card do
begin
R := Records[I];
if R = SR0 then
continue;
if R.PClass <> nil then
if R.PClass = C then
if R.Kind = KindTYPE then
begin
R.Name := '@' + R.Name;
Exit;
end;
end;
end;
function TBaseSymbolTable.ImportFromTable(st: TBaseSymbolTable;
const FullName: String;
UpCase: Boolean;
DoRaiseError: Boolean = true): Integer;
function TranslateId(Id: Integer): Integer;
var
S: String;
begin
S := st[Id].FullName;
result := LookupFullName(S, UpCase);
if result = 0 then
result := ImportFromTable(st, S, UpCase);
end;
var
I, J, Id, Id1, Id2, FinTypeId, Kind, LevelId, TypeBaseId,
OriginTypeId, FieldTypeId, RangeTypeId, ElemTypeId: Integer;
S, TypeName: String;
RI: TSymbolRec;
B1, B2: Integer;
ResTypeId, ParamId, ParamTypeId, H_Sub, OriginId: Integer;
PClass: TClass;
GUID: TGUID;
D: packed record
D1, D2: Double;
end;
IsGlobalMember: Boolean;
MethodClass: TClass;
MethodIndex: Integer;
OverList: TIntegerList;
begin
result := 0;
Id := st.LookupFullName(FullName, UpCase);
if id = 0 then
begin
if DoRaiseError then
RaiseError(errUndeclaredIdentifier, [FullName]);
Exit;
end;
MethodClass := nil;
LevelId := st[Id].Level;
if LevelId > 0 then
begin
IsGlobalMember := st[LevelId].Kind = kindNAMESPACE;
if not IsGlobalMember then
if st[LevelId].FinalTypeId = typeCLASS then
MethodClass := st[LevelId].PClass;
LevelId := TranslateId(LevelId);
end
else
IsGlobalMember := true;
Kind := st[id].Kind;
FinTypeId := st[Id].FinalTypeId;
case Kind of
kindTYPE:
if FinTypeId in (StandardTypes - [typeENUM]) then
begin
TypeName := ExtractName(FullName);
if st[id].PatternId = 0 then // this is a subrange type
begin
Id1 := st.GetLowBoundRec(id).Id;
Id2 := st.GetHighBoundRec(id).Id;
B1 := st[Id1].Value;
B2 := st[Id2].Value;
TypeBaseId := TranslateId(st[id].TypeID);
result := RegisterSubrangeType(LevelId, TypeName,
TypeBaseId,
B1, B2);
end
else // this is an alias type
begin
OriginTypeId := TranslateId(st[id].PatternId);
result := RegisterTypeAlias(LevelId, TypeName, OriginTypeId);
end;
end
else if FinTypeId = typePOINTER then
begin
TypeName := ExtractName(FullName);
OriginTypeId := TranslateId(st[id].PatternId);
result := RegisterPointerType(LevelId, TypeName, OriginTypeId);
end
else if FinTypeId = typeRECORD then
begin
TypeName := ExtractName(FullName);
result := RegisterRecordType(LevelId, TypeName, st[Id].DefaultAlignment);
for I := Id + 1 to st.Card do
begin
RI := st[I];
if RI = SR0 then
break;
if RI.Kind = kindTYPE_FIELD then
if RI.Level = Id then
begin
FieldTypeId := TranslateId(RI.TypeID);
RegisterTypeField(result, RI.Name, FieldTypeId, RI.Shift);
end;
end;
end // typeRECORD
else if FinTypeId = typeARRAY then
begin
TypeName := ExtractName(FullName);
st.GetArrayTypeInfo(id, RangeTypeId, ElemTypeId);
RangeTypeId := TranslateId(RangeTypeId);
ElemTypeId := TranslateId(ElemTypeId);
result := RegisterArrayType(LevelId, TypeName,
RangeTypeId, ElemTypeId, st[Id].DefaultAlignment);
end // type ARRAY
else if FinTypeId = typeDYNARRAY then
begin
TypeName := ExtractName(FullName);
ElemTypeId := TranslateId(st[id].PatternId);
result := RegisterDynamicArrayType(LevelId, TypeName, ElemTypeId);
end
else if FinTypeId = typeENUM then
begin
TypeName := ExtractName(FullName);
TypeBaseId := TranslateId(st[id].PatternId);
result := RegisterEnumType(LevelId, TypeName, TypeBaseId);
for I := Id + 1 to st.Card do
begin
RI := st[I];
if RI = SR0 then
break;
if RI.Kind = KindTYPE then
break;
if RI.Kind = kindCONST then
if RI.TypeId = Id then
RegisterEnumValue(result, RI.Name, RI.Value);
end;
end // typeENUM
else if FinTypeId = typePROC then
begin
TypeName := ExtractName(FullName);
OriginId := TranslateId(st[id].PatternId);
result := RegisterProceduralType(LevelId, TypeName, Records[OriginId].Shift);
end
else if FinTypeId = typeEVENT then
begin
TypeName := ExtractName(FullName);
OriginId := TranslateId(st[id].PatternId);
result := RegisterEventType(LevelId, TypeName, Records[OriginId].Shift);
end
else if FinTypeId = typeSET then
begin
TypeName := ExtractName(FullName);
OriginTypeId := TranslateId(st[id].PatternId);
result := RegisterSetType(LevelId, TypeName, OriginTypeId);
end
else if FinTypeId = typeCLASSREF then
begin
TypeName := ExtractName(FullName);
OriginTypeId := TranslateId(st[id].PatternId);
result := RegisterClassReferenceType(LevelId, TypeName, OriginTypeId);
end
else if FinTypeId = typeCLASS then
begin
PClass := st[id].PClass;
result := RegisterClassType(LevelId, PClass);
for I := Id + 1 to st.Card do
begin
RI := st[I];
if RI = SR0 then
break;
if RI.Kind = kindTYPE_FIELD then
if RI.Level = Id then
begin
FieldTypeId := TranslateId(RI.TypeID);
RegisterTypeField(result, RI.Name, FieldTypeId, RI.Shift);
end;
end;
end
else if FinTypeId = typeINTERFACE then
begin
TypeName := ExtractName(FullName);
D.D1 := st[Id + 1].Value;
D.D2 := st[Id + 2].Value;
Move(D, GUID, SizeOf(GUID));
result := RegisterInterfaceType(LevelId, TypeName, GUID);
end
else
RaiseError(errInternalError, []);
// kindTYPE
kindSUB:
begin
S := ExtractName(FullName);
ResTypeId := TranslateId(st[Id].TypeID);
OverList := TIntegerList.Create;
try
OverList := st.LookUpSub(S,
LevelId,
UpCase);
for J := 0 to OverList.Count - 1 do
begin
Id := OverList[J];
if IsGlobalMember then
begin
H_Sub := RegisterRoutine(LevelId, S, ResTypeId,
st[Id].CallConv, st[id].Address);
result := LastSubId;
end
else
begin
H_Sub := RegisterMethod(LevelId, S, ResTypeId, st[Id].CallConv,
st[Id].Address, st[Id].IsSharedMethod,
st[Id].CallMode,
st[Id].MethodIndex);
result := LastSubId;
Self[LastSubId].IsFakeMethod := st[id].IsFakeMethod;
if MethodClass <> nil then
begin
MethodIndex := VirtualMethodIndex(MethodClass,
st[Id].Address) + 1;
if MethodIndex > 0 then
Records[LastSubId].MethodIndex := MethodIndex;
end;
Records[LastSubId].CallMode := st[id].CallMode;
end;
Records[result].OverCount := st[id].OverCount;
for I := 0 to st[id].Count - 1 do
begin
ParamId := st.GetParamId(id, I);
ParamTypeId := TranslateId(st[ParamId].TypeId);
RegisterParameter(H_Sub, ParamTypeId, st[ParamId].Value,
st[ParamId].ByRef, st[ParamId].Name);
Records[Card].IsConst := st[ParamId].IsConst;
Records[Card].IsOpenArray := st[ParamId].IsOpenArray;
Records[Card].Optional := st[ParamId].Optional;
end;
end;
finally
FreeAndNil(OverList);
end;
end; // KindSUB
KindCONSTRUCTOR:
begin
S := ExtractName(FullName);
OverList := TIntegerList.Create;
try
OverList := st.LookUpSub(S,
LevelId,
UpCase);
for J := 0 to OverList.Count - 1 do
begin
Id := OverList[J];
H_Sub := RegisterConstructor(LevelId, S, st[id].Address,
st[id].IsSharedMethod,
st[Id].CallConv);
result := LastSubId;
if MethodClass <> nil then
begin
MethodIndex := VirtualMethodIndex(MethodClass, st[id].Address) + 1;
if MethodIndex > 0 then
Records[result].MethodIndex := MethodIndex;
end;
Records[result].OverCount := st[id].OverCount;
for I := 0 to st[id].Count - 1 do
begin
ParamId := st.GetParamId(id, I);
ParamTypeId := TranslateId(st[ParamId].TypeId);
RegisterParameter(H_Sub, ParamTypeId, st[ParamId].Value,
st[ParamId].ByRef, st[ParamId].Name);
Records[Card].IsConst := st[ParamId].IsConst;
Records[Card].IsOpenArray := st[ParamId].IsOpenArray;
Records[Card].Optional := st[ParamId].Optional;
end;
end;
finally
FreeAndNil(OverList);
end;
end;
KindDESTRUCTOR:
begin
S := ExtractName(FullName);
RegisterMethod(LevelId, S, TypeVOID,
st[id].CallConv, st[id].Address, false,
cmOVERRIDE,
0);
result := LastSubId;
Records[result].Kind := kindDESTRUCTOR;
end;
KindVAR:
begin
S := ExtractName(FullName);
result := RegisterVariable(LevelId, S,
TranslateId(st[Id].TypeID), st[id].Address);
end;
KindCONST:
begin
S := ExtractName(FullName);
result := RegisterConstant(LevelId, S,
TranslateId(st[Id].TypeID), st[id].Value);
end;
end;
end;
function TBaseSymbolTable.GetOpenArrayHighId(Id: Integer): Integer;
begin
if Records[Id].Kind = KindVAR then
Id := Records[Id].TypeId;
result := Id;
while Records[result].Kind <> KindVAR do
Inc(result);
end;
function TBaseSymbolTable.GetOuterThisId(TypeId: Integer): Integer;
var
I: Integer;
R: TSymbolRec;
begin
result := 0;
CheckError(TypeId = 0);
if Records[TypeId].Kind <> KindTYPE then
Exit;
if Records[TypeId].FinalTypeId <> typeCLASS then
Exit;
for I := TypeId + 1 to Card do
begin
R := Records[I];
if R.Level = TypeId then
if R.Kind = KindTYPE_FIELD then
if R.Name = StrOuterThis then
begin
result := I;
Exit;
end;
end;
end;
function TBaseSymbolTable.HasAbstractAncestor(ClassId: Integer): Boolean;
begin
result := false;
repeat
ClassId := Records[ClassId].AncestorId;
if ClassId = 0 then
Exit;
if Records[ClassId].IsAbstract then
begin
result := true;
break;
end;
until false;
end;
function TBaseSymbolTable.GetTypeParameters(Id: Integer): TIntegerList;
var
I: Integer;
R: TSymbolRec;
b: Boolean;
begin
result := TIntegerList.Create;
R := Records[Id];
if R.Kind = KindTYPE then
begin
if not R.IsGeneric then
Exit;
b := false;
for I := Id + 1 to Card do
begin
R := Records[I];
if (R.Kind = KindTYPE) and (R.TypeId = typeTYPEPARAM) then
begin
b := true;
result.Add(I);
end
else if b then
Exit;
end;
end
else if R.Kind in KindSUBS then
begin
if not Records[R.Level].IsGeneric then
Exit;
b := false;
for I := Id + 1 to Card do
begin
R := Records[I];
if (R.Kind = KindTYPE) and (R.TypeId = typeTYPEPARAM) then
begin
b := true;
result.Add(I);
end
else if b then
Exit;
end;
end;
end;
function TBaseSymbolTable.ExtractEnumNames(EnumTypeId: Integer): TStringList;
var
I: Integer;
R: TSymbolRec;
begin
result := TStringList.Create;
for I:=EnumTypeId + 1 to Card do
begin
R := Records[I];
if R = SR0 then
break;
if R.Kind in [KindTYPE, KindSUB, KindNAMESPACE] then
break;
if R.TypeId = EnumTypeId then
if R.Name <> '' then
result.Add(R.Name);
end;
end;
function IsFrameworkTypeId(Id: Integer): Boolean;
begin
result := (Id = H_TFW_Boolean) or
(Id = H_TFW_ByteBool) or
(Id = H_TFW_WordBool) or
(Id = H_TFW_LongBool) or
(Id = H_TFW_Byte) or
(Id = H_TFW_SmallInt) or
(Id = H_TFW_ShortInt) or
(Id = H_TFW_Word) or
(Id = H_TFW_Cardinal) or
(Id = H_TFW_Double) or
(Id = H_TFW_Single) or
(Id = H_TFW_Extended) or
(Id = H_TFW_Currency) or
(Id = H_TFW_AnsiChar) or
(Id = H_TFW_WideChar) or
(Id = H_TFW_Integer) or
(Id = H_TFW_Int64) or
(Id = H_TFW_Variant) or
(Id = H_TFW_DateTime) or
(Id = H_TFW_AnsiString) or
(Id = H_TFW_UnicString) or
(Id = H_TFW_Array);
end;
function TBaseSymbolTable.GetSizeOfPointer: Integer;
begin
result := SizeOf(Pointer);
if Types.PAX64 then
result := 8;
end;
function TBaseSymbolTable.GetSizeOfTMethod: Integer;
begin
result := SizeOfPointer * 2;
end;
procedure TBaseSymbolTable.SetPAX64(value: Boolean);
var
I: Integer;
R: TSymbolRec;
begin
Types.PAX64 := value;
if value then
begin
H_ExceptionPtr := H_ExceptionPtr_64;
H_ByteCodePtr := H_ByteCodePtr_64;
H_Flag := H_Flag_64;
H_SkipPop := H_SkipPop_64;
FirstShiftValue := FirstShiftValue_64;
end
else
begin
H_ExceptionPtr := H_ExceptionPtr_32;
H_ByteCodePtr := H_ByteCodePtr_32;
H_Flag := H_Flag_32;
H_SkipPop := H_SkipPop_32;
FirstShiftValue := FirstShiftValue_32;
end;
for I := Types.Count + 1 to Card do
begin
R := Records[I];
if R <> SR0 then
if R.Shift <> 0 then
begin
R.Completed := false;
R.FinSize := -1;
end;
end;
end;
function TBaseSymbolTable.LookupAnonymousInterface(ClassId: Integer): Integer;
var
I, J, SubId: Integer;
List: TIntegerList;
S: String;
begin
result := 0;
SubId := 0;
for I := ClassId + 1 to Card do
begin
if Records[I].Kind = KindSUB then
if Records[I].Level = ClassId then
begin
SubId := I;
break;
end;
end;
if SubId = 0 then
Exit;
if Records[SubId].Name <> ANONYMOUS_METHOD_NAME then
RaiseError(errInternalError, []);
S := UpperCase(Records[SubId].SignatureEx);
List := HashArray.GetList(ANONYMOUS_METHOD_NAME);
for J := List.Count - 1 downto 0 do
begin
I := List[J];
if I = SubId then
continue;
with Records[I] do
begin
if Kind <> KindSUB then
continue;
if Level = 0 then
continue;
if Name <> ANONYMOUS_METHOD_NAME then
continue;
if Records[Level].FinalTypeId <> typeINTERFACE then
continue;
if UpperCase(Records[I].SignatureEx) <> S then
continue;
result := Level;
Exit;
end;
end;
end;
function TBaseSymbolTable.LookupAnonymousMethod(IntfId: Integer): Integer;
var
I: Integer;
begin
result := 0;
for I := IntfId + 1 to Card do
begin
if Records[I].Kind = KindSUB then
if Records[I].Level = IntfId then
begin
if Records[I].Name = ANONYMOUS_METHOD_NAME then
result := I;
break;
end;
end;
end;
function TBaseSymbolTable.GetTypeHelpers(TypeId: Integer): TIntegerList;
procedure Collect(T: Integer);
var
I: Integer;
begin
for I := TypeHelpers.Count - 1 downto 0 do
if TypeHelpers.Values[I] = T then
result.Add(TypeHelpers.Keys[I]);
end;
begin
result := TIntegerList.Create(true);
Collect(TypeId);
if Records[TypeId].HasPAnsiCharType or Records[TypeId].HasPWideCharType then
begin
{$IFNDEF PAXARM}
Collect(typeANSISTRING);
Collect(typeWIDESTRING);
Collect(typeSHORTSTRING);
{$ENDIF}
Collect(typeUNICSTRING);
end;
end;
end.
|
{ *********************************************************************** }
{ }
{ Author: Yanniel Alvarez Alfonso }
{ Description: Miscellaneous routines }
{ Copyright (c) ????-2012 Pinogy Corporation }
{ }
{ *********************************************************************** }
unit MiscUtils;
interface
uses
Windows, SysUtils, Classes;
function ExecuteProgram(aExecutable, ParamStr: string;
var ProcID: DWord; aWait: Boolean): DWord;
function ConnectNetDrive(aUNCPath, aUsername, aPassword: string; out aDrive: string): Boolean;
function DisconnectNetDrive(aDrive: string): Boolean;
function GetResourceAsString(ResName: pchar; ResType: pchar): string;
procedure StrToFile(aStr, aFileName: String);
function GetComputerNetName: string;
implementation
uses
Forms, NetDrive;
function ExecuteProgram(aExecutable, ParamStr: string;
var ProcID: DWord; aWait: Boolean): DWord;
var
StartInfo: TStartupInfo;
ProcInfo: TProcessInformation;
CreateOK: Boolean;
ErrorCode,
AppDone: DWord;
begin
ErrorCode:= 0;
FillChar(StartInfo, SizeOf(TStartupInfo), #0);
FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
StartInfo.cb:= SizeOf(TStartupInfo);
CreateOK:= Windows.CreateProcess(nil,
PChar(aExecutable + ' ' + ParamStr),
nil, nil, False,
CREATE_NEW_PROCESS_GROUP + IDLE_PRIORITY_CLASS + SYNCHRONIZE,
nil, nil, StartInfo, ProcInfo);
WaitForInputIdle(ProcInfo.hProcess, INFINITE);
if CreateOK then
if aWait then
begin
repeat
AppDone:= WaitForSingleObject(ProcInfo.hProcess, 10);
Application.ProcessMessages;
until AppDone <> WAIT_TIMEOUT;
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end
else
procid:= ProcInfo.hProcess;
GetExitCodeProcess(ProcInfo.hProcess, ErrorCode);
Result:= ErrorCode;
end;
function ConnectNetDrive(aUNCPath, aUsername, aPassword: string; out aDrive: string): Boolean;
var
NetFolder: TNetDrive;
Error: string;
begin
if aUNCPath = '' then Exit;
Result:= False;
NetFolder:= TNetDrive.Create(nil);
try
NetFolder.Connect(aUNCPath, aUsername, aPassword, Error);
Result:= (Length(NetFolder.Drive) >= 2) and
(NetFolder.Drive[Length(NetFolder.Drive)] = ':');
if Result then
aDrive:= NetFolder.Drive;
finally
NetFolder.Free;
end;
end;
function DisconnectNetDrive(aDrive: string): Boolean;
var
NetFolder: TNetDrive;
Error: string;
begin
if aDrive = '' then Exit;
Result:= False;
NetFolder:= TNetDrive.Create(nil);
try
NetFolder.Drive:= aDrive;
Result:= NetFolder.Disconnect(Error);
finally
NetFolder.Free;
end;
end;
function GetResourceAsPointer(ResName: pchar; ResType: pchar;
out Size: longword): pointer;
var
InfoBlock: HRSRC;
GlobalMemoryBlock: HGLOBAL;
begin
InfoBlock := FindResource(hInstance, resname, restype);
if InfoBlock = 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
size := SizeofResource(hInstance, InfoBlock);
if size = 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
GlobalMemoryBlock := LoadResource(hInstance, InfoBlock);
if GlobalMemoryBlock = 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
Result := LockResource(GlobalMemoryBlock);
if Result = nil then
raise Exception.Create(SysErrorMessage(GetLastError));
end;
function GetResourceAsString(ResName: pchar; ResType: pchar): string;
var
ResData: PChar;
ResSize: Longword;
begin
ResData := GetResourceAsPointer(resname, restype, ResSize);
SetString(Result, ResData, ResSize);
end;
procedure StrToFile(aStr, aFileName: String);
var
Stream: TStream;
begin
Stream := TFileStream.Create(aFileName, fmCreate);
try
Stream.WriteBuffer(Pointer(aStr)^, Length(aStr));
finally
Stream.Free;
end;
end;
function GetComputerNetName: string;
var
nBuffer: array[0..255] of char;
nSize: dword;
begin
Result := '';
nSize := 256;
if GetComputerName(nBuffer, nSize) then
Result := Trim(nBuffer);
end;
end.
|
unit LrTabs;
interface
uses
SysUtils, Windows, Types, Classes, Controls, Graphics, StdCtrls;
type
TLrCustomTabs = class(TCustomControl)
private
FTabCount: Integer;
FSelectedIndex: Integer;
FAlignment: TAlignment;
protected
function GetMouseTab(var inX: Integer): Integer;
function GetTabWidth: Integer; virtual; abstract;
procedure SetAlignment(const Value: TAlignment);
procedure SetSelectedIndex(const Value: Integer);
procedure SetTabCount(const Value: Integer);
protected
// procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure TabClick(inIndex, inX, inY: Integer); virtual;
public
constructor Create(inOwner: TComponent); override;
published
property Align;
property Alignment: TAlignment read FAlignment write SetAlignment
default taLeftJustify;
property SelectedIndex: Integer read FSelectedIndex write SetSelectedIndex
default 0;
property TabCount: Integer read FTabCount write SetTabCount
default 0;
property Visible;
end;
//
TLrTabs = class(TLrCustomTabs)
private
FImageList: TImageList;
protected
function GetImageWidth: Integer;
function GetTabWidth: Integer; override;
procedure SetImageList(const Value: TImageList);
protected
procedure Paint; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure TabClick(inIndex, inX, inY: Integer); override;
published
property ImageList: TImageList read FImageList write SetImageList;
end;
//
TLrTabs2 = class(TLrCustomTabs)
protected
function GetTabWidth: Integer; override;
protected
procedure Paint; override;
procedure TabClick(inIndex, inX, inY: Integer); override;
end;
implementation
uses
Math;
{ TLrCustomTabs }
constructor TLrCustomTabs.Create(inOwner: TComponent);
begin
inherited;
FAlignment := taLeftJustify;
end;
function TLrCustomTabs.GetMouseTab(var inX: Integer): Integer;
var
d, m: Word;
begin
DivMod(inX, GetTabWidth, d, m);
Result := d;
inX := m;
end;
procedure TLrCustomTabs.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
t: Integer;
begin
t := GetMouseTab(X);
TabClick(t, X, Y);
end;
procedure TLrCustomTabs.TabClick(inIndex, inX, inY: Integer);
begin
SelectedIndex := inIndex;
end;
procedure TLrCustomTabs.SetAlignment(const Value: TAlignment);
begin
FAlignment := Value;
Invalidate;
end;
procedure TLrCustomTabs.SetSelectedIndex(const Value: Integer);
begin
FSelectedIndex := Value;
Invalidate;
end;
procedure TLrCustomTabs.SetTabCount(const Value: Integer);
begin
FTabCount := Value;
Invalidate;
end;
{ TLrTabs }
const
TT_SELSTART = 0;
TT_SELBAR = 1;
TT_SELEND = 2;
TT_SELDIVIDE = 3;
TT_START = 4;
TT_BAR = 5;
TT_END = 6;
TT_DIVIDE = 7;
TT_BACK = 8;
BAR_SEGS = 4;
function TLrTabs.GetImageWidth: Integer;
begin
if ImageList <> nil then
Result := ImageList.Width
else
Result := 1;
end;
function TLrTabs.GetTabWidth: Integer;
begin
Result := GetImageWidth * (BAR_SEGS + 1);
end;
procedure TLrTabs.TabClick(inIndex, inX, inY: Integer);
begin
if (inX < GetTabWidth) and (inIndex > 0) and (inIndex <> SelectedIndex) then
Dec(inIndex);
inherited;
end;
procedure TLrTabs.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
if (AComponent = FImageList) then
FImageList := nil;
end;
procedure TLrTabs.Paint;
var
iw, w, x, i, j, iis, iib, iie: Integer;
begin
inherited;
if ImageList <> nil then
begin
iw := ImageList.Width;
//
case Alignment of
taCenter:
begin
w := TabCount * (BAR_SEGS + 1) * iw;
x := (Width - w) div 2;
if (x < 0) then
x := 0;
i := 0;
while (i < x) do
begin
ImageList.Draw(Canvas, i, 0, TT_BACK);
Inc(i, iw);
end;
end;
//
else x := 0;
end;
//
for i := 0 to Pred(TabCount) do
begin
if SelectedIndex = i then
begin
iis := TT_SELSTART;
iib := TT_SELBAR;
if (i < Pred(TabCount)) then
iie := TT_SELDIVIDE
else
iie := TT_SELEND;
end
else begin
if (i = 0) then
iis := TT_START
else
iis := -1;
iib := TT_BAR;
if (i = Pred(TabCount)) then
iie := TT_END
else if (SelectedIndex <> i + 1) then
iie := TT_DIVIDE
else
iie := -1;
end;
if iis <> -1 then
begin
ImageList.Draw(Canvas, x, 0, iis);
Inc(x, iw);
end;
for j := 1 to BAR_SEGS do
begin
ImageList.Draw(Canvas, x, 0, iib);
Inc(x, iw);
end;
if SelectedIndex = i then
Canvas.Font.Style := [ fsBold ]
else
Canvas.Font.Style := [ ];
SetBkMode(Canvas.Handle, Windows.TRANSPARENT);
Canvas.TextOut(x - iw*BAR_SEGS + 6, 2, 'Tab ' + IntToStr(i));
if iie <> -1 then
begin
ImageList.Draw(Canvas, x, 0, iie);
Inc(x, iw);
end;
end;
while x < ClientWidth do
begin
ImageList.Draw(Canvas, x, 0, TT_BACK);
Inc(x, iw);
end;
end;
end;
procedure TLrTabs.SetImageList(const Value: TImageList);
begin
if FImageList <> nil then
FImageList.RemoveFreeNotification(Self);
FImageList := Value;
if FImageList <> nil then
FImageList.FreeNotification(Self);
Invalidate;
end;
{ TLrTabs2 }
function TLrTabs2.GetTabWidth: Integer;
begin
Result := 64;
end;
procedure TLrTabs2.Paint;
var
r: TRect;
i: Integer;
begin
inherited;
r := Rect(0, 0, GetTabWidth, 24);
for i := 0 to Pred(TabCount) do
begin
if SelectedIndex = i then
Canvas.Brush.Color := clWhite
else
Canvas.Brush.Color := clBtnFace;
Canvas.RoundRect(r.Left, r.Top, r.Right, r.Bottom, 8, 8);
OffsetRect(r, GetTabWidth, 0);
end;
end;
procedure TLrTabs2.TabClick(inIndex, inX, inY: Integer);
begin
inherited;
end;
end.
|
{------------------------------------
功能说明:接口工厂
创建日期:2014/08/12
作者:mx
版权:mx
-------------------------------------}
unit uSysFactory;
interface
uses Classes, SysUtils, uFactoryIntf, uSysSvc;
type
//工厂基类
TBaseFactory = class(TInterfacedObject, ISysFactory)
private
protected
FIntfGUID: TGUID;
{ISysFactory}
procedure CreateInstance(const IID: TGUID; out Obj); virtual; abstract;
procedure ReleaseInstance; virtual; abstract;
function Supports(IID: TGUID): Boolean; virtual;
public
constructor Create(const IID: TGUID); //virtual;
destructor Destroy; override;
end;
//接口工厂 通过本工厂注册的接口用户每次获取接口都会创建一个实例,当用户使用完成后自动释放实例.
TIntfFactory = class(TBaseFactory)
private
FIntfCreatorFunc: TIntfCreatorFunc;
protected
procedure CreateInstance(const IID: TGUID; out Obj); override;
procedure ReleaseInstance; override;
public
constructor Create(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc); virtual;
destructor Destroy; override;
end;
//单例工厂 通过本工厂注册的接口不管用户获取多少次接口,内存中都只有一个实例,而且只有到退出系统才会释放这个实例.
TSingletonFactory = class(TIntfFactory)
private
FInstance: IInterface;
protected
procedure CreateInstance(const IID: TGUID; out Obj); override;
procedure ReleaseInstance; override;
public
constructor Create(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc); override;
destructor Destroy; override;
end;
//实例工厂 实例工厂注册方式和前两种不一样,它主要用于把外部对象实现的接口注册进系统.
//比如主窗体实现了IMainForm,因为程序运行时主窗体已经创建了,这时就需要用TObjFactory向系统注册IMainform接口.
//注意:系统不允许使用TObjFactory或TObjFactoryEx注册由TInterfacedObject对象及其子类实现的接口,
//因为TInterfacedObject在接口引用计数为0时会自动释放,这样很容易引发实例被提前释放或重复释放的问题.
TObjFactory = class(TBaseFactory)
private
FOwnsObj: Boolean;
FInstance: TObject;
FRefIntf: IInterface;
protected
procedure CreateInstance(const IID: TGUID; out Obj); override;
procedure ReleaseInstance; override;
public
constructor Create(IID: TGUID; Instance: TObject; OwnsObj: Boolean = False);
destructor Destroy; override;
end;
//在其它包中可以通过这个来注册
TRegInf = class(TInterfacedObject, IRegInf)
private
protected
{IRegSysFactory}
procedure RegIntfFactory(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc);
procedure RegSingletonFactory(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc);
procedure RegObjFactory(IID: TGUID; Instance: TObject; OwnsObj: Boolean = False);
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses uSysFactoryMgr;
const
Err_IntfExists = '接口%s已存在,不能重复注册!';
Err_IntfNotSupport = '对象不支持%s接口!';
{ TBaseFactory }
constructor TBaseFactory.Create(const IID: TGUID);
begin
if FactoryManager.Exists(IID) then
begin
raise Exception.CreateFmt(Err_IntfExists, [GUIDToString(IID)]);
end;
FIntfGUID := IID;
FactoryManager.RegistryFactory(Self);
end;
destructor TBaseFactory.Destroy;
begin
inherited;
end;
function TBaseFactory.Supports(IID: TGUID): Boolean;
begin
Result := IsEqualGUID(IID, FIntfGUID);
end;
{ TIntfFactory }
constructor TIntfFactory.Create(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc);
begin
self.FIntfCreatorFunc := IntfCreatorFunc;
inherited Create(IID);
end;
procedure TIntfFactory.CreateInstance(const IID: TGUID; out Obj);
var
tmpIntf: IInterface;
begin
self.FIntfCreatorFunc(tmpIntf);
tmpIntf.QueryInterface(IID, Obj);
end;
destructor TIntfFactory.Destroy;
begin
inherited;
end;
procedure TIntfFactory.ReleaseInstance;
begin
end;
{ TSingletonFactory }
constructor TSingletonFactory.Create(IID: TGUID;
IntfCreatorFunc: TIntfCreatorFunc);
begin
FInstance := nil;
inherited Create(IID, IntfCreatorFunc);
end;
procedure TSingletonFactory.CreateInstance(const IID: TGUID; out Obj);
begin
if FInstance = nil then
inherited Createinstance(IID, FInstance);
if FInstance.QueryInterface(IID, Obj) <> S_OK then
raise Exception.CreateFmt(Err_IntfNotSupport, [GUIDToString(IID)]);
end;
destructor TSingletonFactory.Destroy;
begin
FInstance := nil;
inherited;
end;
procedure TSingletonFactory.ReleaseInstance;
begin
FInstance := nil; //释放
end;
{ TObjFactory }
constructor TObjFactory.Create(IID: TGUID; Instance: TObject; OwnsObj: Boolean);
begin
if not Instance.GetInterface(IID, FRefIntf) then
raise Exception.CreateFmt('对象%s未实现%s接口!', [Instance.ClassName, GUIDToString(IID)]);
if (Instance is TInterfacedObject) then
raise Exception.Create('不要用TObjFactory注册TInterfacedObject及其子类实现的接口!');
FOwnsObj := OwnsObj;
FInstance := Instance;
inherited Create(IID);
end;
procedure TObjFactory.CreateInstance(const IID: TGUID; out Obj);
begin
IInterface(Obj) := FRefIntf;
end;
destructor TObjFactory.Destroy;
begin
inherited;
end;
procedure TObjFactory.ReleaseInstance;
begin
inherited;
FRefIntf := nil;
if FOwnsObj then
FreeAndNil(FInstance);
end;
{ TRegSysFactory }
constructor TRegInf.Create;
begin
end;
destructor TRegInf.Destroy;
begin
inherited;
end;
procedure TRegInf.RegIntfFactory(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc);
begin
TIntfFactory.Create(IID, IntfCreatorFunc);
end;
procedure TRegInf.RegObjFactory(IID: TGUID; Instance: TObject;
OwnsObj: Boolean);
begin
TObjFactory.Create(IID, Instance, OwnsObj);
end;
procedure TRegInf.RegSingletonFactory(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc);
begin
TSingletonFactory.Create(IID, IntfCreatorFunc);
end;
procedure CreateRegInf(out anInstance: IInterface);
begin
anInstance := TRegInf.Create;
end;
initialization
TSingletonFactory.Create(IRegInf, @CreateRegInf);
finalization
end.
|
unit uFrmAccountAddAmount;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls,
DB, ADODB, Mask, DateBox;
const
TYPE_CREDIT = 1;
TYPE_DEBIT = 2;
TYPE_CANCEL = 3;
TYPE_EXP_DATE = 4;
type
TFrmAccountAddAmount = class(TFrmParentAll)
lbOBS: TLabel;
memOBS: TMemo;
btnSave: TButton;
spAccountAddAmount: TADOStoredProc;
cmdCancelAccount: TADOCommand;
pnlAmount: TPanel;
Label2: TLabel;
edtAmount: TEdit;
pnlExpDate: TPanel;
lbExpDate: TLabel;
dtExp: TDateBox;
cmdExpDate: TADOCommand;
procedure btCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnSaveClick(Sender: TObject);
procedure edtAmountKeyPress(Sender: TObject; var Key: Char);
private
bInserted : Boolean;
FAccountCard : String;
FType : Integer;
FBalance : Currency;
function ValidateFields:Boolean;
procedure AddAmount;
public
function Start(AccountCard: String; iType : Integer; Balance : Currency):Boolean;
end;
implementation
uses uDM, uMsgConstant, uDMGlobal, uMsgBox, uCharFunctions, uNumericFunctions;
{$R *.dfm}
procedure TFrmAccountAddAmount.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrmAccountAddAmount.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
function TFrmAccountAddAmount.Start(AccountCard: String;
iType: Integer; Balance : Currency): Boolean;
begin
FAccountCard := AccountCard;
FBalance := Balance;
FType := iType;
pnlAmount.Visible := FType in [TYPE_CREDIT, TYPE_DEBIT];
pnlExpDate.Visible := FType in [TYPE_EXP_DATE];
dtExp.Date := Now;
lbOBS.Visible := FType <> TYPE_EXP_DATE;
memOBS.Visible := lbOBS.Visible;
bInserted := False;
ShowModal;
Result := bInserted;
end;
procedure TFrmAccountAddAmount.btnSaveClick(Sender: TObject);
begin
inherited;
if ValidateFields then
begin
AddAmount;
Close;
end;
end;
function TFrmAccountAddAmount.ValidateFields: Boolean;
begin
Result := False;
if FType = TYPE_CREDIT then
if MyStrToMoney(edtAmount.Text) <= 0 then
begin
MsgBox(MSG_CRT_NO_AMOUNT_ZERO, vbCritical + vbOkOnly);
edtAmount.SetFocus;
Exit;
end;
if FType = TYPE_DEBIT then
begin
if MyStrToMoney(edtAmount.Text) <= 0 then
begin
MsgBox(MSG_CRT_NO_AMOUNT_ZERO, vbCritical + vbOkOnly);
edtAmount.SetFocus;
Exit;
end;
if (FBalance - MyStrToMoney(edtAmount.Text)) <= 0 then
begin
MsgBox(MSG_CRT_NO_AMOUNT_ZERO, vbCritical + vbOkOnly);
edtAmount.SetFocus;
Exit;
end;
end;
if (FType <> TYPE_EXP_DATE) and (Trim(memOBS.Text) = '') then
begin
MsgBox(MSG_CRT_NO_EMPTY_REASON, vbCritical + vbOkOnly);
memOBS.SetFocus;
Exit;
end;
Result := True;
end;
procedure TFrmAccountAddAmount.AddAmount;
var
Credit : Boolean;
Amount : Currency;
begin
case FType of
TYPE_CREDIT : begin
Credit := True;
Amount := MyStrToMoney(edtAmount.Text);
end;
TYPE_DEBIT : begin
Credit := False;
Amount := MyStrToMoney(edtAmount.Text);
end;
TYPE_CANCEL : begin
Credit := False;
Amount := FBalance;
end;
end;
try
if FType in [TYPE_CREDIT, TYPE_DEBIT, TYPE_CANCEL] then
begin
DM.ADODBConnect.BeginTrans;
try
with spAccountAddAmount do
begin
Parameters.ParamByName('@CardNumber').Value := FAccountCard;
Parameters.ParamByName('@Amount').Value := Amount;
Parameters.ParamByName('@IDPreSale').Value := NULL;
Parameters.ParamByName('@IDLancamento').Value := NULL;
Parameters.ParamByName('@IDUser').Value := DM.fUser.ID;
Parameters.ParamByName('@Credit').Value := Credit;
Parameters.ParamByName('@OBS').Value := memOBS.Text;
ExecProc;
end;
DM.ADODBConnect.CommitTrans;
except
DM.ADODBConnect.RollbackTrans;
end;
end;
if FType = TYPE_CANCEL then
with cmdCancelAccount do
begin
Parameters.ParamByName('CardNumber').Value := FAccountCard;
Parameters.ParamByName('Canceled').Value := True;
Execute;
end;
if FType = TYPE_EXP_DATE then
with cmdExpDate do
begin
Parameters.ParamByName('CardNumber').Value := FAccountCard;
if dtExp.Text <> '' then
Parameters.ParamByName('ExpirationDate').Value := dtExp.Date
else
Parameters.ParamByName('ExpirationDate').Value := NULL;
Execute;
end;
bInserted := True;
except
raise;
bInserted := False;
end;
end;
procedure TFrmAccountAddAmount.edtAmountKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := ValidatePositiveCurrency(Key);
end;
end.
|
unit ZwischenUnit1;
interface
uses
System.SysUtils, System.Classes;
type
TZwischenModul1 = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
private
function GetValue(str_Ident: string): string;
procedure SetValue(str_Ident: string; const Value: string);
{ Private-Deklarationen }
public
{ Public-Deklarationen }
{$REGION 'Value'}
/// <summary>
/// Value reads and writes a Setting in INI File
/// </summary>
/// <param name="str_Ident : string">
/// Ident of Item
/// </param>
/// <param name="Value : string">
/// Value of the Item, readable and writeable
/// </param>
{$ENDREGION}
property Value [ str_Ident : string ] : string read GetValue write SetValue;
end;
var
ZwischenModul1: TZwischenModul1;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
uses ArbeitsUnit1;
{$R *.dfm}
procedure TZwischenModul1.DataModuleCreate(Sender: TObject);
begin
ArbeitsModul1 := TArbeitsModul1.Create( Self );
end;
function TZwischenModul1.GetValue(str_Ident: string): string;
begin
Result := ArbeitsModul1.Value[str_Ident];
end;
procedure TZwischenModul1.SetValue(str_Ident: string; const Value: string);
begin
ArbeitsModul1.Value[str_Ident] := Value;
end;
end.
|
{Ingresar K números que representan montos de ventas de una empresa, ordenados en forma
ascendente.
Calcular y mostrar por pantalla el promedio de los mismos y el % de participación de cada uno
respecto de la suma total en forma descendente.}
Program montos;
Type
TV = array[1..100] of real;
Var
Vec:TV;
Function Suma(Vec:TV; K:byte):real;
Var
i:byte;
aux:real;
begin
aux:= 0;
For i:= 1 to K do
aux:= aux + Vec[i];
Suma:= aux;
end;
Function Promedio(Vec:TV; K:byte):real;
begin
Promedio:= Suma(Vec,K) / K;
end;
Function Porcentaje(Vec:TV; K,i:byte):real;
begin
Porcentaje:= (Vec[i] / Suma(Vec,K)) * 100;
end;
Procedure MuestraDescendente(var Vec:TV; K:byte);
Var
i:byte;
begin
For i:= K downto 1 do
writeln('El porcentaje de participacion de $',Vec[i]:2:0,' es del ',Porcentaje(Vec,K,i):2:0,' %');
end;
Procedure IngresaMontos(Var Vec:TV);
Var
i,K:byte;
begin
write('Ingrese la cantidad de ventas: ');readln(K);
For i:= 1 to K do
begin
write('Ingrese el monto de la venta: ');readln(Vec[i]);
end;
writeln;
writeln('El promedio es de: $',Promedio(Vec,K):2:2);
writeln;
writeln('Montos en forma descendente');
MuestraDescendente(Vec,K);
end;
Begin
IngresaMontos(Vec);
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [R06]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit R06VO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL, R07VO;
type
TR06VO = class(TVO)
private
FID: Integer;
FID_OPERADOR: Integer;
FID_IMPRESSORA: Integer;
FID_ECF_CAIXA: Integer;
FSERIE_ECF: String;
FCOO: Integer;
FGNF: Integer;
FGRG: Integer;
FCDC: Integer;
FDENOMINACAO: String;
FDATA_EMISSAO: TDateTime;
FHORA_EMISSAO: String;
FLOGSS: String;
FListaR07VO: TListaR07VO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdOperador: Integer read FID_OPERADOR write FID_OPERADOR;
property IdImpressora: Integer read FID_IMPRESSORA write FID_IMPRESSORA;
property IdEcfCaixa: Integer read FID_ECF_CAIXA write FID_ECF_CAIXA;
property SerieEcf: String read FSERIE_ECF write FSERIE_ECF;
property Coo: Integer read FCOO write FCOO;
property Gnf: Integer read FGNF write FGNF;
property Grg: Integer read FGRG write FGRG;
property Cdc: Integer read FCDC write FCDC;
property Denominacao: String read FDENOMINACAO write FDENOMINACAO;
property DataEmissao: TDateTime read FDATA_EMISSAO write FDATA_EMISSAO;
property HoraEmissao: String read FHORA_EMISSAO write FHORA_EMISSAO;
property HashRegistro: String read FLOGSS write FLOGSS;
property ListaR07VO: TListaR07VO read FListaR07VO write FListaR07VO;
end;
TListaR06VO = specialize TFPGObjectList<TR06VO>;
implementation
constructor TR06VO.Create;
begin
inherited;
FListaR07VO := TListaR07VO.Create;
end;
destructor TR06VO.Destroy;
begin
FreeAndNil(FListaR07VO);
inherited;
end;
initialization
Classes.RegisterClass(TR06VO);
finalization
Classes.UnRegisterClass(TR06VO);
end.
|
unit fDuneFighterU;
interface
uses
Winapi.Windows,
System.Classes,
System.SysUtils,
Vcl.StdCtrls,
Vcl.Buttons,
Vcl.Controls,
Vcl.ExtCtrls,
Vcl.ComCtrls,
Vcl.Forms,
Vcl.Graphics,
Vcl.Imaging.Jpeg,
GLCadencer,
GLVectorFileObjects,
GLScene,
GLObjects,
GLMaterial,
GLNavigator,
GLTerrainRenderer,
GLCoordinates,
GLCrossPlatform,
GLBaseClasses,
GLWin32Viewer,
GLSkydome,
GLFileMD2,
GLFile3DS,
GLTexture,
GLColor,
GLVectorGeometry,
GLKeyboard,
GLRandomHDS;
type
TFDuneFighter = class(TForm)
GLScene1: TGLScene;
camThirdPerson: TGLCamera;
dcMushroom: TGLDummyCube;
GLSceneViewer1: TGLSceneViewer;
Actor1: TGLActor;
Actor2: TGLActor;
GLCadencer1: TGLCadencer;
Panel1: TPanel;
Timer1: TTimer;
camFirstPerson: TGLCamera;
Label3: TLabel;
Label4: TLabel;
DummyCube2: TGLDummyCube;
ffMushroom: TGLFreeForm;
GLLightSource2: TGLLightSource;
dcCamera3rd: TGLDummyCube;
Label1: TLabel;
GLNavigator1: TGLNavigator;
GLUserInterface1: TGLUserInterface;
GLTerrainRenderer1: TGLTerrainRenderer;
dcTerrain: TGLDummyCube;
GLMaterialLibrary1: TGLMaterialLibrary;
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure HandleKeys(const deltaTime: Double);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
procedure FormActivate(Sender: TObject);
private
hdsDunes: TGLFractalHDS;
procedure AddMushrooms;
public
end;
var
FDuneFighter: TFDuneFighter;
implementation
{$R *.DFM}
const
cWalkStep = 6; // this is our walking speed, in 3D units / second
cStrafeStep = 6; // this is our strafing speed, in 3D units / second
cRotAngle = 60; // this is our turning speed, in degrees / second
cRunBoost = 2; // speed boost when running
cSpread = 200;
cDepthOfView = 200;
cNbMushrooms = 25;
var
FirstActivate: boolean = True;
procedure TfDuneFighter.FormCreate(Sender: TObject);
begin
{ Create terrain }
GLTerrainRenderer1.Up.SetVector(0, 0, 1);
GLTerrainRenderer1.Direction.SetVector(0, 1, 0);
// with GLMaterialLibrary1.AddTextureMaterial('Dune','057terresable-Clair.jpg') do begin
with GLMaterialLibrary1.AddTextureMaterial('Dune', 'nature073-Terre+Herbe.jpg') do begin
Material.FrontProperties.Emission.Color := clrWhite;
// TextureScale.SetVector(3,3,3);
// GLTerrainRenderer1.Material.MaterialLibrary.LibMaterialByName('Dune');
end;
hdsDunes := TGLFractalHDS.Create(Self);
with hdsDunes do
begin
TerrainRenderer := GLTerrainRenderer1;
MaterialName := 'Dune';
TextureScale := 4;
LandCover := False;
Sea := True;
Amplitude := 30;
SeaLevel := -Amplitude * 0.5;
Depth := 7;
Cyclic := True;
Shadows := True;
Lighting := True;
LightDirection := VectorMake(1, 0.5, 1);
KeepNormals := True;
BuildLandscape;
end; // with
// Load mushroom mesh
ffMushroom.LoadFromFile('mushroom.3ds');
// Load Actor into GLScene
Actor1.LoadFromFile('waste.md2');
Actor1.Material.Texture.Image.LoadFromFile('waste.jpg');
Actor1.Animations.LoadFromFile('Quake2Animations.aaf');
Actor1.Scale.SetVector(0.04, 0.04, 0.04, 0);
// Load weapon model and texture
Actor2.LoadFromFile('WeaponWaste.md2');
Actor2.Material.Texture.Image.LoadFromFile('WeaponWaste.jpg');
Actor2.Animations.Assign(Actor1.Animations);
// Define animation properties
Actor1.AnimationMode := aamLoop;
Actor1.SwitchToAnimation('stand');
Actor1.FrameInterpolation := afpLinear;
Actor2.Synchronize(Actor1);
{ View parameters }
camThirdPerson.DepthOfView := cDepthOfView;
camFirstPerson.DepthOfView := cDepthOfView;
GLSceneViewer1.Buffer.FogEnvironment.FogEnd := cDepthOfView;
GLSceneViewer1.Buffer.FogEnvironment.FogStart := cDepthOfView / 2;
GLTerrainRenderer1.QualityDistance := cDepthOfView;
{ Set 3rd person camera }
GLSceneViewer1.Camera := camThirdPerson;
Actor1.Visible := True;
Label4.Font.Style := Label4.Font.Style - [fsBold];
Label3.Font.Style := Label3.Font.Style + [fsBold];
GLCadencer1.Enabled := True;
end;
procedure TfDuneFighter.HandleKeys(const deltaTime: Double);
var
moving: String;
boost: Single;
ay, cy: Single;
v: tVector;
begin
// This function uses asynchronous keyboard check (see Keyboard.pas)
if IsKeyDown(VK_ESCAPE) then
Close;
// Change Cameras
if IsKeyDown(VK_F7) then
begin
GLSceneViewer1.Camera := camThirdPerson;
Actor1.Visible := True;
Label4.Font.Style := Label4.Font.Style - [fsBold];
Label3.Font.Style := Label3.Font.Style + [fsBold];
end;
if IsKeyDown(VK_F8) then
begin
GLSceneViewer1.Camera := camFirstPerson;
Actor1.Visible := False;
Label4.Font.Style := Label4.Font.Style + [fsBold];
Label3.Font.Style := Label3.Font.Style - [fsBold];
end;
// Move Actor in the scene
// if nothing specified, we are standing
moving := 'stand';
// first, are we running ? if yes give animation & speed a boost
if IsKeyDown(VK_SHIFT) then
begin
Actor1.Interval := 100;
boost := cRunBoost * deltaTime
end
else
begin
Actor1.Interval := 150;
boost := deltaTime;
end;
Actor2.Interval := Actor1.Interval;
// are we advaning/backpedaling ?
if IsKeyDown(VK_UP) then
begin
GLNavigator1.MoveForward(cWalkStep * boost);
moving := 'run';
end;
if IsKeyDown(VK_DOWN) then
begin
GLNavigator1.MoveForward(-cWalkStep * boost);
moving := 'run';
end;
// slightly more complex, depending on CTRL key, we either turn or strafe
if IsKeyDown(VK_LEFT) then
begin
if IsKeyDown(VK_CONTROL) then
GLNavigator1.StrafeHorizontal(-cStrafeStep * boost)
else
GLNavigator1.TurnHorizontal(-cRotAngle * boost);
moving := 'run';
end;
if IsKeyDown(VK_RIGHT) then
begin
if IsKeyDown(VK_CONTROL) then
GLNavigator1.StrafeHorizontal(cStrafeStep * boost)
else
GLNavigator1.TurnHorizontal(cRotAngle * boost);
moving := 'run';
end;
{ Walk on the terrain, not beneath! }
with DummyCube2.Position do
begin
ay := GLTerrainRenderer1.InterpolatedHeight(VectorMake(X, Y, Z)) *
dcTerrain.Scale.Y + 1;
Y := ay;
end; // with
{ Prevent the 3rd person camera from going under the ground }
with camThirdPerson do
begin
cy := GLTerrainRenderer1.InterpolatedHeight(AbsolutePosition);
cy := MaxFloat(ay + 1, cy + 2);
v := AbsolutePosition;
v.Y := cy;
AbsolutePosition := v;
end; // with
// camFirstPerson.Up.AsVector:=hdsDunes.Normal(camFirstPerson.AbsolutePosition);
// update animation (if required)
// you can use faster methods (such as storing the last value of "moving")
// but this ones shows off the brand new "CurrentAnimation" function :)
if Actor1.CurrentAnimation <> moving then
begin
Actor1.SwitchToAnimation(moving);
Actor2.Synchronize(Actor1);
end;
end;
procedure TfDuneFighter.GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
begin
HandleKeys(deltaTime);
GLUserInterface1.Mouselook;
GLSceneViewer1.Invalidate;
GLUserInterface1.MouseUpdate;
end;
// add a few mushrooms to make the "landscape"
procedure TfDuneFighter.AddMushrooms;
var
i: Integer;
proxy: TGLProxyObject;
s: tVector;
f: Single;
X, Y, Z: Single;
begin
// spawn some more mushrooms using proxy objects
for i := 0 to cNbMushrooms - 1 do
begin
// create a new proxy and set its MasterObject property
proxy := TGLProxyObject(dcMushroom.AddNewChild(TGLProxyObject));
with proxy do
begin
ProxyOptions := [pooObjects];
MasterObject := ffMushroom;
// retrieve reference attitude
Direction := ffMushroom.Direction;
Up := ffMushroom.Up;
// randomize scale
s := ffMushroom.Scale.AsVector;
f := (1 * Random + 1);
ScaleVector(s, f);
Scale.AsVector := s;
// randomize position
X := Random(cSpread) - (cSpread / 2);
Z := Random(cSpread) - (cSpread / 2);
Y := GLTerrainRenderer1.InterpolatedHeight(VectorMake(X, Y, Z)) + 1.1;
AbsolutePosition := VectorMake(X, Y, Z);
// randomize orientation
RollAngle := Random(360);
TransformationChanged;
end;
end;
end;
procedure TfDuneFighter.Timer1Timer(Sender: TObject);
begin
Caption := Format('%.2f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TfDuneFighter.FormActivate(Sender: TObject);
begin
{ Duplicate our reference mushroom (but not its mesh data !)
We cannot do this in the OnCreate event as the tTerrainRenderer must have been
built (we need the height to place the mushrooms) }
if FirstActivate then
begin
GLSceneViewer1.Update;
AddMushrooms;
FirstActivate := False;
end; // if
end;
end.
|
unit geTipofDay;
interface
uses
classes,controls,dialogs,forms,graphics,messages,registry,stdctrls,
sysutils, windows, frmTip;
const
sTIPOFDAY = 'TipOfDay';
sSHOWATSTART = 'ShowAtStart';
sLASTTIP = 'LastTip';
type
TGETipOfDay = class(TComponent)
private
fDisableShowOnStart : boolean;
fLastTip : integer;
fReg : TRegIniFile;
fRegPath : string;
fRelativeTipFile:string;
fShowAtStart : boolean;
fTips: TStringList;
procedure SetLastTip(Value:integer);
procedure SetShowAtStart(Value:boolean);
procedure SetTips(Value: TStringList);
protected
procedure Loaded;override;
procedure LoadFromRegistry;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: boolean;
property LastTip : integer read fLastTip write SetLastTip;
property Reg: TRegIniFile read fReg write fReg;
published
property DisableShowAtStart : boolean read fDisableShowOnStart write fDisableShowOnStart;
property ShowAtStart: boolean read FShowAtStart write SetShowAtStart;
property RelativeTipFile:string read fRelativeTipFile write fRelativeTipFile;
property RegPath:string read fRegPath write fRegPath;
property Tips: TStringList read FTips write SetTips;
end;
procedure Register;
implementation
// ------ TGETipOfDay.Loaded ---------------------------------------------------
procedure TGETipOfDay.Loaded;
var
sTipFile:string;
begin
inherited Loaded;
if not (csDesigning in ComponentState) then
begin
LoadFromRegistry;
if (fRelativeTipFile <> '') then
begin
sTipFile := ExtractFilePath(ParamStr(0))+fRelativeTipFile;
if FileExists(sTipFile) then
Tips.LoadFromFile(sTipFile);
end;
end;
end;
// ------ TGETipOfDay.Create ---------------------------------------------------
constructor TGETipOfDay.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fReg := TRegIniFile.Create;
fTips := TStringList.Create;
fRelativeTipFile := '';
end;
// ------ TGETipOfDay.Destroy --------------------------------------------------
destructor TGETipOfDay.Destroy;
begin
fReg.Free;
fTips.Free;
inherited Destroy;
end;
// ------ TGETipOfDay.LoadFromRegistry -----------------------------------------
procedure TGETipOfDay.LoadFromRegistry;
begin
Reg.OpenKey(RegPath,true);
fShowAtStart := Reg.ReadBool(STIPOFDAY,SSHOWATSTART,true);
fLastTip := Reg.ReadInteger(STIPOFDAY,SLASTTIP,-1); // default = first tip;
Reg.CloseKey;
end;
// ------ TGETipOfDay.Execute --------------------------------------------------
function TGETipOfDay.Execute: boolean;
var
GETipDialog: TformGETip;
begin
LoadFromRegistry;
GETipDialog := TFormGETip.Create(nil);
GETipDialog.cbxShowTips.Enabled := not DisableShowatStart;
if DisableShowAtStart then
GETipDialog.cbxShowTips.Checked := false;
result := true;
with GETipDialog do
begin
FormTips.Assign(FTips);
cbxShowTips.Checked := FShowAtStart;
NumTip := fLastTip+1; {** increment this for the next tip}
try
ShowModal;
ShowAtStart := cbxShowTips.CHecked;
LastTip := NumTip;
finally
Release;
end;
end;
end;
// ------ TGETipOfDay.SetLastTip -----------------------------------------------
procedure TGETipOfDay.SetLastTip(value:integer);
begin
if (Value <> fLastTip) then
begin
fLastTip := value;
Reg.OpenKey(RegPath,true);
Reg.WriteInteger(STIPOFDAY,SLASTTIP,value);
Reg.CloseKey;
end;
end;
// ------ TGETipOfDay.SetShowAtStart -------------------------------------------
procedure TGETipOfDay.SetShowAtStart(value:boolean);
begin
fShowAtStart := Value;
Reg.OpenKey(RegPath,true);
Reg.WriteBool(STIPOFDAY,SSHOWATSTART,value);
Reg.CloseKey;
end;
// ------ TGETipOfDay.SetTips --------------------------------------------------
procedure TGETipOfDay.SetTips(Value: TStringList);
begin
if Value <> FTips then
FTips.Assign(Value);
end;
// ------ Register -------------------------------------------------------------
procedure Register;
begin
RegisterComponents('Graphic Edge IO', [TGETipOfDay]);
end;
end.
|
unit API_MVC_DB;
interface
uses
System.Generics.Collections,
API_MVC,
API_DB,
API_ORM;
type
TModelDB = class abstract(TModelAbstract)
protected
FDBEngine: TDBEngine;
public
constructor Create(aData: TDictionary<string, variant>;
aObjData: TObjectDictionary<string, TObject>); override;
end;
TControllerDB = class abstract(TControllerAbstract)
private
procedure ConnectToDB;
protected
FConnectParams: TConnectParams;
FDBEngine: TDBEngine;
FDBEngineClass: TDBEngineClass;
FConnectOnCreate: Boolean;
procedure InitDB; virtual; abstract;
procedure CallModel(aModelClass: TModelClass; aProcName: string = ''; aIsAsync: Boolean = False); override;
function GetConnectParams(aFileName: String): TConnectParams;
public
constructor Create(aMainView: TViewAbstract); override;
destructor Destroy; override;
end;
implementation
uses
System.Classes;
constructor TModelDB.Create(aData: TDictionary<string, variant>;
aObjData: TObjectDictionary<string, TObject>);
begin
inherited;
FDBEngine := FObjData.Items['DBEngine'] as TDBEngine;
end;
procedure TControllerDB.CallModel(aModelClass: TModelClass; aProcName: string = ''; aIsAsync: Boolean = False);
begin
FObjData.AddOrSetValue('DBEngine', FDBEngine);
inherited;
end;
function TControllerDB.GetConnectParams(aFileName: String): TConnectParams;
var
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.LoadFromFile(aFileName);
Result.Host := SL.Values['Host'];
Result.DataBase := SL.Values['DataBase'];
Result.Login := SL.Values['Login'];
Result.Password := SL.Values['Password'];
Result.CharacterSet := SL.Values['CharacterSet'];
finally
SL.Free;
end;
end;
destructor TControllerDB.Destroy;
begin
FDBEngine.Free;
inherited;
end;
procedure TControllerDB.ConnectToDB;
begin
FDBEngine.OpenConnection(FConnectParams);
end;
constructor TControllerDB.Create(aMainView: TViewAbstract);
begin
inherited;
Self.InitDB;
FDBEngine := FDBEngineClass.Create;
if FConnectOnCreate then ConnectToDB;
end;
end.
|
unit MainUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, TrayIcon, ExtCtrls;
type
TMainForm = class(TForm)
TrayIcon: TTrayIcon;
TrayPopupMenu: TPopupMenu;
CloseUnFreezerMenu: TMenuItem;
UnFreezerTimer: TTimer;
procedure UnFreezerTimerTimer(Sender: TObject);
procedure CloseUnFreezerMenuClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
hDesktopWindow: HWND;
hProgManWindow: HWND;
function IsKeysPressed: Boolean;
procedure KillProcess;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
function OneInstance(MutexName: string): Boolean;
var
hMutex: THANDLE;
Running: Boolean;
begin
//attempt to create Mutex
hMutex := CreateMutex(nil, FALSE, PCHAR(MutexName));
//See if it was successful
Running := ((GetLastError() = ERROR_ALREADY_EXISTS) or (GetLastError() = ERROR_ACCESS_DENIED));
//release rhe mutex
if(hMutex <> NULL) then
ReleaseMutex(hMutex);
result := Running;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
if(OneInstance('UnFreezerApp')) then begin
Application.Terminate;
Exit;
end;
// Get the desktop windows handle
hDesktopWindow := GetDesktopWindow();
hProgManWindow := FindWindow(PCHAR('Progman'), PCHAR('Program Manager'));
end;
procedure TMainForm.KillProcess;
var
pid: DWORD;
hWindow, hProc: HWND;
begin
// Get the foreground window handle
hWindow := GetForegroundWindow();
// Bail if the handle is the desktop window
if((hWindow = Self.Handle) or (hWindow = hProgManWindow) or (hWindow = hDesktopWindow)) then
Exit;
pid := 0;
// Terminate the process belonging to the foreground window
GetWindowThreadProcessId(hWindow, @pid);
if(pid <> 0) then begin
hProc := OpenProcess(PROCESS_TERMINATE, False, pid);
TerminateProcess(hProc, 0);
CloseHandle(hProc);
end;
end;
function TMainForm.IsKeysPressed: Boolean;
begin
Result := False;
// Check if the keys are pressed
if(((GetAsyncKeyState(VK_CONTROL) and $8000) > 0)) then begin
if(((GetAsyncKeyState(VK_SHIFT) and $8000) > 0)) then begin
if(((GetAsyncKeyState(VK_INSERT) and $8000) > 0)) then begin
Result := True;
end;
end;
end;
end;
procedure TMainForm.UnFreezerTimerTimer(Sender: TObject);
begin
// If the good combinason of keys are pressed, kill the process of the foreground window
if(IsKeysPressed) then begin
// Disable the timer
UnFreezerTimer.Enabled := False;
Application.ProcessMessages;
// Kill the process
KillProcess;
// Wait to restart the timer until the keys are released
while(IsKeysPressed) do
Sleep(1000);
// Enable the timer
UnFreezerTimer.Enabled := True;
end;
end;
procedure TMainForm.CloseUnFreezerMenuClick(Sender: TObject);
begin
// Stop the timer then close the app.
UnFreezerTimer.Enabled := False;
Application.ProcessMessages;
Close;
end;
end.
|
unit uStillImage;
interface
uses
uMemory,
SysUtils,
Classes,
ActiveX,
Registry,
Windows;
const
stillDll = 'Sti.dll';
CLSID_Sti: TGUID = '{B323F8E0-2E68-11D0-90EA-00AA0060F86C}';
IID_IStillImageW: TGUID = '{641BD880-2DC8-11D0-90EA-00AA0060F86C}';
type
IStillImageW = interface(IUnknown)
// IStillImage methods
function Initialize(hinst: HINST; dwVersion: DWORD): HRESULT; stdcall;
function GetDeviceList(dwType: DWORD; dwFlags: DWORD; out pdwItemsReturned: PDWORD; out ppBuffer: Pointer): HRESULT; stdcall;
function GetDeviceInfo(pwszDeviceName: LPWSTR; out ppBuffer: Pointer): HRESULT; stdcall;
function CreateDevice(pwszDeviceName: LPWSTR; dwMode: DWORD; out pDevice: IUnknown; punkOuter: IUnknown): HRESULT; stdcall;
//
// Device instance values. Used to associate various data with device.
//
function GetDeviceValue(pwszDeviceName: LPWSTR; pValueName: LPWSTR; out pType: LPDWORD; out pData: Pointer; var cbData: LPDWORD): HRESULT; stdcall;
function SetDeviceValue(pwszDeviceName: LPWSTR; pValueName: LPWSTR; out pType: LPDWORD; out pData: Pointer; var cbData: LPDWORD): HRESULT; stdcall;
//
// For appllication started through push model launch, returns associated information
//
function GetSTILaunchInformation(pwszDeviceName: LPWSTR; out pdwEventCode: PDWORD; out pwszEventName: LPWSTR): HRESULT; stdcall;
function RegisterLaunchApplication(pwszAppName: LPWSTR; pwszCommandLine: LPWSTR): HRESULT; stdcall;
function UnregisterLaunchApplication(pwszAppName: LPWSTR): HRESULT; stdcall;
end;
//Pointer to a null-terminated string that contains the full path to the executable file for this application. Additional command line arguments can be appended to this command. Two pairs of quotation marks should be used, for example, "\"C:\Program Files\MyExe.exe\" /arg1".
function RegisterStillHandler(Name, CommandLine: string): Boolean;
function UnRegisterStillHandler(Name: string): Boolean;
implementation
function RegisterStillHandler(Name, CommandLine: string): Boolean;
var
HR: HRESULT;
StillImage: IStillImageW;
begin
Result := False;
HR := CoCreateInstance (CLSID_Sti, nil, CLSCTX_INPROC_SERVER, IID_IStillImageW, StillImage);
if Succeeded(HR) then
begin
HR := StillImage.RegisterLaunchApplication(PChar(Name), PChar(CommandLine));
Result := Succeeded(HR);
end;
end;
function UnRegisterStillHandler(Name: string): Boolean;
const
EventsLocation = 'SYSTEM\CurrentControlSet\Control\StillImage\Events\STIProxyEvent';
var
HR: HRESULT;
StillImage: IStillImageW;
Reg: TRegistry;
I: Integer;
EventList: TStrings;
begin
Result := False;
HR := CoCreateInstance (CLSID_Sti, nil, CLSCTX_INPROC_SERVER, IID_IStillImageW, StillImage);
if Succeeded(HR) then
begin
HR := StillImage.UnregisterLaunchApplication(PChar(Name));
Result := Succeeded(HR);
end;
//for some reason unregistered application is still visible in registry, so clean-up manually
Reg := TRegistry.Create;
try
Reg.RootKey := Windows.HKEY_LOCAL_MACHINE;
if Reg.OpenKey(EventsLocation, False) then
begin
EventList := TStringList.Create;
try
Reg.GetKeyNames(EventList);
Reg.CloseKey;
for I := 0 to EventList.Count - 1 do
begin
if Reg.OpenKey(EventsLocation + '\' + EventList[I], False) then
begin
if Reg.ReadString('Name') = Name then
begin
Reg.CloseKey;
Reg.DeleteKey(EventsLocation + '\' + EventList[I]);
Reg.DeleteKey('SOFTWARE\Classes\CLSID\' + EventList[I]);
end else
Reg.CloseKey;
end;
end;
finally
F(EventList);
end;
end;
finally
F(Reg);
end;
end;
end.
|
{********************************************************************}
{ ** Arquivos INI Exemplo by Prodigy ** }
{ - Autor: Glauber A. Dantas(Prodigy_-) }
{ - Info: masterx@cpunet.com.br, }
{ #DelphiX - [Brasnet] irc.brasnet.org - www.delphix.com.br }
{ - Descrição: }
{ Utilização de arquivos ini(IniFiles). }
{ - Este exemplo pode ser modificado livremente. }
{********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, INIFiles;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
ComboBox1: TComboBox;
GroupBox2: TGroupBox;
CheckBox1: TCheckBox;
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
ComboBox2: TComboBox;
Button1: TButton;
Label3: TLabel;
Edit4: TEdit;
Button2: TButton;
Button3: TButton;
GroupBox3: TGroupBox;
Label5: TLabel;
Button4: TButton;
Label4: TLabel;
ComboBox4: TComboBox;
Label6: TLabel;
Button5: TButton;
LBL_Fonte: TLabel;
Label8: TLabel;
Label9: TLabel;
FontDialog1: TFontDialog;
ComboBox3: TComboBox;
Label7: TLabel;
Button6: TButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure ComboBox2Change(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure ComboBox3Change(Sender: TObject);
procedure Button6Click(Sender: TObject);
private
{ Private declarations }
ini : TIniFile;{** variavel do tipo arquivo ini **}
Pasta : String;{** variavel com valor da pasta local **}
procedure SalvarFonte;
procedure CarregarFonte;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
{retorna a pasta local}
Pasta := ExtractFilePath(Application.ExeName);//Pasta := ParamStr(0);
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{cria o arquivo ini na pasta local}
ini := TiniFile.Create(Pasta + 'Teste.ini');
{grava estado da CheckBox}
if Checkbox1.Checked then
ini.WriteBool('Valores', 'CheckBox1', True)
else
ini.WriteBool('Valores', 'CheckBox1', False);
{grava texto do Edit1}
ini.WriteString('Valores','Edit1', Edit1.Text);
{grava valor do Edit2}
ini.WriteFloat('Valores','Edit2', StrToFloat(Edit2.TExt));
{grava dimensoes do Form}
ini.WriteInteger('Config', 'Left', Left);
ini.WriteInteger('Config', 'Top', Top);
ini.WriteInteger('Config', 'Width', Width);
ini.WriteInteger('Config', 'Height', Height);
{libera o arquivo ini}
ini.Free;
{grava fonte do LBL_Fonte}
SalvarFonte;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
ini := TiniFile.Create(Pasta + 'Teste.ini');
{Retorna todas as seções existentes}
ini.ReadSections(ComboBox1.Items);
ComboBox1.ItemIndex := 0;
ComboBox3.Items := ComboBox1.Items;
ComboBox3.ItemIndex := 0;
{carrega estado da CheckBox}
if ini.ReadBool('Valores', 'CheckBox1', False) = True then
Checkbox1.Checked := True
else
Checkbox1.Checked := False;
{carrega texto dos Edits}
Edit1.Text := ini.ReadString('Valores', 'Edit1', '');
Edit2.Text := FloatToStr(ini.ReadFloat('Valores', 'Edit2', 0));
{carrega dimensoes do Form}
Left := ini.ReadInteger('Config', 'Left', Left);
Top := ini.ReadInteger('Config', 'Top', Top);
Width := ini.ReadInteger('Config', 'Width', Width);
Height := ini.ReadInteger('Config', 'Height', Height);
ini.Free;
{carrega fonte do LBL_Fonte}
CarregarFonte;
ComboBox1.OnChange(Self);
ComboBox3.OnChange(Self);
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
ini := TiniFile.Create(Pasta + 'Teste.ini');
ini.ReadSection(ComboBox1.Items[ComboBox1.ItemIndex], ComboBox2.Items);
ComboBox2.ItemIndex := 0;
Edit4.Clear;
ini.Free;
end;
procedure TForm1.ComboBox2Change(Sender: TObject);
begin
ini := TiniFile.Create(Pasta + 'Teste.ini');
Edit4.TExt := ini.ReadString(ComboBox1.Items[ComboBox1.ItemIndex],
ComboBox2.Items[ComboBox2.ItemIndex], '');
ini.Free;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ini := TiniFile.Create(Pasta + 'Teste.ini');
ini.WriteString(ComboBox1.Items[ComboBox1.ItemIndex],
ComboBox2.Items[ComboBox2.ItemIndex],
Edit4.TExt);
ini.Free;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
ini := TiniFile.Create(Pasta + 'Teste.ini');
ini.EraseSection(ComboBox1.Items[ComboBox1.ItemIndex]);
ini.Free;
Form1.OnShow(self);
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
ini := TiniFile.Create(Pasta + 'Teste.ini');
ini.DeleteKey(ComboBox1.Items[ComboBox1.ItemIndex],
ComboBox2.Items[ComboBox2.ItemIndex]);
ini.Free;
ComboBox2.Text := '';
Form1.OnShow(self);
end;
procedure TForm1.SalvarFonte;
var
FontSize, FontColor : Integer;
FontName : String;
begin
ini := TiniFile.Create(Pasta + 'Teste.ini');
with FontDialog1 do
begin
FontName := Font.Name;
FontSize := Font.Size;
FontColor:= Font.Color;
ini.WriteString('FONTE', 'Name', FontName);
ini.WriteInteger('FONTE', 'Size', FontSize);
ini.WriteInteger('FONTE', 'Color', FontColor);
if fsBold in Font.Style then
ini.WriteInteger('FONTE','Bold',1)
Else
ini.WriteInteger('FONTE','Bold',0);
if fsItalic in Font.Style then
ini.WriteInteger('FONTE','Italic',1)
Else
ini.WriteInteger('FONTE','Italic',0);
if fsUnderline in Font.Style then
ini.WriteInteger('FONTE','Underline',1)
Else
ini.WriteInteger('FONTE','Underline',0);
if fsStrikeOut in Font.Style then
ini.WriteInteger('FONTE','Strikeout',1)
Else
ini.WriteInteger('FONTE','Strikeout',0);
end;
ini.Free;
end;
procedure TForm1.CarregarFonte;
var
FonteX : TFont;
begin
ini := TiniFile.Create(Pasta + 'Teste.ini');
FonteX := TFont.Create;
FonteX.Name := ini.ReadString('FONTE', 'Name', 'MS Sans Serif');
FonteX.Size := ini.ReadInteger('FONTE', 'Size', 8);
FonteX.Color:= ini.ReadInteger('FONTE', 'Color', 0);
if ini.ReadInteger('FONTE', 'Bold', 0) = 1 then
FonteX.Style := FonteX.Style + [fsBold];
if ini.ReadInteger('FONTE', 'Italic', 0) = 1 then
FonteX.Style := FonteX.Style + [fsItalic];
if ini.ReadInteger('FONTE', 'Underline', 0) = 1 then
FonteX.Style := FonteX.Style + [fsUnderline];
if ini.ReadInteger('FONTE', 'Strikeout', 0) = 1 then
FonteX.Style := FonteX.Style + [fsStrikeOut];
LBL_Fonte.Font := FonteX;
ini.Free;
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
FontDialog1.Font := LBL_Fonte.Font;
if FontDialog1.Execute then
LBL_Fonte.Font := FontDialog1.Font;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
ini := TiniFile.Create(Pasta + 'Teste.ini');
ini.ReadSections(ComboBox3.Items);
ComboBox3.ItemIndex := 0;
ini.Free;
ComboBox3.OnChange(Self);
end;
procedure TForm1.ComboBox3Change(Sender: TObject);
begin
ini := TiniFile.Create(Pasta + 'Teste.ini');
ComboBox4.Items.Clear;
ini.ReadSectionValues(ComboBox3.Items[ComboBox3.ItemIndex], ComboBox4.Items);
ComboBox4.ItemIndex := 0;
ini.Free;
end;
procedure TForm1.Button6Click(Sender: TObject);
begin
Form1.OnShow(Self);
end;
end.
|
unit feli_event_participant;
{$mode objfpc}
interface
uses
feli_document,
feli_collection,
fpjson;
type
FeliEventParticipantKey = class
public
const
username = 'username';
createdAt = 'created_at';
ticketId = 'ticket_id';
end;
FeliEventParticipant = class(FeliDocument)
public
username, ticketId: ansiString;
createdAt: int64;
function toTJsonObject(secure: boolean = false): TJsonObject; override;
// Factory Methods
class function fromTJsonObject(participantObject: TJsonObject): FeliEventParticipant; static;
end;
FeliEventParticipantCollection = class(FeliCollection)
public
procedure add(eventParticipant: FeliEventParticipant);
class function fromFeliCollection(collection: FeliCollection): FeliEventParticipantCollection; static;
end;
FeliEventWaitingCollection = class(FeliEventParticipantCollection)
end;
implementation
uses feli_stack_tracer, sysutils;
function FeliEventParticipant.toTJsonObject(secure: boolean = false): TJsonObject;
var
eventParticipant: TJsonObject;
begin
FeliStackTrace.trace('begin', 'function FeliEventParticipant.toTJsonObject(secure: boolean = false): TJsonObject;');
eventParticipant := TJsonObject.create();
eventParticipant.add(FeliEventParticipantKey.username, username);
eventParticipant.add(FeliEventParticipantKey.ticketId, ticketId);
eventParticipant.add(FeliEventParticipantKey.createdAt, createdAt);
result := eventParticipant;
FeliStackTrace.trace('end', 'function FeliEventParticipant.toTJsonObject(secure: boolean = false): TJsonObject;');
end;
class function FeliEventParticipant.fromTJsonObject(participantObject: TJsonObject): FeliEventParticipant; static;
var
feliEventParticipantInstance: FeliEventParticipant;
tempString: ansiString;
begin
feliEventParticipantInstance := FeliEventParticipant.create();
with feliEventParticipantInstance do
begin
try username := participantObject.getPath(FeliEventParticipantKey.username).asString; except on e: exception do begin end; end;
try
begin
tempString := participantObject.getPath(FeliEventParticipantKey.createdAt).asString;
createdAt := StrToInt64(tempString);
end;
except on e: exception do begin end; end;
try ticketId := participantObject.getPath(FeliEventParticipantKey.ticketId).asString; except on e: exception do begin end; end;
end;
result := feliEventParticipantInstance;
end;
procedure FeliEventParticipantCollection.add(eventParticipant: FeliEventParticipant);
begin
FeliStackTrace.trace('begin', 'procedure FeliEventParticipantCollection.add(eventParticipant: FeliEventParticipant);');
data.add(eventParticipant.toTJsonObject());
FeliStackTrace.trace('end', 'procedure FeliEventParticipantCollection.add(eventParticipant: FeliEventParticipant);');
end;
class function FeliEventParticipantCollection.fromFeliCollection(collection: FeliCollection): FeliEventParticipantCollection; static;
var
feliEventParticipantCollectionInstance: FeliEventParticipantCollection;
begin
FeliStackTrace.trace('begin', 'class function FeliEventParticipantCollection.fromFeliCollection(collection: FeliCollection): FeliEventParticipantCollection; static;');
feliEventParticipantCollectionInstance := FeliEventParticipantCollection.create();
feliEventParticipantCollectionInstance.data := collection.data;
result := feliEventParticipantCollectionInstance;
FeliStackTrace.trace('end', 'class function FeliEventParticipantCollection.fromFeliCollection(collection: FeliCollection): FeliEventParticipantCollection; static;');
end;
end. |
unit DailyRotateLogger.Service;
interface
uses
Quick.Logger,
Quick.Logger.Provider.Files,
Quick.Logger.ExceptionHook,
Quick.Threads;
type
TMyService = class
private
fScheduler : TScheduledTasks;
public
constructor Create;
destructor Destroy; override;
procedure Execute;
end;
implementation
constructor TMyService.Create;
begin
fScheduler := TScheduledTasks.Create;
GlobalLogFileProvider.DailyRotate := True;
GlobalLogFileProvider.DailyRotateFileDateFormat := 'yyyymmdd';
GlobalLogFileProvider.MaxRotateFiles := 10;
GlobalLogFileProvider.MaxFileSizeInMB := 10;
GlobalLogFileProvider.RotatedFilesPath := '.\logs';
Logger.Providers.Add(GlobalLogFileProvider);
GlobalLogFileProvider.Enabled := True;
end;
destructor TMyService.Destroy;
begin
fScheduler.Free;
inherited;
end;
procedure TMyService.Execute;
begin
fScheduler.AddTask('LogToFile',procedure(aTask : ITask)
begin
Logger.Info('Logged a new entry');
end
).StartNow.RepeatEvery(10,TTimeMeasure.tmSeconds);
fScheduler.Start;
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmTreeNonViewEdit
Purpose : Property editor for the TrmTreeNonView component.
Date : 12-01-1999
Author : Ryan J. Mills
Version : 1.92
Notes : This unit was originally based upon the work of Patrick O'Keeffe.
It was at his request that I took the component over and rm'ified it.
================================================================================}
unit rmTreeNonViewEdit;
interface
{$I CompilerDefines.INC}
{$ifdef D6_or_higher}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DesignIntf, DesignEditors, Registry, rmTreeNonView, StdCtrls, ComCtrls, rmPathTreeView;
{$else}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DsgnIntf, Registry, rmTreeNonView, StdCtrls, ComCtrls, rmPathTreeView;
{$endif}
type
TfrmTreeNonViewEditor = class(TForm)
btnCancel: TButton;
btnOK: TButton;
grpItems: TGroupBox;
tvItems: TrmPathTreeView;
btnNew: TButton;
btnNewSub: TButton;
btnDelete: TButton;
btnLoad: TButton;
grpProperties: TGroupBox;
Label1: TLabel;
edText: TEdit;
procedure btnNewClick(Sender: TObject);
procedure btnNewSubClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure edTextKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure tvItemsChange(Sender: TObject; Node: TrmTreeNode);
private
{ Private declarations }
public
{ Public declarations }
end;
TrmTreeNonViewItemsProperty = class( TPropertyEditor )
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure Edit; override;
end;
implementation
{$R *.DFM}
uses
LibHelp;
const
Section = 'rmTreeNonView Items Editor';
function TrmTreeNonViewItemsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog]; { Edit method will display a dialog }
end;
function TrmTreeNonViewItemsProperty.GetValue: string;
begin
{ The GetPropType method is used to retrieve information pertaining to the }
{ property type being edited. In this case, the Name of the property class }
{ is displayed in the value column of the Object Inspector. }
Result := Format( '(%s)', [ GetPropType^.Name ] );
end;
procedure TrmTreeNonViewItemsProperty.Edit;
var
Component: TComponent;
Dialog: TfrmTreeNonViewEditor;
N : TrmTreeNonViewNode;
A : TrmTreeNode;
begin
Dialog := TfrmTreeNonViewEditor.Create(Application);
try
if (PropCount = 1) and (GetComponent(0) is TComponent) then
begin
Component := TComponent(GetComponent(0));
with Component as TrmTreeNonView do
begin
Dialog.tvItems.SepChar := SepChar;
N := Items.GetFirstNode;
while N <> nil do
begin
Dialog.tvItems.AddPathNode(nil, NodePath(N));
N := N.GetNext;
end;
if Dialog.ShowModal = mrOK then
begin
Items.Clear;
A := Dialog.tvItems.Items.GetFirstNode;
while A <> nil do
begin
AddPathNode(nil, Dialog.tvItems.NodePath(A));
A := A.GetNext;
end;
Modified;
end;
end;
end;
finally
Dialog.Free;
end;
end;
procedure TfrmTreeNonViewEditor.btnNewClick(Sender: TObject);
var
N : TrmTreeNode;
begin
N := tvItems.Items.Add(nil, '');
N.Selected := True;
edText.SetFocus;
end;
procedure TfrmTreeNonViewEditor.btnNewSubClick(Sender: TObject);
var
N : TrmTreeNode;
begin
N := tvItems.Items.AddChild(tvItems.Selected, '');
N.Selected := True;
edText.SetFocus;
end;
procedure TfrmTreeNonViewEditor.btnDeleteClick(Sender: TObject);
begin
if tvItems.Selected <> nil then
tvItems.Selected.Delete;
end;
procedure TfrmTreeNonViewEditor.edTextKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if tvItems.Selected <> nil then
tvItems.Selected.Text := edText.Text;
end;
procedure TfrmTreeNonViewEditor.tvItemsChange(Sender: TObject;
Node: TrmTreeNode);
begin
edText.Text := Node.Text;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: dlgConfigureTools
Author: Kiriakos Vlahos
Date: 03-Jun-2005
Purpose: Dialog for Configuring Tools
History:
-----------------------------------------------------------------------------}
unit dlgConfigureTools;
interface
uses
SysUtils, Classes, Windows, Controls, Forms, StdCtrls;
type
TConfigureTools = class(TForm)
AddBtn: TButton;
RemoveBtn: TButton;
ModifyBtn: TButton;
OKBtn: TButton;
CancelBtn: TButton;
MoveUpBtn: TButton;
MoveDownBtn: TButton;
ToolsList: TListBox;
procedure AddBtnClick(Sender: TObject);
procedure ModifyBtnClick(Sender: TObject);
procedure RemoveBtnClick(Sender: TObject);
procedure ToolsListClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ToolsListDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure ToolsListDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure MoveDownBtnClick(Sender: TObject);
procedure MoveUpBtnClick(Sender: TObject);
private
fTools : TCollection;
procedure CheckButtons;
procedure UpdateList;
end;
function ConfigureTools(Tools : TCollection): Boolean;
implementation
uses
JvJVCLUtils, JvJCLUtils, JvConsts, JVBoxProcs, cTools, dlgToolProperties,
Math;
{$R *.dfm}
function ConfigureTools(Tools : TCollection): Boolean;
begin
Result := False;
if not Assigned(Tools) then Exit;
with TConfigureTools.Create(Application) do
try
fTools.Assign(Tools);
UpdateList;
Result := ShowModal = mrOK;
if Result and Assigned(Tools) then
Tools.Assign(fTools);
finally
Release;
end;
end;
//=== { TConfigureTools } =============================================
procedure TConfigureTools.CheckButtons;
begin
ModifyBtn.Enabled := (ToolsList.Items.Count > 0) and
(ToolsList.ItemIndex >= 0);
RemoveBtn.Enabled := ModifyBtn.Enabled;
MoveUpBtn.Enabled := ToolsList.ItemIndex > 0;
MoveDownBtn.Enabled := InRange(ToolsList.ItemIndex, 0, ToolsList.Count - 2);
end;
procedure TConfigureTools.AddBtnClick(Sender: TObject);
begin
if EditTool((fTools.Add as TToolItem).ExternalTool) then begin
UpdateList;
ToolsList.ItemIndex := ToolsList.Count - 1;
CheckButtons;
end else
fTools.Delete(fTools.Count - 1);
end;
procedure TConfigureTools.ModifyBtnClick(Sender: TObject);
Var
Index : integer;
begin
Index := ToolsList.ItemIndex;
if (Index >= 0) and EditTool((fTools.FindItemID(
Integer(ToolsList.Items.Objects[Index]))
as TToolItem).ExternalTool)
then begin
UpdateList;
ToolsList.ItemIndex := Index;
CheckButtons;
end;
end;
procedure TConfigureTools.RemoveBtnClick(Sender: TObject);
begin
if ToolsList.ItemIndex >= 0 then begin
fTools.Delete(fTools.FindItemID(
Integer(ToolsList.Items.Objects[ToolsList.ItemIndex])).Index);
UpdateList;
end;
end;
procedure TConfigureTools.ToolsListClick(Sender: TObject);
begin
CheckButtons;
end;
procedure TConfigureTools.FormShow(Sender: TObject);
begin
CheckButtons;
end;
procedure TConfigureTools.ToolsListDragDrop(Sender, Source: TObject;
X, Y: Integer);
begin
if ToolsList.ItemIndex >= 0 then begin
fTools.Items[ToolsList.ItemIndex].Index :=
ToolsList.ItemAtPos(Point(X, Y), True);
UpdateList;
end;
end;
procedure TConfigureTools.ToolsListDragOver(Sender, Source: TObject;
X, Y: Integer; State: TDragState; var Accept: Boolean);
begin
BoxDragOver(ToolsList, Source, X, Y, State, Accept, ToolsList.Sorted);
CheckButtons;
end;
procedure TConfigureTools.FormCreate(Sender: TObject);
begin
fTools := TCollection.Create(TToolItem);
end;
procedure TConfigureTools.FormDestroy(Sender: TObject);
begin
fTools.Free;
end;
procedure TConfigureTools.UpdateList;
var
I: Integer;
begin
ToolsList.Clear;
for i := 0 to fTools.Count - 1 do
ToolsList.Items.AddObject(ftools.Items[i].DisplayName,
TObject(fTools.Items[i].ID));
CheckButtons;
end;
procedure TConfigureTools.MoveDownBtnClick(Sender: TObject);
Var
Index : integer;
begin
Index := ToolsList.ItemIndex;
if InRange(Index, 0, ToolsList.Count - 2) then begin
fTools.Items[Index].Index := fTools.Items[Index].Index + 1;
UpdateList;
ToolsList.ItemIndex := Index + 1;
CheckButtons;
end;
end;
procedure TConfigureTools.MoveUpBtnClick(Sender: TObject);
Var
Index : integer;
begin
Index := ToolsList.ItemIndex;
if Index > 0 then begin
fTools.Items[Index].Index := fTools.Items[Index].Index - 1;
UpdateList;
ToolsList.ItemIndex := Index - 1;
CheckButtons;
end;
end;
end.
|
namespace NotificationsExtensions;
interface
uses
System,
System.Collections.ObjectModel,
System.Runtime.InteropServices,
System.Text,
BadgeContent,
Windows.Data.Xml.Dom;
type
NotificationContentText = assembly sealed class(INotificationContentText)
constructor ;
public
property Text: String read m_Text write m_Text;
property Lang: String read m_Lang write m_Lang;
private
var m_Text: String;
var m_Lang: String;
end;
NotificationContentImage = assembly sealed class(INotificationContentImage)
constructor ;
public
property Src: String read m_Src write m_Src;
property Alt: String read m_Alt write m_Alt;
private
var m_Src: String;
var m_Alt: String;
end;
Util = assembly static class
public
const NOTIFICATION_CONTENT_VERSION: Integer = 1;
class method HttpEncode(value: String): String;
end;
/// <summary>
/// Base class for the notification content creation helper classes.
/// </summary>
NotificationBase = abstract assembly class
protected
constructor (aTemplateName: String; aImageCount: Integer; aTextCount: Integer);
public
property StrictValidation: Boolean read m_StrictValidation write m_StrictValidation;
method GetContent: String; abstract;
method ToString: String; override;
method GetXml: XmlDocument;
/// <summary>
/// Retrieves the list of images that can be manipulated on the notification content.
/// </summary>
property Images: array of INotificationContentImage read m_Images;
/// <summary>
/// Retrieves the list of text fields that can be manipulated on the notification content.
/// </summary>
property TextFields: array of INotificationContentText read m_TextFields;
/// <summary>
/// The base Uri path that should be used for all image references in the notification.
/// </summary>
property BaseUri: String read m_BaseUri write set_BaseUri;
method set_BaseUri(value: String);
property Lang: String read m_Lang write m_Lang;
protected
method SerializeProperties(globalLang: String; globalBaseUri: String): String;
public
property TemplateName: String read m_TemplateName;
private
var m_StrictValidation: Boolean := true;
var m_Images: array of INotificationContentImage;
var m_TextFields: array of INotificationContentText;
// Remove when "lang" is not required on the visual element
var m_Lang: String := 'en-US';
var m_BaseUri: String;
var m_TemplateName: String;
end;
/// <summary>
/// Exception returned when invalid notification content is provided.
/// </summary>
NotificationContentValidationException = assembly sealed class(COMException)
public
constructor (message: String);
end;
implementation
constructor NotificationContentText;
begin
end;
constructor NotificationContentImage;
begin
end;
class method Util.HttpEncode(value: String): String;
begin
exit value.Replace('&', '&').Replace('<', '<').Replace('>', '>').Replace('"', '"').Replace(#39, ''')
end;
constructor NotificationBase(aTemplateName: String; aImageCount: Integer; aTextCount: Integer);
begin
m_TemplateName := aTemplateName;
m_Images := new INotificationContentImage[aImageCount];
begin
var i: Integer := 0;
while i < m_Images.Length do begin begin
m_Images[i] := new NotificationContentImage()
end;
inc(i);
end;
end;
m_TextFields := new INotificationContentText[aTextCount];
begin
var i: Integer := 0;
while i < m_TextFields.Length do begin begin
m_TextFields[i] := new NotificationContentText()
end;
inc(i);
end;
end
end;
method NotificationBase.ToString: String;
begin
exit GetContent()
end;
method NotificationBase.GetXml: XmlDocument;
begin
var xml: XmlDocument := new XmlDocument();
xml.LoadXml(GetContent());
exit xml
end;
method NotificationBase.set_BaseUri(value: String); begin
var goodPrefix: Boolean := (self.StrictValidation) or (value = nil);
goodPrefix := (goodPrefix) or (value.StartsWith('http://', StringComparison.OrdinalIgnoreCase));
goodPrefix := (goodPrefix) or (value.StartsWith('https://', StringComparison.OrdinalIgnoreCase));
goodPrefix := (goodPrefix) or (value.StartsWith('ms-appx:///', StringComparison.OrdinalIgnoreCase));
goodPrefix := (goodPrefix) or (value.StartsWith('ms-appdata:///local/', StringComparison.OrdinalIgnoreCase));
if not goodPrefix then begin
raise new ArgumentException('The BaseUri must begin with http://, https://, ms-appx:///, or ms-appdata:///local/.', 'value')
end;
m_BaseUri := value
end;
method NotificationBase.SerializeProperties(globalLang: String; globalBaseUri: String): String;
begin
globalLang := iif((globalLang <> nil), globalLang, String.Empty);
globalBaseUri := iif(String.IsNullOrWhiteSpace(globalBaseUri), nil, globalBaseUri);
var builder: StringBuilder := new StringBuilder(String.Empty);
begin
var i: Integer := 0;
while i < m_Images.Length do begin begin
if not String.IsNullOrEmpty(m_Images[i].Src) then begin
var escapedSrc: String := Util.HttpEncode(m_Images[i].Src);
if not String.IsNullOrWhiteSpace(m_Images[i].Alt) then begin
var escapedAlt: String := Util.HttpEncode(m_Images[i].Alt);
builder.AppendFormat('<image id=''{0}'' src=''{1}'' alt=''{2}''/>', i + 1, escapedSrc, escapedAlt)
end
else begin
builder.AppendFormat('<image id=''{0}'' src=''{1}''/>', i + 1, escapedSrc)
end
end
end;
// TODO: not supported Increment might not get called when using continue
{POST}inc(i);
end;
end;
begin
var i: Integer := 0;
while i < m_TextFields.Length do begin begin
if not String.IsNullOrWhiteSpace(m_TextFields[i].Text) then begin
var escapedValue: String := Util.HttpEncode(m_TextFields[i].Text);
if (not String.IsNullOrWhiteSpace(m_TextFields[i].Lang)) and (not m_TextFields[i].Lang.Equals(globalLang)) then begin
var escapedLang: String := Util.HttpEncode(m_TextFields[i].Lang);
builder.AppendFormat('<text id=''{0}'' lang=''{1}''>{2}</text>', i + 1, escapedLang, escapedValue)
end
else begin
builder.AppendFormat('<text id=''{0}''>{1}</text>', i + 1, escapedValue)
end
end
end;
// TODO: not supported Increment might not get called when using continue
{POST}inc(i);
end;
end;
exit builder.ToString()
end;
constructor NotificationContentValidationException(message: String);
begin
inherited constructor(message, $80070057 as Integer);
end;
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 183159
////////////////////////////////////////////////////////////////////////////////
unit junit.framework.Assert;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JAssert = interface;
JAssertClass = interface(JObjectClass)
['{71B31235-EA78-4714-8E96-FCD538E08AE9}']
function format(&message : JString; expected : JObject; actual : JObject) : JString; cdecl;// (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/String; A: $9
procedure assertEquals(&message : JString; expected : Byte; actual : Byte) ; cdecl; overload;// (Ljava/lang/String;BB)V A: $9
procedure assertEquals(&message : JString; expected : Char; actual : Char) ; cdecl; overload;// (Ljava/lang/String;CC)V A: $9
procedure assertEquals(&message : JString; expected : Double; actual : Double; delta : Double) ; cdecl; overload;// (Ljava/lang/String;DDD)V A: $9
procedure assertEquals(&message : JString; expected : Int64; actual : Int64) ; cdecl; overload;// (Ljava/lang/String;JJ)V A: $9
procedure assertEquals(&message : JString; expected : Integer; actual : Integer) ; cdecl; overload;// (Ljava/lang/String;II)V A: $9
procedure assertEquals(&message : JString; expected : JObject; actual : JObject) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V A: $9
procedure assertEquals(&message : JString; expected : JString; actual : JString) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V A: $9
procedure assertEquals(&message : JString; expected : Single; actual : Single; delta : Single) ; cdecl; overload;// (Ljava/lang/String;FFF)V A: $9
procedure assertEquals(&message : JString; expected : SmallInt; actual : SmallInt) ; cdecl; overload;// (Ljava/lang/String;SS)V A: $9
procedure assertEquals(&message : JString; expected : boolean; actual : boolean) ; cdecl; overload;// (Ljava/lang/String;ZZ)V A: $9
procedure assertEquals(expected : Byte; actual : Byte) ; cdecl; overload; // (BB)V A: $9
procedure assertEquals(expected : Char; actual : Char) ; cdecl; overload; // (CC)V A: $9
procedure assertEquals(expected : Double; actual : Double; delta : Double) ; cdecl; overload;// (DDD)V A: $9
procedure assertEquals(expected : Int64; actual : Int64) ; cdecl; overload; // (JJ)V A: $9
procedure assertEquals(expected : Integer; actual : Integer) ; cdecl; overload;// (II)V A: $9
procedure assertEquals(expected : JObject; actual : JObject) ; cdecl; overload;// (Ljava/lang/Object;Ljava/lang/Object;)V A: $9
procedure assertEquals(expected : JString; actual : JString) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;)V A: $9
procedure assertEquals(expected : Single; actual : Single; delta : Single) ; cdecl; overload;// (FFF)V A: $9
procedure assertEquals(expected : SmallInt; actual : SmallInt) ; cdecl; overload;// (SS)V A: $9
procedure assertEquals(expected : boolean; actual : boolean) ; cdecl; overload;// (ZZ)V A: $9
procedure assertFalse(&message : JString; condition : boolean) ; cdecl; overload;// (Ljava/lang/String;Z)V A: $9
procedure assertFalse(condition : boolean) ; cdecl; overload; // (Z)V A: $9
procedure assertNotNull(&message : JString; &object : JObject) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Object;)V A: $9
procedure assertNotNull(&object : JObject) ; cdecl; overload; // (Ljava/lang/Object;)V A: $9
procedure assertNotSame(&message : JString; expected : JObject; actual : JObject) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V A: $9
procedure assertNotSame(expected : JObject; actual : JObject) ; cdecl; overload;// (Ljava/lang/Object;Ljava/lang/Object;)V A: $9
procedure assertNull(&message : JString; &object : JObject) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Object;)V A: $9
procedure assertNull(&object : JObject) ; cdecl; overload; // (Ljava/lang/Object;)V A: $9
procedure assertSame(&message : JString; expected : JObject; actual : JObject) ; cdecl; overload;// (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V A: $9
procedure assertSame(expected : JObject; actual : JObject) ; cdecl; overload;// (Ljava/lang/Object;Ljava/lang/Object;)V A: $9
procedure assertTrue(&message : JString; condition : boolean) ; cdecl; overload;// (Ljava/lang/String;Z)V A: $9
procedure assertTrue(condition : boolean) ; cdecl; overload; // (Z)V A: $9
procedure fail ; cdecl; overload; // ()V A: $9
procedure fail(&message : JString) ; cdecl; overload; // (Ljava/lang/String;)V A: $9
procedure failNotEquals(&message : JString; expected : JObject; actual : JObject) ; cdecl;// (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V A: $9
procedure failNotSame(&message : JString; expected : JObject; actual : JObject) ; cdecl;// (Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V A: $9
procedure failSame(&message : JString) ; cdecl; // (Ljava/lang/String;)V A: $9
end;
[JavaSignature('junit/framework/Assert')]
JAssert = interface(JObject)
['{0688B753-D1E4-4BBC-A885-6530B702342E}']
end;
TJAssert = class(TJavaGenericImport<JAssertClass, JAssert>)
end;
implementation
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
FPS-like movement behaviour and manager.
}
unit VXS.FPSMovement;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
System.UITypes,
FMX.Graphics,
VXS.OpenGL,
VXS.VectorTypes,
VXS.Context,
VXS.CrossPlatform,
VXS.VectorGeometry,
VXS.Scene,
VXS.Coordinates,
VXS.VectorFileObjects,
VXS.VectorLists,
VXS.XCollection,
VXS.GeomObjects,
VXS.Navigator,
VXS.RenderContextInfo,
VXS.BaseClasses,
VXS.Manager,
VXS.State;
type
TContactPoint = record
intPoint, intNormal: TVector;
end;
TCollisionState = class
public
Position: TVector;
Contact: TContactPoint;
Time: Int64;
end;
TCollisionStates = class(TList)
end;
TVXBFPSMovement = class;
TVXMapCollectionItem = class(TXCollectionItem)
private
FMap: TVXFreeForm;
FMapName: string;
FCollisionGroup: integer;
procedure setMap(value: TVXFreeForm);
protected
procedure WriteToFiler(writer: TWriter); override;
procedure ReadFromFiler(reader: TReader); override;
procedure Loaded; override;
public
constructor Create(aOwner: TXCollection); override;
class function FriendlyName: String; override;
published
property Map: TVXFreeForm read FMap write setMap;
{ Indicates the collision group of this map. A Collision Group
is a set of logical maps and movers that can collide between
themselves (i.e. a Behaviour with group 1 can only collide with
maps that are also on group 1).
}
property CollisionGroup: integer read FCollisionGroup write FCollisionGroup;
end;
TVXMapCollectionItemClass = class of TVXMapCollectionItem;
TVXMapCollection = class(TXCollection)
public
class function ItemsClass: TXCollectionItemClass; override;
function addMap(Map: TVXFreeForm; CollisionGroup: integer = 0)
: TVXMapCollectionItem;
function findMap(mapFreeForm: TVXFreeForm): TVXMapCollectionItem;
end;
TVXFPSMovementManager = class(TComponent)
private
FNavigator: TVXNavigator;
FDisplayTime: integer;
FMovementScale: single;
FMaps: TVXMapCollection;
FScene: TVXScene;
procedure SetNavigator(value: TVXNavigator);
procedure setScene(value: TVXScene);
procedure DrawArrows(intPoint, intNormal, Ray: TVector;
Arrow1, Arrow2: TVXArrowLine);
protected
procedure Loaded; override;
procedure DefineProperties(Filer: TFiler); override;
procedure WriteMaps(stream: TStream);
procedure ReadMaps(stream: TStream);
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
// Basic idea is to OctreeSphereSweepIntersect to plane, update position then change
// velocity to slide along the plane
// Camera can collide with multiple planes (e.g. floor + multiple walls + ceiling)
// limit iterations to 4 or 5 for now, may need to be higher for more complex maps or fast motion
function SphereSweepAndSlide(freeform: TVXFreeForm;
behaviour: TVXBFPSMovement; SphereStart: TVector;
var Velocity, newPosition: TVector; sphereRadius: single)
: boolean; overload;
procedure SphereSweepAndSlide(behaviour: TVXBFPSMovement;
SphereStart: TVector; var Velocity, newPosition: TVector;
sphereRadius: single); overload;
published
property Maps: TVXMapCollection read FMaps write FMaps;
property Navigator: TVXNavigator read FNavigator write SetNavigator;
property Scene: TVXScene read FScene write setScene;
{ Display Time for the arrow lines. }
property DisplayTime: integer read FDisplayTime write FDisplayTime;
property MovementScale: single read FMovementScale write FMovementScale;
end;
TVXBFPSMovement = class(TVXBehaviour)
private
FManager: TVXFPSMovementManager;
CollisionStates: TCollisionStates;
ArrowLine1, ArrowLine2, ArrowLine3, ArrowLine4, ArrowLine5,
ArrowLine6: TVXArrowLine;
dirGl: TVXDirectOpenVX;
tickCount: Int64;
oldPosition: TVector;
FGravityEnabled: boolean;
FSphereRadius: single;
FShowArrows: boolean;
FCollisionGroup: integer;
FManagerName: string;
procedure setShowArrows(value: boolean);
procedure RenderArrowLines(Sender: TObject; var rci: TVXRenderContextInfo);
protected
procedure WriteToFiler(writer: TWriter); override;
procedure ReadFromFiler(reader: TReader); override;
procedure Loaded; override;
public
Velocity: TVector;
constructor Create(aOwner: TXCollection); override;
destructor Destroy; override;
procedure DoProgress(const progressTime: TVXProgressTimes); override;
class function FriendlyName: string; override;
Procedure TurnHorizontal(Angle: single);
Procedure TurnVertical(Angle: single);
Procedure MoveForward(Distance: single);
Procedure StrafeHorizontal(Distance: single);
Procedure StrafeVertical(Distance: single);
Procedure Straighten;
published
property Manager: TVXFPSMovementManager read FManager write FManager;
{
Radius to execute the testing with. A value < 0 indicates to use
the boundingSphereRadius of the object.
}
property sphereRadius: single read FSphereRadius write FSphereRadius;
{ Show Arrows and trailing for debuging. }
property ShowArrows: boolean read FShowArrows write setShowArrows;
{ Indicates the collision group of this behaviour. A Collision Group
is a set of logical maps and movers that can collide between
themselves (i.e. a Behaviour with group 1 can only collide with
maps that are also on group 1) }
property CollisionGroup: integer read FCollisionGroup write FCollisionGroup;
property GravityEnabled: boolean read FGravityEnabled write FGravityEnabled;
end;
function GetFPSMovement(behaviours: TVXBehaviours): TVXBFPSMovement; overload;
function GetFPSMovement(obj: TVXBaseSceneObject): TVXBFPSMovement; overload;
function GetOrCreateFPSMovement(behaviours: TVXBehaviours)
: TVXBFPSMovement; overload;
function GetOrCreateFPSMovement(obj: TVXBaseSceneObject)
: TVXBFPSMovement; overload;
//-------------------------------------------------------------------------
implementation
//-------------------------------------------------------------------------
function GetFPSMovement(behaviours: TVXBehaviours): TVXBFPSMovement; overload;
var
i: integer;
begin
i := behaviours.IndexOfClass(TVXBFPSMovement);
if i >= 0 then
Result := TVXBFPSMovement(behaviours[i])
else
Result := nil;
end;
function GetFPSMovement(obj: TVXBaseSceneObject): TVXBFPSMovement; overload;
begin
Result := GetFPSMovement(obj.behaviours);
end;
function GetOrCreateFPSMovement(behaviours: TVXBehaviours)
: TVXBFPSMovement; overload;
var
i: integer;
begin
i := behaviours.IndexOfClass(TVXBFPSMovement);
if i >= 0 then
Result := TVXBFPSMovement(behaviours[i])
else
Result := TVXBFPSMovement.Create(behaviours);
end;
function GetOrCreateFPSMovement(obj: TVXBaseSceneObject)
: TVXBFPSMovement; overload;
begin
Result := GetOrCreateFPSMovement(obj.behaviours);
end;
// ------------------
// ------------------ TVXMapCollectionItem ------------------
// ------------------
constructor TVXMapCollectionItem.Create(aOwner: TXCollection);
begin
inherited Create(aOwner);
FCollisionGroup := 0;
end;
procedure TVXMapCollectionItem.setMap(value: TVXFreeForm);
begin
assert(owner.owner.InheritsFrom(TVXFPSMovementManager));
if assigned(FMap) then
FMap.RemoveFreeNotification(TComponent(owner.owner));
FMap := value;
if assigned(FMap) then
FMap.FreeNotification(TComponent(owner.owner));
end;
procedure TVXMapCollectionItem.WriteToFiler(writer: TWriter);
begin
inherited WriteToFiler(writer);
with writer do
begin
writeInteger(0); // ArchiveVersion
writeInteger(FCollisionGroup);
if assigned(FMap) then
WriteString(FMap.Name)
else
WriteString('');
end;
end;
procedure TVXMapCollectionItem.ReadFromFiler(reader: TReader);
var
archiveVersion: integer;
begin
inherited ReadFromFiler(reader);
with reader do
begin
archiveVersion := readInteger;
assert(archiveVersion = 0, 'Wrong ArchiveVersion for TVXMapCollectionItem');
FCollisionGroup := readInteger;
FMapName := ReadString;
end;
end;
procedure TVXMapCollectionItem.Loaded;
begin
if FMapName <> '' then
begin
assert(owner.owner.InheritsFrom(TVXFPSMovementManager));
Map := TVXFreeForm(TVXFPSMovementManager(owner.owner)
.Scene.FindSceneObject(FMapName));
end;
end;
class function TVXMapCollectionItem.FriendlyName: String;
begin
Result := 'FPSMovementMap';
end;
// ------------------
// ------------------ TVXMapCollection ------------------
// ------------------
class function TVXMapCollection.ItemsClass: TXCollectionItemClass;
begin
Result := TVXMapCollectionItem;
end;
function TVXMapCollection.addMap(Map: TVXFreeForm; CollisionGroup: integer = 0)
: TVXMapCollectionItem;
begin
// no repeated maps (would only present delays...)
Result := findMap(Map);
if assigned(Result) then
exit;
Result := TVXMapCollectionItem.Create(self);
Result.Map := Map;
Result.CollisionGroup := CollisionGroup;
add(Result);
end;
function TVXMapCollection.findMap(mapFreeForm: TVXFreeForm)
: TVXMapCollectionItem;
var
i: integer;
aux: TVXMapCollectionItem;
begin
Result := nil;
for i := 0 to count - 1 do
begin
aux := TVXMapCollectionItem(Items[i]);
if aux.Map = mapFreeForm then
begin
Result := aux;
break;
end;
end;
end;
// ------------------
// ------------------ TVXFPSMovementManager ------------------
// ------------------
constructor TVXFPSMovementManager.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
Maps := TVXMapCollection.Create(self);
MovementScale := 4.0;
DisplayTime := 2000;
RegisterManager(self);
end;
destructor TVXFPSMovementManager.Destroy;
begin
DeRegisterManager(self);
Maps.Free;
inherited Destroy;
end;
procedure TVXFPSMovementManager.Loaded;
begin
inherited Loaded;
if assigned(FMaps) then
Maps.Loaded;
end;
// DefineProperties
//
procedure TVXFPSMovementManager.DefineProperties(Filer: TFiler);
begin
inherited;
{ FOriginalFiler := Filer; }
Filer.DefineBinaryProperty('MapsData', ReadMaps, WriteMaps,
(assigned(FMaps) and (FMaps.count > 0)));
{ FOriginalFiler:=nil; }
end;
// WriteBehaviours
//
procedure TVXFPSMovementManager.WriteMaps(stream: TStream);
var
writer: TWriter;
begin
writer := TWriter.Create(stream, 16384);
try
Maps.WriteToFiler(writer);
finally
writer.Free;
end;
end;
procedure TVXFPSMovementManager.ReadMaps(stream: TStream);
var
reader: TReader;
begin
reader := TReader.Create(stream, 16384);
try
Maps.ReadFromFiler(reader);
finally
reader.Free;
end;
end;
procedure TVXFPSMovementManager.SetNavigator(value: TVXNavigator);
begin
if assigned(FNavigator) then
FNavigator.RemoveFreeNotification(self);
FNavigator := value;
if assigned(value) then
value.FreeNotification(self);
end;
procedure TVXFPSMovementManager.setScene(value: TVXScene);
begin
if assigned(FScene) then
FScene.RemoveFreeNotification(self);
FScene := value;
if assigned(FScene) then
FScene.FreeNotification(self);
end;
procedure TVXFPSMovementManager.Notification(AComponent: TComponent;
Operation: TOperation);
var
Map: TVXMapCollectionItem;
begin
inherited Notification(AComponent, Operation);
if Operation <> opRemove then
exit;
if (AComponent = FNavigator) then
Navigator := nil;
if (AComponent = FScene) then
FScene := nil;
if AComponent.InheritsFrom(TVXFreeForm) then
begin
Map := Maps.findMap(TVXFreeForm(AComponent));
if assigned(Map) then
Map.Map := nil;
end;
end;
procedure TVXFPSMovementManager.DrawArrows(intPoint, intNormal, Ray: TVector;
Arrow1, Arrow2: TVXArrowLine);
begin
Arrow1.Position.AsVector := intPoint;
Arrow1.Direction.AsVector := intNormal;
Arrow1.Scale.z := VectorLength(intNormal);
Arrow1.Move(Arrow1.Scale.z / 2);
Arrow1.Visible := True;
Arrow2.Position.AsVector := intPoint;
Arrow2.Direction.AsVector := Ray;
Arrow2.Visible := True;
end;
procedure TVXFPSMovementManager.SphereSweepAndSlide(behaviour: TVXBFPSMovement;
SphereStart: TVector; var Velocity, newPosition: TVector;
sphereRadius: single);
var
i: integer;
Map: TVXMapCollectionItem;
begin
for i := 0 to Maps.count - 1 do
begin
Map := TVXMapCollectionItem(Maps.GetItems(i));
if Map.CollisionGroup = behaviour.CollisionGroup then
SphereSweepAndSlide(Map.Map, behaviour, SphereStart, Velocity,
newPosition, sphereRadius)
end;
end;
function TVXFPSMovementManager.SphereSweepAndSlide(freeform: TVXFreeForm;
behaviour: TVXBFPSMovement; SphereStart: TVector;
var Velocity, newPosition: TVector; sphereRadius: single): boolean;
var
oldPosition, Ray: TVector;
vel, slidedistance: single;
intPoint, intNormal: TVector;
newDirection, newRay, collisionPosition, pointOnSphere,
point2OnSphere: TVector;
i: integer;
CollisionState: TCollisionState;
SphereRadiusRel: single; // mrqzzz
begin
SphereRadiusRel := sphereRadius / freeform.Scale.x;
// could be Scale.y, or Scale.z assuming they are the same
oldPosition := SphereStart;
Result := True;
// Direction sphere is moving in
Ray := VectorSubtract(newPosition, oldPosition);
// ray:=Velocity;
// newPosition:=VectorAdd(newPosition,ray);
// Speed of sphere
vel := VectorLength(Ray);
// if the Sphere is not moving, nothing is required
// else do up to 7 loops
if vel > 0 then
for i := 0 to 6 do
begin
// if an intersection occurs, will need to do further calculations
if (freeform.OctreeSphereSweepIntersect(oldPosition, Ray, vel,
SphereRadiusRel, @intPoint, @intNormal)) then
begin
if VectorDistance2(oldPosition, intPoint) <= sqr(sphereRadius) then
begin
// sphere is intersecting triangle
intNormal := VectorScale(VectorSubtract(oldPosition,
intPoint), 1.0001);
end
else
begin
// sphere is not intersecting triangle
// intNormal:=VectorSubtract(oldPosition,intPoint); //not correct but works okay at small time steps
// intNormal:=VectorScale(VectorNormalize(intNormal),SphereRadius+0.0001);
if RayCastSphereInterSect(intPoint, VectorNormalize(VectorNegate(Ray)
), oldPosition, sphereRadius, pointOnSphere, point2OnSphere) > 0
then
intNormal := VectorScale(VectorSubtract(oldPosition,
pointOnSphere), 1.0001)
// intNormal:=VectorScale(VectorNormalize(VectorSubtract(oldPosition,PointOnSphere)),SphereRadius+0.001)//VectorDistance(oldPosition,PointOnSphere));
else
begin
// Assert(False); //this shouldn't happen (this is here for debugging)
intNormal := VectorScale(VectorSubtract(oldPosition,
intPoint), 1.0001);
end;
end;
// calculate position of centre of sphere when collision occurs
collisionPosition := VectorAdd(intPoint, intNormal);
oldPosition := collisionPosition;
// calculate distance that wasn't travelled, due to obstacle
newRay := VectorSubtract(newPosition, collisionPosition);
// calculate new direction when a wall is hit (could add bouncing to this)
newDirection := VectorCrossProduct(intNormal,
VectorCrossProduct(newRay, intNormal));
if VectorNorm(newDirection) > 0 then
NormalizeVector(newDirection);
// calculate distance that it should slide (depends on angle between plane & ray)
slidedistance := vectorDotProduct(newRay, newDirection);
// still need to implement friction properly
// if abs(SlideDistance)<10*deltaTime then SlideDistance:=0;
ScaleVector(newDirection, slidedistance);
// calculate new position sphere is heading towards
newPosition := VectorAdd(collisionPosition, newDirection);
Ray := newDirection;
vel := VectorLength(Ray);
// display arrows for collision normals & slide direction
if (i = 0) and (behaviour.ShowArrows) then
DrawArrows(intPoint, intNormal, Ray, behaviour.ArrowLine1,
behaviour.ArrowLine4)
else if (i = 1) and (behaviour.ShowArrows) then
DrawArrows(intPoint, intNormal, Ray, behaviour.ArrowLine2,
behaviour.ArrowLine5)
else if (i = 2) and (behaviour.ShowArrows) then
DrawArrows(intPoint, intNormal, Ray, behaviour.ArrowLine3,
behaviour.ArrowLine6)
else if i = 6 then
begin
// caption:=FloatToStr(vectordistance(newPosition,oldPosition));
newPosition := oldPosition;
break;
end;
// check if very small motion (e.g. when stuck in a corner)
if vel < 1E-10 then // deltaTime then
begin
newPosition := oldPosition;
break;
end;
CollisionState := TCollisionState.Create();
CollisionState.Position := oldPosition;
CollisionState.Contact.intNormal := intNormal;
CollisionState.Contact.intPoint := intPoint;
CollisionState.Time := TThread.GetTickCount();
behaviour.CollisionStates.add(CollisionState);
end
else // no collision occured, so quit loop
begin
if i = 0 then
Result := false;
break;
end;
end; // end i loop
Velocity := Ray;
end;
// ------------------
// ------------------ TVXBFPSMovement ------------------
// ------------------
constructor TVXBFPSMovement.Create(aOwner: TXCollection);
procedure setupArrow(arrow: TVXArrowLine; color: TColor);
begin
with arrow do
begin
slices := 16;
stacks := 4;
TopArrowHeadHeight := 0.1;
TopArrowHeadRadius := 0.04;
TopRadius := 0.02;
BottomArrowHeadHeight := 0.05;
BottomArrowHeadRadius := 0.02;
BottomRadius := 0.02;
Material.FrontProperties.Diffuse.AsWinColor := color;
end;
end;
begin
inherited Create(aOwner);
Velocity := NullHmgVector;
sphereRadius := -1;
CollisionGroup := 0;
CollisionStates := TCollisionStates.Create;
// FIXME: Creating arrows here, but they should be only added when
// a "showArrows" property changed
ArrowLine1 := TVXArrowLine.Create(nil);
setupArrow(ArrowLine1, TColors.Red);
ArrowLine2 := TVXArrowLine.Create(nil);
setupArrow(ArrowLine2, TColors.Green);
ArrowLine3 := TVXArrowLine.Create(nil);
setupArrow(ArrowLine3, TColors.Blue);
ArrowLine4 := TVXArrowLine.Create(nil);
setupArrow(ArrowLine4, TColors.Silver);
ArrowLine5 := TVXArrowLine.Create(nil);
setupArrow(ArrowLine5, TColors.Silver);
ArrowLine6 := TVXArrowLine.Create(nil);
setupArrow(ArrowLine6, TColors.Silver);
dirGl := TVXDirectOpenVX.Create(nil);
dirGl.OnRender := RenderArrowLines;
oldPosition := OwnerBaseSceneObject.Position.AsVector;
FManagerName := '';
end;
destructor TVXBFPSMovement.Destroy;
var
i: integer;
begin
// remove all states
for i := 0 to CollisionStates.count - 1 do
TCollisionState(CollisionStates[i]).Free;
FreeAndNil(CollisionStates);
// remove all objects used to display graphical results of collisions
FreeAndNil(ArrowLine1);
FreeAndNil(ArrowLine2);
FreeAndNil(ArrowLine3);
FreeAndNil(ArrowLine4);
FreeAndNil(ArrowLine5);
FreeAndNil(ArrowLine6);
FreeAndNil(dirGl);
inherited Destroy;
end;
class function TVXBFPSMovement.FriendlyName: String;
begin
Result := 'FPS Movement';
end;
procedure TVXBFPSMovement.WriteToFiler(writer: TWriter);
begin
inherited WriteToFiler(writer);
with writer do
begin
writeInteger(0); // ArchiveVersion 0 (initial)
writeInteger(FCollisionGroup);
WriteSingle(FSphereRadius);
WriteBoolean(FGravityEnabled);
WriteBoolean(FShowArrows);
if assigned(FManager) then
WriteString(FManager.GetNamePath)
else
WriteString('');
end;
end;
procedure TVXBFPSMovement.ReadFromFiler(reader: TReader);
var
archiveVersion: integer;
begin
inherited ReadFromFiler(reader);
with reader do
begin
archiveVersion := readInteger;
assert(archiveVersion = 0, 'Wrong ArchiveVersion for TVXBFPSMovement');
CollisionGroup := readInteger;
sphereRadius := ReadSingle;
GravityEnabled := ReadBoolean;
ShowArrows := ReadBoolean;
FManagerName := ReadString;
end;
end;
procedure TVXBFPSMovement.Loaded;
var
mng: TComponent;
begin
inherited Loaded;
if FManagerName <> '' then
begin
mng := FindManager(TVXFPSMovementManager, FManagerName);
if assigned(mng) then
Manager := TVXFPSMovementManager(mng);
FManagerName := '';
end;
end;
procedure TVXBFPSMovement.setShowArrows(value: boolean);
begin
FShowArrows := value;
dirGl.Visible := value;
if (OwnerBaseSceneObject <> nil) and
not(csDesigning in OwnerBaseSceneObject.ComponentState) then
begin
ArrowLine1.MoveTo(OwnerBaseSceneObject.Parent);
ArrowLine2.MoveTo(OwnerBaseSceneObject.Parent);
ArrowLine3.MoveTo(OwnerBaseSceneObject.Parent);
ArrowLine4.MoveTo(OwnerBaseSceneObject.Parent);
ArrowLine5.MoveTo(OwnerBaseSceneObject.Parent);
ArrowLine6.MoveTo(OwnerBaseSceneObject.Parent);
dirGl.MoveTo(OwnerBaseSceneObject.Parent);
end;
end;
procedure TVXBFPSMovement.MoveForward(Distance: single);
var
prevObj: TVXBaseSceneObject;
begin
Assert(assigned(Manager),
'Manager not assigned on TVXBFPSMovement behaviour!');
prevObj := Manager.Navigator.MovingObject;
Manager.Navigator.MovingObject := OwnerBaseSceneObject;
Manager.Navigator.MoveForward(Distance);
Manager.Navigator.MovingObject := prevObj;
end;
procedure TVXBFPSMovement.StrafeHorizontal(Distance: single);
var
prevObj: TVXBaseSceneObject;
begin
Assert(assigned(Manager),
'Manager not assigned on TVXBFPSMovement behaviour!');
prevObj := Manager.Navigator.MovingObject;
Manager.Navigator.MovingObject := OwnerBaseSceneObject;
Manager.Navigator.StrafeHorizontal(Distance);
Manager.Navigator.MovingObject := prevObj;
end;
procedure TVXBFPSMovement.StrafeVertical(Distance: single);
var
prevObj: TVXBaseSceneObject;
begin
Assert(assigned(Manager),
'Manager not assigned on TVXBFPSMovement behaviour!');
prevObj := Manager.Navigator.MovingObject;
Manager.Navigator.MovingObject := OwnerBaseSceneObject;
Manager.Navigator.StrafeVertical(Distance);
Manager.Navigator.MovingObject := prevObj;
end;
procedure TVXBFPSMovement.TurnHorizontal(Angle: single);
var
prevObj: TVXBaseSceneObject;
begin
Assert(assigned(Manager),
'Manager not assigned on TVXBFPSMovement behaviour!');
prevObj := Manager.Navigator.MovingObject;
Manager.Navigator.MovingObject := OwnerBaseSceneObject;
Manager.Navigator.TurnHorizontal(Angle);
Manager.Navigator.MovingObject := prevObj;
end;
procedure TVXBFPSMovement.TurnVertical(Angle: single);
var
prevObj: TVXBaseSceneObject;
begin
assert(assigned(Manager),
'Manager not assigned on TVXBFPSMovement behaviour!');
prevObj := Manager.Navigator.MovingObject;
Manager.Navigator.MovingObject := OwnerBaseSceneObject;
Manager.Navigator.TurnVertical(Angle);
Manager.Navigator.MovingObject := prevObj;
end;
procedure TVXBFPSMovement.Straighten;
var
prevObj: TVXBaseSceneObject;
begin
Assert(assigned(Manager),
'Manager not assigned on TVXBFPSMovement behaviour!');
prevObj := Manager.Navigator.MovingObject;
Manager.Navigator.MovingObject := OwnerBaseSceneObject;
Manager.Navigator.Straighten;
Manager.Navigator.MovingObject := prevObj;
end;
procedure TVXBFPSMovement.DoProgress(const progressTime: TVXProgressTimes);
var
newPosition: TVector;
CollisionState: TCollisionState;
begin
inherited DoProgress(progressTime);
Assert(assigned(Manager), 'FPS Manager not assigned to behaviour.');
// make arrowlines invisible (they are made visible in SphereSweepAndSlide)
ArrowLine1.Visible := false;
ArrowLine2.Visible := false;
ArrowLine3.Visible := false;
ArrowLine4.Visible := false;
ArrowLine5.Visible := false;
ArrowLine6.Visible := false;
CollisionState := TCollisionState.Create();
CollisionState.Position := oldPosition;
CollisionStates.add(CollisionState);
// this is the position we are trying to move to with controls
newPosition := OwnerBaseSceneObject.Position.AsVector;
// Change in position = velocity * time taken
if GravityEnabled then
newPosition.Y := newPosition.Y - Manager.MovementScale * 0.5 *
progressTime.deltaTime;
// do some magic!!! and store new position in newPosition
if sphereRadius < 0 then
Manager.SphereSweepAndSlide(self, oldPosition, Velocity, newPosition,
OwnerBaseSceneObject.boundingSphereRadius)
else
Manager.SphereSweepAndSlide(self, oldPosition, Velocity, newPosition,
sphereRadius);
OwnerBaseSceneObject.Position.AsVector := newPosition;
oldPosition := newPosition;
if CollisionStates.count > 0 then
begin
CollisionState := TCollisionState(CollisionStates.First);
TickCount := TThread.GetTickCount();
// remove all old states
while (CollisionState <> nil) and
(CollisionState.Time < tickCount - Manager.DisplayTime) do
begin
CollisionStates.Remove(CollisionState);
CollisionState.Free;
if CollisionStates.count = 0 then
exit;
CollisionState := TCollisionState(CollisionStates.First);
end;
end;
end;
procedure TVXBFPSMovement.RenderArrowLines(Sender: TObject;
var rci: TVXRenderContextInfo);
var
x, y, z, t: single;
i: integer;
CollisionState: TCollisionState;
begin
// caption:= IntToStr(CollisionStates.Count);
glColor3f(1, 1, 1);
rci.VXStates.Disable(stLighting);
// draw position trail
glBegin(GL_LINE_STRIP);
for i := 0 to CollisionStates.count - 1 do
begin
CollisionState := TCollisionState(CollisionStates.Items[i]);
x := CollisionState.Position.X;
y := CollisionState.Position.Y;
z := CollisionState.Position.Z;
glVertex3f(x, y, z);
end;
glEnd();
// draw normals trail
glBegin(GL_LINES);
for i := 0 to CollisionStates.count - 1 do
begin
CollisionState := TCollisionState(CollisionStates.Items[i]);
t := (Manager.DisplayTime - (tickCount - CollisionState.Time)) /
Manager.DisplayTime;
glColor3f(t, t, t);
glVertex3f(CollisionState.Contact.intPoint.X,
CollisionState.Contact.intPoint.Y, CollisionState.Contact.intPoint.Z);
glVertex3f(CollisionState.Contact.intPoint.X +
CollisionState.Contact.intNormal.X, //VKSphere4.Radius,
CollisionState.Contact.intPoint.Y + CollisionState.Contact.intNormal.Y,
//VKSphere4.Radius,
CollisionState.Contact.intPoint.Z + CollisionState.Contact.intNormal.Z);
//VKSphere4.Radius);
end;
glEnd();
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterXCollectionItemClass(TVXMapCollectionItem);
RegisterXCollectionItemClass(TVXBFPSMovement);
finalization
UnregisterXCollectionItemClass(TVXMapCollectionItem);
UnregisterXCollectionItemClass(TVXBFPSMovement);
end.
|
unit TaxLiabilities_SummaEnable;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxCheckBox, cxContainer, cxEdit, cxLabel,
cxDBLabel, StdCtrls, cxButtons, cxControls, Ibase,cxGroupBox,TaxLiabilities_DM,
cxTextEdit, cxDBEdit;
type
TTaxLiabilitiesSummaEnableForm = class(TForm)
NameTaxLiabilitiesGroupBox: TcxGroupBox;
cxGroupBox2: TcxGroupBox;
YesButton: TcxButton;
CancelButton: TcxButton;
SummaTaxable20CheckBox: TcxCheckBox;
SummaPDVCheckBox: TcxCheckBox;
SummaTaxableCheckBox: TcxCheckBox;
SummaExemptCheckBox: TcxCheckBox;
SummaExportCheckBox: TcxCheckBox;
SummaEnableDBTextEdit: TcxDBTextEdit;
procedure CancelButtonClick(Sender: TObject);
procedure YesButtonClick(Sender: TObject);
private
PDb_Handle : TISC_DB_HANDLE;
public
constructor Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE);reintroduce;
end;
var
TaxLiabilitiesSummaEnableForm: TTaxLiabilitiesSummaEnableForm;
implementation
{$R *.dfm}
constructor TTaxLiabilitiesSummaEnableForm.Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE);
begin
inherited Create(AOwner);
PDb_Handle := Db_Handle;
end;
procedure TTaxLiabilitiesSummaEnableForm.CancelButtonClick(Sender: TObject);
begin
Close;
end;
procedure TTaxLiabilitiesSummaEnableForm.YesButtonClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
end.
|
{*******************************************************************************
* uDepartmentsData *
* *
* Модуль данных справочника подразделений *
* Copyright © 2002-2005, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uDepartmentsData;
interface
uses
SysUtils, Classes, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet,
cxClasses, cxStyles, cxGridTableView, FIBQuery, pFIBQuery, frxClass,
frxDBSet, frxDesgn, ExtCtrls, frxExportPDF, frxExportRTF, frxExportHTML,
frxExportXLS, frxExportTXT, Controls;
type
TdmDepartments = class(TDataModule)
Database: TpFIBDatabase;
DefaultTransaction: TpFIBTransaction;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
SelectDepartments: TpFIBDataSet;
MoveQuery: TpFIBQuery;
GetRoot: TpFIBDataSet;
DepTypesSelect: TpFIBDataSet;
DepTypesSelectID_DEP_TYPE: TFIBIntegerField;
DepTypesSelectNAME_DEP_TYPE: TFIBStringField;
SelectDepartmentsID_DEPARTMENT: TFIBIntegerField;
SelectDepartmentsID_PARENT: TFIBIntegerField;
SelectDepartmentsNAME_SHORT: TFIBStringField;
SelectDepartmentsDISPLAY_ORDER: TFIBIntegerField;
SelectDepartmentsDISPLAY_ORDER2: TFIBIntegerField;
SelectDepartmentsNAME_FULL: TFIBStringField;
SelectDepartmentsPATH: TFIBStringField;
SelectDepartmentsDEPARTMENT_CODE: TFIBStringField;
SelectDepartmentsDISPLAY_NAME: TStringField;
frxDesigner1: TfrxDesigner;
DepartmentsDS: TfrxDBDataset;
DepPropDS: TpFIBDataSet;
DepPropDSID_PROPERTY: TFIBIntegerField;
DepPropDSNAME_PROPERTY: TFIBStringField;
DepPropDSDATE_BEG: TFIBDateField;
DepPropDSDATE_END: TFIBDateField;
DepPropDataSource: TDataSource;
SpDepProp: TpFIBDataSet;
DeleteProp: TpFIBQuery;
SpDepPropID_PROPERTY: TFIBIntegerField;
SpDepPropNAME_PROPERTY: TFIBStringField;
Timer1: TTimer;
SelectDepartmentsIs_Deleted: TIntegerField;
SelectDepartmentsUse_End: TDateTimeField;
RestoreQuery: TpFIBQuery;
TeleportDepartment: TpFIBQuery;
PrintProp: TpFIBDataSet;
ReportDBSet: TfrxDBDataset;
DepartmentsReport: TfrxReport;
procedure SelectDepartmentsCalcFields(DataSet: TDataSet);
procedure SelectDepartmentsAfterScroll(DataSet: TDataSet);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
public
InputActDate: TDate;
procedure GetDepType(var Value: Variant; var DisplayText: string);
end;
implementation
uses uSelectForm, Variants;
{$R *.dfm}
procedure TdmDepartments.GetDepType(var Value: Variant; var DisplayText: string);
begin
if qSelect(DepTypesSelect) then
begin
Value := DepTypesSelect['Id_Dep_Type'];
DisplayText := DepTypesSelect['Name_Dep_Type'];
end;
end;
procedure TdmDepartments.SelectDepartmentsCalcFields(DataSet: TDataSet);
begin
if SelectDepartments.IsEmpty then Exit;
if Trim(SelectDepartments['Name_Short']) = '' then
SelectDepartments['Display_Name'] := SelectDepartments['Name_Full']
else SelectDepartments['Display_Name'] := SelectDepartments['Name_Full'] +
'(' + SelectDepartments['Name_Short'] + ')';
if SelectDepartments['Is_Deleted'] = 1 then
SelectDepartments['Display_Name'] := SelectDepartments['Display_Name'] +
' [вилучено ' + DateToStr(SelectDepartments['Use_End']) + ']';
end;
procedure TdmDepartments.SelectDepartmentsAfterScroll(DataSet: TDataSet);
begin
SelectDepartmentsCalcFields(DataSet);
{ if not DataSet.IsEmpty then
begin
DepPropDS.Close;
DepPropDS.ParamByName('Id_Department').AsInteger := DataSet['Id_Department'];
DepPropDS.Open;
end;}
end;
procedure TdmDepartments.Timer1Timer(Sender: TObject);
var
id_prop: Variant;
begin
if not SelectDepartments.IsEmpty then
begin
id_prop := Null;
if not DepPropDS.IsEmpty then
id_prop := DepPropDS['Id_Property'];
DepPropDS.Close;
DepPropDS.ParamByName('Id_Department').AsInteger :=
SelectDepartments['Id_Department'];
DepPropDS.Open;
if not VarIsNull(id_prop) then
DepPropDS.Locate('Id_Property', id_prop, [])
end;
end;
end.
|
unit Dienst.nfsBackup;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs,
Objekt.Allgemein, Objekt.Backupchecker, Objekt.Option, Objekt.OptionList, Objekt.Maildat,
Objekt.SendMail;
type
TnfsBackup = class(TService)
procedure ServiceCreate(Sender: TObject);
procedure ServiceDestroy(Sender: TObject);
procedure ServiceAfterInstall(Sender: TService);
procedure ServiceAfterUninstall(Sender: TService);
procedure ServiceBeforeInstall(Sender: TService);
procedure ServiceBeforeUninstall(Sender: TService);
procedure ServiceContinue(Sender: TService; var Continued: Boolean);
procedure ServiceExecute(Sender: TService);
procedure ServicePause(Sender: TService; var Paused: Boolean);
procedure ServiceShutdown(Sender: TService);
procedure ServiceStart(Sender: TService; var Started: Boolean);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
private
fDataFile: string;
fProgrammpfad: string;
fBackupchecker: TBackupchecker;
fMaildat: TMailDat;
procedure BackupLauft(Sender: TObject; aOption: TOption);
procedure BackupEndet(Sender: TObject; aOption: TOption);
procedure ErrorBackup(Sender: TObject; aOption: TOption; aError: string);
procedure MailError(Sender: TObject; aError: string);
public
function GetServiceController: TServiceController; override;
end;
var
nfsBackup: TnfsBackup;
implementation
{$R *.dfm}
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
nfsBackup.Controller(CtrlCode);
end;
function TnfsBackup.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TnfsBackup.ServiceCreate(Sender: TObject);
begin
AllgemeinObj := TAllgemeinObj.create;
AllgemeinObj.Log.DienstInfo('ServiceCreate');
AllgemeinObj.Log.DienstInfo('Version 1.0.0 vom 17.09.2018 10:30');
fProgrammpfad := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
AllgemeinObj.Log.DebugInfo('fProgrammpfad='+fProgrammpfad);
fDataFile := fProgrammpfad + 'nfsBackup.dat';
fBackupchecker := TBackupchecker.Create;
AllgemeinObj.Log.DebugInfo('fDataFile='+fDataFile);
fBackupChecker.FullDataFilename := fDataFile;
fBackupchecker.OnStartBackup := BackupLauft;
fBackupchecker.OnEndBackup := BackupEndet;
fBackupchecker.OnBackupError := ErrorBackup;
fMaildat := TMailDat.Create;
end;
procedure TnfsBackup.ServiceDestroy(Sender: TObject);
begin
FreeAndNil(fBackupchecker);
FreeAndNil(fMaildat);
FreeAndNil(AllgemeinObj);
end;
procedure TnfsBackup.ServiceExecute(Sender: TService);
begin
AllgemeinObj.Log.DienstInfo('Dienst läuft');
fBackupchecker.TimerEnabled := true;
while not Terminated do
begin
sleep(100);
ServiceThread.ProcessRequests(false);
end;
fBackupchecker.TimerEnabled := false;
AllgemeinObj.Log.DienstInfo('Dienst ist beendet');
end;
procedure TnfsBackup.ServicePause(Sender: TService; var Paused: Boolean);
begin
AllgemeinObj.Log.DienstInfo('ServicePause');
end;
procedure TnfsBackup.ServiceShutdown(Sender: TService);
begin
AllgemeinObj.Log.DienstInfo('Shutdown');
end;
procedure TnfsBackup.ServiceStart(Sender: TService; var Started: Boolean);
begin
AllgemeinObj.Log.DienstInfo('ServiceStart');
end;
procedure TnfsBackup.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
AllgemeinObj.Log.DienstInfo('ServiceStop');
end;
procedure TnfsBackup.ServiceAfterInstall(Sender: TService);
begin
AllgemeinObj.Log.DienstInfo('AfterInstall');
end;
procedure TnfsBackup.ServiceAfterUninstall(Sender: TService);
begin
AllgemeinObj.Log.DienstInfo('AfterUnInstall');
end;
procedure TnfsBackup.ServiceBeforeInstall(Sender: TService);
begin
AllgemeinObj.Log.DienstInfo('BeforeInstall');
end;
procedure TnfsBackup.ServiceBeforeUninstall(Sender: TService);
begin
AllgemeinObj.Log.DienstInfo('BeforeUnInstall');
end;
procedure TnfsBackup.ServiceContinue(Sender: TService; var Continued: Boolean);
begin
AllgemeinObj.Log.DienstInfo('ServiceContinue');
end;
procedure TnfsBackup.BackupEndet(Sender: TObject; aOption: TOption);
begin
AllgemeinObj.Log.BackupInfo('Backup beendet - ' + aOption.Datenbank);
AllgemeinObj.Log.BackupInfo(' ');
end;
procedure TnfsBackup.BackupLauft(Sender: TObject; aOption: TOption);
begin
AllgemeinObj.Log.BackupInfo('');
AllgemeinObj.Log.BackupInfo('Backup läuft - ' + aOption.Datenbank);
end;
procedure TnfsBackup.ErrorBackup(Sender: TObject; aOption: TOption;
aError: string);
var
Mail: TSendMail;
s: string;
begin
AllgemeinObj.Log.BackupInfo('Backupfehler: ' + aError);
Mail := TSendMail.Create;
try
Mail.OnMailError := MailError;
fMaildat.Load;
if (Trim(fMaildat.Mail) = '') or (Trim(fMaildat.Passwort) = '') then
begin
AllgemeinObj.Log.DienstInfo('Mail kann nicht gesendet werden, da EMail-Adresse und oder EMail-Passwort fehlt');
AllgemeinObj.Log.DebugInfo('Mail kann nicht gesendet werden, da EMail-Adresse und oder EMail-Passwort fehlt');
exit;
end;
s := 'Backupfehler: ' + sLineBreak +
'Servername: ' + aOption.Servername + sLineBreak +
'Datenbank: ' + aOption.Datenbank + sLineBreak +
'Backupdatei: ' + aOption.Backupdatei + sLineBreak + sLineBreak +
'Fehlerbeschreibung:' + sLineBreak + aError;
Mail.Host := fMaildat.Host;
Mail.MeineEMail := fMaildat.Mail;
Mail.MeinPasswort := fMaildat.Passwort;
Mail.MeinUsername := fMaildat.User;
Mail.Betreff := fMaildat.Betreff;
Mail.Nachricht := s;
Mail.EMailAdresse := fMaildat.MailAn;
Mail.OnMailError := MailError;
if fMaildat.Provider = pvExchange then
Mail.SendenUeberExchange;
if fMaildat.Provider = pvGmail then
Mail.SendenUeberGMail;
if fMaildat.Provider = pvWeb then
Mail.SendenUeberWebDe;
finally
FreeAndNil(Mail);
end;
end;
procedure TnfsBackup.MailError(Sender: TObject; aError: string);
begin
AllgemeinObj.Log.DebugInfo('Fehler beim Senden einer Mail: ' + aError);
AllgemeinObj.Log.DienstInfo('Fehler beim Senden einer Mail: ' + aError);
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.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 DPM.Core.Dependency.Resolution;
interface
uses
Spring.Collections,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Package.Interfaces,
DPM.Core.Dependency.Version,
DPM.Core.Dependency.Interfaces;
type
TResolution = class(TInterfacedObject, IResolution)
private
FPackage : IPackageInfo;
FParentId : string;
FVersionRange : TVersionRange;
FProject : string;
protected
function GetIsTopLevel : boolean;
function GetPackage : IPackageInfo;
function GetParentId : string;
function GetProject : string;
function GetVersionRange : TVersionRange;
procedure SetVersionRange(const value : TVersionRange);
function Clone(const parentId : string) : IResolution;
public
constructor Create(const package : IPackageInfo; const range : TVersionRange; const parentId : string; const project : string);
end;
implementation
uses
System.SysUtils,
DPM.Core.Constants;
{ TResolution }
function TResolution.Clone(const parentId: string): IResolution;
begin
result := TResolution.Create(FPackage, FVersionRange, parentId, FProject);
end;
constructor TResolution.Create(const package : IPackageInfo; const range : TVersionRange; const parentId : string; const project : string);
begin
FPackage := package;
FVersionRange := range;
if FVersionRange.IsEmpty then
raise EArgumentOutOfRangeException.Create('Empty version range provided for resolution');
FParentId := parentId;
FProject := project;
end;
function TResolution.GetIsTopLevel: boolean;
begin
result := FParentId = cRootNode;
end;
function TResolution.GetPackage : IPackageInfo;
begin
result := FPackage;
end;
function TResolution.GetParentId : string;
begin
result := FParentId;
end;
function TResolution.GetProject: string;
begin
result := FProject;
end;
function TResolution.GetVersionRange : TVersionRange;
begin
result := FVersionRange;
end;
procedure TResolution.SetVersionRange(const value : TVersionRange);
begin
FVersionRange := value;
end;
end.
|
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
unit uConexoes;
interface
uses
FireDAC.Comp.Client, FireDAC.Phys, FireDAC.Phys.Intf,
FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.Stan.Def,
System.Classes, uEnum, FireDAC.Comp.UI, uParametrosConexao
, FireDAC.Phys.Oracle
, FireDAC.Phys.OracleDef
;
type
IModelConexao = interface
['{14819F40-456A-4003-AB12-2A14CB87BA4E}']
function GetConexao: TFDConnection;
function AbrirConexao: iModelConexao;
function FecharConexao: iModelConexao;
end;
TModelConexao = class(TInterfacedObject, iModelConexao)
private
oConexao: TFDConnection;
oWaitCursor: TFDGUIxWaitCursor;
oDriverFirebird: TFDPhysFBDriverLink;
oDriverOracle: TFDPhysOracleDriverLink;
procedure CarregarParametros(AParametros: IParametrosConexao);
protected
public
constructor Create(AParametros: IParametrosConexao); overload;
destructor Destroy; override;
function GetConexao: TFDConnection;
function AbrirConexao: iModelConexao;
function FecharConexao: iModelConexao;
class function New(AParametros: IParametrosConexao): iModelConexao;
published
end;
implementation
uses
System.SysUtils;
const
_DRIVERORACLE = 'Ora';
{ TModelConexao }
constructor TModelConexao.Create(AParametros: IParametrosConexao);
begin
oWaitCursor := TFDGUIxWaitCursor.Create(Nil);
oConexao := TFDConnection.Create(Nil);
if (AParametros.GetDriverID = _DRIVERORACLE) then
oDriverOracle := TFDPhysOracleDriverLink.Create(Nil)
else
oDriverFirebird := TFDPhysFBDriverLink.Create(Nil);
CarregarParametros(AParametros);
AbrirConexao;
end;
destructor TModelConexao.Destroy;
begin
oConexao.Free;
inherited;
end;
function TModelConexao.FecharConexao: iModelConexao;
begin
oConexao.Connected := False;
end;
function TModelConexao.GetConexao: TFDConnection;
begin
Result := oConexao;
end;
class function TModelConexao.New(AParametros: IParametrosConexao): iModelConexao;
begin
Result := Self.Create(AParametros);
end;
function TModelConexao.AbrirConexao: iModelConexao;
begin
try
oConexao.Connected := True;
except
on e:Exception do
begin
raise Exception.Create('Erro ao conectar ' + e.Message);
end;
end;
end;
procedure TModelConexao.CarregarParametros(AParametros: IParametrosConexao);
begin
oConexao.Params.Database := AParametros.GetBanco;
oConexao.Params.UserName := AParametros.GetUsuario;
oConexao.Params.Password := AParametros.GetSenha;
oConexao.Params.DriverID := AParametros.GetDriverID;
oConexao.Params.Add('Server=' + AParametros.GetServer);
oConexao.Params.Add('Port=' + AParametros.GetPorta);
end;
end.
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
|
unit GLDMeshFrame;
interface
uses
Classes, Controls, Forms, Buttons, StdCtrls,
GL, GLDTypes, GLDSystem, GLDMesh, GLDNameAndColorFrame;
type
TGLDMeshFrame = class(TFrame)
NameAndColor: TGLDNameAndColorFrame;
GB_SubSelection: TGroupBox;
SB_Vertices: TSpeedButton;
SB_Polygons: TSpeedButton;
SB_Object: TSpeedButton;
GB_Vertices: TGroupBox;
SB_NewVertices: TSpeedButton;
SB_DeleteVertices: TSpeedButton;
GB_Polygons: TGroupBox;
SB_NewPolygons: TSpeedButton;
SB_DeletePolygons: TSpeedButton;
procedure SB_Click(Sender: TObject);
private
FDrawer: TGLDDrawer;
procedure SetDrawer(Value: TGLDDrawer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function HaveMesh: GLboolean;
procedure SetParams(const Name: string; const Color: TGLDColor3ub);
procedure SetParamsFrom(Mesh: TGLDCustomMesh);
property Drawer: TGLDDrawer read FDrawer write SetDrawer;
end;
procedure Register;
implementation
{$R *.dfm}
constructor TGLDMeshFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDrawer := nil;
end;
destructor TGLDMeshFrame.Destroy;
begin
if Assigned(FDrawer) then
begin
if (FDrawer.IOFrame = Self) then
FDrawer.IOFrame := nil;
FDrawer.SelectionType := GLD_ST_OBJECTS;
FDrawer := nil;
end;
inherited Destroy;
end;
function TGLDMeshFrame.HaveMesh: GLboolean;
begin
if Assigned(FDrawer) and
Assigned(FDrawer.EditedObject) and
(FDrawer.EditedObject is TGLDCustomMesh) then
Result := True
else Result := False;
end;
procedure TGLDMeshFrame.SetParams(const Name: string; const Color: TGLDColor3ub);
begin
NameAndColor.NameParam := Name;
NameAndColor.ColorParam := Color;
end;
procedure TGLDMeshFrame.SetParamsFrom(Mesh: TGLDCustomMesh);
begin
if Assigned(Mesh) then
with Mesh do
SetParams(Name, Color.Color3ub);
end;
procedure TGLDMeshFrame.SB_Click(Sender: TObject);
begin
if not Assigned(FDrawer) then Exit;
if not Assigned(FDrawer.EditedObject) then Exit;
if not (FDrawer.EditedObject is TGLDCustomMesh) then Exit;
if Sender = SB_Vertices then
FDrawer.SelectionType := GLD_ST_VERTICES else
if Sender = SB_Polygons then
FDrawer.SelectionType := GLD_ST_POLYGONS else
if Sender = SB_Object then
FDrawer.SelectionType := GLD_ST_OBJECTS else
if Sender = SB_NewVertices then
FDrawer.StartCreatingVertices else
if Sender = SB_DeleteVertices then
TGLDCustomMesh(FDrawer.EditedObject).DeleteSelectedVertices else
if Sender = SB_NewPolygons then
FDrawer.StartCreatingPolygons else
if Sender = SB_DeletePolygons then
TGLDCustomMesh(FDrawer.EditedObject).DeleteSelectedPolygons(True);
end;
procedure TGLDMeshFrame.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and
(Operation = opRemove) then FDrawer := nil;
inherited Notification(AComponent, Operation);
end;
procedure TGLDMeshFrame.SetDrawer(Value: TGLDDrawer);
begin
FDrawer := Value;
NameAndColor.Drawer := FDrawer;
end;
procedure Register;
begin
//RegisterComponents('GLDraw', [TGLDMeshFrame]);
end;
end.
|
unit ZStageUnit;
// ========================================================================
// MesoScan: Z Stage control module
// (c) J.Dempster, Strathclyde Institute for Pharmacy & Biomedical Sciences
// ========================================================================
// 7/6/12 Supports Prior OptiScan II controller
// 14.5.14 Supports voltage-controlled lens positioner
interface
uses
System.SysUtils, System.Classes, Windows, FMX.Dialogs, math ;
type
TZStage = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
FStageType : Integer ; // Type of stage
FEnabled : Boolean ; // Z stage Enabled/disabled flag
ComHandle : THandle ; // Com port handle
ComPortOpen : Boolean ; // Com port open flag
FControlPort : DWord ; // Control port number
FBaudRate : DWord ; // Com port baud rate
ControlState : Integer ; // Z stage control state
Status : String ; // Z stage status report
MoveToRequest : Boolean ; // Go to requested flag
MoveToPosition : Double ; // Position (um) to go to
OverLapStructure : POVERLAPPED ;
procedure OpenCOMPort ;
procedure CloseCOMPort ;
procedure ResetCOMPort ;
procedure SendCommand( const Line : string ) ;
function ReceiveBytes( var EndOfLine : Boolean ) : string ;
procedure SetControlPort( Value : DWord ) ;
procedure SetBaudRate( Value : DWord ) ;
procedure SetEnabled( Value : Boolean ) ;
procedure SetStageType( Value : Integer ) ;
procedure UpdateZPositionOSII ;
procedure UpdateZPositionPZ ;
procedure MoveToOSII( Position : Double ) ;
procedure MoveToPZ( Position : Double ) ;
function GetZScaleFactorUnits : string ;
public
{ Public declarations }
ZPosition : Double ; // Z position (um)
ZScaleFactor : Double ; // Z step scaling factor
ZStepTime : Double ; // Time to perform Z step (s)
procedure Open ;
procedure Close ;
procedure UpdateZPosition ;
procedure MoveTo( Position : Double ) ;
procedure GetZStageTypes( List : TStrings ) ;
procedure GetControlPorts( List : TStrings ) ;
published
Property ControlPort : DWORD read FControlPort write SetControlPort ;
Property BaudRate : DWORD read FBaudRate write SetBaudRate ;
Property Enabled : Boolean read FEnabled write SetEnabled ;
Property StageType : Integer read FStageType write SetStageType ;
Property ZScaleFactorUnits : string read GetZScaleFactorUnits ;
end;
var
ZStage: TZStage;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
uses LabIOUnit;
{$R *.dfm}
const
csIdle = 0 ;
csWaitingForPosition = 1 ;
csWaitingForCompletion = 2 ;
stNone = 0 ;
stOptiscanII = 1 ;
stPiezo = 2 ;
procedure TZStage.DataModuleCreate(Sender: TObject);
// ---------------------------------------
// Initialisations when module is created
// ---------------------------------------
begin
FStageType := stNone ;
FEnabled := False ;
ComPortOpen := False ;
FControlPort := 0 ;
FBaudRate := 9600 ;
Status := '' ;
ControlState := csIdle ;
ZPosition := 0.0 ;
ZscaleFactor := 1.0 ;
MoveToRequest := False ;
MoveToPosition := 0.0 ;
end;
procedure TZStage.DataModuleDestroy(Sender: TObject);
// --------------------------------
// Tidy up when module is destroyed
// --------------------------------
begin
if ComPortOpen then CloseComPort ;
end;
procedure TZStage.GetZStageTypes( List : TStrings ) ;
// -----------------------------------
// Get list of supported Z stage types
// -----------------------------------
begin
List.Clear ;
List.Add('None') ;
List.Add('Prior Optiscan II') ;
List.Add('Piezo (Voltage Controlled)');
end;
procedure TZStage.GetControlPorts( List : TStrings ) ;
// -----------------------------------
// Get list of available control ports
// -----------------------------------
var
i : Integer ;
iDev: Integer;
begin
List.Clear ;
case FStageType of
stOptiscanII : begin
// COM ports
for i := 1 to 16 do List.Add(format('COM%d',[i]));
end ;
stPiezo : begin
// Analog outputs
for iDev := 1 to LabIO.NumDevices do
for i := 0 to LabIO.NumDACs[iDev]-1 do begin
List.Add(Format('Dev%d:AO%d',[iDev,i])) ;
end;
end;
else begin
List.Add('None');
end ;
end;
end;
procedure TZStage.Open ;
// ---------------------------
// Open Z stage for operation
// ---------------------------
begin
// Close COM port (if open)
if ComPortOpen then CloseComPort ;
case FStageType of
stOptiscanII : begin
OpenComPort ;
end ;
stPiezo : begin
end;
end;
end;
function TZStage.GetZScaleFactorUnits : string ;
// -------------------------------
// Return units for Z scale factor
// -------------------------------
begin
case FStageType of
stOptiscanII : Result := 'steps/um' ;
stPiezo : Result := 'V/um' ;
else Result := '' ;
end;
end;
procedure TZStage.Close ;
// ---------------------------
// Close down Z stage operation
// ---------------------------
begin
if ComPortOpen then CloseComPort ;
end;
procedure TZStage.UpdateZPosition ;
// ---------------------------
// Update position of Z stage
// ---------------------------
begin
case FStageType of
stOptiscanII : UpdateZPositionOSII ;
stPiezo : UpdateZPositionPZ ;
end;
end;
procedure TZStage.MoveTo( Position : Double ) ;
// -----------------
// Go to Z position
// -----------------
begin
case FStageType of
stOptiscanII : MoveToOSII( Position ) ;
stPiezo : MoveToPZ( Position ) ;
end;
end;
procedure TZStage.OpenCOMPort ;
// ----------------------------------------
// Establish communications with COM port
// ----------------------------------------
var
DCB : TDCB ; { Device control block for COM port }
CommTimeouts : TCommTimeouts ;
begin
if ComPortOpen then Exit ;
{ Open com port }
ComHandle := CreateFile( PCHar(format('COM%d',[ControlPort+1])),
GENERIC_READ or GENERIC_WRITE,
0,
Nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0) ;
if ComHandle < 0 then Exit ;
{ Get current state of COM port and fill device control block }
GetCommState( ComHandle, DCB ) ;
{ Change settings to those required for 1902 }
DCB.BaudRate := CBR_9600 ;
DCB.ByteSize := 8 ;
DCB.Parity := NOPARITY ;
DCB.StopBits := ONESTOPBIT ;
{ Update COM port }
SetCommState( ComHandle, DCB ) ;
{ Initialise Com port and set size of transmit/receive buffers }
SetupComm( ComHandle, 4096, 4096 ) ;
{ Set Com port timeouts }
GetCommTimeouts( ComHandle, CommTimeouts ) ;
CommTimeouts.ReadIntervalTimeout := $FFFFFFFF ;
CommTimeouts.ReadTotalTimeoutMultiplier := 0 ;
CommTimeouts.ReadTotalTimeoutConstant := 0 ;
CommTimeouts.WriteTotalTimeoutMultiplier := 0 ;
CommTimeouts.WriteTotalTimeoutConstant := 5000 ;
SetCommTimeouts( ComHandle, CommTimeouts ) ;
ComPortOpen := True ;
Status := '' ;
ControlState := csIdle ;
end ;
procedure TZStage.CloseCOMPort ;
// ----------------------
// Close serial COM port
// ----------------------
begin
if ComPortOpen then CloseHandle( ComHandle ) ;
ComPortOpen := False ;
end ;
procedure TZStage.SendCommand(
const Line : string { Text to be sent to Com port }
) ;
{ --------------------------------------
Write a line of ASCII text to Com port
--------------------------------------}
var
i : Integer ;
nWritten,nC : DWORD ;
xBuf : array[0..258] of ansichar ;
Overlapped : Pointer ;
OK : Boolean ;
begin
if not FEnabled then Exit ;
{ Copy command line to be sent to xMit buffer and and a CR character }
nC := Length(Line) ;
for i := 1 to nC do xBuf[i-1] := ANSIChar(Line[i]) ;
xBuf[nC] := #13 ;
Inc(nC) ;
// xBuf[nC] := chr(10) ;
// Inc(nC) ;
Overlapped := Nil ;
OK := WriteFile( ComHandle, xBuf, nC, nWritten, Overlapped ) ;
if (not OK) or (nWRitten <> nC) then begin
//ShowMessage( ' Error writing to COM port ' ) ;
FEnabled := False ;
end;
end ;
function TZStage.ReceiveBytes(
var EndOfLine : Boolean
) : string ; { bytes received }
{ -------------------------------------------------------
Read bytes from Com port until a line has been received
-------------------------------------------------------}
var
Line : string ;
rBuf : array[0..255] of ansichar ;
ComState : TComStat ;
PComState : PComStat ;
NumBytesRead,ComError,NumRead : DWORD ;
begin
if not FEnabled then Exit ;
PComState := @ComState ;
Line := '' ;
rBuf[0] := ' ' ;
NumRead := 0 ;
EndOfLine := False ;
Result := '' ;
{ Find out if there are any characters in receive buffer }
ClearCommError( ComHandle, ComError, PComState ) ;
// Read characters until CR is encountered
while (NumRead < ComState.cbInQue) and (RBuf[0] <> #13) do begin
ReadFile( ComHandle,rBuf,1,NumBytesRead,OverlapStructure ) ;
if rBuf[0] <> #13 then Line := Line + String(rBuf[0])
else EndOfLine := True ;
//outputdebugstring(pwidechar(RBuf[0]));
Inc( NumRead ) ;
end ;
Result := Line ;
end ;
procedure TZStage.UpdateZPositionOSII ;
// ----------------------------------------
// Update position of Z stage (Optoscan II)
// ----------------------------------------
var
EndOfLine : Boolean ;
begin
case ControlState of
csIdle :
begin
if MoveToRequest then
begin
// Go to required position
SendCommand(format('U %d',[Round((MoveToPosition-ZPosition)*ZScaleFactor)])) ;
ControlState := csWaitingForCompletion ;
MoveToRequest := False ;
end
else
begin
// Request stage position
SendCommand( 'PZ' ) ;
ControlState := csWaitingForPosition ;
end ;
end;
csWaitingForPosition :
begin
Status := Status + ReceiveBytes( EndOfLine ) ;
if EndOfLine then
begin
ZScaleFactor := Max(ZScaleFactor,1E-3) ;
ZPosition := StrToInt64(Status)/ZScaleFactor ;
Status := '' ;
ControlState := csIdle ;
end;
end ;
csWaitingForCompletion :
begin
Status := ReceiveBytes( EndOfLine ) ;
if EndOfLine then
begin
Status := '' ;
ControlState := csIdle ;
end;
end;
end;
end;
procedure TZStage.MoveToOSII( Position : Double ) ;
// ------------------------------
// Go to Z position (Optoscan II)
// ------------------------------
begin
MoveToPosition := Position ;
MoveToRequest := True ;
end;
procedure TZStage.SetControlPort( Value : DWord ) ;
// ----------------
// Set Control Port
//-----------------
begin
FControlPort := Max(Value,0) ;
ResetCOMPort ;
end;
procedure TZStage.SetBaudRate( Value : DWord ) ;
// ----------------------
// Set com Port baud rate
//-----------------------
begin
if Value <= 0 then Exit ;
FBaudRate := Value ;
ResetCOMPort ;
end;
procedure TZStage.ResetCOMPort ;
// --------------------------
// Reset COM port (if in use)
// --------------------------
begin
case FStageType of
stOptiscanII :
begin
if ComPortOpen then
begin
CloseComPort ;
OpenComPort ;
end;
end;
end;
end;
procedure TZStage.SetEnabled( Value : Boolean ) ;
// ------------------------------
// Enable/disable Z stage control
//-------------------------------
begin
FEnabled := Value ;
case FStageType of
stOptiscanII :
begin
if FEnabled and (not ComPortOpen) then OpenComPort
else if (not FEnabled) and ComPortOpen then CloseComPort ;
end;
end ;
end;
procedure TZStage.SetStageType( Value : Integer ) ;
// ------------------------------
// Set type of Z stage controller
// ------------------------------
begin
// Close existing stage
Close ;
FStageType := Value ;
// Reopen new stage
Open ;
end;
procedure TZStage.UpdateZPositionPZ ;
// ----------------------------------
// Update position of Z stage (Piezo)
// ----------------------------------
begin
end;
procedure TZStage.MoveToPZ( Position : Double ) ;
// -------------------------
// Go to Z position (Piezo)
// -------------------------
var
iPort,iChan,iDev : Integer ;
begin
ZPosition := Position ;
iPort := 0 ;
for iDev := 1 to LabIO.NumDevices do
for iChan := 0 to LabIO.NumDACs[iDev]-1 do
begin
if iPort = FControlPort then
begin
LabIO.WriteDAC(iDev,Position*ZScaleFactor,iChan);
end;
inc(iPort) ;
end;
end ;
end.
|
unit uThemesUtils;
interface
uses
uMemory,
Vcl.Themes,
Vcl.Graphics;
type
TDatabaseTheme = class(TObject)
private
function GetPanelColor: TColor;
function GetPanelFontColor: TColor;
function GetListViewColor: TColor;
function GetListViewFontColor: TColor;
function GetHighlightTextColor: TColor;
function GetHighlightColor: TColor;
function GetEditColor: TColor;
function GetWindowColor: TColor;
function GetGradientFromColor: TColor;
function GetGradientToColor: TColor;
function GetMenuColor: TColor;
function GetWizardColor: TColor;
function GetListSelectedColor: TColor;
function GetListColor: TColor;
function GetListFontColor: TColor;
function GetListFontSelectedColor: TColor;
function GetComboBoxColor: TColor;
function GetWindowTextColor: TColor;
function GetListViewSelectedFontColor: TColor;
function GetGradientText: TColor;
public
property PanelColor: TColor read GetPanelColor;
property PanelFontColor: TColor read GetPanelFontColor;
property ListViewColor: TColor read GetListViewColor;
property ListViewFontColor: TColor read GetListViewFontColor;
property ListViewSelectedFontColor: TColor read GetListViewSelectedFontColor;
property HighlightTextColor: TColor read GetHighlightTextColor;
property HighlightColor: TColor read GetHighlightColor;
property EditColor: TColor read GetEditColor;
property WindowColor: TColor read GetWindowColor;
property WindowTextColor: TColor read GetWindowTextColor;
property GradientFromColor: TColor read GetGradientFromColor;
property GradientToColor: TColor read GetGradientToColor;
property GradientText: TColor read GetGradientText;
property MenuColor: TColor read GetMenuColor;
property WizardColor: TColor read GetWizardColor;
property ListSelectedColor: TColor read GetListSelectedColor;
property ListColor: TColor read GetListColor;
property ListFontColor: TColor read GetListFontColor;
property ListFontSelectedColor: TColor read GetListFontSelectedColor;
property ComboBoxColor: TColor read GetComboBoxColor;
end;
function Theme: TDatabaseTheme;
implementation
{ Theme }
var
FTheme: TDatabaseTheme = nil;
function Theme: TDatabaseTheme;
begin
if FTheme = nil then
FTheme := TDatabaseTheme.Create;
Result := FTheme;
end;
function TDatabaseTheme.GetComboBoxColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleColor(scComboBox)
else
Result := clWindow;
end;
function TDatabaseTheme.GetEditColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleColor(scEdit)
else
Result := clWindow;
end;
{
ListView.Selection.GradientColorTop := MakeDarken(StyleServices.GetSystemColor(clHighlight), 0.8);
ListView.Selection.GradientColorBottom := MakeDarken(StyleServices.GetSystemColor(clHighlight), 1.2);
ListView.Selection.TextColor := StyleServices.GetSystemColor(clHighlightText);
{ListView.Selection.GradientColorTop := StyleServices.GetStyleColor(scGenericGradientBase);
ListView.Selection.GradientColorBottom := StyleServices.GetStyleColor(scGenericGradientEnd);
ListView.Selection.TextColor := StyleServices.GetStyleFontColor(sfListItemTextNormal);
}
function TDatabaseTheme.GetGradientFromColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleColor(scGenericGradientBase)
else
Result := clGradientActiveCaption;
end;
function TDatabaseTheme.GetGradientToColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleColor(scGenericGradientEnd)
else
Result := clGradientInactiveCaption;
end;
function TDatabaseTheme.GetGradientText: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleFontColor(sfWindowTextNormal)
else
Result := clWindowText;
end;
function TDatabaseTheme.GetHighlightColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetSystemColor(clHighlight)
else
Result := clHighlight;
end;
function TDatabaseTheme.GetHighlightTextColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetSystemColor(clHighlightText)
else
Result := clHighlightText;
end;
function TDatabaseTheme.GetListColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleColor(scListBox)
else
Result := clWindow;
end;
function TDatabaseTheme.GetListFontColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleFontColor(sfListItemTextNormal)
else
Result := clWindowText;
end;
function TDatabaseTheme.GetListFontSelectedColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleFontColor(sfListItemTextSelected)
else
Result := clHighlightText;
end;
function TDatabaseTheme.GetListSelectedColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetSystemColor(clHighlight)
else
Result := clHighlight;
end;
function TDatabaseTheme.GetListViewColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleColor(scListView)
else
Result := clWindow;
end;
function TDatabaseTheme.GetListViewFontColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleFontColor(sfListItemTextNormal)
else
Result := clWindowText;
end;
function TDatabaseTheme.GetListViewSelectedFontColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleFontColor(sfListItemTextSelected)
else
Result := clHighlightText;
end;
function TDatabaseTheme.GetMenuColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleColor(scWindow)
else
Result := clMenu;
end;
function TDatabaseTheme.GetPanelColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleColor(scPanel)
else
Result := clBtnFace;
end;
function TDatabaseTheme.GetPanelFontColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleFontColor(sfPanelTextNormal)
else
Result := clWindowText;
end;
function TDatabaseTheme.GetWindowColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleColor(scWindow)
else
Result := clWindow;
end;
function TDatabaseTheme.GetWindowTextColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetStyleFontColor(sfWindowTextNormal)
else
Result := clWindowText;
end;
function TDatabaseTheme.GetWizardColor: TColor;
begin
if StyleServices.Enabled then
Result := StyleServices.GetSystemColor(clWindow)
else
Result := clWhite;
end;
initialization
finalization
F(FTheme);
end.
|
unit Comparing;
interface
uses
SysUtils, Classes;
type
//Опис фрагменту
TRange = record
//Початок проміжку
Start: integer;
//Кінець проміжку
Stop: integer;
end;
PChange = ^TChange;
//Опис зміни
TChange = record
//Фрагмент у початковому наборі
Left: TRange;
//Фрагмент, на який був замінений даний у кінцевому наборі
Right: TRange;
end;
PChanges = ^TChanges;
TChanges = array [0 .. MaxInt div 32] of TChange;
EComparerError = class(Exception);
TCompareHash = function(const s: string): Cardinal of object; register;
TCompareText = function(const s1, s2: string): boolean of object; register;
//Базовий клас для простого порівняння наборів рядків
TBaseComparer = class
private
FChanges: PChanges;
FCount: integer;
FAlloc: integer;
FOnHash: TCompareHash;
FOnCompare: TCompareText;
function GetChange(Index: integer): TChange;
procedure SetSize(NewCount: integer);
protected
function DefaultHash(const s: string): Cardinal; register;
function DefaultCompare(const s1, s2: string): boolean; register;
public
constructor Create;
destructor Destroy; override;
//Звільняє зайняту останнім порівнянням пам'ять
procedure Clear;
//Власне порівнює набори рядків
procedure Compare(List1, List2: TStrings);
//Повертає кількість змін
property Count: integer read FCount;
//Повертає структуру зміни за індексом
property Change[Index: integer]: TChange read GetChange; default;
end;
//Клас для порівняння текстових даних (дозволяє ігнорувати пробіли та регістр символів)
TComparer = class(TBaseComparer)
private
FIgnoreCase: boolean;
FIgnoreSpaces: boolean;
FSpacesAsOne: boolean;
protected
function Hash_ynn(const s: string): Cardinal; register;
function Hash_nyn(const s: string): Cardinal; register;
function Hash_yyn(const s: string): Cardinal; register;
function Hash_nny(const s: string): Cardinal; register;
function Hash_yny(const s: string): Cardinal; register;
function Compare_ynn(const s1, s2: string): boolean; register;
function Compare_nyn(const s1, s2: string): boolean; register;
function Compare_yyn(const s1, s2: string): boolean; register;
function Compare_nny(const s1, s2: string): boolean; register;
function Compare_yny(const s1, s2: string): boolean; register;
public
//Оновлена процедура порівняння
procedure Compare(List1, List2: TStrings);
//Властивість для задання необхідності ігнорування регістру
property IgnoreCase: boolean read FIgnoreCase write FIgnoreCase;
//Задає ігнорування пробілів
property IgnoreSpaces: boolean read FIgnoreSpaces write FIgnoreSpaces;
//Дозволяє враховувати послідовність пробілів за один
property SpacesAsOne: boolean read FSpacesAsOne write FSpacesAsOne;
end;
implementation
constructor TBaseComparer.Create;
begin
inherited;
FChanges := nil;
FCount := 0;
FAlloc := 0;
end;
destructor TBaseComparer.Destroy;
begin
Clear;
inherited;
end;
procedure TBaseComparer.SetSize(NewCount: integer);
begin
FAlloc := NewCount;
ReAllocMem(FChanges, FAlloc * SizeOf(TChange));
if FCount > FAlloc then
FCount := FAlloc;
end;
procedure TBaseComparer.Clear;
begin
SetSize(0);
end;
function TBaseComparer.GetChange(Index: integer): TChange;
begin
if (Index < 0) or (Index >= FCount) then
raise EComparerError.Create('Невірний індекс елементу');
Result := FChanges^[Index];
end;
function TBaseComparer.DefaultHash(const s: string): Cardinal;
var
k, len: integer;
begin
Result := 0;
len := Length(s);
for k := 1 to len do
Result := 19 * Result + Ord(s[k]);
end;
function TBaseComparer.DefaultCompare(const s1, s2: string): boolean;
begin
Result := s1 = s2;
end;
procedure TBaseComparer.Compare(List1, List2: TStrings);
type
TFileInfo = record
Strings: TStrings;
Count: integer;
LineHash: array of Cardinal;
HashLine: array of integer;
HashColl: array of integer;
end;
var
HashFunc: TCompareHash;
CompareFunc: TCompareText;
Info1, Info2: TFileInfo;
procedure InitFileInfo(var Info: TFileInfo; AStrings: TStrings);
var
idx, back, coll: Integer;
begin
with Info do
begin
Strings := AStrings;
Count := Strings.Count;
SetLength(LineHash, Count);
SetLength(HashLine, 2 * Count);
SetLength(HashColl, 2 * Count);
if Count < 1 then
exit;
for idx := 0 to Count - 1 do
begin
LineHash[idx] := HashFunc(Strings[idx]);
HashLine[idx] := -1;
HashColl[idx] := -1;
end;
coll := Count - 1;
for idx := 0 to Count - 1 do
begin
back := integer(Cardinal(LineHash[idx]) mod Cardinal(Count));
if HashLine[back] < 0 then
HashLine[back] := idx
else
begin
inc(coll);
HashLine[coll] := HashLine[back];
HashColl[coll] := HashColl[back];
HashLine[back] := idx;
HashColl[back] := coll;
end;
end;
end;
end;
procedure AddChange(l1a, l1e, l2a, l2e: integer);
begin
if (l1a >= l1e) and (l2a >= l2e) then
exit;
if FCount >= FAlloc then
SetSize(FAlloc + 32);
with FChanges^[FCount] do
begin
Left.Start := l1a;
Left.Stop := l1e;
Right.Start := l2a;
Right.Stop := l2e;
end;
inc(FCount);
end;
function DistanceLess(l1a, l1e, l2a, l2e: integer;
bp1, bp2, np1, np2: integer): boolean;
var
t1, b1, t2, b2: integer;
begin
t1 := abs((bp1 - l1a) - (bp2 - l2a));
b1 := abs((l1e - bp1) - (l2e - bp2));
t2 := abs((np1 - l2a) - (np2 - l2a));
b2 := abs((l2e - np1) - (l2e - np2));
Result := (t2 + b2) < (t1 + b1);
end;
function CountEqualLines(l1p, l1e, l2p, l2e, bsz: integer): integer;
var
max: integer;
begin
max := 0;
while (l1p + max < l1e) and
(l2p + max < l2e) and
(Info1.LineHash[l1p + max] = Info2.LineHash[l2p + max]) do
inc(max);
Result := 0;
if max < bsz then
exit;
while (Result < max) and
CompareFunc(Info1.Strings[l1p], Info2.Strings[l2p]) do
begin
inc(l1p);
inc(l2p);
inc(Result);
end;
end;
procedure ChangeRange(l1a, l1e, l2a, l2e: integer);
var
bp1, bp2, bsz, scan, idx, pos, cnt: integer;
begin
while true do
begin
if (l1a >= l1e) or (l2a >= l2e) then
break;
bp1 := -1;
bp2 := -1;
bsz := 0;
if l1e - l1a < l2e - l2a then
begin
scan := l1a;
while scan < l1e - bsz do
begin
idx := integer(Cardinal(Info1.LineHash[scan]) mod Cardinal(Info2.Count));
repeat
pos := Info2.HashLine[idx];
if pos < l2a then
break;
if pos + bsz <= l2e then
begin
cnt := CountEqualLines(scan, l1e, pos, l2e, bsz);
if (cnt > bsz) or
((cnt = bsz) and DistanceLess(l1a, l1e, l2a, l2e, bp1, bp2, scan, pos)) then
begin
bsz := cnt;
bp1 := scan;
bp2 := pos;
end;
end;
idx := Info2.HashColl[idx];
until idx < 0;
if (bsz >= 50) then
break;
inc(scan);
end;
end
else
begin
scan := l2a;
while scan < l2e - bsz do
begin
idx := integer(Cardinal(Info2.LineHash[scan]) mod Cardinal(Info1.Count));
repeat
pos := Info1.HashLine[idx];
if pos < l1a then
break;
if pos + bsz <= l1e then
begin
cnt := CountEqualLines(pos, l1e, scan, l2e, bsz);
if (cnt > bsz) or
((cnt = bsz) and DistanceLess(l1a, l1e, l2a, l2e, bp1, bp2, pos, scan)) then
begin
bsz := cnt;
bp1 := pos;
bp2 := scan;
end;
end;
idx := Info1.HashColl[idx];
until idx < 0;
if (bsz >= 50) then
break;
inc(scan);
end;
end;
if bsz = 0 then
break;
ChangeRange(l1a, bp1, l2a, bp2);
l1a := bp1 + bsz;
l2a := bp2 + bsz;
end;
AddChange(l1a, l1e, l2a, l2e);
end;
begin
Clear;
if Assigned(FOnHash) and Assigned(FOnCompare) then
begin
HashFunc := FOnHash;
CompareFunc := FOnCompare;
end
else
begin
HashFunc := DefaultHash;
CompareFunc := DefaultCompare;
end;
InitFileInfo(Info1, List1);
InitFileInfo(Info2, List2);
ChangeRange(0, Info1.Count, 0, Info2.Count);
end;
function RemoveSpaces(const s: string): string;
var
len, p: integer;
pc: PChar;
begin
len := Length(s);
SetLength(Result, len);
pc := @s[1];
p := 0;
while len > 0 do
begin
if not (pc^ in [#0, #9, #10, #13, #32]) then
begin
inc(p);
Result[p] := pc^;
end;
inc(pc);
dec(len);
end;
SetLength(Result, p);
end;
function ReduceSpaces(const s: string): string;
var
len, p, sp: integer;
pc: PChar;
begin
len := Length(s);
SetLength(Result, len);
pc := @s[1];
p := 0;
sp := 0;
while len > 0 do
begin
if pc^ in [#0, #9, #10, #13, #32] then
inc(sp, p)
else
begin
if sp > 0 then
begin
sp := 0;
inc(p);
Result[p] := ' ';
end;
inc(p);
Result[p] := pc^;
end;
inc(pc);
dec(len);
end;
SetLength(Result, p);
end;
function TComparer.Hash_ynn(const s: string): Cardinal;
begin
Result := DefaultHash(Lowercase(s));
end;
function TComparer.Hash_nyn(const s: string): Cardinal;
begin
Result := DefaultHash(RemoveSpaces(s));
end;
function TComparer.Hash_yyn(const s: string): Cardinal;
begin
Result := DefaultHash(Lowercase(RemoveSpaces(s)));
end;
function TComparer.Hash_nny(const s: string): Cardinal;
begin
Result := DefaultHash(ReduceSpaces(s));
end;
function TComparer.Hash_yny(const s: string): Cardinal;
begin
Result := DefaultHash(Lowercase(ReduceSpaces(s)));
end;
function TComparer.Compare_ynn(const s1, s2: string): boolean;
begin
Result := Lowercase(s1) = Lowercase(s2);
end;
function TComparer.Compare_nyn(const s1, s2: string): boolean;
begin
Result := RemoveSpaces(s1) = RemoveSpaces(s2);
end;
function TComparer.Compare_yyn(const s1, s2: string): boolean;
begin
Result := Lowercase(RemoveSpaces(s1)) = Lowercase(RemoveSpaces(s2));
end;
function TComparer.Compare_nny(const s1, s2: string): boolean;
begin
Result := ReduceSpaces(s1) = ReduceSpaces(s2);
end;
function TComparer.Compare_yny(const s1, s2: string): boolean;
begin
Result := Lowercase(ReduceSpaces(s1)) = Lowercase(ReduceSpaces(s2));
end;
procedure TComparer.Compare(List1, List2: TStrings);
var
HashFunc: TCompareHash;
CompareFunc: TCompareText;
begin
HashFunc := FOnHash;
CompareFunc := FOnCompare;
try
case 4 * Ord(FIgnoreCase) + 2 * Ord(FIgnoreSpaces) + Ord(FSpacesAsOne) of
0 + 0 + 0: begin
FOnHash := nil;
FOnCompare := nil;
end;
0 + 0 + 1: begin
FOnHash := Hash_nny;
FOnCompare := Compare_nny;
end;
0 + 2 + 0,
0 + 2 + 1: begin
FOnHash := Hash_nyn;
FOnCompare := Compare_nyn;
end;
4 + 0 + 0: begin
FOnHash := Hash_ynn;
FOnCompare := Compare_ynn;
end;
4 + 0 + 1: begin
FOnHash := Hash_yny;
FOnCompare := Compare_yny;
end;
4 + 2 + 0,
4 + 2 + 1: begin
FOnHash := Hash_yyn;
FOnCompare := Compare_yyn;
end;
end;
inherited Compare(List1, List2);
finally
FOnHash := HashFunc;
FOnCompare := CompareFunc;
end;
end;
end.
|
unit uSelector;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base,
System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt,
Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, FMX.ListView,
FMX.StdCtrls, FMX.Controls.Presentation, Data.DB, FMX.Objects, FireDAC.Comp.Client,
FMX.Edit, FMX.Layouts, FMX.TabControl, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FMX.SearchBox,
FireDAC.Stan.StorageBin, FMX.ScrollBox, FMX.Memo, FMX.ListBox;
type
TSelectorForm = class(TForm)
ToolBar1: TToolBar;
HeaderText: TText;
BackBTN: TButton;
OtherBTN: TButton;
TabControl1: TTabControl;
SelectTab: TTabItem;
OtherTab: TTabItem;
OtherLayout: TLayout;
Layout12: TLayout;
Text6: TText;
OtherEdit: TEdit;
ClearEditButton2: TClearEditButton;
SaveBTN: TButton;
BindSourceDBTableName: TBindSourceDB;
BindingsListCB: TBindingsList;
LinkFillControlToField: TLinkFillControlToField;
SCBindLink: TBindLink;
BindSourceDBRequestType: TBindSourceDB;
BindSourceDBGroups: TBindSourceDB;
PickerLB: TListBox;
Button1: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure OtherBTNClick(Sender: TObject);
procedure BackBTNClick(Sender: TObject);
procedure SaveBTNClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
ResultField: String;
BindSourceDBCBRemote: TBindSourceDB;
public
{ Public declarations }
procedure SetParamsView;
procedure SetGroupsView;
procedure SaveValue(const S: String);
procedure SetDataSetResult(const aField: String; BS: TBindSourceDB);
procedure ClearSearchBox(Sender: TObject);
end;
var
SelectorForm: TSelectorForm;
implementation
{$R *.fmx}
uses
uMainForm;
procedure TSelectorForm.Button1Click(Sender: TObject);
var
I: Integer;
SL: TStringList;
begin
SL := TStringList.Create;
SL.StrictDelimiter := True;
for I := 0 to PickerLB.Items.Count-1 do
begin
if PickerLB.ListItems[I].IsChecked=True then
SL.Append(PickerLB.Items[I]);
end;
SaveValue(SL.CommaText);
SL.Free;
end;
procedure TSelectorForm.ClearSearchBox(Sender: TObject);
var
I: Integer;
SearchBox: TSearchBox;
begin
for I := 0 to TListView(Sender).Controls.Count-1 do
if TListView(Sender).Controls[I].ClassType = TSearchBox then
begin
SearchBox := TSearchBox(TListView(Sender).Controls[I]);
SearchBox.Text := '';
Break;
end;
end;
procedure TSelectorForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
BackBTNClick(Self);
end;
procedure TSelectorForm.FormShow(Sender: TObject);
var
I: Integer;
begin
for I := 0 to PickerLB.Items.Count-1 do
begin
PickerLB.ListItems[I].Height := 50;
end;
end;
procedure TSelectorForm.SetParamsView;
begin
LinkFillControlToField.Active := False;
LinkFillControlToField.FillDataSource := BindSourceDBRequestType;
LinkFillControlToField.FillDisplayFieldName := 'RequestType';
LinkFillControlToField.Active := True;
HeaderText.Text := 'Select Request Type';
OtherBTN.Visible := True;
end;
procedure TSelectorForm.SaveBTNClick(Sender: TObject);
begin
SaveValue(OtherEdit.Text);
end;
procedure TSelectorForm.SetDataSetResult(const aField: String; BS: TBindSourceDB);
begin
BindSourceDBCBRemote := BS;
ResultField := aField;
end;
procedure TSelectorForm.BackBTNClick(Sender: TObject);
begin
OtherEdit.Text := '';
OtherBTN.Visible := True;
ClearSearchBox(PickerLB);
TabControl1.ActiveTab := SelectTab;
SelectorForm.Hide;
MainForm.Show;
end;
procedure TSelectorForm.OtherBTNClick(Sender: TObject);
begin
OtherBTN.Visible := False;
TabControl1.ActiveTab := OtherTab;
//ShowKeyboard(OtherEdit);
end;
procedure TSelectorForm.SaveValue(const S: String);
begin
if BindSourceDBCBRemote.DataSet<>nil then
begin
if BindSourceDBCBRemote.DataSet.Active = False then
begin
BindSourceDBCBRemote.DataSet.Open;
end;
BindSourceDBCBRemote.DataSet.DisableControls;
if not (BindSourceDBCBRemote.DataSet.State in [dsEdit, dsInsert]) then BindSourceDBCBRemote.DataSet.Edit;
BindSourceDBCBRemote.DataSet.FieldByName(ResultField).AsString := S;
BindSourceDBCBRemote.DataSet.Post;
BindSourceDBCBRemote.DataSet.EnableControls;
end;
OtherEdit.Text := '';
OtherBTN.Visible := True;
ClearSearchBox(PickerLB);
TabControl1.ActiveTab := SelectTab;
SelectorForm.Hide;
MainForm.Show;
end;
procedure TSelectorForm.SetGroupsView;
begin
LinkFillControlToField.Active := False;
LinkFillControlToField.FillDataSource := BindSourceDBGroups;
LinkFillControlToField.FillDisplayFieldName := 'Group';
LinkFillControlToField.Active := True;
HeaderText.Text := 'Select Group';
OtherBTN.Visible := True;
end;
end.
|
unit SHDevelopIntf;
interface
uses
Classes, SysUtils;
type
ISHBranchInfo = interface
['{A4E9B90B-25F8-4155-B45C-1FE1F0FEF587}']
function GetBranchIID: TGUID;
function GetBranchName: string;
property BranchIID: TGUID read GetBranchIID;
property BranchName: string read GetBranchName;
end;
IibSHBranchInfo = interface(ISHBranchInfo)
['{4D4F5FE1-7915-4B90-9DE7-FACB8BAC6803}']
end;
IseSHBranchInfo = interface(ISHBranchInfo)
['{0F972677-0D0F-492A-B3A2-638E2085D603}']
end;
implementation
end.
|
//*******************************************************//
// //
// DelphiFlash.com //
// Copyright (c) 2004-2008 FeatherySoft, Inc. //
// info@delphiflash.com //
// //
//*******************************************************//
// Description: Level of SWF-objects
// Last update: 12 mar 2008
{$I defines.inc}
{$WARNINGS OFF}
{$HINTS OFF}
Unit SWFObjects;
interface
Uses Windows, SysUtils, Classes, SWFConst, Graphics, Contnrs,
{$IFDEF ExternalUTF}
Unicode,
{$ENDIF}
{$IFDEF VARIANTS}
Variants,
{$ENDIF}
SWFTools;
type
TSWFRect = class (TObject)
private
FXmax: LongInt;
FXmin: LongInt;
FYmax: LongInt;
FYmin: LongInt;
procedure CompareXY(flag: byte);
function GetHeight: Integer;
function GetRec: recRect;
function GetRect: TRect;
function GetWidth: Integer;
procedure SetRec(Value: recRect);
procedure SetRect(Value: TRect);
procedure SetXmax(Value: LongInt);
procedure SetXmin(Value: LongInt);
procedure SetYmax(Value: LongInt);
procedure SetYmin(Value: LongInt);
public
procedure Assign(Source: TSWFRect);
property Height: Integer read GetHeight;
property Rec: recRect read GetRec write SetRec;
property Rect: TRect read GetRect write SetRect;
property Width: Integer read GetWidth;
property Xmax: LongInt read FXmax write SetXmax;
property Xmin: LongInt read FXmin write SetXmin;
property Ymax: LongInt read FYmax write SetYmax;
property Ymin: LongInt read FYmin write SetYmin;
end;
TSWFRGB = class (TObject)
private
FB: Byte;
FG: Byte;
FR: Byte;
function GetRGB: recRGB;
procedure SetRGB(Value: recRGB); virtual;
public
procedure Assign(Source: TObject); virtual;
property B: Byte read FB write FB;
property G: Byte read FG write FG;
property R: Byte read FR write FR;
property RGB: recRGB read GetRGB write SetRGB;
end;
TSWFRGBA = class (TSWFRGB)
private
FA: Byte;
FHasAlpha: Boolean;
function GetRGBA: recRGBA;
procedure SetA(Value: Byte);
procedure SetHasAlpha(Value: Boolean);
procedure SetRGBA(Value: recRGBA);
protected
procedure SetRGB(value: recRGB); override;
public
constructor Create(a: boolean = false);
procedure Assign(Source: TObject); override;
property A: Byte read FA write SetA;
property HasAlpha: Boolean read FHasAlpha write SetHasAlpha;
property RGBA: recRGBA read GetRGBA write SetRGBA;
end;
TSWFColorTransform = class (TObject)
private
FaddA: Integer;
FaddB: Integer;
FaddG: Integer;
FaddR: Integer;
FhasAdd: Boolean;
FhasAlpha: Boolean;
FhasMult: Boolean;
FmultA: Integer;
FmultB: Integer;
FmultG: Integer;
FmultR: Integer;
function GetREC: recColorTransform;
procedure SetaddA(Value: Integer);
procedure SetaddB(Value: Integer);
procedure SetaddG(Value: Integer);
procedure SetaddR(Value: Integer);
procedure SetmultA(Value: Integer);
procedure SetmultB(Value: Integer);
procedure SetmultG(Value: Integer);
procedure SetmultR(Value: Integer);
procedure SetREC(Value: recColorTransform);
public
procedure AddTint(Color: TColor);
procedure Assign(Source: TSWFColorTransform);
function CheckAddValue(value: integer): integer;
function CheckMultValue(value: integer): integer;
procedure SetAdd(R, G, B, A: integer);
procedure SetMult(R, G, B, A: integer);
property addA: Integer read FaddA write SetaddA;
property addB: Integer read FaddB write SetaddB;
property addG: Integer read FaddG write SetaddG;
property addR: Integer read FaddR write SetaddR;
property hasAdd: Boolean read FhasAdd write FhasAdd;
property hasAlpha: Boolean read FhasAlpha write FhasAlpha;
property hasMult: Boolean read FhasMult write FhasMult;
property multA: Integer read FmultA write SetmultA;
property multB: Integer read FmultB write SetmultB;
property multG: Integer read FmultG write SetmultG;
property multR: Integer read FmultR write SetmultR;
property REC: recColorTransform read GetREC write SetREC;
end;
TSWFMatrix = class (TObject)
private
FHasScale: Boolean;
FHasSkew: Boolean;
FScaleX: LongInt;
FScaleY: LongInt;
FSkewX: LongInt;
FSkewY: LongInt;
FTranslateX: LongInt;
FTranslateY: LongInt;
function GetREC: recMatrix;
function GetScaleX: Single;
function GetScaleY: Single;
function GetSkewX: Single;
function GetSkewY: Single;
procedure SetREC(Value: recMatrix);
procedure SetScaleX(Value: Single);
procedure SetScaleY(Value: Single);
procedure SetSkewX(Value: Single);
procedure SetSkewY(Value: Single);
public
procedure Assign(M : TSWFMatrix);
procedure SetRotate(angle: single);
procedure SetScale(ScaleX, ScaleY: single);
procedure SetSkew(SkewX, SkewY: single);
procedure SetTranslate(X, Y: LongInt);
property HasScale: Boolean read FHasScale write FHasScale;
property HasSkew: Boolean read FHasSkew write FHasSkew;
property REC: recMatrix read GetREC write SetREC;
property ScaleX: Single read GetScaleX write SetScaleX;
property ScaleY: Single read GetScaleY write SetScaleY;
property SkewX: Single read GetSkewX write SetSkewX;
property SkewY: Single read GetSkewY write SetSkewY;
property TranslateX: LongInt read FTranslateX write FTranslateX;
property TranslateY: LongInt read FTranslateY write FTranslateY;
end;
TBasedSWFObject = class (TObject)
public
procedure Assign(Source: TBasedSWFObject); virtual; abstract;
function LibraryLevel: Byte; virtual; abstract;
function MinVersion: Byte; virtual;
procedure WriteToStream(be: TBitsEngine); virtual; abstract;
end;
TSWFObject = class (TBasedSWFObject)
private
FBodySize: LongWord;
FTagID: Word;
public
procedure Assign(Source: TBasedSWFObject); override;
function GetFullSize: LongInt;
function LibraryLevel: Byte; override;
procedure ReadFromStream(be: TBitsEngine); virtual;
procedure WriteTagBody(be: TBitsEngine); virtual;
procedure WriteToStream(be: TBitsEngine); override;
property BodySize: LongWord read FBodySize write FBodySize;
property TagID: Word read FTagID write FTagID;
end;
// TSWFErrorTag = class (TSWFObject)
// private
// FTagIDFrom: Word;
// FText: string;
// public
// constructor Create;
// property TagIDFrom: Word read FTagIDFrom write FTagIDFrom;
// property Text: string read FText write FText;
// end;
TSWFTagEvent = procedure (sender: TSWFObject; BE: TBitsEngine) of object;
// ===========================================================
// Control Tags
// ===========================================================
TSWFSetBackgroundColor = class (TSWFObject)
private
FColor: TSWFRGB;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property Color: TSWFRGB read FColor;
end;
TSWFFrameLabel = class (TSWFObject)
private
FisAnchor: Boolean;
FName: string;
public
constructor Create; overload;
constructor Create(fl: string); overload;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property isAnchor: Boolean read FisAnchor write FisAnchor;
property Name: string read FName write FName;
end;
TSWFProtect = class (TSWFObject)
private
FHash: string;
FPassword: string;
public
constructor Create; virtual;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property Hash: string read FHash write FHash;
property Password: string read FPassword write FPassword;
end;
TSWFEnd = class (TSWFObject)
public
constructor Create;
end;
TSWFExportAssets = class (TSWFObject)
private
FAssets: TStringList;
function GetCharacterId(name: string): Integer;
procedure SetCharacterId(name: string; Value: Integer);
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure SetAsset(Name: string; CharacterId: word);
procedure WriteTagBody(be: TBitsEngine); override;
property Assets: TStringList read FAssets;
property CharacterId[name: string]: Integer read GetCharacterId write SetCharacterId;
end;
TSWFImportAssets = class (TSWFExportAssets)
private
FURL: string;
public
constructor Create; override;
procedure Assign(Source: TBasedSWFObject); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property URL: string read FURL write FURL;
end;
TSWFImportAssets2 = class(TSWFImportAssets)
public
constructor Create; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
end;
TSWFEnableDebugger = class (TSWFProtect)
public
constructor Create; override;
function MinVersion: Byte; override;
end;
TSWFEnableDebugger2 = class (TSWFProtect)
public
constructor Create; override;
function MinVersion: Byte; override;
end;
TSWFScriptLimits = class (TSWFObject)
private
FMaxRecursionDepth: Word;
FScriptTimeoutSeconds: Word;
public
constructor Create;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property MaxRecursionDepth: Word read FMaxRecursionDepth write FMaxRecursionDepth;
property ScriptTimeoutSeconds: Word read FScriptTimeoutSeconds write FScriptTimeoutSeconds;
end;
TSWFSetTabIndex = class (TSWFObject)
private
FDepth: Word;
FTabIndex: Word;
public
constructor Create;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property Depth: Word read FDepth write FDepth;
property TabIndex: Word read FTabIndex write FTabIndex;
end;
TSWFSymbolClass = class (TSWFExportAssets)
public
constructor Create; override;
function MinVersion: Byte; override;
end;
TSWFFileAttributes = class (TSWFObject)
private
FHasMetadata: boolean;
FUseNetwork: boolean;
FActionScript3: boolean;
public
constructor Create;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property ActionScript3: boolean read FActionScript3 write FActionScript3;
property HasMetadata: boolean read FHasMetadata write FHasMetadata;
property UseNetwork: boolean read FUseNetwork write FUseNetwork;
end;
TSWFMetadata = class (TSWFObject)
private
FMetadata: AnsiString;
public
constructor Create;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property Metadata: AnsiString read FMetadata write FMetadata;
end;
TSWFProductInfo = class (TSWFObject)
private
FMajorBuild: longword;
FMinorBuild: longword;
FCompilationDate: TDateTime;
FEdition: longint;
FMinorVersion: byte;
FMajorVersion: byte;
FProductId: longint;
public
constructor Create;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property MajorBuild: longword read FMajorBuild write FMajorBuild;
property MinorBuild: longword read FMinorBuild write FMinorBuild;
property CompilationDate: TDateTime read FCompilationDate write FCompilationDate;
property Edition: longint read FEdition write FEdition;
property MajorVersion: byte read FMajorVersion write FMajorVersion;
property MinorVersion: byte read FMinorVersion write FMinorVersion;
property ProductId: longint read FProductId write FProductId;
end;
TSWFDefineScalingGrid = class (TSWFObject)
private
FCharacterId: word;
FSplitter: TSWFRect;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property CharacterId: word read FCharacterId write FCharacterId;
property Splitter: TSWFRect read FSplitter;
end;
// ===========================================================
// Actions
// ===========================================================
// ------------ SWF 3 -----------
TSWFAction = class (TObject)
private
FActionCode: Byte;
FBodySize: Word;
public
procedure Assign(Source: TSWFAction); virtual;
function GetFullSize: Word;
function MinVersion: Byte; virtual;
procedure ReadFromStream(be: TBitsEngine); virtual;
procedure WriteActionBody(be: TBitsEngine); virtual;
procedure WriteToStream(be: TBitsEngine); virtual;
property ActionCode: Byte read FActionCode write FActionCode;
property BodySize: Word read FBodySize write FBodySize;
end;
TSWFActionRecord = TSWFAction;
TSWFActionGotoFrame = class (TSWFAction)
private
FFrame: Word;
public
constructor Create;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
property Frame: Word read FFrame write FFrame;
end;
TSWFActionGetUrl = class (TSWFAction)
private
FTarget: string;
FURL: AnsiString;
public
constructor Create;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
property Target: string read FTarget write FTarget;
property URL: AnsiString read FURL write FURL;
end;
TSWFActionNextFrame = class (TSWFAction)
public
constructor Create;
end;
TSWFActionPreviousFrame = class (TSWFAction)
public
constructor Create;
end;
TSWFActionPlay = class (TSWFAction)
public
constructor Create;
end;
TSWFActionStop = class (TSWFAction)
public
constructor Create;
end;
TSWFActionToggleQuality = class (TSWFAction)
public
constructor Create;
end;
TSWFActionStopSounds = class (TSWFAction)
public
constructor Create;
end;
TSWFActionWaitForFrame = class (TSWFAction)
private
FFrame: Word;
FSkipCount: Byte;
public
constructor Create;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
property Frame: Word read FFrame write FFrame;
property SkipCount: Byte read FSkipCount write FSkipCount;
end;
TSWFActionSetTarget = class (TSWFAction)
private
FTargetName: string;
public
constructor Create;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
property TargetName: string read FTargetName write FTargetName;
end;
TSWFActionGoToLabel = class (TSWFAction)
private
FFrameLabel: string;
public
constructor Create;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
property FrameLabel: string read FFrameLabel write FFrameLabel;
end;
// ------------ SWF 4 -----------
TSWFAction4 = class (TSWFAction)
public
function MinVersion: Byte; override;
end;
TSWFOffsetMarker = class (TSWFAction)
private
FisUsing: Boolean;
FJumpToBack: Boolean;
FManualSet: Boolean;
FMarkerName: string;
FRootStreamPosition: LongInt;
FSizeOffset: Byte;
FStartPosition: LongInt;
public
constructor Create;
procedure Assign(Source: TSWFAction); override;
procedure WriteActionBody(be: TBitsEngine); override;
procedure WriteOffset(be: TBitsEngine);
property isUsing: Boolean read FisUsing write FisUsing;
property JumpToBack: Boolean read FJumpToBack write FJumpToBack;
property ManualSet: Boolean read FManualSet write FManualSet;
property MarkerName: string read FMarkerName write FMarkerName;
property RootStreamPosition: LongInt read FRootStreamPosition write FRootStreamPosition;
property SizeOffset: Byte read FSizeOffset write FSizeOffset;
property StartPosition: LongInt read FStartPosition write FStartPosition;
end;
TSWFTryOffsetMarker = class (TSWFOffsetMarker)
private
{ FTryAction: TSWFAction;}
FPrvieusMarker: TSWFTryOffsetMarker;
end;
// -- Stack Operations --
TPushValueInfo = class (TObject)
private
FValue: Variant;
FValueType: TSWFValueType;
procedure SetValue(v: Variant);
procedure SetValueType(v: TSWFValueType);
public
isValueInit: Boolean;
property Value: Variant read FValue write SetValue;
property ValueType: TSWFValueType read FValueType write SetValueType;
end;
TSWFActionPush = class (TSWFAction4)
private
FValues: TObjectList;
function GetValue(index: integer): Variant;
function GetValueInfo(index: integer): TPushValueInfo;
procedure SetValue(index: integer; v: Variant);
public
constructor Create;
destructor Destroy; override;
function AddValue(V: Variant): Integer;
procedure Assign(Source: TSWFAction); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
function ValueCount: Word;
procedure WriteActionBody(be: TBitsEngine); override;
property Value[index: integer]: Variant read GetValue write SetValue;
property ValueInfo[index: integer]: TPushValueInfo read GetValueInfo;
end;
TSWFActionPop = class (TSWFAction4)
public
constructor Create;
end;
// -- Arithmetic Operators --
TSWFActionAdd = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionSubtract = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionMultiply = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionDivide = class (TSWFAction4)
public
constructor Create;
end;
// -- Numerical Comparison --
TSWFActionEquals = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionLess = class (TSWFAction4)
public
constructor Create;
end;
// -- Logical Operators --
TSWFActionAnd = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionOr = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionNot = class (TSWFAction4)
public
constructor Create;
end;
// -- String Manipulation --
TSWFActionStringEquals = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionStringLength = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionStringAdd = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionStringExtract = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionStringLess = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionMBStringLength = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionMBStringExtract = class (TSWFAction4)
public
constructor Create;
end;
// -- Type Conversion --
TSWFActionToInteger = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionCharToAscii = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionAsciiToChar = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionMBCharToAscii = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionMBAsciiToChar = class (TSWFAction4)
public
constructor Create;
end;
// -- Control Flow --
TSWFActionJump = class (TSWFAction4)
private
FBranchOffset: SmallInt;
FBranchOffsetMarker: TSWFOffsetMarker;
FStaticOffset: Boolean;
StartPosition: Integer;
function GetBranchOffsetMarker: TSWFOffsetMarker;
procedure SetBranchOffset(v: SmallInt);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property BranchOffset: SmallInt read FBranchOffset write SetBranchOffset;
property BranchOffsetMarker: TSWFOffsetMarker read GetBranchOffsetMarker write FBranchOffsetMarker;
property StaticOffset: Boolean read FStaticOffset write FStaticOffset;
end;
TSWFActionIf = class (TSWFActionJump)
public
constructor Create;
end;
TSWFActionCall = class (TSWFAction4)
public
constructor Create;
end;
// -- Variables --
TSWFActionGetVariable = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionSetVariable = class (TSWFAction4)
public
constructor Create;
end;
// -- Movie Control --
TSWFActionGetURL2 = class (TSWFAction4)
private
FLoadTargetFlag: Boolean;
FLoadVariablesFlag: Boolean;
FSendVarsMethod: Byte;
public
constructor Create;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
property LoadTargetFlag: Boolean read FLoadTargetFlag write FLoadTargetFlag;
property LoadVariablesFlag: Boolean read FLoadVariablesFlag write FLoadVariablesFlag;
property SendVarsMethod: Byte read FSendVarsMethod write FSendVarsMethod;
end;
TSWFActionGotoFrame2 = class (TSWFAction4)
private
FPlayFlag: Boolean;
FSceneBias: Word;
FSceneBiasFlag: Boolean;
public
constructor Create;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
property PlayFlag: Boolean read FPlayFlag write FPlayFlag;
property SceneBias: Word read FSceneBias write FSceneBias;
property SceneBiasFlag: Boolean read FSceneBiasFlag write FSceneBiasFlag;
end;
TSWFActionSetTarget2 = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionGetProperty = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionSetProperty = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionCloneSprite = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionRemoveSprite = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionStartDrag = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionEndDrag = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionWaitForFrame2 = class (TSWFAction4)
public
constructor Create;
end;
// -- Utilities --
TSWFActionTrace = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionGetTime = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionRandomNumber = class (TSWFAction4)
public
constructor Create;
end;
TSWFActionFSCommand2 = class (TSWFAction4)
public
constructor Create;
end;
// ------------ SWF 5 -----------
// -- ScriptObject Actions --
TSWFActionByteCode = class (TSWFAction4)
private
FData: Pointer;
FDataSize: LongInt;
FSelfDestroy: Boolean;
function GetByteCode(Index: word): Byte;
function GetStrByteCode: AnsiString;
procedure SetByteCode(Index: word; Value: Byte);
procedure SetStrByteCode(Value: AnsiString);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFAction); override;
procedure SetSize(newsize: word);
procedure WriteActionBody(be: TBitsEngine); override;
property ByteCode[Index: word]: Byte read GetByteCode write SetByteCode;
property Data: Pointer read FData write FData;
property DataSize: LongInt read FDataSize write FDataSize;
property SelfDestroy: Boolean read FSelfDestroy write FSelfDestroy;
property StrByteCode: AnsiString read GetStrByteCode write SetStrByteCode;
end;
TSWFAction5 = class (TSWFAction)
public
function MinVersion: Byte; override;
end;
TSWFActionCallFunction = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionCallMethod = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionConstantPool = class (TSWFAction5)
private
FConstantPool: TStringList;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
property ConstantPool: TStringList read FConstantPool;
end;
TSWFActionDefineFunction = class (TSWFAction5)
private
FCodeSize: Word;
FCodeSizeMarker: TSWFOffsetMarker;
FFunctionName: string;
FParams: TStringList;
FStaticOffset: Boolean;
StartPosition: Integer;
function GetCodeSizeMarker: TSWFOffsetMarker;
procedure SetCodeSize(v: Word);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property CodeSize: Word read FCodeSize write SetCodeSize;
property CodeSizeMarker: TSWFOffsetMarker read GetCodeSizeMarker write FCodeSizeMarker;
property FunctionName: string read FFunctionName write FFunctionName;
property Params: TStringList read FParams;
property StaticOffset: Boolean read FStaticOffset write FStaticOffset;
end;
TSWFActionDefineLocal = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionDefineLocal2 = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionDelete = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionDelete2 = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionEnumerate = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionEquals2 = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionGetMember = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionInitArray = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionInitObject = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionNewMethod = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionNewObject = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionSetMember = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionTargetPath = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionWith = class (TSWFAction5)
private
FSize: Word;
FSizeMarker: TSWFOffsetMarker;
FStaticOffset: Boolean;
StartPosition: Integer;
function GetSizeMarker: TSWFOffsetMarker;
procedure SetSize(w: Word);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property Size: Word read FSize write SetSize;
property SizeMarker: TSWFOffsetMarker read GetSizeMarker write FSizeMarker;
property StaticOffset: Boolean read FStaticOffset write FStaticOffset;
end;
// -- Type Actions --
TSWFActionToNumber = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionToString = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionTypeOf = class (TSWFAction5)
public
constructor Create;
end;
// -- Math Actions --
TSWFActionAdd2 = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionLess2 = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionModulo = class (TSWFAction5)
public
constructor Create;
end;
// -- Stack Operator Actions --
TSWFActionBitAnd = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionBitLShift = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionBitOr = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionBitRShift = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionBitURShift = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionBitXor = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionDecrement = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionIncrement = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionPushDuplicate = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionReturn = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionStackSwap = class (TSWFAction5)
public
constructor Create;
end;
TSWFActionStoreRegister = class (TSWFAction5)
private
FRegisterNumber: Byte;
public
constructor Create;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
property RegisterNumber: Byte read FRegisterNumber write FRegisterNumber;
end;
// ------------ SWF 6 -----------
TSWFAction6 = class (TSWFAction)
public
function MinVersion: Byte; override;
end;
TSWFActionInstanceOf = class (TSWFAction6)
public
constructor Create;
end;
TSWFActionEnumerate2 = class (TSWFAction6)
public
constructor Create;
end;
TSWFActionStrictEquals = class (TSWFAction6)
public
constructor Create;
end;
TSWFActionGreater = class (TSWFAction6)
public
constructor Create;
end;
TSWFActionStringGreater = class (TSWFAction6)
public
constructor Create;
end;
// ------------ SWF 7 -----------
TSWFAction7 = class (TSWFAction)
public
function MinVersion: Byte; override;
end;
TSWFActionDefineFunction2 = class (TSWFAction7)
private
FCodeSize: Word;
FCodeSizeMarker: TSWFOffsetMarker;
FFunctionName: string;
FParameters: TStringList;
FPreloadArgumentsFlag: Boolean;
FPreloadGlobalFlag: Boolean;
FPreloadParentFlag: Boolean;
FPreloadRootFlag: Boolean;
FPreloadSuperFlag: Boolean;
FPreloadThisFlag: Boolean;
FRegisterCount: Byte;
FStaticOffset: Boolean;
FSuppressArgumentsFlag: Boolean;
FSuppressSuperFlag: Boolean;
FSuppressThisFlag: Boolean;
StartPosition: Integer;
function GetCodeSizeMarker: TSWFOffsetMarker;
function GetParamRegister(Index: byte): byte;
procedure SetCodeSize(v: Word);
procedure SetParamRegister(index, value: byte);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFAction); override;
procedure AddParam(const param: string; reg: byte);
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property CodeSize: Word read FCodeSize write SetCodeSize;
property CodeSizeMarker: TSWFOffsetMarker read GetCodeSizeMarker write FCodeSizeMarker;
property FunctionName: string read FFunctionName write FFunctionName;
property Parameters: TStringList read FParameters write FParameters;
property ParamRegister[Index: byte]: byte read GetParamRegister write SetParamRegister;
property PreloadArgumentsFlag: Boolean read FPreloadArgumentsFlag write FPreloadArgumentsFlag;
property PreloadGlobalFlag: Boolean read FPreloadGlobalFlag write FPreloadGlobalFlag;
property PreloadParentFlag: Boolean read FPreloadParentFlag write FPreloadParentFlag;
property PreloadRootFlag: Boolean read FPreloadRootFlag write FPreloadRootFlag;
property PreloadSuperFlag: Boolean read FPreloadSuperFlag write FPreloadSuperFlag;
property PreloadThisFlag: Boolean read FPreloadThisFlag write FPreloadThisFlag;
property RegisterCount: Byte read FRegisterCount write FRegisterCount;
property StaticOffset: Boolean read FStaticOffset write FStaticOffset;
property SuppressArgumentsFlag: Boolean read FSuppressArgumentsFlag write FSuppressArgumentsFlag;
property SuppressSuperFlag: Boolean read FSuppressSuperFlag write FSuppressSuperFlag;
property SuppressThisFlag: Boolean read FSuppressThisFlag write FSuppressThisFlag;
end;
TSWFActionExtends = class (TSWFAction7)
public
constructor Create;
end;
TSWFActionCastOp = class (TSWFAction7)
public
constructor Create;
end;
TSWFActionImplementsOp = class (TSWFAction7)
public
constructor Create;
end;
TSWFActionTry = class (TSWFAction7)
private
FCatchBlockFlag: Boolean;
FCatchInRegisterFlag: Boolean;
FCatchName: string;
FCatchRegister: Byte;
FCatchSize: Word;
FCatchSizeMarker: TSWFTryOffsetMarker;
FFinallyBlockFlag: Boolean;
FFinallySize: Word;
FFinallySizeMarker: TSWFTryOffsetMarker;
FStaticOffset: Boolean;
FTrySize: Word;
FTrySizeMarker: TSWFTryOffsetMarker;
StartPosition: Integer;
function GetCatchSizeMarker: TSWFTryOffsetMarker;
function GetFinallySizeMarker: TSWFTryOffsetMarker;
function GetTrySizeMarker: TSWFTryOffsetMarker;
procedure SetCatchSize(w: Word);
procedure SetFinallySize(w: Word);
procedure SetTrySize(w: Word);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFAction); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteActionBody(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property CatchBlockFlag: Boolean read FCatchBlockFlag write FCatchBlockFlag;
property CatchInRegisterFlag: Boolean read FCatchInRegisterFlag write FCatchInRegisterFlag;
property CatchName: string read FCatchName write FCatchName;
property CatchRegister: Byte read FCatchRegister write FCatchRegister;
property CatchSize: Word read FCatchSize write SetCatchSize;
property CatchSizeMarker: TSWFTryOffsetMarker read GetCatchSizeMarker write FCatchSizeMarker;
property FinallyBlockFlag: Boolean read FFinallyBlockFlag write FFinallyBlockFlag;
property FinallySize: Word read FFinallySize write SetFinallySize;
property FinallySizeMarker: TSWFTryOffsetMarker read GetFinallySizeMarker write FFinallySizeMarker;
property StaticOffset: Boolean read FStaticOffset write FStaticOffset;
property TrySize: Word read FTrySize write SetTrySize;
property TrySizeMarker: TSWFTryOffsetMarker read GetTrySizeMarker write FTrySizeMarker;
end;
TSWFActionThrow = class (TSWFAction7)
public
constructor Create;
end;
TSWFActionList = class (TObjectList)
private
function GetAction(Index: word): TSWFAction;
procedure SetAction(Index: word; Value: TSWFAction);
public
property Action[Index: word]: TSWFAction read GetAction write SetAction; default;
end;
TSWFDoAction = class (TSWFObject)
private
FActions: TSWFActionList;
FParseActions: Boolean;
SelfDestroy: Boolean;
public
constructor Create; overload; virtual;
constructor Create(A: TSWFActionList); overload; virtual;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property Actions: TSWFActionList read FActions;
property ParseActions: Boolean read FParseActions write FParseActions;
end;
TSWFDoInitAction = class (TSWFDoAction)
private
FSpriteID: Word;
public
constructor Create; override;
constructor Create(A: TSWFActionList); override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property SpriteID: Word read FSpriteID write FSpriteID;
end;
// ===========================================================
// AS3
// ===========================================================
TSWFDoubleObject = class (TObject)
Value: Double;
constructor Create(init: double);
end;
TSWFNameSpaceObject = class (TObject)
Kind: byte;
Name: Longint;
constructor Create(kind: byte; name: Longint);
end;
TSWFIntegerList = class (TList)
private
function GetInt(index: Integer): longint;
procedure SetInt(index: Integer; const Value: longint);
public
procedure WriteToStream(be: TBitsEngine);
procedure AddInt(value: longint);
property Int[index: longint]: longint read GetInt write SetInt;
end;
TSWFBasedMultiNameObject = class (TObject)
private
FMultinameKind: byte;
public
procedure ReadFromStream(be: TBitsEngine); virtual;
procedure WriteToStream(be: TBitsEngine); virtual;
property MultinameKind: byte read FMultinameKind write FMultinameKind;
end;
TSWFmnQName = class (TSWFBasedMultiNameObject)
private
FNS: Longint;
FName: Longint;
public
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property NS: Longint read FNS write FNS;
property Name: Longint read FName write FName;
end;
TSWFmnRTQName = class (TSWFBasedMultiNameObject)
private
FName: Longint;
public
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property Name: Longint read FName write FName;
end;
TSWFmnRTQNameL = TSWFBasedMultiNameObject;
TSWFmnMultiname = class (TSWFBasedMultiNameObject)
private
FNSSet: Longint;
FName: Longint;
public
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property NSSet: Longint read FNSSet write FNSSet;
property Name: Longint read FName write FName;
end;
TSWFmnMultinameL = class (TSWFBasedMultiNameObject)
private
FNSSet: Longint;
public
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property NSSet: Longint read FNSSet write FNSSet;
end;
TSWFAS3ConstantPool = class (TObject)
private
IntegerList: TSWFIntegerList;
UIntegerList: TList;
DoubleList: TObjectList;
StringList: TStringList;
NameSpaceList: TObjectList;
NameSpaceSETList: TObjectList;
MultinameList: TObjectList;
function GetMultiname(index: Integer): TSWFBasedMultiNameObject;
function GetMultinameCount: longint;
procedure SetMultiname(index: Integer; const Value: TSWFBasedMultiNameObject);
function GetNameSpaceSET(index: Integer): TSWFIntegerList;
function GetNameSpaceSETCount: longint;
procedure SetNameSpaceSET(index: Integer; const Value: TSWFIntegerList);
function GetNameSpace(index: Integer): TSWFNameSpaceObject;
function GetNameSpaceCount: longint;
procedure SetNameSpace(index: Integer; const Value: TSWFNameSpaceObject);
function GetStrings(index: Integer): string;
function GetStringsCount: longint;
procedure SetStrings(index: longint; const Value: string);
function GetDouble(index: Integer): Double;
function GetDoubleCount: longint;
procedure SetDouble(index: Integer; const Value: Double);
function GetUInt(index: Integer): longword;
function GetUIntCount: longword;
procedure SetUInt(index: Integer; const Value: longword);
function GetIntCount: longint;
function GetInt(index: longint): longint;
procedure SetInt(index: longint; const Value: longint);
public
constructor Create;
destructor Destroy; override;
procedure ReadFromStream(be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
property Double[index: longint]: Double read GetDouble write SetDouble;
property DoubleCount: longint read GetDoubleCount;
property Int[index: longint]: longint read GetInt write SetInt;
property IntCount: longint read GetIntCount;
property Multiname[index: longint]: TSWFBasedMultiNameObject read GetMultiname write SetMultiname;
property MultinameCount: longint read GetMultinameCount;
property NameSpace[index: longint]: TSWFNameSpaceObject read GetNameSpace write SetNameSpace;
property NameSpaceCount: longint read GetNameSpaceCount;
property NameSpaceSET[index: longint]: TSWFIntegerList read GetNameSpaceSET write SetNameSpaceSET;
property NameSpaceSETCount: longint read GetNameSpaceSETCount;
property Strings[index: longint]: string read GetStrings write SetStrings;
property StringsCount: longint read GetStringsCount;
property UInt[index: longint]: longword read GetUInt write SetUInt;
property UIntCount: longword read GetUIntCount;
end;
TSWFAS3MethodOptions = class (TObject)
val: longint;
kind: byte;
end;
TSWFAS3Method = class (TObject)
private
FHasOptional: boolean;
FHasParamNames: boolean;
FName: Longint;
FNeedActivation: boolean;
FNeedArguments: boolean;
FNeedRest: boolean;
FOptions: TObjectList;
FParamNames: TSWFIntegerList;
FParamTypes: TSWFIntegerList;
FReturnType: Longint;
FSetDxns: boolean;
function GetOption(index: integer): TSWFAS3MethodOptions;
public
constructor Create;
destructor Destroy; override;
function AddOption: TSWFAS3MethodOptions;
property HasOptional: boolean read FHasOptional write FHasOptional;
property HasParamNames: boolean read FHasParamNames write FHasParamNames;
property Name: Longint read FName write FName;
property NeedActivation: boolean read FNeedActivation write FNeedActivation;
property NeedArguments: boolean read FNeedArguments write FNeedArguments;
property NeedRest: boolean read FNeedRest write FNeedRest;
property Option[index: integer]: TSWFAS3MethodOptions read GetOption;
property Options: TObjectList read FOptions;
property ParamNames: TSWFIntegerList read FParamNames;
property ParamTypes: TSWFIntegerList read FParamTypes;
property ReturnType: Longint read FReturnType write FReturnType;
property SetDxns: boolean read FSetDxns write FSetDxns;
end;
TSWFAS3Methods = class (TObject)
private
MethodsList: TObjectList;
function GetMethod(index: integer): TSWFAS3Method;
public
constructor Create;
destructor Destroy; override;
function AddMethod: TSWFAS3Method;
procedure ReadFromStream(be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
property Method[index: integer]: TSWFAS3Method read GetMethod;
end;
TSWFAS3MetadataItem = class (TObject)
private
FKey: LongInt;
FValue: LongInt;
public
property Value: LongInt read FValue write FValue;
property Key: LongInt read FKey write FKey;
end;
TSWFAS3MetadataInfo = class (TObject)
private
FInfoList: TObjectList;
FName: Longint;
function GetItem(index: integer): TSWFAS3MetadataItem;
public
constructor Create;
destructor Destroy; override;
function AddMetadataItem: TSWFAS3MetadataItem;
property InfoList: TObjectList read FInfoList;
property MetaItem[index: integer]: TSWFAS3MetadataItem read GetItem;
property Name: Longint read FName write FName;
end;
TSWFAS3Metadata = class (TObject)
private
FMetadataList: TObjectList;
function GetMetadata(index: integer): TSWFAS3MetadataInfo;
public
constructor Create;
destructor Destroy; override;
function AddMetaInfo: TSWFAS3MetadataInfo;
procedure ReadFromStream(be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
property MetadataList: TObjectList read FMetadataList;
property MetadataInfo[index: integer]: TSWFAS3MetadataInfo read GetMetadata;
end;
TSWFAS3Trait = class (TObject)
private
FID: LongInt;
FIsFinal: Boolean;
FIsMetadata: Boolean;
FIsOverride: Boolean;
FName: LongInt;
FTraitType: byte;
FMetadata: TSWFIntegerList;
FSpecID: LongInt;
FVIndex: LongInt;
FVKind: byte;
function GetMetadata: TSWFIntegerList;
procedure SetIsMetadata(const Value: Boolean);
public
destructor Destroy; override;
procedure ReadFromStream(be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
property ID: LongInt read FID write FID;
property IsFinal: Boolean read FIsFinal write FIsFinal;
property IsMetadata: Boolean read FIsMetadata write SetIsMetadata;
property IsOverride: Boolean read FIsOverride write FIsOverride;
property Name: LongInt read FName write FName;
property TraitType: byte read FTraitType write FTraitType;
property Metadata: TSWFIntegerList read GetMetadata;
property SpecID: LongInt read FSpecID write FSpecID;
property VIndex: LongInt read FVIndex write FVIndex;
property VKind: byte read FVKind write FVKind;
end;
TSWFAS3Traits = class (TObject)
FTraits: TObjectList;
function GetTrait(Index: Integer): TSWFAS3Trait;
public
constructor Create; virtual;
destructor Destroy; override;
function AddTrait: TSWFAS3Trait;
property Trait[Index: longint]: TSWFAS3Trait read GetTrait;
property Traits: TObjectList read FTraits;
end;
TSWFAS3InstanceItem = class (TSWFAS3Traits)
private
FClassFinal: Boolean;
FClassInterface: Boolean;
FClassProtectedNs: Boolean;
FClassSealed: Boolean;
FIinit: LongInt;
FInterfaces: TSWFIntegerList;
FName: LongInt;
FProtectedNs: LongInt;
FSuperName: LongInt;
public
constructor Create; override;
destructor Destroy; override;
procedure ReadFromStream(be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
property ClassFinal: Boolean read FClassFinal write FClassFinal;
property ClassInterface: Boolean read FClassInterface write FClassInterface;
property ClassProtectedNs: Boolean read FClassProtectedNs write FClassProtectedNs;
property ClassSealed: Boolean read FClassSealed write FClassSealed;
property Iinit: LongInt read FIinit write FIinit;
property Interfaces: TSWFIntegerList read FInterfaces;
property Name: LongInt read FName write FName;
property ProtectedNs: LongInt read FProtectedNs write FProtectedNs;
property SuperName: LongInt read FSuperName write FSuperName;
end;
TSWFAS3Instance = class (TObjectList)
private
function GetInstanceItem(Index: longint): TSWFAS3InstanceItem;
public
function AddInstanceItem: TSWFAS3InstanceItem;
procedure ReadFromStream(Count: Longint; be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
property InstanceItem[Index: longint]: TSWFAS3InstanceItem read GetInstanceItem;
end;
TSWFAS3ClassInfo = class (TSWFAS3Traits)
private
FCInit: LongInt;
public
procedure ReadFromStream(be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
property CInit: LongInt read FCInit write FCInit;
end;
TSWFAS3Classes = class(TObjectList)
private
function GetClassInfo(Index: Integer): TSWFAS3ClassInfo;
public
procedure ReadFromStream(rcount: longInt; be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
function AddClassInfo: TSWFAS3ClassInfo;
property _ClassInfo[Index: Integer]: TSWFAS3ClassInfo read GetClassInfo;
end;
TSWFAS3ScriptInfo = TSWFAS3ClassInfo;
TSWFAS3Scripts = class(TObjectList)
private
function GetScriptInfo(Index: Integer): TSWFAS3ScriptInfo;
public
procedure ReadFromStream(be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
function AddScriptInfo: TSWFAS3ScriptInfo;
property ScriptInfo[Index: Integer]: TSWFAS3ScriptInfo read GetScriptInfo;
end;
TSWFAS3Exception = class (TObject)
private
FExcType: LongInt;
FFrom: LongInt;
FTarget: LongInt;
FVarName: LongInt;
F_To: LongInt;
public
property ExcType: LongInt read FExcType write FExcType;
property From: LongInt read FFrom write FFrom;
property Target: LongInt read FTarget write FTarget;
property VarName: LongInt read FVarName write FVarName;
property _To: LongInt read F_To write F_To;
end;
TSWFAS3MethodBodyInfo = class (TSWFAS3Traits)
private
FCode: TMemoryStream;
FExceptions: TObjectList;
FInitScopeDepth: LongInt;
FLocalCount: LongInt;
FMaxScopeDepth: LongInt;
FMaxStack: LongInt;
FMethod: LongInt;
function GetException(Index: Integer): TSWFAS3Exception;
function GetCodeItem(Index: Integer): byte;
procedure SetCodeItem(Index: Integer; const Value: byte);
procedure SetStrByteCode(Value: AnsiString);
function GetStrByteCode: AnsiString;
public
constructor Create; override;
destructor Destroy; override;
procedure ReadFromStream(be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
function AddException: TSWFAS3Exception;
property Code: TMemoryStream read FCode;
property StrCode: AnsiString read GetStrByteCode write SetStrByteCode;
property CodeItem[Index: Integer]: byte read GetCodeItem write SetCodeItem;
property Exception[Index: Integer]: TSWFAS3Exception read GetException;
property Exceptions: TObjectList read FExceptions;
property InitScopeDepth: LongInt read FInitScopeDepth write FInitScopeDepth;
property LocalCount: LongInt read FLocalCount write FLocalCount;
property MaxScopeDepth: LongInt read FMaxScopeDepth write FMaxScopeDepth;
property MaxStack: LongInt read FMaxStack write FMaxStack;
property Method: LongInt read FMethod write FMethod;
end;
TSWFAS3MethodBodies = class(TObjectList)
private
function GetClassInfo(Index: Integer): TSWFAS3MethodBodyInfo;
public
procedure ReadFromStream(be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
function AddMethodBodyInfo: TSWFAS3MethodBodyInfo;
property MethodBodyInfo[Index: Integer]: TSWFAS3MethodBodyInfo read GetClassInfo;
end;
TSWFDoABC = class (TSWFObject)
private
FData: Pointer;
FDataSize: LongInt;
FSelfDestroy: Boolean;
FClasses: TSWFAS3Classes;
FDoAbcLazyInitializeFlag: boolean;
FMinorVersion: Word;
FMajorVersion: Word;
FConstantPool: TSWFAS3ConstantPool;
FInstance: TSWFAS3Instance;
FMethods: TSWFAS3Methods;
FMethodBodies: TSWFAS3MethodBodies;
FMetadata: TSWFAS3Metadata;
FScripts: TSWFAS3Scripts;
FActionName: string;
FParseActions: Boolean;
function GetClasses: TSWFAS3Classes;
function GetInstance: TSWFAS3Instance;
function GetMetadata: TSWFAS3Metadata;
function GetMethods: TSWFAS3Methods;
function GetScripts: TSWFAS3Scripts;
function GetStrVersion: string;
function GetMethodBodies: TSWFAS3MethodBodies;
procedure SetStrVersion(ver: string);
public
constructor Create;
destructor Destroy; override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property ActionName: string read FActionName write FActionName;
property Classes: TSWFAS3Classes read GetClasses;
property ConstantPool: TSWFAS3ConstantPool read FConstantPool;
property Data: Pointer read FData write FData;
property DataSize: LongInt read FDataSize write FDataSize;
property DoAbcLazyInitializeFlag: boolean read FDoAbcLazyInitializeFlag write FDoAbcLazyInitializeFlag;
property Instance: TSWFAS3Instance read GetInstance;
property MajorVersion: Word read FMajorVersion write FMajorVersion;
property Metadata: TSWFAS3Metadata read GetMetadata;
property MethodBodies: TSWFAS3MethodBodies read GetMethodBodies;
property Methods: TSWFAS3Methods read GetMethods;
property MinorVersion: Word read FMinorVersion write FMinorVersion;
property ParseActions: Boolean read FParseActions write FParseActions;
property Scripts: TSWFAS3Scripts read GetScripts;
property SelfDestroy: Boolean read FSelfDestroy write FSelfDestroy;
property StrVersion: string read GetStrVersion write SetStrVersion;
end;
// ===========================================================
// Display List
// ===========================================================
TSWFBasedPlaceObject = class (TSWFObject)
private
FCharacterId: Word;
FDepth: Word;
procedure SetCharacterId(ID: Word); virtual;
public
procedure Assign(Source: TBasedSWFObject); override;
property CharacterId: Word read FCharacterId write SetCharacterId;
property Depth: Word read FDepth write FDepth;
end;
TSWFPlaceObject = class (TSWFBasedPlaceObject)
private
FColorTransform: TSWFColorTransform;
FInitColorTransform: Boolean;
FMatrix: TSWFMatrix;
function GetInitColorTransform: Boolean;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property ColorTransform: TSWFColorTransform read FColorTransform;
property InitColorTransform: Boolean read GetInitColorTransform write FInitColorTransform;
property Matrix: TSWFMatrix read FMatrix;
end;
TSWFClipActionRecord = class (TSWFActionList)
private
FEventFlags: TSWFClipEvents;
FKeyCode: Byte;
procedure SetKeyCode(Value: Byte);
function GetActions: TSWFActionList;
public
// constructor Create;
// destructor Destroy; override;
procedure Assign(Source: TSWFClipActionRecord);
property Actions: TSWFActionList read GetActions;
property EventFlags: TSWFClipEvents read FEventFlags write FEventFlags;
property KeyCode: Byte read FKeyCode write SetKeyCode;
end;
TSWFClipActions = class (TObject)
private
FActionRecords: TObjectList;
FAllEventFlags: TSWFClipEvents;
function GetActionRecord(Index: Integer): TSWFClipActionRecord;
public
constructor Create;
destructor Destroy; override;
function AddActionRecord(EventFlags: TSWFClipEvents; KeyCode: byte): TSWFClipActionRecord;
procedure Assign(Source: TSWFClipActions);
function Count: integer;
property ActionRecord[Index: Integer]: TSWFClipActionRecord read GetActionRecord;
property ActionRecords: TObjectList read FActionRecords;
property AllEventFlags: TSWFClipEvents read FAllEventFlags write FAllEventFlags;
end;
TSWFPlaceObject2 = class (TSWFBasedPlaceObject)
private
fClipActions: TSWFClipActions;
FClipDepth: Word;
FColorTransform: TSWFColorTransform;
FMatrix: TSWFMatrix;
FName: string;
FParseActions: Boolean;
FPlaceFlagHasCharacter: Boolean;
FPlaceFlagHasClipActions: Boolean;
FPlaceFlagHasClipDepth: Boolean;
FPlaceFlagHasColorTransform: Boolean;
FPlaceFlagHasMatrix: Boolean;
FPlaceFlagHasName: Boolean;
FPlaceFlagHasRatio: Boolean;
FPlaceFlagMove: Boolean;
FRatio: Word;
FSWFVersion: Byte;
function GetColorTransform: TSWFColorTransform;
function GetMatrix: TSWFMatrix;
procedure SetCharacterId(Value: Word); override;
procedure SetClipDepth(Value: Word);
procedure SetName(Value: string);
procedure SetRatio(Value: Word);
protected
procedure ReadFilterFromStream(be: TBitsEngine); virtual;
procedure ReadAddonFlag(be: TBitsEngine); virtual;
procedure WriteAddonFlag(be: TBitsEngine); virtual;
procedure WriteFilterToStream(be: TBitsEngine); virtual;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function ClipActions: TSWFClipActions;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property ClipDepth: Word read FClipDepth write SetClipDepth;
property ColorTransform: TSWFColorTransform read GetColorTransform;
property Matrix: TSWFMatrix read GetMatrix;
property Name: string read FName write SetName;
property ParseActions: Boolean read FParseActions write FParseActions;
property PlaceFlagHasCharacter: Boolean read FPlaceFlagHasCharacter write FPlaceFlagHasCharacter;
property PlaceFlagHasClipActions: Boolean read FPlaceFlagHasClipActions write FPlaceFlagHasClipActions;
property PlaceFlagHasClipDepth: Boolean read FPlaceFlagHasClipDepth write FPlaceFlagHasClipDepth;
property PlaceFlagHasColorTransform: Boolean read FPlaceFlagHasColorTransform write FPlaceFlagHasColorTransform;
property PlaceFlagHasMatrix: Boolean read FPlaceFlagHasMatrix write FPlaceFlagHasMatrix;
property PlaceFlagHasName: Boolean read FPlaceFlagHasName write FPlaceFlagHasName;
property PlaceFlagHasRatio: Boolean read FPlaceFlagHasRatio write FPlaceFlagHasRatio;
property PlaceFlagMove: Boolean read FPlaceFlagMove write FPlaceFlagMove;
property Ratio: Word read FRatio write SetRatio;
property SWFVersion: Byte read FSWFVersion write FSWFVersion;
end;
TSWFFilter = class (TObject)
private
FFilterID: TSWFFilterID;
public
procedure Assign(Source: TSWFFilter); virtual; abstract;
procedure ReadFromStream(be: TBitsEngine); virtual; abstract;
procedure WriteToStream(be: TBitsEngine); virtual; abstract;
property FilterID: TSWFFilterID read FFilterID write FFilterID;
end;
TSWFColorMatrixFilter = class (TSWFFilter)
private
FMatrix: array [0..19] of single;
function GetMatrix(Index: Integer): single;
function GetR0: single;
function GetR1: single;
function GetR2: single;
function GetR3: single;
function GetR4: single;
function GetG0: single;
function GetG1: single;
function GetG2: single;
function GetG3: single;
function GetG4: single;
function GetB0: single;
function GetB1: single;
function GetB2: single;
function GetB3: single;
function GetB4: single;
function GetA0: single;
function GetA1: single;
function GetA2: single;
function GetA3: single;
function GetA4: single;
procedure SetMatrix(Index: Integer; const Value: single);
procedure SetR0(const Value: single);
procedure SetR1(const Value: single);
procedure SetR2(const Value: single);
procedure SetR3(const Value: single);
procedure SetR4(const Value: single);
procedure SetG0(const Value: single);
procedure SetG1(const Value: single);
procedure SetG2(const Value: single);
procedure SetG3(const Value: single);
procedure SetG4(const Value: single);
procedure SetB0(const Value: single);
procedure SetB1(const Value: single);
procedure SetB2(const Value: single);
procedure SetB3(const Value: single);
procedure SetB4(const Value: single);
procedure SetA0(const Value: single);
procedure SetA1(const Value: single);
procedure SetA2(const Value: single);
procedure SetA3(const Value: single);
procedure SetA4(const Value: single);
public
constructor Create;
procedure AdjustColor(Brightness, Contrast, Saturation, Hue: Integer);
procedure Assign(Source: TSWFFilter); override;
procedure ResetValues;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property Matrix[Index: Integer]: single read GetMatrix write SetMatrix;
property R0: single read GetR0 write SetR0;
property R1: single read GetR1 write SetR1;
property R2: single read GetR2 write SetR2;
property R3: single read GetR3 write SetR3;
property R4: single read GetR4 write SetR4;
property G0: single read GetG0 write SetG0;
property G1: single read GetG1 write SetG1;
property G2: single read GetG2 write SetG2;
property G3: single read GetG3 write SetG3;
property G4: single read GetG4 write SetG4;
property B0: single read GetB0 write SetB0;
property B1: single read GetB1 write SetB1;
property B2: single read GetB2 write SetB2;
property B3: single read GetB3 write SetB3;
property B4: single read GetB4 write SetB4;
property A0: single read GetA0 write SetA0;
property A1: single read GetA1 write SetA1;
property A2: single read GetA2 write SetA2;
property A3: single read GetA3 write SetA3;
property A4: single read GetA4 write SetA4;
end;
TSWFConvolutionFilter = class (TSWFFilter)
private
FBias: single;
FClamp: Boolean;
FDefaultColor: TSWFRGBA;
FDivisor: single;
FMatrix: TList;
FMatrixX: byte;
FMatrixY: byte;
FPreserveAlpha: Boolean;
function GetMatrix(Index: Integer): single;
procedure SetMatrix(Index: Integer; const Value: single);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFFilter); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property Bias: single read FBias write FBias;
property Clamp: Boolean read FClamp write FClamp;
property DefaultColor: TSWFRGBA read FDefaultColor;
property Divisor: single read FDivisor write FDivisor;
property Matrix[Index: Integer]: single read GetMatrix write SetMatrix;
property MatrixX: byte read FMatrixX write FMatrixX;
property MatrixY: byte read FMatrixY write FMatrixY;
property PreserveAlpha: Boolean read FPreserveAlpha write FPreserveAlpha;
end;
TSWFBlurFilter = class (TSWFFilter)
private
FBlurX: single;
FBlurY: single;
FPasses: byte;
public
constructor Create; virtual;
procedure Assign(Source: TSWFFilter); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property BlurX: single read FBlurX write FBlurX;
property BlurY: single read FBlurY write FBlurY;
property Passes: byte read FPasses write FPasses;
end;
TSWFGlowFilter = class(TSWFBlurFilter)
private
FStrength: single;
FGlowColor: TSWFRGBA;
FInnerGlow: Boolean;
FKnockout: Boolean;
FCompositeSource: Boolean;
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TSWFFilter); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property GlowColor: TSWFRGBA read FGlowColor;
property InnerGlow: Boolean read FInnerGlow write FInnerGlow;
property Knockout: Boolean read FKnockout write FKnockout;
property CompositeSource: Boolean read FCompositeSource write FCompositeSource;
property Strength: single read FStrength write FStrength;
end;
TSWFDropShadowFilter = class (TSWFBlurFilter)
private
FAngle: single;
FCompositeSource: Boolean;
FDistance: single;
FInnerShadow: Boolean;
FKnockout: Boolean;
FStrength: single;
FDropShadowColor: TSWFRGBA;
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TSWFFilter); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property Angle: single read FAngle write FAngle;
property CompositeSource: Boolean read FCompositeSource write FCompositeSource;
property Distance: single read FDistance write FDistance;
property DropShadowColor: TSWFRGBA read FDropShadowColor;
property InnerShadow: Boolean read FInnerShadow write FInnerShadow;
property Knockout: Boolean read FKnockout write FKnockout;
property Strength: single read FStrength write FStrength;
end;
TSWFBevelFilter = class(TSWFBlurFilter)
private
FAngle: single;
FCompositeSource: Boolean;
FDistance: single;
FInnerShadow: Boolean;
FKnockout: Boolean;
FStrength: single;
FShadowColor: TSWFRGBA;
FHighlightColor: TSWFRGBA;
FOnTop: Boolean;
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TSWFFilter); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property Angle: single read FAngle write FAngle;
property CompositeSource: Boolean read FCompositeSource write FCompositeSource;
property Distance: single read FDistance write FDistance;
property ShadowColor: TSWFRGBA read FShadowColor;
property InnerShadow: Boolean read FInnerShadow write FInnerShadow;
property Knockout: Boolean read FKnockout write FKnockout;
property HighlightColor: TSWFRGBA read FHighlightColor;
property OnTop: Boolean read FOnTop write FOnTop;
property Strength: single read FStrength write FStrength;
end;
TSWFGradientRec = record
color: recRGBA;
ratio: byte;
end;
TSWFGradientGlowFilter = class(TSWFBlurFilter)
private
FAngle: single;
FColor: array [1..15] of TSWFRGBA;
FCompositeSource: Boolean;
FDistance: single;
FInnerShadow: Boolean;
FKnockout: Boolean;
FNumColors: byte;
FStrength: single;
FOnTop: Boolean;
FRatio: array [1..15] of byte;
function GetGradient(Index: byte): TSWFGradientRec;
function GetGradientColor(Index: Integer): TSWFRGBA;
function GetGradientRatio(Index: Integer): Byte;
procedure SetGradientRatio(Index: Integer; Value: Byte);
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TSWFFilter); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property Angle: single read FAngle write FAngle;
property CompositeSource: Boolean read FCompositeSource write FCompositeSource;
property Distance: single read FDistance write FDistance;
property Gradient[Index: byte]: TSWFGradientRec read GetGradient;
property GradientColor[Index: Integer]: TSWFRGBA read GetGradientColor;
property GradientRatio[Index: Integer]: Byte read GetGradientRatio write
SetGradientRatio;
property InnerShadow: Boolean read FInnerShadow write FInnerShadow;
property Knockout: Boolean read FKnockout write FKnockout;
property NumColors: byte read FNumColors write FNumColors;
property OnTop: Boolean read FOnTop write FOnTop;
property Strength: single read FStrength write FStrength;
end;
TSWFGradientBevelFilter = class (TSWFGradientGlowFilter)
public
constructor Create; override;
end;
TSWFFilterList = class (TObjectList)
private
function GetFilter(Index: Integer): TSWFFilter;
public
function AddFilter(id: TSwfFilterID): TSWFFilter;
procedure ReadFromStream(be: TBitsEngine);
procedure WriteToStream(be: TBitsEngine);
property Filter[Index: Integer]: TSWFFilter read GetFilter;
end;
TSWFPlaceObject3 = class(TSWFPlaceObject2)
private
FBlendMode: TSWFBlendMode;
FPlaceFlagHasCacheAsBitmap: Boolean;
FPlaceFlagHasBlendMode: Boolean;
FPlaceFlagHasFilterList: Boolean;
FSaveAsPO2: boolean;
FSurfaceFilterList: TSWFFilterList;
FPlaceFlagHasImage: boolean;
FPlaceFlagHasClassName: boolean;
FClassName: string;
function GetSurfaceFilterList: TSWFFilterList;
procedure SetClassName(const Value: string);
protected
procedure ReadAddonFlag(be: TBitsEngine); override;
procedure ReadFilterFromStream(be: TBitsEngine); override;
procedure WriteAddonFlag(be: TBitsEngine); override;
procedure WriteFilterToStream(be: TBitsEngine); override;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
property BlendMode: TSWFBlendMode read FBlendMode write FBlendMode;
property _ClassName: string read FClassName write SetClassName;
property PlaceFlagHasCacheAsBitmap: Boolean read FPlaceFlagHasCacheAsBitmap
write FPlaceFlagHasCacheAsBitmap;
property PlaceFlagHasBlendMode: Boolean read FPlaceFlagHasBlendMode write
FPlaceFlagHasBlendMode;
property PlaceFlagHasImage: boolean read FPlaceFlagHasImage write FPlaceFlagHasImage;
property PlaceFlagHasClassName: boolean read FPlaceFlagHasClassName write FPlaceFlagHasClassName;
property PlaceFlagHasFilterList: Boolean read FPlaceFlagHasFilterList write
FPlaceFlagHasFilterList;
property SaveAsPO2: boolean read FSaveAsPO2 write FSaveAsPO2;
property SurfaceFilterList: TSWFFilterList read GetSurfaceFilterList;
end;
TSWFRemoveObject = class (TSWFObject)
private
FCharacterID: Word;
FDepth: Word;
public
constructor Create;
procedure Assign(Source: TBasedSWFObject); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property CharacterID: Word read FCharacterID write FCharacterID;
property Depth: Word read FDepth write FDepth;
end;
TSWFRemoveObject2 = class (TSWFObject)
private
Fdepth: Word;
public
constructor Create;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property depth: Word read Fdepth write Fdepth;
end;
TSWFShowFrame = class (TSWFObject)
public
constructor Create;
end;
// =========================================================
// Shape
// =========================================================
TSWFFillStyle = class (TObject)
private
FhasAlpha: Boolean;
FSWFFillType: TSWFFillType;
public
procedure Assign(Source: TSWFFillStyle); virtual;
procedure ReadFromStream(be: TBitsEngine); virtual; abstract;
procedure WriteToStream(be: TBitsEngine); virtual; abstract;
property hasAlpha: Boolean read FhasAlpha write FhasAlpha;
property SWFFillType: TSWFFillType read FSWFFillType write FSWFFillType;
end;
TSWFLineStyle = class (TObject)
private
FColor: TSWFRGBA;
FWidth: Word;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TSWFLineStyle); virtual;
procedure ReadFromStream(be: TBitsEngine); virtual;
procedure WriteToStream(be: TBitsEngine); virtual;
property Color: TSWFRGBA read FColor;
property Width: Word read FWidth write FWidth;
end;
TSWFLineStyle2 = class (TSWFLineStyle)
private
FHasFillFlag: Boolean;
FStartCapStyle: byte;
FJoinStyle: byte;
FNoClose: Boolean;
FNoHScaleFlag: Boolean;
FNoVScaleFlag: Boolean;
FPixelHintingFlag: Boolean;
FEndCapStyle: byte;
FFillStyle: TSWFFillStyle;
FMiterLimitFactor: single;
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TSWFLineStyle); override;
function GetFillStyle(style: integer): TSWFFillStyle;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property HasFillFlag: Boolean read FHasFillFlag write FHasFillFlag;
property StartCapStyle: byte read FStartCapStyle write FStartCapStyle;
property JoinStyle: byte read FJoinStyle write FJoinStyle;
property NoClose: Boolean read FNoClose write FNoClose;
property NoHScaleFlag: Boolean read FNoHScaleFlag write FNoHScaleFlag;
property NoVScaleFlag: Boolean read FNoVScaleFlag write FNoVScaleFlag;
property PixelHintingFlag: Boolean read FPixelHintingFlag write
FPixelHintingFlag;
property EndCapStyle: byte read FEndCapStyle write FEndCapStyle;
property MiterLimitFactor: single read FMiterLimitFactor write
FMiterLimitFactor;
end;
TSWFColorFill = class (TSWFFillStyle)
private
FColor: TSWFRGBA;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFFillStyle); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property Color: TSWFRGBA read FColor;
end;
TSWFImageFill = class (TSWFFillStyle)
private
FImageID: Word;
FMatrix: TSWFMatrix;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFFillStyle); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure ScaleTo(Frame: TRect; W, H: word);
procedure WriteToStream(be: TBitsEngine); override;
property ImageID: Word read FImageID write FImageID;
property Matrix: TSWFMatrix read FMatrix;
end;
TSWFBaseGradientFill = class(TSWFFillStyle)
private
FColor: array [1..15] of TSWFRGBA;
FCount: Byte;
FInterpolationMode: TSWFInterpolationMode;
FRatio: array [1..15] of byte;
FSpreadMode: TSWFSpreadMode;
function GetGradient(Index: byte): TSWFGradientRec;
function GetGradientColor(Index: Integer): TSWFRGBA;
function GetGradientRatio(Index: Integer): Byte;
procedure SetGradientRatio(Index: Integer; Value: Byte);
protected
property InterpolationMode: TSWFInterpolationMode read FInterpolationMode write
FInterpolationMode;
property SpreadMode: TSWFSpreadMode read FSpreadMode write FSpreadMode;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFFillStyle); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property Count: Byte read FCount write FCount;
property Gradient[Index: byte]: TSWFGradientRec read GetGradient;
property GradientColor[Index: Integer]: TSWFRGBA read GetGradientColor;
property GradientRatio[Index: Integer]: Byte read GetGradientRatio write SetGradientRatio;
end;
TSWFGradientFill = class (TSWFBaseGradientFill)
private
FMatrix: TSWFMatrix;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFFillStyle); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure ScaleTo(Frame: TRect);
procedure WriteToStream(be: TBitsEngine); override;
property Matrix: TSWFMatrix read FMatrix;
end;
TSWFFocalGradientFill = class(TSWFGradientFill)
private
FFocalPoint: smallint;
function GetFocalPoint: single;
procedure SetFocalPoint(const Value: single);
public
constructor Create;
procedure Assign(Source: TSWFFillStyle); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property FocalPoint: single read GetFocalPoint write SetFocalPoint;
property InterpolationMode;
property SpreadMode;
end;
TSWFShapeRecord = class (TObject)
private
FShapeRecType: TShapeRecType;
public
procedure Assign(Source: TSWFShapeRecord); virtual;
procedure WriteToStream(be: TBitsEngine); virtual; abstract;
property ShapeRecType: TShapeRecType read FShapeRecType write FShapeRecType;
end;
TSWFEndShapeRecord = class (TSWFShapeRecord)
public
constructor Create;
procedure WriteToStream(be: TBitsEngine); override;
end;
TSWFStraightEdgeRecord = class (TSWFShapeRecord)
private
FX: LongInt;
FY: LongInt;
public
constructor Create;
procedure Assign(Source: TSWFShapeRecord); override;
procedure WriteToStream(be: TBitsEngine); override;
property X: LongInt read FX write FX;
property Y: LongInt read FY write FY;
end;
TSWFStyleChangeRecord = class (TSWFStraightEdgeRecord)
private
bitsFill: Byte;
bitsLine: Byte;
FFill0Id: Word;
FFill1Id: Word;
FLineId: Word;
FNewFillStyles: TObjectList;
FNewLineStyles: TObjectList;
FStateFillStyle0: Boolean;
FStateFillStyle1: Boolean;
FStateLineStyle: Boolean;
FStateMoveTo: Boolean;
FStateNewStyles: Boolean;
hasAlpha: Boolean;
function GetNewFillStyles: TObjectList;
function GetNewLineStyles: TObjectList;
procedure SetFill0Id(Value: Word);
procedure SetFill1Id(Value: Word);
procedure SetLineId(Value: Word);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFShapeRecord); override;
procedure WriteToStream(be: TBitsEngine); override;
property Fill0Id: Word read FFill0Id write SetFill0Id;
property Fill1Id: Word read FFill1Id write SetFill1Id;
property LineId: Word read FLineId write SetLineId;
property NewFillStyles: TObjectList read GetNewFillStyles;
property NewLineStyles: TObjectList read GetNewLineStyles;
property StateFillStyle0: Boolean read FStateFillStyle0 write FStateFillStyle0;
property StateFillStyle1: Boolean read FStateFillStyle1 write FStateFillStyle1;
property StateLineStyle: Boolean read FStateLineStyle write FStateLineStyle;
property StateMoveTo: Boolean read FStateMoveTo write FStateMoveTo;
property StateNewStyles: Boolean read FStateNewStyles write FStateNewStyles;
end;
TSWFCurvedEdgeRecord = class (TSWFShapeRecord)
private
FAnchorX: LongInt;
FAnchorY: LongInt;
FControlX: LongInt;
FControlY: LongInt;
public
constructor Create;
procedure Assign(Source: TSWFShapeRecord); override;
procedure WriteToStream(be: TBitsEngine); override;
property AnchorX: LongInt read FAnchorX write FAnchorX;
property AnchorY: LongInt read FAnchorY write FAnchorY;
property ControlX: LongInt read FControlX write FControlX;
property ControlY: LongInt read FControlY write FControlY;
end;
TSWFDefineShape = class (TSWFObject)
private
FEdges: TObjectList;
FFillStyles: TObjectList;
FhasAlpha: Boolean;
FLineStyles: TObjectList;
FShapeBounds: TSWFRect;
FShapeId: Word;
protected
function GetEdgeRecord(index: longint): TSWFShapeRecord;
procedure ReadAddonFromStream(be: TBitsEngine); virtual;
procedure WriteAddonToStream(be: TBitsEngine); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property EdgeRecord[index: longint]: TSWFShapeRecord read GetEdgeRecord;
property Edges: TObjectList read FEdges write FEdges;
property FillStyles: TObjectList read FFillStyles;
property hasAlpha: Boolean read FhasAlpha write FhasAlpha;
property LineStyles: TObjectList read FLineStyles;
property ShapeBounds: TSWFRect read FShapeBounds;
property ShapeId: Word read FShapeId write FShapeId;
end;
TSWFDefineShape2 = class (TSWFDefineShape)
public
constructor Create; override;
function MinVersion: Byte; override;
end;
TSWFDefineShape3 = class (TSWFDefineShape)
public
constructor Create; override;
function MinVersion: Byte; override;
end;
TSWFDefineShape4 = class (TSWFDefineShape)
private
FEdgeBounds: TSWFRect;
FUsesNonScalingStrokes: Boolean;
FUsesScalingStrokes: Boolean;
protected
procedure ReadAddonFromStream(be: TBitsEngine); override;
procedure WriteAddonToStream(be: TBitsEngine); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
property EdgeBounds: TSWFRect read FEdgeBounds;
property UsesNonScalingStrokes: Boolean read FUsesNonScalingStrokes write
FUsesNonScalingStrokes;
property UsesScalingStrokes: Boolean read FUsesScalingStrokes write
FUsesScalingStrokes;
end;
// ==========================================================
// Bitmaps
// ==========================================================
TSWFDataObject = class (TSWFObject)
private
FData: Pointer;
FDataSize: LongInt;
FOnDataWrite: TSWFTagEvent;
FSelfDestroy: Boolean;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
property Data: Pointer read FData write FData;
property DataSize: LongInt read FDataSize write FDataSize;
property OnDataWrite: TSWFTagEvent read FOnDataWrite write FOnDataWrite;
property SelfDestroy: Boolean read FSelfDestroy write FSelfDestroy;
end;
TSWFDefineBinaryData = class (TSWFDataObject)
private
FCharacterID: word;
public
constructor Create; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property CharacterID: word read FCharacterID write FCharacterID;
end;
TSWFImageTag = class (TSWFDataObject)
private
FCharacterID: Word;
public
procedure Assign(Source: TBasedSWFObject); override;
property CharacterID: Word read FCharacterID write FCharacterID;
end;
TSWFDefineBits = class (TSWFImageTag)
public
constructor Create; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
end;
TSWFJPEGTables = class (TSWFDataObject)
public
constructor Create; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
end;
TSWFDefineBitsJPEG2 = class (TSWFDefineBits)
public
constructor Create; override;
function MinVersion: Byte; override;
procedure WriteTagBody(be: TBitsEngine); override;
end;
TSWFDefineBitsJPEG3 = class (TSWFDefineBitsJPEG2)
private
FAlphaData: Pointer;
FAlphaDataSize: LongInt;
FOnAlphaDataWrite: TSWFTagEvent;
FSelfAlphaDestroy: Boolean;
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property AlphaData: Pointer read FAlphaData write FAlphaData;
property AlphaDataSize: LongInt read FAlphaDataSize write FAlphaDataSize;
property OnAlphaDataWrite: TSWFTagEvent read FOnAlphaDataWrite write FOnAlphaDataWrite;
property SelfAlphaDestroy: Boolean read FSelfAlphaDestroy write FSelfAlphaDestroy;
end;
TSWFDefineBitsLossless = class (TSWFImageTag)
private
FBitmapColorTableSize: Byte;
FBitmapFormat: Byte;
FBitmapHeight: Word;
FBitmapWidth: Word;
public
constructor Create; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property BitmapColorTableSize: Byte read FBitmapColorTableSize write FBitmapColorTableSize;
property BitmapFormat: Byte read FBitmapFormat write FBitmapFormat;
property BitmapHeight: Word read FBitmapHeight write FBitmapHeight;
property BitmapWidth: Word read FBitmapWidth write FBitmapWidth;
end;
TSWFDefineBitsLossless2 = class (TSWFDefineBitsLossless)
public
constructor Create; override;
function MinVersion: Byte; override;
end;
// ==========================================================
// Morphing
// ==========================================================
TSWFMorphGradientRec = record
StartColor,
EndColor: recRGBA;
StartRatio,
EndRatio: byte;
end;
TSWFMorphLineStyle = class (TObject)
private
FEndColor: TSWFRGBA;
FEndWidth: Word;
FStartColor: TSWFRGBA;
FStartWidth: Word;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TSWFMorphLineStyle);
procedure ReadFromStream(be: TBitsEngine); virtual;
procedure WriteToStream(be: TBitsEngine); virtual;
property EndColor: TSWFRGBA read FEndColor;
property EndWidth: Word read FEndWidth write FEndWidth;
property StartColor: TSWFRGBA read FStartColor;
property StartWidth: Word read FStartWidth write FStartWidth;
end;
TSWFMorphLineStyle2 = class (TSWFMorphLineStyle)
private
FEndCapStyle: byte;
FHasFillFlag: Boolean;
FJoinStyle: byte;
FMiterLimitFactor: single;
FNoClose: Boolean;
FNoHScaleFlag: Boolean;
FNoVScaleFlag: Boolean;
FPixelHintingFlag: Boolean;
FStartCapStyle: byte;
FFillStyle: TSWFFillStyle;
public
destructor Destroy; override;
function GetFillStyle(style: integer): TSWFFillStyle;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property EndCapStyle: byte read FEndCapStyle write FEndCapStyle;
property HasFillFlag: Boolean read FHasFillFlag write FHasFillFlag;
property JoinStyle: byte read FJoinStyle write FJoinStyle;
property MiterLimitFactor: single read FMiterLimitFactor write
FMiterLimitFactor;
property NoClose: Boolean read FNoClose write FNoClose;
property NoHScaleFlag: Boolean read FNoHScaleFlag write FNoHScaleFlag;
property NoVScaleFlag: Boolean read FNoVScaleFlag write FNoVScaleFlag;
property PixelHintingFlag: Boolean read FPixelHintingFlag write
FPixelHintingFlag;
property StartCapStyle: byte read FStartCapStyle write FStartCapStyle;
end;
TSWFMorphFillStyle = class (TObject)
private
FSWFFillType: TSWFFillType;
public
procedure Assign(Source: TSWFMorphFillStyle); virtual; abstract;
procedure ReadFromStream(be: TBitsEngine); virtual; abstract;
procedure WriteToStream(be: TBitsEngine); virtual; abstract;
property SWFFillType: TSWFFillType read FSWFFillType write FSWFFillType;
end;
TSWFMorphColorFill = class (TSWFMorphFillStyle)
private
FEndColor: TSWFRGBA;
FStartColor: TSWFRGBA;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFMorphFillStyle); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property EndColor: TSWFRGBA read FEndColor;
property StartColor: TSWFRGBA read FStartColor;
end;
TSWFMorphGradientFill = class (TSWFMorphFillStyle)
private
FCount: Byte;
FEndColor: array [1..8] of TSWFRGBA;
FEndMatrix: TSWFMatrix;
FEndRatio: array [1..8] of byte;
FStartColor: array [1..8] of TSWFRGBA;
FStartMatrix: TSWFMatrix;
FStartRatio: array [1..8] of byte;
FSpreadMode: byte;
FInterpolationMode: byte;
function GetEndColor(Index: Integer): TSWFRGBA;
function GetEndGradient(Index: byte): TSWFGradientRec;
function GetEndRatio(Index: Integer): Byte;
function GetGradient(Index: byte): TSWFMorphGradientRec;
function GetStartColor(Index: Integer): TSWFRGBA;
function GetStartGradient(Index: byte): TSWFGradientRec;
function GetStartRatio(Index: Integer): Byte;
procedure SetEndRatio(Index: Integer; Value: Byte);
procedure SetStartRatio(Index: Integer; Value: Byte);
protected
property InterpolationMode: byte read FInterpolationMode write FInterpolationMode;
property SpreadMode: byte read FSpreadMode write FSpreadMode;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TSWFMorphFillStyle); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property Count: Byte read FCount write FCount;
property EndColor[Index: Integer]: TSWFRGBA read GetEndColor;
property EndGradient[Index: byte]: TSWFGradientRec read GetEndGradient;
property EndMatrix: TSWFMatrix read FEndMatrix;
property EndRatio[Index: Integer]: Byte read GetEndRatio write SetEndRatio;
property Gradient[Index: byte]: TSWFMorphGradientRec read GetGradient;
property StartColor[Index: Integer]: TSWFRGBA read GetStartColor;
property StartGradient[Index: byte]: TSWFGradientRec read GetStartGradient;
property StartMatrix: TSWFMatrix read FStartMatrix;
property StartRatio[Index: Integer]: Byte read GetStartRatio write SetStartRatio;
end;
TSWFMorphFocalGradientFill = class (TSWFMorphGradientFill)
private
FStartFocalPoint: smallint;
FEndFocalPoint: smallint;
function GetStartFocalPoint: single;
procedure SetStartFocalPoint(const Value: single);
function GetEndFocalPoint: single;
procedure SetEndFocalPoint(const Value: single);
public
constructor Create; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property StartFocalPoint: single read GetStartFocalPoint write SetStartFocalPoint;
property EndFocalPoint: single read GetEndFocalPoint write SetEndFocalPoint;
property InterpolationMode;
property SpreadMode;
end;
TSWFMorphImageFill = class (TSWFMorphFillStyle)
private
FEndMatrix: TSWFMatrix;
FImageID: Word;
FStartMatrix: TSWFMatrix;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFMorphFillStyle); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property EndMatrix: TSWFMatrix read FEndMatrix;
property ImageID: Word read FImageID write FImageID;
property StartMatrix: TSWFMatrix read FStartMatrix;
end;
TSWFDefineMorphShape = class (TSWFObject)
private
FCharacterID: Word;
FEndBounds: TSWFRect;
FEndEdges: TObjectList;
FMorphFillStyles: TObjectList;
FMorphLineStyles: TObjectList;
FStartBounds: TSWFRect;
FStartEdges: TObjectList;
function GetEndEdgeRecord(Index: Integer): TSWFShapeRecord;
function GetStartEdgeRecord(Index: Integer): TSWFShapeRecord;
protected
procedure ReadAddonFromStream(be: TBitsEngine); virtual;
procedure WriteAddonToStream(be: TBitsEngine); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property CharacterID: Word read FCharacterID write FCharacterID;
property EndBounds: TSWFRect read FEndBounds;
property EndEdgeRecord[Index: Integer]: TSWFShapeRecord read GetEndEdgeRecord;
property EndEdges: TObjectList read FEndEdges;
property MorphFillStyles: TObjectList read FMorphFillStyles;
property MorphLineStyles: TObjectList read FMorphLineStyles;
property StartBounds: TSWFRect read FStartBounds;
property StartEdgeRecord[Index: Integer]: TSWFShapeRecord read GetStartEdgeRecord;
property StartEdges: TObjectList read FStartEdges;
end;
TSWFDefineMorphShape2 = class (TSWFDefineMorphShape)
private
FStartEdgeBounds: TSWFRect;
FEndEdgeBounds: TSWFRect;
FUsesNonScalingStrokes: Boolean;
FUsesScalingStrokes: Boolean;
protected
procedure ReadAddonFromStream(be: TBitsEngine); override;
procedure WriteAddonToStream(be: TBitsEngine); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
property StartEdgeBounds: TSWFRect read FStartEdgeBounds;
property EndEdgeBounds: TSWFRect read FEndEdgeBounds;
property UsesNonScalingStrokes: Boolean read FUsesNonScalingStrokes write FUsesNonScalingStrokes;
property UsesScalingStrokes: Boolean read FUsesScalingStrokes write FUsesScalingStrokes;
end;
// ==========================================================
// TEXT
// ==========================================================
TSWFDefineFont = class (TSWFObject)
private
FFontID: Word;
FGlyphShapeTable: TObjectList;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property FontID: Word read FFontID write FFontID;
property GlyphShapeTable: TObjectList read FGlyphShapeTable write FGlyphShapeTable;
end;
TSWFDefineFontInfo = class (TSWFObject)
private
FCodeTable: TList;
FFontFlagsANSI: Boolean;
FFontFlagsBold: Boolean;
FFontFlagsItalic: Boolean;
FFontFlagsShiftJIS: Boolean;
FFontFlagsSmallText: Boolean;
FFontFlagsWideCodes: Boolean;
FFontID: Word;
FFontName: string;
FSWFVersion: Byte;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property CodeTable: TList read FCodeTable;
property FontFlagsANSI: Boolean read FFontFlagsANSI write FFontFlagsANSI;
property FontFlagsBold: Boolean read FFontFlagsBold write FFontFlagsBold;
property FontFlagsItalic: Boolean read FFontFlagsItalic write FFontFlagsItalic;
property FontFlagsShiftJIS: Boolean read FFontFlagsShiftJIS write FFontFlagsShiftJIS;
property FontFlagsSmallText: Boolean read FFontFlagsSmallText write FFontFlagsSmallText;
property FontFlagsWideCodes: Boolean read FFontFlagsWideCodes write FFontFlagsWideCodes;
property FontID: Word read FFontID write FFontID;
property FontName: string read FFontName write FFontName;
property SWFVersion: Byte read FSWFVersion write FSWFVersion;
end;
TSWFDefineFontInfo2 = class (TSWFDefineFontInfo)
private
FLanguageCode: Byte;
public
constructor Create; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property LanguageCode: Byte read FLanguageCode write FLanguageCode;
end;
TSWFKerningRecord = class (TObject)
private
FFontKerningAdjustment: Integer;
FFontKerningCode1: Word;
FFontKerningCode2: Word;
public
procedure Assign(source: TSWFKerningRecord);
property FontKerningAdjustment: Integer read FFontKerningAdjustment write FFontKerningAdjustment;
property FontKerningCode1: Word read FFontKerningCode1 write FFontKerningCode1;
property FontKerningCode2: Word read FFontKerningCode2 write FFontKerningCode2;
end;
TSWFDefineFont2 = class (TSWFDefineFont)
private
FCodeTable: TList;
FFontAdvanceTable: TList;
FFontAscent: Word;
FFontBoundsTable: TObjectList;
FFontDescent: Word;
FFontFlagsANSI: Boolean;
FFontFlagsBold: Boolean;
FFontFlagsHasLayout: Boolean;
FFontFlagsItalic: Boolean;
FFontFlagsShiftJIS: Boolean;
FFontFlagsSmallText: Boolean;
FFontFlagsWideCodes: Boolean;
FFontFlagsWideOffsets: Boolean;
FFontKerningTable: TObjectList;
FFontLeading: Word;
FFontName: string;
FKerningCount: Word;
FLanguageCode: Byte;
FSWFVersion: Byte;
function GetFontKerningTable: TObjectList;
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property CodeTable: TList read FCodeTable;
property FontAdvanceTable: TList read FFontAdvanceTable;
property FontAscent: Word read FFontAscent write FFontAscent;
property FontBoundsTable: TObjectList read FFontBoundsTable;
property FontDescent: Word read FFontDescent write FFontDescent;
property FontFlagsANSI: Boolean read FFontFlagsANSI write FFontFlagsANSI;
property FontFlagsBold: Boolean read FFontFlagsBold write FFontFlagsBold;
property FontFlagsHasLayout: Boolean read FFontFlagsHasLayout write FFontFlagsHasLayout;
property FontFlagsItalic: Boolean read FFontFlagsItalic write FFontFlagsItalic;
property FontFlagsShiftJIS: Boolean read FFontFlagsShiftJIS write FFontFlagsShiftJIS;
property FontFlagsSmallText: Boolean read FFontFlagsSmallText write FFontFlagsSmallText;
property FontFlagsWideCodes: Boolean read FFontFlagsWideCodes write FFontFlagsWideCodes;
property FontFlagsWideOffsets: Boolean read FFontFlagsWideOffsets write FFontFlagsWideOffsets;
property FontKerningTable: TObjectList read GetFontKerningTable;
property FontLeading: Word read FFontLeading write FFontLeading;
property FontName: string read FFontName write FFontName;
property KerningCount: Word read FKerningCount write FKerningCount;
property LanguageCode: Byte read FLanguageCode write FLanguageCode;
property SWFVersion: Byte read FSWFVersion write FSWFVersion;
end;
TSWFDefineFont3 = class (TSWFDefineFont2)
private
public
constructor Create; override;
function MinVersion: Byte; override;
end;
TSWFZoneData = class (TObject)
private
FAlignmentCoordinate: word;
FRange: word;
public
property AlignmentCoordinate: word read FAlignmentCoordinate write
FAlignmentCoordinate;
property Range: word read FRange write FRange;
end;
TSWFZoneRecord = class (TObjectList)
private
FNumZoneData: byte;
FZoneMaskX: Boolean;
FZoneMaskY: Boolean;
function GetZoneData(Index: Integer): TSWFZoneData;
public
function AddZoneData: TSWFZoneData;
property NumZoneData: byte read FNumZoneData write FNumZoneData;
property ZoneData[Index: Integer]: TSWFZoneData read GetZoneData;
property ZoneMaskX: Boolean read FZoneMaskX write FZoneMaskX;
property ZoneMaskY: Boolean read FZoneMaskY write FZoneMaskY;
end;
TSWFZoneTable = class (TObjectList)
private
function GetZoneRecord(Index: Integer): TSWFZoneRecord;
public
function AddZoneRecord: TSWFZoneRecord;
property ZoneRecord[Index: Integer]: TSWFZoneRecord read GetZoneRecord; default;
end;
TSWFDefineFontAlignZones = class (TSWFObject)
private
FCSMTableHint: byte;
FFontID: word;
FZoneTable: TSWFZoneTable;
public
constructor Create;
destructor Destroy; override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property CSMTableHint: byte read FCSMTableHint write FCSMTableHint;
property FontID: word read FFontID write FFontID;
property ZoneTable: TSWFZoneTable read FZoneTable;
end;
TSWFDefineFontName = class (TSWFObject)
private
FFontID: word;
FFontName: string;
FFontCopyright: string;
public
constructor Create;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property FontID: word read FFontID write FFontID;
property FontName: string read FFontName write FFontName;
property FontCopyright: string read FFontCopyright write FFontCopyright;
end;
TSWFGlyphEntry = class (TObject)
private
FGlyphAdvance: Integer;
FGlyphIndex: Word;
public
property GlyphAdvance: Integer read FGlyphAdvance write FGlyphAdvance;
property GlyphIndex: Word read FGlyphIndex write FGlyphIndex;
end;
TSWFTextRecord = class (TObject)
private
FFontID: Word;
FGlyphEntries: TObjectList;
FStyleFlagsHasColor: Boolean;
FStyleFlagsHasFont: Boolean;
FStyleFlagsHasXOffset: Boolean;
FStyleFlagsHasYOffset: Boolean;
FTextColor: TSWFRGBA;
FTextHeight: Word;
FXOffset: Integer;
FYOffset: Integer;
function GetGlyphEntry(Index: word): TSWFGlyphEntry;
function GetTextColor: TSWFRGBA;
procedure SetFontID(Value: Word);
procedure SetTextHeight(Value: Word);
procedure SetXOffset(Value: Integer);
procedure SetYOffset(Value: Integer);
protected
hasAlpha: Boolean;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TSWFTextRecord);
procedure WriteToStream(be: TBitsEngine; gb, ab: byte);
property FontID: Word read FFontID write SetFontID;
property GlyphEntries: TObjectList read FGlyphEntries;
property GlyphEntry[Index: word]: TSWFGlyphEntry read GetGlyphEntry;
property StyleFlagsHasColor: Boolean read FStyleFlagsHasColor write FStyleFlagsHasColor;
property StyleFlagsHasFont: Boolean read FStyleFlagsHasFont write FStyleFlagsHasFont;
property StyleFlagsHasXOffset: Boolean read FStyleFlagsHasXOffset write FStyleFlagsHasXOffset;
property StyleFlagsHasYOffset: Boolean read FStyleFlagsHasYOffset write FStyleFlagsHasYOffset;
property TextColor: TSWFRGBA read GetTextColor;
property TextHeight: Word read FTextHeight write SetTextHeight;
property XOffset: Integer read FXOffset write SetXOffset;
property YOffset: Integer read FYOffset write SetYOffset;
end;
TSWFDefineText = class (TSWFObject)
private
FAdvanceBits: Byte;
FCharacterID: Word;
FGlyphBits: Byte;
FhasAlpha: Boolean;
FTextBounds: TSWFRect;
FTextMatrix: TSWFMatrix;
FTextRecords: TObjectList;
function GetTextRecord(Index: Integer): TSWFTextRecord;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property AdvanceBits: Byte read FAdvanceBits write FAdvanceBits;
property CharacterID: Word read FCharacterID write FCharacterID;
property GlyphBits: Byte read FGlyphBits write FGlyphBits;
property hasAlpha: Boolean read FhasAlpha write FhasAlpha;
property TextBounds: TSWFRect read FTextBounds;
property TextMatrix: TSWFMatrix read FTextMatrix;
property TextRecord[Index: Integer]: TSWFTextRecord read GetTextRecord;
property TextRecords: TObjectList read FTextRecords;
end;
TSWFDefineText2 = class (TSWFDefineText)
public
constructor Create;
function MinVersion: Byte; override;
end;
TSWFDefineEditText = class (TSWFObject)
private
FAlign: Byte;
FAutoSize: Boolean;
FBorder: Boolean;
FBounds: TSWFRect;
FCharacterID: Word;
FFontHeight: Word;
FFontID: Word;
FHasFont: Boolean;
FHasLayout: Boolean;
FHasMaxLength: Boolean;
FHasText: Boolean;
FHasTextColor: Boolean;
FHTML: Boolean;
FIndent: Word;
FInitialText: AnsiString;
FLeading: Word;
FLeftMargin: Word;
FMaxLength: Word;
FMultiline: Boolean;
FNoSelect: Boolean;
FPassword: Boolean;
FReadOnly: Boolean;
FRightMargin: Word;
FSWFVersion: Integer;
FTextColor: TSWFRGBA;
FUseOutlines: Boolean;
FVariableName: string;
FWideInitialText: WideString;
// FWideLength: Cardinal;
FWordWrap: Boolean;
FHasFontClass: boolean;
FFontClass: string;
function GetTextColor: TSWFRGBA;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property Align: Byte read FAlign write FAlign;
property AutoSize: Boolean read FAutoSize write FAutoSize;
property Border: Boolean read FBorder write FBorder;
property Bounds: TSWFRect read FBounds;
property CharacterID: Word read FCharacterID write FCharacterID;
property FontHeight: Word read FFontHeight write FFontHeight;
property FontID: Word read FFontID write FFontID;
property FontClass: string read FFontClass write FFontClass;
property HasFont: Boolean read FHasFont write FHasFont;
property HasFontClass: boolean read FHasFontClass write FHasFontClass;
property HasLayout: Boolean read FHasLayout write FHasLayout;
property HasMaxLength: Boolean read FHasMaxLength write FHasMaxLength;
property HasText: Boolean read FHasText write FHasText;
property HasTextColor: Boolean read FHasTextColor write FHasTextColor;
property HTML: Boolean read FHTML write FHTML;
property Indent: Word read FIndent write FIndent;
property InitialText: AnsiString read FInitialText write FInitialText;
property Leading: Word read FLeading write FLeading;
property LeftMargin: Word read FLeftMargin write FLeftMargin;
property MaxLength: Word read FMaxLength write FMaxLength;
property Multiline: Boolean read FMultiline write FMultiline;
property NoSelect: Boolean read FNoSelect write FNoSelect;
property Password: Boolean read FPassword write FPassword;
property ReadOnly: Boolean read FReadOnly write FReadOnly;
property RightMargin: Word read FRightMargin write FRightMargin;
property SWFVersion: Integer read FSWFVersion write FSWFVersion;
property TextColor: TSWFRGBA read GetTextColor;
property UseOutlines: Boolean read FUseOutlines write FUseOutlines;
property VariableName: string read FVariableName write FVariableName;
property WideInitialText: WideString read FWideInitialText write FWideInitialText;
property WordWrap: Boolean read FWordWrap write FWordWrap;
end;
TSWFCSMTextSettings = class (TSWFObject)
private
FGridFit: byte;
FSharpness: single;
FTextID: word;
FThickness: single;
FUseFlashType: byte;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property GridFit: byte read FGridFit write FGridFit;
property Sharpness: single read FSharpness write FSharpness;
property TextID: word read FTextID write FTextID;
property Thickness: single read FThickness write FThickness;
property UseFlashType: byte read FUseFlashType write FUseFlashType;
end;
// ===========================================================
// SOUND
// ===========================================================
TSWFDefineSound = class (TSWFDataObject)
private
FSeekSamples: Word;
FSoundFormat: Byte;
FSoundId: Word;
FSoundRate: Byte;
FSoundSampleCount: dword;
FSoundSize: Boolean;
FSoundType: Boolean;
public
constructor Create; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property SeekSamples: Word read FSeekSamples write FSeekSamples;
property SoundFormat: Byte read FSoundFormat write FSoundFormat;
property SoundId: Word read FSoundId write FSoundId;
property SoundRate: Byte read FSoundRate write FSoundRate;
property SoundSampleCount: dword read FSoundSampleCount write FSoundSampleCount;
property SoundSize: Boolean read FSoundSize write FSoundSize;
property SoundType: Boolean read FSoundType write FSoundType;
end;
TSWFSoundEnvelope = class (TObject)
private
FLeftLevel: Word;
FPos44: dword;
FRightLevel: Word;
public
procedure Assign(Source: TSWFSoundEnvelope);
property LeftLevel: Word read FLeftLevel write FLeftLevel;
property Pos44: dword read FPos44 write FPos44;
property RightLevel: Word read FRightLevel write FRightLevel;
end;
TSWFStartSound = class (TSWFObject)
private
FHasEnvelope: Boolean;
FHasInPoint: Boolean;
FHasLoops: Boolean;
FHasOutPoint: Boolean;
FInPoint: dword;
FLoopCount: Word;
FOutPoint: dword;
FSoundClassName: string;
FSoundEnvelopes: TObjectList;
FSoundId: Word;
FSyncNoMultiple: Boolean;
FSyncStop: Boolean;
procedure SetInPoint(const Value: dword);
procedure SetLoopCount(Value: Word);
procedure SetOutPoint(const Value: dword);
protected
property SoundClassName: string read FSoundClassName write FSoundClassName;
public
constructor Create;
destructor Destroy; override;
procedure AddEnvelope(pos: dword; left, right: word);
procedure Assign(Source: TBasedSWFObject); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property HasEnvelope: Boolean read FHasEnvelope write FHasEnvelope;
property HasInPoint: Boolean read FHasInPoint write FHasInPoint;
property HasLoops: Boolean read FHasLoops write FHasLoops;
property HasOutPoint: Boolean read FHasOutPoint write FHasOutPoint;
property InPoint: dword read FInPoint write SetInPoint;
property LoopCount: Word read FLoopCount write SetLoopCount;
property OutPoint: dword read FOutPoint write SetOutPoint;
property SoundEnvelopes: TObjectList read FSoundEnvelopes;
property SoundId: Word read FSoundId write FSoundId;
property SyncNoMultiple: Boolean read FSyncNoMultiple write FSyncNoMultiple;
property SyncStop: Boolean read FSyncStop write FSyncStop;
end;
TSWFStartSound2 = class(TSWFStartSound)
public
constructor Create;
function MinVersion: Byte; override;
property SoundClassName;
end;
TSWFSoundStreamHead = class (TSWFObject)
private
FLatencySeek: Integer;
FPlaybackSoundRate: Byte;
FPlaybackSoundSize: Boolean;
FPlaybackSoundType: Boolean;
FStreamSoundCompression: Byte;
FStreamSoundRate: Byte;
FStreamSoundSampleCount: Word;
FStreamSoundSize: Boolean;
FStreamSoundType: Boolean;
public
constructor Create; virtual;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property LatencySeek: Integer read FLatencySeek write FLatencySeek;
property PlaybackSoundRate: Byte read FPlaybackSoundRate write FPlaybackSoundRate;
property PlaybackSoundSize: Boolean read FPlaybackSoundSize write FPlaybackSoundSize;
property PlaybackSoundType: Boolean read FPlaybackSoundType write FPlaybackSoundType;
property StreamSoundCompression: Byte read FStreamSoundCompression write FStreamSoundCompression;
property StreamSoundRate: Byte read FStreamSoundRate write FStreamSoundRate;
property StreamSoundSampleCount: Word read FStreamSoundSampleCount write FStreamSoundSampleCount;
property StreamSoundSize: Boolean read FStreamSoundSize write FStreamSoundSize;
property StreamSoundType: Boolean read FStreamSoundType write FStreamSoundType;
end;
TSWFSoundStreamHead2 = class (TSWFSoundStreamHead)
public
constructor Create; override;
function MinVersion: Byte; override;
end;
TSWFSoundStreamBlock = class (TSWFDataObject)
private
FSampleCount: Word;
FSeekSamples: SmallInt;
FStreamSoundCompression: Byte;
public
constructor Create; override;
procedure Assign(Source: TBasedSWFObject); override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property SampleCount: Word read FSampleCount write FSampleCount;
property SeekSamples: SmallInt read FSeekSamples write FSeekSamples;
property StreamSoundCompression: Byte read FStreamSoundCompression write FStreamSoundCompression;
end;
// ==========================================================//
// Buttons //
// ==========================================================//
TSWFButtonRecord = class (TObject)
private
FBlendMode: TSWFBlendMode;
FButtonHasBlendMode: Boolean;
FButtonHasFilterList: Boolean;
FButtonState: TSWFButtonStates;
FCharacterID: Word;
FColorTransform: TSWFColorTransform;
FDepth: Word;
FhasColorTransform: Boolean;
FMatrix: TSWFMatrix;
FFilterList: TSWFFilterList;
function GetColorTransform: TSWFColorTransform;
function GetMatrix: TSWFMatrix;
function GetFilterList: TSWFFilterList;
public
constructor Create(ChID: word);
destructor Destroy; override;
procedure Assign(Source: TSWFButtonRecord);
procedure WriteToStream(be: TBitsEngine);
property BlendMode: TSWFBlendMode read FBlendMode write FBlendMode;
property ButtonHasBlendMode: Boolean read FButtonHasBlendMode write
FButtonHasBlendMode;
property ButtonHasFilterList: Boolean read FButtonHasFilterList write
FButtonHasFilterList;
property ButtonState: TSWFButtonStates read FButtonState write FButtonState;
property CharacterID: Word read FCharacterID write FCharacterID;
property ColorTransform: TSWFColorTransform read GetColorTransform;
property Depth: Word read FDepth write FDepth;
property hasColorTransform: Boolean read FhasColorTransform write FhasColorTransform;
property Matrix: TSWFMatrix read GetMatrix;
property FilterList: TSWFFilterList read GetFilterList;
end;
TSWFBasedButton = class (TSWFObject)
private
FActions: TSWFActionList;
FButtonId: Word;
FButtonRecords: TObjectList;
FParseActions: Boolean;
function GetButtonRecord(index: integer): TSWFButtonRecord;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
property Actions: TSWFActionList read FActions;
property ButtonId: Word read FButtonId write FButtonId;
property ButtonRecord[index: integer]: TSWFButtonRecord read GetButtonRecord;
property ButtonRecords: TObjectList read FButtonRecords;
property ParseActions: Boolean read FParseActions write FParseActions;
end;
TSWFDefineButton = class (TSWFBasedButton)
private
function GetAction(Index: Integer): TSWFAction;
public
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property Action[Index: Integer]: TSWFAction read GetAction;
end;
TSWFButtonCondAction = class (TSWFActionList)
private
FActionConditions: TSWFStateTransitions;
FID_Key: Byte;
public
procedure Assign(Source: TSWFButtonCondAction);
function Actions: TSWFActionList;
procedure WriteToStream(be: TBitsEngine; isEnd:boolean);
property ActionConditions: TSWFStateTransitions read FActionConditions write FActionConditions;
property ID_Key: Byte read FID_Key write FID_Key;
end;
TSWFDefineButton2 = class (TSWFBasedButton)
private
FTrackAsMenu: Boolean;
function GetCondAction(Index: Integer): TSWFButtonCondAction;
public
constructor Create; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property CondAction[Index: Integer]: TSWFButtonCondAction read GetCondAction;
property TrackAsMenu: Boolean read FTrackAsMenu write FTrackAsMenu;
end;
TSWFDefineButtonSound = class (TSWFObject)
private
FButtonId: Word;
FHasIdleToOverUp: Boolean;
FHasOverDownToOverUp: Boolean;
FHasOverUpToIdle: Boolean;
FHasOverUpToOverDown: Boolean;
FSndIdleToOverUp: TSWFStartSound;
FSndOverDownToOverUp: TSWFStartSound;
FSndOverUpToIdle: TSWFStartSound;
FSndOverUpToOverDown: TSWFStartSound;
function GetSndIdleToOverUp: TSWFStartSound;
function GetSndOverDownToOverUp: TSWFStartSound;
function GetSndOverUpToIdle: TSWFStartSound;
function GetSndOverUpToOverDown: TSWFStartSound;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property ButtonId: Word read FButtonId write FButtonId;
property HasIdleToOverUp: Boolean read FHasIdleToOverUp write FHasIdleToOverUp;
property HasOverDownToOverUp: Boolean read FHasOverDownToOverUp write FHasOverDownToOverUp;
property HasOverUpToIdle: Boolean read FHasOverUpToIdle write FHasOverUpToIdle;
property HasOverUpToOverDown: Boolean read FHasOverUpToOverDown write FHasOverUpToOverDown;
property SndIdleToOverUp: TSWFStartSound read GetSndIdleToOverUp;
property SndOverDownToOverUp: TSWFStartSound read GetSndOverDownToOverUp;
property SndOverUpToIdle: TSWFStartSound read GetSndOverUpToIdle;
property SndOverUpToOverDown: TSWFStartSound read GetSndOverUpToOverDown;
end;
TSWFDefineButtonCxform = class (TSWFObject)
private
FButtonColorTransform: TSWFColorTransform;
FButtonId: Word;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property ButtonColorTransform: TSWFColorTransform read FButtonColorTransform;
property ButtonId: Word read FButtonId write FButtonId;
end;
// ==========================================================//
// SPRITE //
// ==========================================================//
TSWFDefineSprite = class (TSWFObject)
private
FControlTags: TObjectList;
FFrameCount: Word;
FParseActions: Boolean;
FSpriteID: Word;
FSWFVersion: Byte;
function GetControlTag(Index: Integer): TSWFObject;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property ControlTag[Index: Integer]: TSWFObject read GetControlTag;
property ControlTags: TObjectList read FControlTags;
property FrameCount: Word read FFrameCount write FFrameCount;
property ParseActions: Boolean read FParseActions write FParseActions;
property SpriteID: Word read FSpriteID write FSpriteID;
property SWFVersion: Byte read FSWFVersion write FSWFVersion;
end;
TSWFDefineSceneAndFrameLabelData = class (TSWFObject)
private
FScenes: TStringList;
FFrameLabels: TStringList;
public
constructor Create;
destructor Destroy; override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property FrameLabels: TStringList read FFrameLabels;
property Scenes: TStringList read FScenes;
end;
// ==========================================================//
// Video //
// ==========================================================//
TSWFDefineVideoStream = class (TSWFObject)
private
FCharacterID: Word;
FCodecID: Byte;
FHeight: Word;
FNumFrames: Word;
FVideoFlagsDeblocking: Byte;
FVideoFlagsSmoothing: Boolean;
FWidth: Word;
public
constructor Create;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property CharacterID: Word read FCharacterID write FCharacterID;
property CodecID: Byte read FCodecID write FCodecID;
property Height: Word read FHeight write FHeight;
property NumFrames: Word read FNumFrames write FNumFrames;
property VideoFlagsDeblocking: Byte read FVideoFlagsDeblocking write FVideoFlagsDeblocking;
property VideoFlagsSmoothing: Boolean read FVideoFlagsSmoothing write FVideoFlagsSmoothing;
property Width: Word read FWidth write FWidth;
end;
TSWFVideoFrame = class (TSWFDataObject)
private
FFrameNum: Word;
FStreamID: Word;
public
constructor Create; override;
procedure Assign(Source: TBasedSWFObject); override;
function MinVersion: Byte; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
property FrameNum: Word read FFrameNum write FFrameNum;
property StreamID: Word read FStreamID write FStreamID;
end;
// ================== undocumented tags ====================================
TSWFByteCodeTag = class (TSWFDataObject)
private
FTagIDFrom: Word;
FText: string;
function GetByteCode(Index: word): Byte;
public
constructor Create; override;
procedure ReadFromStream(be: TBitsEngine); override;
procedure WriteTagBody(be: TBitsEngine); override;
procedure WriteToStream(be: TBitsEngine); override;
property ByteCode[Index: word]: Byte read GetByteCode;
property TagIDFrom: Word read FTagIDFrom write FTagIDFrom;
property Text: string read FText write FText;
end;
// ==================== tools ==============================
Function GenerateSWFObject(ID: word): TSWFObject;
Function GenerateSWFAction(ID: word): TSWFAction;
procedure CopyActionList(Source, Dest: TSWFActionList);
Procedure WriteCustomData(Dest: TStream; TagID: byte; data: pointer; Size: longint); overload;
Procedure WriteCustomData(Dest: TStream; TagID: byte; data: TStream; Size: longint = 0); overload;
procedure CopyShapeRecords(Source, Dest: TObjectList);
const
noSupport = false;
implementation
Uses SWFMD5, Math, TypInfo;
var tmpMemStream: TMemoryStream;
nGlyphs: word;
{$IFDEF DebugAS3}
SLDebug: TStringList;
procedure AddDebugAS3(s: string);
begin
if SLDebug = nil then SLDebug := TStringList.Create;
SLDebug.Add(s);
end;
{$ENDIF}
{
********************************************************* TSWFRect **********************************************************
}
procedure TSWFRect.Assign(Source: TSWFRect);
begin
Rec := Source.Rec;
end;
procedure TSWFRect.CompareXY(flag: byte);
var
tmp: LongInt;
begin
if ((flag and 1) = 1) and (FXmin > FXMax) then
begin
tmp := FXMax;
FXMax := FXmin;
FXmin := tmp;
end;
if ((flag and 2) = 2) and (FYmin > FYMax) then
begin
tmp := FYMax;
FYMax := FYmin;
FYmin := tmp;
end;
end;
function TSWFRect.GetHeight: Integer;
begin
result := YMax - YMin;
end;
function TSWFRect.GetRec: recRect;
begin
Result.XMin := XMin;
Result.YMin := YMin;
Result.XMax := XMax;
Result.YMax := YMax
end;
function TSWFRect.GetRect: TRect;
begin
Result.Left := Xmin;
Result.Top := YMin;
Result.Right := XMax;
Result.Bottom := YMax;
end;
function TSWFRect.GetWidth: Integer;
begin
result := XMax - XMin;
end;
procedure TSWFRect.SetRec(Value: recRect);
begin
FXMin := Value.XMin;
FYMin := Value.YMin;
FXMax := Value.XMax;
FYMax := Value.YMax;
CompareXY(3);
end;
procedure TSWFRect.SetRect(Value: TRect);
begin
FXMin := Value.Left;
FYMin := Value.Top;
FXMax := Value.Right;
FYMax := Value.Bottom;
CompareXY(3);
end;
procedure TSWFRect.SetXmax(Value: LongInt);
begin
FXmax := Value;
CompareXY(1);
end;
procedure TSWFRect.SetXmin(Value: LongInt);
begin
FXmin := Value;
CompareXY(1);
end;
procedure TSWFRect.SetYmax(Value: LongInt);
begin
FYmax := Value;
CompareXY(2);
end;
procedure TSWFRect.SetYmin(Value: LongInt);
begin
FYmin := Value;
CompareXY(2);
end;
{
********************************************************** TSWFRGB **********************************************************
}
procedure TSWFRGB.Assign(Source: TObject);
begin
RGB := TSWFRGB(Source).RGB;
end;
function TSWFRGB.GetRGB: recRGB;
begin
Result := SWFRGB(R, G, B);
end;
procedure TSWFRGB.SetRGB(Value: recRGB);
begin
R := value.R;
G := value.G;
B := value.B;
end;
{
********************************************************* TSWFRGBA **********************************************************
}
constructor TSWFRGBA.Create(a: boolean = false);
begin
hasAlpha := a;
end;
procedure TSWFRGBA.Assign(Source: TObject);
begin
if Source is TSWFRGBA then RGBA := TSWFRGBA(Source).RGBA
else RGB := TSWFRGB(Source).RGB;
end;
function TSWFRGBA.GetRGBA: recRGBA;
begin
Result := SWFRGBA(R, G, B, A);
end;
procedure TSWFRGBA.SetA(Value: Byte);
begin
FA := Value;
if Value < 255 then FHasAlpha := true;
end;
procedure TSWFRGBA.SetHasAlpha(Value: Boolean);
begin
FhasAlpha := Value;
if not Value then FA := 255;
end;
procedure TSWFRGBA.SetRGB(value: recRGB);
begin
inherited SetRGB(Value);
A := 255;
end;
procedure TSWFRGBA.SetRGBA(Value: recRGBA);
begin
R := value.R;
G := value.G;
B := value.B;
A := value.A;
end;
{
**************************************************** TSWFColorTransform *****************************************************
}
procedure TSWFColorTransform.Assign(Source: TSWFColorTransform);
begin
Rec := Source.Rec;
end;
procedure TSWFColorTransform.AddTint(Color: TColor);
begin
multR := 0;
multG := 0;
multB := 0;
multA := 255;
addR := GetRValue(Color);
addG := GetGValue(Color);
addB := GetBValue(Color);
addA := 0;
end;
function TSWFColorTransform.CheckAddValue(value: integer): integer;
begin
if value < -255 then Result := -255 else
if value > 255 then Result := 255 else Result := value;
end;
function TSWFColorTransform.CheckMultValue(value: integer): integer;
begin
if value < 0 then Result := 0 else
if value > 256 then Result := 256 else Result := value;
end;
function TSWFColorTransform.GetREC: recColorTransform;
begin
Result.hasAlpha := hasAlpha;
if hasAdd then
begin
Result.hasADD := true;
Result.addR := addR;
Result.addG := addG;
Result.addB := addB;
if hasAlpha then Result.addA := addA;
end else Result.hasAdd := false;
if hasMULT then
begin
Result.hasMULT := true;
Result.multR := multR;
Result.multG := multG;
Result.multB := multB;
if hasAlpha then Result.multA := multA;
end else Result.hasMULT := false;
end;
procedure TSWFColorTransform.SetAdd(R, G, B, A: integer);
begin
addR := R;
addG := G;
addB := B;
addA := A;
end;
procedure TSWFColorTransform.SetaddA(Value: Integer);
begin
hasAdd := true;
hasAlpha := true;
FaddA := CheckAddValue(Value);
end;
procedure TSWFColorTransform.SetaddB(Value: Integer);
begin
hasAdd := true;
FaddB := CheckAddValue(Value);
end;
procedure TSWFColorTransform.SetaddG(Value: Integer);
begin
hasAdd := true;
FaddG := CheckAddValue(Value);
end;
procedure TSWFColorTransform.SetaddR(Value: Integer);
begin
hasAdd := true;
FaddR := CheckAddValue(Value);
end;
procedure TSWFColorTransform.SetMult(R, G, B, A: integer);
begin
multR := R;
multG := G;
multB := B;
multA := A;
end;
procedure TSWFColorTransform.SetmultA(Value: Integer);
begin
hasMult := true;
hasAlpha := true;
FmultA := CheckMultValue(Value);
end;
procedure TSWFColorTransform.SetmultB(Value: Integer);
begin
hasMult := true;
FmultB := CheckMultValue(Value);
end;
procedure TSWFColorTransform.SetmultG(Value: Integer);
begin
hasMult := true;
FmultG := CheckMultValue(Value);
end;
procedure TSWFColorTransform.SetmultR(Value: Integer);
begin
hasMult := true;
FmultR := CheckMultValue(Value);
end;
procedure TSWFColorTransform.SetREC(Value: recColorTransform);
begin
hasAlpha := Value.hasAlpha;
if Value.hasAdd then
begin
addR := value.addR;
addG := value.addG;
addB := value.addB;
if value.hasAlpha then addA := value.addA;
end else hasAdd := false;
if Value.hasMULT then
begin
multR := value.multR;
multG := value.multG;
multB := value.multB;
if value.hasAlpha then multA := value.multA;
end else hasMULT := false;
end;
{
******************************************************** TSWFMatrix *********************************************************
}
procedure TSWFMatrix.Assign(M : TSWFMatrix);
begin
FHasScale := M.FHasScale;
FHasSkew := M.FHasSkew;
FScaleX := M.FScaleX;
FScaleY := M.FScaleY;
FSkewX := M.FSkewX;
FSkewY := M.FSkewY;
FTranslateX := M.FTranslateX;
FTranslateY := M.FTranslateY;
end;
function TSWFMatrix.GetREC: recMatrix;
begin
Result := MakeMatrix(hasScale, hasSkew,
FScaleX, FScaleY, FSkewX, FSkewY, TranslateX, TranslateY);
end;
function TSWFMatrix.GetScaleX: Single;
begin
Result := IntToSingle(FScaleX);
end;
function TSWFMatrix.GetScaleY: Single;
begin
Result := IntToSingle(FScaleY);
end;
function TSWFMatrix.GetSkewX: Single;
begin
Result := IntToSingle(FSkewX);
end;
function TSWFMatrix.GetSkewY: Single;
begin
Result := IntToSingle(FSkewY);
end;
procedure TSWFMatrix.SetREC(Value: recMatrix);
begin
FScaleX := Value.ScaleX;
FScaleY := Value.ScaleY;
FSkewX := Value.SkewX;
FSkewY := Value.SkewY;
TranslateX := Value.TranslateX;
TranslateY := Value.TranslateY;
hasScale := Value.hasScale;
hasSkew := Value.hasSkew;
end;
procedure TSWFMatrix.SetRotate(angle: single);
var
R, oldSx, oldSy, oldSkX, oldSkY: Double;
begin
if HasSkew then
begin
oldSkX := SkewX;
oldSkY := SkewY;
end else
begin
oldSkX := 0;
oldSkY := 0;
end;
if HasScale then
begin
oldSx := ScaleX;
oldSy := ScaleY;
end else
begin
oldSx := 1;
oldSy := 1;
end;
R := DegToRad(angle);
ScaleX := oldSx * cos(r) + oldSky * sin(r);
ScaleY := oldSy * cos(r) - oldSkx * sin(r);
SkewX := oldSy * sin(r) + oldSkX * cos(r);
SkewY := - oldSx * sin(r) + oldSkY * cos(r);
end;
procedure TSWFMatrix.SetScale(ScaleX, ScaleY: single);
begin
self.ScaleX := ScaleX;
self.ScaleY := ScaleY;
end;
procedure TSWFMatrix.SetScaleX(Value: Single);
begin
FScaleX := SingleToInt(value);
HasScale := true;
end;
procedure TSWFMatrix.SetScaleY(Value: Single);
begin
FScaleY := SingleToInt(value);
HasScale := true;
end;
procedure TSWFMatrix.SetSkew(SkewX, SkewY: single);
begin
self.SkewX := SkewX;
self.SkewY := SkewY;
end;
procedure TSWFMatrix.SetSkewX(Value: Single);
begin
FSkewX := SingleToInt(value);
HasSkew := true;
end;
procedure TSWFMatrix.SetSkewY(Value: Single);
begin
FSkewY := SingleToInt(value);
HasSkew := true;
end;
procedure TSWFMatrix.SetTranslate(X, Y: LongInt);
begin
TranslateX := X;
TranslateY := Y;
end;
{
****************************************************** TXMLReadWriteSettings ******************************************************
}
{
****************************************************** TBasedSWFObject ******************************************************
}
function TBasedSWFObject.MinVersion: Byte;
begin
Result := SWFVer1;
end;
{
******************************************************** TSWFObject *********************************************************
}
procedure TSWFObject.Assign(Source: TBasedSWFObject);
begin
BodySize := TSWFObject(Source).BodySize;
end;
function TSWFObject.GetFullSize: LongInt;
begin
Result := BodySize + 2 + Byte(BodySize >= $3f) * 4;
end;
function TSWFObject.LibraryLevel: Byte;
begin
Result := SWFLevel;
end;
procedure TSWFObject.ReadFromStream(be: TBitsEngine);
begin
end;
procedure TSWFObject.WriteTagBody(be: TBitsEngine);
begin
// no code for empty tags
end;
procedure TSWFObject.WriteToStream(be: TBitsEngine);
var
tmpMem: tMemoryStream;
tmpBE: TBitsEngine;
tmpW: Word;
isLong: Boolean;
begin
if TagID in [tagEnd, tagShowFrame] {no body} then be.WriteWord(TagID shl 6)
else
begin
tmpMem := TMemoryStream.Create;
tmpBE := TBitsEngine.Create(tmpMem);
WriteTagBody(tmpBE);
BodySize := tmpMem.Size;
isLong := (BodySize >= $3f) or
(TagId in [tagDefineBitsLossless, tagDefineBitsLossless2,
tagDefineVideoStream, tagSoundStreamBlock]);
if isLong
then tmpW := TagID shl 6 + $3f
else tmpW := TagID shl 6 + BodySize;
be.BitsStream.Write(tmpW, 2);
if isLong then be.WriteDWord(BodySize);
if BodySize > 0 then
begin
tmpMem.Position := 0;
be.BitsStream.CopyFrom(tmpMem, BodySize);
end;
tmpBE.Free;
tmpMem.Free;
end;
end;
{
******************************************************* TSWFErrorTag ********************************************************
}
//constructor TSWFErrorTag.Create;
//begin
// TagId := tagErrorTag;
//end;
procedure CopyShapeRecords(Source, Dest: TObjectList);
var
il: longint;
ER: TSWFShapeRecord;
SCR: TSWFStyleChangeRecord;
LER: TSWFStraightEdgeRecord;
CER: TSWFCurvedEdgeRecord;
begin
if Source.Count = 0 then Dest.Clear else
for il := 0 to Source.Count - 1 do
begin
ER := TSWFShapeRecord(Source[il]);
Case ER.ShapeRecType of
EndShapeRecord: Dest.Add(TSWFEndShapeRecord.Create);
StyleChangeRecord:
begin
SCR := TSWFStyleChangeRecord.Create;
SCR.Assign(ER);
Dest.Add(SCR);
end;
StraightEdgeRecord:
begin
LER := TSWFStraightEdgeRecord.Create;
LER.Assign(ER);
Dest.Add(LER);
end;
CurvedEdgeRecord:
begin
CER := TSWFCurvedEdgeRecord.Create;
CER.Assign(ER);
Dest.Add(CER);
end;
end;
end;
end;
Procedure ReadShapeRecord(be: TBitsEngine; Edges: TObjectList; nBitsFill, nBitsLine: byte; owner: TSWFDefineShape);
var
FlagRead, isVis, isLine, Flag1: boolean;
SCR: TSWFStyleChangeRecord;
LER: TSWFStraightEdgeRecord;
CER: TSWFCurvedEdgeRecord;
bCoord, b: byte;
il, StyleCount: integer;
LS: TSWFLineStyle;
FS: TSWFFillStyle;
begin
FlagRead := true;
While FlagRead do
begin
isVis := Boolean(be.GetBits(1));
if isVis then
begin
isLine := Boolean(be.GetBits(1));
if isLine then
begin
LER := TSWFStraightEdgeRecord.Create;
bCoord := be.GetBits(4) + 2;
Flag1 := Boolean(be.GetBits(1));
if Flag1 then
begin
LER.X := be.GetSBits(bCoord);
LER.Y := be.GetSBits(bCoord);
end else
begin
Flag1 := Boolean(be.GetBits(1));
if Flag1 then LER.Y := be.GetSBits(bCoord)
else LER.X := be.GetSBits(bCoord);
end;
Edges.Add(LER);
end else
begin
CER := TSWFCurvedEdgeRecord.Create;
bCoord := be.GetBits(4) + 2;
CER.ControlX := be.GetSBits(bCoord);
CER.ControlY := be.GetSBits(bCoord);
CER.AnchorX := be.GetSBits(bCoord);
CER.AnchorY := be.GetSBits(bCoord);
Edges.Add(CER);
end;
end else
begin
b := be.GetBits(5);
if b = 0 then
begin
FlagRead := false;
Edges.Add(TSWFEndShapeRecord.Create);
end else
begin
SCR := TSWFStyleChangeRecord.Create;
SCR.StateNewStyles := CheckBit(b, 5);
SCR.stateLineStyle := CheckBit(b, 4);
SCR.stateFillStyle1 := CheckBit(b, 3);
SCR.stateFillStyle0 := CheckBit(b, 2);
SCR.stateMoveTo := CheckBit(b, 1);
if SCR.stateMoveTo then
begin
bCoord := be.GetBits(5);
SCR.X := be.GetSBits(bcoord);
SCR.Y := be.GetSBits(bcoord);
end;
if SCR.stateFillStyle0 then
SCR.Fill0Id := be.GetBits(nBitsFill);
if SCR.stateFillStyle1 then
SCR.Fill1Id := be.GetBits(nBitsFill);
if SCR.stateLineStyle then
SCR.LineId := be.GetBits(nbitsLine);
if SCR.StateNewStyles then
begin
be.FlushLastByte(false);
b := be.ReadByte;
if b = $FF then StyleCount := be.ReadWord else StyleCount := b;
if StyleCount > 0 then
for il := 1 to StyleCount do
begin
b := be.ReadByte;
case b of
SWFFillSolid:
FS := TSWFColorFill.Create;
SWFFillLinearGradient, SWFFillRadialGradient:
FS := TSWFGradientFill.Create;
SWFFillFocalGradient:
FS := TSWFFocalGradientFill.Create;
SWFFillTileBitmap, SWFFillClipBitmap,
SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap:
FS := TSWFImageFill.Create;
else FS := nil;
end;
FS.SWFFillType := B;
if owner = nil
then FS.hasAlpha := true
else FS.hasAlpha := owner.hasAlpha;
FS.ReadFromStream(be);
SCR.NewFillStyles.Add(FS);
end;
b := be.ReadByte;
if b = $FF then StyleCount := be.ReadWord else StyleCount := b;
if StyleCount > 0 then
for il := 1 to StyleCount do
begin
if (owner <> nil) and (owner.TagID = tagDefineShape4)
then LS := TSWFLineStyle2.Create
else LS := TSWFLineStyle.Create;
if owner = nil
then LS.Color.hasAlpha := true
else LS.Color.hasAlpha := owner.hasAlpha;
LS.ReadFromStream(be);
SCR.NewLineStyles.Add(LS);
end;
be.FlushLastByte(false); // need ??
b := be.ReadByte;
nBitsFill := b shr 4;
nBitsLine := b and $F;
end;
Edges.Add(SCR);
end;
end;
end;
be.FlushLastByte(false);
end;
Procedure ReadActionList(BE: TBitsEngine; AL: TSWFActionList; ActionsSize: longint);
var
il: Word;
AC: Byte;
A: TSWFAction;
StartPos: LongInt;
Marker: TSWFOffsetMarker;
nLabel: word;
Procedure FindPosition(SizeOffset: longint);
var ipos: word;
SeekOffset: longint;
begin
ipos := il;
SeekOffset := SizeOffset;
Marker.ManualSet := false;
if SeekOffset < 0 then inc(iPos);
While SeekOffset <> 0 do
begin
if SeekOffset > 0 then
begin
inc(ipos);
if TSWFAction(AL[ipos]).ActionCode < $FF then
Dec(SeekOffset, TSWFAction(AL[ipos]).GetFullSize);
if SeekOffset < 0 then
begin
Marker.MarkerName := 'Error Size offset: ' + IntToStr(SizeOffset);
Marker.isUsing := false;
Break;
end;
end else
begin
if (ipos = 0) and (SeekOffset < 0) then
begin
Marker.MarkerName := 'Error Size offset: ' + IntToStr(SizeOffset);
Marker.isUsing := false;
Break;
end else
begin
Dec(iPos);
if TSWFAction(AL[ipos]).ActionCode < $FF then
Inc(SeekOffset, TSWFAction(AL[ipos]).GetFullSize);
if SeekOffset > 0 then
begin
Marker.MarkerName := 'Error Size offset: ' + IntToStr(SizeOffset);
Marker.isUsing := false;
Break;
end;
end;
end;
if SeekOffset = 0 then
begin
if Marker.MarkerName = '' then
begin
inc(nLabel);
Marker.MarkerName := 'label ' + IntToStr(nLabel);
end;
Marker.isUsing := true;
if iPos > il then inc(ipos);
if iPos = AL.Count then AL.Add(Marker) else
AL.Insert(iPos, Marker);
Break;
end;
end;
end;
begin
StartPos := be.BitsStream.Position;
nLabel := 0;
Repeat
AC := be.ReadByte;
if AC > 0 then
begin
A := GenerateSWFAction(AC);
if A<>nil then
begin
if AC >= $80 then
begin
A.BodySize := be.ReadWord;
A.ReadFromStream(be);
end;
end else
begin
A := TSWFActionByteCode.Create;
with TSWFActionByteCode(A) do
begin
if AC >= $80 then
begin
BodySize := be.ReadWord + 1;
SetSize(BodySize);
be.BitsStream.Seek(-3, 1{soCurrent});
ReadFromStream(be);
end else
begin
SetSize(1);
ByteCode[0]:=AC;
end;
end;
A.ReadFromStream(be);
end;
AL.Add(A);
end;
Until (AC = 0) or (be.BitsStream.Position >= (StartPos + ActionsSize));
il := 0;
while il < AL.Count do
if AL[il].ActionCode in [actionJump, actionIf, actionDefineFunction,
actionWith, ActionDefineFunction2, actionTry] then
begin
Case AL[il].ActionCode of
actionJump,
actionIf: With TSWFactionJump(AL[il]) do
begin
BranchOffsetMarker.JumpToBack := BranchOffset < 0;
Marker := BranchOffsetMarker;
FindPosition(BranchOffset);
end;
actionDefineFunction: With TSWFactionDefineFunction(AL[il]) do
begin
CodeSizeMarker.JumpToBack := false;
Marker := CodeSizeMarker;
FindPosition(CodeSize);
end;
actionWith: with TSWFactionWith(AL[il]) do
begin
SizeMarker.JumpToBack := false;
Marker := SizeMarker;
FindPosition(Size);
end;
actionDefineFunction2: With TSWFactionDefineFunction2(AL[il]) do
begin
CodeSizeMarker.JumpToBack := false;
Marker := CodeSizeMarker;
FindPosition(CodeSize);
end;
actionTry: With TSWFactionTry(AL[il]) do
begin
inc(nLabel);
TrySizeMarker.JumpToBack := false;
Marker := TrySizeMarker;
Marker.MarkerName := 'Try ' + IntToStr(nLabel);
FindPosition(TrySize);
if CatchBlockFlag then
begin
CatchSizeMarker.JumpToBack := false;
Marker := CatchSizeMarker;
Marker.MarkerName := 'Catch ' + IntToStr(nLabel);
FindPosition(CatchSize + TrySize);
end;
if FinallyBlockFlag then
begin
FinallySizeMarker.JumpToBack := false;
Marker := FinallySizeMarker;
Marker.MarkerName := 'Finally ' + IntToStr(nLabel);
FindPosition(FinallySize + TrySize + Byte(CatchBlockFlag) * CatchSize);
end;
end;
end;
if Marker.JumpToBack then inc(il, 2) else inc(il);
end else inc(il);
(* deleting empty jump
il := 0;
while il < AL.Count do
if AL[il].ActionCode = actionJump then
begin
if TSWFactionJump(AL[il]).BranchOffset = 0 then AL.Delete(il) else inc(il);
end else inc(il); *)
end;
procedure CopyActionList(Source, Dest: TSWFActionList);
var ASrc, ADest: TSWFAction;
il, ind: word;
begin
if Source.Count > 0 then
begin
for il := 0 to Source.Count - 1 do
begin
ASrc := Source[il];
ADest := GenerateSWFAction(ASrc.ActionCode);
Dest.Add(ADest);
ADest.Assign(ASrc);
end;
for il := 0 to Source.Count - 1 do
begin
ASrc := Source[il];
case ASrc.ActionCode of
actionJump,
actionIf: With TSWFactionJump(ASrc) do
if not StaticOffset then
begin
ind := Source.Indexof(BranchOffsetMarker);
ADest := TSWFAction(Dest[ind]);
TSWFactionJump(Dest[il]).BranchOffsetMarker := TSWFOffsetMarker(ADest);
end;
actionDefineFunction: With TSWFactionDefineFunction(ASrc) do
if not StaticOffset then
begin
ind := Source.Indexof(CodeSizeMarker);
ADest := TSWFAction(Dest[ind]);
TSWFactionDefineFunction(Dest[il]).CodeSizeMarker := TSWFOffsetMarker(ADest);
end;
actionWith: with TSWFactionWith(ASrc) do
if not StaticOffset then
begin
ind := Source.Indexof(SizeMarker);
ADest := TSWFAction(Dest[ind]);
TSWFactionWith(Dest[il]).SizeMarker := TSWFOffsetMarker(ADest);
end;
actionDefineFunction2: With TSWFactionDefineFunction2(ASrc) do
if not StaticOffset then
begin
ind := Source.Indexof(CodeSizeMarker);
ADest := TSWFAction(Dest[ind]);
TSWFactionDefineFunction2(Dest[il]).CodeSizeMarker := TSWFOffsetMarker(ADest);
end;
actionTry: With TSWFactionTry(ASrc) do
if not StaticOffset then
begin
ind := Source.Indexof(TrySizeMarker);
ADest := TSWFAction(Dest[ind]);
TSWFactionTry(Dest[il]).TrySizeMarker := TSWFTryOffsetMarker(ADest);
if CatchBlockFlag then
begin
ind := Source.Indexof(CatchSizeMarker);
ADest := TSWFAction(Dest[ind]);
TSWFactionTry(Dest[il]).CatchSizeMarker := TSWFTryOffsetMarker(ADest);
end;
if FinallyBlockFlag then
begin
ind := Source.Indexof(FinallySizeMarker);
ADest := TSWFAction(Dest[ind]);
TSWFactionTry(Dest[il]).FinallySizeMarker := TSWFTryOffsetMarker(ADest);
end;
end;
end;
end;
end;
end;
function FindEndActions(be: TBitsEngine): longint;
var SPos: longint;
AC: Byte;
ASz: word;
begin
SPos := be.BitsStream.Position;
Result := SPos;
Repeat
AC := be.ReadByte;
if AC > 0 then
begin
if AC >= $80 then
begin
ASz := be.ReadWord;
be.BitsStream.Seek(ASz, soFromCurrent);
end;
end else Result := be.BitsStream.Position;
Until (AC = 0) or (be.BitsStream.Position = be.BitsStream.Size);
be.BitsStream.Position := SPos;
end;
Procedure FreeOffsetMarker(var Marker: TSWFOffsetMarker);
begin
try
if Assigned(Marker) and not Marker.isUsing then FreeAndNil(Marker);
except
end;
end;
Procedure WriteCustomData(Dest: TStream; TagId: byte; data: pointer; Size: longint);
var tmpW: word;
isLong: boolean;
begin
isLong := (Size >= $3f) or (TagId in [tagDefineBitsLossless, tagDefineBitsLossless2, tagDefineVideoStream]);
if isLong
then tmpW := TagID shl 6 + $3f
else tmpW := TagID shl 6 + Size;
Dest.Write(tmpW, 2);
if isLong then Dest.Write(Size, 4);
Dest.Write(data^, Size);
end;
Procedure WriteCustomData(Dest: TStream; TagID: byte; data: TStream; Size: longint = 0);
var tmpW: word;
fSize: longint;
isLong: boolean;
begin
if Size = 0 then fSize := data.Size else fSize := Size;
isLong := (fSize >= $3f) or (TagId in [tagDefineBitsLossless, tagDefineBitsLossless2, tagDefineVideoStream]);
if isLong
then tmpW := TagID shl 6 + $3f
else tmpW := TagID shl 6 + fSize;
Dest.Write(tmpW, 2);
if isLong then Dest.Write(fSize, 4);
Dest.CopyFrom(data, fSize);
end;
// ===========================================================
// Control Tags
// ===========================================================
{
************************************************** TSWFSetBackgroundColor ***************************************************
}
constructor TSWFSetBackgroundColor.Create;
begin
inherited;
TagID := tagSetBackgroundColor;
FColor := TSWFRGB.Create;
end;
destructor TSWFSetBackgroundColor.Destroy;
begin
FColor.Free;
inherited;
end;
procedure TSWFSetBackgroundColor.Assign(Source: TBasedSWFObject);
begin
inherited;
Color.Assign(TSWFSetBackgroundColor(Source).Color);
end;
procedure TSWFSetBackgroundColor.ReadFromStream(be: TBitsEngine);
begin
Color.RGB := be.ReadRGB;
end;
procedure TSWFSetBackgroundColor.WriteTagBody(be: TBitsEngine);
begin
be.WriteColor(Color.RGB);
end;
{
****************************************************** TSWFFrameLabel *******************************************************
}
constructor TSWFFrameLabel.Create;
begin
inherited;
TagID := tagFrameLabel;
end;
constructor TSWFFrameLabel.Create(fl: string);
begin
inherited Create;
TagID := tagFrameLabel;
Name := fl;
end;
procedure TSWFFrameLabel.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFFrameLabel(Source) do
begin
self.Name := Name;
self.isAnchor := isAnchor;
end;
end;
function TSWFFrameLabel.MinVersion: Byte;
begin
if isAnchor then Result := SWFVer6 else Result := SWFVer3;
end;
procedure TSWFFrameLabel.ReadFromStream(be: TBitsEngine);
var
PP: LongInt;
begin
PP := BE.BitsStream.Position;
Name := BE.ReadString;
if (BodySize - (BE.BitsStream.Position - PP)) = 1 then isAnchor := Boolean( be.ReadByte );
end;
procedure TSWFFrameLabel.WriteTagBody(be: TBitsEngine);
begin
be.WriteString(name);
if isAnchor then be.WriteByte(1);
end;
{
******************************************************** TSWFProtect ********************************************************
}
constructor TSWFProtect.Create;
begin
TagID := tagProtect;
end;
procedure TSWFProtect.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFProtect(Source) do
begin
self.Password := Password;
self.Hash := Hash;
end;
end;
function TSWFProtect.MinVersion: Byte;
begin
if (Hash<>'') or (Password<>'') then Result := SWFVer5 else Result := SWFVer2;
end;
procedure TSWFProtect.ReadFromStream(be: TBitsEngine);
begin
if BodySize > 0 then
begin
be.ReadWord;
Hash := be.ReadString(BodySize - 2);
end;
end;
procedure TSWFProtect.WriteTagBody(be: TBitsEngine);
begin
if (Password <> '') or (Hash <> '') then be.WriteWord(0);
if Password <> '' then
Hash := Cript_MD5(Password, '');
if Hash <> '' then be.WriteString(Hash);
end;
{
********************************************************** TSWFEnd **********************************************************
}
constructor TSWFEnd.Create;
begin
TagID := tagEnd;
end;
{
***************************************************** TSWFExportAssets ******************************************************
}
constructor TSWFExportAssets.Create;
begin
TagID := tagExportAssets;
FAssets := TStringList.Create;
end;
destructor TSWFExportAssets.Destroy;
begin
FAssets.Free;
inherited;
end;
procedure TSWFExportAssets.Assign(Source: TBasedSWFObject);
begin
inherited;
Assets.AddStrings(TSWFExportAssets(Source).Assets);
end;
function TSWFExportAssets.GetCharacterId(name: string): Integer;
var
Ind: Integer;
begin
ind := Assets.IndexOf(name);
if ind = -1 then Result := -1
else Result := Longint(Assets.Objects[ind]);
end;
function TSWFExportAssets.MinVersion: Byte;
begin
Result := SWFVer5;
end;
procedure TSWFExportAssets.ReadFromStream(be: TBitsEngine);
var
il, C, Tag: Word;
name: string;
begin
C := be.ReadWord;
if C > 0 then
For il:= 0 to C - 1 do
begin
Tag := be.ReadWord;
name := be.ReadString;
Assets.AddObject(Name, Pointer(LongInt(Tag)));
end;
end;
procedure TSWFExportAssets.SetAsset(Name: string; CharacterId: word);
begin
self.CharacterId[Name] := CharacterId;
end;
procedure TSWFExportAssets.SetCharacterId(name: string; Value: Integer);
var
Ind: Integer;
begin
ind := Assets.IndexOf(name);
if ind = -1 then ind := Assets.Add(name);
Assets.Objects[ind] := Pointer(LongInt(Value));
end;
procedure TSWFExportAssets.WriteTagBody(be: TBitsEngine);
var
il: Word;
begin
be.WriteWord(Assets.Count);
if Assets.Count > 0 then
For il:=0 to Assets.Count-1 do
begin
be.WriteWord(LongInt(Assets.Objects[il]));
be.WriteString(Assets[il]);
end;
end;
{
***************************************************** TSWFImportAssets ******************************************************
}
constructor TSWFImportAssets.Create;
begin
inherited;
TagID := tagImportAssets;
end;
procedure TSWFImportAssets.Assign(Source: TBasedSWFObject);
begin
inherited;
URL := TSWFImportAssets(Source).URL;
end;
procedure TSWFImportAssets.ReadFromStream(be: TBitsEngine);
begin
FURL := be.ReadString;
inherited;
end;
procedure TSWFImportAssets.WriteTagBody(be: TBitsEngine);
begin
be.WriteString(FURL);
inherited;
end;
{
***************************************************** TSWFImportAssets2 ******************************************************
}
constructor TSWFImportAssets2.Create;
begin
inherited;
TagID := tagImportAssets2;
end;
procedure TSWFImportAssets2.ReadFromStream(be: TBitsEngine);
begin
FURL := be.ReadString;
be.ReadWord;
inherited;
end;
procedure TSWFImportAssets2.WriteTagBody(be: TBitsEngine);
begin
be.WriteString(FURL);
be.WriteByte(1);
be.WriteByte(0);
inherited;
end;
{
**************************************************** TSWFEnableDebugger *****************************************************
}
constructor TSWFEnableDebugger.Create;
begin
inherited;
TagID := tagEnableDebugger;
end;
function TSWFEnableDebugger.MinVersion: Byte;
begin
Result := SWFVer5;
end;
{
**************************************************** TSWFEnableDebugger2 ****************************************************
}
constructor TSWFEnableDebugger2.Create;
begin
inherited;
TagID := tagEnableDebugger2;
end;
function TSWFEnableDebugger2.MinVersion: Byte;
begin
Result := SWFVer6;
end;
{
***************************************************** TSWFScriptLimits ******************************************************
}
constructor TSWFScriptLimits.Create;
begin
TagID := tagScriptLimits;
end;
procedure TSWFScriptLimits.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFScriptLimits(Source) do
begin
self.MaxRecursionDepth := MaxRecursionDepth;
self.ScriptTimeoutSeconds := ScriptTimeoutSeconds;
end;
end;
function TSWFScriptLimits.MinVersion: Byte;
begin
result := SWFVer7;
end;
procedure TSWFScriptLimits.ReadFromStream(be: TBitsEngine);
begin
MaxRecursionDepth := be.ReadWord;
ScriptTimeoutSeconds := be.ReadWord;
end;
procedure TSWFScriptLimits.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(MaxRecursionDepth);
be.WriteWord(ScriptTimeoutSeconds);
end;
{
****************************************************** TSWFSetTabIndex ******************************************************
}
constructor TSWFSetTabIndex.Create;
begin
TagID := tagSetTabIndex;
end;
procedure TSWFSetTabIndex.Assign(Source: TBasedSWFObject);
begin
inherited;
with TSWFSetTabIndex(Source) do
begin
self.Depth := Depth;
self.TabIndex := TabIndex
end;
end;
function TSWFSetTabIndex.MinVersion: Byte;
begin
result := SWFVer7;
end;
procedure TSWFSetTabIndex.ReadFromStream(be: TBitsEngine);
begin
Depth := be.ReadWord;
TabIndex := be.ReadWord;
end;
procedure TSWFSetTabIndex.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(Depth);
be.WriteWord(TabIndex);
end;
{
****************************************************** TSWFSymbolClass ****************************************************
}
constructor TSWFSymbolClass.Create;
begin
inherited;
TagID := tagSymbolClass;
end;
function TSWFSymbolClass.MinVersion: Byte;
begin
Result := SWFVer9;
end;
{
****************************************************** TSWFFileAttributes ****************************************************
}
procedure TSWFFileAttributes.Assign(Source: TBasedSWFObject);
begin
inherited;
HasMetadata := TSWFFileAttributes(Source).HasMetadata;
UseNetwork := TSWFFileAttributes(Source).UseNetwork;
end;
constructor TSWFFileAttributes.Create;
begin
TagID := tagFileAttributes;
end;
function TSWFFileAttributes.MinVersion: Byte;
begin
Result := SWFVer8;
end;
procedure TSWFFileAttributes.ReadFromStream(be: TBitsEngine);
var
b: Byte;
begin
b := be.ReadByte;
HasMetadata := CheckBit(b, 4);
ActionScript3 := CheckBit(b, 3);
UseNetwork := CheckBit(b, 1);
be.ReadWord;
be.ReadByte;
end;
procedure TSWFFileAttributes.WriteTagBody(be: TBitsEngine);
var
b: Byte;
begin
b := byte(HasMetadata) shl 3 + byte(ActionScript3) shl 2 + byte(UseNetwork);
be.WriteByte(b);
be.WriteWord(0);
be.WriteByte(0);
end;
{
****************************************************** TSWFMetadata ****************************************************
}
procedure TSWFMetadata.Assign(Source: TBasedSWFObject);
begin
inherited;
Metadata := TSWFMetadata(Source).Metadata;
end;
constructor TSWFMetadata.Create;
begin
TagID := tagMetadata;
end;
function TSWFMetadata.MinVersion: Byte;
begin
Result := SWFVer8;
end;
procedure TSWFMetadata.ReadFromStream(be: TBitsEngine);
begin
Metadata := be.ReadString;
end;
procedure TSWFMetadata.WriteTagBody(be: TBitsEngine);
begin
be.WriteString(Metadata, true, true);
end;
{ TSWFProductInfo }
procedure TSWFProductInfo.Assign(Source: TBasedSWFObject);
begin
inherited;
with TSWFProductInfo(Source) do
begin
self.FMajorBuild := MajorBuild;
self.MinorBuild := MinorBuild;
self.FCompilationDate := CompilationDate;
self.FEdition := Edition;
self.FMinorVersion := MinorVersion;
self.FMajorVersion := MajorVersion;
self.FProductId := ProductId;
end;
end;
constructor TSWFProductInfo.Create;
begin
TagID := tagProductInfo;
end;
function TSWFProductInfo.MinVersion: Byte;
begin
Result := SWFVer9;
end;
procedure TSWFProductInfo.ReadFromStream(be: TBitsEngine);
begin
ProductId := be.ReadDWord;
Edition := be.ReadDWord;
MajorVersion := be.ReadByte;
MinorVersion := be.ReadByte;
MajorBuild := be.ReadDWord;
MinorBuild := be.ReadDWord;
CompilationDate := be.ReadSTDDouble;
end;
procedure TSWFProductInfo.WriteTagBody(be: TBitsEngine);
begin
be.WriteDWord(ProductId);
be.WriteDWord(Edition);
be.WriteByte(MajorVersion);
be.WriteByte(MinorVersion);
be.WriteDWord(MajorBuild);
be.WriteDWord(MinorBuild);
be.WriteStdDouble(CompilationDate);
end;
{
**************************************************** TSWFDefineScalingGrid **************************************************
}
procedure TSWFDefineScalingGrid.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFDefineScalingGrid(Source) do
begin
self.Splitter.Assign(Splitter);
self.CharacterId := CharacterId;
end;
end;
constructor TSWFDefineScalingGrid.Create;
begin
TagID := tagDefineScalingGrid;
FSplitter := TSWFRect.Create;
end;
destructor TSWFDefineScalingGrid.Destroy;
begin
FSplitter.Free;
inherited;
end;
function TSWFDefineScalingGrid.MinVersion: Byte;
begin
Result := SWFVer8;
end;
procedure TSWFDefineScalingGrid.ReadFromStream(be: TBitsEngine);
begin
CharacterId := be.ReadWord;
Splitter.Rect := be.ReadRect;
end;
procedure TSWFDefineScalingGrid.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(CharacterId);
be.WriteRect(Splitter.Rect);
end;
// ===========================================================
// Actions
// ===========================================================
// --------------------------- SWF 3 -------------------------
{
******************************************************** TSWFAction *********************************************************
}
procedure TSWFAction.Assign(Source: TSWFAction);
begin
BodySize := Source.BodySize;
end;
function TSWFAction.GetFullSize: Word;
begin
Result := 1;
if (ActionCode >= $80) then Result := Result + 2 + BodySize;
end;
function TSWFAction.MinVersion: Byte;
begin
Result := SWFVer3;
end;
procedure TSWFAction.ReadFromStream(be: TBitsEngine);
begin
// for non-realized or empty actions
if BodySize > 0 then be.BitsStream.Seek(soFromCurrent, BodySize);
end;
procedure TSWFAction.WriteActionBody(be: TBitsEngine);
begin
end;
procedure TSWFAction.WriteToStream(be: TBitsEngine);
var
tmpMem: tMemoryStream;
tmpBE: TBitsEngine;
begin
if ActionCode in [actionOffsetWork, actionByteCode] then
WriteActionBody(BE)
else
begin
be.WriteByte(ActionCode);
if ActionCode >= $80 then
begin
tmpMem := TMemoryStream.Create;
tmpBE := TBitsEngine.Create(tmpMem);
WriteActionBody(tmpBE);
BodySize := tmpMem.Size;
if BodySize > 0 then
begin
be.WriteWord(BodySize);
tmpMem.Position := 0;
be.BitsStream.CopyFrom(tmpMem, BodySize);
end;
tmpBE.Free;
tmpMem.Free;
end;
end;
end;
{
**************************************************** TSWFActionGotoFrame ****************************************************
}
constructor TSWFActionGotoFrame.Create;
begin
ActionCode := actionGotoFrame;
end;
procedure TSWFActionGotoFrame.Assign(Source: TSWFAction);
begin
inherited;
Frame := TSWFActionGotoFrame(Source).Frame;
end;
procedure TSWFActionGotoFrame.ReadFromStream(be: TBitsEngine);
begin
Frame := be.ReadWord;
end;
procedure TSWFActionGotoFrame.WriteActionBody(be: TBitsEngine);
begin
be.WriteWord(Frame);
end;
{
***************************************************** TSWFActionGetUrl ******************************************************
}
constructor TSWFActionGetUrl.Create;
begin
ActionCode := actionGetUrl;
end;
procedure TSWFActionGetUrl.Assign(Source: TSWFAction);
begin
inherited;
With TSWFActionGetUrl(Source) do
begin
self.URL := URL;
self.Target := Target;
end;
end;
procedure TSWFActionGetUrl.ReadFromStream(be: TBitsEngine);
begin
URL := BE.ReadString;
Target := BE.ReadString;
end;
procedure TSWFActionGetUrl.WriteActionBody(be: TBitsEngine);
begin
BE.WriteString(URL, true, true);
BE.WriteString(Target);
end;
{
**************************************************** TSWFActionNextFrame ****************************************************
}
constructor TSWFActionNextFrame.Create;
begin
ActionCode := actionNextFrame;
end;
{
************************************************** TSWFActionPreviousFrame **************************************************
}
constructor TSWFActionPreviousFrame.Create;
begin
ActionCode := actionPreviousFrame;
end;
{
****************************************************** TSWFActionPlay *******************************************************
}
constructor TSWFActionPlay.Create;
begin
ActionCode := actionPlay;
end;
{
****************************************************** TSWFActionStop *******************************************************
}
constructor TSWFActionStop.Create;
begin
ActionCode := actionStop;
end;
{
************************************************** TSWFActionToggleQuality **************************************************
}
constructor TSWFActionToggleQuality.Create;
begin
ActionCode := actionToggleQuality;
end;
{
*************************************************** TSWFActionStopSounds ****************************************************
}
constructor TSWFActionStopSounds.Create;
begin
ActionCode := actionStopSounds;
end;
{
************************************************** TSWFActionWaitForFrame ***************************************************
}
constructor TSWFActionWaitForFrame.Create;
begin
ActionCode := actionWaitForFrame;
end;
procedure TSWFActionWaitForFrame.Assign(Source: TSWFAction);
begin
inherited;
With TSWFActionWaitForFrame(Source) do
begin
self.Frame := Frame;
self.SkipCount := SkipCount;
end;
end;
procedure TSWFActionWaitForFrame.ReadFromStream(be: TBitsEngine);
begin
Frame := be.ReadWord;
SkipCount := be.ReadByte;
end;
procedure TSWFActionWaitForFrame.WriteActionBody(be: TBitsEngine);
begin
be.WriteWord(Frame);
be.WriteByte(SkipCount);
end;
{
**************************************************** TSWFActionSetTarget ****************************************************
}
constructor TSWFActionSetTarget.Create;
begin
ActionCode := actionSetTarget;
end;
procedure TSWFActionSetTarget.Assign(Source: TSWFAction);
begin
inherited;
TargetName := TSWFActionSetTarget(Source).TargetName;
end;
procedure TSWFActionSetTarget.ReadFromStream(be: TBitsEngine);
begin
TargetName := be.ReadString;
end;
procedure TSWFActionSetTarget.WriteActionBody(be: TBitsEngine);
begin
be.WriteString(TargetName);
end;
{
**************************************************** TSWFActionGoToLabel ****************************************************
}
constructor TSWFActionGoToLabel.Create;
begin
ActionCode := actionGoToLabel;
end;
procedure TSWFActionGoToLabel.Assign(Source: TSWFAction);
begin
inherited;
FrameLabel := TSWFActionGoToLabel(Source).FrameLabel;
end;
procedure TSWFActionGoToLabel.ReadFromStream(be: TBitsEngine);
begin
FrameLabel := be.ReadString;
end;
procedure TSWFActionGoToLabel.WriteActionBody(be: TBitsEngine);
begin
be.WriteString(FrameLabel);
end;
// ------------ SWF 4 -----------
{
******************************************************** TSWFAction4 ********************************************************
}
function TSWFAction4.MinVersion: Byte;
begin
result := SWFVer4;
end;
{
***************************************************** TSWFOffsetMarker ******************************************************
}
constructor TSWFOffsetMarker.Create;
begin
ActionCode := actionOffsetWork;
JumpToBack := true;
SizeOffset := 2;
ManualSet := true;
end;
procedure TSWFOffsetMarker.Assign(Source: TSWFAction);
begin
inherited;
With TSWFOffsetMarker(Source) do
begin
self.isUsing := isUsing;
self.JumpToBack := JumpToBack;
self.MarkerName := MarkerName;
self.SizeOffset := SizeOffset;
self.ManualSet := ManualSet;
end;
end;
procedure TSWFOffsetMarker.WriteActionBody(be: TBitsEngine);
var
TmpP: LongInt;
LW: LongWord;
begin
isUsing := true;
if not ManualSet then Exit;
if JumpToBack then
StartPosition := be.BitsStream.Position
else
begin
TmpP := be.BitsStream.Position;
be.BitsStream.Position := StartPosition;
LW := TmpP - StartPosition - sizeOffset;
case SizeOffset of
4: be.WriteDWord(LW);
2: be.WriteWord(LW);
end;
be.BitsStream.Position := TmpP;
end;
end;
procedure TSWFOffsetMarker.WriteOffset(be: TBitsEngine);
var
LW: LongWord;
begin
if not ManualSet then Exit;
if JumpToBack then
begin
LW := RootStreamPosition - StartPosition + SizeOffset;
case SizeOffset of
4: be.WriteDWord(DWord(- LW));
2: be.WriteWord(Word(-LW));
end;
end else
begin
StartPosition := RootStreamPosition;
LW := 0;
be.BitsStream.Write(LW, sizeOffset);
end;
end;
// -- Stack Operations --
{
****************************************************** TPushValueInfo *******************************************************
}
procedure TPushValueInfo.SetValue(v: Variant);
begin
isValueInit := true;
case VarType(v) of
varString, varOleStr:
begin
if fvUndefined = v then ValueType := vtUndefined else
if fvNull = v then ValueType := vtNull else
ValueType := vtString;
end;
varNull: ValueType := vtNull;
varEmpty: ValueType := vtUndefined;
varDouble, varCurrency, varDate: ValueType := vtDouble;
varSingle: ValueType := vtFloat;
varBoolean: ValueType := vtBoolean;
varSmallInt, varInteger, varByte
{$IFDEF VARIANTS}
, varShortInt, varWord, varLongWord, varInt64
{$ENDIF}
: ValueType := vtInteger;
else isValueInit := false;
end;
if isValueInit then
begin
if ValueType in [vtNull, vtUndefined] then fValue := Copy(v, 10, 9)
else fValue := v;
end;
end;
procedure TPushValueInfo.SetValueType(v: TSWFValueType);
begin
if not (v = vtDefault) then fValueType := V;
end;
{
****************************************************** TSWFActionPush *******************************************************
}
constructor TSWFActionPush.Create;
begin
ActionCode := actionPush;
FValues := TObjectList.Create;
end;
destructor TSWFActionPush.Destroy;
begin
FValues.Free;
inherited;
end;
function TSWFActionPush.AddValue(V: Variant): Integer;
var
PV: TPushValueInfo;
begin
PV := TPushValueInfo.Create;
PV.Value := V;
Result := FValues.Add(PV);
end;
procedure TSWFActionPush.Assign(Source: TSWFAction);
var
il: Word;
begin
inherited;
With TSWFActionPush(Source) do
if ValueCount > 0 then
For il := 0 to ValueCount - 1 do
self.ValueInfo[self.AddValue(Value[il])].ValueType := ValueInfo[il].ValueType;
end;
function TSWFActionPush.GetValue(index: integer): Variant;
begin
Result := TPushValueInfo(FValues[index]).Value;
end;
function TSWFActionPush.GetValueInfo(index: integer): TPushValueInfo;
begin
Result := TPushValueInfo(FValues[index]);
end;
function TSWFActionPush.MinVersion: Byte;
var
il: Integer;
begin
Result := SWFVer4;
if ValueCount > 0 then
for il := 0 to ValueCount - 1 do
if ValueInfo[il].ValueType > vtFloat then
begin
Result := SWFVer5;
Break;
end;
end;
procedure TSWFActionPush.ReadFromStream(be: TBitsEngine);
var
lw: LongWord;
LI: LongInt;
d: Double;
s: Single;
il, il2: Integer;
AB: array [0..7] of byte absolute d;
TmpType: TSWFValueType;
TmpValue: Variant;
begin
il:=0;
(* be.BitsStream.Read(AB, Size);
if AB[0] > 0 then;
*)
While il < BodySize do
begin
TmpType := TSWFValueType(be.readByte);
inc(il);
Case TmpType of
vtString:
begin
TmpValue:= be.readString;
inc(il, length(TmpValue) + 1);
end;
vtFloat:
begin
LW := be.ReadDWord;
Move(LW, S, 4);
TmpValue := S;
inc(il, 4);
end;
vtNull: TmpValue := fvNull;
vtUndefined: TmpValue := fvUndefined;
vtDouble:
begin
for il2 := 4 to 7 do ab[il2] := be.ReadByte;
for il2 := 0 to 3 do ab[il2] := be.ReadByte;
TmpValue := D;
inc(il, 8);
end;
vtInteger:
begin
LI := longint(be.ReadDWord);
TmpValue := LI;
inc(il, 4);
end;
vtRegister, vtBoolean, vtConstant8:
begin
TmpValue := be.ReadByte;
inc(il);
end;
vtConstant16:
begin
TmpValue := be.ReadWord;
inc(il, 2);
end;
end;
ValueInfo[AddValue(TmpValue)].ValueType := TmpType;
end;
end;
procedure TSWFActionPush.SetValue(index: integer; v: Variant);
begin
TPushValueInfo(FValues[index]).Value := V;
end;
function TSWFActionPush.ValueCount: Word;
begin
Result := FValues.Count;
end;
procedure TSWFActionPush.WriteActionBody(be: TBitsEngine);
var
LW: LongWord;
D: Double;
S: Single;
il, il2: Word;
AB: Array [0..7] of byte absolute D;
begin
if ValueCount > 0 then
For il := 0 to ValueCount - 1 do
With ValueInfo[il] do
if isValueInit then
begin
be.WriteByte(byte(ValueType));
case ValueType of
vtString: be.WriteString(Value);
vtFloat: begin
S := Value;
Move(S, LW, 4);
be.Write4Byte(LW);
end;
vtDouble: begin
D := Value;
for il2 := 4 to 7 do be.WriteByte(ab[il2]);
for il2 := 0 to 3 do be.WriteByte(ab[il2]);
end;
vtInteger: be.Write4byte(Value);
vtRegister, vtBoolean, vtConstant8: be.WriteByte(Value);
vtConstant16: be.WriteWord(Value);
end;
end;
end;
{
******************************************************* TSWFActionPop *******************************************************
}
constructor TSWFActionPop.Create;
begin
ActionCode := actionPop;
end;
// -- Arithmetic Operators --
{
******************************************************* TSWFActionAdd *******************************************************
}
constructor TSWFActionAdd.Create;
begin
ActionCode := actionAdd;
end;
{
**************************************************** TSWFActionSubtract *****************************************************
}
constructor TSWFActionSubtract.Create;
begin
ActionCode := actionSubtract;
end;
{
**************************************************** TSWFActionMultiply *****************************************************
}
constructor TSWFActionMultiply.Create;
begin
ActionCode := actionMultiply;
end;
{
***************************************************** TSWFActionDivide ******************************************************
}
constructor TSWFActionDivide.Create;
begin
ActionCode := actionDivide;
end;
// -- Numerical Comparison --
{
***************************************************** TSWFActionEquals ******************************************************
}
constructor TSWFActionEquals.Create;
begin
ActionCode := actionEquals;
end;
{
****************************************************** TSWFActionLess *******************************************************
}
constructor TSWFActionLess.Create;
begin
ActionCode := actionLess;
end;
// -- Logical Operators --
{
******************************************************* TSWFActionAnd *******************************************************
}
constructor TSWFActionAnd.Create;
begin
ActionCode := actionAnd;
end;
{
******************************************************* TSWFActionOr ********************************************************
}
constructor TSWFActionOr.Create;
begin
ActionCode := actionOr;
end;
{
******************************************************* TSWFActionNot *******************************************************
}
constructor TSWFActionNot.Create;
begin
ActionCode := actionNot;
end;
// -- String Manipulation --
{
************************************************** TSWFActionStringEquals ***************************************************
}
constructor TSWFActionStringEquals.Create;
begin
ActionCode := actionStringEquals;
end;
{
************************************************** TSWFActionStringLength ***************************************************
}
constructor TSWFActionStringLength.Create;
begin
ActionCode := actionStringLength;
end;
{
**************************************************** TSWFActionStringAdd ****************************************************
}
constructor TSWFActionStringAdd.Create;
begin
ActionCode := actionStringAdd;
end;
{
************************************************** TSWFActionStringExtract **************************************************
}
constructor TSWFActionStringExtract.Create;
begin
ActionCode := actionStringExtract;
end;
{
*************************************************** TSWFActionStringLess ****************************************************
}
constructor TSWFActionStringLess.Create;
begin
ActionCode := actionStringLess;
end;
{
************************************************* TSWFActionMBStringLength **************************************************
}
constructor TSWFActionMBStringLength.Create;
begin
ActionCode := actionMBStringLength;
end;
{
************************************************* TSWFActionMBStringExtract *************************************************
}
constructor TSWFActionMBStringExtract.Create;
begin
ActionCode := actionMBStringExtract;
end;
// -- Type Conversion --
{
**************************************************** TSWFActionToInteger ****************************************************
}
constructor TSWFActionToInteger.Create;
begin
ActionCode := actionToInteger;
end;
{
*************************************************** TSWFActionCharToAscii ***************************************************
}
constructor TSWFActionCharToAscii.Create;
begin
ActionCode := actionCharToAscii;
end;
{
*************************************************** TSWFActionAsciiToChar ***************************************************
}
constructor TSWFActionAsciiToChar.Create;
begin
ActionCode := actionAsciiToChar;
end;
{
************************************************** TSWFActionMBCharToAscii **************************************************
}
constructor TSWFActionMBCharToAscii.Create;
begin
ActionCode := actionMBCharToAscii;
end;
{
************************************************** TSWFActionMBAsciiToChar **************************************************
}
constructor TSWFActionMBAsciiToChar.Create;
begin
ActionCode := actionMBAsciiToChar;
end;
// -- Control Flow --
{
****************************************************** TSWFActionJump *******************************************************
}
constructor TSWFActionJump.Create;
begin
ActionCode := actionJump;
end;
destructor TSWFActionJump.Destroy;
begin
FreeOffsetMarker(FBranchOffsetMarker);
inherited;
end;
procedure TSWFActionJump.Assign(Source: TSWFAction);
begin
inherited;
With TSWFActionJump(Source) do
begin
self.BranchOffset := BranchOffset;
self.StaticOffset := StaticOffset;
end;
end;
function TSWFActionJump.GetBranchOffsetMarker: TSWFOffsetMarker;
begin
if FBranchOffsetMarker = nil then
FBranchOffsetMarker := TSWFOffsetMarker.Create;
Result := FBranchOffsetMarker;
end;
procedure TSWFActionJump.ReadFromStream(be: TBitsEngine);
begin
BranchOffset := SmallInt(be.ReadWord);
end;
procedure TSWFActionJump.SetBranchOffset(v: SmallInt);
begin
fBranchOffset := V;
StaticOffset := true;
end;
procedure TSWFActionJump.WriteActionBody(be: TBitsEngine);
begin
if StaticOffset or (FBranchOffsetMarker = nil) then be.WriteWord(BranchOffset) else
if FBranchOffsetMarker <> nil then
begin
FBranchOffsetMarker.RootStreamPosition := StartPosition + 3; // Size(2) + Code(1)
FBranchOffsetMarker.WriteOffset(be);
end;
end;
procedure TSWFActionJump.WriteToStream(be: TBitsEngine);
begin
StartPosition := be.BitsStream.Position;
inherited;
end;
{
******************************************************* TSWFActionIf ********************************************************
}
constructor TSWFActionIf.Create;
begin
ActionCode := actionIf;
end;
{
****************************************************** TSWFActionCall *******************************************************
}
constructor TSWFActionCall.Create;
begin
ActionCode := actionCall;
end;
// -- Variables --
{
*************************************************** TSWFActionGetVariable ***************************************************
}
constructor TSWFActionGetVariable.Create;
begin
ActionCode := actionGetVariable;
end;
{
*************************************************** TSWFActionSetVariable ***************************************************
}
constructor TSWFActionSetVariable.Create;
begin
ActionCode := actionSetVariable;
end;
// -- Movie Control --
{
***************************************************** TSWFActionGetURL2 *****************************************************
}
constructor TSWFActionGetURL2.Create;
begin
ActionCode := actionGetURL2;
end;
procedure TSWFActionGetURL2.Assign(Source: TSWFAction);
begin
inherited;
With TSWFActionGetURL2(Source) do
begin
self.LoadTargetFlag := LoadTargetFlag;
self.LoadVariablesFlag := LoadVariablesFlag;
self.SendVarsMethod := SendVarsMethod;
end;
end;
procedure TSWFActionGetURL2.ReadFromStream(be: TBitsEngine);
var
b: Byte;
begin
b := be.ReadByte;
SendVarsMethod := b and 3;
LoadTargetFlag := CheckBit(b, 7);
LoadVariablesFlag:= CheckBit(b, 8);
end;
procedure TSWFActionGetURL2.WriteActionBody(be: TBitsEngine);
begin
be.WriteBit(LoadVariablesFlag);
be.WriteBit(LoadTargetFlag);
be.WriteBits(0, 4);
be.WriteBits(SendVarsMethod, 2);
end;
{
*************************************************** TSWFActionGotoFrame2 ****************************************************
}
constructor TSWFActionGotoFrame2.Create;
begin
ActionCode := actionGotoFrame2;
end;
procedure TSWFActionGotoFrame2.Assign(Source: TSWFAction);
begin
inherited;
With TSWFActionGotoFrame2(Source) do
begin
self.PlayFlag := PlayFlag;
self.SceneBiasFlag := SceneBiasFlag;
if SceneBiasFlag then
self.SceneBias := SceneBias;
end;
end;
procedure TSWFActionGotoFrame2.ReadFromStream(be: TBitsEngine);
var
b: Byte;
begin
b := be.ReadByte;
SceneBiasFlag := CheckBit(b, 2);
PlayFlag := CheckBit(b, 1);
if SceneBiasFlag then SceneBias := be.ReadWord;
end;
procedure TSWFActionGotoFrame2.WriteActionBody(be: TBitsEngine);
begin
be.WriteBits(0, 6);
be.WriteBit(SceneBiasFlag);
be.WriteBit(PlayFlag);
if SceneBiasFlag then be.WriteWord(SceneBias);
end;
{
*************************************************** TSWFActionSetTarget2 ****************************************************
}
constructor TSWFActionSetTarget2.Create;
begin
ActionCode := actionSetTarget2;
end;
{
*************************************************** TSWFActionGetProperty ***************************************************
}
constructor TSWFActionGetProperty.Create;
begin
ActionCode := actionGetProperty;
end;
{
*************************************************** TSWFActionSetProperty ***************************************************
}
constructor TSWFActionSetProperty.Create;
begin
ActionCode := actionSetProperty;
end;
{
*************************************************** TSWFActionCloneSprite ***************************************************
}
constructor TSWFActionCloneSprite.Create;
begin
ActionCode := actionCloneSprite;
end;
{
************************************************** TSWFActionRemoveSprite ***************************************************
}
constructor TSWFActionRemoveSprite.Create;
begin
ActionCode := actionRemoveSprite;
end;
{
**************************************************** TSWFActionStartDrag ****************************************************
}
constructor TSWFActionStartDrag.Create;
begin
ActionCode := actionStartDrag;
end;
{
***************************************************** TSWFActionEndDrag *****************************************************
}
constructor TSWFActionEndDrag.Create;
begin
ActionCode := actionEndDrag;
end;
{
************************************************** TSWFActionWaitForFrame2 **************************************************
}
constructor TSWFActionWaitForFrame2.Create;
begin
ActionCode := actionWaitForFrame2;
end;
// -- Utilities --
{
****************************************************** TSWFActionTrace ******************************************************
}
constructor TSWFActionTrace.Create;
begin
ActionCode := actionTrace;
end;
{
***************************************************** TSWFActionGetTime *****************************************************
}
constructor TSWFActionGetTime.Create;
begin
ActionCode := actionGetTime;
end;
{
************************************************** TSWFActionRandomNumber ***************************************************
}
constructor TSWFActionRandomNumber.Create;
begin
ActionCode := actionRandomNumber;
end;
{
************************************************** TSWFActionRandomNumber ***************************************************
}
constructor TSWFActionFSCommand2.Create;
begin
ActionCode := actionFSCommand2;
end;
// ------------ SWF 5 -----------
// -- ScriptObject Actions --
{
**************************************************** TSWFActionByteCode *****************************************************
}
constructor TSWFActionByteCode.Create;
begin
ActionCode := actionByteCode;
end;
destructor TSWFActionByteCode.Destroy;
begin
if selfdestroy and (DataSize > 0) then FreeMem(Data, DataSize);
inherited ;
end;
procedure TSWFActionByteCode.Assign(Source: TSWFAction);
begin
inherited;
with TSWFActionByteCode(Source) do
if DataSize > 0 then
begin
self.DataSize := DataSize;
GetMem(self.FData, DataSize);
Move(Data^, self.FData^, DataSize);
self.SelfDestroy := true;
end;
end;
procedure TSWFActionByteCode.SetSize(newsize: word);
begin
if (DataSize > 0) and SelfDestroy then FreeMem(Data, DataSize);
DataSize := newsize;
GetMem(FData, DataSize);
SelfDestroy := true;
end;
function TSWFActionByteCode.GetByteCode(Index: word): Byte;
var
P: PByte;
begin
P := Data;
if Index > 0 then inc(p, Index);
Result := P^;
end;
function TSWFActionByteCode.GetStrByteCode: AnsiString;
var
il: Word;
P: pbyte;
s2: string[2];
begin
if DataSize = 0 then Result := '' else
begin
p := Data;
SetLength(Result, DataSize * 2);
for il := 0 to DataSize - 1 do
begin
s2 := IntToHex(P^, 2);
Result[il*2 + 1] := s2[1];
Result[il*2 + 2] := s2[2];
inc(P);
end;
end;
end;
procedure TSWFActionByteCode.SetByteCode(Index: word; Value: Byte);
var
P: PByte;
begin
P := Data;
if Index > 0 then inc(P, Index);
P^ := Value;
end;
procedure TSWFActionByteCode.SetStrByteCode(Value: AnsiString);
var
L, il: Word;
s2: string[2];
P: PByte;
begin
L := Length(Value) div 2;
if (L <> DataSize) and (DataSize > 0) and SelfDestroy then
begin
FreeMem(Data, DataSize);
DataSize := 0;
end;
if L > 0 then
begin
s2 := ' ';
SelfDestroy := true;
if DataSize = 0 then GetMem(fData, L);
DataSize := L;
P := Data;
for il := 0 to DataSize - 1 do
begin
s2[1] := Value[il*2 + 1];
s2[2] := Value[il*2 + 2];
P^ := StrToInt('$'+ s2);
Inc(P);
end;
end;
end;
procedure TSWFActionByteCode.WriteActionBody(be: TBitsEngine);
begin
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
BodySize := DataSize;
end;
{
******************************************************** TSWFAction5 ********************************************************
}
function TSWFAction5.MinVersion: Byte;
begin
Result := SWFVer5;
end;
{
************************************************** TSWFActionCallFunction ***************************************************
}
constructor TSWFActionCallFunction.Create;
begin
ActionCode := actionCallFunction;
end;
{
*************************************************** TSWFActionCallMethod ****************************************************
}
constructor TSWFActionCallMethod.Create;
begin
ActionCode := actionCallMethod;
end;
{
************************************************** TSWFActionConstantPool ***************************************************
}
constructor TSWFActionConstantPool.Create;
begin
ActionCode := actionConstantPool;
FConstantPool := TStringList.Create;
end;
destructor TSWFActionConstantPool.Destroy;
begin
FConstantPool.Free;
inherited Destroy;
end;
procedure TSWFActionConstantPool.Assign(Source: TSWFAction);
begin
inherited;
ConstantPool.AddStrings(TSWFActionConstantPool(Source).ConstantPool);
end;
procedure TSWFActionConstantPool.ReadFromStream(be: TBitsEngine);
var
il: Word;
Count: Word;
PP: LongInt;
begin
PP := BE.BitsStream.Position;
Count := be.ReadWord;
if Count > 0 then
For il := 1 to Count do
ConstantPool.add(be.ReadString);
if (BE.BitsStream.Position - PP) <> BodySize then
BodySize := BE.BitsStream.Position - PP;
end;
procedure TSWFActionConstantPool.WriteActionBody(be: TBitsEngine);
var
il: Word;
begin
be.WriteWord(ConstantPool.Count);
if ConstantPool.Count > 0 then
For il := 0 to ConstantPool.Count - 1 do
be.WriteString(ConstantPool[il]);
end;
{
************************************************* TSWFActionDefineFunction **************************************************
}
constructor TSWFActionDefineFunction.Create;
begin
ActionCode := actionDefineFunction;
FParams := TStringList.Create;
end;
destructor TSWFActionDefineFunction.Destroy;
begin
FreeOffsetMarker(FCodeSizeMarker);
FParams.Free;
end;
procedure TSWFActionDefineFunction.Assign(Source: TSWFAction);
begin
inherited;
With TSWFActionDefineFunction(Source) do
begin
self.StaticOffset := StaticOffset;
self.FunctionName := FunctionName;
self.Params.AddStrings(Params);
if StaticOffset then
self.CodeSize := CodeSize;
//**//
end;
end;
function TSWFActionDefineFunction.GetCodeSizeMarker: TSWFOffsetMarker;
begin
if FCodeSizeMarker = nil then
FCodeSizeMarker := TSWFOffsetMarker.Create;
Result := FCodeSizeMarker;
end;
procedure TSWFActionDefineFunction.ReadFromStream(be: TBitsEngine);
var
Count, il: Word;
begin
FunctionName := be.ReadString;
Count := be.ReadWord;
if Count>0 then
For il:=0 to Count - 1 do
Params.Add(be.ReadString);
CodeSize := be.ReadWord;
end;
procedure TSWFActionDefineFunction.SetCodeSize(v: Word);
begin
fCodeSize := v;
StaticOffset := true;
end;
procedure TSWFActionDefineFunction.WriteActionBody(be: TBitsEngine);
var
il: Integer;
begin
be.WriteString(FunctionName);
be.WriteWord(Params.Count);
if Params.Count>0 then
For il:=0 to Params.Count - 1 do be.WriteString(Params[il]);
if StaticOffset then be.WriteWord(CodeSize) else
if FCodeSizeMarker <> nil then
begin
FCodeSizeMarker.RootStreamPosition := StartPosition + 3 + be.BitsStream.Position;
FCodeSizeMarker.WriteOffset(be);
end;
end;
procedure TSWFActionDefineFunction.WriteToStream(be: TBitsEngine);
begin
StartPosition := be.BitsStream.Position;
inherited;
end;
{
*************************************************** TSWFActionDefineLocal ***************************************************
}
constructor TSWFActionDefineLocal.Create;
begin
ActionCode := actionDefineLocal;
end;
{
************************************************** TSWFActionDefineLocal2 ***************************************************
}
constructor TSWFActionDefineLocal2.Create;
begin
ActionCode := actionDefineLocal2;
end;
{
***************************************************** TSWFActionDelete ******************************************************
}
constructor TSWFActionDelete.Create;
begin
ActionCode := actionDelete;
end;
{
***************************************************** TSWFActionDelete2 *****************************************************
}
constructor TSWFActionDelete2.Create;
begin
ActionCode := actionDelete2;
end;
{
**************************************************** TSWFActionEnumerate ****************************************************
}
constructor TSWFActionEnumerate.Create;
begin
ActionCode := actionEnumerate;
end;
{
***************************************************** TSWFActionEquals2 *****************************************************
}
constructor TSWFActionEquals2.Create;
begin
ActionCode := actionEquals2;
end;
{
**************************************************** TSWFActionGetMember ****************************************************
}
constructor TSWFActionGetMember.Create;
begin
ActionCode := actionGetMember;
end;
{
**************************************************** TSWFActionInitArray ****************************************************
}
constructor TSWFActionInitArray.Create;
begin
ActionCode := actionInitArray;
end;
{
*************************************************** TSWFActionInitObject ****************************************************
}
constructor TSWFActionInitObject.Create;
begin
ActionCode := actionInitObject;
end;
{
**************************************************** TSWFActionNewMethod ****************************************************
}
constructor TSWFActionNewMethod.Create;
begin
ActionCode := actionNewMethod;
end;
{
**************************************************** TSWFActionNewObject ****************************************************
}
constructor TSWFActionNewObject.Create;
begin
ActionCode := actionNewObject;
end;
{
**************************************************** TSWFActionSetMember ****************************************************
}
constructor TSWFActionSetMember.Create;
begin
ActionCode := actionSetMember;
end;
{
*************************************************** TSWFActionTargetPath ****************************************************
}
constructor TSWFActionTargetPath.Create;
begin
ActionCode := actionTargetPath;
end;
{
****************************************************** TSWFActionWith *******************************************************
}
constructor TSWFActionWith.Create;
begin
ActionCode := actionWith;
end;
destructor TSWFActionWith.Destroy;
begin
FreeOffsetMarker(FSizeMarker);
inherited;
end;
procedure TSWFActionWith.Assign(Source: TSWFAction);
begin
inherited;
With TSWFActionWith(Source) do
begin
self.StaticOffset := StaticOffset;
if StaticOffset then
self.Size := Size;
//**//
end;
end;
function TSWFActionWith.GetSizeMarker: TSWFOffsetMarker;
begin
if FSizeMarker = nil then
FSizeMarker := TSWFOffsetMarker.Create;
Result := FSizeMarker;
end;
procedure TSWFActionWith.ReadFromStream(be: TBitsEngine);
begin
Size := be.ReadWord;
end;
procedure TSWFActionWith.SetSize(w: Word);
begin
fSize := w;
StaticOffset := true;
end;
procedure TSWFActionWith.WriteActionBody(be: TBitsEngine);
begin
if StaticOffset then be.WriteWord(Size) else
begin
if FSizeMarker <> nil then
begin
SizeMarker.RootStreamPosition := StartPosition + 3;
SizeMarker.WriteOffset(be);
end;
end;
end;
procedure TSWFActionWith.WriteToStream(be: TBitsEngine);
begin
StartPosition := be.BitsStream.Position;
inherited;
end;
// -- Type Actions --
{
**************************************************** TSWFActionToNumber *****************************************************
}
constructor TSWFActionToNumber.Create;
begin
ActionCode := actionToNumber;
end;
{
**************************************************** TSWFActionToString *****************************************************
}
constructor TSWFActionToString.Create;
begin
ActionCode := actionToString;
end;
{
***************************************************** TSWFActionTypeOf ******************************************************
}
constructor TSWFActionTypeOf.Create;
begin
ActionCode := actionTypeOf;
end;
// -- Math Actions --
{
****************************************************** TSWFActionAdd2 *******************************************************
}
constructor TSWFActionAdd2.Create;
begin
ActionCode := actionAdd2;
end;
{
****************************************************** TSWFActionLess2 ******************************************************
}
constructor TSWFActionLess2.Create;
begin
ActionCode := actionLess2;
end;
{
***************************************************** TSWFActionModulo ******************************************************
}
constructor TSWFActionModulo.Create;
begin
ActionCode := actionModulo;
end;
// -- Stack Operator Actions --
{
***************************************************** TSWFActionBitAnd ******************************************************
}
constructor TSWFActionBitAnd.Create;
begin
ActionCode := actionBitAnd;
end;
{
**************************************************** TSWFActionBitLShift ****************************************************
}
constructor TSWFActionBitLShift.Create;
begin
ActionCode := actionBitLShift;
end;
{
****************************************************** TSWFActionBitOr ******************************************************
}
constructor TSWFActionBitOr.Create;
begin
ActionCode := actionBitOr;
end;
{
**************************************************** TSWFActionBitRShift ****************************************************
}
constructor TSWFActionBitRShift.Create;
begin
ActionCode := actionBitRShift;
end;
{
*************************************************** TSWFActionBitURShift ****************************************************
}
constructor TSWFActionBitURShift.Create;
begin
ActionCode := actionBitURShift;
end;
{
***************************************************** TSWFActionBitXor ******************************************************
}
constructor TSWFActionBitXor.Create;
begin
ActionCode := actionBitXor;
end;
{
**************************************************** TSWFActionDecrement ****************************************************
}
constructor TSWFActionDecrement.Create;
begin
ActionCode := actionDecrement;
end;
{
**************************************************** TSWFActionIncrement ****************************************************
}
constructor TSWFActionIncrement.Create;
begin
ActionCode := actionIncrement;
end;
{
************************************************** TSWFActionPushDuplicate **************************************************
}
constructor TSWFActionPushDuplicate.Create;
begin
ActionCode := actionPushDuplicate;
end;
{
***************************************************** TSWFActionReturn ******************************************************
}
constructor TSWFActionReturn.Create;
begin
ActionCode := actionReturn;
end;
{
**************************************************** TSWFActionStackSwap ****************************************************
}
constructor TSWFActionStackSwap.Create;
begin
ActionCode := actionStackSwap;
end;
{
************************************************** TSWFActionStoreRegister **************************************************
}
constructor TSWFActionStoreRegister.Create;
begin
ActionCode := actionStoreRegister;
end;
procedure TSWFActionStoreRegister.Assign(Source: TSWFAction);
begin
inherited;
RegisterNumber := TSWFActionStoreRegister(Source).RegisterNumber;
end;
procedure TSWFActionStoreRegister.ReadFromStream(be: TBitsEngine);
begin
RegisterNumber := be.ReadByte;
end;
procedure TSWFActionStoreRegister.WriteActionBody(be: TBitsEngine);
begin
be.WriteByte(RegisterNumber);
end;
// ------------ SWF 6 -----------
{
******************************************************** TSWFAction6 ********************************************************
}
function TSWFAction6.MinVersion: Byte;
begin
Result := SWFVer6;
end;
{
*************************************************** TSWFActionInstanceOf ****************************************************
}
constructor TSWFActionInstanceOf.Create;
begin
ActionCode := actionInstanceOf;
end;
{
*************************************************** TSWFActionEnumerate2 ****************************************************
}
constructor TSWFActionEnumerate2.Create;
begin
ActionCode := actionEnumerate2;
end;
{
************************************************** TSWFActionStrictEquals ***************************************************
}
constructor TSWFActionStrictEquals.Create;
begin
ActionCode := actionStrictEquals;
end;
{
***************************************************** TSWFActionGreater *****************************************************
}
constructor TSWFActionGreater.Create;
begin
ActionCode := actionGreater;
end;
{
************************************************** TSWFActionStringGreater **************************************************
}
constructor TSWFActionStringGreater.Create;
begin
ActionCode := actionStringGreater;
end;
// ------------ SWF 7 -----------
{
******************************************************** TSWFAction7 ********************************************************
}
function TSWFAction7.MinVersion: Byte;
begin
Result := SWFVer7;
end;
{
************************************************* TSWFActionDefineFunction2 *************************************************
}
constructor TSWFActionDefineFunction2.Create;
begin
ActionCode := actionDefineFunction2;
Parameters := TStringList.Create;
end;
destructor TSWFActionDefineFunction2.Destroy;
begin
FreeOffsetMarker(FCodeSizeMarker);
Parameters.Free;
inherited;
end;
procedure TSWFActionDefineFunction2.Assign(Source: TSWFAction);
begin
inherited;
With TSWFActionDefineFunction2(Source) do
begin
self.FunctionName := FunctionName;
self.Parameters.AddStrings(Parameters);
self.RegisterCount := RegisterCount;
self.PreloadArgumentsFlag := PreloadArgumentsFlag;
self.PreloadGlobalFlag := PreloadGlobalFlag;
self.PreloadParentFlag := PreloadParentFlag;
self.PreloadRootFlag := PreloadRootFlag;
self.PreloadSuperFlag := PreloadSuperFlag;
self.PreloadThisFlag := PreloadThisFlag;
self.SuppressArgumentsFlag := SuppressArgumentsFlag;
self.SuppressSuperFlag := SuppressSuperFlag;
self.SuppressThisFlag := SuppressThisFlag;
self.StaticOffset := StaticOffset;
if StaticOffset then
self.CodeSize := CodeSize;
// CodeSizeMarker: TSWFOffsetMarker;
//**//
end;
end;
procedure TSWFActionDefineFunction2.AddParam(const param: string; reg: byte);
begin
Parameters.AddObject(param, Pointer(reg));
end;
function TSWFActionDefineFunction2.GetCodeSizeMarker: TSWFOffsetMarker;
begin
if FCodeSizeMarker = nil then
FCodeSizeMarker := TSWFOffsetMarker.Create;
Result := FCodeSizeMarker;
end;
function TSWFActionDefineFunction2.GetParamRegister(Index: byte): byte;
begin
Result := Longint(Parameters.Objects[Index]);
end;
procedure TSWFActionDefineFunction2.ReadFromStream(be: TBitsEngine);
var
il, ParamCount: Word;
b: Byte;
begin
FunctionName := be.ReadString;
ParamCount := be.ReadWord;
RegisterCount := be.ReadByte;
b := be.ReadByte;
PreloadParentFlag := CheckBit(b, 8);
PreloadRootFlag := CheckBit(b, 7);
SuppressSuperFlag := CheckBit(b, 6);
PreloadSuperFlag := CheckBit(b, 5);
SuppressArgumentsFlag := CheckBit(b, 4);
PreloadArgumentsFlag := CheckBit(b, 3);
SuppressThisFlag := CheckBit(b, 2);
PreloadThisFlag := CheckBit(b, 1);
b := be.ReadByte;
PreloadGlobalFlag := CheckBit(b, 1);
if ParamCount > 0 then
For il:=0 to ParamCount - 1 do
begin
b := be.ReadByte;
Parameters.Objects[Parameters.Add(be.ReadString)] := Pointer(LongInt(b));
end;
CodeSize:=be.ReadWord;
end;
procedure TSWFActionDefineFunction2.SetCodeSize(v: Word);
begin
fCodeSize := v;
StaticOffset := true;
end;
procedure TSWFActionDefineFunction2.SetParamRegister(index, value: byte);
begin
Parameters.Objects[Index] := Pointer(value);
end;
procedure TSWFActionDefineFunction2.WriteActionBody(be: TBitsEngine);
var
il: Word;
begin
be.WriteString(FunctionName);
be.WriteWord(Parameters.Count);
be.WriteByte(RegisterCount);
be.WriteBit(PreloadParentFlag);
be.WriteBit(PreloadRootFlag);
be.WriteBit(SuppressSuperFlag);
be.WriteBit(PreloadSuperFlag);
be.WriteBit(SuppressArgumentsFlag);
be.WriteBit(PreloadArgumentsFlag);
be.WriteBit(SuppressThisFlag);
be.WriteBit(PreloadThisFlag);
be.WriteBits(0, 7);
be.WriteBit(PreloadGlobalFlag);
if Parameters.Count > 0 then
For il:=0 to Parameters.Count - 1 do
begin
be.WriteByte(LongInt(Parameters.Objects[il]));
be.WriteString(Parameters[il]);
end;
if StaticOffset then be.WriteWord(CodeSize) else
if FCodeSizeMarker <> nil then
begin
FCodeSizeMarker.RootStreamPosition := StartPosition + 3 + be.BitsStream.Position;
FCodeSizeMarker.WriteOffset(be);
end;
end;
procedure TSWFActionDefineFunction2.WriteToStream(be: TBitsEngine);
begin
StartPosition := be.BitsStream.Position;
inherited;
end;
{
***************************************************** TSWFActionExtends *****************************************************
}
constructor TSWFActionExtends.Create;
begin
ActionCode := actionExtends;
end;
{
***************************************************** TSWFActionCastOp ******************************************************
}
constructor TSWFActionCastOp.Create;
begin
ActionCode := actionCastOp;
end;
{
************************************************** TSWFActionImplementsOp ***************************************************
}
constructor TSWFActionImplementsOp.Create;
begin
ActionCode := actionImplementsOp;
end;
{
******************************************************* TSWFActionTry *******************************************************
}
constructor TSWFActionTry.Create;
begin
ActionCode := actionTry;
end;
destructor TSWFActionTry.Destroy;
procedure fFree(var Marker: TSWFTryOffsetMarker);
begin
try
if Assigned(Marker) and not Marker.isUsing then FreeAndNil(Marker);
except
end;
end;
begin
fFree(FTrySizeMarker);
fFree(FCatchSizeMarker);
fFree(FFinallySizeMarker);
inherited;
end;
procedure TSWFActionTry.Assign(Source: TSWFAction);
begin
inherited;
With TSWFActionTry(Source) do
begin
self.CatchName := CatchName;
self.StaticOffset := StaticOffset;
self.CatchBlockFlag := CatchBlockFlag;
self.CatchInRegisterFlag := CatchInRegisterFlag;
self.CatchRegister := CatchRegister;
self.CatchSize := CatchSize;
self.FinallyBlockFlag := FinallyBlockFlag;
// CatchSizeMarker: TSWFOffsetMarker;
self.FinallySize := FinallySize;
// FinallySizeMarker: TSWFOffsetMarker;
self.TrySize := TrySize;
// TrySizeMarker: TSWFOffsetMarker;
//**//
end;
end;
function TSWFActionTry.GetCatchSizeMarker: TSWFTryOffsetMarker;
begin
if FCatchSizeMarker = nil then
FCatchSizeMarker := TSWFTryOffsetMarker.Create;
Result := FCatchSizeMarker;
end;
function TSWFActionTry.GetFinallySizeMarker: TSWFTryOffsetMarker;
begin
if FFinallySizeMarker = nil then
FFinallySizeMarker := TSWFTryOffsetMarker.Create;
Result := FFinallySizeMarker;
end;
function TSWFActionTry.GetTrySizeMarker: TSWFTryOffsetMarker;
begin
if FTrySizeMarker = nil then
FTrySizeMarker := TSWFTryOffsetMarker.Create;
Result := FTrySizeMarker;
end;
procedure TSWFActionTry.ReadFromStream(be: TBitsEngine);
var
b: Byte;
begin
b := be.ReadByte;
CatchInRegisterFlag := CheckBit(b, 3);
FinallyBlockFlag := CheckBit(b, 2);
CatchBlockFlag := CheckBit(b, 1);
TrySize := be.ReadWord;
CatchSize := be.ReadWord;
FinallySize := be.ReadWord;
if CatchInRegisterFlag
then CatchRegister := be.ReadByte
else CatchName := be.ReadString;
end;
procedure TSWFActionTry.SetCatchSize(w: Word);
begin
fCatchSize := w;
StaticOffset := true;
end;
procedure TSWFActionTry.SetFinallySize(w: Word);
begin
fFinallySize := W;
StaticOffset := true;
end;
procedure TSWFActionTry.SetTrySize(w: Word);
begin
fTrySize := W;
StaticOffset := true;
end;
procedure TSWFActionTry.WriteActionBody(be: TBitsEngine);
begin
be.Writebits(0, 5);
be.WriteBit(CatchInRegisterFlag);
be.WriteBit(FinallyBlockFlag);
be.WriteBit(CatchBlockFlag);
if StaticOffset then
begin
be.WriteWord(TrySize);
be.WriteWord(CatchSize);
be.WriteWord(FinallySize);
end else
begin
if FTrySizeMarker <> nil then
begin
FTrySizeMarker.RootStreamPosition := StartPosition + 3 + be.BitsStream.Position;
FTrySizeMarker.WriteOffset(be);
end;
if CatchBlockFlag
then
begin
if FCatchSizeMarker <> nil then
begin
FCatchSizeMarker.RootStreamPosition := StartPosition + 3 + be.BitsStream.Position;
FCatchSizeMarker.WriteOffset(be);
FCatchSizeMarker.FPrvieusMarker := FTrySizeMarker;
end;
end
else be.WriteWord(0);
if FinallyBlockFlag
then begin
if FFinallySizeMarker <> nil then
begin
FFinallySizeMarker.RootStreamPosition := StartPosition + 3 + be.BitsStream.Position;
FFinallySizeMarker.WriteOffset(be);
if CatchBlockFlag
then FFinallySizeMarker.FPrvieusMarker := FCatchSizeMarker
else FFinallySizeMarker.FPrvieusMarker := FTrySizeMarker;
end;
end
else be.WriteWord(0);
end;
if CatchInRegisterFlag
then be.WriteByte(CatchRegister)
else be.WriteString(CatchName);
end;
procedure TSWFActionTry.WriteToStream(be: TBitsEngine);
begin
StartPosition := be.BitsStream.Position;
inherited;
end;
{
****************************************************** TSWFActionThrow ******************************************************
}
constructor TSWFActionThrow.Create;
begin
ActionCode := actionThrow;
end;
{
****************************************************** TSWFActionList *******************************************************
}
function TSWFActionList.GetAction(Index: word): TSWFAction;
begin
Result := TSWFAction(Items[Index]);
end;
procedure TSWFActionList.SetAction(Index: word; Value: TSWFAction);
begin
Items[Index] := Value;
end;
{
******************************************************* TSWFDoAction ********************************************************
}
constructor TSWFDoAction.Create;
begin
TagID := tagDoAction;
FActions := TSWFActionList.Create;
SelfDestroy := true;
end;
constructor TSWFDoAction.Create(A: TSWFActionList);
begin
TagID := tagDoAction;
FActions := A;
SelfDestroy := false;
end;
destructor TSWFDoAction.Destroy;
begin
if SelfDestroy then FActions.Free;
inherited ;
end;
procedure TSWFDoAction.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFDoAction(Source) do
begin
self.SelfDestroy := SelfDestroy;
CopyActionList(Actions, self.Actions);
end;
end;
function TSWFDoAction.MinVersion: Byte;
var
il: Word;
begin
Result := SWFVer3;
if Actions.Count > 0 then
for il := 0 to Actions.Count -1 do
if Result < Actions[il].MinVersion then
Result := Actions[il].MinVersion;
end;
procedure TSWFDoAction.ReadFromStream(be: TBitsEngine);
var
BA: TSWFActionByteCode;
begin
if ParseActions then ReadActionList(be, Actions, BodySize)
else
begin
BA := TSWFActionByteCode.Create;
BA.DataSize := BodySize - 1;
BA.SelfDestroy := true;
GetMem(BA.fData, BA.DataSize);
be.BitsStream.Read(BA.Data^, BA.DataSize);
Actions.Add(BA);
be.ReadByte; // last 0
end;
// if be.BitsStream.Position < (StartPos + BodySize) then
// be.BitsStream.Position := StartPos + BodySize;
end;
procedure TSWFDoAction.WriteTagBody(be: TBitsEngine);
var
il: Word;
begin
if Actions.Count > 0 then
For il:=0 to Actions.Count-1 do
Actions[il].WriteToStream(be);
be.WriteByte(0); // End flag
end;
{
***************************************************** TSWFDoInitAction ******************************************************
}
constructor TSWFDoInitAction.Create;
begin
inherited ;
TagID := tagDoInitAction;
end;
constructor TSWFDoInitAction.Create(A: TSWFActionList);
begin
inherited ;
TagID := tagDoInitAction;
end;
procedure TSWFDoInitAction.Assign(Source: TBasedSWFObject);
begin
inherited;
SpriteID := TSWFDoInitAction(Source).SpriteID;
end;
function TSWFDoInitAction.MinVersion: Byte;
begin
Result := SWFVer6;
end;
procedure TSWFDoInitAction.ReadFromStream(be: TBitsEngine);
var
BA: TSWFActionByteCode;
begin
SpriteID := be.ReadWord;
if ParseActions then ReadActionList(be, Actions, BodySize - 2)
else
begin
BA := TSWFActionByteCode.Create;
BA.DataSize := BodySize - 3;
BA.SelfDestroy := true;
GetMem(BA.fData, BA.DataSize);
be.BitsStream.Read(BA.Data^, BA.DataSize);
Actions.Add(BA);
be.ReadByte;
end;
end;
procedure TSWFDoInitAction.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(SpriteID);
inherited;
end;
// ===========================================================
// AS3
// ===========================================================
{ TDoubleObject }
constructor TSWFDoubleObject.Create(init: double);
begin
Value := init;
end;
{ TNameSpaceObject }
constructor TSWFNameSpaceObject.Create(kind: byte; name: Longint);
begin
self.Kind := kind;
self.Name := name;
end;
{ TIntegerList }
function TSWFIntegerList.GetInt(index: Integer): longint;
begin
Result := longint(items[index]);
end;
procedure TSWFIntegerList.SetInt(index: Integer; const Value: longint);
begin
Items[index] := Pointer(Value);
end;
procedure TSWFIntegerList.WriteToStream(be: TBitsEngine);
var il: integer;
begin
be.WriteEncodedU32(Count);
if Count > 0 then
for il := 0 to Count - 1 do
be.WriteEncodedU32(Int[il]);
end;
procedure TSWFIntegerList.AddInt(value: longint);
begin
Add(Pointer(Value));
end;
{ TSWFBasedMultiNameObject }
procedure TSWFBasedMultiNameObject.ReadFromStream(be: TBitsEngine);
begin
// empty
end;
procedure TSWFBasedMultiNameObject.WriteToStream(be: TBitsEngine);
begin
// empty
end;
procedure TSWFmnQName.ReadFromStream(be: TBitsEngine);
begin
NS := be.ReadEncodedU32;
Name := be.ReadEncodedU32;
end;
procedure TSWFmnQName.WriteToStream(be: TBitsEngine);
begin
be.WriteEncodedU32(NS);
be.WriteEncodedU32(Name);
end;
procedure TSWFmnRTQName.ReadFromStream(be: TBitsEngine);
begin
Name := be.ReadEncodedU32;
end;
procedure TSWFmnRTQName.WriteToStream(be: TBitsEngine);
begin
be.WriteEncodedU32(Name);
end;
procedure TSWFmnMultiname.ReadFromStream(be: TBitsEngine);
begin
Name := be.ReadEncodedU32;
NSSet := be.ReadEncodedU32;
end;
procedure TSWFmnMultiname.WriteToStream(be: TBitsEngine);
begin
be.WriteEncodedU32(Name);
be.WriteEncodedU32(NSSet);
end;
procedure TSWFmnMultinameL.ReadFromStream(be: TBitsEngine);
begin
NSSet := be.ReadEncodedU32;
end;
procedure TSWFmnMultinameL.WriteToStream(be: TBitsEngine);
begin
be.WriteEncodedU32(NSSet);
end;
{ TSWFAS3ConstantPool }
constructor TSWFAS3ConstantPool.Create;
begin
IntegerList := TSWFIntegerList.Create;
UIntegerList := TList.Create;
DoubleList := TObjectList.Create;
StringList := TStringList.Create;
NameSpaceList := TObjectList.Create;
NameSpaceSETList := TObjectList.Create;
MultinameList := TObjectList.Create;
end;
destructor TSWFAS3ConstantPool.Destroy;
begin
MultinameList.Free;
NameSpaceSETList.Free;
NameSpaceList.Free;
StringList.Free;
DoubleList.Free;
UIntegerList.Free;
IntegerList.Free;
inherited;
end;
function TSWFAS3ConstantPool.GetDouble(index: Integer): Double;
begin
Result := TSWFDoubleObject(DoubleList[index]).Value;
end;
function TSWFAS3ConstantPool.GetDoubleCount: longint;
begin
Result := DoubleList.Count;
end;
function TSWFAS3ConstantPool.GetInt(index: longint): longint;
begin
Result := IntegerList.Int[index];
end;
function TSWFAS3ConstantPool.GetIntCount: longint;
begin
Result := IntegerList.Count;
end;
function TSWFAS3ConstantPool.GetMultiname(index: Integer): TSWFBasedMultiNameObject;
begin
Result := TSWFBasedMultiNameObject(MultinameList[index]);
end;
function TSWFAS3ConstantPool.GetMultinameCount: longint;
begin
Result := MultinameList.Count;
end;
function TSWFAS3ConstantPool.GetNameSpace(index: Integer): TSWFNameSpaceObject;
begin
Result := TSWFNameSpaceObject(NameSpaceList[index]);
end;
function TSWFAS3ConstantPool.GetNameSpaceCount: longint;
begin
Result := NameSpaceList.Count;
end;
function TSWFAS3ConstantPool.GetNameSpaceSET(index: Integer): TSWFIntegerList;
begin
Result := TSWFIntegerList(NameSpaceSETList[index]);
end;
function TSWFAS3ConstantPool.GetNameSpaceSETCount: longint;
begin
Result := NameSpaceSETList.Count;
end;
function TSWFAS3ConstantPool.GetStrings(index: Integer): string;
begin
Result := StringList[index];
end;
function TSWFAS3ConstantPool.GetStringsCount: longint;
begin
Result := StringList.Count;
end;
function TSWFAS3ConstantPool.GetUInt(index: Integer): longword;
begin
Result := longword(UIntegerList[index]);
end;
function TSWFAS3ConstantPool.GetUIntCount: longword;
begin
Result := UIntegerList.Count;
end;
procedure TSWFAS3ConstantPool.ReadFromStream(be: TBitsEngine);
var count, subcount, il, il2: dword;
Kind: byte;
NSSet: TSWFIntegerList;
MK: TSWFBasedMultiNameObject;
begin
be.ReadByte; // "unnecessary" byte
count := be.ReadEncodedU32;
if count > 0 then
for il := 1 to count - 1 do
IntegerList.AddInt(be.ReadEncodedU32);
count := be.ReadEncodedU32;
if count > 0 then
for il := 1 to count - 1 do
UIntegerList.Add(Pointer(be.ReadEncodedU32));
count := be.ReadEncodedU32;
if count > 0 then
for il := 1 to count - 1 do
DoubleList.Add(TSWFDoubleObject.Create(be.ReadStdDouble));
count := be.ReadEncodedU32;
if count > 0 then
for il := 1 to count - 1 do
StringList.Add(be.ReadLongString(true));
count := be.ReadEncodedU32;
if count > 0 then
for il := 1 to count - 1 do
begin
Kind := be.ReadByte;
NameSpaceList.Add(TSWFNameSpaceObject.Create(Kind, be.ReadEncodedU32));
end;
count := be.ReadEncodedU32;
if count > 0 then
for il := 1 to count - 1 do
begin
subcount := be.ReadEncodedU32;
NSSet := TSWFIntegerList.Create;
NameSpaceSETList.Add(NSSet);
if subcount > 0 then
for il2 := 0 to subcount - 1 do
NSSet.AddInt(be.ReadEncodedU32);
end;
count := be.ReadEncodedU32;
if count > 0 then
for il := 1 to count - 1 do
begin
Kind := be.ReadByte;
case Kind of
mkQName, mkQNameA:
MK := TSWFmnQName.Create;
mkRTQName, mkRTQNameA:
MK := TSWFmnRTQName.Create;
mkRTQNameL, mkRTQNameLA:
MK := TSWFmnRTQNameL.Create;
mkMultiname, mkMultinameA:
MK := TSWFmnMultiname.Create;
else {mkMultinameL, mkMultinameLA:}
MK := TSWFmnMultinameL.Create;
end;
MK.MultinameKind := Kind;
MK.ReadFromStream(be);
MultinameList.Add(MK);
end;
end;
procedure TSWFAS3ConstantPool.WriteToStream(be: TBitsEngine);
var il: dword;
begin
be.WriteByte(0); // "unnecessary" byte
if IntCount > 0 then
begin
be.WriteEncodedU32(IntCount + 1);
for il := 0 to IntCount - 1 do
be.WriteEncodedU32(Int[il]);
end else be.WriteByte(0);
if UIntCount > 0 then
begin
be.WriteEncodedU32(UIntCount + 1);
for il := 0 to UIntcount - 1 do
be.WriteEncodedU32(UInt[il]);
end else be.WriteByte(0);
if DoubleCount > 0 then
begin
be.WriteEncodedU32(DoubleCount + 1);
for il := 0 to DoubleCount - 1 do
be.WriteStdDouble(Double[il]);
end else be.WriteByte(0);
if StringsCount > 0 then
begin
be.WriteEncodedU32(StringsCount + 1);
for il := 0 to StringsCount - 1 do
be.WriteEncodedString(Strings[il]);
end else be.WriteByte(0);
if NameSpaceCount > 0 then
begin
be.WriteEncodedU32(NameSpaceCount + 1);
for il := 0 to NameSpaceCount - 1 do
with NameSpace[il] do
begin
be.WriteByte(Kind);
be.WriteEncodedU32(Name);
end;
end else be.WriteByte(0);
if NameSpaceSETCount > 0 then
begin
be.WriteEncodedU32(NameSpaceSETCount + 1);
for il := 0 to NameSpaceSETCount - 1 do
NameSpaceSET[il].WriteToStream(be);
end else be.WriteByte(0);
if MultinameCount > 0 then
begin
be.WriteEncodedU32(MultinameCount + 1);
for il := 0 to MultinameCount - 1 do
begin
be.WriteByte(Multiname[il].MultinameKind);
Multiname[il].WriteToStream(be);
end;
end else be.WriteByte(0);
end;
procedure TSWFAS3ConstantPool.SetDouble(index: Integer; const Value: Double);
begin
if index = -1 then DoubleList.Add(TSWFDoubleObject.Create(Value))
else TSWFDoubleObject(DoubleList[index]).Value := Value;
end;
procedure TSWFAS3ConstantPool.SetInt(index: longint; const Value: longint);
begin
if index = -1 then IntegerList.Add(Pointer(Value))
else IntegerList.Int[index] := Value;
end;
procedure TSWFAS3ConstantPool.SetMultiname(index: Integer; const Value: TSWFBasedMultiNameObject);
begin
if index = -1 then MultinameList.Add(Value)
else MultinameList[index] := Value;
end;
procedure TSWFAS3ConstantPool.SetNameSpace(index: Integer; const Value: TSWFNameSpaceObject);
begin
if index = -1 then NameSpaceList.Add(Value)
else NameSpaceList[index] := Value;
end;
procedure TSWFAS3ConstantPool.SetNameSpaceSET(index: Integer; const Value: TSWFIntegerList);
begin
if index = -1 then NameSpaceSETList.Add(Value)
else NameSpaceSETList[index] := Value;
end;
procedure TSWFAS3ConstantPool.SetStrings(index: longint; const Value: string);
begin
if index = -1 then StringList.Add(Value)
else StringList[index] := Value;
end;
procedure TSWFAS3ConstantPool.SetUInt(index: Integer; const Value: longword);
begin
if index = -1 then UIntegerList.Add(Pointer(Value))
else UIntegerList[index] := Pointer(Value);
end;
function TSWFAS3MetadataInfo.AddMetadataItem: TSWFAS3MetadataItem;
begin
Result := TSWFAS3MetadataItem.Create;
FInfoList.Add(Result);
end;
constructor TSWFAS3MetadataInfo.Create;
begin
FInfoList := TObjectList.Create;
end;
destructor TSWFAS3MetadataInfo.Destroy;
begin
FInfoList.Free;
inherited;
end;
function TSWFAS3MetadataInfo.GetItem(index: integer): TSWFAS3MetadataItem;
begin
Result := TSWFAS3MetadataItem(InfoList[index]);
end;
{ TSWFAS3Metadata }
function TSWFAS3Metadata.AddMetaInfo: TSWFAS3MetadataInfo;
begin
Result := TSWFAS3MetadataInfo.Create;
FMetadataList.Add(Result);
end;
constructor TSWFAS3Metadata.Create;
begin
FMetadataList := TObjectList.Create;
end;
destructor TSWFAS3Metadata.Destroy;
begin
FMetadataList.Free;
inherited;
end;
function TSWFAS3Metadata.GetMetadata(index: integer): TSWFAS3MetadataInfo;
begin
Result := TSWFAS3MetadataInfo(FMetadataList[index]);
end;
procedure TSWFAS3Metadata.ReadFromStream(be: TBitsEngine);
var count, icount, il, il2: longint;
MInfo: TSWFAS3MetadataInfo;
MItem: TSWFAS3MetadataItem;
begin
count := be.ReadEncodedU32;
if count > 0 then
for il := 0 to count - 1 do
begin
MInfo := AddMetaInfo;
MInfo.Name := be.ReadEncodedU32;
icount := be.ReadEncodedU32;
if icount > 0 then
for il2 := 0 to icount - 1 do
begin
MItem := MInfo.AddMetadataItem;
MItem.Key := be.ReadEncodedU32;
MItem.Value := be.ReadEncodedU32;
end;
end;
end;
procedure TSWFAS3Metadata.WriteToStream(be: TBitsEngine);
var il, il2: longint;
begin
be.WriteEncodedU32(MetadataList.Count);
if MetadataList.Count > 0 then
for il := 0 to MetadataList.Count - 1 do
with MetadataInfo[il] do
begin
be.WriteEncodedU32(Name);
be.WriteEncodedU32(InfoList.Count);
if InfoList.Count > 0 then
for il2 := 0 to InfoList.Count - 1 do
with MetaItem[il2] do
begin
be.WriteEncodedU32(Key);
be.WriteEncodedU32(Value);
end;
end;
end;
{ TSWFAS3Methods }
constructor TSWFAS3Method.Create;
begin
FParamNames := TSWFIntegerList.Create;
FParamTypes := TSWFIntegerList.Create;
FOptions := TObjectList.Create;
end;
destructor TSWFAS3Method.Destroy;
begin
FParamNames.Free;
FOptions.Free;
FParamTypes.Free;
inherited;
end;
function TSWFAS3Method.AddOption: TSWFAS3MethodOptions;
begin
Result := TSWFAS3MethodOptions.Create;
Options.Add(Result);
HasOptional := true;
end;
function TSWFAS3Method.GetOption(index: integer): TSWFAS3MethodOptions;
begin
Result := TSWFAS3MethodOptions(Options[index]);
end;
function TSWFAS3Methods.AddMethod: TSWFAS3Method;
begin
Result := TSWFAS3Method.Create;
MethodsList.Add(Result);
end;
constructor TSWFAS3Methods.Create;
begin
MethodsList := TObjectList.Create;
end;
destructor TSWFAS3Methods.Destroy;
begin
MethodsList.Free;
inherited;
end;
function TSWFAS3Methods.GetMethod(index: integer): TSWFAS3Method;
begin
Result := TSWFAS3Method(MethodsList[index]);
end;
procedure TSWFAS3Methods.ReadFromStream(be: TBitsEngine);
var count, pCount, i1, i2: longint;
M: TSWFAS3Method;
Op: TSWFAS3MethodOptions;
flags: byte;
begin
count := be.ReadEncodedU32;
if count > 0 then
for i1 := 0 to Count - 1 do
begin
M := AddMethod;
pCount := be.ReadEncodedU32;
M.ReturnType := be.ReadEncodedU32;
if pCount > 0 then
for i2 := 0 to pCount - 1 do
M.ParamTypes.AddInt(be.ReadEncodedU32);
M.Name := be.ReadEncodedU32;
flags := be.ReadByte;
M.NeedArguments := CheckBit(flags, 1);
M.NeedActivation := CheckBit(flags, 2);
M.NeedRest := CheckBit(flags, 3);
M.HasOptional := CheckBit(flags, 4);
M.SetDxns := CheckBit(flags, 6);
M.HasParamNames := CheckBit(flags, 8);
if M.HasOptional then
begin
pCount := be.ReadEncodedU32;
if (pCount > 0) {and (M.ParamTypes.Count > pCount)} then
for i2 := M.ParamTypes.Count - pCount to M.ParamTypes.Count - 1 do
begin
Op := M.AddOption;
Op.val := be.ReadEncodedU32;
Op.kind := be.ReadByte;
end;
end;
if M.HasParamNames and (M.ParamTypes.Count > 0) then
begin
for i2 := 0 to M.ParamTypes.Count - 1 do
M.ParamNames.AddInt(be.ReadEncodedU32);
end;
end;
end;
procedure TSWFAS3Methods.WriteToStream(be: TBitsEngine);
var il, il2: integer;
begin
be.WriteEncodedU32(MethodsList.Count);
if MethodsList.Count > 0 then
for il := 0 to MethodsList.Count - 1 do
with Method[il] do
begin
be.WriteEncodedU32(ParamTypes.Count);
be.WriteEncodedU32(ReturnType);
if ParamTypes.Count > 0 then
for il2 := 0 to ParamTypes.Count - 1 do
be.WriteEncodedU32(ParamTypes.Int[il2]);
be.WriteEncodedU32(Name);
be.WriteByte(byte(NeedArguments) + byte(NeedActivation) shl 1 + byte(NeedRest) shl 2 +
byte(HasOptional) shl 3 + byte(SetDxns) shl 5 + byte(HasParamNames) shl 7);
if HasOptional then
begin
be.WriteEncodedU32(Options.Count);
if Options.Count > 0 then
for il2 := 0 to Options.Count - 1 do
with Option[il2] do
begin
be.WriteEncodedU32(val);
be.WriteByte(kind);
end;
end;
if HasParamNames and (ParamTypes.Count > 0) then
for il2 := 0 to ParamTypes.Count - 1 do
be.WriteEncodedU32(ParamNames.Int[il2]);
end;
end;
destructor TSWFAS3Trait.Destroy;
begin
if Assigned(FMetadata) then FreeAndNil(FMetadata);
end;
function TSWFAS3Trait.GetMetadata: TSWFIntegerList;
begin
if not Assigned(FMetadata) then
begin
FMetadata := TSWFIntegerList.Create;
FIsMetadata := true;
end;
Result := FMetadata;
end;
procedure TSWFAS3Trait.ReadFromStream(be: TBitsEngine);
var b: byte;
il, icount: integer;
begin
Name := be.ReadEncodedU32;
b := Be.ReadByte;
TraitType := b and 15;
IsFinal := CheckBit(b, 5);
IsOverride := CheckBit(b, 6);
IsMetadata := CheckBit(b, 7);
ID := be.ReadEncodedU32;
SpecID := be.ReadEncodedU32;
if TraitType in [Trait_Slot, Trait_Const] then
begin
VIndex := be.ReadEncodedU32;
if VIndex > 0 then VKind := be.ReadByte;
end;
if IsMetadata then
begin
icount := be.ReadEncodedU32;
if icount > 0 then
for il := 0 to icount - 1 do
Metadata.AddInt(be.ReadEncodedU32);
end;
end;
procedure TSWFAS3Trait.SetIsMetadata(const Value: Boolean);
begin
FIsMetadata := Value;
if Value then FMetadata := TSWFIntegerList.Create
else FreeAndNil(FMetadata);
end;
procedure TSWFAS3Trait.WriteToStream(be: TBitsEngine);
begin
be.WriteEncodedU32(Name);
be.WriteByte(TraitType + byte(isFinal) shl 4 + byte(IsOverride) shl 5 +
byte(IsMetadata) shl 6);
be.WriteEncodedU32(ID);
be.WriteEncodedU32(SpecID);
if TraitType in [Trait_Slot, Trait_Const] then
begin
be.WriteEncodedU32(VIndex);
if VIndex > 0 then be.WriteByte(VKind);
end;
if IsMetadata then
Metadata.WriteToStream(be);
end;
{ TSWFAS3Traits }
function TSWFAS3Traits.AddTrait: TSWFAS3Trait;
begin
Result := TSWFAS3Trait.Create;
FTraits.Add(Result);
end;
constructor TSWFAS3Traits.Create;
begin
FTraits := TObjectList.Create;
end;
destructor TSWFAS3Traits.Destroy;
begin
FTraits.Free;
inherited;
end;
function TSWFAS3Traits.GetTrait(Index: Integer): TSWFAS3Trait;
begin
Result := TSWFAS3Trait(FTraits[Index]);
end;
{ TSWFAS3InstanceItem }
constructor TSWFAS3InstanceItem.Create;
begin
inherited;
FInterfaces := TSWFIntegerList.Create;
end;
destructor TSWFAS3InstanceItem.Destroy;
begin
FInterfaces.Free;
inherited;
end;
procedure TSWFAS3InstanceItem.ReadFromStream(be: TBitsEngine);
var b: byte;
icount, i: longint;
Tr: TSWFAS3Trait;
{$IFDEF DebugAS3}
mpos: longint;
ssave: boolean;
{$ENDIF}
begin
Name := be.ReadEncodedU32;
SuperName := be.ReadEncodedU32;
b := be.ReadByte;
ClassSealed := CheckBit(b, 1);
ClassFinal := CheckBit(b, 2);
ClassInterface := CheckBit(b, 3);
ClassProtectedNs := CheckBit(b, 4);
if ClassProtectedNs then
ProtectedNs := be.ReadEncodedU32;
icount := be.ReadEncodedU32;
if icount > 0 then
for i := 0 to iCount - 1 do
Interfaces.AddInt(be.ReadEncodedU32);
Iinit := be.ReadEncodedU32;
icount := be.ReadEncodedU32;
{$IFDEF DebugAS3}
ssave := false;
{$ENDIF}
if icount > 0 then
begin
for i := 0 to iCount - 1 do
begin
{$IFDEF DebugAS3}
mpos := be.BitsStream.Position;
{$ENDIF}
Tr := TSWFAS3Trait.Create;
Tr.ReadFromStream(be);
Traits.Add(Tr);
{$IFDEF DebugAS3}
if ssave then
begin
AddDebugAS3(Format('Traits %d: name: %d pos: %d', [i, Tr.Name, mpos]));
SLDebug.SaveToFile('debugAsS3.txt');
end;
{$ENDIF}
end;
end;
end;
procedure TSWFAS3InstanceItem.WriteToStream(be: TBitsEngine);
var il: integer;
begin
be.WriteEncodedU32(Name);
be.WriteEncodedU32(SuperName);
be.WriteByte(byte(ClassSealed) + byte(ClassFinal) shl 1 +
byte(ClassInterface) shl 2 + byte(ClassProtectedNs) shl 3);
if ClassProtectedNs then
be.WriteEncodedU32(ProtectedNs);
Interfaces.WriteToStream(be);
be.WriteEncodedU32(Iinit);
be.WriteEncodedU32(Traits.Count);
if Traits.Count > 0 then
for il := 0 to Traits.Count - 1 do
Trait[il].WriteToStream(be);
end;
{ TSWFAS3Instance }
function TSWFAS3Instance.AddInstanceItem: TSWFAS3InstanceItem;
begin
Result := TSWFAS3InstanceItem.Create;
Add(Result);
end;
function TSWFAS3Instance.GetInstanceItem(Index: longint): TSWFAS3InstanceItem;
begin
Result := TSWFAS3InstanceItem(Items[index]);
end;
procedure TSWFAS3Instance.ReadFromStream(Count: Longint; be: TBitsEngine);
var IItem: TSWFAS3InstanceItem;
il: longint;
{$IFDEF DebugAS3}
SL: TStringList;
{$ENDIF}
begin
{$IFDEF DebugAS3}
SL := TStringList.Create;
{$ENDIF}
if Count > 0 then
for il := 0 to Count - 1 do
begin
{$IFDEF DebugAS3}
SL.Add(IntToStr(be.BitsStream.Position));
{$ENDIF}
IItem := TSWFAS3InstanceItem.Create;
IItem.ReadFromStream(be);
Add(IItem);
{$IFDEF DebugAS3}
SL.Add(IntToStr(il)+ ': '+ IntToStr(IItem.Name));
SL.SaveToFile('D:\_Flash\abc\out\inst_pos.txt');
{$ENDIF}
end;
{$IFDEF DebugAS3}
SL.Free;
{$ENDIF}
end;
procedure TSWFAS3Instance.WriteToStream(be: TBitsEngine);
var il: integer;
begin
if Count > 0 then
for il := 0 to Count - 1 do
InstanceItem[il].WriteToStream(be);
end;
{ TSWFAS3ClassesInfo }
procedure TSWFAS3ClassInfo.ReadFromStream(be: TBitsEngine);
var il, icount: longint;
Tr: TSWFAS3Trait;
begin
CInit := be.ReadEncodedU32;
icount := be.ReadEncodedU32;
if icount > 0 then
for il := 0 to iCount - 1 do
begin
Tr := TSWFAS3Trait.Create;
Tr.ReadFromStream(be);
Traits.Add(Tr);
end;
end;
procedure TSWFAS3ClassInfo.WriteToStream(be: TBitsEngine);
var il: integer;
begin
be.WriteEncodedU32(CInit);
be.WriteEncodedU32(Traits.Count);
if Traits.Count > 0 then
for il := 0 to Traits.Count - 1 do
Trait[il].WriteToStream(be);
end;
{ TSWFAS3Classes }
function TSWFAS3Classes.AddClassInfo: TSWFAS3ClassInfo;
begin
Result := TSWFAS3ClassInfo.Create;
Add(Result);
end;
function TSWFAS3Classes.GetClassInfo(Index: Integer): TSWFAS3ClassInfo;
begin
Result := TSWFAS3ClassInfo(Items[index]);
end;
procedure TSWFAS3Classes.ReadFromStream(rcount: longInt; be: TBitsEngine);
var il: integer;
CI: TSWFAS3ClassInfo;
begin
for il :=0 to rCount - 1 do
begin
CI := TSWFAS3ClassInfo.Create;
CI.ReadFromStream(be);
Add(CI);
end;
end;
procedure TSWFAS3Classes.WriteToStream(be: TBitsEngine);
var il: integer;
begin
if Count > 0 then
for il := 0 to Count - 1 do
_ClassInfo[il].WriteToStream(be);
end;
{ TSWFAS3Scripts }
function TSWFAS3Scripts.AddScriptInfo: TSWFAS3ScriptInfo;
begin
Result := TSWFAS3ScriptInfo.Create;
Add(Result);
end;
function TSWFAS3Scripts.GetScriptInfo(Index: Integer): TSWFAS3ScriptInfo;
begin
Result := TSWFAS3ScriptInfo(Items[Index]);
end;
procedure TSWFAS3Scripts.ReadFromStream(be: TBitsEngine);
var il, iCount: longint;
SI: TSWFAS3ScriptInfo;
begin
iCount := be.ReadEncodedU32;
for il :=0 to iCount - 1 do
begin
SI := TSWFAS3ScriptInfo.Create;
SI.ReadFromStream(be);
Add(SI);
end;
end;
procedure TSWFAS3Scripts.WriteToStream(be: TBitsEngine);
var il: integer;
begin
be.WriteEncodedU32(Count);
if Count > 0 then
for il := 0 to Count - 1 do
ScriptInfo[il].WriteToStream(be);
end;
{ TSWFAS3MethodBodyInfo }
function TSWFAS3MethodBodyInfo.AddException: TSWFAS3Exception;
begin
Result := TSWFAS3Exception.Create;
FExceptions.Add(Result);
end;
constructor TSWFAS3MethodBodyInfo.Create;
begin
inherited;
FCode := TMemoryStream.Create;
FExceptions := TObjectList.Create;
end;
destructor TSWFAS3MethodBodyInfo.Destroy;
begin
FExceptions.Free;
FCode.Free;
inherited;
end;
function TSWFAS3MethodBodyInfo.GetCodeItem(Index: Integer): byte;
var PB: PByte;
begin
PB := FCode.Memory;
if Index > 0 then Inc(PB, Index);
Result := PB^;
end;
function TSWFAS3MethodBodyInfo.GetException(Index: Integer): TSWFAS3Exception;
begin
Result := TSWFAS3Exception(FExceptions[Index]);
end;
procedure TSWFAS3MethodBodyInfo.ReadFromStream(be: TBitsEngine);
var icount, il: longint;
Tr: TSWFAS3Trait;
Exc: TSWFAS3Exception;
begin
Method := be.ReadEncodedU32;
MaxStack := be.ReadEncodedU32;
LocalCount := be.ReadEncodedU32;
InitScopeDepth := be.ReadEncodedU32;
MaxScopeDepth := be.ReadEncodedU32;
icount := be.ReadEncodedU32;
FCode.CopyFrom(Be.BitsStream, icount);
icount := be.ReadEncodedU32;
if icount > 0 then
for il := 0 to iCount - 1 do
begin
Exc := TSWFAS3Exception.Create;
Exc.From := be.ReadEncodedU32;
Exc._To := be.ReadEncodedU32;
Exc.Target := be.ReadEncodedU32;
Exc.ExcType := be.ReadEncodedU32;
Exc.VarName := be.ReadEncodedU32;
FExceptions.Add(Exc);
end;
icount := be.ReadEncodedU32;
if icount > 0 then
for il := 0 to iCount - 1 do
begin
Tr := TSWFAS3Trait.Create;
Tr.ReadFromStream(be);
Traits.Add(Tr);
end;
end;
procedure TSWFAS3MethodBodyInfo.SetCodeItem(Index: Integer; const Value: byte);
var PB: PByte;
begin
PB := FCode.Memory;
if Index > 0 then Inc(PB, Index);
PB^ := Value;
end;
procedure TSWFAS3MethodBodyInfo.SetStrByteCode(Value: AnsiString);
var
L, il: Word;
s2: string[2];
P: PByte;
begin
L := Length(Value) div 2;
Code.SetSize(L);
if L > 0 then
begin
s2 := ' ';
P := Code.Memory;
for il := 0 to L - 1 do
begin
s2[1] := Value[il*2 + 1];
s2[2] := Value[il*2 + 2];
P^ := StrToInt('$'+ s2);
Inc(P);
end;
end;
end;
function TSWFAS3MethodBodyInfo.GetStrByteCode: ansistring;
var il: longint;
PB: PByte;
begin
Result := '';
PB := FCode.Memory;
for il := 0 to FCode.Size - 1 do
begin
Result := Result + IntToHex(PB^, 2);
inc(PB);
end;
end;
procedure TSWFAS3MethodBodyInfo.WriteToStream(be: TBitsEngine);
var il: integer;
begin
be.WriteEncodedU32(Method);
be.WriteEncodedU32(MaxStack);
be.WriteEncodedU32(LocalCount);
be.WriteEncodedU32(InitScopeDepth);
be.WriteEncodedU32(MaxScopeDepth);
Code.Position := 0;
be.WriteEncodedU32(Code.Size);
Be.BitsStream.CopyFrom(Code, Code.Size);
be.WriteEncodedU32(Exceptions.Count);
if Exceptions.Count > 0 then
for il := 0 to Exceptions.Count - 1 do
with Exception[il] do
begin
be.WriteEncodedU32(From);
be.WriteEncodedU32(_To);
be.WriteEncodedU32(Target);
be.WriteEncodedU32(ExcType);
be.WriteEncodedU32(VarName);
end;
be.WriteEncodedU32(Traits.Count);
if Traits.Count > 0 then
for il := 0 to Traits.Count - 1 do
Trait[il].WriteToStream(be);
end;
{ TSWFAS3MethodBodies }
function TSWFAS3MethodBodies.AddMethodBodyInfo: TSWFAS3MethodBodyInfo;
begin
Result := TSWFAS3MethodBodyInfo.Create;
Add(Result);
end;
function TSWFAS3MethodBodies.GetClassInfo(Index: Integer): TSWFAS3MethodBodyInfo;
begin
Result := TSWFAS3MethodBodyInfo(Items[Index]);
end;
procedure TSWFAS3MethodBodies.ReadFromStream(be: TBitsEngine);
var il, iCount: longint;
MB: TSWFAS3MethodBodyInfo;
begin
iCount := be.ReadEncodedU32;
for il := 0 to iCount - 1 do
begin
MB := TSWFAS3MethodBodyInfo.Create;
MB.ReadFromStream(be);
Add(MB);
end;
end;
procedure TSWFAS3MethodBodies.WriteToStream(be: TBitsEngine);
var il: integer;
begin
be.WriteEncodedU32(Count);
if Count > 0 then
for il := 0 to Count - 1 do
MethodBodyInfo[il].WriteToStream(be);
end;
{*************************************************** TSWFDoABC ***************************************************}
constructor TSWFDoABC.Create;
begin
TagID := tagDoABC;
FConstantPool := TSWFAS3ConstantPool.Create;
FMethods := TSWFAS3Methods.Create;
FMetadata := TSWFAS3Metadata.Create;
FInstance := TSWFAS3Instance.Create;
FClasses := TSWFAS3Classes.Create;
FScripts := TSWFAS3Scripts.Create;
FMethodBodies := TSWFAS3MethodBodies.Create;
end;
destructor TSWFDoABC.Destroy;
begin
if SelfDestroy and (DataSize > 0) then FreeMem(FData, DataSize);
FMethodBodies.Free;
FScripts.Free;
FClasses.Free;
FInstance.Free;
FMetadata.Free;
FMethods.Free;
FConstantPool.Free;
inherited;
end;
function TSWFDoABC.GetClasses: TSWFAS3Classes;
begin
Result := FClasses;
end;
function TSWFDoABC.GetInstance: TSWFAS3Instance;
begin
Result := FInstance;
end;
function TSWFDoABC.GetMetadata: TSWFAS3Metadata;
begin
Result := FMetadata;
end;
function TSWFDoABC.GetMethodBodies: TSWFAS3MethodBodies;
begin
Result := FMethodBodies;
end;
function TSWFDoABC.GetMethods: TSWFAS3Methods;
begin
Result := FMethods;
end;
function TSWFDoABC.GetScripts: TSWFAS3Scripts;
begin
Result := FScripts;
end;
function TSWFDoABC.GetStrVersion: string;
begin
Result := Format('%d.%d.%d.%d', [HiByte(MajorVersion), LoByte(MajorVersion),
HiByte(MinorVersion), LoByte(MinorVersion)]);
end;
function TSWFDoABC.MinVersion: Byte;
begin
Result := SWFVer9;
end;
procedure TSWFDoABC.ReadFromStream(be: TBitsEngine);
var
b: byte;
Pos: Longint;
CClass: Longint;
begin
Pos := BE.BitsStream.Position;
b := be.ReadByte;
be.ReadByte; // reserved
be.ReadWord; // reserved
DoAbcLazyInitializeFlag := CheckBit(b, 1);
FActionName := be.ReadString();
be.BitsStream.Seek(-1, 1); //soFromCurrent
MinorVersion := be.ReadWord;
MajorVersion := be.ReadWord;
if ParseActions then
begin
ConstantPool.ReadFromStream(be);
Methods.ReadFromStream(be);
Metadata.ReadFromStream(be);
CClass := be.ReadEncodedU32;
Instance.ReadFromStream(CClass, be);
Classes.ReadFromStream(CClass, be);
Scripts.ReadFromStream(be);
MethodBodies.ReadFromStream(be);
{$IFDEF DebuagAS3}
// BE.BitsStream.Position := Pos{ + 8};
// FS := TFileStream.Create('DoABC.dat', fmCreate);
// FS.CopyFrom(BE.BitsStream, BodySize {- 8});
// FS.Free;
{$ENDIF}
end else
begin
DataSize := BodySize - (BE.BitsStream.Position - Pos);
GetMem(FData, DataSize);
be.BitsStream.Read(FData^, DataSize);
SelfDestroy := true;
end;
end;
procedure TSWFDoABC.SetStrVersion(ver: string);
var b: array [0..3] of byte;
il, ib, start: byte;
subs: string;
begin
try
ib := 0;
start := 1;
for il := 1 to length(ver) do
if (ver[il] = '.') or (il = length(ver)) then
begin
subs := Copy(ver, start, il - start + 1 * byte(il = length(ver)));
start := il + 1;
b[ib] := StrToInt(subs);
inc(ib);
end;
MajorVersion := b[0] shl 8 + b[1];
MinorVersion := b[2] shl 8 + b[3];
except
MajorVersion := 46 shl 8;
MinorVersion := 16 shl 8;
end;
end;
procedure TSWFDoABC.WriteTagBody(be: TBitsEngine);
begin
be.WriteByte(byte(DoAbcLazyInitializeFlag));
be.WriteByte(0);
be.WriteWord(0);
if ActionName <> '' then
be.WriteString(ActionName, false);
be.WriteWord(MinorVersion);
be.WriteWord(MajorVersion);
if SelfDestroy and (DataSize > 0) then
begin
be.BitsStream.Write(Data^, DataSize);
end else
begin
ConstantPool.WriteToStream(be);
Methods.WriteToStream(be);
Metadata.WriteToStream(be);
be.WriteEncodedU32(Classes.Count);
Instance.WriteToStream(be);
Classes.WriteToStream(be);
Scripts.WriteToStream(be);
MethodBodies.WriteToStream(be);
end;
end;
// ===========================================================
// Display List
// ===========================================================
{
*************************************************** TSWFBasedPlaceObject ****************************************************
}
procedure TSWFBasedPlaceObject.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFBasedPlaceObject(Source) do
begin
self.FCharacterId := CharacterId;
self.Depth := Depth;
end;
end;
procedure TSWFBasedPlaceObject.SetCharacterId(ID: Word);
begin
FCharacterId := ID;
end;
{
****************************************************** TSWFPlaceObject ******************************************************
}
constructor TSWFPlaceObject.Create;
begin
inherited;
TagID := tagPlaceObject;
FColorTransform := TSWFColorTransform.Create;
ColorTransform.hasAlpha := false;
FMatrix := TSWFMatrix.Create;
end;
destructor TSWFPlaceObject.Destroy;
begin
FColorTransform.Free;
FMatrix.Free;
inherited Destroy;
end;
procedure TSWFPlaceObject.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFPlaceObject(Source) do
begin
if InitColorTransform then self.ColorTransform.REC := ColorTransform.REC;
Self.Matrix.Assign(Matrix);
end;
end;
function TSWFPlaceObject.GetInitColorTransform: Boolean;
begin
Result := FInitColorTransform or ColorTransform.hasAdd or ColorTransform.hasMult;
end;
procedure TSWFPlaceObject.ReadFromStream(be: TBitsEngine);
var
PP: LongInt;
begin
PP := be.BitsStream.Position;
CharacterId := be.ReadWord;
Depth := be.ReadWord;
Matrix.Rec := be.ReadMatrix;
initColorTransform := (be.BitsStream.Position - PP) < BodySize;
if initColorTransform then
ColorTransform.REC := be.ReadColorTransform(false);
end;
procedure TSWFPlaceObject.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(CharacterId);
be.WriteWord(Depth);
be.WriteMatrix(Matrix.Rec);
if initColorTransform then be.WriteColorTransform(ColorTransform.REC);
end;
{
*************************************************** TSWFClipActionRecord ****************************************************
}
procedure TSWFClipActionRecord.Assign(Source: TSWFClipActionRecord);
begin
KeyCode := Source.KeyCode;
EventFlags := Source.EventFlags;
CopyActionList(Source, self);
end;
{
function TSWFClipActionRecord.GetAction(Index: Integer): TSWFAction;
begin
Result := TSWFAction(FActions[index]);
end;
}
function TSWFClipActionRecord.GetActions: TSWFActionList;
begin
Result := self
end;
procedure TSWFClipActionRecord.SetKeyCode(Value: Byte);
begin
FKeyCode := Value;
if Value = 0 then Exclude(FEventFlags, ceKeyPress)
else Include(FEventFlags, ceKeyPress);
end;
{
****************************************************** TSWFClipActions ******************************************************
}
constructor TSWFClipActions.Create;
begin
FActionRecords := TObjectList.Create;
end;
destructor TSWFClipActions.Destroy;
begin
FActionRecords.Free;
inherited Destroy;
end;
function TSWFClipActions.AddActionRecord(EventFlags: TSWFClipEvents; KeyCode: byte): TSWFClipActionRecord;
begin
Result := TSWFClipActionRecord.Create;
Result.EventFlags := EventFlags;
Result.KeyCode := KeyCode;
if KeyCode > 0 then Include(Result.FEventFlags, ceKeyPress);
ActionRecords.Add(Result);
AllEventFlags := AllEventFlags + EventFlags;
end;
procedure TSWFClipActions.Assign(Source: TSWFClipActions);
var
il: Word;
CA: TSWFClipActionRecord;
begin
AllEventFlags := Source.AllEventFlags;
if Source.ActionRecords.Count > 0 then
for il := 0 to Source.ActionRecords.Count - 1 do
begin
With Source.ActionRecord[il] do
CA := self.AddActionRecord(EventFlags, KeyCode);
CA.Assign(Source.ActionRecord[il]);
end;
end;
function TSWFClipActions.Count: integer;
begin
Result := ActionRecords.Count;
end;
function TSWFClipActions.GetActionRecord(Index: Integer): TSWFClipActionRecord;
begin
Result := TSWFClipActionRecord(ActionRecords[index]);
end;
{
***************************************************** TSWFPlaceObject2 ******************************************************
}
constructor TSWFPlaceObject2.Create;
begin
TagID := tagPlaceObject2;
SWFVersion := SWFVer3;
end;
destructor TSWFPlaceObject2.Destroy;
begin
if FMatrix <> nil then FMatrix.Free;
if fClipActions <> nil then fClipActions.Free;
if FColorTransform <> nil then FColorTransform.Free;
end;
procedure TSWFPlaceObject2.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFPlaceObject2(Source) do
begin
if PlaceFlagHasCharacter then Self.CharacterId := CharacterId
else self.PlaceFlagHasCharacter := false;
if PlaceFlagHasClipDepth then Self.ClipDepth := ClipDepth
else self.PlaceFlagHasClipDepth := false;
if PlaceFlagHasRatio then Self.Ratio := Ratio
else self.PlaceFlagHasRatio := false;
if PlaceFlagHasName then Self.Name := Name
else self.PlaceFlagHasName := false;
if PlaceFlagHasMatrix then Self.Matrix.Assign(Matrix)
else self.PlaceFlagHasMatrix := false;
self.PlaceFlagMove := PlaceFlagMove;
self.SWFVersion := SWFVersion;
if PlaceFlagHasColorTransform then Self.ColorTransform.REC := ColorTransform.REC
else self.PlaceFlagHasColorTransform := false;
if PlaceFlagHasClipActions then
self.ClipActions.Assign(ClipActions);
end;
end;
function TSWFPlaceObject2.ClipActions: TSWFClipActions;
begin
if fClipActions = nil then
begin
fClipActions := TSWFClipActions.Create;
PlaceFlagHasClipActions := true;
end;
Result := fClipActions;
end;
function TSWFPlaceObject2.GetColorTransform: TSWFColorTransform;
begin
if FColorTransform = nil then
begin
FColorTransform := TSWFColorTransform.Create;
FColorTransform.hasAlpha := true;
end;
PlaceFlagHasColorTransform := true;
Result := FColorTransform;
end;
function TSWFPlaceObject2.GetMatrix: TSWFMatrix;
begin
if FMatrix = nil then FMatrix := TSWFMatrix.Create;
Result := FMatrix;
PlaceFlagHasMatrix := true;
end;
function TSWFPlaceObject2.MinVersion: Byte;
begin
Result := SWFVer3;
if PlaceFlagHasClipActions then
begin
Result := SWFVer5;
if Result < SWFVersion then Result := SWFVersion;
end;
end;
procedure TSWFPlaceObject2.ReadFromStream(be: TBitsEngine);
var
PP: LongInt;
DW, ActionRecordSize: DWord;
b: Byte;
// w: Word;
AR: TSWFClipActionRecord;
BA: TSWFActionByteCode;
procedure fReadEventFlags(var EF: TSWFClipEvents; RW: dword);
var ab: array[0..3] of byte;
begin
Move(RW, ab, 4);
EF := [];
if CheckBit(ab[0], 8) then Include(EF, ceKeyUp);
if CheckBit(ab[0], 7) then Include(EF, ceKeyDown);
if CheckBit(ab[0], 6) then Include(EF, ceMouseUp);
if CheckBit(ab[0], 5) then Include(EF, ceMouseDown);
if CheckBit(ab[0], 4) then Include(EF, ceMouseMove);
if CheckBit(ab[0], 3) then Include(EF, ceUnload);
if CheckBit(ab[0], 2) then Include(EF, ceEnterFrame);
if CheckBit(ab[0], 1) then Include(EF, ceLoad);
if CheckBit(ab[1], 8) then Include(EF, ceDragOver);
if CheckBit(ab[1], 7) then Include(EF, ceRollOut);
if CheckBit(ab[1], 6) then Include(EF, ceRollOver);
if CheckBit(ab[1], 5) then Include(EF, ceReleaseOutside);
if CheckBit(ab[1], 4) then Include(EF, ceRelease);
if CheckBit(ab[1], 3) then Include(EF, cePress);
if CheckBit(ab[1], 2) then Include(EF, ceInitialize);
if CheckBit(ab[1], 1) then Include(EF, ceData);
if SWFVersion >= SWFVer6 then
begin
if CheckBit(ab[2], 3) then Include(EF, ceConstruct);
if CheckBit(ab[2], 2) then Include(EF, ceKeyPress);
if CheckBit(ab[2], 1) then Include(EF, ceDragOut);
end;
end;
begin
PP := be.BitsStream.Position;
b := be.ReadByte;
PlaceFlagMove := (b and 1) = 1; b := b shr 1;
PlaceFlagHasCharacter := (b and 1) = 1; b := b shr 1;
PlaceFlagHasMatrix := (b and 1) = 1; b := b shr 1;
PlaceFlagHasColorTransform := (b and 1) = 1; b := b shr 1;
PlaceFlagHasRatio := (b and 1) = 1; b := b shr 1;
PlaceFlagHasName := (b and 1) = 1; b := b shr 1;
PlaceFlagHasClipDepth := (b and 1) = 1; b := b shr 1;
PlaceFlagHasClipActions := (b and 1) = 1;
ReadAddonFlag(be);
Depth := be.ReadWord;
if PlaceFlagHasCharacter then CharacterId := be.ReadWord;
if PlaceFlagHasMatrix then Matrix.Rec := be.ReadMatrix;
if PlaceFlagHasColorTransform then ColorTransform.REC := be.ReadColorTransform;
if PlaceFlagHasRatio then Ratio := be.ReadWord;
if PlaceFlagHasName then Name := be.ReadString;
if PlaceFlagHasClipDepth then ClipDepth := be.ReadWord;
ReadFilterFromStream(be);
if PlaceFlagHasClipActions then
begin
{W :=} be.ReadWord;
if SWFVersion >= SWFVer6 then DW := be.ReadDWord else DW := be.ReadWord;
fReadEventFlags(ClipActions.fAllEventFlags, DW);
if (be.BitsStream.Position - PP) < BodySize then
Repeat
if SWFVersion >= SWFVer6 then DW := be.ReadDWord else DW := be.ReadWord;
if (DW > 0) then
begin
AR := TSWFClipActionRecord.Create;
fReadEventFlags(AR.FEventFlags, DW);
ActionRecordSize := be.ReadDWord;
if ceKeyPress in AR.EventFlags then
AR.KeyCode := be.ReadByte;
if ParseActions then
ReadActionList(be, AR, ActionRecordSize)
else
begin
BA := TSWFActionByteCode.Create;
BA.DataSize := ActionRecordSize;
BA.SelfDestroy := true;
GetMem(BA.fData, BA.DataSize);
be.BitsStream.Read(BA.Data^, BA.DataSize);
AR.Add(BA);
end;
ClipActions.ActionRecords.Add(AR);
end;
Until DW = 0;
if ClipActions.ActionRecords.Count = 0 then PlaceFlagHasClipActions := false;
end;
if BodySize > (be.BitsStream.Position - PP) then
be.BitsStream.Position := integer(BodySize) + PP;
end;
procedure TSWFPlaceObject2.SetCharacterId(Value: Word);
begin
FCharacterId := value;
PlaceFlagHasCharacter := true;
end;
procedure TSWFPlaceObject2.SetClipDepth(Value: Word);
begin
FClipDepth := value;
PlaceFlagHasClipDepth := true;
end;
procedure TSWFPlaceObject2.SetName(Value: string);
begin
FName := Value;
PlaceFlagHasName := Value<>'';
end;
procedure TSWFPlaceObject2.SetRatio(Value: Word);
begin
FRatio := Value;
PlaceFlagHasRatio := true;
end;
procedure TSWFPlaceObject2.WriteTagBody(be: TBitsEngine);
var
il, il2: Word;
Offset, Adr: LongInt;
write0, tmpPlaceAction: boolean;
procedure fWriteEventFlags(EF: TSWFClipEvents);
begin
be.WriteBit(ceKeyUp in EF);
be.WriteBit(ceKeyDown in EF);
be.WriteBit(ceMouseUp in EF);
be.WriteBit(ceMouseDown in EF);
be.WriteBit(ceMouseMove in EF);
be.WriteBit(ceUnload in EF);
be.WriteBit(ceEnterFrame in EF);
be.WriteBit(ceLoad in EF);
be.WriteBit(ceDragOver in EF);
be.WriteBit(ceRollOut in EF);
be.WriteBit(ceRollOver in EF);
be.WriteBit(ceReleaseOutside in EF);
be.WriteBit(ceRelease in EF);
be.WriteBit(cePress in EF);
be.WriteBit(ceInitialize in EF);
be.WriteBit(ceData in EF);
if SWFVersion >= SWFVer6 then
begin
be.WriteBits(0, 5);
be.WriteBit(ceConstruct in EF);
be.WriteBit(ceKeyPress in EF);
be.WriteBit(ceDragOut in EF);
be.WriteByte(0);
end;
end;
begin
tmpPlaceAction := PlaceFlagHasClipActions and (ClipActions.ActionRecords.Count > 0);
be.WriteBit(tmpPlaceAction);
be.WriteBit(PlaceFlagHasClipDepth);
be.WriteBit(PlaceFlagHasName);
be.WriteBit(PlaceFlagHasRatio);
be.WriteBit(PlaceFlagHasColorTransform);
be.WriteBit(PlaceFlagHasMatrix);
be.WriteBit(PlaceFlagHasCharacter);
be.WriteBit(PlaceFlagMove);
WriteAddonFlag(be);
be.WriteWord(Depth);
if PlaceFlagHasCharacter then be.WriteWord(CharacterId);
if PlaceFlagHasMatrix then be.WriteMatrix(Matrix.Rec);
if PlaceFlagHasColorTransform then be.WriteColorTransform(ColorTransform.REC);
if PlaceFlagHasRatio then be.WriteWord(Ratio);
if PlaceFlagHasName then be.WriteString(Name);
if PlaceFlagHasClipDepth then be.WriteWord(ClipDepth);
WriteFilterToStream(be);
if tmpPlaceAction then
begin
if SWFVersion < MinVersion then SWFVersion := MinVersion;
be.WriteWord(0);
fWriteEventFlags(ClipActions.AllEventFlags);
if ClipActions.ActionRecords.Count > 0 then
begin
for il:= 0 to ClipActions.ActionRecords.Count - 1 do
with ClipActions.ActionRecord[il] do
begin
fWriteEventFlags(EventFlags);
Offset := be.BitsStream.Position;
be.WriteDWord(0);
if ceKeyPress in EventFlags then be.WriteByte(KeyCode);
if Count > 0 then
begin
For il2 := 0 to Count - 1 do
Action[il2].WriteToStream(be);
case Action[Count - 1].ActionCode of
0, actionOffsetWork: write0 := false;
actionByteCode:
with TSWFActionByteCode(Action[Count - 1]) do
if DataSize = 0 then write0 := true
else write0 := ByteCode[DataSize - 1] <> 0;
else write0 := true;
end;
if write0 then be.WriteByte(0);
end else be.WriteByte(0);
Adr := be.BitsStream.Position;
be.BitsStream.Position := Offset;
Offset := Adr - Offset - 4;
be.BitsStream.Write(Offset, 4);
be.BitsStream.Position := Adr;
end;
if SWFVersion >= SWFVer6 then be.WriteDWord(0) else be.WriteWord(0);
end;
// ClipActions: TSWFClipActions;
end;
end;
procedure TSWFPlaceObject2.ReadFilterFromStream(be: TBitsEngine);
begin
// empty
end;
procedure TSWFPlaceObject2.ReadAddonFlag(be: TBitsEngine);
begin
// empty
end;
procedure TSWFPlaceObject2.WriteAddonFlag(be: TBitsEngine);
begin
// empty
end;
procedure TSWFPlaceObject2.WriteFilterToStream(be: TBitsEngine);
begin
// empty
end;
{
***************************************************** TSWFColorMatrixFilter ******************************************************
}
constructor TSWFColorMatrixFilter.Create;
begin
FFilterID := fidColorMatrix;
end;
procedure TSWFColorMatrixFilter.AdjustColor(Brightness, Contrast, Saturation, Hue: Integer);
var Value: integer;
lumR, lumG, lumB,
cosVal, sinVal, X: single;
FArray: Array [0..24] of single;
const
AContrast: array [0..100] of single = (
0, 0.01, 0.02, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.11,
0.12, 0.14, 0.15, 0.16, 0.17, 0.18, 0.20, 0.21, 0.22, 0.24,
0.25, 0.27, 0.28, 0.30, 0.32, 0.34, 0.36, 0.38, 0.40, 0.42,
0.44, 0.46, 0.48, 0.5, 0.53, 0.56, 0.59, 0.62, 0.65, 0.68,
0.71, 0.74, 0.77, 0.80, 0.83, 0.86, 0.89, 0.92, 0.95, 0.98,
1.0, 1.06, 1.12, 1.18, 1.24, 1.30, 1.36, 1.42, 1.48, 1.54,
1.60, 1.66, 1.72, 1.78, 1.84, 1.90, 1.96, 2.0, 2.12, 2.25,
2.37, 2.50, 2.62, 2.75, 2.87, 3.0, 3.2, 3.4, 3.6, 3.8,
4.0, 4.3, 4.7, 4.9, 5.0, 5.5, 6.0, 6.5, 6.8, 7.0,
7.3, 7.5, 7.8, 8.0, 8.4, 8.7, 9.0, 9.4, 9.6, 9.8,
10.0);
procedure FCheckValue(V: integer; Max: byte);
begin
if V < -Max then Value := - Max else
if V > Max then Value := Max else Value := V;
end;
procedure MultMatrix(A: Array of single);
var i, j, k: byte;
col: array [0..4] of single;
V: single;
begin
for i := 0 to 4 do
begin
for j := 0 to 4 do
col[j] := FArray[j+i*5];
for j :=0 to 4 do
begin
V := 0;
for k := 0 to 4 do
V := V + A[j+k*5]*col[k];
FArray[j+i*5] := V;
end;
end;
end;
begin
ResetValues;
FillChar(FArray, SizeOf(FArray), 0);
FArray[0] := 1;
FArray[6] := 1;
FArray[12] := 1;
FArray[18] := 1;
FArray[24] := 1;
if Hue <> 0 then
begin
FCheckValue(Hue, 180);
cosVal := cos(Value / 180 * PI);
sinVal := sin(Value / 180 * PI);
lumR := 0.213;
lumG := 0.715;
lumB := 0.072;
MultMatrix([
lumR+cosVal*(1-lumR)+sinVal*(-lumR),lumG+cosVal*(-lumG)+sinVal*(-lumG),lumB+cosVal*(-lumB)+sinVal*(1-lumB),0,0,
lumR+cosVal*(-lumR)+sinVal*(0.143),lumG+cosVal*(1-lumG)+sinVal*(0.140),lumB+cosVal*(-lumB)+sinVal*(-0.283),0,0,
lumR+cosVal*(-lumR)+sinVal*(-(1-lumR)),lumG+cosVal*(-lumG)+sinVal*(lumG),lumB+cosVal*(1-lumB)+sinVal*(lumB),0,0,
0,0,0,1,0,
0,0,0,0,1]);
end;
if Contrast <> 0 then
begin
FCheckValue(Contrast, 100);
if Value < 0 then X := 127 + Value/100*127
else
begin
X := Value mod 1;
if (X = 0)
then
X := AContrast[Round(Value)]
else
X := AContrast[Trunc(Value)]*(1-X) + AContrast[Trunc(Value)+1]*X;
X := X*127 + 127;
end;
MultMatrix([
X/127,0,0,0,0.5*(127-X),
0,X/127,0,0,0.5*(127-X),
0,0,X/127,0,0.5*(127-X),
0,0,0,1,0,
0,0,0,0,1]);
end;
if Brightness <> 0 then
begin
FCheckValue(Brightness, 100);
MultMatrix([
1,0,0,0,Value,
0,1,0,0,Value,
0,0,1,0,Value,
0,0,0,1,0,
0,0,0,0,1]);
end;
if Saturation <> 0 then
begin
FCheckValue(Saturation, 100);
if (Value > 0)
then
X := 1+ 3*Value/100
else
X := Value/100 + 1;
lumR := 0.3086;
lumG := 0.6094;
lumB := 0.0820;
MultMatrix([
lumr*(1-x)+x,lumg*(1-x),lumb*(1-x),0,0,
lumr*(1-x),lumg*(1-x)+x,lumb*(1-x),0,0,
lumr*(1-x),lumg*(1-x),lumb*(1-x)+x,0,0,
0,0,0,1,0,
0,0,0,0,1]);
end;
Move(FArray, FMatrix, SizeOf(FMatrix));
end;
procedure TSWFColorMatrixFilter.Assign(Source: TSWFFilter);
var il: byte;
begin
with TSWFColorMatrixFilter(Source) do
for il := 0 to 19 do
self.Matrix[il] := Matrix[il];
end;
function TSWFColorMatrixFilter.GetMatrix(Index: Integer): single;
begin
Result := FMatrix[index];
end;
function TSWFColorMatrixFilter.GetR0: single;
begin
Result := FMatrix[0];
end;
function TSWFColorMatrixFilter.GetR1: single;
begin
Result := FMatrix[1];
end;
function TSWFColorMatrixFilter.GetR2: single;
begin
Result := FMatrix[2];
end;
function TSWFColorMatrixFilter.GetR3: single;
begin
Result := FMatrix[3];
end;
function TSWFColorMatrixFilter.GetR4: single;
begin
Result := FMatrix[4];
end;
function TSWFColorMatrixFilter.GetG0: single;
begin
Result := FMatrix[5];
end;
function TSWFColorMatrixFilter.GetG1: single;
begin
Result := FMatrix[6];
end;
function TSWFColorMatrixFilter.GetG2: single;
begin
Result := FMatrix[7];
end;
function TSWFColorMatrixFilter.GetG3: single;
begin
Result := FMatrix[8];
end;
function TSWFColorMatrixFilter.GetG4: single;
begin
Result := FMatrix[9];
end;
function TSWFColorMatrixFilter.GetB0: single;
begin
Result := FMatrix[10];
end;
function TSWFColorMatrixFilter.GetB1: single;
begin
Result := FMatrix[11];
end;
function TSWFColorMatrixFilter.GetB2: single;
begin
Result := FMatrix[12];
end;
function TSWFColorMatrixFilter.GetB3: single;
begin
Result := FMatrix[13];
end;
function TSWFColorMatrixFilter.GetB4: single;
begin
Result := FMatrix[14];
end;
function TSWFColorMatrixFilter.GetA0: single;
begin
Result := FMatrix[15];
end;
function TSWFColorMatrixFilter.GetA1: single;
begin
Result := FMatrix[16];
end;
function TSWFColorMatrixFilter.GetA2: single;
begin
Result := FMatrix[17];
end;
function TSWFColorMatrixFilter.GetA3: single;
begin
Result := FMatrix[18];
end;
function TSWFColorMatrixFilter.GetA4: single;
begin
Result := FMatrix[19];
end;
procedure TSWFColorMatrixFilter.ReadFromStream(be: TBitsEngine);
var il: byte;
begin
for il := 0 to 19 do
Matrix[il] := be.ReadFloat;
end;
procedure TSWFColorMatrixFilter.SetMatrix(Index: Integer; const Value: single);
begin
FMatrix[index] := Value;
end;
procedure TSWFColorMatrixFilter.SetR0(const Value: single);
begin
FMatrix[0] := Value;
end;
procedure TSWFColorMatrixFilter.SetR1(const Value: single);
begin
FMatrix[1] := Value;
end;
procedure TSWFColorMatrixFilter.SetR2(const Value: single);
begin
FMatrix[2] := Value;
end;
procedure TSWFColorMatrixFilter.SetR3(const Value: single);
begin
FMatrix[3] := Value;
end;
procedure TSWFColorMatrixFilter.SetR4(const Value: single);
begin
FMatrix[4] := Value;
end;
procedure TSWFColorMatrixFilter.SetG0(const Value: single);
begin
FMatrix[5] := Value;
end;
procedure TSWFColorMatrixFilter.SetG1(const Value: single);
begin
FMatrix[6] := Value;
end;
procedure TSWFColorMatrixFilter.SetG2(const Value: single);
begin
FMatrix[7] := Value;
end;
procedure TSWFColorMatrixFilter.SetG3(const Value: single);
begin
FMatrix[8] := Value;
end;
procedure TSWFColorMatrixFilter.SetG4(const Value: single);
begin
FMatrix[9] := Value;
end;
procedure TSWFColorMatrixFilter.SetB0(const Value: single);
begin
FMatrix[10] := Value;
end;
procedure TSWFColorMatrixFilter.SetB1(const Value: single);
begin
FMatrix[11] := Value;
end;
procedure TSWFColorMatrixFilter.SetB2(const Value: single);
begin
FMatrix[12] := Value;
end;
procedure TSWFColorMatrixFilter.SetB3(const Value: single);
begin
FMatrix[13] := Value;
end;
procedure TSWFColorMatrixFilter.SetB4(const Value: single);
begin
FMatrix[14] := Value;
end;
procedure TSWFColorMatrixFilter.SetA0(const Value: single);
begin
FMatrix[15] := Value;
end;
procedure TSWFColorMatrixFilter.SetA1(const Value: single);
begin
FMatrix[16] := Value;
end;
procedure TSWFColorMatrixFilter.SetA2(const Value: single);
begin
FMatrix[17] := Value;
end;
procedure TSWFColorMatrixFilter.SetA3(const Value: single);
begin
FMatrix[18] := Value;
end;
procedure TSWFColorMatrixFilter.SetA4(const Value: single);
begin
FMatrix[19] := Value;
end;
procedure TSWFColorMatrixFilter.ResetValues;
begin
FillChar(FMatrix, SizeOf(FMatrix), 0);
FMatrix[0] := 1;
FMatrix[6] := 1;
FMatrix[12] := 1;
FMatrix[18] := 1;
end;
procedure TSWFColorMatrixFilter.WriteToStream(be: TBitsEngine);
var il: byte;
begin
be.WriteByte(FFilterID);
for il := 0 to 19 do
be.WriteFloat(Matrix[il]);
end;
{
***************************************************** TSWFConvolutionFilter ******************************************************
}
constructor TSWFConvolutionFilter.Create;
begin
FFilterID := fidConvolution;
FDefaultColor := TSWFRGBA.Create(true);
FMatrix := TList.Create;
end;
destructor TSWFConvolutionFilter.Destroy;
begin
FDefaultColor.Free;
FMatrix.Free;
inherited;
end;
procedure TSWFConvolutionFilter.Assign(Source: TSWFFilter);
var il: byte;
begin
with TSWFConvolutionFilter(Source) do
begin
self.Bias := Bias;
self.Clamp := Clamp;
self.Divisor := Divisor;
self.DefaultColor.Assign(DefaultColor);
self.MatrixX := MatrixX;
self.MatrixY := MatrixY;
self.PreserveAlpha := PreserveAlpha;
for il := 0 to MatrixX*MatrixY-1 do
self.Matrix[il] := Matrix[il];
end;
end;
function TSWFConvolutionFilter.GetMatrix(Index: Integer): single;
var LW: longword;
begin
while (Index+1) > FMatrix.Count do FMatrix.Add(nil);
LW := LongInt(FMatrix.Items[Index]);
Move(LW, Result, 4);
end;
procedure TSWFConvolutionFilter.ReadFromStream(be: TBitsEngine);
var il, b: byte;
begin
MatrixX := be.ReadByte;
MatrixY := be.ReadByte;
Divisor := be.ReadSingle;
Bias := be.ReadSingle;
for il := 0 to MatrixX*MatrixY-1 do
Matrix[il] := be.ReadSingle;
DefaultColor.RGBA := be.ReadRGBA;
b := be.ReadByte;
Clamp := CheckBit(b, 2);
PreserveAlpha := CheckBit(b, 1);
end;
procedure TSWFConvolutionFilter.SetMatrix(Index: Integer; const Value: single);
var LW: longword;
begin
while (Index+1) > FMatrix.Count do FMatrix.Add(nil);
Move(Value, LW, 4);
FMatrix.Items[Index] := Pointer(LW);
end;
procedure TSWFConvolutionFilter.WriteToStream(be: TBitsEngine);
var il: byte;
begin
be.WriteByte(FFilterID);
be.WriteByte(MatrixX);
be.WriteByte(MatrixY);
be.WriteSingle(Divisor);
be.WriteSingle(Bias);
for il := 0 to MatrixX*MatrixY-1 do
be.WriteSingle(Matrix[il]);
be.WriteColor(DefaultColor.RGBA);
be.WriteByte(byte(Clamp) shl 1 + byte(PreserveAlpha));
end;
{
***************************************************** TSWFBlurFilter ******************************************************
}
constructor TSWFBlurFilter.Create;
begin
FFilterID := fidBlur;
Passes := 1;
end;
procedure TSWFBlurFilter.Assign(Source: TSWFFilter);
begin
With TSWFBlurFilter(Source) do
begin
self.BlurX := BlurX;
self.BlurY := BlurY;
self.Passes := Passes;
end;
end;
procedure TSWFBlurFilter.ReadFromStream(be: TBitsEngine);
var b: byte;
begin
BlurX := be.ReadSingle;
BlurY := be.ReadSingle;
b := be.ReadByte;
Passes := b shr 3;
end;
procedure TSWFBlurFilter.WriteToStream(be: TBitsEngine);
begin
be.WriteByte(FFilterID);
be.WriteSingle(BlurX);
be.WriteSingle(BlurY);
be.WriteByte(Passes shl 3);
end;
{
***************************************************** TSWFDropShadowFilter ******************************************************
}
constructor TSWFGlowFilter.Create;
begin
FFilterID := fidGlow;
FGlowColor := TSWFRGBA.Create(true);
CompositeSource := true;
end;
destructor TSWFGlowFilter.Destroy;
begin
FGlowColor.Free;
inherited;
end;
procedure TSWFGlowFilter.Assign(Source: TSWFFilter);
begin
inherited;
with TSWFGlowFilter(Source) do
begin
self.CompositeSource := CompositeSource;
self.InnerGlow := InnerGlow;
self.Knockout := Knockout;
self.Strength := Strength;
self.GlowColor.Assign(GlowColor);
end;
end;
procedure TSWFGlowFilter.ReadFromStream(be: TBitsEngine);
var b: byte;
begin
GlowColor.RGBA := be.ReadRGBA;
BlurX := be.ReadSingle;
BlurY := be.ReadSingle;
Strength := WordToSingle(be.ReadWord);
b := be.ReadByte;
InnerGlow := CheckBit(b, 8);
Knockout := CheckBit(b, 7);
CompositeSource := CheckBit(b, 6);
Passes := b and 31;
end;
procedure TSWFGlowFilter.WriteToStream(be: TBitsEngine);
begin
be.WriteByte(FFilterID);
be.WriteColor(GlowColor.RGBA);
be.WriteSingle(BlurX);
be.WriteSingle(BlurY);
be.WriteWord(SingleToWord(Strength));
be.WriteByte(byte(InnerGlow) shl 7 +
byte(Knockout) shl 6 +
byte(CompositeSource) shl 5 +
(Passes and 31));
end;
{
***************************************************** TSWFDropShadowFilter ******************************************************
}
constructor TSWFDropShadowFilter.Create;
begin
FFilterID := fidDropShadow;
FDropShadowColor := TSWFRGBA.Create(true);
CompositeSource := true;
DropShadowColor.A := $FF;
end;
destructor TSWFDropShadowFilter.Destroy;
begin
FDropShadowColor.Free;
inherited;
end;
procedure TSWFDropShadowFilter.Assign(Source: TSWFFilter);
begin
inherited;
with TSWFDropShadowFilter(Source) do
begin
self.Angle := Angle;
self.CompositeSource := CompositeSource;
self.Distance := Distance;
self.InnerShadow := InnerShadow;
self.Knockout := Knockout;
self.Strength := Strength;
self.DropShadowColor.Assign(DropShadowColor);
end;
end;
procedure TSWFDropShadowFilter.ReadFromStream(be: TBitsEngine);
var b: byte;
begin
DropShadowColor.RGBA := be.ReadRGBA;
BlurX := be.ReadSingle;
BlurY := be.ReadSingle;
Angle := be.ReadSingle;
Distance := be.ReadSingle;
Strength := WordToSingle(be.ReadWord);
b := be.ReadByte;
InnerShadow := CheckBit(b, 8);
Knockout := CheckBit(b, 7);
CompositeSource := CheckBit(b, 6);
Passes := b and 31;
end;
procedure TSWFDropShadowFilter.WriteToStream(be: TBitsEngine);
begin
be.WriteByte(FFilterID);
be.WriteColor(DropShadowColor.RGBA);
be.WriteSingle(BlurX);
be.WriteSingle(BlurY);
be.WriteSingle(Angle);
be.WriteSingle(Distance);
be.WriteWord(SingleToWord(Strength));
be.WriteByte(byte(InnerShadow) shl 7 +
byte(Knockout) shl 6 +
byte(CompositeSource) shl 5 +
(Passes and 31));
end;
{
***************************************************** TSWFBevelFilter ******************************************************
}
constructor TSWFBevelFilter.Create;
begin
FFilterID := fidBevel;
FShadowColor := TSWFRGBA.Create(True);
FHighlightColor := TSWFRGBA.Create(True);
CompositeSource := true;
end;
destructor TSWFBevelFilter.Destroy;
begin
FHighlightColor.Free;
FShadowColor.Free;
inherited;
end;
procedure TSWFBevelFilter.Assign(Source: TSWFFilter);
begin
inherited;
with TSWFBevelFilter(Source) do
begin
self.Angle := Angle;
self.CompositeSource := CompositeSource;
self.Distance := Distance;
self.InnerShadow := InnerShadow;
self.Knockout := Knockout;
self.OnTop := OnTop;
self.Strength := Strength;
self.HighlightColor.Assign(HighlightColor);
self.ShadowColor.Assign(ShadowColor);
end;
end;
procedure TSWFBevelFilter.ReadFromStream(be: TBitsEngine);
var b: byte;
begin
ShadowColor.RGBA := be.ReadRGBA;
HighlightColor.RGBA := be.ReadRGBA;
BlurX := be.ReadSingle;
BlurY := be.ReadSingle;
Angle := be.ReadSingle;
Distance := be.ReadSingle;
Strength := WordToSingle(be.ReadWord);
b := be.ReadByte;
InnerShadow := CheckBit(b, 8);
Knockout := CheckBit(b, 7);
CompositeSource := CheckBit(b, 6);
OnTop := CheckBit(b, 5);
Passes := b and 15;
end;
procedure TSWFBevelFilter.WriteToStream(be: TBitsEngine);
begin
be.WriteByte(FFilterID);
be.WriteColor(ShadowColor.RGBA);
be.WriteColor(HighlightColor.RGBA);
be.WriteSingle(BlurX);
be.WriteSingle(BlurY);
be.WriteSingle(Angle);
be.WriteSingle(Distance);
be.WriteWord(SingleToWord(Strength));
be.WriteByte(byte(InnerShadow) shl 7 +
byte(Knockout) shl 6 +
byte(CompositeSource) shl 5 +
byte(OnTop) shl 4 +
(Passes and 15));
end;
{
************************************************** TSWFGradientGlowFilter ****************************************************
}
constructor TSWFGradientGlowFilter.Create;
begin
FFilterID := fidGradientGlow;
CompositeSource := true;
NumColors := 2;
FColor[1] := TSWFRGBA.Create(true);
FColor[2] := TSWFRGBA.Create(true);
FRatio[1] := 0;
FRatio[2] := 255;
end;
destructor TSWFGradientGlowFilter.Destroy;
var
il: Byte;
begin
For il := 1 to 15 do
if FColor[il] <> nil then FreeAndNil(FColor[il]);
inherited;
end;
procedure TSWFGradientGlowFilter.Assign(Source: TSWFFilter);
var il: integer;
begin
inherited;
with TSWFGradientGlowFilter(Source) do
begin
self.Angle := Angle;
self.CompositeSource := CompositeSource;
self.Distance := Distance;
self.InnerShadow := InnerShadow;
self.Knockout := Knockout;
self.OnTop := OnTop;
self.Strength := Strength;
self.NumColors := NumColors;
for il := 1 to NumColors do
begin
self.GradientRatio[il] := GradientRatio[il];
self.GradientColor[il].Assign(GradientColor[il]);
end;
end;
end;
function TSWFGradientGlowFilter.GetGradient(Index: byte): TSWFGradientRec;
begin
Result.color := GradientColor[index].RGBA;
Result.Ratio := FRatio[index];
end;
function TSWFGradientGlowFilter.GetGradientColor(Index: Integer): TSWFRGBA;
begin
if FColor[index] = nil then FColor[index] := TSWFRGBA.Create;
Result := FColor[index];
end;
function TSWFGradientGlowFilter.GetGradientRatio(Index: Integer): Byte;
begin
Result := FRatio[index];
end;
procedure TSWFGradientGlowFilter.ReadFromStream(be: TBitsEngine);
var b, il: byte;
begin
NumColors := be.ReadByte;
for il := 1 to NumColors do
GradientColor[il].RGBA := be.ReadRGBA;
for il := 1 to NumColors do
GradientRatio[il] := be.ReadByte;
BlurX := be.ReadSingle;
BlurY := be.ReadSingle;
Angle := be.ReadSingle;
Distance := be.ReadSingle;
Strength := WordToSingle(be.ReadWord);
b := be.ReadByte;
InnerShadow := CheckBit(b, 8);
Knockout := CheckBit(b, 7);
CompositeSource := CheckBit(b, 6);
OnTop := CheckBit(b, 5);
Passes := b and 15;
end;
procedure TSWFGradientGlowFilter.SetGradientRatio(Index: Integer; Value: Byte);
begin
FRatio[index] := Value;
end;
procedure TSWFGradientGlowFilter.WriteToStream(be: TBitsEngine);
var il: byte;
begin
be.WriteByte(FFilterID);
be.WriteByte(NumColors);
for il := 1 to NumColors do
be.WriteColor(GradientColor[il].RGBA);
for il := 1 to NumColors do
be.WriteByte(GradientRatio[il]);
be.WriteSingle(BlurX);
be.WriteSingle(BlurY);
be.WriteSingle(Angle);
be.WriteSingle(Distance);
be.WriteWord(SingleToWord(Strength));
be.WriteByte(byte(InnerShadow) shl 7 +
byte(Knockout) shl 6 +
byte(CompositeSource) shl 5 +
byte(OnTop) shl 4 +
(Passes and 15));
end;
{
************************************************ TSWFGradientBevelFilter **************************************************
}
constructor TSWFGradientBevelFilter.Create;
begin
inherited;
FFilterID := fidGradientBevel;
end;
{
***************************************************** TSWFFilterList ******************************************************
}
function TSWFFilterList.GetFilter(Index: Integer): TSWFFilter;
begin
Result := TSWFFilter(Items[Index]);
end;
function TSWFFilterList.AddFilter(id: TSwfFilterID): TSWFFilter;
begin
Result := nil;
case id of
fidDropShadow:
Result := TSWFDropShadowFilter.Create;
fidBlur:
Result := TSWFBlurFilter.Create;
fidGlow:
Result := TSWFGlowFilter.Create;
fidBevel:
Result := TSWFBevelFilter.Create;
fidGradientGlow:
Result := TSWFGradientGlowFilter.Create;
fidConvolution:
Result := TSWFConvolutionFilter.Create;
fidColorMatrix:
Result := TSWFColorMatrixFilter.Create;
fidGradientBevel:
Result := TSWFGradientBevelFilter.Create;
end;
Add(Result);
end;
procedure TSWFFilterList.ReadFromStream(be: TBitsEngine);
var c, il: byte;
begin
c := be.ReadByte;
if c > 0 then
for il := 0 to c - 1 do
AddFilter(be.ReadByte).ReadFromStream(be);
end;
procedure TSWFFilterList.WriteToStream(be: TBitsEngine);
var il: integer;
begin
be.WriteByte(Count);
for il := 0 to Count - 1 do
Filter[il].WriteToStream(be);
end;
{
***************************************************** TSWFPlaceObject3 ******************************************************
}
constructor TSWFPlaceObject3.Create;
begin
TagID := tagPlaceObject3;
SWFVersion := SWFVer8;
end;
destructor TSWFPlaceObject3.Destroy;
begin
inherited;
if FSurfaceFilterList <> nil then FSurfaceFilterList.Free;
end;
procedure TSWFPlaceObject3.Assign(Source: TBasedSWFObject);
var il: byte;
begin
inherited;
with TSWFPlaceObject3(Source) do
begin
self.PlaceFlagHasImage := PlaceFlagHasImage;
self.PlaceFlagHasClassName := PlaceFlagHasClassName;
self._ClassName := _ClassName;
self.PlaceFlagHasCacheAsBitmap := PlaceFlagHasCacheAsBitmap;
self.PlaceFlagHasBlendMode := PlaceFlagHasBlendMode;
if PlaceFlagHasBlendMode then
self.BlendMode := BlendMode;
self.PlaceFlagHasFilterList := PlaceFlagHasFilterList;
if PlaceFlagHasFilterList then
begin
self.SurfaceFilterList.Clear;
for il := 0 to SurfaceFilterList.Count - 1 do
self.SurfaceFilterList.AddFilter(SurfaceFilterList.Filter[il].FilterID).Assign(SurfaceFilterList.Filter[il]);
end;
end;
end;
function TSWFPlaceObject3.GetSurfaceFilterList: TSWFFilterList;
begin
if FSurfaceFilterList = nil then
begin
FSurfaceFilterList := TSWFFilterList.Create;
PlaceFlagHasFilterList := true;
end;
Result := FSurfaceFilterList;
end;
function TSWFPlaceObject3.MinVersion: Byte;
begin
Result := SWFVer8 + Byte(PlaceFlagHasImage or PlaceFlagHasClassName);
end;
procedure TSWFPlaceObject3.ReadAddonFlag(be: TBitsEngine);
var b: byte;
begin
b := be.ReadByte;
if SWFVersion = SWFVer9 then
begin
PlaceFlagHasImage := CheckBit(b, 5);
PlaceFlagHasClassName := CheckBit(b, 4);
end else
begin
PlaceFlagHasImage := false;
PlaceFlagHasClassName := false;
end;
PlaceFlagHasCacheAsBitmap := CheckBit(b, 3);
PlaceFlagHasBlendMode := CheckBit(b, 2);
PlaceFlagHasFilterList := CheckBit(b, 1);
if PlaceFlagHasClassName or (PlaceFlagHasImage and PlaceFlagHasCharacter) then
_ClassName := be.ReadString;
end;
procedure TSWFPlaceObject3.ReadFilterFromStream(be: TBitsEngine);
begin
if PlaceFlagHasFilterList then SurfaceFilterList.ReadFromStream(be);
if PlaceFlagHasBlendMode then BlendMode := be.ReadByte;
end;
procedure TSWFPlaceObject3.SetClassName(const Value: string);
begin
FClassName := Value;
PlaceFlagHasClassName := Value <> '';
end;
procedure TSWFPlaceObject3.WriteAddonFlag(be: TBitsEngine);
var b: byte;
begin
if SaveAsPO2 then Exit;
b := byte(PlaceFlagHasImage) shl 4 +
byte(PlaceFlagHasClassName) shl 3 +
byte(PlaceFlagHasCacheAsBitmap) shl 2 +
byte(PlaceFlagHasBlendMode) shl 1 +
byte(PlaceFlagHasFilterList and (FSurfaceFilterList.Count > 0));
be.WriteByte(b);
if PlaceFlagHasClassName or (PlaceFlagHasImage and PlaceFlagHasCharacter) then
be.WriteString(_ClassName);
end;
procedure TSWFPlaceObject3.WriteFilterToStream(be: TBitsEngine);
begin
if SaveAsPO2 then Exit;
if PlaceFlagHasFilterList and (SurfaceFilterList.Count > 0) then
SurfaceFilterList.WriteToStream(be);
if PlaceFlagHasBlendMode then be.WriteByte(BlendMode);
end;
{
***************************************************** TSWFRemoveObject ******************************************************
}
constructor TSWFRemoveObject.Create;
begin
inherited;
TagID := tagRemoveObject;
end;
procedure TSWFRemoveObject.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFRemoveObject(Source) do
begin
self.CharacterID := CharacterID;
self.Depth := Depth;
end;
end;
procedure TSWFRemoveObject.ReadFromStream(be: TBitsEngine);
begin
CharacterID := be.ReadWord;
Depth := be.ReadWord;
end;
procedure TSWFRemoveObject.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(CharacterID);
be.WriteWord(Depth);
end;
{
***************************************************** TSWFRemoveObject2 *****************************************************
}
constructor TSWFRemoveObject2.Create;
begin
inherited;
TagID := tagRemoveObject2;
end;
procedure TSWFRemoveObject2.Assign(Source: TBasedSWFObject);
begin
inherited;
Depth := TSWFRemoveObject2(Source).Depth;
end;
function TSWFRemoveObject2.MinVersion: Byte;
begin
result := SWFVer3;
end;
procedure TSWFRemoveObject2.ReadFromStream(be: TBitsEngine);
begin
Depth := be.ReadWord;
end;
procedure TSWFRemoveObject2.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(Depth);
end;
{
******************************************************* TSWFShowFrame *******************************************************
}
constructor TSWFShowFrame.Create;
begin
TagID := tagShowFrame;
end;
// =========================================================
// Shape
// =========================================================
{
******************************************************* TSWFLineStyle *******************************************************
}
constructor TSWFLineStyle.Create;
begin
FColor := TSWFRGBA.Create;
end;
destructor TSWFLineStyle.Destroy;
begin
FColor.Free;
inherited Destroy;
end;
procedure TSWFLineStyle.Assign(Source: TSWFLineStyle);
begin
Width := Source.Width;
Color.Assign(Source.Color);
end;
procedure TSWFLineStyle.ReadFromStream(be: TBitsEngine);
begin
Width := be.ReadWord;
if Color.hasAlpha then Color.RGBA := be.ReadRGBA
else Color.RGB := be.ReadRGB;
end;
procedure TSWFLineStyle.WriteToStream(be: TBitsEngine);
begin
be.WriteWord(Width);
if Color.hasAlpha then be.WriteColor(Color.RGBA)
else be.WriteColor(Color.RGB);
end;
{
******************************************************* TSWFLineStyle2 *******************************************************
}
constructor TSWFLineStyle2.Create;
begin
inherited;
FColor.HasAlpha := true;
end;
destructor TSWFLineStyle2.Destroy;
begin
if FFillStyle <> nil then FFillStyle.Free;
inherited;
end;
procedure TSWFLineStyle2.Assign(Source: TSWFLineStyle);
var Source2: TSWFLineStyle2;
begin
inherited;
if Source is TSWFLineStyle2 then
begin
Source2 := Source as TSWFLineStyle2;
HasFillFlag := Source2.HasFillFlag;
StartCapStyle := Source2.StartCapStyle;
JoinStyle := Source2.JoinStyle;
NoClose := Source2.NoClose;
NoHScaleFlag := Source2.NoHScaleFlag;
NoVScaleFlag := Source2.NoVScaleFlag;
PixelHintingFlag := Source2.PixelHintingFlag;
EndCapStyle := Source2.EndCapStyle;
MiterLimitFactor := Source2.MiterLimitFactor;
if HasFillFlag then
GetFillStyle(Source2.FFillStyle.SWFFillType).Assign(Source2.FFillStyle);
end;
end;
function TSWFLineStyle2.GetFillStyle(style: integer): TSWFFillStyle;
var fmake: boolean;
begin
if style > -1 then
begin
fmake := true;
if FFillStyle <> nil then
begin
if FFillStyle.SWFFillType <> style then FFillStyle.Free
else fmake := false;
end;
if fmake then
case style of
SWFFillSolid:
FFillStyle := TSWFColorFill.Create;
SWFFillLinearGradient, SWFFillRadialGradient:
FFillStyle := TSWFGradientFill.Create;
SWFFillFocalGradient:
FFillStyle := TSWFFocalGradientFill.Create;
SWFFillTileBitmap, SWFFillClipBitmap,
SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap:
FFillStyle := TSWFImageFill.Create;
end;
FFillStyle.hasAlpha := true;
FFillStyle.SWFFillType := style;
end;
Result := FFillStyle;
end;
procedure TSWFLineStyle2.ReadFromStream(be: TBitsEngine);
var b: byte;
begin
Width := be.ReadWord;
b := be.ReadByte;
StartCapStyle := b shr 6;
JoinStyle := (b shr 4) and 3;
HasFillFlag := CheckBit(b, 4);
NoHScaleFlag := CheckBit(b, 3);
NoVScaleFlag := CheckBit(b, 2);
PixelHintingFlag := CheckBit(b, 1);
b := be.ReadByte;
NoClose := CheckBit(b, 3);
EndCapStyle := b and 3;
if JoinStyle = 2 then
MiterLimitFactor := WordToSingle(be.ReadWord);
if HasFillFlag
then GetFillStyle(be.ReadByte).ReadFromStream(be)
else Color.RGBA := be.ReadRGBA;
end;
procedure TSWFLineStyle2.WriteToStream(be: TBitsEngine);
begin
be.WriteWord(Width);
be.WriteBits(StartCapStyle, 2);
be.WriteBits(JoinStyle, 2);
be.WriteBit(HasFillFlag);
be.WriteBit(NoHScaleFlag);
be.WriteBit(NoVScaleFlag);
be.WriteBit(PixelHintingFlag);
be.WriteBits(0, 5);
be.WriteBit(NoClose);
be.WriteBits(EndCapStyle, 2);
if JoinStyle = 2 then
be.WriteWord(SingleToWord(MiterLimitFactor));
if HasFillFlag
then GetFillStyle(-1).WriteToStream(be)
else be.WriteColor(Color.RGBA);
end;
{
******************************************************* TSWFFillStyle *******************************************************
}
procedure TSWFFillStyle.Assign(Source: TSWFFillStyle);
begin
hasAlpha := Source.hasAlpha;
FSWFFillType := Source.FSWFFillType;
end;
{
******************************************************* TSWFColorFill *******************************************************
}
constructor TSWFColorFill.Create;
begin
inherited ;
SWFFillType := SWFFillSolid;
FColor := TSWFRGBA.Create;
end;
destructor TSWFColorFill.Destroy;
begin
FColor.Free;
inherited Destroy;
end;
procedure TSWFColorFill.Assign(Source: TSWFFillStyle);
begin
inherited;
Color.Assign(TSWFColorFill(Source).Color);
end;
procedure TSWFColorFill.ReadFromStream(be: TBitsEngine);
begin
if hasAlpha
then Color.RGBA := be.ReadRGBA
else Color.RGB := be.ReadRGB;
Color.HasAlpha := hasAlpha;
end;
procedure TSWFColorFill.WriteToStream(be: TBitsEngine);
begin
be.WriteByte(SWFFillType);
if hasAlpha then be.WriteColor(Color.RGBA) else be.WriteColor(Color.RGB);
end;
{
******************************************************* TSWFImageFill *******************************************************
}
constructor TSWFImageFill.Create;
begin
inherited ;
SWFFillType := SWFFillClipBitmap;
FMatrix := TSWFMatrix.Create;
end;
destructor TSWFImageFill.Destroy;
begin
FMatrix.Free;
inherited Destroy;
end;
procedure TSWFImageFill.Assign(Source: TSWFFillStyle);
begin
inherited;
with TSWFImageFill(Source) do
begin
self.Matrix.Assign(Matrix);
self.ImageID := ImageID;
end;
end;
procedure TSWFImageFill.ReadFromStream(be: TBitsEngine);
begin
ImageID := be.ReadWord;
Matrix.Rec := be.ReadMatrix;
end;
procedure TSWFImageFill.ScaleTo(Frame: TRect; W, H: word);
begin
Matrix.SetTranslate(Frame.Left - twips div 4, Frame.Top - twips div 4);
Matrix.SetScale((Frame.Right - Frame.Left)/W + $f0 / specFixed,
(Frame.Bottom - Frame.Top)/H + $f0 / specFixed);
end;
procedure TSWFImageFill.WriteToStream(be: TBitsEngine);
begin
be.WriteByte(SWFFillType);
be.WriteWord(ImageID);
be.WriteMatrix(Matrix.Rec);
end;
{
*************************************************** TSWFBaseGradientFill ****************************************************
}
constructor TSWFBaseGradientFill.Create;
begin
inherited ;
SWFFillType := SWFFillLinearGradient;
FColor[1] := TSWFRGBA.Create;
FColor[2] := TSWFRGBA.Create;
end;
destructor TSWFBaseGradientFill.Destroy;
var
il: Byte;
begin
For il := 1 to 15 do
if FColor[il] <> nil then FreeAndNil(FColor[il]);
inherited Destroy;
end;
procedure TSWFBaseGradientFill.Assign(Source: TSWFFillStyle);
var
il: Byte;
begin
inherited;
with TSWFBaseGradientFill(Source) do
begin
self.Count := Count;
if Count > 0 then
For il := 1 to Count do
begin
self.FRatio[il] := FRatio[il];
self.GradientColor[il].Assign(GradientColor[il]);
end;
end;
end;
function TSWFBaseGradientFill.GetGradient(Index: byte): TSWFGradientRec;
begin
Result.color := GradientColor[index].RGBA;
Result.Ratio := FRatio[index];
end;
function TSWFBaseGradientFill.GetGradientColor(Index: Integer): TSWFRGBA;
begin
if FColor[index] = nil then FColor[index] := TSWFRGBA.Create;
Result := FColor[index];
end;
function TSWFBaseGradientFill.GetGradientRatio(Index: Integer): Byte;
begin
Result := FRatio[index];
end;
procedure TSWFBaseGradientFill.ReadFromStream(be: TBitsEngine);
var
il, bc: Byte;
begin
bc := be.ReadByte;
SpreadMode := bc shr 6;
InterpolationMode := (bc shr 4) and 3;
Count := bc and 15;
if Count > 0 then
for il := 1 to Count do
begin
GradientRatio[il] := be.ReadByte;
GradientColor[il].HasAlpha := hasAlpha;
if hasAlpha then GradientColor[il].RGBA := be.ReadRGBA
else GradientColor[il].RGB := be.ReadRGB;
end;
end;
procedure TSWFBaseGradientFill.SetGradientRatio(Index: Integer; Value: Byte);
begin
FRatio[index] := Value;
end;
procedure TSWFBaseGradientFill.WriteToStream(be: TBitsEngine);
var
il, bc: Byte;
begin
bc := SpreadMode shl 6 + InterpolationMode shl 4 + Count;
be.WriteByte(bc);
For il := 1 to Count do
begin
be.WriteByte(Gradient[il].ratio);
if hasAlpha then be.WriteColor(Gradient[il].Color)
else be.WriteColor(WithoutA(Gradient[il].Color));
end;
end;
{
***************************************************** TSWFGradientFill ******************************************************
}
constructor TSWFGradientFill.Create;
begin
inherited ;
FMatrix := TSWFMatrix.Create;
end;
destructor TSWFGradientFill.Destroy;
begin
FMatrix.Free;
inherited Destroy;
end;
procedure TSWFGradientFill.Assign(Source: TSWFFillStyle);
begin
inherited;
with TSWFGradientFill(Source) do
self.Matrix.Assign(Matrix);
end;
procedure TSWFGradientFill.ReadFromStream(be: TBitsEngine);
begin
Matrix.Rec := be.ReadMatrix;
inherited;
(* Count := be.ReadByte;
if Count > 0 then
for il := 1 to Count do
begin
GradientRatio[il] := be.ReadByte;
GradientColor[il].HasAlpha := hasAlpha;
if hasAlpha then GradientColor[il].RGBA := be.ReadRGBA
else GradientColor[il].RGB := be.ReadRGB;
end; *)
end;
procedure TSWFGradientFill.ScaleTo(Frame: TRect);
var
kX, kY: Double;
begin
kX := (Frame.Right - Frame.Left) /GradientSizeXY;
kY := (Frame.Bottom - Frame.Top)/GradientSizeXY;
Matrix.SetScale(kX, kY);
Matrix.SetTranslate(Frame.Left + (Frame.Right - Frame.Left) div 2,
Frame.Top + (Frame.Bottom - Frame.Top) div 2);
end;
procedure TSWFGradientFill.WriteToStream(be: TBitsEngine);
begin
be.WriteByte(SWFFillType);
be.WriteMatrix(Matrix.Rec);
inherited;
(* be.WriteByte(Count);
For il := 1 to Count do
begin
be.WriteByte(Gradient[il].ratio);
if hasAlpha then be.WriteColor(Gradient[il].Color)
else be.WriteColor(WithoutA(Gradient[il].Color));
end; *)
end;
{
*************************************************** TSWFFocalGradientFill ****************************************************
}
constructor TSWFFocalGradientFill.Create;
begin
inherited;
SWFFillType := SWFFillFocalGradient;
end;
procedure TSWFFocalGradientFill.Assign(Source: TSWFFillStyle);
begin
inherited;
FocalPoint := TSWFFocalGradientFill(Source).FocalPoint;
InterpolationMode := TSWFFocalGradientFill(Source).InterpolationMode;
SpreadMode := TSWFFocalGradientFill(Source).SpreadMode;
end;
function TSWFFocalGradientFill.GetFocalPoint: single;
begin
Result := FFocalPoint/255;
if Result > 1 then Result := 1 else
if Result < -1 then Result := -1;
end;
procedure TSWFFocalGradientFill.SetFocalPoint(const Value: single);
begin
FFocalPoint := Round(value * 255);
if FFocalPoint > 255 then FFocalPoint := 255 else
if FFocalPoint < -255 then FFocalPoint := -255;
end;
procedure TSWFFocalGradientFill.ReadFromStream(be: TBitsEngine);
begin
inherited;
FFocalPoint := smallint(be.ReadWord);
end;
procedure TSWFFocalGradientFill.WriteToStream(be: TBitsEngine);
begin
inherited;
be.WriteWord(word(FFocalPoint));
end;
{
****************************************************** TSWFShapeRecord ******************************************************
}
procedure TSWFShapeRecord.Assign(Source: TSWFShapeRecord);
begin
end;
{
**************************************************** TSWFEndShapeRecord *****************************************************
}
constructor TSWFEndShapeRecord.Create;
begin
ShapeRecType := EndShapeRecord;
end;
procedure TSWFEndShapeRecord.WriteToStream(be: TBitsEngine);
begin
be.WriteBits(0, 6);
end;
{
************************************************** TSWFStraightEdgeRecord ***************************************************
}
constructor TSWFStraightEdgeRecord.Create;
begin
ShapeRecType := StraightEdgeRecord;
end;
procedure TSWFStraightEdgeRecord.Assign(Source: TSWFShapeRecord);
begin
with TSWFStraightEdgeRecord(Source) do
begin
self.X := X;
self.Y := Y;
end;
end;
procedure TSWFStraightEdgeRecord.WriteToStream(be: TBitsEngine);
var
nBits: Byte;
begin
//if (X = 0) and (Y = 0) then Exit;
BE.WriteBit(true); //edge flag
BE.WriteBit(true); // Line EDGE
nBits := GetBitsCount(SWFTools.MaxValue(X, Y), 1);
if nBits = 0 then nBits := 2;
BE.WriteBits(nBits - 2, 4);
if (X<>0) and (Y<>0) then
begin
BE.WriteBit(true); // GeneralLineFlag
BE.WriteBits(X, nBits);
BE.WriteBits(Y, nBits);
end else
begin
BE.WriteBit(false); // GeneralLineFlag
BE.WriteBit(X = 0); // verticalLine
if X = 0 then BE.WriteBits(Y, nBits) else
BE.WriteBits(X, nBits);
end;
end;
{
*************************************************** TSWFStyleChangeRecord ***************************************************
}
constructor TSWFStyleChangeRecord.Create;
begin
ShapeRecType := StyleChangeRecord;
end;
destructor TSWFStyleChangeRecord.Destroy;
begin
if FNewFillStyles <> nil then FNewFillStyles.Free;
if FNewLineStyles <> nil then FNewLineStyles.Free;
inherited;
end;
procedure TSWFStyleChangeRecord.Assign(Source: TSWFShapeRecord);
var
il: Word;
OldFS, NewFS: TSWFFillStyle;
LS: TSWFLineStyle;
LS2: TSWFLineStyle2;
begin
inherited;
with TSWFStyleChangeRecord(Source) do
begin
self.bitsFill := bitsFill;
self.bitsLine := bitsLine;
self.Fill0Id := Fill0Id;
self.Fill1Id := Fill1Id;
self.LineId := LineId;
self.StateFillStyle0 := StateFillStyle0;
self.StateFillStyle1 := StateFillStyle1;
self.StateLineStyle := StateLineStyle;
self.StateMoveTo := StateMoveTo;
self.StateNewStyles := StateNewStyles;
if StateNewStyles then
begin
if (FNewFillStyles <> nil) and (FNewFillStyles.Count > 0) then
for il := 0 to FNewFillStyles.Count - 1 do
begin
OldFS := TSWFFillStyle(FNewFillStyles[il]);
NewFS := nil;
Case OldFS.SWFFillType of
SWFFillSolid:
NewFS := TSWFColorFill.Create;
SWFFillLinearGradient, SWFFillRadialGradient:
NewFS := TSWFGradientFill.Create;
SWFFillFocalGradient:
NewFS := TSWFFocalGradientFill.Create;
SWFFillTileBitmap, SWFFillClipBitmap,
SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap:
NewFS := TSWFImageFill.Create;
end;
NewFS.Assign(OldFS);
self.NewFillStyles.Add(NewFS);
end;
if (FNewLineStyles <> nil) and (FNewLineStyles.Count > 0) then
for il := 0 to FNewLineStyles.Count -1 do
if FNewLineStyles[il] is TSWFLineStyle2 then
begin
LS2 := TSWFLineStyle2.Create;
LS2.Assign(TSWFLineStyle2(FNewLineStyles[il]));
self.NewLineStyles.Add(LS2);
end else
begin
LS := TSWFLineStyle.Create;
LS.Assign(TSWFLineStyle(FNewLineStyles[il]));
self.NewLineStyles.Add(LS);
end;
end;
end;
end;
function TSWFStyleChangeRecord.GetNewFillStyles: TObjectList;
begin
if FNewFillStyles = nil then FNewFillStyles := TObjectList.Create;
StateNewStyles := true;
Result := FNewFillStyles;
end;
function TSWFStyleChangeRecord.GetNewLineStyles: TObjectList;
begin
if FNewLineStyles = nil then FNewLineStyles := TObjectList.Create;
StateNewStyles := true;
Result := FNewLineStyles;
end;
procedure TSWFStyleChangeRecord.SetFill0Id(Value: Word);
begin
if not StateFillStyle0 or (FFill0Id <> Value) then
begin
StateFillStyle0 := true;
FFill0Id := Value;
end;
end;
procedure TSWFStyleChangeRecord.SetFill1Id(Value: Word);
begin
if not StateFillStyle1 or (FFill1Id <> Value) then
begin
StateFillStyle1 := true;
FFill1Id := Value;
end;
end;
procedure TSWFStyleChangeRecord.SetLineId(Value: Word);
begin
if not StateLineStyle or (FLineId <> Value) then
begin
StateLineStyle := true;
FLineId := Value;
end;
end;
procedure TSWFStyleChangeRecord.WriteToStream(be: TBitsEngine);
var
nBits: Byte;
w, il: Word;
fState: Boolean;
begin
BE.WriteBit(false); // no edge info
BE.WriteBit(stateNewStyles);
BE.WriteBit(stateLineStyle);
BE.WriteBit(stateFillStyle1);
BE.WriteBit(stateFillStyle0);
if stateFillStyle0 or stateFillStyle1 or stateLineStyle
then fState := stateMoveTo
else fState := true;
BE.WriteBit(fState);
if fState then
begin
nBits := GetBitsCount(SWFTools.MaxValue(X, Y), 1);
BE.WriteBits(nBits, 5);
BE.WriteBits(X, nBits);
BE.WriteBits(Y, nBits);
end;
if stateFillStyle0 then
BE.WriteBits(Fill0Id, bitsFill);
if stateFillStyle1 then
BE.WriteBits(Fill1Id, bitsFill);
if stateLineStyle then
BE.WriteBits(LineId, bitsLine);
if stateNewStyles then
begin
be.FlushLastByte;
w := NewFillStyles.Count;
if w > $fe then
begin
BE.WriteByte($ff);
BE.WriteWord(w);
end else BE.WriteByte(w);
if w > 0 then
for il := 0 to w - 1 do
with TSWFFillStyle(NewFillStyles[il]) do
begin
hasAlpha := self.hasAlpha;
WriteToStream(BE);
end;
w := NewLineStyles.Count;
if w > $fe then
begin
BE.WriteByte($ff);
BE.WriteWord(w);
end else BE.WriteByte(w);
if w > 0 then
for il := 0 to w - 1 do
with TSWFLineStyle(NewLineStyles[il]) do
begin
Color.hasAlpha := hasAlpha;
WriteToStream(BE);
end;
be.FlushLastByte(true); // need ??
bitsFill := GetBitsCount(NewFillStyles.Count);
bitsLine := GetBitsCount(NewLineStyles.Count);
BE.WriteBits(bitsFill, 4);
BE.WriteBits(bitsLine, 4);
end;
end;
{
*************************************************** TSWFCurvedEdgeRecord ****************************************************
}
constructor TSWFCurvedEdgeRecord.Create;
begin
ShapeRecType := CurvedEdgeRecord;
end;
procedure TSWFCurvedEdgeRecord.Assign(Source: TSWFShapeRecord);
begin
with TSWFCurvedEdgeRecord(Source) do
begin
self.ControlX := ControlX;
self.ControlY := ControlY;
self.AnchorX := AnchorX;
self.AnchorY := AnchorY;
end;
end;
procedure TSWFCurvedEdgeRecord.WriteToStream(be: TBitsEngine);
var
nBits: Byte;
begin
if (ControlX = 0) and (ControlY = 0) and (AnchorX = 0) and (AnchorY = 0) then Exit;
BE.WriteBit(true); //edge flag
BE.WriteBit(false); // Line_EDGE, This is a curved edge record
nBits := GetBitsCount(SWFTools.MaxValue(ControlX, ControlY, AnchorX, AnchorY), 1);
BE.WriteBits(nBits - 2, 4);
BE.WriteBits(ControlX, nBits);
BE.WriteBits(ControlY, nBits);
BE.WriteBits(AnchorX, nBits);
BE.WriteBits(AnchorY, nBits);
end;
{
****************************************************** TSWFDefineShape ******************************************************
}
constructor TSWFDefineShape.Create;
begin
TagId := tagDefineShape;
FShapeBounds := TSWFRect.Create;
FEdges := TObjectList.Create;
FLineStyles := TObjectList.Create;
FFillStyles := TObjectList.Create;
end;
destructor TSWFDefineShape.Destroy;
begin
FShapeBounds.Free;
FEdges.free;
FLineStyles.Free;
FFillStyles.Free;
inherited ;
end;
procedure TSWFDefineShape.Assign(Source: TBasedSWFObject);
var
il: Word;
LS: TSWFLineStyle;
NewFS, OldFS: TSWFFIllStyle;
begin
inherited;
With TSWFDefineShape(Source) do
begin
self.ShapeId := ShapeId;
self.ShapeBounds.Assign(ShapeBounds);
self.hasAlpha := hasAlpha;
CopyShapeRecords(Edges, Self.Edges);
if LineStyles.Count > 0 then
for il := 0 to LineStyles.Count -1 do
begin
if LineStyles[il] is TSWFLineStyle2
then LS := TSWFLineStyle2.Create
else LS := TSWFLineStyle.Create;
LS.Assign(TSWFLineStyle(LineStyles[il]));
self.LineStyles.Add(LS);
end;
if FillStyles.Count > 0 then
for il := 0 to FillStyles.Count -1 do
begin
OldFS := TSWFFillStyle(FillStyles[il]);
NewFS := nil;
Case OldFS.SWFFillType of
SWFFillSolid:
NewFS := TSWFColorFill.Create;
SWFFillLinearGradient, SWFFillRadialGradient:
NewFS := TSWFGradientFill.Create;
SWFFillFocalGradient:
NewFS := TSWFFocalGradientFill.Create;
SWFFillTileBitmap, SWFFillClipBitmap,
SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap:
NewFS := TSWFImageFill.Create;
end;
NewFS.Assign(OldFS);
self.FillStyles.Add(NewFS);
end;
end;
end;
function TSWFDefineShape.GetEdgeRecord(index: longint): TSWFShapeRecord;
begin
Result := TSWFShapeRecord(Edges[index]);
end;
procedure TSWFDefineShape.ReadFromStream(be: TBitsEngine);
var
PP: LongInt;
StylesCount: Word;
il: Word;
FS: TSWFFillStyle;
LS: TSWFLineStyle;
b: Byte;
nBitsFill, nBitsLine: Word;
begin
PP := BE.BitsStream.Position;
ShapeId := be.ReadWord;
ShapeBounds.Rect := be.ReadRect;
ReadAddonFromStream(be);
StylesCount := be.ReadByte;
if StylesCount = $FF then StylesCount := be.ReadWord;
if StylesCount > 0 then
for il := 1 to StylesCount do
begin
b := be.ReadByte;
FS := nil;
case b of
SWFFillSolid:
FS := TSWFColorFill.Create;
SWFFillLinearGradient, SWFFillRadialGradient:
FS := TSWFGradientFill.Create;
SWFFillFocalGradient:
FS := TSWFFocalGradientFill.Create;
SWFFillTileBitmap, SWFFillClipBitmap,
SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap:
FS := TSWFImageFill.Create;
end;
FS.SWFFillType := B;
FS.hasAlpha := hasAlpha;
FS.ReadFromStream(be);
FillStyles.Add(FS);
end;
StylesCount := be.ReadByte;
if StylesCount = $FF then StylesCount := be.ReadWord;
if StylesCount > 0 then
for il := 1 to StylesCount do
begin
if TagId = tagDefineShape4 then LS := TSWFLineStyle2.Create
else LS := TSWFLineStyle.Create;
LS.Color.hasAlpha := hasAlpha;
LS.ReadFromStream(be);
LineStyles.Add(LS)
end;
B := be.ReadByte;
nBitsFill := B shr 4;
nBitsLine := b and $F;
ReadShapeRecord(be, Edges, nBitsFill, nBitsLine, self);
be.BitsStream.Position := integer(BodySize) + PP;
end;
procedure TSWFDefineShape.WriteTagBody(be: TBitsEngine);
var
W: Word;
il: longint;
nBitsFill, nBitsLine: Word;
begin
be.WriteWord(ShapeId);
be.WriteRect(ShapeBounds.Rect);
WriteAddonToStream(be);
w := FillStyles.Count;
if w > $fe then
begin
BE.WriteByte($ff);
BE.WriteWord(w);
end else BE.WriteByte(w);
if w > 0 then
for il := 0 to w - 1 do
with TSWFFillStyle(FillStyles.Items[il]) do
begin
hasAlpha := self.hasAlpha;
WriteToStream(BE);
end;
w := LineStyles.Count;
if w > $fe then
begin
BE.WriteByte($ff);
BE.WriteWord(w);
end else BE.WriteByte(w);
if w > 0 then
for il := 0 to w - 1 do
with TSWFLineStyle(LineStyles.Items[il]) do
begin
Color.hasAlpha := hasAlpha;
WriteToStream(BE);
end;
nBitsFill := GetBitsCount(FillStyles.Count);
nBitsLine := GetBitsCount(LineStyles.Count);
BE.WriteBits(nBitsFill, 4);
BE.WriteBits(nBitsLine, 4);
if Edges.Count > 0 then
begin
for il:=0 to Edges.Count - 1 do
With TSWFShapeRecord(Edges[il]) do
begin
if ShapeRecType = StyleChangeRecord then
with TSWFStyleChangeRecord(Edges[il]) do
begin
hasAlpha := self.hasAlpha;
bitsFill := nBitsFill;
bitsLine := nBitsLine;
if StateNewStyles then
else
begin
if bitsFill = 0 then
begin
StateFillStyle0 := false;
StateFillStyle1 := false;
end;
if bitsLine = 0 then StateLineStyle := false;
end;
end;
if (ShapeRecType <> EndShapeRecord) or
((ShapeRecType = EndShapeRecord) and (il = (Edges.Count - 1)))
then WriteToStream(be);
if (ShapeRecType = StyleChangeRecord) then
with TSWFStyleChangeRecord(Edges[il]) do
if StateNewStyles then
begin
nBitsFill := bitsFill;
nBitsLine := bitsLine;
end;
if (il = (Edges.Count - 1)) and (ShapeRecType<>EndShapeRecord)
then be.WriteBits(0, 6); // add automtic end flag
end;
end else be.WriteBits(0, 6); // end flag
BE.FlushLastByte;
end;
procedure TSWFDefineShape.ReadAddonFromStream(be: TBitsEngine);
begin
//
end;
procedure TSWFDefineShape.WriteAddonToStream(be: TBitsEngine);
begin
//
end;
{
***************************************************** TSWFDefineShape2 ******************************************************
}
constructor TSWFDefineShape2.Create;
begin
inherited ;
TagId := tagDefineShape2;
end;
function TSWFDefineShape2.MinVersion: Byte;
begin
Result := SWFVer2;
end;
{
***************************************************** TSWFDefineShape3 ******************************************************
}
constructor TSWFDefineShape3.Create;
begin
inherited ;
TagId := tagDefineShape3;
hasAlpha := true;
end;
function TSWFDefineShape3.MinVersion: Byte;
begin
Result := SWFVer3;
end;
{
***************************************************** TSWFDefineShape4 ******************************************************
}
procedure TSWFDefineShape4.Assign(Source: TBasedSWFObject);
begin
inherited;
with TSWFDefineShape4(Source) do
begin
self.FEdgeBounds.Assign(FEdgeBounds);
self.FUsesNonScalingStrokes := FUsesNonScalingStrokes;
self.FUsesScalingStrokes := FUsesScalingStrokes;
end;
end;
constructor TSWFDefineShape4.Create;
begin
inherited ;
TagId := tagDefineShape4;
hasAlpha := true;
FEdgeBounds := TSWFRect.Create;
end;
destructor TSWFDefineShape4.Destroy;
begin
FEdgeBounds.Free;
inherited;
end;
function TSWFDefineShape4.MinVersion: Byte;
begin
Result := SWFVer8;
end;
procedure TSWFDefineShape4.ReadAddonFromStream(be: TBitsEngine);
var b: byte;
begin
EdgeBounds.Rect := be.ReadRect;
b := be.ReadByte;
UsesNonScalingStrokes := CheckBit(b, 2);
UsesScalingStrokes := CheckBit(b, 1);
end;
procedure TSWFDefineShape4.WriteAddonToStream(be: TBitsEngine);
var il: integer;
begin
be.WriteRect(EdgeBounds.Rec);
UsesNonScalingStrokes := false;
UsesScalingStrokes := false;
if LineStyles.Count > 0 then
for il := 0 to LineStyles.Count - 1 do
with TSWFLineStyle2(LineStyles[il]) do
if NoHScaleFlag or NoVScaleFlag then UsesNonScalingStrokes := true
else UsesScalingStrokes := true;
be.WriteByte(byte(UsesNonScalingStrokes) shl 1 + byte(UsesScalingStrokes));
end;
// ==========================================================
// Bitmaps
// ==========================================================
{
****************************************************** TSWFDataObject *******************************************************
}
constructor TSWFDataObject.Create;
begin
inherited;
selfdestroy := true;
end;
destructor TSWFDataObject.Destroy;
begin
if selfdestroy and (DataSize > 0) then FreeMem(Data, DataSize);
inherited ;
end;
procedure TSWFDataObject.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFDataObject(Source) do
begin
if Assigned(FOnDataWrite) then self.FOnDataWrite := OnDataWrite
else
begin
if DataSize > 0 then
begin
self.DataSize := DataSize;
GetMem(self.FData, DataSize);
Move(Data^, self.FData^, DataSize);
end;
Self.SelfDestroy := SelfDestroy;
end;
end;
end;
{
******************************************************* TSWFImageTag ********************************************************
}
procedure TSWFImageTag.Assign(Source: TBasedSWFObject);
begin
inherited;
CharacterId := TSWFImageTag(Source).CharacterId;
end;
{
****************************************************** TSWFDefineBits *******************************************************
}
constructor TSWFDefineBits.Create;
begin
inherited ;
TagId := tagDefineBits;
end;
procedure TSWFDefineBits.ReadFromStream(be: TBitsEngine);
var
ReadEnd: boolean;
begin
CharacterID := be.ReadWord;
DataSize := BodySize - 2;
ReadEnd := true;
SelfDestroy := true;
DataSize := DataSize - 2;
if be.ReadWord = $D9FF then
begin
be.ReadWord;
DataSize := DataSize - 2;
ReadEnd := false;
end;
if ReadEnd then DataSize := DataSize - 2;
GetMem(FData, DataSize);
be.BitsStream.Read(Data^, DataSize);
if ReadEnd then be.ReadWord;
(*var
Check: Word;
begin
CharacterID := be.ReadWord;
DataSize := BodySize - 2 * 2; // ID + End
Repeat
Check := be.ReadWord;
DataSize := DataSize - 2;
Until Check = $D8FF;
GetMem(FData, DataSize);
SelfDestroy := true;
be.BitsStream.Read(Data^, DataSize);
be.ReadWord;*)
end;
procedure TSWFDefineBits.WriteTagBody(be: TBitsEngine);
var PW: PWord;
begin
be.WriteWord(CharacterID);
if Assigned(OnDataWrite) then OnDataWrite(self, be) else
begin
PW := Data;
if PW^ = $D8FF then be.WriteWord($D9FF);
be.WriteWord($D8FF);
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
if PW^ <> $D8FF then be.WriteWord($D9FF);
end;
(*
be.WriteByte($FF);
be.WriteByte($D8);
if Assigned(OnDataWrite) then OnDataWrite(self, be) else
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
be.WriteByte($FF);
be.WriteByte($D9); *)
end;
{
****************************************************** TSWFJPEGTables *******************************************************
}
constructor TSWFJPEGTables.Create;
begin
inherited ;
TagID := tagJPEGTables;
end;
procedure TSWFJPEGTables.ReadFromStream(be: TBitsEngine);
var
ReadEnd: boolean;
begin
ReadEnd := true;
SelfDestroy := true;
DataSize := BodySize;
DataSize := DataSize - 2;
if be.ReadWord = $D9FF then
begin
be.ReadWord;
DataSize := DataSize - 2;
ReadEnd := false;
end;
if ReadEnd then DataSize := DataSize - 2;
GetMem(FData, DataSize);
be.BitsStream.Read(Data^, DataSize);
if ReadEnd then be.ReadWord;
end;
procedure TSWFJPEGTables.WriteTagBody(be: TBitsEngine);
var PW: PWord;
begin
if Assigned(OnDataWrite) then OnDataWrite(self, be) else
if DataSize > 0 then
begin
PW := Data;
if PW^ = $D8FF then be.WriteWord($D9FF);
be.WriteWord($D8FF);
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
if PW^ <> $D8FF then be.WriteWord($D9FF);
end;
end;
{
**************************************************** TSWFDefineBitsJPEG2 ****************************************************
}
constructor TSWFDefineBitsJPEG2.Create;
begin
inherited ;
TagId := tagDefineBitsJPEG2;
end;
function TSWFDefineBitsJPEG2.MinVersion: Byte;
begin
Result := SWFVer2;
end;
procedure TSWFDefineBitsJPEG2.WriteTagBody(be: TBitsEngine);
begin
inherited;
(*
be.WriteWord(CharacterID);
be.WriteByte($ff);
be.WriteByte($d9);
be.WriteByte($FF);
be.WriteByte($D8);
if Assigned(OnDataWrite) then OnDataWrite(self, be) else
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
be.WriteByte($FF);
be.WriteByte($D9); *)
end;
{
**************************************************** TSWFDefineBitsJPEG3 ****************************************************
}
constructor TSWFDefineBitsJPEG3.Create;
begin
inherited ;
TagId := tagDefineBitsJPEG3;
end;
destructor TSWFDefineBitsJPEG3.Destroy;
begin
if SelfAlphaDestroy and (AlphaDataSize > 0) then FreeMem(AlphaData, AlphaDataSize);
inherited ;
end;
procedure TSWFDefineBitsJPEG3.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFDefineBitsJPEG3(Source) do
begin
if Assigned(FOnAlphaDataWrite) then self.FOnAlphaDataWrite := OnAlphaDataWrite
else
begin
if AlphaDataSize > 0 then
begin
self.AlphaDataSize := AlphaDataSize;
GetMem(Self.FAlphaData, AlphaDataSize);
Move(AlphaData^, self.FAlphaData^, AlphaDataSize);
end;
Self.SelfAlphaDestroy := SelfAlphaDestroy;
end;
end;
end;
function TSWFDefineBitsJPEG3.MinVersion: Byte;
begin
Result := SWFVer3;
end;
procedure TSWFDefineBitsJPEG3.ReadFromStream(be: TBitsEngine);
var ReadEnd: boolean;
del: word;
begin
SelfDestroy := true;
SelfAlphaDestroy := true;
CharacterID := be.ReadWord;
ReadEnd := true;
DataSize := be.ReadDWord;
// 4 = SMarker(2) + EMarker(2)
if be.ReadWord = $D9FF then
begin
be.ReadWord;
ReadEnd := false;
end;
del := 4;
DataSize := DataSize - del;
GetMem(FData, DataSize);
be.BitsStream.Read(Data^, DataSize);
if ReadEnd then be.ReadWord;
// 6 = AlphaOffset(4) + CharacterID(2)
AlphaDataSize := Integer(BodySize) - DataSize - del - 4;
GetMem(FAlphaData, AlphaDataSize);
be.BitsStream.Read(AlphaData^, AlphaDataSize);
end;
procedure TSWFDefineBitsJPEG3.WriteTagBody(be: TBitsEngine);
var
pp: dword;
PW: PWord;
begin
be.WriteWord(CharacterID);
pp := be.BitsStream.Position;
PW := Data;
be.WriteDWord(0);
if Assigned(OnDataWrite) then OnDataWrite(self, be) else
begin
if PW^ = $D8FF then be.WriteWord($D9FF);
be.WriteWord($D8FF);
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
if PW^ <> $D8FF then be.WriteWord($D9FF);
end;
be.BitsStream.Position := PP;
PP := be.BitsStream.Size - PP - 4;
be.WriteDWord(PP);
be.BitsStream.Position := be.BitsStream.Size;
if Assigned(FOnAlphaDataWrite) then OnAlphaDataWrite(self, be) else
if AlphaDataSize > 0 then be.BitsStream.Write(AlphaData^, AlphaDataSize);
end;
{
************************************************** TSWFDefineBitsLossless ***************************************************
}
constructor TSWFDefineBitsLossless.Create;
begin
inherited ;
TagId := tagDefineBitsLossless;
end;
procedure TSWFDefineBitsLossless.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFDefineBitsLossless(Source) do
begin
self.BitmapColorTableSize := BitmapColorTableSize;
self.BitmapFormat := BitmapFormat;
self.BitmapHeight := BitmapHeight;
self.BitmapWidth := BitmapWidth;
end;
end;
function TSWFDefineBitsLossless.MinVersion: Byte;
begin
Result := SWFVer2;
end;
procedure TSWFDefineBitsLossless.ReadFromStream(be: TBitsEngine);
var
PP: dword;
begin
pp := be.BitsStream.Position;
CharacterID := be.ReadWord;
BitmapFormat := be.ReadByte;
BitmapWidth := be.ReadWord;
BitmapHeight := be.ReadWord;
if BitmapFormat = BMP_8bit then BitmapColorTableSize := be.ReadByte;
// pp := be.BitsStream.Position;
DataSize := BodySize - (be.BitsStream.Position - PP);
selfdestroy := true;
GetMem(FData, DataSize);
be.BitsStream.Read(Data^, DataSize);
end;
procedure TSWFDefineBitsLossless.WriteTagBody(be: TBitsEngine);
begin
BE.WriteWord(CharacterID);
BE.WriteByte(BitmapFormat); // type
BE.WriteWord(BitmapWidth);
BE.WriteWord(BitmapHeight);
if BitmapFormat = BMP_8bit then BE.WriteByte(BitmapColorTableSize);
if Assigned(OnDataWrite) then OnDataWrite(self, be) else
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
end;
{
************************************************** TSWFDefineBitsLossless2 **************************************************
}
constructor TSWFDefineBitsLossless2.Create;
begin
inherited ;
TagId := tagDefineBitsLossless2;
end;
function TSWFDefineBitsLossless2.MinVersion: Byte;
begin
Result := SWFVer3;
end;
// ==========================================================
// Morphing
// ==========================================================
{
**************************************************** TSWFMorphColorFill *****************************************************
}
constructor TSWFMorphColorFill.Create;
begin
inherited ;
SWFFillType := SWFFillSolid;
FStartColor := TSWFRGBA.Create(true);
FEndColor := TSWFRGBA.Create(true);
end;
destructor TSWFMorphColorFill.Destroy;
begin
FStartColor.Free;
FEndColor.Free;
inherited Destroy;
end;
procedure TSWFMorphColorFill.Assign(Source: TSWFMorphFillStyle);
begin
With TSWFMorphColorFill(Source) do
begin
self.StartColor.Assign(StartColor);
self.EndColor.Assign(EndColor);
end;
end;
procedure TSWFMorphColorFill.ReadFromStream(be: TBitsEngine);
begin
StartColor.RGBA := be.ReadRGBA;
EndColor.RGBA := be.ReadRGBA;
end;
procedure TSWFMorphColorFill.WriteToStream(be: TBitsEngine);
begin
be.WriteByte(SWFFillType);
be.WriteColor(StartColor.RGBA);
be.WriteColor(EndColor.RGBA);
end;
{
*************************************************** TSWFMorphGradientFill ***************************************************
}
constructor TSWFMorphGradientFill.Create;
begin
inherited ;
SWFFillType := SWFFillLinearGradient;
FStartColor[1] := TSWFRGBA.Create(true);
FStartColor[2] := TSWFRGBA.Create(true);
FEndColor[1] := TSWFRGBA.Create(true);
FEndColor[2] := TSWFRGBA.Create(true);
FStartMatrix := TSWFMatrix.Create;
FEndMatrix := TSWFMatrix.Create;
end;
destructor TSWFMorphGradientFill.Destroy;
var
il: Byte;
begin
For il := 1 to 8 do
begin
if FStartColor[il] <> nil then FStartColor[il].Free;
if FEndColor[il] <> nil then FEndColor[il].Free;
end;
FStartMatrix.Free;
FEndMatrix.Free;
inherited Destroy;
end;
procedure TSWFMorphGradientFill.Assign(Source: TSWFMorphFillStyle);
var
il: Byte;
begin
with TSWFMorphGradientFill(Source) do
begin
self.Count := Count;
self.StartMatrix.Assign(StartMatrix);
self.EndMatrix.Assign(EndMatrix);
if Count > 0 then
For il := 1 to Count do
begin
self.FStartRatio[il] := FStartRatio[il];
self.FEndRatio[il] := FEndRatio[il];
self.StartColor[il].Assign(StartColor[il]);
self.EndColor[il].Assign(EndColor[il]);
end;
end;
end;
function TSWFMorphGradientFill.GetEndColor(Index: Integer): TSWFRGBA;
begin
if FEndColor[index] = nil then FEndColor[index] := TSWFRGBA.Create(true);
Result := FEndColor[index];
end;
function TSWFMorphGradientFill.GetEndGradient(Index: byte): TSWFGradientRec;
begin
Result.color := EndColor[index].RGBA;
Result.Ratio := FEndRatio[index];
end;
function TSWFMorphGradientFill.GetEndRatio(Index: Integer): Byte;
begin
Result := FEndRatio[index];
end;
function TSWFMorphGradientFill.GetGradient(Index: byte): TSWFMorphGradientRec;
begin
Result.StartColor := StartColor[index].RGBA;
Result.StartRatio := FStartRatio[index];
Result.EndColor := EndColor[index].RGBA;
Result.EndRatio := FEndRatio[index];
end;
function TSWFMorphGradientFill.GetStartColor(Index: Integer): TSWFRGBA;
begin
if FStartColor[index] = nil then FStartColor[index] := TSWFRGBA.Create(true);
Result := FStartColor[index];
end;
function TSWFMorphGradientFill.GetStartGradient(Index: byte): TSWFGradientRec;
begin
Result.color := StartColor[index].RGBA;
Result.Ratio := FStartRatio[index];
end;
function TSWFMorphGradientFill.GetStartRatio(Index: Integer): Byte;
begin
Result := FStartRatio[index];
end;
procedure TSWFMorphGradientFill.ReadFromStream(be: TBitsEngine);
var
il, bc: Byte;
begin
StartMatrix.Rec := be.ReadMatrix;
EndMatrix.Rec := be.ReadMatrix;
bc := be.ReadByte;
SpreadMode := bc shr 6;
InterpolationMode := (bc shr 4) and 3;
Count := bc and 15;
if Count > 0 then
for il := 1 to Count do
begin
StartRatio[il] := be.ReadByte;
StartColor[il].RGBA := be.ReadRGBA;
EndRatio[il] := be.ReadByte;
EndColor[il].RGBA := be.ReadRGBA;
end;
end;
procedure TSWFMorphGradientFill.SetEndRatio(Index: Integer; Value: Byte);
begin
FEndRatio[index] := Value;
end;
procedure TSWFMorphGradientFill.SetStartRatio(Index: Integer; Value: Byte);
begin
FStartRatio[index] := Value;
end;
procedure TSWFMorphGradientFill.WriteToStream(be: TBitsEngine);
var
il: Byte;
begin
be.WriteByte(SWFFillType);
be.WriteMatrix(StartMatrix.Rec);
be.WriteMatrix(EndMatrix.Rec);
be.WriteByte(Count);
For il := 1 to Count do
begin
be.WriteByte(StartRatio[il]);
be.WriteColor(StartColor[il].RGBA);
be.WriteByte(EndRatio[il]);
be.WriteColor(EndColor[il].RGBA)
end;
end;
{
************************************************ TSWFMorphFocalGradientFill *************************************************
}
constructor TSWFMorphFocalGradientFill.Create;
begin
inherited;
SWFFillType := SWFFillFocalGradient;
end;
function TSWFMorphFocalGradientFill.GetStartFocalPoint: single;
begin
Result := FStartFocalPoint/255;
if Result > 1 then Result := 1 else
if Result < -1 then Result := -1;
end;
function TSWFMorphFocalGradientFill.GetEndFocalPoint: single;
begin
Result := FEndFocalPoint/255;
if Result > 1 then Result := 1 else
if Result < -1 then Result := -1;
end;
procedure TSWFMorphFocalGradientFill.ReadFromStream(be: TBitsEngine);
begin
inherited;
FStartFocalPoint := smallint(be.ReadWord);
FEndFocalPoint := smallint(be.ReadWord);
end;
procedure TSWFMorphFocalGradientFill.SetStartFocalPoint(const Value: single);
begin
FStartFocalPoint := Round(value * 255);
if FStartFocalPoint > 255 then FStartFocalPoint := 255 else
if FStartFocalPoint < -255 then FStartFocalPoint := -255;
end;
procedure TSWFMorphFocalGradientFill.SetEndFocalPoint(const Value: single);
begin
FEndFocalPoint := Round(value * 255);
if FEndFocalPoint > 255 then FEndFocalPoint := 255 else
if FEndFocalPoint < -255 then FEndFocalPoint := -255;
end;
procedure TSWFMorphFocalGradientFill.WriteToStream(be: TBitsEngine);
begin
inherited;
be.WriteWord(word(FStartFocalPoint));
be.WriteWord(word(FEndFocalPoint));
end;
{
**************************************************** TSWFMorphImageFill *****************************************************
}
constructor TSWFMorphImageFill.Create;
begin
inherited ;
SWFFillType := SWFFillClipBitmap;
FStartMatrix := TSWFMatrix.Create;
FEndMatrix := TSWFMatrix.Create;
end;
destructor TSWFMorphImageFill.Destroy;
begin
FStartMatrix.Free;
FEndMatrix.Free;
inherited Destroy;
end;
procedure TSWFMorphImageFill.Assign(Source: TSWFMorphFillStyle);
begin
with TSWFImageFill(Source) do
begin
self.StartMatrix.Assign(StartMatrix);
self.EndMatrix.Assign(EndMatrix);
self.ImageID := ImageID;
end;
end;
procedure TSWFMorphImageFill.ReadFromStream(be: TBitsEngine);
begin
ImageID := be.ReadWord;
StartMatrix.Rec := be.ReadMatrix;
EndMatrix.Rec := be.ReadMatrix;
end;
procedure TSWFMorphImageFill.WriteToStream(be: TBitsEngine);
begin
be.WriteByte(SWFFillType);
be.WriteWord(ImageID);
be.WriteMatrix(StartMatrix.Rec);
be.WriteMatrix(EndMatrix.Rec);
end;
{
**************************************************** TSWFMorphLineStyle *****************************************************
}
constructor TSWFMorphLineStyle.Create;
begin
FStartColor := TSWFRGBA.Create(true);
FEndColor := TSWFRGBA.Create(true);
end;
destructor TSWFMorphLineStyle.Destroy;
begin
FStartColor.Free;
FEndColor.Free;
inherited Destroy;
end;
procedure TSWFMorphLineStyle.Assign(Source: TSWFMorphLineStyle);
begin
StartWidth := Source.StartWidth;
StartColor.Assign(Source.StartColor);
EndWidth := Source.EndWidth;
EndColor.Assign(Source.EndColor);
end;
procedure TSWFMorphLineStyle.ReadFromStream(be: TBitsEngine);
begin
StartWidth := be.ReadWord;
EndWidth := be.ReadWord;
StartColor.RGBA := be.ReadRGBA;
EndColor.RGBA := be.ReadRGBA;
end;
procedure TSWFMorphLineStyle.WriteToStream(be: TBitsEngine);
begin
be.WriteWord(StartWidth);
be.WriteWord(EndWidth);
be.WriteColor(StartColor.RGBA);
be.WriteColor(EndColor.RGBA);
end;
{
**************************************************** TSWFMorphLineStyle2 *****************************************************
}
destructor TSWFMorphLineStyle2.Destroy;
begin
if FFillStyle <> nil then FFillStyle.Free;
inherited;
end;
function TSWFMorphLineStyle2.GetFillStyle(style: integer): TSWFFillStyle;
var fmake: boolean;
begin
if style > -1 then
begin
fmake := true;
if FFillStyle <> nil then
begin
if FFillStyle.SWFFillType <> style then FFillStyle.Free
else fmake := false;
end;
if fmake then
case style of
SWFFillSolid:
FFillStyle := TSWFColorFill.Create;
SWFFillLinearGradient, SWFFillRadialGradient:
FFillStyle := TSWFGradientFill.Create;
SWFFillFocalGradient:
FFillStyle := TSWFFocalGradientFill.Create;
SWFFillTileBitmap, SWFFillClipBitmap,
SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap:
FFillStyle := TSWFImageFill.Create;
end;
end;
Result := FFillStyle;
end;
procedure TSWFMorphLineStyle2.ReadFromStream(be: TBitsEngine);
var b: byte;
begin
StartWidth := be.ReadWord;
EndWidth := be.ReadWord;
b := be.ReadByte;
StartCapStyle := b shr 6;
JoinStyle := (b shr 4) and 3;
HasFillFlag := CheckBit(b, 4);
NoHScaleFlag := CheckBit(b, 3);
NoVScaleFlag := CheckBit(b, 2);
PixelHintingFlag := CheckBit(b, 1);
b := be.ReadByte;
NoClose := CheckBit(b, 3);
EndCapStyle := b and 3;
if JoinStyle = 2 then
MiterLimitFactor := WordToSingle(be.ReadWord);
if HasFillFlag
then GetFillStyle(be.ReadByte).ReadFromStream(be)
else
begin
StartColor.RGBA := be.ReadRGBA;
EndColor.RGBA := be.ReadRGBA;
end;
end;
procedure TSWFMorphLineStyle2.WriteToStream(be: TBitsEngine);
begin
be.WriteWord(StartWidth);
be.WriteWord(EndWidth);
be.WriteBits(StartCapStyle, 2);
be.WriteBits(JoinStyle, 2);
be.WriteBit(HasFillFlag);
be.WriteBit(NoHScaleFlag);
be.WriteBit(NoVScaleFlag);
be.WriteBit(PixelHintingFlag);
be.WriteBits(0, 5);
be.WriteBit(NoClose);
be.WriteBits(EndCapStyle, 2);
if JoinStyle = 2 then
be.WriteWord(SingleToWord(MiterLimitFactor));
if HasFillFlag
then GetFillStyle(-1).WriteToStream(be)
else
begin
be.WriteColor(StartColor.RGBA);
be.WriteColor(EndColor.RGBA);
end
end;
{
*************************************************** TSWFDefineMorphShape ****************************************************
}
constructor TSWFDefineMorphShape.Create;
begin
TagID := tagDefineMorphShape;
FStartBounds := TSWFRect.Create;
FEndBounds := TSWFRect.Create;
FMorphLineStyles := TObjectList.Create;
FMorphFillStyles := TObjectList.Create;
FStartEdges := TObjectList.Create;
FEndEdges := TObjectList.Create;
end;
destructor TSWFDefineMorphShape.Destroy;
begin
FStartBounds.Free;
FEndBounds.Free;
FMorphLineStyles.Free;
FMorphFillStyles.Free;
FStartEdges.Free;
FEndEdges.Free;
inherited;
end;
procedure TSWFDefineMorphShape.Assign(Source: TBasedSWFObject);
var
il: Word;
LS: TSWFMorphLineStyle;
NewFS, OldFS: TSWFMorphFIllStyle;
begin
inherited;
With TSWFDefineMorphShape(Source) do
begin
self.CharacterId := CharacterId;
self.StartBounds.Assign(StartBounds);
self.EndBounds.Assign(EndBounds);
CopyShapeRecords(StartEdges, Self.StartEdges);
CopyShapeRecords(EndEdges, Self.EndEdges);
if MorphLineStyles.Count > 0 then
for il := 0 to MorphLineStyles.Count -1 do
begin
if MorphLineStyles[il] is TSWFMorphLineStyle2
then LS := TSWFMorphLineStyle2.Create
else LS := TSWFMorphLineStyle.Create;
LS.Assign(TSWFMorphLineStyle(MorphLineStyles[il]));
self.MorphLineStyles.Add(LS);
end;
if MorphFillStyles.Count > 0 then
for il := 0 to MorphFillStyles.Count -1 do
begin
OldFS := TSWFMorphFillStyle(MorphFillStyles[il]);
NewFS := nil;
Case OldFS.SWFFillType of
SWFFillSolid:
NewFS := TSWFMorphColorFill.Create;
SWFFillLinearGradient, SWFFillRadialGradient:
NewFS := TSWFMorphGradientFill.Create;
SWFFillTileBitmap, SWFFillClipBitmap,
SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap:
NewFS := TSWFMorphImageFill.Create;
end;
NewFS.Assign(OldFS);
self.MorphFillStyles.Add(NewFS);
end;
end;
end;
function TSWFDefineMorphShape.GetEndEdgeRecord(Index: Integer): TSWFShapeRecord;
begin
Result := TSWFShapeRecord(EndEdges[index]);
end;
function TSWFDefineMorphShape.GetStartEdgeRecord(Index: Integer): TSWFShapeRecord;
begin
Result := TSWFShapeRecord(StartEdges[index]);
end;
function TSWFDefineMorphShape.MinVersion: Byte;
begin
Result := SWFVer3;
end;
procedure TSWFDefineMorphShape.ReadFromStream(be: TBitsEngine);
var
PP: LongInt;
StylesCount: Word;
il: Word;
FS: TSWFMorphFillStyle;
LS: TSWFMorphLineStyle;
b: Byte;
nBitsFill, nBitsLine: Word;
// Offset: DWord;
begin
PP := BE.BitsStream.Position;
CharacterId := be.ReadWord;
StartBounds.Rect := be.ReadRect;
EndBounds.Rect := be.ReadRect;
ReadAddonFromStream(be);
{Offset :=} be.ReadDWord;
// PP2 := BE.BitsStream.Position;
StylesCount := be.ReadByte;
if StylesCount = $FF then StylesCount := be.ReadWord;
if StylesCount > 0 then
for il := 1 to StylesCount do
begin
b := be.ReadByte;
FS := nil;
case b of
SWFFillSolid:
FS := TSWFMorphColorFill.Create;
SWFFillLinearGradient, SWFFillRadialGradient:
FS := TSWFMorphGradientFill.Create;
SWFFillFocalGradient:
FS := TSWFMorphFocalGradientFill.Create;
SWFFillTileBitmap, SWFFillClipBitmap,
SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap:
FS := TSWFMorphImageFill.Create;
end;
FS.SWFFillType := b;
FS.ReadFromStream(be);
MorphFillStyles.Add(FS);
end;
StylesCount := be.ReadByte;
if StylesCount = $FF then StylesCount := be.ReadWord;
if StylesCount > 0 then
for il := 1 to StylesCount do
begin
LS := TSWFMorphLineStyle.Create;
LS.ReadFromStream(be);
MorphLineStyles.Add(LS)
end;
b := be.ReadByte;
nBitsFill := b shr 4;
nBitsLine := b and $F;
ReadShapeRecord(be, StartEdges, nBitsFill, nBitsLine, nil);
// be.BitsStream.Position := Offset + pp2;
b := be.ReadByte;
nBitsFill := b shr 4;
nBitsLine := b and $F;
ReadShapeRecord(be, EndEdges, nBitsFill, nBitsLine, nil);
be.BitsStream.Position := Longint(BodySize) + PP;
end;
procedure TSWFDefineMorphShape.WriteTagBody(be: TBitsEngine);
var
W: Word;
il: Integer;
nBitsFill, nBitsLine: Word;
Offset: DWord;
begin
be.WriteWord(CharacterId);
be.WriteRect(StartBounds.Rect);
be.WriteRect(EndBounds.Rect);
WriteAddonToStream(be);
Offset := be.BitsStream.Position;
be.WriteDWord(Offset);
w := MorphFillStyles.Count;
if w > $fe then
begin
BE.WriteByte($ff);
BE.WriteWord(w);
end else BE.WriteByte(w);
if w > 0 then
for il := 0 to w - 1 do
with TSWFMorphFillStyle(MorphFillStyles.Items[il]) do
WriteToStream(BE);
w := MorphLineStyles.Count;
if w > $fe then
begin
BE.WriteByte($ff);
BE.WriteWord(w);
end else BE.WriteByte(w);
if w > 0 then
for il := 0 to w - 1 do
with TSWFMorphLineStyle(MorphLineStyles.Items[il]) do
WriteToStream(BE);
nBitsFill := GetBitsCount(MorphFillStyles.Count);
nBitsLine := GetBitsCount(MorphLineStyles.Count);
BE.WriteBits(nBitsFill, 4);
BE.WriteBits(nBitsLine, 4);
if StartEdges.Count > 0 then
begin
for il:=0 to StartEdges.Count - 1 do
With StartEdgeRecord[il] do
begin
if ShapeRecType = StyleChangeRecord then
with TSWFStyleChangeRecord(StartEdges[il]) do
begin
bitsFill := nBitsFill;
bitsLine := nBitsLine;
if MorphFillStyles.Count = 0 then
begin
StateFillStyle0 := false;
StateFillStyle1 := false;
end;
if MorphLineStyles.Count = 0 then StateLineStyle := false;
end;
WriteToStream(be);
if (il = (StartEdges.Count - 1)) and (ShapeRecType<>EndShapeRecord)
then be.WriteBits(0, 6); // add automtic end flag
end;
end else be.WriteBits(0, 6); // end flag
BE.FlushLastByte;
BE.BitsStream.Position := Offset;
BE.WriteDWord(BE.BitsStream.Size - Offset - 4);
BE.BitsStream.Seek(0, 2);
if TagID = tagDefineMorphShape then
begin
nBitsFill := 0;
nBitsLine := 0;
BE.WriteByte(0);
end else
begin
BE.WriteBits(nBitsFill, 4);
BE.WriteBits(nBitsLine, 4);
end;
if EndEdges.Count > 0 then
begin
for il:=0 to EndEdges.Count - 1 do
With EndEdgeRecord[il] do
begin
if ShapeRecType = StyleChangeRecord then
with TSWFStyleChangeRecord(EndEdges[il]) do
begin
bitsFill := nBitsFill;
bitsLine := nBitsLine;
if MorphFillStyles.Count = 0 then
begin
StateFillStyle0 := false;
StateFillStyle1 := false;
end;
if MorphLineStyles.Count = 0 then StateLineStyle := false;
{ StateFillStyle0 := false;
StateFillStyle1 := false;
StateLineStyle := false;}
end;
WriteToStream(be);
if (il = (EndEdges.Count - 1)) and (ShapeRecType<>EndShapeRecord)
then be.WriteBits(0, 6); // add automtic end flag
end;
end else be.WriteBits(0, 6); // end flag
BE.FlushLastByte;
end;
procedure TSWFDefineMorphShape.ReadAddonFromStream(be: TBitsEngine);
begin
//
end;
procedure TSWFDefineMorphShape.WriteAddonToStream(be: TBitsEngine);
begin
//
end;
{
*************************************************** TSWFDefineMorphShape2 *****************************************************
}
constructor TSWFDefineMorphShape2.Create;
begin
inherited;
TagId := tagDefineMorphShape2;
FStartEdgeBounds := TSWFRect.Create;
FEndEdgeBounds := TSWFRect.Create;
end;
destructor TSWFDefineMorphShape2.Destroy;
begin
FStartEdgeBounds.Free;
FEndEdgeBounds.Free;
inherited;
end;
procedure TSWFDefineMorphShape2.Assign(Source: TBasedSWFObject);
var il: integer;
LS2: TSWFMorphLineStyle2;
begin
inherited;
if Source is TSWFDefineMorphShape2 then
with TSWFDefineMorphShape2(Source) do
begin
self.StartEdgeBounds.Assign(StartEdgeBounds);
self.EndEdgeBounds.Assign(EndEdgeBounds);
end else
begin
StartEdgeBounds.Assign(StartBounds);
EndEdgeBounds.Assign(EndBounds);
if MorphLineStyles.Count > 0 then
for il := 0 to MorphLineStyles.Count - 1 do
if not (MorphLineStyles[il] is TSWFMorphLineStyle2) then
begin
LS2 := TSWFMorphLineStyle2.Create;
With TSWFMorphLineStyle(MorphLineStyles[il]) do
begin
LS2.StartWidth := StartWidth;
LS2.EndWidth := EndWidth;
LS2.StartColor.Assign(StartColor);
LS2.EndColor.Assign(EndColor);
end;
MorphLineStyles.Insert(il, LS2);
MorphLineStyles.Delete(il+1);
end;
end;
end;
procedure TSWFDefineMorphShape2.ReadAddonFromStream(be: TBitsEngine);
var b: byte;
begin
StartEdgeBounds.Rect := be.ReadRect;
EndEdgeBounds.Rect := be.ReadRect;
b := be.ReadByte;
UsesNonScalingStrokes := CheckBit(b, 2);
UsesScalingStrokes := CheckBit(b, 1);
end;
procedure TSWFDefineMorphShape2.WriteAddonToStream(be: TBitsEngine);
var il: integer;
begin
be.WriteRect(StartEdgeBounds.Rec);
be.WriteRect(EndEdgeBounds.Rec);
UsesNonScalingStrokes := false;
UsesScalingStrokes := false;
if MorphLineStyles.Count > 0 then
for il := 0 to MorphLineStyles.Count - 1 do
with TSWFLineStyle2(MorphLineStyles[il]) do
if NoHScaleFlag or NoVScaleFlag then UsesNonScalingStrokes := true
else UsesScalingStrokes := true;
be.WriteByte(byte(UsesNonScalingStrokes) shl 1 + byte(UsesScalingStrokes));
end;
// ==========================================================
// TEXT
// ==========================================================
{
****************************************************** TSWFDefineFont *******************************************************
}
constructor TSWFDefineFont.Create;
begin
TagId := tagDefineFont;
GlyphShapeTable := TObjectList.Create;
end;
destructor TSWFDefineFont.Destroy;
begin
GlyphShapeTable.free;
inherited;
end;
procedure TSWFDefineFont.Assign(Source: TBasedSWFObject);
var
OldEdges, NewEdges: TObjectList;
il: Word;
begin
inherited;
With TSWFDefineFont(Source) do
begin
self.FontId := FontId;
if GlyphShapeTable.Count > 0 then
for il := 0 to GlyphShapeTable.Count - 1 do
begin
OldEdges := TObjectList(GlyphShapeTable.Items[il]);
NewEdges := TObjectList.Create;
CopyShapeRecords(OldEdges, NewEdges);
self.GlyphShapeTable.Add(NewEdges);
end;
end;
end;
procedure TSWFDefineFont.ReadFromStream(be: TBitsEngine);
var
pp: dword;
il: Word;
Offset: Word;
OffsetTable: TList;
Edges: TObjectList;
B: Byte;
begin
pp := be.BitsStream.Position;
FontID := be.ReadWord;
OffsetTable := TList.Create;
il := 0;
Repeat
Offset := be.ReadWord;
if il = 0 then nGlyphs := Offset div 2;
OffsetTable.Add(Pointer(Offset));
inc(il);
until il = nGlyphs;
For il := 0 to nGlyphs - 1 do
begin
Edges := TObjectList.Create;
B := be.ReadByte;
ReadShapeRecord(be, Edges, b shr 4, b and $F, nil);
GlyphShapeTable.Add(Edges);
end;
OffsetTable.Free;
be.BitsStream.Position := pp + BodySize;
end;
procedure TSWFDefineFont.WriteTagBody(be: TBitsEngine);
var
OffsetTable: TList;
PP: LongInt;
il, il2: Word;
Edges: TObjectList;
begin
be.WriteWord(FontID);
OffsetTable := TList.Create;
if GlyphShapeTable.Count = 0 then be.WriteWord(0) else
begin
PP := be.BitsStream.Position;
for il := 1 to GlyphShapeTable.Count do be.WriteWord(0);
for il := 0 to GlyphShapeTable.Count - 1 do
begin
OffsetTable.Add(Pointer(be.BitsStream.Position - PP));
BE.WriteByte($10);
Edges := TObjectList(GlyphShapeTable.Items[il]);
if Edges.Count > 0 then
begin
for il2 := 0 to Edges.Count - 1 do
With TSWFShapeRecord(Edges[il2]) do
begin
if ShapeRecType = StyleChangeRecord then
with TSWFStyleChangeRecord(Edges[il2]) do
begin
bitsFill := 1;
bitsLine := 0;
{ StateFillStyle0 := false;
StateFillStyle1 := true;
Fill1Id := 1;
StateLineStyle := true; }
end;
WriteToStream(be);
if (il2 = (Edges.Count - 1)) and (ShapeRecType<>EndShapeRecord)
then be.WriteBits(0, 6); // add automtic end flag
end;
end else be.WriteBits(0, 6); // end flag
BE.FlushLastByte;
end;
be.BitsStream.Position := PP;
for il := 0 to OffsetTable.Count - 1 do
be.WriteWord(LongInt(OffsetTable[il]));
be.BitsStream.Position := be.BitsStream.Size;
end;
OffsetTable.Free;
end;
{
**************************************************** TSWFDefineFontInfo *****************************************************
}
constructor TSWFDefineFontInfo.Create;
begin
TagId := tagDefineFontInfo;
FCodeTable := TList.Create;
end;
destructor TSWFDefineFontInfo.Destroy;
begin
CodeTable.Free;
inherited;
end;
procedure TSWFDefineFontInfo.Assign(Source: TBasedSWFObject);
var
il: Word;
begin
inherited;
With TSWFDefineFontInfo(Source) do
begin
self.FontID := FontID;
self.SWFVersion := SWFVersion;
self.FontName := FontName;
self.FontFlagsSmallText := FontFlagsSmallText;
self.FontFlagsShiftJIS := FontFlagsShiftJIS;
self.FontFlagsANSI := FontFlagsANSI;
self.FontFlagsItalic := FontFlagsItalic;
self.FontFlagsBold := FontFlagsBold;
self.FontFlagsWideCodes := FontFlagsWideCodes;
if CodeTable.Count > 1 then
For il := 0 to CodeTable.Count - 1 do
self.CodeTable.Add(CodeTable[il]);
end;
end;
procedure TSWFDefineFontInfo.ReadFromStream(be: TBitsEngine);
var
b: Byte;
il, code: Word;
begin
FontID := be.ReadWord;
b := be.ReadByte;
FontName := be.ReadString(b);
b := be.ReadByte;
FontFlagsSmallText := CheckBit(b, 6);
FontFlagsShiftJIS := CheckBit(b, 5);
FontFlagsANSI := CheckBit(b, 4);
FontFlagsItalic := CheckBit(b, 3);
FontFlagsBold := CheckBit(b, 2);
FontFlagsWideCodes := CheckBit(b, 1);
if nGlyphs > 0 then
for il := 0 to nGlyphs - 1 do
begin
if FontFlagsWideCodes
then code := be.ReadWord
else code := be.ReadByte;
CodeTable.Add(Pointer(Code));
end;
end;
procedure TSWFDefineFontInfo.WriteTagBody(be: TBitsEngine);
var
il: Integer;
begin
be.WriteWord(FontID);
if SWFVersion > SWFVer5
then be.WriteByte(length(AnsiToUTF8(FontName)))
else be.WriteByte(length(FontName));
be.WriteString(FontName, false, SWFVersion > SWFVer5);
be.WriteBits(0, 2);
be.WriteBit(FontFlagsSmallText);
be.WriteBit(FontFlagsShiftJIS);
be.WriteBit(FontFlagsANSI);
be.WriteBit(FontFlagsItalic);
be.WriteBit(FontFlagsBold);
be.WriteBit(FontFlagsWideCodes);
if CodeTable.Count > 0 then
For il := 0 to CodeTable.Count - 1 do
if FontFlagsWideCodes
then be.WriteWord(Word(CodeTable[il]))
else be.WriteByte(byte(CodeTable[il]));
end;
{
**************************************************** TSWFDefineFontInfo2 ****************************************************
}
constructor TSWFDefineFontInfo2.Create;
begin
inherited ;
TagId := tagDefineFontInfo2;
end;
procedure TSWFDefineFontInfo2.Assign(Source: TBasedSWFObject);
begin
inherited;
LanguageCode := TSWFDefineFontInfo2(Source).LanguageCode;
end;
function TSWFDefineFontInfo2.MinVersion: Byte;
begin
Result := SWFVer6;
end;
procedure TSWFDefineFontInfo2.ReadFromStream(be: TBitsEngine);
var
b: Byte;
il: Word;
begin
FontID := be.ReadWord;
b := be.ReadByte;
FontName := be.ReadString(b);
b := be.ReadByte;
FontFlagsSmallText := CheckBit(b, 6);
FontFlagsShiftJIS := CheckBit(b, 5);
FontFlagsANSI := CheckBit(b, 4);
FontFlagsItalic := CheckBit(b, 3);
FontFlagsBold := CheckBit(b, 2);
FontFlagsWideCodes := CheckBit(b, 1); // Always = 1
LanguageCode := be.ReadByte;
if nGlyphs > 0 then
for il := 0 to nGlyphs - 1 do
CodeTable.Add(Pointer(be.ReadWord));
end;
procedure TSWFDefineFontInfo2.WriteTagBody(be: TBitsEngine);
var
il: Integer;
begin
be.WriteWord(FontID);
be.WriteByte(Length(AnsiToUtf8(FontName)));
be.WriteString(FontName, false, true);
be.WriteBits(0, 2);
be.WriteBit(FontFlagsSmallText);
be.WriteBit(FontFlagsShiftJIS);
be.WriteBit(FontFlagsANSI);
be.WriteBit(FontFlagsItalic);
be.WriteBit(FontFlagsBold);
be.WriteBit(true); // Always FontFlagsWideCodes = 1
be.WriteByte(LanguageCode);
For il := 0 to CodeTable.Count - 1 do
be.WriteWord(Word(CodeTable[il]));
end;
{
*************************************************** TSWFKerningRecord ****************************************************
}
procedure TSWFKerningRecord.Assign(source: TSWFKerningRecord);
begin
FontKerningCode1 := source.FontKerningCode1;
FontKerningCode2 := source.FontKerningCode2;
FontKerningAdjustment := source.FontKerningAdjustment;
end;
{
*************************************************** TSWFDefineFont2 ******************************************************
}
constructor TSWFDefineFont2.Create;
begin
inherited;
TagId := tagDefineFont2;
FCodeTable := TList.Create;
FFontBoundsTable := TObjectList.Create;
FFontAdvanceTable := TList.Create;
end;
destructor TSWFDefineFont2.Destroy;
begin
FontKerningTable.Free;
FontAdvanceTable.Free;
FontBoundsTable.Free;
CodeTable.Free;
inherited;
end;
procedure TSWFDefineFont2.Assign(Source: TBasedSWFObject);
var
il: Word;
R: TSWFRect;
KR: TSWFKerningRecord;
begin
inherited;
With TSWFDefineFont2(Source) do
begin
self.SWFVersion := SWFVersion;
self.FontFlagsHasLayout := FontFlagsHasLayout;
self.FontFlagsShiftJIS := FontFlagsShiftJIS;
self.FontFlagsSmallText := FontFlagsSmallText;
self.FontFlagsANSI := FontFlagsANSI;
self.FontFlagsWideOffsets := FontFlagsWideOffsets ;
self.FontFlagsWideCodes := FontFlagsWideCodes;
self.FontFlagsItalic := FontFlagsItalic;
self.FontFlagsBold := FontFlagsBold;
self.LanguageCode := LanguageCode;
self.FontName := FontName;
if CodeTable.Count>0 then
For il:=0 to CodeTable.Count-1 do
self.CodeTable.Add(CodeTable.Items[il]);
if FontFlagsHasLayout then
begin
self.FontAscent := FontAscent;
self.FontDescent := FontDescent;
self.FontLeading := FontLeading;
if FontAdvanceTable.Count > 0 then
For il:=0 to FontAdvanceTable.Count-1 do
self.FontAdvanceTable.Add(FontAdvanceTable[il]);
if FontBoundsTable.Count > 0 then
For il:=0 to FontBoundsTable.Count-1 do
begin
R := TSWFRect.Create;
R.Assign(TSWFRect(FontBoundsTable[il]));
self.FontBoundsTable.Add(R);
end;
if FontKerningTable.Count > 0 then
for il:=0 to FontKerningTable.Count-1 do
begin
KR := TSWFKerningRecord.Create;
KR.Assign(TSWFKerningRecord(FontKerningTable[il]));
self.FontKerningTable.Add(KR);
end;
end;
end;
end;
function TSWFDefineFont2.GetFontKerningTable: TObjectList;
begin
if FFontKerningTable = nil then FFontKerningTable := TObjectList.Create;
Result := FFontKerningTable;
end;
function TSWFDefineFont2.MinVersion: Byte;
begin
Result := SWFVer3;
end;
procedure TSWFDefineFont2.ReadFromStream(be: TBitsEngine);
var
PP, il: LongInt;
b, SizeOffset: Byte;
tmpGlyphCount: Word;
CodeTableOffset, OffsetPos: dword;
LO: TObjectList;
SWFRect: TSWFRect;
Kerning: TSWFKerningRecord;
OffsetList: TList;
begin
PP := be.BitsStream.Position;
FontID := be.ReadWord;
b := be.ReadByte;
FontFlagsHasLayout := CheckBit(b, 8);
FontFlagsShiftJIS := CheckBit(b, 7);
FontFlagsSmallText := CheckBit(b, 6);
FontFlagsANSI := CheckBit(b, 5);
FontFlagsWideOffsets := CheckBit(b, 4);
FontFlagsWideCodes := CheckBit(b, 3);
FontFlagsItalic := CheckBit(b, 2);
FontFlagsBold := CheckBit(b, 1);
LanguageCode := be.ReadByte;
b := be.ReadByte;
FontName := be.ReadString(b);
if SWFVersion > SWFVer5
then FontName := UTF8ToAnsi(FontName);
tmpGlyphCount := be.ReadWord;
SizeOffset := 2 + 2 * byte(FontFlagsWideOffsets);
OffsetList := TList.Create;
OffsetPos := be.BitsStream.Position;
CodeTableOffset := 0;
if tmpGlyphCount > 0 then
for il := 0 to tmpGlyphCount{ - 1} do
begin
be.BitsStream.Read(CodeTableOffset, SizeOffset);
OffsetList.Add(Pointer(Longint(CodeTableOffset)));
end;
// be.BitsStream.Seek(soFromCurrent, tmpGlyphCount *();
(* if FontFlagsWideOffsets
then CodeTableOffset := be.ReadDWord
else CodeTableOffset := be.ReadWord; *)
if tmpGlyphCount>0 then
begin
for il := 0 to tmpGlyphCount - 1 do
begin
be.BitsStream.Position := Longint(OffsetPos) + Longint(OffsetList[il]);
LO := TObjectList.Create;
b := be.ReadByte;
ReadShapeRecord(be, LO, b shr 4, b and $F, nil);
GlyphShapeTable.Add(LO);
end;
for il := 0 to tmpGlyphCount - 1 do
begin
if FontFlagsWideCodes
then CodeTable.Add(Pointer(Longint(be.ReadWord)))
else
CodeTable.Add(Pointer(LongInt(be.Readbyte)));
end;
end;
If FontFlagsHasLayout then
begin
FontAscent := be.ReadWord;
FontDescent := be.ReadWord;
FontLeading := be.ReadWord;
if tmpGlyphCount>0 then
begin
For il := 0 to tmpGlyphCount-1 do
FontAdvanceTable.Add(Pointer(smallint(be.ReadWord)));
For il := 0 to tmpGlyphCount-1 do
With be.ReadRect do
begin
SWFRect := TSWFRect.Create;
SWFRect.Xmin := Left;
SWFRect.Ymin := Top;
SWFRect.Xmax := Right;
SWFRect.Ymax := Bottom;
FontBoundsTable.Add(SWFRect);
end;
end;
KerningCount := be.ReadWord;
if KerningCount > 0 then
for il:=0 to KerningCount - 1 do
begin
Kerning := TSWFKerningRecord.Create;
if FontFlagsWideCodes then
begin
Kerning.FontKerningCode1 := be.ReadWord;
Kerning.FontKerningCode2 := be.ReadWord;
end else
begin
Kerning.FontKerningCode1 := be.ReadByte;
Kerning.FontKerningCode2 := be.ReadByte;
end;
Kerning.FontKerningAdjustment := Smallint(be.ReadWord);
FontKerningTable.Add(Kerning);
end;
end;
OffsetList.Free;
be.BitsStream.Position := Longint(BodySize) + PP;
end;
procedure TSWFDefineFont2.WriteTagBody(be: TBitsEngine);
var
il, il2: Integer;
OffsetSize: Byte;
CodeTableOffset, OffsetPos: dWord;
Edges: TObjectList;
tmpLayout: boolean;
begin
be.WriteWord(FontID);
tmpLayout := FontFlagsHasLayout and (CodeTable.Count > 0);
be.WriteBit(tmpLayout);
be.WriteBit(FontFlagsShiftJIS);
be.WriteBit(FontFlagsSmallText);
be.WriteBit(FontFlagsANSI or (CodeTable.Count = 0));
FontFlagsWideOffsets := CodeTable.Count > 128;
be.WriteBit(FontFlagsWideOffsets);
be.WriteBit(FontFlagsWideCodes);
be.WriteBit(FontFlagsItalic);
be.WriteBit(FontFlagsBold);
be.WriteByte(LanguageCode);
if SWFVersion > SWFVer5
then be.WriteByte(length(AnsiToUTF8(FontName)))
else be.WriteByte(length(FontName));
be.WriteString(FontName, false, SWFVersion > SWFVer5);
be.WriteWord(CodeTable.Count);
OffsetSize := 2 + 2 * byte(FontFlagsWideOffsets);
CodeTableOffset := 0;
OffsetPos := be.BitsStream.Position;
if CodeTable.Count > 0 then
For il := 0 to CodeTable.Count - 1 do
be.BitsStream.Write(CodeTableOffset, OffsetSize); // fill zero
be.BitsStream.Write(CodeTableOffset, OffsetSize);
if GlyphShapeTable.Count>0 then
For il:=0 to GlyphShapeTable.Count-1 do
begin
CodeTableOffset := BE.BitsStream.Position - OffsetPos;
be.BitsStream.Position := LongInt(OffsetPos) + OffsetSize * il;
be.BitsStream.Write(CodeTableOffset, OffsetSize);
be.BitsStream.Seek(0, soFromEnd);
// inc(OffsetPos, OffsetSize);
BE.WriteByte($10);
Edges := TObjectList(GlyphShapeTable.Items[il]);
if Edges.Count > 0 then
begin
for il2 := 0 to Edges.Count - 1 do
With TSWFShapeRecord(Edges[il2]) do
begin
if (ShapeRecType = StyleChangeRecord) then
with TSWFStyleChangeRecord(Edges[il2]) do
begin
bitsFill := 1;
bitsLine := 0;
if (il2 = 0) and (not (StateFillStyle0 or StateFillStyle1) or
(StateFillStyle1 and (Fill1Id = 0))) then
begin
StateFillStyle0 := false;
StateFillStyle1 := true;
StateLineStyle := true;
Fill1Id := 1
end;
end;
WriteToStream(be);
if (il2 = (Edges.Count - 1)) and (ShapeRecType<>EndShapeRecord)
then be.WriteBits(0, 6); // add automtic end flag
end;
end else be.WriteBits(0, 6); // end flag
BE.FlushLastByte;
end;
CodeTableOffset := BE.BitsStream.Position - OffsetPos;
be.BitsStream.Position := Longint(OffsetPos) + OffsetSize * GlyphShapeTable.Count;
be.BitsStream.Write(CodeTableOffset, OffsetSize);
be.BitsStream.Seek(0, soFromEnd);
if CodeTable.Count>0 then
For il:=0 to CodeTable.Count-1 do
begin
CodeTableOffset := Longint(CodeTable.Items[il]);
be.BitsStream.Write(CodeTableOffset, 1 + byte(FontFlagsWideCodes));
end;
if tmpLayout then
begin
be.WriteWord(FontAscent);
be.WriteWord(FontDescent);
be.WriteWord(FontLeading);
if FontAdvanceTable.Count > 0 then
For il:=0 to FontAdvanceTable.Count-1 do
be.WriteWord(word(FontAdvanceTable[il]));
if FontBoundsTable.Count > 0 then
For il:=0 to FontBoundsTable.Count-1 do
with TSWFRect(FontBoundsTable[il]) do
be.WriteRect(Rect);
be.WriteWord(FontKerningTable.Count);
if FontKerningTable.Count > 0 then
for il:=0 to FontKerningTable.Count-1 do
with TSWFKerningRecord(FontKerningTable[il]) do
begin
if FontFlagsWideCodes then be.WriteWord(FontKerningCode1)
else be.WriteByte(FontKerningCode1);
if FontFlagsWideCodes then be.WriteWord(FontKerningCode2)
else be.WriteByte(FontKerningCode2);
be.WriteWord(Word(FontKerningAdjustment));
end;
end;
end;
{
****************************************************** TSWFTextRecord *******************************************************
}
constructor TSWFDefineFont3.Create;
begin
inherited;
TagID := tagDefineFont3;
FontFlagsWideCodes := true;
end;
function TSWFDefineFont3.MinVersion: Byte;
begin
Result := SWFVer8;
end;
function TSWFZoneRecord.AddZoneData: TSWFZoneData;
begin
Result := TSWFZoneData.Create;
Add(Result);
end;
{
****************************************************** TSWFZoneRecord *******************************************************
}
function TSWFZoneRecord.GetZoneData(Index: Integer): TSWFZoneData;
begin
Result := TSWFZoneData(Items[Index]);
end;
function TSWFZoneTable.AddZoneRecord: TSWFZoneRecord;
begin
Result := TSWFZoneRecord.Create;
Add(Result);
end;
{
****************************************************** TSWFZoneTable *******************************************************
}
function TSWFZoneTable.GetZoneRecord(Index: Integer): TSWFZoneRecord;
begin
Result := TSWFZoneRecord(Items[Index]);
end;
{
****************************************************** TSWFDefineFontAlignZones *******************************************************
}
constructor TSWFDefineFontAlignZones.Create;
begin
inherited;
TagID := tagDefineFontAlignZones;
FZoneTable := TSWFZoneTable.Create;
end;
destructor TSWFDefineFontAlignZones.Destroy;
begin
FZoneTable.Free;
inherited;
end;
function TSWFDefineFontAlignZones.MinVersion: Byte;
begin
Result := SWFVer8;
end;
procedure TSWFDefineFontAlignZones.ReadFromStream(be: TBitsEngine);
var b: byte;
PP: LongInt;
ZR: TSWFZoneRecord;
ZD: TSWFZoneData;
begin
PP := be.BitsStream.Position;
FontID := be.ReadWord;
b := be.ReadByte;
CSMTableHint := b shr 6;
While (PP + Longint(BodySize) > be.BitsStream.Position) do
begin
ZR := ZoneTable.AddZoneRecord;
ZR.NumZoneData := be.ReadByte;
While ZR.Count < ZR.FNumZoneData do
begin
ZD := ZR.AddZoneData;
ZD.AlignmentCoordinate := be.ReadWord;//be.ReadFloat16;// WordToSingle();
ZD.Range := be.ReadWord;//be.ReadFloat16; //WordToSingle(be.ReadWord);
end;
b := be.ReadByte;
ZR.ZoneMaskX := CheckBit(b, 8);
ZR.ZoneMaskY := CheckBit(b, 7);
end;
be.BitsStream.Position := PP + Longint(BodySize);
end;
procedure TSWFDefineFontAlignZones.WriteTagBody(be: TBitsEngine);
var il, il2: word;
begin
be.WriteWord(FontID);
be.WriteByte(CSMTableHint shl 6);
if ZoneTable.Count > 0 then
for il := 0 to ZoneTable.Count - 1 do
with ZoneTable[il] do
begin
be.WriteByte(NumZoneData);
for il2 := 0 to Count - 1 do
begin
be.WriteWord(ZoneData[il2].AlignmentCoordinate);
be.WriteWord(ZoneData[il2].Range);
// be.WriteWord(SingleToWord(ZoneData[il2].AlignmentCoordinate));
// be.WriteWord(SingleToWord(ZoneData[il2].Range));
end;
be.WriteBit(ZoneMaskX);
be.WriteBit(ZoneMaskY);
be.FlushLastByte;
end;
end;
{ ****************************************************** TSWFDefineFontName ***********************************************}
constructor TSWFDefineFontName.Create;
begin
TagID := tagDefineFontName;
end;
function TSWFDefineFontName.MinVersion: Byte;
begin
Result := SWFVer9;
end;
procedure TSWFDefineFontName.ReadFromStream(be: TBitsEngine);
begin
FontId := be.ReadWord;
FontName := be.ReadString;
FontCopyright := be.ReadString;
end;
procedure TSWFDefineFontName.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(FontId);
be.WriteString(FontName);
be.WriteString(FontCopyright);
end;
{
****************************************************** TSWFTextRecord *******************************************************
}
constructor TSWFTextRecord.Create;
begin
FGlyphEntries := TObjectList.Create;
end;
destructor TSWFTextRecord.Destroy;
begin
if FTextColor <> nil then TextColor.Free;
GlyphEntries.Free;
inherited;
end;
procedure TSWFTextRecord.Assign(Source: TSWFTextRecord);
var
il: Word;
GE: TSWFGlyphEntry;
begin
With Source do
begin
self.StyleFlagsHasFont := StyleFlagsHasFont;
self.StyleFlagsHasColor := StyleFlagsHasColor;
self.StyleFlagsHasYOffset := StyleFlagsHasYOffset;
self.StyleFlagsHasXOffset := StyleFlagsHasXOffset;
if self.StyleFlagsHasFont then
self.FontID := FontID;
if StyleFlagsHasColor then
self.TextColor.Assign(TextColor);
if StyleFlagsHasXOffset then self.XOffset := XOffset;
if StyleFlagsHasYOffset then self.YOffset := YOffset;
if StyleFlagsHasFont then self.TextHeight := TextHeight;
if GlyphEntries.Count > 0 then
for il := 0 to GlyphEntries.Count-1 do
begin
GE := TSWFGlyphEntry.Create;
GE.GlyphAdvance := GlyphEntry[il].GlyphAdvance;
GE.GlyphIndex := GlyphEntry[il].GlyphIndex;
self.GlyphEntries.Add(GE);
end;
end;
end;
function TSWFTextRecord.GetGlyphEntry(Index: word): TSWFGlyphEntry;
begin
Result := TSWFGlyphEntry(GlyphEntries[index]);
end;
function TSWFTextRecord.GetTextColor: TSWFRGBA;
begin
FStyleFlagsHasColor := true;
if FTextColor = nil then FTextColor := TSWFRGBA.Create;
Result := FTextColor;
end;
procedure TSWFTextRecord.SetFontID(Value: Word);
begin
FStyleFlagsHasFont := true;
FFontID := Value;
end;
procedure TSWFTextRecord.SetTextHeight(Value: Word);
begin
FStyleFlagsHasFont := true;
FTextHeight := Value;
end;
procedure TSWFTextRecord.SetXOffset(Value: Integer);
begin
StyleFlagsHasXOffset := true;
FXOffset := Value;
end;
procedure TSWFTextRecord.SetYOffset(Value: Integer);
begin
StyleFlagsHasYOffset := true;
FYOffset := Value;
end;
procedure TSWFTextRecord.WriteToStream(be: TBitsEngine; gb, ab: byte);
var
il: Integer;
begin
be.WriteBit(true); // TextRecordType
be.WriteBits(0, 3);// StyleFlagsReserved
be.WriteBit(StyleFlagsHasFont);
be.WriteBit(StyleFlagsHasColor);
be.WriteBit(StyleFlagsHasYOffset);
be.WriteBit(StyleFlagsHasXOffset);
if StyleFlagsHasFont then be.WriteWord(FontID);
if StyleFlagsHasColor then
begin
if hasAlpha then be.WriteColor(TextColor.RGBA)
else be.WriteColor(TextColor.RGB);
end;
if StyleFlagsHasXOffset then be.WriteWord(XOffset);
if StyleFlagsHasYOffset then be.WriteWord(YOffset);
if StyleFlagsHasFont then be.WriteWord(TextHeight);
be.WriteByte(GlyphEntries.Count);
if GlyphEntries.Count > 0 then
for il := 0 to GlyphEntries.Count-1 do
with TSWFGlyphEntry(GlyphEntries[il]) do
begin
be.WriteBits(GlyphIndex, gb);
be.WriteBits(GlyphAdvance, ab);
end;
be.FlushLastByte;
end;
{
****************************************************** TSWFDefineText *******************************************************
}
constructor TSWFDefineText.Create;
begin
TagID := tagDefineText;
FTextRecords := TObjectList.Create;
FTextMatrix := TSWFMatrix.Create;
FTextBounds := TSWFRect.Create;
end;
destructor TSWFDefineText.Destroy;
begin
TextRecords.Free;
TextMatrix.Free;
TextBounds.Free;
inherited;
end;
procedure TSWFDefineText.Assign(Source: TBasedSWFObject);
var
TR: TSWFTextRecord;
il: Word;
begin
inherited;
With TSWFDefineText(Source) do
begin
self.CharacterId := CharacterId;
self.AdvanceBits := AdvanceBits;
self.CharacterID := CharacterID;
self.GlyphBits := GlyphBits;
self.hasAlpha := hasAlpha;
self.TextBounds.Assign(TextBounds);
self.TextMatrix.Assign(TextMatrix);
if TextRecords.Count > 0 then
for il := 0 to TextRecords.Count - 1 do
begin
TR := TSWFTextRecord.Create;
TR.Assign(TextRecord[il]);
self.TextRecords.Add(TR);
end;
end;
end;
function TSWFDefineText.GetTextRecord(Index: Integer): TSWFTextRecord;
begin
Result := TSWFTextRecord(TextRecords[Index]);
end;
procedure TSWFDefineText.ReadFromStream(be: TBitsEngine);
var
PP: LongInt;
TR: TSWFTextRecord;
GE: TSWFGlyphEntry;
b, fGliphCount, il: Byte;
begin
PP := be.BitsStream.Position;
CharacterID := be.ReadWord;
TextBounds.Rect := be.ReadRect;
TextMatrix.Rec := be.ReadMatrix;
GlyphBits := be.ReadByte;
AdvanceBits := be.ReadByte;
Repeat
b := be.ReadByte;
if b > 0 then
begin
TR := TSWFTextRecord.Create;
TR.hasAlpha := hasAlpha;
TR.StyleFlagsHasFont := CheckBit(b, 4);
TR.StyleFlagsHasColor := CheckBit(b, 3);
TR.StyleFlagsHasYOffset := CheckBit(b, 2);
TR.StyleFlagsHasXOffset := CheckBit(b, 1);
if TR.StyleFlagsHasFont then TR.FontID := be.ReadWord;
if TR.StyleFlagsHasColor then
begin
if hasAlpha then TR.TextColor.RGBA := be.ReadRGBA
else TR.TextColor.RGB := be.ReadRGB;
end;
if TR.StyleFlagsHasXOffset then TR.XOffset := be.ReadWord;
if TR.StyleFlagsHasYOffset then TR.YOffset := be.ReadWord;
if TR.StyleFlagsHasFont then TR.TextHeight := be.ReadWord;
fGliphCount := be.ReadByte;
if fGliphCount > 0 then
for il :=1 to fGliphCount do
begin
GE := TSWFGlyphEntry.Create;
GE.GlyphIndex := be.GetBits(GlyphBits);
GE.GlyphAdvance := be.GetSBits(AdvanceBits);
TR.GlyphEntries.Add(GE);
end;
be.FlushLastByte(false);
TextRecords.Add(TR);
end;
Until b = 0;
be.BitsStream.Position := Longint(BodySize) + PP;
end;
procedure TSWFDefineText.WriteTagBody(be: TBitsEngine);
var
il: Integer;
begin
be.WriteWord(CharacterID);
be.WriteRect(TextBounds.Rect);
be.WriteMatrix(TextMatrix.Rec);
be.WriteByte(GlyphBits);
be.WriteByte(AdvanceBits);
for il := 0 to TextRecords.Count - 1 do
with TSWFTextRecord(TextRecords[il]) do
begin
hasAlpha := self.hasAlpha;
WriteToStream(be, GlyphBits, AdvanceBits);
end;
be.WriteByte(0); // EndOfRecordsFlag
end;
{
****************************************************** TSWFDefineText2 ******************************************************
}
constructor TSWFDefineText2.Create;
begin
inherited ;
TagID := tagDefineText2;
hasAlpha := true;
end;
function TSWFDefineText2.MinVersion: Byte;
begin
Result := SWFVer3;
end;
{
**************************************************** TSWFDefineEditText *****************************************************
}
constructor TSWFDefineEditText.Create;
begin
TagID := tagDefineEditText;
FBounds := TSWFRect.Create;
end;
destructor TSWFDefineEditText.Destroy;
begin
if FBounds <> nil then FBounds.Free;
if FTextColor <> nil then FTextColor.Free;
inherited;
end;
procedure TSWFDefineEditText.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFDefineEditText(Source) do
begin
self.CharacterID := CharacterID;
self.Bounds.Assign(Bounds);
self.HasText := HasText;
self.WordWrap := WordWrap;
self.Multiline := Multiline;
self.Password := Password;
self.ReadOnly := ReadOnly;
self.HasTextColor := HasTextColor;
self.HasMaxLength := HasMaxLength;
self.HasFont := HasFont;
self.AutoSize := AutoSize;
self.HasLayout := HasLayout;
self.NoSelect := NoSelect;
self.Border := Border;
self.HTML := HTML;
self.UseOutlines := UseOutlines;
if HasFont then
begin
self.FontID := FontID;
self.FontHeight := FontHeight;
end;
self.HasFontClass := HasFontClass;
if HasFontClass then self.FontClass := FontClass;
if HasTextColor then self.TextColor.Assign(TextColor);
If HasMaxLength then self.MaxLength := MaxLength;
If HasLayout then
begin
self.Align := Align;
self.LeftMargin := LeftMargin;
self.RightMargin := RightMargin;
self.Indent := Indent;
self.Leading := Leading;
end;
self.VariableName := VariableName;
if HasText then
self.InitialText := InitialText;
end;
end;
function TSWFDefineEditText.GetTextColor: TSWFRGBA;
begin
if FTextColor = nil then FTextColor := TSWFRGBA.Create;
HasTextColor := true;
Result := FTextColor;
end;
function TSWFDefineEditText.MinVersion: Byte;
begin
if HasFontClass then Result := SWFVer9 else
if AutoSize then Result := SWFVer6
else Result := SWFVer4;
end;
procedure TSWFDefineEditText.ReadFromStream(be: TBitsEngine);
var
b: Byte;
begin
CharacterID := be.ReadWord;
Bounds.Rect := be.ReadRect;
b := be.ReadByte;
HasText := CheckBit(b, 8);
WordWrap := CheckBit(b, 7);
Multiline := CheckBit(b, 6);
Password := CheckBit(b, 5);
ReadOnly := CheckBit(b, 4);
HasTextColor := CheckBit(b, 3);
HasMaxLength := CheckBit(b, 2);
HasFont := CheckBit(b, 1);
b := be.ReadByte;
if SWFVersion > SWFVer8
then HasFontClass := CheckBit(b, 8)
else HasFontClass := false;
AutoSize := CheckBit(b, 7);
HasLayout := CheckBit(b, 6);
NoSelect := CheckBit(b, 5);
Border := CheckBit(b, 4);
HTML := CheckBit(b, 2);
UseOutlines := CheckBit(b, 1);
if HasFont then
FontID := be.ReadWord;
if HasFontClass then
FontClass := be.ReadString;
if HasFont then
FontHeight := be.ReadWord;
if HasTextColor then TextColor.RGBA := be.ReadRGBA;
If HasMaxLength then MaxLength := be.ReadWord;
If HasLayout then
begin
Align := be.ReadByte;
LeftMargin := be.ReadWord;
RightMargin := be.ReadWord;
Indent := be.ReadWord;
Leading := be.ReadWord;
end;
VariableName := be.ReadString;
if HasText then
InitialText := be.ReadString;
end;
procedure TSWFDefineEditText.WriteTagBody(be: TBitsEngine);
var
Len: Integer;
UTF8Ar: PChar;
begin
be.WriteWord(CharacterID);
be.WriteRect(Bounds.Rect);
be.WriteBit(HasText);
be.WriteBit(WordWrap);
be.WriteBit(Multiline);
be.WriteBit(Password);
be.WriteBit(ReadOnly);
be.WriteBit(HasTextColor);
be.WriteBit(HasMaxLength);
be.WriteBit(HasFont);
HasFontClass := (SWFVersion > SWFVer8) and (ClassName <> '');
be.WriteBit(HasFontClass);
be.WriteBit(AutoSize);
be.WriteBit(HasLayout);
be.WriteBit(NoSelect);
be.WriteBit(Border);
be.WriteBit(false); // Flash Reserved
be.WriteBit(HTML);
be.WriteBit(UseOutlines);
if HasFont then
be.WriteWord(FontID);
if HasFontClass then
be.WriteString(FontClass);
if HasFont then
be.WriteWord(FontHeight);
if HasTextColor then be.WriteColor(TextColor.RGBA);
If HasMaxLength then be.WriteWord(MaxLength);
If HasLayout then
begin
be.WriteByte(Align);
be.WriteWord(LeftMargin);
be.WriteWord(RightMargin);
be.WriteWord(Indent);
be.WriteWord(Leading);
end;
be.WriteString(VariableName, true, SWFVersion > SWFVer5);
if HasText then
begin
If (WideInitialText = '') then
be.WriteString(InitialText, true, (not HTML) and (SWFVersion > SWFVer5))
else
begin
Len := UnicodeToUtf8(nil, $FFFF, PWideChar(WideInitialText), Length(WideInitialText));
GetMem(UTF8Ar, Len);
UnicodeToUtf8(UTF8Ar, Len, PWideChar(WideInitialText), Length(WideInitialText));
be.WriteUTF8String(UTF8Ar, Len);
FreeMem(UTF8Ar, Len);
end;
end;
end;
{
****************************************************** TSWFCSMTextSettings *******************************************************
}
constructor TSWFCSMTextSettings.Create;
begin
TagID := tagCSMTextSettings;
end;
destructor TSWFCSMTextSettings.Destroy;
begin
inherited;
end;
procedure TSWFCSMTextSettings.Assign(Source: TBasedSWFObject);
begin
with TSWFCSMTextSettings(Source) do
begin
self.TextID := TextID;
self.UseFlashType := UseFlashType;
self.GridFit := GridFit;
self.Thickness := Thickness;
self.Sharpness := Sharpness;
end;
end;
function TSWFCSMTextSettings.MinVersion: Byte;
begin
Result := SWFVer8;
end;
procedure TSWFCSMTextSettings.ReadFromStream(be: TBitsEngine);
var b: byte;
begin
TextID := be.ReadWord;
b := be.ReadByte;
UseFlashType := b shr 6;
GridFit := (b shr 3) and 3;
Thickness := be.ReadFloat;
Sharpness := be.ReadFloat;
be.ReadByte;
end;
procedure TSWFCSMTextSettings.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(TextID);
be.WriteBits(UseFlashType, 2);
be.WriteBits(GridFit, 3);
be.FlushLastByte;
be.WriteFloat(Thickness);
be.WriteFloat(Sharpness);
be.WriteByte(0);
end;
// ===========================================================
// VIDEO
// ===========================================================
{
****************************************************** TSWFVideoFrame *******************************************************
}
constructor TSWFVideoFrame.Create;
begin
tagID := tagVideoFrame;
end;
procedure TSWFVideoFrame.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFVideoFrame(Source) do
begin
self.StreamId := StreamId;
self.FrameNum := FrameNum;
end;
end;
function TSWFVideoFrame.MinVersion: Byte;
begin
Result := SWFVer6;
end;
procedure TSWFVideoFrame.ReadFromStream(be: TBitsEngine);
begin
StreamID := be.ReadWord;
FrameNum := be.ReadWord;
DataSize := BodySize - 4;
selfdestroy := true;
GetMem(FData, DataSize);
be.BitsStream.Read(Data^, DataSize);
end;
procedure TSWFVideoFrame.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(StreamID);
be.WriteWord(FrameNum);
if Assigned(FOnDataWrite) then OnDataWrite(self, be) else
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
end;
{
*************************************************** TSWFDefineVideoStream ***************************************************
}
constructor TSWFDefineVideoStream.Create;
begin
tagID := tagDefinevideoStream;
end;
procedure TSWFDefineVideoStream.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFDefineVideoStream(Source) do
begin
self.CharacterID := CharacterID;
self.CodecID := CodecID;
self.Height := Height;
self.NumFrames := NumFrames;
self.VideoFlagsDeblocking := VideoFlagsDeblocking;
self.VideoFlagsSmoothing := VideoFlagsSmoothing;
self.Width := Width;
end;
end;
function TSWFDefineVideoStream.MinVersion: Byte;
begin
Result := SWFVer6 + byte(CodecID = 3);
end;
procedure TSWFDefineVideoStream.ReadFromStream(be: TBitsEngine);
var
B: Byte;
begin
CharacterID := be.ReadWord;
NumFrames := be.ReadWord;
Width := be.ReadWord;
Height := be.ReadWord;
B := be.ReadByte;
VideoFlagsDeblocking := (B shr 1) and 7;
VideoFlagsSmoothing := CheckBit(b, 1);
CodecID := be.ReadByte;
end;
procedure TSWFDefineVideoStream.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(CharacterID);
be.WriteWord(NumFrames);
be.WriteWord(Width);
be.WriteWord(Height);
be.WriteBits(0, 5);
be.WriteBits(VideoFlagsDeblocking, 2);
be.WriteBit(VideoFlagsSmoothing);
be.WriteByte(CodecID);
end;
// ===========================================================
// SOUND
// ===========================================================
{
****************************************************** TSWFDefineSound ******************************************************
}
constructor TSWFDefineSound.Create;
begin
inherited;
tagID := tagDefineSound;
end;
procedure TSWFDefineSound.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFDefineSound(Source) do
begin
self.SeekSamples := SeekSamples;
self.SoundFormat := SoundFormat;
self.SoundId := SoundId;
self.SoundRate := SoundRate;
self.SoundSampleCount := SoundSampleCount;
self.SoundSize := SoundSize;
self.SoundType := SoundType;
end;
end;
function TSWFDefineSound.MinVersion: Byte;
begin
Case SoundFormat of
snd_MP3, snd_PCM_LE: Result := SWFVer4;
snd_Nellymoser: Result := SWFVer6;
else Result := SWFVer1;
end;
end;
procedure TSWFDefineSound.ReadFromStream(be: TBitsEngine);
var
B: Byte;
PP: LongInt;
begin
pp := be.BitsStream.Position;
SoundId := BE.ReadWord;
b := be.ReadByte;
SoundFormat := b shr 4;
SoundRate := byte(b shl 4) shr 6;
SoundSize := CheckBit(b, 2);
SoundType := CheckBit(b, 1);
SoundSampleCount := BE.ReadDWord;
if SoundFormat = snd_mp3 then
begin
SeekSamples := BE.ReadWord;
end;
DataSize := BodySize - (BE.BitsStream.Position - PP);
GetMem(FData, DataSize);
be.BitsStream.Read(Data^, DataSize);
end;
procedure TSWFDefineSound.WriteTagBody(be: TBitsEngine);
begin
BE.WriteWord(SoundId);
BE.WriteBits(SoundFormat, 4);
BE.WriteBits(SoundRate, 2);
BE.WriteBit(SoundSize);
BE.WriteBit(SoundType);
BE.WriteDWord(SoundSampleCount);
if SoundFormat = snd_MP3 then
begin
BE.WriteWord(SeekSamples);
// BE.WriteWord($FFFF);
end;
if Assigned(OnDataWrite) then OnDataWrite(self, be) else
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
end;
{
***************************************************** TSWFSoundEnvelope *****************************************************
}
procedure TSWFSoundEnvelope.Assign(Source: TSWFSoundEnvelope);
begin
LeftLevel := Source.LeftLevel;
RightLevel := Source.RightLevel;
Pos44 := Source.Pos44;
end;
{
****************************************************** TSWFStartSound *******************************************************
}
constructor TSWFStartSound.Create;
begin
TagID := tagStartSound;
FSoundEnvelopes := TObjectList.Create;
end;
destructor TSWFStartSound.Destroy;
begin
FSoundEnvelopes.Free;
end;
procedure TSWFStartSound.AddEnvelope(pos: dword; left, right: word);
var
env: TSWFSoundEnvelope;
begin
env := TSWFSoundEnvelope.Create;
env.Pos44 := pos;
env.LeftLevel := left;
env.RightLevel :=right;
SoundEnvelopes.Add(env);
HasEnvelope := true;
end;
procedure TSWFStartSound.Assign(Source: TBasedSWFObject);
var
il: Word;
SE: TSWFSoundEnvelope;
begin
inherited;
With TSWFStartSound(Source) do
begin
self.SoundId := SoundId;
self.FSoundClassName := SoundClassName;
self.SyncStop := SyncStop;
self.SyncNoMultiple := SyncNoMultiple;
self.hasEnvelope := hasEnvelope;
self.HasLoops := HasLoops;
self.HasOutPoint := HasOutPoint;
self.HasInPoint := HasInPoint;
if HasInPoint then self.InPoint := InPoint;
if HasOutPoint then self.OutPoint := OutPoint;
if HasLoops then self.LoopCount := LoopCount;
if HasEnvelope and (SoundEnvelopes.Count > 0) then
for il:=0 to SoundEnvelopes.Count - 1 do
begin
SE := TSWFSoundEnvelope.Create;
SE.Assign(TSWFSoundEnvelope(SoundEnvelopes[il]));
self.SoundEnvelopes.Add(SE);
end;
end;
end;
procedure TSWFStartSound.ReadFromStream(be: TBitsEngine);
var
b: Byte;
SE: TSWFSoundEnvelope;
begin
if TagID = tagStartSound
then SoundId := be.ReadWord
else SoundClassName := be.ReadString;
b := be.ReadByte;
SyncStop := CheckBit(b, 6);
SyncNoMultiple := CheckBit(b, 5);
HasEnvelope := CheckBit(b, 4);
HasLoops := CheckBit(b, 3);
HasOutPoint := CheckBit(b, 2);
HasInPoint := CheckBit(b, 1);
if HasInPoint then InPoint := be.ReadDWord;
if HasOutPoint then OutPoint := be.ReadDWord;
if HasLoops then LoopCount := be.ReadWord;
if HasEnvelope then
begin
b := be.ReadByte; // this Envelope point count
while b > 0 do
begin
SE := TSWFSoundEnvelope.Create;
SE.Pos44 := be.ReadDWord;
SE.LeftLevel := be.ReadWord;
SE.RightLevel := be.ReadWord;
SoundEnvelopes.Add(SE);
dec(b);
end;
end;
end;
procedure TSWFStartSound.SetInPoint(const Value: dword);
begin
HasInPoint := Value > 0;
FInPoint := Value;
end;
procedure TSWFStartSound.SetLoopCount(Value: Word);
begin
HasLoops := Value > 0;
FLoopCount := Value;
end;
procedure TSWFStartSound.SetOutPoint(const Value: dword);
begin
HasOutPoint := Value > 0;
FOutPoint := Value;
end;
procedure TSWFStartSound.WriteTagBody(be: TBitsEngine);
var
il: Word;
begin
if TagID = tagStartSound
then be.WriteWord(SoundId)
else be.WriteString(SoundClassName);
be.WriteBits(0, 2);
be.WriteBit(SyncStop);
be.WriteBit(SyncNoMultiple);
hasEnvelope := hasEnvelope and (SoundEnvelopes.Count > 0);
be.WriteBit(HasEnvelope);
be.WriteBit(HasLoops);
be.WriteBit(HasOutPoint);
be.WriteBit(HasInPoint);
if HasInPoint then be.WriteDWord(InPoint);
if HasOutPoint then be.WriteDWord(OutPoint);
if HasLoops then be.WriteWord(LoopCount);
if HasEnvelope then
begin
be.Writebyte(SoundEnvelopes.Count);
for il:=0 to SoundEnvelopes.Count - 1 do
with TSWFSoundEnvelope(SoundEnvelopes[il]) do
begin
be.WriteDWord(Pos44);
be.WriteWord(LeftLevel);
be.WriteWord(RightLevel);
end;
end;
end;
{
**************************************************** TSWFStartSound2 ****************************************************
}
constructor TSWFStartSound2.Create;
begin
TagID := tagStartSound2;
end;
function TSWFStartSound2.MinVersion: Byte;
begin
Result := SWFVer9;
end;
{
**************************************************** TSWFSoundStreamHead ****************************************************
}
constructor TSWFSoundStreamHead.Create;
begin
TagID := tagSoundStreamHead;
end;
procedure TSWFSoundStreamHead.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFSoundStreamHead(Source) do
begin
self.LatencySeek := LatencySeek;
self.PlaybackSoundRate := PlaybackSoundRate;
self.PlaybackSoundSize := PlaybackSoundSize;
self.PlaybackSoundType := PlaybackSoundType;
self.StreamSoundCompression := StreamSoundCompression;
self.StreamSoundRate := StreamSoundRate;
self.StreamSoundSampleCount := StreamSoundSampleCount;
self.StreamSoundSize := StreamSoundSize;
self.StreamSoundType := StreamSoundType;
end;
end;
function TSWFSoundStreamHead.MinVersion: Byte;
begin
Result := SWFVer1;
if StreamSoundCompression = SWFVer2 then Result := SWFVer4;
end;
procedure TSWFSoundStreamHead.ReadFromStream(be: TBitsEngine);
var
b: Byte;
begin
b := be.ReadByte;
PlaybackSoundRate := b shr 2;
PlaybackSoundSize := (b and 2) = 2;
PlaybackSoundType := (b and 1) = 1;
b := be.ReadByte;
StreamSoundCompression := b shr 4;
StreamSoundRate := byte(b shl 4) shr 6;
StreamSoundSize := (b and 2) = 2;
StreamSoundType := (b and 1) = 1;
StreamSoundSampleCount := be.ReadWord;
if (StreamSoundCompression = snd_MP3) and (BodySize > 4) then LatencySeek := be.ReadWord;
end;
procedure TSWFSoundStreamHead.WriteTagBody(be: TBitsEngine);
begin
BE.WriteBits(0, 4);
BE.WriteBits(PlaybackSoundRate, 2);
BE.WriteBit(PlaybackSoundSize); // PlaybackSoundSize 16bit
BE.WriteBit(PlaybackSoundType);
BE.WriteBits(StreamSoundCompression, 4);
BE.WriteBits(StreamSoundRate, 2);
BE.WriteBit(StreamSoundSize);
BE.WriteBit(StreamSoundType);
BE.BitsStream.Write(StreamSoundSampleCount, 2);
if StreamSoundCompression = snd_MP3 then BE.BitsStream.Write(LatencySeek, 2);
end;
{
*************************************************** TSWFSoundStreamHead2 ****************************************************
}
constructor TSWFSoundStreamHead2.Create;
begin
inherited;
TagID := tagSoundStreamHead2;
end;
function TSWFSoundStreamHead2.MinVersion: Byte;
begin
Result := SWFVer3;
if StreamSoundCompression = SWFVer2 then Result := SWFVer4 else
if StreamSoundCompression = SWFVer6 then Result := SWFVer6;
end;
{
*************************************************** TSWFSoundStreamBlock ****************************************************
}
constructor TSWFSoundStreamBlock.Create;
begin
inherited;
TagID := tagSoundStreamBlock;
end;
procedure TSWFSoundStreamBlock.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFSoundStreamBlock(Source) do
begin
self.StreamSoundCompression := StreamSoundCompression;
self.SeekSamples := SeekSamples;
self.SampleCount := SampleCount;
end;
end;
procedure TSWFSoundStreamBlock.ReadFromStream(be: TBitsEngine);
begin
DataSize := BodySize;
case StreamSoundCompression of
snd_MP3: begin
SampleCount := be.ReadWord;
SeekSamples := be.ReadWord;
DataSize := DataSize - 4;
end;
end;
SelfDestroy := true;
GetMem(FData, DataSize);
be.BitsStream.Read(Data^, DataSize);
end;
procedure TSWFSoundStreamBlock.WriteTagBody(be: TBitsEngine);
begin
case StreamSoundCompression of
snd_MP3:
begin
be.WriteWord(SampleCount);
be.WriteWord(word(SeekSamples));
end;
end;
if Assigned(OnDataWrite) then OnDataWrite(self, be) else
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
end;
// ==========================================================//
// Buttons //
// ==========================================================//
{
***************************************************** TSWFButtonRecord ******************************************************
}
constructor TSWFButtonRecord.Create(ChID: word);
begin
CharacterId := ChID;
end;
destructor TSWFButtonRecord.Destroy;
begin
if FMatrix <> nil then FMatrix.Free;
if FColorTransform <> nil then FColorTransform.Free;
end;
procedure TSWFButtonRecord.Assign(Source: TSWFButtonRecord);
begin
ButtonHasBlendMode := Source.ButtonHasBlendMode;
ButtonHasFilterList := Source.ButtonHasFilterList;
ButtonState := Source.ButtonState;
CharacterID := Source.CharacterID;
if Source.hasColorTransform then
ColorTransform.Assign(Source.ColorTransform);
Depth := Source.Depth;
Matrix.Assign(Source.Matrix);
BlendMode := Source.BlendMode;
// todo FilterList.A
end;
function TSWFButtonRecord.GetColorTransform: TSWFColorTransform;
begin
if FColorTransform = nil then
begin
FColorTransform := TSWFColorTransform.Create;
FColorTransform.hasAlpha := true;
end;
hasColorTransform := true;
Result := FColorTransform;
end;
function TSWFButtonRecord.GetMatrix: TSWFMatrix;
begin
if FMatrix = nil then FMatrix := TSWFMatrix.Create;
Result := FMatrix;
end;
function TSWFButtonRecord.GetFilterList: TSWFFilterList;
begin
if FFilterList = nil then
begin
FFilterList := TSWFFilterList.Create;
ButtonHasFilterList := true;
end;
Result := FFilterList;
end;
procedure TSWFButtonRecord.WriteToStream(be: TBitsEngine);
begin
be.WriteBits(0, 2);
be.WriteBit(ButtonHasBlendMode);
be.WriteBit(ButtonHasFilterList);
be.WriteBit(bsHitTest in ButtonState);
be.WriteBit(bsDown in ButtonState);
be.WriteBit(bsOver in ButtonState);
be.WriteBit(bsUp in ButtonState);
be.WriteWord(CharacterID);
be.WriteWord(Depth);
be.WriteMatrix(Matrix.Rec);
if hasColorTransform then
begin
ColorTransform.hasAlpha := true;
be.WriteColorTransform(ColorTransform.REC);
end;
if ButtonHasFilterList then FilterList.WriteToStream(be);
if ButtonHasBlendMode then be.WriteByte(BlendMode);
end;
{
****************************************************** TSWFBasedButton ******************************************************
}
constructor TSWFBasedButton.Create;
begin
TagId := tagDefineButton;
FButtonRecords := TObjectList.Create;
FActions := TSWFActionList.Create;
end;
destructor TSWFBasedButton.Destroy;
begin
ButtonRecords.Free;
Actions.Free;
inherited ;
end;
procedure TSWFBasedButton.Assign(Source: TBasedSWFObject);
var
il: Word;
BR: TSWFButtonRecord;
begin
inherited;
With TSWFDefineButton(Source) do
begin
self.ButtonId := ButtonId;
if ButtonRecords.Count > 0 then
for il := 0 to ButtonRecords.Count - 1 do
begin
BR := TSWFButtonRecord.Create(ButtonRecord[il].CharacterID);
BR.Assign(ButtonRecord[il]);
self.ButtonRecords.Add(BR);
end;
end;
end;
function TSWFBasedButton.GetButtonRecord(index: integer): TSWFButtonRecord;
begin
Result := TSWFButtonRecord(ButtonRecords[index]);
end;
function TSWFBasedButton.MinVersion: Byte;
begin
Result:= SWFVer3;
end;
{
***************************************************** TSWFDefineButton ******************************************************
}
procedure TSWFDefineButton.Assign(Source: TBasedSWFObject);
begin
inherited;
CopyActionList(Actions, TSWFDefineButton(Source).Actions);
end;
function TSWFDefineButton.GetAction(Index: Integer): TSWFAction;
begin
Result := TSWFAction(Actions[index]);
end;
function TSWFDefineButton.MinVersion: Byte;
var
il: Word;
begin
Result := SWFVer3;
if Actions.Count > 0 then
for il := 0 to Actions.Count - 1 do
if Result < Action[il].MinVersion then Result := Action[il].MinVersion;
end;
procedure TSWFDefineButton.ReadFromStream(be: TBitsEngine);
var
b: Byte;
BR: TSWFButtonRecord;
BA: TSWFActionByteCode;
AESz: LongInt;
begin
ButtonID := be.ReadWord;
Repeat
b := be.ReadByte;
if b > 0 then
begin
BR := TSWFButtonRecord.Create(0);
BR.ButtonHasBlendMode := false;
BR.ButtonHasFilterList := false;
BR.ButtonState := [];
if CheckBit(b, 4) then
BR.ButtonState := [bsHitTest];
if CheckBit(b, 3) then
BR.ButtonState := BR.ButtonState + [bsDown];
if CheckBit(b, 2) then
BR.ButtonState := BR.ButtonState + [bsOver];
if CheckBit(b, 1) then
BR.ButtonState := BR.ButtonState + [bsUp];
BR.CharacterID := be.ReadWord;
BR.Depth := be.ReadWord;
BR.Matrix.Rec := be.ReadMatrix;
ButtonRecords.Add(BR);
end;
Until b = 0;
if ParseActions then ReadActionList(be, Actions, $FFFF)
else
begin
AESz := FindEndActions(be);
BA := TSWFActionByteCode.Create;
BA.DataSize := AESz - be.BitsStream.Position - 1;
if BA.DataSize > 0 then
begin
BA.SelfDestroy := true;
GetMem(BA.fData, BA.DataSize);
be.BitsStream.Read(BA.Data^, BA.DataSize);
end;
Actions.Add(BA);
be.ReadByte; // last 0
end;
end;
procedure TSWFDefineButton.WriteTagBody(be: TBitsEngine);
var
il: Integer;
begin
be.WriteWord(ButtonID);
if ButtonRecords.Count > 0 then
for il := 0 to ButtonRecords.Count - 1 do
ButtonRecord[il].WriteToStream(be);
BE.WriteByte(0); //EndFlag
if Actions.count>0 then
for il := 0 to Actions.count - 1 do
TSWFAction(Actions[il]).WriteToStream(BE);
BE.WriteByte(0);
end;
{
*************************************************** TSWFButtonCondAction ****************************************************
}
procedure TSWFButtonCondAction.Assign(Source: TSWFButtonCondAction);
begin
ID_Key := Source.Id_Key;
ActionConditions := Source.ActionConditions;
CopyActionList(Source, self);
end;
function TSWFButtonCondAction.Actions: TSWFActionList;
begin
Result := self;
end;
procedure TSWFButtonCondAction.WriteToStream(be: TBitsEngine; isEnd:boolean);
var
AOffset: LongInt;
il: Word;
begin
AOffset := be.BitsStream.Size;
BE.WriteWord(0); // Offset from start of this field to next
BE.WriteBit(IdleToOverDown in ActionConditions);
BE.WriteBit(OutDownToIdle in ActionConditions);
BE.WriteBit(OutDownToOverDown in ActionConditions);
BE.WriteBit(OverDownToOutDown in ActionConditions);
BE.WriteBit(OverDownToOverUp in ActionConditions);
BE.WriteBit(OverUpToOverDown in ActionConditions);
BE.WriteBit(OverUpToIdle in ActionConditions);
BE.WriteBit(IdleToOverUp in ActionConditions);
BE.WriteBits(ID_KEY, 7);
BE.WriteBit(OverDownToIdle in ActionConditions);
if Count > 0 then
for il:=0 to Count - 1 do
Action[il].WriteToStream(BE);
BE.WriteByte(0); //EndFlag
if not isEnd then
begin
BE.BitsStream.Position := AOffset;
BE.WriteWord(BE.BitsStream.Size - AOffset);
BE.BitsStream.Position := BE.BitsStream.Size;
end;
end;
{
***************************************************** TSWFDefineButton2 *****************************************************
}
constructor TSWFDefineButton2.Create;
begin
inherited ;
TagId := tagDefineButton2;
end;
procedure TSWFDefineButton2.Assign(Source: TBasedSWFObject);
var
CA: TSWFButtonCondAction;
il: Word;
begin
inherited;
With TSWFDefineButton2(Source) do
begin
self.TrackAsMenu := TrackAsMenu;
if Actions.Count > 0 then
for il := 0 to Actions.Count - 1 do
begin
CA := TSWFButtonCondAction.Create;
self.Actions.Add(CA);
CA.Assign(CondAction[il]);
end;
end;
end;
function TSWFDefineButton2.GetCondAction(Index: Integer): TSWFButtonCondAction;
begin
Result := TSWFButtonCondAction(Actions[index]);
end;
function TSWFDefineButton2.MinVersion: Byte;
begin
Result := SWFVer3;
// + check actions
end;
procedure TSWFDefineButton2.ReadFromStream(be: TBitsEngine);
var
b: Byte;
ActionOffset, CondActionSize: Word;
PP: LongInt;
BCA: TSWFButtonCondAction;
BR: TSWFButtonRecord;
BA: TSWFActionByteCode;
AESz: LongInt;
begin
PP := be.BitsStream.Position;
ButtonId := be.ReadWord;
b := be.ReadByte;
TrackAsMenu := CheckBit(b, 1);
ActionOffset := be.ReadWord;
// if ActionOffset > 0 then
Repeat
b := be.ReadByte;
if b > 0 then
begin
BR := TSWFButtonRecord.Create(0);
BR.ButtonHasBlendMode := CheckBit(b, 6);
BR.ButtonHasFilterList := CheckBit(b, 5);
BR.hasColorTransform := true;
BR.ButtonState := [];
if CheckBit(b, 4) then
BR.ButtonState := [bsHitTest];
if CheckBit(b, 3) then
BR.ButtonState := BR.ButtonState + [bsDown];
if CheckBit(b, 2) then
BR.ButtonState := BR.ButtonState + [bsOver];
if CheckBit(b, 1) then
BR.ButtonState := BR.ButtonState + [bsUp];
BR.CharacterID := be.ReadWord;
BR.Depth := be.ReadWord;
BR.Matrix.Rec := be.ReadMatrix;
BR.ColorTransform.REC := be.ReadColorTransform;
if BR.ButtonHasFilterList then
begin
BR.FilterList.ReadFromStream(be);
end;
if BR.ButtonHasBlendMode then BR.BlendMode := be.ReadByte;
ButtonRecords.Add(BR);
end;
Until b = 0;
PP := BodySize - (be.BitsStream.Position - PP);
if (ActionOffset > 0) and (PP > 0) then
Repeat
BCA := TSWFButtonCondAction.Create;
CondActionSize := be.ReadWord;
b := be.ReadByte;
if CheckBit(b, 8) then BCA.ActionConditions := [IdleToOverDown]
else BCA.ActionConditions := [];
if CheckBit(b, 7) then BCA.ActionConditions := BCA.ActionConditions + [OutDownToIdle];
if CheckBit(b, 6) then BCA.ActionConditions := BCA.ActionConditions + [OutDownToOverDown];
if CheckBit(b, 5) then BCA.ActionConditions := BCA.ActionConditions + [OverDownToOutDown];
if CheckBit(b, 4) then BCA.ActionConditions := BCA.ActionConditions + [OverDownToOverUp];
if CheckBit(b, 3) then BCA.ActionConditions := BCA.ActionConditions + [OverUpToOverDown];
if CheckBit(b, 2) then BCA.ActionConditions := BCA.ActionConditions + [OverUpToIdle];
if CheckBit(b, 1) then BCA.ActionConditions := BCA.ActionConditions + [IdleToOverUp];
b := be.ReadByte;
if CheckBit(b, 1) then BCA.ActionConditions := BCA.ActionConditions + [OverDownToIdle];
BCA.ID_Key := b shr 1;
(* if CondActionSize = 0 then ASize := PP else
begin
ASize := CondActionSize - 2; // 1 + 1
PP := PP - CondActionSize;
end; *)
if ParseActions then ReadActionList(be, BCA, $FFFF) // Auto find End
else
begin
AESz := FindEndActions(be);
BA := TSWFActionByteCode.Create;
BA.DataSize := AESz - be.BitsStream.Position - 1;
if BA.DataSize > 0 then
begin
BA.SelfDestroy := true;
GetMem(BA.fData, BA.DataSize);
be.BitsStream.Read(BA.Data^, BA.DataSize);
end;
BCA.Add(BA);
be.ReadByte; // last 0
end;
Actions.Add(BCA);
Until CondActionSize = 0;
end;
procedure TSWFDefineButton2.WriteTagBody(be: TBitsEngine);
var
AOffset: LongInt;
il: Word;
begin
BE.WriteWord(ButtonId);
BE.WriteByte(Byte(TrackAsMenu));
AOffset := be.BitsStream.Size;
BE.WriteWord(0);
if ButtonRecords.count>0 then
for il:=0 to ButtonRecords.count - 1 do
with ButtonRecord[il] do
begin
hasColorTransform := true;
WriteToStream(BE);
end;
BE.WriteByte(0); //EndFlag
if Actions.Count > 0 then
begin
be.BitsStream.Position := AOffset;
AOffset := be.BitsStream.Size - AOffset ;
be.WriteWord(AOffset);
be.BitsStream.Position := be.BitsStream.Size;
for il:=0 to Actions.Count-1 do
TSWFButtonCondAction(Actions[il]).WriteToStream(BE, il = (Actions.Count-1));
end;
end;
{
************************************************** TSWFDefineButtonCxform ***************************************************
}
constructor TSWFDefineButtonCxform.Create;
begin
TagID := tagDefineButtonCxform;
FButtonColorTransform := TSWFColorTransform.Create;
end;
destructor TSWFDefineButtonCxform.Destroy;
begin
FButtonColorTransform.Free;
end;
procedure TSWFDefineButtonCxform.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFDefineButtonCxform(Source) do
begin
self.ButtonId := ButtonId;
self.ButtonColorTransform.Assign(ButtonColorTransform);
end;
end;
function TSWFDefineButtonCxform.MinVersion: Byte;
begin
result := SWFVer2;
end;
procedure TSWFDefineButtonCxform.ReadFromStream(be: TBitsEngine);
begin
ButtonID := be.ReadWord;
ButtonColorTransform.REC := be.ReadColorTransform(false);
end;
procedure TSWFDefineButtonCxform.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(ButtonID);
be.WriteColorTransform(ButtonColorTransform.REC);
end;
{
*************************************************** TSWFDefineButtonSound ***************************************************
}
constructor TSWFDefineButtonSound.Create;
begin
TagID := tagDefineButtonSound;
end;
destructor TSWFDefineButtonSound.Destroy;
begin
if FSndIdleToOverUp <> nil then FSndIdleToOverUp.Free;
if FSndOverDownToOverUp <> nil then FSndOverDownToOverUp.Free;
if FSndOverUpToIdle <> nil then FSndOverUpToIdle.Free;
if FSndOverUpToOverDown <> nil then FSndOverUpToOverDown.Free;
inherited Destroy;
end;
procedure TSWFDefineButtonSound.Assign(Source: TBasedSWFObject);
begin
inherited;
With TSWFDefineButtonSound(Source) do
begin
self.ButtonId := ButtonId;
if HasOverUpToIdle and (SndOverUpToIdle.SoundId > 0)
then self.SndOverUpToIdle.Assign(SndOverUpToIdle);
if HasIdleToOverUp and (SndIdleToOverUp.SoundId > 0)
then self.SndIdleToOverUp.Assign(SndIdleToOverUp);
if HasOverUpToOverDown and (SndOverUpToOverDown.SoundId > 0)
then self.SndOverUpToOverDown.Assign(SndOverUpToOverDown);
if HasOverDownToOverUp and (SndOverDownToOverUp.SoundId > 0)
then self.SndOverDownToOverUp.Assign(SndOverDownToOverUp);
end;
end;
function TSWFDefineButtonSound.GetSndIdleToOverUp: TSWFStartSound;
begin
if FSndIdleToOverUp = nil then FSndIdleToOverUp := TSWFStartSound.Create;
HasIdleToOverUp := true;
Result := FSndIdleToOverUp;
end;
function TSWFDefineButtonSound.GetSndOverDownToOverUp: TSWFStartSound;
begin
if FSndOverDownToOverUp = nil then FSndOverDownToOverUp := TSWFStartSound.Create;
HasOverDownToOverUp:= true;
Result := FSndOverDownToOverUp;
end;
function TSWFDefineButtonSound.GetSndOverUpToIdle: TSWFStartSound;
begin
if FSndOverUpToIdle = nil then FSndOverUpToIdle := TSWFStartSound.Create;
HasOverUpToIdle := true;
Result := FSndOverUpToIdle;
end;
function TSWFDefineButtonSound.GetSndOverUpToOverDown: TSWFStartSound;
begin
if FSndOverUpToOverDown = nil then FSndOverUpToOverDown:= TSWFStartSound.Create;
HasOverUpToOverDown := true;
Result := FSndOverUpToOverDown;
end;
function TSWFDefineButtonSound.MinVersion: Byte;
begin
Result := SWFVer2;
end;
procedure TSWFDefineButtonSound.ReadFromStream(be: TBitsEngine);
var
W: Word;
begin
ButtonId := be.ReadWord;
W := be.ReadWord;
if W > 0 then
begin
be.BitsStream.Seek( -2, soFromCurrent);
SndOverUpToIdle.ReadFromStream(be);
end;
W := be.ReadWord;
if W > 0 then
begin
be.BitsStream.Seek( -2, soFromCurrent);
SndIdleToOverUp.ReadFromStream(be);
end;
W := be.ReadWord;
if W > 0 then
begin
be.BitsStream.Seek( -2, soFromCurrent);
SndOverUpToOverDown.ReadFromStream(be);
end;
W := be.ReadWord;
if W > 0 then
begin
be.BitsStream.Seek( -2, soFromCurrent);
SndOverDownToOverUp.ReadFromStream(be);
end;
end;
procedure TSWFDefineButtonSound.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(ButtonId);
if HasOverUpToIdle and (SndOverUpToIdle.SoundId > 0)
then SndOverUpToIdle.WriteTagBody(be) else be.WriteWord(0);
if HasIdleToOverUp and (SndIdleToOverUp.SoundId > 0)
then SndIdleToOverUp.WriteTagBody(be) else be.WriteWord(0);
if HasOverUpToOverDown and (SndOverUpToOverDown.SoundId > 0)
then SndOverUpToOverDown.WriteTagBody(be) else be.WriteWord(0);
if HasOverDownToOverUp and (SndOverDownToOverUp.SoundId > 0)
then SndOverDownToOverUp.WriteTagBody(be) else be.WriteWord(0);
end;
// ==========================================================//
// SPRITE //
// ==========================================================//
{
***************************************************** TSWFDefineSprite ******************************************************
}
constructor TSWFDefineSprite.Create;
begin
TagId := tagDefineSprite;
FControlTags := TObjectList.Create;
end;
destructor TSWFDefineSprite.Destroy;
begin
ControlTags.Free;
inherited;
end;
procedure TSWFDefineSprite.Assign(Source: TBasedSWFObject);
var
il: Word;
NewT, OldT: TSWFObject;
begin
inherited;
With TSWFDefineSprite(Source) do
begin
self.SWFVersion := SWFVersion;
self.SpriteID := SpriteID;
self.FrameCount := FrameCount;
self.ParseActions := ParseActions;
if ControlTags.Count > 0 then
For il := 0 to ControlTags.Count - 1 do
begin
OldT := TSWFObject(ControlTags[il]);
NewT := GenerateSWFObject(OldT.TagId);
NewT.Assign(OldT);
self.ControlTags.Add(NewT);
end;
end;
end;
function TSWFDefineSprite.GetControlTag(Index: Integer): TSWFObject;
begin
Result := TSWFObject(ControlTags[Index]);
end;
function TSWFDefineSprite.MinVersion: Byte;
begin
Result := SWFVer3;
end;
procedure TSWFDefineSprite.ReadFromStream(be: TBitsEngine);
var
EndFlag: Boolean;
tmpW: Word;
SWFTag: TSWFObject;
SndType: byte;
begin
SpriteID := be.ReadWord;
FrameCount := be.ReadWord;
Repeat
tmpW := be.ReadWord;
EndFlag := tmpW = 0;
if not EndFlag then
begin
SWFTag := GenerateSWFObject(tmpW shr 6);
SWFTag.BodySize := (tmpW and $3f);
if SWFTag.BodySize = $3f then
SWFTag.BodySize := be.ReadDWord;
case SWFTag.TagID of
tagPlaceObject2:
with TSWFPlaceObject2(SWFTag) do
begin
SWFVersion := self.SWFVersion;
ParseActions := self.ParseActions;
end;
tagDoAction, tagDoInitAction:
TSWFDoAction(SWFTag).ParseActions := ParseActions;
tagSoundStreamBlock:
TSWFSoundStreamBlock(SWFTag).StreamSoundCompression := SndType;
end;
SWFTag.ReadFromStream(be);
if SWFTag.TagID in [tagSoundStreamHead, tagSoundStreamHead2] then
SndType := TSWFSoundStreamHead(SWFTag).StreamSoundCompression;
end else
SWFTag := GenerateSWFObject(0);
ControlTags.Add(SWFTag);
Until EndFlag;
end;
procedure TSWFDefineSprite.WriteTagBody(be: TBitsEngine);
var
il: Integer;
EndFlag: Boolean;
begin
be.WriteWord(SpriteID);
be.WriteWord(FrameCount);
EndFlag := false;
if ControlTags.Count >0 then
For il := 0 to ControlTags.Count - 1 do
With TBasedSWFObject(ControlTags[il]) do
begin
WriteToStream(be);
if (il = (ControlTags.Count - 1)) and (LibraryLevel = 0) then
with TSWFObject(ControlTags[il]) do
EndFlag := tagID = tagEnd;
end;
if not EndFlag then be.WriteWord(0);
end;
{================================= TSWFDefineSceneAndFrameLabelData ======================================}
constructor TSWFDefineSceneAndFrameLabelData.Create;
begin
TagID := tagDefineSceneAndFrameLabelData;
FScenes := TStringList.Create;
FFrameLabels := TStringList.Create;
end;
destructor TSWFDefineSceneAndFrameLabelData.Destroy;
begin
FFrameLabels.Free;
FScenes.Free;
inherited;
end;
function TSWFDefineSceneAndFrameLabelData.MinVersion: Byte;
begin
Result := SWFVer9;
end;
procedure TSWFDefineSceneAndFrameLabelData.ReadFromStream(be: TBitsEngine);
var count, il, len, fnum: DWord;
begin
count := be.ReadEncodedU32;
if count > 0 then
for il := 0 to count - 1 do
begin
len := be.ReadEncodedU32;
Scenes.Add(be.ReadString);
end;
count := be.ReadEncodedU32;
if count > 0 then
for il := 0 to count - 1 do
begin
fnum := be.ReadEncodedU32;
FrameLabels.AddObject(be.ReadString, Pointer(fnum));
end;
end;
procedure TSWFDefineSceneAndFrameLabelData.WriteTagBody(be: TBitsEngine);
var il: integer;
begin
be.WriteEncodedU32(Scenes.Count);
if Scenes.Count > 0 then
for il := 0 to Scenes.Count -1 do
begin
be.WriteEncodedU32(Length(Scenes[il]));
be.WriteString(Scenes[il]);
end;
be.WriteEncodedU32(FrameLabels.Count);
if FrameLabels.Count > 0 then
for il := 0 to FrameLabels.Count -1 do
begin
be.WriteEncodedU32(longint(FrameLabels.Objects[il]));
be.WriteString(FrameLabels[il]);
end;
end;
// ================== undocumented Flash tags ==========================
constructor TSWFByteCodeTag.Create;
begin
inherited;
FTagID := tagErrorTag;
end;
function TSWFByteCodeTag.GetByteCode(Index: word): Byte;
var B: PByte;
begin
B := Data;
Inc(B, Index);
Result := B^;
end;
procedure TSWFByteCodeTag.ReadFromStream(be: TBitsEngine);
begin
DataSize := BodySize;
GetMem(FData, DataSize);
be.BitsStream.Read(Data^, DataSize);
selfdestroy := true;
end;
procedure TSWFByteCodeTag.WriteToStream(be: TBitsEngine);
begin
TagID := TagIDFrom;
inherited;
TagIDFrom := tagErrorTag;
end;
procedure TSWFByteCodeTag.WriteTagBody(be: TBitsEngine);
begin
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
end;
{ ====================================== TSWFDefineBinaryData ===================================}
constructor TSWFDefineBinaryData.Create;
begin
inherited;
TagID := tagDefineBinaryData;
end;
procedure TSWFDefineBinaryData.ReadFromStream(be: TBitsEngine);
begin
CharacterID := be.ReadWord;
be.ReadDWord; // Reserved space
DataSize := BodySize - 2 - 4;
GetMem(FData, DataSize);
be.BitsStream.Read(Data^, DataSize);
selfdestroy := true;
end;
procedure TSWFDefineBinaryData.WriteTagBody(be: TBitsEngine);
begin
be.WriteWord(CharacterID);
be.Write4byte(0);
if Assigned(OnDataWrite) then OnDataWrite(self, be) else
if DataSize > 0 then be.BitsStream.Write(Data^, DataSize);
end;
// ========================= TOOLS ================================
Function GenerateSWFObject(ID: word): TSWFObject;
begin
Case ID of
// Display List
tagPlaceObject:
Result := TSWFPlaceObject.Create;
tagPlaceObject2:
Result := TSWFPlaceObject2.Create;
tagPlaceObject3:
Result := TSWFPlaceObject3.Create;
tagRemoveObject:
Result := TSWFRemoveObject.Create;
tagRemoveObject2:
Result := TSWFRemoveObject2.Create;
tagShowFrame:
Result := TSWFShowFrame.Create;
// Control Tags
tagSetBackgroundColor:
Result := TSWFSetBackgroundColor.Create;
tagFrameLabel:
Result := TSWFFrameLabel.Create;
tagProtect:
Result := TSWFProtect.Create;
tagEnd:
Result := TSWFEnd.Create;
tagExportAssets:
Result := TSWFExportAssets.Create;
tagImportAssets:
Result := TSWFImportAssets.Create;
tagEnableDebugger:
result := TSWFEnableDebugger.Create;
tagEnableDebugger2:
result := TSWFEnableDebugger2.Create;
tagScriptLimits:
Result := TSWFScriptLimits.Create;
tagSetTabIndex:
Result := TSWFSetTabIndex.Create;
tagFileAttributes:
Result := TSWFFileAttributes.Create;
tagMetadata:
Result := TSWFMetadata.Create;
tagProductInfo:
Result := TSWFProductInfo.Create;
tagDefineScalingGrid:
Result := TSWFDefineScalingGrid.Create;
tagImportAssets2:
Result := TSWFImportAssets2.Create;
tagSymbolClass:
Result := TSWFSymbolClass.Create;
// Actions
tagDoAction:
Result := TSWFDoAction.Create;
tagDoInitAction:
Result := TSWFDoInitAction.Create;
tagDoABC:
Result := TSWFDoABC.Create;
// Shapes
tagDefineShape:
Result := TSWFDefineShape.Create;
tagDefineShape2:
Result := TSWFDefineShape2.Create;
tagDefineShape3:
Result := TSWFDefineShape3.Create;
tagDefineShape4:
Result := TSWFDefineShape4.Create;
// Bitmaps
tagDefineBits:
Result := TSWFDefineBits.Create;
tagJPEGTables:
Result := TSWFJPEGTables.Create;
tagDefineBitsJPEG2:
Result := TSWFDefineBitsJPEG2.Create;
tagDefineBitsJPEG3:
Result := TSWFDefineBitsJPEG3.Create;
tagDefineBitsLossless:
Result := TSWFDefineBitsLossless.Create;
tagDefineBitsLossless2:
Result := TSWFDefineBitsLossless2.Create;
// Shape Morphing
tagDefineMorphShape:
Result := TSWFDefineMorphShape.Create;
tagDefineMorphShape2:
Result := TSWFDefineMorphShape2.Create;
// Fonts and Text
tagDefineFont:
Result := TSWFDefineFont.Create;
tagDefineFont2:
Result := TSWFDefineFont2.Create;
tagDefineFont3:
Result := TSWFDefineFont3.Create;
tagDefineFontInfo:
Result := TSWFDefineFontInfo.Create;
tagDefineFontInfo2:
Result := TSWFDefineFontInfo2.Create;
tagDefineFontAlignZones:
Result := TSWFDefineFontAlignZones.Create;
tagDefineFontName:
Result := TSWFDefineFontName.Create;
tagDefineText:
Result := TSWFDefineText.Create;
tagDefineText2:
Result := TSWFDefineText2.Create;
tagDefineEditText:
Result := TSWFDefineEditText.Create;
tagCSMTextSettings:
Result := TSWFCSMTextSettings.Create;
// Sounds
tagStartSound:
Result := TSWFStartSound.Create;
tagStartSound2:
Result := TSWFStartSound2.Create;
tagSoundStreamHead:
Result := TSWFSoundStreamHead.Create;
tagSoundStreamHead2:
Result := TSWFSoundStreamHead2.Create;
tagSoundStreamBlock:
Result := TSWFSoundStreamBlock.Create;
tagDefineSound :
Result := TSWFDefineSound.Create;
// Button
tagDefineButton:
Result := TSWFDefineButton.Create;
tagDefineButton2:
Result := TSWFDefineButton2.Create;
tagDefineButtonSound:
result := TSWFDefineButtonSound.Create;
tagDefineButtonCxform:
result := TSWFDefineButtonCxform.Create;
// Sprite
tagDefineSprite:
Result := TSWFDefineSprite.Create;
tagDefineSceneAndFrameLabelData:
Result := TSWFDefineSceneAndFrameLabelData.Create;
// Video
tagDefineVideoStream:
result := TSWFDefineVideoStream.Create;
tagVideoFrame:
result := TSWFVideoFrame.Create;
tagDefineBinaryData:
result := TSWFDefineBinaryData.Create;
else
begin
Result := TSWFByteCodeTag.Create;
with TSWFByteCodeTag(Result) do
begin
Text := 'Uniknow tag';
FTagIDFrom := ID;
end;
end;
end;
end;
Function GenerateSWFAction(ID: word): TSWFAction;
begin
Case ID of
// SWF 3
ActionPlay: Result := TSWFActionPlay.Create;
ActionStop: Result := TSWFActionStop.Create;
ActionNextFrame: Result := TSWFActionNextFrame.Create;
ActionPreviousFrame: Result := TSWFActionPreviousFrame.Create;
ActionGotoFrame: Result := TSWFActionGotoFrame.Create;
ActionGoToLabel: Result := TSWFActionGoToLabel.Create;
ActionWaitForFrame: Result := TSWFActionWaitForFrame.Create;
ActionGetURL: Result := TSWFActionGetURL.Create;
ActionStopSounds: Result := TSWFActionStopSounds.Create;
ActionToggleQuality: Result := TSWFActionToggleQuality.Create;
ActionSetTarget: Result := TSWFActionSetTarget.Create;
//SWF 4
ActionAdd: Result := TSWFActionAdd.Create;
ActionDivide: Result := TSWFActionDivide.Create;
ActionMultiply: Result := TSWFActionMultiply.Create;
ActionSubtract: Result := TSWFActionSubtract.Create;
ActionEquals: Result := TSWFActionEquals.Create;
ActionLess: Result := TSWFActionLess.Create;
ActionAnd: Result := TSWFActionAnd.Create;
ActionNot: Result := TSWFActionNot.Create;
ActionOr: Result := TSWFActionOr.Create;
ActionStringAdd: Result := TSWFActionStringAdd.Create;
ActionStringEquals: Result := TSWFActionStringEquals.Create;
ActionStringExtract: Result := TSWFActionStringExtract.Create;
ActionStringLength: Result := TSWFActionStringLength.Create;
ActionMBStringExtract: Result := TSWFActionMBStringExtract.Create;
ActionMBStringLength: Result := TSWFActionMBStringLength.Create;
ActionStringLess: Result := TSWFActionStringLess.Create;
ActionPop: Result := TSWFActionPop.Create;
ActionPush: Result := TSWFActionPush.Create;
ActionAsciiToChar: Result := TSWFActionAsciiToChar.Create;
ActionCharToAscii: Result := TSWFActionCharToAscii.Create;
ActionToInteger: Result := TSWFActionToInteger.Create;
ActionMBAsciiToChar: Result := TSWFActionMBAsciiToChar.Create;
ActionMBCharToAscii: Result := TSWFActionMBCharToAscii.Create;
ActionCall: Result := TSWFActionCall.Create;
ActionIf: Result := TSWFActionIf.Create;
ActionJump: Result := TSWFActionJump.Create;
ActionGetVariable: Result := TSWFActionGetVariable.Create;
ActionSetVariable: Result := TSWFActionSetVariable.Create;
ActionGetURL2: Result := TSWFActionGetURL2.Create;
ActionGetProperty: Result := TSWFActionGetProperty.Create;
ActionGotoFrame2: Result := TSWFActionGotoFrame2.Create;
ActionRemoveSprite: Result := TSWFActionRemoveSprite.Create;
ActionSetProperty: Result := TSWFActionSetProperty.Create;
ActionSetTarget2: Result := TSWFActionSetTarget2.Create;
ActionStartDrag: Result := TSWFActionStartDrag.Create;
ActionWaitForFrame2: Result := TSWFActionWaitForFrame2.Create;
ActionCloneSprite: Result := TSWFActionCloneSprite.Create;
ActionEndDrag: Result := TSWFActionEndDrag.Create;
ActionGetTime: Result := TSWFActionGetTime.Create;
ActionRandomNumber: Result := TSWFActionRandomNumber.Create;
ActionTrace: Result := TSWFActionTrace.Create;
//SWF 5
ActionCallFunction: Result := TSWFActionCallFunction.Create;
ActionCallMethod: Result := TSWFActionCallMethod.Create;
ActionConstantPool: Result := TSWFActionConstantPool.Create;
ActionDefineFunction: Result := TSWFActionDefineFunction.Create;
ActionDefineLocal: Result := TSWFActionDefineLocal.Create;
ActionDefineLocal2: Result := TSWFActionDefineLocal2.Create;
ActionDelete: Result := TSWFActionDelete.Create;
ActionDelete2: Result := TSWFActionDelete2.Create;
ActionEnumerate: Result := TSWFActionEnumerate.Create;
ActionEquals2: Result := TSWFActionEquals2.Create;
ActionGetMember: Result := TSWFActionGetMember.Create;
ActionInitArray: Result := TSWFActionInitArray.Create;
ActionInitObject: Result := TSWFActionInitObject.Create;
ActionNewMethod: Result := TSWFActionNewMethod.Create;
ActionNewObject: Result := TSWFActionNewObject.Create;
ActionSetMember: Result := TSWFActionSetMember.Create;
ActionTargetPath: Result := TSWFActionTargetPath.Create;
ActionWith: Result := TSWFActionWith.Create;
ActionToNumber: Result := TSWFActionToNumber.Create;
ActionToString: Result := TSWFActionToString.Create;
ActionTypeOf: Result := TSWFActionTypeOf.Create;
ActionAdd2: Result := TSWFActionAdd2.Create;
ActionLess2: Result := TSWFActionLess2.Create;
ActionModulo: Result := TSWFActionModulo.Create;
ActionBitAnd: Result := TSWFActionBitAnd.Create;
ActionBitLShift: Result := TSWFActionBitLShift.Create;
ActionBitOr: Result := TSWFActionBitOr.Create;
ActionBitRShift: Result := TSWFActionBitRShift.Create;
ActionBitURShift: Result := TSWFActionBitURShift.Create;
ActionBitXor: Result := TSWFActionBitXor.Create;
ActionDecrement: Result := TSWFActionDecrement.Create;
ActionIncrement: Result := TSWFActionIncrement.Create;
ActionPushDuplicate: Result := TSWFActionPushDuplicate.Create;
ActionReturn: Result := TSWFActionReturn.Create;
ActionStackSwap: Result := TSWFActionStackSwap.Create;
ActionStoreRegister: Result := TSWFActionStoreRegister.Create;
//SWF 6
ActionInstanceOf: Result := TSWFActionInstanceOf.Create;
ActionEnumerate2: Result := TSWFActionEnumerate2.Create;
ActionStrictEquals: Result := TSWFActionStrictEquals.Create;
ActionGreater: Result := TSWFActionGreater.Create;
ActionStringGreater: Result := TSWFActionStringGreater.Create;
//SWF 7
ActionDefineFunction2: Result := TSWFActionDefineFunction2.Create;
ActionExtends: Result := TSWFActionExtends.Create;
ActionCastOp: Result := TSWFActionCastOp.Create;
ActionImplementsOp: Result := TSWFActionImplementsOp.Create;
ActionTry: Result := TSWFActionTry.Create;
ActionThrow: Result := TSWFActionThrow.Create;
actionFSCommand2: Result := TSWFActionFSCommand2.Create;
actionByteCode: Result := TSWFActionByteCode.Create;
ActionOffsetWork: Result := TSWFOffsetMarker.Create;
else Result := nil;
end;
end;
Initialization
tmpMemStream := TMemoryStream.Create;
finalization
tmpMemStream.free;
{$IFDEF DebugAS3}
if SLDebug <> nil then
begin
SLDebug.SaveToFile('debugAsS3.txt');
SLDebug.Free;
end;
{$ENDIF}
end.
|
unit CatJSRunnerAS;
{
Catarinka ActiveScript Executor (from Syhunt Scarlett project)
Copyright (c) 2013-2020 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
}
interface
uses
Classes, CatActiveScript, CatActiveScript32, SysUtils;
type
TScarlettActiveScriptError = procedure(Line, Pos: Integer;
ASrc, ADescription: String) of object;
type
TScarlettActiveScript = class
private
asw: TSyActiveScriptWindow;
aswold: TXSyActiveScriptWindow;
fErrors: TStringList;
fUseOldParser: boolean;
fScript: string;
fScriptHeader: TStringList;
fScriptSuccess: boolean;
fScriptLanguage: string;
fOnScriptError: TScarlettActiveScriptError;
fUseSafeSubSet: boolean;
procedure aswError(Sender: TObject; Line, Pos: Integer;
ASrc, ADescription: String);
procedure SetLanguage(lang:string);
procedure SetSafeSubSet(b:boolean);
public
engine: TObject;
constructor Create(AOwner: TObject);
destructor Destroy; override;
function RunScript(s: string): boolean;
function RunExpression(s: string): string;
function RunExpressionDirect(s: string): string;
procedure AddNamedItem(AName : string; AIntf : IUnknown);
procedure AddGlobalMember(AName:string);
// properties
property Errors: TStringList read fErrors;
property Script: string read fScript;
property ScriptHeader: TStringList read fScriptHeader;
property ScriptLanguage: string read fScriptLanguage write SetLanguage;
property ScriptSuccess: boolean read fScriptSuccess;
property OnScriptError: TScarlettActiveScriptError read fOnScriptError
write fOnScriptError;
property UseOldEngine: boolean read fUseOldParser write fUseOldParser;
property UseSafeSubset: boolean read fUseSafeSubSet write SetSafeSubSet;
end;
var
FActiveScript: TScarlettActiveScript;
const
crlf = #13 + #10;
implementation
const
cDefaultLanguage = 'JScript';
procedure TScarlettActiveScript.SetLanguage(lang:string);
begin
fscriptlanguage := lang;
asw.ScriptLanguage := lang;
aswold.ScriptLanguage := lang;
end;
procedure TScarlettActiveScript.SetSafeSubSet(b:boolean);
begin
fUseSafeSubSet := b;
asw.usesafesubset := b;
aswold.usesafesubset := b;
end;
procedure TScarlettActiveScript.AddGlobalMember(AName:string);
begin
if fUseOldParser = false then
asw.AddGlobalMember(Aname) else
aswold.AddGlobalMember(AName);
end;
procedure TScarlettActiveScript.AddNamedItem(AName : string; AIntf : IUnknown);
begin
if fUseOldParser = false then
asw.AddNamedItem(Aname, AIntf) else
aswold.AddNamedItem(AName, AIntf);
end;
function TScarlettActiveScript.RunExpression(s: string): string;
begin
fScriptSuccess := true;
errors.clear;
if fUseOldParser = false then
result := asw.RunExpression(s) else
result := aswold.RunExpression(s);
end;
function TScarlettActiveScript.RunExpressionDirect(s: string): string;
begin
if fUseOldParser = false then
result := asw.RunExpression(s) else
result := aswold.RunExpression(s);
end;
function TScarlettActiveScript.RunScript(s: string): boolean;
begin
fScriptSuccess := true;
errors.clear;
fscript := scriptheader.text + s;
if fUseOldParser = false then
asw.execute(script) else
aswold.Execute(script);
result := ScriptSuccess;
end;
procedure TScarlettActiveScript.aswError(Sender: TObject; Line, Pos: Integer;
ASrc, ADescription: String);
begin
fScriptSuccess := false;
errors.add(inttostr(Line) + ': ' + ADescription + ' [' + ASrc + ']');
if Assigned(fOnScriptError) then
fOnScriptError(Line, Pos, ASrc, ADescription);
end;
constructor TScarlettActiveScript.Create(AOwner: TObject);
begin
inherited Create;
fActiveScript := Self; // important
if AOwner <> nil then
engine := AOwner;
fUseSafeSubSet := true; // more SECURITY
fUseOldParser := false;
ferrors := TStringList.Create;
fscriptheader := TStringList.Create;
asw := TSyActiveScriptWindow.Create(nil);
asw.OnError := aswError;
aswold := TXSyActiveScriptWindow.Create(nil);
aswold.OnError := aswError;
SetLanguage(cDefaultLanguage);
SetSafeSubSet(fUseSafeSubSet);
end;
destructor TScarlettActiveScript.Destroy;
begin
ferrors.Free;
scriptheader.free;
aswold.Free;
asw.free;
inherited;
end;
end.
|
(*
Category: SWAG Title: MATH ROUTINES
Original name: 0002.PAS
Description: CIRCLE3P.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:50
*)
Program ThreePoints_TwoPoints;
{
I Really appreciate ya helping me With this 3 points on a
circle problem. The only thing is that I still can't get it
to work. I've tried the Program you gave me and it spits out
the wrong answers. I don't know if there are parentheses in the
wrong place or what. Maybe you can find the error.
You'll see that I've inserted True coordinates For this test.
Thank you once again...and please, when you get any more information
on this problem...call me collect person to person or leave it on my
BBS. I get the turbo pascal echo from a California BBS and that sure
is long distance. Getting a good pascal Procedure For this is
important to me because I am using it in a soon to be released math
Program called Mr. Machinist! I've been racking my brain about this
for 2 weeks now and I've even been dream'in about it!
Your help is appreciated!!!
+
+AL+
(716) 434-7823 Voice
(716) 434-1448 BBS ... if none of these, then leave Program on TP echo.
}
Uses
Crt;
Const
x1 = 4.0642982;
y1 = 0.9080732;
x2 = 1.6679862;
y2 = 2.8485684;
x3 = 4.0996421;
y3 = 0.4589868;
Var
Selection : Integer;
Procedure ThreePoints;
Var
Slope1,
Slope2,
Mid1x,
Mid1y,
Mid2x,
Mid2y,
Cx,
Cy,
Radius : Real;
begin
ClrScr;
Writeln('3 points on a circle');
Writeln('====================');
Writeln;
Writeln('X1 -> 4.0642982');
Writeln('Y1 -> 0.9080732');
Writeln;
Writeln('X2 -> 1.6679862');
Writeln('Y2 -> 2.8485684');
Writeln;
Writeln('X3 -> 4.0996421');
Writeln('Y3 -> 0.4589868');
Writeln;
Slope1 := (y2 - y1) / (x2 - x1);
Slope2 := (y3 - y2) / (x3 - x2);
Mid1x := (x1 + x2) / 2;
Mid1y := (y1 + y2) / 2;
Mid2x := (x2 + x3) / 2;
Mid2y := (y2 + y3) / 2;
Slope1 := -1 * (1 / Slope1);
Slope2 := -1 * (1 / Slope2);
Cx := (Slope2 * x2 - y2 - Slope1 * x1 + y1) / (Slope1 - Slope2);
Cy := Slope1 * (Cx + x1) - y1;
{
I believe you missed out on using Cx and Cy in next line,
Radius := sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)));
I think it should be . . .
}
Radius := Sqrt(Sqr((x1 - Cx) + (y1 - Cy)));
Writeln;
Writeln('X center line (Program answer) is ', Cx : 4 : 4);
Writeln('Y center line (Program answer) is ', Cy : 4 : 4);
Writeln('The radius (Program answer) is ', Radius : 4 : 4);
Writeln;
Writeln('True X center = 1.7500');
Writeln('True Y center = 0.5000');
Writeln('True Radius = 2.3500');
Writeln('Strike any key to continue . . .');
ReadKey;
end;
Procedure Distance2Points;
Var
x1, y1,
x2, y2,
Distance : Real;
begin
ClrScr;
Writeln('Distance between 2 points');
Writeln('=========================');
Writeln;
Write('X1 -> ');
Readln(x1);
Write('Y1 -> ');
Readln(y1);
Writeln;
Write('X2 -> ');
Readln(x2);
Write('Y2 -> ');
Readln(y2);
Writeln;
Writeln;
Distance := Sqrt((Sqr(x2 - x1)) + (Sqr(y2 - y1)));
Writeln('Distance between point 1 and point 2 = ', Distance : 4 : 4);
Writeln;
Writeln('Strike any key to continue . . .');
ReadKey;
end;
begin
ClrScr;
Writeln;
Writeln;
Writeln('1) Distance between 2 points');
Writeln('2) 3 points on a circle test Program');
Writeln('0) Quit');
Writeln;
Write('Choose a menu number: ');
Readln(Selection);
Case Selection of
1 : Distance2Points;
2 : ThreePoints;
end;
ClrScr;
end.
|
Unit HookProgressForm;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
Interface
Uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, ExtCtrls,
StdCtrls, ComCtrls,
Generics.Collections, HookObjects;
Type
THookProgressFrm = Class;
THookProgressThread = Class (TThread)
Private
FForm : THookProgressFrm;
FOpList : TTaskOperationList;
FCurrentObject : TTaskObject;
FCurrentOpType : EHookObjectOperation;
FCurrentOp : WideString;
FStatus : Cardinal;
Procedure UpdateGUI;
Protected
Procedure Execute; Override;
Public
Constructor Create(ACreateSuspended:Boolean; AForm:THookProgressFrm; AOpList:TTaskOperationList); Reintroduce;
end;
THookProgressFrm = Class (TForm)
LowerPanel: TPanel;
CloseButton: TButton;
ProgressListView: TListView;
procedure CloseButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure ProgressListViewAdvancedCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage;
var DefaultDraw: Boolean);
Private
FThread : THookProgressThread;
FOperationCount : Cardinal;
FSuccessCount : Cardinal;
FErrorCount : Cardinal;
FWarningCount : Cardinal;
Procedure OnThreadTerminated(Sender:TObject);
Public
Constructor Create(AOwner:TComponent; AOpList:TTaskOperationList); Reintroduce;
end;
Implementation
Procedure THookProgressThread.UpdateGUI;
Var
r : EHookObjectOperationResult;
addrStr : WideString;
lw : TListView;
begin
r := FCurrentObject.OperationResult(FCurrentOpType, FStatus);
Inc(FForm.FOperationCount);
Case r Of
hoorSuccess: Inc(FForm.FSuccessCount);
hoorWarning: Inc(FForm.FWarningCount);
hoorError: Inc(FForm.FErrorCount);
end;
lw := FForm.ProgressListView;
With lw.Items.Add Do
begin
Data := Pointer(r);
Caption := FCurrentOp;
SubItems.Add(FCurrentObject.ObjectTpye);
addrStr := '';
If FCurrentObject Is THookObject Then
addrStr := Format(' (0x%p)', [(FCurrentObject As THookObject).Address]);
SubItems.Add(Format('%s%s', [FCurrentObject.Name, addrStr]));
SubItems.Add(Format('%u', [FStatus]));
SubItems.Add(FCurrentObject.StatusDescription(FCurrentOpType, FStatus))
end;
end;
Procedure THookProgressThread.Execute;
Var
I : Cardinal;
p : TPair<EHookObjectOperation, TTaskObject>;
begin
FreeOnTerminate := False;
I := 0;
While I < FOpList.Count Do
begin
p := FOpList.Items[I];
FCurrentObject := p.Value;
FCurrentOp := FCurrentObject.OperationString(p.Key);
FCurrentOpType := p.Key;
FStatus := FCurrentObject.Operation(p.Key);
Synchronize(UpdateGUI);
Inc(I);
end;
FOpList.Clear;
FForm.CloseButton.Enabled := True;
end;
Constructor THookProgressThread.Create(ACreateSuspended:Boolean; AForm:THookProgressFrm; AOpList:TTaskOperationList);
begin
FForm := AForm;
FOpList := AOpList;
Inherited Create(ACreateSuspended);
end;
{$R *.DFM}
Constructor THookProgressFrm.Create(AOwner:TComponent; AOpList:TTaskOperationList);
begin
FThread := THookProgressThread.Create(True, Self, AOpList);
Inherited Create(AOwner);
end;
Procedure THookProgressFrm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FThread.WaitFor;
FThread.Free;
end;
Procedure THookProgressFrm.OnThreadTerminated(Sender:TObject);
begin
If (FErrorCount = 0) Then
Close;
end;
Procedure THookProgressFrm.FormCreate(Sender: TObject);
begin
FOperationCount := 0;
FSuccessCount := 0;
FErrorCount := 0;
FWarningCount := 0;
FThread.OnTerminate := OnThreadTerminated;
FThread.Start;
end;
Procedure THookProgressFrm.ProgressListViewAdvancedCustomDrawItem(
Sender: TCustomListView; Item: TListItem; State: TCustomDrawState;
Stage: TCustomDrawStage; var DefaultDraw: Boolean);
Var
lw : TListView;
r : EHookObjectOperationResult;
begin
lw := (Sender As TListView);
r := EHookObjectOperationResult(Item.Data);
Case r Of
hoorSuccess: lw.Canvas.Font.Color := clGreen;
hoorWarning: lw.Canvas.Font.Color := clBlue;
hoorError: lw.Canvas.Font.Color := clRed;
end;
end;
Procedure THookProgressFrm.CloseButtonClick(Sender: TObject);
begin
Close;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [COLABORADOR]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit ColaboradorVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
TipoAdmissaoVO, SituacaoColaboradorVO, PessoaVO, TipoColaboradorVO,
NivelFormacaoVO, CargoVO, SetorVO;
type
TColaboradorVO = class(TVO)
private
FID: Integer;
FID_SINDICATO: Integer;
FID_TIPO_ADMISSAO: Integer;
FID_SITUACAO_COLABORADOR: Integer;
FID_PESSOA: Integer;
FID_TIPO_COLABORADOR: Integer;
FID_NIVEL_FORMACAO: Integer;
FID_CARGO: Integer;
FID_SETOR: Integer;
FMATRICULA: String;
FFOTO_34: String;
FDATA_CADASTRO: TDateTime;
FDATA_ADMISSAO: TDateTime;
FVENCIMENTO_FERIAS: TDateTime;
FDATA_TRANSFERENCIA: TDateTime;
FFGTS_OPTANTE: String;
FFGTS_DATA_OPCAO: TDateTime;
FFGTS_CONTA: Integer;
FPAGAMENTO_FORMA: String;
FPAGAMENTO_BANCO: String;
FPAGAMENTO_AGENCIA: String;
FPAGAMENTO_AGENCIA_DIGITO: String;
FPAGAMENTO_CONTA: String;
FPAGAMENTO_CONTA_DIGITO: String;
FEXAME_MEDICO_ULTIMO: TDateTime;
FEXAME_MEDICO_VENCIMENTO: TDateTime;
FPIS_DATA_CADASTRO: TDateTime;
FPIS_NUMERO: String;
FPIS_BANCO: String;
FPIS_AGENCIA: String;
FPIS_AGENCIA_DIGITO: String;
FCTPS_NUMERO: String;
FCTPS_SERIE: String;
FCTPS_DATA_EXPEDICAO: TDateTime;
FCTPS_UF: String;
FDESCONTO_PLANO_SAUDE: String;
FSAI_NA_RAIS: String;
FCATEGORIA_SEFIP: String;
FOBSERVACAO: String;
FOCORRENCIA_SEFIP: Integer;
FCODIGO_ADMISSAO_CAGED: Integer;
FCODIGO_DEMISSAO_CAGED: Integer;
FCODIGO_DEMISSAO_SEFIP: Integer;
FDATA_DEMISSAO: TDateTime;
FCODIGO_TURMA_PONTO: String;
FCAGED_APRENDIZ: String;
FCAGED_DEFICIENCIA: String;
FCLASSIFICACAO_CONTABIL_CONTA: String;
FTipoAdmissaoVO: TTipoAdmissaoVO;
FSituacaoColaboradorVO: TSituacaoColaboradorVO;
FPessoaVO: TPessoaVO;
FTipoColaboradorVO: TTipoColaboradorVO;
FNivelFormacaoVO: TNivelFormacaoVO;
FCargoVO: TCargoVO;
FSetorVO: TSetorVO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdSindicato: Integer read FID_SINDICATO write FID_SINDICATO;
// Pessoa
property IdPessoa: Integer read FID_PESSOA write FID_PESSOA;
// Tipo Admissão
property IdTipoAdmissao: Integer read FID_TIPO_ADMISSAO write FID_TIPO_ADMISSAO;
// Situação Colaborador
property IdSituacaoColaborador: Integer read FID_SITUACAO_COLABORADOR write FID_SITUACAO_COLABORADOR;
// Tipo de Colaborador
property IdTipoColaborador: Integer read FID_TIPO_COLABORADOR write FID_TIPO_COLABORADOR;
// Nível de Formação
property IdNivelFormacao: Integer read FID_NIVEL_FORMACAO write FID_NIVEL_FORMACAO;
// Cargo
property IdCargo: Integer read FID_CARGO write FID_CARGO;
// Setor
property IdSetor: Integer read FID_SETOR write FID_SETOR;
property Matricula: String read FMATRICULA write FMATRICULA;
property Foto34: String read FFOTO_34 write FFOTO_34;
property DataCadastro: TDateTime read FDATA_CADASTRO write FDATA_CADASTRO;
property DataAdmissao: TDateTime read FDATA_ADMISSAO write FDATA_ADMISSAO;
property VencimentoFerias: TDateTime read FVENCIMENTO_FERIAS write FVENCIMENTO_FERIAS;
property DataTransferencia: TDateTime read FDATA_TRANSFERENCIA write FDATA_TRANSFERENCIA;
property FgtsOptante: String read FFGTS_OPTANTE write FFGTS_OPTANTE;
property FgtsDataOpcao: TDateTime read FFGTS_DATA_OPCAO write FFGTS_DATA_OPCAO;
property FgtsConta: Integer read FFGTS_CONTA write FFGTS_CONTA;
property PagamentoForma: String read FPAGAMENTO_FORMA write FPAGAMENTO_FORMA;
property PagamentoBanco: String read FPAGAMENTO_BANCO write FPAGAMENTO_BANCO;
property PagamentoAgencia: String read FPAGAMENTO_AGENCIA write FPAGAMENTO_AGENCIA;
property PagamentoAgenciaDigito: String read FPAGAMENTO_AGENCIA_DIGITO write FPAGAMENTO_AGENCIA_DIGITO;
property PagamentoConta: String read FPAGAMENTO_CONTA write FPAGAMENTO_CONTA;
property PagamentoContaDigito: String read FPAGAMENTO_CONTA_DIGITO write FPAGAMENTO_CONTA_DIGITO;
property ExameMedicoUltimo: TDateTime read FEXAME_MEDICO_ULTIMO write FEXAME_MEDICO_ULTIMO;
property ExameMedicoVencimento: TDateTime read FEXAME_MEDICO_VENCIMENTO write FEXAME_MEDICO_VENCIMENTO;
property PisDataCadastro: TDateTime read FPIS_DATA_CADASTRO write FPIS_DATA_CADASTRO;
property PisNumero: String read FPIS_NUMERO write FPIS_NUMERO;
property PisBanco: String read FPIS_BANCO write FPIS_BANCO;
property PisAgencia: String read FPIS_AGENCIA write FPIS_AGENCIA;
property PisAgenciaDigito: String read FPIS_AGENCIA_DIGITO write FPIS_AGENCIA_DIGITO;
property CtpsNumero: String read FCTPS_NUMERO write FCTPS_NUMERO;
property CtpsSerie: String read FCTPS_SERIE write FCTPS_SERIE;
property CtpsDataExpedicao: TDateTime read FCTPS_DATA_EXPEDICAO write FCTPS_DATA_EXPEDICAO;
property CtpsUf: String read FCTPS_UF write FCTPS_UF;
property DescontoPlanoSaude: String read FDESCONTO_PLANO_SAUDE write FDESCONTO_PLANO_SAUDE;
property SaiNaRais: String read FSAI_NA_RAIS write FSAI_NA_RAIS;
property CategoriaSefip: String read FCATEGORIA_SEFIP write FCATEGORIA_SEFIP;
property Observacao: String read FOBSERVACAO write FOBSERVACAO;
property OcorrenciaSefip: Integer read FOCORRENCIA_SEFIP write FOCORRENCIA_SEFIP;
property CodigoAdmissaoCaged: Integer read FCODIGO_ADMISSAO_CAGED write FCODIGO_ADMISSAO_CAGED;
property CodigoDemissaoCaged: Integer read FCODIGO_DEMISSAO_CAGED write FCODIGO_DEMISSAO_CAGED;
property CodigoDemissaoSefip: Integer read FCODIGO_DEMISSAO_SEFIP write FCODIGO_DEMISSAO_SEFIP;
property DataDemissao: TDateTime read FDATA_DEMISSAO write FDATA_DEMISSAO;
property CodigoTurmaPonto: String read FCODIGO_TURMA_PONTO write FCODIGO_TURMA_PONTO;
property CagedAprendiz: String read FCAGED_APRENDIZ write FCAGED_APRENDIZ;
property CagedDeficiencia: String read FCAGED_DEFICIENCIA write FCAGED_DEFICIENCIA;
property ClassificacaoContabilConta: String read FCLASSIFICACAO_CONTABIL_CONTA write FCLASSIFICACAO_CONTABIL_CONTA;
property TipoAdmissaoVO: TTipoAdmissaoVO read FTipoAdmissaoVO write FTipoAdmissaoVO;
property SituacaoColaboradorVO: TSituacaoColaboradorVO read FSituacaoColaboradorVO write FSituacaoColaboradorVO;
property PessoaVO: TPessoaVO read FPessoaVO write FPessoaVO;
property TipoColaboradorVO: TTipoColaboradorVO read FTipoColaboradorVO write FTipoColaboradorVO;
property NivelFormacaoVO: TNivelFormacaoVO read FNivelFormacaoVO write FNivelFormacaoVO;
property CargoVO: TCargoVO read FCargoVO write FCargoVO;
property SetorVO: TSetorVO read FSetorVO write FSetorVO;
end;
TListaColaboradorVO = specialize TFPGObjectList<TColaboradorVO>;
implementation
constructor TColaboradorVO.Create;
begin
inherited;
FTipoAdmissaoVO := TTipoAdmissaoVO.Create;
FSituacaoColaboradorVO := TSituacaoColaboradorVO.Create;
FPessoaVO := TPessoaVO.Create;
FTipoColaboradorVO := TTipoColaboradorVO.Create;
FNivelFormacaoVO := TNivelFormacaoVO.Create;
FCargoVO := TCargoVO.Create;
FSetorVO := TSetorVO.Create;
end;
destructor TColaboradorVO.Destroy;
begin
FreeAndNil(FTipoAdmissaoVO);
FreeAndNil(FSituacaoColaboradorVO);
FreeAndNil(FPessoaVO);
FreeAndNil(FTipoColaboradorVO);
FreeAndNil(FNivelFormacaoVO);
FreeAndNil(FCargoVO);
FreeAndNil(FSetorVO);
inherited;
end;
initialization
Classes.RegisterClass(TColaboradorVO);
finalization
Classes.UnRegisterClass(TColaboradorVO);
end.
|
(*
Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES
Original name: 0022.PAS
Description: SWAPNUMS.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:53
*)
{
>Is there a way (using bit manipulations such as AND, OR, XOR) to
>swap to Variables without making a 3rd temporary Variable?
>
If the two Variables are numbers, and the following operations
won't overflow the limitations of the Type, then yes, you can
do it like this:
}
Var
A, B : Integer;
begin
A := 5;
B := 3;
WriteLn('A = ',a,', B = ',b);
A := A + B;
B := A - B;
A := A - B;
{ which is
A := 5 + 3 (8)
B := 8 - 3 (5)
A := 8 - 5 (3)
A = 3
B = 5 }
WriteLn('A = ',a,', B = ',b);
end.
|
{-----------------------------------------------------------------------------
Miguel A. Risco Castillo TuEKnob v0.65
http://ue.accesus.com/uecontrols
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
-----------------------------------------------------------------------------}
unit uEKnob;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls,
LCLIntf, LCLType, LCLProc, Types,
BGRABitmap, BGRABitmapTypes, uERotImage;
type
TuEAngle = 0..3600; // 0.0 - 360.0 deg
{ TCustomuEKnob }
TCustomuEKnob = class(TCustomuERotImage)
protected
FMax: Real;
FMaxAngle: TuEAngle;
FMin: Real;
FMinAngle: TuEAngle;
FLTicks: integer;
FLTicksColor: TColor;
FLTicksSize: integer;
FSTicks: integer;
FSTicksColor: TColor;
FSTicksSize: integer;
FTicksMargin: integer;
FShowValues: Boolean;
FValuesFont: TFont;
FValuesMargin: integer;
FOnChange: TNotifyEvent;
FPosition: Real;
FTransparent:Boolean;
procedure SetLTicksColor(const AValue: TColor); virtual;
procedure SetMax(const AValue: Real); virtual;
procedure SetMaxAngle(const AValue: TuEAngle); virtual;
procedure SetMin(const AValue: Real); virtual;
procedure SetMinAngle(const AValue: TuEAngle); virtual;
procedure SetPosition(const AValue: Real); virtual;
procedure SetLargeTicks(const AValue: integer); virtual;
procedure SetLTicksSize(const AValue: integer); virtual;
procedure SetSTicks(const AValue: integer); virtual;
procedure SetSTicksColor(const AValue: TColor); virtual;
procedure SetSTicksSize(const AValue: integer); virtual;
procedure SetTicksMargin(const AValue: integer); virtual;
procedure SetShowValues(const AValue: Boolean); virtual;
procedure SetTransparent(const AValue: Boolean); virtual;
procedure SetValueMargin(const AValue: integer); virtual;
procedure SetValuesFont(const AValue: TFont); virtual;
class procedure WSRegisterClass; override;
procedure CalculatePreferredSize(var PreferredWidth,
PreferredHeight: integer;
WithThemeSpace: Boolean); override;
class function GetControlClassDefaultSize: TSize; override;
procedure Paint; override;
procedure Loaded; override;
procedure FontChanged(Sender: TObject); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure DefaultPicture; virtual;
procedure ForcePosition(const AValue: Real); virtual;
procedure DrawScales(LBitmap:TBGRABitmap); virtual;
procedure UpdateScales; virtual;
procedure DoOnChange; virtual;
procedure Resize; override;
function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override;
function GetCenter: TPoint;
function PointToAngle(APoint, ACenter: TPoint): TuEAngle;
function AngleToPos(AnAngle: TuEAngle): Real;
function PosToAngle(Pos: Real): TuEAngle;
property Position: Real read FPosition write SetPosition;
property Max: Real read FMax write SetMax;
property MaxAngle: TuEAngle read FMaxAngle write SetMaxAngle;
property Min: Real read FMin write SetMin;
property MinAngle: TuEAngle read FMinAngle write SetMinAngle;
property TicksMargin:integer read FTicksMargin write SetTicksMargin;
property LTicks:integer read FLTicks write SetLargeTicks;
property LTicksSize:integer read FLTicksSize write SetLTicksSize;
property LTicksColor:TColor read FLTicksColor write SetLTicksColor;
property STicks:integer read FSTicks write SetSTicks;
property STicksSize:integer read FSTicksSize write SetSTicksSize;
property STicksColor:TColor read FSTicksColor write SetSTicksColor;
property ShowValues:Boolean read FShowValues write SetShowValues;
property ValuesMargin:integer read FValuesMargin write SetValueMargin;
property ValuesFont:TFont read FValuesFont write SetValuesFont;
property Transparent:Boolean read FTransparent write SetTransparent;
property OnPaint;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
public
Background:TBGRABitmap;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{ TuEKnob }
TuEKnob = class(TCustomuEKnob)
published
procedure DrawScales(LBitmap:TBGRABitmap); override;
property Max;
property MaxAngle;
property Min;
property MinAngle;
property Picture;
property Position;
property TicksMargin;
property LTicks;
property LTicksSize;
property LTicksColor;
property STicks;
property STicksSize;
property STicksColor;
property ShowValues;
property ValuesMargin;
property ValuesFont;
property Transparent;
property OnChange;
property OnPaint;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
//
property Align;
property Anchors;
property BorderSpacing;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property ParentColor;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnChangeBounds;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnClick;
property OnConstrainedResize;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnResize;
property OnStartDock;
property OnStartDrag;
end;
procedure Register;
implementation
{ TCustomuEKnob }
procedure TCustomuEKnob.SetMax(const AValue: Real);
begin
if (FMax=AValue) and (AValue<=FMin) then exit;
FMax:=AValue;
UpdateScales;
ForcePosition(FPosition);
end;
procedure TCustomuEKnob.SetMaxAngle(const AValue: TuEAngle);
begin
if FMaxAngle=AValue then exit;
FMaxAngle:=AValue;
UpdateScales;
ForcePosition(FPosition);
end;
procedure TCustomuEKnob.SetMin(const AValue: Real);
begin
if (FMin=AValue) and (AValue>=FMax) then exit;
FMin:=AValue;
UpdateScales;
ForcePosition(FPosition);
end;
procedure TCustomuEKnob.SetMinAngle(const AValue: TuEAngle);
begin
if FMinAngle=AValue then exit;
FMinAngle:=AValue;
UpdateScales;
ForcePosition(FPosition);
end;
procedure TCustomuEKnob.SetPosition(const AValue: Real);
begin
if FPosition=AValue then exit;
ForcePosition(AValue);
end;
procedure TCustomuEKnob.ForcePosition(const AValue: Real);
begin
if AValue<FMin then FPosition:=FMin
else if AValue>FMax then FPosition:=FMax
else FPosition:=AValue;
inherited Angle:=PostoAngle(FPosition)/10;
invalidate;
DoOnChange;
end;
procedure TCustomuEKnob.SetShowValues(const AValue: Boolean);
begin
if FShowValues=AValue then exit;
FShowValues:=AValue;
UpdateScales;
invalidate;
end;
procedure TCustomuEKnob.SetTransparent(const AValue: Boolean);
begin
if FTransparent=AValue then exit;
FTransparent:=AValue;
UpdateScales;
invalidate;
end;
procedure TCustomuEKnob.SetSTicks(const AValue: integer);
begin
if FSTicks=AValue then exit;
FSTicks:=AValue;
UpdateScales;
invalidate;
end;
procedure TCustomuEKnob.SetSTicksColor(const AValue: TColor);
begin
if FSTicksColor=AValue then exit;
FSTicksColor:=AValue;
UpdateScales;
invalidate;
end;
procedure TCustomuEKnob.SetSTicksSize(const AValue: integer);
begin
if FSTicksSize=AValue then exit;
FSTicksSize:=AValue;
UpdateScales;
invalidate;
end;
procedure TCustomuEKnob.SetTicksMargin(const AValue: integer);
begin
if FTicksMargin=AValue then exit;
FTicksMargin:=AValue;
UpdateScales;
invalidate;
end;
procedure TCustomuEKnob.SetValueMargin(const AValue: integer);
begin
if FValuesMargin=AValue then exit;
FValuesMargin:=AValue;
UpdateScales;
invalidate;
end;
procedure TCustomuEKnob.SetValuesFont(const AValue: TFont);
begin
if FValuesFont.IsEqual(AValue) then exit;
FValuesFont.Assign(AValue);
end;
class procedure TCustomuEKnob.WSRegisterClass;
begin
inherited WSRegisterClass;
end;
procedure TCustomuEKnob.CalculatePreferredSize(var PreferredWidth,
PreferredHeight: integer; WithThemeSpace: Boolean);
begin
inherited CalculatePreferredSize(PreferredWidth, PreferredHeight,
WithThemeSpace);
end;
class function TCustomuEKnob.GetControlClassDefaultSize: TSize;
begin
Result.CX := 90;
Result.CY := 90;
end;
procedure TCustomuEKnob.Paint;
begin
Background.Draw(inherited Canvas,0,0,false);
inherited Paint;
end;
procedure TCustomuEKnob.DefaultPicture;
const ks=34;
var
TempBitmap: TBitmap;
c:real;
begin
c:=(ks-1)/2;
TempBitmap := TBitmap.Create;
Bitmap.SetSize(ks,ks);
Bitmap.Fill(BGRAPixelTransparent);
Bitmap.FillEllipseAntialias(c,c,c,c,BGRABlack);
Bitmap.GradientFill(0,0,ks,ks,
BGRA(128,128,128,255),BGRA(0,0,0,0),
gtRadial,PointF(c,c),PointF(0,c),
dmDrawWithTransparency);
Bitmap.DrawLineAntialias(c,c+5,c,ks-5,BGRAWhite,2);
try
TempBitmap.PixelFormat:=pf32bit;
TempBitmap.SetSize(ks,ks);
With TempBitmap
do begin
Transparent:=true;
TransparentColor:=clLime;
Canvas.Brush.Color:=clLime;
Canvas.FillRect(Canvas.ClipRect);
end;
Bitmap.Draw(TempBitmap.Canvas,0,0,true);
Picture.Assign(TempBitmap);
Picture.Graphic.Transparent:=true;
finally
TempBitmap.Free;
end;
end;
procedure TCustomuEKnob.Loaded;
begin
inherited Loaded;
ForcePosition(FPosition);
end;
procedure TCustomuEKnob.FontChanged(Sender: TObject);
begin
inherited FontChanged(Sender);
UpdateScales;
invalidate;
end;
function TCustomuEKnob.AngleToPos(AnAngle: TuEAngle): Real;
// Convert angle AnAngle to a position.
begin
Result := FMin + ((FMax - FMin) * (AnAngle - FMinAngle)/(FMaxAngle - FMinAngle));
end;
function TCustomuEKnob.PosToAngle(Pos: Real): TuEAngle;
// Convert position Pos to an angle.
begin
Result := FMinAngle + Round((FMaxAngle - FMinAngle) * (Pos - FMin) / (FMax - FMin));
end;
procedure TCustomuEKnob.Resize;
begin
if ([csLoading,csDestroying]*ComponentState<>[]) then exit;
if AutoSizeDelayed then exit;
BackGround.SetSize(width,height);
UpdateScales;
inherited Resize;
end;
function TCustomuEKnob.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer;
MousePos: TPoint): Boolean;
begin
Result:=inherited DoMouseWheel(Shift, WheelDelta, MousePos);
SetPosition(FPosition+WheelDelta/200);
end;
constructor TCustomuEKnob.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if not Assigned(Picture.Graphic) then DefaultPicture;
UniqueSize:=true;
Center:=true;
FPosition:=0;
FMax:=100;
FMin:=0;
FMaxAngle:=3300;
FMinAngle:=300;
FTicksMargin:=20;
FLTicks:=10;
FLTicksSize:=8;
FLTicksColor:=clBlack;
FSTicks:=3;
FSTicksSize:=5;
FSTicksColor:=clBlack;
FShowValues:=true;
FValuesMargin:=8;
FValuesFont:=TFont.Create;
FValuesFont.Name:='Sans';
FValuesFont.Orientation:=0;
FValuesFont.Style:=[];
FValuesFont.Color:=clBlack;
FValuesFont.Size:=8;
FValuesFont.OnChange:=@FontChanged;
FTransparent:=true;
ControlStyle := ControlStyle + [csReplicatable, csCaptureMouse, csClickEvents, csDoubleClicks];
with GetControlClassDefaultSize do
begin
SetInitialBounds(0, 0, CX, CY);
BackGround:=TBGRABitmap.Create(CX,CY);
end;
end;
destructor TCustomuEKnob.Destroy;
begin
FreeThenNil(Background);
FValuesFont.OnChange:=nil;
FValuesFont.free;
inherited Destroy;
end;
// Convert a APoint to an angle (relative to ACenter),
// where bottom is 0, left is 900, top is 1800 and so on.
function TCustomuEKnob.PointToAngle(APoint, ACenter: TPoint): TuEAngle;
var
N: Integer;
begin
N := APoint.X - ACenter.X;
if N = 0 then
if APoint.Y < ACenter.Y then Result := 900 else Result := 2700
else
begin
Result:=Round(ArcTan((ACenter.Y - APoint.Y) / N) * 1800 / PI);
end;
if N < 0 then Result := Result + 1800;
Result := 2700 - Result;
end;
procedure TCustomuEKnob.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
inherited MouseDown(Button, Shift, X, Y);
MouseCapture := True;
SetPosition(AngletoPos(PointToAngle(Point(X, Y), GetCenter)));
end;
procedure TCustomuEKnob.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited MouseMove(Shift, X, Y);
if MouseCapture then
SetPosition(AngletoPos(PointToAngle(Point(X, Y), GetCenter)));
end;
procedure TCustomuEKnob.MouseUp(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
inherited MouseUp(Button, Shift, X, Y);
MouseCapture := False;
end;
procedure TCustomuEKnob.DoOnChange;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
function TCustomuEKnob.GetCenter: TPoint;
begin
with Result do
begin
X := Width div 2;
Y := Height div 2;
end;
end;
procedure TCustomuEKnob.SetLTicksColor(const AValue: TColor);
begin
if FLTicksColor=AValue then exit;
FLTicksColor:=AValue;
UpdateScales;
invalidate;
end;
procedure TCustomuEKnob.SetLargeTicks(const AValue: integer);
begin
if FLTicks=AValue then exit;
FLTicks:=AValue;
UpdateScales;
invalidate;
end;
procedure TCustomuEKnob.SetLTicksSize(const AValue: integer);
begin
if FLTicksSize=AValue then exit;
FLTicksSize:=AValue;
UpdateScales;
invalidate;
end;
procedure TCustomuEKnob.DrawScales(LBitmap:TBGRABitmap);
var i,j:integer;
x1,y1,x2,y2,lpos:real;
xc,yc,langle:real;
sn,cn:real;
lc,sc,vc:TBGRAPixel;
ts:TSize;
la:string;
begin
xc:=LBitmap.Width/2-1;
yc:=LBitmap.Height/2-1;
lc:=ColorToBGRA(ColorToRGB(FLTicksColor));
sc:=ColorToBGRA(ColorToRGB(FSTicksColor));
vc:=ColorToBGRA(ColorToRGB(FValuesFont.Color));
LBitmap.FontHeight:=abs(FValuesFont.Height);
LBitmap.FontStyle:=FValuesFont.Style;
LBitmap.FontName:=FValuesFont.Name;
LBitmap.FontOrientation:=FValuesFont.Orientation;
if FLTicks>0 then For i:=0 to FLTicks do
begin
lpos:=(i/FLTicks)*(FMax-FMin)+FMin;
langle:=PosToAngle(lpos)*PI/1800 +PI/2;
sn:=sin(langle);
cn:=cos(langle);
x1:=xc+FTicksMargin*cn;
y1:=yc+FTicksMargin*sn;
x2:=xc+(FTicksMargin+FLTicksSize)*cn;
y2:=yc+(FTicksMargin+FLTicksSize)*sn;
LBitmap.DrawLineAntialias(x1,y1,x2,y2,lc, 1);
if FShowValues then
begin
x2:=xc+(FTicksMargin+FLTicksSize+FValuesMargin)*cn;
y2:=yc+(FTicksMargin+FLTicksSize+FValuesMargin)*sn;
la:=floattostrF(lpos,ffGeneral,4,2);
ts:=LBitmap.TextSize(la);
LBitmap.TextOut(trunc(x2+1), trunc(y2-ts.cy/2+1), la, vc, taCenter);
end;
if (lpos<Fmax) then For j:=1 to FSTicks do
begin
lpos:=(i/FLTicks)*(FMax-FMin)+FMin+j*((FMax-FMin)/FLTicks)/(FSTicks+1);
langle:=PosToAngle(lpos)*PI/1800 +PI/2;
sn:=sin(langle);
cn:=cos(langle);
x1:=xc+FTicksMargin*cn;
y1:=yc+FTicksMargin*sn;
x2:=xc+(FTicksMargin+FSTicksSize)*cn;
y2:=yc+(FTicksMargin+FSTicksSize)*sn;
LBitmap.DrawLineAntialias(x1,y1,x2,y2,sc, 1);
end;
end;
end;
procedure TCustomuEKnob.UpdateScales;
begin
if FTransparent then BackGround.Fill(BGRAPixelTransparent) else BackGround.Fill(ColortoBGRA(ColortoRGB(Color)));
DrawScales(BackGround);
end;
{ TuEKnob }
procedure TuEKnob.DrawScales(LBitmap: TBGRABitmap);
begin
inherited DrawScales(LBitmap);
end;
procedure Register;
begin
{$I ueknob_icon.lrs}
RegisterComponents('uEControls', [TuEKnob]);
end;
end.
|
unit SRepAutoLoad;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, ToolEdit, Buttons, ExtCtrls, DB, MemDS, DBAccess,
Ora, uOilQuery, IdBaseComponent, IdComponent, IdTCPConnection, IdFTP, SRepRef,
IdTCPClient, IdExplicitTLSClientServerBase, DBTables, MemTable, uHelpButton,
IdFTPCommon, IdGlobal, ComCtrls, IdIOHandlerStack, IdConnectThroughHttpProxy,
RxLookup, RXClock;
type
TUploadResultType = (urtSuccessful, urtUnSuccessful);
TSRepAutoLoadF = class(TForm)
p1: TPanel;
p2: TPanel;
bbCancel: TBitBtn;
deLoadDir: TDirectoryEdit;
l1: TLabel;
bbLoadDir: TBitBtn;
IdFTP: TIdFTP;
tPeriod: TTimer;
tWork: TTimer;
l5: TLabel;
eFTPName: TEdit;
metFrom: TMaskEdit;
metTo: TMaskEdit;
l3: TLabel;
l4: TLabel;
sbAutoLoad: TSpeedButton;
l6: TLabel;
ePeriods: TEdit;
sbLog: TSpeedButton;
cbFileExpOil: TCheckBox;
cbFileExpDBF: TCheckBox;
qDBF: TQuery;
qColumns: TQuery;
qWork: TOilQuery;
bHelp: TOilHelpButton;
cbFileErrorLoadOnFTP: TCheckBox;
sbSaveSettings: TSpeedButton;
bbLoadFTP: TBitBtn;
qRestNP: TOilQuery;
pbPerfect: TProgressBar;
pbDetailed: TProgressBar;
eProxyHost: TEdit;
l7: TLabel;
eProxyPort: TEdit;
l8: TLabel;
dsSections: TOraDataSource;
qSections: TOilQuery;
rcLoad: TRxClock;
pClock: TPanel;
lClock: TLabel;
l9: TLabel;
pnb: TPanel;
nb: TNotebook;
lSections: TLabel;
sbSections: TSpeedButton;
cbLoadAddSections: TCheckBox;
dblcSections: TRxDBLookupCombo;
cbLoadMyPack: TCheckBox;
cbLoadAddDBF: TCheckBox;
cbLoadRestDBF: TCheckBox;
procedure FormShow(Sender: TObject);
procedure bbLoadDirClick(Sender: TObject);
procedure deLoadDirKeyPress(Sender: TObject; var Key: Char);
procedure sbAutoLoadClick(Sender: TObject);
procedure tPeriodTimer(Sender: TObject);
procedure tWorkTimer(Sender: TObject);
procedure ePeriodsKeyPress(Sender: TObject; var Key: Char);
procedure sbLogClick(Sender: TObject);
procedure metFromExit(Sender: TObject);
procedure cbFileExpOilClick(Sender: TObject);
procedure cbFileExpDBFClick(Sender: TObject);
procedure eFTPNameChange(Sender: TObject);
procedure sbSaveSettingsClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure bbLoadFTPClick(Sender: TObject);
procedure eProxyHostKeyPress(Sender: TObject; var Key: Char);
procedure cbLoadAddSectionsClick(Sender: TObject);
procedure sbSectionsClick(Sender: TObject);
private
iPackets, iRecords: integer;
bAutoLoad: boolean;
qPart, qRez, qRash, qRashMin: TOilQuery;
function ConnectFTP: boolean; // підключаємося до FTP (ftp://login:pass@host)
// шукає вільну назву файлу у директорії і копіює туди файл
function CopyLoadedFile(p_FileName, p_Dir: string; p_Del: boolean;
p_NoFileName: string = ''): string;
procedure PutPacketsWithFTP; // забираємо файли з FTP
procedure BackupFiles(); // робимо резервну копію файлів із АЗС
procedure LoadPackets(bMes: boolean=true); // завантажуємо файли DBF, OIL і ZIP з папки
procedure FileErrorLoadOnFTP(sFileName: string); // Файлы, загруженные с ошибками выкладывать на FTP
procedure GetVisibleClock(b: boolean); // Время следующей загрузки
procedure GetActivePage(); // сторінка OIL/DBF
function IsFileOK(p_FileName: string): boolean; // перевірка по назві файлу
procedure GetRashMin(p_NP: integer); // повсюду будемо брати відпуск на АЗС із найменшим ід
procedure GetRashMinFilter(p_AZS_ID, p_NPG, p_NP: integer); // фільтруємо qRashMin
// ****** BEGIN BDF
procedure AddSRDBF(sFileName: string); // завантажуємо файли DBF
procedure GetAZS(
SL: TStringList; ADep_id: integer;
AAZS, ADepOKPO: string; var AId: integer);
procedure GetNPG(SL: TStringList; AValue: string; var AId: integer);
procedure GetNB(SL: TStringList; ANB: string; var AId: integer);
procedure SetPrihRepDBF(
p_Date: TDateTime;
p_REP_ID, p_DEP_ID, p_NB_ID, p_AZS_ID, p_NPG: integer;
p_LITR, p_PRICE, p_WEIGHT, p_DENSITY: Real); // створюємо прихід НП на АЗС
procedure SetRashRepDBF(
p_AZS_ID, p_REP_ID, p_NPG, p_NP, p_OPER_ID: integer;
p_LITR, p_PRICE, p_WEIGHT, p_DENSITY, p_SUMM: Real); // створюємо реалізацію НП на АЗС
// ****** END BDF
procedure SaveDbLog(AResultType: TUploadResultType; AResultComment, AFileName: string;
ARepId, ARepInst: variant);
public
SRepRef: TSRepRefForm;
class procedure DailyRepAddRash(
p_AZS_ID, p_REP_ID, p_NPG, p_NP, p_OPER_ID: integer;
p_LITR, p_PRICE, p_WEIGHT, p_DENSITY, p_SUMM: Real
);
function SetRestNPDailyRep(
p_AzsID, p_NpgID, p_NpID: integer; // АЗС, Група НП або Тип НП
p_RestLitr, p_RestCount: real; // залишок, який має бути на дату p_Date
p_Date: TDateTime; // дата, на яку треба мати залишок p_RestLitr і p_RestCount
var p_RepID: integer; // ID шапки змінного звіту із корегуючими даними
p_AutoLoad: string='Y'; // тип загрузки
p_Commit: boolean=false // чи зберігати дані у цій процедурі
): boolean; // якщо false, то товар не відпускався на АЗС
procedure SetPrihRep(
p_Date: TDateTime;
p_From {від кого}, p_NB {яка НБ}, p_AZS {якій АЗС}, p_Np,
p_Rep_id, p_Rep_inst, // змінний звіт
p_Rash_id, p_Rash_inst, // відпуск на АЗС
p_Part_id, p_Part_inst, // партія
p_Rez_id, p_Rez_inst, // резервуар
p_Auto_id, p_Auto_inst, // автомобіль
p_Emp_id, p_Emp_inst: integer; // водій
p_TTN_Date: TDateTime; // дата ТТН
p_TTN, p_Car: string; // номер ТТН, номер машини/цистерни
p_Litr, p_Price, p_Weight, p_Density, p_Temper: Real;
p_CH_Prih: boolean=true; // створюємо прихід на НБ
p_CH_Rash: boolean=true; // створюємо відпуск з НБ
p_CH_DR : boolean=true // створюємо прихід на АЗС
); // створюємо прихід НП на АЗС
end;
var
SRepAutoLoadF: TSRepAutoLoadF;
slSRepMes: TStringList; // повідомлення
sSRepDirLog: string;
procedure SRepAutoLoadLog(s: string); // лог
implementation
{$R *.dfm}
uses Main, ExFunc, OilStd, SRep, uCommonForm, UDbFunc, Memo, ChooseOrg,
uXMLForm, PacketClass;
//==============================================================================
procedure SRepAutoLoadLog(s: string); // лог
begin
if DR_AUTOLOAD then
begin
ExFunc.log(
sSRepDirLog +'\SRepAutoLoad_'+ FormatDateTime('yyyy-mm-dd', now()) +'.log',
FormatDateTime('dd.mm.yyyy hh:nn:ss', now()) +' '+ s);
if slSRepMes <> nil then
slSRepMes.Add(s);
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.sbLogClick(Sender: TObject);
var
SL: TStringList;
begin
if FileExists(deLoadDir.Text +'\SRepAutoLoad_'+ FormatDateTime('yyyy-mm-dd', now()) +'.log') then
begin
SL := TStringList.Create;
try
SL.Clear;
SL.LoadFromFile(deLoadDir.Text +'\SRepAutoLoad_'+ FormatDateTime('yyyy-mm-dd', now()) +'.log');
ShowText(SL.Text);
finally
FreeAndNil(SL);
end;
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.FormShow(Sender: TObject);
begin // витягуємо з реєстру збережені дані
// Папка
deLoadDir.Text := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadDir');
if deLoadDir.Text = '' then
deLoadDir.Text := GetMainDir;
deLoadDir.InitialDir := deLoadDir.Text;
sSRepDirLog := deLoadDir.Text;
eFTPName.Text := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadFTP');
eProxyHost.Text := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadProxyHost');
eProxyPort.Text := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadProxyPort');
metFrom.Text := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadTimeFrom');
metTo.Text := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadTimeTo');
ePeriods.Text := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadPeriods');
// автоматична загрузка даних
if SysParamExists('RUN_OIL_AUTOLOAD_SREP') then
begin
cbFileExpDBF.Checked := AnsiUpperCase(SysParamValue('RUN_OIL_AUTOLOAD_SREP')) = 'DBF';
cbFileExpOIL.Checked := AnsiUpperCase(SysParamValue('RUN_OIL_AUTOLOAD_SREP')) = 'OIL';
sbAutoLoad.Down := true;
sbAutoLoad.Click;
end;
cbFileExpDBFClick(nil);
cbFileExpOilClick(nil);
cbFileErrorLoadOnFTP.Checked := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadFileErrorLoadOnFTP_Checked') = '1';
cbLoadAddDBF.Checked := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadAddDBF_Checked') = '1';
cbLoadAddSections.Checked := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadAddSections_Checked') = '1';
cbLoadAddSectionsClick(nil);
cbLoadMyPack.Checked := ReadPieceOfRegistry(HKEY_CURRENT_USER, '\Software\Oil', 'SRepAutoLoadMyPack_Checked') = '1';
sbSaveSettings.Enabled := false;
slSRepMes := TStringList.Create;
end;
//==============================================================================
procedure TSRepAutoLoadF.deLoadDirKeyPress(Sender: TObject; var Key: Char);
begin
Key := #0;
end;
//==============================================================================
procedure TSRepAutoLoadF.ePeriodsKeyPress(Sender: TObject; var Key: Char);
begin
if not (key in ['0'..'9', #8]) then key := #0;
end;
//==============================================================================
procedure TSRepAutoLoadF.bbLoadDirClick(Sender: TObject);
begin
try
DR_AUTOLOAD := true;
slSRepMes.Clear;
LoadPackets(true); // завантажуємо файли DBF, OIL і ZIP з папки
finally
DR_AUTOLOAD := false;
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.bbLoadFTPClick(Sender: TObject);
begin
try
DR_AUTOLOAD := true;
slSRepMes.Clear;
PutPacketsWithFTP; // забираємо файли з FTP
LoadPackets(true); // завантажуємо файли DBF, OIL і ZIP з папки
finally
DR_AUTOLOAD := false;
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.GetVisibleClock(b: boolean); // Время следующей загрузки
begin
pClock.Visible := b;
lClock.Visible := b;
if b then
begin
if not tWork.Enabled then
begin
pClock.Caption := FormatDateTime('hh: nn: ss', Now + (tWork.Interval / (60000 * 24 * 60)));
tWork.Enabled := true;
end;
end
else
begin
pClock.Caption := '';
tWork.Enabled := false;
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.sbAutoLoadClick(Sender: TObject);
begin
inherited;
if (deLoadDir.Text = '') or (metFrom.Text = ' : ') or (metTo.Text = ' : ')
or (ePeriods.Text = '') then
begin
MessageDlg(TranslateText('Необходимо указать все поля!'), mtError, [mbOk], 0);
sbAutoLoad.Down := false;
exit;
end;
CreateDir(deLoadDir.Text); // створюємо директорію, якщо її встигли видалити
sSRepDirLog := deLoadDir.Text;
bbLoadDir.Enabled := not sbAutoLoad.Down;
bbLoadFTP.Enabled := not sbAutoLoad.Down;
sbLog.Enabled := not sbAutoLoad.Down;
p2.Enabled := not sbAutoLoad.Down;
tPeriod.Enabled := sbAutoLoad.Down;
if not sbAutoLoad.Down then
begin
GetVisibleClock(false); // Время следующей загрузки
tWork.Enabled := false;
end;
DR_AUTOLOAD := sbAutoLoad.Down;
if sbAutoLoad.Down then
sbAutoLoad.Hint := TranslateText('Выключить автозагрузку')
else sbAutoLoad.Hint := TranslateText('Включить автозагрузку');
end;
//==============================================================================
procedure TSRepAutoLoadF.tPeriodTimer(Sender: TObject);
var
HourFrom, HourTo, MinFrom, MinTo: integer;
TimeFrom, TimeTo, TimeNow: integer;
iHour, iMin, iSec, iMSec: Word;
begin
HourFrom := StrToInt(Copy(metFrom.Text, 1, 2));
MinFrom := StrToInt(Copy(metFrom.Text, 4, 2));
HourTo := StrToInt(Copy(metTo.Text, 1, 2));
MinTo := StrToInt(Copy(metTo.Text, 4, 2));
DecodeTime(Now, iHour, iMin, iSec, iMSec);
TimeFrom := HourFrom*3600 + MinFrom*60;
TimeTo := HourTo*3600 + MinTo*60;
TimeNow := iHour*3600 + iMin*60;
if (TimeFrom <= TimeNow) and (TimeTo >= TimeNow) then
begin
tWork.Interval := StrToInt(ePeriods.Text) * 60000;
GetVisibleClock(true); // Время следующей загрузки
end
else
if tWork.Enabled then
begin
GetVisibleClock(false); // Время следующей загрузки
sbLog.Click;
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.tWorkTimer(Sender: TObject);
begin
if not bAutoLoad then
try
// вмикаємо автоматичну загрузку, вимикаємо видачу повідомлень
bAutoLoad := true;
slSRepMes.Clear;
if eFTPName.Text <> '' then
PutPacketsWithFTP; // забираємо файли з FTP
LoadPackets(false); // завантажуємо файли DBF, OIL і ZIP з папки
finally
tWork.Enabled := false;
GetVisibleClock(true); // Время следующей загрузки
bAutoLoad := false;
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.metFromExit(Sender: TObject);
var
Msg: string;
begin
if SRep.SMRep.DateTimeIsCorrect(DateToStr(trunc(Now)) +' '+ (Sender as TMaskEdit).Text, Msg) then
else
begin
MessageDlg(Msg, mtError, [mbOk], 0);
(Sender as TMaskEdit).Text := ' : ';
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.GetActivePage(); // сторінка OIL/DBF
begin
if cbFileExpOil.Checked then
nb.ActivePage := 'OIL'
else
nb.ActivePage := 'DBF';
end;
//==============================================================================
procedure TSRepAutoLoadF.cbFileExpOilClick(Sender: TObject);
var
bClick: boolean;
begin
cbFileExpDBF.Checked := not cbFileExpOil.Checked;
GetActivePage(); // сторінка OIL/DBF
// Загружать только свои пакеты
cbLoadMyPack.Enabled := cbFileExpOil.Checked;
// Догружать дополнительные данные к сменным отчетам
cbLoadAddSections.Enabled := cbFileExpOil.Checked;
bClick := sbSaveSettings.Enabled;
cbLoadAddSectionsClick(nil);
sbSaveSettings.Enabled := bClick;
end;
//==============================================================================
procedure TSRepAutoLoadF.cbFileExpDBFClick(Sender: TObject);
begin
cbFileExpOil.Checked := not cbFileExpDBF.Checked;
GetActivePage(); // сторінка OIL/DBF
cbLoadRestDBF.Enabled := cbFileExpDBF.Checked;
if not cbLoadRestDBF.Enabled then
cbLoadRestDBF.Checked := false;
cbLoadAddDBF.Enabled := cbFileExpDBF.Checked;
if not cbLoadAddDBF.Enabled then
cbLoadAddDBF.Checked := false;
end;
//==============================================================================
function TSRepAutoLoadF.IsFileOK(p_FileName: string): boolean; // перевірка по назві файлу
begin
result :=
(p_FileName <> '.') and (p_FileName <> '..') and
((((AnsiUpperCase(ExtractFileExt(p_FileName)) = '.ZIP') or
(AnsiUpperCase(ExtractFileExt(p_FileName)) = '.OIL')) and cbFileExpOil.Checked) or
((AnsiUpperCase(ExtractFileExt(p_FileName)) = '.DBF') and cbFileExpDBF.Checked)) and
(pos('ERROR_', AnsiUpperCase(ExtractFileName(p_FileName))) = 0) and
(pos('ОСТАТКИ', AnsiUpperCase(ExtractFileName(p_FileName))) = 0) and
(pos('ЛОГИ', AnsiUpperCase(ExtractFileName(p_FileName))) = 0) and
(pos('РЕЗУЛЬТАТ ЗАПРОСА', AnsiUpperCase(ExtractFileName(p_FileName))) = 0);
end;
//==============================================================================
procedure TSRepAutoLoadF.BackupFiles();
var
SearchRec: TSearchRec;
Res: integer;
begin
try
CreateDir(deLoadDir.Text +'\BackupPacketsAZS');
Res := FindFirst(deLoadDir.Text +'\*.*', faAnyFile, SearchRec);
// знаходимо усі файли із АЗС
while Res = 0 do
begin
if IsFileOK(SearchRec.Name) then // перевірка по назві файлу
CopyLoadedFile(deLoadDir.Text +'\'+ SearchRec.Name,
deLoadDir.Text +'\BackupPacketsAZS', false);
Res := FindNext(SearchRec);
end;
FindClose(SearchRec);
except on E: Exception do
raise Exception.Create(E.Message);
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.LoadPackets(bMes: boolean=true); // завантажуємо файли DBF, OIL і ZIP з папки
var
SLPackets: TStringList;
SearchRec: TSearchRec;
Res: integer;
//****************************************************************************
procedure FindSR_H(p_azs_id: integer; p_rep_date: TDateTime);
// якщо за даний день знайдено змінний звіт внесений вручну,
// то за цей день не можна грузити автоматично змінні звіти
begin
if GetSqlValueParSimple(
'select count(*) from Oil_Daily_Rep' +
' where trunc(rep_date) = trunc(to_date(:p_rep_date, ''dd.mm.yyyy HH24:mi''))' +
' and state = ''Y''' +
' and azs_id = :p_azs_id and azs_inst = :p_azs_id' +
' and auto_load in (''H'', ''HE'', ''Y'', ''YE'')',
['p_rep_date', p_rep_date,
'p_azs_id', p_azs_id]) <> 0 then
raise Exception.Create(
TranslateText('Невозможно загрузить сменный отчет, так как он уже введен вручную!'));
end;
//****************************************************************************
//****************************************************************************
procedure DeleteSrTable(sTableName: string; ARep_Id, ARep_Inst: integer); // видаляємо дані із АЗС
begin
_ExecSql(
'update '+ sTableName +' set state = ''N''' +
' where state = ''Y'' and rep_id = :p_rep_id and rep_inst = :p_rep_inst',
['p_rep_id', ARep_Id,
'p_rep_inst', ARep_Inst]);
end;
//****************************************************************************
//****************************************************************************
function LoadAddSections(sFileName: string): boolean; // завантаження додаткових секцій
var
SLPacketText, SLSections: TStringList;
ARep_Date: TDateTime;
i, ARep_Id, ARep_Inst, AAZS_Id, ASmena_Num: integer;
Packet: TPacket;
IsDocAZS: boolean; // додаткові дані із АЗС
begin
result := false;
pbDetailed.Position := 0;
pbDetailed.Max := 4;
SLPacketText := TStringList.Create;
Application.CreateForm(TSRepForm, SMRep);
try
SLPacketText.Clear;
SMRep.OpenFileSRep(sFileName, SLPacketText); // завантаження файлу
pbDetailed.StepIt;
// якщо пакет не містить секції TOTAL, або ми бажаємо загрузити якусь окрему секцію, то
if (pos('TOTAL:', SLPacketText.Text) = 0) or (dblcSections.KeyValue <> null) then
begin
// знаходимо змінний звіт
ARep_Date := 0;
ASmena_Num := 0;
AAZS_Id := 0;
for i := 0 to SLPacketText.Count - 1 do
begin
// Дата змінного звіту
if (Pos('DATE:', SLPacketText[i]) = 1) and (Length(SLPacketText[i]) > 5) then
ARep_Date := StrToDateTime(Copy(SLPacketText[i], 7, Length(SLPacketText[i])));
// Зміна
if (Pos('NOM:', SLPacketText[i]) = 1) and (Length(SLPacketText[i]) > 4) then
ASmena_Num := StrToInt(Copy(SLPacketText[i], 5, Length(SLPacketText[i])));
// Id АЗС
if (Pos('AZS:', SLPacketText[i]) = 1) and (Length(SLPacketText[i]) > 4) then
AAZS_Id := 1000000 + StrToInt(Copy(SLPacketText[i], 5, Length(SLPacketText[i])));
end;
pbDetailed.StepIt;
IsDocAZS := ASmena_Num = -1; // додаткові дані із АЗС
qWork.Close;
qWork.SQL.Text :=
'select id, inst from Oil_Daily_Rep' +
' where state = ''Y''' +
' and inst = :p_inst' +
' and azs_id = :p_azs_id and azs_inst = :p_azs_id' +
' and to_date(to_char(rep_date, ''dd.mm.yyyy HH24:mi''), ''dd.mm.yyyy HH24:mi'') =' +
' to_date(to_char(:p_rep_date, ''dd.mm.yyyy HH24:mi''), ''dd.mm.yyyy HH24:mi'')' +
' and smena_num = :p_smena_num';
_OpenQueryPar(qWork,
['p_inst', MAIN_ORG.Inst,
'p_azs_id', AAZS_Id,
'p_rep_date', ARep_Date,
'p_smena_num', ASmena_Num]);
if qWork.IsEmpty then
begin
if IsDocAZS then // додаткові дані із АЗС
begin
// Это сменный отчет с дополнительными данными с АЗС.
ARep_Id := DBSaver.SaveRecord('OIL_DAILY_REP',
['ID', GetNextId('OIL_DAILY_REP', ['INST', MAIN_ORG.Inst], 'S_DAILY_REP'),
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'REP_DATE', ARep_Date,
'AZS_ID', AAZS_Id,
'AZS_INST', AAZS_Id,
'REP_NUM', StrToInt(FormatDateTime('dd', ARep_Date)),
'SMENA_NUM', -1,
'EMP_ID', null,
'EMP_INST', null,
'AUTO_LOAD', 'P',
'USER_ID', SUPER_REAL_EMP_ID
]);
ARep_Inst := MAIN_ORG.Inst;
end
else
raise Exception.Create(
TranslateText('Не найден сменный отчет, к которому можно догрузить дополнительные данные!'));
end
else
begin
ARep_Id := qWork.FieldByName('id').AsInteger;
ARep_Inst := qWork.FieldByName('inst').AsInteger;
end;
pbDetailed.StepIt;
// загрузка секцій із АЗС
Packet := TPacket.Create(SLPacketText);
try
if dblcSections.KeyValue <> null then
begin
SRepAutoLoadLog(TranslateText('Начало загрузки секции ')+ dblcSections.KeyValue);
// видаляємо дані із АЗС
DeleteSrTable(qSections.FieldByName('table_name').AsString, ARep_Id, ARep_Inst);
// вставляємо дані
SMRep.SaveSection(
ARep_Id,
ARep_Inst,
qSections.FieldByName('table_name').AsString,
qSections.FieldByName('section_name').AsString,
qSections.FieldByName('table_fields').AsString,
qSections.FieldByName('section_fields').AsString,
Packet
);
end
else
begin
SRepAutoLoadLog(TranslateText('Загрузка секций ...'));
SLSections := Packet.GetAllSections; // знаходимо усі секції
qWork.Close;
qWork.SQL.Text :=
'select * from oil_azs_sections' +
' where state = ''Y''' +
' and table_name is not null and table_fields is not null' +
' and section_name is not null and section_fields is not null' +
' order by id';
_OpenQuery(qWork); // відкриваємо дані про всі секціії
for i := 0 to SLSections.Count - 1 do
begin
if (Packet.OpenSection(SLSections[i]) < 0) or qWork.IsEmpty then
Continue;
SRepAutoLoadLog(' '+ SLSections[i]);
qWork.Filtered := false;
qWork.Filter := 'section_name = '+ QuotedStr(SLSections[i]);
qWork.Filtered := true;
// видаляємо дані із АЗС
DeleteSrTable(qWork.FieldByName('table_name').AsString, ARep_Id, ARep_Inst);
// вставляємо дані
SMRep.SaveSection(
ARep_Id,
ARep_Inst,
qWork.FieldByName('table_name').AsString,
SLSections[i],
qWork.FieldByName('table_fields').AsString,
qWork.FieldByName('section_fields').AsString,
Packet
);
end;
end;
finally
if Assigned(Packet) then FreeAndNil(Packet);
end; // Packet := TPacket.Create(SLPacketText);
pbDetailed.StepIt;
CommitSQL;
SRepAutoLoadLog(TranslateText('ЗАГРУЖЕН ') +
TranslateText(' Дата: ')+ DateTimeToStr(ARep_Date) +
TranslateText(' АЗС: ')+ GetOrgName(AAZS_Id, AAZS_Id) +
TranslateText(' Номер смены: ')+ IntToStr(ASmena_Num));
// копіювання завантаженного файлу і видалення його
CopyLoadedFile(sFileName, deLoadDir.Text +'\LoadedPacketsAZS', true);
result := true;
end;
finally
FreeAndNil(SLPacketText);
FreeAndNil(SMRep);
qWork.Filter := '';
qWork.Filtered := false;
qWork.Close;
pbDetailed.Position := 0;
end;
end;
//****************************************************************************
//****************************************************************************
procedure AddSROil(sFileName: string);
begin
// Догружать дополнительные данные к сменным отчетам
if cbLoadAddSections.Checked then
if LoadAddSections(sFileName) then // завантаження додаткових секцій
exit;
pbDetailed.Position := 0;
pbDetailed.Max := 8;
with SRepRef do
begin
try
if not q.Active then q.Open;
// вставка нового рядка
q.Insert;
q.FieldByName('Id').AsInteger := GetSeqNextVal('S_DAILY_REP');
q.FieldByName('Inst').AsInteger := MAIN_ORG.Inst;
q.Post; pbDetailed.StepIt;
// відкриття форми змінного звіту і редагування її
Application.CreateForm(TSRepForm, SMRep);
try
SMrep.bLoadMyPack := cbLoadMyPack.Checked; // Загружать только свои пакеты
SMrep.mode := 1;
SMrep.pLoadFromFile.Visible := True;
SMRep.FormShow(SMRep); pbDetailed.StepIt;
SMRep.odPacket.FileName := sFileName; // передаємо наш файл
SMRep.Visible := false;
SMRep.bbLoadFromFile.Click; pbDetailed.StepIt;
SMRep.bbRealization.Click; pbDetailed.StepIt;
SMRep.bbIncas.Click; pbDetailed.StepIt;
// якщо за даний день знайдено змінний звіт внесений вручну,
// то за цей день не можна грузити автоматично змінні звіти
FindSR_H(q.FieldByName('AZS_Id').AsInteger, q.FieldByName('Rep_Date').AsDateTime);
SMRep.bbOk.Click; pbDetailed.StepIt;
// приймаємо повідомлення
if q.State <> dsBrowse then q.Post;
// корегування номеру зміни
//--------------------------------------------------------------------
qWork.Close;
qWork.SQL.Text :=
'select row_number() over(order by rep_date) as num, dr.* from Oil_Daily_Rep dr' +
' where trunc(rep_date) = trunc(to_date(:p_rep_date, ''dd.mm.yyyy HH24:mi''))' +
' and state = ''Y'' and smena_num > 0' +
' and AZS_Id = :p_azs_id and AZS_Inst = :p_azs_id' +
' order by rep_date';
_OpenQueryPar(qWork,
['p_rep_date', FormatDateTime('dd.mm.yyyy hh:nn', q.FieldByName('Rep_Date').AsDateTime),
'p_azs_id', q.FieldByName('AZS_Id').AsInteger]);
qWork.First;
while not qWork.Eof do
begin
if qWork.FieldByName('smena_num').AsInteger <> qWork.FieldByName('num').AsInteger then
begin
DBSaver.SaveRecord('OIL_DAILY_REP',
['ID', qWork.FieldByName('Id').AsInteger,
'INST', qWork.FieldByName('Inst').AsInteger,
'SMENA_NUM', qWork.FieldByName('num').AsInteger
]);
SRepAutoLoadLog(
TranslateText('Дата: ')+ q.FieldByName('REP_DATE').AsString +
TranslateText(' АЗС: ')+ q.FieldByName('AZS_NAME').AsString +
TranslateText(' Номер смены: ')+
qWork.FieldByName('smena_num').AsString +' --> '+ qWork.FieldByName('num').AsString);
end;
qWork.Next
end;
pbDetailed.StepIt;
//--------------------------------------------------------------------
SaveAzsReceive;
finally
FreeAndNil(SMRep);
end;
iPackets := iPackets + 1;
SRepAutoLoadLog(TranslateText('ЗАГРУЖЕН ') +
TranslateText(' Дата: ')+ q.FieldByName('REP_DATE').AsString +
TranslateText(' АЗС: ')+ q.FieldByName('AZS_NAME').AsString +
TranslateText(' Номер смены: ')+ q.FieldByName('SMENA_NUM').AsString);
SaveDbLog(urtSuccessful, '', sFileName,
q.FieldByName('Id').AsInteger,
q.FieldByName('Inst').AsInteger);
pbDetailed.StepIt;
CommitSQL;
// копіювання завантаженного файлу і видалення його
CopyLoadedFile(sFileName, deLoadDir.Text +'\LoadedPacketsAZS', true);
pbDetailed.Position := 0;
except on E: Exception do
begin
pbDetailed.Position := 0;
if q.State <> dsBrowse then q.Post;
q.Delete;
raise Exception.Create(E.Message);
end;
end;
end;
end;
//****************************************************************************
begin
if not cbFileExpOil.Checked and not cbFileExpDBF.Checked then exit;
if deLoadDir.Text = '' then
begin
MessageDlg(TranslateText('Необходимо выбрать папку, с которой будут грузиться файлы с АЗС!'), mtError, [mbOk], 0);
exit;
end;
CreateDir(deLoadDir.Text); // створюємо директорію, якщо її встигли видалити
BackupFiles(); // робимо резервну копію файлів із АЗС
sSRepDirLog := deLoadDir.Text;
try
SLPackets := TStringList.Create;
try
//------------------------------------------------------------------------
SLPackets.Clear;
Res := FindFirst(deLoadDir.Text +'\*.*', faAnyFile, SearchRec);
// знаходимо усі файли із АЗС
while Res = 0 do
begin
if IsFileOK(SearchRec.Name) then // перевірка по назві файлу
SLPackets.Add(deLoadDir.Text +'\'+ SearchRec.Name);
Res := FindNext(SearchRec);
end;
FindClose(SearchRec);
SLPackets.Sort;
//------------------------------------------------------------------------
CreateDir(deLoadDir.Text +'\LoadedPacketsAZS');
iPackets := 0;
Res := 0;
pbPerfect.Position := 0;
pbPerfect.Max := SLPackets.Count;
// завантажуємо усі файли із АЗС
SRepAutoLoadLog('/*************************************************************/');
SRepAutoLoadLog(TranslateText('/**********************/Начало загрузки/**********************/'));
SRepAutoLoadLog(TranslateText('Количество загружаемых файлов: ')+ IntToStr(SLPackets.Count) +'.');
if bMes then
if MessageDlg(TranslateText('Загрузить файлы с папки ')+ deLoadDir.Text +' ?'#10#13 +
TranslateText('Количество загружаемых файлов: ')+ IntToStr(SLPackets.Count) +'.',
mtConfirmation, [mbYes, mbNo], 0) = mrNo then exit;
//------------------------------------------------------------------------
if SLPackets.Count > 0 then
begin
SRepAutoLoadLog(' ');
SLPackets.Sorted := true;
SLPackets.Sort;
while Res <> SLPackets.Count do
begin
SRepAutoLoadLog(TranslateText('Начало загрузки файла "')+ ExtractFileName(SLPackets.Strings[Res]) +'"');
StartSQL;
try
if cbFileExpOil.Checked then AddSROil(SLPackets.Strings[Res]); // OIL, ZIP
if cbFileExpDBF.Checked then AddSRDBF(SLPackets.Strings[Res]); // DBF
except on E: Exception do
begin
// якщо це завантаження пакетів із АЗС і помилка "OPERATION ABORTED", то не перейменовуємо
if not (cbFileExpOil.Checked and (pos('OPERATION ABORTED', AnsiUpperCase(E.Message)) > 0)) then
FileErrorLoadOnFTP(SLPackets.Strings[Res]);
if cbFileExpDBF.Checked then
SRepAutoLoadLog(TranslateText('Ошибка на строке: ')+ IntToStr(iRecords + 1) +'.');
SRepAutoLoadLog(TranslateText('НЕ ЗАГРУЖЕН!!! ОШИБКА: ')+ trim(E.Message)); // помилка
RollbackSQL;
SaveDbLog(urtUnSuccessful, '', SLPackets.Strings[Res], null, null);
CommitSQL;
end;
end;
SRepAutoLoadLog(' ');
Res := Res + 1;
pbPerfect.StepIt;
end;
end;
//------------------------------------------------------------------------
finally
pbPerfect.Position := 0;
SRepAutoLoadLog(TranslateText('Количество загруженных файлов: ')+ IntToStr(iPackets) +'.');
SRepAutoLoadLog(TranslateText('Лог загрузки у файле "')+ deLoadDir.Text +'\' +
'SRepAutoLoad_'+ FormatDateTime('yyyy-mm-dd', now()) +'.log"');
SRepAutoLoadLog(TranslateText('/**********************/Конец загрузки /**********************/'));
SRepAutoLoadLog('/*************************************************************/');
SRepAutoLoadLog(' ');
SRepAutoLoadLog(' ');
FreeAndNil(SLPackets);
if bMes and (slSRepMes.Count <> 0) then
ShowText(slSRepMes.Text);
end;
except on E: Exception do
begin
if bMes then
MessageDlg(TranslateText('Ошибка загрузки: ')+ E.Message, mtError, [mbOk], 0)
else SRepAutoLoadLog(TranslateText('Ошибка загрузки: ')+ E.Message);
end;
end;
end;
//==============================================================================
function TSRepAutoLoadF.ConnectFTP: boolean; // підключаємося до FTP (ftp://login:pass@host)
var
AConnStr: string;
Handler: TIdIOHandlerStack;
Through: TIdConnectThroughHttpProxy;
begin
result := true;
try
if IdFTP.Connected then
IdFTP.Disconnect;
AConnStr := eFTPName.Text;
if trim(AConnStr) <> '' then
begin
IdFTP.UserName := copy(AConnStr, 1, pos(':',AConnStr)-1);
AConnStr := copy(AConnStr, pos(':',AConnStr)+1, Length(AConnStr));
IdFTP.Password := copy(AConnStr, 1, pos('@',AConnStr)-1);
AConnStr := copy(AConnStr, pos('@',AConnStr)+1, Length(AConnStr));
if pos('/', AConnStr) > 0 then
IdFTP.Host := copy(AConnStr, 1, pos('/', AConnStr)-1)
else
IdFTP.Host := AConnStr;
// Proxy
//------------------------------------------------------------------------
if (eProxyHost.Text <> '') and (eProxyPort.Text <> '') then
begin
Handler := TIdIOHandlerStack.Create(self);
Through := TIdConnectThroughHttpProxy.Create(self);
Through.Host := eProxyHost.Text;
Through.Port := StrToInt(eProxyPort.Text);
Through.Enabled := true;
IdFTP.IOHandler := Handler;
Handler.TransparentProxy := Through;
end;
//------------------------------------------------------------------------
end
else
begin
SRepAutoLoadLog(TranslateText('Соединение с FTP не прошло успешно!') +#10+
TranslateText('Не указан адрес FTP!'));
result := false;
exit;
end;
IdFTP.TransferType := ftBinary;
IdFTP.Passive := true;
IdFTP.IPVersion := Id_IPv4;
IdFTP.Connect;
// взнаємо директорію на FTP
if pos('/', AConnStr) > 0 then
begin
AConnStr := copy(AConnStr, pos('/',AConnStr)+1, Length(AConnStr));
if AConnStr <> '' then
IdFTP.ChangeDir(AConnStr); // заходимо у необхідну директорію
end;
SRepAutoLoadLog(TranslateText('Соединение с FTP прошло успешно'));
except on E: Exception do
begin
SRepAutoLoadLog(TranslateText('Соединение с FTP не прошло успешно! Ошибка: ')+ E.Message);
result := false;
end;
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.PutPacketsWithFTP; // забираємо файли з FTP
var
SL: TStringList;
i, iSentFiles: integer;
begin
SRepAutoLoadLog('/*************************************************************/');
SRepAutoLoadLog(TranslateText('/**********************/Работа с FTP /**********************/'));
SL := TStringList.Create;
try
if not ConnectFTP then exit;
try
try
IdFTP.List(SL, '*.*', false);
except on E: Exception do
if not (pos('10054', e.Message) > 0) then // немає файлів
raise Exception.Create(E.Message);
end;
SRepAutoLoadLog(TranslateText('Информация о файлах на FTP считана'));
iSentFiles := 0;
for i := 0 to SL.Count - 1 do
begin
if SL.Strings[i] <> '' then
if IsFileOK(SL.Strings[i]) then // перевірка по назві файлу
try
DeleteFile(deLoadDir.Text +'\'+ SL.Strings[i]);
IdFTP.Get(SL.Strings[i], deLoadDir.Text +'\'+ SL.Strings[i]{, true, false});
IdFTP.Delete(SL.Strings[i]);
SRepAutoLoadLog(TranslateText('Файл "')+ SL.Strings[i] +TranslateText('" c FTP загружен.'));
iSentFiles := iSentFiles + 1;
except
end;
end;
SRepAutoLoadLog(TranslateText('Файлы c FTP загружены. Количество загруженных файлов: ')+ IntToStr(iSentFiles));
except on E: Exception do
SRepAutoLoadLog(TranslateText('Загрузка файлов c FTP не произошла! Ошибка: ')+ e.Message);
end;
finally
SRepAutoLoadLog(TranslateText('Отсоединение от FTP'));
IdFTP.Disconnect;
FreeAndNil(SL);
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.AddSRDBF(sFileName: string); // завантажуємо файли DBF
const
UpdRepDet =
'update %s set state = ''N''' +
' where state = ''Y''' +
' and (srep_id, srep_inst) in' +
' (select /*+ORDERED*/ drd.id, drd.inst' +
' from oil_daily_rep dr, oil_dr_data drd, v_oil_azs azs' +
' where dr.state = ''Y'' and drd.state = ''Y''' +
' and dr.auto_load = ''Y''' +
' and drd.rep_id = dr.id' +
' and drd.rep_inst = dr.inst' +
' and trunc(dr.rep_date) between :DateFrom and :DateTo' +
' and :obl_id in (azs.obl_id, azs.par)' +
' and dr.azs_id = azs.id' +
' and dr.azs_inst = azs.inst)';
var
SL_AZS, SL_NPG, SL_NB: TStringList;
Year, Month, Day: Word;
isFirstRep, isFirstRepMonth: boolean; // це перший змінний звіт, це перший змінний звіт у цьому місяці
isHand, isDelNpRest: boolean; // це змінний звіт внесений вручну, залишки є вже видалені
REP_ID, DEP_ID, AZS_ID, REP_AZS_ID, NPG_ID, NB_ID: integer;
DEP_NAME, DateFrom, DateTo: string;
REP_DATE: TDateTime;
iRestRecords, iHandRecords: integer;
REP_ID_REST_CORR: integer; // для корегування залишків
REP_DATE_REST_CORR: TDateTime; // для корегування залишків
FilesDBF: TMemoryStream; // DBF-файл приводимо до нормального кодування
REST_DATE: TDateTime;
begin
REP_ID := 0;
REP_AZS_ID := 0;
REP_DATE := 0;
REP_ID_REST_CORR := 0; // для корегування залишків
REP_DATE_REST_CORR := 0; // для корегування залишків
iRecords := 0;
iRestRecords := 0;
iHandRecords := 0;
isFirstRep := false;
isFirstRepMonth := false;
isDelNpRest := false;
isHand := true;
SL_AZS := TStringList.Create;
SL_NPG := TStringList.Create;
SL_NB := TStringList.Create;
qPart := TOilQuery.Create(nil);
qRez := TOilQuery.Create(nil);
qRash := TOilQuery.Create(nil);
try
if FileExists(deLoadDir.Text +'\ImportListAZSId.cfg') then
SL_AZS.LoadFromFile(deLoadDir.Text +'\ImportListAZSId.cfg');
if FileExists(deLoadDir.Text +'\ImportListNPGId.cfg') then
SL_NPG.LoadFromFile(deLoadDir.Text +'\ImportListNPGId.cfg');
if FileExists(deLoadDir.Text +'\ImportListNBId.cfg') then
SL_NB.LoadFromFile(deLoadDir.Text +'\ImportListNBId.cfg');
// DBF-файл приводимо до нормального кодування
FilesDBF := TMemoryStream.Create;
try
FilesDBF.LoadFromFile(sFileName);
FilesDBF.Position := 29;
FilesDBF.Write('W1', 1);
FilesDBF.SaveToFile(sFileName);
finally
FilesDBF.Free;
end;
qDBF.Close;
qDBF.SQL.Text := 'select * from "'+ sFileName + '"';
qDBF.Open;
if not qDBF.FieldList.Equals(qColumns.SQL) then // перевірка полів у файлі DBF
raise Exception.Create(TranslateText('Неверный формат таблицы!'));
qDBF.Close;
qDBF.SQL.Text := 'select count(*) from "'+ sFileName +'" group by obl_okpo';
qDBF.Open;
if qDBF.RecordCount <> 1 then
raise Exception.Create(TranslateText('У DBF-файле не допускается несколько главных организаций!'));
qDBF.Close;
qDBF.SQL.Text :=
'select rep_date, obl_okpo, azs_name, smena_num, np_name, oper_type, oper_id,' +
' koment_op, p_price, litr, weight, density, summ, nb' +
' from "'+ sFileName +'"' +
' order by rep_date, obl_okpo, azs_name, smena_num, np_name, oper_type, oper_id';
qDBF.Open;
// взнаємо період даних у файлі
qDBF.First;
DateFrom := FormatDateTime('dd.mm.yyyy', qDBF.FieldByName('rep_date').AsDateTime);
qDBF.Last;
DateTo := FormatDateTime('dd.mm.yyyy', qDBF.FieldByName('rep_date').AsDateTime);
SRepAutoLoadLog(TranslateText('Количество загружаемых строк: ')+ IntToStr(qDBF.RecordCount) +'.');
qDBF.First;
// знаходимо організацію
if nvl(GetSqlValueParSimple(
'select count(1) from oil_org' +
' where state = ''Y''' +
' and id = inst' +
' and id_num = :id_num',
['id_num', qDBF.FieldByName('obl_okpo').AsString]), 0) = 0 then
raise Exception.Create(TranslateText('Не найдена главная организация!'));
// беремо із першої записі ОКПО і знаємо, що цей обл буде і у всіх інших записях
DEP_ID := nvl(GetSqlValueParSimple(
'select id from oil_org' +
' where state = ''Y''' +
' and id = inst' +
' and instr('','' || :id_list || '','', '','' || id || '','') > 0' +
' and id_num = :id_num',
['id_list', GetInst_List(MAIN_ORG.Inst, MAIN_ORG.Inst),
'id_num', qDBF.FieldByName('obl_okpo').AsString]), 0);
if pos(IntToStr(DEP_ID), GetInst_List(MAIN_ORG.Inst, MAIN_ORG.Inst)) <= 0 then
raise Exception.Create(TranslateText('Организация не имеет прав загружаться в данную базу данных!'));
// взнаємо назву організації
DEP_NAME := GetOrgName(DEP_ID, DEP_ID);
SRepAutoLoadLog(TranslateText(' Организация: ')+ DEP_NAME +
TranslateText(' Период с ')+ DateFrom +TranslateText(' по ')+ DateTo);
// видаляємо змінні звіти за період
//--------------------------------------------------------------------------
if (nvl(GetSqlValueParSimple(
'select count(*) from oil_daily_rep dr, v_oil_azs azs' +
' where dr.state = ''Y''' +
' and dr.auto_load = ''Y''' +
' and trunc(dr.rep_date) between :DateFrom and :DateTo' +
' and :obl_id in (azs.obl_id, azs.par)' +
' and dr.azs_id = azs.id' +
' and dr.azs_inst = azs.inst',
['DateFrom', DateFrom,
'DateTo', DateTo,
'obl_id', DEP_ID]), 0) <> 0) and (not cbLoadAddDBF.Checked) then
begin
// змінний звіт
_ExecSql(Format(UpdRepDet, ['oil_vedomost']),
['DateFrom', DateFrom,
'DateTo', DateTo,
'obl_id', DEP_ID]);
_ExecSql(Format(UpdRepDet, ['oil_srtalon']),
['DateFrom', DateFrom,
'DateTo', DateTo,
'obl_id', DEP_ID]);
_ExecSql(Format(UpdRepDet, ['oil_srother']),
['DateFrom', DateFrom,
'DateTo', DateTo,
'obl_id', DEP_ID]);
_ExecSql(
'update oil_dr_data set state = ''N''' +
' where state = ''Y''' +
' and (rep_id, rep_inst) in' +
' (select /*+ORDERED*/ dr.id, dr.inst' +
' from oil_daily_rep dr, v_oil_azs azs' +
' where dr.state = ''Y''' +
' and dr.auto_load = ''Y''' +
' and trunc(dr.rep_date) between :DateFrom and :DateTo' +
' and :obl_id in (azs.obl_id, azs.par)' +
' and dr.azs_id = azs.id' +
' and dr.azs_inst = azs.inst)',
['DateFrom', DateFrom,
'DateTo', DateTo,
'obl_id', DEP_ID]);
_ExecSql(
'update exch_receive_azs set state = ''N''' +
' where state = ''Y''' +
' and (rep_id, rep_inst) in' +
' (select /*+ORDERED*/ dr.id, dr.inst' +
' from oil_daily_rep dr, v_oil_azs azs' +
' where dr.state = ''Y''' +
' and dr.auto_load = ''Y''' +
' and trunc(dr.rep_date) between :DateFrom and :DateTo' +
' and :obl_id in (azs.obl_id, azs.par)' +
' and dr.azs_id = azs.id' +
' and dr.azs_inst = azs.inst)',
['DateFrom', DateFrom,
'DateTo', DateTo,
'obl_id', DEP_ID]);
_ExecSql(
'update oil_daily_rep dr set dr.state = ''N''' +
' where dr.state = ''Y''' +
' and dr.auto_load = ''Y''' +
' and trunc(dr.rep_date) between :DateFrom and :DateTo' +
' and exists (select 1 from v_oil_azs azs' +
' where :obl_id in (azs.obl_id, azs.par)' +
' and dr.azs_id = azs.id' +
' and dr.azs_inst = azs.inst)',
['DateFrom', DateFrom,
'DateTo', DateTo,
'obl_id', DEP_ID]);
// приходи на НБ
{
_ExecSql(
'update oil_prihod set state = ''N''' +
' where state = ''Y''' +
' and (id, inst) in' +
' (select /*+ORDERED*/ r.ttn_num, r.inst' +
' from oil_daily_rep dr,' +
' oil_dr_data drd,' +
' oil_rashod r,' +
' v_oil_azs azs' +
' where dr.state = ''Y'' and drd.state = ''Y'' and r.state = ''Y''' +
' and dr.auto_load = ''Y''' +
' and drd.oper_type = 0' +
' and dr.id = drd.rep_id' +
' and dr.inst = drd.rep_inst' +
' and drd.ttn_id = r.id' +
' and drd.ttn_inst = r.inst' +
' and dr.azs_id = azs.id' +
' and dr.azs_inst = azs.inst' +
' and trunc(dr.rep_date) between :DateFrom and :DateTo' +
' and :obl_id in (azs.obl_id, azs.par))',
['DateFrom', DateFrom,
'DateTo', DateTo,
'obl_id', DEP_ID]);
_ExecSql(
'update oil_prih_det set state = ''N''' +
' where state = ''Y''' +
' and (prihod_id, inst) in' +
' (select id, inst from oil_prihod where state = ''N'')');
// відпуски на АЗС
_ExecSql(
'update oil_rashod set state = ''N''' +
' where state = ''Y''' +
' and (id, inst) in' +
' (select /*+ORDERED*/ drd.ttn_id, drd.ttn_inst' +
' from oil_daily_rep dr, oil_dr_data drd, v_oil_azs azs' +
' where dr.state = ''Y'' and drd.state = ''Y''' +
' and dr.auto_load = ''Y''' +
' and drd.oper_type = 0' +
' and dr.id = drd.rep_id' +
' and dr.inst = drd.rep_inst' +
' and dr.azs_id = azs.id' +
' and dr.azs_inst = azs.inst' +
' and trunc(dr.rep_date) between :DateFrom and :DateTo' +
' and :obl_id in (azs.obl_id, azs.par))',
['DateFrom', DateFrom,
'DateTo', DateTo,
'obl_id', DEP_ID]);
}
end;
//--------------------------------------------------------------------------
pbDetailed.Position := 0;
pbDetailed.Max := qDBF.RecordCount;
// повсюду будемо брати партію із найменшим ід
qPart.SQL.Text :=
'select /*+ORDERED*/ min(p.np_type) as np_id, min(p.id) as id, p.inst, np.grp_id' +
' from oil_part p, oil_np_type np' +
' where p.state = ''Y''' +
' and p.np_type = np.id' +
' group by p.inst, np.grp_id' +
' order by decode(ov.GetVal(''INST''), inst, 0, inst)';
_OpenQuery(qPart);
// повсюду будемо брати резервуар із найменшим ід
qRez.SQL.Text :=
'select /*+ORDERED*/ min(r.id) as id, r.inst, np.grp_id, r.id_org, r.inst_org' +
' from oil_rezervuar r, oil_np_type np' +
' where r.state = ''Y''' +
' and r.np_type_id = np.id' +
' group by r.inst, np.grp_id, r.id_org, r.inst_org' +
' order by decode(ov.GetVal(''INST''), inst, 0, inst)';
_OpenQuery(qRez);
// відпуски на АЗС
qRash.SQL.Text :=
'select /*+ORDERED*/ r.id, r.date_, r.inst, npt.np_grp, r.from_id, r.from_inst, r.to_id, r.to_inst, r.litr, r.count_, r.ud_weig, r.price' +
' from oil_rashod r, oil_part p, v_oil_np_type npt' +
' where r.state = ''Y'' and p.state = ''Y''' +
' and r.part_id = p.id and r.part_inst = p.inst' +
' and r.oper_id in (7, 10)' +
' and p.np_type = npt.id' +
' and not exists (select 1' +
' from oil_dr_data drd' +
' where drd.state = ''Y''' +
' and r.id = drd.ttn_id and r.inst = drd.ttn_inst)';
_OpenQuery(qRash);
//--------------------------------------------------------------------------
qDBF.First;
while not qDBF.Eof do
begin
iRecords := iRecords + 1;
// знаходимо АЗС
GetAZS(SL_AZS, DEP_ID, qDBF.FieldByName('azs_name').AsString,
qDBF.FieldByName('obl_okpo').AsString, AZS_ID);
// знаходимо групу НП
GetNPG(SL_NPG, qDBF.FieldByName('np_name').AsString, NPG_ID);
if (AZS_ID <> 0) and (NPG_ID <> 0) then
begin
// знаходимо змінний звіт або добавляємо його
if not ((REP_AZS_ID = AZS_ID) and (REP_DATE = qDBF.FieldByName('rep_date').AsDateTime)) then
begin
REP_ID_REST_CORR := 0; // для корегування залишків
if REP_DATE_REST_CORR = 0 then
REP_DATE_REST_CORR := qDBF.FieldByName('rep_date').AsDateTime; // для корегування залишків
REP_AZS_ID := AZS_ID;
REP_DATE := Trunc(qDBF.FieldByName('rep_date').AsDateTime);
// це перший змінний звіт
isFirstRep := nvl(GetSqlValueParSimple(
'select count(*) from oil_daily_rep' +
' where state = ''Y'' and azs_id = :p_azs_id and azs_inst = :p_azs_id' +
' and trunc(rep_date) < :p_rep_date' +
' and trunc(rep_date) <> to_date(''31.05.2009'', ''dd.mm.yyyy'')',
['p_azs_id', AZS_ID, 'p_rep_date', REP_DATE]), 0) = 0;
// це перший змінний звіт у цьому місяці
isFirstRepMonth := nvl(GetSqlValueParSimple(
'select count(*) from oil_daily_rep' +
' where state = ''Y'' and azs_id = :p_azs_id and azs_inst = :p_azs_id' +
' and trunc(rep_date) between trunc(:p_rep_date, ''mm'') and trunc(:p_rep_date)',
['p_azs_id', AZS_ID, 'p_rep_date', REP_DATE]), 0) = 0;
// видалення попередніх залишків, якщо вони введені не вручну
if (not isDelNpRest) and isFirstRepMonth then
begin
// формуємо дату залишків
DecodeDate(REP_DATE, Year, Month, Day);
REST_DATE := EncodeDate(year, month, 1);
_ExecSqlOra(
'update oil_np_rest set state = ''N''' +
' where state = ''Y'' and manual = ''N''' +
' and inst = :p_inst and trunc(date_) = trunc(:p_rep_date)',
['p_inst', MAIN_ORG.Inst, 'p_rep_date', REST_DATE]);
isDelNpRest := true;
end;
// взнаємо чи це змінний звіт внесений вручну
isHand := false;
qWork.Close;
qWork.SQL.Text := 'select * from oil_daily_rep' +
' where state = ''Y'' and smena_num = 1' +
' and trunc(rep_date) = :p_rep_date' +
' and azs_id = :p_azs_id and azs_inst = :p_azs_id';
_OpenQueryPar(qWork, ['p_azs_id', AZS_ID, 'p_rep_date', REP_DATE]);
if not qWork.IsEmpty then
isHand := qWork.FieldByName('auto_load').AsString <> 'Y';
// якщо стоїть галочка "Догружать все данные",
// то ми, або догружаємо всі дані до існуючого змінного звіту,
// або догружаємо всі дані до створеного змінного звіту
if cbLoadAddDBF.Checked and (not qWork.FieldByName('id').IsNull) then
REP_ID := qWork.FieldByName('id').AsInteger
else
if (not isHand) or cbLoadAddDBF.Checked then
begin
DecodeDate(REP_DATE, Year, Month, Day);
REP_ID := DBSaver.SaveRecord('OIL_DAILY_REP',
['ID', GetNextId('OIL_DAILY_REP', ['INST', MAIN_ORG.Inst, 'AUTO_LOAD', 'Y'], 'S_DAILY_REP'),
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'REP_DATE', REP_DATE,
'AZS_ID', AZS_ID,
'AZS_INST', AZS_ID,
'REP_NUM', Day,
'SMENA_NUM', 1,
'EMP_ID', null,
'EMP_INST', null,
'AUTO_LOAD', 'Y',
'USER_ID', SUPER_REAL_EMP_ID
]);
SaveDbLog(urtSuccessful, '', sFileName, REP_ID, MAIN_ORG.Inst);
end;
end;
if (REP_ID <> 0) and ((not isHand) or cbLoadAddDBF.Checked) then
begin
// створюємо прихід НП на АЗС
if ((qDBF.FieldByName('oper_type').AsInteger = 0) and isFirstRep)
or (qDBF.FieldByName('oper_type').AsInteger = 1) then
begin
// знаходимо НБ
NB_ID := 0;
GetNB(SL_NB, qDBF.FieldByName('nb').AsString, NB_ID);
SetPrihRepDBF(
REP_DATE,
REP_ID, DEP_ID, NB_ID, AZS_ID, NPG_ID,
qDBF.FieldByName('LITR').AsFloat,
qDBF.FieldByName('P_PRICE').AsFloat,
qDBF.FieldByName('WEIGHT').AsFloat,
qDBF.FieldByName('DENSITY').AsFloat);
end;
// якщо це не перший змінний звіт по АЗС, то всі залишки вважаємо вже завантаженими
if (qDBF.FieldByName('oper_type').AsInteger = 0) and not isFirstRep then
begin
// якщо це є перший змінний звіт у цьому місяці, і НЕ перший змінний звіт
if isFirstRepMonth then // заносимо залишки у базу даних
begin
qPart.Filtered := false;
qPart.Filter := 'grp_id = '+ IntToStr(NPG_ID);
qPart.Filtered := true;
if qRashMin = nil then
begin
qRashMin := TOilQuery.Create(nil);
GetRashMin(0); // повсюду будемо брати відпуск на АЗС із найменшим ід
end;
GetRashMinFilter(AZS_ID, NPG_ID, 0); // фільтруємо qRashMin
if qRashMin.FieldByName('id').IsNull then
begin
GetRashMin(0); // повсюду будемо брати відпуск на АЗС із найменшим ід
GetRashMinFilter(AZS_ID, NPG_ID, 0); // фільтруємо qRashMin
end;
DBSaver.SaveRecord('OIL_NP_REST',
['ID', GetNextId('OIL_NP_REST', ['DATE_', REST_DATE]),
'INST', MAIN_ORG.Inst,
'STATE', 'Y',
'DATE_', REST_DATE,
'AZS_ID', AZS_ID,
'NP_TYPE_ID', qPart.FieldByName('np_id').AsInteger,
'TTN_ID', qRashMin.FieldByName('id').AsInteger,
'TTN_INST', qRashMin.FieldByName('inst').AsInteger,
'PRICE', qDBF.FieldByName('P_PRICE').AsFloat,
'UD_WEIGHT', qDBF.FieldByName('DENSITY').AsFloat,
'REST_LITR', MRound(qDBF.FieldByName('LITR').AsFloat, 3),
'REST_KG', MRound(qDBF.FieldByName('WEIGHT').AsFloat, DR_ROUND_COUNT),
'MANUAL', 'N'
]);
end;
// корегуємо залишки
// якщо це перший змінний звіт у цьому місяці,
// або стоїть галочка "Откорректировать остатки на начало периода"
if cbLoadRestDBF.Checked and (REP_DATE = REP_DATE_REST_CORR) then
begin
if not SetRestNPDailyRep(
AZS_ID, NPG_ID, 0, qDBF.FieldByName('LITR').AsFloat, qDBF.FieldByName('WEIGHT').AsFloat,
REP_DATE_REST_CORR, REP_ID_REST_CORR) then
// якщо товар не відпускався на АЗС, то створюємо його прихід
SetPrihRepDBF(
REP_DATE,
REP_ID, DEP_ID, 0, AZS_ID, NPG_ID,
qDBF.FieldByName('LITR').AsFloat,
qDBF.FieldByName('P_PRICE').AsFloat,
qDBF.FieldByName('WEIGHT').AsFloat,
qDBF.FieldByName('DENSITY').AsFloat);
end
else
iRestRecords := iRestRecords + 1;
end;
// створюємо реалізацію НП на АЗС
if qDBF.FieldByName('oper_type').AsInteger = 2 then
SetRashRepDBF(
AZS_ID, REP_ID, NPG_ID, 0,
qDBF.FieldByName('oper_id').AsInteger,
qDBF.FieldByName('LITR').AsFloat,
qDBF.FieldByName('P_PRICE').AsFloat,
qDBF.FieldByName('WEIGHT').AsFloat,
qDBF.FieldByName('DENSITY').AsFloat,
qDBF.FieldByName('SUMM').AsFloat);
end;
if isHand and (not cbLoadAddDBF.Checked) then
iHandRecords := iHandRecords + 1;
end;
pbDetailed.StepIt;
qDBF.Next;
end;
//--------------------------------------------------------------------------
CommitSQL;
iPackets := iPackets + 1;
SRepAutoLoadLog(TranslateText('Количество обработанных строк: ')+ IntToStr(iRecords) +'.');
SRepAutoLoadLog(TranslateText('Откорректировано остатки на ')+ DateToStr(REP_DATE_REST_CORR) +'.');
SRepAutoLoadLog(TranslateText('Количество не загруженных строк с остатками: ')+ IntToStr(iRestRecords) +'.');
SRepAutoLoadLog(TranslateText('Количество не загруженных строк (сменные отчеты введены вручную): ')+ IntToStr(iHandRecords) +'.');
SRepAutoLoadLog(TranslateText('ЗАГРУЖЕН ')+TranslateText(' Организация: ')+ DEP_NAME +
TranslateText(' Период с ')+ DateFrom +TranslateText(' по ')+ DateTo);
// копіювання завантаженного файлу і видалення його
CopyLoadedFile(sFileName, deLoadDir.Text +'\LoadedPacketsAZS', true);
SL_AZS.SaveToFile(deLoadDir.Text +'\ImportListAZSId.cfg');
SL_NPG.SaveToFile(deLoadDir.Text +'\ImportListNPGId.cfg');
SL_NB.SaveToFile(deLoadDir.Text +'\ImportListNBId.cfg');
finally
pbDetailed.Position := 0;
FreeAndNil(SL_AZS);
FreeAndNil(SL_NPG);
FreeAndNil(SL_NB);
FreeAndNil(qPart);
FreeAndNil(qRez);
FreeAndNil(qRash);
FreeAndNil(qRashMin);
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.GetAZS(
SL: TStringList; ADep_id: integer;
AAZS, ADepOKPO: string; var AId: integer);
var
AZS_Num, pInst: integer;
pName, pValue: string;
begin
try
pValue := AAZS +' '+ ADepOKPO;
AId := -1;
if (SL.Values[pValue] <> '') then // Выбор из сохраненных
AId := StrToInt(SL.Values[pValue]);
if AId = -1 then
if TryStrToInt(AAZS, AZS_Num) then // Исчем по номеру
AId := nvl(GetSqlValueParSimple(
'select id from v_oil_azs where azs_num = :azs_num and par = :par and par_inst = :par_inst',
['azs_num', AZS_Num, 'par', ADep_id, 'par_inst', ADep_id]), -1);
if AId = -1 then // Даем выбор
begin
ShowMessage('Сделайте выбор АЗС для значения '+ pValue);
ChooseOrg.CaptureOrg(2, ADep_id, ADep_id, 'yyy', AId, pInst, pName);
SL.Values[pValue] := IntToStr(AId); // Сохраняем выбор
end;
if AId = -1 then
raise Exception.Create(TranslateText('Не выбрана АЗС для значения ')+ pValue);
except on E: Exception do
raise Exception.Create('GetAZS: '+ E.Message);
end
end;
//==============================================================================
procedure TSRepAutoLoadF.GetNPG(SL: TStringList; AValue: string; var AId: integer);
begin
try
AId := -1;
if SL.Values[AValue] <> '' then // Выбор из сохраненных
AId := StrToInt(SL.Values[AValue]);
if AId = -1 then // Даем выбор
begin
ShowMessage('Сделайте выбор группы НП для значения '+ AValue);
XMLChoose('NpGroupRef', AId);
SL.Values[AValue] := IntToStr(AId);
end;
if AId = -1 then
raise Exception.Create(TranslateText('Не выбрана группа НП для значения ')+ AValue);
except on E: Exception do
raise Exception.Create('GetNPG: '+ E.Message);
end
end;
//==============================================================================
procedure TSRepAutoLoadF.GetNB(SL: TStringList; ANB: string; var AId: integer);
var
pInst: integer;
pName: string;
begin
if ANB <> '' then
try
AId := -1;
if (SL.Values[ANB] <> '') then // Выбор из сохраненных
AId := StrToInt(SL.Values[ANB]);
if AId = -1 then // Даем выбор
begin
ShowMessage('Сделайте выбор НБ для значения '+ ANB);
ChooseOrg.CaptureOrg(1, 0, 0, 'yyx', AId, pInst, pName);
SL.Values[ANB] := IntToStr(AId); // Сохраняем выбор
end;
if AId = -1 then
raise Exception.Create(TranslateText('Не выбрана НБ для значения ')+ ANB);
except on E: Exception do
raise Exception.Create('GetNB: '+ E.Message);
end
end;
//==============================================================================
procedure TSRepAutoLoadF.SetPrihRepDBF(
p_Date: TDateTime;
p_REP_ID, p_DEP_ID, p_NB_ID, p_AZS_ID, p_NPG: integer;
p_LITR, p_PRICE, p_WEIGHT, p_DENSITY: Real); // створюємо прихід НП на АЗС
var
NB_ID, FROM_ID, FROM_INST: integer;
begin
// повсюду будемо брати партію із найменшим ід
qPart.Filtered := false;
qPart.Filter := 'grp_id = '+ IntToStr(p_NPG);
qPart.Filtered := true;
if p_NB_ID = 0 then
NB_ID := p_DEP_ID
else NB_ID := p_NB_ID;
if NB_ID = 0 then
NB_ID := MAIN_ORG.Inst;
// повсюду будемо брати резервуар із найменшим ід
qRez.Filtered := false;
qRez.Filter :=
' grp_id = '+ IntToStr(p_NPG) +' and '+
' id_org = '+ IntToStr(NB_ID) +' and '+
'inst_org = '+ IntToStr(NB_ID);
qRez.Filtered := true;
// відпуски на АЗС
qRash.Filtered := false;
qRash.Filter :=
' date_ = '+ QuotedStr(FormatDateTime('dd.mm.yyyy', p_Date)) +
' and inst = '+ IntToStr(MAIN_ORG.Inst) +
' and np_grp = '+ IntToStr(p_NPG) +
' and from_id = '+ IntToStr(p_NB_ID) +
' and from_inst = '+ IntToStr(p_NB_ID) +
' and to_id = '+ IntToStr(p_AZS_ID) +
' and to_inst = '+ IntToStr(p_AZS_ID) +
' and litr = '+ QuotedStr(FloatToStr(p_LITR)) +
' and count_ = '+ QuotedStr(FloatToStr(MRound(p_WEIGHT, DR_ROUND_COUNT))) +
' and ud_weig = '+ QuotedStr(FloatToStr(p_DENSITY)) +
' and price = '+ QuotedStr(FloatToStr(p_PRICE));
qRash.Filtered := true;
FROM_ID := MAIN_ORG.Par;
FROM_INST := MAIN_ORG.Par_inst;
SRep.SMRep.GetSupplierPrih(FROM_ID, FROM_INST); // знаходимо постачальника
SetPrihRep(
trunc(p_Date),
FROM_ID, NB_ID, p_AZS_ID, qPart.FieldByName('np_id').AsInteger,
p_REP_ID, MAIN_ORG.Inst, // змінний звіт
qRash.FieldByName('id').AsInteger, qRash.FieldByName('inst').AsInteger, // відпуск на АЗС
qPart.FieldByName('id').AsInteger, qPart.FieldByName('inst').AsInteger, // партія
qRez.FieldByName('id').AsInteger, qRez.FieldByName('inst').AsInteger, // резервуар
0, 0, // автомобіль
0, 0, // водій
trunc(p_Date), // дата ТТН
IntToStr(p_REP_ID), '', // номер ТТН, номер машини/цистерни
p_LITR, p_PRICE, p_WEIGHT, p_DENSITY, 0,
qRash.FieldByName('id').IsNull, // створюємо прихід на НБ
qRash.FieldByName('id').IsNull, // створюємо відпуск з НБ
true // створюємо прихід на АЗС
); // створюємо прихід НП на АЗС
end;
//==============================================================================
procedure TSRepAutoLoadF.GetRashMin(p_NP: integer); // повсюду будемо брати відпуск на АЗС із найменшим ід
begin
qRashMin.Close;
qRashMin.SQL.Text :=
'select min(p.np_type) as np_id, min(r.id) as id, r.inst,' +
' np.'+ decode([p_NP, 0, 'grp_id', 'id']) +' as np, r.to_id, r.to_inst' +
' from oil_rashod r, oil_part p, oil_np_type np' +
' where r.state = ''Y'' and p.state = ''Y'' and np.state = ''Y''' +
' and r.part_id = p.id and r.part_inst = p.inst' +
' and p.np_type = np.id' +
' group by r.inst, np.'+ decode([p_NP, 0, 'grp_id', 'id']) +', r.to_id, r.to_inst' +
' order by decode(ov.GetVal(''INST''), inst, 0, inst)';
_OpenQuery(qRashMin);
end;
//==============================================================================
procedure TSRepAutoLoadF.GetRashMinFilter(p_AZS_ID, p_NPG, p_NP: integer); // фільтруємо qRashMin
begin
qRashMin.Filtered := false;
qRashMin.Filter :=
' np = '+ IntToStr(decode([p_NP, 0, p_NPG, p_NP])) +
' and to_id = '+ IntToStr(p_AZS_ID) +
' and to_inst = '+ IntToStr(p_AZS_ID);
qRashMin.Filtered := true;
end;
//==============================================================================
procedure TSRepAutoLoadF.SetRashRepDBF(
p_AZS_ID, p_REP_ID, p_NPG, p_NP, p_OPER_ID: integer;
p_LITR, p_PRICE, p_WEIGHT, p_DENSITY, p_SUMM: Real); // створюємо реалізацію НП на АЗС
var
DR_ID: integer;
qDRRash: TOilQuery;
OUT_NAL_LITR, OUT_NAL_COUNT, OUT_NAL_MONEY,
OUT_VED_LITR, OUT_VED_COUNT, OUT_VED_MONEY,
OUT_TALON_LITR, OUT_TALON_COUNT, OUT_TALON_MONEY,
OUT_SN_LITR, OUT_SN_COUNT, OUT_SN_MONEY,
OUT_LITR, OUT_COUNT, OUT_MONEY: variant;
begin
if qRashMin = nil then
begin
qRashMin := TOilQuery.Create(nil);
GetRashMin(p_NP); // повсюду будемо брати відпуск на АЗС із найменшим ід
end;
GetRashMinFilter(p_AZS_ID, p_NPG, p_NP); // фільтруємо qRashMin
if qRashMin.FieldByName('id').IsNull then
begin
GetRashMin(p_NP); // повсюду будемо брати відпуск на АЗС із найменшим ід
GetRashMinFilter(p_AZS_ID, p_NPG, p_NP); // фільтруємо qRashMin
end;
qDRRash := TOilQuery.Create(nil);
try
// знаходимо реалізацію по необхідному торару
qDRRash.SQL.Text :=
'select /*+ORDERED*/' +
' drd.id,' +
' out_nal_litr, out_nal_count, out_nal_money,' +
' out_ved_litr, out_ved_count, out_ved_money,' +
' out_talon_litr, out_talon_count, out_talon_money,' +
' out_sn_litr, out_sn_count, out_sn_money,' +
' out_litr, out_count, out_money' +
' from oil_dr_data drd, oil_rashod r, oil_part p, oil_np_type np' +
' where r.state = ''Y'' and p.state = ''Y'' and np.state = ''Y'' and drd.state = ''Y''' +
' and r.part_id = p.id and r.part_inst = p.inst' +
' and p.np_type = np.id' +
' and drd.oper_type = 1' +
' and r.to_id = :azs_id and r.to_inst = :azs_id' +
' and drd.rep_id = :rep_id and drd.rep_inst = :rep_inst' +
' and np.'+ decode([p_NP, 0, 'grp_id', 'id']) +' = :np_id' +
' and drd.ttn_id = r.id and drd.ttn_inst = r.inst';
_OpenQueryPar(qDRRash,
['np_id', decode([p_NP, 0, p_NPG, p_NP]),
'azs_id', p_AZS_ID,
'rep_id', p_REP_ID,
'rep_inst', MAIN_ORG.Inst]);
if not qRashMin.FieldByName('id').IsNull then
begin
if qDRRash.FieldByName('id').IsNull then
DR_ID := GetNextId('OIL_DR_DATA', ['REP_ID', p_REP_ID, 'REP_INST', MAIN_ORG.Inst])
else
DR_ID := qDRRash.FieldByName('id').AsInteger;
{за нал/р (л) 0
по ведомостям (л) 11
по визе (л) 201
по ТК УКРНАФТА (л) 277
по ТК РД АВИАС (л) 276
по ТК МРД АВИАС (л) 275
по СКРЕТЧ РД АВИАС (л) 274
по СКРЕТЧ МРД АВИАС (л) 273
по ТАЛОНАМ РД ANP (л) 14
по СМАРТ КАРТАМ МРД ANP(л) 153
тал. РД (л) бумажные разовые 272
тал МРД (л) бумажные разовые 272
тал. РД (л) нового образца 271
тал МРД (л) нового образца 270
Корректировка остатков тонн 278}
if p_OPER_ID >= 0 then
begin
OUT_NAL_LITR := qDRRash.FieldByName('OUT_NAL_LITR').AsFloat;
OUT_NAL_COUNT := qDRRash.FieldByName('OUT_NAL_COUNT').AsFloat;
OUT_NAL_MONEY := qDRRash.FieldByName('OUT_NAL_MONEY').AsFloat;
OUT_VED_LITR := qDRRash.FieldByName('OUT_VED_LITR').AsFloat;
OUT_VED_COUNT := qDRRash.FieldByName('OUT_VED_COUNT').AsFloat;
OUT_VED_MONEY := qDRRash.FieldByName('OUT_VED_MONEY').AsFloat;
OUT_TALON_LITR := qDRRash.FieldByName('OUT_TALON_LITR').AsFloat;
OUT_TALON_COUNT := qDRRash.FieldByName('OUT_TALON_COUNT').AsFloat;
OUT_TALON_MONEY := qDRRash.FieldByName('OUT_TALON_MONEY').AsFloat;
OUT_SN_LITR := qDRRash.FieldByName('OUT_SN_LITR').AsFloat;
OUT_SN_COUNT := qDRRash.FieldByName('OUT_SN_COUNT').AsFloat;
OUT_SN_MONEY := qDRRash.FieldByName('OUT_SN_MONEY').AsFloat;
OUT_LITR := qDRRash.FieldByName('OUT_LITR').AsFloat;
OUT_COUNT := qDRRash.FieldByName('OUT_COUNT').AsFloat;
OUT_MONEY := qDRRash.FieldByName('OUT_MONEY').AsFloat;
case p_OPER_ID of
0:
begin
OUT_NAL_LITR := OUT_NAL_LITR + p_LITR;
OUT_NAL_COUNT := OUT_NAL_COUNT + p_WEIGHT;
OUT_NAL_MONEY := OUT_NAL_MONEY + p_SUMM;
end;
11:
begin
OUT_VED_LITR := OUT_VED_LITR + p_LITR;
OUT_VED_COUNT := OUT_VED_COUNT + p_WEIGHT;
OUT_VED_MONEY := OUT_VED_MONEY + p_SUMM;
end;
14:
begin
OUT_TALON_LITR := OUT_TALON_LITR + p_LITR;
OUT_TALON_COUNT := OUT_TALON_COUNT + p_WEIGHT;
OUT_TALON_MONEY := OUT_TALON_MONEY + p_SUMM;
end;
153, 201, 270, 271, 272, 273, 274, 275, 276, 277, 278, 55:
begin
OUT_LITR := OUT_LITR + p_LITR;
OUT_COUNT := OUT_COUNT + p_WEIGHT;
OUT_MONEY := OUT_MONEY + p_SUMM;
end;
else
raise Exception.CreateFmt('Не обработаная операция %d',[p_OPER_ID])
end;
end;
DBSaver.SaveRecord('OIL_DR_DATA',
['ID', DR_ID,
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'REP_ID', p_REP_ID,
'REP_INST', MAIN_ORG.Inst,
'OPER_TYPE', 1,
'TTN_ID', qRashMin.FieldByName('id').AsInteger,
'TTN_INST', qRashMin.FieldByName('inst').AsInteger,
'PR_LITR', null,
'PR_UD_WEIG', p_DENSITY,
'PR_COUNT', null,
'S_PRICE', p_PRICE,
'OUT_NAL_LITR', OUT_NAL_LITR,
'OUT_NAL_COUNT', MRound(OUT_NAL_COUNT, DR_ROUND_COUNT),
'OUT_NAL_MONEY', OUT_NAL_MONEY,
'OUT_VED_LITR', OUT_VED_LITR,
'OUT_VED_COUNT', MRound(OUT_VED_COUNT, DR_ROUND_COUNT),
'OUT_VED_MONEY', OUT_VED_MONEY,
'OUT_TALON_LITR', OUT_TALON_LITR,
'OUT_TALON_COUNT', MRound(OUT_TALON_COUNT, DR_ROUND_COUNT),
'OUT_TALON_MONEY', OUT_TALON_MONEY,
'OUT_SN_LITR', OUT_SN_LITR,
'OUT_SN_COUNT', MRound(OUT_SN_COUNT, DR_ROUND_COUNT),
'OUT_SN_MONEY', OUT_SN_MONEY,
'OUT_RASH_ID', null,
'OUT_LITR', OUT_LITR,
'OUT_COUNT', MRound(OUT_COUNT, DR_ROUND_COUNT),
'OUT_MONEY', OUT_MONEY,
'SUB_PART', qRashMin.FieldByName('np_id').AsInteger,
'START_SM', 0,
'END_SM', 0
]);
if p_OPER_ID > 0 then
begin
case p_OPER_ID of
11:
begin
DBSaver.SaveRecord('OIL_VEDOMOST',
['ID', GetNextId('OIL_VEDOMOST', ['SREP_ID', DR_ID, 'SREP_INST', MAIN_ORG.Inst]),
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'SREP_ID', DR_ID,
'SREP_INST', MAIN_ORG.Inst,
'LITR', p_LITR,
'COUNT_T', MRound(p_WEIGHT, DR_ROUND_COUNT),
'PRICE', p_PRICE,
'AMOUNT', p_SUMM
]);
end;
14:
begin
DBSaver.SaveRecord('OIL_SRTALON',
['ID', GetNextId('OIL_SRTALON', ['SREP_ID', DR_ID, 'SREP_INST', MAIN_ORG.Inst]),
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'SREP_ID', DR_ID,
'SREP_INST', MAIN_ORG.Inst,
'SER', null,
'NUM', 0,
'LITR', p_LITR,
'COUNT_T', MRound(p_WEIGHT, DR_ROUND_COUNT),
'PRICE', p_PRICE,
'INTHEWAY', 4
]);
end;
153, 201, 270, 271, 272, 273, 274, 275, 276, 277, 278, 55:
begin
DBSaver.SaveRecord('OIL_SROTHER',
['ID', GetNextId('OIL_SROTHER', ['SREP_ID', DR_ID, 'SREP_INST', MAIN_ORG.Inst]),
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'SREP_ID', DR_ID,
'SREP_INST', MAIN_ORG.Inst,
'OPER_ID', p_OPER_ID,
'LITR', p_LITR,
'COUNT_T', MRound(p_WEIGHT, DR_ROUND_COUNT),
'PRICE', p_PRICE,
'AMOUNT', p_SUMM
]);
end;
end;
end;
end
else
raise Exception.Create(TranslateText('Не найдено отпуска на АЗС для группы НП ')+ IntToStr(p_NPG));
finally
FreeAndNil(qDRRash);
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.SaveDbLog(AResultType: TUploadResultType; AResultComment, AFileName: string;
ARepId, ARepInst: variant);
var
ResultCode: integer;
//****************************************************************************
function GetCommentOil(): string;
var
i: integer;
sl: TStringList;
IsProcessed: boolean;
begin
sl := TStringList.Create;
try
IsProcessed := False;
// Читаем лог с конца (ЗАГРУЖЕН) до начала загрузки
for i := slSRepMes.Count-1 downto 0 do
begin
if pos('ЗАГРУЖЕН', slSRepMes[i]) <> 0 then
IsProcessed := True;
if IsProcessed then
sl.Insert(0, slSRepMes[i]);
if pos('Начало загрузки файла', slSRepMes[i]) <> 0 then
break;
end;
Result := sl.Text;
finally
FreeAndNil(sl);
end;
end;
//****************************************************************************
begin
if DBObjectExists('EXCH_RECEIVE_AZS', 'TABLE', DBSaver.OS.Username) then
begin
case AResultType of
urtSuccessful: ResultCode := 0;
urtUnSuccessful: ResultCode := 1;
else
raise Exception.Create(TranslateText('SaveDbLog: Не определен код результата загрузки!'));
end;
if (AResultComment = '') and cbFileExpOil.Checked then
AResultComment := GetCommentOil();
DBSaver.SaveRecord('EXCH_RECEIVE_AZS',
['ID', GetNextId('EXCH_RECEIVE_AZS', ['REP_ID', ARepId, 'REP_INST', ARepInst]),
'INST', MAIN.INST,
'STATE', 'Y',
'EXCH_TYPE', decode([cbFileExpOil.Checked, true, 1, 2]),
'REP_ID', ARepId,
'REP_INST', ARepInst,
'DATE_RECEIVE', GetSystemDate(),
'RESULT', ResultCode,
'RES_COMMENT', copy(AResultComment, 1, 2048),
'FILENAME', ExtractFileName(AFileName)]);
end;
end;
//==============================================================================
class procedure TSRepAutoLoadF.DailyRepAddRash(
p_AZS_ID, p_REP_ID, p_NPG, p_NP, p_OPER_ID: integer;
p_LITR, p_PRICE, p_WEIGHT, p_DENSITY, p_SUMM: Real);
var
FAL: TSRepAutoLoadF;
begin
FAL := TSRepAutoLoadF.Create(nil);
try
FAL.SetRashRepDBF(
p_AZS_ID, p_REP_ID, p_NPG, p_NP, p_OPER_ID,
p_LITR, p_PRICE, p_WEIGHT, p_DENSITY, p_SUMM);
finally
FreeAndNil(FAL);
end;
end;
//==============================================================================
procedure TSRepAutoLoadF.eFTPNameChange(Sender: TObject);
begin
sbSaveSettings.Enabled := true;
cbFileErrorLoadOnFTP.Enabled := eFTPName.Text <> '';
eProxyHost.Enabled := cbFileErrorLoadOnFTP.Enabled;
eProxyPort.Enabled := cbFileErrorLoadOnFTP.Enabled;
end;
//==============================================================================
procedure TSRepAutoLoadF.sbSaveSettingsClick(Sender: TObject);
begin
WritePieceOfRegistry('SRepAutoLoadDir', deLoadDir.Text);
WritePieceOfRegistry('SRepAutoLoadFTP', eFTPName.Text);
WritePieceOfRegistry('SRepAutoLoadProxyHost', eProxyHost.Text);
WritePieceOfRegistry('SRepAutoLoadProxyPort', eProxyPort.Text);
WritePieceOfRegistry('SRepAutoLoadTimeFrom', metFrom.Text);
WritePieceOfRegistry('SRepAutoLoadTimeTo', metTo.Text);
WritePieceOfRegistry('SRepAutoLoadPeriods', ePeriods.Text);
WritePieceOfRegistry('SRepAutoLoadFileErrorLoadOnFTP_Checked', decode([cbFileErrorLoadOnFTP.Checked, true, '1', '0']));
WritePieceOfRegistry('SRepAutoLoadAddDBF_Checked', decode([cbLoadAddDBF.Checked, true, '1', '0']));
WritePieceOfRegistry('SRepAutoLoadAddSections_Checked', decode([cbLoadAddSections.Checked, true, '1', '0']));
WritePieceOfRegistry('SRepAutoLoadMyPack_Checked', decode([cbLoadMyPack.Checked, true, '1', '0']));
sbSaveSettings.Enabled := false;
end;
//==============================================================================
procedure TSRepAutoLoadF.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if qRashMin <> nil then // повсюду будемо брати відпуск на АЗС із найменшим ід
FreeAndNil(qRashMin);
FreeAndNil(slSRepMes);
DR_AUTOLOAD := false;
end;
//==============================================================================
procedure TSRepAutoLoadF.FileErrorLoadOnFTP(sFileName: string);
// Файлы, загруженные с ошибками выкладывать на FTP
var
sFileNameNEW: string;
begin
sFileName := CopyLoadedFile(sFileName, ExtractFilePath(sFileName),
true, 'Error_');
sFileNameNEW := ExtractFilePath(sFileName) +'Error_'+ ExtractFileName(sFileName);
RenameFile(sFileName, sFileNameNEW);
if cbFileErrorLoadOnFTP.Checked then
try
if ConnectFTP then
try
IdFTP.Put(sFileNameNEW, ExtractFileName(sFileNameNEW));
SRepAutoLoadLog(TranslateText('Файл отправлен на FTP'));
finally
IdFTP.Disconnect;
end;
except
SRepAutoLoadLog(TranslateText('Файл НЕ отправлен на FTP'));
end;
end;
//==============================================================================
function TSRepAutoLoadF.CopyLoadedFile(p_FileName, p_Dir: string; p_Del: boolean;
p_NoFileName: string = ''): string;
// шукає вільну назву файлу у директорії і копіює туди файл
var
sFileNameTo, sExt, sName, sNameTemp: string;
i, iTemp, iExt, iName: integer;
begin
if p_Dir[length(p_Dir)] = '\' then
p_Dir := copy(p_Dir, 1, length(p_Dir)-1);
sFileNameTo := p_Dir +'\'+ ExtractFileName(p_FileName);
// назва файлу
sName := ExtractFileName(sFileNameTo);
iName := length(sName);
// розширення файлу
sExt := ExtractFileExt(sFileNameTo);
iExt := length(sExt);
// шукаємо останній "_"
iTemp := 0;
for i := length(sName) downto 1 do
if sName[i] = '_' then
begin
iTemp := length(sName) - i + 1;
break;
end;
// якщо розмір змінився до 2, то дозволяємо зміну
sNameTemp := copy(sName, 1, iName - iTemp) + sExt;
if abs(length(sNameTemp) - length(sName)) <= 2 then
begin
sName := sNameTemp;
iName := length(sName);
sFileNameTo := p_Dir +'\'+ ExtractFileName(sName);
end;
// шукаємо вільну назву файлу
for i := 1 to 99 do
if FileExists(sFileNameTo)
or FileExists(p_Dir +'\'+ p_NoFileName + ExtractFileName(sFileNameTo)) then
sFileNameTo :=
p_Dir +'\'+ copy(sName, 1, iName - iExt) +'_'+ IntToStr(i) + sExt
else break;
CopyFile(PChar(p_FileName), PChar(sFileNameTo), false);
if p_Del then
DeleteFile(p_FileName);
result := sFileNameTo;
end;
//==============================================================================
function TSRepAutoLoadF.SetRestNPDailyRep(
p_AzsID, p_NpgID, p_NpID: integer; // АЗС, Група НП або Тип НП
p_RestLitr, p_RestCount: real; // залишок, який має бути на дату p_Date
p_Date: TDateTime; // дата, на яку треба мати залишок p_RestLitr і p_RestCount
var p_RepID: integer; // ID шапки змінного звіту із корегуючими даними
p_AutoLoad: string='Y'; // тип загрузки
p_Commit: boolean=false // чи зберігати дані у цій процедурі
): boolean; // якщо false, то товар не відпускався на АЗС
var
RashLitr, RashCount: real;
begin
result := true;
if p_Commit then StartSQL;
try
if (p_AzsID = 0) or (p_Date = 0)
or ((p_NpgID = 0) and (p_NpID = 0))
or ((p_NpgID <> 0) and (p_NpID <> 0)) then
raise Exception.Create(
TranslateText('Неверно введены параметры процедуры SetRestNPDailyRep!'));
// знаходимо залишки
if p_NpgID = 0 then qRestNP.SQL.Text := qRestNP.BaseSQL +' and c.np_type_id = :p_np'
else qRestNP.SQL.Text := qRestNP.BaseSQL +' and c.np_grp = :p_np';
_OpenQueryPar(qRestNP,
['p_rep_date', p_Date,
'p_azs_id', p_AzsID,
'p_np', decode([p_NpgID, 0, p_NpID, p_NpgID])]);
if qRestNP.IsEmpty then
raise Exception.Create(
TranslateText('Не найдено отпусков на ')+ GetOrgName(p_AzsID, p_AzsID) +
TranslateText(' для группы НП ')+ IntToStr(p_NpgID));
if (p_RepID = 0) then
begin
// можливо за цей день вже були зміни із корегуючими залишками
try
p_RepID := nvl(GetSqlValueParSimple(
'select id from oil_daily_rep' +
' where state = ''Y''' +
' and inst = :p_inst' +
' and azs_id = :p_azs_id and azs_inst = :p_azs_id' +
' and to_date(to_char(rep_date, ''dd.mm.yyyy HH24:mi''), ''dd.mm.yyyy HH24:mi'') =' +
' to_date(to_char(:p_rep_date, ''dd.mm.yyyy HH24:mi''), ''dd.mm.yyyy HH24:mi'')',
['p_rep_date', StrToDateTime(FormatDateTime('dd.mm.yyyy hh:nn:ss', p_Date - 1 / (24 * 60))),
'p_azs_id', p_AzsID,
'p_inst', MAIN_ORG.Inst]), 0);
except
p_RepID := 0;
end;
if p_RepID = 0 then // шапка змінного звіту
p_RepID := DBSaver.SaveRecord('OIL_DAILY_REP',
['ID', GetNextId('OIL_DAILY_REP', ['INST', MAIN_ORG.Inst, 'AUTO_LOAD', 'Y'], 'S_DAILY_REP'),
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'REP_DATE', StrToDateTime(FormatDateTime('dd.mm.yyyy hh:nn:ss', p_Date - 1 / (24 * 60))),
'AZS_ID', p_AzsID,
'AZS_INST', p_AzsID,
'REP_NUM', 1,
'SMENA_NUM', 1,
'EMP_ID', null,
'EMP_INST', null,
'AUTO_LOAD', p_AutoLoad,
'USER_ID', SUPER_REAL_EMP_ID
]);
end;
RashLitr := MRound(qRestNP.FieldByName('RestOpenL').AsFloat - p_RestLitr, 3);
RashCount := MRound(qRestNP.FieldByName('RestOpenT').AsFloat - p_RestCount, DR_ROUND_COUNT);
if (RashLitr <> 0) or (RashCount <> 0) and (p_RepID <> 0) then
SetRashRepDBF(
p_AzsID, p_RepID, p_NpgID, p_NpID, 278,
RashLitr, qRestNP.FieldByName('s_price').AsFloat, RashCount,
qRestNP.FieldByName('ud_weig').AsFloat, RashLitr * qRestNP.FieldByName('s_price').AsFloat);
if p_Commit then CommitSQL;
except on E: Exception do
begin
result := false;
if p_Commit then RollbackSQL;
raise Exception.Create(TranslateText('Ошибка при корректировке остатков по : ')+ E.Message);
end;
end
end;
//==============================================================================
procedure TSRepAutoLoadF.eProxyHostKeyPress(Sender: TObject; var Key: Char);
begin
if key = ',' then key := '.';
if not (key in ['0'..'9', '.', #8]) then key := #0;
end;
//==============================================================================
procedure TSRepAutoLoadF.cbLoadAddSectionsClick(Sender: TObject);
begin
lSections.Enabled := cbLoadAddSections.Checked and cbLoadAddSections.Enabled;
dblcSections.Enabled := lSections.Enabled;
sbSections.Enabled := lSections.Enabled;
if lSections.Enabled and not qSections.Active then
_OpenQuery(qSections);
eFTPNameChange(nil);
end;
//==============================================================================
procedure TSRepAutoLoadF.sbSectionsClick(Sender: TObject);
begin
dblcSections.KeyValue := '';
end;
//==============================================================================
procedure TSRepAutoLoadF.SetPrihRep(
p_Date: TDateTime;
p_From {від кого}, p_NB {яка НБ}, p_AZS {якій АЗС}, p_Np,
p_Rep_id, p_Rep_inst, // змінний звіт
p_Rash_id, p_Rash_inst, // відпуск на АЗС
p_Part_id, p_Part_inst, // партія
p_Rez_id, p_Rez_inst, // резервуар
p_Auto_id, p_Auto_inst, // автомобіль
p_Emp_id, p_Emp_inst: integer; // водій
p_TTN_Date: TDateTime; // дата ТТН
p_TTN, p_Car: string; // номер ТТН, номер машини/цистерни
p_Litr, p_Price, p_Weight, p_Density, p_Temper: Real;
p_CH_Prih: boolean=true; // створюємо прихід на НБ
p_CH_Rash: boolean=true; // створюємо відпуск з НБ
p_CH_DR : boolean=true // створюємо прихід на АЗС
); // створюємо прихід НП на АЗС
var
Prih_id, Rash_id: integer;
begin
if (p_Part_id = 0) or (p_Rez_id = 0) then
raise Exception.Create(
TranslateText('Приход не создан!') +#13+
TranslateText('Не найдено партию и резервуар') +
TranslateText(' (по организации "')+ GetOrgName(p_NB, p_NB) +
TranslateText('") для типа НП ')+ IntToStr(p_Np)
);
Rash_id := 0;
if p_CH_Prih then
begin
Prih_id := DBSaver.SaveRecord('OIL_PRIHOD',
['ID', GetNextId('OIL_PRIHOD',
['INST', MAIN_ORG.Inst,
'DATE_', FormatDateTime('dd.mm.yyyy', p_Date)], 'S_OIL_PRIH'),
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'EMP_ID', EMP_ID,
'DATE_', FormatDateTime('dd.mm.yyyy', p_Date),
'DATE_DOC', FormatDateTime('dd.mm.yyyy', p_Date),
'DATE_DOC_RAIL', FormatDateTime('dd.mm.yyyy', p_Date),
'DATE_OTPR', FormatDateTime('dd.mm.yyyy', p_Date),
'OPER_ID', 1, // Приход собственого товара
'DOST', 3, // Автоцистерна
'NP_TYPE', p_Np,
'FROM_', p_From,
'FROM_INST', p_From,
'TO_', p_NB,
'TO_INST', p_NB,
'PART_ID', p_Part_id,
'PART_INST', p_Part_inst,
'DAYS_ON_WAY', 1
]);
DBSaver.SaveRecord('OIL_PRIH_DET',
['ID', GetNextId('OIL_PRIH_DET', ['INST', MAIN_ORG.Inst, 'PRIHOD_ID', Prih_id]),
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'PRIHOD_ID', Prih_id,
'NAKL', p_TTN,
'TANK', p_Car,
'DOC_COUNT', MRound(p_Weight, DR_ROUND_COUNT),
'FACT_COUNT', MRound(p_Weight, DR_ROUND_COUNT),
'REZ', p_Rez_id,
'REZ_INST', p_Rez_inst,
'NED_NORM_UB', 0,
'NED_NORM_ER', 0,
'NED_POST', 0,
'NED_RAIL', 0,
'IZL_NORM', 0,
'IZL_POST', 0,
'IS_DIGITAL_WEIGHT', 1,
'TECH_LOSS', 0
]);
end;
if p_CH_Rash then
begin
Rash_id := DBSaver.SaveRecord('OIL_RASHOD',
['ID', GetNextId('OIL_RASHOD',
['INST', MAIN_ORG.Inst,
'DATE_', FormatDateTime('dd.mm.yyyy', p_Date)], 'S_OIL_RASH'),
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'EMP_ID', EMP_ID,
'DATE_', FormatDateTime('dd.mm.yyyy', p_Date),
'FROM_ID', p_NB,
'FROM_INST', p_NB,
'TO_ID', p_AZS,
'TO_INST', p_AZS,
'OPER_ID', 10,
'TTN_NUM', decode([p_TTN, '', null, p_TTN]),
'TTN_DATE', FormatDateTime('dd.mm.yyyy', p_TTN_Date),
'PART_ID', p_Part_id,
'PART_INST', p_Part_inst,
'REZ', p_Rez_id,
'REZ_INST', p_Rez_inst,
'AUTO_ID', decode([p_Auto_id, 0, null, p_Auto_id]),
'AUTO_INST', decode([p_Auto_inst, 0, null, p_Auto_inst]),
'EMPLOY_ID', decode([p_Emp_id, 0, null, p_Emp_id]),
'EMPLOY_INST', decode([p_Emp_inst, 0, null, p_Emp_inst]),
'TEMPER', p_Temper,
'UD_WEIG', p_Density,
'LITR', p_Litr,
'COUNT_', MRound(p_Weight, DR_ROUND_COUNT),
'PRICE', p_Price,
'SUMMA', MRound(p_Litr * p_Price, 2),
'PACK', decode([p_Np, 62, TranslateText('Пропановоз'), TranslateText('Бензовоз')]),
'INCL_DEBET', 'Y',
'SBOR_POST', 'N',
'SBOR_NAC', 'N',
'SBOR_NDS', 'N',
'UCH_PRICE', 'N',
'OWN_GOOD', 'N',
'USER_ID', SUPER_REAL_EMP_ID]);
end;
if p_CH_DR then
begin
DBSaver.SaveRecord('OIL_DR_DATA',
['ID', GetNextId('OIL_DR_DATA', ['REP_ID', p_Rep_id, 'REP_INST', MAIN_ORG.Inst]),
'STATE', 'Y',
'INST', MAIN_ORG.Inst,
'REP_ID', p_Rep_id,
'REP_INST', p_Rep_inst,
'OPER_TYPE', 0,
'TTN_ID', decode([Rash_id, 0, p_Rash_id, Rash_id]),
'TTN_INST', decode([Rash_id, 0, p_Rash_inst, MAIN_ORG.Inst]),
'PR_LITR', p_Litr,
'PR_UD_WEIG', p_Density,
'PR_COUNT', MRound(p_Weight, DR_ROUND_COUNT),
'S_PRICE', p_Price,
'OUT_NAL_LITR', null,
'OUT_NAL_COUNT', null,
'OUT_NAL_MONEY', null,
'OUT_VED_LITR', null,
'OUT_VED_COUNT', null,
'OUT_VED_MONEY', null,
'OUT_TALON_LITR', null,
'OUT_TALON_COUNT', null,
'OUT_TALON_MONEY', null,
'OUT_SN_LITR', null,
'OUT_SN_COUNT', null,
'OUT_SN_MONEY', null,
'OUT_RASH_ID', null,
'OUT_LITR', null,
'OUT_COUNT', null,
'OUT_MONEY', null,
'SUB_PART', p_Part_id,
'START_SM', null,
'END_SM', null
]);
end;
end;
//==============================================================================
end.
|
unit kantu_definitions;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TRealPoint = record
x,y:extended;
end;
type TRealPointArray=array of TRealPoint;
type TPointArray = array of TPoint;
type
TOrder = record
orderType : integer;
lastSignalOpenPrice : double;
openPrice : double;
closePrice : double;
volume : double;
SL : double;
TP : double;
openTime : TDateTime;
closeTime : TDateTime;
profit : double;
symbol : string;
end;
type
Tohlc = record
open : double;
high : double;
low : double;
close : double;
volume: double;
end;
type
TSymbolHistory = record
time : array of TDateTime;
OHLC : array of Tohlc;
ATR : array of double;
symbol : string;
spread : double;
contractSize : double;
timeFrame : integer;
slippage : double;
commission : double;
isVolume : boolean;
pointConversion: integer;
roundLots : integer;
MinimumStop : double;
end;
type
TCandleObject = record
rules : array of array of integer;
direction : integer;
shift : integer;
end;
type
TPricePattern = record
candles : array of TCandleObject;
SL: double;
TP: double;
hourFilter: integer;
dayFilter : integer;
timeExit : integer;
end;
type
TIndicator = record
data: array of double;
indiType: integer;
name: string;
end;
type
TIndicatorPattern = record
tradingRules: array of array of integer;
allowLongSignals: boolean;
allowShortSignals: boolean;
SL: double;
TP: double;
TL: double;
SLTSLope: double;
hourFilter: integer;
dayFilter : integer;
timeExit : integer;
end;
type TIndicatorGroup = array of TIndicator;
type TIndicatorPatternGroup = array of TIndicatorPattern;
type
TSimulationResults = record
balanceCurve : array of double;
trades : array of TOrder;
symbol : integer;
totalTrades : integer;
shortTrades : integer;
longTrades : integer;
consecutiveWins : integer;
consecutiveLoses : integer;
maximumDrawDown : double;
maximumDrawDownLength : integer;
absoluteProfit : double;
rewardToRisk : double;
winningPercent : double;
profitFactor : double;
profitToDD : double;
linearFitR2 : double;
systemQualityNumber : double;
totalYears : double;
customFilter : double;
skewness : double;
kurtosis : double;
ulcerIndex : double;
standardDeviation : double;
linearFitSlope : double;
linearFitIntercept : double;
modifiedSharpeRatio : double;
standardDeviationResiduals : double;
standardDeviationBreach : double;
startDate : TDateTime;
endDate : TDateTime;
entryPricePattern : TPricePattern;
closePricePattern : TPricePattern;
isInconsistentLogic : boolean;
end;
type
TIndicatorSimulationResults = record
balanceCurve : array of double;
trades : array of TOrder;
MFE_Longs : array of double;
MUE_Longs : array of double;
MFE_Shorts : array of double;
MUE_Shorts : array of double;
lowestLag : integer;
total_ME : double;
totalLongSignals : integer;
totalShortSignals : integer;
symbol : integer;
totalTrades : integer;
shortTrades : integer;
longTrades : integer;
consecutiveWins : integer;
consecutiveLoses : integer;
maximumDrawDown : double;
maximumDrawDownLength : integer;
absoluteProfit : double;
absoluteProfitLongs : double;
absoluteProfitShorts : double;
rewardToRisk : double;
winningPercent : double;
profitFactor : double;
profitToDD : double;
linearFitR2 : double;
systemQualityNumber : double;
totalYears : double;
customFilter : double;
skewness : double;
kurtosis : double;
ulcerIndex : double;
standardDeviation : double;
linearFitSlope : double;
linearFitIntercept : double;
modifiedSharpeRatio : double;
standardDeviationResiduals : double;
standardDeviationBreach : double;
startDate : TDateTime;
endDate : TDateTime;
entryPricePattern : TIndicatorPattern;
closePricePattern : TIndicatorPattern;
daysOut : integer;
isLastYearProfit : boolean;
idealR : double;
isInconsistentLogic : boolean;
end;
const
// order constants
NONE = 0 ;
BUY = 1 ;
SELL = 2 ;
EVAL_TYPE_ENTRY = 0;
EVAL_TYPE_EXIT = 1;
// simulation types
SIMULATION_TYPE_PRICE_PATTERN = 0;
SIMULATION_TYPE_INDICATORS = 1;
// indicator pattern
IDX_FIRST_INDICATOR = 0;
IDX_SECOND_INDICATOR = 1;
IDX_FIRST_INDICATOR_SHIFT = 2;
IDX_SECOND_INDICATOR_SHIFT = 3;
INDICATOR_RULES_TOTAL = 4;
LESS_THAN = 0;
GREATER_THAN = 1;
// price pattern
ENTRY_PATTERN = 1;
EXIT_PATTERN = 2;
DIRECTION_NORMAL = 1;
DIRECTION_REVERSE = 2;
// statistics
IDX_ABSOLUTE_PROFIT = 0;
IDX_MAX_DRAWDOWN = 1;
IDX_CONSECUTIVE_WIN = 2;
IDX_CONSECUTIVE_LOSS = 3;
IDX_AAR_TO_DD_RATIO = 4;
//rules
IDX_CHOSEN_RULE = 0;
IDX_CANDLE_TO_COMPARE = 1;
TOTAL_CANDLE_RULES = 42;
TOTAL_VOLUME_RULES = 2;
// back-testing
INITIAL_BALANCE = 100000;
ATR_PERIOD = 20;
MINIMUM_TRADE_NUMBER = 150;
LONG_ENTRY = 1;
SHORT_ENTRY = 2;
SHORT_EXIT = 3;
LONG_EXIT = 4;
// result grid
IDX_GRID_USE_IN_PORTFOLIO = 0;
IDX_GRID_RESULT_NUMBER = 1;
IDX_GRID_SYMBOL = 2;
IDX_GRID_PROFIT = 3;
IDX_GRID_PROFIT_PER_TRADE = 4;
IDX_GRID_PROFIT_LONGS = 5;
IDX_GRID_PROFIT_SHORTS = 6;
IDX_GRID_LONG_COUNT = 7;
IDX_GRID_SHORT_COUNT = 8;
IDX_GRID_TOTAL_COUNT = 9;
IDX_GRID_MAX_DRAWDOWN = 10;
IDX_GRID_IDEAL_R = 11;
IDX_GRID_LINEAR_FIT_R2 = 12;
IDX_GRID_ULCER_INDEX = 13;
IDX_GRID_MAX_DRAWDOWN_LENGTH = 14;
IDX_GRID_CONS_LOSS = 15;
IDX_GRID_CONS_WIN = 16;
IDX_GRID_PROFIT_TO_DD_RATIO = 17;
IDX_GRID_WINNING_PERCENT = 18;
IDX_GRID_REWARD_TO_RISK = 19;
IDX_GRID_SKEWNESS = 20;
IDX_GRID_KURTOSIS = 21;
IDX_GRID_PROFIT_FACTOR = 22;
IDX_GRID_STD_DEV = 23;
IDX_GRID_STD_DEV_BREACH = 24;
IDX_GRID_TOTAL_ME = 25;
IDX_GRID_SQN = 26;
IDX_GRID_MODIFIED_SHARPE_RATIO= 27;
IDX_GRID_CUSTOM_CRITERIA = 28;
IDX_GRID_DAYS_OUT = 29;
IDX_GRID_OUT_OF_SAMPLE_PROFIT = 30;
IDX_GRID_OSP_PER_TRADE = 31;
IDX_GRID_OS_PROFIT_LONGS = 32;
IDX_GRID_OS_PROFIT_SHORTS = 33;
IDX_GRID_OS_LONG_COUNT = 34;
IDX_GRID_OS_SHORT_COUNT = 35;
IDX_GRID_OS_TOTAL_COUNT = 36;
IDX_GRID_OS_MAX_DRAWDOWN = 37;
IDX_GRID_OS_ULCER_INDEX = 38;
IDX_GRID_OS_MAX_DRAWDOWN_LENGTH = 39;
IDX_GRID_OS_CONS_LOSS = 40;
IDX_GRID_OS_CONS_WIN = 41;
IDX_GRID_OS_PROFIT_TO_DD_RATIO = 42;
IDX_GRID_OS_WINNING_PERCENT = 43;
IDX_GRID_OS_REWARD_TO_RISK = 44;
IDX_GRID_OS_SKEWNESS = 45;
IDX_GRID_OS_KURTOSIS = 46;
IDX_GRID_OS_PROFIT_FACTOR = 47;
IDX_GRID_OS_STD_DEV = 48;
IDX_GRID_OS_STD_DEV_BREACH = 49;
IDX_GRID_OS_TOTAL_ME = 50;
IDX_GRID_OS_LINEAR_FIT_R2 = 51;
IDX_GRID_OS_SQN = 52;
IDX_GRID_OS_MODIFIED_SHARPE_RATIO= 53;
IDX_GRID_OS_CUSTOM_CRITERIA = 54;
IDX_GRID_OS_DAYS_OUT = 55;
IDX_GRID_LOWEST_LAG = 56;
// portfolio result grid
IDX_PGRID_PROFIT = 1;
IDX_PGRID_PROFIT_PER_TRADE = 2;
IDX_PGRID_LONG_COUNT = 3;
IDX_PGRID_SHORT_COUNT = 4;
IDX_PGRID_TOTAL_COUNT = 5;
IDX_PGRID_MAX_DRAWDOWN = 6;
IDX_PGRID_MAX_DRAWDOWN_LENGTH = 7;
IDX_PGRID_CONS_LOSS = 8;
IDX_PGRID_CONS_WIN = 9;
IDX_PGRID_PROFIT_TO_DD_RATIO = 10;
IDX_PGRID_WINNING_PERCENT = 11;
IDX_PGRID_REWARD_TO_RISK = 12;
IDX_PGRID_SKEWNESS = 13;
IDX_PGRID_KURTOSIS = 14;
IDX_PGRID_PROFIT_FACTOR = 15;
IDX_PGRID_LINEAR_FIT_R2 = 16;
IDX_PGRID_SQN = 17;
IDX_PGRID_ULCER_INDEX = 18;
IDX_PGRID_STD_DEV = 19;
IDX_PGRID_MODIFIED_SHARPE_RATIO= 20;
//options grid
IDX_OPT_MAX_RULES_PER_CANDLE =1;
IDX_OPT_MAX_CANDLE_SHIFT =2;
IDX_OPT_SHIFT_STEP =3;
IDX_OPT_FIXED_SL =4;
IDX_OPT_FIXED_TP =5;
IDX_OPT_FIXED_TL =6;
IDX_OPT_FIXED_HOUR =7;
IDX_OPT_SLTPTL_STEP =8;
IDX_OPT_MAX_SLTPTL =9;
IDX_OPT_NO_OF_CORES =10;
IDX_OPT_BARS_ME =11;
IDX_OPT_REQUESTED_SYSTEMS =12;
// filters grid
IDX_FILTER_TRADES = 1;
IDX_FILTER_RISK_TO_REWARD = 2;
IDX_FILTER_WINNING_PERCENT = 3;
IDX_FILTER_PROFIT = 4;
IDX_FILTER_PROFIT_TO_DD = 5;
IDX_FILTER_DD = 6;
IDX_FILTER_DD_LENGTH = 7;
IDX_FILTER_PROFIT_FACTOR = 8;
IDX_FILTER_IDEAL_R = 9;
IDX_FILTER_LINEAR_FIT_R2 = 10;
IDX_FILTER_SQN = 11;
IDX_FILTER_CUSTOM = 12;
IDX_FILTER_SKEWNESS = 13;
IDX_FILTER_KURTOSIS = 14;
IDX_FILTER_ULCER_INDEX = 15;
IDX_FILTER_STD_DEV = 16;
IDX_FILTER_MODIFIED_SHARPE_RATIO = 17;
IDX_FILTER_STD_DEV_BREACH = 18;
IDX_FILTER_TOTAL_ME = 19;
TRADES_FOR_IR_CALCULATION = 20;
// genetics
TOP_PERFORMERS_SAVED = 5;
// symbol selection
FIRST_SYMBOL = 0;
// program version
KANTU_VERSION = '2.40';
implementation
end.
|
unit Queue;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, JvExControls, JvSpeedButton, ExtCtrls, ComCtrls, Menus, Addmap;
type
TfrmQueue = class(TForm)
lvQueue: TListView;
pnl1: TPanel;
btnRemove: TJvSpeedButton;
btnAddNew: TJvSpeedButton;
btnProced: TJvSpeedButton;
pmAdd: TPopupMenu;
MenuItem1: TMenuItem;
MenuItem2: TMenuItem;
procedure btnProcedClick(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
procedure AddWorkshopMapClick(Sender: TObject);
procedure MenuItem2Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lvQueueCustomDrawItem(Sender: TCustomListView; Item: TListItem;
State: TCustomDrawState; var DefaultDraw: Boolean);
procedure lvQueueClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lvQueueChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
private
{ Private declarations }
public
var
addType: TAddType
{ Public declarations }
end;
var
frmQueue: TfrmQueue;
implementation
{$R *.dfm}
uses
Main, UFuncoes, Workshop;
procedure TfrmQueue.AddWorkshopMapClick(Sender: TObject);
var
frmAdd: TFormAdd;
mdResult: Integer;
itemID, lgAddWkspItem, lgWkspIdUrl, lgInvalidUrlID, inputText: string;
Item: TListItem;
isMod: Boolean;
begin
frmAdd := TFormAdd.Create(Self);
mdResult := mrNone;
try
if FormMain.appLanguage = 'BR' then
begin
lgAddWkspItem := 'Adicionar item da Workshop';
lgWkspIdUrl := 'ID ou URL da Workshop:';
lgInvalidUrlID := 'ID/URL inválidos';
end
else
begin
lgAddWkspItem := 'Add Workshop item';
lgWkspIdUrl := 'Workshop ID or URL:';
lgInvalidUrlID := 'Invalid ID/URL';
end;
if InputQuery(lgAddWkspItem, lgWkspIdUrl, inputText) then
begin
if Length(inputText) <= 11 then
begin
itemID := cleanInt(inputText)
end
else
begin
itemID := WorkshopURLtoID(inputText);
end;
if Length(itemID) > 4 then
begin
frmAdd.edtID.Text := itemID;
frmAdd.SetAddType(addType);
mdResult := frmAdd.ShowModal;
if mdResult = mrOk then
begin
Item := lvQueue.Items.Add;
Item.Caption := frmAdd.itemID;
Item.SubItems.Add(BoolToWord(frmAdd.addWkspRedirect));
isMod := addType = EditWorkshopItem;
if isMod then
begin
Item.SubItems.Add(BoolToWord(False));
Item.SubItems.Add(BoolToWord(False));
end
else
begin
Item.SubItems.Add(BoolToWord(frmAdd.addMapENtry));
Item.SubItems.Add(BoolToWord(frmAdd.addMapCycle));
end;
Item.SubItems.Add(BoolToWord(frmAdd.downloadNow));
if FormMain.appLanguage = 'BR' then
Item.SubItems.Add('Pendente')
else
Item.SubItems.Add('Pending');
end;
end
else
begin
ShowMessage('Invalid ID/URL');
end;
end;
finally
frmAdd.Free;
end;
end;
procedure TfrmQueue.btnProcedClick(Sender: TObject);
var
ItemName: string;
itemID: string;
slItems, i: Integer;
itemsDone: Integer;
modalResult: Integer;
addWkspRedirect, downloadNow, addMapCycle, addMapENtry: Boolean;
begin
if lvQueue.Items.Count < 0 then
begin
ShowMessage('You need add some items to download');
Exit;
end
else
begin
slItems := FormMain.getSelectedCount(lvQueue);
itemsDone := 0;
modalResult := mrNone;
try
for i := 0 to lvQueue.Items.Count - 1 do
begin
// For more than one item
ItemName := '';
itemID := lvQueue.Items[i].Caption;
addWkspRedirect := UpperCase(lvQueue.Items[i].SubItems[0]) = 'TRUE';
addMapENtry := UpperCase(lvQueue.Items[i].SubItems[1]) = 'TRUE';
addMapCycle := UpperCase(lvQueue.Items[i].SubItems[2]) = 'TRUE';
downloadNow := UpperCase(lvQueue.Items[i].SubItems[3]) = 'TRUE';
lvQueue.Items[i].SubItems[4] := 'Working';
try
if FormMain.kfItems.NewItem(itemID, ItemName, addWkspRedirect,
downloadNow, addMapCycle, addMapENtry) then
begin
lvQueue.Items[i].SubItems[4] := 'Sucess';
end
else
begin
lvQueue.Items[i].SubItems[4] := 'Falied';
end;
except
lvQueue.Items[i].SubItems[4] := 'Falied';
end;
end;
ShowMessage('All items finished');
except
on E: Exception do
ShowMessage(E.Message);
end;
end;
end;
procedure TfrmQueue.btnRemoveClick(Sender: TObject);
var
i: Integer;
slCount: Integer;
begin
slCount := FormMain.getSelectedCount(lvQueue);
if lvQueue.Selected = nil then
begin
ShowMessage('Select na item first.');
Exit;
end
else
begin
lvQueue.Update;
for i := 0 to lvQueue.Items.Count - 1 do
begin
if lvQueue.Items[i].Selected then
lvQueue.Items[i].Delete;
end;
lvQueue.Update;
btnProced.Enabled := lvQueue.Items.Count > 0;
end;
end;
procedure TfrmQueue.FormCreate(Sender: TObject);
begin
btnRemove.Enabled := False;
btnProced.Enabled := False;
if FormMain.appLanguage = 'BR' then
begin
btnRemove.Caption := 'Remover';
btnAddNew.Caption := 'Adicionar';
btnProced.Caption := 'Proceder';
lvQueue.Columns[1].Caption := 'Ad. inscrição';
lvQueue.Columns[2].Caption := 'Ad. entrada do mapa';
lvQueue.Columns[3].Caption := 'Ad. ao ciclo de mapas';
lvQueue.Columns[4].Caption := 'Baixar agora';
MenuItem1.Caption := 'ID/URL da workshop';
MenuItem2.Caption := 'Procurar na workshop';
end;
end;
procedure TfrmQueue.FormShow(Sender: TObject);
begin
if addType = EditWorkshopMap then
begin
end;
if addType = EditWorkshopItem then
begin
lvQueue.Columns[2].Width := 0;
lvQueue.Columns[3].Width := 0;
lvQueue.Columns[2].MaxWidth := 1;
lvQueue.Columns[3].MaxWidth := 1;
lvQueue.Columns[2].Caption := '';
lvQueue.Columns[3].Caption := '';
end;
end;
procedure TfrmQueue.lvQueueChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
btnProced.Enabled := lvQueue.Items.Count > 0;
end;
procedure TfrmQueue.lvQueueClick(Sender: TObject);
begin
if lvQueue.Selected <> nil then
begin
btnRemove.Enabled := True;
end
else
begin
btnRemove.Enabled := False;
end;
end;
procedure TfrmQueue.lvQueueCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
begin
with lvQueue.Canvas.Brush do
begin
if (Item.Index mod 2) = 0 then
Color := clInactiveBorder
else
Color := clWhite;
end;
end;
procedure TfrmQueue.MenuItem2Click(Sender: TObject);
var
frmAdd: TFormAdd;
frmWksp: TFormWorkshop;
textToFind: string;
itemID: string;
isMod: Boolean;
lgFindAItemWksp, lgSearchFor: string;
mdResult: Integer;
Item: TListItem;
begin
mdResult := mrNone;
if FormMain.appLanguage = 'BR' then
begin
lgFindAItemWksp := 'Buscar na workshop';
lgSearchFor := 'Buscar por';
end
else
begin
lgFindAItemWksp := 'Find a item in workshop';
lgSearchFor := 'Search for';
end;
if InputQuery(lgFindAItemWksp, lgSearchFor, textToFind) then
begin
frmWksp := TFormWorkshop.Create(Self);
try
isMod := addType = EditWorkshopItem;
if isMod then
itemID := frmWksp.BrowserItem(TWkspType.WorkshopMod, textToFind)
else
itemID := frmWksp.BrowserItem(TWkspType.WorkshopMap, textToFind);
if itemID <> '' then
begin
frmAdd := TFormAdd.Create(Self);
try
if isMod then
begin
frmAdd.SetAddType(TAddType.EditWorkshopItem);
end
else
begin
frmAdd.SetAddType(TAddType.EditWorkshopMap);
end;
frmAdd.edtID.Text := itemID;
mdResult := frmAdd.ShowModal;
if mdResult = mrOk then
begin
Item := lvQueue.Items.Add;
Item.Caption := frmAdd.itemID;
Item.SubItems.Add(BoolToWord(frmAdd.addWkspRedirect));
if isMod then
begin
Item.SubItems.Add(BoolToWord(False));
Item.SubItems.Add(BoolToWord(False));
end
else
begin
Item.SubItems.Add(BoolToWord(frmAdd.addMapENtry));
Item.SubItems.Add(BoolToWord(frmAdd.addMapCycle));
end;
Item.SubItems.Add(BoolToWord(frmAdd.downloadNow));
if FormMain.appLanguage = 'BR' then
Item.SubItems.Add('Pendente')
else
Item.SubItems.Add('Pending');
end;
finally
frmAdd.Free;
end;
end;
finally
frmWksp.Free;
end;
end;
end;
end.
|
unit trl_irttibroker;
{$mode objfpc}{$H+}
interface
uses
TypInfo, Classes;
type
{.$interfaces corba}
{ IRBDataItem }
IRBDataItem = interface
['{30206B79-2DC2-4A3C-AD96-70B9617EDD69}']
function GetName: string;
function GetClassName: string;
function GetIsObject: Boolean;
function GetIsMemo: Boolean;
function GetIsID: Boolean;
function GetIsInterface: Boolean;
function GetTypeKind: TTypeKind;
function GetAsPersist: string;
procedure SetAsPersist(AValue: string);
function GetAsInteger: integer;
function GetAsString: string;
function GetAsBoolean: Boolean;
procedure SetAsInteger(AValue: integer);
procedure SetAsString(AValue: string);
procedure SetAsBoolean(AValue: Boolean);
function GetAsObject: TObject;
procedure SetAsObject(AValue: TObject);
function GetAsVariant: Variant;
procedure SetAsVariant(AValue: Variant);
function GetAsClass: TClass;
function GetEnumName(AValue: integer): string;
function GetEnumNameCount: integer;
function GetAsPtrInt: PtrInt;
procedure SetAsPtrInt(AValue: PtrInt);
function GetAsInterface: IUnknown;
procedure SetAsInterface(AValue: IUnknown);
property Name: string read GetName;
property ClassName: string read GetClassName;
property IsObject: Boolean read GetIsObject;
property IsMemo: Boolean read GetIsMemo;
property IsID: Boolean read GetIsID;
property IsInterface: Boolean read GetIsInterface;
property TypeKind: TTypeKind read GetTypeKind;
property AsPersist: string read GetAsPersist write SetAsPersist;
property AsString: string read GetAsString write SetAsString;
property AsInteger: integer read GetAsInteger write SetAsInteger;
property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean;
property AsObject: TObject read GetAsObject write SetAsObject;
property AsVariant: variant read GetAsVariant write SetAsVariant;
property AsClass: TClass read GetAsClass;
property EnumNameCount: integer read GetEnumNameCount;
property EnumName[AValue: integer]: string read GetEnumName;
property AsPtrInt: PtrInt read GetAsPtrInt write SetAsPtrInt;
property AsInterface: IUnknown read GetAsInterface write SetAsInterface;
end;
{ IRBData }
IRBData = interface
['{2B5DE8F9-F2FA-4E5A-A0F4-15C87BFB0551}']
function GetClassName: string;
function GetClassType: TClass;
function GetCount: integer;
function GetItemByName(const AName: string): IRBDataItem;
function GetItemIndex(const AName: string): integer;
function GetItems(AIndex: integer): IRBDataItem;
function FindItem(const AName: string): IRBDataItem;
function GetUnderObject: TObject;
procedure SetUnderObject(AValue: TObject);
procedure Assign(const AData: IRBData);
property Count: integer read GetCount;
property ClassName: string read GetClassName;
property ClassType: TClass read GetClassType;
property Items[AIndex: integer]: IRBDataItem read GetItems; default;
property ItemByName[const AName: string]: IRBDataItem read GetItemByName;
property ItemIndex[const AName: string]: integer read GetItemIndex;
property UnderObject: TObject read GetUnderObject write SetUnderObject;
end;
implementation
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit uJavaClassImport;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
uCodeParser, uModel, uIntegrator, uModelEntity, uJavaClass, uError;
type
TJavaClassImporter = class(TImportIntegrator)
private
function NeedPackageHandler(const AName: string; var AStream: TStream; OnlyLookUp: Boolean = False):String;
public
procedure ImportOneFile(const FileName : string); override;
class function GetFileExtensions : TStringList; override;
end;
implementation
type
TJavaClassParser = class(TCodeParser)
private
OM : TObjectModel;
function GetVisibility(flags : integer) : TVisibility;
function ExtractPackageName(CName : string) : string;
function ExtractClassName(CName : string) : string;
function GetFieldType(const Field : string; var Index : integer) : TClassifier;
function NeedClassifier(CName : string; TheClass : TModelEntityClass = nil) : TClassifier;
public
procedure ParseStream(AStream: TStream; AModel: TAbstractPackage; AOM: TObjectModel); override;
end;
{ TJavaClassImporter }
procedure TJavaClassImporter.ImportOneFile(const FileName : string);
var
Str : TStream;
Parser : TJavaClassParser;
begin
Str := CodeProvider.LoadStream(FileName);
if Assigned(Str) then
begin
Parser := TJavaClassParser.Create;
try
Parser.NeedPackage := @NeedPackageHandler;
Parser.ParseStream(Str, Model.ModelRoot, Model);
finally
Parser.Free;
end;
end;
end;
function TJavaClassImporter.NeedPackageHandler(const AName: string; var AStream: TStream; OnlyLookUp: Boolean = False):String;
var
FileName : string;
begin
AStream := nil;
FileName := AName + '.class';
FileName := CodeProvider.LocateFile(FileName);
Result := FileName;
//Dont read same file twice
if (not OnlyLookUp) and (FileName<>'') and (FilesRead.IndexOf(FileName)=-1) then
begin
AStream := CodeProvider.LoadStream(FileName);
FilesRead.Add(FileName);
end;
end;
class function TJavaClassImporter.GetFileExtensions: TStringList;
begin
Result := TStringList.Create;
Result.Values['.class'] := 'Java Class';
end;
{ TJavaClassParser }
procedure TJavaClassParser.ParseStream(AStream: TStream; AModel: TAbstractPackage; AOM: TObjectModel);
var
JC : TClassFile;
U : TUnitPackage;
C : TClass;
Int : TInterface;
I : integer;
PName,S : string;
procedure ParseOp(Op : TOperation; Met : TMethodInfo);
var
Desc : string;
I,J : integer;
begin
Op.Visibility := GetVisibility(Met.access_flags);
Op.IsAbstract := TAccData.isAbstract(Met.access_flags);
Desc := Met.descriptor.GetString;
I := 1;
if Desc[I]='(' then
begin
//parameters
J := 0;
Inc(I);
while (Desc[I]<>')') and (I<Length(Desc)) do
Op.AddParameter( char( Ord('a') + J ) ).TypeClassifier := GetFieldType(Desc,I);
Inc(I);
end;
if Desc[I]<>'V' then
Op.ReturnValue := GetFieldType(Desc,I);
if Met.isConstructor then
begin
Op.OperationType := otConstructor;
Op.Name := C.Name;
end else if Assigned(Op.ReturnValue) then
Op.OperationType := otFunction
else
Op.OperationType := otProcedure
end;
procedure ParseAttr(Attr : TAttribute; Fi : TFieldInfo);
var
I : integer;
begin
Attr.Visibility := GetVisibility(Fi.access_flags);
I := 1;
Attr.TypeClassifier := GetFieldType(Fi.descriptor.getString,I);
end;
begin
FModel := AModel;
OM := AOM;
JC := TClassFile.Create(AStream);
try
PName := ExtractPackageName( JC.clsName );
U := OM.ModelRoot.FindUnitPackage(PName);
if not Assigned(U) then
U := (FModel as TLogicPackage).AddUnit( PName );
if TAccData.isInterface( JC.classDecl.accessFlags ) then
begin
//interface
Int := U.AddInterface( ExtractClassName(JC.clsName) );
Int.Visibility := GetVisibility( JC.classDecl.accessFlags );
for I:=0 to Length(JC.classFields.classFields)-1 do
begin
S := JC.classFields.classFields[I].name.GetString;
if (Length(S)>0) and (S[1]<>'$') then
ParseAttr( Int.AddAttribute( S ),JC.classFields.classFields[I] );
end;
for I:=0 to Length(JC.classMethods.classMethods)-1 do
begin
S := JC.classMethods.classMethods[I].name.GetString;
if (Length(S)>0) and (not (S[1] in ['<','$'])) then
ParseOp( Int.AddOperation( S ) ,JC.classMethods.classMethods[I]);
end;
end
else
begin
//class
C := U.AddClass( ExtractClassName(JC.clsName) );
//ancestor
if Assigned(JC.classDecl.superClass) then
begin
S := TObjNameFormat.ToDotSeparator(JC.classDecl.superClass.getString);
if S<>'java.lang.Object' then
C.Ancestor := NeedClassifier( S , TClass) as TClass;
end;
//implements
for I := 0 to Length(JC.classDecl.interfaces)-1 do
C.AddImplements( NeedClassifier( TObjNameFormat.toDotSeparator(JC.classDecl.interfaces[I].getString), TInterface ) as TInterface);
C.Visibility := GetVisibility( JC.classDecl.accessFlags );
for I:=0 to Length(JC.classFields.classFields)-1 do
begin
S := JC.classFields.classFields[I].name.GetString;
if (Length(S)>0) and (S[1]<>'$') then
ParseAttr( C.AddAttribute( S ),JC.classFields.classFields[I] );
end;
for I:=0 to Length(JC.classMethods.classMethods)-1 do
begin
S := JC.classMethods.classMethods[I].name.GetString;
if S='<init>' then //Constructor has internal name '<init>'
S := C.Name;
if (Length(S)>0) and (not (S[1] in ['<','$'])) then
ParseOp( C.AddOperation( S ) ,JC.classMethods.classMethods[I]);
end;
end;
finally
JC.Free;
end;
end;
//Translate java-visibility
function TJavaClassParser.GetVisibility(flags: integer): TVisibility;
begin
Result := viPrivate;
if TAccData.isPublic( flags ) then
Result := viPublic
else if TAccData.isPrivate( flags ) then
Result := viPrivate
else if TAccData.isProtected( flags ) then
Result := viProtected;
end;
function TJavaClassParser.ExtractPackageName(CName: string): string;
var
I : integer;
begin
I := LastDelimiter('.',CName);
if I=0 then
Result := 'Default'
else
Result := Copy(CName,1,I-1);
end;
//Extract short class name
function TJavaClassParser.ExtractClassName(CName: string): string;
var
I : integer;
begin
I := LastDelimiter('.',CName);
if I=0 then
Result := CName
else
Result := Copy(CName,I+1,255);
end;
function TJavaClassParser.NeedClassifier(CName: string; TheClass : TModelEntityClass = nil): TClassifier;
var
PName,ShortName : string;
U : TUnitPackage;
Parser : TJavaClassParser;
Str : TStream;
begin
Result := nil;
PName := ExtractPackageName(CName);
ShortName := ExtractClassName(CName);
//First look in model
U := OM.ModelRoot.FindUnitPackage(PName);
if Assigned(U) then
Result := U.FindClassifier(ShortName,False,TheClass,True);
if not Assigned(Result) then
begin
//See if we can find the file that we need
Str := nil;
if Assigned(NeedPackage) then
NeedPackage( ShortName ,str);
if Assigned(Str) then
begin
Parser := TJavaClassParser.Create;
try
Parser.NeedPackage := NeedPackage;
Parser.ParseStream(Str, OM.ModelRoot, OM);
finally
Parser.Free;
end;
U := OM.ModelRoot.FindUnitPackage(PName);
if Assigned(U) then
Result := U.FindClassifier(ShortName,False,TheClass,True);
end;
end;
if not Assigned(Result) then
begin
//Look in unknown package
Result := OM.UnknownPackage.FindClassifier(CName,False,TheClass,True);
if not Assigned(Result) then
begin
if (TheClass=nil) or (TheClass=TClass) then
Result := OM.UnknownPackage.AddClass(CName)
else if TheClass=TInterface then
Result := OM.UnknownPackage.AddInterface(CName)
else if TheClass=TDataType then
Result := OM.UnknownPackage.AddDataType(CName)
end;
end;
if not Assigned(Result) then
raise Exception.Create(ClassName + ' failed to locate ' + Cname);
end;
function TJavaClassParser.GetFieldType(const Field: string; var Index: integer): TClassifier;
var
DimCount,I : integer;
S : string;
IsPrimitive : boolean;
begin
Result := nil;
DimCount := 0;
while Field[Index]='[' do
begin
Inc(DimCount);
Inc(Index);
end;
IsPrimitive := True;
case Field[Index] of
'B' : S := 'byte';
'C' : S := 'char';
'D' : S := 'double';
'F' : S := 'float';
'I' : S := 'int';
'J' : S := 'long';
'L' :
begin
Inc(Index);
I := Index;
while (Field[I]<>';') and (I<Length(Field)) do
Inc(I);
S := TObjNameFormat.toDotSeparator( Copy(Field,Index,I-Index) );
Index := I;
IsPrimitive := False;
end;
'S' : S := 'short';
'Z' : S := 'boolean';
end;
Inc(Index);
for I := 0 to DimCount-1 do
S := S + '[]';
if S='' then
ErrorHandler.Trace(ClassName + ' getfieldtype: ' + Field)
else
begin
if IsPrimitive then
Result := NeedClassifier( S , TDataType)
else
Result := NeedClassifier( S );
end;
end;
initialization
Integrators.Register(TJavaClassImporter);
end.
|
unit UEngineArchives;
(*====================================================================
Functions for reading various types of archive files. The Scan... functions
read the archive and put the files to a unified collection of TOneArc items,
which is then given to the Engine to dispatch to tree.
======================================================================*)
{$A-}
interface
uses UTypes, UCollections, UStream, UApiTypes, UBaseTypes;
type
TQSearchRec = record
Time: Integer;
Size: Integer;
Attr: Integer;
Name: ShortString;
end;
POneArcItem = ^TOneArcItem;
TOneArcItem = object(TQObject)
Attr : Byte;
Time : Longint;
Size : Longint;
Name : TPQString;
Dir : TPQString;
OffsetInArc: longint;
constructor Init (aDir: ShortString; aName: ShortString;
aSize, aTime: longint; aAttr: byte;
aOffsetInArc: longint);
destructor Done; virtual;
end;
PArcCollection = ^TArcCollection;
TArcCollection = object(TQSortedCollection)
constructor Init (ALimit, ADelta: Integer);
function Compare(Key1, Key2: Pointer): Integer; virtual;
end;
function ScanZipFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
function ScanARCFile (Col: PArcCollection; WholeFileSpec: ShortString): boolean;
function ScanBAKFile (Col: PArcCollection; WholeFileSpec: ShortString): boolean;
function ScanPCBFile (Col: PArcCollection; WholeFileSpec: ShortString; CPB: boolean): boolean;
function ScanNBFile (Col: PArcCollection; WholeFileSpec: ShortString): boolean;
function ScanARJFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
function ScanLHArcFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
function ScanRARFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
function ScanACEFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
function ScanAR6File (Col: PArcCollection; WholeFileSpec: ShortString): boolean;
function ScanExeFile (Col: PArcCollection; WholeFileSpec: ShortString;
ScanAlsoNonZipArchives: boolean; var ArchiveType: TArchiveType): boolean;
implementation
uses
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
SysUtils, UCallbacks, UBaseUtils, ULang, UExceptions,
UUnRar, UUnAce;
const
labZjistujiObsah = lsExploringContent;
labPCBHlavaNenalezena = lsCentralDirCPBNotFound;
//=== TOneArcItem =============================================================
constructor TOneArcItem.Init (aDir: ShortString; aName: ShortString;
aSize, aTime: longint; aAttr: byte;
aOffsetInArc: longint);
var TmpSt: ShortString;
begin
inherited Init;
TmpSt := AnsiUpperCase(aDir);
if (TmpSt = aDir) then aDir := AnsiLowerCase(aDir);
Dir := QNewStr('\' + aDir); // the backslash is added so that the string is never nil
if aName = '' then aName := ' '; // avoid nil
TmpSt := AnsiUpperCase(aName);
if (TmpSt = aName) then aName := AnsiLowerCase(aName);
Name := QNewStr(aName);
Size := aSize;
Time := aTime;
Attr := aAttr;
OffsetInArc := aOffsetInArc;
end;
//-----------------------------------------------------------------------------
destructor TOneArcItem.Done;
begin
QDisposeStr(Dir);
QDisposeStr(Name);
inherited Done;
end;
//=== TArcCollection ==========================================================
constructor TArcCollection.Init (ALimit, ADelta: Integer);
begin
inherited Init (ALimit, ADelta);
Duplicates := true;
end;
//-----------------------------------------------------------------------------
function TArcCollection.Compare (Key1, Key2: Pointer): Integer;
begin
if GetPQString(POneArcItem(Key1)^.Dir) > GetPQString(POneArcItem(Key2)^.Dir)
then Compare := 1
else
if GetPQString(POneArcItem(Key1)^.Dir) < GetPQString(POneArcItem(Key2)^.Dir)
then Compare := -1
else
if GetPQString(POneArcItem(Key1)^.Name) > GetPQString(POneArcItem(Key2)^.Name)
then Compare := 1
else
if GetPQString(POneArcItem(Key1)^.Name) < GetPQString(POneArcItem(Key2)^.Name)
then Compare := -1
else Compare := 0;
end;
//=============================================================================
// Scans AR6 files - created by Manager602
function ScanAR6File (Col: PArcCollection; WholeFileSpec: ShortString): boolean;
type
AR6HeaderType = record
AR : array [1..3] of char;
Rest: array [1..15] of char;
end;
AR6RawType = record
rHeaderFlag : array[1..6] of char;
rCompVersion : word;
rDateTime : longint;
rCRC : longint;
rCompSize : LongWord;
rSize : LongWord;
rNameLength : word;
rExtraLength : word;
end;
var
AR6File : TQBufStream;
AR6EOFStatus : boolean;
AR6Header : AR6HeaderType;
AR6Raw : AR6RawType;
FPath : ShortString;
LongName : ShortString;
function GetFirstFile: boolean;
type
Buffer = array[1..256] of char;
var
Buf : ^Buffer;
QResult : longword;
LastSlash : byte;
TmpPath : ShortString;
i : byte;
begin
GetFirstFile := false;
AR6File.ReadExt(AR6Raw, SizeOf(AR6Raw), QResult);
if QResult <> SizeOf(AR6Raw) then exit;
if AR6Raw.rHeaderFlag <> 'AR6'#1'd'#0 then exit;
{'AR6'#2'd'#0 - is by central dir struct}
with AR6Raw do
begin
GetMem(Buf,rNameLength);
AR6File.ReadExt(Buf^, rNameLength, QResult);
if rNameLength > 255 then
begin
Move(Buf^[rNameLength-255+1], Buf^[1], 255);
rNameLength := 255;
end;
LongName[0] := char(rNameLength);
move(Buf^[1], LongName[1], rNameLength);
FreeMem(Buf,rNameLength);
if QResult <> rNameLength then exit;
if rExtraLength > 0 then
begin
GetMem(Buf,rExtraLength);
AR6File.ReadExt(Buf^, rExtraLength, QResult);
FreeMem(Buf,rExtraLength);
if QResult <> rExtraLength then exit;
end;
end;
GetFirstFile := true;
with AR6Raw do
begin
LastSlash := 0;
for i := 1 to length(LongName) do
begin
if LongName[i] = '/' then LongName[i] := '\';
if LongName[i] = '\' then LastSlash := i;
end;
if LastSlash <> 0
then
begin
TmpPath := ShortCopy(LongName, 1, LastSlash);
ShortDelete (LongName, 1, LastSlash);
end
else
TmpPath := '';
if TmpPath <> FPath then FPath := TmpPath;
end;
end;
function GetNextFile: boolean;
var
FPos : LongWord;
begin
GetNextFile := true;
FPos := AR6File.GetPos + AR6Raw.rCompSize;
if FPos < AR6File.GetSize
then
begin
AR6File.Seek(FPos);
if not GetFirstFile then
begin
GetNextFile := false;
AR6EofStatus := true;
end;
end
else
begin
AR6EofStatus := true;
GetNextFile := false;
end;
end;
var
QResult : longword;
TmpStrArr: array[0..256] of char;
begin
try
Result := false;
AR6EofStatus := False;
FPath := '';
{--- opening ---}
AR6File.Init(StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
AR6File.ReadExt(AR6Header, SizeOf(AR6Header), QResult);
if AR6Header.AR <> 'AR6' then
begin
AR6File.Done;
exit;
end;
CB_NewLineToIndicator(labZjistujiObsah + WholeFileSpec);
if not GetFirstFile then
begin
AR6File.Done;
exit;
end;
while not AR6EofStatus do
begin
with AR6Raw do
begin
LongName := TrimSpaces(LongName);
Col^.Insert(New (POneArcItem, Init(FPath, LongName, rSize, rDateTime, 0, 0)));
Result := true;
end;
GetNextFile; // if not successful, set AR6EofStatus to true
end;
AR6File.Done;
except
on EQDirException do
Result := false;
end;
end;
//=============================================================================
// Scans ZIP file, not using the central directory at the end
function SlowScanZipFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
type
ZIPLocHeadType = record
rHeaderFlag : array[1..4] of char;
rVersionNeeded : word;
rGenPurposeFlag : word;
rCompVersion : word;
rDateTime : longint;
rCRC : longint;
rCompSize : LongWord;
rSize : LongWord;
rNameLength : word;
rExtraLength : word;
end;
ZIPCenHeadType = record
rHeaderFlag : array[1..4] of char;
rVersionMadeBy : word;
rVersionNeeded : word;
rGenPurposeFlag : word;
rCompVersion : word;
rDateTime : longint;
rCRC : longint;
rCompSize : LongWord;
rSize : LongWord;
rNameLength : word;
rExtraLength : word;
rCommentLength : word;
rDiskNumStart : word;
rIntFileAttr : word;
rExtFileAttr : longint;
rRelOfsLocHead : LongWord;
end;
ZIPEndHeadType = record
rHeaderFlag : array[1..4] of char;
rNumOfThisDisk : word;
rNumOfStartDisk : word; // number of disk with the start of central dir
// must be equal to rNumOfThisDisk
rEntrInThisDir : word;
rEntrInWholeDir : word;
rSizeOfCentralDir: LongWord;
rCenDirOfs : LongWord;
rZipCommentLen : word;
end;
var
ZIPFile : TQBufStream;
ZIPEOFStatus : boolean;
ZIPLocHead : ZIPLocHeadType;
LongName : ShortString;
FPath : ShortString;
LocHeadOffset : longint;
function GetFirstFile (First: boolean): boolean;
type
Buffer = array[1..256] of char;
var
Buf : ^Buffer;
QResult : longword;
LastSlash : byte;
TmpPath : ShortString;
i : byte;
begin
GetFirstFile := false;
ZIPFile.ReadExt(ZIPLocHead, SizeOf(ZIPLocHead), QResult);
if QResult <> SizeOf(ZIPLocHead) then exit;
if ZIPLocHead.rHeaderFlag <> 'PK'#3#4 then exit;
LocHeadOffset := ZIPFile.GetPos - SizeOf(ZIPLocHead);
with ZIPLocHead do
begin
GetMem(Buf,rNameLength);
ZIPFile.ReadExt(Buf^, rNameLength, QResult);
if rNameLength > 255 then
begin
Move(Buf^[rNameLength-255+1], Buf^[1], 255);
rNameLength := 255;
end;
LongName[0] := char(rNameLength);
move(Buf^[1], LongName[1], rNameLength);
FreeMem(Buf,rNameLength);
if QResult <> rNameLength then exit;
///OemToCharBuff(@LongName[1], @LongName[1], rNameLength);
if rExtraLength > 0 then
begin
GetMem(Buf,rExtraLength);
ZIPFile.ReadExt(Buf^, rExtraLength, QResult);
FreeMem(Buf,rExtraLength);
if QResult <> rExtraLength then exit;
end;
end;
GetFirstFile := true;
with ZIPLocHead do
begin
LastSlash := 0;
for i := 1 to length(LongName) do
begin
if LongName[i] = '/' then LongName[i] := '\';
if LongName[i] = '\' then LastSlash := i;
end;
if LastSlash <> 0
then
begin
TmpPath := ShortCopy(LongName, 1, LastSlash);
ShortDelete (LongName, 1, LastSlash);
end
else
TmpPath := '';
if TmpPath <> FPath then FPath := TmpPath;
end;
end;
function GetNextFile: boolean;
var
FPos : LongWord;
begin
GetNextFile := true;
FPos := ZIPFIle.GetPos + ZIPLocHead.rCompSize;
if FPos < ZIPFile.GetSize
then
begin
ZIPFile.Seek(FPos);
if not GetFirstFile(false) then
begin
GetNextFile := false;
ZIPEofStatus := true;
end;
end
else
begin
ZIPEofStatus := true;
GetNextFile := false;
end;
end;
var
TmpStrArr : array[0..256] of char;
begin
try
Result := false;
LocHeadOffset := 0;
ZIPEofStatus := False;
FPath := '';
{--- opening ---}
CB_NewLineToIndicator(labZjistujiObsah + WholeFileSpec);
ZIPFile.Init(StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
if StartOffset > 0 then ZIPFile.Seek(StartOffset);
if not GetFirstFile(true) then
begin
ZIPFile.Done;
exit;
end;
while not ZIPEofStatus do
begin
with ZIPLocHead do
begin
LongName := TrimSpaces(LongName);
if LongName <> '' then
Col^.Insert(New (POneArcItem, Init(FPath, LongName, rSize, rDateTime,
0, LocHeadOffset)));
Result := true;
end;
GetNextFile; // if unsuccessful, sets ZIPEofStatus to true
end;
ZIPFile.Done;
except
on EQDirException do
Result := false;
end;
end;
//-----------------------------------------------------------------------------
// Scans ZIP file, using the central directory at the end
function ScanZipFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
type
rHeaderFlag = array[1..4] of char;
ZIPLocHeadType = record
rVersionNeeded : word;
rGenPurposeFlag : word;
rCompVersion : word;
rDateTime : longint;
rCRC : longint;
rCompSize : longint;
rSize : longint;
rNameLength : word;
rExtraLength : word;
end;
ZIPCenHeadType = record
rVersionMadeBy : word;
rVersionNeeded : word;
rGenPurposeFlag : word;
rCompVersion : word;
rDateTime : longint;
rCRC : longint;
rCompSize : longint;
rSize : longint;
rNameLength : word;
rExtraLength : word;
rCommentLength : word;
rDiskNumStart : word;
rIntFileAttr : word;
rExtFileAttr : longint;
rRelOfsLocHead : longint;
end;
ZIPEndHeadType = record
rNumOfThisDisk : word;
rNumOfStartDisk : word;
rEntrInThisDir : word;
rEntrInWholeDir : word;
rSizeOfCentralDir: longint;
rCenDirOfs : longint;
rZipCommentLen : word;
end;
var
ZIPFile : TQBufStream;
ZIPEOFStatus : boolean;
ZIPCenHead : ZIPCenHeadType;
LongName : ShortString;
FPath : ShortString;
ZipSplitted : boolean;
function GetCentrDirOfset(StartOffset: longint): boolean;
const
HalfBufSize = 512;
type
Buffer = array[1..2*HalfBufSize+1] of char;
var
Buf : Buffer;
QResult : longword;
Header : rHeaderFlag;
ZSeek : longint;
ZSize : longint;
FileSmall : boolean;
ZRead : word;
ZPos : longint;
Found : boolean;
EndRec : ZIPEndHeadType;
begin
GetCentrDirOfset := false;
if StartOffset = 0
then
begin
ZSize := ZIPFile.GetSize;
ZSeek := ZSize - 2 * HalfBufSize;
if ZSeek < 0
then
begin
ZSeek := 0;
FileSmall := true;
ZRead := ZSize;
end
else
begin
FileSmall := false;
ZRead := 2 * HalfBufSize;
end;
ZIPFile.Seek(ZSeek);
ZIPFile.ReadExt(Buf, ZRead, QResult);
if QResult <> ZRead then exit;
ZPos := RPos(Buf, ZRead, 'PK'#5#6);
Found := ZPos > 0;
if not FileSmall then
begin
ZRead := 2 * HalfBufSize;
while not Found and (ZSeek > 0) and ((ZSize - ZSeek) < $0FFF0) do
begin
ZSeek := ZSeek - HalfBufSize;
if ZSeek < 0 then ZSeek := 0;
ZIPFile.Seek(ZSeek);
ZIPFile.ReadExt(Buf, ZRead, QResult);
if QResult <> ZRead then exit;
ZPos := RPos(Buf, ZRead, 'PK'#5#6);
Found := ZPos > 0;
end;
end;
if not Found then // central directroy not found
begin
Result := SlowScanZipFile (Col, WholeFileSpec, 0);
exit;
end;
ZSeek := ZSeek + ZPos + 3 {- 1 + 4};
end
else
ZSeek := StartOffset + 4;
ZIPFile.Seek(ZSeek);
ZIPFile.ReadExt(EndRec, SizeOf(EndRec), QResult);
if QResult <> SizeOf(EndRec) then exit;
with EndRec do
begin
if rNumOfThisDisk <> rNumOfStartDisk then exit; // central dir is on multiple disks
ZIPSplitted := rNumOfThisDisk > 0;
ZSeek := ZSeek - rSizeOfCentralDir - 4;
if ZSeek < 0 then exit;
ZIPFile.Seek(ZSeek);
ZIPFile.ReadExt(Header, SizeOf(Header), QResult);
if Header <> 'PK'#1#2 then exit;
ZIPFile.Seek(ZSeek);
end;
GetCentrDirOfset := true;
end;
function GetNextFile: boolean;
type
Buffer = array[1..256] of char;
var
Buf : ^Buffer;
QResult : longword;
LastSlash : byte;
TmpPath : ShortString;
i : byte;
Header : rHeaderFlag;
begin
GetNextFile := false;
ZIPFile.ReadExt(Header, SizeOf(Header), QResult);
if Header <> 'PK'#1#2 then exit;
ZIPFile.ReadExt(ZIPCenHead, SizeOf(ZIPCenHead), QResult);
if QResult <> SizeOf(ZIPCenHead) then exit;
with ZIPCenHead do
begin
GetMem(Buf,rNameLength);
ZIPFile.ReadExt(Buf^, rNameLength, QResult);
if rNameLength > 255 then
begin
Move(Buf^[rNameLength-255+1], Buf^[1], 255);
rNameLength := 255;
end;
LongName[0] := char(rNameLength);
move(Buf^[1], LongName[1], rNameLength);
FreeMem(Buf,rNameLength);
if QResult <> rNameLength then exit;
///OemToCharBuff(@LongName[1], @LongName[1], rNameLength);
if (rExtraLength > 0) or (rCommentLength > 0) then
ZIPFile.Seek(ZIPFile.GetPos + rExtraLength + rCommentLength);
end;
GetNextFile := true;
with ZIPCenHead do
begin
if (LongName[0] > #1) and (LongName[2]= ':') then ShortDelete(LongName,1,2);
LastSlash := 0;
for i := 1 to length(LongName) do
begin
if LongName[i] = '/' then LongName[i] := '\';
if LongName[i] = '\' then LastSlash := i;
end;
if LastSlash <> 0
then
begin
TmpPath := ShortCopy(LongName, 1, LastSlash);
ShortDelete (LongName, 1, LastSlash);
end
else
TmpPath := '';
if TmpPath <> FPath then FPath := TmpPath;
end;
end;
var
TmpStrArr : array[0..256] of char;
begin
try
Result := false;
ZIPSplitted := true; // because of DirInfo
ZIPEofStatus := false;
FPath := '';
{--- opening ---}
CB_NewLineToIndicator(labZjistujiObsah + WholeFileSpec);
ZIPFile.Init (StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
if not GetCentrDirOfset(StartOffset) then
begin
ZIPFile.Done;
exit;
end;
if not GetNextFile then
begin
ZIPFile.Done;
exit;
end;
while not ZIPEofStatus do
begin
with ZIPCenHead do
begin
LongName := TrimSpaces(LongName);
if LongName <> '' then
Col^.Insert(New (POneArcItem, Init(FPath, LongName, rSize,
rDateTime, 0, rRelOfsLocHead)));
// rRelOfsLocHead is invalid for EXE files, as the first file
// has offset 0 and not the code size
Result := true;
end;
if not GetNextFile then ZIPEofStatus := true;
end;
ZIPFile.Done;
except
on EQDirException do
Result := false;
end;
end;
//=============================================================================
// Scans PkARC file
function ScanARCFile (Col: PArcCollection; WholeFileSpec: ShortString): boolean;
type
ARCRawType = record
rHeaderFlag : byte;
rCompVersion : byte;
rName : array [1..13] of char;
rCompSize : LongWord;
rDate : word;
rTime : word;
rCRC : word;
rSize : LongWord;
end;
var
ARCFile : TQBufStream;
ARCEOFStatus : boolean;
ARCRaw : ARCRawType;
fName : string[12];
function GetFirstFile (First: boolean): boolean;
var
QResult : longword;
i : Integer;
begin
GetFirstFile := false;
ArcFile.ReadExt(ARCRaw, SizeOf(ARCRaw), QResult);
if QResult <> SizeOf(ARCRaw) then exit;
if ArcRaw.rHeaderFlag <> $1A then
begin
exit;
end;
with ARCRaw do
begin
FillChar (fName, SizeOf(fName), ' ');
i := pos(#0, rName) - 1;
if (i < 1) or (i > 12) then exit;
GetFirstFile := true;
move (rName[1], fName[1], i);
fName[0] := chr(12);
end;
end;
function GetNextFile: boolean;
var
FPos : LongWord;
begin
GetNextFile := true;
FPos := ARCFile.GetPos + ARCRaw.rCompSize;
if FPos < ARCFile.GetSize
then
begin
ARCFile.Seek(FPos);
if not GetFirstFile(false) then
begin
GetNextFile := false;
ARCEofStatus := true;
end;
end
else
begin
ARCEofStatus := true;
GetNextFile := false;
end;
end;
var
TmpStrArr: array[0..256] of char;
begin
try
Result := false;
ARCEofStatus := False;
{--- opening ---}
CB_NewLineToIndicator(labZjistujiObsah + WholeFileSpec);
ARCFile.Init (StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
if not GetFirstFile(true) then
begin
ARCFile.Done;
exit;
end;
while not ARCEofStatus do
begin
with ARCRaw do
begin
fName := TrimSpaces(fName);
Col^.Insert(New (POneArcItem, Init('', fName, rSize,
longint(rTime) or (longint(rDate) shl 16), 0, 0)));
Result := true;
end;
GetNextFile;
end;
ARCFile.Done;
except
on EQDirException do
Result := false;
end;
end;
//=============================================================================
// Scans BAK file (Microsoft old backup)
function ScanBAKFile (Col: PArcCollection; WholeFileSpec: ShortString): boolean;
var
BakFile : TQBufStream;
i : byte;
Line : ShortString;
Len : byte;
FPath : ShortString;
QSearchRec : TQSearchRec;
TmpStrArr : array[0..256] of char;
begin
try
Result := false;
FPath := '';
CB_NewLineToIndicator(labZjistujiObsah + WholeFileSpec);
BakFile.Init(StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
while not BakFile.Eof do
begin
BakFile.Read(Len,1);
BakFile.Read(Line[1],pred(len));
Line[0] := chr(pred(Len));
if Len < 40
then
begin
with QSearchRec do
begin
move(line[1],Name[1],12);
Name[0] := #12;
for i := 1 to length(Name) do if Name[i] < #32 then Name[i] := ' ';
while ShortCopy(Name,length(Name),1) = ' ' do
ShortDelete(Name,length(Name),1);
move(line[28],Attr,1);
move(line[24],Size,4);
move(line[30],Time,4);
Col^.Insert(New (POneArcItem, Init(FPath, Name, Size, Time, Attr, 0)));
end;
Result := true;
end
else
if Len < 75
then
begin
FPath := line;
for i := 1 to length(FPath) do
if FPath[i] < #32 then FPath[i] := ' ';
i := 1;
while (i < length(FPath)) and (FPath[i] <> ' ') do inc(i);
dec(i);
FPath[0] := chr(i);
if FPath[length(FPath)] <> '\' then FPath := FPath + '\';
end
else
begin
for i := 1 to length(Line) do
if Line[i] < #32 then Line[i] := ' ';
if ShortCopy(line,1,6) <> 'BACKUP' then
begin
BakFile.Done;
exit;
end;
end;
end;
BakFile.Done;
except
on EQDirException do
Result := false;
end;
end;
//=============================================================================
// Scans CPB file CentralPointBackup (PCTools 7)
function ScanPCBFile (Col: PArcCollection; WholeFileSpec: ShortString; CPB: boolean): boolean;
var
Rec : array[0 .. 127] of byte;
FPath : ShortString;
QSearchRec: TQSearchRec;
procedure WritelnRec;
var
i : byte;
SwapTime : array[1..2] of word;
STime : longint absolute SwapTime;
Path : ShortString;
begin
case Rec[0] of
$DA: // next subfolder
begin
i := 1;
while (Rec[i+1] <> 0) and (i < 16) do
begin
Path[i] := chr(Rec[i+1]);
inc(i);
end;
Path[0] := chr(pred(i));
FPath := FPath + Path;
if ShortCopy(FPath,2,1) = ':' then ShortDelete(FPath,1,2);
if FPath[length(FPath)] <> '\' then FPath := FPath + '\';
end;
$DC: // one level up
begin
i := pred(length(FPath));
while (i > 1) and (FPath[i] <> '\') do dec(i);
if i > 0 then
ShortDelete(FPath,succ(i),length(FPath)-i);
if FPath[length(FPath)] <> '\' then FPath := FPath + '\';
end;
$DB: // file
begin
with QSearchRec do
begin
Attr := 0;
i := 1;
while (Rec[i+1] <> 0) and (i < 13) do
begin
Name[i] := chr(Rec[i+1]);
inc(i);
end;
Name[0] := chr(pred(i));
move(Rec[20],Size,4);
move(Rec[16],SwapTime[2],2);
move(Rec[18],SwapTime[1],2);
Time := STime;
Col^.Insert(New (POneArcItem, Init(FPath, Name, Size, Time, Attr, 0)));
end;
Result := true;
end;
end;
end;
var
PCBFile : TQBufStream;
ID : array[1..4] of char;
Found : boolean;
SavePos : longint;
Rec512 : array[1..512] of char;
EndOfHeader : boolean;
QResult : longword;
TmpStrArr : array[0..256] of char;
begin
try
Result := false;
CB_NewLineToIndicator(labZjistujiObsah + WholeFileSpec);
SavePos := 0;
Found := false;
PCBFile.Init (StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
FPath := '';
Rec[0] := 0;
if CPB
then
begin
while not (PCBFile.Eof or Found) do
begin
SavePos := PCBFile.GetPos;
PCBFile.ReadExt(Rec512, 512, QResult);
if (Rec512[1] = #1) and (Rec512[2] = 'D') and
(Rec512[3] = 'C') and (Rec512[4] = 'P') then Found := true;
end;
if Found then PCBFile.Seek(SavePos);
end
else
begin
PCBFile.Read(ID, 4);
if ID = #1'DCP' then Found := true;
end;
if not Found then
begin
CB_AppendLineToIndicator(labPCBHlavaNenalezena);
exit;
end;
while not PCBFile.Eof and (Rec[0] <> $DA) do
PCBFile.Read(Rec[0], 1);
if PCBFile.Eof then exit;
PCBFile.Read(Rec[1], 15);
writelnRec;
EndOfHeader := false;
while not (PCBFile.Eof or EndOfHeader) do
begin
PCBFile.Read(Rec[0], 1);
if PCBFile.Eof then EndOfHeader := true;
case Rec[0] of
$DA : PCBFile.Read(Rec[1], 15);
$DB : PCBFile.Read(Rec[1], 27);
$DC : ;
else EndOfHeader := true;
end;
writelnRec;
end;
PCBFile.Done;
except
on EQDirException do
Result := false;
end;
end;
//=============================================================================
// Scans Norton backup file
function ScanNBFile (Col: PArcCollection; WholeFileSpec: ShortString): boolean;
const
Delka = 32;
Signature = #0'NORTON Ver 1';
type
TPolozka = array [1..Delka] of char;
var
NBFile : TQBufStream;
P : TPolozka;
FName : ShortString;
FExt : ShortString;
i,j : Integer;
FPath : ShortString;
CP : array [1..length(Signature)] of char;
QSearchRec : TQSearchRec;
DirLevel : shortint;
ActualLevel : shortint;
ToSeek : longint;
TmpStrArr : array[0..256] of char;
begin
try
Result := false;
ToSeek := 0;
NBFile.Init (StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
NBFile.Read(P, 1);
move (P, CP, length(Signature));
if CP <> Signature then
begin
NBFile.Done;
exit;
end;
CB_NewLineToIndicator(labZjistujiObsah + WholeFileSpec);
inc(ToSeek, 16);
NBFile.Seek(ToSeek);
FPath := '';
ActualLevel := 0;
while not (NBFile.Eof or (P[1] = #$FF)) do
begin
NBFile.Read(P, 1);
move (P, CP, length(Signature));
if CP = Signature then
begin
inc(ToSeek, 16);
NBFile.Seek(ToSeek);
continue;
end;
if P[1] = #$FF then break;
if P[1] = #0
then
begin
move(P[ 2], FName[1], 8);
i := 8;
while (i > 0) and (FName[i] <= ' ') do dec(i);
FName [0] := char(i);
move(P[10], FExt [1], 3);
i := 3;
while (i > 0) and (FExt[i] <= ' ') do dec(i);
FExt[0] := char(i);
with QSearchRec do
begin
Name := FName + '.' + FExt;
move(P[13], Attr, 1);
move(P[23], Time, 4);
move(P[29], Size, 4);
Col^.Insert(New (POneArcItem, Init(
ShortCopy(FPath, 2, pred(length(FPath))),
Name, Size, Time, Attr, 0)));
end;
Result := true;
end
else
begin
FillChar(QSearchRec, SizeOf(QSearchRec), 0);
move(P[ 1], FName[1], 8);
i := 8;
while (i > 0) and (FName[i] <= ' ') do dec(i);
FName [0] := char(i);
move(P[9], FExt [1], 3);
i := 3;
while (i > 0) and (FExt[i] <= ' ') do dec(i);
FExt[0] := char(i);
QSearchRec.Name := FName + '.' + FExt;
QSearchRec.Attr := faDirectory;
DirLevel := byte(P[12]);
if DirLevel = 0 then Continue;
while DirLevel <= ActualLevel do
begin
if FPath <> '' then dec(FPath[0]);
for j := length(FPath) downto 1 do
if FPath[j] = '\' then break;
FPath[0] := char(j);
dec(ActualLevel);
end;
if FPath[length(FPath)] <> '\' then FPath := FPath + '\';
if FPath[2] = ':' then ShortDelete(FPath, 1, 2);
FPath := FPath + FName + FExt + '\';
Inc(ActualLevel);
end;
end;
NBFile.Done;
except
on EQDirException do
Result := false;
end;
end;
//=============================================================================
// Scans LHarc file
function ScanLHArcFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
type
TLzHead = record
HeadSiz: byte;
HeadChk: byte;
HeadID : array[1..5] of char;
PacSiz : longint;
OrgSiz : longint;
Ftime : longint; {union with stamp}
Attr : word;
Fname : ShortString;
end;
var
LZHFile : TQBufStream;
CurPos : longint;
MaxPos : longint;
Dir : ShortString;
LzHead : TLzHead;
LastSlash : Integer;
i : Integer;
OneArcItem : POneArcItem;
TmpStrArr : array[0..256] of char;
LocHeadOffset: longint;
begin
try
Result := false;
{--- opening ---}
CB_NewLineToIndicator(labZjistujiObsah + WholeFileSpec);
LZHFile.Init (StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
if StartOffset >= 2 then dec(StartOffset, 2);
// the header begins by 2 bytes earlier than -lz
CurPos := StartOffset;
MaxPos := LZHFile.GetSize;
if MaxPos < SizeOf(TLzHead) then exit;
MaxPos := MaxPos - SizeOf(TLzHead);
while not (LZHFile.Eof or (CurPos > MaxPos)) do
begin
LZHFile.Seek(CurPos);
LocHeadOffset := LZHFile.GetPos;
LZHFile.Read(LzHead, sizeOf(LzHead));
//check if it is LHARC - HeadID should be one of: "-lz4-", "-lz5-", "-lh0-", "-lh1-"
if (LzHead.HeadID[1] <> '-') or (LzHead.HeadID[2] <> 'l') or
(LzHead.HeadID[5] <> '-') then
begin
LZHFile.Done;
exit;
end;
LastSlash := 0;
for i := 1 to length(LzHead.Fname) do
begin
if LzHead.Fname[i] = '/' then LzHead.Fname[i] := '\';
if LzHead.Fname[i] = '\' then LastSlash := i;
end;
if LastSlash <> 0
then
begin
Dir := ShortCopy(LzHead.Fname, 1, LastSlash);
ShortDelete (LzHead.Fname, 1, LastSlash);
end
else
Dir := '';
OneArcItem := New (POneArcItem, Init(Dir, LzHead.Fname,
LzHead.OrgSiz, LzHead.Ftime, byte(LzHead.Attr), LocHeadOffset));
Col^.Insert(OneArcItem);
CurPos := CurPos + LzHead.HeadSiz + LzHead.PacSiz + 2;
end;
Result := true;
LZHFile.Done;
except
on EQDirException do
Result := false;
end;
end;
//=============================================================================
// Scans ARJ file
function ScanARJFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
const
HEADER_ID = $EA60;
HEADER_ID_HI = $EA;
HEADER_ID_LO = $60;
FNAME_MAX = 512;
COMMENT_MAX = 2048;
FIRST_HDR_SIZE = 30;
HEADERSIZE_MAX = FIRST_HDR_SIZE + 10 + FNAME_MAX + COMMENT_MAX;
HEADERSIZE_MIN = FIRST_HDR_SIZE + 10;
CRC_MASK = $FFFFFFFF;
CRCPOLY = $EDB88320;
GARBLED_FLAG = $01;
RESERVED = $02;
VOLUME_FLAG = $04;
EXTFILE_FLAG = $08;
PATHSYM_FLAG = $10;
BACKUP_FLAG = $20;
MaxPossibleHeaders = 100;
// FType (0 = binary, 1 = text, 2 = comment header,
// 3 = directory, 4 = volume label)
type
THeader = array[0..HEADERSIZE_MAX] of byte;
PHeader = ^THeader;
THeaderStruct = record
HeaderId : word;
HeaderSize : word;
HeaderCrc : LongWord;
FirstHdrSize : byte;
ArjVer : byte;
ArjVerNeeded : byte;
HostOS : byte;
ArjFlags : byte;
Method : byte;
FileType : byte;
Reserved : byte;
TimeStamp : LongWord;
CompSize : LongWord;
OrigSize : LongWord;
FileCRC : LongWord;
EntryPos : word;
FMode : word;
HostData : word;
FileName : ShortString;
ExtHeaderSize: word;
end;
PHeaderStruct = ^THeaderStruct;
var
CRC : LongWord;
CRCTable : array [0..255] of LongWord;
Header : PHeader;
HeaderStruct: PHeaderStruct;
LastPos : LongWord;
PossibleHeaders: array[1..MaxPossibleHeaders] of LongWord;
LocHeadOffset : LongWord;
procedure MakeCRCTable;
var
i, j: longint;
r: LongWord;
begin
for i := 0 to 255 do
begin
r := i;
for j := 8 downto 1 do
begin
if (r and 1) <> 0
then r := (r shr 1) xor CRCPOLY
else r := r shr 1;
end;
crctable[i] := r;
end;
end;
procedure crc_buf (var str: THeader; len: LongWord);
var
i : longint;
begin
for i := 0 to len-1 do
crc:= crctable[(crc xor str[i]) and $FF] xor (crc shr 8)
end;
function FindFirstPossibleHeaders(var F: TQBufStream): boolean;
const
MaxBytesToScan = $FFF0; {63*1024;}
type
TBuffer = array[0..MaxBytesToScan] of char;
PTBuffer = ^TBuffer;
var
PBuffer : PTBuffer;
ScanBytes: LongWord;
SavePos : LongWord;
i : longint;
QResult : LongWord;
FoundCounter: longint;
begin
Result := false;
FillChar(PossibleHeaders, sizeof(PossibleHeaders), 0);
SavePos := F.GetPos;
F.Seek(0);
ScanBytes := F.GetSize;
if ScanBytes > MaxBytesToScan then ScanBytes := MaxBytesToScan;
GetMem(PBuffer, ScanBytes);
F.ReadExt(PBuffer^, ScanBytes, QResult);
FoundCounter := 0;
if QResult = ScanBytes then
begin
for i := 0 to ScanBytes-2 do
begin
if (byte(PBuffer^[i]) = HEADER_ID_LO) and
(byte(PBuffer^[succ(i)]) = HEADER_ID_HI) then
begin
if FoundCounter < MaxPossibleHeaders then
begin
inc(FoundCounter);
PossibleHeaders[FoundCounter] := i;
Result := true;
end;
end;
end;
end;
FreeMem(PBuffer, ScanBytes);
F.Seek(SavePos);
end;
function FindHeader (var F: TQBufStream): longint;
const
LimitForSearch = 1024; {if not found in 1 kB, exit}
var
ArcPos : LongWord;
C : byte;
LimitCounter: LongWord;
begin
FindHeader := -1;
LimitCounter := LimitForSearch;
ArcPos := F.GetPos;
while (ArcPos < LastPos) do
begin
F.Seek(ArcPos);
F.Read(C, 1);
while (ArcPos < LastPos) do
begin
dec(LimitCounter);
if LimitCounter = 0 then exit;
if (c <> HEADER_ID_LO)
then
F.Read(c, 1)
else
begin
F.Read(c, 1);
if (c = HEADER_ID_HI) then break;
end;
inc(ArcPos);
end;
if (ArcPos >= LastPos) then break;
LocHeadOffset := F.GetPos - 2;
F.Read(HeaderStruct^.HeaderSize, 2);
if HeaderStruct^.HeaderSize = 0 then exit; {it is the end of archive}
if HeaderStruct^.HeaderSize <= HEADERSIZE_MAX then
begin
crc := CRC_MASK;
F.Read(Header^, HeaderStruct^.HeaderSize);
crc_buf(Header^, HeaderStruct^.HeaderSize);
F.Read(HeaderStruct^.HeaderCrc, 4);
if (crc xor CRC_MASK) = HeaderStruct^.HeaderCrc then
begin
FindHeader := ArcPos;
exit;
end;
end;
inc(ArcPos);
end;
end;
function ReadHeader (var F: TQBufStream): boolean;
var
StartPos, i : LongWord;
HeadPos : longint;
SeekPos : LongWord;
begin
ReadHeader := false;
HeadPos := FindHeader(F); // reads also Header^
if HeadPos = -1 then exit;
with HeaderStruct^ do
begin
move(Header^, HeaderStruct^.FirstHdrSize, 30); // 30 is from FirstHeaderSize to HostData}
StartPos := FirstHdrSize;
i := StartPos;
while (Header^[i] <> 0) and (i < HeaderSize) do inc (i);
if (i - StartPos) > 255 then i := StartPos + 255;
move(Header^[StartPos], FileName[1], i - StartPos);
FileName[0] := char(i - StartPos);
if (ArjFlags and PATHSYM_FLAG) <> 0 then
for i := 1 to length(FileName) do
if FileName[i] = '/' then
FileName[i] := '\';
F.Read(ExtHeaderSize, 2);
if (ExtHeaderSize <> 0) then F.Seek(F.GetPos + ExtHeaderSize + 4);
if (FileType <> 2) then
begin
SeekPos := F.GetPos + CompSize;
if SeekPos > LastPos then SeekPos := LastPos;
F.Seek(SeekPos);
end;
end;
ReadHeader := true;
end;
var
ARJFile : TQBufStream;
Dir : ShortString;
TmpStrArr : array[0..256] of char;
i : Integer;
LastSlash : Integer;
FoundHeader : longint;
begin
try
MakeCRCTable;
Result := false;
{--- opening ---}
CB_NewLineToIndicator(labZjistujiObsah + WholeFileSpec);
ArjFile.Init(StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
if StartOffset > 0 then ArjFile.Seek(StartOffset);
LastPos := ArjFile.GetSize - HEADERSIZE_MIN;
if LastPos <= 0 then
begin
ArjFile.Done;
exit;
end;
New(Header);
New(HeaderStruct);
FoundHeader := FindHeader(ArjFile);
if FoundHeader = -1 then {not found}
begin
if FindFirstPossibleHeaders(ArjFile) then
begin
i := 1;
while (PossibleHeaders[i] > 0) and (FoundHeader = -1) do
begin
ArjFile.Seek(PossibleHeaders[i]);
FoundHeader := FindHeader(ArjFile);
inc(i);
end;
end;
end;
if FoundHeader = -1 then
begin
ArjFile.Done;
Dispose(HeaderStruct);
Dispose(Header);
exit;
end;
ArjFile.Seek(FoundHeader);
while ReadHeader(ArjFile) do
with HeaderStruct^ do
begin
LastSlash := 0;
for i := length(FileName) downto 1 do
if FileName[i] = '\' then
begin
LastSlash := i;
break;
end;
if LastSlash <> 0
then
begin
Dir := ShortCopy(FileName, 1, LastSlash);
ShortDelete (FileName, 1, LastSlash);
end
else
Dir := '';
Col^.Insert(New (POneArcItem, Init(Dir, FileName, OrigSize,
TimeStamp, 0, LocHeadOffset)));
Result := true;
end;
Dispose(HeaderStruct);
Dispose(Header);
ArjFile.Done;
except
on EQDirException do
Result := false;
end;
end;
//=============================================================================
// Scans RAR file by supplied DLL from RAR developers
function ScanRARFileByDll (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
var
hRarArchive: integer;
RarOpenArchiveData: TRarOpenArchiveData;
RarHeaderData : TRarHeaderData;
ZString: array[0..256] of char;
RHCode : longint;
PFCode : longint;
Dir : ShortString;
FileName : ShortString;
iLen : integer;
LastSlash : integer;
i : integer;
begin
Result := false;
if not UnRarDllLoaded then exit;
StrPCopy(ZString, WholeFileSpec);
RarOpenArchiveData.ArcName := @ZString;
RarOpenArchiveData.OpenMode := RAR_OM_LIST;
RarOpenArchiveData.OpenResult := 0;
RarOpenArchiveData.CmtBuf := nil;
RarOpenArchiveData.CmtBufSize := 0;
RarOpenArchiveData.CmtSize := 0;
RarOpenArchiveData.CmtState := 0;
hRarArchive := RarOpenArchive(RarOpenArchiveData);
if (RarOpenArchiveData.OpenResult <> 0) then // unsuccessful
begin
RarCloseArchive(hRarArchive);
exit;
end;
repeat
RHCode:= RARReadHeader(hRarArchive, RarHeaderData);
if RHCode<>0 then Break;
if (RarHeaderData.FileAttr and (faDirectory or faVolumeID) = 0) then
begin
iLen := strlen(RarHeaderData.FileName);
if (iLen > 254) then iLen := 254;
FileName[0] := char (iLen);
///OemToCharBuff(@(RarHeaderData.FileName), @(FileName[1]), iLen);
LastSlash := 0;
for i := 1 to length(FileName) do
begin
if FileName[i] = '/' then FileName[i] := '\';
if FileName[i] = '\' then LastSlash := i;
end;
if LastSlash <> 0
then
begin
Dir := ShortCopy(FileName, 1, LastSlash);
ShortDelete (FileName, 1, LastSlash);
end
else
Dir := '';
Col^.Insert(New (POneArcItem, Init(Dir, FileName, RarHeaderData.UnpSize,
RarHeaderData.FileTime, RarHeaderData.FileAttr,
0)));
Result := true;
end;
PFCode:= RARProcessFile(hRarArchive, RAR_SKIP, nil, nil);
if (PFCode<>0) then Break;
until False;
RarCloseArchive(hRarArchive);
end;
//-----------------------------------------------------------------------------
// Scans RAR file internally
function ScanRARFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
type
THeaderStruct = record
HeadCRC : word;
HeadType : byte;
HeadFlags : word;
HeadSize : word;
end;
TFHeaderStruct = record
CompSize : longint;
OrigSize : longint;
HostOS : byte;
FileCRC : longint;
DateTime : longint;
UnpVer : byte;
Method : byte;
NameSize : word;
Attr : longint;
end;
var
HeaderStruct : THeaderStruct;
FHeaderStruct: TFHeaderStruct;
FileName : ShortString;
RARFileSize : longint;
LocHeadOffset: longint;
function ReadBlock (var F: TQBufStream): boolean;
var
AddSize : longint;
SeekTo : longint;
SavePos : longint;
begin
ReadBlock := false;
AddSize := 0;
SavePos := F.GetPos;
LocHeadOffset := F.GetPos;
if SavePos = RARFileSize then exit; // we are at the end
F.Read(HeaderStruct, SizeOf(HeaderStruct));
with HeaderStruct do
begin
case HeadType of
$72: {marker block}
begin
if (HeadFlags and $8000) <> 0 then F.Read(AddSize, 4);
SeekTo := SavePos + HeadSize + AddSize;
end;
$73: {archive header}
begin
if (HeadFlags and $8000) <> 0 then F.Read(AddSize, 4);
SeekTo := SavePos + HeadSize + AddSize;
end;
$74: {file header}
begin
F.Read(FHeaderStruct, SizeOf(FHeaderStruct));
with FHeaderStruct do
begin
if NameSize > 255 then NameSize := 255;
FileName[0] := char(NameSize);
F.Read(FileName[1], NameSize);
SeekTo := SavePos + HeadSize + CompSize;
end;
end;
$75: {comment header}
begin
if (HeadFlags and $8000) <> 0 then F.Read(AddSize, 4);
SeekTo := SavePos + HeadSize + AddSize;
end;
$76: {extra information}
begin
if (HeadFlags and $8000) <> 0 then F.Read(AddSize, 4);
SeekTo := SavePos + HeadSize + AddSize;
end;
else exit;
end; {case}
if SeekTo > RarFileSize then exit;
F.Seek(SeekTo);
end; {with}
ReadBlock := true;
end;
var
RARFile : TQBufStream;
Dir : ShortString;
Identifier : array[1..4] of char;
TmpStrArr : array[0..256] of char;
LastSlash : Integer;
i : Integer;
begin
if ScanRARFileByDll (Col, WholeFileSpec, StartOffset) then
begin
Result := true;
exit;
end;
try
Result := false;
{--- opening ---}
CB_NewLineToIndicator(labZjistujiObsah + WholeFileSpec);
RARFile.Init(StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
if StartOffset > 0 then RarFile.Seek(StartOffset);
RARFileSize := RARFile.GetSize;
RARFile.Read(Identifier, 4);
if Identifier = 'Rar!' then
begin
RARFile.Seek(RARFile.GetPos-4);
while ReadBlock(RARFile) do
if (HeaderStruct.HeadType = $74) and
(FHeaderStruct.Attr and (faDirectory or faVolumeID) = 0) then
with FHeaderStruct do
begin
LastSlash := 0;
for i := 1 to length(FileName) do
begin
if FileName[i] = '/' then FileName[i] := '\';
if FileName[i] = '\' then LastSlash := i;
end;
if LastSlash <> 0
then
begin
Dir := ShortCopy(FileName, 1, LastSlash);
ShortDelete (FileName, 1, LastSlash);
end
else
Dir := '';
Col^.Insert(New (POneArcItem, Init(Dir, FileName, OrigSize,
DateTime, Attr, LocHeadOffset)));
Result := true;
end;
end;
RARFile.Done;
except
on EQDirException do
Result := false;
end;
end;
//=============================================================================
// ACE file scanning, using external DLL
var
AceCommentBuf: array[0..COMMENTBUFSIZE-1] of char;
AceCol: PArcCollection;
// ACE callback functions
function AceInfoProc(Info : pACEInfoCallbackProcStruc) : integer; stdcall;
begin
Result:=ACE_CALLBACK_RETURN_OK;
end;
function AceErrorProc(Error : pACEErrorCallbackProcStruc) : integer; stdcall;
begin
Result:=ACE_CALLBACK_RETURN_CANCEL;
end;
function AceRequestProc(Request : pACERequestCallbackProcStruc) : integer; stdcall;
begin
Result:=ACE_CALLBACK_RETURN_CANCEL;
end;
function AceStateProc(State: pACEStateCallbackProcStruc) : integer; stdcall;
var
Dir : ShortString;
FileName : ShortString;
iLen : integer;
LastSlash : integer;
i : integer;
begin
Result:=ACE_CALLBACK_RETURN_OK;
case State^.StructureType of
ACE_CALLBACK_TYPE_ARCHIVE:
begin
iLen := strlen(State^.Archive.ArchiveData^.ArchiveName);
if (iLen > 254) then iLen := 254;
FileName[0] := char (iLen);
///CopyMemory(@FileName[1], State^.Archive.ArchiveData^.ArchiveName, iLen);
end;
ACE_CALLBACK_TYPE_ARCHIVEDFILE:
begin
if ((State^.ArchivedFile.Code = ACE_CALLBACK_STATE_STARTFILE) and
(State^.ArchivedFile.FileData^.Attributes and (faDirectory or faVolumeID) = 0)) then
begin
FillChar(FileName, sizeof(FileName), 0);
iLen := strlen(State^.ArchivedFile.FileData^.SourceFileName);
if (iLen > 254) then iLen := 254;
FileName[0] := char (iLen);
///CopyMemory(@FileName[1], State^.ArchivedFile.FileData^.SourceFileName, iLen);
LastSlash := 0;
for i := 1 to length(FileName) do
begin
if FileName[i] = '/' then FileName[i] := '\';
if FileName[i] = '\' then LastSlash := i;
end;
if LastSlash <> 0
then
begin
Dir := ShortCopy(FileName, 1, LastSlash);
ShortDelete (FileName, 1, LastSlash);
end
else
Dir := '';
AceCol^.Insert(New (POneArcItem, Init(Dir, FileName,
State^.ArchivedFile.FileData^.Size,
State^.ArchivedFile.FileData^.Time,
State^.ArchivedFile.FileData^.Attributes,
0)));
exit;
end;
end;
end;
Result:=ACE_CALLBACK_RETURN_OK;
end;
//-----------------------------------------------------------------------------
function ScanACEFile (Col: PArcCollection; WholeFileSpec: ShortString;
StartOffset: longint): boolean;
var
DllData : tACEInitDllStruc;
zTempDir : array[0..255] of char;
List : tACEListStruc;
ZString: array[0..256] of char;
begin
Result := false;
if not UnAceDllLoaded then exit;
FillChar(DllData, SizeOf(DllData), 0);
DllData.GlobalData.MaxArchiveTestBytes := $1ffFF; // search for archive
// header in first 128k
// of file
DllData.GlobalData.MaxFileBufSize := $2ffFF; // read/write buffer size
// is 256k
DllData.GlobalData.Comment.BufSize := SizeOf(AceCommentBuf)-1;
DllData.GlobalData.Comment.Buf := @AceCommentBuf; // set comment bufffer
// to receive comments
// of archive and/or
// set comments
{$ifdef mswidnows} // set comments
GetTempPath(255, @zTempDir);
DllData.GlobalData.TempDir := @zTempDir;
{$else}
DllData.GlobalData.TempDir := PChar(GetTempDir);
{$endif}
// set callback function pointers
DllData.GlobalData.InfoCallbackProc := @AceInfoProc;
DllData.GlobalData.ErrorCallbackProc := @AceErrorProc;
DllData.GlobalData.RequestCallbackProc := @AceRequestProc;
DllData.GlobalData.StateCallbackProc := @AceStateProc;
if (ACEInitDll(@DllData) <> 0) then exit;
AceCol := Col;
FillChar(List, SizeOf(List), 0); // set all fields to zero
List.Files.SourceDir := ''; // archive main directory is
// base directory for FileList
List.Files.FileList := ''; // set FileList
List.Files.ExcludeList := ''; // no files to exclude
List.Files.FullMatch := true; // also list files partially matching
// (for instance: list DIR1\TEST.DAT
// if FileList specifies TEST.DAT)
StrPCopy(ZString, WholeFileSpec);
Result:= ACEList(@ZString, @List) = 0;
end;
//=============================================================================
// Tries to identify, if the EXE file is a self-extracting archive
function ScanExeFile (Col: PArcCollection; WholeFileSpec: ShortString;
ScanAlsoNonZipArchives: boolean;
var ArchiveType: TArchiveType): boolean;
type
String4 = String[4];
const
MaxBytesToScan = $FFF0; {65520}
MaxBytesToScanZIP = 32*1024; // must be smaller than MaxBytesToScan
RarID : String4 = 'Rar!';
ArjID : String4 = #$60#$EA;
LhaID1 : String4 = '-lh';
LhaID2 : String4 = '-lz';
ZipID : String4 = 'PK'#3#4;
ZipIDCentral : String4 = 'PK'#5#6;
type
TBuffer = array[0..MaxBytesToScan] of char;
PTBuffer = ^TBuffer;
var
ExeFile : TQBufStream;
ScanBytes : LongWord;
ScanBytesZIP: LongWord;
TmpStrArr : array[0..256] of char;
PBuffer : PTBuffer;
QResult : LongWord;
ScanString : ShortString;
BufScanPos : LongWord;
RarIDFound : boolean;
ArjIDFound : boolean;
ZipIDFound : boolean;
RarIDPos : LongWord;
ArjIDPos : LongWord;
ZipIDPos : LongWord;
procedure ScanForIDFromLeft(ID: String4; var IDFound: boolean; var IDPos: LongWord);
var
i : LongWord;
begin
if not IDFound then
begin
i := pos(ID, ScanString);
if i > 0 then
begin
IDFound := true;
IDPos := BufScanPos + i - 1;
end;
end;
end;
begin
try
Result := false;
RarIDFound := false;
ArjIDFound := false;
ZipIDFound := false;
ArchiveType := atOther;
RarIDPos := 0;
ArjIDPos := 0;
ZipIDPos := 0;
ExeFile.Init(StrPCopy(TmpStrArr, WholeFileSpec), stOpenReadNonExclusive);
ScanBytes := ExeFile.GetSize;
if ScanBytes = 0 then exit;
if ScanBytes > MaxBytesToScan then ScanBytes := MaxBytesToScan;
GetMem(PBuffer, ScanBytes);
if PBuffer = nil then exit;
// first check for central dir of ZIP file
ScanBytesZIP := ExeFile.GetSize;
if ScanBytesZIP > MaxBytesToScanZIP then ScanBytesZIP := MaxBytesToScanZIP;
ExeFile.Seek(ExeFile.GetSize - ScanBytesZIP);
ExeFile.ReadExt(PBuffer^, ScanBytesZIP, QResult);
if QResult = ScanBytesZIP then
begin
ZipIDPos := RPos(PBuffer^, ScanBytesZIP, ZipIDCentral);
if ZipIDPos <> 0 then
begin
ZipIDFound := true;
ZipIDPos := ZipIDPos + ExeFile.GetSize - ScanBytesZIP - 1;
end;
end;
if ZipIDFound then
begin
FreeMem(PBuffer, ScanBytes);
ExeFile.Done;
Result := ScanZIPFile(Col, WholeFileSpec, ZipIDPos);
ArchiveType := atZip;
exit;
end;
if not ScanAlsoNonZipArchives then
begin
FreeMem(PBuffer, ScanBytes);
ExeFile.Done;
Result := false;
exit;
end;
// central dis not found, continue
ExeFile.Seek(0);
ExeFile.ReadExt(PBuffer^, ScanBytes, QResult);
if QResult = ScanBytes then
begin
// find position
ScanString[0] := #255;
BufScanPos := 0;
while (BufScanPos + 255) < ScanBytes do
begin
move(PBuffer^[BufScanPos], ScanString[1], 255);
ScanForIDFromLeft(ZipID, ZipIDFound, ZipIDPos);
ScanForIDFromLeft(ArjID, ArjIDFound, ArjIDPos);
ScanForIDFromLeft(RarID, RarIDFound, RarIDPos);
inc(BufScanPos, 250);
end;
end;
FreeMem(PBuffer, ScanBytes);
ExeFile.Done;
if ZipIDFound then
begin
Result := SlowScanZIPFile(Col, WholeFileSpec, ZipIDPos);
ArchiveType := atZip;
end;
if (Result) then exit;
if RarIDFound then
begin
Result := ScanRarFile(Col, WholeFileSpec, RarIDPos);
ArchiveType := atRar;
end;
if (Result) then exit;
if ArjIDFound then
begin
Result := ScanArjFile(Col, WholeFileSpec, ArjIDPos);
ArchiveType := atArj;
end;
if (Result) then exit;
Result := false;
except
on EQDirException do
Result := false;
end;
end;
//-----------------------------------------------------------------------------
begin
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 180540
////////////////////////////////////////////////////////////////////////////////
unit java.util.concurrent.ExecutorCompletionService;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JExecutorCompletionService = interface;
JExecutorCompletionServiceClass = interface(JObjectClass)
['{84934053-66D9-4B73-AFBF-E15865702803}']
function init(executor : JExecutor) : JExecutorCompletionService; cdecl; overload;// (Ljava/util/concurrent/Executor;)V A: $1
function init(executor : JExecutor; completionQueue : JBlockingQueue) : JExecutorCompletionService; cdecl; overload;// (Ljava/util/concurrent/Executor;Ljava/util/concurrent/BlockingQueue;)V A: $1
function poll : JFuture; cdecl; overload; // ()Ljava/util/concurrent/Future; A: $1
function poll(timeout : Int64; &unit : JTimeUnit) : JFuture; cdecl; overload;// (JLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/Future; A: $1
function submit(task : JCallable) : JFuture; cdecl; overload; // (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future; A: $1
function submit(task : JRunnable; result : JObject) : JFuture; cdecl; overload;// (Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/Future; A: $1
function take : JFuture; cdecl; // ()Ljava/util/concurrent/Future; A: $1
end;
[JavaSignature('java/util/concurrent/ExecutorCompletionService')]
JExecutorCompletionService = interface(JObject)
['{5FA022A3-FF87-455A-8A67-E3DF8348DAAE}']
function poll : JFuture; cdecl; overload; // ()Ljava/util/concurrent/Future; A: $1
function poll(timeout : Int64; &unit : JTimeUnit) : JFuture; cdecl; overload;// (JLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/Future; A: $1
function submit(task : JCallable) : JFuture; cdecl; overload; // (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future; A: $1
function submit(task : JRunnable; result : JObject) : JFuture; cdecl; overload;// (Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/Future; A: $1
function take : JFuture; cdecl; // ()Ljava/util/concurrent/Future; A: $1
end;
TJExecutorCompletionService = class(TJavaGenericImport<JExecutorCompletionServiceClass, JExecutorCompletionService>)
end;
implementation
end.
|
unit MyCat.Config.Model;
interface
uses
System.SysUtils;
type
// *
// * 系统基础配置项
// *
TSystemConfig = class
private const
DEFAULT_PORT: Integer = 8066;
DEFAULT_MANAGER_PORT: Integer = 9066;
DEFAULT_SQL_PARSER: string = 'druidparser';
DEFAULT_BUFFER_CHUNK_SIZE: SmallInt = 4096;
DEFAULT_BUFFER_POOL_PAGE_SIZE: Integer = 512 * 1024 * 4;
DEFAULT_BUFFER_POOL_PAGE_NUMBER: SmallInt = 64;
RESERVED_SYSTEM_MEMORY_BYTES: string = '384m';
MEMORY_PAGE_SIZE: string = '1m';
SPILLS_FILE_BUFFER_SIZE: string = '2K';
DATANODE_SORTED_TEMP_DIR: string = 'datanode';
// private int frontSocketSoRcvbuf = 1024 * 1024;
// private int frontSocketSoSndbuf = 4 * 1024 * 1024;
// private int backSocketSoRcvbuf = 4 * 1024 * 1024;// mysql 5.6
private
class var DEFAULT_CHARSET: TEncoding;
class var DEFAULT_PROCESSORS: Integer;
public const
SYS_HOME: string = 'MYCAT_HOME';
DEFAULT_POOL_SIZE: Integer = 128; // 保持后端数据通道的默认最大值
DEFAULT_IDLE_TIMEOUT: Int64 = 30 * 60 * 1000;
public
class constructor Create;
end;
// public final class SystemConfig {
//
// private int processorBufferLocalPercent;
// // net_buffer_length
// // defaut 4M
//
// private int backSocketSoSndbuf = 1024 * 1024;
// private int frontSocketNoDelay = 1; // 0=false
// private int backSocketNoDelay = 1; // 1=true
// private static final long DEFAULT_PROCESSOR_CHECK_PERIOD = 1 * 1000L;
// private static final long DEFAULT_DATANODE_IDLE_CHECK_PERIOD = 5 * 60 * 1000L;
// private static final long DEFAULT_DATANODE_HEARTBEAT_PERIOD = 10 * 1000L;
// private static final long DEFAULT_CLUSTER_HEARTBEAT_PERIOD = 5 * 1000L;
// private static final long DEFAULT_CLUSTER_HEARTBEAT_TIMEOUT = 10 * 1000L;
// private static final int DEFAULT_CLUSTER_HEARTBEAT_RETRY = 10;
// private static final int DEFAULT_MAX_LIMIT = 100;
// private static final String DEFAULT_CLUSTER_HEARTBEAT_USER = "_HEARTBEAT_USER_";
// private static final String DEFAULT_CLUSTER_HEARTBEAT_PASS = "_HEARTBEAT_PASS_";
// private static final int DEFAULT_PARSER_COMMENT_VERSION = 50148;
// private static final int DEFAULT_SQL_RECORD_COUNT = 10;
// private static final boolean DEFAULT_USE_ZK_SWITCH = false;
// private int maxStringLiteralLength = 65535;
// private int frontWriteQueueSize = 2048;
// private String bindIp = "0.0.0.0";
// private String fakeMySQLVersion = null;
// private int serverPort;
// private int managerPort;
// private String charset;
// private int processors;
// private int processorExecutor;
// private int timerExecutor;
// private int managerExecutor;
// private long idleTimeout;
// private int catletClassCheckSeconds = 60;
// // sql execute timeout (second)
// private long sqlExecuteTimeout = 300;
// private long processorCheckPeriod;
// private long dataNodeIdleCheckPeriod;
// private long dataNodeHeartbeatPeriod;
// private String clusterHeartbeatUser;
// private String clusterHeartbeatPass;
// private long clusterHeartbeatPeriod;
// private long clusterHeartbeatTimeout;
// private int clusterHeartbeatRetry;
// private int txIsolation;
// private int parserCommentVersion;
// private int sqlRecordCount;
//
// // a page size
// private int bufferPoolPageSize;
//
// //minimum allocation unit
// private short bufferPoolChunkSize;
//
// // buffer pool page number
// private short bufferPoolPageNumber;
//
// //大结果集阈值,默认512kb
// private int maxResultSet=512*1024;
// //大结果集拒绝策略次数过滤限制,默认10次
// private int bigResultSizeSqlCount=10;
// //大结果集拒绝策咯,bufferpool使用率阈值(0-100),默认80%
// private int bufferUsagePercent=80;
// //大结果集保护策咯,0:不开启,1:级别1为在当前mucat bufferpool
// //使用率大于bufferUsagePercent阈值时,拒绝超过defaultBigResultSizeSqlCount
// //sql次数阈值并且符合超过大结果集阈值maxResultSet的所有sql
// //默认值0
// private int flowControlRejectStrategy=0;
// //清理大结果集记录周期
// private long clearBigSqLResultSetMapMs=10*60*1000;
//
// private int defaultMaxLimit = DEFAULT_MAX_LIMIT;
// public static final int SEQUENCEHANDLER_LOCALFILE = 0;
// public static final int SEQUENCEHANDLER_MYSQLDB = 1;
// public static final int SEQUENCEHANDLER_LOCAL_TIME = 2;
// public static final int SEQUENCEHANDLER_ZK_DISTRIBUTED = 3;
// public static final int SEQUENCEHANDLER_ZK_GLOBAL_INCREMENT = 4;
// /*
// * 注意!!! 目前mycat支持的MySQL版本,如果后续有新的MySQL版本,请添加到此数组, 对于MySQL的其他分支,
// * 比如MariaDB目前版本号已经到10.1.x,但是其驱动程序仍然兼容官方的MySQL,因此这里版本号只需要MySQL官方的版本号即可。
// */
// public static final String[] MySQLVersions = { "5.5", "5.6", "5.7" };
// private int sequnceHandlerType = SEQUENCEHANDLER_LOCALFILE;
// private String sqlInterceptor = "io.mycat.server.interceptor.impl.DefaultSqlInterceptor";
// private String sqlInterceptorType = "select";
// private String sqlInterceptorFile = System.getProperty("user.dir")+"/logs/sql.txt";
// public static final int MUTINODELIMIT_SMALL_DATA = 0;
// public static final int MUTINODELIMIT_LAR_DATA = 1;
// private int mutiNodeLimitType = MUTINODELIMIT_SMALL_DATA;
//
// public static final int MUTINODELIMIT_PATCH_SIZE = 100;
// private int mutiNodePatchSize = MUTINODELIMIT_PATCH_SIZE;
//
// private String defaultSqlParser = DEFAULT_SQL_PARSER;
// private int usingAIO = 0;
// private int packetHeaderSize = 4;
// private int maxPacketSize = 16 * 1024 * 1024;
// private int mycatNodeId=1;
// private int useCompression =0;
// private int useSqlStat = 1;
// //子查询中存在关联查询的情况下,检查关联字段中是否有分片字段 .默认 false
// private boolean subqueryRelationshipCheck = false;
//
// // 是否使用HandshakeV10Packet来与client进行通讯, 1:是 , 0:否(使用HandshakePacket)
// // 使用HandshakeV10Packet为的是兼容高版本的jdbc驱动, 后期稳定下来考虑全部采用HandshakeV10Packet来通讯
// private int useHandshakeV10 = 0;
//
// //处理分布式事务开关,默认为不过滤分布式事务
// private int handleDistributedTransactions = 0;
//
// private int checkTableConsistency = 0;
// private long checkTableConsistencyPeriod = CHECKTABLECONSISTENCYPERIOD;
// private final static long CHECKTABLECONSISTENCYPERIOD = 1 * 60 * 1000;
//
// private int processorBufferPoolType = 0;
//
// // 全局表一致性检测任务,默认24小时调度一次
// private static final long DEFAULT_GLOBAL_TABLE_CHECK_PERIOD = 24 * 60 * 60 * 1000L;
// private int useGlobleTableCheck = 1; // 全局表一致性检查开关
//
// private long glableTableCheckPeriod;
//
// /**
// * Mycat 使用 Off Heap For Merge/Order/Group/Limit计算相关参数
// */
//
//
// /**
// * 是否启用Off Heap for Merge 1-启用,0-不启用
// */
// private int useOffHeapForMerge;
//
// /**
// *页大小,对应MemoryBlock的大小,单位为M
// */
// private String memoryPageSize;
//
//
// /**
// * DiskRowWriter写磁盘是临时写Buffer,单位为K
// */
// private String spillsFileBufferSize;
//
// /**
// * 启用结果集流输出,不经过merge模块,
// */
// private int useStreamOutput;
//
// /**
// * 该变量仅在Merge使用On Heap
// * 内存方式时起作用,如果使用Off Heap内存方式
// * 那么可以认为-Xmx就是系统预留内存。
// * 在On Heap上给系统预留的内存,
// * 主要供新小对象创建,JAVA简单数据结构使用
// * 以保证在On Heap上大结果集计算时情况,能快速响应其他
// * 连接操作。
// */
// private String systemReserveMemorySize;
//
// private String XARecoveryLogBaseDir;
//
// private String XARecoveryLogBaseName;
//
// /**
// * 排序时,内存不够时,将已经排序的结果集
// * 写入到临时目录
// */
// private String dataNodeSortedTempDir;
//
// /**
// * 是否启用zk切换
// */
// private boolean useZKSwitch=DEFAULT_USE_ZK_SWITCH;
//
//
// /**
// * huangyiming add
// * 无密码登陆标示, 0:否,1:是,默认为0
// */
// private int nonePasswordLogin = DEFAULT_NONEPASSWORDLOGIN ;
//
// private final static int DEFAULT_NONEPASSWORDLOGIN = 0;
//
// public String getDefaultSqlParser() {
// return defaultSqlParser;
// }
//
// public void setDefaultSqlParser(String defaultSqlParser) {
// this.defaultSqlParser = defaultSqlParser;
// }
//
// public SystemConfig() {
// this.serverPort = DEFAULT_PORT;
// this.managerPort = DEFAULT_MANAGER_PORT;
// this.charset = DEFAULT_CHARSET;
// this.processors = DEFAULT_PROCESSORS;
// this.bufferPoolPageSize = DEFAULT_BUFFER_POOL_PAGE_SIZE;
// this.bufferPoolChunkSize = DEFAULT_BUFFER_CHUNK_SIZE;
//
// /**
// * 大结果集时 需增大 network buffer pool pages.
// */
// this.bufferPoolPageNumber = (short) (DEFAULT_PROCESSORS*20);
//
// this.processorExecutor = (DEFAULT_PROCESSORS != 1) ? DEFAULT_PROCESSORS * 2 : 4;
// this.managerExecutor = 2;
//
// this.processorBufferLocalPercent = 100;
// this.timerExecutor = 2;
// this.idleTimeout = DEFAULT_IDLE_TIMEOUT;
// this.processorCheckPeriod = DEFAULT_PROCESSOR_CHECK_PERIOD;
// this.dataNodeIdleCheckPeriod = DEFAULT_DATANODE_IDLE_CHECK_PERIOD;
// this.dataNodeHeartbeatPeriod = DEFAULT_DATANODE_HEARTBEAT_PERIOD;
// this.clusterHeartbeatUser = DEFAULT_CLUSTER_HEARTBEAT_USER;
// this.clusterHeartbeatPass = DEFAULT_CLUSTER_HEARTBEAT_PASS;
// this.clusterHeartbeatPeriod = DEFAULT_CLUSTER_HEARTBEAT_PERIOD;
// this.clusterHeartbeatTimeout = DEFAULT_CLUSTER_HEARTBEAT_TIMEOUT;
// this.clusterHeartbeatRetry = DEFAULT_CLUSTER_HEARTBEAT_RETRY;
// this.txIsolation = Isolations.REPEATED_READ;
// this.parserCommentVersion = DEFAULT_PARSER_COMMENT_VERSION;
// this.sqlRecordCount = DEFAULT_SQL_RECORD_COUNT;
// this.glableTableCheckPeriod = DEFAULT_GLOBAL_TABLE_CHECK_PERIOD;
// this.useOffHeapForMerge = 1;
// this.memoryPageSize = MEMORY_PAGE_SIZE;
// this.spillsFileBufferSize = SPILLS_FILE_BUFFER_SIZE;
// this.useStreamOutput = 0;
// this.systemReserveMemorySize = RESERVED_SYSTEM_MEMORY_BYTES;
// this.dataNodeSortedTempDir = System.getProperty("user.dir");
// this.XARecoveryLogBaseDir = SystemConfig.getHomePath()+"/tmlogs/";
// this.XARecoveryLogBaseName ="tmlog";
// }
//
// public String getDataNodeSortedTempDir() {
// return dataNodeSortedTempDir;
// }
//
// public int getUseOffHeapForMerge() {
// return useOffHeapForMerge;
// }
//
// public void setUseOffHeapForMerge(int useOffHeapForMerge) {
// this.useOffHeapForMerge = useOffHeapForMerge;
// }
//
// public String getMemoryPageSize() {
// return memoryPageSize;
// }
//
// public void setMemoryPageSize(String memoryPageSize) {
// this.memoryPageSize = memoryPageSize;
// }
//
// public String getSpillsFileBufferSize() {
// return spillsFileBufferSize;
// }
//
// public void setSpillsFileBufferSize(String spillsFileBufferSize) {
// this.spillsFileBufferSize = spillsFileBufferSize;
// }
//
// public int getUseStreamOutput() {
// return useStreamOutput;
// }
//
// public void setUseStreamOutput(int useStreamOutput) {
// this.useStreamOutput = useStreamOutput;
// }
//
// public String getSystemReserveMemorySize() {
// return systemReserveMemorySize;
// }
//
// public void setSystemReserveMemorySize(String systemReserveMemorySize) {
// this.systemReserveMemorySize = systemReserveMemorySize;
// }
//
// public boolean isUseZKSwitch() {
// return useZKSwitch;
// }
//
// public void setUseZKSwitch(boolean useZKSwitch) {
// this.useZKSwitch = useZKSwitch;
// }
//
// public String getXARecoveryLogBaseDir() {
// return XARecoveryLogBaseDir;
// }
//
// public void setXARecoveryLogBaseDir(String XARecoveryLogBaseDir) {
// this.XARecoveryLogBaseDir = XARecoveryLogBaseDir;
// }
//
// public String getXARecoveryLogBaseName() {
// return XARecoveryLogBaseName;
// }
//
// public void setXARecoveryLogBaseName(String XARecoveryLogBaseName) {
// this.XARecoveryLogBaseName = XARecoveryLogBaseName;
// }
//
// public int getUseGlobleTableCheck() {
// return useGlobleTableCheck;
// }
//
// public void setUseGlobleTableCheck(int useGlobleTableCheck) {
// this.useGlobleTableCheck = useGlobleTableCheck;
// }
//
// public long getGlableTableCheckPeriod() {
// return glableTableCheckPeriod;
// }
//
// public void setGlableTableCheckPeriod(long glableTableCheckPeriod) {
// this.glableTableCheckPeriod = glableTableCheckPeriod;
// }
//
// public String getSqlInterceptor() {
// return sqlInterceptor;
// }
//
// public void setSqlInterceptor(String sqlInterceptor) {
// this.sqlInterceptor = sqlInterceptor;
// }
//
// public int getSequnceHandlerType() {
// return sequnceHandlerType;
// }
//
// public void setSequnceHandlerType(int sequnceHandlerType) {
// this.sequnceHandlerType = sequnceHandlerType;
// }
//
// public int getPacketHeaderSize() {
// return packetHeaderSize;
// }
//
// public void setPacketHeaderSize(int packetHeaderSize) {
// this.packetHeaderSize = packetHeaderSize;
// }
//
// public int getMaxPacketSize() {
// return maxPacketSize;
// }
//
// public int getCatletClassCheckSeconds() {
// return catletClassCheckSeconds;
// }
//
// public void setCatletClassCheckSeconds(int catletClassCheckSeconds) {
// this.catletClassCheckSeconds = catletClassCheckSeconds;
// }
//
// public void setMaxPacketSize(int maxPacketSize) {
// this.maxPacketSize = maxPacketSize;
// }
//
// public int getFrontWriteQueueSize() {
// return frontWriteQueueSize;
// }
//
// public void setFrontWriteQueueSize(int frontWriteQueueSize) {
// this.frontWriteQueueSize = frontWriteQueueSize;
// }
//
// public String getBindIp() {
// return bindIp;
// }
//
// public void setBindIp(String bindIp) {
// this.bindIp = bindIp;
// }
//
// public int getDefaultMaxLimit() {
// return defaultMaxLimit;
// }
//
// public void setDefaultMaxLimit(int defaultMaxLimit) {
// this.defaultMaxLimit = defaultMaxLimit;
// }
//
// public static String getHomePath() {
// String home = System.getProperty(SystemConfig.SYS_HOME);
// if (home != null
// && home.endsWith(File.pathSeparator)) {
// home = home.substring(0, home.length() - 1);
// System.setProperty(SystemConfig.SYS_HOME, home);
// }
//
// // MYCAT_HOME为空,默认尝试设置为当前目录或上级目录。BEN
// if(home == null) {
// try {
// String path = new File("..").getCanonicalPath().replaceAll("\\\\", "/");
// File conf = new File(path+"/conf");
// if(conf.exists() && conf.isDirectory()) {
// home = path;
// } else {
// path = new File(".").getCanonicalPath().replaceAll("\\\\", "/");
// conf = new File(path+"/conf");
// if(conf.exists() && conf.isDirectory()) {
// home = path;
// }
// }
//
// if (home != null) {
// System.setProperty(SystemConfig.SYS_HOME, home);
// }
// } catch (IOException e) {
// // 如出错,则忽略。
// }
// }
//
// return home;
// }
//
// // 是否使用SQL统计
// public int getUseSqlStat()
// {
// return useSqlStat;
// }
//
// public void setUseSqlStat(int useSqlStat)
// {
// this.useSqlStat = useSqlStat;
// }
//
// public int getUseCompression()
// {
// return useCompression;
// }
//
// public void setUseCompression(int useCompression)
// {
// this.useCompression = useCompression;
// }
//
// public String getCharset() {
// return charset;
// }
//
// public void setCharset(String charset) {
// this.charset = charset;
// }
//
// public String getFakeMySQLVersion() {
// return fakeMySQLVersion;
// }
//
// public void setFakeMySQLVersion(String mysqlVersion) {
// this.fakeMySQLVersion = mysqlVersion;
// }
//
// public int getServerPort() {
// return serverPort;
// }
//
// public void setServerPort(int serverPort) {
// this.serverPort = serverPort;
// }
//
// public int getManagerPort() {
// return managerPort;
// }
//
// public void setManagerPort(int managerPort) {
// this.managerPort = managerPort;
// }
//
// public int getProcessors() {
// return processors;
// }
//
// public void setProcessors(int processors) {
// this.processors = processors;
// }
//
// public int getProcessorExecutor() {
// return processorExecutor;
// }
//
// public void setProcessorExecutor(int processorExecutor) {
// this.processorExecutor = processorExecutor;
// }
//
// public int getManagerExecutor() {
// return managerExecutor;
// }
//
// public void setManagerExecutor(int managerExecutor) {
// this.managerExecutor = managerExecutor;
// }
//
// public int getTimerExecutor() {
// return timerExecutor;
// }
//
// public void setTimerExecutor(int timerExecutor) {
// this.timerExecutor = timerExecutor;
// }
//
// public long getIdleTimeout() {
// return idleTimeout;
// }
//
// public void setIdleTimeout(long idleTimeout) {
// this.idleTimeout = idleTimeout;
// }
//
// public long getProcessorCheckPeriod() {
// return processorCheckPeriod;
// }
//
// public void setProcessorCheckPeriod(long processorCheckPeriod) {
// this.processorCheckPeriod = processorCheckPeriod;
// }
//
// public long getDataNodeIdleCheckPeriod() {
// return dataNodeIdleCheckPeriod;
// }
//
// public void setDataNodeIdleCheckPeriod(long dataNodeIdleCheckPeriod) {
// this.dataNodeIdleCheckPeriod = dataNodeIdleCheckPeriod;
// }
//
// public long getDataNodeHeartbeatPeriod() {
// return dataNodeHeartbeatPeriod;
// }
//
// public void setDataNodeHeartbeatPeriod(long dataNodeHeartbeatPeriod) {
// this.dataNodeHeartbeatPeriod = dataNodeHeartbeatPeriod;
// }
//
// public String getClusterHeartbeatUser() {
// return clusterHeartbeatUser;
// }
//
// public void setClusterHeartbeatUser(String clusterHeartbeatUser) {
// this.clusterHeartbeatUser = clusterHeartbeatUser;
// }
//
// public long getSqlExecuteTimeout() {
// return sqlExecuteTimeout;
// }
//
// public void setSqlExecuteTimeout(long sqlExecuteTimeout) {
// this.sqlExecuteTimeout = sqlExecuteTimeout;
// }
//
// public String getClusterHeartbeatPass() {
// return clusterHeartbeatPass;
// }
//
// public void setClusterHeartbeatPass(String clusterHeartbeatPass) {
// this.clusterHeartbeatPass = clusterHeartbeatPass;
// }
//
// public long getClusterHeartbeatPeriod() {
// return clusterHeartbeatPeriod;
// }
//
// public void setClusterHeartbeatPeriod(long clusterHeartbeatPeriod) {
// this.clusterHeartbeatPeriod = clusterHeartbeatPeriod;
// }
//
// public long getClusterHeartbeatTimeout() {
// return clusterHeartbeatTimeout;
// }
//
// public void setClusterHeartbeatTimeout(long clusterHeartbeatTimeout) {
// this.clusterHeartbeatTimeout = clusterHeartbeatTimeout;
// }
//
// public int getFrontsocketsorcvbuf() {
// return frontSocketSoRcvbuf;
// }
//
// public int getFrontsocketsosndbuf() {
// return frontSocketSoSndbuf;
// }
//
// public int getBacksocketsorcvbuf() {
// return backSocketSoRcvbuf;
// }
//
// public int getBacksocketsosndbuf() {
// return backSocketSoSndbuf;
// }
//
// public int getClusterHeartbeatRetry() {
// return clusterHeartbeatRetry;
// }
//
// public void setClusterHeartbeatRetry(int clusterHeartbeatRetry) {
// this.clusterHeartbeatRetry = clusterHeartbeatRetry;
// }
//
// public int getTxIsolation() {
// return txIsolation;
// }
//
// public void setTxIsolation(int txIsolation) {
// this.txIsolation = txIsolation;
// }
//
// public int getParserCommentVersion() {
// return parserCommentVersion;
// }
//
// public void setParserCommentVersion(int parserCommentVersion) {
// this.parserCommentVersion = parserCommentVersion;
// }
//
// public int getSqlRecordCount() {
// return sqlRecordCount;
// }
//
// public void setSqlRecordCount(int sqlRecordCount) {
// this.sqlRecordCount = sqlRecordCount;
// }
//
//
// public short getBufferPoolChunkSize() {
// return bufferPoolChunkSize;
// }
//
// public void setBufferPoolChunkSize(short bufferPoolChunkSize) {
// this.bufferPoolChunkSize = bufferPoolChunkSize;
// }
//
// public int getMaxResultSet() {
// return maxResultSet;
// }
//
// public void setMaxResultSet(int maxResultSet) {
// this.maxResultSet = maxResultSet;
// }
//
// public int getBigResultSizeSqlCount() {
// return bigResultSizeSqlCount;
// }
//
// public void setBigResultSizeSqlCount(int bigResultSizeSqlCount) {
// this.bigResultSizeSqlCount = bigResultSizeSqlCount;
// }
//
// public int getBufferUsagePercent() {
// return bufferUsagePercent;
// }
//
// public void setBufferUsagePercent(int bufferUsagePercent) {
// this.bufferUsagePercent = bufferUsagePercent;
// }
//
// public int getFlowControlRejectStrategy() {
// return flowControlRejectStrategy;
// }
//
// public void setFlowControlRejectStrategy(int flowControlRejectStrategy) {
// this.flowControlRejectStrategy = flowControlRejectStrategy;
// }
//
// public long getClearBigSqLResultSetMapMs() {
// return clearBigSqLResultSetMapMs;
// }
//
// public void setClearBigSqLResultSetMapMs(long clearBigSqLResultSetMapMs) {
// this.clearBigSqLResultSetMapMs = clearBigSqLResultSetMapMs;
// }
//
// public int getBufferPoolPageSize() {
// return bufferPoolPageSize;
// }
//
// public void setBufferPoolPageSize(int bufferPoolPageSize) {
// this.bufferPoolPageSize = bufferPoolPageSize;
// }
//
// public short getBufferPoolPageNumber() {
// return bufferPoolPageNumber;
// }
//
// public void setBufferPoolPageNumber(short bufferPoolPageNumber) {
// this.bufferPoolPageNumber = bufferPoolPageNumber;
// }
//
// public int getFrontSocketSoRcvbuf() {
// return frontSocketSoRcvbuf;
// }
//
// public void setFrontSocketSoRcvbuf(int frontSocketSoRcvbuf) {
// this.frontSocketSoRcvbuf = frontSocketSoRcvbuf;
// }
//
// public int getFrontSocketSoSndbuf() {
// return frontSocketSoSndbuf;
// }
//
// public void setFrontSocketSoSndbuf(int frontSocketSoSndbuf) {
// this.frontSocketSoSndbuf = frontSocketSoSndbuf;
// }
//
// public int getBackSocketSoRcvbuf() {
// return backSocketSoRcvbuf;
// }
//
// public void setBackSocketSoRcvbuf(int backSocketSoRcvbuf) {
// this.backSocketSoRcvbuf = backSocketSoRcvbuf;
// }
//
// public int getBackSocketSoSndbuf() {
// return backSocketSoSndbuf;
// }
//
// public void setBackSocketSoSndbuf(int backSocketSoSndbuf) {
// this.backSocketSoSndbuf = backSocketSoSndbuf;
// }
//
// public int getFrontSocketNoDelay() {
// return frontSocketNoDelay;
// }
//
// public void setFrontSocketNoDelay(int frontSocketNoDelay) {
// this.frontSocketNoDelay = frontSocketNoDelay;
// }
//
// public int getBackSocketNoDelay() {
// return backSocketNoDelay;
// }
//
// public void setBackSocketNoDelay(int backSocketNoDelay) {
// this.backSocketNoDelay = backSocketNoDelay;
// }
//
// public int getMaxStringLiteralLength() {
// return maxStringLiteralLength;
// }
//
// public void setMaxStringLiteralLength(int maxStringLiteralLength) {
// this.maxStringLiteralLength = maxStringLiteralLength;
// }
//
// public int getMutiNodeLimitType() {
// return mutiNodeLimitType;
// }
//
// public void setMutiNodeLimitType(int mutiNodeLimitType) {
// this.mutiNodeLimitType = mutiNodeLimitType;
// }
//
// public int getMutiNodePatchSize() {
// return mutiNodePatchSize;
// }
//
// public void setMutiNodePatchSize(int mutiNodePatchSize) {
// this.mutiNodePatchSize = mutiNodePatchSize;
// }
//
// public int getProcessorBufferLocalPercent() {
// return processorBufferLocalPercent;
// }
//
// public void setProcessorBufferLocalPercent(int processorBufferLocalPercent) {
// this.processorBufferLocalPercent = processorBufferLocalPercent;
// }
//
// public String getSqlInterceptorType() {
// return sqlInterceptorType;
// }
//
// public void setSqlInterceptorType(String sqlInterceptorType) {
// this.sqlInterceptorType = sqlInterceptorType;
// }
//
// public String getSqlInterceptorFile() {
// return sqlInterceptorFile;
// }
//
// public void setSqlInterceptorFile(String sqlInterceptorFile) {
// this.sqlInterceptorFile = sqlInterceptorFile;
// }
//
// public int getUsingAIO() {
// return usingAIO;
// }
//
// public void setUsingAIO(int usingAIO) {
// this.usingAIO = usingAIO;
// }
//
// public int getMycatNodeId() {
// return mycatNodeId;
// }
//
// public void setMycatNodeId(int mycatNodeId) {
// this.mycatNodeId = mycatNodeId;
// }
//
// @Override
// public String toString() {
// return "SystemConfig [processorBufferLocalPercent="
// + processorBufferLocalPercent + ", frontSocketSoRcvbuf="
// + frontSocketSoRcvbuf + ", frontSocketSoSndbuf="
// + frontSocketSoSndbuf + ", backSocketSoRcvbuf="
// + backSocketSoRcvbuf + ", backSocketSoSndbuf="
// + backSocketSoSndbuf + ", frontSocketNoDelay="
// + frontSocketNoDelay + ", backSocketNoDelay="
// + backSocketNoDelay + ", maxStringLiteralLength="
// + maxStringLiteralLength + ", frontWriteQueueSize="
// + frontWriteQueueSize + ", bindIp=" + bindIp + ", serverPort="
// + serverPort + ", managerPort=" + managerPort + ", charset="
// + charset + ", processors=" + processors
// + ", processorExecutor=" + processorExecutor
// + ", timerExecutor=" + timerExecutor + ", managerExecutor="
// + managerExecutor + ", idleTimeout=" + idleTimeout
// + ", catletClassCheckSeconds=" + catletClassCheckSeconds
// + ", sqlExecuteTimeout=" + sqlExecuteTimeout
// + ", processorCheckPeriod=" + processorCheckPeriod
// + ", dataNodeIdleCheckPeriod=" + dataNodeIdleCheckPeriod
// + ", dataNodeHeartbeatPeriod=" + dataNodeHeartbeatPeriod
// + ", clusterHeartbeatUser=" + clusterHeartbeatUser
// + ", clusterHeartbeatPass=" + clusterHeartbeatPass
// + ", clusterHeartbeatPeriod=" + clusterHeartbeatPeriod
// + ", clusterHeartbeatTimeout=" + clusterHeartbeatTimeout
// + ", clusterHeartbeatRetry=" + clusterHeartbeatRetry
// + ", txIsolation=" + txIsolation + ", parserCommentVersion="
// + parserCommentVersion + ", sqlRecordCount=" + sqlRecordCount
// + ", bufferPoolPageSize=" + bufferPoolPageSize
// + ", bufferPoolChunkSize=" + bufferPoolChunkSize
// + ", bufferPoolPageNumber=" + bufferPoolPageNumber
// + ", maxResultSet=" +maxResultSet
// + ", bigResultSizeSqlCount="+bigResultSizeSqlCount
// + ", bufferUsagePercent="+bufferUsagePercent
// + ", flowControlRejectStrategy="+flowControlRejectStrategy
// + ", clearBigSqLResultSetMapMs="+clearBigSqLResultSetMapMs
// + ", defaultMaxLimit=" + defaultMaxLimit
// + ", sequnceHandlerType=" + sequnceHandlerType
// + ", sqlInterceptor=" + sqlInterceptor
// + ", sqlInterceptorType=" + sqlInterceptorType
// + ", sqlInterceptorFile=" + sqlInterceptorFile
// + ", mutiNodeLimitType=" + mutiNodeLimitType
// + ", mutiNodePatchSize=" + mutiNodePatchSize
// + ", defaultSqlParser=" + defaultSqlParser
// + ", usingAIO=" + usingAIO
// + ", packetHeaderSize=" + packetHeaderSize
// + ", maxPacketSize=" + maxPacketSize
// + ", mycatNodeId=" + mycatNodeId + "]";
// }
//
//
// public int getCheckTableConsistency() {
// return checkTableConsistency;
// }
//
// public void setCheckTableConsistency(int checkTableConsistency) {
// this.checkTableConsistency = checkTableConsistency;
// }
//
// public long getCheckTableConsistencyPeriod() {
// return checkTableConsistencyPeriod;
// }
//
// public void setCheckTableConsistencyPeriod(long checkTableConsistencyPeriod) {
// this.checkTableConsistencyPeriod = checkTableConsistencyPeriod;
// }
//
// public int getProcessorBufferPoolType() {
// return processorBufferPoolType;
// }
//
// public void setProcessorBufferPoolType(int processorBufferPoolType) {
// this.processorBufferPoolType = processorBufferPoolType;
// }
//
// public int getHandleDistributedTransactions() {
// return handleDistributedTransactions;
// }
//
// public void setHandleDistributedTransactions(int handleDistributedTransactions) {
// this.handleDistributedTransactions = handleDistributedTransactions;
// }
//
// public int getUseHandshakeV10() {
// return useHandshakeV10;
// }
//
// public void setUseHandshakeV10(int useHandshakeV10) {
// this.useHandshakeV10 = useHandshakeV10;
// }
//
// public int getNonePasswordLogin() {
// return nonePasswordLogin;
// }
//
// public void setNonePasswordLogin(int nonePasswordLogin) {
// this.nonePasswordLogin = nonePasswordLogin;
// }
//
// public boolean isSubqueryRelationshipCheck() {
// return subqueryRelationshipCheck;
// }
//
// public void setSubqueryRelationshipCheck(boolean subqueryRelationshipCheck) {
// this.subqueryRelationshipCheck = subqueryRelationshipCheck;
// }
//
//
// }
TDBHostConfig = class
private
FIdleTimeout: Int64; // 连接池中连接空闲超时时间
FHostName: string;
FIP: String;
FPort: Integer;
FUrl: String;
FUser: String;
FPassWord: String;
FEncryptPassWord: String; // 密文
FMaxConn: Integer;
FMinConn: Integer;
FDBType: string;
FFilters: String;
FLogTime: Int64;
FWeight: Integer;
public
constructor Create(HostName: string; IP: string; Port: Integer; Url: string;
User: String; PassWord: String; EncryptPassWord: String);
end;
// public class DBHostConfig {
//
//
// public String getDbType() {
// return dbType;
// }
//
// public void setDbType(String dbType) {
// this.dbType = dbType;
// }
//
// public DBHostConfig() {
// super();
// this.hostName = hostName;
// this.ip = ip;
// this.port = port;
// this.url = url;
// this.user = user;
// this.password = password;
// this.encryptPassword = encryptPassword;
// }
//
// public long getIdleTimeout() {
// return idleTimeout;
// }
//
// public void setIdleTimeout(long idleTimeout) {
// this.idleTimeout = idleTimeout;
// }
//
// public int getMaxCon() {
// return maxCon;
// }
//
// public void setMaxCon(int maxCon) {
// this.maxCon = maxCon;
// }
//
// public int getMinCon() {
// return minCon;
// }
//
// public void setMinCon(int minCon) {
// this.minCon = minCon;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public String getIp() {
// return ip;
// }
//
// public int getPort() {
// return port;
// }
//
// public String getUrl() {
// return url;
// }
//
// public String getUser() {
// return user;
// }
// public String getFilters() {
// return filters;
// }
//
// public void setFilters(String filters) {
// this.filters = filters;
// }
// public String getPassword() {
// return password;
// }
//
// public long getLogTime() {
// return logTime;
// }
//
// public void setLogTime(long logTime) {
// this.logTime = logTime;
// }
//
// public int getWeight() {
// return weight;
// }
//
// public void setWeight(int weight) {
// this.weight = weight;
// }
//
// public String getEncryptPassword() {
// return this.encryptPassword;
// }
//
// @Override
// public String toString() {
// return "DBHostConfig [hostName=" + hostName + ", url=" + url + "]";
// }
//
// }
// *
// * Datahost is a group of DB servers which is synchronized with each other
// *
TDataHostConfig = class
public const
NOT_SWITCH_DS: Integer = -1;
DEFAULT_SWITCH_DS: Integer = 1;
SYN_STATUS_SWITCH_DS: Integer = 2;
CLUSTER_STATUS_SWITCH_DS: Integer = 3;
end;
// public class DataHostConfig {
// private static final Pattern pattern = Pattern.compile("\\s*show\\s+slave\\s+status\\s*",Pattern.CASE_INSENSITIVE);
// private static final Pattern patternCluster = Pattern.compile("\\s*show\\s+status\\s+like\\s+'wsrep%'",Pattern.CASE_INSENSITIVE);
// private String name;
// private int maxCon = SystemConfig.DEFAULT_POOL_SIZE;
// private int minCon = 10;
// private int balance = PhysicalDBPool.BALANCE_NONE;
// private int writeType = PhysicalDBPool.WRITE_ONLYONE_NODE;
// private final String dbType;
// private final String dbDriver;
// private final DBHostConfig[] writeHosts;
// private final Map<Integer, DBHostConfig[]> readHosts;
// private String hearbeatSQL;
// private boolean isShowSlaveSql=false;
// private boolean isShowClusterSql=false;
// private String connectionInitSql;
// private int slaveThreshold = -1;
// private final int switchType;
// private String filters="mergeStat";
// private long logTime=300000;
// private boolean tempReadHostAvailable = false; //如果写服务挂掉, 临时读服务是否继续可用
// private final Set<String> dataNodes; //包含的所有dataNode名字
// private String slaveIDs;
// private int maxRetryCount = 3; // 心跳失败时候重试的次数. @auth zwy
// public DataHostConfig(String name, String dbType, String dbDriver,
// DBHostConfig[] writeHosts, Map<Integer, DBHostConfig[]> readHosts,int switchType,int slaveThreshold, boolean tempReadHostAvailable) {
// super();
// this.name = name;
// this.dbType = dbType;
// this.dbDriver = dbDriver;
// this.writeHosts = writeHosts;
// this.readHosts = readHosts;
// this.switchType=switchType;
// this.slaveThreshold=slaveThreshold;
// this.tempReadHostAvailable = tempReadHostAvailable;
// this.dataNodes = new HashSet<>();
// }
//
// public boolean isTempReadHostAvailable() {
// return this.tempReadHostAvailable;
// }
//
// public int getSlaveThreshold() {
// return slaveThreshold;
// }
//
// public void setSlaveThreshold(int slaveThreshold) {
// this.slaveThreshold = slaveThreshold;
// }
//
// public int getSwitchType() {
// return switchType;
// }
//
// public String getConnectionInitSql()
// {
// return connectionInitSql;
// }
//
// public void setConnectionInitSql(String connectionInitSql)
// {
// this.connectionInitSql = connectionInitSql;
// }
//
// public int getWriteType() {
// return writeType;
// }
//
// public void setWriteType(int writeType) {
// this.writeType = writeType;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public boolean isShowSlaveSql()
// {
// return isShowSlaveSql;
// }
//
// public int getMaxCon() {
// return maxCon;
// }
//
// public void setMaxCon(int maxCon) {
// this.maxCon = maxCon;
// }
//
// public int getMinCon() {
// return minCon;
// }
//
// public void setMinCon(int minCon) {
// this.minCon = minCon;
// }
//
// public String getSlaveIDs() {
// return slaveIDs;
// }
//
// public void setSlaveIDs(String slaveIDs) {
// this.slaveIDs = slaveIDs;
// }
//
// public int getBalance() {
// return balance;
// }
//
// public void setBalance(int balance) {
// this.balance = balance;
// }
//
// public String getDbType() {
// return dbType;
// }
//
// public String getDbDriver() {
// return dbDriver;
// }
//
// public DBHostConfig[] getWriteHosts() {
// return writeHosts;
// }
//
// public Map<Integer, DBHostConfig[]> getReadHosts() {
// return readHosts;
// }
//
// public String getHearbeatSQL() {
// return hearbeatSQL;
// }
//
// public void setHearbeatSQL(String heartbeatSQL) {
// this.hearbeatSQL = heartbeatSQL;
// Matcher matcher = pattern.matcher(heartbeatSQL);
// if (matcher.find())
// {
// isShowSlaveSql=true;
// }
// Matcher matcher2 = patternCluster.matcher(heartbeatSQL);
// if (matcher2.find())
// {
// isShowClusterSql=true;
// }
// }
//
// public String getFilters() {
// return filters;
// }
//
// public void setFilters(String filters) {
// this.filters = filters;
// }
//
// public long getLogTime() {
// return logTime;
// }
//
// public boolean isShowClusterSql() {
// return this.isShowClusterSql;
// }
//
// public void setLogTime(long logTime) {
// this.logTime = logTime;
// }
//
// public void addDataNode(String name){
// this.dataNodes.add(name);
// }
//
// public String getRandomDataNode() {
// int index = (int) (Math.random() * dataNodes.size());
// return Iterables.get(dataNodes,index);
// }
//
// public boolean containDataNode(String randomDn) {
// return dataNodes.contains(randomDn);
// }
//
// public int getMaxRetryCount() {
// return maxRetryCount;
// }
//
// public void setMaxRetryCount(int maxRetryCount) {
// this.maxRetryCount = maxRetryCount;
// }
//
// }
implementation
{ TDBHostConfig }
constructor TDBHostConfig.Create(HostName, IP: string; Port: Integer;
Url, User, PassWord, EncryptPassWord: String);
begin
FIdleTimeout := TSystemConfig.DEFAULT_IDLE_TIMEOUT; // 连接池中连接空闲超时时间
FFilters := 'MergeStat';
FLogTime := 300000;
end;
{ TSystemConfig }
class constructor TSystemConfig.Create;
begin
DEFAULT_CHARSET := TEncoding.UTF8;
DEFAULT_PROCESSORS := CPUCount;
end;
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 182852
////////////////////////////////////////////////////////////////////////////////
unit android.text.Layout_Alignment;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JLayout_Alignment = interface;
JLayout_AlignmentClass = interface(JObjectClass)
['{3F3E9E33-D367-4D06-9ECE-4A3216E2AA0F}']
function _GetALIGN_CENTER : JLayout_Alignment; cdecl; // A: $4019
function _GetALIGN_NORMAL : JLayout_Alignment; cdecl; // A: $4019
function _GetALIGN_OPPOSITE : JLayout_Alignment; cdecl; // A: $4019
function valueOf(&name : JString) : JLayout_Alignment; cdecl; // (Ljava/lang/String;)Landroid/text/Layout$Alignment; A: $9
function values : TJavaArray<JLayout_Alignment>; cdecl; // ()[Landroid/text/Layout$Alignment; A: $9
property ALIGN_CENTER : JLayout_Alignment read _GetALIGN_CENTER; // Landroid/text/Layout$Alignment; A: $4019
property ALIGN_NORMAL : JLayout_Alignment read _GetALIGN_NORMAL; // Landroid/text/Layout$Alignment; A: $4019
property ALIGN_OPPOSITE : JLayout_Alignment read _GetALIGN_OPPOSITE; // Landroid/text/Layout$Alignment; A: $4019
end;
[JavaSignature('android/text/Layout_Alignment')]
JLayout_Alignment = interface(JObject)
['{E3A84940-2CD7-4B93-8A87-79488715E8F5}']
end;
TJLayout_Alignment = class(TJavaGenericImport<JLayout_AlignmentClass, JLayout_Alignment>)
end;
implementation
end.
|
unit ufrmSupplierType;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMaster, ufraFooter5Button, StdCtrls, ExtCtrls, ActnList,
uConn, uRetnoUnit, DB, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxEdit, cxNavigator, cxDBData, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, System.Actions, ufrmMasterBrowse, dxBarBuiltInMenu,
cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, ufraFooter4Button,
cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxPC,
Datasnap.DBClient, uDMClient;
type
TfrmSupplierType = class(TfrmMasterBrowse)
cxGridViewColumn1: TcxGridDBColumn;
cxGridViewColumn2: TcxGridDBColumn;
cxGridViewColumn3: TcxGridDBColumn;
cxGridViewColumn4: TcxGridDBColumn;
cxGridViewColumn5: TcxGridDBColumn;
cxGridViewColumn6: TcxGridDBColumn;
cxGridViewColumn7: TcxGridDBColumn;
cxGridViewColumn8: TcxGridDBColumn;
cxGridViewColumn9: TcxGridDBColumn;
procedure actAddExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
private
FCDSBrowse: TClientDataset;
property CDSBrowse: TClientDataset read FCDSBrowse write FCDSBrowse;
public
procedure RefreshData; override;
{ Public declarations }
end;
var
frmSupplierType: TfrmSupplierType;
implementation
uses uTSCommonDlg, Math, uConstanta, uDXUtils,
uDBUtils, uModSuplier, ufrmDialogSupplierType;
{$R *.dfm}
procedure TfrmSupplierType.actAddExecute(Sender: TObject);
begin
inherited;
ShowDialogForm(TfrmDialogSupplierType)
end;
procedure TfrmSupplierType.actEditExecute(Sender: TObject);
begin
inherited;
ShowDialogForm(TfrmDialogSupplierType,
cxGridView.DS.FieldByName('REF$TIPE_SUPLIER_ID').AsString)
end;
procedure TfrmSupplierType.RefreshData;
begin
CDSBrowse := TDBUtils.DSToCDS(
DMClient.DSProviderClient.TipeSuplier_GetDSOverview(),self);
cxGridView.LoadFromCDS(CDSBrowse);
end;
end.
|
unit DesignClip;
interface
uses
Windows, Classes;
type
TDesignComponentClipboard = class
protected
Stream: TMemoryStream;
procedure Close;
procedure Open;
procedure ReadError(Reader: TReader; const Message: string;
var Handled: Boolean);
public
function GetComponent: TComponent;
procedure CloseRead;
procedure CloseWrite;
procedure OpenRead;
procedure OpenWrite;
procedure SetComponent(inComponent: TComponent);
end;
//
TDesignComponentClipboardReader = class(TDesignComponentClipboard)
public
constructor Create;
destructor Destroy; override;
end;
//
TDesignComponentClipboardWriter = class(TDesignComponentClipboard)
public
constructor Create;
destructor Destroy; override;
end;
function DesignLoadComponentFromBinaryStream(inStream: TStream;
inComp: TComponent; inOnError: TReaderError): TComponent;
procedure DesignSaveComponentToBinaryStream(inStream: TStream;
inComp: TComponent);
procedure DesignCopyStreamFromClipboard(inFmt: Cardinal; inS: TStream);
procedure DesignCopyStreamToClipboard(inFmt: Cardinal; inS: TStream);
implementation
uses
SysUtils, Clipbrd, DesignUtils;
var
CF_COMPONENTSTREAM: Cardinal;
procedure DesignSaveComponentToBinaryStream(inStream: TStream;
inComp: TComponent);
var
ms: TMemoryStream;
sz: Int64;
begin
ms := TMemoryStream.Create;
try
ms.WriteComponent(inComp);
ms.Position := 0;
sz := ms.Size;
inStream.Write(sz, 8);
inStream.CopyFrom(ms, sz);
finally
ms.Free;
end;
end;
function DesignLoadComponentFromBinaryStream(inStream: TStream;
inComp: TComponent; inOnError: TReaderError): TComponent;
var
ms: TMemoryStream;
sz: Int64;
begin
inStream.Read(sz, 8);
ms := TMemoryStream.Create;
try
ms.CopyFrom(inStream, sz);
ms.Position := 0;
with TReader.Create(ms, 4096) do
try
OnError := inOnError;
Result := ReadRootComponent(inComp);
finally
Free;
end;
finally
ms.Free;
end;
end;
procedure DesignCopyStreamToClipboard(inFmt: Cardinal; inS: TStream);
var
hMem: THandle;
pMem: Pointer;
begin
inS.Position := 0;
hMem := GlobalAlloc(GHND or GMEM_DDESHARE, inS.Size);
if hMem <> 0 then
begin
pMem := GlobalLock(hMem);
if pMem <> nil then
begin
inS.Read(pMem^, inS.Size);
inS.Position := 0;
GlobalUnlock(hMem);
Clipboard.Open;
try
Clipboard.SetAsHandle(inFmt, hMem);
finally
Clipboard.Close;
end;
end
else begin
GlobalFree(hMem);
OutOfMemoryError;
end;
end else
OutOfMemoryError;
end;
procedure DesignCopyStreamFromClipboard(inFmt: Cardinal; inS: TStream);
var
hMem: THandle;
pMem: Pointer;
begin
hMem := Clipboard.GetAsHandle(inFmt);
if hMem <> 0 then
begin
pMem := GlobalLock(hMem);
if pMem <> nil then
begin
inS.Write(pMem^, GlobalSize(hMem));
inS.Position := 0;
GlobalUnlock(hMem);
end;
end;
end;
{ TDesignComponentClipboard }
procedure TDesignComponentClipboard.Close;
begin
Stream.Free;
Clipboard.Close;
end;
procedure TDesignComponentClipboard.CloseRead;
begin
Close;
end;
procedure TDesignComponentClipboard.CloseWrite;
begin
DesignCopyStreamToClipboard(CF_COMPONENTSTREAM, Stream);
Close;
end;
function TDesignComponentClipboard.GetComponent: TComponent;
begin
if Stream.Position < Stream.Size then
Result := DesignLoadComponentFromBinaryStream(Stream, nil, ReadError)
else
Result := nil;
end;
procedure TDesignComponentClipboard.Open;
begin
Clipboard.Open;
Stream := TMemoryStream.Create;
end;
procedure TDesignComponentClipboard.OpenRead;
begin
Open;
DesignCopyStreamFromClipboard(CF_COMPONENTSTREAM, Stream);
end;
procedure TDesignComponentClipboard.OpenWrite;
begin
Open;
end;
procedure TDesignComponentClipboard.ReadError(Reader: TReader;
const Message: string; var Handled: Boolean);
begin
Handled := true;
end;
procedure TDesignComponentClipboard.SetComponent(inComponent: TComponent);
begin
DesignSaveComponentToBinaryStream(Stream, inComponent);
end;
{ TDesignComponentClipboardReader }
constructor TDesignComponentClipboardReader.Create;
begin
OpenRead;
end;
destructor TDesignComponentClipboardReader.Destroy;
begin
CloseRead;
inherited;
end;
{ TDesignComponentClipboardWriter }
constructor TDesignComponentClipboardWriter.Create;
begin
OpenWrite;
end;
destructor TDesignComponentClipboardWriter.Destroy;
begin
CloseWrite;
inherited;
end;
initialization
{ The following string should not be localized }
CF_COMPONENTSTREAM := RegisterClipboardFormat('Delphi Components');
end.
|
(*
Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES
Original name: 0016.PAS
Description: RANDOM2.PAS (Like TP6)
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:53
*)
{ MR> I have started playing With Borland Turbo Pascal 7.0 and I have a
MR> problem. The Random routine is not the same as the one in TP 6.0.
MR> Using the same RandSeed, they generate different series of numbers.
MR> I have a couple of applications that depend upon the number series
MR> generated by the TP 6.0 version. Can anyone supply me With the
MR> algorithm used in the TP 6.0 Random routine? or maybe point me in
MR> the right direction? I want to Construct my own TP 7 Random routine
MR> that will behave as the one in TP 6.
The way both generators work is to update System.Randseed, then calculate the
new random value from that one. There have been several different ways to
calculate the value; I think TP 6 is different from TP 5.5, and TP 7 is
different again. The update algorithm has been pretty Constant.
As I recall, you can simulate the TP 6 Random(N) Function in TP 7 as follows:
}
Function TP6Random(N:Word):Word;
Var
junk : Word;
myrandseed : Record
lo, hi : Word
end Absolute system.randseed;
begin
junk := Random(0); { Update Randseed }
TP6Random := myrandseed.hi mod N;
end;
{
You might want to keep the following around in Case the update algorithm gets
changed sometime in the future:
Demonstration Program to show how the TP 6.0 random number generator
updates System.Randseed. Allows the seed to be cycled backwards. }
Procedure CycleRandseed(cycles:Integer);
{ For cycles > 0, mimics cycles calls to the TP random number generator.
For cycles < 0, backs it up the given number of calls. }
Var
i : Integer;
begin
if cycles > 0 then
For i := 1 to cycles do
system.randseed := system.randseed*134775813 + 1
else
For i := -1 downto cycles do
system.randseed := (system.randseed-1)*(-649090867);
end;
Var
i : Integer;
begin
randomize;
Writeln('Forwards:');
For i:=1 to 5 do
Writeln(random);
Writeln('Backwards:');
For i:=1 to 5 do
begin
CycleRandseed(-1); { Back to previous value }
Writeln(random); { Show it }
CycleRandseed(-1); { Back up over it again }
end;
end.
|
unit Config;
interface
uses Classes, SysUtils, IniFiles;
Procedure LoadCgf();
type
ServerConfig = record
ServerName: String;
ServerIP: String;
ServerPort: Integer;
Level_Seed: Integer;
Max_Players: Integer;
ServerSalt: String;
end;
var
Cgf: ServerConfig;
implementation
Procedure LoadCgf();
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini');
if FileExists('config.ini') = True then
begin
Cgf.ServerName := IniFile.ReadString('Server Configuration', 'ServerName',
'A MCDelphi Server');
Cgf.ServerIP := IniFile.ReadString('Server Configuration', 'ServerIP',
'127.0.0.1');
Cgf.ServerPort := StrToInt(IniFile.ReadString('Server Configuration',
'ServerPort', '7777'));
Cgf.Level_Seed := StrToInt(IniFile.ReadString('Server Configuration',
'Level_Seed', '476'));
Cgf.Max_Players := StrToInt(IniFile.ReadString('Server Configuration',
'Max_Players', '1000'));
Cgf.ServerSalt := IniFile.ReadString('Server Configuration', 'ServerSalt',
'dtryb5rty6vst');
end
else
begin
IniFile.WriteString('Server Configuration', 'ServerName,',
'A MCDelphi Server');
IniFile.WriteString('Server Configuration', 'ServerIP', '127.0.0.1');
IniFile.WriteString('Server Configuration', 'ServerPort', '7777');
IniFile.WriteString('Server Configuration', 'Level_Seed', '4574');
IniFile.WriteString('Server Configuration', 'Max_Players', '1000');
IniFile.WriteString('Server Configuration', 'ServerSalt', 'dtryb5rty6vst');
IniFile.UpdateFile;
end;
end;
end.
|
{..............................................................................}
{ Summary Deleting Cross Sheet Connectors and replacing them with Ports }
{ }
{ Copyright (c) 2008 by Altium Limited }
{..............................................................................}
{..............................................................................}
Procedure ReplaceCrossSheetsWithPorts;
Var
OldCrossConn : ISch_CrossSheetConnector;
CrossConn : ISch_CrossSheetConnector;
Port : ISch_Port;
CurrentSheet : ISch_Document;
Iterator : ISch_Iterator;
Begin
// Obtain the schematic server interface.
If SchServer = Nil Then Exit;
// Then obtain the current schematic sheet interface.
CurrentSheet := SchServer.GetCurrentSchDocument;
If CurrentSheet = Nil Then Exit;
// Initialize the robots in Schematic editor.
SchServer.ProcessControl.PreProcess(CurrentSheet, '');
// Set up iterator to look for Port objects only
Iterator := CurrentSheet.SchIterator_Create;
If Iterator = Nil Then Exit;
Iterator.AddFilter_ObjectSet(MkSet(eCrossSheetConnector));
Try
CrossConn := Iterator.FirstSchObject;
While CrossConn <> Nil Do
Begin
OldCrossConn := CrossConn;
//create a new port object to replace this cross sheet connector.
Port := SchServer.SchObjectFactory(ePort,eCreate_GlobalCopy);
If Port = Nil Then Exit;
// grab CrossConn location and pass onto the new port's location
Port.Location := CrossConn.Location;
// Port alignment is determined by the CrossConnector's Style.
If CrossConn.CrossSheetStyle = eCrossSheetRight Then
Port.Alignment := eRightAlign
Else
Port.Alignment := eLeftAlign;
// assume port.IOType is Bidirectional;
Port.IOType := ePortBidirectional;
// Port Style determined by CrossConn orientation.
If CrossConn.Orientation = eRotate0 Then Port.Style := ePortRight;
If CrossConn.Orientation = eRotate90 Then Port.Style := ePortTop;
If CrossConn.Orientation = eRotate180 Then Port.Style := ePortLeft;
If CrossConn.Orientation = eRotate270 Then Port.Style := ePortBottom;
// Assume Width of 500 Mils =
Port.Width := MilsToCoord(500);
// assume white for area and black for text
Port.AreaColor := $FFFFFF;
Port.TextColor := $0;
//Port Netname = Cross Sheet Connector's Text property.
Port.Name := CrossConn.Text;
// Add a port object onto the existing schematic document
CurrentSheet.RegisterSchObjectInContainer(Port);
CrossConn := Iterator.NextSchObject;
CurrentSheet.RemoveSchObject(OldCrossConn);
SchServer.RobotManager.SendMessage(CurrentSheet.I_ObjectAddress,c_BroadCast,
SCHM_PrimitiveRegistration,OldCrossConn.I_ObjectAddress);
End;
Finally
CurrentSheet.SchIterator_Destroy(Iterator);
End;
// Clean up robots in Schematic editor.
SchServer.ProcessControl.PostProcess(CurrentSheet, '');
// Refresh the screen
CurrentSheet.GraphicallyInvalidate;
End;
{..............................................................................}
{..............................................................................}
|
unit uMpsPub_R;
interface
uses
SysUtils, Classes, DB,
ComCtrls,DBClient;
{
接口名称:生产版基类公用接口
时间: 2010-2-8
编写: 许志祥
}
type
PTreeNode=^TreeNode;
TreeNode=Record
ID: string;
isReport: Boolean;
end;
type
IproducePub=interface
['{964D2911-56C5-494E-9131-CE9B0CA0E255}']
function SaveBill:Boolean; //保存单据
function Audit:Boolean; //审核单据
function UAudit:Boolean; //反审核
function DelBill:Boolean; //删除单据
end;
function getID(l, str: string): integer;//获取树节点
procedure LoadTree(len:string;query:TClientDataSet; tree: TTreeview;root:string;ty:Integer=0);//加载树形图
function getStringPval(src:string;index:integer):string;
function DelStringPval(var src:string;index:integer):string;
implementation
//删除字符串指定位置字符---
function DelStringPval(var src:string;index:integer):string;
var list:TstringList;
len,p,i:integer;
begin
result:='';
list:=TstringList.Create;
try
len:=length(src);
p:=1;
while p<len do
begin
if char(src[p])<=#128 then
begin
list.Add(string(src[p]));
inc(p);
end
else
begin
list.Add(copy(src,p,2));
p:=p+2;
end;
end;
if index<=list.Count then
begin
list[index-1]:='';
for i:=0 to list.Count-1 do
result:=result+trim(list[i]);
//showmessage(result);
end;
finally
list.Free;
end;
end;
//获取字符串指定位置字符---
function getStringPval(src:string;index:integer):string;
var list:TstringList;
len,p:integer;
begin
result:='';
list:=TstringList.Create;
try
len:=length(src);
p:=1;
while p<len do
begin
if char(src[p])<=#128 then
begin
list.Add(string(src[p]));
inc(p);
end
else
begin
list.Add(copy(src,p,2));
p:=p+2;
end;
end;
if index<=list.Count then
begin
result:=list[index-1];
end;
finally
list.Free;
end;
end;
//--------------获取树节点------------------------------------------------------
function getID(l, str: string): integer;
var i,k,p:integer;
begin
p:=0;
k:=0;
for i:=1 to length(l) do
begin
k:=k+strtoint(l[i]);
if length(str)=k then
begin
p:=i;
break;
end;
end;
result:=p;
end;
//----------------------------加载树形图----------------------------------------
procedure LoadTree(len:string;query:TClientDataSet; tree: TTreeview;root:string;ty:Integer=0);
var p,lev:integer;
node:array [0..4] of Ttreenode;
id:PTreeNode;
rootNode:Ttreenode;
begin
if root='' then exit;
tree.Items.Clear;
rootNode:=tree.Items.add(tree.TopItem,root);
rootNode.StateIndex:=4;
rootNode.ImageIndex:=4;
rootNode.SelectedIndex:=5;
lev:=0;
node[lev]:=tree.Items[0];
query.First;
while not query.Eof do
begin
p:=getID(len,query.fieldbyname('treeid').AsString);
lev:=p;
if Ty=0 then
node[lev]:=tree.Items.AddChild(node[lev-1],query.Fields[1].AsString+'('+query.fieldbyname('treeid').AsString+')')
else
begin
node[lev]:=tree.Items.AddChild(node[lev-1],query.Fields[1].AsString);
end;
new(id);
id^.ID:=trim(query.fieldbyname('treeid').AsString);
if query.FindField('Report_ID') <> nil then
id^.isReport := trim(query.fieldbyname('Report_ID').AsString) <> '';
//showmessage(str^);
if id<>nil then
node[lev].Data:=id;
node[lev].StateIndex:=4;
node[lev].ImageIndex:=4;
node[lev].SelectedIndex:=5;
if id^.isReport then
begin
node[lev].StateIndex:=6;
node[lev].ImageIndex:=6;
node[lev].SelectedIndex:=7;
end;
//freemem(str,SizeOf(str));
query.Next;
end;
tree.FullCollapse;
if tree.Items[0] <>nil then
tree.Items[0].Expanded:=True;
end;
end.
|
unit uFrmMensagem;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Buttons, ExtCtrls, StdCtrls, BCPanel;
type
TIcone = (tiErro, tiAviso, tiDuvida, tiInformacao);
{ TfrmMensagem }
TfrmMensagem = class(TForm)
btnOk: TBitBtn;
btnCancelar: TBitBtn;
iconeAviso: TImage;
iconeDuvida: TImage;
iconeInformacao: TImage;
iconeErro: TImage;
imgLogoTitulo: TImage;
imglstFrmMensagem: TImageList;
lblMensagem: TLabel;
pnlFrmMensagem: TBCPanel;
pnlTitulo: TBCPanel;
procedure btnCancelarClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure lblMensagemResize(Sender: TObject);
procedure pnlTituloMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure pnlTituloMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure pnlTituloMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
private
public
resultadoBtn: TModalResult;
procedure InfoFormMensagem(titulo: string; icone: TIcone; mensagem: string);
end;
var
frmMensagem: TfrmMensagem;
capitura : boolean = false;
px, py : integer;
implementation
{$R *.lfm}
{ TfrmMensagem }
procedure TfrmMensagem.btnCancelarClick(Sender: TObject);
begin
resultadoBtn := mrNo;
end;
procedure TfrmMensagem.btnOkClick(Sender: TObject);
begin
resultadoBtn := mrOK;
end;
procedure TfrmMensagem.lblMensagemResize(Sender: TObject);
begin
if lblMensagem.Height > 70 then
Self.Height := Self.Height + (lblMensagem.Height - 70);
end;
procedure TfrmMensagem.pnlTituloMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
capitura := true;
if capitura then
begin
px := X;
py := Y;
end;
end;
procedure TfrmMensagem.pnlTituloMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if capitura then
begin
Left := (Left + X) - px;
Top := (Top + Y) - py;
end;
end;
procedure TfrmMensagem.pnlTituloMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
capitura := false;
end;
procedure TfrmMensagem.InfoFormMensagem(titulo: string; icone: TIcone; mensagem: string);
begin
case icone of
tiErro: begin
iconeErro.Visible := true;
btnOk.Left := 236;
btnCancelar.Visible := false;
btnOk.Caption := 'OK';
end;
tiAviso: begin
iconeAviso.Visible := true;
btnOk.Left := 236;
btnCancelar.Visible := false;
btnOk.Caption := 'OK';
end;
tiDuvida : begin
iconeDuvida.Visible := true;
btnOk.Left := 160;
btnCancelar.Visible := true;
btnOk.Caption := 'Sim';
btnCancelar.Caption := 'Não';
end;
tiInformacao : begin
iconeInformacao.Visible := true;
btnOk.Left := 236;
btnCancelar.Visible := false;
btnOk.Caption := 'OK';
end;
end;
lblMensagem.Caption := mensagem;
pnlTitulo.Caption := titulo;
Self.ShowModal;
end;
end.
|
unit UFiles;
interface
implementation
uses
UHistory, SysUtils;
procedure readHistory();
var
historyFile: file of THistoryCell;
historyCell: THistoryCell;
begin
AssignFile(historyFile, 'results.dat');
if FileExists('results.dat') then
begin
Reset(historyFile);
while not eof(historyFile) do
begin
read(historyFile, historyCell);
addHistoryItem(historyCell);
end;
end
else
Rewrite(historyFile);
CloseFile(historyFile);
end;
procedure saveHistory();
var
historyFile: file of THistoryCell;
historyArray: THistoryArray;
i: Integer;
begin
AssignFile(historyFile, 'results.dat');
Rewrite(historyFile);
historyArray := returnHistory;
for i := 0 to length(historyArray) - 1 do
begin
write(historyFile, historyArray[i]);
end;
CloseFile(historyFile);
end;
initialization
readHistory();
finalization
saveHistory();
end.
|
unit Dialog_ViewProd;
//YXC_2010_04_23_21_39_33
//显示产品列表
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, RzPanel, RzSplit, Grids, BaseGrid, AdvGrid,
ElXPThemedControl, ElTree, StdCtrls,Class_Dict,Class_Rend,Class_Cate,
Class_Prod, AdvObj;
type
TDialogViewProd = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
RzSplitter1: TRzSplitter;
Panel3: TPanel;
Panel4: TPanel;
Tree_Cate: TElTree;
AdvGrid: TAdvStringGrid;
Button1: TButton;
Button2: TButton;
Image1: TImage;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Tree_CateClick(Sender: TObject);
procedure AdvGridGetAlignment(Sender: TObject; ARow, ACol: Integer;
var HAlign: TAlignment; var VAlign: TVAlignment);
procedure AdvGridCanEditCell(Sender: TObject; ARow, ACol: Integer;
var CanEdit: Boolean);
private
FEditCode:Integer;
FDictRule:TDict;
protected
procedure SetInitialize;
procedure SetCommonParams;
procedure SetAdvGridParams;
public
procedure RendTreeItem;
procedure FillAdvGrid(AStrs:TStringList);
function ExportStrsProd:TStringList;
end;
var
DialogViiewProd: TDialogViewProd;
function FuncViewProd(AEditCode:Integer;ADictRule:TDict;var AStrsProd:TStringList):Integer;
implementation
uses
ConstValue,UtilLib,UtilLib_UiLib;
{$R *.dfm}
function FuncViewProd(AEditCode:Integer;ADictRule:TDict;var AStrsProd:TStringList):Integer;
begin
try
DialogViiewProd:=TDialogViewProd.Create(nil);
DialogViiewProd.FEditCode:=AEditCode;
DialogViiewProd.FDictRule:=ADictRule;
Result:=DialogViiewProd.ShowModal;
if Result=Mrok then
begin
AStrsProd:=DialogViiewProd.ExportStrsProd;
end;
finally
FreeAndNil(DialogViiewProd);
end;
end;
procedure TDialogViewProd.Button2Click(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TDialogViewProd.Button1Click(Sender: TObject);
begin
if GetAdvGridCheckCount(AdvGrid)=0 then
begin
ShowMessage('请选择套餐');
Exit;
end;
ModalResult:=mrOk;
end;
procedure TDialogViewProd.SetAdvGridParams;
begin
with AdvGrid do
begin
ColWidths[0]:=40;
ColWidths[1]:=40;
end;
end;
procedure TDialogViewProd.SetCommonParams;
begin
Caption:='产品选择';
end;
procedure TDialogViewProd.SetInitialize;
begin
SetCommonParams;
SetAdvGridParams;
RendTreeItem;
end;
procedure TDialogViewProd.FormCreate(Sender: TObject);
begin
UtilLib_UiLib.SetCommonDialogParams(Self);
UtilLib_UiLib.SetCommonAdvGridParams(AdvGrid);
end;
procedure TDialogViewProd.FormShow(Sender: TObject);
begin
SetInitialize;
end;
procedure TDialogViewProd.RendTreeItem;
var
AStrs:TStringList;
ASQL :string;
begin
ASQL:='SELECT * FROM TBL_CATE WHERE UNIT_LINK=%S AND CATE_KIND=%S ORDER BY UNIT_LINK,CATE_LEVL';
ASQL:=Format(ASQL,[QuotedStr(CONST_CODELINK),QuotedStr(FDictRule.DictCode)]);
AStrs:=TCate.StrsDB(ASQL);
TRend.RendCate(Tree_Cate,AStrs);
end;
procedure TDialogViewProd.Tree_CateClick(Sender: TObject);
var
ASQL:string;
Cate:TCate;
Strs:TStringList;
begin
if Tree_Cate.Selected=nil then Exit;
Cate:=TCate(Tree_Cate.Selected.Data);
if Cate=nil then Exit;
ASQL:='SELECT * FROM TBL_PROD WHERE UNIT_LINK=%S AND PROD_CATE LIKE %S ';
ASQL:=Format(ASQL,[QuotedStr(CONST_CODELINK),QuotedStr(Cate.CodeLink+'%')]);
Strs:=TProd.StrsDB(ASQL);
FillAdvGrid(Strs);
end;
procedure TDialogViewProd.FillAdvGrid(AStrs: TStringList);
var
I :Integer;
Idex:Integer;
AObj:TProd;
begin
UtilLib.ClearAdvGrid(AdvGrid,1);
if (AStrs=nil) or (AStrs.Count=0) then Exit;
UtilLib.ClearAdvGrid(AdvGrid,AStrs.Count);
with AdvGrid do
begin
BeginUpdate;
for I:=0 to AStrs.Count -1 do
begin
Idex:=I+1;
AObj:=TProd(AStrs.Objects[I]);
Ints[0,Idex] :=Idex;
Objects[0,Idex]:=AObj;
AddCheckBox(1,Idex,False,False);
Cells[2,Idex] :=AObj.ProdName;
Cells[3,Idex] :=AObj.ProdCode;
Cells[4,Idex] :=FloatToStr(AObj.ProdCost);
Cells[5,Idex] :=AObj.ProdVirt;
Cells[6,Idex] :=AObj.ProdMemo;
end;
EndUpdate;
end;
end;
procedure TDialogViewProd.AdvGridGetAlignment(Sender: TObject; ARow,
ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
begin
if ARow=0 then
begin
HAlign:=taCenter;
end else
if (ARow>0) and (ACol in [0,1]) then
begin
HAlign:=taCenter;
end else
if (ARow>0) and (ACol =4) then
begin
HAlign:=taRightJustify;
end;
end;
procedure TDialogViewProd.AdvGridCanEditCell(Sender: TObject; ARow,
ACol: Integer; var CanEdit: Boolean);
begin
CanEdit:=ACol =1;
end;
function TDialogViewProd.ExportStrsProd: TStringList;
var
I:Integer;
State:Boolean;
AObj :TProd;
begin
Result:=TStringList.Create;
with AdvGrid do
begin
for I:=1 to RowCount-1 do
begin
State:=False;
GetCheckBoxState(1,I,State);
if State then
begin
AObj:=TProd(Objects[0,I]);
Result.AddObject(AObj.ProdName,AObj);
end;
end;
end;
end;
end.
|
unit SDUCheckLst;
// Description: TCheckListBox with ReadOnly property
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
CheckLst;
type
TSDUCheckListBox = class(TCheckListBox)
private
FReadOnly: boolean;
protected
procedure SetReadOnly(ro: boolean);
procedure ClickCheck(); override;
public
procedure SwapItems(a: integer; b: integer);
procedure SelectedMoveUp();
procedure SelectedMoveDown();
procedure SelectedDelete();
procedure SelectedChecked(value: boolean);
published
property ReadOnly: boolean read FReadOnly write SetReadOnly;
end;
procedure Register;
implementation
uses
Classes, Graphics;
procedure Register;
begin
RegisterComponents('SDeanUtils', [TSDUCheckListBox]);
end;
procedure TSDUCheckListBox.SetReadOnly(ro: boolean);
begin
FReadOnly := ro;
Enabled := not(FReadOnly);
if FReadOnly then
begin
Color := clBtnFace;
end
else
begin
Color := clWindow;
end;
end;
procedure TSDUCheckListBox.ClickCheck();
var
i: integer;
begin
if FReadOnly then
begin
for i:=0 to (items.count-1) do
begin
if Selected[i] then
begin
Checked[i] := not(Checked[i]);
end;
end;
end
else
begin
inherited;
end;
end;
procedure TSDUCheckListBox.SwapItems(a: integer; b: integer);
var
tempItem: string;
tempObj: TObject;
tempSelected: boolean;
tempEnabled: boolean;
tempChecked: boolean;
begin
Items.BeginUpdate;
try
tempItem := self.Items[a];
tempObj := self.Items.Objects[a];
tempSelected := self.Selected[a];
tempEnabled := self.ItemEnabled[a];
tempChecked := self.Checked[a];
self.Items[a] := self.Items[b];
self.Items.Objects[a] := self.Items.Objects[b];
self.Selected[a] := self.Selected[b];
self.ItemEnabled[a] := self.ItemEnabled[b];
self.Checked[a] := self.Checked[b];
self.Items[b] := tempItem;
self.Items.Objects[b] := tempObj;
self.Selected[b] := tempSelected;
self.ItemEnabled[b] := tempEnabled;
self.Checked[b] := tempChecked;
finally
Items.EndUpdate
end;
end;
procedure TSDUCheckListBox.SelectedMoveUp();
var
i: integer;
begin
// Start from 1 - can't move the first item up
for i:=1 to (items.count-1) do
begin
if selected[i] then
begin
SwapItems(i, (i-1));
end;
end;
end;
procedure TSDUCheckListBox.SelectedMoveDown();
var
i: integer;
begin
// -2 because we can't move the last item down
for i:=(items.count-2) downto 0 do
begin
if selected[i] then
begin
SwapItems(i, (i+1));
end;
end;
end;
procedure TSDUCheckListBox.SelectedDelete();
var
i: integer;
begin
for i:=(items.count-1) downto 0 do
begin
if selected[i] then
begin
Items.Delete(i);
end;
end;
end;
procedure TSDUCheckListBox.SelectedChecked(value: boolean);
var
i: integer;
begin
for i:=(items.count-1) downto 0 do
begin
if selected[i] then
begin
Checked[i] := value;
end;
end;
end;
END.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.