text stringlengths 14 6.51M |
|---|
unit TestThItemImage;
interface
uses
TestFramework, BaseTestUnit, FMX.Types, FMX.Forms, System.Classes, FMX.Platform,
System.UITypes, System.Types, System.SysUtils, FMX.Controls, System.UIConsts;
type
// #18 캔버스에 사각형을 추가한다.
TestTThImage = class(TThCanvasBaseTestUnit)
protected
procedure CreateObject; override;
published
procedure TestItemFactory;
// #222 로컬의 이미지를 선택하여 로드한다.
procedure TestAddImage;
{$IFDEF RELEASE}
procedure TestAddSelectImage;
// #223 이미지 추가 시 경로 미선택 시 추가가 취소되어야 한다.
procedure TestAddSelectImageCancel;
{$ENDIF}
// #224 이미지 추가 시 중앙에 위치해야 한다.
procedure TestAddImageCenterPosition;
end;
implementation
uses
DebugUtils,
FMX.TestLib, ThItem, ThImageItem, ThItemFactory, ThConsts, ThTypes, FMX.Dialogs;
var
TestImagePath: string;
{ TestTThImage }
procedure TestTThImage.CreateObject;
begin
inherited;
if TestImagePath <> '' then
Exit;
TestImagePath := GetImagePath;
end;
procedure TestTThImage.TestItemFactory;
var
Item: TThItem;
begin
// Not assigned number 0
Item := ItemFactory.Get(0);
try
Check(not Assigned(Item));
finally
if Assigned(Item) then
Item.Free;
end;
// 2000 is Image
Item := ItemFactory.Get(ItemFactoryIDImageFile, TThFileItemData.Create(TestImagePath));
try
Check(Assigned(Item));
finally
if Assigned(Item) then
Item.Free;
end;
end;
procedure TestTThImage.TestAddImage;
begin
Check(FCanvas.ItemCount = 0);
FCanvas.AppendFileItem(ItemFactoryIDImageFile, TestImagePath);
Check(FCanvas.ItemCount = 1);
end;
{$IFDEF RELEASE}
procedure TestTThImage.TestAddSelectImage;
var
ServiceIntf: IInterface;
thread: TThread;
begin
// Clipboard에 추가
if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, ServiceIntf) then
(ServiceIntf as IFMXClipboardService).SetClipboard(TestImagePath);
thread := TThread.CreateAnonymousThread(
procedure
var
I: Integer;
begin
for I := 0 to 20 do
begin
Sleep(1000);
TestLib.RunKeyPress([vkControl, Ord('V')]);
TestLib.RunKeyPress([vkReturn]);
if FCanvas.ItemCount > 0 then
Break;
end;
end
);
thread.FreeOnTerminate := False;
thread.Start;
FCanvas.AppendFileItem(ItemFactoryIDImageFile);
thread.WaitFor;
thread.Terminate;
thread.Free;
Check(FCanvas.ItemCount = 1);
TestLib.RunMouseClick(150, 150);
CheckNotNull(FCanvas.SelectedItem);
Check(TThImageItem(FCanvas.SelectedItem).Bitmap.Width > 0);
end;
procedure TestTThImage.TestAddSelectImageCancel;
var
ServiceIntf: IInterface;
thread: TThread;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, ServiceIntf) then
(ServiceIntf as IFMXClipboardService).SetClipboard(TestImagePath);
thread := TThread.CreateAnonymousThread(
procedure
var
I: Integer;
begin
for I := 0 to 20 do
begin
Sleep(100);
TestLib.RunKeyPress([vkEscape]);
end;
end
);
thread.FreeOnTerminate := False;
thread.Start;
FCanvas.AppendFileItem(ItemFactoryIDImageFile);
thread.WaitFor;
thread.Terminate;
thread.Free;
Application.ProcessMessages;
Check(FCanvas.ItemCount = 0);
end;
{$ENDIF}
procedure TestTThImage.TestAddImageCenterPosition;
begin
FCanvas.AppendFileItem(ItemFactoryIDImageFile, TestImagePath);
TestLib.RunMouseClick(10, 10);
CheckNull(FCanvas.SelectedItem);
TestLib.RunMouseClick(150, 150);
CheckNotNull(FCanvas.SelectedItem);
end;
initialization
RegisterTest(TestTThImage.Suite);
end.
|
unit API_MVC;
interface
uses
System.Classes,
System.SysUtils,
System.Generics.Collections,
Vcl.Forms;
type
TModelAbstract = class;
TModelClass = class of TModelAbstract;
TViewAbstract = class;
TViewAbstractClass = class of TViewAbstract;
TControllerAbstract = class;
TControllerClass = class of TControllerAbstract;
TProc = procedure of object;
TEventListener = procedure(aEventMsg: string) of object;
// Model
TModelAbstract = class abstract
protected
FData: TDictionary<string, variant>;
FObjData: TObjectDictionary<string, TObject>;
FOnEvent: TEventListener;
//FProc: TProc;
procedure CreateEvent(aEventMsg: string);
public
procedure Execute; virtual; abstract;
constructor Create(aData: TDictionary<string, variant>;
aObjData: TObjectDictionary<string, TObject>); virtual;
property OnEvent: TEventListener read FOnEvent write FOnEvent;
//property Proc: TProc read FProc write FProc;
end;
// View
/// <summary>
/// Base View Class in MVC pattern.
/// </summary>
TViewAbstract = class abstract(TForm)
private
FIsMainForm: Boolean;
protected
FController: TControllerAbstract;
FControllerClass: TControllerClass;
procedure InitMVC; virtual; abstract;
procedure InitView; virtual; abstract;
procedure SendMessage(aMsg: string);
procedure FreeAfterClose(Sender: TObject; var Action: TCloseAction);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{$M+}
// Controller
TControllerAbstract = class abstract
protected
FData: TDictionary<string, variant>;
{FObjData: TObjectDictionary<string, TObject>;}
FMainView: TViewAbstract;
procedure PerfomViewMessage(aMsg: string); virtual; abstract;
procedure EventListener(aEventMsg: string); virtual; abstract;
procedure CallView(aViewAbstractClass: TViewAbstractClass; aIsModal: Boolean = false);
procedure CallModel(aModelClass: TModelClass; aProcName: string = ''; aIsAsync: Boolean = False); virtual;
procedure CallAsyncModel(aModelClass: TModelClass; aProcName: string = '');
public
procedure ReceiveViewMessage(aMsg: string);
constructor Create(aMainView: TViewAbstract); virtual;
destructor Destroy; override;
end;
{$M-}
implementation
procedure TControllerAbstract.CallAsyncModel(aModelClass: TModelClass; aProcName: string = '');
begin
CallModel(aModelClass, aProcName, True);
end;
procedure TModelAbstract.CreateEvent(aEventMsg: string);
begin
if Assigned(FOnEvent) then
FOnEvent(aEventMsg);
end;
constructor TModelAbstract.Create(aData: TDictionary<string, variant>;
aObjData: TObjectDictionary<string, TObject>);
begin
FData := aData;
FObjData := aObjData;
end;
destructor TControllerAbstract.Destroy;
begin
FData.Free;
{FObjData.Free;}
inherited;
end;
procedure TControllerAbstract.CallModel(aModelClass: TModelClass; aProcName: string = ''; aIsAsync: Boolean = False);
var
Model: TModelAbstract;
ModelProc: TProc;
begin
Model := aModelClass.Create(FData, FObjData);
try
Model.OnEvent := EventListener;
if aProcName = '' then
Model.Execute
else
begin
TMethod(ModelProc).Code := Model.MethodAddress(aProcName);
TMethod(ModelProc).Data := Model;
if Assigned(ModelProc) then
ModelProc;
end;
finally
if not aIsAsync then FreeAndNil(Model);
end;
end;
procedure TViewAbstract.FreeAfterClose(Sender: TObject; var Action: TCloseAction);
begin
Release;
{SendMessage(Self.Name + 'Closed');}
end;
procedure TControllerAbstract.CallView(aViewAbstractClass: TViewAbstractClass; aIsModal: Boolean = false);
var
View: TViewAbstract;
begin
View := aViewAbstractClass.Create(FMainView);
if aIsModal then
View.ShowModal
else
View.Show;
end;
procedure TControllerAbstract.ReceiveViewMessage(aMsg: string);
var
ControllerProc: TProc;
begin
TMethod(ControllerProc).Code := Self.MethodAddress(aMsg);
TMethod(ControllerProc).Data := Self;
if Assigned(ControllerProc) then
ControllerProc
else
PerfomViewMessage(aMsg);
end;
procedure TViewAbstract.SendMessage(aMsg: string);
begin
FController.ReceiveViewMessage(aMsg);
end;
constructor TControllerAbstract.Create(aMainView: TViewAbstract);
begin
FMainView := aMainView;
FData := TDictionary<string, variant>.Create;
{FObjData := TObjectDictionary<string, TObject>.Create;}
end;
constructor TViewAbstract.Create(AOwner: TComponent);
begin
inherited;
InitView;
if AOwner is TViewAbstract then
begin
Self.FController := TViewAbstract(AOwner).FController;
Self.OnClose := Self.FreeAfterClose;
end;
if not Assigned(FController) then
begin
FIsMainForm := True;
Self.InitMVC;
FController := FControllerClass.Create(TViewAbstract(Self));
end;
end;
destructor TViewAbstract.Destroy;
begin
if FIsMainForm then
begin
FController.Free;
end;
inherited;
end;
end.
|
unit Invoice.Controller.WinInfo.Default;
interface
uses Invoice.Controller.Interfaces, Winapi.Windows, Winapi.Messages, System.SysUtils;
type
TControllerWinInfoDefault = class(TInterfacedObject, iControllerWinInfoDefault)
private
FUserName: String;
FComputerName: String;
public
constructor Create;
destructor Destroy; Override;
class function New: iControllerWinInfoDefault;
function UserName: String;
function ComputerName: String;
end;
implementation
{ TControllerWinInfoDefault }
function GetWindowsComputerName: String;
var
Name: Array [0 .. 255] of Char;
NameSize: Dword;
begin
NameSize := SizeOf(Name);
if not GetComputerName(Name, NameSize) then
Name[0] := #0;
Result := StrPas(Name);
end;
function GetWindowsUserName: String;
var
Name: Array [0 .. 255] of Char;
NameSize: Dword;
begin
NameSize := SizeOf(Name);
if not GetUserName(Name, NameSize) then
Name[0] := #0;
result := StrPas(Name);
end;
constructor TControllerWinInfoDefault.Create;
begin
FUserName := GetWindowsUserName;
FComputerName := GetWindowsComputerName;
end;
destructor TControllerWinInfoDefault.Destroy;
begin
inherited;
end;
class function TControllerWinInfoDefault.New: iControllerWinInfoDefault;
begin
Result := Self.Create;
end;
function TControllerWinInfoDefault.UserName: String;
begin
Result := FUserName;
end;
function TControllerWinInfoDefault.ComputerName: String;
begin
Result := FComputerName;
end;
end.
|
unit LogSaleDeadbeat;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls, Mask, ToolEdit, uDBFunc, uMessageDlgExt,
uCommonForm,uOilQuery,Ora, uOilStoredProc{$IFDEF VER150},Variants{$ENDIF};
type
TSaleToDeadbeat = record
OldOrgId, OldOrgInst : integer;
OldOrgIsDebetor : boolean;
NewOrgId, NewOrgInst : integer;
NewOrgName : string;
NewOrgIsDebetor : boolean;
Sale_id, Sale_inst : integer;
Table_name : string;
end;
TLogSaleDeadbeatForm = class(TCommonForm)
Label4: TLabel;
edtSaleType: TEdit;
Label1: TLabel;
xdeSaleDate: TDateEdit;
Label2: TLabel;
Label5: TLabel;
edtOrg: TEdit;
edtRespondent: TEdit;
Label3: TLabel;
edtInstructor: TEdit;
lblWarning: TLabel;
Panel1: TPanel;
Panel3: TPanel;
bbOk: TBitBtn;
bbCancel: TBitBtn;
Label6: TLabel;
procedure bbOkClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
SaleToDeadbeat : TSaleToDeadbeat;
end;
procedure ClearSaleToDeadbeat(var V : TSaleToDeadbeat);
procedure SwitchDeadbeatToN;
procedure MarkDeadbeat(org_id, org_inst : integer; summa : real);
Function ConfirmSaleToDeadbeat(SaleToDeadbeat : TSaleToDeadbeat):boolean;
procedure DeleteSaleFromLog(Sale_id,Sale_inst,inst : integer; table_name : string);
procedure InitOldOrg(pOrg_id, pOrg_inst : integer; pOrgName : string;
pSale_id, pSale_inst : integer; pTable_name : string;
var SaleToDeadbeat : TSaleToDeadbeat);
function InitNewOrg(pOrg_id, pOrg_inst : integer; pOrgName : string;
pSale_id, pSale_inst : integer; pTable_name : string;
var SaleToDeadbeat : TSaleToDeadbeat; pShowMessage : boolean = True) : boolean;
var
LogSaleDeadbeatForm: TLogSaleDeadbeatForm;
implementation
uses Main;
{$R *.DFM}
procedure ClearSaleToDeadbeat(var V : TSaleToDeadbeat);
Begin
V.OldOrgId := 0;
V.OldOrgInst := 0;
V.OldOrgIsDebetor := False;
V.NewOrgId := 0;
V.NewOrgInst := 0;
V.NewOrgName := '';
V.NewOrgIsDebetor := False;
V.Sale_id := 0;
V.Sale_inst := 0;
V.Table_name := '';
End;
Function ConfirmSaleToDeadbeat(SaleToDeadbeat : TSaleToDeadbeat):boolean;
var LogForm : TLogSaleDeadbeatForm;
DelLog, Confirm : boolean;
Begin
Result := True;
if (SaleToDeadbeat.NewOrgId=0) and (SaleToDeadbeat.NewOrgInst=0) and
((SaleToDeadbeat.OldOrgId<>0) or (SaleToDeadbeat.OldOrgInst<>0))
then InitNewOrg(SaleToDeadbeat.OldOrgId, SaleToDeadbeat.OldOrgInst,
SaleToDeadbeat.NewOrgName,
SaleToDeadbeat.Sale_id, SaleToDeadbeat.Sale_inst,
SaleToDeadbeat.Table_name, SaleToDeadbeat, False);
DelLog := not SaleToDeadbeat.OldOrgIsDebetor and SaleToDeadbeat.NewOrgIsDebetor
or
SaleToDeadbeat.OldOrgIsDebetor and SaleToDeadbeat.NewOrgIsDebetor and
((SaleToDeadbeat.OldOrgId<>SaleToDeadbeat.NewOrgId) or
(SaleToDeadbeat.OldOrgInst<>SaleToDeadbeat.NewOrgInst))
or
SaleToDeadbeat.OldOrgIsDebetor and not SaleToDeadbeat.NewOrgIsDebetor;
Confirm := not SaleToDeadbeat.OldOrgIsDebetor and SaleToDeadbeat.NewOrgIsDebetor
or
SaleToDeadbeat.OldOrgIsDebetor and SaleToDeadbeat.NewOrgIsDebetor and
((SaleToDeadbeat.OldOrgId<>SaleToDeadbeat.NewOrgId) or
(SaleToDeadbeat.OldOrgInst<>SaleToDeadbeat.NewOrgInst));
if DelLog
then DeleteSaleFromLog(SaleToDeadbeat.Sale_id, SaleToDeadbeat.Sale_inst,
REAL_INST,SaleToDeadbeat.Table_name);
if Confirm
then Begin
LogForm := TLogSaleDeadbeatForm.Create(nil);
LogForm.SaleToDeadbeat := SaleToDeadbeat;
LogForm.xdeSaleDate.Date := GetSystemDate;
LogForm.ShowModal;
Result := LogForm.ModalResult = mrOK;
End;
End;
procedure InitOldOrg(pOrg_id, pOrg_inst : integer; pOrgName : string;
pSale_id, pSale_inst : integer; pTable_name : string;
var SaleToDeadbeat : TSaleToDeadbeat);
Begin
SaleToDeadbeat.OldOrgId := pOrg_id;
SaleToDeadbeat.OldOrgInst := pOrg_inst;
SaleToDeadbeat.Sale_id := pSale_id;
SaleToDeadbeat.Sale_inst := pSale_inst;
SaleToDeadbeat.Table_name := pTable_name;
if SaleToDeadbeat.NewOrgName = '' then SaleToDeadbeat.NewOrgName := pOrgName;
SaleToDeadbeat.OldOrgIsDebetor := 0<
GetSQLValue('select count(*) from OIL_SALE_DEADBEAT_LOG where state=''Y'' and sale_id='+IntToStr(pSale_id)+
' and sale_inst='+IntToStr(pSale_inst)+' and table_name='''+pTable_name+
''' and inst='+IntToStr(REAL_INST)+' and org_id='+IntToStr(pOrg_id)+' and org_inst='+IntToStr(pOrg_inst));
End;
Function InitNewOrg(pOrg_id, pOrg_inst : integer; pOrgName : string;
pSale_id, pSale_inst : integer; pTable_name : string;
var SaleToDeadbeat : TSaleToDeadbeat; pShowMessage : boolean = True) : boolean;
var vNewOrgIsDebetor, StoreParams : boolean;
SaleStr : string;
// Функция проверяет, является ли организация дебетором
// если да - предупреждает юзера и в случае его согласия с выбором - сохраняет параметры отпуска
Begin
StoreParams := True;
vNewOrgIsDebetor := 0<
GetSQLValue('select count(*) from OIL_DEADBEAT where state=''Y'' and org_id='+IntToStr(pOrg_id)+
' and org_inst='+IntToStr(pOrg_inst)+' and inst='+IntToStr(REAL_INST));
Result := not vNewOrgIsDebetor;
SaleStr := TranslateText('Отпуски таким организациям запрещены!');
if pTable_name = 'OIL_SERVICE'
then SaleStr := TranslateText('Предоставление услуг таким организациям запрещено!');
if vNewOrgIsDebetor and pShowMessage
then if MessageDlgExt(TranslateText('Внимание!')+#13#10+TranslateText('Организация ')+#13#10+pOrgName+#13#10+
TranslateText(' имеет просроченную задолженность.')+#13#10+
SaleStr,
mtWarning,[TranslateText('Продолжить'),TranslateText('Отменить')],2)<>1
then StoreParams := False;
if StoreParams
then Begin
Result := True;
SaleToDeadbeat.Sale_id := pSale_id;
SaleToDeadbeat.Sale_inst := pSale_inst;
SaleToDeadbeat.Table_name := pTable_name;
SaleToDeadbeat.NewOrgId := pOrg_id;
SaleToDeadbeat.NewOrgInst := pOrg_inst;
SaleToDeadbeat.NewOrgName := pOrgName;
SaleToDeadbeat.NewOrgIsDebetor := vNewOrgIsDebetor;
End;
End;
procedure SwitchDeadbeatToN;
Begin
_ExecSQL('update OIL_DEADBEAT set state = ''N'' where state = ''Y''');
End;
procedure MarkDeadbeat(org_id, org_inst : integer; summa : real);
Begin
DBSaver.SaveRecord('OIL_DEADBEAT',
['ORG_ID', Org_Id,
'ORG_INST', Org_inst,
'STATE', 'Y',
'INST', REAL_INST,
'DATE_', null,
'SUMMOVER', summa
]);
End;
Procedure DeleteSaleFromLog(Sale_id,Sale_inst,inst : integer; table_name : string);
Begin
_ExecSQL('update OIL_SALE_DEADBEAT_LOG set state=''N'' where sale_id='+IntToStr(Sale_id)+
' and sale_inst='+IntToStr(sale_inst)+' and table_name='''+table_name+''' and inst='+IntToStr(inst));
End;
procedure TLogSaleDeadbeatForm.bbOkClick(Sender: TObject);
var S : string;
begin
try
if edtRespondent.Text = ''
then Raise Exception.Create(TranslateText('Введите свою фамилию !'));
if edtInstructor.Text = ''
then Raise Exception.Create(TranslateText('Введите, по чьему указанию производится отпуск !'));
S := edtRespondent.Text;
if (Length(S) <3) or
(ANSIUpperCase(Copy(S,1,1))<> Copy(S,1,1)) or
(Pos('1',S)+Pos('2',S)+Pos('3',S)+Pos('4',S)+Pos('5',S)+Pos('6',S)+
Pos('7',S)+Pos('8',S)+Pos('9',S)+Pos('0',S)<>0)
then Raise Exception.Create(TranslateText('Неправильно введена фамилия !'));
S := edtInstructor.Text;
if (Length(S) <3) or
(ANSIUpperCase(Copy(S,1,1))<> Copy(S,1,1)) or
(Pos('1',S)+Pos('2',S)+Pos('3',S)+Pos('4',S)+Pos('5',S)+Pos('6',S)+
Pos('7',S)+Pos('8',S)+Pos('9',S)+Pos('0',S)<>0)
then Raise Exception.Create(TranslateText('Неправильно введена фамилия распорядителя!'));
DBSaver.SaveRecord('OIL_SALE_DEADBEAT_LOG',
['INST', REAL_INST,
'STATE', 'Y',
'SALE_ID', SaleToDeadbeat.Sale_id,
'SALE_INST', SaleToDeadbeat.Sale_inst,
'TABLE_NAME', SaleToDeadbeat.Table_name,
'ORG_ID', SaleToDeadbeat.NewOrgId,
'ORG_INST', SaleToDeadbeat.NewOrgInst,
'DATE_', xdeSaleDate.Date,
'USER_', edtRespondent.Text,
'INSTRUCTOR', edtInstructor.Text
]);
Self.ModalResult := mrOK;
except on E:Exception do Begin
ShowMessage(E.Message)
End;
End;
end;
procedure TLogSaleDeadbeatForm.FormShow(Sender: TObject);
begin
Self.ModalResult := mrNone;
if SaleToDeadbeat.Table_name ='OIL_RASHOD'
then edtSaleType.Text := TranslateText('Отпуск нефтепродуктов (id=')+IntToStr(SaleToDeadbeat.Sale_id)+')';
if SaleToDeadbeat.Table_name ='OIL_TALON_OUT'
then edtSaleType.Text := TranslateText('Отпуск талонов (id=')+IntToStr(SaleToDeadbeat.Sale_id)+')';
if SaleToDeadbeat.Table_name ='OIL_SERVICE'
then edtSaleType.Text := TranslateText('Услуга (id=')+IntToStr(SaleToDeadbeat.Sale_id)+')';
edtOrg.Text := SaleToDeadbeat.NewOrgName;
end;
end.
|
unit mrDBEdit;
interface
uses
SysUtils, Classes, Controls, StdCtrls, ExtCtrls, mrBoundLabel,
Types, Graphics, Messages, cxDBEdit;
type
TmrDBEdit = class(TcxDBTextEdit)
private
FEditLabel: TmrBoundLabel;
FRequiredLabel: TmrBoundLabel;
FLocked: Boolean;
FRequired: Boolean;
FLabelSpacing: Integer;
FLabelPosition: TLabelPosition;
procedure SetLabelSpacing(const Value: Integer);
procedure SetLocked(const Value: Boolean);
procedure SetRequired(const Value: Boolean);
procedure GetFieldConfig;
protected
procedure SetParent(AParent: TWinControl); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetName(const Value: TComponentName); override;
procedure CMVisiblechanged(var Message: TMessage); message CM_VISIBLECHANGED;
procedure CMEnabledchanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure CMBidimodechanged(var Message: TMessage); message CM_BIDIMODECHANGED;
public
constructor Create(AOwner: TComponent); override;
procedure SetupInternalLabel;
procedure SetLabelPosition(const Value: TLabelPosition);
procedure SetBounds(ALeft: Integer; ATop: Integer; AWidth: Integer; AHeight: Integer); override;
published
property EditLabel: TmrBoundLabel read FEditLabel;
property LabelPosition: TLabelPosition read FLabelPosition write SetLabelPosition;
property LabelSpacing: Integer read FLabelSpacing write SetLabelSpacing;
property Required: Boolean read FRequired write SetRequired;
property Locked: Boolean read FLocked write SetLocked;
end;
procedure Register;
implementation
uses DB;
procedure Register;
begin
RegisterComponents('MultiTierDataControls', [TmrDBEdit]);
end;
{ TmrDBEdit }
procedure TmrDBEdit.CMBidimodechanged(var Message: TMessage);
begin
inherited;
FEditLabel.BiDiMode := BiDiMode;
FRequiredLabel.BiDiMode := BiDiMode;
end;
procedure TmrDBEdit.CMEnabledchanged(var Message: TMessage);
begin
inherited;
FEditLabel.Enabled := Enabled;
FRequiredLabel.Enabled := Enabled;
end;
procedure TmrDBEdit.CMVisiblechanged(var Message: TMessage);
begin
inherited;
FEditLabel.Visible := Visible;
FRequiredLabel.Visible := Visible;
if Visible and Required then
FRequiredLabel.Parent := Self.Parent
else
FRequiredLabel.Parent := nil;
end;
constructor TmrDBEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLabelPosition := lpLeft;
FLabelSpacing := 6;
SetupInternalLabel;
end;
procedure TmrDBEdit.GetFieldConfig;
begin
if Assigned(DataBinding.DataLink.Field) then
begin
FEditLabel.Caption := DataBinding.DataLink.Field.DisplayLabel + ' : ';
Required := DataBinding.DataLink.Field.Required;
//Locked := DataBinding.DataLink.Field.ReadOnly;
end;
end;
procedure TmrDBEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FEditLabel) and (Operation = opRemove) then
FEditLabel := nil;
if (AComponent = FRequiredLabel) and (Operation = opRemove) then
FRequiredLabel := nil;
end;
procedure TmrDBEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
SetLabelPosition(FLabelPosition);
GetFieldConfig;
end;
procedure TmrDBEdit.SetLabelPosition(const Value: TLabelPosition);
var
P: TPoint;
begin
if Assigned(FEditLabel) then
begin
FLabelPosition := Value;
case Value of
lpAbove: P := Point(Left, Top - FEditLabel.Height - FLabelSpacing);
lpBelow: P := Point(Left, Top + Height + FLabelSpacing);
lpLeft : P := Point(Left - FEditLabel.Width - FLabelSpacing,
Top + ((Height - FEditLabel.Height) div 2));
lpRight: P := Point(Left + Width + FLabelSpacing,
Top + ((Height - FEditLabel.Height) div 2));
end;
FEditLabel.SetBounds(P.x, P.y, FEditLabel.Width, FEditLabel.Height);
end;
if Assigned(FRequiredLabel) then
FRequiredLabel.SetBounds(Left + Width + 3, Top + 1, FRequiredLabel.Width, FRequiredLabel.Height);
end;
procedure TmrDBEdit.SetLabelSpacing(const Value: Integer);
begin
FLabelSpacing := Value;
SetLabelPosition(FLabelPosition);
end;
procedure TmrDBEdit.SetLocked(const Value: Boolean);
begin
FLocked := Value;
Properties.ReadOnly := Value;
ParentColor := Value;
if not Value then
Color := clWindow;
end;
procedure TmrDBEdit.SetName(const Value: TComponentName);
begin
if (csDesigning in ComponentState) and ((FEditlabel.GetTextLen = 0) or
(CompareText(FEditLabel.Caption, Name) = 0)) then
FEditLabel.Caption := Value;
inherited SetName(Value);
if csDesigning in ComponentState then
Text := '';
end;
procedure TmrDBEdit.SetParent(AParent: TWinControl);
begin
inherited SetParent(AParent);
if Assigned(FEditLabel) then
begin
FEditLabel.Parent := AParent;
FEditLabel.Visible := True;
end;
end;
procedure TmrDBEdit.SetRequired(const Value: Boolean);
begin
FRequired := Value;
if Value then
FRequiredLabel.Parent := Self.Parent
else
FRequiredLabel.Parent := nil;
if Assigned(DataBinding.DataLink.Field) then
DataBinding.DataLink.Field.Required := Value;
end;
procedure TmrDBEdit.SetupInternalLabel;
begin
if not Assigned(FEditLabel) then
begin
FEditLabel := TmrBoundLabel.Create(Self);
FEditLabel.Name := 'SubEditLabel';
FEditLabel.SetSubComponent(True);
FEditLabel.FreeNotification(Self);
TLabel(FEditLabel).FocusControl := Self;
end;
if not Assigned(FRequiredLabel) then
begin
FRequiredLabel := TmrBoundLabel.Create(Self);
with FRequiredLabel do
begin
Name := 'SubRequiredLabel';
SetSubComponent(True);
FreeNotification(Self);
Caption := '*';
Font.Color := $00804000;
Font.Style := [fsBold];
Font.Size := 15;
Font.Name := 'Verdana';
Transparent := True;
end;
end;
end;
end.
|
unit trl_upersist;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils, trl_ipersist, fgl, trl_irttibroker, typinfo, trl_urttibroker;
type
{ TPersistManyDataItem }
TPersistManyDataItem = class(TInterfacedObject, IRBDataItem)
private
fPersistMany: IPersistMany;
fIndex: integer;
protected
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);
public
constructor Create(const APersistMany: IPersistMany; AIndex: integer);
end;
{ TPersistMany }
TPersistMany<TItem> = class(TInterfacedObject, IPersistMany, IPersistManyItems<TItem>)
private
fData: TFPGList<TItem>;
function GetAsPersistDataClass: IRBData;
protected
function GetAsPersist(AIndex: integer): string; virtual; abstract;
procedure SetAsPersist(AIndex: integer; AValue: string); virtual; abstract;
function GetAsString(AIndex: integer): string; virtual; abstract;
procedure SetAsString(AIndex: integer; AValue: string); virtual; abstract;
function GetAsObject(AIndex: integer): TObject; virtual;
procedure SetAsObject(AIndex: integer; AValue: TObject); virtual;
function GetEnumName(AValue: integer): string;
function GetEnumNameCount: integer;
function GetIsObject: Boolean;
function GetIsInterface: Boolean;
function GetIsMemo: Boolean;
function GetIsID: Boolean;
function GetAsInterface(AIndex: integer): IUnknown; virtual;
procedure SetAsInterface(AIndex: integer; AValue: IUnknown); virtual;
function GetClassName: string; virtual;
//
function GetAsPersistData(AIndex: integer): IRBData; virtual;
procedure SetAsPersistData(AIndex: integer; AValue: IRBData); virtual;
function ItemTypeInfo: PTypeInfo;
function GetCount: integer;
function GetItem(AIndex: integer): TItem; virtual;
procedure SetCount(AValue: integer);
procedure SetItem(AIndex: integer; AValue: TItem); virtual;
property Count: integer read GetCount write SetCount;
property Item[AIndex: integer]: TItem read GetItem write SetItem; default;
procedure Delete(AIndex: integer);
property AsPersist[AIndex: integer]: string read GetAsPersist write SetAsPersist;
property AsString[AIndex: integer]: string read GetAsString write SetAsString;
property AsObject[AIndex: integer]: TObject read GetAsObject write SetAsObject;
property AsInterface[AIndex: integer]: IUnknown read GetAsInterface write SetAsInterface;
property AsPersistData[AIndex: integer]: IRBData read GetAsPersistData write SetAsPersistData;
property AsPersistDataClass: IRBData read GetAsPersistDataClass;
property IsObject: Boolean read GetIsObject;
property IsInterface: Boolean read GetIsInterface;
property IsMemo: Boolean read GetIsMemo;
property IsID: Boolean read GetIsID;
property ClassName: string read GetClassName;
public
constructor Create;
destructor Destroy; override;
end;
{ TPersistManyObjects }
TPersistManyObjects<TObjItem: TObject> = class(TPersistMany<TObjItem>)
protected
function GetItem(AIndex: integer): TObjItem; override;
procedure SetItem(AIndex: integer; AValue: TObjItem); override;
function GetAsObject(AIndex: integer): TObject; override;
procedure SetAsObject(AIndex: integer; AValue: TObject); override;
function GetAsPersistData(AIndex: integer): IRBData; override;
procedure SetAsPersistData(AIndex: integer; AValue: IRBData); override;
end;
{ TPersistManyIntegers }
TPersistManyIntegers = class(TPersistMany<Integer>, IPersistManyIntegers)
protected
function GetAsPersist(AIndex: integer): string; override;
function GetAsString(AIndex: integer): string; override;
procedure SetAsPersist(AIndex: integer; AValue: string); override;
procedure SetAsString(AIndex: integer; AValue: string); override;
end;
{ TPersistManyStrings }
TPersistManyStrings = class(TPersistMany<String>, IPersistManyStrings)
protected
function GetAsPersist(AIndex: integer): string; override;
function GetAsString(AIndex: integer): string; override;
procedure SetAsPersist(AIndex: integer; AValue: string); override;
procedure SetAsString(AIndex: integer; AValue: string); override;
end;
implementation
{ TPersistMany<TItem> }
constructor TPersistMany<TItem>.Create;
begin
fData := TFPGList<TItem>.Create;
end;
destructor TPersistMany<TItem>.Destroy;
begin
FreeAndNil(fData);
inherited;
end;
function TPersistMany<TItem>.GetIsObject: Boolean;
begin
Result := ItemTypeInfo^.Kind in [tkClass, tkObject];
end;
function TPersistMany<TItem>.GetIsInterface: Boolean;
begin
Result := ItemTypeInfo^.Kind in [tkInterface, tkInterfaceRaw];
end;
function TPersistMany<TItem>.GetIsMemo: Boolean;
begin
Result := SameText(ItemTypeInfo^.Name, cMemoStringType);
end;
function TPersistMany<TItem>.GetIsID: Boolean;
begin
Result := SameText(ItemTypeInfo^.Name, cIDStringType);
end;
function TPersistMany<TItem>.GetAsInterface(AIndex: integer): IUnknown;
begin
Result := nil;
end;
function TPersistMany<TItem>.GetAsPersistData(AIndex: integer): IRBData;
begin
Result := nil;
end;
procedure TPersistMany<TItem>.SetAsPersistData(AIndex: integer; AValue: IRBData
);
begin
end;
function TPersistMany<TItem>.GetAsPersistDataClass: IRBData;
begin
Result := TRBData.Create(GetTypeData(ItemTypeInfo)^.ClassType);
end;
function TPersistMany<TItem>.GetClassName: string;
begin
Result := '';
end;
procedure TPersistMany<TItem>.SetAsInterface(AIndex: integer; AValue: IUnknown);
begin
end;
function TPersistMany<TItem>.GetAsObject(AIndex: integer): TObject;
begin
Result := nil;
end;
procedure TPersistMany<TItem>.SetAsObject(AIndex: integer; AValue: TObject);
begin
end;
function TPersistMany<TItem>.GetEnumName(AValue: integer): string;
begin
Result := typinfo.GetEnumName(ItemTypeInfo, AValue);
end;
function TPersistMany<TItem>.GetEnumNameCount: integer;
begin
Result := typinfo.GetEnumNameCount(ItemTypeInfo);
end;
function TPersistMany<TItem>.ItemTypeInfo: PTypeInfo;
begin
Result := TypeInfo(TItem);
end;
function TPersistMany<TItem>.GetCount: integer;
begin
Result := fData.Count;
end;
function TPersistMany<TItem>.GetItem(AIndex: integer): TItem;
begin
Result := fData[AIndex];
end;
procedure TPersistMany<TItem>.SetCount(AValue: integer);
begin
fData.Count := AValue;
end;
procedure TPersistMany<TItem>.SetItem(AIndex: integer; AValue: TItem);
begin
fData[AIndex] := AValue;
end;
procedure TPersistMany<TItem>.Delete(AIndex: integer);
begin
fData.Delete(AIndex);
end;
{ TPersistManyObjects<TItem> }
function TPersistManyObjects<TObjItem>.GetItem(AIndex: integer): TObjItem;
begin
if AIndex > Count - 1 then
Count := AIndex + 1;
Result := inherited GetItem(AIndex);
if not assigned(Result) then begin
Result := TObjItem.Create;
inherited SetItem(AIndex, Result);
end;
end;
procedure TPersistManyObjects<TObjItem>.SetItem(AIndex: integer; AValue: TObjItem);
begin
Item[AIndex].Free;
Item[AIndex] := AValue as TObjItem;
end;
function TPersistManyObjects<TObjItem>.GetAsObject(AIndex: integer): TObject;
begin
Result := Item[AIndex];
end;
procedure TPersistManyObjects<TObjItem>.SetAsObject(AIndex: integer;
AValue: TObject);
begin
Item[AIndex] := AValue as TObjItem;
end;
function TPersistManyObjects<TObjItem>.GetAsPersistData(AIndex: integer): IRBData;
begin
Result := TRBData.Create(AsObject[AIndex]);
end;
procedure TPersistManyObjects<TObjItem>.SetAsPersistData(AIndex: integer; AValue: IRBData);
begin
AsObject[AIndex] := AValue.UnderObject;
end;
{ TPersistManyDataItem }
function TPersistManyDataItem.GetName: string;
begin
end;
function TPersistManyDataItem.GetClassName: string;
begin
Result := fPersistMany.ClassName;
end;
function TPersistManyDataItem.GetIsObject: Boolean;
begin
Result := fPersistMany.IsObject;
end;
function TPersistManyDataItem.GetIsMemo: Boolean;
begin
Result := fPersistMany.IsMemo;
end;
function TPersistManyDataItem.GetIsID: Boolean;
begin
Result := fPersistMany.IsID;
end;
function TPersistManyDataItem.GetIsInterface: Boolean;
begin
Result := fPersistMany.IsInterface;
end;
function TPersistManyDataItem.GetTypeKind: TTypeKind;
begin
end;
function TPersistManyDataItem.GetAsPersist: string;
begin
Result := fPersistMany.AsPersist[fIndex];
end;
procedure TPersistManyDataItem.SetAsPersist(AValue: string);
begin
fPersistMany.AsPersist[fIndex] := AValue;
end;
function TPersistManyDataItem.GetAsInteger: integer;
begin
end;
function TPersistManyDataItem.GetAsString: string;
begin
Result := fPersistMany.AsString[fIndex];
end;
function TPersistManyDataItem.GetAsBoolean: Boolean;
begin
end;
procedure TPersistManyDataItem.SetAsInteger(AValue: integer);
begin
end;
procedure TPersistManyDataItem.SetAsString(AValue: string);
begin
fPersistMany.AsString[fIndex] := AValue;
end;
procedure TPersistManyDataItem.SetAsBoolean(AValue: Boolean);
begin
end;
function TPersistManyDataItem.GetAsObject: TObject;
begin
Result := fPersistMany.AsObject[fIndex];
end;
procedure TPersistManyDataItem.SetAsObject(AValue: TObject);
begin
fPersistMany.AsObject[fIndex] := AValue;
end;
function TPersistManyDataItem.GetAsVariant: Variant;
begin
end;
procedure TPersistManyDataItem.SetAsVariant(AValue: Variant);
begin
end;
function TPersistManyDataItem.GetAsClass: TClass;
begin
end;
function TPersistManyDataItem.GetEnumName(AValue: integer): string;
begin
Result := fPersistMany.EnumName[AValue];
end;
function TPersistManyDataItem.GetEnumNameCount: integer;
begin
Result := fPersistMany.EnumNameCount;
end;
function TPersistManyDataItem.GetAsPtrInt: PtrInt;
begin
end;
procedure TPersistManyDataItem.SetAsPtrInt(AValue: PtrInt);
begin
end;
function TPersistManyDataItem.GetAsInterface: IUnknown;
begin
Result := fPersistMany.AsInterface[fIndex];
end;
procedure TPersistManyDataItem.SetAsInterface(AValue: IUnknown);
begin
fPersistMany.AsInterface[fIndex] := AValue;
end;
constructor TPersistManyDataItem.Create(const APersistMany: IPersistMany;
AIndex: integer);
begin
fPersistMany := APersistMany;
fIndex := AIndex;
end;
{ TPersistManyStrings }
function TPersistManyStrings.GetAsPersist(AIndex: integer): string;
begin
Result := Item[AIndex];
end;
function TPersistManyStrings.GetAsString(AIndex: integer): string;
begin
Result := AsPersist[AIndex];
end;
procedure TPersistManyStrings.SetAsPersist(AIndex: integer; AValue: string);
begin
Item[AIndex] := AValue;
end;
procedure TPersistManyStrings.SetAsString(AIndex: integer; AValue: string);
begin
AsPersist[AIndex] := AValue;
end;
{ TPersistManyIntegers }
function TPersistManyIntegers.GetAsPersist(AIndex: integer): string;
begin
Result := IntToStr(Item[AIndex]);
end;
function TPersistManyIntegers.GetAsString(AIndex: integer): string;
begin
Result := AsPersist[AIndex];
end;
procedure TPersistManyIntegers.SetAsPersist(AIndex: integer; AValue: string);
begin
if AValue = '' then
Item[AIndex] := 0
else
Item[AIndex] := StrToInt(AValue);
end;
procedure TPersistManyIntegers.SetAsString(AIndex: integer; AValue: string);
begin
AsPersist[AIndex] := AValue;
end;
end.
|
unit MensagemBase;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Base.View, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, cxControls, cxContainer,
cxEdit, dxGDIPlusClasses,
Vcl.ExtCtrls, cxLabel, Vcl.StdCtrls, cxButtons, Base.View.Interf,
Tipos.Controller.Interf,
cxTextEdit, cxMemo, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Silver, dxSkinOffice2016Colorful, dxSkinOffice2016Dark;
type
TFMensagemView = class(TFBaseView, IBaseMensagemView)
BtSalvar: TcxButton;
MmMensagem: TcxMemo;
procedure BtSalvarClick(Sender: TObject);
procedure BtEncerrarClick(Sender: TObject);
private
{ Private declarations }
protected
FResposta: Boolean;
FMensagem: string;
public
{ Public declarations }
class function New: IBaseMensagemView;
function mensagem(AValue: string): IBaseMensagemView;
function &exibir: Boolean;
end;
var
FMensagemView: TFMensagemView;
implementation
{$R *.dfm}
procedure TFMensagemView.BtEncerrarClick(Sender: TObject);
begin
inherited;
FResposta := False;
end;
procedure TFMensagemView.BtSalvarClick(Sender: TObject);
begin
inherited;
FResposta := True;
Close;
end;
function TFMensagemView.exibir: Boolean;
begin
ShowModal;
end;
function TFMensagemView.mensagem(AValue: string): IBaseMensagemView;
begin
Result := Self;
FMensagem := AValue;
end;
class function TFMensagemView.New: IBaseMensagemView;
begin
Result := Self.Create(nil);
end;
end.
|
unit DeviceIntegrationInterface;
interface
uses uCreditCardFunction, uMRPinpad, ProcessorInterface;
type
IDeviceIntegration = Interface
function InitializeStatus(): Boolean;
function ProcessCommand(arg_xml: WideString): Boolean;
// Credit Transactions
function CreditProcessSale(): Boolean;
function CreditProcessReturn(): Boolean;
function CreditVoidSale(): Boolean;
function CreditVoidReturn(): Boolean;
// Debit Transactions
function DebitProcessSale(): Boolean;
function DebitProcessReturn(): Boolean;
// Prepaid transactions
function GiftProcessSale(): Boolean;
function GiftProcessReturn(): Boolean;
function GiftVoidSale(): Boolean;
function GiftVoidReturn(): Boolean;
function GiftIssue: Boolean;
function GiftVoidIssue: Boolean;
function GiftReload: Boolean;
function GiftVoidReload: Boolean;
function GiftBalance: Boolean;
function GiftNoNSFSale: Boolean;
function GiftCashOut: Boolean;
// Antonio September 11, 2013
function tryIssueCard(arg_salePrice: double): TTransactionReturn;
function tryBalanceCard(arg_salePrice: double): TTransactionReturn;
procedure SetProcessor(arg_processor: IProcessor);
procedure SetPinPad(arg_device: TMRPinPad);
function GetTransaction(): IProcessor;
procedure BeforeProcessCard();
procedure BeforeVoid();
end;
implementation
end.
|
program recommend_uploader;
{$mode objfpc}{$H+}
uses
cthreads,
Classes,
SysUtils,
CustApp,
unt_command,
unt_recommend_upload;
type
{ TRecommendUploader }
TRecommendUploader = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TRecommendUploader }
procedure TRecommendUploader.DoRun;
var
apk: string;
icon: string;
unixNme: string;
mode: integer;
account: string;
password: string;
begin
if HasOption('h', 'help') then
begin
WriteHelp;
Terminate;
Exit;
end;
if HasOption('f') then
begin
apk := GetOptionValue('f');
end;
if HasOption('i') then
begin
icon := GetOptionValue('i');
end;
if HasOption('u') then
begin
unixNme := GetOptionValue('u');
end;
if HasOption('m') then
begin
mode := StrToIntDef(GetOptionValue('m'), -1);
end;
if HasOption('a') then
begin
account := GetOptionValue('a');
end;
if HasOption('p') then
begin
password := GetOptionValue('p');
end;
if (apk = '') or (icon = '') or (unixNme = '') or (mode = -1) or (account = '') or (password = '') then
begin
WriteHelp;
Terminate;
Exit;
end;
DoUpload(apk, icon, unixNme, mode, account, password);
Terminate;
end;
constructor TRecommendUploader.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException := True;
end;
destructor TRecommendUploader.Destroy;
begin
inherited Destroy;
end;
procedure TRecommendUploader.WriteHelp;
begin
WriteLn('Usage: -h');
WriteLn(' -f <apk file path>');
WriteLn(' -i <icon file path>');
WriteLn(' -u <unix name>');
WriteLn(' -m <mode: 0=add, 1=update>');
WriteLn(' -a <user account>');
WriteLn(' -p <user password>');
end;
var
Application: TRecommendUploader;
begin
Application := TRecommendUploader.Create(nil);
Application.Run;
Application.Free;
end.
|
{ -------------------------------------------------------------------------------
Unit Name: cStructured3DDataset
Author: HochwimmerA
Purpose: Code for managing a 3D structured dataset - has provision
$Id: cStructured3DDataSet.pas,v 1.2 2003/10/28 04:18:51 hochwimmera Exp $
------------------------------------------------------------------------------- }
unit cStructured3DDataSet;
interface
uses
System.Classes, System.SysUtils,
Vcl.Graphics, Vcl.Dialogs,
GLVectorgeometry, GLGraph, GLMesh, GLTexture, GLScene, GLObjects,
GLVectorTypes, cUtilities, GLColor, GLMaterial;
type
{ : T3DSPoint is a class containing information for one point in the
structured grid. It only holds scalar data }
T3DSPoint = class(TObject)
private
fScalarVal: single; // scalar value
public
property ScalarVal: single read fScalarVal write fScalarVal;
end;
{ : T3DVPoint is a class containing information for one point in the
structured grid. It only holds vector data }
T3DVPoint = class(TObject)
private
fDirection: TVector; // direction
fMagnitude: single; // magnitude (positive)
public
property Direction: TVector read fDirection write fDirection;
property Magnitude: single read fMagnitude write fMagnitude;
end;
T3DStructuredDataSet = class;
T3DStructuredScalar = class(TObject)
private
fCutXY: TGLHeightField; // cut plane for constant Z
fCutXZ: TGLHeightField; // cut plane for constant Y
fCutYZ: TGLHeightField; // cut plane for constant X
fDescription: string;
fDummyCube: TGLDummyCube; // used to group objects
fParentGrid: T3DStructuredDataSet; // external pointer
fPointList: TStringList;
fMaxValue: single;
fMinValue: single;
fXLevel: integer;
fYLevel: integer;
fZLevel: integer;
protected
procedure ContourXY(const x, y: single; var z: single;
var color: TColorVector; var texPoint: TTexPoint);
procedure ContourXZ(const x, y: single; var z: single;
var color: TColorVector; var texPoint: TTexPoint);
procedure ContourYZ(const x, y: single; var z: single;
var color: TColorVector; var texPoint: TTexPoint);
procedure Index_IJK(const iIndex: integer; var I, J, K: integer);
procedure InitCutPlanes;
public
constructor Create(aParent: T3DStructuredDataSet);
destructor Destroy; override;
procedure GetMinMax;
property Description: string read fDescription write fDescription;
property PointList: TStringList read fPointList write fPointList;
property XLevel: integer read fXLevel write fXLevel;
property YLevel: integer read fYLevel write fYLevel;
property ZLevel: integer read fZLevel write fZLevel;
// use to group gl data below the "parent cube"
property DummyCube: TGLDummyCube read fDummyCube write fDummyCube;
property CutXY: TGLHeightField read fCutXY write fCutXY;
// cut plane for constant Z
property CutXZ: TGLHeightField read fCutXZ write fCutXZ;
// cut plane for constant Y
property CutYZ: TGLHeightField read fCutYZ write fCutYZ;
// cut plane for constant X property MaxValue : single read fMaxValue write fMaxValue;
property MaxValue: single read fMaxValue write fMaxValue;
property MinValue: single read fMinValue write fMinValue;
property ParentGrid: T3DStructuredDataSet read fParentGrid
write fParentGrid;
end;
{ : T3DStructuredDataSet is a class for managing a structured 3D dataset.
At its core it manages a list of T3GeneralPoint. GLScene objects that are
related to the 3D structured dataset are handed in the fDummyCube obtained
via the constructor. Note that the number of data items n of each type of data
must match the number of points or cells in the dataset }
T3DStructuredDataSet = class(TObject)
private
FBox: TGLXYZGrid;
fDescription: string;
fDummyCube: TGLDummyCube; // external pointer
FN: integer;
FNX: integer;
FNY: integer;
FNZ: integer;
FNYNZ: integer; // used for converting index <-> i,j,k
FScalarData: TStringList; // maintains a list T3DStructuredScalar
FVectorData: TStringList; // maintains a list T3DStructuredVector
Fxdelta: double;
Fxlo: double;
Fxhi: double;
Fydelta: double;
Fylo: double;
Fyhi: double;
Fzdelta: double;
Fzlo: double;
Fzhi: double;
procedure GenerateBoundingBox;
protected
public
constructor Create(aDummyCube: TGLDummyCube);
destructor Destroy; override;
function ImportVTKFile(sFileName: string): integer;
property Box: TGLXYZGrid read FBox write FBox;
property Description: string read fDescription write fDescription;
property DummyCube: TGLDummyCube read fDummyCube write fDummyCube; // ext
property N: integer read FN write FN;
property NX: integer read FNX write FNX;
property NY: integer read FNY write FNY;
property NYNZ: integer read FNYNZ write FNYNZ;
property NZ: integer read FNZ write FNZ;
property ScalarData: TStringList read FScalarData write FScalarData;
property VectorData: TStringList read FVectorData write FVectorData;
property xDelta: double read Fxdelta write Fxdelta;
property xlo: double read Fxlo write Fxlo;
property xhi: double read Fxhi write Fxhi;
property yDelta: double read Fydelta write Fydelta;
property ylo: double read Fylo write Fylo;
property yhi: double read Fyhi write Fyhi;
property zDelta: double read Fzdelta write Fzdelta;
property zlo: double read Fzlo write Fzlo;
property zhi: double read Fzhi write Fzhi;
end;
implementation
// =============================================================================
// T3DStructuredScalar Implementation
// =============================================================================
{ : Converts 1d iIndex into i,j,k notation }
procedure T3DStructuredScalar.Index_IJK(const iIndex: integer;
var I, J, K: integer);
begin
I := iIndex div ParentGrid.NYNZ; // int division;
J := (iIndex - ParentGrid.NYNZ * I) div ParentGrid.NZ; // int division
K := (iIndex - ParentGrid.NYNZ * I - ParentGrid.NZ * J);
end;
// ----- T3DStructuredScalar.InitCutPlanes -------------------------------------
procedure T3DStructuredScalar.InitCutPlanes;
begin
// with CutXY do
CutXY.Position.z := ParentGrid.zlo;
CutXY.XSamplingScale.Min := ParentGrid.xlo;
CutXY.XSamplingScale.Max := ParentGrid.xhi + 0.01 * ParentGrid.xDelta;
CutXY.XSamplingScale.Origin := ParentGrid.xlo;
CutXY.XSamplingScale.Step := ParentGrid.xDelta;
CutXY.YSamplingScale.Min := ParentGrid.ylo;
CutXY.YSamplingScale.Max := ParentGrid.yhi + 0.01 * ParentGrid.yDelta;
CutXY.YSamplingScale.Origin := ParentGrid.ylo;
CutXY.YSamplingScale.Step := ParentGrid.yDelta;
CutXY.ColorMode := hfcmDiffuse;
CutXY.OngetHeight := ContourXY;
CutXY.StructureChanged;
// with CutXZ do
CutXZ.Up.AsVector := ZHmgVector;
CutXZ.Direction.AsVector := yHmgVector;
CutXZ.Direction.y := -1;
CutXZ.Position.z := ParentGrid.ylo;
CutXZ.XSamplingScale.Min := ParentGrid.xlo;
CutXZ.XSamplingScale.Max := ParentGrid.xhi + 0.01 * ParentGrid.xDelta;
CutXZ.XSamplingScale.Origin := ParentGrid.xlo;
CutXZ.XSamplingScale.Step := ParentGrid.xDelta;
CutXZ.YSamplingScale.Min := ParentGrid.zlo;
CutXZ.YSamplingScale.Max := ParentGrid.zhi + 0.01 * ParentGrid.zDelta;
CutXZ.YSamplingScale.Origin := ParentGrid.zlo;
CutXZ.YSamplingScale.Step := ParentGrid.zDelta;
CutXZ.ColorMode := hfcmEmission;
CutXZ.OngetHeight := ContourXZ;
CutXZ.StructureChanged;
// with CutYZ do
CutYZ.Up.AsVector := ZHmgVector;
CutYZ.Direction.AsVector := xHmgVector;
CutYZ.Position.z := ParentGrid.xlo;
CutYZ.XSamplingScale.Min := ParentGrid.ylo;
CutYZ.XSamplingScale.Max := ParentGrid.yhi + 0.01 * ParentGrid.yDelta;
CutYZ.XSamplingScale.Origin := ParentGrid.ylo;
CutYZ.XSamplingScale.Step := ParentGrid.yDelta;
CutYZ.YSamplingScale.Min := ParentGrid.zlo;
CutYZ.YSamplingScale.Max := ParentGrid.zhi + 0.01 * ParentGrid.zDelta;
CutYZ.YSamplingScale.Origin := ParentGrid.zlo;
CutYZ.YSamplingScale.Step := ParentGrid.zDelta;
CutYZ.ColorMode := hfcmEmission;
CutYZ.OngetHeight := ContourYZ;
CutYZ.StructureChanged;
end;
// ----- T3DStructuredScalar.ContourXY -----------------------------------------
procedure T3DStructuredScalar.ContourXY(const x, y: single; var z: single;
var color: TColorVector; var texPoint: TTexPoint);
const
SMALL = 0.01;
var
I, J, K, iIndex: integer;
dp: single;
dratio, rstar: double;
col1, col2: TColor;
bforward: boolean;
ColorVect: TColorVector;
glC1, glC2: TGLColor;
begin
// flat - its a cut plane
z := 0;
I := Trunc((x - ParentGrid.xlo - 0.01 * ParentGrid.xDelta) /
ParentGrid.xDelta);
J := Trunc((y - ParentGrid.ylo - 0.01 * ParentGrid.yDelta) /
ParentGrid.yDelta);
if ZLevel = ParentGrid.NZ then
K := ZLevel - 1
else
K := ZLevel;
iIndex := K * ParentGrid.NX * ParentGrid.NY;
iIndex := iIndex + J * ParentGrid.NY;
iIndex := iIndex + I;
if iIndex < PointList.Count - 1 then
begin
dp := T3DSPoint(PointList.Objects[iIndex]).ScalarVal;
dratio := (MaxValue - dp) / (MaxValue - MinValue);
bforward := false;
ColourRamp(dratio, bforward, col1, col2, rstar);
glC1 := TGLColor.Create(nil);
glC2 := TGLColor.Create(nil);
glC1.AsWinColor := col1;
glC2.AsWinColor := col2;
VectorLerp(glC1.color, glC2.color, rstar, colorvect);
color := colorvect;
glC1.Free;
glC2.Free;
color.V[3] := 0.75;
end
else
color := clrwhite;
end;
// ----- T3DStructuredScalar.ContourXZ-----------------------------------------
procedure T3DStructuredScalar.ContourXZ(const x, y: single; var z: single;
var color: TColorVector; var texPoint: TTexPoint);
const
SMALL = 0.01;
var
I, J, K, iIndex: integer;
dp: single;
dratio, rstar: double;
col1, col2: TColor;
bforward: boolean;
colorvect: TColorVector;
glC1, glC2: TGLColor;
begin
// flat - its a cut plane
z := 0.0;
I := Trunc((x - ParentGrid.xlo - 0.01 * ParentGrid.xDelta) /
ParentGrid.xDelta);
J := Trunc((y - ParentGrid.zlo - 0.01 * ParentGrid.zDelta) /
ParentGrid.zDelta);
if YLevel = ParentGrid.NY then
K := YLevel - 1
else
K := YLevel;
iIndex := J * ParentGrid.NX * ParentGrid.NY;
iIndex := iIndex + K * ParentGrid.NX;
iIndex := iIndex + I;
if iIndex < PointList.Count - 1 then
begin
dp := T3DSPoint(PointList.Objects[iIndex]).ScalarVal;
dratio := (MaxValue - dp) / (MaxValue - MinValue);
bforward := false;
ColourRamp(dratio, bforward, col1, col2, rstar);
glC1 := TGLColor.Create(nil);
glC2 := TGLColor.Create(nil);
glC1.AsWinColor := col1;
glC2.AsWinColor := col2;
VectorLerp(glC1.color, glC2.color, rstar, colorvect);
color := colorvect;
color.V[3] := 0.75;
// color := clrRed;
glC1.Free;
glC2.Free;
end
else
color := clrwhite;
end;
// ----- T3DStructuredScalar.ContourYZ-----------------------------------------
procedure T3DStructuredScalar.ContourYZ(const x, y: single; var z: single;
var color: TColorVector; var texPoint: TTexPoint);
const
SMALL = 0.01;
var
I, J, K, iIndex: integer;
dp: single;
dratio, rstar: double;
col1, col2: TColor;
bforward: boolean;
colorvect: TColorVector;
glC1, glC2: TGLColor;
begin
// flat - its a cut plane
z := 0.0;
I := Trunc((x - ParentGrid.ylo - 0.01 * ParentGrid.yDelta) /
ParentGrid.yDelta);
J := Trunc((y - ParentGrid.zlo - 0.01 * ParentGrid.zDelta) /
ParentGrid.zDelta);
if XLevel = ParentGrid.NX then
K := XLevel - 1
else
K := XLevel;
iIndex := J * ParentGrid.NX * ParentGrid.NY;
iIndex := iIndex + I * ParentGrid.NY;
iIndex := iIndex + K;
if iIndex < PointList.Count - 1 then
begin
dp := T3DSPoint(PointList.Objects[iIndex]).ScalarVal;
dratio := (MaxValue - dp) / (MaxValue - MinValue);
bforward := false;
ColourRamp(dratio, bforward, col1, col2, rstar);
glC1 := TGLColor.Create(nil);
glC2 := TGLColor.Create(nil);
glC1.AsWinColor := col1;
glC2.AsWinColor := col2;
VectorLerp(glC1.color, glC2.color, rstar, colorvect);
color := colorvect;
// color := clrRed;
color.V[3] := 0.75;
glC1.Free;
glC2.Free;
end
else
color := clrwhite;
end;
// ----- T3DStructuredScalar.Create --------------------------------------------
constructor T3DStructuredScalar.Create(aParent: T3DStructuredDataSet);
begin
ParentGrid := aParent;
PointList := TStringList.Create;
DummyCube := TGLDummyCube(ParentGrid.DummyCube.AddNewChild(TGLDummyCube));
CutXY := TGLHeightField(DummyCube.AddNewChild(TGLHeightField));
CutXY.Material.BlendingMode := bmTransparency;
CutXZ := TGLHeightField(DummyCube.AddNewChild(TGLHeightField));
CutXZ.Material.BlendingMode := bmTransparency;
CutYZ := TGLHeightField(DummyCube.AddNewChild(TGLHeightField));
CutYZ.Material.BlendingMode := bmTransparency;
ZLevel := 0;
InitCutPlanes;
end;
// ----- T3DStructuredScalar.Destroy -------------------------------------------
destructor T3DStructuredScalar.Destroy;
begin
CutXY.Free;
CutXZ.Free;
CutYZ.Free;
DummyCube.Free;
PointList.Free;
end;
// ----- T3DStructuredScalar.GetMinMax -----------------------------------------
procedure T3DStructuredScalar.GetMinMax;
const
BIG = 1E30;
var
I: integer;
d: double;
begin
MinValue := BIG;
MaxValue := -BIG;
for I := 0 to PointList.Count - 1 do
begin
d := T3DSPoint(PointList.Objects[I]).ScalarVal;
if d > MaxValue then
MaxValue := d;
if d < MinValue then
MinValue := d;
end;
end;
// =============================================================================
// T3DStructuredDataSet Implementation
// =============================================================================
procedure T3DStructuredDataSet.GenerateBoundingBox;
begin
// probably should be done after reading in?
Box.Parts := Box.Parts + [gpZ];
Box.LineColor.AsWinColor := clBlue;
with Box.XSamplingScale do
begin
Origin := xlo;
Min := xlo;
Step := (xhi - xlo);
Max := xhi;
end;
with Box.YSamplingScale do
begin
Origin := ylo;
Min := ylo;
Step := (yhi - ylo);
Max := yhi;
end;
with Box.ZSamplingScale do
begin
Origin := zlo;
Min := zlo;
Step := (zhi - zlo);
Max := zhi;
end;
end;
// ----- T3DStructuredDataSet.Create -------------------------------------------
constructor T3DStructuredDataSet.Create(aDummyCube: TGLDummyCube);
begin
inherited Create;
fDummyCube := aDummyCube; { ** assign externally }
FBox := TGLXYZGrid(DummyCube.AddNewChild(TGLXYZGrid));
FScalarData := TStringList.Create;
FVectorData := TStringList.Create;
end;
// ------ T3DStructuredDataSet.Destroy -----------------------------------------
destructor T3DStructuredDataSet.Destroy;
begin
FBox.Free;
// clear objects first
while ScalarData.Count > 0 do
begin
T3DStructuredScalar(FScalarData.Objects[0]).Free;
FScalarData.Delete(0);
end;
FScalarData.Free;
FVectorData.Free;
inherited Destroy;
end;
// ----- T3dStructuredDataSet.ImportVTKFile ------------------------------------
function T3DStructuredDataSet.ImportVTKFile(sFileName: string): integer;
var
sLine, s1, sTemp: string;
lines: TStringList;
ic, iPos, iIndex: integer;
bSeek: boolean;
sds: T3DStructuredScalar;
spt: T3DSPoint;
I, J, K: integer;
// ----- SeekNextLine ----------------------------------------------------------
procedure SeekNextLine;
var
bSeek: boolean;
begin
bSeek := true;
while bSeek do
begin
sLine := lines.Strings[ic];
if (Trim(sLine) = '') then
Inc(ic)
else
bSeek := false;
end;
end;
begin
lines := TStringList.Create;
lines.LoadFromFile(sFileName);
ic := 0;
// read header
sLine := lines.Strings[0];
if Pos('# vtk DataFile Version', sLine) > 0 then
begin
Inc(ic);
Description := lines.Strings[1];
Inc(ic);
if (lines.Strings[ic] = 'ASCII') then
begin
Inc(ic);
bSeek := true;
while bSeek do
begin
sLine := lines.Strings[ic];
if (Trim(sLine) = '') then
Inc(ic)
else
bSeek := false;
end;
if (sLine <> 'DATASET STRUCTURED_POINTS') then
begin
MessageDlg('Only STRUCTURED_POINTS supported!', mtError, [mbOK], 0);
lines.Free;
exit;
end;
Inc(ic);
// read the Dimensions. Note NX, NY, NZ must be greater than 1
sLine := lines[ic];
StripString(sLine, s1); // "Dimensions"
StripString(sLine, s1);
NX := StrToInt(s1);
StripString(sLine, s1);
NY := StrToInt(s1);
StripString(sLine, s1);
NZ := StrToInt(s1);
Inc(ic);
NYNZ := NY * NZ;
{ ** read in the origin position }
sLine := lines[ic];
StripString(sLine, s1); // "Type"
StripString(sLine, s1);
xlo := StrToFloat(s1);
StripString(sLine, s1);
ylo := StrToFloat(s1);
StripString(sLine, s1);
zlo := StrToFloat(s1);
Inc(ic);
// read in the deltas/steps
sLine := lines[ic];
StripString(sLine, s1);
StripString(sLine, s1);
xDelta := StrToFloat(s1);
StripString(sLine, s1);
yDelta := StrToFloat(s1);
StripString(sLine, s1);
zDelta := StrToFloat(s1);
xhi := xlo + NX * xDelta;
yhi := ylo + NY * yDelta;
zhi := zlo + NZ * zDelta;
Inc(ic);
GenerateBoundingBox;
SeekNextLine; // this sets the current values of sLine
StripString(sLine, s1);
StripString(sLine, s1);
N := StrToInt(s1);
Inc(ic);
Inc(ic); // skip scalar/vector
Inc(ic); // skip lookup table
SeekNextLine;
sds := T3DStructuredScalar.Create(self); // will initialise cut planes
ScalarData.AddObject('1', sds);
while (T3DStructuredScalar(ScalarData.Objects[0]).PointList.Count < N) do
begin
while (sLine <> '') do
begin
StripString(sLine, s1);
spt := T3DSPoint.Create;
spt.ScalarVal := StrToFloat(s1);
iIndex := T3DStructuredScalar(ScalarData.Objects[0]).PointList.Count;
T3DStructuredScalar(ScalarData.Objects[0])
.PointList.AddObject(IntToStr(iIndex + 1), spt);
end;
if (ic < lines.Count - 1) then
begin
Inc(ic);
sLine := lines[ic];
end;
end;
T3DStructuredScalar(ScalarData.Objects[0]).GetMinMax;
end
else
MessageDlg('Only ASCII files supported..', mtWarning, [mbOK], 0);
end
else
MessageDlg('Not a VTK File!', mtError, [mbOK], 0);
lines.Free;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clImap4FileHandler;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
{$IFDEF DELPHI7}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ENDIF}
uses
Classes, clTcpServer, clImap4Server, clImapUtils, clMailMessage, SyncObjs;
type
TclImap4FileCommandConnection = class(TclImap4CommandConnection)
private
FMessages: TStringList;
public
constructor Create;
destructor Destroy; override;
property Messages: TStringList read FMessages;
end;
TclImap4LoadMessageEvent = procedure (Sender: TObject; AConnection: TclImap4CommandConnection;
const AMailBoxPath, AMessageFile: string; var ACanLoad: Boolean) of object;
TclImap4FileHandler = class(TComponent)
private
FAccessor: TCriticalSection;
FServer: TclImap4Server;
FMailBoxDir: string;
FMailBoxInfoFile: string;
FOnLoadMessage: TclImap4LoadMessageEvent;
function GetNextCounter(AConnection: TclImap4CommandConnection): Integer;
function GetCurrentCounter(AConnection: TclImap4CommandConnection): Integer;
procedure SetServer(const Value: TclImap4Server);
procedure SetMailBoxDir(const Value: string);
procedure SetMailBoxInfoFile(const Value: string);
procedure DoCreateConnection(Sender: TObject; var AConnection: TclCommandConnection);
procedure DoCanAppendMessage(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMailBox: string; var Result: TclImap4MailBoxResult);
procedure DoCopyMessages(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMessageSet, AMailBox: string; AUseUID: Boolean; var Result: TclImap4MailBoxResult);
procedure DoCreateMailBox(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMailBox: string; var Result: TclImap4MailBoxResult);
procedure DoDeleteMailBox(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMailBox: string; var Result: TclImap4MailBoxResult);
procedure DoPurgeMessages(Sender: TObject; AConnection: TclImap4CommandConnection;
IsSilent: Boolean; AMessageIDs: TStrings; var Result: TclImap4MessageResult);
procedure DoFetchMessages(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMessageSet, ADataItems: string; AUseUID: Boolean; AResponse: TclImap4FetchResponseList;
var Result: TclImap4MessageResult);
procedure DoGetMailBoxes(Sender: TObject; AConnection: TclImap4CommandConnection;
const AReferenceName, ACriteria: string; AMailBoxes: TclImap4MailBoxList);
procedure DoGetMailBoxInfo(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMailBox: string; IsSelectMailBox: Boolean; AMailBoxInfo: TclImap4MailBoxInfo;
var Result: TclImap4MailBoxResult);
procedure DoMessageAppended(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMailBox: string; AFlags: TclMailMessageFlags; AMessage: TStrings;
var Result: TclImap4MailBoxResult);
procedure DoRenameMailBox(Sender: TObject; AConnection: TclImap4CommandConnection;
const ACurrentName, ANewName: string; var Result: TclImap4MailBoxResult);
procedure DoSearchMessages(Sender: TObject; AConnection: TclImap4CommandConnection;
const ASearchCriteria: string; AUseUID: Boolean; AMessageIDs: TStrings;
var Result: TclImap4MessageResult);
procedure DoStoreMessages(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMessageSet: string; AFlagsMethod: TclSetFlagsMethod; AFlags: TclMailMessageFlags;
IsSilent: Boolean; AUseUID: Boolean; AResponse: TclImap4FetchResponseList;
var Result: TclImap4MessageResult);
procedure DoSubscribeMailBox(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMailBox: string; var Result: TclImap4MailBoxResult);
procedure DoUnsubscribeMailBox(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMailBox: string; var Result: TclImap4MailBoxResult);
function GetMailBoxPath(const AUserName: string): string;
function GetIsSubscribed(const AMailBoxPath: string): Boolean;
procedure SetIsSubscribed(const AMailBoxPath: string; AIsSubscribed: Boolean);
function GetMessageFlags(AConnection: TclImap4CommandConnection;
const AMailBoxPath, AMessageFile: string): string;
function SetMessageFlags(AConnection: TclImap4CommandConnection;
const AMailBoxPath, AMessageFile: string; AFlagsMethod: TclSetFlagsMethod;
ANewFlags: TclMailMessageFlags): string;
function MailBoxToPath(const AMailBox: string): string;
procedure InternalSubscribeMailBox(AConnection: TclImap4CommandConnection;
const AMailBox: string; AIsSubscribed: Boolean; var Result: TclImap4MailBoxResult);
function GetFileTimeStamp(const AFileName: string): Integer;
procedure FillMessageList(AConnection: TclImap4CommandConnection;
const AMailBoxPath: string; AList: TStrings);
procedure UpdateMailBoxInfo(AConnection: TclImap4CommandConnection; const AMailBoxPath: string;
AMessageList: TStringList; IsSelectMailBox: Boolean;
var ARecentCount, AUnseenMessages, AFirstUnseen: Integer);
function BuildMessageInfo(const AUid: string;
AFlags: TclMailMessageFlags): string;
procedure ParseMessageInfo(const ASource: string; var AUid: string;
var AFlags: TclMailMessageFlags);
function GetMessageList(AConnection: TclImap4CommandConnection): TStringList;
function GetMessageUID(AConnection: TclImap4CommandConnection;
const AMessageFile: string): string;
function GetMsgFileByUID(AList: TStrings; AUID: Integer): string;
procedure SearchAllMessages(AConnection: TclImap4CommandConnection;
AUseUID: Boolean; AMessageIDs: TStrings);
procedure SearchMessages(AConnection: TclImap4CommandConnection;
const AKey, AParam: string; AUseUID: Boolean; AMessageIDs: TStrings);
procedure FillTargetList(AConnection: TclImap4CommandConnection;
const AMessageSet: string; AUseUID: Boolean; ATargetList: TStrings);
function GenMessageFileName(AConnection: TclImap4CommandConnection): string;
procedure FetchMessage(AConnection: TclImap4CommandConnection;
const AMessageFile: string; ARequest: TclImap4FetchRequestList;
AUseUID: Boolean; AResponseItem: TclImap4FetchResponseItem);
function GetLocalFileSize(const AFileName: string): Integer;
procedure FetchHeader(const AMessagePath, ACommand, AParams: string; AResponseItem: TclImap4FetchResponseItem);
procedure FetchHeaderFields(const AMessagePath, ACommand, AParams: string; AResponseItem: TclImap4FetchResponseItem);
procedure FetchBodyText(const AMessagePath, ACommand, AParams: string; AResponseItem: TclImap4FetchResponseItem);
procedure FetchBody(const AMessagePath, ACommand, AParams: string; AResponseItem: TclImap4FetchResponseItem);
function FetchMessageEnvelope(const AMessagePath: string): string;
function FetchBodyStructure(const AMessagePath: string): string;
procedure ParseHeaderFieldParams(const ASource: string;
AFields: TStrings);
function GetMessageInternalDate(const AMessagePath: string): TDateTime;
function DateTimeToImapTime(ADateTime: TDateTime): string;
function GetMimeBodyStructure(ABodies: TclMessageBodies): string;
procedure ExtractContentTypeParts(const AContentType: string; var AType, ASubType: string);
function GetMimeBodySize(ABody: TclMessageBody): string;
procedure GetUueBodySize(AMessage: TStrings; var ASize,
ALines: Integer);
procedure RefreshMailBoxInfo(AConnection: TclImap4CommandConnection);
function GetMailBoxInfo(AConnection: TclImap4CommandConnection;
const AMailBox: string; IsSelectMailBox: Boolean;
AMailBoxInfo: TclImap4MailBoxInfo; AMessageList: TStringList): TclImap4MailBoxResult;
procedure GetBodyIDs(const AParams: string; var ABodyIDs: array of Integer);
function GetBodyByIndex(var ABodyIDs: array of Integer;
AIndex: Integer; ABodies: TclMessageBodies): TclMessageBody;
protected
function GetMessageEnvelope(AMessage: TStrings): string; virtual;
function GetBodyStructure(AMessage: TStrings): string; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure CleanEventHandlers; virtual;
procedure InitEventHandlers; virtual;
procedure DoLoadMessage(AConnection: TclImap4CommandConnection;
const AMailBoxPath, AMessageFile: string; var ACanLoad: Boolean); virtual;
property Accessor: TCriticalSection read FAccessor;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Server: TclImap4Server read FServer write SetServer;
property MailBoxDir: string read FMailBoxDir write SetMailBoxDir;
property MailBoxInfoFile: string read FMailBoxInfoFile write SetMailBoxInfoFile;
property OnLoadMessage: TclImap4LoadMessageEvent read FOnLoadMessage write FOnLoadMessage;
end;
const
cMailBoxSection = 'MAILBOXINFO';
cMessagesSection = 'MESSAGES';
implementation
uses
Windows, SysUtils, clUtils, IniFiles, clEncoder, clPCRE;
type
TclMessageBodyIDs = array[0..9] of Integer;
{ TclImap4FileHandler }
procedure TclImap4FileHandler.CleanEventHandlers;
begin
Server.OnCreateConnection := nil;
Server.OnGetMailBoxes := nil;
Server.OnCreateMailBox := nil;
Server.OnDeleteMailBox := nil;
Server.OnRenameMailBox := nil;
Server.OnSubscribeMailBox := nil;
Server.OnUnsubscribeMailBox := nil;
Server.OnGetMailBoxInfo := nil;
Server.OnSearchMessages := nil;
Server.OnCopyMessages := nil;
Server.OnFetchMessages := nil;
Server.OnStoreMessages := nil;
Server.OnPurgeMessages := nil;
Server.OnCanAppendMessage := nil;
Server.OnMessageAppended := nil;
end;
constructor TclImap4FileHandler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAccessor := TCriticalSection.Create();
FMailBoxInfoFile := cImapMailBoxInfoFile;
end;
destructor TclImap4FileHandler.Destroy;
begin
FAccessor.Free();
inherited Destroy();
end;
procedure TclImap4FileHandler.InitEventHandlers;
begin
Server.OnCreateConnection := DoCreateConnection;
Server.OnGetMailBoxes := DoGetMailBoxes;
Server.OnCreateMailBox := DoCreateMailBox;
Server.OnDeleteMailBox := DoDeleteMailBox;
Server.OnRenameMailBox := DoRenameMailBox;
Server.OnSubscribeMailBox := DoSubscribeMailBox;
Server.OnUnsubscribeMailBox := DoUnsubscribeMailBox;
Server.OnGetMailBoxInfo := DoGetMailBoxInfo;
Server.OnSearchMessages := DoSearchMessages;
Server.OnCopyMessages := DoCopyMessages;
Server.OnFetchMessages := DoFetchMessages;
Server.OnStoreMessages := DoStoreMessages;
Server.OnPurgeMessages := DoPurgeMessages;
Server.OnCanAppendMessage := DoCanAppendMessage;
Server.OnMessageAppended := DoMessageAppended;
end;
procedure TclImap4FileHandler.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation <> opRemove) then Exit;
if (AComponent = FServer) then
begin
CleanEventHandlers();
FServer := nil;
end;
end;
procedure TclImap4FileHandler.SetServer(const Value: TclImap4Server);
begin
if (FServer <> Value) then
begin
{$IFDEF DELPHI5}
if (FServer <> nil) then
begin
FServer.RemoveFreeNotification(Self);
CleanEventHandlers();
end;
{$ENDIF}
FServer := Value;
if (FServer <> nil) then
begin
FServer.FreeNotification(Self);
InitEventHandlers();
end;
end;
end;
function TclImap4FileHandler.GetMailBoxPath(const AUserName: string): string;
begin
Result := AddTrailingBackSlash(MailBoxDir) + AddTrailingBackSlash(AUserName);
end;
function TclImap4FileHandler.GetIsSubscribed(const AMailBoxPath: string): Boolean;
var
ini: TIniFile;
begin
Result := FileExists(AMailBoxPath + MailBoxInfoFile);
if not Result then Exit;
ini := TIniFile.Create(AMailBoxPath + MailBoxInfoFile);
try
Result := ini.ReadBool(cMailBoxSection, 'Subscribed', False);
finally
ini.Free();
end;
end;
procedure TclImap4FileHandler.SetIsSubscribed(const AMailBoxPath: string; AIsSubscribed: Boolean);
var
ini: TIniFile;
begin
ini := TIniFile.Create(AMailBoxPath + MailBoxInfoFile);
try
ini.WriteBool(cMailBoxSection, 'Subscribed', AIsSubscribed);
finally
ini.Free();
end;
end;
function TclImap4FileHandler.MailBoxToPath(const AMailBox: string): string;
begin
if SameText('INBOX', AMailBox) then
begin
Result := '';
end else
begin
Result := StringReplace(AMailBox, Server.MailBoxSeparator, '\', [rfReplaceAll]);
end;
end;
procedure TclImap4FileHandler.DoGetMailBoxes(Sender: TObject;
AConnection: TclImap4CommandConnection; const AReferenceName, ACriteria: string;
AMailBoxes: TclImap4MailBoxList);
procedure CollectMailboxes(const ARegEx, APath, ABase: string);
var
sr: TSearchRec;
found: string;
item: TclImap4MailBoxItem;
begin
if SysUtils.FindFirst(APath + '*.*', faDirectory, sr) = 0 then
begin
repeat
if ((sr.Attr and faDirectory) <> 0) and (sr.Name <> '.') and (sr.Name <> '..') then
begin
found := ABase + sr.Name;
if not SameText(found, 'INBOX') then
begin
if RE_Match(found, ARegEx, PCRE_CASELESS) then
begin
item := AMailBoxes.Add();
item.Name := StringReplace(found, '\', Server.MailBoxSeparator, [rfReplaceAll]);
item.IsSubscribed := GetIsSubscribed(APath + sr.Name + '\');
end;
CollectMailboxes(ARegEx, APath + sr.Name + '\', found + Server.MailBoxSeparator);
end else
begin
CollectMailboxes(ARegEx, APath + 'INBOX' + '\', 'INBOX' + Server.MailBoxSeparator);
end;
end;
until SysUtils.FindNext(sr) <> 0;
SysUtils.FindClose(sr);
end;
end;
var
i: Integer;
pattern, regEx: string;
item: TclImap4MailBoxItem;
begin
pattern := AReferenceName + ACriteria;
regEx := '^';
for i := 1 to Length(pattern) do
begin
case pattern[i] of
'*' : regEx := regEx + '.*';
'%' : regEx := regEx + '[^' + Server.MailBoxSeparator + ']*';
'+', '-', '.', '$', '(', ')': regEx := regEx + '\' + pattern[i];
else regEx := regEx + pattern[i];
end;
end;
regEx := regEx + '$';
if RE_Match('INBOX', regEx, PCRE_CASELESS) then
begin
item := AMailBoxes.Add();
item.Name := 'INBOX';
item.IsSubscribed := GetIsSubscribed(GetMailBoxPath(AConnection.UserName));
end;
CollectMailboxes(regEx, GetMailBoxPath(AConnection.UserName), '');
end;
procedure TclImap4FileHandler.DoCreateMailBox(Sender: TObject;
AConnection: TclImap4CommandConnection; const AMailBox: string; var Result: TclImap4MailBoxResult);
var
path: string;
begin
if SameText('INBOX', AMailBox) then
begin
Result := mrAccessDenied;
Exit;
end;
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AMailBox));
if DirectoryExists(path) then
begin
Result := mrAlreadyExists;
end else
if ForceFileDirectories(path) then
begin
Result := mrSuccess;
end else
begin
Result := mrAccessDenied;
end;
end;
procedure TclImap4FileHandler.DoDeleteMailBox(Sender: TObject;
AConnection: TclImap4CommandConnection; const AMailBox: string; var Result: TclImap4MailBoxResult);
var
path: string;
begin
if SameText('INBOX', AMailBox) then
begin
Result := mrAccessDenied;
Exit;
end;
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AMailBox));
if DirectoryExists(path) then
begin
if DeleteRecursiveDir(path) then
begin
Result := mrSuccess;
end else
begin
Result := mrAccessDenied;
end;
end else
begin
Result := mrNotFound;
end;
end;
procedure TclImap4FileHandler.DoRenameMailBox(Sender: TObject; AConnection: TclImap4CommandConnection;
const ACurrentName, ANewName: string; var Result: TclImap4MailBoxResult);
var
curName, newName: string;
begin
if SameText('INBOX', ACurrentName) or SameText('INBOX', ANewName) then
begin
Result := mrAccessDenied;
Exit;
end;
curName := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(ACurrentName));
newName := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(ANewName));
if DirectoryExists(curName) then
begin
if not DirectoryExists(newName) then
begin
if RenameFile(curName, newName) then
begin
Result := mrSuccess;
end else
begin
Result := mrAccessDenied;
end;
end else
begin
Result := mrAlreadyExists;
end;
end else
begin
Result := mrNotFound;
end;
end;
procedure TclImap4FileHandler.InternalSubscribeMailBox(AConnection: TclImap4CommandConnection;
const AMailBox: string; AIsSubscribed: Boolean; var Result: TclImap4MailBoxResult);
var
path: string;
begin
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AMailBox));
if DirectoryExists(path) then
begin
try
SetIsSubscribed(path, AIsSubscribed);
Result := mrSuccess;
except
Result := mrAccessDenied;
end;
end else
begin
Result := mrNotFound;
end;
end;
procedure TclImap4FileHandler.DoSubscribeMailBox(Sender: TObject;
AConnection: TclImap4CommandConnection; const AMailBox: string; var Result: TclImap4MailBoxResult);
begin
InternalSubscribeMailBox(AConnection, AMailBox, True, Result);
end;
procedure TclImap4FileHandler.DoUnsubscribeMailBox(Sender: TObject;
AConnection: TclImap4CommandConnection; const AMailBox: string; var Result: TclImap4MailBoxResult);
begin
InternalSubscribeMailBox(AConnection, AMailBox, False, Result);
end;
function TclImap4FileHandler.GetFileTimeStamp(const AFileName: string): Integer;
var
Handle: THandle;
FindData: TWin32FindData;
pTime: TFileTime;
s: string;
begin
s := AFileName;
if (s <> '') and (s[Length(s)] = '\') then
begin
SetLength(s, Length(s) - 1);
end;
Handle := FindFirstFile(PChar(s), FindData);
if Handle <> INVALID_HANDLE_VALUE then
begin
Windows.FindClose(Handle);
FileTimeToLocalFileTime(FindData.ftLastWriteTime, pTime);
if FileTimeToDosDateTime(pTime, LongRec(Result).Hi, LongRec(Result).Lo) then
begin
Exit;
end;
end;
Result := 0;
end;
function TclImap4FileHandler.GetMessageInternalDate(const AMessagePath: string): TDateTime;
var
Handle: THandle;
FindData: TWin32FindData;
s: string;
begin
Result := 0;
s := AMessagePath;
if (s <> '') and (s[Length(s)] = '\') then
begin
SetLength(s, Length(s) - 1);
end;
Handle := FindFirstFile(PChar(s), FindData);
if Handle <> INVALID_HANDLE_VALUE then
begin
Windows.FindClose(Handle);
Result := ConvertFileTimeToDateTime(FindData.ftLastWriteTime);
end;
end;
function TclImap4FileHandler.GetMessageEnvelope(AMessage: TStrings): string;
function Normalize(const ASource: string): string;
begin
if (ASource = '') then
begin
Result := 'NIL';
end else
begin
Result := '"' + ASource + '"';
end;
end;
function GetField(ASource, AFieldList: TStrings; const AName: string): string;
begin
Result := GetHeaderFieldValue(ASource, AFieldList, AName);
Result := Normalize(Result);
end;
function GetMBName(const AEmail: string): string;
var
ind: Integer;
begin
Result := '';
ind := system.Pos('@', AEmail);
if (ind > 0) then
begin
Result := system.Copy(AEmail, 1, ind - 1);
end;
end;
function GetDName(const AEmail: string): string;
var
ind: Integer;
begin
Result := AEmail;
ind := system.Pos('@', AEmail);
if (ind > 0) then
begin
Result := system.Copy(AEmail, ind + 1, Length(AEmail));
end;
end;
function GetMails(ASource, AFieldList: TStrings; const AName: string): string;
var
i: Integer;
list: TStrings;
name, email: string;
begin
Result := '';
list := TStringList.Create();
try
list.Text := StringReplace(GetHeaderFieldValue(ASource, AFieldList, AName), ',', #13#10, [rfReplaceAll]);
for i := 0 to list.Count - 1 do
begin
GetEmailAddressParts(list[i], name, email);
Result := Result + '(' + Normalize(name) + #32'NIL'#32 + Normalize(GetMBName(email)) + #32
+ Normalize(GetDName(email)) + ')';
end;
finally
list.Free();
end;
if (Result = '') then
begin
Result := 'NIL';
end else
begin
Result := '(' + Result + ')';
end;
end;
var
fieldList: TStrings;
from, sender: string;
begin
fieldList := nil;
try
fieldList := TStringList.Create();
GetHeaderFieldList(0, AMessage, fieldList);
Result := Result + GetField(AMessage, fieldList, 'Date') + #32;
Result := Result + GetField(AMessage, fieldList, 'Subject') + #32;
from := GetMails(AMessage, fieldList, 'From');
Result := Result + from + #32;
sender := GetMails(AMessage, fieldList, 'Sender');
if (sender = 'NIL') then
begin
sender := from;
end;
Result := Result + sender + #32;
Result := Result + GetMails(AMessage, fieldList, 'Reply-To') + #32;
Result := Result + GetMails(AMessage, fieldList, 'To') + #32;
Result := Result + GetMails(AMessage, fieldList, 'Cc') + #32;
Result := Result + GetMails(AMessage, fieldList, 'Bcc') + #32;
Result := Result + 'NIL'#32;
Result := Result + GetField(AMessage, fieldList, 'Message-ID');
finally
fieldList.Free();
end;
end;
procedure TclImap4FileHandler.DoLoadMessage(AConnection: TclImap4CommandConnection;
const AMailBoxPath, AMessageFile: string; var ACanLoad: Boolean);
begin
if Assigned(OnLoadMessage) then
begin
OnLoadMessage(Self, AConnection, AMailBoxPath, AMessageFile, ACanLoad);
end;
end;
procedure TclImap4FileHandler.FillMessageList(AConnection: TclImap4CommandConnection;
const AMailBoxPath: string; AList: TStrings);
var
searchRec: TSearchRec;
canLoad: Boolean;
begin
AList.Clear();
if SysUtils.FindFirst(AMailBoxPath + '*.*', 0, searchRec) = 0 then
begin
repeat
canLoad := not SameText(MailBoxInfoFile, searchRec.Name);
DoLoadMessage(AConnection, AMailBoxPath, searchRec.Name, canLoad);
if canLoad then
begin
AList.Add(searchRec.Name);
end;
until (SysUtils.FindNext(searchRec) <> 0);
SysUtils.FindClose(searchRec);
end;
end;
procedure TclImap4FileHandler.ParseMessageInfo(const ASource: string; var AUid: string;
var AFlags: TclMailMessageFlags);
var
ind: Integer;
s: string;
begin
ind := system.Pos(':', ASource);
if (ind > 0) then
begin
AUid := Trim(system.Copy(ASource, 1, ind - 1));
s := Trim(system.Copy(ASource, ind + 1, MaxInt));
end;
AFlags := GetImapMessageFlagsByStr(UpperCase(s));
end;
function TclImap4FileHandler.BuildMessageInfo(const AUid: string; AFlags: TclMailMessageFlags): string;
begin
Result := AUid + ':' + GetStrByImapMessageFlags(AFlags);
end;
function CompareMessageUIDs(List: TStringList; Index1, Index2: Integer): Integer;
var
uid1, uid2: Integer;
begin
uid1 := Integer(List.Objects[Index1]);
uid2 := Integer(List.Objects[Index2]);
if (uid1 < uid2) then
begin
Result := -1;
end else
if (uid1 > uid2) then
begin
Result := 1;
end else
begin
Result := 0;
end;
end;
procedure TclImap4FileHandler.UpdateMailBoxInfo(AConnection: TclImap4CommandConnection;
const AMailBoxPath: string; AMessageList: TStringList; IsSelectMailBox: Boolean;
var ARecentCount, AUnseenMessages, AFirstUnseen: Integer);
var
i: Integer;
ini: TIniFile;
list: TStrings;
uid: string;
flags: TclMailMessageFlags;
begin
FAccessor.Enter();
try
ARecentCount := 0;
AUnseenMessages := 0;
AFirstUnseen := 0;
ini := nil;
list := nil;
try
ini := TIniFile.Create(AMailBoxPath + MailBoxInfoFile);
list := TStringList.Create();
ini.ReadSection(cMessagesSection, list);
for i := 0 to list.Count - 1 do
begin
if (AMessageList.IndexOf(list[i]) < 0) then
begin
ini.DeleteKey(cMessagesSection, list[i]);
end;
end;
for i := 0 to AMessageList.Count - 1 do
begin
uid := '';
flags := [];
ParseMessageInfo(ini.ReadString(cMessagesSection, AMessageList[i], ''), uid, flags);
if (uid = '') then
begin
uid := IntToStr(GetNextCounter(AConnection));
flags := flags + [mfRecent];
end else
if IsSelectMailBox then
begin
flags := flags - [mfRecent];
end;
ini.WriteString(cMessagesSection, AMessageList[i], BuildMessageInfo(uid, flags));
AMessageList.Objects[i] := TObject(Integer(StrToInt(uid)));
end;
AMessageList.CustomSort(CompareMessageUIDs);
for i := 0 to AMessageList.Count - 1 do
begin
uid := '';
flags := [];
ParseMessageInfo(ini.ReadString(cMessagesSection, AMessageList[i], ''), uid, flags);
if not (mfSeen in flags) then
begin
Inc(AUnseenMessages);
if (AFirstUnseen = 0) then
begin
AFirstUnseen := i + 1;
end;
end;
if (mfRecent in flags) then
begin
Inc(ARecentCount);
end;
end;
finally
list.Free();
ini.Free();
end;
finally
FAccessor.Leave();
end;
end;
function TclImap4FileHandler.GetMessageList(AConnection: TclImap4CommandConnection): TStringList;
begin
Result := (AConnection as TclImap4FileCommandConnection).Messages;
end;
function TclImap4FileHandler.GetMessageUID(AConnection: TclImap4CommandConnection;
const AMessageFile: string): string;
var
ind: Integer;
list: TStringList;
begin
list := GetMessageList(AConnection);
ind := list.IndexOf(AMessageFile);
Result := IntToStr(Integer(list.Objects[ind]));
end;
function TclImap4FileHandler.GetMsgFileByUID(AList: TStrings; AUID: Integer): string;
var
i: Integer;
begin
for i := 0 to AList.Count - 1 do
begin
if (Integer(AList.Objects[i]) = AUID) then
begin
Result := AList[i];
Exit;
end;
end;
Result := '';
Assert(False);
end;
procedure TclImap4FileHandler.RefreshMailBoxInfo(AConnection: TclImap4CommandConnection);
var
mailboxInfo: TclImap4MailBoxInfo;
result: TclImap4MailBoxResult;
begin
//TODO
mailboxInfo := TclImap4MailBoxInfo.Create();
try
result := GetMailBoxInfo(AConnection, AConnection.CurrentMailBox.Name,
False, mailboxInfo, GetMessageList(AConnection));
if (result = mrSuccess) then
begin
AConnection.CurrentMailBox.Assign(mailboxInfo);
end;
finally
mailboxInfo.Free();
end;
end;
function TclImap4FileHandler.GetMailBoxInfo(AConnection: TclImap4CommandConnection;
const AMailBox: string; IsSelectMailBox: Boolean;
AMailBoxInfo: TclImap4MailBoxInfo; AMessageList: TStringList): TclImap4MailBoxResult;
var
path: string;
recentCount, unseenCount, firstUnseen: Integer;
begin
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AMailBox));
if DirectoryExists(path) then
begin
try
AMailBoxInfo.Clear();
AMailBoxInfo.Name := AMailBox;
AMailBoxInfo.Flags := [mfAnswered, mfFlagged, mfDeleted, mfSeen, mfDraft, mfRecent];
AMailBoxInfo.ChangeableFlags := [mfAnswered, mfFlagged, mfDeleted, mfSeen, mfDraft];
FillMessageList(AConnection, path, AMessageList);
recentCount := 0;
unseenCount := 0;
firstUnseen := 0;
UpdateMailBoxInfo(AConnection, path, AMessageList, IsSelectMailBox, recentCount, unseenCount, firstUnseen);
AMailBoxInfo.ExistsMessages := AMessageList.Count;
AMailBoxInfo.RecentMessages := recentCount;
AMailBoxInfo.UnseenMessages := unseenCount;
AMailBoxInfo.FirstUnseen := firstUnseen;
AMailBoxInfo.UIDValidity := IntToStr(GetFileTimeStamp(path));
AMailBoxInfo.UIDNext := IntToStr(GetCurrentCounter(AConnection));
Result := mrSuccess;
except
Result := mrAccessDenied;
end;
end else
begin
Result := mrNotFound;
end;
end;
procedure TclImap4FileHandler.DoGetMailBoxInfo(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMailBox: string; IsSelectMailBox: Boolean; AMailBoxInfo: TclImap4MailBoxInfo;
var Result: TclImap4MailBoxResult);
var
list, messageList: TStringList;
begin
list := nil;
try
if IsSelectMailBox then
begin
messageList := GetMessageList(AConnection);
end else
begin
list := TStringList.Create();
messageList := list;
end;
Result := GetMailBoxInfo(AConnection, AMailBox, IsSelectMailBox, AMailBoxInfo, messageList);
finally
list.Free();
end;
end;
procedure TclImap4FileHandler.SearchAllMessages(AConnection: TclImap4CommandConnection;
AUseUID: Boolean; AMessageIDs: TStrings);
var
i: Integer;
msgList: TStrings;
begin
msgList := GetMessageList(AConnection);
for i := 0 to msgList.Count - 1 do
begin
if AUseUID then
begin
AMessageIDs.Add(GetMessageUID(AConnection, msgList[i]));
end else
begin
AMessageIDs.Add(IntToStr(i + 1));
end;
end;
end;
procedure TclImap4FileHandler.SearchMessages(AConnection: TclImap4CommandConnection;
const AKey, AParam: string; AUseUID: Boolean; AMessageIDs: TStrings);
var
i: Integer;
msgList, msgSrc, fieldList: TStrings;
path: string;
begin
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AConnection.CurrentMailBox.Name));
msgList := GetMessageList(AConnection);
fieldList := TStringList.Create();
msgSrc := TStringList.Create();
try
for i := 0 to msgList.Count - 1 do
begin
if FileExists(path + msgList[i]) then
begin
msgSrc.LoadFromFile(path + msgList[i]);
GetHeaderFieldList(0, msgSrc, fieldList);
if (system.Pos(UpperCase(AParam), UpperCase(GetHeaderFieldValue(msgSrc, fieldList, AKey))) > 0) then
begin
if AUseUID then
begin
AMessageIDs.Add(GetMessageUID(AConnection, msgList[i]));
end else
begin
AMessageIDs.Add(IntToStr(i + 1));
end;
end;
end;
end;
finally
msgSrc.Free();
fieldList.Free();
end;
end;
procedure TclImap4FileHandler.DoSearchMessages(Sender: TObject; AConnection: TclImap4CommandConnection;
const ASearchCriteria: string; AUseUID: Boolean; AMessageIDs: TStrings; var Result: TclImap4MessageResult);
var
ind: Integer;
key, param: string;
begin
RefreshMailBoxInfo(AConnection);
ind := Pos(#32, ASearchCriteria);
if (ind > 0) then
begin
key := UpperCase(system.Copy(ASearchCriteria, 1, ind - 1));
param := system.Copy(ASearchCriteria, ind + 1, Length(ASearchCriteria));
end else
begin
key := UpperCase(ASearchCriteria);
param := '';
end;
AMessageIDs.Clear();
Result := msOk;
try
if (key = 'ALL') then
begin
SearchAllMessages(AConnection, AUseUID, AMessageIDs);
end else
if (key = 'FROM') or (key = 'TO') or (key = 'SUBJECT') then
begin
SearchMessages(AConnection, key, param, AUseUID, AMessageIDs);
end else
begin
Result := msBad;
end;
except
Result := msNo;
end;
end;
procedure TclImap4FileHandler.FillTargetList(AConnection: TclImap4CommandConnection;
const AMessageSet: string; AUseUID: Boolean; ATargetList: TStrings);
var
i: Integer;
msgList, msgFileList: TStrings;
begin
msgList := TStringList.Create();
try
msgFileList := GetMessageList(AConnection);
if AUseUID then
begin
for i := 0 to msgFileList.Count - 1 do
begin
msgList.Add(GetMessageUID(AConnection, msgFileList[i]));
end;
end else
begin
for i := 0 to msgFileList.Count - 1 do
begin
msgList.Add(IntToStr(i + 1));
end;
end;
ParseMessageSet(AMessageSet, msgList, ATargetList);
if AUseUID then
begin
for i := 0 to ATargetList.Count - 1 do
begin
ATargetList[i] := GetMsgFileByUID(msgFileList, StrToInt(ATargetList[i]));
end;
end else
begin
for i := 0 to ATargetList.Count - 1 do
begin
ATargetList[i] := msgFileList[StrToInt(ATargetList[i]) - 1];
end;
end;
finally
msgList.Free();
end;
end;
function TclImap4FileHandler.GenMessageFileName(AConnection: TclImap4CommandConnection): string;
begin
Result := GetUniqueFileName(Format('MAIL%.8d.MSG', [GetNextCounter(AConnection)]));
end;
procedure TclImap4FileHandler.DoCopyMessages(Sender: TObject; AConnection: TclImap4CommandConnection;
const AMessageSet, AMailBox: string; AUseUID: Boolean; var Result: TclImap4MailBoxResult);
var
i: Integer;
s, currentPath, targetPath: string;
targetList: TStrings;
begin
currentPath := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AConnection.CurrentMailBox.Name));
targetPath := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AMailBox));
if not DirectoryExists(targetPath) then
begin
Result := mrNotFound;
Exit;
end;
try
targetList := TStringList.Create();
try
FillTargetList(AConnection, AMessageSet, AUseUID, targetList);
for i := 0 to targetList.Count - 1 do
begin
s := targetPath + targetList[i];
while not CopyFile(PChar(currentPath + targetList[i]), PChar(s), True) do
begin
s := targetPath + GenMessageFileName(AConnection);
end;
end;
finally
targetList.Free();
end;
Result := mrSuccess;
except
Result := mrAccessDenied;
end;
end;
function TclImap4FileHandler.GetLocalFileSize(const AFileName: string): Integer;
var
h: THandle;
begin
h := CreateFile(PChar(AFileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
if (h <> INVALID_HANDLE_VALUE) then
begin
Result := GetFileSize(h, nil);
CloseHandle(h);
end else
begin
Result := -1;
end;
end;
function TclImap4FileHandler.GetMessageFlags(AConnection: TclImap4CommandConnection;
const AMailBoxPath, AMessageFile: string): string;
var
ini: TIniFile;
uid: string;
flags: TclMailMessageFlags;
begin
Result := '';
if not FileExists(AMailBoxPath + MailBoxInfoFile) then Exit;
ini := TIniFile.Create(AMailBoxPath + MailBoxInfoFile);
try
Result := ini.ReadString(cMessagesSection, AMessageFile, '');
ParseMessageInfo(Result, uid, flags);
Result := GetStrByImapMessageFlags(flags);
finally
ini.Free();
end;
end;
function TclImap4FileHandler.SetMessageFlags(AConnection: TclImap4CommandConnection;
const AMailBoxPath, AMessageFile: string; AFlagsMethod: TclSetFlagsMethod;
ANewFlags: TclMailMessageFlags): string;
var
ini: TIniFile;
uid: string;
flags: TclMailMessageFlags;
begin
Result := '';
ini := nil;
try
ini := TIniFile.Create(AMailBoxPath + MailBoxInfoFile);
Result := ini.ReadString(cMessagesSection, AMessageFile, '');
ParseMessageInfo(Result, uid, flags);
case AFlagsMethod of
fmReplace: flags := ANewFlags;
fmAdd: flags := flags + ANewFlags;
fmRemove: flags := flags - ANewFlags;
end;
ini.WriteString(cMessagesSection, AMessageFile, BuildMessageInfo(uid, flags));
Result := GetStrByImapMessageFlags(flags);
finally
ini.Free();
end;
end;
procedure TclImap4FileHandler.ParseHeaderFieldParams(const ASource: string; AFields: TStrings);
var
i, ind: Integer;
s: string;
begin
s := ASource;
ind := system.Pos('(', s);
if (ind > 0) then
begin
s := system.Copy(s, ind + 1, Length(s));
end;
ind := system.Pos(')', s);
if (ind > 0) then
begin
SetLength(s, ind - 1);
end;
AFields.Text := StringReplace(s, #32, #13#10, [rfReplaceAll]);
for i := 0 to AFields.Count - 1 do
begin
AFields[i] := LowerCase(Trim(AFields[i]));
end;
end;
procedure TclImap4FileHandler.GetBodyIDs(const AParams: string; var ABodyIDs: array of Integer);
var
i, ind: Integer;
begin
for i := 0 to High(ABodyIDs) do
begin
ABodyIDs[i] := 0;
end;
ind := 0;
for i := 1 to Length(AParams) do
begin
if(AParams[i] in [#$30..#$39]) then
begin
ABodyIDs[ind] := StrToInt(AParams[i]);
end else
if(AParams[i] = '.') then
begin
Inc(ind);
if (ind > High(ABodyIDs)) then
begin
Break;
end;
end else
begin
Break;
end;
end;
end;
procedure TclImap4FileHandler.FetchHeaderFields(const AMessagePath, ACommand, AParams: string;
AResponseItem: TclImap4FetchResponseItem);
function GetHeaderFieldsStr(AHeader: TStrings; const AParams: string): string;
var
i, ind: Integer;
reqFields, fieldList: TStrings;
begin
Result := '';
reqFields := nil;
fieldList := nil;
try
reqFields := TStringList.Create();
ParseHeaderFieldParams(AParams, reqFields);
fieldList := TStringList.Create();
GetHeaderFieldList(0, AHeader, fieldList);
for i := 0 to reqFields.Count - 1 do
begin
ind := fieldList.IndexOf(reqFields[i]);
if (ind > - 1) then
begin
Result := Result + system.Copy(AHeader[Integer(fieldList.Objects[ind])], 1, Length(fieldList[ind]));
Result := Result + ': '+ GetHeaderFieldValue(AHeader, fieldList, ind) + #13#10;
end;
end;
if (Result <> '') then
begin
Result := Result + #13#10;
end;
finally
fieldList.Free();
reqFields.Free();
end;
end;
var
msg: TclMailMessage;
src: TStrings;
s: string;
bodyIDs: TclMessageBodyIDs;
body: TclMessageBody;
begin
GetBodyIDs(AParams, bodyIDs);
msg := nil;
src := nil;
try
msg := TclMailMessage.Create(nil);
src := TStringList.Create();
src.LoadFromFile(AMessagePath);
msg.MessageSource := src;
s := '';
if (bodyIDs[0] = 0) then
begin
s := GetHeaderFieldsStr(msg.RawHeader, AParams);
end else
begin
body := GetBodyByIndex(bodyIDs, 0, msg.Bodies);
if (body <> nil) then
begin
s := GetHeaderFieldsStr(body.RawHeader, AParams);
end;
end;
AResponseItem.MessageData := AResponseItem.MessageData
+ Format('%s {%d}'#13#10, [ACommand, Length(s)]) + s;
finally
src.Free();
msg.Free();
end;
end;
procedure TclImap4FileHandler.FetchHeader(const AMessagePath, ACommand, AParams: string;
AResponseItem: TclImap4FetchResponseItem);
var
msg: TclMailMessage;
src: TStrings;
s: string;
bodyIDs: TclMessageBodyIDs;
body: TclMessageBody;
begin
GetBodyIDs(AParams, bodyIDs);
msg := nil;
src := nil;
try
msg := TclMailMessage.Create(nil);
src := TStringList.Create();
src.LoadFromFile(AMessagePath);
msg.MessageSource := src;
s := '';
if (bodyIDs[0] = 0) then
begin
s := msg.RawHeader.Text + #13#10;
end else
begin
body := GetBodyByIndex(bodyIDs, 0, msg.Bodies);
if (body <> nil) then
begin
s := body.RawHeader.Text + #13#10;
end;
end;
AResponseItem.MessageData := AResponseItem.MessageData
+ Format('%s {%d}'#13#10, [ACommand, Length(s)]) + s;
finally
src.Free();
msg.Free();
end;
end;
function TclImap4FileHandler.GetBodyByIndex(var ABodyIDs: array of Integer;
AIndex: Integer; ABodies: TclMessageBodies): TclMessageBody;
var
ind: Integer;
begin
Result := nil;
if (AIndex > High(ABodyIDs)) then Exit;
ind := ABodyIDs[AIndex] - 1;
if (ind < 0) or (ind > ABodies.Count - 1) then Exit;
if (ABodies[ind] is TclMultipartBody) then
begin
if (AIndex < High(ABodyIDs)) and (ABodyIDs[AIndex + 1] > 0) then
begin
Result := GetBodyByIndex(ABodyIDs, AIndex + 1, TclMultipartBody(ABodies[ind]).Bodies);
end else
begin
Result := ABodies[ind];
end;
end else
if (AIndex < High(ABodyIDs)) and (ABodyIDs[AIndex + 1] = 0) then
begin
Result := ABodies[ind];
end;
end;
procedure TclImap4FileHandler.FetchBodyText(const AMessagePath, ACommand, AParams: string;
AResponseItem: TclImap4FetchResponseItem);
var
msg: TclMailMessage;
src: TStrings;
s: string;
bodyIDs: TclMessageBodyIDs;
body: TclMessageBody;
begin
GetBodyIDs(AParams, bodyIDs);
msg := nil;
src := nil;
try
msg := TclMailMessage.Create(nil);
src := TStringList.Create();
src.LoadFromFile(AMessagePath);
msg.MessageSource := src;
s := '';
if (bodyIDs[0] = 0) then
begin
s := GetTextStr(src, msg.RawBodyStart, src.Count);
end else
begin
body := GetBodyByIndex(bodyIDs, 0, msg.Bodies);
if (body <> nil) then
begin
s := GetTextStr(src, body.RawBodyStart, body.EncodedLines);
end;
end;
AResponseItem.MessageData := AResponseItem.MessageData
+ Format('%s {%d}'#13#10, [ACommand, Length(s)]) + s;
finally
src.Free();
msg.Free();
end;
end;
procedure TclImap4FileHandler.FetchBody(const AMessagePath, ACommand, AParams: string;
AResponseItem: TclImap4FetchResponseItem);
var
stream: TStream;
s: string;
bodyIDs: TclMessageBodyIDs;
begin
GetBodyIDs(AParams, bodyIDs);
if (bodyIDs[0] = 0) then
begin
stream := TFileStream.Create(AMessagePath, fmOpenRead or fmShareDenyWrite);
try
SetString(s, nil, stream.Size);
stream.Read(PChar(s)^, stream.Size);
AResponseItem.MessageData := AResponseItem.MessageData
+ Format('%s {%d}'#13#10, [ACommand, Length(s)]) + s;
finally
stream.Free();
end;
end else
begin
FetchBodyText(AMessagePath, ACommand, AParams, AResponseItem);
end;
end;
function TclImap4FileHandler.DateTimeToImapTime(ADateTime: TDateTime): string;
var
Year, Month, Day, Hour, Min, Sec, MSec: Word;
MonthName: String;
begin
DecodeDate(ADateTime, Year, Month, Day);
DecodeTime(ADateTime, Hour, Min, Sec, MSec);
MonthName := cMonths[Month];
Result := Format('%d-%s-%d %d:%.2d:%.2d %s',
[Day, MonthName, Year, Hour, Min, Sec, TimeZoneBiasString]);
end;
procedure TclImap4FileHandler.FetchMessage(AConnection: TclImap4CommandConnection;
const AMessageFile: string; ARequest: TclImap4FetchRequestList;
AUseUID: Boolean; AResponseItem: TclImap4FetchResponseItem);
var
i, k: Integer;
path, s: string;
begin
AResponseItem.MessageID := GetMessageList(AConnection).IndexOf(AMessageFile) + 1;
Assert(AResponseItem.MessageID > 0);
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AConnection.CurrentMailBox.Name));
for i := 0 to ARequest.Count - 1 do
begin
if ('UID' = ARequest[i].Name) then
begin
if not AUseUID and (Length(AResponseItem.MessageData) > 0) then
begin
AResponseItem.MessageData := AResponseItem.MessageData + #32;
end;
end else
if (Length(AResponseItem.MessageData) > 0) then
begin
AResponseItem.MessageData := AResponseItem.MessageData + #32;
end;
if ('BODY' = ARequest[i].Name) or ('BODY.PEEK' = ARequest[i].Name) then
begin
s := UpperCase(ARequest[i].Params);
if (system.Pos('HEADER.FIELDS', s) > 0) then
begin
FetchHeaderFields(path + AMessageFile, 'BODY[' + s + ']', s, AResponseItem);
end else
if (system.Pos('HEADER', s) > 0) then
begin
FetchHeader(path + AMessageFile, 'BODY[' + s + ']', s, AResponseItem);
end else
if (system.Pos('MIME', s) > 0) then
begin
FetchHeader(path + AMessageFile, 'BODY[' + s + ']', s, AResponseItem);
end else
if (system.Pos('TEXT', s) > 0) then
begin
FetchBodyText(path + AMessageFile, 'BODY[' + s + ']', s, AResponseItem);
end else
begin
FetchBody(path + AMessageFile, 'BODY[' + s + ']', s, AResponseItem);
end;
if ('BODY' = ARequest[i].Name) then
begin
SetMessageFlags(AConnection, path, AMessageFile, fmRemove, [mfSeen]);
end;
end else
if ('RFC822' = ARequest[i].Name) then
begin
FetchBody(path + AMessageFile, 'RFC822', '', AResponseItem);
end else
if ('RFC822.HEADER' = ARequest[i].Name) then
begin
FetchHeader(path + AMessageFile, 'RFC822.HEADER', '', AResponseItem);
end else
if ('RFC822.SIZE' = ARequest[i].Name) then
begin
k := GetLocalFileSize(path + AMessageFile);
if (k > -1) then
begin
AResponseItem.MessageData := AResponseItem.MessageData + Format('RFC822.SIZE %d', [k]);
end;
end else
if ('UID' = ARequest[i].Name) and (not AUseUID) then
begin
AResponseItem.MessageData := AResponseItem.MessageData + 'UID ' + GetMessageUID(AConnection, AMessageFile);
end else
if ('FLAGS' = ARequest[i].Name) then
begin
s := GetMessageFlags(AConnection, path, AMessageFile);
AResponseItem.MessageData := AResponseItem.MessageData + 'FLAGS (' + s + ')';
end else
if ('ENVELOPE' = ARequest[i].Name) then
begin
AResponseItem.MessageData := AResponseItem.MessageData + 'ENVELOPE ('
+ FetchMessageEnvelope(path + AMessageFile) + ')';
end else
if ('BODYSTRUCTURE' = ARequest[i].Name) then
begin
AResponseItem.MessageData := AResponseItem.MessageData + 'BODYSTRUCTURE ('
+ FetchBodyStructure(path + AMessageFile) + ')';
end else
if ('INTERNALDATE' = ARequest[i].Name) then
begin
s := DateTimeToImapTime(GetMessageInternalDate(path + AMessageFile));
AResponseItem.MessageData := AResponseItem.MessageData + 'INTERNALDATE "' + s + '"';
end;
end;
if AUseUID and (Length(AResponseItem.MessageData) > 0) then
begin
AResponseItem.MessageData := 'UID ' + GetMessageUID(AConnection, AMessageFile) + #32 + AResponseItem.MessageData;
end;
end;
procedure TclImap4FileHandler.DoFetchMessages(Sender: TObject;
AConnection: TclImap4CommandConnection; const AMessageSet, ADataItems: string;
AUseUID: Boolean; AResponse: TclImap4FetchResponseList; var Result: TclImap4MessageResult);
var
i: Integer;
path: string;
targetList: TStrings;
request: TclImap4FetchRequestList;
begin
RefreshMailBoxInfo(AConnection);
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AConnection.CurrentMailBox.Name));
try
targetList := TStringList.Create();
request := TclImap4FetchRequestList.Create(TclImap4FetchRequestItem);
try
FillTargetList(AConnection, AMessageSet, AUseUID, targetList);
request.Parse(ADataItems);
AResponse.Clear();
for i := 0 to targetList.Count - 1 do
begin
FetchMessage(AConnection, targetList[i], request, AUseUID, AResponse.Add());
end;
finally
request.Free();
targetList.Free();
end;
Result := msOk;
except
Result := msNo;
end;
end;
procedure TclImap4FileHandler.DoStoreMessages(Sender: TObject;
AConnection: TclImap4CommandConnection; const AMessageSet: string;
AFlagsMethod: TclSetFlagsMethod; AFlags: TclMailMessageFlags; IsSilent: Boolean;
AUseUID: Boolean; AResponse: TclImap4FetchResponseList; var Result: TclImap4MessageResult);
var
i: Integer;
path, s: string;
targetList: TStrings;
item: TclImap4FetchResponseItem;
begin
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AConnection.CurrentMailBox.Name));
try
targetList := TStringList.Create();
try
FillTargetList(AConnection, AMessageSet, AUseUID, targetList);
AResponse.Clear();
for i := 0 to targetList.Count - 1 do
begin
s := SetMessageFlags(AConnection, path, targetList[i], AFlagsMethod, AFlags);
if not IsSilent then
begin
item := AResponse.Add();
item.MessageID := GetMessageList(AConnection).IndexOf(targetList[i]) + 1;
Assert(item.MessageID > 0);
item.MessageData := 'FLAGS (' + s + ')';
end;
end;
finally
targetList.Free();
end;
Result := msOk;
except
Result := msNo;
end;
end;
procedure TclImap4FileHandler.DoPurgeMessages(Sender: TObject;
AConnection: TclImap4CommandConnection; IsSilent: Boolean; AMessageIDs: TStrings;
var Result: TclImap4MessageResult);
var
i, ind: Integer;
path, uid: string;
ini: TIniFile;
list, msgList: TStrings;
flags: TclMailMessageFlags;
begin
AMessageIDs.Clear();
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(MailBoxToPath(AConnection.CurrentMailBox.Name));
if not FileExists(path + MailBoxInfoFile) then
begin
Result := msNo;
Exit;
end;
try
ini := nil;
list := nil;
try
ini := TIniFile.Create(path + MailBoxInfoFile);
list := TStringList.Create();
msgList := GetMessageList(AConnection);
ini.ReadSection(cMessagesSection, list);
for i := list.Count - 1 downto 0 do
begin
ParseMessageInfo(ini.ReadString(cMessagesSection, list[i], ''), uid, flags);
if (mfDeleted in flags) then
begin
if DeleteFile(path + list[i]) and (not IsSilent) then
begin
ind := msgList.IndexOf(list[i]);
if (ind > -1) then
begin
AMessageIDs.Add(IntToStr(ind + 1));
end;
end;
ini.DeleteKey(cMessagesSection, list[i]);
end;
end;
finally
list.Free();
ini.Free();
end;
Result := msOk;
except
Result := msNo;
end;
end;
procedure TclImap4FileHandler.DoCanAppendMessage(Sender: TObject;
AConnection: TclImap4CommandConnection; const AMailBox: string;
var Result: TclImap4MailBoxResult);
var
path: string;
begin
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(AMailBox);
if DirectoryExists(path) then
begin
Result := mrSuccess;
end else
begin
Result := mrNotFound;
end;
end;
procedure TclImap4FileHandler.DoMessageAppended(Sender: TObject;
AConnection: TclImap4CommandConnection; const AMailBox: string;
AFlags: TclMailMessageFlags; AMessage: TStrings; var Result: TclImap4MailBoxResult);
var
path, fileName: string;
begin
path := GetMailBoxPath(AConnection.UserName) + AddTrailingBackSlash(AMailBox);
try
fileName := GenMessageFileName(AConnection);
AMessage.SaveToFile(path + fileName);
if (AFlags <> []) then
begin
SetMessageFlags(AConnection, path, fileName, fmReplace, AFlags);
end;
Result := mrSuccess;
except
Result := mrAccessDenied;
end;
end;
procedure TclImap4FileHandler.SetMailBoxDir(const Value: string);
begin
FAccessor.Enter();
try
FMailBoxDir := Value;
finally
FAccessor.Leave();
end;
end;
procedure TclImap4FileHandler.SetMailBoxInfoFile(const Value: string);
begin
FAccessor.Enter();
try
FMailBoxInfoFile := Value;
finally
FAccessor.Leave();
end;
end;
procedure TclImap4FileHandler.DoCreateConnection(Sender: TObject; var AConnection: TclCommandConnection);
begin
AConnection := TclImap4FileCommandConnection.Create();
end;
function TclImap4FileHandler.GetCurrentCounter(AConnection: TclImap4CommandConnection): Integer;
var
ini: TIniFile;
begin
ini := TIniFile.Create(GetMailBoxPath(AConnection.UserName) + MailBoxInfoFile);
try
Result := ini.ReadInteger(cMailBoxSection, 'Counter', 1);
finally
ini.Free();
end;
end;
function TclImap4FileHandler.GetNextCounter(AConnection: TclImap4CommandConnection): Integer;
var
ini: TIniFile;
begin
ini := TIniFile.Create(GetMailBoxPath(AConnection.UserName) + MailBoxInfoFile);
try
Result := ini.ReadInteger(cMailBoxSection, 'Counter', 1);
ini.WriteInteger(cMailBoxSection, 'Counter', Result + 1);
finally
ini.Free();
end;
end;
function TclImap4FileHandler.FetchMessageEnvelope(const AMessagePath: string): string;
var
stream: TStream;
msg: TStrings;
begin
Result := '';
if not FileExists(AMessagePath) then Exit;
stream := nil;
msg := nil;
try
stream := TFileStream.Create(AMessagePath, fmOpenRead or fmShareDenyWrite);
msg := TStringList.Create();
GetTopLines(stream, 0, msg);
Result := GetMessageEnvelope(msg);
finally
msg.Free();
stream.Free();
end;
end;
const
EncodingMap: array[TclEncodeMethod] of string = ('"7bit"', '"quoted-printable"', '"base64"', 'NIL', '"8bit"');
procedure TclImap4FileHandler.ExtractContentTypeParts(const AContentType: string; var AType, ASubType: string);
var
ind: Integer;
begin
AType := 'NIL';
ASubType := 'NIL';
if (AContentType = '') then Exit;
ind := system.Pos('/', AContentType);
if (ind > 0) then
begin
AType := '"' + system.Copy(AContentType, 1, ind - 1) + '"';
ASubType := '"' + system.Copy(AContentType, ind + 1, 1000) + '"';
end else
begin
AType := '"' + AContentType + '"';
end;
end;
function TclImap4FileHandler.GetMimeBodySize(ABody: TclMessageBody): string;
var
cntType, subType: string;
begin
ExtractContentTypeParts(ABody.ContentType, cntType, subType);
if SameText(cntType, '"text"') then
begin
Result := Format('%d %d ', [ABody.EncodedSize, ABody.EncodedLines]);
end else
begin
Result := Format('%d ', [ABody.EncodedSize]);
end;
end;
function TclImap4FileHandler.GetMimeBodyStructure(ABodies: TclMessageBodies): string;
var
i: Integer;
body: TclMessageBody;
s, cntType, subType: string;
begin
Result := '';
for i := 0 to ABodies.Count - 1 do
begin
body := ABodies[i];
if (ABodies.Count > 1) then
begin
Result := Result + '(';
end;
if (body is TclTextBody) then
begin
ExtractContentTypeParts(body.ContentType, cntType, subType);
Result := Result + Format('%s %s ', [cntType, subType]);
if (TclTextBody(body).CharSet <> '') then
begin
Result := Result + Format('("charset" "%s") ', [TclTextBody(body).CharSet]);
end;
Result := Result + 'NIL NIL ' + EncodingMap[body.Encoding] + ' ';
Result := Result + GetMimeBodySize(body);
Result := Result + 'NIL NIL NIL';
end else
if (body is TclAttachmentBody) then
begin
ExtractContentTypeParts(body.ContentType, cntType, subType);
Result := Result + Format('%s %s ', [cntType, subType]);
Result := Result + Format('("name" "%s") ', [TclAttachmentBody(body).FileName]);
s := TclAttachmentBody(body).ContentID;
if (s <> '') then
begin
if (s[1] <> '<') then
begin
s := '<' + s + '>';
end;
Result := Result + '"' + s + '" NIL ';
Result := Result + EncodingMap[body.Encoding] + ' ';
Result := Result + GetMimeBodySize(body);
Result := Result + 'NIL NIL NIL';
end else
begin
Result := Result + 'NIL NIL '+ EncodingMap[body.Encoding] + ' ';
Result := Result + GetMimeBodySize(body);
Result := Result + Format('NIL ("attachment" ("filename" "%s")) NIL', [TclAttachmentBody(body).FileName]);
end;
end else
if (body is TclMultipartBody) then
begin
Result := Result + GetMimeBodyStructure(TclMultipartBody(body).Bodies);
ExtractContentTypeParts(body.ContentType, cntType, subType);
cntType := '';
if (TclMultipartBody(body).ContentSubType <> '') then
begin
cntType := Format('"type" "%s" ', [TclMultipartBody(body).ContentSubType]);
end;
Result := Trim(Result) + Format(' %s (%s"boundary" "%s") NIL NIL',
[subType, cntType, TclMultipartBody(body).Boundary]);
end;
if (ABodies.Count > 1) then
begin
Result := Result + ')';
end;
end;
end;
procedure TclImap4FileHandler.GetUueBodySize(AMessage: TStrings; var ASize, ALines: Integer);
var
i: Integer;
isBody: Boolean;
begin
ASize := 0;
ALines := 0;
isBody := False;
for i := 0 to AMessage.Count - 1 do
begin
if isBody then
begin
ASize := ASize + Length(AMessage[i]) + Length(#13#10);
end else
if (AMessage[i] = '') then
begin
isBody := True;
ALines := i;
end;
end;
if (ALines > 0) then
begin
ALines := AMessage.Count - ALines - 1;
end;
end;
function TclImap4FileHandler.GetBodyStructure(AMessage: TStrings): string;
var
msg: TclMailMessage;
cntType, subType: string;
size, lines: Integer;
begin
msg := TclMailMessage.Create(nil);
try
msg.MessageSource := AMessage;
if (msg.MessageFormat = mfUUencode) then
begin
GetUueBodySize(AMessage, size, lines);
Result := Format('"TEXT" "PLAIN" NIL NIL NIL "7BIT" %d %d NIL NIL NIL', [size, lines]);
end else
begin
Result := GetMimeBodyStructure(msg.Bodies);
if (msg.Bodies.Count > 1) and (msg.Boundary <> '') then
begin
ExtractContentTypeParts(msg.ContentType, cntType, subType);
cntType := '';
if (msg.ContentSubType <> '') then
begin
cntType := Format('"type" "%s" ', [msg.ContentSubType]);
end;
Result := Trim(Result) + Format(' %s ("boundary" "%s") NIL NIL', [subType, msg.Boundary]);
end;
end;
finally
msg.Free();
end;
end;
function TclImap4FileHandler.FetchBodyStructure(const AMessagePath: string): string;
var
msg: TStrings;
begin
Result := '';
if not FileExists(AMessagePath) then Exit;
msg := TStringList.Create();
try
msg.LoadFromFile(AMessagePath);
Result := GetBodyStructure(msg);
finally
msg.Free();
end;
end;
{ TclImap4FileCommandConnection }
constructor TclImap4FileCommandConnection.Create;
begin
inherited Create();
FMessages := TStringList.Create();
end;
destructor TclImap4FileCommandConnection.Destroy;
begin
FMessages.Free();
inherited Destroy();
end;
end.
|
unit uSubModelWarranty;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentSub, siComp, siLangRT, DB, ADODB, StdCtrls, DBCtrls,
dbcgrids, ExtCtrls;
type
TSubModelWarranty = class(TParentSub)
quModelWarranty: TADODataSet;
dsModelWarranty: TDataSource;
quModelWarrantyIDModel: TIntegerField;
quModelWarrantyModel: TStringField;
quModelWarrantyDescription: TStringField;
quModelWarrantySellingPrice: TBCDField;
quModelWarrantyCostPrice: TBCDField;
quModelWarrantyModelDescr: TStringField;
Label1: TLabel;
cbxWarranty: TComboBox;
quModelWarrantyReplacementCost: TBCDField;
quModelWarrantyStoreSellingPrice: TBCDField;
procedure quModelWarrantyAfterOpen(DataSet: TDataSet);
procedure quModelWarrantyCalcFields(DataSet: TDataSet);
procedure cbxWarrantyChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
fIDModel,
fIDModelSelected : Integer;
fAmount : Currency;
fSellingPrice : Currency;
procedure FillWarranty;
protected
procedure AfterSetParam; override;
public
{ Public declarations }
procedure DataSetRefresh;
procedure DataSetOpen; override;
procedure DataSetClose; override;
function GiveInfo(InfoString: String): String; override;
end;
implementation
uses uDM, uParamFunctions, uMsgBox, uMsgConstant, uNumericFunctions, uSystemConst;
{$R *.dfm}
{ TSubModelWarranty }
procedure TSubModelWarranty.AfterSetParam;
begin
inherited;
fIDModel := StrToIntDef(ParseParam(FParam, 'IDModel'),0);
fAmount := MyStrToMoney(ParseParam(FParam, 'Amount'));
fIDModelSelected := -1;
if (fIDModel = 0) then
begin
NotifyChanges('Empty='+BoolToStr(False)+';');
Exit;
end;
DataSetRefresh;
end;
procedure TSubModelWarranty.DataSetClose;
begin
inherited;
with quModelWarranty do
if Active then
Close;
end;
procedure TSubModelWarranty.DataSetOpen;
begin
inherited;
with quModelWarranty do
if not Active then
begin
Parameters.ParamByName('IDModel').Value := fIDModel;
Parameters.ParamByName('Amount').Value := fAmount;
Parameters.ParamByName('IDStore').Value := DM.fStore.ID;
Open;
end;
end;
procedure TSubModelWarranty.DataSetRefresh;
begin
DataSetClose;
DataSetOpen;
end;
procedure TSubModelWarranty.FillWarranty;
begin
cbxWarranty.Clear;
cbxWarranty.Items.AddObject('', Pointer(-1));
with quModelWarranty do
if Active then
begin
First;
While not EOF do
begin
cbxWarranty.Items.AddObject(quModelWarrantyModelDescr.AsString, Pointer(quModelWarrantyIDModel.AsInteger));
Next;
end;
end;
cbxWarranty.ItemIndex := 1;
cbxWarrantyChange(Self);
end;
procedure TSubModelWarranty.quModelWarrantyAfterOpen(DataSet: TDataSet);
var
bHasID : Boolean;
begin
inherited;
bHasID := DataSet.RecordCount>0;
NotifyChanges('Empty='+BoolToStr(bHasID)+';');
if bHasID then
FillWarranty;
end;
procedure TSubModelWarranty.quModelWarrantyCalcFields(DataSet: TDataSet);
begin
inherited;
if quModelWarrantyStoreSellingPrice.AsCurrency <> 0 then
fSellingPrice := quModelWarrantyStoreSellingPrice.AsCurrency
else
fSellingPrice := quModelWarrantySellingPrice.AsCurrency;
quModelWarrantyModelDescr.AsString := '[' + quModelWarrantyModel.AsString + ' - ' +
quModelWarrantyDescription.AsString + '] - ' +
FormatFloat('#,##0.00', fSellingPrice);
end;
procedure TSubModelWarranty.cbxWarrantyChange(Sender: TObject);
var
sResult : String;
begin
inherited;
fIDModelSelected := -1;
if cbxWarranty.ItemIndex > 0 then
fIDModelSelected := LongInt(cbxWarranty.Items.Objects[cbxWarranty.ItemIndex]);
sResult := 'Empty='+BoolToStr(True)+';HasWarranty='+BoolToStr(fIDModelSelected<>-1)+';';
NotifyChanges(sResult);
end;
function TSubModelWarranty.GiveInfo(InfoString: String): String;
begin
Result := '';
if fIDModelSelected = -1 then
Exit;
if quModelWarrantyStoreSellingPrice.AsCurrency <> 0 then
fSellingPrice := quModelWarrantyStoreSellingPrice.AsCurrency
else
fSellingPrice := quModelWarrantySellingPrice.AsCurrency;
if quModelWarranty.Locate('IDModel', fIDModelSelected, []) then
Result := 'IDModel=' +quModelWarrantyIDModel.AsString + ';' +
'SalePrice=' +quModelWarrantySellingPrice.AsString + ';';
if DM.fSystem.SrvParam[PARAM_USE_ESTIMATED_COST] then
Result := Result + 'CostPrice=' +quModelWarrantyReplacementCost.AsString+';'
else
Result := Result + 'CostPrice=' +quModelWarrantyCostPrice.AsString + ';';
end;
procedure TSubModelWarranty.FormDestroy(Sender: TObject);
begin
DataSetClose;
inherited;
end;
initialization
RegisterClass(TSubModelWarranty);
end.
|
unit u_tokens;
{$mode objfpc}{$H+}
interface
type
TMashTokenType = (
ttToken, ttDigit, ttString, ttWord, ttEndOfLine, ttNull
);
TMashTokenID = (
tkProc, tkFunc,
tkOBr, tkCBr, tkORBr, tkCRBr, tkSm, tkBg,
tkEq, tkBEq, tkSEq, tkInc, tkDec,
tkAdd, tkSub, tkMul, tkDiv, tkIDiv, tkMod,
tkAnd, tkOr, tkXor, tkSHL, tkSHR, tkNEq,
tkAssign, tkMov, tkMovBP, tkGVBP, tkGP,
tkCMSep, tkBegin, tkComma, tkDot, tkRange, tkIs,
tkAddSym, tkSubSym, tkMulSym, tkDivSym, tkIDivSym, tkModSym,
tkAndSym, tkOrSym, tkXorSym, tkNotSym, tkSHLSym, tkSHRSym,
tkIf, tkElse, tkSwitch, tkCase, tkDefault,
tkFor, tkIn, tkBack, tkBreak, tkContinue,
tkWhile, tkWhilst,
tkClass, tkVar, tkThis, tkByPtr, tkNew, tkInit,
tkPublic, tkProtected, tkPrivate,
tkTry, tkCatch, tkRaise,
tkLaunch, tkAsync, tkWait,
tkConst, tkResource, tkEnum,
tkImport, tkAPI, tkUses,
tkInline,
tkEnd, tkReturn,
tkNull, tkSpecial
);
const
MashTokens: array[tkProc..tkReturn] of string = (
'proc', 'func',
'(', ')', '[', ']', '<', '>',
'==', '>=', '<=', '++', '--',
'+=', '-=', '*=', '/=', '\=', '%=',
'&=', '|=', '^=', '<<=', '>>=', '<>',
'?=', '=', '@=', '?', '@',
'::', ':', ',', '.', '..', 'is',
'+', '-', '*', '/', '\', '%', '&', '|', '^', '~', '<<', '>>',
'if', 'else',
'switch', 'case', 'default',
'for', 'in', 'back', 'break', 'continue',
'while', 'whilst',
'class', 'var', '$', '->', 'new', 'init', 'public', 'protected', 'private',
'try', 'catch', 'raise',
'launch', 'async', 'wait',
'const', 'resource', 'enum',
'import', 'api', 'uses',
'inline',
'end', 'return'
);
MashExprTokens: set of TMashTokenID = [
tkAddSym, tkSubSym, tkMulSym, tkDivSym, tkIDivSym, tkModSym,
tkAndSym, tkOrSym, tkXorSym, tkNotSym, tkSHLSym, tkSHRSym,
tkAssign, tkMov, tkMovBP,
tkGVBP, tkGP, tkEq, tkBEq, tkSEq, tkInc, tkDec, tkAdd, tkSub,
tkMul, tkDiv, tkIDiv, tkMod, tkAnd, tkOr, tkXor, tkSHL, tkSHR, tkNEq,
tkOBr, tkCBr, tkORBr, tkCRBr, tkSm, tkBg,
tkByPtr, tkThis, tkSpecial, tkIn, tkRange, tkIs, tkComma, tkDot, tkNew
];
MashParamsTokens: set of TMashTokenID = [tkORBr, tkCRBr];
MashOperatorsTokens: set of TMashTokenID = [
tkAddSym, tkSubSym, tkMulSym, tkDivSym, tkIDivSym, tkModSym,
tkAndSym, tkOrSym, tkXorSym, tkSHLSym, tkSHRSym,
tkGVBP, tkAssign, tkMovBP, tkDot,
tkSm, tkBg, tkEq, tkBEq, tkSEq,
tkAdd, tkSub, tkMul, tkDiv, tkIDiv, tkMod,
tkAnd, tkOr, tkXor, tkSHL, tkSHR, tkNEq,
tkIn, tkRange, tkIs
];
MashOperationToken: set of TMashTokenID = [
tkInc, tkDec, tkGVBP, tkGP,
tkNotSym, tkSubSym, tkNew, tkDot
];
MashOperationsPriority: array[0..6] of set of TMashTokenID = (
[tkAssign, tkMov, tkMovBP, tkAdd, tkSub, tkMul,
tkDiv, tkIDiv, tkMod, tkAnd, tkOr, tkXor, tkSHL, tkSHR],
[tkSm, tkBg, tkEq, tkBEq, tkSEq, tkNEq],
[tkAndSym, tkOrSym, tkXorSym, tkIn, tkSHLSym, tkSHRSym],
[tkRange, tkIs],
[tkAddSym, tkSubSym],
[tkMulSym, tkDivSym, tkIDivSym, tkModSym],
[tkInc, tkDec, tkGVBP, tkGP,
tkNotSym, tkSubSym, tkNew, tkDot]
);
MashOperationLeft: set of TMashTokenID = [
tkGVBP, tkGP, tkNotSym, tkSubSym, tkNew
];
MashOperationRight: set of TMashTokenID = [tkInc, tkDec];
type
TMashToken = class
public
value: string;
info: TMashTokenType;
short: TMashTokenID;
line: Cardinal;
filep: PString;
constructor Create(_value: string;
_info: TMashTokenType;
_line: Cardinal;
var _filep: string);
end;
implementation
constructor TMashToken.Create(_value: string;
_info: TMashTokenType;
_line: Cardinal;
var _filep: string);
var
i, l: byte;
begin
self.value := _value;
self.info := _info;
self.line := _line;
self.filep := @_filep;
self.short := tkNull;
if _value = 'this' then
self.short := tkSpecial
else
if _info = ttToken then
begin
i := 0;
l := Length(MashTokens);
while i < l do
begin
if MashTokens[TMashTokenID(i)] = _value then
begin
self.short := TMashTokenID(i);
break;
end;
inc(i);
end;
end;
end;
end.
|
unit MediaPlayerWin;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
MediaPlayer_TLB, MessageWin, Math;
type
TMediaPlayerForm = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
protected
FMediaPlayer : TWindowsMediaPlayer;
procedure MediaPlayerReadyStateChange(Sender: TObject; ReadyState: ReadyStateConstants);
procedure SetFormToImageSize;
public
procedure Play(const ASRC : String); overload;
procedure Play(const ASRC : String; AStart : LongInt); overload;
procedure Play(const ASRC : String; AStart, AEnd : LongInt); overload;
property Player : TWindowsMediaPlayer read FMediaPlayer;
end;
implementation
{$R *.DFM}
const
CRLF = #13#10;
resourcestring
rsMediaPlayerNotFound = 'To use the audio/video media features of The Alim you need to have the Microsoft Windows Media Player installed on your computer.'+
'You do not appear to have the Windows Media Player installed.'+CRLF+CRLF +
'1. Please exit The Alim.'+CRLF+
'2. From Windows, browse your Alim CD.'+CRLF+
'3. Open the folder called REDIST on the Alim CD.'+CRLF+
'4. Run the program called SetupMediaPlayer.'+CRLF+
'5. Follow any prompts or instructions in the Setup program.'+CRLF+CRLF+
'Once you have installed the Microsoft Windows Media Player, restart your computer and then run The Alim again. If you have any trouble '+
'or questions, please contact technical support via e-mail (support@islsoftware.com) or phone (301-622-3915).';
procedure TMediaPlayerForm.FormCreate(Sender: TObject);
begin
// create this manually because delphi was having a problem creating it automatically
// (kept erroring out)
try
FMediaPlayer := TWindowsMediaPlayer.Create(Self);
with FMediaPlayer do begin
Parent := Self;
//OnPlayStateChange := MediaPlayerPlayStateChange;
OnReadyStateChange := MediaPlayerReadyStateChange;
Visible := True;
Align := alClient;
//ShowCaptioning := True;
//ShowStatusBar := True
end;
//sldVolume.Value := FMediaPlayer.Volume;
except
FMediaPlayer := Nil;
ShowMessage(rsMediaPlayerNotFound);
end;
end;
procedure TMediaPlayerForm.Play(const ASRC : String);
begin
if FMediaPlayer = Nil then
Exit;
FMediaPlayer.FileName := ASRC;
try
FMediaPlayer.Play;
except
on E : Exception do
MessageWindow.Add('MP', '%s (%s)', [E.Message, ASRC]);
end;
end;
procedure TMediaPlayerForm.Play(const ASRC : String; AStart : LongInt);
begin
if FMediaPlayer = Nil then
Exit;
FMediaPlayer.Open(ASRC);
FMediaPlayer.CurrentPosition := AStart;
FMediaPlayer.SelectionStart := AStart;
FMediaPlayer.Play;
end;
procedure TMediaPlayerForm.Play(const ASRC : String; AStart, AEnd : LongInt);
begin
if FMediaPlayer = Nil then
Exit;
FMediaPlayer.Open(ASRC);
FMediaPlayer.CurrentPosition := AStart;
FMediaPlayer.SelectionStart := AStart;
FMediaPlayer.SelectionEnd := AEnd;
FMediaPlayer.Play;
end;
procedure TMediaPlayerForm.SetFormToImageSize;
const
ControlPaneHeight = 75;
ControlPaneWidth = 300;
begin
if FMediaPlayer = Nil then
Exit;
if FMediaPlayer.ImageSourceWidth > 0 then begin
Width := Max(FMediaPlayer.ImageSourceWidth, ControlPaneWidth);
Height := FMediaPlayer.ImageSourceHeight+ControlPaneHeight;
end;
end;
procedure TMediaPlayerForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if FMediaPlayer <> Nil then
FMediaPlayer.Stop;
end;
procedure TMediaPlayerForm.MediaPlayerReadyStateChange(Sender: TObject; ReadyState: ReadyStateConstants);
begin
if ReadyState = mpReadyStateComplete then
SetFormToImageSize;
end;
end.
|
unit Dictionaries;
interface
uses Classes, Sysutils, Dialogs;
const
CHAR_LOW = 0;
CHAR_MAX = 255;
type
TWord = record
key: Integer;
hash: Integer;
end;
PWord = ^TWord;
TWordDictionary = class
private
FCount: Integer;
FList: array[CHAR_LOW..CHAR_MAX] of TStringList;
function hashStr(const s: String): Integer;
public
constructor Create;
destructor Destroy; override;
procedure Add(word: String; Key: Integer);
procedure Delete(word: String);
procedure Clear;
function Find(word: String): Integer;
function UpdateKeyOrCreate(word: String; Value: Integer): Boolean;
function GetStringList(var ss: TStringList): Boolean;
property Count: Integer read FCount;
end;
TSimpleAliasList = class
private
FWords: TStringList;
FAliases: TStringList;
public
constructor Create;
destructor Destroy; override;
function Add(const word, alias: String): Integer;
function Get(Index: Integer; out word, alias: String): Boolean;
function FindAlias(const word: String): String;
function FindWord(const alias: String): String;
procedure Clear;
procedure Delete(Index: Integer);
function Count: Integer;
procedure LoadFromStrings(ss: TStrings; const delimiter: String);
procedure LoadFromFile(const filename, delimiter: String);
end;
implementation
{ TWordDictionary }
procedure TWordDictionary.Add(word: String; Key: Integer);
var
first: Integer;
pW: PWord;
begin
word := AnsiLowerCase(word);
first := Ord(word[1]);
if NOT (Assigned(FList[first])) then
begin
FList[first] := TStringList.Create;
//FList[first].Sorted := True;
//FList[first].CaseSensitive := True;
end;
New(pW);
pW^.key := Key;
//compute string hash
pW^.hash := hashStr(word);
FList[first].AddObject(word, TObject(pW));
Inc(FCount);
end;
procedure TWordDictionary.Clear;
var
i, j: Integer;
pW: PWord;
begin
FCount := 0;
//clear and dispose PWord objects from the list
for i := CHAR_LOW to CHAR_MAX do
if Assigned(FList[i]) then
begin
for j := 0 to FList[i].Count - 1 do
begin
pW := PWord(FList[i].Objects[j]);
Dispose(pW);
end;
FList[i].Free;
FList[i] := nil;
end;
end;
constructor TWordDictionary.Create;
var
i: Integer;
begin
FCount := 0;
//initialize array with nils
for i := CHAR_LOW to CHAR_MAX do
FList[i] := nil;
end;
procedure TWordDictionary.Delete(word: String);
var
first: Integer;
i, hash: Integer;
pW: PWord;
begin
word := AnsiLowerCase(word);
first := Ord(word[1]);
if NOT (Assigned(FList[first])) then
Exit;
hash := hashStr(word);
//find string by hash and direct compare it
//then dispose and delete
for i := 0 to FList[first].Count - 1 do
begin
pW := PWord(FList[first].Objects[i]);
if (pW^.hash = hash) AND (FList[first][i] = word) then
begin
Dispose(pW);
FList[first].Delete(i);
Dec(FCount);
Exit;
end;
end;
end;
destructor TWordDictionary.Destroy;
begin
Clear;
inherited;
end;
function TWordDictionary.Find(word: String): Integer;
var
first: Integer;
i: Integer;
pW: PWord;
hash: Integer;
begin
Result := -1;
if '' = word then
Exit;
//find word by hash and direct
//return key as result
word := AnsiLowerCase(word);
first := Ord(word[1]);
if NOT (Assigned(FList[first])) then
Exit;
hash := hashStr(word);
for i := 0 to FList[first].Count - 1 do
begin
pW := PWord(FList[first].Objects[i]);
if (pW^.hash = hash) AND (FList[first][i] = word) then
begin
Result := pW^.key;
Exit;
end;
end;
end;
function TWordDictionary.UpdateKeyOrCreate(word: String;
Value: Integer): Boolean;
var
first: Integer;
i: Integer;
pW: PWord;
hash: Integer;
begin
Result := False;
if '' = word then
Exit;
//find word by hash and direct
word := AnsiLowerCase(word);
first := Ord(word[1]);
if NOT (Assigned(FList[first])) then
begin
//create new one
Self.Add(word, Value);
Result := True;
Exit;
end;
hash := hashStr(word);
for i := 0 to FList[first].Count - 1 do
begin
pW := PWord(FList[first].Objects[i]);
if (pW^.hash = hash) AND (FList[first][i] = word) then
begin
//key found
//update it
pW^.key := pW^.key + Value;
Result := True;
Exit;
end;
end;
//create new one
Self.Add(word, Value);
Result := True;
end;
function TWordDictionary.GetStringList(var ss: TStringList): Boolean;
var
i, j: Integer;
pW: PWord;
begin
Result := False;
if (ss = nil) then
Exit;
//clear and dispose PWord objects from the list
for i := CHAR_LOW to CHAR_MAX do
if Assigned(FList[i]) then
begin
for j := 0 to FList[i].Count - 1 do
begin
pW := PWord(FList[i].Objects[j]);
ss.AddObject(FList[i][j], Pointer(pW^.key));
end;
end;
end;
function TWordDictionary.hashStr(const s: String): Integer;
var
i : Integer;
begin
//compute hash of given string
Result := Length(s);
for i := 1 to Length(s) do
Result := ((Result shr 5) xor (Result shl 27)) xor Ord(s[i]);
end;
{ TSimpleAlias }
function TSimpleAliasList.Add(const word, alias: String): Integer;
begin
Result := FWords.Add(word);
FAliases.Add(alias);
end;
procedure TSimpleAliasList.Clear;
begin
FWords.Clear;
FAliases.Clear;
end;
function TSimpleAliasList.Count: Integer;
begin
Result := FWords.Count;
end;
constructor TSimpleAliasList.Create;
begin
FWords := TStringList.Create;
FAliases := TStringList.Create;
end;
procedure TSimpleAliasList.Delete(Index: Integer);
begin
FWords.Delete(Index);
FAliases.Delete(Index);
end;
destructor TSimpleAliasList.Destroy;
begin
FWords.Free;
FAliases.Free;
inherited;
end;
function TSimpleAliasList.FindAlias(const word: String): String;
var
i: Integer;
begin
i := FWords.IndexOf(word);
if i >= 0 then
Result := FAliases[i]
else
Result := '';
end;
function TSimpleAliasList.FindWord(const alias: String): String;
var
i: Integer;
begin
i := FAliases.IndexOf(alias);
if i >= 0 then
Result := FWords[i]
else
Result := '';
end;
function TSimpleAliasList.Get(Index: Integer; out word,
alias: String): Boolean;
begin
if Index >= FWords.Count then
begin
Result := False;
Exit;
end;
word := FWords[Index];
alias := FAliases[Index];
Result := True;
end;
procedure TSimpleAliasList.LoadFromFile(const filename, delimiter: String);
var
ss: TStringList;
begin
ss := TStringList.Create;
try
ss.LoadFromFile(filename);
LoadFromStrings(ss, delimiter);
finally
ss.Free;
end;
end;
procedure TSimpleAliasList.LoadFromStrings(ss: TStrings;
const delimiter: String);
var
i, j: Integer;
alias, word: String;
begin
for i := 0 to ss.Count - 1 do
begin
j := Pos(delimiter, ss[i]);
if j > 0 then
begin
word := Copy(ss[i], 1, j - 1);
alias := Copy(ss[i], j + 1, Length(ss[i]));
FWords.Add(word);
FAliases.Add(alias);
end;
end;
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.Packaging.Archive;
interface
uses
System.Zip,
System.Classes,
Spring.Container,
Spring.Container.Common,
VSoft.SemanticVersion;
type
//wrapper for archive zip file (or extracted folder).
IPackageArchive = interface
['{A5CE5203-6405-49D9-9F86-AB6D10580D1C}']
function GetArchiveName : string;
function GetArchivePath : string;
function Open(const fileName : string) : boolean;
procedure Close;
function Exists : boolean;
function IsArchive : boolean;
function GetLastErrorString : string;
property ArchiveName : string read GetArchiveName;
property ArchivePath : string read GetArchivePath;
property LastErrorString : string read GetLastErrorString;
end;
// IPackageArchiveReader = interface(IPackageArchive)
// ['{28705A4E-7B7D-4C56-A48F-77D706D0AD26}']
// //Read the metaDataFile into a stream;
// function ReadMetaDataFile(const stream : TStream) : boolean;
// function ReadFileNames : TArray<string>;
// function ExtractFileTo(const fileName : string; const destFileName : string) : boolean;
// function ExtractTo(const path : string) : boolean;
// end;
IPackageArchiveWriter = interface(IPackageArchive)
['{B1BA4ED1-E456-42DE-AA17-AA53480EE645}']
procedure SetBasePath(const path : string);
function WriteMetaDataFile(const stream : TStream) : Boolean;
function AddIcon(const filePath : string) : boolean;
function AddFile(const filePath : string) : Boolean; overload;
function AddFile(const fileName : string; const archiveFileName : string) : boolean; overload;
function AddFiles(const files : System.TArray < System.string > ) : Boolean;
end;
implementation
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Ellipsoid collision functions (mainly used by DCE).
}
unit VXS.EllipseCollision;
interface
{$I VXScene.inc}
uses
VXS.VectorGeometry,
VXS.Octree,
VXS.VectorLists,
VXS.VectorTypes;
type
TECPlane = class
public
Equation: array [0 .. 3] of Single;
Origin: TAffineVector;
Normal: TAffineVector;
procedure MakePlane(const nOrigin, nNormal: TAffineVector); overload;
procedure MakePlane(const p1, p2, p3: TAffineVector); overload;
function isFrontFacingTo(const Direction: TAffineVector): Boolean;
function signedDistanceTo(const Point: TAffineVector): Single;
end;
// Object collision properties
TECObjectInfo = record
AbsoluteMatrix: TMatrix;
Solid: Boolean;
IsDynamic: Boolean;
ObjectID: Integer;
end;
TECTriangle = record
p1, p2, p3: TAffineVector;
end;
TECTriMesh = record
Triangles: Array of TECTriangle;
ObjectInfo: TECObjectInfo;
end;
TECTriMeshList = Array of TECTriMesh;
TECFreeForm = record
OctreeNodes: array of POctreeNode;
triangleFiler: ^TAffineVectorList;
InvertedNormals: Boolean;
ObjectInfo: TECObjectInfo;
end;
TECFreeFormList = Array of TECFreeForm;
TECColliderShape = (csEllipsoid, csPoint);
TECCollider = record
Position: TAffineVector;
Radius: TAffineVector;
Shape: TECColliderShape;
ObjectInfo: TECObjectInfo;
end;
TECColliderList = Array of TECCollider;
TECContact = record
// Generated by the collision procedure
Position: TAffineVector;
SurfaceNormal: TAffineVector;
Distance: Single;
// Collider data
ObjectInfo: TECObjectInfo;
end;
TECContactList = Array of TECContact;
TECCollisionPacket = record
// Information about the move being requested: (in eSpace)
Velocity: TAffineVector;
NormalizedVelocity: TAffineVector;
BasePoint: TAffineVector;
// Hit information
FoundCollision: Boolean;
NearestDistance: Single;
NearestObject: Integer;
IntersectionPoint: TAffineVector;
IntersectionNormal: TAffineVector;
end;
TECMovePack = record
// List of closest triangles
TriMeshes: TECTriMeshList;
// List of freeform octree nodes
Freeforms: TECFreeFormList;
// List of other colliders (f.i. ellipsoids)
Colliders: TECColliderList;
// Movement params
Position: TAffineVector;
Velocity: TAffineVector;
Gravity: TAffineVector;
Radius: TAffineVector;
ObjectInfo: TECObjectInfo;
CollisionRange: Single; // Stores the range where objects may collide
// Internal
UnitScale: Double;
MaxRecursionDepth: Byte;
CP: TECCollisionPacket;
collisionRecursionDepth: Byte;
// Result
ResultPos: TAffineVector;
NearestObject: Integer;
VelocityCollided: Boolean;
GravityCollided: Boolean;
GroundNormal: TAffineVector;
Contacts: TECContactList end;
function VectorDivide(const v, divider: TAffineVector): TAffineVector;
procedure CollideAndSlide(var MP: TECMovePack);
procedure CollideWithWorld(var MP: TECMovePack; pos, vel: TAffineVector;
var HasCollided: Boolean);
const
cECCloseDistance: Single = 0.005;
{ .$DEFINE DEBUG }
var
Debug_tri: Array of TECTriangle;
//=================================================================
implementation
//=================================================================
{$IFDEF DEBUG}
procedure AddDebugTri(p1, p2, p3: TAffineVector);
begin
SetLength(Debug_tri, Length(Debug_tri) + 1);
Debug_tri[High(Debug_tri)].p1 := p1;
Debug_tri[High(Debug_tri)].p2 := p2;
Debug_tri[High(Debug_tri)].p3 := p3;
end;
{$ENDIF}
{ Utility functions }
function CheckPointInTriangle(Point, pa, pb, pc: TAffineVector): Boolean;
var
e10, e20, vp: TAffineVector;
a, b, c, d, e, ac_bb, x, y, z: Single;
begin
e10 := VectorSubtract(pb, pa);
e20 := VectorSubtract(pc, pa);
a := VectorDotProduct(e10, e10);
b := VectorDotProduct(e10, e20);
c := VectorDotProduct(e20, e20);
ac_bb := (a * c) - (b * b);
vp := AffineVectorMake(Point.x - pa.x, Point.y - pa.y, Point.z - pa.z);
d := VectorDotProduct(vp, e10);
e := VectorDotProduct(vp, e20);
x := (d * c) - (e * b);
y := (e * a) - (d * b);
z := x + y - ac_bb;
result := ((z < 0) and not((x < 0) or (y < 0)));
end;
function GetLowestRoot(a, b, c, maxR: Single; var Root: Single): Boolean;
var
determinant: Single;
sqrtD, r1, r2, temp: Single;
begin
// No (valid) solutions
result := false;
// Check if a solution exists
determinant := b * b - 4 * a * c;
// If determinant is negative it means no solutions.
if (determinant < 0) then
Exit;
// calculate the two roots: (if determinant == 0 then
// x1==x2 but letís disregard that slight optimization)
sqrtD := sqrt(determinant);
if a = 0 then
a := -0.01; // is this really needed?
r1 := (-b - sqrtD) / (2 * a);
r2 := (-b + sqrtD) / (2 * a);
// Sort so x1 <= x2
if (r1 > r2) then
begin
temp := r2;
r2 := r1;
r1 := temp;
end;
// Get lowest root:
if (r1 > 0) and (r1 < maxR) then
begin
Root := r1;
result := true;
Exit;
end;
// It is possible that we want x2 - this can happen
// if x1 < 0
if (r2 > 0) and (r2 < maxR) then
begin
Root := r2;
result := true;
Exit;
end;
end;
function VectorDivide(const v, divider: TAffineVector): TAffineVector;
begin
result.x := v.x / divider.x;
result.y := v.y / divider.y;
result.z := v.z / divider.z;
end;
procedure VectorSetLength(var v: TAffineVector; Len: Single);
var
l, l2: Single;
begin
l2 := v.x * v.x + v.y * v.y + v.z * v.z;
l := sqrt(l2);
if l <> 0 then
begin
Len := Len / l;
v.x := v.x * Len;
v.y := v.y * Len;
v.z := v.z * Len;
end;
end;
//-----------------------------------------
{ TECPlane }
//-----------------------------------------
procedure TECPlane.MakePlane(const nOrigin, nNormal: TAffineVector);
begin
Normal := nNormal;
Origin := nOrigin;
Equation[0] := Normal.x;
Equation[1] := Normal.y;
Equation[2] := Normal.z;
Equation[3] := -(Normal.x * Origin.x + Normal.y * Origin.y + Normal.z *
Origin.z);
end;
procedure TECPlane.MakePlane(const p1, p2, p3: TAffineVector);
begin
Normal := CalcPlaneNormal(p1, p2, p3);
MakePlane(p1, Normal);
end;
function TECPlane.isFrontFacingTo(const Direction: TAffineVector): Boolean;
var
Dot: Single;
begin
Dot := VectorDotProduct(Normal, Direction);
result := (Dot <= 0);
end;
function TECPlane.signedDistanceTo(const Point: TAffineVector): Single;
begin
result := VectorDotProduct(Point, Normal) + Equation[3];
end;
{ Collision detection functions }
// Assumes: p1,p2 and p3 are given in ellisoid space:
// Returns true if collided
function CheckTriangle(var MP: TECMovePack; const p1, p2, p3: TAffineVector;
ColliderObjectInfo: TECObjectInfo; var ContactInfo: TECContact): Boolean;
var
trianglePlane: TECPlane;
t0, t1: Double;
embeddedInPlane: Boolean;
signedDistToTrianglePlane: Double;
normalDotVelocity: Single;
temp: Double;
collisionPoint: TAffineVector;
foundCollison: Boolean;
t: Single;
planeIntersectionPoint, v: TAffineVector;
Velocity, base: TAffineVector;
velocitySquaredLength: Single;
a, b, c: Single; // Params for equation
newT: Single;
edge, baseToVertex: TAffineVector;
edgeSquaredLength: Single;
edgeDotVelocity: Single;
edgeDotBaseToVertex: Single;
distToCollision: Single;
begin
result := false;
// Make the plane containing this triangle.
trianglePlane := TECPlane.Create;
trianglePlane.MakePlane(p1, p2, p3);
// Is triangle front-facing to the velocity vector?
// We only check front-facing triangles
// (your choice of course)
if not(trianglePlane.isFrontFacingTo(MP.CP.NormalizedVelocity)) then
begin
trianglePlane.Free;
Exit;
end; // }
// Get interval of plane intersection:
embeddedInPlane := false;
// Calculate the signed distance from sphere
// position to triangle plane
// V := VectorAdd(MP.CP.basePoint,MP.CP.velocity);
// signedDistToTrianglePlane := trianglePlane.signedDistanceTo(v);
signedDistToTrianglePlane := trianglePlane.signedDistanceTo(MP.CP.BasePoint);
// cache this as weíre going to use it a few times below:
normalDotVelocity := VectorDotProduct(trianglePlane.Normal, MP.CP.Velocity);
// if sphere is travelling parrallel to the plane:
if normalDotVelocity = 0 then
begin
if (abs(signedDistToTrianglePlane) >= 1) then
begin
// Sphere is not embedded in plane.
// No collision possible:
trianglePlane.Free;
Exit;
end
else
begin
// sphere is embedded in plane.
// It intersects in the whole range [0..1]
embeddedInPlane := true;
t0 := 0;
// t1 := 1;
end;
end
else
begin
// N dot D is not 0. Calculate intersection interval:
t0 := (-1 - signedDistToTrianglePlane) / normalDotVelocity;
t1 := (1 - signedDistToTrianglePlane) / normalDotVelocity;
// Swap so t0 < t1
if (t0 > t1) then
begin
temp := t1;
t1 := t0;
t0 := temp;
end;
// Check that at least one result is within range:
if (t0 > 1) or (t1 < 0) then
begin
trianglePlane.Free;
Exit; // Both t values are outside values [0,1] No collision possible:
end;
// Clamp to [0,1]
if (t0 < 0) then
t0 := 0;
if (t0 > 1) then
t0 := 1;
// if (t1 < 0) then t1 := 0;
// if (t1 > 1) then t1 := 1;
end;
// OK, at this point we have two time values t0 and t1
// between which the swept sphere intersects with the
// triangle plane. If any collision is to occur it must
// happen within this interval.
foundCollison := false;
t := 1;
// First we check for the easy case - collision inside
// the triangle. If this happens it must be at time t0
// as this is when the sphere rests on the front side
// of the triangle plane. Note, this can only happen if
// the sphere is not embedded in the triangle plane.
if (not embeddedInPlane) then
begin
planeIntersectionPoint := VectorSubtract(MP.CP.BasePoint,
trianglePlane.Normal);
v := VectorScale(MP.CP.Velocity, t0);
VectorAdd(planeIntersectionPoint, v);
if CheckPointInTriangle(planeIntersectionPoint, p1, p2, p3) then
begin
foundCollison := true;
t := t0;
collisionPoint := planeIntersectionPoint;
end;
end;
// if we havenít found a collision already weíll have to
// sweep sphere against points and edges of the triangle.
// Note: A collision inside the triangle (the check above)
// will always happen before a vertex or edge collision!
// This is why we can skip the swept test if the above
// gives a collision!
if (not foundCollison) then
begin
// some commonly used terms:
Velocity := MP.CP.Velocity;
base := MP.CP.BasePoint;
velocitySquaredLength := VectorNorm(Velocity);
// velocitySquaredLength := Sqr(VectorLength(velocity));
// For each vertex or edge a quadratic equation have to
// be solved. We parameterize this equation as
// a*t^2 + b*t + c = 0 and below we calculate the
// parameters a,b and c for each test.
// Check against points:
a := velocitySquaredLength;
// P1
v := VectorSubtract(base, p1);
b := 2.0 * (VectorDotProduct(Velocity, v));
c := VectorNorm(v) - 1.0; // c := Sqr(VectorLength(V)) - 1.0;
if (GetLowestRoot(a, b, c, t, newT)) then
begin
t := newT;
foundCollison := true;
collisionPoint := p1;
end;
// P2
v := VectorSubtract(base, p2);
b := 2.0 * (VectorDotProduct(Velocity, v));
c := VectorNorm(v) - 1.0; // c := Sqr(VectorLength(V)) - 1.0;
if (GetLowestRoot(a, b, c, t, newT)) then
begin
t := newT;
foundCollison := true;
collisionPoint := p2;
end;
// P3
v := VectorSubtract(base, p3);
b := 2.0 * (VectorDotProduct(Velocity, v));
c := VectorNorm(v) - 1.0; // c := Sqr(VectorLength(V)) - 1.0;
if (GetLowestRoot(a, b, c, t, newT)) then
begin
t := newT;
foundCollison := true;
collisionPoint := p3;
end;
// Check against edges:
// p1 -> p2:
edge := VectorSubtract(p2, p1);
baseToVertex := VectorSubtract(p1, base);
edgeSquaredLength := VectorNorm(edge);
// edgeSquaredLength := Sqr(VectorLength(edge));
edgeDotVelocity := VectorDotProduct(edge, Velocity);
edgeDotBaseToVertex := VectorDotProduct(edge, baseToVertex);
// Calculate parameters for equation
a := edgeSquaredLength * -velocitySquaredLength + edgeDotVelocity *
edgeDotVelocity;
b := edgeSquaredLength * (2 * VectorDotProduct(Velocity, baseToVertex)) -
2.0 * edgeDotVelocity * edgeDotBaseToVertex;
c := edgeSquaredLength * (1 - VectorNorm(baseToVertex)) +
// (1- Sqr(VectorLength(baseToVertex)) )
edgeDotBaseToVertex * edgeDotBaseToVertex;
// Does the swept sphere collide against infinite edge?
if (GetLowestRoot(a, b, c, t, newT)) then
begin
// Check if intersection is within line segment:
temp := (edgeDotVelocity * newT - edgeDotBaseToVertex) /
edgeSquaredLength;
if (temp >= 0) and (temp <= 1) then
begin
// intersection took place within segment.
t := newT;
foundCollison := true;
collisionPoint := VectorAdd(p1, VectorScale(edge, temp));
end;
end;
// p1 -> p2:
edge := VectorSubtract(p3, p2);
baseToVertex := VectorSubtract(p2, base);
edgeSquaredLength := VectorNorm(edge);
// edgeSquaredLength := Sqr(VectorLength(edge));
edgeDotVelocity := VectorDotProduct(edge, Velocity);
edgeDotBaseToVertex := VectorDotProduct(edge, baseToVertex);
// Calculate parameters for equation
a := edgeSquaredLength * -velocitySquaredLength + edgeDotVelocity *
edgeDotVelocity;
b := edgeSquaredLength * (2 * VectorDotProduct(Velocity, baseToVertex)) -
2.0 * edgeDotVelocity * edgeDotBaseToVertex;
c := edgeSquaredLength * (1 - VectorNorm(baseToVertex)) +
// (1- Sqr(VectorLength(baseToVertex)) )
edgeDotBaseToVertex * edgeDotBaseToVertex;
// Does the swept sphere collide against infinite edge?
if (GetLowestRoot(a, b, c, t, newT)) then
begin
// Check if intersection is within line segment:
temp := (edgeDotVelocity * newT - edgeDotBaseToVertex) /
edgeSquaredLength;
if (temp >= 0) and (temp <= 1) then
begin
// intersection took place within segment.
t := newT;
foundCollison := true;
collisionPoint := VectorAdd(p2, VectorScale(edge, temp));
end;
end;
// p3 -> p1:
edge := VectorSubtract(p1, p3);
baseToVertex := VectorSubtract(p3, base);
edgeSquaredLength := VectorNorm(edge);
// edgeSquaredLength := Sqr(VectorLength(edge));
edgeDotVelocity := VectorDotProduct(edge, Velocity);
edgeDotBaseToVertex := VectorDotProduct(edge, baseToVertex);
// Calculate parameters for equation
a := edgeSquaredLength * -velocitySquaredLength + edgeDotVelocity *
edgeDotVelocity;
b := edgeSquaredLength * (2 * VectorDotProduct(Velocity, baseToVertex)) -
2.0 * edgeDotVelocity * edgeDotBaseToVertex;
c := edgeSquaredLength * (1 - VectorNorm(baseToVertex)) +
// (1- Sqr(VectorLength(baseToVertex)) )
edgeDotBaseToVertex * edgeDotBaseToVertex;
// Does the swept sphere collide against infinite edge?
if (GetLowestRoot(a, b, c, t, newT)) then
begin
// Check if intersection is within line segment:
temp := (edgeDotVelocity * newT - edgeDotBaseToVertex) /
edgeSquaredLength;
if (temp >= 0) and (temp <= 1) then
begin
// intersection took place within segment.
t := newT;
foundCollison := true;
collisionPoint := VectorAdd(p3, VectorScale(edge, temp));
end;
end;
end;
// Set result:
if foundCollison then
begin
// distance to collision: ítí is time of collision
distToCollision := t * VectorLength(MP.CP.Velocity);
result := true;
with ContactInfo do
begin
Position := collisionPoint;
SurfaceNormal := trianglePlane.Normal;
Distance := distToCollision;
ObjectInfo := ColliderObjectInfo;
end;
// Does this triangle qualify for the closest hit?
// it does if itís the first hit or the closest
if ((MP.CP.FoundCollision = false) or
(distToCollision < MP.CP.NearestDistance)) and (MP.ObjectInfo.Solid) and
(ColliderObjectInfo.Solid) then
begin
// Collision information nessesary for sliding
MP.CP.NearestDistance := distToCollision;
MP.CP.NearestObject := ColliderObjectInfo.ObjectID;
MP.CP.IntersectionPoint := collisionPoint;
MP.CP.IntersectionNormal := trianglePlane.Normal;
MP.CP.FoundCollision := true;
end;
end;
trianglePlane.Free;
end;
function CheckPoint(var MP: TECMovePack; pPos, pNormal: TAffineVector;
ColliderObjectInfo: TECObjectInfo): Boolean;
var
newPos: TAffineVector;
Distance: Single;
FoundCollision: Boolean;
begin
newPos := VectorAdd(MP.CP.BasePoint, MP.CP.Velocity);
// *** Need to check if the ellipsoid is embedded ***
Distance := VectorDistance(pPos, newPos) - 1; // 1 is the sphere radius
if Distance < 0 then
Distance := 0;
if (VectorNorm(MP.CP.Velocity) >= VectorDistance2(MP.CP.BasePoint, pPos)) then
Distance := 0;
FoundCollision := Distance <= (cECCloseDistance * MP.UnitScale);
// Very small distance
result := FoundCollision;
// Set result:
if FoundCollision then
begin
// Add a contact
SetLength(MP.Contacts, Length(MP.Contacts) + 1);
with MP.Contacts[High(MP.Contacts)] do
begin
Position := pPos;
ScaleVector(Position, MP.Radius);
SurfaceNormal := pNormal;
Distance := Distance;
ObjectInfo := ColliderObjectInfo;
end;
if ((MP.CP.FoundCollision = false) or (Distance < MP.CP.NearestDistance))
and (MP.ObjectInfo.Solid) and (ColliderObjectInfo.Solid) then
begin
// Collision information nessesary for sliding
MP.CP.NearestDistance := Distance;
MP.CP.NearestObject := ColliderObjectInfo.ObjectID;
MP.CP.IntersectionPoint := pPos;
MP.CP.IntersectionNormal := pNormal;
MP.CP.FoundCollision := true;
end;
end;
end;
function CheckEllipsoid(var MP: TECMovePack; ePos, eRadius: TAffineVector;
ColliderObjectInfo: TECObjectInfo): Boolean;
var
newPos, nA, rA, nB, rB, iPoint, iNormal: TAffineVector;
dist: Single;
begin
result := false;
// Check if the new position has passed the ellipse
if VectorNorm(MP.CP.Velocity) < VectorDistance2(MP.CP.BasePoint, ePos) then
newPos := VectorAdd(MP.CP.BasePoint, MP.CP.Velocity)
else
begin
nA := VectorScale(VectorNormalize(VectorSubtract(MP.CP.BasePoint,
ePos)), 1);
newPos := VectorAdd(ePos, nA);
end;
// Find intersection
nA := VectorNormalize(VectorDivide(VectorSubtract(ePos, newPos), eRadius));
rA := VectorAdd(newPos, nA);
nB := VectorNormalize(VectorDivide(VectorSubtract(rA, ePos), eRadius));
ScaleVector(nB, eRadius);
// Is colliding?
dist := VectorDistance(newPos, ePos) - 1 - VectorLength(nB);
if (dist > cECCloseDistance) then
Exit;
rB := VectorAdd(ePos, nB);
iPoint := rB;
iNormal := VectorNormalize(VectorDivide(VectorSubtract(newPos, ePos),
eRadius));
if dist < 0 then
dist := 0;
// Add a contact
SetLength(MP.Contacts, Length(MP.Contacts) + 1);
with MP.Contacts[High(MP.Contacts)] do
begin
Position := iPoint;
ScaleVector(Position, MP.Radius);
SurfaceNormal := iNormal;
Distance := dist;
ObjectInfo := ColliderObjectInfo;
end;
if ((MP.CP.FoundCollision = false) or (dist < MP.CP.NearestDistance)) and
(MP.ObjectInfo.Solid) and (ColliderObjectInfo.Solid) then
begin
MP.CP.NearestDistance := dist;
MP.CP.NearestObject := ColliderObjectInfo.ObjectID;
MP.CP.IntersectionPoint := iPoint;
MP.CP.IntersectionNormal := iNormal;
MP.CP.FoundCollision := true;
end;
result := true;
end;
procedure CheckCollisionFreeForm(var MP: TECMovePack);
var
n, i, t, k: Integer;
p: POctreeNode;
p1, p2, p3: PAffineVector;
v1, v2, v3: TAffineVector;
Collided: Boolean;
ContactInfo: TECContact;
begin
// For each freeform
for n := 0 to High(MP.Freeforms) do
begin
// For each octree node
for i := 0 to High(MP.Freeforms[n].OctreeNodes) do
begin
p := MP.Freeforms[n].OctreeNodes[i];
// for each triangle
for t := 0 to High(p.TriArray) do
begin
k := p.TriArray[t];
// These are the vertices of the triangle to check
p1 := @MP.Freeforms[n].triangleFiler^.List[k];
p2 := @MP.Freeforms[n].triangleFiler^.List[k + 1];
p3 := @MP.Freeforms[n].triangleFiler^.List[k + 2];
if not MP.Freeforms[n].InvertedNormals then
begin
SetVector(v1, VectorTransform(p1^,
MP.Freeforms[n].ObjectInfo.AbsoluteMatrix));
SetVector(v2, VectorTransform(p2^,
MP.Freeforms[n].ObjectInfo.AbsoluteMatrix));
SetVector(v3, VectorTransform(p3^,
MP.Freeforms[n].ObjectInfo.AbsoluteMatrix));
end
else
begin
SetVector(v1, VectorTransform(p3^,
MP.Freeforms[n].ObjectInfo.AbsoluteMatrix));
SetVector(v2, VectorTransform(p2^,
MP.Freeforms[n].ObjectInfo.AbsoluteMatrix));
SetVector(v3, VectorTransform(p1^,
MP.Freeforms[n].ObjectInfo.AbsoluteMatrix));
end;
{$IFDEF DEBUG}
AddDebugTri(v1, v2, v3); // @Debug
{$ENDIF}
// Set the triangles to the ellipsoid space
v1 := VectorDivide(v1, MP.Radius);
v2 := VectorDivide(v2, MP.Radius);
v3 := VectorDivide(v3, MP.Radius);
Collided := CheckTriangle(MP, v1, v2, v3, MP.Freeforms[n].ObjectInfo,
ContactInfo);
// Add a contact
if Collided then
begin
SetLength(MP.Contacts, Length(MP.Contacts) + 1);
ScaleVector(ContactInfo.Position, MP.Radius);
MP.Contacts[High(MP.Contacts)] := ContactInfo;
end;
end;
end;
end; // for n
end;
procedure CheckCollisionTriangles(var MP: TECMovePack);
var
n, i: Integer;
p1, p2, p3: TAffineVector;
Collided: Boolean;
ContactInfo: TECContact;
begin
for n := 0 to High(MP.TriMeshes) do
begin
for i := 0 to High(MP.TriMeshes[n].Triangles) do
begin
{$IFDEF DEBUG}
AddDebugTri(MP.TriMeshes[n].Triangles[i].p1,
MP.TriMeshes[n].Triangles[i].p2, MP.TriMeshes[n].Triangles[i].p3);
// @Debug
{$ENDIF}
// These are the vertices of the triangle to check
p1 := VectorDivide(MP.TriMeshes[n].Triangles[i].p1, MP.Radius);
p2 := VectorDivide(MP.TriMeshes[n].Triangles[i].p2, MP.Radius);
p3 := VectorDivide(MP.TriMeshes[n].Triangles[i].p3, MP.Radius);
Collided := CheckTriangle(MP, p1, p2, p3, MP.TriMeshes[n].ObjectInfo,
ContactInfo);
// Add a contact
if Collided then
begin
SetLength(MP.Contacts, Length(MP.Contacts) + 1);
ScaleVector(ContactInfo.Position, MP.Radius);
MP.Contacts[High(MP.Contacts)] := ContactInfo;
end;
end;
end;
end;
procedure CheckCollisionColliders(var MP: TECMovePack);
var
i: Integer;
p1, p2: TAffineVector;
begin
for i := 0 to High(MP.Colliders) do
begin
p1 := VectorDivide(MP.Colliders[i].Position, MP.Radius);
p2 := VectorDivide(MP.Colliders[i].Radius, MP.Radius);
case MP.Colliders[i].Shape of
csEllipsoid:
CheckEllipsoid(MP, p1, p2, MP.Colliders[i].ObjectInfo);
csPoint:
CheckPoint(MP, p1, p2, MP.Colliders[i].ObjectInfo);
end;
end;
end;
procedure CollideAndSlide(var MP: TECMovePack);
var
eSpacePosition, eSpaceVelocity: TAffineVector;
begin
// calculate position and velocity in eSpace
eSpacePosition := VectorDivide(MP.Position, MP.Radius);
eSpaceVelocity := VectorDivide(MP.Velocity, MP.Radius);
// Iterate until we have our final position.
MP.collisionRecursionDepth := 0;
CollideWithWorld(MP, eSpacePosition, eSpaceVelocity, MP.VelocityCollided);
// Add gravity pull:
// Set the new R3 position (convert back from eSpace to R3
MP.GroundNormal := NullVector;
MP.GravityCollided := false;
if not VectorIsNull(MP.Gravity) then
begin
eSpaceVelocity := VectorDivide(MP.Gravity, MP.Radius);
eSpacePosition := MP.ResultPos;
MP.collisionRecursionDepth := 0;
CollideWithWorld(MP, eSpacePosition, eSpaceVelocity, MP.GravityCollided);
if MP.GravityCollided then
MP.GroundNormal := MP.CP.IntersectionNormal;
end;
// Convert final result back to R3:
ScaleVector(MP.ResultPos, MP.Radius);
end;
procedure CollideWithWorld(var MP: TECMovePack; pos, vel: TAffineVector;
var HasCollided: Boolean);
var
veryCloseDistance: Single;
destinationPoint, newBasePoint, v: TAffineVector;
slidePlaneOrigin, slidePlaneNormal: TAffineVector;
slidingPlane: TECPlane;
newDestinationPoint, newVelocityVector: TAffineVector;
begin
// First we set to false (no collision)
if (MP.collisionRecursionDepth = 0) then
HasCollided := false;
veryCloseDistance := cECCloseDistance * MP.UnitScale;
MP.ResultPos := pos;
// do we need to worry?
if (MP.collisionRecursionDepth > MP.MaxRecursionDepth) then
Exit;
// Ok, we need to worry:
MP.CP.Velocity := vel;
MP.CP.NormalizedVelocity := VectorNormalize(vel);
MP.CP.BasePoint := pos;
MP.CP.FoundCollision := false;
// Check for collision (calls the collision routines)
CheckCollisionFreeForm(MP);
CheckCollisionTriangles(MP);
CheckCollisionColliders(MP);
// If no collision we just move along the velocity
if (not MP.CP.FoundCollision) then
begin
MP.ResultPos := VectorAdd(pos, vel);
Exit;
end;
// *** Collision occured ***
if (MP.CP.FoundCollision) then
HasCollided := true;
MP.NearestObject := MP.CP.NearestObject;
// The original destination point
destinationPoint := VectorAdd(pos, vel);
newBasePoint := pos;
// only update if we are not already very close
// and if so we only move very close to intersection..not
// to the exact spot.
if (MP.CP.NearestDistance >= veryCloseDistance) then
begin
v := vel;
VectorSetLength(v, MP.CP.NearestDistance - veryCloseDistance);
newBasePoint := VectorAdd(MP.CP.BasePoint, v);
// Adjust polygon intersection point (so sliding
// plane will be unaffected by the fact that we
// move slightly less than collision tells us)
NormalizeVector(v);
ScaleVector(v, veryCloseDistance);
SubtractVector(MP.CP.IntersectionPoint, v);
end;
// Determine the sliding plane
slidePlaneOrigin := MP.CP.IntersectionPoint;
slidePlaneNormal := VectorSubtract(newBasePoint, MP.CP.IntersectionPoint);
NormalizeVector(slidePlaneNormal);
slidingPlane := TECPlane.Create;
slidingPlane.MakePlane(slidePlaneOrigin, slidePlaneNormal);
v := VectorScale(slidePlaneNormal,
slidingPlane.signedDistanceTo(destinationPoint));
newDestinationPoint := VectorSubtract(destinationPoint, v);
// Generate the slide vector, which will become our new
// velocity vector for the next iteration
newVelocityVector := VectorSubtract(newDestinationPoint,
MP.CP.IntersectionPoint);
if (MP.CP.NearestDistance = 0) then
begin
v := VectorNormalize(VectorSubtract(newBasePoint, MP.CP.IntersectionPoint));
v := VectorScale(v, veryCloseDistance);
AddVector(newVelocityVector, v);
end;
// Recurse:
// dont recurse if the new velocity is very small
if (VectorNorm(newVelocityVector) < Sqr(veryCloseDistance)) then
begin
MP.ResultPos := newBasePoint;
slidingPlane.Free;
Exit;
end;
slidingPlane.Free;
Inc(MP.collisionRecursionDepth);
CollideWithWorld(MP, newBasePoint, newVelocityVector, HasCollided);
end;
end.
|
{
Role
Draw shapes using the mouse actions.
}
unit ThDrawObject;
interface
uses
System.Classes,
System.Generics.Collections,
GR32, GR32_Polygons, GR32_VectorUtils,
clipper,
ThTypes, ThClasses, ThItemStyle,
ThItem, ThItemCollections, ThShapeItem;
type
TThCustomDrawObject = class(TThInterfacedObject, IThDrawObject)
private
FDrawStyle: IThDrawStyle;
protected
FMouseDowned: Boolean;
public
constructor Create(AStyle: IThDrawStyle); virtual;
procedure Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); virtual;
procedure MouseDown(const APoint: TFloatPoint; AShift: TShiftState); virtual;
procedure MouseMove(const APoint: TFloatPoint; AShift: TShiftState); virtual;
procedure MouseUp(const APoint: TFloatPoint; AShift: TShiftState); virtual;
function GetItemInstance: IThItem; virtual;
property DrawStyle: IThDrawStyle read FDrawStyle write FDrawStyle;
end;
// 자유선으로 그리기 객체(Free draw object)
TThPenDrawObject = class(TThCustomDrawObject)
private
FPenItem: TThPenItem;
FPath: TList<TFloatPoint>;
FPolyPolyPath: TPaths;
FPolyPoly: TThPolyPoly;
public
constructor Create(AStyle: IThDrawStyle); override;
destructor Destroy; override;
procedure MouseDown(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseMove(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseUp(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); override;
function GetItemInstance: IThItem; override;
end;
// 지우개 베이스 클래스
TThCustomEraserObject = class(TThCustomDrawObject)
private
FItemList: TThItemList;
function GetDrawStyle: TThEraserStyle;
property DrawStyle: TThEraserStyle read GetDrawStyle;
protected
FPos: TFloatPoint;
public
constructor Create(AStyle: IThDrawStyle; AItems: TThItemList); reintroduce;
procedure Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); override;
end;
// 지나간 객체 지우개(Passed objects eraser)
TThObjectEraserObject = class(TThCustomEraserObject)
public
procedure MouseDown(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseMove(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseUp(const APoint: TFloatPoint; AShift: TShiftState); override;
end;
/// Shape Objects base
TThShapeDrawObject = class(TThCustomDrawObject)
private
FShapeId: string;
FShapeItem: IThShapeItem;
protected
FStartPoint, FCurrPoint: TFloatPoint;
public
constructor Create(AStyle: IThDrawStyle); override;
destructor Destroy; override;
procedure MouseDown(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseMove(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseUp(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint); override;
function GetItemInstance: IThItem; override;
property ShapeId: string read FShapeId write FShapeId;
end;
// Shape (multi)select
// Select > Move, Delete, Resize, Link
TDragMode = (dmNone, dmItemMove, dmItemResize, dmMultSelect{Drag for select});
TThSelectObject = class(TThCustomDrawObject)
private
FDragMode: TDragMode;
FLastPoint: TFloatPoint;
FItemList: TThItemList;
FSelectedItem: IThSelectableItem;
// FSelectedItems: TThSelectedItems;
procedure ProcessSelect(ASelectingItem: IThSelectableItem; AIsMultipleSelect: Boolean);
public
constructor Create(AItems: TThItemList); reintroduce;
destructor Destroy; override;
procedure MouseDown(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseMove(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure MouseUp(const APoint: TFloatPoint; AShift: TShiftState); override;
procedure DeleteSelectedItems;
procedure ClearSelection;
end;
implementation
uses
// Winapi.Windows, // ODS
ThUtils,
System.SysUtils,
System.Math;
{ TThDrawObject }
constructor TThCustomDrawObject.Create(AStyle: IThDrawStyle);
begin
FDrawStyle := AStyle;
end;
procedure TThCustomDrawObject.MouseDown;
begin
FMouseDowned := True;
end;
procedure TThCustomDrawObject.MouseMove(const APoint: TFloatPoint;
AShift: TShiftState);
begin
end;
procedure TThCustomDrawObject.MouseUp;
begin
FMouseDowned := False;
end;
function TThCustomDrawObject.GetItemInstance: IThItem;
begin
Result := nil;
end;
procedure TThCustomDrawObject.Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint);
begin
end;
{ TThPenObject }
constructor TThPenDrawObject.Create(AStyle: IThDrawStyle);
begin
inherited;
FPath := TList<TFloatPoint>.Create;
end;
destructor TThPenDrawObject.Destroy;
begin
FPath.Free;
inherited;
end;
procedure TThPenDrawObject.MouseDown(const APoint: TFloatPoint; AShift: TShiftState);
var
LPoly: TThPoly;
begin
inherited;
FPenItem := TThPenItem.Create;
FPenItem.SetStyle(FDrawStyle);
FPath.Add(APoint);
LPoly := Circle(APoint, FPenItem.Thickness / 2);
FPolyPoly := GR32_VectorUtils.PolyPolygon(LPoly);
FPolyPolyPath := AAFloatPoint2AAPoint(FPolyPoly, 3);
end;
procedure TThPenDrawObject.MouseMove(const APoint: TFloatPoint; AShift: TShiftState);
var
Poly: TThPoly;
PolyPath: TPath;
LastPt: TFloatPoint; // Adjusted point
begin
inherited;
if FMouseDowned then
begin
FPath.Add(APoint);
LastPt := FPath.Items[FPath.Count-2];
Poly := BuildPolyline([LastPt, APoint], FPenItem.Thickness, jsRound, esRound);
PolyPath := AAFloatPoint2AAPoint(Poly, 3);
with TClipper.Create do
try
AddPaths(FPolyPolyPath, ptSubject, True);
AddPath(PolyPath, ptClip, True);
Execute(ctUnion, FPolyPolyPath, pftNonZero);
finally
Free;
end;
FPolyPoly := AAPoint2AAFloatPoint(FPolyPolyPath, 3);
end;
end;
procedure TThPenDrawObject.MouseUp;
begin
inherited;
FPath.Clear;
FPolyPolyPath := nil;
FPolyPoly := nil;
FPenItem := nil;
end;
procedure TThPenDrawObject.Draw(Bitmap: TBitmap32; AScale, AOffset: TFloatPoint);
begin
if Assigned(FPenItem) then
FPenItem.DrawPoly(Bitmap, AScale, AOffset, FPath.ToArray, FPolyPoly);
end;
function TThPenDrawObject.GetItemInstance: IThItem;
begin
Result := FPenItem;
FPenItem := nil;
end;
{ TThEraserDrawObject }
constructor TThCustomEraserObject.Create(AStyle: IThDrawStyle;
AItems: TThItemList);
begin
if not Assigned(AStyle) then
AStyle := TThEraserStyle.Create;
inherited Create(AStyle);
FItemList := AItems;
end;
procedure TThCustomEraserObject.Draw(Bitmap: TBitmap32; AScale,
AOffset: TFloatPoint);
var
Poly: TThPoly;
begin
Poly := Circle(FPos, DrawStyle.Thickness / 2);
PolylineFS(Bitmap, Poly, clBlack32, True);
end;
function TThCustomEraserObject.GetDrawStyle: TThEraserStyle;
begin
Result := TThEraserStyle(FDrawStyle);
end;
{ TThObjectEraserObject }
procedure TThObjectEraserObject.MouseDown(const APoint: TFloatPoint; AShift: TShiftState);
begin
inherited;
FPos := APoint;
MouseMove(APoint, AShift);
end;
procedure TThObjectEraserObject.MouseMove(const APoint: TFloatPoint; AShift: TShiftState);
var
I: Integer;
Poly: TThPoly;
LItems: TArray<IThItem>;
begin
inherited;
if FMouseDowned then
begin
FPos := APoint;
Poly := Circle(APoint, DrawStyle.Thickness / 2);
LItems := FItemList.PolyInItems(Poly);
for I := 0 to Length(LItems) - 1 do
TThPenItem(LItems[I]).IsDeletion := True;
end;
end;
procedure TThObjectEraserObject.MouseUp(const APoint: TFloatPoint; AShift: TShiftState);
var
I: Integer;
Item: IThItem;
begin
inherited;
for I := FItemList.Count - 1 downto 0 do
begin
Item := FItemList[I];
if TThPenItem(Item).IsDeletion then
FItemList.Delete(I);
end;
end;
{ TThShapeDrawObject }
constructor TThShapeDrawObject.Create(AStyle: IThDrawStyle);
begin
if not Assigned(AStyle) then
AStyle := TThShapeStyle.Create;
inherited Create(AStyle);
end;
destructor TThShapeDrawObject.Destroy;
begin
inherited;
end;
procedure TThShapeDrawObject.MouseDown(const APoint: TFloatPoint; AShift: TShiftState);
begin
inherited;
FStartPoint := APoint;
end;
procedure TThShapeDrawObject.MouseMove(const APoint: TFloatPoint; AShift: TShiftState);
begin
inherited;
if FMouseDowned then
begin
if not Assigned(FShapeItem) then
FShapeItem := TThShapeItemFactory.GetShapeItem(FShapeId, FDrawStyle);
FCurrPoint := APoint;
end;
end;
procedure TThShapeDrawObject.MouseUp(const APoint: TFloatPoint; AShift: TShiftState);
begin
inherited;
FStartPoint := EmptyPoint;
FCurrPoint := EmptyPoint;
end;
procedure TThShapeDrawObject.Draw(Bitmap: TBitmap32; AScale,
AOffset: TFloatPoint);
begin
if Assigned(FShapeItem) then
FShapeItem.DrawPoints(Bitmap, AScale, AOffset, FStartPoint, FCurrPoint);
end;
function TThShapeDrawObject.GetItemInstance: IThItem;
begin
Result := nil;
if not Assigned(FShapeItem) then
Exit;
Result := FShapeItem;
FShapeItem := nil;
end;
{ TThSelectObject }
constructor TThSelectObject.Create(AItems: TThItemList);
begin
FItemList := AItems;
end;
destructor TThSelectObject.Destroy;
begin
inherited;
end;
procedure TThSelectObject.ClearSelection;
begin
// FSelectedItems.Clear;
end;
// Single(Click)
// Canvas : Clear Selections
// Item : Select Item
// Selected Item : None
// Item Handle : Start drag
// Multiple(Shift + Click)
// Canvas : None
// Item : Add to selection
// Selected Item : Remove from selection
// Item Handle : Start drag
procedure TThSelectObject.ProcessSelect(ASelectingItem: IThSelectableItem; AIsMultipleSelect: Boolean);
begin
FDragMode := dmNone;
if not Assigned(ASelectingItem) then
// Canvas click
begin
if not AIsMultipleSelect then
FItemList.ClearSelected;
// ClearSelection;
FSelectedItem := nil;
end
else
// Item click
begin
if not ASelectingItem.Selected then
// Unselected Item click
begin
if not AIsMultipleSelect then
ClearSelection;
ASelectingItem.Selected := True;
// FItemList2.Add(ASelectingItem);
// FSelectedItems.Add(ASelectingItem);
FSelectedItem := ASelectingItem;
FDragMode := dmItemMove;
end
else
// Selected item click
begin
if not Assigned(ASelectingItem.Selection.HotHandle) then
// Item click
begin
if AIsMultipleSelect then
// Cancel select of Selecting item
begin
ASelectingItem.Selected := False;
// FSelectedItems.Remove(ASelectingItem);
FSelectedItem := nil;
end
else
begin
FSelectedItem := ASelectingItem;
FDragMode := dmItemMove;
end;
end
else
// Handle click
begin
FDragMode := dmItemResize;
FSelectedItem := ASelectingItem;
end;
end;
end;
end;
procedure TThSelectObject.MouseDown(const APoint: TFloatPoint; AShift: TShiftState);
//var
// ConnectionItem: IThConnectableItem;
begin
inherited;
FItemList.MouseDown(APoint);
FLastPoint := APoint;
ProcessSelect(
FItemList.TargetItem, // ASelectingItem
AShift * [ssShift, ssCtrl] <> [] // AIsMultipleSelect
);
// if FDragMode = dmItemResize then
// begin
// if Supports(FSelectedItem, IThItemConnector) then
// begin
// ConnectionItem := FItemList.GetConnectionItem(APoint);
// if Assigned(ConnectionItem) then
// begin
// ConnectionItem.ShowConnection;
// ConnectionItem.MouseDown(APoint);
// end;
// end;
// end;
end;
procedure TThSelectObject.MouseMove(const APoint: TFloatPoint;
AShift: TShiftState);
var
MovePoint: TFloatPoint;
ConnectionItem: IThConnectableItem;
begin
inherited;
FItemList.MouseMove(APoint);
if FMouseDowned then
begin
if FDragMode = dmItemMove then
begin
MovePoint := APoint - FLastPoint;
FItemList.MoveSelectedItems(MovePoint);
// FSelectedItems.MoveItems(MovePoint);
FLastPoint := APoint;
end
else if FDragMode = dmItemResize then
begin
FSelectedItem.Selection.ResizeItem(APoint);
{ TODO : 현재 선택된 항목이 Connector이며,
포인트가 위치한 항목(크기 조정 중인 항목 제외)이 Connection 지원하는 경우
AnchorPoint 표시 }
if Supports(FSelectedItem, IThConnectorItem) then
begin
ConnectionItem := FItemList.GetConnectionItem(APoint);
if Assigned(ConnectionItem) then
begin
ConnectionItem.ShowConnection;
ConnectionItem.MouseMove(APoint);
end;
end;
end;
end
else
begin
end;
end;
procedure TThSelectObject.MouseUp(const APoint: TFloatPoint; AShift: TShiftState);
var
ConnectionItem: IThConnectableItem;
begin
FItemList.MouseUp(APoint);
if Assigned(FSelectedItem) and (FItemList.TargetItem <> FSelectedItem) then
FSelectedItem.MouseUp(APoint);
if FDragMode = dmItemResize then
begin
if Supports(FSelectedItem, IThConnectorItem) then
begin
ConnectionItem := FItemList.GetConnectionItem(APoint);
if Assigned(ConnectionItem) then
begin
ConnectionItem.HideConnection;
ConnectionItem.MouseUp(APoint);
end;
end;
end;
FDragMode := dmNone;
inherited;
end;
procedure TThSelectObject.DeleteSelectedItems;
begin
FItemList.RemoveSelectedItems;
end;
end.
|
unit TestULoteController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, DB, DBXJSON, UCondominioController, UCondominioVo, ConexaoBD,
Generics.Collections, UController, Classes, ULoteController, SysUtils, DBClient,
DBXCommon, SQLExpr, ULoteVO;
type
// Test methods for class TLoteController
TestTLoteController = class(TTestCase)
strict private
FLoteController: TLoteController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
procedure TestConsultaPorIdNaoEncontrado;
end;
implementation
procedure TestTLoteController.SetUp;
begin
FLoteController := TLoteController.Create;
end;
procedure TestTLoteController.TearDown;
begin
FLoteController.Free;
FLoteController := nil;
end;
procedure TestTLoteController.TestConsultaPorIdNaoEncontrado;
var
ReturnValue: TLoteVO;
begin
ReturnValue := FLoteController.ConsultarPorId(100);
if(returnvalue <> nil) then
check(false,'Lote pesquisado com sucesso!')
else
check(true,'Lote nao encontrado!');
end;
procedure TestTLoteController.TestConsultarPorId;
var
ReturnValue: TLoteVO;
begin
ReturnValue := FLoteController.ConsultarPorId(19);
if(returnvalue <> nil) then
check(True,'Lote pesquisado com sucesso!')
else
check(False,'Lote nao encontrado!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTLoteController.Suite);
end.
|
unit ManagedRecords_101_form;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Rtti;
type
TForm5 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Button2: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
private
{ Private declarations }
public
end;
var
Form5: TForm5;
procedure Log (const strMessage: string);
implementation
{$R *.dfm}
var
recNo: Integer = 0;
type
TMyRecord = record
private
FNumber: Integer;
public
Value: Integer;
class operator Initialize (out Dest: TMyRecord);
class operator Finalize(var Dest: TMyRecord);
class operator Assign (var Dest: TMyRecord;
const [ref] Src: TMyRecord);
end;
{ TMyRecord record}
class operator TMyRecord.Initialize (out Dest: TMyRecord);
begin
Inc (recNo);
Dest.FNumber := recNo;
Dest.Value := 10;
Log('created ' + Dest.FNumber.ToString + ' ' + IntToHex (Integer(Pointer(@Dest))));
end;
class operator TMyRecord.Assign (var Dest: TMyRecord; const [ref] Src: TMyRecord);
begin
Dest.Value := Src.Value;
// do not copy recNo!
Log (Src.FNumber.ToString + ' copied to ' + Dest.FNumber.ToString);
end;
class operator TMyRecord.Finalize(var Dest: TMyRecord);
begin
Log('destroyed ' + Dest.FNumber.ToString + ' ' + IntToHex (Integer(Pointer(@Dest))));
end;
procedure LocalVarTest;
var
t: TMyRecord;
begin
Log(t.Value.ToString);
end;
procedure InlineVarTest;
begin
var t: TMyRecord;
Log(t.Value.ToString);
end;
procedure InlineVarTest2;
var
my1: TMyRecord;
begin
var t := my1;
Log(t.Value.ToString);
var s: TMyRecord;
Log(s.Value.ToString);
end;
procedure SimpleAssign;
var
my1, my2: TMyRecord;
begin
my1.Value := 22;
my2 := my1;
end;
procedure ParByValue (rec: TMyRecord);
begin
Log ('ParByValue');
// rec.Value := 100;
end;
procedure ParByConstValue (const rec: TMyRecord);
begin
Log ('ParByConstValue');
// rec.Value := 100; // cannot assign to const
end;
procedure ParByRef (var rec: TMyRecord);
begin
Log ('ParByRef');
rec.Value := 100;
end;
procedure ParByConstRef (const rec: TMyRecord);
begin
Log ('ParByConstRef');
// rec.Value := 100; // cannot assign to const
end;
function ParReturned: TMyRecord;
begin
Log ('ParReturned');
Result.Value := 42;
end;
procedure TForm5.Button1Click(Sender: TObject);
begin
Log ('LocalVarTest');
LocalVarTest;
Log ('');
Log ('InlineVarTest');
InlineVarTest;
Log ('');
Log ('SimpleAssign');
SimpleAssign;
Log ('');
Log ('InlineVarTest2');
InlineVarTest2;
Log ('');
end;
procedure Log(const strMessage: string);
begin
Form5.Memo1.Lines.Add (strMessage);
end;
procedure TForm5.Button2Click(Sender: TObject);
var
my1: TMyRecord;
begin
Log(my1.Value.ToString);
ParByValue (my1);
Log(my1.Value.ToString);
ParByConstValue (my1);
Log(my1.Value.ToString);
ParByRef (my1);
Log(my1.Value.ToString);
ParByConstRef (my1);
Log(my1.Value.ToString);
my1 := ParReturned;
Log(my1.Value.ToString);
end;
var
fRaise: Boolean = False;
type
TMRException = record
x: Integer;
class operator Initialize(out Dest: TMRException);
class operator Finalize(var Dest: TMRException);
end;
class operator TMRException.Initialize(out Dest: TMRException);
begin
Log('created ' + IntToHex (Integer(Pointer(@Dest))));
if fRaise then
raise Exception.Create('Error Message');
end;
class operator TMRException.Finalize(var Dest: TMRException);
begin
Log('destroyed ' + IntToHex (Integer(Pointer(@Dest))));
end;
procedure ExceptionTest;
begin
fRaise := False;
var a: TMRException;
var b: TMRException;
raise Exception.Create('Error Message');
end;
procedure ExceptionInConstructor;
begin
Log ('ExceptionInConstructor');
fRaise := True;
var d: TMRException;
end;
procedure TForm5.Button4Click(Sender: TObject);
begin
try
ExceptionTest;
except
;
end;
try
ExceptionInConstructor;
except
;
end;
end;
procedure ArrOfRec;
var
a1: array [1..5] of TMyRecord;
begin
Log ('ArrOfRec');
// use array
for var I := Low(a1) to High (a1) do
Log (a1[I].Value.ToString);
end;
procedure ArrOfDyn;
var
a2: array of TMyRecord;
begin
Log ('ArrOfDyn');
SetLength(a2, 5);
for var I := Low(a2) to High (a2) do
Log (a2[I].Value.ToString);
end;
procedure TForm5.Button5Click(Sender: TObject);
begin
ArrOfRec;
ArrOfDyn;
end;
type
TMyRec4 = record
x: Integer;
constructor Create (const recc: TMyRec4);
end;
constructor TMyRec4.Create (const recc: TMyRec4);
begin
Log ('copy 4 onstructor');
end;
type
TMyRec5 = record
x: Integer;
class operator Initialize(out Dest: TMyRec5);
constructor Create (const recc: TMyRec5);
end;
class operator TMyRec5.Initialize(out Dest: TMyRec5);
begin
Log ('regular 5 constructor');
end;
constructor TMyRec5.Create (const recc: TMyRec5);
begin
Log ('MR 5 copy constructor');
end;
procedure TForm5.Button6Click(Sender: TObject);
var
rc: TRttiContext;
mr2: TMyRec4;
mrc2: TMyRec5;
begin
// copy constructor called twice
var mr1 := TMyRec4.Create (mr2);
if rc.GetType(TypeInfo(TMyRec4)).TypeKind = tkMRecord then
Log ('managed record')
else if rc.GetType(TypeInfo(TMyRec4)).TypeKind = tkRecord then
Log ('regular record');
var mrc55 := TMyRec5.Create (mrc2);
if rc.GetType(TypeInfo(TMyRec5)).TypeKind = tkMRecord then
Log ('managed record')
else if rc.GetType(TypeInfo(TMyRec5)).TypeKind = tkRecord then
Log ('regular record');
var mrc56 := mrc2;
end;
end.
|
{------------------------------------------------------------------------------}
{ 单元名称: GClearServer.pas }
{ }
{ 单元作者: 清清 }
{ 创建日期: 2008-02-22 20:30:00 }
{ }
{ 功能介绍: }
{ 实现开区清空服务器数据 }
{ }
{ 使用说明: }
{ }
{ }
{ 更新历史: }
{ }
{ 尚存问题: }
{ }
{ }
{------------------------------------------------------------------------------}
unit GClearServer;
interface
uses StdCtrls, Windows, forms, Inifiles, SysUtils, GShare, GMain , Dialogs,ShellApi;
procedure ListBoxAdd(ListBox: TListBox; AddStr:string); //增加ListBox记录
procedure ListBoxDel(ListBox: TListBox); //删除ListBox某条记录
function ClearGlobal(FileName: string):Boolean;//清全局变量
function DeleteTree(s: string):Boolean;//删除目录
function ClearWriteINI(FileName,ini1,ini2,ini3:string):Boolean; //写INI文件
procedure ClearTxt(TxtName: string); //清空TXT文件
procedure ListBoxClearTxtFile(ListBox: TListBox); //清空ListBox里的Txt文件
procedure ListBoxDelFile(ListBox: TListBox); //删除ListBox里的文件
function ListBoxDelDir(ListBox: TListBox):Boolean; //清空ListBod里的目录
function Clear_IniConf(): Boolean; //写配置信息
procedure Clear_LoadIniConf(); //读取配置信息
procedure ClearModValue(); //使保存按钮正常使用
var
GlobalVal: array[0..999] of Integer;
GlobalAVal: array[0..999] of string;
rec_stack: array [1..30] of TSearchRec;
rec_pointer: Integer;
g_sClearError: string;
implementation
procedure ClearModValue();
begin
frmMain.ClearSaveBtn.Enabled := True;
end;
function ClearGlobal(FileName: string):Boolean;
var
Config: TIniFile;
I:integer;
begin
Result := False;
Config := TIniFile.Create(FileName);
for I := Low(GlobalVal) to High(GlobalVal) do begin
Config.WriteInteger('Setup', 'GlobalVal' + IntToStr(I), 0);
end;
for I := Low(GlobalAVal) to High(GlobalAVal) do begin
Config.WriteString('Setup', 'GlobalStrVal' + IntToStr(I), '');
end;
Config.Free;
//sleep(2000);
Result := True;
end;
procedure ListBoxAdd(ListBox: TListBox; AddStr:string);
var i: Integer;
begin
for i:=0 to ListBox.Items.Count - 1 do
begin
if ListBox.Items.Strings [i] = AddStr then
begin
application.MessageBox('此文件路径已在列表中,请重新选择!!','提示信息',MB_ICONASTERISK);
Exit;
end;
end;
ListBox.Items.Add(AddStr);
end;
procedure ListBoxDel(ListBox: TListBox);
begin
ListBox.Items.BeginUpdate;
try
ListBox.DeleteSelected;
finally
ListBox.Items.EndUpdate;
end;
end;
//删除目录到回收站
function DeleteFileWithUndo(sFileName : string): boolean;
var
T : TSHFileOpStruct;
begin
FillChar(T, SizeOf(T), 0 );
with T do begin
wFunc := FO_DELETE;
pFrom := PChar(sFileName);
fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_SILENT;
end;
Result := ( 0 = ShFileOperation(T));
end;
function DeleteTree(s: string):Boolean;
var searchRec:TSearchRec;
begin
Result := True;
if FindFirst(s+'\*.*', faAnyFile, SearchRec)=0 then
repeat
if (SearchRec.Name<>'.') and (SearchRec.Name<>'..') then
begin
if (SearchRec.Attr and faDirectory >0) then
begin
rec_stack[rec_pointer]:=SearchRec;
rec_pointer:=rec_pointer-1;
DeleteTree(s+'\'+SearchRec.Name);
rec_pointer:=rec_pointer+1;
SearchRec:=rec_stack[rec_pointer];
end else begin
try
FileSetAttr(s+'\'+SearchRec.Name,faArchive);
//DeleteFile(s+'\'+SearchRec.Name);
if not DeleteFileWithUndo(s+'\'+SearchRec.Name) then//少部分文件没能清理掉,想不通 20080928
DeleteFile(s+'\'+SearchRec.Name);
except
g_sClearError := '删除文件:'+s+'\'+SearchRec.Name+'错误!';
Result := False;
end;
end;
end;
until (FindNext(SearchRec)<>0);
FindClose(SearchRec);
if rec_pointer<30 then begin
try
FileSetAttr(s,faArchive);
RemoveDir(s);
except
g_sClearError := '删除目录:'+s+'\'+SearchRec.Name+'错误!';
Result := False;
end;
end;
end;
function ClearWriteINI(FileName,ini1,ini2,ini3:string):Boolean;
var
Myinifile: TIniFile;
begin
Result := False;
Myinifile:=Tinifile.Create(FileName);
Myinifile.WriteString(ini1,ini2,ini3);
Myinifile.Free;
//sleep(2000);
Result := True;
end;
procedure ClearTxt(TxtName: string);
var
f:textfile;
begin
assignfile(f,TxtName);
rewrite(f);
closefile(f);
end;
procedure ListBoxClearTxtFile(ListBox: TListBox);
var
I: Integer;
begin
for I:=0 to ListBox.Items.Count -1 do
begin
ClearTxt(ListBox.Items.Strings [I]);
end;
end;
procedure ListBoxDelFile(ListBox: TListBox);
var
I: Integer;
begin
for I:=0 to ListBox.Items.Count -1 do
begin
DeleteFile(ListBox.Items.Strings [I]);
end;
end;
function ListBoxDelDir(ListBox: TListBox):Boolean;
var
I: Integer;
begin
Result := False;
for I:=0 to ListBox.Items.Count -1 do
begin
DeleteTree(ListBox.Items.Strings [I]);
end;
Result := True;
end;
function Clear_IniConf(): Boolean;
var
I: Integer;
begin
Result := False;
g_IniConf.WriteString('ClearServer', 'IDDB', frmMain.IDEd.Text);
g_IniConf.WriteString('ClearServer', 'FDB', frmMain.DBed.Text);
g_IniConf.WriteString('ClearServer', 'BaseDir', frmMain.LogEd.Text);
g_IniConf.WriteString('ClearServer', 'Castle', frmMain.CsEd.Text);
g_IniConf.WriteString('ClearServer', 'GuildBase', frmMain.CBed.Text);
g_IniConf.WriteString('ClearServer', 'ConLog', frmMain.CLed.Text);
g_IniConf.WriteString('ClearServer', 'market_upg', frmMain.upged.Text);
g_IniConf.WriteString('ClearServer', 'Market_SellOff', frmMain.Soed.Text);
g_IniConf.WriteString('ClearServer', 'ChrLog', frmMain.ChrLog.Text);
g_IniConf.WriteString('ClearServer', 'CountLog', frmMain.CountLog.Text);
g_IniConf.WriteString('ClearServer', 'Log', frmMain.M2Log.Text);
g_IniConf.WriteString('ClearServer', 'Market_prices', frmMain.sred1.Text);
g_IniConf.WriteString('ClearServer', 'Market_saved', frmMain.sred2.Text);
g_IniConf.WriteString('ClearServer', 'Sort', frmMain.EdtSort.Text);
g_IniConf.WriteBool('ClearServer', 'Global', frmMain.CheckBoxGlobal.Checked);
g_IniConf.WriteBool('ClearServer', 'UserData', frmMain.CheckBoxUserData.Checked);
g_IniConf.WriteBool('ClearServer', 'MasterNo', frmMain.CheckBoxMasterNo.Checked);
g_IniConf.WriteInteger('ClearServer', 'MyGetTxtNum', frmMain.ListBoxMyGetTXT.Items.Count);
if frmMain.ListBoxMyGetTXT.Items.Count <> 0 then begin
for I:=0 to frmMain.ListBoxMyGetTXT.Items.Count - 1 do
begin
g_IniConf.WriteString('ClearServer','MyGetTxt'+IntToStr(i),frmMain.ListBoxMyGetTXT.Items.Strings[i]);
end;
end;
g_IniConf.WriteInteger('ClearServer', 'MyGetFileNum', frmMain.ListBoxMyGetFile.Items.Count);
if frmMain.ListBoxMyGetFile.Items.Count <> 0 then begin
for I:=0 to frmMain.ListBoxMyGetFile.Items.Count -1 do
begin
g_IniConf.WriteString('ClearServer','MyGetFile'+IntToStr(i),frmMain.ListBoxMyGetFile.Items.Strings[i]);
end;
end;
g_IniConf.WriteInteger('ClearServer', 'MyGetDirNum', frmMain.ListBoxMyGetDir.Items.Count);
if frmMain.ListBoxMyGetDir.Items.Count <> 0 then begin
for I:=0 to frmMain.ListBoxMyGetDir.Items.Count -1 do
begin
g_IniConf.WriteString('ClearServer','MyGetDir'+IntToStr(i),frmMain.ListBoxMyGetDir.Items.Strings[i]);
end;
end;
Result := True;
end;
procedure Clear_LoadIniConf();
var
nMyGetTxtNum, nMyGetFileNum, nMyGetDirNum, I: Integer;
begin
frmMain.IDEd.Text := g_IniConf.ReadString('ClearServer', 'IDDB',frmMain.IDEd.Text);
frmMain.DBed.Text := g_IniConf.ReadString('ClearServer', 'FDB', frmMain.DBed.Text);
frmMain.LogEd.Text := g_IniConf.ReadString('ClearServer', 'BaseDir', frmMain.LogEd.Text);
frmMain.CsEd.Text := g_IniConf.ReadString('ClearServer', 'Castle', frmMain.CsEd.Text);
frmMain.CBed.Text := g_IniConf.ReadString('ClearServer', 'GuildBase', frmMain.CBed.Text);
frmMain.CLed.Text := g_IniConf.ReadString('ClearServer', 'ConLog', frmMain.CLed.Text);
frmMain.upged.Text := g_IniConf.ReadString('ClearServer', 'market_upg', frmMain.upged.Text);
frmMain.Soed.Text := g_IniConf.ReadString('ClearServer', 'Market_SellOff', frmMain.Soed.Text);
frmMain.ChrLog.Text := g_IniConf.ReadString('ClearServer', 'ChrLog', frmMain.ChrLog.Text);
frmMain.CountLog.Text := g_IniConf.ReadString('ClearServer', 'CountLog', frmMain.CountLog.Text);
frmMain.M2Log.Text := g_IniConf.ReadString('ClearServer', 'Log', frmMain.M2Log.Text);
frmMain.sred1.Text := g_IniConf.ReadString('ClearServer', 'Market_prices', frmMain.sred1.Text);
frmMain.sred2.Text := g_IniConf.ReadString('ClearServer', 'Market_saved', frmMain.sred2.Text);
frmMain.EdtSort.Text := g_IniConf.ReadString('ClearServer', 'Sort', frmMain.EdtSort.Text);
frmMain.CheckBoxGlobal.Checked := g_IniConf.ReadBool('ClearServer', 'Global', frmMain.CheckBoxGlobal.Checked);
frmMain.CheckBoxUserData.Checked := g_IniConf.ReadBool('ClearServer', 'UserData', frmMain.CheckBoxUserData.Checked);
frmMain.CheckBoxMasterNo.Checked := g_IniConf.ReadBool('ClearServer', 'MasterNo', frmMain.CheckBoxMasterNo.Checked);
nMyGetTxtNum := g_IniConf.ReadInteger('ClearServer', 'MyGetTxtNum', 0);
nMyGetFileNum := g_IniConf.ReadInteger('ClearServer', 'MyGetFileNum', 0);
nMyGetDirNum := g_IniConf.ReadInteger('ClearServer', 'MyGetDirNum', 0);
if nMyGetTxtNum <> 0 then begin
frmMain.ListBoxMyGetTXT.Items.Clear;
for I:=0 to nMyGetTxtNum - 1 do
begin
frmMain.ListBoxMyGetTXT.Items.Add(g_IniConf.ReadString('ClearServer','MyGetTxt'+IntToStr(I),'读取配置文件错误'));
end;
end;
if nMyGetFileNum <> 0 then begin
frmMain.ListBoxMyGetFile.Items.Clear;
for I:=0 to nMyGetFileNum - 1 do
begin
frmMain.ListBoxMyGetFile.Items.Add(g_IniConf.ReadString('ClearServer','MyGetFile'+IntToStr(I),'读取配置文件错误'));
end;
end;
if nMyGetDirNum <> 0 then begin
frmMain.ListBoxMyGetDir.Items.Clear;
for I:=0 to nMyGetDirNum - 1 do
begin
frmMain.ListBoxMyGetDir.Items.Add(g_IniConf.ReadString('ClearServer','MyGetDir'+IntToStr(I),'读取配置文件错误'));
end;
end;
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_PASCAL_PARSER.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PAXCOMP_PASCAL_PARSER;
interface
uses {$I uses.def}
SysUtils,
Classes,
PAXCOMP_CONSTANTS,
PAXCOMP_TYPES,
PAXCOMP_SYS,
PAXCOMP_BASESYMBOL_TABLE,
PAXCOMP_SCANNER,
PAXCOMP_BYTECODE,
PAXCOMP_MODULE,
PAXCOMP_STDLIB,
PAXCOMP_PARSER,
PAXCOMP_KERNEL,
PAXCOMP_BASERUNNER,
PAXCOMP_CLASSFACT,
PAXCOMP_GENERIC,
PAXCOMP_PASCAL_SCANNER;
const
dirNONE = 0;
dirFORWARD = 1;
dirOVERLOAD = 2;
dirABSTRACT = 3;
dirVIRTUAL = 4;
dirOVERRIDE = 5;
dirREINTRODUCE = 6;
dirDYNAMIC = 7;
dirSTATIC = 8;
dirFINAL = 9;
type
TPascalParser = class(TBaseParser)
private
I_STRICT: Integer;
I_PRIVATE: Integer;
I_PROTECTED: Integer;
I_PUBLIC: Integer;
I_PUBLISHED: Integer;
WasInherited: Boolean;
ForInCounter: Integer;
CONST_ONLY: Boolean;
OuterList: TAssocStringInt;
procedure GenExternalSub(SubId: Integer);
function MatchEx(const S: String): Boolean;
function InScope(const S: String): Boolean;
function Parse_AnonymousRoutine(IsFunc: Boolean): Integer;
procedure RemoveKeywords;
procedure RestoreKeywords;
protected
function CreateScanner: TBaseScanner; override;
function GetLanguageName: String; override;
function GetFileExt: String; override;
function GetLanguageId: Integer; override;
function GetUpcase: Boolean; override;
public
OnParseUnitName: TParserIdentEvent;
OnParseImplementationSection: TParserNotifyEvent;
OnParseBeginUsedUnitList: TParserNotifyEvent;
OnParseEndUsedUnitList: TParserNotifyEvent;
OnParseUsedUnitName: TParserIdentEvent;
OnParseTypeDeclaration: TParserIdentEvent;
OnParseForwardTypeDeclaration: TParserIdentEvent;
OnParseBeginClassTypeDeclaration: TParserIdentEventEx;
OnParseEndClassTypeDeclaration: TParserIdentEvent;
OnParseAncestorTypeDeclaration: TParserIdentEvent;
OnParseUsedInterface: TParserIdentEvent;
OnParseClassReferenceTypeDeclaration: TParserTypedIdentEvent;
OnParseAliasTypeDeclaration: TParserTypedIdentEvent;
OnParseProceduralTypeDeclaration: TParserIdentEventEx;
OnParseEventTypeDeclaration: TParserIdentEventEx;
OnParseMethodReferenceTypeDeclaration: TParserIdentEventEx;
OnParseSetTypeDeclaration: TParserTypedIdentEvent;
OnParsePointerTypeDeclaration: TParserTypedIdentEvent;
OnParseArrayTypeDeclaration: TParserArrayTypeEvent;
OnParseDynArrayTypeDeclaration: TParserTypedIdentEvent;
OnParseShortStringTypeDeclaration: TParserNamedValueEvent;
OnParseSubrangeTypeDeclaration: TParserDeclarationEvent;
OnParseBeginRecordTypeDeclaration: TParserIdentEventEx;
OnParseEndRecordTypeDeclaration: TParserIdentEvent;
OnParseBeginClassHelperTypeDeclaration: TParserTypedIdentEvent;
OnParseEndClassHelperTypeDeclaration: TParserIdentEvent;
OnParseBeginRecordHelperTypeDeclaration: TParserTypedIdentEvent;
OnParseEndRecordHelperTypeDeclaration: TParserIdentEvent;
OnParseBeginInterfaceTypeDeclaration: TParserIdentEvent;
OnParseEndInterfaceTypeDeclaration: TParserIdentEvent;
OnParseBeginEnumTypeDeclaration: TParserIdentEvent;
OnParseEndEnumTypeDeclaration: TParserIdentEvent;
OnParseEnumName: TParserNamedValueEvent;
OnParseFieldDeclaration: TParserTypedIdentEvent;
OnParseVariantRecordFieldDeclaration: TParserVariantRecordFieldEvent;
OnParsePropertyDeclaration: TParserTypedIdentEvent;
OnParseConstantDeclaration: TParserNamedValueEvent;
OnParseResourceStringDeclaration: TParserNamedValueEvent;
OnParseTypedConstantDeclaration: TParserNamedTypedValueEvent;
OnParseVariableDeclaration: TParserTypedIdentEvent;
OnParseBeginSubDeclaration: TParserIdentEvent;
OnParseEndSubDeclaration: TParserDeclarationEvent;
OnParseBeginFormalParameterList: TParserNotifyEvent;
OnParseEndFormalParameterList: TParserNotifyEvent;
OnParseFormalParameterDeclaration: TParserNamedTypedValueEvent;
OnParseResultType: TParserIdentEvent;
OnParseSubDirective: TParserIdentEvent;
constructor Create; override;
destructor Destroy; override;
procedure ParseProgram; override;
procedure Call_SCANNER; override;
procedure Match(const S: String); override;
procedure ReadToken; override;
procedure InitSub(var SubId: Integer); override;
function GetIncludedFileExt: String; override;
procedure Init(i_kernel: Pointer; M: TModule); override;
function Parse_DirectiveList(SubId: Integer): TIntegerList;
function Parse_PortabilityDirective: TPortDir;
procedure GenDefaultConstructor(ClassId: Integer);
procedure GenDefaultDestructor(ClassId: Integer);
procedure Parse_Attribute;
procedure Parse_Message(SubId: Integer);
procedure Parse_Library;
procedure Parse_ProgramBlock(namespace_id: Integer);
procedure Parse_Unit(IsExternalUnit: Boolean = false); override;
procedure Parse_Block;
procedure Parse_NamespaceDeclaration;
procedure Parse_UsesClause(IsImplementationSection: Boolean);
procedure Parse_NamespaceMemberDeclaration;
procedure Parse_DeclarationPart(IsImplementation: Boolean = false);
procedure Parse_VariableDeclaration(vis: TClassVisibility = cvNone);
procedure Parse_ConstantDeclaration(vis: TClassVisibility = cvNone);
procedure Parse_ResourcestringDeclaration;
procedure Parse_LabelDeclaration;
function Parse_FormalParameterList(SubId: Integer;
bracket: Char = '('): Integer;
procedure Parse_ProcedureDeclaration(IsSharedMethod: Boolean = false);
procedure Parse_FunctionDeclaration(IsSharedMethod: Boolean = false);
procedure Parse_OperatorDeclaration;
procedure Parse_ConstructorDeclaration;
procedure Parse_DestructorDeclaration;
procedure Parse_SubBlock;
procedure Parse_ConstantInitialization(ID: Integer);
function Parse_VariableInitialization: Integer;
// types
procedure Parse_TypeDeclaration(IsExternalUnit: Boolean = false;
vis: TClassVisibility = cvPublic);
procedure Parse_ProceduralTypeDeclaration(TypeID: Integer;
var SubId: Integer);
procedure Parse_ArrayTypeDeclaration(ArrayTypeID: Integer; IsPacked: Boolean);
function Parse_RecordConstructorHeading(IsSharedMethod: Boolean;
RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
function Parse_RecordDestructorHeading(IsSharedMethod: Boolean;
RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
function Parse_RecordProcedureHeading(IsSharedMethod: Boolean;
RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
function Parse_RecordFunctionHeading(IsSharedMethod: Boolean;
RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
function Parse_RecordOperatorHeading(RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
function Parse_RecordProperty(RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
procedure Parse_RecordVariantPart(VarLevel: Integer;
CurrVarCnt: Int64;
vis: TClassVisibility);
procedure Parse_RecordHelperItem;
procedure Parse_RecordTypeDeclaration(RecordTypeID: Integer; IsPacked: Boolean;
IsExternalUnit: Boolean = false);
function Parse_ClassConstructorHeading(IsSharedMethod: Boolean;
ClassTypeId: Integer;
vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
function Parse_ClassDestructorHeading(IsSharedMethod: Boolean;
ClassTypeId: Integer;
vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
function Parse_ClassProcedureHeading(IsSharedMethod: Boolean;
ClassTypeId: Integer;
vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
function Parse_ClassFunctionHeading(IsSharedMethod: Boolean;
ClassTypeId: Integer;
vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
function Parse_ClassProperty(IsShared: Boolean;
ClassTypeId: Integer;
vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
procedure Parse_ClassTypeDeclaration(ClassTypeID: Integer; IsPacked: Boolean;
IsExternalUnit: Boolean = false);
procedure Parse_InterfaceTypeDeclaration(IntfTypeID: Integer);
procedure Parse_MethodRefTypeDeclaration(TypeID: Integer);
procedure Parse_EnumTypeDeclaration(TypeID: Integer);
procedure Parse_PointerTypeDeclaration(TypeID: Integer);
{$IFNDEF PAXARM}
procedure Parse_ShortStringTypeDeclaration(TypeID: Integer);
{$ENDIF}
procedure Parse_SetTypeDeclaration(TypeID: Integer);
procedure Parse_SubrangeTypeDeclaration(TypeID, TypeBaseId: Integer;
var Declaration: String;
Expr1ID: Integer = 0);
function Parse_OrdinalType(var Declaration: String): Integer;
function Parse_Type: Integer;
function Parse_OpenArrayType(var ElemTypeName: String): Integer;
procedure ParseExternalSub(SubId: Integer);
//statements
function Parse_Statement: Boolean;
procedure Parse_CompoundStmt;
procedure Parse_StmtList;
procedure Parse_Write;
procedure Parse_Writeln;
procedure Parse_Print;
procedure Parse_Println;
procedure Parse_AssignmentStmt;
procedure Parse_CaseStmt;
procedure Parse_IfStmt;
procedure Parse_GotoStmt;
procedure Parse_BreakStmt;
procedure Parse_ContinueStmt;
procedure Parse_ExitStmt;
procedure Parse_WhileStmt;
procedure Parse_RepeatStmt;
procedure Parse_ForStmt;
procedure Parse_WithStmt;
procedure Parse_TryStmt;
procedure Parse_RaiseStmt;
function Parse_LoopStmt(l_break, l_continue, l_loop: Integer): Boolean;
//expressions
function Parse_LambdaParameters(SubId: Integer) : Integer;
function Parse_LambdaExpression: Integer;
function Parse_AnonymousFunction: Integer;
function Parse_AnonymousProcedure: Integer;
function Parse_ArgumentList(SubId: Integer): Integer;
function Parse_ConstantExpression: Integer;
function Parse_Expression: Integer; override;
function Parse_SimpleExpression: Integer;
function Parse_Term: Integer;
function Parse_Factor: Integer; override;
function Parse_SetConstructor: Integer;
function Parse_Designator(init_id: Integer = 0): Integer;
function Parse_Label: Integer;
function Parse_Ident: Integer; override;
// generic
procedure EndMethodDef(SubId: Integer); override;
procedure Parse_TypeRestriction(LocalTypeParams: TStringObjectList); override;
end;
TPascalExprParser = class
private
kernel: Pointer;
scanner: TPascalScanner;
function GetCurrToken: String;
function GetTokenClass: TTokenClass;
function Parse_SetConstructor: Variant;
function IsCurrText(const S: String): Boolean;
procedure Match(const S: String);
function NotMatch(const S: String): Boolean;
procedure Cancel;
procedure Call_SCANNER;
function Parse_Expression: Variant;
function Parse_SimpleExpression: Variant;
function Parse_Term: Variant;
function Parse_Factor: Variant;
public
LevelList: TIntegerList;
IsSet: Boolean;
ResExpr: String;
constructor Create(akernel: Pointer; const Expr: String);
destructor Destroy; override;
function ParseExpression: Variant;
function Lookup(const S: String): Variant;
function LegalValue(const V: Variant): Boolean;
property CurrToken: String read GetCurrToken;
property TokenClass: TTokenClass read GetTokenClass;
end;
implementation
uses
PAXCOMP_VAROBJECT;
constructor TPascalExprParser.Create(akernel: Pointer; const Expr: String);
begin
inherited Create;
LevelList := TIntegerList.Create(true);
kernel := akernel;
scanner := TPascalScanner.Create;
scanner.Init(kernel, Expr, 0);
ResExpr := '';
end;
destructor TPascalExprParser.Destroy;
begin
scanner.Free;
LevelList.Free;
inherited;
end;
function TPascalExprParser.GetCurrToken: String;
begin
result := scanner.Token.Text;
end;
function TPascalExprParser.GetTokenClass: TTokenClass;
begin
result := scanner.Token.TokenClass;
end;
function TPascalExprParser.IsCurrText(const S: String): Boolean;
begin
result := StrEql(S, CurrToken);
end;
function TPascalExprParser.LegalValue(const V: Variant): Boolean;
begin
result := VarType(V) <> varEmpty;
end;
procedure TPascalExprParser.Match(const S: String);
begin
if IsCurrText(S) then
Call_SCANNER
else
Cancel;
end;
procedure TPascalExprParser.Cancel;
begin
raise PaxCancelException.Create('');
end;
procedure TPascalExprParser.Call_SCANNER;
begin
scanner.ReadToken;
ResExpr := ResExpr + CurrToken;
end;
function TPascalExprParser.NotMatch(const S: String): Boolean;
begin
if not IsCurrText(S) then
result := true
else
begin
result := false;
Call_SCANNER;
end;
end;
function TPascalExprParser.Lookup(const S: String): Variant;
var
I, L, Id: Integer;
begin
for I := 0 to LevelList.Count - 1 do
begin
L := LevelList[I];
Id := TKernel(kernel).SymbolTable.LookUp(S, L, true);
if Id > 0 then
begin
result := TKernel(kernel).SymbolTable[Id].Value;
Exit;
end;
end;
end;
function TPascalExprParser.ParseExpression: Variant;
begin
Call_SCANNER;
Call_SCANNER;
Call_SCANNER;
try
result := Parse_Expression;
except
// canceled
end;
end;
function TPascalExprParser.Parse_Expression: Variant;
var
Op: Integer;
V: Variant;
begin
result := Parse_SimpleExpression;
if not LegalValue(result) then
Cancel;
if CurrToken = '=' then
Op := OP_EQ
else if CurrToken = '<>' then
Op := OP_NE
else if CurrToken = '>' then
Op := OP_GT
else if CurrToken = '>=' then
Op := OP_GE
else if CurrToken = '<' then
Op := OP_LT
else if CurrToken = '<=' then
Op := OP_LT
else
Op := 0;
while Op <> 0 do
begin
Call_SCANNER;
V := Parse_SimpleExpression;
if not LegalValue(V) then
Cancel;
if Op = OP_EQ then
result := result = V
else if Op = OP_NE then
result := result <> V
else if Op = OP_GT then
result := result > V
else if Op = OP_GE then
result := result >= V
else if Op = OP_LT then
result := result < V
else if Op = OP_LE then
result := result <= V;
if CurrToken = '=' then
Op := OP_EQ
else if CurrToken = '<>' then
Op := OP_NE
else if CurrToken = '>' then
Op := OP_GT
else if CurrToken = '>=' then
Op := OP_GE
else if CurrToken = '<' then
Op := OP_LT
else if CurrToken = '<=' then
Op := OP_LT
else
Op := 0;
end;
end;
function TPascalExprParser.Parse_SimpleExpression: Variant;
var
Op: Integer;
V: Variant;
begin
result := Parse_Term;
if not LegalValue(result) then
Cancel;
if CurrToken = '+' then
Op := OP_PLUS
else if CurrToken = '-' then
Op := OP_MINUS
else if StrEql(CurrToken, 'or') then
Op := OP_OR
else if StrEql(CurrToken, 'xor') then
Op := OP_XOR
else
Op := 0;
while Op <> 0 do
begin
Call_SCANNER;
V := Parse_Term;
if not LegalValue(V) then
Cancel;
if Op = OP_PLUS then
result := result + V
else if Op = OP_MINUS then
result := result - V
else if Op = OP_OR then
result := result or V
else if Op = OP_XOR then
result := result xor V;
if CurrToken = '+' then
Op := OP_PLUS
else if CurrToken = '-' then
Op := OP_MINUS
else if StrEql(CurrToken, 'or') then
Op := OP_OR
else if StrEql(CurrToken, 'xor') then
Op := OP_XOR
else
Op := 0;
end;
end;
function TPascalExprParser.Parse_Term: Variant;
var
Op: Integer;
V: Variant;
begin
result := Parse_Factor;
if not LegalValue(result) then
Cancel;
if CurrToken = '*' then
Op := OP_MULT
else if CurrToken = '/' then
Op := OP_DIV
else if StrEql(CurrToken, 'div') then
Op := OP_IDIV
else if StrEql(CurrToken, 'mod') then
Op := OP_MOD
else if StrEql(CurrToken, 'shl') then
Op := OP_SHL
else if StrEql(CurrToken, 'shr') then
Op := OP_SHL
else if StrEql(CurrToken, 'and') then
Op := OP_AND
else
Op := 0;
while Op <> 0 do
begin
Call_SCANNER;
V := Parse_Factor;
if not LegalValue(V) then
Cancel;
if Op = OP_MULT then
result := result * V
else if Op = OP_DIV then
begin
if V = 0.0 then
begin
if result = 0.0 then
result := NaN
else if result = 1.0 then
result := Infinity
else if result = - 1.0 then
result := NegInfinity
end
else
result := result / V;
end
else if Op = OP_IDIV then
result := result div V
else if Op = OP_MOD then
result := result mod V
else if Op = OP_SHL then
result := result shl V
else if Op = OP_SHR then
result := result shr V
else if Op = OP_AND then
result := result and V;
if CurrToken = '*' then
Op := OP_MULT
else if CurrToken = '/' then
Op := OP_DIV
else if StrEql(CurrToken, 'div') then
Op := OP_IDIV
else if StrEql(CurrToken, 'mod') then
Op := OP_MOD
else if StrEql(CurrToken, 'shl') then
Op := OP_SHL
else if StrEql(CurrToken, 'shr') then
Op := OP_SHL
else if StrEql(CurrToken, 'and') then
Op := OP_AND
else
Op := 0;
end;
end;
function TPascalExprParser.Parse_Factor: Variant;
var
I, J: Integer;
D: Double;
begin
{$IFDEF PAXARM}
if TokenClass = tcCharConst then
begin
result := Ord(CurrToken[1]);
Call_SCANNER;
end
else if TokenClass = tcNumCharConst then
begin
result := StrToInt(CurrToken);
Call_SCANNER;
end
else if TokenClass = tcPCharConst then
begin
result := CurrToken;
Call_SCANNER;
end
{$ELSE}
if TokenClass = tcCharConst then
begin
result := Ord(CurrToken[1]);
Call_SCANNER;
end
else if TokenClass = tcNumCharConst then
begin
result := StrToInt(CurrToken);
Call_SCANNER;
end
else if TokenClass = tcPCharConst then
begin
result := CurrToken;
Call_SCANNER;
end
{$ENDIF}
else if TokenClass = tcIntegerConst then
begin
val(CurrToken, i, j);
if j = 0 then begin
if Pos('$', CurrToken) > 0 then
begin
{$IFDEF VARIANTS}
result := Cardinal(i);
{$ELSE}
result := Integer(i);
{$ENDIF}
end
else
begin
result := i;
end;
end;
Call_SCANNER;
end
else if TokenClass = tcVariantConst then
begin
Call_SCANNER;
end
else if TokenClass = tcDoubleConst then
begin
Val(CurrToken, D, I);
result := D;
Call_SCANNER;
end
else if IsCurrText('nil') then
begin
result := 0;
Call_SCANNER;
end
else if IsCurrText('true') then
begin
result := true;
Call_SCANNER;
end
else if IsCurrText('false') then
begin
result := false;
Call_SCANNER;
end
else if IsCurrText('+') then
begin
Call_SCANNER;
result := Parse_Factor;
end
else if IsCurrText('-') then
begin
Call_SCANNER;
result := - Parse_Factor;
end
else if IsCurrText('not') then
begin
Call_SCANNER;
result := not Parse_Factor;
end
else if IsCurrText('low') then
begin
Call_SCANNER;
Match('(');
result := Lookup(CurrToken);
Call_SCANNER;
Match(')');
end
else if IsCurrText('high') then
begin
Call_SCANNER;
Match('(');
I := Lookup(CurrToken);
Call_SCANNER;
Match(')');
end
else if IsCurrText('SizeOf') then
begin
Call_SCANNER;
Match('(');
I := Lookup(CurrToken);
Call_SCANNER;
Match(')');
end
else if IsCurrText('pred') then
begin
Call_SCANNER;
Match('(');
result := Parse_Expression - 1;
Match(')');
end
else if IsCurrText('succ') then
begin
Call_SCANNER;
Match('(');
result := Parse_Expression + 1;
Match(')');
end
else if IsCurrText('ord') then
begin
Call_SCANNER;
Match('(');
result := Parse_Expression;
Match(')');
end
else if IsCurrText('chr') then
begin
Call_SCANNER;
Match('(');
result := Parse_Expression;
Match(')');
end
else if IsCurrText('(') then
begin
Match('(');
result := Parse_Expression;
Match(')');
end
else if IsCurrText('@') then
begin
Cancel;
end
else if IsCurrText('[') then
begin
result := Parse_SetConstructor;
end
else if IsCurrText('procedure') then
begin
Cancel;
end
else if IsCurrText('function') then
begin
Cancel;
end
else if IsCurrText('array') then
begin
Cancel;
end
else if IsCurrText('deprecated') then
begin
Cancel;
end
else if IsCurrText('pchar') then
begin
Cancel;
end
else if IsCurrText('[') then
begin
result := Parse_SetConstructor;
end
else
begin
result := LookUp(CurrToken);
Call_SCANNER;
while IsCurrText('.') do
begin
Match('.');
result := LookUp(CurrToken);
Call_SCANNER;
end;
if IsCurrText('(') then
begin
Match('(');
result := Parse_Expression;
Match(')');
end;
end;
end;
function TPascalExprParser.Parse_SetConstructor: Variant;
begin
Match('[');
if not IsCurrText(']') then
begin
repeat
Parse_Expression;
if IsCurrText('..') then
begin
Match('..');
Parse_Expression;
end;
If NotMatch(',') then
break;
until false;
end;
Match(']');
IsSet := true;
result := ResExpr;
end;
constructor TPascalParser.Create;
begin
inherited;
OuterList := TAssocStringInt.Create;
AddKeyword('and');
AddKeyword('array');
AddKeyword('as');
AddKeyword('asm');
AddKeyword('begin');
AddKeyword('case');
AddKeyword('class');
AddKeyword('const');
AddKeyword('constructor');
AddKeyword('destructor');
AddKeyword('dispinterface');
AddKeyword('div');
AddKeyword('do');
AddKeyword('downto');
AddKeyword('else');
AddKeyword('end');
AddKeyword('except');
AddKeyword('exports');
AddKeyword('external');
AddKeyword('file');
AddKeyword('finalization');
AddKeyword('finally');
AddKeyword('for');
AddKeyword('function');
AddKeyword('goto');
AddKeyword('if');
AddKeyword('implementation');
AddKeyword('in');
AddKeyword('inherited');
AddKeyword('initialization');
AddKeyword('inline');
AddKeyword('interface');
AddKeyword('is');
AddKeyword('label');
AddKeyword('library');
AddKeyword('mod');
AddKeyword('nil');
AddKeyword('not');
AddKeyword('object');
AddKeyword('of');
AddKeyword('on');
AddKeyword('or');
AddKeyword('out');
AddKeyword('packed');
I_STRICT := AddKeyword('strict');
I_PRIVATE := AddKeyword('private');
AddKeyword('procedure');
AddKeyword('program');
AddKeyword('property');
I_PROTECTED := AddKeyword('protected');
I_PUBLIC := AddKeyword('public');
I_PUBLISHED := AddKeyword('published');
AddKeyword('raise');
AddKeyword('record');
AddKeyword('repeat');
AddKeyword('resourcestring');
AddKeyword('set');
AddKeyword('shl');
AddKeyword('shr');
AddKeyword('string');
AddKeyword('then');
AddKeyword('threadvar');
AddKeyword('to');
AddKeyword('try');
AddKeyword('type');
AddKeyword('unit');
AddKeyword('until');
AddKeyword('uses');
AddKeyword('var');
AddKeyword('while');
AddKeyword('with');
AddKeyword('xor');
AddKeyword(EXTRA_KEYWORD);
AddOperator(pascal_Implicit, gen_Implicit);
AddOperator(pascal_Explicit, gen_Explicit);
AddOperator(pascal_Add, gen_Add);
AddOperator(pascal_Divide, gen_Divide);
AddOperator(pascal_IntDivide, gen_IntDivide);
AddOperator(pascal_Modulus, gen_Modulus);
AddOperator(pascal_Multiply, gen_Multiply);
AddOperator(pascal_Subtract, gen_Subtract);
AddOperator(pascal_Negative, gen_Negative);
AddOperator(pascal_Positive, gen_Positive);
AddOperator(pascal_LogicalNot, gen_LogicalNot);
AddOperator(pascal_LeftShift, gen_LeftShift);
AddOperator(pascal_RightShift, gen_RightShift);
AddOperator(pascal_LogicalAnd, gen_LogicalAnd);
AddOperator(pascal_LogicalOr, gen_LogicalOr);
AddOperator(pascal_LogicalXor, gen_LogicalXor);
AddOperator(pascal_LessThan, gen_LessThan);
AddOperator(pascal_LessThanOrEqual, gen_LessThanOrEqual);
AddOperator(pascal_GreaterThan, gen_GreaterThan);
AddOperator(pascal_GreaterThanOrEqual, gen_GreaterThanOrEqual);
AddOperator(pascal_Equal, gen_Equal);
AddOperator(pascal_NotEqual, gen_NotEqual);
AddOperator(pascal_Inc, gen_Inc);
AddOperator(pascal_Dec, gen_Dec);
end;
destructor TPascalParser.Destroy;
begin
FreeAndNil(OuterList);
inherited;
end;
function TPascalParser.CreateScanner: TBaseScanner;
begin
result := TPascalScanner.Create;
end;
function TPascalParser.GetLanguageName: String;
begin
result := 'Pascal';
end;
function TPascalParser.GetFileExt: String;
begin
result := 'pas';
end;
function TPascalParser.GetIncludedFileExt: String;
begin
result := 'pas';
end;
function TPascalParser.GetLanguageId: Integer;
begin
result := PASCAL_LANGUAGE;
end;
function TPascalParser.GetUpcase: Boolean;
begin
result := true;
end;
procedure TPascalParser.Init(i_kernel: Pointer; M: TModule);
begin
Inherited Init(i_kernel, M);
WasInherited := true;
ForInCounter := 0;
IMPLEMENTATION_SECTION := false;
OuterList.Clear;
end;
procedure TPascalParser.GenDefaultConstructor(ClassId: Integer);
var
SubId, ResId, L: Integer;
begin
GenComment('BEGIN OF DEFAULT CONSTRUCTOR OF ' + GetName(ClassId));
LevelStack.Push(ClassId);
SubId := NewTempVar;
SetName(SubId, 'Create');
BeginClassConstructor(SubId, ClassId);
SetVisibility(SubId, cvPublic);
inherited InitSub(SubId);
SetCallMode(SubId, cmOVERRIDE);
Gen(OP_ADD_MESSAGE, SubId, NewConst(typeINTEGER, -1000), 0);
Gen(OP_CHECK_OVERRIDE, SubId, 0, 0);
Gen(OP_SAVE_EDX, 0, 0, 0);
L := NewLabel;
Gen(OP_GO_DL, L, 0, 0);
Gen(OP_CREATE_OBJECT, ClassId, 0, CurrSelfId);
if GetSymbolRec(ClassId).IsAbstract then
Gen(OP_ERR_ABSTRACT, NewConst(typeSTRING,
GetFullName(ClassId)), 0, SubId);
SetLabelHere(L);
Gen(OP_BEGIN_WITH, CurrSelfId, 0, 0);
WithStack.Push(CurrSelfId);
NewTempVar;
ResId := NewTempVar;
Gen(OP_PUSH_CLASSREF, CurrSelfId, 0, ResId);
Gen(OP_EVAL_INHERITED, SubId, 0, ResId);
SetDefault(SubId, true);
Gen(OP_UPDATE_DEFAULT_CONSTRUCTOR, SubId, 0, ResId);
// will insertion here
Gen(OP_CALL_INHERITED, ResId, 0, 0);
Gen(OP_END_WITH, WithStack.Top, 0, 0);
WithStack.Pop;
Gen(OP_RESTORE_EDX, 0, 0, 0);
L := NewLabel;
Gen(OP_GO_DL, L, 0, 0);
Gen(OP_ONCREATE_OBJECT, CurrSelfId, 0, 0);
Gen(OP_ON_AFTER_OBJECT_CREATION, CurrSelfId, 0, 0);
SetLabelHere(L);
EndSub(SubId);
LevelStack.Pop;
GenComment('END OF DEFAULT CONSTRUCTOR OF ' + GetName(ClassId));
end;
procedure TPascalParser.GenDefaultDestructor(ClassId: Integer);
var
SubId, Id, ResId: Integer;
begin
GenComment('BEGIN OF DEFAULT DESTRUCTOR OF ' + GetName(ClassId));
LevelStack.Push(ClassId);
SubId := NewTempVar;
SetName(SubId, 'Destroy');
BeginClassDestructor(SubId, ClassId);
SetVisibility(SubId, cvPublic);
SetCallMode(SubId, cmOVERRIDE);
inherited InitSub(SubId);
Gen(OP_BEGIN_WITH, CurrSelfId, 0, 0);
WithStack.Push(CurrSelfId);
Id := NewTempVar;
ResId := NewTempVar;
SetName(Id, 'Destroy');
Gen(OP_EVAL, 0, 0, Id);
Gen(OP_EVAL_INHERITED, Id, 0, ResId);
Gen(OP_CALL, ResId, 0, 0);
Gen(OP_END_WITH, WithStack.Top, 0, 0);
WithStack.Pop;
EndSub(SubId);
LevelStack.Pop;
GenComment('END OF DEFAULT DESTRUCTOR OF ' + GetName(ClassId));
end;
procedure TPascalParser.Parse_DeclarationPart(IsImplementation: Boolean = false);
var
ok: Boolean;
begin
repeat
ok := false;
if IsCurrText('label') then
begin
Parse_LabelDeclaration;
ok := true;
end
else if IsCurrText('var') then
begin
Parse_VariableDeclaration;
ok := true;
end
else if IsCurrText('threadvar') then
begin
Parse_VariableDeclaration;
ok := true;
end
else if IsCurrText('const') then
begin
Parse_ConstantDeclaration;
ok := true;
end
else if IsCurrText('resourcestring') then
begin
Parse_ResourcestringDeclaration;
ok := true;
end
else if IsCurrText('procedure') then
begin
Parse_ProcedureDeclaration;
ok := true;
end
else if IsCurrText('function') then
begin
Parse_FunctionDeclaration;
ok := true;
end
else if IsCurrText('class') then
begin
Call_SCANNER;
if IsCurrText('procedure') then
Parse_ProcedureDeclaration(true)
else if IsCurrText('function') then
Parse_FunctionDeclaration(true)
else if IsCurrText('operator') then
Parse_OperatorDeclaration
else
Match('procedure');
ok := true;
end
else if IsCurrText('constructor') then
begin
Parse_ConstructorDeclaration;
ok := true;
end
else if IsCurrText('destructor') then
begin
Parse_DestructorDeclaration;
ok := true;
end
else if IsCurrText('type') then
begin
Parse_TypeDeclaration;
ok := true;
end
until not ok;
if GetKind(LevelStack.Top) in KindSUBS then
Exit;
end;
procedure TPascalParser.ParseProgram;
var
namespace_id: Integer;
begin
EXECUTABLE_SWITCH := 0;
Call_SCANNER;
if IsEOF then
Exit;
namespace_id := 0;
if IsCurrText('program') then
begin
DECLARE_SWITCH := true;
Call_SCANNER;
// SetKind(CurrToken.Id, KindNONE);
// Call_SCANNER;
namespace_id := Parse_Ident;
DECLARE_SWITCH := false;
Match(';');
end;
if IsCurrText('unit') then
Parse_Unit
else if IsCurrText('library') then
Parse_Library
else
Parse_ProgramBlock(namespace_id);
end;
procedure TPascalParser.Parse_Library;
var
id, I: Integer;
L: TAssocStringInt;
S: String;
begin
DECLARE_SWITCH := true;
Match('library');
Gen(OP_BEGIN_LIBRARY, Parse_Ident, 0, 0);
Match(';');
while IsCurrText('uses') do
begin
Parse_UsesClause(false);
end;
Gen(OP_END_IMPORT, 0, 0, 0);
repeat
if IsEOF then
Match('exports');
if IsCurrText('exports') then
break;
Parse_NamespaceMemberDeclaration;
until false;
DECLARE_SWITCH := false;
Gen(OP_BEGIN_EXPORT, 0, 0, 0);
Match('exports');
L := TAssocStringInt.Create;
try
repeat
S := CurrToken.Text;
id := Parse_Ident;
L.AddValue(S, id);
if IsCurrText(',') then
Call_SCANNER
else
break;
until false;
// L.Sort;
for I := 0 to L.Count - 1 do
begin
Id := L.Values[I];
Gen(OP_EXPORTS, id, 0, 0);
end;
finally
FreeAndNil(L);
end;
Match(';');
Parse_CompoundStmt;
MatchFinal('.');
end;
procedure TPascalParser.Parse_NamespaceDeclaration;
var
l: TIntegerList;
i, namespace_id: Integer;
begin
DECLARE_SWITCH := true;
RemoveLastIdent(CurrToken.Id);
Match('namespace');
l := TIntegerList.Create;
try
repeat // ParseQualifiedIdentifier
namespace_id := Parse_Ident;
l.Add(namespace_id);
BeginNamespace(namespace_id);
if NotMatch('.') then
break;
until false;
// Parse namespace body
repeat
if IsEOF then
Match('end');
if IsCurrText('end') then
break;
Parse_NamespaceMemberDeclaration;
until false;
for i := l.Count - 1 downto 0 do
begin
EndNamespace(l[i]);
Gen(OP_BEGIN_USING, l[i], 0, 0);
end;
finally
FreeAndNil(L);
end;
Match('end');
Match(';');
end;
procedure TPascalParser.Parse_UsesClause(IsImplementationSection: Boolean);
var
unit_id, id: Integer;
S: String;
AlreadyExists: Boolean;
RootKernel: TKernel;
begin
RootKernel := TKernel(Kernel).RootKernel;
UsedUnitList.Clear;
DECLARE_SWITCH := false;
Match('uses');
if Assigned(OnParseBeginUsedUnitList) then
OnParseBeginUsedUnitList(Owner);
repeat
unit_id := Parse_UnitName(S);
if Assigned(OnParseUsedUnitName) then
OnParseUsedUnitName(Owner, S, unit_id);
AlreadyExists := GetKind(unit_id) = kindNAMESPACE;
Gen(OP_BEGIN_USING, unit_id, 0, 0);
if IsCurrText('in') then
begin
Call_SCANNER;
id := Parse_PCharLiteral;
S := GetValue(id);
if (PosCh('\', S) > 0) or (PosCh('/', S) > 0) then
if not Assigned(RootKernel.OnUsedUnit) then
begin
if (Pos('.\', S) > 0) or (Pos('./', S) > 0) then
S := ExpandFileName(S)
else
S := GetCurrentDir + S;
end;
AlreadyExists := false;
end
else
S := S + '.' + GetFileExt;
if not AlreadyExists then
if not ImportOnly then
AddModuleFromFile(S, unit_id, IsImplementationSection);
if NotMatch(',') then
Break;
until false;
Match(';');
end;
procedure TPascalParser.Parse_NamespaceMemberDeclaration;
begin
if IsCurrText('type') then
Parse_TypeDeclaration
else if IsCurrText('procedure') then
Parse_ProcedureDeclaration
else if IsCurrText('function') then
Parse_FunctionDeclaration
else if IsCurrText('class') then
begin
Call_SCANNER;
if IsCurrText('procedure') then
Parse_ProcedureDeclaration(true)
else if IsCurrText('function') then
Parse_FunctionDeclaration(true)
else if IsCurrText('operator') then
Parse_OperatorDeclaration
else
Match('procedure');
end
else if IsCurrText('var') then
Parse_VariableDeclaration
else if IsCurrText('const') then
Parse_ConstantDeclaration
else if IsCurrText('resourcestring') then
Parse_ResourcestringDeclaration
else
Match('end');
end;
function TPascalParser.Parse_Statement: Boolean;
begin
result := false;
if CurrToken.TokenClass = tcIdentifier then
if GetKind(CurrToken.Id) = KindLABEL then
if GetName(CurrToken.Id) <> '' then
begin
SetLabelHere(CurrToken.Id);
Call_SCANNER;
Match(':');
end;
Gen(OP_STMT, 0, 0, 0);
if IsCurrText('begin') then
begin
Parse_CompoundStmt;
result := true;
end
else if IsCurrText('case') then
Parse_CaseStmt
else if IsCurrText('if') then
Parse_IfStmt
else if IsCurrText('goto') then
Parse_GotoStmt
else if IsCurrText('while') then
Parse_WhileStmt
else if IsCurrText('repeat') then
Parse_RepeatStmt
else if IsCurrText('for') then
Parse_ForStmt
else if IsCurrText('break') then
begin
if (BreakStack.Count = 0) or (Lookups('break', LevelStack) > 0) then
Parse_AssignmentStmt
else
begin
RemoveLastEvalInstructionAndName('break');
Parse_BreakStmt;
end;
end
else if IsCurrText('continue') then
begin
if (ContinueStack.Count = 0) or (Lookups('continue', LevelStack) > 0) then
Parse_AssignmentStmt
else
begin
RemoveLastEvalInstructionAndName('continue');
Parse_ContinueStmt;
end;
end
else if IsCurrText('exit') then
begin
if Lookups('exit', LevelStack) > 0 then
Parse_AssignmentStmt
else
begin
RemoveLastEvalInstructionAndName('exit');
Parse_ExitStmt;
end;
end
else if IsCurrText('with') then
Parse_WithStmt
else if IsCurrText('try') then
Parse_TryStmt
else if IsCurrText('raise') then
Parse_RaiseStmt
else
begin
if IsCurrText(PrintKeyword) then
begin
if (CurrToken.Id > StdCard) and (GetKind(CurrToken.Id) = kindSUB) then
Parse_AssignmentStmt
else
begin
Call_SCANNER;
Parse_Print;
end;
end
else if IsCurrText(PrintlnKeyword) then
begin
if (CurrToken.Id > StdCard) and (GetKind(CurrToken.Id) = kindSUB) then
Parse_AssignmentStmt
else
begin
Call_SCANNER;
Parse_Println;
end;
end
else if IsCurrText('write') then
begin
Call_SCANNER;
Parse_Write;
end
else if IsCurrText('writeln') then
begin
Call_SCANNER;
Parse_Writeln;
end
else
Parse_AssignmentStmt;
end;
Gen(OP_STMT, 0, 0, 0);
end;
procedure TPascalParser.Parse_Write;
var
ID, ID_L1, ID_L2: Integer;
begin
IsConsoleApp := true;
Match('(');
repeat
ID := Parse_Expression;
ID_L1 := 0;
ID_L2 := 0;
if IsCurrText(':') then
begin
Call_SCANNER;
ID_L1 := Parse_Expression;
end;
if IsCurrText(':') then
begin
Call_SCANNER;
ID_L2 := Parse_Expression;
end;
Gen(OP_PRINT, ID, ID_L1, ID_L2);
if NotMatch(',') then
Break;
until false;
Match(')');
end;
procedure TPascalParser.Parse_Writeln;
begin
IsConsoleApp := true;
if IsCurrText('(') then
Parse_Write;
Gen(OP_PRINT, 0, 0, 0);
end;
procedure TPascalParser.Parse_Print;
var
ID, ID_L1, ID_L2: Integer;
begin
if IsCurrText(';') then
begin
Exit;
end;
repeat
ID := Parse_Expression;
ID_L1 := 0;
ID_L2 := 0;
if IsCurrText(':') then
begin
Call_SCANNER;
ID_L1 := Parse_Expression;
end;
if IsCurrText(':') then
begin
Call_SCANNER;
ID_L2 := Parse_Expression;
end;
Gen(OP_PRINT_EX, ID, ID_L1, ID_L2);
if NotMatch(',') then
Break;
until false;
end;
procedure TPascalParser.Parse_Println;
begin
if not IsCurrText(';') then
Parse_Print;
{$IFDEF PAXARM}
Gen(OP_PRINT_EX, NewConst(typeUNICSTRING, #13#10), 0, 0);
{$ELSE}
Gen(OP_PRINT_EX, NewConst(typeANSISTRING, #13#10), 0, 0);
{$ENDIF}
end;
procedure TPascalParser.Parse_Block;
begin
DECLARE_SWITCH := true;
Parse_DeclarationPart;
Parse_CompoundStmt;
end;
procedure TPascalParser.Parse_ProgramBlock(namespace_id: Integer);
var
B1, B2: Integer;
begin
{$IFDEF ZERO_NS}
namespace_id := 0;
{$ENDIF}
while IsCurrText('uses') do
Parse_UsesClause(false);
Gen(OP_END_IMPORT, 0, 0, 0);
B1 := CodeCard;
if namespace_id > 0 then
begin
BeginNamespace(namespace_id, false);
end;
while IsCurrText('namespace') do
Parse_NamespaceDeclaration;
// parse block
DECLARE_SWITCH := true;
Parse_DeclarationPart;
Gen(OP_END_INTERFACE_SECTION, CurrModule.ModuleNumber, 0, 0);
Gen(OP_BEGIN_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
{$IFDEF HTML}
Inc(EXECUTABLE_SWITCH);
DECLARE_SWITCH := false;
Parse_StmtList;
Dec(EXECUTABLE_SWITCH);
{$ELSE}
Parse_CompoundStmt;
{$ENDIF}
B2 := CodeCard;
Gen(OP_EPILOGUE_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_EPILOGUE_GLOBAL_BLOCK2, 0, 0, 0);
GenDestroyGlobalDynamicVariables(B1, B2);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_END_GLOBAL_BLOCK, 0, 0, 0);
if IsCurrText('.') then
begin
// ok
end
else
begin
{$IFDEF HTML}
// ok
CALL_SCANNER;
{$ELSE}
MatchFinal('.');
{$ENDIF}
end;
if namespace_id > 0 then
EndNamespace(namespace_id, false);
end;
procedure TPascalParser.ParseExternalSub(SubId: Integer);
var
SubNameId, LibId, L, I: Integer;
S: String;
b: Boolean;
label
LabName;
begin
ReplaceForwardDeclaration(SubId);
SetExternal(SubId, true);
S := GetName(SubId);
L := GetLevel(SubId);
if L > 0 then
if GetKind(L) = KindTYPE then
begin
b := false;
for I := 0 to OuterList.Count - 1 do
if OuterList.Values[I] = L then
begin
S := ExtractFullName(OuterList.Keys[I]) + '.' + GetName(L) + '.' + S;
b := true;
break;
end;
if not b then
S := GetName(L) + '.' + S;
end;
SubNameId := NewConst(typeSTRING, S);
ReadToken; // skip external
EndSub(SubId);
if ImportOnly then
begin
if IsCurrText(';') then
begin
Call_SCANNER;
Exit;
end;
end;
if CurrToken.TokenClass = tcPCharConst then
begin
S := RemoveCh('''', CurrToken.Text);
LibId := NewConst(typeSTRING, S);
end
else
begin
LibId := Lookup(CurrToken.Text, CurrLevel);
if (LibId = 0) or (not IsStringConst(LibId)) then
LibId := Lookup(S, CurrLevel);
if not ImportOnly then
begin
if LibId = 0 then
RaiseError(errUndeclaredIdentifier, [S]);
if not IsStringConst(LibId) then
RaiseError(errIncompatibleTypesNoArgs, []);
end;
end;
if ImportOnly then
if IsCurrText('name') then
goto LabName;
ReadToken;
RemoveSub;
if IsCurrText(';') then
begin
Gen(OP_LOAD_PROC, SubId, SubNameId, LibId);
Match(';');
end
else
begin
if IsCurrText('delayed') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
Match(';');
Exit;
end;
LabName:
Match('name');
SubNameId := CurrToken.Id;
Gen(OP_LOAD_PROC, SubId, SubNameId, LibId);
if ImportOnly then
Parse_ConstantExpression
else
Call_SCANNER;
if IsCurrText('delayed') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
end;
Match(';');
end;
end;
procedure TPascalParser.GenExternalSub(SubId: Integer);
var
SubNameId, LibId, namespace_id: Integer;
S, TypeName: String;
begin
namespace_id := GetLevel(SubId);
if GetKind(namespace_id) = kindTYPE then
TypeName := GetName(namespace_id)
else
TypeName := '';
while GetKind(namespace_id) <> kindNAMESPACE do
namespace_id := GetLevel(namespace_id);
SetForward(SubId, false);
SetExternal(SubId, true);
ReplaceForwardDeclaration(SubId, true);
S := GetName(SubId);
if TypeName <> '' then
S := TypeName + '.' + S;
SubNameId := NewConst(typeSTRING, S);
EndSub(SubId);
RemoveSub;
LibId := NewConst(typeSTRING,
GetName(namespace_id) + '.' + PCU_FILE_EXT);
Gen(OP_LOAD_PROC, SubId, SubNameId, LibId);
end;
procedure TPascalParser.Parse_Unit(IsExternalUnit: Boolean = false);
var
B1, B2: Integer;
procedure Parse_InterfaceSection;
procedure Parse_ProcedureHeading;
var
SubId: Integer;
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
Match('procedure');
SubId := Parse_Ident;
BeginSub(SubId);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(SubId), SubId);
try
Parse_FormalParameterList(SubId);
SetName(CurrResultId, '');
SetKind(CurrResultId, KindNONE);
SetType(SubId, TypeVOID);
SetType(CurrResultId, TypeVOID);
if InterfaceOnly then
begin
if IsCurrText(';') then
Match(';');
end
else
Match(';');
DirectiveList := Parse_DirectiveList(SubId);
FreeAndNil(DirectiveList);
if IsCurrText('external') then
begin
ParseExternalSub(SubId);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(SubId);
Exit;
end;
SetForward(SubId, true);
EndSub(SubId);
finally
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
OnParseEndSubDeclaration(Owner, GetName(SubId), SubId, Declaration);
end;
end;
end;
procedure Parse_FunctionHeading;
var
SubId, TypeId: Integer;
DirectiveList: TIntegerList;
Declaration, StrType: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
Match('function');
SubId := Parse_Ident;
BeginSub(SubId);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(SubId), SubId);
try
Parse_FormalParameterList(SubId);
DECLARE_SWITCH := false;
StrType := '';
TypeId := 0;
if ImportOnly then
begin
if IsCurrText(':') then
begin
Match(':');
Parse_Attribute;
DECLARE_SWITCH := true;
TypeID := Parse_Type;
StrType := GetName(TypeId);
Gen(OP_ASSIGN_TYPE, SubId, TypeID, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, TypeID, 0);
end;
end
else
begin
Match(':');
Parse_Attribute;
DECLARE_SWITCH := true;
TypeID := Parse_Type;
StrType := GetName(TypeId);
Gen(OP_ASSIGN_TYPE, SubId, TypeID, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, TypeID, 0);
end;
if Assigned(OnParseResultType) then
OnParseResultType(Owner, StrType, TypeId);
DECLARE_SWITCH := true;
if InterfaceOnly then
begin
if IsCurrText(';') then
Match(';');
end
else
Match(';');
DirectiveList := Parse_DirectiveList(SubId);
FreeAndNil(DirectiveList);
if IsCurrText('external') then
begin
ParseExternalSub(SubId);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(SubId);
Exit;
end;
SetForward(SubId, true);
EndSub(SubId);
finally
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
if Assigned(OnParseEndSubDeclaration) then
OnParseEndSubDeclaration(Owner, GetName(SubId), SubId, Declaration);
end;
end;
var
ok: Boolean;
begin
Match('interface');
while IsCurrText('uses') do
Parse_UsesClause(false);
if Assigned(OnParseEndUsedUnitList) then
OnParseEndUsedUnitList(Owner);
Gen(OP_END_IMPORT, 0, 0, 0);
B1 := CodeCard;
repeat
ok := false;
if IsCurrText('var') then
begin
Parse_VariableDeclaration;
ok := true;
end
else if IsCurrText('threadvar') then
begin
Parse_VariableDeclaration;
ok := true;
end
else if IsCurrText('const') then
begin
Parse_ConstantDeclaration;
ok := true;
end
else if IsCurrText('resourcestring') then
begin
Parse_ResourcestringDeclaration;
ok := true;
end
else if IsCurrText('procedure') then
begin
Parse_ProcedureHeading;
ok := true;
end
else if IsCurrText('function') then
begin
Parse_FunctionHeading;
ok := true;
end
else if IsCurrText('type') then
begin
Parse_TypeDeclaration(IsExternalUnit);
ok := true;
end
until not ok;
end; // interface section
procedure Parse_ImplementationSection;
var
I, InnerTypeId, OuterTypeId: Integer;
S, OldFullName: String;
R: TPaxClassFactoryRec;
begin
for I := 0 to OuterList.Count - 1 do
begin
S := OuterList.Keys[I];
InnerTypeId := OuterList.Values[I];
OuterTypeId := TKernel(kernel).SymbolTable.LookupFullName(S, true);
if OuterTypeId = 0 then
RaiseError(errUndeclaredIdentifier, [S]);
OldFullName := GetFullName(InnerTypeId);
R := TKernel(kernel).ClassFactory.FindRecordByFullName(OldFullName);
if R = nil then
RaiseError(errInternalError, [S]);
R.FullClassName := S + '.' + GetName(InnerTypeId);
SetLevel(InnerTypeId, OuterTypeId);
end;
IMPLEMENTATION_SECTION := true;
Match('implementation');
while IsCurrText('uses') do
Parse_UsesClause(true);
Parse_DeclarationPart(true);
end;
procedure Parse_InitSection;
begin
DECLARE_SWITCH := false;
if IsCurrText('initialization') then
begin
BeginInitialization;
Gen(OP_BEGIN_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Call_SCANNER;
Parse_StmtList;
Gen(OP_EPILOGUE_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_EPILOGUE_GLOBAL_BLOCK2, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_END_GLOBAL_BLOCK, 0, 0, 0);
EndInitialization;
if IsCurrText('finalization') then
begin
BeginFinalization;
Gen(OP_BEGIN_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Call_SCANNER;
Parse_StmtList;
B2 := CodeCard;
Gen(OP_EPILOGUE_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_EPILOGUE_GLOBAL_BLOCK2, 0, 0, 0);
GenDestroyGlobalDynamicVariables(B1, B2);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_END_GLOBAL_BLOCK, 0, 0, 0);
EndFinalization;
end
else
begin
BeginFinalization;
Gen(OP_BEGIN_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
B2 := CodeCard;
Gen(OP_EPILOGUE_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_EPILOGUE_GLOBAL_BLOCK2, 0, 0, 0);
GenDestroyGlobalDynamicVariables(B1, B2);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_END_GLOBAL_BLOCK, 0, 0, 0);
EndFinalization;
end;
Match('end');
end
else if IsCurrText('begin') then
begin
BeginInitialization;
Gen(OP_BEGIN_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Call_SCANNER;
Parse_StmtList;
Gen(OP_EPILOGUE_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_EPILOGUE_GLOBAL_BLOCK2, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_END_GLOBAL_BLOCK, 0, 0, 0);
EndInitialization;
Match('end');
BeginFinalization;
Gen(OP_BEGIN_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
B2 := CodeCard;
Gen(OP_EPILOGUE_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_EPILOGUE_GLOBAL_BLOCK2, 0, 0, 0);
GenDestroyGlobalDynamicVariables(B1, B2);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_END_GLOBAL_BLOCK, 0, 0, 0);
EndFinalization;
end
else if IsCurrText('finalization') then
begin
BeginFinalization;
Gen(OP_BEGIN_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Call_SCANNER;
Parse_StmtList;
B2 := CodeCard;
Gen(OP_EPILOGUE_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_EPILOGUE_GLOBAL_BLOCK2, 0, 0, 0);
GenDestroyGlobalDynamicVariables(B1, B2);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_END_GLOBAL_BLOCK, 0, 0, 0);
EndFinalization;
Match('end');
end
else if IsCurrText('end') then
begin
BeginFinalization;
Gen(OP_BEGIN_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Call_SCANNER;
B2 := CodeCard;
Gen(OP_EPILOGUE_GLOBAL_BLOCK, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_EPILOGUE_GLOBAL_BLOCK2, 0, 0, 0);
GenDestroyGlobalDynamicVariables(B1, B2);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_NOP, 0, 0, 0);
Gen(OP_END_GLOBAL_BLOCK, 0, 0, 0);
EndFinalization;
end
else
Match('end');
end;
var
namespace_name: String;
namespace_id: Integer;
begin
DECLARE_SWITCH := true;
Match('unit');
namespace_id := Parse_UnitName(namespace_name);
if Assigned(OnParseUnitName) then
OnParseUnitName(Owner, namespace_name, namespace_id);
if CurrModule.IsExtra then
SaveExtraNamespace(namespace_id);
Parse_PortabilityDirective;
Match(';');
Parse_InterfaceSection;
if IsExternalUnit then
begin
Match('implementation');
Exit;
end;
Gen(OP_END_INTERFACE_SECTION, CurrModule.ModuleNumber, 0, 0);
if InterfaceOnly then
begin
if Assigned(OnParseImplementationSection) then
OnParseImplementationSection(Owner);
if ImportOnly then
Exit;
Match('implementation');
while not scanner.IsEOF do
ReadToken;
EndNamespace(namespace_id);
end
else
begin
Parse_ImplementationSection;
Inc(EXECUTABLE_SWITCH);
Parse_InitSection;
Dec(EXECUTABLE_SWITCH);
EndNamespace(namespace_id);
MatchFinal('.');
end;
end;
procedure TPascalParser.Parse_VariableDeclaration(vis: TClassVisibility = cvNone);
var
L: TIntegerList;
I, ID, TypeID, ExprID: Integer;
S, Declaration: String;
VarNameId, LibId: Integer;
begin
L := TIntegerList.Create;
try
if InterfaceOnly then
Gen(OP_BEGIN_VAR, 0, 0, 0);
DECLARE_SWITCH := true;
if IsCurrText('threadvar') then
Call_SCANNER
else
Match('var');
repeat
Parse_Attribute;
L.Clear;
repeat
ID := Parse_Ident;
SetVisibility(ID, vis);
Gen(OP_DECLARE_LOCAL_VAR, CurrLevel, ID, 0);
L.Add(ID);
if NotMatch(',') then break;
until false;
DECLARE_SWITCH := false;
if EXPLICIT_OFF then
begin
TypeId := 0;
if IsCurrText(';') then
begin
//ok
end
else
begin
Match(':');
TypeID := Parse_Type;
end;
end
else
begin
Match(':');
TypeID := Parse_Type;
end;
for I:=0 to L.Count - 1 do
Gen(OP_ASSIGN_TYPE, L[I], TypeID, 0);
S := '';
if IsCurrText('absolute') then
begin
RemoveLastIdent(CurrToken.Id);
DECLARE_SWITCH := false;
Call_SCANNER;
ExprId := Parse_Ident;
for I:=0 to L.Count - 1 do
Gen(OP_ABSOLUTE, L[I], ExprID, 0);
end
else if IsCurrText('=') then
begin
if GetKind(CurrLevel) = KindSUB then
CreateError(errCannotInitializeLocalVariables, []);
DECLARE_SWITCH := false;
Match('=');
Id := L[0];
BeginInitConst(Id);
ExprID := Parse_VariableInitialization;
S := ExtractText(PrevPosition, PrevPosition + PrevLength - 1);
for I:=0 to L.Count - 1 do
Gen(OP_ASSIGN, L[I], ExprID, L[I]);
EndInitConst(Id);
end;
Parse_PortabilityDirective;
if Assigned(OnParseVariableDeclaration) then
for I:=0 to L.Count - 1 do
begin
if S = '' then
Declaration := GetName(L[I]) + ':' + GetName(TypeID) + ';'
else
Declaration := GetName(L[I]) + ':' + GetName(TypeID) + '=' + ';';
OnParseVariableDeclaration(Owner, GetName(L[I]), L[I], GetName(TypeID),
Declaration);
end;
DECLARE_SWITCH := true;
if not MatchEx(';') then
break;
if IsCurrText('external') then
begin
SetExternal(Id, true);
S := GetName(Id);
VarNameId := NewConst(typeSTRING, S);
ReadToken; // skip external
if CurrToken.TokenClass = tcPCharConst then
begin
S := RemoveCh('''', CurrToken.Text);
LibId := NewConst(typeSTRING, S);
end
else
begin
LibId := Lookup(S, CurrLevel);
if LibId = 0 then
RaiseError(errUndeclaredIdentifier, [S]);
if not IsStringConst(LibId) then
RaiseError(errIncompatibleTypesNoArgs, []);
end;
ReadToken;
Gen(OP_LOAD_PROC, Id, VarNameId, LibId);
Match(';');
Exit;
end;
until CurrToken.TokenClass <> tcIdentifier;
finally
if InterfaceOnly then
Gen(OP_END_VAR, 0, 0, 0);
FreeAndNil(L);
end;
end;
procedure TPascalParser.Parse_ConstantDeclaration(vis: TClassVisibility = cvNone);
var
ID: Integer;
S: String;
VarNameId, LibId, ConstId, TypeId: Integer;
Declaration: String;
SavedPosition: Integer;
IsBuildingPCU: Boolean;
begin
IsBuildingPCU := BuildingAll;
Gen(OP_EMIT_OFF, 0, 0, 0);
try
DECLARE_SWITCH := true;
Match('const');
repeat
Parse_Attribute;
SavedPosition := CurrToken.Position;
ID := Parse_Ident;
SetVisibility(Id, vis);
if InterfaceOnly then
Gen(OP_BEGIN_CONST, Id, 0, 0);
Gen(OP_DECLARE_LOCAL_VAR, CurrLevel, ID, 0);
SetKind(ID, kindCONST);
DECLARE_SWITCH := false;
if IsCurrText(':') then
begin
Match(':');
TypeId := Parse_Type;
Gen(OP_ASSIGN_TYPE, ID, TypeId, 0);
if not ImportOnly then
levelStack.Push(CurrNamespaceId);
Match('=');
Parse_ConstantInitialization(ID);
if Assigned(OnParseTypedConstantDeclaration) then
begin
Declaration := ExtractText(SavedPosition,
CurrToken.Position + CurrToken.Length - 1);
OnParseTypedConstantDeclaration(Owner,
GetName(ID), ID, GetName(TypeId), GetValue(ID), Declaration);
end;
if not ImportOnly then
levelStack.Pop;
end
else
begin
if not ImportOnly then
levelStack.Push(CurrNamespaceId);
Match('=');
if IsBuildingPCU or IsCurrText('[') then
begin
Parse_ConstantInitialization(ID);
ConstId := Id;
end
else
begin
ConstId := Parse_ConstantExpression;
if TKernel(kernel).SignCodeCompletion then
SetType(ID, GetSymbolRec(ConstId).TypeID);
Gen(OP_ASSIGN_CONST, ID, ConstId, ID);
end;
if Assigned(OnParseConstantDeclaration) then
begin
Declaration := ExtractText(SavedPosition,
CurrToken.Position + CurrToken.Length - 1);
OnParseConstantDeclaration(Owner, GetName(ID), ID, GetValue(ConstID), Declaration);
end;
if not ImportOnly then
levelStack.Pop;
end;
DECLARE_SWITCH := true;
if InterfaceOnly then
Gen(OP_END_CONST, Id, 0, 0);
Parse_PortabilityDirective;
if not MatchEx(';') then
break;
if IsCurrText('external') then
begin
S := GetName(Id);
VarNameId := NewConst(typeSTRING, S);
ReadToken; // skip external
if CurrToken.TokenClass = tcPCharConst then
begin
S := RemoveCh('''', CurrToken.Text);
LibId := NewConst(typeSTRING, S);
end
else
begin
LibId := Lookup(S, CurrLevel);
if LibId = 0 then
RaiseError(errUndeclaredIdentifier, [S]);
if not IsStringConst(LibId) then
RaiseError(errIncompatibleTypesNoArgs, []);
end;
ReadToken;
Gen(OP_LOAD_PROC, Id, VarNameId, LibId);
Match(';');
Exit;
end;
until CurrToken.TokenClass <> tcIdentifier;
finally
Gen(OP_EMIT_ON, 0, 0, 0);
end;
end;
procedure TPascalParser.Parse_ResourcestringDeclaration;
var
ID: Integer;
Value: Variant;
Declaration: String;
IsBuildingPCU: Boolean;
begin
IsBuildingPCU := BuildingAll;
Gen(OP_EMIT_OFF, 0, 0, 0);
try
DECLARE_SWITCH := true;
Match('resourcestring');
repeat
ID := Parse_Ident;
Gen(OP_DECLARE_LOCAL_VAR, CurrLevel, ID, 0);
SetKind(ID, kindCONST);
DECLARE_SWITCH := false;
Match('=');
if IsBuildingPCU then
Parse_ConstantInitialization(ID)
else
Gen(OP_ASSIGN_CONST, ID, Parse_ConstantExpression, ID);
if Assigned(OnParseConstantDeclaration) then
begin
Value := GetValue(Id);
if not VariantIsString(Value) then
Value := String(Chr(Integer(Value)));
Declaration := GetName(Id) + ' = ' + Value;
OnParseResourceStringDeclaration(Owner, GetName(ID), ID, Value, Declaration);
end;
Parse_PortabilityDirective;
DECLARE_SWITCH := true;
if not MatchEx(';') then
break;
until CurrToken.TokenClass <> tcIdentifier;
finally
Gen(OP_EMIT_ON, 0, 0, 0);
end;
end;
procedure TPascalParser.Parse_ConstantInitialization(ID: Integer);
var
ExprId, ItemId, NameId, K, ConstId: Integer;
begin
BeginInitConst(Id);
if IsCurrText('(') then
begin
K := -1;
Call_SCANNER;
repeat
if IsCurrText(')') then
break;
Inc(K);
if IsCurrText('(') then
begin
ExprId := NewTempVar();
SetLevel(ExprId, 0);
Parse_ConstantInitialization(ExprId);
Gen(OP_ASSIGN_SHIFT, 0, K, ExprId);
if NotMatch(',') then
break;
end
else
begin
ItemId := NewTempVar();
SetLevel(ItemId, 0);
if IsNextText(':') then
begin
SetName(CurrToken.Id, '');
SetKind(CurrToken.Id, KindNONE);
NameId := NewConst(typeSTRING, CurrToken.Text);
SetKind(NameId, kindNONE);
Call_SCANNER;
Match(':');
if IsCurrText('(') then
begin
ExprId := NewTempVar();
SetLevel(ExprId, 0);
Parse_ConstantInitialization(ExprId);
Gen(OP_ASSIGN_SHIFT, 0, K, ExprId);
end
else
begin
ExprId := Parse_ConstantExpression;
Gen(OP_RECORD_ITEM, ID, NameId, ItemId);
Gen(OP_ASSIGN, ItemId, ExprId, ItemId);
end;
if NotMatch(';') then
break;
end
else
begin
ExprId := Parse_ConstantExpression;
Gen(OP_ITEM, ID, K, ItemId);
Gen(OP_ASSIGN, ItemId, ExprId, ItemId);
if NotMatch(',') then
break;
end;
end;
until false;
Match(')');
end
else
begin
ConstId := Parse_ConstantExpression;
Gen(OP_ASSIGN, ID, ConstId, ID);
SetValue(Id, GetValue(ConstId));
end;
EndInitConst(Id);
end;
function TPascalParser.Parse_VariableInitialization: Integer;
var
ExprId, ItemId, NameId, K: Integer;
begin
if IsCurrText('(') then
begin
result := NewTempVar;
K := -1;
Call_SCANNER;
repeat
if IsCurrText(')') then
break;
Inc(K);
if IsCurrText('(') then
begin
ExprId := NewTempVar();
SetLevel(ExprId, 0);
Gen(OP_ASSIGN, ExprId, Parse_VariableInitialization, ExprId);
Gen(OP_ASSIGN_SHIFT, 0, K, ExprId);
if NotMatch(',') then
break;
end
else
begin
ItemId := NewTempVar();
SetLevel(ItemId, 0);
if IsNextText(':') then
begin
SetName(CurrToken.Id, '');
SetKind(CurrToken.Id, KindNONE);
NameId := NewConst(typeSTRING, CurrToken.Text);
SetKind(NameId, kindNONE);
Call_SCANNER;
Match(':');
if IsCurrText('(') then
begin
ExprId := NewTempVar();
SetLevel(ExprId, 0);
Gen(OP_ASSIGN, ExprId, Parse_VariableInitialization, ExprId);
Gen(OP_ASSIGN_SHIFT, 0, K, ExprId);
end
else
begin
ExprId := Parse_Expression;
Gen(OP_RECORD_ITEM, result, NameId, ItemId);
Gen(OP_ASSIGN, ItemId, ExprId, ItemId);
end;
if NotMatch(';') then
break;
end
else
begin
ExprId := Parse_Expression;
Gen(OP_ITEM, result, K, ItemId);
Gen(OP_ASSIGN, ItemId, ExprId, ItemId);
if NotMatch(',') then
break;
end;
end;
until false;
Match(')');
end
else
result := Parse_Expression;
end;
procedure TPascalParser.Parse_LabelDeclaration;
begin
DECLARE_SWITCH := true;
Match('label');
repeat
Parse_Label;
if NotMatch(',') then break;
until false;
Match(';');
end;
procedure TPascalParser.Parse_TypeDeclaration(IsExternalUnit: Boolean = false;
vis: TClassVisibility = cvPublic);
var
ok: Boolean;
TypeID, T, SubId, TypeBaseId: Integer;
IsPacked: Boolean;
S, Q: String;
begin
TypeParams.Clear;
DECLARE_SWITCH := true;
Match('type');
repeat
Parse_Attribute;
BeginTypeDef(CurrToken.Id);
TypeId := Parse_Ident;
SetVisibility(TypeId, vis);
SetKind(TypeId, KindTYPE);
SetLevel(TypeId, CurrLevel);
if Assigned(OnParseTypeDeclaration) then
OnParseTypeDeclaration(Owner, GetName(TypeId), TypeId);
S := GetFullName(TypeId);
while IsCurrText('.') do
begin
SetKind(TypeId, KindNONE);
SetName(TypeId, '');
Call_SCANNER;
TypeId := Parse_Ident;
S := S + '.' + GetName(TypeId);
end;
if S <> GetFullName(TypeId) then
begin
S := ExtractFullOwner(S);
OuterList.AddValue(S, TypeId);
end;
SetKind(TypeID, KindTYPE);
if InterfaceOnly then
Gen(OP_BEGIN_TYPE, TypeId, 0, 0);
DECLARE_SWITCH := false;
Match('=');
ok := false;
if IsCurrText('packed') then
begin
Match('packed');
IsPacked := true;
end
else
IsPacked := false;
if IsCurrText('array') then
begin
IsPacked := true;
Parse_ArrayTypeDeclaration(TypeID, IsPacked);
Parse_PortabilityDirective;
EndTypeDef(TypeId);
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else if IsCurrText('record') then
begin
DECLARE_SWITCH := true;
Parse_RecordTypeDeclaration(TypeID, IsPacked);
Parse_PortabilityDirective;
EndTypeDef(TypeId);
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else if IsCurrText('class') then
begin
IsPacked := true;
DECLARE_SWITCH := true;
Parse_ClassTypeDeclaration(TypeID, IsPacked, IsExternalUnit);
Parse_PortabilityDirective;
EndTypeDef(TypeId);
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else if IsCurrText('interface') then
begin
DECLARE_SWITCH := true;
Parse_InterfaceTypeDeclaration(TypeID);
Parse_PortabilityDirective;
EndTypeDef(TypeId);
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else if IsCurrText('dispinterface') then
begin
if not ImportOnly then
RaiseNotImpl;
DECLARE_SWITCH := true;
Parse_InterfaceTypeDeclaration(TypeID);
Parse_PortabilityDirective;
EndTypeDef(TypeId);
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else if IsCurrText('reference') then
begin
RemoveLastIdent(CurrToken.Id);
DECLARE_SWITCH := true;
Call_SCANNER;
Match('to');
Parse_MethodRefTypeDeclaration(TypeID);
Parse_PortabilityDirective;
DECLARE_SWITCH := true;
ok := true;
end
else if IsCurrText('^') then
begin
if IsPacked then
CreateError(errPACKEDNotAllowedHere, []);
if TypeParams.Count > 0 then
RaiseError(errTypeParameterNotAllowed, []);
Parse_PointerTypeDeclaration(TypeID);
Parse_PortabilityDirective;
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else if IsCurrText('(') then
begin
if IsPacked then
CreateError(errPACKEDNotAllowedHere, []);
if TypeParams.Count > 0 then
RaiseError(errTypeParameterNotAllowed, []);
DECLARE_SWITCH := true;
Parse_EnumTypeDeclaration(TypeID);
Parse_PortabilityDirective;
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else if IsCurrText('procedure') or IsCurrText('function') then
begin
if IsPacked then
CreateError(errPACKEDNotAllowedHere, []);
DECLARE_SWITCH := true;
Parse_ProceduralTypeDeclaration(TypeID, SubId);
EndTypeDef(TypeId);
DECLARE_SWITCH := true;
if InterfaceOnly then
begin
if IsCurrText(';') then
ok := MatchEx(';');
end
else
ok := MatchEx(';');
end
else if IsCurrText('set') then
begin
if IsPacked then
CreateError(errPACKEDNotAllowedHere, []);
if TypeParams.Count > 0 then
RaiseError(errTypeParameterNotAllowed, []);
DECLARE_SWITCH := true;
Parse_SetTypeDeclaration(TypeID);
Parse_PortabilityDirective;
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else if CurrToken.TokenClass = tcIntegerConst then
begin
if IsPacked then
CreateError(errPACKEDNotAllowedHere, []);
if TypeParams.Count > 0 then
RaiseError(errTypeParameterNotAllowed, []);
Parse_SubrangeTypeDeclaration(TypeID, typeINTEGER, Q, 0);
Parse_PortabilityDirective;
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else if CurrToken.TokenClass = tcCharConst then
begin
if IsPacked then
CreateError(errPACKEDNotAllowedHere, []);
if TypeParams.Count > 0 then
RaiseError(errTypeParameterNotAllowed, []);
Parse_SubrangeTypeDeclaration(TypeID, typeCHAR, Q, 0);
Parse_PortabilityDirective;
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else if CurrToken.TokenClass = tcBooleanConst then
begin
if IsPacked then
CreateError(errPACKEDNotAllowedHere, []);
if TypeParams.Count > 0 then
RaiseError(errTypeParameterNotAllowed, []);
Parse_SubrangeTypeDeclaration(TypeID, typeBOOLEAN, Q, 0);
Parse_PortabilityDirective;
DECLARE_SWITCH := true;
ok := MatchEx(';');
end
else
begin
if IsPacked then
CreateError(errPACKEDNotAllowedHere, []);
if IsCurrText('type') then
begin
Call_SCANNER;
if IsCurrText('of') then
Call_SCANNER;
end;
if IsCurrText('string') then
begin
Call_SCANNER;
if IsCurrText('[') then
begin
{$IFDEF PAXARM}
Match(';');
{$ELSE}
Parse_ShortStringTypeDeclaration(TypeID);
{$ENDIF}
end
else
begin
if InterfaceOnly then
Gen(OP_BEGIN_ALIAS_TYPE, TypeId, 0, 0);
SetType(TypeId, typeALIAS);
Gen(OP_ASSIGN_TYPE_ALIAS, TypeId, typeSTRING, 0);
if Assigned(OnParseAliasTypeDeclaration) then
OnParseAliasTypeDeclaration(Owner, GetName(TypeId), TypeId, 'string',
GetName(TypeId) + ' = string;');
if InterfaceOnly then
Gen(OP_END_ALIAS_TYPE, TypeId, 0, 0);
end;
end
else
begin
case CurrToken.TokenClass of
tcSpecial: typeBaseId := typeINTEGER;
tcIntegerConst: typeBaseId := typeINTEGER;
tcCharConst: typeBaseId := typeCHAR;
tcBooleanConst: typeBaseId := typeBOOLEAN;
tcIdentifier: typeBaseId := GetType(CurrToken.Id);
else
TypeBaseId := typeINTEGER;
end;
T := Parse_Expression;
if IsCurrText('..') then
Parse_SubrangeTypeDeclaration(TypeID, TypeBaseId, Q, T)
else
begin
if InterfaceOnly then
Gen(OP_BEGIN_ALIAS_TYPE, TypeId, 0, 0);
SetType(TypeId, typeALIAS);
Gen(OP_ASSIGN_TYPE_ALIAS, TypeId, T, 0);
if Assigned(OnParseAliasTypeDeclaration) then
OnParseAliasTypeDeclaration(Owner, GetName(TypeId), TypeId, GetName(T),
GetName(TypeId) + ' = ' + GetName(T) + ';');
if InterfaceOnly then
Gen(OP_END_ALIAS_TYPE, TypeId, 0, 0);
end;
end;
Parse_PortabilityDirective;
DECLARE_SWITCH := true;
TypeParams.Clear;
ok := MatchEx(';');
end;
Gen(OP_ADD_TYPEINFO, TypeId, 0, 0);
if InterfaceOnly then
Gen(OP_END_TYPE, TypeId, 0, 0);
if CurrToken.TokenClass = tcKeyword then
Break;
until not ok;
end;
function TPascalParser.Parse_OrdinalType(var Declaration: String): Integer;
var
T: Integer;
begin
Declaration := '';
if IsCurrText('(') then
begin
result := NewTempVar;
Parse_EnumTypeDeclaration(result);
end
else if (CurrToken.TokenClass = tcIntegerConst) or IsCurrText('-') then
begin
result := NewTempVar;
Parse_SubrangeTypeDeclaration(result, typeINTEGER, Declaration, 0);
end
else if CurrToken.TokenClass = tcCharConst then
begin
result := NewTempVar;
Parse_SubrangeTypeDeclaration(result, typeCHAR, Declaration, 0);
end
else if CurrToken.TokenClass = tcBooleanConst then
begin
result := NewTempVar;
Parse_SubrangeTypeDeclaration(result, typeBOOLEAN, Declaration, 0);
end
else if IsCurrText('ord') and IsNextText('(') then
begin
result := NewTempVar;
Parse_SubrangeTypeDeclaration(result, typeBYTE, Declaration, 0);
end
else if IsCurrText('chr') and IsNextText('(') then
begin
result := NewTempVar;
Parse_SubrangeTypeDeclaration(result, typeCHAR, Declaration, 0);
end
else if IsCurrText('low') and IsNextText('(') then
begin
result := NewTempVar;
Parse_SubrangeTypeDeclaration(result, typeBYTE, Declaration, 0);
end
else if IsCurrText('high') and IsNextText('(') then
begin
result := NewTempVar;
Parse_SubrangeTypeDeclaration(result, typeBYTE, Declaration, 0);
end
else
begin
T := Parse_QualId;
if IsCurrText('..') then
begin
result := NewTempVar;
Parse_SubrangeTypeDeclaration(result, typeENUM, Declaration, T);
end
else
begin
result := T;
Declaration := GetName(T);
// AddTypeExpRec(result);
end;
end;
end;
function TPascalParser.Parse_OpenArrayType(var ElemTypeName: String): Integer;
begin
DECLARE_SWITCH := true;
Match('array');
DECLARE_SWITCH := false;
Match('of');
ElemTypeName := CurrToken.Text;
if IsCurrText('const') then
begin
Call_SCANNER;
result := H_Dynarray_TVarRec;
end
else if IsCurrText('Integer') then
begin
Call_SCANNER;
result := H_Dynarray_Integer;
end
{$IFDEF UNIC}
else if IsCurrText('String') then
begin
ElemTypeName := 'UnicodeString';
Call_SCANNER;
result := H_Dynarray_UnicodeString;
end
else if IsCurrText('Char') then
begin
ElemTypeName := 'WideChar';
Call_SCANNER;
result := H_Dynarray_AnsiChar;
end
{$ELSE}
else if IsCurrText('String') then
begin
ElemTypeName := 'AnsiString';
Call_SCANNER;
result := H_Dynarray_AnsiString;
end
else if IsCurrText('Char') then
begin
ElemTypeName := 'AnsiChar';
Call_SCANNER;
result := H_Dynarray_WideChar;
end
{$ENDIF}
else if IsCurrText('Byte') then
begin
Call_SCANNER;
result := H_Dynarray_Byte;
end
else if IsCurrText('Word') then
begin
Call_SCANNER;
result := H_Dynarray_Word;
end
else if IsCurrText('ShortInt') then
begin
Call_SCANNER;
result := H_Dynarray_ShortInt;
end
else if IsCurrText('SmallInt') then
begin
Call_SCANNER;
result := H_Dynarray_SmallInt;
end
else if IsCurrText('Cardinal') then
begin
Call_SCANNER;
result := H_Dynarray_Cardinal;
end
else if IsCurrText('Int64') then
begin
Call_SCANNER;
result := H_Dynarray_Int64;
end
else if IsCurrText('UInt64') then
begin
Call_SCANNER;
result := H_Dynarray_UInt64;
end
else if IsCurrText('AnsiChar') then
begin
Call_SCANNER;
result := H_Dynarray_AnsiChar;
end
else if IsCurrText('WideChar') then
begin
Call_SCANNER;
result := H_Dynarray_WideChar;
end
else if IsCurrText('AnsiString') then
begin
Call_SCANNER;
result := H_Dynarray_AnsiString;
end
else if IsCurrText('WideString') then
begin
Call_SCANNER;
result := H_Dynarray_WideString;
end
else if IsCurrText('UnicodeString') then
begin
Call_SCANNER;
result := H_Dynarray_UnicodeString;
end
else if IsCurrText('ShortString') then
begin
Call_SCANNER;
result := H_Dynarray_ShortString;
end
else if IsCurrText('Double') then
begin
Call_SCANNER;
result := H_Dynarray_Double;
end
else if IsCurrText('Single') then
begin
Call_SCANNER;
result := H_Dynarray_Single;
end
else if IsCurrText('Extended') then
begin
Call_SCANNER;
result := H_Dynarray_Extended;
end
else if IsCurrText('Currency') then
begin
Call_SCANNER;
result := H_Dynarray_Currency;
end
else if IsCurrText('Boolean') then
begin
Call_SCANNER;
result := H_Dynarray_Boolean;
end
else if IsCurrText('ByteBool') then
begin
Call_SCANNER;
result := H_Dynarray_ByteBool;
end
else if IsCurrText('WordBool') then
begin
Call_SCANNER;
result := H_Dynarray_WordBool;
end
else if IsCurrText('LongBool') then
begin
Call_SCANNER;
result := H_Dynarray_LongBool;
end
else if IsCurrText('Variant') then
begin
Call_SCANNER;
result := H_Dynarray_Variant;
end
else if IsCurrText('OleVariant') then
begin
Call_SCANNER;
result := H_Dynarray_OleVariant;
end
else if IsCurrText('Pointer') then
begin
Call_SCANNER;
result := H_Dynarray_Pointer;
end
else
begin
result := NewTempVar;
BeginOpenArrayType(result);
Gen(OP_CREATE_DYNAMIC_ARRAY_TYPE, result, Parse_Ident, 0);
EndOpenArrayType(result, ElemTypeName);
end;
DECLARE_SWITCH := false;
end;
function TPascalParser.Parse_Type: Integer;
var
IsPacked: Boolean;
SubId: Integer;
S: String;
begin
IsPacked := false;
if IsCurrText('packed') then
begin
Match('packed');
IsPacked := true;
end
else if IsCurrText('System') then
begin
Match('System');
Match('.');
end;
if IsCurrText('array') then
begin
result := NewTempVar;
DECLARE_SWITCH := true;
Parse_ArrayTypeDeclaration(result, IsPacked);
DECLARE_SWITCH := false;
end
else if IsCurrText('record') then
begin
result := NewTempVar;
DECLARE_SWITCH := true;
Parse_RecordTypeDeclaration(result, IsPacked);
DECLARE_SWITCH := false;
end
else if IsCurrText('class') then
begin
result := NewTempVar;
DECLARE_SWITCH := true;
Parse_ClassTypeDeclaration(result, IsPacked);
DECLARE_SWITCH := false;
end
else if IsCurrText('interface') then
begin
result := NewTempVar;
DECLARE_SWITCH := true;
Parse_InterfaceTypeDeclaration(result);
DECLARE_SWITCH := false;
end
else if IsCurrText('dispinterface') then
begin
result := NewTempVar;
DECLARE_SWITCH := true;
Parse_InterfaceTypeDeclaration(result);
DECLARE_SWITCH := false;
end
else if IsCurrText('reference') then
begin
RemoveLastIdent(CurrToken.Id);
result := NewTempVar;
DECLARE_SWITCH := true;
Call_SCANNER;
Match('to');
Parse_MethodRefTypeDeclaration(result);
DECLARE_SWITCH := false;
end
else if IsCurrText('^') then
begin
result := NewTempVar;
Parse_PointerTypeDeclaration(result);
DECLARE_SWITCH := false;
end
else if IsCurrText('set') then
begin
result := NewTempVar;
Parse_SetTypeDeclaration(result);
DECLARE_SWITCH := false;
end
else if IsCurrText('procedure') or IsCurrText('function') then
begin
result := NewTempVar;
Parse_ProceduralTypeDeclaration(result, SubId);
DECLARE_SWITCH := false;
end
else if IsCurrText('string') then
begin
// result := Parse_Ident;
{$IFDEF PAXARM}
result := typeUNICSTRING;
{$ELSE}
if IsUNIC then
result := typeUNICSTRING
else
result := typeANSISTRING;
{$ENDIF}
Call_SCANNER;
if IsCurrText('[') then
begin
result := NewTempVar;
{$IFDEF PAXARM}
Match(';');
{$ELSE}
Parse_ShortStringTypeDeclaration(result);
{$ENDIF}
DECLARE_SWITCH := false;
end;
end
else if IsCurrText('double') then
begin
result := Parse_Ident;
end
else
begin
result := Parse_OrdinalType(S);
end;
Gen(OP_ADD_TYPEINFO, result, 0, 0);
end;
procedure TPascalParser.Parse_ArrayTypeDeclaration(ArrayTypeID: Integer; IsPacked: Boolean);
var
I, T, RangeTypeId, ElemTypeId: Integer;
L: TIntegerList;
RangeList: TStringList;
Declaration, S: String;
begin
L := TIntegerList.Create;
RangeList := TStringList.Create;
try
Match('array');
DECLARE_SWITCH := false;
if IsCurrText('of') then // dynamic array
begin
Match('of');
BeginDynamicArrayType(ArrayTypeID);
if IsCurrText('const') then
begin
Call_SCANNER;
Gen(OP_CREATE_DYNAMIC_ARRAY_TYPE, ArrayTypeId, H_TVarRec, 0);
ElemTypeId := H_TVarRec;
end
else
begin
ElemTypeId := Parse_Type;
Gen(OP_CREATE_DYNAMIC_ARRAY_TYPE, ArrayTypeId, ElemTypeId, 0);
end;
EndDynamicArrayType(ArrayTypeID);
if Assigned(OnParseDynArrayTypeDeclaration) then
begin
Declaration := 'array of ' + ExtractText(PrevPosition, PrevPosition + PrevLength - 1);
OnParseDynArrayTypeDeclaration(Owner, GetName(ArrayTypeId), ArrayTypeId,
GetName(ElemTypeId), Declaration);
end;
end
else // static array
begin
BeginArrayType(ArrayTypeID);
if IsPacked then
SetPacked(ArrayTypeID);
L.Add(ArrayTypeId);
Match('[');
repeat
T := NewTypeAlias;
RangeTypeId := Parse_OrdinalType(S);
Gen(OP_ASSIGN_TYPE_ALIAS, T, RangeTypeId, 0);
RangeList.Add(S);
if IsCurrText(',') then
begin
Match(',');
ArrayTypeId := NewTempVar;
BeginArrayType(ArrayTypeID);
if IsPacked then
SetPacked(ArrayTypeID);
L.Add(ArrayTypeId);
end
else
break;
until false;
Match(']');
Match('of');
T := NewTypeAlias;
ElemTypeId := Parse_Type;
Gen(OP_ASSIGN_TYPE_ALIAS, T, ElemTypeId, 0);
DECLARE_SWITCH := true;
for I:=0 to L.Count - 1 do
begin
EndArrayType(L[I]);
end;
if Assigned(OnParseArrayTypeDeclaration) then
begin
S := GetName(ElemTypeId);
OnParseArrayTypeDeclaration(Owner, GetName(L[0]), L[0],
RangeList,
S);
end;
end;
finally
FreeAndNil(L);
FreeAndNil(RangeList);
end;
end;
function TPascalParser.Parse_RecordConstructorHeading(IsSharedMethod: Boolean;
RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
Match('constructor');
result := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
SetVisibility(result, vis);
BeginStructureConstructor(result, RecordTypeId);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
Parse_FormalParameterList(result);
Match(';');
DirectiveList := Parse_DirectiveList(result);
if (DirectiveList.IndexOf(dirVIRTUAL) >= 0) or
(DirectiveList.IndexOf(dirDYNAMIC) >= 0) or
(DirectiveList.IndexOf(dirOVERRIDE) >= 0) then
begin
CreateError(errE2379, []);
// Virtual methods not allowed in record types.
end;
FreeAndNil(DirectiveList);
SetForward(result, true);
if IsCurrText('external') then
begin
ParseExternalSub(result);
SetForward(result, false);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(result);
Exit;
end;
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
if IsSharedMethod then
Declaration := 'class ' + Declaration;
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
function TPascalParser.Parse_RecordDestructorHeading(IsSharedMethod: Boolean;
RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
NP: Integer;
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
Match('destructor');
result := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
SetVisibility(result, vis);
BeginStructureDestructor(result, RecordTypeId);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
NP := 0;
if IsCurrText('(') then
begin
Call_SCANNER;
Match(')');
end;
SetCount(result, NP);
Match(';');
DirectiveList := Parse_DirectiveList(result);
if (DirectiveList.IndexOf(dirVIRTUAL) >= 0) or
(DirectiveList.IndexOf(dirDYNAMIC) >= 0) or
(DirectiveList.IndexOf(dirOVERRIDE) >= 0) then
begin
CreateError(errE2379, []);
// Virtual methods not allowed in record types.
end;
FreeAndNil(DirectiveList);
SetForward(result, true);
if IsCurrText('external') then
begin
ParseExternalSub(result);
SetForward(result, false);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(result);
Exit;
end;
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
if IsSharedMethod then
Declaration := 'class ' + Declaration;
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
function TPascalParser.Parse_RecordProcedureHeading(IsSharedMethod: Boolean;
RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
Match('procedure');
result := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
if IsCurrText('.') then
begin
Scanner.CurrComment.AllowedDoComment := false;
Match('.');
Parse_Ident;
DECLARE_SWITCH := false;
Match('=');
Parse_Ident;
Match(';');
Exit;
end;
SetVisibility(result, vis);
BeginStructureMethod(result, RecordTypeId, false, IsSharedMethod);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
Parse_FormalParameterList(result);
Match(';');
DirectiveList := Parse_DirectiveList(result);
if DirectiveList.IndexOf(dirABSTRACT) >= 0 then
begin
inherited InitSub(result);
Gen(OP_ERR_ABSTRACT, NewConst(typeSTRING,
GetName(RecordTypeId) + '.' + GetName(result)), 0, result);
end
else if (DirectiveList.IndexOf(dirVIRTUAL) >= 0) or
(DirectiveList.IndexOf(dirDYNAMIC) >= 0) or
(DirectiveList.IndexOf(dirOVERRIDE) >= 0) then
begin
CreateError(errE2379, []);
// Virtual methods not allowed in record types.
end
else if IsSharedMethod and (DirectiveList.IndexOf(dirSTATIC) = -1) then
begin
CreateError(errE2398, []);
// Class methods in record types must be static.
end
else
SetForward(result, true);
FreeAndNil(DirectiveList);
if IsCurrText('external') then
begin
ParseExternalSub(result);
SetForward(result, false);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(result);
Exit;
end;
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
if IsSharedMethod then
Declaration := 'class ' + Declaration;
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
function TPascalParser.Parse_RecordFunctionHeading(IsSharedMethod: Boolean;
RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
TypeID: Integer;
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
Match('function');
result := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
if IsCurrText('.') then
begin
Scanner.CurrComment.AllowedDoComment := false;
Match('.');
Parse_Ident;
DECLARE_SWITCH := false;
Match('=');
Parse_Ident;
Match(';');
Exit;
end;
SetVisibility(result, vis);
BeginStructureMethod(result, RecordTypeId, true, IsSharedMethod);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
Parse_FormalParameterList(result);
DECLARE_SWITCH := false;
Match(':');
Parse_Attribute;
TypeID := Parse_Type;
Gen(OP_ASSIGN_TYPE, result, TypeID, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, TypeID, 0);
if Assigned(OnParseResultType) then
OnParseResultType(Owner, GetName(TypeId), TypeId);
DECLARE_SWITCH := true;
Match(';');
DirectiveList := Parse_DirectiveList(result);
if DirectiveList.IndexOf(dirABSTRACT) >= 0 then
begin
inherited InitSub(result);
Gen(OP_ERR_ABSTRACT, NewConst(typeSTRING,
GetName(RecordTypeId) + '.' + GetName(result)), 0, result);
end
else if (DirectiveList.IndexOf(dirVIRTUAL) >= 0) or
(DirectiveList.IndexOf(dirDYNAMIC) >= 0) or
(DirectiveList.IndexOf(dirOVERRIDE) >= 0) then
begin
CreateError(errE2379, []);
// Virtual methods not allowed in record types.
end
else if IsSharedMethod and (DirectiveList.IndexOf(dirSTATIC) = -1) then
begin
CreateError(errE2398, []);
// Class methods in record types must be static.
end
else
SetForward(result, true);
FreeAndNil(DirectiveList);
if IsCurrText('external') then
begin
ParseExternalSub(result);
SetForward(result, false);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(result);
Exit;
end;
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
if IsSharedMethod then
Declaration := 'class ' + Declaration;
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
function TPascalParser.Parse_RecordOperatorHeading(RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
I, TypeID: Integer;
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
RemoveLastIdent(CurrToken.Id);
Match('operator');
I := OperatorIndex(CurrToken.Text);
if I = -1 then
CreateError(errE2393, []);
// errE2393 = 'Invalid operator declaration';
result := Parse_Ident;
SetName(result, operators.Values[I]);
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
SetVisibility(result, vis);
BeginStructureOperator(result, RecordTypeId);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
Parse_FormalParameterList(result);
DECLARE_SWITCH := false;
Match(':');
Parse_Attribute;
TypeID := Parse_Type;
Gen(OP_ASSIGN_TYPE, result, TypeID, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, TypeID, 0);
if Assigned(OnParseResultType) then
OnParseResultType(Owner, GetName(TypeId), TypeId);
DECLARE_SWITCH := true;
Match(';');
DirectiveList := Parse_DirectiveList(result);
FreeAndNil(DirectiveList);
SetForward(result, true);
SetOverloaded(result);
if IsCurrText('external') then
begin
ParseExternalSub(result);
SetForward(result, false);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(result);
Exit;
end;
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := 'class ' + ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
function TPascalParser.Parse_RecordProperty(RecordTypeId: Integer;
Vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
TypeID, ReadId, WriteId, ImplementsId: Integer;
Declaration: String;
SavedPosition: Integer;
begin
DECLARE_SWITCH := true;
SavedPosition := CurrToken.Position;
Match('property');
result := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
SetVisibility(result, vis);
BeginProperty(result, RecordTypeId);
ReadId := 0;
WriteId := 0;
TypeId := 0;
try
Parse_FormalParameterList(result, '[');
SetReadId(result, ReadId);
SetWriteId(result, WriteId);
if IsCurrText(';') then
begin
Match(';');
Gen(OP_DETERMINE_PROP, result, 0, 0);
EndProperty(result);
Exit;
end;
if IsCurrText(':') then
begin
DECLARE_SWITCH := false;
Match(':');
TypeID := Parse_QualId;
Gen(OP_ASSIGN_TYPE, result, TypeID, 0);
end;
repeat
DECLARE_SWITCH := false;
if IsCurrText('read') and (ReadId = 0) then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
ReadId := Parse_QualId;
ReadId := Lookup(GetName(ReadId), RecordTypeId);
if ReadId = 0 then
RaiseError(errUndeclaredIdentifier, [CurrToken.Text]);
SetReadId(result, ReadId);
end
else if IsCurrText('write') and (WriteId = 0) then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
WriteId := Parse_QualId;
WriteId := Lookup(GetName(WriteId), RecordTypeId);
if WriteId = 0 then
RaiseError(errUndeclaredIdentifier, [CurrToken.Text]);
SetWriteId(result, WriteId);
end
else if IsCurrText('implements') then
begin
RemoveLastIdent(CurrToken.Id);
DECLARE_SWITCH := false;
Call_SCANNER;
if not StrEql(GetName(result), CurrToken.Text) then
DiscardLastStRecord;
ImplementsId := Parse_Ident;
Gen(OP_IMPLEMENTS, result, ImplementsId, 0);
end
else if IsCurrText('stored') then
begin
DECLARE_SWITCH := false;
if not StrEql(GetName(result), CurrToken.Text) then
DiscardLastStRecord;
Call_SCANNER;
Parse_Expression;
end
else if IsCurrText('index') then
begin
DECLARE_SWITCH := false;
if not StrEql(GetName(result), CurrToken.Text) then
DiscardLastStRecord;
Call_SCANNER;
Parse_Expression;
end
else if IsCurrText('default') then
begin
if not StrEql(GetName(result), CurrToken.Text) then
DiscardLastStRecord;
Call_SCANNER;
if IsCurrText(';') then
SetDefault(result, true)
else
Parse_Expression;
end
else if IsCurrText('nodefault') then
begin
if not StrEql(GetName(result), CurrToken.Text) then
DiscardLastStRecord;
Call_SCANNER;
end
else
break;
until false;
if IsNextText('default') then
begin
Call_SCANNER;
Match('default');
SetDefault(result, true);
end;
if ReadId + WriteId = 0 then
RaiseError(errSyntaxError, []);
if ReadId > 0 then
TKernel(kernel).Code.used_private_members.Add(ReadId);
if WriteId > 0 then
TKernel(kernel).Code.used_private_members.Add(WriteId);
Match(';');
EndProperty(result);
finally
if Assigned(OnParsePropertyDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
OnParsePropertyDeclaration(Owner, GetName(result), result,
GetName(TypeId), Declaration);
end;
end;
end;
procedure TPascalParser.Parse_RecordVariantPart(VarLevel: Integer;
CurrVarCnt: Int64;
vis: TClassVisibility);
var
id, I, TypeId: Integer;
V, VarCnt: Int64;
L: TIntegerList;
S, Declaration: String;
SavedPosition: Integer;
begin
L := TIntegerList.Create;
try
VarCnt := 0;
if IsNext2Text(':') then
begin
DECLARE_SWITCH := true;
Match('case');
DECLARE_SWITCH := false;
id := Parse_Ident;
Match(':');
TypeId := Parse_Ident;
SetKind(Id, KindTYPE_FIELD);
Gen(OP_ASSIGN_TYPE, id, TypeId, 0);
end
else
begin
DECLARE_SWITCH := false;
Match('case');
TypeId := Parse_Ident;
Gen(OP_EVAL, 0, 0, TypeId);
end;
DECLARE_SWITCH := false;
Match('of');
repeat
Inc(VarCnt);
if IsEOF then
Break;
if IsCurrText('end') then
Break;
if IsCurrText(')') then
begin
Break;
end;
// RecVariant
// ConstList
repeat
if IsEOF then
Break;
if IsCurrText('end') then
Break;
Parse_Expression;
if NotMatch(',') then
break;
until false;
Match(':');
// FieldList
DECLARE_SWITCH := true;
Match('(');
if not IsCurrText(')') then
begin
if IsCurrText('case') then
begin
case VarLevel of
1: V := VarCnt;
2: V := VarCnt * 100 + CurrVarCnt;
3: V := VarCnt * 10000 + CurrVarCnt;
4: V := VarCnt * 1000000 + CurrVarCnt;
5: V := VarCnt * 100000000 + CurrVarCnt;
6: V := VarCnt * 10000000000 + CurrVarCnt;
7: V := VarCnt * 1000000000000 + CurrVarCnt;
else
begin
V := 0;
RaiseError(errTooManyNestedCaseBlocks, []);
end;
end;
Parse_RecordVariantPart(VarLevel + 1, V, vis);
end
else
begin
repeat
L.Clear;
repeat // parse ident list
L.Add(Parse_Ident);
if NotMatch(',') then
break;
until false;
DECLARE_SWITCH := false;
Match(':');
SavedPosition := CurrToken.Position;
TypeID := Parse_Type;
S := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
case VarLevel of
1: V := VarCnt;
2: V := VarCnt * 100 + CurrVarCnt;
3: V := VarCnt * 10000 + CurrVarCnt;
4: V := VarCnt * 1000000 + CurrVarCnt;
5: V := VarCnt * 100000000 + CurrVarCnt;
6: V := VarCnt * 10000000000 + CurrVarCnt;
7: V := VarCnt * 1000000000000 + CurrVarCnt;
else
begin
V := 0;
RaiseError(errTooManyNestedCaseBlocks, []);
end;
end;
for I:=0 to L.Count - 1 do
begin
SetKind(L[I], KindTYPE_FIELD);
SetVarCount(L[I], V);
SetVisibility(L[I], vis);
Gen(OP_ASSIGN_TYPE, L[I], TypeID, 0);
if Assigned(OnParseVariantRecordFieldDeclaration) then
begin
Declaration := GetName(L[I]) + ' = ' + S + ';';
OnParseVariantRecordFieldDeclaration(Owner, GetName(L[I]), L[I],
GetName(TypeId), V, Declaration);
end;
end;
if IsCurrText(';') then
begin
DECLARE_SWITCH := true;
Match(';');
if IsCurrText(')') then
break;
if IsCurrText('case') then
begin
Parse_RecordVariantPart(VarLevel + 1, V, vis);
break;
end;
end
else
break;
until false;
end;
DECLARE_SWITCH := true;
end;
DECLARE_SWITCH := false;
Match(')');
if IsCurrText(';') then
Match(';');
until false;
finally
FreeAndNil(L);
end;
end;
procedure TPascalParser.Parse_RecordHelperItem;
begin
if IsCurrText('const') then
Parse_ConstantDeclaration;
end;
procedure TPascalParser.Parse_RecordTypeDeclaration(RecordTypeID: Integer; IsPacked: Boolean;
IsExternalUnit: Boolean = false);
var
vis: TClassVisibility;
var
L: TIntegerList;
I, TypeID, Id, TrueRecordId: Integer;
b: Boolean;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
TrueRecordId := 0;
vis := cvPublic;
if IsNextText('helper') then
begin
Match('record');
DECLARE_SWITCH := false;
RemoveLastIdent(CurrToken.Id);
Match('helper');
Match('for');
TrueRecordId := Parse_QualId;
BeginHelperType(RecordTypeId, TrueRecordId);
if Assigned(OnParseBeginRecordHelperTypeDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
Declaration := GetName(RecordTypeId) + ' = ' + Declaration;
if Assigned(OnParseBeginClassHelperTypeDeclaration) then
begin
OnParseBeginRecordHelperTypeDeclaration(Owner, GetName(RecordTypeId), RecordTypeId,
GetName(TrueRecordId),
Declaration);
end;
end;
end
else
begin
BeginRecordType(RecordTypeID);
if IsPacked then
SetPacked(RecordTypeID);
Match('record');
if Assigned(OnParseBeginRecordTypeDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
Declaration := GetName(RecordTypeId) + ' = ' + Declaration;
OnParseBeginRecordTypeDeclaration(Owner, GetName(RecordTypeId), RecordTypeId, Declaration);
end;
end;
b := false;
L := TIntegerList.Create;
try
repeat
if IsEOF then
Break;
if IsCurrText('end') then
Break;
if IsCurrText('case') then
begin
Parse_RecordVariantPart(1, 0, vis);
break;
end
else
begin
repeat
if IsCurrText('strict') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
if IsCurrText('protected') then
begin
Call_SCANNER;
vis := cvStrictProtected;
end
else
begin
Match('private');
vis := cvStrictPrivate;
end;
b := false;
end
else if IsCurrText('private') then
begin
Call_SCANNER;
vis := cvPrivate;
b := false;
end
else if IsCurrText('protected') then
begin
Call_SCANNER;
vis := cvProtected;
b := false;
end
else if IsCurrText('public') then
begin
Call_SCANNER;
vis := cvPublic;
b := false;
end
else if IsCurrText('published') then
begin
Call_SCANNER;
vis := cvPublished;
b := false;
end
else
break;
until false;
if IsCurrText('end') then
Break;
Parse_Attribute;
if IsCurrText('case') then
begin
Parse_RecordVariantPart(1, 0, vis);
break;
end
else if IsCurrText('constructor') then
begin
Parse_RecordConstructorHeading(false, RecordTypeId, vis, IsExternalUnit);
b := true;
end
else if IsCurrText('destructor') then
begin
Parse_RecordDestructorHeading(false, RecordTypeId, vis, IsExternalUnit);
b := true;
end
else if IsCurrText('procedure') then
begin
Parse_RecordProcedureHeading(false, RecordTypeId, vis, IsExternalUnit);
b := true;
end
else if IsCurrText('function') then
begin
Parse_RecordFunctionHeading(false, RecordTypeId, vis, IsExternalUnit);
b := true;
end
else if IsCurrText('var') or IsCurrText('threadvar') then
begin
if IsCurrText('threadvar') then
Call_SCANNER
else
Match('var');
repeat
Parse_Attribute;
L.Clear;
repeat // parse ident list
Id := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, Id, 0);
L.Add(Id);
if NotMatch(',') then
break;
until false;
DECLARE_SWITCH := false;
Match(':');
TypeID := Parse_Type;
for I:=0 to L.Count - 1 do
begin
SetKind(L[I], KindTYPE_FIELD);
SetVisibility(L[I], vis);
Gen(OP_ASSIGN_TYPE, L[I], TypeID, 0);
end;
DECLARE_SWITCH := true;
Parse_PortabilityDirective;
if IsCurrText(';') then
Match(';');
if CurrToken.TokenClass <> tcIdentifier then
if not IsCurrText('[') then
break;
until false;
end
else if IsCurrText('class') then
begin
b := true;
Call_SCANNER;
if IsCurrText('constructor') then
Parse_RecordConstructorHeading(true, RecordTypeId, vis, IsExternalUnit)
else if IsCurrText('destructor') then
Parse_RecordDestructorHeading(true, RecordTypeId, vis, IsExternalUnit)
else if IsCurrText('procedure') then
Parse_RecordProcedureHeading(true, RecordTypeId, vis, IsExternalUnit)
else if IsCurrText('function') then
Parse_RecordFunctionHeading(true, RecordTypeId, vis, IsExternalUnit)
else if IsCurrText('operator') then
Parse_RecordOperatorHeading(RecordTypeId, vis, IsExternalUnit)
else if IsCurrText('property') then
Parse_RecordProperty(RecordTypeId, vis, IsExternalUnit)
else if IsCurrText('var') or IsCurrText('threadvar') then
Parse_VariableDeclaration(vis);
end
else if IsCurrText('property') then
begin
Parse_RecordProperty(RecordTypeId, vis, IsExternalUnit);
b := true;
end
else if IsCurrText('type') then
begin
Parse_TypeDeclaration(false, vis);
b := true;
end
else if IsCurrText('const') then
begin
Parse_ConstantDeclaration(vis);
b := true;
end
else
begin
if IsCurrText('threadvar') then
Call_SCANNER
else if IsCurrText('var') then
Call_SCANNER;
if b then
CreateError(errFieldDefinitionNotAllowedAfter, []);
L.Clear;
repeat // parse ident list
Id := Parse_Ident;
SetVisibility(Id, Vis);
Gen(OP_DECLARE_MEMBER, CurrLevel, Id, 0);
L.Add(Id);
if NotMatch(',') then
break;
until false;
DECLARE_SWITCH := false;
Match(':');
SavedPosition := CurrToken.Position;
TypeID := Parse_Type;
for I:=0 to L.Count - 1 do
begin
SetKind(L[I], KindTYPE_FIELD);
Gen(OP_ASSIGN_TYPE, L[I], TypeID, 0);
if Assigned(OnParseFieldDeclaration) then
begin
Declaration := GetName(L[I]) + ':' +
ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
OnParseFieldDeclaration(Owner, GetName(L[I]), L[I], GetName(TypeId),
Declaration);
end;
end;
DECLARE_SWITCH := true;
Parse_PortabilityDirective;
if IsCurrText(';') then
Match(';');
end;
if IsCurrText('case') then
begin
Parse_RecordVariantPart(1, 0, vis);
break;
end;
end;
until false;
finally
FreeAndNil(L);
end;
if TrueRecordId > 0 then
begin
EndHelperType(RecordTypeId);
if Assigned(OnParseEndRecordHelperTypeDeclaration) then
OnParseEndRecordHelperTypeDeclaration(Owner, GetName(RecordTypeId), RecordTypeId);
end
else
begin
EndRecordType(RecordTypeId);
if Assigned(OnParseEndRecordTypeDeclaration) then
OnParseEndRecordTypeDeclaration(Owner, GetName(RecordTypeId), RecordTypeId);
end;
Match('end');
end;
procedure TPascalParser.Parse_Message(SubId: Integer);
begin
DECLARE_SWITCH := false;
Call_SCANNER;
if CurrToken.TokenClass = tcIntegerConst then
begin
Gen(OP_ADD_MESSAGE, SubId, CurrToken.Id, 0);
end
else if CurrToken.TokenClass = tcIdentifier then
begin
Gen(OP_ADD_MESSAGE, SubId, CurrToken.Id, 0);
end
else
begin
RaiseError(errIncompatibleTypesNoArgs, []);
end;
ReadToken;
end;
function TPascalParser.Parse_ClassConstructorHeading(IsSharedMethod: Boolean;
ClassTypeId: Integer;
vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
Match('constructor');
result := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
SetVisibility(result, vis);
BeginClassConstructor(result, ClassTypeId);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
GetSymbolRec(result).IsSharedMethod := IsSharedMethod;
Parse_FormalParameterList(result);
Match(';');
CheckRedeclaredSub(result);
DirectiveList := Parse_DirectiveList(result);
try
if not ImportOnly then
if CountAtLevel(GetName(result), GetLevel(result), KindCONSTRUCTOR, IsSharedMethod) > 1 then
if DirectiveList.IndexOf(dirOVERLOAD) = -1 then
CreateError(errOverloadExpected, [GetName(result)]);
if (DirectiveList.IndexOf(dirSTATIC) >= 0) and
(
(DirectiveList.IndexOf(dirVIRTUAL) >= 0) or
(DirectiveList.IndexOf(dirDYNAMIC) >= 0) or
(DirectiveList.IndexOf(dirOVERRIDE) >= 0)
) then
begin
CreateError(errE2376, []);
//STATIC can only be used on non-virtual class methods.
end;
finally
FreeAndNil(DirectiveList);
end;
SetForward(result, true);
if IsCurrText('external') then
begin
ParseExternalSub(result);
SetForward(result, false);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(result);
Exit;
end;
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
if IsSharedMethod then
Declaration := 'class ' + Declaration;
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
function TPascalParser.Parse_ClassDestructorHeading(IsSharedMethod: Boolean;
ClassTypeId: Integer;
vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
NP: Integer;
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
Match('destructor');
result := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
SetVisibility(result, vis);
BeginClassDestructor(result, ClassTypeId);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
GetSymbolRec(result).IsSharedMethod := IsSharedMethod;
NP := 0;
if IsCurrText('(') then
begin
Call_SCANNER;
Match(')');
end;
SetCount(result, NP);
Match(';');
CheckRedeclaredSub(result);
DirectiveList := Parse_DirectiveList(result);
try
if not ImportOnly then
begin
if not IsSharedMethod then
if DirectiveList.IndexOf(dirOVERRIDE) = -1 then
Match('override');
if CountAtLevel(GetName(result), GetLevel(result), KindDESTRUCTOR, IsSharedMethod) > 1 then
if DirectiveList.IndexOf(dirOVERLOAD) = -1 then
CreateError(errOverloadExpected, [GetName(result)]);
end;
finally
FreeAndNil(DirectiveList);
end;
SetForward(result, true);
if IsCurrText('external') then
begin
ParseExternalSub(result);
SetForward(result, false);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(result);
Exit;
end;
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
if IsSharedMethod then
Declaration := 'class ' + Declaration;
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
function TPascalParser.Parse_ClassProcedureHeading(IsSharedMethod: Boolean;
ClassTypeId: Integer;
vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
BeginTypeExt(ClassTypeId);
Match('procedure');
result := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
if IsCurrText('.') then
begin
Scanner.CurrComment.AllowedDoComment := false;
Match('.');
Parse_Ident;
DECLARE_SWITCH := false;
Match('=');
Parse_Ident;
Match(';');
Exit;
end;
SetVisibility(result, vis);
BeginClassMethod(result, ClassTypeId, false, IsSharedMethod, false);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
Parse_FormalParameterList(result);
EndTypeExt(ClassTypeId);
Match(';');
CheckRedeclaredSub(result);
if IsCurrText('message') then
Parse_Message(result);
DirectiveList := Parse_DirectiveList(result);
try
if DirectiveList.IndexOf(dirABSTRACT) >= 0 then
begin
inherited InitSub(result);
Gen(OP_ERR_ABSTRACT, NewConst(typeSTRING,
GetName(ClassTypeId) + '.' + GetName(result)), 0, result);
end
else if (DirectiveList.IndexOf(dirSTATIC) >= 0) and
(
(IsSharedMethod = false) or
(DirectiveList.IndexOf(dirVIRTUAL) >= 0) or
(DirectiveList.IndexOf(dirDYNAMIC) >= 0) or
(DirectiveList.IndexOf(dirOVERRIDE) >= 0)
) then
begin
CreateError(errE2376, []);
//STATIC can only be used on non-virtual class methods.
end
else if DirectiveList.IndexOf(dirOVERRIDE) >= 0 then
begin
SetForward(result, true);
end
else
SetForward(result, true);
if CountAtLevel(GetName(result), GetLevel(result)) > 1 then
if DirectiveList.IndexOf(dirOVERLOAD) = -1 then
if not ImportOnly then
CreateError(errOverloadExpected, [GetName(result)]);
finally
FreeAndNil(DirectiveList);
end;
if IsCurrText('external') then
begin
ParseExternalSub(result);
SetForward(result, false);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(result);
Exit;
end;
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
if IsSharedMethod then
Declaration := 'class ' + Declaration;
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
function TPascalParser.Parse_ClassFunctionHeading(IsSharedMethod: Boolean;
ClassTypeId: Integer;
vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
TypeID: Integer;
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := true;
Match('function');
result := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
if IsCurrText('.') then
begin
Scanner.CurrComment.AllowedDoComment := false;
Match('.');
Parse_Ident;
DECLARE_SWITCH := false;
Match('=');
Parse_Ident;
Match(';');
Exit;
end;
SetVisibility(result, vis);
BeginClassMethod(result, ClassTypeId, true, IsSharedMethod, false);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
Parse_FormalParameterList(result);
DECLARE_SWITCH := false;
Match(':');
Parse_Attribute;
TypeID := Parse_Type;
Gen(OP_ASSIGN_TYPE, result, TypeID, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, TypeID, 0);
if Assigned(OnParseResultType) then
OnParseResultType(Owner, GetName(TypeId), TypeId);
DECLARE_SWITCH := true;
Match(';');
CheckRedeclaredSub(result);
if IsCurrText('message') then
Parse_Message(result);
DirectiveList := Parse_DirectiveList(result);
try
if DirectiveList.IndexOf(dirABSTRACT) >= 0 then
begin
inherited InitSub(result);
Gen(OP_ERR_ABSTRACT, NewConst(typeSTRING,
GetName(ClassTypeId) + '.' + GetName(result)), 0, result);
end
else if (DirectiveList.IndexOf(dirSTATIC) >= 0) and
(
(IsSharedMethod = false) or
(DirectiveList.IndexOf(dirVIRTUAL) >= 0) or
(DirectiveList.IndexOf(dirDYNAMIC) >= 0) or
(DirectiveList.IndexOf(dirOVERRIDE) >= 0)
) then
begin
CreateError(errE2376, []);
//STATIC can only be used on non-virtual class methods.
end
else if DirectiveList.IndexOf(dirOVERRIDE) >= 0 then
begin
SetForward(result, true);
end
else
SetForward(result, true);
if CountAtLevel(GetName(result), GetLevel(result)) > 1 then
if DirectiveList.IndexOf(dirOVERLOAD) = -1 then
if not ImportOnly then
CreateError(errOverloadExpected, [GetName(result)]);
finally
FreeAndNil(DirectiveList);
end;
if IsCurrText('external') then
begin
ParseExternalSub(result);
SetForward(result, false);
Exit;
end;
if IsExternalUnit then
begin
GenExternalSub(result);
Exit;
end;
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
if IsSharedMethod then
Declaration := 'class ' + Declaration;
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
function TPascalParser.Parse_ClassProperty(IsShared: Boolean;
ClassTypeId: Integer;
vis: TClassVisibility;
IsExternalUnit: Boolean): Integer;
var
ReadId, WriteId, ImplementsId, TypeID, K: Integer;
StrType, StrDefault, Declaration: String;
SavedPosition: Integer;
begin
RemoveKeywords;
SavedPosition := CurrToken.Position;
ReadId := 0;
WriteId := 0;
DECLARE_SWITCH := true;
Match('property');
result := Parse_Ident;
StrType := '';
StrDefault := '';
try
Gen(OP_DECLARE_MEMBER, CurrLevel, result, 0);
SetVisibility(result, vis);
BeginProperty(result, ClassTypeId);
Parse_FormalParameterList(result, '[');
if IsCurrText(';') then
begin
Gen(OP_DETERMINE_PROP, result, 0, 0);
EndProperty(result);
Exit;
end
else if IsCurrText('default') then
begin
Call_SCANNER;
StrDefault := CurrToken.Text;
if not IsCurrText(';') then
Parse_Expression;
Gen(OP_DETERMINE_PROP, result, 0, 0);
EndProperty(result);
Exit;
end
else if IsCurrText('nodefault') then
begin
Call_SCANNER;
Gen(OP_DETERMINE_PROP, result, 0, 0);
EndProperty(result);
Exit;
end;
if IsCurrText(':') then
begin
DECLARE_SWITCH := false;
Match(':');
TypeID := Parse_QualId;
StrType := GetName(TypeId);
Gen(OP_ASSIGN_TYPE, result, TypeID, 0);
end;
repeat
DECLARE_SWITCH := false;
if IsCurrText('read') and (ReadId = 0) then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
ReadId := Parse_QualId;
Gen(OP_SET_READ_ID, result, ReadId, 0);
SetReadId(result, ReadId);
if IsCurrText(';') then
if IsNextText('default') then
Call_SCANNER;
end
else if IsCurrText('write') and (WriteId = 0) then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
WriteId := Parse_QualId;
Gen(OP_SET_WRITE_ID, result, WriteId, 0);
SetWriteId(result, WriteId);
if IsCurrText(';') then
if IsNextText('default') then
Call_SCANNER;
end
else if IsCurrText('implements') then
begin
RemoveLastIdent(CurrToken.Id);
DECLARE_SWITCH := false;
Call_SCANNER;
if not StrEql(GetName(result), CurrToken.Text) then
DiscardLastStRecord;
repeat
ImplementsId := Parse_QualId;
Gen(OP_IMPLEMENTS, result, ImplementsId, 0);
if NotMatch(',') then
break;
until false;
end
else if IsCurrText('stored') then
begin
DECLARE_SWITCH := false;
if not StrEql(GetName(result), CurrToken.Text) then
DiscardLastStRecord;
Call_SCANNER;
Parse_Expression;
end
else if IsCurrText('index') then
begin
DECLARE_SWITCH := false;
if not StrEql(GetName(result), CurrToken.Text) then
DiscardLastStRecord;
Call_SCANNER;
Parse_Expression;
end
else if IsCurrText('default') then
begin
if not StrEql(GetName(result), CurrToken.Text) then
DiscardLastStRecord;
Call_SCANNER;
if IsCurrText(';') then
SetDefault(result, true)
else
Parse_Expression;
end
else if IsCurrText('nodefault') then
begin
if not StrEql(GetName(result), CurrToken.Text) then
DiscardLastStRecord;
Call_SCANNER;
end
else
break;
until false;
if IsNextText('default') then
begin
Call_SCANNER;
Match('default');
StrDefault := CurrToken.Text;
SetDefault(result, true);
end;
if ReadId > 0 then
TKernel(kernel).Code.used_private_members.Add(ReadId);
if WriteId > 0 then
TKernel(kernel).Code.used_private_members.Add(WriteId);
EndProperty(result);
finally
RestoreKeywords;
if Assigned(OnParsePropertyDeclaration) then
begin
Declaration := ExtractText(SavedPosition,
CurrToken.Position + CurrToken.Length - 1);
if IsShared then
Declaration := 'class ' + Declaration;
if StrType = '' then
if GetSymbolRec(result).Vis in [cvPublic, cvProtected] then
begin
if ReadId > 0 then
begin
TypeId := GetSymbolRec(ReadId).TypeID;
StrType := GetName(TypeId);
end;
if StrType = '' then
if WriteId > 0 then
begin
if GetKind(WriteId) = KindSUB then
begin
K := GetCount(result);
K := GetParamId(WriteId, K);
TypeId := GetSymbolRec(K).TypeID;
StrType := GetName(TypeId);
end
else
begin
TypeId := GetSymbolRec(WriteId).TypeID;
StrType := GetName(TypeId);
end;
end;
if StrType = '' then
if StrDefault <> '' then
begin
if StrEql(StrDefault, 'true') or StrEql(StrDefault, 'false') then
StrType := 'Boolean';
end;
end;
OnParsePropertyDeclaration(Owner, GetName(result), result, StrType,
Declaration);
end;
end;
end;
procedure TPascalParser.Parse_ClassTypeDeclaration(ClassTypeID: Integer; IsPacked: Boolean;
IsExternalUnit: Boolean = false);
var
vis: TClassVisibility;
var
L: TIntegerList;
I, TypeID, AncestorId, RefTypeId, Id: Integer;
b: Boolean;
Declaration: String;
TrueClassId: Integer;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
if IsNextText('of') then
begin
DECLARE_SWITCH := false;
BeginClassReferenceType(ClassTypeID);
Match('class');
Match('of');
RefTypeId := Parse_QualId;
Gen(OP_CREATE_CLASSREF_TYPE, ClassTypeId, RefTypeId, 0);
EndClassReferenceType(ClassTypeID);
if Assigned(OnParseClassReferenceTypeDeclaration) then
begin
Declaration := ExtractText(SavedPosition, CurrToken.Position + CurrToken.Length - 1);
OnParseClassReferenceTypeDeclaration(Owner,
GetName(ClassTypeId), ClassTypeId, GetName(RefTypeId), Declaration);
end;
Exit;
end
else if IsNextText('helper') then
begin
Match('class');
DECLARE_SWITCH := false;
RemoveLastIdent(CurrToken.Id);
Match('helper');
Match('for');
TrueClassId := Parse_QualId;
BeginHelperType(ClassTypeId, TrueClassId);
end
else
begin
BeginClassType(ClassTypeID);
TrueClassId := 0;
if IsPacked then
SetPacked(ClassTypeID);
Match('class');
if IsCurrText(';') then // forward declaration
begin
SetForward(ClassTypeId, true);
EndClassType(ClassTypeId, true);
if Assigned(OnParseForwardTypeDeclaration) then
OnParseForwardTypeDeclaration(Owner, GetName(ClassTypeId), ClassTypeId);
Exit;
end;
if IsCurrText('abstract') then
begin
RemoveLastEvalInstruction('abstract');
SetAbstract(ClassTypeId, true);
Call_SCANNER;
end
else if IsCurrText('sealed') then
begin
SetFinal(ClassTypeId, true);
Call_SCANNER;
end;
end;
if TrueClassId > 0 then
begin
if Assigned(OnParseBeginClassHelperTypeDeclaration) then
begin
OnParseBeginClassHelperTypeDeclaration(Owner, GetName(ClassTypeId), ClassTypeId,
GetName(TrueClassId),
Declaration);
end;
end
else if Assigned(OnParseBeginClassTypeDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
Declaration := GetName(ClassTypeId) + ' = ' + Declaration;
OnParseBeginClassTypeDeclaration(Owner, GetName(ClassTypeId), ClassTypeId, Declaration);
end;
if IsCurrText('(') then
begin
DECLARE_SWITCH := false;
Match('(');
AncestorId := Parse_QualId;
Gen(OP_ADD_ANCESTOR, ClassTypeId, AncestorId, 0);
if Assigned(OnParseAncestorTypeDeclaration) then
OnParseAncestorTypeDeclaration(Owner, GetName(AncestorId), AncestorId);
if StrEql(GetName(ClassTypeId), GetName(AncestorId)) then
RaiseError(errRedeclaredIdentifier, [GetName(AncestorId)]);
if IsCurrText(',') then
begin
Call_SCANNER;
repeat
AncestorId := Parse_QualId;
Gen(OP_ADD_INTERFACE, ClassTypeId, AncestorId, 0);
if Assigned(OnParseUsedInterface) then
OnParseUsedInterface(Owner, GetName(AncestorId), AncestorId);
if NotMatch(',') then
break;
until false;
end;
DECLARE_SWITCH := true;
Match(')')
end
else
if Assigned(OnParseAncestorTypeDeclaration) then
OnParseAncestorTypeDeclaration(Owner, GetName(H_TObject), H_TObject);
if IsCurrText(';') then
begin
if TrueClassId > 0 then
begin
EndHelperType(ClassTypeId);
if Assigned(OnParseEndClassHelperTypeDeclaration) then
OnParseEndClassHelperTypeDeclaration(Owner, GetName(ClassTypeId), ClassTypeId);
end
else
begin
EndClassType(ClassTypeId);
if Assigned(OnParseEndClassTypeDeclaration) then
OnParseEndClassTypeDeclaration(Owner, GetName(ClassTypeId), ClassTypeId);
if FindConstructorId(ClassTypeId) = 0 then
GenDefaultConstructor(ClassTypeId);
if FindDestructorId(ClassTypeId) = 0 then
GenDefaultDestructor(ClassTypeId);
end;
Exit;
end;
vis := cvPublished;
b := false;
L := TIntegerList.Create;
try
repeat
if IsEOF then
Break;
if IsCurrText('end') then
Break;
repeat
if IsCurrText('strict') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
if IsCurrText('protected') then
begin
Call_SCANNER;
vis := cvStrictProtected;
end
else
begin
Match('private');
vis := cvStrictPrivate;
end;
b := false;
end
else if IsCurrText('private') then
begin
Call_SCANNER;
vis := cvPrivate;
b := false;
end
else if IsCurrText('protected') then
begin
Call_SCANNER;
vis := cvProtected;
b := false;
end
else if IsCurrText('public') then
begin
Call_SCANNER;
vis := cvPublic;
b := false;
end
else if IsCurrText('published') then
begin
Call_SCANNER;
vis := cvPublished;
b := false;
end
else
break;
until false;
if IsCurrText('end') then
Break;
Parse_Attribute;
if IsCurrText('constructor') then
begin
Parse_ClassConstructorHeading(false, ClassTypeId, vis, IsExternalUnit);
b := true;
end
else if IsCurrText('destructor') then
begin
Parse_ClassDestructorHeading(false, ClassTypeId, vis, IsExternalUnit);
b := true;
end
else if IsCurrText('procedure') then
begin
Parse_ClassProcedureHeading(false, ClassTypeId, vis, IsExternalUnit);
b := true;
end
else if IsCurrText('function') then
begin
Parse_ClassFunctionHeading(false, ClassTypeId, vis, IsExternalUnit);
b := true;
end
else if IsCurrText('var') or IsCurrText('threadvar') then
begin
if IsCurrText('threadvar') then
Call_SCANNER
else
Match('var');
repeat
Parse_Attribute;
L.Clear;
repeat // parse ident list
Id := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, Id, 0);
L.Add(Id);
if NotMatch(',') then
break;
until false;
DECLARE_SWITCH := false;
Match(':');
TypeID := Parse_Type;
for I:=0 to L.Count - 1 do
begin
SetKind(L[I], KindTYPE_FIELD);
SetVisibility(L[I], vis);
Gen(OP_ASSIGN_TYPE, L[I], TypeID, 0);
end;
DECLARE_SWITCH := true;
Parse_PortabilityDirective;
if IsCurrText(';') then
Match(';');
if CurrToken.TokenClass <> tcIdentifier then
if not IsCurrText('[') then
break;
until false;
end
else if IsCurrText('class') then
begin
b := true;
Call_SCANNER;
if IsCurrText('constructor') then
Parse_ClassConstructorHeading(true, ClassTypeId, vis, IsExternalUnit)
else if IsCurrText('destructor') then
Parse_ClassDestructorHeading(true, ClassTypeId, vis, IsExternalUnit)
else if IsCurrText('procedure') then
Parse_ClassProcedureHeading(true, ClassTypeId, vis, IsExternalUnit)
else if IsCurrText('function') then
Parse_ClassFunctionHeading(true, ClassTypeId, vis, IsExternalUnit)
else if IsCurrText('property') then
Parse_ClassProperty(true, ClassTypeId, vis, IsExternalUnit)
else if IsCurrText('var') or IsCurrText('threadvar') then
begin
if vis = cvPublished then
Parse_VariableDeclaration(cvPublic)
else
Parse_VariableDeclaration(vis);
end;
end
else if IsCurrText('property') then
begin
Parse_ClassProperty(false, ClassTypeId, vis, IsExternalUnit);
b := true;
end
else if IsCurrText('type') then
begin
Parse_TypeDeclaration(false, vis);
b := true;
end
else if IsCurrText('const') then
begin
if vis = cvPublished then
Parse_ConstantDeclaration(cvPublic)
else
Parse_ConstantDeclaration(vis);
b := true;
end
else
begin
if IsCurrText('var') then
Call_SCANNER
else if IsCurrText('threadvar') then
Call_SCANNER;
if b then
CreateError(errFieldDefinitionNotAllowedAfter, []);
Parse_Attribute;
L.Clear;
repeat // parse ident list
Id := Parse_Ident;
Gen(OP_DECLARE_MEMBER, CurrLevel, Id, 0);
L.Add(Id);
if NotMatch(',') then
break;
until false;
DECLARE_SWITCH := false;
Match(':');
SavedPosition := CurrToken.Position;
TypeID := Parse_Type;
for I:=0 to L.Count - 1 do
begin
SetKind(L[I], KindTYPE_FIELD);
SetVisibility(L[I], vis);
Gen(OP_ASSIGN_TYPE, L[I], TypeID, 0);
if Assigned(OnParseFieldDeclaration) then
begin
Declaration := GetName(L[I]) + ':' +
ExtractText(SavedPosition, CurrToken.Position + CurrToken.Length - 1);
OnParseFieldDeclaration(Owner, GetName(L[I]), L[I], GetName(TypeId),
Declaration);
end;
end;
end;
DECLARE_SWITCH := true;
Parse_PortabilityDirective;
if IsCurrText(';') then
Match(';');
until false;
finally
FreeAndNil(L);
end;
if TrueClassId > 0 then
begin
EndHelperType(ClassTypeId);
if Assigned(OnParseEndClassHelperTypeDeclaration) then
OnParseEndClassHelperTypeDeclaration(Owner, GetName(ClassTypeId), ClassTypeId);
end
else
begin
EndClassType(ClassTypeId);
if Assigned(OnParseEndClassTypeDeclaration) then
OnParseEndClassTypeDeclaration(Owner, GetName(ClassTypeId), ClassTypeId);
if FindConstructorId(ClassTypeId) = 0 then
GenDefaultConstructor(ClassTypeId);
if FindDestructorId(ClassTypeId) = 0 then
GenDefaultDestructor(ClassTypeId);
end;
Match('end');
end;
procedure TPascalParser.Parse_MethodRefTypeDeclaration(TypeID: Integer);
var
NegativeMethodIndex: Integer;
function Parse_ProcedureHeading: Integer;
var
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
Dec(NegativeMethodIndex);
DECLARE_SWITCH := true;
Match('procedure');
result := NewTempVar();
SetName(result, ANONYMOUS_METHOD_NAME);
BeginInterfaceMethod(result, TypeId, false);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
Parse_FormalParameterList(result);
Gen(OP_ADD_METHOD_INDEX, result, NegativeMethodIndex, 0);
DECLARE_SWITCH := true;
EndTypeDef(TypeId);
Match(';');
DirectiveList := Parse_DirectiveList(result);
if DirectiveList.IndexOf(dirABSTRACT) >= 0 then
CreateError(errUnknownDirective, ['abstract']);
EndSub(result);
FreeAndNil(DirectiveList);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
function Parse_FunctionHeading: Integer;
var
ResTypeID: Integer;
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
Dec(NegativeMethodIndex);
DECLARE_SWITCH := true;
Match('function');
result := NewTempVar();
SetName(result, ANONYMOUS_METHOD_NAME);
BeginInterfaceMethod(result, TypeId, true);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
Parse_FormalParameterList(result);
DECLARE_SWITCH := false;
Match(':');
Parse_Attribute;
ResTypeID := Parse_Type;
Gen(OP_ASSIGN_TYPE, result, ResTypeID, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, ResTypeID, 0);
Gen(OP_ADD_METHOD_INDEX, result, NegativeMethodIndex, 0);
if Assigned(OnParseResultType) then
OnParseResultType(Owner, GetName(ResTypeId), TypeId);
DECLARE_SWITCH := true;
EndTypeDef(TypeId);
Match(';');
DirectiveList := Parse_DirectiveList(result);
if DirectiveList.IndexOf(dirABSTRACT) >= 0 then
CreateError(errUnknownDirective, ['abstract']);
EndSub(result);
FreeAndNil(DirectiveList);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
end;
var
SavedPosition: Integer;
Declaration: String;
begin
SavedPosition := CurrToken.Position;
NegativeMethodIndex := 0;
BeginMethodRefType(TypeID);
if IsCurrText('procedure') then
begin
Parse_ProcedureHeading;
end
else if IsCurrText('function') then
begin
Parse_FunctionHeading;
end
else
Match('procedure');
EndMethodRefType(TypeId);
if Assigned(OnParseMethodReferenceTypeDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition +
PrevLength - 1);
OnParseMethodReferenceTypeDeclaration(Owner, GetName(TypeId), TypeId,
Declaration);
end;
end;
procedure TPascalParser.Parse_InterfaceTypeDeclaration(IntfTypeID: Integer);
const
IsPacked = true;
var
NegativeMethodIndex: Integer;
function Parse_ProcedureHeading: Integer;
var
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
Dec(NegativeMethodIndex);
DECLARE_SWITCH := true;
Match('procedure');
result := Parse_Ident;
BeginInterfaceMethod(result, IntfTypeId, false);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
Parse_FormalParameterList(result);
Gen(OP_ADD_METHOD_INDEX, result, NegativeMethodIndex, 0);
DECLARE_SWITCH := true;
Match(';');
if IsCurrText('dispid') then
begin
Call_SCANNER;
Parse_Expression;
end;
DirectiveList := Parse_DirectiveList(result);
if DirectiveList.IndexOf(dirABSTRACT) >= 0 then
CreateError(errUnknownDirective, ['abstract']);
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
FreeAndNil(DirectiveList);
end;
function Parse_FunctionHeading: Integer;
var
TypeID: Integer;
DirectiveList: TIntegerList;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
Dec(NegativeMethodIndex);
DECLARE_SWITCH := true;
Match('function');
result := Parse_Ident;
BeginInterfaceMethod(result, IntfTypeId, true);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(result), result);
Parse_FormalParameterList(result);
DECLARE_SWITCH := false;
Match(':');
Parse_Attribute;
TypeID := Parse_Type;
Gen(OP_ASSIGN_TYPE, result, TypeID, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, TypeID, 0);
Gen(OP_ADD_METHOD_INDEX, result, NegativeMethodIndex, 0);
if Assigned(OnParseResultType) then
OnParseResultType(Owner, GetName(TypeId), TypeId);
DECLARE_SWITCH := true;
Match(';');
if IsCurrText('dispid') then
begin
Call_SCANNER;
Parse_Expression;
end;
DirectiveList := Parse_DirectiveList(result);
if DirectiveList.IndexOf(dirABSTRACT) >= 0 then
CreateError(errUnknownDirective, ['abstract']);
EndSub(result);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
OnParseEndSubDeclaration(Owner, GetName(result), result, Declaration);
end;
FreeAndNil(DirectiveList);
end;
function Parse_Property: Integer;
var
TypeID, ReadId, WriteId: Integer;
Declaration: String;
SavedPosition: Integer;
begin
DECLARE_SWITCH := true;
SavedPosition := CurrToken.Position;
Match('property');
result := Parse_Ident;
BeginProperty(result, IntfTypeId);
ReadId := 0;
WriteId := 0;
TypeId := 0;
try
SetVisibility(result, cvPublic);
Parse_FormalParameterList(result, '[');
DECLARE_SWITCH := false;
Match(':');
TypeID := Parse_QualId;
Gen(OP_ASSIGN_TYPE, result, TypeID, 0);
if IsCurrText('readonly') then
begin
Call_SCANNER;
end
else if IsCurrText('writeonly') then
begin
Call_SCANNER;
end;
if IsCurrText('dispid') then
begin
Call_SCANNER;
Parse_Expression;
if IsNextText('default') then
begin
Match(';');
Call_SCANNER;
SetDefault(result, true);
end;
EndProperty(result);
Exit;
end;
repeat
if IsCurrText('read') and (ReadId = 0) then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
ReadId := Parse_QualId;
ReadId := Lookup(GetName(ReadId), IntfTypeId);
if ReadId = 0 then
RaiseError(errUndeclaredIdentifier, [CurrToken.Text]);
SetReadId(result, ReadId);
end
else if IsCurrText('write') and (WriteId = 0) then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
WriteId := Parse_QualId;
WriteId := Lookup(GetName(WriteId), IntfTypeId);
if WriteId = 0 then
RaiseError(errUndeclaredIdentifier, [CurrToken.Text]);
SetWriteId(result, WriteId);
end
else
break;
until false;
if IsCurrText(';') then
Call_SCANNER
else
RaiseError(errTokenExpected, [';', CurrToken.Text]);
if IsCurrText('default') then
begin
Call_SCANNER;
SetDefault(result, true);
end;
if ReadId + WriteId = 0 then
RaiseError(errSyntaxError, []);
EndProperty(result);
finally
if Assigned(OnParsePropertyDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition +
PrevLength - 1);
OnParsePropertyDeclaration(Owner, GetName(result), result, GetName(TypeId),
Declaration);
end;
end;
end;
var
L: TIntegerList;
I, AncestorId: Integer;
S: String;
IntfList: TIntegerList;
begin
IntfList := TIntegerList.Create;
try
NegativeMethodIndex := 0;
BeginInterfaceType(IntfTypeID);
SetPacked(IntfTypeID);
if IsCurrText('dispinterface') then
Call_SCANNER
else
Match('interface');
if IsCurrText(';') then // forward declaration
begin
SetForward(IntfTypeId, true);
EndInterfaceType(IntfTypeId, true);
if Assigned(OnParseForwardTypeDeclaration) then
OnParseForwardTypeDeclaration(Owner, GetName(IntfTypeId), IntfTypeId);
Exit;
end;
if IsCurrText('(') then
begin
DECLARE_SWITCH := false;
Match('(');
repeat
AncestorId := Parse_Ident;
IntfList.Add(AncestorId);
Gen(OP_ADD_INTERFACE, IntfTypeId, AncestorId, 0);
if NotMatch(',') then
break;
until false;
DECLARE_SWITCH := true;
Match(')');
end
else
begin
Gen(OP_ADD_INTERFACE, IntfTypeId, H_IUnknown, 0);
IntfList.Add(H_IUnknown);
end;
if IsCurrText('[') then
begin
Match('[');
if CurrToken.TokenClass = tcPCharConst then
begin
I := Parse_PCharLiteral;
S := GetValue(I);
SetGuid(IntfTypeId, S);
end
else
begin
I := Parse_Ident;
S := GetValue(I);
// SetGuid(IntfTypeId, S);
if ImportOnly then
GetSymbolRec(IntfTypeId).NoGUID := true;
end;
Match(']');
end
else
begin
if ImportOnly then
GetSymbolRec(IntfTypeId).NoGUID := true;
SetNewGuid(IntfTypeId);
end;
if Assigned(OnParseBeginInterfaceTypeDeclaration) then
OnParseBeginInterfaceTypeDeclaration(Owner, GetName(IntfTypeId), IntfTypeId);
if Assigned(OnParseAncestorTypeDeclaration) then
begin
AncestorId := IntfList[0];
OnParseAncestorTypeDeclaration(Owner, GetName(AncestorId), AncestorId);
end;
if Assigned(OnParseUsedInterface) then
for I := 1 to IntfList.Count - 1 do
begin
AncestorId := IntfList[I];
OnParseUsedInterface(Owner, GetName(AncestorId), AncestorId);
end;
L := TIntegerList.Create;
try
repeat
if IsEOF then
Break;
if IsCurrText('end') then
Break;
repeat
if IsCurrText('private') then
begin
CreateError(errKeywordNotAllowedInInterfaceDeclaration, [CurrToken.Text]);
Call_SCANNER;
end
else if IsCurrText('protected') then
begin
CreateError(errKeywordNotAllowedInInterfaceDeclaration, [CurrToken.Text]);
Call_SCANNER;
end
else if IsCurrText('public') then
begin
CreateError(errKeywordNotAllowedInInterfaceDeclaration, [CurrToken.Text]);
Call_SCANNER;
end
else if IsCurrText('published') then
begin
CreateError(errKeywordNotAllowedInInterfaceDeclaration, [CurrToken.Text]);
Call_SCANNER;
end
else
break;
until false;
if IsCurrText('end') then
Break;
if IsCurrText('procedure') then
begin
Parse_ProcedureHeading;
end
else if IsCurrText('function') then
begin
Parse_FunctionHeading;
end
else if IsCurrText('property') then
begin
Parse_Property;
end
else if IsCurrText('[') then
Parse_Attribute
else
Match('end');
DECLARE_SWITCH := true;
if IsCurrText(';') then
Match(';');
until false;
finally
FreeAndNil(L);
end;
EndInterfaceType(IntfTypeId);
if Assigned(OnParseEndInterfaceTypeDeclaration) then
OnParseEndInterfaceTypeDeclaration(Owner, GetName(IntfTypeId), IntfTypeId);
Match('end');
finally
FreeAndNil(IntfList);
end;
end;
procedure TPascalParser.Parse_PointerTypeDeclaration(TypeID: Integer);
var
RefTypeId: Integer;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := false;
Match('^');
BeginPointerType(TypeID);
RefTypeId := Parse_QualId;
Gen(OP_CREATE_POINTER_TYPE, TypeId, RefTypeId, 0);
EndPointerType(TypeID);
if Assigned(OnParsePointerTypeDeclaration) then
begin
Declaration := GetName(TypeId) + '=' +
ExtractText(SavedPosition, CurrToken.Position + CurrToken.Length - 1);
OnParsePointerTypeDeclaration(Owner,
GetName(TypeId), TypeId, GetName(RefTypeId), Declaration);
end;
end;
{$IFNDEF PAXARM}
procedure TPascalParser.Parse_ShortStringTypeDeclaration(TypeID: Integer);
var
ExprId: Integer;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := false;
Match('[');
BeginShortStringType(TypeID);
ExprId := Parse_ConstantExpression;
Gen(OP_CREATE_SHORTSTRING_TYPE, TypeId, ExprId, 0);
EndShortStringType(TypeID);
Match(']');
if Assigned(OnParseShortStringTypeDeclaration) then
begin
Declaration := 'String' + ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
OnParseShortStringTypeDeclaration(Owner, GetName(TypeId), TypeId, GetValue(ExprId),
Declaration);
end;
end;
{$ENDIF}
procedure TPascalParser.Parse_ProceduralTypeDeclaration(TypeID: Integer;
var SubId: Integer);
var
IsFunc: Boolean;
SubTypeId: Integer;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
if IsCurrText('function') then
begin
Match('function');
IsFunc := true;
end
else
begin
Match('procedure');
IsFunc := false;
end;
SubTypeId := typeVOID;
SubId := NewTempVar;
BeginProceduralType(TypeID, SubId);
if Assigned(OnParseBeginSubDeclaration) then
OnParseBeginSubDeclaration(Owner, GetName(SubId), SubId);
Parse_FormalParameterList(SubId);
DECLARE_SWITCH := false;
if IsFunc then
begin
Match(':');
DECLARE_SWITCH := true;
SubTypeID := Parse_Type;
if Assigned(OnParseResultType) then
OnParseResultType(Owner, GetName(SubTypeID), SubTypeID);
end;
Gen(OP_ASSIGN_TYPE, SubId, SubTypeID, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, SubTypeID, 0);
EndProceduralType(TypeID);
if Assigned(OnParseEndSubDeclaration) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
end;
if IsCurrText('of') then
begin
Match('of');
Match('object');
SetType(TypeId, typeEVENT);
end;
DECLARE_SWITCH := true;
if IsCurrText('stdcall') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccSTDCALL);
end
else if IsCurrText('safecall') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccSTDCALL);
end
else if IsCurrText('register') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccSTDCALL);
end
else if IsCurrText('cdecl') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccSTDCALL);
end
else if IsCurrText('msfastcall') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccSTDCALL);
end
else if IsCurrText('pascal') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccSTDCALL);
end
//--------------
else if IsNextText('stdcall') then
begin
Call_SCANNER;
RemoveLastIdent(CurrToken.Id);
SetCallConvention(SubId, ccSTDCALL);
Call_SCANNER;
end
else if IsNextText('safecall') then
begin
Call_SCANNER;
RemoveLastIdent(CurrToken.Id);
SetCallConvention(SubId, ccSAFECALL);
Call_SCANNER;
end
else if IsNextText('register') then
begin
Call_SCANNER;
RemoveLastIdent(CurrToken.Id);
SetCallConvention(SubId, ccREGISTER);
Call_SCANNER;
end
else if IsNextText('cdecl') then
begin
Call_SCANNER;
RemoveLastIdent(CurrToken.Id);
SetCallConvention(SubId, ccCDECL);
Call_SCANNER;
end
else if IsNextText('msfastcall') then
begin
Call_SCANNER;
RemoveLastIdent(CurrToken.Id);
SetCallConvention(SubId, ccMSFASTCALL);
Call_SCANNER;
end
else if IsNextText('pascal') then
begin
Call_SCANNER;
RemoveLastIdent(CurrToken.Id);
SetCallConvention(SubId, ccPASCAL);
Call_SCANNER;
end;
if Assigned(OnParseEndSubDeclaration) then
begin
OnParseEndSubDeclaration(Owner, GetName(SubId), SubId, Declaration);
end;
if GetType(TypeId) = typePROC then
begin
if Assigned(OnParseProceduralTypeDeclaration) then
begin
Declaration := ExtractText(SavedPosition, CurrToken.Position +
CurrToken.Length - 1);
OnParseProceduralTypeDeclaration(Owner, GetName(TypeId), TypeId,
Declaration);
end;
end
else
begin
if Assigned(OnParseEventTypeDeclaration) then
begin
Declaration := ExtractText(SavedPosition, CurrToken.Position +
CurrToken.Length - 1);
OnParseEventTypeDeclaration(Owner, GetName(TypeId), TypeId,
Declaration);
end;
end;
end;
procedure TPascalParser.Parse_SetTypeDeclaration(TypeID: Integer);
var
TypeBaseId: Integer;
Declaration: String;
SavedPosition: Integer;
begin
SavedPosition := CurrToken.Position;
DECLARE_SWITCH := false;
Match('set');
Match('of');
TypeBaseId := Parse_OrdinalType(Declaration);
BeginSetType(TypeID, TypeBaseId);
EndSetType(TypeID);
if Assigned(OnParseSetTypeDeclaration) then
begin
Declaration := GetName(TypeId) + '=' +
ExtractText(SavedPosition, CurrToken.Position + CurrToken.Length - 1);
OnParseSetTypeDeclaration(Owner, GetName(TypeId), TypeId, GetName(TypeBaseId),
Declaration);
end;
end;
procedure TPascalParser.Parse_EnumTypeDeclaration(TypeID: Integer);
var
ID, TempID, L, K: Integer;
Declaration: String;
SavedPosition: Integer;
begin
L := CurrLevel;
BeginEnumType(TypeID, TypeINTEGER);
if Assigned(OnParseBeginEnumTypeDeclaration) then
OnParseBeginEnumTypeDeclaration(Owner, GetName(TypeId), TypeId);
DECLARE_SWITCH := true;
Match('(');
TempID := NewConst(TypeID, 0);
K := 0;
repeat
SavedPosition := CurrToken.Position;
ID := Parse_EnumIdent;
Inc(K);
SetLevel(ID, L);
if IsCurrText('=') then
begin
DECLARE_SWITCH := false;
Match('=');
Gen(OP_ASSIGN_ENUM, ID, Parse_ConstantExpression, ID);
Gen(OP_ASSIGN_ENUM, TempID, ID, TempID);
Gen(OP_INC, TempID, NewConst(typeINTEGER, 1), tempID);
DECLARE_SWITCH := true;
end
else
begin
Gen(OP_ASSIGN_ENUM, ID, TempID, ID);
Gen(OP_INC, TempID, NewConst(typeINTEGER, 1), tempID);
end;
if Assigned(OnParseEnumName) then
begin
Declaration := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
OnParseEnumName(Owner, GetName(ID), ID, K - 1, Declaration);
end;
if NotMatch(',') then
Break;
until false;
Match(')');
EndEnumType(TypeID, K);
if Assigned(OnParseEndEnumTypeDeclaration) then
OnParseEndEnumTypeDeclaration(Owner, GetName(TypeId), TypeId);
end;
procedure TPascalParser.Parse_SubrangeTypeDeclaration(TypeID, TypeBaseId: Integer;
var Declaration: String;
Expr1ID: Integer = 0);
var
ID1, ID2, ExprId1, ExprId2: Integer;
SavedPosition: Integer;
begin
SavedPosition := Scanner.FindPosition([Ord('='), Ord('['), Ord(':'), Ord(',')]) + 1;
BeginSubrangeType(TypeID, TypeBaseID);
ID1 := NewConst(TypeBaseId);
ID2 := NewConst(TypeBaseId);
if Expr1ID = 0 then
begin
ExprId1 := Parse_ConstantExpression;
Gen(OP_ASSIGN_CONST, ID1, ExprId1, ID1);
end
else
begin
Gen(OP_ASSIGN_CONST, ID1, Expr1ID, ID1);
end;
Match('..');
ExprId2 := Parse_ConstantExpression;
Gen(OP_ASSIGN_CONST, ID2, ExprId2, ID2);
Gen(OP_CHECK_SUBRANGE_TYPE, ID1, ID2, 0);
EndSubrangeType(TypeID);
Declaration := GetName(TypeId) + ' = ' + ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
if Assigned(OnParseSubrangeTypeDeclaration) then
OnParseSubrangeTypeDeclaration(Owner, GetName(TypeId), TypeId, Declaration);
end;
function TPascalParser.Parse_FormalParameterList(SubId: Integer;
bracket: Char = '('): Integer;
var
L: TIntegerList;
I, ID, TypeId, ExprId: Integer;
ByRef, IsConst, HasDefaultParameters, IsOpenArray, IsOut: Boolean;
Declaration, DefaultValue, ParamMod, StrType: String;
SavedPosition: Integer;
begin
result := 0;
if Assigned(OnParseBeginFormalParameterList) then
OnParseBeginFormalParameterList(Owner);
BeginCollectSig(SubId);
try
DECLARE_SWITCH := true;
if IsCurrText('(') then
Call_SCANNER
else if IsCurrText('[') then
Call_SCANNER
else
begin
if IsCurrText(':') then
Sig := '( ) : ' + GetNextText
else
Sig := '( ) ;';
Exit;
end;
HasDefaultParameters := false;
if not IsCurrText(')') then
begin
L := TIntegerList.Create;
StrType := '';
try
repeat
ByRef := false;
IsConst := false;
IsOut := false;
Parse_Attribute;
ParamMod := '';
if IsCurrText('var') then
begin
ParamMod := 'var';
Match('var');
ByRef := true;
end
else if IsCurrText('out') then
begin
ParamMod := 'out';
Match('out');
ByRef := true;
IsOut := true;
end
else if IsCurrText('const') then
begin
ParamMod := 'const';
Match('const');
IsConst := true;
end;
Parse_Attribute;
L.Clear;
repeat
Inc(result);
ID := Parse_FormalParameter;
Gen(OP_DECLARE_LOCAL_VAR, SubId, ID, 0);
L.Add(ID);
if NotMatch(',') then
break;
until false;
DECLARE_SWITCH := false;
IsOpenArray := false;
if ByRef or IsConst then
begin
if IsCurrText(':') then
begin
Match(':');
IsOpenArray := IsCurrText('array');
if IsOpenArray then
TypeId := Parse_OpenArrayType(StrType)
else
begin
TypeId := Parse_Type;
StrType := GetName(TypeId);
end;
end
else
TypeId := typePVOID;
end
else
begin
Match(':');
IsOpenArray := IsCurrText('array');
if IsOpenArray then
TypeId := Parse_OpenArrayType(StrType)
else
begin
TypeId := Parse_Type;
StrType := GetName(TypeId);
end;
end;
DECLARE_SWITCH := true;
for I:=0 to L.Count - 1 do
begin
if ByRef then if not IsOpenArray then
SetByRef(L[I]);
if IsOut then
GetSymbolRec(L[I]).IsOut := true;
if IsConst then
SetIsConst(L[I]);
if IsOpenArray then
begin
SetOpenArray(L[I], true);
end;
Gen(OP_ASSIGN_TYPE, L[I], TypeID, 0);
end;
DefaultValue := '';
if IsCurrText('=') then
begin
// if L.Count > 1 then
// CreateError(errParameterNotAllowedHere, [GetName(L[1])]);
DECLARE_SWITCH := false;
CollectSig := false;
Sig := RemoveCh('=', Sig);
Match('=');
SavedPosition := CurrToken.Position;
if ImportOnly then
ExprId := Parse_Expression
else
ExprId := Parse_ConstantExpression;
DefaultValue := ExtractText(SavedPosition, PrevPosition + PrevLength - 1);
for I := 0 to L.Count - 1 do
begin
Gen(OP_ASSIGN_CONST, L[I], ExprId, L[I]);
SetOptional(L[I]);
end;
CollectSig := true;
Sig := Sig + CurrToken.Text;
DECLARE_SWITCH := true;
HasDefaultParameters := true;
end
else
begin
if HasDefaultParameters then
CreateError(errDefaultValueRequired, [GetName(L[0])]);
end;
if Assigned(OnParseFormalParameterDeclaration) then
begin
if IsOpenArray then
StrType := 'ARRAY OF ' + StrType;
for I := 0 to L.Count - 1 do
begin
if DefaultValue = '' then
Declaration := GetName(L[I]) + ' : ' + StrType + ';'
else
Declaration := GetName(L[I]) + ' : ' +
StrType + '=' + DefaultValue + ';';
if ParamMod <> '' then
Declaration := ParamMod + ' ' + Declaration;
OnParseFormalParameterDeclaration(Owner,
GetName(L[I]), L[I], StrType, DefaultValue, Declaration);
end;
end;
if NotMatch(';') then
Break;
until false;
finally
FreeAndNil(L);
end;
end;
if bracket = '(' then
Match(')')
else if bracket = '[' then
Match(']');
if IsCurrText(':') then
Sig := Sig + ' ' + GetNextText;
finally
SetCount(SubId, result);
EndCollectSig(SubId);
if Assigned(OnParseEndFormalParameterList) then
OnParseEndFormalParameterList(Owner);
end;
end;
procedure TPascalParser.Parse_SubBlock;
begin
if GetName(CurrSelfId) = '' then
begin
Gen(OP_STMT, 0, 0, 0);
Parse_Block;
end
else
begin
Gen(OP_STMT, 0, 0, 0);
DECLARE_SWITCH := true;
Parse_DeclarationPart;
Gen(OP_BEGIN_WITH, CurrSelfId, 0, 0);
WithStack.Push(CurrSelfId);
Parse_CompoundStmt;
Gen(OP_END_WITH, WithStack.Top, 0, 0);
WithStack.Pop;
end;
end;
procedure TPascalParser.Parse_ProcedureDeclaration(IsSharedMethod: Boolean = false);
var
SubId, ForwardId: Integer;
DirectiveList: TIntegerList;
NotDeclared, WaitOverload: Boolean;
K: Integer;
begin
DECLARE_SWITCH := true;
K := 0;
BeginMethodDef;
try
NotDeclared := false;
WaitOverload := false;
if IsSharedMethod then
begin
ForwardId := ReadType;
if ForwardId = 0 then
CreateError(errUndeclaredIdentifier, [CurrToken.Text]);
Call_SCANNER;
DECLARE_SWITCH := true;
Scanner.CurrComment.AllowedDoComment := false;
Match('.');
SubId := Parse_Ident;
BeginClassMethod(SubId, ForwardId, false, true, true);
end
else
begin
ForwardId := ReadType;
if (ForwardId > 0) and (GetKind(ForwardId) = KindTYPE) then
begin
Call_SCANNER;
while GetNext2Text = '.' do
begin
Inc(K);
levelStack.Push(ForwardId);
ReadToken;
ForwardId := Lookup(CurrToken.Text, CurrLevel);
if ForwardId = 0 then
RaiseError(errUndeclaredIdentifier, [CurrToken.Text]);
ReadToken;
end;
DECLARE_SWITCH := true;
Scanner.CurrComment.AllowedDoComment := false;
Match('.');
SubId := Parse_Ident;
if Lookup(GetName(SubId), ForwardId) = 0 then
NotDeclared := true;
BeginClassMethod(SubId, ForwardId, false, false, true);
end
else
begin
if ForwardId > 0 then
if GetKind(ForwardId) in KindSUBS then
if not GetSymbolRec(ForwardId).IsForward then
if GetSymbolRec(ForwardId).Host = false then
if GetSymbolRec(ForwardId).OverCount = 0 then
RaiseError(errRedeclaredIdentifier, [CurrToken.Text])
else
WaitOverload := true;
SubId := NewVar(CurrToken.Text);
SetPosition(SubId, CurrToken.Position - 1);
CurrToken.Id := SubId;
Parse_Ident;
BeginSub(SubId);
end;
end;
Parse_FormalParameterList(SubId);
SetName(CurrResultId, '');
SetKind(CurrResultId, KindNONE);
SetType(SubId, TypeVOID);
SetType(CurrResultId, TypeVOID);
Match(';');
if NotDeclared then
CreateError(errUndeclaredIdentifier, [GetName(SubId)]);
DirectiveList := Parse_DirectiveList(SubId);
try
if DirectiveList.IndexOf(dirFORWARD) >= 0 then
begin
SetForward(SubId, true);
EndSub(SubId);
Exit;
end;
if WaitOverload then
begin
if DirectiveList.IndexOf(dirOVERLOAD) = -1 then
CreateError(errOverloadExpected, [GetName(SubId)]);
end;
finally
FreeAndNil(DirectiveList);
end;
if IsCurrText('external') then
begin
ParseExternalSub(SubId);
Exit;
end;
InitSub(SubId);
if ForwardId > 0 then
if not GetSymbolRec(ForwardId).IsForward then
CheckRedeclaredSub(SubId);
Parse_SubBlock;
EndSub(SubId);
EndMethodDef(SubId);
Match(';');
finally
while K > 0 do
begin
Dec(K);
levelStack.Pop;
end;
end;
end;
function TPascalParser.Parse_AnonymousFunction: Integer;
begin
result := Parse_AnonymousRoutine(true);
end;
function TPascalParser.Parse_AnonymousProcedure: Integer;
begin
result := Parse_AnonymousRoutine(false);
end;
function TPascalParser.Parse_AnonymousRoutine(IsFunc: Boolean): Integer;
var
I, Id, RefId, ClassId, SubId, ResTypeId: Integer;
ClsName, ObjName: String;
begin
NewAnonymousNames(ClsName, ObjName);
GenComment('BEGIN OF ANONYMOUS CLASS ' + ClsName);
TypeParams.Clear;
ClassId := NewTempVar;
SetName(ClassId, ClsName);
BeginClassType(ClassId);
SetPacked(ClassId);
SetAncestorId(ClassId, H_TInterfacedObject);
// Gen(OP_ADD_INTERFACE, ClassId, 0, 0); // 0 - anonymous
GenDefaultConstructor(ClassId);
GenDefaultDestructor(ClassId);
DECLARE_SWITCH := true;
if IsFunc then
Match('function')
else
Match('procedure');
DECLARE_SWITCH := false;
SubId := NewTempVar;
SetName(SubId, ANONYMOUS_METHOD_NAME);
BeginClassMethod(SubId,
ClassId,
IsFunc, // has result
false, // is shared
true); // is implementation
Parse_FormalParameterList(SubId);
DECLARE_SWITCH := false;
if IsFunc then
begin
Match(':');
Parse_Attribute;
ResTypeId := Parse_Type;
Gen(OP_ASSIGN_TYPE, SubId, ResTypeId, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, ResTypeId, 0);
end;
DECLARE_SWITCH := true;
AnonymStack.Push(SubId);
try
InitSub(SubId);
Parse_SubBlock;
EndSub(SubId);
for I := 0 to AnonymStack.Top.BindList.Count - 1 do
begin
Id := NewTempVar;
SetName(Id, GetName(AnonymStack.Top.BindList[I]));
SetLevel(Id, ClassId);
SetKind(Id, KindTYPE_FIELD);
SetVisibility(Id, cvPublic);
Gen(OP_ASSIGN_THE_SAME_TYPE, Id, AnonymStack.Top.BindList[I], 0);
end;
EndClassType(ClassId);
GenComment('END OF ANONYMOUS CLASS ' + ClsName);
Gen(OP_ADD_TYPEINFO, ClassId, 0, 0);
result := NewTempVar;
Gen(OP_DECLARE_LOCAL_VAR, CurrSubId, result, 0);
SetName(result, ObjName);
SetType(result, ClassId);
RefId := NewField('Create', result);
Gen(OP_FIELD, ClassId, RefId, RefId);
Gen(OP_ASSIGN, result, RefId, result);
for I := 0 to AnonymStack.Top.BindList.Count - 1 do
begin
RefId := NewField(GetName(AnonymStack.Top.BindList[I]), result);
Gen(OP_FIELD, result, RefId, RefId);
Gen(OP_ASSIGN, RefId, AnonymStack.Top.BindList[I], RefId);
end;
finally
AnonymStack.Pop;
end;
Gen(OP_ADD_INTERFACE, ClassId, 0, 0); // 0 - anonymous
end;
function TPascalParser.Parse_LambdaExpression: Integer;
var
I, Id, RefId, ClassId, SubId: Integer;
ClsName, ObjName: String;
begin
NewAnonymousNames(ClsName, ObjName);
GenComment('BEGIN OF ANONYMOUS CLASS ' + ClsName);
TypeParams.Clear;
ClassId := NewTempVar;
SetName(ClassId, ClsName);
BeginClassType(ClassId);
SetPacked(ClassId);
SetAncestorId(ClassId, H_TInterfacedObject);
GenDefaultConstructor(ClassId);
GenDefaultDestructor(ClassId);
SubId := NewTempVar;
Gen(OP_ASSIGN_LAMBDA_TYPES, SubId, 0, 0);
SetName(SubId, ANONYMOUS_METHOD_NAME);
BeginClassMethod(SubId,
ClassId,
true, // has result
false, // is shared
true); // is implementation
DECLARE_SWITCH := true;
Match('lambda');
Parse_LambdaParameters(SubId);
DECLARE_SWITCH := false;
Match('=>');
AnonymStack.Push(SubId);
try
InitSub(SubId);
Gen(OP_BEGIN_WITH, CurrSelfId, 0, 0);
WithStack.Push(CurrSelfId);
Id := CurrResultId;
Gen(OP_ASSIGN, Id, Parse_Expression, Id);
Gen(OP_END_WITH, WithStack.Top, 0, 0);
WithStack.Pop;
EndSub(SubId);
for I := 0 to AnonymStack.Top.BindList.Count - 1 do
begin
Id := NewTempVar;
SetName(Id, GetName(AnonymStack.Top.BindList[I]));
SetLevel(Id, ClassId);
SetKind(Id, KindTYPE_FIELD);
SetVisibility(Id, cvPublic);
Gen(OP_ASSIGN_THE_SAME_TYPE, Id, AnonymStack.Top.BindList[I], 0);
end;
EndClassType(ClassId);
GenComment('END OF ANONYMOUS CLASS ' + ClsName);
Gen(OP_ADD_TYPEINFO, ClassId, 0, 0);
result := NewTempVar;
Gen(OP_DECLARE_LOCAL_VAR, CurrSubId, result, 0);
SetName(result, ObjName);
SetType(result, ClassId);
RefId := NewField('Create', result);
Gen(OP_FIELD, ClassId, RefId, RefId);
Gen(OP_ASSIGN, result, RefId, result);
for I := 0 to AnonymStack.Top.BindList.Count - 1 do
begin
RefId := NewField(GetName(AnonymStack.Top.BindList[I]), result);
Gen(OP_FIELD, result, RefId, RefId);
Gen(OP_ASSIGN, RefId, AnonymStack.Top.BindList[I], RefId);
end;
finally
AnonymStack.Pop;
end;
Gen(OP_ASSIGN_LAMBDA_TYPES, SubId, ClassId, result);
end;
function TPascalParser.Parse_LambdaParameters(SubId: Integer) : Integer;
var
ID: Integer;
begin
result := 0;
if not IsCurrText('(') then
repeat
Inc(result);
ID := Parse_FormalParameter;
Gen(OP_DECLARE_LOCAL_VAR, SubId, ID, 0);
SetCount(SubId, result);
if NotMatch(',') then
Exit;
until false;
Match('(');
if IsCurrText(')') then
begin
Match(')');
SetCount(SubId, result);
Exit;
end;
repeat
Inc(result);
ID := Parse_FormalParameter;
Gen(OP_DECLARE_LOCAL_VAR, SubId, ID, 0);
if NotMatch(',') then
break;
until false;
Match(')');
SetCount(SubId, result);
end;
procedure TPascalParser.Parse_FunctionDeclaration(IsSharedMethod: Boolean = false);
var
SubId, TypeId, ForwardId: Integer;
DirectiveList: TIntegerList;
L: TIntegerList;
NotDeclared, WaitOverload: Boolean;
K: Integer;
begin
DECLARE_SWITCH := true;
K := 0;
BeginMethodDef;
try
NotDeclared := false;
WaitOverload := false;
if IsSharedMethod then
begin
ForwardId := ReadType;
if ForwardId = 0 then
CreateError(errUndeclaredIdentifier, [CurrToken.Text]);
Call_SCANNER;
DECLARE_SWITCH := true;
Scanner.CurrComment.AllowedDoComment := false;
Match('.');
SubId := Parse_Ident;
BeginClassMethod(SubId, ForwardId, true, true, true);
end
else
begin
ForwardId := ReadType;
if (ForwardId > 0) and (GetKind(ForwardId) = KindTYPE) then
begin
Call_SCANNER;
while GetNext2Text = '.' do
begin
Inc(K);
levelStack.Push(ForwardId);
ReadToken;
ForwardId := Lookup(CurrToken.Text, CurrLevel);
if ForwardId = 0 then
RaiseError(errUndeclaredIdentifier, [CurrToken.Text]);
ReadToken;
end;
DECLARE_SWITCH := true;
Scanner.CurrComment.AllowedDoComment := false;
Match('.');
SubId := Parse_Ident;
if Lookup(GetName(SubId), ForwardId) = 0 then
NotDeclared := true;
BeginClassMethod(SubId, ForwardId, true, false, true);
end
else
begin
if ForwardId > 0 then
if GetKind(ForwardId) in KindSUBS then
if not GetSymbolRec(ForwardId).IsForward then
if GetSymbolRec(ForwardId).OverCount = 0 then
RaiseError(errRedeclaredIdentifier, [CurrToken.Text])
else
WaitOverload := true;
SubId := NewVar(CurrToken.Text);
SetPosition(SubId, CurrToken.Position - 1);
Parse_Ident;
BeginSub(SubId);
end;
end;
Parse_FormalParameterList(SubId);
DECLARE_SWITCH := false;
if IsCurrText(';') then
begin
L := LookupForwardDeclarations(SubId);
if L = nil then
RaiseError(errUnsatisfiedForwardOrExternalDeclaration, [GetName(SubId)])
else
FreeAndNil(L);
end
else
begin
Match(':');
Parse_Attribute;
TypeID := Parse_Type;
Gen(OP_ASSIGN_TYPE, SubId, TypeID, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, TypeID, 0);
end;
DECLARE_SWITCH := true;
if IsCurrText(';') then
Match(';');
if NotDeclared then
CreateError(errUndeclaredIdentifier, [GetName(SubId)]);
DirectiveList := Parse_DirectiveList(SubId);
try
if DirectiveList.IndexOf(dirFORWARD) >= 0 then
begin
SetForward(SubId, true);
EndSub(SubId);
Exit;
end;
if WaitOverload then
if DirectiveList.IndexOf(dirOVERLOAD) = -1 then
CreateError(errOverloadExpected, [GetName(SubId)]);
finally
FreeAndNil(DirectiveList);
end;
if IsCurrText('external') then
begin
ParseExternalSub(SubId);
Exit;
end;
InitSub(SubId);
if ForwardId > 0 then
if not GetSymbolRec(ForwardId).IsForward then
CheckRedeclaredSub(SubId);
if InitFuncResult then
Gen(OP_CALL_DEFAULT_CONSTRUCTOR, CurrResultId, 0, 0);
Parse_SubBlock;
EndSub(SubId);
EndMethodDef(SubId);
Match(';');
finally
while K > 0 do
begin
Dec(K);
levelStack.Pop;
end;
end;
end;
procedure TPascalParser.Parse_OperatorDeclaration;
var
I, SubId, TypeId, ForwardId: Integer;
L: TIntegerList;
NotDeclared: Boolean;
begin
NotDeclared := false;
ReadToken;
ForwardId := Lookup(CurrToken.Text, CurrLevel);
if ForwardId = 0 then
CreateError(errUndeclaredIdentifier, [CurrToken.Text]);
Call_SCANNER;
DECLARE_SWITCH := true;
Match('.');
I := OperatorIndex(CurrToken.Text);
if I = -1 then
CreateError(errE2393, []);
// errE2393 = 'Invalid operator declaration';
SubId := Parse_Ident;
SetName(SubId, operators.Values[I]);
BeginStructureOperator(SubId, ForwardId);
Parse_FormalParameterList(SubId);
DECLARE_SWITCH := false;
if IsCurrText(';') then
begin
L := LookupForwardDeclarations(SubId);
if L = nil then
RaiseError(errUnsatisfiedForwardOrExternalDeclaration, [GetName(SubId)])
else
FreeAndNil(L);
end
else
begin
Match(':');
Parse_Attribute;
TypeID := Parse_Type;
Gen(OP_ASSIGN_TYPE, SubId, TypeID, 0);
Gen(OP_ASSIGN_TYPE, CurrResultId, TypeID, 0);
end;
DECLARE_SWITCH := true;
Match(';');
if NotDeclared then
CreateError(errUndeclaredIdentifier, [GetName(SubId)]);
if IsCurrText('external') then
begin
ParseExternalSub(SubId);
Exit;
end;
InitSub(SubId);
if ForwardId > 0 then
if not GetSymbolRec(ForwardId).IsForward then
if not StrEql(GetName(SubId), pascal_Implicit) then
if not StrEql(GetName(SubId), pascal_Explicit) then
CheckRedeclaredSub(SubId);
Parse_SubBlock;
EndSub(SubId);
Match(';');
end;
procedure TPascalParser.Parse_ConstructorDeclaration;
var
ClassTypeId, SubId, L: Integer;
DirectiveList: TIntegerList;
OldSubId: Integer;
K, ForwardId: Integer;
begin
DECLARE_SWITCH := true;
K := 0;
ClassTypeId := 0;
BeginMethodDef;
try
ForwardId := ReadType;
if (ForwardId > 0) and (GetKind(ForwardId) = KindTYPE) then
begin
Call_SCANNER;
while GetNext2Text = '.' do
begin
Inc(K);
levelStack.Push(ForwardId);
ReadToken;
ForwardId := Lookup(CurrToken.Text, CurrLevel);
if ForwardId = 0 then
RaiseError(errUndeclaredIdentifier, [CurrToken.Text]);
ReadToken;
end;
ClassTypeId := ForwardId;
DECLARE_SWITCH := true;
Match('.');
SubId := Parse_Ident;
if GetSymbolRec(ClassTypeId).FinalTypeId = typeRECORD then
BeginStructureConstructor(SubId, ClassTypeId)
else
BeginClassConstructor(SubId, ClassTypeId);
end
else
RaiseError(errUndeclaredIdentifier, [CurrToken.Text]);
Parse_FormalParameterList(SubId);
Inc(EXECUTABLE_SWITCH);
Match(';');
DirectiveList := Parse_DirectiveList(SubId);
if DirectiveList.IndexOf(dirFORWARD) >= 0 then
begin
SetForward(SubId, true);
EndSub(SubId);
FreeAndNil(DirectiveList);
Dec(EXECUTABLE_SWITCH);
Exit;
end;
FreeAndNil(DirectiveList);
OldSubId := SubId;
InitSub(SubId);
if OldSubId = SubId then
RaiseError(errUndeclaredIdentifier, [GetName(OldSubId)]);
if GetSymbolRec(ClassTypeId).FinalTypeId = typeRECORD then
begin
Parse_SubBlock;
end
else
begin
WasInherited := false;
Gen(OP_SAVE_EDX, 0, 0, 0);
L := NewLabel;
Gen(OP_GO_DL, L, 0, 0);
Gen(OP_CREATE_OBJECT, ClassTypeId, 0, CurrSelfId);
SetLabelHere(L);
Parse_SubBlock;
// if not WasInherited then
// CreateError(errTheCallOfInheritedConstructorIsMandatory, []);
Gen(OP_RESTORE_EDX, 0, 0, 0);
L := NewLabel;
Gen(OP_GO_DL, L, 0, 0);
Gen(OP_ON_AFTER_OBJECT_CREATION, CurrSelfId, 0, 0);
SetLabelHere(L);
end;
EndSub(SubId);
Dec(EXECUTABLE_SWITCH);
EndMethodDef(SubId);
Match(';');
finally
while K > 0 do
begin
Dec(K);
levelStack.Pop;
end;
end;
end;
procedure TPascalParser.Parse_DestructorDeclaration;
var
ClassTypeId, SubId, NP: Integer;
DirectiveList: TIntegerList;
OldSubId: Integer;
K: Integer;
begin
DECLARE_SWITCH := true;
K := 0;
BeginMethodDef;
try
ClassTypeId := ReadType;
if (ClassTypeId > 0) and (GetKind(ClassTypeId) = KindTYPE) then
begin
Call_SCANNER;
while GetNext2Text = '.' do
begin
Inc(K);
levelStack.Push(ClassTypeId);
ReadToken;
ClassTypeId := Lookup(CurrToken.Text, CurrLevel);
if ClassTypeId = 0 then
RaiseError(errUndeclaredIdentifier, [CurrToken.Text]);
ReadToken;
end;
DECLARE_SWITCH := true;
Match('.');
SubId := Parse_Ident;
BeginClassDestructor(SubId, ClassTypeId);
end
else
RaiseError(errUndeclaredIdentifier, [CurrToken.Text]);
NP := 0;
if IsCurrText('(') then
begin
Call_SCANNER;
Match(')');
end;
SetCount(SubId, NP);
Inc(EXECUTABLE_SWITCH);
Match(';');
DirectiveList := Parse_DirectiveList(SubId);
if DirectiveList.IndexOf(dirFORWARD) >= 0 then
begin
SetForward(SubId, true);
EndSub(SubId);
FreeAndNil(DirectiveList);
Dec(EXECUTABLE_SWITCH);
Exit;
end;
FreeAndNil(DirectiveList);
OldSubId := SubId;
InitSub(SubId);
if OldSubId = SubId then
RaiseError(errUndeclaredIdentifier, [GetName(OldSubId)]);
Parse_SubBlock;
EndSub(SubId);
Dec(EXECUTABLE_SWITCH);
EndMethodDef(SubId);
Match(';');
finally
while K > 0 do
begin
Dec(K);
levelStack.Pop;
end;
end;
end;
// STATEMENTS
procedure TPascalParser.Parse_CompoundStmt;
begin
Inc(EXECUTABLE_SWITCH);
DECLARE_SWITCH := false;
Match('begin');
Parse_StmtList;
Match('end');
Dec(EXECUTABLE_SWITCH);
end;
procedure TPascalParser.Parse_StmtList;
begin
DECLARE_SWITCH := false;
repeat
if IsEOF then
break;
if IsCurrText('end') then
break;
if IsCurrText('finalization') then
break;
Parse_Statement;
if NotMatch(';') then break;
until false;
end;
procedure TPascalParser.Parse_AssignmentStmt;
var
I, LeftID, RightId, SizeId, SubId, L, ID1, ID2: Integer;
R: TCodeRec;
Lst: TIntegerList;
// SignProp: Boolean;
K1: Integer;
begin
if IsCurrText('inherited') then
begin
Call_SCANNER;
LeftId := NewTempVar;
if IsCurrText(';') or IsCurrText('else') then
begin
SubId := CurrLevel;
L := NewTempVar;
SetName(L, GetName(SubId));
Gen(OP_EVAL, 0, 0, L);
Gen(OP_EVAL_INHERITED, L, 0, LeftId);
for I:=0 to GetCount(SubId) - 1 do
Gen(OP_PUSH, GetParamId(SubId, I), I, LeftId);
Gen(OP_CALL_INHERITED, LeftID, 0, 0);
end
else
begin
L := Parse_Ident;
if IsCurrText('[') then
begin
// SignProp := true;
RemoveInstruction(OP_EVAL, -1, -1, L);
end
else
begin
RemoveInstruction(OP_EVAL, -1, -1, L);
// SignProp := false;
end;
Gen(OP_EVAL_INHERITED, L, 0, LeftId);
if IsCurrText('(') or IsCurrText('[') then
Gen(OP_CALL_INHERITED, LeftID, Parse_ArgumentList(LeftId), 0)
else
Gen(OP_CALL_INHERITED, LeftID, 0, 0);
// if SignProp then
if IsCurrText(':=') then
begin
K1 := CodeCard;
Call_SCANNER;
Gen(OP_PUSH, Parse_Expression, GetCodeRec(K1).Arg2, LeftId);
GetCodeRec(K1).Arg2 := GetCodeRec(K1).Arg2 + 1;
Gen(OP_CALL, LeftId, GetCodeRec(K1).Arg2, 0);
GetCodeRec(K1).Op := OP_NOP;
Exit;
end;
end;
if GetKind(CurrSubId) = kindCONSTRUCTOR then
begin
Gen(OP_RESTORE_EDX, 0, 0, 0);
L := NewLabel;
Gen(OP_GO_DL, L, 0, 0);
Gen(OP_ONCREATE_OBJECT, CurrSelfId, 0, 0);
SetLabelHere(L);
Gen(OP_SAVE_EDX, 0, 0, 0);
WasInherited := true;
end;
Exit;
end
else if IsCurrText('Include') and (not InScope('Include')) then
begin
RemoveInstruction(OP_EVAL, -1, -1, -1);
Call_SCANNER;
Match('(');
ID1 := Parse_Expression;
Match(',');
ID2 := Parse_Expression;
Match(')');
Gen(OP_SET_INCLUDE, ID1, ID2, 0);
Exit;
end
else if IsCurrText('Exclude') and (not InScope('Exclude')) then
begin
RemoveInstruction(OP_EVAL, -1, -1, -1);
Call_SCANNER;
Match('(');
ID1 := Parse_Expression;
Match(',');
ID2 := Parse_Expression;
Match(')');
Gen(OP_SET_EXCLUDE, ID1, ID2, 0);
Exit;
end
else if IsCurrText('inc') and (not InScope('inc')) then
begin
Call_SCANNER;
if not IsCurrText('(') then
RaiseError(errTokenExpected, ['(', CurrToken.Text]);
Push_SCANNER;
Call_SCANNER;
ID1 := Parse_Designator;
Pop_SCANNER;
Call_SCANNER;
ID2 := Parse_Designator;
if IsCurrText(',') then
begin
Call_SCANNER;
Gen(OP_INC, ID2, Parse_Expression, ID1);
end
else
Gen(OP_INC, ID2, NewConst(typeINTEGER, 1), ID1);
Match(')');
Exit;
end
else if IsCurrText('dec') and (not InScope('dec')) then
begin
Call_SCANNER;
if not IsCurrText('(') then
RaiseError(errTokenExpected, ['(', CurrToken.Text]);
Push_SCANNER;
Call_SCANNER;
ID1 := Parse_Designator;
Pop_SCANNER;
Call_SCANNER;
ID2 := Parse_Designator;
if IsCurrText(',') then
begin
Call_SCANNER;
Gen(OP_DEC, ID2, Parse_Expression, ID1);
end
else
Gen(OP_DEC, ID2, NewConst(typeINTEGER, 1), ID1);
Match(')');
Exit;
end
else if IsCurrText('SetLength') and (not InScope('SetLength')) then
begin
Lst := TIntegerList.Create;
try
Call_SCANNER;
Match('(');
LeftID := Parse_Designator;
Call_SCANNER;
repeat
Lst.Add(Parse_Expression);
if NotMatch(',') then
break;
until false;
if Lst.Count = 1 then
Gen(OP_SET_LENGTH, LeftID, Lst[0], 0)
else
begin
for I := 0 to Lst.Count - 1 do
Gen(OP_PUSH_LENGTH, Lst[I], 0, 0);
Gen(OP_SET_LENGTH_EX, LeftID, Lst.Count, 0);
end;
Match(')');
finally
FreeAndNil(Lst);
end;
Exit;
end
else if IsCurrText('str') and (not InScope('str')) then
begin
LeftID := NewTempVar;
Call_SCANNER;
Match('(');
try
Gen(OP_PUSH, Parse_Expression, 3, LeftID);
if IsCurrText(':') then
begin
Call_SCANNER;
Gen(OP_PUSH, Parse_Expression, 2, LeftID);
end
else
Gen(OP_PUSH, NewConst(typeINTEGER, 0), 2, LeftID);
if IsCurrText(':') then
begin
Call_SCANNER;
Gen(OP_PUSH, Parse_Expression, 1, LeftID);
end
else
Gen(OP_PUSH, NewConst(typeINTEGER, 0), 1, LeftID);
Match(',');
Gen(OP_PUSH, Parse_Expression, 0, LeftID);
finally
Gen(OP_STR, LeftID, 0, 0);
end;
Match(')');
Exit;
end
else if IsCurrText('new') and (not InScope('new')) then
begin
SetCompletionTarget('new');
Call_SCANNER;
Match('(');
LeftId := Parse_Designator;
SizeId := NewTempVar;
SubId := NewTempVar;
SetName(SubId, 'GetMem');
SetKind(SubId, kindNONE);
Gen(OP_EVAL, 0, 0, SubId);
Gen(OP_SIZEOF, LeftId, 0, SizeId);
Gen(OP_PUSH, LeftId, 0, SubId);
Gen(OP_PUSH, SizeId, 1, SubId);
Gen(OP_CALL, SubId, 0, 0);
Match(')');
Exit;
end
else if IsCurrText('dispose') and (not InScope('dispose')) then
begin
SetCompletionTarget('Dispose');
Call_SCANNER;
Match('(');
LeftId := Parse_Designator;
SizeId := NewTempVar;
SubId := NewTempVar;
SetName(SubId, 'FreeMem');
SetKind(SubId, kindNONE);
Gen(OP_EVAL, 0, 0, SubId);
Gen(OP_SIZEOF, LeftId, 0, SizeId);
Gen(OP_PUSH, LeftId, 0, SubId);
Gen(OP_PUSH, SizeId, 1, SubId);
Gen(OP_CALL, SubId, 0, 0);
Match(')');
Exit;
end
else if IsCurrText('pause') and (not InScope('pause')) then
begin
Call_SCANNER;
if IsCurrText('(') then
begin
Match('(');
Match(')');
end;
L := NewLabel;
Gen(OP_PAUSE, L, 0, 0);
SetLabelHere(L);
Exit;
end
else if IsCurrText('halt') or IsCurrText('abort') then
begin
Call_SCANNER;
if IsCurrText('(') then
begin
Match('(');
if not IsCurrText(')') then
begin
Gen(OP_HALT, Parse_ConstantExpression, 0, 0);
end
else
Gen(OP_HALT, NewConst(typeINTEGER, 0), 0, 0);
Match(')');
end
else
Gen(OP_HALT, NewConst(typeINTEGER, 0), 0, 0);
Exit;
end;
if IsCurrText('(') then
LeftID := Parse_Factor
else
LeftID := Parse_SimpleExpression;
if IsEOF then
Exit;
if IsCurrText(';') or (CurrToken.TokenClass = tcKeyword) then
begin
R := LastCodeRec;
if R.Op = OP_CALL then
begin
SetKind(R.Res, KindNONE);
R.Res := 0;
end
else if GetKind(LeftId) = kindCONST then
RaiseError(errIdentifierExpectedNoArgs, [])
else
begin
{$IFDEF CPP_SYN}
if (R.Arg1 = LeftId) and (R.Op = OP_ASSIGN) then
begin
if (LastCodeRec2.Op = OP_PLUS) or (LastCodeRec2.Op = OP_MINUS) then
Exit;
end
else if R.Op = OP_POSTFIX_EXPRESSION then
Exit;
{$ENDIF}
Gen(OP_CALL, LeftID, 0, 0);
end;
Exit;
end;
Gen(OP_LVALUE, LeftId, 0, 0);
if IsCurrText(':=') then
begin
Call_SCANNER;
RightId := Parse_Expression;
Gen(OP_ASSIGN, LeftID, RightId, LeftID);
end
{$IFDEF CPP_SYN}
else if IsCurrText('+=') then
begin
Call_SCANNER;
ID1 := NewTempVar;
Gen(OP_PLUS, LeftId, Parse_Expression, ID1);
Gen(OP_ASSIGN, LeftId, ID1, LeftId);
end
else if IsCurrText('-=') then
begin
Call_SCANNER;
ID1 := NewTempVar;
Gen(OP_MINUS, LeftId, Parse_Expression, ID1);
Gen(OP_ASSIGN, LeftId, ID1, LeftId);
end
else if IsCurrText('*=') then
begin
Call_SCANNER;
ID1 := NewTempVar;
Gen(OP_MULT, LeftId, Parse_Expression, ID1);
Gen(OP_ASSIGN, LeftId, ID1, LeftId);
end
else if IsCurrText('/=') then
begin
Call_SCANNER;
ID1 := NewTempVar;
Gen(OP_DIV, LeftId, Parse_Expression, ID1);
Gen(OP_ASSIGN, LeftId, ID1, LeftId);
end
else if IsCurrText('~=') then
begin
Call_SCANNER;
ID1 := NewTempVar;
Gen(OP_IDIV, LeftId, Parse_Expression, ID1);
Gen(OP_ASSIGN, LeftId, ID1, LeftId);
end
else if IsCurrText('%=') then
begin
Call_SCANNER;
ID1 := NewTempVar;
Gen(OP_MOD, LeftId, Parse_Expression, ID1);
Gen(OP_ASSIGN, LeftId, ID1, LeftId);
end
else if IsCurrText('^=') then
begin
Call_SCANNER;
ID1 := NewTempVar;
Gen(OP_XOR, LeftId, Parse_Expression, ID1);
Gen(OP_ASSIGN, LeftId, ID1, LeftId);
end
else if IsCurrText('|=') then
begin
Call_SCANNER;
ID1 := NewTempVar;
Gen(OP_OR, LeftId, Parse_Expression, ID1);
Gen(OP_ASSIGN, LeftId, ID1, LeftId);
end
else if IsCurrText('&=') then
begin
Call_SCANNER;
ID1 := NewTempVar;
Gen(OP_AND, LeftId, Parse_Expression, ID1);
Gen(OP_ASSIGN, LeftId, ID1, LeftId);
end
{$ENDIF}
else if IsCurrText('(') then
begin
R := Gen(OP_CALL, LeftID, Parse_ArgumentList(LeftId), 0);
if IsCurrText(':=') then
begin
R.Res := NewTempVar;
Call_SCANNER;
Gen(OP_ASSIGN, R.Res, Parse_Expression, R.Res);
end
else if IsCurrText('(') then
begin
R.Res := NewTempVar;
Gen(OP_CALL, R.Res, Parse_ArgumentList(R.Res), 0);
end;
end
else
begin
Gen(OP_CALL, LeftID, 0, 0);
end;
end;
procedure TPascalParser.Parse_CaseStmt;
var
lg, lf, lt, lc, id, expr1_id, cond_id: Integer;
begin
Match('case');
lg := NewLabel;
cond_id := NewTempVar;
id := NewTempVar;
Gen(OP_ASSIGN, Id, Parse_Expression, id);
Match('of');
repeat
// Parse case selector
lt := NewLabel;
lf := NewLabel;
repeat
lc := NewLabel;
expr1_id := Parse_ConstantExpression;
if IsCurrText('..') then
begin
Gen(OP_GE, id, expr1_id, cond_id);
Gen(OP_GO_FALSE, lc, cond_id, 0);
Match('..');
Gen(OP_LE, id, Parse_ConstantExpression, cond_id);
Gen(OP_GO_FALSE, lc, cond_id, 0);
end
else
Gen(OP_EQ, id, expr1_id, cond_id);
Gen(OP_GO_TRUE, lt, cond_id, 0);
SetLabelHere(lc);
if NotMatch(',') then
break;
until false;
Gen(OP_GO, lf, 0, 0);
SetLabelHere(lt);
Match(':');
if IsCurrText(';') then
begin
end
else
Parse_Statement;
Gen(OP_GO, lg, 0, 0);
SetLabelHere(lf);
// end of case selector
if NotMatch(';') then
Break;
if IsCurrText('else') then
break;
if IsCurrText('end') then
break;
until false;
if IsCurrText('else') then
begin
Match('else');
Parse_StmtList;
end;
if IsCurrText(';') then
Match(';');
Match('end');
SetLabelHere(lg);
end;
procedure TPascalParser.Parse_IfStmt;
var
lf, lg: Integer;
begin
Match('if');
lf := NewLabel;
Gen(OP_GO_FALSE, lf, Parse_Expression, 0);
Match('then');
if not IsCurrText('else') then
Parse_Statement;
if IsCurrText('else') then
begin
Gen(OP_NOP, 0, 0, 0);
lg := NewLabel();
Gen(OP_GO, lg, 0, 0);
SetLabelHere(lf);
Match('else');
Parse_Statement;
SetLabelHere(lg);
end
else
SetLabelHere(lf);
end;
procedure TPascalParser.Parse_GotoStmt;
begin
Match('goto');
Gen(OP_GO, Parse_Label, 0, 0);
end;
procedure TPascalParser.Parse_BreakStmt;
begin
if BreakStack.Count = 0 then
RaiseError(errBreakOrContinueOutsideOfLoop, []);
Match('break');
if IsCurrText('(') then
begin
Match('(');
Match(')');
end;
if not SupportedSEH then
Gen(OP_GO, BreakStack.TopLabel, 0, 0)
else
begin
if IsTryContext(BreakStack.Top) then
Gen(OP_EXIT, BreakStack.TopLabel, Integer(emBreak), CurrLevel)
else
Gen(OP_GO, BreakStack.TopLabel, 0, 0);
end;
end;
procedure TPascalParser.Parse_ContinueStmt;
begin
if ContinueStack.Count = 0 then
RaiseError(errBreakOrContinueOutsideOfLoop, []);
Match('continue');
if IsCurrText('(') then
begin
Match('(');
Match(')');
end;
if not SupportedSEH then
Gen(OP_GO, ContinueStack.TopLabel, 0, 0)
else
begin
if IsTryContext(ContinueStack.Top) then
Gen(OP_EXIT, ContinueStack.TopLabel, Integer(emContinue), CurrLevel)
else
Gen(OP_GO, ContinueStack.TopLabel, 0, 0);
end;
end;
procedure TPascalParser.Parse_ExitStmt;
begin
Match('exit');
if IsCurrText('(') then
begin
Match('(');
Match(')');
end;
if not SupportedSEH then
Gen(OP_GO, SkipLabelStack.Top, 0, CurrLevel)
else
Gen(OP_EXIT, SkipLabelStack.Top, 0, CurrLevel);
end;
procedure TPascalParser.Parse_WhileStmt;
var
lf, lg, l_loop: Integer;
begin
Match('while');
lf := NewLabel;
lg := NewLabel;
SetLabelHere(lg);
l_loop := lg;
Gen(OP_GO_FALSE, lf, Parse_Expression, 0);
Match('do');
Parse_LoopStmt(lf, lg, l_loop);
Gen(OP_GO, lg, 0, 0);
SetLabelHere(lf);
end;
procedure TPascalParser.Parse_RepeatStmt;
var
lf, lg, l_loop: Integer;
begin
Match('repeat');
lf := NewLabel;
lg := NewLabel;
SetLabelHere(lf);
l_loop := lf;
repeat
if IsCurrText('until') then
Break;
if IsEOF then
Break;
Parse_LoopStmt(lg, lf, l_loop);
if NotMatch(';') then
Break;
until false;
Match('until');
Gen(OP_GO_FALSE, lf, Parse_Expression, 0);
SetLabelHere(lg);
end;
procedure TPascalParser.Parse_ForStmt;
var
id, expr1_id, expr2_id, limit_cond_id1, limit_cond_id2: Integer;
i, compound: Boolean;
lf, lg, lc, l_loop: Integer;
element_id, collection_id, enumerator_id, bool_id: Integer;
begin
l_loop := NewLabel;
SetLabelHere(l_loop);
Match('for');
if IsNextText('in') then
begin
Inc(ForInCounter);
lf := NewLabel;
lg := NewLabel;
lc := NewLabel;
enumerator_id := NewTempVar;
bool_id := NewTempVar;
element_id := Parse_Ident;
Match('in');
collection_id := Parse_Expression;
Match('do');
Gen(OP_LOCK_VARRAY, collection_id, ForInCounter, 0);
Gen(OP_GET_ENUMERATOR, collection_id, ForInCounter, enumerator_id);
SetLabelHere(lg);
Gen(OP_CURRENT, enumerator_id, ForInCounter, element_id);
compound := Parse_LoopStmt(lf, lc, l_loop);
SetLabelHere(lc, ForInCounter);
if not compound then
GenPause;
Gen(OP_MOVE_NEXT, element_id, ForInCounter, bool_id);
Gen(OP_GO_FALSE, lf, bool_id, 0);
Gen(OP_GO, lg, 0, 0);
SetLabelHere(lf, 0, ForInCounter);
Gen(OP_UNLOCK_VARRAY, collection_id, ForInCounter, 0);
Exit;
end;
lf := NewLabel;
lg := NewLabel;
lc := NewLabel;
limit_cond_id1 := NewTempVar;
limit_cond_id2 := NewTempVar;
expr1_id := NewTempVar;
expr2_id := NewTempVar;
id := Parse_Ident;
Match(':=');
Gen(OP_ASSIGN, expr1_id, Parse_Expression, expr1_id);
Gen(OP_ASSIGN, id, expr1_id, id);
if IsCurrText('downto') then
begin
Match('downto');
Gen(OP_ASSIGN, expr2_id, Parse_Expression, expr2_id);
Gen(OP_LT, id, expr2_id, limit_cond_id1);
i := false;
end
else
begin
Match('to');
Gen(OP_ASSIGN, expr2_id, Parse_Expression, expr2_id);
Gen(OP_GT, id, expr2_id, limit_cond_id1);
i := true;
end;
Gen(OP_GO_TRUE, lg, limit_cond_id1, 0);
Match('do');
SetLabelHere(lf);
compound := Parse_LoopStmt(lg, lc, l_loop);
SetLabelHere(lc);
if i then
begin
Gen(OP_INC, id, NewConst(typeINTEGER, 1), id);
Gen(OP_GT, id, expr2_id, limit_cond_id2);
end
else
begin
Gen(OP_DEC, id, NewConst(typeINTEGER, 1), id);
Gen(OP_LT, id, expr2_id, limit_cond_id2);
end;
if not compound then
GenPause;
Gen(OP_GO_FALSE, lf, limit_cond_id2, 0);
SetLabelHere(lg);
end;
procedure TPascalParser.Parse_WithStmt;
var
id, K: Integer;
begin
K := WithStack.Count;
Match('with');
repeat
id := Parse_Expression;
Gen(OP_BEGIN_WITH, id, 0, 0);
WithStack.Push(id);
if NotMatch(',') then
Break;
until false;
Match('do');
Parse_Statement;
while WithStack.Count > K do
begin
id := WithStack.Top;
Gen(OP_END_WITH, id, 0, 0);
WithStack.Pop;
end;
end;
procedure TPascalParser.Parse_TryStmt;
var
id, type_id, l_try, BlockId: Integer;
begin
if not SupportedSEH then
RaiseError(errTryExceptNotImplemented, []);
l_try := GenBeginTry;
Match('try');
repeat
if IsCurrText('except') then
Break;
if IsCurrText('finally') then
Break;
if IsEOF then
Break;
Parse_Statement;
if NotMatch(';') then
Break;
until false;
Gen(OP_EXCEPT_SEH, 0, 0, 0);
if IsCurrText('except') then
begin
Gen(OP_GO, l_try, 0, 0);
GenExcept;
Call_SCANNER;
//ExceptionBlock
if IsCurrText('on') then
begin
while IsCurrText('on') do
begin
BlockId := NewTempVar;
LevelStack.push(BlockId);
Gen(OP_BEGIN_BLOCK, BlockId, 0, 0);
if IsNext2Text(':') then
begin
DECLARE_SWITCH := true;
Match('on');
id := Parse_Ident;
DECLARE_SWITCH := false;
Match(':');
type_id := Parse_Ident;
end
else
begin
DECLARE_SWITCH := false;
Match('on');
type_id := Parse_Ident;
id := NewTempVar;
end;
Gen(OP_ASSIGN_TYPE, id, type_id, 0);
GenExceptOn(type_id);
Gen(OP_ASSIGN, id, CurrExceptionObjectId, id);
Gen(OP_BEGIN_EXCEPT_BLOCK, 0, 0, 0);
Match('do');
Parse_Statement;
Gen(OP_END_EXCEPT_BLOCK, 0, 0, 0);
Gen(OP_GO, l_try, 0, 0);
Gen(OP_END_BLOCK, BlockId, 0, 0);
LevelStack.Pop;
if IsCurrText(';') then
Match(';');
end;
GenExceptOn(0);
if IsCurrText('else') then
begin
Gen(OP_BEGIN_EXCEPT_BLOCK, 0, 0, 0);
Call_SCANNER;
Parse_Statement;
if IsCurrText(';') then
Match(';');
Gen(OP_END_EXCEPT_BLOCK, 0, 0, 0);
end;
end
else
begin
Gen(OP_BEGIN_EXCEPT_BLOCK, 0, 0, 0);
repeat
if IsCurrText('end') then
Break;
if IsEOF then
Break;
Parse_Statement;
if NotMatch(';') then
Break;
until false;
Gen(OP_END_EXCEPT_BLOCK, 0, 0, 0);
end;
end // except
else if IsCurrText('finally') then
begin
GenFinally;
Call_SCANNER;
repeat
if IsCurrText('end') then
Break;
if IsEOF then
Break;
Parse_Statement;
if NotMatch(';') then
Break;
until false;
GenCondRaise;
end // finally
else
Match('finally');
SetLabelHere(l_try);
GenEndTry;
Match('end');
end;
procedure TPascalParser.Parse_RaiseStmt;
begin
if not SupportedSEH then
RaiseError(errRaiseNotImplemented, []);
Match('raise');
if IsCurrText(';') then
Gen(OP_RAISE, 0, RaiseMode, 0)
else
begin
Gen(OP_RAISE, Parse_Expression, RaiseMode, 0);
end;
end;
// EXPRESSIONS
function TPascalParser.Parse_ArgumentList(SubId: Integer): Integer;
var
I: Integer;
L: TIntegerList;
bracket: String;
begin
try
bracket := ')';
L := TIntegerList.Create;
try
if IsCurrText('(') then
begin
Match('(');
bracket := ')';
end
else if IsCurrText('[') then
begin
Match('[');
bracket := ']';
end
else
Match('(');
result := 0;
if (not IsCurrText(')')) then
begin
repeat
Inc(result);
L.Add(Parse_Expression);
if NotMatch(',') then
Break;
until false;
end;
for I:=0 to L.Count - 1 do
Gen(OP_PUSH, L[I], I, SubID);
Match(bracket);
finally
FreeAndNil(L);
end;
except
Gen(OP_CALL, SubId, 0, 0);
raise;
end;
end;
function TPascalParser.Parse_ConstantExpression: Integer;
begin
try
CONST_ONLY := true;
result := Parse_Expression;
finally
CONST_ONLY := false;
end;
end;
function TPascalParser.Parse_Expression: Integer;
var
Op: Integer;
begin
if IsCurrText('procedure') then
begin
result := Parse_AnonymousProcedure;
Exit;
end
else if IsCurrText('function') then
begin
result := Parse_AnonymousFunction;
Exit;
end
else if IsCurrText('lambda') then
begin
RemoveLastIdent(CurrToken.Id);
result := Parse_LambdaExpression;
Exit;
end;
result := Parse_SimpleExpression;
while (CurrToken.Id = OP_LT) or
(CurrToken.Id = OP_LE) or
(CurrToken.Id = OP_GT) or
(CurrToken.Id = OP_GE) or
(CurrToken.Id = OP_EQ) or
(CurrToken.Id = OP_NE) or
(CurrToken.Id = OP_IS) or
(CurrToken.Id = OP_AS) or
(CurrToken.Id = OP_SET_MEMBERSHIP) do
begin
Op := CurrToken.Id;
Call_SCANNER;
result := BinOp(Op, result, Parse_SimpleExpression);
end;
end;
function TPascalParser.Parse_SimpleExpression: Integer;
var
Op, L, I: Integer;
Lst: TCodeRecList;
R: TCodeRec;
begin
if CompleteBooleanEval then
begin
result := Parse_Term;
while IsCurrText('+') or
IsCurrText('-') or
IsCurrText('or') or
IsCurrText('xor') do
begin
Op := CurrToken.Id;
Call_SCANNER;
result := BinOp(Op, result, Parse_Term);
end;
Exit;
end;
L := 0;
Lst := TCodeRecList.Create;
try
result := Parse_Term;
while (CurrToken.Id = OP_PLUS) or
(CurrToken.Id = OP_MINUS) or
(CurrToken.Id = OP_OR) or
(CurrToken.Id = OP_XOR) do
begin
if (CurrToken.Id = OP_OR) and (Lst.Count = 0) then
L := NewLabel;
if CurrToken.Id = OP_OR then
begin
R := Gen(OP_ASSIGN, 0, result, 0);
Lst.Add(R);
Gen(OP_GO_TRUE_BOOL, L, result, 0);
end;
Op := CurrToken.Id;
Call_SCANNER;
result := BinOp(Op, result, Parse_Term);
end;
if Lst.Count > 0 then
begin
for I:=0 to Lst.Count - 1 do
begin
R := TCodeRec(Lst[I]);
R.Arg1 := result;
R.Res := result;
end;
SetLabelHere(L);
end;
finally
FreeAndNil(Lst);
end;
end;
function TPascalParser.Parse_Term: Integer;
var
Op, L, I: Integer;
Lst: TCodeRecList;
R: TCodeRec;
begin
if CompleteBooleanEval then
begin
result := Parse_Factor;
while (CurrToken.Id = OP_MULT) or
(CurrToken.Id = OP_DIV) or
(CurrToken.Id = OP_IDIV) or
(CurrToken.Id = OP_MOD) or
(CurrToken.Id = OP_SHL) or
(CurrToken.Id = OP_SHR) or
(CurrToken.Id = OP_AND) do
begin
Op := CurrToken.Id;
Call_SCANNER;
result := BinOp(Op, result, Parse_Factor);
end;
Exit;
end;
L := 0;
Lst := TCodeRecList.Create;
try
result := Parse_Factor;
while (CurrToken.Id = OP_MULT) or
(CurrToken.Id = OP_DIV) or
(CurrToken.Id = OP_IDIV) or
(CurrToken.Id = OP_MOD) or
(CurrToken.Id = OP_SHL) or
(CurrToken.Id = OP_SHR) or
(CurrToken.Id = OP_AND) do
begin
if (CurrToken.Id = OP_AND) and (Lst.Count = 0) then
L := NewLabel;
if CurrToken.Id = OP_AND then
begin
R := Gen(OP_ASSIGN, 0, result, 0);
Lst.Add(R);
Gen(OP_GO_FALSE_BOOL, L, result, 0);
end;
Op := CurrToken.Id;
Call_SCANNER;
result := BinOp(Op, result, Parse_Factor);
end;
if Lst.Count > 0 then
begin
for I:=0 to Lst.Count - 1 do
begin
R := TCodeRec(Lst[I]);
R.Arg1 := result;
R.Res := result;
end;
SetLabelHere(L);
end;
finally
FreeAndNil(Lst);
end;
end;
function TPascalParser.Parse_Factor: Integer;
var
SubId, K, Id: Integer;
ValidConst: Boolean;
{$IFDEF CPP_SYN}
temp, r: Integer;
{$ENDIF}
S: String;
v: Variant;
label
LabelDesignator;
begin
if CurrToken.TokenClass = tcBooleanConst then
begin
result := Parse_BooleanLiteral;
if IsCurrText('.') then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
result := Parse_Designator(result);
end;
end
else if CurrToken.TokenClass = tcCharConst then
begin
result := Parse_CharLiteral;
if IsCurrText('.') then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
result := Parse_Designator(result);
end;
end
else if CurrToken.TokenClass = tcPCharConst then
begin
result := Parse_PCharLiteral;
if IsCurrText('.') then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
result := Parse_Designator(result);
end;
end
else if CurrToken.TokenClass = tcIntegerConst then
begin
result := Parse_IntegerLiteral;
if IsCurrText('.') then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
result := Parse_Designator(result);
end;
end
else if CurrToken.TokenClass = tcDoubleConst then
begin
result := Parse_DoubleLiteral;
if IsCurrText('.') then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
result := Parse_Designator(result);
end;
end
else if IsCurrText('+') then
begin
Call_SCANNER;
result := UnaryOp(OP_POSITIVE, Parse_Factor);
end
else if IsCurrText('-') then
begin
Call_SCANNER;
ValidConst := CurrToken.TokenClass in [tcIntegerConst, tcDoubleConst];
Id := Parse_Factor;
if ValidConst then
begin
result := Id;
v := GetValue(id);
if v > 0 then
SetValue(Id, - v);
end
else
result := UnaryOp(OP_NEG, Id);
end
{$IFDEF CPP_SYN}
else if IsCurrText('++') then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
Call_SCANNER;
result := Parse_Expression;
Id := NewTempVar;
Gen(OP_PLUS, result, NewConst(typeINTEGER, 1), Id);
Gen(OP_ASSIGN, result, Id, result);
end
else if IsCurrText('--') then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
Call_SCANNER;
result := Parse_Expression;
Id := NewTempVar;
Gen(OP_MINUS, result, NewConst(typeINTEGER, 1), Id);
Gen(OP_ASSIGN, result, Id, result);
end
{$ENDIF}
else if IsCurrText('*') then
begin
Call_SCANNER;
result := UnaryOp(OP_POSITIVE, Parse_Factor);
end
else if IsCurrText('not') then
begin
Call_SCANNER;
result := UnaryOp(OP_NOT, Parse_Factor);
end
else if IsCurrText('(') then
begin
Match('(');
result := Parse_Expression;
Match(')');
if IsCurrText('.') or IsCurrText('[') then
result := Parse_Designator(result);
end
else if IsCurrText('[') then
begin
result := Parse_SetConstructor;
end
else if IsCurrText('@') then
begin
Match('@');
result := NewTempVar;
Gen(OP_ADDRESS, Parse_Designator, 0, result);
end
else if IsCurrText('assigned') and (not InScope('assigned')) then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
Call_SCANNER;
Match('(');
result := NewTempVar;
Gen(OP_ASSIGNED, Parse_Expression, 0, result);
Match(')');
Exit;
end
else if IsCurrText('sizeof') and (not InScope('sizeof')) then
begin
Match('sizeof');
Match('(');
result := NewTempVar;
Gen(OP_SIZEOF, Parse_Expression, 0, result);
Match(')');
end
else if IsCurrText('typeinfo') and (not InScope('typeinfo')) then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
Match('typeinfo');
Match('(');
result := NewTempVar;
SetType(result, typePOINTER);
Gen(OP_TYPEINFO, Parse_Expression, 0, result);
Match(')');
end
else if IsCurrText('pred') and (not InScope('pred')) then
begin
Match('pred');
Match('(');
result := NewTempVar;
Gen(OP_PRED, Parse_Expression, 0, result);
Match(')');
end
else if IsCurrText('succ') and (not InScope('succ')) then
begin
Match('succ');
Match('(');
result := NewTempVar;
Gen(OP_SUCC, Parse_Expression, 0, result);
Match(')');
end
else if IsCurrText('ord') and (not InScope('ord')) then
begin
Match('ord');
Match('(');
result := NewTempVar;
Gen(OP_ORD, Parse_Expression, 0, result);
Match(')');
end
else if IsCurrText('chr') and (not InScope('chr')) then
begin
Match('chr');
Match('(');
result := NewTempVar;
Gen(OP_CHR, Parse_Expression, 0, result);
Match(')');
end
else if IsCurrText('high') and (not InScope('high')) then
begin
Match('high');
Match('(');
result := NewTempVar;
Gen(OP_HIGH, Parse_Expression, 0, result);
Match(')');
end
else if IsCurrText('low') and (not InScope('low')) then
begin
Match('low');
Match('(');
result := NewTempVar;
Gen(OP_LOW, Parse_Expression, 0, result);
Match(')');
end
else if IsCurrText('abs') and (not InScope('abs')) then
begin
Match('abs');
Match('(');
result := NewTempVar;
Gen(OP_ABS, Parse_Expression, 0, result);
Match(')');
end
else if IsCurrText('length') and (not InScope('length')) then
begin
S := GetNext2Text;
Id := Lookup(S, CurrLevel);
if Id = 0 then
goto LabelDesignator;
if GetSymbolRec(Id).FinalTypeId <> typeOPENARRAY then
goto LabelDesignator;
Id := GetOpenArrayHighId(Id);
result := NewTempVar;
Gen(OP_PLUS, Id, NewConst(typeINTEGER, 1), result);
Match('length');
Match('(');
Parse_Expression;
Match(')');
end
else if IsCurrText('inherited') then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
Call_SCANNER;
SubId := NewTempVar;
result := NewTempVar;
K := Parse_Ident;
RemoveInstruction(OP_EVAL, -1, -1, K);
Gen(OP_EVAL_INHERITED, K, 0, SubId);
if IsCurrText('(') or IsCurrText('[') then
Gen(OP_CALL_INHERITED, SubID, Parse_ArgumentList(SubId), result)
else
Gen(OP_CALL_INHERITED, SubID, 0, result);
end
else
begin
LabelDesignator:
result := Parse_Designator;
if IsCurrText(':=') then
if GetSymbolRec(result).OwnerId = 0 then
if CurrLevel > 0 then
if GetKind(CurrLevel) in KindSUBS then
if (GetName(result) <> '') and StrEql(GetName(result), GetName(CurrSubId)) then
result := CurrResultId;
if IsCurrText('(') then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
SubId := result;
result := NewTempVar;
K := Parse_ArgumentList(SubId);
Gen(OP_CALL, SubID, K, result);
if IsCurrText('.') or IsCurrText('[') then
result := Parse_Designator(result);
end
else if GetKind(result) = KindSUB then
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
SubId := result;
result := NewTempVar;
SetName(result, GetName(SubId));
SetKind(result, KindNONE);
Gen(OP_EVAL, 0, 0, result);
if IsCurrText('.') or IsCurrText('[') then
result := Parse_Designator(result);
end;
{$IFDEF CPP_SYN}
if IsCurrText('++') then // post increment expression
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
Match('++');
temp := NewTempVar;
Gen(OP_ASSIGN, temp, result, temp);
r := NewTempVar;
Gen(OP_PLUS, result, NewConst(typeINTEGER, 1), r);
Gen(OP_ASSIGN, result, r, result);
Gen(OP_POSTFIX_EXPRESSION, 0, 0, 0);
result := temp;
end
else if IsCurrText('--') then // post decrement expression
begin
if CONST_ONLY then
CreateError(errConstantExpressionExpected, []);
Match('--');
temp := NewTempVar;
Gen(OP_ASSIGN, temp, result, temp);
r := NewTempVar;
Gen(OP_MINUS, result, NewConst(typeINTEGER, 1), r);
Gen(OP_ASSIGN, result, r, result);
Gen(OP_POSTFIX_EXPRESSION, 0, 0, 0);
result := temp;
end;
{$ENDIF}
end;
end;
function TPascalParser.Parse_SetConstructor: Integer;
var
id1, id2, k: Integer;
begin
Match('[');
if not IsCurrText(']') then
begin
k := 0;
result := NewTempVar;
repeat
if IsEOF then
break;
// parse member group
id1 := Parse_Expression;
if IsCurrText('..') then
begin
Match('..');
id2 := Parse_Expression;
Gen(OP_CHECK_SUBRANGE_TYPE, id1, id2, 0);
Gen(OP_SET_INCLUDE_INTERVAL, result, id1, id2);
end
else
Gen(OP_SET_INCLUDE, result, id1, 0);
Inc(k);
If NotMatch(',') then
break;
until false;
SetCount(result, k);
end
else
result := EmptySetId;
Match(']');
end;
function TPascalParser.Parse_Designator(init_id: Integer = 0): Integer;
var
ok: Boolean;
id: Integer;
S: String;
begin
if init_id = 0 then
result := Parse_QualId
else
result := init_id;
if IsOuterLocalVar(result) then
begin
AnonymStack.Top.BindList.Add(result);
S := GetName(result);
result := NewTempVar;
SetName(result, S);
Gen(OP_EVAL, 0, 0, result);
end;
repeat
if IsCurrText('.') then
begin
FIELD_OWNER_ID := result;
id := FIELD_OWNER_ID;
Match('.');
result := Parse_Ident;
Gen(OP_FIELD, id, result, result);
ok := true;
end
else if IsCurrText('[') then // index
begin
Match('[');
repeat
id := result;
result := NewTempVar;
Gen(OP_ELEM, id, Parse_Expression, result);
if NotMatch(',') then
Break;
until false;
Match(']');
ok := true;
end
else if IsCurrText('(') then
begin
Id := result;
result := NewTempVar;
Gen(OP_CALL, Id, Parse_ArgumentList(Id), result);
ok := true;
end
else if IsCurrText('^') then
begin
Match('^');
id := result;
result := NewTempVar;
Gen(OP_TERMINAL, id, 0, result);
ok := true;
end
else
ok := false;
until not ok;
end;
function TPascalParser.Parse_Label: Integer;
begin
if not (CurrToken.TokenClass in [tcIntegerConst, tcIdentifier]) then
RaiseError(errIdentifierExpected, [CurrToken.Text]);
result := CurrToken.Id;
if DECLARE_SWITCH then
SetKind(result, KindLABEL)
else if GetKind(result) <> KindLABEL then
RaiseError(errLabelExpected, []);
Call_SCANNER;
end;
function TPascalParser.Parse_Ident: Integer;
begin
if CurrToken.TokenClass = tcKeyword then
begin
if IsCurrText('nil') then
begin
result := NilId;
Call_SCANNER;
Exit;
end;
end;
result := inherited Parse_Ident;
end;
procedure TPascalParser.Call_SCANNER;
var
S: String;
begin
SetPrevToken;
inherited;
while CurrToken.TokenClass = tcSeparator do
begin
Gen(OP_SEPARATOR, CurrModule.ModuleNumber, CurrToken.Id, 0);
inherited Call_SCANNER;
end;
if CollectSig then
Sig := Sig + ' ' + CurrToken.Text;
if DECLARE_SWITCH then
Exit;
if CurrToken.TokenClass = tcKeyword then
begin
if StrEql(CurrToken.Text, 'String') then
begin
{$IFDEF PAXARM}
CurrToken.Id := typeUNICSTRING;
{$ELSE}
if IsUNIC then
CurrToken.Id := typeUNICSTRING
else
CurrToken.Id := typeANSISTRING;
{$ENDIF}
CurrToken.TokenClass := tcIdentifier;
Exit;
end
else if StrEql(CurrToken.Text, 'File') then
begin
CurrToken.Id := H_TFileRec;
CurrToken.TokenClass := tcIdentifier;
Exit;
end;
end;
if CurrToken.TokenClass = tcIdentifier then
begin
S := CurrToken.Text;
if StrEql(S, 'Char') then
begin
{$IFDEF PAXARM}
CurrToken.Id := typeWIDECHAR;
{$ELSE}
if IsUNIC then
CurrToken.Id := typeWIDECHAR
else
CurrToken.Id := typeANSICHAR;
{$ENDIF}
end
else if StrEql(S, 'PChar') then
begin
{$IFDEF PAXARM}
CurrToken.Id := typePWIDECHAR;
{$ELSE}
if IsUNIC then
CurrToken.Id := typePWIDECHAR
else
CurrToken.Id := typePANSICHAR;
{$ENDIF}
end
else if StrEql(S, 'NativeInt') then
begin
CurrToken.Id := typeNATIVEINT;
end;
end;
end;
procedure TPascalParser.ReadToken;
begin
inherited;
while CurrToken.TokenClass = tcSeparator do
begin
Gen(OP_SEPARATOR, CurrModule.ModuleNumber, CurrToken.Id, 0);
inherited ReadToken;
end;
end;
function TPascalParser.Parse_DirectiveList(SubId: Integer): TIntegerList;
var
S: String;
begin
result := TIntegerList.Create;
repeat
if Parse_PortabilityDirective <> portNone then
if IsCurrText(';') then
Match(';');
S := CurrToken.Text;
if StrEql(S, 'overload') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, dirOVERLOAD);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
result.Add(dirOVERLOAD);
SetOverloaded(SubId);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'forward') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, dirFORWARD);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
result.Add(dirFORWARD);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'message') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, 0);
RemoveLastIdent(CurrToken.Id);
if DECLARE_SWITCH then
if CurrToken.Id = StCard then
DiscardLastSTRecord;
Call_SCANNER;
Parse_Expression;
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'inline') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, 0);
Call_SCANNER;
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'stdcall') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, ccSTDCALL);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccSTDCALL);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'safecall') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, ccSAFECALL);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccSAFECALL);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'register') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, ccREGISTER);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccREGISTER);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'cdecl') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, ccCDECL);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccCDECL);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'msfastcall') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, ccMSFASTCALL);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccMSFASTCALL);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'pascal') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, ccPASCAL);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
SetCallConvention(SubId, ccPASCAL);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'virtual') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, cmVIRTUAL);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
result.Add(dirVIRTUAL);
SetCallMode(SubId, cmVIRTUAL);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'static') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, cmSTATIC);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
result.Add(dirSTATIC);
SetCallMode(SubId, cmSTATIC);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'dynamic') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, cmDYNAMIC);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
result.Add(dirDYNAMIC);
SetCallMode(SubId, cmDYNAMIC);
Gen(OP_ADD_MESSAGE, SubId, NewConst(typeINTEGER, -1000), 0);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'assembler') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, 0);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'override') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, cmOVERRIDE);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
result.Add(dirOVERRIDE);
SetCallMode(SubId, cmOVERRIDE);
Gen(OP_ADD_MESSAGE, SubId, NewConst(typeINTEGER, -1000), 0);
Gen(OP_CHECK_OVERRIDE, SubId, 0, 0);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'abstract') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, dirABSTRACT);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
result.Add(dirABSTRACT);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'final') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, dirFINAL);
RemoveLastIdent(CurrToken.Id);
SetFinal(SubId, true);
Call_SCANNER;
result.Add(dirFINAL);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else if StrEql(S, 'reintroduce') then
begin
if Assigned(OnParseSubDirective) then
OnParseSubDirective(Owner, S, dirREINTRODUCE);
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
result.Add(dirREINTRODUCE);
if Parse_PortabilityDirective <> portNone then
Match(';')
else if IsCurrText(';') then
Match(';');
end
else
break;
until false;
if result.IndexOf(dirVIRTUAL) >= 0 then
if result.IndexOf(dirVIRTUAL) = -1 then
CreateError(errAbstractMethodsMustBeVirtual, []);
Parse_PortabilityDirective;
if IsCurrText(';') then
Match(';');
end;
function TPascalParser.Parse_PortabilityDirective: TPortDir;
var
ok: Boolean;
S: String;
begin
result := portNone;
repeat
ok := false;
S := CurrToken.Text;
if StrEql(S, 'platform') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
if IsCurrText('=') then
begin
Call_SCANNER;
Parse_Expression;
end;
result := portPlatform;
ok := true;
end;
if StrEql(S, 'deprecated') then
begin
RemoveLastIdent(CurrToken.Id);
Call_SCANNER;
if not IsCurrText(';') then
Call_SCANNER;
result := portDeprecated;
ok := true;
end;
if StrEql(S, 'library') then
begin
Call_SCANNER;
result := portLibrary;
ok := true;
end;
until not ok;
end;
procedure TPascalParser.InitSub(var SubId: Integer);
begin
if AnonymStack.Count = 0 then
begin
CheckAbstract(SubId);
ReplaceForwardDeclaration(SubId);
end;
inherited InitSub(SubId);
Scanner.AttachId(SubId, true);
Scanner.DoComment;
if GetSymbolRec(SubId).CallMode = cmSTATIC then
GetSymbolRec(CurrSelfId).Name := '';
InitMethodDef(SubId);
end;
procedure TPascalParser.Match(const S: String);
begin
inherited;
end;
function TPascalParser.MatchEx(const S: String): Boolean;
begin
result := true;
Tag := 0;
Match(S);
if Tag = 1 then
result := false;
end;
function TPascalParser.InScope(const S: String): Boolean;
var
id: Integer;
begin
id := Lookups(S, LevelStack);
if id = 0 then
result := false
else
result := not GetSymbolRec(id).Host;
end;
procedure TPascalParser.EndMethodDef(SubId: Integer);
var
TypeId: Integer;
begin
inherited;
TypeId := GetLevel(SubId);
// if CurrModule.IsExtra then
// Exit;
if TypeId = 0 then
Exit;
if GetKind(TypeId) <> KindTYPE then
Exit;
// if not IsGeneric(TypeId) then
// Exit;
if GetSymbolRec(SubId).IsSharedMethod then
with TKernel(kernel).TypeDefList.FindMethodDef(SubId) do
Definition := 'class ' + Definition;
end;
procedure TPascalParser.Parse_TypeRestriction(LocalTypeParams: TStringObjectList);
var
temp: Boolean;
I: Integer;
TR: TTypeRestrictionRec;
begin
temp := DECLARE_SWITCH;
try
DECLARE_SWITCH := false;
if not IsCurrText(':') then
Exit;
Call_SCANNER;
TR := TTypeRestrictionRec.Create;
TR.N := TKernel(kernel).Code.Card;
if IsCurrText('class') then
begin
Call_SCANNER;
if IsCurrText(',') then
begin
Match(',');
Match('constructor');
end;
TR.Id := H_TObject;
end
else if IsCurrText('constructor') then
begin
Call_SCANNER;
if IsCurrText(',') then
begin
Match(',');
Match('class');
end;
TR.Id := H_TObject;
end
else if IsCurrText('record') then
begin
Call_SCANNER;
TR.Id := typeRECORD;
end
else
begin
TR.Id := Parse_QualId;
if IsCurrText(',') then
begin
Match(',');
Match('constructor');
end;
end;
finally
DECLARE_SWITCH := temp;
end;
if TR = nil then
Exit;
for I := LocalTypeParams.Count - 1 downto 0 do
begin
if LocalTypeParams.Objects[I] <> nil then
break;
LocalTypeParams.Objects[I] := TR.Clone;
end;
FreeAndNil(TR);
end;
procedure TPascalParser.Parse_Attribute;
begin
while IsCurrText('[') do
begin
Call_SCANNER;
repeat
Parse_Expression;
if NotMatch(',') then
break;
until false;
Match(']');
end;
end;
procedure TPascalParser.RemoveKeywords;
begin
HideKeyword(I_STRICT);
HideKeyword(I_PRIVATE);
HideKeyword(I_PROTECTED);
HideKeyword(I_PUBLIC);
HideKeyword(I_PUBLISHED);
end;
procedure TPascalParser.RestoreKeywords;
begin
inherited;
end;
function TPascalParser.Parse_LoopStmt(l_break, l_continue, l_loop: Integer): Boolean;
begin
BreakStack.Push(l_break, l_loop);
ContinueStack.Push(l_continue, l_loop);
BeginLoop;
result := Parse_Statement;
EndLoop;
BreakStack.Pop;
ContinueStack.Pop;
end;
end.
|
unit St_UnitAccessForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxControls, cxContainer, cxEdit, cxTextEdit,
cxLookAndFeelPainters, cxLabel, StdCtrls, cxButtons, ExtCtrls,
AccMGMT, Registry, St_Messages, St_Loader_Unit, cxGroupBox, jpeg, cxImage,
cxRadioGroup, cxCheckBox, st_AccessCrypto_Unit;
type
TFZAccess = class(TForm)
YesBtn: TcxButton;
CancelBtn: TcxButton;
Panel1: TPanel;
Image1: TImage;
cxLabel1: TcxLabel;
LoginEdit: TcxTextEdit;
UserEdit: TcxTextEdit;
LoginLabel: TcxLabel;
UserLabel: TcxLabel;
SafePassword_CheckBox: TcxCheckBox;
procedure YesBtnClick(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
procedure UserEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure LoginEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
// procedure FormCreate(Sender: TObject);
procedure RebuildWindowRgn;
procedure WMNCHitTest(var M: TWMNCHitTest);
procedure FormShow(Sender: TObject);
private
AccessResult:TSt_AccessResult;
countoftry:byte;
public
constructor Create(AOwner:TComponent);override;
Property Result:TSt_AccessResult read AccessResult;
end;
function St_Access(AOwner:TComponent):TSt_AccessResult;stdcall;
exports St_Access;
implementation
{$R *.dfm}
const Error_Caption = 'Помилка';
const Access_UserLabel_Caption = 'Користувач';
const Access_UserLogin_Caption = 'Пароль';
const Access_YesBtn_Caption = 'Прийняти';
const Access_CancelBtn_Caption = 'Вихід';
function NotViewFormAccess:boolean;
var reg: TRegistry;
res:boolean;
begin
res:=False;
try
reg:=TRegistry.Create;
reg.RootKey:=HKEY_CURRENT_USER;
res := reg.OpenKey('\Software\Studcity\NotLogin\',False);
finally
reg.Free;
end;
Result:=Res;
end;
function St_Access(AOwner:TComponent):TSt_AccessResult;stdcall;
var FormAccess:TFZAccess;
Res:TSt_AccessResult;
FormResult:TModalResult;
begin
if NotViewFormAccess then
begin
res.ID_User:=-999;
Res.Name_user:='Режим беспарольного доступа';
Res.User_Id_Card:=-999;
Res.User_Fio:='Режим беспарольного доступа';
Result:=Res;
Exit;
end;
FormAccess:=TFZAccess.Create(AOwner);
Res.ID_User:=0;
if FormAccess.ShowModal=mrYes then
Res:=FormAccess.Result;
FormAccess.Free;
Result:=Res;
end;
constructor TFZAccess.Create(AOwner:TComponent);
var
reg: TRegistry;
begin
inherited Create(AOwner);
countoftry := 0;
UserLabel.Caption := Access_UserLabel_Caption;
LoginLabel.Caption := Access_UserLogin_Caption;
YesBtn.Caption := Access_YesBtn_Caption;
CancelBtn.Caption := Access_CancelBtn_Caption;
reg:=TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\Studcity\Login\',False) then
begin
UserEdit.Text:=reg.ReadString('Login');
end;
if reg.OpenKey('\Software\Studcity\Password\',False) then
begin
// LoginEdit.Text:=Decrypt(reg.ReadString('Password'),1916);
LoginEdit.Text:=reg.ReadString('Password');
if LoginEdit.Text <> '' then
SafePassword_CheckBox.Checked:=true;
end
finally
reg.Free;
end;
end;
procedure TFZAccess.YesBtnClick(Sender: TObject);
var
InitResult: Integer;
reg: TRegistry;
// CurrentAccessResult:TZAccessResult;
CurrentLogin, CurrentPassword:string;
ResultInfo : TResultInfo;
Label GameOver;
begin
inc(countoftry);
//******************************************************************************
CurrentLogin := UserEdit.Text;
CurrentPassword := LoginEdit.Text;
reg := TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\Studcity\Login\',True) then
begin
reg.WriteString('Login',CurrentLogin);
end;
if SafePassword_CheckBox.Checked then
if reg.OpenKey('\Software\Studcity\Password\',True) then
begin
// reg.WriteString('Password',Encrypt(CurrentPassword,1916));
reg.WriteString('Password',CurrentPassword);
end;
if not SafePassword_CheckBox.Checked then
if reg.OpenKey('\Software\Studcity\Password\',True) then
begin
reg.DeleteValue('Password');
end
finally
reg.Free;
end;
//******************************************************************************
//InitResult := -1;
try
ResultInfo := fibInitConnection(CurrentLogin,CurrentPassword);
except
on e: Exception do
begin
MessageDlg(e.Message, mtError,[mbOk],0);
if CountOfTry>=3 then Application.Terminate
else Exit;
end;
end;
//******************************************************************************
if ResultInfo.ErrorCode <> ACCMGMT_OK then
begin
StShowMessage(Error_Caption,AcMgmtErrMsg(ResultInfo.ErrorCode),mtError,[mbOk]);
begin
UserEdit.SetFocus;
try
CloseConnection;
except
on e: Exception do
MessageDlg(e.Message, mtError,[mbOk],0);
end;
end;
UserEdit.SetFocus;
goto GameOver;
end
//******************************************************************************
else
begin
AccessResult.ID_User:=GetUserId;
AccessResult.User_Id_Card:=GetCurrentUserIDExt;
AccessResult.User_Fio := GetUserFIO;
AccessResult.Name_user:=CurrentLogin;
AccessResult.Password:=CurrentPassword;
AccessResult.DB_Handle := ResultInfo.DBHandle;
if fibCheckPermission('/ROOT/Studcity','Belong')=0 then
begin
ModalResult:=mrYes;
try
// CloseConnection;
except
on e: Exception do
MessageDlg(e.Message, mtError,[mbOk],0);
end;
GoTo GameOver;
end
else
begin
StShowMessage('Помилка','Ви не маєте прав на вход до цієї системи',mtError,[mbOK]);
try
CloseConnection;
except
on e: Exception do
MessageDlg('Фатальна помилка в системы безпеки : ' + e.Message, mtError,[mbOk],0);
end;
GoTo GameOver;
end;
end;
//******************************************************************************
GameOver:
if (countoftry>=3) and (ModalResult<>mrYes) then Application.Terminate;
end;
procedure TFZAccess.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrNo;
end;
procedure TFZAccess.UserEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=VK_RETURN then LoginEdit.SetFocus;
end;
procedure TFZAccess.LoginEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=VK_RETURN then YesBtnClick(Sender);
end;
{procedure TFZAccess.FormCreate(Sender: TObject);
begin
inherited;
HorzScrollBar.Visible:= False; // убираем сколлбары, чтобы не мешались
VertScrollBar.Visible:= False; // при изменении размеров формы
RebuildWindowRgn; // строим новый регион
end;}
procedure TFZAccess.RebuildWindowRgn;
var
FullRgn, Rgn: THandle;
ClientX, ClientY, I: Integer;
begin
// определяем относительные координаты клиентской части
ClientX:= (Width - ClientWidth) div 2;
ClientY:= Height - ClientHeight - ClientX;
FullRgn:= CreateRectRgn(0, 0, Width, Height); // создаем регион для всей формы
// создаем регион для клиентской части формы и вычитаем его из FullRgn
Rgn:= CreateRectRgn(ClientX, ClientY, ClientX + ClientWidth, ClientY +ClientHeight);
CombineRgn(FullRgn, FullRgn, Rgn, rgn_Diff);
// теперь добавляем к FullRgn регионы каждого контрольного элемента
for I:= 0 to ControlCount -1 do
with Controls[I] do begin
Rgn:= CreateRectRgn(ClientX + Left, ClientY + Top, ClientX + Left +Width, ClientY + Top + Height);
CombineRgn(FullRgn, FullRgn, Rgn, rgn_Or);
end;
SetWindowRgn(Handle, FullRgn, True); // устанавливаем новый регион окна
end;
procedure TFZAccess.WMNCHitTest(var M: TWMNCHitTest);
begin
inherited; // вызов унаследованного обработчика
if M.Result = htClient then // Мышь сидит на окне? Если да
M.Result := htCaption; // - то пусть Windows думает, что мышь на caption bar
end;
procedure TFZAccess.FormShow(Sender: TObject);
begin
LoginEdit.setfocus;
end;
end.
|
unit WhatsNew_MainForm;
interface
uses
Windows, Messages, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, jpeg, cxButtons, ComCtrls,
cxLookAndFeelPainters, zProc, Unit_zGlobal_Consts;
type
TFWhatsNew = class(TForm)
btnOK: TcxButton;
bvBottom: TBevel;
lbCompanyName: TLabel;
MemoInfo: TRichEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnOKClick(Sender: TObject);
private
PLanguageIndex:byte;
public
constructor Create(AOwner:TComponent;FileName:string);reintroduce;
end;
implementation
uses SysUtils;
{$R *.dfm}
constructor TFWhatsNew.Create(AOwner:TComponent;FileName:string);
begin
inherited Create(AOwner);
MemoInfo.Lines.LoadFromFile(ExtractFilePath(Application.ExeName)+FileName);
PLanguageIndex := LanguageIndex;
btnOK.Caption := ExitBtn_Caption[PLanguageIndex];
Caption := WhatsNew_Caption[PLanguageIndex];
lbCompanyName.Caption := DonNU_Name_Full[PLanguageIndex];
end;
procedure TFWhatsNew.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFWhatsNew.btnOKClick(Sender: TObject);
begin
Close;
end;
end.
|
(*
Category: SWAG Title: EGA/VGA ROUTINES
Original name: 0131.PAS
Description: CatMull-Rom spline source
Author: LEON DEBOER
Date: 08-25-94 09:11
*)
{
From: ldeboer@cougar.multiline.com.au (Leon DeBoer) }
{------------------------------------------------------------------------}
{ Catmull_Rom and BSpline Parametric Spline Program }
{ }
{ All source written and devised by Leon de Boer, (c)1994 }
{ E-Mail: ldeboer@cougar.multiline.com.au }
{ }
{ After many request and talk about spline techniques on the }
{ internet I decided to break out my favourite spline programs and }
{ donate to the discussion. }
{ }
{ Each of splines is produced using it's parametric basis matrix }
{ }
{ B-Spline: }
{ -1 3 -3 1 / }
{ 3 -6 3 0 / }
{ -3 0 3 0 / 6 }
{ 1 4 1 0 / }
{ }
{ CatMull-Rom: }
{ -1 3 -3 1 / }
{ 2 -5 4 -1 / }
{ -1 0 1 0 / 2 }
{ 0 2 0 0 / }
{ }
{ The basic differences between the splines: }
{ }
{ B-Splines only passes through the first and last point in the }
{ list of control points, the other points merely provide degrees of }
{ influence over parts of the curve (BSpline in green shows this). }
{ }
{ Catmull-Rom splines is one of a few splines that actually pass }
{ through each and every control point the tangent of the curve as }
{ it passes P1 is the tangent of the slope between P0 and P2 (The }
{ curve is shown in red) }
{ }
{ There is another spline type that passes through all the }
{ control points which was developed by Kochanek and Bartels and if }
{ anybody knows the basis matrix could they E-Mail to me ASAP. }
{ }
{ In the example shown the program produces 5 random points and }
{ displays the 2 spline as well as the control points. You can alter }
{ the number of points as well as the drawing resolution via the }
{ appropriate parameters. }
{------------------------------------------------------------------------}
PROGRAM Spline;
USES Graph;
TYPE
Point3D = Record
X, Y, Z: Real;
End;
VAR CtrlPt: Array [-1..80] Of Point3D;
PROCEDURE Spline_Calc (Ap, Bp, Cp, Dp: Point3D; T, D: Real; Var X, Y: Real);
VAR T2, T3: Real;
BEGIN
T2 := T * T; { Square of t }
T3 := T2 * T; { Cube of t }
X := ((Ap.X*T3) + (Bp.X*T2) + (Cp.X*T) + Dp.X)/D; { Calc x value }
Y := ((Ap.Y*T3) + (Bp.Y*T2) + (Cp.Y*T) + Dp.Y)/D; { Calc y value }
END;
PROCEDURE BSpline_ComputeCoeffs (N: Integer; Var Ap, Bp, Cp, Dp: Point3D);
BEGIN
Ap.X := -CtrlPt[N-1].X + 3*CtrlPt[N].X - 3*CtrlPt[N+1].X + CtrlPt[N+2].X;
Bp.X := 3*CtrlPt[N-1].X - 6*CtrlPt[N].X + 3*CtrlPt[N+1].X;
Cp.X := -3*CtrlPt[N-1].X + 3*CtrlPt[N+1].X;
Dp.X := CtrlPt[N-1].X + 4*CtrlPt[N].X + CtrlPt[N+1].X;
Ap.Y := -CtrlPt[N-1].Y + 3*CtrlPt[N].Y - 3*CtrlPt[N+1].Y + CtrlPt[N+2].Y;
Bp.Y := 3*CtrlPt[N-1].Y - 6*CtrlPt[N].Y + 3*CtrlPt[N+1].Y;
Cp.Y := -3*CtrlPt[N-1].Y + 3*CtrlPt[N+1].Y;
Dp.Y := CtrlPt[N-1].Y + 4*CtrlPt[N].Y + CtrlPt[N+1].Y;
END;
PROCEDURE Catmull_Rom_ComputeCoeffs (N: Integer; Var Ap, Bp, Cp, Dp: Point3D);
BEGIN
Ap.X := -CtrlPt[N-1].X + 3*CtrlPt[N].X - 3*CtrlPt[N+1].X + CtrlPt[N+2].X;
Bp.X := 2*CtrlPt[N-1].X - 5*CtrlPt[N].X + 4*CtrlPt[N+1].X - CtrlPt[N+2].X;
Cp.X := -CtrlPt[N-1].X + CtrlPt[N+1].X;
Dp.X := 2*CtrlPt[N].X;
Ap.Y := -CtrlPt[N-1].Y + 3*CtrlPt[N].Y - 3*CtrlPt[N+1].Y + CtrlPt[N+2].Y;
Bp.Y := 2*CtrlPt[N-1].Y - 5*CtrlPt[N].Y + 4*CtrlPt[N+1].Y - CtrlPt[N+2].Y;
Cp.Y := -CtrlPt[N-1].Y + CtrlPt[N+1].Y;
Dp.Y := 2*CtrlPt[N].Y;
END;
PROCEDURE BSpline (N, Resolution, Colour: Integer);
VAR I, J: Integer; X, Y, Lx, Ly: Real; Ap, Bp, Cp, Dp: Point3D;
BEGIN
SetColor(Colour);
CtrlPt[-1] := CtrlPt[1];
CtrlPt[0] := CtrlPt[1];
CtrlPt[N+1] := CtrlPt[N];
CtrlPt[N+2] := CtrlPt[N];
For I := 0 To N Do Begin
BSpline_ComputeCoeffs(I, Ap, Bp, Cp, Dp);
Spline_Calc(Ap, Bp, Cp, Dp, 0, 6, Lx, Ly);
For J := 1 To Resolution Do Begin
Spline_Calc(Ap, Bp, Cp, Dp, J/Resolution, 6, X, Y);
Line(Round(Lx), Round(Ly), Round(X), Round(Y));
Lx := X; Ly := Y;
End;
End;
END;
PROCEDURE Catmull_Rom_Spline (N, Resolution, Colour: Integer);
VAR I, J: Integer; X, Y, Lx, Ly: Real; Ap, Bp, Cp, Dp: Point3D;
BEGIN
SetColor(Colour);
CtrlPt[0] := CtrlPt[1];
CtrlPt[N+1] := CtrlPt[N];
For I := 1 To N-1 Do Begin
Catmull_Rom_ComputeCoeffs(I, Ap, Bp, Cp, Dp);
Spline_Calc(Ap, Bp, Cp, Dp, 0, 2, Lx, Ly);
For J := 1 To Resolution Do Begin
Spline_Calc(Ap, Bp, Cp, Dp, J/Resolution, 2, X, Y);
Line(Round(Lx), Round(Ly), Round(X), Round(Y));
Lx := X; Ly := Y;
End;
End;
END;
VAR I, J, Res, NumPts: Integer;
BEGIN
I := Detect;
InitGraph(I, J, 'e:\bp\bgi');
I := GetMaxX; J := GetMaxY;
Randomize;
CtrlPt[1].X := Random(I); CtrlPt[1].Y := Random(J);
CtrlPt[2].X := Random(I); CtrlPt[2].Y := Random(J);
CtrlPt[3].X := Random(I); CtrlPt[3].Y := Random(J);
CtrlPt[4].X := Random(I); CtrlPt[4].Y := Random(J);
CtrlPt[5].X := Random(I); CtrlPt[5].Y := Random(J);
Res := 20;
NumPts := 5;
BSpline(NumPts, Res, LightGreen);
CatMull_Rom_Spline(NumPts, Res, LightRed);
SetColor(Yellow);
For I := 1 To NumPts Do Begin
Line(Round(CtrlPt[I].X-3), Round(CtrlPt[I].Y),
Round(CtrlPt[I].X+3), Round(CtrlPt[I].Y));
Line(Round(CtrlPt[I].X), Round(CtrlPt[I].Y-3),
Round(CtrlPt[I].X), Round(CtrlPt[I].Y+3));
End;
ReadLn;
CloseGraph;
END.
|
(*
Desciption: Find biggest and smallest numbers of 3 reals
Programmer: Loc Pham
Date: 22/01/2016
Version: v1.0
*)
(* Program name *)
program HomeWork3;
(* Unit's inclusion *)
uses crt;
(* Variable's declration *)
var
realA, realB, realC : real;
(* Function's declaration *)
function FindBiggest(realA, realB, realC : real) : real;
(* Local variables *)
var tempResult : real;
(* Funtion body *)
begin
if (realA > realB) then
begin
tempResult := realA;
end
else
begin
tempResult := realB;
end;
if (tempResult < realC) then
begin
tempResult := realC;
end;
FindBiggest := tempResult;
end;
function FindSmallest(realA, realB, realC : real) : real;
(* Local variables *)
var tempResult : real;
(* Funtion body *)
begin
if (realA < realB) then
begin
tempResult := realA;
end
else
begin
tempResult := realB;
end;
if (tempResult > realC) then
begin
tempResult := realC;
end;
FindSmallest := tempResult;
end;
(* Main program *)
begin
write('Enter A, B, C: ');
readln(realA, realB, realC);
writeln('Biggest is: ', FindBiggest(realA, realB, realC):0:2);
writeln('Smallest is: ', FindSmallest(realA, realB, realC):0:2);
ReadKey();
end. |
unit mTranslitOnlineRu;
interface
uses
API_MVC;
type
TModelTranslitOnlineRu = class(TModelAbstract)
public
class function ConvertTrToRu(const aText: string): string;
end;
implementation
uses
API_HTTP,
API_Strings,
System.Classes,
System.SysUtils;
class function TModelTranslitOnlineRu.ConvertTrToRu(const aText: string): string;
var
HTTP: THTTP;
PostData: TStringList;
ResponseHTML: string;
begin
HTTP := THTTP.Create;
PostData := TStringList.Create;
try
PostData.Add(Format('in=%s', [aText.Trim]));
PostData.Add('translate=перевести');
ResponseHTML := HTTP.Post('http://translit-online.ru/perevod-s-translita-na-russkij.html', PostData);
Result := TStrTool.CutByKey(ResponseHTML, 'placeholder="результат перевода с транслита на русский">', '<');
finally
PostData.Free;
HTTP.Free;
end;
end;
end.
|
(*
* FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV
*
*
* 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 uPAL;
interface
uses LCLIntf, LCLType, classes, SysUtils, uFrmMessageBox, uBMP, uFPG, uPCX, uLanguage;
function Load_PAL ( palette:PByte; name : string ) : boolean;
function Load_JASP_pal( palette:PByte; name : string ) : boolean;
function Load_DIV2_pal( palette:PByte; name : string ) : boolean;
function Load_MS_pal ( palette:PByte; name : string ) : boolean;
function Load_BMP_pal ( palette:PByte; name : string ) : boolean;
function Load_PCX_pal ( palette:PByte; name : string ) : boolean;
function Save_JASP_pal( palette:PByte; name : string ) : boolean;
function Save_DIV2_pal( palette:PByte; name : string ) : boolean;
function Save_MS_pal ( palette:PByte; name : string ) : boolean;
implementation
function Load_PAL(palette:PByte; name : string ) : boolean;
begin
result := false;
// Archivo PCX
if ( AnsiPos( '.pcx',AnsiLowerCase(name)) > 0 ) then
begin
if not Load_PCX_pal(palette, name) then
begin
feMessageBox( LNG_ERROR, 'PCX ' + LNG_NOT_FOUND_PALETTE, 0, 0);
// FPG.loadPalette := false;
Exit;
end;
result := true;
Exit;
end;
// Archivo BMP
if ( AnsiPos( '.bmp',AnsiLowerCase(name)) > 0 ) then
begin
if not Load_BMP_pal(palette, name) then
begin
feMessageBox( LNG_ERROR,'BMP ' + LNG_NOT_FOUND_PALETTE, 0, 0);
// fpg.loadPalette := false;
Exit;
end;
result := true;
Exit;
end;
// Archivo FPG
if ( AnsiPos( '.fpg',AnsiLowerCase(name)) > 0 ) then
begin
if not Load_DIV2_pal(palette, name) then
begin
feMessageBox(LNG_ERROR, 'FPG ' + LNG_NOT_FOUND_PALETTE, 0, 0);
// fpg.loadPalette := false;
Exit;
end;
result := true;
Exit;
end;
// Archivos PAL
if ( AnsiPos( '.pal', AnsiLowerCase(name)) > 0 ) then
begin
result := Load_DIV2_pal(palette, name);
if not result then
result := Load_MS_pal(palette, name);
if not result then
result := Load_JASP_pal(palette, name);
if not result then
begin
feMessageBox(LNG_ERROR, 'PAL ' + LNG_NOT_FOUND_PALETTE, 0, 0);
// fpg.loadpalette := false;
Exit;
end;
result := true;
Exit;
end;
end;
function Load_JASP_pal( palette:PByte; name : string ) : boolean;
var
f : TextFile;
tstring : string;
r, g, b, i : byte;
begin
result := false;
try
AssignFile(f, name);
Reset(f);
except
feMessageBox(LNG_ERROR, LNG_NOT_OPEN_FILE, 0, 0 );
Exit;
end;
Readln(f, tstring);
if AnsiPos('JASC-PAL',tstring) <= 0 then
begin
CloseFile(f);
Exit;
end;
Readln(f);
for i:= 0 to 255 do
begin
Read(f, r); Read(f, g); Readln(f, b);
palette[i*3] := r shr 2;
palette[(i*3) + 1] := g shr 2;
palette[(i*3) + 2] := b shr 2;
palette[i*3] := palette[i*3] shl 2;
palette[(i*3) + 1] := palette[(i*3) + 1] shl 2;
palette[(i*3) + 2] := palette[(i*3) + 2] shl 2;
end;
// fpg.loadPalette := true;
result := true;
CloseFile(f);
end;
function Load_DIV2_pal( palette:PByte; name : string ) : boolean;
var
f : TFileStream;
fpg : TFpg;
i : Word;
begin
result := false;
try
f := TFileStream.Create(name, fmOpenRead);
except
feMessageBox(LNG_ERROR, LNG_NOT_OPEN_FILE, 0, 0 );
Exit;
end;
try
fpg.loadHeaderFromStream(f);
except
f.free;
Exit;
end;
if not (
(fpg.MSDOSEnd [0] = 26) and (fpg.MSDOSEnd [1] = 13) and
(fpg.MSDOSEnd [2] = 10) and (fpg.MSDOSEnd [3] = 0) )then
begin
f.free;
Exit;
end;
if fpg.Magic[2]<>'g' then
begin
f.free;
Exit;
end;
f.Read(fpg.palette, 768);
f.free;
for i:=0 to 767 do
palette[i] := fpg.palette[i] shl 2;
// fpg.loadPalette := true;
result := true;
end;
function Load_MS_pal( palette:PByte; name : string ) : boolean;
var
f : TFileStream;
i : LongInt;
header : Array [0 .. 3] of char;
ms_pal : Array [0 .. 1023] of byte;
begin
result := false;
try
f := TFileStream.Create(name, fmOpenRead);
except
feMessageBox(LNG_ERROR, LNG_NOT_OPEN_FILE, 0, 0 );
Exit;
end;
f.Read(header, 4);
f.Read(i, 4);
if( (header[0] <> 'R') or (header[1] <> 'I') or (header[2] <> 'F') or
(header[3] <> 'F') or ( i <> 1044) ) then
begin
f.free;
Exit;
end;
f.Read(header, 4);
f.Read(header, 4);
f.Read(i, 4);
f.Read(i, 4);
f.Read(ms_pal, 1024);
f.free;
//Ajustamos la paleta
for i:= 0 to 255 do
begin
palette[i*3] := ms_pal[(i * 4) + 2] shr 2;
palette[(i*3) + 1] := ms_pal[(i * 4) + 1] shr 2;
palette[(i*3) + 2] := ms_pal[i * 4] shr 2;
palette[i*3] := palette[i*3] shl 2;
palette[(i*3) + 1] := palette[(i*3) + 1] shl 2;
palette[(i*3) + 2] := palette[(i*3) + 2] shl 2;
end;
// fpg.loadPalette := true;
result := true;
end;
function Load_BMP_pal( palette:PByte; name : string ) : Boolean;
var
f : TFileStream;
i : word;
begin
result := false;
load_BMP_header(name);
if is_BMP then
begin
f := TFileStream.Create(name, fmOpenRead);
f.Seek( 54, soFromBeginning);
f.Read( BMP_palette, 1024 );
f.free;
//Ajustamos la paleta
for i:= 0 to 255 do
begin
palette[i*3] := BMP_palette[(i * 4) + 2] shr 2;
palette[(i*3) + 1] := BMP_palette[(i * 4) + 1] shr 2;
palette[(i*3) + 2] := BMP_palette[i * 4] shr 2;
palette[i*3] := palette[i*3] shl 2;
palette[(i*3) + 1] := palette[(i*3) + 1] shl 2;
palette[(i*3) + 2] := palette[(i*3) + 2] shl 2;
end;
// fpg.loadpalette := true;
result := true;
end;
end;
function Load_PCX_pal( palette:PByte; name : string ) : Boolean;
var
f : TFileStream;
i : integer;
begin
result := false;
load_PCX_header(name);
if is_PCX then
begin
f := TFileStream.Create(name, fmOpenRead);
f.Seek( f.Size - 768, soFromBeginning);
f.Read( Palette, 768 );
f.free;
//Ajustamos la paleta
for i:= 0 to 255 do
begin
palette[i*3] := palette[i*3] shr 2;
palette[(i*3) + 1] := palette[(i*3) + 1] shr 2;
palette[(i*3) + 2] := palette[(i*3) + 2] shr 2;
palette[i*3] := palette[i*3] shl 2;
palette[(i*3) + 1] := palette[(i*3) + 1] shl 2;
palette[(i*3) + 2] := palette[(i*3) + 2] shl 2;
end;
// fpg.loadPalette := true;
result := true;
end;
end;
function Save_JASP_pal( palette:PByte; name : string ) : boolean;
var
f : TextFile;
i : byte;
begin
result := false;
try
AssignFile(f, name);
ReWrite(f);
except
feMessageBox(LNG_ERROR, LNG_NOT_OPEN_FILE, 0, 0 );
Exit;
end;
Writeln(f, 'JASC-PAL');
Writeln(f, '0100');
Writeln(f, '256');
for i:= 0 to 255 do
begin
Write(f, palette[i*3]);
Write(f, ' ');
Write(f, palette[(i*3) + 1]);
Write(f, ' ');
WriteLn(f, palette[(i*3) + 2]);
end;
result := true;
CloseFile(f);
end;
function Save_DIV2_pal( palette:PByte; name : string ) : boolean;
var
f : file of byte;
temp_byte: byte;
i : Word;
begin
result := false;
try
AssignFile(f, name);
ReWrite(f);
except
feMessageBox(LNG_ERROR, LNG_NOT_OPEN_FILE, 0, 0 );
Exit;
end;
temp_byte := Ord('p'); Write(f, temp_byte);
temp_byte := Ord('a'); Write(f, temp_byte);
temp_byte := Ord('l'); Write(f, temp_byte);
temp_byte := 26; Write(f, temp_byte);
temp_byte := 13; Write(f, temp_byte);
temp_byte := 10; Write(f, temp_byte);
temp_byte := 0; Write(f, temp_byte); Write(f, temp_byte);
for i:=0 to 767 do
begin
temp_byte := palette[i] shr 2;
Write(f, temp_byte);
end;
temp_byte := 0;
for i:=0 to 575 do
Write(f, temp_byte);
CloseFile(f);
result := true;
end;
function Save_MS_pal( palette:PByte; name : string ) : boolean;
var
f : TFileStream;
i : LongInt;
header : Array [0 .. 7] of char;
ms_pal : Array [0 .. 1023] of byte;
begin
result := false;
try
f := TFileStream.Create(name, fmCreate);
except
feMessageBox( LNG_ERROR, LNG_NOT_OPEN_FILE, 0, 0 );
Exit;
end;
header := 'RIFF';
f.Write(header, 4);
i := 1044;
f.Write(i, 4);
header := 'PAL data';
f.Write(header, 8);
i := 1032;
f.Write(i, 4);
i := 16777984;
f.Write(i, 4);
//Ajustamos la paleta
for i:= 0 to 255 do
begin
ms_pal[(i * 4) + 2] := 0;
ms_pal[(i * 4) + 2] := palette[i*3];
ms_pal[(i * 4) + 1] := palette[(i*3) + 1];
ms_pal[ i * 4 ] := palette[(i*3) + 2];
end;
f.Write(ms_pal, 1024);
ms_pal[0] := 255; ms_pal[1] := 255; ms_pal[2] := 255; ms_pal[3] := 255;
f.Write(ms_pal, 4);
f.free;
result := true;
end;
end.
|
unit uOptionFrameDemo;
interface
uses
Windows, AIMPCustomPlugin, Forms, uOptionFrameDemoForm, apiOptions, apiObjects, apiCore;
type
{ TAIMPDemoPluginOptionFrame }
TAIMPDemoPluginOptionFrame = class(TInterfacedObject, IAIMPOptionsDialogFrame)
strict private
FFrame: TfrmOptionFrameDemo;
procedure HandlerModified(Sender: TObject);
protected
// IAIMPOptionsDialogFrame
function CreateFrame(ParentWnd: HWND): HWND; stdcall;
procedure DestroyFrame; stdcall;
function GetName(out S: IAIMPString): HRESULT; stdcall;
procedure Notification(ID: Integer); stdcall;
end;
{ TAIMPDemoPlugin }
TAIMPDemoPlugin = class(TAIMPCustomPlugin)
protected
function InfoGet(Index: Integer): PWideChar; override; stdcall;
function InfoGetCategories: Cardinal; override; stdcall;
function Initialize(Core: IAIMPCore): HRESULT; override; stdcall;
end;
implementation
uses
apiWrappers, SysUtils, apiPlugin;
{ TAIMPDemoPluginOptionFrame }
function TAIMPDemoPluginOptionFrame.CreateFrame(ParentWnd: HWND): HWND;
var
R: Trect;
begin
FFrame := TfrmOptionFrameDemo.CreateParented(ParentWnd);
FFrame.OnModified := HandlerModified;
GetWindowRect(ParentWnd, R);
OffsetRect(R, -R.Left, -R.Top);
FFrame.BoundsRect := R;
FFrame.Visible := True;
Result := FFrame.Handle;
end;
procedure TAIMPDemoPluginOptionFrame.DestroyFrame;
begin
FreeAndNil(FFrame);
end;
function TAIMPDemoPluginOptionFrame.GetName(out S: IAIMPString): HRESULT;
begin
try
S := MakeString('Custom Frame');
Result := S_OK;
except
Result := E_UNEXPECTED;
end;
end;
procedure TAIMPDemoPluginOptionFrame.Notification(ID: Integer);
begin
if FFrame <> nil then
case ID of
AIMP_SERVICE_OPTIONSDIALOG_NOTIFICATION_LOCALIZATION:
TfrmOptionFrameDemo(FFrame).ApplyLocalization;
AIMP_SERVICE_OPTIONSDIALOG_NOTIFICATION_LOAD:
TfrmOptionFrameDemo(FFrame).ConfigLoad;
AIMP_SERVICE_OPTIONSDIALOG_NOTIFICATION_SAVE:
TfrmOptionFrameDemo(FFrame).ConfigSave;
end;
end;
procedure TAIMPDemoPluginOptionFrame.HandlerModified(Sender: TObject);
var
AServiceOptions: IAIMPServiceOptionsDialog;
begin
if Supports(CoreIntf, IAIMPServiceOptionsDialog, AServiceOptions) then
AServiceOptions.FrameModified(Self);
end;
{ TAIMPDemoPlugin }
function TAIMPDemoPlugin.InfoGet(Index: Integer): PWideChar;
begin
case Index of
AIMP_PLUGIN_INFO_NAME:
Result := 'OptionFrame Demo';
AIMP_PLUGIN_INFO_AUTHOR:
Result := 'Artem Izmaylov';
AIMP_PLUGIN_INFO_SHORT_DESCRIPTION:
Result := 'This plugin show how to use Options API';
else
Result := nil;
end;
end;
function TAIMPDemoPlugin.InfoGetCategories: Cardinal;
begin
Result := AIMP_PLUGIN_CATEGORY_ADDONS;
end;
function TAIMPDemoPlugin.Initialize(Core: IAIMPCore): HRESULT;
begin
Result := inherited Initialize(Core);
if Succeeded(Result) then
Core.RegisterExtension(IID_IAIMPServiceOptionsDialog, TAIMPDemoPluginOptionFrame.Create);
end;
end.
|
unit uDemoViewTipo2;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox,
FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls,
uInterfaces,
uAtributos,
uDemoInterfaces,
uDemoViewModels,
uTypes,
uView;
type
[ViewForVM(IMyViewModel2, TMyViewModel2, EInstanceType.itSingleton)]
TfrmIntf2 = class(TFormView<IMyViewModel2, TMyViewModel2>)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
protected
public
{ Public declarations }
function GetVM_AsInterface: IMyViewModel2; override;
function GetVM_AsObject: TMyViewModel2; override;
end;
var
frmIntf2: TfrmIntf2;
implementation
{$R *.fmx}
{ TfrmIntf2 }
procedure TfrmIntf2.Button1Click(Sender: TObject);
begin
Memo1.Lines.Add(GetVM_AsInterface.Hello2);
end;
function TfrmIntf2.GetVM_AsInterface: IMyViewModel2;
begin
Result := FViewModel as IMyViewModel2
end;
function TfrmIntf2.GetVM_AsObject: TMyViewModel2;
begin
Result := FViewModel as TMyViewModel2;
end;
end.
|
unit Demo.Hello;
{ Hello world example.
Very simple example, most useful for compilation tests. }
interface
uses
Duktape,
Demo;
type
TDemoHello = class(TDemo)
private
class function NativeAdder(const ADuktape: TDuktape): TdtResult; cdecl; static;
public
procedure Run; override;
end;
implementation
{ TDemoHello }
class function TDemoHello.NativeAdder(const ADuktape: TDuktape): TdtResult;
var
I, N: Integer;
Res: Double;
begin
N := ADuktape.GetTop; // Number of arguments
Res := 0;
for I := 0 to N - 1 do
Res := Res + ADuktape.ToNumber(I);
ADuktape.PushNumber(Res);
Result := TdtResult.HasResult;
end;
procedure TDemoHello.Run;
begin
Duktape.PushDelphiFunction(NativeAdder, DT_VARARGS);
Duktape.PutGlobalString('adder');
Duktape.Eval('print("Hello World!");');
Duktape.Eval('print("2+3=" + adder(2, 3));');
Duktape.Pop; // Pop eval result
end;
initialization
TDemo.Register('Hello World!', TDemoHello);
end.
|
unit uDemoViewModels;
interface
uses
uInterfaces,
uDemoInterfaces;
type
TMyViewModel1 = class(TViewModel, IMyViewModel1, IViewModel)
public
function Hello1: String;
end;
TMyViewModel2 = class(TViewModel, IMyViewModel2, IViewModel)
public
function Hello2: String;
end;
TMyViewModel3 = class(TViewModel, IMyViewModel3, IViewModel)
private
FVM1: IMyViewModel1;
FVM2: IMyViewModel2;
protected
function GetVM_Tipo1: IMyViewModel1;
function GetVM_Tipo2: IMyViewModel2;
procedure SetVM_Tipo1(AValue: IMyViewModel1);
procedure SetVM_Tipo2(AValue: IMyViewModel2);
public
function Hello: String;
property VM_Tipo1: IMyViewModel1 read GetVM_Tipo1 write SetVM_Tipo1;
property VM_Tipo2: IMyViewModel2 read GetVM_Tipo2 write SetVM_Tipo2;
end;
implementation
{ TMyViewModel1 }
function TMyViewModel1.Hello1: String;
begin
Result := self.QualifiedClassName
end;
{ TMyViewModel2 }
function TMyViewModel2.Hello2: String;
begin
Result := self.QualifiedClassName
end;
{ TMyViewModel3 }
function TMyViewModel3.GetVM_Tipo1: IMyViewModel1;
begin
Result := FVM1;
end;
function TMyViewModel3.GetVM_Tipo2: IMyViewModel2;
begin
Result := FVM2;
end;
function TMyViewModel3.Hello: String;
begin
Result := FVM1.Hello1 + ' - ' + FVM2.Hello2;
end;
procedure TMyViewModel3.SetVM_Tipo1(AValue: IMyViewModel1);
begin
FVM1 := AValue;
end;
procedure TMyViewModel3.SetVM_Tipo2(AValue: IMyViewModel2);
begin
FVM2 := AValue;
end;
end.
|
unit txDefs;
interface
uses SysUtils;
type
TtxItemType=(
itObj,itObjType,
itTok,itTokType,
itRef,itRefType,
itFilter,
itRealm,
itUser,
itReport,
itJournal,
itJournalEntry,
itJournalEntryType,
//add new here above
it_Unknown
);
const
ApplicationName='tx';
//TODO: dynamic settings?
Use_Terms=true;//requires WikiEngine.dll and tables Trm, Trl
Use_ObjTokRefCache=true;//requires table ObjTokRefCache
Use_ObjHist=true;//requires table ObjHist
Use_ObjPath=true;//requires table ObjPath
Use_NewUserEmailActivation=true;
Use_Unread=true;//requires table Obx,Urx
Use_Journals=true;//requires table Jrl,Jre
Use_Extra=false;//use prefix "::" on ObjType.system
txItemTypeKey:array[TtxItemType] of string=(
'i','ot','t','tt','r','rt','f','rm','u','rp','j','je','jet',
//add new here above (see also procedure txItem below)
''
);
txItemTypeName:array[TtxItemType] of string=(
'object','objecttype',
'token','tokentype',
'reference','referencetype',
'filter','realm','user','report','journal','journalentry','journalentrytype',
//add new here above
'unknown'
);
txItemTypeTable:array[TtxItemType] of UTF8String=(
'Obj','ObjType',
'Tok','TokType',
'Ref','RefType',
'Flt','Rlm','Usr','Rpt','Jrl','Jre','Jrt',
//add new here above
''
);
txItemSQL_PidById:array[TtxItemType] of UTF8String=(
'SELECT pid FROM Obj WHERE id=?',
'SELECT pid FROM ObjType WHERE id=?',
'','SELECT pid FROM TokType WHERE id=?',
'','SELECT pid FROM RefType WHERE id=?',
'','','','','','','',
//add new here above
''
);
txItemSQL_Move:array[TtxItemType] of UTF8String=(
'UPDATE Obj SET pid=? WHERE id=?',
'UPDATE ObjType SET pid=? WHERE id=?',
'','UPDATE TokType SET pid=? WHERE id=?',
'','UPDATE RefType SET pid=? WHERE id=?',
'','','','','','','',
//add new here above
''
);
globalIconAlign='align="top" border="0" ';
globalImgExt='svg';//'png';
globalImgVer='?v=1';
lblLocation= '<img src="img_loc.'+globalImgExt+globalImgVer+'" width="16" height="16" alt="location:" '+globalIconAlign+'/>';
lblDescendants='<img src="img_dsc.'+globalImgExt+globalImgVer+'" width="16" height="16" alt="children:" '+globalIconAlign+'/>';
lblTokens= '<img src="img_tok.'+globalImgExt+globalImgVer+'" width="16" height="16" alt="tokens:" '+globalIconAlign+'/>';
lblReferences= '<img src="img_ref.'+globalImgExt+globalImgVer+'" width="16" height="16" alt="references:" '+globalIconAlign+'/>';
{
lblTreeNone= '<img src="img_trx.'+globalImgExt+globalImgVer+'" width="16" height="16" alt="" '+globalIconAlign+'/>';
lblTreeOpen= '<img src="img_tr0.'+globalImgExt+globalImgVer+'" width="16" height="16" alt="[-]" '+globalIconAlign+'/>';
lblTreeClosed= '<img src="img_tr1.'+globalImgExt+globalImgVer+'" width="16" height="16" alt="[+]" '+globalIconAlign+'/>';
}
txFormButton='<input type="submit" value="Apply" id="formsubmitbutton" class="formsubmitbutton" />';
lblLoading='<i style="color:#CC3300;"><img src="loading.gif" width="16" height="16" alt="" '+globalIconAlign+'/> Loading...</i>';
DefaultRlmID=0;//do not change
EmailCheckRegEx='^[-\+_\.a-z0-9]+?@[-\.a-z0-9]+?\.[a-z][a-z]+$';//TODO: unicode?
procedure txItem(const KeyX:string;var ItemType:TtxItemType;var ItemID:integer);
function txImg(IconNr:integer; const Desc:string=''):string;
function txForm(const Action:string; const HVals:array of OleVariant;const OnSubmitEval:string=''):string; overload;
function DateToXML(d:TDateTime):string;
function NiceDateTime(const x:OleVariant):string;
function ShortDateTime(d:TDateTime):string;
function JournalDateTime(d:TDateTime):string;
function JournalGranulate(d:TDateTime;granularity:integer):TDateTime;
function JournalTime(d:TDateTime;granularity:integer):string;
function JournalMinutes(minutes:integer):string;
function JournalMinutesTD(minutes:integer):string;
function jtToDateTime(const jt:string):TDateTime;
function jtFromDateTime(d:TDateTime):string;
function IntToStrU(x:integer):UTF8String;
implementation
uses Variants;
procedure txItem(const KeyX:string;var ItemType:TtxItemType;var ItemID:integer);
var
Key:AnsiString;
i:integer;
begin
Key:=AnsiString(KeyX);
ItemType:=itObj;//default;
ItemID:=0;
for i:=1 to Length(Key) do if Key[i] in ['0'..'9'] then ItemID:=ItemID*10+(byte(Key[i]) and $F);
if Length(Key)>1 then
case Key[1] of
'i':ItemType:=itObj;
'o':
case Key[2] of
't': ItemType:=itObjType;
else ItemType:=itObj;
end;
't':
case Key[2] of
't': ItemType:=itTokType;
else ItemType:=itTok;
end;
'r':
case Key[2] of
't': ItemType:=itRefType;
'p': ItemType:=itReport;
'm': ItemType:=itRealm;
else ItemType:=itRef;
end;
'f':ItemType:=itFilter;
'u':ItemType:=itUser;
'j':
if (Key[2]='e') and (Key[3]='t') then
ItemType:=itJournalEntryType
else
ItemType:=itJournal;
//else raise?
else ItemType:=it_Unknown;
end;
end;
//HTMLEncode here since no other units required
function HTMLEncode(const x:string):string;
begin
Result:=
StringReplace(
StringReplace(
StringReplace(
StringReplace(
x,
'&','&',[rfReplaceAll]),
'<','<',[rfReplaceAll]),
'>','>',[rfReplaceAll]),
'"','"',[rfReplaceAll]);
end;
function txImg(IconNr:integer; const Desc:string): string;
begin
Result:='<img src="img/ic'+IntToStr(IconNr)+'.'+globalImgExt+globalImgVer+'" width="16" height="16" ';
if Desc<>'' then Result:=Result+'alt="'+HTMLEncode(Desc)+'" title="'+HTMLEncode(Desc)+'" ';
Result:=Result+globalIconAlign+'/>';
end;
function txForm(const Action:string; const HVals:array of OleVariant;const OnSubmitEval:string=''):string; overload;
var
s:string;
i:integer;
begin
if OnSubmitEval='' then s:='true' else
s:=HTMLEncode(StringReplace(OnSubmitEval,'"','''',[rfReplaceAll]));
Result:='<form action="'+HTMLEncode(Action)+
'" method="post" onsubmit="return default_form_submit('+s+');">'#13#10;
for i:=0 to (Length(HVals) div 2)-1 do
if not VarIsNull(HVals[i*2+1]) then
Result:=Result+'<input type="hidden" name="'+HTMLEncode(VarToStr(HVals[i*2]))+'" value="'+
HTMLEncode(VarToStr(HVals[i*2+1]))+'" />'#13#10;
end;
function DateToXML(d:TDateTime):string;
var
dy,dm,dd,dw,th,tm,ts,tz:word;
const
EngDayNames:array[0..6] of string=('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
EngMonthNames:array[1..12] of string=('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Okt','Nov','Dec');
begin
DecodeDateFully(d,dy,dm,dd,dw);
DecodeTime(d,th,tm,ts,tz);
//TODO: get time info bias
Result:=EngDayNames[dw]+', '+IntToStr(dd)+' '+EngMonthNames[dm]+' '+IntToStr(dy)+' '+Format('%.2d:%.2d:%.2d',[th,tm,ts])+' +01:00';
end;
function NiceDateTime(const x:OleVariant):string;
begin
if VarIsNull(x) then Result:='?' else Result:=FormatDateTime('ddd c',VarFromDateTime(x));
end;
function ShortDateTime(d:TDateTime):string;
var
d1:TDateTime;
dy1,dy2,dm,dd:word;
begin
if d=0.0 then
Result:='?'
else
begin
d1:=Date;
if Trunc(d)=d1 then
Result:=FormatDateTime('hh:nn',d)
else
begin
DecodeDate(d,dy1,dm,dd);
DecodeDate(d1,dy2,dm,dd);
if dy1=dy2 then
Result:=FormatDateTime('ddd d/mm',d)
else
if d>d1-533.0 then
Result:=FormatDateTime('d/mm/yyyy',d)
else
Result:=FormatDateTime('mm/yyyy',d);
end;
end;
end;
function JournalDateTime(d:TDateTime):string;
begin
//TODO: JournalGranulate here?
Result:=FormatDateTime('ddd d/mm hh:nn',d);
end;
function JournalGranulate(d:TDateTime;granularity:integer):TDateTime;
begin
//Round? Trunc(+constant)? Tunc(+(g/2))?
Result:=Trunc((d*1440.0+(1/60))/granularity)*granularity/1440.0;
end;
function JournalTime(d:TDateTime;granularity:integer):string;
var
d0:TDateTime;
m:integer;
begin
if granularity<=0 then granularity:=60;
d0:=JournalGranulate(Now,granularity);
d:=JournalGranulate(d,granularity);
m:=Round((d0-d)*1440.0);
if Trunc(d)=Trunc(d0) then Result:=FormatDateTime('hh:nn',d) else Result:=FormatDateTime('ddd d/mm hh:nn',d);
if m>60 then
Result:=Result+Format(' (%d:%.2d'')',[m div 60,m mod 60])
else
Result:=Result+' ('+IntToStr(m)+''')';
end;
function JournalMinutes(minutes:integer):string; //inline;
begin
Result:=Format('%d:%.2d',[minutes div 60,minutes mod 60]);
end;
function JournalMinutesTD(minutes:integer):string; //inline;
begin
if minutes=0 then
Result:='<td style="text-align:center;color:#C0C0C0;">—</td>'
else
Result:='<td style="text-align:right;">'+Format('%d:%.2d',[minutes div 60,minutes mod 60])+'</td>';
end;
const
jtDelta=63000000;
function jtToDateTime(const jt:string):TDateTime;
var
i:integer;
begin
if not TryStrToInt(jt,i) then raise Exception.Create('Invalid JournalTime value');
Result:=(i+jtDelta)/1440.0;
end;
function jtFromDateTime(d:TDateTime):string;
begin
Result:=IntToStr(Round(d*1440.0)-jtDelta);
end;
function IntToStrU(x:integer):UTF8String;
var
c:array[0..11] of byte;
i,j:integer;
neg:boolean;
begin
//Result:=UTF8String(IntToStr(x));
neg:=x<0;
if neg then x:=-x;
i:=0;
while x<>0 do
begin
c[i]:=x mod 10;
x:=x div 10;
inc(i);
end;
if i=0 then
begin
c[0]:=0;
inc(i);
end;
if neg then
begin
SetLength(Result,i+1);
Result[1]:='-';
j:=2;
end
else
begin
SetLength(Result,i);
j:=1;
end;
while i<>0 do
begin
dec(i);
Result[j]:=AnsiChar($30+c[i]);
inc(j);
end;
end;
end.
|
unit LrObserverList;
interface
uses
Classes;
type
TLrObserverList = class(TPersistent)
private
FObserverList: TList;
FEventList: TList;
protected
property EventList: TList read FEventList;
property ObserverList: TList read FObserverList;
public
constructor Create;
destructor Destroy; override;
procedure Add(inEvent: TNotifyEvent);
procedure Remove(inEvent: TNotifyEvent);
procedure Notify;
end;
implementation
{ TLrObserverList }
constructor TLrObserverList.Create;
begin
FObserverList := TList.Create;
FEventList := TList.Create;
end;
destructor TLrObserverList.Destroy;
begin
FObserverList.Free;
FEventList.Free;
inherited;
end;
procedure TLrObserverList.Add(inEvent: TNotifyEvent);
begin
ObserverList.Add(TMethod(inEvent).Data);
EventList.Add(TMethod(inEvent).Code);
end;
procedure TLrObserverList.Remove(inEvent: TNotifyEvent);
var
i: Integer;
begin
i := ObserverList.IndexOf(TMethod(inEvent).Data);
if i >= 0 then
begin
ObserverList.Delete(i);
EventList.Delete(i);
end;
end;
procedure TLrObserverList.Notify;
var
i: Integer;
e: TNotifyEvent;
begin
for i := 0 to Pred(ObserverList.Count) do
begin
TMethod(e).Data := ObserverList[i];
TMethod(e).Code := EventList[i];
e(Self);
end;
end;
end.
|
program HowToDrawAnAnimation;
uses
SwinGame, sgTypes;
procedure Main();
var
explosion: Animation;
begin
OpenAudio();
OpenGraphicsWindow('Draw Animation', 200, 200);
LoadResourceBundle('explosion_bundle.txt');
explosion := CreateAnimation('explosion_loop', AnimationScriptNamed('explosionScrpt'));
repeat
ProcessEvents();
ClearScreen(ColorWhite);
DrawAnimation(explosion, BitmapNamed('explosionBmp'), 64, 64);
UpdateAnimation(explosion);
RefreshScreen(60);
until WindowCloseRequested();
Delay(800);
CloseAudio();
ReleaseAllResources();
end;
begin
Main();
end. |
unit StockDayData_Get_Sina;
interface
uses
BaseApp,
Sysutils,
UtilsHttp,
win.iobuffer,
define_price,
define_dealitem,
define_stockday_sina,
StockDayDataAccess;
const
BaseSinaDayUrl1 = 'http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/';
BaseSinaDayUrl_weight = 'http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_FuQuanMarketHistory/stockid/';
(*//
// http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_FuQuanMarketHistory/stockid/600000.phtml
// http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/600000.phtml
// 上证指数
// http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/000001/type/S.phtml?year=2015&jidu=1
深圳成分
http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/399001/type/S.phtml
沪深 300
http://vip.stock.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/000300/type/S.phtml
//*)
function GetStockDataDay_Sina(App: TBaseApp; AStockItem: PRT_DealItem; AWeightMode: TWeightMode; ANetSession: PHttpClientSession; AHttpData: PIOBuffer): Boolean;
function DataGet_DayData_SinaNow(ADataAccess: TStockDayDataAccess; ANetSession: PHttpClientSession; AHttpData: PIOBuffer): Boolean; overload;
implementation
uses
Classes,
Windows,
Define_DataSrc,
define_stock_quotes,
UtilsDateTime,
//StockDayData_Parse_Sina_Html1,
//StockDayData_Parse_Sina_Html2,
StockDayData_Parse_Sina_Html3,
QuickList_Int,
UtilsLog,
StockDayData_Parse_Sina,
StockDayData_Load,
StockDayData_Save;
function DataGet_DayData_SinaNow(ADataAccess: TStockDayDataAccess; ANetSession: PHttpClientSession; AHttpData: PIOBuffer): Boolean; overload;
var
tmpurl: string;
tmpHttpData: PIOBuffer;
tmpDayDataList: TALIntegerList;
tmpDayData: PRT_Quote_Day;
i: integer;
begin
Result := false;
if weightNone <> ADataAccess.WeightMode then
tmpUrl := BaseSinaDayUrl_weight
else
tmpUrl := BaseSinaDayUrl1;
tmpurl := tmpurl + ADataAccess.StockItem.sCode + '.phtml';
tmpHttpData := GetHttpUrlData(tmpUrl, ANetSession, AHttpData, SizeMode_512k);
if nil <> tmpHttpData then
begin
try
//Result := StockDayData_Parse_Sina_Html1.DataParse_DayData_Sina(ADataAccess, tmpHttpData);
//Result := StockDayData_Parse_Sina_Html2.DataParse_DayData_Sina(ADataAccess, tmpHttpData);
tmpDayDataList := StockDayData_Parse_Sina_Html3.DataParse_DayData_Sina(tmpHttpData);
if nil <> tmpDayDataList then
begin
try
if 0 < tmpDayDataList.Count then
begin
for i := 0 to tmpDayDataList.Count - 1 do
begin
tmpDayData := PRT_Quote_Day(tmpDayDataList.Objects[i]);
AddDealDayData(ADataAccess, tmpDayData);
Result := True;
end;
end;
for i := tmpDayDataList.Count - 1 downto 0 do
begin
FreeMem(PRT_Quote_Day(tmpDayDataList.Objects[i]));
end;
tmpDayDataList.Clear;
finally
tmpDayDataList.Free;
end;
end;
finally
if AHttpData <> tmpHttpData then
begin
CheckInIOBuffer(tmpHttpData);
end;
end;
end;
Sleep(100);
end;
function DataGet_DayData_Sina(ADataAccess: TStockDayDataAccess; AYear, ASeason: Word; ANetSession: PHttpClientSession; AHttpData: PIOBuffer): Boolean; overload;
var
tmpUrl: string;
tmpHttpData: PIOBuffer;
tmpRepeat: Integer;
tmpDayDataList: TALIntegerList;
i: integer;
tmpDayData: PRT_Quote_Day;
begin
Result := false;
if weightNone <> ADataAccess.WeightMode then
begin
tmpUrl := BaseSinaDayUrl_weight;
ADataAccess.WeightMode := weightBackward;
end else
begin
tmpUrl := BaseSinaDayUrl1;
end;
tmpurl := tmpurl + ADataAccess.StockItem.sCode + '.phtml';
if (0 <> AYear) and (0 < ASeason) then
begin
tmpurl := tmpurl + '?year=' + inttostr(AYear);
tmpUrl := tmpUrl + '&' + 'jidu=' + inttostr(ASeason);
end;
// parse html data
tmpRepeat := 3;
while tmpRepeat > 0 do
begin
tmpHttpData := GetHttpUrlData(tmpUrl, ANetSession, AHttpData, SizeMode_512k);
if nil <> tmpHttpData then
begin
try
//Result := StockDayData_Parse_Sina_Html1.DataParse_DayData_Sina(ADataAccess, tmpHttpData);
//Result := StockDayData_Parse_Sina_Html2.DataParse_DayData_Sina(ADataAccess, tmpHttpData);
tmpDayDataList := StockDayData_Parse_Sina_Html3.DataParse_DayData_Sina(tmpHttpData);
if nil <> tmpDayDataList then
begin
try
if 0 < tmpDayDataList.Count then
begin
for i := 0 to tmpDayDataList.Count - 1 do
begin
tmpDayData := PRT_Quote_Day(tmpDayDataList.Objects[i]);
AddDealDayData(ADataAccess, tmpDayData);
Result := True;
end;
end;
for i := tmpDayDataList.Count - 1 downto 0 do
begin
FreeMem(PRT_Quote_Day(tmpDayDataList.Objects[i]));
end;
tmpDayDataList.Clear;
finally
tmpDayDataList.Free;
end;
end;
finally
if AHttpData <> tmpHttpData then
begin
CheckInIOBuffer(tmpHttpData);
end;
end;
end;
if Result then
Break;
Dec(tmpRepeat);
Sleep(500 * (3 - tmpRepeat));
end;
end;
function GetStockDataDay_Sina(App: TBaseApp; AStockItem: PRT_DealItem; AWeightMode: TWeightMode; ANetSession: PHttpClientSession; AHttpData: PIOBuffer): Boolean;
var
tmpStockDataAccess: TStockDayDataAccess;
tmpLastDealDate: Word;
tmpInt: integer;
tmpQuoteDay: PRT_Quote_Day;
tmpFromYear: Word;
tmpFromMonth: Word;
tmpFromDay: Word;
tmpCurrentYear: Word;
tmpCurrentMonth: Word;
tmpCurrentDay: Word;
tmpJidu: integer;
begin
Result := false;
if weightNone <> AWeightMode then
begin
AWeightMode := weightBackward;
end;
tmpStockDataAccess := TStockDayDataAccess.Create(AStockItem, src_Sina, AWeightMode);
try
tmpLastDealDate := Trunc(now());
tmpInt := DayOfWeek(tmpLastDealDate);
if 1 = tmpInt then
begin
tmpLastDealDate := tmpLastDealDate - 2;
end else if 7 = tmpInt then
begin
tmpLastDealDate := tmpLastDealDate - 1;
end else
begin
// 当天数据不下载
tmpLastDealDate := tmpLastDealDate - 1;
end;
if CheckNeedLoadStockDayData(App, tmpStockDataAccess, tmpLastDealDate) then
begin
end else
exit;
(*//
// 先以 163 必须 获取到数据为前提 ???
if AStockItem.FirstDealDate < 1 then
begin
exit;
end;
//*)
DecodeDate(now, tmpCurrentYear, tmpCurrentMonth, tmpCurrentDay);
if (0 < tmpStockDataAccess.LastDealDate) and (0 < tmpStockDataAccess.FirstDealDate) then
begin
DecodeDate(tmpStockDataAccess.LastDealDate, tmpFromYear, tmpFromMonth, tmpFromDay);
end else
begin
if tmpStockDataAccess.StockItem.FirstDealDate > 0 then
begin
DecodeDate(tmpStockDataAccess.StockItem.FirstDealDate, tmpFromYear, tmpFromMonth, tmpFromDay);
end else
begin
end;
end;
if tmpFromYear < 1980 then
begin
if tmpStockDataAccess.StockItem.FirstDealDate = 0 then
begin
tmpFromYear := 2013;
tmpFromYear := 1990;
tmpFromMonth := 12;
end;
end;
tmpJidu := SeasonOfMonth(tmpFromMonth);
while tmpFromYear < tmpCurrentYear do
begin
while tmpJidu < 5 do
begin
DataGet_DayData_Sina(tmpStockDataAccess, tmpFromYear, tmpJidu, ANetSession, AHttpData);
Inc(tmpJidu);
end;
Inc(tmpFromYear);
tmpJidu := 1;
end;
while tmpJidu < SeasonOfMonth(tmpCurrentMonth) do
begin
DataGet_DayData_Sina(tmpStockDataAccess, tmpCurrentYear, tmpJidu, ANetSession, AHttpData);
Inc(tmpJidu);
end;
DataGet_DayData_SinaNow(tmpStockDataAccess, ANetSession, AHttpData);
tmpStockDataAccess.Sort;
SaveStockDayData(App, tmpStockDataAccess);
if 0 = AStockItem.FirstDealDate then
begin
if 0 < tmpStockDataAccess.RecordCount then
begin
tmpQuoteDay := tmpStockDataAccess.RecordItem[0];
AStockItem.FirstDealDate := tmpQuoteDay.DealDate.Value;
AStockItem.IsDataChange := 1;
end;
end;
finally
tmpStockDataAccess.Free;
end;
end;
end.
|
PROGRAM Minimum;
FUNCTION Min2(number1: INTEGER; number2: INTEGER) : INTEGER;
BEGIN
IF number1 <= number2 THEN {* Schritt 1 *}
Min2 := number1 {* Schritt 2 *}
ELSE Min2 := number2; {* Schritt 3 *}
END;
FUNCTION Min3a(number1: INTEGER; number2: INTEGER; number3: INTEGER) : INTEGER;
VAR
help : INTEGER;
BEGIN
IF number1 <= number2 THEN {* Schritt 1 *}
help := number1
ELSE help := number2;
IF help <= number3 THEN {* Schritt 2 *}
Min3a := help
ELSE Min3a := number3;
END;
FUNCTION Min3b(number1: INTEGER; number2: INTEGER; number3: INTEGER) : INTEGER;
VAR help: INTEGER;
BEGIN
help := Min2(number1, number2); {* Schritt 1 *}
Min3b := Min2(help, number3); {* Schritt 2 *}
END;
PROCEDURE AssertMin2(number1: INTEGER; number2: INTEGER; expectedResult: INTEGER);
BEGIN
IF Min2(number1,number2) = expectedResult THEN
WriteLn('Min2(' , number1 , ',' , number2 , ') should return value: ' , expectedResult , ' --> OK')
ELSE WriteLn('Min2(' , number1 , ',' , number2 , ') should return value: ' , expectedResult , ' --> X')
END;
PROCEDURE AssertMin3a(number1: INTEGER; number2: INTEGER; number3: INTEGER; expectedResult: INTEGER);
BEGIN
IF Min3a(number1,number2,number3) = expectedResult THEN
WriteLn('Min3a(' , number1 , ',' , number2 , ',' , number3 , ') should return value: ' , expectedResult , ' --> OK')
ELSE WriteLn('Min3a(' , number1 , ',' , number2 , ',' , number3 , ') should return value: ' , expectedResult , ' --> X')
END;
PROCEDURE AssertMin3b(number1: INTEGER; number2: INTEGER; number3: INTEGER; expectedResult: INTEGER);
BEGIN
IF Min3b(number1,number2,number3) = expectedResult THEN
WriteLn('Min3b(' , number1 , ',' , number2 , ',' , number3 , ') should return value: ' , expectedResult , ' --> OK')
ELSE WriteLn('Min3b(' , number1 , ',' , number2 , ',' , number3 , ') should return value: ' , expectedResult , ' --> X')
END;
BEGIN
AssertMin2(1,1,1);
AssertMin2(2,1,1);
AssertMin2(1,2,1);
AssertMin2(-3,1,-3);
AssertMin2(1,-3,-3);
AssertMin2(32768,1,-32768);
AssertMin2(-32769,1,1);
WriteLn();
AssertMin3a(1,1,1,1);
AssertMin3a(2,1,1,1);
AssertMin3a(2,1,2,1);
AssertMin3a(2,2,1,1);
AssertMin3a(-3,1,1,-3);
AssertMin3a(2,1,-3,-3);
AssertMin3a(32768,1,1,-32768);
AssertMin3a(1,-32769,1,1);
WriteLn();
AssertMin3b(1,1,1,1);
AssertMin3b(2,1,1,1);
AssertMin3b(2,1,2,1);
AssertMin3b(2,2,1,1);
AssertMin3b(-3,1,1,-3);
AssertMin3b(2,1,-3,-3);
AssertMin3b(32768,1,1,-32768);
AssertMin3b(1,-32769,1,1);
END.
|
unit WorldPayProcessor;
interface
uses SysUtils, Classes, contnrs, ProcessorInterface, uCreditCardFunction;
type
TWorldPayProcessor = class(TInterfacedObject, IProcessor)
private
FTerminalID: String;
fDeviceParamValue: Integer;
fIsDeviceInitialized: Boolean;
fClassTypeName: String;
fPadType: String;
fSecureDevice: String;
FIdPaymentType: Integer;
FManualCvv: String;
FmanualCvv2: String;
FmanualZipCode: String;
FmanualStreet: String;
FManualMember: String;
FExpiresDate: String;
FTax: Double;
FInvoiceNo: String;
FMessage: String;
FoperatorID: String;
FAcctNo: String;
FAppLabel: String;
FAuthCode: String;
FCardType: String;
FDateTransaction: String;
FEntryMethod: String;
FIpPort: String;
FIPProcessorAddress: String;
FLabelAID: String;
FlabelARC: String;
FLabelCVM: String;
FLabelIAD: String;
FLabelTSI: String;
FLabelTVR: String;
FLastDigits: String;
FMerchantID: String;
FRecordNo: String;
FRefNo: String;
FResultAcqRefData: String;
FSequenceNo: String;
FTimeTransaction: String;
FTrancode: String;
FTrueCardTypeName: String;
FPurchase: Currency;
FAuthorize: Currency;
FBalance: Currency;
FConnectionTimeOut: Integer;
FResponseTimeOut: Integer;
FgiftIP: String;
FgiftPort: String;
FgiftMerchantID: String;
FdialUpBridge: Boolean;
FTransactionResult: TTransactionReturn;
public
constructor create();
procedure SetTerminalID(arg_terminalID: String);
function GetTerminalID(): String;
procedure SetDeviceInitialized(arg_started: Boolean);
function IsDeviceInitialized(): Boolean;
procedure SetDeviceIniParameter(arg_value: Integer);
function GetClassTypeName(): String;
procedure SetPadType(arg_name: String);
function GetPadType(): String;
procedure SetSecureDevice(arg_sdcode: String);
function GetSecureDevice(): String;
procedure SetTax(arg_tax: double);
function GetTax(): Double;
procedure SetInvoiceNo(arg_invoiceNo: String);
function GetInvoiceNo(): String;
procedure SetOperatorID(arg_operatorID: String);
function GetOperatorID(): String;
procedure SetAuthCode(arg_authCode: String);
function GetAuthCode(): String;
procedure SetResultAcqRefData(arg_acqRefData: String);
function GetResultAcqRefData(): String;
procedure SetRefNo(arg_refNo: String);
function GetRefNo(): String;
procedure SetAcctNo(arg_acctNo: String);
function GetAcctNo(): String;
procedure SetLastDigits(arg_lastDigits: String);
function GetLastDigits(): String;
procedure SetMerchantID(arg_merchantID: String);
function GetMerchantID(): String;
procedure SetPurchase(arg_purchase: Currency);
function GetPurchase(): Currency;
procedure SetAuthorize(arg_authorize: Currency);
function GetAuthorize(): Currency;
procedure SetSequenceNo(arg_sequence: String);
function GetSequenceNo(): String;
procedure SetTrueCardTypeName(arg_name: String);
function GetTrueCardTypeName(): String;
procedure SetCardType(arg_type: String);
function GetCardType(): String;
procedure SetEntryMethod(arg_entryMethod: String);
function GetEntryMethod(): String;
procedure SetAppLabel(arg_appLabel: String);
function GetAppLabel(): String;
procedure SetRecordNo(arg_recordNo: String);
function GetRecordNo(): String;
procedure SetIPPort(arg_port: String);
function GetIPPort(): String;
procedure SetIPAddress(arg_address: String);
function GetIPAddress(): String;
function GetMerchandID(): String;
procedure SetIPProcessorAddress(arg_address: String);
function GetIPProcessorAddres(): String;
procedure SetConnectionTimeOut(arg_timeOut: Integer);
function GetConnectionTimeOut(): Integer;
procedure SetResponseTimeOut(arg_responseTimeOut: Integer);
function GetResponseTimeOut(): Integer;
procedure SetMessage(arg_msg: String);
function GetMessage(): String;
procedure SetGiftIP(arg_giftIP: String);
function GetGiftIP(): String;
procedure SetGiftPort(arg_giftPort: String);
function GetGiftPort(): String;
procedure SetGiftMerchantID(arg_merchantid: String);
function GetGiftMerchantID(): String;
procedure SetDialUpBridge(arg_dialBridge: Boolean);
function GetDialUpBridge(): Boolean;
procedure SetManualStreeAddress(arg_address: String);
function GetManualStreeAddress(): String;
procedure SetManualZipCode(arg_zipCode: String);
function GetManualZipCode(): String;
procedure SetManualCVV2(arg_cvv2: String);
function GetManualCvv2(): String;
procedure SetManualCardNumber(arg_cardNumber: String);
function GetManualCardNumber(): String;
procedure SetManualMemberName(arg_member: String);
function GetManualMemberName(): String;
procedure SetManualCvv(arg_cvv: String);
function GetManualCvv(): String;
procedure SetExpireDate(arg_date: String);
function GetExpireDate(): String;
procedure SetCustomerCode(arg_customerCode: String);
function GetCustomerCode(): String;
procedure SetIdPaymentType(arg_paymentType: Integer);
function GetIdPaymentType(): Integer;
procedure SetTransactionResult(arg_result: TTransactionReturn);
function GetTransactionResult(): TTransactionReturn;
procedure SetBalance(arg_balance: Currency);
function GetBalance(): Currency;
procedure SetTransactionErrorCode(arg_transerror: String);
function GetransactionErrorCode(): String;
// methods bellow are only to EMV transactions
procedure SetDateTransaction(arg_date: String);
function GetDateTransaction(): String;
procedure SetTimeTransaction(arg_time: String);
function GetTimeTransaction(): String;
procedure SetLabelAID(arg_label: String);
function GetLabelAID(): String;
procedure SetLabelTVR(arg_label: String);
function GetLabelTVR(): String;
procedure SetLabelIAD(arg_label: String);
function GetLAbelIAD(): String;
procedure SetLabelTSI(arg_label: String);
function GetLabelTSI(): String;
procedure SetLabelARC(arg_label: String);
function GetLabelARC(): String;
procedure SetLabelCVM(arg_label: String);
function GetLabelCVM(): String;
procedure SetTrancode(arg_trancode: String);
function GetTrancode(): String;
end;
implementation
uses StrUtils, Controls;
{ TWorldPayProcessor }
constructor TWorldPayProcessor.create;
begin
fClassTypeName := 'TWorldPayProcessor';
end;
function TWorldPayProcessor.GetAcctNo: String;
begin
result := FAcctNo;
end;
function TWorldPayProcessor.GetAppLabel: String;
begin
result := FAppLabel;
end;
function TWorldPayProcessor.GetAuthCode: String;
begin
result := FAuthCode;
end;
function TWorldPayProcessor.GetAuthorize: Currency;
begin
result := FAuthorize;
end;
function TWorldPayProcessor.GetBalance: Currency;
begin
end;
function TWorldPayProcessor.GetCardType: String;
begin
result := FCardType;
end;
function TWorldPayProcessor.GetClassTypeName: String;
begin
result := fClassTypeName;
end;
function TWorldPayProcessor.GetConnectionTimeOut: Integer;
begin
result := FConnectionTimeOut;
end;
function TWorldPayProcessor.GetCustomerCode: String;
begin
end;
function TWorldPayProcessor.GetDateTransaction: String;
begin
result := FDateTransaction;
end;
function TWorldPayProcessor.GetDialUpBridge: Boolean;
begin
//
end;
function TWorldPayProcessor.GetEntryMethod: String;
begin
result := FEntryMethod;
end;
function TWorldPayProcessor.GetExpireDate: String;
begin
end;
function TWorldPayProcessor.GetGiftIP: String;
begin
end;
function TWorldPayProcessor.GetGiftMerchantID: String;
begin
result := FgiftMerchantID
end;
function TWorldPayProcessor.GetGiftPort: String;
begin
end;
function TWorldPayProcessor.GetIdPaymentType: Integer;
begin
result := FIdPaymentType;
end;
function TWorldPayProcessor.GetInvoiceNo: String;
begin
result := FinvoiceNo;
end;
function TWorldPayProcessor.GetIPPort: String;
begin
result := FIPPort;
end;
function TWorldPayProcessor.GetIPProcessorAddres: String;
begin
result := FIPProcessorAddress;
end;
function TWorldPayProcessor.GetLabelAID: String;
begin
result := FLabelAID;
end;
function TWorldPayProcessor.GetLabelARC: String;
begin
result := FLabelARC;
end;
function TWorldPayProcessor.GetLabelCVM: String;
begin
result := FLabelCVM;
end;
function TWorldPayProcessor.GetLabelIAD: String;
begin
result := FLabelIAD;
end;
function TWorldPayProcessor.GetLabelTSI: String;
begin
result := FLabelTSI;
end;
function TWorldPayProcessor.GetLabelTVR: String;
begin
result := FLabelTVR;
end;
function TWorldPayProcessor.GetLastDigits: String;
begin
result := FlastDigits;
end;
function TWorldPayProcessor.GetManualCardNumber: String;
begin
result := FAcctNo;
end;
function TWorldPayProcessor.GetManualCvv: String;
begin
result := FManualCvv;
end;
function TWorldPayProcessor.GetManualCvv2: String;
begin
result := FmanualCvv2;
end;
function TWorldPayProcessor.GetManualMemberName: String;
begin
result := FManualMember;
end;
function TWorldPayProcessor.GetManualStreeAddress: String;
begin
result := FmanualStreet;
end;
function TWorldPayProcessor.GetManualZipCode: String;
begin
end;
function TWorldPayProcessor.GetMerchandID: String;
begin
end;
function TWorldPayProcessor.GetMerchantID: String;
begin
result := FMerchantID;
end;
function TWorldPayProcessor.GetMessage: String;
begin
result := FMessage;
end;
function TWorldPayProcessor.GetOperatorID: String;
begin
result := FoperatorId;
end;
function TWorldPayProcessor.GetPadType: String;
begin
result := fPadType;
end;
function TWorldPayProcessor.GetPurchase: Currency;
begin
result := FPurchase;
end;
function TWorldPayProcessor.GetransactionErrorCode: String;
begin
result := FTrancode;
end;
function TWorldPayProcessor.GetRecordNo: String;
begin
result := FRecordNo;
end;
function TWorldPayProcessor.GetRefNo: String;
begin
result := FRefNo;
end;
function TWorldPayProcessor.GetResponseTimeOut: Integer;
begin
result := FResponseTimeOut;
end;
function TWorldPayProcessor.GetResultAcqRefData: String;
begin
result := FResultAcqRefData;
end;
function TWorldPayProcessor.GetSecureDevice: String;
begin
end;
function TWorldPayProcessor.GetSequenceNo: String;
begin
result := FSequenceNo;
end;
function TWorldPayProcessor.GetTax: Double;
begin
result := FTax;
end;
function TWorldPayProcessor.GetTimeTransaction: String;
begin
result := FTimeTransaction;
end;
function TWorldPayProcessor.GetTrancode: String;
begin
result := FTrancode;
end;
function TWorldPayProcessor.GetTransactionResult: TTransactionReturn;
begin
end;
function TWorldPayProcessor.GetTrueCardTypeName: String;
begin
result := FTrueCardTypeName;
end;
function TWorldPayProcessor.IsDeviceInitialized: Boolean;
begin
end;
procedure TWorldPayProcessor.SetAcctNo(arg_acctNo: String);
begin
FAcctNo := arg_acctNo;
end;
procedure TWorldPayProcessor.SetAppLabel(arg_appLabel: String);
begin
FAppLabel := arg_appLabel;
end;
procedure TWorldPayProcessor.SetAuthCode(arg_authCode: String);
begin
FAuthCode := arg_authCode;
end;
procedure TWorldPayProcessor.SetAuthorize(arg_authorize: Currency);
begin
FAuthorize := arg_authorize;
end;
procedure TWorldPayProcessor.SetBalance(arg_balance: Currency);
begin
end;
procedure TWorldPayProcessor.SetCardType(arg_type: String);
begin
FCardType := arg_type;
end;
procedure TWorldPayProcessor.SetConnectionTimeOut(arg_timeOut: Integer);
begin
FConnectionTimeOut := arg_timeOut;
end;
procedure TWorldPayProcessor.SetCustomerCode(arg_customerCode: String);
begin
end;
procedure TWorldPayProcessor.SetDateTransaction(arg_date: String);
begin
FDateTransaction := arg_date;
end;
procedure TWorldPayProcessor.SetDeviceIniParameter(arg_value: Integer);
begin
end;
procedure TWorldPayProcessor.SetDeviceInitialized(arg_started: Boolean);
begin
fIsDeviceInitialized := arg_started;
end;
procedure TWorldPayProcessor.SetDialUpBridge(arg_dialBridge: Boolean);
begin
//
end;
procedure TWorldPayProcessor.SetEntryMethod(arg_entryMethod: String);
begin
FEntryMethod := arg_entryMethod;
end;
procedure TWorldPayProcessor.SetExpireDate(arg_date: String);
begin
end;
procedure TWorldPayProcessor.SetGiftIP(arg_giftIP: String);
begin
end;
procedure TWorldPayProcessor.SetGiftMerchantID(arg_merchantid: String);
begin
FgiftMerchantID := arg_merchantid;
end;
procedure TWorldPayProcessor.SetGiftPort(arg_giftPort: String);
begin
end;
procedure TWorldPayProcessor.SetIdPaymentType(arg_paymentType: Integer);
begin
end;
procedure TWorldPayProcessor.SetInvoiceNo(arg_invoiceNo: String);
begin
FinvoiceNo := arg_invoiceNo;
end;
procedure TWorldPayProcessor.SetIPPort(arg_port: String);
begin
FIPPort := arg_port;
end;
procedure TWorldPayProcessor.SetIPProcessorAddress(arg_address: String);
begin
FIPProcessorAddress := arg_address;
end;
procedure TWorldPayProcessor.SetLabelAID(arg_label: String);
begin
FLabelAID := arg_label;
end;
procedure TWorldPayProcessor.SetLabelARC(arg_label: String);
begin
FLabelARC := arg_label;
end;
procedure TWorldPayProcessor.SetLabelCVM(arg_label: String);
begin
FLabelCVM := arg_label;
end;
procedure TWorldPayProcessor.SetLabelIAD(arg_label: String);
begin
end;
procedure TWorldPayProcessor.SetLabelTSI(arg_label: String);
begin
FLabelTSI := arg_label;
end;
procedure TWorldPayProcessor.SetLabelTVR(arg_label: String);
begin
FLabelTVR := arg_label;
end;
procedure TWorldPayProcessor.SetLastDigits(arg_lastDigits: String);
begin
FLastDigits := arg_lastDigits;
end;
procedure TWorldPayProcessor.SetManualCardNumber(arg_cardNumber: String);
begin
end;
procedure TWorldPayProcessor.SetManualCvv(arg_cvv: String);
begin
end;
procedure TWorldPayProcessor.SetManualCVV2(arg_cvv2: String);
begin
end;
procedure TWorldPayProcessor.SetManualMemberName(arg_member: String);
begin
end;
procedure TWorldPayProcessor.SetManualStreeAddress(arg_address: String);
begin
end;
procedure TWorldPayProcessor.SetManualZipCode(arg_zipCode: String);
begin
end;
procedure TWorldPayProcessor.SetMerchantID(arg_merchantID: String);
begin
FMerchantID := arg_merchantID;
end;
procedure TWorldPayProcessor.SetMessage(arg_msg: String);
begin
FMessage := arg_msg;
end;
procedure TWorldPayProcessor.SetOperatorID(arg_operatorID: String);
begin
end;
procedure TWorldPayProcessor.SetPadType(arg_name: String);
begin
fPadType := arg_name;
end;
procedure TWorldPayProcessor.SetPurchase(arg_purchase: Currency);
begin
FPurchase := arg_purchase;
end;
procedure TWorldPayProcessor.SetRecordNo(arg_recordNo: String);
begin
FRecordNo := arg_recordNo;
end;
procedure TWorldPayProcessor.SetRefNo(arg_refNo: String);
begin
FRefNo := arg_refNo;
end;
procedure TWorldPayProcessor.SetResponseTimeOut(
arg_responseTimeOut: Integer);
begin
FResponseTimeOut := arg_responseTimeOut;
end;
procedure TWorldPayProcessor.SetResultAcqRefData(arg_acqRefData: String);
begin
FResultAcqRefData := arg_acqRefData;
end;
procedure TWorldPayProcessor.SetSecureDevice(arg_sdcode: String);
begin
end;
procedure TWorldPayProcessor.SetSequenceNo(arg_sequence: String);
begin
FSequenceNo := arg_sequence;
end;
procedure TWorldPayProcessor.SetTax(arg_tax: double);
begin
end;
procedure TWorldPayProcessor.SetTimeTransaction(arg_time: String);
begin
FTimeTransaction := arg_time;
end;
procedure TWorldPayProcessor.SetTrancode(arg_trancode: String);
begin
FTrancode := arg_trancode;
end;
procedure TWorldPayProcessor.SetTransactionErrorCode(
arg_transerror: String);
begin
FTrancode := arg_transerror;
end;
procedure TWorldPayProcessor.SetTransactionResult(
arg_result: TTransactionReturn);
begin
end;
procedure TWorldPayProcessor.SetTrueCardTypeName(arg_name: String);
begin
FTrueCardTypeName := arg_name;
end;
end.
|
namespace CirrusMethodLogAspectLibrary;
interface
uses
RemObjects.Elements.Cirrus;
type
[AttributeUsage(AttributeTargets.Class + AttributeTargets.Struct)]
MethodLogAttribute = public class(Attribute, RemObjects.Elements.Cirrus.IMethodImplementationDecorator)
public
[Aspect:RemObjects.Elements.Cirrus.AutoInjectIntoTarget]
method LogMessage(aEnter: Boolean; aName: String; Args: Array of object);
method HandleImplementation(Services: RemObjects.Elements.Cirrus.IServices; aMethod: RemObjects.Elements.Cirrus.IMethodDefinition);
end;
implementation
method MethodLogAttribute.HandleImplementation(Services: RemObjects.Elements.Cirrus.IServices; aMethod: RemObjects.Elements.Cirrus.IMethodDefinition);
begin
if String.Equals(aMethod.Name, 'LogMessage',
StringComparison.OrdinalIgnoreCase) then exit;
aMethod.SetBody(Services,
method begin
try
LogMessage(true, typeof(self) + Aspects.MethodName, Aspects.GetParameters);
Aspects.OriginalBody;
finally
LogMessage(false, Aspects.MethodName, Aspects.GetParameters);
end;
end);
end;
method MethodLogAttribute.LogMessage(aEnter: Boolean; aName: String; Args: Array of object);
begin
var lMessage: String := iif(aEnter, 'Entering ', 'Exiting ') + aName;
if (aEnter and (assigned(Args))) then begin
lMessage := lMessage + ' with arguments';
for I: Int32 := 0 to Length(Args)-1 do
lMessage := lMessage + String.Format(' {0}', Args[i]);
end;
Console.WriteLine(lMessage);
end;
end.
|
unit glShellTreeView;
interface
uses
SysUtils, Classes, Controls, ComCtrls, Windows;
type
TglShellTreeView = class(TCustomTreeView)
private
FRemovable, FFixed, FRemote, FCDROM, FUnknown: integer;
function SrNodeTree(pTreeNode: TTreeNode; var sRuta: string): string;
function DirectoryName(name: string): Boolean;
procedure NextLevel(ParentNode: TTreeNode);
protected
function CanExpand(Node: TTreeNode): Boolean; override;
public
constructor Create(AOwner: TComponent); override;
procedure MakeTree;
function GetPath: string;
published
property ImageIndexRemovable: integer read FRemovable write FRemovable;
property ImageIndexFixed: integer read FFixed write FFixed;
property ImageIndexRemote: integer read FRemote write FRemote;
property ImageIndexCDROM: integer read FCDROM write FCDROM;
property ImageIndexUnknown: integer read FUnknown write FUnknown;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Golden Line', [TglShellTreeView]);
end;
{ TglShellTreeView }
function TglShellTreeView.CanExpand(Node: TTreeNode): Boolean;
begin
result := inherited CanExpand(Node);
if result then
begin
Items.BeginUpdate;
Node.DeleteChildren;
NextLevel(Node);
Items.EndUpdate;
end;
end;
constructor TglShellTreeView.Create(AOwner: TComponent);
begin
inherited;
MakeTree;
end;
function TglShellTreeView.DirectoryName(name: string): Boolean;
begin
result := (name <> '.') and (name <> '..');
end;
function TglShellTreeView.GetPath: string;
var
s: string;
begin
result := SrNodeTree(Selected, s);
end;
procedure TglShellTreeView.MakeTree;
var
c: Char;
s: string;
Node: TTreeNode;
DriveType: integer;
begin
inherited;
Items.BeginUpdate;
for c := 'A' to 'Z' do
begin
s := c + ':';
DriveType := GetDriveType(PChar(s));
if DriveType = DRIVE_NO_ROOT_DIR then
Continue;
Node := Items.AddChild(nil, s);
case DriveType of
DRIVE_REMOVABLE:
Node.ImageIndex := FRemovable;
DRIVE_FIXED:
Node.ImageIndex := FFixed;
DRIVE_REMOTE:
Node.ImageIndex := FRemote;
DRIVE_CDROM:
Node.ImageIndex := FCDROM;
else
Node.ImageIndex := FUnknown;
end;
Node.SelectedIndex := Node.ImageIndex;
Node.HasChildren := true;
end;
Items.EndUpdate;
end;
procedure TglShellTreeView.NextLevel(ParentNode: TTreeNode);
var
sr, srChild: TSearchRec;
Node: TTreeNode;
path: string;
begin
Node := ParentNode;
path := '';
repeat
path := Node.Text + '\' + path;
Node := Node.Parent;
until Node = nil;
if FindFirst(path + '*.*', faDirectory, sr) = 0 then
begin
repeat
if (sr.Attr and faDirectory <> 0) and DirectoryName(sr.name) then
begin
Node := Items.AddChild(ParentNode, sr.name);
Node.ImageIndex := 2;
Node.SelectedIndex := 1;
Node.HasChildren := false;
if FindFirst(path + sr.name + '\*.*', faDirectory, srChild) = 0 then
begin
repeat
if (srChild.Attr and faDirectory <> 0) and
DirectoryName(srChild.name) then
Node.HasChildren := true;
until (FindNext(srChild) <> 0) or Node.HasChildren;
end;
SysUtils.FindClose(srChild);
end;
until FindNext(sr) <> 0;
end
else
ParentNode.HasChildren := false;
SysUtils.FindClose(sr);
end;
function TglShellTreeView.SrNodeTree(pTreeNode: TTreeNode;
var sRuta: string): string;
begin
sRuta := pTreeNode.Text + '\' + sRuta;
if pTreeNode.Level = 0 then
result := sRuta
else
result := SrNodeTree(pTreeNode.Parent, sRuta);
end;
end.
|
unit ProgressForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxProgressBar;
type
TfProgress = class(TForm)
pBar: TcxProgressBar;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
fCloseCall: tNotifyEvent;
public
procedure SetPos(aPos, aMax: int64);
procedure SetText(fText: String);
property CloseCall: tNotifyEvent read fCloseCall write fCloseCall;
{ Public declarations }
end;
//var
// fProgress: TfProgress;
implementation
{$R *.dfm}
procedure TfProgress.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
ModalResult := mrCancel;
CanClose := false;
if assigned(fCloseCall) then
fCloseCall(Sender);
end;
procedure TfProgress.FormCreate(Sender: TObject);
begin
ModalResult := mrNone;
end;
procedure TfProgress.SetPos(aPos, aMax: int64);
begin
PbAR.Properties.Max := aMax;
pBaR.Position := aPos;
end;
procedure TfProgress.SetText(fText: String);
begin
if fText = '' then
pBar.Properties.ShowTextStyle := cxtsPercent
else
begin
pBar.Properties.ShowTextStyle := cxtstext;
pBar.Properties.Text := fText;
end;
Application.ProcessMessages;
end;
end.
|
unit files;
{ Open and close files, interpret command line, do input, do most output}
interface uses globals, multfile;
procedure readParagraph (var P: paragraph; var no: line_nos;
var L: paragraph_index0);
function styleFileFound: boolean;
procedure processOption(j: char);
procedure OpenFiles;
procedure CloseFiles;
procedure putLine (line: string);
procedure put(line: string; putspace: boolean);
procedure TeXtype2 (s: string);
function endOfInfile: boolean;
implementation uses control, strings, utility;
const param_leader = '-';
stylefilename: string = 'mtxstyle.txt';
var teststyle: integer;
function endOfInfile: boolean;
begin endOfInfile:=eofAll; end;
procedure putTeXlines(s: string);
var p: integer;
begin p:=pos1(#10,s);
while p>0 do
begin
putLine('\'+substr(s,1,p-1)+'\');
predelete(s,p);
p:=pos1(#10,s)
end;
if length(s)>0 then putLine('\'+s+'\');
end;
procedure TeXtype2 (s: string);
begin
if pmx_preamble_done then
if s[1]='%' then putLine(s)
else if first_paragraph then putTeXLines(s)
else putLine('\\'+s+'\')
else putLine(s);
end;
procedure putLine (line: string);
begin if outlen+length(line) > pmxlinelength-1 then writeln(outfile);
writeln(outfile,line); outlen:=0;
end;
procedure put(line: string; putspace: boolean);
var l: integer;
begin l:=length(line);
if l>pmxlinelength then error('Item longer than PMX line length',print);
if outlen+l > pmxlinelength-1 then
begin putLine(''); put(line,false) end
else begin if putspace and (outlen>0) and (line[1]<>' ') then
line:=' '+line;
write(outfile,line); inc(outlen,l);
end
end;
function styleFileFound: boolean;
begin styleFileFound := teststyle<>0; end;
procedure helpmessage;
begin
writeln('Usage: prepmx [-bcfnhimtuvwDH0123456789] MTXFILE [TEXDIR] [STYLEFILE]')
end;
procedure bighelpmessage;
begin helpmessage; writeln;
writeln('MTXFILE: name of .mtx file without its extension');
writeln('TEXDIR: directory where the TeX file made by PMX goes, default is ./');
writeln('STYLEFILE: name of a file containing style definitions. Default is');
writeln(' mtxstyle.txt. This feature is now deprecated; use Include: STYLEFILE');
writeln(' in the preamble of the .mtx file instead.');
writeln('Options: (can also be entered separately: -b -c ...)');
writeln(' -b: disable unbeamVocal');
writeln(' -c: disable doChords');
writeln(' -f: enable solfaNoteNames');
writeln(' -h: display this message and quit');
writeln(' -i: enable ignoreErrors');
writeln(' -m: disable doLyrics');
writeln(' -n: enable instrumentNames');
writeln(' -t: disable doUptext');
writeln(' -u: disable uptextOnRests');
writeln(' -v: enable beVerbose');
writeln(' -w: enable pedanticWarnings');
writeln(' -D: enable debugMode');
writeln(' -0123456789: select Case');
writeln(' -H: print enabled status of all options');
writeln('All the above, and some other, options can be enabled or disabled');
writeln(' in the preamble. What you do there overrides what you do here.')
end;
procedure processOption(j: char);
begin case j of
'b': setFeature('unbeamVocal',false);
'c': setFeature('doChords',false);
'f': setFeature('solfaNoteNames',true);
'h': begin bighelpmessage; halt(255) end;
'i': setFeature('ignoreErrors',true);
'm': setFeature('doLyrics',false);
'n': setFeature('instrumentNames',true);
't': setFeature('doUptext',false);
'u': setFeature('uptextOnRests',false);
'v': setFeature('beVerbose',true);
'w': setFeature('pedanticWarnings',true);
'D': setFeature('debugMode',true);
'0'..'9': choice:=j;
'H': printFeatures(true);
else write(j); error(': invalid option',not print);
end;
end;
procedure OpenFiles;
var i, j, l, fileid, testin: integer;
infilename, outfilename, basename, param, ext: string;
procedure checkExistingFile;
var tryfile: file;
begin
{$I-}
assign(tryfile,basename); reset(tryfile); testin := ioresult;
{$I+}
if testin<>0 then exit else close(tryfile);
writeln('There exists a file named ',basename,'. I am treating this');
error(' as a fatal error unless you specify -i',not print);
end;
begin
fileid:=0; line_no:=0; paragraph_no:=0;
for i:=1 to ParamCount do
begin param:=ParamStr(i);
if param[1]=param_leader then
for j:=2 to length(param) do processOption(param[j])
else if fileid=0 then fileid:=i
else if texdir='' then texdir:=param
else stylefilename:=param;
end;
if fileid=0 then
begin helpmessage; writeln('Try "prepmx -h" for more information.'); halt(255) end
else basename:=paramstr(fileid);
l:=length(basename);
if (l>4) and (basename[l-3]='.') then
begin ext:=substr(basename,l-2,3); toUpper(ext); if ext='MTX' then
begin warning('.mtx extension deleted from basename',not print);
shorten(basename,l-4);
end;
end;
if pos1('.',basename)>0 then checkExistingFile;
infilename := basename+'.mtx'; outfilename := basename+'.pmx';
{$I-}
pushFile(infilename);
assign(outfile,outfilename); rewrite(outfile);
assign(stylefile,stylefilename); reset(stylefile); teststyle := ioresult;
if (teststyle<>0) and (stylefilename<>'mtxstyle.txt') then
writeln('Can''t read ',stylefilename);
{$I+}
if fileError then fatalError('Input file '+infilename+' not found');
outfile_open := true; writeln('Writing to ',basename,'.pmx');
end;
procedure CloseFiles;
begin close(outfile); closeAll; if teststyle=0 then close(stylefile);
end;
procedure readParagraph (var P: paragraph; var no: line_nos;
var L: paragraph_index0);
var another: boolean;
filename, buffer: string;
begin
L:=0; buffer:=readData; line_no:=currentLineNo;
if isEmpty(buffer) then exit;
if debugMode then writeln('>>>> ',buffer);
inc(paragraph_no);
{ Handle directives affecting the processing of the input file }
repeat another:=false;
if startsWithIgnoreCase(buffer,'SUSPEND') then
begin ignore_input:=true; another:=true; if beVerbose then
writeln('-->> Suspending input file ',currentFilename,
' at line ', line_no);
end;
if startsWithIgnoreCase(buffer,'RESUME') then
begin ignore_input:=false; another:=true; if beVerbose then
writeln('-->> Resuming input file ',currentFilename,
' at line ', line_no);
end;
if startsWithIgnoreCase(buffer,'INCLUDE:') then
begin predelete(buffer,8); filename:=nextWord(buffer,' ',' ');
pushfile(filename); another:=true;
end;
if another then begin buffer:=readLine; line_no:=currentLineNo; end;
until not another;
{ Normal paragraph input}
repeat
if L<lines_in_paragraph then
begin inc(L); P[L]:=buffer; buffer:=''; no[L]:=line_no;
end
else warning('Paragraph too long: skipping line',not print);
buffer:=readLine; line_no := currentLineNo;
if debugMode then writeln(line_no,' >> ', buffer);
until isEmpty(buffer);
skipBlanks; { needed to identify final paragraph }
end;
end.
|
unit NetTools;
interface
uses
Windows, Classes, SysUtils, IdStack;
function GetLocalIP:string;
implementation
function GetLocalIP:string;
var
IdStack : TIdStack;
begin
IdStack := TIdStack.CreateStack;
try
Result := IdStack.LocalAddress;
finally
IdStack.Free;
end;
end;
end.
|
{
publish with BSD Licence.
Copyright (c) Terry Lao
}
unit filter;
{$MODE Delphi}
interface
uses iLBC_define,C2Delphi_header;
{----------------------------------------------------------------*
* all-pole filter
*---------------------------------------------------------------}
procedure AllPoleFilter(
InOut:PAreal; { (i/o) on entrance InOut[-orderCoef] to
InOut[-1] contain the state of the
filter (delayed samples). InOut[0] to
InOut[lengthInOut-1] contain the filter
input, on en exit InOut[-orderCoef] to
InOut[-1] is unchanged and InOut[0] to
InOut[lengthInOut-1] contain filtered
samples }
Coef:PAreal;{ (i) filter coefficients, Coef[0] is assumed
to be 1.0 }
lengthInOut:integer;{ (i) number of input/output samples }
orderCoef:integer { (i) number of filter coefficients }
);
procedure AllZeroFilter(
nIn:PAreal; { (i) In[0] to In[lengthInOut-1] contain
filter input samples }
Coef:PAreal;{ (i) filter coefficients (Coef[0] is assumed
to be 1.0) }
lengthInOut:integer;{ (i) number of input/output samples }
orderCoef:integer; { (i) number of filter coefficients }
nOut:PAreal { (i/o) on entrance Out[-orderCoef] to Out[-1]
contain the filter state, on exit Out[0]
to Out[lengthInOut-1] contain filtered
samples }
);
procedure ZeroPoleFilter(
nIn:PAreal; { (i) In[0] to In[lengthInOut-1] contain
filter input samples In[-orderCoef] to
In[-1] contain state of all-zero
section }
ZeroCoef:pareal;{ (i) filter coefficients for all-zero
section (ZeroCoef[0] is assumed to
be 1.0) }
PoleCoef:pareal;{ (i) filter coefficients for all-pole section
(ZeroCoef[0] is assumed to be 1.0) }
lengthInOut:integer;{ (i) number of input/output samples }
orderCoef:integer; { (i) number of filter coefficients }
nOut:pareal { (i/o) on entrance Out[-orderCoef] to Out[-1]
contain state of all-pole section. On
exit Out[0] to Out[lengthInOut-1]
contain filtered samples }
);
procedure DownSample (
nIn:PAreal; { (i) input samples }
Coef:pareal; { (i) filter coefficients }
lengthIn:integer; { (i) number of input samples }
state:pareal; { (i) filter state }
nOut:PAreal { (o) downsampled output }
);
implementation
procedure AllPoleFilter(
InOut:PAreal; { (i/o) on entrance InOut[-orderCoef] to
InOut[-1] contain the state of the
filter (delayed samples). InOut[0] to
InOut[lengthInOut-1] contain the filter
input, on en exit InOut[-orderCoef] to
InOut[-1] is unchanged and InOut[0] to
InOut[lengthInOut-1] contain filtered
samples }
Coef:PAreal;{ (i) filter coefficients, Coef[0] is assumed
to be 1.0 }
lengthInOut:integer;{ (i) number of input/output samples }
orderCoef:integer { (i) number of filter coefficients }
);
var
n,k:integer;
begin
for n:=0 to lengthInOut-1 do
begin
for k:=1 to orderCoef do
begin
InOut[0] :=InOut[0] - Coef[k]*InOut[-k];
end;
InOut:=@InOut[1];
end;
end;
{----------------------------------------------------------------*
* all-zero filter
*---------------------------------------------------------------}
procedure AllZeroFilter(
nIn:PAreal; { (i) In[0] to In[lengthInOut-1] contain
filter input samples }
Coef:PAreal;{ (i) filter coefficients (Coef[0] is assumed
to be 1.0) }
lengthInOut:integer;{ (i) number of input/output samples }
orderCoef:integer; { (i) number of filter coefficients }
nOut:PAreal { (i/o) on entrance Out[-orderCoef] to Out[-1]
contain the filter state, on exit Out[0]
to Out[lengthInOut-1] contain filtered
samples }
);
var
n,k:integer;
begin
for n:=0 to lengthInOut-1 do
begin
nOut[n] := Coef[0]*nIn[0];
for k:=1 to orderCoef do
begin
nOut[n] :=nOut[n]+ Coef[k]*nIn[-k];
end;
nIn:=@nIn[1];
end;
end;
{----------------------------------------------------------------*
* pole-zero filter
*---------------------------------------------------------------}
procedure ZeroPoleFilter(
nIn:PAreal; { (i) In[0] to In[lengthInOut-1] contain
filter input samples In[-orderCoef] to
In[-1] contain state of all-zero
section }
ZeroCoef:pareal;{ (i) filter coefficients for all-zero
section (ZeroCoef[0] is assumed to
be 1.0) }
PoleCoef:pareal;{ (i) filter coefficients for all-pole section
(ZeroCoef[0] is assumed to be 1.0) }
lengthInOut:integer;{ (i) number of input/output samples }
orderCoef:integer; { (i) number of filter coefficients }
nOut:pareal { (i/o) on entrance Out[-orderCoef] to Out[-1]
contain state of all-pole section. On
exit Out[0] to Out[lengthInOut-1]
contain filtered samples }
);
begin
AllZeroFilter(nIn,ZeroCoef,lengthInOut,orderCoef,nOut);
AllPoleFilter(nOut,PoleCoef,lengthInOut,orderCoef);
end;
{----------------------------------------------------------------*
* downsample (LP filter and decimation)
*---------------------------------------------------------------}
procedure DownSample (
nIn:PAreal; { (i) input samples }
Coef:pareal; { (i) filter coefficients }
lengthIn:integer; { (i) number of input samples }
state:pareal; { (i) filter state }
nOut:PAreal { (o) downsampled output }
);
var
o:real;
Out_ptr:^real;
Coef_ptr, In_ptr:^real;
state_ptr:^real;
i, j, stop:integer;
begin
Out_ptr := @nOut[0];
{ LP filter and decimate at the same time }
i := DELAY_DS;
while ( i < lengthIn) do
begin
Coef_ptr := @Coef[0];
In_ptr := @nIn[i];
state_ptr := @state[FILTERORDER_DS-2];
o := 0.0;
if (i < FILTERORDER_DS) then
stop := i + 1
else
stop := FILTERORDER_DS;
for j := 0 to stop-1 do
begin
o :=o + Coef_ptr^ * In_ptr^;
inc(Coef_ptr);
dec(In_ptr);
end;
for j := i + 1 to FILTERORDER_DS-1 do
begin
o :=o + Coef_ptr^ * (state_ptr^);
inc(Coef_ptr);
dec(state_ptr);
end;
Out_ptr^ := o;
inc(Out_ptr);
i:=i+FACTOR_DS;
end;
{ Get the last part (use zeros as input for the future) }
i:=(lengthIn+FACTOR_DS);
while ( i<(lengthIn+DELAY_DS)) do
begin
o:=0.0;
if (i<lengthIn) then
begin
Coef_ptr := @Coef[0];
In_ptr := @nIn[i];
for j:=0 to FILTERORDER_DS-1 do
begin
o :=o + Coef_ptr^ * Out_ptr^;
inc(Coef_ptr);
dec(Out_ptr);
end;
end
else
begin
Coef_ptr := @Coef[i-lengthIn];
In_ptr := @nIn[lengthIn-1];
for j:=0 to FILTERORDER_DS-(i-lengthIn)-1 do
begin
o := o+ Coef_ptr^ * In_ptr^;
inc(Coef_ptr);
dec(In_ptr);
end;
end;
Out_ptr^ := o;
inc(Out_ptr);
i:=i+FACTOR_DS;
end;
end;
end.
|
unit FAbout;
(*====================================================================
The About Dialog, available in Menu->Help->About
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
Windows
{$ELSE}
LCLIntf, LCLType, LMessages, ComCtrls,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls,
UTypes;
type
TFormAbout = class(TForm)
ButtonOK: TButton;
ButtonMoreInfo: TButton;
LabelAbout: TLabel;
Panel1: TPanel;
procedure ButtonOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ButtonMoreInfoClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormAbout: TFormAbout;
implementation
{$R *.dfm}
uses
ULang;
//-----------------------------------------------------------------------------
procedure TFormAbout.ButtonOKClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
//-----------------------------------------------------------------------------
procedure TFormAbout.FormCreate(Sender: TObject);
begin
// these constants are defined in UTypes
LabelAbout.Caption := About2;
end;
//-----------------------------------------------------------------------------
procedure TFormAbout.ButtonMoreInfoClick(Sender: TObject);
begin
Application.HelpContext(10);
end;
//-----------------------------------------------------------------------------
procedure TFormAbout.FormShow(Sender: TObject);
var S: ShortString;
begin
ActiveControl := ButtonOK;
end;
//-----------------------------------------------------------------------------
end.
|
{
StrFunctions by Mattias Fagerlund, mattias@cambrianlabs.com
}
unit StrFunctions;
interface
function GetBefore(sSubString, sLongString : string) : string;
function GetAfter(sSubString, sLongString : string) : string;
function GetReallyAfter(sSubString, sLongString : string) : string;
function GetBetween(sSubString, sLongString : string) : string;
function GetBetweenDifferent(sSubStringFirst,sSubStringSecond, sLongString : string) : string;
function GetNTh(sSubString, sLongString : string; iNumber : integer) : string;
function GetNThAsSingle(sSubString, sLongString : string; iNumber : integer) : single;
function RightStr(sLongString : string; count : integer) : string;
function LeftStr(sLongString : string; count : integer) : string;
function PadStr(sShortString, sLongString : string; count : integer) : string;
function StringPartsEqual(const sShortString, sLongString : string; CaseSensitive : boolean=true) : boolean;
function StringExists(sShortString, sLongString : string; CaseSensitive : boolean=true) : boolean;
function CL_IfThen(b : boolean; s1, s2 : string) : string;
implementation
uses
SysUtils;
function GetBefore(sSubString, sLongString : string) : string;
var
i : integer;
begin
i := Pos(sSubString, sLongString);
if i <> 0 then
GetBefore := Copy(sLongString,0, i-1)
else
GetBefore := '';
end;
function GetAfter(sSubString, sLongString : string) : string;
var
i : integer;
begin
i := Pos(sSubString, sLongString);
if i <> 0 then
GetAfter := Copy(sLongString,i+Length(sSubString), Length(sLongString)-i)
else
GetAfter := '';
end;
function GetReallyAfter(sSubString, sLongString : string) : string;
var
i : integer;
begin
i := Pos(sSubString, sLongString);
if i <> 0 then
Result := Copy(sLongString,i+Length(sSubString), Length(sLongString)-i)
else
Result := '';
end;
function GetBetween(sSubString, sLongString : string) : string;
begin
GetBetween := GetBefore(sSubString,GetAfter(sSubString,sLongString));
end;
function GetBetweenDifferent(sSubStringFirst,sSubStringSecond, sLongString : string) : string;
begin
GetBetweenDifferent := GetBefore(sSubStringSecond,GetReallyAfter(sSubStringFirst,sLongString));
end;
function GetNTh(sSubString, sLongString : string; iNumber : integer) : string;
var
i : integer;
sLongLeft : string;
sTempResult : string;
begin
sLongLeft := sLongString;
sLongLeft := sLongLeft + sSubString;
for i := 0 to iNumber do
begin
sTempResult := GetBefore(sSubString, sLongLeft);
sLongLeft := GetAfter(sSubString, sLongLeft);
end;
GetNth := sTempResult;
end;
function GetNThAsSingle(sSubString, sLongString : string; iNumber : integer) : single;
var
s : string;
begin
s := Trim(GetNTh(sSubString, sLongString, iNumber));
result := StrToFloat(s);
end;
function RightStr(sLongString : string; count : integer) : string;
begin
result := Copy(sLongString,length(sLongString)-count+1,count);
end;
function LeftStr(sLongString : string; count : integer) : string;
begin
result := Copy(sLongString,1,count);
end;
function PadStr(sShortString, sLongString : string; count : integer) : string;
begin
while Length(sLongString)<count do
sLongString := sShortString+sLongString;
result := sLongString;
end;
function StringPartsEqual(const sShortString, sLongString : string; CaseSensitive : boolean) : boolean;
begin
// We only care about part of the long string
if CaseSensitive then
result := (sShortString= Copy(sLongString,1, length(sShortString)))
else
result := (UpperCase(sShortString)=UpperCase( Copy(sLongString,1, length(sShortString))));
end;
function StringExists(sShortString, sLongString : string; CaseSensitive : boolean=true) : boolean;
begin
if CaseSensitive then
result := Pos(sShortString, sLongString)>0
else
result := Pos(UpperCase(sShortString),UpperCase(sLongString))>0;
end;
function CL_IfThen(b : boolean; s1, s2 : string) : string;
begin
if b then
result := s1
else
result := s2;
end;
end.
|
unit BasicVXLSETypes;
interface
uses Graphics, BasicMathsTypes;
type
TVoxelUnpacked = record
Colour,
Normal,
Flags: Byte;
Used: Boolean;
end;
TTempViewData = record
V : TVoxelUnpacked;
VC : TVector3i; // Cordinates of V
VU : Boolean; // Is V Used, if so we can do this to the VXL file when needed
X,Y : Integer;
end;
TTempView = record
Data : Array of TTempViewData;
Data_no : integer;
end;
TTempLine = record
x1 : integer;
y1 : integer;
x2 : integer;
y2 : integer;
colour : TColor;
width : integer;
end;
TTempLines = record
Data : Array of TTempLine;
Data_no : integer;
end;
TVoxelPacked = LongInt;
TThumbnail = record
Width, Height: Integer;
end;
TViewport = record
Left, Top, Zoom: Integer;
hasBeenUsed: Boolean; // this flag lets the ui know if this
// view has been used already (so zoom is a user setting)
end;
EError = (OK, ReadFailed, WriteFailed, InvalidSpanDataSizeCalced, InvalidSpan,
BadSpan_SecondVoxelCount, Unhandled_Exception);
EDrawMode = (ModeDraw, ModeFloodFill, ModeRectFill, ModeMagnify, ModeLine, ModeColSelect, ModeBrush, ModeRect, ModeSelect, ModePippet,
ModeErase, ModeBumpColour, ModeBumpDownColour,ModeFloodFillErase);
EClickMode = (ModeSingleClick, ModeDoubleClick);
ESpectrumMode = (ModeColours, ModeNormals);
EViewMode = (ModeFull, ModeEmphasiseDepth, ModeCrossSection);
EVoxelViewOrient = (oriX, oriY, oriZ);
EVoxelViewDir = (dirTowards, dirAway);
TVoxelType = (vtLand, vtAir);
implementation
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit uSynAttribs;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ConTEXTSynEdit, SynEdit, uCommon, Clipbrd,
ExtCtrls, SynEditHighlighter, uSafeRegistry,
SynEditTypes, uHighlighterProcs, uCommonClass;
type
TMySynAttrib = class
private
fName: string;
fBackground: TColor;
fForeground: TColor;
fStyle: TFontStyles;
public
procedure AssignToAttrib(HLAttrib: TSynHighlighterAttributes);
property Name: string read fName write fName;
property Background: TColor read fBackground write fBackground;
property Foreground: TColor read fForeground write fForeground;
property Style: TFontStyles read fStyle write fStyle;
end;
TMySynAttribList = class(TList)
private
function Get(Index: integer): TMySynAttrib;
procedure Put(Index: integer; const Value: TMySynAttrib);
public
constructor Create;
destructor Destroy; override;
procedure LoadSettings;
procedure SaveSettings;
function Add(Attrib: TMySynAttrib): integer; reintroduce;
function IndexOf(Name: string): integer;
function Exists(Name: string): boolean;
procedure AssignToHighlighter(HL: TSynCustomHighlighter);
procedure AddFromHighlighter(HL: TSynCustomHighlighter);
procedure Clear; override;
property Items[Index: integer]: TMySynAttrib read Get write Put; default;
end;
var
SynAttribList: TMySynAttribList;
implementation
////////////////////////////////////////////////////////////////////////////////////////////
// Property functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TMySynAttrib.AssignToAttrib(HLAttrib: TSynHighlighterAttributes);
begin
HLAttrib.Foreground:=fForeground;
HLAttrib.Background:=fBackground;
HLAttrib.Style:=fStyle;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Property functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
function TMySynAttribList.Get(Index: integer): TMySynAttrib;
begin
result:=inherited Get(Index);
end;
//------------------------------------------------------------------------------------------
procedure TMySynAttribList.Put(Index: integer; const Value: TMySynAttrib);
begin
inherited Put(Index, Value);
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
function TMySynAttribList.Add(Attrib: TMySynAttrib): integer;
begin
if not Exists(Attrib.Name) then
result:=inherited Add(Attrib)
else
result:=-1;
end;
//------------------------------------------------------------------------------------------
procedure TMySynAttribList.Clear;
var
i: integer;
begin
for i:=0 to Count-1 do
Items[i].Free;
inherited;
end;
//------------------------------------------------------------------------------------------
function TMySynAttribList.IndexOf(Name: string): integer;
var
i: integer;
begin
result:=-1;
Name:=UpperCase(Name);
i:=0;
while (i<Count) do begin
if (Items[i].Name=Name) then begin
result:=i;
BREAK;
end;
inc(i);
end;
end;
//------------------------------------------------------------------------------------------
function TMySynAttribList.Exists(Name: string): boolean;
begin
result:=(IndexOf(Name)<>-1);
end;
//------------------------------------------------------------------------------------------
procedure TMySynAttribList.LoadSettings;
begin
end;
//------------------------------------------------------------------------------------------
procedure TMySynAttribList.SaveSettings;
begin
end;
//------------------------------------------------------------------------------------------
procedure TMySynAttribList.AssignToHighlighter(HL: TSynCustomHighlighter);
var
i: integer;
n: integer;
begin
for i:=0 to HL.AttrCount-1 do begin
n:=IndexOf(HL.Attribute[i].Name);
if (n<>-1) then
Items[n].AssignToAttrib(HL.Attribute[i]);
end;
end;
//------------------------------------------------------------------------------------------
procedure TMySynAttribList.AddFromHighlighter(HL: TSynCustomHighlighter);
begin
// for i:=0 to HL.AttrCount-1 do begin
// Add(HL.Attribute[i].Name);
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Contructor, Destructor
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TMySynAttribList.Create;
begin
Capacity:=16;
end;
//------------------------------------------------------------------------------------------
destructor TMySynAttribList.Destroy;
begin
inherited;
end;
//------------------------------------------------------------------------------------------
initialization
// SynAttribList:=TMySynAttribList.Create;
finalization
// FreeAndNil(SynAttribList);
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, JPEG, PNGImage, System.Generics.Collections;
type
TGameItem = class
Image:TPNGImage;
name:String;
coords:TPoint;
RoomN:Shortint; //0 - inventory -1 - some strange place
constructor Create(const n:String;const RN:ShortInt; const coord:TPoint);
end;
TRoom = class
Image:TJPEGImage;
class var fRoomN:Byte;
class procedure setRoomN(const D:Byte);static;
class property RoomN:Byte read fRoomN write setRoomN;
constructor Create(const N:Byte);
end;
TForm1 = class(TForm)
procedure FormShow(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
private
Wid20,
Hei20:Word;
basementLight:Boolean;
BackBuffer:TBitmap;
Room:TList<TRoom>;
Items:TList<TGameItem>;
FlashLight:TPNGImage;
FlashCoord:TPoint;
procedure CreateItems;
procedure reDraw;
procedure Clicked(I:TGameItem);
function ItemClicked(const X,Y:Word):Boolean;
function FindItem(const n:String):TGameItem;
public
LiftAt:Byte;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
constructor TRoom.Create(const N:Byte);
begin
Image:=TJPEGImage.Create;
Image.LoadFromFile('RES\Rooms\r'+IntToStr(N)+'.jpg');
end;
constructor TGameItem.Create(const n:String;const RN:ShortInt; const coord:TPoint);
begin
Image:=TPNGImage.Create;
Image.LoadFromFile('RES\Objects\'+n+'.png');
RoomN:=RN;
name:=n;
Coords:=Coord;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
var z:TRoom;x:TGameItem;
begin
for z in Room do
z.Destroy;
Room.Destroy;
for x in Items do
x.Destroy;
Items.Destroy;
end;
function TForm1.ItemClicked(const X,Y:Word):Boolean;
var I:TGameItem;
Begin
Result:=false;
for I in Items do
if I.RoomN=TRoom.RoomN then
if (X>I.coords.X)and(X<I.coords.X+I.Image.Width)and(Y>I.coords.Y)and(Y<I.coords.Y+I.Image.Height) then
Begin
Clicked(I);
Result:=true;
Exit;
End;
End;
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if not ItemClicked(X,Y) then
Begin
if (x>ClientWidth-Wid20)and(ABS(y-(clientHeight div 2))<ClientHeight*0.1) then TRoom.RoomN:=4 else
if (x<Wid20)and(ABS(y-(clientHeight div 2))<ClientHeight*0.1) then TRoom.RoomN:=3 else
if (y>ClientHeight-Hei20)and(ABS(x-(clientWidth div 2))<ClientWidth*0.1) then TRoom.RoomN:=2 else
if (y<Hei20)and(ABS(x-(clientWidth div 2))<ClientWidth*0.1) then TRoom.RoomN:=1;
End;
Form1.Repaint;
end;
procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
reDraw;
if (TRoom.RoomN in [69..85])and((FindItem('flashlight')<>nil)and(FindItem('flashlight').RoomN=0)) then
Begin
FlashCoord.x:=x;
FlashCoord.y:=y;
End
end;
procedure TForm1.reDraw;
var I:TGameItem;
begin
if not(TRoom.RoomN in [69..85])or(BasementLight)or((FindItem('flashlight')<>nil)and(FindItem('flashlight').RoomN=0)) then
Begin
Backbuffer.Canvas.Draw(0,0,Room[TRoom.RoomN].Image);
for I in Items do
if I.RoomN=TRoom.RoomN then
Backbuffer.Canvas.Draw(I.coords.X,I.coords.Y,I.Image);
if (TRoom.RoomN in [69..85])and((FindItem('flashlight')<>nil)and(FindItem('flashlight').RoomN=0)) then
Backbuffer.Canvas.Draw(Flashcoord.x-480,Flashcoord.3y-240,FlashLight);
End
else
BackBuffer.Canvas.Draw(0,0,Room[0].Image);
canvas.Draw(0,0,BackBuffer);
end;
procedure TForm1.FormPaint(Sender: TObject);
begin
reDraw;
end;
procedure TForm1.CreateItems;
begin
FlashLight:=TPNGImage.Create;
FlashLight.LoadFromFile('RES\Objects\light.png');
Items:=TList<TGameItem>.create;
Items.Add(TGameItem.Create('elb',15,TPoint.Create(163,67)));
Items.Add(TGameItem.Create('elb',18,TPoint.Create(145,67)));
Items.Add(TGameItem.Create('elb',44,TPoint.Create(163,67)));
Items.Add(TGameItem.Create('elb',69,TPoint.Create(121,67)));
Items.Add(TGameItem.Create('elb',46,TPoint.Create(115,67)));
Items.Add(TGameItem.Create('elbup',17,TPoint.Create(7,43)));
Items.Add(TGameItem.Create('elbdn',17,TPoint.Create(7,80)));
Items.Add(TGameItem.Create('utkey',29,TPoint.Create(292,171)));
Items.Add(TGameItem.Create('corlockrclsd',12,TPoint.Create(49,94)));
Items.Add(TGameItem.Create('corlockropn',-1,TPoint.Create(49,94)));
Items.Add(TGameItem.Create('druglckrcls',14,TPoint.Create(247,65)));
Items.Add(TGameItem.Create('druglckropn',-1,TPoint.Create(247,65)));
Items.Add(TGameItem.Create('ffoodwindclsd',19,TPoint.Create(52,51)));
Items.Add(TGameItem.Create('ffoodwindopen',-1,TPoint.Create(52,48)));
Items.Add(TGameItem.Create('hardwarewindclsd',21,TPoint.Create(385,52)));
Items.Add(TGameItem.Create('hardwarewindopen',-1,TPoint.Create(385,52)));
Items.Add(TGameItem.Create('hardwarelckrclsd',21,TPoint.Create(436,148)));
Items.Add(TGameItem.Create('hardwarelckropen',-1,TPoint.Create(436,148)));
Items.Add(TGameItem.Create('fuseboxclsd',85,TPoint.Create(341,49)));
Items.Add(TGameItem.Create('fuseboxopen',-1,TPoint.Create(341,49)));
Items.Add(TGameItem.Create('helidrclsd',1,TPoint.Create(150,112)));
Items.Add(TGameItem.Create('helidropen',-1,TPoint.Create(150,112)));
Items.Add(TGameItem.Create('helifuelclsd',1,TPoint.Create(96,120)));
Items.Add(TGameItem.Create('helifuelopen',-1,TPoint.Create(96,120)));
end;
procedure TForm1.FormShow(Sender: TObject);
var z:Byte;
begin
BackBuffer:=TBitmap.Create;
BackBuffer.Width:=480;
BackBuffer.Height:=239;
Room:=TList<TRoom>.create;
Wid20:=Round(ClientWidth*0.1);
Hei20:=Round(ClientHeight*0.1);
for z := 0 to 89 do
Room.Add(TRoom.Create(z));
TRoom.fRoomN:=21;
CreateItems;
LiftAt:=2;
BasementLight:=false;
end;
procedure TForm1.Clicked(I: TGameItem);
begin
if I.name='elb' then
Begin
case TRoom.RoomN of
46:LiftAt:=4;
15:LiftAt:=3;
18:LiftAt:=2;
44:LiftAt:=1;
69:LiftAt:=0;
end;
End else
if I.name='elbup' then
Begin
if LiftAt<4 then LiftAt:=LiftAt+1
End else
if I.name='elbdn' then
Begin
if LiftAt>0 then LiftAt:=LiftAt-1
End;
if I.name='utkey' then
Begin
if I.RoomN<>0 then I.RoomN:=0
End else
if I.name='corlockrclsd' then
Begin
I.RoomN:=-1;
FindItem('corlockropn').RoomN:=12;
if FindItem('glove')=nil then
Begin
Items.Add(TGameItem.create('glove',12,TPoint.Create(50,200)));
Items.Add(TGameItem.create('can',12,TPoint.Create(100,190)));
End;
End else
if I.name='corlockropn' then
Begin
I.RoomN:=-1;
FindItem('corlockrclsd').RoomN:=12;
End else
if I.name='druglckrcls' then
Begin
I.RoomN:=-1;
FindItem('druglckropn').RoomN:=14;
if FindItem('medkit')=nil then
Begin
Items.Add(TGameItem.create('medkit',14,TPoint.Create(247,170)));
End;
End else
if I.name='druglckropn' then
Begin
I.RoomN:=-1;
FindItem('druglckrcls').RoomN:=14;
End else
if I.name='ffoodwindclsd' then
Begin
I.RoomN:=-1;
FindItem('ffoodwindopen').RoomN:=19;
End else
if I.name='ffoodwindopen' then
Begin
I.RoomN:=-1;
FindItem('ffoodwindclsd').RoomN:=19;
End else
if I.name='hardwarewindclsd' then
Begin
I.RoomN:=-1;
FindItem('hardwarewindopen').RoomN:=21;
End else
if I.name='hardwarewindopen' then
Begin
I.RoomN:=-1;
FindItem('hardwarewindclsd').RoomN:=21;
End else
if I.name='hardwarelckrclsd' then
Begin
I.RoomN:=-1;
FindItem('hardwarelckropen').RoomN:=21;
if FindItem('flashlight')=nil then
Begin
Items.Add(TGameItem.create('flashlight',21,TPoint.Create(380,210)));
End;
End else
if I.name='hardwarelckropen' then
Begin
I.RoomN:=-1;
FindItem('hardwarelckrclsd').RoomN:=21;
End else
if I.name='fuseboxclsd' then
Begin
I.RoomN:=-1;
FindItem('fuseboxopen').RoomN:=85;
End else
if I.name='fuseboxopen' then
Begin
I.RoomN:=-1;
FindItem('fuseboxclsd').RoomN:=85;
End else
if I.name='helidrclsd' then
Begin
I.RoomN:=-1;
FindItem('helidropen').RoomN:=1;
End else
if I.name='helidropen' then
Begin
I.RoomN:=-1;
FindItem('helidrclsd').RoomN:=1;
End else
if I.name='helifuelclsd' then
Begin
I.RoomN:=-1;
FindItem('helifuelopen').RoomN:=1;
End else
if I.name='helifuelopen' then
Begin
I.RoomN:=-1;
FindItem('helifuelclsd').RoomN:=1;
End else
if I.name='flashlight' then
Begin
I.RoomN:=0;
End;
end;
function TForm1.FindItem(const n: string):TGameItem;
var I:TGameItem;
begin
result:=nil;
for I in Items do
if I.name=n then
Begin
Result:=I;
exit;
End;
end;
class procedure TRoom.setRoomN(const D: Byte);
begin
case RoomN of
1:Case D of
1:Begin
if Form1.FindItem('helidropen').RoomN=1 then
fRoomN:=89
End;
4:fRoomN:=2
End;
2:Case D of
2:fRoomN:=3;
3:fRoomN:=1
End;
3:Case D of
1:fRoomN:=2;
2:fRoomN:=4
End;
4:Case D of
1:fRoomN:=3;
2:fRoomN:=5;
3:fRoomN:=7;
End;
5:Case D of
1:fRoomN:=4;
2:fRoomN:=6;
3:fRoomN:=28;
End;
6:Case D of
1:fRoomN:=5;
3:fRoomN:=30;
End;
7:Case D of
3:fRoomN:=8;
4:fRoomN:=4;
End;
8:Case D of
2:fRoomN:=9;
3:fRoomN:=10;
4:fRoomN:=7;
End;
9:Case D of
1:fRoomN:=8;
End;
10:Case D of
1:fRoomN:=12;
3:fRoomN:=11;
4:fRoomN:=8;
End;
11:Case D of
4:fRoomN:=10;
End;
12:Case D of
1:fRoomN:=13;
2:fRoomN:=10;
End;
13:Case D of
1:fRoomN:=15;
4:fRoomN:=14;
2:fRoomN:=12;
End;
14:Case D of
3:fRoomN:=13;
End;
15:Case D of
3:fRoomN:=16;
2:fRoomN:=13;
1:if Form1.LiftAt=3 then fRoomN:=17;
End;
16:Case D of
4:fRoomN:=15;
End;
//elevator
17:Case D of
2:Case Form1.LiftAt of
0:fRoomN:=69;
1:fRoomN:=44;
2:fRoomN:=18;
3:fRoomN:=15;
//check key
4:Begin
if Form1.FindItem('utkey').RoomN=0 then
fRoomN:=46;
End;
End;
End;
18:Case D of
1:if Form1.LiftAt=2 then fRoomN:=17;
2:fRoomN:=20;
3:fRoomN:=19;
End;
19:Case D of
4:fRoomN:=18;
End;
20:Case D of
1:fRoomN:=18;
2:fRoomN:=22;
4:fRoomN:=21;
End;
21:Case D of
3:fRoomN:=20;
End;
22:Case D of
1:fRoomN:=20;
2:fRoomN:=25;
3:fRoomN:=23;
4:fRoomN:=24;
End;
23:Case D of
4:fRoomN:=22;
End;
24:Case D of
3:fRoomN:=22;
End;
25:Case D of
1:fRoomN:=22;
2:fRoomN:=26;
4:fRoomN:=27;
End;
26:Case D of
1:fRoomN:=25;
End;
27:Case D of
3:fRoomN:=25;
4:fRoomN:=28;
End;
28:Case D of
2:fRoomN:=29;
3:fRoomN:=27;
4:fRoomN:=5;
End;
29:Case D of
1:fRoomN:=28;
End;
30:Case D of
3:fRoomN:=31;
4:fRoomN:=6;
End;
31:Case D of
2:fRoomN:=32;
3:fRoomN:=33;
4:fRoomN:=30;
End;
32:Case D of
1:fRoomN:=31;
End;
33:Case D of
1:fRoomN:=38;
2:fRoomN:=34;
3:fRoomN:=37;
4:fRoomN:=31;
End;
34:Case D of
1:fRoomN:=33;
2:fRoomN:=36;
3:fRoomN:=35;
End;
35:Case D of
2:fRoomN:=83;
4:fRoomN:=34;
End;
//outside down
36:Case D of
1:fRoomN:=34;
2:fRoomN:=68;
3:fRoomN:=88;
4:fRoomN:=51;
End;
37:Case D of
4:fRoomN:=33;
End;
38:Case D of
1:fRoomN:=40;
2:fRoomN:=33;
3:fRoomN:=39;
End;
39:Case D of
4:fRoomN:=38;
End;
40:Case D of
1:fRoomN:=44;
2:fRoomN:=38;
3:fRoomN:=41;
4:fRoomN:=42;
End;
41:Case D of
4:fRoomN:=40;
End;
42:Case D of
2:fRoomN:=43;
3:fRoomN:=40;
4:fRoomN:=60;
End;
43:Case D of
1:fRoomN:=42;
End;
44:Case D of
1:if Form1.LiftAt=1 then fRoomN:=17;
2:fRoomN:=40;
3:fRoomN:=47;
4:fRoomN:=45;
End;
45:Case D of
3:fRoomN:=44;
End;
46:Case D of
1:if Form1.LiftAt=4 then fRoomN:=17;
End;
47:Case D of
3:fRoomN:=48;
4:fRoomN:=44;
End;
//outside left
48:Case D of
1:fRoomN:=49;
2:fRoomN:=66;
3:fRoomN:=68;//death
4:fRoomN:=47;
End;
49:Case D of
1:fRoomN:=68;
2:fRoomN:=48;
3:fRoomN:=68;//death
End;
51:Case D of
2:fRoomN:=68;//death
3:fRoomN:=36;
4:fRoomN:=52;
End;
52:Case D of
2:fRoomN:=68;//death
3:fRoomN:=51;
4:fRoomN:=86;
End;
54:Case D of
1:fRoomN:=55;
2:fRoomN:=68;//death
3:fRoomN:=87;
4:fRoomN:=68;
End;
55:Case D of
1:fRoomN:=56;
2:fRoomN:=54;
4:fRoomN:=68;//death
End;
56:Case D of
1:fRoomN:=57;
2:fRoomN:=55;
4:fRoomN:=68;//death
End;
57:Case D of
1:fRoomN:=58;
2:fRoomN:=56;
4:fRoomN:=68;//death
End;
58:Case D of
1:fRoomN:=68;
2:fRoomN:=57;
3:fRoomN:=59;
4:fRoomN:=68;//death
End;
59:Case D of
1:fRoomN:=68;//death
3:fRoomN:=61;
4:fRoomN:=58;
End;
60:Case D of
1:fRoomN:=68;//death
3:fRoomN:=42;
4:fRoomN:=61;
End;
61:Case D of
1:fRoomN:=68;//death
3:fRoomN:=60;
4:fRoomN:=59;
End;
62:Case D of
1:fRoomN:=63;
2:fRoomN:=68;//death
3:fRoomN:=68;
4:fRoomN:=88;
End;
63:Case D of
1:fRoomN:=64;
2:fRoomN:=62;
3:fRoomN:=68;//death
End;
64:Case D of
1:fRoomN:=65;
2:fRoomN:=63;
3:fRoomN:=68;//death
End;
65:Case D of
1:fRoomN:=66;
2:fRoomN:=64;
3:fRoomN:=68;//death
End;
66:Case D of
1:fRoomN:=48;
2:fRoomN:=65;
3:fRoomN:=68;//death
End;
//basement
69:Case D of
1:if Form1.LiftAt=0 then fRoomN:=17;
3:fRoomN:=77;
4:fRoomN:=70;
End;
70:Case D of
3:fRoomN:=69;
4:fRoomN:=71;
End;
71:Case D of
2:fRoomN:=72;
3:fRoomN:=70;
4:fRoomN:=74;
End;
72:Case D of
1:fRoomN:=71;
2:fRoomN:=73;
End;
73:Case D of
1:fRoomN:=72;
2:fRoomN:=75;
End;
74:Case D of
3:fRoomN:=71;
End;
75:Case D of
1:fRoomN:=73;
3:fRoomN:=76;
End;
76:Case D of
4:fRoomN:=75;
End;
77:Case D of
3:fRoomN:=78;
4:fRoomN:=69;
End;
78:Case D of
2:fRoomN:=79;
4:fRoomN:=77;
End;
79:Case D of
1:fRoomN:=78;
2:fRoomN:=80;
End;
80:Case D of
1:fRoomN:=79;
2:fRoomN:=81;
4:fRoomN:=84;
End;
81:Case D of
1:fRoomN:=80;
2:fRoomN:=82;
End;
82:Case D of
1:fRoomN:=81;
4:fRoomN:=83;
End;
83:Case D of
1:fRoomN:=35;
3:fRoomN:=82;
End;
84:Case D of
3:fRoomN:=80;
4:fRoomN:=85;
End;
85:Case D of
3:fRoomN:=84;
End;
86:Case D of
2:fRoomN:=68;//death
3:fRoomN:=52;
4:fRoomN:=87;
End;
87:Case D of
2:fRoomN:=68;
3:fRoomN:=86;
4:fRoomN:=54;
End;
88:Case D of
2:fRoomN:=68;
3:fRoomN:=62;
4:fRoomN:=36;
End;
89:Case D of
4:fRoomN:=1;
End;
end;
Form1.Caption:=IntToStr(fRoomN)
end;
end.
|
unit ibSHSQLPlayer;
interface
uses
SysUtils, Classes,
SHDesignIntf,
ibSHDesignIntf, ibSHTool;
type
TibSHSQLPlayer = class(TibBTTool, IibSHSQLPlayer, IibSHBranch, IfbSHBranch)
private
FServer: string;
FMode: string;
FAbortOnError: Boolean;
FAfterError: string;
FAutoDDL: Boolean;
FDefaultSQLDialect: Integer;
FSignScript: Boolean;
FLockModeChanging: Boolean;
function GetServer: string;
procedure SetServer(Value: string);
function GetMode: string;
procedure SetMode(Value: string);
function GetAutoDDL: Boolean;
procedure SetAutoDDL(Value: Boolean);
function GetAbortOnError: Boolean;
procedure SetAbortOnError(Value: Boolean);
function GetAfterError: string;
procedure SetAfterError(Value: string);
function GetDefaultSQLDialect: Integer;
procedure SetDefaultSQLDialect(Value: Integer);
function GetSignScript: Boolean;
procedure SetSignScript(Value: Boolean);
protected
FBTCLDatabaseInternal: IibSHDatabase;
procedure SetOwnerIID(Value: TGUID); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Server: string read GetServer write SetServer;
property Mode: string read GetMode write SetMode;
property AutoDDL: Boolean read GetAutoDDL write SetAutoDDL;
property AbortOnError: Boolean read GetAbortOnError write SetAbortOnError;
property AfterError: string read GetAfterError write SetAfterError;
property DefaultSQLDialect: Integer read GetDefaultSQLDialect write SetDefaultSQLDialect;
property SignScript: Boolean read GetSignScript write SetSignScript;
end;
TibSHSQLPlayerFactory = class(TibBTToolFactory)
end;
procedure Register();
implementation
uses
ibSHConsts, ibSHSQLs,
ibSHSQLPlayerActions,
ibSHSQLPlayerEditors;
procedure Register();
begin
SHRegisterImage(GUIDToString(IibSHSQLPlayer), 'SQLPlayer.bmp');
SHRegisterImage(TibSHSQLPlayerPaletteAction.ClassName, 'SQLPlayer.bmp');
SHRegisterImage(TibSHSQLPlayerFormAction.ClassName, 'Form_SQLText.bmp');
SHRegisterImage(TibSHSQLPlayerToolbarAction_Run.ClassName, 'Button_Run.bmp');
SHRegisterImage(TibSHSQLPlayerToolbarAction_RunCurrent.ClassName, 'Button_RunTrace.bmp');
SHRegisterImage(TibSHSQLPlayerToolbarAction_RunFromCurrent.ClassName, 'Button_RunTraceAll.bmp');
SHRegisterImage(TibSHSQLPlayerToolbarAction_Pause.ClassName, 'Button_Stop.bmp');
SHRegisterImage(TibSHSQLPlayerToolbarAction_Region.ClassName, 'Button_Tree.bmp');
SHRegisterImage(TibSHSQLPlayerToolbarAction_Refresh.ClassName, 'Button_Refresh.bmp');
SHRegisterImage(TibSHSQLPlayerToolbarAction_Open.ClassName, 'Button_Open.bmp');
SHRegisterImage(TibSHSQLPlayerToolbarAction_Save.ClassName, 'Button_Save.bmp');
SHRegisterImage(TibSHSQLPlayerToolbarAction_SaveAs.ClassName, 'Button_SaveAs.bmp');
SHRegisterImage(TibSHSQLPlayerToolbarAction_RunFromFile.ClassName, 'Button_RunFromFile1.bmp');
SHRegisterImage(TibSHSQLPlayerEditorAction_CheckAll.ClassName, 'Button_Check.bmp');
SHRegisterImage(TibSHSQLPlayerEditorAction_UnCheckAll.ClassName, 'Button_UnCheck.bmp');
SHRegisterImage(SCallSQLStatements, 'Form_SQLText.bmp');
SHRegisterComponents([TibSHSQLPlayer, TibSHSQLPlayerFactory]);
SHRegisterActions([
// Palette
TibSHSQLPlayerPaletteAction,
// Forms
TibSHSQLPlayerFormAction,
// Toolbar
TibSHSQLPlayerToolbarAction_Run,
TibSHSQLPlayerToolbarAction_RunFromFile,
TibSHSQLPlayerToolbarAction_RunCurrent,
TibSHSQLPlayerToolbarAction_RunFromCurrent,
TibSHSQLPlayerToolbarAction_Pause,
TibSHSQLPlayerToolbarAction_Region,
TibSHSQLPlayerToolbarAction_Refresh,
TibSHSQLPlayerEditorAction_CheckAll,
TibSHSQLPlayerEditorAction_UnCheckAll,
TibSHSQLPlayerToolbarAction_Open,
TibSHSQLPlayerToolbarAction_Save,
TibSHSQLPlayerToolbarAction_SaveAs,
// Editors
TibSHSQLPlayerEditorAction_SendToSQLPlayer]);
SHRegisterPropertyEditor(IibSHSQLPlayer, SCallDefaultSQLDialect,
TibSHDefaultSQLDialectPropEditor);
SHRegisterPropertyEditor(IibSHSQLPlayer, SCallMode,
TibSHSQLPlayerModePropEditor);
SHRegisterPropertyEditor(IibSHSQLPlayer, SCallAfterError,
TibSHSQLPlayerAfterErrorPropEditor);
end;
{ TibBTSQLScript }
constructor TibSHSQLPlayer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMode := PlayerModes[0];
FAutoDDL := True;
FAbortOnError := True;
FDefaultSQLDialect := 3;
FSignScript := True;
FLockModeChanging := False;
MakePropertyVisible('AfterError');
FAfterError := PlayerAfterErrors[1];
end;
destructor TibSHSQLPlayer.Destroy;
begin
inherited Destroy;
end;
function TibSHSQLPlayer.GetServer: string;
begin
if Assigned(BTCLServer) then
Result := Format('%s (%s) ', [BTCLServer.Caption, BTCLServer.CaptionExt]);
end;
procedure TibSHSQLPlayer.SetServer(Value: string);
begin
if AnsiSameText(FMode, PlayerModes[0]) then
FServer := Value;
end;
function TibSHSQLPlayer.GetAutoDDL: Boolean;
begin
Result := FAutoDDL;
end;
function TibSHSQLPlayer.GetMode: string;
begin
Result := FMode;
end;
procedure TibSHSQLPlayer.SetMode(Value: string);
var
vPlayerForm: IibSHSQLPlayerForm;
begin
if not FLockModeChanging then
begin
try
FLockModeChanging := True;
if (FMode <> Value) then
begin
FMode := Value;
// Designer.UpdateObjectInspector;
if GetComponentFormIntf(IibSHSQLPlayerForm, vPlayerForm) then
begin
if AnsiSameText(PlayerModes[1], FMode) then
begin
if not vPlayerForm.ChangeNotification then
begin
FMode := PlayerModes[0];
vPlayerForm.ChangeNotification;
end;
end
else
vPlayerForm.ChangeNotification;
end;
end;
finally
FLockModeChanging := False;
end;
end;
Designer.UpdateActions;
end;
procedure TibSHSQLPlayer.SetAutoDDL(Value: Boolean);
begin
FAutoDDL := Value;
end;
function TibSHSQLPlayer.GetAbortOnError: Boolean;
begin
Result := FAbortOnError;
end;
procedure TibSHSQLPlayer.SetAbortOnError(Value: Boolean);
begin
FAbortOnError := Value;
if FAbortOnError then
MakePropertyVisible('AfterError')
else
MakePropertyInvisible('AfterError');
Designer.UpdateObjectInspector;
end;
function TibSHSQLPlayer.GetAfterError: string;
begin
Result := FAfterError;
end;
procedure TibSHSQLPlayer.SetAfterError(Value: string);
begin
FAfterError := Value;
end;
function TibSHSQLPlayer.GetDefaultSQLDialect: Integer;
begin
Result := FDefaultSQLDialect;
end;
procedure TibSHSQLPlayer.SetDefaultSQLDialect(Value: Integer);
begin
FDefaultSQLDialect := Value;
end;
function TibSHSQLPlayer.GetSignScript: Boolean;
begin
Result := FSignScript;
end;
procedure TibSHSQLPlayer.SetSignScript(Value: Boolean);
begin
FSignScript := Value;
end;
procedure TibSHSQLPlayer.SetOwnerIID(Value: TGUID);
begin
if AnsiSameText(FMode, PlayerModes[0]) then
begin
if not IsEqualGUID(OwnerIID, Value) then
begin
if Supports(Designer.FindComponent(Value), IibSHDatabase, FBTCLDatabaseIntf) then
begin
FBTCLServerIntf := FBTCLDatabaseIntf.BTCLServer;
MakePropertyInvisible('Server');
end
else
begin
Supports(Designer.FindComponent(Value), IibSHServer, FBTCLServerIntf);
FBTCLDatabaseIntf := nil;
MakePropertyVisible('Server');
end;
end;
inherited SetOwnerIID(Value);
end;
end;
initialization
Register;
end.
|
{
MODEL STATUS Not Working.
DOC STATUS Not Implemented.
CODEGEN STATUS Not Implemented.
}
unit utstrecordtypes;
{
UML 2.5 10.2.3.1 these should be represented as structured datatypes
with attributes. ? How to handle RPoint below.
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
// Model as Aggregated Association Classifiers.
// ?? could be done by just having more than one Association in datatype features ??
// ?? TRecord datatype in Model ??
// ?? «Record» keyword if viewed in diagram ??
Point = Record
X,Y,Z : Real;
end;
// functionally identical, semantically identical, CodeStyle different
// Require Packed {Feature | Member of TRecord}
{$PackRecords 1}
Trec2A = Record
A : Byte;
B : Word;
end;
{$PackRecords default}
Trec2B = Packed Record
A : Byte;
B : Word;
end;
// Requires Single Control Classifier (TDataType parent)
// Control Classifier Instance[s] -> Aggregated Association Classifier[s]
// OR Control Classifier Instance[s] -> TRecord
// ?? Probably requires seperate Model Class ??
//
RPoint = Record
Case Boolean of
False : (X,Y,Z : Real);
True : (R,theta,phi : Real);
end;
BetterRPoint = Record
Case UsePolar : Boolean of
False : (X,Y,Z : Real);
True : (R,theta,phi : Real);
end;
// ??????? Control Classifier implied integer ???
MyRec = Record
X : Longint;
Case byte of
2 : (Y : Longint;
case byte of
3 : (Z : Longint);
);
end;
implementation
end.
|
unit UnitDBFileDialogs;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Generics.Collections,
System.SysUtils,
System.Classes,
Winapi.Windows,
Winapi.ActiveX,
Winapi.ShlObj,
Vcl.Dialogs,
Vcl.ExtDlgs,
Dmitry.Utils.System,
Dmitry.Utils.Dialogs,
{$IFDEF PHOTODB}
uAppUtils,
uPortableDeviceManager,
{$ENDIF}
uConstants,
uMemory,
uVistaFuncs;
type
DBSaveDialog = class(TObject)
private
Dialog: TObject;
FFilterIndex: Integer;
FFilter: string;
procedure SetFilter(const Value: string);
procedure OnFilterIndexChanged(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
function Execute: Boolean;
procedure SetFilterIndex(const Value: Integer);
function GetFilterIndex: Integer;
function FileName: string;
procedure SetFileName(FileName: string);
property FilterIndex: Integer write SetFilterIndex;
property Filter: string read FFilter write SetFilter;
end;
type
DBOpenDialog = class(TObject)
private
Dialog: TObject;
FFilterIndex: Integer;
FFilter: string;
procedure SetFilter(const Value: string);
function GetShellItem: IShellItem;
public
constructor Create();
destructor Destroy; override;
function Execute: Boolean;
procedure SetFilterIndex(const Value: Integer);
function GetFilterIndex: Integer;
function FileName: string;
procedure SetFileName(FileName: string);
procedure SetOption(Option: TFileDialogOptions);
procedure EnableMultyFileChooseWithDirectory;
function GetFiles: TStrings;
procedure EnableChooseWithDirectory;
property FilterIndex: Integer write SetFilterIndex;
property Filter: string read FFilter write SetFilter;
property ShellItem: IShellItem read GetShellItem;
end;
type
DBOpenPictureDialog = class(TObject)
private
Dialog: TObject;
FFilterIndex: Integer;
FFilter: string;
procedure SetFilter(const Value: string);
public
constructor Create();
destructor Destroy; override;
function Execute: Boolean;
procedure SetFilterIndex(const Value: Integer);
function GetFilterIndex: Integer;
function FileName: string;
procedure SetFileName(FileName: string);
property FilterIndex: Integer write SetFilterIndex;
property Filter: string read FFilter write SetFilter;
end;
type
DBSavePictureDialog = class(TObject)
private
Dialog: TObject;
FFilterIndex: Integer;
FFilter: string;
procedure SetFilter(const Value: string);
procedure OnFilterIndexChanged(Sender: TObject);
public
constructor Create();
destructor Destroy; override;
function Execute: Boolean;
procedure SetFilterIndex(const Value: Integer);
function GetFilterIndex: Integer;
function FileName: string;
procedure SetFileName(FileName: string);
property FilterIndex: Integer write SetFilterIndex;
property Filter: string read FFilter write SetFilter;
end;
function DBSelectDir(Handle: THandle; Title: string): string; overload;
function DBSelectDir(Handle: THandle; Title, SelectedRoot: string): string; overload;
implementation
function GetDOSEnvVar(const VarName: string): string;
var
I: Integer;
begin
Result := '';
try
I := GetEnvironmentVariable(PWideChar(VarName), nil, 0);
if I > 0 then
begin
SetLength(Result, I);
GetEnvironmentVariable(PWideChar(VarName), PWideChar(Result), I);
end;
except
Result := '';
end;
end;
function CanUseVistaDlg: Boolean;
begin
Result := IsWindowsVista and (GetDOSEnvVar('SAFEBOOT_OPTION') = '');
end;
function DBSelectDir(Handle: THandle; Title: string): string;
begin
Result := DBSelectDir(Handle, Title, '');
end;
function GetItemName(Item: IShellItem; var ItemName: TFileName): HResult;
var
pszItemName: LPCWSTR;
begin
Result := Item.GetDisplayName(SIGDN_FILESYSPATH, pszItemName);
if Failed(Result) then
Result := Item.GetDisplayName(SIGDN_NORMALDISPLAY, pszItemName);
if Succeeded(Result) then
try
ItemName := pszItemName;
finally
CoTaskMemFree(pszItemName);
end;
end;
function DBSelectDir(Handle: THandle; Title, SelectedRoot: string): string;
var
OpenDialog: DBOpenDialog;
{$IFDEF PHOTODB}
Parent: IShellItem;
FullItemPath, RootShellPath: string;
I: Integer;
ShellItemName: TFileName;
ShellParentList: TList<IShellItem>;
{$ENDIF}
begin
Result := '';
if not CanUseVistaDlg then
begin
Result := SelectDirPlus(Handle, Title, SelectedRoot);
end else
begin
OpenDialog := DBOpenDialog.Create;
try
if SelectedRoot <> '' then
if DirectoryExists(SelectedRoot) then
OpenDialog.SetFileName(SelectedRoot);
OpenDialog.SetOption([FdoPickFolders]);
if OpenDialog.Execute then
Result := OpenDialog.FileName;
{$IFDEF PHOTODB}
FullItemPath := '';
if (Length(Result) > 2) and (Result[2] <> ':') and (OpenDialog.ShellItem <> nil) then
begin
ShellParentList := TList<IShellItem>.Create;
try
Parent := OpenDialog.ShellItem;
while Parent <> nil do
begin
ShellParentList.Add(Parent);
if not Succeeded(Parent.GetParent(Parent)) then
Break;
end;
if ShellParentList.Count > 2 then
begin
RootShellPath := '';
for I := 0 to ShellParentList.Count - 3 do
begin
GetItemName(ShellParentList[I], ShellItemName);
FullItemPath := ShellItemName + '\' + FullItemPath;
RootShellPath := ShellItemName;
end;
if CreateDeviceManagerInstance.GetDeviceByName(RootShellPath) <> nil then
Result := cDevicesPath + '\' + FullItemPath;
Result := ExcludeTrailingPathDelimiter(Result);
end;
finally
F(ShellParentList);
end;
end;
{$ENDIF}
finally
F(OpenDialog);
end;
end;
end;
{ DBSaveDialog }
constructor DBSaveDialog.Create;
begin
if CanUseVistaDlg then
begin
Dialog := TFileSaveDialog.Create(nil);
TFileSaveDialog(Dialog).OnTypeChange := OnFilterIndexChanged;
end else
begin
Dialog := TSaveDialog.Create(nil);
end;
end;
destructor DBSaveDialog.Destroy;
begin
F(Dialog);
end;
function DBSaveDialog.Execute : boolean;
begin
if CanUseVistaDlg then
Result := TFileSaveDialog(Dialog).Execute
else
Result := TSaveDialog(Dialog).Execute;
end;
function DBSaveDialog.FileName: string;
begin
if CanUseVistaDlg then
Result := TFileSaveDialog(Dialog).FileName
else
Result := TSaveDialog(Dialog).FileName;
end;
function DBSaveDialog.GetFilterIndex: integer;
begin
if CanUseVistaDlg then
Result := TFileSaveDialog(Dialog).FileTypeIndex
else
Result := TSaveDialog(Dialog).FilterIndex;
end;
procedure DBSaveDialog.OnFilterIndexChanged(Sender: TObject);
begin
TFileSaveDialog(Dialog).FileTypeIndex := TFileSaveDialog(Dialog).FileTypeIndex;
end;
procedure DBSaveDialog.SetFileName(FileName: string);
begin
if CanUseVistaDlg then
begin
TFileSaveDialog(Dialog).DefaultFolder := ExtractFileDir(FileName);
TFileSaveDialog(Dialog).FileName := ExtractFileName(FileName);
end else
begin
TSaveDialog(Dialog).FileName := FileName;
end;
end;
procedure DBSaveDialog.SetFilter(const Value: string);
var
I, P: Integer;
FilterStr: string;
FilterMask: string;
StrTemp: string;
IsFilterMask: Boolean;
begin
FFilter := Value;
if CanUseVistaDlg then
begin
// DataDase Results (*.ids)|*.ids|DataDase FileList (*.dbl)|*.dbl|DataDase ImTh Results (*.ith)|*.ith
P := 1;
IsFilterMask := False;
for I := 1 to Length(Value) do
if (Value[I] = '|') or (I = Length(Value)) then
begin
if I = Length(Value) then
StrTemp := Copy(Value, P, I - P + 1)
else
StrTemp := Copy(Value, P, I - P);
if not IsFilterMask then
FilterStr := StrTemp
else
FilterMask := StrTemp;
if IsFilterMask then
begin
with TFileSaveDialog(Dialog).FileTypes.Add() do
begin
DisplayName := FilterStr;
FileMask := FilterMask;
end;
end;
IsFilterMask := not IsFilterMask;
P := I + 1;
end;
end else
begin
TSaveDialog(Dialog).Filter := Value;
end;
end;
procedure DBSaveDialog.SetFilterIndex(const Value: Integer);
begin
FFilterIndex := Value;
if CanUseVistaDlg then
TFileSaveDialog(Dialog).FileTypeIndex := Value
else
TSaveDialog(Dialog).FilterIndex := Value;
end;
{ DBOpenDialog }
constructor DBOpenDialog.Create;
begin
if CanUseVistaDlg then
Dialog := TFileOpenDialog.Create(nil)
else
Dialog := TOpenDialog.Create(nil);
end;
destructor DBOpenDialog.Destroy;
begin
F(Dialog);
inherited;
end;
procedure DBOpenDialog.EnableChooseWithDirectory;
begin
if CanUseVistaDlg then
begin
TFileOpenDialog(Dialog).Options := TFileOpenDialog(Dialog).Options + [FdoPickFolders, FdoStrictFileTypes];
TFileOpenDialog(Dialog).Files;
end else
begin
TOpenDialog(Dialog).Options := TOpenDialog(Dialog).Options + [OfPathMustExist, OfFileMustExist, OfEnableSizing];
end;
end;
procedure DBOpenDialog.EnableMultyFileChooseWithDirectory;
begin
if CanUseVistaDlg then
begin
TFileOpenDialog(Dialog).Options := TFileOpenDialog(Dialog).Options + [FdoPickFolders, FdoForceFileSystem,
FdoAllowMultiSelect, FdoPathMustExist, FdoFileMustExist,
FdoForcePreviewPaneOn];
TFileOpenDialog(Dialog).Files;
end else
begin
TOpenDialog(Dialog).Options := TOpenDialog(Dialog).Options + [OfAllowMultiSelect, OfPathMustExist,
OfFileMustExist, OfEnableSizing];
end;
end;
function DBOpenDialog.Execute: Boolean;
begin
if CanUseVistaDlg then
Result := TFileOpenDialog(Dialog).Execute
else
Result := TOpenDialog(Dialog).Execute;
end;
function DBOpenDialog.FileName: string;
begin
if CanUseVistaDlg then
Result := TFileOpenDialog(Dialog).FileName
else
Result := TOpenDialog(Dialog).FileName;
end;
function DBOpenDialog.GetFiles: TStrings;
begin
if CanUseVistaDlg then
Result := TFileOpenDialog(Dialog).Files
else
Result := TOpenDialog(Dialog).Files;
end;
function DBOpenDialog.GetFilterIndex: Integer;
begin
if CanUseVistaDlg then
Result := TFileOpenDialog(Dialog).FileTypeIndex
else
Result := TOpenDialog(Dialog).FilterIndex;
end;
function DBOpenDialog.GetShellItem: IShellItem;
begin
if CanUseVistaDlg then
Result := TFileOpenDialog(Dialog).ShellItem
else
Result := nil; //not supported
end;
procedure DBOpenDialog.SetFileName(FileName: string);
begin
if CanUseVistaDlg then
begin
TFileOpenDialog(Dialog).DefaultFolder := ExtractFileDir(FileName);
TFileOpenDialog(Dialog).FileName := ExtractFileName(FileName);
end else
begin
TOpenDialog(Dialog).FileName := FileName;
end;
end;
procedure DBOpenDialog.SetFilter(const Value: string);
var
I, P: Integer;
FilterStr: string;
FilterMask: string;
StrTemp: string;
IsFilterMask: Boolean;
FileType: TFileTypeItem;
begin
FFilter := Value;
if CanUseVistaDlg then
begin
// DataDase Results (*.ids)|*.ids|DataDase FileList (*.dbl)|*.dbl|DataDase ImTh Results (*.ith)|*.ith
P := 1;
IsFilterMask := False;
for I := 1 to Length(Value) do
if (Value[I] = '|') or (I = Length(Value)) then
begin
if I = Length(Value) then
StrTemp := Copy(Value, P, I - P + 1)
else
StrTemp := Copy(Value, P, I - P);
if not IsFilterMask then
FilterStr := StrTemp
else
FilterMask := StrTemp;
if IsFilterMask then
begin
FileType := TFileOpenDialog(Dialog).FileTypes.Add();
FileType.DisplayName := FilterStr;
FileType.FileMask := FilterMask;
end;
IsFilterMask := not IsFilterMask;
P := I + 1;
end;
end else
begin
TOpenDialog(Dialog).Filter := Value;
end;
end;
procedure DBOpenDialog.SetFilterIndex(const Value: Integer);
begin
FFilterIndex := Value;
if CanUseVistaDlg then
TFileSaveDialog(Dialog).FileTypeIndex := Value
else
TOpenDialog(Dialog).FilterIndex := Value;
end;
procedure DBOpenDialog.SetOption(Option: TFileDialogOptions);
begin
if CanUseVistaDlg then
TFileSaveDialog(Dialog).Options := TFileSaveDialog(Dialog).Options + Option;
end;
{ DBOpenPictureDialog }
constructor DBOpenPictureDialog.Create;
begin
inherited;
if CanUseVistaDlg then
begin
Dialog := TFileOpenDialog.Create(nil);
TFileOpenDialog(Dialog).Options := TFileOpenDialog(Dialog).Options + [FdoForcePreviewPaneOn];
end else
begin
Dialog := TOpenPictureDialog.Create(nil);
end;
end;
destructor DBOpenPictureDialog.Destroy;
begin
F(Dialog);
end;
function DBOpenPictureDialog.Execute: Boolean;
begin
if CanUseVistaDlg then
Result := TFileOpenDialog(Dialog).Execute
else
Result := TOpenPictureDialog(Dialog).Execute;
end;
function DBOpenPictureDialog.FileName: string;
begin
if CanUseVistaDlg then
Result := TFileOpenDialog(Dialog).FileName
else
Result := TOpenPictureDialog(Dialog).FileName;
end;
function DBOpenPictureDialog.GetFilterIndex: Integer;
begin
if CanUseVistaDlg then
Result := TFileOpenDialog(Dialog).FileTypeIndex
else
Result := TOpenPictureDialog(Dialog).FilterIndex;
end;
procedure DBOpenPictureDialog.SetFileName(FileName: string);
begin
if CanUseVistaDlg then
begin
TFileOpenDialog(Dialog).DefaultFolder := ExtractFileDir(FileName);
TFileOpenDialog(Dialog).FileName := ExtractFileName(FileName);
end else
begin
TOpenPictureDialog(Dialog).FileName := FileName;
end;
end;
procedure DBOpenPictureDialog.SetFilter(const Value: string);
var
I, P: Integer;
FilterStr: string;
FilterMask: string;
StrTemp: string;
IsFilterMask: Boolean;
FileType: TFileTypeItem;
begin
FFilter := Value;
if CanUseVistaDlg then
begin
// DataDase Results (*.ids)|*.ids|DataDase FileList (*.dbl)|*.dbl|DataDase ImTh Results (*.ith)|*.ith
P := 1;
IsFilterMask := False;
for I := 1 to Length(Value) do
if (Value[I] = '|') or (I = Length(Value)) then
begin
if I = Length(Value) then
StrTemp := Copy(Value, P, I - P + 1)
else
StrTemp := Copy(Value, P, I - P);
if not IsFilterMask then
FilterStr := StrTemp
else
FilterMask := StrTemp;
if IsFilterMask then
begin
FileType := TFileSaveDialog(Dialog).FileTypes.Add();
FileType.DisplayName := FilterStr;
FileType.FileMask := FilterMask;
end;
IsFilterMask := not IsFilterMask;
P := I + 1;
end;
end else
begin
TOpenPictureDialog(Dialog).Filter := Value;
end;
end;
procedure DBOpenPictureDialog.SetFilterIndex(const Value: Integer);
begin
FFilterIndex := Value;
if CanUseVistaDlg then
TFileSaveDialog(Dialog).FileTypeIndex := Value
else
TOpenPictureDialog(Dialog).FilterIndex := Value;
end;
{ DBSavePictureDialog }
constructor DBSavePictureDialog.Create;
begin
if CanUseVistaDlg then
begin
Dialog := TFileSaveDialog.Create(nil);
TFileSaveDialog(Dialog).Options := TFileSaveDialog(Dialog).Options + [FdoForcePreviewPaneOn];
TFileSaveDialog(Dialog).OnTypeChange := OnFilterIndexChanged;
end else
begin
Dialog := TSavePictureDialog.Create(nil);
end;
end;
destructor DBSavePictureDialog.Destroy;
begin
F(Dialog);
inherited;
end;
function DBSavePictureDialog.Execute: boolean;
begin
if CanUseVistaDlg then
Result := TFileSaveDialog(Dialog).Execute
else
Result := TSavePictureDialog(Dialog).Execute;
end;
function DBSavePictureDialog.FileName: string;
begin
if CanUseVistaDlg then
Result := TFileSaveDialog(Dialog).FileName
else
Result := TSavePictureDialog(Dialog).FileName;
end;
function DBSavePictureDialog.GetFilterIndex: Integer;
begin
if CanUseVistaDlg then
Result := TFileSaveDialog(Dialog).FileTypeIndex
else
Result := TSavePictureDialog(Dialog).FilterIndex;
end;
procedure DBSavePictureDialog.OnFilterIndexChanged(Sender: TObject);
begin
TFileSaveDialog(Dialog).FileTypeIndex := TFileSaveDialog(Dialog).FileTypeIndex;
end;
procedure DBSavePictureDialog.SetFileName(FileName: string);
begin
if CanUseVistaDlg then
begin
TFileSaveDialog(Dialog).DefaultFolder := ExtractFileDir(FileName);
TFileSaveDialog(Dialog).FileName := ExtractFileName(FileName);
end else
begin
TSavePictureDialog(Dialog).FileName := FileName;
end;
end;
procedure DBSavePictureDialog.SetFilter(const Value: string);
var
I, P: Integer;
FilterStr: string;
FilterMask: string;
StrTemp: string;
IsFilterMask: Boolean;
FileType: TFileTypeItem;
begin
FFilter := Value;
if CanUseVistaDlg then
begin
// DataDase Results (*.ids)|*.ids|DataDase FileList (*.dbl)|*.dbl|DataDase ImTh Results (*.ith)|*.ith
P := 1;
IsFilterMask := False;
for I := 1 to Length(Value) do
if (Value[I] = '|') or (I = Length(Value)) then
begin
if I = Length(Value) then
StrTemp := Copy(Value, P, I - P + 1)
else
StrTemp := Copy(Value, P, I - P);
if not IsFilterMask then
FilterStr := StrTemp
else
FilterMask := StrTemp;
if IsFilterMask then
begin
FileType := TFileSaveDialog(Dialog).FileTypes.Add();
FileType.DisplayName := FilterStr;
FileType.FileMask := FilterMask;
end;
IsFilterMask := not IsFilterMask;
P := I + 1;
end;
end else
begin
TSavePictureDialog(Dialog).Filter := Value;
end;
end;
procedure DBSavePictureDialog.SetFilterIndex(const Value: Integer);
begin
FFilterIndex := Value;
if CanUseVistaDlg then
TFileSaveDialog(Dialog).FileTypeIndex := Value
else
TSavePictureDialog(Dialog).FilterIndex := Value;
end;
end.
|
unit uMenu;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.Imaging.jpeg, Vcl.StdCtrls, Vcl.ComCtrls, uPersistencia,
uControleTelas;
type
TfMenu = class(TForm)
btnUsuario: TButton;
btnCliente: TButton;
btnProduto: TButton;
btnPedido: TButton;
btnEntradaEstoque: TButton;
btnFaturamento: TButton;
btnRelatorios: TButton;
Label1: TLabel;
lblVersao: TLabel;
procedure btnUsuarioClick(Sender: TObject);
procedure btnClienteClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnProdutoClick(Sender: TObject);
procedure btnPedidoClick(Sender: TObject);
procedure btnEntradaEstoqueClick(Sender: TObject);
procedure btnFaturamentoClick(Sender: TObject);
procedure btnRelatoriosClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fMenu: TfMenu;
implementation
{$R *.dfm}
procedure TfMenu.btnPedidoClick(Sender: TObject);
begin
ControleTelas.chamaTela(btnPedido.Hint);
end;
procedure TfMenu.btnProdutoClick(Sender: TObject);
begin
ControleTelas.chamaTela(btnProduto.Hint);
end;
procedure TfMenu.btnUsuarioClick(Sender: TObject);
begin
ControleTelas.chamaTela(btnUsuario.Hint);
end;
procedure TfMenu.btnRelatoriosClick(Sender: TObject);
begin
ControleTelas.chamaTela(btnRelatorios.Hint);
end;
procedure TfMenu.btnEntradaEstoqueClick(Sender: TObject);
begin
ControleTelas.chamaTela(btnEntradaEstoque.Hint);
end;
procedure TfMenu.btnFaturamentoClick(Sender: TObject);
begin
ControleTelas.chamaTela(btnFaturamento.Hint);
end;
procedure TfMenu.btnClienteClick(Sender: TObject);
begin
ControleTelas.chamaTela(btnCliente.Hint);
end;
procedure TfMenu.FormCreate(Sender: TObject);
begin
Persistencia.qTelasLoginPossui.Parameters.ParamByName('idUsuario').Value :=
Persistencia.qLoginID.AsInteger;
Persistencia.qTelasLoginPossui.Open;
btnUsuario.Visible := Persistencia.qTelasLoginPossui.Locate('NOME',
btnUsuario.Hint, []);
btnCliente.Visible := Persistencia.qTelasLoginPossui.Locate('NOME',
btnCliente.Hint, []);
btnProduto.Visible := Persistencia.qTelasLoginPossui.Locate('NOME',
btnProduto.Hint, []);
btnPedido.Visible := Persistencia.qTelasLoginPossui.Locate('NOME',
btnPedido.Hint, []);
btnEntradaEstoque.Visible := Persistencia.qTelasLoginPossui.Locate('NOME',
btnEntradaEstoque.Hint, []);
btnFaturamento.Visible := Persistencia.qTelasLoginPossui.Locate('NOME',
btnFaturamento.Hint, []);
btnRelatorios.Visible := Persistencia.qTelasLoginPossui.Locate('NOME',
btnRelatorios.Hint, []);
lblVersao.Caption := ParamStr(3);
end;
procedure TfMenu.FormDestroy(Sender: TObject);
begin
Persistencia.qTelasLoginPossui.Close;
Persistencia.qLogin.Close;
Persistencia.qLogin.Open;
end;
Initialization
RegisterClass(TfMenu);
Finalization
UnRegisterClass(TfMenu);
end.
|
//=============================================================================
// sgShared.pas
//=============================================================================
//
// The shared data and functions that are private to the SwinGame SDK. This
// unit should not be accessed directly by games.
//
// Change History:
//
// Version 3:
// - 2009-12-21: Andrew : Write exceptions to stderr if not raised.
// - 2009-12-18: Andrew : Added screen rect cache
// - 2009-12-10: Andrew : Added iter free - fixed memory leak
// - 2009-11-11: Andrew : Switched to release rather than drain on the autorelease pool
// - 2009-11-06: Andrew : Added resource management type code
// - 2009-10-16: Andrew : Added the free notifier, so it can be called from many places
// - 2009-07-29: Andrew : Added flag for opened audio.
// - 2009-07-27: Andrew : Added code to cycle auto release pool for Objective C
// : Fixed possible double release of AutoRelease pool
// - 2009-07-10: Andrew : Added initialisation code
// - 2009-06-23: Clinton: Comment/format cleanup/tweaks
// : Slight optimization to NewSDLRect (redundant code)
// : Renamed scr to screen
// - 2009-06-05: Andrew : Created to contain all globals that are hidden from
// the library
//=============================================================================
unit sgShared;
//=============================================================================
interface
uses
stringhash, sgInputBackend, sgTypes, sgBackendTypes;
//=============================================================================
type
RectPtr = ^Rectangle;
// The resource contain is an object to hold the resource for the
// hash table
TResourceContainer = class(tObject)
private
resource_val : Pointer;
public
constructor Create(data: Pointer);
property Resource: Pointer read resource_val;
end;
// The resource contain is an object to hold the resource for the
// hash table
TIntegerContainer = class(tObject)
private
val : Longint;
public
constructor Create(data: Longint);
property Value: Longint read val write val;
end;
// Used by release all
ReleaseFunction = procedure(const name: String);
IntProc = procedure(val: Longword);
// Immediate if
function iif(pred: Boolean; trueVal, falseVal: Single): Single; overload;
// Calls Release on all of the resources in the tbl hash table.
procedure ReleaseAll(tbl: TStringHash; releaser: ReleaseFunction);
procedure XYFromOpts(const opts: DrawingOptions; var x, y: Single);
// Rounds `x` up... 1.1 -> 2
function Ceiling(x: Single): Longint;
// Used by SwinGame units to register event "handlers" what will be called
// when SDL events have occured. Events such as mouse movement, button
// clicking and key changes (up/down). See sgInput.
// procedure RegisterEventProcessor(handle: EventProcessPtr; handle2: EventStartProcessPtr);
// All SwinGame initialisation code must call this before performing any processing...
procedure InitialiseSwinGame();
procedure RaiseException(const message: String);
procedure RaiseWarning(const message: String);
{$IFDEF DARWIN}
{$IFDEF NO_ARC}
procedure CyclePool();
{$ENDIF}
// procedure BringForeground();
{$ENDIF}
function RoundUByte(val: Double): Byte;
function RoundInt(val: Double): LongInt;
function RoundUShort(val: Double): Word;
function RoundShort(val: Double): Smallint;
function StrToSingle(const val: String): Single;
function StrToUByte(const val: String): Byte;
/// Called when ANY resource is freed to inform other languages to remove from
/// their caches.
procedure CallFreeNotifier(p: Pointer);
// Global variables that can be shared.
var
// The base path to the program's executable.
applicationPath: String = '';
// The singleton instance manager used to check events and called
// registered "handlers". See `RegisterEventProcessor`.
//sdlManager: TSDLManager = nil;
// The name of the icon file shown.
// TODO: Does this work? Full path or just resource/filename?
iconFile: String = '';
// Contains the last error message that has occured if `HasException` is
// true. If multiple error messages have occured, only the last is stored.
// Used only by the generated library code.
ErrorMessage: String = '';
// This flag is set to true if an error message has occured. Used only by
// the generated library code.
HasException: Boolean = False;
// This flag indicates if the audio has been opened.
AudioOpen: Boolean = False;
// The function pointer to call into the other language to tell them something was freed
_FreeNotifier: FreeNotifier = nil;
// Timing details related to calculating FPS
_lastUpdateTime: Longword = 0;
_UpdateFPSData: IntProc = nil;
UseExceptions: Boolean = True;
// The main application window -- close this to quit
_PrimaryWindow: WindowPtr;
// The one the programmer has currently selected
_CurrentWindow: WindowPtr;
const
DLL_VERSION = 'TEST BUILD';
{$ifndef FPC}
LineEnding = #13#10; // Delphi Windows \r\n pair
{$endif}
//=============================================================================
implementation
uses
SysUtils, Math, Classes, StrUtils,
sgTrace, sgGraphics,
sgImages, sgDriver, sgDriverImages,
sgDrawingOptions, sgCamera;
//=============================================================================
var
is_initialised: Boolean = False;
//----------------------------------------------------------------------------
// Global variables for Mac OS Autorelease Pool
//----------------------------------------------------------------------------
{$ifdef DARWIN}
{$IFDEF NO_ARC}
NSAutoreleasePool: Pointer;
pool: Pointer = nil;
{$ENDIF}
{$endif}
//---------------------------------------------------------------------------
// OS X dylib external link
//---------------------------------------------------------------------------
{$ifdef DARWIN}
{$linklib libobjc.dylib}
{$IFNDEF IOS}
procedure NSApplicationLoad(); cdecl; external 'Cocoa'; {$EXTERNALSYM NSApplicationLoad}
{$ENDIF}
function objc_getClass(name: PChar): Pointer; cdecl; external 'libobjc.dylib'; {$EXTERNALSYM objc_getClass}
function sel_registerName(name: PChar): Pointer; cdecl; external 'libobjc.dylib'; {$EXTERNALSYM sel_registerName}
function class_respondsToSelector(cls, sel: Pointer): Boolean; cdecl; external 'libobjc.dylib'; {$EXTERNALSYM class_respondsToSelector}
function objc_msgSend(self, cmd: Pointer): Pointer; cdecl; external 'libobjc.dylib'; {$EXTERNALSYM objc_msgSend}
// function objc_msgSendSender(self, cmd, sender: Pointer): Pointer; cdecl; external 'libobjc.dylib' name 'objc_msgSend'; {$EXTERNALSYM objc_msgSend}
{$endif}
constructor TResourceContainer.create(data: Pointer);
begin
inherited create;
resource_val := data;
end;
constructor TIntegerContainer.create(data: Longint);
begin
inherited create;
val := data;
end;
// {$ifdef DARWIN}
// procedure BringForeground();
// var
// NSApplication: Pointer;
// app, wnd: Pointer;
// begin
// NSApplication := objc_getClass('NSApplication');
// app := objc_msgSend(NSApplication, sel_registerName('sharedApplication'));
// WriteLn('App: ', HexStr(app));
// objc_msgSendSender(app, sel_registerName('hideOtherApplications:'), nil);
// end;
// {$endif}
procedure InitialiseSwinGame();
begin
if is_initialised then exit;
is_initialised := True;
{$IFDEF TRACE}
TraceEnter('sgShared', 'InitialiseSwinGame', '');
{$ENDIF}
Randomize();
{$ifdef DARWIN}
{$IFDEF Trace}
TraceIf(tlInfo, 'sgShared', 'INFO', 'InitialiseSwinGame', 'Loading Mac version');
{$ENDIF}
//FIX: Error with Mac and FPC 2.2.2
SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]);
{$IFNDEF IOS}
{$IFDEF NO_ARC}
NSAutoreleasePool := objc_getClass('NSAutoreleasePool');
pool := objc_msgSend(NSAutoreleasePool, sel_registerName('alloc'));
pool := objc_msgSend(pool, sel_registerName('init'));
{$ENDIF}
NSApplicationLoad();
{$endif}
{$endif}
{$IFDEF Trace}
TraceIf(tlInfo, 'sgShared', 'INFO', 'InitialiseSwinGame', 'About to initialise SDL');
{$ENDIF}
if not Assigned(Driver.Init) then LoadDefaultDriver();
Driver.Init();
{$IFDEF TRACE}
TraceExit('sgShared', 'InitialiseSwinGame');
{$ENDIF}
end;
{$ifdef DARWIN}
{$IFDEF NO_ARC}
// No longer needed with SDL 1.2 static libraries...?
//
procedure CyclePool();
begin
if class_respondsToSelector(NSAutoreleasePool, sel_registerName('drain')) then
begin
//Drain the pool - releases it
objc_msgSend(pool, sel_registerName('drain'));
// WriteLn('Drain');
//Create a new pool
pool := objc_msgSend(NSAutoreleasePool, sel_registerName('alloc'));
pool := objc_msgSend(pool, sel_registerName('init'));
end;
end;
{$ENDIF}
{$endif}
function Ceiling(x: Single): Longint;
begin
result := Round(x);
if result < x then result := result + 1;
end;
procedure RaiseException(const message: String);
begin
HasException := True;
ErrorMessage := message;
{$IFDEF TRACE}
TraceIf(tlError, '', 'EXCP', '** Exception Raised **', message);
TraceExit('', 'Ended with exception');
{$ENDIF}
if UseExceptions then raise Exception.Create(message)
else
begin
// Wrap in error handler as exception will be raised on
// Windows when program is an app and stderr is "full"
try
WriteLn(stderr, message);
except
end;
end;
end;
procedure RaiseWarning(const message: String);
begin
// Watch for exceptions with this on Windows
try
WriteLn(stderr, message);
except
end;
{$IFDEF Trace}
TraceIf(tlWarning, '', 'WARN', '** Warning Raised **', message);
{$ENDIF}
end;
//---------------------------------------------------------------------------
procedure CallFreeNotifier(p: Pointer);
begin
if Assigned(_FreeNotifier) then
begin
try
_FreeNotifier(p);
except
ErrorMessage := 'Error calling free notifier';
HasException := True;
end;
end;
end;
//----------------------------------------------------------------------------
procedure ReleaseAll(tbl: TStringHash; releaser: ReleaseFunction);
var
iter: TStrHashIterator;
names: array of String;
i: Integer;
begin
if tbl.count = 0 then exit;
SetLength(names, tbl.count);
iter := tbl.getIterator();
i := 0;
while i < Length(names) do
begin
names[i] := iter.key;
i := i + 1;
iter.next;
end;
if Assigned(releaser) then
begin
for i := Low(names) to High(names) do
begin
releaser(names[i]);
end;
end;
iter.Free();
tbl.deleteAll();
end;
function iif(pred: Boolean; trueVal, falseVal: Single): Single; overload;
begin
if pred then result := trueVal
else result := falseVal;
end;
function RoundUByte(val: Double): Byte;
begin
result := Byte(Round(val));
end;
function RoundInt(val: Double): LongInt;
begin
result := LongInt(Round(val));
end;
function RoundUShort(val: Double): Word;
begin
result := Word(Round(val));
end;
function RoundShort(val: Double): SmallInt;
begin
result := SmallInt(Round(val));
end;
function StrToSingle(const val: String): Single;
begin
result := Single(StrToFloat(val));
end;
function StrToUByte(const val: String): Byte;
begin
result := Byte(StrToInt(val));
end;
procedure XYFromOpts(const opts: DrawingOptions; var x, y: Single);
begin
// check cases where drawn without camera...
case opts.camera of
DrawToScreen: exit;
DrawDefault: if opts.dest <> _CurrentWindow then exit;
end;
// update location using camera
x := ToScreenX(x);
y := ToScreenY(y);
end;
//=============================================================================
initialization
begin
InitialiseSwinGame();
end;
//=============================================================================
finalization
begin
{$ifdef DARWIN}
{$IFDEF NO_ARC}
if not assigned(pool) then
begin
pool := objc_msgSend(NSAutoreleasePool, sel_registerName('alloc'));
pool := objc_msgSend(pool, sel_registerName('init'));
end;
{$ENDIF}
{$endif}
Driver.Quit();
{$ifdef DARWIN}
{$IFDEF NO_ARC}
// last pool will self drain...
if assigned(pool) then
begin
objc_msgSend(pool, sel_registerName('drain'));
end;
pool := nil;
NSAutoreleasePool := nil;
{$ENDIF}
{$endif}
end;
end. |
{ *********************************************************************** }
{ }
{ GUI Hangman }
{ Version 1.0 - First release of program }
{ Last Revised: 27nd of July 2004 }
{ Copyright (c) 2004 Chris Alley }
{ }
{ *********************************************************************** }
unit UPlayerReport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, QRCtrls, QuickRpt, ExtCtrls;
type
TPlayerReportForm = class(TForm)
PlayerQuickRep: TQuickRep;
V: TQRBand;
PlayerReportQRLabel: TQRLabel;
PlayerLoginQRLabel: TQRLabel;
EasyGamesPlayedQRLabel: TQRLabel;
EasyAverageScoreQRLabel: TQRLabel;
EasyBestScoreQRLabel: TQRLabel;
GamesPlayedQRLabel1: TQRLabel;
AverageScoreQRLabel1: TQRLabel;
BestScoreQRLabel1: TQRLabel;
EasyQRLabel: TQRLabel;
NormalQRLabel: TQRLabel;
HardQRLabel: TQRLabel;
QRShape1: TQRShape;
QRShape2: TQRShape;
QRShape3: TQRShape;
BestScoreQRLabel3: TQRLabel;
AverageScoreQRLabel3: TQRLabel;
GamesPlayedQRLabel3: TQRLabel;
HardGamesPlayedQRLabel: TQRLabel;
HardAverageScoreQRLabel: TQRLabel;
HardBestScoreQRLabel: TQRLabel;
NormalBestScoreQRLabel: TQRLabel;
GamesPlayedQRLabel2: TQRLabel;
AverageScoreQRLabel2: TQRLabel;
BestScoreQRLabel2: TQRLabel;
NormalAverageScoreQRLabel: TQRLabel;
NormalGamesPlayedQRLabel: TQRLabel;
private
{ Private declarations }
public
{ Public declarations }
end;
var
PlayerReportForm: TPlayerReportForm;
implementation
{$R *.dfm}
end.
|
//Un supermercado otorga puntos para canjear por premios, por las compras que realiza en tres rubros.
//Otorga 1 punto cada $3 en alimentos,$2 en limpieza y $5 en otros.
//Ingresar los tres importes e informar los puntos obtenidos. (si en algún rubro no realizó compras, dicho importe es cero)
Program canjes;
Var
rubro:char;
puntos,compra:real;
Begin
writeln('ingrese el valor de su compra :');readln(compra);
writeln('Ingrese el rubro que desea canjear : 1- alimentos / 2- limpieza / 3- otros');readln(rubro);
If (rubro = '1') then
puntos:= compra / 3
Else if (rubro = '2') then
puntos:= compra / 2
Else if (rubro = '3') then
puntos:= compra / 5;
writeln('Los puntos obtenidos son :',puntos:2:0);
end.
|
{
Copyright (c) 2016, Vencejo Software
Distributed under the terms of the Modified BSD License
The full license is distributed with this software
}
unit ooConfigSectionMock_test;
interface
uses
SysUtils, Forms,
ooConfig.Intf, ooINIConfig,
ooConfigSectionMock,
{$IFDEF FPC}
fpcunit, testregistry
{$ELSE}
Windows,
TestFramework
{$ENDIF};
type
TConfigSectionMockTest = class(TTestCase)
private
function IniFileName: String;
function SerializeSection(const Section: IConfigSection): Boolean;
function CreateSection: IConfigSection;
published
procedure SerializeConfig;
procedure DeserializeConfig;
end;
implementation
function TConfigSectionMockTest.IniFileName: String;
begin
Result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
Result := Result + 'Config.ini';
end;
function TConfigSectionMockTest.CreateSection: IConfigSection;
begin
Result := TConfigSectionMock.New;
with TConfigSectionMock(Result) do
begin
ValueInteger := 99987;
ValueString := 'Test mock string.';
ValueBoolean := True;
ValueFloat := 123.456;
ValueDateTime := Date;
end;
end;
function TConfigSectionMockTest.SerializeSection(const Section: IConfigSection): Boolean;
begin
Result := TINIConfig.New(IniFileName).SaveSection(Section);
end;
procedure TConfigSectionMockTest.SerializeConfig;
begin
if FileExists(IniFileName) then
SysUtils.DeleteFile(IniFileName);
CheckTrue(SerializeSection(CreateSection));
CheckTrue(FileExists(IniFileName));
end;
procedure TConfigSectionMockTest.DeserializeConfig;
var
Section: IConfigSection;
begin
if not FileExists(IniFileName) then
SerializeSection(CreateSection);
Section := TConfigSectionMock.New;
TINIConfig.New(IniFileName).LoadSection(Section);
CheckEquals(99987, TConfigSectionMock(Section).ValueInteger);
CheckEquals('Test mock string.', TConfigSectionMock(Section).ValueString);
CheckTrue(TConfigSectionMock(Section).ValueBoolean);
CheckEquals(123.456, TConfigSectionMock(Section).ValueFloat);
CheckEquals(Date, TConfigSectionMock(Section).ValueDateTime);
end;
initialization
RegisterTest(TConfigSectionMockTest {$IFNDEF FPC}.Suite {$ENDIF});
end.
|
unit uRtFileReaderBase;
interface
uses
Classes,uLKJRuntimeFile,uRtHeadInfoReader,SysUtils,uVSConst;
type
TRunTimeFileReaderBase = class
public
procedure ReadHead(FileName : string;var HeadInfo: RLKJRTFileHeadInfo);virtual;
procedure LoadFromFile(FileName : string;RuntimeFile : TLKJRuntimeFile);virtual;abstract;
procedure LoadFromFiles(FileList : TStrings;RuntimeFile : TLKJRuntimeFile);virtual;
end;
{功能:转换原始文件为格式化文件}
function FmtLkjOrgFile(orgFile: string): string;
implementation
function FmtLkjOrgFile(orgFile: string): string;
{功能:转换原始文件为格式化文件}
var
strFormatFile : string;
strPath: string;
begin
strPath := ExtractFilePath(ParamStr(0));
strFormatFile := strPath + 'format\';
if not DirectoryExists(strFormatFile) then
ForceDirectories(strFormatFile);
strFormatFile := strFormatFile + ExtractFileName(orgFile) + 'f';
NewFmtFile(strPath,orgFile,strFormatFile);
Result := strFormatFile;
end;
{ TRunTimeFileReaderBase }
procedure TRunTimeFileReaderBase.LoadFromFiles(FileList: TStrings;
RuntimeFile: TLKJRuntimeFile);
var
tempList,orderList : TStrings;
dtMin : TDateTime;
header : RLKJRTFileHeadInfo;
i,nIndex: Integer;
begin
tempList := TStringList.Create;
tempList.AddStrings(FileList);
//按文件的头信息中的运行记录生成时间排序,从小到大
orderList := TStringList.Create;
try
while tempList.Count > 0 do
begin
dtMin := 10000000;
nIndex := -1;
for i := 0 to tempList.Count - 1 do
begin
ReadHead(tempList[i],header);
if dtMin > header.DTFileHeadDt then
begin
dtMin := header.DTFileHeadDt;
nIndex := i;
end;
end;
orderList.Add(tempList[nIndex]);
tempList.Delete(nIndex);
end;
//将多个文件的运行记录组合成一个列表,并以时间最小的文件的头文件信息为
//整个结构的头文件
RuntimeFile.Clear;
for i := 0 to orderList.Count - 1 do
begin
if i = 0 then
begin
ReadHead(orderList[i],header);
end;
LoadFromFile(orderList[i], RuntimeFile);
end;
RuntimeFile.HeadInfo := header;
finally
tempList.Free;
orderList.Free;
end;
end;
procedure TRunTimeFileReaderBase.ReadHead(FileName: string;
var HeadInfo: RLKJRTFileHeadInfo);
var
OrgHeadReader: TOrgHeadReader;
begin
OrgHeadReader := TOrgHeadReader.Create;
try
OrgHeadReader.read(FileName,HeadInfo);
finally
OrgHeadReader.Free;
end;
end;
end.
|
{ *********************************************************************** }
{ }
{ GUI Hangman }
{ Version 1.0 - First release of program }
{ Last Revised: 27nd of July 2004 }
{ Copyright (c) 2004 Chris Alley }
{ }
{ *********************************************************************** }
unit UAllGamesReport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, QuickRpt, UDataModule, QRCtrls;
type
TAllGamesReportForm = class(TForm)
AllGamesQuickRep: TQuickRep;
TitleBand1: TQRBand;
DetailBand1: TQRBand;
AllGamesReportQRLabel: TQRLabel;
PlayerQRLabel: TQRLabel;
QRShape1: TQRShape;
FirstNameQRDBText: TQRDBText;
LastNameQRDBText: TQRDBText;
DateTimeQRLabel: TQRLabel;
DifficultyLevelQRLabel: TQRLabel;
ScoreQRLabel: TQRLabel;
QRShape2: TQRShape;
QRSubDetail: TQRSubDetail;
DifficultyLevelQRDBText: TQRDBText;
DateTimeQRDBText: TQRDBText;
ScoreQRDBText: TQRDBText;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
end.
|
unit uProtocol;
interface
uses
System.Classes;
type
TCommunicatorState = (csStopped, csNotConnected, csConnecting, csConnected, csStop);
TChangeCommunicatorState = procedure(AState: TCommunicatorState) of object;
TWriteLog = procedure(AMessage: ansistring) of object;
TProtocol = class(TThread)
private
FOnChangeState: TChangeCommunicatorState;
FOnWriteLog: TWriteLog;
procedure ChangeState(AValue: TCommunicatorState);
procedure DoChangeState;
procedure DoWriteLog;
protected
FBuf: Ansistring;
FCommunicatorState: TCommunicatorState;
FLogMessage: ansistring;
function Deserialize(Data: AnsiString): AnsiString; virtual; abstract;
procedure Execute; override; abstract;
procedure WriteLog(AMessage: ansistring);
public
constructor Create; virtual;
property CommunicatorState: TCommunicatorState read FCommunicatorState write ChangeState;
property OnChangeState: TChangeCommunicatorState read FOnChangeState;
property OnWriteLog: TWriteLog read FOnWriteLog write FOnWriteLog;
end;
function BinToHex(aStr: AnsiString): AnsiString;
implementation
uses
uMain;
function BinToHex(aStr: AnsiString): AnsiString;
const
aHexChars: AnsiString = '0123456789ABCDEF';
var
i: integer;
begin
Result := '';
for I := 1 to Length(aStr) do
Result := Result + aHexChars[1 + (Byte(aStr[i]) div 16)] + aHexChars[1 + (Byte(aStr[i]) mod 16)] + ' ';
end;
{ TCommunication }
procedure TProtocol.ChangeState(AValue: TCommunicatorState);
begin
FCommunicatorState := AValue;
DoChangeState;
end;
constructor TProtocol.Create;
begin
inherited Create(true);
Priority := tpNormal;
FreeOnTerminate := true;
FCommunicatorState := csNotConnected;
end;
procedure TProtocol.DoChangeState;
begin
if Assigned(FOnChangeState) then
FOnChangeState(FCommunicatorState);
end;
procedure TProtocol.DoWriteLog;
begin
if Assigned(FOnWriteLog) then
FOnWriteLog(FLogMessage);
end;
procedure TProtocol.WriteLog(AMessage: ansistring);
var
s: ansistring;
begin
s := AMessage;
s := copy(s, 1, pos(' ', s)) + BinToHex(copy(s, pos(' ', s) + 1, length(s)));
FLogMessage := s;
DoWriteLog;
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmFileDrop
Purpose : Allows for files to be dropped from the Shell on target WinControl
Date : 08-02-1997
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmFileDrop;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, Classes, Controls, rmGlobalComponentHook;
type
TrmFileDrop = class(TComponent)
private
{ Private declarations }
fXPoint: integer;
fYPoint: integer;
fFileList: tstringlist;
fOnFileDrop: TNotifyEvent;
fDropLocation: TWinControl;
fActive: boolean;
fNeedReactivate: TNotifyEvent;
procedure Activate;
procedure Deactivate;
procedure GetFileList(fhnd: integer);
procedure SetDropLocation(location: TWinControl);
protected
{ Protected declarations }
OldWndProc: TFarProc;
NewWndProc: Pointer;
procedure HookWin;
procedure UnhookWin;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function DropLocationHandle:THandle;
public
{ Public declarations }
procedure HookWndProc(var AMsg: TMessage);
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ResetFileList;
procedure Reparented;
property Active : boolean read fActive default false;
property FileList: tstringlist read ffilelist;
property X: integer read fxpoint default -1;
property Y: integer read fypoint default -1;
published
{ Published declarations }
property DropLocation: TWinControl read fDropLocation write SetDropLocation;
property OnFileDroped: TNotifyEvent read fOnFileDrop write fOnFileDrop;
property OnReactivateNeeded: TNotifyEvent read fNeedReactivate write fNeedReactivate;
end;
implementation
uses SysUtils, Forms, ShellAPI;
procedure TrmFileDrop.activate;
begin
if (csDesigning in componentstate) then exit;
if fDropLocation = nil then exit;
if factive = true then exit;
if DropLocationHandle = 0 then exit;
DragAcceptFiles(DropLocationHandle, true);
Hookwin;
factive := true;
end;
procedure TrmFileDrop.deactivate;
begin
if (csDesigning in componentstate) then exit;
if fDropLocation = nil then exit;
if factive = false then exit;
if DropLocationHandle = 0 then exit;
DragAcceptFiles(DropLocationHandle, false);
unhookwin;
factive := false;
end;
procedure TrmFileDrop.getfilelist(fhnd: integer);
var
fname: pchar;
fnsize, fcount, index: integer;
fdroppoint: tpoint;
begin
ffilelist.Clear;
DragQueryPoint(fhnd, fdroppoint);
fxpoint := fdroppoint.x;
fypoint := fdroppoint.y;
fcount := dragqueryfile(fhnd, $FFFFFFFF, nil, 0);
index := 0;
while index < fcount do
begin
fnsize := DragQueryFile(fhnd, index, nil, 0);
fname := stralloc(fnsize + 1);
DragQueryFile(fhnd, index, fname, fnsize + 1);
ffilelist.Add(strpas(fname));
strdispose(fname);
inc(index);
end;
dragfinish(fhnd);
end;
procedure TrmFileDrop.SetDropLocation(location: TWinControl);
begin
if location <> fdroplocation then
begin
fdroplocation := location;
deactivate;
activate;
end;
end;
procedure TrmFileDrop.HookWin;
begin
if csDesigning in componentstate then exit;
if not assigned(NewWndProc) then
begin
OldWndProc := TFarProc(GetWindowLong(DroplocationHandle, GWL_WNDPROC));
{$ifdef D6_or_higher}
NewWndProc := Classes.MakeObjectInstance(HookWndProc);
{$else}
NewWndProc := MakeObjectInstance(HookWndProc);
{$endif}
SetWindowLong(DroplocationHandle, GWL_WNDPROC, LongInt(NewWndProc));
PushOldProc(fDroplocation, OldWndProc);
end;
end; { HookWin }
procedure TrmFileDrop.UnhookWin;
begin
if csDesigning in componentstate then exit;
if assigned(NewWndProc) then
begin
SetWindowLong(DroplocationHandle, GWL_WNDPROC, LongInt(PopOldProc(fDroplocation)));
if assigned(NewWndProc) then
{$ifdef D6_or_higher}
Classes.FreeObjectInstance(NewWndProc);
{$else}
FreeObjectInstance(NewWndProc);
{$endif}
NewWndProc := nil;
end;
end; { UnHookWin }
procedure TrmFileDrop.loaded;
begin
inherited loaded;
activate;
end;
procedure TrmFileDrop.HookWndProc(var AMsg: TMessage);
begin
if (AMsg.msg = WM_Destroy) then
begin
Deactivate;
SendMessage(DropLocationHandle, AMsg.msg, AMsg.WParam, AMsg.LParam);
AMsg.Result := 1;
exit;
end;
if (AMsg.Msg = WM_DROPFILES) then
begin
if assigned(fonfiledrop) then
begin
getfilelist(AMsg.wparam);
fonfiledrop(self);
end;
AMsg.Result := 0;
end
else
AMsg.Result := CallWindowProc(OldWndProc, DropLocationHandle, AMsg.Msg, AMsg.wParam, AMsg.lParam);
end; { HookWndProc }
constructor TrmFileDrop.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ffilelist := tstringlist.create;
factive := false;
fdroplocation := nil;
end;
destructor TrmFileDrop.Destroy;
begin
ffilelist.free;
deactivate;
inherited destroy; {Call default processing.}
end;
procedure TrmFileDrop.ResetFileList;
begin
fFileList.Clear;
fxPoint := -1;
fyPoint := -1;
end;
procedure TrmFileDrop.Reparented;
begin
Deactivate;
Activate;
end;
procedure TrmFileDrop.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if aComponent = fDropLocation then
begin
if operation = opRemove then
begin
fDropLocation := nil;
if not (csDestroying in ComponentState) and assigned(fNeedReactivate) then
fNeedReactivate(self);
end;
end;
end;
function TrmFileDrop.DropLocationHandle: THandle;
begin
if assigned(FDropLocation) then
begin
if fDropLocation <> owner then
result := fDroplocation.handle
else
begin
if (fDropLocation is TForm) and (TForm(fDropLocation).FormStyle = fsMDIForm) then
begin
if TForm(fDroplocation).Clienthandle > 0 then
result := TForm(fDroplocation).Clienthandle
else
result := THandle(0);
end
else
result := fDroplocation.handle;
end;
end
else
result := THandle(0);
end;
end.
|
unit uMenuItem;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
PAIDETODOS, Db, DBTables, Grids, LblEffct, ExtCtrls, StdCtrls, ResizePanel,
DBCtrls, MemoStr, Buttons, Mask, ADODB, siComp, siLangRT, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGrid;
type
TFrmMenuItem = class(TFrmParent)
quMenuItem: TADOQuery;
quMenuItemParentMenu: TStringField;
quMenuItemName: TStringField;
quMenuItemCmdLine: TStringField;
dsMenuItem: TDataSource;
DbMemoStr1: TDbMemoStr;
ResizePanel1: TResizePanel;
quMenuItemTip: TStringField;
quMenuItemVisible: TBooleanField;
spHelp: TSpeedButton;
quMenuItemEnabled: TBooleanField;
quMenuItemIDMenu: TIntegerField;
quMenuItemIDSubMenu: TIntegerField;
quMenuItemIDMenuName: TStringField;
quMenuItemShortcut: TIntegerField;
quMenuItemImageIndex: TIntegerField;
grdMenuItem: TcxGrid;
grdMenuItemDB: TcxGridDBTableView;
grdMenuItemLevel: TcxGridLevel;
grdMenuItemDBParentMenu: TcxGridDBColumn;
grdMenuItemDBEnabled: TcxGridDBColumn;
grdMenuItemDBName: TcxGridDBColumn;
grdMenuItemDBCmdLine: TcxGridDBColumn;
grdMenuItemDBVisible: TcxGridDBColumn;
grdMenuItemDBIDMenuName: TcxGridDBColumn;
grdMenuItemDBShortcut: TcxGridDBColumn;
grdMenuItemDBImageIndex: TcxGridDBColumn;
procedure btCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure spHelpClick(Sender: TObject);
procedure quMenuItemCalcFields(DataSet: TDataSet);
procedure quMenuItemBeforeOpen(DataSet: TDataSet);
private
{ Private declarations }
//MenuItem
procedure MenuItemClose;
procedure MenuItemOpen;
procedure MenuItemPost;
public
{ Public declarations }
end;
implementation
{$R *.DFM}
uses uDM, uMsgBox, uMsgConstant, uDMGlobal, imglist;
procedure TFrmMenuItem.MenuItemClose;
begin
MenuItemPost;
with quMenuItem do
if Active then
Close;
end;
procedure TFrmMenuItem.MenuItemOpen;
begin
with quMenuItem do
if not Active then
Open;
end;
procedure TFrmMenuItem.MenuItemPost;
begin
with quMenuItem do
if Active then
if State in dsEditModes then
begin
Post;
MsgBox(MSG_INF_CHANGES_SYS, vbOkOnly + vbInformation);
end;
end;
procedure TFrmMenuItem.btCloseClick(Sender: TObject);
begin
inherited;
MenuItemClose;
Close;
end;
procedure TFrmMenuItem.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
DM.imgSubMenu.DrawingStyle := dsNormal;
Action := caFree;
end;
procedure TFrmMenuItem.FormShow(Sender: TObject);
begin
inherited;
MenuItemOpen;
DM.imgSubMenu.DrawingStyle := dsTransparent;
end;
procedure TFrmMenuItem.spHelpClick(Sender: TObject);
begin
inherited;
Application.HelpContext(2060);
end;
procedure TFrmMenuItem.quMenuItemCalcFields(DataSet: TDataSet);
begin
inherited;
quMenuItemIDMenuName.AsString := quMenuItemIDMenu.AsString + ' - ' +
quMenuItemParentMenu.AsString;
end;
procedure TFrmMenuItem.quMenuItemBeforeOpen(DataSet: TDataSet);
begin
inherited;
quMenuItem.Parameters.ParamByName('IDLanguage').Value := DMGlobal.IDLanguage;
end;
end.
|
unit Dicionario;
{
Dicionario by Master_Zion
}
interface
uses SysUtils;
function AbreDicionario(Arquivo:String):String;
function FechaDicionario:String;
function LocalizarProxima(var Proxima:String):String;
function LocalizarPalavra(const Palavra:String):String;
const mzOK :String='ok';
var
fArquivo : TextFile;
implementation
function IniciaArquivo:String;
begin
result := 'Erro desconhecido';
try
Reset(fArquivo);
result := mzOK;
except
on E : Exception do Result:= 'ERRO!!! '+E.Message;
end;
end;
function AbreDicionario(Arquivo:String):String;
begin
if FileExists(Arquivo) then begin
AssignFile(fArquivo, Arquivo);
Result := IniciaArquivo;
end
else
result := 'Arquivo não encontrado!!!';
end;
function FechaDicionario:String;
begin
result := 'Erro desconhecido';
try
Close(fArquivo);
result := mzOK;
except
on E : Exception do Result:= 'ERRO!!! '+E.Message;
end;
end;
function LocalizarProxima(var Proxima:String):String;
begin
if Eof(fArquivo) then begin
Proxima := '';
result := 'EOF';
exit;
end;
Readln(fArquivo, Proxima);
Result := mzOK;
end;
function LocalizarPalavra(const Palavra:String):String;
var
s, Linha : String;
begin
s := IniciaArquivo;
if (s <> mzOK) then begin
Result := s;
exit;
end;
while (Linha <> Palavra) do begin
if Eof(fArquivo) then begin
result := 'EOF';
exit;
end;
Readln(fArquivo, Linha);
end;
end;
end.
|
unit uCiaComport;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{ Author: Mestdagh Wilfried
Web: http://www.mestdagh.biz
eMail: wilfried@mestdagh.biz
If you try this component then please drop me a email with your comments. Any
comment is welcome, also negative. Please goto my web to download the latest
version.
Properties
Port
Commnumber of the port (starts at 1)
Baudrate
You have to fill in a valid baudreate
ByteSize
Default 8 bit. Note that there can be illegal combinations between
StopBits and ByteSize.
Parity
TParity enumerated value
StopBits
TStopbits enumerated value. Note that there can be illegal combinations
between StopBits and ByteSize.
FlowCtrl
Set all possible flow controls. Note that there can be illegal
combinations. See DCB in windows API help for more information.
RxBuffer
TxBuffer
Size of both rx and tx queue used by windows
LineMode
If set then the component will fire OnDataAvailable only when the
LineEnd characters are received
LineEnd
string to indicate the end of line.
Open
Open or close the port
RxCount
Available characters in buffer, only valid if called from within
OnDataAvailable
Events
OnDataAvailable
Fired when characters are received by the component
OnDataSent
Fired when the tx queue is emply. If you have to send a large amount
of data then this is the place to send next chunck
Methods
procedure PurgeRx;
Purge Rx buffer
procedure PurgeTx;
Purge Tx buffer and stops transmitting immediatly
function Send(Buffer: Pointer; Len: integer): cardinal;
Put Buffer in the txqueue, returns char's writed
procedure SendStr(const Tx: string);
Call's Send. Use this one if you realy wants to use strings
function Receive(Buffer: Pointer; Len: integer): cardinal;
Only to be called in OnDataAvailable. You have to read all available
characters (call RxCount to know how much there is in buffer).
function ReceiveStr: string;
Call's Receive. Use this if you really wants to use strings
function GetFreeOutBuf: integer;
Returns free space in Tx buffer.
procedure GetAvailablePorts(PortList: TStrings);
Returns all available ports on the machine
CommFunction(Value: DWord);
Possible values are:
CLRDTR Clears the DTR (data-terminal-ready) signal.
CLRRTS Clears the RTS (request-to-send) signal.
SETDTR Sends the DTR (data-terminal-ready) signal.
SETRTS Sends the RTS (request-to-send) signal.
SETXOFF Causes transmission to act as if XOFF has been received.
SETXON Causes transmission to act as if XON has been received.
SETBREAK Suspends transmission and places the line in a break state.
CLRBREAK Restores transmission and places the line in a nonbreak.
Note that some combinations are illegal. For example toggle the
hardware lines when hardware handshaking is set.
Version information:
1.00 18 Nov 2001
- First version (only tested on W2K, service pack 2)
1.01 20 Nov 2001
- Propery editor for LineEnd
1.02 24 Nov 2001
- Added logic in Receive in case someone does not want to receive
all available bytes.
- If OnDataAvailable has no handler then we receive and trow away.
- LineMode and LineEnd
1.03 3 Mar 2002
- Added GetFreeOutBuf wich returns free space in output buffer
- Made changing port settings possible when port is already open
- Added software and hardware handshaking
1.04 4 Mar 2002
- Corrected wrong calculation from XonLimit and XoffLimit
- Added TxContinueXoff property in FlowCtrl.
1.05 16 Mar 2002
- Added GetAvailablePorts(PortList: TStrings), suggested by Wilson Lima
[wsl@dglnet.com.br]
- Added property ByteSize
- Added CommFunction(Value: DWord).
- Added PurgeRx to clear the Rx buffer and PurgeTx wich clears the Tx
buffers and stop transmitting immediatly.
- Corrected closing when there is still data in buffer (could be if
LineMode is set) then OnDataAvailable will fire before closing.
- Corrected if setting LineMode to False and there is still data in
buffer then OnDataAvailable will fire immediatly.
1.06 24 Apr 2002
- Ported to Delphi 6 by moving the property editor to a separate file
uCiaComportE.pas and adding conditional compilation. See notes in
uCiaComportE.pas on what to do for Delphi6.
1.07 15 May 2002
- There was a bug when closing the port in Delphi 6. Serge Wagener
[serge@wagener-consulting.lu] found offending line. Ivan Turcan
[iturcan@drake.sk] proposed a bug fix for it. Problem was because
the thread was created with FreeOnTerminate to True and with Delphi 6
the thread seems to be destroyed while the WaitFor was still looping.
1.08 1 Jul 2002
- Added global function CiaEnumPorts.
- Corrected spelling error in property Version (it was Verstion) found.
Thanks to Dirk Claesen [dirk.claesen@pandora.be]. Note that you will
have a 'property not found' error for this one, but just ignore it.
- Bug fix in LineEnd when the byte before the first byte in LineEnd was
exacly that same byte (eg: #13#13#10 and LineEnd #13#10). In that
case OnDataAvailable was not fired. Fixed with a windowing function.
Todo
- Making partial receive possible when LineMode is set to True.
- Implementing port events CTS, DSR, RLSD, RING, BREAK, ERR
- Adding more exception handling
- Make it thread safe, creating a hidden window and use SendMessage to it
instead of using the Synchronize method
- Check DCB on illegal values, eg: XonOff together with Hardware
handshaking
}
interface
uses
Windows, Classes, SysUtils;
const
CIA_COMMVERSION = '1.08';
type
TCiaComPort = class;
TStopBits = (sbOne, sbOne_5, sbTwo);
TParity = (ptNone, ptOdd, ptEven, ptMark, ptSpace);
ECiaComPort = class(Exception);
TCiaCommBuffer = class
private
FRcvd: PChar; // pointer to buffer
FRcvdSize: cardinal; // size of buffer
FReadPtr: integer;
FWritePtr: integer;
FLineEndPtr: Integer;
public
destructor Destroy; override;
procedure Grow(Len: cardinal);
end;
TCiaCommThread = class(TThread)
private
FCiaComPort: TCiaComPort;
FEventMask: cardinal;
FRxCount: cardinal;
FRcvBuffer: TCiaCommBuffer; // if LineMode then we receive in our own buffer
procedure PortEvent;
procedure InternalReceive;
function CheckLineEnd(P: Pchar): boolean;
public
ComHandle: THandle;
CloseEvent: THandle;
procedure Execute; override;
end;
TDtrControl = (dtrDisable, dtrEnable, dtrHandshake);
TRtsControl = (rtsDisable, rtsEnable, rtsHandshake, rtsToggle);
TFlowCtrl = class(TPersistent)
private
FFlags: LongInt;
FComPort: TCiaComPort;
FRxDtrControl: TDtrControl;
FRxRtsControl: TRtsControl;
FRxDsrSensivity: boolean;
FTxContinueXoff: boolean;
FTxCtsFlow: boolean;
FTxDsrFlow: boolean;
FXonOff: boolean;
public
constructor Create(Port: TCiaComPort);
procedure SetRxDtrControl(Value: TDtrControl);
procedure SetRxRtsControl(Value: TRtsControl);
procedure SetRxDsrSensivity(Value: boolean);
procedure SetTxContinueXoff(Value: boolean);
procedure SetTxCtsFlow(Value: boolean);
procedure SetTxDsrFlow(Value: boolean);
procedure SetXonOff(Value: boolean);
procedure ChangeCommState;
published
property RxDsrSensivity: boolean read FRxDsrSensivity write SetRxDsrSensivity;
property RxDtrControl: TDtrControl read FRxDtrControl write SetRxDtrControl;
property RxRtsControl: TRtsControl read FRxRtsControl write SetRxRtsControl;
property TxContinueXoff: boolean read FTxContinueXoff write SetTxContinueXoff;
property TxCtsFlow: boolean read FTxCtsFlow write SetTxCtsFlow;
property TxDsrFlow: boolean read FTxDsrFlow write SetTxDsrFlow;
property XonXoff: boolean read FXonOff write SetXOnOff;
end;
TCiaComPort = class(TComponent)
private
FFlowCtrl: TFlowCtrl;
FLineMode: boolean;
FLineEnd: string;
FBaudrate: integer;
FByteSize: byte;
FStopbits: TStopBits;
FParity: TParity;
FVersion: string;
FOpen: boolean;
FPort: integer;
FRxBuffer: cardinal;
FXOffLimit: dword;
FXOnLimit: dword;
FTxBuffer: cardinal;
FCommThread: TCiaCommThread;
FOnDataAvailable: TNotifyEvent;
FOnDataSent: TNotifyEvent;
function GetRxCount: cardinal;
procedure OpenPort;
procedure ClosePort;
procedure SetOpen(Value: boolean);
procedure SetVersion(Value: string);
procedure SetBaudRate(Value: integer);
procedure SetParity(Value: TParity);
procedure SetStopBits(Value: TStopBits);
procedure SetRxBuffer(Value: cardinal);
procedure SetLineMode(Value: boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CommFunction(Value: dword);
procedure GetAvailablePorts(PortList: TStrings);
function GetFreeOutBuf: integer;
procedure PurgeRx;
procedure PurgeTx;
function Send(Buffer: Pointer; Len: integer): cardinal;
procedure SendStr(const Tx: string);
function Receive(Buffer: Pointer; Len: integer): cardinal;
function ReceiveStr: string;
property Open: boolean read FOpen write SetOpen;
property RxCount: cardinal read GetRxCount;
published
property Baudrate: integer read FBaudrate write SetBaudrate;
property ByteSize: byte read FByteSize write FByteSize;
property FlowCtrl: TFlowCtrl read FFlowCtrl write FFlowCtrl;
property LineEnd: string read FLineEnd write FLineEnd;
property LineMode: boolean read FLineMode write SetLineMode;
property Parity: TParity read FParity write SetParity;
property Port: integer read FPort write FPort;
property RxBuffer: cardinal read FRxBuffer write SetRxBuffer;
property StopBits: TStopBits read FStopBits write SetStopBits;
property TxBuffer: cardinal read FTxBuffer write FTxBuffer;
property Version: string read FVersion write SetVersion;
property OnDataAvailable: TNotifyEvent read FOnDataAvailable write FOnDataAvailable;
property OnDataSent: TNotifyEvent read FOnDataSent write FOnDataSent;
end;
procedure CiaEnumPorts(PortList: TStrings);
implementation
//------------------------------------------------------------------------------
//---- TCiaCommBuffer ----------------------------------------------------------
//------------------------------------------------------------------------------
destructor TCiaCommBuffer.Destroy;
begin
if Assigned(FRcvd) then
FreeMem(FRcvd);
inherited;
end;
//------------------------------------------------------------------------------
procedure TCiaCommBuffer.Grow(Len: cardinal);
begin
ReallocMem(FRcvd, FRcvdSize + Len);
inc(FRcvdSize, Len);
end;
//------------------------------------------------------------------------------
//---- TFlowCtrl ---------------------------------------------------------------
//------------------------------------------------------------------------------
constructor TFlowCtrl.Create(Port: TCiaComPort);
begin
inherited Create;
FComPort := Port;
FRxDtrControl := dtrEnable;
FRxRtsControl := rtsEnable;
FFlags := 1 or // binary mode
$10 or // dtrEnable
$1000; // rtsEnable
end;
//------------------------------------------------------------------------------
procedure TFlowCtrl.SetRxDsrSensivity(Value: boolean);
begin
if Value = FRxDsrSensivity then
Exit;
FRxDsrSensivity := Value;
if Value then
FFlags := FFlags or $40
else
FFlags := FFlags and $FFFFFFBF;
ChangeCommState;
end;
//------------------------------------------------------------------------------
procedure TFlowCtrl.SetRxDtrControl(Value: TDtrControl);
begin
if Value = FRxDtrControl then
Exit;
FRxDtrControl := Value;
FFlags := FFlags and $FFFFFFCF; // reset fDTRControl bits
case Value of
dtrDisable:
;
dtrEnable:
FFlags := FFlags or $10;
dtrHandshake:
FFlags := FFlags or $20;
end;
ChangeCommState;
end;
//------------------------------------------------------------------------------
procedure TFlowCtrl.SetRxRtsControl(Value: TRtsControl);
begin
if Value = FRxRtsControl then
Exit;
FRxRtsControl := Value;
FFlags := FFlags and $FFFFCFFF; // reset fRTSControl bits
case Value of
rtsDisable:
;
rtsEnable:
FFlags := FFlags or $1000;
rtsHandshake:
FFlags := FFlags or $2000;
rtsToggle:
FFlags := FFlags or $3000;
end;
ChangeCommState;
end;
//------------------------------------------------------------------------------
procedure TFlowCtrl.SetTxContinueXoff(Value: boolean);
begin
if Value = FTxContinueXoff then
Exit;
FTxContinueXoff := Value;
if Value then
FFlags := FFlags or $80
else
FFlags := FFlags and $FFFFFF7F;
ChangeCommState;
end;
//------------------------------------------------------------------------------
procedure TFlowCtrl.SetTxCtsFlow(Value: boolean);
begin
if Value = FTxCtsFlow then
Exit;
FTxCtsFlow := Value;
if Value then
FFlags := FFlags or $4
else
FFlags := FFlags and $FFFFFFFB;
ChangeCommState;
end;
//------------------------------------------------------------------------------
procedure TFlowCtrl.SetTxDsrFlow(Value: boolean);
begin
if Value = FTxDsrFlow then
Exit;
FTxDsrFlow := Value;
if Value then
FFlags := FFlags or $8
else
FFlags := FFlags and $FFFFFFF7;
ChangeCommState;
end;
//------------------------------------------------------------------------------
procedure TFlowCtrl.SetXonOff(Value: boolean);
begin
if Value = FXonOff then
Exit;
FXonOff := Value;
if Value then
FFlags := FFlags or $300
else
FFlags := FFlags and $FFFFFCFF;
ChangeCommState;
end;
//------------------------------------------------------------------------------
procedure TFlowCtrl.ChangeCommState;
var
DCB: TDCB;
begin
if not FComport.Open then
Exit;
GetCommState(FComPort.FCommThread.ComHandle, DCB);
DCB.Flags := FFlags;
SetCommState(FComPort.FCommThread.ComHandle, DCB);
end;
//------------------------------------------------------------------------------
//---- TCiaComPort -------------------------------------------------------------
//------------------------------------------------------------------------------
constructor TCiaComPort.Create(AOwner: TComponent);
begin
inherited;
FFlowCtrl := TFlowCtrl.Create(Self);
FVersion := CIA_COMMVERSION;
FLineEnd := #13#10;
FRxBuffer := 8192;
FTxBuffer := 8192;
FXOffLimit := FRxBuffer div 2;
FXOnLimit := FRxBuffer div 4 * 3;
FBaudrate := 9600;
FByteSize := 8;
FStopBits := sbOne;
FParity := ptNone;
end;
//------------------------------------------------------------------------------
destructor TCiaComPort.Destroy;
begin
if FOpen then
ClosePort;
if Assigned(FFlowCtrl) then
FFlowCtrl.Destroy;
inherited;
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.SetVersion(Value: string);
begin
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.SetRxBuffer(Value: cardinal);
var
DCB: TDCB;
begin
if Value = FRxBuffer then
Exit;
FRxBuffer := Value;
FXOffLimit := Value div 4 * 3;
FXOnLimit := Value div 2;
if (csDesigning in ComponentState) or not Open then
Exit;
GetCommState(FCommThread.ComHandle, DCB);
DCB.XoffLim := FXOffLimit;
DCB.XonLim := FXOnLimit;
SetCommState(FCommThread.ComHandle, DCB);
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.SetBaudRate(Value: integer);
var
DCB: TDCB;
begin
if Value = FBaudRate then
Exit;
FBaudRate := Value;
if (csDesigning in ComponentState) or not Open then
Exit;
GetCommState(FCommThread.ComHandle, DCB);
DCB.BaudRate := Value;
SetCommState(FCommThread.ComHandle, DCB);
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.SetParity(Value: TParity);
var
DCB: TDCB;
begin
if Value = FParity then
Exit;
FParity := Value;
if (csDesigning in ComponentState) or not Open then
Exit;
GetCommState(FCommThread.ComHandle, DCB);
DCB.Parity := Ord(Value);
SetCommState(FCommThread.ComHandle, DCB);
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.SetStopBits(Value: TStopBits);
var
DCB: TDCB;
begin
if Value = FStopBits then
Exit;
FStopBits := Value;
if (csDesigning in ComponentState) or not Open then
Exit;
GetCommState(FCommThread.ComHandle, DCB);
DCB.StopBits := Ord(Value);
SetCommState(FCommThread.ComHandle, DCB);
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.SetLineMode(Value: boolean);
begin
if Value = FLineMode then
Exit;
FLineMode := Value;
if not FLineMode and (FCommThread.FRxCount > 0) then
FOnDataAvailable(Self);
end;
//------------------------------------------------------------------------------
procedure CiaEnumPorts(PortList: TStrings);
var
n, MaxPorts: integer;
Port: THandle;
PortName: string;
begin
if Win32PlatForm = VER_PLATFORM_WIN32_NT then
MaxPorts := 256
else { if VER_PLATFORM_WIN32_WINDOWS }
MaxPorts := 9;
for n := 1 to MaxPorts do
begin
PortName := '\\.\COM' + IntToStr(n);
Port := CreateFile(PChar(PortName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, 0, 0);
if (Port <> INVALID_HANDLE_VALUE) or (GetLastError = ERROR_ACCESS_DENIED) then
PortList.Add(IntToStr(n));
CloseHandle(Port);
end;
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.GetAvailablePorts(PortList: TStrings);
begin
CiaEnumPorts(PortList);
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.CommFunction(Value: dword);
begin
EscapeCommFunction(FCommThread.ComHandle, Value);
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.OpenPort;
var
P: string;
hPort: THandle;
DCB: TDCB;
begin
P := '\\.\COM' + IntToStr(FPort);
hPort := CreateFile(PChar(P), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if hPort = INVALID_HANDLE_VALUE then
raise ECiaComPort.Create('Cannot open port ' + '''' + P + '''');
GetCommState(hPort, DCB);
with DCB do begin
Baudrate := FBaudrate;
XoffLim := FXOffLimit;
XonLim := FXOnLimit;
ByteSize := FByteSize;
Parity := Ord(FParity);
StopBits := Ord(FStopBits);
Flags := FFlowCtrl.FFlags;
end;
SetupComm(hPort, FRxBuffer, FTxBuffer);
SetCommState(hPort, DCB);
SetCommMask(hPort, EV_RXCHAR or EV_TXEMPTY);
FCommThread := TCiaCommThread.Create(True);
with FCommThread do begin
FCiaComPort := Self;
ComHandle := hPort;
//FreeOnTerminate := True;
FRcvBuffer := TCiaCommBuffer.Create;
Resume;
end;
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.ClosePort;
begin
if LineMode and (FCommThread.FRxCount > 0) then
FOnDataAvailable(Self);
with FCommThread do begin
SetEvent(CloseEvent);
FRcvBuffer.Destroy;
WaitFor;
//WaitForSingleObject(Handle, Infinite);
Free;
end;
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.SetOpen(Value: boolean);
begin
if Value = FOpen then
Exit;
if Value then
OpenPort
else
ClosePort;
FOpen := Value;
end;
//------------------------------------------------------------------------------
function TCiaComPort.GetFreeOutBuf: integer;
var
ComStat: TComStat;
ErrorMask: cardinal;
begin
ClearCommError(FCommThread.ComHandle, ErrorMask, @ComStat);
Result := TxBuffer - ComStat.cbOutQue;
end;
//------------------------------------------------------------------------------
function TCiaComPort.Receive(Buffer: Pointer; Len: integer): cardinal;
var
OverLapped: TOverLapped;
Buf: TCiaCommBuffer;
begin
if Len <= 0 then
begin
Result := 0;
Exit;
end;
if cardinal(Len) > FCommThread.FRxCount then
Len := FCommThread.FRxCount;
if FLineMode then begin
Buf := FCommThread.FRcvBuffer;
Move(Buf.FRcvd[Buf.FReadPtr], Buffer^, Len);
Inc(Buf.FReadPtr, Len);
if Buf.FReadPtr >= Buf.FWritePtr then begin
Buf.FReadPtr := 0;
Buf.FWritePtr := 0;
Buf.FLineEndPtr := 0;
end;
Result := Len;
end
else begin
FillChar(OverLapped, SizeOf(OverLapped), 0);
Readfile(FCommThread.ComHandle, Buffer^, Len, Result, @OverLapped);
end;
Dec(FCommThread.FRxCount, Result);
end;
//------------------------------------------------------------------------------
function TCiaComPort.ReceiveStr: string;
begin
SetLength(Result, RxCount);
Receive(Pointer(Result), RxCount);
end;
//------------------------------------------------------------------------------
function TCiaComPort.GetRxCount: cardinal;
begin
Result := FCommThread.FRxCount;
end;
//------------------------------------------------------------------------------
function TCiaComPort.Send(Buffer: Pointer; Len: integer): cardinal;
var
OverLap: TOverlapped;
begin
if not FOpen then
raise ECiaComPort.Create('Port not open');
FillChar(OverLap, SizeOf(OverLap), 0);
WriteFile(FCommThread.ComHandle, Buffer^, Len, Result, @OverLap);
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.SendStr(const Tx: string);
begin
Send(Pointer(Tx), Length(Tx));
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.PurgeRx;
begin
PurgeComm(FCommThread.ComHandle, PURGE_RXCLEAR or PURGE_RXABORT);
end;
//------------------------------------------------------------------------------
procedure TCiaComPort.PurgeTx;
begin
PurgeComm(FCommThread.ComHandle, PURGE_TXCLEAR or PURGE_TXABORT);
end;
//------------------------------------------------------------------------------
//---- TCiaCommThread ----------------------------------------------------------
//------------------------------------------------------------------------------
procedure TCiaCommThread.Execute;
var
WaitHandles: array[0..1] of THandle;
OverLap: TOverLapped;
WaitEvent: cardinal;
begin
FillChar(OverLap, sizeof(OverLapped), 0);
CloseEvent := CreateEvent(nil, True, False, nil);
OverLap.hEvent := CreateEvent(nil, True, True, nil);
WaitHandles[0] := CloseEvent;
WaitHandles[1] := OverLap.hEvent;
while not Terminated do begin
WaitCommEvent(ComHandle, FEventMask, @OverLap);
WaitEvent := WaitForMultipleObjects(2, @WaitHandles, False, INFINITE);
case WaitEvent of
WAIT_OBJECT_0:
Terminate;
WAIT_OBJECT_0 + 1:
Synchronize(PortEvent);
end;
end;
CloseHandle(OverLap.hEvent);
CloseHandle(CloseEvent);
CloseHandle(ComHandle);
end;
//------------------------------------------------------------------------------
function TCiaCommThread.CheckLineEnd(P: Pchar): boolean;
var
n: integer;
begin
n := 1;
while (n <= Length(FCiaComPort.LineEnd)) and (P[n - 1] = FCiaComPort.LineEnd[n]) do
Inc(n);
Result := n > Length(FCiaComPort.LineEnd);
end;
//------------------------------------------------------------------------------
procedure TCiaCommThread.InternalReceive; // synchronized method
var
OverLapped: TOverLapped;
Count: Cardinal;
//j: Integer;
begin
if FRcvBuffer.FRcvdSize - cardinal(FRcvBuffer.FWritePtr) < FRxCount then
FRcvBuffer.Grow(FRxCount);
FillChar(OverLapped, SizeOf(OverLapped), 0);
Readfile(ComHandle, FRcvBuffer.FRcvd[FRcvBuffer.FWritePtr], FRxCount, Count, @OverLapped);
Inc(FRcvBuffer.FWritePtr, Count);
Dec(FRxCount, Count);
while (FRcvBuffer.FWritePtr - FRcvBuffer.FLineEndPtr) >= Length(FCiaComPort.LineEnd) do
begin
if CheckLineEnd(FRcvBuffer.FRcvd + FRcvBuffer.FLineEndPtr) then
begin
Inc(FRcvBuffer.FLineEndPtr, Length(FCiaComPort.LineEnd));
if Assigned(FCiaComPort.FOnDataAvailable) then
begin
FRxCount := FRcvBuffer.FLineEndPtr - FRcvBuffer.FReadPtr;
FCiaComPort.FOnDataAvailable(FCiaComPort);
if FRcvBuffer.FReadPtr = FRcvBuffer.FWritePtr then
Exit;
end;
end;
Inc(FRcvBuffer.FLineEndPtr);
end;
{while FRcvBuffer.FLineEndPtr < FRcvBuffer.FWritePtr do begin
j := 1;
while FRcvBuffer.FRcvd[FRcvBuffer.FLineEndPtr] = FCiaComPort.LineEnd[j] do begin
Inc(j);
Inc(FRcvBuffer.FLineEndPtr);
if (j > Length(FCiaComPort.LineEnd)) and Assigned(FCiaComPort.FOnDataAvailable) then begin
FRxCount := FRcvBuffer.FLineEndPtr - FRcvBuffer.FReadPtr;
FCiaComPort.FOnDataAvailable(FCiaComPort); // found match
if FRcvBuffer.FReadPtr = FRcvBuffer.FWritePtr then
Exit;
end;
if FRcvBuffer.FLineEndPtr >= FRcvBuffer.FWritePtr then begin
Dec(FRcvBuffer.FLineEndPtr, j - 1); // partial match, rewind to match of first char
Exit;
end;
end;
Inc(FRcvBuffer.FLineEndPtr);
end; }
end;
//------------------------------------------------------------------------------
procedure TCiaCommThread.PortEvent; // synchronized method
var
ComStat: TComStat;
ErrorMask: cardinal;
TrashCan: string[255];
begin
ClearCommError(ComHandle, ErrorMask, @ComStat);
// we have to check all the events, because more than one can happen the same time
if (FEventMask and EV_RXCHAR) > 0 then begin
FRxCount := ComStat.cbInQue;
if FRxCount > 0 then
if not Assigned(FCiaComPort.FOnDataAvailable) then // nobody wants to receive
while FRxCount > 0 do
FCiaComPort.Receive(@TrashCan[1], High(TrashCan))
else
if FCiaComPort.LineMode then
InternalReceive
else
FCiaComPort.FOnDataAvailable(FCiaComPort);
end;
if ((FEventMask and EV_TXEMPTY) > 0) and Assigned(FCiaComPort.FOnDataSent) then
FCiaComPort.FOnDataSent(FCiaComPort);
// Have to add them also in the SetCommMask
//if (FEventMask and EV_CTS) > 0 then
//if (FEventMask and EV_DSR) > 0 then
//if (FEventMask and EV_RLSD) > 0 then
//if (FEventMask and EV_RING) > 0 then
//if (FEventMask and EV_ERR) > 0 then
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
end.
|
unit ibSHData;
interface
uses
Classes, SysUtils, Forms, Controls,
SHDesignIntf, ibSHDesignIntf, ibSHDriverIntf, ibSHMessages, ibSHConsts,
ibSHValues;
type
TibBTData = class(TSHComponent, IibSHData{, IibSHStatistics})
private
FDRVReadTransaction: TSHComponent;
FDRVWriteTransaction: TSHComponent;
FDRVDataset: TSHComponent;
FStatistics: TSHComponent;
FSQLGenerator: TSHComponent;
FErrorText: string;
FReadOnly: Boolean;
procedure CreateDRV;
procedure FreeDRV;
function GetDatabase: IibSHDatabase;
function GetWriteTransaction: IibSHDRVTransaction;
function GetSQLGenerator: IibSHSQLGenerator;
function GetAutoCommit: Boolean;
function GetSQLEditor: IibSHSQLEditor;
function GetReadOnly: Boolean;
procedure SetReadOnly(const Value: Boolean);
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall;
{ IibSHData }
function GetTransaction: IibSHDRVTransaction;
function GetDataset: IibSHDRVDataset;
function GetErrorText: string;
function Prepare: Boolean;
function Open: Boolean;
procedure FetchAll;
procedure Close;
procedure Commit;
procedure Rollback;
{IibSHStatisticsCollection}
function GetStatistics: IibSHStatistics;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Database: IibSHDatabase read GetDatabase;
property ReadTransaction: IibSHDRVTransaction read GetTransaction;
property WriteTransaction: IibSHDRVTransaction read GetWriteTransaction;
property Dataset: IibSHDRVDataset read GetDataset;
property Statistics: IibSHStatistics read GetStatistics;
property SQLGenerator: IibSHSQLGenerator read GetSQLGenerator;
property SQLEditor: IibSHSQLEditor read GetSQLEditor;
property AutoCommit: Boolean read GetAutoCommit;
end;
implementation
{ TibBTData }
procedure Register;
begin
SHRegisterComponents([TibBTData]);
end;
constructor TibBTData.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
CreateDRV;
FReadOnly := False;
end;
destructor TibBTData.Destroy;
begin
FreeDRV;
inherited Destroy;
end;
procedure TibBTData.CreateDRV;
var
vComponentClass: TSHComponentClass;
begin
vComponentClass := Designer.GetComponent(IibSHSQLGenerator);
if Assigned(vComponentClass) then FSQLGenerator := vComponentClass.Create(nil);
if Assigned(Database) and Assigned(Database.BTCLServer) then
begin
vComponentClass := Designer.GetComponent(Database.BTCLServer.DRVNormalize(IibSHDRVTransaction));
if Assigned(vComponentClass) then
begin
FDRVReadTransaction := vComponentClass.Create(Self);
ReadTransaction.Params.Text := TRWriteParams;
ReadTransaction.Database := Database.DRVQuery.Database;
FDRVWriteTransaction := vComponentClass.Create(Self);
WriteTransaction.Params.Text := TRWriteParams;
WriteTransaction.Database := Database.DRVQuery.Database;
end;
vComponentClass := Designer.GetComponent(Database.BTCLServer.DRVNormalize(IibSHDRVDataset));
if Assigned(vComponentClass) then
begin
FDRVDataset := vComponentClass.Create(Self);
Dataset.Database := Database.DRVQuery.Database;
Dataset.ReadTransaction := ReadTransaction;
end;
vComponentClass := Designer.GetComponent(IibSHStatistics);
if Assigned(vComponentClass) then
begin
FStatistics := vComponentClass.Create(Self);
Statistics.Database := Database;
if Supports(Dataset, IibSHDRVExecTimeStatistics) then
Statistics.DRVTimeStatistics := Dataset as IibSHDRVExecTimeStatistics;
end;
end;
end;
procedure TibBTData.FreeDRV;
begin
if Assigned(FDRVReadTransaction) then FDRVReadTransaction.Free;
if Assigned(FDRVWriteTransaction) then FDRVWriteTransaction.Free;
if Assigned(FDRVDataset) then FDRVDataset.Free;
if Assigned(FStatistics) then FStatistics.Free;
if Assigned(FSQLGenerator) then FSQLGenerator.Free;
end;
function TibBTData.GetDatabase: IibSHDatabase;
begin
Supports(Owner, IibSHDatabase, Result);
end;
function TibBTData.GetWriteTransaction: IibSHDRVTransaction;
begin
Supports(FDRVWriteTransaction, IibSHDRVTransaction, Result);
end;
function TibBTData.GetSQLGenerator: IibSHSQLGenerator;
begin
Supports(FSQLGenerator, IibSHSQLGenerator, Result);
end;
function TibBTData.GetAutoCommit: Boolean;
begin
if Assigned(SQLEditor) then
Result := SQLEditor.AutoCommit
else
Result := False;
end;
function TibBTData.GetSQLEditor: IibSHSQLEditor;
begin
Supports(Owner, IibSHSQLEditor, Result);
end;
function TibBTData.GetReadOnly: Boolean;
begin
Result := FReadOnly;
end;
procedure TibBTData.SetReadOnly(const Value: Boolean);
begin
FReadOnly := Value;
end;
function TibBTData.GetDataset: IibSHDRVDataset;
begin
Supports(FDRVDataset, IibSHDRVDataset, Result);
end;
function TibBTData.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if IsEqualGUID(IID, IibSHStatistics) then
begin
IInterface(Obj) := Statistics;
if Pointer(Obj) <> nil then
Result := S_OK
else
Result := E_NOINTERFACE;
end
else
Result := inherited QueryInterface(IID, Obj);
end;
function TibBTData.GetTransaction: IibSHDRVTransaction;
begin
Supports(FDRVReadTransaction, IibSHDRVTransaction, Result);
end;
function TibBTData.GetErrorText: string;
begin
Result := FErrorText;
end;
function TibBTData.Prepare: Boolean;
var
I: Integer;
vSQLEditorForm: IibSHSQLEditorForm;
begin
Result := True;
FErrorText := EmptyStr;
if not Dataset.Prepare then
begin
FErrorText := Dataset.ErrorText;
Result := False;
end
else
if Supports(Owner, IibSHSQLEditor) then
for I := 0 to Pred((Owner as TSHComponent).ComponentForms.Count) do
if Supports((Owner as TSHComponent).ComponentForms[I], IibSHSQLEditorForm, vSQLEditorForm) then
begin
vSQLEditorForm.ShowPlan;
Break;
end;
end;
function TibBTData.Open: Boolean;
var
vDRVParams: IibSHDRVParams;
vInputParameters: IibSHInputParameters;
vCanContinue: Boolean;
vComponentClass: TSHComponentClass;
vComponent: TSHComponent;
begin
Result := False;
FErrorText := EmptyStr;
if Assigned(Database) and Assigned(SQLGenerator) then
begin
if Database.WasLostConnect then Exit;
Dataset.Close;
SQLGenerator.SetAutoGenerateSQLsParams(TSHComponent(Owner));
//этот вызвов необходим для генерации SELECT для таблицы
//и для установки параметров автогенерации
if not ReadTransaction.InTransaction then
begin
if AutoCommit then
begin
ReadTransaction.Params.Text := TRWriteParams;
Dataset.WriteTransaction := WriteTransaction;
Dataset.AutoCommit := True;
end
else
begin
if Assigned(SQLEditor) then
ReadTransaction.Params.Text := GetTransactionParams(SQLEditor.IsolationLevel, SQLEditor.TransactionParams.Text);
Dataset.WriteTransaction := ReadTransaction;
Dataset.AutoCommit := False;
end;
Dataset.ReadTransaction.StartTransaction;
end;
try
if Prepare then
//В принципе Prepare до ввода параметров не нужно, но это страховка от глюков Буза, есои сиквел окажеться некорректным
begin
vCanContinue := True;
vComponentClass := Designer.GetComponent(IibSHInputParameters);
if Assigned(vComponentClass) and Supports(Dataset, IibSHDRVParams, vDRVParams) then
begin
vComponent := vComponentClass.Create(nil);
try
if Supports(vComponent, IibSHInputParameters, vInputParameters) then
begin
vCanContinue := vInputParameters.InputParameters(vDRVParams);
vInputParameters := nil;
end;
finally
FreeAndNil(vComponent);
end;
vDRVParams := nil;
end;
if vCanContinue then
begin
// FEnabledFetchEvent := True;
Screen.Cursor := crHourGlass;
Dataset.Open;
FErrorText := Dataset.ErrorText;
Result := not (Length(Dataset.ErrorText) > 0);
if Result then
SQLGenerator.GenerateSQLs(TSHComponent(Owner));
//этот вызов необходим для генерации RefreshSQL
//т.к. в BeforePost, BeforeDelete нужно иметь
//--валидные сиквела Update и Delete для производства корректной
//--проверки на MultiUpdate и MultiDelete,
//--а автогенерация срабатывает после вызова BeforePost, BeforeDelete :(
Result := Result and (not Database.WasLostConnect);
end;
end;
finally
Screen.Cursor := crDefault;
end;
end;
end;
procedure TibBTData.FetchAll;
begin
Dataset.FetchAll;
end;
procedure TibBTData.Close;
begin
FErrorText := EmptyStr;
Dataset.Close;
end;
procedure TibBTData.Commit;
begin
FErrorText := EmptyStr;
ReadTransaction.Commit;
FErrorText := ReadTransaction.ErrorText;
end;
procedure TibBTData.Rollback;
begin
FErrorText := EmptyStr;
ReadTransaction.Rollback;
FErrorText := ReadTransaction.ErrorText;
end;
function TibBTData.GetStatistics: IibSHStatistics;
begin
Supports(FStatistics, IibSHStatistics, Result);
end;
initialization
Register;
end.
|
unit ParseFastTest;
interface
uses
DUnitX.TestFramework,
SysUtils,
Math,
uEnums,
TestHelper,
uIntX;
type
[TestFixture]
TToParseFastTest = class(TObject)
private
F_length: Integer;
const
StartLength = Integer(1024);
LengthIncrement = Integer(101);
RepeatCount = Integer(50);
RandomStartLength = Integer(1024);
RandomEndLength = Integer(4000);
RandomRepeatCount = Integer(50);
function GetAllNineChars(mlength: Integer): String;
function GetRandomChars(): String;
public
[Setup]
procedure Setup;
[Test]
procedure CompareWithClassic();
[Test]
procedure CompareWithClassicRandom();
end;
implementation
procedure TToParseFastTest.Setup;
begin
F_length := StartLength;
Randomize;
end;
function TToParseFastTest.GetAllNineChars(mlength: Integer): String;
begin
result := StringOfChar('9', mlength);
end;
function TToParseFastTest.GetRandomChars(): String;
var
mlength: Integer;
builder: TStringBuilder;
begin
mlength := RandomRange(RandomStartLength, RandomEndLength);
builder := TStringBuilder.Create(mlength);
try
builder.Clear;
builder.Append(RandomRange(1, 9));
Dec(mlength);
while mlength <> 0 do
begin
builder.Append(RandomRange(0, 9));
Dec(mlength);
end;
result := builder.ToString();
finally
builder.Free;
end;
end;
[Test]
procedure TToParseFastTest.CompareWithClassic();
var
str: String;
classic, fast: TIntX;
begin
TTestHelper.Repeater(RepeatCount,
procedure
begin
str := GetAllNineChars(F_length);
classic := TIntX.Parse(str, TParseMode.pmClassic);
fast := TIntX.Parse(str, TParseMode.pmFast);
Assert.IsTrue(classic = fast);
F_length := F_length + LengthIncrement;
end);
end;
[Test]
procedure TToParseFastTest.CompareWithClassicRandom();
var
str: String;
classic, fast: TIntX;
begin
TTestHelper.Repeater(RandomRepeatCount,
procedure
begin
str := GetRandomChars();
classic := TIntX.Parse(str, TParseMode.pmClassic);
fast := TIntX.Parse(str, TParseMode.pmFast);
Assert.IsTrue(classic = fast);
end);
end;
initialization
TDUnitX.RegisterTestFixture(TToParseFastTest);
end.
|
unit FormPartConfig;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TFormPartConfig = class(TComponent)
private
{ Private declarations }
FPostOnInsert : Boolean;
FRequiredFields : TStringList;
FDependentTables, FDependentTableKeys : TStringList;
FPrefixoCodigo: String;
procedure SetRequiredFields(Value : TStringList);
procedure SetDependentTables(Value : TStringList);
procedure SetDependentTableKeys(Value : TStringList);
protected
{ Protected declarations }
destructor Destroy; override;
constructor Create(AOwner: TComponent); override;
public
{ Public declarations }
published
{ Published declarations }
property PrefixoCodigo : String read FPrefixoCodigo write FPrefixoCodigo;
property PostOnInsert : Boolean read FPostOnInsert write FPostOnInsert default False;
property RequiredFields : TStringList read FRequiredFields write SetRequiredFields;
property DependentTables : TStringList read FDependentTables write SetDependentTables;
property DependentTableKeys : TStringList read FDependentTableKeys write SetDependentTableKeys;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NewPower', [TFormPartConfig]);
end;
constructor TFormPartConfig.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPostOnInsert := False;
FRequiredFields := TStringList.Create;
FDependentTables := TStringList.Create;
FDependentTableKeys := TStringList.Create;
end;
destructor TFormPartConfig.Destroy;
begin
FRequiredFields.Free;
FDependentTables.Free;
FDependentTableKeys.Free;
inherited Destroy;
end;
procedure TFormPartConfig.SetRequiredFields(Value : TStringList);
begin
if FRequiredFields <> Value then
FRequiredFields.Assign(Value);
end;
procedure TFormPartConfig.SetDependentTables(Value : TStringList);
begin
if FDependentTables <> Value then
FDependentTables.Assign(Value);
end;
procedure TFormPartConfig.SetDependentTableKeys(Value : TStringList);
begin
if FDependentTableKeys <> Value then
FDependentTableKeys.Assign(Value);
end;
end.
|
Unit Mapmem;
{ * Mapmem :
* *
* Esta unidad se encarga del mapeo de paginas dentro de dp , tanto *
* usuarios como el del kernel , en los casos del usuario , puede *
* pasar que la pagina se encuentre mas alla de HIGH_MEMORY , *
* asi solo a traves del KERNEL_PDT se podra acceder a estas paginas *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* 05 / 07 / 2004 : Version Inicial *
* *
*********************************************************************
}
interface
{DEFINE DEBUG}
{$I ../include/toro/procesos.inc}
{$I ../include/head/asm.h}
{$I ../include/head/mm.h}
{$I ../include/head/printk_.h}
{$I ../include/head/paging.h}
implementation
{ * Kmapmem : *
* *
* add_f : Direccion fisica de la pagina a mapear *
* add_l : Direccion logica donde sera mapeada *
* add_dir : Puntero al PDT *
* Atributos : !!! *
* *
* Esta funcion mapea dentro de un PDT dado una dir pagina en la dir *
* logica dada . En caso de no haber un PT la crea . Esta funcion solo *
* es llamada por el kernel *
* *
***********************************************************************
}
function kmapmem(add_f , add_l , add_dir:pointer;atributos:word):dword;[public , alias :'KMAPMEM'];
var i:indice;
dp,tp:^dword;
tmp:pointer;
begin
{ Las direcciones deven estar alineadas con los 4 kb }
If ((longint(add_f) and $FFF) =0) or ((longint(add_l) and $FFF)=0) then
else exit(-1);
{ Se calcula el indice dentro de la tabla de directorio y }
{ dentro de la tabla de paginas }
i := Get_Page_Index(add_l);
dp := add_dir;
{ Si el directorio no estubiese presente se crea uno }
If (dp[i.dir_i] and Present_Page) = 0 then
begin
tmp := get_free_kpage;
If tmp=nil then exit(-1);
dp[I.dir_i]:=longint(tmp) or Write_Page or Present_page;
end;
tp:=pointer(dp[I.dir_i] and $FFFFF000);
{ Si la pagina estubiese presente }
If (tp[i.page_i] and Present_Page) = Present_Page then exit(-1);
tp[I.page_i]:=longint(add_f) or atributos ;
exit(0);
end;
{ * Umapmem : *
* *
* add_f : Direccion fisica de la pagina *
* add_l : Direccion logica donde sera mapeada *
* add_dir : PDT *
* atributos : Atributos de la pagina *
* *
* Esta funcion mapea una direccion logica dentro de un PDT dado a difere *
* ncia de kmapmem , utiliza las paginas de la memoria alta . *
* Aclaracion : Trabaja sobre Kernel_Pdt *
*
**************************************************************************
}
function umapmem(add_f , add_l , add_dir:pointer;atributos:word):dword;[public , alias :'UMAPMEM'];
var i:indice;
dp,tp:^dword;
tmp:pointer;
begin
{ Las direcciones deven estar alineadas con los 4 kb }
If ((longint(add_f) and $FFF) =0) or ((longint(add_l) and $FFF)=0) then
else exit(-1);
{ Se calcula el indice dentro de la tabla de directorio y }
{ dentro de la tabla de paginas }
i:=Get_Page_Index(add_l);
dp:=add_dir;
{ Si el directorio no estubiese presente se crea uno }
If (dp[i.dir_i] and Present_Page) = 0 then
begin
tmp:=get_free_page;
If tmp=nil then exit(-1);
dp[I.dir_i]:= Longint(tmp) or User_Mode or Write_Page or Present_page;
end;
tp:=pointer(dp[I.dir_i] and $FFFFF000);
{ Si la pagina estubiese presente }
If (tp[i.page_i] and Present_Page) = Present_Page then exit(-1);
tp[I.page_i]:=longint(add_f) or atributos;
exit(0);
end;
{ * Kunmapmem : *
* *
* add_l : Direccion logica de la pagina *
* add_dir : Directorio de paginas *
* *
* Esta funcion quita de un directorio una direcion logica dada , pero *
* no llama a free_page , devuelve la pagina fisica , para que sea *
* liberada luego , si la tabla de paginas estubiese vacia la libera *
* del PDT *
* *
***********************************************************************
}
function kunmapmem(add_l,add_dir:pointer):pointer;[public , alias :'KUNMAPMEM'];
var tp,dp:^dword;
i:indice;
tmp,count:word;
begin
{ Las direcciones deven estar alineadas con los 4 kb }
If ((longint(add_l) and $FFF) =0) or ((longint(add_dir) and $FFF)=0) then
else exit(nil);
i:=Get_Page_Index(add_l);
dp:=add_dir;
dp+=i.dir_i;
{ Si el directorio no estubiese presente }
If (dp^ and Present_Page) = 0 then exit(nil);
{ Punteo al comienzo de la Tabla de Paginas }
tp:=pointer(dp[I.dir_i] and $FFFFF000);
{ Si la pagina no estubiese presente }
If (tp[I.Page_i] and Present_Page)= 0 then exit(nil);
kunmapmem:=pointer(tp[I.page_i] and $FFFFF000);
tp[I.Page_i]:=0;
{ Se verifica si todas las paginas de la tabla fueron liberadas }
{ y en ese caso se libera la tabla de paginas }
for tmp:= 1 to (Page_Size div 4) do If tp[tmp]=0 then count+=1;
If count =(Page_Size div 4) then
begin
Free_Page(pointer(dp^ and $FFFFF000));
{ Se calcula la dir fisica para Free_Page }
dp^:=0; { Es borrada la entrada en el directorio }
end;
end;
{ * Unmapmem : *
* *
* Vease KUNMAPMEN , es exactamente lo mismo pero para el usuario *
* Aclaracion : Deve trabajar sobre Kernel_Pdt *
* *
***********************************************************************
}
function unmapmem(add_l,add_dir:pointer):pointer;[public , alias :'UNMAPMEM'];
var tp,dp:^dword;
i:indice;
tmp,count:word;
begin
{ Las direcciones deven estar alineadas con los 4 kb }
If ((longint(add_l) and $FFF) =0) or ((longint(add_dir) and $FFF)=0) then
else exit(nil);
i := Get_Page_Index(add_l);
dp := add_dir;
dp += i.dir_i;
{ Si el directorio no estubiese presente }
If (dp^ and Present_Page) = 0 then exit(nil);
{ Punteo al comienzo de la Tabla de Paginas }
tp:=pointer(dp[I.dir_i] and $FFFFF000);
{ Si la pagina no estubiese presente }
If (tp[I.Page_i] and Present_Page)= 0 then exit(nil);
unmapmem:=pointer(tp[I.page_i] and $FFFFF000);
tp[I.Page_i]:=0;
{ Se verifica si todas las paginas de la tabla fueron liberadas }
{ y en ese caso se libera la tabla de paginas }
for tmp:= 1 to (Page_Size div 4) do If tp[tmp]=0 then count+=1;
If count =(Page_Size div 4) then
begin
Free_Page(pointer(dp^ and $FFFFF000));{ Se calcula la dir fisica para Free_Page}
dp^:=0;{ Es borrada la entrada en el directorio }
end;
end;
end.
|
unit uBase256;
{
Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
}
interface
uses
System.SysUtils, uBase;
function Encode(data: TBytes): String;
function Decode(data: String): TBytes;
const
DefaultAlphabet: Array [0 .. 255] of string = ('!', '#', '$', '%', '&', '''',
'(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\', ']', '^', '_', '`', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', ' ', '¡', '¢',
'£', '¤', '¥', '¦', '§', '¨', '©', 'ª', '«', '¬', '', '®', '¯', '°', '±',
'²', '³', '´', 'µ', '¶', '·', '¸', '¹', 'º', '»', '¼', '½', '¾', '¿', 'À',
'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï',
'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', '×', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ',
'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í',
'î', 'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', '÷', 'ø', 'ù', 'ú', 'û', 'ü',
'ý', 'þ', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ',
'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě',
'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ',
'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'ĸ',
'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł');
DefaultSpecial = Char(0);
implementation
function Encode(data: TBytes): string;
var
i, dataLength: Integer;
tempResult: TStringBuilder;
begin
if ((data = nil) or (Length(data) = 0)) then
begin
Exit('');
end;
tempResult := TStringBuilder.Create;
tempResult.Clear;
dataLength := Length(data);
try
for i := 0 to Pred(dataLength) do
begin
tempResult.Append(DefaultAlphabet[data[i]]);
end;
result := tempResult.ToString;
finally
tempResult.Free;
end;
end;
function Decode(data: String): TBytes;
var
i: Integer;
begin
if isNullOrEmpty(data) then
begin
SetLength(result, 1);
result := Nil;
Exit;
end;
SetLength(result, Length(data));
Base(Length(DefaultAlphabet), DefaultAlphabet, DefaultSpecial);
for i := 1 to (Length(data)) do
begin
result[i - 1] := Byte(InvAlphabet[Ord(data[i])]);
end;
end;
end.
|
{
+ BUG: Аккумулятор не удаляется при переходе в меню - патроны видны поверх
+ BUG: Не реализовано различное поведение при столкновении в зависимости от
UserType в TdfPhys. Реализация в TdfMainGame.OnCollision
+ BUG: Не исчезает "Осталось целей" при новой игре
+ BUG: При новой игре следует отключать искусственный интеллект у противников
У первых он остается после последнего этапа
+ BUG: Newgame пролистывается на второй раз
+ BUG: Не исчезает "осталось целей" при окончании этапа
+ BUG: Оставить счетчик по окончании 10-го этапа
+ BUG: Планета не вращается вместе с камерой
+ BUG: При загрузке новой игры не сбрасываются параметры.
+ Перенести соответствующий функционал в Load()
+ ПРОВЕРИТЬ
? TODO: Перерисовать хинт для мыши
+ TODO: Допилить InGameMenu, оно же PauseMenu. Базовый функционал:
"вернуться в игру" и "в главное меню"
+ TODO: "Стрелочки" в HUD, указывающие направление движения корабля
+ Перенести из прототипа
+ TODO: Spacefighter - загрузка текстуры через MatLib с проверкой на
существование текстуры
+ TODO: Создание "врага" с полоской жизни, реализация повреждений
+ Перенести из прототипа
+ TODO: Реализация "Текущий объект", рамка, направление, крестик движения
+ Перенести из прототипа.
+ Перенесено, не проверено.
+ Внести в класс UserControl
+ TODO: При отключении flight mode переводить игрока в главную плоскость
и возвращать камеру на нормальную позицию.
+ TODO: Индикатор скорости игрока
+ TODO: Перерисовать direction для target
+ TODO: Эффекты при столкновении снарядов с астероидами или разрушаемыми
объектами
+ TODO: Индикатор расстояния до цели
TODO: Надо бы комментарии по коду расставить, для себя
+ TODO: Туториал - стрельба по резко двигающимя целям. Цели имеют здоровье
Нельзя отпускать цели далеко от себя.
+ TODO: Реализация списка объектов для выделения
У каждого Spacefighter есть список его врагов, нейтралов и друзей
Определяется по group_id, "клану". Например
0 - нейтральные объекты
1 - дружественные игроку (и сам игрок)
2 - враждебные игроку
+ При добавлении объекта в AllObjects требуется Notify, который
добавляет этот объект в списки у spacefighter-ов.
+ TODO: Реализация класс туториала, у него должен быть
доступ к mainGame для управления
Решено через uGameObjects.pas
+ TODO: Реализация ИИ тренировочной мишени
+ TODO: Графическая реализация мишени - полупрозрачный корабль
синего или иного цвета (аналог голограммы, псевдонастоящий
корабль)
+ TODO: Обучающие надписи. Возможно, стоит создать игровой экран
паузы с подсказками?
+ TODO: Сценарий обучения, тексты
+ TODO: Добавить иконку таймера, допилить его появление и исчезновение
+ TODO: Реплей при неуничтожении всех объектов
+ TODO: Игровой экран "Увы, в альфа версии больше нечего делать" и кнопки
"Выйти" и "Я еще полетаю".
+ TODO: Общая шлифовка туториала
+ TODO: Добавить число оставшихся мишеней
+ TODO: Допилить NewGame - выравнять тексты, поправить тексты
+ TODO: Добавить FadeIn для MainGame.
1 TODO: Нормально реализовать класс планет и других удаленных объектов
1 TODO: FadeIn вызывает Load(), FadeOutComplete - Unload(). Регламентировать
для всех GameScreen-ов, сделать Load и UnLoad защищенными (protected)
1 TODO: Реализовать класс таймера отдельно
2 TODO: Физика на боксах, возможность задать несколько боксов или сфер
для объекта. Предпроверка коллизий по баундинг сферам
3 TODO: Создание режима гонки
? TODO: Переделать титры, добавить им анимацию (уезжаем типа вверх?)
Добавить "спасибо" для Fantom-а, Веон-а, Yar-а и сообщества glscene.ru
Предусмотреть место под тестеров
- TODO: Статусы gssNone, gssFadeOutComplete - регламентировать вызовы
+ TODO: Альтернатива IsKeyDown(VK_LBUTTON), иначе в credits-ах нереально что-то
посмотреть. Продумать систему MouseDown / MouseClick
+-Частично решено в dfKeyboardExt
+ Решено, работает
+ TODO: Допилить кредитсы, добавить надпись для сайта GLScene.ru
+-Частично сделано
+ Сделано
+ TODO: Разобраться со статусами, load-ами и действиями. Уже каша
+-Частично решено. Остается вопрос о том, что gssFadeOutComplete дублирует
gssNone и gssFadeInComplete дублирует gssReady
+ TODO: доделать NewGame
+- Пока сойдет, можно потом попилить
+ Допилено
+ TODO: Перенести игровую логику из прототипа
+ TODO: Добавить надпись left mouse button to skip it!
Roadmap на техническую часть, рефакторинг:
Дата начала работ: после альфы проекта
+ 1. Создание единого предка для UserControl и AIControl
+ 2. Единый предок для всех видимых трехмерных объектов игры
Общие свойства: "жизнь", "разрушаемость", физическая сущность,
процедура апдейта
3. Разгрестись с Load-Unload игровых экранов. Load должен вызывать
настройку начальных параметров, UnLoad - выгружать ненужные данные
4. Унификация загрузки - возможность загружать большую часть ресурсов и
параметров из файлов. Вероятно, рассмотреть вопрос о поддержке XML
вместо ini. Упаковка в архивы, либо перегонка в бинарные файлы
5. Редактор мира для расстановки объектов
6. У TdfTarget Chaser может быть только объектом с оружием. Значит, следует
создать потомка TdfGameObject, который может обладать оружием и
интеллектом
7. У TdfGameObject следует создать Enabled, при Enabled=False -
запрещать Update
Roadmap на геймплейную часть:
Дата начала работ: после альфы проекта
1. Решить статус игры: sandbox с фриплеем, или жестко заданные миссии
2. Далее - какие составляющие будут в игре:
* Квесты (помимо основных), и как они будут выглядеть
* Экономика (покупка кораблей, вооружения, оборудования)
* Экономика 2 (продажа хлама, добыча руды из астероидов)
* РПГ-составляющие - отыгрыш роли, навыки, репутация
* Стратегические составляющие - экономика на планетах
}
unit uGame;
interface
uses
Classes, Controls, Windows, SysUtils, Contnrs, Forms, IniFiles,
GLScene, GLWin32Viewer, GLCadencer, GLObjects, GLRenderContextInfo,
GLCrossPlatform, GLMaterial, GLParticleFX, GLPerlinPFX,
uGameScreen, uLog;
const
C_WAIT_BEFORE_EXIT = 0.3;
C_SYSTEM_FILE = 'data\system.ini';
C_MAIN_SECTION = 'Main';
C_CAMERA_SECTION = 'Camera';
C_BUFFER_SECTION = 'Buffer';
type
TdfGame = class
private
FOwner: TComponent;
FScene: TGLScene;
FViewer: TGLSceneViewer;
FCadencer: TGLCadencer;
FMatLib: TGLMaterialLibrary;
FEngineFX, FBoomFX, FBigBoomFX: TGLPerlinPFXManager;
FCamera: TGLCamera;
FLight: TGLLightSource;
FGameScreens: TObjectList;
FActiveScreen: TdfGameScreen;
FSubject: TdfGameScreen;
FAction: TdfNotifyAction;
FmX, FmY: Integer; //позиция курсора мыши
FWait: Double;
FFPSInd: Integer;
t: Double;
// FGLSceneInfo: TdfGLSceneInfo;
procedure MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure Progress(Sender: TObject; const deltaTime, newTime: Double);
function GetActiveScene: TdfGameScreen;
procedure SetActiveScene(const aScene: TdfGameScreen);
public
constructor Create(aOwner: TComponent); virtual;
destructor Destroy; override;
function AddGameScene(aGameSceneClass: TdfGameSceneClass): TdfGameScreen;
procedure NotifyGameScenes(Subject: TdfGameScreen; Action: TdfNotifyAction);
property ActiveScreen: TdfGameScreen read GetActiveScene write SetActiveScene;
procedure Start;
procedure Stop;
end;
implementation
uses
uTweener, uFonts, uDebugInfo, uGLSceneObjects,
GLVectorGeometry;
{ TdfGame }
procedure TdfGame.Progress(Sender: TObject; const deltaTime, newTime: Double);
var
i: Integer;
begin
FViewer.Invalidate;
Tweener.Update(deltaTime);
t := t + deltaTime;
dfDebugInfo.UpdateParam(FFPSInd, FViewer.FramesPerSecond);
if t >= 1 then
begin
FViewer.ResetPerformanceMonitor;
t := 0;
end;
for i := 0 to FGameScreens.Count - 1 do
TdfGameScreen(FGameScreens[i]).Update(deltaTime, FmX, FmY);
if FActiveScreen.Status = gssFadeInComplete then
begin
logWriteMessage('TdfGame: "' + FActiveScreen.Name + '" status gssFadeInComplete');
FActiveScreen.Status := gssReady;
end;
if Assigned(FSubject) then
case FAction of
naNone: Exit;
naSwitchTo:
if (FActiveScreen.Status = gssFadeOutComplete) or
(FActiveScreen.Status = gssNone) then
begin
logWriteMessage('TdfGame: "' + FActiveScreen.Name + '" status gssFadeOutComplete');
FActiveScreen.Status := gssNone;
FActiveScreen.Unload;
FSubject.Load();
if FSubject.Status = gssPaused then
FSubject.Status := gssReady
else
FSubject.Status := gssFadeIn;
FActiveScreen := FSubject;
FSubject := nil;
end;
naSwitchToQ:
begin
FActiveScreen.Status := gssFadeOutComplete;
FActiveScreen.Unload;
FSubject.Load;
FSubject.Status := gssReady;
FActiveScreen := FSubject;
FSubject := nil;
end;
naPreload: Exit;
//Показываем Subject поверх текущей ActiveScene
naShowModal:
begin
FActiveScreen.Status := gssPaused;
FSubject.Load();
FSubject.Status := gssFadeIn;
FActiveScreen := FSubject;
FSubject := nil;
end;
// else
// begin
// FSubject.Update(deltaTime, FmX, FmY);
// end;
end;
if FAction = naQuitGame then
begin
FWait := FWait + deltaTime;
if FWait >= C_WAIT_BEFORE_EXIT then
begin
PostQuitMessage(0);
Stop();
Free;
end;
end;
end;
function TdfGame.GetActiveScene: TdfGameScreen;
begin
if Assigned(FActiveScreen) then
Result := FActiveScreen
else
begin
Result := nil;
logWriteError('TdfGame: GetActiveScene - nil at FActiveScene!');
end;
end;
procedure TdfGame.MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
FmX := X;
FmY := Y;
end;
procedure TdfGame.SetActiveScene(const aScene: TdfGameScreen);
begin
if Assigned(aScene) then
if not Assigned(FActiveScreen) then
begin
FActiveScreen := aScene;
FActiveScreen.Load();
FActiveScreen.Status := gssFadeIn;
end
else
if aScene <> FActiveScreen then
NotifyGameScenes(aScene, naSwitchTo);
end;
procedure TdfGame.Start;
begin
// dfGLSceneObjects.HUDDummy.MoveLast;
dfDebugInfo.MoveLast;
FCadencer.Enabled := True;
end;
procedure TdfGame.Stop;
begin
FCadencer.Enabled := False;
end;
function TdfGame.AddGameScene(aGameSceneClass: TdfGameSceneClass): TdfGameScreen;
begin
Result := aGameSceneClass.Create();
Result.OnNotify := Self.NotifyGameScenes;
logWriteMessage('TdfGame: Added "' + Result.Name + '" game scene with index: ' + IntToStr(FGameScreens.Add(Result)));
end;
constructor TdfGame.Create(aOwner: TComponent);
var
ind: Integer;
Ini: TIniFile;
begin
inherited Create();
if FileExists(C_SYSTEM_FILE) then
begin
Ini := TIniFile.Create(C_SYSTEM_FILE);
FOwner := aOwner;
FScene := TGLScene.Create(FOwner);
FScene.VisibilityCulling := vcNone;
// FScene.ObjectsSorting := osInherited;
// FScene.ObjectsSorting :=
FCadencer := TGLCadencer.Create(FOwner);
FCadencer.Enabled := False;
FCadencer.OnProgress := Self.Progress;
FCadencer.Scene := FScene;
FCamera := TGLCamera.CreateAsChild(FScene.Objects);
FCamera.DepthOfView := Ini.ReadFloat(C_CAMERA_SECTION, 'DepthOfView', 1000);
FCamera.Direction.SetVector(0,0,1);
FCamera.FocalLength := 90;
FViewer := TGLSceneViewer.Create(FOwner);
FViewer.Buffer.DepthPrecision := dp24bits;
FViewer.Camera := FCamera;
FViewer.Align := alClient;
FViewer.Parent := TWinControl(aOwner);
FViewer.OnMouseMove := MouseMove;
FMatLib := TGLMaterialLibrary.Create(FOwner);
FEngineFX := TGLPerlinPFXManager.Create(FOwner);
FEngineFX.Cadencer := FCadencer;
{+debug}
FEngineFX.ColorInner.SetColor(0.5, 0.5, 0.9, 1.0);
FEngineFX.ColorOuter.SetColor(0.1, 0.1, 0.8, 0.5);
FEngineFX.ParticleSize := 2.1;
with FEngineFX.LifeColors.Add do
begin
LifeTime := 0.3;
end;
FBoomFX := TGLPerlinPFXManager.Create(FOwner);
FBoomFX.Cadencer := FCadencer;
FBoomFX.ColorInner.SetColor(0.9, 0.5, 0.5, 1.0);
FBoomFX.ColorOuter.SetColor(0.7, 0.5, 0.5, 0.5);
FBoomFX.ParticleSize := 1.4;
with FBoomFX.LifeColors.Add do
begin
LifeTime := 0.4;
end;
FBigBoomFX := TGLPerlinPFXManager.Create(FOwner);
FBigBoomFX.Cadencer := FCadencer;
FBigBoomFX.ColorInner.SetColor(0.9, 0.7, 0.7, 1.0);
FBigBoomFX.ColorOuter.SetColor(0.8, 0.4, 0.4, 0.5);
FBigBoomFX.ParticleSize := 5.5;
with FBigBoomFX.LifeColors.Add do
begin
LifeTime := 1.0;
end;
{-debug}
FGameScreens :=TObjectList.Create(True);
FActiveScreen := nil;
FSubject := nil;
FLight := TGLLightSource.CreateAsChild(FCamera);
FLight.Diffuse.SetColor(1, 1, 1);
FViewer.Buffer.BackgroundColor := RGB(
Ini.ReadInteger(C_BUFFER_SECTION, 'backR', 0),
Ini.ReadInteger(C_BUFFER_SECTION, 'backG', 0),
Ini.ReadInteger(C_BUFFER_SECTION, 'backB', 0));
{+debug}
ind := uFonts.AddFont(aOwner, C_FONT_1);
with GetFont(ind) do
Font.Size := 24;
with GetFont(AddFont(aOwner, C_FONT_2)) do
Font.Size := 10;
{-debug}
//Заполняем синглтоны
with dfGLSceneObjects do
begin
Scene := FScene;
Viewer := FViewer;
Cadencer := FCadencer;
MatLibrary := FMatLib;
EnginesFX[0] := FEngineFX;
BoomFX[0] := FBoomFX;
BoomFX[1] := FBigBoomFX;
Camera := FCamera;
end;
dfDebugInfo := TdfDebugInfo.CreateAsChild(FScene.Objects);
dfDebugInfo.Position.Z := -0.5;
dfDebugInfo.BitmapFont := GetFont(C_FONT_2);
dfDebugInfo.Layout := tlTop;
dfDebugInfo.Alignment := taLeftJustify;
dfDebugInfo.Visible := Ini.ReadBool(C_MAIN_SECTION, 'Debug', False);
FFPSInd := dfDebugInfo.AddNewString('FPS');
Ini.Free;
end
else
begin
logWriteError('TdfGame: File ' + C_SYSTEM_FILE + ' not founded', True, True, True);
Free;
end;
end;
destructor TdfGame.Destroy;
begin
//Так как компоненты GLScene, GLViewer и GLCadencer были созданы с родителем
//То их освободит родитель, в нашем случае - сама форма
FGameScreens.Free;
inherited;
end;
procedure TdfGame.NotifyGameScenes(Subject: TdfGameScreen; Action: TdfNotifyAction);
begin
if FAction = naQuitGame then
Exit;
FSubject := Subject;
FAction := Action;
case Action of
naSwitchTo:
begin
// logWriteMessage('TdfGame: Notified action: switch to "' + Subject.Name + '" game scene');
if Assigned(FActiveScreen) then
FActiveScreen.Status := gssFadeOut
else
begin
FSubject.Status := gssFadeIn;
end;
end;
naSwitchToQ: Exit;
naPreload: Subject.Load();
naQuitGame: FWait := 0;
naShowModal: Exit;
end;
end;
end.
|
unit fi_info_reader;
interface
uses
fi_common,
classes;
type
TInfoReader = procedure(stream: TStream; var info: TFontInfo);
TExtensions = array of String;
{
Register font info reader.
All extensions must be in lower case and contain leading periods.
}
procedure RegisterReader(
reader: TInfoReader; const extensions: array of String);
{
Return sorted list of all supported extensions.
These are all extensions that were passed to RegisterReader.
}
function GetSupportedExtensions: TExtensions;
{
Return info reader for the given extension.
The extension must be in lower case and contain a leading period.
If there is no reader for the extension, NIL is returned.
}
function FindReader(const extension: String): TInfoReader;
implementation
uses
fi_utils;
type
TReaderRec = record
extensions: TExtensions;
reader: TInfoReader;
end;
var
readers: array of TReaderRec;
function IsValidExtension(const extension: String): Boolean;
var
c: Char;
begin
if Length(extension) = 0 then
exit(FALSE);
if extension[1] <> '.' then
exit(FALSE);
for c in extension do
if LowerCase(c) <> c then
exit(FALSE);
result := TRUE;
end;
procedure RegisterReader(
reader: TInfoReader; const extensions: array of String);
var
i, j: SizeInt;
begin
Assert(reader <> NIL, 'Reader is NIL');
Assert(Length(extensions) > 0, 'Extension list is empty');
for i := 0 to High(readers) do
if reader = readers[i].reader then
Assert(FALSE, 'Reader is already registered');
i := Length(readers);
SetLength(readers, i + 1);
SetLength(readers[i].extensions, Length(extensions));
for j := 0 to High(extensions) do
begin
Assert(
IsValidExtension(extensions[j]),
'Invalid extension ' + extensions[j]);
readers[i].extensions[j] := extensions[j];
end;
readers[i].reader := reader;
end;
function GetSupportedExtensions: TExtensions;
var
i, j, k: SizeInt;
begin
SetLength(result, 0);
for i := 0 to High(readers) do
begin
j := Length(result);
SetLength(result, j + Length(readers[i].extensions));
for k := 0 to High(readers[i].extensions) do
result[j + k] := readers[i].extensions[k];
end;
specialize SortArray<String>(result);
end;
function FindReader(const extension: String): TInfoReader;
var
i, j: SizeInt;
begin
Assert(IsValidExtension(extension), 'Invalid extension ' + extension);
for i := 0 to High(readers) do
for j := 0 to High(readers[i].extensions) do
if extension = readers[i].extensions[j] then
exit(readers[i].reader);
result := NIL;
end;
end.
|
function TPipeCommand_EGrep.Compile( args: TStrArray ): string;
begin
if length( args ) <> 1 then
exit( 'bad egrep command usage. please type "man egrep" in order to see help!' );
_arguments := args;
exit(''); // no error
end;
procedure TPipeCommand_EGrep.Run;
var i: integer = 0;
n: integer = 0;
begin
n := length( _input );
for i:=0 to n - 1 do begin
//writeln( 'grep: ', _arguments[0], ' in ', _input[i] );
if preg_match( _input[i], _arguments[0] ) then
push( _output, _input[i] );
end;
end;
|
program Schachsimulator;
const
BRETTSIZE = 8;
type
tRichtung = (Oben,Unten,Rechts,Links,ObenRechts,UntenLinks,ObenLinks,UntenRechts);
tFarbe = (Weiss, Schwarz);
tArt = (King, Queen, Rook, Horse, Bishop, Pawn);
tRefFelder = ^tFeld;
tFeld = record
Zeile : integer;
Spalte : integer;
next : tRefFelder;
end;
tRefSchachfigur = ^tSchachfigur;
tSchachfigur = record
Farbe : tFarbe;
Art : tArt;
Kurz : char;
Basiswert : integer;
PositionZ : integer;
PositionS : integer;
Wert : integer;
PossibleMoves : tRefFelder;
next : tRefSchachfigur;
end;
var
Figuren : tRefSchachfigur;
Figur : tRefSchachfigur;
i,
j : integer;
function InizialisiereSpielbrett : tRefSchachfigur;
{inizialisiert alle Figuren. Jeder Eigenschaft wird dabei ein Startwert zugewiesen.
* Es Werden erst alle weissen dann alle schwarzen Sonderfiguren inizialisiert,
* dann weisse dann schwarze Bauern. Alle Figuren sind in einer linearen Liste. Der Funktionswert
* ist eine Referenz auf diese Liste.}
var
ZeigerFigur,
ZeigerFigurNeu : tRefSchachfigur;
i : integer;
begin
ZeigerFigur := nil;
begin{inizialisiere Weisse Sonder Figuren}
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Weiss;
ZeigerFigurNeu^.Art := Rook;
ZeigerFigurNeu^.Kurz := 'R';
ZeigerFigurNeu^.Basiswert := 50;
ZeigerFigurNeu^.PositionZ := 1;
ZeigerFigurNeu^.PositionS := 1;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Weiss;
ZeigerFigurNeu^.Art := Horse;
ZeigerFigurNeu^.Kurz := 'H';
ZeigerFigurNeu^.Basiswert := 40;
ZeigerFigurNeu^.PositionZ := 1;
ZeigerFigurNeu^.PositionS := 2;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Weiss;
ZeigerFigurNeu^.Art := Bishop;
ZeigerFigurNeu^.Kurz := 'B';
ZeigerFigurNeu^.Basiswert := 30;
ZeigerFigurNeu^.PositionZ := 1;
ZeigerFigurNeu^.PositionS := 3;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Weiss;
ZeigerFigurNeu^.Art := King;
ZeigerFigurNeu^.Kurz := 'K';
ZeigerFigurNeu^.Basiswert := 10000;
ZeigerFigurNeu^.PositionZ := 1;
ZeigerFigurNeu^.PositionS := 4;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Weiss;
ZeigerFigurNeu^.Art := Queen;
ZeigerFigurNeu^.Kurz := 'Q';
ZeigerFigurNeu^.Basiswert := 100;
ZeigerFigurNeu^.PositionZ := 1;
ZeigerFigurNeu^.PositionS := 5;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Weiss;
ZeigerFigurNeu^.Art := Bishop;
ZeigerFigurNeu^.Kurz := 'B';
ZeigerFigurNeu^.Basiswert := 30;
ZeigerFigurNeu^.PositionZ := 1;
ZeigerFigurNeu^.PositionS := 6;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Weiss;
ZeigerFigurNeu^.Art := Horse;
ZeigerFigurNeu^.Kurz := 'H';
ZeigerFigurNeu^.Basiswert := 40;
ZeigerFigurNeu^.PositionZ := 1;
ZeigerFigurNeu^.PositionS := 7;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Weiss;
ZeigerFigurNeu^.Art := Rook;
ZeigerFigurNeu^.Kurz := 'R';
ZeigerFigurNeu^.Basiswert := 50;
ZeigerFigurNeu^.PositionZ := 1;
ZeigerFigurNeu^.PositionS := 8;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
end;{inizialisiere Weisse Sonder Figuren}
begin{inizialisiere Schwarze Sonder Figuren}
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Schwarz;
ZeigerFigurNeu^.Art := Rook;
ZeigerFigurNeu^.Kurz := 'r';
ZeigerFigurNeu^.Basiswert := 50;
ZeigerFigurNeu^.PositionZ := 8;
ZeigerFigurNeu^.PositionS := 1;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Schwarz;
ZeigerFigurNeu^.Art := Horse;
ZeigerFigurNeu^.Kurz := 'h';
ZeigerFigurNeu^.Basiswert := 40;
ZeigerFigurNeu^.PositionZ := 8;
ZeigerFigurNeu^.PositionS := 2;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Schwarz;
ZeigerFigurNeu^.Art := Bishop;
ZeigerFigurNeu^.Kurz := 'b';
ZeigerFigurNeu^.Basiswert := 30;
ZeigerFigurNeu^.PositionZ := 8;
ZeigerFigurNeu^.PositionS := 3;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Schwarz;
ZeigerFigurNeu^.Art := King;
ZeigerFigurNeu^.Kurz := 'k';
ZeigerFigurNeu^.Basiswert := 10000;
ZeigerFigurNeu^.PositionZ := 8;
ZeigerFigurNeu^.PositionS := 4;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Schwarz;
ZeigerFigurNeu^.Art := Queen;
ZeigerFigurNeu^.Kurz := 'q';
ZeigerFigurNeu^.Basiswert := 100;
ZeigerFigurNeu^.PositionZ := 8;
ZeigerFigurNeu^.PositionS := 5;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Schwarz;
ZeigerFigurNeu^.Art := Bishop;
ZeigerFigurNeu^.Kurz := 'b';
ZeigerFigurNeu^.Basiswert := 30;
ZeigerFigurNeu^.PositionZ := 8;
ZeigerFigurNeu^.PositionS := 6;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Schwarz;
ZeigerFigurNeu^.Art := Horse;
ZeigerFigurNeu^.Kurz := 'h';
ZeigerFigurNeu^.Basiswert := 40;
ZeigerFigurNeu^.PositionZ := 8;
ZeigerFigurNeu^.PositionS := 7;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Schwarz;
ZeigerFigurNeu^.Art := Rook;
ZeigerFigurNeu^.Kurz := 'r';
ZeigerFigurNeu^.Basiswert := 50;
ZeigerFigurNeu^.PositionZ := 8;
ZeigerFigurNeu^.PositionS := 8;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
end;{inizialisiere Schwarze Sonder Figuren}
for i := 1 to BRETTSIZE do
{erstelle Reihe Weise Bauern}
begin
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Weiss;
ZeigerFigurNeu^.Art := Pawn;
ZeigerFigurNeu^.Kurz := 'P';
ZeigerFigurNeu^.Basiswert := 10;
ZeigerFigurNeu^.PositionZ := 2;
ZeigerFigurNeu^.PositionS := i;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
end;
for i := 1 to BRETTSIZE do
{erstelle Reihe schwarzer Bauern}
begin
new(ZeigerFigurNeu);
ZeigerFigurNeu^.Farbe := Schwarz;
ZeigerFigurNeu^.Art := Pawn;
ZeigerFigurNeu^.Kurz := 'p';
ZeigerFigurNeu^.Basiswert := 10;
ZeigerFigurNeu^.PositionZ := 7;
ZeigerFigurNeu^.PositionS := i;
ZeigerFigurNeu^.Wert := 10;
ZeigerFigurNeu^.next := ZeigerFigur;
ZeigerFigur := ZeigerFigurNeu;
end;
InizialisiereSpielbrett := ZeigerFigur;
end;{InizialisiereSpielbrett}
function CheckField(
inRefFiguren : tRefSchachfigur;
inZeile : integer;
inSpalte : integer) : tRefSchachfigur;
{Prüft ob das Feld (inZeile,inSpalte) besetzt ist. Wenn ja liefert es eine Referenz auf die Figur zurück sonst nil.}
var
ZeigerFigur : tRefSchachfigur;
gefunden : boolean;
begin
gefunden := false;
ZeigerFigur := inRefFiguren;
while (ZeigerFigur <> nil) and (not gefunden) do
begin
if (ZeigerFigur^.PositionZ = inZeile) and (ZeigerFigur^.PositionS = inSpalte) then
gefunden := true
else
ZeigerFigur := ZeigerFigur^.next;
if gefunden then
CheckField := ZeigerFigur
else
CheckField := nil;
end;
end;{CheckFiled}
procedure ShowChessBoard(inRefFiguren : tRefSchachfigur);
{Gibt eine Grafik des gegenwärtigen Schachfeldes aus. o steht für leeres Feld kleine Buchstaben für schwarze und große
* für weise Figuren}
var
ZeigerFigur : tRefSchachfigur;
i,
j : integer;
begin
ZeigerFigur := inRefFiguren;
for i := 1 to BRETTSIZE do
begin
for j := 1 to BRETTSIZE do
begin
ZeigerFigur := CheckField(inRefFiguren,i,j);
if ZeigerFigur <> nil then
write(ZeigerFigur^.Kurz,' ')
else
write('o ');
end;
writeln;
end;
end;{ShowChessBoard}
function istWeiss(inRefFigur : tRefSchachfigur) : boolean;
begin
if inRefFigur^.Farbe = Weiss then
istWeiss := true
else
istWeiss := false;
end;{istWeiss}
function istArt(
inRefFigur : tRefSchachfigur;
inArt : tArt) : boolean;
{Prüft ob Figur mit Referenz inRefFigur die Art inArt hat}
begin
if inRefFigur^.Art = inArt then
istArt := true
else
istArt := false;
end;{istArt}
function sindAndersfarbig(
inRefFigur1 : tRefSchachfigur;
inRefFigur2 : tRefSchachfigur) : boolean;
begin
if istWeiss(inRefFigur1) = istWeiss(inRefFigur2) then
sindAndersfarbig := false
else
sindAndersfarbig := true;
end;{sindAndersfarbig}
procedure loadPlusDirection(
inRichtung : tRichtung;
var outPlusZ : integer;
var outPlusS : integer);
{Berechnet die Werte PlusZ und PlusS welche die Schrittrichtung steuern in Abhängigkeit von der eingegebenen Richtung}
var
plusZ,
plusS : integer;
begin
if inRichtung = Oben then
begin
plusZ := -1;
plusS := 0;
end;
if inRichtung = Unten then
begin
plusZ := 1;
plusS := 0;
end;
if inRichtung = Rechts then
begin
plusZ := 0;
plusS := 1;
end;
if inRichtung = Links then
begin
plusZ := 0;
plusS := -1;
end;
if inRichtung = ObenRechts then
begin
plusZ := -1;
plusS := 1;
end;
if inRichtung = UntenLinks then
begin
plusZ := 1;
plusS := -1;
end;
if inRichtung = ObenLinks then
begin
plusZ := -1;
plusS := -1;
end;
if inRichtung = UntenRechts then
begin
plusZ := 1;
plusS := 1;
end;
OutPlusZ := plusZ;
OutPlusS := plusS;
end;{loadPlusDirection}
function FindNextFigur(
inRichtung : tRichtung;
inRefFiguren : tRefSchachfigur;
inRefFigur : tRefSchachfigur) : tRefSchachfigur;
{Findet eine Referenz auf eine Figur die in der gegebenen Richtung am nächsten zu der
* Figur mit Referenz inRefFigur liegt}
var
RefNextFigur : tRefSchachfigur;
Zeile,
Spalte : integer;
plusZ,
plusS : integer;
begin
RefNextFigur := nil;
Zeile := inRefFigur^.PositionZ;
Spalte := inRefFigur^.PositionS;
loadPlusDirection(inRichtung,plusZ,plusS);
Zeile := Zeile + plusZ;
Spalte := Spalte + plusS;
while (RefNextFigur = nil) and (Zeile <= BRETTSIZE) and (Zeile >= 1) and (Spalte <= BRETTSIZE) and ( Spalte >= 1) do
begin
RefNextFigur := CheckField(inRefFiguren,Zeile,Spalte);
Zeile := Zeile + plusZ;
Spalte := Spalte + plusS;
end;
FindNextFigur := RefNextFigur;
end;{FindNextFigure}
procedure CalculateDistance(
inRefFigur1 : tRefSchachfigur;
inRefFigur2 : tRefSchachfigur;
var outDistanceZ : integer;
var outDistanceS : integer);
{Prozedur nimmt 2 Referenzen auf Schachfiguren und berechnet aus deren Postionsattributen ihre Distanz zu einander.
* die Prozedur hat 2 outVariablen die die Distanz in Zeilen und Spalten ist. Die Distanz ist negativ wenn Figur1 rechts bzw unterhalb
* von Figur2 steht.}
var
DistanceZ,
DistanceS : integer;
begin
DistanceZ := inRefFigur2^.PositionZ - inRefFigur1^.PositionZ;
DistanceS := inRefFigur2^.PositionS - inRefFigur1^.PositionS;
outDistanceZ := DistanceZ;
outDistanceS := DistanceS;
end;{CalculateDistance}
procedure addMove(
inRefFigur : tRefSchachfigur;
inZeile : integer;
inSpalte : integer);
{fügt einer Figur ein erreichbares Feld in die Liste PossibleMoves hinzu.}
var
ZeigerFeld : tRefFelder;
ZeigerNewFeld : tRefFelder;
begin
ZeigerFeld := inRefFigur^.PossibleMoves;
new(ZeigerNewFeld);
ZeigerNewFeld^.Zeile := inZeile;
ZeigerNewFeld^.Spalte := inSpalte;
ZeigerNewFeld^.next := ZeigerFeld;
inRefFigur^.PossibleMoves := ZeigerNewFeld;
end;{addMove}
procedure deleteAllMoves(inRefFigur : tRefSchachfigur);
{Löscht die Liste alle mögliches Züge der Figur inRefFigur}
var
ZeigerFeld : tRefFelder;
procedure deleteMove(inZeigerFeld : tRefFelder);
begin
if inZeigerFeld <> nil then
begin
deleteMove(inZeigerFeld^.next);
dispose(inZeigerFeld);
end;
end;{deleteMove}
begin
ZeigerFeld := inRefFigur^.PossibleMoves;
deleteMove(ZeigerFeld);
end;{deleteAllMoves}
procedure ShowMoves(inRefFigur : tRefSchachfigur);
{Schreibt alle Felder in der Liste PossibleMoves aus}
var
ZeigerFeld : tRefFelder;
begin
ZeigerFeld := inRefFigur^.PossibleMoves;
while ZeigerFeld <> nil do
begin
writeln(inRefFigur^.PositionZ,',',inRefFigur^.PositionS,' --> ',ZeigerFeld^.Zeile,',',ZeigerFeld^.Spalte);
ZeigerFeld := ZeigerFeld^.next;
end;
end;
procedure PossibleMovesPawn(
inRefFiguren : tRefSchachfigur;
inRefFigur : tRefSchachfigur);
{Fügt alle möglichen Züge für einen Bauern in die Liste PossibleMpves der Figur
* inRefFigur ein}
var
RefFigur : tRefSchachfigur;
RefNearFigur : tRefSchachfigur;
DistanceZ,
DistanceS : integer;
begin
RefFigur := inRefFigur;
if istWeiss(RefFigur) then
begin
RefNearFigur := FindNextFigur(Unten,inRefFiguren,RefFigur);
{adde gerade moves}
if RefNearFigur <> nil then
begin
CalculateDistance(RefFigur,RefNearFigur,DistanceZ,DistanceS);
if abs(DistanceZ) > 1 then
begin
addMove(RefFigur,RefFigur^.PositionZ + 1,RefFigur^.PositionS);
if (abs(DistanceZ) > 2) and (RefFigur^.PositionZ = 2) then
addMove(RefFigur,RefFigur^.PositionZ + 2,RefFigur^.PositionS);
end;
end
else
{RefNextFigur ist nil}
begin
if RefFigur^.PositionZ + 1 <= BRETTSIZE then
begin
addMove(RefFigur,RefFigur^.PositionZ + 1,RefFigur^.PositionS);
if (RefFigur^.PositionZ + 2 <= BRETTSIZE) and (RefFigur^.PositionZ = 2) then
addMove(RefFigur,RefFigur^.PositionZ + 2,RefFigur^.PositionS);
end;
end;
RefNearFigur := FindNextFigur(UntenRechts,inRefFiguren,RefFigur);
{adde Moves nach unten Rechts}
if RefNearFigur <> nil then
begin
CalculateDistance(RefFigur,RefNearFigur,DistanceZ,DistanceS);
if (abs(DistanceS) = 1) and (abs(DistanceZ) = 1) and (sindAndersfarbig(RefFigur,RefNearFigur)) then
addMove(RefFigur,RefFigur^.PositionZ + DistanceZ,RefFigur^.PositionS + DistanceS);
end;
RefNearFigur := FindNextFigur(UntenLinks,inRefFiguren,RefFigur);
{adde Moves nach unten Links}
if RefNearFigur <> nil then
begin
CalculateDistance(RefFigur,RefNearFigur,DistanceZ,DistanceS);
if (abs(DistanceS) = 1) and (abs(DistanceZ) = 1) and (sindAndersfarbig(RefFigur,RefNearFigur)) then
addMove(RefFigur,RefFigur^.PositionZ + DistanceZ,RefFigur^.PositionS + DistanceS);
end;
end
else
{Bauer ist schwarz}
begin
RefNearFigur := FindNextFigur(Oben,inRefFiguren,RefFigur);
{adde gerade moves}
if RefNearFigur <> nil then
begin
CalculateDistance(RefFigur,RefNearFigur,DistanceZ,DistanceS);
if abs(DistanceZ) > 1 then
begin
addMove(RefFigur,RefFigur^.PositionZ - 1,RefFigur^.PositionS);
if (abs(DistanceZ) > 2) and (RefFigur^.PositionZ = 7) then
addMove(RefFigur,RefFigur^.PositionZ - 2,RefFigur^.PositionS);
end;
end
else
{RefNextFigur ist nil}
begin
if RefFigur^.PositionZ - 1 >= 1 then
begin
addMove(RefFigur,RefFigur^.PositionZ - 1,RefFigur^.PositionS);
if (RefFigur^.PositionZ - 2 >= 1) and (RefFigur^.PositionZ = 7) then
addMove(RefFigur,RefFigur^.PositionZ - 2,RefFigur^.PositionS);
end;
end;
RefNearFigur := FindNextFigur(ObenRechts,inRefFiguren,RefFigur);
{adde Moves nach oben Rechts}
if RefNearFigur <> nil then
begin
CalculateDistance(RefFigur,RefNearFigur,DistanceZ,DistanceS);
if (abs(DistanceS) = 1) and (abs(DistanceZ) = 1) and (sindAndersfarbig(RefFigur,RefNearFigur)) then
addMove(RefFigur,RefFigur^.PositionZ + DistanceZ,RefFigur^.PositionS + DistanceS);
end;
RefNearFigur := FindNextFigur(ObenLinks,inRefFiguren,RefFigur);
{adde Moves nach unten Links}
if RefNearFigur <> nil then
begin
CalculateDistance(RefFigur,RefNearFigur,DistanceZ,DistanceS);
if (abs(DistanceS) = 1) and (abs(DistanceZ) = 1) and (sindAndersfarbig(RefFigur,RefNearFigur)) then
addMove(RefFigur,RefFigur^.PositionZ + DistanceZ,RefFigur^.PositionS + DistanceS);
end;
end;
end;{PossibleMovesPawn}
procedure AddMovesDirection(
inRichtung : tRichtung;
inRefFiguren : tRefSchachfigur;
inRefFigur : tRefSchachfigur);
{fügt der Figur inRefFigur alle möglichen Felder in Richtung inRichtung bis zur nächsten Figur in die Liste PossibleMoves hinzu}
var
RefFigur : tRefSchachfigur;
RefNearFigur : tRefSchachfigur;
DistanceZ,
DistanceS,
plusZ,
plusS,
i,
j : integer;
begin
RefFigur := inRefFigur;
loadPlusDirection(inRichtung,plusZ,plusS);
RefNearFigur := FindNextFigur(inRichtung,inRefFiguren,inRefFigur);
if RefNearFigur <> nil then
begin
CalculateDistance(RefFigur,RefNearFigur,DistanceZ,DistanceS);
i := RefFigur^.PositionZ + plusZ;
j := RefFigur^.PositionS + plusS;
while (i <> RefNearFigur^.PositionZ) or (j <> RefNearFigur^.PositionS) do
begin
addMove(RefFigur,i,j);
i := i + plusZ;
j := j + plusS;
end;
if sindAndersfarbig(RefFigur,RefNearFigur) then
addMove(RefFigur,RefNearFigur^.PositionZ,RefNearFigur^.PositionS);
end
else
{RefNearFigur ist nil}
begin
i := RefFigur^.PositionZ + plusZ;
j := RefFigur^.PositionS + plusS;
while (i <= BRETTSIZE) and (j <= BRETTSIZE) and (i >= 1) and (j >= 1) do
begin
addMove(RefFigur,i,j);
i := i + plusZ;
j := j + plusS;
end;
end;
end;{AddMovesDirection}
procedure PossibleMovesKing(
inRefFiguren : tRefSchachfigur;
inRefFigur : tRefSchachfigur);
var
RefNearFigur : tRefSchachfigur;
Richtung : tRichtung;
plusZ,
plusS : integer;
begin
for Richtung := Oben to UntenRechts do
begin
loadPlusDirection(Richtung,plusZ,plusS);
RefNearFigur := CheckField(inRefFiguren,inRefFigur^.PositionZ + plusZ,inRefFigur^.PositionS + plusS);
if RefNearFigur <> nil then
begin
if sindAndersfarbig(inRefFigur,RefNearFigur) then
addMove(inRefFigur,RefNearFigur^.PositionZ,RefNearFigur^.PositionS);
end
else
{RefNearFigur ist nil}
begin
if (inRefFigur^.PositionZ + plusZ <= BRETTSIZE) and (inRefFigur^.PositionZ + plusZ >= 1) and (inRefFigur^.PositionS + plusS <= BRETTSIZE) and (inRefFigur^.PositionS + plusS >= 1) then
addMove(inRefFigur, inRefFigur^.PositionZ + plusZ,inRefFigur^.PositionS + plusS);
end;
end;
end;{PossibleMovesKing}
procedure PossibleMovesHorse(
inRefFiguren : tRefSchachfigur;
inRefFigur : tRefSchachfigur);
{berechnet alle möglichen Züge für eine Figur inRefFigur von der Art Horse und Fügt sie in die Liste PossibleMoves ein.}
var
RefNearFigur : tRefSchachfigur;
Richtung : tRichtung;
plusZ,
plusS : integer;
begin
for Richtung := ObenRechts to UntenRechts do
begin
loadPlusDirection(Richtung,plusZ,plusS);
RefNearFigur := CheckField(inRefFiguren,inRefFigur^.PositionZ + 2 * plusZ ,inRefFigur^.PositionS + 1 * plusS);
if RefNearFigur <> nil then
begin
if sindAndersfarbig(inRefFigur,RefNearFigur) then
addMove(inRefFigur,RefNearFigur^.PositionZ, RefNearFigur^.PositionS);
end
else
{RefNearFigur ist nil}
begin
if (inRefFigur^.PositionZ + 2 * plusZ <= BRETTSIZE) and (inRefFigur^.PositionZ + 2 * plusZ >= 1) and (inRefFigur^.PositionS + plusS <= BRETTSIZE) and (inRefFigur^.PositionS + plusS >= 1) then
addMove(inRefFigur, inRefFigur^.PositionZ + 2 * plusZ, inRefFigur^.PositionS + plusS);
end;
end;
{das selbe VErfahren wird durchgeführt aber nun wird plusS mal 2 gerechnet und plusZ mal 1}
for Richtung := ObenRechts to UntenRechts do
begin
loadPlusDirection(Richtung,plusZ,plusS);
RefNearFigur := CheckField(inRefFiguren,inRefFigur^.PositionZ + 1 * plusZ ,inRefFigur^.PositionS + 2 * plusS);
if RefNearFigur <> nil then
begin
if sindAndersfarbig(inRefFigur,RefNearFigur) then
addMove(inRefFigur,RefNearFigur^.PositionZ, RefNearFigur^.PositionS);
end
else
{RefNearFigur ist nil}
begin
if (inRefFigur^.PositionZ + 1 * plusZ <= BRETTSIZE) and (inRefFigur^.PositionZ + 1 * plusZ >= 1) and (inRefFigur^.PositionS + 2 * plusS <= BRETTSIZE) and (inRefFigur^.PositionS + 2 * plusS >= 1) then
addMove(inRefFigur, inRefFigur^.PositionZ + 1 * plusZ,inRefFigur^.PositionS + 2 * plusS);
end;
end;
end;{CalculateMovesHorse}
procedure CalculatePossibleMoves(
inRefFiguren : tRefSchachfigur;
inRefFigur : tRefSchachfigur);
{Berechnet die Möglichen Züge einer Figur mit Referenz inFigur}
var
Richtung : tRichtung;
begin
if istArt(inRefFigur,Pawn) then
PossibleMovesPawn(inRefFiguren,inRefFigur);
if istArt(inRefFigur,Rook) then
for Richtung := Oben to Links do
AddMovesDirection(Richtung,inRefFiguren,inRefFigur);
if istArt(inRefFigur,Bishop) then
for Richtung := ObenRechts to UntenRechts do
AddMovesDirection(Richtung,inRefFiguren,inRefFigur);
if istArt(inRefFigur,Queen) then
for Richtung := Oben to UntenRechts do
AddMovesDirection(Richtung,inRefFiguren,inRefFigur);
if istArt(inRefFigur,King) then
PossibleMovesKing(inRefFiguren,inRefFigur);
if istArt(inRefFigur,Horse) then
PossibleMovesHorse(inRefFiguren,inRefFigur);
end;{CalculatePossibleMoves}
procedure CalculateAllPossibleMoves(inRefFiguren : tRefSchachfigur);
{berechnet für alle Figuren in der Liste mit Referenz inRefFiguren das Attribut
* Possible Moves.}
var
RefFigur : tRefSchachfigur;
begin
RefFigur := inRefFiguren;
while RefFigur <> nil do
begin
deleteAllMoves(RefFigur);
CalculatePossibleMoves(inRefFiguren,RefFigur);
RefFigur := RefFigur^.next;
end;
end;{CalculateAllPossibleMoves}
begin
Figuren := InizialisiereSpielbrett;
ShowChessBoard(Figuren);
CalculateAllPossibleMoves(Figuren);
Figur := CheckField(Figuren,8,2);
ShowMoves(Figur);
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_KERNEL.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PAXCOMP_KERNEL;
interface
uses {$I uses.def}
Classes,
SysUtils,
TypInfo,
PAXCOMP_CONSTANTS,
PAXCOMP_TYPES,
PAXCOMP_SYS,
PAXCOMP_MODULE,
PAXCOMP_SCANNER,
PAXCOMP_PARSER,
PAXCOMP_SYMBOL_REC,
PAXCOMP_BASESYMBOL_TABLE,
PAXCOMP_SYMBOL_TABLE,
PAXCOMP_BYTECODE,
PAXCOMP_ERROR,
PAXCOMP_OFFSET,
PAXCOMP_VAROBJECT,
PAXCOMP_STDLIB,
PAXCOMP_TYPEINFO,
PAXCOMP_MAP,
PAXCOMP_CLASSFACT,
PAXCOMP_BASERUNNER,
PAXCOMP_RTI,
{$ifdef DRTTI}
RTTI,
PAXCOMP_2010,
PAXCOMP_2010REG,
{$endif}
PAXCOMP_GENERIC;
type
TWhatParse = (wpProgram, wpExpression, wpEvalExpression);
TUsedUnitEvent = function (Sender: TObject; const AUnitName: String;
var SourceCode: String): Boolean of object;
TImportMemberEvent = procedure (Sender: TObject;
MemberId: Integer;
const AMemberName: String) of object;
TIncludeEvent = procedure (Sender: TObject; const FileName: String;
var Text: String) of object;
TCompilerDirectiveEvent = procedure (Sender: TObject;
const Directive: String;
var ok: Boolean)
of object;
TUndeclaredIdentifierEvent = function (Sender: TObject;
const IdentName: String;
var Scope: String;
var FullTypeName: String): boolean
of object;
TCommentEvent = procedure (Sender: TObject;
const Comment: String;
const Context: String;
CommentedTokens: TStrings) of object;
TUnitAliasEvent = procedure (Sender: TObject;
var UnitName: String) of object;
TKernel = class
private
fPAX64: Boolean;
fTargetPlatform: TTargetPlatform;
fSearchPathList: TStringList;
function GetPAX64: Boolean;
procedure SetPAX64(value: Boolean);
procedure SetFieldOffsets;
procedure RemoveTypes;
function GetRootKernel: TKernel;
function GetRootSearchPathList: TStringList;
procedure SetupDefaultSettings;
function GetRunnerKind: TRunnerKind;
function GetTargetPlatform: TTargetPlatform;
procedure SetTargetPlatform(value: TTargetPlatform);
function GetSupportedSEH: Boolean;
public
IsUNIC: Boolean;
ParserList: TParserList;
SymbolTable: TSymbolTable;
Code: TCode;
Errors: TErrorList;
Warnings: TErrorList;
UndeclaredTypes: TUndeclaredTypeList;
UndeclaredIdents: TUndeclaredIdentList;
Modules: TModuleList;
OffsetList: TOffsetList;
ExportList: TExportList;
HostClassListIds: TIntegerList;
CondDirectiveList, ExternalSymList: TStringList;
DefList: TDefList;
ClassFactory: TPaxClassFactory;
TypeInfoList: TPaxTypeInfoList;
MessageList: TMessageList;
UsedUnitList: TStringList;
TypeDefList: TTypeDefList;
EvalList: TStringList;
Owner: TObject;
TryCount: Integer;
OnCompilerProgress: TNotifyEvent;
OnUsedUnit: TUsedUnitEvent;
OnImportUnit: TImportMemberEvent;
OnImportType: TImportMemberEvent;
OnImportGlobalMembers: TNotifyEvent;
OnSavePCU: TSavePCUEvent;
OnLoadPCU: TLoadPCUEvent;
OnInclude: TIncludeEvent;
OnSavePCUFinished: TSavePCUFinishedEvent; // jason
OnLoadPCUFinished: TLoadPCUFinishedEvent; // jason
OnDefineDirective: TCompilerDirectiveEvent;
OnUndefineDirective: TCompilerDirectiveEvent;
OnUnknownDirective: TCompilerDirectiveEvent;
OnUndeclaredIdentifier: TUndeclaredIdentifierEvent;
OnComment: TCommentEvent;
OnUnitAlias: TUnitAliasEvent;
DEBUG_MODE: Boolean;
CurrParser: TBaseParser;
IsConsoleApp: Boolean;
Alignment: Integer;
SignCompression: Boolean;
Canceled: Boolean;
CancelChar: Char;
CompletionPrefix: String;
SignCodeCompletion: Boolean;
CompletionTarget: String;
CompletionHasParsed: Boolean;
InterfaceOnly: Boolean;
ImportOnly: Boolean;
UndeclaredIdentifiers: TStringList;
TypeMap: TTypeMap;
BuildAll: Boolean;
BuildWithRuntimePackages: Boolean;
BuildedUnits: TStringList;
PCUStreamList: TStreamList;
PCUOwner: Pointer;
DefaultParser: TBaseParser;
CurrLanguage: String;
ModeSEH: Boolean;
GT: TBaseSymbolTable;
IsFramework: Boolean;
FindDeclId: Integer;
prog: TBaseRunner;
AnonymousClassCount: Integer;
{$ifdef DRTTI}
ImportUnitList: TUnitList;
{$endif}
ExAlphaList: TAssocIntegers;
constructor Create(i_Owner: TObject);
destructor Destroy; override;
function GetRunnerClass: TBaseRunnerClass;
function AddModule(const Name, LanguageName: String;
IsPCU: Boolean = false): TModule;
procedure AddCode(const ModuleName, Text: String);
procedure AddCodeFromFile(const ModuleName, FileName: String);
procedure RegisterParser(P: TBaseParser);
function GetHandle(LevelId: Integer; const Name: String; Upcase: Boolean): Integer;
procedure ParseModule(M: TModule; ModuleNumber: Integer;
What: TWhatParse = wpProgram;
eval: Pointer = nil);
procedure Parse(CodeCompletion: Boolean = false;
const CancelModuleName: String = '';
X: Integer = -1;
Y: Integer = -1);
procedure ParseCompletion(const CancelModuleName: String;
X: Integer;
Y: Integer);
procedure ParseExpression(const Expression: String;
const LangName: String = '');
procedure Link;
function HasError: Boolean;
procedure RaiseError(const Message: string; params: array of Const);
procedure CreateError(const Message: string; params: array of Const);
procedure CreateWarning(const Message: string; params: array of Const);
function SourceLineToByteCodeLine(const ModuleName: String;
SourceLine: Integer): Integer;
function IsExecutableLine(const ModuleName: String;
SourceLine: Integer): Boolean;
function FindFullPath(const FileName: String): String;
function GetOffset(S: TSymbolRec): Integer;
function ExistsOffset(S: TSymbolRec): Boolean;
procedure Reset;
procedure ResetCompilation;
function GetTypeMapRec(Id: Integer): TTypeMapRec;
procedure CopyRootEvents;
procedure AssignImportTable(ImportTable: Pointer);
procedure SetProg(AProg: TBaseRunner);
procedure UpdateTypeInfos;
procedure CompressHostClassList(HostMapTable: TMapTable);
procedure CreateRTI(aprogram: TBaseRunner);
procedure AllocateConstants(const PData: Pointer);
function GetDestructorAddress: Pointer;
{$ifdef DRTTI}
procedure RegisterImportUnit(Level: Integer; const AUnitName: String);
{$endif}
property RootKernel: TKernel read GetRootKernel;
property PAX64: Boolean read GetPAX64 write SetPAX64;
property RootSearchPathList: TStringList read GetRootSearchPathList;
property RunnerKind: TRunnerKind read GetRunnerKind;
property TargetPlatform: TTargetPlatform read GetTargetPlatform write SetTargetPlatform;
property SupportedSEH: Boolean read GetSupportedSEH;
end;
function CheckProc(const TypeName: String; Data: Pointer;
errKind: TExternRecKind): Boolean;
var
VarCheckProc: TCheckProc = CheckProc;
var
CurrKernel: TKernel;
implementation
uses
PAXCOMP_EVAL,
PAXCOMP_PASCAL_PARSER;
constructor TKernel.Create(i_Owner: TObject);
begin
FindAvailTypes;
GT := GlobalSymbolTable;
SetupDefaultSettings;
Owner := i_Owner;
OnCompilerProgress := nil;
Errors := TErrorList.Create(Self);
Warnings := TErrorList.Create(Self);
UndeclaredTypes := TUndeclaredTypeList.Create;
UndeclaredIdents := TUndeclaredIdentList.Create;
SymbolTable := TSymbolTable.Create(Self);
SymbolTable.Reset;
Code := TCode.Create(Self);
Code.Reset;
Modules := TModuleList.Create(Self);
Modules.Clear;
ParserList := TParserList.Create(Self);
DEBUG_MODE := false;
CondDirectiveList := TStringList.Create;
DefList := TDefList.Create;
ExternalSymList := TStringList.Create;
UsedUnitList := TStringList.Create;
TypeDefList := TTypeDefList.Create;
EvalList := TStringList.Create;
OffsetList := nil;
ExportList := nil;
HostClassListIds := TIntegerList.Create;
Alignment := GlobalAlignment;
SignCompression := true;
Canceled := false;
SignCodeCompletion := false;
InterfaceOnly := false;
UndeclaredIdentifiers := TStringList.Create;
BuildedUnits := TStringList.Create;
PCUStreamList := TStreamList.Create;
TypeMap := TTypeMap.Create;
DefaultParser := TPascalParser.Create;
{$ifdef DRTTI}
ImportUnitList := TUnitList.Create;
{$endif}
fSearchPathList := TStringList.Create;
ExAlphaList := TAssocIntegers.Create;
end;
destructor TKernel.Destroy;
begin
FreeAndNil(SymbolTable);
FreeAndNil(Code);
FreeAndNil(Modules);
FreeAndNil(Errors);
FreeAndNil(Warnings);
UndeclaredTypes.Reset;
FreeAndNil(UndeclaredTypes);
UndeclaredIdents.Reset;
FreeAndNil(UndeclaredIdents);
FreeAndNil(HostClassListIds);
FreeAndNil(ParserList);
FreeAndNil(DefList);
FreeAndNil(CondDirectiveList);
FreeAndNil(ExternalSymList);
FreeAndNil(UsedUnitList);
FreeAndNil(TypeDefList);
FreeAndNil(EvalList);
FreeAndNil(UndeclaredIdentifiers);
FreeAndNil(BuildedUnits);
FreeAndNil(PCUStreamList);
FreeAndNil(TypeMap);
FreeAndNil(DefaultParser);
{$ifdef DRTTI}
FreeAndNil(ImportUnitList);
{$endif}
FreeAndNil(fSearchPathList);
FreeAndNil(ExAlphaList);
inherited;
end;
procedure TKernel.Reset;
begin
CompletionTarget := '';
SetupDefaultSettings;
SymbolTable.Reset;
Code.Reset;
Errors.Reset;
Warnings.Reset;
UndeclaredTypes.Reset;
UndeclaredIdents.Reset;
HostClassListIds.Clear;
Modules.Clear;
ParserList.Clear;
DefList.Clear;
UsedUnitList.Clear;
TypeDefList.Clear;
EvalList.Clear;
TryCount := 0;
Canceled := false;
SignCodeCompletion := false;
InterfaceOnly := false;
UndeclaredIdentifiers.Clear;
BuildedUnits.Clear;
PCUStreamList.Clear;
ExternalSymList.Clear;
TypeMap.Clear;
PCUOwner := nil;
AnonymousClassCount := 0;
{$ifdef DRTTI}
ImportUnitList.Clear;
{$endif}
fSearchPathList.Clear;
ExAlphaList.Clear;
end;
procedure TKernel.ResetCompilation;
begin
CompletionTarget := '';
if Code.Card = 0 then
SymbolTable.CompileCard := SymbolTable.Card
else
SymbolTable.ResetCompilation;
Code.Reset;
Errors.Reset;
Warnings.Reset;
UndeclaredTypes.Reset;
UndeclaredIdents.Reset;
HostClassListIds.Clear;
Modules.Clear;
DefList.Clear;
UsedUnitList.Clear;
TypeDefList.Clear;
EvalList.Clear;
TryCount := 0;
Canceled := false;
InterfaceOnly := false;
UndeclaredIdentifiers.Clear;
ExternalSymList.Clear;
TypeMap.Clear;
PCUOwner := nil;
AnonymousClassCount := 0;
{$ifdef DRTTI}
ImportUnitList.Clear;
{$endif}
end;
function TKernel.AddModule(const Name, LanguageName: String;
IsPCU: Boolean = false): TModule;
var
I: Integer;
Found: Boolean;
begin
if Modules.Count = 0 then
begin
SymbolTable.CompileCard := SymbolTable.Card;
CurrLanguage := LanguageName;
end;
Found := false;
for I := 0 to ParserList.Count - 1 do
if StrEql(LanguageName, ParserList[I].LanguageName) then
Found := true;
if not Found then
begin
if StrEql(LanguageName, 'Pascal') then
begin
RegisterParser(DefaultParser);
end
else
RaiseError(errUnregisteredLanguage, [LanguageName]);
end;
result := Modules.AddModule(Name, LanguageName);
result.IsPCU := IsPCU;
end;
procedure TKernel.AddCode(const ModuleName, Text: String);
var
I: Integer;
begin
I := Modules.IndexOf(ModuleName);
if I = -1 then
RaiseError(errModuleNotFound, [ModuleName]);
Modules[I].Lines.Text := Modules[I].Lines.Text + Text;
end;
procedure TKernel.AddCodeFromFile(const ModuleName, FileName: String);
var
L: TStringList;
S, FullPath: String;
I: Integer;
{$IFDEF MACOS}
J: Integer;
{$ENDIF}
begin
I := Modules.IndexOf(ModuleName);
if I = -1 then
RaiseError(errModuleNotFound, [ModuleName]);
FullPath := FindFullPath(FileName);
if not FileExists(FullPath) then
RaiseError(errFileNotFound, [FileName]);
L := TStringList.Create;
try
L.LoadFromFile(FullPath);
S := L.Text;
{$IFDEF MACOS}
for J := SLow(S) to SHigh(S) do
if (Ord(S[J]) = 8220) or (Ord(S[J]) = 8221) then
S[J] := '"';
{$ENDIF}
Modules[I].Lines.Text := Modules[I].Lines.Text + S;
Modules[I].FileName := FullPath;
finally
FreeAndNil(L);
end;
end;
procedure TKernel.RegisterParser(P: TBaseParser);
begin
ParserList.AddParser(P);
end;
function TKernel.GetHandle(LevelId: Integer; const Name: String; Upcase: Boolean): Integer;
var
id, I, P: Integer;
Ok: Boolean;
S: String;
begin
P := 0;
for I:= Length(Name) downto 1 do
if Name[I] = '.' then
begin
P := I;
break;
end;
if P > 0 then
begin
S := Copy(Name, 1, P - 1);
LevelId := GetHandle(LevelId, S, Upcase);
if LevelId = 0 then
begin
result := 0;
Exit;
end;
S := Copy(Name, P + 1, Length(Name) - P);
end
else
S := Name;
id := 0;
with SymbolTable do
for I := Card downto 1 do
begin
if (Records[I].Level = LevelId) and
(Records[I].OwnerId = 0) and
(Records[I].Kind <> KindNONE) then
begin
if UpCase then
ok := StrEql(Records[I].Name, S)
else
ok := Records[I].Name = S;
if ok then
begin
id := I;
break;
end;
end;
end;
if id > 0 then
begin
if SymbolTable[id].Kind in KindSUBs then
result := - SymbolTable[id].Value
else if SymbolTable[id].Kind in [KindNAMESPACE, KindTYPE] then
result := id
else
result := SymbolTable[id].Shift;
end
else
result := 0;
end;
procedure TKernel.ParseModule(M: TModule; ModuleNumber: Integer;
What: TWhatParse = wpProgram;
eval: Pointer = nil);
var
LanguageNamespaceId: Integer;
L, I, J, Id, ExitLabelId, CurrSelfId, CurrN: Integer;
parser: TBaseParser;
R: TSymbolRec;
ExtraNamespaceList: TStringList;
begin
UsedUnitList.Clear;
if eval = nil then
ExtraNamespaceList := nil
else
ExtraNamespaceList := TEval(eval).NamespaceList;
Canceled := false;
// DefList.Clear;
for I := 0 to CondDirectiveList.Count - 1 do
DefList.Add(CondDirectiveList[I]);
parser := ParserList.FindParser(M.LanguageName);
if parser = nil then
RaiseError(errLanguageNotRegistered, [M.LanguageName]);
CurrParser := parser;
M.ModuleNumber := ModuleNumber;
CurrLanguage := M.LanguageName;
parser.Init(Self, M);
ExitLabelId := 0;
L := 0;
LanguageNamespaceId := 0;
try
parser.ParsesModule := true;
try
parser.Gen(OP_BEGIN_MODULE, ModuleNumber, parser.LanguageId, Integer(parser.UpCase));
parser.Gen(OP_SEPARATOR, ModuleNumber, 0, 0);
LanguageNamespaceId := SymbolTable.LookUp(M.LanguageName + 'Namespace', 0, true);
if LanguageNamespaceId = 0 then
LanguageNamespaceId := H_PascalNamespace;
// LanguageNamespaceId := SymbolTable.RegisterNamespace(0, M.LanguageName + 'Namespace');
IsFramework := false;
{$IFDEF EXPLICIT_OFF}
parser.EXPLICIT_OFF := true;
parser.Gen(OP_OPTION_EXPLICIT, 0, 0, 0);
{$ENDIF}
parser.Gen(OP_WARNINGS_ON, 0, 0, 0);
parser.Gen(OP_BEGIN_USING, LanguageNamespaceId, 0, 0);
parser.Gen(OP_BEGIN_USING, 0, 0, 0);
if ExtraNamespaceList <> nil then
begin
for I := 0 to ExtraNamespaceList.Count - 1 do
begin
Id := SymbolTable.LookupFullName(ExtraNamespaceList[I], parser.UpCase);
if Id > 0 then
parser.Gen(OP_BEGIN_USING, Id, 0, 0);
end;
end;
L := parser.NewLabel;
parser.SkipLabelStack.Push(L);
ExitLabelId := parser.NewLabel;
parser.ExitLabelStack.Push(L);
case What of
wpProgram:
begin
parser.ParseProgram;
end;
wpExpression:
begin
parser.Gen(OP_END_INTERFACE_SECTION, 0, 0, 0);
parser.DECLARE_SWITCH := false;
parser.Call_SCANNER;
parser.Gen(OP_ASSIGN, SymbolTable.ResultId, parser.Parse_Expression, SymbolTable.ResultId);
end;
wpEvalExpression:
begin
R := SymbolTable.AddRecord;
R.Kind := KindVAR;
R.Name := StrExprResult;
R.Level := 0;
if eval <> nil then
TEval(eval).ResultId := SymbolTable.Card;
CurrN := TBaseRunner(TEval(eval).SProg).CurrN;
if CurrN > 0 then
CurrSelfId := TKernel(TEval(eval).SKernel).Code.GetCurrSelfId(CurrN)
else
CurrSelfId := 0;
parser.Gen(OP_END_INTERFACE_SECTION, 0, 0, 0);
if CurrSelfId > 0 then
begin
Parser.Gen(OP_BEGIN_WITH, CurrSelfId, 0, 0);
Parser.WithStack.Push(CurrSelfId);
end;
parser.DECLARE_SWITCH := false;
parser.Call_SCANNER;
parser.Gen(OP_ASSIGN, R.Id, parser.Parse_Expression, R.Id);
if CurrSelfId > 0 then
begin
Parser.Gen(OP_END_WITH, CurrSelfId, 0, 0);
Parser.WithStack.Pop;
end;
end;
else
parser.ParseProgram;
end;
except
on E: Exception do
begin
if E is PaxCompilerException then
begin
// already has been processed
end
else if E is PaxCancelException then
begin
if CompletionHasParsed then
begin
Errors.Reset;
Warnings.Reset;
end;
Canceled := true;
end
else
begin
CreateError(E.Message, []);
end;
end;
end;
finally
CurrParser := nil;
parser.SkipLabelStack.Pop;
parser.SetLabelHere(L);
parser.ExitLabelStack.Pop;
parser.SetLabelHere(ExitLabelId);
parser.Gen(OP_END_USING, LanguageNamespaceId, 0, 0);
parser.Gen(OP_END_USING, 0, 0, 0);
// parser.Gen(OP_RET, 0, 0, 0);
parser.Gen(OP_END_MODULE, ModuleNumber, 0, 0);
IsConsoleApp := parser.IsConsoleApp;
if Assigned(prog) then
prog.Console := IsConsoleApp;
parser.ParsesModule := false;
end;
if parser.InterfaceOnly then
Exit;
if Canceled then
begin
Parser.Gen(OP_NOP, 0, 0, 0);
Parser.Gen(OP_NOP, 0, 0, 0);
Parser.Gen(OP_NOP, 0, 0, 0);
Parser.Gen(OP_NOP, 0, 0, 0);
Exit;
end;
if What = wpExpression then
Exit;
if What = wpEvalExpression then
Exit;
if SignCodeCompletion then
Exit;
if not StrEql(M.LanguageName, 'C') then
for I:=FirstLocalId + 1 to SymbolTable.Card do
begin
if SymbolTable[I].IsForward then
begin
for J := 1 to Code.Card do
if Code[J].Op = OP_BEGIN_SUB then
if Code[J].Arg1 = I then
begin
Code.N := J;
break;
end;
CreateError(errUnsatisfiedForwardOrExternalDeclaration, [SymbolTable[I].Name]);
end;
end;
if parser.scanner.DefStack.Count > 0 then
CreateError(errMissingENDIFdirective, ['']);
end;
procedure TKernel.Parse(CodeCompletion: Boolean = false;
const CancelModuleName: String = '';
X: Integer = -1;
Y: Integer = -1);
var
I, J, CancelPos: Integer;
Temp: Boolean;
ExtraModuleName, ExtraCode: String;
begin
CompletionHasParsed := false;
SignCodeCompletion := CodeCompletion;
Temp := false;
code.Reset;
SymbolTable.CompileCard := SymbolTable.Card;
I := 0;
while (I < Modules.Count) do
begin
if CodeCompletion and StrEql(CancelModuleName, Modules[I].Name) then
begin
CancelPos := Modules.GetPos(CancelModuleName, X, Y);
if CancelPos = -1 then
Exit;
Modules[I].CancelPos := CancelPos;
end;
Modules[I].State := msCompiling;
if not Modules[I].SkipParsing then
begin
ParseModule(Modules[I], I);
end;
Modules[I].State := msCompiled;
Inc(I);
if Canceled then
begin
Temp := True;
if I >= Modules.Count then
break;
end;
end;
Canceled := Temp;
for I := Modules.Count - 1 downto 0 do
if Modules[I].SkipParsing then
Modules.Delete(Modules[I]);
if ImportOnly then
Exit;
RemoveTypes;
TypeDefList.GenPascalUnits;
for J := 0 to TypeDefList.TypeModuleList.Count - 1 do
if TypeDefList.TypeModuleList[J].LangId = PASCAL_LANGUAGE then
if TypeDefList.TypeModuleList[J].Success then
begin
ExtraModuleName := strExtraPascalUnit + TypeDefList.TypeModuleList[J].ModuleName;
ExtraCode := TypeDefList.TypeModuleList[J].Source;
AddModule(ExtraModuleName, 'Pascal');
AddCode(ExtraModuleName, ExtraCode);
I := Modules.Count - 1;
Modules[I].IsExtra := true;
Modules[I].State := msCompiling;
ParseModule(Modules[I], I);
Modules[I].State := msCompiled;
end;
TypeDefList.GenBasicUnits;
for J := 0 to TypeDefList.TypeModuleList.Count - 1 do
if TypeDefList.TypeModuleList[J].LangId = BASIC_LANGUAGE then
if TypeDefList.TypeModuleList[J].Success then
begin
ExtraModuleName := strExtraBasicUnit + TypeDefList.TypeModuleList[J].ModuleName;
ExtraCode := TypeDefList.TypeModuleList[J].Source;
AddModule(ExtraModuleName, 'Basic');
AddCode(ExtraModuleName, ExtraCode);
I := Modules.Count - 1;
Modules[I].IsExtra := true;
Modules[I].State := msCompiling;
ParseModule(Modules[I], I);
Modules[I].State := msCompiled;
end;
TypeDefList.GenJavaUnits;
for J := 0 to TypeDefList.TypeModuleList.Count - 1 do
if TypeDefList.TypeModuleList[J].LangId = JAVA_LANGUAGE then
if TypeDefList.TypeModuleList[J].Success then
begin
ExtraModuleName := strExtraJavaUnit + TypeDefList.TypeModuleList[J].ModuleName;
ExtraCode := TypeDefList.TypeModuleList[J].Source;
AddModule(ExtraModuleName, 'Java');
AddCode(ExtraModuleName, ExtraCode);
I := Modules.Count - 1;
Modules[I].IsExtra := true;
Modules[I].State := msCompiling;
ParseModule(Modules[I], I);
Modules[I].State := msCompiled;
end;
end;
procedure TKernel.ParseCompletion(const CancelModuleName: String;
X: Integer;
Y: Integer);
var
I, J, J1, CancelPos, Card1, Op: Integer;
S: String;
ActiveUnitList: TStringList;
begin
CompletionHasParsed := false;
SignCodeCompletion := true;
code.Reset;
SymbolTable.CompileCard := SymbolTable.Card;
I := Modules.IndexOf(CancelModuleName);
if I = -1 then
Exit;
CancelPos := Modules.GetPos(CancelModuleName, X, Y);
if CancelPos = -1 then
Exit;
Modules[I].CancelPos := CancelPos;
Modules[I].State := msCompiling;
ParseModule(Modules[I], I);
Modules[I].State := msCompiled;
Canceled := false;
Card1 := Code.Card;
InterfaceOnly := true;
ActiveUnitList := TStringList.Create;
try
for J1 := 0 to UsedUnitList.Count - 1 do
begin
S := UpperCase(UsedUnitList[J1]);
ActiveUnitList.Add(S);
end;
J := 0;
while J < ActiveUnitList.Count do
begin
S := ActiveUnitList[J];
I := Modules.IndexOf(S);
if I >= 0 then
begin
Modules[I].State := msCompiling;
ParseModule(Modules[I], I);
Modules[I].State := msCompiled;
for J1 := 0 to UsedUnitList.Count - 1 do
begin
S := UpperCase(UsedUnitList[J1]);
if ActiveUnitList.IndexOf(S) = -1 then
ActiveUnitList.Add(S);
end;
end;
Inc(J);
end;
finally
FreeAndNil(ActiveUnitList);
InterfaceOnly := false;
end;
for I := Code.Card downto Card1 do
begin
Op := Code[I].Op;
if (Op <> OP_EVAL) and
(Op <> OP_BEGIN_MODULE) and
(Op <> OP_END_MODULE) and
(Op <> OP_BEGIN_USING) and
(Op <> OP_ASSIGN_CONST) and
(Op <> OP_ADD_ANCESTOR) and
(Op <> OP_ASSIGN_TYPE) then
begin
Code.DeleteRecord(I);
end;
end;
end;
procedure TKernel.ParseExpression(const Expression: String;
const LangName: String = '');
var
M: TModule;
begin
if LangName = '' then
M := AddModule('$', 'Pascal')
else
M := AddModule('$', LangName);
AddCode('$', Expression);
ParseModule(M, 0, wpExpression);
end;
procedure TKernel.RaiseError(const Message: string; params: array of Const);
begin
CreateError(Message, params);
if SignCodeCompletion then
raise PaxCancelException.Create(Format(Message, params))
else
raise PaxCompilerException.Create(Format(Message, params));
end;
procedure TKernel.CreateError(const Message: string; params: array of Const);
var
E: TError;
S: String;
begin
dmp;
S := Format(Message, params);
E := TError.Create(Self, S);
Errors.Add(E);
end;
procedure TKernel.CreateWarning(const Message: string; params: array of Const);
var
E: TError;
begin
dmp;
E := TError.Create(Self, Format(Message, params));
Warnings.Add(E);
end;
function TKernel.HasError: Boolean;
begin
result := Errors.Count > 0;
end;
function CheckProc(const TypeName: String; Data: Pointer; errKind: TExternRecKind): Boolean;
var
Code: TCode;
CodeRec: TCodeRec;
SymbolTable: TSymbolTable;
I, Id, K: Integer;
S: String;
begin
S := ExtractName(TypeName);
result := false;
Code := TKernel(Data).Code;
SymbolTable := TKernel(Data).SymbolTable;
K := SymbolTable.Card;
for I := 1 to Code.Card do
begin
CodeRec := Code[I];
Id := CodeRec.Arg1;
if (Id > StdCard) and (Id <= K) then
if StrEql(S, SymbolTable[Id].Name) then
begin
Code.N := I;
result := true;
Exit;
end;
Id := CodeRec.Arg2;
if (Id > StdCard) and (Id <= K) then
if StrEql(S, SymbolTable[Id].Name) then
begin
Code.N := I;
result := true;
Exit;
end;
Id := CodeRec.Res;
if (Id > StdCard) and (Id <= K) then
if StrEql(S, SymbolTable[Id].Name) then
begin
Code.N := I;
result := true;
Exit;
end;
end;
end;
procedure TKernel.Link;
{$ifdef DRTTI}
var
Q: TStringList;
I, Id: Integer;
AUnitName: String;
{$endif}
begin
CurrProg := Prog;
SymbolTable.LinkCard := SymbolTable.CompileCard;
try
{$ifdef DRTTI}
if ImportUnitList.Count > 0 then
begin
dmp;
Q := TStringList.Create;
try
Code.CreateEvalList(EvalList);
if EvalList.Count > 0 then
begin
for I := 0 to ImportUnitList.Count - 1 do
Q.Add(ImportUnitList[I].Name);
ImportUnitList.FindMembers(EvalList);
ImportUnitList.Sort;
if IsDump then
ImportUnitList.Dump('simp_units.txt');
for I := 0 to ImportUnitList.Count - 1 do
begin
Id := RegisterUnit(ImportUnitList[I], SymbolTable, EvalList, Self);
if Assigned(OnImportUnit) then
begin
AUnitName := ImportUnitList[I].Name;
if Q.IndexOf(AUnitName) >= 0 then
begin
try
SymbolTable.HeaderParser.kernel := Self;
SymbolTable.HeaderParser.CurrImportUnit := AUnitName;
OnImportUnit(Owner, Id, AUnitName);
finally
SymbolTable.HeaderParser.CurrImportUnit := '';
SymbolTable.HeaderParser.kernel := nil;
end;
end;
end;
end;
if Assigned(OnImportGlobalMembers) then
OnImportGlobalMembers(Owner);
SymbolTable.LinkCard := SymbolTable.Card;
end;
finally
FreeAndNil(Q);
end;
end;
{$endif}
dmp;
SymbolTable.Update;
try
SymbolTable.ResolveExternList(VarCheckProc, Self);
except
on E: Exception do
begin
CreateError(E.Message, []);
end;
end;
if HasError then Exit;
code.RemoveEvalOpForTypes;
if HasError then Exit;
code.ProcessImplements;
if HasError then Exit;
code.RemoveEvalOp;
if HasError then Exit;
if HasError then Exit;
if not Canceled then
code.GenHostStructConst;
if HasError then Exit;
if not Canceled then
code.UpdateDefaultConstructors;
if HasError then Exit;
modules.CreateLoadOrder;
if HasError then Exit;
code.CheckOverride;
if HasError then Exit;
code.CheckTypes;
if Canceled then
begin
Exit;
end;
if InterfaceOnly then
begin
Exit;
end;
if SignCodeCompletion then
begin
Exit;
end;
code.CheckExpansions;
if HasError then Exit;
code.AddWarnings;
if HasError then Exit;
code.InsertDynamicTypeDestructors;
if HasError then Exit;
code.InsertFinalizators;
if HasError then Exit;
code.InsertTryFinally;
if HasError then Exit;
try
SymbolTable.SetShifts(prog);
except
on E: Exception do
CreateError(E.Message, []);
end;
UpdateTypeInfos;
if HasError then Exit;
SetFieldOffsets;
if HasError then Exit;
code.ProcessSizeOf;
if HasError then Exit;
code.ChangeOrderOfActualParams;
if HasError then Exit;
code.AssignShifts;
if HasError then Exit;
code.RemoveLoadProc;
if HasError then Exit;
code.InsertHostMonitoring;
if HasError then Exit;
code.Optimization;
if HasError then Exit;
code.AdjustTryList;
if HasError then Exit;
if DEBUG_MODE then
Code.InsertCallHostEvents;
Code.SetLastCondRaise;
dmp;
except
end;
end;
function TKernel.SourceLineToByteCodeLine(const ModuleName: String;
SourceLine: Integer): Integer;
var
I: Integer;
M: TModule;
begin
result := 0;
I := Modules.IndexOf(ModuleName);
if I = -1 then
Exit;
M := Modules[I];
for I:=M.P1 to M.P3 do
if Code[I].OP = OP_SEPARATOR then
if Code[I].Arg2 = SourceLine then
begin
result := I;
Exit;
end;
end;
function TKernel.IsExecutableLine(const ModuleName: String;
SourceLine: Integer): Boolean;
var
I, J: Integer;
M: TModule;
begin
result := false;
I := Modules.IndexOf(ModuleName);
if I = -1 then
Exit;
M := Modules[I];
for I:=M.P1 to M.P3 do
if Code[I].OP = OP_SEPARATOR then
if Code[I].Arg2 = SourceLine then
begin
J := I;
repeat
Inc(J);
if J > Code.Card then
Exit;
if Code[J].Op = OP_SEPARATOR then
Exit;
if Code[J].Op = OP_SET_CODE_LINE then
begin
result := true;
Exit;
end;
until false;
Exit;
end;
end;
function TKernel.GetOffset(S: TSymbolRec): Integer;
var
Shift: Integer;
begin
if SignCompression then
begin
Shift := S.Shift;
if (Shift <= 0) or (S.Kind = kindTYPE_FIELD) then
begin
result := Shift;
Exit;
end
else if PAX64 then
begin
if S.Param or S.Local then
begin
result := Shift;
Exit;
end;
end;
result := OffsetList.GetOffset(Shift);
if result = -1 then
RaiseError(errInternalError, []);
end
else
result := S.Shift;
end;
function TKernel.ExistsOffset(S: TSymbolRec): Boolean; //18.09.2009
var
Shift: Integer;
begin
if SignCompression then
begin
Shift := S.Shift;
if (Shift <= 0) or (S.Kind = kindTYPE_FIELD) then
begin
result := true;
Exit;
end;
result := OffsetList.GetOffset(Shift) <> - 1;
end
else
result := true;
end;
function TKernel.GetTypeMapRec(Id: Integer): TTypeMapRec;
var
T: Integer;
begin
result := nil;
T := SymbolTable[Id].FinalTypeId;
if not (T in [typeRECORD, typeCLASS]) then
Exit;
T := SymbolTable[Id].TerminalTypeId;
result := TypeMap.Lookup(T);
if result = nil then
result := TypeMap.Add(T);
if not result.Completed then
begin
result.Fields.Clear;
SymbolTable.GetFieldCount(Id, result);
result.Completed := true;
end;
end;
function TKernel.GetRootKernel: TKernel;
begin
result := Self;
while result.PCUOwner <> nil do
result := result.PCUOwner;
end;
procedure TKernel.CopyRootEvents;
var
RK: TKernel;
begin
RK := RootKernel;
if Self <> RK then
begin
Owner := RK.Owner;
OnCompilerProgress := RK.OnCompilerProgress;
OnUsedUnit := RK.OnUsedUnit;
OnSavePCU := RK.OnSavePCU;
OnLoadPCU := RK.OnLoadPCU;
OnInclude := RK.OnInclude;
OnDefineDirective := RK.OnDefineDirective;
OnUndefineDirective := RK.OnUndefineDirective;
OnUnknownDirective := RK.OnUnknownDirective;
OnSavePCUFinished := RK.OnSavePCUFinished; // jason
OnLoadPCUFinished := RK.OnLoadPCUFinished; // jason
end;
end;
procedure TKernel.AssignImportTable(ImportTable: Pointer);
begin
GT := ImportTable;
SymbolTable.SetImportTable(GT);
end;
procedure TKernel.SetProg(AProg: TBaseRunner);
begin
prog := AProg;
if prog = nil then
Exit;
ClassFactory := prog.ProgClassFactory;
TypeInfoList := prog.ProgTypeInfoList;
OffsetList := prog.OffsetList;
ExportList := prog.ExportList;
MessageList := prog.MessageList;
prog.ModeSEH := ModeSEH;
prog.PAX64 := PAX64;
prog.UseMapping := true;
prog.SetGlobalSym(GT);
end;
procedure TKernel.UpdateTypeInfos;
var
I, J: Integer;
RI: TTypeInfoContainer;
ClassTypeDataContainer: TClassTypeDataContainer;
SR: TSymbolRec;
begin
for I := 0 to TypeInfoList.Count - 1 do
begin
RI := TypeInfoList[I];
if RI.TypeInfo.Kind = tkClass then
begin
ClassTypeDataContainer :=
RI.TypeDataContainer as
TClassTypeDataContainer;
with ClassTypeDataContainer.AnotherFieldListContainer do
for J := 0 to Count - 1 do
begin
SR := SymbolTable[Records[J].Id];
Records[J].Offset := SR.Shift;
Records[J].FinalFieldTypeId := SR.FinalTypeId;
end;
end;
end;
end;
function TKernel.GetPAX64: Boolean;
begin
result := fPAX64;
end;
procedure TKernel.SetPAX64(value: Boolean);
begin
fPAX64 := value;
if fPAX64 then
begin
ModeSEH := false;
SymbolTable.SetPAX64(true);
end;
end;
procedure TKernel.CompressHostClassList(HostMapTable: TMapTable);
begin
SymbolTable.CompressHostClassList(HostMapTable, HostClassListIds);
end;
procedure TKernel.SetFieldOffsets;
var
I, J, Id: Integer;
ClassTypeDataContainer: TClassTypeDataContainer;
FieldListContainer: TFieldListContainer;
begin
for I:=0 to TypeInfoList.Count - 1 do
if TypeInfoList[I].TypeInfo.Kind = tkClass then
begin
ClassTypeDataContainer := TypeInfoList[I].TypeDataContainer as
TClassTypeDataContainer;
FieldListContainer := ClassTypeDataContainer.FieldListContainer;
for J := 0 to FieldListContainer.Count - 1 do
begin
Id := FieldListContainer[J].Id;
FieldListContainer[J].Offset := SymbolTable[Id].Shift;
end;
end;
end;
procedure TKernel.RemoveTypes;
var
I, TypeId: Integer;
S, OldFullName, NewFullName: String;
begin
for I := 0 to TypeDefList.RemTypeIds.Count - 1 do
begin
TypeId := TypeDefList.RemTypeIds[I];
S := SymbolTable[TypeId].Name;
OldFullName := SymbolTable[TypeId].FullName;
S := S + '#';
SymbolTable[TypeId].Name := S;
NewFullName := SymbolTable[TypeId].FullName;
if SymbolTable[TypeId].FinalTypeId = typeCLASS then
if not ClassFactory.RenameClass(OldFullName, NewFullName) then
RaiseError(errInternalError, []);
end;
end;
procedure TKernel.CreateRTI(aprogram: TBaseRunner);
var
RuntimeModuleList: TRuntimeModuleList;
I, J, K, Index, Id: Integer;
UsedName: String;
MR: TModuleRec;
begin
RuntimeModuleList := aprogram.RunTimeModuleList;
RuntimeModuleList.Clear;
SetLength(RuntimeModuleList.SourceLines, Code.Card + 1);
SetLength(RuntimeModuleList.ModuleIndexes, Code.Card + 1);
for I:=1 to Code.Card do
begin
RuntimeModuleList.SourceLines[I] := Code.GetSourceLineNumber(I);
RuntimeModuleList.ModuleIndexes[I] := Code.GetModuleNumber(I);
end;
for I:=0 to Modules.Count - 1 do
begin
MR := RuntimeModuleList.Modules.AddRecord;
with MR do
begin
ModuleName := Modules[I].Name;
P1 := Modules[I].P1;
P2 := Modules[I].P2;
P3 := Modules[I].P3;
Code.CreateExecLines(MR);
UsedModules.Clear;
for J:=P1 to P2 do
begin
if Code[J].Op = OP_BEGIN_USING then
begin
Id := Code[J].Arg1;
if Id > 0 then
begin
UsedName := Code.GetSymbolRec(Id).Name;
if StrEql(ExtractName(UsedName), ExtractName(ModuleName)) then
continue;
if StrEql(UsedName, strPascalNamespace) then
continue;
if StrEql(UsedName, strBasicNamespace) then
continue;
Index := -1;
for K := 0 to UsedModules.Count - 1 do
if StrEql(UsedModules[K], UsedName) then
begin
Index := K;
break;
end;
if Index = -1 then
UsedModules.Add(UsedName);
end;
end;
end;
end;
end;
end;
procedure TKernel.AllocateConstants(const PData: Pointer);
var
I, J, Shift: Integer;
RI: TSymbolRec;
P: Pointer;
I64: Int64;
UI64: UInt64;
VCardinal: Cardinal;
ByteSet: TByteSet;
SetSize, VT, TypeID: Integer;
SS: String;
GUID: TGUID;
{$IFDEF PAXARM}
WS: String;
{$ELSE}
S: AnsiString;
WS: WideString;
{$ENDIF}
begin
I := 0;
while I < SymbolTable.Card do
begin
Inc(I);
if not SymbolTable.InCode[I] then
continue;
RI := SymbolTable[I];
if RI = SymbolTable.SR0 then
continue;
if RI.Shift = 0 then
continue;
case RI.Kind of
KindCONST:
case RI.FinalTypeID of
typeDOUBLE:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Double(P^) := Double(RI.Value);
end;
typeSINGLE:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Single(P^) := Single(RI.Value);
end;
typeEXTENDED:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Extended(P^) := Extended(RI.Value);
end;
typeCURRENCY:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Currency(P^) := Currency(RI.Value);
end;
{$IFDEF VARIANTS}
typeINT64:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
I64 := RI.Value;
Int64(P^) := I64;
end;
typeUINT64:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
UI64 := RI.Value;
UInt64(P^) := UI64;
end;
{$ELSE}
typeINT64, typeUINT64:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
I64 := Integer(RI.Value);
Int64(P^) := I64;
end;
{$ENDIF}
typeINTEGER, typeCLASS:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Integer(P^) := Integer(RI.Value);
end;
typeSHORTINT:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
ShortInt(P^) := Integer(RI.Value);
end;
typeSMALLINT:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
SmallInt(P^) := Integer(RI.Value);
end;
typeWORD:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
VCardinal := RI.Value;
Word(P^) := VCardinal;
end;
typeWIDECHAR:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
VCardinal := RI.Value;
Word(P^) := VCardinal;
end;
typeBOOLEAN:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Boolean(P^) := RI.Value;
end;
typeBYTEBOOL:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
{$IFDEF FPC}
if RI.Value <> 0 then
ByteBool(P^) := true
else
ByteBool(P^) := false;
{$ELSE}
ByteBool(P^) := RI.Value;
{$ENDIF}
end;
typeWORDBOOL:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
WordBool(P^) := RI.Value;
end;
typeLONGBOOL:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
LongBool(P^) := RI.Value;
end;
typeBYTE, typeENUM:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
VCardinal := RI.Value;
Byte(P^) := VCardinal;
end;
{$IFNDEF PAXARM}
typeANSICHAR:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
VCardinal := RI.Value;
Byte(P^) := VCardinal;
end;
{$ENDIF}
typeCARDINAL:
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
VCardinal := RI.Value;
Cardinal(P^) := VCardinal;
end;
typeVARIANT:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Variant(P^) := RI.Value;
end;
typeOLEVARIANT:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
OleVariant(P^) := RI.Value;
end;
typeSET:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
ByteSet := RI.ValueAsByteSet;
SetSize := SymbolTable.GetSizeOfSetType(RI.TerminalTypeId);
Move(ByteSet, P^, SetSize);
end;
typeCLASSREF:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
IntPax(P^) := IntPax(RI.Value);
end;
typeRECORD:
if RI.TerminalTypeId = H_TGUID then
begin
VT := VarType(RI.Value);
if (VT = varString) or (VT = varUString) then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
SS := RI.Value;
GUID := StringToGuid(SS);
Move(GUID, P^, SizeOf(TGUID));
end;
end;
typePOINTER:
begin
TypeID := RI.TypeId;
if SymbolTable[TypeId].PatternId = typeWIDECHAR then
begin
WS := RI.Value;
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
P := ShiftPointer(P, 4);
Integer(P^) := Length(WS);
P := ShiftPointer(P, 4);
if WS = '' then
Word(P^) := 0
else
begin
for J := SLow(WS) to SHigh(WS) do
begin
Move(WS[J], P^, SizeOf(WideChar));
Inc(IntPax(P), 2);
end;
Word(P^) := 0;
end;
end
{$IFNDEF PAXARM}
else if SymbolTable[TypeId].PatternId = typeANSICHAR then
begin
S := AnsiString(RI.Value);
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift + 4);
Integer(P^) := -1;
P := ShiftPointer(P, 4);
Integer(P^) := Length(S);
P := ShiftPointer(P, 4);
if S = '' then
Byte(P^) := 0
else
Move(Pointer(S)^, P^, Length(S) + 1);
end
{$ENDIF}
else
if RI.MustBeAllocated then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
VCardinal := RI.Value;
Cardinal(P^) := VCardinal;
end;
end;
end;
KindVAR:
if (RI.IsStatic) and (not IsEmpty(RI.Value)) then
case RI.FinalTypeID of
typeBOOLEAN, typeBYTE:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Byte(P^) := Integer(RI.Value);
end;
{$IFNDEF PAXARM}
typeANSICHAR:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Byte(P^) := Integer(RI.Value);
end;
{$ENDIF}
typeINTEGER:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Integer(P^) := Integer(RI.Value);
end;
typeDOUBLE:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Double(P^) := Double(RI.Value);
end;
typeSINGLE:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Single(P^) := Single(RI.Value);
end;
typeEXTENDED:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Extended(P^) := Extended(RI.Value);
end;
typeCURRENCY:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Currency(P^) := Currency(RI.Value);
end;
{$IFDEF VARIANTS}
typeINT64:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
I64 := RI.Value;
Int64(P^) := I64;
end;
typeUINT64:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
UI64 := RI.Value;
UInt64(P^) := UI64;
end;
{$ELSE}
typeINT64, typeUINT64:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
I64 := Integer(RI.Value);
Int64(P^) := I64;
end;
{$ENDIF}
typeSET:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
ByteSet := RI.ValueAsByteSet;
SetSize := SymbolTable.GetSizeOfSetType(RI.TerminalTypeId);
Move(ByteSet, P^, SetSize);
end;
typeCLASSREF:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
IntPax(P^) := IntPax(RI.Value);
end;
typeVARIANT:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Variant(P^) := Variant(RI.Value);
end;
typeOLEVARIANT:
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
OleVariant(P^) := Variant(RI.Value);
end;
typeRECORD:
if RI.TerminalTypeId = H_TGUID then
begin
VT := VarType(RI.Value);
if (VT = varString) or (VT = varUString) then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
SS := RI.Value;
GUID := StringToGuid(SS);
Move(GUID, P^, SizeOf(TGUID));
end;
end;
end;
KindSUB:
if not RI.Host then
begin
Shift := GetOffset(RI);
P := ShiftPointer(PData, Shift);
Integer(P^) := RI.Value;
end;
end; // case
end;
end;
function TKernel.GetRunnerClass: TBaseRunnerClass;
begin
if prog = nil then
result := DefaultRunnerClass
else
result := TBaseRunnerClass(prog.ClassType)
end;
function TKernel.GetDestructorAddress: Pointer;
begin
if prog = nil then
result := nil
else
result := prog.GetDestructorAddress;
end;
{$ifdef DRTTI}
procedure TKernel.RegisterImportUnit(Level: Integer; const AUnitName: String);
var
u: TUnit;
procedure P(t: TRTTIType);
var
S: String;
begin
S := ExtractUnitName(t);
if StrEql(S, AUnitName) then
if u.UsedTypes.IndexOf(t) = -1 then
begin
if not CheckType(t) then
Exit;
u.UsedTypes.Add(t);
end;
end;
var
t: TRTTIType;
begin
u := ImportUnitList.AddUnit(AUnitName, Level);
for t in PaxContext.GetTypes do
P(t);
end;
{$endif}
function TKernel.GetRootSearchPathList: TStringList;
begin
result := RootKernel.fSearchPathList;
end;
function TKernel.FindFullPath(const FileName: String): String;
var
I: Integer;
S: String;
begin
result := FileName;
if SysUtils.FileExists(result) then
Exit;
for I := 0 to RootSearchPathList.Count - 1 do
begin
S := RootSearchPathList[I];
if S[Length(S)] <> '\' then
S := S + '\';
S := S + FileName;
if SysUtils.FileExists(S) then
begin
result := S;
Exit;
end;
end;
end;
procedure TKernel.SetupDefaultSettings;
begin
fTargetPlatform := tpNONE;
{$IFDEF MACOS}
fTargetPlatform := tpOSX32;
{$ENDIF}
{$IFDEF LINUX}
fTargetPlatform := tpLINUX32;
{$ENDIF}
{$IFDEF IOS}
fTargetPlatform := tpiOSSim;
{$ENDIF}
{$IFDEF CPUARM}
{$IFDEF ANDROID}
fTargetPlatform := tpANDROID;
{$ELSE}
fTargetPlatform := tpiOSDev;
{$ENDIF}
{$ENDIF}
{$IFDEF MSWINDOWS}
{$IFDEF PAX64}
fPAX64 := true;
fTargetPlatform := tpWIN64;
{$ELSE}
fTargetPlatform := tpWIN32;
{$ENDIF}
{$ENDIF}
{$IFDEF UNIC}
IsUNIC := true;
{$ELSE}
IsUNIC := false;
{$ENDIF}
ModeSEH := fTargetPlatform = tpWIN32;
end;
function TKernel.GetRunnerKind: TRunnerKind;
begin
if prog = nil then
result := rkNONE
else if StrEql(prog.ClassName, 'TProgram') then
result := rkPROGRAM
else
result := rkINTERPRETER;
end;
function TKernel.GetTargetPlatform: TTargetPlatform;
begin
result := fTargetPlatform;
end;
procedure TKernel.SetTargetPlatform(value: TTargetPlatform);
begin
fTargetPlatform := value;
PAX64 := (value = tpWin64);
end;
function TKernel.GetSupportedSEH: Boolean;
begin
result := (TargetPlatform = tpWIN32) or (RunnerKind = rkINTERPRETER);
end;
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2011 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
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/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox 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. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_SHA2;
// Note to the curious:
// These options settings will soon be migrated to an include file.
// Why are they here? A few units in the project are sensitive to some
// compiler options such as range-check and overflow-check. Normally this
// isnt an issue because units should be compiled into a run-time library
// with options as provided. However, a few users are employing the units
// holistically (not in a library), and in thier applications settings using
// incompatible project options. By explicity setting compiler options here
// and in other sensitive units, we can ensure that the units are compiled
// with options as designed, irrespective of how the developer-user incorporates
// the units (holistic or library).
// Delphi 7 Options
{$A8,B-,C-,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
{$MINSTACKSIZE $00004000}
{$MAXSTACKSIZE $00100000}
{$IMAGEBASE $00400000}
{$APPTYPE GUI}
{$WARN SYMBOL_DEPRECATED ON}
{$WARN SYMBOL_LIBRARY ON}
{$WARN SYMBOL_PLATFORM ON}
{$WARN UNIT_LIBRARY ON}
{$WARN UNIT_PLATFORM ON}
{$WARN UNIT_DEPRECATED ON}
{$WARN HRESULT_COMPAT ON}
{$WARN HIDING_MEMBER ON}
{$WARN HIDDEN_VIRTUAL ON}
{$WARN GARBAGE ON}
{$WARN BOUNDS_ERROR ON}
{$WARN ZERO_NIL_COMPAT ON}
{$WARN STRING_CONST_TRUNCED ON}
{$WARN FOR_LOOP_VAR_VARPAR ON}
{$WARN TYPED_CONST_VARPAR ON}
{$WARN ASG_TO_TYPED_CONST ON}
{$WARN CASE_LABEL_RANGE ON}
{$WARN FOR_VARIABLE ON}
{$WARN CONSTRUCTING_ABSTRACT ON}
{$WARN COMPARISON_FALSE ON}
{$WARN COMPARISON_TRUE ON}
{$WARN COMPARING_SIGNED_UNSIGNED ON}
{$WARN COMBINING_SIGNED_UNSIGNED ON}
{$WARN UNSUPPORTED_CONSTRUCT ON}
{$WARN FILE_OPEN ON}
{$WARN FILE_OPEN_UNITSRC ON}
{$WARN BAD_GLOBAL_SYMBOL ON}
{$WARN DUPLICATE_CTOR_DTOR ON}
{$WARN INVALID_DIRECTIVE ON}
{$WARN PACKAGE_NO_LINK ON}
{$WARN PACKAGED_THREADVAR ON}
{$WARN IMPLICIT_IMPORT ON}
{$WARN HPPEMIT_IGNORED ON}
{$WARN NO_RETVAL ON}
{$WARN USE_BEFORE_DEF ON}
{$WARN FOR_LOOP_VAR_UNDEF ON}
{$WARN UNIT_NAME_MISMATCH ON}
{$WARN NO_CFG_FILE_FOUND ON}
{$WARN MESSAGE_DIRECTIVE ON}
{$WARN IMPLICIT_VARIANTS ON}
{$WARN UNICODE_TO_LOCALE ON}
{$WARN LOCALE_TO_UNICODE ON}
{$WARN IMAGEBASE_MULTIPLE ON}
{$WARN SUSPICIOUS_TYPECAST ON}
{$WARN PRIVATE_PROPACCESSOR ON}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_CAST OFF}
// End Delphi 7 Options
// Delphi 2005 Options
{$IF CompilerVersion >= 17.00}
{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
{$MINSTACKSIZE $00004000}
{$MAXSTACKSIZE $00100000}
{$IMAGEBASE $00400000}
{$APPTYPE GUI}
{$WARN SYMBOL_DEPRECATED ON}
{$WARN SYMBOL_LIBRARY ON}
{$WARN SYMBOL_PLATFORM ON}
{$WARN SYMBOL_EXPERIMENTAL ON}
{$WARN UNIT_LIBRARY ON}
{$WARN UNIT_PLATFORM ON}
{$WARN UNIT_DEPRECATED ON}
{$WARN UNIT_EXPERIMENTAL ON}
{$WARN HRESULT_COMPAT ON}
{$WARN HIDING_MEMBER ON}
{$WARN HIDDEN_VIRTUAL ON}
{$WARN GARBAGE ON}
{$WARN BOUNDS_ERROR ON}
{$WARN ZERO_NIL_COMPAT ON}
{$WARN STRING_CONST_TRUNCED ON}
{$WARN FOR_LOOP_VAR_VARPAR ON}
{$WARN TYPED_CONST_VARPAR ON}
{$WARN ASG_TO_TYPED_CONST ON}
{$WARN CASE_LABEL_RANGE ON}
{$WARN FOR_VARIABLE ON}
{$WARN CONSTRUCTING_ABSTRACT ON}
{$WARN COMPARISON_FALSE ON}
{$WARN COMPARISON_TRUE ON}
{$WARN COMPARING_SIGNED_UNSIGNED ON}
{$WARN COMBINING_SIGNED_UNSIGNED ON}
{$WARN UNSUPPORTED_CONSTRUCT ON}
{$WARN FILE_OPEN ON}
{$WARN FILE_OPEN_UNITSRC ON}
{$WARN BAD_GLOBAL_SYMBOL ON}
{$WARN DUPLICATE_CTOR_DTOR ON}
{$WARN INVALID_DIRECTIVE ON}
{$WARN PACKAGE_NO_LINK ON}
{$WARN PACKAGED_THREADVAR ON}
{$WARN IMPLICIT_IMPORT ON}
{$WARN HPPEMIT_IGNORED ON}
{$WARN NO_RETVAL ON}
{$WARN USE_BEFORE_DEF ON}
{$WARN FOR_LOOP_VAR_UNDEF ON}
{$WARN UNIT_NAME_MISMATCH ON}
{$WARN NO_CFG_FILE_FOUND ON}
{$WARN MESSAGE_DIRECTIVE ON}
{$WARN IMPLICIT_VARIANTS ON}
{$WARN UNICODE_TO_LOCALE ON}
{$WARN LOCALE_TO_UNICODE ON}
{$WARN IMAGEBASE_MULTIPLE ON}
{$WARN SUSPICIOUS_TYPECAST ON}
{$WARN PRIVATE_PROPACCESSOR ON}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_CAST OFF}
{$WARN OPTION_TRUNCATED ON}
{$WARN WIDECHAR_REDUCED ON}
{$WARN DUPLICATES_IGNORED ON}
{$ENDIF}
// End Delphi 2005 Options
// Delphi 2007 Options
{$IF CompilerVersion >= 18.50}
{$A8,B-,C-,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
{$MINSTACKSIZE $00004000}
{$MAXSTACKSIZE $00100000}
{$IMAGEBASE $00400000}
{$APPTYPE GUI}
{$WARN SYMBOL_DEPRECATED ON}
{$WARN SYMBOL_LIBRARY ON}
{$WARN SYMBOL_PLATFORM ON}
{$WARN SYMBOL_EXPERIMENTAL ON}
{$WARN UNIT_LIBRARY ON}
{$WARN UNIT_PLATFORM ON}
{$WARN UNIT_DEPRECATED ON}
{$WARN UNIT_EXPERIMENTAL ON}
{$WARN HRESULT_COMPAT ON}
{$WARN HIDING_MEMBER ON}
{$WARN HIDDEN_VIRTUAL ON}
{$WARN GARBAGE ON}
{$WARN BOUNDS_ERROR ON}
{$WARN ZERO_NIL_COMPAT ON}
{$WARN STRING_CONST_TRUNCED ON}
{$WARN FOR_LOOP_VAR_VARPAR ON}
{$WARN TYPED_CONST_VARPAR ON}
{$WARN ASG_TO_TYPED_CONST ON}
{$WARN CASE_LABEL_RANGE ON}
{$WARN FOR_VARIABLE ON}
{$WARN CONSTRUCTING_ABSTRACT ON}
{$WARN COMPARISON_FALSE ON}
{$WARN COMPARISON_TRUE ON}
{$WARN COMPARING_SIGNED_UNSIGNED ON}
{$WARN COMBINING_SIGNED_UNSIGNED ON}
{$WARN UNSUPPORTED_CONSTRUCT ON}
{$WARN FILE_OPEN ON}
{$WARN FILE_OPEN_UNITSRC ON}
{$WARN BAD_GLOBAL_SYMBOL ON}
{$WARN DUPLICATE_CTOR_DTOR ON}
{$WARN INVALID_DIRECTIVE ON}
{$WARN PACKAGE_NO_LINK ON}
{$WARN PACKAGED_THREADVAR ON}
{$WARN IMPLICIT_IMPORT ON}
{$WARN HPPEMIT_IGNORED ON}
{$WARN NO_RETVAL ON}
{$WARN USE_BEFORE_DEF ON}
{$WARN FOR_LOOP_VAR_UNDEF ON}
{$WARN UNIT_NAME_MISMATCH ON}
{$WARN NO_CFG_FILE_FOUND ON}
{$WARN IMPLICIT_VARIANTS ON}
{$WARN UNICODE_TO_LOCALE ON}
{$WARN LOCALE_TO_UNICODE ON}
{$WARN IMAGEBASE_MULTIPLE ON}
{$WARN SUSPICIOUS_TYPECAST ON}
{$WARN PRIVATE_PROPACCESSOR ON}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_CAST OFF}
{$WARN OPTION_TRUNCATED ON}
{$WARN WIDECHAR_REDUCED ON}
{$WARN DUPLICATES_IGNORED ON}
{$WARN UNIT_INIT_SEQ ON}
{$WARN LOCAL_PINVOKE ON}
{$WARN MESSAGE_DIRECTIVE ON}
{$WARN TYPEINFO_IMPLICITLY_ADDED ON}
{$WARN XML_WHITESPACE_NOT_ALLOWED ON}
{$WARN XML_UNKNOWN_ENTITY ON}
{$WARN XML_INVALID_NAME_START ON}
{$WARN XML_INVALID_NAME ON}
{$WARN XML_EXPECTED_CHARACTER ON}
{$WARN XML_CREF_NO_RESOLVE ON}
{$WARN XML_NO_PARM ON}
{$WARN XML_NO_MATCHING_PARM ON}
{$ENDIF}
// End Delphi 2007 Options
// Delphi 2010 Options
{$IF CompilerVersion >= 21.00}
{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N-,O-,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
{$MINSTACKSIZE $00004000}
{$MAXSTACKSIZE $00100000}
{$IMAGEBASE $00400000}
{$APPTYPE GUI}
{$WARN SYMBOL_DEPRECATED ON}
{$WARN SYMBOL_LIBRARY ON}
{$WARN SYMBOL_PLATFORM ON}
{$WARN SYMBOL_EXPERIMENTAL ON}
{$WARN UNIT_LIBRARY ON}
{$WARN UNIT_PLATFORM ON}
{$WARN UNIT_DEPRECATED ON}
{$WARN UNIT_EXPERIMENTAL ON}
{$WARN HRESULT_COMPAT ON}
{$WARN HIDING_MEMBER ON}
{$WARN HIDDEN_VIRTUAL ON}
{$WARN GARBAGE ON}
{$WARN BOUNDS_ERROR ON}
{$WARN ZERO_NIL_COMPAT ON}
{$WARN STRING_CONST_TRUNCED ON}
{$WARN FOR_LOOP_VAR_VARPAR ON}
{$WARN TYPED_CONST_VARPAR ON}
{$WARN ASG_TO_TYPED_CONST ON}
{$WARN CASE_LABEL_RANGE ON}
{$WARN FOR_VARIABLE ON}
{$WARN CONSTRUCTING_ABSTRACT ON}
{$WARN COMPARISON_FALSE ON}
{$WARN COMPARISON_TRUE ON}
{$WARN COMPARING_SIGNED_UNSIGNED ON}
{$WARN COMBINING_SIGNED_UNSIGNED ON}
{$WARN UNSUPPORTED_CONSTRUCT ON}
{$WARN FILE_OPEN ON}
{$WARN FILE_OPEN_UNITSRC ON}
{$WARN BAD_GLOBAL_SYMBOL ON}
{$WARN DUPLICATE_CTOR_DTOR ON}
{$WARN INVALID_DIRECTIVE ON}
{$WARN PACKAGE_NO_LINK ON}
{$WARN PACKAGED_THREADVAR ON}
{$WARN IMPLICIT_IMPORT ON}
{$WARN HPPEMIT_IGNORED ON}
{$WARN NO_RETVAL ON}
{$WARN USE_BEFORE_DEF ON}
{$WARN FOR_LOOP_VAR_UNDEF ON}
{$WARN UNIT_NAME_MISMATCH ON}
{$WARN NO_CFG_FILE_FOUND ON}
{$WARN IMPLICIT_VARIANTS ON}
{$WARN UNICODE_TO_LOCALE ON}
{$WARN LOCALE_TO_UNICODE ON}
{$WARN IMAGEBASE_MULTIPLE ON}
{$WARN SUSPICIOUS_TYPECAST ON}
{$WARN PRIVATE_PROPACCESSOR ON}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_CAST OFF}
{$WARN OPTION_TRUNCATED ON}
{$WARN WIDECHAR_REDUCED ON}
{$WARN DUPLICATES_IGNORED ON}
{$WARN UNIT_INIT_SEQ ON}
{$WARN LOCAL_PINVOKE ON}
{$WARN MESSAGE_DIRECTIVE ON}
{$WARN TYPEINFO_IMPLICITLY_ADDED ON}
{$WARN RLINK_WARNING ON}
{$WARN IMPLICIT_STRING_CAST ON}
{$WARN IMPLICIT_STRING_CAST_LOSS ON}
{$WARN EXPLICIT_STRING_CAST OFF}
{$WARN EXPLICIT_STRING_CAST_LOSS OFF}
{$WARN CVT_WCHAR_TO_ACHAR ON}
{$WARN CVT_NARROWING_STRING_LOST ON}
{$WARN CVT_ACHAR_TO_WCHAR OFF}
{$WARN CVT_WIDENING_STRING_LOST OFF}
{$WARN XML_WHITESPACE_NOT_ALLOWED ON}
{$WARN XML_UNKNOWN_ENTITY ON}
{$WARN XML_INVALID_NAME_START ON}
{$WARN XML_INVALID_NAME ON}
{$WARN XML_EXPECTED_CHARACTER ON}
{$WARN XML_CREF_NO_RESOLVE ON}
{$WARN XML_NO_PARM ON}
{$WARN XML_NO_MATCHING_PARM ON}
{$ENDIF}
// End Delphi 2010 Options
interface
uses classes, uTPLb_HashDsc, uTPLb_StreamCipher, uTPLb_Decorators;
type
TSHA2FamilyMember = (SHA_224, SHA_256, SHA_348, SHA_512, SHA_512_224, SHA_512_256);
{$IF compilerversion >= 21} [DesignDescription(
'SHA-2 is a family of hashes designed to supersede SHA-1. As of the date ' +
'of this writing, there are no discovered collisions for any SHA-2 member.'
)] {$ENDIF}
TSHA2 = class( TInterfacedObject,
IHashDsc, ICryptoGraphicAlgorithm, IControlObject)
private
FAlgorithm: TSHA2FamilyMember;
function DisplayName: string;
function ProgId: string;
function Features: TAlgorithmicFeatureSet;
function DigestSize: integer; // in units of bits. Must be a multiple of 8.
function UpdateSize: integer; // Size that the input to the Update must be.
function MakeHasher( const Params: IInterface): IHasher;
function DefinitionURL: string;
function WikipediaReference: string;
function ControlObject: TObject;
public
constructor Create( Algorithm1: TSHA2FamilyMember);
end;
implementation
uses SysUtils, uTPLb_BinaryUtils, uTPLb_StreamUtils, uTPLb_PointerArithmetic,
uTPLb_IntegerUtils, uTPLB_Constants, uTPLb_I18n, uTPLb_StrUtils;
type
TaToh = (a, b, c, d, e, f, g, h);
TSHA256_M_Array = array[0..15] of uint32;
TSHA512_M_Array = array[0..15] of uint64;
TSHA256_W_Array = array[0..63] of uint32;
TSHA512_W_Array = array[0..79] of uint64;
TaToh_Array32 = array[ TaToh ] of uint32;
TaToh_Array64 = array[ TaToh ] of uint64;
TSHA2_BaseHasher = class( TInterfacedObject, IHasher)
private
constructor Create( Algorithm1: TSHA2FamilyMember);
protected
FAlgorithm: TSHA2FamilyMember;
FCount: uint64;
FisEnding: boolean;
protected
procedure InitHashVectors; virtual; abstract;
procedure Update( Source{in}: TMemoryStream); virtual; abstract;
procedure End_Hash( PartBlock{in}: TMemoryStream; Digest: TStream); virtual; abstract;
procedure Burn; virtual; abstract;
function SelfTest_Source: TBytes; virtual; abstract;
function SelfTest_ReferenceHashValue: TBytes; virtual; abstract;
end;
TSHA256 = class( TSHA2_BaseHasher)
protected
FH: TaToh_Array32;
procedure InitHashVectors; override;
procedure Update( Source{in}: TMemoryStream); override;
procedure End_Hash( PartBlock{in}: TMemoryStream; Digest: TStream); override;
procedure Burn; override;
function SelfTest_Source: TBytes; override;
function SelfTest_ReferenceHashValue: TBytes; override;
end;
TSHA224 = class( TSHA256)
protected
procedure InitHashVectors; override;
function SelfTest_Source: TBytes; override;
function SelfTest_ReferenceHashValue: TBytes; override;
end;
TSHA512 = class( TSHA2_BaseHasher)
protected
FH: TaToh_Array64;
procedure InitHashVectors; override;
procedure Update( Source{in}: TMemoryStream); override;
procedure End_Hash( PartBlock{in}: TMemoryStream; Digest: TStream); override;
procedure Burn; override;
function SelfTest_Source: TBytes; override;
function SelfTest_ReferenceHashValue: TBytes; override;
end;
TSHA384 = class( TSHA512)
protected
procedure InitHashVectors; override;
function SelfTest_Source: TBytes; override;
function SelfTest_ReferenceHashValue: TBytes; override;
end;
TSHA512_224 = class( TSHA512)
protected
procedure InitHashVectors; override;
function SelfTest_Source: TBytes; override;
function SelfTest_ReferenceHashValue: TBytes; override;
end;
TSHA512_256 = class( TSHA512)
protected
procedure InitHashVectors; override;
function SelfTest_Source: TBytes; override;
function SelfTest_ReferenceHashValue: TBytes; override;
end;
///////////////////////////////////////
// SHA-2 Primitives
{ 4.2.2 SHA-224 and SHA-256 Constants
SHA-224 and SHA-256 use the same sequence of sixty-four constant 32-bit words,
These words represent the first thirty-two bits of the fractional parts of
the cube roots of the first sixty-four prime numbers. In hex, these constant
words are (from left to right). }
const K_Values_32: array[ 0..63 ] of uint32 = (
$428a2f98, $71374491, $b5c0fbcf, $e9b5dba5, $3956c25b, $59f111f1, $923f82a4, $ab1c5ed5,
$d807aa98, $12835b01, $243185be, $550c7dc3, $72be5d74, $80deb1fe, $9bdc06a7, $c19bf174,
$e49b69c1, $efbe4786, $0fc19dc6, $240ca1cc, $2de92c6f, $4a7484aa, $5cb0a9dc, $76f988da,
$983e5152, $a831c66d, $b00327c8, $bf597fc7, $c6e00bf3, $d5a79147, $06ca6351, $14292967,
$27b70a85, $2e1b2138, $4d2c6dfc, $53380d13, $650a7354, $766a0abb, $81c2c92e, $92722c85,
$a2bfe8a1, $a81a664b, $c24b8b70, $c76c51a3, $d192e819, $d6990624, $f40e3585, $106aa070,
$19a4c116, $1e376c08, $2748774c, $34b0bcb5, $391c0cb3, $4ed8aa4a, $5b9cca4f, $682e6ff3,
$748f82ee, $78a5636f, $84c87814, $8cc70208, $90befffa, $a4506ceb, $bef9a3f7, $c67178f2);
{ 4.2.3 SHA-384, SHA-512, SHA-512/224 and SHA-512/256 Constants
SHA-384, SHA-512, SHA-512/224 and SHA-512/256 use the same sequence of eighty
constant 64-bit words, . These words represent the first sixty-four bits of
the fractional parts of the cube roots of the first eighty prime numbers.
In hex, these constant words are (from left to right) }
{$IF compilerversion > 15}
const K_Values_64: array[ 0..79 ] of uint64 = (
$428a2f98d728ae22, $7137449123ef65cd, $b5c0fbcfec4d3b2f, $e9b5dba58189dbbc,
$3956c25bf348b538, $59f111f1b605d019, $923f82a4af194f9b, $ab1c5ed5da6d8118,
$d807aa98a3030242, $12835b0145706fbe, $243185be4ee4b28c, $550c7dc3d5ffb4e2,
$72be5d74f27b896f, $80deb1fe3b1696b1, $9bdc06a725c71235, $c19bf174cf692694,
$e49b69c19ef14ad2, $efbe4786384f25e3, $0fc19dc68b8cd5b5, $240ca1cc77ac9c65,
$2de92c6f592b0275, $4a7484aa6ea6e483, $5cb0a9dcbd41fbd4, $76f988da831153b5,
$983e5152ee66dfab, $a831c66d2db43210, $b00327c898fb213f, $bf597fc7beef0ee4,
$c6e00bf33da88fc2, $d5a79147930aa725, $06ca6351e003826f, $142929670a0e6e70,
$27b70a8546d22ffc, $2e1b21385c26c926, $4d2c6dfc5ac42aed, $53380d139d95b3df,
$650a73548baf63de, $766a0abb3c77b2a8, $81c2c92e47edaee6, $92722c851482353b,
$a2bfe8a14cf10364, $a81a664bbc423001, $c24b8b70d0f89791, $c76c51a30654be30,
$d192e819d6ef5218, $d69906245565a910, $f40e35855771202a, $106aa07032bbd1b8,
$19a4c116b8d2d0c8, $1e376c085141ab53, $2748774cdf8eeb99, $34b0bcb5e19b48a8,
$391c0cb3c5c95a63, $4ed8aa4ae3418acb, $5b9cca4f7763e373, $682e6ff3d6b2b8a3,
$748f82ee5defb2fc, $78a5636f43172f60, $84c87814a1f0ab72, $8cc702081a6439ec,
$90befffa23631e28, $a4506cebde82bde9, $bef9a3f7b2c67915, $c67178f2e372532b,
$ca273eceea26619c, $d186b8c721c0c207, $eada7dd6cde0eb1e, $f57d4f7fee6ed178,
$06f067aa72176fba, $0a637dc5a2c898a6, $113f9804bef90dae, $1b710b35131c471b,
$28db77f523047d84, $32caab7b40c72493, $3c9ebe0a15c9bebc, $431d67c49c100d4c,
$4cc5d4becb3e42b6, $597f299cfc657e2a, $5fcb6fab3ad6faec, $6c44198c4a475817);
{$ELSE} // Delphi 7
const K_Values_64: array[ 0..79 ] of uint64 = (
{<UtoS_Cnvt>}uint64( $428A2F98D728AE22){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $7137449123EF65CD){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$4A3F043013B2C4D1){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$164A245A7E762444){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $3956C25BF348B538){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $59F111F1B605D019){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$6DC07D5B50E6B065){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$54E3A12A25927EE8){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( -$27F855675CFCFDBE){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $12835B0145706FBE){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $243185BE4EE4B28C){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $550C7DC3D5FFB4E2){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $72BE5D74F27B896F){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$7F214E01C4E9694F){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$6423F958DA38EDCB){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$3E640E8B3096D96C){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( -$1B64963E610EB52E){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$1041B879C7B0DA1D){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $0FC19DC68B8CD5B5){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $240CA1CC77AC9C65){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $2DE92C6F592B0275){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $4A7484AA6EA6E483){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $5CB0A9DCBD41FBD4){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $76F988DA831153B5){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( -$67C1AEAD11992055){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$57CE3992D24BCDF0){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$4FFCD8376704DEC1){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$40A680384110F11C){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( -$391FF40CC257703E){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$2A586EB86CF558DB){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $06CA6351E003826F){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $142929670A0E6E70){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $27B70A8546D22FFC){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $2E1B21385C26C926){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $4D2C6DFC5AC42AED){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $53380D139D95B3DF){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $650A73548BAF63DE){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $766A0ABB3C77B2A8){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$7E3D36D1B812511A){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$6D8DD37AEB7DCAC5){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( -$5D40175EB30EFC9C){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$57E599B443BDCFFF){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$3DB4748F2F07686F){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$3893AE5CF9AB41D0){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( -$2E6D17E62910ADE8){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$2966F9DBAA9A56F0){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$0BF1CA7AA88EDFD6){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $106AA07032BBD1B8){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $19A4C116B8D2D0C8){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $1E376C085141AB53){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $2748774CDF8EEB99){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $34B0BCB5E19B48A8){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $391C0CB3C5C95A63){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $4ED8AA4AE3418ACB){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $5B9CCA4F7763E373){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $682E6FF3D6B2B8A3){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $748F82EE5DEFB2FC){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $78A5636F43172F60){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$7B3787EB5E0F548E){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$7338FDF7E59BC614){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( -$6F410005DC9CE1D8){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$5BAF9314217D4217){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$41065C084D3986EB){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$398E870D1C8DACD5){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( -$35D8C13115D99E64){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$2E794738DE3F3DF9){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$15258229321F14E2){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( -$0A82B08011912E88){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $06F067AA72176FBA){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $0A637DC5A2C898A6){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $113F9804BEF90DAE){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $1B710B35131C471B){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $28DB77F523047D84){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $32CAAB7B40C72493){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $3C9EBE0A15C9BEBC){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $431D67C49C100D4C){</UtoS_Cnvt>},
{<UtoS_Cnvt>}uint64( $4CC5D4BECB3E42B6){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $597F299CFC657E2A){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $5FCB6FAB3AD6FAEC){</UtoS_Cnvt>}, {<UtoS_Cnvt>}uint64( $6C44198C4A475817){</UtoS_Cnvt>});
{$ENDIF}
// FIPS PUB 180-4 | 4.1.2 | Ch() function
function Ch32( x, y, z: uint32): uint32;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// Ch(x,y,z) = (x ^ y) xor (not x ^ z)
result := (x and y) xor ((not x) and z)
end;
// FIPS PUB 180-4 | 4.1.3 | Ch() function
function Ch64( x, y, z: uint64): uint64;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// Ch(x,y,z) = (x ^ y) xor (not x ^ z)
result := (x and y) xor ((not x) and z)
end;
// FIPS PUB 180-4 | 4.1.2 | Maj() function
function Maj32( x, y, z: uint32): uint32;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// Ch(x,y,z) = (x ^ y) xor (x ^ z) xor (y ^ z)
result := (x and y) xor (x and z) xor (y and z)
end;
// FIPS PUB 180-4 | 4.1.3 | Maj() function
function Maj64( x, y, z: uint64): uint64;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// Ch(x,y,z) = (x ^ y) xor (x ^ z) xor (y ^ z)
result := (x and y) xor (x and z) xor (y and z)
end;
// FIPS PUB 180-4 | 4.2.4 | ROTR operation
function Rotr32( Shift: integer; x: uint32): uint32;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
result := (x shr Shift) or (x shl (32 - Shift))
end;
function Rotr64( Shift: integer; x: uint64): uint64;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
result := (x shr Shift) or (x shl (64 - Shift))
end;
// FIPS PUB 180-4 | 4.1.2 | SIGMA[0,256]() function
function BigSigma0_256_32( x: uint32): uint32;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// SIGMA[0,256](x) = ROTR[2](x) xor ROTR[13](x) xor ROTR[22](x)
result := Rotr32( 2, x) xor Rotr32( 13, x) xor Rotr32( 22, x)
end;
// FIPS PUB 180-4 | 4.1.2 | SIGMA[1,256]() function
function BigSigma1_256_32( x: uint32): uint32;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// SIGMA[1,256](x) = ROTR[6](x) xor ROTR[11](x) xor ROTR[25](x)
result := Rotr32( 6, x) xor Rotr32( 11, x) xor Rotr32( 25, x)
end;
// FIPS PUB 180-4 | 4.1.3 | SIGMA[0,512]() function
function BigSigma0_512_64( x: uint64): uint64;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// SIGMA[0,512](x) = ROTR[28](x) xor ROTR[34](x) xor ROTR[39](x)
result := Rotr64( 28, x) xor Rotr64( 34, x) xor Rotr64( 39, x)
end;
// FIPS PUB 180-4 | 4.1.3 | SIGMA[1,512]() function
function BigSigma1_512_64( x: uint64): uint64;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// SIGMA[1,512](x) = ROTR[14](x) xor ROTR[18](x) xor ROTR[41](x)
result := Rotr64( 14, x) xor Rotr64( 18, x) xor Rotr64( 41, x)
end;
// FIPS PUB 180-4 | 4.1.2 | sigma[0,256]() function
function LittleSigma0_256_32( x: uint32): uint32;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// sigma[0,256](x) = ROTR[7](x) xor ROTR[18](x) xor SHR[3](x)
result := Rotr32( 7, x) xor Rotr32( 18, x) xor (x shr 3)
end;
// FIPS PUB 180-4 | 4.1.2 | sigma[1,256]() function
function LittleSigma1_256_32( x: uint32): uint32;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// sigma[1,256](x) = ROTR[17](x) xor ROTR[19](x) xor SHR[10](x)
result := Rotr32( 17, x) xor Rotr32( 19, x) xor (x shr 10)
end;
// FIPS PUB 180-4 | 4.1.3 | sigma[0,512]() function
function LittleSigma0_512_64( x: uint64): uint64;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// sigma[0,512](x) = ROTR[1](x) xor ROTR[8](x) xor SHR[7](x)
result := Rotr64( 1, x) xor Rotr64( 8, x) xor (x shr 7)
end;
// FIPS PUB 180-4 | 4.1.3 | sigma[1,512]() function
function LittleSigma1_512_64( x: uint64): uint64;
{$IF CompilerVersion >= 17.0} inline; {$ENDIF}
begin
// sigma[1,512](x) = ROTR[19](x) xor ROTR[61](x) xor SHR[6](x)
result := Rotr64( 19, x) xor Rotr64( 61, x) xor (x shr 6)
end;
function SHA_StylePadding_64_in_512( MessageLengthInBits: uint64; var Pad): integer;
// The padded message will be 512 bits or 64 bytes.
// Assume Pad is at least that long.
// Return number of bytes of padding.
var
PadByte: PByte;
BigEndienLenInBits: uint64;
Excess, Zeros: integer;
begin
PadByte := @Pad;
PadByte^ := $80;
Inc( PadByte);
Excess := ((MessageLengthInBits + 7) div 8) mod 64;
Zeros := 55 - Excess;
if Zeros < 0 then
Inc( Zeros, 64);
if Zeros > 0 then
begin
FillChar( PadByte^, Zeros, $00);
Inc( PadByte, Zeros)
end;
BigEndienLenInBits := SwapEndien_u64( MessageLengthInBits);
Move( BigEndienLenInBits, PadByte^, 8);
result := Zeros + 9
end;
function SHA_StylePadding_128_in_1024(
Lo64MessageLengthInBits, Hi64MessageLengthInBits: uint64; var Pad): integer;
// The padded message will be 1024 bits or 128 bytes.
// Assume Pad is at least that long.
// Return number of bytes of padding.
var
PadByte: PByte;
BigEndienLenInBits: uint64;
Excess, Zeros: integer;
begin
PadByte := @Pad;
PadByte^ := $80;
Inc( PadByte);
Excess := ((Lo64MessageLengthInBits + 7) div 8) mod 128;
Zeros := 111 - Excess;
if Zeros < 0 then
Inc( Zeros, 128);
if Zeros > 0 then
begin
FillChar( PadByte^, Zeros, $00);
Inc( PadByte, Zeros)
end;
BigEndienLenInBits := SwapEndien_s64( Hi64MessageLengthInBits);
Move( BigEndienLenInBits, PadByte^, 8);
Inc( PadByte, 8);
BigEndienLenInBits := SwapEndien_s64( Lo64MessageLengthInBits);
Move( BigEndienLenInBits, PadByte^, 8);
result := Zeros + 17
end;
procedure SHA256_Step1(
const M: TSHA256_M_Array;
var W: TSHA256_W_Array);
var
t: integer;
Temp32: uint32;
begin
for t := 0 to 15 do
W[t] := M[t];
for t := 16 to 63 do
begin
Temp32 := LittleSigma1_256_32( W[t-2]) +
W[t-7] +
LittleSigma0_256_32( W[t-15]) +
W[t-16];
W[t] := Temp32
end
end;
procedure SHA512_Step1(
const M: TSHA512_M_Array;
var W: TSHA512_W_Array);
var
t: integer;
Temp64: uint64;
begin
for t := 0 to 15 do
W[t] := M[t];
for t := 16 to 79 do
begin
Temp64 := LittleSigma1_512_64( W[t-2]) +
W[t-7] +
LittleSigma0_512_64( W[t-15]) +
W[t-16];
W[t] := Temp64
end
end;
procedure SHA256_Step3(
var aa: TaToh_Array32;
const W: TSHA256_W_Array);
var
T1, T2: uint32;
t: integer;
begin
for t := 0 to 63 do
begin
T1 := aa[h] + BigSigma1_256_32( aa[e]) + Ch32( aa[e], aa[f], aa[g]) + K_Values_32[t] + W[t];
T2 := BigSigma0_256_32( aa[a]) + Maj32( aa[a], aa[b], aa[c]);
aa[h] := aa[g];
aa[g] := aa[f];
aa[f] := aa[e];
aa[e] := aa[d] + T1;
aa[d] := aa[c];
aa[c] := aa[b];
aa[b] := aa[a];
aa[a] := T1 + T2
end
end;
procedure SHA512_Step3(
var aa: TaToh_Array64;
const W: TSHA512_W_Array);
var
T1, T2: uint64;
t: integer;
begin
for t := 0 to 79 do
begin
T1 := aa[h] + BigSigma1_512_64( aa[e]) + Ch64( aa[e], aa[f], aa[g]) + K_Values_64[t] + W[t];
T2 := BigSigma0_512_64( aa[a]) + Maj64( aa[a], aa[b], aa[c]);
aa[h] := aa[g];
aa[g] := aa[f];
aa[f] := aa[e];
aa[e] := aa[d] + T1;
aa[d] := aa[c];
aa[c] := aa[b];
aa[b] := aa[a];
aa[a] := T1 + T2
end
end;
procedure SHA256_Step4(
var HH: TaToh_Array32;
const aa: TaToh_Array32);
var
Letter: TaToh;
begin
for Letter := a to h do
HH[ Letter] := HH[ Letter] + aa[ Letter]
end;
procedure SHA512_Step4(
var HH: TaToh_Array64;
const aa: TaToh_Array64);
var
Letter: TaToh;
begin
for Letter := a to h do
HH[ Letter] := HH[ Letter] + aa[ Letter]
end;
procedure SHA256_Step2(
var aa: TaToh_Array32;
const HH: TaToh_Array32);
var
Letter: TaToh;
begin
for Letter := a to h do
aa[ Letter] := HH[ Letter]
end;
procedure SHA512_Step2(
var aa: TaToh_Array64;
const HH: TaToh_Array64);
var
Letter: TaToh;
begin
for Letter := a to h do
aa[ Letter] := HH[ Letter]
end;
///////////////////////////////////////
// TSHA-2 Class
function TSHA2.ControlObject: TObject;
begin
result := self
end;
constructor TSHA2.Create( Algorithm1: TSHA2FamilyMember);
begin
FAlgorithm := Algorithm1
end;
function TSHA2.DefinitionURL: string;
begin
result := 'http://csrc.nist.gov/publications/drafts/' +
'fips180-4/Draft-FIPS180-4_Feb2011.pdf'
end;
const DigestSizes: array[ TSHA2FamilyMember] of integer = (
// SHA_224, SHA_256, SHA_384, SHA_512, SHA_512_224, SHA_512_256
224, 256, 384, 512, 224, 256);
function TSHA2.DigestSize: integer;
begin
result := DigestSizes[ FAlgorithm]
end;
function TSHA2.DisplayName: string;
const Names: array[ TSHA2FamilyMember] of string = (
// SHA_224, SHA_256, SHA_384, SHA_512, SHA_512_224, SHA_512_256
'224', '256', '384', '512', '512/224', '512/256');
begin
result := 'SHA-' + Names[ FAlgorithm]
end;
function TSHA2.Features: TAlgorithmicFeatureSet;
begin
result := [afOpenSourceSoftware];
if FAlgorithm in [SHA_512_224, SHA_512_256] then
Include( result, afStar)
end;
function TSHA2.MakeHasher( const Params: IInterface): IHasher;
type
TSHA2_BaseHasherClass = class of TSHA2_BaseHasher;
const
Classes: array[ TSHA2FamilyMember] of TSHA2_BaseHasherClass = (
TSHA224, TSHA256, TSHA384, TSHA512, TSHA512_224, TSHA512_256);
begin
result := Classes[ Falgorithm].Create( FAlgorithm)
end;
function TSHA2.ProgId: string;
const Names: array[ TSHA2FamilyMember] of string = (
// SHA_224, SHA_256, SHA_348, SHA_512, SHA_512_224, SHA_512_256
SHA224_ProgId, SHA256_ProgId,
SHA384_ProgId, SHA512_ProgId, SHA512_224_ProgId, SHA512_256_ProgId);
begin
result := Names[ FAlgorithm]
end;
function TSHA2.UpdateSize: integer;
const Sizes: array[ TSHA2FamilyMember] of integer = (
// SHA_224, SHA_256, SHA_384, SHA_512, SHA_512_224, SHA_512_256
512, 512, 1024, 1024, 1024, 1024);
begin
result := Sizes[ FAlgorithm]
end;
function TSHA2.WikipediaReference: string;
begin
result := {'http://en.wikipedia.org/wiki/' +} 'Sha-2'
end;
{ TSHA2_BaseHasher }
constructor TSHA2_BaseHasher.Create( Algorithm1: TSHA2FamilyMember);
begin
FAlgorithm := Algorithm1;
FCount := 0;
FisEnding := False;
InitHashVectors
end;
{ TSHA256 }
procedure TSHA256.InitHashVectors;
begin
FH[a] := $6a09e667;
FH[b] := $bb67ae85;
FH[c] := $3c6ef372;
FH[d] := $a54ff53a;
FH[e] := $510e527f;
FH[f] := $9b05688c;
FH[g] := $1f83d9ab;
FH[h] := $5be0cd19
end;
procedure TSHA256.Update( Source: TMemoryStream);
var
M: TSHA256_M_Array;
W: TSHA256_W_Array;
aa: TaToh_Array32;
t: integer;
Temp32: uint32;
begin
Assert( Source.Size = 64, 'TSHA256.Update - Wrong block size.');
if not FisEnding then
Inc( FCount, 512);
Source.Position := 0;
for t := 0 to 15 do
begin
Source.Read( Temp32, 4);
M[t] := SwapEndien_u32( Temp32)
end;
SHA256_Step1( M, W);
SHA256_Step2( aa, FH);
SHA256_Step3( aa, W);
SHA256_Step4( FH, aa)
end;
procedure TSHA256.End_Hash( PartBlock: TMemoryStream; Digest: TStream);
var
MessageLengthInBits, L: uint64;
Pad: packed array[ 0..71 ] of byte;
PaddingCountInBytes: integer;
PadOrigin, Xfer: integer;
jj: TaToh;
lwDigest: uint32;
begin
L := PartBlock.Position;
Assert( L <= 64, 'TSHA256.End_Hash - Wrong block size.');
FisEnding := True;
Inc( FCount, L * 8);
MessageLengthInBits := FCount;
PaddingCountInBytes := SHA_StylePadding_64_in_512( MessageLengthInBits, Pad);
PadOrigin := 0;
Xfer := 64 - L;
if Xfer < 0 then
Xfer := 0;
if Xfer > PaddingCountInBytes then
Xfer := PaddingCountInBytes;
if Xfer > 0 then
begin
PartBlock.Write( Pad, Xfer);
Inc( PadOrigin, Xfer);
Dec( PaddingCountInBytes, Xfer)
end;
Update( PartBlock);
Xfer := PaddingCountInBytes;
if Xfer > 0 then
begin
PartBlock.Position := 0;
PartBlock.Write( Pad[ PadOrigin], Xfer);
Assert( Xfer = 64, 'TSHA256.End_Hash - Wrong block size.');
Update( PartBlock)
end;
PartBlock.Position := L;
L := DigestSizes[ FAlgorithm] div 8; // digest size in bytes.
Digest.Position := 0;
for jj := a to h do
begin
if L <= 0 then break;
lwDigest := SwapEndien_u32( FH[jj]);
Xfer := 4;
if Xfer > L then
Xfer := L;
if Xfer <= 0 then break;
Digest.WriteBuffer( lwDigest, Xfer);
Dec( L, Xfer)
end;
Digest.Position := 0;
FillChar( FH, SizeOf( FH), 0)
end;
procedure TSHA256.Burn;
begin
FCount := 0;
FillChar( FH, SizeOf( FH), 0);
FisEnding := False
end;
function TSHA256.SelfTest_Source: TBytes;
begin
result := AnsiBytesOf('abc')
end;
function TSHA256.SelfTest_ReferenceHashValue: TBytes;
begin
result := AnsiBytesOf('BA7816BF 8F01CFEA ' +
'414140DE 5DAE2223 B00361A3 96177A9C B410FF61 F20015AD')
end;
{ TSHA224 }
procedure TSHA224.InitHashVectors;
begin
FH[a] := $c1059ed8;
FH[b] := $367cd507;
FH[c] := $3070dd17;
FH[d] := $f70e5939;
FH[e] := $ffc00b31;
FH[f] := $68581511;
FH[g] := $64f98fa7;
FH[h] := $befa4fa4
end;
function TSHA224.SelfTest_Source: TBytes;
begin
result := AnsiBytesOf('abc');
// Two block alternative:
// result := 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'
end;
function TSHA224.SelfTest_ReferenceHashValue: TBytes;
begin
result := AnsiBytesOf('23097D22 3405D822 8642A477 BDA255B3 2AADBCE4 BDA0B3F7 E36C9DA7');
// Two block alternative:
// result := '75388B16 512776CC 5DBA5DA1 FD890150 B0C6455C B4F58B19 52522525'
end;
{ TSHA512 }
procedure TSHA512.InitHashVectors;
begin
{$IF compilerversion > 15}
FH[a] := $6a09e667f3bcc908;
FH[b] := $bb67ae8584caa73b;
FH[c] := $3c6ef372fe94f82b;
FH[d] := $a54ff53a5f1d36f1;
FH[e] := $510e527fade682d1;
FH[f] := $9b05688c2b3e6c1f;
FH[g] := $1f83d9abfb41bd6b;
FH[h] := $5be0cd19137e2179
{$ELSE} // Delphi 7
FH[a] := {<UtoS_Cnvt>}uint64( $6A09E667F3BCC908){</UtoS_Cnvt>};
FH[b] := {<UtoS_Cnvt>}uint64( -$4498517A7B3558C5){</UtoS_Cnvt>};
FH[c] := {<UtoS_Cnvt>}uint64( $3C6EF372FE94F82B){</UtoS_Cnvt>};
FH[d] := {<UtoS_Cnvt>}uint64( -$5AB00AC5A0E2C90F){</UtoS_Cnvt>};
FH[e] := {<UtoS_Cnvt>}uint64( $510E527FADE682D1){</UtoS_Cnvt>};
FH[f] := {<UtoS_Cnvt>}uint64( -$64FA9773D4C193E1){</UtoS_Cnvt>};
FH[g] := {<UtoS_Cnvt>}uint64( $1F83D9ABFB41BD6B){</UtoS_Cnvt>};
FH[h] := {<UtoS_Cnvt>}uint64( $5BE0CD19137E2179){</UtoS_Cnvt>}
{$ENDIF}
end;
procedure TSHA512.Update( Source: TMemoryStream);
var
M: TSHA512_M_Array;
W: TSHA512_W_Array;
aa: TaToh_Array64;
t: integer;
Temp64: uint64;
begin
Assert( Source.Size = 128, 'TSHA512.Update - Wrong block size.');
if not FisEnding then
Inc( FCount, 1024);
Source.Position := 0;
for t := 0 to 15 do
begin
Source.Read( Temp64, 8);
M[t] := SwapEndien_u64( Temp64)
end;
SHA512_Step1( M, W);
SHA512_Step2( aa, FH);
SHA512_Step3( aa, W);
SHA512_Step4( FH, aa)
end;
procedure TSHA512.End_Hash( PartBlock: TMemoryStream; Digest: TStream);
var
Lo64MessageLengthInBits, Hi64MessageLengthInBits, L: uint64;
Pad: packed array[ 0..255 ] of byte;
PaddingCountInBytes: integer;
PadOrigin, Xfer: integer;
jj: TaToh;
lwDigest: uint64;
begin
L := PartBlock.Position;
Assert( L <= 128, 'TSHA512.End_Hash - Wrong block size.');
FisEnding := True;
Inc( FCount, L * 8);
Lo64MessageLengthInBits := FCount;
Hi64MessageLengthInBits := 0;
PaddingCountInBytes := SHA_StylePadding_128_in_1024(
Lo64MessageLengthInBits, Hi64MessageLengthInBits, Pad);
PadOrigin := 0;
Xfer := 128 - L;
if Xfer < 0 then
Xfer := 0;
if Xfer > PaddingCountInBytes then
Xfer := PaddingCountInBytes;
if Xfer > 0 then
begin
PartBlock.Write( Pad, Xfer);
Inc( PadOrigin, Xfer);
Dec( PaddingCountInBytes, Xfer)
end;
Update( PartBlock);
Xfer := PaddingCountInBytes;
if Xfer > 0 then
begin
PartBlock.Position := 0;
PartBlock.Write( Pad[ PadOrigin], Xfer);
Assert( Xfer = 128, 'TSHA512.End_Hash - Wrong block size.');
Update( PartBlock)
end;
PartBlock.Position := L;
L := DigestSizes[ FAlgorithm] div 8; // digest size in bytes.
Digest.Position := 0;
for jj := a to h do
begin
if L <= 0 then break;
lwDigest := SwapEndien_u64( FH[jj]);
Xfer := 8;
if Xfer > L then
Xfer := L;
if Xfer <= 0 then break;
Digest.WriteBuffer( lwDigest, Xfer);
Dec( L, Xfer)
end;
Digest.Position := 0;
FillChar( FH, SizeOf( FH), 0)
end;
procedure TSHA512.Burn;
begin
FCount := 0;
FillChar( FH, SizeOf( FH), 0);
FisEnding := False
end;
function TSHA512.SelfTest_Source: TBytes;
begin
result := AnsiBytesOf('abc');
end;
function TSHA512.SelfTest_ReferenceHashValue: TBytes;
begin
result := AnsiBytesOf(
'DDAF35A1 93617ABA CC417349 AE204131 ' +
'12E6FA4E 89A97EA2 0A9EEEE6 4B55D39A 2192992A 274FC1A8 ' +
'36BA3C23 A3FEEBBD 454D4423 643CE80E 2A9AC94F A54CA49F');
end;
{ TSHA348 }
procedure TSHA384.InitHashVectors;
begin
{$IF compilerversion > 15}
FH[a] := $cbbb9d5dc1059ed8;
FH[b] := $629a292a367cd507;
FH[c] := $9159015a3070dd17;
FH[d] := $152fecd8f70e5939;
FH[e] := $67332667ffc00b31;
FH[f] := $8eb44a8768581511;
FH[g] := $db0c2e0d64f98fa7;
FH[h] := $47b5481dbefa4fa4
{$ELSE} // Delphi 7
FH[a] := {<UtoS_Cnvt>}uint64( -$344462A23EFA6128){</UtoS_Cnvt>};
FH[b] := {<UtoS_Cnvt>}uint64( $629A292A367CD507){</UtoS_Cnvt>};
FH[c] := {<UtoS_Cnvt>}uint64( -$6EA6FEA5CF8F22E9){</UtoS_Cnvt>};
FH[d] := {<UtoS_Cnvt>}uint64( $152FECD8F70E5939){</UtoS_Cnvt>};
FH[e] := {<UtoS_Cnvt>}uint64( $67332667FFC00B31){</UtoS_Cnvt>};
FH[f] := {<UtoS_Cnvt>}uint64( -$714BB57897A7EAEF){</UtoS_Cnvt>};
FH[g] := {<UtoS_Cnvt>}uint64( -$24F3D1F29B067059){</UtoS_Cnvt>};
FH[h] := {<UtoS_Cnvt>}uint64( $47B5481DBEFA4FA4){</UtoS_Cnvt>}
{$ENDIF}
end;
function TSHA384.SelfTest_Source: TBytes;
begin
result := AnsiBytesOf('abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijk' +
'lmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu');
end;
function TSHA384.SelfTest_ReferenceHashValue: TBytes;
begin
result := AnsiBytesOf(
'09330C33 F71147E8 3D192FC7 82CD1B47 53111B17 3B3B05D2 ' +
'2FA08086 E3B0F712 FCC7C71A 557E2DB9 66C3E9FA 91746039');
end;
{ TSHA512_224 }
procedure TSHA512_224.InitHashVectors;
begin
{$IF compilerversion > 15}
FH[a] := $8C3D37C819544DA2;
FH[b] := $73E1996689DCD4D6;
FH[c] := $1DFAB7AE32FF9C82;
FH[d] := $679DD514582F9FCF;
FH[e] := $0F6D2B697BD44DA8;
FH[f] := $77E36F7304C48942;
FH[g] := $3F9D85A86A1D36C8;
FH[h] := $1112E6AD91D692A1
{$ELSE} // Delphi 7
FH[a] := {<UtoS_Cnvt>}uint64( -$73C2C837E6ABB25E){</UtoS_Cnvt>};
FH[b] := {<UtoS_Cnvt>}uint64( $73E1996689DCD4D6){</UtoS_Cnvt>};
FH[c] := {<UtoS_Cnvt>}uint64( $1DFAB7AE32FF9C82){</UtoS_Cnvt>};
FH[d] := {<UtoS_Cnvt>}uint64( $679DD514582F9FCF){</UtoS_Cnvt>};
FH[e] := {<UtoS_Cnvt>}uint64( $0F6D2B697BD44DA8){</UtoS_Cnvt>};
FH[f] := {<UtoS_Cnvt>}uint64( $77E36F7304C48942){</UtoS_Cnvt>};
FH[g] := {<UtoS_Cnvt>}uint64( $3F9D85A86A1D36C8){</UtoS_Cnvt>};
FH[h] := {<UtoS_Cnvt>}uint64( $1112E6AD91D692A1){</UtoS_Cnvt>}
{$ENDIF}
end;
function TSHA512_224.SelfTest_Source: TBytes;
begin
result := AnsiBytesOf('abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhi' +
'jklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu');
end;
function TSHA512_224.SelfTest_ReferenceHashValue: TBytes;
begin
result := AnsiBytesOf('23FEC5BB 94D60B23 30819264 0B0C4533 35D66473 4FE40E72 68674AF9');
end;
{ TSHA512_256 }
procedure TSHA512_256.InitHashVectors;
begin
{$IF compilerversion > 15}
FH[a] := $22312194FC2BF72C;
FH[b] := $9F555FA3C84C64C2;
FH[c] := $2393B86B6F53B151;
FH[d] := $963877195940EABD;
FH[e] := $96283EE2A88EFFE3;
FH[f] := $BE5E1E2553863992;
FH[g] := $2B0199FC2C85B8AA;
FH[h] := $0EB72DDC81C52CA2
{$ELSE} // Delphi 7
FH[a] := {<UtoS_Cnvt>}uint64( $22312194FC2BF72C){</UtoS_Cnvt>};
FH[b] := {<UtoS_Cnvt>}uint64( -$60AAA05C37B39B3E){</UtoS_Cnvt>};
FH[c] := {<UtoS_Cnvt>}uint64( $2393B86B6F53B151){</UtoS_Cnvt>};
FH[d] := {<UtoS_Cnvt>}uint64( -$69C788E6A6BF1543){</UtoS_Cnvt>};
FH[e] := {<UtoS_Cnvt>}uint64( -$69D7C11D5771001D){</UtoS_Cnvt>};
FH[f] := {<UtoS_Cnvt>}uint64( -$41A1E1DAAC79C66E){</UtoS_Cnvt>};
FH[g] := {<UtoS_Cnvt>}uint64( $2B0199FC2C85B8AA){</UtoS_Cnvt>};
FH[h] := {<UtoS_Cnvt>}uint64( $0EB72DDC81C52CA2){</UtoS_Cnvt>}
{$ENDIF}
end;
function TSHA512_256.SelfTest_Source: TBytes;
begin
result := AnsiBytesOf('abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijkl' +
'mnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu');
end;
function TSHA512_256.SelfTest_ReferenceHashValue: TBytes;
begin
result := AnsiBytesOf('3928E184 FB8690F8 40DA3988 121D31BE 65CB9D3E F83EE614 ' +
'6FEAC861 E19B563A');
end;
end.
|
{/*!
Provides exception classes for different situations.
\modified 2019-07-09 14:30pm
\author Wuping Xin
*/}
namespace TsmPluginFx.Core;
type
EDllModuleLoadingException = public class(Exception)
public
constructor(const aModuleName: not nullable String; const aError: not nullable String);
begin
inherited($"Module {aModuleName} failed to be loaded with error: {aError}.");
end;
end;
EUiScriptCompileErrorException = public class(Exception)
private
fErrors: String;
public
constructor(const aErrors: not nullable String);
begin
inherited ('UI script failed to compile with errors.');
fErrors := aErrors;
end;
property Errors: String read fErrors;
end;
EParameterItemNameNotUniqueException = public class(Exception)
public
constructor(const aItemName: not nullable String);
begin
inherited($"Parameter item name {aItemName} is not unique.");
end;
end;
EParameterItemMissingException = public class(Exception)
public
constructor(const aItemName: not nullable String);
begin
inherited($"Parameter item with name {aItemName} is missing.");
end;
end;
EInvalidParameterItemTypeException = public class(Exception)
public
constructor(const aItemName: not nullable String; const aItemType: not nullable String);
begin
inherited($"Parameter item {aItemName} has invalid type {aItemType}.");
end;
end;
end. |
unit Cargo;
interface
type
TCargo = class
private
FId: Integer;
FDescricao: string;
public
property Id: Integer read FId write FId;
property Descricao: string read FDescricao write FDescricao;
constructor Create; overload;
constructor Create(Id: Integer); overload;
constructor Create(Id: Integer; Descricao: string); overload;
end;
implementation
{ TCliente }
constructor TCargo.Create;
begin
end;
constructor TCargo.Create(Id: Integer);
begin
Self.FId := Id;
end;
constructor TCargo.Create(Id: Integer; Descricao: string);
begin
Self.FId := Id;
Self.FDescricao := Descricao;
end;
end.
|
unit mpSysCheck;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fphttpclient, mpdisk{$IFDEF Unix} ,Linux {$ENDIF},nosodebug,
nosocrypto;
Type
TThreadHashtest = class(TThread)
protected
procedure Execute; override;
public
Constructor Create(CreateSuspended : boolean);
end;
Function Sys_HashSpeed(cores:integer=4):int64;
Function AllocateMem(UpToMb:integer=1024):int64;
Function TestDownloadSpeed():int64;
var
OpenHashThreads : integer;
implementation
constructor TThreadHashtest.Create(CreateSuspended : boolean);
Begin
inherited Create(CreateSuspended);
End;
procedure TThreadHashtest.Execute;
var
counter : integer;
Begin
for counter := 1 to 10000 do
HashSha256String(IntToStr(counter));
Dec(OpenHashThreads);
End;
Function Sys_HashSpeed(cores:integer=4):int64;
var
counter : integer;
StartTime, EndTime : int64;
ThisThread : TThreadHashtest;
Begin
OpenHashThreads := cores;
for counter := 1 to cores do
begin
ThisThread := TThreadHashtest.Create(true);
ThisThread.FreeOnTerminate:=true;
ThisThread.Start;
end;
StartTime := GetTickCount64;
Repeat
sleep(1);
until OpenHashThreads=0;
EndTime := GetTickCount64;
Result := (cores*10000) div (EndTime-StartTime);
End;
Function AllocateMem(UpToMb:integer=1024):int64;
var
MemMb : array of pointer;
Finished : boolean = false;
h: TFPCHeapStatus;
i: cardinal;
LastHeapFails: boolean;
Z: Pointer;
{$IFDEF Unix} Info : TSysInfo; {$ENDIF}
Begin
result := 0;
{$IFDEF WINDOWS}
Result := 0;
LastHeapFails := ReturnNilIfGrowHeapFails;
ReturnNilIfGrowHeapFails := True;
for i := 1 to $FFFF do
begin
Z := GetMem(i * $10000);
if Z = nil then
break;
h := GetFPCHeapStatus;
Result := h.MaxHeapSize div 1048576;
Freemem(Z);
end;
ReturnNilIfGrowHeapFails := LastHeapFails;
{$ENDIF}
{$IFDEF Unix}
SysInfo(@Info);
result := Info.freeram div 1048576;
{$ENDIF}
End;
Function TestDownloadSpeed():int64;
var
MS: TMemoryStream;
DownLink : String = '';
Conector : TFPHttpClient;
Sucess : boolean = false;
timeStart, timeEnd : int64;
trys : integer = 0;
Begin
result := 0;
DownLink := 'https://raw.githubusercontent.com/Noso-Project/NosoWallet/main/1mb.dat';
MS := TMemoryStream.Create;
Conector := TFPHttpClient.Create(nil);
conector.ConnectTimeout:=1000;
conector.IOTimeout:=1000;
conector.AllowRedirect:=true;
REPEAT
timeStart := GetTickCount64;
TRY
Conector.Get(DownLink,MS);
MS.SaveToFile('NOSODATA'+DirectorySeparator+'1mb.dat');
timeEnd := GetTickCount64;
//DeleteFile('NOSODATA'+DirectorySeparator+'1mb.dat');
Sucess := true;
EXCEPT ON E:Exception do
AddLineToDebugLog('events',TimeToStr(now)+e.Message);
END{Try};
Inc(Trys);
UNTIL ( (sucess) or (trys=5) );
MS.Free;
conector.free;
if Sucess then result := 1048576 div (TimeEnd-TimeStart);
End;
END. // END UNIT
|
unit frmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IniFiles, Vcl.Mask, JvExMask,
JvToolEdit, Vcl.ComCtrls;
type
TformMain = class(TForm)
edWorkDir: TJvDirectoryEdit;
edMkvEditDir: TJvDirectoryEdit;
lblWorkDir: TLabel;
lblMkvEditPath: TLabel;
btnStart: TButton;
objStatusBar: TStatusBar;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edWorkDirChange(Sender: TObject);
procedure edMkvEditDirChange(Sender: TObject);
procedure btnStartClick(Sender: TObject);
private
{ Private declarations }
szBasePath, szWorkPath, szMkvEditPath: String;
iniSource: TIniFile;
procedure ValidateMkvEdit;
public
{ Public declarations }
end;
var
formMain: TformMain;
implementation
uses ShellAPI;
{$R *.dfm}
procedure TformMain.ValidateMkvEdit;
begin
if not FileExists(szMkvEditPath + '\mkvpropedit.exe')
then
begin
btnStart.Enabled := false;
edMkvEditDir.SetFocus();
objStatusBar.SimpleText := 'mkvpropedit.exe not found'
end
else
begin
btnStart.Enabled := true;
btnStart.SetFocus();
objStatusBar.SimpleText := 'Ready'
end;
end;
procedure TformMain.btnStartClick(Sender: TObject);
var
listFiles: TStrings;
SRec: TSearchRec;
i, iErrors: Integer;
begin
iErrors := 0;
listFiles := TStringList.Create();
try
if FindFirst(szWorkPath + '\*.mkv', faNormal, SRec) = 0 then
begin
repeat
listFiles.Add(SRec.Name);
until FindNext(SRec) <> 0;
FindClose(SRec);
end;
if listFiles.Count > 0
then
begin
for i := 0 to listFiles.Count-1 do
begin
objStatusBar.SimpleText := 'Processing ' + listFiles[i];
if ShellExecute(Handle, 'open', PChar(szMkvEditPath + '\mkvpropedit.exe'), PChar('"' + listFiles[i] + '"' + ' --edit info --set "title=' + Copy(listFiles[i], 0, LastDelimiter('.',listFiles[i]) - 1) + '"'), PChar(szWorkPath), SW_HIDE) < 33 then Inc(iErrors);
end;
objStatusBar.SimpleText := IntToStr(listFiles.Count) + ' file(s) processed - ' + IntToStr(iErrors) + ' error(s)';
end
else objStatusBar.SimpleText := 'No files found';
finally
listFiles.Free();
end;
end;
procedure TformMain.edMkvEditDirChange(Sender: TObject);
begin
szMkvEditPath := edMkvEditDir.Directory;
iniSource.WriteString('Paths', 'mkvtoolnix', szMkvEditPath);
ValidateMkvEdit();
end;
procedure TformMain.edWorkDirChange(Sender: TObject);
begin
szWorkPath := edWorkDir.Directory;
iniSource.WriteString('Paths', 'workdir', szWorkPath);
end;
procedure TformMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
iniSource.UpdateFile();
iniSource.Free();
end;
procedure TformMain.FormShow(Sender: TObject);
begin
szBasePath := ExtractFileDir(ParamStr(0));
iniSource := TIniFile.Create(szBasePath + '\mkvtitle.ini');
szWorkPath := iniSource.ReadString('Paths', 'workdir', szBasePath);
szMkvEditPath := iniSource.ReadString('Paths', 'mkvtoolnix', '');
edWorkDir.Directory := szWorkPath;
edMkvEditDir.Directory := szMkvEditPath;
ValidateMkvEdit();
end;
end.
|
{: TexCombineShader demo / mini-lab.<p>
This is an advanced demo, which showcases use and setup of extra texture
units, along with texture combination possibilities.<p>
The texture combiner allows to declare how each texture unit should
be used, and how each should be combined with the others. Basicly,
a texture combiner "code" defines how each texture should be combined,
knowing that the result of the last texture unit (the one with the higher
index) defines the final output.<br>
Note that if the code allows you to declare the combiners in any order,
the hardware will evaluate them in their index order, and will only accept
one combiner assignement for each texture unit.
}
unit Unit1;
interface
uses
SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, GLScene, GLTexture, GLObjects, StdCtrls, ExtCtrls,
GLLCLViewer, GLTexCombineShader, GLHUDObjects, GLMaterial,
GLCoordinates, GLCrossPlatform, GLBaseClasses;
type
TForm1 = class(TForm)
GLScene: TGLScene;
SceneViewer: TGLSceneViewer;
Image1: TImage;
Image2: TImage;
BUApply: TButton;
GLCamera: TGLCamera;
GLDummyCube: TGLDummyCube;
GLMaterialLibrary: TGLMaterialLibrary;
Image3: TImage;
Label1: TLabel;
Image4: TImage;
GLTexCombineShader: TGLTexCombineShader;
GLHUDSprite: TGLHUDSprite;
PATex1: TPanel;
PATex2: TPanel;
PATex3: TPanel;
CBTex0: TCheckBox;
CBTex1: TCheckBox;
CBTex2: TCheckBox;
CBTex3: TCheckBox;
Label3: TLabel;
Label4: TLabel;
Panel1: TPanel;
MECombiner: TMemo;
Label2: TLabel;
ColorDialog: TColorDialog;
PAPrimary: TPanel;
procedure FormCreate(Sender: TObject);
procedure BUApplyClick(Sender: TObject);
procedure SceneViewerPostRender(Sender: TObject);
procedure CBTex0Click(Sender: TObject);
procedure PAPrimaryClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses GLUtils;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
with GLMaterialLibrary.Materials do
begin
Image1.Picture.LoadFromFile('beigemarble.jpg');
Items[0].Material.Texture.Image.Assign(Image1.Picture);
Image2.Picture.LoadFromFile('Flare1.bmp');
Items[1].Material.Texture.Image.Assign(Image2.Picture);
Image3.Picture.LoadFromFile('clover.jpg');
Items[2].Material.Texture.Image.Assign(Image3.Picture);
Image4.Picture.LoadFromFile('cm_front.jpg');
Items[3].Material.Texture.Image.Assign(Image4.Picture);
end;
GLTexCombineShader.Combiners.Assign(MECombiner.Lines);
Application.HintHidePause := 30000;
end;
procedure TForm1.BUApplyClick(Sender: TObject);
begin
// Apply new combiner code
// Depending on shader and hardware, errors may be triggered during render
GLTexCombineShader.Combiners.Assign(MECombiner.Lines);
end;
procedure TForm1.SceneViewerPostRender(Sender: TObject);
var
n: integer;
begin
// disable whatever texture units are not supported by the local hardware
n := SceneViewer.Buffer.LimitOf[limNbTextureUnits];
PATex1.Visible := (n < 2);
CBTex1.Enabled := (n >= 2);
PATex2.Visible := (n < 3);
CBTex2.Enabled := (n >= 3);
PATex3.Visible := (n < 4);
CBTex3.Enabled := (n >= 4);
CBTex1.Checked := CBTex1.Checked and CBTex1.Enabled;
end;
procedure TForm1.CBTex0Click(Sender: TObject);
var
libMat: TGLLibMaterial;
begin
// This event is used for all 4 checkboxes of the 4 texture units
libMat := GLMaterialLibrary.Materials.GetLibMaterialByName(
(Sender as TCheckBox).Caption);
if Assigned(libMat) then
libMat.Material.Texture.Enabled := TCheckBox(Sender).Checked;
end;
procedure TForm1.PAPrimaryClick(Sender: TObject);
begin
// Allow choosing the primary color
ColorDialog.Color := PAPrimary.Color;
if ColorDialog.Execute then
begin
PAPrimary.Color := ColorDialog.Color;
with GLMaterialLibrary.Materials[0].Material.FrontProperties do
Diffuse.AsWinColor := ColorDialog.Color;
SceneViewer.Invalidate;
end;
end;
end.
|
unit Chapter09._09_Solution3;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Math,
DeepStar.UString,
DeepStar.Utils;
/// LCS问题
/// 动态规划, 躲避边界条件
/// 时间复杂度: O(len(s1)*len(s2))
/// 空间复杂度: O(len(s1)*len(s2))
type
TSolution = class(TObject)
public
function GetLCS(const s1, s2: UString): UString;
end;
procedure Main;
implementation
procedure Main;
var
s1, s2: UString;
begin
s1 := 'ABCD';
s2 := 'AEBD';
with TSolution.Create do
begin
WriteLn(GetLCS(s1, s2));
Free;
end;
end;
{ TSolution }
function TSolution.GetLCS(const s1, s2: UString): UString;
var
m, n, j, i: integer;
memo: TArr2D_int;
res: UString;
begin
m := Length(s1);
n := Length(s2);
// memo 是 (m + 1) * (n + 1) 的动态规划表格
// memo[i][j] 表示s1的前i个字符和s2前j个字符的最长公共子序列的长度
// 其中memo[0][j] 表示s1取空字符串时, 和s2的前j个字符作比较
// memo[i][0] 表示s2取空字符串时, 和s1的前i个字符作比较
// 所以, memo[0][j] 和 memo[i][0] 均取0
// 我们不需要对memo进行单独的边界条件处理 :-)
SetLength(memo, m + 1, n + 1);
// 动态规划的过程
// 注意, 由于动态规划状态的转变, 下面的i和j可以取到m和n
for i := 1 to m do
for j := 1 to n do
if s1.Chars[i - 1] = s2.Chars[j - 1] then
memo[i, j] := 1 + memo[i - 1, j - 1]
else
memo[i, j] := Max(memo[i - 1, j], memo[i, j - 1]);
// 通过memo反向求解s1和s2的最长公共子序列
res := '';
while (m > 0) and (n > 0) do
begin
if s1.Chars[m - 1] = s2.Chars[n - 1] then
begin
res := s1.Chars[m - 1] + res;
m -= 1;
n -= 1;
end
else if memo[m - 1, n] > memo[m, n - 1] then
m -= 1
else
n -= 1;
end;
Result := res;
end;
end.
|
unit URepositorioDeposito;
interface
uses
UEmpresaMatriz,
UDeposito,
URepositorioEmpresaMatriz,
UEntidade,
URepositorioDB,
SqlExpr
;
type
TRepositorioDeposito = class (TrepositorioDB<TDEPOSITO>)
private
FRepositorioEmpresa : TRepositorioEmpresa;
public
constructor create;
destructor Destroy; Override;
procedure AtribuiDBParaEntidade (const coDeposito : TDEPOSITO); override;
procedure AtribuiEntidadeParaDB (const coDeposito : TDEPOSITO;
const coSQLQuery : TSQLQuery); override;
end;
implementation
uses
UDM,
SysUtils
;
{ TRepositórioFilail }
procedure TRepositorioDeposito.AtribuiDBParaEntidade(const coDeposito: TDEPOSITO);
begin
inherited;
with FSQLSelect do
begin
coDeposito.DESCRICAO := FieldByName(FLD_DEPOSITO_DESCRICAO).AsString;
coDeposito.FEMPRESA := TEmpresa (
FRepositorioEmpresa.Retorna( FieldByName( FLD_DEPOSITO_EMPRESA_ID).AsInteger));
end;
end;
procedure TRepositorioDeposito.AtribuiEntidadeParaDB(const coDeposito: TDEPOSITO;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_DEPOSITO_DESCRICAO).AsString := coDeposito.DESCRICAO;
ParambyName(FLD_DEPOSITO_EMPRESA_ID).AsInteger := coDeposito.FEMPRESA.ID;
end;
end;
constructor TRepositorioDeposito.create;
begin
inherited Create (TDEPOSITO, TBL_DEPOSITO, FLD_ENTIDADE_ID, STR_DEPOSITO);
FRepositorioEmpresa := TRepositorioEmpresa.Create;
end;
destructor TRepositorioDeposito.Destroy;
begin
FreeAndNil(FRepositorioEmpresa);
inherited;
end;
end.
|
unit DAW.ViewADB;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.Edit,
FMX.Controls.Presentation,
FMX.StdCtrls,
FMX.Layouts,
FMX.ScrollBox,
FMX.Memo;
type
TViewAdbDialog = class(TForm)
lytAdbExe: TLayout;
lblAdbExe: TLabel;
edtAdbExe: TEdit;
lytDeviceIp: TLayout;
lblDeviceIp: TLabel;
edtDeviceIp: TEdit;
grpLog: TGroupBox;
mmoLog: TMemo;
btnConnect: TEditButton;
btnBrowse: TEditButton;
lytExec: TLayout;
lblExec: TLabel;
edtExec: TEdit;
btnExec: TEditButton;
procedure btnConnectClick(Sender: TObject);
procedure btnBrowseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnExecClick(Sender: TObject);
private
{ Private declarations }
FDir: string;
public
{ Public declarations }
procedure Log(const AData: string);
class function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;
function SetupDir: Boolean;
procedure CheckResult(const Msg: string);
procedure ADBExecute(const ACmd: string);
end;
var
ViewAdbDialog: TViewAdbDialog;
implementation
uses
DAW.Tools,
Winapi.Windows;
{$R *.fmx}
{ TViewAdbDialog }
procedure TViewAdbDialog.ADBExecute(const ACmd: string);
begin
CheckResult(GetDosOutput(ACmd, FDir));
end;
procedure TViewAdbDialog.btnBrowseClick(Sender: TObject);
var
OD: TOpenDialog;
begin
OD := TOpenDialog.Create(nil);
try
OD.DefaultExt := 'adb.exe';
if OD.Execute then
edtAdbExe.Text := OD.FileName;
SetupDir;
finally
OD.Free;
end;
end;
procedure TViewAdbDialog.btnConnectClick(Sender: TObject);
begin
if SetupDir then
begin
CheckResult(GetDosOutput('adb kill-server', FDir));
CheckResult(GetDosOutput('adb tcpip 5555', FDir));
CheckResult(GetDosOutput('adb connect ' + edtDeviceIp.Text, FDir));
end;
end;
procedure TViewAdbDialog.btnExecClick(Sender: TObject);
begin
ADBExecute(edtExec.Text);
end;
procedure TViewAdbDialog.CheckResult(const Msg: string);
begin
if Msg.Contains('adb: usage: adb connect <host>[:<port>]') then
begin
Log('Unsupperted format IP. Check settings');
end
else if Msg.Contains('error: no devices/emulators found') then
begin
end
else
Log(Msg);
end;
procedure TViewAdbDialog.FormCreate(Sender: TObject);
begin
edtAdbExe.Text := TDawTools.AdbExe;
end;
class function TViewAdbDialog.GetDosOutput(CommandLine, Work: string): string;
var
SA: TSecurityAttributes;
SI: TStartupInfo;
PI: TProcessInformation;
StdOutPipeRead, StdOutPipeWrite: THandle;
WasOK: Boolean;
Buffer: array [0 .. 255] of AnsiChar;
BytesRead: Cardinal;
WorkDir: string;
Handle: Boolean;
begin
Result := '';
with SA do
begin
nLength := SizeOf(SA);
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
try
with SI do
begin
FillChar(SI, SizeOf(SI), 0);
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE;
hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
hStdOutput := StdOutPipeWrite;
hStdError := StdOutPipeWrite;
end;
WorkDir := Work;
Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine), nil, nil, True, 0, nil,
PChar(WorkDir), SI, PI);
CloseHandle(StdOutPipeWrite);
if Handle then
try
repeat
WasOK := ReadFile(StdOutPipeRead, Buffer, 255, BytesRead, nil);
if BytesRead > 0 then
begin
Buffer[BytesRead] := #0;
Result := Result + Buffer;
end;
until not WasOK or (BytesRead = 0);
WaitForSingleObject(PI.hProcess, INFINITE);
finally
CloseHandle(PI.hThread);
CloseHandle(PI.hProcess);
end;
finally
CloseHandle(StdOutPipeRead);
end;
end;
procedure TViewAdbDialog.Log(const AData: string);
begin
mmoLog.Lines.Add(AData);
end;
function TViewAdbDialog.SetupDir: Boolean;
begin
FDir := ExtractFilePath(edtAdbExe.Text);
if (DirectoryExists(FDir) and FileExists(edtAdbExe.Text)) then
begin
Result := True;
end
else
begin
Log('bad path, adb not found');
Result := False;
end;
end;
end.
|
unit ClueGui;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.AppAnalytics, System.Actions, Vcl.ActnList, System.ImageList, Vcl.ImgList,
Vcl.Menus, Vcl.AppEvnts, Vcl.Mask, Vcl.ComCtrls, System.Win.TaskbarCore,
Vcl.Taskbar, ShlObj, imageconvertor, cluetypes;
type
TClueForm = class(TForm)
buttonPanel: TPanel;
Btn_Close: TButton;
Btn_Update: TButton;
mainPanel: TPanel;
basefolderLabel: TLabel;
cluefolderLabel: TLabel;
patternLabel: TLabel;
patternEdit: TEdit;
startatlabel: TLabel;
startatEdit: TEdit;
domainLabel: TLabel;
georefLabel: TLabel;
cluefolderEdit: TButtonedEdit;
arrowImages: TImageList;
cluefolderListMenu: TPopupMenu;
mainEvents: TApplicationEvents;
processedFolderListMenu: TPopupMenu;
basefolderEdit: TButtonedEdit;
ilwisDomainBEdit: TButtonedEdit;
domainsMenu: TPopupMenu;
georefsMenu: TPopupMenu;
ilwisGeorefBEdit: TButtonedEdit;
styleChooser: TComboBox;
progressConvertMove: TProgressBar;
progressLabel: TLabel;
exploreButton: TButton;
historyCombobox: TComboBox;
recentLabel: TLabel;
overwriteCheckbox: TCheckBox;
aboutButton: TButton;
procedure Btn_CloseClick(Sender: TObject);
procedure Btn_UpdateClick(Sender: TObject);
procedure buttonPanelResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure mainEventsActivate(Sender: TObject);
procedure changeStyleClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure exploreButtonClick(Sender: TObject);
procedure startatEditExit(Sender: TObject);
procedure patternEditExit(Sender: TObject);
procedure aboutButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormActivate(Sender: TObject);
private
TaskBarNative: ITaskBarList3;
_ic : TImageConvertor;
procedure HandleThreadResult(var Message: TUMWorkerDone); message UM_WORKERDONE;
procedure HandleThreadProgress(var Message: TUMWorkerProgress); message UM_WORKERPROGRESS;
procedure saveConfig;
procedure populateFromConfig;
procedure clueFolderMenuClick(Sender: TObject);
procedure processedFolderMenuClick(Sender: TObject);
procedure updateFolderEdit(edit : TObject; folder : string);
procedure domainsMenuClick(Sender: TObject);
procedure georefsMenuClick(Sender: TObject);
public
{ Public declarations }
end;
var
ClueForm: TClueForm;
implementation
{$R *.dfm}
uses
Registry, ShellApi, ComObj,
themes, styles, system.types, ioutils,
CluesConfig, about, TlHelp32;
function ProcessCount(const ExeName: String): Integer;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
FSnapshotHandle:= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize:= SizeOf(FProcessEntry32);
ContinueLoop:= Process32First(FSnapshotHandle, FProcessEntry32);
Result:= 0;
while Integer(ContinueLoop) <> 0 do begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
UpperCase(ExeName)) or (UpperCase(FProcessEntry32.szExeFile) =
UpperCase(ExeName))) then Inc(Result);
ContinueLoop:= Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
procedure TClueForm.aboutButtonClick(Sender: TObject);
var
about : TaboutForm;
begin
about := TaboutForm.Create(self);
about.Show;
end;
procedure TClueForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
saveConfig;
end;
procedure TClueForm.Btn_CloseClick(Sender: TObject);
begin
Close;
end;
procedure TClueForm.Btn_UpdateClick(Sender: TObject);
begin
saveConfig;
Btn_Close.Enabled := false;
progressConvertMove.Visible := true;
// start thread
_ic := TImageConvertor.Create(self.Handle);
end;
procedure TClueForm.changeStyleClick(Sender: TObject);
begin
if styleChooser.ItemIndex >= 0 then begin
TStyleManager.TrySetStyle(styleChooser.Items[styleChooser.ItemIndex]);
end;
end;
procedure TClueForm.buttonPanelResize(Sender: TObject);
begin
Btn_Close.Width := buttonPanel.Width div 2;
Btn_Update.Width := buttonPanel.Width div 2;
end;
procedure TClueForm.FormResize(Sender: TObject);
begin
// prepare size of progressbar on top of move button
progressConvertMove.Left := Btn_Update.Left + 2;
progressConvertMove.Width := Btn_Update.Width - 4;
progressConvertMove.Top := Btn_Update.Top + 2;
progressConvertMove.Height := Btn_Update.Height - 4;
// Now adjust the progress label
progressLabel.Top := 0;
progressLabel.Left := 0;
progressLabel.Width := progressConvertMove.ClientWidth;
progressLabel.Height := progressConvertMove.ClientHeight;
end;
procedure TClueForm.FormCreate(Sender: TObject);
var
configname : string;
styles : TArray<String>;
i : integer;
szpos : string;
parts : TStringList;
clueHandle : THandle;
begin
// theme related stuff
styles := TStylemanager.StyleNames;
for i := 0 to length(styles) - 1 do
styleChooser.AddItem(styles[i], nil);
styleChooser.ItemIndex := 2; // 'Emerald Light Slate'
TStyleManager.TrySetStyle(styleChooser.Items[2]);
TaskBarNative := CreateComObject(CLSID_TaskbarList) as ITaskBarList3;
TaskBarNative.SetProgressState(Handle, ord(TTaskBarProgressState.Normal));
// setup of progress bar
progressLabel.Parent := progressConvertMove;
progressLabel.AutoSize := false;
progressLabel.Transparent := true;
progressLabel.Top := 0;
progressLabel.Left := 0;
progressLabel.Width := progressConvertMove.ClientWidth;
progressLabel.Height := progressConvertMove.ClientHeight;
progressLabel.Alignment := taCenter;
progressLabel.Layout := tlCenter;
// Actual application stuff
configname := extractFilePath(Application.ExeName) + 'clues.config';
config := TCluesConfig.Create(configname);
parts := TStringList.Create;
parts.Delimiter := ',';
szpos := config.item['WindowPosition'];
if Length(szpos) > 0 then
begin
parts.CommaText := szpos;
if parts.Count = 2 then begin
self.Top := StrToIntDef(parts[0], self.Top);
self.Left := StrToIntDef(parts[1], self.Left);
end;
end;
szpos := config.item['WindowSize'];
if Length(szpos) > 0 then
begin
parts.CommaText := szpos;
if parts.Count = 2 then begin
self.Width := StrToIntDef(parts[0], self.Width);
self.Height := StrToIntDef(parts[1], self.Height);
end;
end;
parts.Free;
populateFromConfig;
historyCombobox.Items.Clear;
for i := config.history.Count - 1 downto 0 do
historyCombobox.Items.Add(config.history[i]); // add in reverse order
historyCombobox.ItemIndex := 0;
if ProcessCount('clues.exe') > 0 then
begin
clueHandle := FindWindow(nil, 'Dyna-CLUE');
if clueHandle > 0 then
SetForegroundWindow(clueHandle);
end
else
if FileExists(ExpandFileName(clueFolderEdit.Text) + '\clues.exe') then
ShellExecute(Handle, 'open', PChar(ExpandFileName(clueFolderEdit.Text) + '\clues.exe'), nil, PChar(ExpandFileName(clueFolderEdit.Text)), SW_SHOWNORMAL) ;
end;
procedure TClueForm.FormActivate(Sender: TObject);
begin
// check if everything is visible
if aboutButton.Left < (overwriteCheckbox.Left + overwriteCheckbox.Width) then
self.Width := self.Width + (overwriteCheckbox.Left + overwriteCheckbox.Width) - aboutButton.Left + 10; // 10 small margin
if (historyCombobox.Top + historyCombobox.Height) > buttonPanel.Top then
self.Height := self.Height + (historyCombobox.Top + historyCombobox.Height) - buttonPanel.Top + 10; // 10 small margin
end;
// repopulate the folder lists and the files lists to account for external changes
procedure TClueForm.mainEventsActivate(Sender: TObject);
procedure addMenuItem(where : TPopupMenu; fname : string; eventHandler : TNotifyEvent);
var
item : TMenuItem;
begin
item := TMenuItem.Create(where);
item.Caption := extractFileName(fname);
item.OnClick := eventHandler;
item.SubMenuImages := arrowImages;
item.ImageIndex := 1;
where.Items.Add(item);
end;
var
i : integer;
path : string;
folders : TStringDynArray;
files : TStringDynArray;
begin
folders := TDirectory.getDirectories(extractFilePath(Application.ExeName));
clueFolderListMenu.Items.Clear;
processedFolderListMenu.Items.Clear;
for i := 0 to length(folders) - 1 do begin
addMenuItem(cluefolderListMenu, ExtractFileName(folders[i]), clueFolderMenuClick);
addMenuItem(processedFolderListMenu, ExtractFileName(folders[i]), ProcessedFolderMenuClick);
end;
addMenuItem(processedFolderListMenu, '<new>', ProcessedFolderMenuClick);
path := ExpandFileName(cluefolderEdit.Text);
// get ilwis domain files
domainsMenu.Items.Clear;
ilwisDomainBEdit.Color := clWebAliceBlue;
if DirectoryExists(path) then begin
files := TDirectory.GetFiles(path, '*.dom');
for i := 0 to length(files) - 1 do
addMenuItem(domainsMenu, extractFileName(files[i]), domainsMenuClick);
ilwisDomainBEdit.Enabled := (length(files) > 0);
if length(files) > 0 then
ilwisDomainBEdit.Color := clWindow;
end;
// get ilwis georef files
georefsMenu.Items.Clear;
ilwisGeorefBEdit.Color := clWebAliceBlue;
if DirectoryExists(path) then begin
files := TDirectory.GetFiles(path, '*.grf');
for i := 0 to length(files) - 1 do
addMenuItem(georefsMenu, extractFileName(files[i]), georefsMenuClick);
ilwisGeorefBEdit.Enabled := (length(files) > 0);
if length(files) > 0 then
ilwisGeorefBEdit.Color := clWindow;
end;
end;
procedure TClueForm.clueFolderMenuClick(Sender: TObject);
var
folder : string;
begin
if not (Sender is TMenuItem) then
exit;
folder := (Sender as TMenuItem).Caption;
updateFolderEdit(clueFolderEdit, folder);
mainEventsActivate(cluefolderEdit);
end;
procedure TClueForm.processedFolderMenuClick(Sender: TObject);
var
folder : string;
begin
if not (Sender is TMenuItem) then
exit;
folder := (Sender as TMenuItem).Caption;
updateFolderEdit(baseFolderEdit, folder);
end;
procedure TClueForm.domainsMenuClick(Sender: TObject);
var
diskitem : string;
begin
if not (Sender is TMenuItem) then
exit;
diskitem := (Sender as TMenuItem).Caption;
updateFolderEdit(ilwisDomainBEdit, diskitem);
end;
procedure TClueForm.exploreButtonClick(Sender: TObject);
begin
if historyCombobox.ItemIndex >= 0 then
ShellExecute(Handle, 'open', PChar(historyCombobox.Items[historyCombobox.ItemIndex]), nil, nil, SW_SHOWNORMAL);
end;
procedure TClueForm.georefsMenuClick(Sender: TObject);
var
diskitem : string;
begin
if not (Sender is TMenuItem) then
exit;
diskitem := (Sender as TMenuItem).Caption;
updateFolderEdit(ilwisGeorefBEdit, diskitem);
end;
procedure TClueForm.HandleThreadProgress(var Message: TUMWorkerProgress);
var
progress : integer;
begin
progressConvertMove.Max := Message.total;
progressConvertMove.Position := Message.progress;
progress := Message.progress * 100 div Message.total;
progressLabel.Caption := Format('%d %%', [progress]);
TaskBarNative.SetProgressValue(Handle, Message.progress, Message.total);
end;
procedure TClueForm.HandleThreadResult(var Message: TUMWorkerDone);
begin
progressConvertMove.Visible := false;
TaskBarNative.SetProgressValue(Handle, 0, 100);
historyCombobox.Items.Insert(0, ExpandFileName(config.getScenarioFolder));
historyCombobox.ItemIndex := 0;
exploreButton.Enabled := historyCombobox.Items.Count > 0;
Btn_Close.Enabled := true;
Btn_Close.SetFocus;
// update config
config.nextFolder;
populateFromConfig;
if Message.Result = 2 then ShowMessage('Files successfully moved and converted');
if Message.Result = 1 then ShowMessage('Error moving and converting files');
if Message.Result = 10 then ShowMessage('Could not create folder in destination');
if Message.Result = 20 then ShowMessage('Missing files in source folder; did you run the simulation?');
end;
procedure TClueForm.updateFolderEdit(edit : TObject; folder : string);
var
item : TButtonedEdit;
newfolder : string;
begin
if not (edit is TButtonedEdit) then
exit;
item := edit as TButtonedEdit;
if folder = '<new>' then begin
if Length(item.Text) > 0 then
newfolder := ExpandFileName(item.Text);
if not DirectoryExists(newfolder) then begin
if CreateDir(newfolder) then begin
folder := ExtractFileName(newfolder);
mainEventsActivate(self); // add the new folder to the menus
end;
end;
end;
item.Text := folder;
end;
procedure TClueForm.saveConfig;
begin
// save conversion configuration
config.item['CluesOutputFolder'] := cluefolderEdit.Text;
config.item['BaseDestinationFolder'] := basefolderEdit.Text;
config.item['SubfolderPattern'] := patternEdit.Text;
config.item['IlwisGeoref'] := ilwisGeorefBEdit.Text;
config.item['IlwisDomain'] := ilwisDomainBEdit.Text;
if overwriteCheckbox.Checked then
config.item['OverwriteFolder'] := 'True'
else
config.item['OverwriteFolder'] := 'False';
// save gui stuff
config.item['WindowPosition'] := Format('%d,%d', [self.Top, self.Left]);
config.item['WindowSize'] := Format('%d,%d', [self.Width, self.Height]);
if styleChooser.ItemIndex >= 0 then
config.item['Theme'] := styleChooser.Items[styleChooser.ItemIndex]
else
config.item['Theme'] := styleChooser.Items[2];
end;
procedure TClueForm.startatEditExit(Sender: TObject);
var
num :integer;
begin
if length(startatEdit.Text) > 0 then begin
num := StrToIntDef(startatEdit.Text, -1);
if num > 0 then
config.startNum := num
else
ShowMessage('Please enter a valid number');
end;
end;
procedure TClueForm.patternEditExit(Sender: TObject);
var
i : integer;
begin
if length(basefolderEdit.Text) > 0 then
config.item['BaseDestinationFolder'] := basefolderEdit.Text;
if length(patternEdit.Text) > 0 then
begin
config.pattern := patternEdit.Text;
historyCombobox.Items.Clear;
for i := config.history.Count - 1 downto 0 do
historyCombobox.Items.Add(config.history[i]); // add in reverse order
historyCombobox.ItemIndex := 0;
startatEdit.Text := config.getStartNumAsString;
end;
end;
procedure TClueForm.populateFromConfig;
var
i, index : integer;
item : string;
begin
item := config.item['CluesOutputFolder'];
if (length(item) > 0) and DirectoryExists(item) then
begin
cluefolderEdit.Text := item;
end;
item := config.item['BaseDestinationFolder'];
if (length(item) > 0) and DirectoryExists(item) then basefolderEdit.Text := item;
item := config.item['SubfolderPattern'];
if length(item) > 0 then patternEdit.Text := item;
if config.startNum > 0 then
startatEdit.Text := config.getStartNumAsString;
item := config.item['IlwisGeoref'];
if (length(item) > 0) and (length(config.sourceFolder) > 0) then
if FileExists(ExpandFileName(config.sourceFolder + '\' + item)) then
ilwisGeorefBEdit.Text := item;
item := config.item['IlwisDomain'];
if (length(item) > 0) and (length(config.sourceFolder) > 0) then
if FileExists(ExpandFileName(config.sourceFolder + '\' + item)) then
ilwisDomainBEdit.Text := item;
item := config.item['OverwriteFolder'];
if length(item) > 0 then overwriteCheckbox.Checked := item = 'True';
item := config.item['Theme'];
index := styleChooser.Items.IndexOf(item);
if index >= 0 then
styleChooser.ItemIndex := index
else
styleChooser.ItemIndex := 2; // fallback
changeStyleClick(self);
end;
end.
|
unit uExecuteFileTransfer;
interface
uses
Classes, uTransferFile, SysUtils;
type
TExecuteFileTransfer = class(TThread)
private
FRemoteWorkingDir: String;
FLocalWorkingDir: String;
FFileList: TStringList;
FIDCashReg: Integer;
FOnServerStatus: TOnServerStatus;
FRunning: Boolean;
FOnFinish: TOnFinish;
procedure DoOnServerStatus(Online : Boolean);
protected
procedure Execute; override;
public
property RemoteWorkingDir: String read FRemoteWorkingDir write FRemoteWorkingDir;
property LocalWorkingDir: String read FLocalWorkingDir write FLocalWorkingDir;
property FileList: TStringList read FFileList write FFileList;
property IDCashReg: Integer read FIDCashReg write FIDCashReg;
property Running: Boolean read FRunning write FRunning;
property OnServerStatus: TOnServerStatus read FOnServerStatus write FOnServerStatus;
property OnFinish: TOnFinish read FOnFinish write FOnFinish;
constructor Create(CreateSuspended: Boolean);
destructor Destroy; override;
end;
implementation
uses uFileFunctions;
{ TExecuteFileTransfer }
constructor TExecuteFileTransfer.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
FFileList := TStringList.Create;
end;
destructor TExecuteFileTransfer.Destroy;
begin
FFileList.Free;
inherited Destroy;
end;
procedure TExecuteFileTransfer.DoOnServerStatus(Online: Boolean);
begin
if Assigned(FOnServerStatus) then
OnServerStatus(Online);
end;
procedure TExecuteFileTransfer.Execute;
var
i : Integer;
sArquivoLocal,
sArquivoRemoto: String;
lstTmp: TStringList;
begin
FRunning := True;
try
for i := 0 to FFileList.Count-1 do
if FFileList[i] <> '' then
begin
try
sArquivoLocal := FLocalWorkingDir + FFileList[i];
sArquivoRemoto := FRemoteWorkingDir + IntToStr(FIDCashReg) + '\' + FFileList[i];
if not DirectoryExists(ExtractFilePath(sArquivoRemoto)) then
ForceDirectories(ExtractFilePath(sArquivoRemoto));
lstTmp := TStringList.Create;
try
LoadFileNoLock(lstTmp, sArquivoLocal);
if FileExists(sArquivoRemoto) then
DeleteFile(PChar(sArquivoRemoto));
lstTmp.SaveToFile(sArquivoRemoto);
finally
lstTmp.Free;
end;
DoOnServerStatus(True);
except
DoOnServerStatus(False);
end;
end
finally
FRunning := False;
if Assigned(FOnFinish) then
OnFinish;
end;
end;
end.
|
unit MSCryptoAPI;
// Description: Sarah Dean's MS CryptoAPI
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// This file contains a Delphi port of *part* of the MS CryptoAPI
//
// It is *not* a full port, and only contains a very *limited* subset of
// definitions
interface
uses
Windows; // Required for various definitions (e.g. BOOL, LPCSTR)
const
ADVAPI = 'advapi32.dll';
const
{
From WinCrypt.h (MS Platform SDK)
}
// dwFlags definitions for CryptAcquireContext
CRYPT_VERIFYCONTEXT = $F0000000;
CRYPT_NEWKEYSET = $00000008;
CRYPT_DELETEKEYSET = $00000010;
CRYPT_MACHINE_KEYSET = $00000020;
CRYPT_SILENT = $00000040;
{
From WinCrypt.h (MS Platform SDK)
CryptSetProvParam section
}
PP_CLIENT_HWND = 1;
PP_CONTEXT_INFO = 11;
PP_KEYEXCHANGE_KEYSIZE = 12;
PP_SIGNATURE_KEYSIZE = 13;
PP_KEYEXCHANGE_ALG = 14;
PP_SIGNATURE_ALG = 15;
PP_DELETEKEY = 24;
PROV_RSA_FULL = 1;
PROV_RSA_SIG = 2;
PROV_DSS = 3;
PROV_FORTEZZA = 4;
PROV_MS_EXCHANGE = 5;
PROV_SSL = 6;
PROV_RSA_SCHANNEL = 12;
PROV_DSS_DH = 13;
PROV_EC_ECDSA_SIG = 14;
PROV_EC_ECNRA_SIG = 15;
PROV_EC_ECDSA_FULL = 16;
PROV_EC_ECNRA_FULL = 17;
PROV_DH_SCHANNEL = 18;
PROV_SPYRUS_LYNKS = 20;
PROV_RNG = 21;
PROV_INTEL_SEC = 22;
PROV_REPLACE_OWF = 23;
PROV_RSA_AES = 24;
{
From WinCrypt.h (MS Platform SDK)
Provider friendly names section
}
MS_DEF_PROV = 'Microsoft Base Cryptographic Provider v1.0';
MS_ENHANCED_PROV = 'Microsoft Enhanced Cryptographic Provider v1.0';
MS_STRONG_PROV = 'Microsoft Strong Cryptographic Provider';
MS_DEF_RSA_SIG_PROV = 'Microsoft RSA Signature Cryptographic Provider';
MS_DEF_RSA_SCHANNEL_PROV = 'Microsoft RSA SChannel Cryptographic Provider';
MS_DEF_DSS_PROV = 'Microsoft Base DSS Cryptographic Provider';
MS_DEF_DSS_DH_PROV = 'Microsoft Base DSS and Diffie-Hellman Cryptographic Provider';
MS_ENH_DSS_DH_PROV = 'Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider';
MS_DEF_DH_SCHANNEL_PROV = 'Microsoft DH SChannel Cryptographic Provider';
MS_SCARD_PROV = 'Microsoft Base Smart Card Crypto Provider';
MS_ENH_RSA_AES_PROV = 'Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)';
type
{
From WinCrypt.h (MS Platform SDK):
typedef ULONG_PTR HCRYPTPROV;
}
ULONG_PTR = ^ULONG;
HCRYPTPROV = ULONG_PTR;
PHCRYPTPROV = ^HCRYPTPROV;
{
From WinCrypt.h (MS Platform SDK):
WINADVAPI
BOOL
WINAPI
CryptAcquireContextA(
HCRYPTPROV *phProv,
LPCSTR szContainer,
LPCSTR szProvider,
DWORD dwProvType,
DWORD dwFlags
);
WINADVAPI
BOOL
WINAPI
CryptAcquireContextW(
HCRYPTPROV *phProv,
LPCWSTR szContainer,
LPCWSTR szProvider,
DWORD dwProvType,
DWORD dwFlags
);
#ifdef UNICODE
#define CryptAcquireContext CryptAcquireContextW
#else
#define CryptAcquireContext CryptAcquireContextA
#endif // !UNICODE
}
{$WARNINGS OFF} // Useless warning about platform - this is the *published* API!
function CryptAcquireContext(phProv: PHCRYPTPROV; szContainer: LPCSTR; szProvider: LPCSTR; dwProvType: DWORD; dwFlags: DWORD): BOOL;
stdcall; external ADVAPI name 'CryptAcquireContextA';
function CryptAcquireContextA(phProv: PHCRYPTPROV; szContainer: LPCSTR; szProvider: LPCSTR; dwProvType: DWORD; dwFlags: DWORD): BOOL;
stdcall; external ADVAPI name 'CryptAcquireContextA';
function CryptAcquireContextW(phProv: PHCRYPTPROV; szContainer: LPCWSTR; szProvider: LPCWSTR; dwProvType: DWORD; dwFlags: DWORD): BOOL;
stdcall; external ADVAPI name 'CryptAcquireContextW';
{$WARNINGS ON}
{
From WinCrypt.h (MS Platform SDK):
WINADVAPI
BOOL
WINAPI
CryptReleaseContext(
HCRYPTPROV hProv,
DWORD dwFlags
);
}
function CryptReleaseContext(hProv: HCRYPTPROV; dwFlags: DWORD): BOOL;
stdcall; external ADVAPI name 'CryptReleaseContext';
{
From WinCrypt.h (MS Platform SDK):
WINADVAPI
BOOL
WINAPI
CryptGenRandom(
HCRYPTPROV hProv,
DWORD dwLen,
BYTE *pbBuffer
);
}
function CryptGenRandom(hProv: HCRYPTPROV; dwLen: DWORD; pbBuffer: PByte): BOOL;
stdcall; external ADVAPI name 'CryptGenRandom';
implementation
END.
|
unit Myloo.Patterns.Singleton;
interface
uses
Winapi.Windows,
System.Classes,
System.Generics.Defaults,
System.Generics.Collections,
System.Rtti,
System.TypInfo,
System.RTLConsts,
System.SysUtils;
type
TSingleton<T: class, constructor> = class
strict private
class var FInstance : T;
public
class function GetInstance(): T;
class procedure ReleaseInstance();
end;
implementation
{ TSingleton }
class function TSingleton<T>.GetInstance: T;
begin
if not Assigned(Self.FInstance) then
Self.FInstance := T.Create();
Result := Self.FInstance;
end;
class procedure TSingleton<T>.ReleaseInstance;
begin
if Assigned(Self.FInstance) then
Self.FInstance.Free;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit uShaders;
interface
uses
FMX.Types3D, MV.Utils, IOUtils;
type
TPixelMode = (pmNoTexture, pmDiffuse, pmNormal, pmSpecular, pmAmbient, pmEffects, pmComposition);
const
TPixelModeNames: array [TPixelMode] of String =
('notexture','diffuse', 'normal', 'specular', 'ambient', 'effects', 'composition' );
type
TPixelModeList = array [TPixelMode] of TContextShader;
TShaders = class
private
FContext: TContext3D;
FPixelMode: TPixelModeList;
FVertexMode: TContextShader;
public
property PixelMode: TPixelModeList read FPixelMode;
property VertexMode: TContextShader read FVertexMode;
constructor Create(const AContext: TContext3D);
destructor Destroy; override;
end;
implementation
constructor TShaders.Create(const AContext: TContext3D);
var
LMode: TPixelMode;
LFileName: String;
// LFileBytes: pointer;
begin
FContext := AContext;
// load shaders
for LMode := Low(TPixelMode) to High(TPixelMode) do
begin
LFileName := SHADERS_PATH + TPixelModeNames[LMode] + '.ps.fxo';
// LFileBytes := TFile.ReadAllBytes(LFileName);
FPixelMode[LMode] := AContext.CreatePixelShader(TFile.ReadAllBytes(LFileName), nil, nil)
end;
FVertexMode := AContext.CreateVertexShader(
TFile.ReadAllBytes(SHADERS_PATH + 'composition.vs.fxo'), nil);
end;
destructor TShaders.Destroy;
var
LMode: TPixelMode;
begin
for LMode := Low(TPixelMode) to High(TPixelMode) do
FContext.DestroyPixelShader(FPixelMode[LMode]);
FContext.DestroyVertexShader(FVertexMode);
end;
end.
|
unit tal_uwindowlog;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, trl_ilog, Forms, StdCtrls, Controls;
type
{ TWindowLog }
TWindowLog = class(TInterfacedObject, ILog)
private
fLogForm: TCustomForm;
fLogMemo: TMemo;
fLevel: string;
procedure IncLevel;
procedure DecLevel;
procedure NewLogForm;
procedure OnLogFormCloseQuery(Sender : TObject; var CanClose : boolean);
procedure AddLine(const AText: string);
protected
// ILog
procedure DebugLn(const s: string = ''); overload;
procedure DebugLn(const S: String; Args: array of const); overload;
procedure DebugLnEnter(const s: string = ''); overload;
procedure DebugLnEnter(s: string; Args: array of const); overload;
procedure DebugLnExit(const s: string = ''); overload;
procedure DebugLnExit(s: string; Args: array of const); overload;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
implementation
{ TWindowLog }
procedure TWindowLog.IncLevel;
begin
fLevel := fLevel + '--';
end;
procedure TWindowLog.DecLevel;
begin
fLevel := copy(fLevel, 1, Length(fLevel) - 2);
end;
procedure TWindowLog.NewLogForm;
begin
fLogForm := TCustomForm.CreateNew(nil);
fLogForm.Caption := 'LOG';
fLogForm.FormStyle := fsStayOnTop;
fLogForm.OnCloseQuery := @OnLogFormCloseQuery;
fLogMemo := TMemo.Create(fLogForm);
fLogMemo.Parent := fLogForm;
fLogMemo.Align := alClient;
fLogMemo.Visible := True;
fLogForm.Visible := True;
end;
procedure TWindowLog.OnLogFormCloseQuery(Sender: TObject; var CanClose: boolean
);
begin
CanClose := False;
end;
procedure TWindowLog.AddLine(const AText: string);
begin
fLogMemo.Lines.Add(fLevel + AText);
end;
procedure TWindowLog.DebugLn(const s: string);
begin
AddLine(s);
end;
procedure TWindowLog.DebugLn(const S: String; Args: array of const);
begin
DebugLn(Format(S, Args));
end;
procedure TWindowLog.DebugLnEnter(const s: string);
begin
IncLevel;
DebugLn(s);
end;
procedure TWindowLog.DebugLnEnter(s: string; Args: array of const);
begin
DebugLnEnter(Format(S, Args));
end;
procedure TWindowLog.DebugLnExit(const s: string);
begin
DebugLn(s);
DecLevel;
end;
procedure TWindowLog.DebugLnExit(s: string; Args: array of const);
begin
DebugLnExit(Format(s, Args));
end;
procedure TWindowLog.AfterConstruction;
begin
inherited AfterConstruction;
NewLogForm;
end;
procedure TWindowLog.BeforeDestruction;
begin
FreeAndNil(fLogForm);
inherited BeforeDestruction;
end;
end.
|
unit FBLibHelper;
interface
type
IFBLibrariesHelper = interface
['{6226A860-A397-4DF4-9419-F377627E6979}']
function LoadLibrary(const LibraryPath: UnicodeString): HMODULE;
function FreeLibrary(Handle: HMODULE): Boolean;
procedure FreeAll;
end;
var
FBLibrariesHelper: IFBLibrariesHelper;
procedure FreeAllFBLibraries;
implementation
uses
Windows;
type
TFBLibrariesHelper = class(TInterfacedObject, IFBLibrariesHelper)
private
FCriticalSection: TRTLCriticalSection;
FLoadedLibraries: array of HMODULE;
FCallFbShutdownOnLastUnload: Boolean;
protected
{ IFBLibrariesHelper }
function LoadLibrary(const LibraryPath: UnicodeString): HMODULE;
function FreeLibrary(Handle: HMODULE): Boolean;
procedure FreeAll;
public
constructor Create(ACallFbShutdownOnLastUnload: Boolean);
destructor Destroy; override;
end;
{ TFBLibrariesHelper }
constructor TFBLibrariesHelper.Create(ACallFbShutdownOnLastUnload: Boolean);
begin
inherited Create;
FCallFbShutdownOnLastUnload := ACallFbShutdownOnLastUnload;
InitializeCriticalSection(FCriticalSection);
end;
destructor TFBLibrariesHelper.Destroy;
begin
DeleteCriticalSection(FCriticalSection);
inherited;
end;
procedure TFBLibrariesHelper.FreeAll;
var
I: Integer;
begin
EnterCriticalSection(FCriticalSection);
try
for I := High(FLoadedLibraries) downto 0 do
Self.FreeLibrary(FLoadedLibraries[I]);
finally
LeaveCriticalSection(FCriticalSection);
end;
end;
function TFBLibrariesHelper.FreeLibrary(Handle: HMODULE): Boolean;
procedure Extract(Handle: HMODULE; out IsLastWithThisHandle: Boolean);
var
I, J: Integer;
begin
IsLastWithThisHandle := False;
for I := 0 to High(FLoadedLibraries) do
begin
if FLoadedLibraries[I] = Handle then
begin
IsLastWithThisHandle := True;
for J := I + 1 to High(FLoadedLibraries) do
begin
if FLoadedLibraries[J] = Handle then
IsLastWithThisHandle := False;
FLoadedLibraries[J - 1] := FLoadedLibraries[J];
end;
SetLength(FLoadedLibraries, Length(FLoadedLibraries) - 1);
Exit;
end;
end;
// Assert(False);
end;
const
fb_shutrsn_svc_stopped = -1;
fb_shutrsn_no_connection = -2;
fb_shutrsn_app_stopped = -3;
fb_shutrsn_device_removed = -4;
fb_shutrsn_signal = -5;
fb_shutrsn_services = -6;
fb_shutrsn_exit_called = -7;
var
IsLastWithThisHandle: Boolean;
// fb_shutdownRes: Integer;
fb_shutdown: function(timeout: Cardinal; const reason: Integer): Integer; {$IFDEF UNIX} cdecl; {$ELSE} stdcall; {$ENDIF}
begin
EnterCriticalSection(FCriticalSection);
try
Extract(Handle, IsLastWithThisHandle);
if IsLastWithThisHandle and FCallFbShutdownOnLastUnload then
begin
fb_shutdown := GetProcAddress(Handle, 'fb_shutdown');
if Assigned(fb_shutdown) then
{fb_shutdownRes := }fb_shutdown(60000, fb_shutrsn_app_stopped); // other good connections had been dropped
Result := Boolean(Windows.FreeLibrary(Handle));
IsLastWithThisHandle := True;
end
else
Result := Boolean(Windows.FreeLibrary(Handle));
finally
LeaveCriticalSection(FCriticalSection);
end;
end;
function TFBLibrariesHelper.LoadLibrary(
const LibraryPath: UnicodeString): HMODULE;
begin
EnterCriticalSection(FCriticalSection);
try
if (Pos(':', LibraryPath) <> 0) or (Pos('\', LibraryPath) <> 0) then
Result := Windows.LoadLibraryExW(PWideChar(LibraryPath), 0, LOAD_WITH_ALTERED_SEARCH_PATH)
else
Result := Windows.LoadLibraryW(PWideChar(LibraryPath));
if Result > HINSTANCE_ERROR then
begin
SetLength(FLoadedLibraries, Length(FLoadedLibraries) + 1);
FLoadedLibraries[High(FLoadedLibraries)] := Result;
end;
finally
LeaveCriticalSection(FCriticalSection);
end;
end;
procedure FreeAllFBLibraries;
begin
if Assigned(FBLibrariesHelper) then
FBLibrariesHelper.FreeAll;
end;
initialization
FBLibrariesHelper := TFBLibrariesHelper.Create(True);
finalization
FreeAllFBLibraries;
FBLibrariesHelper := nil;
end.
|
program poj1061;
var a,b,t,x,y,x1,y1,n,m,l,p : int64;
function gcd(a,b:int64):int64;
begin
if b = 0 then
begin
x := 1; y := 0; exit(a);
end;
gcd := gcd(b,a mod b);
t := x; x := y; y := t - (a div b) * y;
end;
begin
readln(x1,y1,n,m,l);
if n > m then begin b := y1-x1; a := n-m; end
else begin b := x1-y1; a := m-n; end;
p := gcd(a,l);
if b mod p <> 0 then writeln('Impossible') else
begin
x := x * (b div p); l := l div p;
if x <= 0 then x := x + l * ((-x-1) div l + 1);
x := x mod l;
writeln(x);
end;
end.
|
unit YarxiTango;
{
Tango
Nomer Номер. В точности соответствует номеру записи, можно игнорировать.
K1 Ссылка на кандзи или ноль.
K2
K3
K4
Kana Кана, см. ParseTangoKana
Reading Чтение, см. ParseTangoReading
Russian Перевод, см. ParseTangoRussian
Hyphens Список позиций, где вставить знаки препинания, см. ParseTangoHyphens
Yo Список номеров букв "е", которые "ё", см. ParseTangoYo
}
interface
function ParseTangoKana(K1, K2, K3, K4: SmallInt; inp: string): string;
type
TTangoReading = record
text: string;
rare: boolean;
dollar: boolean; //флаг *$* - встречается в небольшом числе случаев, хз что значит
end;
PTangoReading = ^TTangoReading;
TTangoReadings = array of TTangoReading;
function ParseTangoReading(inp: string): TTangoReadings;
type
TTangoRussian = string; //тип определён так временно
function ParseTangoRussian(inp: string): TTangoRussian;
function ParseTangoHyphens(reading: TTangoReading; inp: string): TTangoReading; //может быть лучше будет редактировать на месте, а не возвращать
function ParseTangoYo(russian: TTangoRussian; inp: string): TTangoRussian; //может быть лучше будет редактировать на месте, а не возвращать
implementation
uses SysUtils, WcExceptions, KanaConv, YarxiStrings, YarxiCore, YarxiRefs,
YarxiReadingCommon;
{
Tango.Kana
Cлово составляется так:
K1 K2 K3 K4 (Ki идут до первого нуля)
Затем в полученный текст вставляется кана:
2no4kara ==> 1 2 NO 3 4 KARA
Куски каны добавляются туда, куда указывает цифра перед ними.
Скобки трактуются вполне буквально:
2(4) ==> 1 2 (3 4)
2[4] ==> 1 2 (3 4)
Все неиспользованные кандзи добавляются в конец, то есть, можно сделать так:
0a:kanso: ==> A:KANSO: 1 2
В кане могут быть вставлены дополнительные кандзи #номер##номер#:
13 251 2861 251 2ha4wo#642##1850#6suru #1030
akkaharyo:kawokuchikusuru
По умолчанию кана - хирагана; катакана включается так:
^a:kanso: ==> A:KANSO: (катаканой)
0^amerika1@ri ==> AMERIKA1ri (включили обратно хирагану)
Непонятно:
0akarasama akarasama *2прямой,ясный,открытый;честный,откровенный
все кандзи 0, последнее -1 -- втф?
похоже, по такой схеме пишутся все слова, которые не используют кандзи и
НЕ катакана (пишутся хираганой, нативные)
Хотя видимой разницы нет, если заменить на ноль.
1^ei akaei #ихт.#красный хвостокол(скат),=Dasyatis akajei
зачем такая схема? кандзи всего один, можно было не ставить 1
видимо, ^ по умолчанию предполагает цифру перед ним (обычно это ноль),
а т.к. здесь не ноль - её указали явно. Не знаю, что будет если сделать просто "^ei", и встречается ли такое.
}
//True, если символ - буква, которая может встречаться в ромадзи
function IsTangoRomajiChar(const ch: char): boolean;
begin
Result := IsLatin(ch) or (ch=':'){долгота в транскрипциях}
or (ch=''''){после буквы n}
or (ch='(') or (ch=')')
or (ch='[') or (ch=']') //#337
;
end;
//Читает транскрипцию начиная с текущей буквы
function EatTangoRomaji(var pc: PChar): string;
var ps: PChar;
begin
ps := pc;
while IsTangoRomajiChar(pc^) do
Inc(pc);
Result := spancopy(ps,pc);
end;
//Находит номер символа, которым в строке идёт i-й по счёту кандзи
//Если запрошен нулевой символ, возвращает ноль. Если символ, которого по счёту
//нет, то позицию после конца строки.
function charIdxOfKanji(s: string; i: integer): integer;
var pc: PChar;
begin
Result := 0;
if s='' then exit;
pc := PChar(s);
while i>0 do begin
Inc(Result);
if pc^=#00 then break;
if IsKanji(pc^) then
Dec(i);
Inc(pc);
end;
end;
function ParseTangoKana(K1, K2, K3, K4: SmallInt; inp: string): string;
var pc: PChar;
flag_minusOne: boolean;
flag_katakana: boolean;
kpos: integer;
kstr: string;
begin
Result := '';
flag_katakana := false;
//Стыкуем кандзи-базу
if K1>0 then
Result := Result + getKanji(K1)
else
Check(K1=0);
if K2>0 then begin
Check(K1>0);
Result := Result + getKanji(K2);
end else
Check(K2=0);
if K3>0 then begin
Check(K2>0);
Result := Result + getKanji(K3);
end else
Check(K3=0);
if K4>0 then begin
Check(K3>0);
Result := Result + getKanji(K4);
end else
if K4=-1 then
flag_minusOne := true
else begin
flag_minusOne := false;
Check(K4=0);
end;
//Теперь вставляем кану
if inp='' then exit; //всё сделано
pc := PChar(inp);
kpos := 0;
while pc^<>#00 do
//Доп. кандзи в конец строки
if pc^='#' then begin
Inc(pc);
Result := Result + getKanji(EatNumber(pc));
Check(pc^='#');
Inc(pc);
end else
//Переключатели катаканы-хираганы
if pc^='^' then begin
flag_katakana := true;
Inc(pc);
end else
if pc^='@' then begin
flag_katakana := false;
Inc(pc);
end else
if IsDigit(pc^) then
kpos := EatNumber(pc)
else
//Обычный блок
begin
kstr := EatTangoRomaji(pc);
Check(kstr<>'', 'Пустой блок ромадзи в строчке %s', [inp]);
if flag_katakana then
kstr := RomajiToKana('K'+kstr)
else
kstr := RomajiToKana('H'+kstr);
insert(kstr, Result, charIdxOfKanji(Result, kpos+1));
end;
end;
{
Tango.Reading.
Формат: чтение*чтение**чтение**
* следующий вариант чтения
** прошлое чтение - редкое (напр. #54)
*$* х.з. что, ставлю флаг (#7197)
*=* альтернатива, см. CombineAlternativeReading
*(* далее идёт список вариантов/разбиений на слова
Список разбиений скрыт, используется только для поиска:
agarisagari*(*agari*sagari* (#413) - будет найдено по sagari, но не по saga
Формат какой-то дебильный и неоднозначный, встречается следующее:
aizenmyo:o:*(*myo:o:*aizen* переставлены местами!
eikyu:*towa**tokoshinae**(*eikyu:*towa**tokoshi*na*e***eikyu:*towa**tokoshie*** #5312
В первом случае куски строки переставлены. Получается, порядок неважен. Нахрена
тогда во втором дублировать весь базовый набор дважды?
Логика добавления звёздочек тоже никакому здравому смыслу не подчиняется.
Но, слава богу, эти разбиения не особо нужны, так что мы их пока просто
выкидываем. Если кому-то очень хочется, могут разобраться и написать парсер.
}
function IsTranscriptionChar(const ch: char): boolean;
begin
Result := IsLatin(ch) or (ch=':'){долгота в транскрипциях}
or (ch=''''){после буквы n}
;
end;
//Читает транскрипцию начиная с текущей буквы
function EatTranscription(var pc: PChar): string;
var ps: PChar;
begin
ps := pc;
while IsTranscriptionChar(pc^) do
Inc(pc);
Result := spancopy(ps,pc);
end;
function ParseTangoReading(inp: string): TTangoReadings;
var pc: PChar;
rd: PTangoReading;
tmp_str: string;
begin
SetLength(Result, 0);
if inp='' then exit;
rd := nil;
pc := PChar(inp);
while pc^<>#00 do begin
if pc[0]='(' then begin
break; // Да пошло всё в задницу.
end else
if (pc[0]='*') and (pc[1]='$') then begin
Check(rd<>nil);
Check(not rd.dollar); //чтоб дважды не допускать
rd.dollar := true;
Inc(pc, 2);
end else
if (pc[0]='*') and (pc[1]='*') then begin
Check(rd<>nil);
Check(not rd.rare); //чтоб дважды не допускать
rd.rare := true;
Inc(pc, 2);
end else
if pc^='=' then begin
{ Альтернативное написание - поддерживается только ва/ха, как в Яркси }
Check(rd<>nil, 'Нельзя дать альтернативное чтение без главного');
Inc(pc);
Check(pc^='*'); //можно ослабить и сделать if pc^=='*' then Inc(pc);
Inc(pc);
tmp_str := EatTranscription(pc);
Check(tmp_str<>'');
rd.text := CombineAlternativeReading(rd.text, tmp_str);
// req_sep := true;
end else
if (pc[0]='*') then begin
Inc(pc);
end else
//Обычный текст
begin
tmp_str := EatTranscription(pc);
Check(tmp_str<>'');
SetLength(Result, Length(Result)+1);
rd := @Result[Length(Result)-1];
rd.text := tmp_str;
rd.rare := false;
end;
end;
end;
{
Tango.Russian
Во многом повторяет Kanji.KunyomiRussian - надо вынести общее.
\ мусорный символ, разделяющий компоненты для поиска. Удалять.
! в начале строчки === "не проверено"
@ === специальные фразы:
3 = "и т.п."
'' === хирагана:
''no'' === (хираганой) no
# === переключение италика
#text# === text италиком
() === скобки
По умолчанию текст в скобках - италик.
(, ) === италик-скобки
(#, #) === не-италик скобки
>[цифры] === специальный тип слова
1 = мужское имя
2 = женское имя
3 = фамилия
4 = псевдоним
5 = топоним
Цифры могут объединяться: >35 === "фамилия и топоним"
Повторяться: >11 == "мужские имена"
& === начало следующего варианта
Например: &строение из камня&запор на двери
1. строение из камня
2. запор на двери
Звёздочки:
*0 === "~shita", и т.п., 0..9:
shita, suru, na, no, ni, de, to, taru, shite, shite iru
**0 === "~o suru", и т.п., 0..9:
o suru, ga aru, no aru, no nai, de aru, des, da, ni suru, ni naru, to shite
***0 === "~naru", и т.п., 0..9:
naru, kara, made, mo, wa, to suru, yori, ga shite iru, to shita, to shite iru
****0 === таких нет.
*=00 === двойной номер (их дофига, надо таблицу выдрать).
Минус перед номером значит, что весь блок в скобках:
*-4 === "(~ni)"
Закрывающая квадраная скобка после номера значит, что номер в квадратных скобках:
*4] === "~[4]"
Загадки:
\_
Примеры:
&#\муз.#\интерлюдия\(\особ.\на сямисэне между двумя песнями\)
&\оживляющий возглас\(\в песне\)
&\вставная\(#\непрошенная\#)\реплика
<i>: муз.
<i>: особ. на сямисэне между двумя песнями
<i>: в песне
1: *=00 *=01 *=02 *=03 *=04 *=05 *=06 *=07 *=08 *=09
2: *=10 *=11 *=12 *=13 *=14 *=15 *=16 *=17 *=18 *=19
3: *=20 *=21 *=22 *=23 *=24 *=25 *=26 *=27 *=28 *=29
4: *=30 *=31 *=32 *=33 *=34 *=35 *=36 *=37 *=38 *=39
}
function ParseTangoRussian(inp: string): TTangoRussian;
begin
end;
{
Tango.Hyphens
Список позиций, где следует вставить знаки препинания, напр.:
"-7 9" + "aiduchiwoutsu" = "aiduchi-wo utsu".
Проверенные знаки:
" "
"-"
Также встречается, непонятно:
(4)7 #279 видимо, скобки? проверить
(6)9*(5)8
3-7 9
**(7)9 #5312 -- звёздочки?
}
function ParseTangoHyphens(reading: TTangoReading; inp: string): TTangoReading; //может быть лучше будет редактировать на месте, а не возвращать
begin
end;
{
Tango.Yo
Список номеров букв "е", которые на самом деле ё, напр.:
"1,3" + "елки зеленые" = "ёлки зелёные"
Разделение нужно, видимо, для поиска.
}
function ParseTangoYo(russian: TTangoRussian; inp: string): TTangoRussian; //может быть лучше будет редактировать на месте, а не возвращать
begin
end;
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 180529
////////////////////////////////////////////////////////////////////////////////
unit java.lang.reflect.UndeclaredThrowableException;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JUndeclaredThrowableException = interface;
JUndeclaredThrowableExceptionClass = interface(JObjectClass)
['{3EF2B151-EAB3-4C18-8549-5445AB8093E9}']
function getCause : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $1
function getUndeclaredThrowable : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $1
function init(exception : JThrowable) : JUndeclaredThrowableException; cdecl; overload;// (Ljava/lang/Throwable;)V A: $1
function init(exception : JThrowable; detailMessage : JString) : JUndeclaredThrowableException; cdecl; overload;// (Ljava/lang/Throwable;Ljava/lang/String;)V A: $1
end;
[JavaSignature('java/lang/reflect/UndeclaredThrowableException')]
JUndeclaredThrowableException = interface(JObject)
['{32763691-AF55-4A80-A5C7-94BA5139EF82}']
function getCause : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $1
function getUndeclaredThrowable : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $1
end;
TJUndeclaredThrowableException = class(TJavaGenericImport<JUndeclaredThrowableExceptionClass, JUndeclaredThrowableException>)
end;
implementation
end.
|
// -------------------------------------------------------------
// Este programa implementa um jogo espacial. :~
// Revisado por Luiz Reginaldo - Desenvolvedor do Pzim
// Autores: Marco André Dinis e José Luis Teixeira
// -------------------------------------------------------------
Program WordKill;
var letra : char ;
i : integer;
//-------------------------------------------------------------------
// Desenha a tela inicial do jogo
//-------------------------------------------------------------------
Procedure ExibeTelaInicial ;
Begin
textbackground(BLUE);
textcolor(WHITE);
clrscr;
writeln('________________________________');
writeln('|******************************|');
writeln('|>--===^^ Word Kill ^^===--<|');
writeln('|******************************|');
writeln('|______________________________|');
writeln('v 0.1');
writeln('Créditos: Marco André Dinis');
writeln(' José Luis Teixeira');
writeln('11 PTGEI Escola Secundária de');
writeln('Amarante 2007/2008');
writeln('Disciplina: SDAC');
writeln('');
writeln('Este jogo é muito simples.');
writeln('Quando aparecer uma letra no');
writeln('ecrã você apenas precisa digitar');
writeln('a letra correspondente no teclado');
writeln('');
writeln('Presione a tecla W para jogar');
End ;
//-------------------------------------------------------------------
// Desenha a tela inicial do jogo
//-------------------------------------------------------------------
Procedure DesenhaTabuleiro ;
var i: integer ;
begin
clrscr;
writeln('________________________________');
for i:= 1 to 20 do
writeln('| |');
writeln('| % |');
writeln('______________#',#1,'#_______________');
writeln('Nivel:');
writeln('Pontuação:');
End;
//-------------------------------------------------------------------
// Roda o jogo
//-------------------------------------------------------------------
Procedure IniciaJogo ;
var i, j: integer ;
letra : char ;
pontos, nivel: integer ;
continuar : boolean ;
achouRepetido, acertouTodas : boolean ;
sorteadas : array[1..7] of char ; // Letras sorteadas no nivel
colSorteadas : array[1..30] of integer ; // coluna das letras
Begin
// Valor inicial para as variaveis do jogo
nivel := 1 ;
pontos := 0 ;
continuar := true ;
randomize ;
Repeat
// Desenha o tabuleiro do jogo
DesenhaTabuleiro;
// Informa em que nivel está o jogo
gotoxy(8,24);
write(nivel);
// Sorteia as letras desse nível
for i:= 1 to 7 do
Begin
j := random(25)+65;
sorteadas[i] :=chr(j);
End ;
// Sorteia a coluna em que vai aparecer cada uma das letras sorteadas
Repeat
// Sorteia as colunas das letras
for i:=1 to 7 do
colSorteadas[i] := random(30) + 2;
// Verifica se alguma coluna é repetida
// Se for, um novo sorteiro vai ser feito
achouRepetido := false ;
for i:=1 to 7 do
for j:=1 to 7 do
if (i<>j) and (colSorteadas[i] = colSorteadas[j]) then
achouRepetido := true ;
Until not achouRepetido ;
// Desenha as letras sorteadas na parte de cima da tela
for i:=1 to 7 do
begin
gotoxy(colSorteadas[i],2);
write(sorteadas[i]);
end;
// Repeticao para descer as letras uma linha de cada vez
for i:=1 to 20 do
begin
// Se usuario pressionou uma tecla verifica se essa
// tecla é alguma das sorteadas
if keypressed then
begin
letra := Upcase(readkey);
for j:=1 to 7 do
begin
if letra = sorteadas[j] then
begin
pontos := pontos + 10 ;
sorteadas[j]:=' ';
gotoxy(colSorteadas[i]+2,2+i);
write (' ');
end;
end;
end;
// Informa a pontuacao
gotoxy(12,25);
write(pontos);
// Desenha as letras sorteadas na proxima linha
for j:=1 to 7 do
begin
gotoxy(colSorteadas[j],1+i);
write(' ');
gotoxy(colSorteadas[j],2+i);
write (sorteadas[j]);
end;
// Verifica se acertou todas as letras sorteadas
acertouTodas := true ;
for j:=1 to 7 do
begin
if sorteadas[j] <> ' ' then acertouTodas:= false ;
end;
// Se acertou todas, passa para o proximo nivel
if acertouTodas then
begin
nivel := nivel + 1 ;
break ;
end;
// Se chegou na ultima linha sem acertar as letras termina o jogo
gotoxy(16,22);
delay(600-(nivel*15));
if (i=20) and (not acertouTodas) then
continuar:=false;
end;
Until continuar=false;
// Mostra a pontuacao final
gotoxy(1,26);
Writeln('A sua pontuação foi de: ',pontos);
Writeln('Chegaste ao nivel: ',nivel);
Writeln('Pressione <ENTER> para sair');
end;
//----------------------------------------------------------------
// Inicio do jogo
//----------------------------------------------------------------
Begin
// Mostra a tela inicial do jogo
ExibeTelaInicial ;
// Aguarda o usuário pressionar w para poder jogar
repeat
letra := upCase(ReadKey);
until letra='W';
// Desenha a faixa que corre da esquerda para direita
writeln(#7,'A carregar...');
for i:=1 to 32 do
begin
delay(50) ;
write(#177) ;
end;
// Começa o jogo
IniciaJogo ;
End.
|
unit Invoice.Model.Product;
interface
uses
DB,
Classes,
SysUtils,
Generics.Collections,
/// orm
ormbr.types.blob,
ormbr.types.lazy,
ormbr.types.mapping,
ormbr.types.nullable,
ormbr.mapping.classes,
ormbr.mapping.register,
ormbr.mapping.attributes;
type
[Entity]
[Table('Product', '')]
TProduct = class
private
{ Private declarations }
FidProduct: Integer;
FnameProduct: String;
FpriceProduct: Currency;
public
{ Public declarations }
[Restrictions([NotNull])]
[Column('idProduct', ftInteger)]
[Dictionary('idProduct', 'Mensagem de validação', '', '', '', taCenter)]
property idProduct: Integer Index 0 read FidProduct write FidProduct;
[Restrictions([NotNull])]
[Column('nameProduct', ftString, 100)]
[Dictionary('nameProduct', 'Mensagem de validação', '', '', '', taLeftJustify)]
property nameProduct: String Index 1 read FnameProduct write FnameProduct;
[Restrictions([NotNull])]
[Column('priceProduct', ftCurrency)]
[Dictionary('priceProduct', 'Mensagem de validação', '0', '', '', taRightJustify)]
property priceProduct: Currency Index 2 read FpriceProduct write FpriceProduct;
end;
implementation
initialization
TRegisterClass.RegisterEntity(TProduct)
end.
|
unit clMMTimer;
interface
uses
Winapi.Windows,
System.Classes,
Winapi.MMSystem;
type
TMMTimer = class
private
FInterval: integer;
fId: UINT;
FOnTimer: TNotifyEvent;
function GetEnabled: boolean;
procedure SetEnabled(Value: boolean);
procedure SetInterval(Value: integer);
protected
procedure DoTimer; virtual;
public
property Interval: integer read FInterval write SetInterval;
property Enabled: boolean read GetEnabled write SetEnabled;
property OnTimer: TNotifyEvent read FOnTimer write FOnTimer;
destructor Destroy; override;
end;
implementation
{ TMMTimer }
procedure MMCallBack(uTimerID, uMsg: UINT; dwUser, dw1, dw2: DWORD); stdcall;
begin
if dwUser <> 0 then
TMMTimer(dwUser).DoTimer;
end;
destructor TMMTimer.Destroy;
begin
if Enabled then
begin
if (fId <> 0) then
begin
timeKillEvent(fId);
fId := 0;
end
end;
inherited;
end;
procedure TMMTimer.DoTimer;
begin
if Assigned(FOnTimer) then
FOnTimer(Self);
end;
function TMMTimer.GetEnabled: boolean;
begin
try
Result := fId <> 0
except
Result := False;
end;
end;
procedure TMMTimer.SetEnabled(Value: boolean);
begin
if Enabled <> Value then
begin
if fId <> 0 then
begin
timeKillEvent(fId);
fId := 0;
end
else
begin
fId := timeSetEvent(FInterval, 0, @MMCallBack, DWORD(Self),
TIME_CALLBACK_FUNCTION or TIME_PERIODIC or TIME_KILL_SYNCHRONOUS);
end;
end;
end;
procedure TMMTimer.SetInterval(Value: integer);
var
oldEnabled: boolean;
begin
if FInterval <> Value then
begin
oldEnabled := Enabled;
Enabled := false;
FInterval := Value;
Enabled := oldEnabled;
end;
end;
end.
|
unit MagentoSearchCriteria;
interface
uses
Magento.Interfaces;
type
TMagentoSearchCriteria = class (TInterfacedObject, iMagentoSearchCriteria)
private
FParent : iMagentoHTTP_V1;
FField : String;
FValue : String;
FCondition_Type : String;
FAndOr : Boolean;
public
constructor Create(Parent : iMagentoHTTP_V1);
destructor Destroy; override;
class function New(Parent : iMagentoHTTP_V1) : iMagentoSearchCriteria;
function Field(Value : String) : iMagentoSearchCriteria;
function Value(aValue : String) : iMagentoSearchCriteria;
function Condition_type(Value : String) : iMagentoSearchCriteria;
function AndOr(Value : Boolean) : iMagentoSearchCriteria;
function Get(Value : String) : iMagentoSearchCriteria; overload;
function &End : iMagentoHTTP_V1;
end;
implementation
{ TMagentoSearchCriteria }
function TMagentoSearchCriteria.AndOr(Value: Boolean): iMagentoSearchCriteria;
begin
Result := Self;
FAndOr := Value;
end;
function TMagentoSearchCriteria.Condition_type(
Value: String): iMagentoSearchCriteria;
begin
Result := Self;
FCondition_Type := Value;
end;
function TMagentoSearchCriteria.&End: iMagentoHTTP_V1;
begin
Result := FParent;
end;
constructor TMagentoSearchCriteria.Create(Parent : iMagentoHTTP_V1);
begin
FParent := Parent;
end;
destructor TMagentoSearchCriteria.Destroy;
begin
inherited;
end;
function TMagentoSearchCriteria.Field(Value: String): iMagentoSearchCriteria;
begin
Result := Self;
FField := Value;
end;
function TMagentoSearchCriteria.Get(Value: String): iMagentoSearchCriteria;
begin
Result := Self;
end;
class function TMagentoSearchCriteria.New(Parent : iMagentoHTTP_V1) : iMagentoSearchCriteria;
begin
Result := self.Create(Parent);
end;
function TMagentoSearchCriteria.Value(aValue: String): iMagentoSearchCriteria;
begin
Result := Self;
FValue := aValue;
end;
end.
|
unit UDSortFields;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeSortFieldsDlg = class(TForm)
pnlSortFields: TPanel;
lblFieldName: TLabel;
lblNumber: TLabel;
rgDirection: TRadioGroup;
lbNumbers: TListBox;
btnOk: TButton;
btnClear: TButton;
cbFieldNames: TComboBox;
btnAdd: TButton;
btnDelete: TButton;
btnInsert: TButton;
lblCount: TLabel;
editCount: TEdit;
procedure lbNumbersClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure rgDirectionClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure UpdateSortFields;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnInsertClick(Sender: TObject);
procedure cbFieldNamesChange(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure lbNumbersDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
procedure lbNumbersDragDrop(Sender, Source: TObject; X, Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
SortIndex : smallint;
end;
var
CrpeSortFieldsDlg: TCrpeSortFieldsDlg;
bSortFields : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.FormCreate(Sender: TObject);
begin
bSortFields := True;
LoadFormPos(Self);
btnOk.Tag := 1;
btnAdd.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.FormShow(Sender: TObject);
begin
UpdateSortFields;
end;
{------------------------------------------------------------------------------}
{ UpdateSortFields }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.UpdateSortFields;
var
OnOff : boolean;
i : integer;
sList : TStringList;
begin
cbFieldNames.Clear;
cbFieldNames.Items.AddStrings(Cr.Tables.FieldNames);
sList := TStringList.Create;
sList.AddStrings(Cr.Formulas.Names);
for i := 0 to sList.Count-1 do
cbFieldNames.Items.Add(NameToCrFormulaFormat(sList[i], 'Formulas'));
sList.Free;
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
begin
OnOff := False;
btnAdd.Enabled := False;
SortIndex := -1;
end
else
begin
OnOff := (Cr.SortFields.Count > 0);
btnAdd.Enabled := True;
{Get SortFields Index}
if OnOff then
begin
if Cr.SortFields.ItemIndex > -1 then
SortIndex := Cr.SortFields.ItemIndex
else
SortIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff = True then
begin
for i := 0 to (Cr.SortFields.Count - 1) do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Cr.SortFields.Count);
lbNumbers.ItemIndex := SortIndex;
lbNumbersClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbSNumberClick }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.lbNumbersClick(Sender: TObject);
var
i : integer;
begin
SortIndex := lbNumbers.ItemIndex;
i := cbFieldNames.Items.IndexOf(Cr.SortFields[SortIndex].FieldName);
if i = -1 then i := 0;
cbFieldNames.ItemIndex := i;
rgDirection.ItemIndex := Ord(Cr.SortFields.Item.Direction);
end;
{------------------------------------------------------------------------------}
{ lbNumbersDragOver }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.lbNumbersDragOver(Sender, Source: TObject; X,
Y: Integer; State: TDragState; var Accept: Boolean);
begin
if Sender is TListBox then
begin
if TListBox(Sender).Name = 'lbNumbers' then
Accept := True;
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersDragDrop }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.lbNumbersDragDrop(Sender, Source: TObject; X,
Y: Integer);
var
p : TPoint;
i : integer;
begin
p.x := X;
p.y := y;
i := lbNumbers.ItemAtPos(p, True);
if i > -1 then
begin
Cr.SortFields.Swap(TListBox(Source).ItemIndex, i);
UpdateSortFields;
end;
end;
{------------------------------------------------------------------------------}
{ cbFieldNamesChange }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.cbFieldNamesChange(Sender: TObject);
begin
Cr.SortFields.Item.FieldName := cbFieldNames.Items[cbFieldNames.ItemIndex];
end;
{------------------------------------------------------------------------------}
{ rgSDirectionClick }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.rgDirectionClick(Sender: TObject);
begin
Cr.SortFields.Item.Direction := TCrSortDirection(rgDirection.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ btnAddSFieldClick }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.btnAddClick(Sender: TObject);
begin
if cbFieldNames.Items.Count = 0 then
Exit;
Cr.SortFields.Add(cbFieldNames.Items[0]);
UpdateSortFields;
end;
{------------------------------------------------------------------------------}
{ btnDeleteSFieldClick }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.btnDeleteClick(Sender: TObject);
var
nIndex : integer;
begin
nIndex := lbnumbers.ItemIndex;
{Delete SortField from VCL}
Cr.SortFields.Delete(nIndex);
lbnumbers.Items.Delete(nIndex);
{Reset ItemIndex}
if lbnumbers.Items.Count > 0 then
begin
if (nIndex > (lbnumbers.Items.Count - 1)) or (nIndex < 0) then
nIndex := (lbnumbers.Items.Count - 1);
lbnumbers.ItemIndex := nIndex;
lbnumbersClick(Self);
end;
UpdateSortFields;
end;
{------------------------------------------------------------------------------}
{ btnInsertClick }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.btnInsertClick(Sender: TObject);
var
nIndex : integer;
begin
if cbFieldNames.Items.Count = 0 then
Exit;
nIndex := lbnumbers.ItemIndex;
if nIndex < 0 then nIndex := 0;
{Insert SortField}
Cr.SortFields.Insert(nIndex, cbFieldNames.Items[0], sdDescending);
UpdateSortFields;
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.btnClearClick(Sender: TObject);
begin
Cr.SortFields.Clear;
UpdateSortFields;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeSortFieldsDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bSortFields := False;
Release;
end;
end.
|
unit uMoveReportParams;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uMoveReportData, uDateControl, uFControl, uLabeledFControl,
uSpravControl, StdCtrls, Buttons, frxClass, frxDBSet, uCharControl,
frxExportHTML, frxExportPDF, frxExportXLS, frxExportRTF;
type
TfmMoveReport = class(TForm)
Department: TqFSpravControl;
DateBeg: TqFDateControl;
DateEnd: TqFDateControl;
OkButton: TBitBtn;
CancelButton: TBitBtn;
Report: TfrxReport;
MovesDS: TfrxDBDataset;
SignPost: TqFCharControl;
SignFIO: TqFCharControl;
frxRTFExport1: TfrxRTFExport;
frxXLSExport1: TfrxXLSExport;
frxPDFExport1: TfrxPDFExport;
frxHTMLExport1: TfrxHTMLExport;
ExportButton: TBitBtn;
procedure DepartmentOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure OkButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ExportButtonClick(Sender: TObject);
private
DM: TdmMoveReport;
DesignReport: Boolean;
procedure PrepareReport;
public
constructor Create(AOwner: TComponent; DM: TdmMoveReport;
DesignReport: Boolean); reintroduce;
end;
var
fmMoveReport: TfmMoveReport;
implementation
{$R *.dfm}
uses uCommonSp, Registry, NagScreenUnit, qFTools, uExportReport;
constructor TfmMoveReport.Create(AOwner: TComponent; DM: TdmMoveReport;
DesignReport: Boolean);
begin
inherited Create(AOwner);
Self.DM := DM;
Self.DesignReport := DesignReport;
DateEnd.Value := Date;
DateBeg.Value := IncMonth(Date, -1);
DM.CurrentDepartment.Close;
DM.CurrentDepartment.Open;
end;
procedure TfmMoveReport.DepartmentOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(DM.DB.Handle);
FieldValues['Actual_Date'] := DateBeg.Value;
FieldValues['Root_Department'] := DM.CurrentDepartment['Current_Department'];
Post;
end;
// показать справочник и проанализировать результат (выбор одного подр.)
sp.Show;
if ( sp.Output <> nil ) and not sp.Output.IsEmpty then
begin
Value := sp.Output['Id_Department'];
DisplayText := sp.Output['Name_Full'];
end;
sp.Free;
end;
end;
procedure TfmMoveReport.OkButtonClick(Sender: TObject);
begin
PrepareReport;
if DesignReport then Report.DesignReport
else Report.ShowReport;
end;
procedure TfmMoveReport.FormCreate(Sender: TObject);
var
reg: TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey('\Software\ASUP\MovesReport\', False) then
begin
try
Department.Value := reg.ReadInteger('Id_Department');
Department.DisplayText := reg.ReadString('Name_Department');
SignPost.Value := reg.ReadString('SignPost');
SignFIO.Value := reg.ReadString('SignFIO');
except
end;
try
DateBeg.Value := reg.ReadDate('Date_Beg');
DateEnd.Value := reg.ReadDate('Date_End');
except
end;
end;
reg.CloseKey;
finally
reg.Free;
end;
end;
procedure TfmMoveReport.FormClose(Sender: TObject;
var Action: TCloseAction);
var
reg: TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey('\Software\ASUP\MovesReport\', True) then
begin
try
reg.WriteInteger('Id_Department', Department.Value);
reg.WriteString('Name_Department', Department.DisplayText);
reg.WriteDate('Date_Beg', DateBeg.Value);
reg.WriteDate('Date_End', DateEnd.Value);
reg.WriteString('SignPost', SignPost.Value);
reg.WriteString('SignFIO', SignFIO.Value);
except
end;
end;
reg.CloseKey;
finally
reg.Free;
end;
end;
procedure TfmMoveReport.PrepareReport;
var
NagScreen: TNagScreen;
begin
NagScreen := TNagScreen.Create(Application.MainForm);
NagScreen.Show;
NagScreen.SetStatusText('Формується звіт...');
try
DM.MoveDataSet.Close;
DM.MoveDataSet.ParamByName('Root_Department').AsInteger := Department.Value;
DM.MoveDataSet.ParamByName('Date_Beg').AsDate := DateBeg.Value;
DM.MoveDataSet.ParamByName('Date_End').AsDate := DateEnd.Value;
DM.MoveDataSet.Open;
if DM.MoveDataSet.IsEmpty then
begin
qFErrorDialog('Переводів не знайдено!');
Exit;
end;
MovesDS.DataSet := DM.MoveDataSet;
Report.LoadFromFile('Reports\Asup\MovesReport.fr3');
Report.Variables['Date_Beg'] := QuotedStr(DateToStr(DateBeg.Value));
Report.Variables['Date_End'] := QuotedStr(DateToStr(DateEnd.Value));
Report.Variables['Department'] := QuotedStr(Department.DisplayText);
Report.Variables['SIGN_POST'] := QuotedStr(SignPost.Value);
Report.Variables['SIGN_FIO'] := QuotedStr(SignFIO.Value);
finally
NagScreen.Free;
end;
end;
procedure TfmMoveReport.ExportButtonClick(Sender: TObject);
begin
PrepareReport;
ExportReportTo(Report);
end;
end.
|
unit BsMemoFilter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxClasses, cxTextEdit, cxLabel, cxDBLookupComboBox, cxCheckBox,
cxCalendar, cxDropDownEdit, cxMemo, cxCurrencyEdit;
type
TBsMemoFilter=class(TForm)
private
curIndex, nComponents:Smallint;
arParams:array of Variant;
NameComponents:array of string;
FormFilter:TComponent;
public
constructor Create(NameComp:string; FForm:TComponent);reintroduce;
procedure SetParams;
function MoveOnIndex(Undo:Boolean):Boolean;
function FillComponents:Boolean;
function EnableBtn(isUndo:Boolean):Boolean;
function GetValueByNameComponent(NameComponent:string):Variant;
function GetValueByNameComponentEx(NameComponent:string):Variant;
function FilterArrayIsNil:Boolean;
function FilterUndo:Boolean;
function FilterRedo:Boolean;
end;
implementation
constructor TBsMemoFilter.Create(NameComp:string; FForm:TComponent);
var i:Smallint;
begin
Self.curIndex:=0;
if Trim(NameComp)='' then Self.nComponents:=0
else
begin
Self.nComponents:=1;
SetLength(Self.NameComponents,Self.nComponents);
for i:=1 to Length(NameComp) do
begin
if NameComp[i]<>';' then
Self.NameComponents[Self.nComponents-1]:=Self.NameComponents[Self.nComponents-1]+NameComp[i]
else
begin
Inc(Self.nComponents);
SetLength(Self.NameComponents, Self.nComponents);
end;
end;
end;
FormFilter:=FForm;
end;
function TBsMemoFilter.GetValueByNameComponent(NameComponent:string):Variant;
begin
if FormFilter.FindComponent(NameComponent) is TcxTextEdit then
Result:=(FormFilter.FindComponent(NameComponent) as TcxTextEdit).Text
else if FormFilter.FindComponent(NameComponent) is TcxCheckBox then
Result:=(FormFilter.FindComponent(NameComponent) as TcxCheckBox).Checked
else if FormFilter.FindComponent(NameComponent) is TcxDateEdit then
Result:=(FormFilter.FindComponent(NameComponent) as TcxDateEdit).Date
else if FormFilter.FindComponent(NameComponent) is TcxLookupComboBox then
Result:=(FormFilter.FindComponent(NameComponent) as TcxLookupComboBox).EditValue
else if FormFilter.FindComponent(NameComponent) is TcxComboBox then
Result:=(FormFilter.FindComponent(NameComponent) as TcxComboBox).EditValue
else if FormFilter.FindComponent(NameComponent) is TcxMemo then
Result:=(FormFilter.FindComponent(NameComponent) as TcxMemo).Text
else if FormFilter.FindComponent(NameComponent) is TcxCurrencyEdit then
Result:=(FormFilter.FindComponent(NameComponent) as TcxCurrencyEdit).Value;
end;
function TBsMemoFilter.GetValueByNameComponentEx(NameComponent:string):Variant;
var i:SmallInt;
v:Variant;
begin
v:=Self.arParams[Self.curIndex];
for i:=0 to Self.nComponents-1 do
begin
if Self.NameComponents[i]=NameComponent then
begin
Result:=v[i];
Break;
end;
end;
end;
procedure TBsMemoFilter.SetParams;
var i:SmallInt;
v:Variant;
begin
if Self.arParams=nil then SetLength(Self.arParams, 1)
else SetLength(Self.arParams, Length(Self.arParams)+1);
Self.curIndex:=Length(Self.arParams)-1;
v:=VarArrayCreate([0, Self.nComponents-1], varVariant);
for i:=0 to Self.nComponents-1 do
begin
v[i]:=GetValueByNameComponent(Self.NameComponents[i]);
end;
Self.arParams[Self.curIndex]:=v;
end;
function TBsMemoFilter.FilterUndo:Boolean;
begin
Result:=False;
if Self.curIndex>0 then
begin
Dec(Self.curIndex);
Result:=True;
end;
end;
function TBsMemoFilter.FilterRedo:Boolean;
begin
Result:=False;
if Self.curIndex<Length(Self.arParams) then
begin
Inc(Self.curIndex);
Result:=True;
end;
end;
function TBsMemoFilter.MoveOnIndex(Undo:Boolean):Boolean;
begin
if not Undo then
begin
if Self.curIndex>=Length(Self.arParams) then
begin
Result:=False;
end
else
begin
Result:=True;
Inc(Self.curIndex);
end;
end
else
begin
if Self.curIndex<=0 then
begin
Result:=False;
end
else
begin
Result:=True;
Dec(Self.curIndex);
end;
end;
end;
function TBsMemoFilter.FillComponents:Boolean;
var i:SmallInt;
v:Variant;
begin
try
v:=arParams[curIndex];
for i:=0 to Self.nComponents-1 do
begin
if FormFilter.FindComponent(Self.NameComponents[i]) is TcxTextEdit then
(FormFilter.FindComponent(Self.NameComponents[i]) as TcxTextEdit).Text:=v[i]
else if FormFilter.FindComponent(Self.NameComponents[i]) is TcxCheckBox then
(FormFilter.FindComponent(Self.NameComponents[i]) as TcxCheckBox).Checked:=v[i]
else if FormFilter.FindComponent(Self.NameComponents[i]) is TcxDateEdit then
(FormFilter.FindComponent(Self.NameComponents[i]) as TcxDateEdit).Date:=v[i]
else if FormFilter.FindComponent(Self.NameComponents[i]) is TcxComboBox then
(FormFilter.FindComponent(Self.NameComponents[i]) as TcxComboBox).EditValue:=v[i]
else if FormFilter.FindComponent(Self.NameComponents[i]) is TcxMemo then
(FormFilter.FindComponent(Self.NameComponents[i]) as TcxMemo).Text:=v[i]
else if FormFilter.FindComponent(Self.NameComponents[i]) is TcxCurrencyEdit then
(FormFilter.FindComponent(Self.NameComponents[i]) as TcxCurrencyEdit).Value:=v[i];
end;
Result:=True;
except
Result:=False;
end;
end;
function TBsMemoFilter.EnableBtn(isUndo:Boolean):Boolean;
begin
Result:=False;
if isUndo then
begin
if curIndex in [1..Length(Self.arParams)-1] then Result:=True;
end
else
begin
if curIndex in [0..Length(Self.arParams)-2] then Result:=True;
end;
end;
function TBsMemoFilter.FilterArrayIsNil:Boolean;
begin
if Self.arParams=nil then Result:=True
else Result:=False;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.