text stringlengths 14 6.51M |
|---|
unit Ths.Erp.Helper.BaseTypes;
interface
{$I ThsERP.inc}
uses
System.SysUtils;
type
TInputType = (itString, itInteger, itFloat, itMoney, itDate, itTime);
function LowCase(pKey: Char): Char;
function LowCaseTr(pKey: Char): Char;
function UpCaseTr(pKey: Char): Char;
function toMoneyToDouble(pVal: string; pInputType: TInputType): Double;
implementation
function LowCase(pKey: Char): Char;
begin
//Result := Char(Word(pKey) or $0020);
Result := pKey;
if CharInSet(Result, ['A'..'Z']) then
Inc(Result, Ord('a')-Ord('A'));
end;
function LowCaseTr(pKey: Char): Char;
begin
case pKey of
'I': pKey := 'ý';
'Ý': pKey := 'i';
'Ð': pKey := 'ð';
'Ü': pKey := 'ü';
'Þ': pKey := 'þ';
'Ö': pKey := 'ö';
'Ç': pKey := 'ç';
else
pKey := LowCase(pKey);
end;
Result := pKey;
end;
function UpCaseTr(pKey: Char): Char;
begin
case pKey of
'ý': pKey := 'I';
'i': pKey := 'Ý';
'ð': pKey := 'Ð';
'ü': pKey := 'Ü';
'þ': pKey := 'Þ';
'ö': pKey := 'Ö';
'ç': pKey := 'Ç';
else
pKey := UpCase(pKey);
end;
Result := pKey;
end;
function toMoneyToDouble(pVal: string; pInputType: TInputType): Double;
begin
Result := 0;
if pInputType = itMoney then
Result := StrToFloat(StringReplace(pVal, FormatSettings.ThousandSeparator, '', [rfReplaceAll]));
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,
OpenGL;
type
TfrmGL = class(TForm)
btnColor: TButton;
ColorDialog1: TColorDialog;
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnColorClick(Sender: TObject);
private
hrc : HGLRC;
R, G, B : GLFloat;
procedure ColorToGL (c : TColor; var R, G, B : GLFloat);
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Перевод цвета из TColor в OpenGL}
procedure TfrmGL.ColorToGL (c : TColor; var R, G, B : GLFloat);
begin
R := (c mod $100) / 255;
G := ((c div $100) mod $100) / 255;
B := (c div $10000) / 255;
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glClearColor (R, G, B, 1.0); // цвет фона
glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета
wglMakeCurrent(0, 0);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
SetDCPixelFormat(Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
Randomize;
R := random;
G := random;
B := random;
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
end;
procedure TfrmGL.btnColorClick(Sender: TObject);
begin
If ColorDialog1.Execute then begin
ColorToGL (ColorDialog1.Color, R, G, B);
Refresh;
end;
end;
end.
|
unit uWatchForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Buttons, ExtCtrls, Grids, uResourceStrings, uView, uProcessor,
StdCtrls, Menus, uMisc, Registry, ImgList;
type
TRAMRefreshRequestEvent = procedure(Listener: IRAM) of object;
TRAMUpdateRequestEvent = procedure(Address: Word; Value: Byte) of object;
TIOPortsRefreshRequestEvent = procedure(Listener: IIOPorts) of object;
TIOPortsUpdateRequestEvent = procedure(PortNo: Byte; Value: Byte) of object;
TWatchForm = class(TForm, ILanguage, IRadixView, IRAM, IIOPorts, IRegistry, IProcessor)
sgWatch: TStringGrid;
PopupMenu: TPopupMenu;
miClose: TMenuItem;
N1: TMenuItem;
miStayOnTop: TMenuItem;
N2: TMenuItem;
miAddWatchRAM: TMenuItem;
miDelWatch: TMenuItem;
miDelAll: TMenuItem;
miAddWatchIPORT: TMenuItem;
miAddWatchOPort: TMenuItem;
iRAM: TImage;
iIPort: TImage;
iOPort: TImage;
ImageList: TImageList;
procedure FormCreate(Sender: TObject);
procedure sgWatchDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure miCloseClick(Sender: TObject);
procedure miStayOnTopClick(Sender: TObject);
procedure sgWatchKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure sgWatchDblClick(Sender: TObject);
procedure sgWatchSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure FormDestroy(Sender: TObject);
procedure miAddWatchRAMClick(Sender: TObject);
procedure miDelWatchClick(Sender: TObject);
procedure miDelAllClick(Sender: TObject);
procedure miAddWatchIPORTClick(Sender: TObject);
procedure miAddWatchOPortClick(Sender: TObject);
procedure FormCanResize(Sender: TObject; var NewWidth,
NewHeight: Integer; var Resize: Boolean);
private
_Block: Boolean;
_Width: Integer;
_WatchList: TWatchList;
_Radix: TRadix;
_View: TView;
_ARow: Integer;
_ACol: Integer;
_OnRAMRefreshRequest: TRAMRefreshRequestEvent;
_OnRAMUpdateRequest: TRAMUpdateRequestEvent;
_OnIPortsRefreshRequest: TIOPortsRefreshRequestEvent;
_OnIPortsUpdateRequest: TIOPortsUpdateRequestEvent;
_OnOPortsRefreshRequest: TIOPortsRefreshRequestEvent;
procedure RefreshObject(Sender: TObject);
procedure Reset(Sender: TObject);
procedure RAMUpdate(Sender: TObject; Address: Word; Value: Byte);
procedure PortUpdate(Sender: TObject; Index: Byte; Value: Byte);
procedure PortAction(Sender: TObject; Active: Boolean);
procedure BeforeCycle(Sender: TObject);
procedure AfterCycle(Sender: TObject);
procedure StateChange(Sender: TObject; Halt: Boolean);
procedure LoadData(RegistryList: TRegistryList);
procedure SaveData(RegistryList: TRegistryList);
public
procedure LoadLanguage;
procedure RadixChange(Radix: TRadix; View: TView);
property OnRAMRefreshRequest: TRAMRefreshRequestEvent read _OnRAMRefreshRequest write _OnRAMRefreshRequest;
property OnRAMUpdateRequest: TRAMUpdateRequestEvent read _OnRAMUpdateRequest write _OnRAMUpdateRequest;
property OnIPortsRefreshRequest: TIOPortsRefreshRequestEvent read _OnIPortsRefreshRequest write _OnIPortsRefreshRequest;
property OnIPortsUpdateRequest: TIOPortsUpdateRequestEvent read _OnIPortsUpdateRequest write _OnIPortsUpdateRequest;
property OnOPortsRefreshRequest: TIOPortsRefreshRequestEvent read _OnOPortsRefreshRequest write _OnOPortsRefreshRequest;
end;
var
WatchForm: TWatchForm;
implementation
uses uEditForm;
{$R *.dfm}
procedure TWatchForm.FormCreate(Sender: TObject);
begin
_Block:= true;
_WatchList:= TWatchList.Create;
_Radix:= rOctal;
_View:= vShort;
sgWatch.RowCount:= _WatchList.Count+1;
sgWatch.ColCount:= 4;
sgWatch.ColWidths[0]:= 100;
sgWatch.ColWidths[1]:= 100;
sgWatch.ColWidths[2]:= 24;
sgWatch.ColWidths[3]:= 0;
sgWatch.Cells[3,0]:= '';
sgWatch.Left:= 0;
sgWatch.Top:= 0;
ClientWidth:= 244;
ClientHeight:= sgWatch.RowHeights[0] * 10;
_Width:= Width;
sgWatch.Canvas.CopyMode:= cmMergeCopy;
_ARow:= -1;
_ACol:= -1;
LoadLanguage;
_Block:= false;
end;
procedure TWatchForm.FormCanResize(Sender: TObject; var NewWidth,
NewHeight: Integer; var Resize: Boolean);
begin
if not _Block then
NewWidth:= _Width;
end;
procedure TWatchForm.FormDestroy(Sender: TObject);
begin
_WatchList.Free;
end;
procedure TWatchForm.sgWatchDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
Item: TWatchItem;
begin
if (ARow = 0) or (ACol = 0) then
sgWatch.Canvas.Brush.Color:= sgWatch.FixedColor
else
sgWatch.Canvas.Brush.Color:= sgWatch.Color;
sgWatch.Canvas.FillRect(Rect);
if (ACol = 1) and (sgWatch.Cells[3,ARow] <> '') then
sgWatch.Canvas.Font.Color:= clRed
else
sgWatch.Canvas.Font.Color:= clWindowText;
if ACol < 2 then
begin
Rect.Top:= Rect.Top + ((sgWatch.RowHeights[ARow] -
sgWatch.Canvas.TextHeight(sgWatch.Cells[ACol,ARow]))) div 2;
if ARow = 0 then
Rect.Left:= Rect.Left + (sgWatch.ColWidths[ACol] -
sgWatch.Canvas.TextWidth(sgWatch.Cells[ACol,ARow])) div 2
else
Rect.Left:= Rect.Right - 4 - sgWatch.Canvas.TextWidth(sgWatch.Cells[ACol,ARow]);
sgWatch.Canvas.TextOut(Rect.Left,Rect.Top,sgWatch.Cells[ACol,ARow]);
end
else
if (ARow > 0) and (ACol = 2) then
begin
Item:= _WatchList.Item[ARow-1];
if Assigned(Item) then
case Item.WatchType of
wtRAM : sgWatch.Canvas.CopyRect(Rect,iRAM.Canvas,Bounds(0,0,24,24));
wtIPort : sgWatch.Canvas.CopyRect(Rect,iIPort.Canvas,Bounds(0,0,24,24));
wtOPort : sgWatch.Canvas.CopyRect(Rect,iOPort.Canvas,Bounds(0,0,24,24));
end;
end;
end;
procedure TWatchForm.miCloseClick(Sender: TObject);
begin
Close;
end;
procedure TWatchForm.miStayOnTopClick(Sender: TObject);
begin
if miStayOnTop.Checked then
FormStyle:= fsNormal
else
FormStyle:= fsStayOnTop;
miStayOnTop.Checked:= not miStayOnTop.Checked;
end;
procedure TWatchForm.miAddWatchRAMClick(Sender: TObject);
var
P: TPoint;
result: Integer;
begin
if Assigned(OnRAMRefreshRequest) then
begin
P.X:= Mouse.CursorPos.X;
P.Y:= Mouse.CursorPos.Y;
EditForm.Value:= 0;
if _Radix = rDecimalNeg then result:= EditForm.ShowModal(rDecimal,_View,14,P)
else result:= EditForm.ShowModal(_Radix,_View,14,P);
if (result = mrOk) then
begin
if _WatchList.AddressExists(EditForm.Value,wtRAM) then
MessageDlg(getString(rsExistingAddress),mtInformation,[mbOk],0)
else
begin
_WatchList.Add(EditForm.Value,wtRAM);
sgWatch.RowCount:= _WatchList.Count+1;
sgWatch.Cells[3,sgWatch.RowCount-1];
sgWatch.FixedRows:= 1;
OnRAMRefreshRequest(Self);
end;
end;
end;
end;
procedure TWatchForm.miAddWatchIPORTClick(Sender: TObject);
var
P: TPoint;
result: Integer;
begin
if Assigned(OnIPortsRefreshRequest) then
begin
P.X:= Mouse.CursorPos.X;
P.Y:= Mouse.CursorPos.Y;
EditForm.Value:= Ti8008IPorts.FirstPortNo;
if _Radix = rDecimalNeg then result:= EditForm.ShowModal(rDecimal,vLong,3,P)
else result:= EditForm.ShowModal(_Radix,vLong,3,P);
if (result = mrOk) then
begin
if (EditForm.Value >= Ti8008IPorts.FirstPortNo) and
(EditForm.Value < Ti8008IPorts.FirstPortNo+Ti8008IPorts.Count) then
begin
if _WatchList.AddressExists(EditForm.Value,wtIPort) then
MessageDlg(getString(rsExistingAddress),mtInformation,[mbOk],0)
else begin
_WatchList.Add(EditForm.Value,wtIPort);
sgWatch.RowCount:= _WatchList.Count+1;
sgWatch.Cells[3,sgWatch.RowCount-1];
sgWatch.FixedRows:= 1;
OnIPortsRefreshRequest(Self);
end;
end
else
MessageDlg(getString(rsInvalidPortAddress),mtError,[mbOk],0)
end;
end;
end;
procedure TWatchForm.miAddWatchOPortClick(Sender: TObject);
var
P: TPoint;
result: Integer;
begin
if Assigned(OnIPortsRefreshRequest) then
begin
P.X:= Mouse.CursorPos.X;
P.Y:= Mouse.CursorPos.Y;
EditForm.Value:= Ti8008OPorts.FirstPortNo;
if _Radix = rDecimalNeg then result:= EditForm.ShowModal(rDecimal,vLong,5,P)
else result:= EditForm.ShowModal(_Radix,vLong,5,P);
if (result = mrOk) then
begin
if (EditForm.Value >= Ti8008OPorts.FirstPortNo) and
(EditForm.Value < Ti8008OPorts.FirstPortNo+Ti8008OPorts.Count) then
begin
if _WatchList.AddressExists(EditForm.Value,wtOPort) then
MessageDlg(getString(rsExistingAddress),mtInformation,[mbOk],0)
else
begin
_WatchList.Add(EditForm.Value,wtOPort);
sgWatch.RowCount:= _WatchList.Count+1;
sgWatch.Cells[3,sgWatch.RowCount-1];
sgWatch.FixedRows:= 1;
OnIPortsRefreshRequest(Self);
end;
end
else
MessageDlg(getString(rsInvalidPortAddress),mtError,[mbOk],0)
end;
end;
end;
procedure TWatchForm.miDelWatchClick(Sender: TObject);
begin
if Assigned(OnRAMRefreshRequest) then
begin
_WatchList.Delete(_ARow-1);
sgWatch.RowCount:= _WatchList.Count+1;
OnRAMRefreshRequest(Self);
OnIPortsRefreshRequest(Self);
OnOPortsRefreshRequest(Self);
end;
end;
procedure TWatchForm.miDelAllClick(Sender: TObject);
begin
if Assigned(OnRAMRefreshRequest) and
Assigned(OnIPortsRefreshRequest) and
Assigned(OnOPortsRefreshRequest) then
begin
_WatchList.Clear;
sgWatch.RowCount:= _WatchList.Count+1;
OnRAMRefreshRequest(Self);
OnIPortsRefreshRequest(Self);
OnOPortsRefreshRequest(Self);
end;
end;
procedure TWatchForm.sgWatchSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
begin
CanSelect:= ACol < 3;
if CanSelect then begin
_ARow:= ARow;
_ACol:= ACol;
end;
end;
procedure TWatchForm.sgWatchDblClick(Sender: TObject);
var
C: Boolean;
P: TPoint;
Item: TWatchItem;
result: Integer;
begin
if (_ARow > 0) and (_ACol = 1) then begin
Item:= _WatchList.Item[_ARow-1];
if Assigned(Item) and not (Item.WatchType = wtOPort) then begin
P.X:= Mouse.CursorPos.X;
P.Y:= Mouse.CursorPos.Y;
if Item.WatchType = wtRAM then begin
EditForm.Value:= RadixToWord(sgWatch.Cells[_ACol,_ARow],_Radix,vLong,C);
if (EditForm.ShowModal(_Radix,vLong,8,P) = mrOk) and Assigned(OnRAMUpdateRequest) then
OnRAMUpdateRequest(Item.Address,EditForm.Value);
end else if Item.WatchType = wtIPort then begin
if _Radix = rDecimalNeg then begin
EditForm.Value:= RadixToWord(sgWatch.Cells[_ACol,_ARow],rDecimal,vLong,C);
result:= EditForm.ShowModal(rDecimal,vLong,8,P)
end else begin
EditForm.Value:= RadixToWord(sgWatch.Cells[_ACol,_ARow],_Radix,vLong,C);
result:= EditForm.ShowModal(_Radix,vLong,8,P);
end;
if (result = mrOk) and Assigned(OnIPortsUpdateRequest) then
OnIPortsUpdateRequest(Item.Address,EditForm.Value);
end;
end;
end;
end;
procedure TWatchForm.sgWatchKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then sgWatchDblClick(Sender);
if Key = VK_DELETE then miDelWatchClick(Sender);
end;
procedure TWatchForm.RefreshObject(Sender: TObject);
var
i: Integer;
Bits: Byte;
Item: TWatchItem;
Address: Word;
begin
if Sender is Ti8008RAM then begin
for i:= 0 to _WatchList.Count-1 do begin
Item:= _WatchList.Item[i];
if Assigned(Item) and (Item.WatchType = wtRAM) then begin
Address:= Item.Address;
sgWatch.Cells[0,i+1]:= WordToRadix(Address,_Radix,_View,14);
sgWatch.Cells[1,i+1]:= WordToRadix((Sender as Ti8008RAM).RAM[Address],
_Radix,vLong,8);
end;
end;
end else if (Sender is TIOPorts) then begin
for i:= 0 to _WatchList.Count-1 do begin
Item:= _WatchList.Item[i];
if Assigned(Item) and (Item.WatchType in [wtIPort, wtOPort]) then begin
Address:= Item.Address;
case (Sender as TIOPorts).PortType of
ptIN : Bits:= 3;
ptOUT : Bits:= 5;
else Bits:= 16;
end;
if _Radix = rDecimalNeg then begin
sgWatch.Cells[0,i+1]:= WordToRadix(Address,rDecimal,vLong,Bits);
sgWatch.Cells[1,i+1]:= WordToRadix((Sender as TIOPorts).Value[Address],
rDecimal,vLong,8);
end else begin
sgWatch.Cells[0,i+1]:= WordToRadix(Address,_Radix,vLong,Bits);
sgWatch.Cells[1,i+1]:= WordToRadix((Sender as TIOPorts).Value[Address],
_Radix,vLong,8);
end;
end;
end;
end;
sgWatch.Invalidate;
end;
procedure TWatchForm.Reset(Sender: TObject);
var
i: Integer;
Bits: Byte;
Item: TWatchItem;
Address: Word;
begin
if Sender is Ti8008RAM then begin
for i:= 0 to _WatchList.Count-1 do begin
Item:= _WatchList.Item[i];
if Assigned(Item) and (Item.WatchType = wtRAM) then begin
Address:= Item.Address;
sgWatch.Cells[3,i+1]:= '';
sgWatch.Cells[0,i+1]:= WordToRadix(Address,_Radix,_View,14);
sgWatch.Cells[1,i+1]:= WordToRadix((Sender as Ti8008RAM).RAM[Address],
_Radix,vLong,8);
end;
end;
end else if (Sender is TIOPorts) then begin
for i:= 0 to _WatchList.Count-1 do begin
Item:= _WatchList.Item[i];
if Assigned(Item) and (Item.WatchType = wtIPort) and ((Sender as TIOPorts).PortType = ptIN) then begin
Address:= Item.Address;
Bits:= 3;
sgWatch.Cells[3,i+1]:= '';
if _Radix = rDecimalNeg then begin
sgWatch.Cells[0,i+1]:= WordToRadix(Address,rDecimal,vLong,Bits);
sgWatch.Cells[1,i+1]:= WordToRadix((Sender as TIOPorts).Value[Address],
rDecimal,vLong,8);
end else begin
sgWatch.Cells[0,i+1]:= WordToRadix(Address,_Radix,vLong,Bits);
sgWatch.Cells[1,i+1]:= WordToRadix((Sender as TIOPorts).Value[Address],
_Radix,vLong,8);
end;
end else if Assigned(Item) and (Item.WatchType = wtOPort) and ((Sender as TIOPorts).PortType = ptOUT) then begin
Address:= Item.Address;
Bits:= 5;
sgWatch.Cells[3,i+1]:= '';
if _Radix = rDecimalNeg then begin
sgWatch.Cells[0,i+1]:= WordToRadix(Address,rDecimal,vLong,Bits);
sgWatch.Cells[1,i+1]:= WordToRadix((Sender as TIOPorts).Value[Address],
rDecimal,vLong,8);
end else begin
sgWatch.Cells[0,i+1]:= WordToRadix(Address,_Radix,vLong,Bits);
sgWatch.Cells[1,i+1]:= WordToRadix((Sender as TIOPorts).Value[Address],
_Radix,vLong,8);
end;
end
end;
end;
end;
procedure TWatchForm.RAMUpdate(Sender: TObject; Address: Word; Value: Byte);
var
Index: Integer;
sValue: String;
begin
Index:= _WatchList.FindAddress(Address,wtRAM);
if Index >= 0 then begin
sValue:= WordToRadix(Value,_Radix,vLong,8);
if sValue <> sgWatch.Cells[1,Index+1] then sgWatch.Cells[3,Index+1]:= '*';
sgWatch.Cells[1,Index+1]:= sValue;
end;
end;
procedure TWatchForm.PortUpdate(Sender: TObject; Index: Byte; Value: Byte);
var
lIndex: Integer;
sValue: String;
begin
if (Sender is TIOPorts) then begin
case (Sender as TIOPorts).PortType of
ptIN : lIndex:= _WatchList.FindAddress(Index,wtIPort);
ptOUT : lIndex:= _WatchList.FindAddress(Index,wtOPort);
else lIndex:= -1;
end;
if lIndex >= 0 then begin
if _Radix = rDecimalNeg then sValue:= WordToRadix(Value,rDecimal,vLong,8)
else sValue:= WordToRadix(Value,_Radix,vLong,8);
if sValue <> sgWatch.Cells[1,lIndex+1] then sgWatch.Cells[3,lIndex+1]:= '*';
sgWatch.Cells[1,lIndex+1]:= sValue;
end;
end
end;
procedure TWatchForm.PortAction(Sender: TObject; Active: Boolean);
begin
end;
procedure TWatchForm.BeforeCycle(Sender: TObject);
var
i: Integer;
begin
for i:= 1 to sgWatch.RowCount-1 do
begin
sgWatch.Cells[3,i]:= '';
sgWatch.Cells[1,i]:= sgWatch.Cells[1,i];
end;
end;
procedure TWatchForm.AfterCycle(Sender: TObject);
begin
end;
procedure TWatchForm.StateChange(Sender: TObject; Halt: Boolean);
begin
end;
procedure TWatchForm.LoadData(RegistryList: TRegistryList);
begin
if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,false) then
RegistryList.LoadFormSettings(Self,true);
end;
procedure TWatchForm.SaveData(RegistryList: TRegistryList);
begin
if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,true) then
RegistryList.SaveFormSettings(Self,true);
end;
procedure TWatchForm.LoadLanguage;
begin
Caption:= 'i8008 '+getString(rsWatch);
sgWatch.Cells[0,0]:= getString(rsAddress);
sgWatch.Cells[1,0]:= getString(rsValue);
miAddWatchRAM.Caption:= getString(rsAddWatchRAM);
miAddWatchIPort.Caption:= getString(rsAddWatchIPort);
miAddWatchOPort.Caption:= getString(rsAddWatchOPort);
miDelWatch.Caption:= getString(rsDelWatch);
miDelAll.Caption:= getString(rsDelAll);
miClose.Caption:= getString(rsClose);
miStayOnTop.Caption:= getString(rsStayOnTop);
end;
procedure TWatchForm.RadixChange(Radix: TRadix; View: TView);
begin
_Radix:= Radix;
_View:= View;
end;
end.
|
// -------------------------------------------------------------------------------
// Descrição: O preço de um automóvel é calculado pela soma do preço de fábrica
// com o preço dos impostos (45% do preço de fábrica) e a percentagem do revendedor
// (28% do preço de 4 fábrica). Faça um algoritmo que leia o nome do automóvel
// e o preço de fábrica e imprima o nome do automóvel e o preço final.
// -------------------------------------------------------------------------------
// Autor : Fernando Gomes
// Data : 22/08/2021
// -------------------------------------------------------------------------------
Program Preco_automovel ;
const
imposto = 0.45;
revendedor = 0.28;
var
nome_automovel: String;
prec_fabrica, prec_final: real;
Begin
write('Digite o nome do automóvel: ');
readln(nome_automovel);
write('Digite o preco de fábrica do automóvel: ');
readln(prec_fabrica);
prec_final := (prec_fabrica + (prec_fabrica * imposto) + (prec_fabrica * revendedor));
writeln();
writeln('Nome do automóvel: ',nome_automovel);
writeln('Preço final: ',prec_final:6:2);
End. |
unit TipoRelatorioEditFormUn;
interface
uses
osCustomEditFrm, DB, DBClient, osClientDataset, StdCtrls, Mask,
DBCtrls, Menus, ImgList, Controls, Classes, ActnList, osActionList,
ComCtrls, ToolWin, Buttons, ExtCtrls, acCustomSQLMainDataUn;
type
TTipoRelatorioEditForm = class(TosCustomEditForm)
TipoRelatorioClientDataSet: TosClientDataset;
Label2: TLabel;
NomeEdit: TDBEdit;
TipoRelatorioClientDataSetNOME: TStringField;
Label1: TLabel;
DescricaoEdit: TDBEdit;
TipoRelatorioClientDataSetDESCRICAO: TStringField;
TipoRelatorioClientDataSetIDTIPORELATORIO: TIntegerField;
procedure TipoRelatorioClientDataSetBeforePost(DataSet: TDataSet);
procedure TipoRelatorioClientDataSetAfterApplyUpdates(
Sender: TObject; var OwnerData: OleVariant);
private
public
end;
var
TipoRelatorioEditForm: TTipoRelatorioEditForm;
implementation
uses TipoRelatorioDataUn, osUtils, SQLMainData;
{$R *.DFM}
procedure TTipoRelatorioEditForm.TipoRelatorioClientDataSetBeforePost(DataSet: TDataSet);
begin
inherited;
TipoRelatorioData.Validate(DataSet);
end;
procedure TTipoRelatorioEditForm.TipoRelatorioClientDataSetAfterApplyUpdates(
Sender: TObject; var OwnerData: OleVariant);
begin
inherited;
if TClientDataSet(Sender).UpdateStatus in [usModified, usInserted, usDeleted] then
MainData.UpdateVersion(tnTipoRelatorio);
end;
initialization
OSRegisterClass(TTipoRelatorioEditForm);
end.
|
unit NestedClass;
interface
type
TOne = class
private
someData: Integer;
public
// nested constant
const foo = 12;
// nested type
type TInside = class
type TInsideInside = class
procedure Two;
end;
public
procedure InsideHello;
private
Msg: string;
InsIns: TInsideInside;
end;
public
procedure Hello;
constructor Create;
end;
implementation
uses
SysUtils, NestedTypesForm;
{ TOne }
constructor TOne.Create;
begin
inherited Create;
end;
procedure TOne.Hello;
var
ins: TInside;
begin
ins := TInside.Create;
try
ins.Msg := 'hi';
ins.InsideHello;
Show ('constant is ' + IntToStr (foo));
finally
ins.Free;
end;
end;
{ TOne.TInside }
procedure TOne.TInside.InsideHello;
begin
msg := 'new msg';
Show ('internal call');
if not Assigned (InsIns) then
InsIns := TInsideInside.Create;
InsIns.Two;
end;
{ TOne.TInside.TInsideInside }
procedure TOne.TInside.TInsideInside.Two;
begin
Show ('this is a method of a nested/nested class');
end;
end.
|
{*******************************************************************************
* *
* TksMapView - extended map view component *
* *
* https://bitbucket.org/gmurt/kscomponents *
* *
* Copyright 2017 Graham Murt *
* *
* email: graham@kernow-software.co.uk *
* *
* 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 ksMapView;
interface
{$I ksComponents.inc}
uses
Classes, FMX.Types, FMX.Controls, FMX.Graphics, System.UITypes,
FMX.StdCtrls, System.Generics.Collections, FMX.Objects, FMX.Effects,
System.UIConsts, ksSpeedButton, ksTypes, FMX.Maps, System.Types;
type
TksMapMarker = class;
TksMarkerEvent = procedure(Marker: TksMapMarker) of object;
TksMapMarker = class
private
FMarker: TMapMarker;
FID: string;
FTagStr: string;
function GetSnippet: string;
function GetTitle: string;
public
procedure Remove;
property ID: string read FID;
property Title: string read GetTitle;
//property Marker: TMapMarker read FMarker;
property Snipped: string read GetSnippet;
property TagStr: string read FTagStr write FTagStr;
end;
TksMapMarkers = class(TList<TksMapMarker>)
private
function GetMarkerByID(AID: string): TksMapMarker; public
procedure DeleteMarker(AMarker: TksMapMarker); overload;
procedure DeleteMarker(AMarkerID: string); overload;
property MarkerByID[AID: string]: TksMapMarker read GetMarkerByID;
public
function GetKsMarker(AMarker: TMapMarker): TksMapMarker;
procedure Clear; virtual;
end;
IksMapView = interface
['{AABA39E3-52EB-4344-BF48-5F3DAE1CB6AA}']
procedure SetTilt(const Degrees: Single);
end;
[ComponentPlatformsAttribute(
pidWin32 or
pidWin64 or
{$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or
{$IFDEF XE10_3_OR_NEWER} pidiOSSimulator32 or pidiOSSimulator64 {$ELSE} pidiOSSimulator {$ENDIF} or
{$IFDEF XE10_3_OR_NEWER} pidAndroid32Arm or pidAndroid64Arm {$ELSE} pidAndroid {$ENDIF}
)]
TksMapView = class(TMapView, IksMapView)
private
FMarkers: TksMapMarkers;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function AddMarker(AID: string; ALocation: TMapCoordinate; ATitle, ASnippet: string; AImage: TBitmap): TksMapMarker; overload;
function AddMarker(AID: string; ALat, ALon: Extended; ATitle, ASnippet: string; AImage: TBitmap): TksMapMarker; overload;
property Markers: TksMapMarkers read FMarkers;
published
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
procedure Register;
implementation
uses SysUtils, Math, ksCommon;
procedure Register;
begin
RegisterComponents('Kernow Software FMX', [TksMapView]);
end;
{ TksMapView }
function TksMapView.AddMarker(AID: string; ALocation: TMapCoordinate; ATitle, ASnippet: string; AImage: TBitmap): TksMapMarker;
begin
Result := AddMarker(AID, ALocation.Latitude, ALocation.Longitude, ATitle, ASnippet, AImage);
end;
function TksMapView.AddMarker(AID: string; ALat, ALon: Extended; ATitle, ASnippet: string; AImage: TBitmap): TksMapMarker;
var
ADesc : TMapMarkerDescriptor;
ALastMarker: TksMapMarker;
begin
ALastMarker := FMarkers.MarkerByID[AID];
Result := TksMapMarker.Create;
ADesc := TMapMarkerDescriptor.Create(TMapCoordinate.Create(ALat, ALon), ATitle);
ADesc.Snippet := ASnippet;
ADesc.Icon := AImage;
Result.FMarker := AddMarker(ADesc);
Result.FID := AID;
FMarkers.Add(Result);
if ALastMarker <> nil then
FMarkers.DeleteMarker(ALastMarker);
end;
constructor TksMapView.Create(AOwner: TComponent);
begin
inherited;
FMarkers := TksMapMarkers.Create;
end;
destructor TksMapView.Destroy;
begin
FMarkers.Clear;
FreeAndNil(FMarkers);
inherited;
end;
{ TksMapMarkers }
procedure TksMapMarkers.Clear;
var
Marker: TksMapMarker;
begin
for Marker in Self do
Marker.FMarker.Remove;
inherited Clear;
end;
procedure TksMapMarkers.DeleteMarker(AMarker: TksMapMarker);
begin
AMarker.FMarker.Remove;
Delete(IndexOf(AMarker));
end;
procedure TksMapMarkers.DeleteMarker(AMarkerID: string);
var
Marker: TksMapMarker;
begin
Marker := MarkerByID[AMarkerID];
if Marker <> nil then
DeleteMarker(Marker);
end;
function TksMapMarkers.GetKsMarker(AMarker: TMapMarker): TksMapMarker;
var
Marker: TksMapMarker;
begin
Result := nil;
for Marker in Self do
begin
if Marker.FMarker = AMarker then
begin
Result := Marker;
Exit;
end;
end;
end;
function TksMapMarkers.GetMarkerByID(AID: string): TksMapMarker;
var
Marker: TksMapMarker;
begin
Result := nil;
for Marker in Self do
begin
if Marker.FID = AID then
begin
Result := Marker;
Exit;
end;
end;
end;
{ TksMapMarker }
function TksMapMarker.GetSnippet: string;
begin
Result := FMarker.Descriptor.Snippet;
end;
function TksMapMarker.GetTitle: string;
begin
Result := FMarker.Descriptor.Title;
end;
procedure TksMapMarker.Remove;
begin
FMarker.Remove;
end;
end.
|
// Implement socket transport interfaces using Indy components
unit IndySockTransport;
{$R-}
interface
uses
Classes, SysUtils, IdTCPClient, idTCPConnection, SockTransport;
type
{ TIndyTCPConnectionTransport }
TIndyTCPConnectionTransport = class(TInterfacedObject, ITransport)
private
FEvent: THandle;
FSocket: TIdTCPConnection;
protected
{ ITransport }
function GetWaitEvent: THandle;
function GetConnected: Boolean;
procedure SetConnected(Value: Boolean); virtual;
function Receive(WaitForInput: Boolean; Context: Integer): IDataBlock;
function Send(const Data: IDataBlock): Integer;
public
constructor Create(AConnection: TIdTCPConnection);
destructor Destroy; override;
end;
TIndyTCPClientTransport = class(TIndyTCPConnectionTransport)
private
FSocket: TIdTCPClient;
FHost: string;
FPort: Integer;
protected
{ ITransport }
procedure SetConnected(Value: Boolean); override;
public
constructor Create;
destructor Destroy; override;
property Host: string read FHost write FHost;
property Port: Integer read FPort write FPort;
property Socket: TIdTCPClient read FSocket write FSocket;
end;
implementation
uses
RTLConsts;
{ TIndyTCPConnectionTransport }
constructor TIndyTCPConnectionTransport.Create(AConnection: TIdTCPConnection);
begin
inherited Create;
FSocket := AConnection;
FEvent := 0;
end;
destructor TIndyTCPConnectionTransport.Destroy;
begin
// jmt.!!! SetConnected(False);
inherited Destroy;
end;
function TIndyTCPConnectionTransport.GetWaitEvent: THandle;
begin
(* jmt.!!! FEvent := WSACreateEvent;
WSAEventSelect(FSocket.SocketHandle, FEvent, FD_READ or FD_CLOSE);
*)
Result := FEvent;
end;
function TIndyTCPConnectionTransport.GetConnected: Boolean;
begin
Result := (FSocket <> nil) and (FSocket.Connected);
end;
resourcestring
sNoHost = 'No host';
sSocketReadError = 'Socket read error';
procedure TIndyTCPConnectionTransport.SetConnected(Value: Boolean);
begin
Assert(False, 'Must be implemented by descendent');
end;
function TIndyTCPConnectionTransport.Receive(WaitForInput: Boolean; Context: Integer): IDataBlock;
var
Sig, StreamLen: Integer;
P: Pointer;
begin
Result := nil;
if not WaitForInput then
// jmt.!!! if not FSocket.Binding.Readable(1) then Exit;
Assert(False); // Change this for new Indy
FSocket.ReadBuffer(Sig, Sizeof(Sig));
CheckSignature(Sig);
FSocket.ReadBuffer(StreamLen, SizeOf(StreamLen));
Result := TDataBlock.Create as IDataBlock;
Result.Size := StreamLen;
Result.Signature := Sig;
P := Result.Memory;
Inc(Integer(P), Result.BytesReserved);
FSocket.ReadBuffer(P^, StreamLen);
end;
function TIndyTCPConnectionTransport.Send(const Data: IDataBlock): Integer;
var
P: Pointer;
begin
Result := 0;
P := Data.Memory;
FSocket.WriteBuffer(P^, Data.Size + Data.BytesReserved);
end;
{ TIndyTCPClientTransport }
constructor TIndyTCPClientTransport.Create;
begin
FSocket := TIdTCPClient.Create(nil);
inherited Create(FSocket);
end;
destructor TIndyTCPClientTransport.Destroy;
begin
inherited;
FSocket.Disconnect;
FSocket.Free;
end;
procedure TIndyTCPClientTransport.SetConnected(Value: Boolean);
begin
if GetConnected = Value then Exit;
if Value then
begin
if FHost = '' then
raise ESocketConnectionError.Create(sNoHost);
FSocket.Port := FPort;
FSocket.Host := FHost;
FSocket.Connect;
end
else
FSocket.Disconnect;
end;
end.
|
(**
This module contains the code to install the main wizard into the IDE.
@Version 1.0
@Author David Hoyle
@Date 05 Jan 2018
**)
Unit ITHelper.OTAInterfaces;
Interface
Uses
ToolsAPI;
Function InitWizard(Const BorlandIDEServices : IBorlandIDEServices; RegisterProc : TWizardRegisterProc;
var Terminate: TWizardTerminateProc) : Boolean; StdCall;
Exports
InitWizard Name WizardEntryPoint;
Implementation
Uses
ITHelper.Wizard;
{$INCLUDE 'CompilerDefinitions.inc'}
(**
This is a procedure to initialising the wizard interface when loading the
package as a DLL wizard.
@precon None.
@postcon Initialises the wizard.
@nocheck MissingCONSTInParam
@nohints
@param BorlandIDEServices as an IBorlandIDEServices as a constant
@param RegisterProc as a TWizardRegisterProc
@param Terminate as a TWizardTerminateProc as a reference
@return a Boolean
**)
Function InitWizard(Const BorlandIDEServices : IBorlandIDEServices; RegisterProc : TWizardRegisterProc;
Var Terminate: TWizardTerminateProc) : Boolean; StdCall; //FI:O804
Begin
Result := BorlandIDEServices <> Nil;
If Result Then
RegisterProc(TITHWizard.Create);
End;
End.
|
unit uContador;
interface
uses
uRegistro;
type
TContador = class(TRegistro)
private
fID : Integer; // Toda chave primaria nossa no banco dentro do objeto vai chamar ID
fNome : String;
fCRC : Integer;
procedure SetCRC(const Value: Integer);
procedure SetID(const Value: Integer);
procedure SetNome(const Value: String);
public
property ID : Integer read fID write SetID;
property Nome : String read fNome write SetNome;
property CRC : Integer read fCRC write SetCRC;
constructor create();
end;
implementation
{ TContador }
constructor TContador.create;
begin
end;
procedure TContador.SetCRC(const Value: Integer);
begin
fCRC := Value;
end;
procedure TContador.SetID(const Value: Integer);
begin
fID := Value;
end;
procedure TContador.SetNome(const Value: String);
begin
fNome := Value;
end;
end.
|
unit classe.professor;
interface
Uses TEntity, AttributeEntity, SysUtils, classe.disciplina, Generics.Collections;
type
[TableName('PROFESSOR')]
TProfessor = class(TGenericEntity)
private
FIdProfessor:integer;
FNome:string;
FDisciplinas : TList<TDisciplina>;
procedure setIdProfessor(const Value: integer);
procedure setNome(value:string);
public
[KeyField('IDPROFESSOR')]
[FieldName('IDPROFESSOR')]
property Codigo: integer read FIdProfessor write setIdProfessor;
[FieldName('NOME')]
property Nome :string read FNome write setNome;
[ManyValuedAssociation(ftEager, orRequired, ctCascadeAll)]
[ForeignJoinColumn('IDDISCIPLINA', [cpRequired])]
property Itens: TList<TDisciplina> read FDisciplinas write FDisciplinas;
function ToString:string; override;
end;
implementation
procedure TProfessor.setIdProfessor(const Value: integer);
begin
FIdProfessor := Value;
end;
procedure TProfessor.setNome(value: string);
begin
FNome := Value;
end;
function TProfessor.toString;
begin
result := ' Código : '+ IntToStr(Codigo) + ' Nome: '+ Nome;
end;
end.
|
unit TextTokenizer;
interface
uses
Classes, Character, RegularExpressions, Generics.Collections, SysUtils;
type
TTextTokenizer = class
private type
TPatterns = class
private const
Word = '[à-ÿ¸]+';
UnsupportedCharacters = '[^-!,:;\.\?\sà-ÿ¸]';
WhitespaceCharacters = '\s+';
UnifiedWhitespaceCharacter = ' ';
EndSentenceCharacters = '[!;\.\?]+';
UnifiedEndSentenceCharacter = '.';
MultipleColonsWithWhitespaces = ':[:\s]+';
SingleColon = ':';
MultipleHyphensWithWhitespaces = '-[-\s]+';
SingleHyphen = '-';
MultipleComasWithWhitespaces = ',[,\s]+';
SingleComa = ',';
SingleHyphenBetweenWords = '(?<=[à-ÿ¸])-(?=[à-ÿ¸])';
Colons = ' *: *';
UnifiedColon = ': ';
Hyphens = ' *- *';
UnifiedHyphen = ' - ';
Comas = ' *, *';
UnifiedComa = ', ';
EndOfTheSentence = '\. ?';
EndOfTheSentenceForSplit = '__END__';
end;
public type
TUnitType = (utNone, utHyphen, utExclamationMark, utComa, utColon, utSemicolon, utDot, utQuestionMark, utSpace, utWord);
TSentenceUnit = record
UnitType: TUnitType;
Text: String;
end;
private
FRegex: TRegEx;
private
function DeleteUnsupportedCharacters(AText: String): String;
function DeleteSingleHyphens(AText: String): String;
function ShrinkWhitespaceCharacters(AText: String): String;
function ShrinkEndSentenceCharacters(AText: String): String;
function ShrinkColons(AText: String): String;
function ShrinkHyphens(AText: String): String;
function ShrinkComas(AText: String): String;
function VerifyAndFixColons(AText: String): String;
function VerifyAndFixHyphens(AText: String): String;
function VerifyAndFixComas(AText: String): String;
function TranslateTextIntoLowercase(AText: String): String;
function SplitTextIntoSentences(AText: String): TArray<String>;
function DeleteEmptySentences(ASentences: TArray<String>): TArray<String>;
public
function GetCleanText(AText: String): String;
function GetCleanSentences(AText: String): TArray<String>;
function GetTokenizedSentence(ASentence: String): TArray<TSentenceUnit>;
function GetTokenizedSentences(AText: String): TArray<TArray<TSentenceUnit>>;
end;
implementation
function TTextTokenizer.DeleteEmptySentences(ASentences: TArray<String>): TArray<String>;
var
Sentences: TStringList;
i: Integer;
begin
Sentences := TStringList.Create;
FRegex := TRegEx.Create(TPatterns.Word);
for i := Low(ASentences) to High(ASentences) do
begin
if (FRegex.Match(ASentences[i]).Success) then
begin
Sentences.Add(ASentences[i]);
end;
end;
Result := Sentences.ToStringArray;
FreeAndNil(Sentences);
end;
function TTextTokenizer.DeleteSingleHyphens(AText: String): String;
begin
FRegex.Create(TPatterns.SingleHyphenBetweenWords);
Result := FRegex.Replace(AText, nil);
end;
function TTextTokenizer.DeleteUnsupportedCharacters(AText: String): String;
begin
FRegex.Create(TPatterns.UnsupportedCharacters, [roIgnoreCase]);
Result := FRegex.Replace(AText, nil);
end;
function TTextTokenizer.GetCleanSentences(AText: String): TArray<String>;
var
Text: String;
begin
Text := GetCleanText(AText);
Result := SplitTextIntoSentences(Text);
Result := DeleteEmptySentences(Result);
end;
function TTextTokenizer.GetCleanText(AText: String): String;
begin
Result := DeleteUnsupportedCharacters(AText);
Result := DeleteSingleHyphens(Result);
Result := ShrinkWhitespaceCharacters(Result);
Result := ShrinkEndSentenceCharacters(Result);
Result := ShrinkColons(Result);
Result := ShrinkHyphens(Result);
Result := ShrinkComas(Result);
Result := VerifyAndFixColons(Result);
Result := VerifyAndFixHyphens(Result);
Result := VerifyAndFixComas(Result);
Result := TranslateTextIntoLowercase(Result);
end;
function TTextTokenizer.GetTokenizedSentence(ASentence: String): TArray<TSentenceUnit>;
var
Units: TList<TSentenceUnit>;
SentenceUnit: TSentenceUnit;
MatchCollection: TMatchCollection;
i: Integer;
begin
Units := TList<TSentenceUnit>.Create;
FRegex.Create('(?<Hyphen>-)|(?<ExclamationMark>!)|(?<Coma>,)|(?<Colon>:)|(?<Semicolon>;)|(?<Dot>\.)|(?<QuestionMark>\?)|(?<Space>\s)|(?<Word>[à-ÿ¸]+)');
MatchCollection := FRegex.Matches(ASentence);
for i := 0 to MatchCollection.Count - 1 do
begin
case MatchCollection.Item[i].Groups.Count of
0:
begin
SentenceUnit.Text := '';
SentenceUnit.UnitType := utNone
end;
1:
begin
SentenceUnit.Text := '';
SentenceUnit.UnitType := utNone;
end;
2:
begin
SentenceUnit.Text := MatchCollection.Item[i].Groups.Item[1].Value;
SentenceUnit.UnitType := utHyphen;
end;
3:
begin
SentenceUnit.Text := MatchCollection.Item[i].Groups.Item[2].Value;
SentenceUnit.UnitType := utExclamationMark;
end;
4:
begin
SentenceUnit.Text := MatchCollection.Item[i].Groups.Item[3].Value;
SentenceUnit.UnitType := utComa;
end;
5:
begin
SentenceUnit.Text := MatchCollection.Item[i].Groups.Item[4].Value;
SentenceUnit.UnitType := utColon;
end;
6:
begin
SentenceUnit.Text := MatchCollection.Item[i].Groups.Item[5].Value;
SentenceUnit.UnitType := utSemicolon;
end;
7:
begin
SentenceUnit.Text := MatchCollection.Item[i].Groups.Item[6].Value;
SentenceUnit.UnitType := utDot;
end;
8:
begin
SentenceUnit.Text := MatchCollection.Item[i].Groups.Item[7].Value;
SentenceUnit.UnitType := utQuestionMark;
end;
9:
begin
SentenceUnit.Text := MatchCollection.Item[i].Groups.Item[8].Value;
SentenceUnit.UnitType := utSpace;
end;
10:
begin
SentenceUnit.Text := MatchCollection.Item[i].Groups.Item[9].Value;
SentenceUnit.UnitType := utWord;
end;
end;
Units.Add(SentenceUnit);
end;
Result := Units.ToArray;
FreeAndNil(Units);
end;
function TTextTokenizer.GetTokenizedSentences(AText: String): TArray<TArray<TSentenceUnit>>;
var
TokenizedSentences: TList<TArray<TSentenceUnit>>;
Sentences: TArray<String>;
i: Integer;
begin
TokenizedSentences := TList < TArray < TSentenceUnit >>.Create;
Sentences := GetCleanSentences(AText);
for i := Low(Sentences) to High(Sentences) do
begin
TokenizedSentences.Add(GetTokenizedSentence(Sentences[i]));
end;
Result := TokenizedSentences.ToArray;
FreeAndNil(TokenizedSentences);
end;
function TTextTokenizer.ShrinkColons(AText: String): String;
begin
FRegex.Create(TPatterns.MultipleColonsWithWhitespaces);
Result := FRegex.Replace(AText, TPatterns.SingleColon);
end;
function TTextTokenizer.ShrinkComas(AText: String): String;
begin
FRegex.Create(TPatterns.MultipleComasWithWhitespaces);
Result := FRegex.Replace(AText, TPatterns.SingleComa);
end;
function TTextTokenizer.ShrinkEndSentenceCharacters(AText: String): String;
begin
FRegex.Create(TPatterns.EndSentenceCharacters);
Result := FRegex.Replace(AText, TPatterns.UnifiedEndSentenceCharacter);
end;
function TTextTokenizer.ShrinkHyphens(AText: String): String;
begin
FRegex.Create(TPatterns.MultipleHyphensWithWhitespaces);
Result := FRegex.Replace(AText, TPatterns.SingleHyphen);
end;
function TTextTokenizer.ShrinkWhitespaceCharacters(AText: String): String;
begin
FRegex.Create(TPatterns.WhitespaceCharacters);
Result := FRegex.Replace(AText, TPatterns.UnifiedWhitespaceCharacter);
end;
function TTextTokenizer.SplitTextIntoSentences(AText: String): TArray<String>;
var
Text: String;
begin
FRegex.Create(TPatterns.EndOfTheSentence);
Text := FRegex.Replace(AText, TPatterns.UnifiedEndSentenceCharacter + TPatterns.EndOfTheSentenceForSplit);
FRegex.Create(TPatterns.EndOfTheSentenceForSplit);
Result := FRegex.Split(Text);
end;
function TTextTokenizer.TranslateTextIntoLowercase(AText: String): String;
begin
Result := ToLower(AText);
end;
function TTextTokenizer.VerifyAndFixComas(AText: String): String;
begin
FRegex.Create(TPatterns.Comas);
Result := FRegex.Replace(AText, TPatterns.UnifiedComa);
end;
function TTextTokenizer.VerifyAndFixColons(AText: String): String;
begin
FRegex.Create(TPatterns.Colons);
Result := FRegex.Replace(AText, TPatterns.UnifiedColon);
end;
function TTextTokenizer.VerifyAndFixHyphens(AText: String): String;
begin
FRegex.Create(TPatterns.Hyphens);
Result := FRegex.Replace(AText, TPatterns.UnifiedHyphen);
end;
end.
|
unit intensive.Controller.DTO.Interfaces;
interface
uses
intensive.Services.Generic,
intensive.Model.Entity.Cliente;
type
iClienteDTO = interface
function Id(Value : Integer) : iClienteDTO; overload;
function Id : Integer; overload;
function Nome(Value : String) : iClienteDTO; overload;
function Nome : String; overload;
function Telefone(Value : String) : iClienteDTO; overload;
function Telefone : String; overload;
function Build : iService<TCliente>;
end;
implementation
end.
|
unit untRoleManager;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, RzPanel, GridsEh, DBGridEh, ExtCtrls, DB,
Menus, ActnList, StdCtrls, Mask, RzEdit, RzDBEdit, RzLabel, RzButton,
ImgList, DBGridEhGrouping;
type
TfrmRoleManager = class(TForm)
pnlTop: TPanel;
pnlCenter: TPanel;
dgeRoleList: TDBGridEh;
RzToolbar1: TRzToolbar;
btnCreate: TRzToolButton;
btnDelete: TRzToolButton;
btnUpdate: TRzToolButton;
btnOK: TRzToolButton;
btnCancel: TRzToolButton;
ilRoleManager: TImageList;
lblRoleName: TRzLabel;
lblRemark: TRzLabel;
edtRoleName: TRzDBEdit;
edtRoleRemark: TRzDBEdit;
actlstRoleManager: TActionList;
actCreateRole: TAction;
actDeleteRole: TAction;
actUpdateRole: TAction;
actSetPermission: TAction;
pmRoleManager: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
btnExit: TRzToolButton;
btnRefresh: TRzToolButton;
actRefresh: TAction;
procedure actCreateRoleExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actDeleteRoleExecute(Sender: TObject);
procedure actUpdateRoleExecute(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure actSetPermissionExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnExitClick(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
private
procedure SetButtonEnable;
public
{ Public declarations }
end;
//var
// frmRoleManager: TfrmRoleManager;
implementation
uses untSysManagerDM, untSetPrivilege, untCommonUtil;
{$R *.dfm}
procedure TfrmRoleManager.FormCreate(Sender: TObject);
begin
frmSysManagerDM.qryRoleList.Open;
end;
procedure TfrmRoleManager.SetButtonEnable;
begin
//按钮
btnCreate.Enabled := not btnCreate.Enabled;
btnDelete.Enabled := not btnDelete.Enabled;
btnUpdate.Enabled := not btnUpdate.Enabled;
btnOK.Enabled := not btnOK.Enabled;
btnCancel.Enabled := not btnCancel.Enabled;
//编辑框
edtRoleName.ReadOnly := not edtRoleName.ReadOnly;
edtRoleRemark.ReadOnly := not edtRoleRemark.ReadOnly;
//表格
dgeRoleList.Enabled := not dgeRoleList.Enabled;
end;
//增加角色
procedure TfrmRoleManager.actCreateRoleExecute(Sender: TObject);
begin
SetButtonEnable;
if frmSysManagerDM.qryRoleList.State <> dsBrowse then
begin
frmSysManagerDM.qryRoleList.Cancel;
end;
frmSysManagerDM.qryRoleList.Append;
frmSysManagerDM.qryRoleList.FieldByName('create_date').AsDateTime := Date;
end;
//删除角色
procedure TfrmRoleManager.actDeleteRoleExecute(Sender: TObject);
begin
if Application.MessageBox('确定删除记录?', '提示', MB_OKCANCEL +
MB_DEFBUTTON2) = IDOK then
begin
SetButtonEnable;
if frmSysManagerDM.qryRoleList.State <> dsBrowse then
begin
frmSysManagerDM.qryRoleList.Cancel;
end;
frmSysManagerDM.qryRoleList.Delete;
SetButtonEnable;
end;
end;
//修改角色
procedure TfrmRoleManager.actUpdateRoleExecute(Sender: TObject);
begin
SetButtonEnable;
if frmSysManagerDM.qryRoleList.State <> dsBrowse then
begin
frmSysManagerDM.qryRoleList.Cancel;
end;
frmSysManagerDM.qryRoleList.Edit;
end;
//确定
procedure TfrmRoleManager.btnOKClick(Sender: TObject);
begin
if frmSysManagerDM.qryRoleList.State <> dsBrowse then
begin
frmSysManagerDM.qryRoleList.Post;
end;
SetButtonEnable;
end;
//取消
procedure TfrmRoleManager.btnCancelClick(Sender: TObject);
begin
if frmSysManagerDM.qryRoleList.State <> dsBrowse then
begin
frmSysManagerDM.qryRoleList.Cancel;
end;
SetButtonEnable;
end;
//设置权限
procedure TfrmRoleManager.actSetPermissionExecute(Sender: TObject);
begin
if frmSysManagerDM.qryRoleList.RecordCount > 0 then
ShowModalForm(TfrmSetPrivilege)
else
ShowMessage('请选择角色!');
end;
procedure TfrmRoleManager.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
frmSysManagerDM.qryRoleList.Close;
end;
//退出窗口
procedure TfrmRoleManager.btnExitClick(Sender: TObject);
begin
Self.Close;
end;
procedure TfrmRoleManager.actRefreshExecute(Sender: TObject);
begin
frmSysManagerDM.qryRoleList.Refresh;
end;
end.
|
unit mGMV_GridGraph;
{
================================================================================
*
* Application: Vitals
* Revision: $Revision: 2 $ $Modtime: 8/14/09 2:03p $
* Developer: ddomain.user@domain.ext/doma.user@domain.ext
* Site: Hines OIFO
*
* Description: Manages both tabular and graphical display of a patients
* vitals records. Uses the TChart component which requires
* the Delphi DB components be on the palette as well.
*
* Notes:
*
================================================================================
* $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSVIEW/mGMV_GridGraph.pas $
*
* $History: mGMV_GridGraph.pas $
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 8/20/09 Time: 10:15a
* Updated in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSVIEW
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSVIEW
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:39p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSVIEW
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSVIEW
*
* ***************** Version 7 *****************
* User: Zzzzzzandria Date: 6/17/08 Time: 4:04p
* Updated in $/Vitals/5.0 (Version 5.0)/VitalsGUI2007/Vitals/VITALSVIEW
*
* ***************** Version 4 *****************
* User: Zzzzzzandria Date: 2/20/08 Time: 1:42p
* Updated in $/Vitals GUI 2007/Vitals/VITALSVIEW
* Build 5.0.23.0
*
* ***************** Version 3 *****************
* User: Zzzzzzandria Date: 1/07/08 Time: 6:52p
* Updated in $/Vitals GUI 2007/Vitals/VITALSVIEW
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 7/17/07 Time: 2:30p
* Updated in $/Vitals GUI 2007/Vitals-5-0-18/VITALSVIEW
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/14/07 Time: 10:31a
* Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSVIEW
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 6/13/06 Time: 11:15a
* Updated in $/Vitals/VITALS-5-0-18/VitalsView
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:44p
* Created in $/Vitals/VITALS-5-0-18/VitalsView
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:33p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsView
*
* ***************** Version 4 *****************
* User: Zzzzzzandria Date: 7/22/05 Time: 3:51p
* Updated in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsView
*
* ***************** Version 3 *****************
* User: Zzzzzzandria Date: 7/06/05 Time: 12:11p
* Updated in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsView
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 6/03/05 Time: 6:02p
* Updated in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsView
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 5:04p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsView
*
*
================================================================================
}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
Grids,
ExtCtrls,
Chart,
Buttons,
ExtDlgs,
Menus, ActnList, ImgList, ComCtrls
, mGMV_MDateTime, TeeProcs, Series, TeEngine, StdActns, System.Actions,
VclTee.TeeGDIPlus, System.ImageList
;
type
TStringToDouble = Function(aString: String): Double;
TfraGMV_GridGraph = class(TFrame)
pnlMain: TPanel;
ActionList1: TActionList;
acResizeGraph: TAction;
acPrintGraph: TAction;
acValueCaptions: TAction;
ImageList1: TImageList;
acGraphButtons: TAction;
pnlGridGraph: TPanel;
splGridGraph: TSplitter;
pnlGraph: TPanel;
pnlGrid: TPanel;
grdVitals: TStringGrid;
pnlDateRange: TPanel;
acEnterVitals: TAction;
ac3D: TAction;
pnlTitle: TPanel;
pnlPtInfo: TPanel;
Panel9: TPanel;
lblHospital: TLabel;
Label6: TLabel;
pnlActions: TPanel;
sbEnterVitals: TSpeedButton;
pnlGraphBackground: TPanel;
chrtVitals: TChart;
pnlGridTop: TPanel;
pnlGSelect: TPanel;
acOptions: TAction;
Label1: TLabel;
pnlDateRangeInfo: TPanel;
Label11: TLabel;
lblDateFromTitle: TLabel;
pnlGBot: TPanel;
pnlGTop: TPanel;
pnlGLeft: TPanel;
pnlGRight: TPanel;
sbEnteredInError: TSpeedButton;
acEnteredInError: TAction;
acCustomRange: TAction;
pnlGraphOptions: TPanel;
PopupMenu1: TPopupMenu;
cbValues: TCheckBox;
ckb3D: TCheckBox;
cbAllowZoom: TCheckBox;
acZoom: TAction;
acGraphOptions: TAction;
ShowHideGraphOptions1: TMenuItem;
Panel5: TPanel;
pnlPTop: TPanel;
pnlPRight: TPanel;
pnlPLeft: TPanel;
pnlPBot: TPanel;
pnlDateRangeTop: TPanel;
lbDateRange: TListBox;
Panel6: TPanel;
lblDateRange: TLabel;
acEnteredInErrorByTime: TAction;
N1: TMenuItem;
MarkasEnteredInError1: TMenuItem;
N2: TMenuItem;
Print1: TMenuItem;
acPatientAllergies: TAction;
sbtnAllergies: TSpeedButton;
ColorSelect1: TColorSelect;
ColorDialog1: TColorDialog;
cbChrono: TCheckBox;
cbxGraph: TComboBox;
SelectGraphColor1: TMenuItem;
EnterVitals1: TMenuItem;
Allergies1: TMenuItem;
Panel4: TPanel;
trbHGraph: TTrackBar;
Bevel1: TBevel;
Bevel2: TBevel;
Bevel3: TBevel;
acZoomOut: TAction;
acZoomIn: TAction;
acZoomReset: TAction;
pnlRight: TPanel;
pnlDebug: TPanel;
pnlZoom: TPanel;
sbPlus: TSpeedButton;
sbMinus: TSpeedButton;
sbReset: TSpeedButton;
edZoom: TEdit;
PrintDialog1: TPrintDialog;
sbTest: TStatusBar;
Series2: TLineSeries;
Series3: TLineSeries;
Series1: TLineSeries;
acUpdateGridColors: TAction;
UpdateGridColors1: TMenuItem;
acPatientInfo: TAction;
edPatientName: TEdit;
edPatientInfo: TEdit;
acVitalsReport: TAction;
acRPCLog: TAction;
pnlGSelectLeft: TPanel;
pnlGSelectRight: TPanel;
pnlGSelectBottom: TPanel;
pnlGSelectTop: TPanel;
acShowGraphReport: TAction;
procedure cbxDateRangeClick(Sender: TObject);
procedure cbxGraphChange(Sender: TObject);
procedure ShowHideLabels(Sender: TObject);
procedure chrtVitalsClickSeries(Sender: TCustomChart; Series: TChartSeries;
ValueIndex: integer; Button: TMouseButton; Shift: TShiftState; x,
Y: integer);
procedure chrtVitalsAfterDraw(Sender: TObject);
procedure sbtnPrintGraphClick(Sender: TObject);
procedure sbtnLabelsClick(Sender: TObject);
procedure sbtnMaxGraphClick(Sender: TObject);
procedure grdVitalsDrawCell(Sender: TObject; ACol, ARow: integer;
Rect: TRect; State: TGridDrawState);
procedure grdVitalsSelectCell(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; x, Y: integer);
procedure acResizeGraphExecute(Sender: TObject);
procedure acPrintGraphExecute(Sender: TObject);
procedure acValueCaptionsExecute(Sender: TObject);
procedure acEnterVitalsExecute(Sender: TObject);
procedure ac3DExecute(Sender: TObject);
procedure lbDateRangeMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Panel9Resize(Sender: TObject);
procedure scbHGraphChange(Sender: TObject);
procedure chrtVitalsResize(Sender: TObject);
procedure cbxGraphExit(Sender: TObject);
procedure cbxGraphEnter(Sender: TObject);
procedure lbDateRangeExit(Sender: TObject);
procedure lbDateRangeEnter(Sender: TObject);
procedure grdVitalsEnter(Sender: TObject);
procedure grdVitalsExit(Sender: TObject);
procedure acEnteredInErrorExecute(Sender: TObject);
procedure acCustomRangeExecute(Sender: TObject);
procedure lbDateRangeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure acZoomExecute(Sender: TObject);
procedure acGraphOptionsExecute(Sender: TObject);
procedure acEnteredInErrorByTimeExecute(Sender: TObject);
procedure acPatientAllergiesExecute(Sender: TObject);
procedure ColorSelect1Accept(Sender: TObject);
procedure sbGraphColorClick(Sender: TObject);
procedure cbChronoClick(Sender: TObject);
procedure lbDateRangeMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure chrtVitalsBeforeDrawSeries(Sender: TObject);
procedure grdVitalsTopLeftChanged(Sender: TObject);
procedure chrtVitalsClickLegend(Sender: TCustomChart;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure acZoomOutExecute(Sender: TObject);
procedure acZoomInExecute(Sender: TObject);
procedure acZoomResetExecute(Sender: TObject);
procedure splGridGraphMoved(Sender: TObject);
procedure chrtVitalsDblClick(Sender: TObject);
procedure acUpdateGridColorsExecute(Sender: TObject);
procedure pnlPtInfoEnter(Sender: TObject);
procedure pnlPtInfoExit(Sender: TObject);
procedure acPatientInfoExecute(Sender: TObject);
procedure acVitalsReportExecute(Sender: TObject);
procedure pnlPtInfoMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pnlPtInfoMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure grdVitalsMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure acRPCLogExecute(Sender: TObject);
procedure acShowGraphReportExecute(Sender: TObject);
private
fAxisMax,
fAxisMin: Double;
bLabelShow: Boolean;
bIgnoreBlueLines: Boolean;
fXL,fXR: LongInt; // X coordinates of the Blue Lines
FbgColor: TColor; // graph bg color
FbgTodayColor: TColor; // graph bg color
ptName:String;
ptInfo: String;
FPatientDFN: string; // parent copy to enter vitals, to retreive data
FMDateTimeRange: TMDateTimeRange; // parent copy to retreive data
FObservationRange: String; // string copy of the above
FPatientLocation: String; // parent copy to enter vitals
FPatientLocationName:String;
fGridRow:Integer;
fGraphIndex:Integer;
fFrameInitialized: Boolean;
FStyle:String; // fsVitals or fsDLL
FCurrentPoint: Integer;
fSelectedDateTime:TDateTime; // entered in error
iIgnoreCount:Integer;
iIgnoreGraph:Integer;
function MetricValueString(_Row_:Integer;_Value_:String):String;// AAN 06/24/2002
procedure drawMissingDataLines(Sender: TObject);
procedure drawMissingLines(aStartPoint,aStopPoint:Integer);
procedure maximizeGraph(Sender: TObject);
// procedure printGraph(Sender: TObject);
procedure setPatientDFN(const Value: string);
procedure getVitalsData(aFrom,aTo:String);
procedure GraphDataByIndex(anIndex:Integer);
procedure getGraphByName(aName:String);
procedure setGraphIndex(anIndex:Integer);
procedure setStyle(aStyle:String);
procedure setPatientLocation(aLocation:String);
procedure setPatientLocationName(aLocationName:String);
procedure setMDateTimeRange(aMDTR: TMDateTimeRange);
procedure setTRP;
procedure setBP;
procedure setBPWeight;
procedure setHW;
procedure setSingleGraph(anIndex:Integer;aName:String;
aConverter:TStringToDouble = nil);
procedure setSingleVital(aRow:Integer;aSeria:Integer=0;aName:String='';
aConverter:TStringToDouble = nil);
procedure setSeriesAxis(TheSeries:Array of Integer);
procedure setCurrentPoint(aValue: Integer);
procedure setGridPosition(aPosition: Integer);
procedure setObservationRange(aRange:String);
procedure setTrackBarLimits;
procedure updateLists;
procedure setColor(aColor:TColor);
procedure setTodayColor(aColor:TColor);
function GraphNameByGridRow(aRow:Integer):String;
function GridRowByGraphIndex(anIndex:Integer):Integer;
function getDefaultGridPosition: Integer;
// procedure setPatientInfoView(aName,anInfo:String);
function getPatientName:String;
function getPatientInfo:String;
function GridScrollBarIsVisible:Boolean;
procedure ShowGraphReport;
public
PackageSignature: String; //?
InputTemplateName: String;
procedure setGraphTitle(aFirst,aSecond: String);
procedure updateTimeLabels;
procedure updateFrame(Reload:Boolean=True);
procedure setUpFrame;
procedure saveStatus;
procedure restoreUserPreferences;
procedure setGraphByABBR(aABBR:String);
procedure showVitalsReport;
published
property BGColor: TColor read fBGColor write SetColor;
property BGTodayColor: TColor read fBGTodayColor write SetTodayColor;
property FrameInitialized: Boolean read FFrameInitialized write FFrameInitialized;
property GraphIndex: Integer read FGraphIndex write setGraphIndex; //needs update
property FrameStyle: String read FStyle write SetStyle; //CPRS or Vitals
property PatientDFN: string read FPatientDFN write SetPatientDFN;
property PatientLocation: string read FPatientLocation write SetPatientLocation;
property PatientLocationName:string read FPatientLocationName write SetPatientLocationName;
property MDateTimeRange: TMDateTimeRange read FMDateTimeRange write setMDateTimeRange;
property CurrentPoint: Integer read FCurrentPoint write setCurrentPoint;
property ObservationRange: String read FObservationRange write setObservationRange;
property IgnoreCount: Integer read iIgnoreCount write iIgnoreCount;
property GridRow: Integer read fGridRow write fGridRow;
function GraphIndexByGridRow(aRow:Integer):Integer;
end;
const
fsVitals = 'Vitals';
fsDLL = 'Dll';
implementation
uses
fGMV_DateRange,
fGMV_ShowSingleVital
, uGMV_Const
, uGMV_GlobalVars
, uGMV_User
, uGMV_Utils
, fGMV_InputLite
, uGMV_Engine
, fGMV_EnteredInError
, fGMV_PtInfo, uGMV_VitalTypes
, uGMV_Common
, Math
, Clipbrd, Printers
, fGMV_UserSettings, fGMV_RPCLog
{$IFNDEF DLL}
, fGMV_UserMain
{$ENDIF}
, uGMV_Log
, System.Types;
{$R *.DFM}
const
rHeader = 0;
rTemp = 1;
rPulse = 2;
rResp = 3;
rPOx = 4;
rBP = 6;
rWeight = 7;
rBMI = 8;
rHeight = 9;
rGirth = 10;
rCVP = 11;
rIntake = 12;
rOutput = 13;
rPain = 14;
rLocation = 15;
rEnteredBy = 16;
rSource = 17; // Data Source
// Graph names================================================================
sgnNoGraph = 'No Graph';
sgnTRP = 'TPR';
sgnBP = 'B/P';
sgnHW = 'Height/Weight';
sgnPOX = 'Pulse Ox.';
sgnBPWeight = 'B/P -- Weight';
sgnTemp = 'Temperature';
sgnPulse = 'Pulse';
sgnResp = 'Respiration';// Cells[0, 4] := ' P Ox %:'; //AAN 2003/06/03
sgnWeight = 'Weight'; // Cells[0, 7] := ' Wt (lbs):';
sgnBMI = 'BMI'; // Cells[0, 8] := ' BMI:';
sgnHeight = 'Height'; // Cells[0, 9] := ' Ht (in):';
sgnGirth = 'C/G'; // Cells[0, 10] := ' C/G:';
sgnCVP = 'CVP'; // Cells[0, 11] := ' CVP (cmH2O):';
sgnIn = 'Intake'; // Cells[0, 12] := ' In 24hr (c.c.):';
sgnOutput = 'Output'; // Cells[0, 13] := ' Out 24hr (c.c.):';
sgnPain = 'Pain'; // Cells[0, 14] := ' Pain:';
iMaximumLimit = 2000;
sNoData = 'NO DATA';
////////////////////////////////////////////////////////////////////////////////
function BPMeanBP(aString:String):Double;
begin
Result := BPMean(aString);
end;
function BPDias(aString:String):Double;
var
s2,s3:String;
begin
s2 := Piece(Piece(aString,'/',2),' ',1);
s3 := Piece(Piece(aString,'/',3),' ',1);
if s3 = '' then
Result := iVal(s2)
else
Result := iVal(s3);
end;
function PainNo99(aString:String):Double;
begin
if trim(aString) = '99' then
Result := iIgnore
else
Result := iVal(aString);
end;
//////////////////////////////////////////////////////////////////////////////
function getDateTime(aString:String):String;
var
sDate,sTime:String;
const
// sValid = '24:00:00'; // 061227 zzzzzzandria
sValid = '23:59:59';
begin
// Result := Piece(aString, '^', 1) + ' ' + Piece(aString, '^', 2); // Date Time
// zzzzzzandria 060920 -- 148503 ----------------------------------------- Start
sDate := Piece(aString, '^', 1);
sTime := Piece(aString, '^', 2);
// 061228 zzzzzzandria: 24:00:00 is corrected when data is added to the series only.
// no need to change data in the Grid header.
// if sTime = '24:00:00' then sTime := sValid
// else if sTime = '00:00:00' then sTime := sValid
;
// zzzzzzandria 2007-07-17 Remedy 148503 --------------------------- begin
// assuming '00:00:00' is a valid time for I/O only
if sTime = '00:00:00' then sTime := sValid;
// zzzzzzandria 2007-07-17 Remedy 148503 ----------------------------- end
Result := sDate + ' ' + sTime;
// zzzzzzandria 060920 -- 148503 ----------------------------------------- End
end;
function getTemperature(aString:String):String;
begin
Result := Piece(Piece(aString, '^', 3), '-', 1) + Piece(Piece(aString, '^', 3), '-', 2); //temperature
end;
function getPulse(aString:String):String;
var
s1,s2:String;
begin
s1 := Piece(Piece(aString, '^', 4), '-', 1);
s2 := Piece(Piece(aString, '^', 4), '-', 2);
while pos(' ',s2)=1 do
s2 := copy(s2,2,length(s2)-1);
Result := s1 + ' ' +Piece(s2, ' ', 1) + ' ' +
Piece(s2, ' ', 2) + ' ' +
Piece(s2, ' ', 3) + ' ' +
Piece(s2, ' ', 4);
end;
function getRespiration(aString:String):String;
begin
Result := Piece(Piece(aString, '^', 5), '-', 1) +Piece(Piece(aString, '^', 5), '-', 2); // Respiratory
end;
function getBP(aString:String):String;
begin
Result := Piece(Piece(aString, '^', 7), '-', 1) + ' ' + Piece(Piece(aString, '^', 7), '-', 2);
end;
function getWeight(aString:String):String;
begin
Result := Piece(Piece(aString, '^', 8), '-', 1) + Piece(Piece(aString, '^', 8), '-', 2);
end;
////////////////////////////////////////////////////////////////////////////////
procedure PrintBitmap(Canvas: TCanvas; DestRect: TRect; Bitmap: TBitmap);
var
BitmapHeader: pBitmapInfo;
BitmapImage : POINTER;
HeaderSize : DWORD; // Use DWORD for D3-D5 compatibility
ImageSize : DWORD;
begin
GetDIBSizes(Bitmap.Handle, HeaderSize, ImageSize);
GetMem(BitmapHeader, HeaderSize);
GetMem(BitmapImage, ImageSize);
try
GetDIB(Bitmap.Handle, Bitmap.Palette, BitmapHeader^, BitmapImage^);
StretchDIBits(Canvas.Handle,
DestRect.Left, DestRect.Top, // Destination Origin
DestRect.Right - DestRect.Left, // Destination Width
DestRect.Bottom - DestRect.Top, // Destination Height
0, 0, // Source Origin
Bitmap.Width, Bitmap.Height, // Source Width & Height
BitmapImage,
TBitmapInfo(BitmapHeader^),
DIB_RGB_COLORS,
SRCCOPY)
finally
FreeMem(BitmapHeader);
FreeMem(BitmapImage)
end
end {PrintBitmap};
procedure CPRSPrintGraph(GraphImage: TChart; PageTitle: string);
var
AHeader: TStringList;
i, y, LineHeight: integer;
GraphPic: TBitMap;
Magnif: integer;
const
TX_FONT_SIZE = 12;
TX_FONT_NAME = 'Courier New';
CF_BITMAP = 2; // from Windows.pas
begin
ClipBoard;
AHeader := TStringList.Create;
// CreatePatientHeader(AHeader, PageTitle);
aHeader.Text := PageTitle;
GraphPic := TBitMap.Create;
try
GraphImage.CopyToClipboardBitMap;
GraphPic.LoadFromClipBoardFormat(CF_BITMAP, ClipBoard.GetAsHandle(CF_BITMAP), 0);
with Printer do
begin
Canvas.Font.Size := TX_FONT_SIZE;
Canvas.Font.Name := TX_FONT_NAME;
Title := aHeader[0];
Magnif := ((Canvas.TextWidth(StringOfChar('=', 74))) div GraphImage.Width);
LineHeight := Printer.Canvas.TextHeight(TX_FONT_NAME);
y := LineHeight;
BeginDoc;
try
for i := 0 to AHeader.Count - 1 do
begin
Canvas.TextOut(0, y, AHeader[i]);
y := y + LineHeight;
end;
y := y + (4 * LineHeight);
//GraphImage.PrintPartial(Rect(0, y, Canvas.TextWidth(StringOfChar('=', 74)), y + (Magnif * GraphImage.Height)));
PrintBitmap(Canvas, Rect(0, y, Canvas.TextWidth(StringOfChar('=', 74)), y + (Magnif * GraphImage.Height)), GraphPic);
finally
EndDoc;
end;
end;
finally
ClipBoard.Clear;
GraphPic.Free;
AHeader.Free;
end;
end;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.acPrintGraphExecute(Sender: TObject);
var
bGrid,
b:Boolean;
sName,sInfo,
sPatient,sLocation,sPrinted,sLabel,sType,sPeriod,
ss,sss: String;
i,iLen: Integer;
begin
if not PrintDialog1.Execute then Exit;
b := bIgnoreBlueLines;
bIgnoreBlueLines := true;
iLen := 74;
sLocation := 'Hospital location: '+lblHospital.Caption;
sName := getPatientName;
sInfo := getPatientInfo;
sPatient := sName
+ StringOfChar(' ',iLen -1 - Length(sName) - Length(sInfo)) + sInfo;
sPrinted := 'Printed On: ' + FormatDateTime('mmm dd, yyyy hh:nn', Now);
sLabel := ' WORK COPY ONLY ';
while Length(sLabel) < iLen do sLabel := '*'+sLabel +'*';
sLabel := copy(sLabel,1,ilen-1);
sPeriod := 'Period: '+lblDateFromTitle.Caption;
sType := 'Vitals Type: '+cbxGraph.Text;
sss := '';
for i := 1 to Length(sPeriod) do
begin
if Copy(sPeriod,i,1) = '/' then sss := sss + '-'
else sss := sss + Copy(sPeriod,i,1);
end;
sPeriod := sss;
sss := '';
ss := sType + sPeriod;
while Length(ss) < iLen-1 do
begin
sss := sss + ' ';
ss := sType + sss + sPeriod;
end;
ss :=
ss + #13 +
sPatient + #13 +
sLabel + #13 +
sLocation + StringOfChar(' ', iLen - Length(sPrinted+sLocation)-1) + sPrinted+#13
;
ChrtVitals.Invalidate;
Application.ProcessMessages;
bGrid := pnlGrid.Visible;
splGridGraph.Align := alTop;
if bGrid then pnlGrid.Visible := false;
CPRSPrintGraph(ChrtVitals,ss);
pnlGrid.Visible := bGrid;
splGridGraph.Align := alBottom;
bIgnoreBlueLines := b;
ChrtVitals.Invalidate;
Application.ProcessMessages;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.GetVitalsData(aFrom,aTo:String);
var
VMEntry: TStringlist;
procedure CleanUpGrid;
var
c,r: Integer;
begin
with grdVitals do
begin
for c := 1 to ColCount - 1 do
for r := 1 to RowCount - 1 do
Cells[c, r] := '';
end;
end;
procedure PopulateGrid;
var
i, c, j: integer;
_S_,__S,s3,
s1, s2: string;
begin
with grdVitals do
begin
c := 1;
ColCount := VMEntry.Count + 1;
for i := VMEntry.Count - 1 downto 0 do
begin
s1 := VMEntry[i];
_s_ := VMEntry[i];
Cells[c, rHeader] := getDateTime(_s_);
Cells[c, rTemp] := getTemperature(_s_);
Cells[c, rPulse] := getPulse(_s_);
Cells[c, rResp] := getRespiration(_s_);
// Pulse Oximetry
s1 := Piece(Piece(VMEntry[i], '^', 6), '-', 1);//Value
s2 := Piece(Piece(VMEntry[i], '^', 6), '-', 2);//Method
s3 := Piece(Piece(VMEntry[i], '^', 6), '--',2);// ?
Cells[c, rPOx{4}] := s1;//Moving qualifiers away
// REMEDY-152003: Spaces around "/" affect the presentation- Start
__s := Piece(Piece(VMEntry[i], '^',6), '-', 3)+'/'+
Piece(Piece(VMEntry[i],'^', 6), '-', 4); //Pox
if __s = '/' then
Cells[c, rPOx+1{5}] := s2
else
Cells[c, rPOx+1{5}] := __s+ ' '+s2; // zzzzzzandria 060727
// REMEDY-152003: Spaces around "/" affect the presentation -- end
Cells[c, rBP{6}] := getBP(_s_);
Cells[c, rWeight{7}] := getWeight(_s_);
Cells[c, rBMI{8}] := Piece(Piece(VMEntry[i], '^', 10), '-', 1)
+ Piece(Piece(VMEntry[i], '^', 10), '-', 2);
Cells[c, rHeight{9}] := Piece(Piece(VMEntry[i], '^', 11), '-', 1)
+ Piece(Piece(VMEntry[i], '^', 11), '-', 2);
Cells[c, rGirth{10}] := Piece(Piece(VMEntry[i], '^', 13), '-', 1)
+ Piece(Piece(VMEntry[i], '^', 13), '-', 2);
Cells[c, rCVP{11}] := Piece(VMEntry[i], '^', 15);
Cells[c, rIntake{12}] := Piece(Piece(VMEntry[i], '^', 17), '-', 1);
Cells[c, rOutput{13}] := Piece(Piece(VMEntry[i], '^', 18), '-', 1);
Cells[c, rPain{14}] := Piece(Piece(VMEntry[i], '^', 19), '-', 1);
Cells[c, rLocation] := Piece(VMEntry[i], '^', 22);
Cells[c, rEnteredBy] := Piece(VMEntry[i], '^', 23);
{$IFDEF PATCH_5_0_23}
Cells[c, rSource] := Piece(VMEntry[i], '^', 24);
{$ENDIF}
for j := 0 to 14 do //AAN 07/11/2002
if pos('Unavail',Cells[c,j]) <> 0 then //AAN 07/11/2002
Cells[c,j] := 'Unavailable'; //AAN 07/11/2002
inc(c);
end;
Col := ColCount - 1;
Row := 1;
end;
end;
begin
if not Assigned(MDateTimeRange) or (MDateTimeRange.getSWRange = '')
or (FPatientDFN = '') then
Exit;
try
CleanUpGrid;
VMEntry := getAllPatientData(FPatientDFN,aFrom,aTo);
if VMEntry.Count > 0 then
PopulateGrid;
GrdVitals.Refresh;
finally
VMEntry.Free;
end;
end;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.setSeriesAxis(TheSeries:Array of Integer);
var
i: Integer;
dXMin,dXMax,
dMax,dMin,dDelta: Double;
function LocalMin(aSeries:TChartSeries): Double;
var
j: Integer;
LM: Double;
flag: Boolean;
begin
LM := 500;
flag := false;
for j := 0 to aSeries.Count - 1 do
if aSeries.YValue[j] = 0 then continue
else
begin
LM := min(LM,aSeries.YValues[j]);
flag := True;
end;
if Flag then
Result := LM
else
Result :=0;
end;
function LocalXMin(aSeries:TChartSeries): Double;
var
j: Integer;
LM: Double;
begin
LM := Now;
for j := 0 to aSeries.Count - 1 do
if aSeries.XValue[j] = 0 then continue
else LM := min(LM,aSeries.XValues[j]);
Result := LM
end;
begin
if chrtVitals.LeftAxis.Minimum > 0 then chrtVitals.LeftAxis.Minimum := 0;
dMax := chrtVitals.Series[Low(TheSeries)].MaxYValue;
dXMax := chrtVitals.Series[Low(TheSeries)].MaxXValue;
dXMin := LocalXMin(chrtVitals.Series[Low(TheSeries)]);
if cbChrono.Checked then dMin := chrtVitals.Series[Low(TheSeries)].MinYValue
else dMin := LocalMin(chrtVitals.Series[Low(TheSeries)]);
for i := Low(TheSeries) to High(TheSeries) do
begin
if not chrtVitals.Series[Theseries[i]].Active then Continue;
dMax := Max(dMax,chrtVitals.Series[Theseries[i]].MaxYValue);
if cbChrono.Checked then
dMin := Min(dMin,chrtVitals.Series[i].MinYValue)
else
dMin := Min(dMin,LocalMin(chrtVitals.Series[i]));
dXMax := Max(dXMax,chrtVitals.Series[Theseries[i]].MaxXValue);
dXMin := Min(dXMin,LocalXMin(chrtVitals.Series[Theseries[i]]));
end;
dDelta := 0.05*(dMax - dMin);
dDelta := max(dDelta,0.05*dMax);
if dDelta = 0 then dDelta := 1
else if dDelta < 0 then dDelta := - dDelta;
try
chrtVitals.LeftAxis.Automatic := False;
if dMax+dDelta < chrtVitals.LeftAxis.Minimum then
begin
chrtVitals.LeftAxis.Minimum := dMin-dDelta;
chrtVitals.LeftAxis.Maximum := dMax+dDelta;
end
else
begin
chrtVitals.LeftAxis.Maximum := dMax+dDelta;
chrtVitals.LeftAxis.Minimum := dMin-dDelta;
end;
fAxisMax := dMax+dDelta;
fAxisMin := dMin-dDelta;
except
on E: Exception do
ShowMessage('(2) Set Series Axis error:'+#13#10+E.Message);
end;
try
if dXMax < dXMin then dXMax := dXMin;
chrtVitals.BottomAxis.Automatic := False;
if chrtVitals.BottomAxis.Maximum < trunc(dXMax+1) then
chrtVitals.BottomAxis.Maximum := trunc(dXMax+1)
else
if dXMax < chrtVitals.BottomAxis.Minimum then
begin
chrtVitals.BottomAxis.Minimum := trunc(dXMin);
chrtVitals.BottomAxis.Maximum := trunc(dXMax+1);
end
else
begin
chrtVitals.BottomAxis.Maximum := trunc(dXMax+1);
chrtVitals.BottomAxis.Minimum := trunc(dXMin);
end;
if chrtVitals.BottomAxis.Minimum = 0 then
chrtVitals.BottomAxis.Minimum := trunc(dXMin);
except
on E: Exception do
ShowMessage('(3) Set Series Axis error:'+#13#10+E.Message);
end;
chrtVitals.BottomAxis.ExactDateTime := True;// 051031 zzzzzzandria
chrtVitals.BottomAxis.Increment := DateTimeStep[dtOneMinute];// 051031 zzzzzzandria
end;
procedure TfraGMV_GridGraph.setSingleVital(aRow:Integer;aSeria:Integer=0;aName:String='';
aConverter:TStringToDouble = nil);
var
gCol: integer;
dValue: Double;
d: Double;
function ValueDateTime(aCol:Integer):Double;
var
ss:String;
dd: Double;
begin
try
ss := grdVitals.Cells[aCol, rHeader];
ss := ReplaceStr(ss,'-','/');
// zzzzzzandria 061228 - replacement for chart only. to fix position
ss := ReplaceStr(ss,'24:00:00','23:59:59');
// zzzzzzandria 2007-07-17 Remedy 148503 --------------------------- begin
// assuming '00:00:00' is a valid time for I/O only
ss := ReplaceStr(ss,'00:00:00','23:59:59');
// zzzzzzandria 2007-07-17 Remedy 148503 ----------------------------- end
dD := StrToDateTimeDef(ss, Now);
except
dd := Now;
end;
Result := dd;
end;
begin
chrtVitals.LeftAxis.Automatic := False;
try
if 0 < chrtVitals.LeftAxis.Maximum then
chrtVitals.LeftAxis.Minimum := 0;
chrtVitals.LeftAxis.Maximum := 500;
except
on E: Exception do
ShowMessage('Set Single Vital'+#13+E.Message);
end;
chrtVitals.Series[aSeria].Clear;
if aName = '' then
chrtVitals.Series[aSeria].Title := grdVitals.Cells[0,aRow]
else
chrtVitals.Series[aSeria].Title := aName;
chrtVitals.Series[aSeria].Identifier := IntToStr(aRow);
gCol := 1;
with grdVitals do
while (Cells[gCol, rHeader] <> '') and (gCol < ColCount) do
begin
try
d := ValueDateTime(gCol);
if cbChrono.Checked then
begin
if HasNumericValue(Cells[gCol, aRow]) then
begin
if assigned(aConverter) then
dValue := aConverter(Cells[gCol, aRow])
else
dValue := dVal(Cells[gCol, aRow],grdVitals.Cells[gCol, rHeader]);
if dValue <> iIgnore then
chrtVitals.Series[aSeria].AddXY(d,dValue, SeriesLabel(Cells[gCol, rHeader]), clTeeColor);
end
{$IFDEF LINES}
else
chrtVitals.Series[aSeria].AddNull(SeriesLabel(Cells[gCol, rHeader]));
{$ENDIF}
;
end
else
begin
if assigned(aConverter) then
dValue := aConverter(Cells[gCol, aRow])
else
dValue := dVal(Cells[gCol, aRow],grdVitals.Cells[gCol, rHeader]);
if dValue <> iIgnore then
begin
if HasNumericValue(Cells[gCol, aRow]) then
chrtVitals.Series[aSeria].Add(dValue, SeriesLabel(Cells[gCol, rHeader]), clTeeColor)
else
chrtVitals.Series[aSeria].AddNull(SeriesLabel(Cells[gCol, rHeader]));
end
else // we can not just delete 99 for pain
chrtVitals.Series[aSeria].AddNull(SeriesLabel(Cells[gCol, rHeader]))
end;
except
chrtVitals.Series[aSeria].AddNull(SeriesLabel(Cells[gCol, rHeader]));
end;
inc(gCol);
end;
setSeriesAxis([aSeria]);
try
if aRow = rPain then chrtVitals.LeftAxis.Minimum := -0.5;
if aRow = rPain then chrtVitals.LeftAxis.Maximum := 12;
except
on E: Exception do
ShowMessage('Pain setup error:'+#13#10+E.Message);
end;
chrtVitals.Series[aSeria].Active := True;
try
if (grdVitals.ColCount = 2) and
((pos(sNoData,grdVitals.Cells[1,0]) = 1)
or (trim(grdVitals.Cells[1,aRow])='')) then
chrtVitals.Series[aSeria].Active := False;
except
end;
end;
procedure TfraGMV_GridGraph.setHW;
begin
SetSingleVital(rHeight,0,'Height');
SetSingleVital(rWeight,1,'Weight');
setSeriesAxis([0,1]);
end;
procedure TfraGMV_GridGraph.setTRP;
begin
SetSingleVital(rTemp,0,'Temp.');
SetSingleVital(rPulse,1,'Pulse');
SetSingleVital(rResp,2,'Resp.');
setSeriesAxis([0,1,2]);
end;
procedure TfraGMV_GridGraph.setBP;
begin
SetSingleVital(rBP,0,'Sys.');
// SetSingleVital(rBP,1,'Mean',BPMeanBP);
// SetSingleVital(rBP,2,'Dias.',BPDias);
// setSeriesAxis([0,1,2]);
SetSingleVital(rBP,1,'Dias.',BPDias);
setSeriesAxis([0,1]);
end;
procedure TfraGMV_GridGraph.setBPWeight;
begin
SetSingleVital(rBP,0,'Sys.');
SetSingleVital(rBP,1,'Dias.',BPDias);
SetSingleVital(rWeight,2,'Weight');
setSeriesAxis([0,1,2]);
end;
procedure TfraGMV_GridGraph.setSingleGraph(anIndex:Integer;aName:String;
aConverter:TStringToDouble = nil);
begin
SetSingleVital(anIndex,0,aName,aConverter);
end;
//==============================================================================
//==============================================================================
//==============================================================================
function TfraGMV_GridGraph.getDefaultGridPosition: Integer;
begin
Result := (grdVitals.Width - grdVitals.ColWidths[0]-grdVitals.GridLineWidth)
div (grdVitals.ColWidths[1]+grdVitals.GridLineWidth);
Result := grdVitals.ColCount - Result;
if Result < 1 then
Result := 1;
end;
procedure TfraGMV_GridGraph.getGraphByName(aName:String);
function DataFound:Boolean;
var
i: integer;
begin
DataFound := False;
for i := 1 to grdVitals.ColCount - 1 do
begin
if Trim(grdVitals.Cells[i,fGridRow]) = '' then continue;
DataFound := True;
Break;
end;
end;
procedure CleanUp;
var
j: Integer;
begin
with chrtVitals do
begin
ScaleLastPage := true;
UndoZoom;
for j := SeriesList.Count-1 downto 0 do
begin
Series[j].Clear;
Series[j].Active := False;
Series[j].Marks.Visible := cbValues.Checked;
end;
end;
end;
begin
acGraphButtons.Enabled := True;
acResizeGraph.Enabled := True;
if FPatientDFN = '' then Exit;
if (aName = sgnNoGraph) or (aName = sgnGirth) then
begin
chrtVitals.Visible := False;
acGraphButtons.Enabled := False;
acResizeGraph.Enabled := False;
if not pnlGrid.Visible then MaximizeGraph(nil);
if aName = sgnNoGraph then
pnlGraphBackground.Caption := 'Sorry there is no data for this graph.'
else
pnlGraphBackground.Caption := 'Sorry the graph of <'+aName+'> is not available.';
Exit;
end
else
chrtVitals.Visible := True;
CleanUp;
if aName = sgnTRP then setTRP
else if aName = sgnBP then setBP
else if aName = sgnPain then setSingleGraph(rPain,sgnPain,PainNo99) // values of 99 will be ignored
else if aName = sgnHW then setHW
else if aName = sgnPOX then setSingleGraph(rPOx,sgnPOX)
else if aName = sgnHeight then setSingleGraph(rHeight,sgnHeight)
else if aName = sgnWeight then setSingleGraph(rWeight,sgnWeight)
else if aName = sgnBMI then setSingleGraph(rBMI,sgnBMI)
else if aName = sgnTemp then setSingleGraph(rTemp,sgnTemp)
else if aName = sgnPulse then setSingleGraph(rPulse,sgnPulse)
else if aName = sgnResp then setSingleGraph(rResp,sgnResp)
else if aName = sgngIRTH then setSingleGraph(rGirth,sgngIRTH)
else if aName = sgnCVP then setSingleGraph(rCVP,sgnCVP)
else if aName = sgnIn then setSingleGraph(rIntake,sgnIn)
else if aName = sgnOutput then setSingleGraph(rOutput,sgnOutput)
else if aName = sgnBPWeight then setBPWeight
;
if aName = sgnTemp then
chrtVitals.LeftAxis.MinorTickCount := 9
else
chrtVitals.LeftAxis.MinorTickCount := 4;
setTrackBarLimits;
// the next line was uncommented to fix Remedy 281003. zzzzzzandria 2008-11-03
CurrentPoint := getDefaultGridPosition; //commented zzzzzzandria 2008-08-07
trbHGraph.Position := getDefaultGridPosition;
end;
procedure TfraGMV_GridGraph.GraphDataByIndex(anIndex:Integer);
var
aTime: TDateTime;
begin
aTime := now;
getGraphByName(cbxGraph.Items[anIndex]);
EventAdd('GraphDataByIndex.UpdateFrame',Format('GraphIndex=%d',[GraphIndex]),aTime);
end;
////////////////////////////////////////////////////////////////////////////////
function TfraGMV_GridGraph.GridScrollBarIsVisible:Boolean;
begin
Result := (GetWindowlong(grdVitals.Handle, GWL_STYLE) and WS_VSCROLL) <> 0;// zzzzzzandria 20081031
end;
procedure TfraGMV_GridGraph.setTrackBarLimits;
var
iGridColCount: Integer;
iMax: Integer;
begin
iGridColCount := (grdVitals.Width - grdVitals.ColWidths[0]) div
(grdVitals.ColWidths[1]+grdVitals.GridLineWidth);
if GridScrollBarIsVisible then
Inc(iGridColCount);
iMax := (grdVitals.ColCount - 1) - (iGridColCount - 1);
if GridScrollBarIsVisible then
Inc(iMax);
(* zzzzzzandria 2008-04-13 =====================================================
if (FrameStyle=fsVitals) then //zzzzzzandria 051205
iMax := iMax - 1;
==============================================================================*)
if iMax < 1 then
iMax := 1;
trbHGraph.min := 1;
trbHGraph.max := iMax;
end;
procedure TfraGMV_GridGraph.setGridPosition(aPosition: Integer);
var
iPos,
iMin,iMax: Integer;
function getVisibleColumnsCount:Integer;
begin
Result := ((grdVitals.Width - grdVitals.ColWidths[0]) div grdVitals.ColWidths[1]);
(* zzzzzzandria 2008-04-13 ====================================================
if (FrameStyle=fsVitals) then
// and scrollbarIsVisible then
Result := Result + 1;
==============================================================================*)
end;
begin
try
iPos := aPosition;
if iPos < 1 then iPos := 1;
grdVitals.LeftCol := iPos;
sbTest.SimpleText := Format(
' Current Tab Position: %4d (%4d/%4d) Leftmost Grid column %4d (Total: %4d)',
[aPosition,trbHGraph.Min,trbHGraph.Max,grdVitals.LeftCol,grdVitals.ColCount]);
if not cbChrono.Checked then
begin
chrtVitals.BottomAxis.Automatic := False;
iMin := grdVitals.LeftCol -1; // needs correction becouse Series starts from 0
iMax := iMin + getVisibleColumnsCount - 1;
if iMin <= iMax then
begin
if chrtVitals.BottomAxis.Minimum > iMin then
begin
chrtVitals.BottomAxis.Minimum := iMin;
chrtVitals.BottomAxis.Maximum := iMax;
end
else
if chrtVitals.BottomAxis.Maximum < iMax then
begin
chrtVitals.BottomAxis.Maximum := iMax;
chrtVitals.BottomAxis.Minimum := iMin;
end
else
begin
chrtVitals.BottomAxis.Minimum := 0;
chrtVitals.BottomAxis.Maximum := iMax;
chrtVitals.BottomAxis.Minimum := iMin;
end;
end;
chrtVitals.Invalidate;
end
else
setSeriesAxis([0,1,2]);
except
{$IFDEF AANTEST}
on E: Exception do
ShowMessage('3'+#13#10+E.Message);
{$ENDIF}
end;
end;
procedure TfraGMV_GridGraph.setCurrentPoint(aValue: Integer);
begin
FCurrentPoint := aValue;
grdVitals.LeftCol := aValue;// zzzzzzandria 051204
// if iIgnoreCount > 0 then Exit; //zzzzzzandria 2008-08-07
Inc(iIgnoreCount);
setGridPosition(aValue);
Dec(iIgnoreCount);
end;
procedure TfraGMV_GridGraph.scbHGraphChange(Sender: TObject);
begin
CurrentPoint := trbHGraph.Position;
end;
procedure TfraGMV_GridGraph.grdVitalsTopLeftChanged(Sender: TObject);
begin
trbHGraph.Position := grdVitals.LeftCol;
CurrentPoint := grdVitals.LeftCol;
chrtVitals.Invalidate;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.setMDateTimeRange(aMDTR: TMDateTimeRange);
begin
FMDateTimeRange := aMDTR;
UpdateTimeLabels;
end;
procedure TfraGMV_GridGraph.setObservationRange(aRange:String);
var
aTime: TDateTime;
begin
if MDateTimeRange.setMRange(aRange) then
begin
if (Uppercase(aRange) = sDateRange) then
UpdateLists;
FObservationRange:= aRange;
updateTimeLabels;
//set interface elements
lbDateRange.ItemIndex := lbDateRange.Items.IndexOf(FObservationRange);
if iIGnoreCount > 0 then Exit;
Inc(iIgnoreCount);
if FrameInitialized then
begin //zzzzzzandria 060610
aTime := EventStart('SetObservationRange.UpdateFrame');
UpdateFrame;
EventStop('SetObservationRange.UpdateFrame','Reload',aTime);
end;
Dec(iIgnoreCount);
end;
end;
procedure TfraGMV_GridGraph.cbxDateRangeClick(Sender: TObject);
var
s: String;
begin
try // zzzzzzandria 051208
if lbDateRange.ItemIndex = -1 then
s := lbDateRange.Items[0]
else
s := lbDateRange.Items[lbDateRange.ItemIndex];
except
end;
ObservationRange := s;
if fStyle = fsVitals then
GetParentForm(Self).Perform(CM_PERIODCHANGED, 0, 0);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.UpdateFrame(Reload:Boolean=True);
var
MDT: TMDateTime;
aComments: String;
begin
if not FrameInitialized then
Exit;
aComments := 'No Reload';
try
if Reload then // zzzzzzandria 060609
begin
aComments := 'Reload';
MDT := TMDateTime.Create;
MDT.WDateTime := MDateTimeRange.Stop.WDateTime;
MDT.WDateTime := trunc(MDT.WDateTime)+1-5/(3600*24);
GetVitalsData(MDateTimeRange.Start.getSMDateTime,MDT.getSMDateTime);
MDT.Free;
end;
GraphDataByIndex(GraphIndex);
grdVitals.Invalidate;
chrtVitals.Invalidate;
except
on E:Exception do
ShowMessage('Error in TfraGMV_GridGraph.UpdateFrame: ' + E.Message);
end;
end;
procedure TfraGMV_GridGraph.setPatientDFN(const Value: string);
var
aTime:TDateTime;
begin
FPatientDFN := Value;
Visible := (Value <> '');
if iIgnoreCount > 0 then
Exit;// zzzzzzandria 051202
if Assigned(MDateTimeRange) then
begin //zzzzzzandria 060610
aTime := EventStart('SetPatientDFN -- Begin');
UpdateFrame;
EventStop('SetPatientDFN -- End','DFN: '+fPatientDFN,aTime);
end;
end;
procedure TfraGMV_GridGraph.setGraphIndex(anIndex: Integer);
begin
fGraphIndex := anIndex;
if iIgnoreCount > 0 then Exit;
Inc(iIgnoreCount);
if FGraphIndex <> iIgnoreGraph then
begin
cbxGraph.ItemIndex := fGraphIndex;
getGraphByName(cbxGraph.Items[GraphIndex]);
end
else
begin
fGraphIndex := 0;
getGraphByName(sgnNoGraph);
end;
grdVitals.Invalidate;
chrtVitals.Invalidate;
Dec(iIgnoreCount);
end;
procedure TfraGMV_GridGraph.cbxGraphChange(Sender: TObject);
begin
if Sender = cbxGraph then
GraphIndex := cbxGraph.ItemIndex;
case GraphIndex of
0: fGridRow := 1;
1: fGridRow := 2;
2: fGridRow := 3;
3: fGridRow := 6;
4: fGridRow := 4;
5: fGridRow := 9;
6: fGridRow := 7;
7: fGridRow := 8;
8: fGridRow := 14;
12: fGridRow := 10;
13: fGridRow := 11;
14: fGridRow := 12;
15: fGridRow := 13;
else fGridRow := -1;
end;
//zzzzzzandria 060610
UpdateFrame;
end;
////////////////////////////////////////////////////////////////////////////////
// Resizing ====================================================================
procedure TfraGMV_GridGraph.chrtVitalsResize(Sender: TObject);
begin
setTrackBarLimits;
setGridPosition(grdVitals.LeftCol{-1});// zzzzzzandria 051130
end;
procedure TfraGMV_GridGraph.MaximizeGraph(Sender: TObject);
begin
pnlGrid.Visible := (pnlGrid.Visible = False);
if fStyle = fsVitals then
begin
if pnlGrid.Visible then
begin
splGridGraph.Visible := True;
splGridGraph.Align := alTop;
end
else
begin
splGridGraph.Visible := False;
splGridGraph.Align := alBottom;
end;
end
else
begin
if pnlGrid.Visible then
begin
splGridGraph.Visible := True;
splGridGraph.Align := alBottom;
end
else
begin
splGridGraph.Visible := False;
splGridGraph.Align := alTop;
end;
end;
end;
procedure TfraGMV_GridGraph.Panel9Resize(Sender: TObject);
begin
lblHospital.Width := panel9.Width - lblHospital.Left - 4;
lblHospital.Height := panel9.Height - lblHospital.Top - 2;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.cbChronoClick(Sender: TObject);
var
aTime: TDateTime;
iPos: Integer;
begin
if iIgnoreCount > 0 then Exit;
iPos := grdVitals.LeftCol; // zzzzzzandria 2008-04-14
ChrtVitals.SeriesList[0].XValues.DateTime := cbChrono.Checked;
ChrtVitals.SeriesList[1].XValues.DateTime := cbChrono.Checked;
ChrtVitals.SeriesList[2].XValues.DateTime := cbChrono.Checked;
ckb3D.Enabled := cbChrono.Checked;
if not cbChrono.Checked then
begin
ckb3D.Checked := False;
ckb3D.Enabled := False;
end;
aTime := Now;
UpdateFrame;
EventAdd('UpdateFrame.cbChronoClick','',aTime);
grdVitals.LeftCol := iPos; // zzzzzzandria 2008-04-14
// zzzzzzandria 2008-08-07 last minute fix for Patch 5.0.22.7
// axis X min is not set correctly when in Sychro mode
CurrentPoint := trbHGraph.Position;// zzzzzzandria 2008-08-07
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.UpdateTimeLabels;
begin
lblDateFromTitle.Caption := MDateTimeRange.Start.getSWDate;
lblDateFromTitle.Caption := lblDateFromTitle.Caption + ' -- ' + MDateTimeRange.Stop.getSWDate;
Application.ProcessMessages;
end;
procedure TfraGMV_GridGraph.UpdateLists;
begin
if (pos(MDateTimeRange.getSWRange,lbDateRange.Items.Text) = 0) then
begin
lbDateRange.Items.Add(MDateTimeRange.getSWRange);
lbDateRange.ItemIndex := lbDateRange.Items.IndexOf(MDateTimeRange.getSWRange);
end;
end;
procedure TfraGMV_GridGraph.setGraphTitle(aFirst,aSecond: string);
begin
chrtVitals.Title.Text.Clear;
chrtVitals.Title.Text.Add(aFirst);
chrtVitals.Title.Text.Add(aSecond);
edPatientName.Text := aFirst;
edPatientInfo.Text:= aSecond;
ptName := aFirst;
ptInfo := aSecond;
end;
procedure TfraGMV_GridGraph.ShowHideLabels(Sender: TObject);
var
i: integer;
begin
for i := 0 to chrtVitals.SeriesCount - 1 do
if chrtVitals.Series[i].Active then
chrtVitals.Series[i].Marks.Visible := bLabelShow;
end;
function TfraGMV_GridGraph.MetricValueString(_Row_:Integer;_Value_:String):String;
var
s: String;
f: Extended;
begin
Result := '';
s := piece(_Value_,' ');
if pos('*',s)=Length(s) then s := copy(s,1,Length(s)-1);
case _Row_ of
1:try //Temperature
f := StrToFloat(S);
f := (f-32)/9*5;
s := format('%-8.1f (C)',[f]);
Result := s;
except
end;
7:try //Weight
f := StrToFloat(S);
f := f*0.4535924;
s := format('%-8.2f (kg)',[f]);
Result := s;
except
end;
9,10: try //Height, C/G
f := StrToFloat(S);
f := f*2.54;
s := format('%-8.2f (cm)',[f]);
Result := s;
except
end;
else
Result := '';
end;
end;
procedure TfraGMV_GridGraph.chrtVitalsClickSeries(Sender: TCustomChart;
Series: TChartSeries; ValueIndex: integer; Button: TMouseButton;
Shift: TShiftState; x, Y: integer);
const
iDate = 1;
iTime = 2;
iLocation = 22;
iEnteredBy = 23;
var
iCol,iRow:Integer;
d: Double;
sFrom,sTo,sFor:String;
AllVitalsData,
VitalsData: TStringList;
MDT: TMDateTime;
procedure SetVitalInfo(aRow:Integer);
var
sv: String;
sName,
sValue, sMetric: String;
begin
sName := grdVitals.Cells[0, aRow];
if pos(':',sName) = length(sName) then
sName := copy(sName,1,Length(sName)-1);
sV := grdVitals.Cells[iCol, aRow];
if Trim(sV) <> '' then sValue := Trim(sV)
else sValue := sNoData;
sMetric := MetricValueString(aRow,grdVitals.Cells[iCol, aRow]);
VitalsData.Add(' Vital:' + #9 + sName);
VitalsData.Add(' Value:' + #9 + sValue);
if sMetric <> '' then VitalsData.Add(' ' + #9 + sMetric);
if aRow = 4 then VitalsData.Add(' ' + #9 + grdVitals.Cells[iCol, 5]);
VitalsData.Add('');
end;
function ConvertVitalsToText:String;
var
i: Integer;
_S_,__S,s3,//AAN
s1, s2: string;
s,ss,
sDate,sTime, sLocation,sEnteredBy, sOldInfo,sNewInfo,
sTemp, sPulse,sResp,sBP,sPOx, sFive, sWt, sBMI,
sHt, sGirth, sCVP, sIn, sOut,sPain:String;
const
CRLF = #13#10;
TAB = char(VK_TAB);
procedure AddValue(aLabel,aValue:String);
begin
if aValue <>'' then
begin
ss := ss + TAB+sTime + TAB + aLabel+Piece(aValue,' ',1)+TAB+piece(aValue,' ',2,99) + CRLF;
sTime := TAB;
end;
end;
begin
sOldInfo := '';
sNewInfo := '';
s := '';
ss := '';
sDate := '';
sTime := '';
for i := 0 to AllVitalsData.Count - 1 do
begin
s := AllVitalsData[i];
s1 := s;
_s_ := s;
sDate := Piece(s,'^',iDate);
sTime := Piece(s,'^',iTime);
// 061228 zzzzzzandria uncommening 2 lines
if i = 0 then
ss := ss + CRLF + TAB + sDate + CRLF;
sLocation := Piece(s,'^',iLocation);
sEnteredBy := Piece(s,'^',iEnteredBy);
sNewInfo := '--------------- Location: '+ sLocation+ char(VK_TAB)+' Entered By: '+sEnteredBy+' ---------------';
if sNewInfo <> sOldInfo then
begin
ss := ss + CRLF + TAB+sNewInfo+CRLF;
sOldInfo := sNewInfo;
end;
// ss := ss + TAB+sTime+CRLF;
// ss := ss + TAB+sTime;
sTemp := Piece(Piece(s, '^', 3), '-', 1) + Piece(Piece(s, '^', 3), '-', 2); //temperature
s1 := Piece(Piece(s, '^', 4), '-', 1);
s2 := Piece(Piece(s, '^', 4), '-', 2);
while pos(' ',s2)=1 do s2 := copy(s2,2,length(s2)-1);
sPulse := s1 + ' ' +
Piece(s2, ' ', 1) + ' ' +
Piece(s2, ' ', 2) + ' ' +
Piece(s2, ' ', 3) + ' ' +
Piece(s2, ' ', 4);
sResp := Piece(Piece(s, '^', 5), '-', 1) + Piece(Piece(s, '^', 5), '-', 2); // Respiratory
// Pulse Oximetry
s1 := Piece(Piece(s, '^', 6), '-', 1);//Value
s2 := Piece(Piece(s, '^', 6), '-', 2);//Method
s3 := Piece(Piece(s, '^', 6), '--',2);//
sPOx := s1;//Moving qualifiers away
__s := Piece(Piece(s, '^',6), '-', 3)+' / '+
Piece(Piece(s,'^', 6), '-', 4); //Pox
if __s = ' / ' then sFive := s2
else sFive := __s+ ' / '+s2;
if sFive <> '' then sPOx := sPOx + ' '+sFive;
s1 := Piece(Piece(s, '^', 7), '-', 1);
s2 := Piece(Piece(s, '^', 7), '-', 2);
sBP := s1 + ' ' + s2;
sWt := Piece(Piece(s, '^', 8), '-', 1) + Piece(Piece(s, '^', 8), '-', 2);
sBMI := Piece(Piece(s, '^', 10), '-', 1) + Piece(Piece(s, '^', 10), '-', 2);
sHt := Piece(Piece(s, '^', 11), '-', 1) + Piece(Piece(s, '^', 11), '-', 2);
sGirth := Piece(Piece(s, '^', 13), '-', 1) + Piece(Piece(s, '^', 13), '-', 2);
sCVP := Piece(s, '^', 15);
sIn := Piece(Piece(s, '^', 17), '-', 1);
sOut := Piece(Piece(s, '^', 18), '-', 1);
sPain := Piece(Piece(s, '^', 19), '-', 1);
sBMI := trim(sBMI);
AddValue('Temp.:'+ TAB,trim(sTemp));
AddValue('Pulse:'+ TAB,trim(sPulse));
AddValue('Resp.:'+ TAB,trim(sResp));
AddValue('POx.: '+ TAB,trim(sPOx));
AddValue('BP: '+ TAB,trim(sBP));
AddValue('Wt: '+ TAB,trim(sWt));
AddValue('Ht: '+ TAB,trim(sHt));
AddValue('C/G.: '+ TAB,trim(sGirth));
AddValue('CVP: '+ TAB,trim(sCVP));
AddValue('In: '+ TAB,trim(sIn));
AddValue('Out: '+ TAB,trim(sOut));
AddValue('Pain: '+ TAB,trim(sPain));
end;
Result := ss;
end;
begin
iCol := ValueIndex + 1;
iRow := StrToIntDef(Series.Identifier, 1);
VitalsData := TStringList.Create;
try
VitalsData.Add('');
sFor := piece(grdVitals.Cells[iCol, 0],' ',1);
// VitalsData.Add(' Date:' + #9 + grdVitals.Cells[iCol, 0]);
if cbxGraph.Items[GraphIndex] = sgnTRP then
begin
SetVitalInfo(1);
SetVitalInfo(2);
SetVitalInfo(3);
end
else if cbxGraph.Items[GraphIndex] = sgnHW then
begin
SetVitalInfo(7);
SetVitalInfo(9);
end
else
SetVitalInfo(iRow);
{=== ALL VITALS for the day ===============================================}
if cbChrono.Checked then d := Series.XValue[ValueIndex]
else
begin
sFrom := grdVitals.Cells[ValueIndex+1,0];
// 061228 zzzzzzandria ......
// zzzzzzandria 061228 - replacement was done to fix position on the chart
sFrom := ReplaceStr(sFrom,'24:00:00','23:59:59');
d := getCellDateTime(sFrom);
end;
mdt := TMDateTime.Create;
mdt.WDateTime := trunc(d)+1/24/60/60;
sFrom := mdt.getSMDate;
sFor := mdt.getSWDate;
mdt.WDateTime := d + 1 - 2/24/60/60;
sTo := mdt.getSMDate;
AllVitalsData := getALLPatientData(fPatientDFN,sFrom,sTo);
VitalsData.Text := ConvertVitalsToText;
AllVitalsData.Free;
{===========================================================================}
ShowInfo('Vitals '+getPatientName+' for '+sFor,VitalsData.Text);
mdt.Free;
finally
FreeAndNil(VitalsData);
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.DrawMissingLines(aStartPoint,aStopPoint:Integer);
var
rect, RectOld: TRect;
x,y,
i, j: integer;
SeriesNumber: integer;
FirstDataPoint,
LastDataPoint : integer;
CurrentSeries: TChartSeries;
iActiveCount: Integer;
const
iSize = 3;
procedure DrawEllipse;
begin
rect.left := CurrentSeries.CalcXPos(i)-iSize;
rect.Top := CurrentSeries.CalcYPos(i)-iSize;
rect.Right := CurrentSeries.CalcXPos(i)+iSize;
rect.Bottom := CurrentSeries.CalcYPos(i)+iSize;
chrtVitals.Canvas.Pen.Width := 4;
Brush.Style := bsSolid;
Brush.Color := CurrentSeries.SeriesColor;
chrtVitals.Canvas.Ellipse(rect.Left,rect.top,rect.right,rect.Bottom);
chrtVitals.Canvas.Pen.Width := 2;
end;
procedure DrawRect;
begin
rect.left := CurrentSeries.CalcXPos(i)-iSize;
rect.Top := CurrentSeries.CalcYPos(i)-iSize;
rect.Right := CurrentSeries.CalcXPos(i)+iSize;
rect.Bottom := CurrentSeries.CalcYPos(i)+iSize;
chrtVitals.Canvas.Brush.Color := CurrentSeries.SeriesColor;
chrtVitals.Canvas.FillRect(rect);
end;
procedure DrawPolygon;
begin
end;
function yStep:Integer;
begin
Result := 0;
if not chrtVitals.View3d then Exit;
chrtVitals.CalcSize3dWalls;
if chrtVitals.SeriesCount > 0 then
Result := chrtVitals.Height3D div iActiveCount;
end;
function xStep:Integer;
begin
Result := 0;
if not chrtVitals.View3d then Exit;
chrtVitals.CalcSize3dWalls;
if chrtVitals.SeriesCount > 0 then
Result := chrtVitals.Width3D div iActiveCount;
end;
function xDelta(ii: Integer): Integer;
begin
Result := 0;
end;
function yDelta(ii: Integer): Integer;
begin
Result := 0;
EXIT;
case iActiveCount of
1:begin
yDelta := yStep+2;
end;
2: begin
case ii of
0: yDelta := - yStep - 2
else
yDelta := yStep;
end;
end;
3: begin
case ii of
0: yDelta := yStep + 2;
1: yDelta := 0;
2: yDelta := - yStep - 2
else
yDelta := 0;
end;
end;
else
yDelta := 0;
end;
end;
begin
RectOld := TCanvas(chrtVitals.Canvas).ClipRect;
chrtVitals.Canvas.ClipRectangle(chrtVitals.chartRect);
iActiveCount := 0;
for SeriesNumber := 0 to chrtVitals.SeriesCount - 1 do
if chrtVitals.Series[SeriesNumber].Active then
Inc(iActiveCount);
for SeriesNumber := 0 to chrtVitals.SeriesCount - 1 do
if chrtVitals.Series[SeriesNumber].Active then
begin
CurrentSeries := chrtVitals.Series[SeriesNumber];
if CurrentSeries.Count < 1 then Continue;
FirstDataPoint :=0;
LastDataPoint := CurrentSeries.Count-1;
j := FirstDataPoint;
for i := FirstDataPoint+1 to LastDataPoint do
begin
if not CurrentSeries.IsNull(i) then
begin
with chrtVitals.Canvas do
begin
Pen.Width := 2;
Pen.Color := CurrentSeries.SeriesColor;
// if not chrtVitals.View3d then zzzzzzandria 060106
case SeriesNumber of
0: DrawEllipse;
1: DrawEllipse;
2:begin
Polygon([
Point(CurrentSeries.CalcXPos(i)-iSize,CurrentSeries.CalcYPos(i)+iSize),
Point(CurrentSeries.CalcXPos(i)+iSize,CurrentSeries.CalcYPos(i)+iSize),
Point(CurrentSeries.CalcXPos(i),CurrentSeries.CalcYPos(i)-iSize)
])
end;
3:begin
Polygon([
Point(CurrentSeries.CalcXPos(i)-iSize,CurrentSeries.CalcYPos(i)-iSize),
Point(CurrentSeries.CalcXPos(i)+iSize,CurrentSeries.CalcYPos(i)-iSize),
Point(CurrentSeries.CalcXPos(i),CurrentSeries.CalcYPos(i)+iSize)
])
end;
end;
{}
// to avoid starting with null on the screen
if {(j <> 0) or}
not CurrentSeries.IsNull(j)
and not ((i = LastDataPoint) and (CurrentSeries.IsNull(i)))
then
begin
x := CurrentSeries.CalcXPos(j) + xDelta(SeriesNumber);
y := CurrentSeries.CalcYPos(j) + yDelta(SeriesNumber);
MoveTo(x,y);
x := CurrentSeries.CalcXPos(i) + xDelta(SeriesNumber);
y := CurrentSeries.CalcYPos(i) + YDelta(SeriesNumber);
LineTo(x,y);
{
Pen.Color := clRed;
y := y + chrtVitals.SeriesHeight3d;
LineTo(x,y);
x := CurrentSeries.CalcXPos(i) + xDelta(SeriesNumber);
y := CurrentSeries.CalcYPos(i) + YDelta(SeriesNumber);
MoveTo(x,y);
x := x + chrtVitals.SeriesWidth3d;
LineTo(x,y);
}
end;
end;
j := i;
end;
end;
end;
chrtVitals.Canvas.ClipRectangle(RectOld);//Restore ClipRectangle
end;
procedure TfraGMV_GridGraph.DrawMissingDataLines(Sender: TObject);
var
FirstPointOnPage, LastPointOnPage: integer;
begin
FirstPointOnPage := 0;
LastPointOnPage := chrtVitals.Series[0].Count-1;
DrawMissingLines(FirstPointOnPage,LastPointOnPage);
end;
procedure TfraGMV_GridGraph.chrtVitalsAfterDraw(Sender: TObject);
begin
{$IFDEF LINES}
Exit;
{$ENDIF}
if not cbChrono.Checked then
DrawMissingDataLines(nil);
end;
procedure TfraGMV_GridGraph.grdVitalsDrawCell(
Sender: TObject;
ACol, ARow: integer;
Rect: TRect;
State: TGridDrawState);
function CurrentGraph:Boolean;
begin
case GraphIndex of
0..3: Result := aRow = fGridRow;
4: Result := (aRow = 4) or (aRow=5);
5..8: Result := aRow = fGridRow;
9:Result := (aRow = 7) or (aRow = 9);
10: Result := (aRow = 1) or (aRow = 2) or (aRow=3);
11: Result := (aRow = 6) or (aRow = 7);
else
Result := aRow = fGridRow;
end;
end;
var
sToday,
Value: string;
// Uncomment if you need a separate color for today's values
// TodayValue,
AbnormalValue: Boolean;
begin
sToday :=FormatDateTime('mm-dd-yy',Now);
//with grdVitals do
with TStringGrid(Sender) do
begin
Value := trim(Cells[ACol, ARow]);
AbnormalValue := Pos('*', Value) > 0;
// Uncomment if you need a separate color for today's values
// TodayValue := piece(Cells[aCol,0],' ',1) = sToday;
// Fill in background as btnFace, Abnormal, Normal
if (aRow > 14) or (aRow=0) then
Canvas.Brush.Color := clBtnFace
else if (ACol = 0) then
begin
if (aRow<>0) and CurrentGraph then
Canvas.Brush.Color := clInfoBk
else
Canvas.Brush.Color := clSilver;// clBtnFace;
end
else if AbnormalValue then
begin
// Uncomment if you need a separate color for today's values
// if TodayValue then
// Canvas.Brush.Color := DISPLAYCOLORS[GMVAbnormalTodayBkgd]
// else
Canvas.Brush.Color := DISPLAYCOLORS[GMVAbnormalBkgd];
end
else
// Uncomment if you need a separate color for today's values
// if TodayValue then
// Canvas.Brush.Color := DISPLAYCOLORS[GMVNormalTodayBkgd]
// else
if CurrentGraph then
Canvas.Brush.Color := $00DFDFDF
else
// Canvas.Brush.Color := fBGColor; //DISPLAYCOLORS[GMVNormalBkgd];
Canvas.Brush.Color := DISPLAYCOLORS[GMVNormalBkgd];
Canvas.FrameRect(Rect);
{
// Draw rectangle around selected cell
if (ACol > 0) and (ARow > 0) and (gdSelected in State) then
begin
if AbnormalValue then
Canvas.Pen.Color := DISPLAYCOLORS[GMVAbnormalText]
else
Canvas.Pen.Color := DISPLAYCOLORS[GMVNormalText];
Canvas.FrameRect(Rect);
end;
}
// Set up font color as btnText, Abnormal, Normal
if (ACol = 0) or (ARow = 0) or (ARow = 15) or (ARow = 16) then
begin
Canvas.Font.Color := clBtnText;
Canvas.Font.Style := [];
end
else if AbnormalValue then
begin
Canvas.Font.Color := DISPLAYCOLORS[GMVAbnormalText];
if GMVAbnormalBold then Canvas.Font.Style := [fsBold]
else Canvas.Font.Style := [];
end
else
begin
Canvas.Font.Color := DISPLAYCOLORS[GMVNormalText];
if GMVNormalBold then Canvas.Font.Style := [fsBold]
else Canvas.Font.Style := [];
end;
// Fill in the data
if ((ACol = 0) or (ARow = 0)) and (aRow <>15) and (aRow <>16) then
Canvas.TextRect(Rect, Rect.Left+10, Rect.Top, Value)
else if ((aRow = 15) or (aRow=16)) {and (not cbWho.Checked)} then
begin
Canvas.TextRect(Rect, Rect.Left+10, Rect.Top, Value)
end
else if (aRow = 5) then // zzzzzzandria 2008-01-07 ----------------- begin
// qualifiers are shown regardless of user preferences(options)
begin
if pos('*',trim(Cells[ACol, 4])) >0 then
begin
if not GMVAbnormalQuals then
Value := '';
end
else if not GMVNormalQuals then
Value := '';
Canvas.TextRect(Rect, Rect.Left+10, Rect.Top, Value);
end // zzzzzzandria 2008-01-07 ------------------------------------- end
else if AbnormalValue then
begin
if GMVAbnormalQuals then Canvas.TextRect(Rect, Rect.Left+10, Rect.Top, Value)
else Canvas.TextRect(Rect, Rect.Left+10, Rect.Top, Piece(Value, ' ', 1))
end
else
begin
if GMVNormalQuals then Canvas.TextRect(Rect, Rect.Left+10, Rect.Top, Value)
else Canvas.TextRect(Rect, Rect.Left+10, Rect.Top, Piece(Value, ' ', 1));
end;
if gdSelected in State then
begin
Canvas.Brush.Color := clRed; // clBlack;//zzzzzzandria 050705
Canvas.FrameRect(Rect);
end;
end;
end;
procedure TfraGMV_GridGraph.grdVitalsSelectCell(Sender: TObject; Button: TMouseButton; Shift: TShiftState; x, Y: integer);
var
ACol, ARow: Longint;
begin
grdVitals.MouseToCell(x, Y, ACol, ARow);
if (aCol = 0) then
begin
if GraphIndexByGridRow(aRow) <> iIgnoreGraph then
GraphIndex := GraphIndexByGridRow(aRow)
else
fGraphIndex := 0;
fGridRow := aRow;
UpdateFrame; // zzzzzzandria 060105
grdVitals.Invalidate;
chrtVitals.Invalidate;
end;
if (ACol > 0) and (ARow = 0) then
try
fSelectedDateTime := getCellDateTime(grdVitals.Cells[aCol, 0]);
acEnteredInErrorByTimeExecute(nil);
except
end;
end;
procedure TfraGMV_GridGraph.setPatientLocation(aLocation: String);
begin
FPatientLocation := aLocation;
end;
procedure TfraGMV_GridGraph.setPatientLocationName(aLocationName: String);
begin
FPatientLocationName := aLocationName;
lblHospital.Caption := aLocationName;
end;
// Actions =====================================================================
procedure TfraGMV_GridGraph.sbtnPrintGraphClick(Sender: TObject);
begin
acPrintGraphExecute(Sender);
end;
procedure TfraGMV_GridGraph.sbtnLabelsClick(Sender: TObject);
begin
acValueCaptionsExecute(Sender);
end;
procedure TfraGMV_GridGraph.sbtnMaxGraphClick(Sender: TObject);
begin
acResizeGraphExecute(Sender);
end;
procedure TfraGMV_GridGraph.acCustomRangeExecute(Sender: TObject);
begin
setObservationRange(sDateRange);
UpdateLists;
end;
procedure TfraGMV_GridGraph.acEnteredInErrorExecute(Sender: TObject);
begin
if EnterVitalsInError(FPatientDFN) <> mrCancel then
cbxDateRangeClick(nil);
end;
procedure TfraGMV_GridGraph.acZoomExecute(Sender: TObject);
begin
chrtVitals.AllowZoom := cbAllowZoom.Checked;
edZoom.Enabled := chrtVitals.AllowZoom;
sbPlus.Enabled := chrtVitals.AllowZoom;
sbMinus.Enabled := chrtVitals.AllowZoom;
sbReset.Enabled := chrtVitals.AllowZoom;
end;
procedure TfraGMV_GridGraph.acGraphOptionsExecute(Sender: TObject);
begin
pnlGraphOptions.Visible := not pnlGraphOptions.Visible;
showHideGraphOptions1.Checked := pnlGraphOptions.Visible;
{$IFNDEF DLL}
if Assigned(frmGMV_UserMain) then
frmGMV_UserMain.showHideGraphOptions1.Checked := pnlGraphOptions.Visible;
{$ENDIF}
end;
procedure TfraGMV_GridGraph.acEnteredInErrorByTimeExecute(Sender: TObject);
begin
if fSelectedDateTime = 0 then Exit;
if EnteredInErrorByDate(FPatientDFN,trunc(fSelectedDateTime)+1-1/(3600*24)) <> mrCancel then
cbxDateRangeClick(nil);
end;
procedure TfraGMV_GridGraph.acPatientAllergiesExecute(Sender: TObject);
begin
sbtnAllergies.Down := True;
ShowPatientAllergies(FPatientDFN,'Allergies for:'+edPatientName.Text +
' ' + edPatientInfo.Text);
sbtnAllergies.Down := False;
end;
procedure TfraGMV_GridGraph.ColorSelect1Accept(Sender: TObject);
begin
BGColor := ColorSelect1.Dialog.Color;
end;
procedure TfraGMV_GridGraph.SetColor;
begin
fBGColor := aColor;
begin
chrtVitals.Color := fBGColor;
// pnlRight.Color := fBGColor;
trbHGraph.Invalidate;
grdVitals.Invalidate;
end;
end;
procedure TfraGMV_GridGraph.SetTodayColor;
begin
fBGTodayColor := aColor;
begin
trbHGraph.Invalidate;
grdVitals.Invalidate;
end;
end;
procedure TfraGMV_GridGraph.sbGraphColorClick(Sender: TObject);
begin
if ColorDialog1.Execute then
BGColor := ColorDialog1.Color;
end;
procedure TfraGMV_GridGraph.acEnterVitalsExecute(Sender: TObject);
var
aTime:TDateTime;
begin
VitalsInputDLG(
PatientDFN,
PatientLocation,
'', // Template
'', // Signature
getServerWDateTime,// select server date time - zzzzzzandria 050419
ptName,
ptInfo
) ;
aTime := Now;
UpdateFrame;
EventAdd('fraGMV_GridGraph.UpdateFrame','Reload',aTime);
end;
procedure TfraGMV_GridGraph.acValueCaptionsExecute(Sender: TObject);
begin
bLabelShow := not bLabelShow;
ShowHideLabels(Sender);
end;
procedure TfraGMV_GridGraph.ac3DExecute(Sender: TObject);
begin
chrtVitals.View3D := ckb3D.Checked;
bIgnoreBlueLines := ckb3D.Checked;
end;
procedure TfraGMV_GridGraph.acResizeGraphExecute(Sender: TObject);
begin
MaximizeGraph(Sender);
end;
(*
procedure TfraGMV_GridGraph.PrintGraph(Sender: TObject);
begin
with TPrintDialog.Create(Application) do
try
if Execute then
begin
chrtVitals.PrintProportional := True;
chrtVitals.PrintMargins.Left := 1;
chrtVitals.PrintMargins.Top := 1;
chrtVitals.PrintMargins.Bottom := 1;
chrtVitals.PrintMargins.Right := 1;
chrtVitals.PrintResolution := -10;//-70;
chrtVitals.BottomAxis.LabelsAngle := 0;
chrtVitals.BackImageInside := False;
chrtVitals.Print;
chrtVitals.backimageinside := True;
end;
finally
free;
end;
end;
*)
procedure TfraGMV_GridGraph.lbDateRangeKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then
cbxDateRangeClick(lbDateRange);
end;
////////////////////////////////////////////////////////////////////////////////
function TfraGMV_GridGraph.GraphNameByGridRow(aRow:Integer):String;
begin
case aRow of
rTemp{1}: Result := sgnTemp;
rPulse{2}:Result := sgnPulse;
rResp{3}: Result := sgnResp;
rPOx{4}: Result := sgnPOX;
rPOX+1{5}: Result := sgnPOX;
rBP{6}: Result := sgnBP;
rWeight{7}: Result := sgnWeight;
rBMI{8}: Result := sgnBMI;
rHeight{9}: Result := sgnHeight;
rGirth{10}: Result := sgnGirth;
rCVP{11}: Result := sgnCVP; //GraphNameNoGraph;
rIntake{12}: Result := sgnIn;//GraphNameNoGraph;
rOutput{13}: Result := sgnOutput;//GraphNameNoGraph;
rPain{14}: Result := sgnPain;
else
Result := sgnNoGraph;
end;
end;
function TfraGMV_GridGraph.GraphIndexByGridRow(aRow:Integer):Integer;
begin
case aRow of
rTemp{1}: Result := 0;
rPulse{2}: Result := 1;
rResp{3}: Result := 2;
rPOx{4}: Result := 4;
rPOx+1{5}: Result := 4;
rBP{6}: Result := 3;
rWeight{7}: Result := 6;
rBMI{8}: Result := 7;
rHeight{9}: Result := 5;
rGirth{10}: Result := 12; //iIgnoreGraph; // C/G
rCVP{11}: Result := 13; //iIgnoreGraph; // CVP
rIntake{12}:Result := 14; //iIgnoreGraph; // In
rOutput{13}:Result := 15; //iIgnoreGraph; // Out
rPain{14}: Result := 8;
else
Result := iIgnoreGraph;
end;
end;
function TfraGMV_GridGraph.GridRowByGraphIndex(anIndex:Integer):Integer;
begin
case anIndex of
0: Result := rTemp{1};
1: Result := rPulse{2};
2: Result := rResp{3};
3: Result := rBP{6};
4: Result := rPOx{4};
5: Result := rHeight{9};
6: Result := rWeight{7};
7: Result := rBMI{8};
8: Result := rPain{14};
9: Result := 0;
10:Result := 0;
11:Result := 0;
12:Result := rGirth{11};// CVP
13:Result := rCVP{12};// CVP
14:Result := rIntake{13};// In
15:Result := rOutput{14};// Out
else
if GraphIndex < 9 then
Result := GridRowByGraphIndex(GraphIndex)
else
Result := 0;
end;
end;
procedure TfraGMV_GridGraph.SetStyle(aStyle:String);
begin
splGridGraph.Align := alTop;
pnlGrid.Align := alBottom;
pnlGraph.Align := alClient;
splGridGraph.Align := alBottom;
pnlDateRangeTop.Visible := True;
pnlTitle.Visible := aStyle <> fsVitals;
if aStyle = fsVitals then
pnlGrid.Constraints.MaxHeight := pnlGridTop.Height +
(grdVitals.RowCount+1) * (grdVitals.RowHeights[0]+grdVitals.GridLineWidth);
FStyle := aStyle;
end;
procedure TfraGMV_GridGraph.setUpFrame;
function GridHeight:Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to grdVitals.RowCount - 1 do
Result := Result + grdVitals.RowHeights[i]+grdVitals.GridLineWidth;
end;
begin
if FrameInitialized then Exit;
with grdVitals do
begin
{$IFDEF PATCH_5_0_23}
RowCount := 18;
{$ELSE}
RowCount := 17;
{$ENDIF}
DefaultRowHeight := 15;
DefaultColWidth := 100;
ColWidths[0] := 100;
Cells[0, rTemp{1}] := ' Temp:';
Cells[0, rPulse{2}] := ' Pulse:';
Cells[0, rResp{3}] := ' Resp:';
Cells[0, rPOx{4}] := ' P Ox %:'; //AAN 2003/06/03
Cells[0, rPOx+1{5}] := ' L/Min/%:';
Cells[0, rBP{6}] := ' B/P:';
Cells[0, rWeight{7}] := ' Wt (lbs):';
Cells[0, rBMI{8}] := ' BMI:';
Cells[0, rHeight{9}] := ' Ht (in):';
Cells[0, rGirth{10}] := ' C/G:';
Cells[0, rCVP{11}] := ' CVP (cmH2O):';
Cells[0, rIntake{12}] := ' In 24hr (ml):';
Cells[0, rOutput{13}] := ' Out 24hr (ml):';
Cells[0, rPain{14}] := ' Pain:';
Cells[0, rLocation{15}] := 'Location:';
Cells[0, rEnteredBy{16}] := 'Entered By:';
{$IFDEF PATCH_5_0_23}
Cells[0, rSource] := 'Data Source:';
{$ENDIF}
Height :=(DefaultRowHeight * RowCount) + (GridLineWidth * (RowCount+3)) +
GetSystemMetrics(SM_CYVSCROLL);
if FrameStyle <> fsVitals then
pnlGrid.Height := pnlGridTop.Height + (DefaultRowHeight * RowCount) +
(GridLineWidth * (RowCount+3)) + GetSystemMetrics(SM_CYVSCROLL);
Invalidate;
end;
lbDateRange.Items.Add('TODAY');
lbDateRange.Items.Add('T-1');
lbDateRange.Items.Add('T-2');
lbDateRange.Items.Add('T-3');
lbDateRange.Items.Add('T-4');
lbDateRange.Items.Add('T-5');
lbDateRange.Items.Add('T-6');
lbDateRange.Items.Add('T-7');
lbDateRange.Items.Add('T-15');
lbDateRange.Items.Add('T-30');
lbDateRange.Items.Add('Six Months');
lbDateRange.Items.Add('One Year');
lbDateRange.Items.Add('Two Years');
lbDateRange.Items.Add('All Results');
lbDateRange.Items.Add(sDateRange); //zzzzzzandria 050421
cbxGraph.Items.Add(sgnTemp);
cbxGraph.Items.Add(sgnPulse);
cbxGraph.Items.Add(sgnResp);
cbxGraph.Items.Add(sgnBP);
cbxGraph.Items.Add(sgnPOX);
cbxGraph.Items.Add(sgnHeight);
cbxGraph.Items.Add(sgnWeight);
cbxGraph.Items.Add(sgnBMI);
cbxGraph.Items.Add(sgnPain);
cbxGraph.Items.Add(sgnHW);
cbxGraph.Items.Add(sgnTRP);
cbxGraph.Items.Add(sgnBPWeight);
cbxGraph.Items.Add(sgnGirth);
cbxGraph.Items.Add(sgnCVP);
cbxGraph.Items.Add(sgnIn);
cbxGraph.Items.Add(sgnOutput);
iIgnoreGraph := 21;
bLabelSHow := False;
Inc(iIgnoreCount);
GraphIndex := 1;
Dec(iIgnoreCount);
cbxGraph.ItemIndex := 1;
if Assigned(MDateTimeRange) then
try
lbDateRange.Items.Add(MDateTimeRange.getSWRange);
lbDateRange.ItemIndex := lbDateRange.Items.IndexOf(MDateTimeRange.getSWRange);
except
end;
fSelectedDateTime := 0;
iIgnoreCount := 0;
pnlGrid.Constraints.MaxHeight := pnlGridTop.Height + gridHeight;
grdVitals.ColWidths[0] := pnlDateRange.Width;
{$IFDEF AANTEST}
sbTest.Visible := True;
pnlDebug.Visible := True;
{$ENDIF}
FrameInitialized := True;
end;
// Color frames ================================================================
procedure TfraGMV_GridGraph.cbxGraphExit(Sender: TObject);
begin
cbxGraph.Color := clTabOut;
pnlGSelectBottom.Color := pnlGSelect.Color;
pnlGSelectTop.Color := pnlGSelect.Color;
pnlGSelectLeft.Color := pnlGSelect.Color;
pnlGSelectRight.Color := pnlGSelect.Color;
end;
procedure TfraGMV_GridGraph.cbxGraphEnter(Sender: TObject);
begin
cbxGraph.Color := clTabIn;
pnlGSelectBottom.Color := clTabIn;
pnlGSelectTop.Color := clTabIn;
pnlGSelectLeft.Color := clTabIn;
pnlGSelectRight.Color := clTabIn;
end;
procedure TfraGMV_GridGraph.lbDateRangeExit(Sender: TObject);
begin
pnlPBot.Color := clbtnFace;
pnlPTop.Color := clbtnFace;
pnlPLeft.Color := clbtnFace;
pnlPRight.Color := clbtnFace;
end;
procedure TfraGMV_GridGraph.lbDateRangeEnter(Sender: TObject);
begin
pnlPBot.Color := clTabIn;
pnlPTop.Color := clTabIn;
pnlPLeft.Color := clTabIn;
pnlPRight.Color := clTabIn;
end;
procedure TfraGMV_GridGraph.grdVitalsEnter(Sender: TObject);
begin
pnlGBot.Color := clTabIn;
pnlGTop.Color := clTabIn;
pnlGLeft.Color := clTabIn;
pnlGRight.Color := clTabIn;
end;
procedure TfraGMV_GridGraph.grdVitalsExit(Sender: TObject);
begin
pnlGBot.Color := clbtnFace;
pnlGTop.Color := clbtnFace;
pnlGLeft.Color := clbtnFace;
pnlGRight.Color := clbtnFace;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.chrtVitalsBeforeDrawSeries(Sender: TObject);
var
iLeft,iRight,
iDelta,
iMin,iMax: LongInt;
dBeginPlus, dEndPlus,
dBegin,dEnd: Double;
function ValueDateTime(aCol:Integer):Double;
var
ss:String;
begin
try
ss := grdVitals.Cells[aCol, rHeader];
if ss <>'' then
begin
ss := ReplaceStr(ss,'-','/');
if pos(' 24:',sS)>0 then
ss := piece(ss,' ',1);
Result := StrToDateTime(ss);
end
else
Result := Now;
except
Result := Now;
end;
end;
function yStep:Integer;
begin
Result := 0;
if not chrtVitals.View3d then Exit;
chrtVitals.CalcSize3dWalls;
Result := chrtVitals.Height3D div 2;
end;
function xStep:Integer;
begin
Result := 0;
if not chrtVitals.View3d then Exit;
chrtVitals.CalcSize3dWalls;
Result := chrtVitals.Width3D;
end;
begin
{$IFDEF LINES}
Exit;
{$ENDIF}
if bIgnoreBlueLines then Exit;
if chrtVitals.View3D then Exit;
try
if (grdVitals.ColCount = 2) and
((pos(sNoData,grdVitals.Cells[1,0]) = 1)
or
(trim(grdVitals.Cells[1,fGridRow])='')
) then Exit;
except
Exit;
end;
dBegin := ValueDateTime(grdVitals.LeftCol);
if FrameStyle = fsVitals then
dEnd := ValueDateTime(grdVitals.LeftCol+grdVitals.VisibleColCount)
else
dEnd := ValueDateTime(grdVitals.LeftCol+grdVitals.VisibleColCount-1);
if grdVitals.LeftCol > 1 then
dBeginPlus := ValueDateTime(grdVitals.LeftCol -1)
else
dBeginPlus := dBegin;
if grdVitals.LeftCol+grdVitals.VisibleColCount< grdVitals.ColCount then
dEndPlus := ValueDateTime(grdVitals.LeftCol+grdVitals.VisibleColCount)
else
dEndPlus := dEnd;
fXL := (round(chrtVitals.BottomAxis.CalcPosValue(dBegin))+
round(chrtVitals.BottomAxis.CalcPosValue(dBeginPlus))) div 2
+xStep;
fXR := (round(chrtVitals.BottomAxis.CalcPosValue(dEnd)) +
round(chrtVitals.BottomAxis.CalcPosValue(dEndPlus))) div 2
+xStep;
// idelta := round(0.05*(chrtVitals.LeftAxis.Maximum-chrtVitals.LeftAxis.Minimum));
// if iDelta > 5 then iDelta := 5;
iDelta := 5;
iLeft := -1;
iRight := -1;
with chrtVitals.Canvas do
begin
iMin := chrtVitals.ChartRect.Top+1 + yStep;
iMax := chrtVitals.ChartRect.Bottom-1 + yStep;
Pen.Color := clBlue;
if (fXL > chrtVitals.ChartRect.Left) and (fXL < chrtVitals.ChartRect.Right) then
begin
iLeft := fXL+1;
MoveTo(fXL,iMin);
LineTo(fXL,iMax);
end
else if fXL <= chrtVitals.ChartRect.Left then
iLeft := chrtVitals.ChartRect.Left + 1;
if (fXR > chrtVitals.ChartRect.Left) and (fXR < chrtVitals.ChartRect.Right) then
begin
iRight := fXR;
MoveTo(fXR,iMin);
LineTo(fXR,iMax);
end
else if fXR >= chrtVitals.ChartRect.Right then
iRight := chrtVitals.ChartRect.Right;
Brush.Color := clSilver;
if (iLeft > 0) and (iRight > 0) then
begin
FillRect(Rect(iLeft,iMin,iRight,iMin+iDelta));
FillRect(Rect(iLeft,iMax-iDelta,iRight,iMax));
end;
end;
end;
// Unknown ////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.lbDateRangeMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
cbxDateRangeClick(nil);
end;
procedure TfraGMV_GridGraph.lbDateRangeMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
i: Integer;
begin
i := Y div lbDateRange.ItemHeight + lbDateRange.TopIndex;
if (i < lbDateRange.Items.Count) and (i>=0) then
lbDateRange.Hint := lbDateRange.Items[i];
end;
procedure TfraGMV_GridGraph.SaveStatus;
procedure SaveIntegerItem(aValue:Integer;aName:String);
var
s: String;
begin
try
s := IntToStr(aValue);
setUserSettings(aName,s);
except
end;
end;
procedure SaveBooleanItem(aValue:Boolean;aName:String);
begin
try
if aValue then setUserSettings(aName,'ON')
else setUserSettings(aName,'OFF');
except
end;
end;
begin
try
GMVUser.Setting[usGridDateRange] := IntToStr(lbDateRange.ItemIndex);
except
end;
SaveIntegerItem(pnlGrid.Height,'GRIDSIZE');
SaveIntegerItem(bgColor,'GRAPHCOLOR');
SaveBooleanItem(pnlGraphOptions.Visible,'GRAPHOPTIONS');
SaveBooleanItem(cbValues.Checked,'GRAPHOPTIONS-1');
SaveBooleanItem(ckb3D.Checked,'GRAPHOPTIONS-2');
SaveBooleanItem(cbAllowZoom.Checked,'GRAPHOPTIONS-3');
SaveBooleanItem(cbChrono.Checked,'GRAPHOPTIONS-4');
SaveIntegerItem(GraphIndex,'GRAPH_INDEX');
SaveIntegerItem(GMVAbnormalText, 'ABNORMALTEXTCOLOR');
SaveIntegerItem(GMVAbnormalBkgd, 'ABNORMALBGCOLOR');
// SaveIntegerItem(GMVAbnormalTodayBkgd: integer = 15;
SaveBooleanItem(GMVAbnormalBold, 'ABNORMALBOLD');
SaveBooleanItem(GMVAbnormalQuals, 'ABNORMALQUALIFIERS');
SaveIntegerItem(GMVNormalText, 'NORMALTEXTCOLOR');
SaveIntegerItem(GMVNormalBkgd, 'NORMALBGCOLOR');;
// SaveIntegerItem(GMVNormalTodayBkgd: integer = 15;
SaveBooleanItem(GMVNormalBold, 'NORMALBOLD');
SaveBooleanItem(GMVNormalQuals, 'NORMALQUALIFIERS');
end;
procedure TfraGMV_GridGraph.RestoreUserPreferences;
var
s: String;
function getBoolean(aDefault:Boolean; aName,aTrueString:String):Boolean;
var
ss: String;
begin
ss := getUserSettings(aName);
if ss = '' then // zzzzzzandria 20090814
Result := aDefault // Remedy 342434
else //
Result := ss = aTrueString;
end;
function getInteger(aDefault:Integer;aName:String):Integer;
var
ss: String;
begin
ss := getUserSettings(aName);
if ss = '' then
Result := aDefault
else
try
Result := StrToIntDef(ss,aDefault);
except
Result := aDefault;
end;
end;
begin
s := getUserSettings('GRIDSIZE');
if s <> '' then pnlGrid.Height := StrToInt(s);
BGColor := getInteger(clWindow,'GRAPHCOLOR');
if BGColor = 0 then
BGColor := clWindow;
s := getUserSettings('GRAPHOPTIONS');
pnlGraphOptions.Visible := s <> 'OFF';
ShowHideGraphOptions1.Checked := s <> 'OFF';
{$IFNDEF DLL}
if assigned(frmGMV_UserMain) then
frmGMV_UserMain.ShowHideGraphOptions1.Checked := s <> 'OFF';
{$ENDIF}
cbValues.Checked := getBoolean(TRUE,'GRAPHOPTIONS-1','ON');
s := getUserSettings('GRAPHOPTIONS-4');
inc(iIgnoreCount);
cbChrono.Checked := s <> 'OFF';
dec(iIgnoreCount);
s := getUserSettings('GRAPHOPTIONS-3');
cbAllowZoom.Checked := s='ON';
chrtVitals.AllowZoom := s='ON';
acZoom.Execute;
s := getUserSettings('GRAPHOPTIONS-2');
ckb3D.Checked := (s='ON') and cbChrono.Checked;
ckb3D.Enabled := cbChrono.Checked;
if FrameStyle = fsVitals then
begin
s := getUserSettings('GRAPH_INDEX');
if s <> '' then
GraphIndex:= StrToInt(s)
else
GraphIndex:= 0;
GridRow:= GridRowByGraphIndex(GraphIndex);
end;
GMVAbnormalText := getInteger(GMVAbnormalText,'ABNORMALTEXTCOLOR');
GMVAbnormalBkgd := getInteger(GMVAbnormalBkgd, 'ABNORMALBGCOLOR');
// SaveIntegerItem(GMVAbnormalTodayBkgd: integer = 15;
GMVAbnormalBold := getBoolean(GMVAbnormalBold, 'ABNORMALBOLD','ON');
GMVAbnormalQuals := getBoolean(True, 'ABNORMALQUALIFIERS','ON'); //ZZZZZZBELLC 6/2/10
GMVNormalText := getInteger(GMVNormalText, 'NORMALTEXTCOLOR');
GMVNormalBkgd := getInteger(GMVNormalBkgd, 'NORMALBGCOLOR');;
// SaveIntegerItem(GMVNormalTodayBkgd: integer = 15;
GMVNormalBold := getBoolean(GMVNormalBold, 'NORMALBOLD','ON');
GMVNormalQuals := getBoolean(True, 'NORMALQUALIFIERS','ON'); //ZZZZZZBELLC 6/2/10
grdVitals.Invalidate;
end;
procedure TfraGMV_GridGraph.setGraphByABBR(aABBR:String);
var
aRow: Integer;
begin
if aABBR = 'BMI' then aRow := rBMI{8} // zzzzzzandria 060913 BMI selection
else
case VitalTypeByABBR(aABBR) of
vtTemp:aRow := rTemp{1};
vtPulse:aRow := rPulse{2};
vtResp: aRow := rResp{3};
vtPO2: aRow := rPOx{4};
vtBP: aRow := rBP{6};
vtHeight: aRow := rHeight{9};
vtWeight: aRow := rWeight{7};
// vtBMI: aRow := 8; // zzzzzzandria 060913 BMI selection
vtCircum: aRow := rGirth{10};
vtCVP: aRow := rCVP{11};
// vtIn: aRow := 8;
// vtOutput: aRow := 8;
vtPain: aRow := rPain{14};
else
aRow := 0;
end;
grdVitals.Invalidate;
getGraphByName(GraphNameByGridRow(aRow));
if GraphIndexByGridRow(aRow) <> iIgnoreGraph then
fGridRow := aRow;
GraphIndex := GraphIndexByGridRow(aRow);
grdVitals.Invalidate;
end;
procedure TfraGMV_GridGraph.chrtVitalsClickLegend(Sender: TCustomChart;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
ShowGraphReport;
end;
procedure TfraGMV_GridGraph.ShowGraphReport;
var
bData: Boolean;
iActiveSeries: Integer;
i,j,k,m: Integer;
sName,sLocation,
s,ss,s4: String;
ST,
SL: TStringList;
const
sF = '%-20s';
sNA = 'N/A';
function RowByName(aName:String):Integer;
begin
Result := -1;
if (aName = sgnTemp) or (aName = 'Temp.') then Result := rTemp{1}
else if (aName = sgnPulse)
or (aName = 'Pulse') then Result := rPulse{2}
else if (aName = sgnResp)
or (aName = 'Resp.') then Result := rResp{3}
else if (aName = 'Pulse Ox.') then Result := rPOx{4}
else if (aName = 'Sys.') then Result := rBP{6}
else if (aName = 'Dias.') then Result := -1
else if (aName = sgnWeight) then Result := rWeight{7}
else if (aName = 'BMI') then Result := rBMI{8}
else if (aName = sgnHeight) then Result := rHeight{9}
else if (aName = sgnGirth) then Result := rGirth{10}
else if (aName = sgnCVP) then Result := rCVP{11}
else if (aName = sgnIn) then Result := rIntake{12}
else if (aName = sgnOutput) then Result := rOutput{13}
else if (aName = sgnPain) then Result := rPain{14}
;
end;
procedure addTitle;
var
s: String; //CB Removed Sl (Remedy 370490)
begin
ss := ss + ' ' + Format(sF,['Location'])+Format(sF,['Entered By']); //CB Added space (Remedy 370490)
s := '';
while length(s) < Length(ss) do
s := s + '-';
SL.Add(ss);
SL.Add(s);
end;
begin
bData := False;
iActiveSeries := 0;
SL := TStringList.Create;
ST := TStringList.Create;
ss := Format(sF,['Date/Time']);
for i := 0 to chrtVitals.SeriesCount - 1 do
begin
if not chrtVitals.Series[i].Active then continue;
inc(iActiveSeries);
s := chrtVitals.Series[i].Title;
j := RowByName(s);
if j < 0 then continue;
if s = 'Sys.' then s := 'B/P';
ss := ss + Format(sF,[s]) ;
ST.Add(Format(sF,[s]));
ST.Objects[ST.Count-1] := Pointer(j);
if j = rPOx then
begin
ST.Add('');
ST.Objects[ST.Count-1] := Pointer(rPOx+1{5});
end;
end;
if iActiveSeries = 0 then
begin
ShowInfo('Graph Report on '+getPatientName,'The graph is empty',True);
exit;
end;
AddTitle;
for i := 1 to grdVitals.ColCount - 1 do
begin
s := '';
m := 0;
for j := 0 to ST.Count - 1 do
begin
k := Integer(Pointer(ST.Objects[j]));
ss := grdVitals.Cells[i, k];
case k of
rPOx: s4 := ss; // 4
rPOx+1: s := s + Format(sF,[s4+' '+ss]); // 5
else
s := s + Format(sF,[ss]);
end;
if k <> 4 then inc(m);
end;
if trim(s) <> '' then
begin
bData := True;
sName := grdVitals.Cells[i,rEnteredBy]; if sName = '' then sName := sNA;
sLocation := grdVitals.Cells[i,rLocation]; if sLocation = '' then sLocation := sNA;
k := m * 20;
while (Length(s) > k) and (copy(s,Length(s),1)=' ') and (s<>'') do
s := copy(s,1,Length(s)-1);
if Length(s) = k then
s := s + ' ';
s := Format(sF,[grdVitals.Cells[i,0]]) + s + Format(sF,[sLocation]);
k := (m+2) * 20;
while (Length(s) > k) and (copy(s,Length(s),1)=' ') and (s<>'') do
s := copy(s,1,Length(s)-1);
if Length(s) = k then
s := s + ' ';
s := s + Format(sF,[sName]);
SL.Add(s);
end;
end;
if not bData then
SL.Add('No data available in the graph')
else
begin
// Patient DOB
// Ward and Bed
// Page number
SL.Insert(0,'');
SL.Insert(0,'Location: '+ lblHospital.Caption); // zzzzzzandria 061116
SL.Insert(0,ptInfo); // zzzzzzandria 061116
SL.Insert(0,'Vitals on '+getPatientName+' ('+copy(edPatientInfo.Text,8,4)+')');
end;
ShowInfo('Graph Report on '+getPatientName,SL.Text,True);
SL.Free;
ST.Free;
end;
procedure TfraGMV_GridGraph.acZoomOutExecute(Sender: TObject);
var
d: Double;
i: Integer;
begin
if chrtVitals.LeftAxis.Maximum > iMaximumLimit then Exit;
try
i := StrToIntDef(edZoom.Text,50);
if i > 100 then i := 100;
if i = 100 then edZoom.Text := '100';
except
begin
edZoom.Text := '50';
i := 50;
end;
end;
d := i/100;
try
chrtVitals.LeftAxis.Maximum := (1+d) * chrtVitals.LeftAxis.Maximum;
if chrtVitals.LeftAxis.Minimum >=0 then
chrtVitals.LeftAxis.Minimum := (1-d) * chrtVitals.LeftAxis.Minimum;
except
on E: Exception do
ShowMessage('Zoom In'+#13#10+E.Message);
end;
end;
procedure TfraGMV_GridGraph.acZoomInExecute(Sender: TObject);
var
d: Double;
i: Integer;
begin
try
i := StrToIntDef(edZoom.Text,50);
except
begin
edZoom.Text := '50';
i := 50;
end;
end;
d := i/100;
if ((1-d) * chrtVitals.LeftAxis.Maximum >= (1+d) * chrtVitals.LeftAxis.Minimum) then
begin
try
chrtVitals.LeftAxis.Maximum := (1-d) * chrtVitals.LeftAxis.Maximum;
if chrtVitals.LeftAxis.Minimum >=0 then
chrtVitals.LeftAxis.Minimum := (1+d) * chrtVitals.LeftAxis.Minimum;
except
on E: Exception do
ShowMessage('Zoom Out'+#13#10+E.Message);
end;
end;
end;
procedure TfraGMV_GridGraph.acZoomResetExecute(Sender: TObject);
begin
try
chrtVitals.LeftAxis.Maximum := fAxisMax;
chrtVitals.LeftAxis.Minimum := fAxisMin;
except
on E: Exception do
ShowMessage('Zoom Reset '+#13#10+E.Message);
end;
end;
procedure TfraGMV_GridGraph.splGridGraphMoved(Sender: TObject);
begin
splGridGraph.Align := alTop;
Application.ProcessMessages;
splGridGraph.Align := alBottom;
Application.ProcessMessages;
end;
////////////////////////////////////////////////////////////////////////////////
// debug //
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.chrtVitalsDblClick(Sender: TObject);
begin
{$IFDEF AANTEST}
chrtVitals.CalcSize3DWalls;
ShowMessage(Format('Width = %d Height = %d',[chrtVitals.Width3d,chrtVitals.Height3D]));
{$ENDIF}
end;
procedure TfraGMV_GridGraph.acUpdateGridColorsExecute(Sender: TObject);
begin
UpdateUserSettings;
BGTodayColor := GMVNormalTodayBkgd;
try
grdVitals.Refresh;
except
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfraGMV_GridGraph.acPatientInfoExecute(Sender: TObject);
begin
ShowPatientInfo(PatientDFN,'Patient Inquiry for:'+edPatientName.Text +
' ' + edPatientInfo.Text); // zzzzzzandria 060308
end;
procedure TfraGMV_GridGraph.pnlPtInfoEnter(Sender: TObject);
begin
pnlPtInfo.BevelOuter := bvRaised; // zzzzzzandria 060308
end;
procedure TfraGMV_GridGraph.pnlPtInfoExit(Sender: TObject);
begin
pnlPtInfo.BevelOuter := bvNone; // zzzzzzandria 060308
end;
function TfraGMV_GridGraph.getPatientName:String;
begin
Result := edPatientName.Text;
end;
function TfraGMV_GridGraph.getPatientInfo:String;
begin
Result := edPatientInfo.Text;
end;
procedure TfraGMV_GridGraph.showVitalsReport;
var
sTime, sStart,sEnd,sLine, s,sItem,sVal: String;
j,iEnd,iCount,iStart,iStartLine,i: integer;
begin
s := '';
iCount := 0;
iStartLine := grdVitals.LeftCol + 2;
iStart := 1;
iEnd := grdVitals.ColCount-1;
for i := iStart to iEnd do
begin
if (i = iStart) then
sStart := grdVitals.Cells[i,0];
if (i = iEnd) then
sEnd := grdVitals.Cells[i,0];
sTime := Format(' %s',[grdVitals.Cells[i,0]]);
sVal := '';
sLine := '';
for j := 1 to grdVitals.RowCount - 1 do
begin
sItem := grdVitals.Cells[i,j];
if trim(sItem)<>'' then
begin
sLine := sLine + Format(' %s %s;',[grdVitals.Cells[0,j],sItem]);
sVal := sVal + sItem;
end;
end;
if Trim(sLine) <> '' then // R141401 - zzzzzzandria 060921 --------------
s := s + sTime + sLine + #13#10;
if sVal <> '' then inc(iCount);
end;
if trim(lblHospital.Caption) <> '' then
sLine := lblHospital.Caption
else
sLine := 'no location selected';
s := 'Patient Location: '+ sLine +#13#10 +
'Date Range: '+lblDateFromTitle.Caption + #13#10 +
'The following '+IntToStr(iCount)+
' lines are currently visible in the data grid display.'+#13#10 + s;
ShowInfo('Data Grid Report for '+getPatientName+ ' ' + getPatientInfo,s, False,iStartLine);
end;
procedure TfraGMV_GridGraph.acVitalsReportExecute(Sender: TObject);
begin
ShowVitalsReport;
end;
procedure TfraGMV_GridGraph.pnlPtInfoMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
pnlPtInfo.BevelOuter := bvLowered; // zzzzzzandria 060308
end;
procedure TfraGMV_GridGraph.pnlPtInfoMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
pnlPtInfo.BevelOuter := bvNone; // zzzzzzandria 060308
acPatientInfo.Execute;
end;
// R144771 (Zoom distorts Graph display
// Series.Marks.Clipped set to True
// Chart ClipPoints set to True
procedure TfraGMV_GridGraph.grdVitalsMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
Column, Row: Longint;
begin // 141396 - Scroll data cells
grdVitals.MouseToCell(X, Y, Column, Row);
if (Column < 0) or (Row < 0) then exit; //ZZZZZZBELLC
if (Column <= grdVitals.ColCount - 1) and (Row <= grdVitals.RowCount - 1) then
try
grdVitals.Hint := ' ' + grdVitals.Cells[Column,Row];
except
end;
end;
procedure TfraGMV_GridGraph.acRPCLogExecute(Sender: TObject);
begin
ShowRPCLog;
end;
procedure TfraGMV_GridGraph.acShowGraphReportExecute(Sender: TObject);
begin
ShowGraphReport;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit DSAzDlgSnapshotBlob;
interface
uses
Vcl.Buttons, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, System.Generics.Collections, Vcl.Graphics,
Vcl.Grids, Vcl.StdCtrls, Vcl.ValEdit;
type
TAzSnapshotBlob = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Bevel1: TBevel;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
edtModifiedSince: TEdit;
edtUnmodified: TEdit;
edtNoneMatch: TEdit;
edtMatch: TEdit;
vleMeta: TValueListEditor;
btnAddMetadata: TButton;
btnDelMetadata: TButton;
procedure btnAddMetadataClick(Sender: TObject);
procedure btnDelMetadataClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function GetModifiedSince: String;
function GetUnmodifiedSince: String;
function GetMatch: String;
function GetNoneMatch: String;
procedure AssignMetadata(const meta: TDictionary<String, String>);
procedure PopulateWithMetadata(const meta: TDictionary<String, String>);
function RawMetadata: TStrings;
end;
implementation
uses Vcl.Dialogs;
{$R *.dfm}
procedure TAzSnapshotBlob.AssignMetadata(
const meta: TDictionary<String, String>);
var
I, Count: Integer;
key, value: String;
begin
meta.Clear;
Count := vleMeta.Strings.Count;
for I := 0 to Count - 1 do
begin
key := vleMeta.Strings.Names[I];
value := vleMeta.Strings.ValueFromIndex[I];
if (Length(key) > 0) and (Length(value) > 0) then
meta.Add(key, value);
end;
end;
procedure TAzSnapshotBlob.btnAddMetadataClick(Sender: TObject);
begin
vleMeta.InsertRow('', '', true);
vleMeta.SetFocus;
end;
procedure TAzSnapshotBlob.btnDelMetadataClick(Sender: TObject);
var
row: Integer;
begin
row := vleMeta.Row;
if (row > 0) and (row < vleMeta.RowCount) then
vleMeta.DeleteRow(row);
end;
function TAzSnapshotBlob.GetModifiedSince: String;
begin
Result := edtModifiedSince.Text;
end;
function TAzSnapshotBlob.GetUnmodifiedSince: String;
begin
Result := edtUnmodified.Text;
end;
function TAzSnapshotBlob.GetMatch: String;
begin
Result := edtMatch.Text;
end;
function TAzSnapshotBlob.GetNoneMatch: String;
begin
Result := edtNoneMatch.Text;
end;
procedure TAzSnapshotBlob.PopulateWithMetadata(
const meta: TDictionary<String, String>);
var
keys: TArray<String>;
I, Count: Integer;
begin
vleMeta.Strings.Clear;
keys := meta.Keys.ToArray;
Count := meta.Keys.Count;
for I := 0 to Count - 1 do
vleMeta.Values[keys[I]] := meta.Items[keys[I]];
end;
function TAzSnapshotBlob.RawMetadata: TStrings;
begin
Result := vleMeta.Strings
end;
end.
|
unit Consts;
interface
const
cLivePreviewServerManagerText = 'FireUI Live Preview Server';
cLivePreviewServerProfileText = 'FireUI Live Preview Server Profile';
cLivePreviewGroup = 'FireUILivePreview';
cLivePreviewManagerClientText = 'FireUI Live Preview Client';
cLivePreviewProfileClientText = 'FireUI Live Preview Client Profile';
cTetServerIDIndex = 'TetServerID';
cNonVisibleCommand = 'Visibility';
cHideCommand = 'Hide';
cFormStreamResourceName = 'FormStream';
cDevicNameResourceName = 'DeviceName';
cDeviceDescriptionResourceName = 'DeviceDescription';
cDevicePlatformResourceName = 'DevicePlatform';
cDeviceProtocolResourceName = 'Version';
cDeviceProtocol = '1.00';
resourcestring
sConnDetail = '%s at %s';
sDiscoverTargetsAt = 'Discover Targets at';
sAdvancedOptions = 'Advanced options';
sServerNeedsAuth = 'Private Server';
sPassword = #9'Password'; // First char below #30 will tell InputQuery to treat the box as a password
sConnect = 'Connect';
sDisconnect = 'Disconnect';
sConnecting = 'Connecting...';
sAuthenticating = 'Authenticating...';
sAppName = 'FireUI App Preview';
sAppVersion = 'v1.00';
sAppNameFormat = '%s %s';
sDiscoveringIP = 'Scaning %s';
sDiscoveringNoIP = 'Scanning the local network';
cCannotConnectTo = 'Cannot connect to ';
cErrorGettingPowerService = 'Could not get Power Service';
implementation
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
hrc: HGLRC;
Vertex : Array [0..3, 0..1] of GLFloat;
Colors : Array [0..3, 0..2] of GLFloat;
procedure Init;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
procedure glVertexPointer (size: GLint; atype: GLenum;
stride: GLsizei; data: pointer); stdcall; external OpenGL32;
procedure glColorPointer (size: GLint; atype: GLenum; stride: GLsizei;
data: pointer); stdcall; external OpenGL32;
procedure glDrawArrays (mode: GLenum; first: GLint; count: GLsizei);
stdcall; external OpenGL32;
procedure glEnableClientState (aarray: GLenum); stdcall; external OpenGL32;
procedure glDisableClientState (aarray: GLenum); stdcall; external OpenGL32;
procedure glArrayElement (i: GLint); stdcall; external OpenGL32;
const
GL_VERTEX_ARRAY = $8074;
GL_COLOR_ARRAY = $8076;
procedure TfrmGL.Init;
begin
Vertex[0][0] := -0.9;
Vertex[0][1] := -0.9;
Colors[0][0] := 0.1;
Colors[0][1] := 0.5;
Colors[0][2] := 0.85;
Vertex[1][0] := -0.9;
Vertex[1][1] := 0.9;
Colors[1][0] := 0.85;
Colors[1][1] := 0.1;
Colors[1][2] := 0.5;
Vertex[2][0] := 0.9;
Vertex[2][1] := 0.9;
Colors[2][0] := 0.85;
Colors[2][1] := 0.85;
Colors[2][2] := 0.85;
Vertex[3][0] := 0.9;
Vertex[3][1] := -0.9;
Colors[3][0] := 0.5;
Colors[3][1] := 0.85;
Colors[3][2] := 0.1;
end;
{=======================================================================
Перерисвока окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glViewPort (0, 0, ClientWidth, ClientHeight);
glClearColor (0.5, 0.5, 0.75, 1.0);
glClear (GL_COLOR_BUFFER_BIT);
glVertexPointer(2, GL_FLOAT, 0, @Vertex);
glColorPointer(3, GL_FLOAT, 0, @Colors);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glBegin (GL_POLYGON);
glArrayElement(0);
glArrayElement(1);
glArrayElement(2);
glArrayElement(3);
glEnd;
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
SwapBuffers(Canvas.Handle);
wglMakeCurrent(0, 0);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
SetDCPixelFormat(Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
Init;
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
end;
end.
|
unit ZsbDLL;
interface
uses Forms,Windows;
function Get16MD5ForString(str: WideString): WideString; stdcall; external 'MD5FromDelphi.dll';
function GetVersionString(FileName: WideString): WideString; stdcall; external 'GetVersion.dll';
function GetStringFromIni(FromFile,Section, Ident:WideString): WideString;stdcall; external 'OperIniFile.dll';
function SetStringToIni(ToFile,Section,Ident,strValue:WideString): Boolean;stdcall; external 'OperIniFile.dll';
function SimpleMSNPopUpShow(strText: string;iStartX,iStartY:SmallInt): Boolean; stdcall;external 'MSNPopUpHelper.dll';
function MSNPopUpShow(strText: string; strTitle: string = '提示信息'; iShowTime: SmallInt = 10;
iHeight: SmallInt = 100; iWidth: SmallInt = 200): Boolean;stdcall;external 'MSNPopUpHelper.dll';
procedure ExceptionShowStrNoApp(eMessage: string; bBlack: Boolean = False); stdcall; external 'ExceptionShow.dll';
procedure ShowInfoTips(h: HWND; strShowMess: string; IconType: Integer = 1; strShowCaption: string = '提示信息'; bAutoClose: Boolean = True; iShowTime: Integer = 2000); stdcall; external 'InfoTips.dll';
//function ZsbMsgBoxOk(var App: TApplication; ParentForm: TForm; stsShow: string): Boolean; stdcall; external 'ZsbMessageBox.dll';
//procedure ZsbMsgErrorInfo(var App: TApplication; ParentForm: TForm; stsShow: string); stdcall; external 'ZsbMessageBox.dll';
//function ZsbMsgBoxOkNoBlackNoApp(ParentForm: TForm; stsShow: string): Boolean; stdcall; external 'ZsbMessageBox.dll';
//procedure ZsbMsgErrorInfoNoBlackNoApp(ParentForm: TForm; stsShow: string); stdcall; external 'ZsbMessageBox.dll';
//procedure ZsbMsgErrorInfo(var App: TApplication; ParentForm: TForm; stsShow: string); stdcall; external 'ZsbMessageBox.dll';
procedure ZsbMsgErrorInfoNoApp(ParentForm: TForm; stsShow: string); stdcall; external 'ZsbMessageBox.dll';
function ZsbMsgBoxOkNoApp(ParentForm: TForm; stsShow: string): Boolean; stdcall; external 'ZsbMessageBox.dll';
//function ZsbMsgBoxOk(var App: TApplication; ParentForm: TForm; stsShow: string): Boolean; stdcall; external 'ZsbMessageBox.dll';
implementation
uses U_main;
end.
|
unit uICU300FirmwareData;
interface
uses
SysUtils, Classes;
type
TSendPacketEvent = procedure(Sender: TObject; aSendHexData,aViewHexData: string) of object;
TMainRequestProcess = procedure(Sender: TObject; aEcuID,aNo,aDeviceType: string;aMaxSize,aCurPosition:integer) of object;
TICU300FirmwareProcess = class(TComponent)
private
FMaxSize: integer;
FCurrentPosition: integer;
FNO: string;
FECUID: string;
FDeviceType: string;
FOnMainRequestProcess: TMainRequestProcess;
procedure SetCurrentPosition(const Value: integer);
public
property ECUID : string read FECUID write FECUID;
property NO : string read FNO write FNO;
property DeviceType : string read FDeviceType write FDeviceType;
property MaxSize : integer read FMaxSize write FMaxSize;
property CurrentPosition : integer read FCurrentPosition write SetCurrentPosition;
public
property OnMainRequestProcess : TMainRequestProcess read FOnMainRequestProcess write FOnMainRequestProcess;
end;
TdmICU300FirmwareData = class(TDataModule)
private
ICU300FWData : PChar;
FDeviceID: string;
FPacketSize: integer;
FFirmwareFileName: string;
FCurrentIndex: Integer;
FSendMsgNo: integer;
FFileSize: integer;
FOnSendPacketEvent: TSendPacketEvent;
FDeviceType: string;
procedure SetFirmwareFileName(const Value: string);
{ Private declarations }
public
procedure SendICU300FirmWarePacket(aCmd,aData,aVer:string);
public
{ Public declarations }
property DeviceID : string read FDeviceID write FDeviceID;
property DeviceType : string read FDeviceType write FDeviceType;
property PacketSize : integer read FPacketSize write FPacketSize;
property SendMsgNo : integer read FSendMsgNo write FSendMsgNo;
property FirmwareFileName : string read FFirmwareFileName write SetFirmwareFileName;
property FileSize : integer read FFileSize write FFileSize;
property CurrentIndex : Integer read FCurrentIndex write FCurrentIndex;
public
property OnSendPacketEvent :TSendPacketEvent read FOnSendPacketEvent write FOnSendPacketEvent;
end;
var
dmICU300FirmwareData: TdmICU300FirmwareData;
implementation
{$R *.dfm}
uses
uCommon,
uLomosUtil;
{ TdmICU300FirmwareData }
procedure TdmICU300FirmwareData.SendICU300FirmWarePacket(aCmd, aData,
aVer: string);
var
cKey : char;
stHexData : string;
stHexFirmWareData : string;
nDataLength : integer;
nSendFirmwarePacketSize : integer;
i : integer;
begin
if CurrentIndex * PacketSize + 1 > FileSize then Exit;
stHexFirmWareData := '';
nSendFirmwarePacketSize := PacketSize;
for i := (CurrentIndex * PacketSize) to (CurrentIndex * PacketSize + (PacketSize-1)) do
begin
if i > FileSize - 1 then
begin
nSendFirmwarePacketSize := i - (CurrentIndex * PacketSize);
Break;
end;
stHexFirmWareData := stHexFirmWareData + Dec2Hex(Ord(ICU300FWData[i]),2) + ' ';
end;
cKey := #$20;
nDataLength:= (G_nIDLength + 14) + Length(aData) + nSendFirmwarePacketSize;
stHexData:= Ascii2Hex(STX +FillZeroNumber(nDataLength,3)+ cKey + aVer + DeviceID+ aCmd+InttoStr(SendMsgNo) + aData);
stHexData := stHexData + stringReplace(stHexFirmWareData,' ','',[rfReplaceAll]);
stHexData:= stHexData+ MakeHexCSData(stHexData+'03',G_nProgramType) + '03';
if Assigned(FOnSendPacketEvent) then
begin
OnSendPacketEvent(self,stHexData,stHexFirmWareData);
end;
//aKey:= Ord(ACkStr[5]);
//ACkStr2:= Copy(ACKStr,1,5)+EncodeData(aKey,Copy(ACkStr,6,Length(ACkStr)-6))+ETX;
//if aMsgNo >= 9 then Send_MsgNo:= 0
//else Send_MsgNo:= aMsgNo + 1;
end;
procedure TdmICU300FirmwareData.SetFirmwareFileName(const Value: string);
var
iBytesRead: Integer;
iFileHandle: Integer;
begin
//if FFirmwareFileName = Value then Exit;
FFirmwareFileName := Value;
if Not FileExists(Value) then Exit;
//여기서 파일을 읽어 들이자
iFileHandle := FileOpen(Value, fmOpenRead);
FileSize := FileSeek(iFileHandle,0,2);
FileSeek(iFileHandle,0,0);
ICU300FWData := nil;
ICU300FWData := PChar(AllocMem(FileSize + 1));
iBytesRead := FileRead(iFileHandle, ICU300FWData^, FileSize);
FileClose(iFileHandle);
end;
{ TICU300FirmwareProcess }
procedure TICU300FirmwareProcess.SetCurrentPosition(const Value: integer);
begin
FCurrentPosition := Value;
if Assigned(FOnMainRequestProcess) then
begin
OnMainRequestProcess(self,EcuID,No,DeviceType,MaxSize,Value);
end;
end;
end.
|
unit ToolMngr;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ExtCtrls, Menus;
type
{$IFDEF VER120}
TWMContextMenu = packed record
Msg: Cardinal;
hWnd: HWND;
case Integer of
0: (
XPos: Smallint;
YPos: Smallint);
1: (
Pos: TSmallPoint;
Result: Longint);
end;
{$ENDIF}
TToolContainer = class(TForm)
pgTools: TPageControl;
pmTools: TPopupMenu;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FTools: TList;
FOnNeedClose: TNotifyEvent;
FOnPopupChange: TNotifyEvent;
procedure ArrangeTools;
function GetPageForm(PageIndex: integer): TCustomForm;
function FindPage(ToolForm: TCustomForm): TTabSheet;
procedure PopupClosePage(Sender: TObject);
procedure PopupCloseAll(Sender: TObject);
procedure PopupToolClick(Sender: TObject);
procedure DoToolsPopup(Sender: TObject; MousePos: TPoint);
procedure WMContextMenu(var Message: TWMContextMenu); message WM_CONTEXTMENU;
function GetActivePageForm: TCustomForm;
procedure SetActivePageForm(const Value: TCustomForm);
function GetTool(Index: integer): TCustomForm;
function GetToolCount: integer;
protected
procedure DoPopupChange; virtual;
public
{ Public declarations }
procedure InsertTool(ToolForm: TCustomForm);
procedure RemoveTool(ToolForm: TCustomForm);
procedure RemoveAll;
function IsToolExists(ToolForm: TCustomForm): boolean;
property Tools[Index: integer]: TCustomForm read GetTool;
property ToolCount: integer read GetToolCount;
property ActivePageForm: TCustomForm read GetActivePageForm
write SetActivePageForm;
property OnNeedClose: TNotifyEvent read FOnNeedClose write FOnNeedClose;
property OnPopupChange: TNotifyEvent read FOnPopupChange
write FOnPopupChange;
end;
var
ToolForms: TList;
ToolContainer: TToolContainer;
procedure RegisterToolForm(ToolForm: TCustomForm);
procedure UnRegisterToolForm(ToolForm: TCustomForm);
function FindChildContainer(Control: TWinControl): TToolContainer;
function FindToolParentContainer(ToolForm: TCustomForm): TToolContainer;
function FindToolForm(const AName: string): TCustomForm;
implementation
{$R *.DFM}
function FindToolParentContainer(ToolForm: TCustomForm): TToolContainer;
var Control: TControl;
begin
Result := Nil;
if not Assigned(ToolForm) then exit;
Control := ToolForm.Parent;
while Assigned(Control) do
if Control is TToolContainer then begin
Result := TToolContainer(Control);
break;
end else
Control := Control.Parent;
end;
function FindChildContainer(Control: TWinControl): TToolContainer;
var i: integer;
begin
Result := Nil;
with Control do
for i:=0 to ControlCount-1 do
if Controls[i] is TToolContainer then begin
Result := TToolContainer(Controls[i]);
break;
end;
end;
function FindToolForm(const AName: string): TCustomForm;
var i: integer;
begin
Result := Nil;
for i:=0 to ToolForms.Count-1 do
if TCustomForm(ToolForms[i]).Name = AName then begin
Result := TCustomForm(ToolForms[i]);
break;
end;
end;
procedure RegisterToolForm(ToolForm: TCustomForm);
begin
if not Assigned(ToolForms) then ToolForms := TList.Create;
ToolForms.Add(ToolForm);
end;
procedure UnRegisterToolForm(ToolForm: TCustomForm);
var Container: TToolContainer;
begin
if Assigned(ToolForms) then begin
ToolForms.Remove(ToolForm);
if ToolForms.Count = 0 then
{$IFDEF VER120}
begin
ToolForms.Free;
ToolForms := Nil;
end;
{$ELSE}
FreeAndNil(ToolForms);
{$ENDIF}
end;
Container := FindToolParentContainer(ToolForm);
if Assigned(Container) then Container.RemoveTool(ToolForm);
end;
// TToolContainer ///////////////////////////////////////////////////////////
procedure TToolContainer.FormCreate(Sender: TObject);
begin
FTools := TList.Create;
end;
procedure TToolContainer.FormDestroy(Sender: TObject);
begin
FTools.Free;
end;
procedure TToolContainer.FormShow(Sender: TObject);
begin
with pgTools do begin
Left := -1;
Top := 0;
Width := Self.ClientWidth +3;
Height := Self.ClientHeight +2;
end;
end;
procedure TToolContainer.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
{ FTools.Clear;
ArrangeTools; }
Action := caFree;
end;
procedure TToolContainer.DoPopupChange;
begin
if Assigned(FOnPopupChange) then FOnPopupChange(Self);
end;
function TToolContainer.GetTool(Index: integer): TCustomForm;
begin
Result := TCustomForm(FTools[Index]);
end;
function TToolContainer.GetToolCount: integer;
begin
Result := FTools.Count;
end;
procedure TToolContainer.InsertTool(ToolForm: TCustomForm);
var Container: TToolContainer;
begin
if not Assigned(ToolForm) or (FTools.IndexOf(ToolForm) >= 0) then exit;
Container := FindToolParentContainer(ToolForm);
if Assigned(Container) and (Container <> Self) then
Container.RemoveTool(ToolForm);
FTools.Add(ToolForm);
ArrangeTools;
DoPopupChange;
end;
procedure TToolContainer.RemoveTool(ToolForm: TCustomForm);
begin
FTools.Remove(ToolForm);
ArrangeTools;
if (FTools.Count = 0) and Assigned(FOnNeedClose) then FOnNeedClose(Self);
if not (csDestroying in ComponentState) then DoPopupChange;
end;
procedure TToolContainer.RemoveAll;
begin
FTools.Clear;
ArrangeTools;
if (FTools.Count = 0) and Assigned(FOnNeedClose) then FOnNeedClose(Self);
if not (csDestroying in ComponentState) then DoPopupChange;
end;
function TToolContainer.GetPageForm(PageIndex: integer): TCustomForm;
begin
Result :=
TCustomForm( TWinControl(pgTools.Pages[PageIndex].Controls[0]).Controls[0] );
end;
function TToolContainer.FindPage(ToolForm: TCustomForm): TTabSheet;
var i: integer;
begin
Result := Nil;
for i:=0 to FTools.Count-1 do
if GetPageForm(i) = ToolForm then begin
Result := pgTools.Pages[i];
break;
end;
end;
procedure TToolContainer.ArrangeTools;
var i, Index: integer;
Exists: array of boolean;
ToolForm: TCustomForm;
Page: TTabSheet;
PagePanel: TPanel;
begin
SetLength(Exists, FTools.Count);
FillChar(Exists[0], Length(Exists) * SizeOf(Exists[0]), 0);
i := pgTools.PageCount-1;
while i >= 0 do begin
ToolForm := GetPageForm(i);
Index := FTools.IndexOf(ToolForm);
if Index < 0 then begin
ToolForm.Hide;
ToolForm.Parent := Nil;
try
pgTools.Pages[i].Free
except
end;
end else
Exists[Index] := True;
dec(i);
end;
for i:=0 to Length(Exists)-1 do begin
if Exists[i] then continue;
ToolForm := TCustomForm(FTools[i]);
Page := TTabSheet.Create(Self);
Page.PageControl := pgTools;
Page.Caption := ToolForm.Caption;
PagePanel := TPanel.Create(Self);
with PagePanel do begin
Parent := Page;
Align := alClient;
BevelOuter := bvNone;
Caption := '';
end;
with ToolForm do begin
Parent := PagePanel;
SetBounds(0, 0, Width, Height);
Show;
end;
end;
end;
function TToolContainer.IsToolExists(ToolForm: TCustomForm): boolean;
begin
Result := FTools.IndexOf(ToolForm) >= 0;
end;
procedure TToolContainer.PopupClosePage(Sender: TObject);
begin
RemoveTool(ActivePageForm);
end;
procedure TToolContainer.PopupCloseAll(Sender: TObject);
begin
RemoveAll;
end;
procedure TToolContainer.PopupToolClick(Sender: TObject);
var ToolForm: TCustomForm;
//Container: TToolContainer;
begin
if not (Sender is TMenuItem) then exit;
ToolForm := TCustomForm(TMenuItem(Sender).Tag);
{Container := }FindToolParentContainer(ToolForm);
if IsToolExists(ToolForm) then
RemoveTool(ToolForm)
else begin
InsertTool(ToolForm);
pgTools.ActivePage := FindPage(ToolForm);
end;
end;
function TToolContainer.GetActivePageForm: TCustomForm;
begin
Result := GetPageForm( pgTools.ActivePage.PageIndex );
end;
procedure TToolContainer.SetActivePageForm(const Value: TCustomForm);
begin
pgTools.ActivePage := FindPage(Value);
end;
procedure TToolContainer.DoToolsPopup(Sender: TObject;
MousePos: TPoint);
var i: integer;
pmItem: TMenuItem;
ToolForm: TCustomForm;
begin
if not Assigned(ToolForms) or (ToolForms.Count = 0) then exit;
with pmTools do begin
{$IFNDEF VER120}
Items.Clear;
{$ELSE}
while Items.Count > 0 do Items.Delete(Items.Count-1);
{$ENDIF}
pmItem := TMenuItem.Create(pmTools);
pmItem.Caption := '&Close';
pmItem.OnClick := PopupClosePage;
Items.Add(pmItem);
pmItem := TMenuItem.Create(pmTools);
pmItem.Caption := '-';
Items.Add(pmItem);
for i:=0 to ToolForms.Count-1 do begin
ToolForm := TCustomForm(ToolForms[i]);
pmItem := TMenuItem.Create(pmTools);
pmItem.Caption := ToolForm.Caption;
pmItem.OnClick := PopupToolClick;
pmItem.Tag := integer(ToolForm);
if IsToolExists(ToolForm) then pmItem.Checked := true;
Items.Add(pmItem);
end;
pmItem := TMenuItem.Create(pmTools);
pmItem.Caption := '-';
Items.Add(pmItem);
pmItem := TMenuItem.Create(pmTools);
pmItem.Caption := 'Close &All';
pmItem.OnClick := PopupCloseAll;
Items.Add(pmItem);
MousePos := Self.ClientToScreen(MousePos);
Popup(MousePos.X, MousePos.Y);
end;
end;
procedure TToolContainer.WMContextMenu(var Message: TWMContextMenu);
var Pt: TPoint;
i: integer;
Found: boolean;
begin
Pt := ScreenToClient(Point(Message.XPos, Message.YPos));
if PtInRect(pgTools.BoundsRect, Pt) then begin
dec(Pt.X, pgTools.Left);
dec(Pt.Y, pgTools.Top);
Found := False;
for i:=0 to pgTools.ControlCount-1 do
if PtInRect(pgTools.Controls[i].BoundsRect, Pt) then begin
Found := True;;
break;
end;
if Found then
inherited
else begin
DoToolsPopup(pgTools, Pt);
Message.Result := 1;
end;
end else
inherited;
end;
initialization
finalization
ToolForms.Free;
end.
|
unit TestTry;
{ AFS March 2000
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
This unit tests layout of try..except and try..finally blocks
}
interface
implementation
uses Dialogs, SysUtils, Math;
procedure TestRaise;
begin
raise Exception.Create('Monkey error: please insert soy');
end;
procedure TestRaiseAt;
begin
raise Exception.Create('Shatner error: please insert toupee') at @TestRaiseAt;
end;
procedure TestTryRaise;
begin
try
ShowMessage ('Start');
except
ShowMessage ('except');
raise
end;
end;
procedure TestTryProc;
begin
try ShowMessage ('Start'); try ShowMessage ('trying');
try ShowMessage ('still trying'); finally ShowMessage ('going...'); end;
except ShowMessage ('except'); end;
finally ShowMessage ('Finally!'); end;
end;
procedure Simple;
begin
try
TesttryProc;
except
end;
try
TesttryProc;
except
SHowMessage('It Failed');
end;
end;
procedure ExceptBlock;
begin
try
TesttryProc;
except
on E: Exception do
begin
ShowMessage('There was an exception: ' + E.Message);
end;
end;
end;
procedure complex;
var
liLoop: integer;
begin
try
liLoop := 0;
while liLoop < 10 do
begin
TesttryProc;
inc(liloop);
end;
except
on E: Exception do
begin
ShowMessage('There was an exception: ' + E.Message);
end;
end;
end;
procedure TestSimpleElse;
begin
try
TestTryProc;
except
on E2: EInvalidArgument do
ShowMessage('There was an invalid arg exception: ' + E2.Message);
else
Raise;
end;
try
TestTryProc;
except
on E: EMathError do
begin
ShowMessage('There was a math error: ' + E.Message);
end
else
begin
Raise;
end;
end;
try
TestTryProc;
except
on E: EMathError do
begin
ShowMessage('There was a math error: ' + E.Message);
end
else ;
end;
try
TestTryProc;
except
on E: EMathError do
begin
ShowMessage('There was a math error: ' + E.Message);
end
else
begin
end;
end;
end;
procedure MoreComplexExceptionHandler;
var
liLoop: integer;
begin
try
TesttryProc;
except
on E2: EInvalidArgument do
ShowMessage('There was an invalid arg exception: ' + E2.Message);
on E: EMathError do
begin
ShowMessage('There was an exception: ' + E.Message);
end;
on EOverflow do
ShowMessage('There was an underflow exception');
else
Raise;
end;
end;
procedure TestReraise;
begin
try
TesttryProc;
except
ShowMessage('There was an exception');
Raise;
end;
end;
procedure TestReraise2;
var
li: integer;
begin
try
TesttryProc;
except
ShowMessage('There was an exception');
// whole buncha statements
ShowMessage('There was an exception');
li := 0;
ShowMessage('There was an exception');
for li := 0 to 10 do
ShowMessage('There was an exception');
begin
TesttryProc;
end;
Raise;
end;
end;
procedure TestBigFinally;
var
li: integer;
begin
try
TesttryProc;
finally
ShowMessage('There was an exception');
// whole buncha statements
ShowMessage('There was an exception');
li := 0;
ShowMessage('There was an exception');
for li := 0 to 10 do
ShowMessage('There was an exception');
begin
TesttryProc;
end;
end;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls,
Dialogs, SysUtils,
OpenGL;
type
TfrmGL = class(TForm)
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Timer1Timer(Sender: TObject);
private
DC: HDC;
hrc: HGLRC;
qobj : GLUquadricObj ;
transparent : GLfloat;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
{красная сфера внутри}
glColor3f(1.0, 0.0, 0.0);
gluSphere(qobj, 0.75, 20, 20);
{наружняя сфера}
glColor4f(1.0, 1.0, 1.0, transparent);
gluSphere (qObj, 1.0, 20, 20);
SwapBuffers(DC);
EndPaint(Handle, ps);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
const
mat_specular : Array [0..3] of GLFloat = (1.0, 1.0, 1.0, 1.0);
mat_shininess : GLFloat = 50.0;
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
glMaterialfv(GL_FRONT, GL_SPECULAR, @mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, @mat_shininess);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
qObj := gluNewQuadric;
transparent := 0.0;
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
{включаем режим смешения}
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
end;
{=======================================================================
Обработка нажатия клавиши}
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
If Key = VK_SPACE then begin
transparent := 0;
Timer1.Enabled := True;
end;
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(2.0, 1.0, 95.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0.0, 0.0, -100.0);
glRotatef (90.0, 0.0, 1.0, 0.0);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
gluDeleteQuadric(qObj);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.Timer1Timer(Sender: TObject);
begin
transparent := transparent + 0.05;
If transparent > 1.0 then begin
transparent := 1.0;
Timer1.Enabled := False;
end;
InvalidateRect(Handle, nil, False);
end;
end.
|
unit ccSphericalCapFrame;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, ExtCtrls, StdCtrls, IniFiles,
ccBaseFrame;
type
{ TSphericalCapFrame }
TSphericalCapFrame = class(TBaseFrame)
Bevel3: TBevel;
CbAreaUnits: TComboBox;
CbCapaUnits: TComboBox;
CbRadiusAUnits: TComboBox;
CbRadiusBUnits: TComboBox;
EdRadiusA: TEdit;
EdEps: TEdit;
EdRadiusB: TEdit;
LblArea: TLabel;
LblCapa: TLabel;
LblCapaPerArea: TLabel;
LblRadiusA: TLabel;
LblEps: TLabel;
LblRadiusB: TLabel;
Panel1: TPanel;
TxtArea: TEdit;
TxtCapa: TEdit;
TxtCapaPerArea: TEdit;
TxtCapaPerAreaUnits: TLabel;
private
{ private declarations }
protected
procedure ClearResults; override;
procedure SetEditLeft(AValue: Integer); override;
public
constructor Create(AOwner: TComponent); override;
procedure Calculate; override;
procedure ReadFromIni(ini: TCustomIniFile); override;
function ValidData(out AMsg: String; out AControl: TWinControl): Boolean; override;
procedure WriteToIni(ini: TCustomIniFile); override;
end;
implementation
{$R *.lfm}
uses
ccGlobal, ccStrings;
constructor TSphericalCapFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIniKey := 'Spherical';
end;
procedure TSphericalCapFrame.Calculate;
var
ra, rb, eps : extended;
A, Capa : double;
fa, fc : double;
capaFmt: String;
capaUnits, areaUnits: string;
begin
try
if (EdRadiusA.Text = '') or not TryStrToFloat(EdRadiusA.Text, ra) then exit;
if ra = 0 then exit;
if (EdRadiusB.Text = '') or not TryStrToFloat(EdRadiusB.Text, rb) then exit;
if ra >= rb then exit;
if (EdEps.Text = '') or not TryStrToFloat(EdEps.Text, eps) then exit;
if CbRadiusAUnits.ItemIndex = -1 then exit;
if CbRadiusBUnits.ItemIndex = -1 then exit;
if CbAreaUnits.ItemIndex = -1 then exit;
if CbCapaUnits.ItemIndex = -1 then exit;
ra := ra * Lenfactor[TLenUnits(CbRadiusAUnits.ItemIndex)];
rb := rb * LenFactor[TLenUnits(CbRadiusBUnits.ItemIndex)];
fa := AreaFactor[TAreaUnits(CbAreaUnits.ItemIndex)];
fc := CapaFactor[TCapaUnits(CbCapaUnits.ItemIndex)];
A := 1.0/6.0 * pi *(ra + rb)*(ra + rb)*(ra + rb);
Capa := 4.0 * pi * eps0 * eps / (1.0/ra - 1.0/rb);
if CbCapaUnits.Text='F' then
capaFmt := CapaExpFormat
else
capaFmt := CapaStdFormat;
capaUnits := CbCapaUnits.Items[CbCapaUnits.ItemIndex];
areaUnits := CbAreaUnits.Items[CbAreaUnits.ItemIndex];
// Area
TxtArea.Text := FormatFloat(AreaStdFormat, A / fa);
// Capacitance
TxtCapa.Text := FormatFloat(capafmt, Capa / fc);
// Capacitance per area
TxtCapaPerArea.Text := FormatFloat(CapaPerAreaFormat, Capa / A * fa / fc);
TxtCapaPerAreaUnits.Caption := Format('%s/%s', [capaUnits, areaUnits]);
except
ClearResults;
end;
end;
procedure TSphericalCapFrame.ClearResults;
begin
TxtCapa.Clear;
TxtArea.Clear;
TxtCapaPerArea.Clear;
end;
procedure TSphericalCapFrame.ReadFromIni(ini: TCustomIniFile);
var
fs: TFormatSettings;
s: String;
value: Extended;
begin
fs := DefaultFormatSettings;
fs.DecimalSeparator := '.';
s := ini.ReadString(FIniKey, 'Radius A', '');
if (s <> '') and TryStrToFloat(s, value, fs) then
EdRadiusA.Text := FloatToStr(value) else
EdRadiusA.Clear;
s := ini.ReadString(FIniKey, 'Radius B', '');
if (s <> '') and TryStrToFloat(s, value, fs) then
EdRadiusB.Text := FloatToStr(value) else
EdRadiusB.Clear;
s := ini.ReadString(FIniKey, 'eps', '');
if (s <> '') and TryStrToFloat(s, value, fs) then
EdEps.Text := FloatToStr(value) else
EdEps.Clear;
s := ini.ReadString(FIniKey, 'Radius A units', '');
if (s <> '') then
CbRadiusAUnits.ItemIndex := CbRadiusAUnits.Items.IndexOf(s) else
CbRadiusAUnits.ItemIndex := -1;
s := ini.ReadString(FIniKey, 'Radius B units', '');
if (s <> '') then
CbRadiusBUnits.ItemIndex := CbRadiusBUnits.Items.IndexOf(s) else
CbRadiusBUnits.ItemIndex := -1;
s := ini.ReadString(FIniKey, 'Area units', '');
if (s <> '') then
CbAreaUnits.ItemIndex := CbAreaUnits.Items.IndexOf(s) else
CbAreaUnits.ItemIndex := -1;
s := ini.ReadString(FIniKey, 'Capa units', '');
if (s <> '') then
CbCapaUnits.ItemIndex := CbCapaUnits.Items.Indexof(s) else
CbCapaUnits.ItemIndex := -1;
Calculate;
end;
procedure TSphericalCapFrame.SetEditLeft(AValue: Integer);
begin
if AValue = FEditLeft then exit;
inherited;
EdRadiusA.Left := FEditLeft;
TxtArea.Left := FEditLeft;
TxtArea.Width := EdRadiusA.Width;
Panel1.Height := TxtCapaPerArea.Top + TxtCapaPerArea.Height + TxtArea.Top;
Width := CbRadiusAUnits.Left + CbRadiusAUnits.Width + 2*FControlDist;
end;
function TSphericalCapFrame.ValidData(out AMsg: String; out AControl: TWinControl
): Boolean;
begin
Result := false;
if not IsValidNumber(EdRadiusA, AMsg) then begin
AControl := EdRadiusA;
exit;
end;
if not IsValidNumber(EdRadiusB, AMsg) then begin
AControl := EdRadiusB;
exit;
end;
if not IsValidNumber(EdEps, AMsg) then begin
AControl := EdEps;
exit;
end;
if StrToFloat(EdRadiusA.Text) = StrToFloat(EdRadiusB.Text) then begin
AControl := EdRadiusA;
AMsg := SSphereRadiiMustNotBeEqual;
exit;
end;
if StrToFloat(EdRadiusA.Text) > StrToFloat(EdRadiusB.Text) then begin
AControl := EdRadiusB;
AMsg := SInnerRadiusMustBeSmaller;
exit;
end;
if not IsValidComboValue(CbRadiusAUnits, AMsg) then begin
AControl := CbRadiusAUnits;
exit;
end;
if not IsValidComboValue(CbRadiusBUnits, AMsg) then begin
AControl := CbRadiusBUnits;
exit;
end;
if not IsValidComboValue(CbAreaUnits, AMsg) then begin
AControl := CbAreaUnits;
exit;
end;
if not IsValidComboValue(CbCapaUnits, AMsg) then begin
AControl := CbCapaUnits;
exit;
end;
Result := true;
end;
procedure TSphericalCapFrame.WriteToIni(ini: TCustomIniFile);
var
fs: TFormatSettings;
value: Extended;
begin
fs := DefaultFormatSettings;
fs.DecimalSeparator := '.';
ini.EraseSection(FIniKey);
if (EdRadiusA.Text <> '') and TryStrToFloat(EdRadiusA.Text, value) then
ini.WriteString(FIniKey, 'Radius A', FloatToStr(value, fs));
if CbRadiusAUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Radius A units', CbRadiusAUnits.Items[CbRadiusAUnits.ItemIndex]);
if (EdRadiusB.Text <> '') and TryStrToFloat(EdRadiusB.Text, value) then
ini.WriteString(FIniKey, 'Radius B', FloatToStr(value, fs));
if CbRadiusBUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Radius B units', CbRadiusBUnits.Items[CbRadiusBUnits.ItemIndex]);
if (EdEps.Text <> '') and TryStrToFloat(EdEps.Text, value) then
ini.WriteString(FIniKey, 'eps', FloatToStr(value, fs));
if CbAreaUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Area units', CbAreaUnits.Items[CbAreaUnits.ItemIndex]);
if CbCapaUnits.ItemIndex >= 0 then
ini.WriteString(FIniKey, 'Capa units', CbCapaUnits.Items[CbCapaUnits.ItemIndex]);
end;
end.
|
namespace RemObjects.Elements.Linq;
interface
uses
Foundation;
type
IOrderedFastEnumeration = interface(INSFastEnumeration)
method sortDescriptors: sequence of NSSortDescriptor;
method ThenOrderBy(aBlock: block(aItem: id): id): INSFastEnumeration;
method ThenOrderByDescending(aBlock: block(aItem: id): id): INSFastEnumeration;
end;
OrderedEnumerable = assembly class(NSObject, INSFastEnumeration, IOrderedFastEnumeration)
private
fComparator: NSComparator;
fDescriptor: NSSortDescriptor;
fSorted: NSArray;
fSequence: sequence of id;
{ INSFastEnumeration }
method countByEnumeratingWithState(state: ^NSFastEnumerationState) objects(buffer: ^id) count(len: NSUInteger): NSUInteger;
method sortDescriptors: sequence of NSSortDescriptor;
method ThenOrderBy(aBlock: block(aItem: id): id): INSFastEnumeration; iterator;
public
method initWithSequence(aSequence: sequence of id) comparator(aComparator: NSComparator): instancetype;
end;
implementation
method OrderedEnumerable.initWithSequence(aSequence: sequence of id) comparator(aComparator: NSComparator): instancetype;
begin
self := inherited init();
if assigned(self) then begin
fSequence := aSequence;
fComparator := aComparator;
fDescriptor := new NSSortDescriptor withKey('self') ascending(true) comparator(fComparator);
end;
result := self;
end;
method OrderedEnumerable.sortDescriptors: sequence of NSSortDescriptor;
begin
result := NSArray.arrayWithObject(fDescriptor);
if fSequence is IOrderedFastEnumeration then
result := result.Concat(IOrderedFastEnumeration(fSequence).sortDescriptors);
end;
method OrderedEnumerable.ThenOrderBy(aBlock: block(aItem: id): id): INSFastEnumeration;
begin
var lLocalComparator: NSComparator := (a,b) -> aBlock(b).compare(aBlock(a));
var lLocalDescriptor := new NSSortDescriptor withKey('self') ascending(true) comparator(lLocalComparator);
var lAllDescriptors := NSArray.arrayWithObject(lLocalDescriptor).Concat(sortDescriptors()); // use + operator
var lOrdered := fSequence.array().sortedArrayUsingDescriptors(lAllDescriptors.array());
for each i in lOrdered do
yield i;
end;
{ INSFastEnumeration }
method OrderedEnumerable.countByEnumeratingWithState(state: ^NSFastEnumerationState) objects(buffer: ^id) count(len: NSUInteger): NSUInteger;
begin
if not assigned(fSorted) then fSorted := fSequence.array().sortedArrayUsingComparator(fComparator);
result := fSorted.countByEnumeratingWithState(state) objects(buffer) count(len);
end;
end. |
unit MediaProcessing.VideoAnalytics.Net.EventClient;
interface
uses
Windows, Messages, SysUtils, Classes,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,IdStreamVCL, IdGlobal,SyncObjs,
MediaProcessing.VideoAnalytics.Net.EventDefinitions,MediaProcessing.Definitions;
type
TVaepClient = class
private
FClient : TIdTCPClient;
FLock : TCriticalSection;
FHost : string;
FPort : word;
FUserName: string;
FUserPassword: string;
function GetHost: string;
procedure SetHost(const Value: string);
procedure SetPort(const Value: word);
procedure DestroyClient;
protected
procedure Lock;
procedure Unlock;
procedure CheckConnected;
procedure InitClient; virtual;
function Client: TIdTCPClient;
public
constructor Create(const aHost: string; aPort: Word=VaepProtocolDefaultPort; const aUserName: string=VaepSuperUserName; aUserPassword: string=VaepSuperUserPassword);
destructor Destroy; override;
procedure Connect;
procedure Disconnect;
function Connected:boolean;
property Host: string read GetHost write SetHost;
property Port: word read FPort write SetPort;
function Listen(aTimeout: integer=integer(INFINITE)):TVaepNotify;
end;
EVaepClientError = class (Exception);
implementation
uses NetworkUtils,CryptUtils;
{ TVaepClient }
procedure TVaepClient.CheckConnected;
begin
Lock;
try
if (FClient=nil) or (not FClient.Connected) then
raise EVaepClientError.Create('Нет соединения');
finally
Unlock;
end;
end;
procedure TVaepClient.Connect;
var
aLoginParams: TVaepLoginParams;
aLoginResult: TVaepLoginResult;
aBytes: TBytes;
aDigest: string;
aSize: integer;
begin
DestroyClient; //Была проблема,связанная с тем, что после обрыва соединения связь больше не восстанавливалась. Возможно, это связано с компонентом. Поэтому разрушаем его каждый раз
if Client.Host='' then
raise EVaepClientError.Create('Не указан адрес сервера');
try
Client.Connect;
aDigest:=MD5Encode(Format('%s:%s',[FUserName,FUserPassword]));
aLoginParams:=TVaepLoginParams.Create(VaepProtocolVerion,FUserName,aDigest,ExtractFileName(ParamStr(0)));
try
aLoginParams.SaveToBytes(aBytes);
Client.IOHandler.Write(Length(aBytes));
Client.IOHandler.Write(aBytes);
finally
aLoginParams.Free;
end;
aSize:=Client.IOHandler.ReadLongInt();
aBytes:=nil;
Client.IOHandler.ReadBytes(aBytes,aSize);
aLoginResult:=TVaepLoginResult.Create();
try
aLoginResult.LoadFromBytes(aBytes);
if aLoginResult.Code<>iceOK then
raise EVaepClientError.Create(VaepLoginResultCodeToString(aLoginResult.Code));
finally
aLoginResult.Free;
end;
except
on E:Exception do
raise EVaepClientError.Create('Ошибка соединения: '+E.Message);
end;
Assert(Client.Connected,'Сетевой клиент не выполнил команду коннекта');
end;
//------------------------------------------------------------------------------
function TVaepClient.Connected: boolean;
begin
result:=false;
try
result:=(FClient<>nil) and FClient.Connected;
except
Disconnect;
end;
end;
//------------------------------------------------------------------------------
constructor TVaepClient.Create(const aHost: string; aPort: Word=VaepProtocolDefaultPort; const aUserName: string=VaepSuperUserName; aUserPassword: string=VaepSuperUserPassword);
begin
FLock:=TCriticalSection.Create;
self.Host:=aHost;
self.Port:=aPort;
self.FUserName:=aUserName;
self.FUserPassword:=aUserPassword;
end;
//------------------------------------------------------------------------------
destructor TVaepClient.Destroy;
begin
inherited;
FreeAndNil(FClient);
FreeAndNil(FLock);
end;
//------------------------------------------------------------------------------
function TVaepClient.GetHost: string;
begin
result:=FHost;
end;
//------------------------------------------------------------------------------
procedure TVaepClient.SetHost(const Value: string);
begin
if Host=Value then
exit;
FHost:=Value;
DestroyClient;
end;
//------------------------------------------------------------------------------
procedure TVaepClient.Lock;
begin
FLock.Enter;
end;
//------------------------------------------------------------------------------
function TVaepClient.Listen(aTimeout: integer):TVaepNotify;
var
aMarker: cardinal;
aDataSize: cardinal;
aData: TBytes;
aNotifyType: TVaepNotifyType;
begin
CheckConnected;
if aTimeout<0 then
FClient.ReadTimeout:=IdTimeoutInfinite
else
FClient.ReadTimeout:=aTimeout;
aMarker:=FClient.IOHandler.ReadLongWord;
if aMarker<>VaepFrameBeginMarker then
raise EVaepClientError.Create('Ошибка чтения данных с сервера');
aNotifyType:=TVaepNotifyType(FClient.IOHandler.ReadLongWord);
aDataSize:=FClient.IOHandler.ReadLongWord;
aData:=nil;
FClient.IOHandler.ReadBytes(aData,aDataSize);
aMarker:=FClient.IOHandler.ReadLongWord;
if aMarker<>VaepFrameEndMarker then
raise EVaepClientError.Create('Ошибка чтения данных с сервера');
result:=GetNotifyClass(aNotifyType).CreateFromBytes(aData);
end;
//------------------------------------------------------------------------------
procedure TVaepClient.Unlock;
begin
FLock.Leave;
end;
//------------------------------------------------------------------------------
procedure TVaepClient.DestroyClient;
begin
FreeAndNil(FClient);
end;
//------------------------------------------------------------------------------
procedure TVaepClient.Disconnect;
begin
try
FClient.Disconnect;
except
//Если соединение уже потеряно, будет ошибка. Нам это не интересно
end;
end;
//------------------------------------------------------------------------------
procedure TVaepClient.InitClient;
begin
FClient.Port:=FPort;
FClient.Host:=AddressToIp(FHost);
end;
//------------------------------------------------------------------------------
procedure TVaepClient.SetPort(const Value: word);
begin
FPort := Value;
end;
//------------------------------------------------------------------------------
function TVaepClient.Client: TIdTCPClient;
begin
if FClient=nil then
begin
FClient:=TIdTCPClient.Create(nil);
InitClient;
end;
result:=FClient;
end;
end.
|
unit CommonConnection.Intf;
interface
uses Spring.Container, Spring.Services, System.Classes, Data.DB, DBClient, System.SysUtils,
FireDAC.Stan.Intf, FireDAC.Stan.Option, NGFDMemTable,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client;
const
CDP_IDENT_FD = 'FDConnection';
CDP_IDENT_ADO = 'ADOConnection';
type
EGlobalException = class(Exception);
TDBConnectType = (dctFD, dctADO);
ICommonConnectionProperties = Interface
['{CE6C8655-AF96-49E0-BDCF-8F8124EEE200}']
function EncodeValue(s : string): string;
function DecodeValue(s : string): string;
procedure SetStrValue(sIdent, Value : string);
function GetStrValue(sIdent: string): string;
// DatabaseType
function GetServerTypeID : Integer;
procedure SetServerTypeID(Value: Integer);
property ServerTypeID : Integer read GetServerTypeID write SetServerTypeID;
// UserName
function GetUserName : string;
procedure SetUserName(const Value: string);
property UserName : string read GetUserName write SetUserName;
// Password
function GetPassword : string;
procedure SetPassword(const Value: string);
property Password : string read GetPassword write SetPassword;
// ServerName
function GetServerName : string;
procedure SetServerName(const Value: string);
property ServerName : string read GetServerName write SetServerName;
// DatabaseName
function GetDatabaseName : string;
procedure SetDatabaseName(const Value: string);
property DatabaseName : string read GetDatabaseName write SetDatabaseName;
// PortNumber
function GetPortNumber : string;
procedure SetPortNumber(const Value: string);
property PortNumber : string read GetPortNumber write SetPortNumber;
// Protocol
function GetProtocol : string;
procedure SetProtocol(const Value: string);
property Protocol: string read GetProtocol write SetProtocol;
// ServerLogin
function GetServerLogin : string;
procedure SetServerLogin(const Value: string);
property ServerLogin: string read GetServerLogin write SetServerLogin;
// ServerPassword
function GetServerPassword : string;
procedure SetServerPassword(const Value: string);
property ServerPassword: string read GetServerPassword write SetServerPassword;
// OSAuthentication
function GetOSAuthentication : boolean;
procedure SetOSAuthentication(const Value: boolean);
property OSAuthentication: boolean read GetOSAuthentication write SetOSAuthentication;
// ConnectionString
function GetConnectionString : String;
procedure SetConnectionString(Value: String);
property ConnectionString : string read GetConnectionString write SetConnectionString;
// AsString
function GetAsString: string;
procedure SetAsString(Value: string);
property AsString : string read GetAsString write SetAsString;
procedure SaveToFile(FileName: string);
procedure LoadFromFile(FileName: string);
procedure Assign(Value: ICommonConnectionProperties);
End;
TDatabaseTypeOption = (dtoSQLServer, dtoOracle, dtoACCESS, dtoExcel, dtoSQLite, dtoAll);
ICommonConnection = Interface
['{33785BE9-9C57-43D7-A99B-091D2F4CA038}']
function GetConnectionProperties : ICommonConnectionProperties;
property ConnectionProperties : ICommonConnectionProperties read GetConnectionProperties;
function GetServerType: TDatabaseTypeOption;
procedure SetServerType(Value: TDatabaseTypeOption);
property ServerType : TDatabaseTypeOption read GetServerType write SetServerType;
// Connection
function GetConnection : TObject;
procedure SetConnection(Value: TObject);
property Connection : TObject read GetConnection write SetConnection;
// Connected
function GetConnected: Boolean;
procedure SetConnected(Value: Boolean);
property Connected : Boolean read GetConnected write SetConnected;
//Events
function GetAfterConnect: TNotifyEvent;
procedure SetAfterConnect(Value: TNotifyEvent);
property AfterConnect : TNotifyEvent read GetAfterConnect write SetAfterConnect;
function GetAfterDisconnect: TNotifyEvent;
procedure SetAfterDisconnect(Value: TNotifyEvent);
property AfterDisconnect : TNotifyEvent read GetAfterDisconnect write SetAfterDisconnect;
procedure SetConnectionString;
End;
TomControlState = (ocsLoading, ocsBusy, ocsIdle);
ICommonDataProvider<T: TDataSet> = Interface
['{D600A174-6D01-45FE-A4C3-4CAEABA404C4}']
function GetDBConnection : ICommonConnection;
property DBConnection : ICommonConnection read GetDBConnection;
procedure SetConnectionString(const ServerType : TDatabaseTypeOption;
const HostName, DatabaseName, PortNumber,
LoginName, LoginPassword: string; OSAuthentication: Boolean);
function GetConnected: Boolean;
procedure SetConnected(Value: Boolean);
property Connected : Boolean read GetConnected write SetConnected;
// Checks
procedure CheckCDS(cds : T; cdsName: string; CheckActive : Boolean);
function GetKeyFieldValue(cds: T; KeyFieldName: string) : Variant;
function LocateKeyField(cds: T; KeyFieldName: string; KeyValue: Variant) : Boolean;
function CanEditCDS(cds : T) : Boolean;
function CanInsertCDS(cds: T): Boolean;
function CanCancelCDS(cds: T): Boolean;
function CanSaveCDS(cds: T): Boolean;
function CanDeleteCDS(cds: T): Boolean;
procedure PostCDS(cds : T);
function GetServerDateTimeNow : TDateTime;
// Remove blanks
function TextToListText(s : string): string;
// construct the where and clause for key fields
function KeyFieldsToWhereAnd(TableAlias, KeyFields : string): string;
// Replaces all invalid characters with _
function FieldToParam(FieldName: string): string;
// cds Params
procedure CreateParam(cds : T; ParamName: string;
DataType : TFieldType; ParamValue: Variant);
procedure CreateBlobParam(cds : T; ParamName: string;
BlobType: TBlobType; Stream: TStream);
procedure CreateDefaultParams (cds : T; PageSize, PageNum : Integer);
// Add field identifier
function AddFieldBrackets(FieldName: string): string;
function GetQueryText(QryIndex: Integer; WhereAnd: string): string;
function GetQueryTextTable(const TableName, TableAlias, WhereAnd, KeyFields, OrderBy : string) : string;
procedure cdsExecQryText(QryText: string; cds : T);
procedure cdsOpenQryTextExt(QryText: string;
cds : T; ExecQry, CreateFieldDefs : Boolean;
LAppend: Boolean = False; LUseDP: Boolean = False);
procedure cdsOpenQryText(QryText: string;
cds : T; CreateFieldDefs : Boolean; LAppend: Boolean = False; LUseDP: Boolean = False);
procedure cdsExecQryIndex(QryIndex : Integer; WhereAnd: string; cds : T);
procedure cdsOpenQryIndex(QryIndex : Integer; WhereAnd: string;
cds : T; CreateFieldDefs : Boolean);
procedure cdsOpenTable(const TableName, TableAlias, WhereAnd, OrderBy : string;
cds : T; CreateFieldDefs : Boolean);
procedure cdsOpenTableExt(const TableName, TableAlias, WhereAnd, OrderBy : string;
cds : T; CreateFieldDefs : Boolean;
var DataSetState : TomControlState);
procedure cdsApplyUpdatesTable(cds: T;
TableName, TableAlias, WhereAnd, KeyFields : string);
procedure cdsApplyUpdates(cds: T);
// SQL.Text contains SQL Statement, Params contains all params and values
procedure cdsOpen(cds: T; CreateFieldDefs: Boolean; LAppend: Boolean = False; LUseDP: Boolean = False);
procedure cdsOpenExt(cds: T; CreateFieldDefs: Boolean;
var DataSetState : TomControlState);
procedure cdsExec(cds: T);
procedure ExecSQL(SQL : string);
procedure BeginTransaction;
procedure CommitTransaction;
procedure RollbackTransaction;
procedure ResetQuery(cds : T);
procedure cdsParamGenerate(cds : T);
function CloneDataProvider : ICommonDataProvider<T>;
function GetUseCloneDataProvider: Boolean;
procedure SetUseCloneDataProvider(Value : Boolean);
property UseCloneDataProvider : Boolean read GetUseCloneDataProvider write SetUseCloneDataProvider;
function CheckTableAndField(const s: String): Boolean;
End;
IFDMemTableProvider = ICommonDataProvider<TNGFDMemTable>;
IClientDataSetProvider = ICommonDataProvider<TClientDataSet>;
function EncryptPassword(s: string): string;
function DecryptPassword(s: string): string;
// procedure CreateGlobalDataProvider(ClassIdent : string);
procedure ReleaseGlobalDataProvider;
function NewGUID: string;
function UpdateStatusToInt(Value: TUpdateStatus): Integer;
var
// GlobalDataProvider
cdpFDGlobal : IFDMemTableProvider;
cdpADOGlobal : IClientDataSetProvider;
ResourceString
RS_DatabaseNotConnected = 'Database not connected';
RS_LargeSizeDataSetErr = 'Returning dataset is too large. Please check the filters and try again.';
implementation
function EncryptPassword(s: string): string;
begin
Result := s;
end;
function DecryptPassword(s: string): string;
begin
Result := s;
end;
//procedure CreateGlobalDataProvider(ClassIdent : string);
//begin
// ReleaseGlobalDataProvider;
// cdpFDGlobal := ServiceLocator.GetService<IFDMemTableProvider>(ClassIdent);
//end;
procedure ReleaseGlobalDataProvider;
begin
if Assigned(cdpFDGlobal) then
begin
{$IFNDEF AUTOREFCOUNT}
GlobalContainer.Release(cdpFDGlobal);
{$ENDIF}
cdpFDGlobal := nil;
end;
if Assigned(cdpADOGlobal) then
begin
{$IFNDEF AUTOREFCOUNT}
GlobalContainer.Release(cdpADOGlobal);
{$ENDIF}
cdpADOGlobal := nil;
end;
end;
function NewGUID: string;
var
GUID: TGUID;
begin
System.SysUtils.CreateGUID(GUID);
Result := GUID.ToString;
end;
function UpdateStatusToInt(Value: TUpdateStatus): Integer;
begin
if Value = usInserted then
Result := 1
else if Value = usModified then
Result := 2
else if Value = usDeleted then
Result := 3
else
Result := 0;
end;
initialization
cdpFDGlobal := nil;
cdpADOGlobal := nil;
finalization
ReleaseGlobalDataProvider;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ ActiveX Control Data Bindings Editor }
{ }
{ Copyright (c) 1995-1999 Borland Software Corp. }
{ }
{*******************************************************}
unit DBOleEdt;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, TypInfo, DesignIntf, DesignEditors, DbOleCtl, OCXReg,
LibHelp;
type
TDataBindForm = class(TForm)
Panel1: TPanel;
OkBtn: TButton;
CancelBtn: TButton;
HelpBtn: TButton;
Label1: TLabel;
Label2: TLabel;
PropNameLB: TListBox;
FieldNameLB: TListBox;
BindBtn: TButton;
Label3: TLabel;
BoundLB: TListBox;
DeleteBtn: TButton;
ClearBtn: TButton;
procedure BindBtnClick(Sender: TObject);
procedure ClearBtnClick(Sender: TObject);
procedure DeleteBtnClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure PropNameLBDblClick(Sender: TObject);
procedure FieldNameLBClick(Sender: TObject);
procedure HelpBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FDbCtl: TDbOleControl;
procedure ClearBoundList;
procedure FillDialog;
procedure EnableButtons;
public
function DoEditControl(DbCtl: TDbOleControl): Boolean;
end;
TDataBindEditor = class(TOleControlEditor)
private
FVerbID: Integer;
protected
procedure DoVerb(Verb: Integer); override;
public
function GetVerbCount: Integer; override;
end;
TDataBindProperty = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
implementation
{$R *.dfm}
uses ActiveX, ComObj, DBConsts, VDBConsts;
type
PObjRec = ^TObjRec;
TObjRec = record
FieldName: string;
DispID: TDispID;
end;
{ TDataBindProperty }
procedure TDataBindProperty.Edit;
var
DataBindForm: TDataBindForm;
begin
DataBindForm := TDataBindForm.Create(Application);
try
if DataBindForm.DoEditControl(GetComponent(0) as TDbOleControl) then
Modified;
finally
DataBindForm.Free;
end;
end;
function TDataBindProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paReadOnly];
end;
{ TDataBindEditor }
procedure TDataBindEditor.DoVerb(Verb: Integer);
var
DataBindForm: TDataBindForm;
begin
if Verb = FVerbID then
begin
DataBindForm:= TDataBindForm.Create(nil);
try
DataBindForm.DoEditControl(Component as TDbOleControl);
finally
DataBindForm.Free;
end;
end
else
inherited DoVerb(Verb);
end;
function TDataBindEditor.GetVerbCount: Integer;
var
I, MaxVerb: Integer;
begin
Result := inherited GetVerbCount + 1;
MaxVerb := 0;
// Need to find an unused Verb ID to use for the component editor.
// We just add 1 to the highest Verb ID found.
for I := 0 to Verbs.Count - 1 do
if Integer(Verbs.Objects[I]) >= MaxVerb then
MaxVerb := Integer(Verbs.Objects[I]);
FVerbID := MaxVerb + 1;
Verbs.AddObject(SDataBindings, TObject(FVerbID));
end;
{ TDataBindForm }
procedure TDataBindForm.BindBtnClick(Sender: TObject);
var
ListObjRec: PObjRec;
begin
if (PropNameLB.ItemIndex >= 0) and (PropNameLB.ItemIndex >= 0) then
begin
New(ListObjRec);
with ListObjRec^ do
begin
FieldName := FieldNameLB.Items[FieldNameLB.ItemIndex];
DispID := Integer(PropNameLB.Items.Objects[PropNameLB.ItemIndex]);
end;
BoundLB.Items.AddObject(PropNameLB.Items[PropNameLB.ItemIndex] +
' <---> ' + FieldNameLB.Items[FieldNameLB.ItemIndex], TObject(ListObjRec));
end;
EnableButtons;
end;
procedure TDataBindForm.ClearBoundList;
var
I: Integer;
begin
if BoundLB.Items.Count <> 0 then
begin
for I := 0 to BoundLB.Items.Count - 1 do
if PObjRec(BoundLB.Items.Objects[I]) <> nil then
Dispose(PObjRec(BoundLB.Items.Objects[I]));
BoundLB.Clear;
end;
EnableButtons;
end;
procedure TDataBindForm.ClearBtnClick(Sender: TObject);
begin
ClearBoundList;
end;
procedure TDataBindForm.DeleteBtnClick(Sender: TObject);
begin
if BoundLB.ItemIndex <> -1 then
begin
Dispose(PObjRec(BoundLB.Items.Objects[BoundLB.ItemIndex]));
BoundLB.Items.Delete(BoundLB.ItemIndex);
end;
end;
function TDataBindForm.DoEditControl(DbCtl: TDbOleControl): Boolean;
var
I: Integer;
begin
FDbCtl := DbCtl;
FillDialog;
Result := ShowModal = mrOk;
if Result then
begin
FDbCtl.DataBindings.Clear;
for I:= 0 to BoundLB.Items.Count -1 do
begin
FDbCtl.DataBindings.Add;
FDbCtl.DataBindings.Items[I].DataField := PObjRec(BoundLB.Items.Objects[I]).FieldName;
FDbCtl.DataBindings.Items[I].DispID := PObjRec(BoundLB.Items.Objects[I]).DispID;
end;
end;
end;
procedure TDataBindForm.EnableButtons;
function CanBindProperty(DispID: TDispID): Boolean;
var
I: Integer;
begin
Result := True;
for I := 0 to BoundLB.Items.Count - 1 do
if PObjRec(BoundLB.Items.Objects[I])^.DispID = DispID then
begin
Result := False;
Exit;
end;
end;
begin
BindBtn.Enabled := (PropNameLB.ItemIndex >= 0) and
(FieldNameLB.ItemIndex >= 0) and (PropNameLB.Items.Count > 0) and
(FieldNameLB.Items.Count > 0) and
CanBindProperty(TDispID(PropNameLB.Items.Objects[PropNameLB.ItemIndex]));
DeleteBtn.Enabled := BoundLB.Items.Count > 0;
ClearBtn.Enabled := BoundLB.Items.Count > 0;
end;
procedure TDataBindForm.FillDialog;
const
PropDisplayStr = '%s (%d)';
BoundDisplayStr = '%s <---> %s';
var
TypeAttr: PTypeAttr;
I, I2: Integer;
FuncDesc: PFuncDesc;
VarDesc: PVarDesc;
PropName, DocString: WideString;
HelpContext: Longint;
ListObjRec: PObjRec;
TI: ITypeInfo;
InsertStr: string;
begin
if ((IUnknown(FDbCtl.OleObject) as IDispatch).GetTypeInfo(0,0,TI) = S_OK) then
begin
TI.GetTypeAttr(TypeAttr);
try
for I := 0 to TypeAttr.cFuncs - 1 do
begin
OleCheck(TI.GetFuncDesc(I, FuncDesc));
try
// Only show properties which are bindable and marked as either
// display bindable or default bindable.
if (FuncDesc.invkind <> INVOKE_FUNC) and
(FuncDesc.wFuncFlags and FUNCFLAG_FBINDABLE <> 0) and
((FuncDesc.wFuncFlags and FUNCFLAG_FDISPLAYBIND <> 0) or
(FuncDesc.wFuncFlags and FUNCFLAG_FDEFAULTBIND <> 0)) then
begin
TI.GetDocumentation(FuncDesc.memid, @PropName, @DocString, @HelpContext, nil);
InsertStr := Format(PropDisplayStr, [PropName, FuncDesc.memid]);
if PropNameLB.Items.Indexof(InsertStr) = -1 then
PropNameLB.Items.AddObject(InsertStr, TObject(FuncDesc.memid));
end;
finally
TI.ReleaseFuncDesc(FuncDesc);
end;
end;
for I2 := 0 to TypeAttr.cVars - 1 do
begin
OleCheck(TI.GetVarDesc(I2, VarDesc));
try
// Only show properties which are bindable and marked as either
// display bindable or default bindable.
if (VarDesc.wVarFlags and VARFLAG_FBINDABLE <> 0) and
((VarDesc.wVarFlags and VARFLAG_FDISPLAYBIND <> 0) or
(VarDesc.wVarFlags and VARFLAG_FDEFAULTBIND <> 0)) then
begin
TI.GetDocumentation(VarDesc.memid, @PropName, @DocString, @HelpContext, nil);
InsertStr := Format(PropDisplayStr, [PropName, FuncDesc.memid]);
if PropNameLB.Items.Indexof(InsertStr) = -1 then
PropNameLB.Items.AddObject(InsertStr, TObject(VarDesc.memid));
end;
finally
TI.ReleaseVarDesc(VarDesc);
end;
end;
finally
TI.ReleaseTypeAttr(TypeAttr);
end;
if (FDbCtl.DataSource <> nil) and (FDbCtl.DataSource.Dataset <> nil) then
FDbCtl.DataSource.DataSet.GetFieldNames(FieldNameLB.Items);
ClearBoundList;
if FDbCtl.DataBindings.Count > 0 then
begin
for I := 0 to FDbCtl.DataBindings.Count - 1 do
begin
New(ListObjRec);
ListObjRec^.FieldName := FDbCtl.DataBindings.Items[I].DataField;
ListObjRec^.DispID := FDbCtl.DataBindings.Items[I].DispID;
InsertStr := Format(BoundDisplayStr,
[PropNameLB.Items[PropNameLB.Items.IndexOfObject(TObject(FDbCtl.DataBindings.Items[I].DispID))],
(FDbCtl.DataBindings.Items[I].DataField)]);
BoundLB.Items.AddObject(InsertStr, TObject(ListObjRec));
end;
end;
end;
EnableButtons;
end;
procedure TDataBindForm.FormDestroy(Sender: TObject);
begin
ClearBoundList;
end;
procedure TDataBindForm.PropNameLBDblClick(Sender: TObject);
begin
// Enable double click to do the same thing as the bind button
if BindBtn.Enabled then BindBtnClick(nil);
end;
procedure TDataBindForm.FieldNameLBClick(Sender: TObject);
begin
EnableButtons;
end;
procedure TDataBindForm.HelpBtnClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TDataBindForm.FormCreate(Sender: TObject);
begin
HelpContext := hcDAXDataBindings;
end;
end.
|
unit uLatLong;
interface
uses
Math,
SysUtils;
function LongitudeToStr(L: double): String;
function LatitudeToStr(L: double): String;
function StrToLatitude(S: String): double;
function StrToLongitude(S: String): double;
function EncodeLatitude(G, M: Integer; S: Double): double;
function EncodeLongitude(G, M: Integer; S: Double): double;
procedure DecodeLatitude(L: double; var G, M: Integer; var S: Double);
procedure DecodeLongitude(L: double; var G, M: Integer; var S: Double);
function DistanciaCG(lat1, lat2, long1, long2: double): double;
const
sGrau = '°';
sMin = '''';
sSeg = '"';
implementation
function DistanciaCG(lat1, lat2, long1, long2: double): double;
begin
try
Result := 180*111.2*arccos(sin(PI*lat1/180)*sin(PI*lat2/180)+cos(PI*lat1/180)*cos(PI*lat2/180)*cos(PI*(long1-long2)/180))/PI;
except
Result := 0;
end;
end;
function StrToLatitude(S: String): double;
var
G, M, P, Code: Integer;
LS : Double;
begin
P := Pos(sGrau, S);
if P=0 then
Exception.Create('Latitude inválida');
try
G := StrToInt(Copy(S, 1, P-1));
Delete(S, 1, P);
except
Raise Exception.Create('Latitude Inválida');
end;
P := Pos(sMin, S);
if P=0 then
Exception.Create('Latitude inválida');
try
M := StrToInt(Copy(S, 1, P-1));
Delete(S, 1, P);
except
Raise Exception.Create('Latitude Inválida');
end;
P := Pos(sSeg, S);
if P=0 then
Exception.Create('Latitude inválida');
try
LS := 0;
Val(Copy(S, 1, P-1), LS, Code);
Delete(S, 1, P);
if LS>60 then Exception.Create('Seconds must be less than 60');
except
Raise Exception.Create('Latitude Inválida');
end;
Result := EncodeLatitude(G, M, LS);
end;
function StrToLongitude(S: String): double;
var
G, M, P, Code: Integer;
LS : Double;
begin
P := Pos(sGrau, S);
if P=0 then
Exception.Create('Longitude inválida');
try
G := StrToInt(Copy(S, 1, P-1));
Delete(S, 1, P);
except
Raise Exception.Create('Longitude Inválida');
end;
P := Pos(sMin, S);
if P=0 then
Exception.Create('Longitude inválida');
try
M := StrToInt(Copy(S, 1, P-1));
Delete(S, 1, P);
except
Raise Exception.Create('Longitude Inválida');
end;
P := Pos(sSeg, S);
if P=0 then
Exception.Create('Longitude inválida');
try
LS := 0;
Val(Copy(S, 1, P-1), LS, Code);
Delete(S, 1, P);
if LS>60 then Exception.Create('Seconds must be less than 60');
except
Raise Exception.Create('Longitude Inválida');
end;
Result := EncodeLongitude(G, M, LS);
end;
function EncodeLatitude(G, M: Integer; S: Double): double;
begin
if (G < -90) or (G > 90) then
Raise Exception.Create('Grau da latitude tem que estar dentro da faixa -90 a 90');
if (M < 0) or (M>59) then
Raise Exception.Create('Minuto tem que estar dentro da faixa 0 a 59');
if (S < 0) or (S>=60) then
Raise Exception.Create('Segundo tem que estar dentro da faixa 0 a 59');
if G<0 then begin
S := -1 * S;
M := -1 * M;
end;
Result := G + (S / 3600) + (M / 60);
end;
function EncodeLongitude(G, M: Integer; S: Double): double;
begin
if (G < -180) or (G > 180) then
Raise Exception.Create('Grau da longitude tem que estar dentro da faixa -180 a 180');
if (M < 0) or (M>59) then
Raise Exception.Create('Minuto tem que estar dentro da faixa 0 a 59');
if (S < 0) or (S>=60) then
Raise Exception.Create('Segundo tem que estar dentro da faixa 0 a 59');
if G<0 then begin
S := -1 * S;
M := -1 * M;
end;
Result := G + (S / 3600) + (M / 60);
end;
procedure DecodeLatitude(L: double; var G, M: Integer; var S: Double);
begin
G := Trunc(Int(L));
M := Trunc(Frac(L) * 60);
S := Abs((Frac(L)*3600) - (M*60));
M := Abs(M);
end;
procedure DecodeLongitude(L: double; var G, M: Integer; var S: Double);
begin
DecodeLatitude(L, G, M, S);
end;
function ZeroPad(N: Double; T: Integer; Decimais: Integer=0): String;
var
SDec: String;
begin
Str(N:0:Decimais, Result);
if Decimais>0 then begin
SDec := Copy(Result, Pos('.', Result)+1, Decimais);
while length(SDec) < Decimais do SDec := SDec + '0';
SDec := '.'+SDec;
end else
SDec := '';
Delete(Result, Pos('.', Result), length(Result));
while Length(Result) < T do
if Result[1]='-' then
Result := '-0'+Copy(Result, 2, T)
else
Result := '0' + Result;
Result := Result + SDec;
end;
function LatitudeToStr(L: double): String;
var G, M: Integer; S: Double;
begin
DecodeLatitude(L, G, M, S);
Result := ZeroPad(G, 3) + sGrau +
ZeroPad(M, 2) + sMin +
ZeroPad(S, 2, 2) + sSeg;
end;
function LongitudeToStr(L: double): String;
var G, M: Integer; S: Double;
begin
DecodeLongitude(L, G, M, S);
Result := ZeroPad(G, 4) + sGrau +
ZeroPad(M, 2) + sMin +
ZeroPad(S, 2, 2) + sSeg;
end;
end.
|
UNIT DirUtil;
{ some directory utilities }
interface
procedure Dir(Path : string);
{ Gets a list of names }
function NextName : String;
{get next (or first) name found. '' (null string) after last.}
implementation
USES DOS;
TYPE
NameListPtr = ^NameList;
NameList = Record
FullName : string; { name including path }
Next : NameListPtr;
END;
VAR
MatchingNames : NameListPtr;
CurrentName : NameListPtr;
OldExit : POINTER;
procedure Dir(Path : string);
{ returns a pointer to a linked List of names matching SPEC }
var
I,J: Integer;
Attr: Word;
S: PathStr;
D: DirStr;
N: NameStr;
E: ExtStr;
F: File;
SR : SearchRec;
OldNode,
Node : NameListPtr;
begin
{ properly qualify path name }
Path := FExpand(Path);
if Path[Length(Path)] <> '\' then
begin
Assign(F, Path);
GetFAttr(F, Attr);
if (DosError = 0) and (Attr and Directory <> 0) then
Path := Path + '\';
end;
FSplit(Path, D, N, E);
if N = '' then N := '*';
if E = '' then E := '.*';
Path := D + N + E;
OldNode := NIL;
FindFirst(Path, ReadOnly + Archive, SR);
while (DosError = 0) do
begin
New(Node);
Node^.FullName := D + SR.Name;
Node^.Next := OldNode;
OldNode := Node;
FindNext(SR);
end;
MatchingNames := OldNode;
CurrentName := MatchingNames;
end;
function NextName : String;
BEGIN
IF CurrentName <> NIL THEN
BEGIN
NextName := CurrentName^.FullName;
CurrentName := CurrentName^.Next;
END
ELSE
NextName := '';
END;
{ -------------------------------------------------------------------- }
{$F+}
procedure FreeList;
VAR
Node : NameListPtr;
BEGIN
ExitProc := OldExit;
WHILE MatchingNames <> NIL DO
BEGIN
Node := MatchingNames;
MatchingNames := MatchingNames^.Next;
Dispose(Node);
END;
END;
{$F-}
begin
OldExit := ExitProc;
ExitProc := @FreeList;
end.
|
UNIT DoubleLinkedListUnitCycl;
INTERFACE
Type NodePtr = ^Node;
Node = Record
prev: NodePtr;
val: integer;
next: NodePtr;
End;
List = NodePtr;
PROCEDURE Append(var l: List; n: NodePtr);
PROCEDURE Prepend(var l: List; n: NodePtr);
FUNCTION FindNode(l: List; x: integer): NodePtr;
PROCEDURE InsertSorted(var l: List; n: NodePtr);
IMPLEMENTATION
PROCEDURE Append(var l: List; n: NodePtr);
BEGIN
n^.prev := l^.prev;
n^.next := l;
l^.prev^.next := n;
l^.prev := n;
END;
PROCEDURE Prepend(var l: List; n: NodePtr);
BEGIN
n^.next := l^.next;
n^.prev := l;
l^.next^.prev := n;
l^.next := n;
END;
FUNCTION FindNode(l: List; x: integer): NodePtr;
var cur: NodePtr;
BEGIN
cur := l^.next; (* l^.val := x *)
while (cur <> l) AND (cur^.val <> x) do (* Sentinel spart den ersten Teil der while *)
cur := cur^.next;
if cur = l then
FindNode := NIL
else
FindNode := cur;
END;
(* Verbesserung: Wächter-Knoten (Sentinel)
l^.val := x *)
PROCEDURE InsertSorted(var l: List; n: NodePtr);
var succ: NodePtr;
BEGIN
succ := l^.next;
l^.val := n^.val;
while succ^.val < n^.val do
succ := succ^.next;
n^.next := succ;
n^.prev := succ^.prev;
succ^.prev := n;
n^.prev^.next := n;
END;
BEGIN
END. |
unit FamilyQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, {Sequence,} RepositoryDataModule,
System.Generics.Collections, ExcelDataModule, SearchComponentCategoryQuery,
CustomComponentsQuery, ApplyQueryFrame, BaseFamilyQuery, DSWrap;
type
TFamilyW = class(TBaseFamilyW)
private
FProductCategoryId: TParamWrap;
protected
procedure AddNewValue(const AValue, AProducer: string);
public
constructor Create(AOwner: TComponent); override;
function LocateOrAppend(const AValue, AProducer: string): Boolean;
property ProductCategoryId: TParamWrap read FProductCategoryId;
end;
TQueryFamily = class(TQueryBaseFamily)
private
procedure DoAfterInsert(Sender: TObject);
procedure DoBeforePost(Sender: TObject);
function GetFamilyW: TFamilyW;
{ Private declarations }
protected
procedure ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
function CheckRecord: String;
function CreateDSWrap: TDSWrap; override;
procedure DoAfterOpen(Sender: TObject);
procedure OnDatasheetGetText(Sender: TField; var Text: String;
DisplayText: Boolean);
public
constructor Create(AOwner: TComponent); override;
property FamilyW: TFamilyW read GetFamilyW;
{ Public declarations }
end;
implementation
uses NotifyEvents, System.IOUtils, SettingsController, DBRecordHolder,
ParameterValuesUnit;
{$R *.dfm}
{ TfrmQueryComponents }
constructor TQueryFamily.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DetailParameterName := FamilyW.ProductCategoryId.FieldName;
TNotifyEventWrap.Create(W.AfterInsert, DoAfterInsert, W.EventList);
TNotifyEventWrap.Create(W.AfterOpen, DoAfterOpen, W.EventList);
TNotifyEventWrap.Create(W.BeforePost, DoBeforePost, W.EventList);
end;
procedure TQueryFamily.ApplyInsert(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
var
ARH: TRecordHolder;
begin
inherited;
Assert(ASender = FDQuery);
// Если такого семейства ещё нет
if W.PK.AsInteger <= 0 then
begin
ARH := TRecordHolder.Create(ASender);
try
qProducts.InsertRecord(ARH);
finally
FreeAndNil(ARH);
end;
// Запоминаем сгенерированный первичный ключ
FetchFields([W.PKFieldName], [qProducts.PKValue], ARequest, AAction,
AOptions);
end;
Assert(W.PK.AsInteger > 0);
// Обрабатываем значения параметров
W.UpdateParamValue(W.PKFieldName);
Assert(W.PK.AsInteger > 0);
// Обновляем категории нашего компонента
UpdateCategory(W.PK.AsInteger, W.SubGroup.F.AsString);
inherited;
end;
function TQueryFamily.CheckRecord: String;
begin
Result := '';
if W.Value.F.AsString.Trim.IsEmpty then
begin
Result := 'Необходимо задать наименование';
Exit;
end;
if W.Producer.F.IsNull then
begin
Result := 'Необходимо выбрать производителя';
Exit;
end;
if W.SubGroup.F.AsString.Trim.IsEmpty then
begin
Result := 'Необходимо задать идентификатор категории';
Exit;
end;
end;
function TQueryFamily.CreateDSWrap: TDSWrap;
begin
Result := TFamilyW.Create(FDQuery);
end;
procedure TQueryFamily.DoAfterInsert(Sender: TObject);
begin
// Заполняем SubGroup внешним идентификатором текущей категории компонентов
W.SubGroup.F.AsString := CategoryExternalID;
end;
procedure TQueryFamily.DoAfterOpen(Sender: TObject);
begin
W.Datasheet.F.OnGetText := OnDatasheetGetText;
W.Diagram.F.OnGetText := OnDatasheetGetText;
W.Drawing.F.OnGetText := OnDatasheetGetText;
W.Image.F.OnGetText := OnDatasheetGetText;
end;
procedure TQueryFamily.DoBeforePost(Sender: TObject);
var
AErrorMessage: string;
begin
// Если не происходит вставка новой записи
if not(FDQuery.State in [dsInsert]) then
Exit;
// Проверяем запись на наличие ошибок
AErrorMessage := CheckRecord;
if not AErrorMessage.IsEmpty then
raise Exception.Create(AErrorMessage);
// Если такое семейство уже есть
if qSearchFamily.SearchByValueAndProducer(W.Value.F.AsString,
W.Producer.F.AsString) > 0 then
begin
// Запоминаем найденный первичный ключ
W.PK.Value := qSearchFamily.W.PK.Value;
// Заполняем поля из найденного семейства
UpdateFields([W.IDProducer.F, W.IDDatasheet.F, W.Datasheet.F, W.IDDiagram.F,
W.Diagram.F, W.IDDrawing.F, W.Drawing.F, W.IDImage.F, W.Image.F,
W.DescriptionID.F, W.DescriptionComponentName.F, W.Description.F],
[qSearchFamily.W.IDProducer.F.Value, qSearchFamily.W.IDDatasheet.F.Value,
qSearchFamily.W.Datasheet.F.Value, qSearchFamily.W.IDDiagram.F.Value,
qSearchFamily.W.Diagram.F.Value, qSearchFamily.W.IDDrawing.F.Value,
qSearchFamily.W.Drawing.F.Value, qSearchFamily.W.IDImage.F.Value,
qSearchFamily.W.Image.F.Value, qSearchFamily.W.DescriptionID.F.Value,
qSearchFamily.W.DescriptionComponentName.F.Value,
qSearchFamily.W.Description.F.Value], False);
// Если семейство было найдено в другой категории
if W.SubGroup.F.AsString <> qSearchFamily.W.SubGroup.F.AsString then
W.SubGroup.F.AsString := CombineSubgroup(W.SubGroup.F.AsString,
qSearchFamily.W.SubGroup.F.AsString);
end;
end;
function TQueryFamily.GetFamilyW: TFamilyW;
begin
Result := W as TFamilyW;
end;
procedure TQueryFamily.OnDatasheetGetText(Sender: TField; var Text: String;
DisplayText: Boolean);
begin
if not Sender.AsString.IsEmpty then
Text := TPath.GetFileNameWithoutExtension(Sender.AsString);
end;
constructor TFamilyW.Create(AOwner: TComponent);
begin
inherited;
FProductCategoryId := TParamWrap.Create(Self, 'ProductCategoryID');
end;
procedure TFamilyW.AddNewValue(const AValue, AProducer: string);
begin
Assert(not AValue.Trim.IsEmpty);
Assert(not AProducer.Trim.IsEmpty);
TryAppend;
Value.F.AsString := AValue;
Producer.F.AsString := AProducer;
TryPost;
end;
function TFamilyW.LocateOrAppend(const AValue, AProducer: string): Boolean;
begin
// Ищем компонент по имени без учёта регистра
Result := Value.Locate(AValue, [lxoCaseInsensitive]);
if not Result then
AddNewValue(AValue, AProducer);
end;
end.
|
unit Wasm.Wasi;
// [ApiNamespace] wasi
interface
uses
Wasm, Ownership
;
type
PWasiConfig = ^TWasiConfig;
// [OwnBegin] wasi_config
TOwnWasiConfig = record
private
FStrongRef : IRcContainer<PWasiConfig>;
public
class function Wrap(p : PWasiConfig; deleter : TRcDeleter) : TOwnWasiConfig; overload; static; inline;
class function Wrap(p : PWasiConfig) : TOwnWasiConfig; overload; static;
class operator Finalize(var Dest: TOwnWasiConfig);
class operator Implicit(const Src : IRcContainer<PWasiConfig>) : TOwnWasiConfig;
class operator Positive(Src : TOwnWasiConfig) : PWasiConfig;
class operator Negative(Src : TOwnWasiConfig) : IRcContainer<PWasiConfig>;
function Unwrap() : PWasiConfig;
function IsNone() : Boolean;
end;
// [OwnEnd]
TWasiConfig = record
public
class function New() : TOwnWasiConfig; static;
procedure SetArgv(const argv : array of string);
procedure InheritArgv();
procedure SetEnv(const names : array of string; const values : array of string);
procedure InheritEnv();
procedure SetStdinFile(const path : string);
procedure InheritStdin();
procedure SetStdoutFile(const path : string);
procedure InheritStdout();
procedure SetStderrFile(const path : string);
procedure InheritStderr();
procedure PreopenDir(const path : string; const guest_path : string);
end;
TWasiConfigDelete = procedure({own} name : PWasiConfig); cdecl;
{$REGION 'TWasiConfigNew'}
(*
* \brief Creates a new empty configuration object.
*
* The caller is expected to deallocate the returned configuration
*)
{$ENDREGION}
TWasiConfigNew = function() : PWasiConfig; cdecl;
{$REGION 'TWasiConfigSetArgv'}
(*
* \brief Sets the argv list for this configuration object.
*
* By default WASI programs have an empty argv list, but this can be used to
* explicitly specify what the argv list for the program is.
*
* The arguments are copied into the `config` object as part of this function
* call, so the `argv` pointer only needs to stay alive for this function call.
*)
{$ENDREGION}
TWasiConfigSetArgv = procedure(config : PWasiConfig; argc : Int32; const argv : PPAnsiChar); cdecl;
{$REGION 'TWasiConfigInheritArgv'}
(*
* \brief Indicates that the argv list should be inherited from this process's
* argv list.
*)
{$ENDREGION}
TWasiConfigInheritArgv = procedure(config : PWasiConfig); cdecl;
{$REGION 'TWasiConfigSetEnv'}
(*
* \brief Sets the list of environment variables available to the WASI instance.
*
* By default WASI programs have a blank environment, but this can be used to
* define some environment variables for them.
*
* It is required that the `names` and `values` lists both have `envc` entries.
*
* The env vars are copied into the `config` object as part of this function
* call, so the `names` and `values` pointers only need to stay alive for this
* function call.
*)
{$ENDREGION}
TWasiConfigSetEnv = procedure(config : PWasiConfig; envc : Int32; const names : PPAnsiChar; const values : PPAnsiChar); cdecl;
{$REGION 'TWasiConfigInheritEnv'}
(*
* \brief Indicates that the entire environment of the calling process should be
* inherited by this WASI configuration.
*)
{$ENDREGION}
TWasiConfigInheritEnv = procedure(config : PWasiConfig); cdecl;
{$REGION 'TWasiConfigSetStdinFile'}
(*
* \brief Configures standard input to be taken from the specified file.
*
* By default WASI programs have no stdin, but this configures the specified
* file to be used as stdin for this configuration.
*
* If the stdin location does not exist or it cannot be opened for reading then
* `false` is returned. Otherwise `true` is returned.
*)
{$ENDREGION}
TWasiConfigSetStdinFile = procedure(config : PWasiConfig; const path : PAnsiChar); cdecl;
{$REGION 'TWasiConfigInheritStdin'}
(*
* \brief Configures this process's own stdin stream to be used as stdin for
* this WASI configuration.
*)
{$ENDREGION}
TWasiConfigInheritStdin = procedure(config : PWasiConfig); cdecl;
{$REGION 'TWasiConfigSetStdoutFile'}
(*
* \brief Configures standard output to be written to the specified file.
*
* By default WASI programs have no stdout, but this configures the specified
* file to be used as stdout.
*
* If the stdout location could not be opened for writing then `false` is
* returned. Otherwise `true` is returned.
*)
{$ENDREGION}
TWasiConfigSetStdoutFile = procedure(config : PWasiConfig; const path : PAnsiChar); cdecl;
{$REGION 'TWasiConfigInheritStdout'}
(*
* \brief Configures this process's own stdout stream to be used as stdout for
* this WASI configuration.
*)
{$ENDREGION}
TWasiConfigInheritStdout = procedure(config : PWasiConfig); cdecl;
{$REGION 'TWasiConfigSetStderrFile'}
(*
* \brief Configures standard output to be written to the specified file.
*
* By default WASI programs have no stderr, but this configures the specified
* file to be used as stderr.
*
* If the stderr location could not be opened for writing then `false` is
* returned. Otherwise `true` is returned.
*)
{$ENDREGION}
TWasiConfigSetStderrFile = procedure(config : PWasiConfig; const path : PAnsiChar); cdecl;
{$REGION 'TWasiConfigInheritStderr'}
(*
* \brief Configures this process's own stderr stream to be used as stderr for
* this WASI configuration.
*)
{$ENDREGION}
TWasiConfigInheritStderr = procedure(config : PWasiConfig); cdecl;
{$REGION 'TWasiConfigInheritStderr'}
(*
* \brief Configures a "preopened directory" to be available to WASI APIs.
*
* By default WASI programs do not have access to anything on the filesystem.
* This API can be used to grant WASI programs access to a directory on the
* filesystem, but only that directory (its whole contents but nothing above it).
*
* The `path` argument here is a path name on the host filesystem, and
* `guest_path` is the name by which it will be known in wasm.
*)
{$ENDREGION}
TWasiConfigPreopenDir = procedure(config : PWasiConfig; const path : PAnsiChar; const guest_path : PAnsiChar); cdecl;
TWasi = record
public class var
config_delete : TWasiConfigDelete;
config_new : TWasiConfigNew;
config_set_argv : TWasiConfigSetArgv;
config_inherit_argv : TWasiConfigInheritArgv;
config_set_env : TWasiConfigSetEnv;
config_inherit_env : TWasiConfigInheritEnv;
config_set_stdin_file : TWasiConfigSetStdinFile;
config_inherit_stdin : TWasiConfigInheritStdin;
config_set_stdout_file : TWasiConfigSetStdoutFile;
config_inherit_stdout : TWasiConfigInheritStdout;
config_set_stderr_file : TWasiConfigSetStderrFile;
config_inherit_stderr : TWasiConfigInheritStderr;
config_preopen_dir : TWasiConfigPreopenDir;
public
class procedure InitAPIs(runtime : HMODULE); static;
end;
implementation
uses
Windows;
{ TWasi }
class procedure TWasi.InitAPIs(runtime: HMODULE);
function ProcAddress(name : string) : Pointer;
begin
result := GetProcAddress(runtime, PWideChar(name));
end;
begin
if runtime <> 0 then
begin
config_delete := ProcAddress('wasi_config_delete');
config_new := ProcAddress('wasi_config_new');
config_set_argv := ProcAddress('wasi_config_set_argv');
config_inherit_argv := ProcAddress('wasi_config_inherit_argv');
config_set_env := ProcAddress('wasi_config_set_env');
config_inherit_env := ProcAddress('wasi_config_inherit_env');
config_set_stdin_file := ProcAddress('wasi_config_set_stdin_file');
config_inherit_stdin := ProcAddress('wasi_config_inherit_stdin');
config_set_stdout_file := ProcAddress('wasi_config_set_stdout_file');
config_inherit_stdout := ProcAddress('wasi_config_inherit_stdout');
config_set_stderr_file := ProcAddress('wasi_config_set_stderr_file');
config_inherit_stderr := ProcAddress('wasi_config_inherit_stderr');
config_preopen_dir := ProcAddress('wasi_config_preopen_dir');
end;
end;
// [OwnImplBegin]
{ TOwnWasiConfig }
procedure wasi_config_disposer(p : Pointer);
begin
TWasi.config_delete(p);
end;
class operator TOwnWasiConfig.Finalize(var Dest: TOwnWasiConfig);
begin
Dest.FStrongRef := nil;
end;
function TOwnWasiConfig.IsNone: Boolean;
begin
result := FStrongRef = nil;
end;
class operator TOwnWasiConfig.Negative(Src: TOwnWasiConfig): IRcContainer<PWasiConfig>;
begin
result := Src.FStrongRef;
end;
class operator TOwnWasiConfig.Positive(Src: TOwnWasiConfig): PWasiConfig;
begin
result := Src.Unwrap;
end;
class operator TOwnWasiConfig.Implicit(const Src : IRcContainer<PWasiConfig>) : TOwnWasiConfig;
begin
result.FStrongRef := Src;
end;
function TOwnWasiConfig.Unwrap: PWasiConfig;
begin
result := FStrongRef.Unwrap;
end;
class function TOwnWasiConfig.Wrap(p : PWasiConfig) : TOwnWasiConfig;
begin
if p <> nil then result.FStrongRef := TRcContainer<PWasiConfig>.Create(p, wasi_config_disposer)
else result.FStrongRef := nil;
end;
class function TOwnWasiConfig.Wrap(p : PWasiConfig; deleter : TRcDeleter) : TOwnWasiConfig;
begin
if p <> nil then result.FStrongRef := TRcContainer<PWasiConfig>.Create(p, deleter)
else result.FStrongRef := nil;
end;
// [OwnImplEnd]
{ TWasiConfig }
procedure TWasiConfig.InheritArgv;
begin
TWasi.config_inherit_argv(@self);
end;
procedure TWasiConfig.InheritEnv;
begin
TWasi.config_inherit_env(@self);
end;
procedure TWasiConfig.InheritStderr;
begin
TWasi.config_inherit_stderr(@self);
end;
procedure TWasiConfig.InheritStdin;
begin
TWasi.config_inherit_stdin(@self);
end;
procedure TWasiConfig.InheritStdout;
begin
TWasi.config_inherit_stdout(@self);
end;
class function TWasiConfig.New: TOwnWasiConfig;
begin
var p := TWasi.config_new();
result := TOwnWasiConfig.Wrap(p);
end;
procedure TWasiConfig.PreopenDir(const path, guest_path: string);
begin
TWasi.config_preopen_dir(@self, PAnsiChar(UTF8String(path)), PAnsiChar(UTF8String(guest_path)) );
end;
procedure TWasiConfig.SetArgv(const argv: array of string);
begin
var argvp : TArray<PPAnsiChar>;
var len := Length(argv);
SetLength(argvp, len);
for var i := 0 to len-1 do
begin
argvp[i] := PPAnsiChar(UTF8String(argv[i]));
end;
TWasi.config_set_argv(@self, len, @argvp[0]);
end;
procedure TWasiConfig.SetEnv(const names, values: array of string);
begin
var namep, valuep : TArray<PAnsiChar>;
var len := Length(names);
var len2 := Length(values);
if len = len2 then
begin
SetLength(namep, len);
SetLength(valuep, len);
for var i := 0 to len-1 do
begin
namep[i] := PAnsiChar(UTF8String(names[i]));
valuep[i] := PAnsiChar(UTF8String(values[i]));
end;
TWasi.config_set_env(@self, len, @namep[0], @valuep[0]);
end;
end;
procedure TWasiConfig.SetStderrFile(const path: string);
begin
TWasi.config_set_stderr_file(@self, PAnsiChar(UTF8String(path)));
end;
procedure TWasiConfig.SetStdinFile(const path: string);
begin
TWasi.config_set_stdin_file(@self, PAnsiChar(UTF8String(path)));
end;
procedure TWasiConfig.SetStdoutFile(const path: string);
begin
TWasi.config_set_stdout_file(@self, PAnsiChar(UTF8String(path)));
end;
end.
|
unit nkMemData;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, typinfo, DB, DateUtils, LResources, Forms, Controls, Graphics, Dialogs, rxmemds, IdHttp,
idGlobal, fpjson;
type
{ TnkMemData }
TnkMemData = class(TRxMemoryData)
private
FHttp:TIdHttp;
protected
public
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
function InitStructFromJson(AJson:string):boolean;//从Json初始化表结构
function InitStructFromUrl(AUrl:string):boolean;//从URL获取JSON初始化表结构
function FillDataFromJson(AJson:string):boolean;//从Json填充数据
function FillDataFromUrl(AUrl:string):boolean;//从URL获取Json填充数据
function ExportStructToJson:string;//导出表结构到JSON
function ExportDataToJson:string;//导出表数据到JSON
published
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Data Access',[TnkMemData]);
end;
{ TnkMemData }
constructor TnkMemData.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHttp:=TIdHttp.Create(Self);
FHttp.HandleRedirects:=True;
FHttp.ReadTimeout:=30000;
FHttp.Request.UserAgent:='Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Highland)';
end;
destructor TnkMemData.Destroy;
begin
FHttp.Free;
inherited Destroy;
end;
function TnkMemData.InitStructFromJson(AJson: string): boolean;
var
mOldActive:boolean;
jRecord: TJSONData;
i: Integer;
mFieldName:string;
mFieldTypeStr:string;
mFieldType:TFieldType;
mFieldSize:integer;
mFieldNo:integer;
begin
if Trim(AJson)='' then
Result:=False
else
begin
Self.DisableControls;
mOldActive:=Self.Active;
Self.Active:=False;
Self.FieldDefs.Clear;
try
jRecord:=GetJson(AJson,True);
for i:=0 to jRecord.Count-1 do
begin
mFieldName:=TJsonObject(jRecord.Items[i]).FindPath('name').AsString;
mFieldTypeStr:=TJsonObject(jRecord.Items[i]).FindPath('type').AsString;
mFieldType:=TFieldType(GetEnumValue(TypeInfo(TFieldType), mFieldTypeStr));
mFieldSize:=TJsonObject(jRecord.Items[i]).FindPath('size').AsInteger;
mFieldNo:=TJsonObject(jRecord.Items[i]).FindPath('no').AsInteger;
Self.FieldDefs.Add(mFieldName,mFieldType,mFieldSize,False,mFieldNo);
//Self.CreateTable;
end;
Result:=True;
except
Result:=False;
end;
Self.Active:=mOldActive;
Self.EnableControls;
end;
end;
function TnkMemData.InitStructFromUrl(AUrl: string): boolean;
var
mS:string;
begin
try
mS:=FHttp.Get(AUrl);
Result:=Self.InitStructFromJson(mS);
except
Result:=False;
end;
end;
function TnkMemData.FillDataFromJson(AJson: string): boolean;
var
jData : TJSONData;
jRecord: TJSONData;
i, j: Integer;
mTmp:Tstrings;
mStream:TMemoryStream;
begin
if (Trim(AJson)='') or (Self.Active=False) then
Result:=False
else
begin
Self.DisableControls;
try
mtmp:=TStringList.Create;
mTmp.Add(AJson);
mStream:=TMemoryStream.Create;
mTmp.SaveToStream(mStream);
mStream.Seek(0, soBeginning);
JData:=GetJson(mStream, True);
mStream.Free;
mTmp.Free;
Self.Close;
Self.Open;
Self.First;
while not Self.Eof do
begin
Self.Delete;
end;
for i := 0 to jData.Count - 1 do
begin
Self.Append;
jRecord := jData.Items[i];
for j := 0 to Self.FieldCount - 1 do
begin
case Self.Fields.Fields[j].DataType of
ftString, ftMemo, ftInteger, ftFloat:
Self.Fields[j].Text := jRecord.GetPath(Self.Fields[j].FieldName).AsString;
ftDate, ftDatetime:
Self.Fields[j].AsDateTime := UnixToDatetime(strtoint(jRecord.GetPath(Self.Fields[j].FieldName).AsString));
ftBoolean:
Self.Fields.Fields[j].AsBoolean:=(jRecord.GetPath(Self.Fields[j].FieldName).AsString='true');
end;
end;
Self.Post;
end;
Result:=True;
except
Result:=False;
end;
Self.EnableControls;
end;
end;
function TnkMemData.FillDataFromUrl(AUrl: string): boolean;
var
mS:string;
begin
try
mS:=FHttp.Get(AUrl,IndyTextEncoding_UTF8);
Result:=Self.FillDataFromJson(mS);
except
Result:=False;
end;
end;
function TnkMemData.ExportStructToJson: string;
var
i:integer;
mFieldName:string;
mFieldType:String;
mFieldSize:string;
mFieldNo:string;
begin
Result:='[';
Self.DisableControls;
for i:=0 to Self.FieldDefs.Count-1 do
begin
mFieldName:=Self.FieldDefs.Items[i].Name;
mFieldType:=GetEnumName(TypeInfo(TFieldType),Ord(Self.FieldDefs.Items[i].DataType));
mFieldSize:=inttostr(Self.FieldDefs.Items[i].Size);
mFieldNo:=inttostr(Self.FieldDefs.Items[i].FieldNo);
Result:=Result+'{"name":"'+mFieldName+'","type":"'+mFieldType+'","size":'+mFieldSize+',"no":'+mFieldNo+'}';
if i<Self.FieldDefs.Count-1 then
Result:=Result+',';
end;
Self.EnableControls;
Result:=Result+']';
end;
function TnkMemData.ExportDataToJson: string;
var
i,j:integer;
mValue:string;
mRecord:string;
begin
Result:='[';
if not Self.Active then
Exit;
Self.DisableControls;
Self.First;
for j:=0 to Self.RecordCount-1 do
begin
mRecord:='{';
for i:=0 to Self.Fields.Count-1 do
begin
case Self.Fields.Fields[i].DataType of
ftString, ftMemo: mValue:=Self.Fields.Fields[i].AsString;
ftDate, ftDatetime: mValue:=inttostr(DateTimeToUnix(Self.Fields.Fields[i].AsDateTime));
ftBoolean: if Self.Fields.Fields[i].AsBoolean then mValue:='true' else mValue:='false';
ftInteger: mValue:=inttostr(Self.Fields.Fields[i].AsInteger);
ftFloat: mValue:=floattostr(Self.Fields.Fields[i].AsFloat);
end;
mRecord:=mRecord+'"'+Self.Fields.Fields[i].FieldName+'":"'+mValue+'"';
if i < Self.Fields.Count-1 then
mRecord:=mRecord+',';
end;
mRecord:=mRecord+'}';
Result:=Result+mRecord;
if i<Self.RecordCount-1 then
Result:=Result+',';
Self.Next;
end;
Self.EnableControls;
Result:=Result+']';
end;
end.
|
// ================================================================
//
// Unit uDSProcessMgmtUtils.pas
//
// This unit contains some utilities for being used in process
// management routines.
//
// Esta unit contém utilidades para ser usadas no processo de
// leitura de memória.
//
// ===============================================================
unit uDSProcessMgmtUtils;
interface
uses
Windows, SysUtils;
// Function for checking the process "Dark Souls"
// Função para checar o processo "Dark Souls"
function IsDarkSoulsRunning: Boolean;
implementation
function IsDarkSoulsRunning: Boolean;
begin
Result := FindWindow(nil, 'DARK SOULS') <> 0;
end;
end.
|
unit FIToolkit.Types;
interface
type
TApplicationCommand = (
acStart,
acPrintHelp, acPrintVersion, acGenerateConfig, acSetConfig, acSetNoExitBehavior, acSetLogFile,
acExtractProjects, acExcludeProjects, acRunFixInsight, acParseReports, acExcludeUnits, acBuildReport, acMakeArchive,
acTerminate);
TApplicationState = (
asInitial,
asHelpPrinted, asVersionPrinted, asConfigGenerated, asConfigSet, asNoExitBehaviorSet, asLogFileSet,
asProjectsExtracted, asProjectsExcluded, asFixInsightRan, asReportsParsed, asUnitsExcluded, asReportBuilt, asArchiveMade,
asFinal);
TInputFileType = (iftUnknown, iftDPR, iftDPK, iftDPROJ, iftGROUPPROJ);
TNoExitBehavior = (neDisabled, neEnabled, neEnabledOnException);
implementation
end.
|
UNIT LinkBGI;
{register those graphics modes you might use}
interface
uses Graph, { library of graphics routines }
Drivers, { all the BGI drivers }
Fonts; { all the BGI fonts }
TYPE
GraphModes = (CGA,EGAVGA,ATT,Hercules,PC3270);
GraphModeSet = SET OF GraphModes;
PROCEDURE InstallGraphicsModes(modes : GraphModeSet);
(*================================================================== *)
implementation
var
GraphDriver, GraphMode, Error : integer;
procedure Abort(Msg : string);
begin
Writeln(Msg, ': ', GraphErrorMsg(GraphResult));
Halt(1);
end;
PROCEDURE InstallGraphicsModes(modes : GraphModeSet);
begin
{ Register all the drivers }
IF CGA IN modes THEN
if RegisterBGIdriver(@CGADriverProc) < 0 then
Abort('CGA');
IF EGAVGA IN modes THEN
if RegisterBGIdriver(@EGAVGADriverProc) < 0 then
Abort('EGA/VGA');
IF Hercules IN modes THEN
if RegisterBGIdriver(@HercDriverProc) < 0 then
Abort('Herc');
IF ATT IN modes THEN
if RegisterBGIdriver(@ATTDriverProc) < 0 then
Abort('AT&T');
IF PC3270 IN modes THEN
if RegisterBGIdriver(@PC3270DriverProc) < 0 then
Abort('PC 3270');
END;
end.
|
{------------------------------------------------------------------------------
This file is part of the MotifMASTER project. This software is
distributed under GPL (see gpl.txt for details).
This software 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.
Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru)
------------------------------------------------------------------------------}
unit CBRCComponent;
interface
uses Classes, SelfSaved, ClassInheritIDs;
type
TCBRCComponent = class(TSelfSavedComponent)
{ the component Controlled By References Counter (CBRC) }
protected
FRefCount: LongInt;
IntControlled: Boolean;
function _AddRef: Integer; virtual; stdcall;
function _Release: Integer; virtual; stdcall;
class function GetPropHeaderRec: TPropHeaderRec; override;
class procedure ReadProperties(
const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent
); override;
class procedure WriteProperties(
const Writer: TWriter;
const AnObject: TSelfSavedComponent
); override;
public
procedure Free;
property RefCount: LongInt read FRefCount;
end;
implementation
procedure TCBRCComponent.Free;
begin
if Self <> nil then
begin
if RefCount = 0 then inherited
else IntControlled := True;
end;
end;
class function TCBRCComponent.GetPropHeaderRec: TPropHeaderRec;
begin
Result.ClassInheritID := CBRCClassInheritID;
Result.PropVersionNum := CBRCCurVerNum;
end;
class procedure TCBRCComponent.ReadProperties(const Reader: TReader;
const PropHeaderRec: TPropHeaderRec;
const AnObject: TSelfSavedComponent);
begin
end;
class procedure TCBRCComponent.WriteProperties(const Writer: TWriter;
const AnObject: TSelfSavedComponent);
begin
end;
function TCBRCComponent._AddRef: Integer;
begin
Inc(FRefCount);
Result := RefCount;
end;
function TCBRCComponent._Release: Integer;
begin
Dec(FRefCount);
Result := RefCount;
if IntControlled and (Result = 0) then Free;
end;
initialization
RegisterClass(TCBRCComponent);
end.
|
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
program processturn;
uses
sysutils,
exceptions,
world;
// Command line argument: directory of last turn, directory of next turn
// The last turn directory should contain these files:
// server.json
// state-for-player-ID.json (these are ignored by this program)
// turn-for-player-ID.json
// (where ID is the player ID)
// The next turn directory should not yet exist (and will be created).
// The state-for-player-ID.json JSON files are ignored (they are the
// output from the last turn; see below). The server.json file has
// the following format:
{
Turn: T,
Players: [ player, player, player, ... ],
Provinces: [ province, province, province, ... ],
}
// Players and provinces are referenced by their ID which is given
// in the JSON object, see below.
// Each province is a JSON object with the following format:
{
ID: number, // the province ID
Name: 'string...',
Owner: 'string', // the player ID
Troups: number,
Neighbours: [ number, number, ... ], // province IDs
}
// Each player is a JSON object with the following format:
{
Name: 'string...',
ID: 'string...',
}
// Player IDs must be 1 to 10 characters long, only characters in
// the range 'a' to 'z' (lowercase).
// The turn-for-player-ID.json JSON files have the following format:
{
Actions: [ action, action, ... ],
}
// Each action is a JSON object with the following format:
{
Action: 'move',
From: number, // province ID
To: number, // province ID
Count: number, // number of troops to move
}
// If there are insufficient turn files for the last turn, then the
// server does nothing. If the files are malformed, they are
// treated as empty orders. If some orders are invalid, those
// orders are ignored, but the rest are applied.
// Otherwise, it outputs new server.json and state-for-player-ID.json
// files. The server.json file is for internal use (it tracks the
// server state). The state-for-player-ID.json JSON files have the
// following format:
{
Player: 'id...', // the player ID
Turn: T, // the turn number, first turn (as output by start-game) is 1
Players: [ player, player, player, ... ], // see above for format
Provinces: [ province, province, province, ... ], // see above for format
}
procedure ProcessTurn(const LastTurnDir, NextTurnDir: AnsiString);
var
World: TPerilWorldTurn;
begin
if (not DirectoryExists(LastTurnDir)) then
raise Exception.Create('first argument is not a directory that exists');
if (DirectoryExists(NextTurnDir)) then
raise Exception.Create('third argument is a directory that exists');
if (not CreateDir(NextTurnDir)) then
raise Exception.Create('could not create directory for next turn');
World := TPerilWorldTurn.Create();
try
World.LoadData(LastTurnDir + '/server.json', [pdfProvinces, pdfPlayers, pdfTurnNumber]);
World.LoadInstructions(LastTurnDir);
World.ExecuteInstructions();
World.SaveData(NextTurnDir);
finally
World.Free();
end;
end;
begin
try
if (ParamCount() <> 2) then
raise Exception.Create('arguments must be <last-turn-directory> <next-turn-directory>');
ProcessTurn(ParamStr(1), ParamStr(2));
except
on E: Exception do
begin
{$IFDEF DEBUG}
Writeln('Unexpected failure in process-turn:');
ReportCurrentException();
{$ELSE}
Writeln('process-turn: ', E.Message);
{$ENDIF}
ExitCode := 1;
end;
end;
end. |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2015-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Beacon.Common;
interface
uses
System.Beacon;
type
/// <summary>
/// Implements TBeaconManager for the android and OSX platforms, and for the alternative beacons mode in iOS
/// </summary>
TPlatformBeaconManager = class(TBeaconManager)
public
class function GetInstance(AMode: TBeaconScanMode): TBeaconManager; override;
end;
implementation
uses
System.SysUtils,
System.Bluetooth,
System.NetConsts,
System.TypInfo,
System.Math,
System.Generics.Collections,
System.Classes,
System.SyncObjs,
System.DateUtils,
System.Types;
const
CHECKING_ALIVE_TIME = 2000;
type
TBeaconIDToRegister = record
BeaconsInRegion: Word;
case KindofBeacon: TKindofBeacon of
TKindofBeacon.Eddystones:
(Namespace: TNamespace; Instance: TInstance; AllInstances: Boolean;);
TKindofBeacon.iBeacons, TKindofBeacon.AltBeacons, TKindofBeacon.iBAltBeacons:
(GUID: TGUID; Major, Minor: Integer; ManufacturerId: Integer);
end;
TBeaconIDToRegisterList = TList<TBeaconIDToRegister>;
TRcCommonBeacon = record
BeaconInfo: TBeaconInfo;
Rssi: Integer;
Distance: Double;
Proximity: TBeaconProximity;
RssiMean: TMeanCalculator<Integer>;
LastMRSSI: Integer;
end;
TCommonBeacon = class(TInterfacedObject, IBeacon)
private
FRBeacon: TRcCommonBeacon;
FTimeAlive: TDateTime;
FIsAlive: Boolean;
FregionID: Integer;
public
constructor create(const ARcCommonBeacon: TRcCommonBeacon);
/// <summary> deprecated use IStandardBeacon.GUID <summary>
function GetGUID: TGUID;
/// <summary> deprecated use IStandardBeacon.Major <summary>
function GetMajor: Word;
/// <summary> deprecated use IStandardBeacon.Minor <summary>
function GetMinor: Word;
function GetRssi: Integer;
function GetDistance: Double;
function GetDeviceIdentifier: string;
function IsEqualTo(const AGUID: TGUID; AMajor, AMinor: Word): Boolean; overload;
function IsEqualTo(const ANamespace: TNamespace; const AInstance: TInstance): Boolean; overload;
function IsEqualTo(const AIBeacon: IBeacon): Boolean; overload;
function ItsAlive:Boolean;
function GettxPower: Integer; inline;
function GetProximity: TBeaconProximity;
/// <summary> deprecated use IStandardBeacon.AltAdditionalData <summary>
function GetAdditionalData: TBytes;
function GetKindofBeacon: TKindofBeacon;
procedure SetProximity(AProximity: TBeaconProximity); inline;
procedure SetRssi(ARssi: Integer); inline;
procedure SetDistance(ADistance: Double); inline;
property txPower: Integer read GettxPower;
property Rssi: Integer write SetRssi;
property Distance: Double write SetDistance;
property TimeAlive: TDateTime read FTimeAlive write FTimeAlive;
property RegionID: Integer read FRegionID write FRegionID;
property Proximity: TBeaconProximity read GetProximity write SetProximity;
/// <summary> deprecated use IStandardBeacon.AltAdditionalData <summary>
property AdditionalData: TBytes read GetAdditionalData;
end;
TStandardBeacon = class(TCommonBeacon, IStandardBeacon)
end;
TiBeacon = class(TStandardBeacon, IiBeacon)
end;
TAltBeacon = class(TStandardBeacon, IAltBeacon)
public
function GetAltAdditionalData: byte;
end;
TEddystoneBeacon = class(TCommonBeacon, IEddystoneBeacon)
protected
function GetEddystoneBeacon: TEddystoneBeaconInfo;
procedure SetEddystoneBeacon(const AValue: TEddystoneBeaconInfo);
public
function GetKindofEddystones: TKindofEddystones;
function GetEddystoneUID: TEddystoneUID;
function GetEddystoneURL: TEddystoneURL;
function GetEddystoneTLM: TEddystoneTLM;
end;
TBeAlive = procedure(const Sender: TObject) of object;
TCommonBeaconManager = class(TBeaconManager)
const
/// <summary> Eddystone UID frame type </summary>
EDDYSTONE_UID = $00;
/// <summary> Eddystone URL frame type </summary>
EDDYSTONE_URL = $10;
/// <summary> Eddystone TLM frame type </summary>
EDDYSTONE_TLM = $20;
EDDY_NAMESPACE_MASK: TNamespace = ($0,$0,$0,$0,$0,$0,$0,$0,$0,$0);
EDDY_INSTANCE_MASK: TInstance = ($0,$0,$0,$0,$0,$0);
EDDY_FRAMETYPE_POS = 0;
EDDY_TX_POS = 1;
EDDY_URL_SCHEME_POS = 2;
EDDY_SIGNAL_LOSS_METER: Byte = 41;
EDDY_UID_LEN = 20;
EDDY_UID_NAMESPACE_POS = 2;
EDDY_UID_NAMESPACE_LEN = 10;
EDDY_UID_INSTANCE_POS = 12;
EDDY_UID_INSTANCE_LEN = 6;
EDDY_TLM_LEN = 14;
EDDY_TLM_VERSION_POS = 1;
EDDY_TLM_BATTVOLTAGE_POS = 2;
EDDY_TLM_BEACONTEMP_POS = 4;
EDDY_TLM_ADVPDUCOUNT_POS = 6;
EDDY_TLM_TIMESINCEPOWERON_POS = 10;
EDDY_RFU_DATA_POS = 18;
EDDY_RFU_DATA_LEN = 2;
EDDY_MIN_URL_LEN = 3;
EDDY_ENCODED_URL_LEN = 17;
private type
TThreadScanner = class(TThread)
private
[Weak]FTManager: TBluetoothLEManager;
FEvent: TEvent;
FAliveEvent: TEvent;
FTimeScanning: Integer;
FTimeSleeping: Integer;
FBluetoothLEScanFilterList: TBluetoothLEScanFilterList;
public
constructor Create(const ATManager: TBluetoothLEManager);
destructor Destroy; override;
procedure Execute; override;
end;
TThreadIsAlive = class(TThread)
const
FChekingTime = CHECKING_ALIVE_TIME;
private
FBeAlive: TBeAlive;
FEvent: TEvent;
FScannerEvent: TEvent;
public
constructor Create(ABeAlive: TBeAlive);
destructor Destroy; override;
procedure Execute; override;
end;
protected
function DoRegisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons;
AManufacturerId: Integer = MANUFATURER_ID_ALL): Boolean; overload; override;
function DoRegisterBeacon(const AGUID: TGUID; AMajor: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons;
AManufacturerId: Integer = MANUFATURER_ID_ALL): Boolean; overload; override;
function DoRegisterBeacon(const AGUID: TGUID; AMajor, AMinor: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons;
AManufacturerId: Integer = MANUFATURER_ID_ALL): Boolean; overload; override;
function DoRegisterEddyBeacon(const ANamespace: TNamespace): Boolean; overload; override;
function DoRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean; overload; override;
function DoUnregisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons): Boolean; overload; override;
function DoUnregisterBeacon(const AGUID: TGUID; AMajor: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons): Boolean; overload; override;
function DoUnregisterBeacon(const AGUID: TGUID; AMajor, AMinor: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons): Boolean; overload; override;
function DoUnRegisterEddyBeacon(const ANamespace: TNamespace): Boolean; overload; override;
function DoUnRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean; overload; override;
function DoNearest: IBeacon; override;
function DoStartScan: Boolean; override;
function DoStopScan: Boolean; override;
procedure SetBeaconDeathTime(AValue: Integer); override;
procedure SetScanningSleepingTime(AValue: Integer); override;
procedure SetScanningTime(AValue: Integer); override;
procedure SetSPC(AValue: Single); override;
procedure SetBeaconType(AValue: Word); override;
function CreateScanFilters: TBluetoothLEScanFilterList;
function GetNumberofBeaconsRegistered: Integer; override;
procedure DoSetKindofBeacons(AValue: TKindofBeacons); override;
function GeTKindofBeacons: TKindofBeacons; override;
class function GetInstance(AMode: TBeaconScanMode): TBeaconManager; override;
private
FBeaconIDToRegisterList: TBeaconIDToRegisterList;
FRssiAccumulatedDiff: Single;
FThreadScanner: TThreadScanner;
FThreadIsAlive: TThreadIsAlive;
FManager: TBluetoothLEManager;
FBeaconList: TBeaconList;
FBeaconListLock: TObject;
FCommonBeaconDeathTime: TDateTime;
FCommonCalcMode: TBeaconCalcMode;
FScanning: Boolean;
procedure DiscoverLEDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice; Rssi: Integer; const ScanResponse: TScanResponse);
procedure BeAlive(const Sender: TObject);
function FRegisterBeacon(const ABeaconIDToRegister: TBeaconIDToRegister): Boolean;
function FUnregisterBeacon(const AGUID: TGUID; AMajor, AMinor: Integer; const AKindofBeacon: TKindofBeacon;
const ANamespace: TNamespace; const AInstance: TInstance): Boolean;
public
constructor Create(AMode: TBeaconScanMode);
destructor Destroy; override;
property IsScanning: Boolean read FScanning;
end;
TStandardBeaconParser = class(TBeaconManufacturerDataParser)
const
BEACON_GUID_POSITION = 4;
BEACON_TYPE_POSITION = 2;
BEACON_MAJOR_POSITION = 20;
BEACON_MINOR_POSITION = 22;
public
class function Parse(const AData: TBytes; var BeaconInfo: TBeaconInfo): Boolean; override;
end;
TAlternativeBeaconParser = class(TBeaconManufacturerDataParser)
const
BEACON_GUID_POSITION = 4;
BEACON_TYPE_POSITION = 2;
BEACON_MAJOR_POSITION = 20;
BEACON_MINOR_POSITION = 22;
public
class function Parse(const AData: TBytes; var BeaconInfo: TBeaconInfo): Boolean; override;
end;
{ TCommonBeacon }
constructor TCommonBeacon.create(const ARcCommonBeacon: TRcCommonBeacon);
begin
FRBeacon := ARcCommonBeacon;
FTimeAlive := Now;
end;
function TCommonBeacon.GetRssi: Integer;
begin
TMonitor.Enter(Self);
try
Result := FRBeacon.Rssi;
finally
TMonitor.Exit(Self);
end;
end;
function TCommonBeacon.GetDistance: Double;
begin
TMonitor.Enter(Self);
try
Result := FRBeacon.Distance;
finally
TMonitor.Exit(Self);
end;
end;
function TCommonBeacon.GetKindofBeacon: TKindofBeacon;
begin
Result := FRBeacon.BeaconInfo.KindofBeacon;
end;
function TCommonBeacon.GetDeviceIdentifier: string;
begin
Result := FRBeacon.BeaconInfo.DeviceIdentifier;
end;
function TCommonBeacon.IsEqualTo(const AGUID: TGUID; AMajor, AMinor: word): Boolean;
begin
Result := ((FRBeacon.BeaconInfo.GUID = AGUID) and (FRBeacon.BeaconInfo.Major = AMajor) and (FRBeacon.BeaconInfo.Minor = AMinor));
end;
function TCommonBeacon.IsEqualTo(const ANamespace: TNamespace; const AInstance: TInstance): Boolean;
begin
Result := CompareMem(@FRBeacon.BeaconInfo.EddystoneBeacon.EddystoneUID.Namespace, @ANamespace, TCommonBeaconManager.EDDY_UID_NAMESPACE_LEN) and
CompareMem(@FRBeacon.BeaconInfo.EddystoneBeacon.EddystoneUID.Instance, @AInstance, TCommonBeaconManager.EDDY_UID_INSTANCE_LEN);
end;
function TCommonBeacon.IsEqualTo(const AIBeacon: IBeacon): Boolean;
var
LIStandardBeacon: IStandardBeacon;
begin
case AIBeacon.KindofBeacon of
TKindofBeacon.iBeacons, TKindofBeacon.AltBeacons:
if (Supports(AIBeacon, IStandardBeacon, LIStandardBeacon)) then
Result := IsEqualTo(LIStandardBeacon.GUID, LIStandardBeacon.Major, LIStandardBeacon.Minor)
else
Result := False;
TKindofBeacon.Eddystones: Result := (AIBeacon.DeviceIdentifier = FRBeacon.BeaconInfo.DeviceIdentifier);
else
Result := False;
end;
end;
function TCommonBeacon.ItsAlive:Boolean;
begin
TMonitor.Enter(Self);
try
Result := FIsAlive;
finally
TMonitor.Exit(Self);
end;
end;
function TCommonBeacon.GetTxPower: Integer;
begin
Result := FRBeacon.BeaconInfo.TxPower;
end;
function TCommonBeacon.GetProximity: TBeaconProximity;
begin
TMonitor.Enter(Self);
try
Result := FRBeacon.Proximity;
finally
TMonitor.Exit(Self);
end;
end;
procedure TCommonBeacon.SetProximity(AProximity: TBeaconProximity);
begin
FRBeacon.Proximity := AProximity;
end;
procedure TCommonBeacon.SetRssi(ARssi: Integer);
begin
FRBeacon.Rssi := ARssi;
end;
procedure TCommonBeacon.SetDistance(ADistance: Double);
begin
FRBeacon.Distance := ADistance;
end;
function TCommonBeacon.GetAdditionalData: TBytes;
begin
TMonitor.Enter(Self);
try
SetLength(Result, 1);
Result[0] := FRBeacon.BeaconInfo.AdditionalData;
finally
TMonitor.Exit(Self);
end;
end;
function TCommonBeacon.GetGUID: TGUID;
begin
Result := FRBeacon.BeaconInfo.GUID;
end;
function TCommonBeacon.GetMinor: Word;
begin
Result := FRBeacon.BeaconInfo.Minor;
end;
function TCommonBeacon.GetMajor: Word;
begin
Result := FRBeacon.BeaconInfo.Major;
end;
{ TAltBeacon }
function TAltBeacon.GetAltAdditionalData: Byte;
begin
TMonitor.Enter(Self);
try
Result := FRBeacon.BeaconInfo.AdditionalData;
finally
TMonitor.Exit(Self);
end;
end;
{ TCommonBeaconManager }
class function TCommonBeaconManager.GetInstance(AMode: TBeaconScanMode): TBeaconManager;
begin
Result := TCommonBeaconManager.Create(AMode);
end;
function TCommonBeaconManager.GeTKindofBeacons: TKindofBeacons;
begin
Result := FKindofBeacons;
end;
function TCommonBeaconManager.GetNumberofBeaconsRegistered: Integer;
begin
if FBeaconIDToRegisterList <> nil then
Result := FBeaconIDToRegisterList.Count
else
Result := 0;
end;
function TCommonBeaconManager.DoRegisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon; AManufacturerId: Integer): Boolean;
var
LBeaconIDToRegister: TBeaconIDToRegister;
begin
if AKindofBeacon <> TKindofBeacon.Eddystones then
begin
LBeaconIDToRegister.BeaconsInRegion := 0;
LBeaconIDToRegister.KindofBeacon := AKindofBeacon;
LBeaconIDToRegister.GUID := AGUID;
LBeaconIDToRegister.Major := MAJOR_REGION_ALL;
LBeaconIDToRegister.Minor := MINOR_REGION_ALL;
LBeaconIDToRegister.ManufacturerId := AManufacturerId;
Result := FRegisterBeacon(LBeaconIDToRegister);
end
else
Result := False;
end;
function TCommonBeaconManager.DoRegisterBeacon(const AGUID: TGUID; AMajor: Word; const AKindofBeacon: TKindofBeacon; AManufacturerId: Integer): Boolean;
var
LBeaconIDToRegister: TBeaconIDToRegister;
begin
if AKindofBeacon <> TKindofBeacon.Eddystones then
begin
LBeaconIDToRegister.BeaconsInRegion := 0;
LBeaconIDToRegister.KindofBeacon := AKindofBeacon;
LBeaconIDToRegister.GUID := AGUID;
LBeaconIDToRegister.Major := AMajor;
LBeaconIDToRegister.Minor := MINOR_REGION_ALL;
LBeaconIDToRegister.ManufacturerId := AManufacturerId;
Result := FRegisterBeacon(LBeaconIDToRegister);
end
else
Result := False;
end;
function TCommonBeaconManager.DoRegisterBeacon(const AGUID: TGUID; AMajor, AMinor: Word; const AKindofBeacon: TKindofBeacon; AManufacturerId: Integer): Boolean;
var
LBeaconIDToRegister: TBeaconIDToRegister;
begin
if AKindofBeacon <> TKindofBeacon.Eddystones then
begin
LBeaconIDToRegister.BeaconsInRegion := 0;
LBeaconIDToRegister.KindofBeacon := AKindofBeacon;
LBeaconIDToRegister.GUID := AGUID;
LBeaconIDToRegister.Major := AMajor;
LBeaconIDToRegister.Minor := AMinor;
LBeaconIDToRegister.ManufacturerId := AManufacturerId;
Result := FRegisterBeacon(LBeaconIDToRegister);
end
else
Result := False;
end;
function TCommonBeaconManager.DoRegisterEddyBeacon(const ANamespace: TNamespace): Boolean;
var
LBeaconIDToRegister: TBeaconIDToRegister;
begin
LBeaconIDToRegister.BeaconsInRegion := 0;
LBeaconIDToRegister.KindofBeacon := TKindofBeacon.Eddystones;
LBeaconIDToRegister.Namespace := ANamespace;
LBeaconIDToRegister.Instance := EDDY_INSTANCE_MASK;
LBeaconIDToRegister.AllInstances := True;
Result := FRegisterBeacon(LBeaconIDToRegister);
end;
function TCommonBeaconManager.DoRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean;
var
LBeaconIDToRegister: TBeaconIDToRegister;
begin
LBeaconIDToRegister.BeaconsInRegion := 0;
LBeaconIDToRegister.KindofBeacon := TKindofBeacon.Eddystones;
LBeaconIDToRegister.Namespace := ANamespace;
LBeaconIDToRegister.Instance := AInstance;
LBeaconIDToRegister.AllInstances := False;
Result := FRegisterBeacon(LBeaconIDToRegister);
end;
function TCommonBeaconManager.FRegisterBeacon(const ABeaconIDToRegister: TBeaconIDToRegister): Boolean;
var
I: Integer;
LDiscovering: Boolean;
LNamespace: TNamespace;
LInstance: TInstance;
begin
Result := True;
if FBeaconIDToRegisterList = nil then
FBeaconIDToRegisterList := TBeaconIDToRegisterList.create;
if FManager <> nil then
begin
LDiscovering := isScanning;
if LDiscovering then
DoStopScan;
end
else
LDiscovering := False;
I := 0;
while I < FBeaconIDToRegisterList.Count do
begin
if FBeaconIDToRegisterList[I].KindofBeacon = ABeaconIDToRegister.KindofBeacon then
if (ABeaconIDToRegister.KindofBeacon = TKindofBeacon.Eddystones)then
begin
LNamespace := FBeaconIDToRegisterList[I].Namespace;
if CompareMem(@LNamespace, @ABeaconIDToRegister.Namespace, EDDY_UID_NAMESPACE_LEN) then
begin
LInstance := FBeaconIDToRegisterList[I].Instance;
if CompareMem(@LInstance, @ABeaconIDToRegister.Instance, EDDY_UID_INSTANCE_LEN) then
Result := False
else
FUnregisterBeacon(TGUID.Empty, 0, 0, ABeaconIDToRegister.KindofBeacon, ABeaconIDToRegister.Namespace, ABeaconIDToRegister.Instance);
Break;
end;
end
else
begin
if FBeaconIDToRegisterList[I].GUID = ABeaconIDToRegister.GUID then
begin
if (FBeaconIDToRegisterList[I].Major = ABeaconIDToRegister.Major) and (FBeaconIDToRegisterList[I].Minor = ABeaconIDToRegister.Minor) then
Result := False
else
FUnregisterBeacon(ABeaconIDToRegister.GUID, MAJOR_REGION_ALL, MINOR_REGION_ALL, ABeaconIDToRegister.KindofBeacon, EDDY_NAMESPACE_MASK, EDDY_INSTANCE_MASK);
Break;
end;
end;
Inc(I);
end;
if Result then
FBeaconIDToRegisterList.Add(ABeaconIDToRegister);
if LDiscovering then
DoStartScan;
end;
function TCommonBeaconManager.DoUnregisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon): Boolean;
begin
Result := FUnregisterBeacon(AGUID, MAJOR_REGION_ALL, MINOR_REGION_ALL, AKindofBeacon, EDDY_NAMESPACE_MASK, EDDY_INSTANCE_MASK);
end;
function TCommonBeaconManager.DoUnregisterBeacon(const AGUID: TGUID; AMajor: Word; const AKindofBeacon: TKindofBeacon): Boolean;
begin
Result := FUnregisterBeacon(AGUID, AMajor, MINOR_REGION_ALL, AKindofBeacon, EDDY_NAMESPACE_MASK, EDDY_INSTANCE_MASK);
end;
function TCommonBeaconManager.DoUnregisterBeacon(const AGUID: TGUID; AMajor, AMinor: Word; const AKindofBeacon: TKindofBeacon): Boolean;
begin
Result := FUnregisterBeacon(AGUID, AMajor, AMinor, AKindofBeacon, EDDY_NAMESPACE_MASK, EDDY_INSTANCE_MASK);
end;
function TCommonBeaconManager.DoUnRegisterEddyBeacon(const ANamespace: TNamespace): Boolean;
begin
Result := FUnregisterBeacon(TGUID.Empty, 0, 0, TKindofBeacon.Eddystones, ANamespace, EDDY_INSTANCE_MASK);
end;
function TCommonBeaconManager.DoUnRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean;
begin
Result := FUnregisterBeacon(TGUID.Empty, 0, 0, TKindofBeacon.Eddystones, ANamespace, AInstance);
end;
function TCommonBeaconManager.FUnregisterBeacon(const AGUID: TGUID; AMajor, AMinor: Integer; const AKindofBeacon: TKindofBeacon;
const ANamespace: TNamespace; const AInstance: TInstance): Boolean;
procedure BeaconListChecking;
var
I: Integer;
LBLength: Integer;
LTailElements: Integer;
LIBeacon: IBeacon;
begin
if FBeaconList <> nil then
begin
LBLength := Length(FBeaconList);
for I := LBLength - 1 downto 0 do
begin
if ((FBeaconList[I].KindofBeacon = AKindofBeacon) or
((AKindofBeacon = TKindofBeacon.iBAltBeacons) and ((FBeaconList[I].KindofBeacon = TKindofBeacon.iBeacons) or
(FBeaconList[I].KindofBeacon = TKindofBeacon.AltBeacons))))
and (FBeaconList[I].GUID = AGUID) then
begin
LIBeacon := FBeaconList[I];
(LIBeacon as TCommonBeacon).FIsAlive := False;
LTailElements := LBLength - (I + 1);
FBeaconList[I] := nil;
if LTailElements > 0 then
Move(FBeaconList[I + 1], FBeaconList[I], SizeOf(IBeacon) * LTailElements);
Initialize(FBeaconList[LBLength - 1]);
SetLength(FBeaconList, LBLength - 1);
LBLength := Length(FBeaconList);
end;
end;
end;
end;
var
I: Integer;
LDiscovering: Boolean;
LNamespace: TNamespace;
LInstance: TInstance;
begin
Result := False;
I := 0;
if FBeaconIDToRegisterList <> nil then
begin
if FManager <> nil then
begin
LDiscovering := (FManager.CurrentAdapter.State = TBluetoothAdapterState.Discovering);
if LDiscovering then
DoStopScan;
end
else
LDiscovering := False;
while I < FBeaconIDToRegisterList.Count do
begin
if (FBeaconIDToRegisterList[I].KindofBeacon = AKindofBeacon) then
begin
if (AKindofBeacon = TKindofBeacon.Eddystones) then
begin
LNamespace := FBeaconIDToRegisterList[I].Namespace;
LInstance := FBeaconIDToRegisterList[I].Instance;
if CompareMem(@LNamespace, @ANamespace, EDDY_UID_NAMESPACE_LEN) then
begin
Result := True;
FBeaconIDToRegisterList.Delete(I);
BeaconListChecking;
Break;
end;
end
else
if (FBeaconIDToRegisterList[I].Guid = AGuid) and ((AMajor = MAJOR_REGION_ALL) or ((FBeaconIDToRegisterList[I].Major = AMajor) and
(AMinor = MINOR_REGION_ALL)) or ((FBeaconIDToRegisterList[I].Major = AMajor) and (FBeaconIDToRegisterList[I].Minor = AMinor))) then
begin
Result := True;
FBeaconIDToRegisterList.Delete(I);
BeaconListChecking;
Break;
end;
end;
Inc(I);
end;
if LDiscovering then
DoStartScan;
end;
end;
function TCommonBeaconManager.DoNearest: IBeacon;
var
I: Word;
LBLength: Word;
LDistance: Double;
LBeaconNum: Word;
begin
if FBeaconList <> nil then
begin
I := 0;
LBeaconNum := 0;
LDistance := LDistance.MaxValue;
TMonitor.Enter(FBeaconListLock);
try
LBLength := Length(FBeaconList);
while I < LBLength do
begin
if FBeaconList[I].Distance < LDistance then
begin
LDistance := FBeaconList[I].Distance;
LBeaconNum := I;
end;
Inc(I);
end;
Result := FBeaconList[LBeaconNum];
finally
TMonitor.Exit(FBeaconListLock);
end;
end;
end;
function TCommonBeaconManager.CreateScanFilters: TBluetoothLEScanFilterList;
var
LBeaconManufacturerDataHelper: TBeaconManufacturerDataHelper;
LBluetoothLEScanFilter: TBluetoothLEScanFilter;
LiBeaconFiltered: Boolean;
LAltBeaconFiltered: Boolean;
LBeaconIDToRegister: TBeaconIDToRegister;
LTB: TBytes;
I: Integer;
function CreateMnfDataBeaconsFilter(const AGUIDToRegister: TBeaconIDToRegister): TBluetoothLEScanFilter;
begin
Result := TBluetoothLEScanFilter.Create;
LBeaconManufacturerDataHelper.GUID := AGUIDToRegister.GUID;
if AGUIDToRegister.Major > -1 then
LBeaconManufacturerDataHelper.Major := AGUIDToRegister.Major;
if AGUIDToRegister.Minor > -1 then
LBeaconManufacturerDataHelper.Minor := AGUIDToRegister.Minor;
LBeaconManufacturerDataHelper.BeaconType := AGUIDToRegister.KindofBeacon;
LBeaconManufacturerDataHelper.ManufacturerId := AGUIDToRegister.ManufacturerId;
Result.ManufacturerSpecificData := LBeaconManufacturerDataHelper.ToByteArray;
Result.ManufacturerSpecificDataMask := LBeaconManufacturerDataHelper.MDataMask;
DoNewBLEScanFilter(TKindofScanFilter.ManufacturerData, Result);
end;
function CreateServDataBeaconsFilter(const AGUIDToRegister: TBeaconIDToRegister; ARFU: Boolean): TBluetoothLEScanFilter;
var
LServiceDataRawData: TServiceDataRawData;
begin
Result := TBluetoothLEScanFilter.Create;
Result.ServiceUUID := EDDYSTONE_SERVICE_UUID;
LServiceDataRawData.Key := EDDYSTONE_SERVICE_UUID;
LServiceDataRawData.Value := TBeaconManufacturerDataHelper.EDDY_UID_NAMESPACE_MASK;
if not ARFU then
SetLength(LServiceDataRawData.Value, Length(TBeaconManufacturerDataHelper.EDDY_UID_NAMESPACE_MASK) - EDDY_RFU_DATA_LEN);
LServiceDataRawData.Value[EDDY_FRAMETYPE_POS] := EDDYSTONE_UID;
Move(AGUIDToRegister.Namespace, LServiceDataRawData.Value[EDDY_UID_NAMESPACE_POS], EDDY_UID_NAMESPACE_LEN);
if CompareMem(@AGUIDToRegister.Instance, @EDDY_INSTANCE_MASK, EDDY_UID_INSTANCE_LEN) then
begin
if ARFU then
Result.ServiceDataMask := TBeaconManufacturerDataHelper.EDDY_UID_NAMESPACE_MASK
else
begin
LTB := TBeaconManufacturerDataHelper.EDDY_UID_NAMESPACE_MASK;
SetLength(LTB, Length(TBeaconManufacturerDataHelper.EDDY_UID_NAMESPACE_MASK) - EDDY_RFU_DATA_LEN);
Result.ServiceDataMask := LTB;
end;
end
else
begin
Move(AGUIDToRegister.Instance, LServiceDataRawData.Value[EDDY_UID_INSTANCE_POS], EDDY_UID_INSTANCE_LEN);
if ARFU then
Result.ServiceDataMask := TBeaconManufacturerDataHelper.EDDY_UID_INSTANCE_MASK
else
begin
LTB := TBeaconManufacturerDataHelper.EDDY_UID_INSTANCE_MASK;
SetLength(LTB, Length(TBeaconManufacturerDataHelper.EDDY_UID_INSTANCE_MASK) - EDDY_RFU_DATA_LEN);
Result.ServiceDataMask := LTB;
end;
end;
Result.ServiceData := LServiceDataRawData;
DoNewBLEScanFilter(TKindofScanFilter.ServiceData, Result);
end;
begin
LiBeaconFiltered := False;
LAltBeaconFiltered := False;
Result := TBluetoothLEScanFilterList.Create;
LBeaconManufacturerDataHelper := TBeaconManufacturerDataHelper.Create(ScanMode);
try
if FBeaconIDToRegisterList <> nil then
for I := 0 to FBeaconIDToRegisterList.Count - 1 do
begin
case FScanMode of
TBeaconScanMode.Standard:
if (FBeaconIDToRegisterList[I].KindofBeacon = TKindofBeacon.iBeacons) or
(FBeaconIDToRegisterList[I].KindofBeacon = TKindofBeacon.iBAltBeacons) then
begin
LBluetoothLEScanFilter := CreateMnfDataBeaconsFilter(FBeaconIDToRegisterList[I]);
Result.Add(LBluetoothLEScanFilter);
end;
TBeaconScanMode.Alternative:
if (FBeaconIDToRegisterList[I].KindofBeacon = TKindofBeacon.AltBeacons) or
(FBeaconIDToRegisterList[I].KindofBeacon = TKindofBeacon.iBAltBeacons) then
begin
LBluetoothLEScanFilter := CreateMnfDataBeaconsFilter(FBeaconIDToRegisterList[I]);
Result.Add(LBluetoothLEScanFilter);
end;
TBeaconScanMode.Eddystone:
if FBeaconIDToRegisterList[I].KindofBeacon = TKindofBeacon.Eddystones then
begin
LBluetoothLEScanFilter := CreateServDataBeaconsFilter(FBeaconIDToRegisterList[I], True);
Result.Add(LBluetoothLEScanFilter);
LBluetoothLEScanFilter := CreateServDataBeaconsFilter(FBeaconIDToRegisterList[I], False);
Result.Add(LBluetoothLEScanFilter);
end;
TBeaconScanMode.Extended:
begin
case FBeaconIDToRegisterList[I].KindofBeacon of
TKindofBeacon.iBeacons:
if (TKindofBeacon.iBeacons in FKindofBeacons) then
begin
LBluetoothLEScanFilter := CreateMnfDataBeaconsFilter(FBeaconIDToRegisterList[I]);
LiBeaconFiltered := True;
Result.Add(LBluetoothLEScanFilter);
end;
TKindofBeacon.AltBeacons:
if (TKindofBeacon.AltBeacons in FKindofBeacons) then
begin
LBluetoothLEScanFilter := CreateMnfDataBeaconsFilter(FBeaconIDToRegisterList[I]);
LAltBeaconFiltered := True;
Result.Add(LBluetoothLEScanFilter);
end;
TKindofBeacon.iBAltBeacons:
begin
if (TKindofBeacon.iBeacons in FKindofBeacons) then
begin
LBeaconIDToRegister := FBeaconIDToRegisterList[I];
LBeaconIDToRegister.KindofBeacon := TKindofBeacon.iBeacons;
LBluetoothLEScanFilter := CreateMnfDataBeaconsFilter(LBeaconIDToRegister);
LAltBeaconFiltered := True;
Result.Add(LBluetoothLEScanFilter);
end;
if (TKindofBeacon.AltBeacons in FKindofBeacons) then
begin
LBeaconIDToRegister := FBeaconIDToRegisterList[I];
LBeaconIDToRegister.KindofBeacon := TKindofBeacon.AltBeacons;
LBluetoothLEScanFilter := CreateMnfDataBeaconsFilter(LBeaconIDToRegister);
LAltBeaconFiltered := True;
Result.Add(LBluetoothLEScanFilter);
end;
end;
TKindofBeacon.Eddystones:
if (TKindofBeacon.Eddystones in FKindofBeacons) then
begin
LBluetoothLEScanFilter := CreateServDataBeaconsFilter(FBeaconIDToRegisterList[I], True);
Result.Add(LBluetoothLEScanFilter);
LBluetoothLEScanFilter := CreateServDataBeaconsFilter(FBeaconIDToRegisterList[I], False);
Result.Add(LBluetoothLEScanFilter);
end;
end;
end;
end;
LBeaconManufacturerDataHelper.RestartHelper;
end;
if (FScanMode = TBeaconScanMode.Extended) then
begin
if (TKindofBeacon.iBeacons in FKindofBeacons) and (not LiBeaconFiltered) then
begin
LBluetoothLEScanFilter := TBluetoothLEScanFilter.Create;
LBluetoothLEScanFilter.ManufacturerSpecificData := TBeaconManufacturerDataHelper.TYPE_OF_BEACON_MASK;
LBluetoothLEScanFilter.ManufacturerSpecificData[BEACON_TYPE_POS] := WordRec(BEACON_ST_TYPE).Hi;
LBluetoothLEScanFilter.ManufacturerSpecificData[BEACON_TYPE_POS + 1] := WordRec(BEACON_ST_TYPE).Lo;
LBluetoothLEScanFilter.ManufacturerSpecificDataMask := TBeaconManufacturerDataHelper.TYPE_OF_BEACON_MASK;
DoNewBLEScanFilter(TKindofScanFilter.ManufacturerData, LBluetoothLEScanFilter);
Result.Add(LBluetoothLEScanFilter);
end;
if (TKindofBeacon.AltBeacons in FKindofBeacons) and (not LAltBeaconFiltered) then
begin
LBluetoothLEScanFilter := TBluetoothLEScanFilter.Create;
LTB := TBeaconManufacturerDataHelper.TYPE_OF_BEACON_MASK;
SetLength(LTB, Length(TBeaconManufacturerDataHelper.TYPE_OF_BEACON_MASK) + 1);
LBluetoothLEScanFilter.ManufacturerSpecificData := LTB;
LBluetoothLEScanFilter.ManufacturerSpecificData[BEACON_TYPE_POS] := WordRec(BEACON_Al_TYPE).Hi;
LBluetoothLEScanFilter.ManufacturerSpecificData[BEACON_TYPE_POS + 1] := WordRec(BEACON_Al_TYPE).Lo;
LTB := TBeaconManufacturerDataHelper.TYPE_OF_BEACON_MASK;
SetLength(LTB, Length(TBeaconManufacturerDataHelper.TYPE_OF_BEACON_MASK) + 1);
LBluetoothLEScanFilter.ManufacturerSpecificDataMask := LTB;
DoNewBLEScanFilter(TKindofScanFilter.ManufacturerData, LBluetoothLEScanFilter);
Result.Add(LBluetoothLEScanFilter);
end;
// ******** General Eddystone-UID Filter ********************
// if (TKindofBeacon.Eddystones in FKindofBeacons) then
// begin
// LBluetoothLEScanFilter := TBluetoothLEScanFilter.Create;
// LBluetoothLEScanFilter.ServiceUUID := EDDYSTONE_SERVICE_UUID;
// LServiceDataRawData.Key := EDDYSTONE_SERVICE_UUID;
// LServiceDataRawData.Value := EDDY_FRAME_UID_MASK;
// LServiceDataRawData.Value[EDDY_FRAMETYPE_POS] := EDDYSTONE_UID;
// LBluetoothLEScanFilter.ServiceData := LServiceDataRawData;
// LBluetoothLEScanFilter.ServiceDataMask := EDDY_FRAME_UID_MASK;
// Result.Add(LBluetoothLEScanFilter);
// end;
end;
if (FScanMode = TBeaconScanMode.Eddystone) or
((FScanMode = TBeaconScanMode.Extended) and (TKindofBeacon.Eddystones in FKindofBeacons)) then
begin
// ******** Eddystone-Service Filter ********************
LBluetoothLEScanFilter := TBluetoothLEScanFilter.Create;
LBluetoothLEScanFilter.ServiceUUID := EDDYSTONE_SERVICE_UUID;
DoNewBLEScanFilter(TKindofScanFilter.Service, LBluetoothLEScanFilter);
Result.Add(LBluetoothLEScanFilter);
// ******** General Eddystone-TLM Filter ********************
// if not Assigned(FOnNewEddystoneURL) then
// begin
// LBluetoothLEScanFilter := TBluetoothLEScanFilter.Create;
// LBluetoothLEScanFilter.ServiceUUID := EDDYSTONE_SERVICE_UUID;
// LServiceDataRawData.Key := EDDYSTONE_SERVICE_UUID;
// LServiceDataRawData.Value := EDDY_FRAME_TLM_MASK;
// LServiceDataRawData.Value[EDDY_FRAMETYPE_POS] := EDDYSTONE_TLM;
// LBluetoothLEScanFilter.ServiceData := LServiceDataRawData;
// LBluetoothLEScanFilter.ServiceDataMask := EDDY_FRAME_TLM_MASK;
// Result.Add(LBluetoothLEScanFilter);
// end;
end;
finally
LBeaconManufacturerDataHelper.Free;
end;
end;
function TCommonBeaconManager.DoStartScan: Boolean;
var
LBluetoothLEScanFilterList: TBluetoothLEScanFilterList;
I: Integer;
begin
Result := False;
if FManager = nil then
begin
FManager := TBluetoothLEManager.Current;
FBeaconListLock := TObject.Create;
end;
DoStopScan;
FManager.OnDiscoverLeDevice := DiscoverLEDevice;
FCommonCalcMode := CalcMode;
if (FScanMode = TBeaconScanMode.Extended) then
Result := True
else
if((FBeaconIDToRegisterList <> nil) and (FBeaconIDToRegisterList.Count > 0)) then
for I := 0 to FBeaconIDToRegisterList.Count - 1 do
case FScanMode of
TBeaconScanMode.Standard:
if (FBeaconIDToRegisterList[I].KindofBeacon = TKindofBeacon.iBeacons) or
(FBeaconIDToRegisterList[I].KindofBeacon = TKindofBeacon.iBAltBeacons) then
begin
Result := True;
Break;
end;
TBeaconScanMode.Alternative:
if (FBeaconIDToRegisterList[I].KindofBeacon = TKindofBeacon.AltBeacons) or
(FBeaconIDToRegisterList[I].KindofBeacon = TKindofBeacon.iBAltBeacons) then
begin
Result := True;
Break;
end;
TBeaconScanMode.Eddystone:
if FBeaconIDToRegisterList[I].KindofBeacon = TKindofBeacon.Eddystones then
begin
Result := True;
Break;
end;
end;
if not Result then
raise EBeaconManagerException.Create(SBeaconNoDeviceRegister);
FThreadIsAlive := TThreadIsAlive.Create(BeAlive);
FCommonBeaconDeathTime := FBeaconDeathTime;
FThreadScanner := TThreadScanner.Create(FManager);
FThreadScanner.FTimeScanning := FScanningTime;
FThreadScanner.FTimeSleeping := FScanningSleepingTime;
FThreadScanner.FAliveEvent := FThreadIsAlive.FEvent;
FThreadIsAlive.FScannerEvent := FThreadScanner.FEvent;
LBluetoothLEScanFilterList := CreateScanFilters;
FThreadScanner.FBluetoothLEScanFilterList := LBluetoothLEScanFilterList;
FThreadIsAlive.Start;
FThreadScanner.Start;
Result := True;
FScanning := Result;
end;
function TCommonBeaconManager.DoStopScan: Boolean;
begin
Result := False;
if (FManager <> nil) then
begin
FManager.OnDiscoverLeDevice := nil;
if (FThreadScanner <> nil) then
begin
FThreadScanner.DisposeOf;
FThreadScanner := nil;
Result := True;
end;
if (FThreadIsAlive <> nil) then
begin
FThreadIsAlive.DisposeOf;
FThreadIsAlive := nil;
end;
FManager.CancelDiscovery;
end;
FScanning := False;
end;
procedure TCommonBeaconManager.SetBeaconType(AValue: Word);
begin
if AValue <> FBeaconType then
FBeaconType := AValue;
end;
procedure TCommonBeaconManager.DoSetKindofBeacons(AValue: TKindofBeacons);
begin
if AValue <> FKindofBeacons then
FBeaconList := nil;
FKindofBeacons := AValue;
end;
procedure TCommonBeaconManager.SetBeaconDeathTime(AValue: Integer);
begin
FBeaconDeathTime := AValue;
end;
procedure TCommonBeaconManager.SetScanningSleepingTime(AValue: Integer);
begin
FScanningSleepingTime := AValue;
end;
procedure TCommonBeaconManager.SetScanningTime(AValue: Integer);
begin
FScanningTime := AValue;
end;
procedure TCommonBeaconManager.SetSPC(AValue: Single);
begin
FSPC := AValue;
end;
destructor TCommonBeaconManager.Destroy;
begin
DoStopScan;
FBeaconIDToRegisterList.Free;
FBeaconListLock.Free;
FManufacturerDataParsers.Free;
inherited;
end;
function BeaconIDToBeaconRegion(const AValue: TBeaconIDToRegister): TBeaconsRegion;
begin
Result.KindofBeacon := AValue.KindofBeacon;
case Result.KindofBeacon of
TKindofBeacon.Eddystones:
if AValue.AllInstances then
Result.EddysUIDRegion.Initialize(AValue.Namespace)
else
Result.EddysUIDRegion.Initialize(AValue.Namespace, AValue.Instance);
TKindofBeacon.iBeacons, TKindofBeacon.AltBeacons, TKindofBeacon.iBAltBeacons:
Result.iBAltBeaconRegion.Initialize(AValue.GUID, AValue.Major, AValue.Minor, AValue.KindofBeacon, AValue.ManufacturerId);
end;
end;
procedure TCommonBeaconManager.DiscoverLEDevice(const Sender: TObject; const ADevice: TBluetoothLEDevice;
Rssi: Integer; const ScanResponse: TScanResponse);
function RssiToProximity(const ABeacon: TCommonBeacon; ARssiValue: Integer; var AProximity: TBeaconProximity): Double;
var
LDistance: Double;
LBeaconListLength: Integer;
LRSSIDiff: Integer;
LDistanceCalculated: Boolean;
begin
if ABeacon.FRBeacon.BeaconInfo.EddystoneBeacon.LastKindofEddystone <> TKindofEddystone.TLM then
begin
LDistanceCalculated := DoBeaconCalcDistance(ABeacon, ABeacon.txPower, ARssiValue, LDistance);
if Not LDistanceCalculated then
LDistanceCalculated := DoBeaconCalcDistance(ABeacon.GetGUID, ABeacon.GetMajor, ABeacon.GetMinor, ABeacon.txPower,
ARssiValue, LDistance);
if Not LDistanceCalculated then
begin
if FCommonCalcMode = TBeaconCalcMode.Stabilized then
begin
if not ABeacon.FRBeacon.RssiMean.IsEmpty then
begin // "Differential Filter", it detects when we are in movement.
LRSSIDiff := Abs(ABeacon.FRBeacon.LastMRSSI - ARssiValue);
LBeaconListLength := Length(FBeaconList);
if LBeaconListLength > 0 then
FRssiAccumulatedDiff := ((FRssiAccumulatedDiff / LBeaconListLength) * (LBeaconListLength - 1)) + LRSSIDiff / LBeaconListLength;
end;
ARssiValue := ABeacon.FRBeacon.RssiMean.AddGetValue(ARssiValue, FRssiAccumulatedDiff >= DIFFERENTIAL_FILTER_BOUNDARY);
end;
ABeacon.FRBeacon.LastMRSSI := ARssiValue;
LDistance := System.Math.RoundTo(FManager.RssiToDistance(ARssiValue, ABeacon.GettxPower, SPC), DISTANCE_DECIMALS);
end;
Result := LDistance;
if Result < PROXIMITY_IMMEDIATE then
AProximity := TBeaconProximity(Immediate)
else
if Result < PROXIMITY_NEAR then
AProximity := TBeaconProximity(Near)
else
if Result < PROXIMITY_FAR then
AProximity := TBeaconProximity(Far)
else
AProximity := TBeaconProximity(Away);
end
else
Result := ABeacon.FRBeacon.Distance;
end;
function BelongsToRegion(const ARcCommonBeacon: TRcCommonBeacon; var LRegionID: Integer): Boolean;
var
LNamespace: TNamespace;
LInstance: TInstance;
LScannable: Boolean;
LKindofBeaconInRegisterList: Boolean;
begin
LRegionID := 0;
Result := False;
LKindofBeaconInRegisterList := False;
if FBeaconIDToRegisterList <> nil then
while LRegionID < FBeaconIDToRegisterList.Count do
begin
LScannable := False;
case FBeaconIDToRegisterList[LRegionID].KindofBeacon of
TKindofBeacon.iBeacons:
begin
if (TKindofBeacon.iBeacons = ARcCommonBeacon.BeaconInfo.KindofBeacon) then
if (ScanMode = TBeaconScanMode.Standard) or ((ScanMode = TBeaconScanMode.Extended) and
((TKindofBeacon.iBeacons in FKindofBeacons) or (TKindofBeacon.iBAltBeacons in FKindofBeacons))) then
begin
LKindofBeaconInRegisterList := True;
LScannable := True;
end;
end;
TKindofBeacon.AltBeacons:
begin
if (TKindofBeacon.AltBeacons = ARcCommonBeacon.BeaconInfo.KindofBeacon) then
if (ScanMode = TBeaconScanMode.Alternative) or ((ScanMode = TBeaconScanMode.Extended) and
((TKindofBeacon.AltBeacons in FKindofBeacons) or (TKindofBeacon.iBAltBeacons in FKindofBeacons))) then
begin
LKindofBeaconInRegisterList := True;
LScannable := True;
end;
end;
TKindofBeacon.iBAltBeacons:
case ScanMode of
TBeaconScanMode.Standard:
if ARcCommonBeacon.BeaconInfo.KindofBeacon = TKindofBeacon.iBeacons then
begin
LKindofBeaconInRegisterList := True;
LScannable := True;
end;
TBeaconScanMode.Alternative:
if ARcCommonBeacon.BeaconInfo.KindofBeacon = TKindofBeacon.AltBeacons then
begin
LKindofBeaconInRegisterList := True;
LScannable := True;
end;
TBeaconScanMode.Extended:
if ((ARcCommonBeacon.BeaconInfo.KindofBeacon = TKindofBeacon.iBeacons) and
(TKindofBeacon.iBeacons in FKindofBeacons))
or ((ARcCommonBeacon.BeaconInfo.KindofBeacon = TKindofBeacon.AltBeacons) and
(TKindofBeacon.AltBeacons in FKindofBeacons)) then
begin
LKindofBeaconInRegisterList := True;
LScannable := True;
end;
end;
TKindofBeacon.Eddystones:
begin
if (TKindofBeacon.Eddystones = ARcCommonBeacon.BeaconInfo.KindofBeacon) and
(TKindofEddystone.UID in ARcCommonBeacon.BeaconInfo.EddystoneBeacon.KindofEddystones) then
if (ScanMode = TBeaconScanMode.Eddystone) or ((ScanMode = TBeaconScanMode.Extended) and
(TKindofBeacon.Eddystones in FKindofBeacons)) then
begin
LKindofBeaconInRegisterList := True;
LScannable := True;
end;
end;
end;
if LScannable then
if ARcCommonBeacon.BeaconInfo.KindofBeacon = TKindofBeacon.Eddystones then
begin
LNamespace := FBeaconIDToRegisterList[LRegionID].Namespace;
LInstance := FBeaconIDToRegisterList[LRegionID].Instance;
if CompareMem(@ARcCommonBeacon.BeaconInfo.EddystoneBeacon.EddystoneUID.Namespace, @LNamespace, EDDY_UID_NAMESPACE_LEN) then
if FBeaconIDToRegisterList[LRegionID].AllInstances or
CompareMem(@ARcCommonBeacon.BeaconInfo.EddystoneBeacon.EddystoneUID.Instance, @LInstance, EDDY_UID_INSTANCE_LEN) then
begin
Result := True;
Break;
end;
end
else
if FBeaconIDToRegisterList[LRegionID].Guid = ARcCommonBeacon.BeaconInfo.Guid then
begin
if (FBeaconIDToRegisterList[LRegionID].Major = MAJOR_REGION_ALL) then
Result := True
else
if (FBeaconIDToRegisterList[LRegionID].Major = ARcCommonBeacon.BeaconInfo.Major) then
if (FBeaconIDToRegisterList[LRegionID].Minor = MINOR_REGION_ALL) then
Result := True
else
if (FBeaconIDToRegisterList[LRegionID].Minor = ARcCommonBeacon.BeaconInfo.Minor) then
Result := True;
break;
end;
Inc(LRegionID);
end;
if (not Result) and (not LKindofBeaconInRegisterList) and ((FScanMode = TBeaconScanMode.Eddystone) or
(FScanMode = TBeaconScanMode.Extended) and (ARcCommonBeacon.BeaconInfo.KindofBeacon in FKindofBeacons)) then
begin
LRegionID := -1;
Result := True;
end;
end;
function BeaconInList(const ARcCommonBeacon: TRcCommonBeacon; var ListID: Word): Boolean;
var
Handler: IEddystoneBeacon;
begin
Result := False;
ListID := 0;
while ListID < Length(FBeaconList) do
begin
if FBeaconList[ListID].KindofBeacon = ARcCommonBeacon.BeaconInfo.KindofBeacon then
if ARcCommonBeacon.BeaconInfo.KindofBeacon = TKindofBeacon.Eddystones then
begin
if (ARcCommonBeacon.BeaconInfo.EddystoneBeacon.LastKindofEddystone = TKindofEddystone.UID) and
(Supports(FBeaconList[ListID], IEddystoneBeacon, Handler)) and
(TKindofEddystone.UID in Handler.KindofEddystones) then
begin
if FBeaconList[ListID].IsEqualTo(ARcCommonBeacon.BeaconInfo.EddystoneBeacon.EddystoneUID.Namespace,
ARcCommonBeacon.BeaconInfo.EddystoneBeacon.EddystoneUID.Instance) then
begin
Result := True;
Break;
end;
end
else
if FBeaconList[ListID].DeviceIdentifier = ARcCommonBeacon.BeaconInfo.DeviceIdentifier then
begin
Result := True;
Break;
end;
end
else
if FBeaconList[ListID].IsEqualTo(ARcCommonBeacon.BeaconInfo.GUID,
ARcCommonBeacon.BeaconInfo.Major, ARcCommonBeacon.BeaconInfo.Minor) then
begin
Result := True;
Break;
end;
Inc(ListID);
end;
end;
function InitBeacon(const ABeacon: TBeaconInfo): TRcCommonBeacon;
begin
Result.BeaconInfo.GUID := ABeacon.GUID;
Result.BeaconInfo.Major := ABeacon.Major;
Result.BeaconInfo.Minor := ABeacon.Minor;
Result.BeaconInfo.TxPower := ABeacon.TxPower;
Result.BeaconInfo.AdditionalData := ABeacon.AdditionalData;
Result.RssiMean := TMeanCalculator<Integer>.Create(RSSI_MEAN_ITEMS);
Result.BeaconInfo.KindofBeacon := ABeacon.KindofBeacon;
Result.BeaconInfo.EddystoneBeacon := ABeacon.EddystoneBeacon;
Result.BeaconInfo.DeviceIdentifier := ABeacon.DeviceIdentifier;
end;
function GetBeaconData(var ABeaconData: TRcCommonBeacon): Boolean;
var
LBeaconInfo: TBeaconInfo;
LMData: TBytes;
LSData: TServiceDataRawData;
LBeaconType: Word;
I: Integer;
LEddystoneBeacon: TEddystoneBeaconInfo;
begin
Result := False;
LMData := ADevice.ScannedAdvertiseData.ManufacturerSpecificData;
LSData.Key := TGUID.Empty;
if (FScanMode <> TBeaconScanMode.Eddystone) then
begin
if Length(LMData) > 0 then
begin
LBeaconInfo.EddystoneBeacon.EddystoneUID.Namespace := EDDY_NAMESPACE_MASK;
LBeaconInfo.EddystoneBeacon.EddystoneUID.Instance := EDDY_INSTANCE_MASK;
DoParseManufacturerData(LMData, LBeaconInfo, Result);
if (not Result) and (ManufacturerDataParsers <> nil) and (ManufacturerDataParsers.Parse(LMData, LBeaconInfo)) then
Result := True;
end;
if (not Result) and (Length(LMData) >= STANDARD_DATA_LENGTH) then
begin
LBeaconType := Swap(PWord(@LMData[TStandardBeaconParser.BEACON_TYPE_POSITION])^);
if (FScanMode = TBeaconScanMode.Extended) then
begin
if (LBeaconType = BEACON_ST_TYPE) then
Result := TStandardBeaconParser.Parse(LMData, LBeaconInfo)
else
if (LBeaconType = BEACON_AL_TYPE) then
Result := TAlternativeBeaconParser.Parse(LMdata, LBeaconInfo);
end
else
if (LBeaconType = FBeaconType) then
if (FScanMode = TBeaconScanMode.Standard) then
Result := TStandardBeaconParser.Parse(LMData, LBeaconInfo)
else
if (FScanMode = TBeaconScanMode.Alternative) then
Result := TAlternativeBeaconParser.Parse(LMdata, LBeaconInfo);
end;
end;
if (not Result) and ((FScanMode = TBeaconScanMode.Eddystone) or
((FScanMode = TBeaconScanMode.Extended) and (TKindofBeacon.Eddystones in FKindofBeacons))) then
begin
if (Length(ADevice.ScannedAdvertiseData.ServiceData) > 0) then
begin
LSData := ADevice.ScannedAdvertiseData.ServiceData[0];
DoParseServiceData(LSData, LBeaconInfo, Result);
// if (not Result) and (ServicesDataParsers <> nil) and (ServicesDataParsers.Parse(LSData, LBeaconInfo)) then
// Result := True;
end;
if (not Result) and (LSData.key = EDDYSTONE_SERVICE_UUID) then
begin
LBeaconInfo.GUID := TGUID.Empty;
LBeaconInfo.Major := 0;
LBeaconInfo.Minor := 0;
LBeaconInfo.BeaconType := 0;
LBeaconInfo.KindofBeacon := TKindofBeacon.Eddystones;
if (Length(LSData.Value) > 0) then
case LSData.Value[EDDY_FRAMETYPE_POS] of
EDDYSTONE_UID:
begin
if Length(LSData.Value) >= (EDDY_UID_LEN - EDDY_RFU_DATA_LEN) then
begin
LBeaconInfo.TxPower := ShortInt(LSData.Value[EDDY_TX_POS] - EDDY_SIGNAL_LOSS_METER);
Move(LSData.Value[EDDY_UID_NAMESPACE_POS], LEddystoneBeacon.EddystoneUID.Namespace[0], EDDY_UID_NAMESPACE_LEN);
Move(LSData.Value[EDDY_UID_INSTANCE_POS], LEddystoneBeacon.EddystoneUID.Instance[0], EDDY_UID_INSTANCE_LEN);
if Length(LSData.Value) = (EDDY_UID_LEN) then
begin
SetLength(LEddystoneBeacon.AdditionalData,word.Size);
LEddystoneBeacon.AdditionalData[0] := Swap(PWord(@LSData.Value[EDDY_RFU_DATA_POS])^);
end;
LEddystoneBeacon.KindofEddystones := [TKindofEddystone.UID];
LEddystoneBeacon.LastKindofEddystone := TKindofEddystone.UID;
LBeaconInfo.EddystoneBeacon := LEddystoneBeacon;
Result := True;
end;
end;
EDDYSTONE_URL:
begin
if Length(LSData.Value) >= EDDY_MIN_URL_LEN then
begin
LBeaconInfo.TxPower := ShortInt(LSData.Value[EDDY_TX_POS] - EDDY_SIGNAL_LOSS_METER);
if (Length(LSData.Value) - EDDY_MIN_URL_LEN) > 0 then
begin
I := Length(LSData.Value) - EDDY_URL_SCHEME_POS;
SetLength(LEddystoneBeacon.EddystoneURL.EncodedURL, I);
Move(LSData.Value[EDDY_URL_SCHEME_POS], LEddystoneBeacon.EddystoneURL.EncodedURL[0], I);
end;
end;
LEddystoneBeacon.EddystoneURL.URL := LEddystoneBeacon.EddystoneURL.URLToString;
LEddystoneBeacon.KindofEddystones := [TKindofEddystone.URL];
LEddystoneBeacon.LastKindofEddystone := TKindofEddystone.URL;
LBeaconInfo.EddystoneBeacon := LEddystoneBeacon;
Result := True;
end;
EDDYSTONE_TLM:
begin
if Length(LSData.Value) = (EDDY_TLM_LEN) then
begin
Move(LSData.Value[EDDY_TLM_VERSION_POS], LEddystoneBeacon.EddystoneTLM.EncodedTLM[0], EDDY_TLM_LEN - EDDY_TLM_VERSION_POS);
LEddystoneBeacon.EddystoneTLM.BattVoltage := Swap(PWord(@LEddystoneBeacon.EddystoneTLM.EncodedTLM[EDDY_TLM_BATTVOLTAGE_POS - EDDY_TLM_VERSION_POS])^);
LEddystoneBeacon.EddystoneTLM.BeaconTemp := Swap(PWord(@LEddystoneBeacon.EddystoneTLM.EncodedTLM[EDDY_TLM_BEACONTEMP_POS - EDDY_TLM_VERSION_POS])^);
LEddystoneBeacon.EddystoneTLM.AdvPDUCount := (Swap(PWord(@LEddystoneBeacon.EddystoneTLM.EncodedTLM[EDDY_TLM_ADVPDUCOUNT_POS - EDDY_TLM_VERSION_POS])^) shl 16) or
(Swap(PWord(@LEddystoneBeacon.EddystoneTLM.EncodedTLM[EDDY_TLM_ADVPDUCOUNT_POS + (2 - EDDY_TLM_VERSION_POS)])^));
LEddystoneBeacon.EddystoneTLM.TimeSincePowerOn := (Swap(PWord(@LEddystoneBeacon.EddystoneTLM.EncodedTLM[EDDY_TLM_TIMESINCEPOWERON_POS - EDDY_TLM_VERSION_POS])^) shl 16) or
(Swap(PWord(@LEddystoneBeacon.EddystoneTLM.EncodedTLM[EDDY_TLM_TIMESINCEPOWERON_POS + (2 - EDDY_TLM_VERSION_POS)])^));
LEddystoneBeacon.KindofEddystones := [TKindofEddystone.TLM];
LEddystoneBeacon.LastKindofEddystone := TKindofEddystone.TLM;
LBeaconInfo.EddystoneBeacon := LEddystoneBeacon;
Result := True;
end;
end;
end;
end;
end;
if Result then
begin
LBeaconInfo.DeviceIdentifier := ADevice.Identifier;
ABeaconData := InitBeacon(LBeaconInfo);
end;
end;
procedure CheckBeaconData(var ABeaconData: TRcCommonBeacon);
var
LTXPower: ShortInt;
LCheckTxPower: Boolean;
begin
case ABeaconData.BeaconInfo.KindofBeacon of
Eddystones:
LCheckTxPower := (UID in ABeaconData.BeaconInfo.EddystoneBeacon.KindofEddystones)
or (URL in ABeaconData.BeaconInfo.EddystoneBeacon.KindofEddystones);
else
LCheckTxPower := True;
end;
if LCheckTxPower then
begin
if ABeaconData.BeaconInfo.TxPower > -EDDY_SIGNAL_LOSS_METER then
begin
LTXPower := ABeaconData.BeaconInfo.TxPower;
ABeaconData.BeaconInfo.TxPower := -EDDY_SIGNAL_LOSS_METER;
DoBeaconError(TBeaconError.IncorrectTxPower, Format(SIncorrectTxPower,[LTXPower]), ABeaconData.BeaconInfo);
end;
end;
end;
var
ListID: Word;
LRcCommonBeacon: TRcCommonBeacon;
LEddystoneBeaconInfo: TEddystoneBeaconInfo;
LNewEddystoneBeaconInfo: TEddystoneBeaconInfo;
LRegion: TBeaconIDToRegister;
LBeacon: TCommonBeacon;
LIBeacon: IBeacon;
LRaiseProximityEvent: Boolean;
LRssi: Integer;
LDistance: Double;
LProximity: TBeaconProximity;
LRegionID: Integer;
LMData: TBytes;
LNewEddyURL: Boolean;
LNewEddyTLM: Boolean;
Handler: IEddystoneBeacon;
begin
LNewEddyURL := False;
LNewEddyTLM := False;
LBeacon := nil;
LMData := ADevice.ScannedAdvertiseData.ManufacturerSpecificData;
if GetBeaconData(LRcCommonBeacon) then
begin
CheckBeaconData(LRcCommonBeacon);
TMonitor.Enter(FBeaconListLock);
try
if BelongsToRegion(LRcCommonBeacon, LRegionID) then
if BeaconInList(LRcCommonBeacon, ListID) then
begin
LBeacon := (FBeaconList[ListID] as TCommonBeacon);
LRssi := Rssi;
LDistance := RssiToProximity(LBeacon, LRssi, LProximity);
if LProximity = LBeacon.Proximity then
LRaiseProximityEvent := False
else
LRaiseProximityEvent:= True;
TMonitor.Enter(LBeacon);
try
LBeacon.Rssi := LRssi;
LBeacon.Distance := LDistance;
LBeacon.Proximity := LProximity;
LBeacon.TimeAlive := Now;
if (LBeacon.GetKindofBeacon = TKindofBeacon.Eddystones) and (Supports(LBeacon, IEddystoneBeacon, Handler)) then
begin
LEddystoneBeaconInfo := TEddystoneBeacon(Handler).GetEddystoneBeacon;
LNewEddystoneBeaconInfo := LRcCommonBeacon.BeaconInfo.EddystoneBeacon;
case LNewEddystoneBeaconInfo.LastKindofEddystone of
TKindofEddystone.URL:
if LEddystoneBeaconInfo.EddystoneURL.URL <> LNewEddystoneBeaconInfo.EddystoneURL.URL then
begin
LEddystoneBeaconInfo.EddystoneURL := LNewEddystoneBeaconInfo.EddystoneURL;
LNewEddyURL := True
end;
TKindofEddystone.UID: LEddystoneBeaconInfo.EddystoneUID := LNewEddystoneBeaconInfo.EddystoneUID;
TKindofEddystone.TLM:
begin
LEddystoneBeaconInfo.EddystoneTLM := LNewEddystoneBeaconInfo.EddystoneTLM;
LNewEddyTLM := True;
end;
end;
LEddystoneBeaconInfo.KindofEddystones := LEddystoneBeaconInfo.KindofEddystones +
[LNewEddystoneBeaconInfo.LastKindofEddystone];
TEddystoneBeacon(Handler).SetEddystoneBeacon(LEddystoneBeaconInfo);
end;
finally
TMonitor.Exit(LBeacon);
end;
if LRaiseProximityEvent then
DoBeaconChangedProximity(LBeacon, TBeaconProximity(LProximity));
end
else
begin
LRcCommonBeacon.Rssi := Rssi;
case LRcCommonBeacon.BeaconInfo.KindofBeacon of
TKindofBeacon.iBeacons: LIBeacon := TiBeacon.create(LRcCommonBeacon);
TKindofBeacon.AltBeacons: LIBeacon := TAltBeacon.create(LRcCommonBeacon);
TKindofBeacon.Eddystones:
begin
LIBeacon := TEddystoneBeacon.create(LRcCommonBeacon);
if LRcCommonBeacon.BeaconInfo.EddystoneBeacon.LastKindofEddystone = TKindofEddystone.URL then
LNewEddyURL := True
else
if LRcCommonBeacon.BeaconInfo.EddystoneBeacon.LastKindofEddystone = TKindofEddystone.TLM then
LNewEddyTLM := True;
end;
end;
LBeacon := LIBeacon as TCommonBeacon;
LBeacon.FregionID := LRegionID;
LBeacon.FIsAlive := True;
setLength(FBeaconList, length(FBeaconList) + 1);
FBeaconList[length(FBeaconList) - 1] := LIBeacon;
LBeacon.Distance := RssiToProximity(LBeacon, Rssi, LBeacon.FRBeacon.Proximity);
if LRegionID > -1 then
begin
LRegion := FBeaconIDToRegisterList[LRegionID];
if LRegion.BeaconsInRegion = 0 then
begin
DoBeaconsRegionEnter(BeaconIDToBeaconRegion(LRegion));
case LRegion.KindofBeacon of
iBeacons, AltBeacons, iBAltBeacons:
DoRegionEnter(LRegion.GUID, LRegion.Major, LRegion.Minor);
end;
end;
Inc(LRegion.BeaconsInRegion);
FBeaconIDToRegisterList[LRegionID] := LRegion;
end;
DoBeaconEnter(LIBeacon, FBeaconList);
end;
if LNewEddyURL and (LBeacon <> nil) then
DoNewEddystoneURL(LBeacon, LBeacon.FRBeacon.BeaconInfo.EddystoneBeacon.EddystoneURL);
if LNewEddyTLM and (LBeacon <> nil) then
DoNewEddystoneTLM(LBeacon, LBeacon.FRBeacon.BeaconInfo.EddystoneBeacon.EddystoneTLM);
finally
TMonitor.Exit(FBeaconListLock);
end;
end;
end;
procedure TCommonBeaconManager.BeAlive(const Sender: TObject);
var
ListId: Word;
LBLength: Word;
LTailElements: Word;
LBeacon: TCommonBeacon;
LIBeacon: IBeacon;
LBeaconIDToRegister: TBeaconIDToRegister;
SEC: Integer;
begin
ListId := 0;
if FBeaconList <> nil then
begin
TMonitor.Enter(FBeaconListLock);
try
LBLength := Length(FBeaconList);
while ListId < LBLength do
begin
LIBeacon := FBeaconList[ListId];
LBeacon := LiBeacon as TCommonBeacon;
SEC := SecondsBetween(now, LBeacon.TimeAlive);
if SEC > FCommonBeaconDeathTime then
begin
TMonitor.Enter(LBeacon);
try
LTailElements := LBLength - (ListId + 1);
FBeaconList[ListId] := nil;
if LTailElements > 0 then
Move(FBeaconList[ListId + 1], FBeaconList[ListId], SizeOf(IBeacon) * LTailElements);
Initialize(FBeaconList[LBLength - 1]);
SetLength(FBeaconList, LBLength - 1);
LBLength := Length(FBeaconList);
if LBeacon.RegionID > -1 then
begin
LBeaconIDToRegister := FBeaconIDToRegisterList[LBeacon.RegionID];
Dec(LBeaconIDToRegister.BeaconsInRegion);
if LBeaconIDToRegister.BeaconsInRegion = 0 then
begin
DoBeaconsRegionExit(BeaconIDToBeaconRegion(LBeaconIDToRegister));
case LBeaconIDToRegister.KindofBeacon of
iBeacons, AltBeacons, iBAltBeacons:
DoRegionExit(LBeaconIDToRegister.GUID, LBeaconIDToRegister.Major, LBeaconIDToRegister.Minor);
end;
end;
FBeaconIDToRegisterList[LBeacon.RegionID] := LBeaconIDToRegister;
end;
LBeacon.FIsAlive := False;
finally
TMonitor.Exit(LBeacon);
end;
DoBeaconExit(LIBeacon, FBeaconList);
end;
Inc(ListId);
end;
finally
TMonitor.Exit(FBeaconListLock);
end;
end;
end;
constructor TCommonBeaconManager.Create(AMode: TBeaconScanMode);
begin
if FScanMode <> AMode then
FBeaconList := nil;
FScanMode := AMode;
case AMode of
TBeaconScanMode.Standard: FBeaconType := BEACON_ST_TYPE;
TBeaconScanMode.Alternative: FBeaconType := BEACON_AL_TYPE;
end;
FRssiAccumulatedDiff := ACCUMMULATE_DIFF_START_VALUE;
FBeaconDeathTime := KBEACONDEATHTIME;
FScanningTime := SCANNING_TIME;
FScanningSleepingTime := SCANNING_SLEEPINGTIME;
FSPC := SIGNAL_PROPAGATION_CONSTANT;
FCalcMode := TBeaconCalcMode.Stabilized;
FManufacturerDataParsers := TBeaconManufacturerParsers.Create;
end;
{TCommonBeaconManager.TThreadScanner}
constructor TCommonBeaconManager.TThreadScanner.Create(const ATManager: TBluetoothLEManager);
begin
inherited Create(True);
FTmanager := ATManager;
FEvent := TEvent.Create;
end;
destructor TCommonBeaconManager.TThreadScanner.Destroy;
var
I: Integer;
begin
Terminate;
FEvent.SetEvent;
inherited;
FEvent.Free;
for I := 0 to FBluetoothLEScanFilterList.Count - 1 do
FBluetoothLEScanFilterList[I].DisposeOf;
FBluetoothLEScanFilterList.Free;
FAliveEvent := nil;
end;
procedure TCommonBeaconManager.TThreadScanner.Execute;
var
LRefresh: Boolean;
begin
LRefresh := True;
while not Terminated do
begin
if FEvent.WaitFor(FTimeSleeping) = TWaitResult.wrTimeout then
begin
try
FTManager.StartDiscoveryRaw(FBluetoothLEScanFilterList, LRefresh);
LRefresh := False;
except
FAliveEvent.SetEvent;
if Assigned(System.Classes.ApplicationHandleException) then
System.Classes.ApplicationHandleException(Self)
else
raise;
Terminate
end;
end
else
begin
FTManager.CancelDiscovery;
Terminate;
end;
if not Terminated then
if FEvent.WaitFor(FTimeScanning) = TWaitResult.wrTimeout then
begin
try
FTManager.CancelDiscovery;
except
FAliveEvent.SetEvent;
if Assigned(System.Classes.ApplicationHandleException) then
System.Classes.ApplicationHandleException(Self)
else
raise;
Terminate
end;
end
else
begin
FTManager.CancelDiscovery;
Terminate;
end;
end;
end;
{TCommonBeaconManager.TThreadIsAlive}
constructor TCommonBeaconManager.TThreadIsAlive.Create(ABeAlive: TBeAlive);
begin
inherited Create(True);
FBeAlive := ABeAlive;
FEvent := TEvent.Create;
end;
destructor TCommonBeaconManager.TThreadIsAlive.Destroy;
begin
Terminate;
FEvent.SetEvent;
inherited;
FEvent.Free;
FScannerEvent := nil;
end;
procedure TCommonBeaconManager.TThreadIsAlive.Execute;
begin
while not Terminated do
if FEvent.WaitFor(FChekingTime) = TWaitResult.wrTimeout then
begin
try
FBeAlive(nil);
except
FScannerEvent.SetEvent;
if Assigned(System.Classes.ApplicationHandleException) then
System.Classes.ApplicationHandleException(Self)
else
raise;
Terminate;
end;
end
else
Terminate;
end;
{ TStandardBeaconParser }
class function TStandardBeaconParser.Parse(const AData: TBytes; var BeaconInfo: TBeaconInfo): Boolean;
begin
Result := False;
if Length(AData) = STANDARD_DATA_LENGTH then
begin
BeaconInfo.KindofBeacon := TKindofBeacon.iBeacons;
BeaconInfo.GUID := TGUID.Create(AData[BEACON_GUID_POSITION], TEndian.Big);
WordRec(BeaconInfo.BeaconType).Hi := Adata[BEACON_TYPE_POSITION];
WordRec(BeaconInfo.BeaconType).Lo := Adata[BEACON_TYPE_POSITION + 1];
WordRec(BeaconInfo.Major).Hi := Adata[BEACON_MAJOR_POSITION];
WordRec(BeaconInfo.Major).Lo := Adata[BEACON_MAJOR_POSITION + 1];
WordRec(BeaconInfo.Minor).Hi := Adata[BEACON_MINOR_POSITION];
WordRec(BeaconInfo.Minor).Lo := Adata[BEACON_MINOR_POSITION + 1];
BeaconInfo.TxPower := ShortInt(AData[Length(AData) - 1]);
Result := True;
end;
end;
{ TAlternativeBeaconParser }
class function TAlternativeBeaconParser.Parse(const AData: TBytes; var BeaconInfo: TBeaconInfo): Boolean;
begin
Result := False;
if Length(AData) = ALTERNATIVE_DATA_LENGTH then
begin
BeaconInfo.KindofBeacon := TKindofBeacon.AltBeacons;
BeaconInfo.GUID := TGUID.Create(AData[BEACON_GUID_POSITION], TEndian.Big);
WordRec(BeaconInfo.BeaconType).Hi := Adata[BEACON_TYPE_POSITION];
WordRec(BeaconInfo.BeaconType).Lo := Adata[BEACON_TYPE_POSITION + 1];
WordRec(BeaconInfo.Major).Hi := Adata[BEACON_MAJOR_POSITION];
WordRec(BeaconInfo.Major).Lo := Adata[BEACON_MAJOR_POSITION + 1];
WordRec(BeaconInfo.Minor).Hi := Adata[BEACON_MINOR_POSITION];
WordRec(BeaconInfo.Minor).Lo := Adata[BEACON_MINOR_POSITION + 1];
BeaconInfo.TxPower := ShortInt(AData[Length(AData) - 2]);
BeaconInfo.AdditionalData := AData[Length(AData) - 1];
Result := True;
end;
end;
{ TPlatformBeaconManager }
class function TPlatformBeaconManager.GetInstance(AMode: TBeaconScanMode): TBeaconManager;
begin
Result := TCommonBeaconManager.GetInstance(AMode);
end;
{ TEddystoneBeacon }
function TEddystoneBeacon.GetEddystoneBeacon: TEddystoneBeaconInfo;
begin
Result := FRBeacon.BeaconInfo.EddystoneBeacon;
end;
procedure TEddystoneBeacon.SetEddystoneBeacon(const AValue: TEddystoneBeaconInfo);
begin
FRBeacon.BeaconInfo.EddystoneBeacon := AValue;
end;
function TEddystoneBeacon.GetEddystoneTLM: TEddystoneTLM;
begin
Result := FRBeacon.BeaconInfo.EddystoneBeacon.EddystoneTLM;
end;
function TEddystoneBeacon.GetEddystoneUID: TEddystoneUID;
begin
Result := FRBeacon.BeaconInfo.EddystoneBeacon.EddystoneUID;
end;
function TEddystoneBeacon.GetEddystoneURL: TEddystoneURL;
begin
Result := FRBeacon.BeaconInfo.EddystoneBeacon.EddystoneURL;
end;
function TEddystoneBeacon.GetKindofEddystones: TKindofEddystones;
begin
Result := FRBeacon.BeaconInfo.EddystoneBeacon.KindofEddystones;
end;
end.
|
unit uPrincipal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, uCliente, uListaCliente;
type
TForm1 = class(TForm)
btnAdicionar: TButton;
btnRemover: TButton;
btnContar: TButton;
edtIDCliente: TEdit;
edtNome: TEdit;
edtCNPJ: TEdit;
procedure FormCreate(Sender: TObject);
procedure btnAdicionarClick(Sender: TObject);
procedure btnRemoverClick(Sender: TObject);
procedure btnContarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
auxListaCliente: TListaCliente;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
auxListaCliente := TListaCliente.Create;
end;
procedure TForm1.btnAdicionarClick(Sender: TObject);
var
auxCliente: TCliente;
begin
auxCliente := TCliente.Create;
with auxCliente do
begin
IdCliente:= strtoint(edtIDCliente.Text);
Nome:= edtNome.Text;
CNPJ:= edtCNPJ.Text;
end;
auxListaCliente.Adcionar(auxCliente);
end;
procedure TForm1.btnRemoverClick(Sender: TObject);
var
auxIdCliente: string;
begin
if InputQuery('Remocao de Cliente','Digite o codigo do cliente',auxIdCliente) then
begin
auxListaCliente.Remover(strtoint(auxIdCliente));
end;
end;
procedure TForm1.btnContarClick(Sender: TObject);
begin
showmessage('Total de Clientes na Lista: '+inttostr(auxListaCliente.Count));
end;
end.
|
unit clsTUsuarioDTO;
{$M+}
{$TYPEINFO ON}
interface
type
TUsuarioDTO = class
private
FNasc: TDateTime;
FNome: String;
FID: Integer;
FEmail: String;
FAlterado: Boolean;
procedure SetNasc(const Value: TDateTime);
procedure SetNome(const Value: String);
procedure SetID(const Value: Integer);
procedure SetEmail(const Value: String);
function GetAlterado: Boolean;
procedure SetAlterado(const Value: Boolean);
public
constructor Create;
published
property ID: Integer read FID write SetID;
property Nome: String read FNome write SetNome;
property Nasc: TDateTime read FNasc write SetNasc;
property Email: String read FEmail write SetEmail;
property Alterado: Boolean read GetAlterado write SetAlterado;
end;
implementation
{ TUsuarioDTO }
constructor TUsuarioDTO.Create;
begin
Self.FAlterado := False;
end;
function TUsuarioDTO.GetAlterado: Boolean;
begin
Result := Self.FAlterado;
end;
procedure TUsuarioDTO.SetAlterado(const Value: Boolean);
begin
Self.FAlterado := Value;
end;
procedure TUsuarioDTO.SetEmail(const Value: String);
begin
if Self.FEmail <> Value then
Self.FAlterado := True;
Self.FEmail := Value;
end;
procedure TUsuarioDTO.SetID(const Value: Integer);
begin
if Self.FID <> Value then
Self.FAlterado := True;
Self.FID := Value;
end;
procedure TUsuarioDTO.SetNasc(const Value: TDateTime);
begin
if Self.FNasc <> Value then
Self.FAlterado := True;
Self.FNasc := Value;
end;
procedure TUsuarioDTO.SetNome(const Value: String);
begin
if Self.FNome <> Value then
Self.FAlterado := True;
Self.FNome := Value;
end;
end.
|
unit fEncntKEEP;
//Modifed: 7/26/99
//By: Robert Bott
//Location: ISL
//Description of Mod:
// Moved asignment of historical visit category from the cboNewVisitChange event
// to the ckbHistoricalClick event.
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ORCtrls, ORDtTm, ORFn, ExtCtrls, ComCtrls, ORDtTmRng, fAutoSz, rOptions, fBase508Form;
type
TfrmEncounter = class(TfrmBase508Form)
cboPtProvider: TORComboBox;
lblProvider: TLabel;
cmdOK: TButton;
cmdCancel: TButton;
lblLocation: TLabel;
txtLocation: TCaptionEdit;
pgeVisit: TPageControl;
tabClinic: TTabSheet;
lblClinic: TLabel;
lblDateRange: TLabel;
lstClinic: TORListBox;
tabAdmit: TTabSheet;
lblAdmit: TLabel;
lstAdmit: TORListBox;
tabNewVisit: TTabSheet;
lblVisitDate: TLabel;
lblNewVisit: TLabel;
calVisitDate: TORDateBox;
ckbHistorical: TORCheckBox;
cboNewVisit: TORComboBox;
dlgDateRange: TORDateRangeDlg;
cmdDateRange: TButton;
lblInstruct: TLabel;
procedure FormCreate(Sender: TObject);
procedure pgeVisitChange(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure cboNewVisitNeedData(Sender: TObject; const StartFrom: String;
Direction, InsertAt: Integer);
procedure calVisitDateChange(Sender: TObject);
procedure cboNewVisitChange(Sender: TObject);
procedure calVisitDateExit(Sender: TObject);
procedure cboPtProviderNeedData(Sender: TObject;
const StartFrom: String; Direction, InsertAt: Integer);
procedure ckbHistoricalClick(Sender: TObject);
procedure cmdDateRangeClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lstAdmitChange(Sender: TObject);
procedure lstClinicChange(Sender: TObject);
private
CLINIC_TXT : String;
FFilter: Int64;
FPCDate: TFMDateTime;
FProvider: Int64;
FLocation: Integer;
FLocationName: string;
FDateTime: TFMDateTime;
FVisitCategory: Char;
FStandAlone: Boolean;
FFromSelf: Boolean;
FFromDate: TFMDateTime;
FThruDate: TFMDateTIme;
FEncFutureLimit: string;
FFromCreate: Boolean;
FOldHintEvent: TShowHintEvent;
OKPressed: Boolean;
procedure AppShowHint(var HintStr: string; var CanShow: Boolean;
var HintInfo: THintInfo);
procedure SetVisitCat;
public
{ Public declarations }
end;
procedure UpdateEncounter(PersonFilter: Int64; ADate: TFMDateTime = 0; TIULocation: integer = 0);
procedure UpdateVisit(FontSize: Integer); overload;
procedure UpdateVisit(FontSize: Integer; TIULocation: integer); overload;
implementation
{$R *.DFM}
uses rCore, uCore, uConst, fReview, uPCE, rPCE;
const
TC_MISSING = 'Incomplete Encounter Information';
TX_NO_DATE = 'A valid date/time has not been entered.';
TX_NO_TIME = 'A valid time has not been entered.';
TX_NO_LOC = 'A visit location has not been selected.';
TC_LOCONLY = 'Location for Current Activities';
TX_FUTURE_WARNING = 'You have selected a visit with a date in the future. Are you sure?';
TC_FUTURE_WARNING = 'Visit Is In Future';
var
uTIULocation: integer;
uTIULocationName: string;
procedure UpdateVisit(FontSize: Integer);
begin
UpdateEncounter(NPF_SUPPRESS);
end;
procedure UpdateVisit(FontSize: Integer; TIULocation: integer);
begin
UpdateEncounter(NPF_SUPPRESS, 0, TIULocation);
end;
procedure UpdateEncounter(PersonFilter: Int64; ADate: TFMDateTime = 0; TIULocation: integer = 0);
const
UP_SHIFT = 85;
var
frmEncounter: TfrmEncounter;
CanChange: Boolean;
TimedOut: Boolean;
begin
uTIULocation := TIULocation;
if uTIULocation <> 0 then uTIULocationName := ExternalName(uTIULocation, FN_HOSPITAL_LOCATION);
frmEncounter := TfrmEncounter.Create(Application);
try
TimedOut := False;
ResizeAnchoredFormToFont(frmEncounter);
with frmEncounter do
begin
FFilter := PersonFilter;
FPCDate := ADate;
if PersonFilter = NPF_SUPPRESS then // not prompting for provider
begin
lblProvider.Visible := False;
cboPtProvider.Visible := False;
lblInstruct.Visible := True;
Caption := TC_LOCONLY;
Height := frmEncounter.Height - UP_SHIFT;
end
else // also prompt for provider
begin
// InitLongList must be done AFTER FFilter is set
cboPtProvider.InitLongList(Encounter.ProviderName);
cboPtProvider.SelectByIEN(FProvider);
end;
ShowModal;
if OKPressed then
begin
CanChange := True;
if (PersonFilter <> NPF_SUPPRESS) and
(((Encounter.Provider = User.DUZ) and (FProvider <> User.DUZ)) or
((Encounter.Provider <> User.DUZ) and (FProvider = User.DUZ)))
then CanChange := ReviewChanges(TimedOut);
if CanChange then
begin
if PersonFilter <> NPF_SUPPRESS then Encounter.Provider := FProvider;
Encounter.Location := FLocation;
Encounter.DateTime := FDateTime;
Encounter.VisitCategory := FVisitCategory;
Encounter.StandAlone := FStandAlone;
end;
end;
end;
finally
frmEncounter.Release;
end;
end;
procedure TfrmEncounter.FormCreate(Sender: TObject);
var
ADateFrom, ADateThru: TDateTime;
BDateFrom, BDateThru: Integer;
BDisplayFrom, BDisplayThru: String;
begin
inherited;
FProvider := Encounter.Provider;
FLocation := Encounter.Location;
FLocationName := Encounter.LocationName;
FDateTime := Encounter.DateTime;
FVisitCategory := Encounter.VisitCategory;
FStandAlone := Encounter.StandAlone;
rpcGetEncFutureDays(FEncFutureLimit);
rpcGetRangeForEncs(BDateFrom, BDateThru, False); // Get user's current date range settings.
if BDateFrom > 0 then
BDisplayFrom := 'T-' + IntToStr(BDateFrom)
else
BDisplayFrom := 'T';
if BDateThru > 0 then
BDisplayThru := 'T+' + IntToStr(BDateThru)
else
BDisplayThru := 'T';
lblDateRange.Caption := '(' + BDisplayFrom + ' thru ' + BDisplayThru + ')';
ADateFrom := (FMDateTimeToDateTime(FMToday) - BDateFrom);
ADateThru := (FMDateTimeToDateTime(FMToday) + BDateThru);
FFromDate := DateTimeToFMDateTime(ADateFrom);
FThruDate := DateTimeToFMDateTime(ADateThru) + 0.2359;
FFromCreate := True;
with txtLocation do if Length(FLocationName) > 0 then
begin
Text := FLocationName + ' ';
if (FVisitCategory <> 'H') and (FDateTime <> 0) then
Text := Text + FormatFMDateTime('mmm dd,yy hh:nn', FDateTime);
end
else Text := '< Select a location from the tabs below.... >';
OKPressed := False;
pgeVisit.ActivePage := tabClinic;
pgeVisitChange(Self);
if lstClinic.Items.Count = 0 then
begin
pgeVisit.ActivePage := tabNewVisit;
pgeVisitChange(Self);
end;
ckbHistorical.Hint := 'A historical visit or encounter is a visit that occurred at some time' + CRLF +
'in the past or at some other location (possibly non-VA). Although these' + CRLF +
'are not used for workload credit, they can be used for setting up the' + CRLF +
'PCE reminder maintenance system, or other non-workload-related reasons.';
FOldHintEvent := Application.OnShowHint;
Application.OnShowHint := AppShowHint;
FFromCreate := False;
//JAWS will read the second caption if 2 are displayed, so Combining Labels
CLINIC_TXT := lblClinic.Caption+' ';
lblClinic.Caption := CLINIC_TXT + lblDateRange.Caption;
lblDateRange.Hide;
end;
procedure TfrmEncounter.cboPtProviderNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
begin
inherited;
case FFilter of
NPF_PROVIDER: cboPtProvider.ForDataUse(SubSetOfProviders(StartFrom, Direction));
// NPF_ENCOUNTER: cboPtProvider.ForDataUse(SubSetOfUsersWithClass(StartFrom, Direction, FloatToStr(FPCDate)));
else cboPtProvider.ForDataUse(SubSetOfPersons(StartFrom, Direction));
end;
end;
procedure TfrmEncounter.pgeVisitChange(Sender: TObject);
begin
inherited;
cmdDateRange.Visible := pgeVisit.ActivePage = tabClinic;
if (pgeVisit.ActivePage = tabClinic) and (lstClinic.Items.Count = 0)
then ListApptAll(lstClinic.Items, Patient.DFN, FFromDate, FThruDate);
if (pgeVisit.ActivePage = tabAdmit) and (lstAdmit.Items.Count = 0)
then ListAdmitAll(lstAdmit.Items, Patient.DFN);
if pgeVisit.ActivePage = tabNewVisit then
begin
if cboNewVisit.Items.Count = 0 then
begin
if FVisitCategory <> 'H' then
begin
if uTIULocation <> 0 then
begin
cboNewVisit.InitLongList(uTIULocationName);
cboNewVisit.SelectByIEN(uTIULocation);
end
else
begin
cboNewVisit.InitLongList(FLocationName);
if Encounter.Location <> 0 then cboNewVisit.SelectByIEN(FLocation);
end;
FFromSelf := True;
with calVisitDate do if FDateTime <> 0 then FMDateTime := FDateTime else Text := 'NOW';
FFromSelf := False;
end
else cboNewVisit.InitLongList('');
ckbHistorical.Checked := FVisitCategory = 'E';
end; {if cboNewVisit}
end; {if pgeVisit.ActivePage}
end;
procedure TfrmEncounter.cboNewVisitNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
begin
inherited;
cboNewVisit.ForDataUse(SubSetOfNewLocs(StartFrom, Direction));
end;
procedure TfrmEncounter.cmdDateRangeClick(Sender: TObject);
begin
dlgDateRange.FMDateStart := FFromDate;
dlgDateRange.FMDateStop := FThruDate;
if dlgDateRange.Execute then
begin
FFromDate := dlgDateRange.FMDateStart;
FThruDate := dlgDateRange.FMDateStop + 0.2359;
lblDateRange.Caption := '(' + dlgDateRange.RelativeStart + ' thru '
+ dlgDateRange.RelativeStop + ')';
//label
lblClinic.Caption := CLINIC_TXT + lblDateRange.Caption;
//list
lstClinic.Caption := lblClinic.Caption + ' ' + lblDateRange.Caption;
lstClinic.Items.Clear;
ListApptAll(lstClinic.Items, Patient.DFN, FFromDate, FThruDate);
end;
end;
procedure TfrmEncounter.cboNewVisitChange(Sender: TObject);
begin
inherited;
with cboNewVisit do
begin
FLocation := ItemIEN;
FLocationName := DisplayText[ItemIndex];
FDateTime := calVisitDate.FMDateTime;
SetVisitCat;
with txtLocation do
begin
Text := FLocationName + ' ';
if FDateTime <> 0 then Text := Text + FormatFMDateTime('mmm dd,yy hh:nn', FDateTime);
end;
end;
end;
procedure TfrmEncounter.calVisitDateChange(Sender: TObject);
begin
inherited;
// The FFromSelf was added because without it, a new visit (minus the seconds gets created.
// Setting the text of calVisit caused the text to be re-evaluated & changed the FMDateTime property.
if FFromSelf then Exit;
with cboNewVisit do
begin
FLocation := ItemIEN;
FLocationName := DisplayText[ItemIndex];
FDateTime := calVisitDate.FMDateTime;
SetVisitCat;
txtLocation.Text := FLocationName + ' ' + calVisitDate.Text;
end;
end;
procedure TfrmEncounter.calVisitDateExit(Sender: TObject);
begin
inherited;
with cboNewVisit do if ItemIEN > 0 then
begin
FLocation := ItemIEN;
FLocationName := DisplayText[ItemIndex];
FDateTime := calVisitDate.FMDateTime;
SetVisitCat;
with txtLocation do
begin
Text := FLocationName + ' ';
if FDateTime <> 0 then Text := Text + FormatFMDateTime('mmm dd,yy hh:nn', FDateTime);
end;
end;
end;
procedure TfrmEncounter.cmdOKClick(Sender: TObject);
var
msg: string;
ADate, AMaxDate: TDateTime;
begin
inherited;
msg := '';
if FLocation = 0 then msg := TX_NO_LOC;
if FDateTime <= 0 then msg := msg + CRLF + TX_NO_DATE
else if(pos('.',FloatToStr(FDateTime)) = 0) then msg := msg + CRLF + TX_NO_TIME;
if(msg <> '') then
begin
InfoBox(msg, TC_MISSING, MB_OK);
Exit;
end
else
begin
ADate := FMDateTimeToDateTime(Trunc(FDateTime));
AMaxDate := FMDateTimeToDateTime(FMToday) + StrToIntDef(FEncFutureLimit, 0);
if ADate > AMaxDate then
if InfoBox(TX_FUTURE_WARNING, TC_FUTURE_WARNING, MB_YESNO or MB_ICONQUESTION) = MRNO then exit;
end;
if FFilter <> NPF_SUPPRESS then FProvider := cboPtProvider.ItemIEN;
OKPressed := True;
Close;
end;
procedure TfrmEncounter.cmdCancelClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TfrmEncounter.ckbHistoricalClick(Sender: TObject);
begin
SetVisitCat;
end;
{
procedure TfrmEncounter.cboPtProviderChange(Sender: TObject);
var
txt: string;
AIEN: Int64;
begin
if(FFilter <> NPF_ENCOUNTER) then exit;
AIEN := cboPtProvider.ItemIEN;
if(AIEN <> 0) then
begin
txt := InvalidPCEProviderTxt(AIEN, FPCDate);
if(txt <> '') then
begin
InfoBox(cboPtProvider.text + txt, TX_BAD_PROV, MB_OK);
cboPtProvider.ItemIndex := -1;
end;
end;
end;
}
procedure TfrmEncounter.AppShowHint(var HintStr: string;
var CanShow: Boolean; var HintInfo: THintInfo);
const
HistHintDelay = 30000; // 30 seconds
begin
if (not Assigned(HintInfo.HintControl)) then exit;
if(HintInfo.HintControl = ckbHistorical) then
HintInfo.HideTimeout := HistHintDelay;
if(assigned(FOldHintEvent)) then
FOldHintEvent(HintStr, CanShow, HintInfo);
end;
procedure TfrmEncounter.FormDestroy(Sender: TObject);
begin
//Application.OnShowHint := FOldHintEvent; v22.11f - RV
end;
procedure TfrmEncounter.SetVisitCat;
begin
if ckbHistorical.Checked then
FVisitCategory := 'E'
else
FVisitCategory := GetVisitCat('A', FLocation, Patient.Inpatient);
FStandAlone := (FVisitCategory = 'A');
end;
procedure TfrmEncounter.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Application.OnShowHint := FOldHintEvent;
end;
procedure TfrmEncounter.lstAdmitChange(Sender: TObject);
begin
inherited;
with lstAdmit do
begin
FLocation := StrToIntDef(Piece(Items[ItemIndex], U, 2), 0);
FLocationName := Piece(Items[ItemIndex], U, 3);
FDateTime := MakeFMDateTime(ItemID);
FVisitCategory := 'H';
FStandAlone := False;
txtLocation.Text := FLocationName; // don't show admit date (could confuse user)
end;
end;
procedure TfrmEncounter.lstClinicChange(Sender: TObject);
// V|A;DateTime;LocIEN^DateTime^LocName^Status
begin
inherited;
with lstClinic do
begin
FLocation := StrToIntDef(Piece(ItemID, ';', 3), 0);
FLocationName := Piece(Items[ItemIndex], U, 3);
FDateTime := MakeFMDateTime(Piece(ItemID,';', 2));
FVisitCategory := 'A';
FStandAlone := CharAt(ItemID, 1) = 'V';
with txtLocation do
begin
Text := FLocationName + ' ';
if FDateTime <> 0 then Text := Text + FormatFMDateTime('mmm dd,yy hh:nn', FDateTime);
end;
end;
end;
end.
|
function decimalAbinario(numDec: Integer): Integer;
var numDecAux, numBin, pot10: integer;
begin
numBin := 0;
pot10 := 1;
numDecAux := numDec;
while (numDecAux <> 0) do
begin
numBin := numBin + ((numDecAux mod 2) * pot10);
numDecAux := numDecAux div 2;
pot10 := pot10 * 10;
end;
decimalAbinario := numBin;
end; |
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, SynHighlighterCpp, Forms, Controls, Graphics,
Dialogs, ExtCtrls, StdCtrls, Grids, DBGrids, DbCtrls, ExtDlgs, Spin, ColorBox,
BGRABitmap, BGRABitmapTypes;
type
rect = record
x1, y1, x2, y2: Integer;
end;
profileRow = class
fName: String;
imgX, imgY: Integer; // 実際に読み込まれるタイミングで取得する
r: array of rect;
isUsePre: Boolean;
constructor Create();
end;
{ TForm1 }
TForm1 = class(TForm)
addPicture: TButton;
rectC: TColorBox;
delRect: TButton;
Edit1: TEdit;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
Label17: TLabel;
Label18: TLabel;
Label19: TLabel;
Label20: TLabel;
Label7: TLabel;
arMode1: TRadioButton;
arMode2: TRadioButton;
arMode3: TRadioButton;
RadioGroup1: TRadioGroup;
rowStable: TCheckBox;
rectStable: TCheckBox;
expFNameOnly: TCheckBox;
setRect: TButton;
CheckBox1: TCheckBox;
deletePicture: TButton;
Label12: TLabel;
Label13: TLabel;
Label3: TLabel;
Label8: TLabel;
odPicF: TOpenPictureDialog;
picFNameChange: TButton;
addRect: TButton;
Label10: TLabel;
Label11: TLabel;
cRectPos1: TLabel;
cRectPos2: TLabel;
Label4: TLabel;
Label5: TLabel;
imgFNameShow: TLabel;
Label9: TLabel;
ichimatsu: TImage;
odProf: TOpenDialog;
editRID: TLabel;
profImp: TButton;
profExp: TButton;
imgPre: TButton;
imgNext: TButton;
mainImg: TImage;
Label1: TLabel;
Label2: TLabel;
rectNum: TLabel;
Label6: TLabel;
profFName: TLabel;
Panel1: TPanel;
profileView: TStringGrid;
pfCurrent: TLabel;
sx1: TSpinEdit;
rectA: TSpinEdit;
sy1: TSpinEdit;
sx2: TSpinEdit;
sy2: TSpinEdit;
spProf: TSaveDialog;
rectViewList: TStringGrid;
procedure addPictureClick(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure deletePictureClick(Sender: TObject);
procedure delRectClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure addRectClick(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure imgNextClick(Sender: TObject);
procedure imgPreClick(Sender: TObject);
procedure Label15Click(Sender: TObject);
//procedure mainImgEndDrag(Sender, Target: TObject; X, Y: Integer);
procedure mainImgMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure mainImgMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure mainImgMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure mainImgPaint(Sender: TObject);
//procedure mainImgStartDrag(Sender: TObject; var DragObject: TDragObject);
procedure picFNameChangeClick(Sender: TObject);
procedure profExpClick(Sender: TObject);
procedure profileViewClick(Sender: TObject);
procedure rectViewListClick(Sender: TObject);
procedure setRectClick(Sender: TObject);
private
{ private declarations }
picExtRate: Double;
picXYDiv: Double; // 画像サイズのX/Y
picMovingF: Boolean;
profData: array of profileRow; // 列データ
// 画像のマウス関連
isLC, isRC: Boolean;
crX, crY, clX, clY: Integer;
// 読み込まれた画像本体
bgraIchimatsu, bgraMain, cv: TBGRACustomBitmap;
public
{ public declarations }
procedure setpfViewID(); // imageNumに含まれる画像の増減時にIDを設定しなおす(要らないかも)
procedure selectPicture(); // 画像が選びなおされた時の処理
procedure selectRect(); // 矩形が選びなおされた時の処理
procedure addRectMain(x1, y1, x2, y2: Integer);
// データの配列番号基準の引数をとる
procedure updatePFListView(arg: Integer); // プロファイルの列番号を指定して該当位置リストの内容を更新
procedure updateRectListView(arg: Integer); // 矩形リストの位置番号を指定して(略)
procedure updateRectAll(); // 矩形リストをクリアして一括書き換え。プロファイルの画像を変えるたびに。
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
// コンストラクタ
procedure TForm1.FormCreate(Sender: TObject);
begin
Width:=1280;
Height:=720;
isLC := False;
isRC := False;
picExtRate := 1;
picMovingF:=False;
SetLength(profData, 0);
bgraIchimatsu := TBGRABitmap.Create(ichimatsu.Picture.Bitmap);
bgraMain := TBGRABitmap.Create(ichimatsu.Picture.Bitmap);
cv := TBGRABitmap.Create(bgraMain.Bitmap.Width, bgraMain.Bitmap.Height, BGRA(0,0,0,0));
end;
// プロファイルの列番号を指定して該当位置リストの内容を更新
procedure TForm1.updatePFListView(arg: Integer);
begin
profileView.Cells[0, arg + 1] := IntToStr(arg);
profileView.Cells[1, arg + 1] := ExtractFileName(profData[arg].fName);
profileView.Cells[2, arg + 1] := IntToStr(Length(profData[arg].r));
if profData[arg].isUsePre then
begin
profileView.Cells[3, arg + 1] := 'Use';
end
else
begin
profileView.Cells[3, arg + 1] := 'Unuse';
end;
profileView.Cells[4, arg + 1] := IntToStr(profData[arg].imgX) + ' ,' + IntToStr(profData[arg].imgY);
end;
// 矩形リストの位置番号を指定して(略)
procedure TForm1.updateRectListView(arg: Integer);
begin
rectViewList.Cells[0, arg + 1] := IntToStr(arg);
with profData[profileView.Row - 1] do
begin
rectViewList.Cells[1, arg + 1] := IntToStr(r[arg].x1) + ', ' + IntToStr(r[arg].y1);
rectViewList.Cells[2, arg + 1] := IntToStr(r[arg].x2) + ', ' + IntToStr(r[arg].y2);
end;
end;
// 矩形リスト一括書き換え。プロファイルの画像を変えるたびに。
procedure TForm1.updateRectAll();
var
i: Integer;
begin
for i := Low(profData[profileView.Row - 1].r) to High(profData[profileView.Row - 1].r) do
begin
updateRectListView(i);
end;
end;
procedure TForm1.setpfViewID();
var
i: Integer;
begin
for i := 1 to profileView.RowCount - 1 do
begin
profileView.Cells[0, i] := IntToStr(i - 1);
end;
end;
procedure TForm1.selectPicture();
begin
//mainImg.Picture.Clear();
//mainImg.Picture.LoadFromFile(profData[profileView.Row - 1].fName);
bgraMain.Free;
cv.Free;
bgraMain := TBGRABitmap.Create(profData[profileView.Row - 1].fName);
cv := TBGRABitmap.Create(bgraMain.Bitmap.Width, bgraMain.Bitmap.Height, BGRA(255,255,255,255));
picExtRate := 512.0 / bgraMain.Bitmap.Width;
if picExtRate > 512.0 / bgraMain.Bitmap.Height then
begin
picExtRate:= 512.0 / bgraMain.Bitmap.Height;
end;
end;
procedure TForm1.selectRect();
begin
end;
// 列追加
procedure TForm1.addPictureClick(Sender: TObject);
begin
profileView.RowCount := profileView.RowCount + 1;
setpfViewID();
SetLength(profData, Length(profData) + 1);
profData[High(profData)]:=profileRow.Create();
updatePFListView(Length(profData) - 1);
end;
// preRectフラグが変更された時
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
if profileView.RowCount < 2 then
begin
exit;
end;
profData[profileView.Row - 1].isUsePre := CheckBox1.Checked;
updatePFListView(profileView.Row - 1);
end;
// 列削除 (矩形削除も類似コードなので固有でない動作を更新する際はそっちも)
procedure TForm1.deletePictureClick(Sender: TObject);
var
i: Integer;
begin
if profileView.RowCount < 2 then
begin
exit;
end;
profileView.DeleteRow(profileView.Row);
pfCurrent.Caption := IntToStr(profileView.Row - 1);
if profileView.RowCount = 2 then
begin
SetLength(profData, 0); // 1個しかないのでデータ数を0にする
exit;
end;
// 列データの削除(途中
if rowStable.Checked then
begin
// 安定削除(遅い)
for i := profileView.Row to High(profData) do
begin
profData[i - 1] := profData[i];
end;
end
else
begin
// 適当削除
if Length(profData) > 1 then // 2個以上のデータがあるときに末尾を削除位置にデータ移動
begin
profData[profileView.Row - 1] := profData[High(profData)];
end;
end;
SetLength(profData, Length(profData) - 1);
// データが存在するときに表示を更新
for i := profileView.Row - 1 to Length(profData) - 1 do
begin
updatePFListView(i);
end;
end;
// 矩形を削除(プロファイルのほうのコピーがベースなので) 今はまだコピペしただけなのでこれを矩形向けに書き換え
procedure TForm1.delRectClick(Sender: TObject);
var
i: Integer;
begin
if profileView.Row < 1 then
begin
exit;
end;
if rectViewList.Row < 1 then
begin
exit;
end;
rectViewList.DeleteRow(rectViewList.Row);
editRID.Caption := IntToStr(rectViewList.Row - 1);
if rectViewList.RowCount = 2 then
begin
SetLength(profData[profileView.Row - 1].r, 0); // 1個しかないのでデータ数を0にする
mainImg.OnPaint(nil);
updatePFListView(profileView.Row - 1);
rectNum.Caption := IntToStr(0);
exit;
end;
// 列データの削除(途中
if rectStable.Checked then
begin
// 安定削除(遅い)
for i := rectViewList.Row to High(profData[profileView.Row - 1].r) do
begin
profData[profileView.Row - 1].r[i - 1] := profData[profileView.Row - 1].r[i];
end;
end
else
begin
// 適当削除
if Length(profData[profileView.Row - 1].r) > 1 then // 2個以上のデータがあるときに末尾を削除位置にデータ移動
begin
profData[profileView.Row - 1].r[rectViewList.Row - 1] := profData[profileView.Row - 1].r[High(profData[profileView.Row - 1].r)];
end;
end;
SetLength(profData[profileView.Row - 1].r, Length(profData[profileView.Row - 1].r) - 1);
updatePFListView(profileView.Row - 1);
// データが存在するときに表示を更新
for i := rectViewList.Row - 1 to Length(profData[profileView.Row - 1].r) - 1 do
begin
updateRectListView(i);
end;
end;
// 矩形追加の本動作
procedure TForm1.addRectMain(x1, y1, x2, y2: Integer);
begin
if profileView.Row < 1 then
begin
exit;
end;
rectViewList.RowCount := rectViewList.RowCount + 1;
with profData[profileView.Row - 1] do
begin
SetLength(r, Length(r) + 1);
r[High(r)].x1 := x1;
r[High(r)].y1 := y1;
r[High(r)].x2 := x2;
r[High(r)].y2 := y2;
updateRectListView(High(r));
updatePFListView(profileView.Row - 1);
rectNum.Caption := IntToStr(Length(r));
end;
mainImg.OnPaint(mainImg);
end;
// 矩形を追加
procedure TForm1.addRectClick(Sender: TObject);
var
tx1, ty1, tx2, ty2: Integer;
begin
// x1, y1, x2, y2
if arMode1.Checked then
begin
tx1 := sx1.Value;
ty1 := sy1.Value;
tx2 := sx2.Value;
ty2 := sy2.Value;
end
else
if arMode2.Checked then
begin
tx1 := sx1.Value;
ty1 := sy1.Value;
tx2 := tx1 + sx2.Value;
ty2 := ty1 + sy2.Value;
end
else
if arMode3.Checked then
begin
tx1 := sx1.Value - sx2.Value;
ty1 := sy1.Value - sy2.Value;
tx2 := sx2.Value + sx2.Value;
ty2 := sy2.Value + sy2.Value;
end
else
begin
MessageDlg('Err', 'aaRectClick-Error', TMsgDlgType.mtError, [mbOK], 0);
end;
addRectMain(tx1, ty1, tx2, ty2);
end;
procedure TForm1.FormPaint(Sender: TObject);
begin
end;
// パラメーターでセット
procedure TForm1.setRectClick(Sender: TObject);
begin
end;
procedure TForm1.imgNextClick(Sender: TObject);
begin
end;
procedure TForm1.imgPreClick(Sender: TObject);
begin
end;
procedure TForm1.Label15Click(Sender: TObject);
begin
//rowStable.OnClick(rowStable);
end;
//procedure TForm1.mainImgStartDrag(Sender: TObject; var DragObject: TDragObject);
//begin
// curBeg := Mouse.CursorPos;
//end;
//procedure TForm1.mainImgEndDrag(Sender, Target: TObject; X, Y: Integer);
//var
// tx, ty: Integer;
// tmp: TPoint;
//begin
// if profileView.RowCount < 2 then
// begin
// exit;
// end;
// if Length(profData[profileView.Row - 1].r) < 1 then
// begin
// exit;
// end;
//
// tmp := Mouse.CursorPos;
// tx := Round((tmp.x - curBeg.x) / picExtRate);
// ty := Round((tmp.y - curBeg.y) / picExtRate);
//
// with profData[profileView.Row - 1].r[rectViewList.Row - 1] do
// begin
// x1 := x1 + tx;
// y1 := y1 + ty;
// end;
//end;
// 画像離された
procedure TForm1.mainImgMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
// Left (矩形作成)
if (Button = TMouseButton.mbLeft) then
begin
if isLC =False then
begin
exit;
end;
isLC := False;
addRectMain(Round(clX/picExtRate),Round(clY/picExtRate),Round(X/picExtRate),Round(Y/picExtRate));
end
else
// Right
if (Button = TMouseButton.mbRight) then
begin
if isRC =False then
begin
exit;
end;
isRC := False;
end;
end;
// 画像押された
procedure TForm1.mainImgMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (Button = TMouseButton.mbLeft) then
begin
isLC := True;
clX := X;
clY := Y;
end
else
// Right
if (Button = TMouseButton.mbRight) then
begin
isRC := True;
crX := X;
crY := Y;
end;
end;
// 画像移動
procedure TForm1.mainImgMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
end;
// メイン領域の描画
procedure TForm1.mainImgPaint(Sender: TObject);
var
i: Integer;
stretchCv: TBGRABitmap;
begin
if profileView.RowCount < 2 then
begin
exit;
end;
//cv.PutImage(0,0,bgraIchimatsu,TDrawMode.dmLinearBlend);
//stretchCv.PutImage(0,0,bgraMain,TDrawMode.dmDrawWithTransparency);
bgraIchimatsu.Draw(mainImg.Canvas, 0, 0);
cv.PutImage(0,0,bgraMain,TDrawMode.dmLinearBlend);
with profData[profileView.Row - 1] do
begin
for i := Low(r) to High(r) do
begin
cv.FillRect(Round(r[i].x1 * picExtRate), Round(r[i].y1 * picExtRate),
Round(r[i].x2 * picExtRate), Round(r[i].y2 * picExtRate),
BGRA(Red(rectC.Selected),Green(rectC.Selected),Blue(rectC.Selected),rectA.Value), TDrawMode.dmDrawWithTransparency);
end;
end;
if picXYDiv > 1.0 then
begin
stretchCv := cv.Resample(512,Round(512 / picXYDiv),TResampleMode.rmFineResample) as TBGRABitmap;
end
else
begin
stretchCv := cv.Resample(Round(512 * picXYDiv),512,TResampleMode.rmFineResample) as TBGRABitmap;
end;
StretchCv.Draw(mainImg.Canvas, 0, 0);
stretchCv.Free;
end;
// 列の画像ファイルを更新する
procedure TForm1.picFNameChangeClick(Sender: TObject);
begin
if profileView.RowCount < 2 then
begin
exit;
end;
if odPicF.Execute then
begin
profData[profileView.Row - 1].fName := odPicF.FileName;
// 実際に使う時まで読み込まないことにしたので
//profData[profileView.Row].pic.LoadFromFile(odPicF.FileName);
//profData[profileView.Row].imgX := profData[profileView.Row].pic.Width;
//profData[profileView.Row].imgY := profData[profileView.Row].pic.Height;
updatePFListView(profileView.Row - 1);
end;
end;
// プロファイルの書き出し
procedure TForm1.profExpClick(Sender: TObject);
begin
if odProf.Execute then
begin
//
end;
end;
// 選択されている列を変更する
procedure TForm1.profileViewClick(Sender: TObject);
begin
if profileView.RowCount < 2 then
begin
exit;
end;
// データ更新
pfCurrent.Caption := IntToStr(profileView.Row - 1);
if profData[profileView.Row - 1].fName <> '' then
begin
selectPicture();
profData[profileView.Row - 1].imgX := bgraMain.Bitmap.Width;
profData[profileView.Row - 1].imgY := bgraMain.Bitmap.Height;
end;
imgFNameShow.Caption := ExtractFileName(profData[profileView.Row - 1].fName);
CheckBox1.Checked := profData[profileView.Row - 1].isUsePre;
// 矩形リストの読み直し
rectViewList.RowCount := 1;
rectViewList.RowCount := Length(profData[profileView.Row - 1].r) + 1;
picXYDiv := (bgraMain.Bitmap.Width * 1.0) / (bgraMain.Bitmap.Height * 1.0);
// 矩形SPEditの最大値最小値更新
sx1.MaxValue := bgraMain.Bitmap.Width;
sy1.MaxValue := bgraMain.Bitmap.Height;
sx2.MaxValue := bgraMain.Bitmap.Width;
sy2.MaxValue := bgraMain.Bitmap.Height;
// 表示更新関数を呼ぶ
mainImgPaint(nil);
updateRectAll();
updatePFListView(profileView.Row - 1);
end;
procedure TForm1.rectViewListClick(Sender: TObject);
begin
if rectViewList.RowCount < 2 then
begin
exit;
end;
editRID.Caption := IntToStr(rectViewList.Row - 1);
end;
// -----------------------------------------------------------------------------
constructor profileRow.Create();
begin
SetLength(r, 0);
isUsePre := True;
end;
end.
|
unit CommonFunc;
interface
function FileVersion ( fName : string ) : string;
function UrlEncode(Str: Ansistring): Ansistring;
function UrlDecode(Str: Ansistring): Ansistring;
function LockMutex(AHandle: THandle; ATimeout: integer): Boolean;
function UnlockMutex(AHandle: THandle): boolean;
implementation
uses
Windows, System.SysUtils;
function FileVersion ( fName : string ) : string;
const
Prefix = '\StringFileInfo\040904E4\';
var
FData : Pointer;
FSize : LongInt;
FIHandle : Cardinal;
FFileName : string;
FFileVersion : string;
function GetVerValue(Value: string):string;
var
ItemName: string;
Len : Cardinal;
vVers : Pointer;
begin
ItemName := Prefix + Value;
Result := '';
if VerQueryValue(FData, PChar(ItemName), vVers, Len) then
if Len > 0 then begin
if Len > 255 then
Len := 255;
Result := Copy(PChar(vVers), 1 , Len);
end;{if}
end;{func}
function GetFileVersion: string;
begin
if FSize > 0 then begin
GetMem(FData, FSize);
try
if GetFileVersionInfo(PChar(FFileName), FIHandle, FSize, FData) then begin
FFileVersion:= GetVerValue('FileVersion');
end;{if}
finally
FreeMem(FData, FSize);
end;{try}
end;{if}
Result := FFileVersion;
end;{func}
begin
Result := '';
if FileExists( fName ) then begin
FFileName := fName;
FSize := GetFileVersionInfoSize(PChar(FFileName), FIHandle);
Result := GetFileVersion;
end;
end; { function }
function UrlEncode(Str: ansistring): ansistring;
function CharToHex(Ch: ansiChar): Integer;
asm
and eax, 0FFh
mov ah, al
shr al, 4
and ah, 00fh
cmp al, 00ah
jl @@10
sub al, 00ah
add al, 041h
jmp @@20
@@10:
add al, 030h
@@20:
cmp ah, 00ah
jl @@30
sub ah, 00ah
add ah, 041h
jmp @@40
@@30:
add ah, 030h
@@40:
shl eax, 8
mov al, '%'
end;
var
i, Len: Integer;
Ch: ansiChar;
N: Integer;
P: PansiChar;
begin
Result := str;
Exit;
Len := Length(Str);
P := PansiChar(@N);
for i := 1 to Len do
begin
Ch := Str[i];
if Ch in ['0'..'9', 'A'..'Z', 'a'..'z', '_'] then
Result := Result + Ch
else
begin
if Ch = ' ' then
Result := Result + '+'
else
begin
N := CharToHex(Ch);
Result := Result + P;
end;
end;
end;
end;
function UrlDecode(Str: Ansistring): Ansistring;
function HexToChar(W: word): AnsiChar;
asm
cmp ah, 030h
jl @@error
cmp ah, 039h
jg @@10
sub ah, 30h
jmp @@30
@@10:
cmp ah, 041h
jl @@error
cmp ah, 046h
jg @@20
sub ah, 041h
add ah, 00Ah
jmp @@30
@@20:
cmp ah, 061h
jl @@error
cmp al, 066h
jg @@error
sub ah, 061h
add ah, 00Ah
@@30:
cmp al, 030h
jl @@error
cmp al, 039h
jg @@40
sub al, 030h
jmp @@60
@@40:
cmp al, 041h
jl @@error
cmp al, 046h
jg @@50
sub al, 041h
add al, 00Ah
jmp @@60
@@50:
cmp al, 061h
jl @@error
cmp al, 066h
jg @@error
sub al, 061h
add al, 00Ah
@@60:
shl al, 4
or al, ah
ret
@@error:
xor al, al
end;
function GetCh(P: PAnsiChar; var Ch: AnsiChar): AnsiChar;
begin
Ch := P^;
Result := Ch;
end;
var
P: PAnsiChar;
Ch: AnsiChar;
begin
Result := str;
Exit;
P := @Str[1];
while GetCh(P, Ch) <> #0 do
begin
case Ch of
'+': Result := Result + ' ';
'%':
begin
Inc(P);
Result := Result + HexToChar(PWord(P)^);
Inc(P);
end;
else
Result := Result + Ch;
end;
Inc(P);
end;
end;
function LockMutex(AHandle: THandle; ATimeout: integer): Boolean;
var
res: Cardinal;
begin
Result := False;
try
res := WaitForSingleObject(AHandle, ATimeout);
Result := res = WAIT_OBJECT_0;
except
Result := False;
end;
end;
function UnlockMutex(AHandle: THandle): boolean;
begin
try
Result := ReleaseMutex(AHandle);
except
result := False;
end;
end;
end.
|
unit UserUtils;
interface
type
TUserInfo = record
UserID: string;
UserName: string;
GroupID: Integer;
GroupName: string;
end;
implementation
end.
|
{ **********************************************************************}
{ }
{ DeskMetrics DLL - dskMetricsCPUInfo.pas }
{ Copyright (c) 2010-2011 DeskMetrics Limited }
{ }
{ http://deskmetrics.com }
{ http://support.deskmetrics.com }
{ }
{ support@deskmetrics.com }
{ }
{ This code is provided under the DeskMetrics Modified BSD License }
{ A copy of this license has been distributed in a file called }
{ LICENSE with this source code. }
{ }
{ **********************************************************************}
unit dskMetricsCPUInfo;
interface
uses
Windows, SysUtils;
type
TPDWord = ^DWORD;
TQProcessorArchitecture = (
paUnknown, // Unknown architecture
paX64, // X64 (AMD or Intel)
paIA64, // Intel Itanium processor family (IPF)
paX86 // Intel 32 bit
);
TQProcessorRegisters = record
EAX,
EBX,
ECX,
EDX: Cardinal;
end;
TQProcessorVendor = (
cvUnknown, cvAMD, cvCentaur, cvCyrix, cvIntel,
cvTransmeta, cvNexGen, cvRise, cvUMC, cvNSC, cvSiS
);
{Note: when changing TVendor, also change VendorStr array below}
TQProcessorInstructions =
(isFPU, {80x87}
isTSC, {RDTSC}
isCX8, {CMPXCHG8B}
isSEP, {SYSENTER/SYSEXIT}
isCMOV, {CMOVcc, and if isFPU, FCMOVcc/FCOMI}
isMMX, {MMX}
isFXSR, {FXSAVE/FXRSTOR}
isSSE, {SSE}
isSSE2, {SSE2}
isSSE3, {SSE3*}
isMONITOR, {MONITOR/MWAIT*}
isCX16, {CMPXCHG16B*}
isX64, {AMD AMD64* or Intel EM64T*}
isExMMX, {MMX+ - AMD only}
isEx3DNow, {3DNow!+ - AMD only}
is3DNow, {3DNow! - AMD only}
isHTT, {HyperThreading}
isVME, {Virtualization}
isSSSE3 {SSSE3}
);
{Note: when changing TInstruction, also change InstructionSupportStr below
* - instruction(s) not supported in Delphi 7 assembler}
TQInstructionSupport = set of TQProcessorInstructions;
const
// These constants are required when examining the
// TSystemInfo.wProcessorArchitecture member
// Only constants marked * are currently defined in the MS 2008 SDK
//
PROCESSOR_ARCHITECTURE_UNKNOWN = $FFFF; // Unknown architecture.
PROCESSOR_ARCHITECTURE_INTEL = 0; // x86 *
PROCESSOR_ARCHITECTURE_MIPS = 1; // MIPS architecture
PROCESSOR_ARCHITECTURE_ALPHA = 2; // Alpha architecture
PROCESSOR_ARCHITECTURE_PPC = 3; // PPC architecture
PROCESSOR_ARCHITECTURE_SHX = 4; // SHX architecture
PROCESSOR_ARCHITECTURE_ARM = 5; // ARM architecture
PROCESSOR_ARCHITECTURE_IA64 = 6; // Intel Itanium Processor Family *
PROCESSOR_ARCHITECTURE_ALPHA64 = 7; // Alpha64 architecture
PROCESSOR_ARCHITECTURE_MSIL = 8; // MSIL architecture
PROCESSOR_ARCHITECTURE_AMD64 = 9; // x64 (AMD or Intel) *
PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 = 10; // IA32 on Win64 architecture
//
// These constants are provided in case the obsolete
// TSystemInfo.dwProcessorType needs to be used.
// Constants marked Windows CE are only used on Windows mobile and are only
// provided here for completeness.
// Only constants marked * are defined in the MS SDK 6.1
//
PROCESSOR_INTEL_386 = 386; // Intel i386 processor *
PROCESSOR_INTEL_486 = 486; // Intel i486 processor *
PROCESSOR_INTEL_PENTIUM = 586; // Intel Pentium processor *
PROCESSOR_INTEL_IA64 = 2200; // Intel IA64 processor *
PROCESSOR_AMD_X8664 = 8664; // AMD X86 64 processor *
PROCESSOR_MIPS_R4000 = 4000; // MIPS R4000, R4101, R3910 processor
PROCESSOR_ALPHA_21064 = 21064; // Alpha 210 64 processor
PROCESSOR_PPC_601 = 601; // PPC 601 processor
PROCESSOR_PPC_603 = 603; // PPC 603 processor
PROCESSOR_PPC_604 = 604; // PPC 604 processor
PROCESSOR_PPC_620 = 620; // PPC 620 processor
PROCESSOR_HITACHI_SH3 = 10003; // Hitachi SH3 processor (Windows CE)
PROCESSOR_HITACHI_SH3E = 10004; // Hitachi SH3E processor (Windows CE)
PROCESSOR_HITACHI_SH4 = 10005; // Hitachi SH4 processor (Windows CE)
PROCESSOR_MOTOROLA_821 = 821; // Motorola 821 processor (Windows CE)
PROCESSOR_SHx_SH3 = 103; // SHx SH3 processor (Windows CE)
PROCESSOR_SHx_SH4 = 104; // SHx SH4 processor (Windows CE)
PROCESSOR_STRONGARM = 2577; // StrongARM processor (Windows CE)
PROCESSOR_ARM720 = 1824; // ARM 720 processor (Windows CE)
PROCESSOR_ARM820 = 2080; // ARM 820 processor (Windows CE)
PROCESSOR_ARM920 = 2336; // ARM 920 processor (Windows CE)
PROCESSOR_ARM_7TDMI = 70001; // ARM 7TDMI processor (Windows CE)
PROCESSOR_OPTIL = $494F; // MSIL processor
QInstructionSupportStr:
array[Low(TQProcessorInstructions)..High(TQProcessorInstructions)] of ShortString =
('FPU', 'TSC', 'CX8', 'SEP', 'CMOV', 'MMX', 'FXSR', 'SSE', 'SSE2', 'SSE3',
'MONITOR', 'CX16', 'X64', 'MMX+', '3DNow!+', '3DNow!', 'HyperThreading', 'Virtualization', 'SSSE3');
type
TQCPUFeatures =
({in EDX}
cfFPU, cfVME, cfDE, cfPSE, cfTSC, cfMSR, cfPAE, cfMCE,
cfCX8, cfAPIC, cf_d10, cfSEP, cfMTRR, cfPGE, cfMCA, cfCMOV,
cfPAT, cfPSE36, cfPSN, cfCLFSH, cf_d20, cfDS, cfACPI, cfMMX,
cfFXSR, cfSSE, cfSSE2, cfSS, cfHTT, cfTM, cfIA_64, cfPBE,
{in ECX}
cfSSE3, cf_c1, cf_c2, cfMON, cfDS_CPL, cf_c5, cf_c6, cfEIST,
cfTM2, cfSSSE3, cfCID, cf_c11, cf_c12, cfCX16, cfxTPR, cf_c15,
cf_c16, cf_c17, cf_c18, cf_c19, cf_c20, cf_c21, cf_c22, cf_c23,
cf_c24, cf_c25, cf_c26, cf_c27, cf_c28, cf_c29, cf_c30, cf_c31);
TQCPUFeatureSet = set of TQCPUFeatures;
TQCPUExtendedFeatures =
(cefFPU, cefVME, cefDE, cefPSE, cefTSC, cefMSR, cefPAE, cefMCE,
cefCX8, cefAPIC, cef_10, cefSEP, cefMTRR, cefPGE, cefMCA, cefCMOV,
cefPAT, cefPSE36, cef_18, ceMPC, ceNX, cef_21, cefExMMX, cefMMX,
cefFXSR, cef_25, cef_26, cef_27, cef_28, cefLM, cefEx3DNow, cef3DNow);
TCpuExtendedFeatureSet = set of TQCPUExtendedFeatures;
TQFastCodeTarget =
(fctRTLReplacement, {not specific to any CPU}
fctBlended, {not specific to any CPU, requires FPU, MMX and CMOV}
fctP3, {Pentium/Celeron 3}
fctPM, {Pentium/Celeron M (Banias and Dothan)}
fctP4, {Pentium/Celeron/Xeon 4 without SSE3 (Willamette,
Foster, Foster MP, Northwood, Prestonia, Gallatin)}
fctP4_SSE3, {Pentium/Celeron 4 with SSE3 (Prescott)}
fctP4_64, {Pentium/Xeon 4 with EM64T (some Prescott, and Nocona)}
fctK7, {Athlon/Duron without SSE (Thunderbird and Spitfire)}
fctK7_SSE, {Athlon/Duron/Sempron with SSE (Palomino, Morgan,
Thoroughbred, Applebred, Barton)}
fctK8, {Opteron/Athlon FX/Athlon 64 (Clawhammer, Sledgehammer,
Newcastle)}
fctK8_SSE3); {Opteron/Athlon FX/Athlon 64 with SSE3 (future)}
{Note: when changing TFastCodeTarget, also change FastCodeTargetStr array
below}
TQProcessorVendorStr = string[12];
TQCPUInfo = record
Vendor: TQProcessorVendor;
Signature: Cardinal;
EffType: Byte;
EffFamily: Byte; {ExtendedFamily + Family}
EffFamilyEx: Byte;
EffModel: Byte; {(ExtendedModel shl 4) + Model}
EffModelEx: Byte;
EffStepping: Byte;
CodeL1CacheSize, {KB or micro-ops for Pentium 4}
DataL1CacheSize, {KB}
L2CacheSize, {KB}
L3CacheSize: Word; {KB}
HyperThreading: Boolean;
Virtualization: Boolean;
InstructionSupport: TQInstructionSupport;
end;
TFormatTemp = (ftCelsius, ftFahrenheit);
const
QVendorIDString: array[Low(TQProcessorVendor)..High(TQProcessorVendor)] of TQProcessorVendorStr =
('',
'AuthenticAMD', 'CentaurHauls', 'CyrixInstead', 'GenuineIntel',
'GenuineTMx86', 'NexGenDriven', 'RiseRiseRise', 'UMC UMC UMC ',
'Geode by NSC', 'SiS SiS SiS');
FastCodeTargetStr:
array[Low(TQFastCodeTarget)..High(TQFastCodeTarget)] of ShortString =
('RTLReplacement', 'Blended', 'P3', 'PM', 'P4', 'P4_SSE3', 'P4_64',
'K7', 'K7_SSE', 'K8', 'K8_SSE3');
{ Features Data }
IntelLowestSEPSupportSignature = $633;
K7DuronA0Signature = $630;
C3Samuel2EffModel = 7;
C3EzraEffModel = 8;
PMBaniasEffModel = 9;
PMDothanEffModel = $D;
P3LowestEffModel = 7;
function _GetProcessorFrequencyInternal: Integer;
function _GetProcessorArchitectureInternal: string;
function _GetProcessorVendorInternal: string;
var
ProcessorData: TQCPUInfo;
{ Get all processor information }
FastCodeTarget: TQFastCodeTarget;
SI: TSystemInfo;
pvtProcessorArchitecture: Word = 0;
{Records processor architecture information}
NtQuerySystemInformation: function(infoClass: DWORD;
buffer: Pointer;
bufSize: DWORD;
returnSize: TPDword): DWORD; stdcall = nil;
liOldIdleTime: LARGE_INTEGER = ();
liOldSystemTime: LARGE_INTEGER = ();
Usage: Double;
FCPUName, FCodename, FRevision, FTech: string;
{ Information about specified processor }
implementation
uses
dskMetricsCommon;
function IsCPUID_Available: Boolean; register;
asm
{$IFDEF CPUX86}
PUSHFD {save EFLAGS to stack}
POP EAX {store EFLAGS in EAX}
MOV EDX, EAX {save in EDX for later testing}
XOR EAX, $200000; {flip ID bit in EFLAGS}
PUSH EAX {save new EFLAGS value on stack}
POPFD {replace current EFLAGS value}
PUSHFD {get new EFLAGS}
POP EAX {store new EFLAGS in EAX}
XOR EAX, EDX {check if ID bit changed}
JZ @exit {no, CPUID not available}
MOV EAX, True {yes, CPUID is available}
@exit:
{$ENDIF}
end;
function IsFPU_Available: Boolean;
var
_FCW, _FSW: Word;
asm
{$IFDEF CPUX86}
MOV EAX, False {initialize return register}
MOV _FSW, $5A5A {store a non-zero value}
FNINIT {must use non-wait form}
FNSTSW _FSW {store the status}
CMP _FSW, 0 {was the correct status read?}
JNE @exit {no, FPU not available}
FNSTCW _FCW {yes, now save control word}
MOV DX, _FCW {get the control word}
AND DX, $103F {mask the proper status bits}
CMP DX, $3F {is a numeric processor installed?}
JNE @exit {no, FPU not installed}
MOV EAX, True {yes, FPU is installed}
@exit:
{$ENDIF}
end;
procedure GetCPUID(Param: Cardinal; var Registers: TQProcessorRegisters);
asm
{$IFDEF CPUX86}
PUSH EBX {save affected registers}
PUSH EDI
MOV EDI, Registers
XOR EBX, EBX {clear EBX register}
XOR ECX, ECX {clear ECX register}
XOR EDX, EDX {clear EDX register}
DB $0F, $A2 {CPUID opcode}
MOV TQProcessorRegisters(EDI).&EAX, EAX {save EAX register}
MOV TQProcessorRegisters(EDI).&EBX, EBX {save EBX register}
MOV TQProcessorRegisters(EDI).&ECX, ECX {save ECX register}
MOV TQProcessorRegisters(EDI).&EDX, EDX {save EDX register}
POP EDI {restore registers}
POP EBX
{$ENDIF}
end;
procedure GetCPUVendor;
{$IFDEF CPUX86}
var
VendorStr: TQProcessorVendorStr;
Registers: TQProcessorRegisters;
{$ENDIF CPUX86}
begin
{$IFDEF CPUX86}
try
{call CPUID function 0}
GetCPUID(0, Registers);
{get vendor string}
SetLength(VendorStr, 12);
Move(Registers.EBX, VendorStr[1], 4);
Move(Registers.EDX, VendorStr[5], 4);
Move(Registers.ECX, VendorStr[9], 4);
{get CPU vendor from vendor string}
ProcessorData.Vendor := High(TQProcessorVendor);
while (VendorStr <> QVendorIDString[ProcessorData.Vendor]) and
(ProcessorData.Vendor > Low(TQProcessorVendor)) do
Dec(ProcessorData.Vendor);
except
end;
{$ENDIF CPUX86}
end;
procedure GetCPUFeatures;
{preconditions: 1. maximum CPUID must be at least $00000001
2. GetCPUVendor must have been called}
{$IFDEF CPUX86}
type
_Int64 = packed record
Lo: Longword;
Hi: Longword;
end;
var
Registers: TQProcessorRegisters;
CpuFeatures: TQCPUFeatureSet;
{$ENDIF}
begin
{$IFDEF CPUX86}
try
{call CPUID function $00000001}
GetCPUID($00000001, Registers);
{get CPU signature}
ProcessorData.Signature := Registers.EAX;
{extract effective processor family and model}
ProcessorData.EffType := (ProcessorData.Signature and $00003000) shr 12;
ProcessorData.EffFamily := (ProcessorData.Signature and $00000F00) shr 8;
ProcessorData.EffFamilyEx := ProcessorData.Signature shr 8 and $F;;
ProcessorData.EffModel := (ProcessorData.Signature and $000000F0) shr 4;
ProcessorData.EffModelEx := ProcessorData.Signature shr 4 and $F;
ProcessorData.EffStepping := (ProcessorData.Signature and $0000000F);
if ProcessorData.EffFamily = $F then
begin
ProcessorData.EffFamily := ProcessorData.EffFamily + (ProcessorData.Signature and $0FF00000 shr 20);
ProcessorData.EffModel := ProcessorData.EffModel + (ProcessorData.Signature and $000F0000 shr 12);
end;
{get CPU features}
Move(Registers.EDX, _Int64(CpuFeatures).Lo, 4);
Move(Registers.ECX, _Int64(CpuFeatures).Hi, 4);
{get instruction support}
if cfFPU in CpuFeatures then
Include(ProcessorData.InstructionSupport, isFPU);
if cfTSC in CpuFeatures then
Include(ProcessorData.InstructionSupport, isTSC);
if cfCX8 in CpuFeatures then
Include(ProcessorData.InstructionSupport, isCX8);
if cfSEP in CpuFeatures then
begin
Include(ProcessorData.InstructionSupport, isSEP);
{for Intel CPUs, qualify the processor family and model to ensure that the
SYSENTER/SYSEXIT instructions are actually present - see Intel Application
Note AP-485}
if (ProcessorData.Vendor = cvIntel) and
(ProcessorData.Signature and $0FFF3FFF < IntelLowestSEPSupportSignature) then
Exclude(ProcessorData.InstructionSupport, isSEP);
end;
if cfCMOV in CpuFeatures then
Include(ProcessorData.InstructionSupport, isCMOV);
if cfFXSR in CpuFeatures then
Include(ProcessorData.InstructionSupport, isFXSR);
if cfMMX in CpuFeatures then
Include(ProcessorData.InstructionSupport, isMMX);
if cfSSE in CpuFeatures then
Include(ProcessorData.InstructionSupport, isSSE);
if cfSSE2 in CpuFeatures then
Include(ProcessorData.InstructionSupport, isSSE2);
if cfSSE3 in CpuFeatures then
Include(ProcessorData.InstructionSupport, isSSE3);
if (ProcessorData.Vendor = cvIntel) and (cfMON in CpuFeatures) then
Include(ProcessorData.InstructionSupport, isMONITOR);
if cfCX16 in CpuFeatures then
Include(ProcessorData.InstructionSupport, isCX16);
if cfSSSE3 in CpuFeatures then
Include(ProcessorData.InstructionSupport, isSSSE3);
if cfHTT in CpuFeatures then
Include(ProcessorData.InstructionSupport, isHTT);
except
end;
{$ENDIF}
end;
procedure GetCPUExtendedFeatures;
{preconditions: maximum extended CPUID >= $80000001}
{$IFDEF CPUX86}
var
Registers: TQProcessorRegisters;
CpuExFeatures: TCpuExtendedFeatureSet;
{$ENDIF}
begin
{$IFDEF CPUX86}
try
{call CPUID function $80000001}
GetCPUID($80000001, Registers);
{get CPU extended features}
CPUExFeatures := TCPUExtendedFeatureSet(Registers.EDX);
{get instruction support}
if cefLM in CpuExFeatures then
Include(ProcessorData.InstructionSupport, isX64);
if cefExMMX in CpuExFeatures then
Include(ProcessorData.InstructionSupport, isExMMX);
if cefEx3DNow in CpuExFeatures then
Include(ProcessorData.InstructionSupport, isEx3DNow);
if cef3DNow in CpuExFeatures then
Include(ProcessorData.InstructionSupport, is3DNow);
{ if cefVME in CpuExFeatures then
Include(ProcessorData.InstructionSupport, isVME);
HyperThreading falta}
except
end;
{$ENDIF}
end;
procedure GetProcessorCacheInfo;
{preconditions: 1. maximum CPUID must be at least $00000002
2. GetCPUVendor must have been called}
{$IFDEF CPUX86}
type
TConfigDescriptor = packed array[0..15] of Byte;
var
Registers: TQProcessorRegisters;
i, j: Integer;
QueryCount: Byte;
{$ENDIF}
begin
{$IFDEF CPUX86}
try
{call CPUID function 2}
GetCPUID($00000002, Registers);
QueryCount := Registers.EAX and $FF;
for i := 1 to QueryCount do
begin
for j := 1 to 15 do
with ProcessorData do
{decode configuration descriptor byte}
case TConfigDescriptor(Registers)[j] of
$06: CodeL1CacheSize := 8;
$08: CodeL1CacheSize := 16;
$0A: DataL1CacheSize := 8;
$0C: DataL1CacheSize := 16;
$22: L3CacheSize := 512;
$23: L3CacheSize := 1024;
$25: L3CacheSize := 2048;
$29: L3CacheSize := 4096;
$2C: DataL1CacheSize := 32;
$30: CodeL1CacheSize := 32;
$39: L2CacheSize := 128;
$3B: L2CacheSize := 128;
$3C: L2CacheSize := 256;
$40: {no 2nd-level cache or, if processor contains a valid 2nd-level
cache, no 3rd-level cache}
if L2CacheSize <> 0 then
L3CacheSize := 0;
$41: L2CacheSize := 128;
$42: L2CacheSize := 256;
$43: L2CacheSize := 512;
$44: L2CacheSize := 1024;
$45: L2CacheSize := 2048;
$60: DataL1CacheSize := 16;
$66: DataL1CacheSize := 8;
$67: DataL1CacheSize := 16;
$68: DataL1CacheSize := 32;
$70: if not (ProcessorData.Vendor in [cvCyrix, cvNSC]) then
CodeL1CacheSize := 12; {K micro-ops}
$71: CodeL1CacheSize := 16; {K micro-ops}
$72: CodeL1CacheSize := 32; {K micro-ops}
$78: L2CacheSize := 1024;
$79: L2CacheSize := 128;
$7A: L2CacheSize := 256;
$7B: L2CacheSize := 512;
$7C: L2CacheSize := 1024;
$7D: L2CacheSize := 2048;
$7F: L2CacheSize := 512;
$80: if ProcessorData.Vendor in [cvCyrix, cvNSC] then
begin {Cyrix and NSC only - 16 KB unified L1 cache}
CodeL1CacheSize := 8;
DataL1CacheSize := 8;
end;
$82: L2CacheSize := 256;
$83: L2CacheSize := 512;
$84: L2CacheSize := 1024;
$85: L2CacheSize := 2048;
$86: L2CacheSize := 512;
$87: L2CacheSize := 1024;
end;
if i < QueryCount then
GetCPUID(2, Registers);
end;
except
end;
{$ENDIF}
end;
procedure GetExtendedProcessorCacheInfo;
{preconditions: 1. maximum extended CPUID must be at least $80000006
2. GetCPUVendor and GetCPUFeatures must have been called}
{$IFDEF CPUX86}
var
Registers: TQProcessorRegisters;
{$ENDIF}
begin
{$IFDEF CPUX86}
try
{call CPUID function $80000005}
GetCPUID($80000005, Registers);
{get L1 cache size}
{Note: Intel does not support function $80000005 for L1 cache size, so ignore.
Cyrix returns CPUID function 2 descriptors (already done), so ignore.}
if not (ProcessorData.Vendor in [cvIntel, cvCyrix]) then
begin
ProcessorData.CodeL1CacheSize := Registers.EDX shr 24;
ProcessorData.DataL1CacheSize := Registers.ECX shr 24;
end;
{call CPUID function $80000006}
GetCPUID($80000006, Registers);
{get L2 cache size}
if (ProcessorData.Vendor = cvAMD) and (ProcessorData.Signature and $FFF = K7DuronA0Signature) then
{workaround for AMD Duron Rev A0 L2 cache size erratum - see AMD Technical
Note TN-13}
ProcessorData.L2CacheSize := 64
else if (ProcessorData.Vendor = cvCentaur) and (ProcessorData.EffFamily = 6) and
(ProcessorData.EffModel in [C3Samuel2EffModel, C3EzraEffModel]) then
{handle VIA (Centaur) C3 Samuel 2 and Ezra non-standard encoding}
ProcessorData.L2CacheSize := Registers.ECX shr 24
else {standard encoding}
ProcessorData.L2CacheSize := Registers.ECX shr 16;
except
end;
{$ENDIF}
end;
procedure VerifyOSSupportForXMMRegisters;
begin
{$IFDEF CPUX86}
try
{try a SSE instruction that operates on XMM registers}
try
asm
DB $0F, $54, $C0 // ANDPS XMM0, XMM0
end
except
on E: Exception do
begin
{if it fails, assume that none of the SSE instruction sets are available}
Exclude(ProcessorData.InstructionSupport, isSSE);
Exclude(ProcessorData.InstructionSupport, isSSE2);
Exclude(ProcessorData.InstructionSupport, isSSE3);
end;
end;
except
end;
{$ENDIF}
end;
procedure GetCPUInfo;
{$IFDEF CPUX86}
var
Registers: TQProcessorRegisters;
MaxCPUID: Cardinal;
MaxExCPUID: Cardinal;
{$ENDIF}
begin
{$IFDEF CPUX86}
{initialize - just to be sure}
FillChar(ProcessorData, SizeOf(ProcessorData), 0);
try
if not IsCPUID_Available then
begin
if IsFPU_Available then
Include(ProcessorData.InstructionSupport, isFPU);
end
else
begin
{get maximum CPUID input value}
GetCPUID($00000000, Registers);
MaxCPUID := Registers.EAX;
{get CPU vendor - Max CPUID will always be >= 0}
GetCPUVendor;
{get CPU features if available}
if MaxCPUID >= $00000001 then
GetCPUFeatures;
{get cache info if available}
if MaxCPUID >= $00000002 then
GetProcessorCacheInfo;
{get maximum extended CPUID input value}
GetCPUID($80000000, Registers);
MaxExCPUID := Registers.EAX;
{get CPU extended features if available}
if MaxExCPUID >= $80000001 then
GetCPUExtendedFeatures;
{verify operating system support for XMM registers}
if isSSE in ProcessorData.InstructionSupport then
VerifyOSSupportForXMMRegisters;
{get extended cache features if available}
{Note: ignore processors that only report L1 cache info,
i.e. have a MaxExCPUID = $80000005}
if MaxExCPUID >= $80000006 then
GetExtendedProcessorCacheInfo;
end;
except
end;
{$ENDIF}
end;
procedure GetFastCodeTarget;
{precondition: GetCPUInfo must have been called}
begin
{$IFDEF CPUX86}
try
{as default, select blended target if there is at least FPU, MMX, and CMOV
instruction support, otherwise select RTL Replacement target}
if [isFPU, isMMX, isCMOV] <= ProcessorData.InstructionSupport then
FastCodeTarget := fctBlended
else
FastCodeTarget := fctRTLReplacement;
case ProcessorData.Vendor of
cvIntel:
case ProcessorData.EffFamily of
6: {Intel P6, P2, P3, PM}
if ProcessorData.EffModel in [PMBaniasEffModel, PMDothanEffModel] then
FastCodeTarget := fctPM
else if ProcessorData.EffModel >= P3LowestEffModel then
FastCodeTarget := fctP3;
$F: {Intel P4}
if isX64 in ProcessorData.InstructionSupport then
FastCodeTarget := fctP4_64
else if isSSE3 in ProcessorData.InstructionSupport then
FastCodeTarget := fctP4_SSE3
else
FastCodeTarget := fctP4;
end;
cvAMD:
case ProcessorData.EffFamily of
6: {AMD K7}
if isSSE in ProcessorData.InstructionSupport then
FastCodeTarget := fctK7_SSE
else
FastCodeTarget := fctK7;
$F: {AMD K8}
if isSSE3 in ProcessorData.InstructionSupport then
FastCodeTarget := fctK8_SSE3
else
FastCodeTarget := fctK8;
end;
end;
except
end;
{$ENDIF}
end;
function _GetProcessorArchitectureInternal: string;
begin
{$IFDEF CPUX86}
Result := '32';
try
if isX64 in ProcessorData.InstructionSupport then
Result := '64'
else
Result := '32';
except
Result := '32'; //Assume 32 bits processor
end;
{$ENDIF}
end;
function _GetProcessorVendorInternal: string;
begin
{$IFDEF CPUX86}
Result := '';
try
Result := string(QVendorIDString[ProcessorData.Vendor]);
{ Easy read of user }
if Result = 'AuthenticAMD' then
Result := 'AMD'
else
if Result = 'GenuineIntel' then
Result := 'Intel'
else
if Result = 'GenuineTMx86' then
Result := 'Transmeta'
else
if Result = 'CentaurHauls' then
Result := 'VIA'
else
if Result = 'Geode by NSC' then
Result := 'NationalSemi'
except
Result := '';
end;
{$ENDIF}
end;
function _GetProcessorFrequencyInternal: Integer;
{$IFDEF CPUX86}
const
DelayTime = 500;
ID_BIT = $200000;
var
TimerHi, TimerLo: DWORD;
PriorityClass, Priority: Integer;
{$ENDIF}
begin
{$IFDEF CPUX86}
try
PriorityClass := GetPriorityClass(GetCurrentProcess);
Priority := GetThreadPriority(GetCurrentThread);
SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
Sleep(10);
asm
dw 310Fh // rdtsc
mov TimerLo, eax
mov TimerHi, edx
end;
Sleep(DelayTime);
asm
dw 310Fh // rdtsc
sub eax, TimerLo
sbb edx, TimerHi
mov TimerLo, eax
mov TimerHi, edx
end;
SetThreadPriority(GetCurrentThread, Priority);
SetPriorityClass(GetCurrentProcess, PriorityClass);
Result := Round(TimerLo / (1000.0 * DelayTime));
except
Result := 0;
end;
{$ENDIF}
end;
procedure InitializeEx;
{$IFDEF CPUX86}
type
// Function type of the GetNativeSystemInfo and GetSystemInfo functions
TGetSystemInfo = procedure(var lpSystemInfo: TSystemInfo); stdcall;
var
GetSystemInfoFn: TGetSystemInfo; // fn used to get system info
{$ENDIF}
begin
{$IFDEF CPUX86}
try
{ Extract function from kernel and execute }
GetSystemInfoFn := _LoadKernelFunc('GetNativeSystemInfo');
if not Assigned(GetSystemInfoFn) then
GetSystemInfoFn := Windows.GetSystemInfo;
GetSystemInfoFn(SI);
except
end;
{$ENDIF}
end;
initialization
{ Processor Data Initialization }
try
{$IFDEF CPUX86}
InitializeEx;
GetCPUInfo;
GetFastCodeTarget;
{$ENDIF}
except
end;
end.
|
unit XT_INTV;
{$ifdef VirtualPascal}
{$stdcall+}
{$else}
Error('Interface unit for VirtualPascal');
{$endif}
(*************************************************************************
DESCRIPTION : Interface unit for XT_DLL
REQUIREMENTS : VirtualPascal
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 01.01.05 W.Ehrhardt Initial version a la XT_INTV
0.11 16.07.09 we XT_DLL_Version returns PAnsiChar
0.12 06.08.10 we Longint ILen, XT_CTR_Seek via xt_seek.inc
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2005-2010 Wolfgang Ehrhardt
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
const
XT_Err_Invalid_Key_Size = -1; {Key size in bytes <1 or >56}
XT_Err_Invalid_Length = -3; {No full block for cipher stealing}
XT_Err_Data_After_Short_Block = -4; {Short block must be last}
XT_Err_MultipleIncProcs = -5; {More than one IncProc Setting}
XT_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length}
XT_Err_CTR_SeekOffset = -15; {Invalid offset in XT_CTR_Seek}
XT_Err_Invalid_16Bit_Length = -20; {Pointer + Offset > $FFFF for 16 bit code}
type
TXTBlock = packed array[0..7] of byte;
PXTBlock = ^TXTBlock;
TXTRKArray = packed array[0..31] of longint;
type
TXTIncProc = procedure(var CTR: TXTBlock); {user supplied IncCTR proc}
{$ifdef DLL} stdcall; {$endif}
type
TXTContext = packed record
XA,XB : TXTRKArray; {round key arrays }
IV : TXTBlock; {IV or CTR }
buf : TXTBlock; {Work buffer }
bLen : word; {Bytes used in buf }
Flag : word; {Bit 1: Short block }
IncProc : TXTIncProc; {Increment proc CTR-Mode}
end;
const
XTBLKSIZE = sizeof(TXTBlock);
function XT_DLL_Version: PAnsiChar;
{-Return DLL version as PAnsiChar}
function XT_Init(const Key; KeyBytes: word; var ctx: TXTContext): integer;
{-XTEA context initialization}
procedure XT_Encrypt(var ctx: TXTContext; const BI: TXTBlock; var BO: TXTBlock);
{-encrypt one block (in ECB mode)}
procedure XT_Decrypt(var ctx: TXTContext; const BI: TXTBlock; var BO: TXTBlock);
{-decrypt one block (in ECB mode)}
procedure XT_XorBlock(const B1, B2: TXTBlock; var B3: TXTBlock);
{-xor two blocks, result in third}
procedure XT_SetFastInit(value: boolean);
{-set FastInit variable}
function XT_GetFastInit: boolean;
{-Returns FastInit variable}
function XT_CBC_Init(const Key; KeyBytes: word; const IV: TXTBlock; var ctx: TXTContext): integer;
{-XTEA key expansion, error if invalid key size, save IV}
procedure XT_CBC_Reset(const IV: TXTBlock; var ctx: TXTContext);
{-Clears ctx fields bLen and Flag, save IV}
function XT_CBC_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TXTContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CBC mode}
function XT_CBC_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TXTContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CBC mode}
function XT_CFB_Init(const Key; KeyBytes: word; const IV: TXTBlock; var ctx: TXTContext): integer;
{-XTEA key expansion, error if invalid key size, encrypt IV}
procedure XT_CFB_Reset(const IV: TXTBlock; var ctx: TXTContext);
{-Clears ctx fields bLen and Flag, encrypt IV}
function XT_CFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TXTContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CFB mode}
function XT_CFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TXTContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CFB mode}
function XT_CTR_Init(const Key; KeyBytes: word; const CTR: TXTBlock; var ctx: TXTContext): integer;
{-XTEA key expansion, error if inv. key size, encrypt CTR}
procedure XT_CTR_Reset(const CTR: TXTBlock; var ctx: TXTContext);
{-Clears ctx fields bLen and Flag, encrypt CTR}
function XT_CTR_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TXTContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode}
function XT_CTR_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TXTContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode}
function XT_CTR_Seek(const iCTR: TXTBlock; SOL, SOH: longint; var ctx: TXTContext): integer;
{-Setup ctx for random access crypto stream starting at 64 bit offset SOH*2^32+SOL,}
{ SOH >= 0. iCTR is the initial CTR for offset 0, i.e. the same as in XT_CTR_Init.}
function XT_SetIncProc(IncP: TXTIncProc; var ctx: TXTContext): integer;
{-Set user supplied IncCTR proc}
procedure XT_IncMSBFull(var CTR: TXTBlock);
{-Increment CTR[7]..CTR[0]}
procedure XT_IncLSBFull(var CTR: TXTBlock);
{-Increment CTR[0]..CTR[7]}
procedure XT_IncMSBPart(var CTR: TXTBlock);
{-Increment CTR[7]..CTR[4]}
procedure XT_IncLSBPart(var CTR: TXTBlock);
{-Increment CTR[0]..CTR[3]}
function XT_ECB_Init(const Key; KeyBytes: word; var ctx: TXTContext): integer;
{-XTEA key expansion, error if invalid key size}
procedure XT_ECB_Reset(var ctx: TXTContext);
{-Clears ctx fields bLen and Flag}
function XT_ECB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TXTContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in ECB mode}
function XT_ECB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TXTContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in ECB mode}
function XT_OFB_Init(const Key; KeyBits: word; const IV: TXTBlock; var ctx: TXTContext): integer;
{-XTEA key expansion, error if invalid key size, encrypt IV}
procedure XT_OFB_Reset(const IV: TXTBlock; var ctx: TXTContext);
{-Clears ctx fields bLen and Flag, encrypt IV}
function XT_OFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TXTContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in OFB mode}
function XT_OFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TXTContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in OFB mode}
implementation
function XT_DLL_Version; external 'XT_DLL' name 'XT_DLL_Version';
function XT_Init; external 'XT_DLL' name 'XT_Init';
procedure XT_Encrypt; external 'XT_DLL' name 'XT_Encrypt';
procedure XT_Decrypt; external 'XT_DLL' name 'XT_Decrypt';
procedure XT_XorBlock; external 'XT_DLL' name 'XT_XorBlock';
procedure XT_SetFastInit; external 'XT_DLL' name 'XT_SetFastInit';
function XT_GetFastInit; external 'XT_DLL' name 'XT_GetFastInit';
function XT_CBC_Init; external 'XT_DLL' name 'XT_CBC_Init';
procedure XT_CBC_Reset; external 'XT_DLL' name 'XT_CBC_Reset';
function XT_CBC_Encrypt; external 'XT_DLL' name 'XT_CBC_Encrypt';
function XT_CBC_Decrypt; external 'XT_DLL' name 'XT_CBC_Decrypt';
function XT_CFB_Init; external 'XT_DLL' name 'XT_CFB_Init';
procedure XT_CFB_Reset; external 'XT_DLL' name 'XT_CFB_Reset';
function XT_CFB_Encrypt; external 'XT_DLL' name 'XT_CFB_Encrypt';
function XT_CFB_Decrypt; external 'XT_DLL' name 'XT_CFB_Decrypt';
function XT_CTR_Init; external 'XT_DLL' name 'XT_CTR_Init';
procedure XT_CTR_Reset; external 'XT_DLL' name 'XT_CTR_Reset';
function XT_CTR_Encrypt; external 'XT_DLL' name 'XT_CTR_Encrypt';
function XT_CTR_Decrypt; external 'XT_DLL' name 'XT_CTR_Decrypt';
function XT_SetIncProc; external 'XT_DLL' name 'XT_SetIncProc';
procedure XT_IncMSBFull; external 'XT_DLL' name 'XT_IncMSBFull';
procedure XT_IncLSBFull; external 'XT_DLL' name 'XT_IncLSBFull';
procedure XT_IncMSBPart; external 'XT_DLL' name 'XT_IncMSBPart';
procedure XT_IncLSBPart; external 'XT_DLL' name 'XT_IncLSBPart';
function XT_ECB_Init; external 'XT_DLL' name 'XT_ECB_Init';
procedure XT_ECB_Reset; external 'XT_DLL' name 'XT_ECB_Reset';
function XT_ECB_Encrypt; external 'XT_DLL' name 'XT_ECB_Encrypt';
function XT_ECB_Decrypt; external 'XT_DLL' name 'XT_ECB_Decrypt';
function XT_OFB_Init; external 'XT_DLL' name 'XT_OFB_Init';
procedure XT_OFB_Reset; external 'XT_DLL' name 'XT_OFB_Reset';
function XT_OFB_Encrypt; external 'XT_DLL' name 'XT_OFB_Encrypt';
function XT_OFB_Decrypt; external 'XT_DLL' name 'XT_OFB_Decrypt';
{$define CONST}
{$i xt_seek.inc}
end.
|
program triangle;
uses crt;
{
//BUT : Fait un triangle
//ENTREE : La taille du triangle
//SORTIE : un triangle de la taille désirée
VAR
i, j, taille : ENTIER
DEBUT
ECRIRE 'Entrez la taille du triangle'
LIRE taille
POUR i DE 1 A taille - 1 FAIRE
DEBUT
POUR j DE 1 A taille FAIRE
SI ((j = 1) OU (j = i)) ALORS
ECRIRE('X')
SINON
SI j < i ALORS ECRIRE('O')
FINSI
FINPOUR
ECRIRE()
FINPOUR
POUR i DE 1 A taille FAIRE ECRIRE('X')
FIN
}
{CONST
taille = 8;}
VAR
i, j, taille : INTEGER;
BEGIN
clrscr;
writeln('Entrez une taille');
readln(taille); //Récupère la taille du triangle
FOR i := 1 TO (taille - 1) DO //Boucle pour écrire les lignes à l'exeption de la dernière
BEGIN
FOR j := 1 TO taille DO //Boucle pour écrire le contenu de la ligne
BEGIN
IF ((j = 1) OR (j = i)) THEN //Si le caractère écris est le premier ou le dernier de la ligne il sera un X
write('X')
ELSE
BEGIN
IF j < i THEN write('O'); //Si la caractère écrit est entre le premier et le dernier il sera un O
END;
END;
writeln(); //Passage à la ligne suivante
END;
FOR i := 1 TO taille DO //Boucle pour écrire la dernière ligne
write('X');
readln();
END.
|
unit Frame.TimeInterval;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DateComboBox, Buttons, GMGlobals,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxScrollBox,
dxSkinsCore, cxLabel, cxTextEdit, cxMaskEdit, cxSplitter, cxColorComboBox, cxMemo, cxProgressBar,
cxDropDownEdit, cxCalendar, dxSkinscxPCPainter, dxBarBuiltInMenu, cxPC, cxTimeEdit, cxRadioGroup,
cxGroupBox, cxSpinEdit, cxCheckBox, cxButtonEdit, cxButtons, cxCheckListBox, cxListBox, cxListView,
cxImage, Vcl.Menus, Vcl.ComCtrls, dxCore, cxDateUtils, dxSkinOffice2010Silver;
type
TfrmSelArchTime = class(TFrame)
dcbDate1: TcxDateEdit;
Label2: TcxLabel;
dcbDate2: TcxDateEdit;
cmbTimeStamp: TcxComboBox;
Label1: TcxLabel;
bPrev: TcxButton;
bNext: TcxButton;
procedure dcbDate1Change(Sender: TObject);
procedure bPrevClick(Sender: TObject);
private
{ Private declarations }
function GetD1(): TDateTime;
function GetD2(): TDateTime;
procedure SetD1(const Value: TDateTime);
procedure SetD2(const Value: TDateTime);
procedure DoDataChanged;
public
{ Public declarations }
OnDateChanged: TNotifyEvent;
property D1: TDateTime read GetD1 write SetD1;
property D2: TDateTime read GetD2 write SetD2;
procedure DelInterval(Interval: int);
function GetInterval(): int;
procedure SetIntervalList(intrv: SetOfInt);
constructor Create(AOwner: TComponent); override;
end;
const
SELINTERVAL_OPEN = 0;
SELINTERVAL_HOUR = 1;
SELINTERVAL_DAY = 2;
SELINTERVAL_WEEK = 3;
SELINTERVAL_MONTH = 4;
SELINTERVAL_QUARTER = 5;
SELINTERVAL_HALFYEAR = 6;
SELINTERVAL_YEAR = 7;
SELINTERVAL_ALWAYS = 8;
SELINTERVAL_ALL: SetOfInt = [SELINTERVAL_OPEN .. SELINTERVAL_ALWAYS];
implementation
uses Math, DateUtils;
{$R *.dfm}
function GetFirstDayOfMonth(T: TDateTime): TDateTime;
var
D, M, Y: WORD;
begin
DecodeDate(T, Y, M, D);
Result := EncodeDate(Y, M, 1);
end;
constructor TfrmSelArchTime.Create(AOwner: TComponent);
begin
inherited;
dcbDate1.Date := Floor(Now());
dcbDate2.Date := dcbDate1.Date + 1;
SetIntervalList([SELINTERVAL_OPEN, SELINTERVAL_DAY, SELINTERVAL_WEEK, SELINTERVAL_MONTH, SELINTERVAL_QUARTER,
SELINTERVAL_HALFYEAR, SELINTERVAL_YEAR, SELINTERVAL_ALWAYS]);
cmbTimeStamp.ItemIndex := 1;
end;
procedure TfrmSelArchTime.dcbDate1Change(Sender: TObject);
var
D: TDateTime;
DD, MM, YY: WORD;
begin
dcbDate1.Enabled := (CmbSelectedObj(cmbTimeStamp) <> SELINTERVAL_ALWAYS);
dcbDate2.Enabled := (CmbSelectedObj(cmbTimeStamp) <> SELINTERVAL_ALWAYS);
if Sender is TDateComboBox then
D := TDateComboBox(Sender).DateTime
else
D := dcbDate1.Date;
case CmbSelectedObj(cmbTimeStamp) of
SELINTERVAL_OPEN:
begin // указанный период
if (Sender = dcbDate1) and (D > dcbDate2.Date) then
dcbDate2.Date := D + 1;
if (Sender = dcbDate2) and (D < dcbDate1.Date) then
dcbDate1.Date := D - 1;
end;
SELINTERVAL_HOUR:
begin // День
if Sender = dcbDate2 then
begin
dcbDate2.Date := Ceil(D / OneHour) * OneHour;
dcbDate1.Date := dcbDate2.Date - OneHour;
end
else
begin
dcbDate1.Date := Floor(D / OneHour) * OneHour;
dcbDate2.Date := dcbDate1.Date + OneHour;
end;
end;
SELINTERVAL_DAY:
begin // День
dcbDate1.Date := Math.Floor(D);
dcbDate2.Date := dcbDate1.Date + 1;
end;
SELINTERVAL_WEEK:
begin // Неделя
dcbDate1.Date := Math.Floor(D) - DayOfTheWeek(D) + 1;
dcbDate2.Date := dcbDate1.Date + 7;
end;
SELINTERVAL_MONTH:
begin // Месяц
dcbDate1.Date := GetFirstDayOfMonth(D);
dcbDate2.Date := IncMonth(dcbDate1.Date);
end;
SELINTERVAL_QUARTER:
begin // Квартал
DecodeDate(D, YY, MM, DD);
dcbDate1.Date := EncodeDate(YY, 3 * ((MM - 1) div 3) + 1, 1);
dcbDate2.Date := IncMonth(dcbDate1.Date, 3);
end;
SELINTERVAL_HALFYEAR:
begin // Полгода
DecodeDate(D, YY, MM, DD);
if MM < 7 then
MM := 1
else
MM := 7;
dcbDate1.Date := EncodeDate(YY, MM, 1);
dcbDate2.Date := IncMonth(dcbDate1.Date, 6);
end;
SELINTERVAL_YEAR:
begin // Год
DecodeDate(D, YY, MM, DD);
dcbDate1.Date := EncodeDate(YY, 1, 1);
dcbDate2.Date := EncodeDate(YY + 1, 1, 1);
end;
end;
DoDataChanged();
end;
function TfrmSelArchTime.GetD1: TDateTime;
begin
if CmbSelectedObj(cmbTimeStamp) <> SELINTERVAL_ALWAYS then
Result := dcbDate1.Date
else
Result := EncodeDate(1970, 1, 1);
if not(CmbSelectedObj(cmbTimeStamp) in [SELINTERVAL_OPEN, SELINTERVAL_HOUR]) then
Result := Floor(Result);
end;
function TfrmSelArchTime.GetD2: TDateTime;
begin
if CmbSelectedObj(cmbTimeStamp) <> SELINTERVAL_ALWAYS then
Result := dcbDate2.Date
else
Result := EncodeDate(2050, 1, 1);
if not(CmbSelectedObj(cmbTimeStamp) in [SELINTERVAL_OPEN, SELINTERVAL_HOUR]) then
Result := Floor(Result);
end;
procedure TfrmSelArchTime.bPrevClick(Sender: TObject);
var
D: int;
diff: double;
begin
D := IfThen(Sender = bPrev, -1, 1);
case CmbSelectedObj(cmbTimeStamp) of
SELINTERVAL_OPEN:
begin
diff := D * (D2 - D1);
dcbDate1.Date := dcbDate1.Date + diff;
dcbDate2.Date := dcbDate1.Date + diff;
end;
SELINTERVAL_DAY:
dcbDate1.Date := dcbDate1.Date + D;
SELINTERVAL_WEEK:
dcbDate1.Date := dcbDate1.Date + D * 7;
SELINTERVAL_MONTH:
dcbDate1.Date := IncMonth(dcbDate1.Date, D);
SELINTERVAL_QUARTER:
dcbDate1.Date := IncMonth(dcbDate1.Date, D * 3);
SELINTERVAL_HALFYEAR:
dcbDate1.Date := IncMonth(dcbDate1.Date, D * 6);
SELINTERVAL_YEAR:
dcbDate1.Date := IncMonth(dcbDate1.Date, D * 12);
end;
if Assigned(cmbTimeStamp.Properties.OnChange) then
cmbTimeStamp.Properties.OnChange(cmbTimeStamp);
end;
procedure TfrmSelArchTime.DelInterval(Interval: int);
var
n: int;
begin
n := cmbTimeStamp.Properties.Items.IndexOfObject(TObject(Interval));
if n >= 0 then
cmbTimeStamp.Properties.Items.Delete(n);
end;
function TfrmSelArchTime.GetInterval: int;
begin
Result := CmbSelectedObj(cmbTimeStamp);
end;
procedure TfrmSelArchTime.SetIntervalList(intrv: SetOfInt);
var
n, n1: int;
begin
n := GetInterval();
cmbTimeStamp.Properties.Items.Clear();
if (SELINTERVAL_OPEN in intrv) or (intrv = []) then
cmbTimeStamp.Properties.Items.AddObject('Указать ...', TObject(SELINTERVAL_OPEN));
if SELINTERVAL_DAY in intrv then
cmbTimeStamp.Properties.Items.AddObject('Час', TObject(SELINTERVAL_HOUR));
if SELINTERVAL_DAY in intrv then
cmbTimeStamp.Properties.Items.AddObject('Сутки', TObject(SELINTERVAL_DAY));
if SELINTERVAL_WEEK in intrv then
cmbTimeStamp.Properties.Items.AddObject('Неделя', TObject(SELINTERVAL_WEEK));
if SELINTERVAL_MONTH in intrv then
cmbTimeStamp.Properties.Items.AddObject('Месяц', TObject(SELINTERVAL_MONTH));
if SELINTERVAL_QUARTER in intrv then
cmbTimeStamp.Properties.Items.AddObject('Квартал', TObject(SELINTERVAL_QUARTER));
if SELINTERVAL_HALFYEAR in intrv then
cmbTimeStamp.Properties.Items.AddObject('Полгода', TObject(SELINTERVAL_HALFYEAR));
if SELINTERVAL_YEAR in intrv then
cmbTimeStamp.Properties.Items.AddObject('Год', TObject(SELINTERVAL_YEAR));
if SELINTERVAL_ALWAYS in intrv then
cmbTimeStamp.Properties.Items.AddObject('Всегда', TObject(SELINTERVAL_ALWAYS));
n1 := cmbTimeStamp.Properties.Items.IndexOfObject(TObject(n));
if n1 >= 0 then
cmbTimeStamp.ItemIndex := n1
else
cmbTimeStamp.ItemIndex := 0;
if Assigned(cmbTimeStamp.Properties.OnChange) then
cmbTimeStamp.Properties.OnChange(cmbTimeStamp);
end;
procedure TfrmSelArchTime.SetD1(const Value: TDateTime);
begin
dcbDate1.Date := Value;
dcbDate1Change(dcbDate1);
end;
procedure TfrmSelArchTime.SetD2(const Value: TDateTime);
begin
dcbDate2.Date := Value;
dcbDate1Change(dcbDate2);
end;
procedure TfrmSelArchTime.DoDataChanged;
begin
if Assigned(OnDateChanged) then
OnDateChanged(self);
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, xmldom, XMLIntf, msxmldom, XMLDoc, StdCtrls;
type
TForm2 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
var
XmlFile : TXMLDocument;
MainNode, Attr, Table, Row: IXMLNode;
i, k : Integer;
XMLPath : string;
begin
XMLPath := '2018.10.30.xls';
XmlFile := TXMLDocument.Create(Application);
try
try
XmlFile.LoadFromFile(XMLPath);
XmlFile.Active := True;
MainNode := XmlFile.DocumentElement;
Memo1.Lines.Add(intToStr(MainNode.ChildNodes.Count));
for I := 0 to MainNode.ChildNodes.Count - 1 do
begin
Attr := MainNode.ChildNodes[i].AttributeNodes.FindNode('Name');
if attr <> nil then
begin
if Attr.Text = 'RESUMO DA FATURA' then
begin
Table := MainNode.ChildNodes[i].ChildNodes.FindNode('Table');
if Table <> nil then
begin
for k := 0 to Table.ChildNodes.Count - 1 do
begin
Row := Table.ChildNodes[k];
if Row.ChildNodes.Count > 0 then
begin
if Row.ChildNodes[0].ChildNodes[0].Text = 'Número' then
Memo1.Lines.Add(Row.ChildNodes[1].ChildNodes[0].Text);
if Row.ChildNodes[0].ChildNodes[0].Text = 'Emissão' then
Memo1.Lines.Add(Row.ChildNodes[1].ChildNodes[0].Text);
if Row.ChildNodes[0].ChildNodes[0].Text = 'Vencimento' then
Memo1.Lines.Add(Row.ChildNodes[1].ChildNodes[0].Text);
if Row.ChildNodes[0].ChildNodes[0].Text = 'Valor' then
Memo1.Lines.Add(Row.ChildNodes[1].ChildNodes[0].Text);
end;
end;
end;
end else if Attr.Text = 'PASSAGENS PEDÁGIO' then
begin
Table := MainNode.ChildNodes[i].ChildNodes.FindNode('Table');
if Table <> nil then
begin
for k := 0 to Table.ChildNodes.Count - 1 do
begin
Row := Table.ChildNodes[k];
if Row.ChildNodes.Count > 0 then
begin
Memo1.Lines.Add(Row.ChildNodes[0].ChildNodes[0].Text);
Memo1.Lines.Add(Row.ChildNodes[5].ChildNodes[0].Text);
Memo1.Lines.Add(Row.ChildNodes[6].ChildNodes[0].Text);
Memo1.Lines.Add(Row.ChildNodes[7].ChildNodes[0].Text);
Memo1.Lines.Add(Row.ChildNodes[8].ChildNodes[0].Text);
Memo1.Lines.Add(Row.ChildNodes[9].ChildNodes[0].Text);
Memo1.Lines.Add('-------------------------------------');
end;
end;
end;
end;
end;
end;
except on E : Exception do
showMessage(E.Message);
end;
finally
FreeAndNil(XmlFile);
end;
end;
end.
|
unit ltrapi;
interface
uses SysUtils, ltrapitypes, ltrapidefine;
const
LTR_OK = 0; // Выполнено без ошибок.
LTR_ERROR_UNKNOWN = -1; // Неизвестная ошибка.
LTR_ERROR_PARAMETERS = -2; // Ошибка входных параметров.
LTR_ERROR_PARAMETRS = LTR_ERROR_PARAMETERS;
LTR_ERROR_MEMORY_ALLOC = -3; // Ошибка динамического выделения памяти.
LTR_ERROR_OPEN_CHANNEL = -4; // Ошибка открытия канала обмена с сервером.
LTR_ERROR_OPEN_SOCKET = -5; // Ошибка открытия сокета.
LTR_ERROR_CHANNEL_CLOSED = -6; // Ошибка. Канал обмена с сервером не создан.
LTR_ERROR_SEND = -7; // Ошибка отправления данных.
LTR_ERROR_RECV = -8; // Ошибка приема данных.
LTR_ERROR_EXECUTE = -9; // Ошибка обмена с крейт-контроллером.
LTR_WARNING_MODULE_IN_USE = -10; // Канал обмена с сервером создан в текущей программе
// и в какой-то еще
LTR_ERROR_NOT_CTRL_CHANNEL = -11; // Номер канала для этой операции должен быть CC_CONTROL
LTR_ERROR_SRV_INVALID_CMD = -12; // Команда не поддерживается сервером
LTR_ERROR_SRV_INVALID_CMD_PARAMS = -13; // Сервер не поддерживает указанные параметры команды
LTR_ERROR_INVALID_CRATE = -14; // Указанный крейт не найден
LTR_ERROR_EMPTY_SLOT = -15; // В указанном слоте отсутствует модуль
LTR_ERROR_UNSUP_CMD_FOR_SRV_CTL = -16; // Команда не поддерживается управляющим каналом сервера
LTR_ERROR_INVALID_IP_ENTRY = -17; // Неверная запись сетевого адреса крейта
LTR_ERROR_NOT_IMPLEMENTED = -18; // Данная возможность не реализована
LTR_ERROR_INVALID_MODULE_DESCR = -40; // Неверный описатель модуля
LTR_ERROR_INVALID_MODULE_SLOT = -41; // Указан неверный слот для модуля
LTR_ERROR_INVALID_MODULE_ID = -42; // Неверный ID-модуля в ответе на сброс
LTR_ERROR_NO_RESET_RESPONSE = -43; // Нет ответа на команду сброс
LTR_ERROR_SEND_INSUFFICIENT_DATA = -44; // Передано данных меньше, чем запрашивалось
LTR_ERROR_RECV_INSUFFICIENT_DATA = -45;
LTR_ERROR_NO_CMD_RESPONSE = -46; // Нет ответа на команду сброс
LTR_ERROR_INVALID_CMD_RESPONSE = -47; // Пришел неверный ответ на команду
LTR_ERROR_INVALID_RESP_PARITY = -48; // Неверный бит четности в пришедшем ответе
LTR_ERROR_INVALID_CMD_PARITY = -49; // Ошибка четности переданной команды
LTR_ERROR_UNSUP_BY_FIRM_VER = -50; // Возможность не поддерживается данной версией прошивки
LTR_ERROR_MODULE_STARTED = -51; // Модуль уже запущен
LTR_ERROR_MODULE_STOPPED = -52; // Модуль остановлен
LTR_ERROR_RECV_OVERFLOW = -53; // Произошло переполнение буфера
LTR_ERROR_FIRM_FILE_OPEN = -54; // Ошибка открытия файла прошивки
LTR_ERROR_FIRM_FILE_READ = -55; // Ошибка чтения файла прошивки
LTR_ERROR_FIRM_FILE_FORMAT = -56; // Ошибка формата файла прошивки
LTR_ERROR_FPGA_LOAD_READY_TOUT = -57; // Превышен таймаут ожидания готовности ПЛИС к загрузке
LTR_ERROR_FPGA_LOAD_DONE_TOUT = -58; // Превышен таймаут ожидания перехода ПЛИС в рабочий режим
LTR_ERROR_FPGA_IS_NOT_LOADED = -59; // Прошивка ПЛИС не загружена
LTR_ERROR_FLASH_INVALID_ADDR = -60; // Неверный адрес Flash-памяти
LTR_ERROR_FLASH_WAIT_RDY_TOUT = -61; // Превышен таймаут ожидания завершения записи/стирания Flash-памяти
LTR_ERROR_FIRSTFRAME_NOTFOUND = -62; // First frame in card data stream not found
LTR_ERROR_CARDSCONFIG_UNSUPPORTED = -63;
LTR_ERROR_FLASH_OP_FAILED = -64; // Ошибка выполненя операции flash-памятью
LTR_ERROR_FLASH_NOT_PRESENT = -65; // Flash-память не обнаружена
LTR_ERROR_FLASH_UNSUPPORTED_ID = -66; // Обнаружен неподдерживаемый тип flash-памяти
LTR_ERROR_FLASH_UNALIGNED_ADDR = -67; // Невыровненный адрес flash-памяти
LTR_ERROR_FLASH_VERIFY = -68; // Ошибка при проверки записанных данных во flash-память
LTR_ERROR_FLASH_UNSUP_PAGE_SIZE = -69; // Установлен неподдерживаемый размер страницы flash-памяти
LTR_ERROR_FLASH_INFO_NOT_PRESENT = -70; // Отсутствует информация о модуле во Flash-памяти
LTR_ERROR_FLASH_INFO_UNSUP_FORMAT = -71; // Неподдерживаемый формат информации о модуле во Flash-памяти
LTR_ERROR_FLASH_SET_PROTECTION = -72; // Не удалось установить защиту Flash-памяти
LTR_ERROR_FPGA_NO_POWER = -73; // Нет питания микросхемы ПЛИС
LTR_ERROR_FPGA_INVALID_STATE = -74; // Не действительное состояние загрузки ПЛИС
LTR_ERROR_FPGA_ENABLE = -75; // Не удалось перевести ПЛИС в разрешенное состояние
LTR_ERROR_FPGA_AUTOLOAD_TOUT = -76; // Истекло время ожидания автоматической загрузки ПЛИС
LTR_ERROR_PROCDATA_UNALIGNED = -77; // Обрабатываемые данные не выравнены на границу кадра
LTR_ERROR_PROCDATA_CNTR = -78; // Ошибка счетчика в обрабатываемых данных
LTR_ERROR_PROCDATA_CHNUM = -79; // Неверный номер канала в обрабатываемых данных
LTR_ERROR_PROCDATA_WORD_SEQ = -80; // Неверная последовательность слов в обрабатываемых данных
type
// Значения для управления ножками процессора, доступными для пользовательского программирования
en_LTR_UserIoCfg=(LTR_USERIO_DIGIN1 =1,// ножка является входом и подключена к DIGIN1
LTR_USERIO_DIGIN2 = 2, // ножка является входом и подключена к DIGIN2
LTR_USERIO_DIGOUT = 0, // ножка является выходом (подключение см. en_LTR_DigOutCfg)
LTR_USERIO_DEFAULT = LTR_USERIO_DIGOUT);
// Значения для управления выходами DIGOUTx
en_LTR_DigOutCfg=(
LTR_DIGOUT_CONST0 = $00, // постоянный уровень логического "0"
LTR_DIGOUT_CONST1 = $01, // постоянный уровень логической "1"
LTR_DIGOUT_USERIO0 = $02, // выход подключен к ножке userio0 (PF1 в рев. 0, PF1 в рев. 1)
LTR_DIGOUT_USERIO1 = $03, // выход подключен к ножке userio1 (PG13)
LTR_DIGOUT_DIGIN1 = $04, // выход подключен ко входу DIGIN1
LTR_DIGOUT_DIGIN2 = $05, // выход подключен ко входу DIGIN2
LTR_DIGOUT_START = $06, // на выход подаются метки "СТАРТ"
LTR_DIGOUT_SECOND = $07, // на выход подаются метки "СЕКУНДА"
LTR_DIGOUT_IRIG = $08, // контроль сигналов точного времени IRIG (digout1: готовность, digout2: секунда)
LTR_DIGOUT_DEFAULT = LTR_DIGOUT_CONST0
);
// Значения для управления метками "СТАРТ" и "СЕКУНДА"
en_LTR_MarkMode=(
LTR_MARK_OFF = $00, // метка отключена
LTR_MARK_EXT_DIGIN1_RISE = $01, // метка по фронту DIGIN1
LTR_MARK_EXT_DIGIN1_FALL = $02, // метка по спаду DIGIN1
LTR_MARK_EXT_DIGIN2_RISE = $03, // метка по фронту DIGIN2
LTR_MARK_EXT_DIGIN2_FALL = $04, // метка по спаду DIGIN2
LTR_MARK_INTERNAL = $05, // внутренняя генерация метки
LTR_MARK_NAMUR1_LO2HI = 8, // по сигналу NAMUR1 (START_IN), возрастание тока
LTR_MARK_NAMUR1_HI2LO = 9, // по сигналу NAMUR1 (START_IN), спад тока
LTR_MARK_NAMUR2_LO2HI = 10, // по сигналу NAMUR2 (M1S_IN), возрастание тока
LTR_MARK_NAMUR2_HI2LO = 11, // по сигналу NAMUR2 (M1S_IN), спад тока
{ Источник метки - декодер сигналов точного времени IRIG-B006
IRIG может использоваться только для меток "СЕКУНДА", для "СТАРТ" игнорируется }
LTR_MARK_SEC_IRIGB_DIGIN1 = 16, // со входа DIGIN1, прямой сигнал
LTR_MARK_SEC_IRIGB_nDIGIN1 = 17, // со входа DIGIN1, инвертированный сигнал
LTR_MARK_SEC_IRIGB_DIGIN2 = 18, // со входа DIGIN2, прямой сигнал
LTR_MARK_SEC_IRIGB_nDIGIN2 = 19 // со входа DIGIN2, инвертированный сигнал
);
{$A4}
TLTR=record
saddr:LongWord; // сетевой адрес сервера
sport:word; // сетевой порт сервера
csn:SERNUMtext; // серийный номер крейта
cc:WORD; // номер канала крейта
flags:LongWord; // флаги состояния канала
tmark:LongWord; // последняя принятая метка времени
internal:Pointer; // указатель на канал
end;
pTLTR = ^TLTR;
TLTR_CONFIG=record
userio:array[0..3]of WORD;
digout:array[0..1]of WORD;
digout_en:WORD;
end;
Type t_crate_ipentry_array = array[0..0] of TIPCRATE_ENTRY;
Type p_crate_ipentry_array = ^t_crate_ipentry_array;
{$A+}
Function LTR_Init(out ltr: TLTR):integer; overload;
Function LTR_Open(var ltr: TLTR):integer; overload;
Function LTR_Close(var ltr: TLTR):integer; overload;
Function LTR_IsOpened(var ltr: TLTR):integer; overload;
//заполнения поля с серийным номером в структуре TLTR (используется перед открытием)
Procedure LTR_FillSerial(var ltr: TLTR; csn : string);
Function LTR_GetCrates(var ltr: TLTR; var csn: array of string; out crates_cnt: Integer):integer; overload;
Function LTR_GetCrateModules(var ltr: TLTR; var mids: array of Word):integer; overload;
Function LTR_GetCrateInfo(var ltr:TLTR; out CrateInfo:TCRATE_INFO):integer; overload;
Function LTR_Config(var ltr:TLTR; var conf : TLTR_CONFIG):integer; overload;
Function LTR_StartSecondMark(var ltr:TLTR; mode:en_LTR_MarkMode):integer; overload;
Function LTR_StopSecondMark(var ltr:TLTR):integer; overload;
Function LTR_MakeStartMark(var ltr:TLTR; mode:en_LTR_MarkMode):integer; overload;
Function LTR_AddIPCrate(var ltr: TLTR; ip_addr: LongWord; flags: LongWord; permanent:LongBool):integer; overload;
Function LTR_DeleteIPCrate(var ltr: TLTR; ip_addr: LongWord; permanent:LongBool):integer; overload;
Function LTR_ConnectIPCrate(var ltr: TLTR; ip_addr:LongWord):integer; overload;
Function LTR_DisconnectIPCrate(var ltr: TLTR; ip_addr:LongWord):integer; overload;
Function LTR_ConnectAllAutoIPCrates(var ltr: TLTR):integer; overload;
Function LTR_DisconnectAllIPCrates(var ltr: TLTR):integer; overload;
Function LTR_SetIPCrateFlags(var ltr: TLTR; ip_addr:LongWord; new_flags:LongWord; permanent:LongBool):integer; overload;
Function LTR_GetListOfIPCrates(var ltr: TLTR; ip_net : LongWord; ip_mask:LongWord;
out entries_found: LongWord;
out entries_returned: LongWord;
out info_array: array of TIPCRATE_ENTRY):integer;
Function LTR_GetLogLevel(var ltr: TLTR; out level:integer):integer; overload;
Function LTR_SetLogLevel(var ltr: TLTR; level:integer; permanent: LongBool):integer; overload;
Function LTR_ServerRestart(var ltr: TLTR):integer; overload;
Function LTR_ServerShutdown(var ltr: TLTR):integer; overload;
Function LTR_SetTimeout(var ltr: TLTR; ms:LongWord):integer; overload;
Function LTR_SetServerProcessPriority(var ltr: TLTR; Priority:LongWord):integer; overload;
Function LTR_GetServerProcessPriority(var ltr: TLTR; out Priority:LongWord):integer; overload;
Function LTR_GetServerVersion(var ltr: TLTR; out version:LongWord):integer; overload;
Function LTR_GetLastUnixTimeMark(var ltr: TLTR; out unixtime:UInt64):integer; overload;
Function LTR_CrateGetArray(var ltr: TLTR; address : LongWord; out buf: array of Byte; size : LongWord): Integer;
Function LTR_CratePutArray(var ltr: TLTR; address : LongWord; const buf: array of Byte; size : LongWord): Integer;
{$IFNDEF LTRAPI_DISABLE_COMPAT_DEFS}
// Функции для внутреннего применения
Function LTR__GenericCtlFunc(
TLTR:Pointer; // дескриптор LTR
request_buf:Pointer; // буфер с запросом
request_size:LongWord; // длина запроса (в байтах)
reply_buf:Pointer; // буфер для ответа (или NULL)
reply_size:LongWord; // длина ответа (в байтах)
ack_error_code:integer; // какая ошибка, если ack не GOOD (0 = не использовать ack)
timeout:LongWord // таймаут, мс
):integer; {$I ltrapi_callconvention};
// Функции общего назначения
Function LTR_Init(ltr:pTLTR):integer; {$I ltrapi_callconvention}; overload;
Function LTR_Open(ltr:pTLTR):integer; {$I ltrapi_callconvention}; overload;
Function LTR_Close(ltr:pTLTR):integer; {$I ltrapi_callconvention}; overload;
Function LTR_IsOpened(ltr:pTLTR):integer; {$I ltrapi_callconvention}; overload;
Function LTR_Recv(ltr:pTLTR; dataDWORD:Pointer; tmarkDWORD:POINTER; size:LongWord; timeout:LongWord):integer; {$I ltrapi_callconvention};
Function LTR_Send(ltr:pTLTR; dataDWORD:Pointer; size:LongWord; timeout:LongWord):integer; {$I ltrapi_callconvention};
Function LTR_GetCrates(ltr:pTLTR; csnBYTE:Pointer):integer; {$I ltrapi_callconvention}; overload;
Function LTR_GetCrateModules(ltr:pTLTR; midWORD:Pointer):integer; {$I ltrapi_callconvention}; overload;
Function LTR_GetCrateRawData(ltr:pTLTR; dataDWORD:Pointer; tmarkDWORD:Pointer; size:LongWord; timeout:LongWord):integer; {$I ltrapi_callconvention};
Function LTR_GetErrorString(error:integer):string;
Function LTR_GetCrateInfo(ltr:pTLTR; CrateInfoTCRATE_INFO:Pointer):integer; {$I ltrapi_callconvention}; overload;
Function LTR_Config(ltr:pTLTR; confTLTR_CONFIG:Pointer):integer; {$I ltrapi_callconvention}; overload;
Function LTR_StartSecondMark(ltr:pTLTR; mode:en_LTR_MarkMode):integer; {$I ltrapi_callconvention}; overload;
Function LTR_StopSecondMark(ltr:pTLTR):integer; {$I ltrapi_callconvention}; overload;
Function LTR_MakeStartMark(ltr:pTLTR; mode:en_LTR_MarkMode):integer; {$I ltrapi_callconvention}; overload;
Function LTR_AddIPCrate(ltr:pTLTR; ip_addr:LongWord; flags:LongWord; permanent:LongBool):integer; {$I ltrapi_callconvention}; overload;
Function LTR_DeleteIPCrate(ltr:pTLTR; ip_addr:LongWord; permanent:LongBool):integer; {$I ltrapi_callconvention}; overload;
Function LTR_ConnectIPCrate(ltr:pTLTR; ip_addr:LongWord):integer; {$I ltrapi_callconvention}; overload;
Function LTR_DisconnectIPCrate(ltr:pTLTR; ip_addr:LongWord):integer; {$I ltrapi_callconvention}; overload;
Function LTR_ConnectAllAutoIPCrates(ltr:pTLTR):integer; {$I ltrapi_callconvention}; overload;
Function LTR_DisconnectAllIPCrates(ltr:pTLTR):integer; {$I ltrapi_callconvention}; overload;
Function LTR_SetIPCrateFlags(ltr:pTLTR; ip_addr:LongWord; new_flags:LongWord; permanent:LongBool):integer; {$I ltrapi_callconvention}; overload;
Function LTR_GetLogLevel(ltr:pTLTR; levelINT:Pointer):integer; {$I ltrapi_callconvention}; overload;
Function LTR_SetLogLevel(ltr:pTLTR; level:integer; permanent:LongBool):integer; {$I ltrapi_callconvention}; overload;
Function LTR_ServerRestart(ltr:pTLTR):integer; {$I ltrapi_callconvention}; overload;
Function LTR_ServerShutdown(ltr:pTLTR):integer; {$I ltrapi_callconvention}; overload;
Function LTR_SetTimeout(ltr:pTLTR; ms:LongWord):integer; {$I ltrapi_callconvention}; overload;
Function LTR_SetServerProcessPriority(ltr:pTLTR; Priority:LongWord):integer; {$I ltrapi_callconvention}; overload;
Function LTR_GetServerProcessPriority(ltr:pTLTR; Priority:Pointer):integer; {$I ltrapi_callconvention}; overload;
Function LTR_GetServerVersion(ltr:pTLTR; version:Pointer):integer; {$I ltrapi_callconvention}; overload;
Function LTR_GetLastUnixTimeMark(ltr:pTLTR; unixtime:Pointer):integer;{$I ltrapi_callconvention}; overload;
Function LTR_GetIPCrateDiscoveryMode(ltr:pTLTR; enabledBOOL:Pointer; autoconnectBOOL:Pointer):integer; {$I ltrapi_callconvention};
Function LTR_SetIPCrateDiscoveryMode(ltr:pTLTR; enabled:LongBool; autoconnect:LongBool; permanent:LongBool):integer; {$I ltrapi_callconvention};
{$ENDIF}
Implementation
Type t_crate_mids_array = array[0..MODULE_MAX-1] of Word;
Type p_crate_mids_array = ^t_crate_mids_array;
{$IFNDEF LTRAPI_DISABLE_COMPAT_DEFS}
Function LTR__GenericCtlFunc(TLTR:Pointer;request_buf:Pointer;request_size:LongWord;reply_buf:Pointer;reply_size:LongWord;ack_error_code:integer;timeout:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_Init(ltr:pTLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_Open(ltr:pTLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_Close(ltr:pTLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_IsOpened(ltr:pTLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_Recv(ltr:pTLTR; dataDWORD:Pointer; tmarkDWORD:POINTER; size:LongWord; timeout:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_Send(ltr:pTLTR; dataDWORD:Pointer; size:LongWord; timeout:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_GetCrates(ltr:pTLTR; csnBYTE:Pointer):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_GetCrateModules(ltr:pTLTR; midWORD:Pointer):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_SetServerProcessPriority(ltr:pTLTR; Priority:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_GetCrateRawData(ltr:pTLTR; dataDWORD:Pointer; tmarkDWORD:Pointer; size:LongWord; timeout:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi';
//Function LTR_GetErrorString(error:integer):string; external 'ltrapi';
Function _get_err_str(err : integer) : PAnsiChar; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_GetErrorString';
Function LTR_GetCrateInfo(ltr:pTLTR; CrateInfoTCRATE_INFO:Pointer):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_Config(ltr:pTLTR; confTLTR_CONFIG:Pointer):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_StartSecondMark(ltr:pTLTR; mode:en_LTR_MarkMode):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_StopSecondMark(ltr:pTLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_MakeStartMark(ltr:pTLTR; mode:en_LTR_MarkMode):integer; {$I ltrapi_callconvention}; external 'ltrapi';
//Function LTR_GetListOfIPCrates(ltr:pTLTR; max_entries:DWORD; ip_net:DWORD; ip_mask:DWORD; entries_foundDWORD:Pointer; entries_returnedDWORD:Pointer; var info_array:TIPCRATE_ENTRY):integer; external 'ltrapi';
Function LTR_AddIPCrate(ltr:pTLTR; ip_addr:LongWord; flags:LongWord; permanent:LongBool):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_DeleteIPCrate(ltr:pTLTR; ip_addr:LongWord; permanent:LongBool):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_ConnectIPCrate(ltr:pTLTR; ip_addr:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_DisconnectIPCrate(ltr:pTLTR; ip_addr:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_ConnectAllAutoIPCrates(ltr:pTLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_DisconnectAllIPCrates(ltr:pTLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_SetIPCrateFlags(ltr:pTLTR; ip_addr:LongWord; new_flags:LongWord; permanent:LongBool):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_GetIPCrateDiscoveryMode(ltr:pTLTR; enabledBOOL:Pointer; autoconnectBOOL:Pointer):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_SetIPCrateDiscoveryMode(ltr:pTLTR; enabled:LongBool; autoconnect:LongBool; permanent:LongBool):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_GetLogLevel(ltr:pTLTR; levelINT:Pointer):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_SetLogLevel(ltr:pTLTR; level:integer; permanent:LongBool):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_ServerRestart(ltr:pTLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_ServerShutdown(ltr:pTLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_SetTimeout(ltr:pTLTR; ms:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_GetServerProcessPriority(ltr:pTLTR; Priority:Pointer):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_GetServerVersion(ltr:pTLTR; version:Pointer):integer; {$I ltrapi_callconvention}; external 'ltrapi';
Function LTR_GetLastUnixTimeMark(ltr:pTLTR; unixtime:Pointer):integer; {$I ltrapi_callconvention}; external 'ltrapi';
{$ENDIF}
Function priv_Init(out ltr: TLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_Init';
Function priv_Open(var ltr: TLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_Open';
Function priv_Close(var ltr: TLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_Close';
Function priv_IsOpened(var ltr: TLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_IsOpened';
Function priv_GetCrates(var ltr: TLTR; csn: PAnsiChar): Integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_GetCrates';
Function priv_GetCrateModules(var ltr: TLTR; mids: p_crate_mids_array):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_GetCrateModules';
Function priv_GetCrateInfo(var ltr:TLTR; out CrateInfo:TCRATE_INFO):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_GetCrateInfo';
Function priv_Config(var ltr:TLTR; var conf : TLTR_CONFIG):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_Config';
Function priv_StartSecondMark(var ltr:TLTR; mode:en_LTR_MarkMode):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_StartSecondMark';
Function priv_StopSecondMark(var ltr:TLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_StopSecondMark';
Function priv_MakeStartMark(var ltr:TLTR; mode:en_LTR_MarkMode):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_StopSecondMark';
Function priv_GetListOfIPCrates(var ltr: TLTR; max_entries:LongWord; ip_net:LongWord; ip_mask:LongWord; out entries_found:LongWord; out entries_returned:LongWord; info_array:p_crate_ipentry_array):integer;{$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_GetListOfIPCrates';
Function priv_AddIPCrate(var ltr: TLTR; ip_addr: LongWord; flags: LongWord; permanent:LongBool):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_AddIPCrate';
Function priv_DeleteIPCrate(var ltr: TLTR; ip_addr: LongWord; permanent:LongBool):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_DeleteIPCrate';
Function priv_ConnectIPCrate(var ltr: TLTR; ip_addr:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_ConnectIPCrate';
Function priv_DisconnectIPCrate(var ltr: TLTR; ip_addr:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_DisconnectIPCrate';
Function priv_ConnectAllAutoIPCrates(var ltr: TLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_ConnectAllAutoIPCrates';
Function priv_DisconnectAllIPCrates(var ltr: TLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_DisconnectAllIPCrates';
Function priv_SetIPCrateFlags(var ltr: TLTR; ip_addr:LongWord; new_flags:LongWord; permanent:LongBool):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_SetIPCrateFlags';
Function priv_GetLogLevel(var ltr: TLTR; out level:integer):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_GetLogLevel';
Function priv_SetLogLevel(var ltr: TLTR; level:integer; permanent: LongBool):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_SetLogLevel';
Function priv_ServerRestart(var ltr: TLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_ServerRestart';
Function priv_ServerShutdown(var ltr: TLTR):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_ServerShutdown';
Function priv_SetTimeout(var ltr: TLTR; ms:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_SetTimeout';
Function priv_SetServerProcessPriority(var ltr: TLTR; Priority:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_SetServerProcessPriority';
Function priv_GetServerProcessPriority(var ltr: TLTR; out Priority:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_GetServerProcessPriority';
Function priv_GetServerVersion(var ltr: TLTR; out version:LongWord):integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_GetServerVersion';
Function priv_GetLastUnixTimeMark(var ltr: TLTR; out unixtime:UInt64):integer;{$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_GetLastUnixTimeMark';
Function priv_CrateGetArray(var ltr: TLTR; address : LongWord; out buf; size : LongWord): Integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_CrateGetArray';
Function priv_CratePutArray(var ltr: TLTR; address : LongWord; const buf; size : LongWord): Integer; {$I ltrapi_callconvention}; external 'ltrapi' name 'LTR_CratePutArray';
Procedure LTR_FillSerial(var ltr: TLTR; csn : string);
var
i: Integer;
begin
for i:=0 to SERIAL_NUMBER_SIZE-1 do //устанавливаем серийный номер крейта
begin
if i < Length(csn) then
begin
ltr.csn[i] := AnsiChar(csn[i+1]);
end
else
begin
ltr.csn[i] := AnsiChar(0);
end;
end;
end;
Function LTR_Init(out ltr: TLTR):integer; overload;
begin
LTR_Init := priv_Init(ltr);
end;
Function LTR_Open(var ltr: TLTR):integer; overload;
begin
LTR_Open := priv_Open(ltr);
end;
Function LTR_Close(var ltr: TLTR):integer; overload;
begin
LTR_Close := priv_Close(ltr);
end;
Function LTR_IsOpened(var ltr: TLTR):integer; overload;
begin
LTR_IsOpened := priv_IsOpened(ltr);
end;
Function LTR_GetCrates(var ltr: TLTR; var csn: array of string; out crates_cnt: Integer):integer;
var
serial_array: PAnsiChar;
res,i: Integer;
begin
crates_cnt:=0;
serial_array:=GetMemory(CRATE_MAX*SERIAL_NUMBER_SIZE);
res:= priv_GetCrates(ltr, serial_array);
if res = LTR_OK then
begin
for i:=0 to CRATE_MAX-1 do
begin
if (serial_array[SERIAL_NUMBER_SIZE*i]<> AnsiChar(0)) then //добавляем в список все непустые серийники
begin
if Length(csn) > crates_cnt then
begin
csn[crates_cnt] := string(StrPas(PAnsiChar(@serial_array[SERIAL_NUMBER_SIZE*i])));
end;
crates_cnt:=crates_cnt+1;
end;
end;
end;
FreeMemory(serial_array);
LTR_GetCrates := res;
end;
Function LTR_GetCrateModules(var ltr: TLTR; var mids: array of Word):integer; overload;
var
mid_array: p_crate_mids_array;
res,i: Integer;
begin
mid_array:=GetMemory(MODULE_MAX*2);
res:= priv_GetCrateModules(ltr, mid_array);
if res = LTR_OK then
begin
for i:=0 to Length(mids)-1 do
begin
if (i < MODULE_MAX) then //добавляем в список все непустые серийники
begin
mids[i]:=mid_array^[i];
end
else
begin
mids[i]:=MID_EMPTY;
end;
end;
end;
FreeMemory(mid_array);
LTR_GetCrateModules := res;
end;
Function LTR_GetCrateInfo(var ltr:TLTR; out CrateInfo:TCRATE_INFO):integer; overload;
begin
LTR_GetCrateInfo := priv_GetCrateInfo(ltr, Crateinfo);
end;
Function LTR_Config(var ltr:TLTR; var conf : TLTR_CONFIG):integer; overload;
begin
LTR_Config := priv_Config(ltr, conf);
end;
Function LTR_StartSecondMark(var ltr:TLTR; mode:en_LTR_MarkMode):integer; overload;
begin
LTR_StartSecondMark := priv_StartSecondMark(ltr, mode);
end;
Function LTR_StopSecondMark(var ltr:TLTR):integer; overload;
begin
LTR_StopSecondMark := priv_StopSecondMark(ltr);
end;
Function LTR_MakeStartMark(var ltr:TLTR; mode:en_LTR_MarkMode):integer; overload;
begin
LTR_MakeStartMark := priv_MakeStartMark(ltr, mode);
end;
Function LTR_GetListOfIPCrates(var ltr: TLTR; ip_net : LongWord; ip_mask:LongWord;
out entries_found: LongWord;
out entries_returned: LongWord;
out info_array: array of TIPCRATE_ENTRY):integer;
var
ip_arr: p_crate_ipentry_array;
res, i: Integer;
begin
if Length(info_array) > 0 then
begin
ip_arr:=GetMemory(Length(info_array)*SizeOf(TIPCRATE_ENTRY));
res:= priv_GetListOfIPCrates(ltr, Length(info_array), ip_net, ip_mask,
entries_found, entries_returned, ip_arr);
if res = LTR_OK then
begin
for i:=0 to entries_returned-1 do
info_array[i] := ip_arr^[i];
end;
FreeMemory(ip_arr);
end
else
begin
res:=priv_GetListOfIPCrates(ltr, 0, ip_net, ip_mask, entries_found,
entries_returned, nil);
end;
LTR_GetListOfIPCrates:=res;
end;
Function LTR_AddIPCrate(var ltr: TLTR; ip_addr: LongWord; flags: LongWord; permanent:LongBool):integer; overload;
begin
LTR_AddIPCrate:=priv_AddIPCrate(ltr, ip_addr, flags, permanent);
end;
Function LTR_DeleteIPCrate(var ltr: TLTR; ip_addr: LongWord; permanent:LongBool):integer; overload;
begin
LTR_DeleteIPCrate:=priv_DeleteIPCrate(ltr, ip_addr, permanent);
end;
Function LTR_ConnectIPCrate(var ltr: TLTR; ip_addr:LongWord):integer; overload;
begin
LTR_ConnectIPCrate:=priv_ConnectIPCrate(ltr, ip_addr);
end;
Function LTR_DisconnectIPCrate(var ltr: TLTR; ip_addr:LongWord):integer; overload;
begin
LTR_DisconnectIPCrate:=priv_DisconnectIPCrate(ltr, ip_addr);
end;
Function LTR_ConnectAllAutoIPCrates(var ltr: TLTR):integer; overload;
begin
LTR_ConnectAllAutoIPCrates:=priv_ConnectAllAutoIPCrates(ltr);
end;
Function LTR_DisconnectAllIPCrates(var ltr: TLTR):integer; overload;
begin
LTR_DisconnectAllIPCrates:=priv_DisconnectAllIPCrates(ltr);
end;
Function LTR_SetIPCrateFlags(var ltr: TLTR; ip_addr:LongWord; new_flags:LongWord; permanent:LongBool):integer; overload;
begin
LTR_SetIPCrateFlags:=priv_SetIPCrateFlags(ltr, ip_addr, new_flags, permanent);
end;
Function LTR_GetLogLevel(var ltr: TLTR; out level:integer):integer; overload;
begin
LTR_GetLogLevel:=priv_GetLogLevel(ltr, level);
end;
Function LTR_SetLogLevel(var ltr: TLTR; level:integer; permanent: LongBool):integer; overload;
begin
LTR_SetLogLevel:=priv_SetLogLevel(ltr, level, permanent);
end;
Function LTR_ServerRestart(var ltr: TLTR):integer; overload;
begin
LTR_ServerRestart:=priv_ServerRestart(ltr);
end;
Function LTR_ServerShutdown(var ltr: TLTR):integer; overload;
begin
LTR_ServerShutdown:=priv_ServerShutdown(ltr);
end;
Function LTR_SetTimeout(var ltr: TLTR; ms:LongWord):integer; overload;
begin
LTR_SetTimeout:=priv_SetTimeout(ltr, ms);
end;
Function LTR_SetServerProcessPriority(var ltr: TLTR; Priority:LongWord):integer; overload;
begin
LTR_SetServerProcessPriority:=priv_SetServerProcessPriority(ltr, priority);
end;
Function LTR_GetServerProcessPriority(var ltr: TLTR; out Priority:LongWord):integer; overload;
begin
LTR_GetServerProcessPriority:=priv_GetServerProcessPriority(ltr, priority);
end;
Function LTR_GetServerVersion(var ltr: TLTR; out version:LongWord):integer; overload;
begin
LTR_GetServerVersion:=priv_GetServerVersion(ltr, version);
end;
Function LTR_GetLastUnixTimeMark(var ltr: TLTR; out unixtime:UInt64):integer; overload;
begin
LTR_GetLastUnixTimeMark:=priv_GetLastUnixTimeMark(ltr, unixtime);
end;
Function LTR_GetErrorString(error:integer):string;
begin
LTR_GetErrorString:= string(_get_err_str(error));
end;
Function LTR_CrateGetArray(var ltr: TLTR; address : LongWord; out buf: array of Byte; size : LongWord): Integer;
begin
LTR_CrateGetArray := priv_CrateGetArray(ltr, address, buf, size);
end;
Function LTR_CratePutArray(var ltr: TLTR; address : LongWord; const buf: array of Byte; size : LongWord): Integer;
begin
LTR_CratePutArray := priv_CratePutArray(ltr, address, buf, size);
end;
end.
|
unit edit_database;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, connection_transaction, metadata, DBGrids, sqldb, Dialogs;
function DeleteRecord(ATable: TDBTable; APrimaryKey: integer): integer;
function UpdateRecord(ATable: TDBTable; APrimaryKey: integer; AValues: TVariantDynArray): integer;
function InsertRecord(ATable: TDBTable; APrimaryKey: integer; AValues: TVariantDynArray): integer;
implementation
function DeleteRecord(ATable: TDBTable; APrimaryKey: integer): integer;
begin
Result := 0;
ConTran.CommonSQLQuery.Close;
with ConTran.CommonSQLQuery do begin
SQL.Clear;
SQL.Append('delete from ' + ATable.Name);
SQL.Append('where ' + ATable.Name + '.id = :primary_key');
ParamByName('primary_key').Value := APrimaryKey;
end;
try
ConTran.CommonSQLQuery.ExecSQL;
except
on EIBDatabaseError: Exception do begin
MessageDlg('Невозможно удалить запись.' + #13+#10
+ 'Возможно, она используется в:' + #13+#10
+ TDBTable.TablesUsingTable(ATable), mtError, [mbOk], 0);
Result := 1;
end;
end;
ConTran.DBTransaction.Commit;
end;
function UpdateRecord(ATable: TDBTable; APrimaryKey: integer; AValues: TVariantDynArray): integer;
var
i: integer;
begin
Result := 0;
ConTran.CommonSQLQuery.Close;
with ConTran.CommonSQLQuery.SQL do begin
Clear;
Append('update ' + ATable.Name + ' set');
for i := 1 to High(AValues) do begin
Append(ATable.Fields[i].Name + ' = :value' + IntToStr(i));
Append(',');
end;
Delete(Count - 1);
Append('where ' + ATable.Name + '.id = :primary_key ;');
end;
with ConTran.CommonSQLQuery do begin
for i := 1 to High(AValues) do
ParamByName('value' + IntToStr(i)).Value := AValues[i];
ParamByName('primary_key').Value := APrimaryKey;
end;
try
ConTran.CommonSQLQuery.ExecSQL;
except
on EVariantError: Exception do begin
MessageDlg('Невозможно изменить запись.' + #13 + #10
+ 'Данные введены некорректно.' + #13 + #10
, mtError, [mbOk], 0);
Result := 2;
end;
on EDatabaseError: Exception do begin
MessageDlg('Ошибка.' + #13 + #10
+ 'Возможно, такая запись уже существует.' + #13 + #10
, mtError, [mbOk], 0);
Result := 1;
end;
end;
ConTran.DBTransaction.Commit;
end;
function InsertRecord(ATable: TDBTable; APrimaryKey: integer; AValues: TVariantDynArray): integer;
var
i: integer;
begin
Result := 0;
AValues[0] := APrimaryKey;
ConTran.CommonSQLQuery.Close;
with ConTran.CommonSQLQuery.SQL do begin
Clear;
Append('insert into ' + ATable.Name + ' values');
Append('(');
for i := 0 to High(AValues) do begin
Append(' :value' + IntToStr(i));
Append(',');
end;
Delete(Count - 1);
Append(');');
end;
for i := 0 to High(AValues) do
ConTran.CommonSQLQuery.ParamByName('value'+IntToStr(i)).Value := AValues[i];
try
ConTran.CommonSQLQuery.ExecSQL;
except
on EVariantError: Exception do begin
MessageDlg('Невозможно добавить запись.' + #13 + #10
+ 'Данные введены некорректно.' + #13 + #10
, mtError, [mbOk], 0);
Result := 1;
end;
on EDatabaseError: Exception do begin
MessageDlg('Невозможно добавить запись.' + #13 + #10
+ 'Такая запись уже существует.' + #13 + #10
, mtError, [mbOk], 0);
Result := 2;
end;
end;
ConTran.DBTransaction.Commit;
end;
end.
|
unit ULanguageLoader;
interface
uses SuperObject, WinApi.Windows;
type
TLanguageLoader = class
public
count: Integer;
name: array[0..100] of AnsiString;
lang: array[0..100] of ISuperObject;
jso: TSuperObject;
constructor Create(text: string);
function Find(lang: string):integer;
end;
function WideStringToAnsiString(const strWide: WideString): AnsiString;
implementation
function WideStringToAnsiString(const strWide: WideString): AnsiString;
var
Len: integer;
begin
Result := '';
if strWide = '' then Exit;
Len := WideCharToMultiByte(GetACP,
WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR,
@strWide[1], -1, nil, 0, nil, nil);
SetLength(Result, Len - 1);
if Len > 1 then
WideCharToMultiByte(GetACP,
WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR,
@strWide[1], -1, @Result[1], Len - 1, nil, nil);
end;
constructor TLanguageLoader.Create(text: string);
var
i: Integer;
item: TSuperObjectIter;
begin
jso := SO(text) as TSuperObject;
Count := 0;
if ObjectFindFirst(jso, item) then
repeat
name[Count] := item.key;
lang[Count] := item.val;
inc(Count);
until not ObjectFindNext(item);
{ for i := 0 to Count - 1 do
begin
name[i] := WideStringToAnsiString(jso.NameOf[i]);
lang[i] := jso.FieldByIndex[i] as TlkJSONobject;
end;}
i := 1;
end;
function TLanguageLoader.Find(lang: string):integer;
var i: Integer;
begin
for i := 0 to Count - 1 do
begin
if lang = name[i] then
exit(i);
end;
exit(-1);
end;
end.
|
unit SubsequenceChecking;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
function ContainsSubsequence(Haystack, Needle: string): boolean;
implementation
function ContainsSubsequence(Haystack, Needle: string): boolean;
var
NeedleIndex, HaystackIndex, NeedleLength, HaystackLength: integer;
begin
Result := False;
NeedleLength := Length(Needle);
HaystackLength := Length(Haystack);
if (NeedleLength > 0) and (HaystackLength > NeedleLength) then
begin
NeedleIndex := 1;
HaystackIndex := 1;
while (NeedleIndex <= NeedleLength) and (HaystackIndex <= HaystackLength) do
begin
if Needle[NeedleIndex] = Haystack[HaystackIndex] then
begin
Inc(NeedleIndex);
end;
Inc(HaystackIndex);
end;
Result := NeedleLength = NeedleIndex - 1;
end;
end;
end.
|
unit Variables;
interface
uses
Values, Strings;
type
TVariables = class;
TVariable = class
private
FVariables: TVariables;
FID: TID;
FValue: TValue;
FRef: Boolean;
function GetIndex(): Integer;
function GetValue(): TValue;
procedure SetValue(Value: TValue);
public
constructor Create(AVariables: TVariables; const AID: TID;
AType_: TType_; AExts: TType_Exts; AIndex: Integer = -1);
destructor Destroy(); override;
property Variables: TVariables read FVariables;
property Index: Integer read GetIndex;
property ID: TID read FID;
property Value: TValue read GetValue write SetValue;
end;
TVariableArray = array of TVariable;
TVariables = class
private
FVariables: TVariableArray;
function GetVariable(Index: Integer): TVariable;
function GetCount(): Integer;
public
constructor Create();
destructor Destroy(); override;
function Define(const AID: TID; AType_: TType_;
AExts: TType_Exts = []): TVariable;
procedure Add(AVariable: TVariable; AIndex: Integer = -1);
procedure Delete(AIndex: Integer);
procedure Clear();
function IndexOf(AVariable: TVariable): Integer;
function VariableByID(const AID: TID): TVariable;
property Variables[Index: Integer]: TVariable read GetVariable; default;
property Count: Integer read GetCount;
end;
implementation
{ TVariable }
{ private }
function TVariable.GetIndex(): Integer;
begin
if Assigned(FVariables) then
Result := FVariables.IndexOf(Self)
else
Result := -1;
end;
function TVariable.GetValue(): TValue;
begin
Result := ValueRef(FValue);
end;
procedure TVariable.SetValue(Value: TValue);
begin
if FRef then
FValue.Ref(Value)
else
FValue.Equal(Value);
end;
{ public }
constructor TVariable.Create(AVariables: TVariables; const AID: TID;
AType_: TType_; AExts: TType_Exts; AIndex: Integer);
begin
inherited Create();
FVariables := nil;
FID := AID;
FValue := TValue.Create(AType_);
FRef := teRef in AExts;
if Assigned(AVariables) then
AVariables.Add(Self, AIndex);
end;
destructor TVariable.Destroy();
begin
FValue.Free();
inherited;
end;
{ TVariables }
{ private }
function TVariables.GetVariable(Index: Integer): TVariable;
begin
if (Index < 0) or (Index > High(FVariables)) then
Result := nil
else
Result := FVariables[Index];
end;
function TVariables.GetCount(): Integer;
begin
Result := High(FVariables) + 1;
end;
{ public }
constructor TVariables.Create();
begin
inherited Create();
SetLength(FVariables, 0);
end;
destructor TVariables.Destroy();
begin
Clear();
inherited;
end;
function TVariables.Define(const AID: TID; AType_: TType_;
AExts: TType_Exts): TVariable;
begin
Result := VariableByID(AID);
if not Assigned(Result) then
Result := TVariable.Create(Self, AID, AType_, AExts);
end;
procedure TVariables.Add(AVariable: TVariable; AIndex: Integer);
var
I: Integer;
begin
if (AIndex < -1) or (AIndex > High(FVariables) + 1) then
Exit;
if IndexOf(AVariable) > -1 then
Exit;
SetLength(FVariables, High(FVariables) + 2);
if AIndex = -1 then
AIndex := High(FVariables)
else
for I := High(FVariables) downto AIndex + 1 do
FVariables[I] := FVariables[I - 1];
FVariables[AIndex] := AVariable;
AVariable.FVariables := Self;
end;
procedure TVariables.Delete(AIndex: Integer);
var
I: Integer;
begin
if (AIndex < 0) or (AIndex > High(FVariables)) then
Exit;
FVariables[AIndex].Free();
for I := AIndex to High(FVariables) - 1 do
FVariables[I] := FVariables[I + 1];
SetLength(FVariables, High(FVariables));
end;
procedure TVariables.Clear();
var
I: Integer;
begin
for I := 0 to High(FVariables) do
FVariables[I].Free();
SetLength(FVariables, 0);
end;
function TVariables.IndexOf(AVariable: TVariable): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to High(FVariables) do
if AVariable = FVariables[I] then
begin
Result := I;
Exit;
end;
end;
function TVariables.VariableByID(const AID: TID): TVariable;
var
I: Integer;
begin
Result := nil;
for I := High(FVariables) downto 0 do
if AID = FVariables[I].ID then
begin
Result := FVariables[I];
Exit;
end;
end;
end.
|
unit NtUtils.Exec.Wdc;
interface
uses
NtUtils.Exec, NtUtils.Exceptions;
type
TExecCallWdc = class(TExecMethod)
class function Supports(Parameter: TExecParam): Boolean; override;
class function Execute(ParamSet: IExecProvider; out Info: TProcessInfo):
TNtxStatus; override;
end;
implementation
uses
Winapi.Wdc, Winapi.WinError, NtUtils.Ldr;
{ TExecCallWdc }
class function TExecCallWdc.Execute(ParamSet: IExecProvider;
out Info: TProcessInfo): TNtxStatus;
var
CommandLine: String;
CurrentDir: PWideChar;
begin
CommandLine := PrepareCommandLine(ParamSet);
if ParamSet.Provides(ppCurrentDirectory) then
CurrentDir := PWideChar(ParamSet.CurrentDircetory)
else
CurrentDir := nil;
Result := LdrxCheckModuleDelayedImport(wdc, 'WdcRunTaskAsInteractiveUser');
if not Result.IsSuccess then
Exit;
Result.Location := 'WdcRunTaskAsInteractiveUser';
Result.HResult := WdcRunTaskAsInteractiveUser(PWideChar(CommandLine),
CurrentDir, 0);
if Result.IsSuccess then
with Info do
begin
// The method does not provide any information about the process
FillChar(ClientId, SizeOf(ClientId), 0);
hxProcess := nil;
hxThread := nil;
end;
end;
class function TExecCallWdc.Supports(Parameter: TExecParam): Boolean;
begin
case Parameter of
ppParameters, ppCurrentDirectory:
Result := True;
else
Result := False;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConfig.AuthorizationFrame;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, System.Json, Rest.Json,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
Data.Bind.Controls, FMX.Controls.Presentation, FMX.Edit, FMX.Layouts,
FMX.TabControl, FMX.ListBox, FMX.DialogService, RSConfig.ListControlFrame,
RSConfig.NameValueFrame;
type
TAuthorizationFrame = class(TFrame)
ListControlFrame1: TListControlFrame;
TabControl: TTabControl;
ListItem: TTabItem;
EditItem: TTabItem;
Layout72: TLayout;
SaveButton: TButton;
CancelButton: TButton;
Layout1: TLayout;
Label1: TLabel;
VertScrollBox2: TVertScrollBox;
Layout4: TLayout;
Label4: TLabel;
UsersLB: TListBox;
Layout7: TLayout;
RemoveUsersButton: TButton;
AddUsersButton: TButton;
Layout3: TLayout;
Label3: TLabel;
GroupsLB: TListBox;
Layout8: TLayout;
RemoveGroupsButton: TButton;
AddGroupsButton: TButton;
Label2: TLabel;
PublicSwitch: TSwitch;
Label5: TLabel;
ListBox1: TListBox;
procedure RemoveGroupsButtonClick(Sender: TObject);
procedure AddGroupsButtonClick(Sender: TObject);
procedure RemoveUsersButtonClick(Sender: TObject);
procedure AddUsersButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure SaveButtonClick(Sender: TObject);
procedure PublicSwitchSwitch(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ActiveFrame: TNameValueFrame;
constructor Create(AOwner: TComponent); override;
procedure Callback(Sender: TObject);
procedure LoadSectionList;
procedure SaveSectionList;
procedure ClearFields;
procedure Reset;
end;
implementation
{$R *.fmx}
uses
RSConsole.FormConfig, RSConfig.ConfigDM, RSConfig.Consts;
constructor TAuthorizationFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ListControlFrame1.HelpButton.Hint := strAuthorizationHelp;
end;
procedure TAuthorizationFrame.Reset;
begin
if TabControl.ActiveTab = EditItem then
CancelButtonClick(Self);
end;
procedure TAuthorizationFrame.AddGroupsButtonClick(Sender: TObject);
begin
TDialogService.InputQuery(strAddGroups, [strGroupPrompt], [''],
procedure(const AResult: TModalResult; const Values: array of string)
begin
if AResult = mrOk then
GroupsLB.Items.Add(Values[0]);
end);
end;
procedure TAuthorizationFrame.AddUsersButtonClick(Sender: TObject);
begin
TDialogService.InputQuery(strAddUsers, [strUserPrompt], [''],
procedure(const AResult: TModalResult; const Values: array of string)
begin
if AResult = mrOk then
UsersLB.Items.Add(Values[0]);
end);
end;
procedure TAuthorizationFrame.Callback(Sender: TObject);
var
LAuthorizationItem: TAuthorizationItem;
LIndex: Integer;
begin
ActiveFrame := TNameValueFrame(Sender);
if Assigned(ActiveFrame) then
begin
if ActiveFrame.ValueEdit.Text <> '' then
begin
LAuthorizationItem := TAuthorizationItem.FromJson(ActiveFrame.ValueEdit.Text);
try
PublicSwitch.IsChecked := LAuthorizationItem.&Public;
// handle third state where public is not defined
PublicSwitch.Tag := ActiveFrame.ValueEdit.Text.IndexOf('"public":');
// default to true if public is not defined
if PublicSwitch.Tag = -1 then
PublicSwitch.IsChecked := True;
// reset changed state
PublicSwitch.TagFloat := 0;
for LIndex := Low(LAuthorizationItem.Users) to High(LAuthorizationItem.Users) do
UsersLB.Items.Add(LAuthorizationItem.Users[LIndex]);
for LIndex := Low(LAuthorizationItem.Groups) to High(LAuthorizationItem.Groups) do
GroupsLB.Items.Add(LAuthorizationItem.Groups[LIndex]);
finally
LAuthorizationItem.Free;
end;
end;
TabControl.ActiveTab := EditItem;
ConfigForm.SaveLayout.Visible := False;
end;
end;
procedure TAuthorizationFrame.CancelButtonClick(Sender: TObject);
begin
ClearFields;
TabControl.ActiveTab := ListItem;
ConfigForm.SaveLayout.Visible := True;
end;
procedure TAuthorizationFrame.LoadSectionList;
begin
ListControlFrame1.SetFrameType(AUTHORIZATION_FRAME);
ListControlFrame1.SetListBox(ListBox1);
ListControlFrame1.SetCallback(Callback);
ConfigDM.LoadSectionList(strServerAuthorization, ListBox1, Callback);
end;
procedure TAuthorizationFrame.PublicSwitchSwitch(Sender: TObject);
begin
// designate a changed state
PublicSwitch.TagFloat := 1;
end;
procedure TAuthorizationFrame.RemoveGroupsButtonClick(Sender: TObject);
begin
if GroupsLB.ItemIndex > -1 then
GroupsLB.Items.Delete(GroupsLB.ItemIndex);
end;
procedure TAuthorizationFrame.RemoveUsersButtonClick(Sender: TObject);
begin
if UsersLB.ItemIndex > -1 then
UsersLB.Items.Delete(UsersLB.ItemIndex);
end;
procedure TAuthorizationFrame.SaveButtonClick(Sender: TObject);
var
LAuthorizationItem: TAuthorizationItem;
LIndex: Integer;
LJsonObject: TJSONObject;
begin
if Assigned(ActiveFrame) then
begin
LAuthorizationItem := TAuthorizationItem.Create;
try
LAuthorizationItem.&Public := PublicSwitch.IsChecked;
for LIndex := 0 to UsersLB.Items.Count - 1 do
LAuthorizationItem.Users := LAuthorizationItem.Users + [UsersLB.Items[LIndex]];
for LIndex := 0 to GroupsLB.Items.Count - 1 do
LAuthorizationItem.Groups := LAuthorizationItem.Groups + [GroupsLB.Items[LIndex]];
// if public was not defined and not changed remove it
if (PublicSwitch.Tag = -1) and (PublicSwitch.TagFloat = 0) then
begin
LJsonObject := TJson.ObjectToJsonObject(LAuthorizationItem,[TJsonOption.joIgnoreEmptyArrays,TJsonOption.joIgnoreEmptyStrings]);
try
LJsonObject.RemovePair('public');
ActiveFrame.ValueEdit.Text := LJsonObject.ToJSON;
finally
LJsonObject.Free;
end;
end
else
ActiveFrame.ValueEdit.Text := LAuthorizationItem.ToJson;
finally
LAuthorizationItem.Free;
end;
ClearFields;
ActiveFrame := nil;
end;
TabControl.ActiveTab := ListItem;
ConfigForm.SaveLayout.Visible := True;
end;
procedure TAuthorizationFrame.ClearFields;
begin
PublicSwitch.IsChecked := True;
UsersLB.Items.Clear;
GroupsLB.Items.Clear;
end;
procedure TAuthorizationFrame.SaveSectionList;
begin
ConfigDM.SaveSectionList(strServerAuthorization, ListBox1);
end;
end.
|
unit RegistryUnitTest;
interface
uses RegistryUnit, TestFramework, Registry;
type
TTestRegistry = class(TTestCase)
private
FInstallPath: string;
FModData: string;
FReg: TRegistry;
public
procedure Setup; override;
procedure TearDown; override;
published
procedure TestRegistrySample;
procedure TestGetInstallPath;
end;
function Suite: ITestSuite;
implementation
function Suite: ITestSuite;
begin
Suite := TTestRegistry.Suite;
end;
{ TTestRegistry }
procedure TTestRegistry.Setup;
begin
FInstallPath := 'C:\Program Files\SampleApp';
FModData := 'SomeData';
FReg := TRegistry.Create;
FReg.OpenKey(ABaseKey, true);
FReg.WriteString('InstallPath', FInstallPath);
FReg.OpenKey('ModuleAData', true);
FReg.WriteString('Data', FModData);
FReg.CloseKey;
end;
procedure TTestRegistry.TearDown;
begin
FReg.DeleteKey(ABaseKey);
FReg.Free;
end;
procedure TTestRegistry.TestGetInstallPath;
begin
check(RegistryUnit.GetRegInstallPath = FInstallPath);
end;
procedure TTestRegistry.TestRegistrySample;
var
InstallPath: string;
ModData: string;
begin
RegistryUnit.GetRegData(InstallPath, ModData);
check(InstallPath = FInstallPath);
check(ModData = FModData);
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.CheckLst;
{$T-,H+,X+}
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.StdCtrls;
type
TCheckListBox = class(TCustomListBox)
private
FAllowGrayed: Boolean;
FFlat: Boolean;
FStandardItemHeight: Integer;
FOnClickCheck: TNotifyEvent;
FHeaderColor: TColor;
FHeaderBackgroundColor: TColor;
{$IF NOT DEFINED(CLR)}
FWrapperList: TList;
{$IFEND}
class var FCheckWidth: Integer;
class var FCheckHeight: Integer;
class constructor Create;
class procedure GetCheckSize;
procedure ResetItemHeight;
procedure DrawCheck(const R: TRect; AState: TCheckBoxState; AEnabled: Boolean);
procedure SetChecked(Index: Integer; AChecked: Boolean);
function GetChecked(Index: Integer): Boolean;
procedure SetState(Index: Integer; AState: TCheckBoxState);
function GetState(Index: Integer): TCheckBoxState;
procedure ToggleClickCheck(Index: Integer);
procedure InvalidateCheck(Index: Integer);
function CreateWrapper(Index: Integer): TObject;
function ExtractWrapper(Index: Integer): TObject;
function GetWrapper(Index: Integer): TObject;
function HaveWrapper(Index: Integer): Boolean;
procedure SetFlat(Value: Boolean);
procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
function GetItemEnabled(Index: Integer): Boolean;
procedure SetItemEnabled(Index: Integer; const Value: Boolean);
function GetHeader(Index: Integer): Boolean;
procedure SetHeader(Index: Integer; const Value: Boolean);
procedure SetHeaderBackgroundColor(const Value: TColor);
procedure SetHeaderColor(const Value: TColor);
{$IF DEFINED(CLR)}
procedure WMDestroy(var Msg : TWMDestroy); message WM_DESTROY;
{$IFEND}
protected
procedure DrawItem(Index: Integer; Rect: TRect;
State: TOwnerDrawState); override;
function InternalGetItemData(Index: Integer): TListBoxItemData; override;
procedure InternalSetItemData(Index: Integer; AData: TListBoxItemData); override;
procedure SetItemData(Index: Integer; AData: TListBoxItemData); override;
function GetItemData(Index: Integer): TListBoxItemData; override;
procedure KeyPress(var Key: Char); override;
procedure LoadRecreateItems(RecreateItems: TStrings); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure ResetContent; override;
procedure SaveRecreateItems(RecreateItems: TStrings); override;
procedure DeleteString(Index: Integer); override;
procedure ClickCheck; dynamic;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
function GetCheckWidth: Integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CheckAll(AState: TCheckBoxState; AllowGrayed: Boolean = True;
AllowDisabled: Boolean = True);
property Checked[Index: Integer]: Boolean read GetChecked write SetChecked;
property ItemEnabled[Index: Integer]: Boolean read GetItemEnabled write SetItemEnabled;
property State[Index: Integer]: TCheckBoxState read GetState write SetState;
property Header[Index: Integer]: Boolean read GetHeader write SetHeader;
published
property OnClickCheck: TNotifyEvent read FOnClickCheck write FOnClickCheck;
property Align;
property AllowGrayed: Boolean read FAllowGrayed write FAllowGrayed default False;
property Anchors;
property AutoComplete;
property BevelEdges;
property BevelInner;
property BevelOuter;
property BevelKind;
property BevelWidth;
property BiDiMode;
property BorderStyle;
property Color;
property Columns;
property Constraints;
property Ctl3D;
property DoubleBuffered;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Flat: Boolean read FFlat write SetFlat default True;
property Font;
property HeaderColor: TColor read FHeaderColor write SetHeaderColor default clInfoText;
property HeaderBackgroundColor: TColor read FHeaderBackgroundColor write SetHeaderBackgroundColor default clInfoBk;
property ImeMode;
property ImeName;
property IntegralHeight;
property ItemHeight;
property Items;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentDoubleBuffered;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ScrollWidth;
property ShowHint;
property Sorted;
property Style;
property TabOrder;
property TabStop;
property TabWidth;
property Touch;
property Visible;
property OnClick;
property OnContextPopup;
property OnData;
property OnDataFind;
property OnDataObject;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDrawItem;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGesture;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMeasureItem;
property OnMouseActivate;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
end;
implementation
uses
{$IF DEFINED(CLR)}
System.Runtime.InteropServices, System.Security.Permissions,
{$IFEND}
Vcl.Themes, System.Types, System.RTLConsts;
type
TCheckListBoxDataWrapper = class
private
FData: TListBoxItemData;
FState: TCheckBoxState;
FDisabled: Boolean;
FHeader: Boolean;
procedure SetChecked(Check: Boolean);
function GetChecked: Boolean;
public
class function GetDefaultState: TCheckBoxState; static;
property Checked: Boolean read GetChecked write SetChecked;
property State: TCheckBoxState read FState write FState;
property Disabled: Boolean read FDisabled write FDisabled;
property Header: Boolean read FHeader write FHeader;
end;
{ TCheckListBoxDataWrapper }
procedure TCheckListBoxDataWrapper.SetChecked(Check: Boolean);
begin
if Check then FState := cbChecked else FState := cbUnchecked;
end;
function TCheckListBoxDataWrapper.GetChecked: Boolean;
begin
Result := FState = cbChecked;
end;
class function TCheckListBoxDataWrapper.GetDefaultState: TCheckBoxState;
begin
Result := cbUnchecked;
end;
{ TCheckListBox }
class constructor TCheckListBox.Create;
begin
TCustomStyleEngine.RegisterStyleHook(TCheckListBox, TListBoxStyleHook);
end;
constructor TCheckListBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFlat := True;
FHeaderColor := clInfoText;
FHeaderBackgroundColor := clInfoBk;
if (FCheckWidth = 0) and (FCheckHeight = 0) then
GetCheckSize;
{$IF NOT DEFINED(CLR)}
FWrapperList := TList.Create;
{$IFEND}
end;
destructor TCheckListBox.Destroy;
{$IF NOT DEFINED(CLR)}
var
I: Integer;
{$IFEND}
begin
{$IF NOT DEFINED(CLR)}
for I := 0 to FWrapperList.Count - 1 do
TCheckListBoxDataWrapper(FWrapperList[I]).Free;
FWrapperList.Free;
{$IFEND}
inherited;
end;
[UIPermission(SecurityAction.LinkDemand, Window=UIPermissionWindow.AllWindows)]
procedure TCheckListBox.CreateWnd;
begin
inherited CreateWnd;
ResetItemHeight;
end;
procedure TCheckListBox.CreateParams(var Params: TCreateParams);
begin
inherited;
with Params do
if Style and (LBS_OWNERDRAWFIXED or LBS_OWNERDRAWVARIABLE) = 0 then
Style := Style or LBS_OWNERDRAWFIXED;
end;
function TCheckListBox.GetCheckWidth: Integer;
begin
Result := FCheckWidth + 2;
end;
procedure TCheckListBox.CMFontChanged(var Message: TMessage);
begin
inherited;
ResetItemHeight;
end;
procedure TCheckListBox.ResetItemHeight;
begin
if HandleAllocated and (Style = lbStandard) then
begin
Canvas.Font := Font;
FStandardItemHeight := Canvas.TextHeight('Wg');
if FCheckHeight > FStandardItemHeight then
FStandardItemHeight := FCheckHeight;
Perform(LB_SETITEMHEIGHT, 0, FStandardItemHeight);
end;
end;
procedure TCheckListBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState);
const
HeaderState: array[Boolean] of TThemedCheckListBox = (tclHeaderItemDisabled, tclHeaderItemNormal);
ItemState: array[Boolean] of TThemedCheckListBox = (tclListItemDisabled, tclListItemNormal);
var
LRect: TRect;
ACheckWidth: Integer;
SaveEvent: TDrawItemEvent;
Enable: Boolean;
LColor: TColor;
LStyle: TCustomStyleServices;
LDetails: TThemedElementDetails;
LHeaderColor, LHeaderBackgroundColor: TColor;
begin
ACheckWidth := GetCheckWidth;
if Index < Items.Count then
begin
LRect := Rect;
Enable := Self.Enabled and GetItemEnabled(Index);
LStyle := StyleServices;
if not Header[Index] then
begin
if not UseRightToLeftAlignment then
begin
LRect.Right := Rect.Left;
LRect.Left := LRect.Right - ACheckWidth;
end
else
begin
LRect.Left := Rect.Right;
LRect.Right := LRect.Left + ACheckWidth;
end;
DrawCheck(LRect, GetState(Index), Enable);
if LStyle.Enabled then
begin
LDetails := LStyle.GetElementDetails(ItemState[Enable]);
if LStyle.GetElementColor(LDetails, ecTextColor, LColor) and (LColor <> clNone) then
Canvas.Font.Color := LColor;
end
else if not Enable then
Canvas.Font.Color := clGrayText;
end
else
begin
if Enable then
LHeaderColor := HeaderColor
else
LHeaderColor := clGrayText;
LHeaderBackgroundColor := HeaderBackgroundColor;
if LStyle.Enabled then
begin
LDetails := LStyle.GetElementDetails(HeaderState[Enable]);
if LStyle.GetElementColor(LDetails, ecTextColor, LColor) and (LColor <> clNone) then
LHeaderColor := LColor;
if LStyle.GetElementColor(LDetails, ecFillColor, LColor) and (LColor <> clNone) then
LHeaderBackgroundColor := LColor;
end;
Canvas.Font.Color := LHeaderColor;
Canvas.Brush.Color := LHeaderBackgroundColor;
end;
end;
if (Style = lbStandard) and Assigned(OnDrawItem) then
begin
{ Force lbStandard list to ignore OnDrawItem event. }
SaveEvent := OnDrawItem;
OnDrawItem := nil;
try
inherited;
finally
OnDrawItem := SaveEvent;
end;
end
else
inherited;
end;
procedure TCheckListBox.CNDrawItem(var Message: TWMDrawItem);
var
{$IF DEFINED(CLR)}
LDrawItemStruct: TDrawItemStruct;
{$ELSE}
LDrawItemStruct: PDrawItemStruct;
{$IFEND}
begin
if not (csDestroying in ComponentState) then
begin
if Items.Count = 0 then exit;
LDrawItemStruct := Message.DrawItemStruct;
with LDrawItemStruct{$IFNDEF CLR}^{$ENDIF} do
if not Header[itemID] then
begin
if not UseRightToLeftAlignment then
rcItem.Left := rcItem.Left + GetCheckWidth
else
rcItem.Right := rcItem.Right - GetCheckWidth;
{$IF DEFINED(CLR)}
Message.DrawItemStruct := LDrawItemStruct;
{$IFEND}
end;
inherited;
end;
end;
procedure TCheckListBox.DrawCheck(const R: TRect; AState: TCheckBoxState; AEnabled: Boolean);
var
DrawState: Integer;
DrawRect: TRect;
OldBrushColor: TColor;
OldBrushStyle: TBrushStyle;
OldPenColor: TColor;
ElementDetails: TThemedElementDetails;
ExRect: TRect;
SaveIndex: Integer;
begin
DrawRect.Left := R.Left + (R.Right - R.Left - FCheckWidth) div 2;
DrawRect.Top := R.Top + (R.Bottom - R.Top - FCheckHeight) div 2;
DrawRect.Right := DrawRect.Left + FCheckWidth;
DrawRect.Bottom := DrawRect.Top + FCheckHeight;
with Canvas do
begin
if ThemeControl(Self) then
begin
case AState of
cbChecked:
if AEnabled then
ElementDetails := StyleServices.GetElementDetails(tbCheckBoxCheckedNormal)
else
ElementDetails := StyleServices.GetElementDetails(tbCheckBoxCheckedDisabled);
cbUnchecked:
if AEnabled then
ElementDetails := StyleServices.GetElementDetails(tbCheckBoxUncheckedNormal)
else
ElementDetails := StyleServices.GetElementDetails(tbCheckBoxUncheckedDisabled)
else // cbGrayed
if AEnabled then
ElementDetails := StyleServices.GetElementDetails(tbCheckBoxMixedNormal)
else
ElementDetails := StyleServices.GetElementDetails(tbCheckBoxMixedDisabled);
end;
SaveIndex := SaveDC(Handle);
try
IntersectClipRect(Handle, R.Left, R.Top, R.Right, R.Bottom);
StyleServices.DrawElement(Handle, ElementDetails, R);
finally
RestoreDC(Handle, SaveIndex);
end;
end
else
begin
case AState of
cbChecked:
DrawState := DFCS_BUTTONCHECK or DFCS_CHECKED;
cbUnchecked:
DrawState := DFCS_BUTTONCHECK;
else // cbGrayed
DrawState := DFCS_BUTTON3STATE or DFCS_CHECKED;
end;
if not AEnabled then
DrawState := DrawState or DFCS_INACTIVE;
DrawFrameControl(Handle, DrawRect, DFC_BUTTON, DrawState);
end;
if Flat then
begin
{ Clip the 3d checkbox }
OldBrushStyle := Brush.Style;
OldBrushColor := Brush.Color;
OldPenColor := Pen.Color;
Brush.Style := bsClear;
if TStyleManager.IsCustomStyleActive then
Pen.Color := StyleServices.GetStyleColor(scListBox)
else
Pen.Color := Color;
with DrawRect do
Rectangle(Left, Top, Right, Bottom);
{ Draw flat rectangle in-place of clipped 3d checkbox above }
Brush.Style := bsClear;
if TStyleManager.IsCustomStyleActive then
Pen.Color := StyleServices.GetSystemColor(clBtnShadow)
else
Pen.Color := clBtnShadow;
with DrawRect do
Rectangle(Left + 1, Top + 1, Right - 1, Bottom - 1);
SaveIndex := SaveDC(Handle);
try
ExRect := Rect(R.Left, R.Top, DrawRect.Right + 2, R.Bottom);
Brush.Style := bsSolid;
if TStyleManager.IsCustomStyleActive then
Brush.Color := StyleServices.GetStyleColor(scListBox)
else
Brush.Color := Color;
ExcludeClipRect(Handle, DrawRect.Left, DrawRect.Top, DrawRect.Right, DrawRect.Bottom);
FillRect(ExRect);
finally
RestoreDC(Handle, SaveIndex);
Brush.Style := bsClear;
end;
Brush.Style := OldBrushStyle;
Brush.Color := OldBrushColor;
Pen.Color := OldPenColor;
end;
end;
end;
class procedure TCheckListBox.GetCheckSize;
var
DC: HDC;
LCheckSize: TSize;
LStyle: TCustomStyleServices;
begin
LStyle := StyleServices;
if LStyle.Enabled then
begin
DC := CreateCompatibleDC(0);
try
LStyle.GetElementSize(DC, LStyle.GetElementDetails(tbCheckBoxCheckedNormal), esActual, LCheckSize);
if (LCheckSize.Width <= 0) or (LCheckSize.Height <= 0) then
begin
LStyle := TStyleManager.SystemStyle;
LStyle.GetElementSize(DC, LStyle.GetElementDetails(tbCheckBoxCheckedNormal), esActual, LCheckSize);
end;
FCheckWidth := LCheckSize.Width;
FCheckHeight := LCheckSize.Height;
finally
DeleteDC(DC);
end;
end
else
with TBitmap.Create do
try
{$IF DEFINED(CLR)}
Handle := LoadBitmap(0, OBM_CHECKBOXES);
{$ELSE}
Handle := LoadBitmap(0, PChar(OBM_CHECKBOXES));
{$IFEND}
FCheckWidth := Width div 4;
FCheckHeight := Height div 3;
finally
Free;
end;
end;
procedure TCheckListBox.SetChecked(Index: Integer; AChecked: Boolean);
begin
if AChecked <> GetChecked(Index) then
begin
TCheckListBoxDataWrapper(GetWrapper(Index)).SetChecked(AChecked);
InvalidateCheck(Index);
end;
end;
procedure TCheckListBox.SetItemEnabled(Index: Integer; const Value: Boolean);
begin
if Value <> GetItemEnabled(Index) then
begin
TCheckListBoxDataWrapper(GetWrapper(Index)).Disabled := not Value;
InvalidateCheck(Index);
end;
end;
procedure TCheckListBox.SetState(Index: Integer; AState: TCheckBoxState);
begin
if AState <> GetState(Index) then
begin
TCheckListBoxDataWrapper(GetWrapper(Index)).State := AState;
InvalidateCheck(Index);
end;
end;
procedure TCheckListBox.InvalidateCheck(Index: Integer);
var
R: TRect;
begin
if not Header[Index] then
begin
R := ItemRect(Index);
if not UseRightToLeftAlignment then
R.Right := R.Left + GetCheckWidth
else
R.Left := R.Right - GetCheckWidth;
InvalidateRect(Handle, R, not (csOpaque in ControlStyle));
UpdateWindow(Handle);
end;
end;
function TCheckListBox.GetChecked(Index: Integer): Boolean;
begin
if HaveWrapper(Index) then
Result := TCheckListBoxDataWrapper(GetWrapper(Index)).GetChecked
else
Result := False;
end;
function TCheckListBox.GetItemEnabled(Index: Integer): Boolean;
begin
if HaveWrapper(Index) then
Result := not TCheckListBoxDataWrapper(GetWrapper(Index)).Disabled
else
Result := True;
end;
function TCheckListBox.GetState(Index: Integer): TCheckBoxState;
begin
if HaveWrapper(Index) then
Result := TCheckListBoxDataWrapper(GetWrapper(Index)).State
else
Result := TCheckListBoxDataWrapper.GetDefaultState;
end;
procedure TCheckListBox.CheckAll(AState: TCheckBoxState; AllowGrayed: Boolean; AllowDisabled: Boolean);
var
I: Integer;
begin
for I := 0 to Items.Count - 1 do
if ItemEnabled[I] or (not ItemEnabled[I] and AllowDisabled) then
if(AllowGrayed or (GetState(I) <> cbGrayed))then
SetState(I, AState);
end;
procedure TCheckListBox.KeyPress(var Key: Char);
begin
if (Key = ' ') then
ToggleClickCheck(ItemIndex);
inherited KeyPress(Key);
end;
procedure TCheckListBox.LoadRecreateItems(RecreateItems: TStrings);
var
I, Index: Integer;
begin
with RecreateItems do
begin
BeginUpdate;
try
Items.NameValueSeparator := NameValueSeparator;
Items.QuoteChar := QuoteChar;
Items.Delimiter := Delimiter;
Items.LineBreak := LineBreak;
for I := 0 to Count - 1 do
begin
Index := Items.Add(RecreateItems[I]);
if Objects[I] <> nil then
InternalSetItemData(Index, TListBoxItemData(Objects[I]));
end;
finally
EndUpdate;
end;
end;
end;
procedure TCheckListBox.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
Index: Integer;
begin
inherited;
if Button = mbLeft then
begin
Index := ItemAtPos(Point(X,Y),True);
if (Index <> -1) and GetItemEnabled(Index) then
if not UseRightToLeftAlignment then
begin
if X - ItemRect(Index).Left < GetCheckWidth then
ToggleClickCheck(Index)
end
else
begin
Dec(X, ItemRect(Index).Right - GetCheckWidth);
if (X > 0) and (X < GetCheckWidth) then
ToggleClickCheck(Index)
end;
end;
end;
procedure TCheckListBox.ToggleClickCheck;
var
State: TCheckBoxState;
begin
if (Index >= 0) and (Index < Items.Count) and GetItemEnabled(Index) then
begin
State := Self.State[Index];
case State of
cbUnchecked:
if AllowGrayed then State := cbGrayed else State := cbChecked;
cbChecked: State := cbUnchecked;
cbGrayed: State := cbChecked;
end;
Self.State[Index] := State;
ClickCheck;
end;
end;
procedure TCheckListBox.ClickCheck;
begin
if Assigned(FOnClickCheck) then FOnClickCheck(Self);
end;
function TCheckListBox.GetItemData(Index: Integer): TListBoxItemData;
begin
{$IF DEFINED(CLR)}
Result := nil;
{$ELSE}
Result := 0;
{$IFEND}
if HaveWrapper(Index) then
Result := TCheckListBoxDataWrapper(GetWrapper(Index)).FData;
end;
function TCheckListBox.GetWrapper(Index: Integer): TObject;
begin
Result := ExtractWrapper(Index);
if Result = nil then
Result := CreateWrapper(Index);
end;
function TCheckListBox.ExtractWrapper(Index: Integer): TObject;
begin
{$IF DEFINED(CLR)}
if (Index < 0) or (Index >= Count) then
raise EListError.Create(Format(SListIndexError, [Index]));
Result := inherited GetItemData(Index);
{$ELSE}
Result := TCheckListBoxDataWrapper(inherited GetItemData(Index));
if LB_ERR = IntPtr(Result) then
raise EListError.CreateResFmt(@SListIndexError, [Index]);
{$IFEND}
if (Result <> nil) and (not (Result is TCheckListBoxDataWrapper)) then
Result := nil;
end;
function TCheckListBox.InternalGetItemData(Index: Integer): TListBoxItemData;
begin
Result := inherited GetItemData(Index);
end;
procedure TCheckListBox.InternalSetItemData(Index: Integer; AData: TListBoxItemData);
begin
inherited SetItemData(Index, AData);
end;
function TCheckListBox.CreateWrapper(Index: Integer): TObject;
begin
{$IF NOT DEFINED(CLR)}
FWrapperList.Expand;
{$IFEND}
Result := TCheckListBoxDataWrapper.Create;
{$IF NOT DEFINED(CLR)}
FWrapperList.Add(Result);
{$IFEND}
inherited SetItemData(Index, TListBoxItemData(Result));
end;
function TCheckListBox.HaveWrapper(Index: Integer): Boolean;
begin
Result := ExtractWrapper(Index) <> nil;
end;
procedure TCheckListBox.SetItemData(Index: Integer; AData: TListBoxItemData);
var
Wrapper: TCheckListBoxDataWrapper;
begin
{$IF DEFINED(CLR)}
if HaveWrapper(Index) or (AData <> nil) then
{$ELSE}
if HaveWrapper(Index) or (AData <> 0) then
{$IFEND}
begin
Wrapper := TCheckListBoxDataWrapper(GetWrapper(Index));
Wrapper.FData := AData;
end;
end;
procedure TCheckListBox.ResetContent;
{$IF DEFINED(CLR)}
var
I: Integer;
begin
for I := 0 to Items.Count - 1 do
if HaveWrapper(I) then
GetWrapper(I).Free;
inherited;
{$ELSE}
var
I, Index: Integer;
LWrapper: TCheckListBoxDataWrapper;
begin
for I := 0 to Items.Count - 1 do
begin
LWrapper := TCheckListBoxDataWrapper(ExtractWrapper(I));
if Assigned(LWrapper) then
begin
Index := FWrapperList.IndexOf(LWrapper);
if Index <> -1 then
FWrapperList.Delete(Index);
LWrapper.Free;
end;
end;
inherited;
{$IFEND}
end;
procedure TCheckListBox.SaveRecreateItems(RecreateItems: TStrings);
var
{$IF DEFINED(CLR)}
I, Index: Integer;
{$ELSE}
I: Integer;
LWrapper: TCheckListBoxDataWrapper;
{$IFEND}
begin
{$IF NOT DEFINED(CLR)}
FWrapperList.Clear;
{$IFEND}
with RecreateItems do
begin
BeginUpdate;
try
NameValueSeparator := Items.NameValueSeparator;
QuoteChar := Items.QuoteChar;
Delimiter := Items.Delimiter;
LineBreak := Items.LineBreak;
for I := 0 to Items.Count - 1 do
{$IF DEFINED(CLR)}
AddObject(Items[I], ExtractWrapper(I));
{$ELSE}
begin
LWrapper := TCheckListBoxDataWrapper(ExtractWrapper(I));
AddObject(Items[I], LWrapper);
if LWrapper <> nil then
FWrapperList.Add(LWrapper);
end;
{$IFEND}
finally
EndUpdate;
end;
end;
end;
procedure TCheckListBox.DeleteString(Index: Integer);
{$IF DEFINED(CLR)}
begin
if HaveWrapper(Index) then
GetWrapper(Index).Free;
inherited;
{$ELSE}
var
LIndex: Integer;
LWrapper: TCheckListBoxDataWrapper;
begin
if HaveWrapper(Index) then
begin
LWrapper := TCheckListBoxDataWrapper(GetWrapper(Index));
LIndex := FWrapperList.IndexOf(LWrapper);
if LIndex <> -1 then
FWrapperList.Delete(LIndex);
LWrapper.Free;
end;
inherited;
{$IFEND}
end;
procedure TCheckListBox.SetFlat(Value: Boolean);
begin
if Value <> FFlat then
begin
FFlat := Value;
Invalidate;
end;
end;
{$IF DEFINED(CLR)}
procedure TCheckListBox.WMDestroy(var Msg: TWMDestroy);
begin
ResetContent;
inherited;
end;
{$IFEND}
function TCheckListBox.GetHeader(Index: Integer): Boolean;
begin
if HaveWrapper(Index) then
Result := TCheckListBoxDataWrapper(GetWrapper(Index)).Header
else
Result := False;
end;
procedure TCheckListBox.SetHeader(Index: Integer; const Value: Boolean);
begin
if Value <> GetHeader(Index) then
begin
TCheckListBoxDataWrapper(GetWrapper(Index)).Header := Value;
InvalidateCheck(Index);
end;
end;
procedure TCheckListBox.SetHeaderBackgroundColor(const Value: TColor);
begin
if Value <> HeaderBackgroundColor then
begin
FHeaderBackgroundColor := Value;
Invalidate;
end;
end;
procedure TCheckListBox.SetHeaderColor(const Value: TColor);
begin
if Value <> HeaderColor then
begin
FHeaderColor := Value;
Invalidate;
end;
end;
end.
|
unit UDutycode;
interface
const
NORMAL = '00'; // 정상
HOLIDAY = '49'; // 휴일
HOLIDAY2 = '50'; // 휴근
HOLISATUR = '05'; // 토요휴무
HOLIHALF = '61'; // 반차
HOLIMOHTH = '62'; // 월차
HOLIYEAR = '63'; // 연차
YEARHALF = '64'; // 반연차 2010.06.28
HOLISICK = '71'; // 병가
ABSENCE = '72'; // 결근
ILLNESS = '82'; // 병상
BABYCARE = '83'; // 육아
MILITARY = '84'; // 병역
INDICTMEN = '85'; // 기소
ABROAD = '86'; // 유학
POPULAR = '87'; // 일반
OTHERS = '89'; // 기타
UNDECIDED = '99'; // 미입력
PUBREST = '81'; // 공상
BEAR = '55'; // 산휴
EXCHANGE = '06'; // 교대근무 DSA2000 2005.07.
EXCHHOLI = '07'; // 교대근무자 비번 DSA2000 2005.07.
SPEOFF = '04'; // 교휴 DSA2000 2005.07.
WORKSTOP = '91'; // 정직
BEFORE = '97'; // 불입
TEMPORARY = '98'; // 임시
SPECIAL = '51'; // 특휴 2016.09.23.hjku.. 추가
LONGWORK = '52'; // 장휴
PUBVAR = '53'; // 공가
PUBSICK = '54'; // 공병
implementation
end.
|
unit AGeraEstagiosOP;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, StdCtrls, Buttons, Localizacao, UnDadosProduto,
Grids, CGrades, Mask, numericos, UnOrdemProducao, UnProdutos,
CheckLst;
type
TFGeraEstagiosOP = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
BGravar: TBitBtn;
BCancelar: TBitBtn;
Localiza: TConsultaPadrao;
SpeedButton1: TSpeedButton;
Label1: TLabel;
LNomProduto: TLabel;
ECodProduto: TEditColor;
EQtdProduto: Tnumerico;
Label2: TLabel;
Label3: TLabel;
EUM: TEditColor;
EQtdCelula: Tnumerico;
Label4: TLabel;
Grade: TRBStringGridColor;
ETotalHoras: TEditColor;
Label5: TLabel;
EDesTecnica: TMemoColor;
Label6: TLabel;
ECor: TEditLocaliza;
Label7: TLabel;
Label8: TLabel;
SpeedButton2: TSpeedButton;
BFechar: TBitBtn;
SpeedButton3: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BCancelarClick(Sender: TObject);
procedure BGravarClick(Sender: TObject);
procedure GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer);
procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean);
procedure GradeGetEditMask(Sender: TObject; ACol, ARow: Integer;
var Value: String);
procedure GradeKeyPress(Sender: TObject; var Key: Char);
procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
procedure GradeGetCellAlignment(sender: TObject; ARow, ACol: Integer;
var HorAlignment: TAlignment; var VerAlignment: TVerticalAlignment);
procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure BFecharClick(Sender: TObject);
procedure BImprimirClick(Sender: TObject);
procedure GradeDepoisExclusao(Sender: TObject);
procedure EQtdProdutoExit(Sender: TObject);
procedure EQtdProdutoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure EQtdCelulaExit(Sender: TObject);
procedure EQtdCelulaKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure SpeedButton3Click(Sender: TObject);
private
{ Private declarations }
VprAcao : Boolean;
VprDOrdemProducao : TRBDOrdemProducao;
VprDFracaoOP : TRBDFracaoOrdemProducao;
VprDEstagio : TRBDordemProducaoEstagio;
FunOrdemProducao : TRBFuncoesOrdemProducao;
procedure CarTitulosGrade;
procedure CarDTela;
procedure CarDClasse;
procedure CarDEstagio;
procedure HabilitaBotoes(VpaEstado : Boolean);
procedure AtualizarHorasProducao;
procedure AtualizaQtdCelulas;
public
{ Public declarations }
function GeraEstagioOP(VpaDOrdemProducao : TRBDOrdemProducao;VpaDFracaoOP : TRBDFracaoOrdemProducao):boolean;
end;
var
FGeraEstagiosOP: TFGeraEstagiosOP;
implementation
uses APrincipal, ConstMsg, Constantes, FunString, ANovoProdutoPro;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFGeraEstagiosOP.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
VprAcao := false;
FunOrdemProducao := TRBFuncoesOrdemProducao.cria(FPrincipal.baseDados);
CarTitulosGrade;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFGeraEstagiosOP.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
FunOrdemProducao.free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFGeraEstagiosOP.BCancelarClick(Sender: TObject);
begin
VprAcao := false;
close;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.BGravarClick(Sender: TObject);
begin
CarDClasse;
VprAcao := true;
close;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.CarTitulosGrade;
begin
Grade.Cells[0,0] := 'ID';
Grade.Cells[1,0] := 'Celulas Trabalho';
Grade.Cells[2,0] := 'Horas';
Grade.Cells[3,0] := 'Código';
Grade.Cells[4,0] := 'Estágio';
Grade.Cells[5,0] := 'Descrição';
Grade.Cells[6,0] := 'ID Anterior';
Grade.Cells[7,0] := 'Ordem';
Grade.Cells[8,0] := 'Interna/Externa';
Grade.Cells[9,0] := 'Val Unitário Facção';
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.CarDTela;
begin
ECodProduto.Text := VprDOrdemProducao.CodProduto;
LNomProduto.Caption := VprDOrdemProducao.NomProduto;
EQtdProduto.AValor := VprDFracaoOP.QtdProduto;
EUM.Text := VprDOrdemProducao.UMPedido;
EQtdCelula.AsInteger := VprDFracaoOP.QtdCelula;
EDesTecnica.Lines.Text := VprDOrdemProducao.DesObservacoes;
ECor.AInteiro := VprDOrdemProducao.CodCor;
ECor.Atualiza;
ETotalHoras.text := FunOrdemProducao.RTotalHorasOP(VprDFracaoOP);
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.CarDClasse;
begin
VprDOrdemProducao.DesObservacoes := EDesTecnica.Lines.Text;
VprDFracaoOP.QtdProduto := EQtdProduto.AValor;
VprDFracaoOP.HorProducao := ETotalHoras.Text;
VprDFracaoOP.QtdCelula := EQtdCelula.AsInteger;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.CarDEstagio;
begin
VprDEstagio.QtdCelula := StrToInt(Grade.Cells[1,Grade.ALinha]);
Grade.Cells[2,Grade.ALinha] := FunOrdemProducao.RQtdHorasEstagio(VprDEstagio,FunProdutos.REstagioProduto(VprDOrdemProducao.DProduto,VprDEstagio.SeqEstagio),VprDFracaoOP.QtdProduto);
VprDEstagio.QtdHoras := Grade.Cells[2,Grade.ALinha];
VprdEstagio.NumOrdem := StrToInt(Grade.Cells[7,Grade.ALinha]);
VprdEstagio.IndProducaoInterna := Grade.Cells[8,Grade.ALinha];
if DeletaChars(DeletaChars(Grade.Cells[9,Grade.ALinha],'.'),'0') <> '' then
VprDEstagio.ValUnitarioFaccao := StrToFloat(DeletaChars(Grade.Cells[9,Grade.ALinha],'.'));
ETotalHoras.text := FunOrdemProducao.RTotalHorasOP(VprDFracaoOP);
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.HabilitaBotoes(VpaEstado : Boolean);
begin
BGravar.Enabled := VpaEstado;
BCancelar.Enabled := VpaEstado;
BFechar.Enabled := not VpaEstado;
end;
procedure TFGeraEstagiosOP.AtualizarHorasProducao;
begin
VprDFracaoOP.QtdProduto := EQtdProduto.AValor;
FunOrdemProducao.RecalculaHorasEstagio(VprDOrdemProducao,VprDFracaoOP);
Grade.CarregaGrade;
ETotalHoras.text := FunOrdemProducao.RTotalHorasOP(VprDFracaoOP);
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.AtualizaQtdCelulas;
var
VpfLaco : Integer;
begin
VprDFracaoOP.QtdCelula := EQtdCelula.AsInteger;
for VpfLaco := 0 to VprDFracaoOP.Estagios.count -1 do
begin
TRBDordemProducaoEstagio(VprDFracaoOP.Estagios.Items[VpfLaco]).QtdCelula := VprDFracaoOP.QtdCelula;
end;
AtualizarHorasProducao;
end;
{******************************************************************************}
function TFGeraEstagiosOP.GeraEstagioOP(VpaDOrdemProducao : TRBDOrdemProducao;VpaDFracaoOP : TRBDFracaoOrdemProducao):boolean;
begin
VprDOrdemProducao := VpaDOrdemProducao;
VprDFracaoOP := VpaDFracaoOP;
Grade.ADados := VprDFracaoOP.Estagios;
Grade.CarregaGrade;
CarDTela;
HabilitaBotoes(true);
Showmodal;
result := VprAcao;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.GradeCarregaItemGrade(Sender: TObject;
VpaLinha: Integer);
begin
VprDEstagio := TRBDordemProducaoEstagio(VprDFracaoOP.Estagios.Items[VpaLinha-1]);
Grade.cells[0,VpaLinha] := InttoStr(VprDEstagio.SeqEstagio);
Grade.Cells[1,VpaLinha] := Inttostr(VprDEstagio.QtdCelula);
Grade.cells[2,VpaLinha] := VprDEstagio.QtdHoras;
Grade.cells[3,VpaLinha] := InttoStr(VprDEstagio.CodEstagio);
Grade.cells[4,VpaLinha] := VprDEstagio.NomEstagio;
Grade.cells[5,VpaLinha] := VprDEstagio.DesEstagio;
Grade.cells[6,VpaLinha] := InttoStr(VprDEstagio.SeqEstagioAnterior);
Grade.Cells[7,VpaLinha] := IntTosTr(VprDEstagio.NumOrdem);
Grade.Cells[8,VpaLinha] := VprDEstagio.IndProducaoInterna;
if VprDEstagio.ValUnitarioFaccao <> 0 then
Grade.Cells[9,VpaLinha] := FormatFloat(Varia.MascaraValorUnitario,VprDEstagio.ValUnitarioFaccao)
else
Grade.Cells[9,VpaLinha] := '';
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.GradeDadosValidos(Sender: TObject;
var VpaValidos: Boolean);
begin
VpaValidos := false;
if (Grade.Cells[1,Grade.ALinha] = '') then
begin
Aviso('QUANTIDADE DE CELULA DE TRABALHO NÃO PREENCHIDO!!!'#13'É necessário digitar a quantidade de células de trabalho.');
Grade.Col := 1;
end
else
if (Grade.Cells[2,Grade.ALinha] = '') then
begin
aviso('QUANTIDADE HORAS NÃO PREENCHIDO!!!'#13'É necessário digitar a quantidade de horas.');
Grade.Col := 2;
end
else
if (Grade.Cells[7,Grade.ALinha] = '') then
begin
aviso('ORDEM DO ESTÁGIO NÃO PREENCHIDO!!!'#13'É necessário digitar a ordem do estágio.');
Grade.Col := 7;
end
else
if (Grade.Cells[8,Grade.ALinha] <> 'I') and (Grade.Cells[8,Grade.ALinha] <> 'E') then
begin
aviso('INDICADOR DE PRODUÇÃO INTERNA INVÁLIDO!!!'#13'O indicardor de produção somente pode ser preenchido com "I"(Interna) ou "E"(Externa)...');
Grade.Col := 8;
end
else
VpaValidos := true;
if VpaValidos then
begin
CarDEstagio;
if VprDEstagio.QtdCelula = 0 then
begin
Aviso('QUANTIDADE DE CELULA DE TRABALHO NÃO PREENCHIDO!!!'#13'É necessário digitar a quantidade de células de trabalho.');
VpaValidos := false;
Grade.Col := 1;
end;
end;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.GradeGetEditMask(Sender: TObject; ACol,
ARow: Integer; var Value: String);
begin
case ACol of
4,5 : Value := '000;0; ';
3 : value := '000:00;1;_';
end;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.GradeKeyPress(Sender: TObject; var Key: Char);
begin
case Grade.Col of
3,4 : key :=#0;
8 :begin
if key = 'i' then
key := 'I'
else
if key = 'e' then
key := 'E'
else
if not(key in ['I','E']) then
key := #0;
end;
end;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.GradeMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
begin
if VprDFracaoOP.Estagios.Count > 0 then
VprDEstagio := TRBDordemProducaoEstagio(VprDFracaoOP.Estagios.Items[VpaLinhaAtual-1]);
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.GradeGetCellAlignment(sender: TObject; ARow,
ACol: Integer; var HorAlignment: TAlignment;
var VerAlignment: TVerticalAlignment);
begin
if ARow > 0 then
begin
case ACol of
1 : HorAlignment := taCenter;
2 : HorAlignment := taRightJustify;
end;
end;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.GradeSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
if Grade.AEstadoGrade in [egInsercao,EgEdicao] then
if Grade.AColuna <> ACol then
begin
case Grade.AColuna of
1 : if Grade.Cells[1,Grade.Alinha] <> '' then
begin
if StrToInt(Grade.Cells[1,Grade.Alinha])<> VprDEstagio.QtdCelula then
begin
VprDEstagio.QtdCelula := StrToInt(Grade.Cells[1,Grade.Alinha]);
Grade.Cells[2,Grade.ALinha] := FunOrdemProducao.RQtdHorasEstagio(VprDEstagio,FunProdutos.REstagioProduto(VprDOrdemProducao.DProduto,VprDEstagio.SeqEstagio),VprDFracaoOP.QtdProduto);
end;
end;
end;
end;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.BFecharClick(Sender: TObject);
begin
close;
end;
procedure TFGeraEstagiosOP.BImprimirClick(Sender: TObject);
begin
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.GradeDepoisExclusao(Sender: TObject);
begin
ETotalHoras.text := FunOrdemProducao.RTotalHorasOP(VprDFracaoOP);
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.EQtdProdutoExit(Sender: TObject);
begin
if EQtdProduto.AValor <> VprDFracaoOP.QtdProduto then
AtualizarHorasProducao;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.EQtdProdutoKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = 13 then
AtualizarHorasProducao;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.EQtdCelulaExit(Sender: TObject);
begin
if EQtdCelula.AsInteger <> VprDFracaoOP.QtdCelula then
AtualizaQtdCelulas;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.EQtdCelulaKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if key = 13 then
begin
AtualizaQtdCelulas;
EQtdProduto.SelectAll;
end;
end;
{******************************************************************************}
procedure TFGeraEstagiosOP.SpeedButton3Click(Sender: TObject);
begin
FNovoProdutoPro := TFNovoProdutoPro.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoProdutoPro'));
if FNovoProdutoPro.AlterarProduto(varia.codigoEmpresa,varia.CodigoEmpFil,VprDOrdemProducao.SeqProduto) <> nil then
begin
FunProdutos.CarDProduto(VprDOrdemProducao.DProduto);
FunOrdemProducao.AdicionaEstagiosOP(VprDOrdemProducao.DProduto,VprDFracaoOP,false);
Grade.CarregaGrade;
end;
FNovoProdutoPro.free;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFGeraEstagiosOP]);
end.
|
unit osCipher;
interface
const IVSize = 10;
type
ByteArray = Array [0..255] of Byte;
TCipher = class(TObject)
private
Key, State : ByteArray;
KeyString : string;
KeyLength : integer;
procedure Zero (var InArray : ByteArray; Size : Integer);
procedure String2Array (InString : string; StringLength : Integer;
var OutArray : ByteArray);
procedure GetKey (var InString : String; var Stringlength : Integer);
procedure RC4Setup (InKey : ByteArray; KeySize : Integer);
procedure RC4Cipher (var InputString, OutputString : string; Size: integer);
public
function Encode (InputString: string) : string;
function Decode (InputString: string) : string;
end;
implementation
procedure TCipher.Zero(VAR InArray : ByteArray; Size : Integer);
var
Count : integer;
begin
for Count := 0 to Size do
InArray[Count] := 0
end;
procedure TCipher.String2Array (InString : string; StringLength : Integer;
var OutArray : ByteArray);
var
Count : Integer;
begin
for Count := 1 to StringLength do
OutArray[Count-1] := Ord(InString[Count])
end;
// Gets InString, a string of length <= 256 - IVSize bytes
procedure TCipher.GetKey (var InString : string; var Stringlength : Integer);
begin
InString := 'ItApOcUrUmIxSaIgUaÇu';
StringLength := Length(InString);
end;
procedure TCipher.RC4Setup (InKey : ByteArray; KeySize : Integer);
var
i, j, HoldInfo : integer;
begin
j := 0;
for i := 0 To 255 do
State[i] := i;
for i := 0 to 255 do
begin
j := (j + State[i] + InKey[i mod KeySize]) mod 256;
HoldInfo := State[i];
State[i] := State[j];
State[j] := HoldInfo;
end;
end;
procedure TCipher.RC4Cipher (var InputString, OutputString : string; Size: integer);
var
i, j, k, n, HoldInfo : integer;
OutPutByte, MessageByte : byte;
begin;
i := 0;
j := 0;
for k := 1 to Size do
begin
i := (i + 1) mod 256;
j := (j + State[i]) mod 256;
HoldInfo := State[i];
State[i] := State[j];
State[j] := HoldInfo;
n := (State[i] + State[j]) mod 256;
MessageByte := byte(InputString[k]);
OutputByte := State[n] xor MessageByte;
OutputString[k] := char(OutputByte);
end;
end;
function TCipher.Encode (InputString: string) : string;
var
InitVector : string;
OutputString : string;
Count : integer;
n : integer;
begin
Zero (Key, 255);
Zero (State, 255);
GetKey(KeyString, KeyLength);
String2Array(KeyString, KeyLength, Key);
n := Length(InputString);
SetLength(OutputString, n);
SetLength(InitVector, IVSize);
// generate a random IV, put it at the end of Key
Randomize;
for Count := 1 to IVSize do
begin
Key[Count + KeyLength -1] := Random(256);
InitVector[Count] := char(Key[Count + KeyLength - 1]);
end;
KeyLength := KeyLength + IVSize;
RC4Setup(Key, KeyLength);
RC4Cipher (InputString, OutputString, n);
Result := InitVector + OutputString;
end;
function TCipher.Decode (InputString: string) : string;
var
OutputString : string;
Count : integer;
n : integer;
begin
Zero (Key, 255);
Zero (State, 255);
GetKey(KeyString, KeyLength);
String2Array(KeyString, KeyLength, Key);
n := Length(InputString) - IVSize;
SetLength(OutputString, n);
// get the InitVector from the input string
for Count := 1 to IVSize do
begin
Key[Count + KeyLength - 1] := byte(InputString[Count]);
end;
KeyLength := KeyLength + IVSize;
RC4Setup(Key, KeyLength);
InputString := Copy(InputString, IVSize + 1, n);
RC4Cipher (InputString, OutputString, n);
Result := OutputString;
end;
end.
|
unit uPixMapGtk;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, IntfGraphics,
gtk2def, gdk2pixbuf, gdk2, glib2;
procedure DrawPixbufAtCanvas(Canvas: TCanvas; Pixbuf : PGdkPixbuf; SrcX, SrcY, DstX, DstY, Width, Height: Integer);
function PixBufToBitmap(Pixbuf: PGdkPixbuf): TBitmap;
implementation
uses
GraphType, uGraphics;
procedure DrawPixbufAtCanvas(Canvas: TCanvas; Pixbuf : PGdkPixbuf; SrcX, SrcY, DstX, DstY, Width, Height: Integer);
var
gdkDrawable : PGdkDrawable;
gdkGC : PGdkGC;
gtkDC : TGtkDeviceContext;
iPixbufWidth, iPixbufHeight: Integer;
StretchedPixbuf: PGdkPixbuf;
begin
gtkDC := TGtkDeviceContext(Canvas.Handle);
gdkDrawable := gtkDC.Drawable;
gdkGC := gdk_gc_new(gdkDrawable);
iPixbufWidth := gdk_pixbuf_get_width(Pixbuf);
iPixbufHeight := gdk_pixbuf_get_height(Pixbuf);
if (Width <> iPixbufWidth) or (Height <> iPixbufHeight) then
begin
StretchedPixbuf := gdk_pixbuf_scale_simple(Pixbuf, Width, Height, GDK_INTERP_BILINEAR);
gdk_draw_pixbuf(gdkDrawable, gdkGC, StretchedPixbuf, SrcX, SrcY, DstX, DstY, -1, -1, GDK_RGB_DITHER_NONE, 0, 0);
gdk_pixbuf_unref(StretchedPixbuf);
end
else
gdk_draw_pixbuf(gdkDrawable, gdkGC, Pixbuf, SrcX, SrcY, DstX, DstY, -1, -1, GDK_RGB_DITHER_NONE, 0, 0);
g_object_unref(gdkGC);
end;
function PixBufToBitmap(Pixbuf: PGdkPixbuf): TBitmap;
var
width, height, rowstride, n_channels, i, j: Integer;
pixels: Pguchar;
pSrc: PByte;
pDst: PLongWord;
BmpData: TLazIntfImage;
hasAlphaChannel: Boolean;
QueryFlags: TRawImageQueryFlags = [riqfRGB];
Description: TRawImageDescription;
begin
Result := nil;
n_channels:= gdk_pixbuf_get_n_channels(Pixbuf);
if ((n_channels <> 3) and (n_channels <> 4)) or // RGB or RGBA
(gdk_pixbuf_get_colorspace(pixbuf) <> GDK_COLORSPACE_RGB) or
(gdk_pixbuf_get_bits_per_sample(pixbuf) <> 8) then Exit;
width:= gdk_pixbuf_get_width(Pixbuf);
height:= gdk_pixbuf_get_height(Pixbuf);
rowstride:= gdk_pixbuf_get_rowstride(Pixbuf);
pixels:= gdk_pixbuf_get_pixels(Pixbuf);
hasAlphaChannel:= gdk_pixbuf_get_has_alpha(Pixbuf);
if hasAlphaChannel then
Include(QueryFlags, riqfAlpha);
BmpData := TLazIntfImage.Create(width, height, QueryFlags);
try
BmpData.CreateData;
Description := BmpData.DataDescription;
pDst := PLongWord(BmpData.PixelData);
for j:= 0 to Height - 1 do
begin
pSrc := PByte(pixels) + j * rowstride;
for i:= 0 to Width - 1 do
begin
pDst^ := pSrc[0] shl Description.RedShift +
pSrc[1] shl Description.GreenShift +
pSrc[2] shl Description.BlueShift;
if hasAlphaChannel then
pDst^ := pDst^ + pSrc[3] shl Description.AlphaShift;
Inc(pSrc, n_channels);
Inc(pDst);
end;
end;
Result := TBitmap.Create;
BitmapAssign(Result, BmpData);
if not hasAlphaChannel then
Result.Transparent := True;
finally
BmpData.Free;
end;
end;
// or use this
{
begin
iPixbufWidth := gdk_pixbuf_get_width(pbPicture);
iPixbufHeight := gdk_pixbuf_get_height(pbPicture);
Result := TBitMap.Create;
Result.SetSize(iPixbufWidth, iPixbufHeight);
Result.Canvas.Brush.Color := clBackColor;
Result.Canvas.FillRect(0, 0, iPixbufWidth, iPixbufHeight);
DrawPixbufAtCanvas(Result.Canvas, pbPicture, 0, 0, 0, 0, iPixbufWidth, iPixbufHeight);
end;
}
end.
|
unit BowlFrameUnit; // implements the IBowlFrame interface
interface
uses
Generics.Collections,
BowlingInt;
type
TBowlFrame = class(TInterfacedObject, IBowlFrame) // explanation for items can befound in the BowlingInt unit for this class
private
fNextFrame: IBowlFrame;
fRoll: array[1..3] of integer;
function GetRoll(AnIdx: integer): integer;
function RollRangeCheck(AnIdx: integer): boolean;
function RollCheck(ARoll: integer): boolean;
public
procedure LinkNextFrame(ANextFrame: IBowlFrame = nil);
function NextFrame: IBowlFrame;
function SecondNextFrame: IBowlFrame;
function BowlFrameType(WhichFrame: integer): TBowlFrameType;
function AddRoll(ARoll: integer): boolean; // add a roll to the next available position in the frame, or return false;
function CurrentScore(WhichFrame: integer): integer;
constructor Create;
property Roll[idx: integer]: integer read GetRoll;
end;
implementation
uses
SysUtils, BowlError;
{ TFrame }
constructor TBowlFrame.Create;
begin
inherited;
fRoll[1] := -1;
fRoll[2] := -1;
fRoll[3] := -1;
fNextFrame := nil;
end;
function TBowlFrame.CurrentScore(WhichFrame: integer): integer;
var
temp: integer;
begin
Result := 0;
case BowlFrameType(WhichFrame) of
frameIncomplete,
frameOpen: begin
if Roll[1] <> -1 then Result := Roll[1];
if Roll[2] <> -1 then Result := Result + Roll[2];
end;
frameSpare: begin
Result := 10;
if (WhichFrame = 10) then begin
if (Roll[3] > -1) then begin
Result := Result + Roll[3];
end;
end else begin
if assigned(fNextFrame) then begin
if (fNextFrame.Roll[1] > -1) then begin
Result := Result + fNextFrame.Roll[1];
end;
end;
end;
end;
frameStrike: begin
Result := 10;
if (WhichFrame = 9) then begin
if assigned(fNextFrame) then begin
temp := fNextFrame.Roll[1];
if (temp > -1) then begin
Result := Result + temp;
end;
temp := fNextFrame.Roll[2];
if (temp > -1) then begin
Result := Result + temp;
end;
end;
end else if (WhichFrame = 10) then begin
if (Roll[2] > -1) then begin
Result := Result + Roll[2];
end;
if (Roll[3] > -1) then begin
Result := Result + Roll[3];
end;
end else begin
if assigned(fNextFrame) then begin
temp := fNextFrame.Roll[1];
if (temp > -1) then begin
Result := Result + temp;
end;
if (temp = 10) then begin // move to the next one
if (SecondNextFrame <> nil) then begin
Result := Result + SecondNextFrame.Roll[1];
end;
end else begin
temp := fNextFrame.Roll[2];
if (temp > -1) then begin
Result := Result + temp;
end;
end;
end;
end;
end;
end;
end;
function TBowlFrame.BowlFrameType(WhichFrame: integer): TBowlFrameType;
begin
Result := frameIncomplete;
if (WhichFrame = 10) then begin
if (fRoll[2] = -1) then begin // it's incomplete no matter what
Result := frameIncomplete;
end else if (fRoll[3] <> -1) then begin // it's a spare or strike
if Roll[1] = 10 then begin
Result := frameStrike;
end else begin
Result := frameSpare;
end;
end else if ((fRoll[1] + fRoll[2])< 10) then begin // it's an open frame
Result := frameOpen;
end;
end else begin
if (fRoll[1] = 10) then begin
Result := frameStrike;
end else if ((fRoll[1] + fRoll[2]) = 10) then begin
Result := frameSpare;
end else begin
if (fRoll[2] = -1) then begin
Result := frameIncomplete;
end else begin
Result := frameOpen;
end;
end;
end;
end;
function TBowlFrame.GetRoll(AnIdx: integer): integer;
begin
if RollRangeCheck(AnIdx) then
Result := fRoll[AnIdx]
else
Result := -1;
end;
procedure TBowlFrame.LinkNextFrame(ANextFrame: IBowlFrame);
begin
if not assigned(fNextFrame) and assigned(ANextFrame) then
fNextFrame := ANextFrame;
end;
function TBowlFrame.NextFrame: IBowlFrame;
begin
NextFrame := fNextFrame;
end;
function TBowlFrame.RollCheck(ARoll: integer): boolean;
begin
Result := (ARoll >= 0) and (ARoll <= 10);
if not result then
raise EBowlException.Create('A roll of ' + IntToStr(ARoll) +
' is out of range. (It must be between 0 and 10 to be valid)');// checked
end;
function TBowlFrame.RollRangeCheck(AnIdx: integer): boolean;
begin
Result := (AnIdx >= 1) and (AnIdx <= 3);
if not result then
raise EBowlException.Create('The index ' + IntToStr(AnIdx) +
' to the roll in a frame is out of range. (It must be between 1 and 3 to be valid)'); // unit test
end;
function TBowlFrame.SecondNextFrame: IBowlFrame;
begin
Result := nil;
if assigned(fNextFrame) then
Result := fNextFrame.NextFrame;
end;
function TBowlFrame.AddRoll(ARoll: integer): boolean; // add a roll to the next available position in the frame, or return false;
begin
Result := RollCheck(ARoll);
if Result then begin
if (fRoll[1] = -1) then begin
fRoll[1] := ARoll;
end else if (fRoll[2] = -1) then begin
if (NextFrame = nil) then begin // last frame
if (fRoll[1] = 10) then begin
fRoll[2] := ARoll;
end else begin // normal frame
if((fRoll[1] + ARoll) > 10) then begin
raise EBowlException.Create('Trying to add a ball roll of ' + IntToStr(ARoll) +
' would result in more than 10 pins in this frame.'); // checked
end else begin
fRoll[2] := ARoll;
end;
end;
end else begin // only reachable during unit testing. Shouldn't reach this code as the rolls haven't created a NextFrame
if((fRoll[1] + ARoll) > 10) then begin
raise EBowlException.Create('Trying to add a ball roll of ' + IntToStr(ARoll) +
' would result in more than 10 pins in this frame.'); // unit test
end else begin
fRoll[2] := ARoll;
end;
end;
end else if (fRoll[3] = -1) and (NextFrame = nil) then begin
if (fRoll[1] = 10) or ((fRoll[1] + fRoll[2]) >= 10) then begin // spare or strike allows the third roll to be entered
fRoll[3] := ARoll;
end else begin // whole section only reachable for unit testing.
if (NextFrame = nil) then begin
raise EBowlException.Create('Trying to add a ball roll of ' + IntToStr(ARoll) +
' past the allowed number of rolls. The tenth frame is full.'); // unit test
end else begin // only reachable during unit testing.
raise EBowlException.Create('Trying to add a ball roll of ' + IntToStr(ARoll) +
' past the allowed number of rolls.'); // unit test
end;
end;
end else begin
raise EBowlException.Create('Trying to add a ball roll of ' + IntToStr(ARoll) +
' past the allowed number of rolls.'); // unit test
end;
end;
end;
end.
|
unit ServerMethodsUnit1;
interface
uses
System.SysUtils, System.Classes, System.Json,
Datasnap.DSServer, Datasnap.DSAuth, DataSnap.DSProviderDataModuleAdapter,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Phys.IB, FireDAC.Phys.IBDef, FireDAC.VCLUI.Wait,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Stan.StorageJSON,
FireDAC.Comp.UI, FireDAC.Phys.IBBase,
{Namespace para Reflection}
Data.FireDACJSONReflect, FireDAC.Stan.StorageBin;
type
TServerMethods1 = class(TDSServerModule)
FDConnection1: TFDConnection;
FDPhysIBDriverLink1: TFDPhysIBDriverLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
FDQueryDepartmentNames: TFDQuery;
FDQueryDepartment: TFDQuery;
FDQueryDepartmentEmployees: TFDQuery;
FDStanStorageBinLink1: TFDStanStorageBinLink;
private
{ Private declarations }
public
{ Public declarations }
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
function GetDepartmentNames: TFDJSONDataSets;
function GetDepartmentEmployees(const AID: string): TFDJSONDataSets;
procedure ApplyChangesDepartmentEmployees(const ADeltaList: TFDJSONDeltas);
end;
implementation
{$R *.dfm}
uses
System.StrUtils;
const
sDepartment = 'Department';
sEmployees = 'Employees';
procedure TServerMethods1.ApplyChangesDepartmentEmployees(const ADeltaList: TFDJSONDeltas);
var
LApply: IFDJSONDeltasApplyUpdates;
begin
//ApplyUpdates
LApply := TFDJSONDeltasApplyUpdates.Create(ADeltaList);
LApply.ApplyUpdates(sDepartment, FDQueryDepartment.Command);
if LApply.Errors.Count = 0 then
LApply.ApplyUpdates(sEmployees, FDQueryDepartmentEmployees.Command);
if LApply.Errors.Count > 0 then
raise Exception.Create(LApply.Errors.Strings.Text);
end;
function TServerMethods1.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods1.GetDepartmentEmployees(
const AID: string): TFDJSONDataSets;
begin
FDQueryDepartmentEmployees.Active := False;
FDQueryDepartment.Active := False;
FDQueryDepartment.Params[0].Value := AID;
FDQueryDepartmentEmployees.Params[0].Value := AID;
Result := TFDJSONDataSets.Create;
TFDJSONDataSetsWriter.ListAdd(Result, sDepartment, FDQueryDepartment);
TFDJSONDataSetsWriter.ListAdd(Result, sEmployees , FDQueryDepartmentEmployees);
end;
function TServerMethods1.GetDepartmentNames: TFDJSONDataSets;
begin
FDQueryDepartmentNames.Active := False;
Result := TFDJSONDataSets.Create;
TFDJSONDataSetsWriter.ListAdd(Result, FDQueryDepartmentNames);
end;
function TServerMethods1.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: FShaderMemo<p>
Shader code editor.<p>
<b>Historique : </b><font size=-1><ul>
<li>31/03/11 - Yar - Creation
</ul></font>
}
// TODO: decide how to load templates from external file,
// update it without package recompilation
unit FShaderMemo;
interface
{$I GLScene.inc}
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Win.Registry,
VCL.Controls,
VCL.Forms,
VCL.ComCtrls,
VCL.ImgList,
VCL.Dialogs,
VCL.Menus,
VCL.ActnList,
VCL.ToolWin,
VCL.ExtCtrls,
VCL.StdCtrls,
VCL.Graphics,
//GLS
GLSMemo;
type
TShaderMemoForm = class(TForm)
ImageList: TImageList;
ToolBar: TToolBar;
TBOpen: TToolButton;
TBSave: TToolButton;
TBStayOnTop: TToolButton;
TBHelp: TToolButton;
ToolButton2: TToolButton;
TBCopy: TToolButton;
TBPaste: TToolButton;
TBCut: TToolButton;
ToolButton10: TToolButton;
TBTemplate: TToolButton;
TBUndo: TToolButton;
TBRedo: TToolButton;
ToolButton4: TToolButton;
GLSLMemo: TGLSSynHiMemo;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
TemplateMenu: TPopupMenu;
GLSL120: TMenuItem;
GLSL330: TMenuItem;
GLSL400: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
CompilatorLog: TMemo;
TBIncIndent: TToolButton;
TBDecIndent: TToolButton;
TBComment: TToolButton;
TBUncoment: TToolButton;
ToolButton1: TToolButton;
Panel1: TPanel;
CancelButton: TButton;
OKButton: TButton;
CheckButton: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure GLSLMemoGutterClick(Sender: TObject; LineNo: Integer);
procedure GLSLMemoGutterDraw(Sender: TObject; ACanvas: TCanvas; LineNo: Integer; rct: TRect);
procedure TBOpenClick(Sender: TObject);
procedure TBSaveClick(Sender: TObject);
procedure TBStayOnTopClick(Sender: TObject);
procedure TBUndoClick(Sender: TObject);
procedure GLSLMemoUndoChange(Sender: TObject; CanUndo, CanRedo: Boolean);
procedure TBRedoClick(Sender: TObject);
procedure TBCopyClick(Sender: TObject);
procedure TBPasteClick(Sender: TObject);
procedure TBCutClick(Sender: TObject);
procedure CheckButtonClick(Sender: TObject);
procedure TBIncIndentClick(Sender: TObject);
procedure TBDecIndentClick(Sender: TObject);
procedure TBCommentClick(Sender: TObject);
procedure TBUncomentClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FLightLineStyle: Integer;
FOnCheck: TNotifyEvent;
procedure OnTemplateClick(Sender: TObject);
public
{ Public declarations }
property OnCheck: TNotifyEvent read FOnCheck write FOnCheck;
end;
function GLShaderEditorForm: TShaderMemoForm;
procedure ReleaseGLShaderEditor;
//------------------------------------------------------------------
//------------------------------------------------------------------
//------------------------------------------------------------------
implementation
//------------------------------------------------------------------
//------------------------------------------------------------------
//------------------------------------------------------------------
{$R *.dfm}
const
cRegistryKey = 'Software\GLScene\GLSceneShaderEdit';
{$IFDEF GLS_REGION}{$REGION 'Syntax keywords'}{$ENDIF}
const
GLSLDirectives: array[0..12] of string =
(
'#define',
'#undef',
'#if',
'#ifdef',
'#ifndef',
'#else',
'#elif',
'#endif',
'#error',
'#pragma',
'#extension',
'#version',
'#line'
);
GLSLQualifiers: array[0..33] of string =
(
'attribute', 'const', 'uniform', 'varying',
'layout',
'centroid', 'flat', 'smooth', 'noperspective',
'patch', 'sample',
'break', 'continue', 'do', 'for', 'while', 'switch', 'case', 'default',
'if', 'else',
'subroutine',
'in', 'out', 'inout',
'true', 'false',
'invariant',
'discard', 'return',
'lowp', 'mediump', 'highp', 'precision'
);
GLSLTypes: array[0..85] of string =
(
'float', 'double', 'int', 'void', 'bool',
'mat2', 'mat3', 'mat4', 'dmat2', 'dmat3', 'dmat4',
'mat2x2', 'mat2x3', 'mat2x4', 'dmat2x2', 'dmat2x3', 'dmat2x4',
'mat3x2', 'mat3x3', 'mat3x4', 'dmat3x2', 'dmat3x3', 'dmat3x4',
'mat4x2', 'mat4x3', 'mat4x4', 'dmat4x2', 'dmat4x3', 'dmat4x4',
'vec2', 'vec3', 'vec4', 'ivec2', 'ivec3', 'ivec4', 'bvec2', 'bvec3', 'bvec4', 'dvec2', 'dvec3', 'dvec4',
'uint', 'uvec2', 'uvec3', 'uvec4',
'sampler1D', 'sampler2D', 'sampler3D', 'samplerCube',
'sampler1DShadow', 'sampler2DShadow', 'samplerCubeShadow',
'sampler1DArray', 'sampler2DArray',
'sampler1DArrayShadow', 'sampler2DArrayShadow',
'isampler1D', 'isampler2D', 'isampler3D', 'isamplerCube',
'isampler1DArray', 'isampler2DArray',
'usampler1D', 'usampler2D', 'usampler3D', 'usamplerCube',
'usampler1DArray', 'usampler2DArray',
'sampler2DRect', 'sampler2DRectShadow', 'isampler2DRect', 'usampler2DRect',
'samplerBuffer', 'isamplerBuffer', 'usamplerBuffer',
'sampler2DMS', 'isampler2DMS', 'usampler2DMS',
'sampler2DMSArray', 'isampler2DMSArray', 'usampler2DMSArray',
'samplerCubeArray', 'samplerCubeArrayShadow', 'isamplerCubeArray', 'usamplerCubeArray',
'struct'
);
GLSLBuildIn: array[0..117] of string =
(
'gl_Color',
'gl_SecondaryColor',
'gl_Normal',
'gl_Vertex',
'gl_MultiTexCoord0',
'gl_MultiTexCoord1',
'gl_MultiTexCoord2',
'gl_MultiTexCoord3',
'gl_MultiTexCoord4',
'gl_MultiTexCoord5',
'gl_MultiTexCoord6',
'gl_MultiTexCoord7',
'gl_FogCoord',
'gl_FrontColor',
'gl_BackColor',
'gl_FrontSecondaryColor',
'gl_BackSecondaryColor',
'gl_TexCoord',
'gl_FogFragCoord',
'gl_PointCoord',
'gl_Position',
'gl_PointSize',
'gl_ClipVertex',
'gl_FragCoord',
'gl_FrontFacing',
'gl_FragColor',
'gl_FragData',
'gl_FragDepth',
'gl_VertexID',
'gl_InstanceID',
'gl_in',
'gl_out',
'gl_PrimitiveIDIn',
'gl_InvocationID',
'gl_PrimitiveID',
'gl_Layer',
'gl_PatchVerticesIn',
'gl_TessLevelOuter',
'gl_TessLevelInner',
'gl_TessCoord',
'gl_SampleID',
'gl_SamplePosition',
'gl_SampleMask',
'gl_FrontFacing',
'gl_ClipDistance',
'gl_MaxVertexAttribs',
'gl_MaxVertexUniformComponents',
'gl_MaxVaryingFloats',
'gl_MaxVaryingComponents',
'gl_MaxVertexOutputComponents',
'gl_MaxGeometryInputComponents',
'gl_MaxGeometryOutputComponents',
'gl_MaxFragmentInputComponents',
'gl_MaxVertexTextureImageUnits',
'gl_MaxCombinedTextureImageUnits',
'gl_MaxTextureImageUnits',
'gl_MaxFragmentUniformComponents',
'gl_MaxDrawBuffers',
'gl_MaxClipDistances',
'gl_MaxGeometryTextureImageUnits',
'gl_MaxGeometryOutputVertices',
'gl_MaxGeometryTotalOutputComponents',
'gl_MaxGeometryUniformComponents',
'gl_MaxGeometryVaryingComponents',
'gl_MaxTessControlInputComponents',
'gl_MaxTessControlOutputComponents',
'gl_MaxTessControlTextureImageUnits',
'gl_MaxTessControlUniformComponents',
'gl_MaxTessControlTotalOutputComponents',
'gl_MaxTessEvaluationInputComponents',
'gl_MaxTessEvaluationOutputComponents',
'gl_MaxTessEvaluationTextureImageUnits',
'gl_MaxTessEvaluationUniformComponents',
'gl_MaxTessPatchComponents',
'gl_MaxPatchVertices',
'gl_MaxTessGenLevel',
'gl_MaxTextureUnits',
'gl_MaxTextureCoords',
'gl_MaxClipPlanes',
'gl_DepthRange',
'gl_ModelViewMatrix',
'gl_ProjectionMatrix',
'gl_ModelViewProjectionMatrix',
'gl_TextureMatrix',
'gl_NormalMatrix',
'gl_ModelViewMatrixInverse',
'gl_ProjectionMatrixInverse',
'gl_ModelViewProjectionMatrixInverse',
'gl_TextureMatrixInverse',
'gl_ModelViewMatrixTranspose',
'gl_ProjectionMatrixTranspose',
'gl_ModelViewProjectionMatrixTranspose',
'gl_TextureMatrixTranspose',
'gl_ModelViewMatrixInverseTranspose',
'gl_ProjectionMatrixInverseTranspose',
'gl_ModelViewProjectionMatrixInverseTranspose',
'gl_TextureMatrixInverseTranspose',
'gl_NormalScale',
'gl_ClipPlane',
'gl_Point',
'gl_FrontMaterial',
'gl_BackMaterial',
'gl_LightSource',
'gl_LightModel',
'gl_FrontLightModelProduct',
'gl_BackLightModelProduct',
'gl_FrontLightProduct',
'gl_BackLightProduct',
'gl_TextureEnvColor',
'gl_EyePlaneS',
'gl_EyePlaneT',
'gl_EyePlaneR',
'gl_EyePlaneQ',
'gl_ObjectPlaneS',
'gl_ObjectPlaneT',
'gl_ObjectPlaneR',
'gl_ObjectPlaneQ',
'gl_Fog'
);
GLSLFunctions: array[0..139] of string =
(
// Angle and Trigonometry Functions
'radians',
'degrees',
'sin',
'cos',
'tan',
'asin',
'acos',
'atan',
'sinh',
'cosh',
'tanh',
'asinh',
'acosh',
'atanh',
// Exponetial
'pow',
'exp',
'log',
'exp2',
'log2',
'sqrt',
'inversesqrt',
// Common
'abs',
'sign',
'floor',
'trunc',
'round',
'roundEven',
'ceil',
'fract',
'mod',
'min',
'max',
'clamp',
'mix',
'step',
'smoothstep',
'isnan',
'isinf',
'floatBitsToInt',
'floatBitsToUint',
'intBitsToFloat',
'uintBitsToFloat',
'fma',
'frexp',
'ldexp',
// Floating-Point Pack and Unpack Functions
'packUnorm2x16',
'packUnorm4x8',
'packSnorm4x8',
'unpackUnorm2x16',
'unpackUnorm4x8',
'unpackSnorm4x8',
'packDouble2x32',
'unpackDouble2x32',
// Geometric
'length',
'distance',
'dot',
'cross',
'normalize',
'ftransform',
'faceforward',
'reflect',
'maxtrixCompMult',
'outerProduct',
'transpose',
'determinant',
'inverse',
// Vector
'lessThan',
'lessThanEqual',
'greaterThan',
'greaterThanEqual',
'equal',
'notEqual',
'any',
'all',
'not',
// Integer Functions
'uaddCarry',
'usubBorrow',
'umulExtended',
'bitfieldExtract',
'bitfieldInsert',
'bitfieldReverse',
'bitCount',
'findLSB',
'findMSB',
// Texture
'texture1D',
'texture1DProj',
'texture1DLod',
'texture1DProjLod',
'texture2D',
'texture2DProj',
'texture2DLod',
'texture2DProjLod',
'texture3D',
'texture3DProj',
'texture3DLod',
'texture3DProjLod',
'textureCube',
'textureCubeLod',
'shadow1D',
'shadow1DProj',
'shadow1DLod',
'shadow1DProjLod',
'shadow2D',
'shadow2DProj',
'shadow2DLod',
'shadow2DProjLod',
'textureSize',
'textureQueryLod',
'texture',
'textureProj',
'textureLod',
'textureOffset',
'texelFetch',
'texelFetchOffset',
'textureProjOffset',
'textureLodOffset',
'textureProjLod',
'textureProjLodOffset',
'textureGrad',
'textureGradOffset',
'textureProjGrad',
'textureProjGradOffset',
'textureGather',
'textureGatherOffset',
'textureGatherOffsets',
// Fragment
'dFdx',
'dFdy',
'fwidth',
// Interpolation Functions
'interpolateAtCentroid',
'interpolateAtSample',
'interpolateAtOffset',
// Noise
'noise1',
'noise2',
'noise3',
'noise4',
// Geometry Shader Functions
'EmitStreamVertex',
'EndStreamPrimitive',
'EmitVertex',
'EndPrimitive',
// Shader Invocation Control Functions
'barrier'
);
{$IFDEF GLS_REGION}{$ENDREGION}{$ENDIF}
{$IFDEF GLS_REGION}{$REGION 'Shader template'}{$ENDIF}
const
cTemplates: array[0..6] of string =
(
'#version 120'#10#13+
#10#13+
'attribute vec3 Position;'#10#13+
'attribute vec3 Normal;'#10#13+
'varying vec3 v2f_Normal;'#10#13+
'varying vec3 v2f_LightDir;'#10#13+
'varying vec3 v2f_ViewDir;'#10#13+
#10#13+
'uniform mat4 ModelMatrix;'#10#13+
'uniform mat4 ViewProjectionMatrix;'#10#13+
'uniform mat3 NormalMatrix;'#10#13+
'uniform vec4 LightPosition;'#10#13+
'uniform vec4 CameraPosition;'#10#13+
#10#13+
'void main()'#10#13+
'{'#10#13+
' vec4 WorldPos = ModelMatrix * vec4(Position,1.0);'#10#13+
' gl_Position = ViewProjectionMatrix * WorldPos;'#10#13+
' v2f_Normal = NormalMatrix * Normal;'#10#13+
' v2f_LightDir = LightPosition.xyz - WorldPos.xyz;'#10#13+
' v2f_ViewDir = CameraPosition.xyz - WorldPos.xyz;'#10#13+
'}'#10#13,
//-----------------------------------------------------------------------
'#version 120'#10#13+
#10#13+
'attribute vec3 Position;'#10#13+
'attribute vec3 Normal;'#10#13+
'attribute vec3 Tangent;'#10#13+
'attribute vec3 Binormal;'#10#13+
'attribute vec2 TexCoord0;'#10#13+
#10#13+
'varying vec2 v2f_TexCoord;'#10#13+
'varying vec3 v2f_Normal;'#10#13+
'varying vec3 v2f_Tangent;'#10#13+
'varying vec3 v2f_Binormal;'#10#13+
'varying vec3 v2f_LightDir;'#10#13+
'varying vec3 v2f_ViewDir;'#10#13+
#10#13+
'uniform mat4 ModelMatrix;'#10#13+
'uniform mat4 ViewProjectionMatrix;'#10#13+
'uniform vec4 LightPosition;'#10#13+
'uniform vec4 CameraPosition;'#10#13+
'uniform vec2 BaseTextureRepeat;'#10#13+
#10#13+
'void main()'#10#13+
'{'#10#13+
' vec3 WorldPos = (ModelMatrix * vec4(Position,1.0)).xyz;'#10#13+
' gl_Position = ViewProjectionMatrix * vec4(WorldPos, 1.0);'#10#13+
' v2f_TexCoord = TexCoord0.xy*BaseTextureRepeat;'#10#13+
' v2f_Normal = Normal;'#10#13+
' v2f_Tangent = Tangent;'#10#13+
' v2f_Binormal = Binormal;'#10#13+
' v2f_LightDir = LightPosition.xyz - WorldPos.xyz;'#10#13+
' v2f_ViewDir = CameraPosition.xyz - WorldPos.xyz;'#10#13+
'}'#10#13,
//-----------------------------------------------------------------------
'#version 120'#10#13+
#10#13+
'varying vec3 v2f_Normal;'#10#13+
'varying vec3 v2f_LightDir;'#10#13+
'varying vec3 v2f_ViewDir;'#10#13+
#10#13+
'uniform vec4 MaterialAmbientColor;'#10#13+
'uniform vec4 MaterialDiffuseColor;'#10#13+
'uniform vec4 MaterialSpecularColor;'#10#13+
'uniform float MaterialShiness;'#10#13+
#10#13+
'void main()'#10#13+
'{'#10#13+
' vec3 N = normalize(v2f_Normal);'#10#13+
#10#13+
' vec3 L = normalize(v2f_LightDir);'#10#13+
' float DiffuseIntensity = max( dot( N, L ), 0.0);'#10#13+
' vec4 cDiffuse = DiffuseIntensity * MaterialDiffuseColor;'#10#13+
#10#13+
' vec4 cSpecular = vec4(0.0);'#10#13+
' if (DiffuseIntensity > 0.0)'#10#13+
' {'#10#13+
' vec3 V = normalize(v2f_ViewDir);'#10#13+
' vec3 R = reflect(-V, N);'#10#13+
' float RdotL = max( dot( L, R ), 0.0);'#10#13+
' if (RdotL > 0.0)'#10#13+
' cSpecular = pow( RdotL, MaterialShiness) * MaterialSpecularColor;'#10#13+
' }'#10#13+
#10#13+
' gl_FragColor = MaterialAmbientColor + cDiffuse + cSpecular;'#10#13+
'}'#10#13,
//-----------------------------------------------------------------------
'#version 120'#10#13+
#10#13+
'varying vec3 v2f_Normal;'#10#13+
'varying vec3 v2f_Tangent;'#10#13+
'varying vec3 v2f_Binormal;'#10#13+
'varying vec3 v2f_LightDir;'#10#13+
'varying vec3 v2f_ViewDir;'#10#13+
'varying vec2 v2f_TexCoord;'#10#13+
#10#13+
'uniform mat3 NormalMatrix;'#10#13+
'uniform sampler2D DiffuseMap;'#10#13+
'uniform sampler2D NormalMap;'#10#13+
#10#13+
'uniform vec4 MaterialAmbientColor;'#10#13+
'uniform vec4 MaterialDiffuseColor;'#10#13+
'uniform vec4 MaterialSpecularColor;'#10#13+
'uniform float MaterialShiness;'#10#13+
#10#13+
'void main()'#10#13+
'{'#10#13+
' vec3 normal = normalize(v2f_Normal);'#10#13+
' vec3 tangent = normalize(v2f_Tangent);'#10#13+
' vec3 binormal = normalize(v2f_Binormal);'#10#13+
' mat3 basis = mat3(tangent, binormal, normal);'#10#13+
' vec3 N = texture2D(NormalMap, v2f_TexCoord).xyz;'#10#13+
' N = N * vec3(2.0) - vec3(1.0);'#10#13+
' N = basis*N;'#10#13+
' N = NormalMatrix*N;'#10#13+
' N = normalize(N);'#10#13+
#10#13+
' vec3 L = normalize(v2f_LightDir);'#10#13+
' float DiffuseIntensity = max( dot( N, L ), 0.0);'#10#13+
' vec4 cDiffuse = DiffuseIntensity * MaterialDiffuseColor;'#10#13+
#10#13+
' vec4 cSpecular = vec4(0.0);'#10#13+
' if (DiffuseIntensity > 0.0)'#10#13+
' {'#10#13+
' vec3 V = normalize(v2f_ViewDir);'#10#13+
' vec3 R = reflect(-V, N);'#10#13+
' float RdotL = max( dot( L, R ), 0.0);'#10#13+
' if (RdotL > 0.0)'#10#13+
' cSpecular = pow( RdotL, MaterialShiness) * MaterialSpecularColor;'#10#13+
' }'#10#13+
#10#13+
' vec4 cBaseColor = texture2D( DiffuseMap, v2f_TexCoord);'#10#13+
' gl_FragColor = (MaterialAmbientColor + cDiffuse ) * cBaseColor + cSpecular;'#10#13+
'}'#10#13,
//-----------------------------------------------------------------------
'#version 330'#10#13+
'layout(triangles_adjacency) in;'#10#13+
'layout(line_strip, max_vertices = 6) out;'#10#13+
'in vec4 v2g_WorldPos[]; // Vertex position in view space'#10#13+
'uniform vec4 CameraPosition;'#10#13+
#10#13+
'// calculating facing of a triangle relative to eye'#10#13+
'float facing(vec4 v0, vec4 v1, vec4 v2, vec4 eye_pos)'#10#13+
'{'#10#13+
' vec3 e0 = v1.xyz - v0.xyz;'#10#13+
' vec3 e1 = v2.xyz - v0.xyz;'#10#13+
' vec4 p;'#10#13+
' p.xyz = cross(e1, e0);'#10#13+
' p.w = -dot(v0.xyz, p.xyz);'#10#13+
' return -dot(p, eye_pos);'#10#13+
'}'#10#13+
#10#13+
'// output lines on silhouette edges by comparing facing of adjacent triangles'#10#13+
'void main()'#10#13+
'{'#10#13+
' float f = facing(v2g_WorldPos[0], v2g_WorldPos[2], v2g_WorldPos[4], CameraPosition);'#10#13+
' // only look at front facing triangles'#10#13+
' if (f > 0.0)'#10#13+
' {'#10#13+
' float f;'#10#13+
' // test edge 0'#10#13+
' f = facing(v2g_WorldPos[0], v2g_WorldPos[1], v2g_WorldPos[2], CameraPosition);'#10#13+
' if (f <= 0)'#10#13+
' {'#10#13+
' gl_Position = gl_in[0].gl_Position;'#10#13+
' EmitVertex();'#10#13+
' gl_Position = gl_in[2].gl_Position;'#10#13+
' EmitVertex();'#10#13+
' EndPrimitive();'#10#13+
' }'#10#13+
#10#13+
' // test edge 1'#10#13+
' f = facing(v2g_WorldPos[2], v2g_WorldPos[3], v2g_WorldPos[4], CameraPosition);'#10#13+
' if (f <= 0.0)'#10#13+
' {'#10#13+
' gl_Position = gl_in[2].gl_Position;'#10#13+
' EmitVertex();'#10#13+
' gl_Position = gl_in[4].gl_Position;'#10#13+
' EmitVertex();'#10#13+
' EndPrimitive();'#10#13+
' }'#10#13+
#10#13+
' // test edge 2'#10#13+
' f = facing(v2g_WorldPos[4], v2g_WorldPos[5], v2g_WorldPos[0], CameraPosition);'#10#13+
' if (f <= 0.0)'#10#13+
' {'#10#13+
' gl_Position = gl_in[4].gl_Position;'#10#13+
' EmitVertex();'#10#13+
' gl_Position = gl_in[0].gl_Position;'#10#13+
' EmitVertex();'#10#13+
' EndPrimitive();'#10#13+
' }'#10#13+
' }'#10#13+
'}'#10#13,
//-----------------------------------------------------------------------
'attribute vec3 Position;'#10#13+
'attribute vec4 Color;'#10#13+
'attribute vec3 Normal;'#10#13+
'attribute vec3 Tangent;'#10#13+
'attribute vec3 Binormal;'#10#13+
'attribute vec2 TexCoord0;'#10#13+
'attribute vec2 TexCoord1;'#10#13+
'attribute vec2 TexCoord2;'#10#13+
'attribute vec2 TexCoord3;'#10#13+
'attribute vec2 TexCoord4;'#10#13+
'attribute vec2 TexCoord5;'#10#13+
'attribute vec2 TexCoord6;'#10#13+
'attribute vec2 TexCoord7;'#10#13+
'attribute vec4 Custom0;'#10#13+
'attribute vec2 Custom1;'#10#13+
'attribute vec2 Custom2;'#10#13,
//-----------------------------------------------------------------------
'in vec3 Position;'#10#13+
'in vec4 Color;'#10#13+
'in vec3 Normal;'#10#13+
'in vec3 Tangent;'#10#13+
'in vec3 Binormal;'#10#13+
'in vec2 TexCoord0;'#10#13+
'in vec2 TexCoord1;'#10#13+
'in vec2 TexCoord2;'#10#13+
'in vec2 TexCoord3;'#10#13+
'in vec2 TexCoord4;'#10#13+
'in vec2 TexCoord5;'#10#13+
'in vec2 TexCoord6;'#10#13+
'in vec2 TexCoord7;'#10#13+
'in vec4 Custom0;'#10#13+
'in vec2 Custom1;'#10#13+
'in vec2 Custom2;'#10#13
);
{$IFDEF GLS_REGION}{$ENDREGION}{$ENDIF}
type
TFriendlyMemo = class(TGLSSynHiMemo);
var
vGLShaderEditor: TShaderMemoForm;
function GLShaderEditorForm: TShaderMemoForm;
begin
if not Assigned(vGLShaderEditor) then
vGLShaderEditor := TShaderMemoForm.Create(nil);
Result := vGLShaderEditor;
end;
procedure ReleaseGLShaderEditor;
begin
if Assigned(vGLShaderEditor) then
begin
vGLShaderEditor.Free;
vGLShaderEditor := nil;
end;
end;
function ReadRegistryInteger(reg: TRegistry; const name: string;
defaultValue: Integer): Integer;
begin
if reg.ValueExists(name) then
Result := reg.ReadInteger(name)
else
Result := defaultValue;
end;
procedure TShaderMemoForm.FormCreate(Sender: TObject);
var
reg: TRegistry;
No: Integer;
item: TMenuItem;
begin
reg := TRegistry.Create;
try
if reg.OpenKey(cRegistryKey, True) then
begin
Left := ReadRegistryInteger(reg, 'Left', Left);
Top := ReadRegistryInteger(reg, 'Top', Top);
Width := ReadRegistryInteger(reg, 'Width', 500);
Height := ReadRegistryInteger(reg, 'Height', 640);
end;
finally
reg.Free;
end;
No := GLSLMemo.Styles.Add(clRed, clWhite, []);
GLSLMemo.AddWord(No, GLSLDirectives);
No := GLSLMemo.Styles.Add(clPurple, clWhite, [fsBold]);
GLSLMemo.AddWord(No, GLSLQualifiers);
No := GLSLMemo.Styles.Add(clBlue, clWhite, [fsBold]);
GLSLMemo.AddWord(No, GLSLTypes);
No := GLSLMemo.Styles.Add(clGray, clWhite, [fsBold]);
GLSLMemo.AddWord(No, GLSLBuildIn);
No := GLSLMemo.Styles.Add(clGreen, clWhite, [fsItalic]);
GLSLMemo.AddWord(No, GLSLFunctions);
No := GLSLMemo.Styles.Add(clYellow, clSilver, [fsItalic]);
GLSLMemo.AddWord(No, GLSLFunctions);
FLightLineStyle := GLSLMemo.Styles.Add(clBlack, clLtGray, []);
GLSLMemo.MultiCommentLeft := '/*';
GLSLMemo.MultiCommentRight := '*/';
GLSLMemo.LineComment := '//';
GLSLMemo.CaseSensitive := True;
GLSLMemo.DelErase := True;
item := NewItem('Attribute block', 0, False, True, OnTemplateClick, 0, '');
item.Tag := 5;
GLSL120.Add(item);
item := NewItem('Basic vertex program', 0, False, True, OnTemplateClick, 0, '');
item.Tag := 0;
GLSL120.Add(item);
item := NewItem('Basic vertex program with TBN pass', 0, False, True, OnTemplateClick, 0, '');
item.Tag := 1;
GLSL120.Add(item);
item := NewItem('Basic fragment program, Phong lighting', 0, False, True, OnTemplateClick, 0, '');
item.Tag := 2;
GLSL120.Add(item);
item := NewItem('Fragment program, normal mapping', 0, False, True, OnTemplateClick, 0, '');
item.Tag := 3;
GLSL120.Add(item);
item := NewItem('Attribute block', 0, False, True, OnTemplateClick, 0, '');
item.Tag := 6;
GLSL330.Add(item);
item := NewItem('Geometry program, edge detection', 0, False, True, OnTemplateClick, 0, '');
item.Tag := 4;
GLSL330.Add(item);
end;
procedure TShaderMemoForm.FormDestroy(Sender: TObject);
var
reg: TRegistry;
begin
reg := TRegistry.Create;
try
if reg.OpenKey(cRegistryKey, True) then
begin
reg.WriteInteger('Left', Left);
reg.WriteInteger('Top', Top);
reg.WriteInteger('Width', Width);
reg.WriteInteger('Height', Height);
end;
finally
reg.Free;
end;
end;
procedure TShaderMemoForm.FormShow(Sender: TObject);
begin
if GLSLMemo.Lines.Count = 0 then
GLSLMemo.Lines.Add('');
end;
procedure TShaderMemoForm.GLSLMemoGutterClick(Sender: TObject; LineNo: Integer);
begin
with GLSLMemo do
begin
LineStyle[LineNo] := FLightLineStyle - LineStyle[LineNo];
end;
end;
procedure TShaderMemoForm.GLSLMemoGutterDraw(Sender: TObject; ACanvas: TCanvas;
LineNo: Integer; rct: TRect);
var
txt: string;
begin
if GLSLMemo.LineStyle[LineNo] = FLightLineStyle then
with rct, ACanvas do
begin
Pen.Color := GLSLMemo.GutterColor;
Brush.Color := clWhite;
Font.Style := Font.Style + [fsBold];
txt := IntToStr(LineNo+1);
TextRect(rct, txt, [tfCenter]);
end;
end;
procedure TShaderMemoForm.GLSLMemoUndoChange(Sender: TObject; CanUndo, CanRedo: Boolean);
begin
TBUndo.Enabled := CanUndo;
TBRedo.Enabled := CanRedo;
end;
procedure TShaderMemoForm.OnTemplateClick(Sender: TObject);
begin
GLSLMemo.InsertTemplate(cTemplates[TMenuItem(Sender).Tag]);
end;
procedure TShaderMemoForm.TBCommentClick(Sender: TObject);
var
I: Integer;
S, E: Integer;
begin
with TFriendlyMemo(GLSLMemo) do
begin
if SelLength > 0 then
begin
S := SelStart.Y;
E := SelEnd.Y;
for I := S to E do
begin
SetCursor(0, I);
InsertChar('/');
InsertChar('/');
end;
SelectLines(S, E);
end;
end;
end;
procedure TShaderMemoForm.TBUncomentClick(Sender: TObject);
var
I: Integer;
S, E: Integer;
C: string;
begin
with TFriendlyMemo(GLSLMemo) do
begin
if SelLength > 0 then
begin
S := SelStart.Y;
E := SelEnd.Y;
for I := S to E do
begin
C := Lines[I];
if (C[1] = '/') and (C[2] = '/') then
begin
Delete(C, 1, 2);
Lines[I] := C;
LineStyle[I] := 0;
end;
end;
SelectLines(S, E);
end;
end;
end;
procedure TShaderMemoForm.TBCopyClick(Sender: TObject);
begin
GLSLMemo.CopyToClipBoard;
end;
procedure TShaderMemoForm.TBCutClick(Sender: TObject);
begin
GLSLMemo.CutToClipBoard;
end;
procedure TShaderMemoForm.TBIncIndentClick(Sender: TObject);
var
I: Integer;
S, E: Integer;
begin
with TFriendlyMemo(GLSLMemo) do
begin
if SelLength > 0 then
begin
S := SelStart.Y;
E := SelEnd.Y;
for I := S to E do
begin
SetCursor(0, I);
InsertChar(#9);
end;
SelectLines(S, E);
end;
end;
end;
procedure TShaderMemoForm.TBDecIndentClick(Sender: TObject);
var
I, J: Integer;
S, E: Integer;
C: string;
begin
with TFriendlyMemo(GLSLMemo) do
begin
if SelLength > 0 then
begin
S := SelStart.Y;
E := SelEnd.Y;
for I := S to E do
begin
C := Lines[I];
for J := 1 to TabSize do
if C[1] = ' ' then
Delete(C, 1, 1);
Lines[I] := C;
end;
SelectLines(S, E);
end;
end;
end;
procedure TShaderMemoForm.TBOpenClick(Sender: TObject);
begin
if OpenDialog.Execute then
GLSLMemo.Lines.LoadFromFile(OpenDialog.FileName);
SetFocus;
end;
procedure TShaderMemoForm.TBPasteClick(Sender: TObject);
begin
GLSLMemo.PasteFromClipBoard;
end;
procedure TShaderMemoForm.TBRedoClick(Sender: TObject);
begin
with GLSLMemo do
begin
Redo;
SetFocus;
end;
end;
procedure TShaderMemoForm.TBSaveClick(Sender: TObject);
begin
if SaveDialog.Execute then
GLSLMemo.Lines.SaveToFile(SaveDialog.FileName);
SetFocus;
end;
procedure TShaderMemoForm.TBStayOnTopClick(Sender: TObject);
begin
if TBStayOnTop.Down then
FormStyle := fsStayOnTop
else
FormStyle := fsNormal;
end;
procedure TShaderMemoForm.TBUndoClick(Sender: TObject);
begin
with GLSLMemo do
begin
Undo;
SetFocus;
end;
end;
procedure TShaderMemoForm.CheckButtonClick(Sender: TObject);
begin
if Assigned(FOnCheck) then
FOnCheck(Self);
end;
initialization
finalization
ReleaseGLShaderEditor;
end.
|
unit ANovoCaixa;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, Db, DBTables, Tabela,
CBancoDados, StdCtrls, Buttons, Mask, DBCtrls, Localizacao,
DBKeyViolation, BotaoCadastro, UnCaixa, Grids, CGrades, UnDadosCR, UnContasAReceber,
numericos, Constantes;
type
TFNovoCaixa = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
Localiza: TConsultaPadrao;
Label3: TLabel;
Label4: TLabel;
ValidaGravacao1: TValidaGravacao;
PanelColor3: TPanelColor;
PanelColor4: TPanelColor;
PanelColor2: TPanelColor;
Label7: TLabel;
Grade: TRBStringGridColor;
EFormaPagamento: TEditLocaliza;
Label1: TLabel;
SpeedButton1: TSpeedButton;
Label2: TLabel;
EContaCaixa: TEditLocaliza;
ESeqCaixa: Tnumerico;
EDatAbertura: TEditColor;
Label5: TLabel;
SpeedButton2: TSpeedButton;
Label6: TLabel;
EUsuario: TEditLocaliza;
EValInicial: Tnumerico;
BGravar: TBitBtn;
BCancelar: TBitBtn;
EValCheques: Tnumerico;
Label8: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EContaCaixaCadastrar(Sender: TObject);
procedure EContaCaixaChange(Sender: TObject);
procedure BGravarClick(Sender: TObject);
procedure EContaCaixaRetorno(Retorno1, Retorno2: String);
procedure GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer);
procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean);
procedure GradeGetEditMask(Sender: TObject; ACol, ARow: Integer;
var Value: String);
procedure GradeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure EFormaPagamentoCadastrar(Sender: TObject);
procedure EFormaPagamentoRetorno(Retorno1, Retorno2: String);
procedure GradeKeyPress(Sender: TObject; var Key: Char);
procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
procedure GradeNovaLinha(Sender: TObject);
procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure GradeDepoisExclusao(Sender: TObject);
procedure BCancelarClick(Sender: TObject);
private
{ Private declarations }
VprAcao : Boolean;
VprOperacao : TRBDOperacaoCadastro;
VprCodFormaPagamentoAnterior : String;
VprDCaixa : TRBDCaixa;
VprDFormaPagamento : TRBDCaixaFormaPagamento;
FunCaixa : TRBFuncoesCaixa;
procedure CarTituloGrade;
procedure InicializaTela;
procedure CarDCaixaFormaPagamento;
procedure CarDClasse;
function ExisteFormaPagamento : Boolean;
procedure AtualizaValTotal;
public
{ Public declarations }
function NovoCaixa : boolean;
end;
var
FNovoCaixa: TFNovoCaixa;
implementation
uses APrincipal, ANovaConta, ConstMsg, FunString,
AFormasPagamento;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFNovoCaixa.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
CarTituloGrade;
VprAcao := false;
FunCaixa := TRBFuncoesCaixa.cria(FPrincipal.BaseDados);
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFNovoCaixa.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
FunCaixa.Free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
procedure TFNovoCaixa.EContaCaixaCadastrar(Sender: TObject);
begin
FNovaConta := TFNovaConta.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovaConta'));
FNovaConta.CadContas.Insert;
FNovaConta.showmodal;
FNovaConta.free;
Localiza.AtualizaConsulta;
end;
{******************************************************************************}
procedure TFNovoCaixa.EContaCaixaChange(Sender: TObject);
begin
if VprOperacao in [ocedicao,ocinsercao] then
ValidaGravacao1.execute;
end;
{******************************************************************************}
function TFNovoCaixa.NovoCaixa : boolean;
begin
VprOperacao := ocinsercao;
VprDCaixa := TRBDCaixa.cria;
Grade.ADados := VprDCaixa.FormasPagamento;
Grade.CarregaGrade;
InicializaTela;
Showmodal;
result := VprAcao;
VprDCaixa.free;
end;
{******************************************************************************}
procedure TFNovoCaixa.CarTituloGrade;
begin
Grade.Cells[1,0] := 'Código';
Grade.Cells[2,0] := 'Forma Pagamento';
Grade.Cells[3,0] := 'Valor Inicial';
end;
{******************************************************************************}
procedure TFNovoCaixa.InicializaTela;
begin
VprDCaixa.CodUsuarioAbertura := Varia.CodigoUsuario;
VprDCaixa.DatAbertura := now;
EDatAbertura.Text := FormatDateTime('DD/MM/YYYY HH:MM:SS',VprDCaixa.DatAbertura);
EUsuario.AInteiro := varia.CodigoUsuario;
EUsuario.Atualiza;
ValidaGravacao1.execute;
end;
{******************************************************************************}
procedure TFNovoCaixa.CarDCaixaFormaPagamento;
begin
VprDFormaPagamento.ValInicial := StrToFloat(DeletaChars(Grade.Cells[3,Grade.ALinha],'.'));
AtualizaValTotal;
end;
{******************************************************************************}
procedure TFNovoCaixa.CarDClasse;
begin
VprDCaixa.NumConta := EContaCaixa.Text;
end;
{******************************************************************************}
function TFNovoCaixa.ExisteFormaPagamento : Boolean;
begin
result := false;
if Grade.Cells[1,Grade.ALinha] <> '' then
begin
if Grade.Cells[1,Grade.ALinha] = VprCodFormaPagamentoAnterior then
result := true
else
begin
result := FunContasAReceber.ExisteFormaPagamento(StrToInt(Grade.cells[1,Grade.ALinha]),VprDFormaPagamento);
if result then
begin
VprCodFormaPagamentoAnterior := Grade.Cells[1,Grade.ALinha];
Grade.Cells[2,Grade.ALinha] := VprDFormaPagamento.NomFormaPagamento;
end;
end;
end;
end;
{******************************************************************************}
procedure TFNovoCaixa.AtualizaValTotal;
begin
VprDCaixa.ValInicial := FunCaixa.RValTotalFormaPagamento(VprDCaixa);
EValInicial.AValor := VprDCaixa.ValInicial;
end;
{******************************************************************************}
procedure TFNovoCaixa.BGravarClick(Sender: TObject);
var
VpfResultado : string;
begin
CarDClasse;
VpfResultado := FunCaixa.GravaDCaixa(VprDCaixa);
if VpfResultado = '' then
VpfResultado := FunCaixa.AtualizaSeqCaixaContaCaixa(VprDCaixa.NumConta,VprDCaixa.SeqCaixa);
if VpfResultado = '' then
begin
ESeqCaixa.AsInteger := VprDCaixa.SeqCaixa;
VprAcao := true;
close;
end
else
Aviso(VpfResultado);
end;
{******************************************************************************}
procedure TFNovoCaixa.EContaCaixaRetorno(Retorno1, Retorno2: String);
begin
If retorno2 <> '' then
begin
EContaCaixa.SetFocus;
aviso('CONTA CAIXA JÁ EXISTE ABERTA!!!'#13'Não é possível abrir uma conta que ainda não foi fechada.');
end;
if retorno1 <> '' then
begin
FunCaixa.InicializaValoresCaixa(VprDCaixa,StrToInt(Retorno1));
AtualizaValTotal;
Grade.CarregaGrade;
end;
end;
{******************************************************************************}
procedure TFNovoCaixa.GradeCarregaItemGrade(Sender: TObject;
VpaLinha: Integer);
begin
VprDFormaPagamento := TRBDCaixaFormaPagamento(VprDCaixa.FormasPagamento.Items[VpaLinha-1]);
if VprDFormaPagamento.CodFormaPagamento <> 0 then
Grade.Cells[1,VpaLinha] := IntToStr(VprDFormaPagamento.CodFormaPagamento)
else
Grade.Cells[1,VpaLinha] := '';
Grade.Cells[2,VpaLinha] := VprDFormaPagamento.NomFormaPagamento;
if VprDFormaPagamento.ValInicial <> 0 then
Grade.Cells[3,VpaLinha] := FormatFloat(varia.MascaraValor,VprDFormaPagamento.ValInicial)
else
Grade.Cells[3,VpaLinha] := '';
end;
{******************************************************************************}
procedure TFNovoCaixa.GradeDadosValidos(Sender: TObject;
var VpaValidos: Boolean);
begin
VpaValidos := true;
if not ExisteFormaPagamento then
begin
aviso('FORMA DE PAGAMENTO NÃO CADASTRADA!!!'+#13+'A forma de pagamento digita não existe cadastrada...');
VpaValidos := false;
Grade.col := 1;
end
else
if Grade.Cells[3,Grade.ALinha] = '' then
begin
aviso('VALOR INICIAL NÃO PREENCHIDO!!!'+#13+'É necessário preencher o valor inicial.');
VpaValidos := false;
Grade.Col := 3;
end;
if VpaValidos then
CarDCaixaFormaPagamento;
if VpaValidos then
begin
if VprDFormaPagamento.ValInicial = 0 then
begin
aviso('VALOR INICIAL NÃO PREENCHIDO!!!'+#13+'É necessário preencher o valor inicial.');
VpaValidos := false;
Grade.Col := 3;
end;
if VpaValidos then
begin
if FunCaixa.FormaPagamentoDuplicada(VprDCaixa) then
begin
aviso('FORMA DE PAGAMENTO DUPLICADO!!!'+#13+'Não é permitido duplicar a mesma forma de pagamento.');
VpaValidos := false;
Grade.Col := 1;
end;
end;
end;
end;
{******************************************************************************}
procedure TFNovoCaixa.GradeGetEditMask(Sender: TObject; ACol,
ARow: Integer; var Value: String);
begin
case ACol of
1 : Value := '00000;0; ';
end;
end;
{******************************************************************************}
procedure TFNovoCaixa.GradeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case key of
114 :
begin // F3
case Grade.Col of
1 : EFormaPagamento.AAbreLocalizacao;
end;
end;
end;
end;
{******************************************************************************}
procedure TFNovoCaixa.EFormaPagamentoCadastrar(Sender: TObject);
begin
FFormasPagamento := TFFormasPagamento.CriarSDI(self,'',FPrincipal.VerificaPermisao('FFormasPagamento'));
FFormasPagamento.BotaoCadastrar1.Click;
FFormasPagamento.showmodal;
FFormasPagamento.free;
Localiza.AtualizaConsulta;
end;
{******************************************************************************}
procedure TFNovoCaixa.EFormaPagamentoRetorno(Retorno1, Retorno2: String);
begin
if Retorno1 <> '' then
begin
Grade.Cells[1,Grade.ALinha] := EFormaPagamento.Text;
Grade.cells[2,grade.ALinha] := Retorno1;
VprDFormaPagamento.CodFormaPagamento := EFormaPagamento.AInteiro;
VprDFormaPagamento.NomFormaPagamento := Retorno1;
VprCodFormaPagamentoAnterior := EFormaPagamento.Text;
end
else
begin
Grade.Cells[1,Grade.ALinha] := '';
Grade.Cells[2,Grade.ALinha] := '';
VprDFormaPagamento.CodFormaPagamento :=0;
end;
end;
{******************************************************************************}
procedure TFNovoCaixa.GradeKeyPress(Sender: TObject; var Key: Char);
begin
case Grade.Col of
2 : key := #0;
end;
if (key = '.') and (Grade.col in [3]) then
key := DecimalSeparator;
end;
{******************************************************************************}
procedure TFNovoCaixa.GradeMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
begin
if VprDCaixa.FormasPagamento.Count > 0 then
begin
VprDFormaPagamento := TRBDCaixaFormaPagamento(VprDCaixa.FormasPagamento.Items[VpaLinhaAtual -1]);
VprCodFormaPagamentoAnterior := IntToStr(VprDFormaPagamento.CodFormaPagamento);
end;
end;
{******************************************************************************}
procedure TFNovoCaixa.GradeNovaLinha(Sender: TObject);
begin
VprDFormaPagamento := VprDCaixa.AddFormaPagamento;
end;
{******************************************************************************}
procedure TFNovoCaixa.GradeSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
begin
if Grade.AEstadoGrade in [egInsercao,EgEdicao] then
if Grade.AColuna <> ACol then
begin
case Grade.AColuna of
1 :if not ExisteFormaPagamento then
begin
if not EFormaPagamento.AAbreLocalizacao then
begin
Grade.Cells[1,Grade.ALinha] := '';
abort;
end;
end;
end;
end;
end;
{******************************************************************************}
procedure TFNovoCaixa.GradeDepoisExclusao(Sender: TObject);
begin
AtualizaValTotal;
end;
procedure TFNovoCaixa.BCancelarClick(Sender: TObject);
begin
VprAcao := false;
close;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFNovoCaixa]);
end.
|
{ Project Explorer
This demo shows how to use many of the new APIs available in the Tools API.
What it demos:
How to get notified when certain events occur in Delphi.
Add a menu item to an arbitrary location in the Delphi main menu tree.
How to obtain and use interfaces for the form designer.
Accessing components on the form and get and set properties.
}
unit PrjExpl;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
IniFiles, ComCtrls, EditIntf, ExptIntf, ToolIntf, Menus, VirtIntf;
type
TProjectExplorer = class(TForm)
TreeView1: TTreeView;
StatusBar1: TStatusBar;
PopupMenu1: TPopupMenu;
EditItem: TMenuItem;
SelectItem: TMenuItem;
N1: TMenuItem;
RenameItem: TMenuItem;
DeleteItem: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TreeView1Expanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
procedure TreeView1KeyPress(Sender: TObject; var Key: Char);
procedure TreeView1Change(Sender: TObject; Node: TTreeNode);
procedure TreeView1Editing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
procedure TreeView1Edited(Sender: TObject; Node: TTreeNode;
var NewText: string);
procedure EditItemClick(Sender: TObject);
procedure PopupMenu1Popup(Sender: TObject);
procedure RenameItemClick(Sender: TObject);
procedure SelectItemClick(Sender: TObject);
procedure DeleteItemClick(Sender: TObject);
private
procedure SaveWindowState(Desktop: TIniFile);
procedure LoadWindowState(Desktop: TIniFile);
public
{ Public declarations }
end;
TFormBrowserExpert = class;
TModuleNotifier = class;
TModuleEntry = class
FileName: string;
UnitName: string;
FormName: string;
ModuleNode: TTreeNode;
FormNode: TTreeNode;
ModuleInterface: TIModuleInterface;
ModuleNotifier: TModuleNotifier;
FormHandle: Pointer;
constructor Create(const AFileName, AUnitName, AFormName: string);
destructor Destroy; override;
end;
TAddInNotifier = class(TIAddInNotifier)
private
FFormBrowser: TFormBrowserExpert;
public
constructor Create(AFormBrowser: TFormBrowserExpert);
procedure FileNotification(NotifyCode: TFileNotification;
const FileName: string; var Cancel: Boolean); override;
procedure EventNotification(NotifyCode: TEventNotification;
var Cancel: Boolean); override;
end;
TModuleNotifier = class(TIModuleNotifier)
private
FFormBrowser: TFormBrowserExpert;
FModuleEntry: TModuleEntry;
public
constructor Create(AFormBrowser: TFormBrowserExpert; ModuleEntry: TModuleEntry);
destructor Destroy; override;
procedure Notify(NotifyCode: TNotifyCode); override;
procedure ComponentRenamed(ComponentHandle: Pointer;
const OldName, NewName: string); override;
end;
TProjectNotifier = class(TIModuleNotifier)
private
FFormBrowser: TFormBrowserExpert;
public
constructor Create(AFormBrowser: TFormBrowserExpert);
procedure Notify(NotifyCode: TNotifyCode); override;
procedure ComponentRenamed(ComponentHandle: Pointer;
const OldName, NewName: string); override;
end;
TFormBrowserExpert = class(TIExpert)
private
ViewProjectExplorerItem: TIMenuItemIntf;
AddInNotifier: TAddInNotifier;
ProjectNotifier: TProjectNotifier;
ProjectModule: TIModuleInterface;
ModuleList: TStringList;
public
constructor Create;
destructor Destroy; override;
function EnumProc(const FileName, UnitName, FormName: string): Boolean;
procedure OpenProject(const FileName: string);
procedure CloseProject;
procedure AddedToProject(const FileName: string);
procedure RemovedFromProject(const FileName: string);
procedure LoadDesktop(const FileName: string);
procedure SaveDesktop(const FileName: string);
procedure ViewProjectExplorerClick(Sender: TIMenuItemIntf);
function GetName: string; override;
function GetStyle: TExpertStyle; override;
function GetIDString: string; override;
function GetAuthor: string; override;
function GetComment: string; override;
function GetPage: string; override;
function GetGlyph: HICON; override;
function GetState: TExpertState; override;
function GetMenuText: string; override;
procedure Execute; override;
end;
var
ProjectExplorer: TProjectExplorer = nil;
FormBrowserExpert: TFormBrowserExpert = nil;
function InitExpert(ToolServices: TIToolServices; RegisterProc: TExpertRegisterProc;
var Terminate: TExpertTerminateProc): Boolean; stdcall;
implementation
{$R *.DFM}
{$I PRJEXPL.INC}
function GetComponentName(Component: TIComponentInterface): string;
begin
Result := '';
Component.GetPropValueByName('Name', Result);
end;
procedure SetComponentName(Component: TIComponentInterface; const Value: string);
begin
Component.SetPropByName('Name', Value);
end;
procedure CreateForm(InstanceClass: TComponentClass; var Reference);
begin
if TComponent(Reference) = nil then
begin
TComponent(Reference) := TComponent(InstanceClass.NewInstance);
try
TComponent(Reference).Create(Application);
except
TComponent(Reference).Free;
TComponent(Reference) := nil;
raise
end;
end;
end;
{ TModuleEntry }
constructor TModuleEntry.Create(const AFileName, AUnitName, AFormName: string);
begin
FileName := AFileName;
UnitName := AUnitName;
FormName := AFormName;
end;
destructor TModuleEntry.Destroy;
begin
ModuleNotifier.Free;
ModuleInterface.Free;
inherited Destroy;
end;
{ TAddInNotifier }
constructor TAddInNotifier.Create(AFormBrowser: TFormBrowserExpert);
begin
inherited Create;
FFormBrowser := AFormBrowser;
end;
procedure TAddInNotifier.FileNotification(NotifyCode: TFileNotification;
const FileName: string; var Cancel: Boolean);
begin
if ProjectExplorer <> nil then
if NotifyCode = fnProjectOpened then
FFormBrowser.OpenProject(FileName)
else if NotifyCode = fnAddedToProject then
FFormBrowser.AddedToProject(FileName)
else if NotifyCode = fnRemovedFromProject then
FFormBrowser.RemovedFromProject(FileName);
if NotifyCode = fnProjectDesktopLoad then
FFormBrowser.LoadDesktop(FileName)
else if NotifyCode = fnProjectDesktopSave then
FFormBrowser.SaveDesktop(FileName);
end;
procedure TAddInNotifier.EventNotification(NotifyCode: TEventNotification;
var Cancel: Boolean);
begin
end;
function FindNode(TreeView: TCustomTreeView; Node: TTreeNode;
ComponentHandle: Pointer): TTreeNode;
function SearchNodes(Node: TTreeNode): TTreeNode;
var
ChildNode: TTreeNode;
begin
Result := nil;
if Node.Data = ComponentHandle then
Result := Node
else
begin
ChildNode := Node.GetFirstChild;
while ChildNode <> nil do
begin
Result := SearchNodes(ChildNode);
if Result <> nil then
Break
else ChildNode := Node.GetNextChild(ChildNode);
end;
end;
end;
begin
if Node = nil then Node := TTreeView(TreeView).Items.GetFirstNode;
Result := SearchNodes(Node);
end;
{ TModuleNotifier }
constructor TModuleNotifier.Create(AFormBrowser: TFormBrowserExpert; ModuleEntry: TModuleEntry);
begin
inherited Create;
FFormBrowser := AFormBrowser;
FModuleEntry := ModuleEntry;
FModuleEntry.ModuleInterface.AddNotifier(Self);
end;
destructor TModuleNotifier.Destroy;
begin
with FModuleEntry do
begin
ModuleInterface.RemoveNotifier(Self);
ModuleNotifier := nil;
ModuleInterface := nil;
FormHandle := nil;
end;
inherited Destroy;
end;
procedure TModuleNotifier.Notify(NotifyCode: TNotifyCode);
begin
if NotifyCode = ncModuleDeleted then
begin
with FModuleEntry do
if FormNode <> nil then
begin
FormNode.DeleteChildren;
FormNode.HasChildren := True;
end;
Free;
end;
end;
procedure TModuleNotifier.ComponentRenamed(ComponentHandle: Pointer;
const OldName, NewName: string);
var
Component, ParentComponent: TIComponentInterface;
Node, ParentNode: TTreeNode;
begin
try
with FModuleEntry do
if ComponentHandle = FormHandle then
Node := FormNode
else Node := FindNode(FormNode.TreeView, FormNode, ComponentHandle);
if (Node <> nil) and (NewName <> '') then
Node.Text := NewName
else if (Node <> nil) and (NewName = '') then
Node.Free
else if (Node = nil) and (NewName <> '') then
with FModuleEntry.ModuleInterface.GetFormInterface do
try
Component := GetComponentFromHandle(ComponentHandle);
if Component <> nil then
try
ParentNode := FModuleEntry.FormNode;
if Component.IsTControl then
begin
ParentComponent := GetCreateParent;
try
if ParentComponent.GetComponentHandle <> FModuleEntry.FormHandle then
ParentNode := FindNode(FModuleEntry.FormNode.TreeView,
FModuleEntry.FormNode, ParentComponent.GetComponentHandle);
finally
ParentComponent.Free;
end;
end;
if ParentNode <> nil then
ParentNode.Owner.AddChildObject(ParentNode, NewName,
ComponentHandle).MakeVisible;
finally
Component.Free;
end;
finally
Free;
end;
except
end;
end;
{ TProjectNotifier }
constructor TProjectNotifier.Create(AFormBrowser: TFormBrowserExpert);
begin
inherited Create;
FFormBrowser := AFormBrowser;
end;
procedure TProjectNotifier.Notify(NotifyCode: TNotifyCode);
begin
if NotifyCode = ncModuleDeleted then
begin
if ProjectExplorer <> nil then ProjectExplorer.Hide;
FFormBrowser.CloseProject;
end;
end;
procedure TProjectNotifier.ComponentRenamed(ComponentHandle: Pointer;
const OldName, NewName: string);
begin
// Nothing to do here but needs to be overridden anyway
end;
{ TFormBrowserExpert }
constructor TFormBrowserExpert.Create;
var
MainMenu: TIMainMenuIntf;
ProjManMenu: TIMenuItemIntf;
ViewMenu: TIMenuItemIntf;
MenuItems: TIMenuItemIntf;
begin
inherited Create;
ModuleList := TStringList.Create;
MainMenu := ToolServices.GetMainMenu;
if MainMenu <> nil then
try
MenuItems := MainMenu.GetMenuItems;
if MenuItems <> nil then
try
ProjManMenu := MainMenu.FindMenuItem('ViewPrjMgrItem');
if ProjManMenu <> nil then
try
ViewMenu := ProjManMenu.GetParent;
if ViewMenu <> nil then
try
ViewProjectExplorerItem := ViewMenu.InsertItem(ProjManMenu.GetIndex + 1,
sMenuItemCaption, 'ViewProjectExplorerItem', '', 0, 0, 0,
[mfVisible, mfEnabled], ViewProjectExplorerClick);
finally
ViewMenu.Free;
end;
finally
ProjManMenu.Free;
end;
finally
MenuItems.Free;
end;
finally
MainMenu.Free;
end;
AddInNotifier := TAddInNotifier.Create(Self);
ToolServices.AddNotifier(AddInNotifier);
end;
destructor TFormBrowserExpert.Destroy;
begin
ToolServices.RemoveNotifier(AddInNotifier);
CloseProject;
ViewProjectExplorerItem.Free;
AddInNotifier.Free;
ModuleList.Free;
inherited Destroy;
end;
function TFormBrowserExpert.EnumProc(const FileName, UnitName,
FormName: string): Boolean;
begin
ModuleList.AddObject(UnitName,
TModuleEntry.Create(FileName, UnitName, FormName));
Result := True;
end;
function ProjEnumProc(Param: Pointer; const FileName, UnitName,
FormName: string): Boolean; stdcall;
begin
try
Result := TFormBrowserExpert(Param).EnumProc(FileName, UnitName, FormName);
except
Result := False;
end;
end;
procedure TFormBrowserExpert.OpenProject(const FileName: string);
var
I: Integer;
Node: TTreeNode;
begin
CloseProject;
ToolServices.EnumProjectUnits(ProjEnumProc, Self);
ProjectModule := ToolServices.GetModuleInterface(FileName);
if ProjectModule <> nil then
begin
ProjectNotifier := TProjectNotifier.Create(Self);
ProjectModule.AddNotifier(ProjectNotifier);
if (ProjectExplorer <> nil) and (ModuleList.Count > 0) then
with ProjectExplorer, ToolServices do
begin
with TModuleEntry(ModuleList.Objects[0]) do
begin
Node := TreeView1.Items.Add(nil, UnitName);
ModuleNode := Node;
end;
for I := 1 to ModuleList.Count - 1 do
with TModuleEntry(ModuleList.Objects[I]) do
if UnitName <> '' then
begin
ModuleNode := TreeView1.Items.AddChildObject(Node, UnitName,
ModuleList.Objects[I]);
if FormName <> '' then
begin
FormNode := TreeView1.Items.AddChildObject(ModuleNode, FormName,
ModuleList.Objects[I]);
FormNode.HasChildren := True;
end;
end;
Node.Expanded := True;
end;
end;
end;
procedure TFormBrowserExpert.CloseProject;
var
I: Integer;
begin
if ProjectModule <> nil then
begin
if ProjectExplorer <> nil then
ProjectExplorer.TreeView1.Items.Clear;
for I := 0 to ModuleList.Count - 1 do
TModuleEntry(ModuleList.Objects[I]).Free;
ModuleList.Clear;
ProjectModule.RemoveNotifier(ProjectNotifier);
ProjectNotifier.Free;
ProjectModule.Free;
ProjectNotifier := nil;
ProjectModule := nil;
end;
end;
function FindNewProjectItem(Param: Pointer; const ModFileName, ModUnitName,
ModFormName: string): Boolean; stdcall;
begin
try
with TModuleEntry(Param) do
if AnsiCompareText(FileName, ModFileName) = 0 then
begin
Result := False;
UnitName := ModUnitName;
FormName := ModFormName;
end else Result := True;
except
Result := False;
end;
end;
procedure TFormBrowserExpert.AddedToProject(const FileName: string);
var
NewModuleEntry: TModuleEntry;
begin
if ModuleList.Count > 0 then
begin
NewModuleEntry := TModuleEntry.Create(FileName, '', '');
ToolServices.EnumProjectUnits(FindNewProjectItem, NewModuleEntry);
ModuleList.AddObject(FileName, NewModuleEntry);
if ProjectExplorer <> nil then
with ProjectExplorer, NewModuleEntry do
begin
ModuleNode :=
TreeView1.Items.AddChildObject(TModuleEntry(ModuleList.Objects[0]).ModuleNode,
NewModuleEntry.UnitName, NewModuleEntry);
if FormName <> '' then
begin
FormNode := TreeView1.Items.AddChildObject(NewModuleEntry.ModuleNode,
FormName, NewModuleEntry);
FormNode.HasChildren := True;
end;
end;
end;
end;
procedure TFormBrowserExpert.RemovedFromProject(const FileName: string);
var
I: Integer;
ModuleEntry: TModuleEntry;
begin
for I := 0 to ModuleList.Count - 1 do
begin
ModuleEntry := TModuleEntry(ModuleList.Objects[I]);
if AnsiCompareText(ModuleEntry.FileName, FileName) = 0 then
begin
ModuleList.Delete(I);
ModuleEntry.ModuleNode.Free;
ModuleEntry.Free;
Break;
end;
end;
end;
const
isProjectFormViewer = 'ProjectExplorer';
ivCreate = 'Create';
ivVisible = 'Visible';
ivState = 'State';
ivTop = 'Top';
ivLeft = 'Left';
ivWidth = 'Width';
ivHeight = 'Height';
ivMaxLeft = 'MaxLeft';
ivMaxTop = 'MaxTop';
ivMaxWidth = 'MaxWidth';
ivMaxHeight = 'MaxHeight';
procedure TFormBrowserExpert.LoadDesktop(const FileName: string);
var
Desktop: TIniFile;
begin
Desktop := TIniFile.Create(FileName);
try
if DeskTop.ReadBool(isProjectFormViewer, ivCreate, False) then
begin
CreateForm(TProjectExplorer, ProjectExplorer);
ProjectExplorer.LoadWindowState(Desktop);
end else if ProjectExplorer <> nil then ProjectExplorer.Hide;
finally
Desktop.Free;
end;
end;
procedure TFormBrowserExpert.SaveDesktop(const FileName: string);
var
Desktop: TIniFile;
begin
Desktop := TIniFile.Create(FileName);
try
if ProjectExplorer <> nil then ProjectExplorer.SaveWindowState(Desktop);
finally
Desktop.Free;
end;
end;
procedure TFormBrowserExpert.ViewProjectExplorerClick(Sender: TIMenuItemIntf);
begin
CreateForm(TProjectExplorer, ProjectExplorer);
ProjectExplorer.Show;
end;
function TFormBrowserExpert.GetName: string;
begin
Result := sExpertName;
end;
function TFormBrowserExpert.GetStyle: TExpertStyle;
begin
Result := esAddIn;
end;
function TFormBrowserExpert.GetIDString: string;
begin
Result := 'Borland.ProjectExplorer';
end;
function TFormBrowserExpert.GetAuthor: string;
begin
end;
function TFormBrowserExpert.GetComment: string;
begin
end;
function TFormBrowserExpert.GetPage: string;
begin
end;
function TFormBrowserExpert.GetGlyph: HICON;
begin
Result := 0;
end;
function TFormBrowserExpert.GetState: TExpertState;
begin
Result := [];
end;
function TFormBrowserExpert.GetMenuText: string;
begin
end;
procedure TFormBrowserExpert.Execute;
begin
end;
{ TProjectExplorer }
procedure TProjectExplorer.FormCreate(Sender: TObject);
var
ProjectName: string;
begin
ProjectName := ToolServices.GetProjectName;
if ProjectName <> '' then
FormBrowserExpert.OpenProject(ProjectName);
end;
procedure TProjectExplorer.FormDestroy(Sender: TObject);
begin
ProjectExplorer := nil;
end;
function OpenModule(ModuleEntry: TModuleEntry; Ask: Boolean): Boolean;
begin
with ModuleEntry do
begin
Result := False;
if ModuleInterface = nil then
begin
if not ToolServices.IsFileOpen(FileName) then
if not Ask or (MessageDlg(Format(sFileNotLoaded, [FileName]),
mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
begin
if not ToolServices.OpenFile(FileName) then Exit;
end else Exit;
ModuleInterface := ToolServices.GetModuleInterface(FileName);
ModuleNotifier := TModuleNotifier.Create(FormBrowserExpert, ModuleEntry);
Result := True;
end else Result := True;
end;
end;
procedure AddChildControl(Node: TTreeNode; IsRoot: Boolean; Component: TIComponentInterface); forward;
function GetChildProc(Param: Pointer; Component: TIComponentInterface): Boolean; stdcall;
begin
try
try
AddChildControl(TTreeNode(Param), False, Component);
finally
Component.Free; // Release the component interface.
end;
Result := True;
except
Result := False;
end;
end;
procedure AddChildControl(Node: TTreeNode; IsRoot: Boolean; Component: TIComponentInterface);
var
ChildNode: TTreeNode;
begin
if IsRoot then
ChildNode := Node
else ChildNode := ProjectExplorer.TreeView1.Items.AddChildObject(Node,
GetComponentName(Component), Component.GetComponentHandle);
Component.GetChildren(ChildNode, GetChildProc);
end;
procedure TProjectExplorer.TreeView1Expanding(Sender: TObject;
Node: TTreeNode; var AllowExpansion: Boolean);
var
ModuleEntry: TModuleEntry;
Component: TIComponentInterface;
begin
if Node.Level = 2 then
begin
ModuleEntry := TModuleEntry(Node.Data);
with ModuleEntry do
begin
if ModuleInterface = nil then
if OpenModule(ModuleEntry, True) then
begin
TreeView1.Items.BeginUpdate;
try
with ModuleInterface.GetFormInterface do
try
Component := GetFormComponent;
try
FormHandle := Component.GetComponentHandle;
AddChildControl(Node, True, Component);
finally
Component.Free;
end;
finally
Free;
end;
finally
TreeView1.Items.EndUpdate;
end;
if Node.GetFirstChild = nil then
Node.HasChildren := False;
end;
end;
end;
end;
procedure TProjectExplorer.TreeView1KeyPress(Sender: TObject; var Key: Char);
begin
with TreeView1 do
if not IsEditing and (Selected <> nil) and (Selected.Level < 3) and
(Key = '*') then Key := #0;
end;
function GetModuleEntry(Node: TTreeNode): TModuleEntry;
begin
while Node.Level > 2 do
Node := Node.Parent;
Result := TModuleEntry(Node.Data);
end;
function GetNodeComponent(Node: TTreeNode): TIComponentInterface;
var
ModuleEntry: TModuleEntry;
FormInterface: TIFormInterface;
Handle: Pointer;
begin
Result := nil;
if (Node <> nil) and (Node.Level >= 2) then
begin
ModuleEntry := GetModuleEntry(Node);
if ModuleEntry.ModuleInterface <> nil then
begin
FormInterface := ModuleEntry.ModuleInterface.GetFormInterface;
try
if Node.Level = 2 then
Handle := ModuleEntry.FormHandle
else Handle := Node.Data;
Result := FormInterface.GetComponentFromHandle(Handle);
finally
FormInterface.Free;
end;
end;
end;
end;
procedure TProjectExplorer.TreeView1Change(Sender: TObject; Node: TTreeNode);
var
ModuleEntry: TModuleEntry;
Component: TIComponentInterface;
begin
if Node = nil then Exit;
if Node.Level > 2 then
begin
Component := GetNodeComponent(Node);
if Component <> nil then
try
StatusBar1.SimpleText := Component.GetComponentType;
finally
Component.Free;
end else StatusBar1.SimpleText := '';
end else if (Node.Level = 1) or (Node.Level = 2) then
begin
ModuleEntry := TModuleEntry(Node.Data);
if Node.Level = 1 then
StatusBar1.SimpleText := ModuleEntry.FileName
else StatusBar1.SimpleText := ChangeFileExt(ModuleEntry.FileName, '.dfm');
end else if Node.Level = 0 then
if FormBrowserExpert.ProjectModule <> nil then
with FormBrowserExpert.ProjectModule.GetEditorInterface do
try
StatusBar1.SimpleText := FileName;
finally
Free;
end;
end;
procedure TProjectExplorer.TreeView1Editing(Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean);
var
Component: TIComponentInterface;
begin
if Node <> nil then
begin
Component := GetNodeComponent(Node);
try
if (Node.Level < 2) or (Component = nil) then
AllowEdit := False;
finally
Component.Free;
end;
end;
end;
procedure TProjectExplorer.TreeView1Edited(Sender: TObject; Node: TTreeNode;
var Newtext: string);
var
Component: TIComponentInterface;
begin
if Node.Level >= 2 then
begin
Component := GetNodeComponent(Node);
try
SetComponentName(Component, NewText);
finally
Component.Free;
end;
NewText := Node.Text;
end;
end;
procedure TProjectExplorer.PopupMenu1Popup(Sender: TObject);
var
Node: TTreeNode;
NodeComponent: TIComponentInterface;
begin
Node := TreeView1.Selected;
EditItem.Enabled := Node <> nil;
NodeComponent := GetNodeComponent(Node);
try
SelectItem.Enabled := (Node <> nil) and (Node.Level > 1) and
(NodeComponent <> nil);
RenameItem.Enabled := (Node <> nil) and (Node.Level > 1) and
(NodeComponent <> nil);
DeleteItem.Enabled := (Node <> nil) and (Node.Level > 2) and
(NodeComponent <> nil);
finally
NodeComponent.Free;
end;
end;
procedure TProjectExplorer.EditItemClick(Sender: TObject);
var
Node: TTreeNode;
ModuleEntry: TModuleEntry;
Component: TIComponentInterface;
begin
Node := TreeView1.Selected;
if Node <> nil then
if Node.Level >= 2 then
begin
ModuleEntry := GetModuleEntry(Node);
Component := GetNodeComponent(Node);
try
if (Node.Level = 2) and (Component = nil) then
begin
if OpenModule(ModuleEntry, False) then
ModuleEntry.ModuleInterface.ShowForm;
end else if Component <> nil then
begin
Component.Select;
Component.Focus;
end;
finally
Component.Free;
end;
end else if Node.Level = 1 then
begin
ModuleEntry := TModuleEntry(Node.Data);
if OpenModule(ModuleEntry, False) then
ModuleEntry.ModuleInterface.ShowSource;
end else if Node.Level = 0 then
if FormBrowserExpert.ProjectModule <> nil then
FormBrowserExpert.ProjectModule.ShowSource;
end;
procedure TProjectExplorer.SelectItemClick(Sender: TObject);
var
Node: TTreeNode;
Component: TIComponentInterface;
begin
Node := TreeView1.Selected;
if Node <> nil then
if Node.Level >= 2 then
begin
Component := GetNodeComponent(Node);
try
Component.Select;
finally
Component.Free;
end;
end;
end;
procedure TProjectExplorer.RenameItemClick(Sender: TObject);
var
Node: TTreeNode;
begin
Node := TreeView1.Selected;
if Node <> nil then Node.EditText;
end;
procedure TProjectExplorer.DeleteItemClick(Sender: TObject);
var
Node: TTreeNode;
Component: TIComponentInterface;
begin
Node := TreeView1.Selected;
if Node <> nil then
if Node.Level > 2 then
begin
Component := GetNodeComponent(Node);
try
Component.Delete;
finally
Component.Free;
end;
end;
end;
procedure TProjectExplorer.SaveWindowState(Desktop: TIniFile);
var
WindowPlacement: TWindowPlacement;
begin
if Visible then with Desktop do
begin
WriteBool(isProjectFormViewer, ivCreate, True);
WriteBool(isProjectFormViewer, ivVisible, Visible);
WriteInteger(isProjectFormViewer, ivState, Ord(WindowState));
if WindowState in [wsMinimized, wsMaximized] then { 3.1 only }
begin
WindowPlacement.length := SizeOf(WindowPlacement);
GetWindowPlacement(Handle, @WindowPlacement);
with WindowPlacement.rcNormalPosition do
begin
WriteInteger(isProjectFormViewer, ivLeft, left);
WriteInteger(isProjectFormViewer, ivTop, top);
WriteInteger(isProjectFormViewer, ivWidth, right - left);
WriteInteger(isProjectFormViewer, ivHeight, bottom - top);
WriteInteger(isProjectFormViewer, ivMaxLeft, WindowPlacement.ptMaxPosition.x);
WriteInteger(isProjectFormViewer, ivMaxTop, WindowPlacement.ptMaxPosition.y);
if WindowState = wsMaximized then
begin
WriteInteger(isProjectFormViewer, ivMaxWidth, Width);
WriteInteger(isProjectFormViewer, ivMaxHeight, Height);
end;
end;
end
else
begin
WriteInteger(isProjectFormViewer, ivLeft, Left);
WriteInteger(isProjectFormViewer, ivTop, Top);
WriteInteger(isProjectFormViewer, ivWidth, Width);
WriteInteger(isProjectFormViewer, ivHeight, Height);
end;
end;
end;
procedure TProjectExplorer.LoadWindowState(Desktop: TIniFile);
var
X, Y, W, H: Integer;
Visible: Boolean;
WindowState: TWindowState;
WindowPlacement: TWindowPlacement;
begin
if Desktop.ReadBool(isProjectFormViewer, ivCreate, False) then with Desktop do
begin
Position := poDesigned;
Visible := ReadBool(isProjectFormViewer, ivVisible, False);
WindowState := TWindowState(ReadInteger(isProjectFormViewer, ivState, Ord(wsNormal)));
X := ReadInteger(isProjectFormViewer, ivLeft, Left);
Y := ReadInteger(isProjectFormViewer, ivTop, Top);
W := ReadInteger(isProjectFormViewer, ivWidth, Width);
H := ReadInteger(isProjectFormViewer, ivHeight, Height);
with WindowPlacement do
begin
length := SizeOf(WindowPlacement);
rcNormalPosition.left := X;
rcNormalPosition.top := Y;
rcNormalPosition.right := X + W;
rcNormalPosition.bottom := Y + H;
ptMaxPosition.x := ReadInteger(isProjectFormViewer, ivMaxLeft, -GetSystemMetrics(SM_CXFRAME));
ptMaxPosition.y := ReadInteger(isProjectFormViewer, ivMaxTop, -GetSystemMetrics(SM_CYFRAME));
case WindowState of
wsMinimized: showCmd := SW_SHOWMINIMIZED;
wsMaximized: showCmd := SW_SHOWMAXIMIZED;
wsNormal: showCmd := SW_NORMAL;
end;
flags := 0;
end;
SetWindowPlacement(Handle, @WindowPlacement);
if WindowState = wsMaximized then
begin
W := ReadInteger(isProjectFormViewer, ivMaxWidth, Width);
H := ReadInteger(isProjectFormViewer, ivMaxHeight, Height);
SetBounds(Left, Top, W, H);
end;
Self.Visible := Visible;
end;
end;
function InitExpert(ToolServices: TIToolServices; RegisterProc: TExpertRegisterProc;
var Terminate: TExpertTerminateProc): Boolean;
begin
Result := True;
try
ExptIntf.ToolServices := ToolServices;
Application.Handle := ToolServices.GetParentHandle;
FormBrowserExpert := TFormBrowserExpert.Create;
RegisterProc(FormBrowserExpert);
except
ToolServices.RaiseException(ReleaseException);
end;
end;
end.
|
unit FirmsFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, Db, DBTables, DBGrids, ExtCtrls, DBCtrls, BtrDS, Menus, Deals,
StdCtrls, Buttons, ComCtrls, SearchFrm, FirmFrm;
type
TFirmsForm = class(TDataBaseForm)
DataSource: TDataSource;
DBGrid: TDBGrid;
StatusBar: TStatusBar;
BtnPanel: TPanel;
OkBtn: TBitBtn;
CancelBtn: TBitBtn;
NameEdit: TEdit;
SearchIndexComboBox: TComboBox;
MainMenu: TMainMenu;
OperItem: TMenuItem;
FindItem: TMenuItem;
InsItem: TMenuItem;
DelItem: TMenuItem;
EditBreaker: TMenuItem;
NameLabel: TLabel;
EditItem: TMenuItem;
CopyItem: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure NameEditChange(Sender: TObject);
procedure SearchIndexComboBoxChange(Sender: TObject);
procedure BtnPanelResize(Sender: TObject);
procedure FindItemClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure InsItemClick(Sender: TObject);
procedure EditItemClick(Sender: TObject);
procedure DelItemClick(Sender: TObject);
procedure CopyItemClick(Sender: TObject);
procedure DBGridDblClick(Sender: TObject);
private
procedure UpdateFirm(CopyCurrent, New: Boolean);
public
SearchForm: TSearchForm;
procedure TakePrintData(var PrintForm: TFileName;
var ADBGrid: TDBGrid); override;
end;
TFirmDataSet = class(TBtrDataSet)
protected
procedure InternalInitFieldDefs; override;
public
property ActiveRecord;
function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override;
constructor Create(AOwner: TComponent);
end;
var
ObjList: TList;
implementation
{$R *.DFM}
constructor TFirmDataSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBufSize := SizeOf(TFirmRec);
end;
procedure TFirmDataSet.InternalInitFieldDefs;
begin
FieldDefs.Clear;
TFieldDef.Create(FieldDefs,'clAccC',ftString,20,False,0);
TFieldDef.Create(FieldDefs,'clInn',ftString,16,False,1);
TFieldDef.Create(FieldDefs,'clKpp',ftString,16,False,2);
TFieldDef.Create(FieldDefs,'clNameC',ftString,44,False,3);
end;
function TFirmDataSet.GetFieldData(Field: TField; Buffer: Pointer): Boolean;
var
I: integer;
begin
Result := true;
case Field.Index of
0: StrLCopy(Buffer, @(PFirmRec(ActiveBuffer)^.clAccC), SizeOf(TAccount));
1: StrLCopy(Buffer, PFirmRec(ActiveBuffer)^.clInn, SizeOf(TInn));
2: StrLCopy(Buffer, PFirmRec(ActiveBuffer)^.clKpp, SizeOf(TInn));
3: begin
I:=0;
while (I<clMaxVar) and (PFirmRec(ActiveBuffer)^.clNameC[I]<>#13)
and (PFirmRec(ActiveBuffer)^.clNameC[I]<>#0) do begin
Inc(I);
end;
StrLCopy(Buffer, @(PFirmRec(ActiveBuffer)^.clNameC),I);
DosToWin(Buffer);
end;
end;
end;
{procedure TFirmForm.AfterScrollDS(DataSet: TDataSet);
begin
NameEdit.Text:=DataSet.Fields.Fields[5].AsString;
end;}
procedure TFirmsForm.FormCreate(Sender: TObject);
begin
ObjList.Add(Self);
DataSource.DataSet := TFirmDataSet.Create(Self);
with DataSource.DataSet as TFirmDataSet do begin
FKeyNum := 2;
FBufSize := SizeOf(TFirmRec)+64;
SetTableName(BaseDir+'Firm.btr');
Active := true;
{ AfterScroll:=AfterScrollDS;}
end;
DefineGridCaptions(DBGrid, PatternDir+'Firms.tab');
SearchForm:=TSearchForm.Create(Self);
SearchIndexComboBox.ItemIndex:=2;
end;
procedure TFirmsForm.FormDestroy(Sender: TObject);
begin
ObjList.Remove(Self);
end;
procedure TFirmsForm.TakePrintData(var PrintForm: TFileName;
var ADBGrid: TDBGrid);
begin
ADBGrid:=DBGrid;
PrintForm:='Firm.pfm';
end;
procedure TFirmsForm.NameEditChange(Sender: TObject);
var
T: array[0..512] of Char;
I,Err: LongInt;
SearchData: packed record Bik: LongInt; Acc: TAccount end;
S: string;
begin
case SearchIndexComboBox.ItemIndex of
0:
begin
S:=NameEdit.Text;
I:=Pos('/',S);
if I>0 then begin
StrPCopy(SearchData.Acc,Copy(S,I+1,Length(S)-I));
S:=Copy(S,1,I-1);
end else StrCopy(SearchData.Acc,'');
while Length(S)<8 do S:=S+'0';
Val(S,SearchData.Bik,Err);
TBtrDataSet(DataSource.DataSet).LocateBtrRecordByIndex(SearchData,0,bsGe);
end;
else begin
StrPCopy(T,NameEdit.Text);
WinToDos(T);
(DataSource.DataSet as TBtrDataSet).LocateBtrRecordByIndex(
T, SearchIndexComboBox.ItemIndex, bsGe);
end;
end;
end;
procedure TFirmsForm.SearchIndexComboBoxChange(Sender: TObject);
begin
(DataSource.DataSet as TBtrDataSet).KeyNum:=SearchIndexComboBox.ItemIndex
end;
const
BtnDist=6;
procedure TFirmsForm.BtnPanelResize(Sender: TObject);
begin
CancelBtn.Left:=BtnPanel.ClientWidth-CancelBtn.Width-2*BtnDist;
OkBtn.Left:=CancelBtn.Left-OkBtn.Width-BtnDist;
end;
procedure TFirmsForm.FindItemClick(Sender: TObject);
begin
SearchForm.ShowModal;
end;
procedure TFirmsForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if FormStyle=fsMDIChild then Action:=caFree;
end;
procedure TFirmsForm.UpdateFirm(CopyCurrent, New: Boolean);
var
FirmForm: TFirmForm;
FirmRec: TFirmRec;
Err: Integer;
T: array[0..512] of Char;
begin
FirmForm := TFirmForm.Create(Self);
with FirmForm do begin
FillChar(FirmRec,SizeOf(FirmRec),#0);
if CopyCurrent then
TFirmDataSet(DataSource.DataSet).GetBtrRecord(PChar(@FirmRec));
with FirmRec do begin
DosToWin(clNameC);
StrLCopy(T,clAccC,SizeOf(clAccC));
RsEdit.Text := StrPas(T);
StrLCopy(T,clInn,SizeOf(clInn));
InnEdit.Text := StrPas(T);
StrLCopy(T,clKpp,SizeOf(clKpp));
KppEdit.Text := StrPas(T);
NameMemo.Text := StrPas(clNameC);
end;
if ShowModal = mrOk then begin
with FirmRec do begin
StrPCopy(clAccC,RsEdit.Text);
StrPCopy(clInn,InnEdit.Text);
StrPCopy(clKpp,KppEdit.Text);
StrPCopy(clNameC,NameMemo.Text);
WinToDos(clNameC);
end;
if New then begin
if TFirmDataSet(DataSource.DataSet).AddBtrRecord(PChar(@FirmRec),
SizeOf(FirmRec))
then
DataSource.DataSet.Refresh
else
MessageBox(Handle, 'Невозможно добавить запись', 'Редактирование',
MB_OK + MB_ICONERROR);
end else begin
if TFirmDataSet(DataSource.DataSet).UpdateBtrRecord(PChar(@FirmRec),
SizeOf(FirmRec))
then
DataSource.DataSet.UpdateCursorPos
else
MessageBox(Handle, 'Невозможно изменить запись', 'Редактирование',
MB_OK + MB_ICONERROR);
end;
end;
Free;
end;
end;
procedure TFirmsForm.InsItemClick(Sender: TObject);
begin
UpdateFirm(False,True);
end;
procedure TFirmsForm.EditItemClick(Sender: TObject);
begin
UpdateFirm(True,False);
end;
procedure TFirmsForm.CopyItemClick(Sender: TObject);
begin
UpdateFirm(True,True)
end;
procedure TFirmsForm.DelItemClick(Sender: TObject);
begin
if MessageBox(Handle, 'Фирма будет удалена из списка. Вы уверены?',
'Удаление', MB_YESNOCANCEL + MB_ICONQUESTION) = IDYES
then
DataSource.DataSet.Delete;
end;
procedure TFirmsForm.DBGridDblClick(Sender: TObject);
begin
if FormStyle=fsMDIChild then EditItemClick(Sender)
else ModalResult := mrOk;
end;
end.
|
unit TestConstants;
{ constants used in tests }
{ the directories where the test files are found}
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestConstants, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
{ get the directory for the test files, relative to the exe dir, not hardcoded }
function GetBaseDir: string;
function GetExeFilesDir: string;
function GetTestFilesDir: string;
function GetObsOutFilesDir: string;
function GetRefOutFilesDir: string;
function GetTestSettingsFileName: string;
procedure InitTestSettings;
implementation
uses
{ delphi }
SysUtils,
Windows,
{ local }
JcfStringUtils,
JcfRegistrySettings, JcfSettings, ConvertTypes;
var
msEXEFilesDir: string = '';
msBaseDir: string = '';
procedure GenerateDirs;
const
OUTPUT_DIR: string = '\Output\';
OUTPUT_DIR_LEN: integer = 8;
var
outputIndex: integer;
begin
// calculate this once, read the app path
msEXEFilesDir := ExtractFilePath(ParamStr(0));
msBaseDir := msEXEFilesDir;
{ expect this to be, in my e.g. "C:\Code\JcfCheckout\CodeFormat\Jcf2\Output\"
The base dir strips off the /output
}
outputIndex := Pos(OUTPUT_DIR, msBaseDir);
if outputIndex > 0 then
begin
msBaseDir := StrLeft(msBaseDir, outputIndex);
end;
end;
function GetBaseDir: string;
begin
if msBaseDir = '' then
GenerateDirs;
Result := msBaseDir;
end;
function GetExeFilesDir: string;
begin
if msEXEFilesDir = '' then
GenerateDirs;
Result := msEXEFilesDir;
end;
function GetTestFilesDir: string;
begin
Result := GetBaseDir + 'Test\TestCases\';
end;
function GetObsOutFilesDir: string;
begin
Result := GetTestFilesDir + 'ObfuscatedOut\';
end;
function GetRefOutFilesDir: string;
begin
Result := GetTestFilesDir + 'Out\';
end;
function GetTestSettingsFileName: string;
begin
Result := GetTestFilesDir + 'JCFTestSettings.cfg';
end;
procedure InitTestSettings;
var
lsSettingsFileName: string;
begin
if not GetRegSettings.HasRead then
GetRegSettings.ReadAll;
{ use clarify test settings }
lsSettingsFileName := GetTestSettingsFileName;
if not (FileExists(lsSettingsFileName)) then
raise Exception.Create('Settings file ' + lsSettingsFileName + ' not found');
GetRegSettings.FormatConfigFileName := lsSettingsFileName;
JcfFormatSettings; // create and read
JcfFormatSettings.Obfuscate.Enabled := False;
{ some registry settings can be painfull in automated tests }
GetRegSettings.LogTime := False;
GetRegSettings.ViewLogAfterRun := False;
GetRegSettings.ShowParseTreeOption := eShowNever;
end;
end.
|
program Hanoi;
procedure hanoi(n: integer; from: string; _to: string; via: string);
begin
if n > 1 then
begin
hanoi(n - 1, from, via, _to);
writeln(from + ' -> ' + _to);
hanoi(n - 1, via, _to, from)
end
else
writeln(from + ' -> ' + _to)
end;
var n: integer;
begin
readln(n);
hanoi(n, 'a', 'b', 'c')
end.
|
unit myStack;
interface
type pPointer = ^tComponent;
tInfo = integer;
tComponent = record
info: tInfo;
next: pPointer;
end;
tStack = record
pTop: pPointer;
end;
procedure CreateStack(var stack: tStack; element: tInfo);
procedure Push(var stack: tStack; element: tInfo);
procedure Pop(var stack: tStack; var element: tInfo);
implementation
procedure CreateStack();
begin
new(stack.pTop);
stack.pTop^.next:= nil;
stack.pTop^.info:= element;
end;
procedure Push();
var pElement: pPointer;
begin
new(pElement);
pElement^.next:= stack.pTop;
stack.pTop:= pElement;
stack.pTop^.info:= element;
end;
procedure Pop();
var pElement: pPointer;
begin
pElement:= stack.pTop;
element:= stack.pTop^.info;
stack.pTop:= stack.pTop^.next;
dispose(pElement);
end;
end. |
unit WorldMap;
interface
uses System.Classes, Graphics, TiledMap, Mobs;
type
TWorldMap = class(TObject)
public type
TDir = (drMapLeft, drMapUp, drMapRight, drMapDown, drMapTop, drMapBottom);
public type
TMapInfo = record
FileName: string;
Neighbors: array [TDir] of string;
end;
private
FMapInfo: array of TMapInfo;
FTiledMap: array of TTiledMap;
FTiledMapMobs: array of TMobs;
FCurrentMap: Integer;
FSections: TStringList;
FOwner: TComponent;
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
procedure LoadFromFile(const FileName: string);
function Count: Integer;
property CurrentMap: Integer read FCurrentMap;
function GetMapIndex(SectionName: string): Integer;
function GetMap(I: Integer): TTiledMap;
function GetCurrentMapInfo: TMapInfo;
function GetCurrentMap: TTiledMap;
function GetMapMobs(I: Integer): TMobs;
function GetCurrentMapMobs: TMobs;
function Go(Dir: TDir): Boolean;
procedure Render(Canvas: TCanvas);
end;
var
Map: TWorldMap;
implementation
uses System.SysUtils, Dialogs, System.IniFiles, Utils, Mods;
{ TWorldMap }
function TWorldMap.Count: Integer;
begin
Result := FSections.Count;
end;
constructor TWorldMap.Create(AOwner: TComponent);
begin
FOwner := AOwner;
FSections := TStringList.Create;
FCurrentMap := 0;
end;
destructor TWorldMap.Destroy;
var
I: Integer;
begin
for I := 0 to Count - 1 do
begin
FreeAndNil(FTiledMap[I]);
FreeAndNil(FTiledMapMobs[I]);
end;
FreeAndNil(FSections);
inherited;
end;
function TWorldMap.GetCurrentMap: TTiledMap;
begin
Result := FTiledMap[FCurrentMap];
end;
function TWorldMap.GetCurrentMapInfo: TMapInfo;
begin
Result := FMapInfo[FCurrentMap];
end;
function TWorldMap.GetCurrentMapMobs: TMobs;
begin
Result := FTiledMapMobs[FCurrentMap];
end;
function TWorldMap.GetMap(I: Integer): TTiledMap;
begin
Result := FTiledMap[I];
end;
function TWorldMap.GetMapIndex(SectionName: string): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if (Trim(SectionName) = FSections[I]) then
begin
Result := I;
Break;
end;
end;
function TWorldMap.GetMapMobs(I: Integer): TMobs;
begin
Result := FTiledMapMobs[I];
end;
function TWorldMap.Go(Dir: TDir): Boolean;
var
NextMapFileName: string;
I, J: Integer;
P: TMobInfo;
begin
Result := False;
NextMapFileName := GetCurrentMapInfo.Neighbors[Dir];
if NextMapFileName <> '' then
begin
I := GetMapIndex(NextMapFileName);
if (I < 0) then
Exit;
with GetCurrentMapMobs do
begin
P := Get(Player.Idx);
Del(Player.Idx);
Player.Idx := -1;
GetMapMobs(I).Add(P);
for J := 0 to GetMapMobs(I).Count - 1 do
begin
P := GetMapMobs(I).Get(J);
if P.Force = 1 then
begin
GetMapMobs(I).Player.Idx := J;
Break;
end;
end;
end;
FCurrentMap := I;
Result := True;
end;
end;
procedure TWorldMap.LoadFromFile(const FileName: string);
var
I: Integer;
F: TIniFile;
begin
FCurrentMap := 0;
F := TIniFile.Create(GMods.GetPath('maps', FileName));
try
FSections.Clear;
F.ReadSections(FSections);
SetLength(FMapInfo, Count);
SetLength(FTiledMap, Count);
SetLength(FTiledMapMobs, Count);
for I := 0 to Count - 1 do
begin
FMapInfo[I].FileName := Trim(FSections[I]);
FMapInfo[I].Neighbors[drMapLeft] := F.ReadString(FSections[I], 'MapLeft', '');
FMapInfo[I].Neighbors[drMapUp] := F.ReadString(FSections[I], 'MapUp', '');
FMapInfo[I].Neighbors[drMapRight] := F.ReadString(FSections[I], 'MapRight', '');
FMapInfo[I].Neighbors[drMapDown] := F.ReadString(FSections[I], 'MapDown', '');
FMapInfo[I].Neighbors[drMapTop] := F.ReadString(FSections[I], 'MapTop', '');
FMapInfo[I].Neighbors[drMapBottom] := F.ReadString(FSections[I], 'MapBottom', '');
FTiledMap[I] := TTiledMap.Create(FOwner);
FTiledMap[I].LoadFromFile(Format('%s.tmx', [FMapInfo[I].FileName]));
FTiledMapMobs[I] := TMobs.Create;
FTiledMapMobs[I].LoadFromMap(I);
end;
finally
FreeAndNil(F);
end;
end;
procedure TWorldMap.Render(Canvas: TCanvas);
var
Y: Integer;
X: Integer;
L: TTiledMap.TLayerEnum;
begin
for Y := 0 to Map.GetCurrentMap.Height - 1 do
for X := 0 to Map.GetCurrentMap.Width - 1 do
begin
for L := Low(TTiledMap.TLayerEnum) to TTiledMap.TLayerEnum.lrItems do
if (Map.GetCurrentMap.FMap[L][X][Y] >= 0) then
Canvas.Draw(X * Map.GetCurrentMap.TileSize, Y * Map.GetCurrentMap.TileSize,
Map.GetCurrentMap.TiledObject[Map.GetCurrentMap.FMap[L][X][Y]].Image);
end;
end;
end.
|
unit Support.Crucial;
interface
uses
SysUtils, Math,
Support, Device.SMART.List;
type
TCrucialNSTSupport = class sealed(TNSTSupport)
private
InterpretingSMARTValueList: TSMARTValueList;
function GetFullSupport: TSupportStatus;
function GetTotalWrite: TTotalWrite;
function IsM500: Boolean;
function IsM550: Boolean;
function IsModelHasCrucialString: Boolean;
function IsMX100: Boolean;
function IsMX200: Boolean;
function IsMX300: Boolean;
function IsProductOfCrucial: Boolean;
public
function GetSupportStatus: TSupportStatus; override;
function GetSMARTInterpreted(SMARTValueList: TSMARTValueList):
TSMARTInterpreted; override;
end;
implementation
{ TCrucialNSTSupport }
function TCrucialNSTSupport.IsModelHasCrucialString: Boolean;
begin
result := Pos('CRUCIAL', Identify.Model) > 0;
end;
function TCrucialNSTSupport.IsMX100: Boolean;
begin
result := Pos('MX100', Identify.Model) > 0;
end;
function TCrucialNSTSupport.IsMX200: Boolean;
begin
result := Pos('MX200', Identify.Model) > 0;
end;
function TCrucialNSTSupport.IsMX300: Boolean;
begin
result := Pos('MX300', Identify.Model) > 0;
end;
function TCrucialNSTSupport.IsM550: Boolean;
begin
result := Pos('M550', Identify.Model) > 0;
end;
function TCrucialNSTSupport.IsM500: Boolean;
begin
result := Pos('M500', Identify.Model) > 0;
end;
function TCrucialNSTSupport.IsProductOfCrucial: Boolean;
begin
result := IsModelHasCrucialString and
(IsMX100 or IsMX200 or IsMX300 or
IsM500 or IsM550);
end;
function TCrucialNSTSupport.GetFullSupport: TSupportStatus;
begin
result.Supported := Supported;
result.FirmwareUpdate := true;
result.TotalWriteType := TTotalWriteType.WriteSupportedAsValue;
end;
function TCrucialNSTSupport.GetSupportStatus: TSupportStatus;
begin
result.Supported := NotSupported;
if IsProductOfCrucial then
result := GetFullSupport;
end;
function TCrucialNSTSupport.GetTotalWrite: TTotalWrite;
const
LBAtoMiB: Double = 1/2 * 1/1024;
IDOfHostWrite = 246;
var
RAWValue: UInt64;
begin
result.InValue.TrueHostWriteFalseNANDWrite := true;
RAWValue :=
InterpretingSMARTValueList.GetRAWByID(IDOfHostWrite);
result.InValue.ValueInMiB := Floor(RAWValue * LBAtoMiB);
end;
function TCrucialNSTSupport.GetSMARTInterpreted(
SMARTValueList: TSMARTValueList): TSMARTInterpreted;
const
IDOfEraseError = 172;
IDOfReplacedSector = 5;
IDofUsedHour = 9;
ReplacedSectorThreshold = 50;
EraseErrorThreshold = 10;
begin
InterpretingSMARTValueList := SMARTValueList;
result.TotalWrite := GetTotalWrite;
result.UsedHour :=
InterpretingSMARTValueList.GetRAWByID(IDOfUsedHour);
result.ReadEraseError.TrueReadErrorFalseEraseError := false;
result.ReadEraseError.Value :=
InterpretingSMARTValueList.GetRAWByID(IDOfEraseError);
result.SMARTAlert.ReadEraseError :=
result.ReadEraseError.Value >= EraseErrorThreshold;
result.ReplacedSectors :=
InterpretingSMARTValueList.GetRAWByID(IDOfReplacedSector);
result.SMARTAlert.ReplacedSector :=
result.ReplacedSectors >= ReplacedSectorThreshold;
end;
end.
|
unit svcReflectorU;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs, ReflectorsU;
type
TNetReflectorService = class(TService)
procedure ServiceCreate(Sender: TObject);
procedure ServiceDestroy(Sender: TObject);
procedure ServiceStart(Sender: TService; var Started: Boolean);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
private
FReflectors: TReflectors;
public
function GetServiceController: TServiceController; override;
{ Public declarations }
end;
var
NetReflectorService: TNetReflectorService;
implementation
{$R *.dfm}
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
NetReflectorService.Controller(CtrlCode);
end;
function TNetReflectorService.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TNetReflectorService.ServiceCreate(Sender: TObject);
begin
FReflectors := TReflectors.Create(Self);
end;
procedure TNetReflectorService.ServiceDestroy(Sender: TObject);
begin
FreeAndNil(FReflectors);
end;
procedure TNetReflectorService.ServiceStart(Sender: TService; var Started: Boolean);
begin
FReflectors.LoadSettings;
Started := FReflectors.Start;
end;
procedure TNetReflectorService.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
Stopped := FReflectors.Stop;
end;
end.
|
unit DialogWidgets;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, ExtCtrls, Graphics, StdCtrls, Controls,
Dialogs, Menus, LazUTF8, fgl, DialogItems, Math, CommonFunc;
type
{ TDialogMessage }
TAttachInfo = class(TObject)
// Информация о вложении
Id: integer;
Name: string;
OnClick: TNotifyEvent;
end;
TAttachList = specialize TFPGObjectList<TAttachInfo>;
{ TMessageData }
TMessageData = class(TObject)
// Данные сообщения
TitleName: string;
Text: string;
Time: TDateTime;
AttachList: TAttachList;
Picture: TPicture;
constructor Create; virtual;
destructor Destroy; override;
end;
TMessageDataList = specialize TFPGObjectList<TMessageData>;
TDialogItemsList = specialize TFPGObjectList<TDialogItem>;
TDialog = class(TCustomPanel)
// Диалог
private
// Реальные окна сообщений
function GetRealMessageItem(Index: integer): TDialogItem;
procedure SetRealMessageItem(Index: integer; AValue: TDialogItem);
// Виртуальные сообщения
function GetMessage(Index: integer): TMessageData;
procedure SetMessage(Index: integer; AValue: TMessageData);
function GetMessageCount: integer;
private
fFriendName: string;
fUserName: string;
fUserPicture: TPicture;
fFriendPicture: TPicture;
fPanel: TCustomPanel;
fScrollBar: TScrollBar;
fMessages: TMessageDataList;
fRealMessageItems: TDialogItemsList;
// Прокрутка окна компонента
function GetRealMessageCount: integer;
procedure OnScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: integer);
procedure OnEventMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: boolean);
procedure OnEventMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: boolean);
// Создание реального элемента сообщения
function AddRealMessage: integer;
// Присвоить данные из виртуального сообщение реальному
procedure RealMessageLoadDataFromVirtualMessage(IndexOfRealMessage, IndexOfVirtualMessage: integer);
// Вернуть верхнею свободную границу в окне
function GetYCoordForNewMessage: Integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
protected
procedure Resize; override;
public
// Настройка компонента
property UserPicture: TPicture read fUserPicture write fUserPicture;
property UserName: string read fUserName write fUserName;
property FriendPicture: TPicture read fFriendPicture write fFriendPicture;
property FriendName: string read fFriendName write fFriendName;
// Добавление виртуального сообщения
procedure Add(AText: string; ATime: TDateTime; AIsFriend: boolean); overload;
procedure Add(AText: string; ATime: TDateTime; AIsFriend: boolean; AAttachList: TAttachList); overload;
// Количество сообщений
property MessageCount: integer read GetMessageCount;
property RealMessageCount: integer read GetRealMessageCount;
// Сообщения виртуальные
property Message[Index: integer]: TMessageData read GetMessage write SetMessage;
// Количество окон для вывода сообщений
property RealMessageItem[Index: integer]: TDialogItem read GetRealMessageItem write SetRealMessageItem;
end;
implementation
{ TMessageData }
constructor TMessageData.Create;
begin
AttachList := TAttachList.Create(True);
Picture := TPicture.Create;
inherited Create;
end;
destructor TMessageData.Destroy;
begin
if Assigned(AttachList) then
AttachList.Free;
if Assigned(Picture) then
Picture.Free;
inherited Destroy;
end;
{ TDialog }
constructor TDialog.Create(AOwner: TComponent);
// Создание компонента
begin
inherited Create(AOwner);
OnMouseWheelDown := @OnEventMouseWheelDown;
OnMouseWheelUp := @OnEventMouseWheelUp;
DoubleBuffered := True;
Self.BevelInner := bvNone;
Self.BevelOuter := bvRaised;
fMessages := TMessageDataList.Create(True);
fRealMessageItems := TDialogItemsList.Create(False); // <- Графические компоненты удаляются при удалении предков (автоматически)
fUserPicture := TPicture.Create;
fFriendPicture := TPicture.Create;
// Компонент
fScrollBar := TScrollBar.Create(self);
fScrollBar.Kind := sbVertical;
fScrollBar.Align := alRight;
fScrollBar.Parent := self;
fScrollBar.OnScroll := @OnScroll;
fScrollBar.Max := 1;
fScrollBar.Min := 1;
fPanel := TCustomPanel.Create(Self);
fPanel.Parent := self;
fPanel.Align := alClient;
end;
destructor TDialog.Destroy;
// Уничтожение
begin
if Assigned(fPanel) then
fPanel.Free;
if Assigned(fScrollBar) then
fScrollBar.Free;
if Assigned(fMessages) then
fMessages.Free;
if Assigned(fRealMessageItems) then
fRealMessageItems.Free;
if Assigned(fUserPicture) then
fUserPicture.Free;
if Assigned(fFriendPicture) then
fFriendPicture.Free;
inherited Destroy;
end;
function TDialog.GetMessage(Index: integer): TMessageData;
begin
Result := fMessages[Index];
end;
function TDialog.GetRealMessageItem(Index: integer): TDialogItem;
begin
Result := fRealMessageItems[Index];
end;
procedure TDialog.SetRealMessageItem(Index: integer; AValue: TDialogItem);
begin
fRealMessageItems[Index] := AValue;
end;
function TDialog.GetMessageCount: integer;
begin
Result := fMessages.Count;
end;
procedure TDialog.SetMessage(Index: integer; AValue: TMessageData);
begin
fMessages[Index] := AValue;
end;
procedure TDialog.OnScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: integer);
var
delta: integer;
begin
if MessageCount = 0 then
exit;
delta := -1 * (ScrollPos + RealMessageItem[0].Top);
case ScrollCode of
scLineUp: fPanel.ScrollBy(0, delta); // = SB_LINEUP
scLineDown: fPanel.ScrollBy(0, delta); // = SB_LINEDOWN
scPageUp: fPanel.ScrollBy(0, delta * -10); // = SB_PAGEUP
scPageDown: fPanel.ScrollBy(0, delta * 10); // = SB_PAGEDOWN
scPosition: fPanel.ScrollBy(0, delta); // = SB_THUMBPOSITION
scTrack: fPanel.ScrollBy(0, delta); // = SB_THUMBTRACK
else
nop;
end;
end;
function TDialog.GetRealMessageCount: integer;
begin
Result := fRealMessageItems.Count;
end;
procedure TDialog.OnEventMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: boolean);
// Прокрутка колёсиком мыши вверх
var
delta: integer;
begin
if MessageCount = 0 then
exit;
fScrollBar.Position := fScrollBar.Position - 10;
delta := -1 * (fScrollBar.Position + RealMessageItem[0].Top);
fPanel.BeginUpdateBounds;
fPanel.ScrollBy(0, delta);
fPanel.EndUpdateBounds;
Application.ProcessMessages;
end;
procedure TDialog.OnEventMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: boolean);
// Прокрутка колёсиком мыши вниз
var
delta: integer;
begin
if MessageCount = 0 then
exit;
fScrollBar.Position := fScrollBar.Position + 10;
delta := -1 * (fScrollBar.Position + RealMessageItem[0].Top);
fPanel.BeginUpdateBounds;
fPanel.ScrollBy(0, delta);
fPanel.EndUpdateBounds;
Application.ProcessMessages;
end;
procedure TDialog.Resize;
begin
inherited Resize;
end;
function TDialog.AddRealMessage: integer;
// Создание реального элемента сообщения
var
Item: TDialogItem;
begin
Item := TDialogItem.Create(fPanel);
Item.Left := 0;
Item.Top := ifthen(RealMessageCount = 0, 0, GetYCoordForNewMessage);
fScrollBar.Visible := Item.Top > Height;
Item.Width := fPanel.Width;
Item.Parent := fPanel;
Item.Anchors := [akLeft, akRight, akTop];
Item.OnMouseWheelUp := @OnEventMouseWheelUp;
Item.OnMouseWheelDown := @OnEventMouseWheelDown;
Item.ReAlign;
fRealMessageItems.Add(Item);
Result := fRealMessageItems.Count - 1;
end;
procedure TDialog.RealMessageLoadDataFromVirtualMessage(IndexOfRealMessage, IndexOfVirtualMessage: integer);
// Присвоить данные из виртуального сообщение реальному
begin
with fMessages[IndexOfVirtualMessage] do
fRealMessageItems[IndexOfRealMessage].Establish(TitleName, Text, Time);
fRealMessageItems[IndexOfRealMessage].Picture.Assign(fMessages[IndexOfVirtualMessage].Picture);
end;
function TDialog.GetYCoordForNewMessage: Integer;
var
i: Integer;
begin
Result := 0;
for i:= 0 to RealMessageCount - 1 do
Result += RealMessageItem[i].Height;
end;
procedure TDialog.Add(AText: string; ATime: TDateTime; AIsFriend: boolean);
begin
Add(AText, ATime, AIsFriend, nil);
end;
procedure TDialog.Add(AText: string; ATime: TDateTime; AIsFriend: boolean; AAttachList: TAttachList);
// Добавление виртуального элемента
var
Data: TMessageData;
begin
// Заполняем данные
Data := TMessageData.Create;
with Data do
begin
TitleName := BoolToStr(AIsFriend, FriendName, UserName);
Text := AText;
Time := ATime;
if Assigned(AAttachList) then
AttachList.Assign(AAttachList);
if AIsFriend then
Data.Picture.Assign(FriendPicture)
else
Data.Picture.Assign(UserPicture);
end;
fMessages.Add(Data);
// Проверяем можем ли мы добавить видимый элемент
RealMessageLoadDataFromVirtualMessage(AddRealMessage, fMessages.Count - 1);
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.Jpeg,
//GLS
GLScene, GLWin32Viewer, GLVectorFileObjects, GLObjects,
GLProxyObjects, GLGeomObjects, GLVectorGeometry, GLCadencer,
GLTexture, GLMaterial, GLCoordinates, GLCrossPlatform,
GLBaseClasses, GLFileSMD;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLMaterialLibrary1: TGLMaterialLibrary;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
InvisibleDummyCube: TGLDummyCube;
GLDummyCube2: TGLDummyCube;
MasterActor: TGLActor;
GLActorProxy1: TGLActorProxy;
GLArrowLine1: TGLArrowLine;
GLLightSource1: TGLLightSource;
Timer1: TTimer;
GLSphere1: TGLSphere;
GLArrowLine3: TGLArrowLine;
GLActorProxy2: TGLActorProxy;
GLArrowLine2: TGLArrowLine;
Panel1: TPanel;
cbActorsAreTurning: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure Timer1Timer(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
private
mouseX, mouseY : Integer;
procedure DoRaycastStuff;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
GLUtils;
procedure TForm1.FormCreate(Sender: TObject);
var
i : Integer;
begin
SetGLSceneMediaDir();
MasterActor.LoadFromFile('TRINITYrage.smd');
MasterActor.AddDataFromFile('run.smd');
MasterActor.AddDataFromFile('jump.smd');
MasterActor.Animations.Items[0].Name:='still';
MasterActor.Animations.Items[1].Name:='walk';
MasterActor.Animations.Items[2].Name:='jump';
for i := 0 to MasterActor.Animations.Count-1 do
begin
MasterActor.Animations[i].MakeSkeletalTranslationStatic;
MasterActor.SwitchToAnimation(i); // forces animations to be initialized for ActorsProxies
end;
MasterActor.SwitchToAnimation(0); // revert back to empty animation (not necessary)
MasterActor.AnimationMode:=aamLoop; // animationmode is shared between proxies.
GLActorProxy1.StoreBonesMatrix:=true;
GLActorProxy2.StoreBonesMatrix:=true;
GLActorProxy1.Animation := MasterActor.Animations[1].Name;
GLActorProxy2.Animation := MasterActor.Animations[2].Name;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
mouseX := X;
mouseY := Y;
end;
procedure TForm1.DoRaycastStuff;
var
rayStart, rayVector, iPoint, iNormal : TVector;
begin
SetVector(rayStart, GLCamera1.AbsolutePosition);
SetVector(rayVector, GLSceneViewer1.Buffer.ScreenToVector(
AffineVectorMake(mouseX, GLSceneViewer1.Height-mouseY, 0)));
NormalizeVector(rayVector);
if GLActorProxy1.RayCastIntersect(rayStart,rayVector,@iPoint,@iNormal) then
begin
GLSphere1.Position.AsVector:=iPoint;
GLSphere1.Direction.AsVector:=VectorNormalize(iNormal);
end
else
if GLActorProxy2.RayCastIntersect(rayStart,rayVector,@iPoint,@iNormal) then
begin
GLSphere1.Position.AsVector:=iPoint;
GLSphere1.Direction.AsVector:=VectorNormalize(iNormal);
end
else
begin
GLSphere1.Position.AsVector:=rayStart;
GLSphere1.Direction.AsVector:=rayVector;
end;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
// Align object to hand
GLArrowLine1.Matrix := GLActorProxy1.BoneMatrix('Bip01 R Finger1');
GLArrowLine2.Matrix := GLActorProxy2.BoneMatrix('Bip01 R Finger1');
// turn actors
if cbActorsAreTurning.Checked then
begin
GLActorProxy1.Turn(-deltaTime *130);
GLActorProxy2.Turn(deltaTime *100);
end;
DoRaycastStuff;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Panel1.Caption:=GLSceneViewer1.FramesPerSecondText(0);
GLSceneViewer1.ResetPerformanceMonitor;
end;
end.
|
unit Test.Threads.Base;
interface
uses Windows, TestFrameWork, GMGlobals, Classes, Threads.Base;
type
TGMHangingThread = class(TGMThread)
protected
procedure SafeExecute(); override;
end;
TGMFinishedThread = class(TGMThread)
protected
procedure SafeExecute(); override;
end;
TGMGoodThread = class(TGMThread)
protected
procedure SafeExecute(); override;
end;
TGMThreadTest = class(TTestCase)
published
procedure Hanging;
procedure HangingPool;
procedure GoodThreadPool;
end;
implementation
uses
IdGlobal, System.SysUtils;
{ TGMHangingThread }
procedure TGMHangingThread.SafeExecute;
begin
while true do
SleepThread(10);
end;
{ TGMFinishedThread }
procedure TGMFinishedThread.SafeExecute;
begin
end;
{ TGMGoodThread }
procedure TGMGoodThread.SafeExecute;
begin
while not Terminated do
Sleep(10);
end;
{ TGMThreadTest }
procedure TGMThreadTest.GoodThreadPool;
var
pool: TGMThreadPool<TGMThread>;
i: int;
timeStart, t: uint64;
begin
pool := TGMThreadPool<TGMThread>.Create();
pool.Add(TGMFinishedThread.Create());
pool.Add(TGMFinishedThread.Create());
for i := 0 to 100 do
pool.Add(TGMGoodThread.Create());
timeStart := GetTickCount64();
pool.Free();
t := GetTickCount64() - timeStart;
Check(t < 2000, IntToStr(t) + ' must be 2000 or less');
end;
procedure TGMThreadTest.Hanging;
var
thr: TGMHangingThread;
begin
thr := TGMHangingThread.Create();
Sleep(100);
thr.Terminate();
thr.WaitForTimeout(100, true);
thr.Free();
Check(true);
end;
procedure TGMThreadTest.HangingPool;
var
pool: TGMThreadPool<TGMThread>;
i: int;
t, t1, dt: int64;
begin
pool := TGMThreadPool<TGMThread>.Create();
pool.Add(TGMFinishedThread.Create());
pool.Add(TGMFinishedThread.Create());
for i := 0 to 100 do
pool.Add(TGMHangingThread.Create());
pool.TimeOut := 1000;
t := GetTickCount64();
pool.Free();
t1 := GetTickCount64();
dt := t1 - t;
Check(dt < 1000, IntTostr(dt) + ' must be 1000 or less');
end;
initialization
RegisterTest('Threads', TGMThreadTest.Suite);
end.
|
{
Esta classe implementa o padrão de projeto singleton.
Objetos desta desta classe são o sujeito observado.
}
unit UProjetoDesenho;
interface
uses
UFormaGeometrica
, Generics.Collections
;
type
IObservadorProjetoDesenho = interface
['{677DA492-08E8-4164-9AF9-F187C0A603B1}']
procedure AtualizouProjeto(const coListaFormaGeometricas: TList<TFormaGeometrica>);
end;
TProjetoDesenho = class
private
FListaFormaGeometricas: TList<TFormaGeometrica>;
FListaObservadores: TList<IObservadorProjetoDesenho>;
procedure AvisaObservadores;
public
constructor Create;
destructor Destroy; override;
procedure RegistraObservador(const coObservador: IObservadorProjetoDesenho);
procedure RemoveObservador(const coObservador: IObservadorProjetoDesenho);
procedure AdicionaFormaGeometrica(const coFormaGeometrica: TFormaGeometrica);
procedure RemoveFormaGeometrica(const coFormaGeometrica: TFormaGeometrica);
class function RetornaUnico: TProjetoDesenho;
end;
implementation
uses
SysUtils
;
var
ProjetoDesenho: TProjetoDesenho = nil;
{ TProjetoDesenho }
procedure TProjetoDesenho.AdicionaFormaGeometrica(
const coFormaGeometrica: TFormaGeometrica);
begin
FListaFormaGeometricas.Add(coFormaGeometrica);
AvisaObservadores;
end;
procedure TProjetoDesenho.RegistraObservador(
const coObservador: IObservadorProjetoDesenho);
begin
FListaObservadores.Add(coObservador);
coObservador.AtualizouProjeto(FListaFormaGeometricas);
end;
procedure TProjetoDesenho.AvisaObservadores;
var
loObservador: IObservadorProjetoDesenho;
begin
for loObservador in FListaObservadores do
loObservador.AtualizouProjeto(FListaFormaGeometricas);
end;
constructor TProjetoDesenho.Create;
begin
FListaObservadores := TList<IObservadorProjetoDesenho>.Create;
FListaFormaGeometricas := TList<TFormaGeometrica>.Create;
end;
destructor TProjetoDesenho.Destroy;
begin
FreeAndNil(FListaObservadores);
FreeAndNil(FListaFormaGeometricas);
inherited;
end;
procedure TProjetoDesenho.RemoveFormaGeometrica(
const coFormaGeometrica: TFormaGeometrica);
begin
FListaFormaGeometricas.Remove(coFormaGeometrica);
AvisaObservadores;
end;
procedure TProjetoDesenho.RemoveObservador(
const coObservador: IObservadorProjetoDesenho);
begin
FListaObservadores.Remove(coObservador);
end;
class function TProjetoDesenho.RetornaUnico: TProjetoDesenho;
begin
if not Assigned(ProjetoDesenho) then
ProjetoDesenho := TProjetoDesenho.Create;
Result := ProjetoDesenho;
end;
end.
|
unit Vigilante.Compilacao.Model;
{$M+}
interface
uses
System.Generics.Collections, Module.ValueObject.URL,
Vigilante.Aplicacao.SituacaoBuild, Vigilante.ChangeSetItem.Model,
Vigilante.Aplicacao.ModelBase;
type
ICompilacaoModel = interface(IVigilanteModelBase)
['{91DCE211-D41D-4BB8-96E8-4DA35C4EC555}']
function GetChangeSet: TObjectList<TChangeSetItem>;
function GetNumero: integer;
function Equals(const CompilacaoModel: ICompilacaoModel): boolean;
property Numero: integer read GetNumero;
property ChangeSet: TObjectList<TChangeSetItem> read GetChangeSet;
end;
implementation
end.
|
{
Maximum Bipartite Matching
Augmenting Path Alg. O(N2.E) Implementation O(N4)
but very near to O(N.E) Implementation O(N3)
Input:
G: UnDirected Simple Bipartite Graph
M, N: Number of vertices
Output:
Mt: Match of Each Vertex (0 if not matched)
Matched: size of matching (number of matched edges)
Reference:
West
By Behdad
}
program
BipartiteMaximumMatching;
const
MaxNum = 100 + 2;
var
M, N : Integer;
G : array [1 .. MaxNum, 1 .. MaxNum] of Integer;
Mt : array [1 .. 2, 1 .. MaxNum] of Integer;
Mark : array [0 .. MaxNum] of Boolean;
Matched : Integer;
function MDfs (V : Integer) : Boolean;
var
I : Integer;
begin
if V = 0 then begin MDfs := True; Exit; end;
Mark[V] := True;
for I := 1 to N do
if (G[V, I] <> 0) and not Mark[Mt[2, I]] and MDfs(Mt[2, I]) then
begin
Mt[1, V] := I;
Mt[2, I] := V;
MDfs := True;
Exit;
end;
MDfs := False;
end;
procedure AugmentingPath;
var
I: Integer;
begin
FillChar(Mark, SizeOf(Mark), 0);
FillChar(Mt, SizeOf(Mark), 0);
for I := 1 to M do
if (Mt[1, I] = 0) and MDfs(I) then
begin
Inc(Matched);
FillChar(Mark, SizeOf(Mark), 0);
I := 0;
end;
end;
begin
AugmentingPath;
end.
|
{**********************************************}
{ TeeChart HighLow Series Editor }
{ Copyright (c) 1999-2004 by David Berneda }
{**********************************************}
unit TeeHighLowEdit;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
ErrorBar, TeCanvas, TeePenDlg, TeeProcs;
type
THighLowEditor = class(TForm)
BPen: TButtonPen;
BHighPen: TButtonPen;
BLowPen: TButtonPen;
BBrush: TButton;
CBColorEach: TCheckBox;
BLowBrush: TButton;
BColor: TButtonColor;
Label1: TLabel;
Edit1: TEdit;
UDTransp: TUpDown;
procedure FormShow(Sender: TObject);
procedure BBrushClick(Sender: TObject);
procedure BLowBrushClick(Sender: TObject);
procedure CBColorEachClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Edit1Change(Sender: TObject);
private
{ Private declarations }
HighLow : THighLowSeries;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeeBrushDlg;
procedure THighLowEditor.FormShow(Sender: TObject);
begin
HighLow:=THighLowSeries(Tag);
if Assigned(HighLow) then
begin
With HighLow do
begin
CBColorEach.Checked:=ColorEachPoint;
BLowPen.LinkPen(LowPen);
BHighPen.LinkPen(HighPen);
BPen.LinkPen(Pen);
UDTransp.Position:=Transparency;
end;
BColor.LinkProperty(HighLow,'SeriesColor');
end;
end;
procedure THighLowEditor.BBrushClick(Sender: TObject);
begin
EditChartBrush(Self,HighLow.HighBrush);
end;
procedure THighLowEditor.BLowBrushClick(Sender: TObject);
begin
EditChartBrush(Self,HighLow.LowBrush);
end;
procedure THighLowEditor.CBColorEachClick(Sender: TObject);
begin
HighLow.ColorEachPoint:=CBColorEach.Checked;
end;
procedure THighLowEditor.FormCreate(Sender: TObject);
begin
Align:=alClient;
end;
procedure THighLowEditor.Edit1Change(Sender: TObject);
begin
if Showing then
HighLow.Transparency:=UDTransp.Position;
end;
initialization
RegisterClass(THighLowEditor);
end.
|
//-----------------------------------------
// Maciej Czekański
// maves90@gmail.com
//-----------------------------------------
unit List;
interface
uses Arkanoid;
TYPE
TNodePtr_Ball = ^TNode_Ball;
TNode_Ball = record
prev: TNodePtr_Ball;
next: TNodePtr_Ball;
data: TBall;
end;
// BALLS
TListOfBalls = object
head: TNodePtr_Ball;
tail: TNodePtr_Ball;
procedure Init;
procedure DeInit;
function PushFront(ball: TBall): TNodePtr_Ball;
function PushBack(ball: TBall): TNodePtr_Ball;
function Front: TBall;
function Back: TBall;
function Count: longint;
function Search(ball: TBall): TNodePtr_Ball;
procedure PopFront;
procedure PopBack;
procedure Remove(node: TNodePtr_Ball);
end;
// BRICKS
TNodePtr_Brick = ^TNode_Brick;
TNode_Brick = record
prev: TNodePtr_Brick;
next: TNodePtr_Brick;
data: TBrick;
end;
TListOfBricks = object
head: TNodePtr_Brick;
tail: TNodePtr_Brick;
procedure Init;
procedure DeInit;
function PushFront(brick: TBrick): TNodePtr_Brick;
function PushBack(brick: TBrick): TNodePtr_Brick;
function Front: TBrick;
function Back: TBrick;
function Count: longint;
function Search(brick: TBrick): TNodePtr_Brick;
procedure PopFront;
procedure PopBack;
procedure Remove(node: TNodePtr_Brick);
end;
// POWERUPS
TNodePtr_Powerup = ^TNode_Powerup;
TNode_Powerup = record
prev: TNodePtr_Powerup;
next: TNodePtr_Powerup;
data: TPowerup;
end;
TListOfPowerups = object
head: TNodePtr_Powerup;
tail: TNodePtr_Powerup;
procedure Init;
procedure DeInit;
function PushFront(powerup: TPowerup): TNodePtr_Powerup;
function PushBack(powerup: TPowerup): TNodePtr_Powerup;
function Front: TPowerup;
function Back: TPowerup;
function Count: longint;
function Search(powerup: TPowerup): TNodePtr_Powerup;
procedure PopFront;
procedure PopBack;
procedure Remove(node: TNodePtr_Powerup);
end;
IMPLEMENTATION
// BALLS ------------------------------------------------------------------------
procedure TlistOfBalls.Init;
begin
head:= nil;
tail:= nil;
end;
procedure TlistOfBalls.DeInit;
var
node: TNodePtr_Ball;
begin
node:= head;
while node <> nil do begin
node:= node^.next;
PopFront;
end;
end;
function TListOfBalls.PushFront(ball: TBall): TNodePtr_Ball;
var
newNode: TNodePtr_Ball;
begin
New(newNode);
newNode^.prev:= nil;
newNode^.next:= head;
newNode^.data:= ball;
if head = nil then begin
head:= newNode;
tail:= newNode;
end
else begin
head^.prev:= newNode;
head:= newNode;
end;
result:= newNode;
end;
function TListOfBalls.PushBack(ball: TBall): TnodePtr_Ball;
var
newNode: TNodePtr_Ball;
begin
New(newNode);
newNode^.prev:= tail;
newNode^.next:= nil;
newNode^.data:= ball;
if tail = nil then begin
head:= newNode;
tail:= newNode;
end
else begin
tail^.next:= newNode;
tail:= newNode;
end;
result:= newNode;
end;
function TlistOfBalls.Front: TBall;
begin
result:= head^.data;
end;
function TListOfBalls.Back: TBall;
begin
result:= tail^.data;
end;
function TListOfBalls.Count: longint;
var
node: TNodePtr_Ball;
num: longint = 0;
begin
node:= head;
while node <> nil do begin
Inc(num);
node:= node^.next;
end;
result:= num;
end;
function TListOfBalls.Search(ball: TBall): TNodePtr_Ball;
var
node: TNodePtr_Ball;
begin
node:= head;
result:= nil;
while node <> nil do begin
if node^.data = ball then begin
result:= node;
break;
end;
node:= node^.next;
end;
end;
procedure TListOfBalls.PopFront;
begin
if head = tail then begin
Dispose(head);
head:= nil;
tail:= nil;
end
else begin
head:= head^.next;
Dispose(head^.prev);
head^.prev:= nil;
end;
end;
procedure TListOfBalls.PopBack;
var
node: TNodePtr_Ball;
begin
node:= tail;
if head = tail then begin
Dispose(tail);
head:= nil;
tail:= nil;
end
else begin
tail:= tail^.prev;
tail^.next:= nil;
Dispose(node);
end;
end;
procedure TListOfBalls.Remove(node: TNodePtr_Ball);
begin
if node = head then
PopFront
else if node = tail then
PopBack
else begin
node^.prev^.next := node^.next;
node^.next^.prev := node^.prev;
Dispose(node);
end;
end;
// BRICKS-------------------------------------------------------------------
procedure TlistOfBricks.Init;
begin
head:= nil;
tail:= nil;
end;
procedure TlistOfBricks.DeInit;
var
node: TNodePtr_Brick;
begin
node:= head;
while node <> nil do begin
node:= node^.next;
PopFront;
end;
head:= nil;
tail:= nil;
end;
function TlistOfBricks.PushFront(brick: TBrick): TNodePtr_Brick;
var
newNode: TNodePtr_Brick;
begin
New(newNode);
newNode^.prev:= nil;
newNode^.next:= head;
newNode^.data:= brick;
if head = nil then begin
head:= newNode;
tail:= newNode;
end
else begin
head^.prev:= newNode;
head:= newNode;
end;
result:= newNode;
end;
function TlistOfBricks.PushBack(brick: TBrick): TNodePtr_Brick;
var
newNode: TNodePtr_Brick;
begin
New(newNode);
newNode^.prev:= tail;
newNode^.next:= nil;
newNode^.data:= brick;
if tail = nil then begin
head:= newNode;
tail:= newNode;
end
else begin
tail^.next:= newNode;
tail:= newNode;
end;
result:= newNode;
end;
function TlistOfBricks.Front: TBrick;
begin
result:= head^.data;
end;
function TlistOfBricks.Back: TBrick;
begin
result:= tail^.data;
end;
function TlistOfBricks.Count: longint;
var
node: TNodePtr_Brick;
num: longint = 0;
begin
node:= head;
while node <> nil do begin
Inc(num);
node:= node^.next;
end;
result:= num;
end;
function TlistOfBricks.Search(brick: TBrick): TNodePtr_Brick;
var
node: TNodePtr_Brick;
begin
node:= head;
result:= nil;
while node <> nil do begin
if node^.data = brick then begin
result:= node;
break;
end;
node:= node^.next;
end;
end;
procedure TlistOfBricks.PopFront;
begin
if head = tail then begin
Dispose(head);
head:= nil;
tail:= nil;
end
else begin
head:= head^.next;
Dispose(head^.prev);
head^.prev:= nil;
end;
end;
procedure TlistOfBricks.PopBack;
var
node: TNodePtr_Brick;
begin
node:= tail;
if head = tail then begin
Dispose(tail);
head:= nil;
tail:= nil;
end
else begin
tail:= tail^.prev;
tail^.next:= nil;
Dispose(node);
end;
end;
procedure TlistOfBricks.Remove(node: TNodePtr_Brick);
begin
if node = head then
PopFront
else if node = tail then
PopBack
else begin
node^.prev^.next := node^.next;
node^.next^.prev := node^.prev;
Dispose(node);
end;
end;
// POWERUPS -------------------------------------------------------------
procedure TlistOfPowerups.Init;
begin
head:= nil;
tail:= nil;
end;
procedure TlistOfPowerups.DeInit;
var
node: TNodePtr_Powerup;
begin
node:= head;
while node <> nil do begin
node:= node^.next;
PopFront;
end;
head:= nil;
tail:= nil;
end;
function TlistOfPowerups.PushFront(powerup: TPowerup): TNodePtr_Powerup;
var
newNode: TNodePtr_Powerup;
begin
New(newNode);
newNode^.prev:= nil;
newNode^.next:= head;
newNode^.data:= powerup;
if head = nil then begin
head:= newNode;
tail:= newNode;
end
else begin
head^.prev:= newNode;
head:= newNode;
end;
result:= newNode;
end;
function TlistOfPowerups.PushBack(powerup: TPowerup): TNodePtr_Powerup;
var
newNode: TNodePtr_Powerup;
begin
New(newNode);
newNode^.prev:= tail;
newNode^.next:= nil;
newNode^.data:= powerup;
if tail = nil then begin
head:= newNode;
tail:= newNode;
end
else begin
tail^.next:= newNode;
tail:= newNode;
end;
result:= newNode;
end;
function TlistOfPowerups.Front: TPowerup;
begin
result:= head^.data;
end;
function TlistOfPowerups.Back: TPowerup;
begin
result:= tail^.data;
end;
function TlistOfPowerups.Count: longint;
var
node: TNodePtr_Powerup;
num: longint = 0;
begin
node:= head;
while node <> nil do begin
Inc(num);
node:= node^.next;
end;
result:= num;
end;
function TlistOfPowerups.Search(powerup: TPowerup): TNodePtr_Powerup;
var
node: TNodePtr_Powerup;
begin
node:= head;
result:= nil;
while node <> nil do begin
if node^.data = powerup then begin
result:= node;
break;
end;
node:= node^.next;
end;
end;
procedure TlistOfPowerups.PopFront;
begin
if head = tail then begin
Dispose(head);
head:= nil;
tail:= nil;
end
else begin
head:= head^.next;
Dispose(head^.prev);
head^.prev:= nil;
end;
end;
procedure TlistOfPowerups.PopBack;
var
node: TNodePtr_Powerup;
begin
node:= tail;
if head = tail then begin
Dispose(tail);
head:= nil;
tail:= nil;
end
else begin
tail:= tail^.prev;
tail^.next:= nil;
Dispose(node);
end;
end;
procedure TlistOfPowerups.Remove(node: TNodePtr_Powerup);
begin
if node = head then
PopFront
else if node = tail then
PopBack
else begin
node^.prev^.next := node^.next;
node^.next^.prev := node^.prev;
Dispose(node);
end;
end;
BEGIN
END.
Lubie placki |
unit umyToolbars;
interface
uses
Classes, Windows, Messages, Controls, Actions, ImgList, Graphics, ActnList, Forms,
Menus, SysUtils, Types;
type
TSkinIndicator = (
siInactive, siHover, siPressed, siSelected, siHoverSelected
);
TmyToolItem = record
Action: TBasicAction;
Enabled: boolean;
Visible: boolean;
ImageIndex: Integer; // 考虑到标题功能图标和实际工具栏功能使用不同图标情况,分开图标索引
Width: Word; // 实际占用宽度,考虑后续加不同的按钮样式使用
Fade: Word; // 褪色量 0 - 255
SaveEvent: TNotifyEvent; // 原始的Action OnChange事件
end;
TmyCustomToolbar = class(TWinControl)
private
FAutoWidth: Boolean;
FItems: array of TmyToolItem;
FCount: Integer;
FImages: TCustomImageList;
FHotIndex: Integer;
FPressedIndex: Integer;
function HitTest(x, y: Integer): Integer;
procedure ExecAction(Index: Integer);
procedure DoOnActionChange(Sender: TObject);
function LoadActionIcon(Idx: Integer; AImg: TBitmap): boolean;
procedure SetAutoWidth(const Value: Boolean);
procedure SetHotIndex(const Value: Integer);
procedure UpdateFade;
procedure WMEraseBkgnd(var message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure WMPaint(var message: TWMPaint); message WM_Paint;
procedure WMMouseLeave(var message: TMessage); message WM_MOUSELEAVE;
procedure WMMouseMove(var message: TWMMouseMove); message WM_MOUSEMOVE;
procedure WMTimer(var message: TWMTimer); message WM_TIMER;
procedure CMHintShow(var Message: TCMHintShow); message CM_HINTSHOW;
function GetActualWidth: Integer;
protected
// 计算实际占用尺寸
function CalcSize: TRect;
procedure UpdateSize;
procedure MouseMove(Shift: TShiftState; x: Integer; y: Integer); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; x: Integer; y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; x: Integer; y: Integer); override;
procedure PaintBackground(DC: HDC);
procedure PaintWindow(DC: HDC); override;
public
procedure Add(Action: TBasicAction; AImageIndex: Integer = -1);
function IndexOf(Action: TBasicAction): Integer;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property AutoWidth: Boolean read FAutoWidth write SetAutoWidth;
property HotIndex: Integer read FHotIndex write SetHotIndex;
property Images: TCustomImageList read FImages write FImages;
property ActualWidth: Integer read GetActualWidth;
end;
TmyToolbar = class(TmyCustomToolbar)
published
property Color;
end;
UISkin = class
private
class procedure DrawTransparentBitmap(Source: TBitmap; sx, sy: Integer;
Destination: HDC; const dX, dY: Integer; w, h: Integer; const Opacity: Byte); overload;
public
class procedure DrawButtonState(DC: HDC; AState: TSkinIndicator; const R:TRect; const AOpacity: Byte); static;
class procedure DrawIcon(DC: HDC; R: TRect; ASrc: TBitmap; const Opacity: Byte = 255);
end;
implementation
CONST
TIMID_FADE = 1; // Action褪色
type
TacAction = class(TBasicAction);
procedure TmyCustomToolbar.Add(Action: TBasicAction; AImageIndex: Integer);
begin
if FCount >= Length(FItems) then
SetLength(FItems, FCount + 5);
ZeroMemory(@FItems[FCount], SizeOf(TmyToolItem));
FItems[FCount].Action := Action;
FItems[FCount].Enabled := true;
FItems[FCount].Visible := true;
FItems[FCount].ImageIndex := AImageIndex;
FItems[FCount].Width := 20;
FItems[FCount].Fade := 0;
FItems[FCount].SaveEvent := TacAction(Action).OnChange;
TacAction(Action).OnChange := DoOnActionChange;
// 初始化状态
with FItems[FCount] do
if Action.InheritsFrom(TContainedAction) then
begin
Enabled := TContainedAction(Action).Enabled;
Visible := TContainedAction(Action).Visible;
end;
inc(FCount);
UpdateSize;
end;
function TmyCustomToolbar.CalcSize: TRect;
const
SIZE_SPLITER = 10;
SIZE_POPMENU = 10;
SIZE_BUTTON = 20;
var
w, h: Integer;
I: Integer;
begin
///
/// 占用宽度
/// 如果考虑比较复杂的按钮样式和显示标题等功能,那么需要计算每个按钮实际占用宽度才能获得。
// w := SIZE_SPLITER * 2 + SIZE_POPMENU;
w := 0;
for I := 0 to FCount - 1 do
if FItems[i].Visible then
w := w + FItems[I].Width;
h := SIZE_BUTTON;
Result := Rect(0, 0, w, h);
end;
procedure TmyCustomToolbar.CMHintShow(var Message: TCMHintShow);
var
Idx: Integer;
sHint: string;
sTitle, sRemark, sShortCut: string;
begin
sTitle := '';
sRemark := '';
sShortCut := '';
Idx := FHotIndex;
if (Idx >= FCount) or (not FItems[idx].Visible) then
Idx := -1;
// get hint data
if Idx >= 0 then
begin
if FItems[Idx].Action.InheritsFrom(TContainedAction) then
with TContainedAction(FItems[Idx].Action) do
begin
sTitle := Caption;
sRemark := Hint;
if ShortCut <> scNone then
sShortCut := ShortCutToText(TCustomAction(Action).ShortCut);
end;
end;
/// format hint string
if sTitle <> '' then
begin
if sShortCut = '' then
sHint := sTitle
else
sHint := Format('%s(%s)', [sTitle, sShortCut]);
if (sRemark <> '') and not SameText(sRemark, sTitle) then
sHint := Format('%s'#13#10' %s', [sHint, sRemark]);
end
else
sHint := sRemark;
Message.HintInfo.HintStr := sHint;
if sHint = '' then
Message.Result := 1;
end;
constructor TmyCustomToolbar.Create(AOwner: TComponent);
begin
inherited;
inherited Height := 20;
inherited Width := 20 * 3;
FHotIndex := -1;
FPressedIndex := -1;
FAutoWidth := true;
end;
destructor TmyCustomToolbar.Destroy;
begin
if HandleAllocated then
KillTimer(Handle, TIMID_FADE);
inherited;
end;
procedure TmyCustomToolbar.DoOnActionChange(Sender: TObject);
var
Idx: Integer;
bResize: boolean;
begin
if Sender is TBasicAction then
begin
Idx := IndexOf(TBasicAction(Sender));
if (Idx >= 0) and (Idx < FCount) then
begin
///
/// 外部状态改变响应
///
if FItems[Idx].Action.InheritsFrom(TContainedAction) then
begin
FItems[Idx].Enabled := TContainedAction(Sender).Enabled;
bResize := FItems[Idx].Visible <> TContainedAction(Sender).Visible;
if bResize then
begin
FItems[Idx].Visible := not FItems[Idx].Visible;
UpdateSize;
end
else if FItems[Idx].Visible then
Invalidate;
end;
/// 执行原有事件
if Assigned(FItems[Idx].SaveEvent) then
FItems[Idx].SaveEvent(Sender);
end;
end;
end;
procedure TmyCustomToolbar.ExecAction(Index: Integer);
begin
///
/// 执行命令
///
if (Index >= 0) and (Index < FCount) then
FItems[Index].Action.Execute;
end;
function TmyCustomToolbar.GetActualWidth: Integer;
var
R: TRect;
begin
R := CalcSize;
Result := r.Width;
end;
function TmyCustomToolbar.HitTest(x, y: Integer): Integer;
var
I: Integer;
Idx: Integer;
iOffx: Integer;
begin
Idx := -1;
iOffx := 0;
if PtInRect(ClientRect, Point(x, y)) then
for I := 0 to FCount - 1 do
begin
if not FItems[I].Visible then
Continue;
iOffx := iOffx + FItems[I].Width;
if (iOffx > x) then
begin
Idx := I;
Break;
end;
end;
// 去除无效的按钮
if (Idx >= 0) and (not FItems[Idx].Visible or not FItems[Idx].Enabled) then
Idx := -1;
Result := Idx;
end;
function TmyCustomToolbar.IndexOf(Action: TBasicAction): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to FCount - 1 do
if FItems[I].Action = Action then
begin
Result := I;
Break;
end;
end;
function TmyCustomToolbar.LoadActionIcon(Idx: Integer; AImg: TBitmap): boolean;
function LoadIcon(AImgs: TCustomImageList; AIndex: Integer): boolean;
begin
Result := False;
if Assigned(AImgs) and (AIndex >= 0) and (AIndex < AImgs.Count) then
Result := AImgs.GetBitmap(AIndex, AImg);
end;
var
bHasImg: boolean;
ImgIdx: Integer;
begin
/// 获取Action的图标
ImgIdx := -1;
AImg.Canvas.Brush.Color := clBlack;
AImg.Canvas.FillRect(Rect(0, 0, AImg.Width, AImg.Height));
bHasImg := LoadIcon(FImages, FItems[Idx].ImageIndex);
if not bHasImg and (FItems[Idx].Action is TCustomAction) then
begin
ImgIdx := TCustomAction(FItems[Idx].Action).ImageIndex;
bHasImg := LoadIcon(TCustomAction(FItems[Idx].Action).Images, ImgIdx);
end;
if not bHasImg then
bHasImg := LoadIcon(FImages, ImgIdx);
Result := bHasImg;
end;
procedure TmyCustomToolbar.MouseDown(Button: TMouseButton; Shift: TShiftState; x, y: Integer);
begin
if mbLeft = Button then
begin
FPressedIndex := HitTest(x, y);
Invalidate;
end;
end;
procedure TmyCustomToolbar.MouseMove(Shift: TShiftState; x, y: Integer);
begin
end;
procedure TmyCustomToolbar.MouseUp(Button: TMouseButton; Shift: TShiftState; x, y: Integer);
var
iPressed: Integer;
begin
if FPressedIndex >= 0 then
begin
iPressed := HitTest(x, y);
if iPressed = FPressedIndex then
ExecAction(iPressed);
end;
FPressedIndex := -1;
Invalidate;
end;
procedure TmyCustomToolbar.PaintBackground(DC: HDC);
var
hB: HBRUSH;
R: TRect;
begin
R := GetClientRect;
hB := CreateSolidBrush(ColorToRGB(Color));
FillRect(DC, R, hB);
DeleteObject(hB);
end;
procedure TmyCustomToolbar.PaintWindow(DC: HDC);
function GetActionState(Idx: Integer): TSkinIndicator;
begin
Result := siInactive;
if (Idx = FPressedIndex) then
Result := siPressed
else if (Idx = FHotIndex) and (FPressedIndex = -1) then
Result := siHover;
end;
var
cIcon: TBitmap;
R: TRect;
I: Integer;
iOpacity: byte;
begin
R := Rect(0, 0, 0, ClientHeight);
/// 绘制Button
cIcon := TBitmap.Create;
cIcon.PixelFormat := pf32bit;
cIcon.alphaFormat := afIgnored;
for I := 0 to FCount - 1 do
begin
if not FItems[i].Visible then
Continue;
R.Right := R.Left + FItems[I].Width;
if FItems[I].Enabled then
UISkin.DrawButtonState(DC, GetActionState(I), R, FItems[I].Fade);
if LoadActionIcon(I, cIcon) then
begin
iOpacity := 255;
/// 处理不可用状态,图标颜色变暗。
/// 简易处理,增加绘制透明度。
if not FItems[I].Enabled then
iOpacity := 100;
UISkin.DrawIcon(DC, R, cIcon, iOpacity);
end;
OffsetRect(R, R.Right - R.Left, 0);
end;
cIcon.free;
end;
procedure TmyCustomToolbar.SetAutoWidth(const Value: Boolean);
begin
if FAutoWidth <> Value then
begin
FAutoWidth := Value;
UpdateSize;
end;
end;
procedure TmyCustomToolbar.SetHotIndex(const Value: Integer);
begin
if FHotIndex <> Value then
begin
FHotIndex := Value;
Invalidate;
if not(csDestroying in ComponentState) and HandleAllocated then
SetTimer(Handle, TIMID_FADE, 90, nil);
end;
end;
procedure TmyCustomToolbar.UpdateFade;
function GetShowAlpha(v: byte): byte; inline;
begin
if v = 0 then Result := 180
else if v <= 180 then Result := 220
else Result := 255;
end;
function GetFadeAlpha(v: byte): byte; inline;
begin
if v >= 255 then Result := 230
else if v >= 230 then Result := 180
else if v >= 180 then Result := 100
else if v >= 100 then Result := 50
else if v >= 50 then Result := 10
else Result := 0;
end;
var
I: Integer;
bHas: boolean;
begin
bHas := False;
for I := 0 to FCount - 1 do
if FItems[I].Visible and FItems[I].Enabled then
begin
if FHotIndex = I then
FItems[I].Fade := GetShowAlpha(FItems[I].Fade)
else if FItems[I].Fade > 0 then
FItems[I].Fade := GetFadeAlpha(FItems[I].Fade);
bHas := bHas or (FItems[I].Fade > 0);
end;
Invalidate;
if not bHas and HandleAllocated then
KillTimer(Handle, TIMID_FADE);
end;
procedure TmyCustomToolbar.UpdateSize;
var
R: TRect;
begin
if FAutoWidth then
begin
R := CalcSize;
SetBounds(Left, Top, R.Width, Height);
end
else
Invalidate;
end;
procedure TmyCustomToolbar.WMEraseBkgnd(var message: TWMEraseBkgnd);
begin
Message.Result := 1;
end;
procedure TmyCustomToolbar.WMMouseLeave(var message: TMessage);
begin
HotIndex := -1;
end;
procedure TmyCustomToolbar.WMMouseMove(var message: TWMMouseMove);
var
iSave: Integer;
begin
iSave := FHotIndex;
HotIndex := HitTest(message.XPos, message.YPos);
if (iSave <> FHotIndex) and (FHotIndex >= 0) and (FPressedIndex = -1) then
Application.ActivateHint(message.Pos);
end;
procedure TmyCustomToolbar.WMPaint(var message: TWMPaint);
var
DC, hPaintDC: HDC;
cBuffer: TBitmap;
PS: TPaintStruct;
R: TRect;
w, h: Integer;
begin
///
/// 绘制客户区域
///
R := GetClientRect;
w := R.Width;
h := R.Height;
DC := Message.DC;
hPaintDC := DC;
if DC = 0 then
hPaintDC := BeginPaint(Handle, PS);
cBuffer := TBitmap.Create;
try
cBuffer.SetSize(w, h);
PaintBackground(cBuffer.Canvas.Handle);
PaintWindow(cBuffer.Canvas.Handle);
BitBlt(hPaintDC, 0, 0, w, h, cBuffer.Canvas.Handle, 0, 0, SRCCOPY);
finally
cBuffer.free;
end;
if DC = 0 then
EndPaint(Handle, PS);
end;
procedure TmyCustomToolbar.WMTimer(var message: TWMTimer);
begin
if message.TimerID = TIMID_FADE then
UpdateFade;
end;
class procedure UISkin.DrawButtonState(DC: HDC; AState: TSkinIndicator; const
R: TRect; const AOpacity: Byte);
const
SKINCOLOR_BTNHOT = $00F2D5C2; // Hot 激活状态
SKINCOLOR_BTNPRESSED = $00E3BDA3; // 按下状态
function GetColor(s: TSkinIndicator): Cardinal; inline;
begin
case s of
siHover : Result := SKINCOLOR_BTNHOT;
siPressed : Result := SKINCOLOR_BTNPRESSED;
siSelected : Result := SKINCOLOR_BTNPRESSED;
siHoverSelected : Result := SKINCOLOR_BTNHOT;
else Result := SKINCOLOR_BTNHOT;
end;
end;
procedure DrawStyle(DC: HDC; const R: TRect; AColor: Cardinal); inline;
var
hB: HBRUSH;
begin
hB := CreateSolidBrush(AColor);
FillRect(DC, R, hB);
DeleteObject(hB);
end;
var
cBmp: TBitmap;
begin
if AOpacity = 255 then
DrawStyle(DC, R, GetColor(AState))
else if AOpacity > 0 then
begin
cBmp := TBitmap.Create;
cBmp.SetSize(r.Width, r.Height);
DrawStyle(cBmp.Canvas.Handle, Rect(0, 0, r.Width, r.Height), GetColor(AState));
DrawTransparentBitmap(cBmp, 0, 0, DC, r.Left, r.Top, r.Width, r.Height, AOpacity);
cBmp.Free;
end;
end;
class procedure UISkin.DrawIcon(DC: HDC; R: TRect; ASrc: TBitmap; const
Opacity: Byte = 255);
var
iXOff: Integer;
iYOff: Integer;
begin
///
/// 绘制图标
/// 绘制图标是会作居中处理
iXOff := r.Left + (R.Right - R.Left - ASrc.Width) div 2;
iYOff := r.Top + (r.Bottom - r.Top - ASrc.Height) div 2;
DrawTransparentBitmap(ASrc, 0, 0, DC, iXOff, iYOff, ASrc.Width, ASrc.Height, Opacity);
end;
class procedure UISkin.DrawTransparentBitmap(Source: TBitmap; sx, sy: Integer;
Destination: HDC; const dX, dY: Integer; w, h: Integer; const Opacity:
Byte);
var
BlendFunc: TBlendFunction;
begin
BlendFunc.BlendOp := AC_SRC_OVER;
BlendFunc.BlendFlags := 0;
BlendFunc.SourceConstantAlpha := Opacity;
if Source.PixelFormat = pf32bit then
BlendFunc.AlphaFormat := AC_SRC_ALPHA
else
BlendFunc.AlphaFormat := 0;
AlphaBlend(Destination, dX, dY, w, h, Source.Canvas.Handle, sx, sy, w, h, BlendFunc);
end;
end.
|
unit uPlImagePlugin;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Windows, ActiveX, Classes, ComObj, Graphics, Forms, Contnrs, OpenGL,
uPlImagePluginInterface, uImageForm, JPEG, pngImage, uGLObjects;
const
MAX_IMAGES_COUNT = 1000;
type
TPlImagePlugin = class(TComObject, IPlImagePluginInterface)
//IPlImagePluginInterface
public
function IMImage_Load(PData: Pointer; DataSize: Integer): HIMAGE;
function IMImage_WindowShow(MonitorIndex: Integer; WindowRect: TRect): HWND;
function IMImage_WindowHide: HRESULT;
function IMImage_Show(AImage: HIMAGE): HRESULT;
function IMImage_ShowPreview(AImage: HIMAGE): HRESULT;
function IMImage_Hide(AImage: HIMAGE): HRESULT;
function IMImage_GetData(AImage: HIMAGE; var PData: Pointer; var DataSize: Integer): HRESULT;
function IMImage_Duplicate(AImage: HIMAGE): HIMAGE;
procedure IMImage_Free(AImage: HIMAGE);
function IMImage_GetPreviewTex(AImage: HIMAGE; ADC: HDC; ARC: HGLRC): GLuint;
procedure IMImage_FreeGLContext(ADC: HDC; ARC: HGLRC);
private
FImages: array[0..MAX_IMAGES_COUNT - 1] of TGraphic;
FImageForm: TImageForm;
FGLContainerList: TObjectList;
FPTempMem: Pointer;
procedure ReleaseAllImages;
function GetMinFreeImageIndex: Integer;
function GetGLContainer(ADC: HDC; ARC: HGLRC): TGLContainer;
function GetOrCreateGLContainer(ADC: HDC; ARC: HGLRC): TGLContainer;
public
procedure Initialize; override;
destructor Destroy; override;
end;
implementation
uses ComServ;
{ TPlImagePlugin }
destructor TPlImagePlugin.Destroy;
begin
FImageForm.Release;
ReleaseAllImages;
if FPTempMem <> nil then
FreeMem(FPTempMem);
FGLContainerList.Free;
inherited;
end;
function TPlImagePlugin.GetGLContainer(ADC: HDC; ARC: HGLRC): TGLContainer;
var
i: Integer;
begin
Result := nil;
i := 0;
while (Result = nil) and (i < FGLContainerList.Count) do
begin
if (TGLContainer(FGLContainerList.Items[i]).DC = ADC) and
(TGLContainer(FGLContainerList.Items[i]).RC = ARC) then
Result := TGLContainer(FGLContainerList.Items[i]);
inc(i);
end;
end;
function TPlImagePlugin.GetMinFreeImageIndex: Integer;
var
i: Integer;
begin
Result := -1;
i := 0;
while (Result = -1) and (i < MAX_IMAGES_COUNT) do
begin
if FImages[i] = nil then
Result := i;
inc(i);
end;
end;
function TPlImagePlugin.GetOrCreateGLContainer(ADC: HDC;
ARC: HGLRC): TGLContainer;
begin
Result := GetGLContainer(ADC, ARC);
if Result = nil then
begin
Result := TGLContainer.Create(ADC, ARC);
FGLContainerList.Add(Result);
end;
end;
function TPlImagePlugin.IMImage_Duplicate(AImage: HIMAGE): HIMAGE;
var
index: Integer;
begin
Result := 0;
if (AImage - 1 >= 0) and
(AImage - 1 < MAX_IMAGES_COUNT) then
begin
index := GetMinFreeImageIndex;
if (index >= 0)then
begin
FImages[index] := TGraphicClass(FImages[AImage - 1].ClassType).Create;
FImages[index].Assign(FImages[AImage - 1]);
Result := index + 1;
end;
end;
end;
procedure TPlImagePlugin.IMImage_Free(AImage: HIMAGE);
begin
if (AImage - 1 >= 0) and
(AImage - 1 < MAX_IMAGES_COUNT) and
(FImages[AImage - 1] <> nil) then
begin
if (FImageForm.Image = FImages[AImage - 1]) then
FImageForm.Image := nil;
FImages[AImage - 1].Free;
FImages[AImage - 1] := nil;
end;
end;
procedure TPlImagePlugin.IMImage_FreeGLContext(ADC: HDC; ARC: HGLRC);
var
cont: TGLContainer;
begin
cont := GetGLContainer(ADC, ARC);
if cont <> nil then
FGLContainerList.Remove(cont);
end;
function TPlImagePlugin.IMImage_GetData(AImage: HIMAGE; var PData: Pointer;
var DataSize: Integer): HRESULT;
var
ms: TMemoryStream;
begin
Result := E_FAIL;
if (AImage - 1 >= 0) and
(AImage - 1 < MAX_IMAGES_COUNT) and
(FImages[AImage - 1] <> nil) then
begin
if (FPTempMem <> nil) then
FreeMem(FPTempMem);
ms := TMemoryStream.Create;
try
FImages[AImage - 1].SaveToStream(ms);
if (ms.Size > 0) then
begin
GetMem(FPTempMem, ms.Size);
ms.Position := 0;
if (ms.Read(FPTempMem^, ms.Size) = ms.Size) then
begin
PData := FPTempMem;
DataSize := ms.Size;
Result := S_OK;
end;
end;
finally
ms.Free;
end;
end;
end;
function TPlImagePlugin.IMImage_GetPreviewTex(AImage: HIMAGE; ADC: HDC;
ARC: HGLRC): GLuint;
var
cont: TGLContainer;
texture: TGLStimTexture;
begin
Result := 0;
if (AImage - 1 >= 0) and
(AImage - 1 < MAX_IMAGES_COUNT) and
(FImages[AImage - 1] <> nil) then
begin
cont := GetOrCreateGLContainer(ADC, ARC);
if cont <> nil then
begin
texture := cont.GetStimTexByImage(AImage);
if texture = nil then
texture := cont.AddNewTexture(AImage, FImages[AImage - 1]);
if texture <> nil then
Result := texture.TexName;
end;
end;
end;
function TPlImagePlugin.IMImage_Hide(AImage: HIMAGE): HRESULT;
begin
Result := S_OK;
if (FImageForm.ImageIndex = AImage - 1) then
begin
FImageForm.Image := nil;
FImageForm.ImageIndex := -1;
end;
// FImageForm.imgImage.Picture.Bitmap.Width := 0;
// FImageForm.imgImage.Picture.Bitmap.Height := 0;
// FImageForm.Invalidate;
end;
function TPlImagePlugin.IMImage_Load(PData: Pointer; DataSize: Integer): HIMAGE;
var
index: Integer;
ms: TMemoryStream;
p1, p2: PByte;
begin
Result := 0;
if DataSize > 1 then
begin
index := GetMinFreeImageIndex;
if (index >= 0) then
begin
//определяем формат изображения по первым 2-м байтам
p1 := pData;
p2 := p1;
inc(p2);
// для bmp это $42 $4D
// для jpg $ff $D8
// для png $89 $50
if (p1^ = $42) and (p2^ = $4D) then
FImages[index] := TBitmap.Create
else if (p1^ = $ff) and (p2^ = $D8) then
FImages[index] := TJPEGImage.Create
else if (p1^ = $89) and (p2^ = $50) then
FImages[index] := TPNGObject.Create;
ms := TMemoryStream.Create;
try
ms.WriteBuffer(PData^, DataSize);
ms.Position := 0;
FImages[index].LoadFromStream(ms);
if (FImages[index].Width > 0) and
(FImages[index].Height > 0) then
Result := index + 1
else
FImages[index].Free;
finally
ms.Free;
end;
end;
end;
end;
function TPlImagePlugin.IMImage_Show(AImage: HIMAGE): HRESULT;
begin
Result := E_FAIL;
if (AImage - 1 >= 0) and
(AImage - 1 < MAX_IMAGES_COUNT) and
(FImages[AImage - 1] <> nil) then
begin
// FImageForm.imgImage.Picture.Graphic := FImages[AImage - 1];
FImageForm.ImageIndex := AImage - 1;
FImageForm.Image := FImages[AImage - 1];
Result := S_OK;
end;
end;
function TPlImagePlugin.IMImage_ShowPreview(AImage: HIMAGE): HRESULT;
var
imf: TImageForm;
begin
Result := E_FAIL;
if (AImage - 1 >= 0) and
(AImage - 1 < MAX_IMAGES_COUNT) and
(FImages[AImage - 1] <> nil) then
begin
imf := TImageForm.Create(Application);
try
// imf.imgImage.Picture.Graphic := FImages[AImage - 1];
imf.BorderStyle := bsToolWindow;
imf.Image := FImages[AImage - 1];
imf.ShowModal;
finally
imf.Release;
end;
Result := S_OK;
end;
end;
function TPlImagePlugin.IMImage_WindowHide: HRESULT;
begin
Result := S_OK;
ShowWindow(FImageForm.Handle, SW_HIDE);
FImageForm.Hide;
end;
function TPlImagePlugin.IMImage_WindowShow(MonitorIndex: Integer;
WindowRect: TRect): HWND;
begin
Result := 0;
if (MonitorIndex >= 0) and
(MonitorIndex < Screen.MonitorCount) then
begin
if not FImageForm.Showing then
begin
ShowWindow(FImageForm.Handle, SW_SHOWNOACTIVATE);
// FImageForm.Show;
end;
OffsetRect(WindowRect, Screen.Monitors[MonitorIndex].Left, Screen.Monitors[MonitorIndex].Top);
FImageForm.BoundsRect := WindowRect;
Result := FImageForm.Handle;
end
else if FImageForm.Showing then
FImageForm.Hide;
end;
procedure TPlImagePlugin.Initialize;
begin
inherited;
FImageForm := TImageForm.Create(Application);
FGLContainerList := TObjectList.Create(True);
end;
procedure TPlImagePlugin.ReleaseAllImages;
var
i: Integer;
begin
i := 0;
while (i < MAX_IMAGES_COUNT) do
begin
if (FImages[i] <> nil) then
begin
if (FImageForm.Image = FImages[i]) then
FImageForm.Image := nil;
FImages[i].Free;
FImages[i] := nil;
end;
inc(i);
end;
end;
initialization
TComObjectFactory.Create(ComServer, TPlImagePlugin, Class_PlImagePlugin,
'PlImagePlugin', '', ciMultiInstance, tmApartment);
end.
|
unit U_POWER_LIST_ACTION;
interface
uses Classes, SysUtils, ADODB, U_PUB_DB_CONN, Forms, U_POWER_LIST_INFO;
type
TPowerListAction = class
private
FAdoquery : TADOQuery;
FMDB : TMDB_CONNECT;
public
constructor Create;
destructor Destroy; override;
{三相四线}
/// <summary>
/// 添加三相四线功率列表
/// </summary>
procedure AddFourPower(AFourInfo : TFourPower);
/// <summary>
/// 清空三相四线功率列表
/// </summary>
procedure ClearFoutPower;
{三相三线}
/// <summary>
/// 添加三相三线功率列表
/// </summary>
procedure AddThreePower(AThreeInfo : TThreePower);
/// <summary>
/// 清空三相三线功率列表
/// </summary>
procedure ClearThreePower;
/// <summary>
/// 获取错误列表
/// </summary>
procedure GetErrorList(AStdPower : TFourPower; slError : TStringList;
dAngle : Double); overload;
procedure GetErrorList(AStdPower : TThreePower; slError : TStringList;
dAngle : Double); overload;
end;
implementation
{ TPowerListAction }
procedure TPowerListAction.AddFourPower(AFourInfo: TFourPower);
const
C_SQL = 'insert into FourPower ( ErrorCode, ErrorCount, U1, U2, U3,' +
'I1, I2, I3, U1I1, U2I2, U3I3, U1U2, U1U3, U2U3 ) values (' +
':ErrorCode, %d, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f,' +
'%f )';
begin
if not Assigned(AFourInfo) then
Exit;
try
with AFourInfo, FadoQuery do
begin
SQL.Text := Format( C_SQL, [ Errorcount, U1, U2, U3, I1, I2, I3,U1i1, U2i2,
U3i3, U1u2, U1u3, U2u3 ] );
Parameters.ParamByName( 'ErrorCode' ).Value := Errorcode;
end;
FadoQuery.ExecSQL;
finally
end;
end;
procedure TPowerListAction.AddThreePower(AThreeInfo: TThreePower);
const
C_SQL = 'insert into ThreePower ( ErrorCode, ErrorCount, U12, U32,' + #13#10 +
'I1, I3, U12I1, U32I3, U12U32 ) values ( :ErrorCode, %d,' + #13#10 +
'%f, %f, %f, %f, %f, %f, %f )';
begin
if not Assigned(AThreeInfo) then
Exit;
try
with AThreeInfo, FadoQuery do
begin
SQL.Text := Format( C_SQL, [ Errorcount, U12, U32, I1, I3, U12i1, U32i3, U12u32 ] );
Parameters.ParamByName( 'ErrorCode' ).Value := Errorcode;
end;
FadoQuery.ExecSQL;
finally
end;
end;
procedure TPowerListAction.ClearFoutPower;
begin
FadoQuery.SQL.Text := 'delete from FourPower';
FadoQuery.ExecSQL;
end;
procedure TPowerListAction.ClearThreePower;
begin
FadoQuery.SQL.Text := 'delete from ThreePower';
FadoQuery.ExecSQL;
end;
constructor TPowerListAction.Create;
begin
FMDB := TMDB_CONNECT.Create(nil);
FMDB.FileName := ExtractFilePath( Application.ExeName ) + 'CKPowerList.mdb';
FAdoquery := FMDB.AdoQuery;
end;
destructor TPowerListAction.Destroy;
begin
FMDB.Free;
FAdoquery.Free;
inherited;
end;
procedure TPowerListAction.GetErrorList(AStdPower: TFourPower;
slError: TStringList; dAngle : Double);
const
C_SQL = 'select * from FourPower where U1=%f and U2 = %f and U3 = %f and '+
'I1=%f and I2 = %f and I3 = %f and U1I1 = %f and U2I2 = %f and '+
'U3I3 = %f and U1U2 = %f and U1U3 = %f and U2U3 = %f order by ErrorCount';
var
APower : TFourPower;
begin
if not (Assigned(AStdPower) and Assigned(slError)) then
Exit;
with FAdoquery, AStdPower do
begin
SQL.Text := Format(C_SQL, [U1, U2, U3, I1, I2, I3, U1I1, U2I2, U3I3, U1U2,
U1U3, U2U3]);
FAdoquery.Open;
while not FAdoquery.Eof do
begin
APower := TFourPower.Create;
APower.Errorcode := FAdoquery.FieldByName('ErrorCode').AsString;
APower.Errorcount := FAdoquery.FieldByName('Errorcount').AsInteger;
APower.U1 := FAdoquery.FieldByName('U1').AsFloat;
APower.U2 := FAdoquery.FieldByName('U2').AsFloat;
APower.U3 := FAdoquery.FieldByName('U3').AsFloat;
APower.I1 := FAdoquery.FieldByName('I1').AsFloat;
APower.I2 := FAdoquery.FieldByName('I2').AsFloat;
APower.I3 := FAdoquery.FieldByName('I3').AsFloat;
APower.U1i1 := FAdoquery.FieldByName('U1i1').AsFloat;
APower.U2i2 := FAdoquery.FieldByName('U2i2').AsFloat;
APower.U3i3 := FAdoquery.FieldByName('U3i3').AsFloat;
APower.U1u2 := FAdoquery.FieldByName('U1u2').AsFloat;
APower.U1u3 := FAdoquery.FieldByName('U1u3').AsFloat;
APower.U2u3 := FAdoquery.FieldByName('U2u3').AsFloat;
APower.Angle := dAngle;
slError.AddObject(FieldByName('ErrorCode').AsString, APower);
Next;
end;
FAdoquery.Close;
end;
end;
procedure TPowerListAction.GetErrorList(AStdPower: TThreePower;
slError: TStringList; dAngle : Double);
const
C_SQL = 'select * from ThreePower where U12=%f and U32 = %f and I1 = %f and '+
'I3=%f and U12i1 = %f and U32i3 = %f and U12u32 = %f order by ErrorCount';
var
APower : TThreePower;
begin
if not (Assigned(AStdPower) and Assigned(slError)) then
Exit;
with FAdoquery, AStdPower do
begin
SQL.Text := Format(C_SQL, [U12, U32, I1, I3, U12i1, U32i3, U12u32]);
FAdoquery.Open;
while not FAdoquery.Eof do
begin
APower := TThreePower.Create;
APower.Errorcode := FAdoquery.FieldByName('ErrorCode').AsString;
APower.Errorcount := FAdoquery.FieldByName('Errorcount').AsInteger;
APower.U12 := FAdoquery.FieldByName('U12').AsFloat;
APower.U32 := FAdoquery.FieldByName('U32').AsFloat;
APower.I1 := FAdoquery.FieldByName('I1').AsFloat;
APower.I3 := FAdoquery.FieldByName('I3').AsFloat;
APower.U12i1 := FAdoquery.FieldByName('U12i1').AsFloat;
APower.U32i3 := FAdoquery.FieldByName('U32i3').AsFloat;
APower.U12u32 := FAdoquery.FieldByName('U12u32').AsFloat;
APower.Angle := dAngle;
slError.AddObject(FieldByName('ErrorCode').AsString, APower);
Next;
end;
FAdoquery.Close;
end;
end;
end.
|
unit BuyOrder;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGridEh, ExtCtrls, StdCtrls, ComCtrls, ToolWin;
type
TBuyOrderForm = class(TForm)
Panel1: TPanel;
CloseButton: TButton;
DBGridEh1: TDBGridEh;
DBGridEh2: TDBGridEh;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
InsertButton: TToolButton;
EditButton: TToolButton;
DeleteButton: TToolButton;
ToolButton2: TToolButton;
Edit1: TEdit;
ToolButton3: TToolButton;
PayButton: TToolButton;
Splitter1: TSplitter;
ToolButton4: TToolButton;
RefreshButton: TToolButton;
procedure EnabledButtons;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CloseButtonClick(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure InsertButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure PayButtonClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DBGridEh1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumnEh; State: TGridDrawState);
procedure DBGridEh1TitleBtnClick(Sender: TObject; ACol: Integer;
Column: TColumnEh);
procedure DBGridEh2DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumnEh; State: TGridDrawState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
BuyOrderForm: TBuyOrderForm;
implementation
uses Main, StoreDM, BuyOrderItem, BuyStructure, PaymentOrder;
{$R *.dfm}
procedure TBuyOrderForm.EnabledButtons;
begin
// Если записей нету, то Деактивируем кнопки "Редактировать" и "Удалить",
// а если есть, Активируем.
if StoreDataModule.BuyOrderDataSet.IsEmpty then
begin
EditButton.Enabled := False;
EditButton.ShowHint := False;
DeleteButton.Enabled := False;
DeleteButton.ShowHint := False;
PayButton.Enabled := False;
PayButton.ShowHint := False;
end
else
begin
EditButton.Enabled := True;
EditButton.ShowHint := True;
DeleteButton.Enabled := True;
DeleteButton.ShowHint := True;
PayButton.Enabled := True;
PayButton.ShowHint := True;
end;
end;
procedure TBuyOrderForm.FormCreate(Sender: TObject);
begin
with StoreDataModule do
begin
BuyOrderDataSet.Open;
BuyStructureDataSet.Open;
end;
CloseButton.Left := Panel1.Width - CloseButton.Width - 10;
Caption := 'Приходные документы (' + TopDate + '-' + BottomDate + ')';
EnabledButtons;
end;
procedure TBuyOrderForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
CurOrderID := 0;
with StoreDataModule do
begin
BuyOrderDataSet.Close;
BuyOrderDataSet.SelectSQL.Strings[4] := '';
BuyOrderDataSet.SelectSQL.Strings[BuyOrderDataSet.SelectSQL.Count - 1] := 'ORDER BY "Date", "OrderID"';
BuyStructureDataSet.Close;
end;
// Удаление форму при ее закрытии
BuyOrderForm := nil;
Action := caFree;
end;
procedure TBuyOrderForm.CloseButtonClick(Sender: TObject);
begin
Close;
end;
procedure TBuyOrderForm.Edit1Change(Sender: TObject);
var
Find : String;
begin
Find := AnsiUpperCase(Edit1.Text);
with StoreDataModule.BuyOrderDataSet do
begin
Close;
SelectSQL.Strings[4] := 'AND (UPPER("CustomerName") CONTAINING ''' + Find + ''')';
Open;
end;
end;
procedure TBuyOrderForm.InsertButtonClick(Sender: TObject);
begin
StoreDataModule.BuyOrderDataSet.Append;
StoreDataModule.BuyOrderDataSet['FirmID'] := MainFirm;
StoreDataModule.BuyOrderDataSet['InDivisionID'] := MainDivision;
StoreDataModule.BuyOrderDataSet['Date'] := Now;
StoreDataModule.BuyOrderDataSet['PayDate'] := Now;
StoreDataModule.BuyOrderDataSet['PriceID'] := 1;
StoreDataModule.BuyOrderDataSet['ProperID'] := 0;
StoreDataModule.BuyOrderDataSet.Post;
EnabledButtons;
BuyOrderItemForm := TBuyOrderItemForm.Create(Self);
BuyOrderItemForm.ShowModal;
end;
procedure TBuyOrderForm.EditButtonClick(Sender: TObject);
begin
// StoreDataModule.BuyOrderDataSet.Edit;
BuyOrderItemForm := TBuyOrderItemForm.Create(Self);
BuyOrderItemForm.ShowModal;
end;
procedure TBuyOrderForm.DeleteButtonClick(Sender: TObject);
var
DeletedStr : String;
begin
with StoreDataModule do
try
DeletedStr := BuyOrderDataSet.FieldByName('OrderID').AsString;
if Application.MessageBox(PChar('Вы действительно хотите удалить запись "' +
DeletedStr + '"?'),
'Удаление записи',
mb_YesNo + mb_IconQuestion + mb_DefButton2) = idYes then
try
BuyOrderDataSet.Delete;
BuyOrderTransaction.Commit;
EnabledButtons;
except
Application.MessageBox(PChar('Запись "' + DeletedStr + '" удалять нельзя.'),
'Ошибка удаления', mb_IconStop);
end; {try except}
finally
if BuyOrderDataSet.Active = False then
BuyOrderDataSet.Open;
end; {try finally}
end;
procedure TBuyOrderForm.PayButtonClick(Sender: TObject);
begin
CurProperID := StoreDataModule.BuyOrderDataSet['ProperID'];
PaymentOrderForm := TPaymentOrderForm.Create(Self);
PaymentOrderForm.ShowModal;
CurOrderID := StoreDataModule.BuyOrderDataSet['OrderID'];
StoreDataModule.BuyOrderDataSet.Close;
StoreDataModule.BuyOrderDataSet.Open;
end;
procedure TBuyOrderForm.RefreshButtonClick(Sender: TObject);
begin
CurOrderID := StoreDataModule.BuyOrderDataSet['OrderID'];
StoreDataModule.BuyOrderDataSet.Close;
StoreDataModule.BuyOrderDataSet.Open;
Caption := 'Приходные документы (' + TopDate + '-' + BottomDate + ')';
end;
procedure TBuyOrderForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_F2 : InsertButton.Click;
VK_F3 : EditButton.Click;
VK_F8 : DeleteButton.Click;
VK_F4 : Edit1.SetFocus;
VK_F9 : PayButton.Click;
VK_F5 : RefreshButton.Click;
end;
end;
procedure TBuyOrderForm.DBGridEh1DrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumnEh;
State: TGridDrawState);
begin
//Выделяем КРАСНЫМ (СИНИМ) просроченную Оплату
with DBGridEh1.Canvas do
begin
if (StoreDataModule.BuyOrderDataSet['Debt'] > 0) and
not (gdFocused in State) then
begin
if (StoreDataModule.BuyOrderDataSet['PayDate'] < now) then
Font.Color := clRed
else
Font.Color := clBlue;
FillRect(Rect);
TextOut(Rect.Left, Rect.Top, Column.DisplayText);
end
else
DBGridEh1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
end;
procedure TBuyOrderForm.DBGridEh1TitleBtnClick(Sender: TObject;
ACol: Integer; Column: TColumnEh);
var
i: Integer;
begin
//Сортировка по клику на заголовке столбца
CurOrderID := StoreDataModule.BuyOrderDataSet['OrderID'];
if Column.Title.Font.Color = clRed then
with StoreDataModule.BuyOrderDataSet do
begin
SelectSQL.Strings[SelectSQL.Count - 1] := 'ORDER BY "OrderID"';
Close;
Open;
for i := 0 to DBGridEh1.Columns.Count - 1 do
begin
DBGridEh1.Columns.Items[i].Title.Font.Color := clWindowText;
end;
end
else
with StoreDataModule.BuyOrderDataSet do
begin
SelectSQL.Strings[SelectSQL.Count - 1] := 'ORDER BY "' + Column.FieldName + '", "OrderID"';
Close;
Open;
for i := 0 to DBGridEh1.Columns.Count - 1 do
begin
DBGridEh1.Columns.Items[i].Title.Font.Color := clWindowText;
end;
Column.Title.Font.Color := clRed;
end;
end;
procedure TBuyOrderForm.DBGridEh2DrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumnEh;
State: TGridDrawState);
var
ItemNo: String;
begin
//Проставляем номера по порядку в строках Документа
with DBGridEh2.Canvas do
begin
if StoreDataModule.BuyStructureDataSet.RecNo <> 0 then
ItemNo := IntToStr(StoreDataModule.BuyStructureDataSet.RecNo)
else
ItemNo := '';
if Column.Index = 0 then
begin
FillRect(Rect);
TextOut(Rect.Right - 3 - TextWidth(ItemNo), Rect.Top, ItemNo);
end
else
DBGridEh2.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Soap.WSDLLookup;
interface
function GetWSDLLookup: TInterfacedObject;
implementation
uses
System.Classes, System.Generics.Collections, System.SysUtils,
Soap.WSDLBind, Soap.WSDLItems;
type
TWSDLLookup = class(TInterfacedObject, IWSDLLookup)
private
FLookup: TDictionary<string, Variant>;
public
constructor Create;
destructor Destroy; override;
{ IWSDLLookup }
procedure BuildWSDLLookup(WSDLItems: IWSDLItems; IterateProc: TWSDLIterateProc); overload;
procedure BuildWSDLLookup(WSDLItems: IWSDLItems); overload;
procedure ClearWSDLLookup;
procedure Add(const URLLocation: string; WSDLItems: IWSDLItems);
procedure AddImport(const URLLocation, ImportURLLocation: string);
function Contains(const URLLocation: string): Boolean;
function GetWSDLItems(const URLLocation: string): IWSDLItems;
function GetWSDLImportList(const URLLocation: string): TList<string>;
function IsEmpty: Boolean;
end;
function GetWSDLLookup: TInterfacedObject;
begin
Result := TWSDLLookup.Create;
end;
{ TWSDLLookup }
constructor TWSDLLookup.Create;
begin
FLookup := TDictionary<string, Variant>.Create;
end;
destructor TWSDLLookup.Destroy;
begin
ClearWSDLLookup;
FLookup.Free;
inherited;
end;
procedure TWSDLLookup.Add(const URLLocation: string; WSDLItems: IWSDLItems);
begin
if not Contains(URLLocation) then
begin
FLookup.Add(URLLocation, WSDLItems);
end;
end;
procedure TWSDLLookup.AddImport(const URLLocation, ImportURLLocation: string);
begin
if not Contains(URLLocation) then
begin
FLookup.Add(URLLocation, ImportURLLocation);
end;
end;
procedure TWSDLLookup.BuildWSDLLookup(WSDLItems: IWSDLItems; IterateProc: TWSDLIterateProc);
function isHTTP(const Name: String): boolean;
const
sHTTPPrefix = 'http://';
sHTTPsPrefix= 'https://';
begin
Result := SameText(Copy(Name, 1, Length(sHTTPPrefix)), sHTTPPrefix) or
SameText(Copy(Name, 1, Length(sHTTPsPrefix)),sHTTPsPrefix);
end;
function GetFullPath(const Path: string): string;
begin
Result := Path;
if IsHTTP(Path) then
Exit;
if FileExists(Path) then
begin
Result := ExpandFileName(Path);
if Result = '' then
Result := Path;
end;
end;
{ Returns path of SchemaLoc relative to its Referer }
function GetRelativePath(const Referer, SchemaLoc: String): String;
const
sPathSep: WideChar = '/';
var
HTTPRef: Boolean;
Path: String;
Len: Integer;
begin
if IsHTTP(SchemaLoc) then
begin
Result := SchemaLoc;
Exit;
end;
HTTPRef := IsHTTP(Referer);
if (HTTPRef) then
begin
Len := High(Referer);
while (Len >= Low(string)) do
begin
if (Referer[Len] = sPathSep) then
begin
Path := Copy(Referer, 0, Len+1-Low(string));
Result := Path + SchemaLoc;
Exit;
end;
Dec(Len);
end;
end;
if FileExists(SchemaLoc) then
begin
Result := SchemaLoc;
Path := ExpandFileName(SchemaLoc);
if Path <> '' then
Result := Path;
Exit;
end;
Path := ExtractFilePath(SchemaLoc);
if Path = '' then
begin
Path := ExtractFilePath(Referer);
if Path <> '' then
begin
Result := ExpandFileName(Path + SchemaLoc);
Exit;
end;
end;
Result := SchemaLoc;
end;
var
Index: Integer;
Imports: IImports;
ImportWSDLItems: IWSDLItems;
WSDLItemsObj: TWSDLItems;
MyLoc, ImportLoc: string;
Stream: TMemoryStream;
begin
{ Add myself to the list }
WSDLItemsObj := WSDLItems.GetWSDLItems;
MyLoc := GetFullPath(WSDLItemsObj.FileName);
if not Assigned(IterateProc) then
begin
if not Contains(MyLoc) then
Add(MyLoc, WSDLItemsObj);
end;
{ Get my imports }
Imports := WSDLItemsObj.Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportLoc := GetRelativePath(MyLoc, Imports[Index].Location);
if Assigned(IterateProc) then
IterateProc(ioBeforeLoad, nil, nil, ImportLoc);
if not Contains(ImportLoc) then
begin
Stream := TMemoryStream.Create;
try
WSDLItems.GetWSDLItems.StreamLoader.Load(ImportLoc, Stream);
ImportWSDLItems := TWSDLItems.Create(WSDLItemsObj, nil);
ImportWSDLItems.GetWSDLItems.LoadFromStream(Stream);
if HasDefinition(ImportWSDLItems) then
begin
ImportWSDLItems.GetWSDLItems.FileName := ImportLoc;
Add(ImportLoc, ImportWSDLItems);
BuildWSDLLookup(ImportWSDLItems.GetWSDLItems);
end
else
begin
// Here we probably have a Schema imported directly
// by a WSDL document, unusual and not WS-I compliant but happens!
AddImport(ImportLoc, MyLoc);
end;
finally
Stream.Free;
end;
end;
end;
end;
end;
procedure TWSDLLookup.BuildWSDLLookup(WSDLItems: IWSDLItems);
begin
BuildWSDLLookup(WSDLItems, TWSDLIterateProc(nil));
end;
procedure TWSDLLookup.ClearWSDLLookup;
begin
FLookup.Clear;
end;
function TWSDLLookup.Contains(const URLLocation: string): Boolean;
begin
Result := FLookup.ContainsKey(URLLocation);
end;
function TWSDLLookup.GetWSDLImportList(const URLLocation: string): TList<string>;
var
AKey: string;
begin
Result := TList<string>.Create;
for AKey in FLookup.Keys do
begin
if (URLLocation = '') or (GetWSDLItems(AKey) <> nil) then
Result.Add(AKey);
end;
end;
function TWSDLLookup.GetWSDLItems(const URLLocation: string): IWSDLItems;
var
V: Variant;
begin
Result := nil;
if Contains(URLLocation) then
begin
V := FLookup[URLLocation];
if (TVarData(V).VType = varUnknown) then
Result := IUnknown(TVarData(V).VUnknown) as IWSDLItems;
end;
end;
function TWSDLLookup.IsEmpty: Boolean;
begin
Result := FLookup.Count = 0;
end;
end.
|
{
23/06/08:
Desfiz alteração de inserir nos arrays a informação de tamanho
(registrada em 12/05/06); há um bug que o diagrama da memória
não mostra corretamente parâmetros var de tipo arranjo; ainda
não sei a solução; o problema ocorre tanto com arranjos de
uma dimensão como de múltiplas dimensões.
05/06/08:
Implementei o procedimento novaJanela, que cria um novo form
que pode então também ser usado como saída gráfica. Dentre as
últimas alterações, está também a variável global Tela, que
representa a paint box da tela principal do sw-tutor. Todas
as rotinas de saída gráfica passaram a usar então, como primeiro
argumento, a Tela ou então uma novaJanela.
10/01/08:
Comecei uma série de alterações no nome das funções e
principalmente na forma de escrever na tela, pois implementei
um "double-buffer" de modo a facilitar o tratamento do evento
"OnPaint". Agora os desenhos não mais desaparecem da tela, nem
durante nem após a execução dos programas. Isto também foi uma
observação feita pelo pessoal do CEFET.
16/08/07:
Criei as funções txtParaReal e realParaTxt.
A necessidade surgiu a partir de um exercício que a turma
do CEFET está fazendo, dentro da experiência conduzida
pelo prof. Dácio Guimarães.
12/05/06:
Há uns dias, fiz a implementação de inserir nos arrays a
informação de tamanho. Quando um array é alocado, no início
da área de memória que ele ocupa há agora um valor inteiro
(tipo Integer) que contém o tamanho do array, ou seja, o
número de elementos. A idéia é abrir caminho para a implementação
de parâmetros tipo "arranjo de T" e, na implementação da rotina,
a função tamanho(x) retorna esse número de elementos.
16/03/06:
Criei a função mat_potência(base, expoente).
21/02/06:
Na criação de um quadro (frame), incluí o comando
Bmp.Canvas.Brush.Color := clBtnFace; // ATENÇÃO - Mesma cor da propriedade
// Color do componente PaintBox
de modo que um quadro começa com um fundo semelhante ao da
saída gráfica do \dsl.
14/02/06:
Incluí janela de configuração das opções do ambiente; por
enquanto, a única configuração é a lista de diretórios onde
os módulos devem ser procurados, no processamento do comando
'inclui'; Implementei também a respectiva alteração no
comando 'inclui', de modo a pesquisar o módulo na lista de
diretórios que pode estar configurada. Nesta implementação
foram criados os módulos port_UFrmConfig.pas e port_UFrmPasta.
30/07/05:
ATENÇÃO - Fiz um bocado de alterações sem registrar nesses
comentários.
Criei gra_estiqueQuadro e gra_quadroEstiqueQuadro.
03/07/05:
Corrigi um problema no comando "caso". As constantes em
TProd_MemberGroup não estavam sendo interpretadas durante
a compilação e isto dava um erro na verificação de se o
caso era repetido.
11/05/05:
Alterei a avaliação de expressões lógicas, de modo a implementar
o "curto-circuito", para os dois operadores, && e ||. Antes dessa
alteração as expressões lógicas estavam sendo sempre avaliadas de
forma completa, sem o "curto-circuito".
24/04/05:
Corrigi bug TProduction.GetNewIdentifierList: identificadores iguais
numa mesma lista estavam sendo permitidos.
Corrigi pequeno bug em TProd_Procedure e TProd_Function: quando o nome
da rotina estava sendo redeclarado, a mensagem de erro estava com
informações erradas de nome, linha e coluna (estava pegando as do próximo
token).
28/11/04:
Acrescentei testes que verificam se a classe do argumento
correspondente a parâmetro "var" é válida.
Acrescentei testes que verificam a classe do argumento usado
em "inc" e "dec".
Acrescentei nova rotina do ambiente: evnt_mouseXY.
20/11/04:
Alterei gra_mouseX e gra_mouseY para evnt_mouseX e evnt_mouseY,
respectivamente.
22/09/04:
Retirei a palavra "então" da sintaxe do comando "se".
Retirei a palavra "faça" da sintaxe dos comandos "enquanto" e "para".
Considerei ";" (ponto e vírgula) como um "comando" (Stmt):
o caractere ";" foi incluído no Set_FirstStmt.
19/09/04:
Implementei diferenciação entre maiúsculas e minúsculas.
Pac-br passa a ser case-sensitive.
18/09/04:
Alterei port_PasTokens de modo aos comentários serem entre /* e */.
Incluí 'ponteiro' como palavra reservada. Declaração de ponteiro
passa a ser: ponteiro para T, ao invés de ^T.
Criei novo comando for (ForStmt_2), com sintaxe semelhante a C.
Fiz parênteses serem obrigatórios nos comandos se, enquanto e
no teste até do comando repita.
15/09/04:
Voltei a usar o RichEdit ao invés do russo EdtPainter. Fico sem syntax
highlight, mas sem bugs estranhos também.
Alterei o port_PasTokens de modo a que os strings e caracteres fiquem
delimitados por aspas duplas, ao invés das aspas simples (apóstrofos).
Alterei também os exemplos, por causa disso.
Alterei os strings das funções e procedimentos padrões, substituindo
"dsl_" pelos prefixos "gra_", "mat_" e "evnt_". Alterei também os exemplos.
13/05/04:
Alterei TProd_AssignStmt.Parse retirando o tratamento de atribuição
ao nome da função (como no Pascal padrão). Agora, TProd_VarReference
está sendo sempre "parsed". Para permitir o uso de uma função como uma
referência opcionalmente qualificada (ou seja, seguida de . ou de ^),
TProd_AssignStmt passou a ter o assinalamento opcional. Ficou mais
simples fazer dessa forma, ao invés de alterar diretamente
TProd_FunctionCall para incluir a qualificação opcional.
Incluí um teste que, durante a interpretação, verifica se o comando
RETORNE foi executado durante a execução de uma função.
12/02/04:
Alterei a palavra reservada 'inclui' para 'inclua'. (Mexi no port_PasTokens
e no componente EdtPainter).
Acrescentei propriedade StandardModule na classe TSymbolInfo; alterei a
forma de pesquisar por um símbolo na tabela de símbolos (TSymbolTable.Enter):
passei a considerar que um símbolo só é encontrado se houve a prévia
inclusão do respectivo módulo padrão.
11/02/04:
Alterei o esquema do comando 'inclui': alguns módulos padrões são
identificados de um modo especial: 'gra*', 'mat*', 'arq*' e 'evnt*'.
Alterei os exemplos de modo a seguir o esquema de 'inclui'.
24/12/03:
Alterei o código das teclas especiais: passei a usar valores pouco usados
da parte inicial da tabela ASCII.
18/10/03:
Incluí a rotina dsl_quadroCopieDeQuadro.
12/10/03:
Alterei "EV_CLIC" para "EV_CLIQUE".
11/10/03:
Corrigi um bug no evento EV_CLIC: ele não estava
atualizando a posição do mouse.
17/07/03:
Criei a rotina dsl_durma(milisegundos).
12/07/03:
Criei as rotinas dsl_mudeIntervaloEventoTempo e
dsl_intervaloEventoTempo.
11/07/03:
Criei o evento EV_TAMANHO_TELA, que ocorre com o OnResize do
painel que serve de base para a saída gráfica do DSL.
Criei as rotinas dsl_larguraDaTela e dsl_alturaDaTela.
10/07/03:
Alterei um pouco o esquema de eventos: passei o registro da
posição de mouse para dentro do tratamento do evento (ou seja,
o registro só ocorre se o programa estiver esperando pelo
respectivo evento.
Alterei também um "mais um" ou "menos um" relacionado com a
cópia de quadro da tela ou para tela (o tom de dúvida é porque
estou escrevendo no dia seguinte).
Estas duas alterações combinadas resolveram um problema que
havia no programa "PASTORALEMAO.PAS", que sempre deixava um
"rastro" visível. O rastro foi totalmente eliminado.
20/04/03:
No preenchimento inicial da tabela de símbolos, acrescentei
identificadores de tipo cuja grafia com acento/til estava
faltando: "lógico", "simOuNão", "não".
18/05/03:
Criei a rotina VerifyDebug. Ela está sendo chamada no final
da interpretação de chamada de procedimento e de função.
O objetivo é fazer com que na execução passo a passo, o
término da execução de uma rotina sempre passe pelo 'fim'
do bloco da rotina. Esta rotina faz o que, até hoje, era
feito exclusivamente na interpretação de TProd_Stmt.
Alterei TProd_Stmt.Interpret, que passou a chamar a nova
rotina, VerifyDebug.
Em TProduction, criei as propriedades ProductionEndLine e
ProductionEndCol, para facilitar a implementação descrita acima.
20/05/03:
Passei a tratar o evento OnCustomOwnerDraw da listview que
exibe o diagrama da memória, de modo a desenhar um pequeno
bitmap quando o item corresponder a uma ativação de rotina.
21/05/03:
Tentei usar a função GlobalMemoryStatus (no método CheckMemory
de TProduction), mas não funcionou. Meu objetivo é detectar
um loop recursivo (por exemplo) que esteja consumindo muita
memória e interromper antes do crash. Mas, na forma como fiz,
não deu certo. Se eu ativo um
procedimento p; inicio p; fim;
aparece, depois de um tempo, a mensagem Stack overflow.
Comentei, então, CheckMemory e os pontos em que era chamado.
28/06/03:
Alterei TProd_VarReference.Parse, incluindo no início um teste
que confirma se o símbolo foi efetivamente declarado. Esta função
é chamada de diferentes pontos, alguns testando isto antes de
chamar a função, porém outros estão chamando sem fazer o teste.
}
unit port_PascalInterpreter;
{$POINTERMATH ON}
interface
uses
Graphics, SysUtils, Classes, extctrls, port_PasTokens;
const
MEM_ITENS_MAX = 10000; // máximo de itens do diagrama da memória
MEM_MEMO_SAIDA_MAX = 20000; // máximo de caracteres na saída padrão
MAX_RANGE = 10000; // máximo de elementos num arranjo
MAX_JANELAS = 10; // máximo de janelas (forms)
MAX_COMPONENTES = 500; // máximo de componentes
MAX_MPLAYERS = 40; // máximo de media players
MAX_TAM_JANELA = 1024; // tamanho máximo para o bitmap da janela
MAX_TAM_ARQ = 1024 * 1024 * 10; // tamanho máximo dos arquivos
{ Tipos de Eventos }
EV_MOUSE_CLICK = 1; { $00000001 }
EV_MOUSE_MOVE = 2; { $00000002 }
EV_MOUSE_UP = 4; { $00000004 }
EV_MOUSE_DOWN = 8; { $00000008 }
EV_KEYBOARD = 16; { $00000010 }
EV_TIME = 32; { $00000020 }
EV_RESIZE = 64; { $00000040 }
{ Estados do mouse }
EV_DIR = 1;
EV_ESQ = 2;
{ Estados do teclado }
EV_SHIFT = 1;
EV_ALT = 2;
EV_CTRL = 4;
{ Teclas especiais - vou usar códigos ASCII "pouco usados"; provavelmente,
terei problemas no futuro; estou fazendo isso para permitir que o tratamento
das teclas especiais seja igual ao das teclas normais }
TECLA_INS = Chr(1);
TECLA_DEL = Chr(2);
TECLA_HOME = Chr(3);
TECLA_END = Chr(4);
TECLA_ESQUERDA = Chr(5);
TECLA_CIMA = Chr(6);
TECLA_DIREITA = Chr(11);
TECLA_BAIXO = Chr(12);
TECLA_PGUP = Chr(14);
TECLA_PGDN = Chr(15);
TECLA_F1 = Chr(16);
TECLA_F2 = Chr(17);
TECLA_F3 = Chr(18);
TECLA_F4 = Chr(19);
TECLA_F5 = Chr(20);
TECLA_F6 = Chr(21);
TECLA_F7 = Chr(22);
TECLA_F8 = Chr(23);
TECLA_F9 = Chr(24);
TECLA_F10 = Chr(25);
TECLA_F11 = Chr(28);
TECLA_F12 = Chr(29);
{ estilos fonte }
EF_NEGRITO = 1;
EF_ITALICO = 2;
EF_SUBLINHADO = 4;
EF_RISCADO = 8;
RESULT_NAME = 'result_2345632175694123546'; // um nome estranho
type
{ Events }
TWriteEvent = procedure (Sender: TObject; S: String) of object;
TReadIntegerEvent = procedure (Sender: TObject; var Value: Integer) of object;
TReadRealEvent = procedure (Sender: TObject; var Value: Extended) of object;
TReadStringEvent = procedure (Sender: TObject; var Value: String) of object;
TReadCharEvent = procedure (Sender: TObject; var Value: Char) of object;
TDebugEvent = procedure (Sender: TObject; Lin, Col: Integer;
Parser: TPascalTokenizer) of object;
TWaitForEvent = procedure (Sender: TObject; Events: Integer) of object;
{ TPascalInterpreter }
TPascalInterpreter = class(TComponent)
private
C: Pointer; // TCompiler
FGraphicImage: TImage;
FCanvas: TCanvas;
FFloatFormat: String;
FOnReadChar: TReadCharEvent;
FOnReadInteger: TReadIntegerEvent;
FOnReadReal: TReadRealEvent;
FOnReadString: TReadStringEvent;
FOnWrite: TWriteEvent;
FOnDebug: TDebugEvent;
FOnWaitFor: TWaitForEvent;
FBreakpointLine: Integer;
FBreakpointFileName: String;
FBreakOnNextStmt: Boolean;
FProgramFile: String;
procedure SetFloatFormat(const Value: String);
procedure SetGraphicImage(const Value: TImage);
procedure SetCanvas(const Value: TCanvas);
procedure SetOnDebug(const Value: TDebugEvent);
procedure SetOnReadChar(const Value: TReadCharEvent);
procedure SetOnReadInteger(const Value: TReadIntegerEvent);
procedure SetOnReadReal(const Value: TReadRealEvent);
procedure SetOnReadString(const Value: TReadStringEvent);
procedure SetOnWrite(const Value: TWriteEvent);
procedure SetOnWaitFor(const Value: TWaitForEvent);
procedure SetProgramFile(const Value: String);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Run(Source: TStrings; ProgramFileName: String);
function Evaluate(Expression: String): String;
procedure Stop;
procedure SetBreakpoint(FileName: String; LineNumber: Integer);
procedure BreakOnNextStatement;
procedure RegisterMouseXY(X, Y: Integer);
procedure RegisterLastEvent(Event: Integer; Sender: TObject);
procedure RegisterShiftState(Shift: TShiftState);
procedure RegisterKeyPressed(Key: Char);
procedure RegisterKeyDown(Key: Word);
procedure RegisterKeyUp(Key: Word);
procedure TrataOnPaint(Sender: TObject);
published
property FloatFormat: String read FFloatFormat write SetFloatFormat;
property GraphicImage: TImage read FGraphicImage
write SetGraphicImage;
property Canvas: TCanvas read FCanvas
write SetCanvas;
// events
property OnWrite: TWriteEvent read FOnWrite
write SetOnWrite;
property OnReadChar: TReadCharEvent read FOnReadChar
write SetOnReadChar;
property OnReadInteger: TReadIntegerEvent read FOnReadInteger
write SetOnReadInteger;
property OnReadString: TReadStringEvent read FOnReadString
write SetOnReadString;
property OnReadReal: TReadRealEvent read FOnReadReal
write SetOnReadReal;
property OnDebug: TDebugEvent read FOnDebug
write SetOnDebug;
property OnWaitFor: TWaitForEvent read FOnWaitFor
write SetOnWaitFor;
property ProgramFile: String read FProgramFile
write SetProgramFile;
end;
{ TSymbolClass }
TSymbolClass = (scConst, scType, scVar, scField, scPointer, scProcedure,
scFunction, scVarParam);
resourcestring
// Memory error and run-time errors
sOutOfMemory = 'Memória insuficiente (OutOfMemory)';
sHeapError = 'Memória insuficiente: erro na heap';
sIndexOutOfRange = 'Indice inválido';
sAssignmentOutOfRange = 'Atribuição inválida';
sEvaluationError = 'Avaliação requer interpretação prévia';
sFileNotFound = 'Arquivo ''%s'' não encontrado';
sOutOfMemory80 = 'Execução interrompida devido ao excessivo consumo de memória';
// Lexical errors
sStringIncomplete = 'Texto incompleto';
sUnexpectedEndOfSourceInComment = 'Fim de arquivo inesperado em um comentário';
sPushBackError = 'Erro interno em PushBack';
sInvalidRealNumber = 'Número real inválido';
sInvalidIntNumber = 'Número inteiro inválido';
sInvalidHexNumber = 'Número hexadecimal inválido';
sInvalidControlString = 'Texto de controle inválido';
// Syntax errors
sValueNotAllowed = 'Valor não permitido';
sIdentifierExpected = 'Identificador esperado';
sTerminalExpected = '''%s'' esperado';
sFileNameExpected = 'Nome de arquivo esperado';
// sIntegerNumberExpected = 'Integer number expected';
sIdentifierRedeclared = 'Identificador já declarado: ''%s''';
sUndeclaredIdentifier = 'Identificador não declarado: ''%s''';
// sIdentifierNotConst = '''%s'' is not a constant';
sConstExpected = 'Constante esperada';
sExpressionExpected = 'Expressão esperada';
sStmtExpected = 'Comando esperado';
sIncompatibleTypes = 'Tipos incompatíveis';
sInvalidOperation = 'Operação inválida';
sExecutionError = 'Erro de execução';
sBoolExprExpected = 'Expressão lógica esperada';
sIntExprExpected = 'Expressão inteira esperada';
sRealVarExpected = 'Variável de tipo real esperada';
sStringExprExpected = 'Expressão do tipo texto esperada';
sToOrDownToExpected = 'A ou DECR esperado';
sUserBreak = 'Interrompido pelo usuário';
// sSetSymbolValueError = 'Internal error in SetSymbolValue';
// sSetAddressError = 'Internal error in SetAddress';
sVarIdentExpected = 'Identificador de variável esperado';
sTypeIdentExpected = 'Identificador de tipo esperado';
sTypeExpected = 'Tipo esperado';
sLowGTHigh = 'Limite inferior é maior que o limite superior';
sIndiceInvalido = 'Tamanho especificado para o arranjo não é válido';
sOrdinalTypeRequired = 'Tipo ordinal requerido';
sSetsMayHave256 = 'Conjuntos podem ter até 256 elementos';
sInvalidSetConstructor = 'Construtor de conjunto inválido';
sInvalidIndexType = 'Tipo de índice inválido';
sArrayTypeRequired = 'Tipo arranjo requerido';
sRecordTypeRequired = 'Tipo registro requerido';
sPointerTypeRequired = 'Tipo apontador requerido';
sCheckPendentPointersError = 'Erro interno em CheckPendentPointers';
sOperatorNotApplicable = 'Operador não aplicável a esse tipo de operando';
sPromoteTo = 'Erro interno em PromoteTo';
// sUnsatisfiedForward = 'Unsatisfied forward declaration';
sDeclDiffers = 'Declaração de ''%s'' difere da declaração prévia';
sNotEnoughActuals = 'Número insuficiente de argumentos';
sWrongActual = 'Tipos dos argumentos e parâmetros var têm de ser idênticos';
sWrongActual2 = 'Argumento não pode ser usado, pois o respectivo parâmetro está declarado como "var"';
sTooManyActuals = 'Excesso de argumentos';
sGetAddress = 'Erro interno em GetAddress';
sSolveWith = 'Erro intero em SolveWithStmt';
// sUnsolveVarParam = 'Internal error in UnsolveVarParam';
sLeftSide = 'Lado esquerdo não pode ser atribuído';
sDuplicateCase = 'Caso duplicado';
sBreakOutsideLoop = 'QUEBRE fora de um comando repetitivo';
sContinueOutsideLoop = 'CONTINUE fora de um comando repetitivo';
sExitOutsideSubroutine = 'RETORNE fora de um bloco de sub-rotina';
sSubroutineLevel = 'Esta versão não permite declaração de PROCEDIMENTO ou FUNÇÃO dentro de outra sub-rotina';
sInvalidInteger = 'não é um número inteiro válido';
sInvalidFloat = 'não é um número real válido';
sFalhaInternaUltimoEvento = 'Falha interna no mecanismo de substituição de eventos';
sFalhaArqTemp = 'Falha ao criar arquivo temporário';
sFalhaToqSom = 'Falha ao tentar tocar o som especificado. Verifique por favor se o nome do som está correto';
sFalhaToqSomExec = 'Falha ao tentar tocar o som especificado. Verifique por favor se o som especificado está correto';
sCharTypeExpected = 'Expressão de tipo caractere esperada';
sFrameTypeExpected = 'Expressão de tipo janela esperada';
sFileTypeExpected = 'Expressão de tipo dsl_TipoArquivo esperada';
sReaderTypeExpected = 'Expressão de tipo dsl_TipoLeitor esperada';
sWriterTypeExpected = 'Expressão de tipo dsl_TipoEscritor esperada';
sBadFileMode = 'Modo inválido especificado para um dsl_TipoArquivo';
sFileNewFailed = 'Falha na execução de novoArquivo';
sReaderHasCharFailed = 'Falha na execução de dsl_leitorTemCaractere';
sReaderNextCharFailed = 'Falha na execução de dsl_leitorProximoCaractere';
sWriterWriteCharFailed = 'Falha na execução de dsl_escritorEscrevaCaractere';
sNoReturnExecutedInFunction = 'Função retornou sem executar o comando RETORNE';
sDiagramaDaMemoriaCheio = 'Foi atingido o limite máximo de itens exibidos';
sLimiteJanelasAtingido = 'Foi atingido o limite máximo de janelas que podem ser criadas';
sLimiteComponentesAtingido = 'Foi atingido o limite máximo de componentes que podem ser criados';
sLimiteMediaPlayersAtingido = 'Foi atingido o limite máximo de sons que podem ser criados';
sMemoSaidaMax = 'Foi atingido o limite máximo de caracteres na saída padrão';
sInvalidRange = 'Foi atingido o limite máximo permitido para o número de elementos num arranjo';
sComponentTypeExpected = 'Expressão de tipo Componente esperada';
sImagem = 'Imagem';
sNaoEncontrada = 'não encontrada';
sTamanhoJanelaMax = 'Tamanho inválido para as dimensões da janela';
sArquivoNaoEncontrado = 'Erro ao tentar ler o arquivo';
sVerifiqueNomeArq = 'Verifique por favor se o nome do arquivo está correto';
sTamanhoArqInvalido = 'O tamanho do arquivo especificado é superior ao limite máximo permitido';
sTamanhoTxtInvalido = 'O tamanho do texto especificado é superior ao limite máximo permitido';
sErroGravandoArq = 'Houve uma falha ao tentar gravar o arquivo';
// some standard procedures
sRectangleProc = 'dsn_ret';
sRectangleProc2 = 'dsn_ret';
sTriangleProc = 'dsn_tri';
sTriangleProc2 = 'dsn_tri';
sEllipseProc = 'dsn_cir';
sLineToProc = 'dsn_lin';
sTextOutProc = 'dsn_txt';
sAltPixel = 'alt_pixel';
sMoveToProc = 'alt_pos_caneta';
sSetPenColorProc = 'alt_cor_caneta';
sSetPenWidthProc = 'alt_tam_caneta';
sSetBrushColorProc = 'alt_cor_pincel';
sSetBrushStyleProc = 'alt_estilo_pincel';
sSetFontColorProc = 'alt_cor_fonte';
sSetFontSizeProc = 'alt_tam_fonte';
sSetFontNameProc = 'alt_nome_fonte';
sSetFontStyleProc = 'alt_estilo_fonte';
sTextWidth = 'obtLarguraTxt';
sTextHeight = 'obtAlturaTxt';
sWaitForProc = 'espere_por';
sBreakProc = 'quebre';
sContinueProc = 'continue';
sExitProc = 'saia';
sTerminateProc = 'termine';
sCopyFrameProc = 'dsnQuadro';
sFrameReadFromFileProc = 'leiaQuadroDeArq';
sFrameDisposeProc = 'libQuadro';
sFrameCopyFromScreenProc = 'copQuadroDaTela';
sFrameCopyFromFrameProc = 'copQuadroDeQuadro';
sFrameSetWidth = 'altDimQuadrogra_quadroMudeLargura';
sFrameSetHeight = 'gra_quadroMudeAltura';
sFrameRectangle = 'gra_quadroDesenheRetangulo';
sFrameRectangle2 = 'gra_quadroDesenheRetângulo';
sFrameEllipse = 'gra_quadroDesenheElipse';
sFrameTriangle = 'gra_quadroDesenheTriangulo';
sFrameTriangle2 = 'gra_quadroDesenheTriângulo';
sFrameLineTo = 'gra_quadroDesenheLinha';
sFrameMoveTo = 'gra_quadroMudeXY';
sFramePenPosX = 'gra_quadroX';
sFramePenPosY = 'gra_quadroY';
sFrameTextOut = 'gra_quadroDesenheTexto';
sFrameSetBrushColor = 'gra_quadroMudeCorDoPincel';
sFrameBrushColor = 'gra_quadroCorDoPincel';
sFrameSetPenColor = 'gra_quadroMudeCorDaCaneta';
sFramePenColor = 'gra_quadroCorDaCaneta';
sFrameSetPenWidth = 'gra_quadroMudeLarguraDaCaneta';
sFramePenWidth = 'gra_quadroLarguraDaCaneta';
sFrameSetFontColor = 'gra_quadroMudeCorDaFonte';
sFrameFontColor = 'gra_quadroCorDaFonte';
sFrameSetFontSize = 'gra_quadroMudeTamanhoDaFonte';
sFrameFontSize = 'gra_quadroTamanhoDaFonte';
sFrameSetFontName = 'gra_quadroMudeNomeDaFonte';
sFrameFontName = 'gra_quadroNomeDaFonte';
sFrameSetBrushStyle = 'gra_quadroMudeEstiloDoPincel';
sFrameBrushStyle = 'gra_quadroEstiloDoPincel';
sSetCopyMode = 'gra_mudeModoDeCopiar';
sCopyMode = 'gra_modoDeCopiar';
sFrameSetCopyMode = 'gra_quadroMudeModoDeCopiar';
sFrameCopyMode = 'gra_quadroModoDeCopiar';
sFrameTextWidth = 'gra_quadroLarguraDoTexto';
sFrameTextHeight = 'gra_quadroAlturaDoTexto';
sArc = 'dsn_arco';
sFrameArc = 'dsn_arco';
sChord = 'dsn_corte';
sFrameChord = 'dsn_corte'; // ok
sPie = 'dsn_fatia';
sFramePie = 'dsn_fatia'; // ok
sBezier = 'dsn_bezier';
sFrameBezier = 'dsn_bezier'; // ok
sNow = 'agora';
sFileExists = 'existe_arq';
sFileNew = 'novo_arq';
sFileDispose = 'lib_arq';
sFileReader = 'arqLeitor';
sFileWriter = 'arqEscritor';
sFileNameComplete = 'arqNomeCompleto';
sReaderHasChar = 'temCrt';
sReaderNextChar = 'leitorProximoCaractere';
sReaderNextChar2 = 'arq_leitorPróximoCaractere';
sWriterWriteChar = 'arq_escritorEscrevaCaractere';
sInc = 'inc';
sDec = 'dec';
sStretch = 'gra_estiqueQuadro';
sFrameStretch = 'gra_quadroEstiqueQuadro';
sFillRect = 'dsn_ret_cheio';
sDsnLinSel = 'dsn_lin_sel';
sDsnRetSel = 'dsn_ret_sel';
// some standard functions
sGetPenPosXFunc = 'obt_caneta_x';
sGetPenPosYFunc = 'obt_caneta_y';
sSqrtFunc = 'raiz';
sLengthFunc = 'tamanho';
sUpperCaseFunc = 'maiúscula';
sUpperCaseFunc2 = 'maiúscula';
sLowerCaseFunc = 'minúscula';
sLowerCaseFunc2 = 'minúscula';
sRoundFunc = 'arredonde';
sSinFunc = 'sen';
sCosFunc = 'cos';
sRandomFunc = 'random';
sPotencia = 'potência';
sOrdFunc = 'crt_para_int';
sChrFunc = 'int_para_crt';
sIntToStrFunc = 'int_para_txt';
sStrToIntFunc = 'txt_para_int';
sCaracterEmFunc = 'caractere_em';
sMouseXFunc = 'mouse_x';
sMouseYFunc = 'mouse_y';
sMouseXY = 'mouse_xy';
sLastEventFunc = 'último_evento';
sLastEventFunc2 = 'último_evento';
sObtPixel = 'obt_pixel';
sBrushColorFunc = 'obt_cor_pincel';
sBrushStyleFunc = 'obt_estilo_pincel';
sPenColorFunc = 'obt_cor_caneta';
sPenWidthFunc = 'obt_tam_caneta';
sFontColorFunc = 'obt_cor_fonte';
sFontSizeFunc = 'obt_tam_fonte';
sFontNameFunc = 'gra_nomeDaFonte';
sBackgroundColorFunc = 'cor_do_fundo';
sKeyPressedFunc = 'última_tecla';
sNewFrameFunc = 'gra_quadroNovo';
sFrameHeight = 'gra_quadroAltura';
sFrameWidth = 'gra_quadroLargura';
sColor = 'cor_rgb';
sSetPenMode = 'alt_modo_caneta';
sFrameSetPenMode = 'alt_modo_caneta'; // ok
sPenMode = 'obt_modo_caneta';
sFramePenMode = 'obt_modo_caneta'; // ok
sSetPenStyle = 'alt_estilo_caneta';
sFrameSetPenStyle = 'alt_estilo_caneta'; // ok
sPenStyle = 'obt_estilo_caneta';
sFramePenStyle = 'obt_estilo_caneta'; // ok
sScreenWidth = 'gra_larguraDaTela';
sScreenHeight = 'gra_alturaDaTela';
sSetTimeEventInterval = 'alt_ev_tempo';
sTimeEventInterval = 'obt_ev_tempo';
sSleep = 'durma';
sMouseState = 'botão_mouse';
sKeyboardState = 'estado_teclado';
sDecodificaData = 'dcod_data';
sDecodificaHora = 'dcod_hora';
sCodificaData = 'cod_data';
sCodificaHora = 'cod_hora';
sFloatToStr = 'real_para_txt';
sStrToFloat = 'txt_para_real';
sNovaJanela = 'nova_janela';
sAltVisJanela = 'alt_vis_janela';
sToqSom = 'toq_som';
sNovoBotao = 'novo_botão';
sTstEvento = 'tstEvento';
sNovoRotulo = 'novo_rótulo';
sLibJanela = 'lib_janela';
sAltPosJanela = 'alt_pos_janela';
sCopImagem = 'cop_imagem';
sCopImagemRet = 'cop_imagem_ret';
sCopJanelaDist = 'cop_janela_dist';
sCopJanelaDistRot = 'cop_janela_dist_rot';
sCopJanelaRot = 'cop_janela_rot';
sCrgImg = 'crg_img';
sCrgJanela = 'crg_janela';
sAltTamJanela = 'alt_tam_janela';
sObtTamJanela = 'obt_tam_janela';
sAltTxtJanela = 'alt_txt_janela';
sObtTxtJanela = 'obt_txt_janela';
sAltFonte = 'alt_fonte';
sAltCor = 'alt_cor_janela';
sNovoEdtLin = 'novo_editor_lin';
sNovoEdtLinhas = 'novo_editor_txt';
sNovaCxMarca = 'nova_caixa_marca';
sNovaCxEscolha = 'nova_caixa_escolha';
sNovaCxLst = 'nova_caixa_lista';
sNovaCxCmb = 'nova_caixa_comb';
sNovaCxGrupo = 'nova_caixa_grupo';
sNovoPainel = 'novo_quadro';
sNovaImagem = 'nova_imagem';
sNovaImagemCrg = 'nova_imagem_crg';
sNovoSom = 'novo_som';
sObtPos = 'obt_pos_janela';
sArqParaTxt = 'arq_para_txt';
sTxtParaArq = 'txt_para_arq';
sRegEvento = 'reg_evento';
sCaixaMarcada = 'caixa_marcada';
procedure Register;
implementation
uses
Types, UITypes, Forms, Windows, Dialogs, StdCtrls, Controls, Buttons, MPlayer,
port_UFrmMemoria, port_UFrmDSL,
g_Heap, port_RWStreams, port_UFrmConfig, port_UQuadro, Math, port_Recursos,
port_UFrmJanela, UMeusComps, UCtrlMediaPlayers;
const
CpModes: array [0..14] of Integer = (
cmBlackness,
cmDstInvert,
cmMergeCopy,
cmMergePaint,
cmNotSrcCopy,
cmNotSrcErase,
cmPatCopy,
cmPatInvert,
cmPatPaint,
cmSrcAnd,
cmSrcCopy,
cmSrcErase,
cmSrcInvert,
cmSrcPaint,
cmWhiteness
);
PenModes: array [0..15] of TPenMode = (
pmBlack,
pmWhite,
pmNop,
pmNot,
pmCopy,
pmNotCopy,
pmMergePenNot,
pmMaskPenNot,
pmMergeNotPen,
pmMaskNotPen,
pmMerge,
pmNotMerge,
pmMask,
pmNotMask,
pmXor,
pmNotXor
);
{ Módulos padrões }
MODL_GRA = 'gra*';
MODL_ARQ = 'arq*';
MODL_EVNT = 'evnt*';
MODL_MAT = 'mat*';
MODL_PAC = 'pac*';
MODL_MM = 'mm*';
type
{ Forwards }
TCompiler = class;
TProduction = class;
TSymbolTable = class;
TSymbolType = class;
TSymbolInfo = class;
TProd_Procedure = class;
TProd_Function = class;
TProd_FunctionCall = class;
TProd_FormalParamList = class;
TProd_Expression = class;
TProd_SimpleExpression = class;
TProd_Term = class;
TProd_Factor = class;
TProd_Stmt = class;
{ TTypeClass }
TSymbolTypeClass = class of TSymbolType;
{ TTypeClass }
TTypeClass = (tcInteger, tcBoolean, tcChar, tcEnum, tcSubrange, tcExtended,
tcString, tcSet, tcArray, tcRecord, tcPointer, tcProcedure,
tcFunction);
{ TSymbolType }
TSymbolType = class
private
FSymbolTable: TSymbolTable;
FTypeClass: TTypeClass;
function GetSize: Integer; virtual; abstract;
function GetAsString: String; virtual; abstract;
public
constructor Create(SymbolTable: TSymbolTable); virtual;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); virtual; abstract;
function ValueAsString(V: TSymbolInfo): String; virtual; abstract;
function ValueThroughAddress(Address: Pointer): String; virtual; abstract;
property Size: Integer read GetSize;
property SymbolTable: TSymbolTable read FSymbolTable;
property AsString: String read GetAsString;
property TypeClass: TTypeClass read FTypeClass;
end;
{ TOrdinalType }
TOrdinalType = class(TSymbolType)
private
function GetRange: Integer; virtual; abstract;
function GetMinValue: Integer; virtual; abstract;
function GetMaxValue: Integer; virtual; abstract;
public
function OrdinalValue(V: TSymbolInfo): Integer; virtual; abstract;
property Range: Integer read GetRange;
property MinValue: Integer read GetMinValue;
property MaxValue: Integer read GetMaxValue;
end;
{ TIntegerType }
TIntegerType = class(TOrdinalType)
private
function GetSize: Integer; override;
function GetAsString: String; override;
function GetRange: Integer; override;
function GetMinValue: Integer; override;
function GetMaxValue: Integer; override;
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
function OrdinalValue(V: TSymbolInfo): Integer; override;
end;
{ TBooleanType }
TBooleanType = class(TOrdinalType)
private
function GetSize: Integer; override;
function GetAsString: String; override;
function GetRange: Integer; override;
function GetMinValue: Integer; override;
function GetMaxValue: Integer; override;
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
function OrdinalValue(V: TSymbolInfo): Integer; override;
end;
{ TExtendedType }
TExtendedType = class(TSymbolType)
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
private
function GetSize: Integer; override;
function GetAsString: String; override;
end;
{ TStringType }
TStringType = class(TSymbolType)
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
private
function GetSize: Integer; override;
function GetAsString: String; override;
end;
{ TCharType }
TCharType = class(TOrdinalType)
private
function GetSize: Integer; override;
function GetAsString: String; override;
function GetRange: Integer; override;
function GetMinValue: Integer; override;
function GetMaxValue: Integer; override;
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
function OrdinalValue(V: TSymbolInfo): Integer; override;
end;
{ TEnumType }
TEnumType = class(TOrdinalType)
private
FEnums: TList;
function GetSize: Integer; override;
function GetAsString: String; override;
function GetRange: Integer; override;
function GetMinValue: Integer; override;
function GetMaxValue: Integer; override;
public
constructor Create(SymbolTable: TSymbolTable); override;
destructor Destroy; override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
function OrdinalValue(V: TSymbolInfo): Integer; override;
end;
{ TSubrangeType }
TSubrangeType = class(TOrdinalType)
private
FInf: TSymbolInfo;
FSup: TSymbolInfo;
FBaseType: TSymbolType;
function GetSize: Integer; override;
function GetAsString: String; override;
function GetRange: Integer; override;
function GetMinValue: Integer; override;
function GetMaxValue: Integer; override;
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
function OrdinalValue(V: TSymbolInfo): Integer; override;
end;
{ TSetType }
TSetType = class(TSymbolType)
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
private
FBaseType: TSymbolType;
function GetSize: Integer; override;
function GetAsString: String; override;
end;
{ TArrayType }
TArrayType = class(TSymbolType)
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
private
FElemSymbol: TSymbolInfo;
FIndexSymbol: TSymbolInfo;
function GetSize: Integer; override;
function GetAsString: String; override;
end;
{ TRecordType }
TRecordType = class(TSymbolType)
public
constructor Create(SymbolTable: TSymbolTable); override;
destructor Destroy; override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
private
FFieldList: TList;
FSize: Integer;
FScope: TSymbolTable;
function GetSize: Integer; override;
function GetAsString: String; override;
end;
{ TPointerType }
TPointerType = class(TSymbolType)
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
procedure Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction); override;
private
FBaseType: TSymbolType;
FBaseId: String; // for solving pending base type
function GetSize: Integer; override;
function GetAsString: String; override;
end;
{ TProcedureType }
TProcedureType = class(TSymbolType)
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
private
FProduction: TProd_Procedure;
function GetSize: Integer; override;
function GetAsString: String; override;
end;
{ TFunctionType }
TFunctionType = class(TSymbolType)
public
constructor Create(SymbolTable: TSymbolTable); override;
function ValueAsString(V: TSymbolInfo): String; override;
function ValueThroughAddress(Address: Pointer): String; override;
private
FProduction: TProd_Function;
function GetSize: Integer; override;
function GetAsString: String; override;
end;
{ Set types }
TSetInteger = set of 0..255;
{ Pointers }
PBoolean = ^Boolean;
PExtended = ^Extended;
PInteger = ^Integer;
PPointer = ^Pointer;
PSetInteger = ^TSetInteger;
{ TSymbolInfo }
TSymbolInfo = class
private
FSymbolClass: TSymbolClass;
FSymbolTable: TSymbolTable;
FSymbolType: TSymbolType;
FOffset: Integer;
FStandardModule: String;
// FNameIndex: Integer;
FName: String;
FRecordType: TSymbolType; // only for fields
function GetAsString: String; virtual;
function GetAddress: Pointer;
function GetVarParamAddress: Pointer;
public
constructor Create(SymbolTable: TSymbolTable; SymbolClass: TSymbolClass;
SymbolType: TSymbolType);
procedure Assign(Value: TSymbolInfo);
property AsString: String read GetAsString;
property Address: Pointer read GetAddress;
property VarParamAddress: Pointer read GetVarParamAddress;
property SymbolClass: TSymbolClass read FSymbolClass;
property SymbolType: TSymbolType read FSymbolType;
property SymbolOffset: Integer read FOffset;
property SymbolTable: TSymbolTable read FSymbolTable;
property RecordType: TSymbolType read FRecordType write FRecordType;
property Name: String read FName {GetName};
property StandardModule: String read FStandardModule write FStandardModule;
end;
{ TSymbolTable }
TSymbolTable = class
private
FCompiler: TCompiler;
FConstOffset: Integer;
FVarOffset: Integer;
FConstArea: Pointer;
FVarArea: TList;
FTable: TStringList;
FNewTables: TList;
FInfos: TList;
FTypes: TList;
FScope: TList;
FIsRecordScope: Boolean;
FPendentPointer: TList; // of TProd_TypeDecl
FForwards: TList; // of TProd_Procedure and TProd_Function
public
constructor Create(Compiler: TCompiler);
destructor Destroy; override;
procedure AddScope(SymbolTable: TSymbolTable);
procedure SetActivation;
procedure LibActivation;
procedure ShowMemCleared;
procedure ShowMemActivation;
procedure MarkAsPointer(VAddr: Integer);
procedure ChangeAddress(OldAddr, NewAddr: Integer);
procedure UpdateVarParam(VAddr: Integer; Value: String);
procedure ShowSubroutineCall(Name: String);
procedure ShowSubroutineReturn;
procedure ShowMemArray(VName: String; VType: TSymbolType; VAddr: Integer;
Global: Boolean);
procedure ShowMemRecord(VName: String; VType: TSymbolType; VAddr: Integer;
Global: Boolean);
procedure ShowMem(VName: String; VType: TSymbolType; VAddr: Integer;
Global: Boolean);
procedure DisposeArray(VType: TSymbolType; VAddr: Integer);
procedure DisposeRecord(VType: TSymbolType; VAddr: Integer);
procedure DisposeHeap(VType: TSymbolType; VAddr: Integer);
procedure UpdateMem(VType: TSymbolType; VAddr: Integer);
procedure UpdateMemArray(VType: TSymbolType; VAddr: Integer);
procedure UpdateMemRecord(VType: TSymbolType; VAddr: Integer);
function AllocSymbolInfo(SymbolClass: TSymbolClass;
SymbolType: TSymbolType): TSymbolInfo;
function AllocType(TypeClass: TSymbolTypeClass): TSymbolType;
function FindSymbol(Name: String): TSymbolInfo;
function Enter(Name: String; SymbolClass: TSymbolClass;
SymbolType: TSymbolType; StdModule: String): TSymbolInfo;
function NewSymbolTable: TSymbolTable;
function DuplicateSymbolInfo(Symbol: TSymbolInfo): TSymbolInfo;
procedure RemoveScope;
procedure ShowTable(S: TStrings);
procedure CheckPendentPointers;
procedure AddPendentPointer(P: TProduction);
procedure AddForward(P: TProduction);
// procedure CheckForwards;
function LookForForward(Id: String): TProduction;
procedure InitArraySize(Mem: Pointer);
class function SizeOfArraySize: Integer;
property IsRecordScope: Boolean read FIsRecordScope write FIsRecordScope;
property Compiler: TCompiler read FCompiler;
end;
EBreakException = class(EInterpreterException);
EContinueException = class(EInterpreterException);
EExitException = class(EInterpreterException);
{ TProductionClass }
TProductionClass = class of TProduction;
{ TCompilerState }
TCompilerState = (csInProcedure, csInFunction, csFindInScope, csInRepetitiveStmt,
csInTypeDecl, csEvaluating, csBreakOnNextStmt, csInArrayDecl);
TCompilerStates = set of TCompilerState;
{ TCompiler }
TCompiler = class
private
FDeclTypeInteger: TSymbolType;
FDeclTypeExtended: TSymbolType;
FDeclTypeBoolean: TSymbolType;
FDeclTypeString: TSymbolType;
FDeclTypeChar: TSymbolType;
FDeclTypePointer: TSymbolType;
FOnWrite: TWriteEvent;
FOnReadChar: TReadCharEvent;
FOnReadInteger: TReadIntegerEvent;
FOnReadString: TReadStringEvent;
FOnReadReal: TReadRealEvent;
FOnDebug: TDebugEvent;
FOnWaitFor: TWaitForEvent;
FParser: TPascalTokenizer;
FSymbolTable: TSymbolTable;
FSource: TStream;
FParserStack: TList;
FIncludeList: TStringList;
FModlList: TStringList;
FProduction: TProduction;
FTerminate: Boolean;
FState: TCompilerStates;
FFloatFormat: String;
FProgramName: String;
FHeap: THeap;
FCanvas: TCanvas;
FProgramSymbolTable: TSymbolTable;
FSubroutineSymbolTable: TSymbolTable;
FBreakPointLine: Integer;
FBreakpointFileName: String;
FMouseX: Integer;
FMouseY: Integer;
FLastEvent: Integer;
FLastEventSender: TObject;
FShiftState: TShiftState;
FKeyPressed: Char;
FKeyDown: Word;
FKeyUp: Word;
FBitmapList: TList;
FStreamList: TList;
FTQuadroList: TList;
FTMediaPlayerList: TList;
// FCompList: TList;
FTela: TQuadro;
procedure InitializeSymbolTable;
procedure DestroyBitmaps;
procedure DestroyStreams;
procedure DestroyTQuadroList;
procedure DestroyTMediaPlayerList;
// procedure DestroyCompList;
public
constructor Create;
destructor Destroy; override;
function Compile(Source: TStream;
ProductionClass: TProductionClass): TProduction; overload;
function Compile(Source: String;
ProductionClass: TProductionClass): TProduction; overload;
procedure Interpret;
function Evaluate(Expression: String): String;
procedure Stop;
procedure Error(S: String);
procedure ShowSyntaxTree(S: TStrings);
procedure ShowSymbolTable(S: TStrings);
procedure SetProgramSymbolTable(T: TSymbolTable);
function SetSubroutineSymbolTable(T: TSymbolTable): TSymbolTable;
function FindSymbol(Symbol: String): TSymbolInfo;
procedure SetBreakpoint(FileName: String; LineNumber: Integer);
procedure BreakOnNextStatement;
procedure RegisterMouseXY(X, Y: Integer);
procedure RegisterLastEvent(Event: Integer; Sender: TObject);
procedure RegisterShiftState(Shift: TShiftState);
procedure RegisterKeyPressed(Key: Char);
procedure RegisterKeyDown(Key: Word);
procedure RegisterKeyUp(Key: Word);
procedure PushStream(FileName: String);
procedure PushStringStream(S: String);
procedure PopStream;
procedure TrataOnPaint(Sender: TObject);
procedure TrataOnClickBotao(Sender: TObject);
procedure TrataOnMouseDownBotao(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure TrataOnMouseUpBotao(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
property Parser: TPascalTokenizer read FParser;
property Source: TStream read FSource;
property SymbolTable: TSymbolTable read FSymbolTable;
property DeclTypeInteger: TSymbolType read FDeclTypeInteger;
property DeclTypeExtended: TSymbolType read FDeclTypeExtended;
property DeclTypeBoolean: TSymbolType read FDeclTypeBoolean;
property DeclTypeString: TSymbolType read FDeclTypeString;
property DeclTypeChar: TSymbolType read FDeclTypeChar;
property DeclTypePointer: TSymbolType read FDeclTypePointer;
property State: TCompilerStates read FState write FState;
property FloatFormat: String read FFloatFormat write FFloatFormat;
property ProgramName: String read FProgramName write FProgramName;
property Heap: THeap read FHeap;
property Canvas: TCanvas read FCanvas
write FCanvas;
// events
property OnWrite: TWriteEvent read FOnWrite
write FOnWrite;
property OnReadChar: TReadCharEvent read FOnReadChar
write FOnReadChar;
property OnReadInteger: TReadIntegerEvent read FOnReadInteger
write FOnReadInteger;
property OnReadString: TReadStringEvent read FOnReadString
write FOnReadString;
property OnReadReal: TReadRealEvent read FOnReadReal
write FOnReadReal;
property OnDebug: TDebugEvent read FOnDebug
write FOnDebug;
property OnWaitFor: TWaitForEvent read FOnWaitFor
write FOnWaitFor;
end;
{ TProduction }
TProduction = class
private
FLevel: Integer;
FProdLst: TList;
FCompiler: TCompiler;
FParent: TProduction;
FPosition: Integer;
FProductionLine: Integer;
FProductionCol: Integer;
FProductionEndLine: Integer;
FProductionEndCol: Integer;
FParser: TPascalTokenizer;
FSymbolTable: TSymbolTable;
FSymbolInfo: TSymbolInfo;
FPromoted: TSymbolInfo;
function GetProductions(Ind: Integer): TProduction;
function GetProductionCount: Integer;
function EstiloFonteParaInt(Fs: TFontStyles): Integer;
function IntParaEstiloFonte(V: Integer): TFontStyles;
function CarregaImg(Img: TImage; Nome: String): Boolean;
function CarregaBmp(Bmp: Graphics.TBitmap; Nome: String): Boolean;
(*
procedure PreparaTransfDistRot(Canvas: TCanvas; Rot: Extended; x, y: Integer);
procedure RestauraTransfDistRot(Canvas: TCanvas);
*)
function ExpandeNomeArq(Nome: String): String;
function FileStreamToString(Fs: TFileStream): String;
function GetParser: TPascalTokenizer;
protected
constructor Create(Compiler: TCompiler); virtual;
procedure Operate(Result, S1, S2: TSymbolInfo; Op: TToken);
function Compile(ProductionClass: TProductionClass): TProduction;
procedure Check(Tokens: TTokens; ErrMsg: String);
function CheckTypes(T1, T2: TSymbolType; Op: TToken): TSymbolType;
procedure Error(S: String; Line, Col: Integer);
function GetIdentifier: String;
function GetNewIdentifier: String;
procedure GetNewIdentifierList(Lst: TStringList);
// function GetIntNumber: Integer;
procedure GetTerminal(Token: TToken);
procedure CheckTerminal(Token: TToken);
function GetSymbolInfo: TSymbolInfo; virtual;
procedure SkipTo(Tokens: TTokens);
function PromoteTo(T: TSymbolType): Boolean; virtual;
function ExecPromotion: Boolean; virtual;
function FormalParamsOk(PFirst, PSecond: TProd_FormalParamList): Boolean;
procedure ReplaceSymbolInfo(SiOld, SiNew: TSymbolInfo);
function StandardProcedure(ProcName: String): Boolean;
procedure VerifyDebug(Lin, Col: Integer; Parser: TPascalTokenizer);
function IsStandardModule(FileName: String): Boolean;
// procedure CheckMemory;
property Level: Integer read FLevel;
property Parent: TProduction read FParent;
property Position: Integer read FPosition;
property ProductionLine: Integer read FProductionLine;
property ProductionCol: Integer read FProductionCol;
property ProductionEndLine: Integer read FProductionEndLine;
property ProductionEndCol: Integer read FProductionEndCol;
property Parser: TPascalTokenizer read GetParser;
property SymbolTable: TSymbolTable read FSymbolTable;
property SymbolInfo: TSymbolInfo read FSymbolInfo write FSymbolInfo;
property Promoted: TSymbolInfo read FPromoted write FPromoted;
public
destructor Destroy; override;
procedure Parse; virtual; abstract;
procedure Interpret; virtual;
procedure ShowSyntaxTree(S: TStrings);
function SolveWithStmt(P: TProduction; Symbol: TSymbolInfo): TSymbolInfo;
property Compiler: TCompiler read FCompiler;
property Productions[Ind: Integer]: TProduction
read GetProductions; default;
property ProductionCount: Integer
read GetProductionCount;
end;
{ TProd_Program }
TProd_Program = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_Block }
TProd_Block = class(TProduction)
private
FCompoundStmt: TProduction;
public
procedure Parse; override;
procedure Interpret; override;
end;
{ TProd_FormalParamList }
TProd_FormalParamList = class(TProduction)
private
FParamLst: TList;
public
destructor Destroy; override;
procedure Parse; override;
end;
{ TProd_ParamDecl }
TProd_ParamDecl = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_Procedure }
TProd_Procedure = class(TProduction)
private
FBlock: TProduction;
FParams: TProd_FormalParamList;
FSymbolTable: TSymbolTable;
FProcId: String;
public
procedure Parse; override;
property ProcId: String read FProcId;
end;
{ TProd_Function }
TProd_Function = class(TProduction)
private
FBlock: TProduction;
FParams: TProd_FormalParamList;
FSymbolTable: TSymbolTable;
FFuncId: String;
FReturnType: TSymbolType;
FSiResult: TSymbolInfo;
public
procedure Parse; override;
property FuncId: String read FFuncId;
end;
{ TProd_DeclPart }
TProd_DeclPart = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_ConstDeclPart }
TProd_ConstDeclPart = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_ConstDecl }
TProd_ConstDecl = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_TypeDeclPart }
TProd_TypeDeclPart = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_TypeDecl }
TProd_TypeDecl = class(TProduction)
private
// both are for pending base type of pointers
FBaseTypeId: String;
FTypeId: String;
public
procedure Parse; override;
end;
{ TProd_VarDeclPart }
TProd_VarDeclPart = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_VarDecl }
TProd_VarDecl = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_Type }
TProd_Type = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_IncludeDecl }
TProd_IncludeDecl = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_EnumType }
TProd_EnumType = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_SubrangeType }
TProd_SubrangeType = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_SetType }
TProd_SetType = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_ArrayType }
TProd_ArrayType = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_IndexType }
TProd_IndexType = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_RecordType }
TProd_RecordType = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_PointerType }
TProd_PointerType = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_SetConstructor }
(*
TProd_SetConstructor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
*)
{ TProd_MemberGroup }
TProd_MemberGroup = class(TProduction)
private
FExprInf, FExprSup: TProd_Expression;
function IsConst: Boolean;
function InRange(Si: TSymbolInfo): Boolean;
function InfSymbol: TSymbolInfo;
function SupSymbol: TSymbolInfo;
public
(*
procedure Interpret; override;
*)
procedure Parse; override;
end;
{ TProd_QualifIndex }
TProd_QualifIndex = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_QualifField }
TProd_QualifField = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_QualifPointer }
TProd_QualifPointer = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_ParamType }
TProd_ParamType = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_VarReference }
TProd_VarReference = class(TProduction)
private
FVarRef: TSymbolInfo;
FWith: TSymbolInfo;
FFieldOffset: Integer;
FFuncCall: TProd_FunctionCall;
FIsLValue: Boolean;
FQualified: Boolean;
public
procedure Parse; override;
procedure Interpret; override;
end;
{ TProd_Expression }
TProd_Expression = class(TProduction)
private
FSimpleExpr1: TProduction;
FSimpleExpr2: TProduction;
FRelOp: TToken;
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SimpleExpression }
TProd_SimpleExpression = class(TProduction)
private
FLstAddOp: TList;
public
constructor Create(Compiler: TCompiler); override;
destructor Destroy; override;
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Term }
TProd_Term = class(TProduction)
private
FLstMulOp: TList;
public
constructor Create(Compiler: TCompiler); override;
destructor Destroy; override;
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Factor }
TProd_Factor = class(TProduction)
private
FExpr: TProduction;
FFact: TProduction;
FSetExpr: TProduction;
FVarRef: TProduction;
FFuncCall: TProduction;
FNegate: Boolean;
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Expression }
TProd_ConstExpression = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_CompoundStmt }
TProd_CompoundStmt = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_Stmt }
TProd_Stmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_AssignStmt }
TProd_AssignStmt = class(TProduction)
private
FIsAssignment: Boolean;
FIsIncrDecr: Boolean;
FTokIncrDecr: TToken;
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_PreAssignStmt }
TProd_PreAssignStmt = class(TProduction)
private
FTokIncrDecr: TToken;
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_IfStmt }
TProd_IfStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TCaseSelector }
TCaseSelector = class
private
FLstMember: TList;
FLstStmt: TList;
public
constructor Create;
destructor Destroy; override;
procedure AddEntry(E: TProd_MemberGroup);
procedure SetStmt(Stmt: TProd_Stmt);
function TestCase(Si: TSymbolInfo): Boolean;
end;
{ TProd_CaseStmt }
TProd_CaseStmt = class(TProduction)
private
FCaseSel: TCaseSelector; // cases part
FElseStmt: TProd_Stmt; // else part
public
destructor Destroy; override;
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_CaseEntry }
TProd_CaseEntry = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_WhileStmt }
TProd_WhileStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_RepeatStmt }
TProd_RepeatStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_ForStmt }
TProd_ForStmt = class(TProduction)
private
FExpr1: TProduction;
FExpr2: TProduction;
FStmt: TProduction;
FDownTo: Boolean;
public
procedure Interpret; override;
procedure Parse; override;
end;
TProd_ForStmt_2 = class(TProduction)
private
FStmt1: TProduction;
FExpr: TProduction;
FStmt2: TProduction;
FStmt: TProduction;
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_WithStmt }
TProd_WithStmt = class(TProduction)
private
FRecordLst: TList; // of TProduction (record var references)
FStmt: TProduction;
public
procedure Interpret; override;
procedure Parse; override;
destructor Destroy; override;
end;
{ TProd_WriteStmt }
TProd_WriteStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_WritelnStmt }
TProd_WritelnStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_ReadStmt }
TProd_ReadStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_NewStmt }
TProd_NewStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_DisposeStmt }
TProd_DisposeStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_ProcedureCall }
TProd_ProcedureCall = class(TProduction)
private
FProcId: String;
public
procedure Parse; override;
procedure Interpret; override;
property ProcId: String read FProcId;
end;
{ TProd_RectangleStmt }
TProd_RectangleStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_DsnRetSel }
TProd_DsnRetSel = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FillRect }
TProd_FillRect = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_dsnLinSel }
TProd_dsnLinSel = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_CopyFrameStmt }
TProd_CopyFrameStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Stretch }
TProd_Stretch = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameStretch }
TProd_FrameStretch = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_TerminateStmt }
TProd_TerminateStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_TriangleStmt }
TProd_TriangleStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_EllipseStmt }
TProd_EllipseStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_LineToStmt }
TProd_LineToStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_MoveToStmt }
TProd_MoveToStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_altPixel }
TProd_altPixel = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_TextOutStmt }
TProd_TextOutStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetBrushColorStmt }
TProd_SetBrushColorStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetPenColorStmt }
TProd_SetPenColorStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetPenWidthStmt }
TProd_SetPenWidthStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_TextHeight }
TProd_TextHeight = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_TextWidth }
TProd_TextWidth = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameTextHeight }
TProd_FrameTextHeight = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameTextWidth }
TProd_FrameTextWidth = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_WriterWriteChar }
TProd_WriterWriteChar = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_caixa_marcada }
TProd_caixa_marcada = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_ReaderHasChar }
TProd_ReaderHasChar = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_ReaderNextChar }
TProd_ReaderNextChar = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetFontColorStmt }
TProd_SetFontColorStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetBrushStyleStmt }
TProd_SetBrushStyleStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetCopyMode }
TProd_SetCopyMode = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetCopyMode }
TProd_FrameSetCopyMode = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_CopyMode }
TProd_CopyMode = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameCopyMode - dsl_quadroModoDeCopiar }
TProd_FrameCopyMode = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetPenMode }
TProd_SetPenMode = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetPenMode }
TProd_FrameSetPenMode = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_PenMode }
TProd_PenMode = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FramePenMode }
TProd_FramePenMode = class(TProduction)
public
(*
procedure Interpret; override;
*)
procedure Parse; override;
end;
{ TProd_SetPenStyle }
TProd_SetPenStyle = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetPenStyle }
TProd_FrameSetPenStyle = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_PenStyle }
TProd_PenStyle = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FramePenStyle }
TProd_FramePenStyle = class(TProduction)
public
(*
procedure Interpret; override;
*)
procedure Parse; override;
end;
{ TProd_Arc - dsl_arco }
TProd_Arc = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameArc - dsl_quadroArco }
TProd_FrameArc = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Chord - dsl_corte }
TProd_Chord = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameChord - dsl_quadroCorte }
TProd_FrameChord = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Pie - dsl_fatia }
TProd_Pie = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FramePie - dsl_quadroFatia }
TProd_FramePie = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Bezier - dsl_bezier }
TProd_Bezier = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameBezier - dsl_quadroBezier }
TProd_FrameBezier = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_BackgroundColor }
TProd_BackgroundColor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_BrushStyle }
TProd_BrushStyle = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetFontSizeStmt }
TProd_SetFontSizeStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetFontNameStmt }
TProd_SetFontNameStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetFontStyleStmt }
TProd_SetFontStyleStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_toqSom }
TProd_toqSom = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_WaitForStmt }
TProd_WaitForStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_BreakStmt }
TProd_BreakStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_ContinueStmt }
TProd_ContinueStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_ReturnStmt }
TProd_ReturnStmt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_GetPenPosX }
TProd_GetPenPosX = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_GetPenPosY }
TProd_GetPenPosY = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Sqrt }
TProd_Sqrt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Length }
TProd_Length = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_obtPixel }
TProd_obtPixel = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetBrushColor - dsl_quadroMudeCorDoPincel }
TProd_FrameSetBrushColor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetBrushStyle - dsl_quadroMudeEstiloDoPincel }
TProd_FrameSetBrushStyle = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetPenColor - dsl_quadroMudeCorDaCaneta }
TProd_FrameSetPenColor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetPenWidth - dsl_quadroMudeLarguraDaCaneta }
TProd_FrameSetPenWidth = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetFontColor - dsl_quadroMudeCorDaFonte }
TProd_FrameSetFontColor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetFontSize - dsl_quadroMudeTamanhoDaFonte }
TProd_FrameSetFontSize = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetFontName - dsl_quadroMudeNomeDaFonte }
TProd_FrameSetFontName = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameRectangle - dsl_quadroRetangulo }
TProd_FrameRectangle = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameEllipse - dsl_quadroElipse }
TProd_FrameEllipse = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameTriangle - dsl_quadroTriangulo }
TProd_FrameTriangle = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_SetTimeEventInterval - dsl_mudeIntervaloEventoTempo }
TProd_SetTimeEventInterval = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Sleep - dsl_durma }
TProd_Sleep = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameHeight - dsl_quadroAltura }
TProd_FrameHeight = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameWidth - dsl_quadroLargura }
TProd_FrameWidth = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetWidth - dsl_quadroMudeLargura }
TProd_FrameSetWidth = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameSetHeight - dsl_quadroMudeAltura }
TProd_FrameSetHeight = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameLineTo - dsl_quadroLinha }
TProd_FrameLineTo = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameMoveTo - dsl_quadroMudeXY }
TProd_FrameMoveTo = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Color - dsl_cor }
TProd_Color = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Now - tpoAgora }
TProd_Now = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FileExists - dsl_arquivoExiste }
TProd_FileExists = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FileNameComplete - dsl_arquivoNomeCompleto }
TProd_FileNameComplete = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FileNew - dsl_arquivoNovo }
TProd_FileNew = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FileDispose - dsl_arquivoLibere }
TProd_FileDispose = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FileReader - dsl_arquivoLeitor }
TProd_FileReader = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FileWriter - dsl_arquivoEscritor }
TProd_FileWriter = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FramePenPosX - dsl_quadroX }
TProd_FramePenPosX = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FramePenPosY - dsl_quadroY }
TProd_FramePenPosY = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameBrushColor - dsl_quadroCorDoPincel }
TProd_FrameBrushColor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameBrushStyle - dsl_quadroEstiloDoPincel }
TProd_FrameBrushStyle = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FramePenColor - dsl_quadroCorDaCaneta }
TProd_FramePenColor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FramePenWidth - dsl_quadroLarguraDaCaneta }
TProd_FramePenWidth = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameFontColor - dsl_quadroCorDaFonte }
TProd_FrameFontColor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameFontSize - dsl_quadroTamanhoDaFonte }
TProd_FrameFontSize = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameFontName }
TProd_FrameFontName = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_TimeEventInterval - dsl_intervaloEventoTempo }
TProd_TimeEventInterval = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_ScreenWidth - dsl_larguraDaTela }
TProd_ScreenWidth = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_ScreenHeight - dsl_alturaDaTela }
TProd_ScreenHeight = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_UpperCase }
TProd_UpperCase = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_LowerCase }
TProd_LowerCase = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Round }
TProd_Round = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Sin }
TProd_Sin = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Cos }
TProd_Cos = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FunctionCall }
TProd_FunctionCall = class(TProduction)
private
FFuncSymbol: TSymbolInfo;
FFuncId: String;
public
procedure Parse; override;
procedure Interpret; override;
property FuncId: String read FFuncId;
end;
{ TProd_Random }
TProd_Random = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Potencia }
TProd_Potencia = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Ord }
TProd_Ord = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Chr }
TProd_Chr = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_IntToStr }
TProd_IntToStr = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FloatToStr }
TProd_FloatToStr = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_StrToInt }
TProd_StrToInt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_StrToFloat }
TProd_StrToFloat = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_CharAt }
TProd_CharAt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameReadFromFile }
TProd_FrameReadFromFile = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameTextOut }
TProd_FrameTextOut = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameCopyFromScreen }
TProd_FrameCopyFromScreen = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FrameCopyFromFrame }
TProd_FrameCopyFromFrame = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_MouseX }
TProd_MouseX = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_MouseY }
TProd_MouseY = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_MouseXY }
TProd_MouseXY = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_BrushColor }
TProd_BrushColor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_PenColor }
TProd_PenColor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_PenWidth }
TProd_PenWidth = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FontColor }
TProd_FontColor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FontSize }
TProd_FontSize = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FontName }
TProd_FontName = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_LastEvent }
TProd_LastEvent = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_reg_evento }
TProd_reg_evento = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_KeyPressed }
TProd_KeyPressed = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_MouseState }
TProd_MouseState = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_KeyboardState }
TProd_KeyboardState = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_NewFrame (dsl_quadroNovo) }
TProd_NewFrame = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novaJanela }
TProd_novaJanela = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_altVisJanela }
TProd_altVisJanela = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novoBotao }
TProd_novoBotao = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novoRotulo }
TProd_novoRotulo = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_nova_imagem }
TProd_nova_imagem = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novoEdtLin }
TProd_novoEdtLin = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novaCxMarca }
TProd_novaCxMarca = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novaCxEscolha }
TProd_novaCxEscolha = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novaCxLst }
TProd_novaCxLst = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novaCxCmb }
TProd_novaCxCmb = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novaCxGrupo }
TProd_novaCxGrupo = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novoPainel }
TProd_novoPainel = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novaImagem }
TProd_novaImagem = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novaImagemCrg }
TProd_novaImagemCrg = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novo_som }
TProd_novo_som = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_novoEdtLinhas }
TProd_novoEdtLinhas = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_libJanela }
TProd_libJanela = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_altPosJanela }
TProd_altPosJanela = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_copJanela }
TProd_copJanela = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_copJanelaRet }
TProd_copJanelaRet = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_copJanelaDist }
TProd_copJanelaDist = class(TProduction)
public
(*
procedure Interpret; override;
*)
procedure Parse; override;
end;
{ TProd_copJanelaDistRot }
TProd_copJanelaDistRot = class(TProduction)
public
(*
procedure Interpret; override;
*)
procedure Parse; override;
end;
{ TProd_copJanelaRot }
TProd_copJanelaRot = class(TProduction)
public
// procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_crgImg }
TProd_crgImg = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_crgJanela }
TProd_crgJanela = class(TProduction)
public
(*
procedure Interpret; override;
*)
procedure Parse; override;
end;
{ TProd_obtPos }
TProd_obtPos = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_altTamJanela }
TProd_altTamJanela = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_obtTamJanela }
TProd_obtTamJanela = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_altTxtJanela }
TProd_altTxtJanela = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
(*
{ TProd_altFonte }
TProd_altFonte = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
*)
{ TProd_altCor }
TProd_altCor = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_tstEvento }
TProd_tstEvento = class(TProduction)
public
(*
procedure Interpret; override;
*)
procedure Parse; override;
end;
{ TProd_FrameDispose (dsl_quadroLibere) }
TProd_FrameDispose = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_arqParaTxt }
TProd_arqParaTxt = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_txtParaArq }
TProd_txtParaArq = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_FunctionAssign }
TProd_FunctionAssign = class(TProduction)
public
procedure Parse; override;
end;
{ TProd_Inc }
TProd_Inc = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_Dec }
TProd_Dec = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_DecodificaData }
TProd_DecodificaData = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_DecodificaHora }
TProd_DecodificaHora = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_CodificaData }
TProd_CodificaData = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_CodificaHora }
TProd_CodificaHora = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
{ TProd_obt_txt_janela }
TProd_obt_txt_janela = class(TProduction)
public
procedure Interpret; override;
procedure Parse; override;
end;
const
BUFSIZE = 16384;
// minimum and maximum defaults for heap size
Default_Heap_Min = 1024 * 1024;
Default_Heap_Max = 16 * Default_Heap_Min;
const
MAX_PROCS = 179;
Procs: array [0..MAX_PROCS] of String = (
sSetPenMode,
sPenMode,
sFrameSetPenMode, // ok
sFramePenMode, // ok
sSetPenStyle,
sPenStyle,
sFrameSetPenStyle, // ok
sFramePenStyle, // ok
sWriterWriteChar,
sReaderNextChar,
sReaderNextChar2,
sReaderHasChar,
sFileReader,
sFileWriter,
sFileDispose,
sFileNew,
sFileExists,
sFileNameComplete,
sNow,
sFrameBezier,
sFrameBezier,
sFramePie,
sFramePie, // ok
sFrameChord,
sFrameChord, // ok
sArc,
sFrameArc,
sTextWidth,
sTextHeight,
sFrameTextWidth,
sFrameTextHeight,
sColor,
sFrameSetCopyMode,
sFrameCopyMode,
sCopyMode,
sSetCopyMode,
sFrameBrushStyle,
sFrameSetBrushStyle,
sFrameFontName,
sFrameSetFontName,
sFrameFontSize,
sFrameSetFontSize,
sFrameFontColor,
sFrameSetFontColor,
sFramePenWidth,
sFrameSetPenWidth,
sFramePenColor,
sFrameSetPenColor,
sFrameBrushColor,
sFrameSetBrushColor,
sFrameTextOut,
sFramePenPosX,
sFramePenPosY,
sFrameMoveTo,
sFrameLineTo,
sFrameTriangle,
sFrameTriangle2,
sFrameEllipse,
sFrameRectangle,
sFrameRectangle2,
sFrameSetWidth,
sFrameSetHeight,
sFrameWidth,
sFrameHeight,
sAltPixel,
sObtPixel,
sFrameCopyFromScreenProc,
sFrameCopyFromFrameProc,
sFrameDisposeProc,
sFrameReadFromFileProc,
sNewFrameFunc,
sKeyPressedFunc,
sBackgroundColorFunc,
sSetBrushStyleProc,
sBrushStyleFunc,
sFontNameFunc,
sFontSizeFunc,
sFontColorFunc,
sPenWidthFunc,
sPenColorFunc,
sBrushColorFunc,
sAltPixel,
sObtPixel,
sLastEventFunc,
sLastEventFunc2,
sMouseXFunc,
sMouseYFunc,
sMouseXY,
sWaitForProc,
sRectangleProc,
sRectangleProc2,
sTriangleProc,
sTriangleProc2,
sEllipseProc,
sLineToProc,
sMoveToProc,
sTextOutProc,
sSetBrushColorProc,
sSetPenColorProc,
sSetPenWidthProc,
sSetFontColorProc,
sSetFontSizeProc,
sSetFontNameProc,
sSetFontStyleProc,
sBreakProc,
sContinueProc,
sTerminateProc,
sCopyFrameProc,
sSqrtFunc,
sLengthFunc,
sUpperCaseFunc,
sUpperCaseFunc2,
sLowerCaseFunc,
sLowerCaseFunc2,
sRoundFunc,
sSinFunc,
sCosFunc,
sGetPenPosXFunc,
sGetPenPosYFunc,
sRandomFunc,
sOrdFunc,
sChrFunc,
sIntToStrFunc,
sStrToIntFunc,
sCaracterEmFunc,
sScreenWidth,
sScreenHeight,
sSetTimeEventInterval,
sTimeEventInterval,
sSleep,
sInc,
sDec,
sMouseState,
sKeyboardState,
sDecodificaData,
sDecodificaHora,
sCodificaData,
sCodificaHora,
sStretch,
sFrameStretch,
sPotencia,
sFloatToStr,
sStrToFloat,
sNovaJanela,
sToqSom,
sNovoBotao,
sTstEvento,
sNovoRotulo,
sLibJanela,
sAltPosJanela,
sAltTamJanela,
sAltTxtJanela,
// sAltFonte,
sAltCor,
sNovoEdtLin,
sNovoEdtLinhas,
sNovaCxMarca,
sNovaCxEscolha,
sNovaCxLst,
sNovaCxCmb,
sNovaCxGrupo,
sNovoPainel,
sNovaImagem,
sNovaImagemCrg,
sNovoSom,
sCopImagem,
sCopJanelaDist,
sCopJanelaDistRot,
sAltVisJanela,
sCrgImg,
sCrgJanela,
sObtTamJanela,
sCopImagemRet,
sArqParaTxt,
sTxtParaArq,
sFillRect,
sDsnLinSel,
sRegEvento,
sObtTxtJanela,
sCaixaMarcada,
sDsnRetSel
);
Prods: array [0..MAX_PROCS] of TProductionClass = (
TProd_FrameSetPenMode,
TProd_FramePenMode,
TProd_FrameSetPenMode,
TProd_FramePenMode,
TProd_FrameSetPenStyle,
TProd_FramePenStyle,
TProd_FrameSetPenStyle,
TProd_FramePenStyle,
TProd_WriterWriteChar,
TProd_ReaderNextChar,
TProd_ReaderNextChar,
TProd_ReaderHasChar,
TProd_FileReader,
TProd_FileWriter,
TProd_FileDispose,
TProd_FileNew,
TProd_FileExists,
TProd_FileNameComplete,
TProd_Now,
TProd_FrameBezier,
TProd_FrameBezier,
TProd_FramePie,
TProd_FramePie,
TProd_FrameChord,
TProd_FrameChord,
TProd_FrameArc,
TProd_FrameArc,
TProd_TextWidth,
TProd_TextHeight,
TProd_FrameTextWidth,
TProd_FrameTextHeight,
TProd_Color,
TProd_FrameSetCopyMode,
TProd_FrameCopyMode,
TProd_CopyMode,
TProd_SetCopyMode,
TProd_FrameBrushStyle,
TProd_FrameSetBrushStyle,
TProd_FrameFontName,
TProd_FrameSetFontName,
TProd_FrameFontSize,
TProd_FrameSetFontSize,
TProd_FrameFontColor,
TProd_FrameSetFontColor,
TProd_FramePenWidth,
TProd_FrameSetPenWidth,
TProd_FramePenColor,
TProd_FrameSetPenColor,
TProd_FrameBrushColor,
TProd_FrameSetBrushColor,
TProd_FrameTextOut,
TProd_FramePenPosX,
TProd_FramePenPosY,
TProd_FrameMoveTo,
TProd_FrameLineTo,
TProd_FrameTriangle,
TProd_FrameTriangle,
TProd_FrameEllipse,
TProd_FrameRectangle,
TProd_FrameRectangle,
TProd_FrameSetWidth,
TProd_FrameSetHeight,
TProd_FrameWidth,
TProd_FrameHeight,
TProd_AltPixel,
TProd_ObtPixel,
TProd_FrameCopyFromScreen,
TProd_FrameCopyFromFrame,
TProd_FrameDispose,
TProd_FrameReadFromFile,
TProd_NewFrame,
TProd_KeyPressed,
TProd_BackgroundColor,
TProd_SetBrushStyleStmt,
TProd_BrushStyle,
TProd_FontName,
TProd_FontSize,
TProd_FontColor,
TProd_PenWidth,
TProd_PenColor,
TProd_BrushColor,
TProd_AltPixel,
TProd_ObtPixel,
TProd_LastEvent,
TProd_LastEvent,
TProd_MouseX,
TProd_MouseY,
TProd_MouseXY,
TProd_WaitForStmt,
TProd_RectangleStmt,
TProd_RectangleStmt,
TProd_TriangleStmt,
TProd_TriangleStmt,
TProd_EllipseStmt,
TProd_LineToStmt,
TProd_MoveToStmt,
TProd_TextOutStmt,
TProd_SetBrushColorStmt,
TProd_SetPenColorStmt,
TProd_SetPenWidthStmt,
TProd_SetFontColorStmt,
TProd_SetFontSizeStmt,
TProd_SetFontNameStmt,
TProd_SetFontStyleStmt,
TProd_BreakStmt,
TProd_ContinueStmt,
TProd_TerminateStmt,
TProd_CopyFrameStmt,
TProd_Sqrt,
TProd_Length,
TProd_UpperCase,
TProd_UpperCase,
TProd_LowerCase,
TProd_LowerCase,
TProd_Round,
TProd_Sin,
TProd_Cos,
TProd_GetPenPosX,
TProd_GetPenPosY,
TProd_Random,
TProd_Ord,
TProd_Chr,
TProd_IntToStr,
TProd_StrToInt,
TProd_CharAt,
TProd_ScreenWidth,
TProd_ScreenHeight,
TProd_SetTimeEventInterval,
TProd_TimeEventInterval,
TProd_Sleep,
TProd_Inc,
TProd_Dec,
TProd_MouseState,
TProd_KeyboardState,
TProd_DecodificaData,
TProd_DecodificaHora,
TProd_CodificaData,
TProd_CodificaHora,
TProd_Stretch,
TProd_FrameStretch,
TProd_Potencia,
TProd_FloatToStr,
TProd_StrToFloat,
TProd_novaJanela,
TProd_toqSom,
TProd_novoBotao,
TProd_tstEvento,
TProd_novoRotulo,
TProd_libJanela,
TProd_altPosJanela,
TProd_altTamJanela,
TProd_altTxtJanela,
// TProd_altFonte,
TProd_altCor,
TProd_novoEdtLin,
TProd_novoEdtLinhas,
TProd_novaCxMarca,
TProd_novaCxEscolha,
TProd_novaCxLst,
TProd_novaCxCmb,
TProd_novaCxGrupo,
TProd_novoPainel,
TProd_novaImagem,
TProd_novaImagemCrg,
TProd_novo_som,
TProd_copJanela,
TProd_copJanelaDist,
TProd_copJanelaDistRot,
TProd_altVisJanela,
TProd_crgImg,
TProd_crgJanela,
TProd_obtTamJanela,
TProd_copJanelaRet,
TProd_arqParaTxt,
TProd_txtParaArq,
TProd_FillRect,
TProd_DsnLinSel,
TProd_reg_evento,
TProd_obt_txt_janela,
TProd_caixa_marcada,
TProd_DsnRetSel
);
Modls: array [0..MAX_PROCS] of String = (
MODL_GRA, // sSetPenMode,
MODL_GRA, // sPenMode,
MODL_GRA, // sFrameSetPenMode,
MODL_GRA, // sFramePenMode,
MODL_GRA, // sSetPenStyle,
MODL_GRA, // sPenStyle,
MODL_GRA, // sFrameSetPenStyle,
MODL_GRA, // sFramePenStyle,
MODL_ARQ, // sWriterWriteChar,
MODL_ARQ, // sReaderNextChar,
MODL_ARQ, // sReaderNextChar2,
MODL_ARQ, // sReaderHasChar,
MODL_ARQ, // sFileReader,
MODL_ARQ, // sFileWriter,
MODL_ARQ, // sFileDispose,
MODL_ARQ, // sFileNew,
MODL_ARQ, // sFileExists,
MODL_ARQ, // sFileNameComplete,
MODL_PAC, // sNow,
MODL_GRA, // sBezier,
MODL_GRA, // sFrameBezier,
MODL_GRA, // sPie,
MODL_GRA, // sFramePie,
MODL_GRA, // sChord,
MODL_GRA, // sFrameChord,
MODL_GRA, // sArc,
MODL_GRA, // sFrameArc,
MODL_GRA, // sTextWidth,
MODL_GRA, // sTextHeight,
MODL_GRA, // sFrameTextWidth,
MODL_GRA, // sFrameTextHeight,
MODL_GRA, // sColor,
MODL_GRA, // sFrameSetCopyMode,
MODL_GRA, // sFrameCopyMode,
MODL_GRA, // sCopyMode,
MODL_GRA, // sSetCopyMode,
MODL_GRA, // sFrameBrushStyle,
MODL_GRA, // sFrameSetBrushStyle,
MODL_GRA, // sFrameFontName,
MODL_GRA, // sFrameSetFontName,
MODL_GRA, // sFrameFontSize,
MODL_GRA, // sFrameSetFontSize,
MODL_GRA, // sFrameFontColor,
MODL_GRA, // sFrameSetFontColor,
MODL_GRA, // sFramePenWidth,
MODL_GRA, // sFrameSetPenWidth,
MODL_GRA, // sFramePenColor,
MODL_GRA, // sFrameSetPenColor,
MODL_GRA, // sFrameBrushColor,
MODL_GRA, // sFrameSetBrushColor,
MODL_GRA, // sFrameTextOut,
MODL_GRA, // sFramePenPosX,
MODL_GRA, // sFramePenPosY,
MODL_GRA, // sFrameMoveTo,
MODL_GRA, // sFrameLineTo,
MODL_GRA, // sFrameTriangle,
MODL_GRA, // sFrameTriangle2,
MODL_GRA, // sFrameEllipse,
MODL_GRA, // sFrameRectangle,
MODL_GRA, // sFrameRectangle2,
MODL_GRA, // sFrameSetWidth,
MODL_GRA, // sFrameSetHeight,
MODL_GRA, // sFrameWidth,
MODL_GRA, // sFrameHeight,
MODL_GRA, // sAltPixel,
MODL_GRA, // sObtPixel,
MODL_GRA, // sFrameCopyFromScreenProc,
MODL_GRA, // sFrameCopyFromFrameProc,
MODL_GRA, // sFrameDisposeProc,
MODL_GRA, // sFrameReadFromFileProc,
MODL_GRA, // sNewFrameFunc,
MODL_EVNT, // sKeyPressedFunc,
MODL_GRA, // sBackgroundColorFunc,
MODL_GRA, // sSetBrushStyleProc,
MODL_GRA, // sBrushStyleFunc,
MODL_GRA, // sFontNameFunc,
MODL_GRA, // sFontSizeFunc,
MODL_GRA, // sFontColorFunc,
MODL_GRA, // sPenWidthFunc,
MODL_GRA, // sPenColorFunc,
MODL_GRA, // sBrushColorFunc,
MODL_GRA, // sAltPixel,
MODL_GRA, // sObtPixel,
MODL_EVNT, // sLastEventFunc,
MODL_EVNT, // sLastEventFunc2,
MODL_EVNT, // sMouseXFunc,
MODL_EVNT, // sMouseYFunc,
MODL_EVNT, // sMouseXY,
MODL_EVNT, // sWaitForProc,
MODL_GRA, // sRectangleProc,
MODL_GRA, // sRectangleProc2,
MODL_GRA, // sTriangleProc,
MODL_GRA, // sTriangleProc2,
MODL_GRA, // sEllipseProc,
MODL_GRA, // sLineToProc,
MODL_GRA, // sMoveToProc,
MODL_GRA, // sTextOutProc,
MODL_GRA, // sSetBrushColorProc,
MODL_GRA, // sSetPenColorProc,
MODL_GRA, // sSetPenWidthProc,
MODL_GRA, // sSetFontColorProc,
MODL_GRA, // sSetFontSizeProc,
MODL_GRA, // sSetFontNameProc,
MODL_GRA, // sSetFontStyleProc
MODL_PAC, // sBreakProc,
MODL_PAC, // sContinueProc,
MODL_PAC, // sTerminateProc,
MODL_GRA, // sCopyFrameProc,
MODL_MAT, // sSqrtFunc,
MODL_PAC, // sLengthFunc,
MODL_PAC, // sUpperCaseFunc,
MODL_PAC, // sUpperCaseFunc2,
MODL_PAC, // sLowerCaseFunc,
MODL_PAC, // sLowerCaseFunc2,
MODL_MAT, // sRoundFunc,
MODL_MAT, // sSinFunc,
MODL_MAT, // sCosFunc,
MODL_GRA, // sGetPenPosXFunc,
MODL_GRA, // sGetPenPosYFunc,
MODL_MAT, // sRandomFunc,
MODL_PAC, // sOrdFunc,
MODL_PAC, // sChrFunc,
MODL_PAC, // sIntToStrFunc,
MODL_PAC, // sStrToIntFunc,
MODL_PAC, // sCaracterEmFunc,
MODL_GRA, // sScreenWidth,
MODL_GRA, // sScreenHeight,
MODL_EVNT, // sSetTimeEventInterval,
MODL_EVNT, // sTimeEventInterval,
MODL_EVNT, // sSleep
MODL_PAC, // sInc
MODL_PAC, // sDec
MODL_EVNT, // sMouseState
MODL_EVNT, // sKeyboardState
MODL_PAC, // sDecodificaData
MODL_PAC, // sDecodificaHora
MODL_PAC, // sCodificaData
MODL_PAC, // sCodificaHora
MODL_GRA, // sStretch
MODL_GRA, // sFrameStretch
MODL_MAT, // sPotencia
MODL_PAC, // sFloatToStr
MODL_PAC, // sStroToFloat
MODL_GRA, // sNovaJanela
MODL_MM, // sToqSom
MODL_GRA, // sNovoBotao
MODL_EVNT,// sTstEvento
MODL_GRA, // sNovoRotulo
MODL_GRA, // sLibJanela
MODL_GRA, // sAltPosJanela
MODL_GRA, // sAltTamJanela
MODL_GRA, // sAltTxtJanela
// MODL_GRA, // sAltFonte
MODL_GRA, // sAltCor
MODL_GRA, // sNovoEdtLin
MODL_GRA, // sNovoEdtLinhas
MODL_GRA, // sNovaCxMarca
MODL_GRA, // sNovaCxEscolha
MODL_GRA, // sNovaCxLst
MODL_GRA, // sNovaCxCmb
MODL_GRA, // sNovaCxGrupo
MODL_GRA, // sNovoPainel
MODL_GRA, // sNovaImagem
MODL_GRA, // sNovaImagemCrg
MODL_MM, // sNovoSom
MODL_GRA, // sCopImagem
MODL_GRA, // sCopJanelaDist
MODL_GRA, // sCopJanelaDistRot
MODL_GRA, // sAltVisJanela
MODL_GRA, // sCrgImg
MODL_GRA, // sCrgJanela
MODL_GRA, // sObtTamJanela
MODL_GRA, // sCopImagemRet
MODL_ARQ, // sArqParaTxt
MODL_ARQ, // sTxtParaArq
MODL_GRA, // sFillRect
MODL_GRA, // sDsnLinSel
MODL_EVNT, // sRegEvento
MODL_GRA, // sObtTxtJanela
MODL_GRA, // sCaixaMarcada
MODL_GRA // sDsnRetSel
);
{ TSymbolType }
constructor TSymbolType.Create(SymbolTable: TSymbolTable);
begin
FSymbolTable := SymbolTable;
end;
{ TIntegerType }
constructor TIntegerType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcInteger;
end;
function TIntegerType.GetSize: Integer;
begin
Result := SizeOf(Integer);
end;
function TIntegerType.GetAsString: String;
begin
Result := 'inteiro';
end;
function TIntegerType.ValueAsString(V: TSymbolInfo): String;
begin
Result := IntToStr(PInteger(V.Address)^);
end;
function TIntegerType.ValueThroughAddress(Address: Pointer): String;
begin
Result := IntToStr(PInteger(Address)^);
end;
function TIntegerType.GetRange: Integer;
begin
Result := 0;
end;
function TIntegerType.GetMinValue: Integer;
begin
Result := -MaxInt;
end;
function TIntegerType.GetMaxValue: Integer;
begin
Result := MaxInt;
end;
{ S1 := S2 op S3 }
procedure TIntegerType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
case Op of
// binary ops
tkTimes:
PInteger(Result)^ := PInteger(Op1)^ * PInteger(Op2)^;
tkRWdiv:
PInteger(Result)^ := PInteger(Op1)^ div PInteger(Op2)^;
tkRWmod:
PInteger(Result)^ := PInteger(Op1)^ mod PInteger(Op2)^;
tkRWand:
PInteger(Result)^ := PInteger(Op1)^ and PInteger(Op2)^;
tkPlus:
PInteger(Result)^ := PInteger(Op1)^ + PInteger(Op2)^;
tkMinus:
PInteger(Result)^ := PInteger(Op1)^ - PInteger(Op2)^;
tkRWor:
PInteger(Result)^ := PInteger(Op1)^ or PInteger(Op2)^;
tkRWxor:
PInteger(Result)^ := PInteger(Op1)^ xor PInteger(Op2)^;
// rel ops
tkLT:
PBoolean(Result)^ := PInteger(Op1)^ < PInteger(Op2)^;
tkLE:
PBoolean(Result)^ := PInteger(Op1)^ <= PInteger(Op2)^;
tkGT:
PBoolean(Result)^ := PInteger(Op1)^ > PInteger(Op2)^;
tkGE:
PBoolean(Result)^ := PInteger(Op1)^ >= PInteger(Op2)^;
tkEqual:
PBoolean(Result)^ := PInteger(Op1)^ = PInteger(Op2)^;
tkNE:
PBoolean(Result)^ := PInteger(Op1)^ <> PInteger(Op2)^;
tkRWin:
PBoolean(Result)^ := PInteger(Op1)^ in PSetInteger(Op2)^;
// unary ops: Result := op Op1 (Op2 not used)
tkRWnot:
PInteger(Result)^ := not PInteger(Op1)^;
tkUnaryMinus:
PInteger(Result)^ := -PInteger(Op1)^;
// assign op
tkAssign:
PInteger(Result)^ := PInteger(Op1)^;
else
raise EInterpreterException.Create(sInvalidOperation, Prod.ProductionLine,
Prod.ProductionCol, Prod.Parser);
end;
end;
function TIntegerType.OrdinalValue(V: TSymbolInfo): Integer;
begin
Result := Ord(PInteger(V.Address)^);
end;
{ TExtendedType }
constructor TExtendedType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcExtended;
end;
function TExtendedType.GetSize: Integer;
begin
Result := SizeOf(Extended);
end;
function TExtendedType.GetAsString: String;
begin
Result := 'real';
end;
function TExtendedType.ValueAsString(V: TSymbolInfo): String;
begin
Result := FormatFloat(
SymbolTable.Compiler.FloatFormat, PExtended(V.Address)^);
end;
function TExtendedType.ValueThroughAddress(Address: Pointer): String;
begin
Result := FormatFloat(
SymbolTable.Compiler.FloatFormat, PExtended(Address)^);
end;
{ S1 := S2 op S3 }
procedure TExtendedType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
case Op of
// binary ops
tkTimes:
PExtended(Result)^ := PExtended(Op1)^ * PExtended(Op2)^;
tkSlash:
PExtended(Result)^ := PExtended(Op1)^ / PExtended(Op2)^;
tkPlus:
PExtended(Result)^ := PExtended(Op1)^ + PExtended(Op2)^;
tkMinus:
PExtended(Result)^ := PExtended(Op1)^ - PExtended(Op2)^;
// rel ops
tkLT:
PBoolean(Result)^ := PExtended(Op1)^ < PExtended(Op2)^;
tkLE:
PBoolean(Result)^ := PExtended(Op1)^ <= PExtended(Op2)^;
tkGT:
PBoolean(Result)^ := PExtended(Op1)^ > PExtended(Op2)^;
tkGE:
PBoolean(Result)^ := PExtended(Op1)^ >= PExtended(Op2)^;
tkEqual:
PBoolean(Result)^ := PExtended(Op1)^ = PExtended(Op2)^;
tkNE:
PBoolean(Result)^ := PExtended(Op1)^ <> PExtended(Op2)^;
// unary ops: Result := op Op1 (Op2 not used)
tkUnaryMinus:
PExtended(Result)^ := -PExtended(Op1)^;
// assign op
tkAssign:
PExtended(Result)^ := PExtended(Op1)^;
else
raise EInterpreterException.Create(sInvalidOperation, Prod.ProductionLine,
Prod.ProductionCol, Prod.Parser);
end;
end;
{ TBooleanType }
constructor TBooleanType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcBoolean;
end;
function TBooleanType.GetSize: Integer;
begin
Result := SizeOf(Boolean);
end;
function TBooleanType.GetAsString: String;
begin
Result := 'lógico';
end;
function TBooleanType.ValueAsString(V: TSymbolInfo): String;
begin
if PBoolean(V.Address)^ then
Result := 'sim'
else
Result := 'não';
end;
function TBooleanType.ValueThroughAddress(Address: Pointer): String;
begin
if PBoolean(Address)^ then
Result := 'sim'
else
Result := 'não';
end;
function TBooleanType.GetRange: Integer;
begin
Result := 2;
end;
function TBooleanType.GetMinValue: Integer;
begin
Result := 0;
end;
function TBooleanType.GetMaxValue: Integer;
begin
Result := 1;
end;
{ S1 := S2 op S3 }
procedure TBooleanType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
case Op of
// binary ops
tkRWand:
PBoolean(Result)^ := PBoolean(Op1)^ and PBoolean(Op2)^;
tkRWor:
PBoolean(Result)^ := PBoolean(Op1)^ or PBoolean(Op2)^;
tkRWxor:
PBoolean(Result)^ := PBoolean(Op1)^ xor PBoolean(Op2)^;
// rel ops
tkLT:
PBoolean(Result)^ := PBoolean(Op1)^ < PBoolean(Op2)^;
tkLE:
PBoolean(Result)^ := PBoolean(Op1)^ <= PBoolean(Op2)^;
tkGT:
PBoolean(Result)^ := PBoolean(Op1)^ > PBoolean(Op2)^;
tkGE:
PBoolean(Result)^ := PBoolean(Op1)^ >= PBoolean(Op2)^;
tkEqual:
PBoolean(Result)^ := PBoolean(Op1)^ = PBoolean(Op2)^;
tkNE:
PBoolean(Result)^ := PBoolean(Op1)^ <> PBoolean(Op2)^;
// unary ops: Result := op Op1 (Op2 not used)
tkRWnot:
PBoolean(Result)^ := not PBoolean(Op1)^;
// assign op
tkAssign:
PBoolean(Result)^ := PBoolean(Op1)^;
else
raise EInterpreterException.Create(sInvalidOperation, Prod.ProductionLine,
Prod.ProductionCol, Prod.Parser);
end;
end;
function TBooleanType.OrdinalValue(V: TSymbolInfo): Integer;
begin
Result := Ord(PBoolean(V.Address)^);
end;
{ TStringType }
constructor TStringType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcString;
end;
function TStringType.GetSize: Integer;
begin
Result := SizeOf(PString);
end;
function TStringType.GetAsString: String;
begin
Result := 'texto';
end;
function TStringType.ValueAsString(V: TSymbolInfo): String;
begin
// Result := PAnsiString(V.Address)^;
Result := PString(V.Address)^;
end;
function TStringType.ValueThroughAddress(Address: Pointer): String;
begin
Result := PString(Address)^;
end;
{ S1 := S2 op S3 }
procedure TStringType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
case Op of
// binary ops
tkPlus:
PString(Result)^ := PString(Op1)^ + PString(Op2)^;
// rel ops
tkLT:
PBoolean(Result)^ := PString(Op1)^ < PString(Op2)^;
tkLE:
PBoolean(Result)^ := PString(Op1)^ <= PString(Op2)^;
tkGT:
PBoolean(Result)^ := PString(Op1)^ > PString(Op2)^;
tkGE:
PBoolean(Result)^ := PString(Op1)^ >= PString(Op2)^;
tkEqual:
PBoolean(Result)^ := PString(Op1)^ = PString(Op2)^;
tkNE:
PBoolean(Result)^ := PString(Op1)^ <> PString(Op2)^;
// assign op
tkAssign:
PString(Result)^ := PString(Op1)^;
else
raise EInterpreterException.Create(sInvalidOperation, Prod.ProductionLine,
Prod.ProductionCol, Prod.Parser);
end;
end;
{ TCharType }
constructor TCharType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcChar;
end;
function TCharType.GetSize: Integer;
begin
Result := SizeOf(Char);
end;
function TCharType.GetAsString: String;
begin
Result := 'caractere';
end;
function TCharType.ValueAsString(V: TSymbolInfo): String;
begin
Result := PChar(V.Address)^;
end;
function TCharType.ValueThroughAddress(Address: Pointer): String;
begin
Result := PChar(Address)^;
end;
function TCharType.GetRange: Integer;
begin
Result := 256;
end;
function TCharType.GetMinValue: Integer;
begin
Result := 0;
end;
function TCharType.GetMaxValue: Integer;
begin
Result := 255;
end;
{ S1 := S2 op S3 }
procedure TCharType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
case Op of
// rel ops
tkLT:
PBoolean(Result)^ := PChar(Op1)^ < PChar(Op2)^;
tkLE:
PBoolean(Result)^ := PChar(Op1)^ <= PChar(Op2)^;
tkGT:
PBoolean(Result)^ := PChar(Op1)^ > PChar(Op2)^;
tkGE:
PBoolean(Result)^ := PChar(Op1)^ >= PChar(Op2)^;
tkEqual:
PBoolean(Result)^ := PChar(Op1)^ = PChar(Op2)^;
tkNE:
PBoolean(Result)^ := PChar(Op1)^ <> PChar(Op2)^;
// tkRWin:
// PBoolean(Result)^ := PChar(Op1)^ in PSetChar(Op2)^;
// assign op
tkAssign:
PChar(Result)^ := PChar(Op1)^;
else
raise EInterpreterException.Create(sInvalidOperation, Prod.ProductionLine,
Prod.ProductionCol, Prod.Parser);
end;
end;
function TCharType.OrdinalValue(V: TSymbolInfo): Integer;
begin
Result := Ord(PChar(V.Address)^);
end;
{ TEnumType }
constructor TEnumType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FEnums := TList.Create;
FTypeClass := tcEnum;
end;
destructor TEnumType.Destroy;
begin
FEnums.Free;
inherited Destroy;
end;
function TEnumType.GetSize: Integer;
begin
Result := SizeOf(Integer);
end;
function TEnumType.GetAsString: String;
begin
Result := 'enum';
end;
function TEnumType.ValueAsString(V: TSymbolInfo): String;
begin
Result := IntToStr(PInteger(V.Address)^);
end;
function TEnumType.ValueThroughAddress(Address: Pointer): String;
begin
Result := IntToStr(PInteger(Address)^);
end;
function TEnumType.GetRange: Integer;
begin
Result :=FEnums.Count;
end;
function TEnumType.GetMinValue: Integer;
begin
Result := 0;
end;
function TEnumType.GetMaxValue: Integer;
begin
Result := FEnums.Count - 1;
end;
{ S1 := S2 op S3 }
procedure TEnumType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
case Op of
// rel ops
tkLT:
PBoolean(Result)^ := PInteger(Op1)^ < PInteger(Op2)^;
tkLE:
PBoolean(Result)^ := PInteger(Op1)^ <= PInteger(Op2)^;
tkGT:
PBoolean(Result)^ := PInteger(Op1)^ > PInteger(Op2)^;
tkGE:
PBoolean(Result)^ := PInteger(Op1)^ >= PInteger(Op2)^;
tkEqual:
PBoolean(Result)^ := PInteger(Op1)^ = PInteger(Op2)^;
tkNE:
PBoolean(Result)^ := PInteger(Op1)^ <> PInteger(Op2)^;
tkRWin:
PBoolean(Result)^ := PInteger(Op1)^ in PSetInteger(Op2)^;
// assign op
tkAssign:
PInteger(Result)^ := PInteger(Op1)^;
else
raise EInterpreterException.Create(sInvalidOperation, Prod.ProductionLine,
Prod.ProductionCol, Prod.Parser);
end;
end;
function TEnumType.OrdinalValue(V: TSymbolInfo): Integer;
begin
Result := Ord(PInteger(V.Address)^);
end;
{ TSubrangeType }
constructor TSubrangeType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcSubrange;
end;
function TSubrangeType.GetSize: Integer;
begin
Result := FBaseType.GetSize;
end;
function TSubrangeType.GetAsString: String;
begin
Result := 'subRange(' + FBaseType.GetAsString + ')';
end;
function TSubrangeType.ValueAsString(V: TSymbolInfo): String;
begin
Result := FBaseType.ValueAsString(V);
end;
function TSubrangeType.ValueThroughAddress(Address: Pointer): String;
begin
Result := FBaseType.ValueThroughAddress(Address);
end;
function TSubrangeType.GetRange: Integer;
begin
if FBaseType is TCharType then
Result := Ord(PChar(FSup.Address)^) - Ord(PChar(FInf.Address)^) + 1
else
Result := PInteger(FSup.Address)^ - PInteger(FInf.Address)^; // + 1;
end;
function TSubrangeType.GetMinValue: Integer;
begin
if FBaseType is TCharType then
Result := Ord(PChar(FInf.Address)^)
else
Result := PInteger(FInf.Address)^;
end;
function TSubrangeType.GetMaxValue: Integer;
begin
if FBaseType is TCharType then
Result := Ord(PChar(FSup.Address)^)
else
Result := PInteger(FSup.Address)^ - 1;
end;
procedure TSubrangeType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
FBaseType.Oper(Result, Op1, Op2, Op, Prod);
end;
function TSubrangeType.OrdinalValue(V: TSymbolInfo): Integer;
begin
Result := Ord(PInteger(V.Address)^);
end;
{ TSetType }
constructor TSetType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcSet;
end;
function TSetType.GetSize: Integer;
begin
Result := 32; // greatest size (provisory)
end;
function TSetType.GetAsString: String;
begin
Result := 'conjunto(' + FBaseType.GetAsString + ')';
end;
function TSetType.ValueAsString(V: TSymbolInfo): String;
var
P: PSetInteger;
I: Integer;
begin
Result := '[';
P := PSetInteger(V.Address);
for I := 0 to 255 do
if I in P^ then
Result := Result + IntToStr(I) + ',';
if Result[Length(Result)] = ',' then
Delete(Result, Length(Result), 1);
Result := Result + ']';
end;
function TSetType.ValueThroughAddress(Address: Pointer): String;
var
P: PSetInteger;
I: Integer;
begin
Result := '[';
P := PSetInteger(Address);
for I := 0 to 255 do
if I in P^ then
Result := Result + IntToStr(I) + ',';
if Result[Length(Result)] = ',' then
Delete(Result, Length(Result), 1);
Result := Result + ']';
end;
procedure TSetType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
case Op of
// binary ops
tkTimes:
PSetInteger(Result)^ := PSetInteger(Op1)^ * PSetInteger(Op2)^;
tkPlus:
PSetInteger(Result)^ := PSetInteger(Op1)^ + PSetInteger(Op2)^;
tkMinus:
PSetInteger(Result)^ := PSetInteger(Op1)^ - PSetInteger(Op2)^;
// rel ops
tkLE:
PBoolean(Result)^ := PSetInteger(Op1)^ <= PSetInteger(Op2)^;
tkGE:
PBoolean(Result)^ := PSetInteger(Op1)^ >= PSetInteger(Op2)^;
tkEqual:
PBoolean(Result)^ := PSetInteger(Op1)^ = PSetInteger(Op2)^;
tkNE:
PBoolean(Result)^ := PSetInteger(Op1)^ <> PSetInteger(Op2)^;
// assign op
tkAssign:
PSetInteger(Result)^ := PSetInteger(Op1)^;
else
raise EInterpreterException.Create(sInvalidOperation, Prod.ProductionLine,
Prod.ProductionCol, Prod.Parser);
end;
end;
{ TArrayType }
constructor TArrayType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcArray;
end;
function TArrayType.GetSize: Integer;
begin
Result := FElemSymbol.SymbolType.Size *
TOrdinalType(FIndexSymbol.SymbolType).Range;
{ acrescenta a área que guarda o tamanho do array }
// Result := Result + TSymbolTable.SizeOfArraySize();
end;
function TArrayType.GetAsString: String;
begin
Result := 'arranjo [' + FIndexSymbol.SymbolType.AsString + '] de ' +
FElemSymbol.SymbolType.AsString;
end;
function TArrayType.ValueAsString(V: TSymbolInfo): String;
begin
Result := '... (ainda não implementado)';
end;
function TArrayType.ValueThroughAddress(Address: Pointer): String;
begin
Result := '... (ainda não implementado)';
end;
procedure TArrayType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
case Op of
// assign op
tkAssign:
Move(PByte(Op1)^, PByte(Result)^, Size);
else
raise EInterpreterException.Create(sInvalidOperation, Prod.ProductionLine,
Prod.ProductionCol, Prod.Parser);
end;
end;
{ TRecordType }
constructor TRecordType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcRecord;
end;
destructor TRecordType.Destroy;
begin
FFieldList.Free;
inherited Destroy;
end;
function TRecordType.GetSize: Integer;
begin
Result := FSize;
end;
function TRecordType.GetAsString: String;
var
I: Integer;
begin
Result := 'registro (';
for I := 0 to FFieldList.Count - 1 do
Result := Result + TSymbolInfo(FFieldList[I]).SymbolType.AsString + ',';
Delete(Result, Length(Result), 1);
Result := Result + ')';
end;
function TRecordType.ValueAsString(V: TSymbolInfo): String;
begin
Result := '... (ainda não implementado)';
end;
function TRecordType.ValueThroughAddress(Address: Pointer): String;
begin
Result := '... (ainda não implementado)';
end;
procedure TRecordType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
case Op of
// assign op
tkAssign:
Move(PByte(Op1)^, PByte(Result)^, Size);
else
raise EInterpreterException.Create(sInvalidOperation, Prod.ProductionLine,
Prod.ProductionCol, Prod.Parser);
end;
end;
{ TPointerType }
constructor TPointerType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcPointer;
end;
function TPointerType.GetSize: Integer;
begin
Result := SizeOf(Pointer);
end;
function TPointerType.GetAsString: String;
begin
if FBaseType <> nil then
Result := 'ponteiro (' + FBaseType.AsString + ')'
else
Result := 'ponteiro';
end;
function TPointerType.ValueAsString(V: TSymbolInfo): String;
var
P: Integer;
begin
P := Integer(V.Address^);
Result := IntToStr(P);
end;
function TPointerType.ValueThroughAddress(Address: Pointer): String;
var
P: Integer;
begin
P := Integer(Address^);
Result := IntToStr(P);
end;
procedure TPointerType.Oper(Result, Op1, Op2: Pointer; Op: TToken; Prod: TProduction);
begin
case Op of
// rel ops
tkEqual:
PBoolean(Result)^ := PPointer(Op1)^ = PPointer(Op2)^;
tkNE:
PBoolean(Result)^ := PPointer(Op1)^ <> PPointer(Op2)^;
// assign op
tkAssign:
PInteger(Result)^ := PInteger(Op1)^;
else
raise EInterpreterException.Create(sInvalidOperation, Prod.ProductionLine,
Prod.ProductionCol, Prod.Parser);
end;
end;
{ TProcedureType }
constructor TProcedureType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcProcedure;
end;
function TProcedureType.GetSize: Integer;
begin
Result := 0;
end;
function TProcedureType.GetAsString: String;
begin
Result := 'procedimento';
end;
function TProcedureType.ValueAsString(V: TSymbolInfo): String;
begin
Result := '';
end;
function TProcedureType.ValueThroughAddress(Address: Pointer): String;
begin
Result := '';
end;
{ TFunctionType }
constructor TFunctionType.Create(SymbolTable: TSymbolTable);
begin
inherited Create(SymbolTable);
FTypeClass := tcFunction;
end;
function TFunctionType.GetSize: Integer;
begin
Result := 0;
end;
function TFunctionType.GetAsString: String;
begin
Result := 'função';
end;
function TFunctionType.ValueAsString(V: TSymbolInfo): String;
begin
Result := '';
end;
function TFunctionType.ValueThroughAddress(Address: Pointer): String;
begin
Result := '';
end;
{ TSymbolInfo }
constructor TSymbolInfo.Create(SymbolTable: TSymbolTable;
SymbolClass: TSymbolClass; SymbolType: TSymbolType);
begin
inherited Create;
FSymbolTable := SymbolTable;
FSymbolClass := SymbolClass;
FSymbolType := SymbolType;
// FNameIndex := -1;
FName := '';
end;
procedure TSymbolInfo.Assign(Value: TSymbolInfo);
begin
FSymbolClass := Value.SymbolClass;
FSymbolTable := Value.SymbolTable;
FSymbolType := Value.SymbolType;
FOffset := Value.FOffset;
FName := Value.Name;
FRecordType := Value.RecordType;
end;
function TSymbolInfo.GetAddress: Pointer;
begin
case SymbolClass of
scConst:
Result := PByte(SymbolTable.FConstArea) + FOffset;
scVar:
Result := PByte(SymbolTable.FVarArea.Last) + FOffset;
scPointer:
Result := Pointer(FOffset);
scVarParam:
begin
Result := PByte(SymbolTable.FVarArea.Last) + FOffset;
Result := PByte(Result^);
end;
else
raise EInterpreterException.Create(sGetAddress, 1, 1, nil);
end;
end;
function TSymbolInfo.GetVarParamAddress: Pointer;
begin
// retorna o endereço, sem derreferenciar o ponteiro
Result := PByte(SymbolTable.FVarArea.Last) + FOffset;
end;
function TSymbolInfo.GetAsString: String;
begin
Result := '';
case SymbolClass of
scConst: Result := 'const ';
scVar: Result := 'var ';
scType: Result := 'tipo ';
scField: Result := 'campo ';
scProcedure: Result := 'procedimento';
scFunction: Result := 'função ';
scVarParam: Result := 'var param ';
else
Result := 'desconhecido!!!';
end;
if SymbolType <> nil then
Result := Result + SymbolType.AsString;
if SymbolClass in [scVar, scConst] then
Result := Result + ' ' + SymbolType.ValueAsString(Self);
end;
{ TSymbolTable }
constructor TSymbolTable.Create(Compiler: TCompiler);
begin
inherited Create;
FCompiler := Compiler;
FTable := TStringList.Create;
FTable.CaseSensitive := True;
// FTable.Sorted := True;
FTable.CaseSensitive := True;
FNewTables := TList.Create;
FInfos := TList.Create;
FTypes := TList.Create;
FScope := TList.Create;
FVarArea := TList.Create;
FPendentPointer := TList.Create;
FForwards := TList.Create;
FScope.Add(Self);
end;
destructor TSymbolTable.Destroy;
var
I: Integer;
begin
for I := 0 to FNewTables.Count - 1 do
TSymbolTable(FNewTables[I]).Free;
FNewTables.Free;
for I := 0 to FInfos.Count - 1 do
TSymbolInfo(FInfos[I]).Free;
FInfos.Free;
for I := 0 to FTypes.Count - 1 do
TSymbolType(FTypes[I]).Free;
FTypes.Free;
FScope.Free;
if FConstArea <> nil then
Compiler.Heap.FreeMem(FConstArea);
// FreeMem(FConstArea);
for I := 0 to FVarArea.Count - 1 do
Compiler.Heap.FreeMem(FVarArea[I]);
// FreeMem(FVarArea[I]);
FVarArea.Free;
FPendentPointer.Free;
FForwards.Free;
FTable.Free;
inherited Destroy;
end;
{ Returns pointer to Name's info or nil if Name not in table }
function TSymbolTable.FindSymbol(Name: String): TSymbolInfo;
var
I, Ind: Integer;
T: TSymbolTable;
begin
// special case when evaluating
if csEvaluating in Compiler.State then
begin
Result := Compiler.FindSymbol(Name);
Exit;
end;
Result := nil;
for I := FScope.Count - 1 downto 0 do
begin
T := TSymbolTable(FScope[I]);
Ind := T.FTable.IndexOf(Name);
if Ind >= 0 then
begin
Result := TSymbolInfo(T.FTable.Objects[Ind]);
// verifica se o módulo associado foi previamente incluído
// obs: se a símbolo é associado a MODL_PAC, considera ok,
// pois é como se fosse da linguagem
if (Result <> nil) {teste de segurança, pois nunca deveria ser!} and
(Result.StandardModule <> MODL_PAC) and
(Compiler.FModlList.IndexOf(Result.StandardModule) < 0) then
Result := nil;
Exit;
end;
// Search for redeclaration must stop when compiling record fields or
// subroutine params and local variables
if csFindInScope in Compiler.State then
Break;
end;
end;
{ Returns pointer to new info structure for Name }
function TSymbolTable.Enter(Name: String; SymbolClass: TSymbolClass;
SymbolType: TSymbolType; StdModule: String): TSymbolInfo;
begin
Result := AllocSymbolInfo(SymbolClass, SymbolType);
Result.SymbolTable.FTable.AddObject(Name, Result);
Result.FName := Name;
Result.StandardModule := StdModule;
end;
{ Returns a new symbol info structure }
function TSymbolTable.AllocSymbolInfo(SymbolClass: TSymbolClass;
SymbolType: TSymbolType): TSymbolInfo;
var
T: TSymbolTable;
I: Integer;
begin
T := FScope.Last;
if SymbolClass <> scField then
begin
// look for last natural (not record) scope
for I := FScope.Count - 1 downto 0 do
if not TSymbolTable(FScope[I]).IsRecordScope then
Break;
T := FScope[I];
end;
Result := TSymbolInfo.Create(T, SymbolClass, SymbolType);
T.FInfos.Add(Result);
case SymbolClass of
scConst:
begin
Result.FOffset := T.FConstOffset;
Inc(T.FConstOffset, SymbolType.Size);
if T.FConstArea = nil then
T.FConstArea := Compiler.Heap.AllocMem(T.FConstOffset)
else
T.FConstArea := Compiler.Heap.ReallocMem(T.FConstArea, T.FConstOffset);
if T.FConstArea = nil then
Compiler.Error(sOutOfMemory);
// ReallocMem(T.FConstArea, T.FConstOffset);
end;
scVar, scField:
begin
Result.FOffset := T.FVarOffset;
Inc(T.FVarOffset, SymbolType.Size);
end;
scVarParam:
begin
Result.FOffset := T.FVarOffset;
Inc(T.FVarOffset, SizeOf(Pointer));
end;
end;
end;
function TSymbolTable.AllocType(TypeClass: TSymbolTypeClass): TSymbolType;
begin
Result := TypeClass.Create(Self);
FTypes.Add(Result);
end;
function TSymbolTable.NewSymbolTable: TSymbolTable;
begin
Result := TSymbolTable.Create(Compiler);
FNewTables.Add(Result);
end;
procedure TSymbolTable.AddScope(SymbolTable: TSymbolTable);
begin
FScope.Add(SymbolTable);
end;
procedure TSymbolTable.RemoveScope;
begin
FScope.Delete(FScope.Count - 1);
end;
procedure TSymbolTable.ShowMemArray(VName: String; VType: TSymbolType;
VAddr: Integer; Global: Boolean);
var
Ref: String;
I, Ind1, Ind2, ElemSize: Integer;
begin
Ind1 := TOrdinalType(TArrayType(VType).FIndexSymbol.SymbolType).MinValue;
Ind2 := TOrdinalType(TArrayType(VType).FIndexSymbol.SymbolType).MaxValue;
ElemSize := TArrayType(VType).FElemSymbol.SymbolType.Size;
{ acrescenta área para o tamanho do array }
// VAddr := VAddr + SizeOfArraySize();
for I := Ind1 to Ind2 do
begin
Ref := VName + '[' + IntToStr(I) + ']';
ShowMem(Ref, TArrayType(VType).FElemSymbol.SymbolType, VAddr, Global);
VAddr := VAddr + ElemSize;
end;
end;
procedure TSymbolTable.ShowMemRecord(VName: String; VType: TSymbolType;
VAddr: Integer; Global: Boolean);
var
Ref: String;
I: Integer;
Si: TSymbolInfo;
begin
for I := 0 to TRecordType(VType).FFieldList.Count - 1 do
begin
Si := TSymbolInfo(TRecordType(VType).FFieldList[I]);
Ref := VName + '.' + Si.Name;
ShowMem(Ref, Si.SymbolType, VAddr, Global);
VAddr := VAddr + Si.SymbolType.Size;
end;
end;
procedure TSymbolTable.ShowMem(VName: String; VType: TSymbolType;
VAddr: Integer; Global: Boolean);
begin
if not FrmDSL.PnlMemoria.Visible then
Exit;
if VType.TypeClass = tcArray then
ShowMemArray(VName, VType, VAddr, Global)
else if VType.TypeClass = tcRecord then
ShowMemRecord(VName, VType, VAddr, Global)
else begin
FrmMemoria.IncluiVar(VName, VAddr, Global);
if VType is TPointerType then
MarkAsPointer(VAddr);
end;
end;
procedure TSymbolTable.DisposeArray(VType: TSymbolType; VAddr: Integer);
var
I, Ind1, Ind2, ElemSize: Integer;
begin
Ind1 := TOrdinalType(TArrayType(VType).FIndexSymbol.SymbolType).MinValue;
Ind2 := TOrdinalType(TArrayType(VType).FIndexSymbol.SymbolType).MaxValue;
ElemSize := TArrayType(VType).FElemSymbol.SymbolType.Size;
{ acrescenta área para o tamanho do array }
// VAddr := VAddr + SizeOfArraySize();
for I := Ind1 to Ind2 do
begin
DisposeHeap(TArrayType(VType).FElemSymbol.SymbolType, VAddr);
VAddr := VAddr + ElemSize;
end;
end;
procedure TSymbolTable.DisposeRecord(VType: TSymbolType; VAddr: Integer);
var
I: Integer;
Si: TSymbolInfo;
begin
for I := 0 to TRecordType(VType).FFieldList.Count - 1 do
begin
Si := TSymbolInfo(TRecordType(VType).FFieldList[I]);
DisposeHeap(Si.SymbolType, VAddr);
VAddr := VAddr + Si.SymbolType.Size;
end;
end;
procedure TSymbolTable.DisposeHeap(VType: TSymbolType; VAddr: Integer);
begin
if not FrmDSL.PnlMemoria.Visible then
Exit;
if VType.TypeClass = tcArray then
DisposeArray(VType, VAddr)
else if VType.TypeClass = tcRecord then
DisposeRecord(VType, VAddr)
else
FrmMemoria.ExcluiVar(VAddr);
end;
procedure TSymbolTable.UpdateMem(VType: TSymbolType; VAddr: Integer);
begin
if not FrmDSL.PnlMemoria.Visible then
Exit;
if VType.TypeClass = tcArray then
UpdateMemArray(VType, VAddr)
else if VType.TypeClass = tcRecord then
UpdateMemRecord(VType, VAddr)
else
FrmMemoria.AtualizaVar(VAddr, VType.ValueThroughAddress(Pointer(VAddr)));
end;
procedure TSymbolTable.UpdateMemArray(VType: TSymbolType; VAddr: Integer);
var
I, Ind1, Ind2, ElemSize: Integer;
begin
Ind1 := TOrdinalType(TArrayType(VType).FIndexSymbol.SymbolType).MinValue;
Ind2 := TOrdinalType(TArrayType(VType).FIndexSymbol.SymbolType).MaxValue;
ElemSize := TArrayType(VType).FElemSymbol.SymbolType.Size;
{ acrescenta área para o tamanho do array }
// VAddr := VAddr + SizeOfArraySize();
for I := Ind1 to Ind2 do
begin
UpdateMem(TArrayType(VType).FElemSymbol.SymbolType, VAddr);
VAddr := VAddr + ElemSize;
end;
end;
procedure TSymbolTable.UpdateMemRecord(VType: TSymbolType; VAddr: Integer);
var
I: Integer;
Si: TSymbolInfo;
begin
for I := 0 to TRecordType(VType).FFieldList.Count - 1 do
begin
Si := TSymbolInfo(TRecordType(VType).FFieldList[I]);
UpdateMem(Si.SymbolType, VAddr);
VAddr := VAddr + Si.SymbolType.Size;
end;
end;
procedure TSymbolTable.ShowMemCleared;
begin
if not FrmDSL.PnlMemoria.Visible then
Exit;
FrmMemoria.Limpa;
end;
procedure TSymbolTable.MarkAsPointer(VAddr: Integer);
begin
if not FrmDSL.PnlMemoria.Visible then
Exit;
FrmMemoria.MarcaComoPonteiro(VAddr);
end;
procedure TSymbolTable.ChangeAddress(OldAddr, NewAddr: Integer);
begin
if not FrmDSL.PnlMemoria.Visible then
Exit;
FrmMemoria.MudaEnder(OldAddr, NewAddr);
end;
procedure TSymbolTable.UpdateVarParam(VAddr: Integer; Value: String);
begin
if not FrmDSL.PnlMemoria.Visible then
Exit;
FrmMemoria.AtualizaVar(VAddr, Value);
end;
procedure TSymbolTable.ShowMemActivation;
var
I: Integer;
Si: TSymbolInfo;
begin
if not FrmDSL.PnlMemoria.Visible then
Exit;
// nada a fazer quando estiver avaliando expressão monitorada
if csEvaluating in Compiler.State then
Exit;
for I := 0 to FTable.Count - 1 do
begin
Si := TSymbolInfo(FTable.Objects[I]);
if Si.SymbolClass in [scVar, scPointer] then
ShowMem(FTable[I], Si.SymbolType, Integer(Si.Address), True)
else if Si.SymbolClass = scVarParam then
FrmMemoria.IncluiVar(FTable[I], Integer(Si.VarParamAddress), True);
end;
end;
{ Inicializa o tamanho das áreas com array }
procedure TSymbolTable.InitArraySize(Mem: Pointer);
var
I: Integer;
Si: TSymbolInfo;
begin
for I := 0 to FTable.Count - 1 do
begin
Si := TSymbolInfo(FTable.Objects[I]);
if (Si.FSymbolType is TArrayType) then
begin
Mem := Pointer(Integer(Mem) + Si.FOffset);
PInteger(Mem)^ := TArrayType(Si.FSymbolType).Size;
end;
end;
end;
class function TSymbolTable.SizeOfArraySize: Integer;
begin
Result := SizeOf(Integer);
end;
procedure TSymbolTable.ShowSubroutineCall(Name: String);
begin
if not FrmDSL.PnlMemoria.Visible then
Exit;
FrmMemoria.IncluiSubrotina(Name);
end;
procedure TSymbolTable.ShowSubroutineReturn;
begin
if not FrmDSL.PnlMemoria.Visible then
Exit;
FrmMemoria.LiberaUltimoEscopo;
end;
procedure TSymbolTable.SetActivation;
var
P1, P2: Pointer;
begin
P1 := Compiler.Heap.AllocMem(FVarOffset);
if P1 = nil then
Compiler.Error(sOutOfMemory);
FVarArea.Add(P1);
if FVarArea.Count > 1 then
begin // copy old area (for solving 'var parameters as arguments' problem)
P2 := FVarArea[FVarArea.Count - 2];
Move(PByte(P2)^, PByte(P1)^, FVarOffset);
end;
end;
procedure TSymbolTable.LibActivation;
begin
Compiler.Heap.FreeMem(FVarArea.Last);
FVarArea.Delete(FVarArea.Count - 1);
end;
function TSymbolTable.DuplicateSymbolInfo(Symbol: TSymbolInfo): TSymbolInfo;
begin
Result := TSymbolInfo.Create(Symbol.SymbolTable, Symbol.SymbolClass,
Symbol.SymbolType);
Result.Assign(Symbol);
// Move(PChar(Symbol)^, PChar(Result)^, TSymbolInfo.InstanceSize);
FInfos.Add(Result);
end;
procedure TSymbolTable.CheckPendentPointers;
var
T: TSymbolTable;
I: Integer;
P: TProd_TypeDecl;
SiType: TSymbolInfo;
SiBaseType: TSymbolInfo;
begin
T := TSymbolTable(FScope.Last);
for I := 0 to T.FPendentPointer.Count - 1 do
begin
P := T.FPendentPointer[I];
SiType := FindSymbol(P.FTypeId);
if SiType = nil then
P.Error(sCheckPendentPointersError, 0, 0);
SiBaseType := FindSymbol(P.FBaseTypeId);
if SiBaseType = nil then
P.Error(Format(sUndeclaredIdentifier, [P.FBaseTypeId]),
P.ProductionLine, P.ProductionCol);
TPointerType(SiType.SymbolType).FBaseType := SiBaseType.SymbolType;
end;
T.FPendentPointer.Clear;
end;
procedure TSymbolTable.AddPendentPointer(P: TProduction);
var
T: TSymbolTable;
begin
T := TSymbolTable(FScope.Last);
T.FPendentPointer.Add(P);
end;
function TSymbolTable.LookForForward(Id: String): TProduction;
var
I: Integer;
S: String;
begin
Result := nil;
for I := 0 to FForwards.Count - 1 do
begin
Result := FForwards[I];
if Result is TProd_Procedure then
S := TProd_Procedure(Result).FProcId
else
S := TProd_Function(Result).FFuncId;
// if AnsiUpperCase(Id) = AnsiUpperCase(S) then
if Id = S then
Exit;
end;
end;
//procedure TSymbolTable.CheckForwards;
//var
// I: Integer;
// P: TProduction;
// Nok: Boolean;
//begin
// Nok := False;
// for I := 0 to FForwards.Count - 1 do
// begin
// P := FForwards[I];
// if P is TProd_Procedure then
// begin
// if TProd_Procedure(P).FBlock = nil then
// Nok := True;
// end
// else
// if TProd_Function(P).FBlock = nil then
// Nok := True;
// if Nok then
// P.Error(sUnsatisfiedForward, P.ProductionLine, P.ProductionCol);
// end;
// FForwards.Clear;
//end;
procedure TSymbolTable.AddForward(P: TProduction);
begin
FForwards.Add(P);
end;
procedure TSymbolTable.ShowTable(S: TStrings);
var
I: Integer;
Str: String;
begin
for I := 0 to FTable.Count - 1 do
begin
Str := FTable[I] + ' ' + TSymbolInfo(FTable.Objects[I]).AsString;
S.Add(Str);
end;
end;
{ TCompiler }
function TCompiler.Compile(Source: String;
ProductionClass: TProductionClass): TProduction;
begin
// libera o anterior e cria novo parser
if FParser <> nil then
FParser.Free;
FParser := TPascalTokenizer.Create(Source, ProgramName);
// limpa a lista de arquivos incluídos
FIncludeList.Clear;
FModlList.Clear;
// compila
FProduction := ProductionClass.Create(Self);
FProduction.FProductionLine := Parser.TokenLine;
FProduction.FProductionCol := Parser.TokenCol;
FProduction.Parse;
FProduction.FProductionEndLine := Parser.TokenLine;
FProduction.FProductionEndCol := Parser.TokenCol;
Result := FProduction;
end;
constructor TCompiler.Create;
begin
inherited Create;
FFloatFormat := '0.0#########';
FHeap := THeap.Create(Default_Heap_Min, Default_Heap_Max);
if FHeap.Handle = 0 then
Error(sHeapError);
FSymbolTable := TSymbolTable.Create(Self);
FParserStack := TList.Create;
FIncludeList := TStringList.Create;
FIncludeList.CaseSensitive := True;
FModlList := TStringList.Create;
FModlList.CaseSensitive := True;
// lista de bitmaps (dsl_quadroXXX) usados no programa
FBitmapList := TList.Create;
FBitmapList.Capacity := 1000;
// lista de streams (leitores ou escritores)
FStreamList := TList.Create;
// lista de TQuadro
FTQuadroList := TList.Create;
// lista de TMediaPlayers
FTMediaPlayerList := TList.Create;
// lista de componentes
// FCompList := TList.Create;
InitializeSymbolTable;
end;
destructor TCompiler.Destroy;
begin
FParser.Free;
FProduction.Free;
FSymbolTable.Free;
FHeap.Free;
FParserStack.Free;
FIncludeList.Free;
FModlList.Free;
DestroyBitmaps;
FBitmapList.Free;
// destrói CompList ANTES de TQuadroList
// DestroyCompList;
// FCompList.Free;
DestroyTQuadroList;
FTQuadroList.Free;
DestroyTMediaPlayerList;
FTMediaPlayerList.Free;
DestroyStreams;
FStreamList.Free;
FTela.Free;
inherited Destroy;
end;
function TCompiler.Compile(Source: TStream;
ProductionClass: TProductionClass): TProduction;
begin
// registra o stream principal
FSource := Source;
// libera o anterior e cria novo parser
if FParser <> nil then
FParser.Free;
FParser := TPascalTokenizer.Create(Source, ProgramName);
// limpa a lista de arquivos incluídos
FIncludeList.Clear;
FModlList.Clear;
// compila
FProduction := ProductionClass.Create(Self);
FProduction.FProductionLine := Parser.TokenLine;
FProduction.FProductionCol := Parser.TokenCol;
FProduction.Parse;
FProduction.FProductionEndLine := Parser.TokenLine;
FProduction.FProductionEndCol := Parser.TokenCol;
Result := FProduction;
end;
procedure TCompiler.Interpret;
begin
SymbolTable.ShowMemCleared;
SymbolTable.SetActivation;
SetProgramSymbolTable(SymbolTable);
SymbolTable.ShowMemActivation;
FProduction.Interpret;
end;
procedure TCompiler.Stop;
begin
FTerminate := True;
end;
procedure TCompiler.ShowSyntaxTree(S: TStrings);
begin
S.Clear;
FProduction.ShowSyntaxTree(S);
end;
procedure TCompiler.ShowSymbolTable(S: TStrings);
begin
S.Clear;
if FProgramSymbolTable <> nil then
FProgramSymbolTable.ShowTable(S);
if FSubroutineSymbolTable <> nil then
begin
S.Add('---');
FProgramSymbolTable.ShowTable(S);
end;
end;
procedure TCompiler.InitializeSymbolTable;
var
Symbol: TSymbolInfo;
begin
// Integer
FDeclTypeInteger := SymbolTable.AllocType(TIntegerType);
SymbolTable.Enter('inteiro', scType, FDeclTypeInteger, MODL_PAC);
// Extended
FDeclTypeExtended := SymbolTable.AllocType(TExtendedType);
SymbolTable.Enter('real', scType, FDeclTypeExtended, MODL_PAC);
// Boolean
FDeclTypeBoolean := SymbolTable.AllocType(TBooleanType);
SymbolTable.Enter('lógico', scType, FDeclTypeBoolean, MODL_PAC);
// String
FDeclTypeString := SymbolTable.AllocType(TStringType);
SymbolTable.Enter('texto', scType, FDeclTypeString, MODL_PAC);
// Char
FDeclTypeChar := SymbolTable.AllocType(TCharType);
SymbolTable.Enter('caractere', scType, FDeclTypeChar, MODL_PAC);
// Pointer
FDeclTypePointer := SymbolTable.AllocType(TPointerType);
SymbolTable.Enter('ponteiro', scType, FDeclTypePointer, MODL_PAC);
// nil
Symbol := SymbolTable.Enter('nulo', scConst, FDeclTypePointer, MODL_PAC);
PPointer(Symbol.Address)^ := nil;
// True
Symbol := SymbolTable.Enter('verdadeiro', scConst, FDeclTypeBoolean, MODL_PAC);
PBoolean(Symbol.Address)^ := True;
// False
Symbol := SymbolTable.Enter('falso', scConst, FDeclTypeBoolean, MODL_PAC);
PBoolean(Symbol.Address)^ := False;
// Sim
Symbol := SymbolTable.Enter('sim', scConst, FDeclTypeBoolean, MODL_PAC);
PBoolean(Symbol.Address)^ := True;
// Não
Symbol := SymbolTable.Enter('não', scConst, FDeclTypeBoolean, MODL_PAC);
PBoolean(Symbol.Address)^ := False;
// Pi
Symbol := SymbolTable.Enter('PI', scConst, FDeclTypeExtended, MODL_MAT);
PExtended(Symbol.Address)^ := PI;
// Janela e demais componentes
SymbolTable.Enter('janela', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('botão', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('rótulo', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('editor_lin', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('editor_txt', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('caixa_marca', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('caixa_escolha', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('caixa_lista', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('caixa_comb', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('caixa_grupo', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('quadro', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('imagem', scType, FDeclTypeInteger, MODL_GRA);
SymbolTable.Enter('som', scType, FDeclTypeInteger, MODL_MM);
// dsl_TipoQuadro
// SymbolTable.Enter('gra_TipoQuadro', scType, FDeclTypeInteger, MODL_GRA);
// dsl_TipoArquivo
// SymbolTable.Enter('dsl_TipoArquivo', scType, FDeclTypeInteger, MODL_ARQ);
// dsl_TipoLeitor
// SymbolTable.Enter('dsl_TipoLeitor', scType, FDeclTypeInteger, MODL_ARQ);
// dsl_TipoEscritor
// SymbolTable.Enter('dsl_TipoEscritor', scType, FDeclTypeInteger, MODL_ARQ);
// clAqua
Symbol := SymbolTable.Enter('COR_AZUL_CLARO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clAqua;
// clBlack
Symbol := SymbolTable.Enter('COR_PRETO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clBlack;
Symbol := SymbolTable.Enter('COR_PRETA', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clBlack;
// clBlue
Symbol := SymbolTable.Enter('COR_AZUL', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clBlue;
// clDkGray
Symbol := SymbolTable.Enter('COR_CINZA_ESCURO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clDkGray;
// cl Fuchsia
Symbol := SymbolTable.Enter('COR_FUCHSIA', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clFuchsia;
// clGray
Symbol := SymbolTable.Enter('COR_CINZA', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clGray;
// clGreen
Symbol := SymbolTable.Enter('COR_VERDE', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clGreen;
// clLime
Symbol := SymbolTable.Enter('COR_VERDE_CLARO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clLime;
// clLtGray
Symbol := SymbolTable.Enter('COR_CINZA_CLARO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clLtGray;
// clMaroon
Symbol := SymbolTable.Enter('COR_MARROM', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clMaroon;
// clNavy
Symbol := SymbolTable.Enter('COR_AZUL_MARINHO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clNavy;
// clOlive
Symbol := SymbolTable.Enter('COR_OLIVA', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clOlive;
// clPurple
Symbol := SymbolTable.Enter('COR_VIOLETA', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clPurple;
// clRed
Symbol := SymbolTable.Enter('COR_VERMELHO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clRed;
Symbol := SymbolTable.Enter('COR_VERMELHA', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clRed;
// clSilver
Symbol := SymbolTable.Enter('COR_PRATA', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clSilver;
// clTeal
Symbol := SymbolTable.Enter('COR_TEAL', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clTeal;
// clWhite
Symbol := SymbolTable.Enter('COR_BRANCO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clWhite;
Symbol := SymbolTable.Enter('COR_BRANCA', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clWhite;
// clYellow
Symbol := SymbolTable.Enter('COR_AMARELO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clYellow;
Symbol := SymbolTable.Enter('COR_AMARELA', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := clYellow;
// evento EV_MOUSE_CLICK
Symbol := SymbolTable.Enter('EV_CLIQUE', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_MOUSE_CLICK;
// evento EV_MOUSE_MOVE
Symbol := SymbolTable.Enter('EV_MOV_MOUSE', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_MOUSE_MOVE;
// evento EV_MOUSE_DOWN
Symbol := SymbolTable.Enter('EV_MOUSE_BAIXO', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_MOUSE_DOWN;
// evento EV_MOUSE_UP
Symbol := SymbolTable.Enter('EV_MOUSE_CIMA', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_MOUSE_UP;
// botão do mouse (BM_DIREITO)
Symbol := SymbolTable.Enter('BM_DIREITO', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_DIR;
// botão do mouse (BM_ESQUERDO)
Symbol := SymbolTable.Enter('BM_ESQUERDO', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_ESQ;
// evento EV_SHIFT
Symbol := SymbolTable.Enter('EV_SHIFT', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_SHIFT;
// evento EV_ALT
Symbol := SymbolTable.Enter('EV_ALT', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_ALT;
// evento EV_CTRL
Symbol := SymbolTable.Enter('EV_CTRL', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_CTRL;
// evento EV_KEYBOARD
Symbol := SymbolTable.Enter('EV_TECLADO', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_KEYBOARD;
// evento EV_TIME
Symbol := SymbolTable.Enter('EV_TEMPO', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_TIME;
// evento EV_RESIZE
Symbol := SymbolTable.Enter('EV_TAMANHO_DA_TELA', scConst, FDeclTypeInteger, MODL_EVNT);
PInteger(Symbol.Address)^ := EV_RESIZE;
// estilo do pincel: EP_SOLIDO
Symbol := SymbolTable.Enter('EP_SOLIDO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Ord(bsSolid);
// estilo do pincel: EP_VAZIO
Symbol := SymbolTable.Enter('EP_VAZIO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Ord(bsClear);
// estilo do pincel: EP_DIAG_CIMA
Symbol := SymbolTable.Enter('EP_DIAG_CIMA', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Ord(bsBDiagonal);
// estilo do pincel: EP_DIAG_BAIXO
Symbol := SymbolTable.Enter('EP_DIAG_BAIXO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Ord(bsFDiagonal);
// estilo do pincel: EP_CRUZADO
Symbol := SymbolTable.Enter('EP_CRUZADO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Ord(bsCross);
// estilo do pincel: EP_DIAG_CRUZ
Symbol := SymbolTable.Enter('EP_DIAG_CRUZ', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Ord(bsDiagCross);
// estilo do pincel: EP_HORIZONTAL
Symbol := SymbolTable.Enter('EP_HORIZONTAL', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Ord(bsHorizontal);
// estilo do pincel: EP_VERTICAL
Symbol := SymbolTable.Enter('EP_VERTICAL', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Ord(bsVertical);
// teclado (teclas especiais): TECLA_ENTER
Symbol := SymbolTable.Enter('TECLA_ENTER', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := Chr(13);
// teclado (teclas especiais): TECLA_ESC
Symbol := SymbolTable.Enter('TECLA_ESC', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := Chr(27);
// teclado (teclas especiais): TECLA_BACKSPACE
Symbol := SymbolTable.Enter('TECLA_BACKSPACE', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := Chr(8);
// teclado (teclas especiais): TECLA_TAB
Symbol := SymbolTable.Enter('TECLA_TAB', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := Chr(9);
// teclado (teclas especiais): TECLA_INS
Symbol := SymbolTable.Enter('TECLA_INS', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_INS;
// teclado (teclas especiais): TECLA_DEL
Symbol := SymbolTable.Enter('TECLA_DEL', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_DEL;
// teclado (teclas especiais): TECLA_HOME
Symbol := SymbolTable.Enter('TECLA_HOME', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_HOME;
// teclado (teclas especiais): TECLA_END
Symbol := SymbolTable.Enter('TECLA_END', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_END;
// teclado (teclas especiais): TECLA_ESQUERDA
Symbol := SymbolTable.Enter('TECLA_ESQUERDA', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_ESQUERDA;
// teclado (teclas especiais): TECLA_CIMA
Symbol := SymbolTable.Enter('TECLA_CIMA', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_CIMA;
// teclado (teclas especiais): TECLA_DIREITA
Symbol := SymbolTable.Enter('TECLA_DIREITA', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_DIREITA;
// teclado (teclas especiais): TECLA_BAIXO
Symbol := SymbolTable.Enter('TECLA_BAIXO', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_BAIXO;
// teclado (teclas especiais): TECLA_PGUP
Symbol := SymbolTable.Enter('TECLA_PGUP', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_PGUP;
// teclado (teclas especiais): TECLA_PGDN
Symbol := SymbolTable.Enter('TECLA_PGDN', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_PGDN;
// teclado (teclas especiais): TECLA_F1
Symbol := SymbolTable.Enter('TECLA_F1', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F1;
// teclado (teclas especiais): TECLA_F2
Symbol := SymbolTable.Enter('TECLA_F2', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F2;
// teclado (teclas especiais): TECLA_F3
Symbol := SymbolTable.Enter('TECLA_F3', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F3;
// teclado (teclas especiais): TECLA_F4
Symbol := SymbolTable.Enter('TECLA_F4', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F4;
// teclado (teclas especiais): TECLA_F5
Symbol := SymbolTable.Enter('TECLA_F5', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F5;
// teclado (teclas especiais): TECLA_F6
Symbol := SymbolTable.Enter('TECLA_F6', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F6;
// teclado (teclas especiais): TECLA_F7
Symbol := SymbolTable.Enter('TECLA_F7', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F7;
// teclado (teclas especiais): TECLA_F8
Symbol := SymbolTable.Enter('TECLA_F8', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F8;
// teclado (teclas especiais): TECLA_F9
Symbol := SymbolTable.Enter('TECLA_F9', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F9;
// teclado (teclas especiais): TECLA_F10
Symbol := SymbolTable.Enter('TECLA_F10', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F10;
// teclado (teclas especiais): TECLA_F11
Symbol := SymbolTable.Enter('TECLA_F11', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F11;
// teclado (teclas especiais): TECLA_F12
Symbol := SymbolTable.Enter('TECLA_F12', scConst, FDeclTypeChar, MODL_EVNT);
PChar(Symbol.Address)^ := TECLA_F12;
// estilo da caneta EC_SOLIDO
Symbol := SymbolTable.Enter('EC_SÓLIDO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Integer(psSolid);
// estilo da caneta EC_TRACO
Symbol := SymbolTable.Enter('EC_TRAÇO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Integer(psDash);
// estilo da caneta EC_PONTO
Symbol := SymbolTable.Enter('EC_PONTO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Integer(psDot);
// estilo da caneta EC_TRACO_PONTO
Symbol := SymbolTable.Enter('EC_TRAÇO_PONTO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Integer(psDashDot);
// estilo da caneta EC_TRACO_PONTO_PONTO
Symbol := SymbolTable.Enter('EC_TRAÇO_PONTO_PONTO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Integer(psDashDotDot);
// estilo da caneta EC_NULO
Symbol := SymbolTable.Enter('EC_NULO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Integer(psClear);
// estilo da caneta EC_INTERNO
Symbol := SymbolTable.Enter('EC_INTERNO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Integer(psInsideFrame);
// estilos fonte
Symbol := SymbolTable.Enter('EF_NEGRITO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := 1;
Symbol := SymbolTable.Enter('EF_ITÁLICO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := 2;
Symbol := SymbolTable.Enter('EF_SUBLINHADO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := 4;
Symbol := SymbolTable.Enter('EF_RISCADO', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := 8;
// Tela
FTela := TQuadroTela.Cria;
FrmDsl.PaintBox.Tag := Integer(FTela);
Symbol := SymbolTable.Enter('tela', scConst, FDeclTypeInteger, MODL_GRA);
PInteger(Symbol.Address)^ := Integer(FTela);
end;
procedure TCompiler.DestroyBitmaps;
var
I: Integer;
Bmp: Graphics.TBitmap;
begin
for I := 0 to FBitmapList.Count - 1 do
begin
Bmp := Graphics.TBitmap(FBitmapList[I]);
Bmp.Free;
end;
end;
procedure TCompiler.DestroyStreams;
var
I: Integer;
RWStrm: TRWStream;
begin
for I := 0 to FStreamList.Count - 1 do
begin
RWStrm := TRWStream(FStreamList[I]);
RWStrm.Free;
end;
end;
{ A implementação desta rotina destrói, num primeiro passo, os
componentes que não contém visualmente outros (ou seja, os que
não são 'parent'); depois, os possíveis contenedores são destruídos
num segundo passo.
Fiz isso (e funcionou) como solução para um problema que ainda não
entendi. Parece que relação 'parent' está também influenciando a
ordem em que os objetos estão sendo destruídos.
}
procedure TCompiler.DestroyTQuadroList;
var
I: Integer;
LstAux: TList;
Q: TQuadro;
begin
LstAux := TList.Create;
for I := 0 to FTQuadroList.Count - 1 do
begin
Q := TQuadro(FTQuadroList[I]);
// deixa pro final os componentes que podem ser 'parent'
if (Q.obt_win_control() <> nil) then
LstAux.Add(Q)
else
Q.Free;
end;
// destrói os que podem ser 'parent' de outros
for I := 0 to LstAux.Count - 1 do
TQuadro(LstAux[I]).Free;
LstAux.Free;
end;
{ Destrói a lista de TMediaPlayers }
procedure TCompiler.DestroyTMediaPlayerList;
var
I: Integer;
begin
for I := 0 to FTMediaPlayerList.Count - 1 do
TMediaPlayer(FTMediaPlayerList[I]).Free;
end;
{ A implementação desta rotina destrói, num primeiro passo, os
componentes que não contém visualmente outros (ou seja, os que
não são 'parent'); depois, os possíveis contenedores são destruídos
num segundo passo.
Fiz isso (e funcionou) como solução para um problema que ainda não
entendi. Parece que relação 'parent' está também influenciando a
ordem em que os objetos estão sendo destruídos.
}
(*
procedure TCompiler.DestroyCompList;
var
I: Integer;
LstAux: TList;
C: TComponent;
begin
LstAux := TList.Create;
for I := 0 to FCompList.Count - 1 do
begin
C := TComponent(FCompList[I]);
// deixa pro final os componentes que podem ser 'parent'
if (C is TGroupBox) or (C is TPanel) then
LstAux.Add(C)
else
C.Free;
end;
// destrói os componentes que podem ser 'parent' de outros
for I := 0 to LstAux.Count - 1 do
TComponent(LstAux[I]).Free;
LstAux.Free;
end;
*)
procedure TCompiler.Error(S: String);
begin
raise EInterpreterException.Create(S, 1, 1, nil);
end;
(*
PROBLEMA: Interpretacao de Expression está provocando excecao;
Tudo indica que tem a ver com a criacao dos symbol infos
durante a "compilação" da expressao.
Acho que devo simular a coisa como se tivesse havido,
no código do usuario, um procedimento Evaluate, previamente
declarado. A expressao teria sido compilada dentro desse
"procedimento".
*)
function TCompiler.Evaluate(Expression: String): String;
var
Source: TStream;
Si: TSymbolInfo;
Prod: TProduction;
SymTbl: TSymbolTable;
begin
Result := '';
// stream creation
Source := TStringStream.Create(Expression);
// special symbol table for temporary symbol infos
SymTbl := TSymbolTable.Create(Self);
SymbolTable.AddScope(SymTbl);
// evaluate
State := State + [csEvaluating];
try
Prod := Compile(Source, TProd_Expression);
SymTbl.SetActivation;
Prod.Interpret;
Si := Prod.SymbolInfo;
Result := Si.SymbolType.ValueAsString(Si);
finally
Source.Free;
State := State - [csEvaluating];
SymbolTable.RemoveScope;
SymTbl.Free;
end;
end;
procedure TCompiler.SetProgramSymbolTable(T: TSymbolTable);
begin
FProgramSymbolTable := T;
end;
function TCompiler.SetSubroutineSymbolTable(T: TSymbolTable): TSymbolTable;
begin
Result := FSubroutineSymbolTable;
FSubroutineSymbolTable := T;
end;
{ This function is used only when csEvaluating in state }
function TCompiler.FindSymbol(Symbol: String): TSymbolInfo;
function Find(T: TSymbolTable; Symbol: String): TSymbolInfo;
var
Ind: Integer;
begin
Result := nil;
Ind := T.FTable.IndexOf(Symbol);
if Ind >= 0 then
Result := TSymbolInfo(T.FTable.Objects[Ind]);
end;
begin
Result := nil;
if FSubroutineSymbolTable <> nil then
Result := Find(FSubroutineSymbolTable, Symbol);
if (Result = nil) and (FProgramSymbolTable <> nil) then
Result := Find(FProgramSymbolTable, Symbol);
end;
procedure TCompiler.SetBreakpoint(FileName: String; LineNumber: Integer);
begin
FBreakpointFileName := FileName;
FBreakpointLine := LineNumber;
end;
procedure TCompiler.BreakOnNextStatement;
begin
State := State + [csBreakOnNextStmt];
end;
procedure TCompiler.RegisterMouseXY(X, Y: Integer);
begin
FMouseX := X;
FMouseY := Y;
end;
procedure TCompiler.RegisterLastEvent(Event: Integer; Sender: TObject);
begin
FLastEvent := Event;
FLastEventSender := Sender;
end;
procedure TCompiler.RegisterShiftState(Shift: TShiftState);
begin
FShiftState := Shift;
end;
procedure TCompiler.RegisterKeyPressed(Key: Char);
begin
FKeyPressed := Key;
end;
procedure TCompiler.RegisterKeyDown(Key: Word);
begin
FKeyDown := Key;
end;
procedure TCompiler.RegisterKeyUp(Key: Word);
begin
FKeyUp := Key;
end;
procedure TCompiler.PushStream(FileName: String);
var
Strm: TStringList;
Toks: TPascalTokenizer;
begin
// cria um stream na memória
Strm := TStringList.Create;
// lê do arquivo
try
Strm.LoadFromFile(FileName);
except
Error(Format(sFileNotFound, [FileName]));
end;
// cria um novo parser
// Strm.Position := 0;
Toks := TPascalTokenizer.Create(Strm.Text, FileName);
FParserStack.Add(FParser);
FIncludeList.Add(FileName);
FParser := Toks;
end;
procedure TCompiler.PushStringStream(S: String);
var
Strm: TStringStream;
Toks: TPascalTokenizer;
begin
// cria um stream na memória
Strm := TStringStream.Create(S);
// cria um novo parser
Strm.Position := 0;
Toks := TPascalTokenizer.Create(Strm);
FParserStack.Add(FParser);
// FIncludeList.Add(FileName); no caso de inserção de string,
// Add(FileName) não é necessário
FParser := Toks;
end;
procedure TCompiler.PopStream;
begin
// libera o parser corrente
// FParser.Stream.Free;
// FParser.Free;
// retoma o parser anterior
FParser := TPascalTokenizer(FParserStack.Last);
FParserStack.Delete(FParserStack.Count - 1);
end;
procedure TCompiler.TrataOnPaint(Sender: TObject);
var
Q: TQuadro;
Canvas: TCanvas;
begin
if (Sender = FrmDSL.PaintBox) then
begin
Q := FTela;
Canvas := FrmDSL.PaintBox.Canvas;
end
else
begin
Q := TQuadro((Sender as TForm).Tag);
Canvas := (Sender as TForm).Canvas;
end;
Canvas.CopyRect(Canvas.ClipRect, Q.Bmp.Canvas, Canvas.ClipRect);
end;
procedure TCompiler.TrataOnClickBotao(Sender: TObject);
begin
if FrmDSL.FWaitingFor and ((EV_MOUSE_CLICK and FrmDSL.FEvents) <> 0) then
begin
FrmDSL.FWaitingFor := False;
RegisterLastEvent(EV_MOUSE_CLICK, Sender);
end;
end;
procedure TCompiler.TrataOnMouseDownBotao(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if FrmDSL.FWaitingFor then
if (EV_MOUSE_DOWN and FrmDSL.FEvents) <> 0 then
begin
RegisterMouseXY(X, Y);
RegisterShiftState(Shift);
FrmDSL.FWaitingFor := False; // libera a espera por evento
RegisterLastEvent(EV_MOUSE_DOWN, Sender);
end;
end;
procedure TCompiler.TrataOnMouseUpBotao(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if FrmDSL.FWaitingFor then
if (EV_MOUSE_UP and FrmDSL.FEvents) <> 0 then
begin
RegisterMouseXY(X, Y);
RegisterShiftState(Shift);
FrmDSL.FWaitingFor := False; // libera a espera por evento
RegisterLastEvent(EV_MOUSE_UP, Sender);
end;
end;
{ TProduction }
const
Set_FirstFactor = [tkId, tkIntNumber, tkFloatNumber, tkString, tkChar,
tkLParen, tkRWnot, tkPlus, tkMinus, tkLBracket, tkRWnil, tkRWfalse,
tkRWtrue, tkRWyes];
Set_FirstStmt = [tkId, tkRWbegin, tkRWif, tkRWwhile, tkRWrepeat, tkRWfor,
tkRWwrite, tkRWwriteln, tkRWwith, tkRWnew, tkRWdispose, tkRWchoose, tkRWread,
tkRWreturn, tkSemiColon, tkIncrement, tkDecrement];
Set_FirstDecl = [tkRWconst, tkRWtype, tkRWvar, tkRWprocedure,
tkRWfunction, tkRWinclude];
Set_MulOp = [tkTimes, tkSlash, tkRWdiv, tkRWmod, tkRWand];
Set_AddOp = [tkPlus, tkMinus, tkRWor, tkRWxor];
Set_RelOp = [tkLT, tkLE, tkGT, tkGE, tkEqual, tkNE, tkRWin];
constructor TProduction.Create(Compiler: TCompiler);
begin
inherited Create;
FCompiler := Compiler;
FParser := FCompiler.Parser;
FSymbolTable := FCompiler.SymbolTable;
FProdLst := TList.Create;
end;
destructor TProduction.Destroy;
var
I: Integer;
begin
for I := 0 to FProdLst.Count - 1 do
TProduction(FProdLst[I]).Free;
FProdLst.Free;
inherited Destroy;
end;
procedure TProduction.Error(S: String; Line, Col: Integer);
begin
raise EInterpreterException.Create(S, Line, Col, Parser);
end;
procedure TProduction.Check(Tokens: TTokens; ErrMsg: String);
begin
if not (Parser.CurrentToken in Tokens) then
Error(ErrMsg, Parser.TokenLine, Parser.TokenCol);
end;
procedure TProduction.GetTerminal(Token: TToken);
begin
if Parser.CurrentToken <> Token then
Error(Format(sTerminalExpected, [Parser.GetTokenName(Token)]),
Parser.TokenLine, Parser.TokenCol);
Parser.GetNextToken;
end;
procedure TProduction.CheckTerminal(Token: TToken);
begin
if Parser.CurrentToken <> Token then
Error(Format(sTerminalExpected, [Parser.GetTokenName(Token)]),
Parser.TokenLine, Parser.TokenCol);
end;
function TProduction.GetProductions(Ind: Integer): TProduction;
begin
Result := FProdLst[Ind];
end;
function TProduction.GetProductionCount: Integer;
begin
Result := FProdLst.Count;
end;
function TProduction.GetIdentifier: String;
begin
Check([tkId, tkRWstring], sIdentifierExpected);
Result := Parser.TokenString;
Parser.GetNextToken;
end;
function TProduction.GetNewIdentifier: String;
begin
Check([tkId], sIdentifierExpected);
Result := Parser.TokenString;
if SymbolTable.FindSymbol(Result) <> nil then
Error(Format(sIdentifierRedeclared, [Parser.TokenString]),
Parser.TokenLine, Parser.TokenCol);
Parser.GetNextToken;
end;
procedure TProduction.GetNewIdentifierList(Lst: TStringList);
begin
repeat
if Lst.IndexOf(Parser.TokenString) <> -1 then
Error(Format(sIdentifierRedeclared, [Parser.TokenString]),
Parser.TokenLine, Parser.TokenCol);
Lst.Add(GetNewIdentifier);
if Parser.CurrentToken <> tkComma then
Break;
Parser.GetNextToken;
until False;
end;
//function TProduction.GetIntNumber: Integer;
//begin
// Check([tkIntNumber], sIntegerNumberExpected);
// Result := StrToInt(Parser.TokenString);
// Parser.GetNextToken;
//end;
procedure TProduction.SkipTo(Tokens: TTokens);
begin
while not (Parser.CurrentToken in Tokens + [tkEndOfSource]) do
Parser.GetNextToken;
end;
function TProduction.SolveWithStmt(P: TProduction; Symbol: TSymbolInfo)
: TSymbolInfo;
function FindRecord(Prod: TProd_WithStmt; Symbol: TSymbolInfo): TSymbolInfo;
var
I: Integer;
begin
Result := nil;
for I := Prod.FRecordLst.Count - 1 downto 0 do
if TProduction(Prod.FRecordLst[I]).SymbolInfo.SymbolType = Symbol.RecordType
then begin
Result := TProduction(Prod.FRecordLst[I]).SymbolInfo;
Exit;
end;
end;
begin
while True do
begin
repeat
P := P.Parent;
until (P = nil) or (P is TProd_WithStmt);
if P = nil then
Error(sSolveWith, ProductionLine, ProductionCol);
Result := FindRecord(TProd_WithStmt(P), Symbol);
Exit;
end;
end;
function TProduction.Compile(ProductionClass: TProductionClass): TProduction;
var
P: TProduction;
begin
P := ProductionClass.Create(Compiler);
P.FParent := Self;
P.FLevel := Level + 1;
P.FPosition := Parser.TokenPosition;
P.FProductionLine := Parser.TokenLine;
P.FProductionCol := Parser.TokenCol;
FProdLst.Add(P);
P.Parse;
P.FProductionEndLine := Parser.TokenLine;
P.FProductionEndCol := Parser.TokenCol;
Result := P;
end;
procedure TProduction.Interpret;
var
I: Integer;
begin
for I := 0 to ProductionCount - 1 do
Productions[I].Interpret;
end;
function TProduction.CheckTypes(T1, T2: TSymbolType; Op: TToken): TSymbolType;
procedure Error;
begin
Self.Error(sIncompatibleTypes, ProductionLine, ProductionCol);
end;
procedure OpeError;
begin
Self.Error(sOperatorNotApplicable, ProductionLine, ProductionCol);
end;
function CheckCompatibility(T1, T2: TSymbolType): TSymbolType;
begin
Result := T1;
// one is subrange of the other
if (T1.TypeClass = tcSubrange) and (TSubrangeType(T1).FBaseType = T2) then
begin
Result := T2;
Exit;
end;
if (T2.TypeClass = tcSubrange) and (TSubrangeType(T2).FBaseType = T1) then
Exit;
// both are subranges of the same host type
if (T1.TypeClass = tcSubrange) and (T2.TypeClass = tcSubrange) and
(TSubrangeType(T1).FBaseType = TSubrangeType(T2).FBaseType) then
begin
Result := TSubrangeType(T1).FBaseType;
Exit;
end;
// both types are set types, and ...
if (T1.TypeClass = tcSet) and (T2.TypeClass = tcSet) then
begin
// one is the empty set
if (TSetType(T1).FBaseType = nil) or (TSetType(T2).FBaseType = nil) then
Exit;
// base types are compatible
CheckCompatibility(TSetType(T1).FBaseType, TSetType(T2).FBaseType);
Exit;
end;
// one is string and the other is char
if (T1.TypeClass = tcString) and (T2.TypeClass = tcChar) then
Exit;
if (T2.TypeClass = tcString) and (T1.TypeClass = tcChar) then
begin
Result := T2;
Exit;
end;
if (T1.TypeClass = tcChar) and (T2.TypeClass = tcChar) and (Op = tkPlus) then
begin
Result := Compiler.DeclTypeString;
Exit;
end;
// both are pointers, and ...
if (T1.TypeClass = tcPointer) and (T2.TypeClass = tcPointer) then
begin
// one is nil
if (T1 = Compiler.DeclTypePointer) or (T2 = Compiler.DeclTypePointer) then
Exit;
// base types are the same
if TPointerType(T1).FBaseType = TPointerType(T2).FBaseType then
Exit;
end;
// promotions
if (T1.TypeClass = tcInteger) and (T2.TypeClass = tcExtended) then
begin
Result := T2;
Exit;
end;
if (T1.TypeClass = tcExtended) and (T2.TypeClass = tcInteger) then
Exit;
if (T1.TypeClass = tcSubrange) and
(TSubrangeType(T1).FBaseType.TypeClass = tcInteger) and
(T2.TypeClass = tcExtended) then
begin
Result := T2;
Exit;
end;
if (T2.TypeClass = tcSubrange) and
(TSubrangeType(T2).FBaseType.TypeClass = tcInteger) and
(T1.TypeClass = tcExtended) then
Exit;
// both types are the same
if T1 = T2 then
Exit;
Error;
Result := nil;
end;
begin
Result := T1;
case Op of
tkTimes, tkPlus, tkMinus:
begin
Result := CheckCompatibility(T1, T2);
if not (Result.TypeClass in
[tcInteger, tcExtended, tcString, tcSet]) then
OpeError;
end;
tkSlash:
begin
CheckCompatibility(T1, T2);
if not (Result.TypeClass in [tcExtended, tcInteger]) then
OpeError;
Result := Compiler.DeclTypeExtended;
end;
tkRWdiv, tkRWmod:
begin
Result := CheckCompatibility(T1, T2);
if not (Result.TypeClass in [tcInteger]) then
OpeError;
end;
tkRWand, tkRWor, tkRWxor, tkRWnot:
begin
Result := CheckCompatibility(T1, T2);
if not (Result.TypeClass in [tcInteger, tcBoolean]) then
OpeError;
end;
tkLT, tkGT:
begin
Result := CheckCompatibility(T1, T2);
if not (Result.TypeClass in [tcInteger, tcExtended, tcBoolean,
tcChar, tcEnum, tcString]) then
OpeError;
end;
tkLE, tkGE, tkEqual, tkNE:
begin
Result := CheckCompatibility(T1, T2);
if not (Result.TypeClass in [tcInteger, tcExtended, tcBoolean, tcChar,
tcEnum, tcString, tcSet, tcPointer]) then
OpeError;
end;
tkRWin:
begin
if T2.TypeClass <> tcSet then
OpeError;
CheckCompatibility(T1, TSetType(T2).FBaseType);
Result := Compiler.DeclTypeBoolean;
end;
tkAssign:
begin
CheckCompatibility(T1, T2);
Result := T1;
if T1.TypeClass = tcSubrange then T1 := TSubrangeType(T1).FBaseType;
if T2.TypeClass = tcSubrange then T2 := TSubrangeType(T2).FBaseType;
if (T1.TypeClass = tcChar) and (T2.TypeClass = tcString) then
Error;
if (T1.TypeClass = tcInteger) and (T2.TypeClass = tcExtended) then
Error;
end;
else
raise EInterpreterException.Create(sInvalidOperation, 1, 1, Parser);
end;
end;
{ Result := S1 op S2 }
procedure TProduction.Operate(Result, S1, S2: TSymbolInfo; Op: TToken);
begin
try
case Op of
// binary ops
tkTimes, tkSlash, tkRWdiv, tkRWmod, tkRWand, tkPlus, tkMinus, tkRWor,
tkLT, tkLE, tkGT, tkGE, tkEqual, tkNE, tkRWin:
S1.SymbolType.Oper(Result.Address, S1.Address, S2.Address, Op, Self);
// unary ops
tkRWnot, tkUnaryMinus, tkAssign:
S1.SymbolType.Oper(Result.Address, S1.Address, nil, Op, Self);
end;
except
on E: Exception do
Error(sExecutionError + ': ' + E.Message, ProductionLine, ProductionCol);
end;
end;
function TProduction.FormalParamsOk(PFirst, PSecond: TProd_FormalParamList): Boolean;
var
I: Integer;
Si1, Si2: TSymbolInfo;
begin
Result := False;
if PSecond.FParamLst.Count > 0 then
begin
if PFirst.FParamLst.Count <> PSecond.FParamLst.Count then
Exit;
for I := 0 to PFirst.FParamLst.Count - 1 do
begin
Si1 := TSymbolInfo(PFirst.FParamLst[I]);
Si2 := TSymbolInfo(PSecond.FParamLst[I]);
if Si1.Name <> Si2.Name then
Exit;
if Si1.SymbolClass <> Si2.SymbolClass then
Exit;
if Si1.SymbolType <> Si2.SymbolType then
Exit;
end;
end;
Result := True;
end;
procedure TProduction.ShowSyntaxTree(S: TStrings);
var
Str: String;
I: Integer;
begin
Str := '';
for I := 1 to Level do
Str := Str + ' ';
Str := Str + ClassName + ' [' + IntToStr(ProductionLine) + ',' +
IntToStr(ProductionCol) + ']';
S.Add(Str);
for I := 0 to ProductionCount - 1 do
Productions[I].ShowSyntaxTree(S);
end;
function TProduction.GetSymbolInfo: TSymbolInfo;
begin
Result := FSymbolInfo;
end;
function TProduction.PromoteTo(T: TSymbolType): Boolean;
var
St: TSymbolType;
begin
Result := False;
if FSymbolInfo = nil then
Error(sPromoteTo, ProductionLine, ProductionCol);
if FPromoted <> nil then
Error(sPromoteTo, ProductionLine, ProductionCol);
St := FSymbolInfo.SymbolType;
// promotion from char to string
if (St.TypeClass = tcChar) and (T.TypeClass = tcString) then
begin
FPromoted := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeString);
Result := True;
end
// promotion from integer to extended
else if (St.TypeClass = tcInteger) and (T.TypeClass = tcExtended) then
begin
FPromoted := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeExtended);
Result := True;
end
else if (St.TypeClass = tcSubrange) and
(TSubrangeType(St).FBaseType.TypeClass = tcInteger) and
(T.TypeClass = tcExtended) then
begin
FPromoted := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeExtended);
Result := True;
end;
end;
function TProduction.ExecPromotion: Boolean;
begin
if FPromoted = nil then
begin
Result := False;
Exit; // nothing to do
end;
Result := True;
if FPromoted.SymbolType.TypeClass = tcString then
PString(FPromoted.Address)^ := PChar(FSymbolInfo.Address)^
else // FPromoted.SymbolType.TypeClass = tcExtended
PExtended(FPromoted.Address)^ := PInteger(FSymbolInfo.Address)^;
end;
procedure TProduction.VerifyDebug(Lin, Col: Integer; Parser: TPascalTokenizer);
begin
if (Assigned(Compiler.FOnDebug)) then
begin
if csBreakOnNextStmt in Compiler.State then
begin
Compiler.State := Compiler.State - [csBreakOnNextStmt];
Compiler.FOnDebug(Self, Lin, Col, Parser);
if Compiler.FTerminate then
Error(sUserBreak, Lin, Col);
end
// else if (ProductionLine = Compiler.FBreakPointLine) and
// (Parser.Name = Compiler.FBreakpointFileName) then
else if (Lin = Compiler.FBreakPointLine) and
(Parser.Name = Compiler.FBreakpointFileName) then
begin
Compiler.FBreakPointLine := 0;
Compiler.FBreakpointFileName := '';
Compiler.FOnDebug(Self, Lin, Col, Parser);
if Compiler.FTerminate then
Error(sUserBreak, Lin, Col);
end;
end;
end;
function TProduction.IsStandardModule(FileName: String): Boolean;
begin
Result := False; // presume que não é um módulo padrão
if FileName = MODL_GRA then
Result := True
else if FileName = MODL_ARQ then
Result := True
else if FileName = MODL_EVNT then
Result := True
else if FileName = MODL_MAT then
Result := True
else if FileName = MODL_MM then
Result := True;
// OBS: MODL_PAC é tratado de forma especial: ele é um "módulo" que
// representa coisas da linguagem, de modo que não é necessário
// (nem permitido) incluí-lo.
end;
//procedure TProduction.CheckMemory;
//var
// MemStatus: TMemoryStatus;
//begin
// MemStatus.dwLength := sizeof(TMemoryStatus);
// GlobalMemoryStatus(MemStatus);
// if MemStatus.dwMemoryLoad >= 75 then
// Error(sOutOfMemory80, 1, 1);
//end;
procedure TProduction.ReplaceSymbolInfo(SiOld, SiNew: TSymbolInfo);
var
I: Integer;
begin
if FSymbolInfo = SiOld then
FSymbolInfo := SiNew;
if Self is TProd_VarReference then
with Self as TProd_VarReference do
begin
if FVarRef = SiOld then
FVarRef := SiNew;
end;
for I := 0 to ProductionCount - 1 do
Productions[I].ReplaceSymbolInfo(SiOld, SiNew);
end;
function TProduction.StandardProcedure(ProcName: String): Boolean;
var
Prod: TProductionClass;
Modl: String;
function FindProc(Name: String; var Modl: String): TProductionClass;
var I: Integer;
begin
Result := nil;
Modl := '';
// Name := AnsiUpperCase(Name);
for I := 0 to MAX_PROCS do
// if Name = AnsiUpperCase(Procs[I]) then
if Name = Procs[I] then
begin
Result := Prods[I];
// verifica se o módulo associado foi previamente incluído
// obs: se a rotina é associada a MODL_PAC, considera ok,
// pois é como se fosse da linguagem
if (Modls[I] <> MODL_PAC) and
(Compiler.FModlList.IndexOf(Modls[I]) < 0) then
Result := nil;
Exit;
end;
end;
begin
Prod := FindProc(Parser.TokenString, Modl);
Result := Prod <> nil;
if Result then
Compile(Prod);
end;
function TProduction.EstiloFonteParaInt(Fs: TFontStyles): Integer;
begin
Result := 0;
if fsBold in Fs then
Result := Result + EF_NEGRITO;
if fsItalic in Fs then
Result := Result + EF_ITALICO;
if fsUnderline in Fs then
Result := Result + EF_SUBLINHADO;
if fsStrikeOut in Fs then
Result := Result + EF_RISCADO;
end;
function TProduction.IntParaEstiloFonte(V: Integer): TFontStyles;
begin
Result := [];
if (V and EF_NEGRITO) <> 0 then
Result := Result + [fsBold];
if (V and EF_ITALICO) <> 0 then
Result := Result + [fsItalic];
if (V and EF_SUBLINHADO) <> 0 then
Result := Result + [fsUnderline];
if (V and EF_RISCADO) <> 0 then
Result := Result + [fsStrikeOut];
end;
function TProduction.CarregaImg(Img: TImage; Nome: String): Boolean;
var
Bmp: Graphics.TBitmap;
begin
Result := True;
Bmp := Graphics.TBitmap.Create;
try
Bmp.LoadFromResourceName(HInstance, Nome);
Img.Picture.Bitmap.Assign(Bmp);
except
Result := False;
end;
Bmp.Free;
end;
(*
procedure TProduction.PreparaTransfDistRot(Canvas: TCanvas; Rot: Extended;
x, y: Integer);
var
xf: TXForm;
begin
// transforma Rot em radianos
Rot := Rot * PI / 180.0;
// salva o modo atual
// GetWorldTransform(Canvas.Handle, FXFormSalvo);
// FGraphicsModeSalvo := GetGraphicsMode(Canvas.Handle);
// altera
if SetGraphicsMode(Canvas.Handle, GM_ADVANCED) = 0 then
Error('Falha em SetGraphicsMode', ProductionLine, ProductionCol);
xf.eM11 := cos(Rot);
xf.eM12 := sin(Rot);
xf.eM21 := -xf.eM12; // -sen
xf.eM22 := xf.eM11; // cos
xf.eDx := x;
xf.eDy := y;
if not SetWorldTransform(Canvas.Handle, xf) then
Error('Falha em SetWorldTransform', ProductionLine, ProductionCol);
end;
*)
(*
procedure TProduction.RestauraTransfDistRot(Canvas: TCanvas);
begin
// SetGraphicsMode(Canvas.Handle, FGraphicsModeSalvo);
// SetWorldTransform(Canvas.Handle, FXFormSalvo);
end;
*)
{ Retorna o nome "completo" do arquivo, considerando a
restrição de todos os arquivos ficarem direta ou
indiretamente no diretório "BASE\arqs", onde BASE
é o diretório onde está o executável. Se nome='abc.txt',
o resultado será 'BASE\arqs\abc.txt' }
function TProduction.ExpandeNomeArq(Nome: String): String;
const
DIR_ARQS = 'arqs';
begin
Result := ExtractFilePath(Application.ExeName);
Result := IncludeTrailingPathDelimiter(Result) + DIR_ARQS;
if not IsPathDelimiter(Nome, 1) then
Result := IncludeTrailingPathDelimiter(Result);
Result := Result + Nome;
end;
function TProduction.FileStreamToString(Fs: TFileStream): String;
var
Ss: TStringStream;
begin
// cria o TStringStream
try
Ss := TStringStream.Create('');
except
Ss := nil;
end;
if Ss = nil then // erro interno, não esperado
Error(sArquivoNaoEncontrado, ProductionLine, ProductionCol);
// copia para o arquivo para TStringStream
try
Ss.CopyFrom(Fs, Fs.Size);
except
Ss.Free;
Ss := nil;
end;
if Ss = nil then
Error(sArquivoNaoEncontrado, ProductionLine, ProductionCol);
// retorna como String e libera o TStringStream
Result := Ss.DataString;
Ss.Free;
end;
function TProduction.GetParser: TPascalTokenizer;
begin
Result := FParser;
end;
function TProduction.CarregaBmp(Bmp: Graphics.TBitmap; Nome: String): Boolean;
begin
Result := True;
try
Bmp.LoadFromResourceName(HInstance, Nome);
except
Result := False;
end;
end;
{ TProd_Program }
procedure TProd_Program.Parse;
begin
if Parser.CurrentToken = tkRWprogram then
begin
Parser.GetNextToken;
GetIdentifier; // nome do programa
if Parser.CurrentToken = tkLParen then
begin
SkipTo([tkRParen]);
Parser.GetNextToken;
end;
GetTerminal(tkSemiColon);
end;
Compile(TProd_Block);
GetTerminal(tkPeriod);
end;
{ TProd_Block }
procedure TProd_Block.Parse;
begin
Compile(TProd_DeclPart);
FCompoundStmt := Compile(TProd_CompoundStmt);
end;
procedure TProd_Block.Interpret;
begin
FCompoundStmt.Interpret;
end;
{ TProd_DeclPart }
procedure TProd_DeclPart.Parse;
begin
repeat
if Parser.CurrentToken = tkRWconst then
Compile(TProd_ConstDeclPart);
if Parser.CurrentToken = tkRWtype then
Compile(TProd_TypeDeclPart);
if Parser.CurrentToken = tkRWvar then
Compile(TProd_VarDeclPart);
if Parser.CurrentToken = tkRWinclude then
Compile(TProd_IncludeDecl);
if Parser.CurrentToken = tkRWprocedure then
Compile(TProd_Procedure);
if Parser.CurrentToken = tkRWfunction then
Compile(TProd_Function);
(*
if (csInSubRoutine in Compiler.State) and
(Parser.CurrentToken in [tkRWprocedure, tkRWfunction]) then
Error(sSubroutineLevel, ProductionLine, ProductionCol);
if not (csInSubRoutine in Compiler.State) then
while Parser.CurrentToken in [tkRWprocedure, tkRWfunction] do
if Parser.CurrentToken = tkRWprocedure then
Compile(TProd_Procedure)
else
Compile(TProd_Function);
*)
until not (Parser.CurrentToken in Set_FirstDecl);
end;
{ TProd_ConstDeclPart }
procedure TProd_ConstDeclPart.Parse;
begin
Parser.GetNextToken; // const
repeat
Compile(TProd_ConstDecl);
until Parser.CurrentToken <> tkId;
end;
{ TProd_ConstDecl }
procedure TProd_ConstDecl.Parse;
var
Expr: TProduction;
Id: String;
begin
Compiler.State := Compiler.State + [csFindInScope];
Id := GetNewIdentifier;
Compiler.State := Compiler.State - [csFindInScope];
GetTerminal(tkEqual);
Expr := Compile(TProd_ConstExpression);
FSymbolInfo := SymbolTable.Enter(Id, scConst, Expr.SymbolInfo.SymbolType, MODL_PAC);
Expr.Interpret;
Operate(FSymbolInfo, Expr.SymbolInfo, nil, tkAssign);
GetTerminal(tkSemiColon);
end;
{ TProd_TypeDeclPart }
procedure TProd_TypeDeclPart.Parse;
begin
Parser.GetNextToken; // type
Compiler.State := Compiler.State + [csInTypeDecl];
repeat
Compile(TProd_TypeDecl);
until Parser.CurrentToken <> tkId;
Compiler.State := Compiler.State - [csInTypeDecl];
// solve pendent pointers
SymbolTable.CheckPendentPointers;
end;
{ TProd_TypeDecl }
procedure TProd_TypeDecl.Parse;
var
TypeDecl: TProduction;
begin
Compiler.State := Compiler.State + [csFindInScope];
FTypeId := GetNewIdentifier;
Compiler.State := Compiler.State - [csFindInScope];
GetTerminal(tkEqual);
TypeDecl := Compile(TProd_Type);
SymbolTable.Enter(FTypeId, scType, TypeDecl.SymbolInfo.SymbolType, MODL_PAC);
GetTerminal(tkSemiColon);
// take care of pending base pointer type
if (TypeDecl.SymbolInfo.SymbolType is TPointerType) then
with TypeDecl.SymbolInfo.SymbolType as TPointerType do
if FBaseType = nil then
begin
FBaseTypeId := FBaseId;
SymbolTable.AddPendentPointer(Self);
end;
end;
{ TProd_Type }
procedure TProd_Type.Parse;
begin
// trata caso especial de declaração de índice de arranjo
if (csInArrayDecl in Compiler.State) then
begin
FSymbolInfo := Compile(TProd_SubrangeType).SymbolInfo;
Exit;
end;
case Parser.CurrentToken of
tkId:
begin
FSymbolInfo := SymbolTable.FindSymbol(Parser.TokenString);
if FSymbolInfo = nil then
Error(Format(sUndeclaredIdentifier, [Parser.TokenString]),
ProductionLine, ProductionCol);
if FSymbolInfo.SymbolClass = scType then
begin
Parser.GetNextToken; // type identifier
Exit;
end;
// subrange type
FSymbolInfo := Compile(TProd_SubrangeType).SymbolInfo
end;
tkRWstring, tkRWinteger, tkRWreal, tkRWboolean, tkRWchar, tkRWyesOrNo:
begin
FSymbolInfo := SymbolTable.FindSymbol(
Parser.GetTokenName(Parser.CurrentToken));
Parser.GetNextToken;
end;
tkIntNumber, tkChar, tkMinus, tkPlus:
FSymbolInfo := Compile(TProd_SubrangeType).SymbolInfo;
tkLParen:
FSymbolInfo := Compile(TProd_EnumType).SymbolInfo;
tkRWset:
FSymbolInfo := Compile(TProd_SetType).SymbolInfo;
tkRWarray:
FSymbolInfo := Compile(TProd_ArrayType).SymbolInfo;
tkRWrecord:
FSymbolInfo := Compile(TProd_RecordType).SymbolInfo;
tkRWpointer: //tkCaret:
FSymbolInfo := Compile(TProd_PointerType).SymbolInfo;
(*
tkRWprocedure:
FSymbolInfo := Compile(TProd_ProcProceduralType).SymbolInfo;
tkRWfunction:
FSymbolInfo := Compile(TProd_FuncProceduralType).SymbolInfo;
*)
else
Error(sTypeExpected, ProductionLine, ProductionCol);
end;
end;
{ TProd_EnumType }
procedure TProd_EnumType.Parse;
var
Lst: TStringList;
T: TSymbolType;
I: Integer;
begin
Lst := TStringList.Create;
Lst.CaseSensitive := True;
try
Parser.GetNextToken; // (
GetNewIdentifierList(Lst);
GetTerminal(tkRParen);
T := SymbolTable.AllocType(TEnumType);
for I := 0 to Lst.Count - 1 do
begin
FSymbolInfo := SymbolTable.Enter(Lst[I], scConst, T, MODL_PAC);
PInteger(FSymbolInfo.Address)^ := I;
TEnumType(T).FEnums.Add(FSymbolInfo);
end;
finally
Lst.Free;
end;
end;
{ TProd_SubrangeType }
procedure TProd_SubrangeType.Parse;
var
Inf, Sup: TSymbolInfo;
T: TSymbolType;
Expr: TProduction;
begin
if (csInArrayDecl in Compiler.State) then
begin
Parser.GetNextToken; // abre colchete ou vírgula
Compiler.Parser.Inject('0..');
Parser.GetNextToken; // 0
end;
Expr := Compile(TProd_ConstExpression);
Expr.Interpret;
Inf := Expr.SymbolInfo;
if (csInArrayDecl in Compiler.State) then
begin
CheckTerminal(tkDotDot);
Compiler.Parser.InjectOff;
end
else
GetTerminal(tkDotDot);
Expr := Compile(TProd_ConstExpression);
Expr.Interpret;
Sup := Expr.SymbolInfo;
if Inf.SymbolType <> Sup.SymbolType then
Error(sIncompatibleTypes, ProductionLine, ProductionCol);
if Inf.SymbolType is TCharType then
begin
if PChar(Inf.Address)^ > PChar(Sup.Address)^ then
Error(sLowGTHigh, ProductionLine, ProductionCol);
end
else if PInteger(Inf.Address)^ > PInteger(Sup.Address)^ then
Error(sLowGTHigh, ProductionLine, ProductionCol)
else if PInteger(Sup.Address)^ <= 0 then
Error(sIndiceInvalido, ProductionLine, ProductionCol);
T := SymbolTable.AllocType(TSubrangeType);
with T as TSubrangeType do
begin
FInf := Inf;
FSup := Sup;
FBaseType := Inf.SymbolType;
end;
FSymbolInfo := SymbolTable.AllocSymbolInfo(scType, T);
end;
{ TProd_SetType }
procedure TProd_SetType.Parse;
var
TBase, TSet: TSymbolType;
begin
Parser.GetNextToken; // consume set
GetTerminal(tkRWof);
TBase := Compile(TProd_Type).SymbolInfo.SymbolType;
if not (TBase is TOrdinalType) then
Error(sOrdinalTypeRequired, ProductionLine, ProductionCol);
if (TOrdinalType(TBase).MinValue < 0) or
(TOrdinalType(TBase).MaxValue > 255) then
Error(sSetsMayHave256, ProductionLine, ProductionCol);
TSet := SymbolTable.AllocType(TSetType);
TSetType(TSet).FBaseType := TBase;
FSymbolInfo := SymbolTable.AllocSymbolInfo(scType, TSet);
end;
{ TProd_ArrayType }
procedure TProd_ArrayType.Parse;
var
I: Integer;
T: TSymbolType;
ElemType: TSymbolInfo;
begin
Parser.GetNextToken; // array
CheckTerminal(tkLBracket); // verifica '[' sem obter o próximo token;
// isso é para o uso da inserção '0..'
while True do
begin
Compiler.State := Compiler.State + [csInArrayDecl];
Compile(TProd_IndexType);
Compiler.State := Compiler.State - [csInArrayDecl];
if Parser.CurrentToken <> tkComma then
Break;
// Parser.GetNextToken; // comma; despreza a vírgula, da mesma forma que o
// colchete inicial
end;
GetTerminal(tkRBracket);
GetTerminal(tkRWof);
ElemType := Compile(TProd_Type).SymbolInfo;
for I := ProductionCount - 2 downto 0 do
begin
T := SymbolTable.AllocType(TArrayType);
TArrayType(T).FElemSymbol := ElemType;
TArrayType(T).FIndexSymbol := Productions[I].SymbolInfo;
FSymbolInfo := SymbolTable.AllocSymbolInfo(scType, T);
ElemType := FSymbolInfo;
end;
end;
{ TProd_IndexType }
procedure TProd_IndexType.Parse;
begin
FSymbolInfo := Compile(TProd_Type).SymbolInfo;
if not (FSymbolInfo.SymbolType is TOrdinalType) then
Error(sOrdinalTypeRequired, ProductionLine, ProductionCol);
if TOrdinalType(FSymbolInfo.SymbolType).Range = 0 then // 'integer' not allowed
Error(sInvalidIndexType, ProductionLine, ProductionCol);
if TOrdinalType(FSymbolInfo.SymbolType).Range > MAX_RANGE then
Error(sInvalidRange, ProductionLine, ProductionCol);
end;
{ TProd_RecordType }
procedure TProd_RecordType.Parse;
var
T: TRecordType;
Lst: TStringList;
I: Integer;
begin
Parser.GetNextToken; // record
// new scope
TSymbolType(T) := SymbolTable.AllocType(TRecordType);
T.FScope := SymbolTable.NewSymbolTable;
T.FScope.IsRecordScope := True;
T.FFieldList := TList.Create;
SymbolTable.AddScope(T.FScope);
// parse field list
Lst := TStringList.Create;
Lst.CaseSensitive := True;
while True do
begin
// id list
Lst.Clear;
Compiler.State := Compiler.State + [csFindInScope];
GetNewIdentifierList(Lst);
Compiler.State := Compiler.State - [csFindInScope];
GetTerminal(tkColon);
FSymbolInfo := Compile(TProd_Type).SymbolInfo;
// enter fields
for I := 0 to Lst.Count - 1 do
begin
T.FFieldList.Add(
SymbolTable.Enter(Lst[I], scField, FSymbolInfo.SymbolType, MODL_PAC));
T.FSize := T.FSize + FSymbolInfo.SymbolType.Size;
end;
if Parser.CurrentToken = tkRWend then
Break;
GetTerminal(tkSemiColon);
if Parser.CurrentToken = tkRWend then
Break;
end;
Parser.GetNextToken; // end
SymbolTable.RemoveScope;
FSymbolInfo := SymbolTable.AllocSymbolInfo(scType, T);
// associate record type with all fields
for I := 0 to T.FFieldList.Count - 1 do
TSymbolInfo(T.FFieldList[I]).RecordType := T;
Lst.Free;
end;
{ TProd_PointerType }
procedure TProd_PointerType.Parse;
var
Id: String;
T: TPointerType;
BaseT: TSymbolType;
begin
Parser.GetNextToken; // ^ (ponteiro)
GetTerminal(tkRWfor); // para
// verifica se é um identificador
Check([tkId, tkRWstring, tkRWinteger, tkRWreal, tkRWboolean,
tkRWyesOrNo, tkRWchar], sIdentifierExpected);
// guarda o string e consome
Id := Parser.TokenString;
Parser.GetNextToken;
// pesquisa
FSymbolInfo := SymbolTable.FindSymbol(Id);
if (FSymbolInfo <> nil) then
begin
if FSymbolInfo.SymbolClass <> scType then
Error(sTypeIdentExpected, ProductionLine, ProductionCol);
BaseT := FSymbolInfo.SymbolType;
end
else
begin
if not (csInTypeDecl in Compiler.State) then
Error(sTypeIdentExpected, ProductionLine, ProductionCol);
BaseT := nil; // will be solved later (see TProd_TypeDecl.Parse)
end;
TSymbolType(T) := SymbolTable.AllocType(TPointerType);
T.FBaseType := BaseT;
T.FBaseId := Id;
FSymbolInfo := SymbolTable.AllocSymbolInfo(scType, T);
end;
{ TProd_ParamType }
procedure TProd_ParamType.Parse;
var
Id: String;
begin
// verifica se é um identificador de tipo
Check([tkId, tkRWstring, tkRWinteger, tkRWreal, tkRWboolean,
tkRWyesOrNo, tkRWchar], sIdentifierExpected);
// guarda o string e consome
Id := Parser.TokenString;
Parser.GetNextToken;
// procura na tabela, verificando se é um tipo
FSymbolInfo := SymbolTable.FindSymbol(Id);
if FSymbolInfo = nil then
Error(Format(sUndeclaredIdentifier, [Id]), ProductionLine, ProductionCol)
else if FSymbolInfo.SymbolClass <> scType then
Error(sTypeIdentExpected, ProductionLine, ProductionCol);
end;
{ TProd_VarDeclPart }
procedure TProd_VarDeclPart.Parse;
begin
Parser.GetNextToken; // var
repeat
Compile(TProd_VarDecl);
until Parser.CurrentToken <> tkId;
end;
{ TProd_VarDecl }
procedure TProd_VarDecl.Parse;
var
I: Integer;
Lst: TStringList;
ProdType: TProd_Type;
begin
Lst := TStringList.Create;
Lst.CaseSensitive := True;
try
Compiler.State := Compiler.State + [csFindInScope];
GetNewIdentifierList(Lst);
Compiler.State := Compiler.State - [csFindInScope];
GetTerminal(tkColon);
ProdType := TProd_Type(Compile(TProd_Type));
GetTerminal(tkSemiColon);
for I := 0 to Lst.Count - 1 do
SymbolTable.Enter(Lst[I], scVar, ProdType.SymbolInfo.SymbolType, MODL_PAC);
finally
Lst.Free;
end;
end;
{ TProd_IncludeDecl }
procedure TProd_IncludeDecl.Parse;
var
FileName: String;
StdModl: Boolean;
begin
Parser.GetNextToken; // inclui
// obtém o nome do arquivo a ser incluído
if Parser.CurrentToken <> tkString then
Error(sFileNameExpected, ProductionLine, ProductionCol);
FileName := Parser.TokenValue.AsString;
StdModl := IsStandardModule(FileName);
if not StdModl then
FileName := FrmConfig.NomeModuloCompleto(FileName);
Parser.GetNextToken; // consome o nome do arquivo
// consome ponto e vírgula obrigatório
GetTerminal(tkSemiColon);
// resolve o caso de módulo padrão
if StdModl then
begin
// inclui na lista (caso já não esteja)
if Compiler.FModlList.IndexOf(FileName) < 0 then
Compiler.FModlList.Add(FileName);
Exit;
end;
// nada a fazer caso o arquivo já tenha sido incluído
if (Compiler.FIncludeList.IndexOf(FileName) >= 0) or
(FileName = Parser.Name) then
Exit;
// verifica se o arquivo existe
if not FileExists(FileName) then
Error(Format(sFileNotFound, [FileName]), ProductionLine, ProductionCol);
// empilha novo parser e compila o arquivo incluído
Compiler.PushStream(FileName);
try
Compile(TProd_DeclPart);
finally
Compiler.PopStream;
end;
end;
{ TProd_CompoundStmt }
procedure TProd_CompoundStmt.Parse;
begin
GetTerminal(tkRWbegin);
repeat
if Parser.CurrentToken = tkRWend then
Break;
Compile(TProd_Stmt);
if Parser.CurrentToken <> tkSemiColon then
Break;
Parser.GetNextToken; // semicolon
until Parser.CurrentToken in [tkRWend, tkEndOfSource];
GetTerminal(tkRWend);
end;
{ TProd_Stmt }
procedure TProd_Stmt.Parse;
begin
Check(Set_FirstStmt, sStmtExpected);
case Parser.CurrentToken of
tkSemiColon:
Parser.GetNextToken; // ;
tkRWbegin:
Compile(TProd_CompoundStmt);
tkId:
begin
// test for some standard procedures
if StandardProcedure(Parser.TokenString) then
Exit;
// user procedure or error
FSymbolInfo := SymbolTable.FindSymbol(Parser.TokenString);
if FSymbolInfo = nil then
Error(Format(sUndeclaredIdentifier, [Parser.TokenString]),
ProductionLine, ProductionCol)
else if FSymbolInfo.SymbolClass = scProcedure then
Compile(TProd_ProcedureCall)
// else if FSymbolInfo.SymbolClass = scFunction then
// Compile(TProd_FunctionCall)
else
Compile(TProd_AssignStmt);
end;
tkRWif:
Compile(TProd_IfStmt);
tkRWwhile:
Compile(TProd_WhileStmt);
tkRWrepeat:
Compile(TProd_RepeatStmt);
tkRWfor:
// Compile(TProd_ForStmt);
Compile(TProd_ForStmt_2);
tkRWwrite:
Compile(TProd_WriteStmt);
tkRWwriteln:
Compile(TProd_WritelnStmt);
tkRWread:
Compile(TProd_ReadStmt);
tkRWwith:
Compile(TProd_WithStmt);
tkRWnew:
Compile(TProd_NewStmt);
tkRWdispose:
Compile(TProd_DisposeStmt);
tkRWchoose:
Compile(TProd_CaseStmt);
tkRWreturn:
Compile(TProd_ReturnStmt);
tkIncrement, tkDecrement:
Compile(TProd_PreAssignStmt);
end;
end;
procedure TProd_Stmt.Interpret;
begin
Application.ProcessMessages;
if Compiler.FTerminate then
Error(sUserBreak, ProductionLine, ProductionCol);
VerifyDebug(ProductionLine, ProductionCol, Parser);
inherited Interpret;
end;
{ TProd_AssignStmt }
procedure TProd_AssignStmt.Parse;
var
T: TSymbolType;
begin
FSymbolInfo := SymbolTable.FindSymbol(Parser.TokenString);
if FSymbolInfo = nil then
Error(Format(sUndeclaredIdentifier, [Parser.TokenString]), ProductionLine,
ProductionCol);
if not (FSymbolInfo.SymbolClass in [scVar, scField, scVarParam,
scFunction]) then
Error(sLeftSide, ProductionLine, ProductionCol);
// if FSymbolInfo.SymbolClass = scFunction then
// Compile(TProd_FunctionAssign)
// else
Compile(TProd_VarReference);
if Parser.CurrentToken = tkAssign then
begin
FIsAssignment := True;
GetTerminal(tkAssign);
Compile(TProd_Expression);
T := CheckTypes(Productions[0].SymbolInfo.SymbolType,
Productions[1].SymbolInfo.SymbolType, tkAssign);
Productions[1].PromoteTo(T);
end
else if (Parser.CurrentToken = tkIncrement) or
(Parser.CurrentToken = tkDecrement) then
begin
FIsIncrDecr := True;
FTokIncrDecr := Parser.CurrentToken;
if not (Productions[0].SymbolInfo.SymbolType.TypeClass in [tcInteger]) then
Error(sIntExprExpected, ProductionLine, ProductionCol);
Parser.GetNextToken; // ++ ou --
end;
end;
procedure TProd_AssignStmt.Interpret;
var
Si: TSymbolInfo;
T: TOrdinalType;
OrdValue: Integer;
begin
Si := nil; // evita um warning do compilador
if FIsAssignment then
begin
Productions[1].Interpret; // expression
Si := Productions[1].SymbolInfo;
// test promotion
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
end;
Productions[0].Interpret; // var reference
if FIsAssignment then
begin
// check range
if Productions[0].SymbolInfo.SymbolType is TOrdinalType then
begin
T := TOrdinalType(Si.SymbolType); // expression must be ordinal
OrdValue := T.OrdinalValue(Si);
T := TOrdinalType(Productions[0].SymbolInfo.SymbolType);
if (OrdValue < T.MinValue) or (OrdValue > T.MaxValue) then
Error(sAssignmentOutOfRange, ProductionLine, ProductionCol);
end;
Operate(Productions[0].SymbolInfo, Si, nil, tkAssign);
// atualiza na memoria
SymbolTable.UpdateMem(Productions[0].SymbolInfo.SymbolType,
Integer(Productions[0].SymbolInfo.Address));
end
else if FIsIncrDecr then
begin
if FTokIncrDecr = tkIncrement then
Inc(PInteger(Productions[0].SymbolInfo.Address)^)
else
Dec(PInteger(Productions[0].SymbolInfo.Address)^);
// atualiza na memoria
SymbolTable.UpdateMem(Productions[0].SymbolInfo.SymbolType,
Integer(Productions[0].SymbolInfo.Address));
end;
end;
{ TProd_PreAssignStmt }
procedure TProd_PreAssignStmt.Parse;
begin
FTokIncrDecr := Parser.CurrentToken;
Parser.GetNextToken; // ++ ou --
FSymbolInfo := SymbolTable.FindSymbol(Parser.TokenString);
if FSymbolInfo = nil then
Error(Format(sUndeclaredIdentifier, [Parser.TokenString]), ProductionLine,
ProductionCol);
if not (FSymbolInfo.SymbolClass in [scVar, scField, scVarParam,
scFunction]) then
Error(sLeftSide, ProductionLine, ProductionCol);
Compile(TProd_VarReference);
if not (Productions[0].SymbolInfo.SymbolType.TypeClass in [tcInteger]) then
Error(sIntExprExpected, ProductionLine, ProductionCol);
end;
procedure TProd_PreAssignStmt.Interpret;
begin
Productions[0].Interpret; // var reference
if FTokIncrDecr = tkIncrement then
Inc(PInteger(Productions[0].SymbolInfo.Address)^)
else
Dec(PInteger(Productions[0].SymbolInfo.Address)^);
// atualiza na memoria
SymbolTable.UpdateMem(Productions[0].SymbolInfo.SymbolType,
Integer(Productions[0].SymbolInfo.Address));
end;
{ TProd_GetPenPosX }
procedure TProd_GetPenPosX.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // obtX
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_GetPenPosX.Interpret;
var
Si: TSymbolInfo;
Q: TQuadro;
V: Integer;
begin
Productions[0].Interpret; // Tela (TQuadro)
Si := Productions[0].SymbolInfo;
V := PInteger(Si.Address)^;
{ obtém o quadro }
Q := TQuadro(V);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ obtém a posição }
PInteger(FSymbolInfo.Address)^ := Q.obt_caneta_x();
end;
{ TProd_GetPenPosY }
procedure TProd_GetPenPosY.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // obtY
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_GetPenPosY.Interpret;
var
Si: TSymbolInfo;
Q: TQuadro;
V: Integer;
begin
Productions[0].Interpret; // Tela (TQuadro)
Si := Productions[0].SymbolInfo;
V := PInteger(Si.Address)^;
{ obtém o quadro }
Q := TQuadro(V);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ obtém a posição }
PInteger(FSymbolInfo.Address)^ := Q.obt_caneta_y();
end;
{ TProd_BackgroundColor }
procedure TProd_BackgroundColor.Parse;
begin
Parser.GetNextToken; // BackgroundColor
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_BackgroundColor.Interpret;
begin
PInteger(FSymbolInfo.Address)^ := FrmDSL.PaintBox.Color;
end;
{ TProd_KeyPressed }
procedure TProd_KeyPressed.Parse;
begin
Parser.GetNextToken; // KeyPressed
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeChar);
end;
procedure TProd_KeyPressed.Interpret;
begin
PChar(FSymbolInfo.Address)^ := Compiler.FKeyPressed;
end;
{ TProd_MouseState }
procedure TProd_MouseState.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // EstadoMouse
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // estado
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeBoolean);
end;
procedure TProd_MouseState.Interpret;
var
Si: TSymbolInfo;
Estado: Integer;
Shift: TShiftState;
begin
Productions[0].Interpret; // estado
Si := Productions[0].SymbolInfo;
Estado := PInteger(Si.Address)^;
Shift := [];
if ((EV_DIR and Estado) <> 0) then
Shift := Shift + [ssRight];
if ((EV_ESQ and Estado) <> 0) then
Shift := Shift + [ssLeft];
{ Resultado da função é: conjunto interseção entre Shift e
Compiler.FShiftState é igual a Shift }
PBoolean(FSymbolInfo.Address)^ := (Shift * Compiler.FShiftState) >= Shift;
end;
{ TProd_KeyboardState }
procedure TProd_KeyboardState.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // EstadoTeclado
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // estado
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeBoolean);
end;
procedure TProd_KeyboardState.Interpret;
var
Si: TSymbolInfo;
Estado: Integer;
Shift: TShiftState;
begin
Productions[0].Interpret; // estado
Si := Productions[0].SymbolInfo;
Estado := PInteger(Si.Address)^;
Shift := [];
if ((EV_SHIFT and Estado) <> 0) then
Shift := Shift + [ssShift];
if ((EV_ALT and Estado) <> 0) then
Shift := Shift + [ssAlt];
if ((EV_CTRL and Estado) <> 0) then
Shift := Shift + [ssCtrl];
{ Resultado da função é: conjunto interseção entre Shift e
Compiler.FShiftState contém a Shift }
PBoolean(FSymbolInfo.Address)^ := (Shift * Compiler.FShiftState) >= Shift;
end;
{ TProd_NewFrame }
procedure TProd_NewFrame.Parse;
begin
Parser.GetNextToken; // dsl_quadroNovo()
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_NewFrame.Interpret;
var
Bmp: Graphics.TBitmap;
begin
Bmp := Graphics.TBitmap.Create;
Bmp.Canvas.Brush.Color := clBtnFace; // ATENÇÃO - Mesma cor da propriedade
// Color do componente PaintBox
Bmp.Transparent := True;
Bmp.TransparentMode := tmFixed;
Bmp.TransparentColor := clBtnFace; // ATENÇÃO - Ver comentário acima
PInteger(FSymbolInfo.Address)^ := Integer(Bmp);
Compiler.FBitmapList.Add(Bmp);
end;
{ TProd_novaJanela }
procedure TProd_novaJanela.Parse;
begin
Parser.GetNextToken; // novaJanela
GetTerminal(tkLParen);
(*
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
*)
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novaJanela.Interpret;
var
Q: TQuadroForm;
begin
// verifica se ultrapassa limite de janelas
if Compiler.FTQuadroList.Count >= MAX_JANELAS then
Error(sLimiteJanelasAtingido, ProductionLine, ProductionCol);
// cria o form
Application.CreateForm(TFrmJanela, FrmJanela);
// cria o TQuadro
Q := TQuadroForm.Cria(FrmJanela);
FrmJanela.Tag := Integer(Q);
Compiler.FTQuadroList.Add(Q);
PInteger(FSymbolInfo.Address)^ := Integer(Q);
end;
{ TProd_altVisJanela }
procedure TProd_altVisJanela.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // altVisJanela
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // vis (visibilidade)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeBoolean then
Error(sBoolExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_altVisJanela.Interpret;
var
Si: TSymbolInfo;
Jan: Integer; // Janela
Vis: Boolean;
begin
Productions[0].Interpret; // janela
Si := Productions[0].SymbolInfo;
Jan := PInteger(Si.Address)^;
Productions[1].Interpret; // vis
Si := Productions[1].SymbolInfo;
Vis := PBoolean(Si.Address)^;
// verifica se a janela é válida
if not (TObject(Jan) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// altera a visibilidade
TQuadro(Jan).alt_vis_janela(Vis);
end;
{ TProd_novoBotao }
procedure TProd_novoBotao.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novoBotão
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novoBotao.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Btn: TMeuSpeedButton;
JanelaMaeOk: Boolean;
Q: TQuadro;
Botao: TQuadroBotao;
JanelaMae: TWinControl;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
Q := TQuadro(V[0]);
JanelaMaeOk := (Q is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// obtém a janela mãe
JanelaMae := Q.obt_win_control();
if (JanelaMae = nil) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de janelas
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o botão
Btn := TMeuSpeedButton.Create(nil);
Btn.Parent := JanelaMae;
Btn.SetBounds(V[1], V[2], V[3], V[4]);
Btn.Caption := Ps^; // texto
// eventos
Btn.OnClick := Compiler.TrataOnClickBotao;
Btn.OnMouseDown := Compiler.TrataOnMouseDownBotao;
Btn.OnMouseUp := Compiler.TrataOnMouseUpBotao;
// cria o TQuadro
Botao := TQuadroBotao.Cria(Btn);
Btn.Tag := Integer(Botao);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(Botao);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(Botao);
end;
{ TProd_novoRotulo }
procedure TProd_novoRotulo.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novoRótulo
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novoRotulo.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Lbl: TLabel;
JanelaMaeOk: Boolean;
JanelaMae: TWinControl;
Q: TQuadro;
Rotulo: TQuadroRotulo;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if Q = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de janelas
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o label (rótulo)
Lbl := TLabel.Create(nil);
Lbl.Parent := JanelaMae;
Lbl.AutoSize := True;
Lbl.SetBounds(V[1], V[2], V[3], V[4]);
Lbl.Caption := Ps^; // texto
// eventos
Lbl.OnClick := Compiler.TrataOnClickBotao;
Lbl.OnMouseDown := Compiler.TrataOnMouseDownBotao;
Lbl.OnMouseUp := Compiler.TrataOnMouseUpBotao;
// cria o TQuadro
Rotulo := TQuadroRotulo.Cria(Lbl);
Lbl.Tag := Integer(Rotulo);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(Rotulo);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(Rotulo);
end;
{ TProd_novoEdtLin }
procedure TProd_novoEdtLin.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novoEdtLin
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novoEdtLin.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Edt: TEdit;
JanelaMaeOk: Boolean;
Q: TQuadro;
JanelaMae: TWinControl;
EditorLin: TQuadroEditorLin;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if JanelaMae = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de janelas
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TEdit (EdtLin)
Edt := TEdit.Create(nil);
Edt.Parent := JanelaMae;
Edt.AutoSize := False;
Edt.SetBounds(V[1], V[2], V[3], V[4]);
Edt.Text := Ps^; // texto
// eventos
Edt.OnClick := Compiler.TrataOnClickBotao;
Edt.OnMouseDown := Compiler.TrataOnMouseDownBotao;
Edt.OnMouseUp := Compiler.TrataOnMouseUpBotao;
// cria o TQuadroEditorLin
EditorLin := TQuadroEditorLin.Cria(Edt);
Edt.Tag := Integer(EditorLin);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(EditorLin);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(EditorLin);
end;
{ TProd_novaCxMarca }
procedure TProd_novaCxMarca.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novaCxMarca
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novaCxMarca.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Cx: TCheckBox;
JanelaMaeOk: Boolean;
Q: TQuadro;
CaixaMarca: TQuadroCaixaMarca;
JanelaMae: TWinControl;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if JanelaMae = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de componentes
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TCheckBox (CxMarca)
Cx := TCheckBox.Create(nil);
Cx.Parent := JanelaMae;
Cx.SetBounds(V[1], V[2], V[3], V[4]);
Cx.Caption := Ps^; // texto
// eventos
Cx.OnClick := Compiler.TrataOnClickBotao;
Cx.OnMouseDown := Compiler.TrataOnMouseDownBotao;
Cx.OnMouseUp := Compiler.TrataOnMouseUpBotao;
// cria o TQuadroCaixaMarca
CaixaMarca := TQuadroCaixaMarca.Cria(Cx);
Cx.Tag := Integer(CaixaMarca);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(CaixaMarca);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(CaixaMarca);
end;
{ TProd_novaCxEscolha }
procedure TProd_novaCxEscolha.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novaCxEscolha
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novaCxEscolha.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Cx: TRadioButton;
JanelaMaeOk: Boolean;
JanelaMae: TWinControl;
CaixaEscolha: TQuadroCaixaEscolha;
Q: TQuadro;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if JanelaMae = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de componentes
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TRadioButton (CxEscolha)
Cx := TRadioButton.Create(nil);
Cx.Parent := JanelaMae;
Cx.SetBounds(V[1], V[2], V[3], V[4]);
Cx.Caption := Ps^; // texto
// eventos
Cx.OnClick := Compiler.TrataOnClickBotao;
Cx.OnMouseDown := Compiler.TrataOnMouseDownBotao;
Cx.OnMouseUp := Compiler.TrataOnMouseUpBotao;
// cria o TQuadroCaixaEscolha
CaixaEscolha := TQuadroCaixaEscolha.Cria(Cx);
Cx.Tag := Integer(CaixaEscolha);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(CaixaEscolha);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(CaixaEscolha);
end;
{ TProd_novaCxLst }
procedure TProd_novaCxLst.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novaCxLst
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novaCxLst.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Cx: TListBox;
JanelaMaeOk: Boolean;
JanelaMae: TWinControl;
Q: TQuadro;
CaixaLista: TQuadroCaixaLista;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if JanelaMae = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de componentes
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TListBox (CxLst)
Cx := TListBox.Create(nil);
Cx.Parent := JanelaMae;
Cx.SetBounds(V[1], V[2], V[3], V[4]);
Cx.Items.Text := Ps^; // texto
// eventos
Cx.OnClick := Compiler.TrataOnClickBotao;
Cx.OnMouseDown := Compiler.TrataOnMouseDownBotao;
Cx.OnMouseUp := Compiler.TrataOnMouseUpBotao;
// cria a CaixaLista
CaixaLista := TQuadroCaixaLista.Cria(Cx);
Cx.Tag := Integer(CaixaLista);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(CaixaLista);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(CaixaLista);
end;
{ TProd_novaCxCmb }
procedure TProd_novaCxCmb.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novaCxCmb
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novaCxCmb.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Cx: TComboBox;
JanelaMaeOk: Boolean;
JanelaMae: TWinControl;
Q: TQuadro;
CaixaComb: TQuadroCaixaComb;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if JanelaMae = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de componentes
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TComboBox (CxCmb)
Cx := TComboBox.Create(nil);
Cx.Parent := JanelaMae;
Cx.SetBounds(V[1], V[2], V[3], V[4]);
Cx.Items.Text := Ps^; // texto
// eventos
Cx.OnClick := Compiler.TrataOnClickBotao;
// cria o TQuadroCaixaComb
CaixaComb := TQuadroCaixaComb.Cria(Cx);
Cx.Tag := Integer(CaixaComb);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(CaixaComb);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(CaixaComb);
end;
{ TProd_novaCxGrupo }
procedure TProd_novaCxGrupo.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novaCxGrupo
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novaCxGrupo.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Cx: TMeuGroupBox;
JanelaMaeOk: Boolean;
JanelaMae: TWinControl;
Q: TQuadro;
CaixaGrupo: TQuadroGroupBox;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if JanelaMae = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de componentes
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TGroupBox (CxGrupo)
Cx := TMeuGroupBox.Create(nil);
Cx.Parent := JanelaMae;
Cx.SetBounds(V[1], V[2], V[3], V[4]);
Cx.Caption := Ps^; // texto
// eventos
Cx.OnClick := Compiler.TrataOnClickBotao;
Cx.OnMouseDown := Compiler.TrataOnMouseDownBotao;
Cx.OnMouseUp := Compiler.TrataOnMouseUpBotao;
// cria o TQuadroGroupBox
CaixaGrupo := TQuadroGroupBox.Cria(Cx);
Cx.Tag := Integer(CaixaGrupo);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(CaixaGrupo);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(CaixaGrupo);
end;
{ TProd_novoPainel }
procedure TProd_novoPainel.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novoPainel
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novoPainel.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Cx: TMeuPanel;
JanelaMaeOk: Boolean;
JanelaMae: TWinControl;
Q: TQuadro;
Panel: TQuadroPanel;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if JanelaMae = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de componentes
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TPanel (Painel)
Cx := TMeuPanel.Create(nil);
Cx.Parent := JanelaMae;
Cx.SetBounds(V[1], V[2], V[3], V[4]);
Cx.Caption := Ps^; // texto
// eventos
Cx.OnClick := Compiler.TrataOnClickBotao;
Cx.OnMouseDown := Compiler.TrataOnMouseDownBotao;
Cx.OnMouseUp := Compiler.TrataOnMouseUpBotao;
// cria o TQuadroPanel
Panel := TQuadroPanel.Cria(Cx);
Cx.Tag := Integer(Panel);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(Panel);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(Panel);
end;
{ TProd_novaImagem }
procedure TProd_novaImagem.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novaImagem
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // nome imagem
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novaImagem.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Img: TImage;
JanelaMaeOk: Boolean;
JanelaMae: TWinControl;
Q: TQuadro;
Imagem: TQuadroImagem;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // nome
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if JanelaMae = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de componentes
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TImage (Imagem)
Img := TImage.Create(nil);
Img.Parent := JanelaMae;
Img.SetBounds(V[1], V[2], V[3], V[4]);
Img.AutoSize := False;
Img.Stretch := True;
if not CarregaImg(Img, Ps^) then
Error(sImagem + ' "' + Ps^ + '" ' + sNaoEncontrada, ProductionLine, ProductionCol);
// eventos
Img.OnClick := Compiler.TrataOnClickBotao;
Img.OnMouseDown := Compiler.TrataOnMouseDownBotao;
Img.OnMouseUp := Compiler.TrataOnMouseUpBotao;
// cria o TQuadroImagem
Imagem := TQuadroImagem.Cria(Img);
Img.Tag := Integer(Imagem);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(Imagem);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(Imagem);
end;
{ TProd_novaImagemCrg }
procedure TProd_novaImagemCrg.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // nova_imagem_crg
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // nome imagem
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novaImagemCrg.Interpret;
var
Si: TSymbolInfo;
Ps: PString;
Bmp: Graphics.TBitmap;
Imagem: TQuadroBitmap;
begin
Productions[0].Interpret; // nome
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
Ps := PString(Si.Address);
// verifica se ultrapassa limite de componentes
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TBitmap
Bmp := Graphics.TBitmap.Create;
if not CarregaBmp(Bmp, Ps^) then
Error(sImagem + ' "' + Ps^ + '" ' + sNaoEncontrada, ProductionLine, ProductionCol);
// eventos
// sem eventos
// cria o TQuadroBitmap
Imagem := TQuadroBitmap.Cria(Bmp);
// Img.Tag := Integer(Imagem);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(Imagem);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(Imagem);
end;
{ TProd_novoEdtLinhas }
procedure TProd_novoEdtLinhas.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novoEdtLinhas
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_novoEdtLinhas.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Edt: TMemo;
JanelaMaeOk: Boolean;
JanelaMae: TWinControl;
Q: TQuadro;
EditorTxt: TQuadroEditorTxt;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if JanelaMae = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de janelas
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TMemo (EdtLinhas)
Edt := TMemo.Create(nil);
Edt.Parent := JanelaMae;
Edt.SetBounds(V[1], V[2], V[3], V[4]);
Edt.ScrollBars := ssBoth;
Edt.Text := Ps^; // texto
// eventos
Edt.OnClick := Compiler.TrataOnClickBotao;
Edt.OnMouseDown := Compiler.TrataOnMouseDownBotao;
Edt.OnMouseUp := Compiler.TrataOnMouseUpBotao;
// cria o TQuadroEditorTxt
EditorTxt := TQuadroEditorTxt.Cria(Edt);
Edt.Tag := Integer(EditorTxt);
// inclui na lista de componentes
Compiler.FTQuadroList.Add(EditorTxt);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(EditorTxt);
end;
{ TProd_libJanela }
procedure TProd_libJanela.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // libJanela
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_libJanela.Interpret;
var
Si: TSymbolInfo;
V: Integer;
begin
Productions[0].Interpret; // janela
Si := Productions[0].SymbolInfo;
V := PInteger(Si.Address)^;
// verifica se a janela é válida
if not (TObject(V) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// remove da lista
Compiler.FTQuadroList.Remove(Pointer(V));
// libera o TQuadro
TQuadro(V).Free;
end;
{ TProd_altPosJanela }
procedure TProd_altPosJanela.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // altPosJanela
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_altPosJanela.Interpret;
var
Si: TSymbolInfo;
V: array [0..2] of Integer;
I: Integer;
begin
for I := 0 to 2 do
begin
Productions[I].Interpret; // janela, x, y
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
// verifica se o componente é valido
if not (TObject(V[0]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// altera a posição
TQuadro(V[0]).alt_pos_janela(V[1], V[2]);
end;
{ TProd_copJanela }
procedure TProd_copJanela.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // copJanela
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // jan
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // janOrig
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_copJanela.Interpret;
var
Si: TSymbolInfo;
V: array [0..3] of Integer;
Jan, JanOrig: TQuadro;
I: Integer;
begin
for I := 0 to 3 do
begin
Productions[I].Interpret; // jan, x, y, janOrig
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
// verifica se as janelas são válidas
if not (TObject(V[0]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
if not (TObject(V[3]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Jan := TQuadro(V[0]);
JanOrig := TQuadro(V[3]);
Jan.cop_janela(V[1], V[2], JanOrig);
end;
{ TProd_copJanelaDist }
procedure TProd_copJanelaDist.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // copJanela
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // jan
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // janOrig
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
(*
procedure TProd_copJanelaDist.Interpret;
var
Si: TSymbolInfo;
V: array [0..5] of Integer;
Jan, JanOrig: TQuadro;
I: Integer;
begin
for I := 0 to 5 do
begin
Productions[I].Interpret; // jan, x1, y1, x2, y2, janOrig
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
// verifica se as janelas são válidas
if not (TObject(V[0]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
if not (TObject(V[5]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Jan := TQuadro(V[0]);
JanOrig := TQuadro(V[5]);
// copia JanOrig para o retângulo (x1, y1, x2, y2) de Jan
// copia na "tela" só se visível
if Jan.Form.Visible then
Jan.CanvasForm.StretchDraw(Rect(V[1], V[2], V[3], V[4]), JanOrig.Bmp);
// sempre copia no bitmap
Jan.Bmp.Canvas.StretchDraw(Rect(V[1], V[2], V[3], V[4]), JanOrig.Bmp);
end;
*)
{ TProd_copJanelaDistRot }
(*
procedimento copJanelaDistRot(jan: Janela;
x1, y1, x2, y2: inteiro;
rot: real;
xr, yr: inteiro;
janOrig: Janela);
*)
procedure TProd_copJanelaDistRot.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // copJanelaDistRot
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // jan
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // rot
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // xr
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // yr
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // janOrig
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
(*
procedure TProd_copJanelaDistRot.Interpret;
var
Si: TSymbolInfo;
X1, Y1, X2, Y2, Xrot, Yrot, V: Integer;
Rot: Extended;
Jan, JanOrig: TQuadro;
begin
Productions[0].Interpret; // jan
Si := Productions[0].SymbolInfo;
V := PInteger(Si.Address)^;
if not (TObject(V) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Jan := TQuadro(V);
Productions[1].Interpret; // x1
Si := Productions[1].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[2].Interpret; // y1
Si := Productions[2].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[3].Interpret; // x2
Si := Productions[3].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[4].Interpret; // y2
Si := Productions[4].SymbolInfo;
Y2 := PInteger(Si.Address)^;
Productions[5].Interpret; // rot
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Rot := PExtended(Si.Address)^;
Productions[6].Interpret; // xr
Si := Productions[6].SymbolInfo;
Xrot := PInteger(Si.Address)^;
Productions[7].Interpret; // yr
Si := Productions[7].SymbolInfo;
Yrot := PInteger(Si.Address)^;
Productions[8].Interpret; // janOrig
Si := Productions[8].SymbolInfo;
V := PInteger(Si.Address)^;
if not (TObject(V) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
JanOrig := TQuadro(V);
// faz a cópia de acordo com o uso de rotação
if Rot = 0.0 then
begin
// copia JanOrig para o retângulo (x1, y1, x2, y2) de Jan
// copia na "tela" só se visível
if Jan.Form.Visible then
Jan.CanvasForm.StretchDraw(Rect(X1, Y1, X2, Y2), JanOrig.Bmp);
// sempre copia no bitmap
Jan.Bmp.Canvas.StretchDraw(Rect(X1, Y1, X2, Y2), JanOrig.Bmp);
end
else
begin
// faz a cópia com rotação no bitmap
PreparaTransfDistRot(Jan.Bmp.Canvas, -Rot, Xrot, Yrot);
Jan.Bmp.Canvas.StretchDraw(Rect(Round(X1 - Xrot), Round(Y1 - Yrot),
Round(X2 - Xrot), Round(Y2 - Yrot)),
JanOrig.Bmp);
RestauraTransfDistRot(Jan.Bmp.Canvas);
// se visível, faz a cópia no form
if Jan.Form.Visible then
begin
PreparaTransfDistRot(Jan.CanvasForm, -Rot, Xrot, Yrot);
Jan.CanvasForm.StretchDraw(Rect(Round(X1 - Xrot), Round(Y1 - Yrot),
Round(X2 - Xrot), Round(Y2 - Yrot)),
JanOrig.Bmp);
RestauraTransfDistRot(Jan.CanvasForm);
end;
end;
end;
*)
{ TProd_copJanelaRot }
(*
procedimento copJanelaRot(jan: Janela;
x, y: inteiro;
rot: real;
janOrig: Janela);
*)
procedure TProd_copJanelaRot.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // copJanelaRot
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // jan
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // rot
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // janOrig
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
(*
procedure TProd_copJanelaRot.Interpret;
var
Si: TSymbolInfo;
x, y, xDraw, yDraw, V: Integer;
Rot: Extended;
Jan, JanOrig: TQuadro;
begin
Productions[0].Interpret; // jan
Si := Productions[0].SymbolInfo;
V := PInteger(Si.Address)^;
if not (TObject(V) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Jan := TQuadro(V);
Productions[1].Interpret; // x
Si := Productions[1].SymbolInfo;
x := PInteger(Si.Address)^;
Productions[2].Interpret; // y
Si := Productions[2].SymbolInfo;
y := PInteger(Si.Address)^;
Productions[3].Interpret; // rot
Si := Productions[3].SymbolInfo;
if Productions[3].ExecPromotion then
Si := Productions[3].Promoted;
Rot := PExtended(Si.Address)^;
Productions[4].Interpret; // janOrig
Si := Productions[4].SymbolInfo;
V := PInteger(Si.Address)^;
if not (TObject(V) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
JanOrig := TQuadro(V);
// determina (xDraw, yDraw) tendo em conta que (x, y) é o centro
xDraw := x - (JanOrig.Bmp.Width div 2);
yDraw := y - (JanOrig.Bmp.Height div 2);
// faz a cópia com rotação no bitmap
PreparaTransfDistRot(Jan.Bmp.Canvas, -Rot, x, y);
Jan.Bmp.Canvas.Draw(xDraw - x, yDraw - y, JanOrig.Bmp);
// se visível, faz a cópia no form
// if Jan.Form.Visible then
// begin
//
// PreparaTransfDistRot(Jan.CanvasForm, -Rot, x, y);
// Jan.CanvasForm.Draw(xDraw - x, yDraw - y, JanOrig.Bmp);
//
if Jan.Form = FrmDSL then
FrmDSL.PaintBox.Repaint
else
Jan.Form.Repaint;
// end;
end;
*)
{ TProd_obtPos }
procedure TProd_obtPos.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // obtPos
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // componente
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_VarReference); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_VarReference); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_obtPos.Interpret;
(*
var
Si: TSymbolInfo;
V: array [0..2] of Integer;
I, X, Y: Integer;
ehQuadro, ehComp: Boolean;
Ctrl: TControl;
*)
begin
(*
Productions[0].Interpret; // Componente
Si := Productions[0].SymbolInfo;
V[0] := PInteger(Si.Address)^;
// verifica se o componente é valido
ehQuadro := TObject(V[0]) is TQuadro;
ehComp := TObject(V[0]) is TComponent;
if not (ehQuadro or ehComp) then
Error(sComponentTypeExpected, ProductionLine, ProductionCol);
// obtém a posição do componente
// obtPosComp(TObject(V[0]), X, Y);
{ OBS: A rotina obtPosComp está comentada porque resolvi não
implementá-la por enquanto. Na verdade, hoje, 23/07/2008,
resolvi não incluir no SW-Tutor as coisas referentes ao
uso de componentes. Está me parecendo uma complicação
incluir não
}
// atualiza os argumentos var
Productions[1].Interpret; // x
Si := Productions[1].SymbolInfo;
PInteger(Si.Address)^ := X;
Productions[2].Interpret; // y
Si := Productions[2].SymbolInfo;
PInteger(Si.Address)^ := Y;
// atualiza na memoria
SymbolTable.UpdateMem(Productions[1].SymbolInfo.SymbolType,
Integer(Productions[1].SymbolInfo.Address));
SymbolTable.UpdateMem(Productions[2].SymbolInfo.SymbolType,
Integer(Productions[2].SymbolInfo.Address));
*)
end;
{ TProd_altTamJanela }
procedure TProd_altTamJanela.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // altTam
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_altTamJanela.Interpret;
var
Si: TSymbolInfo;
V: array [0..2] of Integer;
I: Integer;
Q: TQuadro;
begin
for I := 0 to 2 do
begin
Productions[I].Interpret; // janela, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
// verifica se o componente é valido
if not (TObject(V[0]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
// verifica largura e altura
if ((V[1] < 0) or (V[1] > MAX_TAM_JANELA) or
(V[2] < 0) or (V[2] > MAX_TAM_JANELA)) then
Error(sTamanhoJanelaMax, ProductionLine, ProductionCol);
// altera o tamanho
Q.alt_tam_janela(V[1], V[2]);
end;
{ TProd_obtTamJanela }
procedure TProd_obtTamJanela.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // obtTamJanela
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // var largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // var altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_obtTamJanela.Interpret;
var
SiJanela, SiLargura, SiAltura: TSymbolInfo;
V: Integer;
Q: TQuadro;
Larg, Altu: Integer;
begin
Productions[0].Interpret; // janela
SiJanela := Productions[0].SymbolInfo;
V := PInteger(SiJanela.Address)^;
Productions[1].Interpret; // largura
SiLargura := Productions[1].SymbolInfo;
Productions[2].Interpret; // altura
SiAltura := Productions[2].SymbolInfo;
// verifica se o componente é valido
if not (TObject(V) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V);
// obtém tamanho
Q.obt_tam_janela(Larg, Altu);
PInteger(SiLargura.Address)^ := Larg;
PInteger(SiAltura.Address)^ := Altu;
// atualiza na memoria
SymbolTable.UpdateMem(SiLargura.SymbolType,
Integer(SiLargura.Address));
SymbolTable.UpdateMem(SiAltura.SymbolType,
Integer(SiAltura.Address));
end;
{ TProd_altCor }
procedure TProd_altCor.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // altCor
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // componente
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cor
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_altCor.Interpret;
var
Si: TSymbolInfo;
V: array [0..1] of Integer;
I: Integer;
begin
for I := 0 to 1 do
begin
Productions[I].Interpret; // componente, cor
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
// verifica se o componente é valido
if not (TObject(V[0]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
TQuadro(V[0]).alt_cor_janela(V[1]);
end;
{ TProd_altTxtJanela }
procedure TProd_altTxtJanela.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // altTxt
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // txt
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
end;
procedure TProd_altTxtJanela.Interpret;
var
Si: TSymbolInfo;
V: Integer;
Txt: String;
begin
Productions[0].Interpret; // janela
Si := Productions[0].SymbolInfo;
V := PInteger(Si.Address)^;
Productions[1].Interpret; // texto
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
Txt := PString(Si.Address)^;
// verifica se o componente é valido
if not (TObject(V) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
TQuadro(V).alt_txt_janela(Txt);
end;
{ TProd_crgImg }
procedure TProd_crgImg.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // crgImg
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // nomeImg
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
end;
procedure TProd_crgImg.Interpret;
var
Si: TSymbolInfo;
V: Integer;
Txt: String;
Q: TQuadro;
begin
Productions[0].Interpret; // janela
Si := Productions[0].SymbolInfo;
V := PInteger(Si.Address)^;
Productions[1].Interpret; // nomeImg
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
Txt := PString(Si.Address)^;
// verifica se o componente é valido
if not (TObject(V) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V);
Q.crg_img(Txt);
end;
{ TProd_crgJanela }
procedure TProd_crgJanela.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // crgJanela
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // jan
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // janOrig
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
(*
procedure TProd_crgJanela.Interpret;
var
Si: TSymbolInfo;
V: array [0..5] of Integer;
I, Width, Height: Integer;
Jan, JanOrig: TQuadro;
begin
for I := 0 to 5 do
begin
Productions[I].Interpret; // jan, janOrig, x1, y1, x2, y2
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
// verifica as janelas jan e janOrig
if not (TObject(V[0]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Jan := TQuadro(V[0]);
if not (TObject(V[1]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
JanOrig := TQuadro(V[1]);
Width := Abs(V[4] - V[2]); // Abs(X2 - X1);
Height := Abs(V[5] - V[3]); // Abs(Y2 - Y1);
Jan.Bmp.Width := Width;
Jan.Bmp.Height := Height;
Jan.Bmp.Canvas.CopyRect(Rect(0, 0, Width, Height),
JanOrig.Bmp.Canvas,
Rect(V[2], V[3], V[4], V[5]));
// exibe, se for o caso
if Jan.Form.Visible then
if Jan = Compiler.FTela then
FrmDSL.PaintBox.Repaint
else
Jan.Form.Repaint;
end;
*)
(*
{ TProd_altFonte }
procedure TProd_altFonte.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // altFonte
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // componente
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // nome fonte
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // tam
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // estilo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cor
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_altFonte.Interpret;
var
Si: TSymbolInfo;
Comp, Tam, Estilo, Cor: Integer;
Nome: String;
ehQuadro, ehComp: Boolean;
Fonte: TFont;
begin
Productions[0].Interpret; // componente
Si := Productions[0].SymbolInfo;
Comp := PInteger(Si.Address)^;
Productions[1].Interpret; // nome
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
Nome := PString(Si.Address)^;
Productions[2].Interpret; // tam
Si := Productions[2].SymbolInfo;
Tam := PInteger(Si.Address)^;
Productions[3].Interpret; // estilo
Si := Productions[3].SymbolInfo;
Estilo := PInteger(Si.Address)^;
Productions[4].Interpret; // cor
Si := Productions[4].SymbolInfo;
Cor := PInteger(Si.Address)^;
// verifica se o componente é valido
if not (TObject(Comp) is TQuadro) then
Error(sComponentTypeExpected, ProductionLine, ProductionCol);
// cria a fonte
Fonte := TFont.Create;
Fonte.Name := Nome;
Fonte.Size := Tam;
Fonte.Color := Cor;
Fonte.Style := IntParaEstiloFonte(Estilo);
// altera a fonte e libera
TQuadro(Comp).alt_fonte(Fonte);
Fonte.Free;
end;
*)
{ TProd_tstEvento }
procedure TProd_tstEvento.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // tstEvento
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Componente
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // evento
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeBoolean);
end;
(*
procedure TProd_tstEvento.Interpret;
var
Si: TSymbolInfo;
V: array [0..1] of Integer;
ehQuadro, ehComp: Boolean;
begin
Productions[0].Interpret; // componente
Si := Productions[0].SymbolInfo;
V[0] := PInteger(Si.Address)^;
Productions[1].Interpret; // evento
Si := Productions[1].SymbolInfo;
V[1] := PInteger(Si.Address)^;
// verifica se o componente é valido
ehQuadro := TObject(V[0]) is TQuadro;
ehComp := TObject(V[0]) is TComponent;
if not (ehQuadro or ehComp) then
Error(sComponentTypeExpected, ProductionLine, ProductionCol);
// verifica o evento
if Compiler.FLastEvent <> V[1] then
begin
PBoolean(FSymbolInfo.Address)^ := False;
Exit;
end;
// verifica se está testando a Tela principal
if V[0] = Integer(Compiler.FTela) then
begin
PBoolean(FSymbolInfo.Address)^ :=
Compiler.FLastEventSender = TObject(FrmDSL.PaintBox);
Exit;
end;
// verifica se está testando uma janela separada
if ehQuadro then
begin
PBoolean(FSymbolInfo.Address)^ :=
Compiler.FLastEventSender = TQuadro(V[0]).Form;
Exit;
end;
// evento só pode ter vindo de um componente
PBoolean(FSymbolInfo.Address)^ :=
Compiler.FLastEventSender = TObject(V[0]);
end;
*)
{ TProd_FrameDispose }
procedure TProd_FrameDispose.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroLibere
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameDispose.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// libere o bitmap
Compiler.FBitmapList.Remove(Bmp);
Bmp.Free;
// atualize o visual
PInteger(Si.Address)^ := 0;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
end;
{ TProd_FileDispose }
procedure TProd_FileDispose.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_arquivoLibere
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // arquivo (TStream)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFileTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FileDispose.Interpret;
var
Si: TSymbolInfo;
Strm: TRWStream;
begin
Productions[0].Interpret; // arquivo
Si := Productions[0].SymbolInfo;
Strm := TRWStream(PInteger(Si.Address)^);
if not (Strm is TRWStream) then
Error(sFileTypeExpected, ProductionLine, ProductionCol);
// libere o arquivo
Compiler.FStreamList.Remove(Strm);
Strm.Free;
// atualize o visual
PInteger(Si.Address)^ := 0;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
end;
{ TProd_FrameReadFromFile }
procedure TProd_FrameReadFromFile.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroLeiaDeArquivo
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // nome do arquivo
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
end;
procedure TProd_FrameReadFromFile.Interpret;
var
Si: TSymbolInfo;
FileName: String;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // nome do arquivo
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
FileName := PString(Si.Address)^;
try
Bmp.LoadFromFile(FileName);
except
Error(Format(sFileNotFound, [FileName]), ProductionLine, ProductionCol);
end;
end;
{ TProd_FrameSetFontName }
procedure TProd_FrameSetFontName.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeNomeDaFonte
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // nome da fonte
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetFontName.Interpret;
var
Si: TSymbolInfo;
FontName: String;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // nome da fonte
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
FontName := PString(Si.Address)^;
Bmp.Canvas.Font.Name := FontName;
end;
{ TProd_FrameTextOut }
procedure TProd_FrameTextOut.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroTexto
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
end;
procedure TProd_FrameTextOut.Interpret;
var
Si: TSymbolInfo;
X, Y: Integer;
Txt: String;
Bmp: Graphics.TBitmap;
BrushStyle: TBrushStyle;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // X
Si := Productions[1].SymbolInfo;
X := PInteger(Si.Address)^;
Productions[2].Interpret; // Y
Si := Productions[2].SymbolInfo;
Y := PInteger(Si.Address)^;
Productions[3].Interpret; // texto
Si := Productions[3].SymbolInfo;
if Productions[3].ExecPromotion then
Si := Productions[3].Promoted;
Txt := PString(Si.Address)^;
// Bmp.Canvas.TextFlags := Bmp.Canvas.TextFlags or ETO_OPAQUE;
BrushStyle := Bmp.Canvas.Brush.Style;
Bmp.Canvas.Brush.Style := bsClear;
Bmp.Canvas.TextOut(X, Y, Txt);
Bmp.Canvas.Brush.Style := BrushStyle;
end;
{ TProd_FrameTextHeight }
procedure TProd_FrameTextHeight.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroAlturaDoTexto
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FrameTextHeight.Interpret;
var
Si: TSymbolInfo;
Txt: String;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // texto
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
Txt := PString(Si.Address)^;
PInteger(FSymbolInfo.Address)^ := Bmp.Canvas.TextHeight(Txt);
end;
{ TProd_FileReader }
procedure TProd_FileReader.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_arquivoLeitor
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // arquivo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FileReader.Interpret;
var
Si: TSymbolInfo;
RWStream: TRWStream;
begin
Productions[0].Interpret; // arquivo
Si := Productions[0].SymbolInfo;
RWStream := TRWStream(PInteger(Si.Address)^);
if not (RWStream is TRWStream) then
Error(sFileTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Integer(RWStream);
end;
{ TProd_FileWriter }
procedure TProd_FileWriter.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_arquivoEscritor
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // arquivo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FileWriter.Interpret;
var
Si: TSymbolInfo;
RWStream: TRWStream;
begin
Productions[0].Interpret; // arquivo
Si := Productions[0].SymbolInfo;
RWStream := TRWStream(PInteger(Si.Address)^);
if not (RWStream is TRWStream) then
Error(sFileTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Integer(RWStream);
end;
{ TProd_TextHeight }
procedure TProd_TextHeight.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // dsl_alturaDoTexto
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_TextHeight.Interpret;
var
Si: TSymbolInfo;
Txt: String;
begin
Productions[0].Interpret; // texto
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
Txt := PString(Si.Address)^;
if Compiler.Canvas <> nil then
PInteger(FSymbolInfo.Address)^ := Compiler.Canvas.TextHeight(Txt);
end;
{ TProd_TextWidth }
procedure TProd_TextWidth.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // dsl_larguraDoTexto
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_TextWidth.Interpret;
var
Si: TSymbolInfo;
Txt: String;
begin
Productions[0].Interpret; // texto
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
Txt := PString(Si.Address)^;
if Compiler.Canvas <> nil then
PInteger(FSymbolInfo.Address)^ := Compiler.Canvas.TextWidth(Txt);
end;
{ TProd_FrameTextWidth }
procedure TProd_FrameTextWidth.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroAlturaDoTexto
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FrameTextWidth.Interpret;
var
Si: TSymbolInfo;
Txt: String;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // texto
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
Txt := PString(Si.Address)^;
PInteger(FSymbolInfo.Address)^ := Bmp.Canvas.TextWidth(Txt);
end;
{ TProd_caixa_marcada }
procedure TProd_caixa_marcada.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // caixa_marcada
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // caixa
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sReaderTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeBoolean);
end;
procedure TProd_caixa_marcada.Interpret;
var
Si: TSymbolInfo;
Q: TQuadro;
V: Integer;
begin
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
V := PInteger(Si.Address)^;
{ obtém o quadro }
Q := TQuadro(V);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PBoolean(FSymbolInfo.Address)^ := Q.caixa_marcada();
end;
{ TProd_ReaderHasChar }
procedure TProd_ReaderHasChar.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_leitorTemCaractere
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // leitor
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sReaderTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeBoolean);
end;
procedure TProd_ReaderHasChar.Interpret;
var
Si: TSymbolInfo;
RWStream: TRWStream;
Has: Boolean;
begin
Productions[0].Interpret; // leitor
Si := Productions[0].SymbolInfo;
RWStream := TRWStream(PInteger(Si.Address)^);
if not (RWStream is TRWStream) then
Error(sReaderTypeExpected, ProductionLine, ProductionCol);
// execute o comando no leitor
Has := False;
try
Has := RWStream.ReaderHasChar();
except
Error(sReaderHasCharFailed, ProductionLine, ProductionCol);
end;
PBoolean(FSymbolInfo.Address)^ := Has;
end;
{ TProd_ReaderNextChar }
procedure TProd_ReaderNextChar.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_leitorProximoCaractere
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // leitor
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sReaderTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeChar);
end;
procedure TProd_ReaderNextChar.Interpret;
var
Si: TSymbolInfo;
RWStream: TRWStream;
Ch: Char;
begin
Productions[0].Interpret; // leitor
Si := Productions[0].SymbolInfo;
RWStream := TRWStream(PInteger(Si.Address)^);
if not (RWStream is TRWStream) then
Error(sReaderTypeExpected, ProductionLine, ProductionCol);
// execute o comando no leitor
Ch := ' '; // só pra tirar um warning
try
Ch := RWStream.ReaderNextChar();
except
Error(sReaderNextCharFailed, ProductionLine, ProductionCol);
end;
PChar(FSymbolInfo.Address)^ := Ch;
end;
{ TProd_WriterWriteChar }
procedure TProd_WriterWriteChar.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_escritorEscrevaCaractere
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // escritor
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sWriterTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // caractere
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeChar then
Error(sCharTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_WriterWriteChar.Interpret;
var
Si: TSymbolInfo;
RWStream: TRWStream;
Ch: Char;
begin
Productions[0].Interpret; // escritor
Si := Productions[0].SymbolInfo;
RWStream := TRWStream(PInteger(Si.Address)^);
if not (RWStream is TRWStream) then
Error(sWriterTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // caractere
Si := Productions[1].SymbolInfo;
Ch := PChar(Si.Address)^;
// execute o comando no escritor
try
RWStream.WriterWriteChar(Ch);
except
Error(sWriterWriteCharFailed, ProductionLine, ProductionCol);
end;
end;
{ TProd_FrameCopyFromScreen }
procedure TProd_FrameCopyFromScreen.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroCopieDaTela
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameCopyFromScreen.Interpret;
var
Si: TSymbolInfo;
X1, Y1, X2, Y2: Integer;
Width, Height: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // X1
Si := Productions[1].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[2].Interpret; // Y1
Si := Productions[2].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[3].Interpret; // X2
Si := Productions[3].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[4].Interpret; // Y2
Si := Productions[4].SymbolInfo;
Y2 := PInteger(Si.Address)^;
// Width := Abs(X2 - X1) + 1;
// Height := Abs(Y2 - Y1) + 1;
Width := Abs(X2 - X1);
Height := Abs(Y2 - Y1);
if Compiler.Canvas <> nil then
begin
Bmp.Width := Width;
Bmp.Height := Height;
Bmp.Canvas.CopyRect(
// Rect(0, 0, Width - 1, Height - 1),
Rect(0, 0, Width, Height),
Compiler.Canvas,
Rect(X1, Y1, X2, Y2));
end;
end;
{ TProd_FrameCopyFromFrame }
procedure TProd_FrameCopyFromFrame.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroCopieDeQuadro
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // quadroOrigem
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameCopyFromFrame.Interpret;
var
Si: TSymbolInfo;
X1, Y1, X2, Y2: Integer;
Width, Height: Integer;
Bmp, BmpOrig: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // quadroOrigem
Si := Productions[1].SymbolInfo;
BmpOrig := Graphics.TBitmap(PInteger(Si.Address)^);
if not (BmpOrig is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[2].Interpret; // X1
Si := Productions[2].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[3].Interpret; // Y1
Si := Productions[3].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[4].Interpret; // X2
Si := Productions[4].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[5].Interpret; // Y2
Si := Productions[5].SymbolInfo;
Y2 := PInteger(Si.Address)^;
// Width := Abs(X2 - X1) + 1;
// Height := Abs(Y2 - Y1) + 1;
Width := Abs(X2 - X1);
Height := Abs(Y2 - Y1);
Bmp.Width := Width;
Bmp.Height := Height;
Bmp.Canvas.CopyRect(
// Rect(0, 0, Width - 1, Height - 1),
Rect(0, 0, Width, Height),
BmpOrig.Canvas,
Rect(X1, Y1, X2, Y2));
end;
{ TProd_BrushStyle }
procedure TProd_BrushStyle.Parse;
begin
Parser.GetNextToken; // BrushStyle
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_BrushStyle.Interpret;
begin
PInteger(FSymbolInfo.Address)^ := Ord(Compiler.Canvas.Brush.Style);
end;
{ TProd_Sqrt }
procedure TProd_Sqrt.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // Sqrt
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, T); // extended expression
end;
procedure TProd_Sqrt.Interpret;
var
Si: TSymbolInfo;
V: Extended;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
V := PExtended(Si.Address)^;
PExtended(FSymbolInfo.Address)^ := Sqrt(V);
end;
{ TProd_Length }
procedure TProd_Length.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // Length
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // string or char expression
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_Length.Interpret;
var
Si: TSymbolInfo;
Ps: PString;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
Ps := PString(Si.Address);
PInteger(FSymbolInfo.Address)^ := Length(Ps^);
end;
{ TProd_UpperCase }
procedure TProd_UpperCase.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // UpperCase
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // string or char expression
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, T); // string expression
end;
procedure TProd_UpperCase.Interpret;
var
Si: TSymbolInfo;
Ps: PString;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
Ps := PString(Si.Address);
PString(FSymbolInfo.Address)^ := AnsiUpperCase(Ps^);
end;
{ TProd_LowerCase }
procedure TProd_LowerCase.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // LowerCase
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // string or char expression
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, T); // string expression
end;
procedure TProd_LowerCase.Interpret;
var
Si: TSymbolInfo;
Ps: PString;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
Ps := PString(Si.Address);
PString(FSymbolInfo.Address)^ := LowerCase(Ps^);
end;
{ TProd_Round }
procedure TProd_Round.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // Round
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_Round.Interpret;
var
Si: TSymbolInfo;
V: Extended;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
V := PExtended(Si.Address)^;
PInteger(FSymbolInfo.Address)^ := Round(V);
end;
{ TProd_Sin }
procedure TProd_Sin.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // Sin
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, T); // extended expression
end;
procedure TProd_Sin.Interpret;
var
Si: TSymbolInfo;
V: Extended;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
V := PExtended(Si.Address)^;
PExtended(FSymbolInfo.Address)^ := Sin(V);
end;
{ TProd_Cos }
procedure TProd_Cos.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // Cos
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, T); // extended expression
end;
procedure TProd_Cos.Interpret;
var
Si: TSymbolInfo;
V: Extended;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
V := PExtended(Si.Address)^;
PExtended(FSymbolInfo.Address)^ := Cos(V);
end;
{ TProd_Random }
procedure TProd_Random.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // Random
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeInteger, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, T); // integer expression
end;
procedure TProd_Random.Interpret;
var
Si: TSymbolInfo;
V: Integer;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
V := PInteger(Si.Address)^;
PInteger(FSymbolInfo.Address)^ := Random(V);
end;
{ TProd_Potencia }
procedure TProd_Potencia.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // Potência
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkComma);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, T); // expressão real
end;
procedure TProd_Potencia.Interpret;
var
Si: TSymbolInfo;
Base, Exp: Extended;
begin
Productions[0].Interpret; // base
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
Base := PExtended(Si.Address)^;
Productions[1].Interpret; // expoente
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
Exp := PExtended(Si.Address)^;
try
PExtended(FSymbolInfo.Address)^ := Power(Base, Exp);
except
Error(sInvalidOperation, ProductionLine, ProductionCol);
end;
end;
{ TProd_Ord }
procedure TProd_Ord.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // crtParaInt - antiga ord
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
if not (E.SymbolInfo.SymbolType is TOrdinalType) then
Error(sOrdinalTypeRequired, ProductionLine, ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_Ord.Interpret;
var
Si: TSymbolInfo;
T: TOrdinalType;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
T := TOrdinalType(Si.SymbolType);
PInteger(FSymbolInfo.Address)^ := T.OrdinalValue(Si);
end;
{ TProd_Chr }
procedure TProd_Chr.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // intParaCrt - antiga chr
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
CheckTypes(Compiler.DeclTypeInteger, E.SymbolInfo.SymbolType, tkAssign);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeChar);
end;
procedure TProd_Chr.Interpret;
var
Si: TSymbolInfo;
V: Integer;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
V := PInteger(Si.Address)^;
PChar(FSymbolInfo.Address)^ := Chr(V);
end;
{ TProd_ObtPixel }
procedure TProd_ObtPixel.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // obtPixel
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
CheckTypes(Compiler.DeclTypeInteger, E.SymbolInfo.SymbolType, tkAssign);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
CheckTypes(Compiler.DeclTypeInteger, E.SymbolInfo.SymbolType, tkAssign);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
CheckTypes(Compiler.DeclTypeInteger, E.SymbolInfo.SymbolType, tkAssign);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_ObtPixel.Interpret;
var
Si: TSymbolInfo;
Q: TQuadro;
I: Integer;
V: array [0..2] of Integer;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // quadro, x, y
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ obtém pixel }
{ obs: escolhi pegar do bmp; tinha de ser dele ou do form }
PInteger(FSymbolInfo.Address)^ := Q.Bmp.Canvas.Pixels[V[1], V[2]];
end;
{ TProd_FrameSetBrushColor }
procedure TProd_FrameSetBrushColor.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeCorDoPincel
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cor
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetBrushColor.Interpret;
var
Si: TSymbolInfo;
Color: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // Color
Si := Productions[1].SymbolInfo;
Color := PInteger(Si.Address)^;
Bmp.Canvas.Brush.Color := Color;
end;
{ TProd_FrameSetCopyMode }
procedure TProd_FrameSetCopyMode.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeModoDeCopiar
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // modo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetCopyMode.Interpret;
var
Si: TSymbolInfo;
IndMode: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // modo
Si := Productions[1].SymbolInfo;
IndMode := PInteger(Si.Address)^;
// verifica IndMode
if (IndMode < 0) or (IndMode > 14) then
Error(sValueNotAllowed, ProductionLine, ProductionCol);
Bmp.Canvas.CopyMode := CpModes[IndMode];
end;
{ TProd_FrameSetPenMode }
procedure TProd_FrameSetPenMode.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeModoDaCaneta
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // modo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetPenMode.Interpret;
var
Si: TSymbolInfo;
IndMode: Integer;
Q: TQuadro;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // modo
Si := Productions[1].SymbolInfo;
IndMode := PInteger(Si.Address)^;
// verifica IndMode
if (IndMode < 0) or (IndMode > 15) then
Error(sValueNotAllowed, ProductionLine, ProductionCol);
Q.alt_modo_caneta(PenModes[IndMode]);
end;
{ TProd_FrameSetPenStyle }
procedure TProd_FrameSetPenStyle.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeEstiloDaCaneta
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // estilo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetPenStyle.Interpret;
var
Si: TSymbolInfo;
Style: Integer;
Q: TQuadro;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // estilo
Si := Productions[1].SymbolInfo;
Style := PInteger(Si.Address)^;
Q.alt_estilo_caneta(TPenStyle(Style));
end;
{ TProd_SetCopyMode }
procedure TProd_SetCopyMode.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_mudeModoDeCopiar
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // modo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_SetCopyMode.Interpret;
var
Si: TSymbolInfo;
IndMode: Integer;
begin
Productions[0].Interpret; // modo
Si := Productions[0].SymbolInfo;
IndMode := PInteger(Si.Address)^;
// verifica valor do índice (0 <= IndMode <= 14)
if (IndMode < 0) or (IndMode > 14) then
Error(sValueNotAllowed, ProductionLine, ProductionCol);
if Compiler.Canvas <> nil then
Compiler.Canvas.CopyMode := CpModes[IndMode];
end;
{ TProd_CopyMode }
procedure TProd_CopyMode.Parse;
begin
Parser.GetNextToken; // dsl_modoDeCopiar()
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_CopyMode.Interpret;
var
I: Integer;
begin
PInteger(FSymbolInfo.Address)^ := 10; // um valor default
if Compiler.Canvas <> nil then
for I := 0 to 14 do
if CpModes[I] = Compiler.Canvas.CopyMode then
begin
PInteger(FSymbolInfo.Address)^ := I;
Exit;
end;
end;
{ TProd_SetPenMode }
procedure TProd_SetPenMode.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_mudeModoDaCaneta
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // modo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_SetPenMode.Interpret;
var
Si: TSymbolInfo;
IndMode: Integer;
begin
Productions[0].Interpret; // modo
Si := Productions[0].SymbolInfo;
IndMode := PInteger(Si.Address)^;
// verifica valor do índice (0 <= IndMode <= 15)
if (IndMode < 0) or (IndMode > 15) then
Error(sValueNotAllowed, ProductionLine, ProductionCol);
if Compiler.Canvas <> nil then
Compiler.Canvas.Pen.Mode := PenModes[IndMode];
end;
{ TProd_SetPenStyle }
procedure TProd_SetPenStyle.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_mudeEstiloDaCaneta
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // estilo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_SetPenStyle.Interpret;
var
Si: TSymbolInfo;
Style: Integer;
begin
Productions[0].Interpret; // estilo
Si := Productions[0].SymbolInfo;
Style := PInteger(Si.Address)^;
if Compiler.Canvas <> nil then
Compiler.Canvas.Pen.Style := TPenStyle(Style);
end;
{ TProd_PenStyle }
procedure TProd_PenStyle.Parse;
begin
Parser.GetNextToken; // dsl_estiloDaCaneta()
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_PenStyle.Interpret;
begin
PInteger(FSymbolInfo.Address)^ := 0; // um valor default
if Compiler.Canvas <> nil then
PInteger(FSymbolInfo.Address)^ := Integer(Compiler.Canvas.Pen.Style);
end;
{ TProd_PenMode }
procedure TProd_PenMode.Parse;
begin
Parser.GetNextToken; // dsl_modoDaCaneta()
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_PenMode.Interpret;
var
I: Integer;
begin
PInteger(FSymbolInfo.Address)^ := 0; // um valor default
if Compiler.Canvas <> nil then
for I := 0 to 15 do
if PenModes[I] = Compiler.Canvas.Pen.Mode then
begin
PInteger(FSymbolInfo.Address)^ := I;
Exit;
end;
end;
{ TProd_FrameSetBrushStyle }
procedure TProd_FrameSetBrushStyle.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeEstiloDoPincel
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // estilo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetBrushStyle.Interpret;
var
Si: TSymbolInfo;
Style: TBrushStyle;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // estilo
Si := Productions[1].SymbolInfo;
Style := TBrushStyle(PInteger(Si.Address)^);
Bmp.Canvas.Brush.Style := Style;
end;
{ TProd_FrameSetPenColor }
procedure TProd_FrameSetPenColor.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeCorDaCaneta
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cor
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetPenColor.Interpret;
var
Si: TSymbolInfo;
Color: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // Color
Si := Productions[1].SymbolInfo;
Color := PInteger(Si.Address)^;
Bmp.Canvas.Pen.Color := Color;
end;
{ TProd_FrameSetPenWidth }
procedure TProd_FrameSetPenWidth.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeLarguraDaCaneta
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cor
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetPenWidth.Interpret;
var
Si: TSymbolInfo;
Width: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // Color
Si := Productions[1].SymbolInfo;
Width := PInteger(Si.Address)^;
Bmp.Canvas.Pen.Width := Width;
end;
{ TProd_FrameSetFontColor }
procedure TProd_FrameSetFontColor.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeCorDaFonte
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cor
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetFontColor.Interpret;
var
Si: TSymbolInfo;
Color: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // Color
Si := Productions[1].SymbolInfo;
Color := PInteger(Si.Address)^;
Bmp.Canvas.Font.Color := Color;
end;
{ TProd_FrameSetFontSize }
procedure TProd_FrameSetFontSize.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeTamanhoDaFonte
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // tamanho
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetFontSize.Interpret;
var
Si: TSymbolInfo;
Size: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // tamanho
Si := Productions[1].SymbolInfo;
Size := PInteger(Si.Address)^;
Bmp.Canvas.Font.Size := Size;
end;
{ TProd_SetTimeEventInterval }
procedure TProd_SetTimeEventInterval.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_mudeIntervaloEventoTempo
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // intervalo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_SetTimeEventInterval.Interpret;
var
Si: TSymbolInfo;
begin
Productions[0].Interpret; // intervalo
Si := Productions[0].SymbolInfo;
FrmDsl.TimerEvent.Interval := PInteger(Si.Address)^;
end;
{ TProd_Sleep }
procedure TProd_Sleep.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_durma
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // intervalo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_Sleep.Interpret;
var
Si: TSymbolInfo;
begin
Productions[0].Interpret; // intervalo
Si := Productions[0].SymbolInfo;
Sleep(PInteger(Si.Address)^);
end;
{ TProd_FrameRectangle }
procedure TProd_FrameRectangle.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroRetangulo
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameRectangle.Interpret;
var
Si: TSymbolInfo;
X1, Y1, X2, Y2: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // x1
Si := Productions[1].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[2].Interpret; // y1
Si := Productions[2].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[3].Interpret; // x2
Si := Productions[3].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[4].Interpret; // y2
Si := Productions[4].SymbolInfo;
Y2 := PInteger(Si.Address)^;
Bmp.Canvas.Rectangle(X1, Y1, X2, Y2);
end;
{ TProd_FrameTriangle }
procedure TProd_FrameTriangle.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroTriangulo
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameTriangle.Interpret;
var
Si: TSymbolInfo;
X1, Y1, X2, Y2, Px: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // x1
Si := Productions[1].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[2].Interpret; // y1
Si := Productions[2].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[3].Interpret; // x2
Si := Productions[3].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[4].Interpret; // y2
Si := Productions[4].SymbolInfo;
Y2 := PInteger(Si.Address)^;
Px := (X2 - X1) div 2 + X1;
Bmp.Canvas.Polygon([Point(X1, Y2), Point(Px, Y1), Point(X2, Y2)]);
end;
{ TProd_FrameEllipse }
procedure TProd_FrameEllipse.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroElipse
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameEllipse.Interpret;
var
Si: TSymbolInfo;
X1, Y1, X2, Y2: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // x1
Si := Productions[1].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[2].Interpret; // y1
Si := Productions[2].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[3].Interpret; // x2
Si := Productions[3].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[4].Interpret; // y2
Si := Productions[4].SymbolInfo;
Y2 := PInteger(Si.Address)^;
Bmp.Canvas.Ellipse(X1, Y1, X2, Y2);
end;
{ TProd_FrameHeight }
procedure TProd_FrameHeight.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroAltura
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FrameHeight.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Bmp.Height;
end;
{ TProd_FrameWidth }
procedure TProd_FrameWidth.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroLargura
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FrameWidth.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Bmp.Width;
end;
{ TProd_FrameFontSize }
procedure TProd_FrameFontSize.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroTamanhoDaFonte
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FrameFontSize.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Bmp.Canvas.Font.Size;
end;
{ TProd_FrameFontColor }
procedure TProd_FrameFontColor.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroCorDaFonte
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FrameFontColor.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Bmp.Canvas.Font.Color;
end;
{ TProd_FrameFontName }
procedure TProd_FrameFontName.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroNomeDaFonte
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeString);
end;
procedure TProd_FrameFontName.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PString(FSymbolInfo.Address)^ := Bmp.Canvas.Font.Name;
end;
{ TProd_TimeEventInterval }
procedure TProd_TimeEventInterval.Parse;
begin
Parser.GetNextToken; // dsl_intervaloEventoTempo()
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_TimeEventInterval.Interpret;
begin
PInteger(FSymbolInfo.Address)^ := FrmDSL.TimerEvent.Interval;
end;
{ TProd_ScreenWidth }
procedure TProd_ScreenWidth.Parse;
begin
Parser.GetNextToken; // dsl_larguraDaTela()
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_ScreenWidth.Interpret;
begin
PInteger(FSymbolInfo.Address)^ := FrmDSL.PnlGraf.Width;
end;
{ TProd_ScreenHeight }
procedure TProd_ScreenHeight.Parse;
begin
Parser.GetNextToken; // dsl_alturaDaTela()
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_ScreenHeight.Interpret;
begin
PInteger(FSymbolInfo.Address)^ := FrmDSL.PnlGraf.Height;
end;
{ TProd_FramePenColor }
procedure TProd_FramePenColor.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroCorDaCaneta
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FramePenColor.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Bmp.Canvas.Pen.Color;
end;
{ TProd_FramePenWidth }
procedure TProd_FramePenWidth.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroLarguraDaCaneta
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FramePenWidth.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Bmp.Canvas.Pen.Width;
end;
{ TProd_FrameBrushColor }
procedure TProd_FrameBrushColor.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroCorDoPincel
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FrameBrushColor.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Bmp.Canvas.Brush.Color;
end;
{ TProd_FrameBrushStyle }
procedure TProd_FrameBrushStyle.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroEstiloDoPincel
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FrameBrushStyle.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Integer(Bmp.Canvas.Brush.Style);
end;
{ TProd_FramePenPosX }
procedure TProd_FramePenPosX.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroX
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FramePenPosX.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Bmp.Canvas.PenPos.X;
end;
{ TProd_Color }
procedure TProd_Color.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_cor
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // vermelho
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // verde
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // azul
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_Color.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..2] of Integer;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // vermelho, verde e azul (RGB)
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
PInteger(FSymbolInfo.Address)^ := RGB(V[0], V[1], V[2]);
end;
{ TProd_Now }
procedure TProd_Now.Parse;
begin
Parser.GetNextToken; // dsl_agora()
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeExtended);
end;
procedure TProd_Now.Interpret;
begin
PExtended(FSymbolInfo.Address)^ := Now();
end;
{ TProd_FileExists }
procedure TProd_FileExists.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // existeArq
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeBoolean);
end;
procedure TProd_FileExists.Interpret;
var
Si: TSymbolInfo;
NomeArq, NomeArqRestrito: String;
begin
Productions[0].Interpret; // nome do arquivo
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
NomeArq := PString(Si.Address)^;
NomeArqRestrito := ExpandeNomeArq(NomeArq);
PBoolean(FSymbolInfo.Address)^ := FileExists(NomeArqRestrito);
end;
{ TProd_FileNew }
procedure TProd_FileNew.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // dsl_arquivoNovo
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // nome
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // modo
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FileNew.Interpret;
var
Si: TSymbolInfo;
FileName: String;
ModeStr: String;
RWStrm: TRWStream;
Strm: TStream;
Mode: Word;
begin
// só pra evitar dois warnings chatos
Strm := nil;
Mode := 0;
Productions[0].Interpret; // nome do arquivo
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
FileName := PString(Si.Address)^;
Productions[1].Interpret; // modo
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
ModeStr := PString(Si.Address)^;
// determine o modo de abrir o arquivo
if (ModeStr = 'l') or (ModeStr = 'L') then
Mode := fmOpenRead
else if (ModeStr = 'e') or (ModeStr = 'E') then
Mode := fmCreate
else if (ModeStr = 'a') or (ModeStr = 'A') then
Mode := fmOpenReadWrite
else
Error(sBadFileMode, ProductionLine, ProductionCol);
// crie um FileStream
try
Strm := TFileStream.Create(FileName, Mode OR fmShareDenyWrite);
except
Error(sFileNewFailed, ProductionLine, ProductionCol);
end;
// crie um RWStream
RWStrm := TRWStream.Create(Strm);
Compiler.FStreamList.Add(RWStrm);
PInteger(FSymbolInfo.Address)^ := Integer(RWStrm);
end;
{ TProd_FileNameComplete }
procedure TProd_FileNameComplete.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // dsl_arquivoNomeCompleto
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeString);
end;
procedure TProd_FileNameComplete.Interpret;
var
Si: TSymbolInfo;
FileName: String;
begin
Productions[0].Interpret; // nome do arquivo
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
FileName := PString(Si.Address)^;
PString(FSymbolInfo.Address)^ := ExpandFileName(FileName);
end;
{ TProd_FrameCopyMode }
procedure TProd_FrameCopyMode.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroModoDeCopiar
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FrameCopyMode.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
I: Integer;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := 10; // default
for I := 0 to 14 do
if CpModes[I] = Bmp.Canvas.CopyMode then
begin
PInteger(FSymbolInfo.Address)^ := I;
Exit;
end;
end;
{ TProd_FramePenMode }
procedure TProd_FramePenMode.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroModoDaCaneta
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
(*
procedure TProd_FramePenMode.Interpret;
var
Si: TSymbolInfo;
Q: TQuadro;
I: Integer;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := 0; // default
for I := 0 to 15 do
if PenModes[I] = Q.CanvasForm.Pen.Mode then
begin
PInteger(FSymbolInfo.Address)^ := I;
Exit;
end;
end;
*)
{ TProd_FramePenStyle }
procedure TProd_FramePenStyle.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroEstiloDaCaneta
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
(*
procedure TProd_FramePenStyle.Interpret;
var
Si: TSymbolInfo;
Q: TQuadro;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Integer(Q.CanvasForm.Pen.Mode);
end;
*)
{ TProd_FramePenPosY }
procedure TProd_FramePenPosY.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroY
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FramePenPosY.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Bmp.Canvas.PenPos.Y;
end;
{ TProd_FrameSetWidth }
procedure TProd_FrameSetWidth.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeLargura
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // width
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetWidth.Interpret;
var
Si: TSymbolInfo;
Width: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // width
Si := Productions[1].SymbolInfo;
Width := PInteger(Si.Address)^;
Bmp.Width := Width;
end;
{ TProd_FrameSetHeight }
procedure TProd_FrameSetHeight.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeAltura
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // height
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameSetHeight.Interpret;
var
Si: TSymbolInfo;
Height: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // height
Si := Productions[1].SymbolInfo;
Height := PInteger(Si.Address)^;
Bmp.Height := Height;
end;
{ TProd_FrameLineTo }
procedure TProd_FrameLineTo.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroLinha
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameLineTo.Interpret;
var
Si: TSymbolInfo;
X, Y: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // x
Si := Productions[1].SymbolInfo;
X := PInteger(Si.Address)^;
Productions[2].Interpret; // y
Si := Productions[2].SymbolInfo;
Y := PInteger(Si.Address)^;
Bmp.Canvas.LineTo(X, Y);
end;
{ TProd_FrameMoveTo }
procedure TProd_FrameMoveTo.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroMudeXY
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameMoveTo.Interpret;
var
Si: TSymbolInfo;
X, Y: Integer;
Bmp: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // x
Si := Productions[1].SymbolInfo;
X := PInteger(Si.Address)^;
Productions[2].Interpret; // y
Si := Productions[2].SymbolInfo;
Y := PInteger(Si.Address)^;
Bmp.Canvas.MoveTo(X, Y);
end;
{ TProd_IntToStr }
procedure TProd_IntToStr.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // IntToStr
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeInteger, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeString);
end;
procedure TProd_IntToStr.Interpret;
var
Si: TSymbolInfo;
V: Integer;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
V := PInteger(Si.Address)^;
PString(FSymbolInfo.Address)^ := IntToStr(V);
end;
{ TProd_StrToInt }
procedure TProd_StrToInt.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // StrToInt
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_StrToInt.Interpret;
var
Si: TSymbolInfo;
S: String;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
S := PString(Si.Address)^;
try
PInteger(FSymbolInfo.Address)^ := StrToInt(S);
except
Error('"' + S + '" ' + sInvalidInteger, ProductionLine, ProductionCol);
end;
end;
{ TProd_FloatToStr }
procedure TProd_FloatToStr.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // FloatToStr
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeString);
end;
procedure TProd_FloatToStr.Interpret;
var
Si: TSymbolInfo;
V: Extended;
DecSep: Char;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
V := PExtended(Si.Address)^;
DecSep := SysUtils.FormatSettings.DecimalSeparator;
SysUtils.FormatSettings.DecimalSeparator := '.';
try
PString(FSymbolInfo.Address)^ := FloatToStr(V);
except
PString(FSymbolInfo.Address)^ := 'Erro';
end;
SysUtils.FormatSettings.DecimalSeparator := DecSep;
end;
{ TProd_StrToFloat }
procedure TProd_StrToFloat.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // StrToFloat
GetTerminal(tkLParen);
E := Compile(TProd_Expression);
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeExtended);
end;
procedure TProd_StrToFloat.Interpret;
var
Si: TSymbolInfo;
S: String;
SaveDecSep: Char;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
SaveDecSep := SysUtils.FormatSettings.DecimalSeparator;
SysUtils.FormatSettings.DecimalSeparator := '.';
S := PString(Si.Address)^;
try
PExtended(FSymbolInfo.Address)^ := StrToFloat(S);
except
Error('"' + S + '" ' + sInvalidFloat, ProductionLine, ProductionCol);
end;
SysUtils.FormatSettings.DecimalSeparator := SaveDecSep;
end;
{ TProd_CharAt }
procedure TProd_CharAt.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // CharAt
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // string
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // int (char position, >= 0)
T := CheckTypes(Compiler.DeclTypeInteger, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeChar);
end;
procedure TProd_CharAt.Interpret;
var
Si: TSymbolInfo;
S: String;
N: Integer;
begin
Productions[0].Interpret; // string expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
S := PString(Si.Address)^;
Productions[1].Interpret; // integer expression
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
N := PInteger(Si.Address)^;
if (N < 0) or (N >= Length(S)) then
Error(sIndexOutOfRange, ProductionLine, ProductionCol);
PChar(FSymbolInfo.Address)^ := S[N + 1];
end;
{ TProd_MouseXY }
procedure TProd_MouseXY.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // gra_mouseXY
GetTerminal(tkLParen);
E := Compile(TProd_VarReference); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_VarReference); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_MouseXY.Interpret;
var
Si: TSymbolInfo;
begin
Productions[0].Interpret; // x
Si := Productions[0].SymbolInfo;
PInteger(Si.Address)^ := Compiler.FMouseX;
Productions[1].Interpret; // y
Si := Productions[1].SymbolInfo;
PInteger(Si.Address)^ := Compiler.FMouseY;
// atualiza na memoria
SymbolTable.UpdateMem(Productions[0].SymbolInfo.SymbolType,
Integer(Productions[0].SymbolInfo.Address));
SymbolTable.UpdateMem(Productions[1].SymbolInfo.SymbolType,
Integer(Productions[1].SymbolInfo.Address));
end;
{ TProd_MouseX }
procedure TProd_MouseX.Parse;
begin
Parser.GetNextToken; // MouseX
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_MouseX.Interpret;
begin
PInteger(FSymbolInfo.Address)^ := Compiler.FMouseX;
end;
{ TProd_MouseY }
procedure TProd_MouseY.Parse;
begin
Parser.GetNextToken; // MouseY
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_MouseY.Interpret;
begin
PInteger(FSymbolInfo.Address)^ := Compiler.FMouseY;
end;
{ TProd_LastEvent }
procedure TProd_LastEvent.Parse;
begin
Parser.GetNextToken; // g_LastEvent
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_LastEvent.Interpret;
var
Q: TQuadro;
Subst: Integer;
begin
Q := TQuadro(TComponent(Compiler.FLastEventSender).Tag);
if not (Q is TQuadro) then // não deve acontecer
begin
// Error(sFalhaInternaUltimoEvento, ProductionLine, ProductionCol);
PInteger(FSymbolInfo.Address)^ := Compiler.FLastEvent;
Exit;
end;
if Q.tem_evento_subst(Compiler.FLastEvent, Subst) then
PInteger(FSymbolInfo.Address)^ := Subst
else
PInteger(FSymbolInfo.Address)^ := Compiler.FLastEvent;
end;
{ TProd_BrushColor }
procedure TProd_BrushColor.Parse;
begin
Parser.GetNextToken; // BrushColor
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_BrushColor.Interpret;
begin
if Compiler.Canvas <> nil then
PInteger(FSymbolInfo.Address)^ := Compiler.Canvas.Brush.Color;
end;
{ TProd_PenColor }
procedure TProd_PenColor.Parse;
begin
Parser.GetNextToken; // PenColor
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_PenColor.Interpret;
begin
if Compiler.Canvas <> nil then
PInteger(FSymbolInfo.Address)^ := Compiler.Canvas.Pen.Color;
end;
{ TProd_PenWidth }
procedure TProd_PenWidth.Parse;
begin
Parser.GetNextToken; // PenWidth
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_PenWidth.Interpret;
begin
if Compiler.Canvas <> nil then
PInteger(FSymbolInfo.Address)^ := Compiler.Canvas.Pen.Width;
end;
{ TProd_FontColor }
procedure TProd_FontColor.Parse;
begin
Parser.GetNextToken; // FontColor
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FontColor.Interpret;
begin
if Compiler.Canvas <> nil then
PInteger(FSymbolInfo.Address)^ := Compiler.Canvas.Font.Color;
end;
{ TProd_FontSize }
procedure TProd_FontSize.Parse;
begin
Parser.GetNextToken; // FontSize
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
procedure TProd_FontSize.Interpret;
begin
if Compiler.Canvas <> nil then
PInteger(FSymbolInfo.Address)^ := Compiler.Canvas.Font.Size;
end;
{ TProd_FontName }
procedure TProd_FontName.Parse;
begin
Parser.GetNextToken; // FontName
GetTerminal(tkLParen);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeString);
end;
procedure TProd_FontName.Interpret;
begin
if Compiler.Canvas <> nil then
PString(FSymbolInfo.Address)^ := Compiler.Canvas.Font.Name;
end;
{ TProd_ForStmt }
procedure TProd_ForStmt.Parse;
var
Id: String;
begin
Parser.GetNextToken; // consume for
Id := GetIdentifier;
FSymbolInfo := SymbolTable.FindSymbol(Id);
if FSymbolInfo = nil then
Error(Format(sUndeclaredIdentifier, [Id]), ProductionLine, ProductionCol);
if not (FSymbolInfo.SymbolType is TOrdinalType) then
Error(sOrdinalTypeRequired, ProductionLine, ProductionCol);
GetTerminal(tkAssign);
FExpr1 := Compile(TProd_Expression);
CheckTypes(FSymbolInfo.SymbolType, FExpr1.SymbolInfo.SymbolType, tkAssign);
// if not (Parser.CurrentToken in [tkRWto, tkRWdownto]) then
if not (Parser.CurrentToken in [tkRWuntil, tkRWdownto]) then
Error(sToOrDownToExpected, Parser.TokenLine, Parser.TokenCol);
if Parser.CurrentToken = tkRWdownto then
FDownTo := True;
Parser.GetNextToken; // to or downto
FExpr2 := Compile(TProd_Expression);
CheckTypes(FSymbolInfo.SymbolType, FExpr2.SymbolInfo.SymbolType, tkAssign);
GetTerminal(tkRWdo);
Compiler.State := Compiler.State + [csInRepetitiveStmt];
FStmt := Compile(TProd_Stmt);
Compiler.State := Compiler.State - [csInRepetitiveStmt];
end;
procedure TProd_ForStmt.Interpret;
var
Incr: Integer;
PInfo, P1, P2: PInteger;
IsChar: Boolean;
begin
if FDownTo then
Incr := -1
else
Incr := 1;
FExpr1.Interpret;
FExpr2.Interpret;
PInfo := FSymbolInfo.Address;
P1 := FExpr1.SymbolInfo.Address;
P2 := FExpr2.SymbolInfo.Address;
// IsChar := FSymbolInfo.SymbolType.Size = SizeOf(Char);
IsChar := FSymbolInfo.FSymbolType.FTypeClass = tcChar;
// atribuição inicial
if IsChar then
PChar(PInfo)^ := PChar(P1)^
else
PInfo^ := P1^;
// atualiza na memoria
SymbolTable.UpdateMem(FSymbolInfo.SymbolType, Integer(PInfo));
while True do
begin
// testa variável de controle
if FDownTo then
begin
if IsChar then
begin
if PChar(PInfo)^ < PChar(P2)^ then
Break;
end
else
if PInfo^ < P2^ then
Break;
end
else
begin
if IsChar then
begin
if PChar(PInfo)^ > PChar(P2)^ then
Break;
end
else
begin
if PInfo^ > P2^ then
Break;
end;
end;
// executa o comando
try
FStmt.Interpret;
except
on EBreakException do
Break;
on EContinueException do
;
end;
// incrementa a variável de controle
if IsChar then
PChar(PInfo)^ := Chr(Ord(PChar(PInfo)^) + Incr)
else
PInfo^ := PInfo^ + Incr;
// atualiza na memoria
SymbolTable.UpdateMem(FSymbolInfo.SymbolType, Integer(PInfo));
end;
end;
{ TProd_ForStmt_2 }
procedure TProd_ForStmt_2.Parse;
begin
Parser.GetNextToken; // for
GetTerminal(tkLParen); // (
if (Parser.CurrentToken <> tkSemiColon) then
FStmt1 := Compile(TProd_AssignStmt);
GetTerminal(tkSemiColon);
if (Parser.CurrentToken <> tkSemiColon) then
begin
FExpr := Compile(TProd_Expression);
if FExpr.SymbolInfo.SymbolType <> Compiler.DeclTypeBoolean then
Error(sBoolExprExpected, FExpr.ProductionLine, FExpr.ProductionCol);
end;
GetTerminal(tkSemiColon);
if (Parser.CurrentToken <> tkRParen) then
FStmt2 := Compile(TProd_Stmt);
GetTerminal(tkRParen);
// GetTerminal(tkRWdo);
Compiler.State := Compiler.State + [csInRepetitiveStmt];
FStmt := Compile(TProd_Stmt);
Compiler.State := Compiler.State - [csInRepetitiveStmt];
end;
procedure TProd_ForStmt_2.Interpret;
var
P: PBoolean;
SemTeste: Boolean;
begin
SemTeste := True; // para permitir comando na forma: para (;;)
if FStmt1 <> nil then
begin
FStmt1.Interpret;
if FrmDSL.PnlMemoria.Visible then
FrmDSL.ListViewMem.Refresh;
end;
if FExpr <> nil then
begin
FExpr.Interpret; // expressão boolean
P := FExpr.SymbolInfo.Address;
end
else
P := @SemTeste;
while P^ do
begin
try
FStmt.Interpret; // comando do "para"
except
on EBreakException do
Break;
on EContinueException do
;
end;
if FStmt2 <> nil then
FStmt2.Interpret; // inc ou dec (tipicamente)
if FExpr <> nil then
FExpr.Interpret; // re-interpreta a expressão boolean
end;
end;
{ TProd_IfStmt }
procedure TProd_IfStmt.Parse;
var
Expr: TProduction;
begin
GetTerminal(tkRWif);
GetTerminal(tkLParen);
Expr := Compile(TProd_Expression);
if Expr.SymbolInfo.SymbolType <> Compiler.DeclTypeBoolean then
Error(sBoolExprExpected, Expr.ProductionLine, Expr.ProductionCol);
GetTerminal(tkRParen);
// GetTerminal(tkRWthen);
Compile(TProd_Stmt);
// if Parser.CurrentToken = tkSemiColon then
// Parser.GetNextToken; // ;
if Parser.CurrentToken = tkRWelse then
begin
Parser.GetNextToken; // else
Compile(TProd_Stmt);
end;
end;
procedure TProd_IfStmt.Interpret;
begin
Productions[0].Interpret; // expression
if PBoolean(Productions[0].SymbolInfo.Address)^ then
Productions[1].Interpret // then stmt
else if ProductionCount > 2 then
Productions[2].Interpret; // else stmt
end;
{ TProd_CaseStmt }
procedure TProd_CaseStmt.Parse;
begin
GetTerminal(tkRWchoose); // escolha
GetTerminal(tkLParen);
FSymbolInfo := Compile(TProd_Expression).SymbolInfo;
GetTerminal(tkRParen);
// create case selector; it will be filled during entry's compilation
FCaseSel := TCaseSelector.Create;
while True do
begin
Compile(TProd_CaseEntry);
if Parser.CurrentToken = tkSemiColon then
Parser.GetNextToken;
if Parser.CurrentToken = tkRWend then
Break;
if Parser.CurrentToken = tkRWelse then
begin
Parser.GetNextToken; // else
TProduction(FElseStmt) := Compile(TProd_Stmt);
if Parser.CurrentToken = tkSemiColon then
Parser.GetNextToken;
Break;
end;
end;
GetTerminal(tkRWend);
end;
procedure TProd_CaseStmt.Interpret;
begin
Productions[0].Interpret; // expression
if not FCaseSel.TestCase(Productions[0].SymbolInfo) then
if FElseStmt <> nil then
FElseStmt.Interpret;
end;
destructor TProd_CaseStmt.Destroy;
begin
FCaseSel.Free;
inherited Destroy;
end;
{ TProd_CaseEntry }
procedure TProd_CaseEntry.Parse;
var
P: TProduction;
Member: TProd_MemberGroup;
begin
GetTerminal(tkRWcase);
while True do
begin
TProduction(Member) := Compile(TProd_MemberGroup);
if not Member.IsConst then
Error(sConstExpected, ProductionLine, ProductionCol);
CheckTypes(Member.SymbolInfo.SymbolType, Parent.SymbolInfo.SymbolType,
tkAssign);
try
TProd_CaseStmt(Parent).FCaseSel.AddEntry(Member);
except
Error(sDuplicateCase, ProductionLine, ProductionCol);
end;
if Parser.CurrentToken = tkColon then
Break;
GetTerminal(tkComma);
end;
GetTerminal(tkColon);
P := Compile(TProd_Stmt);
with Parent as TProd_CaseStmt do
FCaseSel.SetStmt(P as TProd_Stmt);
end;
{ TProd_WhileStmt }
procedure TProd_WhileStmt.Parse;
var
Expr: TProduction;
begin
GetTerminal(tkRWwhile);
GetTerminal(tkLParen);
Expr := Compile(TProd_Expression);
if Expr.SymbolInfo.SymbolType <> Compiler.DeclTypeBoolean then
Error(sBoolExprExpected, Expr.ProductionLine, Expr.ProductionCol);
GetTerminal(tkRParen);
// GetTerminal(tkRWdo);
Compiler.State := Compiler.State + [csInRepetitiveStmt];
Compile(TProd_Stmt);
Compiler.State := Compiler.State - [csInRepetitiveStmt];
end;
procedure TProd_WhileStmt.Interpret;
var
P: PBoolean;
begin
Productions[0].Interpret; // expression
P := Productions[0].SymbolInfo.Address;
while P^ do
begin
try
Productions[1].Interpret; // statement
except
on EBreakException do
Break;
on EContinueException do
;
end;
Productions[0].Interpret; // re-evaluate expression
end;
end;
{ TProd_RepeatStmt }
procedure TProd_RepeatStmt.Parse;
var
Expr: TProduction;
begin
GetTerminal(tkRWrepeat);
Compiler.State := Compiler.State + [csInRepetitiveStmt];
repeat
Compile(TProd_Stmt);
GetTerminal(tkSemiColon);
until Parser.CurrentToken in [tkRWuntil, tkEndOfSource];
Compiler.State := Compiler.State - [csInRepetitiveStmt];
GetTerminal(tkRWuntil);
GetTerminal(tkLParen);
Expr := Compile(TProd_Expression);
if Expr.SymbolInfo.SymbolType <> Compiler.DeclTypeBoolean then
Error(sBoolExprExpected, Expr.ProductionLine, Expr.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_RepeatStmt.Interpret;
var
I: Integer;
P: PBoolean;
begin
P := Productions[ProductionCount - 1].SymbolInfo.Address;
repeat
try
for I := 0 to ProductionCount - 2 do
Productions[I].Interpret; // statements
except
on EBreakException do
Break;
on EContinueException do
;
end;
Productions[ProductionCount - 1].Interpret; // expression
until P^;
end;
{ TProd_WriteStmt }
procedure TProd_WriteStmt.Parse;
begin
Parser.GetNextToken; // write
GetTerminal(tkLParen);
while True do
begin
Compile(TProd_Expression);
if Parser.CurrentToken <> tkComma then
Break;
Parser.GetNextToken; // comma
end;
GetTerminal(tkRParen);
end;
procedure TProd_WriteStmt.Interpret;
var
I: Integer;
S: String;
Si: TSymbolInfo;
begin
S := '';
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret;
Si := Productions[I].SymbolInfo;
S := S + Si.SymbolType.ValueAsString(Si);
end;
if Assigned(Compiler.FOnWrite) then
Compiler.OnWrite(Compiler, S);
end;
{ TProd_WritelnStmt }
procedure TProd_WritelnStmt.Parse;
begin
Parser.GetNextToken; // writeln
GetTerminal(tkLParen);
while True do
begin
Compile(TProd_Expression);
if Parser.CurrentToken <> tkComma then
Break;
Parser.GetNextToken; // comma
end;
GetTerminal(tkRParen);
end;
procedure TProd_WritelnStmt.Interpret;
var
I: Integer;
S: String;
Si: TSymbolInfo;
begin
S := '';
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret;
Si := Productions[I].SymbolInfo;
S := S + Si.SymbolType.ValueAsString(Si);
end;
S := S + #13#10;
if Assigned(Compiler.FOnWrite) then
Compiler.OnWrite(Compiler, S);
end;
{ TProd_ReadStmt }
procedure TProd_ReadStmt.Parse;
var
P: TProduction;
begin
Parser.GetNextToken; // read
GetTerminal(tkLParen);
while True do
begin
P := Compile(TProd_Expression);
if not (P.SymbolInfo.SymbolClass in [scVar, scVarParam]) then
Error(sVarIdentExpected, P.ProductionLine, P.ProductionCol);
if Parser.CurrentToken <> tkComma then
Break;
Parser.GetNextToken; // comma
end;
GetTerminal(tkRParen);
end;
procedure TProd_ReadStmt.Interpret;
var
I: Integer;
Si: TSymbolInfo;
VInteger: Integer;
VChar: Char;
VString: String;
VExtended: Extended;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret;
Si := Productions[I].SymbolInfo;
case Si.SymbolType.TypeClass of
tcInteger:
if Assigned(Compiler.FOnReadInteger) then
begin
Compiler.FOnReadInteger(Compiler, VInteger);
Si.SymbolType.Oper(Si.Address, @VInteger, nil, tkAssign, Self);
end;
tcChar:
if Assigned(Compiler.FOnReadChar) then
begin
Compiler.FOnReadChar(Compiler, VChar);
Si.SymbolType.Oper(Si.Address, @VChar, nil, tkAssign, Self);
end;
tcExtended:
if Assigned(Compiler.FOnReadReal) then
begin
Compiler.FOnReadReal(Compiler, VExtended);
Si.SymbolType.Oper(Si.Address, @VExtended, nil, tkAssign, Self);
end;
tcString:
if Assigned(Compiler.FOnReadString) then
begin
Compiler.FOnReadString(Compiler, VString);
Si.SymbolType.Oper(Si.Address, @VString, nil, tkAssign, Self);
end;
end;
// atualiza na memoria
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
end;
end;
{ TProd_WithStmt }
destructor TProd_WithStmt.Destroy;
begin
FRecordLst.Free;
inherited Destroy;
end;
procedure TProd_WithStmt.Parse;
var
P: TProduction;
T: TRecordType;
I: Integer;
begin
Parser.GetNextToken; // with
FRecordLst := TList.Create;
while True do
begin
P := Compile(TProd_VarReference);
if not (P.SymbolInfo.SymbolClass in [scVar, scField, scVarParam, scPointer])
then Error(sRecordTypeRequired, ProductionLine, ProductionCol);
if not (P.SymbolInfo.SymbolType is TRecordType) then
Error(sRecordTypeRequired, ProductionLine, ProductionCol);
FRecordLst.Add(P);
if Parser.CurrentToken <> tkComma then
Break;
Parser.GetNextToken; // comma
end;
GetTerminal(tkRWdo);
// add scope for all record references
for I := 0 to FRecordLst.Count - 1 do
begin
TSymbolType(T) := TProduction(FRecordLst[I]).SymbolInfo.SymbolType;
SymbolTable.AddScope(T.FScope);
end;
// compile stmt
FStmt := Compile(TProd_Stmt);
// remove scopes
for I := 0 to FRecordLst.Count - 1 do
SymbolTable.RemoveScope;
end;
procedure TProd_WithStmt.Interpret;
var
I: Integer;
begin
for I := 0 to FRecordLst.Count - 1 do
TProduction(FRecordLst[I]).Interpret;
FStmt.Interpret;
end;
{ TProd_NewStmt }
procedure TProd_NewStmt.Parse;
begin
Parser.GetNextToken; // new
GetTerminal(tkLParen);
FSymbolInfo := Compile(TProd_VarReference).SymbolInfo;
if not (FSymbolInfo.SymbolType is TPointerType) then
Error(sPointerTypeRequired, ProductionLine, ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_NewStmt.Interpret;
var
P: Pointer;
begin
Productions[0].Interpret; // pointer var reference
FSymbolInfo := Productions[0].SymbolInfo;
P := Compiler.Heap.AllocMem(TPointerType(FSymbolInfo.SymbolType).FBaseType.Size);
if P = nil then
Error(sOutOfMemory, ProductionLine, ProductionCol);
PByte(FSymbolInfo.Address^) := P;
// exibe na heap
SymbolTable.ShowMem('',
TPointerType(FSymbolInfo.SymbolType).FBaseType,
Integer(P), False);
// atualiza visualmente o ponteiro
SymbolTable.UpdateMem(FSymbolInfo.SymbolType, Integer(FSymbolInfo.Address));
end;
{ TProd_DisposeStmt }
procedure TProd_DisposeStmt.Parse;
begin
Parser.GetNextToken; // dispose
GetTerminal(tkLParen);
FSymbolInfo := Compile(TProd_VarReference).SymbolInfo;
if not (FSymbolInfo.SymbolType is TPointerType) then
Error(sPointerTypeRequired, ProductionLine, ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_DisposeStmt.Interpret;
begin
Productions[0].Interpret; // pointer var reference
FSymbolInfo := Productions[0].SymbolInfo;
Compiler.Heap.FreeMem(PByte(FSymbolInfo.Address^));
// atualiza o visual
SymbolTable.DisposeHeap(TPointerType(FSymbolInfo.SymbolType).FBaseType,
Integer(FSymbolInfo.Address^));
end;
{ TProd_Expression }
procedure TProd_Expression.Parse;
var
SymCla: TSymbolClass;
T: TSymbolType;
begin
FSimpleExpr1 := Compile(TProd_SimpleExpression);
FSymbolInfo := FSimpleExpr1.SymbolInfo;
if Parser.CurrentToken in Set_RelOp then
begin
FRelOp := Parser.CurrentToken;
Parser.GetNextToken;
FSimpleExpr2 := Compile(TProd_SimpleExpression);
T := CheckTypes(FSimpleExpr1.SymbolInfo.SymbolType,
FSimpleExpr2.SymbolInfo.SymbolType, FRelOp);
FSimpleExpr1.PromoteTo(T);
FSimpleExpr2.PromoteTo(T);
SymCla := scConst;
if (FSimpleExpr1.SymbolInfo.SymbolClass <> scConst) or
(FSimpleExpr2.SymbolInfo.SymbolClass <> scConst) then
SymCla := scVar;
FSymbolInfo := SymbolTable.AllocSymbolInfo(SymCla, Compiler.DeclTypeBoolean);
end;
end;
procedure TProd_Expression.Interpret;
var
Si1, Si2: TSymbolInfo;
begin
FSimpleExpr1.Interpret;
Si1 := FSimpleExpr1.SymbolInfo;
if ProductionCount > 1 then
begin
if FSimpleExpr1.ExecPromotion then
Si1 := FSimpleExpr1.Promoted;
FSimpleExpr2.Interpret;
Si2 := FSimpleExpr2.SymbolInfo;
if FSimpleExpr2.ExecPromotion then
Si2 := FSimpleExpr2.Promoted;
Operate(FSymbolInfo, Si1, Si2, FRelOp);
// Operate(FSymbolInfo, FSimpleExpr1.SymbolInfo, FSimpleExpr2.SymbolInfo,
// FRelOp);
end;
end;
{ TProd_SimpleExpression }
constructor TProd_SimpleExpression.Create(Compiler: TCompiler);
begin
inherited Create(Compiler);
FLstAddOp := TList.Create;
end;
destructor TProd_SimpleExpression.Destroy;
begin
FLstAddOp.Free;
inherited Destroy;
end;
procedure TProd_SimpleExpression.Parse;
var
T: TSymbolType;
I: Integer;
SymCla: TSymbolClass;
begin
FSymbolInfo := Compile(TProd_Term).SymbolInfo;
if Parser.CurrentToken in Set_AddOp then
begin
repeat
FLstAddOp.Add(Pointer(Parser.CurrentToken));
Parser.GetNextToken;
Compile(TProd_Term);
until not (Parser.CurrentToken in Set_AddOp);
// check types
T := Productions[0].SymbolInfo.SymbolType;
for I := 1 to ProductionCount - 1 do
T := CheckTypes(T, Productions[I].SymbolInfo.SymbolType,
TToken(FLstAddOp[I - 1]));
// T is the result's type: promote; check symbol class
SymCla := scConst;
for I := 0 to ProductionCount - 1 do
begin
Productions[I].PromoteTo(T);
if Productions[I].SymbolInfo.SymbolClass <> scConst then
SymCla := scVar;
end;
FSymbolInfo := SymbolTable.AllocSymbolInfo(SymCla, T);
end;
end;
procedure TProd_SimpleExpression.Interpret;
var
I: Integer;
Si1, Si2: TSymbolInfo;
begin
Productions[0].Interpret;
Si1 := Productions[0].SymbolInfo;
if ProductionCount > 1 then
begin
if Productions[0].ExecPromotion then
Si1 := Productions[0].Promoted;
{ trata o "curto circuito" de expressões lógicas }
if (Si1.FSymbolType.TypeClass = tcBoolean) and
(TToken(FLstAddOp[0]) = tkRWor) and
(PBoolean(Si1.Address)^ = True) then
begin
PBoolean(FSymbolInfo.Address)^ := True;
Exit;
end;
Productions[1].Interpret;
Si2 := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si2 := Productions[1].Promoted;
Operate(FSymbolInfo, Si1, Si2, TToken(FLstAddOp[0]));
for I := 2 to ProductionCount - 1 do
begin
{ trata o "curto circuito" de expressões lógicas }
if (FSymbolInfo.FSymbolType.TypeClass = tcBoolean) and
(TToken(FLstAddOp[I - 1]) = tkRWor) and
(PBoolean(FSymbolInfo.Address)^ = True) then
Exit;
Productions[I].Interpret;
Si1 := Productions[I].SymbolInfo;
if Productions[I].ExecPromotion then
Si1 := Productions[I].Promoted;
Operate(FSymbolInfo, FSymbolInfo, Si1, TToken(FLstAddOp[I - 1]));
end;
end;
end;
{ TProd_Term }
constructor TProd_Term.Create(Compiler: TCompiler);
begin
inherited Create(Compiler);
FLstMulOp := TList.Create;
end;
destructor TProd_Term.Destroy;
begin
FLstMulOp.Free;
inherited Destroy;
end;
procedure TProd_Term.Parse;
var
T: TSymbolType;
I: Integer;
SymCla: TSymbolClass;
begin
FSymbolInfo := Compile(TProd_Factor).SymbolInfo;
if Parser.CurrentToken in Set_MulOp then
begin
repeat
FLstMulOp.Add(Pointer(Parser.CurrentToken));
Parser.GetNextToken;
Compile(TProd_Factor);
until not (Parser.CurrentToken in Set_MulOp);
// check types
T := Productions[0].SymbolInfo.SymbolType;
for I := 1 to ProductionCount - 1 do
T := CheckTypes(T, Productions[I].SymbolInfo.SymbolType,
TToken(FLstMulOp[I - 1]));
// T is the result's type: promote; check symbol class
SymCla := scConst;
for I := 0 to ProductionCount - 1 do
begin
Productions[I].PromoteTo(T);
if Productions[I].SymbolInfo.SymbolClass <> scConst then
SymCla := scVar;
end;
FSymbolInfo := SymbolTable.AllocSymbolInfo(SymCla, T);
end;
end;
procedure TProd_Term.Interpret;
var
I: Integer;
Si1, Si2: TSymbolInfo;
begin
Productions[0].Interpret;
Si1 := Productions[0].SymbolInfo;
if ProductionCount > 1 then
begin
if Productions[0].ExecPromotion then
Si1 := Productions[0].Promoted;
{ trata o "curto circuito" de expressões lógicas }
if (Si1.FSymbolType.TypeClass = tcBoolean) and
(TToken(FLstMulOp[0]) = tkRWand) and
(PBoolean(Si1.Address)^ = False) then
begin
PBoolean(FSymbolInfo.Address)^ := False;
Exit;
end;
Productions[1].Interpret;
Si2 := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si2 := Productions[1].Promoted;
Operate(FSymbolInfo, Si1, Si2, TToken(FLstMulOp[0]));
for I := 2 to ProductionCount - 1 do
begin
{ trata o "curto circuito" de expressões lógicas }
if (FSymbolInfo.FSymbolType.TypeClass = tcBoolean) and
(TToken(FLstMulOp[I - 1]) = tkRWand) and
(PBoolean(FSymbolInfo.Address)^ = False) then
Exit;
Productions[I].Interpret;
Si1 := Productions[I].SymbolInfo;
if Productions[I].ExecPromotion then
Si1 := Productions[I].Promoted;
Operate(FSymbolInfo, FSymbolInfo, Si1, TToken(FLstMulOp[I - 1]));
end;
end;
end;
{ TProd_Factor }
procedure TProd_Factor.Parse;
begin
if Parser.CurrentToken = tkPlus then
Parser.GetNextToken; // throw out unary +
Check(Set_FirstFactor, sExpressionExpected);
case Parser.CurrentToken of
tkLParen:
begin
Parser.GetNextToken; // '('
FExpr := Compile(TProd_Expression);
FSymbolInfo := FExpr.SymbolInfo;
GetTerminal(tkRParen);
end;
(*
tkLBracket:
begin
FSetExpr := Compile(TProd_SetConstructor);
FSymbolInfo := FSetExpr.SymbolInfo;
end;
*)
tkRWnot:
begin
FSymbolInfo := SymbolTable.FindSymbol('não');
Parser.GetNextToken;
if Parser.CurrentToken in Set_FirstFactor then
begin
FNegate := True;
FFact := Compile(TProd_Factor);
if FFact.SymbolInfo.SymbolType <> Compiler.DeclTypeBoolean then
Error(sIncompatibleTypes, ProductionLine, ProductionCol);
// FSymbolInfo := SymbolTable.AllocSymbolInfo(FFact.SymbolInfo.SymbolClass,
// Compiler.DeclTypeBoolean);
// FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar,
// Compiler.DeclTypeBoolean);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scConst,
Compiler.DeclTypeBoolean);
end;
end;
tkMinus:
begin
Parser.GetNextToken; // -
FFact := Compile(TProd_Factor);
if (FFact.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger) and
(FFact.SymbolInfo.SymbolType <> Compiler.DeclTypeExtended) then
Error(sIncompatibleTypes, ProductionLine, ProductionCol);
// FSymbolInfo := SymbolTable.AllocSymbolInfo(FFact.SymbolInfo.SymbolClass,
// FFact.SymbolInfo.SymbolType);
(*
FSymbolInfo := SymbolTable.AllocSymbolInfo(FFact.SymbolInfo.SymbolClass,
FFact.SymbolInfo.SymbolType);
*)
FSymbolInfo := SymbolTable.AllocSymbolInfo(scConst, FFact.SymbolInfo.SymbolType);
// FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, FFact.SymbolInfo.SymbolType);
end;
tkIntNumber:
begin
FSymbolInfo := SymbolTable.AllocSymbolInfo(scConst,
Compiler.DeclTypeInteger);
PInteger(FSymbolInfo.Address)^ := Parser.TokenValue.AsInteger;
Parser.GetNextToken;
end;
tkFloatNumber:
begin
FSymbolInfo := SymbolTable.AllocSymbolInfo(scConst,
Compiler.DeclTypeExtended);
PExtended(FSymbolInfo.Address)^ := Parser.TokenValue.AsExtended;
Parser.GetNextToken;
end;
tkString:
begin
FSymbolInfo := SymbolTable.AllocSymbolInfo(scConst,
Compiler.DeclTypeString);
PString(FSymbolInfo.Address)^ := Parser.TokenValue.AsString;
Parser.GetNextToken;
end;
tkChar:
begin
FSymbolInfo := SymbolTable.AllocSymbolInfo(scConst,
Compiler.DeclTypeChar);
PChar(FSymbolInfo.Address)^ := Parser.TokenValue.AsChar;
Parser.GetNextToken;
end;
tkRWnil:
begin
FSymbolInfo := SymbolTable.FindSymbol('nulo');
Parser.GetNextToken;
end;
tkRWfalse:
begin
FSymbolInfo := SymbolTable.FindSymbol('falso');
Parser.GetNextToken;
end;
tkRWtrue, tkRWyes:
begin
FSymbolInfo := SymbolTable.FindSymbol('verdadeiro');
Parser.GetNextToken;
end;
tkId:
begin
// test for some standard functions
if StandardProcedure(Parser.TokenString) then
begin
FExpr := Productions[0]; // according to the implementation
// of StandardProcedure, the first
// production (Productions[0]) is
// the function
FSymbolInfo := Productions[0].SymbolInfo;
Exit;
end;
FSymbolInfo := SymbolTable.FindSymbol(Parser.TokenString);
if FSymbolInfo = nil then
Error(Format(sUndeclaredIdentifier, [Parser.TokenString]),
Parser.TokenLine, Parser.TokenCol);
if FSymbolInfo.SymbolClass in [scVar, scField, scVarParam,
scFunction] then
begin
FVarRef := Compile(TProd_VarReference);
FSymbolInfo := FVarRef.SymbolInfo;
Exit;
end;
if FSymbolInfo.SymbolClass <> scConst then
Error(sVarIdentExpected, Parser.TokenLine, Parser.TokenCol);
Parser.GetNextToken;
end;
end;
end;
procedure TProd_Factor.Interpret;
begin
if FExpr <> nil then
FExpr.Interpret
else if FSetExpr <> nil then
FSetExpr.Interpret
else if FVarRef <> nil then
FVarRef.Interpret
else if FFuncCall <> nil then
FFuncCall.Interpret
else if FFact <> nil then
begin
FFact.Interpret;
if FNegate then
Operate(FSymbolInfo, FFact.SymbolInfo, nil, tkRWnot)
else
Operate(FSymbolInfo, FFact.SymbolInfo, nil, tkUnaryMinus);
end;
end;
{ TProd_ConstExpression }
procedure TProd_ConstExpression.Parse;
begin
FSymbolInfo := Compile(TProd_Expression).SymbolInfo;
if FSymbolInfo.SymbolClass <> scConst then
Error(sConstExpected, ProductionLine, ProductionCol);
end;
{ TProd_SetConstructor }
(*
procedure TProd_SetConstructor.Parse;
var
TSet, TBase: TSymbolType;
P1, P2: TProd_MemberGroup;
SymClass: TSymbolClass;
I: Integer;
begin
Parser.GetNextToken; // '['
TBase := nil;
if Parser.CurrentToken = tkRBracket then
Parser.GetNextToken // []: empty set
else
begin
TProduction(P1) := Compile(TProd_MemberGroup);
while True do
begin
if Parser.CurrentToken <> tkComma then
Break;
Parser.GetNextToken;
TProduction(P2) := Compile(TProd_MemberGroup);
CheckTypes(P1.SymbolInfo.SymbolType, P2.SymbolInfo.SymbolType, tkAssign);
end;
if Parser.CurrentToken <> tkRBracket then
Error(sInvalidSetConstructor, ProductionLine, ProductionCol);
Parser.GetNextToken;
TBase := P1.SymbolInfo.SymbolType;
end;
TSet := SymbolTable.AllocType(TSetType);
TSetType(TSet).FBaseType := TBase;
//
SymClass := scConst;
for I := 0 to ProductionCount - 1 do
if not TProd_MemberGroup(Productions[I]).IsConst then
SymClass := scVar;
FSymbolInfo := SymbolTable.AllocSymbolInfo(SymClass, TSet);
if SymClass = scConst then
Self.Interpret;
end;
procedure TProd_SetConstructor.Interpret;
var
I, J, Inf, Sup: Integer;
Si1, Si2: TSymbolInfo;
Member: TProd_MemberGroup;
begin
PSetInteger(FSymbolInfo.Address)^ := [];
for I := 0 to ProductionCount - 1 do
begin
TProduction(Member) := Productions[I];
Member.Interpret;
Si1 := Member.FExprInf.SymbolInfo;
if Member.FExprSup = nil then
begin // only one expression
if Si1.SymbolType is TCharType then
PSetChar(FSymbolInfo.Address)^ := PSetChar(FSymbolInfo.Address)^ +
[PChar(Si1.Address)^]
else
PSetInteger(FSymbolInfo.Address)^ := PSetInteger(FSymbolInfo.Address)^ +
[PInteger(Si1.Address)^];
end else
begin // range expression
Si2 := Member.FExprSup.SymbolInfo;
if Si2.SymbolType is TCharType then
begin
Inf := Ord(PChar(Si1.Address)^);
Sup := Ord(PChar(Si2.Address)^);
end else
begin
Inf := PInteger(Si1.Address)^;
Sup := PInteger(Si2.Address)^;
end;
for J := Inf to Sup do
PSetInteger(FSymbolInfo.Address)^ :=
PSetInteger(FSymbolInfo.Address)^ + [J];
end;
end;
end;
*)
{ TProd_MemberGroup }
procedure TProd_MemberGroup.Parse;
begin
TProduction(FExprInf) := Compile(TProd_ConstExpression);
FExprInf.Interpret;
FSymbolInfo := FExprInf.SymbolInfo;
if not (FExprInf.SymbolInfo.SymbolType is TOrdinalType) then
Error(sOrdinalTypeRequired, ProductionLine, ProductionCol);
if Parser.CurrentToken = tkDotDot then
begin
Parser.GetNextToken; // dotdot
TProduction(FExprSup) := Compile(TProd_ConstExpression);
FExprSup.Interpret;
if not (FExprSup.SymbolInfo.SymbolType is TOrdinalType) then
Error(sOrdinalTypeRequired, ProductionLine, ProductionCol);
if FExprInf.SymbolInfo.SymbolType <> FExprSup.SymbolInfo.SymbolType then
Error(sIncompatibleTypes, ProductionLine, ProductionCol);
end;
end;
(*
procedure TProd_MemberGroup.Interpret;
begin
ShowMessage('member group. interpret');
FExprInf.Interpret;
if FExprSup <> nil then
FExprSup.Interpret;
end;
*)
function TProd_MemberGroup.IsConst: Boolean;
begin
Result := FExprInf.SymbolInfo.SymbolClass = scConst;
if FExprSup <> nil then
Result := Result and (FExprSup.SymbolInfo.SymbolClass = scConst);
end;
function TProd_MemberGroup.InRange(Si: TSymbolInfo): Boolean;
begin // test if value of Si is in member's range
if FExprSup = nil then // Si = Inf
Si.SymbolType.Oper(@Result, Si.Address, FExprInf.SymbolInfo.Address,
tkEqual, Self)
else
begin
// Si >= Inf and Si <= Sup
Si.SymbolType.Oper(@Result, Si.Address, FExprInf.SymbolInfo.Address, tkGE, Self);
if Result then
Si.SymbolType.Oper(@Result, Si.Address, FExprSup.SymbolInfo.Address, tkLE, Self);
end;
end;
function TProd_MemberGroup.InfSymbol: TSymbolInfo;
begin
Result := FExprInf.SymbolInfo;
end;
function TProd_MemberGroup.SupSymbol: TSymbolInfo;
begin
if FExprSup = nil then
Result := FExprInf.SymbolInfo
else
Result := FExprSup.SymbolInfo;
end;
{ TProd_Procedure }
procedure TProd_Procedure.Parse;
var
T: TProcedureType;
P: TProd_Procedure;
Col, Line: Integer;
begin
Parser.GetNextToken; // procedure
if Parser.CurrentToken <> tkId then
Error(sIdentifierExpected, Parser.TokenLine, Parser.TokenCol);
FProcId := Parser.TokenString;
Col := Parser.TokenCol;
Line := Parser.TokenLine;
Parser.GetNextToken; // id
Compiler.State := Compiler.State + [csFindInScope];
FSymbolInfo := SymbolTable.FindSymbol(FProcId);
Compiler.State := Compiler.State - [csFindInScope];
if FSymbolInfo <> nil then
begin // must be previous forward declaration
TProduction(P) := SymbolTable.LookForForward(FProcId);
if not (P is TProd_Procedure) or (P = nil) then
Error(Format(sIdentifierRedeclared, [FProcId]), Line, Col);
// this symboltable will be discarded
// it is used only for checking the forward declaration
FSymbolTable := SymbolTable.NewSymbolTable;
SymbolTable.AddScope(FSymbolTable);
TProduction(FParams) := Compile(TProd_FormalParamList);
if not FormalParamsOk(P.FParams, FParams) then
Error(Format(sDeclDiffers, [FProcId]), ProductionLine, ProductionCol);
GetTerminal(tkSemiColon);
SymbolTable.RemoveScope;
SymbolTable.AddScope(P.FSymbolTable);
Compiler.State := Compiler.State + [csInProcedure];
// the block that will be interpreted will be conected to the
// first declaration
P.FBlock := Compile(TProd_Block);
Compiler.State := Compiler.State - [csInProcedure];
GetTerminal(tkSemiColon);
SymbolTable.RemoveScope;
end
else
begin // first declaration
TSymbolType(T) := SymbolTable.AllocType(TProcedureType);
T.FProduction := Self;
SymbolTable.Enter(FProcId, scProcedure, T, MODL_PAC);
FSymbolTable := SymbolTable.NewSymbolTable;
SymbolTable.AddScope(FSymbolTable);
TProduction(FParams) := Compile(TProd_FormalParamList);
GetTerminal(tkSemiColon);
if Parser.CurrentToken = tkRWforward then
begin // forward declaration
Parser.GetNextToken; // forward
SymbolTable.AddForward(Self);
end
else
begin // first declaration: compile block
Compiler.State := Compiler.State + [csInProcedure];
FBlock := Compile(TProd_Block);
Compiler.State := Compiler.State - [csInProcedure];
end;
GetTerminal(tkSemiColon);
SymbolTable.RemoveScope;
end;
end;
{ TProd_Function }
procedure TProd_Function.Parse;
var
T: TFunctionType;
P: TProd_Function;
Line, Col: Integer;
begin
Parser.GetNextToken; // function
if Parser.CurrentToken <> tkId then
Error(sIdentifierExpected, Parser.TokenLine, Parser.TokenCol);
FFuncId := Parser.TokenString;
Line := Parser.TokenLine;
Col := Parser.TokenCol;
Parser.GetNextToken; // id
Compiler.State := Compiler.State + [csFindInScope];
FSymbolInfo := SymbolTable.FindSymbol(FFuncId);
Compiler.State := Compiler.State - [csFindInScope];
if FSymbolInfo <> nil then
begin // must be previous forward declaration
TProduction(P) := SymbolTable.LookForForward(FFuncId);
if not (P is TProd_Function) or (P = nil) then
Error(Format(sIdentifierRedeclared, [FFuncId]), Line, Col);
FSymbolTable := SymbolTable.NewSymbolTable;
SymbolTable.AddScope(FSymbolTable);
// Enter Result as scVarParam; type will be filled later
FSiResult := SymbolTable.Enter(RESULT_NAME, scVarParam, nil, MODL_PAC);
TProduction(FParams) := Compile(TProd_FormalParamList);
if not FormalParamsOk(P.FParams, FParams) then
Error(Format(sDeclDiffers, [FFuncId]), ProductionLine, ProductionCol);
GetTerminal(tkColon);
if Compile(TProd_ParamType).SymbolInfo.SymbolType <> P.FReturnType then
Error(Format(sDeclDiffers, [FFuncId]), ProductionLine, ProductionCol);
GetTerminal(tkSemiColon);
SymbolTable.RemoveScope;
FSiResult.FSymbolType := P.FReturnType;
SymbolTable.AddScope(P.FSymbolTable);
Compiler.State := Compiler.State + [csInFunction];
P.FBlock := Compile(TProd_Block);
Compiler.State := Compiler.State - [csInFunction];
GetTerminal(tkSemiColon);
SymbolTable.RemoveScope;
end
else
begin // first declaration
TSymbolType(T) := SymbolTable.AllocType(TFunctionType);
T.FProduction := Self;
SymbolTable.Enter(FFuncId, scFunction, T, MODL_PAC);
FSymbolTable := SymbolTable.NewSymbolTable;
SymbolTable.AddScope(FSymbolTable);
// Enter Result (scVarParam, so that no space is alocated)
// Type will be filled later
FSiResult := SymbolTable.Enter(RESULT_NAME, scVarParam, nil, MODL_PAC);
TProduction(FParams) := Compile(TProd_FormalParamList);
GetTerminal(tkColon);
// compile result type and fill FSiResult.SymbolType
FSiResult.FSymbolType := Compile(TProd_ParamType).SymbolInfo.SymbolType;
FReturnType := FSiResult.FSymbolType;
GetTerminal(tkSemiColon);
if Parser.CurrentToken = tkRWforward then
begin // forward declaration
Parser.GetNextToken; // forward
SymbolTable.AddForward(Self);
end
else
begin // first declaration: compile block
Compiler.State := Compiler.State + [csInFunction];
FBlock := Compile(TProd_Block);
Compiler.State := Compiler.State - [csInFunction];
end;
GetTerminal(tkSemiColon);
SymbolTable.RemoveScope;
end;
end;
{ TProd_FormalParamList }
procedure TProd_FormalParamList.Parse;
begin
FParamLst := TList.Create;
if Parser.CurrentToken <> tkLParen then
Exit; // no parameters
Parser.GetNextToken; // (
while True do
begin
if Parser.CurrentToken = tkRParen then
Break;
Compile(TProd_ParamDecl);
if Parser.CurrentToken = tkSemiColon then
begin
Parser.GetNextToken;
Continue;
end
else
Break;
end;
GetTerminal(tkRParen);
end;
destructor TProd_FormalParamList.Destroy;
begin
FParamLst.Free;
inherited Destroy;
end;
{ TProd_ParamDecl }
procedure TProd_ParamDecl.Parse;
var
I: Integer;
Lst: TStringList;
ProdType: TProduction;
P: TSymbolInfo;
SymbolClass: TSymbolClass;
begin
Lst := TStringList.Create;
Lst.CaseSensitive := True;
try
if Parser.CurrentToken = tkRWvar then
begin
Parser.GetNextToken; // var
SymbolClass := scVarParam;
end
else
SymbolClass := scVar;
Compiler.State := Compiler.State + [csFindInScope];
GetNewIdentifierList(Lst);
Compiler.State := Compiler.State - [csFindInScope];
GetTerminal(tkColon);
ProdType := Compile(TProd_ParamType);
for I := 0 to Lst.Count - 1 do
begin
P := SymbolTable.Enter(Lst[I], SymbolClass, ProdType.SymbolInfo.SymbolType, MODL_PAC);
TProd_FormalParamList(Parent).FParamLst.Add(P);
end;
finally
Lst.Free;
end;
end;
{ TProd_ProcedureCall }
procedure TProd_ProcedureCall.Parse;
var
I: Integer;
P: TProd_Procedure;
E: TProduction;
Si: TSymbolInfo;
T: TSymbolType;
procedure GetActuals;
begin
GetTerminal(tkLParen);
while True do
begin
Compile(TProd_Expression);
if Parser.CurrentToken <> tkComma then
Break;
Parser.GetNextToken; // comma
end;
GetTerminal(tkRParen);
end;
procedure GetParenthesis;
begin
GetTerminal(tkLParen);
GetTerminal(tkRParen);
end;
begin
FSymbolInfo := SymbolTable.FindSymbol(Parser.TokenString); // again
Parser.GetNextToken; // id
P := TProcedureType(FSymbolInfo.SymbolType).FProduction;
FProcId := P.ProcId;
if P.FParams.FParamLst.Count > 0 then
begin // get actual parameters
GetActuals;
// after GetActuals, ProductionCount = number of actual parameters
if ProductionCount < P.FParams.FParamLst.Count then
Error(sNotEnoughActuals, ProductionLine, ProductionCol);
if ProductionCount > P.FParams.FParamLst.Count then
Error(sTooManyActuals, ProductionLine, ProductionCol);
// check actual parameter types
for I := 0 to ProductionCount - 1 do
begin
Si := P.FParams.FParamLst[I];
E := Productions[I];
if Si.SymbolClass = scVarParam then
begin
if not (E.SymbolInfo.SymbolClass in [scVar, scVarParam, scPointer]) then
Error(sWrongActual2, ProductionLine, ProductionCol);
if Si.SymbolType <> E.SymbolInfo.SymbolType then
Error(sWrongActual, ProductionLine, ProductionCol);
end
else
begin
T := CheckTypes(Si.SymbolType, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
end;
end;
end
else
GetParenthesis;
end;
procedure TProd_ProcedureCall.Interpret;
var
I: Integer;
P: TProd_Procedure;
Sia, Sip: TSymbolInfo;
LstSi: TList;
Addr: Pointer;
LstAddr: TList;
LstType: TList;
SaveSymTbl: TSymbolTable;
begin
// verifica consumo de memória
// CheckMemory;
// interpret arguments and get their addresses
LstAddr := TList.Create;
LstType := TList.Create; // LstType remembers arguments' type, in order
// to transfer them to the area occupied by
// the parameters inside the new scope
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret;
Sia := Productions[I].SymbolInfo;
if Productions[I].ExecPromotion then
Sia := Productions[I].Promoted;
LstAddr.Add(Sia.Address);
LstType.Add(Sia.SymbolType);
end;
// prepare activation
P := TProcedureType(FSymbolInfo.SymbolType).FProduction;
P.FSymbolTable.SetActivation;
SaveSymTbl := Compiler.SetSubroutineSymbolTable(P.FSymbolTable);
LstSi := P.FParams.FParamLst;
// exibe símbolos desta ativação
P.FSymbolTable.ShowSubroutineCall(ProcId);
P.FSymbolTable.ShowMemActivation;
// copy arguments
for I := 0 to ProductionCount - 1 do
begin
Sip := TSymbolInfo(LstSi[I]);
if Sip.SymbolClass = scVarParam then
begin // solve var parameter
Addr := PByte(Sip.SymbolTable.FVarArea.Last) + Sip.FOffset;
PByte(Addr^) := LstAddr[I];
// associa o var param ao argumento
P.FSymbolTable.MarkAsPointer(Integer(Addr));
P.FSymbolTable.UpdateVarParam(Integer(Addr), IntToStr(Integer(LstAddr[I])));
end
else begin
// copia argumento por valor
TSymbolType(LstType[I]).Oper(Sip.Address, LstAddr[I], nil, tkAssign, Self);
// atualiza a parte visual
P.FSymbolTable.UpdateMem(LstType[I], Integer(Sip.Address));
end;
end;
LstAddr.Free;
LstType.Free;
// interpret procedure block
try
P.FBlock.Interpret;
except
on EExitException do // catch Exit
;
end;
// verifica depuração, dando chance à execução passo a passo de
// parar no 'fim' da rotina
VerifyDebug(P.FBlock.FProductionEndLine, P.FBlock.FProductionEndCol, P.Parser);
// apaga símbolos desta ativação
P.FSymbolTable.ShowSubroutineReturn;
P.FSymbolTable.LibActivation;
Compiler.SetSubroutineSymbolTable(SaveSymTbl);
end;
{ TProd_FunctionCall }
procedure TProd_FunctionCall.Parse;
var
I: Integer;
P: TProd_Function;
E: TProduction;
Si: TSymbolInfo;
T: TSymbolType;
procedure GetActuals;
begin
GetTerminal(tkLParen);
while True do
begin
Compile(TProd_Expression);
if Parser.CurrentToken <> tkComma then
Break;
Parser.GetNextToken; // comma
end;
GetTerminal(tkRParen);
end;
procedure GetParenthesis;
begin
GetTerminal(tkLParen);
GetTerminal(tkRParen);
end;
begin
FFuncSymbol := SymbolTable.FindSymbol(Parser.TokenString); // again
Parser.GetNextToken; // function name
P := TFunctionType(FFuncSymbol.SymbolType).FProduction;
FFuncId := P.FuncId;
if P.FParams.FParamLst.Count > 0 then
begin // get actual parameters
GetActuals;
// after GetActuals, ProductionCount = number of actual parameters
if ProductionCount < P.FParams.FParamLst.Count then
Error(sNotEnoughActuals, ProductionLine, ProductionCol);
if ProductionCount > P.FParams.FParamLst.Count then
Error(sTooManyActuals, ProductionLine, ProductionCol);
// check actual parameter types
for I := 0 to ProductionCount - 1 do
begin
Si := P.FParams.FParamLst[I];
E := Productions[I];
if Si.SymbolClass = scVarParam then
begin
if not (E.SymbolInfo.SymbolClass in [scVar, scVarParam, scPointer]) then
Error(sWrongActual2, ProductionLine, ProductionCol);
if Si.SymbolType <> E.SymbolInfo.SymbolType then
Error(sWrongActual, ProductionLine, ProductionCol);
end
else
begin
T := CheckTypes(Si.SymbolType, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
end;
end;
end
else
GetParenthesis;
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, P.FReturnType);
end;
procedure TProd_FunctionCall.Interpret;
var
I: Integer;
P: TProd_Function;
Sia, Sip: TSymbolInfo;
LstSi: TList;
Addr, ResultAddr: Pointer;
LstAddr: TList;
LstType: TList;
SaveSymTbl: TSymbolTable;
ReturnExecuted: Boolean;
begin
// verifica consumo de memória
// CheckMemory;
// get FSymbolInfo.Address before activation
ResultAddr := FSymbolInfo.Address;
// interpret arguments and get their addresses
LstAddr := TList.Create;
LstType := TList.Create; // LstType remembers arguments' type, in order
// to transfer them to the area occupied by
// the parameters inside the new scope
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret;
Sia := Productions[I].SymbolInfo;
if Productions[I].ExecPromotion then
Sia := Productions[I].Promoted;
LstAddr.Add(Sia.Address);
LstType.Add(Sia.SymbolType);
end;
// prepare activation
P := TFunctionType(FFuncSymbol.SymbolType).FProduction;
P.FSymbolTable.SetActivation;
SaveSymTbl := Compiler.SetSubroutineSymbolTable(P.FSymbolTable);
LstSi := P.FParams.FParamLst;
// exibe símbolos desta ativação
P.FSymbolTable.ShowSubroutineCall(FuncId);
P.FSymbolTable.ShowMemActivation;
// copy arguments
for I := 0 to ProductionCount - 1 do
begin
Sip := TSymbolInfo(LstSi[I]);
if Sip.SymbolClass = scVarParam then
begin // solve var parameter
Addr := PByte(Sip.SymbolTable.FVarArea.Last) + Sip.FOffset;
PByte(Addr^) := LstAddr[I];
// associa o var param ao argumento
P.FSymbolTable.MarkAsPointer(Integer(Addr));
P.FSymbolTable.UpdateVarParam(Integer(Addr), IntToStr(Integer(LstAddr[I])));
end
else begin
// copia argumento por valor
TSymbolType(LstType[I]).Oper(Sip.Address, LstAddr[I], nil, tkAssign, Self);
// atualiza a parte visual
P.FSymbolTable.UpdateMem(LstType[I], Integer(Sip.Address));
end;
end;
LstAddr.Free;
LstType.Free;
// replace references to Result and to the function name
Addr := PByte(P.FSiResult.SymbolTable.FVarArea.Last) +
P.FSiResult.FOffset;
PByte(Addr^) := ResultAddr;
// trata caso especial de result ser ponteiro
(*
if P.FSiResult.SymbolType is TPointerType then
begin
P.FSymbolTable.ChangeAddress(Integer(Addr), Integer(ResultAddr));
P.FSymbolTable.MarkAsPointer(Integer(ResultAddr));
end;
*)
P.FSymbolTable.ChangeAddress(Integer(Addr), Integer(ResultAddr));
if P.FSiResult.SymbolType is TPointerType then
P.FSymbolTable.MarkAsPointer(Integer(ResultAddr));
// interpret function block
ReturnExecuted := False;
try
P.FBlock.Interpret;
except
on EExitException do // catch Exit
ReturnExecuted := True;
end;
if not ReturnExecuted then
Error(sNoReturnExecutedInFunction, ProductionLine, ProductionCol);
// verifica depuração, dando chance à execução passo a passo de
// parar no 'fim' da rotina
VerifyDebug(P.FBlock.FProductionEndLine, P.FBlock.FProductionEndCol, P.Parser);
// apaga símbolos desta ativação
P.FSymbolTable.ShowSubroutineReturn;
P.FSymbolTable.LibActivation;
Compiler.SetSubroutineSymbolTable(SaveSymTbl);
end;
{ TProd_RectangleStmt }
procedure TProd_RectangleStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // rectangle
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (Quadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_RectangleStmt.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Q: TQuadro;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // todas as expressões inteiras
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ desenha no quadro e no bmp }
Q.dsn_ret(V[1], V[2], V[3], V[4]);
end;
{ TProd_FillRect }
procedure TProd_FillRect.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsnRetCh
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (Quadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FillRect.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Q: TQuadro;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // todas as expressões inteiras
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ desenha no quadro e no bmp }
Q.dsn_ret_cheio(V[1], V[2], V[3], V[4]);
end;
{ TProd_dsnLinSel }
procedure TProd_dsnLinSel.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsnLinSel
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (Quadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_dsnLinSel.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..2] of Integer;
Q: TQuadro;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // todas as expressões inteiras
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ desenha no quadro e no bmp }
Q.dsn_lin_sel(V[1], V[2]);
end;
{ TProd_TriangleStmt }
procedure TProd_TriangleStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // triangle
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (Quadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_TriangleStmt.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Q: TQuadro;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // todas as expressões inteiras
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ desenha no quadro e no bmp }
Q.dsn_tri(V[1], V[2], V[3], V[4]);
end;
{ TProd_EllipseStmt }
procedure TProd_EllipseStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // ellipse
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_EllipseStmt.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Q: TQuadro;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // the four integer expressions
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ desenha no quadro e no bmp }
Q.dsn_cir(V[1], V[2], V[3], V[4]);
end;
{ TProd_TerminateStmt }
procedure TProd_TerminateStmt.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // dsl_termine
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // mensagem
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
end;
procedure TProd_TerminateStmt.Interpret;
var
Si: TSymbolInfo;
S: String;
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
S := PString(Si.Address)^;
// o comando dsl_termine está sendo implementado como um erro
// de execução, através de uma exceção
Error(S, Productions[0].ProductionLine, Productions[0].ProductionCol);
end;
{ TProd_Arc }
procedure TProd_Arc.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_arco
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_Arc.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..7] of Integer;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // oito expressões inteiras
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
if Compiler.Canvas <> nil then
Compiler.Canvas.Arc(V[0], V[1], V[2], V[3], V[4], V[5], V[6], V[7]);
end;
{ TProd_FrameArc }
procedure TProd_FrameArc.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroArco
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameArc.Interpret;
var
Si: TSymbolInfo;
X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer;
Q: TQuadro;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // x1
Si := Productions[1].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[2].Interpret; // y1
Si := Productions[2].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[3].Interpret; // x2
Si := Productions[3].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[4].Interpret; // y2
Si := Productions[4].SymbolInfo;
Y2 := PInteger(Si.Address)^;
Productions[5].Interpret; // x3
Si := Productions[5].SymbolInfo;
X3 := PInteger(Si.Address)^;
Productions[6].Interpret; // y3
Si := Productions[6].SymbolInfo;
Y3 := PInteger(Si.Address)^;
Productions[7].Interpret; // x4
Si := Productions[7].SymbolInfo;
X4 := PInteger(Si.Address)^;
Productions[8].Interpret; // y4
Si := Productions[8].SymbolInfo;
Y4 := PInteger(Si.Address)^;
Q.dsn_arco(X1, Y1, X2, Y2, X3, Y3, X4, Y4);
end;
{ TProd_Bezier }
procedure TProd_Bezier.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_bezier
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // cx1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cy1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cx2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cy2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_Bezier.Interpret;
var
Si: TSymbolInfo;
V: array [0..2] of TPoint;
begin
if Compiler.Canvas = nil then
Exit; // nada a fazer
// obs: a curva começa na posição corrente do cursor
// primeiro ponto de controle
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
V[0].X := PInteger(Si.Address)^;
Productions[1].Interpret;
Si := Productions[1].SymbolInfo;
V[0].Y := PInteger(Si.Address)^;
// segundo ponto de controle
Productions[2].Interpret;
Si := Productions[2].SymbolInfo;
V[1].X := PInteger(Si.Address)^;
Productions[3].Interpret;
Si := Productions[3].SymbolInfo;
V[1].Y := PInteger(Si.Address)^;
// ponto final
Productions[4].Interpret;
Si := Productions[4].SymbolInfo;
V[2].X := PInteger(Si.Address)^;
Productions[5].Interpret;
Si := Productions[5].SymbolInfo;
V[2].Y := PInteger(Si.Address)^;
Compiler.Canvas.PolyBezierTo(V);
end;
{ TProd_FrameBezier }
procedure TProd_FrameBezier.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsnBezier
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cx1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cy1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cx2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // cy2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameBezier.Interpret;
var
Si: TSymbolInfo;
V: array [0..5] of Integer;
Q: TQuadro;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// obs: a curva começa com a posição corrente do cursor
// primeiro ponto de controle
Productions[1].Interpret;
Si := Productions[1].SymbolInfo;
V[0] := PInteger(Si.Address)^;
Productions[2].Interpret;
Si := Productions[2].SymbolInfo;
V[1] := PInteger(Si.Address)^;
// segundo ponto de controle
Productions[3].Interpret;
Si := Productions[3].SymbolInfo;
V[2] := PInteger(Si.Address)^;
Productions[4].Interpret;
Si := Productions[4].SymbolInfo;
V[3] := PInteger(Si.Address)^;
// ponto final
Productions[5].Interpret;
Si := Productions[5].SymbolInfo;
V[4] := PInteger(Si.Address)^;
Productions[6].Interpret;
Si := Productions[6].SymbolInfo;
V[5] := PInteger(Si.Address)^;
Q.dsn_bezier(V[0], V[1], V[2], V[3], V[4], V[5]);
end;
{ TProd_Chord }
procedure TProd_Chord.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_corte
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_Chord.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..7] of Integer;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // oito expressões inteiras
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
if Compiler.Canvas <> nil then
Compiler.Canvas.Chord(V[0], V[1], V[2], V[3], V[4], V[5], V[6], V[7]);
end;
{ TProd_FrameChord }
procedure TProd_FrameChord.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroCorte
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameChord.Interpret;
var
Si: TSymbolInfo;
X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer;
Q: TQuadro;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // x1
Si := Productions[1].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[2].Interpret; // y1
Si := Productions[2].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[3].Interpret; // x2
Si := Productions[3].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[4].Interpret; // y2
Si := Productions[4].SymbolInfo;
Y2 := PInteger(Si.Address)^;
Productions[5].Interpret; // x3
Si := Productions[5].SymbolInfo;
X3 := PInteger(Si.Address)^;
Productions[6].Interpret; // y3
Si := Productions[6].SymbolInfo;
Y3 := PInteger(Si.Address)^;
Productions[7].Interpret; // x4
Si := Productions[7].SymbolInfo;
X4 := PInteger(Si.Address)^;
Productions[8].Interpret; // y4
Si := Productions[8].SymbolInfo;
Y4 := PInteger(Si.Address)^;
Q.dsn_corte(X1, Y1, X2, Y2, X3, Y3, X4, Y4);
end;
{ TProd_Pie }
procedure TProd_Pie.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_fatia
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_Pie.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..7] of Integer;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // oito expressões inteiras
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
if Compiler.Canvas <> nil then
Compiler.Canvas.Pie(V[0], V[1], V[2], V[3], V[4], V[5], V[6], V[7]);
end;
{ TProd_FramePie }
procedure TProd_FramePie.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroFatia
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y3
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y4
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FramePie.Interpret;
var
Si: TSymbolInfo;
X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer;
Q: TQuadro;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // x1
Si := Productions[1].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[2].Interpret; // y1
Si := Productions[2].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[3].Interpret; // x2
Si := Productions[3].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[4].Interpret; // y2
Si := Productions[4].SymbolInfo;
Y2 := PInteger(Si.Address)^;
Productions[5].Interpret; // x3
Si := Productions[5].SymbolInfo;
X3 := PInteger(Si.Address)^;
Productions[6].Interpret; // y3
Si := Productions[6].SymbolInfo;
Y3 := PInteger(Si.Address)^;
Productions[7].Interpret; // x4
Si := Productions[7].SymbolInfo;
X4 := PInteger(Si.Address)^;
Productions[8].Interpret; // y4
Si := Productions[8].SymbolInfo;
Y4 := PInteger(Si.Address)^;
Q.dsn_fatia(X1, Y1, X2, Y2, X3, Y3, X4, Y4);
end;
{ TProd_CopyFrameStmt }
procedure TProd_CopyFrameStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_copieQuadro
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_CopyFrameStmt.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
X, Y: Integer;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Integer(Bmp) := PInteger(Si.Address)^;
Productions[1].Interpret; // x
Si := Productions[1].SymbolInfo;
X := PInteger(Si.Address)^;
Productions[2].Interpret; // y
Si := Productions[2].SymbolInfo;
Y := PInteger(Si.Address)^;
if Compiler.Canvas <> nil then
Compiler.Canvas.Draw(X, Y, Bmp);
end;
{ TProd_Stretch }
procedure TProd_Stretch.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // gra_estiqueQuadro
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_Stretch.Interpret;
var
Si: TSymbolInfo;
Bmp: Graphics.TBitmap;
X1, Y1, X2, Y2: Integer;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Integer(Bmp) := PInteger(Si.Address)^;
Productions[1].Interpret; // x1
Si := Productions[1].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[2].Interpret; // y1
Si := Productions[2].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[3].Interpret; // x2
Si := Productions[3].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[4].Interpret; // y2
Si := Productions[4].SymbolInfo;
Y2 := PInteger(Si.Address)^;
if Compiler.Canvas <> nil then
Compiler.Canvas.StretchDraw(Rect(X1, Y1, X2, Y2), Bmp);
end;
{ TProd_FrameStretch }
procedure TProd_FrameStretch.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsl_quadroEstiqueQuadro
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // quadro
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // quadroOrigem
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sFrameTypeExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_FrameStretch.Interpret;
var
Si: TSymbolInfo;
X1, Y1, X2, Y2: Integer;
Bmp, BmpOrig: Graphics.TBitmap;
begin
Productions[0].Interpret; // quadro
Si := Productions[0].SymbolInfo;
Bmp := Graphics.TBitmap(PInteger(Si.Address)^);
if not (Bmp is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // quadroOrigem
Si := Productions[1].SymbolInfo;
BmpOrig := Graphics.TBitmap(PInteger(Si.Address)^);
if not (BmpOrig is Graphics.TBitmap) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[2].Interpret; // X1
Si := Productions[2].SymbolInfo;
X1 := PInteger(Si.Address)^;
Productions[3].Interpret; // Y1
Si := Productions[3].SymbolInfo;
Y1 := PInteger(Si.Address)^;
Productions[4].Interpret; // X2
Si := Productions[4].SymbolInfo;
X2 := PInteger(Si.Address)^;
Productions[5].Interpret; // Y2
Si := Productions[5].SymbolInfo;
Y2 := PInteger(Si.Address)^;
Bmp.Canvas.StretchDraw(Rect(X1, Y1, X2, Y2), BmpOrig);
end;
{ TProd_LineToStmt }
procedure TProd_LineToStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // LineTo
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_LineToStmt.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..2] of Integer;
Q: TQuadro;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // três expressões inteiras
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ desenha no quadro e no bmp }
Q.dsn_lin(V[1], V[2]);
end;
{ TProd_WaitForStmt }
procedure TProd_WaitForStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // waitFor
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // events
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_WaitForStmt.Interpret;
var
Si: TSymbolInfo;
Events: Integer;
begin
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
Events := PInteger(Si.Address)^;
if Assigned(Compiler.FOnWaitFor) then
Compiler.FOnWaitFor(Compiler, Events);
end;
{ TProd_MoveToStmt }
procedure TProd_MoveToStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // MoveTo
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_MoveToStmt.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..2] of Integer;
Q: TQuadro;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // quadro, x, y
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ desenha no quadro e no bmp }
Q.alt_pos_caneta(V[1], V[2]);
end;
{ TProd_altPixel }
procedure TProd_altPixel.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // SetPixel
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // color
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_altPixel.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..3] of Integer;
Q: TQuadro;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // quadro, x, y, cor
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ desenha no quadro e no bmp }
Q.alt_pixel(V[1], V[2], V[3]);
end;
{ TProd_TextOutStmt }
procedure TProd_TextOutStmt.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // TextOut
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // the text
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
end;
procedure TProd_TextOutStmt.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..2] of Integer;
Ps: PString;
Q: TQuadro;
begin
for I := 0 to 2 do
begin
Productions[I].Interpret; // quadro, x, y
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[3].Interpret; // string expression
Si := Productions[3].SymbolInfo;
if Productions[3].ExecPromotion then
Si := Productions[3].Promoted;
Ps := PString(Si.Address);
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ desenha no quadro e no bmp }
Q.dsn_txt(V[1], V[2], Ps^);
end;
{ TProd_SetBrushColorStmt }
procedure TProd_SetBrushColorStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // SetBrushColor
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // color
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_SetBrushColorStmt.Interpret;
var
Si: TSymbolInfo;
Color: Integer;
Q: TQuadro;
begin
{ obtém o quadro }
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret;
Si := Productions[1].SymbolInfo;
Color := PInteger(Si.Address)^;
{ desenha no quadro e no bmp }
Q.alt_cor_pincel(TColor(Color));
end;
{ TProd_SetPenColorStmt }
procedure TProd_SetPenColorStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // SetPenColor
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // color
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_SetPenColorStmt.Interpret;
var
Si: TSymbolInfo;
Color: Integer;
Q: TQuadro;
begin
{ obtém o quadro }
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret;
Si := Productions[1].SymbolInfo;
Color := PInteger(Si.Address)^;
{ desenha no quadro e no bmp }
Q.alt_cor_caneta(TColor(Color));
end;
{ TProd_SetPenWidthStmt }
procedure TProd_SetPenWidthStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // SetPenWidth
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // width
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_SetPenWidthStmt.Interpret;
var
Si: TSymbolInfo;
Width: Integer;
Q: TQuadro;
begin
{ obtém o quadro }
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret;
Si := Productions[1].SymbolInfo;
Width := PInteger(Si.Address)^;
{ desenha no quadro e no bmp }
Q.alt_tam_caneta(Width);
end;
{ TProd_SetFontColorStmt }
procedure TProd_SetFontColorStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // SetFontColor
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // color
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_SetFontColorStmt.Interpret;
var
Si: TSymbolInfo;
Color: Integer;
Q: TQuadro;
begin
{ obtém o quadro }
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret;
Si := Productions[1].SymbolInfo;
Color := PInteger(Si.Address)^;
{ desenha no quadro e no bmp }
Q.alt_cor_fonte(TColor(Color));
end;
{ TProd_SetFontSizeStmt }
procedure TProd_SetFontSizeStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // SetFontSize
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // size
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_SetFontSizeStmt.Interpret;
var
Si: TSymbolInfo;
Size: Integer;
Q: TQuadro;
begin
{ obtém o quadro }
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret;
Si := Productions[1].SymbolInfo;
Size := PInteger(Si.Address)^;
{ desenha no quadro e no bmp }
Q.alt_tam_fonte(Size);
end;
{ TProd_SetFontNameStmt }
procedure TProd_SetFontNameStmt.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // SetFontName
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // nome
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
end;
procedure TProd_SetFontNameStmt.Interpret;
var
Si: TSymbolInfo;
Ps: PString;
Q: TQuadro;
begin
{ obtém o quadro }
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret; // nome
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
Ps := PString(Si.Address);
{ desenha no quadro e no bmp }
Q.alt_nome_fonte(Ps^);
end;
{ TProd_toqSom }
procedure TProd_toqSom.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // toq_som
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // som
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_toqSom.Interpret;
var
Si: TSymbolInfo;
Som: Integer; // som
begin
Productions[0].Interpret; // som
Si := Productions[0].SymbolInfo;
Som := PInteger(Si.Address)^;
// verifica se o som é válido
if not (TObject(Som) is TCtrlMediaPlayer) then
Error(sFalhaToqSomExec, ProductionLine, ProductionCol);
// toca
TCtrlMediaPlayer(Som).Toque;
end;
{ TProd_SetBrushStyleStmt }
procedure TProd_SetBrushStyleStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // SetBrushStyle
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // brush style
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_SetBrushStyleStmt.Interpret;
var
Si: TSymbolInfo;
Style: TBrushStyle;
Q: TQuadro;
begin
{ obtém o quadro }
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret;
Si := Productions[1].SymbolInfo;
Style := TBrushStyle(PInteger(Si.Address)^);
{ desenha no quadro e no bmp }
Q.alt_estilo_pincel(Style);
end;
{ TProd_Inc }
procedure TProd_Inc.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // inc
GetTerminal(tkLParen);
E := Compile(TProd_VarReference);
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_Inc.Interpret;
var
Si: TSymbolInfo;
begin
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
PInteger(Si.Address)^ := PInteger(Si.Address)^ + 1;
// atualiza na memoria
SymbolTable.UpdateMem(Productions[0].SymbolInfo.SymbolType,
Integer(Productions[0].SymbolInfo.Address));
end;
{ TProd_Dec }
procedure TProd_Dec.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dec
GetTerminal(tkLParen);
E := Compile(TProd_VarReference);
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_Dec.Interpret;
var
Si: TSymbolInfo;
begin
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
PInteger(Si.Address)^ := PInteger(Si.Address)^ - 1;
// atualiza na memoria
SymbolTable.UpdateMem(Productions[0].SymbolInfo.SymbolType,
Integer(Productions[0].SymbolInfo.Address));
end;
{ TProd_DecodificaData }
procedure TProd_DecodificaData.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // evnt_decodificaData
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // TDateTime (tipicamente, evnt_agora())
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkComma);
E := Compile(TProd_VarReference); // dia
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_VarReference); // mês
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_VarReference); // ano
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_DecodificaData.Interpret;
var
Si: TSymbolInfo;
Data: Extended;
Ano, Mes, Dia: word;
begin
Productions[0].Interpret; // TDateTime
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
Data := PExtended(Si.Address)^;
DecodeDate(Data, Ano, Mes, Dia);
Productions[1].Interpret; // Dia
Si := Productions[1].SymbolInfo;
PInteger(Si.Address)^ := Dia;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
Productions[2].Interpret; // Mês
Si := Productions[2].SymbolInfo;
PInteger(Si.Address)^ := Mes;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
Productions[3].Interpret; // Ano
Si := Productions[3].SymbolInfo;
PInteger(Si.Address)^ := Ano;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
end;
{ TProd_DecodificaHora }
procedure TProd_DecodificaHora.Parse;
var
T: TSymbolType;
E: TProduction;
begin
Parser.GetNextToken; // evnt_decodificaHora
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // TDateTime (tipicamente, evnt_agora())
T := CheckTypes(Compiler.DeclTypeExtended, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkComma);
E := Compile(TProd_VarReference); // hora
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_VarReference); // minuto
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_VarReference); // segundo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_VarReference); // milissegundo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_DecodificaHora.Interpret;
var
Si: TSymbolInfo;
Data: Extended;
Hora, Minuto, Segundo, Mili: word;
begin
Productions[0].Interpret; // TDateTime
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
Data := PExtended(Si.Address)^;
DecodeTime(Data, Hora, Minuto, Segundo, Mili);
Productions[1].Interpret; // Hora
Si := Productions[1].SymbolInfo;
PInteger(Si.Address)^ := Hora;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
Productions[2].Interpret; // Minuto
Si := Productions[2].SymbolInfo;
PInteger(Si.Address)^ := Minuto;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
Productions[3].Interpret; // Segundo
Si := Productions[3].SymbolInfo;
PInteger(Si.Address)^ := Segundo;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
Productions[4].Interpret; // milissegundo
Si := Productions[4].SymbolInfo;
PInteger(Si.Address)^ := Mili;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
end;
{ TProd_CodificaData }
procedure TProd_CodificaData.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // evnt_codificaData
GetTerminal(tkLParen);
E := Compile(TProd_VarReference); // data
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeExtended then
Error(sRealVarExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // Dia
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // Mês
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // Ano
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_CodificaData.Interpret;
var
Si: TSymbolInfo;
Data: TDateTime;
Ano, Mes, Dia: word;
begin
Productions[1].Interpret; // Dia
Si := Productions[1].SymbolInfo;
Dia := PInteger(Si.Address)^;
Productions[2].Interpret; // Mês
Si := Productions[2].SymbolInfo;
Mes := PInteger(Si.Address)^;
Productions[3].Interpret; // Ano
Si := Productions[3].SymbolInfo;
Ano := PInteger(Si.Address)^;
Data := EncodeDate(Ano, Mes, Dia);
Productions[0].Interpret; // (var) data
Si := Productions[0].SymbolInfo;
PExtended(Si.Address)^ := Data;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
end;
{ TProd_CodificaHora }
procedure TProd_CodificaHora.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // evnt_codifiqueHora
GetTerminal(tkLParen);
E := Compile(TProd_VarReference); // hora
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeExtended then
Error(sRealVarExpected, E.ProductionLine, E.ProductionCol);
if (E.SymbolInfo.SymbolClass <> scVar) and
(E.SymbolInfo.SymbolClass <> scField) and
(E.SymbolInfo.SymbolClass <> scVarParam) then
Error(sWrongActual2, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // Hora
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // Minuto
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // Segundo
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // Mili
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_CodificaHora.Interpret;
var
Si: TSymbolInfo;
Data: TDateTime;
Hora, Minuto, Segundo, Mili: word;
begin
Productions[1].Interpret; // Hora
Si := Productions[1].SymbolInfo;
Hora := PInteger(Si.Address)^;
Productions[2].Interpret; // Minuto
Si := Productions[2].SymbolInfo;
Minuto := PInteger(Si.Address)^;
Productions[3].Interpret; // Segundo
Si := Productions[3].SymbolInfo;
Segundo := PInteger(Si.Address)^;
Productions[4].Interpret; // Mili
Si := Productions[4].SymbolInfo;
Mili := PInteger(Si.Address)^;
Data := EncodeTime(Hora, Minuto, Segundo, Mili);
Productions[0].Interpret; // (var) data
Si := Productions[0].SymbolInfo;
PExtended(Si.Address)^ := Data;
SymbolTable.UpdateMem(Si.SymbolType, Integer(Si.Address));
end;
{ TProd_BreakStmt }
procedure TProd_BreakStmt.Parse;
begin
if not (csInRepetitiveStmt in Compiler.State) then
Error(sBreakOutsideLoop, ProductionLine, ProductionCol);
Parser.GetNextToken; // Break
end;
procedure TProd_BreakStmt.Interpret;
begin
raise EBreakException.Create('', 0, 0, Parser);
end;
{ TProd_ContinueStmt }
procedure TProd_ContinueStmt.Parse;
begin
if not (csInRepetitiveStmt in Compiler.State) then
Error(sContinueOutsideLoop, ProductionLine, ProductionCol);
Parser.GetNextToken; // Continue
end;
procedure TProd_ContinueStmt.Interpret;
begin
raise EContinueException.Create('', 0, 0, Parser);
end;
{ TProd_ReturnStmt }
procedure TProd_ReturnStmt.Parse;
var
T: TSymbolType;
begin
Parser.GetNextToken; // Retorne
if (csInProcedure in Compiler.State) then
begin
// dentro de procedimento, RETORNE tem de ser seguido de ponto e vírgula
if Parser.CurrentToken <> tkSemiColon then
Error(Format(sTerminalExpected, [Parser.GetTokenName(tkSemiColon)]),
Parser.TokenLine, Parser.TokenCol);
end
else if (csInFunction in Compiler.State) then
begin
// simule um comando de atribuição 'result := expression'
FSymbolInfo := SymbolTable.FindSymbol(RESULT_NAME);
Compile(TProd_Expression);
T := CheckTypes(FSymbolInfo.SymbolType, Productions[0].SymbolInfo.SymbolType,
tkAssign);
Productions[0].PromoteTo(T);
end
else
Error(sExitOutsideSubroutine, ProductionLine, ProductionCol);
end;
procedure TProd_ReturnStmt.Interpret;
var
Si: TSymbolInfo;
T: TOrdinalType;
OrdValue: Integer;
begin
// caso tenha havido uma expressão, avalie-a
if ProductionCount > 0 then
begin
Productions[0].Interpret; // expression
Si := Productions[0].SymbolInfo;
// test promotion
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
// FSymbolInfo é uma referência a result; verifique o range
if FSymbolInfo.SymbolType is TOrdinalType then
begin
T := TOrdinalType(Si.SymbolType); // expression must be ordinal
OrdValue := T.OrdinalValue(Si);
T := TOrdinalType(FSymbolInfo.SymbolType);
if (OrdValue < T.MinValue) or (OrdValue > T.MaxValue) then
Error(sAssignmentOutOfRange, ProductionLine, ProductionCol);
end;
Operate(FSymbolInfo, Si, nil, tkAssign);
// atualiza na memoria
SymbolTable.UpdateMem(FSymbolInfo.SymbolType, Integer(FSymbolInfo.Address));
end;
raise EExitException.Create('', 0, 0, Parser);
end;
{ TProd_FunctionAssign }
procedure TProd_FunctionAssign.Parse;
var
P: TProd_Function;
begin
FSymbolInfo := SymbolTable.FindSymbol(Parser.TokenString); // again
Parser.GetNextToken; // function name
P := TFunctionType(FSymbolInfo.SymbolType).FProduction;
FSymbolInfo := P.FSiResult;
end;
{ TProd_VarReference }
procedure TProd_VarReference.Parse;
var
Qualif: TProductionClass;
T: TSymbolType;
function QualifClass: TProductionClass;
begin
if (FSymbolInfo.SymbolType is TArrayType) and
(Parser.CurrentToken = tkLBracket) then
Result := TProd_QualifIndex
else if (FSymbolInfo.SymbolType is TRecordType) and
(Parser.CurrentToken = tkPeriod) then
Result := TProd_QualifField
else if (FSymbolInfo.SymbolType is TPointerType) and
(Parser.CurrentToken = tkCaret) then
Result := TProd_QualifPointer
else
Result := nil;
end;
begin
FIsLValue := True;
FSymbolInfo := SymbolTable.FindSymbol(Parser.TokenString); // (maybe) again
if FSymbolInfo = nil then
Error(Format(sUndeclaredIdentifier, [Parser.TokenString]), ProductionLine,
ProductionCol);
if FSymbolInfo.SymbolClass = scField then
begin // prepare for interpretation
FWith := SolveWithStmt(Self, FSymbolInfo);
FFieldOffset := FSymbolInfo.FOffset;
T := FSymbolInfo.SymbolType;
FSymbolInfo := SymbolTable.DuplicateSymbolInfo(FWith);
FSymbolInfo.FOffset := FFieldOffset;
FSymbolInfo.FSymbolType := T;
end;
if FSymbolInfo.SymbolClass = scFunction then
begin
TProduction(FFuncCall) := Compile(TProd_FunctionCall);
FSymbolInfo := FFuncCall.SymbolInfo;
FIsLValue := False;
end
else
Parser.GetNextToken; // get variable id
FVarRef := FSymbolInfo; // store for interpretation
Qualif := QualifClass();
if Qualif <> nil then
begin
FQualified := True;
FSymbolInfo := SymbolTable.DuplicateSymbolInfo(FSymbolInfo);
repeat
Compile(Qualif);
Qualif := QualifClass();
until Qualif = nil;
end;
end;
procedure TProd_VarReference.Interpret;
var
I: Integer;
Aux: TSymbolInfo;
begin
if FWith <> nil then
begin
FVarRef.FOffset := FFieldOffset + Integer(FWith.Address);
FVarRef.FSymbolClass := scPointer;
end;
if FFuncCall <> nil then
begin
Aux := FSymbolInfo;
FSymbolInfo := FVarRef;
FFuncCall.Interpret;
FSymbolInfo := Aux;
end;
if FQualified then
begin // there is one or more qualifiers
// start with the variable reference (without qualifiers)
FSymbolInfo.Assign(FVarRef);
// Move(PChar(FVarRef)^, PChar(FSymbolInfo)^, TSymbolInfo.InstanceSize);
// transform address mode;
// the order of the next two statements is important
Pointer(FSymbolInfo.FOffset) := FSymbolInfo.Address;
FSymbolInfo.FSymbolClass := scPointer;
if FFuncCall <> nil then
I := 1 // skip function call production
else
I := 0;
while I <= ProductionCount - 1 do
begin
Productions[I].Interpret;
I := I + 1;
end;
end;
end;
{ TProd_QualifIndex }
procedure TProd_QualifIndex.Parse;
begin
Parser.GetNextToken; // '['
while True do
begin
FSymbolInfo := Compile(TProd_Expression).SymbolInfo;
CheckTypes(FSymbolInfo.SymbolType,
TArrayType(Parent.SymbolInfo.SymbolType).FIndexSymbol.SymbolType, tkAssign);
// update Parent.SymbolInfo
Parent.SymbolInfo.FSymbolType :=
TArrayType(Parent.SymbolInfo.SymbolType).FElemSymbol.SymbolType;
if Parser.CurrentToken <> tkComma then
Break;
Parser.GetNextToken; // comma
if not (Parent.SymbolInfo.SymbolType is TArrayType) then
Error(sArrayTypeRequired, Parser.TokenLine, Parser.TokenCol);
end;
GetTerminal(tkRBracket);
end;
procedure TProd_QualifIndex.Interpret;
var
I: Integer;
Value, MinIndex, MaxIndex: Integer;
Si: TSymbolInfo;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret;
Si := Productions[I].SymbolInfo;
// get index expression value
if Si.SymbolType.Size = 1 then
Value := Ord(PByte(Si.Address)^)
else
Value := PInteger(Si.Address)^;
// check indexing
MinIndex := TOrdinalType(
TArrayType(Parent.SymbolInfo.SymbolType).FIndexSymbol.SymbolType).MinValue;
MaxIndex := TOrdinalType(
TArrayType(Parent.SymbolInfo.SymbolType).FIndexSymbol.SymbolType).MaxValue;
if (Value < MinIndex) or (Value > MaxIndex) then
Error(sIndexOutOfRange, ProductionLine, ProductionCol);
// adjust according to index type minimum value
Value := Value -
TOrdinalType(
TArrayType(Parent.SymbolInfo.SymbolType).FIndexSymbol.SymbolType).MinValue;
// calculate offset according to element size
Value := Value *
TOrdinalType(
TArrayType(Parent.SymbolInfo.SymbolType).FElemSymbol.SymbolType).Size;
{ acrescenta área para o tamanho do array }
// Value := Value + TSymbolTable.SizeOfArraySize();
// adjust address
PByte(Parent.SymbolInfo.FOffset) := PByte(Parent.SymbolInfo.FOffset) + Value;
// update type
Parent.SymbolInfo.FSymbolType :=
TArrayType(Parent.SymbolInfo.SymbolType).FElemSymbol.SymbolType;
end;
end;
{ TProd_QualifField }
procedure TProd_QualifField.Parse;
var
T: TRecordType;
Evaluating: Boolean;
begin
Parser.GetNextToken; // '.'
TSymbolType(T) := Parent.SymbolInfo.SymbolType;
SymbolTable.AddScope(T.FScope);
// turn evaluating off, temporarily
Evaluating := csEvaluating in Compiler.State;
Compiler.State := Compiler.State - [csEvaluating];
// look for the field
Compiler.State := Compiler.State + [csFindInScope];
FSymbolInfo := SymbolTable.FindSymbol(Parser.TokenString);
Compiler.State := Compiler.State - [csFindInScope];
// turn evaluation on
if Evaluating then
Compiler.State := Compiler.State + [csEvaluating];
SymbolTable.RemoveScope;
if FSymbolInfo = nil then
Error(Format(sUndeclaredIdentifier, [Parser.TokenString]),
Parser.TokenLine, Parser.TokenCol);
Parser.GetNextToken; // field id
// update Parent.SymbolInfo
Parent.SymbolInfo.FSymbolType := FSymbolInfo.SymbolType;
end;
procedure TProd_QualifField.Interpret;
begin
// adjust address
PByte(Parent.SymbolInfo.FOffset) := PByte(Parent.SymbolInfo.FOffset) +
FSymbolInfo.FOffset;
// update type
Parent.SymbolInfo.FSymbolType := FSymbolInfo.SymbolType;
end;
{ TProd_QualifPointer }
procedure TProd_QualifPointer.Parse;
var
T: TPointerType;
begin
Parser.GetNextToken; // '^'
TSymbolType(T) := Parent.SymbolInfo.SymbolType;
// update Parent.SymbolInfo
Parent.SymbolInfo.FSymbolType := T.FBaseType;
// update address mode
Parent.SymbolInfo.FSymbolClass := scPointer; // redundant
end;
procedure TProd_QualifPointer.Interpret;
begin
// adjust address
Pointer(Parent.SymbolInfo.FOffset) := Pointer(Parent.SymbolInfo.Address^);
// update address mode
Parent.SymbolInfo.FSymbolClass := scPointer;
// update type
Parent.SymbolInfo.FSymbolType :=
TPointerType(Parent.SymbolInfo.FSymbolType).FBaseType;
end;
{ TCaseSelector }
constructor TCaseSelector.Create;
begin
inherited Create;
FLstMember := TList.Create;
FLstStmt := TList.Create;
end;
destructor TCaseSelector.Destroy;
begin
FLstMember.Free;
FLstStmt.Free;
inherited Destroy;
end;
procedure TCaseSelector.AddEntry(E: TProd_MemberGroup);
procedure CheckCollision;
var
I: Integer;
M: TProd_MemberGroup;
begin
for I := 0 to FLstMember.Count - 1 do
begin
M := TProd_MemberGroup(FLstMember[I]);
if M.InRange(E.InfSymbol) or
M.InRange(E.SupSymbol) then
raise Exception.Create('');
end;
end;
begin
CheckCollision;
FLstMember.Add(E);
end;
procedure TCaseSelector.SetStmt(Stmt: TProd_Stmt);
var
I, Count: Integer;
begin
Count := FLstMember.Count - FLstStmt.Count;
for I := 1 to Count do
FLstStmt.Add(Stmt);
end;
function TCaseSelector.TestCase(Si: TSymbolInfo): Boolean;
var
I: Integer;
M: TProd_MemberGroup;
begin
Result := False;
for I := 0 to FLstMember.Count - 1 do
begin
M := TProd_MemberGroup(FLstMember[I]);
if M.InRange(Si) then
begin
TProd_Stmt(FLstStmt[I]).Interpret;
Result := True;
end;
end;
end;
{ TPascalInterpreter }
constructor TPascalInterpreter.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFloatFormat := '0.0#########';
end;
destructor TPascalInterpreter.Destroy;
begin
TCompiler(C).Free;
inherited Destroy;
end;
function TPascalInterpreter.Evaluate(Expression: String): String;
begin
if C = nil then
Result := sEvaluationError
else
try
Result := TCompiler(C).Evaluate(Expression);
except
on E: Exception do
Result := E.Message;
end;
end;
procedure TPascalInterpreter.Run(Source: TStrings; ProgramFileName: String);
//var
// S: TMemoryStream;
begin
if C <> nil then
begin // get some compiler properties from the previous instance
FBreakpointLine := TCompiler(C).FBreakpointLine;
FBreakpointFileName := TCompiler(C).FBreakpointFileName;
FBreakOnNextStmt := csBreakOnNextStmt in TCompiler(C).State;
TCompiler(C).Free;
end;
C := TCompiler.Create;
if FGraphicImage <> nil then
TCompiler(C).Canvas := FGraphicImage.Canvas
else if FCanvas <> nil then
TCompiler(C).Canvas := FCanvas;
TCompiler(C).FloatFormat := FFloatFormat;
TCompiler(C).OnReadChar := FOnReadChar;
TCompiler(C).OnReadInteger := FOnReadInteger;
TCompiler(C).OnReadReal := FOnReadReal;
TCompiler(C).OnReadString := FOnReadString;
TCompiler(C).OnWrite := FOnWrite;
TCompiler(C).OnDebug := FOnDebug;
TCompiler(C).OnWaitFor := FOnWaitFor;
TCompiler(C).SetBreakpoint(FBreakpointFileName, FBreakpointLine);
FBreakpointLine := 0;
FBreakpointFileName := '';
if FBreakOnNextStmt then
begin
TCompiler(C).BreakOnNextStatement;
FBreakOnNextStmt := False;
end;
TCompiler(C).ProgramName := ProgramFileName;
// S := TMemoryStream.Create;
try
// Source.SaveToStream(S);
// S.Position := 0;
// TCompiler(C).Compile(S, TProd_Program);
TCompiler(C).Compile(Source.Text, TProd_Program);
TCompiler(C).Interpret;
finally
// S.Free;
TCompiler(C).FBreakpointLine := 0;
TCompiler(C).FBreakpointFileName := '';
TCompiler(C).State := TCompiler(C).State - [csBreakOnNextStmt];
// TCompiler(C).DestroyBitmaps;
// TCompiler(C).FBitmapList.Free;
// TCompiler(C).FBitmapList := nil;
// TCompiler(C).DestroyStreams;
// TCompiler(C).FStreamList.Free;
// TCompiler(C).FStreamList := nil;
end;
end;
procedure TPascalInterpreter.SetBreakpoint(FileName: String; LineNumber: Integer);
begin
if C <> nil then
TCompiler(C).SetBreakpoint(FileName, LineNumber)
else
begin
FBreakpointFileName := FileName;
FBreakpointLine := LineNumber;
end;
end;
procedure TPascalInterpreter.Stop;
begin
if C <> nil then
TCompiler(C).Stop;
end;
procedure TPascalInterpreter.BreakOnNextStatement;
begin
if C <> nil then
TCompiler(C).BreakOnNextStatement
else
FBreakOnNextStmt := True;
end;
procedure TPascalInterpreter.RegisterMouseXY(X, Y: Integer);
begin
if C <> nil then
TCompiler(C).RegisterMouseXY(X, Y);
end;
procedure TPascalInterpreter.RegisterLastEvent(Event: Integer; Sender: TObject);
begin
if C <> nil then
TCompiler(C).RegisterLastEvent(Event, Sender);
end;
procedure TPascalInterpreter.RegisterShiftState(Shift: TShiftState);
begin
if C <> nil then
TCompiler(C).RegisterShiftState(Shift);
end;
procedure TPascalInterpreter.RegisterKeyPressed(Key: Char);
begin
if C <> nil then
TCompiler(C).RegisterKeyPressed(Key);
end;
procedure TPascalInterpreter.RegisterKeyDown(Key: Word);
begin
if C <> nil then
TCompiler(C).RegisterKeyDown(Key);
end;
procedure TPascalInterpreter.RegisterKeyUp(Key: Word);
begin
if C <> nil then
TCompiler(C).RegisterKeyUp(Key);
end;
procedure TPascalInterpreter.TrataOnPaint(Sender: TObject);
begin
if C <> nil then
TCompiler(C).TrataOnPaint(Sender);
end;
{ Registration }
procedure Register;
begin
RegisterComponents('Decarva', [TPascalInterpreter]);
end;
procedure TPascalInterpreter.SetFloatFormat(const Value: String);
begin
FFloatFormat := Value;
if C <> nil then
TCompiler(C).FloatFormat := Value;
end;
procedure TPascalInterpreter.SetGraphicImage(const Value: TImage);
begin
FGraphicImage := Value;
if (C <> nil) and (Value <> nil) then
TCompiler(C).Canvas := Value.Canvas;
end;
procedure TPascalInterpreter.SetCanvas(const Value: TCanvas);
begin
FCanvas := Value;
if (C <> nil) and (Value <> nil) then
TCompiler(C).Canvas := Value;
end;
procedure TPascalInterpreter.SetOnDebug(const Value: TDebugEvent);
begin
FOnDebug := Value;
if C <> nil then
TCompiler(C).OnDebug := Value;
end;
procedure TPascalInterpreter.SetOnReadChar(const Value: TReadCharEvent);
begin
FOnReadChar := Value;
if C <> nil then
TCompiler(C).OnReadChar := Value;
end;
procedure TPascalInterpreter.SetOnReadInteger(
const Value: TReadIntegerEvent);
begin
FOnReadInteger := Value;
if C <> nil then
TCompiler(C).OnReadInteger := Value;
end;
procedure TPascalInterpreter.SetOnReadReal(const Value: TReadRealEvent);
begin
FOnReadReal := Value;
if C <> nil then
TCompiler(C).OnReadReal := Value;
end;
procedure TPascalInterpreter.SetOnReadString(
const Value: TReadStringEvent);
begin
FOnReadString := Value;
if C <> nil then
TCompiler(C).OnReadString := Value;
end;
procedure TPascalInterpreter.SetOnWrite(const Value: TWriteEvent);
begin
FOnWrite := Value;
if C <> nil then
TCompiler(C).OnWrite := Value;
end;
procedure TPascalInterpreter.SetOnWaitFor(const Value: TWaitForEvent);
begin
FOnWaitFor := Value;
if C <> nil then
TCompiler(C).OnWaitFor := Value;
end;
procedure TPascalInterpreter.SetProgramFile(const Value: String);
begin
FProgramFile := Value;
TCompiler(C).Parser.Name := FProgramFile;
end;
{ TProd_arqParaTxt }
procedure TProd_arqParaTxt.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // arqParaTxt
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // nome do arquivo
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeString);
end;
procedure TProd_arqParaTxt.Interpret;
var
Si: TSymbolInfo;
NomeArq, NomeArqRestrito, S: String;
ArqStm: TStringStream;
begin
Productions[0].Interpret; // nome do arquivo
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
NomeArq := PString(Si.Address)^;
NomeArqRestrito := ExpandeNomeArq(NomeArq);
// carrega o arquivo
ArqStm := TStringStream.Create;
try
ArqStm.LoadFromFile(NomeArqRestrito);
except
ArqStm := nil;
end;
if ArqStm = nil then
Error(sArquivoNaoEncontrado + ': ' + NomeArq + #13#10 + sVerifiqueNomeArq,
ProductionLine, ProductionCol);
// verifica o tamanho
if ArqStm.Size > MAX_TAM_ARQ then
Error(sTamanhoArqInvalido, ProductionLine, ProductionCol);
// trasfere o conteúdo para o texto que será o retorno da função arqParaTxt
S := ArqStm.DataString;
// S := FileStreamToString(ArqStm);
// S := AdjustLineBreaks(S, tlbsLF); // converte crlf para lf
PString(FSymbolInfo.Address)^ := S;
ArqStm.Free;
end;
{ TProd_txtParaArq }
procedure TProd_txtParaArq.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // txtParaArq
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // nome do arquivo
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
end;
procedure TProd_txtParaArq.Interpret;
var
Si: TSymbolInfo;
NomeArq, NomeArqRestrito, Txt: String;
ArqStm: TStringStream;
begin
Productions[0].Interpret; // nome do arquivo
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
NomeArq := PString(Si.Address)^;
NomeArqRestrito := ExpandeNomeArq(NomeArq);
Productions[1].Interpret; // texto
Si := Productions[1].SymbolInfo;
if Productions[1].ExecPromotion then
Si := Productions[1].Promoted;
Txt := PString(Si.Address)^;
// Txt := AdjustLineBreaks(Txt, tlbsCRLF); // converte lf para crlf
// abre o arquivo
try
ArqStm := TStringStream.Create(Txt);
except
ArqStm := nil;
end;
if ArqStm = nil then ///// mensagem de erro precisa ser revisada!!!
Error(sArquivoNaoEncontrado + ': ' + NomeArq + #13#10 + sVerifiqueNomeArq,
ProductionLine, ProductionCol);
// verifica o tamanho
if Length(Txt) > MAX_TAM_ARQ then
Error(sTamanhoTxtInvalido, ProductionLine, ProductionCol);
// grava o arquivo
try
ArqStm.SaveToFile(NomeArqRestrito);
except
Error(sErroGravandoArq + ': ' + NomeArq, ProductionLine, ProductionCol);
end;
ArqStm.Free;
end;
{ TProd_SetFontStyleStmt }
procedure TProd_SetFontStyleStmt.Interpret;
var
Si: TSymbolInfo;
Estilo: Integer;
Q: TQuadro;
begin
{ obtém o quadro }
Productions[0].Interpret;
Si := Productions[0].SymbolInfo;
Q := TQuadro(PInteger(Si.Address)^);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Productions[1].Interpret;
Si := Productions[1].SymbolInfo;
Estilo := PInteger(Si.Address)^;
{ desenha no quadro e no bmp }
Q.alt_estilo_fonte(IntParaEstiloFonte(Estilo));
end;
procedure TProd_SetFontStyleStmt.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // SetFontStyle
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // name
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
{ TProd_nova_imagem }
procedure TProd_nova_imagem.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Ps: PString;
Img: TImage;
JanelaMaeOk: Boolean;
Q: TQuadro;
JanelaMae: TWinControl;
Imagem: TQuadroImagem;
begin
for I := 0 to 4 do
begin
Productions[I].Interpret; // janela, x, y, largura, altura
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
Productions[5].Interpret; // texto
Si := Productions[5].SymbolInfo;
if Productions[5].ExecPromotion then
Si := Productions[5].Promoted;
Ps := PString(Si.Address);
// verifica se a janela é válida
JanelaMaeOk := (TObject(V[0]) is TQuadro);
if not JanelaMaeOk then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Q := TQuadro(V[0]);
JanelaMae := Q.obt_win_control();
if JanelaMae = nil then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
// verifica se ultrapassa limite de janelas
if Compiler.FTQuadroList.Count >= MAX_COMPONENTES then
Error(sLimiteComponentesAtingido, ProductionLine, ProductionCol);
// cria o TImage (imagem)
Img := TImage.Create(nil);
Img.Parent := JanelaMae;
Img.Stretch := True;
Img.SetBounds(V[1], V[2], V[3], V[4]);
// eventos
Img.OnClick := Compiler.TrataOnClickBotao;
// cria o TQuadroImagem
Imagem := TQuadroImagem.Cria(Img);
Imagem.crg_img(Ps^); // carrega a imagem
// inclui na lista de componentes
Compiler.FTQuadroList.Add(Imagem);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(Imagem);
end;
procedure TProd_nova_imagem.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // nova_imagem
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Janela
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // largura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // altura
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // texto
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
{ TProd_reg_evento }
procedure TProd_reg_evento.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // reg_evento
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // evento
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // substituto
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
procedure TProd_reg_evento.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..2] of Integer;
Q: TQuadro;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // quadro, evento, substituto
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ registra o evento substituto }
Q.reg_evento(V[1], V[2]);
end;
{ TProd_obt_txt_janela }
procedure TProd_obt_txt_janela.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // obt_txt_janela
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // Tela (TQuadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeString);
end;
procedure TProd_obt_txt_janela.Interpret;
var
Si: TSymbolInfo;
Q: TQuadro;
V: Integer;
begin
Productions[0].Interpret; // Tela (TQuadro)
Si := Productions[0].SymbolInfo;
V := PInteger(Si.Address)^;
{ obtém o quadro }
Q := TQuadro(V);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ obtém o texto }
PString(FSymbolInfo.Address)^ := Q.obt_txt_janela();
end;
{ TProd_copJanelaRet }
procedure TProd_copJanelaRet.Interpret;
var
Si: TSymbolInfo;
V: array [0..5] of Integer;
Jan, JanOrig: TQuadro;
I: Integer;
begin
for I := 0 to 5 do
begin
Productions[I].Interpret; // jan, x1, y1, x2, y2, janOrig
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
// verifica se as janelas são válidas
if not (TObject(V[0]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
if not (TObject(V[5]) is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
Jan := TQuadro(V[0]);
JanOrig := TQuadro(V[5]);
// copia JanOrig para Jan (via CopyRect)
Jan.cop_janela_ret(V[1], V[2], V[3], V[4], JanOrig);
end;
procedure TProd_copJanelaRet.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // cop_janela_ret
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // jan
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // janOrig
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
{ TProd_DsnRetSel }
procedure TProd_DsnRetSel.Interpret;
var
I: Integer;
Si: TSymbolInfo;
V: array [0..4] of Integer;
Q: TQuadro;
begin
for I := 0 to ProductionCount - 1 do
begin
Productions[I].Interpret; // todas as expressões inteiras
Si := Productions[I].SymbolInfo;
V[I] := PInteger(Si.Address)^;
end;
{ obtém o quadro }
Q := TQuadro(V[0]);
if not (Q is TQuadro) then
Error(sFrameTypeExpected, ProductionLine, ProductionCol);
{ desenha no quadro e no bmp }
Q.dsn_ret_sel(V[1], V[2], V[3], V[4]);
end;
procedure TProd_DsnRetSel.Parse;
var
E: TProduction;
begin
Parser.GetNextToken; // dsn_ret_sel
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // tela (Quadro)
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y1
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // x2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkComma);
E := Compile(TProd_Expression); // y2
if E.SymbolInfo.SymbolType <> Compiler.DeclTypeInteger then
Error(sIntExprExpected, E.ProductionLine, E.ProductionCol);
GetTerminal(tkRParen);
end;
{ TProd_novo_som }
procedure TProd_novo_som.Interpret;
var
Si: TSymbolInfo;
Ps: PString;
Som: TCtrlMediaPlayer;
begin
Productions[0].Interpret; // nome
Si := Productions[0].SymbolInfo;
if Productions[0].ExecPromotion then
Si := Productions[0].Promoted;
Ps := PString(Si.Address);
// verifica se ultrapassa limite de componentes
if Compiler.FTMediaPlayerList.Count >= MAX_MPLAYERS then
Error(sLimiteMediaPlayersAtingido, ProductionLine, ProductionCol);
// cria o TCtrlMediaPlayer
Som := TCtrlMediaPlayer.Cria(Ps^);
// eventos
// sem eventos
// inclui na lista de media players
Compiler.FTMediaPlayerList.Add(Som);
// salva o valor de retorno
PInteger(FSymbolInfo.Address)^ := Integer(Som);
end;
procedure TProd_novo_som.Parse;
var
E: TProduction;
T: TSymbolType;
begin
Parser.GetNextToken; // novo_som
GetTerminal(tkLParen);
E := Compile(TProd_Expression); // nome do som
T := CheckTypes(Compiler.DeclTypeString, E.SymbolInfo.SymbolType, tkAssign);
E.PromoteTo(T);
GetTerminal(tkRParen);
FSymbolInfo := SymbolTable.AllocSymbolInfo(scVar, Compiler.DeclTypeInteger);
end;
end.
|
unit caGenetic;
{$INCLUDE ca.inc}
{$DEFINE USE_POINTER_ARRAY}
interface
uses
// Standard Delphi units
Windows,
Classes,
SysUtils,
Math,
// ca units
caClasses,
caUtils,
caVector,
caLog,
caTypes,
caRandom;
const
cOneHundred = 100;
type
TcaPercentage = 0..cOneHundred;
TcaFitnessResolution = (frOneDecPlace, frTwoDecPlaces, frThreeDecPlaces, frFourDecPlaces);
PnnGeneArray = ^TcaGeneArray;
TcaGeneArray = array[0..0] of Double;
TcaOrganism = class;
TcaAddChildOrganismEvent = procedure(Sender: TObject; AChildOrganism: TcaOrganism; var AAccept: Boolean) of object;
TcaApplyConstraintsEvent = procedure(Sender: TObject; AOrganism: TcaOrganism) of object;
TcaEvaluateOrganismEvent = procedure(Sender: TObject; AOrganism: TcaOrganism; var AFitness: Double) of object;
//---------------------------------------------------------------------------
// TcaChromozome
//---------------------------------------------------------------------------
TcaChromozome = class(TObject)
private
{$IFDEF USE_POINTER_ARRAY}
FGenes: PnnGeneArray;
{$ELSE}
FGenes: TcaDoubleVector;
{$ENDIF}
FSize: Integer;
// Property methods
function GetGene(Index: Integer): Double;
function GetSize: Integer;
procedure SetGene(Index: Integer; const Value: Double);
procedure SetSize(const Value: Integer);
// Private methods
{$IFDEF USE_POINTER_ARRAY}
procedure FreeGenesArray;
{$ENDIF}
procedure ResizeGenesArray;
public
constructor Create;
destructor Destroy; override;
// Properties
property Genes[Index: Integer]: Double read GetGene write SetGene;
property Size: Integer read GetSize write SetSize;
end;
//---------------------------------------------------------------------------
// TcaOrganism
//---------------------------------------------------------------------------
TcaPopulation = class;
TcaOrganismGroup = class;
TcaOrganism = class(TObject)
private
// Private fields
FChromozome: TcaChromozome;
FDateOfBirth: Integer;
FOrganismGroup: TcaOrganismGroup;
FPopulation: TcaPopulation;
FParent1: TcaOrganism;
FParent2: TcaOrganism;
// Property fields
FEvalParam: Double;
FEvalResult: Double;
FFitness: Double;
// Property methods
function GetAsString: String;
function GetAverageGene: Double;
function GetChromozomeSize: Integer;
function GetEvalParam: Double;
function GetEvalResult: Double;
function GetFitness: Double;
function GetGene(Index: Integer): Double;
function GetOrganismGroup: TcaOrganismGroup;
procedure SetEvalParam(const Value: Double);
procedure SetEvalResult(const Value: Double);
procedure SetFitness(const Value: Double);
procedure SetGene(Index: Integer; const Value: Double);
procedure SetOrganismGroup(const Value: TcaOrganismGroup);
// Private methods
function HasParents: Boolean;
function IsClone: Boolean;
procedure CopyChromozomeFromOriginal;
procedure CopyStateFromOriginal;
procedure CreateChromozomeFromParents;
procedure CreateRandomChromozome;
public
// Public virtual methods
constructor Create(APopulation: TcaPopulation; AParent1: TcaOrganism = nil; AParent2: TcaOrganism = nil);
destructor Destroy; override;
// Public methods
function Clone: TcaOrganism;
procedure Initialize;
procedure Mutate;
procedure ProduceChildren(APartner: TcaOrganism);
// Properties
property AsString: String read GetAsString;
property AverageGene: Double read GetAverageGene;
property ChromozomeSize: Integer read GetChromozomeSize;
property EvalParam: Double read GetEvalParam write SetEvalParam;
property EvalResult: Double read GetEvalResult write SetEvalResult;
property Fitness: Double read GetFitness write SetFitness;
property Genes[Index: Integer]: Double read GetGene write SetGene;
property OrganismGroup: TcaOrganismGroup read GetOrganismGroup write SetOrganismGroup;
end;
//---------------------------------------------------------------------------
// TcaOrganismGroup
//---------------------------------------------------------------------------
TcaRankedGroups = class;
TcaOrganismGroup = class(TObject)
private
// Private fields
FList: TList;
// Property fields
FFitness: Integer;
FPopulation: TcaPopulation;
FRankedGroups: TcaRankedGroups;
FSortDirection: TcaSortDirection;
// Property methods
function GetCount: Integer;
function GetFitness: Integer;
function GetItem(Index: Integer): TcaOrganism;
function GetRankedGroups: TcaRankedGroups;
function GetSortDirection: TcaSortDirection;
procedure SetFitness(const Value: Integer);
procedure SetRankedGroups(const Value: TcaRankedGroups);
public
constructor Create(APopulation: TcaPopulation);
destructor Destroy; override;
// Public methods
function FitnessExists(AFitness: Double): Boolean;
function RandomChoice: TcaOrganism;
procedure Add(AOrganism: TcaOrganism);
procedure DeleteOrganism(AIndex: Integer);
procedure Sort(ASortDirection: TcaSortDirection);
// Log methods
procedure SendToLog(const AMsg: String; AClearLog: Boolean = False);
// Properties
property Count: Integer read GetCount;
property Fitness: Integer read GetFitness write SetFitness;
property Items[Index: Integer]: TcaOrganism read GetItem; default;
property RankedGroups: TcaRankedGroups read GetRankedGroups write SetRankedGroups;
property SortDirection: TcaSortDirection read GetSortDirection;
end;
//---------------------------------------------------------------------------
// TcaRankedGroups
//---------------------------------------------------------------------------
TcaRankedGroups = class(TObject)
private
// Private fields
FList: TList;
// Property fields
FPopulation: TcaPopulation;
FSortDirection: TcaSortDirection;
// Property methods
function GetCount: Integer;
function GetItem(Index: Integer): TcaOrganismGroup;
function GetSortDirection: TcaSortDirection;
public
constructor Create(APopulation: TcaPopulation);
destructor Destroy; override;
// Interface methods
function FindGroup(AFitness: Integer): TcaOrganismGroup;
function RandomChoice: TcaOrganismGroup;
procedure AddGroup(AGroup: TcaOrganismGroup);
procedure Clear;
procedure DeleteGroup(AIndex: Integer);
procedure Sort(ASortDirection: TcaSortDirection; ASortOrganisms: Boolean = False);
// Properties
property Count: Integer read GetCount;
property Items[Index: Integer]: TcaOrganismGroup read GetItem; default;
property SortDirection: TcaSortDirection read GetSortDirection;
end;
//---------------------------------------------------------------------------
// TcaPopulation
//---------------------------------------------------------------------------
TcaPopulation = class(TObject)
private
// Private fields
FMathUtils: IcaMathUtils;
FNextIndex: Int64;
FPopulationCount: Integer;
FRandom: IcaRandom;
// Property fields
FAllowDuplicates: Boolean;
FFitnessGroups: TcaRankedGroups;
FTolerance: Double;
// Parameter property fields
FAlienExtent: TcaPercentage;
FAlienRate: TcaPercentage;
FChildCount: Integer;
FChromozomeSize: Integer;
FCrossoverRate: TcaPercentage;
FFitnessResolution: TcaFitnessResolution;
FGeneMaxValue: Double;
FGeneMinValue: Double;
FGenerationCount: Integer;
FMaxGenerations: Integer;
FMaxPopulation: Integer;
FMutationExtent: TcaPercentage;
FMutationRate: TcaPercentage;
FRandSeed: Byte;
FTargetFitness: Integer;
// Event property fields
FOnAddChild: TcaAddChildOrganismEvent;
FOnApplyConstraints: TcaApplyConstraintsEvent;
FOnEvaluate: TcaEvaluateOrganismEvent;
FOnGenerationCompleted: TNotifyEvent;
FOnPopulationInitialized: TNotifyEvent;
// Logging property fields
FLogging: Boolean;
// Private methods
function InsertOrganism(AOrganism: TcaOrganism): Boolean;
procedure AddUnparentedOrganism;
procedure ApplyNaturalSelection;
procedure CreateNewGeneration;
procedure CreateRandomNumberGenerator;
procedure Evolve;
procedure EvolveOneGeneration;
procedure InitializePopulation;
procedure SetDefaultValues;
// Property methods
function GetAllowDuplicates: Boolean;
function GetBestOrganism: TcaOrganism;
function GetFitnessGroups: TcaRankedGroups;
function GetMathUtils: IcaMathUtils;
function GetTolerance: Double;
procedure SetAllowDuplicates(const Value: Boolean);
procedure SetTolerance(const Value: Double);
// Parameter property methods
function GetAlienExtent: TcaPercentage;
function GetAlienRate: TcaPercentage;
function GetChildCount: Integer;
function GetChromozomeSize: Integer;
function GetCrossoverRate: TcaPercentage;
function GetFitnessResolution: TcaFitnessResolution;
function GetGeneMaxValue: Double;
function GetGeneMinValue: Double;
function GetGenerationCount: Integer;
function GetMaxGenerations: Integer;
function GetMaxPopulation: Integer;
function GetMutationExtent: TcaPercentage;
function GetMutationRate: TcaPercentage;
function GetRandom: IcaRandom;
function GetRandSeed: Byte;
function GetTargetFitness: Integer;
procedure SetAlienExtent(const Value: TcaPercentage);
procedure SetAlienRate(const Value: TcaPercentage);
procedure SetChildCount(const Value: Integer);
procedure SetChromozomeSize(const Value: Integer);
procedure SetCrossoverRate(const Value: TcaPercentage);
procedure SetFitnessResolution(const Value: TcaFitnessResolution);
procedure SetGeneMaxValue(const Value: Double);
procedure SetGeneMinValue(const Value: Double);
procedure SetMaxGenerations(const Value: Integer);
procedure SetMaxPopulation(const Value: Integer);
procedure SetMutationExtent(const Value: TcaPercentage);
procedure SetMutationRate(const Value: TcaPercentage);
procedure SetRandSeed(const Value: Byte);
procedure SetTargetFitness(const Value: Integer);
// Event property methods
function GetOnAddChild: TcaAddChildOrganismEvent;
function GetOnApplyConstraints: TcaApplyConstraintsEvent;
function GetOnEvaluate: TcaEvaluateOrganismEvent;
function GetOnGenerationCompleted: TNotifyEvent;
function GetOnPopulationInitialized: TNotifyEvent;
procedure SetOnAddChild(const Value: TcaAddChildOrganismEvent);
procedure SetOnApplyConstraints(const Value: TcaApplyConstraintsEvent);
procedure SetOnEvaluate(const Value: TcaEvaluateOrganismEvent);
procedure SetOnGenerationCompleted(const Value: TNotifyEvent);
procedure SetOnPopulationInitialized(const Value: TNotifyEvent);
// Log property methods
function GetLogging: Boolean;
procedure SetLogging(const Value: Boolean);
protected
// Protected static methods
function Evaluate(AOrganism: TcaOrganism): Double;
procedure AddChild(AChildOrganism: TcaOrganism);
// Protected virtual methods
procedure DoAddChild(AChildOrganism: TcaOrganism; var AAccept: Boolean); virtual;
procedure DoApplyConstraints(AOrganism: TcaOrganism); virtual;
procedure DoEvaluate(AOrganism: TcaOrganism; var AFitness: Double); virtual;
procedure DoGenerationCompleted; virtual;
procedure DoPopulationInitialized; virtual;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
// Interface methods
function NextIndex: Integer;
procedure RebuildFitnessGroups;
procedure Run;
// Log methods
procedure LogWithGenerationCount;
procedure SendToLog(const AMsg: String; AClearLog: Boolean = False);
// Properties
property FitnessGroups: TcaRankedGroups read GetFitnessGroups;
property MathUtils: IcaMathUtils read GetMathUtils;
property Tolerance: Double read GetTolerance write SetTolerance;
// Parameter properties
property AlienExtent: TcaPercentage read GetAlienExtent write SetAlienExtent;
property AlienRate: TcaPercentage read GetAlienRate write SetAlienRate;
property AllowDuplicates: Boolean read GetAllowDuplicates write SetAllowDuplicates;
property BestOrganism: TcaOrganism read GetBestOrganism;
property ChildCount: Integer read GetChildCount write SetChildCount;
property ChromozomeSize: Integer read GetChromozomeSize write SetChromozomeSize;
property CrossoverRate: TcaPercentage read GetCrossoverRate write SetCrossoverRate;
property FitnessResolution: TcaFitnessResolution read GetFitnessResolution write SetFitnessResolution;
property GeneMaxValue: Double read GetGeneMaxValue write SetGeneMaxValue;
property GeneMinValue: Double read GetGeneMinValue write SetGeneMinValue;
property GenerationCount: Integer read GetGenerationCount;
property MaxGenerations: Integer read GetMaxGenerations write SetMaxGenerations;
property MaxPopulation: Integer read GetMaxPopulation write SetMaxPopulation;
property MutationExtent: TcaPercentage read GetMutationExtent write SetMutationExtent;
property MutationRate: TcaPercentage read GetMutationRate write SetMutationRate;
property Random: IcaRandom read GetRandom;
property RandSeed: Byte read GetRandSeed write SetRandSeed;
property TargetFitness: Integer read GetTargetFitness write SetTargetFitness;
// Logging options
property Logging: Boolean read GetLogging write SetLogging;
// Event properties
property OnAddChild: TcaAddChildOrganismEvent read GetOnAddChild write SetOnAddChild;
property OnApplyConstraints: TcaApplyConstraintsEvent read GetOnApplyConstraints write SetOnApplyConstraints;
property OnEvaluate: TcaEvaluateOrganismEvent read GetOnEvaluate write SetOnEvaluate;
property OnGenerationCompleted: TNotifyEvent read GetOnGenerationCompleted write SetOnGenerationCompleted;
property OnPopulationInitialized: TNotifyEvent read GetOnPopulationInitialized write SetOnPopulationInitialized;
end;
implementation
//---------------------------------------------------------------------------
// TcaChromozome
//---------------------------------------------------------------------------
constructor TcaChromozome.Create;
begin
inherited;
{$IFDEF USE_POINTER_ARRAY}
{$ELSE}
FGenes := TcaDoubleVector.Create;
{$ENDIF}
end;
destructor TcaChromozome.Destroy;
begin
{$IFDEF USE_POINTER_ARRAY}
FreeGenesArray;
{$ELSE}
FGenes.Free;
{$ENDIF}
inherited;
end;
// Private methods
{$IFDEF USE_POINTER_ARRAY}
procedure TcaChromozome.FreeGenesArray;
begin
if FGenes <> nil then FreeMem(FGenes);
end;
{$ENDIF}
procedure TcaChromozome.ResizeGenesArray;
begin
{$IFDEF USE_POINTER_ARRAY}
FreeGenesArray;
GetMem(FGenes, FSize * SizeOf(TcaGeneArray));
{$ELSE}
FGenes.Clear;
FGenes.GrowBy(FSize);
{$ENDIF}
end;
// Property methods
function TcaChromozome.GetGene(Index: Integer): Double;
begin
{$IFDEF USE_POINTER_ARRAY}
Result := FGenes^[Index];
{$ELSE}
Assert(Index < FGenes.Count);
Result := FGenes[Index];
{$ENDIF}
end;
function TcaChromozome.GetSize: Integer;
begin
Result := FSize;
end;
procedure TcaChromozome.SetGene(Index: Integer; const Value: Double);
begin
{$IFDEF USE_POINTER_ARRAY}
FGenes^[Index] := Value;
{$ELSE}
Assert(Index < FGenes.Count);
FGenes[Index] := Value;
{$ENDIF}
end;
procedure TcaChromozome.SetSize(const Value: Integer);
begin
if Value <> FSize then
begin
FSize := Value;
ResizeGenesArray;
end;
end;
//---------------------------------------------------------------------------
// TcaOrganism
//---------------------------------------------------------------------------
constructor TcaOrganism.Create(APopulation: TcaPopulation; AParent1: TcaOrganism = nil; AParent2: TcaOrganism = nil);
begin
inherited Create;
FChromozome := TcaChromozome.Create;
FPopulation := APopulation;
FParent1 := AParent1;
FParent2 := AParent2;
end;
destructor TcaOrganism.Destroy;
begin
FChromozome.Free;
inherited;
end;
// Public methods
function TcaOrganism.Clone: TcaOrganism;
begin
Result := TcaOrganism.Create(FPopulation, Self, Self);
Result.Initialize;
end;
procedure TcaOrganism.Initialize;
begin
FDateOfBirth := FPopulation.GenerationCount;
FChromozome.Size := FPopulation.ChromozomeSize;
if HasParents then
CreateChromozomeFromParents
else
begin
if IsClone then
begin
CopyChromozomeFromOriginal;
CopyStateFromOriginal;
end
else
CreateRandomChromozome;
end;
end;
procedure TcaOrganism.Mutate;
var
GeneIndex: Integer;
Index: Integer;
MutationCount: Integer;
Random: IcaRandom;
begin
Random := FPopulation.Random;
Random.LowerIntBound := 0;
Random.UpperIntBound := cOneHundred;
if FPopulation.MutationRate > Random.AsInteger then
begin
MutationCount := Round(FPopulation.ChromozomeSize * FPopulation.MutationExtent / cOneHundred);
for Index := 0 to Pred(MutationCount) do
begin
// Find random gene to mutate
Random.LowerIntBound := 0;
Random.UpperIntBound := FPopulation.ChromozomeSize - 1;
GeneIndex := Random.AsInteger;
// Put random value into selected gene
Random.LowerBound := FPopulation.GeneMinValue;
Random.UpperBound := FPopulation.GeneMaxValue;
FChromozome.Genes[GeneIndex] := Random.AsDouble;
end;
end;
end;
procedure TcaOrganism.ProduceChildren(APartner: TcaOrganism);
var
Child: TcaOrganism;
Index: Integer;
begin
for Index := 0 to Pred(FPopulation.ChildCount) do
begin
Child := TcaOrganism.Create(FPopulation, Self, APartner);
Child.Initialize;
Child.Mutate;
FPopulation.AddChild(Child);
end;
end;
// Private methods
function TcaOrganism.HasParents: Boolean;
begin
Result := (FParent1 <> nil) and (FParent2 <> nil) and (FParent1 <> FParent2);
end;
function TcaOrganism.IsClone: Boolean;
begin
Result := (FParent1 <> nil) and (FParent2 <> nil) and (FParent1 = FParent2);
end;
procedure TcaOrganism.CopyChromozomeFromOriginal;
var
GeneIndex: Integer;
begin
for GeneIndex := 0 to Pred(FChromozome.Size) do
SetGene(GeneIndex, FParent1.Genes[GeneIndex]);
end;
procedure TcaOrganism.CopyStateFromOriginal;
begin
FEvalParam := FParent1.EvalParam;
FEvalResult := FParent1.EvalResult;
FFitness := FParent1.Fitness;
end;
procedure TcaOrganism.CreateChromozomeFromParents;
var
Index: Integer;
Random: IcaRandom;
begin
Random := FPopulation.Random;
Random.LowerBound := 0;
Random.UpperBound := 1;
for Index := 0 to Pred(FPopulation.ChromozomeSize) do
begin
if Random.AsDouble < 0.5 then
FChromozome.Genes[Index] := FParent1.Genes[Index]
else
FChromozome.Genes[Index] := FParent2.Genes[Index];
end;
end;
procedure TcaOrganism.CreateRandomChromozome;
var
Index: Integer;
Random: IcaRandom;
begin
Random := FPopulation.Random;
Random.LowerBound := FPopulation.GeneMinValue;
Random.UpperBound := FPopulation.GeneMaxValue;
for Index := 0 to Pred(FPopulation.ChromozomeSize) do
FChromozome.Genes[Index] := Random.AsDouble;
end;
// Property methods
function TcaOrganism.GetAsString: String;
begin
Result := Format('(DOB: %d), (Fitness: %f), (Parent1: %d), (Parent1: %d)',
[FDateOfBirth, FFitness, Integer(FParent1), Integer(FParent2)]);
end;
function TcaOrganism.GetAverageGene: Double;
var
Index: Integer;
begin
Result := 0;
if FChromozome.Size > 0 then
begin
for Index := 0 to Pred(FChromozome.Size) do
Result := Result + FChromozome.Genes[Index];
Result := Result / FChromozome.Size;
end;
end;
function TcaOrganism.GetChromozomeSize: Integer;
begin
Result := FPopulation.ChromozomeSize;
end;
function TcaOrganism.GetEvalParam: Double;
begin
Result := FEvalParam;
end;
function TcaOrganism.GetEvalResult: Double;
begin
Result := FEvalResult;
end;
function TcaOrganism.GetFitness: Double;
begin
Result := FFitness;
end;
function TcaOrganism.GetGene(Index: Integer): Double;
begin
Result := FChromozome.Genes[Index];
end;
function TcaOrganism.GetOrganismGroup: TcaOrganismGroup;
begin
Result := FOrganismGroup;
end;
procedure TcaOrganism.SetEvalParam(const Value: Double);
begin
FEvalParam := Value;
end;
procedure TcaOrganism.SetEvalResult(const Value: Double);
begin
FEvalResult := Value;
end;
procedure TcaOrganism.SetFitness(const Value: Double);
begin
FFitness := Value;
end;
procedure TcaOrganism.SetGene(Index: Integer; const Value: Double);
begin
FChromozome.Genes[Index] := Value;
end;
procedure TcaOrganism.SetOrganismGroup(const Value: TcaOrganismGroup);
begin
FOrganismGroup := Value;
end;
//---------------------------------------------------------------------------
// TcaOrganismGroup
//---------------------------------------------------------------------------
constructor TcaOrganismGroup.Create(APopulation: TcaPopulation);
begin
inherited Create;
FPopulation := APopulation;
FList := TList.Create;
end;
destructor TcaOrganismGroup.Destroy;
var
Index: Integer;
begin
for Index := 0 to Pred(FList.Count) do
TObject(FList[Index]).Free;
FList.Free;
FPopulation := nil;
inherited;
end;
// Public methods
function TcaOrganismGroup.FitnessExists(AFitness: Double): Boolean;
var
Index: Integer;
Organism: TcaOrganism;
begin
// TODO: Use binary search
Result := False;
for Index := 0 to Pred(GetCount) do
begin
Organism := GetItem(Index);
if FPopulation.MathUtils.IsEq(Organism.Fitness, AFitness) then
begin
Result := True;
Break;
end;
end;
end;
function TcaOrganismGroup.RandomChoice: TcaOrganism;
var
Random: IcaRandom;
begin
Random := FPopulation.Random;
Random.LowerIntBound := 0;
Random.UpperIntBound := Pred(FList.Count);
Result := TcaOrganism(FList[Random.AsInteger]);
end;
procedure TcaOrganismGroup.Add(AOrganism: TcaOrganism);
begin
FList.Add(AOrganism);
AOrganism.OrganismGroup := Self;
end;
procedure TcaOrganismGroup.DeleteOrganism(AIndex: Integer);
begin
TObject(FList[AIndex]).Free;
FList.Delete(AIndex);
end;
function TcaOrganismGroup_Sort(Item1, Item2: Pointer): Integer;
var
Diff: Double;
Organism1: TcaOrganism;
Organism2: TcaOrganism;
OrganismGroup: TcaOrganismGroup;
begin
Diff := 0;
Organism1 := TcaOrganism(Item1);
Organism2 := TcaOrganism(Item2);
OrganismGroup := Organism1.OrganismGroup;
case OrganismGroup.SortDirection of
sdAscending: Diff := Organism1.Fitness - Organism2.Fitness;
sdDescending: Diff := Organism2.Fitness - Organism1.Fitness;
end;
if Diff < 0 then Result := -1 else if Diff > 0 then Result := 1 else Result := 0;
end;
procedure TcaOrganismGroup.Sort(ASortDirection: TcaSortDirection);
begin
FSortDirection := ASortDirection;
FList.Sort(TcaOrganismGroup_Sort);
end;
// Log methods
procedure TcaOrganismGroup.SendToLog(const AMsg: String; AClearLog: Boolean = False);
var
Index: Integer;
Organism: TcaOrganism;
begin
if AClearLog then Log.Clear;
if AMsg <> '' then Log.Send(AMsg);
for Index := 0 to Pred(GetCount) do
begin
Organism := GetItem(Index);
Log.Send('Organism', Index);
Log.Send('Fitness', Organism.Fitness);
end;
Log.Send(' ');
end;
// Property methods
function TcaOrganismGroup.GetCount: Integer;
begin
Result := FList.Count;
end;
function TcaOrganismGroup.GetFitness: Integer;
begin
Result := FFitness;
end;
function TcaOrganismGroup.GetItem(Index: Integer): TcaOrganism;
begin
Result := TcaOrganism(FList[Index]);
end;
function TcaOrganismGroup.GetRankedGroups: TcaRankedGroups;
begin
Result := FRankedGroups;
end;
function TcaOrganismGroup.GetSortDirection: TcaSortDirection;
begin
Result := FSortDirection;
end;
procedure TcaOrganismGroup.SetFitness(const Value: Integer);
begin
FFitness := Value;
end;
procedure TcaOrganismGroup.SetRankedGroups(const Value: TcaRankedGroups);
begin
FRankedGroups := Value;
end;
//---------------------------------------------------------------------------
// TcaRankedGroups
//---------------------------------------------------------------------------
constructor TcaRankedGroups.Create(APopulation: TcaPopulation);
begin
inherited Create;
FPopulation := APopulation;
FList := TList.Create;
end;
destructor TcaRankedGroups.Destroy;
var
Index: Integer;
begin
for Index := 0 to Pred(FList.Count) do
TObject(FList[Index]).Free;
FList.Free;
FPopulation := nil;
inherited;
end;
// Interface methods
function TcaRankedGroups.FindGroup(AFitness: Integer): TcaOrganismGroup;
var
ACompare: Integer;
AHigh: Integer;
AIndex: Integer;
ALow: Integer;
Item: TcaOrganismGroup;
begin
Sort(sdAscending);
Result := nil;
ALow := 0;
AHigh := Pred(FList.Count);
while ALow <= AHigh do
begin
AIndex := (ALow + AHigh) shr 1;
Item := TcaOrganismGroup(FList.List^[AIndex]);
ACompare := Item.Fitness - AFitness;
if ACompare < 0 then
ALow := AIndex + 1
else
begin
AHigh := AIndex - 1;
if ACompare = 0 then
begin
Result := Item;
ALow := AIndex;
end;
end;
end;
end;
function TcaRankedGroups.RandomChoice: TcaOrganismGroup;
var
Random: IcaRandom;
begin
Random := FPopulation.Random;
Random.LowerIntBound := 0;
Random.UpperIntBound := Pred(FList.Count);
Result := TcaOrganismGroup(FList[Random.AsInteger]);
end;
procedure TcaRankedGroups.AddGroup(AGroup: TcaOrganismGroup);
begin
AGroup.RankedGroups := Self;
FList.Add(AGroup);
end;
procedure TcaRankedGroups.Clear;
begin
while GetCount > 0 do
DeleteGroup(0);
end;
procedure TcaRankedGroups.DeleteGroup(AIndex: Integer);
begin
TObject(FList[AIndex]).Free;
FList.Delete(AIndex);
end;
function TcaRankedGroups_Sort(Item1, Item2: Pointer): Integer;
var
Group1: TcaOrganismGroup;
Group2: TcaOrganismGroup;
RankedGroups: TcaRankedGroups;
begin
Result := 0;
Group1 := TcaOrganismGroup(Item1);
Group2 := TcaOrganismGroup(Item2);
RankedGroups := Group1.RankedGroups;
case RankedGroups.SortDirection of
sdAscending: Result := Group1.Fitness - Group2.Fitness;
sdDescending: Result := Group2.Fitness - Group1.Fitness;
end;
end;
procedure TcaRankedGroups.Sort(ASortDirection: TcaSortDirection; ASortOrganisms: Boolean = False);
var
Group: TcaOrganismGroup;
GroupIndex: Integer;
begin
FSortDirection := ASortDirection;
FList.Sort(TcaRankedGroups_Sort);
if ASortOrganisms then
begin
for GroupIndex := 0 to Pred(GetCount) do
begin
Group := GetItem(GroupIndex);
Group.Sort(sdAscending);
end;
end;
end;
// Property methods
function TcaRankedGroups.GetCount: Integer;
begin
Result := FList.Count;
end;
function TcaRankedGroups.GetItem(Index: Integer): TcaOrganismGroup;
begin
Result := TcaOrganismGroup(FList[Index]);
end;
function TcaRankedGroups.GetSortDirection: TcaSortDirection;
begin
Result := FSortDirection;
end;
//---------------------------------------------------------------------------
// TcaPopulation
//---------------------------------------------------------------------------
// Public virtual methods
procedure TcaPopulation.AfterConstruction;
begin
inherited;
FLogging := False;
FMathUtils := Utils as IcaMathUtils;
SetDefaultValues;
CreateRandomNumberGenerator;
FFitnessGroups := TcaRankedGroups.Create(Self);
end;
procedure TcaPopulation.BeforeDestruction;
begin
inherited;
FFitnessGroups.Free;
end;
// Public methods
function TcaPopulation.NextIndex: Integer;
begin
Inc(FNextIndex);
Result := FNextIndex;
end;
procedure TcaPopulation.RebuildFitnessGroups;
var
SavedOrganisms: TList;
Group: TcaOrganismGroup;
GroupIndex: Integer;
Organism: TcaOrganism;
OrganismIndex: Integer;
begin
SavedOrganisms := TList.Create;
try
// Clone every organism and save in temp list
for GroupIndex := 0 to Pred(FFitnessGroups.Count) do
begin
Group := FFitnessGroups[GroupIndex];
for OrganismIndex := 0 to Pred(Group.Count) do
begin
Organism := Group[OrganismIndex];
SavedOrganisms.Add(Organism.Clone);
end;
end;
// Empty out everything
FitnessGroups.Clear;
FPopulationCount := 0;
// Insert saved organisms back into groups
for OrganismIndex := 0 to Pred(SavedOrganisms.Count) do
InsertOrganism(TcaOrganism(SavedOrganisms[OrganismIndex]));
finally
SavedOrganisms.Free;
end;
end;
procedure TcaPopulation.Run;
begin
FFitnessGroups.Clear;
FGenerationCount := 0;
FPopulationCount := 0;
InitializePopulation;
DoPopulationInitialized;
Evolve;
end;
// Log methods
procedure TcaPopulation.LogWithGenerationCount;
begin
if FLogging then SendToLog(Format('Generation %d', [FGenerationCount]), True);
end;
procedure TcaPopulation.SendToLog(const AMsg: String; AClearLog: Boolean = False);
var
Group: TcaOrganismGroup;
GroupIndex: Integer;
OrgIndex: Integer;
Organism: TcaOrganism;
begin
if AClearLog then Log.Clear;
Log.Freeze;
if AMsg <> '' then Log.Send(AMsg);
for GroupIndex := 0 to Pred(FFitnessGroups.Count) do
begin
Group := FFitnessGroups[GroupIndex];
Log.Send('Group.Fitness', Group.Fitness);
for OrgIndex := 0 to Pred(Group.Count) do
begin
Organism := Group[OrgIndex];
Log.Send(' Organism.Fitness', Organism.Fitness);
Log.Send(' Organism.EvalParam', Organism.EvalParam);
Log.Send(' Organism.EvalResult', Organism.EvalResult);
Log.Send(' ')
end;
end;
Log.Send(' ');
Log.Unfreeze;
end;
// Protected virtual methods
procedure TcaPopulation.DoAddChild(AChildOrganism: TcaOrganism; var AAccept: Boolean);
begin
if Assigned(FOnAddChild) then FOnAddChild(Self, AChildOrganism, AAccept);
end;
procedure TcaPopulation.DoApplyConstraints(AOrganism: TcaOrganism);
begin
if Assigned(FOnApplyConstraints) then FOnApplyConstraints(Self, AOrganism);
end;
procedure TcaPopulation.DoEvaluate(AOrganism: TcaOrganism; var AFitness: Double);
begin
if Assigned(FOnEvaluate) then FOnEvaluate(Self, AOrganism, AFitness);
end;
procedure TcaPopulation.DoGenerationCompleted;
begin
if Assigned(FOnGenerationCompleted) then FOnGenerationCompleted(Self);
end;
procedure TcaPopulation.DoPopulationInitialized;
begin
if Assigned(FOnPopulationInitialized) then FOnPopulationInitialized(Self);
end;
// Protected static methods
function TcaPopulation.Evaluate(AOrganism: TcaOrganism): Double;
begin
DoEvaluate(AOrganism, Result);
end;
procedure TcaPopulation.AddChild(AChildOrganism: TcaOrganism);
var
Accept: Boolean;
begin
Accept := True;
DoAddChild(AChildOrganism, Accept);
if Accept then InsertOrganism(AChildOrganism);
end;
// Private methods
procedure TcaPopulation.AddUnparentedOrganism;
var
Inserted: Boolean;
Organism: TcaOrganism;
begin
Inserted := False;
while not Inserted do
begin
Organism := TcaOrganism.Create(Self);
Organism.Initialize;
Inserted := InsertOrganism(Organism);
if not Inserted then Organism.Free;
end;
end;
function TcaPopulation.InsertOrganism(AOrganism: TcaOrganism): Boolean;
var
ActualFitness: Double;
Group: TcaOrganismGroup;
OKToAdd: Boolean;
RoundedFitness: Integer;
begin
Result := False;
// If fitness is already set, the organism is a clone and
// no evaluation is needed
if AOrganism.Fitness <> 0 then
ActualFitness := AOrganism.Fitness
else
begin
DoApplyConstraints(AOrganism);
ActualFitness := 0;
DoEvaluate(AOrganism, ActualFitness);
end;
if ActualFitness < MaxInt then
begin
AOrganism.Fitness := ActualFitness;
RoundedFitness := FMathUtils.Trunc(ActualFitness);
Group := FFitnessGroups.FindGroup(RoundedFitness);
if Group = nil then
begin
Group := TcaOrganismGroup.Create(Self);
Group.Fitness := RoundedFitness;
FFitnessGroups.AddGroup(Group);
end;
OKToAdd := True;
if not FAllowDuplicates then
OKToAdd := not Group.FitnessExists(AOrganism.Fitness);
if OKToAdd then
begin
Group.Add(AOrganism);
Inc(FPopulationCount);
end
else
begin
if Group.Count = 0 then
Group.Free;
end;
Result := OKToAdd;
end;
end;
procedure TcaPopulation.ApplyNaturalSelection;
var
WorstGroup: TcaOrganismGroup;
PopulationSurplus: Integer;
begin
FFitnessGroups.Sort(sdDescending);
while FPopulationCount > FMaxPopulation do
begin
WorstGroup := FFitnessGroups[0];
// Delete a whole group as long as some population will be left
if (FPopulationCount - WorstGroup.Count) >= FMaxPopulation then
begin
// Adjust overall population count
Dec(FPopulationCount, WorstGroup.Count);
FFitnessGroups.DeleteGroup(0);
end
else
begin
// If deleting the whole group would send the population negative, delete within group
PopulationSurplus := FPopulationCount - FMaxPopulation;
// Reduce the population count
Dec(FPopulationCount, PopulationSurplus);
// Sort organisms within group by Actual Fitness (IOW, *not* the rounded fitness)
WorstGroup.Sort(sdDescending);
// Delete the weakest organisms until population surplus is zero
while PopulationSurplus > 0 do
begin
WorstGroup.DeleteOrganism(0);
Dec(PopulationSurplus);
end;
end;
end;
end;
procedure TcaPopulation.CreateNewGeneration;
var
Group: TcaOrganismGroup;
GroupIndex: Integer;
Organism: TcaOrganism;
OrganismIndex: Integer;
Partner: TcaOrganism;
CrossoverRateTarget: TcaPercentage;
RandomGroup: TcaOrganismGroup;
begin
// For each organism group in the population
for GroupIndex := 0 to Pred(FFitnessGroups.Count) do
begin
Group := FFitnessGroups[GroupIndex];
for OrganismIndex := 0 to Pred(Group.Count) do
begin
// for each organism in each organism group
Organism := Group[OrganismIndex];
// CrossoverRate determines how often crossover occurs
FRandom.LowerIntBound := 0;
FRandom.UpperIntBound := cOneHundred;
CrossoverRateTarget := FRandom.AsInteger;
if FCrossoverRate > CrossoverRateTarget then
begin
RandomGroup := FFitnessGroups.RandomChoice;
Partner := RandomGroup.RandomChoice;
while Organism = Partner do
begin
RandomGroup := FFitnessGroups.RandomChoice;
Partner := RandomGroup.RandomChoice;
end;
Organism.ProduceChildren(Partner);
end;
end;
end;
end;
procedure TcaPopulation.CreateRandomNumberGenerator;
begin
FRandom := TcaAdditiveRandom.Create(FRandSeed);
end;
procedure TcaPopulation.Evolve;
var
Evolving: Boolean;
begin
FMathUtils.ZeroTolerance := FTolerance;
// Iterate over generations until a stopping condition is met
Evolving := True;
while Evolving do
begin
EvolveOneGeneration;
FFitnessGroups.Sort(sdAscending, True);
LogWithGenerationCount;
DoGenerationCompleted;
// If max gen count matters and generations reached
if (FMaxGenerations > 0) and (FGenerationCount = FMaxGenerations) then
Evolving := False;
// If fitness goal has been reached
if FFitnessGroups[0].Fitness <= FTargetFitness then
Evolving := False;
end;
FMathUtils.RestoreDefaultZeroTolerance;
end;
procedure TcaPopulation.EvolveOneGeneration;
var
AlienRateTarget: TcaPercentage;
AlienCount: Integer;
Index: Integer;
begin
Inc(FGenerationCount);
FRandom.LowerIntBound := 0;
FRandom.UpperIntBound := cOneHundred;
// AlienRate is the percentage of generations in which new
// organisms are randomly added to the population
AlienRateTarget := FRandom.AsInteger;
if FAlienRate > AlienRateTarget then
begin
// AlienExtent is the number of new random organisms relative to the current population count
AlienCount := FMathUtils.EquiRound(FPopulationCount * FAlienExtent / cOneHundred);
for Index := 0 to Pred(AlienCount) do
AddUnparentedOrganism;
end;
// Create new generation of organisms based on parents
CreateNewGeneration;
// Weed out poor organisms
ApplyNaturalSelection;
end;
procedure TcaPopulation.InitializePopulation;
var
Index: Integer;
begin
for Index := 0 to Pred(FMaxPopulation) do
AddUnparentedOrganism;
FFitnessGroups.Sort(sdAscending, True);
LogWithGenerationCount;
end;
procedure TcaPopulation.SetDefaultValues;
begin
FAlienExtent := 8;
FAlienRate := 10;
FChildCount := 1;
FChromozomeSize := 32;
FCrossoverRate := 32;
FGeneMaxValue := High(Integer);
FGeneMinValue := Low(Integer);
FMaxGenerations := 128;
FMaxPopulation := 256;
FMutationExtent := 1;
FMutationRate := 8;
FRandSeed := 1;
FTargetFitness := 0;
end;
// Property methods
function TcaPopulation.GetAllowDuplicates: Boolean;
begin
Result := FAllowDuplicates;
end;
function TcaPopulation.GetBestOrganism: TcaOrganism;
var
FitnessGroups: TcaRankedGroups;
BestGroup: TcaOrganismGroup;
begin
Result := nil;
FitnessGroups := GetFitnessGroups;
if FitnessGroups.Count > 0 then
begin
FitnessGroups.Sort(sdAscending);
BestGroup := FitnessGroups[0];
if BestGroup.Count > 0 then
Result := BestGroup[0];
end;
end;
function TcaPopulation.GetFitnessGroups: TcaRankedGroups;
begin
Result := FFitnessGroups;
end;
function TcaPopulation.GetMathUtils: IcaMathUtils;
begin
Result := FMathUtils;
end;
function TcaPopulation.GetTolerance: Double;
begin
Result := FTolerance;
end;
procedure TcaPopulation.SetAllowDuplicates(const Value: Boolean);
begin
FAllowDuplicates := Value;
end;
procedure TcaPopulation.SetTolerance(const Value: Double);
begin
FTolerance := Value;
end;
// Parameter property methods
function TcaPopulation.GetAlienExtent: TcaPercentage;
begin
Result := FAlienExtent;
end;
function TcaPopulation.GetAlienRate: TcaPercentage;
begin
Result := FAlienRate;
end;
function TcaPopulation.GetChildCount: Integer;
begin
Result := FChildCount;
end;
function TcaPopulation.GetChromozomeSize: Integer;
begin
Result := FChromozomeSize;
end;
function TcaPopulation.GetCrossoverRate: TcaPercentage;
begin
Result := FCrossoverRate;
end;
function TcaPopulation.GetFitnessResolution: TcaFitnessResolution;
begin
Result := FFitnessResolution;
end;
function TcaPopulation.GetGeneMaxValue: Double;
begin
Result := FGeneMaxValue;
end;
function TcaPopulation.GetGeneMinValue: Double;
begin
Result := FGeneMinValue;
end;
function TcaPopulation.GetGenerationCount: Integer;
begin
Result := FGenerationCount;
end;
function TcaPopulation.GetMaxGenerations: Integer;
begin
Result := FMaxGenerations;
end;
function TcaPopulation.GetMaxPopulation: Integer;
begin
Result := FMaxPopulation;
end;
function TcaPopulation.GetMutationExtent: TcaPercentage;
begin
Result := FMutationExtent;
end;
function TcaPopulation.GetMutationRate: TcaPercentage;
begin
Result := FMutationRate;
end;
function TcaPopulation.GetRandSeed: Byte;
begin
Result := FRandSeed;
end;
function TcaPopulation.GetRandom: IcaRandom;
begin
Result := FRandom;
end;
function TcaPopulation.GetTargetFitness: Integer;
begin
Result := FTargetFitness;
end;
procedure TcaPopulation.SetAlienExtent(const Value: TcaPercentage);
begin
FAlienExtent := Value;
end;
procedure TcaPopulation.SetAlienRate(const Value: TcaPercentage);
begin
FAlienRate := Value;
end;
procedure TcaPopulation.SetChildCount(const Value: Integer);
begin
FChildCount := Value;
end;
procedure TcaPopulation.SetChromozomeSize(const Value: Integer);
begin
FChromozomeSize := Value;
end;
procedure TcaPopulation.SetCrossoverRate(const Value: TcaPercentage);
begin
FCrossoverRate := Value;
end;
procedure TcaPopulation.SetFitnessResolution(const Value: TcaFitnessResolution);
begin
FFitnessResolution := Value;
end;
procedure TcaPopulation.SetGeneMaxValue(const Value: Double);
begin
FGeneMaxValue := Value;
end;
procedure TcaPopulation.SetGeneMinValue(const Value: Double);
begin
FGeneMinValue := Value;
end;
procedure TcaPopulation.SetMaxGenerations(const Value: Integer);
begin
FMaxGenerations := Value;
end;
procedure TcaPopulation.SetMaxPopulation(const Value: Integer);
begin
FMaxPopulation := Value;
end;
procedure TcaPopulation.SetMutationExtent(const Value: TcaPercentage);
begin
FMutationExtent := Value;
end;
procedure TcaPopulation.SetMutationRate(const Value: TcaPercentage);
begin
FMutationRate := Value;
end;
procedure TcaPopulation.SetRandSeed(const Value: Byte);
begin
FRandSeed := Value;
end;
procedure TcaPopulation.SetTargetFitness(const Value: Integer);
begin
FTargetFitness := Value;
end;
// Event property methods
function TcaPopulation.GetOnAddChild: TcaAddChildOrganismEvent;
begin
Result := FOnAddChild;
end;
function TcaPopulation.GetOnApplyConstraints: TcaApplyConstraintsEvent;
begin
Result := FOnApplyConstraints;
end;
function TcaPopulation.GetOnEvaluate: TcaEvaluateOrganismEvent;
begin
Result := FOnEvaluate;
end;
function TcaPopulation.GetOnGenerationCompleted: TNotifyEvent;
begin
Result := FOnGenerationCompleted;
end;
function TcaPopulation.GetOnPopulationInitialized: TNotifyEvent;
begin
Result := FOnPopulationInitialized;
end;
procedure TcaPopulation.SetOnAddChild(const Value: TcaAddChildOrganismEvent);
begin
FOnAddChild := Value;
end;
procedure TcaPopulation.SetOnApplyConstraints(const Value: TcaApplyConstraintsEvent);
begin
FOnApplyConstraints := Value;
end;
procedure TcaPopulation.SetOnEvaluate(const Value: TcaEvaluateOrganismEvent);
begin
FOnEvaluate := Value;
end;
procedure TcaPopulation.SetOnGenerationCompleted(const Value: TNotifyEvent);
begin
FOnGenerationCompleted := Value;
end;
procedure TcaPopulation.SetOnPopulationInitialized(const Value: TNotifyEvent);
begin
FOnPopulationInitialized := Value;
end;
// Log property methods
function TcaPopulation.GetLogging: Boolean;
begin
Result := FLogging;
end;
procedure TcaPopulation.SetLogging(const Value: Boolean);
begin
FLogging := Value;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: ufSplash
Author: n0mad
Version: 1.2.8.x
Creation: 01.03.2004
Purpose: Splash screen
History:
-----------------------------------------------------------------------------}
unit ufSplash;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Gauges, ExtCtrls, jpeg, StdCtrls, Menus, SLForms;
type
Tfm_Splash = class(TSLForm)
// FormRestorer: TFrmRstr;
pn_Splash: TPanel;
im_Splash: TImage;
gg_LoadProgress: TGauge;
lb_LoadTitle: TLabel;
lb_ProgramTitle: TLabel;
lb_ProgramTitleShadow: TLabel;
bv_LoadTitle: TBevel;
bv_ProgramTitle: TBevel;
mm_Load: TMemo;
tmr_Splash: TTimer;
bt_Exit: TButton;
procedure tmr_SplashTimer(Sender: TObject);
procedure bt_ExitClick(Sender: TObject);
procedure mm_LoadKeyPress(Sender: TObject; var Key: Char);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure FormInit;
procedure FormClean(SetBorder: boolean);
procedure AddToLog(Str: string; Upd, Line: Boolean);
procedure ScrollMemo(ToEnd: boolean);
procedure SetProgress(Progress: integer);
procedure SetTimer(TimeInterval: integer; EnableTimer: boolean);
end;
procedure AddToLog2(Str: string; Upd, Line: Boolean);
var
fm_Splash: Tfm_Splash;
implementation
uses
Bugger;
const
UnitName: string = 'ufSplash';
{$R *.DFM}
procedure AddToLog2(Str: string; Upd, Line: Boolean);
begin
if Assigned(fm_Splash) then
try
fm_Splash.AddToLog(Str, Upd, Line);
except
end;
end;
procedure Tfm_Splash.FormInit;
begin
tmr_Splash.Enabled := false;
tmr_Splash.OnTimer := tmr_SplashTimer;
if BorderStyle <> bsNone then
BorderStyle := bsNone;
if FormStyle <> fsNormal then
FormStyle := fsNormal; // fsStayOnTop;
// if Position <> poDesktopCenter then
// Position := poDesktopCenter;
if WindowState <> wsNormal then
WindowState := wsNormal;
gg_LoadProgress.MinValue := 0;
gg_LoadProgress.MaxValue := 100;
gg_LoadProgress.Progress := 0;
end;
procedure Tfm_Splash.FormClean(SetBorder: boolean);
begin
Caption := 'About...';
if SetBorder then
if BorderStyle <> bsDialog then
BorderStyle := bsDialog;
if FormStyle <> fsNormal then
FormStyle := fsNormal;
// if Position <> poDesktopCenter then
// Position := poDesktopCenter;
if WindowState <> wsNormal then
WindowState := wsNormal;
bv_LoadTitle.Visible := false;
lb_LoadTitle.Visible := false;
gg_LoadProgress.Visible := false;
mm_Load.Height := pn_Splash.ClientHeight - mm_Load.Top - 20;
mm_Load.ScrollBars := ssBoth;
end;
procedure Tfm_Splash.AddToLog(Str: string; Upd, Line: Boolean);
const
LineLen: integer = 80;
SpaceLen: integer = 3;
Divider: char = '~';
var
Str_Line: string;
Str_Space: string;
Div_Len: integer;
begin
if Line then
begin
Div_Len := (LineLen - Length(Str)) div 2 - SpaceLen;
if (Div_Len > 0) then
Str_Line := StringOfChar(Divider, Div_Len)
else
Str_Line := '';
if (LineLen div 2 > SpaceLen) then
Str_Space := StringOfChar(' ', SpaceLen)
else
Str_Space := ' ';
Str_Line := Str_Line + Str_Space + Str + Str_Space + Str_Line;
mm_Load.Lines.Add(Str_Line);
end
else
mm_Load.Lines.Add(Str);
if Upd then
Self.Update;
end;
procedure Tfm_Splash.ScrollMemo(ToEnd: boolean);
begin
mm_Load.SetFocus;
if ToEnd then
begin
mm_Load.SelStart := Length(mm_Load.Text) - 1;
mm_Load.SelLength := 0;
end
else
begin
mm_Load.SelStart := 0;
mm_Load.SelLength := 0;
end;
end;
procedure Tfm_Splash.SetProgress(Progress: integer);
begin
gg_LoadProgress.Progress := Progress;
end;
procedure Tfm_Splash.SetTimer(TimeInterval: integer; EnableTimer: boolean);
begin
if TimeInterval > 0 then
begin
tmr_Splash.Enabled := false;
tmr_Splash.Interval := TimeInterval;
end;
tmr_Splash.Enabled := EnableTimer;
end;
procedure Tfm_Splash.tmr_SplashTimer(Sender: TObject);
begin
if FindWindow('Tfm_Main', nil) <> 0 then
begin
SetTimer(15000, false);
Visible := false;
FormClean(false);
Close;
end;
end;
procedure Tfm_Splash.bt_ExitClick(Sender: TObject);
begin
if Self.Visible and (not gg_LoadProgress.Visible) then
tmr_SplashTimer(Self);
end;
procedure Tfm_Splash.mm_LoadKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #27 then
bt_ExitClick(Self);
end;
procedure Tfm_Splash.FormActivate(Sender: TObject);
begin
mm_Load.SetFocus;
end;
procedure Tfm_Splash.FormCreate(Sender: TObject);
begin
// FormRestorer := TFrmRstr.Create(fm_Splash);
// if Assigned(FormRestorer) and (FormRestorer is TFrmRstr) then
// FormRestorer.RegKey := 'Software\Home(R)\KinoDe\1.2.8';
end;
procedure Tfm_Splash.FormDestroy(Sender: TObject);
begin
// FormRestorer.Destroy;
end;
{$IFDEF DEBUG_Module_Start_Finish}
initialization
DEBUGMess(0, UnitName + '.Init');
{$ENDIF}
{$IFDEF DEBUG_Module_Start_Finish}
finalization
DEBUGMess(0, UnitName + '.Final');
{$ENDIF}
end.
|
program Cat;
uses SysUtils;
var
i: Integer;
s: String;
(* Longint is only 32 bits, and normal integer is only 16 bits. *)
(* It's necessary to use Longint because it's
equivalent to most languages' int *)
function Catalan (n : Longint) : Longint;
function Binom (n, k : Longint) : Longint;
function Factorial (n : Longint) : Int64;
begin
if (n < 2) then
Factorial := 1
else
Factorial := n * Factorial(n - 1);
end;
begin
(* The / character does real division.
To do integer division, use div *)
Binom := Factorial(n) div (Factorial(k) * Factorial(n - k));
end;
begin
n := Binom(2 * n, n) div (n + 1);
end;
begin
for i := 0 to 9 do
begin
s := format('Catalan number %d is %d', [i, Catalan(i)]);
writeln(s);
end;
end.
|
unit FC.Trade.TerminalDialog;
{$I Compiler.inc}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FC.Dialogs.DockedDialogAndAppWindow_B, ImgList, JvCaptionButton, JvComponentBase,
JvDockControlForm, ExtendControls,Application.Definitions,FC.Definitions, StdCtrls,ActnList,
FC.Trade.TerminalFrame, FC.Trade.ResultPage;
type
TfmTerminalDialog = class(TfmDockedDialogAndAppWindow_B,IStockBrokerEventHandler)
frmTerminal: TfrmTerminalFrame;
private
procedure OnViewTerminalExecute(aAction:TCustomAction);
procedure OnViewTerminalUpdate(aAction:TCustomAction);
//from IStockBrokerEventHandler
procedure OnStart (const aSender: IStockBroker);
procedure OnNewOrder (const aSender: IStockBroker; const aOrder: IStockOrder);
procedure OnModifyOrder(const aSender: IStockBroker; const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
procedure OnNewData (const aSender: IStockBroker; const aSymbol: string);
procedure OnNewMessage (const aSender: IStockBroker; const aMessage: IStockBrokerMessage); overload;
procedure OnNewMessage (const aSender: IStockBroker; const aOrder: IStockOrder; const aMessage: IStockBrokerMessage); overload;
protected
procedure OnFirstShow; override;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
function IsAppWindowByDefault: boolean; override;
end;
implementation
uses
SystemService,Application.Obj,FC.Factory,FC.Singletons,
FC.fmUIDataStorage, ufmForm_B;
{$R *.dfm}
type
TDialogStarter = class(Application.Obj.TActionTarget,IWorkspaceEventHandler)
private
public
//from IWorkspaceEventHandler
procedure OnEvent(const aEventName: string; aParams: TObject);
constructor Create;
destructor Destroy; override;
end;
{ TDialogStarter }
constructor TDialogStarter.Create;
begin
inherited;
Workspace.AddEventHandler(self);
//RegisterActionExecute(fmUIDataStorage.acToolsStockBrokerCenter,OnBrokerConnectionCenterExecute);
end;
destructor TDialogStarter.Destroy;
begin
inherited;
end;
procedure TDialogStarter.OnEvent(const aEventName: string; aParams: TObject);
begin
if AnsiSameText(aEventName,'MainFrameCreated') then
begin
TfmTerminalDialog.Create(nil);
end;
end;
{ TfmTerminalDialog }
constructor TfmTerminalDialog.Create(aOwner: TComponent);
begin
inherited;
StockBrokerConnectionRegistry.AddBrokerEventHandler(self);
ActionTarget.RegisterAction(fmUIDataStorage.acViewTradeTerminal,OnViewTerminalUpdate,OnViewTerminalExecute);
Workspace.MainFrame.AddActionTarget(self);
end;
destructor TfmTerminalDialog.Destroy;
begin
StockBrokerConnectionRegistry.RemoveBrokerEventHandler(self);
inherited;
end;
function TfmTerminalDialog.IsAppWindowByDefault: boolean;
begin
result:=false;
end;
procedure TfmTerminalDialog.OnFirstShow;
begin
inherited;
end;
procedure TfmTerminalDialog.OnModifyOrder(const aSender: IStockBroker; const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
begin
frmTerminal.OnModifyOrder(aOrder,aModifyEventArgs);
end;
procedure TfmTerminalDialog.OnNewData(const aSender: IStockBroker;
const aSymbol: string);
begin
end;
procedure TfmTerminalDialog.OnNewMessage(const aSender: IStockBroker;
const aMessage: IStockBrokerMessage);
begin
frmTerminal.OnNewMessage(aSender,aMessage);
end;
procedure TfmTerminalDialog.OnNewMessage(const aSender: IStockBroker;
const aOrder: IStockOrder; const aMessage: IStockBrokerMessage);
begin
frmTerminal.OnNewMessage(aSender,aOrder,aMessage);
end;
procedure TfmTerminalDialog.OnNewOrder(const aSender: IStockBroker;
const aOrder: IStockOrder);
begin
frmTerminal.OnNewOrder(aOrder);
end;
procedure TfmTerminalDialog.OnStart(const aSender: IStockBroker);
begin
frmTerminal.OnStart(aSender,nil);
end;
procedure TfmTerminalDialog.OnViewTerminalExecute(aAction: TCustomAction);
begin
Show;
end;
procedure TfmTerminalDialog.OnViewTerminalUpdate(aAction: TCustomAction);
begin
//aAction.Checked:=Self.Visible;
end;
initialization
TActionTargetRegistry.AddActionTarget(TDialogStarter.Create);
end.
|
unit NET.HelloWorld;
// CrossTalk v2.0.20
interface
uses
NET.mscorlib,
Atozed.CrossTalk.Middle, Atozed.CrossTalk.BaseObject, Atozed.CrossTalk.Streams, SysUtils, Windows;
type
Class1 = class;
{$SCOPEDENUMS ON}
Class1 = class(TCTBaseObject)
private
protected
class function CTFullTypeName: string; override;
public
constructor Create; overload; override;
function Test(
const aAInput: string): string; overload;
function ToString: string; reintroduce; overload;
function Equals(
const aObj: TCTObject): Boolean; reintroduce; overload;
function GetHashCode: Int32; reintroduce; overload;
function GetType: TypeNET; overload;
end;
implementation
uses
Atozed.CrossTalk.Right, Atozed.CrossTalk.Exception, Atozed.CrossTalk.Boxes;
{HelloWorld.Class1}
class function Class1.CTFullTypeName: string;
begin
Result := 'HelloWorld.Class1'
end;
constructor Class1.Create;
begin
TRight.ObjectCreate(Self, 'HelloWorld.Class1', 0)
end;
function Class1.Test(const aAInput: string): string;
var
xParams: TCTStreamWriter;
begin
xParams := TCTStreamWriter.Create;
xParams.Write(aAInput);
with TRight.MethodCall(Self, '', 'Test', 1948756573, xParams) do try
Result := Results.ReadString;
finally Free; end;
end;
function Class1.ToString: string;
begin
with TRight.MethodCall(Self, '', 'ToString', 0) do try
Result := Results.ReadString;
finally Free; end;
end;
function Class1.Equals(const aObj: TCTObject): Boolean;
var
xParams: TCTStreamWriter;
begin
xParams := TCTStreamWriter.Create;
xParams.Write(aObj);
with TRight.MethodCall(Self, '', 'Equals', 1923550299, xParams) do try
Result := Results.ReadBoolean;
finally Free; end;
end;
function Class1.GetHashCode: Int32;
begin
with TRight.MethodCall(Self, '', 'GetHashCode', 0) do try
Result := Results.ReadInt32;
finally Free; end;
end;
function Class1.GetType: TypeNET;
begin
with TRight.MethodCall(Self, '', 'GetType', 0) do try
Result := NET.mscorlib.TypeNET(Results.ReadObject);
finally Free; end;
end;
initialization
TRight.CheckVersion('NET.HelloWorld', '2.0.20');
TMiddle.AddAssembly('C:\projetos\Teste\crosstalk\obj\Debug\HelloWorld.dll');
end.
|
unit FinInfo;
interface
type
TFinInfo = class(TObject)
private
FCompanyId: string;
FCompanyName: string;
FMonthly: string;
FBalance: string;
public
property CompanyId: string read FCompanyId write FCompanyId;
property CompanyName: string read FCompanyName write FCompanyName;
property Monthly: string read FMonthly write FMonthly;
property Balance: string read FBalance write FBalance;
constructor Create(const companyId: string; const companyName, monthly, balance: string); overload;
end;
var
finInf: TFinInfo;
implementation
constructor TFinInfo.Create(const companyId: string;
const companyName: string; const monthly: string; const balance: string);
begin
FCompanyId := companyId;
FCompanyName := companyName;
FMonthly := monthly;
FBalance := balance;
end;
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is HashSet.pas. }
{ }
{ The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by }
{ Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) }
{ All rights reserved. }
{ }
{ Contributors: }
{ Florent Ouchet (outchy) }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $ }
{ Revision: $Rev:: 2376 $ }
{ Author: $Author:: obones $ }
{ }
{**************************************************************************************************}
unit JclHashSets;
{$I jcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
Classes,
{$IFDEF SUPPORTS_GENERICS}
{$IFDEF CLR}
System.Collections.Generic,
{$ENDIF CLR}
JclAlgorithms,
{$ENDIF SUPPORTS_GENERICS}
JclBase, JclAbstractContainers, JclContainerIntf, JclHashMaps, JclSynch;
{$I containers\JclContainerCommon.imp}
{$I containers\JclHashSets.imp}
{$I containers\JclHashSets.int}
type
{$IFDEF SUPPORTS_GENERICS}
TRefUnique = class;
TRefUnique = class(TEquatable<TRefUnique>)
end;
{$ELSE ~SUPPORTS_GENERICS}
TRefUnique = TObject;
{$ENDIF ~SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclIntfHashSet,TJclIntfAbstractContainer,IJclIntfCollection,IJclIntfSet,IJclIntfMap,IJclIntfIterator, IJclIntfEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,
constructor Create(ACapacity: Integer); overload;,const ,AInterface,IInterface)*)
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclAnsiStrHashSet,TJclAnsiStrAbstractCollection,IJclAnsiStrCollection,IJclAnsiStrSet,IJclAnsiStrMap,IJclAnsiStrIterator, IJclStrContainer\, IJclAnsiStrContainer\, IJclAnsiStrEqualityComparer\,,,
{ IJclStrContainer }
function GetCaseSensitive: Boolean; override;
procedure SetCaseSensitive(Value: Boolean); override;
{ IJclAnsiStrContainer }
function GetEncoding: TJclAnsiStrEncoding; override;
procedure SetEncoding(Value: TJclAnsiStrEncoding); override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;,, override;,
constructor Create(ACapacity: Integer); overload;,const ,AString,AnsiString)*)
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclWideStrHashSet,TJclWideStrAbstractCollection,IJclWideStrCollection,IJclWideStrSet,IJclWideStrMap,IJclWideStrIterator, IJclStrContainer\, IJclWideStrContainer\, IJclWideStrEqualityComparer\,,,
{ IJclStrContainer }
function GetCaseSensitive: Boolean; override;
procedure SetCaseSensitive(Value: Boolean); override;
{ IJclWideStrContainer }
function GetEncoding: TJclWideStrEncoding; override;
procedure SetEncoding(Value: TJclWideStrEncoding); override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;,, override;,
constructor Create(ACapacity: Integer); overload;,const ,AString,WideString)*)
{$IFDEF CONTAINER_ANSISTR}
TJclStrHashSet = TJclAnsiStrHashSet;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TJclStrHashSet = TJclWideStrHashSet;
{$ENDIF CONTAINER_WIDESTR}
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclSingleHashSet,TJclSingleAbstractContainer,IJclSingleCollection,IJclSingleSet,IJclSingleMap,IJclSingleIterator, IJclSingleContainer\, IJclSingleEqualityComparer\,,,
{ IJclSingleContainer }
function GetPrecision: Single; override;
procedure SetPrecision(const Value: Single); override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,
constructor Create(ACapacity: Integer); overload;,const ,AValue,Single)*)
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclDoubleHashSet,TJclDoubleAbstractContainer,IJclDoubleCollection,IJclDoubleSet,IJclDoubleMap,IJclDoubleIterator, IJclDoubleContainer\, IJclDoubleEqualityComparer\,,,
{ IJclDoubleContainer }
function GetPrecision: Double; override;
procedure SetPrecision(const Value: Double); override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,
constructor Create(ACapacity: Integer); overload;,const ,AValue,Double)*)
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclExtendedHashSet,TJclExtendedAbstractContainer,IJclExtendedCollection,IJclExtendedSet,IJclExtendedMap,IJclExtendedIterator, IJclExtendedContainer\, IJclExtendedEqualityComparer\,,,
{ IJclExtendedContainer }
function GetPrecision: Extended; override;
procedure SetPrecision(const Value: Extended); override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,
constructor Create(ACapacity: Integer); overload;,const ,AValue,Extended)*)
{$IFDEF MATH_EXTENDED_PRECISION}
TJclFloatHashSet = TJclExtendedHashSet;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TJclFloatHashSet = TJclDoubleHashSet;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
TJclFloatHashSet = TJclSingleHashSet;
{$ENDIF MATH_SINGLE_PRECISION}
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclIntegerHashSet,TJclIntegerAbstractContainer,IJclIntegerCollection,IJclIntegerSet,IJclIntegerMap,IJclIntegerIterator, IJclIntegerEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,
constructor Create(ACapacity: Integer); overload;,,AValue,Integer)*)
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclCardinalHashSet,TJclCardinalAbstractContainer,IJclCardinalCollection,IJclCardinalSet,IJclCardinalMap,IJclCardinalIterator, IJclCardinalEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,
constructor Create(ACapacity: Integer); overload;,,AValue,Cardinal)*)
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclInt64HashSet,TJclInt64AbstractContainer,IJclInt64Collection,IJclInt64Set,IJclInt64Map,IJclInt64Iterator, IJclInt64EqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,
constructor Create(ACapacity: Integer); overload;,const ,AValue,Int64)*)
{$IFNDEF CLR}
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclPtrHashSet,TJclPtrAbstractContainer,IJclPtrCollection,IJclPtrSet,IJclPtrMap,IJclPtrIterator, IJclPtrEqualityComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,
constructor Create(ACapacity: Integer); overload;,,AValue,Pointer)*)
{$ENDIF ~CLR}
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclHashSet,TJclAbstractContainer,IJclCollection,IJclSet,IJclMap,IJclIterator, IJclObjectOwner\, IJclEqualityComparer\,,,
{ IJclObjectOwner }
function FreeObject(var AObject: TObject): TObject; override;
function GetOwnsObjects: Boolean; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,
constructor Create(ACapacity: Integer; AOwnsObjects: Boolean); overload;,,AObject,TObject)*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO JCLHASHSETINT(TJclHashSet<T>,TJclAbstractContainer<T>,IJclCollection<T>,IJclSet<T>,IJclMap<T\, TRefUnique>,IJclIterator<T>, IJclItemOwner<T>\, IJclEqualityComparer<T>\,,,
{ IJclItemOwner<T> }
function FreeItem(var AItem: T): T; override;
function GetOwnsItems: Boolean; override;,,,,const ,AItem,T)*)
// E = External helper to compare items for equality
TJclHashSetE<T> = class(TJclHashSet<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclContainer, IJclCollection<T>, IJclSet<T>,
IJclItemOwner<T>, IJclEqualityComparer<T>)
private
FEqualityComparer: IEqualityComparer<T>;
protected
procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function ItemsEqual(const A, B: T): Boolean; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AEqualityComparer: IEqualityComparer<T>; const AMap: IJclMap<T, TRefUnique>); overload;
constructor Create(const AEqualityComparer: IEqualityComparer<T>; const AComparer: IComparer<T>;
ACapacity: Integer; AOwnsItems: Boolean); overload;
property EqualityComparer: IEqualityComparer<T> read FEqualityComparer write FEqualityComparer;
end;
// F = Function to compare items for equality
TJclHashSetF<T> = class(TJclHashSet<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclContainer, IJclCollection<T>, IJclSet<T>,
IJclItemOwner<T>, IJclEqualityComparer<T>)
protected
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AEqualityCompare: TEqualityCompare<T>; const AMap: IJclMap<T, TRefUnique>); overload;
constructor Create(const AEqualityCompare: TEqualityCompare<T>; const AHash: THashConvert<T>; const ACompare: TCompare<T>;
ACapacity: Integer; AOwnsItems: Boolean); overload;
end;
// I = Items can compare themselves to an other
TJclHashSetI<T: IEquatable<T>, IComparable<T>, IHashable> = class(TJclHashSet<T>,
{$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE} IJclIntfCloneable, IJclCloneable, IJclPackable,
IJclContainer, IJclCollection<T>, IJclSet<T>, IJclItemOwner<T>, IJclEqualityComparer<T>)
protected
function CreateEmptyContainer: TJclAbstractContainerBase; override;
function ItemsEqual(const A, B: T): Boolean; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AMap: IJclMap<T, TRefUnique>); overload;
constructor Create(ACapacity: Integer; AOwnsItems: Boolean); overload;
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclHashSets.pas $';
Revision: '$Revision: 2376 $';
Date: '$Date: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
var
GlobalRefUnique: TRefUnique = nil;
function RefUnique: TRefUnique;
begin
// We keep the reference till program end. A unique memory address is not
// possible under a garbage collector.
if GlobalRefUnique = nil then
GlobalRefUnique := TRefUnique.Create;
Result := GlobalRefUnique;
end;
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclIntfHashSet.Create(ACapacity: Integer);
begin
Create(TJclIntfHashMap.Create(ACapacity, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfHashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfHashSet.Create(GetCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL}
{$JPPDEFINEMACRO SETTERADDITIONAL}
{$JPPDEFINEMACRO FREEITEM}
{$JPPDEFINEMACRO GETOWNSITEMS}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclIntfHashSet,IJclIntfMap,IJclIntfCollection,IJclIntfIterator,,const ,AInterface,IInterface)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclAnsiStrHashSet.Create(ACapacity: Integer);
begin
Create(TJclAnsiStrHashMap.Create(ACapacity, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrHashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrHashSet.Create(GetCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL
function TJclAnsiStrHashSet.GetCaseSensitive: Boolean;
begin
Result := FMap.GetCaseSensitive;
end;
function TJclAnsiStrHashSet.GetEncoding: TJclAnsiStrEncoding;
begin
Result := FMap.GetEncoding;
end;
}
{$JPPDEFINEMACRO SETTERADDITIONAL
procedure TJclAnsiStrHashSet.SetCaseSensitive(Value: Boolean);
begin
FMap.SetCaseSensitive(Value);
end;
procedure TJclAnsiStrHashSet.SetEncoding(Value: TJclAnsiStrEncoding);
begin
FMap.SetEncoding(Value);
end;
}
{$JPPDEFINEMACRO FREEITEM}
{$JPPDEFINEMACRO GETOWNSITEMS}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclAnsiStrHashSet,IJclAnsiStrMap,IJclAnsiStrCollection,IJclAnsiStrIterator,,const ,AString,AnsiString)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclWideStrHashSet.Create(ACapacity: Integer);
begin
Create(TJclWideStrHashMap.Create(ACapacity, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrHashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrHashSet.Create(GetCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL
function TJclWideStrHashSet.GetCaseSensitive: Boolean;
begin
Result := FMap.GetCaseSensitive;
end;
function TJclWideStrHashSet.GetEncoding: TJclWideStrEncoding;
begin
Result := FMap.GetEncoding;
end;
}
{$JPPDEFINEMACRO SETTERADDITIONAL
procedure TJclWideStrHashSet.SetCaseSensitive(Value: Boolean);
begin
FMap.SetCaseSensitive(Value);
end;
procedure TJclWideStrHashSet.SetEncoding(Value: TJclWideStrEncoding);
begin
FMap.SetEncoding(Value);
end;
}
{$JPPDEFINEMACRO FREEITEM}
{$JPPDEFINEMACRO GETOWNSITEMS}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclWideStrHashSet,IJclWideStrMap,IJclWideStrCollection,IJclWideStrIterator,,const ,AString,WideString)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclSingleHashSet.Create(ACapacity: Integer);
begin
Create(TJclSingleHashMap.Create(ACapacity, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleHashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleHashSet.Create(GetCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL
function TJclSingleHashSet.GetPrecision: Single;
begin
Result := FMap.GetPrecision;
end;
}
{$JPPDEFINEMACRO SETTERADDITIONAL
procedure TJclSingleHashSet.SetPrecision(const Value: Single);
begin
FMap.SetPrecision(Value);
end;
}
{$JPPDEFINEMACRO FREEITEM}
{$JPPDEFINEMACRO GETOWNSITEMS}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclSingleHashSet,IJclSingleMap,IJclSingleCollection,IJclSingleIterator,,const ,AValue,Single)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclDoubleHashSet.Create(ACapacity: Integer);
begin
Create(TJclDoubleHashMap.Create(ACapacity, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleHashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleHashSet.Create(GetCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL
function TJclDoubleHashSet.GetPrecision: Double;
begin
Result := FMap.GetPrecision;
end;
}
{$JPPDEFINEMACRO SETTERADDITIONAL
procedure TJclDoubleHashSet.SetPrecision(const Value: Double);
begin
FMap.SetPrecision(Value);
end;
}
{$JPPDEFINEMACRO FREEITEM}
{$JPPDEFINEMACRO GETOWNSITEMS}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclDoubleHashSet,IJclDoubleMap,IJclDoubleCollection,IJclDoubleIterator,,const ,AValue,Double)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclExtendedHashSet.Create(ACapacity: Integer);
begin
Create(TJclExtendedHashMap.Create(ACapacity, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedHashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedHashSet.Create(GetCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL
function TJclExtendedHashSet.GetPrecision: Extended;
begin
Result := FMap.GetPrecision;
end;
}
{$JPPDEFINEMACRO SETTERADDITIONAL
procedure TJclExtendedHashSet.SetPrecision(const Value: Extended);
begin
FMap.SetPrecision(Value);
end;
}
{$JPPDEFINEMACRO FREEITEM}
{$JPPDEFINEMACRO GETOWNSITEMS}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclExtendedHashSet,IJclExtendedMap,IJclExtendedCollection,IJclExtendedIterator,,const ,AValue,Extended)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclIntegerHashSet.Create(ACapacity: Integer);
begin
Create(TJclIntegerHashMap.Create(ACapacity, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerHashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerHashSet.Create(GetCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL}
{$JPPDEFINEMACRO SETTERADDITIONAL}
{$JPPDEFINEMACRO FREEITEM}
{$JPPDEFINEMACRO GETOWNSITEMS}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclIntegerHashSet,IJclIntegerMap,IJclIntegerCollection,IJclIntegerIterator,,,AValue,Integer)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclCardinalHashSet.Create(ACapacity: Integer);
begin
Create(TJclCardinalHashMap.Create(ACapacity, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalHashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalHashSet.Create(GetCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL}
{$JPPDEFINEMACRO SETTERADDITIONAL}
{$JPPDEFINEMACRO FREEITEM}
{$JPPDEFINEMACRO GETOWNSITEMS}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclCardinalHashSet,IJclCardinalMap,IJclCardinalCollection,IJclCardinalIterator,,,AValue,Cardinal)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclInt64HashSet.Create(ACapacity: Integer);
begin
Create(TJclInt64HashMap.Create(ACapacity, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64HashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64HashSet.Create(GetCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL}
{$JPPDEFINEMACRO SETTERADDITIONAL}
{$JPPDEFINEMACRO FREEITEM}
{$JPPDEFINEMACRO GETOWNSITEMS}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclInt64HashSet,IJclInt64Map,IJclInt64Collection,IJclInt64Iterator,,const ,AValue,Int64)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$IFNDEF CLR}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclPtrHashSet.Create(ACapacity: Integer);
begin
Create(TJclPtrHashMap.Create(ACapacity, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrHashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrHashSet.Create(GetCapacity);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL}
{$JPPDEFINEMACRO SETTERADDITIONAL}
{$JPPDEFINEMACRO FREEITEM}
{$JPPDEFINEMACRO GETOWNSITEMS}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclPtrHashSet,IJclPtrMap,IJclPtrCollection,IJclPtrIterator,,,AValue,Pointer)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$ENDIF ~CLR}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL
constructor TJclHashSet.Create(ACapacity: Integer; AOwnsObjects: Boolean);
begin
Create(TJclHashMap.Create(ACapacity, AOwnsObjects, False));
end;
}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclHashSet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclHashSet.Create(GetCapacity, False);
AssignPropertiesTo(Result);
end;
}
{$JPPDEFINEMACRO GETTERADDITIONAL}
{$JPPDEFINEMACRO SETTERADDITIONAL}
{$JPPDEFINEMACRO FREEITEM
function TJclHashSet.FreeObject(var AObject: TObject): TObject;
begin
Result := (FMap as IJclKeyOwner).FreeKey(AObject);
end;
}
{$JPPDEFINEMACRO GETOWNSITEMS
function TJclHashSet.GetOwnsObjects: Boolean;
begin
Result := (FMap as IJclKeyOwner).GetOwnsKeys;
end;
}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclHashSet,IJclMap,IJclCollection,IJclIterator,False,,AObject,TObject)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
{$IFDEF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CONSTRUCTORADDITIONAL}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO GETTERADDITIONAL}
{$JPPDEFINEMACRO SETTERADDITIONAL}
{$JPPDEFINEMACRO FREEITEM
function TJclHashSet<T>.FreeItem(var AItem: T): T;
begin
Result := (FMap as IJclPairOwner<T, TRefUnique>).FreeKey(AItem);
end;
}
{$JPPDEFINEMACRO GETOWNSITEMS
function TJclHashSet<T>.GetOwnsItems: Boolean;
begin
Result := (FMap as IJclPairOwner<T, TRefUnique>).GetOwnsKeys;
end;
}
(*$JPPEXPANDMACRO JCLHASHSETIMP(TJclHashSet<T>,IJclMap<T\, TRefUnique>,IJclCollection<T>,IJclIterator<T>,False,const ,AItem,T)*)
{$JPPUNDEFMACRO CONSTRUCTORADDITIONAL}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPUNDEFMACRO ITEMSEQUAL(ItemA,ItemB)}
{$JPPUNDEFMACRO GETTERADDITIONAL}
{$JPPUNDEFMACRO SETTERADDITIONAL}
{$JPPUNDEFMACRO FREEITEM}
{$JPPUNDEFMACRO GETOWNSITEMS}
//=== { TJclHashSetE<T> } ====================================================
constructor TJclHashSetE<T>.Create(const AEqualityComparer: IEqualityComparer<T>; const AMap: IJclMap<T, TRefUnique>);
begin
inherited Create(AMap);
FEqualityComparer := AEqualityComparer;
end;
constructor TJclHashSetE<T>.Create(const AEqualityComparer: IEqualityComparer<T>; const AComparer: IComparer<T>;
ACapacity: Integer; AOwnsItems: Boolean);
begin
Create(AEqualityComparer, TJclHashMapE<T, TRefUnique>.Create(AEqualityComparer, RefUnique, AComparer, ACapacity, AOwnsItems, False));
end;
procedure TJclHashSetE<T>.AssignPropertiesTo(Dest: TJclAbstractContainerBase);
begin
inherited AssignPropertiesTo(Dest);
if Dest is TJclHashSetE<T> then
TJclHashSetE<T>(Dest).FEqualityComparer := FEqualityComparer;
end;
function TJclHashSetE<T>.CreateEmptyContainer: TJclAbstractContainerBase;
var
AMap: IJclMap<T, TRefUnique>;
begin
AMap := (FMap as IJclCloneable).Clone as IJclMap<T, TRefUnique>;
AMap.Clear;
Result := TJclHashSetE<T>.Create(FEqualityComparer, AMap);
AssignPropertiesTo(Result);
end;
function TJclHashSetE<T>.ItemsEqual(const A, B: T): Boolean;
begin
if EqualityComparer <> nil then
Result := EqualityComparer.Equals(A, B)
else
Result := inherited ItemsEqual(A, B);
end;
//=== { TJclHashSetF<T> } ====================================================
function EqualityCompareEqObjects(const Obj1, Obj2: TRefUnique): Boolean;
begin
Result := Obj1 = Obj2;
end;
constructor TJclHashSetF<T>.Create(const AEqualityCompare: TEqualityCompare<T>; const AMap: IJclMap<T, TRefUnique>);
begin
inherited Create(AMap);
SetEqualityCompare(AEqualityCompare);
end;
constructor TJclHashSetF<T>.Create(const AEqualityCompare: TEqualityCompare<T>; const AHash: THashConvert<T>; const ACompare: TCompare<T>;
ACapacity: Integer; AOwnsItems: Boolean);
begin
Create(AEqualityCompare, TJclHashMapF<T, TRefUnique>.Create(AEqualityCompare, AHash, EqualityCompareEqObjects, ACompare, ACapacity, AOwnsItems, False));
end;
function TJclHashSetF<T>.CreateEmptyContainer: TJclAbstractContainerBase;
var
AMap: IJclMap<T, TRefUnique>;
begin
AMap := (FMap as IJclCloneable).Clone as IJclMap<T, TRefUnique>;
AMap.Clear;
Result := TJclHashSetF<T>.Create(FEqualityCompare, AMap);
AssignPropertiesTo(Result);
end;
//=== { TJclHashSetI<T> } ====================================================
constructor TJclHashSetI<T>.Create(const AMap: IJclMap<T, TRefUnique>);
begin
inherited Create(AMap);
end;
constructor TJclHashSetI<T>.Create(ACapacity: Integer; AOwnsItems: Boolean);
begin
Create(TJclHashMapI<T, TRefUnique>.Create(ACapacity, AOwnsItems, False));
end;
function TJclHashSetI<T>.CreateEmptyContainer: TJclAbstractContainerBase;
var
AMap: IJclMap<T, TRefUnique>;
begin
AMap := (FMap as IJclCloneable).Clone as IJclMap<T, TRefUnique>;
AMap.Clear;
Result := TJclHashSetI<T>.Create(AMap);
AssignPropertiesTo(Result);
end;
function TJclHashSetI<T>.ItemsEqual(const A, B: T): Boolean;
begin
if Assigned(FEqualityCompare) then
Result := FEqualityCompare(A, B)
else
if Assigned(FCompare) then
Result := FCompare(A, B) = 0
else
Result := A.Equals(B);
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ Web server application components }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
// TUTF8ContentParser is a WebRequest content parser that parses UTF-8 requests.
// TUTF8ContentParser class automatically replace the default content parser when this unit (UTF8ContentParser)
// is used in a web application. You should only use UTF8ContentParser in web applications that generate UTF-8
// responses.
//
// To generated UTF-8 encoded responses, set Response.ContentType as follows before setting Response.Content.
// Response.ContentType := 'text/html; charset=UTF-8';
//
// Note that, if your application uses the ReqMulti unit to parse multipart content, ReqMulti must appear in the application
// uses list after UTF8ContentParser.
{$HPPEMIT '#pragma link "UTF8ContentParser"'} {Do not Localize}
unit UTF8ContentParser;
interface
uses System.SysUtils, System.Classes, System.Masks, System.Contnrs, Web.HTTPApp,
ReqFiles, HTTPParse;
type
{ TUTF8ContentParser }
TUTF8ContentParser = class(TContentParser)
private
FContentFields: TStrings;
public
destructor Destroy; override;
function GetContentFields: TStrings; override;
class function CanParse(AWebRequest: TWebRequest): Boolean; override;
end;
implementation
uses Web.WebConst, WebComp, Web.BrkrConst, Winapi.Windows;
{ TUTF8ContentParser }
class function TUTF8ContentParser.CanParse(AWebRequest: TWebRequest): Boolean;
begin
Result := True;
end;
destructor TUTF8ContentParser.Destroy;
begin
FContentFields.Free;
inherited Destroy;
end;
procedure ExtractHeaderFields(Separators, WhiteSpace: TSysCharSet; Content: PAnsiChar;
Strings: TStrings; Decode: Boolean; Encoding: TEncoding; StripQuotes: Boolean = False); forward;
function TUTF8ContentParser.GetContentFields: TStrings;
begin
if FContentFields = nil then
begin
FContentFields := TStringList.Create;
if WebRequest.ContentLength > 0 then
begin
ExtractHeaderFields(['&'], [], PAnsiChar(WebRequest.RawContent), FContentFields, True, TEncoding.UTF8);
end;
end;
Result := FContentFields;
end;
// Version of HTTP.ExtractHeaderFields that supports encoding parameter
procedure ExtractHeaderFields(Separators, WhiteSpace: TSysCharSet; Content: PAnsiChar;
Strings: TStrings; Decode: Boolean; Encoding: TEncoding; StripQuotes: Boolean = False);
var
Head, Tail: PAnsiChar;
EOS, InQuote, LeadQuote: Boolean;
QuoteChar: AnsiChar;
ExtractedField: AnsiString;
WhiteSpaceWithCRLF: TSysCharSet;
SeparatorsWithCRLF: TSysCharSet;
procedure AddString(const S: AnsiString);
var
LBytes: TBytes;
LString: string;
begin
LBytes := BytesOf(S);
LString := Encoding.GetString(LBytes);
Strings.Add(LString);
end;
function DoStripQuotes(const S: AnsiString): AnsiString;
var
I: Integer;
InStripQuote: Boolean;
StripQuoteChar: AnsiChar;
begin
Result := S;
InStripQuote := False;
StripQuoteChar := #0;
if StripQuotes then
for I := Length(Result) downto 1 do
if CharInSet(Result[I], ['''', '"']) then
if InStripQuote and (StripQuoteChar = Result[I]) then
begin
Delete(Result, I, 1);
InStripQuote := False;
end
else if not InStripQuote then
begin
StripQuoteChar := Result[I];
InStripQuote := True;
Delete(Result, I, 1);
end
end;
begin
if (Content = nil) or (Content^ = #0) then Exit;
WhiteSpaceWithCRLF := WhiteSpace + [#13, #10];
SeparatorsWithCRLF := Separators + [#0, #13, #10, '"'];
Tail := Content;
QuoteChar := #0;
repeat
while CharInSet(Tail^, WhiteSpaceWithCRLF) do Inc(Tail);
Head := Tail;
InQuote := False;
LeadQuote := False;
while True do
begin
while (InQuote and not CharInSet(Tail^, [#0, '"'])) or
not CharInSet(Tail^, SeparatorsWithCRLF) do Inc(Tail);
if Tail^ = '"' then
begin
if (QuoteChar <> #0) and (QuoteChar = Tail^) then
QuoteChar := #0
else
begin
LeadQuote := Head = Tail;
QuoteChar := Tail^;
if LeadQuote then Inc(Head);
end;
InQuote := QuoteChar <> #0;
if InQuote then
Inc(Tail)
else Break;
end else Break;
end;
if not LeadQuote and (Tail^ <> #0) and (Tail^ = '"') then
Inc(Tail);
EOS := Tail^ = #0;
if Head^ <> #0 then
begin
SetString(ExtractedField, Head, Tail-Head);
if Decode then
AddString(HTTPDecode(AnsiString(DoStripQuotes(ExtractedField))))
else AddString(DoStripQuotes(ExtractedField));
end;
Inc(Tail);
until EOS;
end;
initialization
RegisterContentParser(TUTF8ContentParser);
end.
|
unit uTestBaseObj;
interface
uses TestFrameWork, SysUtils, uBase;
type
TTestBaseObj = class( TTestCase )
published
procedure TestID;
end;
implementation
{ TTestBaseObj }
procedure TTestBaseObj.TestID;
const
NullGuid = '{00000000-0000-0000-0000-000000000000}';
var
BaseObj : TBaseObject;
begin
BaseObj := TBaseObject.Create;
try
CheckNotEqualsString( NullGuid, GUIDToString( BaseObj.ID ), 'Guid' );
CheckNotEqualsString( NullGuid, BaseObj.IDAsStr, 'Guid str' );
finally
FreeAndNil( BaseObj );
end;
end;
initialization
TestFramework.RegisterTest( TTestBaseObj.Suite );
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.