text stringlengths 14 6.51M |
|---|
unit LogNTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
Math,
uIntX;
type
{ TTestLogN }
TTestLogN = class(TTestCase)
published
procedure LogNBase10();
procedure LogNBase2();
end;
implementation
procedure TTestLogN.LogNBase10();
var
based, numberd, ans: Double;
number: TIntX;
begin
based := 10;
number := 100;
numberd := 100;
ans := Math.LogN(based, numberd);
AssertTrue(TIntX.LogN(based, number) = ans);
number := 10;
numberd := 10;
ans := Math.LogN(based, numberd);
AssertTrue(TIntX.LogN(based, number) = ans);
number := 500;
numberd := 500;
ans := Math.LogN(based, numberd);
AssertTrue(TIntX.LogN(based, number) = ans);
number := 1000;
numberd := 1000;
ans := Math.LogN(based, numberd);
AssertTrue(TIntX.LogN(based, number) = ans);
end;
procedure TTestLogN.LogNBase2();
var
based, numberd, ans: Double;
number: TIntX;
begin
based := 2;
number := 100;
numberd := 100;
ans := Math.LogN(based, numberd);
AssertTrue(TIntX.LogN(based, number) = ans);
number := 10;
numberd := 10;
ans := Math.LogN(based, numberd);
AssertTrue(TIntX.LogN(based, number) = ans);
number := 500;
numberd := 500;
ans := Math.LogN(based, numberd);
AssertTrue(TIntX.LogN(based, number) = ans);
number := 1000;
numberd := 1000;
ans := Math.LogN(based, numberd);
AssertTrue(TIntX.LogN(based, number) = ans);
number := TIntX.One shl 64 shl High(Int32);
AssertTrue(TIntX.LogN(based, number) = 2147483711);
end;
initialization
RegisterTest(TTestLogN);
end.
|
unit uScanThread;
interface
uses
Windows, Dialogs, Forms, Controls, StdCtrls, Classes, ExtCtrls,SysUtils,Graphics,bass;
type TSpectrumColor = record
ColorLoopStart,ColorLoopEnd,ColorPosition : TColor;
ColorBack,ColorBorder,ColorPeak : TColor;
ColorText : TColor;
end;
type TScanThread = class(TThread)
private
fPaintBox : TPaintBox;
fdecoder : DWORD; // la channel "decode" -> GetLevel
fChannel : DWORD; // la channel en cours -> Position ...
fKillscan : boolean; // quand arreter le scan , utile si il faut re-scanner
fBPP : DWORD; // relation Temps sur TailleX
wavebufL : array of smallint; // tableaux de levels gauche
wavebufR : array of smallint; //droit
fWidth,fHeight:integer; // taille en X et Y
fBufferBitmap : TBitmap; // le bitmap ou on va dessiner desus
fNbLoopSync : DWORD; // indice pr la procedure LoopSyncProc
fSpectrumColor : TSpectrumColor;
fLoopStart,fLoopEnd,fPosition : DWORD; // position de fin , début et en cours
fNeedRedraw : boolean;// utile pr savoir si il faut redessiner
procedure SetBackColor (AColor : TColor);
procedure SetBorderColor (AColor : TColor);
procedure SetPeakColor (AColor : TColor);
procedure SetLoopStartColor (AColor : TColor);
procedure SetLoopEndColor (AColor : TColor);
procedure SetPositionColor (AColor : TColor);
procedure SetTextColor (AColor : TColor);
procedure ScanPeaks; // on recupère les Levels
procedure draw_Spectrum; // on dessiner dans le Bitmap
procedure ThreadProcedure; // fonction principal
protected
// Les <> méthodes relatives au TPaintBox : Paint , onMouseDown , onMouseMove
procedure PaintBoxPaint(Sender: TObject);
procedure PaintBoxMouseDown(Sender: TObject;Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PaintBoxMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
procedure Execute; override;
public
property BPP:DWORD read fBPP;
property LoopStart : DWORD read fLoopStart write fLoopStart;
property LoopEnd : DWORD read fLoopEnd write fLoopEnd;
property Position : DWORD read fPosition write fPosition;
property BackColor : TColor write SetBackColor;
property BorderColor : TColor write SetBorderColor;
property PeakColor : TColor write SetPeakColor;
property LoopStartColor : TColor write SetLoopStartColor;
property LoopEndColor : TColor write SetLoopEndColor;
property PositionColor : TColor write SetPositionColor;
property TextColor : TColor write SetTextColor;
procedure ReDraw;
procedure ReScan;
property SpectrumColor : TSpectrumColor read fSpectrumColor write fSpectrumColor;
constructor Create(ADecoder:DWORD;AChannel:DWORD;AOwner : TComponent;AParent : TWinControl;ALeft,ATop,AWidth,AHeight : DWORD);
destructor Destroy;override;
end;
procedure LoopSyncProc(handle: HSYNC; channel, data: DWORD; user: Pointer); stdcall;
var
NbLoopSync : DWORD =0 ;
GlobalLoopStart : array[0..1000]of DWORD;
fLoopSync : array[0..1000]of HSYNC;
implementation
procedure LoopSyncProc(handle: HSYNC; channel, data: DWORD; user: Pointer); stdcall;
var
i : integer;
begin
for i:=0 to NbLoopSync do begin
if handle = fLoopSync[i] then begin
if not BASS_ChannelSetPosition(channel,GlobalLoopStart[i],BASS_POS_BYTE) then BASS_ChannelSetPosition(channel,0,BASS_POS_BYTE);
end;
end;
end;
//------------------------------------------------------------------------------
{ TScanThread }
constructor TScanThread.Create(ADecoder:DWORD;AChannel:DWORD;AOwner : TComponent;AParent : TWinControl;ALeft,ATop,AWidth,AHeight : DWORD);
begin
inherited create(false);
if NbLoopSync>=1000 then NbLoopSync:=0;
fNeedRedraw:=True;
fNbLoopSync:=NbLoopSync;
fBufferBitmap := TBitmap.Create;
fLoopEnd:=0;
fLoopStart:=0;
GlobalLoopStart[fNbLoopSync]:=fLoopStart;
with fSpectrumColor do begin
ColorLoopStart := ClBlue;
ColorLoopEnd := ClRed;
ColorPosition := ClWhite;
ColorBack := ClBlack;
ColorBorder := ClGray;
ColorPeak := ClLime;
ColorText := ClWhite;
end;
fKillscan := false;
fPaintBox := TPaintBox.Create(AOwner);
fPaintBox.Parent := AParent;
fPaintBox.Parent.DoubleBuffered:=True;
fPaintBox.Width := AWidth;
fPaintBox.Height := AHeight;
fPaintBox.Left:=ALeft;
fPaintBox.Top := ATop;
fWidth:=fPaintBox.Canvas.ClipRect.Right;
fHeight:=fPaintBox.Canvas.ClipRect.Bottom;
fBufferBitmap.Width:=fWidth;
fBufferBitmap.Height:=fHeight;
fDecoder := ADecoder;
fBPP :=BASS_ChannelGetLength(ADecoder,BASS_POS_BYTE) div fWidth;
if (fbpp < BASS_ChannelSeconds2Bytes(ADecoder,0.02)) then // minimum 20ms per pixel (BASS_ChannelGetLevel scans 20ms)
fbpp := BASS_ChannelSeconds2Bytes(ADecoder,0.02);
SetLength(wavebufL,fWidth);
SetLength(wavebufR,fWidth);
Priority := tpNormal;
FreeOnTerminate := false;
fChannel := AChannel;
fLoopSync[fNbLoopSync]:= BASS_ChannelSetSync(fChannel,BASS_SYNC_POS or BASS_SYNC_MIXTIME,fLoopEnd,LoopSyncProc,nil);
NbLoopSync:=NbLoopSync+1;
end;
procedure TScanThread.ReDraw;
begin
fNeedRedraw := true;
end;
procedure TScanThread.ReScan;
begin
fkillscan:=false;
end;
procedure TScanThread.SetBackColor (AColor : TColor);
begin
fSpectrumColor.ColorBack := AColor;
ReDraw;
end;
procedure TScanThread.SetBorderColor (AColor : TColor);
begin
fSpectrumColor.ColorBorder := AColor;
ReDraw;
end;
procedure TScanThread.SetPeakColor (AColor : TColor);
begin
fSpectrumColor.ColorPeak := AColor;
ReDraw;
end;
procedure TScanThread.SetLoopStartColor (AColor : TColor);
begin
fSpectrumColor.ColorLoopStart := AColor;
ReDraw;
end;
procedure TScanThread.SetLoopEndColor (AColor : TColor);
begin
fSpectrumColor.ColorLoopEnd := AColor;
ReDraw;
end;
procedure TScanThread.SetPositionColor (AColor : TColor);
begin
fSpectrumColor.ColorPosition := AColor;
ReDraw;
end;
procedure TScanThread.SetTextColor (AColor : TColor);
begin
fSpectrumColor.ColorText := AColor;
ReDraw;
end;
destructor TScanThread.Destroy;
begin
//NbLoopSync:=NbLoopSync-1;
fKillScan:=true;
fBufferBitmap.Free;
fPaintBox.Free;
inherited Destroy;
end;
procedure TScanThread.PaintBoxPaint(Sender: TObject);
begin
fPaintBox.Canvas.Draw(0,0,fBufferBitmap);
fPaintBox.Canvas.Pen.Color:=fSpectrumColor.ColorLoopStart;
fPaintBox.Canvas.MoveTo(fLoopStart div fBPP,0);
fPaintBox.Canvas.LineTo(fLoopStart div fBPP,fHeight);
fPaintBox.Canvas.Pen.Color:=fSpectrumColor.ColorLoopEnd;
fPaintBox.Canvas.MoveTo(fLoopEnd div fBPP,0);
fPaintBox.Canvas.LineTo(fLoopEnd div fBPP,fHeight);
fPaintBox.Canvas.Pen.Color:=fSpectrumColor.ColorPosition;
fPaintBox.Canvas.MoveTo(fPosition div fBPP,0);
fPaintBox.Canvas.LineTo(fPosition div fBPP,fHeight);
fPaintBox.Canvas.Font.Color := fSpectrumColor.ColorText;
fPaintBox.Canvas.Brush.Color:=fSpectrumColor.ColorBack;
fPaintBox.Canvas.TextOut((fLoopStart div fBPP)+7,12,IntToStr(Round(BASS_ChannelBytes2Seconds(fDecoder,fLoopStart))));
fPaintBox.Canvas.TextOut((fLoopEnd div fBPP)+7,12,IntToStr(Round(BASS_ChannelBytes2Seconds(fDecoder,fLoopEnd))));
fPaintBox.Canvas.TextOut((fPosition div fBPP)+7,12,IntToStr(Round(BASS_ChannelBytes2Seconds(fDecoder,fPosition))));
end;
procedure TScanThread.PaintBoxMouseDown(Sender: TObject;Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in shift then begin
fLoopStart :=DWORD(X)*fBPP;
GlobalLoopStart[fNbLoopSync]:=fLoopStart;
end else if ssRight in shift then begin
fLoopEnd :=DWORD(X)*fBPP;
BASS_ChannelRemoveSync(fChannel,fLoopSync[fNbLoopSync]); // remove old sync
fLoopSync[fNbLoopSync]:= BASS_ChannelSetSync(fChannel,BASS_SYNC_POS or BASS_SYNC_MIXTIME,fLoopEnd,LoopSyncProc,nil);
// set new sync
end else if ssMiddle in shift then
BASS_ChannelSetPosition(fChannel,DWORD(X)*fBPP,BASS_POS_BYTE);
end;
procedure TScanThread.PaintBoxMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in shift then begin
fLoopStart :=DWORD(X)*fBPP;
GlobalLoopStart[fNbLoopSync]:=fLoopStart;
end else if ssRight in shift then begin
fLoopEnd :=DWORD(X)*fBPP;
BASS_ChannelRemoveSync(fChannel,fLoopSync[fNbLoopSync]); // remove old sync
fLoopSync[fNbLoopSync]:= BASS_ChannelSetSync(fChannel,BASS_SYNC_POS or BASS_SYNC_MIXTIME,fLoopEnd,LoopSyncProc,nil);
// set new sync
end else if ssMiddle in shift then
BASS_ChannelSetPosition(fChannel,DWORD(X)*fBPP,BASS_POS_BYTE);
end;
procedure TScanThread.Execute;
begin
ScanPeaks;
fPaintBox.OnPaint := PaintBoxPaint;
fPaintBox.OnMouseDown:=PaintBoxMouseDown;
fPaintBox.OnMouseMove:= PaintBoxMouseMove;
repeat
synchronize(ThreadProcedure);
sleep(20);
until Terminated;
end;
procedure TScanThread.ThreadProcedure;
begin
//ScanPeaks ; //-> normalement inutile , car déjà scanné
if fNeedRedraw then Draw_Spectrum;
fPosition:=BASS_ChannelGetPosition(fChannel,BASS_POS_BYTE);
fPaintBox.Invalidate;
end;
procedure TScanThread.Draw_Spectrum;
var
i,ht : integer;
begin
//clear background
fBufferBitmap.Canvas.Brush.Color := fSpectrumColor.ColorBack;
fBufferBitmap.Canvas.FillRect(Rect(0,0,fBufferBitmap.Width,fBufferBitmap.Height));
fBufferBitmap.Canvas.Pen.Color := fSpectrumColor.ColorBorder;
fBufferBitmap.Canvas.Rectangle(1,0,fBufferBitmap.Width,fBufferBitmap.Canvas.ClipRect.Bottom);
//draw peaks
ht := fHeight div 2;
for i:=0 to length(wavebufL)-1 do
begin
fBufferBitmap.Canvas.MoveTo(i,ht);
fBufferBitmap.Canvas.Pen.Color := fSpectrumColor.ColorPeak;
fBufferBitmap.Canvas.LineTo(i,ht-trunc((wavebufL[i]/32768)*ht));
fBufferBitmap.Canvas.Pen.Color := fSpectrumColor.ColorPeak;
fBufferBitmap.Canvas.MoveTo(i,ht+2);
fBufferBitmap.Canvas.LineTo(i,ht+2+trunc((wavebufR[i]/32768)*ht));
end;
fNeedRedraw:=false;
end;
procedure TScanThread.ScanPeaks;
var
cpos,level : DWord;
peak : array[0..1] of DWORD;
position : DWORD;
counter : integer;
begin
cpos := 0;
peak[0] := 0;
peak[1] := 0;
counter := 0;
while not fKillscan do
begin
level := BASS_ChannelGetLevel(fDecoder); // scan peaks
if (peak[0]<LOWORD(level)) then
peak[0]:=LOWORD(level); // set left peak
if (peak[1]<HIWORD(level)) then
peak[1]:=HIWORD(level); // set right peak
if BASS_ChannelIsActive(fDecoder) <> BASS_ACTIVE_PLAYING then
begin
position := cardinal(-1); // reached the end
end else
position := BASS_ChannelGetPosition(fDecoder,BASS_POS_BYTE) div fBPP;
if position > cpos then
begin
inc(counter);
if counter <= length(wavebufL)-1 then
begin
wavebufL[counter] := peak[0];
wavebufR[counter] := peak[1];
end;
if (position >= DWORD(fWidth)) then
fKillscan:=true;
cpos := position;
end;
peak[0] := 0;
peak[1] := 0;
end;
end;
end.
|
unit LrIterator;
interface
uses
Classes, Controls;
type
TLrIterator = class
private
FIndex: Integer;
public
function Eof: Boolean; virtual; abstract;
function Next: Boolean; overload; virtual;
procedure Reset;
public
property Index: Integer read FIndex write FIndex;
end;
implementation
{ TLrIterator }
procedure TLrIterator.Reset;
begin
Index := 0;
end;
function TLrIterator.Next: Boolean;
begin
Result := not Eof;
if Result then
Inc(FIndex)
else
Reset;
end;
end.
|
unit uFrmBasePtypeInput;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmBaseInput, Menus, cxLookAndFeelPainters, ActnList, cxLabel,
cxControls, cxContainer, cxEdit, cxCheckBox, StdCtrls, cxButtons,
ExtCtrls, Mask, cxTextEdit, cxMaskEdit, cxButtonEdit, cxGraphics,
cxDropDownEdit, uParamObject, ComCtrls, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, uDBComConfig, uGridConfig;
type
TfrmBasePtypeInput = class(TfrmBaseInput)
edtFullname: TcxButtonEdit;
lbl1: TLabel;
lbl2: TLabel;
edtUsercode: TcxButtonEdit;
Label1: TLabel;
edtName: TcxButtonEdit;
edtPYM: TcxButtonEdit;
lbl3: TLabel;
lbl4: TLabel;
Label2: TLabel;
lbl5: TLabel;
edtStandard: TcxButtonEdit;
edtModel: TcxButtonEdit;
edtArea: TcxButtonEdit;
cbbCostMode: TcxComboBox;
lbl6: TLabel;
edtUsefulLifeday: TcxButtonEdit;
lbl7: TLabel;
chkStop: TcxCheckBox;
pgcView: TPageControl;
tsJG: TTabSheet;
gridLVPtypeUnit: TcxGridLevel;
gridPtypeUnit: TcxGrid;
gridTVPtypeUnit: TcxGridTableView;
procedure gridTVPtypeUnitEditing(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; var AAllow: Boolean);
protected
{ Private declarations }
procedure SetFrmData(ASender: TObject; AList: TParamObject); override;
procedure GetFrmData(ASender: TObject; AList: TParamObject); override;
procedure ClearFrmData; override;
function SaveData: Boolean; override;
private
FGridItem: TGridItem;
procedure IniUnitGridField;
public
{ Public declarations }
procedure InitParamList; override;
procedure BeforeFormShow; override;
procedure BeforeFormDestroy; override;
class function GetMdlDisName: string; override; //得到模块显示名称
end;
var
frmBasePtypeInput: TfrmBasePtypeInput;
implementation
{$R *.dfm}
uses uSysSvc, uBaseFormPlugin, uBaseInfoDef, uModelBaseTypeIntf, uModelControlIntf, uOtherIntf,
uDefCom, uMoudleNoDef, uPubFun, DBClient;
{ TfrmBasePtypeInput }
procedure TfrmBasePtypeInput.BeforeFormDestroy;
begin
inherited;
FGridItem.Free;
end;
procedure TfrmBasePtypeInput.BeforeFormShow;
begin
Title := '商品信息';
FModelBaseType := IModelBaseTypePtype((SysService as IModelControl).GetModelIntf(IModelBaseTypePtype));
FModelBaseType.SetParamList(ParamList);
FModelBaseType.SetBasicType(btPtype);
DBComItem.AddItem(edtFullname, 'Fullname', 'PFullname');
DBComItem.AddItem(edtUsercode, 'Usercode', 'PUsercode');
DBComItem.AddItem(edtName, 'Name', 'Name');
DBComItem.AddItem(edtPYM, 'Namepy', 'Pnamepy');
DBComItem.AddItem(edtStandard, 'Standard', 'Standard');
DBComItem.AddItem(edtModel, 'Model', 'Model');
DBComItem.AddItem(edtArea, 'Area', 'Area');
DBComItem.AddItem(cbbCostMode, 'CostMode', 'CostMode');
DBComItem.AddItem(edtUsefulLifeday, 'UsefulLifeday', 'UsefulLifeday', cfPlusInt);
DBComItem.AddItem(chkStop, 'IsStop', 'IsStop');
FGridItem := TGridItem.Create(ClassName + gridPtypeUnit.Name, gridPtypeUnit, gridTVPtypeUnit);
FGridItem.SetGridCellSelect(True);
IniUnitGridField();
inherited;
end;
procedure TfrmBasePtypeInput.ClearFrmData;
begin
inherited;
edtUsefulLifeday.Text := '0';
end;
procedure TfrmBasePtypeInput.GetFrmData(ASender: TObject;
AList: TParamObject);
begin
inherited;
AList.Add('@Parid', ParamList.AsString('ParId'));
DBComItem.SetDataToParam(AList);
AList.Add('@Comment', '');
if FModelBaseType.DataChangeType in [dctModif] then
begin
AList.Add('@typeId', ParamList.AsString('CurTypeid'));
end;
end;
class function TfrmBasePtypeInput.GetMdlDisName: string;
begin
Result := '商品信息';
end;
procedure TfrmBasePtypeInput.InitParamList;
begin
inherited;
MoudleNo := fnMdlBasePtypeList;
end;
procedure TfrmBasePtypeInput.IniUnitGridField;
var
i: Integer;
aColInfo: TColInfo;
begin
FGridItem.ClearField();
FGridItem.AddField('IsBase', 'IsBase', -1, cfInt);
FGridItem.AddField('UnitId', 'UnitId', -1, cfInt);
aColInfo := FGridItem.AddField('UnitType', '项目', 100, cfString);
aColInfo.GridColumn.Options.Editing := False;
FGridItem.AddField('UnitName', '单位名称', 100, cfString);
FGridItem.AddField('UnitRates', '单位关系', 100, cfQty);
FGridItem.AddField('Barcode', '条码', 100, cfString);
FGridItem.AddField('RetailPrice', '零售价', 100, cfPrice);
FGridItem.InitGridData;
gridTVPtypeUnit.DataController.RecordCount := 3;
FGridItem.SetCellValue('UnitId', 0, 0);
FGridItem.SetCellValue('UnitType', 0, '基本单位');
FGridItem.SetCellValue('UnitRates', 0, 1);
FGridItem.SetCellValue('IsBase', 0, 1);
FGridItem.SetCellValue('UnitId', 1, 1);
FGridItem.SetCellValue('UnitType', 1, '辅助单位1');
FGridItem.SetCellValue('IsBase', 1, 0);
FGridItem.SetCellValue('UnitId', 2, 2);
FGridItem.SetCellValue('UnitType', 2, '辅助单位2');
FGridItem.SetCellValue('IsBase', 1, 0);
end;
function TfrmBasePtypeInput.SaveData: Boolean;
var
aUnitInfo: TParamObject;
aRow: Integer;
aUnitName, aBarcode: string;
aURate: Double;
begin
Result := inherited SaveData;
if not Result then Exit;
aUnitInfo := TParamObject.Create;
try
for aRow := FGridItem.GetFirstRow to FGridItem.GetLastRow do
begin
aUnitName := FGridItem.GetCellValue('UnitName', aRow);
aURate := FGridItem.GetCellValue('UnitRates', aRow);
if (StringEmpty(aUnitName) or (aURate = 0)) and (aRow <> 0) then Continue;
aUnitInfo.Clear;
aUnitInfo.Add('@PTypeId', FModelBaseType.CurTypeId);
aUnitInfo.Add('@UnitName', aUnitName);
aUnitInfo.Add('@URate', aURate);
aUnitInfo.Add('@IsBase', FGridItem.GetCellValue('IsBase', aRow));
aUnitInfo.Add('@BarCode', FGridItem.GetCellValue('Barcode', aRow));
aUnitInfo.Add('@Comment', '');
aUnitInfo.Add('@OrdId', FGridItem.GetCellValue('UnitId', aRow));
IModelBaseTypePtype(FModelBaseType).SaveOneUnitInfo(aUnitInfo);
end;
finally
aUnitInfo.Free;
end;
end;
procedure TfrmBasePtypeInput.SetFrmData(ASender: TObject;
AList: TParamObject);
var
aCdsTmp: TClientDataSet;
aUnitId: Integer;
begin
inherited;
DBComItem.GetDataFormParam(AList);
aCdsTmp := TClientDataSet.Create(nil);
try
IModelBaseTypePtype(FModelBaseType).GetUnitInfo(FModelBaseType.CurTypeId, aCdsTmp);
aCdsTmp.First;
while not aCdsTmp.Eof do
begin
aUnitId := aCdsTmp.FieldByName('OrdId').AsInteger;
FGridItem.SetCellValue('UnitName', aUnitId, aCdsTmp.FieldByName('UnitName').AsString);
FGridItem.SetCellValue('UnitRates', aUnitId, aCdsTmp.FieldByName('URate').AsFloat);
FGridItem.SetCellValue('BarCode', aUnitId, aCdsTmp.FieldByName('BarCode').AsString);
aCdsTmp.Next;
end;
finally
aCdsTmp.Free;
end;
end;
procedure TfrmBasePtypeInput.gridTVPtypeUnitEditing(
Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem;
var AAllow: Boolean);
var
aUnitName, aBarcode: string;
aURate: Double;
begin
inherited;
if FGridItem.RowIndex = 0 then
begin
if FGridItem.FindColByFieldName('UnitRates').GridColumn = AItem then
AAllow := False;
end
else if FGridItem.RowIndex = 1 then
begin
aUnitName := FGridItem.GetCellValue('UnitName', 0);
aURate := FGridItem.GetCellValue('UnitRates', 0);
if (StringEmpty(aUnitName) or (aURate = 0)) then AAllow := False;
end
else if FGridItem.RowIndex = 2 then
begin
aUnitName := FGridItem.GetCellValue('UnitName', 1);
aURate := FGridItem.GetCellValue('UnitRates', 1);
if (StringEmpty(aUnitName) or (aURate = 0)) then AAllow := False;
end;
end;
end.
|
unit UBonusOrderEditExtInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFControl, uLabeledFControl, uSpravControl, StdCtrls, Buttons,
GlobalSPR, qFTools, uCommonSP, uCharControl, uFloatControl, DB,
FIBDataSet, pFIBDataSet, cxLookAndFeelPainters, cxButtons, uIntControl,
FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, BaseTypes;
type
TfrmGetExtInfo = class(TForm)
Label3: TLabel;
Department: TqFSpravControl;
PostSalary: TqFSpravControl;
Label4: TLabel;
qFSC_SovmestFIO: TqFSpravControl;
OkButton: TBitBtn;
CancelButton: TBitBtn;
SovmKoeff: TqFFloatControl;
TypePost: TqFSpravControl;
PostSalaryShtat: TqFSpravControl;
ShrId: TqFIntControl;
btnSHRSearch: TcxButton;
SHRSet: TpFIBDataSet;
StorProc: TpFIBStoredProc;
ShrTransaction: TpFIBTransaction;
btnClearinfo: TcxButton;
procedure OkButtonClick(Sender: TObject);
procedure TypePostOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure qFSC_SovmestFIOOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure DepartmentOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure PostSalaryOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure PostSalaryShtatOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure btnSHRSearchClick(Sender: TObject);
procedure btnClearinfoClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
KeySes:Integer;
{ Private declarations }
public
{ Public declarations }
ACT_DATE, DateBeg: TDate;
constructor Create(AOwner:TComponent; KeySession:Integer; DateB:TDate);
procedure ExecProcShr(IsDelete:String);
end;
implementation
uses UpBonusOrderForm, uShtatUtils, uUnivSprav, RxMemDS, uSelectForm;
{$R *.dfm}
constructor TfrmGetExtInfo.Create(AOwner:TComponent; KeySession:Integer; DateB:TDate);
begin
inherited Create(AOwner);
KeySes:=KeySession;
DateBeg:=DateB;
end;
procedure TfrmGetExtInfo.ExecProcShr(IsDelete:String);
begin
StorProc.StoredProcName:='UP_ACCEPT_SHR_INS2';
StorProc.Transaction.StartTransaction;
StorProc.ParamByName('KEY_SESSION').AsInteger:=KeySes;
StorProc.ParamByName('ID_SH_R').Value:=ShrId.Value;
StorProc.ParamByName('RATE_COUNT').AsFloat:=0;
StorProc.ParamByName('ONLY_DELETE').AsString:=IsDelete;
StorProc.ExecProc;
StorProc.Transaction.Commit;
end;
procedure TfrmGetExtInfo.OkButtonClick(Sender: TObject);
begin
if VarIsNull(PostSalaryShtat.Value) then
begin
PostSalaryShtat.Value := PostSalary.Value;
PostSalaryShtat.DisplayText := PostSalary.DisplayText;
end;
if VarIsNull(TypePost.Value) then
begin
agShowMessage('Треба вибрати тип персоналу для суміщення!');
Exit;
end;
ModalResult := mrOk;
ExecProcShr('T');
end;
procedure TfrmGetExtInfo.TypePostOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів персонала';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_ACCEPT_GET_TYPE_POST(' + VarToStr(PostSalaryShtat.Value) + ',' + VarToStr(Department.Value) + ',' + QuotedStr(DateToStr(ACT_DATE)) + ')';
Params.Fields := 'NAME_TYPE_POST,ID_TYPE_POST';
Params.FieldsName := 'Назва';
Params.KeyField := 'ID_TYPE_POST';
Params.ReturnFields := 'NAME_TYPE_POST,ID_TYPE_POST';
Params.DBHandle := Integer(TfmBonusOrder(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
Value := output['ID_TYPE_POST'];
DisplayText := VarToStr(output['NAME_TYPE_POST']);
end;
end;
procedure TfrmGetExtInfo.qFSC_SovmestFIOOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
var
sp: TSprav;
begin
sp := GetSprav('asup\PCardsList');
if sp <> nil then
begin
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(TfmBonusOrder(self.Owner).WorkDatabase.Handle);
FieldValues['ActualDate'] := Date;
FieldValues['AdminMode'] := 0;
FieldValues['Select'] := 1;
FieldValues['ShowStyle'] := 0;
Post;
end;
sp.Show;
if (sp.Output <> nil) and not sp.Output.IsEmpty
then begin
Value := sp.Output['ID_PCARD'];
DisplayText := sp.Output['FIO'];
end;
end;
end;
procedure TfrmGetExtInfo.DepartmentOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
var
sp: TSprav;
begin
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(TfmBonusOrder(self.Owner).WorkDatabase.Handle);
FieldValues['Select'] := 1;
FieldValues['ShowStyle'] := 0;
Post;
end;
sp.Show;
if (sp.Output <> nil) and not sp.Output.IsEmpty
then begin
Value := sp.Output['ID_DEPARTMENT'];
DisplayText := sp.Output['NAME_FULL'];
PostSalary.Blocked := false;
PostSalaryShtat.Blocked := false;
end;
end;
end;
procedure TfrmGetExtInfo.PostSalaryOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів персонала';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
//Params.TableName := 'UP_ACCEPT_GET_POST_EX(' + VarToStr(Department.Value) + ',' + QuotedStr(DateToStr(ACT_DATE)) + ')';
Params.TableName := 'UP_ACCEPT_GET_POST_REAL_2(' + QuotedStr(PostSalaryShtat.Value) +','+QuotedStr(DateToStr(ACT_DATE)) + ')';
Params.Fields := 'POST_NAME,SALARY_MIN,SALARY_MAX,ID_POST_SALARY';
//Params.Fields := 'POST_NAME,NUM_DIGIT,NAME_TYPE_POST,SALARY_MIN,SALARY_MAX,ID_POST_SALARY';
Params.FieldsName := 'Назва,мін,макс';
Params.KeyField := 'ID_POST_SALARY';
Params.ReturnFields := 'POST_NAME,ID_POST_SALARY';
Params.DBHandle := Integer(TfmBonusOrder(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
value := output['ID_POST_SALARY'];
DisplayText := VarToStr(output['POST_NAME']);
//PostSalaryShtat.Value := output['ID_POST_SALARY'];
//PostSalaryShtat.DisplayText := VarToStr(output['POST_NAME']);
TypePost.Blocked := false;
TypePost.Value := null;
TypePost.DisplayText := '';
end;
end;
procedure TfrmGetExtInfo.PostSalaryShtatOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
Params: TUnivParams;
OutPut: TRxMemoryData;
begin
Params.FormCaption := 'Довідник типів персонала';
Params.ShowMode := fsmSelect;
Params.ShowButtons := [fbExit];
Params.TableName := 'UP_ACCEPT_GET_POST_EX(' + VarToStr(Department.Value) + ',' + QuotedStr(DateToStr(ACT_DATE)) + ')';
//Params.TableName := 'UP_ACCEPT_GET_POST_REAL_2(' + QuotedStr(PostSalaryShtat.Value) +','+QuotedStr(DateToStr(ACT_DATE)) + ')';
Params.Fields := 'POST_NAME,NUM_DIGIT,NAME_TYPE_POST,SALARY_MIN,SALARY_MAX,ID_POST_SALARY';
Params.FieldsName := 'Назва,розряд,тип,мін,макс';
Params.KeyField := 'ID_POST_SALARY';
Params.ReturnFields := 'POST_NAME,ID_POST_SALARY';
Params.DBHandle := Integer(TfmBonusOrder(self.Owner).WorkDatabase.Handle);
OutPut := TRxMemoryData.Create(self);
if GetUnivSprav(Params, OutPut)
then begin
value := output['ID_POST_SALARY'];
DisplayText := VarToStr(output['POST_NAME']);
//PostSalaryShtat.Value := output['ID_POST_SALARY'];
// PostSalaryShtat.DisplayText := VarToStr(output['POST_NAME']);
TypePost.Blocked := false;
TypePost.Value := null;
TypePost.DisplayText := '';
end;
end;
procedure TfrmGetExtInfo.btnSHRSearchClick(Sender: TObject);
begin
ExecProcShr('F');
SHRSet.Close;
SHRSet.SQLs.SelectSQL.Text:='select distinct * from UP_DT_ID_SH_R_SELECT(:DATE_BEG, null, :KEY_SESSION, null)';
SHRSet.ParamByName('DATE_BEG').AsDate:=DateBeg;
SHRSet.ParamByName('KEY_SESSION').AsInteger:=KeySes;
SHRSet.Open;
if not SHRSet.IsEmpty then
begin
PostSalary.Blocked:=False;
PostSalaryShtat.Blocked:=False;
TypePost.Blocked:=False;
Department.Value:=SHRSet['Id_Department'];
Department.DisplayText:=SHRSet['Department_Name'];
PostSalaryShtat.Value:=SHRSet['Id_Post_Salary'];
PostSalaryShtat.DisplayText:=SHRSet['Name_Post'];
PostSalary.Value:=SHRSet['Id_Post_Salary'];
PostSalary.DisplayText:=SHRSet['Name_Post'];
SovmKoeff.Value:=SHRSet['Koeff_Pps'];
TypePost.Value:=SHRSet['Id_Type_Post'];
TypePost.DisplayText:=SHRSet['Name_Type_Post'];
end;
end;
procedure TfrmGetExtInfo.btnClearinfoClick(Sender: TObject);
begin
PostSalary.Blocked:=True;
PostSalaryShtat.Blocked:=True;
TypePost.Blocked:=True;
Department.Value:=null;
Department.DisplayText:='';
PostSalaryShtat.Value:=null;
PostSalaryShtat.DisplayText:='';
PostSalary.Value:=null;
PostSalary.DisplayText:='';
SovmKoeff.Value:=0;
TypePost.Value:=null;
TypePost.DisplayText:='';
ExecProcShr('T');
end;
procedure TfrmGetExtInfo.CancelButtonClick(Sender: TObject);
begin
try
ExecProcShr('T');
ModalResult:=mrCancel;
except on e:Exception
do ShowMessage(e.Message);
end;
end;
end.
|
{Dados dos archivos de números enteros positivos A1 (primos) y A2 (no primos).
Leer los números primos de A1 y almacenar en un arreglo VPrimo.
Leer los números de A2 (sin almacenar en un arreglo), determinar e informar para cada uno de ellos cuántos
divisores primos tiene en VPrimos. Recorrer una sola vez el archivo A2.
Ejemplo :
A1 VPrimo = (7, 2 , 5 , 11 , 3)
A2 = 10 105 50 22 30 10 tiene 2 divisores, 105 tiene 1 divisor……}
Program Ad2;
Type
TV = array[1..100] of word;
Procedure LeerArchivoA1(Var VPrimo:TV;Var N:byte);
Var
arch:text;
begin
N:= 0;
assign(arch,'A1.txt');reset(arch);
while not eof (arch) do
begin
N:= N + 1;
read(arch,VPrimo[N]);
end;
close(arch);
end;
Procedure LeerArchivoA2(VPrimo:TV; Var VNPrimo:TV; Var M:byte);
Var
i:byte;
arch:text;
begin
M:= 0;
assign(arch,'A2.txt');reset(arch);
while not eof (arch) do
begin
M:= M + 1;
read(arch,VNPrimo[M]);
end;
close(arch);
end;
{Procedure Informa(VPrimo,VNPrimo:TV; N,M:byte);
Var
i:byte;
begin
For i:= 1 to N do
begin
For j:= 1 to M do
begin
If (VPrimo[i] MOD VNPrimo[N] = 0) then
writeln(VNPrimo[N]:4);
end;
end;
end;}
Var
VPrimo,VNPrimo:TV;
N,M:byte;
Begin
LeerArchivoA1(VPrimo,N);
LeerArchivoA2(VPrimo,VNPrimo,M);
// Informa(VPrimo,VNPrimo,N,M);
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, process, FileUtil, Forms, Controls, Graphics, Dialogs,
StdCtrls, ExtCtrls, AsyncProcess;
type
{ TForm1 }
TForm1 = class(TForm)
AsyncProcess1: TAsyncProcess;
btnMonitorStart: TButton;
btnMonitorStop: TButton;
btnScanFolderNow: TButton;
btnClearLog: TButton;
btnCloseTool: TButton;
btnSendToTray: TButton;
textBuffer: TMemo;
log: TMemo;
Process1: TProcess;
Timer1: TTimer;
appTray: TTrayIcon;
procedure appTrayClick(Sender: TObject);
procedure btnClearLogClick(Sender: TObject);
procedure btnCloseToolClick(Sender: TObject);
procedure btnMonitorStartClick(Sender: TObject);
procedure btnMonitorStopClick(Sender: TObject);
procedure btnScanFolderNowClick(Sender: TObject);
procedure btnSendToTrayClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ private declarations }
util_path : string;
directory : String;
username : String;
password : String;
server : String;
public
{ public declarations }
procedure btnStates();
procedure loadCfg();
procedure SendEmail(filepath : String);
procedure FetchDirectory();
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
Timer1.Enabled:=false;
btnStates();
loadCfg();
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
FetchDirectory();
end;
procedure TForm1.btnMonitorStartClick(Sender: TObject);
begin
timer1.enabled:=true;
btnStates();
end;
procedure TForm1.btnClearLogClick(Sender: TObject);
begin
log.Clear;
end;
procedure TForm1.appTrayClick(Sender: TObject);
begin
form1.Show;
appTray.Visible:=false;
end;
procedure TForm1.btnCloseToolClick(Sender: TObject);
begin
timer1.Enabled:=false;
Close;
end;
procedure TForm1.btnMonitorStopClick(Sender: TObject);
begin
timer1.enabled:=false;
btnStates();
end;
procedure TForm1.btnScanFolderNowClick(Sender: TObject);
begin
FetchDirectory;
end;
procedure TForm1.btnSendToTrayClick(Sender: TObject);
begin
appTray.visible:=true;
form1.Hide;
end;
procedure TForm1.btnStates;
begin
btnMonitorStop.Enabled := timer1.Enabled;
btnMonitorStart.Enabled := not btnMonitorStop.Enabled;
end;
procedure TForm1.loadCfg;
begin
textBuffer.Lines.clear;
if fileexists('mailer.txt') then
begin
textBuffer.lines.LoadFromFile('mailer.txt');
util_path := textBuffer.Lines[0];
directory := textBuffer.lines[1];
username := textBuffer.Lines[2];
password := textBuffer.Lines[3];
server := textBuffer.Lines[4];
log.lines.add(util_path);
log.Lines.Add(directory);
log.lines.add(username);
log.lines.add(password);
log.lines.add(server);
end
else
begin
log.Lines.add('Error - create config file mailer.txt');
log.Lines.add('Github.com/ArtNazarov/TimeSenderTool');
btnMonitorStart.Enabled:=false;
btnMonitorStop.Enabled:=false;
timer1.Enabled:=False;
end;
end;
procedure TForm1.SendEmail(filepath: String);
var
tof : String;
subject : String;
attachment:string;
i : Integer;
cl : String;
attach : String;
mstart, mend : Integer;
len_cl : Integer;
BEGIN
attachment:='';
log.lines.add('sending '+filepath);
AsyncProcess1.CommandLine:=util_path + ' ';
AsyncProcess1.CommandLine:= AsyncProcess1.CommandLine + '"'+filepath + '" ';
AsyncProcess1.CommandLine:= AsyncProcess1.CommandLine + '-u ' + username + ' ';
AsyncProcess1.CommandLine:= AsyncProcess1.CommandLine + '-pw ' + password + ' ';
AsyncProcess1.CommandLine:= AsyncProcess1.CommandLine + '-server '+ server + ' ';
textBuffer.lines.clear;
textBuffer.lines.LoadFromFile(filepath);
tof:=textBuffer.lines[0];
tof:=' -to '+tof+' -f '+ username;
subject:=' -s "'+textBuffer.lines[1]+'" ';
AsyncProcess1.CommandLine:= AsyncProcess1.CommandLine + tof + ' ';
AsyncProcess1.CommandLine:= AsyncProcess1.CommandLine + subject + ' ';
i:=2;
while (i <= textbuffer.lines.count - 1) do
begin
cl:=textbuffer.lines[i];
len_cl := length(cl);
mstart:=pos('<<<', cl);
mend:=pos('>>>', cl);
if (mstart>-1) then
begin
attach:=Copy(cl, mstart+3, mend-mstart-3);
attach:=directory+'\'+attach;
log.lines.add('Found attach:'+attach);
if fileexists(attach) then
begin
log.lines.add('Attach exists');
attachment:=attach+','+attachment;
end;
end;
i:=i+1;
end;
attachment:=Copy(attachment, 1, length(attachment)-1);
If attachment<>'' then
asyncprocess1.commandline:=asyncprocess1.commandline+'-attach '+attachment;
log.lines.Add('');
log.lines.Add(AsyncProcess1.CommandLine);
AsyncProcess1.Options:=[poWaitOnExit];
AsyncProcess1.Execute;
end;
procedure TForm1.FetchDirectory;
var info : TSearchRec;
begin
If FindFirst(directory+'\*.txt',faAnyFile - faDirectory, Info) = 0 then
begin
Repeat
With Info do
begin
If (Attr and faDirectory) <> faDirectory then
begin
log.lines.add('found file '+directory+'\'+Name);
log.Lines.add('-----');
SendEmail(directory+'\'+Name);
log.Lines.add('-----');
log.lines.add('rename file to '+directory+'\'+Name+'.sended');
log.Lines.add('-----');
RenameFile(directory+'\'+Name, directory+'\'+Name+'.sended');
end;
end;
Until FindNext(info)<>0;
end;
FindClose(Info);
end;
end.
|
unit PromoHandleConflict;
interface
uses contnrs, classes, SysUtils, Dialogs, uSystemConst;
Const
NO_TAG_SELECTED = 0;
type
TPromoHandleConflict = class
private
//
FIdTag: Integer;
FEndOnDate: TDateTime;
FIdCurrentPromo: Integer;
// current promo object
FpromoList: TObjectList;
// sign to conflict
FfoundTagConflict: Boolean;
FfoundPromoConflict: Boolean;
FFoundAnyConflict: Boolean;
// list of models found on tag
FidModelList: String;
FIdTagList: String;
// list of promo objects on conflict
FPromoListConflict: TObjectList;
// list of tag objects on conflict
FTagListConflict: TObjectList;
// conflict was fixed inside the view
FIsFixed: Boolean;
FIsBogo: boolean;
// ( Internal Conflict ) get the models associated to the tag inside the current promo ( add or edit screen )
function GetModelListFromTag(idTag: Integer): TStringList;
function GetTagListFromPromo(idTagSelected: Integer; idPromo: Integer): String;
function GetTagListRewardFromPromo(idTagSelected: integer; idPromo: integer): string;
function GetModelListFromPromo(idPromo: Integer): TStringList;
function GetModelListRewardFromPromo(idPromo: integer): TStringList;
// get all active promos already inserted that can be run in parallel.
function GetPromoList(endOnDate: TDateTime): TObjectList;
// Details about conflict to display on screen
procedure ShowConflict(foundConflict: Boolean; var isFixed: Boolean);
function SeekForConflictOnTag(idModelList: String; idTagList: String): TObjectList;
function SeekForConflictOnPromos(idModelList: String; promoList: TObjectList): TObjectList;
function SeekForConflictOnBogoPromos(idModelList: string; promoList: TObjectList): TObjectList;
function DealWithConflicts(isConflict: Boolean): Boolean;
function HandleConflictToPromoByTag(): Boolean;
function HandleConflictToPromoDateChange(): Boolean;
function HandleConflictToBogoPromoByTag(): boolean;
function HandleConflictToBogoPromoRewardTag(): boolean;
function HandleConflictToBogoPromoByDateChange(): boolean;
public
// Called to just to non Bogos
function HandleConflict(endOnDate: TDateTime; idTag: Integer; idCurrentPromo: Integer): boolean; overload;
// Called to Bogo Discount Tag sides
function HandleConflict(idTag: integer; idCurrentPromo: integer; endOnDate: TDateTime): boolean; overload;
// Called to Bogo Reward Tag sides
function HandleConflict(idTag: integer; endOnDate: TDateTime; idCurrentPromo: integer): boolean; overload;
end;
implementation
uses uDM, PromoDTO, ViewPromoConflict;
{ TPromoHandleConflict }
function TPromoHandleConflict.GetModelListFromTag(
idTag: Integer): TStringList;
var
i: Integer;
begin
result := dm.GetModelsFromTagModel(idTag);
for i := 0 to result.Count - 1 do begin
if ( FidModelList = '' ) then begin
FidModelList := Copy(result.Strings[i], (Pos('IdModel', result.Strings[i])+8), 10);
end else begin
FidModelList := FIdModelList + ', ' + Copy(result.Strings[i], (Pos('IdModel', result.Strings[i])+8), 10);
end;
end;
end;
function TPromoHandleConflict.GetPromoList(endOnDate: TDateTime): TObjectList;
begin
FpromoList := dm.GetPromos(endOnDate);
end;
procedure TPromoHandleConflict.showConflict(foundConflict: Boolean; var IsFixed: Boolean);
var
i: integer;
view: TvwPromoConflict;
begin
if ( foundConflict ) then begin
view := TvwPromoConflict.Create(nil);
view.Start(FIdTag, FidModelList, FidTagList, FPromoListConflict, IsFixed);
FIsFixed := IsFixed;
freeAndNil(view);
end;
end;
function TPromoHandleConflict.SeekForConflictOnTag
(idModelList: String; idtagList: String): TObjectList;
begin
result := dm.SeekForConflictOnTag(idModelList, idtagList);
FFoundTagConflict := result.Count > 0;
FFoundAnyConflict := FfoundTagConflict;
FTagListConflict := result;
end;
function TPromoHandleConflict.SeekForConflictOnPromos(idModelList: String; promoList: TObjectList): TObjectList;
begin
result := dm.SeekForConflictOnPromo(idModelList, promoList);
FFoundPromoConflict := result.Count > 0;
FFoundAnyConflict := FFoundAnyConflict or FfoundPromoConflict;
FPromoListConflict := result;
end;
function TPromoHandleConflict.HandleConflictToPromoDateChange(): Boolean;
var
index: Integer;
counter: Integer;
begin
result := false;
// all promos that could be running
GetPromoList(FEndOnDate);
// all models inside tags in the current promo selected.
GetModelListFromPromo(FIdCurrentPromo);
// Get all models inside a tag that intends to be inserted.
//GetModelListFromTag(FIdTag);
// Internal seek ( models x internal tags )
//SeekForConflictOnTag(FidModelList, FIdTagList);
// search to find current promo inside the list
for counter:= 0 to FpromoList.Count - 1 do begin
if ( FIdCurrentPromo = TPromoDTO(FpromoList[counter]).IDDiscount ) then begin
index := counter;
break;
end;
index := 0;
end;
// remove from the list the promo that had date changed.
FpromoList.Remove(FpromoList.Items[index]);
// External seek ( models x external promos )
SeekForConflictOnPromos(FidModelList, FpromoList);
result := DealWithConflicts(FFoundAnyConflict);
end;
function TPromoHandleConflict.HandleConflictToPromoByTag(): Boolean;
begin
result := false;
// all promos that could be running
GetPromoList(FEndOnDate);
// Get all models inside a tag that intends to be inserted.
GetModelListFromTag(FIdTag);
// Get All tags already inserted
GetTagListFromPromo(FIdTag, FIdCurrentPromo);
// Internal seek ( models x internal tags )
if ( length(FidTagList) > 0 ) then begin
SeekForConflictOnTag(FidModelList, FIdTagList);
end;
// External seek ( models x external promos )
if ( FpromoList.Count > 0 ) then begin
SeekForConflictOnPromos(FidModelList, FpromoList);
end;
result := DealWithConflicts(FFoundAnyConflict);
// save memory
if ( FpromoList <> nil ) then FreeAndNil(FPromoList);
if ( FPromoListConflict <> nil ) then FreeAndNil(FPromoListConflict);
if ( FTagListConflict <> nil ) then FreeAndNil(FTagListConflict);
end;
function TPromoHandleConflict.GetModelListFromPromo(
idPromo: Integer): TStringList;
begin
FidModelList := dm.GetModelsFromPromo(idPromo);
end;
function TPromoHandleConflict.GetTagListFromPromo(idTagSelected: Integer; idPromo: Integer): String;
begin
result := dm.GetTagsFromPromo(idTagSelected, idPromo);
FidTagList := result;
end;
function TPromoHandleConflict.DealWithConflicts(
isConflict: Boolean): Boolean;
begin
if ( isConflict ) then begin
ShowConflict(FfoundPromoConflict, FIsFixed);
end else begin
FIsFixed := true;
end;
result := FIsFixed;
end;
function TPromoHandleConflict.HandleConflictToBogoPromoByTag(): boolean;
begin
result := false;
// all promos that could be running
GetPromoList(FEndOnDate);
// Get all models inside a tag that intends to be inserted.
GetModelListFromTag(FIdTag);
// Get All tags already inserted
GetTagListFromPromo(FIdTag, FIdCurrentPromo);
// External seek ( models x external promos )
if ( FpromoList.Count > 0 ) then begin
SeekForConflictOnBogoPromos(FidModelList, FpromoList);
end;
result := DealWithConflicts(FFoundAnyConflict);
// save memory
if ( FpromoList <> nil ) then FreeAndNil(FPromoList);
if ( FPromoListConflict <> nil ) then FreeAndNil(FPromoListConflict);
if ( FTagListConflict <> nil ) then FreeAndNil(FTagListConflict);
end;
function TPromoHandleConflict.HandleConflictToBogoPromoByDateChange(): boolean;
var
index: Integer;
counter: Integer;
begin
result := false;
// all promos that could be running
GetPromoList(FEndOnDate);
// all models inside tags in the current promo selected.
GetModelListRewardFromPromo(FIdCurrentPromo);
// search to find current promo inside the list
for counter:= 0 to FpromoList.Count - 1 do begin
if ( FIdCurrentPromo = TPromoDTO(FpromoList[counter]).IDDiscount ) then begin
index := counter;
break;
end;
end;
// remove from the list the promo that had date changed.
FpromoList.Remove(FpromoList.Items[index]);
// External seek ( models x external promos )
SeekForConflictOnBogoPromos(FidModelList, FpromoList);
result := DealWithConflicts(FFoundAnyConflict);
end;
function TPromoHandleConflict.SeekForConflictOnBogoPromos(
idModelList: string; promoList: TObjectList): TObjectList;
begin
result := dm.SeekForConflictBogoPromo(idModelList, promoList);
FFoundPromoConflict := result.Count > 0;
FFoundAnyConflict := FFoundAnyConflict or FfoundPromoConflict;
FPromoListConflict := result;
end;
function TPromoHandleConflict.HandleConflict(endOnDate: TDateTime; idTag,
idCurrentPromo: Integer): Boolean;
begin
result := false;
FFoundAnyConflict := false;
FIdCurrentPromo := idCurrentPromo;
FEndOnDate := endOnDate;
FIdTag := idTag;
if ( idTag = NO_TAG_SELECTED ) then begin
HandleConflictToPromoDateChange();
end else begin
HandleConflictToPromoByTag();
end;
result := FIsFixed;
end;
function TPromoHandleConflict.HandleConflict(idTag,
idCurrentPromo: integer; endOnDate: TDateTime): boolean;
begin
// To Bogo Discount Tags
result := false;
FFoundAnyConflict := false;
FIdCurrentPromo := idCurrentPromo;
FEndOnDate := endOnDate;
FIsBogo := true;
FIdTag := idTag;
if ( idTag = NO_TAG_SELECTED ) then begin
HandleConflictToBogoPromoByDateChange();
end else begin
HandleConflictToBogoPromoByTag();
end;
result := FIsFixed;
end;
function TPromoHandleConflict.GetTagListRewardFromPromo(idTagSelected,
idPromo: Integer): String;
begin
result := dm.GetTagsRewardFromPromo(idTagSelected, idPromo);
FidTagList := result;
end;
function TPromoHandleConflict.GetModelListRewardFromPromo(
idPromo: integer): TStringList;
begin
FidModelList := dm.GetModelsRewardFromPromo(idPromo);
end;
function TPromoHandleConflict.HandleConflict(idTag: integer;
endOnDate: TDateTime; idCurrentPromo: integer): boolean;
begin
// To Bogo Reward Discounts
result := false;
FFoundAnyConflict := false;
FIdCurrentPromo := idCurrentPromo;
FEndOnDate := endOnDate;
FIsBogo := true;
FIdTag := idTag;
if ( idTag = NO_TAG_SELECTED ) then begin
HandleConflictToBogoPromoByDateChange();
end else begin
HandleConflictToBogoPromoRewardTag();
end;
result := FIsFixed;
end;
function TPromoHandleConflict.HandleConflictToBogoPromoRewardTag: boolean;
begin
result := false;
// all promos that could be running
GetPromoList(FEndOnDate);
// Get all models inside a tag that intends to be inserted.
GetModelListFromTag(FIdTag);
// Get All tags already inserted
GetTagListRewardFromPromo(FIdTag, FIdCurrentPromo);
// External seek ( models x external promos )
if ( FpromoList.Count > 0 ) then begin
SeekForConflictOnBogoPromos(FidModelList, FpromoList);
end;
result := DealWithConflicts(FFoundAnyConflict);
// save memory
if ( FpromoList <> nil ) then FreeAndNil(FPromoList);
if ( FPromoListConflict <> nil ) then FreeAndNil(FPromoListConflict);
if ( FTagListConflict <> nil ) then FreeAndNil(FTagListConflict);
end;
end.
|
unit Data;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
// Тип структуры для представления сведений о пользователе
TEmployeeRec = record
Owner: string[64]; // Сотрудник
Division: string[24]; // Подразделение
Post: string[32]; // Должность
BirthDay: TDateTime; // День рождения
Experience: integer; // Опыт
Salary: real; // Оклад
Prize: real; // Премия
end;
var
IsEditData: boolean; // Признак редактирования данных в проекте
FileName:string;
implementation
begin
IsEditData:= False;
FileName:='';
end.
|
unit AlbumsController;
interface
uses
MediaFile, Generics.Collections,
Aurelius.Engine.ObjectManager;
type
TAlbumsController = class
private
FManager: TObjectManager;
public
constructor Create;
destructor Destroy; override;
procedure DeleteAlbum(Album: TAlbum);
function GetAllAlbums: TList<TAlbum>;
end;
implementation
uses
DBConnection;
{ TAlbunsController }
constructor TAlbumsController.Create;
begin
FManager := TDBConnection.GetInstance.CreateObjectManager;
end;
procedure TAlbumsController.DeleteAlbum(Album: TAlbum);
begin
if not FManager.IsAttached(Album) then
Album := FManager.Find<TAlbum>(Album.Id);
FManager.Remove(Album);
end;
destructor TAlbumsController.Destroy;
begin
FManager.Free;
inherited;
end;
function TAlbumsController.GetAllAlbums: TList<TAlbum>;
begin
FManager.Clear;
Result := FManager.FindAll<TAlbum>;
end;
end.
|
unit Backend.Resource;
interface
uses
System.JSON,
System.SysUtils,
System.Classes,
Data.User.Preferences,
Data.Articles,
Data.API.Google,
Core.Articles.Gen,
Backend.iPool.Connector,
Backend.Google.Connector,
MARS.Core.Registry,
MARS.Core.Attributes,
MARS.Core.MediaType,
MARS.Core.JSON,
MARS.Core.MessageBodyWriters,
MARS.Core.MessageBodyReaders,
MARS.mORMotJWT.Token;
type
[Path('/default')]
TSAIDResource = class
public
[GET, Path('/articles'), Produces(TMediaType.APPLICATION_JSON)]
function GetArticles([BodyParam] AData: TJSONObject): TJSONObject;
end;
TSAIDPreferences = class(TinterfacedObject, IPreferences)
private
FPreferences: TStringList;
public
constructor Create(APref: TStringList);
function GetFavourable(const AKeyword: String): Boolean;
function GetUnfavourable(const AKeyword: String): Boolean;
property Favourable[const AKeyword: String]: Boolean read GetFavourable;
property Unfavourable[const AKeywords: String]: Boolean
read GetUnfavourable;
function GetAllPreferences: TStringList;
destructor Destroy; override;
end;
TConverterToPrefrences = class
class function Convert(AData: TJSONObject): IPreferences;
end;
implementation
{ TSAIDResource }
function TSAIDResource.GetArticles(AData: TJSONObject): TJSONObject;
var
LPreferences: IPreferences;
iPoolConnector: TSAIDiPoolConnector;
LiPoolArticles: IiPoolArticles;
LGoogleConnector: TGoogleConnector;
LArticle: IArticle;
LArr: TJSONArray;
i: integer;
begin
LPreferences := TConverterToPrefrences.Convert(AData);
iPoolConnector := TSAIDiPoolConnector.Create;
LiPoolArticles := iPoolConnector.GetArticles(LPreferences);
FreeAndNil(iPoolConnector);
LGoogleConnector := TGoogleConnector.Create;
LArticle := LGoogleConnector.AnalyzeArticles(LiPoolArticles);
FreeAndNil(LGoogleConnector);
Result := TJSONObject.Create;
Result.AddPair('heading', LArticle.Caption);
Result.AddPair('content', LArticle.Text);
LArr := TJSONArray.Create;
for i := 0 to LArticle.CategoryCount - 1 do
LArr.AddElement(TJSONString.Create(LArticle.Categories[i]));
Result.AddPair('categories', LArr);
end;
{ TConverterToPrefrences }
class function TConverterToPrefrences.Convert(AData: TJSONObject): IPreferences;
var
LPreferenceJSONArr: TJSONArray;
LPreferenceJSONStr: TJSONString;
i: integer;
LPreferences: TStringList;
begin
LPreferences := TStringList.Create;
LPreferenceJSONArr := AData.GetValue('preferences') as TJSONArray;
for i := 0 to LPreferenceJSONArr.Count - 1 do
begin
LPreferenceJSONStr := LPreferenceJSONArr.Items[i] as TJSONString;
LPreferences.Add(LPreferenceJSONStr.Value);
end;
Result := TSAIDPreferences.Create(LPreferences);
end;
{ TSAIDPreferences }
constructor TSAIDPreferences.Create(APref: TStringList);
begin
FPreferences := APref;
end;
destructor TSAIDPreferences.Destroy;
begin
FreeAndNil(FPreferences);
inherited;
end;
function TSAIDPreferences.GetAllPreferences: TStringList;
begin
Result := FPreferences;
end;
function TSAIDPreferences.GetFavourable(const AKeyword: String): Boolean;
begin
Result := FPreferences.IndexOf(AKeyword) <> -1;
end;
function TSAIDPreferences.GetUnfavourable(const AKeyword: String): Boolean;
begin
Result := not GetFavourable(AKeyword);
end;
initialization
TMARSResourceRegistry.Instance.RegisterResource<TSAIDResource>;
end.
|
unit ufrmAdjustmentCashback;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMaster, StdCtrls, ExtCtrls, ufraFooter5Button, ActnList, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls,
dxCore, cxDateUtils, System.Actions, cxCurrencyEdit, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxCalendar, cxGraphics;
type
TfrmAdjustmentCashback = class(TfrmMaster)
fraFooter5Button1: TfraFooter5Button;
pnl1: TPanel;
pnl2: TPanel;
dtAdjustment: TcxDateEdit;
lbl1: TLabel;
lbl3: TLabel;
lbl4: TLabel;
edtMemberCode: TEdit;
edtMemberName: TEdit;
lbl6: TLabel;
edtCashierCode: TEdit;
edtCashierName: TEdit;
lbl5: TLabel;
edtPOSCode: TEdit;
lbl7: TLabel;
edtShiftCode: TEdit;
lbl9: TLabel;
lbl10: TLabel;
lbl11: TLabel;
edtCardCode: TEdit;
edtCardNo: TEdit;
edtCardName: TEdit;
edtCardAuthorize: TEdit;
lbl12: TLabel;
lbl13: TLabel;
lbl14: TLabel;
dtTransact: TcxDateEdit;
curredtTotalTransact: TcxCurrencyEdit;
curredtPaymentCard: TcxCurrencyEdit;
lbl15: TLabel;
curredtCashbackBefore: TcxCurrencyEdit;
curredtCashbackActually: TcxCurrencyEdit;
lbl16: TLabel;
lbl17: TLabel;
curredtAdjustValue: TcxCurrencyEdit;
lbl18: TLabel;
edtNote: TEdit;
bvl1: TBevel;
actlst1: TActionList;
actAddAdjustmentCashback: TAction;
actRefreshAdjustmentCashback: TAction;
edtNoTrans: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
// procedure cbpTransNoKeyPress(Sender: TObject; var Key: Char);
procedure actAddAdjustmentCashbackExecute(Sender: TObject);
procedure actRefreshAdjustmentCashbackExecute(Sender: TObject);
procedure dtAdjustmentKeyPress(Sender: TObject; var Key: Char);
// procedure cbpTransNoChange(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FidAdj: Integer;
// procedure ClearData;
function GetIDAdj: Integer;
procedure LookUpData(sender:TObject; Key: Word);
// procedure ParseDataTransNoForAdjustCashbakToComboBox;
procedure ParseDetilTransaksiCard;
procedure ParseDetilAdjustment;
public
{ Public declarations }
end;
var
frmAdjustmentCashback: TfrmAdjustmentCashback;
implementation
uses ufrmDialogAdjustmentCashback, uTSCommonDlg, DB, uAppUtils;
{$R *.dfm}
procedure TfrmAdjustmentCashback.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmAdjustmentCashback.FormCreate(Sender: TObject);
begin
inherited;
lblHeader.Caption := 'ADJUSTMENT CASHBACK';
end;
procedure TfrmAdjustmentCashback.FormDestroy(Sender: TObject);
begin
inherited;
frmAdjustmentCashback := nil;
end;
procedure TfrmAdjustmentCashback.FormShow(Sender: TObject);
begin
inherited;
dtAdjustment.Date := Now;
dtAdjustment.SetFocus;
dtAdjustment.SelectAll;
end;
//procedure TfrmAdjustmentCashback.cbpTransNoKeyPress(Sender: TObject;
// var Key: Char);
//begin
// if (Key = Chr(VK_RETURN)) then
// begin
// if (Trim(cbpTransNo.Text) <> '') then
// begin
// ParseDetilTransaksiCard;
// ParseDetilAdjustment;
// end;
// end;
//end;
procedure TfrmAdjustmentCashback.actAddAdjustmentCashbackExecute(
Sender: TObject);
begin
if not assigned(frmDialogAdjustmentCashback) then
Application.CreateForm(TfrmDialogAdjustmentCashback, frmDialogAdjustmentCashback);
frmDialogAdjustmentCashback.Caption := 'Add Adjustment Cashback';
frmDialogAdjustmentCashback.FormMode := fmAdd;
SetFormPropertyAndShowDialog(frmDialogAdjustmentCashback);
if (frmDialogAdjustmentCashback.IsProcessSuccessfull) then
begin
// put your code here
// ...
actRefreshAdjustmentCashbackExecute(Self);
CommonDlg.ShowConfirmSuccessfull(atAdd);
end;
frmDialogAdjustmentCashback.Free;
end;
procedure TfrmAdjustmentCashback.actRefreshAdjustmentCashbackExecute(
Sender: TObject);
begin
if (Trim(edtNoTrans.Text) <> '') then
begin
ParseDetilTransaksiCard;
ParseDetilAdjustment;
end;
end;
procedure TfrmAdjustmentCashback.dtAdjustmentKeyPress(Sender: TObject;
var Key: Char);
begin
if (Key = Chr(VK_RETURN)) then
begin
edtNoTrans.SetFocus;
// ParseDataTransNoForAdjustCashbakToComboBox;
end;
end;
//procedure TfrmAdjustmentCashback.ParseDataTransNoForAdjustCashbakToComboBox;
//var
// sSQL: string;
// data: TDataSet;
//begin
// with cbpTransNo do
// begin
// ClearGridData;
// RowCount := 3;
// ColCount := 3;
// AddRow(['id','TRANSACTION NO.','TRANSACTION DATE']);
//
// sSQL := 'SELECT ADJCASH_TRANS_NO, TRANS_DATE, ADJCASH_ID '
// + 'FROM ADJUSTMENT_CASHBACK '
// + ' LEFT OUTER JOIN TRANSAKSI ON (TRANS_NO=ADJCASH_TRANS_NO) '
// + ' AND (TRANS_UNT_ID=ADJCASH_TRANS_UNT_ID) '
// + ' WHERE ADJCASH_DATE = ' + QuotD(dtAdjustment.Date)
// + ' AND ADJCASH_UNT_ID = ' + IntToStr(masternewunit.id);
// data := cOpenQuery(sSQL);
//
// if not (data.IsEmpty) then
// begin
// data.Last;
// data.First;
// while not data.Eof do
// begin
// RowCount := data.RecordCount + 2;
// AddRow([data.FieldByName('ADJCASH_ID').AsString,data.FieldByName('ADJCASH_TRANS_NO').AsString,
// FormatDateTime('dd-mm-yyyy',data.FieldByName('TRANS_DATE').AsDateTime)]);
//
// data.Next;
// end;
// end
// else
// begin
// AddRow(['0',' ',' ']);
// end;
//
// FixedRows := 1;
// SizeGridToData;
// ShowSpeedButton := false;
// end;
//end;
procedure TfrmAdjustmentCashback.ParseDetilTransaksiCard;
var
sSQL: string;
// data: TDataSet;
begin
sSQL := 'SELECT * '
+ 'FROM TRANSAKSI '
+ ' INNER JOIN MEMBER ON (MEMBER_ID=TRANS_MEMBER_ID) '
+ ' AND (MEMBER_UNT_ID=TRANS_MEMBER_UNT_ID) '
+ ' INNER JOIN BEGINNING_BALANCE ON (BALANCE_ID=TRANS_BALANCE_ID) '
+ ' AND (BALANCE_UNT_ID=TRANS_BALANCE_UNT_ID) '
+ ' INNER JOIN AUT$USER ON (USR_ID=BALANCE_USR_ID) '
+ ' AND (USR_UNT_ID=BALANCE_USR_UNT_ID) '
+ ' INNER JOIN SETUPPOS ON (SETUPPOS_ID=BALANCE_SETUPPOS_ID) '
+ ' AND (SETUPPOS_UNT_ID=BALANCE_SETUPPOS_UNT_ID) '
+ ' INNER JOIN SHIFT ON (SHIFT_ID=BALANCE_SHIFT_ID) '
+ ' AND (SHIFT_UNT_ID=BALANCE_SHIFT_UNT_ID) '
+ ' LEFT OUTER JOIN TRANSAKSI_CARD ON (TRANSC_TRANS_NO=TRANS_NO) '
+ ' AND (TRANSC_TRANS_UNT_ID=TRANS_UNT_ID) '
+ ' LEFT OUTER JOIN REF$CREDIT_CARD ON (CARD_ID=TRANSC_CARD_ID) '
+ ' AND (CARD_UNT_ID=TRANSC_CARD_UNT_ID) '
+ ' WHERE TRANS_NO = ' + QuotedStr(edtNoTrans.Text)
+ ' AND TRANS_UNT_ID = ' + IntToStr(masternewunit);
{
data := cOpenQuery(sSQL);
if not (data.IsEmpty) then
begin
with data do
begin
First;
edtMemberCode.Text := FieldByName('MEMBER_CARD_NO').AsString;
edtMemberName.Text := FieldByName('MEMBER_NAME').AsString;
edtCashierCode.Text := FieldByName('USR_USERNAME').AsString;
edtCashierName.Text := FieldByName('USR_FULLNAME').AsString;
edtPOSCode.Text := FieldByName('SETUPPOS_TERMINAL_CODE').AsString;
edtShiftCode.Text := FieldByName('SHIFT_NAME').AsString;
edtCardCode.Text := FieldByName('CARD_CODE').AsString;
edtCardNo.Text := FieldByName('TRANSC_NOMOR').AsString;
edtCardName.Text := FieldByName('CARD_NAME').AsString;
edtCardAuthorize.Text := FieldByName('TRANSC_NO_OTORISASI').AsString;
dtTransact.Date := FieldByName('TRANS_DATE').AsDateTime;
curredtTotalTransact.Value := FieldByName('TRANS_TOTAL_TRANSACTION').AsCurrency;
curredtPaymentCard.Value := FieldByName('TRANS_BAYAR_CARD').AsCurrency;
curredtCashbackBefore.Value := FieldByName('TRANSC_CASHBACK_NILAI').AsCurrency;
end;
end;
}
end;
procedure TfrmAdjustmentCashback.ParseDetilAdjustment;
begin
{
with TAdjustmentCashback.CreateWithUser(Self,FLoginId,masternewunit.id) do
begin
try
if LoadByID(FidAdj,masternewunit.id) then
begin
curredtAdjustValue.Value := Value;
edtNote.Text := Note;
curredtCashbackActually.Value := Actually;
end;
finally
Free;
end;
end; // with
}
end;
//procedure TfrmAdjustmentCashback.ClearData;
//begin
// edtMemberCode.Clear;
// edtMemberName.Clear;
// edtCashierCode.Clear;
// edtCashierName.Clear;
// edtPOSCode.Clear;
// edtShiftCode.Clear;
//
// edtCardCode.Clear;
// edtCardNo.Clear;
// edtCardName.Clear;
// edtCardAuthorize.Clear;
//
// dtTransact.Clear;
// curredtTotalTransact.Clear;
// curredtPaymentCard.Clear;
// curredtCashbackBefore.Clear;
//
// curredtAdjustValue.Clear;
// edtNote.Clear;
// curredtCashbackActually.Clear;
//end;
procedure TfrmAdjustmentCashback.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
if ((Key = vk_F5) or (Key = vk_return)) then
LookUpData(ActiveControl, Key);
end;
function TfrmAdjustmentCashback.GetIDAdj: Integer;
//var
// iAid: Integer;
// sSQL: string;
begin
Result := 0;
// sSQL := 'SELECT ADJCASH_ID, ADJCASH_TRANS_NO, TRANS_DATE '
// + 'FROM ADJUSTMENT_CASHBACK '
// + ' LEFT OUTER JOIN TRANSAKSI ON (TRANS_NO=ADJCASH_TRANS_NO) '
// + ' AND (TRANS_UNT_ID=ADJCASH_TRANS_UNT_ID) '
// + ' WHERE ADJCASH_DATE = ' + TApputils.QuotD(dtAdjustment.Date)
// + ' AND ADJCASH_UNT_ID = ' + IntToStr(masternewunit)
// + ' and ADJCASH_TRANS_NO = '+ QuotedStr(edtNoTrans.Text);
{
with cOpenQuery(sSQL) do
begin
try
if not Eof then
begin
iAid := Fields[0].AsInteger;
end
else
iAid := 0;
finally
Free;
end;
end;
Result := iAid;
}
end;
procedure TfrmAdjustmentCashback.LookUpData(sender:TObject; Key: Word);
var
sSQL: string;
begin
if sender = edtNoTrans then
begin
if Key = vk_F5 then
begin
FidAdj := 0;
sSQL := 'SELECT ADJCASH_TRANS_NO, TRANS_DATE, ADJCASH_ID '
+ 'FROM ADJUSTMENT_CASHBACK '
+ ' LEFT OUTER JOIN TRANSAKSI ON (TRANS_NO=ADJCASH_TRANS_NO) '
+ ' AND (TRANS_UNT_ID=ADJCASH_TRANS_UNT_ID) '
+ ' WHERE ADJCASH_DATE = ' + TApputils.QuotD(dtAdjustment.Date)
+ ' AND ADJCASH_UNT_ID = ' + IntToStr(masternewunit);
{
with cLookUp('Data Adjustment Cashback', sSQL, 200, 2,True) do
begin
if Strings[0] <> '' then
begin
edtNoTrans.Text := Strings[0];
FidAdj := StrToInt(Strings[2]);
LookUpData(Sender, VK_RETURN);
end
else
ClearData;
end;
}
end
else if Key = vk_Return then
begin
ParseDetilTransaksiCard;
ParseDetilAdjustment;
if FidAdj = 0 then
FidAdj := GetIDAdj;
end;
end;
end;
end.
|
unit SConsts;
interface
const
AppKey = 'f1039cf84261ac615fa8221e7938a42d'; // Идентификатор приложения
// Параметры авторизации
DisplayApp = 'page'; // Внешний вид формы мобильных приложений. Допустимые значения:
// "page" — Страница
// "popup" — Всплывающее окно
Expires_at = 604800; // Срок действия access_token в формате UNIX. Также можно указать дельту в секундах.
// Срок действия и дельта не должны превышать две недели, начиная с настоящего времени.
Nofollow = 1; // При передаче параметра nofollow=1 переадресация не происходит. URL возвращается в ответе.
// По умолчанию: 0. Минимальное значение: 0. Максимальное значение: 1.
RedirectURL = 'https://developers.wargaming.net/reference/all/wot/auth/login/'; // URL на который будет переброшен пользователь
// после того как он пройдет аутентификацию.
// По умолчанию: api.worldoftanks.ru/wot//blank/
AuthURL = 'https://api.worldoftanks.ru/wot/auth/login/?application_id=%s&display=%s&expires_at=%s&nofollow=%d'; // URL для запроса
// Коды ошибок авторизации
AUTH_CANCEL = 401; // Пользователь отменил авторизацию для приложения
AUTH_EXPIRED = 403; // Превышено время ожидания авторизации пользователя
AUTH_ERROR = 410; // Ошибка аутентификации
implementation
end.
|
unit LiteScrollbar;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, uColorTheme, LiteButton;
const SB_BAR_DEFAULT_WIDTH = 19;
type MoveResponse = procedure(Shift: TShiftState; X, Y: Integer) of object;
{
Lite Scrollbar
}
type TLiteScrollbar = class(TPanel, IUnknown, IThemeSupporter)
private
theme: ColorTheme;
bar: TLiteButton;
// used when drag starts
savedY: integer;
thumbMovedEvent: MoveResponse;
// Crutch
userValidateStateTrigger: boolean;
procedure updateSelfColors();
// thumb events
procedure startThumbDrag(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure doThumbDrag(Sender: TObject; Shift: TShiftState; X, Y: Integer);
// Crutch
procedure userValidateStateWrite(b: boolean);
protected
procedure Loaded(); override;
procedure Resize(); override;
public
constructor Create(AOwner: TComponent); override;
// IThemeSupporter
procedure setTheme(theme: ColorTheme);
function getTheme(): ColorTheme;
procedure updateColors();
{
Updates state of component
}
procedure validateState();
{
Must be of [0;1]
}
procedure setSize(h: real);
function getSize(): real;
{
Must be of [0;1]
}
procedure setState(state: real);
function getState(): real;
published
property OnThumbMove: MoveResponse read thumbMovedEvent write thumbMovedEvent;
property __UpdateState: boolean read userValidateStateTrigger write userValidateStateWrite;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Lite', [TLiteScrollbar]);
end;
// thumb event
procedure TLiteScrollbar.startThumbDrag(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
savedY := y;
end;
// thumb event
procedure TLiteScrollbar.doThumbDrag(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var newY: integer;
begin
newY := bar.Top;
if bar.isActive then begin
newY := bar.Top + y - savedY;
if newY < 0 then
newY := 0
else if newY > Height - bar.height then
newY := Height - bar.height;
if Assigned(thumbMovedEvent) then
thumbMovedEvent(Shift, X, Y);
end;
bar.Top := newY;
end;
// Override
constructor TLiteScrollbar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
bar := TLiteButton.Create(self);
bar.Parent := self;
theme := CT_DEFAULT_THEME;
updateSelfColors();
// default styles
BevelOuter := bvNone;
Height := 160;
Width := SB_BAR_DEFAULT_WIDTH;
validateState();
bar.OnMouseDown := startThumbDrag;
bar.OnMouseMove := doThumbDrag;
end;
// Override
procedure TLiteScrollbar.Loaded();
begin
Caption := '';
validateState(); // retrieves last wh from resizes
end;
// Override
procedure TLiteScrollbar.setTheme(theme: ColorTheme);
begin
self.theme := theme; // link
bar.setTheme(theme);
end;
// Override
function TLiteScrollbar.getTheme(): ColorTheme;
begin
getTheme := theme;
end;
// Override
procedure TLiteScrollbar.updateColors();
begin
bar.updateColors();
updateSelfColors();
end;
// Override
procedure TLiteScrollbar.Resize();
begin
inherited Resize;
validateState();
end;
// TLiteScrollbar
procedure TLiteScrollbar.userValidateStateWrite(b: boolean);
begin
validateState();
end;
// TLiteScrollbar
procedure TLiteScrollbar.updateSelfColors();
begin
Color := theme.scrollbarBG;
end;
// TLiteScrollbar
procedure TLiteScrollbar.setSize(h: real);
var newH: real;
begin
newH := h * Height;
if newH > Height then newH := Height
else if newH < 24 then newH := 24;
bar.Height := trunc(newH);
end;
// TLiteScrollbar
function TLiteScrollbar.getSize(): real;
begin
getSize := Height / bar.Height;
end;
// TLiteScrollbar
procedure TLiteScrollbar.setState(state: real);
begin
bar.Top := trunc(state * (Height - bar.Height));
end;
// TLiteScrollbar
function TLiteScrollbar.getState(): real;
begin
if Height <= bar.Height then
getState := 1.0
else
getState := (bar.Top + 0.0) / (Height - bar.Height);
end;
// TLiteScrollbar
procedure TLiteScrollbar.validateState();
begin
bar.Width := Width;
end;
end.
|
unit request_pipeline;
interface
uses kernel, period, get;
type
TRequestPipeline = class(TGet)
protected
period: TPeriod;
ItemNames: names;
wItemsMin, wItemsCount: word;
wStepMin, wStepCount: word;
constructor Create(period: TPeriod; ItemNames: names; wItemsMin, wItemsCount: word);
procedure InitStep;
procedure ShowStep;
procedure NextStep;
procedure ShowPeriod(cwPeriod: word);
function GetStep: word; virtual; abstract;
private
wStep: word;
end;
implementation
uses SysUtils, support;
constructor TRequestPipeline.Create(period: TPeriod; ItemNames: names; wItemsMin, wItemsCount: word);
begin
self.period := period;
self.ItemNames := ItemNames;
self.wItemsMin := wItemsMin;
self.wItemsCount := wItemsCount;
end;
procedure TRequestPipeline.InitStep;
begin
wStep := GetStep;
if wStep > 5 then
wStep := (wStep div 5) * 5;
if wStep = 0 then wStep := 1;
wStepMin := wItemsMin;
if wStepMin + wStep - 1 < wItemsCount then
wStepCount := wStep
else
wStepCount := wItemsCount;
end;
procedure TRequestPipeline.ShowStep;
begin
AddInfo('Чтение данных по ' + ItemNames.Plural.Dative + ' '
+ IntToStr(wStepMin) + '-' + IntToStr(wStepMin + wStepCount - 1)
+ ' (всего ' + IntToStr(wStepCount) + ')');
end;
procedure TRequestPipeline.NextStep;
begin
wStepMin := wStepMin + wStepCount;
if wStepMin + wStep - 1 < wItemsCount then
wStepCount := wStep
else
wStepCount := wItemsCount - wStepMin + 1;
end;
procedure TRequestPipeline.ShowPeriod(cwPeriod: word);
begin
AddInfo('');
AddInfo('Чтение данных за ' + period.GetNames.Singular.Nominative + ' -' + IntToStr(cwPeriod));
AddInfo('');
end;
end.
|
(****************************************************************************
*
* WinLIRC plug-in for jetAudio
*
* Copyright (c) 2016-2021 Tim De Baets
*
****************************************************************************
*
* 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.
*
****************************************************************************
*
* Hotkey command implementations
*
****************************************************************************)
unit JFLircCommands;
interface
uses Windows, Messages, Classes, SysUtils, Common2, JetAudioUtil,
JFLircPluginClass;
type
TJACommand = class
public
constructor Create(Owner: TJFLircPlugin);
procedure Execute; virtual; abstract;
private
fOwner: TJFLircPlugin;
end;
TModeJACommand = class(TJACommand)
public
constructor Create(Owner: TJFLircPlugin; Mode: TJAMode);
procedure Execute; override;
private
fMode: TJAMode;
end;
TStandardJACommand = class(TJACommand)
public
constructor Create(Owner: TJFLircPlugin; LParam: Integer);
procedure Execute; override;
private
fLParam: Integer;
end;
TMenuJACommandBase = class(TJACommand)
protected
procedure TriggerFakeVideoWindowPopupMenu;
function TrackPopupMenuCallback(hMenu: HMENU;
var MenuID: Cardinal): Boolean; virtual; abstract;
end;
TMenuJACommand = class(TMenuJACommandBase)
public
constructor Create(Owner: TJFLircPlugin; MenuID: Integer);
procedure Execute; override;
protected
function TrackPopupMenuCallback(hPopupMenu: HMENU;
var MenuID: Cardinal): Boolean; override;
private
fMenuID: Integer;
end;
TCycleAspectModeCommand = class(TMenuJACommandBase)
public
procedure Execute; override;
protected
function TrackPopupMenuCallback(hPopupMenu: HMENU;
var MenuID: Cardinal): Boolean; override;
end;
TSwitchMonitorCommand = class(TJACommand)
public
constructor Create(Owner: TJFLircPlugin; MonitorIdx: Integer);
destructor Destroy; override;
procedure Execute; override;
private
fMonitors: TList;
fMonitorIdx: Integer;
end;
TExecProcessCommand = class(TJACommand)
public
constructor Create(Owner: TJFLircPlugin; const CmdLine: String);
procedure Execute; override;
private
fCmdLine: String;
end;
implementation
uses JetAudio6_API, JetAudio6_Const, MonitorFunc, MultiMon;
constructor TJACommand.Create(Owner: TJFLircPlugin);
begin
fOwner := Owner;
end;
constructor TModeJACommand.Create(Owner: TJFLircPlugin; Mode: TJAMode);
begin
inherited Create(Owner);
fMode := Mode;
end;
procedure TModeJACommand.Execute;
begin
if fOwner.hWndRemocon <> 0 then begin
SendMessage(fOwner.hWndRemocon, WM_REMOCON_CHANGE_COMPONENT,
JAModes[fMode], 0);
end;
end;
constructor TStandardJACommand.Create(Owner: TJFLircPlugin; LParam: Integer);
begin
inherited Create(Owner);
fLParam := LParam;
end;
procedure TStandardJACommand.Execute;
begin
if fOwner.hWndRemocon <> 0 then
SendMessage(fOwner.hWndRemocon, WM_REMOCON_SENDCOMMAND, 0, fLParam);
end;
procedure TMenuJACommandBase.TriggerFakeVideoWindowPopupMenu;
var
hWndVideo: HWND;
Rect: TRect;
begin
if fOwner.hWndRemocon <> 0 then begin
hWndVideo := JAGetVideoViewerWindow(fOwner.hWndRemocon);
if (hWndVideo <> 0) and ApiHooked then begin
GetWindowRect(hWndVideo, Rect);
fOwner.TrackPopupMenuCallback := TrackPopupMenuCallback;
try
// Must pass the correct cursor coordinates here, otherwise JetAudio
// will show the main, generic context menu instead of the specialized
// video context menu.
SendMessage(hWndVideo, WM_CONTEXTMENU, hWndVideo,
MAKE_X_Y_LPARAM(Rect.Left, Rect.Top));
finally
fOwner.TrackPopupMenuCallback := nil;
end;
end;
end;
end;
constructor TMenuJACommand.Create(Owner: TJFLircPlugin; MenuID: Integer);
begin
inherited Create(Owner);
fMenuID := MenuID;
end;
function TMenuJACommand.TrackPopupMenuCallback(hPopupMenu: HMENU;
var MenuID: Cardinal): Boolean;
begin
Result := False; // prevent popup menu from being actually shown
MenuID := fMenuID;
end;
procedure TMenuJACommand.Execute;
begin
TriggerFakeVideoWindowPopupMenu;
end;
const
InvalidAspectMode = eAspectMode(-1);
function TCycleAspectModeCommand.TrackPopupMenuCallback(hPopupMenu: HMENU;
var MenuID: Cardinal): Boolean;
function GetSelectedAspectMode(hSubMenu: HMENU): eAspectMode; overload;
var
AspectMode: eAspectMode;
State: Integer;
begin
Result := InvalidAspectMode;
if hSubMenu = 0 then
Exit;
for AspectMode := Low(eAspectMode) to High(eAspectMode) do begin
State := GetMenuState(hSubMenu, AspectMenuIDs[AspectMode], MF_BYCOMMAND);
if State = -1 then begin
// Menu item does not exist, probably the wrong submenu
Exit;
end;
if State and MF_CHECKED <> 0 then begin
Result := AspectMode;
Exit;
end;
end;
end;
function GetSelectedAspectMode: eAspectMode; overload;
var
MenuCount, i: Integer;
begin
Result := InvalidAspectMode;
MenuCount := GetMenuItemCount(hPopupMenu);
for i := 0 to MenuCount - 1 do begin
Result := GetSelectedAspectMode(GetSubMenu(hPopupMenu, i));
if Result <> InvalidAspectMode then
Break;
end;
end;
var
AspectMode: eAspectMode;
begin
Result := False; // prevent popup menu from being actually shown
AspectMode := GetSelectedAspectMode;
if AspectMode = InvalidAspectMode then
AspectMode := ASPECTMODE_ORG
else
Inc(AspectMode);
if AspectMode > High(eAspectMode) then
AspectMode := Low(eAspectMode);
MenuID := AspectMenuIDs[AspectMode];
end;
procedure TCycleAspectModeCommand.Execute;
begin
TriggerFakeVideoWindowPopupMenu;
end;
constructor TSwitchMonitorCommand.Create(Owner: TJFLircPlugin;
MonitorIdx: Integer);
begin
inherited Create(Owner);
fMonitors := TList.Create;
fMonitorIdx := MonitorIdx;
end;
destructor TSwitchMonitorCommand.Destroy;
begin
FreeAndNil(fMonitors);
end;
procedure TSwitchMonitorCommand.Execute;
procedure ToggleFullScreen;
begin
SendMessage(fOwner.hWndRemocon, WM_REMOCON_SENDCOMMAND, 0,
MAKELPARAM(JRC_ID_CHANGE_SCREEN_SIZE, 0));
end;
var
hWndVideo: HWND;
FullScreen: Boolean;
CurrentMon: HMONITOR;
CurrentMonIdx, NewMonIdx: Integer;
MonInfo: MonitorInfo;
VideoRect: TRect;
MonitorWidth, MonitorHeight, VideoWidth, VideoHeight: Integer;
begin
if fOwner.hWndRemocon = 0 then
Exit;
hWndVideo := JAGetVideoWindow(fOwner.hWndRemocon);
if hWndVideo = 0 then
Exit;
if not GetDisplayMonitors(fMonitors) then
Exit;
if fMonitors.Count <= 1 then
Exit;
if fMonitorIdx >= fMonitors.Count then
Exit;
CurrentMon := MonitorFromWindow(hWndVideo, MONITOR_DEFAULTTOPRIMARY);
CurrentMonIdx := fMonitors.IndexOf(Pointer(CurrentMon));
if fMonitorIdx = -1 then
NewMonIdx := CurrentMonIdx + 1
else
NewMonIdx := fMonitorIdx;
if NewMonIdx >= fMonitors.Count then
NewMonIdx := 0;
if CurrentMonIdx = NewMonIdx then
Exit;
FillChar(MonInfo, SizeOf(MonInfo), 0);
MonInfo.cbSize := SizeOf(MonInfo);
if not GetMonitorInfo(HMONITOR(fMonitors[NewMonIdx]), @MonInfo) then
Exit;
if not GetWindowRect(hWndVideo, VideoRect) then
Exit;
FullScreen := (SendMessage(fOwner.hWndRemocon, WM_REMOCON_GETSTATUS, 0,
GET_STATUS_SCREEN_MODE) = 1);
if FullScreen then
ToggleFullScreen;
try
MonitorWidth := MonInfo.rcWork.Right - MonInfo.rcWork.Left;
MonitorHeight := MonInfo.rcWork.Bottom - MonInfo.rcWork.Top;
VideoWidth := VideoRect.Right - VideoRect.Left;
VideoHeight := VideoRect.Bottom - VideoRect.Top;
{ For some reason, SetWindowPos doesn't seem to work correctly when in full
screen mode }
{SetWindowPos(hWndVideo, 0,
Round(MonInfo.rcWork.Left + (MonitorWidth - VideoWidth) / 2),
Round(MonInfo.rcWork.Top + (MonitorHeight - VideoHeight) / 2),
0, 0,
SWP_NOSIZE or SWP_NOZORDER or SWP_FRAMECHANGED);}
MoveWindow(hWndVideo,
Round(MonInfo.rcWork.Left + (MonitorWidth - VideoWidth) / 2),
Round(MonInfo.rcWork.Top + (MonitorHeight - VideoHeight) / 2),
VideoWidth, VideoHeight, True);
finally
if FullScreen then
ToggleFullScreen;
end;
end;
constructor TExecProcessCommand.Create(Owner: TJFLircPlugin;
const CmdLine: String);
begin
inherited Create(Owner);
fCmdLine := CmdLine;
end;
procedure TExecProcessCommand.Execute;
begin
RunCmdLine(fCmdLine);
end;
end.
|
//
// Generated by JavaToPas v1.4 20140526 - 133130
////////////////////////////////////////////////////////////////////////////////
unit org.apache.http.conn.params.ConnPerRouteBean;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
org.apache.http.conn.routing.HttpRoute;
type
JConnPerRouteBean = interface;
JConnPerRouteBeanClass = interface(JObjectClass)
['{8B5F1D04-BBE6-44AB-80AA-8056AF30234B}']
function _GetDEFAULT_MAX_CONNECTIONS_PER_ROUTE : Integer; cdecl; // A: $19
function getDefaultMax : Integer; cdecl; // ()I A: $1
function getMaxForRoute(route : JHttpRoute) : Integer; cdecl; // (Lorg/apache/http/conn/routing/HttpRoute;)I A: $1
function init : JConnPerRouteBean; cdecl; overload; // ()V A: $1
function init(defaultMax : Integer) : JConnPerRouteBean; cdecl; overload; // (I)V A: $1
procedure setDefaultMaxPerRoute(max : Integer) ; cdecl; // (I)V A: $1
procedure setMaxForRoute(route : JHttpRoute; max : Integer) ; cdecl; // (Lorg/apache/http/conn/routing/HttpRoute;I)V A: $1
procedure setMaxForRoutes(map : JMap) ; cdecl; // (Ljava/util/Map;)V A: $1
property DEFAULT_MAX_CONNECTIONS_PER_ROUTE : Integer read _GetDEFAULT_MAX_CONNECTIONS_PER_ROUTE;// I A: $19
end;
[JavaSignature('org/apache/http/conn/params/ConnPerRouteBean')]
JConnPerRouteBean = interface(JObject)
['{0183A11B-33E0-46C1-A4D7-0325192AFD3E}']
function getDefaultMax : Integer; cdecl; // ()I A: $1
function getMaxForRoute(route : JHttpRoute) : Integer; cdecl; // (Lorg/apache/http/conn/routing/HttpRoute;)I A: $1
procedure setDefaultMaxPerRoute(max : Integer) ; cdecl; // (I)V A: $1
procedure setMaxForRoute(route : JHttpRoute; max : Integer) ; cdecl; // (Lorg/apache/http/conn/routing/HttpRoute;I)V A: $1
procedure setMaxForRoutes(map : JMap) ; cdecl; // (Ljava/util/Map;)V A: $1
end;
TJConnPerRouteBean = class(TJavaGenericImport<JConnPerRouteBeanClass, JConnPerRouteBean>)
end;
const
TJConnPerRouteBeanDEFAULT_MAX_CONNECTIONS_PER_ROUTE = 2;
implementation
end.
|
unit FindUnit.AutoImport;
interface
uses
IniFiles, SysUtils, Log4Pascal, Classes;
type
TAutoImport = class(TObject)
private
FIniFilePath: string;
FSearchMemory: TIniFile;
procedure LoadIniFile;
procedure SaveIniFile;
function LoadClassesToImport: TStringList;
public
constructor Create(IniFilePath: string);
destructor Destroy; override;
procedure Load;
function GetMemorizedUnit(Search: string; out MemUnit: string): Boolean;
procedure SetMemorizedUnit(NameClass, MemUnit: string);
function LoadUnitListToImport: TStringList;
end;
implementation
uses
FindUnit.OTAUtils, ToolsAPI, FindUnit.Utils;
const
SECTION = 'MEMORIZEDUNIT';
{ TAutoImport }
constructor TAutoImport.Create(IniFilePath: string);
begin
inherited Create;
FIniFilePath := IniFilePath;
end;
destructor TAutoImport.Destroy;
begin
inherited;
end;
function TAutoImport.GetMemorizedUnit(Search: string; out MemUnit: string): Boolean;
begin
Result := False;
Search := UpperCase(Search);
MemUnit := FSearchMemory.ReadString(SECTION, Search, '');
Result := MemUnit <> '';
end;
function TAutoImport.LoadUnitListToImport: TStringList;
var
ClassesList: TStringList;
ClassItem: string;
UnitItem: string;
begin
Result := TStringList.Create;
Result.Duplicates := dupIgnore;
Result.Sorted := True;
ClassesList := LoadClassesToImport;
try
for ClassItem in ClassesList do
begin
UnitItem := FSearchMemory.ReadString(SECTION, ClassItem, '');
if UnitItem <> '' then
Result.Add(UnitItem);
end;
finally
ClassesList.Free;
end;
end;
procedure TAutoImport.Load;
begin
LoadIniFile;
end;
procedure TAutoImport.LoadIniFile;
var
DirPath: string;
begin
Logger.Debug('TAutoImport.LoadIniFile: %s', [FIniFilePath]);
DirPath := ExtractFilePath(FIniFilePath);
ForceDirectories(DirPath);
FSearchMemory := TIniFile.Create(FIniFilePath);
end;
function TAutoImport.LoadClassesToImport: TStringList;
var
Errors: TOTAErrors;
ErrorItem: TOTAError;
Item: string;
function GetUndeclaredIdentifier(Text: string): string;
const
ERROR_CODE = 'Undeclared identifier';
begin
Result := '';
if Pos(ERROR_CODE, Text) = 0 then
Exit;
Fetch(Text, #39);
Result := Fetch(Text, #39);
end;
begin
Result := TStringList.Create;
Errors := GetErrorListFromActiveModule;
for ErrorItem in Errors do
begin
Item := GetUndeclaredIdentifier(ErrorItem.Text);
if Item = '' then
Continue;
Result.Add(UpperCase(Item));
end
end;
procedure TAutoImport.SaveIniFile;
begin
FSearchMemory.UpdateFile;
end;
procedure TAutoImport.SetMemorizedUnit(NameClass, MemUnit: string);
begin
NameClass := UpperCase(NameClass);
FSearchMemory.WriteString(SECTION, NameClass, MemUnit);
SaveIniFile;
end;
end.
|
Program Example14;
uses Crt;
{ Program to demonstrate the LowVideo, HighVideo, NormVideo functions. }
begin
textColor(red);
LowVideo;
WriteLn('This is written with LowVideo');
HighVideo;
WriteLn('This is written with HighVideo');
NormVideo;
WriteLn('This is written with NormVideo');
end.
|
unit TimeTrackerLog.TextFile;
interface
uses
TimeTrackerLogInterface,
FileLoggerInterface,
Classes,
SysUtils;
type
TTimeTrackerLog = class(TInterfacedObject,ITimeTrackerLog, IFileLogger)
private
FLogDate :TDateTime;
FDailyLog :TStringList;
FDailyLogFileName :TFileName;
function GetLogFileName: string;
function GetFileName :string;
public
procedure WriteLogEntry(const TimeStamp :TDateTime; const Description :string);
procedure ReadLogEntries(Items :TStrings; const MaxEntries :integer);
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
end;
implementation
uses
Vcl.Forms;
{ TTimeTrackerLog }
procedure TTimeTrackerLog.AfterConstruction;
begin
inherited;
FDailyLog := TStringList.Create;
FLogDate := Now;
FDailyLogFileName := GetLogFileName;
//if the file exists, re-load it so we only create 1 file per day and we never lose information if user exits or program crashes
if FileExists(FDailyLogFileName) then
FDailyLog.LoadFromFile(FDailyLogFileName);
end;
procedure TTimeTrackerLog.BeforeDestruction;
begin
FDailyLog.Free;
inherited;
end;
function TTimeTrackerLog.GetFileName: string;
begin
Result := IncludeTrailingPathDelimiter(ExtractFilePath(Application.EXEName)) + GetLogFileName;
end;
function TTimeTrackerLog.GetLogFileName :string;
begin
Result := FormatDateTime('yyyymmdd',FLogDate)+ ' TimeTrackerLog.txt';
end;
procedure TTimeTrackerLog.ReadLogEntries(Items: TStrings; const MaxEntries: integer);
//copies the text from MaxEntries from the end of the log (most recent ones) to the Items passed.
var
Entries :TStringList;
J,
I: Integer;
Sections :TArray<string>;
FileName :string;
begin
Items.Clear;
FileName := GetLogFileName;
if not FileExists(FileName) then
Exit;
Entries := TStringList.Create;
Entries.LoadFromFile(GetLogFileName);
J := Entries.Count - 1;
for I := 1 to MaxEntries do
begin
if J >= 0 then
begin
//parse out the description portion only
Sections := Entries[J].Split(['|']);
Items.Add(Trim(Sections[1]));
Dec(J,1);
end;
end;
end;
procedure TTimeTrackerLog.WriteLogEntry(const TimeStamp: TDateTime; const Description: string);
begin
//check if logging has spanned a daily boundary
if Trunc(FLogDate) <> Trunc(TimeStamp) then
begin
//save the current entries
FDailyLog.SaveToFile(FDailyLogFileName);
//generate a new log filename and re-start the buffering
FDailyLog.Clear;
FLogDate := TimeStamp;
FDailyLogFileName := GetLogFileName;
end;
//if the description is the same do not create a log entry
if ((FDailyLog.Count > 0) and not FDailyLog[FDailyLog.Count-1].Contains(Description)) or (FDailyLog.Count = 0) then
begin
FDailyLog.Add(DateTimeToStr(TimeStamp)+' | '+Description);
FDailyLog.SaveToFile(FDailyLogFileName);
end;
end;
end.
|
unit BooksView;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
IslUtils, Htmlview, ExtCtrls, ComCtrls, AmlView;
type
TInstalledBooksForm = class(TForm)
BooksTree: TTreeView;
Splitter1: TSplitter;
InfoViewer: THTMLViewer;
procedure BooksTreeClick(Sender: TObject);
public
procedure Populate(const APaths : String; const ByName, ById, ByType : TObjDict);
end;
var
InstalledBooksForm: TInstalledBooksForm;
implementation
{$R *.DFM}
procedure TInstalledBooksForm.Populate(const APaths : String; const ByName, ById, ByType : TObjDict);
procedure FillTree(const ARoot : TTreeNode; AList : TObjDict);
var
I : Integer;
begin
if AList.Count <= 0 then
Exit;
for I := 0 to AList.Count-1 do
BooksTree.Items.AddChildObject(ARoot, AList[I], AList.Objects[I]);
end;
var
ByTypeItem : TTreeNode;
I : Integer;
begin
BooksTree.Items.Clear;
Assert(ByName <> Nil);
Assert(ById <> Nil);
Assert(ByType <> Nil);
FillTree(BooksTree.Items.AddChild(Nil, 'Books By FileName'), ByName);
FillTree(BooksTree.Items.AddChild(Nil, 'Books By Id'), ById);
ByTypeItem := BooksTree.Items.AddChild(Nil, 'Books By Type');
if ByType.Count > 0 then begin
for I := 0 to ByType.Count-1 do
FillTree(BooksTree.Items.AddChild(ByTypeItem, ByType[I]), ByType.Objects[I] as TObjDict);
end;
end;
procedure TInstalledBooksForm.BooksTreeClick(Sender: TObject);
const
PropertyRowFmt = '<tr valign=top bgcolor="%2:s"><td align="right">%0:s</td><td><font color="navy"><b>%1:s</b></font></td></tr>';
var
AmlData : TAmlData;
Html : String;
procedure ShowProperty(const APropertyName, APropertyValue : String);
begin
Html := Html + Format(PropertyRowFmt, [APropertyName, APropertyValue, 'white']);
end;
begin
AmlData := TAmlData(BooksTree.Selected.Data);
if AmlData = Nil then
Exit;
Html := '';
ShowProperty('Id', AmlData.Id);
ShowProperty('ContentType', AmlData.ContentType);
ShowProperty('Name', AmlData.Name);
ShowProperty('ShortName', AmlData.ShortName);
Html := '<table cellspacing=0 cellpadding=3>'+Html+'</table>';
InfoViewer.LoadFromBuffer(PChar(Html), Length(Html));
end;
end.
|
unit uFormListView;
interface
uses
System.Classes,
Winapi.Windows,
Vcl.Graphics,
Vcl.Controls,
EasyListview,
uThreadForm,
uDBDrawing,
uListViewUtils,
uFormInterfaces;
type
TListViewForm = class(TThreadForm, IImageSource)
protected
function GetListView: TEasyListview; virtual;
function IsSelectedVisible: Boolean;
function IsFocusedVisible: Boolean;
procedure CreateParams(var Params: TCreateParams); override;
{ IImageSource }
function GetImage(FileName: string; Bitmap: TBitmap; var Width: Integer; var Height: Integer): Boolean;
function InternalGetImage(FileName: string; Bitmap: TBitmap; var Width: Integer; var Height: Integer): Boolean; virtual;
public
function GetFilePreviw(FileName: string; Bitmap: TBitmap;
var Width: Integer; var Height: Integer): Boolean; virtual;
end;
implementation
{ TListViewForm }
function TListViewForm.GetFilePreviw(FileName: string;
Bitmap: TBitmap; var Width: Integer; var Height: Integer): Boolean;
begin
Result := GetImage(FileName, Bitmap, Width, Height);
end;
function TListViewForm.GetListView: TEasyListview;
begin
Result := nil;
end;
function TListViewForm.GetImage(FileName: string; Bitmap: TBitmap; var Width: Integer; var Height: Integer): Boolean;
begin
Result := InternalGetImage(FileName, Bitmap, Width, Height);
end;
function TListViewForm.InternalGetImage(FileName: string; Bitmap: TBitmap; var Width: Integer; var Height: Integer): Boolean;
begin
Result := False;
end;
function TListViewForm.IsFocusedVisible: Boolean;
var
R: TRect;
Rv: TRect;
ElvMain : TEasyListview;
begin
ElvMain := GetListView;
Result := False;
if ElvMain.Selection.FocusedItem <> nil then
begin
Rv := ElvMain.Scrollbars.ViewableViewportRect;
R := Rect(ElvMain.ClientRect.Left + Rv.Left, ElvMain.ClientRect.Top + Rv.Top, ElvMain.ClientRect.Right + Rv.Left,
ElvMain.ClientRect.Bottom + Rv.Top);
Result := RectInRect(R, TEasyCollectionItemX(ElvMain.Selection.FocusedItem).GetDisplayRect);
end;
end;
function TListViewForm.IsSelectedVisible: Boolean;
var
I: Integer;
R: TRect;
Rv: TRect;
ElvMain : TEasyListview;
begin
ElvMain := GetListView;
Result := False;
Rv := ElvMain.Scrollbars.ViewableViewportRect;
for I := 0 to ElvMain.Items.Count - 1 do
begin
R := Rect(ElvMain.ClientRect.Left + Rv.Left, ElvMain.ClientRect.Top + Rv.Top, ElvMain.ClientRect.Right + Rv.Left,
ElvMain.ClientRect.Bottom + Rv.Top);
if RectInRect(R, TEasyCollectionItemX(ElvMain.Items[I]).GetDisplayRect) then
begin
if ElvMain.Items[I].Selected then
begin
Result := True;
Exit;
end;
end;
end;
end;
procedure TListViewForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.WndParent := GetDesktopWindow;
with Params do
ExStyle := ExStyle or WS_EX_APPWINDOW;
end;
end.
|
unit AVL;
interface
{$IFDEF FPC}
{$MODE DELPHIUNICODE}
{$ENDIF}
uses SysUtils, Classes, Math;
type
TAVLTree<TKey, TData> = class(TObject)
public
type
PAVLNode = ^TAVLNode;
TAVLNode = record
private
FChilds: array[Boolean] of PAVLNode; {Child nodes}
FBalance: Integer; {Used during balancing}
public
Key: TKey;
Data: TData;
end;
TKeys = array of TKey;
TValues = array of TData;
TSortOrder = (soASC, soDESC);
TIterateFunc = function(Node: PAVLNode; OtherData: Pointer): Boolean of object;
TCompareFunc = {$IFNDEF FPC}reference to {$ENDIF}function(const NodeKey1, NodeKey2: TKey): NativeInt;
strict private
const
StackSize = 40;
Left = False;
Right = True;
type
TStackNode = record
Node : PAVLNode;
Comparison : Integer;
end;
TStackArray = array[1..StackSize] of TStackNode;
private
FCount: Integer;
FRoot: PAVLNode; {Root of tree}
FCompareFunc: TCompareFunc;
class procedure InsBalance(var P: PAVLNode; var SubTreeInc: Boolean; CmpRes: Integer); static;
class procedure DelBalance(var P: PAVLNode; var SubTreeDec: Boolean; CmpRes: Integer); static;
function FreeNode(Node: PAVLNode; OtherData : Pointer): Boolean; inline;
protected
class function DoCreateNode(const Key: TKey; const Data: TData): PAVLNode; virtual;
class procedure DoFreeNode(var Key: TKey; var Data: TData); virtual;
public
constructor Create(const CompareFunc: TCompareFunc);
destructor Destroy; override;
///////////////////////////////////////////////////////////////////////////////////////////////
procedure Clear;
procedure Delete(const Key: TKey);
procedure CopyFrom(const Tree: TAVLTree<TKey, TData>);
function InsertNode(const Key: TKey; const Data: TData): PAVLNode;
function Find(const Key: TKey): PAVLNode;
function TryGetValue(const Key: TKey; out Value: TData): Boolean; overload;
function TryGetValue<TDataCast: TData>(const Key: TKey; out Value: TDataCast): Boolean; overload;
function Iterate(Action: TIterateFunc; Up: Boolean; OtherData: Pointer): PAVLNode;
function First: PAVLNode; inline;
function Last: PAVLNode; inline;
function Next(N: PAVLNode): PAVLNode;
function Prev(N: PAVLNode): PAVLNode;
property Count: Integer read FCount;
property Root: PAVLNode read FRoot;
function Keys(SortOrder: TSortOrder = soASC): TKeys;
function Values(SortOrder: TSortOrder = soASC): TValues;
end;
{======================================================================}
function Sign(I: Integer): Integer; inline; // faster then Math.Sign.
implementation
{$IFDEF ThreadSafe}
var
ClassCritSect: TRTLCriticalSection;
{$ENDIF}
function Sign(I: Integer): Integer; inline; // faster then Math.Sign.
begin
if I < 0 then
Sign := -1
else if I > 0 then
Sign := +1
else
Sign := 0;
end;
procedure TAVLTree<TKey, TData>.CopyFrom(const Tree: TAVLTree<TKey, TData>);
var
Node: PAVLNode;
begin
Node := Tree.First;
while Assigned(Node) do
begin
InsertNode(Node.Key, Node.Data);
Node := Tree.Next(Node);
end;
end;
constructor TAVLTree<TKey, TData>.Create(const CompareFunc: TCompareFunc);
begin
FCompareFunc := CompareFunc;
end;
class procedure TAVLTree<TKey, TData>.DelBalance(var P: PAVLNode; var SubTreeDec: Boolean; CmpRes: Integer);
var
P1, P2 : PAVLNode;
B1, B2 : Integer;
LR : Boolean;
begin
CmpRes := Sign(CmpRes);
if P.FBalance = CmpRes then
P.FBalance := 0
else if P.FBalance = 0 then begin
P.FBalance := -CmpRes;
SubTreeDec := False;
end else begin
LR := (CmpRes < 0);
P1 := P.FChilds[LR];
B1 := P1.FBalance;
if (B1 = 0) or (B1 = -CmpRes) then begin
{Single RR or LL rotation}
P.FChilds[LR] := P1.FChilds[not LR];
P1.FChilds[not LR] := P;
if B1 = 0 then begin
P.FBalance := -CmpRes;
P1.FBalance := CmpRes;
SubTreeDec := False;
end else begin
P.FBalance := 0;
P1.FBalance := 0;
end;
P := P1;
end else begin
{Double RL or LR rotation}
P2 := P1.FChilds[not LR];
B2 := P2.FBalance;
P1.FChilds[not LR] := P2.FChilds[LR];
P2.FChilds[LR] := P1;
P.FChilds[LR] := P2.FChilds[not LR];
P2.FChilds[not LR] := P;
if B2 = -CmpRes then
P.FBalance := CmpRes
else
P.FBalance := 0;
if B2 = CmpRes then
P1.FBalance := -CmpRes
else
P1.FBalance := 0;
P := P2;
P2.FBalance := 0;
end;
end;
end;
class procedure TAVLTree<TKey, TData>.InsBalance(var P: PAVLNode; var SubTreeInc: Boolean; CmpRes: Integer);
var
P1 : PAVLNode;
P2 : PAVLNode;
LR : Boolean;
begin
CmpRes := Sign(CmpRes);
if P.FBalance = -CmpRes then begin
P.FBalance := 0;
SubTreeInc := False;
end else if P.FBalance = 0 then
P.FBalance := CmpRes
else begin
LR := (CmpRes > 0);
P1 := P.FChilds[LR];
if P1.FBalance = CmpRes then begin
P.FChilds[LR] := P1.FChilds[not LR];
P1.FChilds[not LR] := P;
P.FBalance := 0;
P := P1;
end else begin
P2 := P1.FChilds[not LR];
P1.FChilds[not LR] := P2.FChilds[LR];
P2.FChilds[LR] := P1;
P.FChilds[LR] := P2.FChilds[not LR];
P2.FChilds[not LR] := P;
if P2.FBalance = CmpRes then
P.FBalance := -CmpRes
else
P.FBalance := 0;
if P2.FBalance = -CmpRes then
P1.FBalance := CmpRes
else
P1.FBalance := 0;
P := P2;
end;
P.FBalance := 0;
SubTreeInc := False;
end;
end;
procedure TAVLTree<TKey, TData>.Clear;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Iterate(FreeNode, True, nil);
FRoot := nil;
FCount := 0;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TAVLTree<TKey, TData>.Delete(const Key: TKey);
var
P : PAVLNode;
Q : PAVLNode;
TmpData : TData;
CmpRes : Integer;
Found : Boolean;
SubTreeDec : Boolean;
StackP : Integer;
Stack : TStackArray;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
P := FRoot;
if not Assigned(P) then
Exit;
{Find node to delete and stack the nodes to reach it}
Found := False;
StackP := 0;
while not Found do begin
CmpRes := FCompareFunc(P.Key, Key);
Inc(StackP);
if CmpRes = 0 then begin
{Found node to delete}
with Stack[StackP] do begin
Node := P;
Comparison := -1;
end;
Found := True;
end else begin
with Stack[StackP] do begin
Node := P;
Comparison := CmpRes;
end;
P := P.FChilds[CmpRes > 0];
if not Assigned(P) then
{Node to delete not found}
Exit;
end;
end;
{Delete the node found}
Q := P;
if (not Assigned(Q.FChilds[Right])) or (not Assigned(Q.FChilds[Left])) then begin
{Node has at most one branch}
Dec(StackP);
P := Q.FChilds[Assigned(Q.FChilds[Right])];
if StackP = 0 then
FRoot := P
else with Stack[StackP] do
Node.FChilds[Comparison > 0] := P;
end else begin
{Node has two branches; stack nodes to reach one with no right child}
P := Q.FChilds[Left];
while Assigned(P.FChilds[Right]) do begin
Inc(StackP);
with Stack[StackP] do begin
Node := P;
Comparison := 1;
end;
P := P.FChilds[Right];
end;
{Swap the node to delete with the terminal node}
TmpData := Q.Data;
Q.Data := P.Data;
Q := P;
with Stack[StackP] do begin
Node.FChilds[Comparison > 0].Data := TmpData;
Node.FChilds[Comparison > 0] := P.FChilds[Left];
end;
end;
{Dispose of the deleted node}
FreeNode(Q, nil);
Dec(FCount);
{Unwind the stack and rebalance}
SubTreeDec := True;
while (StackP > 0) and SubTreeDec do begin
if StackP = 1 then
DelBalance(FRoot, SubTreeDec, Stack[1].Comparison)
else with Stack[StackP-1] do
DelBalance(Node.FChilds[Comparison > 0], SubTreeDec, Stack[StackP].Comparison);
dec(StackP);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
destructor TAVLTree<TKey, TData>.Destroy;
begin
{free nodes}
Clear;
inherited;
end;
class function TAVLTree<TKey, TData>.DoCreateNode(const Key: TKey; const Data: TData): PAVLNode;
begin
New(Result);
FillChar(Result^, SizeOf(TAVLNode), #0);
Result.Key := Key;
Result.Data := Data;
end;
class procedure TAVLTree<TKey, TData>.DoFreeNode(var Key: TKey; var Data: TData);
begin
end;
function TAVLTree<TKey, TData>.Find(const Key: TKey): PAVLNode;
var
P: PAVLNode;
CmpRes: Integer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
P := FRoot;
while Assigned(P) do begin
CmpRes := FCompareFunc(P.Key, Key);
if CmpRes = 0 then begin
Result := P;
Exit;
end else
P := P.FChilds[CmpRes > 0];
end;
Result := nil;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TAVLTree<TKey, TData>.First: PAVLNode;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if Count = 0 then
Result := nil
else begin
Result := FRoot;
while Assigned(Result.FChilds[Left]) do
Result := Result.FChilds[Left];
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TAVLTree<TKey, TData>.FreeNode(Node: PAVLNode; OtherData: Pointer): Boolean;
begin
with Node^ do
DoFreeNode(Key, Data);
Dispose(Node);
//FreeMem(Node);
Result := True;
end;
function TAVLTree<TKey, TData>.Keys(SortOrder: TSortOrder): TKeys;
var
Node: PAVLNode;
Idx: Integer;
begin
Idx := 0;
SetLength(Result, FCount);
case SortOrder of
soASC: begin
Node := First;
while Assigned(Node) do
begin
Result[Idx] := Node.Key;
Inc(Idx);
Node := Next(Node);
end;
end;
soDESC: begin
Node := Last;
while Assigned(Node) do
begin
Result[Idx] := Node.Key;
Inc(Idx);
Node := Prev(Node);
end;
end;
end;
end;
function TAVLTree<TKey, TData>.Values(SortOrder: TSortOrder): TValues;
var
Node: PAVLNode;
Idx: Integer;
begin
Idx := 0;
SetLength(Result, FCount);
case SortOrder of
soASC: begin
Node := First;
while Assigned(Node) do
begin
Result[Idx] := Node.Data;
Inc(Idx);
Node := Next(Node);
end;
end;
soDESC: begin
Node := Last;
while Assigned(Node) do
begin
Result[Idx] := Node.Data;
Inc(Idx);
Node := Prev(Node);
end;
end;
end;
end;
function TAVLTree<TKey, TData>.Iterate(Action: TIterateFunc; Up: Boolean; OtherData: Pointer): PAVLNode;
var
P : PAVLNode;
Q : PAVLNode;
StackP : Integer;
Stack : TStackArray;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
StackP := 0;
P := FRoot;
repeat
while Assigned(P) do begin
Inc(StackP);
Stack[StackP].Node := P;
P := P.FChilds[not Up];
end;
if StackP = 0 then begin
Result := nil;
Exit;
end;
P := Stack[StackP].Node;
Dec(StackP);
Q := P;
P := P.FChilds[Up];
if not Action(Q, OtherData) then begin
Result := Q;
Exit;
end;
until False;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TAVLTree<TKey, TData>.Last: PAVLNode;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if Count = 0 then
Result := nil
else begin
Result := FRoot;
while Assigned(Result.FChilds[Right]) do
Result := Result.FChilds[Right];
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TAVLTree<TKey, TData>.Next(N: PAVLNode) : PAVLNode;
var
Found : Word;
P : PAVLNode;
StackP : Integer;
Stack : TStackArray;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Result := nil;
Found := 0;
StackP := 0;
P := FRoot;
repeat
while Assigned(P) do begin
Inc(StackP);
Stack[StackP].Node := P;
P := P.FChilds[Left];
end;
if StackP = 0 then
Exit;
P := Stack[StackP].Node;
Dec(StackP);
if Found = 1 then begin
Result := P;
Exit;
end;
if P = N then
Inc(Found);
P := P.FChilds[Right];
until False;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TAVLTree<TKey, TData>.Prev(N: PAVLNode): PAVLNode;
var
Found : Word;
P : PAVLNode;
StackP : Integer;
Stack : TStackArray;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Result := nil;
Found := 0;
StackP := 0;
P := FRoot;
repeat
while Assigned(P) do begin
Inc(StackP);
Stack[StackP].Node := P;
P := P.FChilds[Right];
end;
if StackP = 0 then
Exit;
P := Stack[StackP].Node;
Dec(StackP);
if Found = 1 then begin
Result := P;
Exit;
end;
if P = N then
Inc(Found);
P := P.FChilds[Left];
until False;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
function TAVLTree<TKey, TData>.TryGetValue(const Key: TKey; out Value: TData): Boolean;
begin
var ANode := Find(Key);
if Assigned(ANode) then
begin
Value := ANode.Data;
Result := True;
end else
begin
Value := default(TData);
Result := False;
end;
end;
function TAVLTree<TKey, TData>.TryGetValue<TDataCast>(const Key: TKey; out Value: TDataCast): Boolean;
begin
var ANode := Find(Key);
if Assigned(ANode) then
begin
Value := TDataCast(ANode.Data);
Result := True;
end else
begin
Value := nil;
Result := False;
end;
end;
function TAVLTree<TKey, TData>.InsertNode(const Key: TKey; const Data: TData): PAVLNode;
var
P : PAVLNode;
CmpRes : Integer;
StackP : Integer;
Stack : TStackArray;
SubTreeInc : Boolean;
begin
Result := nil;
{Handle first node}
P := FRoot;
if not Assigned(P) then begin
FRoot := DoCreateNode(Key, Data);
Inc(FCount);
Exit;
end;
{Find where new node should fit in tree}
StackP := 0;
CmpRes := 0; {prevent D32 from generating a warning}
while Assigned(P) do begin
CmpRes := FCompareFunc(P.Key, Key);
if CmpRes = 0 then
{New node matches a node already in the tree, return it}
Exit(P);
Inc(StackP);
with Stack[StackP] do begin
Node := P;
Comparison := CmpRes;
end;
P := P.FChilds[CmpRes > 0];
end;
{Insert new node}
Stack[StackP].Node.FChilds[CmpRes > 0] := DoCreateNode(Key, Data);
Inc(FCount);
{Unwind the stack and rebalance}
SubTreeInc := True;
while (StackP > 0) and SubTreeInc do begin
if StackP = 1 then
InsBalance(FRoot, SubTreeInc, Stack[1].Comparison)
else with Stack[StackP-1] do
InsBalance(Node.FChilds[Comparison > 0], SubTreeInc, Stack[StackP].Comparison);
dec(StackP);
end;
end;
{$IFDEF ThreadSafe}
initialization
Windows.InitializeCriticalSection(ClassCritSect);
finalization
Windows.DeleteCriticalSection(ClassCritSect);
{$ENDIF}
end.
|
unit LrParser;
interface
uses
SysUtils, Classes, Contnrs;
const
idNoToken = -1;
type
TLrStateMethod = procedure of object;
//
TLrStateParser = class
protected
FD, FP, FE, FS: PChar;
FL: Integer;
FState: TLrStateMethod;
FChar: Char;
function TokenLength: Integer;
public
constructor Create; virtual;
destructor Destroy; override;
procedure DiscardChar;
procedure DiscardToken;
procedure Parse; virtual;
procedure ParseText(const inText: string); virtual;
end;
//
TLrToken = class
private
FText: string;
FEnabled: Boolean;
protected
function GetText: string; virtual;
procedure SetEnabled(const Value: Boolean);
procedure SetText(const Value: string); virtual;
public
Kind: Integer;
constructor Create; virtual;
property Enabled: Boolean read FEnabled write SetEnabled;
property Text: string read GetText write SetText;
end;
//
TLrParsedToken = class(TLrToken)
protected
FTokens: TObjectList;
function GetText: string; override;
function GetCount: Integer;
function GetTokens(inIndex: Integer): TLrToken;
procedure SetTokens(inIndex: Integer; const Value: TLrToken);
public
constructor Create; override;
destructor Destroy; override;
procedure Add(inToken: TLrToken);
procedure Clear;
function Print: string;
public
property Count: Integer read GetCount;
property Tokens[inIndex: Integer]: TLrToken read GetTokens write SetTokens;
end;
//
TLrTokenParser = class(TLrStateParser)
private
FToken: TLrParsedToken;
protected
procedure SetToken(const Value: TLrParsedToken);
protected
function CreateToken(inKind: Integer = 0): TLrToken; virtual;
procedure EndTokenInclude(inKind: Integer = 0);
procedure EndTokenNoInclude(inKind: Integer = 0);
function LastToken: TLrToken;
function LastTokenKind: Integer;
function NewToken(inKind: Integer = 0): TLrToken;
procedure SetTokenText(inToken: TLrToken; inCount: Integer);
public
procedure Parse; override;
property Token: TLrParsedToken read FToken write SetToken;
end;
implementation
{ TLrStateParser }
constructor TLrStateParser.Create;
begin
//
end;
destructor TLrStateParser.Destroy;
begin
inherited;
end;
function TLrStateParser.TokenLength: Integer;
begin
Result := FP - FS + 1;
end;
procedure TLrStateParser.DiscardChar;
begin
FS := FP + 1;
end;
procedure TLrStateParser.DiscardToken;
begin
FS := FP;
end;
procedure TLrStateParser.Parse;
begin
if (not Assigned(FState)) or (FD = nil) then
exit;
FP := FD;
FE := FP + FL;
FS := FP;
while (FP < FE) do
begin
FChar := FP^;
FState;
Inc(FP);
end;
FChar := #0;
FState;
end;
procedure TLrStateParser.ParseText(const inText: string);
begin
FD := @(inText[1]);
FL := Length(inText);
Parse;
end;
{ TLrToken }
constructor TLrToken.Create;
begin
FEnabled := true;
end;
function TLrToken.GetText: string;
begin
Result := FText;
end;
procedure TLrToken.SetEnabled(const Value: Boolean);
begin
FEnabled := Value;
end;
procedure TLrToken.SetText(const Value: string);
begin
FText := Value;
end;
{ TLrParsedToken }
constructor TLrParsedToken.Create;
begin
FTokens := TObjectList.Create;
end;
destructor TLrParsedToken.Destroy;
begin
FTokens.Free;
inherited;
end;
procedure TLrParsedToken.Add(inToken: TLrToken);
begin
FTokens.Add(inToken);
end;
function TLrParsedToken.GetCount: Integer;
begin
Result := FTokens.Count;
end;
function TLrParsedToken.GetText: string;
var
i: Integer;
begin
Result := '';
for i := 0 to Pred(Count) do
with Tokens[i] do
if Enabled then
Result := Result + Text;
end;
function TLrParsedToken.Print: string;
var
i: Integer;
begin
Result := '';
for i := 0 to Pred(Count) do
Result := Result + '[' + Tokens[i].Text + '] ';
end;
function TLrParsedToken.GetTokens(inIndex: Integer): TLrToken;
begin
Result := TLrToken(FTokens[inIndex]);
end;
procedure TLrParsedToken.SetTokens(inIndex: Integer;
const Value: TLrToken);
begin
FTokens[inIndex] := Value;
end;
procedure TLrParsedToken.Clear;
begin
FTokens.Clear;
end;
{ TLrTokenParser }
function TLrTokenParser.CreateToken(inKind: Integer = 0): TLrToken;
begin
Result := TLrToken.Create;
Result.Kind := inKind;
end;
function TLrTokenParser.NewToken(inKind: Integer = 0): TLrToken;
begin
Result := CreateToken(inKind);
FToken.Add(Result);
end;
function TLrTokenParser.LastToken: TLrToken;
begin
if Token.Count > 0 then
Result := Token.Tokens[Token.Count - 1]
else
Result := nil;
end;
function TLrTokenParser.LastTokenKind: Integer;
begin
if LastToken <> nil then
Result := LastToken.Kind
else
Result := idNoToken;
end;
procedure TLrTokenParser.SetTokenText(inToken: TLrToken; inCount: Integer);
var
t: string;
begin
SetLength(t, inCount);
Move(FS^, t[1], inCount);
inToken.Text := t;
end;
procedure TLrTokenParser.EndTokenNoInclude(inKind: Integer = 0);
begin
if TokenLength > 1 then
begin
SetTokenText(NewToken(inKind), TokenLength - 1);
FS := FP;
end;
end;
procedure TLrTokenParser.EndTokenInclude(inKind: Integer = 0);
begin
if TokenLength > 0 then
begin
SetTokenText(NewToken(inKind), TokenLength);
FS := FP + 1;
end;
end;
procedure TLrTokenParser.Parse;
begin
inherited;
end;
procedure TLrTokenParser.SetToken(const Value: TLrParsedToken);
begin
FToken := Value;
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit fBottomWindowOutputConsole;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, fBottomWindowPage, StdCtrls, DosCommand, JclStrings, uCommon,
ActnList, TB2Item, TBX, Menus, Clipbrd, uCommonClass, uMultiLanguage,
ScrollListBox, JclFileUtils, uSafeRegistry, ShellAPI, fEditor;
type
TCompilerOutputParsedLine = class
private
fFileName: string;
fPosition: TPoint;
public
property FileName: string read fFileName write fFileName;
property Position: TPoint read fPosition write fPosition;
end;
TfmBottomWindowOutputConsole = class(TfmBottomWindowPage)
btnTerminate: TButton;
acSetFont: TAction;
TBXItem6: TTBXItem;
TBXSeparatorItem3: TTBXSeparatorItem;
lb: THScrollListBox;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OnMouseDownEvent(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure acSetFontExecute(Sender: TObject);
procedure btnTerminateClick(Sender: TObject);
private
fExecTerminatedByUser :boolean;
fScrollToLastLine: boolean;
fParserRule: string;
fDosCommand: TDosCommand;
fExecuting: boolean;
fSettingsModified: boolean;
fListBoxFont: TFont;
procedure OnExecNewLine(Sender: TObject; NewLine: string; OutputType: TOutputType);
procedure OnExecTerminated(Sender: TObject);
procedure ApplyFontSettings;
protected
procedure LoadSettings; override;
procedure SaveSettings; override;
procedure JumpToLineInSource; override;
procedure CopySelectedLineToClipboard; override;
procedure CopyAllToClipboard; override;
procedure ClearContents; override;
function JumpToLineInSourceEnabled:boolean; override;
function CopySelectedLineToClipboardEnabled:boolean; override;
function CopyAllToClipboardEnabled:boolean; override;
function ClearContentsEnabled:boolean; override;
public
class function GetDefaultCaption:string; override;
procedure ExecuteCommand(CmdLine:string; StartInDirectory:string);
procedure StopExecution;
procedure JumpToFirstLine;
procedure JumpToLastLine;
procedure Clear(FreeObjects: boolean);
procedure AddCompilerMessage(s:string; IgnoreForParsing:boolean);
property ScrollToLastLine: boolean read fScrollToLastLine write fScrollToLastLine;
property ParserRule: string read fParserRule write fParserRule;
property Executing: boolean read fExecuting;
end;
procedure ExecUserCommand(ed:TfmEditor; MemoLines:TStrings; n:integer; FileName:string);
function ExecUserGetHint(n:integer; FileName:string):string;
function GetExecDef(n:integer; FileName:string):pTUserExecDef;
implementation
uses
fMain, fBottomWindowContainer;
{$R *.dfm}
const
OUTPUT_CONSOLE_REG_KEY = BOTTOM_WINDOW_OPTIONS_REG_KEY+'OutputConsole\';
////////////////////////////////////////////////////////////////////////////////////////////
// Static functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
function ExecUserGetHint(n:integer; FileName:string):string;
var
Def :pTUserExecDef;
begin
Def:=GetExecDef(n, FileName);
if not Assigned(Def) then begin
result:='';
EXIT;
end;
result:=Def^.Hint;
end;
//------------------------------------------------------------------------------------------
function GetExecDef(n:integer; FileName:string):pTUserExecDef;
var
ext :string;
s :string;
i :integer;
found :boolean;
begin
result:=nil;
ext:=UpperCase(ExtractFileExt(FileName));
if (Length(ext)>0) then begin
if (ext[1]='.') then
Delete(ext,1,1);
end else
EXIT;
i:=0;
while (i<EditorCfg.UserExecSetCount) do begin
s:=','+UpperCase(EditorCfg.UserExecCfg[i].Ext)+',';
found:=(Pos(','+ext+',',s)>0);
if found then begin
result:=@EditorCfg.UserExecCfg[i].Def[n];
BREAK;
end;
inc(i);
end;
end;
//------------------------------------------------------------------------------------------
function ResolveParams(ed:TfmEditor; MemoLines:TStrings; FileName:string; StartInDir, Params:string; UseShortName:boolean):string;
var
n :integer;
s :string;
buff :array[0..255] of char;
p :PChar;
rec :WIN32_FIND_DATA;
X,Y :integer;
const
LastPromptParams :string ='';
procedure Replace(SubStr,NewStr:string; var Dest:string);
var
n :integer;
min_pos :integer;
finished :boolean;
begin
min_pos:=1;
repeat
n:=Pos(SubStr,Dest);
finished:=(n<min_pos);
if not finished then begin
Delete(Dest,n,Length(SubStr));
Insert(NewStr,Dest,n);
min_pos:=n+Length(NewStr);
end;
until finished;
end;
function GetFileSpecificParameters:string;
var
s, ss :string;
n :integer;
p :PChar;
begin
ss:='';
if (MemoLines.Count>0) then begin
s:=MemoLines[0];
n:=Pos('%PARAMETERS',UpperCase(s));
if (n>0) then begin
p:=@s[n];
while not (p^ in [#13,#10,'"',#0]) do inc(p);
if (p^='"') then begin
inc(p);
while not (p^ in [#13,#10,'"',#0]) do begin
if (p^='\') and ((p+1)^ in ['\','"']) then
inc(p);
ss:=ss+p^;
inc(p);
end;
end;
end;
end;
result:=ss;
end;
begin
if (UseShortName) then begin
// ime fajla
FillChar(rec,SizeOf(rec),#0);
FindFirstFile(PChar(FileName),rec);
FillChar(buff,SizeOf(buff),#0);
p:=buff;
FileName:=ExtractFilePath(FileName);
GetShortPathName(PChar(FileName),@buff,SizeOf(buff));
FileName:='';
n:=0;
while (n<13) and (rec.cAlternateFileName[n]<>#0) do begin
FileName:=FileName+rec.cAlternateFileName[n];
inc(n);
end;
// u slucaju da je ipak kratko ime fajla
if (Length(FileName)=0) then begin
n:=0;
while (n<13) and (rec.cFileName[n]<>#0) do begin
FileName:=FileName+rec.cFileName[n];
inc(n);
end;
end;
FileName:=string(p)+FileName;
end else begin
Params:=' '+Params+' ';
Replace(' %n ',' "%n" ',Params);
Replace(' %f ',' "%f" ',Params);
Replace(' %p ',' "%p" ',Params);
Replace(' %s ',' "%s" ',Params);
Params:=Trim(Params);
end;
Replace('%%',#255,Params);
Replace('%n',FileName,Params);
Replace('%f',ExtractFileName(FileName),Params);
if (Pos('%P',Params)>0) then begin
s:=GetFileSpecificParameters;
Replace('%P', s, Params);
end;
if (Pos('%F',Params)>0) then begin
s:=ExtractFileName(FileName);
SetLength(s,Length(s)-Length(ExtractFileExt(FileName)));
Replace('%F',s,Params);
end;
Replace('%s',StartInDir,Params);
Replace('%p',ExtractFilePath(FileName),Params);
if (Pos('%e',Params)>0) then begin
s:=ExtractFileExt(FileName);
if (Pos('.',s)=1) then Delete(s,1,1);
Replace('%e',s,Params);
end;
if Assigned(ed) and ((Pos('%c',Params)>0) or (Pos('%l',Params)>0)) then begin
ed.GetCursorPos(X,Y);
Replace('%c',IntToStr(X+1),Params);
Replace('%l',IntToStr(Y+1),Params);
end;
if Assigned(ed) then
Replace('%w',ed.GetWordUnderCursor,Params);
Replace(#255,'%',Params);
repeat
n:=Pos('%?',Params);
if (n>0) then begin
Delete(Params,n,2);
s:=InputBox(mlStr(ML_USREXEC_ERR_PARAM_CAPT, 'Enter optional parameter'),
mlStr(ML_USREXEC_ERR_PARAM_TEXT, 'Parameter:'), LastPromptParams);
Insert(s,Params,n);
LastPromptParams:=s;
end;
until (n=0);
result:=Params;
end;
//------------------------------------------------------------------------------------------
function Execute(App, Param, Dir :string; Window:integer):boolean;
const
win :array[0..2] of integer = (SW_SHOWNORMAL, SW_SHOWMINIMIZED, SW_SHOWMAXIMIZED);
begin
ShellExecute(0, 'open', PChar(App), PChar(Param), PChar(Dir), win[Window]);
result:=TRUE;
end;
//------------------------------------------------------------------------------------------
procedure ExecUserCommand(ed:TfmEditor; MemoLines:TStrings; n:integer; FileName:string);
var
Def :pTUserExecDef;
App :string;
Param :string;
StartIn :string;
ok :boolean;
CurrDir :string;
ConExecParams: string;
begin
Def:=GetExecDef(n, FileName);
if not Assigned(Def) or (Length(Trim(Def^.ExecCommand))=0) then begin
MessageDlg(Format(mlStr(ML_USREXEC_ERR_NO_ASSOCIATON,
'No user command associated with extension ''%s''.'#13#10'Use ''Environment Options / Execute Keys dialog'' to assign commands.')
,[ExtractFileExt(FileName)]),
mtWarning,[mbOK],0);
EXIT;
end;
case Def^.SaveMode of
uesCurrentFile:
if Assigned(ed) and ed.Modified then ed.Save;
uesAllFiles:
fmMain.acSaveAllFilesExecute(nil);
uesNone:
;
end;
CurrDir:=GetCurrentDir;
App:=QuoteFilename(ResolveParams(ed, MemoLines, FileName, StartIn, Def^.ExecCommand, Def^.UseShortName));
Param:=ResolveParams(ed, MemoLines, FileName, StartIn, Def^.Params, Def^.UseShortName);
StartIn:=RemoveQuote(ResolveParams(ed, MemoLines, FileName, Def^.StartDir, Def^.StartDir, Def^.UseShortName));
if (Length(StartIn)=0) or not SetCurrentDir(StartIn) then
StartIn:=ExtractFilePath(FileName);
SetCurrentDir(StartIn);
ConExecParams:='';
if (Def^.PauseAfterExecution and not Def^.CaptureOutput) then
ConExecParams:=ConExecParams+'-p ';
if Def^.IdlePriority then
ConExecParams:=ConExecParams+'-i ';
if Def^.CaptureOutput then begin
fmMain.ShowBottomWindow(bwOutputConsole);
with fmBottomWindowContainer.OutputConsole do begin
Clear(TRUE);
ParserRule:=Def^.ParserRule;
ExecuteCommand(ApplicationDir+'ConExec.exe '+ConExecParams+App+' '+Param, StartIn);
ScrollToLastLine:=Def^.ScrollConsole;
end;
ok:=TRUE;
end else begin
if (Length(ConExecParams)=0) then
ok:=Execute(App, Param, StartIn, Def^.Window)
else
ok:=Execute(ApplicationDir+'ConExec.exe', ConExecParams+App+' '+Param, StartIn, Def^.Window);
end;
SetCurrentDir(CurrDir);
if not ok then begin
; // error
end else begin
if EditorCfg.ShowExecInfoDlg then begin
MessageDlg(Format(mlStr(ML_USREXEC_FINISHED_DLG,'Finished executing ''%s''.'),[App+' '+Param]),mtInformation,[mbOK],0);
end;
end;
end;
//------------------------------------------------------------------------------------------
procedure ParseCompilerOutput(ErrLine, ParserRule:string; ParsedLine:TCompilerOutputParsedLine);
var
ptr :pChar;
s,ss :string;
ch :char;
lPosition: TPoint;
lFileName: string;
function MatchString:boolean;
var
n :integer;
begin
if (Length(s)>0) then begin
n:=Pos(s,ErrLine);
if (n>0) then begin
Delete(ErrLine,1,n+Length(s)-1);
s:='';
end;
end else
n:=1;
result:=n>0;
end;
function GetStringUntilChar(chars:string):string;
var
n :integer;
begin
result:=''; n:=1;
while (n<=Length(ErrLine)) and
((Pos(ErrLine[n],chars)=0) or
((ErrLine[n]=':') and (n+1<=Length(ErrLine)) and (ErrLine[n+1]='\'))
) do begin
result:=result+ErrLine[n];
inc(n);
end;
if (Length(result)>0) then
Delete(ErrLine,1,Length(result));
end;
function GetLineNumber(StopChar:char):integer;
var
s :string;
begin
s:=GetStringUntilChar(StopChar+#00);
while (Length(s)>0) and not (s[Length(s)] in ['0'..'9']) do
SetLength(s,Length(s)-1);
result:=StrToIntDef(s,-1);
end;
function DeleteStringUntilStr(str:string):boolean;
var
n :integer;
begin
n:=Pos(str, ErrLine);
result:=(Length(str)=0) or (n>0);
if result then
Delete(ErrLine, 1, n-1);
end;
function GetNextRuleChar:char;
begin
if (ptr^='\') then
inc(ptr);
result:=ptr^
end;
begin
lFileName:='';
lPosition:=Point(-1, -1);
ptr:=PChar(ParserRule);
s:='';
while (ptr^<>#00) and (Length(ErrLine)>0) do begin
case ptr^ of
'*': begin
ss:='';
while not ((ptr+1)^ in [#00,'*','?','%']) do begin
inc(ptr);
ss:=ss+GetNextRuleChar;
end;
if DeleteStringUntilStr(ss) then
Delete(ErrLine, 1, Length(ss))
else
BREAK;
end;
'?': begin
end;
'%': begin
if ((ptr+1)^<>#00) then begin
inc(ptr);
case UpCase(ptr^) of
'N': begin
if MatchString then begin
inc(ptr);
ch:=GetNextRuleChar; // znak kod kojeg Šemo se zaustaviti s kopiranjem
dec(ptr);
lFileName:=GetStringUntilChar(ch+#00);
end else
BREAK;
end;
'L': begin
if MatchString then begin
// (ptr+1)^ = znak kod kojeg Šemo se zaustaviti s kopiranjem
lPosition.Y:=GetLineNumber((ptr+1)^);
end else
BREAK;
end;
'C': begin
// if MatchString then begin
// (ptr+1)^ = znak kod kojeg Šemo se zaustaviti s kopiranjem
lPosition.X:=GetLineNumber((ptr+1)^);
// end else
// BREAK;
end;
end;
end;
end;
else begin
s:=s+GetNextRuleChar;
end;
end;
inc(ptr);
end;
ParsedLine.Position:=lPosition;
ParsedLine.FileName:=lFileName;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
class function TfmBottomWindowOutputConsole.GetDefaultCaption: string;
begin
result:=mlStr(ML_USREXEC_PANEL_CAPTION, 'Output Console');
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.AddCompilerMessage(s: string; IgnoreForParsing: boolean);
var
Line: TCompilerOutputParsedLine;
begin
// ekspandirajmo tabove
StrReplace(s, #09, ' ', [rfReplaceAll]);
if (not IgnoreForParsing) and (Length(s)>0) then begin
Line:=TCompilerOutputParsedLine.Create;
ParseCompilerOutput(s, fParserRule, Line);
if (Length(Line.FileName)>0) then begin
if (Length(ExtractFilePath(Line.FileName))=0) then
Line.FileName:=PathAddSeparator(fDosCommand.CurrentDir)+Line.FileName;
end else
FreeAndNil(Line);
end else
Line:=nil;
try
lb.AddString(s, Line);
except
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.Clear(FreeObjects: boolean);
var
i: integer;
begin
if FreeObjects then
for i:=0 to lb.Items.Count-1 do
if Assigned(lb.Items.Objects[i]) then
TCompilerOutputParsedLine(lb.Items.Objects[i]).Free;
lb.ClearList;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.ExecuteCommand(CmdLine:string; StartInDirectory:string);
begin
if fExecuting then EXIT;
fExecuting:=TRUE;
{ TODO : [ml] }
AddCompilerMessage('> '+'Executing'+': '+CmdLine,TRUE);
AddCompilerMessage('',TRUE);
btnTerminate.Visible:=(Win32Platform=VER_PLATFORM_WIN32_NT);
fExecTerminatedByUser:=FALSE;
with fDosCommand do begin
CommandLine:=CmdLine;
CurrentDir:=StartInDirectory;
Priority:=NORMAL_PRIORITY_CLASS;
Execute;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.StopExecution;
begin
fExecTerminatedByUser:=TRUE;
fDosCommand.Stop;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.JumpToFirstLine;
begin
if (lb.Items.Count>0) then
lb.ItemIndex:=0;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.JumpToLastLine;
begin
if (lb.Items.Count>0) then
lb.ItemIndex:=lb.Items.Count-1;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.LoadSettings;
var
reg: TSafeRegistry;
begin
reg:=TSafeRegistry.Create;
with reg do
try
if OpenKey(OUTPUT_CONSOLE_REG_KEY, FALSE) then begin
ReadFontData('Font', fListBoxFont);
end;
finally
Free;
end;
fSettingsModified:=FALSE;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.SaveSettings;
var
reg: TSafeRegistry;
begin
if fSettingsModified then begin
reg:=TSafeRegistry.Create;
with reg do
try
OpenKey(OUTPUT_CONSOLE_REG_KEY, TRUE);
WriteFontData('Font', fListBoxFont);
finally
Free;
end;
end;
fSettingsModified:=FALSE;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.ApplyFontSettings;
var
str: TStringList;
n: integer;
begin
str:=TStringList.Create;
try
n:=lb.ItemIndex;
str.Assign(lb.Items);
Clear(FALSE);
lb.Font.Assign(fListBoxFont);
lb.ItemHeight:=lb.Canvas.TextHeight('Ty')+1;
lb.Repaint;
lb.Items.Assign(str);
lb.ItemIndex:=n;
finally
str.Free;
end;
end;
//------------------------------------------------------------------------------------------
function TfmBottomWindowOutputConsole.ClearContentsEnabled: boolean;
begin
result:=lb.Items.Count>0;
end;
//------------------------------------------------------------------------------------------
function TfmBottomWindowOutputConsole.CopyAllToClipboardEnabled: boolean;
begin
result:=lb.Items.Count>0;
end;
//------------------------------------------------------------------------------------------
function TfmBottomWindowOutputConsole.CopySelectedLineToClipboardEnabled: boolean;
begin
result:=lb.ItemIndex<>-1;
end;
//------------------------------------------------------------------------------------------
function TfmBottomWindowOutputConsole.JumpToLineInSourceEnabled: boolean;
begin
result:=(lb.ItemIndex<>-1) and Assigned(lb.Items.Objects[lb.ItemIndex]);
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.ClearContents;
begin
Clear(TRUE);
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.CopyAllToClipboard;
var
buff :PChar;
str :TStringList;
begin
str:=TStringList.Create;
str.Assign(lb.Items);
if (str.Count>0) then begin
buff:=str.GetText;
Clipboard.SetTextBuf(buff);
StrDispose(buff);
end;
str.Free;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.CopySelectedLineToClipboard;
var
buff :PChar;
str :TStringList;
begin
if (lb.ItemIndex<>-1) then begin
str:=TStringList.Create;
str.Add(lb.Items[lb.ItemIndex]);
buff:=str.GetText;
Clipboard.SetTextBuf(buff);
StrDispose(buff);
str.Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.JumpToLineInSource;
var
ParsedOutput: TCompilerOutputParsedLine;
Editor: TfmEditor;
begin
if (lb.ItemIndex<>-1) then begin
ParsedOutput:=TCompilerOutputParsedLine(lb.Items.Objects[lb.ItemIndex]);
if Assigned(ParsedOutput) and fmMain.OpenFile(ParsedOutput.FileName) then begin
Editor:=fmMain.ActiveEditor;
if Assigned(Editor) then begin
Editor.SetCursorPos(0, ParsedOutput.Position.Y-1);
Editor.SetCursorPosNice;
Editor.SetCursorOnFirstNonBlank;
SendMessage(Editor.Handle, WM_MDIACTIVATE, Editor.Handle, 0);
Editor.memo.SetFocus;
end;
end;
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Actions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.acSetFontExecute(Sender: TObject);
begin
with TFontDialog.Create(SELF) do
try
Options:=Options-[fdEffects];
Font.Assign(fListBoxFont);
if Execute then begin
fListBoxFont.Assign(Font);
ApplyFontSettings;
fSettingsModified:=TRUE;
end;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.OnExecNewLine(Sender: TObject; NewLine: string; OutputType: TOutputType);
begin
if (OutputType=otEntireLine) {and (Length(NewLine)>0)} then
AddCompilerMessage(NewLine, FALSE);
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.btnTerminateClick(Sender: TObject);
begin
StopExecution;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.OnExecTerminated(Sender: TObject);
begin
btnTerminate.Visible:=FALSE;
{ TODO : [ml] }
if not fExecTerminatedByUser then
AddCompilerMessage('> '+'Execution finished.',TRUE)
else
AddCompilerMessage('> '+'Execution terminated by user.',TRUE);
if Showing then lb.SetFocus;
if ScrollToLastLine then
JumpToLastLine
else
JumpToFirstLine;
fmMain.OnApplicationActivate(SELF);
fExecuting:=FALSE;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.OnMouseDownEvent(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
XY :TPoint;
begin
if (Button=mbRight) then begin
lb.ItemIndex:=lb.ItemAtPos(Point(X,Y),FALSE);
XY:=lb.ClientToScreen(Point(X,Y));
if Assigned(lb.PopupMenu) then
lb.PopupMenu.Popup(XY.X, XY.Y);
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Form events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.FormCreate(Sender: TObject);
begin
fListBoxFont:=TFont.Create;
inherited;
fDosCommand:=TDosCommand.Create(SELF);
with fDosCommand do begin
OnNewLine:=OnExecNewLine;
OnTerminated:=OnExecTerminated;
end;
acSetFont.Caption:=mlStr(ML_EXEC_POP_SET_FONT, acSetFont.Caption);
ApplyFontSettings;
end;
//------------------------------------------------------------------------------------------
procedure TfmBottomWindowOutputConsole.FormDestroy(Sender: TObject);
begin
FreeAndNil(fDosCommand);
Clear(TRUE);
inherited;
FreeAndNil(fListBoxFont);
end;
//------------------------------------------------------------------------------------------
end.
|
(* MEMOUTIL.PAS - Copyright (c) 1995-1996, Eminent Domain Software *)
unit MemoUtil;
{-Memo simple memo functions}
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, Menus, ExtCtrls;
function Memo_CursorPos (AMemo: TMemo): TPoint;
{-returns the cursor position in row, column}
function Memo_WhereY (AMemo: TMemo): Integer;
{-returns the screen absolute y position of the highlighted word}
implementation
function Memo_CursorPos (AMemo: TMemo): TPoint;
{-returns the cursor position in row, column}
var
Col: integer;
Row: integer;
RowStart: integer;
begin
Row := SendMessage(AMemo.Handle, EM_LINEFROMCHAR, $FFFF, 0);
{-returns the line number of the cursor position}
RowStart := SendMessage(AMemo.Handle, EM_LINEINDEX, $FFFF, 0);
{-returns the index of the start of the line within the buffer}
Col := AMemo.SelStart - RowStart;
Result := Point (Col, Row);
end; { Memo_CursorPos }
function Memo_WhereY (AMemo: TMemo): Integer;
{-returns the screen absolute y position of the highlighted word}
var
CursorPos: TPoint;
AbsMemoXY: TPoint;
TopLine: Integer;
Height: Integer;
begin
TopLine := SendMessage (AMemo.Handle, EM_GETFIRSTVISIBLELINE, 0, 0);
CursorPos := Memo_CursorPos (AMemo);
AbsMemoXY := AMemo.ClientToScreen (Point (0, 0));
Height := Abs (Round (AMemo.Font.Height * (AMemo.Font.PixelsPerInch/72)));
Result := AbsMemoXY.Y + ((CursorPos.Y - TopLine) * Height);
end; { Memo_WhereY }
end. { MemoUtil }
|
unit PhpPage;
interface
uses
SysUtils, Classes, Controls,
ThHtmlPage, TpControls;
type
TTpDebugFlag = ( dfDumpObjects, dfDumpRequest, dfDumpBlocks, dfDumpNodes );
TTpDebugFlags = set of TTpDebugFlag;
//
TPhpPage = class(TThHtmlPage)
private
FDebug: Boolean;
FDebugFlags: TTpDebugFlags;
FJsSource: TStrings;
FJsUrl: string;
FNewName: string;
FOnBeforeClicks: TTpEvent;
FOnBeforeInput: TTpEvent;
FOnGenerate: TTpEvent;
FOnNameChange: TNotifyEvent;
FPhpFilename: string;
FPhpSource: TStrings;
FPreviewOnPublish: Boolean;
FShowCaptions: Boolean;
FShowComponents: Boolean;
FShowGrid: Boolean;
FStyleUrl: string;
FIsModule: Boolean;
protected
function GetAppTag: string;
function GetJsTag(const inSrc: string): string;
function GetStyleTag(const inHref: string): string;
procedure SetJsSource(const Value: TStrings);
procedure SetName(const NewName: TComponentName); override;
procedure SetPhpSource(const Value: TStrings);
procedure SetShowCaptions(const Value: Boolean);
procedure SetShowComponents(const Value: Boolean);
procedure SetShowGrid(const Value: Boolean);
protected
procedure GenerateHeaders; override;
procedure GenerateStyles; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property IsModule: Boolean read FIsModule write FIsModule;
property JsUrl: string read FJsUrl write FJsUrl;
property NewName: string read FNewName;
property OnNameChange: TNotifyEvent read FOnNameChange write FOnNameChange;
property StyleUrl: string read FStyleUrl write FStyleUrl;
published
property Debug: Boolean read FDebug write FDebug default false;
property DebugFlags: TTpDebugFlags read FDebugFlags write FDebugFlags
default [ dfDumpObjects, dfDumpRequest ];
property PhpFilename: string read FPhpFilename
write FPhpFilename;
property JsSource: TStrings read FJsSource write SetJsSource;
property OnBeforeClicks: TTpEvent read FOnBeforeClicks
write FOnBeforeClicks;
property OnBeforeInput: TTpEvent read FOnBeforeInput write FOnBeforeInput;
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
property PreviewOnPublish: Boolean read FPreviewOnPublish
write FPreviewOnPublish default true;
property PhpSource: TStrings read FPhpSource write SetPhpSource;
property ShowCaptions: Boolean read FShowCaptions write SetShowCaptions;
property ShowGrid: Boolean read FShowGrid write SetShowGrid;
property ShowComponents: Boolean read FShowComponents write SetShowComponents;
end;
//
// Backward compat
TPhpForm = class(TPhpPage)
end;
implementation
uses
ThTag;
{ TPhpPage }
constructor TPhpPage.Create(AOwner: TComponent);
begin
inherited;
FDebugFlags := [ dfDumpObjects, dfDumpRequest ];
FJsSource := TStringList.Create;
FPhpSource := TStringList.Create;
FPreviewOnPublish := true;
FShowCaptions := true;
FShowComponents := true;
FShowGrid := true;
Name := 'Page';
end;
destructor TPhpPage.Destroy;
begin
FPhpSource.Free;
FJsSource.Free;
inherited;
end;
procedure TPhpPage.SetName(const NewName: TComponentName);
begin
FNewName := NewName;
if Assigned(OnNameChange) then
OnNameChange(Self);
inherited;
end;
procedure TPhpPage.SetPhpSource(const Value: TStrings);
begin
FPhpSource.Assign(Value);
end;
procedure TPhpPage.SetJsSource(const Value: TStrings);
begin
FJsSource.Assign(Value);
end;
function TPhpPage.GetAppTag: string;
begin
with TThTag.Create('meta') do
try
Add('tpOnGenerate', OnGenerate);
Add('tpOnBeforeClicks', OnBeforeClicks);
Add('tpOnBeforeInput', OnBeforeInput);
Attributes.Add('tpDebug', Debug);
Add('tpDebugFlags', PByte(@DebugFlags)^);
Attributes.Add('tpIsModule', IsModule);
if Attributes.Count = 0 then
Result := ''
else begin
Add('tpClass', 'TTpPage');
Add('tpName', 'page');
Result := Html;
end;
finally
Free;
end;
end;
function TPhpPage.GetJsTag(const inSrc: string): string;
begin
with TThTag.Create('script') do
try
Mono := false;
Add('language', 'javascript');
Add('type', 'text/javascript');
Add('src', inSrc);
Result := Html;
finally
Free;
end;
end;
procedure TPhpPage.GenerateHeaders;
begin
inherited;
StructuredHtml.Headers.Add(GetAppTag);
StructuredHtml.Headers.Add(GetJsTag(JsUrl))
end;
function TPhpPage.GetStyleTag(const inHref: string): string;
begin
with TThTag.Create('link') do
try
Add('rel', 'stylesheet');
Add('type', 'text/css');
Add('href', inHref);
Result := Html;
finally
Free;
end;
end;
procedure TPhpPage.GenerateStyles;
begin
StructuredHtml.Headers.Add(GetStyleTag(StyleUrl))
end;
procedure TPhpPage.SetShowCaptions(const Value: Boolean);
begin
FShowCaptions := Value;
Change;
end;
procedure TPhpPage.SetShowComponents(const Value: Boolean);
begin
FShowComponents := Value;
Change;
end;
procedure TPhpPage.SetShowGrid(const Value: Boolean);
begin
FShowGrid := Value;
Change;
end;
initialization
RegisterClass(TPhpPage);
RegisterClass(TPhpForm);
end.
|
unit UAuxRefOp;
interface
function getDayOfTheYear( fromDate: TDateTime ): word;
function getReferenciaOperacion( fromFecha: TDateTime; numReferencia: Integer ): String;
function testReferenciaOperacion(const Referencia: String): Boolean;
implementation
uses
SysUtils,
rxStrUtils;
function getDayOfTheYear( fromDate: TDateTime ): word ;
const
diasAcumMeses: array [boolean] of array [1..12] of integer =
( ( 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 ),
( 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 ) );
var
anno,
mes,
dia: word;
begin
DecodeDate( fromDate, anno, mes, dia );
result := diasAcumMeses[ isLeapYear( anno ) ][ mes ] + dia;
end;
function getReferenciaOperacion( fromFecha: TDateTime; numReferencia: Integer ): String;
var
auxNumero: Int64;
begin
Result := '2052' + formatDateTime('yyyy',fromFecha)[4] + AddChar( '0', intToStr(getDayOfTheYear(fromFecha)), 3 );
Result := Result + '0' + AddChar( '0', intToStr( numReferencia ), 6 );
// hasta el momento tenemos un número de 16 dígitos. Hay que calcular el módulo 7
auxNumero := strToInt64( Result );
Result := Result + Trim( intToStr( auxNumero mod 7 ) );
end;
function testReferenciaOperacion(const Referencia:String): Boolean;
var
auxNumero: Int64;
auxdc: Integer;
auxString: String;
begin
auxString := Trim(Referencia);
auxNumero := strToInt64(Copy(auxString, 1, 15));
auxDC := strToInt(Copy(auxString, 16, 1));
Result := (auxNumero mod 7) = auxDC;
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2013 Vincent Parrett }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.IoC.Internal;
{$I DUnitX.inc}
///
/// Internals of the DUnitX IoC container;
///
interface
uses
TypInfo,
RTTI,
Generics.Collections,
DUnitX.IoC;
type
//Makes sure virtual constructors are called correctly. Just using a class reference will not call the overriden constructor!
//See http://stackoverflow.com/questions/791069/how-can-i-create-an-delphi-object-from-a-class-reference-and-ensure-constructor
TClassActivator = class
private
class var
FRttiCtx : TRttiContext;
class constructor Create;
public
class function CreateInstance(const AClass : TClass) : IInterface;
end;
//function IocContainerInfo : TDictionary<string,TObject>;
implementation
//Borrowed from XE2 - in earlier versions of delphi these were from the windows unit.
{$IFDEF CPUX86}
{
function InterlockedAdd(var Addend: Integer; Increment: Integer): Integer;
asm
MOV ECX,EAX
MOV EAX,EDX
LOCK XADD [ECX],EAX
ADD EAX,EDX
end;
}
function InterlockedCompareExchange(var Target: Integer; Exchange: Integer; Comparand: Integer): Integer;
asm
XCHG EAX,ECX
LOCK CMPXCHG [ECX],EDX
end;
function InterlockedCompareExchangePointer(var Target: Pointer; Exchange: Pointer; Comparand: Pointer): Pointer;
asm
JMP InterlockedCompareExchange
end;
{$ELSE}
function InterlockedCompareExchangePointer(var Destination: Pointer; Exchange: Pointer; Comparand: Pointer): Pointer;
asm
.NOFRAME
MOV RAX,R8
LOCK CMPXCHG [RCX],RDX
end;
{$ENDIF}
{ TActivator }
class constructor TClassActivator.Create;
begin
TClassActivator.FRttiCtx := TRttiContext.Create;
end;
class function TClassActivator.CreateInstance(const AClass : TClass): IInterface;
var
rType : TRttiType;
method: TRttiMethod;
begin
result := nil;
rType := FRttiCtx.GetType(AClass);
if not (rType is TRttiInstanceType) then
exit;
for method in TRttiInstanceType(rType).GetMethods do
begin
if method.IsConstructor and (Length(method.GetParameters) = 0) then
begin
Result := method.Invoke(TRttiInstanceType(rtype).MetaclassType, []).AsInterface;
Break;
end;
end;
end;
end.
|
{$I texel.inc}
unit txfloat;
interface
{$IFNDEF FPC}
type
Longword = longint;
{$ENDIF}
type
{ type used for internal calculations }
PNumber = ^TNumber;
{$IFDEF FPC}
TNumber = double;
{$ELSE}
TNumber = real;
{$ENDIF}
{ type stored in files }
PExternalNumber = ^TExternalNumber;
TExternalNumber = record
signexp: word;
manthi : longint;
mantlo : longint;
end;
{$IFDEF NEED_FLOAT_CONV}
procedure float_to_external(r: TNumber; res: PExternalNumber);
function float_from_external(e: PExternalNumber; res: PNumber): boolean;
{$ENDIF}
{$IFNDEF FPC}
function isnan(r: TNumber): boolean;
function isinfinite(r: TNumber): boolean;
{$ENDIF}
implementation
{$IFDEF NEED_FLOAT_CONV}
const
IEEE854_LONG_DOUBLE_BIAS = $3fff;
IEEE754_DOUBLE_BIAS = $3ff;
type
bits32 = longword;
float64 = record
case byte of
1: (d : double);
2: (high,low : bits32);
3: (sign, w1 : word; w2: longword);
end;
procedure float_to_external(r: TNumber; res: PExternalNumber);
var f: float64;
exp: word;
begin
f.d := r;
exp := ( f.sign shr 4 ) AND $7FF;
if ( exp = $7FF ) then begin
if ((f.high and $000fffff) <> 0) or (f.low <> 0) then begin
{ NaN }
res^.signexp := (f.sign and $8000) or $7fff;
res^.manthi := -1;
res^.mantlo := -1;
end else begin
{ InF }
res^.signexp := (f.sign and $8000) or $7fff;
res^.manthi := 0;
res^.mantlo := 0;
end;
end else if ( exp = 0 ) then begin
{ Zero }
res^.signexp := (f.sign and $8000);
res^.manthi := 0;
res^.mantlo := 0;
end else begin
res^.signexp := (f.sign and $8000) or (exp + (IEEE854_LONG_DOUBLE_BIAS - IEEE754_DOUBLE_BIAS));
res^.manthi := ((f.high and $000fffff) shl 11) or ((f.low shr 21) and $7ff) or longword($80000000);
res^.mantlo := f.low shl 11;
end;
end;
function float_from_external(e: PExternalNumber; res: PNumber): boolean;
var f: float64;
exp: word;
begin
float_from_external := false;
exp := e^.signexp and $7fff;
if ( exp = $7FFF ) then begin
if ((e^.manthi and $7fffffff) <> 0) or (e^.mantlo <> 0) then begin
{ NaN }
f.sign := (e^.signexp and $8000) or $7fff;
f.w1 := $ffff;
f.w2 := $ffffffff;
end else begin
{ InF }
f.sign := (e^.signexp and $8000) or $7ff0;
f.w1 := 0;
f.w2 := 0;
end;
end else if (exp = 0) then begin
{ Zero }
f.sign := (e^.signexp and $8000);
f.w1 := 0;
f.w2 := 0;
end else if (exp <= (IEEE854_LONG_DOUBLE_BIAS - IEEE754_DOUBLE_BIAS)) then begin
{ Underflow }
float_from_external := true;
f.sign := (e^.signexp and $8000);
f.w1 := 0;
f.w2 := 0;
end else if (exp > (IEEE854_LONG_DOUBLE_BIAS + IEEE754_DOUBLE_BIAS)) then begin
{ Overflow }
float_from_external := true;
f.sign := (e^.signexp and $8000) or $7ff0;
f.w1 := 0;
f.w2 := 0;
end else begin
f.high := ((e^.signexp and $8000) or ((exp - (IEEE854_LONG_DOUBLE_BIAS - IEEE754_DOUBLE_BIAS)) shl 4) shl 16) or
((e^.manthi shr 11) and $fffff);
f.low := (e^.manthi shl 21) or ((e^.mantlo shr 11) and $1fffff);
end;
res^ := f.d;
end;
{$ENDIF}
{$IFNDEF FPC}
type
float80 = record
case byte of
1: (d : real);
2: (signexp: word; manthi, mantlo: longword);
end;
function isnan(r: TNumber): boolean;
var f: float80;
exp: word;
begin
f.d := r;
exp := f.signexp and $7fff;
isnan := false;
if ( exp <> $7FFF ) then exit;
if ((f.manthi and $7fffffff) <> 0) or (f.mantlo <> 0) then isnan := true;
end;
function isinfinite(r: TNumber): boolean;
var f: float80;
exp: word;
begin
f.d := r;
exp := f.signexp and $7fff;
isinfinite := false;
if ( exp <> $7FFF ) then exit;
if ((f.manthi and $7fffffff) = 0) and (f.mantlo = 0) then isinfinite := true;
end;
{$ENDIF}
begin
end.
|
unit dmForma17;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
frxClass, frxDBSet, frxDesgn, IBase, Forms, Variants,
Controls, FIBQuery, pFIBQuery, pFIBStoredProc, Dialogs, Math,
Asup_LoaderPrintDocs_Types, Asup_LoaderPrintDocs_Proc,
Asup_LoaderPrintDocs_WaitForm, ASUP_LoaderPrintDocs_Consts,
ASUP_LoaderPrintDocs_Messages, qFTools, frxExportHTML, frxExportXLS,
frxExportRTF,Graphics;
type
TDM = class(TDataModule)
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
Designer: TfrxDesigner;
DSetData: TpFIBDataSet;
ReportDsetData: TfrxDBDataset;
DSetGlobalData: TpFIBDataSet;
ReportDSetGlobalData: TfrxDBDataset;
RTFExport: TfrxRTFExport;
XLSExport: TfrxXLSExport;
HTMLExport: TfrxHTMLExport;
DSourceDepartments: TDataSource;
ReportDSetDepartment: TfrxDBDataset;
DSetDepartments: TpFIBDataSet;
Report: TfrxReport;
private
PId_Department:Integer;
PFontNames:string;
PFontSizes:integer;
PFontColors:TColor;
PFontStyles:TFontStyles;
PDateFormBeg:TDate;
PDateFormEnd:TDate;
PWithChild:boolean;
PDesignRep:Boolean;
public
constructor Create(AOwner:TComponent);reintroduce;
function PrintSpr(AParameter:TSimpleParam):variant;
property Id_Department:Integer read PId_Department write PId_Department;
property FontNames:string read PFontNames write PFontNames;
property FontSizes:integer read PFontSizes write PFontSizes;
property FontColors:TColor read PFontColors write PFontColors;
property FontStyles:TFontStyles read PFontStyles write PFontStyles;
property WithChild:boolean read PWithChild write PWithChild;
property DateFormBeg:TDate read PDateFormBeg write PDateFormBeg;
property DateFormEnd:TDate read PDateFormEnd write PDateFormEnd;
property DesignRep:Boolean read PDesignRep write PDesignRep;
end;
var DM:TDM;
implementation
{$R *.dfm}
const NameReport = '\Forma17.fr3';
constructor TDM.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
PDateFormBeg := Date;
PDateFormEnd := Date;
PId_Department:=-255;
PDesignRep:=False;
PFontNames:='Times New Roman';
PFontSizes:=-255;
PFontColors:=clDefault;
end;
function TDM.PrintSpr(AParameter:TSimpleParam):variant;
var wf:TForm;
m : TfrxDetailData;
begin
if AParameter.Owner is TForm then
wf:=ShowWaitForm(AParameter.Owner as TForm,wfPrepareData)
else wf:=ShowWaitForm(Application.MainForm,wfPrepareData);
try
Screen.Cursor:=crHourGlass;
DSetData.SQLs.SelectSQL.Text :='SELECT * FROM ASUP_FORMA17('''+DateToStr(PDateFormBeg)+''','''+DateToStr(PDateFormEnd)+''',?ID_DEPARTMENT) order by FIO';
DSetDepartments.SQLs.SelectSQL.Text :=
'SELECT * FROM ASUP_FORMA17_DEPARTMENTS('''+
DateToStr(PDateFormBeg)+''','''+
DateToStr(PDateFormEnd)+''','+
IntToStr(PId_Department)+','+
IfThen(PWithChild,'''T''','''F''')+')';
DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT FIRM_NAME,HEADER_UP_POST,HEADER_UP_FIO FROM INI_ASUP_CONSTS';
try
DSetDepartments.Open;
DSetData.Open;
DSetGlobalData.Open;
except
on E:Exception do
begin
AsupShowMessage(Error_Caption,e.Message,mtError,[mbOK]);
Screen.Cursor:=crDefault;
Exit;
end;
end;
if DSetDepartments.IsEmpty then
begin
qFErrorDialog('За такими даними працівників не знайдено!');
Screen.Cursor:=crDefault;
Exit;
end;
Report.Clear;
Report.LoadFromFile(ExtractFilePath(Application.ExeName)+Path_ALL_Reports+NameReport,True);
Report.Variables.Clear;
Report.Variables[' '+'User Category']:=NULL;
Report.Variables.AddVariable('User Category','PTerm',
'''в термін з '+DateToStr(PDateFormBeg)+' по '+DateToStr(PDateFormEnd)+'''');
if PFontSizes=-255 then PFontSizes:=10;
m := TfrxDetailData(Report.FindObject('DetailData1'));
if m <> nil then
begin
m.Font.Name := PFontNames;
m.Font.Size := PFontSizes;
m.Font.Color := PFontColors;
m.Font.Style := PFontStyles;
end;
Screen.Cursor:=crDefault;
finally
CloseWaitForm(wf);
end;
if not DSetDepartments.IsEmpty then
begin
if PDesignRep then Report.DesignReport
else Report.ShowReport;
Report.Free;
end;
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
end.
|
unit Catalog;
interface
uses SysUtils, Classes, Graphics, ExtCtrls, Browser;
const Version:Integer=Integer($F1953274);
type
//Базовий клас для елементів каталогу
TwcCollectionItem=class(TCollectionItem)
private
FName:String;
function GetParentElem:TwcCollectionItem;
protected
function GetDisplayName:String;override;
procedure SetName(const Value:String);virtual;
procedure SetParentElem(const Value:TwcCollectionItem);virtual;
public
UserData:Pointer;
constructor Create(Collection:TCollection);override;
//Процедура для видалення елементу
procedure Delete;virtual;
//Процедура для читання елементу з потоку
procedure LoadFromStream(AStream:TStream);virtual;
//Процедура для запису елементу в потік
procedure SaveToStream(AStream:TStream);virtual;
//Властивість, що задає "батьківський" елемент
property ParentElem:TwcCollectionItem read GetParentElem write SetParentElem;
//Процедура для імпорту елемента через інтерфейс
procedure AssignIntf(AIntf:IInterface);virtual;
procedure Assign(Source: TPersistent); override;
published
//Властивість, що задає назву елемента
property Name:String read FName write SetName;
end;
TwcItemChange=procedure(Sender:TwcCollectionItem;ChildsChanged:Boolean) of object;
//Базовий клас для колекцій елементів каталогу
TwcCollection=class(TOwnedCollection)
public
//Читає колекцію з потоку
procedure LoadFromStream(AStream:TStream);virtual;
//Записує колекцію в потік
procedure SaveToStream(AStream:TStream);virtual;
//Імпортує колекцію через інтерфейс
procedure AssignIntf(AIntf:IInterface);virtual;
end;
//Клас для операцій над архівами
TwcArchive=class(TwcCollectionItem)
private
FDateTime:TDateTime;
procedure SetDateTime(const Value: TDateTime);
protected
function GetDisplayName: String; override;
procedure SetName(const Value: String); override;
procedure SetParentElem(const Value: TwcCollectionItem);override;
public
constructor Create(Collection: TCollection); override;
procedure Delete; override;
procedure LoadFromStream(AStream: TStream); override;
procedure SaveToStream(AStream: TStream); override;
published
//Властивість для отримання дати та часу створення архіву
property DateTime:TDateTime read FDateTime write SetDateTime;
end;
TwcLink=class;
TwcArchives=class(TwcCollection)
protected
function GetItem(Index: Integer): TwcArchive;
procedure SetItem(Index: Integer; Value: TwcArchive);
public
constructor Create(ALink:TwcLink);
function Add: TwcArchive;
property Items[Index: Integer]: TwcArchive read GetItem write SetItem;default;
procedure LoadFromStream(AStream: TStream); override;
end;
//Базовий клас для категорій та посилань
TwcCategoryOrLink=class(TwcCollectionItem)
private
FInsertColor:TColor;
FModifyColor:TColor;
FDeleteColor:TColor;
FOwnColors:Boolean;
FUpdateTime:TDateTime;
FOwnUpdateTime:Boolean;
FActive:Boolean;
function GetActive: Boolean;
function GetDeleteColor: TColor;
function GetInsertColor: TColor;
function GetModifyColor: TColor;
function GetUpdateTime: TDateTime;
procedure SetDeleteColor(const Value: TColor);
procedure SetInsertColor(const Value: TColor);
procedure SetModifyColor(const Value: TColor);
procedure SetUpdateTime(const Value: TDateTime);
protected
function HasValues:Boolean;
public
constructor Create(Collection: TCollection); override;
procedure LoadFromStream(AStream: TStream); override;
procedure SaveToStream(AStream: TStream); override;
published
//Колір вставлених фрагментів
property InsertColor:TColor read GetInsertColor write SetInsertColor;
//Колір змінених фрагментів
property ModifyColor:TColor read GetModifyColor write SetModifyColor;
//Колір видалених фрагментів
property DeleteColor:TColor read GetDeleteColor write SetDeleteColor;
//Наявність власних налаштувань кольору
property OwnColors:Boolean read FOwnColors write FOwnColors;
//Період оновлення
property UpdateTime:TDateTime read GetUpdateTime write SetUpdateTime;
//Пріоритетність власного періоду оновлення
property OwnUpdateTime:Boolean read FOwnUpdateTime write FOwnUpdateTime;
//Активність посилання чи категорії
property Active:Boolean read GetActive write FActive;
end;
//Клас для операцій над посиланнями
TwcLink=class(TwcCategoryOrLink)
private
FURL:String;
FArchives:TwcArchives;
FLimit:Integer;
procedure SetURL(const AValue:String);
procedure SetArchives(const Value: TwcArchives);
procedure SetLimit(const Value: Integer);
procedure CheckLimit;
protected
procedure SetParentElem(const Value: TwcCollectionItem); override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure LoadFromStream(AStream: TStream); override;
procedure SaveToStream(AStream: TStream); override;
procedure AssignIntf(AIntf:IInterface); override;
published
//URL-адреса посилання
property URL:String read FURL write SetURL;
//Колекція архівів даного посилання
property Archives:TwcArchives read FArchives write SetArchives;
//
property Limit:Integer read FLimit write SetLimit;
end;
TwcCategory=class;
TwcLinks=class(TwcCollection)
protected
function GetItem(Index: Integer): TwcLink;
procedure SetItem(Index: Integer; Value: TwcLink);
public
constructor Create(ACategory:TwcCategory);
function Add: TwcLink;
property Items[Index: Integer]: TwcLink read GetItem write SetItem;default;
procedure AssignIntf(AIntf: IInterface); override;
end;
TwcCategs=class;
//Клас категорії
TwcCategory=class(TwcCategoryOrLink)
private
FSubCategs:TwcCategs;
FLinks:TwcLinks;
procedure SetSubCategs(const Value: TwcCategs);
procedure SetLinks(const Value: TwcLinks);
protected
procedure SetParentElem(const Value: TwcCollectionItem); override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure LoadFromStream(AStream: TStream); override;
procedure SaveToStream(AStream: TStream); override;
procedure AssignIntf(AIntf: IInterface); override;
published
//Колекція підкатегорій
property SubCategs:TwcCategs read FSubCategs write SetSubCategs;
//Колекція посилань безпосередньо у даній категорії
property Links:TwcLinks read FLinks write SetLinks;
end;
TwcCategs=class(TwcCollection)
protected
function GetItem(Index: Integer): TwcCategory;
procedure SetItem(Index: Integer; Value: TwcCategory);
public
constructor Create(AParent:TwcCategory);
function Add: TwcCategory;
property Items[Index: Integer]: TwcCategory read GetItem write SetItem;default;
procedure AssignIntf(AIntf: IInterface); override;
end;
//Компонент, який забезпечує взаємодію усіх класів даного модуля
TwcCatalog=class(TComponent)
private
FRoot:TwcCategory;
FItemChange:TwcItemChange;
procedure SetRoot(const Value: TwcCategory);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure LoadFromStream(AStream:TStream);
procedure SaveToStream(AStream:TStream);
function AddIntf(AIntf:IInterface):TwcCollectionItem;
published
property Root:TwcCategory read FRoot write SetRoot;
property OnItemChange:TwcItemChange read FItemChange write FItemChange;
end;
procedure Register;
implementation
uses DesignIntf, DesignEditors;
const //UnknownName='(не визначено)';
UnknownURL='about:blank';
var Fmt:TFormatSettings;
type
TExtTimeProperty=class(TTimeProperty)
public
function GetValue: String; override;
procedure SetValue(const Value: String); override;
end;
TExtDateTimeProperty=class(TDateTimeProperty)
public
function GetValue: String; override;
procedure SetValue(const Value: String); override;
end;
function StrStarts(const S,SubS:String;IgnoreCase:boolean=False):boolean;
var i:integer;
begin
if (Length(SubS)>Length(S))or(SubS='') then begin Result:=False;Exit end;
for i:=1 to Length(SubS) do
begin
if IgnoreCase then Result:=UpCase(S[i])=UpCase(SubS[i]) else Result:=S[i]=SubS[i];
if not Result then Exit
end;
Result:=True
end;
function UnknownName:String;
begin
Result:=DateToStr(Now,Fmt)
end;
function ReadInteger(AStream:TStream):Integer;
begin
AStream.Read(Result,SizeOf(Result))
end;
procedure WriteInteger(AStream:TStream;const Value:Integer);
begin
AStream.Write(Value,SizeOf(Value))
end;
function ReadString(AStream:TStream):String;
var Len:Integer;
begin
Len:=ReadInteger(AStream);
SetLength(Result,Len);
AStream.Read(Result[1],Len*SizeOf(Result[1]))
end;
procedure WriteString(AStream:TStream;const Value:String);
begin
WriteInteger(AStream,Length(Value));
AStream.Write(Value[1],Length(Value)*SizeOf(Value[1]))
end;
function ReadDateTime(AStream:TStream):TDateTime;
begin
AStream.Read(Result,SizeOf(Result))
end;
procedure WriteDateTime(AStream:TStream;const Value:TDateTime);
begin
AStream.Write(Value,SizeOf(Value))
end;
function ReadBoolean(AStream:TStream):Boolean;
begin
AStream.Read(Result,SizeOf(Result));
end;
procedure WriteBoolean(AStream:TStream;const Value:Boolean);
begin
AStream.Write(Value,SizeOf(Value))
end;
{ TwcArchive }
constructor TwcArchive.Create(Collection: TCollection);
begin
inherited;
FName:='';
FDateTime:=0;
end;
procedure TwcArchive.Delete;
begin
DeleteFile(Name);
inherited;
end;
function TwcArchive.GetDisplayName: String;
begin
Result:=DateToStr(DateTime,Fmt)
end;
procedure TwcArchive.LoadFromStream(AStream: TStream);
begin
inherited;
FDateTime:=ReadDateTime(AStream);
end;
procedure TwcArchive.SaveToStream(AStream: TStream);
begin
inherited;
WriteDateTime(AStream,FDateTime);
end;
procedure TwcArchive.SetDateTime(const Value: TDateTime);
begin
end;
procedure TwcArchive.SetName(const Value: String);
begin
if not FileExists(Value) then Exit;
inherited;
FDateTime:=Now;
FName:=Value
end;
procedure TwcArchive.SetParentElem(const Value: TwcCollectionItem);
begin
if Value<>nil then
begin
if Value.InheritsFrom(TwcLink) then
begin
Collection:=TwcLink(Value).Archives;
end
end else Free
end;
{ TwcArchives }
function TwcArchives.Add: TwcArchive;
begin
Result:=TwcArchive(inherited Add);
TwcLink(Owner).CheckLimit
end;
constructor TwcArchives.Create(ALink: TwcLink);
begin
inherited Create(ALink,TwcArchive)
end;
function TwcArchives.GetItem(Index: Integer): TwcArchive;
begin
Result:=TwcArchive(inherited GetItem(Index))
end;
procedure TwcArchives.LoadFromStream(AStream: TStream);
var i:integer;
begin
inherited;
i:=0;
while i<Count do
begin
with Items[i] do
if not FileExists(Name) then Free else inc(i)
end;
end;
procedure TwcArchives.SetItem(Index: Integer; Value: TwcArchive);
begin
inherited SetItem(Index,Value)
end;
{ TwcCategoryOrLink }
constructor TwcCategoryOrLink.Create(Collection: TCollection);
begin
inherited;
FName:=UnknownName;
FInsertColor:=clGreen;
FModifyColor:=clYellow;
FDeleteColor:=clRed;
FOwnColors:=False;
FUpdateTime:=3/24;
FOwnUpdateTime:=False;
FActive:=True;
end;
function TwcCategoryOrLink.GetActive: Boolean;
begin
if not HasValues then Result:=True else
if not TwcCategory(ParentElem).Active then Result:=False else
Result:=FActive
end;
function TwcCategoryOrLink.GetDeleteColor: TColor;
begin
if not HasValues then Result:=clRed else
if OwnColors then Result:=FDeleteColor else
Result:=TwcCategory(ParentElem).DeleteColor
end;
function TwcCategoryOrLink.GetInsertColor: TColor;
begin
if not HasValues then Result:=clGreen else
if OwnColors then Result:=FInsertColor else
Result:=TwcCategory(ParentElem).InsertColor
end;
function TwcCategoryOrLink.GetModifyColor: TColor;
begin
if not HasValues then Result:=clYellow else
if OwnColors then Result:=FModifyColor else
Result:=TwcCategory(ParentElem).ModifyColor
end;
function TwcCategoryOrLink.GetUpdateTime: TDateTime;
begin
if not HasValues then Result:=3/24 else
if OwnUpdateTime then Result:=FUpdateTime else
Result:=TwcCategory(ParentElem).UpdateTime
end;
function TwcCategoryOrLink.HasValues: Boolean;
begin
if Self=nil then Result:=False else Result:=Self.InheritsFrom(TwcCategoryOrLink);
end;
procedure TwcCategoryOrLink.LoadFromStream(AStream: TStream);
begin
inherited;
FInsertColor:=ReadInteger(AStream);
FModifyColor:=ReadInteger(AStream);
FDeleteColor:=ReadInteger(AStream);
FOwnColors:=ReadBoolean(AStream);
FUpdateTime:=ReadDateTime(AStream);
FOwnUpdateTime:=ReadBoolean(AStream);
FActive:=ReadBoolean(AStream)
end;
procedure TwcCategoryOrLink.SaveToStream(AStream: TStream);
begin
inherited;
WriteInteger(AStream,FInsertColor);
WriteInteger(AStream,FModifyColor);
WriteInteger(AStream,FDeleteColor);
WriteBoolean(AStream,FOwnColors);
WriteDateTime(AStream,FUpdateTime);
WriteBoolean(AStream,FOwnUpdateTime);
WriteBoolean(AStream,FActive);
end;
procedure TwcCategoryOrLink.SetDeleteColor(const Value: TColor);
begin
FDeleteColor:=Value;
FOwnColors:=True
end;
procedure TwcCategoryOrLink.SetInsertColor(const Value: TColor);
begin
FInsertColor:=Value;
FOwnColors:=True
end;
procedure TwcCategoryOrLink.SetModifyColor(const Value: TColor);
begin
FModifyColor:=Value;
FOwnColors:=True
end;
procedure TwcCategoryOrLink.SetUpdateTime(const Value: TDateTime);
begin
FUpdateTime:=Value;
FOwnUpdateTime:=True
end;
{ TwcLink }
procedure TwcLink.AssignIntf(AIntf: IInterface);
var Intf:IwcLink;
begin
if Supports(AIntf,IID_IwcLink,Intf) then
begin
Name:=Intf.Name;
URL:=Intf.URL;
end;
inherited;
end;
constructor TwcLink.Create(Collection: TCollection);
begin
inherited;
FURL:=UnknownURL;
FLimit:=10;
FArchives:=TwcArchives.Create(Self)
end;
destructor TwcLink.Destroy;
begin
FArchives.Free;
inherited;
end;
procedure TwcLink.LoadFromStream(AStream: TStream);
begin
inherited;
FURL:=ReadString(AStream);
FArchives.LoadFromStream(AStream);
end;
procedure TwcLink.SaveToStream(AStream: TStream);
begin
inherited;
WriteString(AStream,FURL);
FArchives.SaveToStream(AStream);
end;
procedure TwcLink.SetArchives(const Value: TwcArchives);
begin
FArchives.Assign(Value);
end;
procedure TwcLink.SetLimit(const Value: Integer);
begin
if Value>0 then FLimit:=Value else FLimit:=0;
CheckLimit
end;
procedure TwcLink.CheckLimit;
var i,n:integer;
begin
n:=Archives.Count-Limit;
for i:=1 to n do
with Archives[0] do
begin
Delete;
Free;
end;
end;
procedure TwcLink.SetParentElem(const Value: TwcCollectionItem);
begin
if Value<>nil then
if Value is TwcCategory then
Collection:=TwcCategory(Value).Links
end;
procedure TwcLink.SetURL(const AValue: String);
var NewURL:String;
P:Integer;
begin
NewURL:=AValue;
P:=Pos('://',NewURL);
if (P=0)and(Pos('about:',LowerCase(NewURL))<>1) then NewURL:='http://'+NewURL;
FURL:=NewURL
end;
{ TwcLinks }
function TwcLinks.Add: TwcLink;
begin
Result:=TwcLink(inherited Add)
end;
procedure TwcLinks.AssignIntf(AIntf: IInterface);
var i:Integer;Intf:IwcLinks;
begin
if Supports(AIntf,IID_IwcLinks,Intf) then
begin
Clear;
with Intf do
for i:=0 to Count-1 do Add.AssignIntf(Item[i]);
end;
inherited
end;
constructor TwcLinks.Create(ACategory: TwcCategory);
begin
inherited Create(ACategory,TwcLink)
end;
function TwcLinks.GetItem(Index: Integer): TwcLink;
begin
Result:=TwcLink(inherited GetItem(Index))
end;
procedure TwcLinks.SetItem(Index: Integer; Value: TwcLink);
begin
inherited SetItem(Index,Value)
end;
{ TwcCategory }
procedure TwcCategory.AssignIntf(AIntf: IInterface);
var Intf:IwcCategory;
begin
if Supports(AIntf,IID_IwcCategory,Intf) then
begin
Name:=Intf.Name;
SubCategs.AssignIntf(Intf.SubCategs);
Links.AssignIntf(Intf.Links);
end;
inherited
end;
constructor TwcCategory.Create(Collection: TCollection);
begin
inherited;
FSubCategs:=TwcCategs.Create(Self);
FLinks:=TwcLinks.Create(Self)
end;
destructor TwcCategory.Destroy;
begin
FSubCategs.Free;
FLinks.Free;
inherited;
end;
procedure TwcCategory.LoadFromStream(AStream: TStream);
begin
inherited;
FSubCategs.LoadFromStream(AStream);
FLinks.LoadFromStream(AStream);
end;
procedure TwcCategory.SaveToStream(AStream: TStream);
begin
inherited;
FSubCategs.SaveToStream(AStream);
FLinks.SaveToStream(AStream);
end;
procedure TwcCategory.SetLinks(const Value: TwcLinks);
begin
FLinks.Assign(Value);
end;
procedure TwcCategory.SetParentElem(const Value: TwcCollectionItem);
begin
if Value<>nil then
if Value is TwcCategory then
Collection:=TwcCategory(Value).SubCategs
end;
procedure TwcCategory.SetSubCategs(const Value: TwcCategs);
begin
FSubCategs.Assign(Value)
end;
{ TwcCategs }
function TwcCategs.Add: TwcCategory;
begin
Result:=TwcCategory(inherited Add)
end;
procedure TwcCategs.AssignIntf(AIntf: IInterface);
var i:Integer;Intf:IwcCategs;
begin
if Supports(AIntf,IID_IwcCategs,Intf) then
begin
Clear;
with Intf do
for i:=0 to Count-1 do Add.AssignIntf(Item[i]);
end;
inherited
end;
constructor TwcCategs.Create(AParent: TwcCategory);
begin
inherited Create(AParent,TwcCategory)
end;
function TwcCategs.GetItem(Index: Integer): TwcCategory;
begin
Result:=TwcCategory(inherited GetItem(Index))
end;
procedure TwcCategs.SetItem(Index: Integer; Value: TwcCategory);
begin
inherited SetItem(Index,Value)
end;
{ TwcCatalog }
function TwcCatalog.AddIntf(AIntf: IInterface):TwcCollectionItem;
var Intf:IInterface;
begin
if Supports(AIntf,IID_IwcCategory,Intf) then begin Result:=Root.SubCategs.Add;TwcCategory(Result).AssignIntf(Intf) end else
if Supports(AIntf,IID_IwcLink,Intf) then begin Result:=Root.Links.Add;TwcLink(Result).AssignIntf(Intf) end else
if Supports(AIntf,IID_IwcCategs,Intf) then begin Result:=Root.SubCategs.Add;TwcCategory(Result).SubCategs.AssignIntf(Intf) end else
if Supports(AIntf,IID_IwcLinks,Intf) then begin Result:=Root.SubCategs.Add;TwcCategory(Result).Links.AssignIntf(Intf) end else
Result:=nil
end;
constructor TwcCatalog.Create(AOwner: TComponent);
begin
inherited;
FRoot:=TwcCategs.Create(TwcCategory(Self)).Add;
FRoot.Name:='Всі'
end;
destructor TwcCatalog.Destroy;
begin
FRoot.Collection.Free;
inherited;
end;
procedure Register;
begin
RegisterComponents('HTMLDiff',[TwcCatalog]);
RegisterPropertyEditor(TypeInfo(TDateTime),TwcCategoryOrLink,'UpdateTime',TExtTimeProperty);
RegisterPropertyEditor(TypeInfo(TDateTime),TwcArchive,'DateTime',TExtDateTimeProperty)
end;
function CalcHash(Data: pointer; DataSize: integer): integer; register;
asm
push ebx
push esi
push edi
mov esi, Data
xor ebx, ebx
or esi, esi
jz @@Exit
mov edx, DataSize
or edx,edx
jz @@Exit
xor ecx,ecx
@@Cycle:
xor eax,eax
mov al,[esi]
inc esi
rol eax,cl
xor ebx,eax
inc ecx
dec edx
jnz @@Cycle
@@Exit:
mov eax,ebx
pop edi
pop esi
pop ebx
end;
procedure TwcCatalog.LoadFromStream(AStream: TStream);
var _Hash,Hash,_Version:Integer;
Stream:TMemoryStream;
begin
Stream:=TMemoryStream.Create;
try
Stream.CopyFrom(AStream,AStream.Size);
if Stream.Memory<>nil then Hash:=CalcHash(Pointer(Cardinal(Stream.Memory)+SizeOf(Version)),Stream.Size-SizeOf(Version)) else Hash:=0;
Stream.Position:=0;
Stream.Read(_Hash,SizeOf(_Hash));
if Hash<>_Hash then raise Exception.Create('Файл пошкоджено');
Stream.Read(_Version,SizeOf(_Version));
if Version<>_Version then raise Exception.Create('Невідома версія формату файлу');
Root.LoadFromStream(Stream)
finally
Stream.Free
end;
end;
procedure TwcCatalog.SaveToStream(AStream: TStream);
var Hash:Integer;
Stream:TMemoryStream;
begin
Stream:=TMemoryStream.Create;
try
Hash:=0;
Stream.Write(Hash,SizeOf(Hash));
Stream.Write(Version,SizeOf(Version));
Root.SaveToStream(Stream);
if Stream.Memory<>nil then Hash:=CalcHash(Pointer(Cardinal(Stream.Memory)+SizeOf(Hash)),Stream.Size-SizeOf(Hash));
Stream.Position:=0;
Stream.Write(Hash,SizeOf(Hash));
Stream.Position:=0;
AStream.CopyFrom(Stream,Stream.Size)
finally
Stream.Free
end;
end;
procedure TwcCatalog.SetRoot(const Value: TwcCategory);
begin
FRoot.Assign(Value);
end;
{ TExtTimeProperty }
function TExtTimeProperty.GetValue: String;
var T:TDateTime;
begin
T:=GetFloatValue;
if T=0 then Result:=UnknownName else Result:=TimeToStr(T,Fmt)
end;
procedure TExtTimeProperty.SetValue(const Value: String);
begin
SetFloatValue(StrToTimeDef(Value,GetFloatValue,Fmt))
end;
{ TExtDateTimeProperty }
function TExtDateTimeProperty.GetValue: String;
var DT:TDateTime;
begin
DT:=GetFloatValue;
if DT=0 then Result:=UnknownName else Result:=DateToStr(DT,Fmt)
end;
procedure TExtDateTimeProperty.SetValue(const Value: String);
begin
SetFloatValue(StrToDateDef(Value,GetFloatValue,Fmt))
end;
{ TwcCollection }
procedure TwcCollection.AssignIntf(AIntf: IInterface);
begin
end;
procedure TwcCollection.LoadFromStream(AStream: TStream);
var n:integer;
begin
Clear;
n:=ReadInteger(AStream);
while n>0 do
begin
TwcCollectionItem(Add).LoadFromStream(AStream);
Dec(n)
end
end;
procedure TwcCollection.SaveToStream(AStream: TStream);
var i:integer;
begin
WriteInteger(AStream,Count);
for i:=0 to Count-1 do TwcCollectionItem(Items[i]).SaveToStream(AStream)
end;
{ TwcCollectionItem }
constructor TwcCollectionItem.Create(Collection: TCollection);
begin
inherited;
FName:=UnknownName;
end;
function TwcCollectionItem.GetDisplayName: String;
begin
Result:=FName
end;
procedure TwcCollectionItem.LoadFromStream(AStream: TStream);
begin
FName:=ReadString(AStream)
end;
function TwcCollectionItem.GetParentElem: TwcCollectionItem;
begin
if Collection<>nil then Result:=TwcCollectionItem(Collection.Owner) else Result:=nil
end;
procedure TwcCollectionItem.SaveToStream(AStream: TStream);
begin
WriteString(AStream,FName);
end;
procedure TwcCollectionItem.SetName(const Value: String);
begin
FName:=Value;
end;
procedure TwcCollectionItem.SetParentElem(const Value: TwcCollectionItem);
begin
end;
procedure TwcCollectionItem.Delete;
begin
end;
procedure TwcCollectionItem.AssignIntf(AIntf: IInterface);
begin
end;
procedure TwcCollectionItem.Assign(Source: TPersistent);
var Stream:TMemoryStream;
begin
if Source.InheritsFrom(TwcCollectionItem) then
begin
Stream:=TMemoryStream.Create;
try
TwcCollectionItem(Source).SaveToStream(Stream);
Stream.Position:=0;
LoadFromStream(Stream);
finally
Stream.Free
end;
Exit
end;
inherited Assign(Source)
end;
initialization
GetLocaleFormatSettings(1,Fmt);
Fmt.ShortDateFormat:='dd.MM.yyyy HH:mm:ss';
Fmt.LongDateFormat:=Fmt.ShortDateFormat;
Fmt.ShortTimeFormat:='HH:mm:ss';
Fmt.LongTimeFormat:=Fmt.ShortTimeFormat;
end.
|
unit uExifInfo;
interface
uses
Generics.Collections,
System.SysUtils,
System.Classes,
Winapi.Windows,
Vcl.ValEdit,
CCR.Exif,
CCR.Exif.BaseUtils,
CCR.Exif.XMPUtils,
Dmitry.Utils.System,
UnitDBDeclare,
UnitLinksSupport,
uConstants,
uMemory,
uStringUtils,
uRawExif,
uExifUtils,
uImageLoader,
uDBEntities,
uAssociations,
uICCProfile,
uTranslate,
uLogger;
type
IExifInfoLine = interface
['{83B2D82D-B8AC-4F75-80AC-C221EB06E903}']
function GetID: string;
function GetName: string;
function GetValue: string;
function GetIsExtended: Boolean;
property ID: string read GetID;
property Name: string read GetName;
property Value: string read GetValue;
property IsExtended: Boolean read GetIsExtended;
end;
IExifInfo = interface
['{D7927F65-F84E-4ED5-A711-95DB23271182}']
function AddLine(Line: IExifInfoLine): IExifInfoLine;
function GetEnumerator: TEnumerator<IExifInfoLine>;
function GetValueByKey(Key: string): string;
function GetDescriptionByKey(Key: string): string;
end;
TExifInfo = class(TInterfacedObject, IExifInfo)
private
FItems: TList<IExifInfoLine>;
public
constructor Create;
destructor Destroy; override;
function AddLine(Line: IExifInfoLine): IExifInfoLine;
function GetEnumerator: TEnumerator<IExifInfoLine>;
function GetValueByKey(Key: string): string;
function GetDescriptionByKey(Key: string): string;
end;
TExifInfoLine = class(TInterfacedObject, IExifInfoLine)
private
FID, FName, FValue: string;
FIsExtended: Boolean;
public
constructor Create(ID, AName, AValue: string; AIsExtended: Boolean);
function GetID: string;
function GetName: string;
function GetValue: string;
function GetIsExtended: Boolean;
end;
procedure LoadExifInfo(VleEXIF: TValueListEditor; FileName: string);
function FillExifInfo(ExifData: TExifData; RawExif: TRawExif; out Info: IExifInfo): Boolean;
implementation
procedure LoadExifInfo(VleEXIF: TValueListEditor; FileName: string);
var
OldMode: Cardinal;
ExifInfo: IExifInfo;
Line: IExifInfoLine;
Info: TMediaItem;
ImageInfo: ILoadImageInfo;
function L(S: string): string;
begin
Result := TA(S, 'PropertiesForm');
end;
begin
VleEXIF.Strings.BeginUpdate;
try
VleEXIF.Strings.Clear;
OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
try
Info := TMediaItem.CreateFromFile(FileName);
try
if LoadImageFromPath(Info, -1, '', [ilfICCProfile, ilfEXIF, ilfPassword, ilfDontUpdateInfo], ImageInfo) then
begin
if FillExifInfo(ImageInfo.ExifData, ImageInfo.RawExif, ExifInfo) then
begin
for Line in ExifInfo do
VleEXIF.InsertRow(Line.Name + ': ', Line.Value, True);
end;
end;
finally
F(Info);
end;
except
on e: Exception do
begin
VleEXIF.InsertRow(L('Info:'), L('Exif header not found.'), True);
Eventlog(e.Message);
end;
end;
finally
SetErrorMode(OldMode);
end;
finally
VleEXIF.Strings.EndUpdate;
end;
end;
function FillExifInfo(ExifData: TExifData; RawExif: TRAWExif; out Info: IExifInfo): Boolean;
var
Orientation: Integer;
Groups: TGroups;
Links: TLinksInfo;
SL: TStringList;
I: Integer;
ICCProfileMem: TMemoryStream;
ICCProfile: string;
People: TPersonAreaCollection;
const
XMPBasicValues: array[TWindowsStarRating] of UnicodeString = ('', '1', '2', '3', '4', '5');
function L(S: string): string;
begin
Result := TA(S, 'PropertiesForm');
Result := TA(Result, 'EXIF');
end;
procedure XInsert(ID, Key, Value: string; IsExtended: Boolean = False; Appendix: string = '');
var
Line: IExifInfoLine;
begin
Value := Trim(Value);
if Value <> '' then
begin
Line := TExifInfoLine.Create(ID, Key, Value + Appendix, IsExtended);
Info.AddLine(Line);
end;
end;
function FractionToString(Fraction: TExifFraction): string;
begin
if Fraction.Denominator <> 0 then
Result := FormatFloat('0.0' , Fraction.Numerator / Fraction.Denominator)
else
Result := Fraction.AsString;
end;
function ExposureFractionToString(Fraction: TExifFraction): string;
begin
if Fraction.Numerator <> 0 then
Result := '1/' + FormatFloat('0' , Fraction.Denominator / Fraction.Numerator)
else
Result := Fraction.AsString;
end;
function FormatBiasFraction(Fraction: TExifSignedFraction): string;
begin
if Fraction.Denominator <> 0 then
Result := FractionToUnicodeString(Fraction.Numerator, Fraction.Denominator)
else
Result := Fraction.AsString;
end;
begin
Result := ExifData <> nil;
if not Result then
Exit;
TTranslateManager.Instance.BeginTranslate;
try
Info := TExifInfo.Create;
if not ExifData.Empty or not ExifData.XMPPacket.Empty then
begin
if not ExifData.Empty then
begin
XInsert('CameraMake', L('Make'), ExifData.CameraMake);
XInsert('CameraModel', L('Model'), ExifData.CameraModel);
XInsert('Copyright', L('Copyright'), ExifData.Copyright);
if ExifData.ImageDateTime > 0 then
XInsert('DateTimeOriginal', L('Date and time'), FormatDateTime('yyyy/mm/dd HH:MM:SS', ExifData.ImageDateTime));
XInsert('ImageDescription', L('Description'), ExifData.ImageDescription);
XInsert('Software', L('Software'), ExifData.Software);
Orientation := ExifOrientationToRatation(Ord(ExifData.Orientation));
case Orientation and DB_IMAGE_ROTATE_MASK of
DB_IMAGE_ROTATE_0:
XInsert('Orientation', L('Orientation'), L('Normal'));
DB_IMAGE_ROTATE_90:
XInsert('Orientation', L('Orientation'), L('Right'));
DB_IMAGE_ROTATE_270:
XInsert('Orientation', L('Orientation'), L('Left'));
DB_IMAGE_ROTATE_180:
XInsert('Orientation', L('Orientation'), L('180 grad.'));
end;
XInsert('ExposureTime', L('Exposure'), ExposureFractionToString(ExifData.ExposureTime), False, L('s'));
if not ExifData.ExposureBiasValue.MissingOrInvalid and (ExifData.ExposureBiasValue.Numerator <> 0) then
XInsert('ExposureBiasValue', L('Exposure bias'), FormatBiasFraction(ExifData.ExposureBiasValue));
XInsert('ISOSpeedRatings', L('ISO'), ExifData.ISOSpeedRatings.AsString);
XInsert('FocalLength', L('Focal length'), FractionToString(ExifData.FocalLength), False, L('mm'));
XInsert('FNumber', L('F number'), FractionToString(ExifData.FNumber));
//TODO: ?
{ExifData.ApertureValue
ExifData.BrightnessValue
ExifData.Contrast
ExifData.Saturation
ExifData.Sharpness
ExifData.MeteringMode
ExifData.SubjectDistance }
end;
if ExifData.XMPPacket.Lens <> '' then
XInsert('Lens', L('Lens'), ExifData.XMPPacket.Lens)
else if not ExifData.Empty and (ExifData.LensModel <> '') then
XInsert('Lens', L('Lens'), ExifData.LensModel);
if not ExifData.Empty then
begin
if ExifData.Flash.Fired then
XInsert('Flash', L('Flash'), L('On'))
else
XInsert('Flash', L('Flash'), L('Off'));
if (ExifData.ExifImageWidth.Value > 0) and (ExifData.ExifImageHeight.Value > 0) then
begin
XInsert('Width', L('Width'), Format('%dpx.', [ExifData.ExifImageWidth.Value]));
XInsert('Height', L('Height'), Format('%dpx.', [ExifData.ExifImageHeight.Value]));
end;
XInsert('Author', L('Author'), ExifData.Author);
XInsert('Comments', L('Comments'), ExifData.Comments);
XInsert('Keywords', L('Keywords'), ExifData.Keywords);
XInsert('Subject', L('Subject'), ExifData.Subject);
XInsert('Title', ('Title'), ExifData.Title);
if ExifData.UserRating <> urUndefined then
XInsert('UserRating', L('User Rating'), XMPBasicValues[ExifData.UserRating]);
if (ExifData.GPSLatitude <> nil) and (ExifData.GPSLongitude <> nil) and not ExifData.GPSLatitude.MissingOrInvalid and not ExifData.GPSLongitude.MissingOrInvalid then
begin
XInsert('GPSLatitude', L('Latitude'), ExifData.GPSLatitude.AsString);
XInsert('GPSLongitude', L('Longitude'), ExifData.GPSLongitude.AsString);
end;
if ExifData.HasICCProfile then
begin
ICCProfileMem := TMemoryStream.Create;
try
if ExifData.ExtractICCProfile(ICCProfileMem) then
begin
ICCProfile := GetICCProfileName(ExifData, ICCProfileMem.Memory, ICCProfileMem.Size);
if ICCProfile <> '' then
XInsert('ICCProfile', L('ICC profile'), ICCProfile);
end;
finally
F(ICCProfileMem);
end;
end;
end;
if not ExifData.XMPPacket.Include then
XInsert('Base search', L('Base search'), L('No'));
if ExifData.XMPPacket.Groups <> '' then
begin
Groups := TGroups.CreateFromString(ExifData.XMPPacket.Groups);
SL := TStringList.Create;
try
for I := 0 to Groups.Count - 1 do
if Groups[I].GroupName <> '' then
SL.Add(Groups[I].GroupName);
XInsert('Groups', L('Groups'), SL.Join(', '));
finally
F(SL);
F(Groups);
end;
end;
if ExifData.XMPPacket.Links <> '' then
begin
Links := ParseLinksInfo(ExifData.XMPPacket.Links);
SL := TStringList.Create;
try
for I := 0 to Length(Links) - 1 do
if Links[I].LinkName <> '' then
SL.Add(Links[I].LinkName);
XInsert('Links', L('Links'), SL.Join(', '));
finally
F(SL);
end;
end;
if ExifData.XMPPacket.People <> '' then
begin
People := TPersonAreaCollection.CreateFromXml(ExifData.XMPPacket.People);
try
SL := TStringList.Create;
try
for I := 0 to People.Count - 1 do
if People[I].PersonName <> '' then
SL.Add(People[I].PersonName);
XInsert('People', L('People on photo'), SL.Join(', '));
finally
F(SL);
end;
finally
F(People);
end;
end;
if ExifData.XMPPacket.Access = Db_access_private then
XInsert('Private', L('Private'), L('Yes'));
end else
begin
if (RawExif <> nil) and (RawExif.Count > 0) then
begin
for I := 0 to RawExif.Count - 1 do
XInsert(RawExif[I].Key, L(RawExif[I].Description), RawExif[I].Value);
end else
XInsert('Info', L('Info'), L('Exif header not found.'));
end;
finally
TTranslateManager.Instance.EndTranslate;
end;
end;
{ TExifInfoLine }
constructor TExifInfoLine.Create(ID, AName, AValue: string; AIsExtended: Boolean);
begin
FID := ID;
FName := AName;
FValue := AValue;
FIsExtended := AIsExtended;
end;
function TExifInfoLine.GetID: string;
begin
Result := FID;
end;
function TExifInfoLine.GetIsExtended: Boolean;
begin
Result := FIsExtended;
end;
function TExifInfoLine.GetName: string;
begin
Result := FName;
end;
function TExifInfoLine.GetValue: string;
begin
Result := FValue;
end;
{ TExifInfo }
function TExifInfo.AddLine(Line: IExifInfoLine): IExifInfoLine;
begin
FItems.Add(Line);
end;
constructor TExifInfo.Create;
begin
FItems := TList<IExifInfoLine>.Create;
end;
destructor TExifInfo.Destroy;
begin
F(FItems);
inherited;
end;
function TExifInfo.GetDescriptionByKey(Key: string): string;
var
I: Integer;
Line: IExifInfoLine;
begin
for I := 0 to FItems.Count - 1 do
begin
Line := FItems[I];
if Line.ID = Key then
Exit(Line.Name);
end;
Exit('');
end;
function TExifInfo.GetEnumerator: TEnumerator<IExifInfoLine>;
begin
Result := FItems.GetEnumerator;
end;
function TExifInfo.GetValueByKey(Key: string): string;
var
I: Integer;
Line: IExifInfoLine;
begin
for I := 0 to FItems.Count - 1 do
begin
Line := FItems[I];
if Line.ID = Key then
Exit(Line.Value);
end;
Exit('');
end;
end.
|
unit FmTstGIF;
{ Exports TTestGifForm, which is the main form of the small test
program "TestGif" which demonstrates the TGifFile object of
the unit GifUnit.
By Reinier Sterkenburg, Delft, The Netherlands
10 Mar 97: - created
3 Apr 97: - added Image Info option (using FmImInfo and FmSubImg)
2 Aug 97: - adapted to changes in used units
}
interface
uses
WinProcs, WinTypes, {Windows,} Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, ExtCtrls,
ColorTbl, { Imports TColorTable }
DynArrB, { Imports TByteArray2D }
FmAbout, { Imports AboutBox }
GifDecl, { Imports CheckType }
GifUnit, { Imports TGifFile }
IniFiles; { Imports TIniFile }
type
TTestGifForm = class(TForm)
MainMenu1: TMainMenu;
File1: TMenuItem;
Open1: TMenuItem;
Save1: TMenuItem;
Saveas1: TMenuItem;
Exit1: TMenuItem;
About1: TMenuItem;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
Image: TImage;
Edit1: TMenuItem;
Imageinfo1: TMenuItem;
procedure Open1Click(Sender: TObject);
procedure Save1Click(Sender: TObject);
procedure Saveas1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure Imageinfo1Click(Sender: TObject);
private
{ Private declarations }
GifFile: TGifFile;
Filename: String;
public
{ Public declarations }
end; { TTestGifForm }
var
TestGifForm: TTestGifForm;
implementation
uses FmImInfo;
{$R *.DFM}
const
CRLF = #13+#10;
procedure TTestGifForm.Open1Click(Sender: TObject);
var
IniFilename: String;
IniFile: TIniFile;
Bitmap: TBitmap;
Colormap: TColorTable;
Pixels: TByteArray2D;
begin { TTestGifForm.Open1Click }
IniFilename := Application.Exename;
IniFilename := ChangeFileExt(Inifilename, '.ini');
IniFile := TIniFile.Create(IniFilename);
OpenDialog.InitialDir := Inifile.ReadString('History', 'Last directory for reading', '');
if OpenDialog.Execute
then begin
case CheckType(OpenDialog.Filename) of
GIF: begin
GifFile := TGifFile.Create;
GifFile.LoadFromFile(OpenDialog.Filename);
Image.Picture.Bitmap := GifFile.AsBitmap;
Filename := OpenDialog.Filename;
Inifile.WriteString('History', 'Last directory for reading', ExtractFilePath(Filename));
end;
BMP: begin
Bitmap := TBitmap.Create;
Bitmap.LoadFromFile(OpenDialog.Filename);
Image.Picture.Bitmap := Bitmap;
BitmapToPixelmatrix(Bitmap, Colormap, Pixels);
GifFile := TGifFile.Create;
GifFile.AddSubImage(Colormap, Pixels);
Inifile.WriteString('History', 'Last directory for reading', ExtractFilePath(Filename));
end;
else ShowMessage('Cannot read file type');
end; { case }
end;
IniFile.Free;
end; { TTestGifForm.Open1Click }
procedure TTestGifForm.Save1Click(Sender: TObject);
var CanSave: Boolean;
begin { TTestGifForm.Save1Click }
if not FileExists(Filename)
then CanSave := True
else CanSave := MessageDlg('File '+Filename+' already exists, overwrite?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes;
if CanSave
then GifFile.SaveToFile(Filename)
end; { TTestGifForm.Save1Click }
procedure TTestGifForm.Saveas1Click(Sender: TObject);
var
IniFile: TIniFile;
IniFilename: String;
begin { TTestGifForm.Saveas1Click }
IniFilename := Application.Exename;
IniFilename := ChangeFileExt(Inifilename, '.ini');
IniFile := TIniFile.Create(IniFilename);
SaveDialog.InitialDir := Inifile.ReadString('History', 'Last directory for writing', '');
if SaveDialog.Execute
then begin
Filename := SaveDialog.Filename;
Save1Click(Sender);
Inifile.WriteString('History', 'Last directory for writing', ExtractFilePath(Filename));
end;
IniFile.Free;
end; { TTestGifForm.Saveas1Click }
procedure TTestGifForm.Exit1Click(Sender: TObject);
begin { TTestGifForm.Exit1Click }
Close
end; { TTestGifForm.Exit1Click }
procedure TTestGifForm.About1Click(Sender: TObject);
begin { TTestGifForm.About1Click }
AboutBox.Show;
end; { TTestGifForm.About1Click }
procedure TTestGifForm.Imageinfo1Click(Sender: TObject);
var GifImageInfoDialog: TGifImageInfoDialog;
begin { TTestGifForm.Imageinfo1Click }
GifImageInfoDialog := TGifImageInfoDialog.Create(GifFile);
GifImageInfoDialog.ShowModal;
GifImageInfoDialog.Free;
end; { TTestGifForm.Imageinfo1Click }
end.
|
PROGRAM WorkWithQueryString(INPUT, OUTPUT);
USES
DOS;
VAR
ReceivedQueryString: STRING;
FUNCTION GetQueryStringParameter(Key: STRING): STRING;
VAR
LengthParametr, LengthQueryString, FindParametr, FindEndOfDirtyParametr: INTEGER;
DirtyParametr: STRING;
BEGIN
ReceivedQueryString := GetEnv('QUERY_STRING');
FindParametr := POS(Key + '=', ReceivedQueryString);
IF FindParametr > 0
THEN
BEGIN
LengthQueryString := length(ReceivedQueryString);
DirtyParametr := COPY(ReceivedQueryString, FindParametr + length(Key) + 1, LengthQueryString - (FindParametr + length(Key)));
FindEndOfDirtyParametr := POS('&', DirtyParametr);
IF FindEndOfDirtyParametr > 0
THEN
GetQueryStringParameter := COPY(DirtyParametr, 1, FindEndOfDirtyParametr - 1)
ELSE
GetQueryStringParameter := COPY(DirtyParametr, 1, length(DirtyParametr))
END
ELSE
GetQueryStringParameter := ''
END;
BEGIN {WorkWithQueryString}
WRITELN('Content-Type: text/plain');
WRITELN;
WRITELN('First Name: ', GetQueryStringParameter('first_name'));
WRITELN('Last Name: ', GetQueryStringParameter('last_name'));
WRITELN('Age: ', GetQueryStringParameter('age'))
END. {WorkWithQueryString}
|
unit BCEditor.Editor.LeftMargin.Colors;
interface
uses
System.Classes, Vcl.Graphics, BCEditor.Consts;
type
TBCEditorLeftMarginColors = class(TPersistent)
strict private
FActiveLineBackground: TColor;
FBackground: TColor;
FBookmarkPanelBackground: TColor;
FBorder: TColor;
FLineNumberLine: TColor;
FLineStateModified: TColor;
FLineStateNormal: TColor;
FOnChange: TNotifyEvent;
procedure SetActiveLineBackground(const AValue: TColor);
procedure SetBackground(const AValue: TColor);
procedure SetBookmarkPanelBackground(const AValue: TColor);
procedure SetBorder(const AValue: TColor);
procedure SetLineNumberLine(const AValue: TColor);
procedure SetLineStateModified(const AValue: TColor);
procedure SetLineStateNormal(const AValue: TColor);
procedure DoChange;
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
published
property ActiveLineBackground: TColor read FActiveLineBackground write SetActiveLineBackground default clActiveLineBackground;
property Background: TColor read FBackground write SetBackground default clLeftMarginBackground;
property BookmarkPanelBackground: TColor read FBookmarkPanelBackground write SetBookmarkPanelBackground default clLeftMarginBackground;
property Border: TColor read FBorder write SetBorder default clLeftMarginBackground;
property LineNumberLine: TColor read FLineNumberLine write SetLineNumberLine default clLeftMarginFontForeground;
property LineStateModified: TColor read FLineStateModified write SetLineStateModified default clYellow;
property LineStateNormal: TColor read FLineStateNormal write SetLineStateNormal default clLime;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
{ TBCEditorLeftMarginColors }
constructor TBCEditorLeftMarginColors.Create;
begin
inherited;
FActiveLineBackground := clActiveLineBackground;
FBackground := clLeftMarginBackground;
FBookmarkPanelBackground := clLeftMarginBackground;
FBorder := clLeftMarginBackground;
FLineNumberLine := clLeftMarginFontForeground;
FLineStateModified := clYellow;
FLineStateNormal := clLime;
end;
procedure TBCEditorLeftMarginColors.Assign(ASource: TPersistent);
begin
if ASource is TBCEditorLeftMarginColors then
with ASource as TBCEditorLeftMarginColors do
begin
Self.FActiveLineBackground := FActiveLineBackground;
Self.FBackground := FBackground;
Self.FBookmarkPanelBackground := FBookmarkPanelBackground;
Self.FBorder := FBorder;
Self.FLineNumberLine := FLineNumberLine;
Self.FLineStateModified := FLineStateModified;
Self.FLineStateNormal := FLineStateNormal;
Self.DoChange;
end
else
inherited Assign(ASource);
end;
procedure TBCEditorLeftMarginColors.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBCEditorLeftMarginColors.SetActiveLineBackground(const AValue: TColor);
begin
if FActiveLineBackground <> AValue then
begin
FActiveLineBackground := AValue;
DoChange;
end;
end;
procedure TBCEditorLeftMarginColors.SetBackground(const AValue: TColor);
begin
if FBackground <> AValue then
begin
FBackground := AValue;
DoChange;
end;
end;
procedure TBCEditorLeftMarginColors.SetBookmarkPanelBackground(const AValue: TColor);
begin
if FBookmarkPanelBackground <> AValue then
begin
FBookmarkPanelBackground := AValue;
DoChange;
end;
end;
procedure TBCEditorLeftMarginColors.SetBorder(const AValue: TColor);
begin
if FBorder <> AValue then
begin
FBorder := AValue;
DoChange;
end;
end;
procedure TBCEditorLeftMarginColors.SetLineNumberLine(const AValue: TColor);
begin
if FLineNumberLine <> AValue then
begin
FLineNumberLine := AValue;
DoChange;
end;
end;
procedure TBCEditorLeftMarginColors.SetLineStateModified(const AValue: TColor);
begin
if FLineStateModified <> AValue then
begin
FLineStateModified := AValue;
DoChange;
end;
end;
procedure TBCEditorLeftMarginColors.SetLineStateNormal(const AValue: TColor);
begin
if FLineStateNormal <> AValue then
begin
FLineStateNormal := AValue;
DoChange;
end;
end;
end.
|
// Diese Unit wird automatisch durch das Tool "./Tool/Embedded_List_to_const" erzeugt.
// Die Arrays werden aus "./fpc.src/fpc/compiler/avr/cpuinfo.pas" und
// "./fpc.src/fpc/compiler/arm/cpuinfo.pas" importiert.
unit Embedded_GUI_Embedded_List_Const;
interface
const
i8086_SubArch_List =
'8086,80186,80286,80386,80486,PENTIUM,PENTIUM2,PENTIUM3,PENTIUM4,PENTIUMM';
i8086_List: array of string = (
// 8086
'',
// 80186
'',
// 80286
'',
// 80386
'',
// 80486
'',
// PENTIUM
'',
// PENTIUM2
'',
// PENTIUM3
'',
// PENTIUM4
'',
// PENTIUMM
'');
const
aarch64_SubArch_List =
'ARMV8';
aarch64_List: array of string = (
// ARMV8
'');
const
powerpc64_SubArch_List =
'970';
powerpc64_List: array of string = (
// 970
'');
const
avr_SubArch_List =
'AVRTINY,AVR1,AVR2,AVR25,AVR3,AVR31,AVR35,AVR4,AVR5,AVR51,AVR6,AVRXMEGA3';
avr_List: array of string = (
// AVRTINY
'ATTINY4,ATTINY5,ATTINY9,ATTINY10,' +
'ATTINY20,ATTINY40,ATTINY102,ATTINY104',
// AVR1
'ATTINY11,ATTINY12,ATTINY15,ATTINY28',
// AVR2
'ATTINY26',
// AVR25
'ATTINY13,ATTINY13A,ATTINY24,ATTINY24A,' +
'ATTINY25,ATTINY43U,ATTINY44,ATTINY44A,' +
'ATTINY45,ATTINY48,ATTINY84,ATTINY84A,' +
'ATTINY85,ATTINY87,ATTINY88,ATTINY261,' +
'ATTINY261A,ATTINY441,ATTINY461,ATTINY461A,' +
'ATTINY828,ATTINY841,ATTINY861,ATTINY861A,' +
'ATTINY2313,ATTINY2313A,ATTINY4313',
// AVR3
'',
// AVR31
'',
// AVR35
'AT90USB82,AT90USB162,ATMEGA8U2,ATMEGA16U2,' +
'ATMEGA32U2,ATTINY167,ATTINY1634',
// AVR4
'AT90PWM1,AT90PWM2B,AT90PWM3B,AT90PWM81,' +
'ATA6285,ATA6286,ATMEGA8,ATMEGA8A,' +
'ATMEGA8HVA,ATMEGA48,ATMEGA48A,ATMEGA48P,' +
'ATMEGA48PA,ATMEGA48PB,ATMEGA88,ATMEGA88A,' +
'ATMEGA88P,ATMEGA88PA,ATMEGA88PB,ATMEGA8515,' +
'ATMEGA8535',
// AVR5
'AVRSIM,AT90CAN32,AT90CAN64,AT90PWM161,' +
'AT90PWM216,AT90PWM316,AT90USB646,AT90USB647,' +
'ATMEGA16,ATMEGA16A,ATMEGA16HVA,ATMEGA16HVB,' +
'ATMEGA16HVBREVB,ATMEGA16M1,ATMEGA16U4,ATMEGA32,' +
'ATMEGA32A,ATMEGA32C1,ATMEGA32HVB,ATMEGA32HVBREVB,' +
'ATMEGA32M1,ATMEGA32U4,ATMEGA64,ATMEGA64A,' +
'ATMEGA64C1,ATMEGA64HVE2,ATMEGA64M1,ATMEGA64RFR2,' +
'ATMEGA162,ATMEGA164A,ATMEGA164P,ATMEGA164PA,' +
'ATMEGA165A,ATMEGA165P,ATMEGA165PA,ATMEGA168,' +
'ATMEGA168A,ATMEGA168P,ATMEGA168PA,ATMEGA168PB,' +
'ATMEGA169A,ATMEGA169P,ATMEGA169PA,ATMEGA324A,' +
'ATMEGA324P,ATMEGA324PA,ATMEGA324PB,ATMEGA325,' +
'ATMEGA325A,ATMEGA325P,ATMEGA325PA,ATMEGA328,' +
'ATMEGA328P,ATMEGA328PB,ATMEGA329,ATMEGA329A,' +
'ATMEGA329P,ATMEGA329PA,ATMEGA406,ATMEGA640,' +
'ATMEGA644,ATMEGA644A,ATMEGA644P,ATMEGA644PA,' +
'ATMEGA644RFR2,ATMEGA645,ATMEGA645A,ATMEGA645P,' +
'ATMEGA649,ATMEGA649A,ATMEGA649P,ATMEGA3250,' +
'ATMEGA3250A,ATMEGA3250P,ATMEGA3250PA,ATMEGA3290,' +
'ATMEGA3290A,ATMEGA3290P,ATMEGA3290PA,ATMEGA6450,' +
'ATMEGA6450A,ATMEGA6450P,ATMEGA6490,ATMEGA6490A,' +
'ATMEGA6490P,ARDUINOLEONARDO,ARDUINOMICRO,ARDUINONANO,' +
'ARDUINOUNO,ATMEGA324PBXPRO',
// AVR51
'AT90CAN128,AT90USB1286,AT90USB1287,ATMEGA128,' +
'ATMEGA128A,ATMEGA128RFA1,ATMEGA128RFR2,ATMEGA1280,' +
'ATMEGA1281,ATMEGA1284,ATMEGA1284P,ATMEGA1284RFR2,' +
'ATMEGA1284PXPLAINED',
// AVR6
'ATMEGA256RFR2,ATMEGA2560,ATMEGA2561,ATMEGA2564RFR2,' +
'ARDUINOMEGA,ATMEGA256RFR2XPRO',
// AVRXMEGA3
'ATMEGA808,ATMEGA809,ATMEGA1608,ATMEGA1609,' +
'ATMEGA3208,ATMEGA3209,ATMEGA4808,ATMEGA4809,' +
'ATTINY202,ATTINY204,ATTINY212,ATTINY214,' +
'ATTINY402,ATTINY404,ATTINY406,ATTINY412,' +
'ATTINY414,ATTINY416,ATTINY416AUTO,ATTINY417,' +
'ATTINY804,ATTINY806,ATTINY807,ATTINY814,' +
'ATTINY816,ATTINY817,ATTINY1604,ATTINY1606,' +
'ATTINY1607,ATTINY1614,ATTINY1616,ATTINY1617,' +
'ATTINY1624,ATTINY1626,ATTINY1627,ATTINY3214,' +
'ATTINY3216,ATTINY3217,ARDUINONANOEVERY,ATMEGA4809XPRO,' +
'ATTINY817XPRO,ATTINY3217XPRO');
const
x86_64_SubArch_List =
'ATHLON64,COREI,COREAVX,COREAVX2';
x86_64_List: array of string = (
// ATHLON64
'',
// COREI
'',
// COREAVX
'',
// COREAVX2
'');
const
riscv64_SubArch_List =
'RV64IMAC,RV64IMA,RV64IM,RV64I';
riscv64_List: array of string = (
// RV64IMAC
'',
// RV64IMA
'',
// RV64IM
'',
// RV64I
'');
const
powerpc_SubArch_List =
'604,750,7400,970';
powerpc_List: array of string = (
// 604
'',
// 750
'',
// 7400
'',
// 970
'');
const
arm_SubArch_List =
'ARMV3,ARMV4,ARMV4T,ARMV5,ARMV5T,ARMV5TE,ARMV5TEJ,ARMV6,ARMV6K,ARMV6T2,ARMV6Z,ARMV6M,ARMV7,ARMV7A,ARMV7R,ARMV7M,ARMV7EM';
arm_List: array of string = (
// ARMV3
'',
// ARMV4
'',
// ARMV4T
'LPC2114,LPC2124,LPC2194,AT91SAM7S256,' +
'AT91SAM7SE256,AT91SAM7X256,AT91SAM7XC256,SC32442B',
// ARMV5
'',
// ARMV5T
'',
// ARMV5TE
'',
// ARMV5TEJ
'',
// ARMV6
'',
// ARMV6K
'',
// ARMV6T2
'',
// ARMV6Z
'',
// ARMV6M
'LPC810M021FN8,LPC811M001FDH16,LPC812M101FDH16,LPC812M101FD20,' +
'LPC812M101FDH20,LPC1110FD20,LPC1111FDH20_002,LPC1111FHN33_101,' +
'LPC1111FHN33_102,LPC1111FHN33_103,LPC1111FHN33_201,LPC1111FHN33_202,' +
'LPC1111FHN33_203,LPC1112FD20_102,LPC1112FDH20_102,LPC1112FDH28_102,' +
'LPC1112FHN33_101,LPC1112FHN33_102,LPC1112FHN33_103,LPC1112FHN33_201,' +
'LPC1112FHN24_202,LPC1112FHN33_202,LPC1112FHN33_203,LPC1112FHI33_202,' +
'LPC1112FHI33_203,LPC1113FHN33_201,LPC1113FHN33_202,LPC1113FHN33_203,' +
'LPC1113FHN33_301,LPC1113FHN33_302,LPC1113FHN33_303,LPC1113FBD48_301,' +
'LPC1113FBD48_302,LPC1113FBD48_303,LPC1114FDH28_102,LPC1114FN28_102,' +
'LPC1114FHN33_201,LPC1114FHN33_202,LPC1114FHN33_203,LPC1114FHN33_301,' +
'LPC1114FHN33_302,LPC1114FHN33_303,LPC1114FHN33_333,LPC1114FHI33_302,' +
'LPC1114FHI33_303,LPC1114FBD48_301,LPC1114FBD48_302,LPC1114FBD48_303,' +
'LPC1114FBD48_323,LPC1114FBD48_333,LPC1115FBD48_303,LPC11C12FBD48_301,' +
'LPC11C14FBD48_301,LPC11C22FBD48_301,LPC11C24FBD48_301,LPC11D14FBD100_302,' +
'LPC1224FBD48_101,LPC1224FBD48_121,LPC1224FBD64_101,LPC1224FBD64_121,' +
'LPC1225FBD48_301,LPC1225FBD48_321,LPC1225FBD64_301,LPC1225FBD64_321,' +
'LPC1226FBD48_301,LPC1226FBD64_301,LPC1227FBD48_301,LPC1227FBD64_301,' +
'LPC12D27FBD100_301,STM32F030C6,STM32F030C8,STM32F030F4,' +
'STM32F030K6,STM32F030R8,STM32F050C4,STM32F050C6,' +
'STM32F050F4,STM32F050F6,STM32F050G4,STM32F050G6,' +
'STM32F050K4,STM32F050K6,STM32F051C4,STM32F051C6,' +
'STM32F051C8,STM32F051K4,STM32F051K6,STM32F051K8,' +
'STM32F051R4,STM32F051R6,STM32F051R8,STM32F091CC,' +
'STM32F091CB,STM32F091RC,STM32F091RB,STM32F091VC,' +
'STM32F091VB,STM32G071RB,NUCLEOG071RB,NRF51422_XXAA,' +
'NRF51422_XXAB,NRF51422_XXAC,NRF51822_XXAA,NRF51822_XXAB,' +
'NRF51822_XXAC',
// ARMV7
'',
// ARMV7A
'ALLWINNER_A20,RASPI2',
// ARMV7R
'',
// ARMV7M
'LPC1311FHN33,LPC1311FHN33_01,LPC1313FHN33,LPC1313FHN33_01,' +
'LPC1313FBD48,LPC1313FBD48_01,LPC1315FHN33,LPC1315FBD48,' +
'LPC1316FHN33,LPC1316FBD48,LPC1317FHN33,LPC1317FBD48,' +
'LPC1317FBD64,LPC1342FHN33,LPC1342FBD48,LPC1343FHN33,' +
'LPC1343FBD48,LPC1345FHN33,LPC1345FBD48,LPC1346FHN33,' +
'LPC1346FBD48,LPC1347FHN33,LPC1347FBD48,LPC1347FBD64,' +
'LPC1754,LPC1756,LPC1758,LPC1764,' +
'LPC1766,LPC1768,STM32F100X4,STM32F100X6,' +
'STM32F100X8,STM32F100XB,STM32F100XC,STM32F100XD,' +
'STM32F100XE,STM32F101X4,STM32F101X6,STM32F101X8,' +
'STM32F101XB,STM32F101XC,STM32F101XD,STM32F101XE,' +
'STM32F101XF,STM32F101XG,STM32F102X4,STM32F102X6,' +
'STM32F102X8,STM32F102XB,STM32F103X4,STM32F103X6,' +
'STM32F103X8,STM32F103XB,STM32F103XC,STM32F103XD,' +
'STM32F103XE,STM32F103XF,STM32F103XG,STM32F107X8,' +
'STM32F107XB,STM32F107XC,STM32F105R8,STM32F105RB,' +
'STM32F105RC,STM32F105V8,STM32F105VB,STM32F105VC,' +
'STM32F107RB,STM32F107RC,STM32F107VB,STM32F107VC,' +
'LM3S1110,LM3S1133,LM3S1138,LM3S1150,' +
'LM3S1162,LM3S1165,LM3S1166,LM3S2110,' +
'LM3S2139,LM3S6100,LM3S6110,LM3S1601,' +
'LM3S1608,LM3S1620,LM3S1635,LM3S1636,' +
'LM3S1637,LM3S1651,LM3S2601,LM3S2608,' +
'LM3S2620,LM3S2637,LM3S2651,LM3S6610,' +
'LM3S6611,LM3S6618,LM3S6633,LM3S6637,' +
'LM3S8630,LM3S1911,LM3S1918,LM3S1937,' +
'LM3S1958,LM3S1960,LM3S1968,LM3S1969,' +
'LM3S2911,LM3S2918,LM3S2919,LM3S2939,' +
'LM3S2948,LM3S2950,LM3S2965,LM3S6911,' +
'LM3S6918,LM3S6938,LM3S6950,LM3S6952,' +
'LM3S6965,LM3S8930,LM3S8933,LM3S8938,' +
'LM3S8962,LM3S8970,LM3S8971,LM3S5951,' +
'LM3S5956,LM3S1B21,LM3S2B93,LM3S5B91,' +
'LM3S9B81,LM3S9B90,LM3S9B92,LM3S9B95,' +
'LM3S9B96,LM3S5D51,ATSAM3X8E,ARDUINO_DUE,' +
'FLIP_N_CLICK,THUMB2_BARE',
// ARMV7EM
'STM32F401CB,STM32F401RB,STM32F401VB,STM32F401CC,' +
'STM32F401RC,STM32F401VC,DISCOVERYF401VC,STM32F401CD,' +
'STM32F401RD,STM32F401VD,STM32F401CE,STM32F401RE,' +
'NUCLEOF401RE,STM32F401VE,STM32F407VG,DISCOVERYF407VG,' +
'STM32F407IG,STM32F407ZG,STM32F407VE,STM32F407ZE,' +
'STM32F407IE,STM32F411CC,STM32F411RC,STM32F411VC,' +
'STM32F411CE,STM32F411RE,NUCLEOF411RE,STM32F411VE,' +
'DISCOVERYF411VE,STM32F429VG,STM32F429ZG,STM32F429IG,' +
'STM32F429VI,STM32F429ZI,DISCOVERYF429ZI,STM32F429II,' +
'STM32F429VE,STM32F429ZE,STM32F429IE,STM32F429BG,' +
'STM32F429BI,STM32F429BE,STM32F429NG,STM32F429NI,' +
'STM32F429NE,STM32F446MC,STM32F446RC,STM32F446VC,' +
'STM32F446ZC,STM32F446ME,STM32F446RE,NUCLEOF446RE,' +
'STM32F446VE,STM32F446ZE,STM32F745XE,STM32F745XG,' +
'STM32F746XE,STM32F746XG,STM32F756XE,STM32F756XG,' +
'LM4F120H5,XMC4500X1024,XMC4500X768,XMC4502X768,' +
'XMC4504X512,MK20DX128VFM5,MK20DX128VFT5,MK20DX128VLF5,' +
'MK20DX128VLH5,TEENSY30,MK20DX128VMP5,MK20DX32VFM5,' +
'MK20DX32VFT5,MK20DX32VLF5,MK20DX32VLH5,MK20DX32VMP5,' +
'MK20DX64VFM5,MK20DX64VFT5,MK20DX64VLF5,MK20DX64VLH5,' +
'MK20DX64VMP5,MK20DX128VLH7,MK20DX128VLK7,MK20DX128VLL7,' +
'MK20DX128VMC7,MK20DX256VLH7,MK20DX256VLK7,MK20DX256VLL7,' +
'MK20DX256VMC7,TEENSY31,TEENSY32,MK20DX64VLH7,' +
'MK20DX64VLK7,MK20DX64VMC7,MK22FN512CAP12,MK22FN512CBP12,' +
'MK22FN512VDC12,MK22FN512VLH12,MK22FN512VLL12,MK22FN512VMP12,' +
'FREEDOM_K22F,MK64FN1M0VDC12,MK64FN1M0VLL12,FREEDOM_K64F,' +
'MK64FN1M0VLQ12,MK64FN1M0VMD12,MK64FX512VDC12,MK64FX512VLL12,' +
'MK64FX512VLQ12,MK64FX512VMD12,NRF52832_XXAA,NRF52840_XXAA');
const
z80_SubArch_List =
'Z80,EZ80';
z80_List: array of string = (
// Z80
'',
// EZ80
'');
const
xtensa_SubArch_List =
'LX106,LX6';
xtensa_List: array of string = (
// LX106
'ESP8266',
// LX6
'ESP32,ESP32_D0WD,ESP32_D2WD,ESP32_S0WD');
const
riscv32_SubArch_List =
'RV32IMAC,RV32IMA,RV32IM,RV32I';
riscv32_List: array of string = (
// RV32IMAC
'FE310G000,FE310G002,HIFIVE1,HIFIVE1REVB,' +
'REDFIVE,REDFIVETHING,GD32VF103C4,GD32VF103C6,' +
'GD32VF103C8,GD32VF103CB,GD32VF103R4,GD32VF103R6,' +
'GD32VF103R8,GD32VF103RB,GD32VF103T4,GD32VF103T6,' +
'GD32VF103T8,GD32VF103TB,GD32VF103V8,GD32VF103VB',
// RV32IMA
'',
// RV32IM
'',
// RV32I
'');
const
jvm_SubArch_List =
'JVM,JVMDALVIK';
jvm_List: array of string = (
// JVM
'',
// JVMDALVIK
'');
const
sparc_SubArch_List =
'SPARCV7,SPARCV8,SPARCV9';
sparc_List: array of string = (
// SPARCV7
'',
// SPARCV8
'',
// SPARCV9
'');
const
m68k_SubArch_List =
'68000,68020,68040,68060,ISAA,ISAA+,ISAB,ISAC,CFV4E';
m68k_List: array of string = (
// 68000
'',
// 68020
'',
// 68040
'',
// 68060
'',
// ISAA
'',
// ISAA+
'',
// ISAB
'',
// ISAC
'',
// CFV4E
'');
const
mips_SubArch_List =
'MIPS1,MIPS2,MIPS3,MIPS4,MIPS5,MIPS32,MIPS32R2,PIC32MX';
mips_List: array of string = (
// MIPS1
'',
// MIPS2
'',
// MIPS3
'',
// MIPS4
'',
// MIPS5
'',
// MIPS32
'',
// MIPS32R2
'',
// PIC32MX
'PIC32MX110F016B,PIC32MX110F016C,PIC32MX110F016D,PIC32MX120F032B,' +
'PIC32MX120F032C,PIC32MX120F032D,PIC32MX130F064B,PIC32MX130F064C,' +
'PIC32MX130F064D,PIC32MX150F128B,PIC32MX150F128C,PIC32MX150F128D,' +
'PIC32MX210F016B,PIC32MX210F016C,PIC32MX210F016D,PIC32MX220F032B,' +
'PIC32MX220F032C,PIC32MX220F032D,PIC32MX230F064B,PIC32MX230F064C,' +
'PIC32MX230F064D,PIC32MX250F128B,PIC32MX250F128C,PIC32MX250F128D,' +
'PIC32MX775F256H,PIC32MX775F256L,PIC32MX775F512H,PIC32MX775F512L,' +
'PIC32MX795F512H,PIC32MX795F512L');
const
i386_SubArch_List =
'80386,80486,PENTIUM,PENTIUM2,PENTIUM3,PENTIUM4,PENTIUMM,COREI,COREAVX,COREAVX2';
i386_List: array of string = (
// 80386
'',
// 80486
'',
// PENTIUM
'',
// PENTIUM2
'',
// PENTIUM3
'',
// PENTIUM4
'',
// PENTIUMM
'',
// COREI
'',
// COREAVX
'',
// COREAVX2
'');
const
sparc64_SubArch_List =
'SPARCV9';
sparc64_List: array of string = (
// SPARCV9
'');
type
Ti8086_ControllerDataList = array of array of String;
const
i8086_ControllerDataList : Ti8086_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Taarch64_ControllerDataList = array of array of String;
const
aarch64_ControllerDataList : Taarch64_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Tpowerpc64_ControllerDataList = array of array of String;
const
powerpc64_ControllerDataList : Tpowerpc64_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Tavr_ControllerDataList = array of array of String;
const
avr_ControllerDataList : Tavr_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'),
('AVRSIM', 'AVRSIM', 'avr5', 'soft', '0', '$20000', '256', '32', '0', '4096'),
('AT90CAN32', 'AT90CAN32', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('AT90CAN64', 'AT90CAN64', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('AT90CAN128', 'AT90CAN128', 'avr51', 'soft', '0', '131072', '256', '4096', '0', '4096'),
('AT90PWM1', 'AT90PWM1', 'avr4', 'soft', '0', '8192', '256', '512', '0', '512'),
('AT90PWM2B', 'AT90PWM2B', 'avr4', 'soft', '0', '8192', '256', '512', '0', '512'),
('AT90PWM3B', 'AT90PWM3B', 'avr4', 'soft', '0', '8192', '256', '512', '0', '512'),
('AT90PWM81', 'AT90PWM81', 'avr4', 'soft', '0', '8192', '256', '256', '0', '512'),
('AT90PWM161', 'AT90PWM161', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('AT90PWM216', 'AT90PWM216', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('AT90PWM316', 'AT90PWM316', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('AT90USB82', 'AT90USB82', 'avr35', 'soft', '0', '8192', '256', '512', '0', '512'),
('AT90USB162', 'AT90USB162', 'avr35', 'soft', '0', '16384', '256', '512', '0', '512'),
('AT90USB646', 'AT90USB646', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('AT90USB647', 'AT90USB647', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('AT90USB1286', 'AT90USB1286', 'avr51', 'soft', '0', '131072', '256', '8192', '0', '4096'),
('AT90USB1287', 'AT90USB1287', 'avr51', 'soft', '0', '131072', '256', '8192', '0', '4096'),
('ATA6285', 'ATA6285', 'avr4', 'soft', '0', '8192', '256', '512', '0', '320'),
('ATA6286', 'ATA6286', 'avr4', 'soft', '0', '8192', '256', '512', '0', '320'),
('ATMEGA8', 'ATMEGA8', 'avr4', 'soft', '0', '8192', '96', '1024', '0', '512'),
('ATMEGA8A', 'ATMEGA8A', 'avr4', 'soft', '0', '8192', '96', '1024', '0', '512'),
('ATMEGA8HVA', 'ATMEGA8HVA', 'avr4', 'soft', '0', '8192', '256', '512', '0', '256'),
('ATMEGA8U2', 'ATMEGA8U2', 'avr35', 'soft', '0', '8192', '256', '512', '0', '512'),
('ATMEGA16', 'ATMEGA16', 'avr5', 'soft', '0', '16384', '96', '1024', '0', '512'),
('ATMEGA16A', 'ATMEGA16A', 'avr5', 'soft', '0', '16384', '96', '1024', '0', '512'),
('ATMEGA16HVA', 'ATMEGA16HVA', 'avr5', 'soft', '0', '16384', '256', '512', '0', '256'),
('ATMEGA16HVB', 'ATMEGA16HVB', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA16HVBREVB', 'ATMEGA16HVBREVB', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA16M1', 'ATMEGA16M1', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA16U2', 'ATMEGA16U2', 'avr35', 'soft', '0', '16384', '256', '512', '0', '512'),
('ATMEGA16U4', 'ATMEGA16U4', 'avr5', 'soft', '0', '16384', '256', '1280', '0', '512'),
('ATMEGA32', 'ATMEGA32', 'avr5', 'soft', '0', '32768', '96', '2048', '0', '1024'),
('ATMEGA32A', 'ATMEGA32A', 'avr5', 'soft', '0', '32768', '96', '2048', '0', '1024'),
('ATMEGA32C1', 'ATMEGA32C1', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA32HVB', 'ATMEGA32HVB', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA32HVBREVB', 'ATMEGA32HVBREVB', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA32M1', 'ATMEGA32M1', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA32U2', 'ATMEGA32U2', 'avr35', 'soft', '0', '32768', '256', '1024', '0', '1024'),
('ATMEGA32U4', 'ATMEGA32U4', 'avr5', 'soft', '0', '32768', '256', '2560', '0', '1024'),
('ATMEGA48', 'ATMEGA48', 'avr4', 'soft', '0', '4096', '256', '512', '0', '256'),
('ATMEGA48A', 'ATMEGA48A', 'avr4', 'soft', '0', '4096', '256', '512', '0', '256'),
('ATMEGA48P', 'ATMEGA48P', 'avr4', 'soft', '0', '4096', '256', '512', '0', '256'),
('ATMEGA48PA', 'ATMEGA48PA', 'avr4', 'soft', '0', '4096', '256', '512', '0', '256'),
('ATMEGA48PB', 'ATMEGA48PB', 'avr4', 'soft', '0', '4096', '256', '512', '0', '256'),
('ATMEGA64', 'ATMEGA64', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA64A', 'ATMEGA64A', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA64C1', 'ATMEGA64C1', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA64HVE2', 'ATMEGA64HVE2', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '1024'),
('ATMEGA64M1', 'ATMEGA64M1', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA64RFR2', 'ATMEGA64RFR2', 'avr5', 'soft', '0', '65536', '512', '8192', '0', '2048'),
('ATMEGA88', 'ATMEGA88', 'avr4', 'soft', '0', '8192', '256', '1024', '0', '512'),
('ATMEGA88A', 'ATMEGA88A', 'avr4', 'soft', '0', '8192', '256', '1024', '0', '512'),
('ATMEGA88P', 'ATMEGA88P', 'avr4', 'soft', '0', '8192', '256', '1024', '0', '512'),
('ATMEGA88PA', 'ATMEGA88PA', 'avr4', 'soft', '0', '8192', '256', '1024', '0', '512'),
('ATMEGA88PB', 'ATMEGA88PB', 'avr4', 'soft', '0', '8192', '256', '1024', '0', '512'),
('ATMEGA128', 'ATMEGA128', 'avr51', 'soft', '0', '131072', '256', '4096', '0', '4096'),
('ATMEGA128A', 'ATMEGA128A', 'avr51', 'soft', '0', '131072', '256', '4096', '0', '4096'),
('ATMEGA128RFA1', 'ATMEGA128RFA1', 'avr51', 'soft', '0', '131072', '512', '16384', '0', '4096'),
('ATMEGA128RFR2', 'ATMEGA128RFR2', 'avr51', 'soft', '0', '131072', '512', '16384', '0', '4096'),
('ATMEGA162', 'ATMEGA162', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA164A', 'ATMEGA164A', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA164P', 'ATMEGA164P', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA164PA', 'ATMEGA164PA', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA165A', 'ATMEGA165A', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA165P', 'ATMEGA165P', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA165PA', 'ATMEGA165PA', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA168', 'ATMEGA168', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA168A', 'ATMEGA168A', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA168P', 'ATMEGA168P', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA168PA', 'ATMEGA168PA', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA168PB', 'ATMEGA168PB', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA169A', 'ATMEGA169A', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA169P', 'ATMEGA169P', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA169PA', 'ATMEGA169PA', 'avr5', 'soft', '0', '16384', '256', '1024', '0', '512'),
('ATMEGA256RFR2', 'ATMEGA256RFR2', 'avr6', 'soft', '0', '262144', '512', '32768', '0', '8192'),
('ATMEGA324A', 'ATMEGA324A', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA324P', 'ATMEGA324P', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA324PA', 'ATMEGA324PA', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA324PB', 'ATMEGA324PB', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA325', 'ATMEGA325', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA325A', 'ATMEGA325A', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA325P', 'ATMEGA325P', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA325PA', 'ATMEGA325PA', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA328', 'ATMEGA328', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA328P', 'ATMEGA328P', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA328PB', 'ATMEGA328PB', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA329', 'ATMEGA329', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA329A', 'ATMEGA329A', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA329P', 'ATMEGA329P', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA329PA', 'ATMEGA329PA', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA406', 'ATMEGA406', 'avr5', 'soft', '0', '40960', '256', '2048', '0', '512'),
('ATMEGA640', 'ATMEGA640', 'avr5', 'soft', '0', '65536', '512', '8192', '0', '4096'),
('ATMEGA644', 'ATMEGA644', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA644A', 'ATMEGA644A', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA644P', 'ATMEGA644P', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA644PA', 'ATMEGA644PA', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA644RFR2', 'ATMEGA644RFR2', 'avr5', 'soft', '0', '65536', '512', '8192', '0', '2048'),
('ATMEGA645', 'ATMEGA645', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA645A', 'ATMEGA645A', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA645P', 'ATMEGA645P', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA649', 'ATMEGA649', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA649A', 'ATMEGA649A', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA649P', 'ATMEGA649P', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA808', 'ATMEGA808', 'avrxmega3', 'soft', '0', '8192', '15360', '1024', '5120', '256'),
('ATMEGA809', 'ATMEGA809', 'avrxmega3', 'soft', '0', '8192', '15360', '1024', '5120', '256'),
('ATMEGA1280', 'ATMEGA1280', 'avr51', 'soft', '0', '131072', '512', '8192', '0', '4096'),
('ATMEGA1281', 'ATMEGA1281', 'avr51', 'soft', '0', '131072', '512', '8192', '0', '4096'),
('ATMEGA1284', 'ATMEGA1284', 'avr51', 'soft', '0', '131072', '256', '16384', '0', '4096'),
('ATMEGA1284P', 'ATMEGA1284P', 'avr51', 'soft', '0', '131072', '256', '16384', '0', '4096'),
('ATMEGA1284RFR2', 'ATMEGA1284RFR2', 'avr51', 'soft', '0', '131072', '512', '16384', '0', '4096'),
('ATMEGA1608', 'ATMEGA1608', 'avrxmega3', 'soft', '0', '16384', '14336', '2048', '5120', '256'),
('ATMEGA1609', 'ATMEGA1609', 'avrxmega3', 'soft', '0', '16384', '14336', '2048', '5120', '256'),
('ATMEGA2560', 'ATMEGA2560', 'avr6', 'soft', '0', '262144', '512', '8192', '0', '4096'),
('ATMEGA2561', 'ATMEGA2561', 'avr6', 'soft', '0', '262144', '512', '8192', '0', '4096'),
('ATMEGA2564RFR2', 'ATMEGA2564RFR2', 'avr6', 'soft', '0', '262144', '512', '32768', '0', '8192'),
('ATMEGA3208', 'ATMEGA3208', 'avrxmega3', 'soft', '0', '32768', '12288', '4096', '5120', '256'),
('ATMEGA3209', 'ATMEGA3209', 'avrxmega3', 'soft', '0', '32768', '12288', '4096', '5120', '256'),
('ATMEGA3250', 'ATMEGA3250', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA3250A', 'ATMEGA3250A', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA3250P', 'ATMEGA3250P', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA3250PA', 'ATMEGA3250PA', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA3290', 'ATMEGA3290', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA3290A', 'ATMEGA3290A', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA3290P', 'ATMEGA3290P', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA3290PA', 'ATMEGA3290PA', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA4808', 'ATMEGA4808', 'avrxmega3', 'soft', '0', '49152', '10240', '6144', '5120', '256'),
('ATMEGA4809', 'ATMEGA4809', 'avrxmega3', 'soft', '0', '49152', '10240', '6144', '5120', '256'),
('ATMEGA6450', 'ATMEGA6450', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA6450A', 'ATMEGA6450A', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA6450P', 'ATMEGA6450P', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA6490', 'ATMEGA6490', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA6490A', 'ATMEGA6490A', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA6490P', 'ATMEGA6490P', 'avr5', 'soft', '0', '65536', '256', '4096', '0', '2048'),
('ATMEGA8515', 'ATMEGA8515', 'avr4', 'soft', '0', '8192', '96', '512', '0', '512'),
('ATMEGA8535', 'ATMEGA8535', 'avr4', 'soft', '0', '8192', '96', '512', '0', '512'),
('ATTINY4', 'ATTINY4', 'avrtiny', 'soft', '0', '512', '64', '32', '0', '0'),
('ATTINY5', 'ATTINY5', 'avrtiny', 'soft', '0', '512', '64', '32', '0', '0'),
('ATTINY9', 'ATTINY9', 'avrtiny', 'soft', '0', '1024', '64', '32', '0', '0'),
('ATTINY10', 'ATTINY10', 'avrtiny', 'soft', '0', '1024', '64', '32', '0', '0'),
('ATTINY11', 'ATTINY11', 'avr1', 'soft', '0', '1024', '0', '0', '0', '0'),
('ATTINY12', 'ATTINY12', 'avr1', 'soft', '0', '1024', '0', '0', '0', '64'),
('ATTINY13', 'ATTINY13', 'avr25', 'soft', '0', '1024', '96', '64', '0', '64'),
('ATTINY13A', 'ATTINY13A', 'avr25', 'soft', '0', '1024', '96', '64', '0', '64'),
('ATTINY15', 'ATTINY15', 'avr1', 'soft', '0', '1024', '0', '0', '0', '64'),
('ATTINY20', 'ATTINY20', 'avrtiny', 'soft', '0', '2048', '64', '128', '0', '0'),
('ATTINY24', 'ATTINY24', 'avr25', 'soft', '0', '2048', '96', '128', '0', '128'),
('ATTINY24A', 'ATTINY24A', 'avr25', 'soft', '0', '2048', '96', '128', '0', '128'),
('ATTINY25', 'ATTINY25', 'avr25', 'soft', '0', '2048', '96', '128', '0', '128'),
('ATTINY26', 'ATTINY26', 'avr2', 'soft', '0', '2048', '96', '128', '0', '128'),
('ATTINY28', 'ATTINY28', 'avr1', 'soft', '0', '2048', '0', '0', '0', '0'),
('ATTINY40', 'ATTINY40', 'avrtiny', 'soft', '0', '4096', '64', '256', '0', '0'),
('ATTINY43U', 'ATTINY43U', 'avr25', 'soft', '0', '4096', '96', '256', '0', '64'),
('ATTINY44', 'ATTINY44', 'avr25', 'soft', '0', '4096', '96', '256', '0', '256'),
('ATTINY44A', 'ATTINY44A', 'avr25', 'soft', '0', '4096', '96', '256', '0', '256'),
('ATTINY45', 'ATTINY45', 'avr25', 'soft', '0', '4096', '96', '256', '0', '256'),
('ATTINY48', 'ATTINY48', 'avr25', 'soft', '0', '4096', '256', '256', '0', '64'),
('ATTINY84', 'ATTINY84', 'avr25', 'soft', '0', '8192', '96', '512', '0', '512'),
('ATTINY84A', 'ATTINY84A', 'avr25', 'soft', '0', '8192', '96', '512', '0', '512'),
('ATTINY85', 'ATTINY85', 'avr25', 'soft', '0', '8192', '96', '512', '0', '512'),
('ATTINY87', 'ATTINY87', 'avr25', 'soft', '0', '8192', '256', '512', '0', '512'),
('ATTINY88', 'ATTINY88', 'avr25', 'soft', '0', '8192', '256', '512', '0', '64'),
('ATTINY102', 'ATTINY102', 'avrtiny', 'soft', '0', '1024', '64', '32', '0', '0'),
('ATTINY104', 'ATTINY104', 'avrtiny', 'soft', '0', '1024', '64', '32', '0', '0'),
('ATTINY167', 'ATTINY167', 'avr35', 'soft', '0', '16384', '256', '512', '0', '512'),
('ATTINY202', 'ATTINY202', 'avrxmega3', 'soft', '0', '2048', '16256', '128', '5120', '64'),
('ATTINY204', 'ATTINY204', 'avrxmega3', 'soft', '0', '2048', '16256', '128', '5120', '64'),
('ATTINY212', 'ATTINY212', 'avrxmega3', 'soft', '0', '2048', '16256', '128', '5120', '64'),
('ATTINY214', 'ATTINY214', 'avrxmega3', 'soft', '0', '2048', '16256', '128', '5120', '64'),
('ATTINY261', 'ATTINY261', 'avr25', 'soft', '0', '2048', '96', '128', '0', '128'),
('ATTINY261A', 'ATTINY261A', 'avr25', 'soft', '0', '2048', '96', '128', '0', '128'),
('ATTINY402', 'ATTINY402', 'avrxmega3', 'soft', '0', '4096', '16128', '256', '5120', '128'),
('ATTINY404', 'ATTINY404', 'avrxmega3', 'soft', '0', '4096', '16128', '256', '5120', '128'),
('ATTINY406', 'ATTINY406', 'avrxmega3', 'soft', '0', '4096', '16128', '256', '5120', '128'),
('ATTINY412', 'ATTINY412', 'avrxmega3', 'soft', '0', '4096', '16128', '256', '5120', '128'),
('ATTINY414', 'ATTINY414', 'avrxmega3', 'soft', '0', '4096', '16128', '256', '5120', '128'),
('ATTINY416', 'ATTINY416', 'avrxmega3', 'soft', '0', '4096', '16128', '256', '5120', '128'),
('ATTINY416AUTO', 'ATTINY416AUTO', 'avrxmega3', 'soft', '0', '4096', '16128', '256', '5120', '128'),
('ATTINY417', 'ATTINY417', 'avrxmega3', 'soft', '0', '4096', '16128', '256', '5120', '128'),
('ATTINY441', 'ATTINY441', 'avr25', 'soft', '0', '4096', '256', '256', '0', '256'),
('ATTINY461', 'ATTINY461', 'avr25', 'soft', '0', '4096', '96', '256', '0', '256'),
('ATTINY461A', 'ATTINY461A', 'avr25', 'soft', '0', '4096', '96', '256', '0', '256'),
('ATTINY804', 'ATTINY804', 'avrxmega3', 'soft', '0', '8192', '15872', '512', '5120', '128'),
('ATTINY806', 'ATTINY806', 'avrxmega3', 'soft', '0', '8192', '15872', '512', '5120', '128'),
('ATTINY807', 'ATTINY807', 'avrxmega3', 'soft', '0', '8192', '15872', '512', '5120', '128'),
('ATTINY814', 'ATTINY814', 'avrxmega3', 'soft', '0', '8192', '15872', '512', '5120', '128'),
('ATTINY816', 'ATTINY816', 'avrxmega3', 'soft', '0', '8192', '15872', '512', '5120', '128'),
('ATTINY817', 'ATTINY817', 'avrxmega3', 'soft', '0', '8192', '15872', '512', '5120', '128'),
('ATTINY828', 'ATTINY828', 'avr25', 'soft', '0', '8192', '256', '512', '0', '256'),
('ATTINY841', 'ATTINY841', 'avr25', 'soft', '0', '8192', '256', '512', '0', '512'),
('ATTINY861', 'ATTINY861', 'avr25', 'soft', '0', '8192', '96', '512', '0', '512'),
('ATTINY861A', 'ATTINY861A', 'avr25', 'soft', '0', '8192', '96', '512', '0', '512'),
('ATTINY1604', 'ATTINY1604', 'avrxmega3', 'soft', '0', '16384', '15360', '1024', '5120', '256'),
('ATTINY1606', 'ATTINY1606', 'avrxmega3', 'soft', '0', '16384', '15360', '1024', '5120', '256'),
('ATTINY1607', 'ATTINY1607', 'avrxmega3', 'soft', '0', '16384', '15360', '1024', '5120', '256'),
('ATTINY1614', 'ATTINY1614', 'avrxmega3', 'soft', '0', '16384', '14336', '2048', '5120', '256'),
('ATTINY1616', 'ATTINY1616', 'avrxmega3', 'soft', '0', '16384', '14336', '2048', '5120', '256'),
('ATTINY1617', 'ATTINY1617', 'avrxmega3', 'soft', '0', '16384', '14336', '2048', '5120', '256'),
('ATTINY1624', 'ATTINY1624', 'avrxmega3', 'soft', '0', '16384', '14336', '2048', '5120', '256'),
('ATTINY1626', 'ATTINY1626', 'avrxmega3', 'soft', '0', '16384', '14336', '2048', '5120', '256'),
('ATTINY1627', 'ATTINY1627', 'avrxmega3', 'soft', '0', '16384', '14336', '2048', '5120', '256'),
('ATTINY1634', 'ATTINY1634', 'avr35', 'soft', '0', '16384', '256', '1024', '0', '256'),
('ATTINY2313', 'ATTINY2313', 'avr25', 'soft', '0', '2048', '96', '128', '0', '128'),
('ATTINY2313A', 'ATTINY2313A', 'avr25', 'soft', '0', '2048', '96', '128', '0', '128'),
('ATTINY3214', 'ATTINY3214', 'avrxmega3', 'soft', '0', '32768', '14336', '2048', '5120', '256'),
('ATTINY3216', 'ATTINY3216', 'avrxmega3', 'soft', '0', '32768', '14336', '2048', '5120', '256'),
('ATTINY3217', 'ATTINY3217', 'avrxmega3', 'soft', '0', '32768', '14336', '2048', '5120', '256'),
('ATTINY4313', 'ATTINY4313', 'avr25', 'soft', '0', '4096', '96', '256', '0', '256'),
('ARDUINOLEONARDO', 'ATMEGA32U4', 'avr5', 'soft', '0', '32768', '256', '2560', '0', '1024'),
('ARDUINOMEGA', 'ATMEGA2560', 'avr6', 'soft', '0', '262144', '512', '8192', '0', '4096'),
('ARDUINOMICRO', 'ATMEGA32U4', 'avr5', 'soft', '0', '32768', '256', '2560', '0', '1024'),
('ARDUINONANO', 'ATMEGA328P', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ARDUINONANOEVERY', 'ATMEGA4809', 'avrxmega3', 'soft', '0', '49152', '10240', '6144', '5120', '256'),
('ARDUINOUNO', 'ATMEGA328P', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA256RFR2XPRO', 'ATMEGA256RFR2', 'avr6', 'soft', '0', '262144', '512', '32768', '0', '8192'),
('ATMEGA324PBXPRO', 'ATMEGA324PB', 'avr5', 'soft', '0', '32768', '256', '2048', '0', '1024'),
('ATMEGA1284PXPLAINED', 'ATMEGA1284P', 'avr51', 'soft', '0', '131072', '256', '16384', '0', '4096'),
('ATMEGA4809XPRO', 'ATMEGA4809', 'avrxmega3', 'soft', '0', '49152', '10240', '6144', '5120', '256'),
('ATTINY817XPRO', 'ATTINY817', 'avrxmega3', 'soft', '0', '8192', '15872', '512', '5120', '128'),
('ATTINY3217XPRO', 'ATTINY3217', 'avrxmega3', 'soft', '0', '32768', '14336', '2048', '5120', '256'));
type
Tx86_64_ControllerDataList = array of array of String;
const
x86_64_ControllerDataList : Tx86_64_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Triscv64_ControllerDataList = array of array of String;
const
riscv64_ControllerDataList : Triscv64_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Tpowerpc_ControllerDataList = array of array of String;
const
powerpc_ControllerDataList : Tpowerpc_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Tarm_ControllerDataList = array of array of String;
const
arm_ControllerDataList : Tarm_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'),
('LPC810M021FN8', 'LPC8xx', 'armv6m', 'soft', '$00000000', '$00001000', '$10000000', '$00000400'),
('LPC811M001FDH16', 'LPC8xx', 'armv6m', 'soft', '$00000000', '$00002000', '$10000000', '$00000800'),
('LPC812M101FDH16', 'LPC8xx', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC812M101FD20', 'LPC8xx', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC812M101FDH20', 'LPC8xx', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1110FD20', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00001000', '$10000000', '$00000400'),
('LPC1111FDH20_002', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00002000', '$10000000', '$00000800'),
('LPC1111FHN33_101', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00002000', '$10000000', '$00000800'),
('LPC1111FHN33_102', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00002000', '$10000000', '$00000800'),
('LPC1111FHN33_103', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00002000', '$10000000', '$00000800'),
('LPC1111FHN33_201', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00002000', '$10000000', '$00001000'),
('LPC1111FHN33_202', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00002000', '$10000000', '$00001000'),
('LPC1111FHN33_203', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00002000', '$10000000', '$00001000'),
('LPC1112FD20_102', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1112FDH20_102', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1112FDH28_102', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1112FHN33_101', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00000800'),
('LPC1112FHN33_102', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00000800'),
('LPC1112FHN33_103', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00000800'),
('LPC1112FHN33_201', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1112FHN24_202', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1112FHN33_202', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1112FHN33_203', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1112FHI33_202', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1112FHI33_203', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1113FHN33_201', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00006000', '$10000000', '$00001000'),
('LPC1113FHN33_202', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00006000', '$10000000', '$00001000'),
('LPC1113FHN33_203', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00006000', '$10000000', '$00001000'),
('LPC1113FHN33_301', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00006000', '$10000000', '$00002000'),
('LPC1113FHN33_302', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00006000', '$10000000', '$00002000'),
('LPC1113FHN33_303', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00006000', '$10000000', '$00002000'),
('LPC1113FBD48_301', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00006000', '$10000000', '$00002000'),
('LPC1113FBD48_302', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00006000', '$10000000', '$00002000'),
('LPC1113FBD48_303', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00006000', '$10000000', '$00002000'),
('LPC1114FDH28_102', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00001000'),
('LPC1114FN28_102', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00001000'),
('LPC1114FHN33_201', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00001000'),
('LPC1114FHN33_202', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00001000'),
('LPC1114FHN33_203', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00001000'),
('LPC1114FHN33_301', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1114FHN33_302', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1114FHN33_303', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1114FHN33_333', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$0000E000', '$10000000', '$00002000'),
('LPC1114FHI33_302', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1114FHI33_303', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1114FBD48_301', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1114FBD48_302', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1114FBD48_303', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1114FBD48_323', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$0000C000', '$10000000', '$00002000'),
('LPC1114FBD48_333', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$0000E000', '$10000000', '$00002000'),
('LPC1115FBD48_303', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00010000', '$10000000', '$00002000'),
('LPC11C12FBD48_301', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00002000'),
('LPC11C14FBD48_301', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC11C22FBD48_301', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00004000', '$10000000', '$00002000'),
('LPC11C24FBD48_301', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC11D14FBD100_302', 'LPC11XX', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1224FBD48_101', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00001000'),
('LPC1224FBD48_121', 'LPC122X', 'armv6m', 'soft', '$00000000', '$0000C000', '$10000000', '$00001000'),
('LPC1224FBD64_101', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00008000', '$10000000', '$00001000'),
('LPC1224FBD64_121', 'LPC122X', 'armv6m', 'soft', '$00000000', '$0000C000', '$10000000', '$00001000'),
('LPC1225FBD48_301', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00010000', '$10000000', '$00002000'),
('LPC1225FBD48_321', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00014000', '$10000000', '$00002000'),
('LPC1225FBD64_301', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00010000', '$10000000', '$00002000'),
('LPC1225FBD64_321', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00014000', '$10000000', '$00002000'),
('LPC1226FBD48_301', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00018000', '$10000000', '$00002000'),
('LPC1226FBD64_301', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00018000', '$10000000', '$00002000'),
('LPC1227FBD48_301', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00020000', '$10000000', '$00002000'),
('LPC1227FBD64_301', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00020000', '$10000000', '$00002000'),
('LPC12D27FBD100_301', 'LPC122X', 'armv6m', 'soft', '$00000000', '$00020000', '$10000000', '$00002000'),
('LPC1311FHN33', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00002000', '$10000000', '$00001000'),
('LPC1311FHN33_01', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00002000', '$10000000', '$00001000'),
('LPC1313FHN33', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1313FHN33_01', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1313FBD48', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1313FBD48_01', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1315FHN33', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1315FBD48', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1316FHN33', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$0000C000', '$10000000', '$00002000'),
('LPC1316FBD48', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$0000C000', '$10000000', '$00002000'),
('LPC1317FHN33', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00010000', '$10000000', '$00002000'),
('LPC1317FBD48', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00010000', '$10000000', '$00002000'),
('LPC1317FBD64', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00010000', '$10000000', '$00002000'),
('LPC1342FHN33', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1342FBD48', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00004000', '$10000000', '$00001000'),
('LPC1343FHN33', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1343FBD48', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1345FHN33', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1345FBD48', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00008000', '$10000000', '$00002000'),
('LPC1346FHN33', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$0000C000', '$10000000', '$00002000'),
('LPC1346FBD48', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$0000C000', '$10000000', '$00002000'),
('LPC1347FHN33', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00010000', '$10000000', '$00002000'),
('LPC1347FBD48', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00010000', '$10000000', '$00002000'),
('LPC1347FBD64', 'LPC13XX', 'armv7m', 'soft', '$00000000', '$00010000', '$10000000', '$00002000'),
('LPC2114', 'LPC21x4', 'armv4t', 'soft', '$00000000', '$00040000', '$40000000', '$00004000'),
('LPC2124', 'LPC21x4', 'armv4t', 'soft', '$00000000', '$00040000', '$40000000', '$00004000'),
('LPC2194', 'LPC21x4', 'armv4t', 'soft', '$00000000', '$00040000', '$40000000', '$00004000'),
('LPC1754', 'LPC1754', 'armv7m', 'soft', '$00000000', '$00020000', '$10000000', '$00004000'),
('LPC1756', 'LPC1756', 'armv7m', 'soft', '$00000000', '$00040000', '$10000000', '$00004000'),
('LPC1758', 'LPC1758', 'armv7m', 'soft', '$00000000', '$00080000', '$10000000', '$00008000'),
('LPC1764', 'LPC1764', 'armv7m', 'soft', '$00000000', '$00020000', '$10000000', '$00004000'),
('LPC1766', 'LPC1766', 'armv7m', 'soft', '$00000000', '$00040000', '$10000000', '$00008000'),
('LPC1768', 'LPC1768', 'armv7m', 'soft', '$00000000', '$00080000', '$10000000', '$00008000'),
('AT91SAM7S256', 'AT91SAM7x256', 'armv4t', 'soft', '$00000000', '$00040000', '$00200000', '$00010000'),
('AT91SAM7SE256', 'AT91SAM7x256', 'armv4t', 'soft', '$00000000', '$00040000', '$00200000', '$00010000'),
('AT91SAM7X256', 'AT91SAM7x256', 'armv4t', 'soft', '$00000000', '$00040000', '$00200000', '$00010000'),
('AT91SAM7XC256', 'AT91SAM7x256', 'armv4t', 'soft', '$00000000', '$00040000', '$00200000', '$00010000'),
('STM32F030C6', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00008000', '$20000000', '$00001000'),
('STM32F030C8', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00010000', '$20000000', '$00002000'),
('STM32F030F4', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F030K6', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00008000', '$20000000', '$00001000'),
('STM32F030R8', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00010000', '$20000000', '$00002000'),
('STM32F050C4', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F050C6', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00008000', '$20000000', '$00001000'),
('STM32F050F4', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F050F6', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00008000', '$20000000', '$00001000'),
('STM32F050G4', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F050G6', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00008000', '$20000000', '$00001000'),
('STM32F050K4', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F050K6', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00008000', '$20000000', '$00001000'),
('STM32F051C4', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F051C6', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00008000', '$20000000', '$00001000'),
('STM32F051C8', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00010000', '$20000000', '$00002000'),
('STM32F051K4', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F051K6', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00008000', '$20000000', '$00001000'),
('STM32F051K8', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00010000', '$20000000', '$00002000'),
('STM32F051R4', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F051R6', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00008000', '$20000000', '$00001000'),
('STM32F051R8', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00010000', '$20000000', '$00002000'),
('STM32F091CC', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00040000', '$20000000', '$00008000'),
('STM32F091CB', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00020000', '$20000000', '$00008000'),
('STM32F091RC', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00040000', '$20000000', '$00008000'),
('STM32F091RB', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00020000', '$20000000', '$00008000'),
('STM32F091VC', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00040000', '$20000000', '$00008000'),
('STM32F091VB', 'STM32F0XX', 'armv6m', 'soft', '$08000000', '$00020000', '$20000000', '$00008000'),
('STM32F100X4', 'STM32F10X_LD', 'armv7m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F100X6', 'STM32F10X_LD', 'armv7m', 'soft', '$08000000', '$00008000', '$20000000', '$00001000'),
('STM32F100X8', 'STM32F10X_MD', 'armv7m', 'soft', '$08000000', '$00010000', '$20000000', '$00002000'),
('STM32F100XB', 'STM32F10X_MD', 'armv7m', 'soft', '$08000000', '$00020000', '$20000000', '$00002000'),
('STM32F100XC', 'STM32F10X_HD', 'armv7m', 'soft', '$08000000', '$00040000', '$20000000', '$00006000'),
('STM32F100XD', 'STM32F10X_HD', 'armv7m', 'soft', '$08000000', '$00060000', '$20000000', '$00008000'),
('STM32F100XE', 'STM32F10X_HD', 'armv7m', 'soft', '$08000000', '$00080000', '$20000000', '$00008000'),
('STM32F101X4', 'STM32F10X_LD', 'armv7m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F101X6', 'STM32F10X_LD', 'armv7m', 'soft', '$08000000', '$00008000', '$20000000', '$00001800'),
('STM32F101X8', 'STM32F10X_MD', 'armv7m', 'soft', '$08000000', '$00010000', '$20000000', '$00002800'),
('STM32F101XB', 'STM32F10X_MD', 'armv7m', 'soft', '$08000000', '$00020000', '$20000000', '$00004000'),
('STM32F101XC', 'STM32F10X_HD', 'armv7m', 'soft', '$08000000', '$00040000', '$20000000', '$00008000'),
('STM32F101XD', 'STM32F10X_HD', 'armv7m', 'soft', '$08000000', '$00060000', '$20000000', '$0000C000'),
('STM32F101XE', 'STM32F10X_HD', 'armv7m', 'soft', '$08000000', '$00080000', '$20000000', '$0000C000'),
('STM32F101XF', 'STM32F10X_XL', 'armv7m', 'soft', '$08000000', '$000C0000', '$20000000', '$00014000'),
('STM32F101XG', 'STM32F10X_XL', 'armv7m', 'soft', '$08000000', '$00100000', '$20000000', '$00014000'),
('STM32F102X4', 'STM32F10X_LD', 'armv7m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F102X6', 'STM32F10X_LD', 'armv7m', 'soft', '$08000000', '$00008000', '$20000000', '$00001800'),
('STM32F102X8', 'STM32F10X_MD', 'armv7m', 'soft', '$08000000', '$00010000', '$20000000', '$00002800'),
('STM32F102XB', 'STM32F10X_MD', 'armv7m', 'soft', '$08000000', '$00020000', '$20000000', '$00004000'),
('STM32F103X4', 'STM32F10X_LD', 'armv7m', 'soft', '$08000000', '$00004000', '$20000000', '$00001000'),
('STM32F103X6', 'STM32F10X_LD', 'armv7m', 'soft', '$08000000', '$00008000', '$20000000', '$00002800'),
('STM32F103X8', 'STM32F10X_MD', 'armv7m', 'soft', '$08000000', '$00010000', '$20000000', '$00005000'),
('STM32F103XB', 'STM32F10X_MD', 'armv7m', 'soft', '$08000000', '$00020000', '$20000000', '$00005000'),
('STM32F103XC', 'STM32F10X_HD', 'armv7m', 'soft', '$08000000', '$00040000', '$20000000', '$0000C000'),
('STM32F103XD', 'STM32F10X_HD', 'armv7m', 'soft', '$08000000', '$00060000', '$20000000', '$00010000'),
('STM32F103XE', 'STM32F10X_HD', 'armv7m', 'soft', '$08000000', '$00080000', '$20000000', '$00010000'),
('STM32F103XF', 'STM32F10X_XL', 'armv7m', 'soft', '$08000000', '$000C0000', '$20000000', '$00018000'),
('STM32F103XG', 'STM32F10X_XL', 'armv7m', 'soft', '$08000000', '$00100000', '$20000000', '$00018000'),
('STM32F107X8', 'STM32F10X_CONN', 'armv7m', 'soft', '$08000000', '$00010000', '$20000000', '$00010000'),
('STM32F107XB', 'STM32F10X_CONN', 'armv7m', 'soft', '$08000000', '$00020000', '$20000000', '$00010000'),
('STM32F107XC', 'STM32F10X_CONN', 'armv7m', 'soft', '$08000000', '$00040000', '$20000000', '$00010000'),
('STM32F105R8', 'STM32F10X_CL', 'armv7m', 'soft', '$08000000', '$00010000', '$20000000', '$00010000'),
('STM32F105RB', 'STM32F10X_CL', 'armv7m', 'soft', '$08000000', '$00020000', '$20000000', '$00010000'),
('STM32F105RC', 'STM32F10X_CL', 'armv7m', 'soft', '$08000000', '$00040000', '$20000000', '$00010000'),
('STM32F105V8', 'STM32F10X_CL', 'armv7m', 'soft', '$08000000', '$00010000', '$20000000', '$00010000'),
('STM32F105VB', 'STM32F10X_CL', 'armv7m', 'soft', '$08000000', '$00020000', '$20000000', '$00010000'),
('STM32F105VC', 'STM32F10X_CL', 'armv7m', 'soft', '$08000000', '$00040000', '$20000000', '$00010000'),
('STM32F107RB', 'STM32F10X_CL', 'armv7m', 'soft', '$08000000', '$00020000', '$20000000', '$00010000'),
('STM32F107RC', 'STM32F10X_CL', 'armv7m', 'soft', '$08000000', '$00040000', '$20000000', '$00010000'),
('STM32F107VB', 'STM32F10X_CL', 'armv7m', 'soft', '$08000000', '$00020000', '$20000000', '$00010000'),
('STM32F107VC', 'STM32F10X_CL', 'armv7m', 'soft', '$08000000', '$00040000', '$20000000', '$00010000'),
('STM32F401CB', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00020000', '$20000000', '$00010000'),
('STM32F401RB', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00020000', '$20000000', '$00010000'),
('STM32F401VB', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00020000', '$20000000', '$00010000'),
('STM32F401CC', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00010000'),
('STM32F401RC', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00010000'),
('STM32F401VC', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00010000'),
('DISCOVERYF401VC', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00010000'),
('STM32F401CD', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00060000', '$20000000', '$00018000'),
('STM32F401RD', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00060000', '$20000000', '$00018000'),
('STM32F401VD', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00060000', '$20000000', '$00018000'),
('STM32F401CE', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00018000'),
('STM32F401RE', 'STM32F401XE', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00018000'),
('NUCLEOF401RE', 'STM32F401XE', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00018000'),
('STM32F401VE', 'STM32F401XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00018000'),
('STM32F407VG', 'STM32F407XX', 'armv7em', 'soft', '$08000000', '$00100000', '$20000000', '$00020000'),
('DISCOVERYF407VG', 'STM32F407XX', 'armv7em', 'soft', '$08000000', '$00100000', '$20000000', '$00020000'),
('STM32F407IG', 'STM32F407XX', 'armv7em', 'soft', '$08000000', '$00100000', '$20000000', '$00020000'),
('STM32F407ZG', 'STM32F407XX', 'armv7em', 'soft', '$08000000', '$00100000', '$20000000', '$00020000'),
('STM32F407VE', 'STM32F407XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('STM32F407ZE', 'STM32F407XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('STM32F407IE', 'STM32F407XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('STM32F411CC', 'STM32F411XE', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00020000'),
('STM32F411RC', 'STM32F411XE', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00020000'),
('STM32F411VC', 'STM32F411XE', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00020000'),
('STM32F411CE', 'STM32F411XE', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('STM32F411RE', 'STM32F411XE', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('NUCLEOF411RE', 'STM32F411XE', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('STM32F411VE', 'STM32F411XE', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('DISCOVERYF411VE', 'STM32F411XE', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('STM32F429VG', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00100000', '$20000000', '$00030000'),
('STM32F429ZG', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00100000', '$20000000', '$00030000'),
('STM32F429IG', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00100000', '$20000000', '$00030000'),
('STM32F429VI', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00200000', '$20000000', '$00030000'),
('STM32F429ZI', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00200000', '$20000000', '$00030000'),
('DISCOVERYF429ZI', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00200000', '$20000000', '$00030000'),
('STM32F429II', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00200000', '$20000000', '$00030000'),
('STM32F429VE', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00030000'),
('STM32F429ZE', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00030000'),
('STM32F429IE', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00030000'),
('STM32F429BG', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00100000', '$20000000', '$00030000'),
('STM32F429BI', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00200000', '$20000000', '$00030000'),
('STM32F429BE', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00030000'),
('STM32F429NG', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00100000', '$20000000', '$00030000'),
('STM32F429NI', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00200000', '$20000000', '$00030000'),
('STM32F429NE', 'STM32F429XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00030000'),
('STM32F446MC', 'STM32F446XX', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00020000'),
('STM32F446RC', 'STM32F446XX', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00020000'),
('STM32F446VC', 'STM32F446XX', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00020000'),
('STM32F446ZC', 'STM32F446XX', 'armv7em', 'soft', '$08000000', '$00040000', '$20000000', '$00020000'),
('STM32F446ME', 'STM32F446XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('STM32F446RE', 'STM32F446XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('NUCLEOF446RE', 'STM32F446XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('STM32F446VE', 'STM32F446XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('STM32F446ZE', 'STM32F446XX', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00020000'),
('STM32F745XE', 'STM32F745', 'armv7em', 'soft', '$08000000', '$00080000', '$20010000', '$00040000'),
('STM32F745XG', 'STM32F745', 'armv7em', 'soft', '$08000000', '$00100000', '$20010000', '$00040000'),
('STM32F746XE', 'STM32F746', 'armv7em', 'soft', '$08000000', '$00080000', '$20010000', '$00040000'),
('STM32F746XG', 'STM32F746', 'armv7em', 'soft', '$08000000', '$00100000', '$20010000', '$00040000'),
('STM32F756XE', 'STM32F756', 'armv7em', 'soft', '$08000000', '$00080000', '$20010000', '$00040000'),
('STM32F756XG', 'STM32F756', 'armv7em', 'soft', '$08000000', '$00100000', '$20010000', '$00040000'),
('STM32G071RB', 'STM32G071XX', 'armv6m', 'soft', '$08000000', '$00020000', '$20000000', '$00009000'),
('NUCLEOG071RB', 'STM32G071XX', 'armv6m', 'soft', '$08000000', '$00020000', '$20000000', '$00009000'),
('LM3S1110', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S1133', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S1138', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S1150', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S1162', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S1165', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S1166', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S2110', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S2139', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S6100', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S6110', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00010000', '$20000000', '$00004000'),
('LM3S1601', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S1608', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S1620', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S1635', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S1636', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S1637', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S1651', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S2601', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S2608', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S2620', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S2637', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S2651', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S6610', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S6611', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S6618', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S6633', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S6637', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S8630', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00020000', '$20000000', '$00008000'),
('LM3S1911', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S1918', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S1937', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S1958', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S1960', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S1968', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S1969', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S2911', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S2918', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S2919', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S2939', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S2948', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S2950', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S2965', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S6911', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S6918', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S6938', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S6950', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S6952', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S6965', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S8930', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S8933', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S8938', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S8962', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S8970', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S8971', 'LM3FURY', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S5951', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S5956', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00010000'),
('LM3S1B21', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00018000'),
('LM3S2B93', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00018000'),
('LM3S5B91', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00018000'),
('LM3S9B81', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00018000'),
('LM3S9B90', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00018000'),
('LM3S9B92', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00018000'),
('LM3S9B95', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00018000'),
('LM3S9B96', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00040000', '$20000000', '$00018000'),
('LM3S5D51', 'LM3TEMPEST', 'armv7m', 'soft', '$00000000', '$00080000', '$20000000', '$00018000'),
('LM4F120H5', 'LM4F120', 'armv7em', 'soft', '$00000000', '$00040000', '$20000000', '$00008000'),
('SC32442B', 'SC32442b', 'armv4t', 'soft', '$00000000', '$00000000', '$00000000', '$08000000'),
('XMC4500X1024', 'XMC4500', 'armv7em', 'soft', '$08000000', '$00100000', '$20000000', '$00010000'),
('XMC4500X768', 'XMC4500', 'armv7em', 'soft', '$08000000', '$000C0000', '$20000000', '$00010000'),
('XMC4502X768', 'XMC4502', 'armv7em', 'soft', '$08000000', '$000C0000', '$20000000', '$00010000'),
('XMC4504X512', 'XMC4504', 'armv7em', 'soft', '$08000000', '$00080000', '$20000000', '$00010000'),
('ALLWINNER_A20', 'ALLWINNER_A20', 'armv7a', 'vfpv4', '$00000000', '$00000000', '$40000000', '$80000000'),
('MK20DX128VFM5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00020000', '$20000000', '$00002000'),
('MK20DX128VFT5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00020000', '$20000000', '$00002000'),
('MK20DX128VLF5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00020000', '$20000000', '$00002000'),
('MK20DX128VLH5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00020000', '$20000000', '$00002000'),
('TEENSY30', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00020000', '$20000000', '$00002000'),
('MK20DX128VMP5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00020000', '$20000000', '$00002000'),
('MK20DX32VFM5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00008000', '$20000000', '$00001000'),
('MK20DX32VFT5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00008000', '$20000000', '$00001000'),
('MK20DX32VLF5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00008000', '$20000000', '$00001000'),
('MK20DX32VLH5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00008000', '$20000000', '$00001000'),
('MK20DX32VMP5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00008000', '$20000000', '$00001000'),
('MK20DX64VFM5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00010000', '$20000000', '$00002000'),
('MK20DX64VFT5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00010000', '$20000000', '$00002000'),
('MK20DX64VLF5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00010000', '$20000000', '$00002000'),
('MK20DX64VLH5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00010000', '$20000000', '$00002000'),
('MK20DX64VMP5', 'MK20D5', 'armv7em', 'soft', '$00000000', '$00010000', '$20000000', '$00002000'),
('MK20DX128VLH7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00020000', '$20000000', '$00004000'),
('MK20DX128VLK7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00020000', '$20000000', '$00004000'),
('MK20DX128VLL7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00020000', '$20000000', '$00004000'),
('MK20DX128VMC7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00020000', '$20000000', '$00004000'),
('MK20DX256VLH7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00040000', '$20000000', '$00008000'),
('MK20DX256VLK7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00040000', '$20000000', '$00008000'),
('MK20DX256VLL7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00040000', '$20000000', '$00008000'),
('MK20DX256VMC7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00040000', '$20000000', '$00008000'),
('TEENSY31', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00040000', '$20000000', '$00008000'),
('TEENSY32', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00040000', '$20000000', '$00008000'),
('MK20DX64VLH7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00010000', '$20000000', '$00002000'),
('MK20DX64VLK7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00010000', '$20000000', '$00002000'),
('MK20DX64VMC7', 'MK20D7', 'armv7em', 'soft', '$00000000', '$00010000', '$20000000', '$00002000'),
('MK22FN512CAP12', 'MK22F51212', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00010000'),
('MK22FN512CBP12', 'MK22F51212', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00010000'),
('MK22FN512VDC12', 'MK22F51212', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00010000'),
('MK22FN512VLH12', 'MK22F51212', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00010000'),
('MK22FN512VLL12', 'MK22F51212', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00010000'),
('MK22FN512VMP12', 'MK22F51212', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00010000'),
('FREEDOM_K22F', 'MK22F51212', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00010000'),
('MK64FN1M0VDC12', 'MK64F12', 'armv7em', 'soft', '$00000000', '$00100000', '$20000000', '$00030000'),
('MK64FN1M0VLL12', 'MK64F12', 'armv7em', 'soft', '$00000000', '$00100000', '$20000000', '$00030000'),
('FREEDOM_K64F', 'MK64F12', 'armv7em', 'soft', '$00000000', '$00100000', '$20000000', '$00030000'),
('MK64FN1M0VLQ12', 'MK64F12', 'armv7em', 'soft', '$00000000', '$00100000', '$20000000', '$00030000'),
('MK64FN1M0VMD12', 'MK64F12', 'armv7em', 'soft', '$00000000', '$00100000', '$20000000', '$00030000'),
('MK64FX512VDC12', 'MK64F12', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00020000'),
('MK64FX512VLL12', 'MK64F12', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00020000'),
('MK64FX512VLQ12', 'MK64F12', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00020000'),
('MK64FX512VMD12', 'MK64F12', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00020000'),
('ATSAM3X8E', 'SAM3X8E', 'armv7m', 'soft', '$00080000', '$00040000', '$20000000', '$00010000'),
('ARDUINO_DUE', 'SAM3X8E', 'armv7m', 'soft', '$00080000', '$00040000', '$20000000', '$00010000'),
('FLIP_N_CLICK', 'SAM3X8E', 'armv7m', 'soft', '$00080000', '$00040000', '$20000000', '$00010000'),
('NRF51422_XXAA', 'NRF51', 'armv6m', 'soft', '$00000000', '$00040000', '$20000000', '$00004000'),
('NRF51422_XXAB', 'NRF51', 'armv6m', 'soft', '$00000000', '$00020000', '$20000000', '$00004000'),
('NRF51422_XXAC', 'NRF51', 'armv6m', 'soft', '$00000000', '$00040000', '$20000000', '$00008000'),
('NRF51822_XXAA', 'NRF51', 'armv6m', 'soft', '$00000000', '$00040000', '$20000000', '$00004000'),
('NRF51822_XXAB', 'NRF51', 'armv6m', 'soft', '$00000000', '$00020000', '$20000000', '$00004000'),
('NRF51822_XXAC', 'NRF51', 'armv6m', 'soft', '$00000000', '$00040000', '$20000000', '$00008000'),
('NRF52832_XXAA', 'NRF52', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00010000'),
('NRF52840_XXAA', 'NRF52', 'armv7em', 'soft', '$00000000', '$00080000', '$20000000', '$00010000'),
('RASPI2', 'RASPI2', 'armv7a', 'vfpv4', '$00000000', '$00000000', '$00008000', '$10000000'),
('THUMB2_BARE', 'THUMB2_BARE', 'armv7m', 'soft', '$00000000', '$00002000', '$20000000', '$00000400'));
type
Tz80_ControllerDataList = array of array of String;
const
z80_ControllerDataList : Tz80_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Txtensa_ControllerDataList = array of array of String;
const
xtensa_ControllerDataList : Txtensa_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'abi', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'),
('ESP8266', 'ESP8266', 'lx106', 'soft', 'abi_xtensa_call0', '$40000000', '1024', '$40070000', '520'),
('ESP32', 'ESP32', 'lx6', 'hard', 'abi_xtensa_windowed', '$40000000', '2'),
('ESP32_D0WD', 'ESP32_D0WD', 'lx6', 'hard', 'abi_xtensa_windowed', '$40000000', '448', '$40070000', '520'),
('ESP32_D2WD', 'ESP32_D2WD', 'lx6', 'hard', 'abi_xtensa_windowed', '$40000000', '448', '$40070000', '520'),
('ESP32_S0WD', 'ESP32_S0WD', 'lx6', 'hard', 'abi_xtensa_windowed', '$40000000', '448', '$40070000', '520'));
type
Triscv32_ControllerDataList = array of array of String;
const
riscv32_ControllerDataList : Triscv32_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'),
('FE310G000', 'FE310G000', 'rv32imac', 'none', '$20400000', '$01000000', '$80000000', '$00004000'),
('FE310G002', 'FE310G002', 'rv32imac', 'none', '$20010000', '$00400000', '$80000000', '$00004000'),
('HIFIVE1', 'FE310G000', 'rv32imac', 'none', '$20400000', '$01000000', '$80000000', '$00004000'),
('HIFIVE1REVB', 'FE310G002', 'rv32imac', 'none', '$20010000', '$00400000', '$80000000', '$00004000'),
('REDFIVE', 'FE310G002', 'rv32imac', 'none', '$20010000', '$00400000', '$80000000', '$00004000'),
('REDFIVETHING', 'FE310G002', 'rv32imac', 'none', '$20010000', '$02400000', '$80000000', '$00004000'),
('GD32VF103C4', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00004000', '$20000000', '$00001800'),
('GD32VF103C6', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00008000', '$20000000', '$00002800'),
('GD32VF103C8', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00010000', '$20000000', '$00005000'),
('GD32VF103CB', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00020000', '$20000000', '$00008000'),
('GD32VF103R4', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00004000', '$20000000', '$00001800'),
('GD32VF103R6', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00008000', '$20000000', '$00002800'),
('GD32VF103R8', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00010000', '$20000000', '$00005000'),
('GD32VF103RB', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00020000', '$20000000', '$00008000'),
('GD32VF103T4', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00004000', '$20000000', '$00001800'),
('GD32VF103T6', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00008000', '$20000000', '$00002800'),
('GD32VF103T8', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00010000', '$20000000', '$00005000'),
('GD32VF103TB', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00020000', '$20000000', '$00008000'),
('GD32VF103V8', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00010000', '$20000000', '$00005000'),
('GD32VF103VB', 'GD32VF103XX', 'rv32imac', 'none', '$08000000', '$00020000', '$20000000', '$00008000'));
type
Tjvm_ControllerDataList = array of array of String;
const
jvm_ControllerDataList : Tjvm_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Tsparc_ControllerDataList = array of array of String;
const
sparc_ControllerDataList : Tsparc_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Tm68k_ControllerDataList = array of array of String;
const
m68k_ControllerDataList : Tm68k_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Tmips_ControllerDataList = array of array of String;
const
mips_ControllerDataList : Tmips_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'),
('PIC32MX110F016B', 'PIC32MX1xxFxxxB', 'pic32mx', 'soft', '$9d000000', '$00004000', '$A0000000', '$00001000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX110F016C', 'PIC32MX1xxFxxxC', 'pic32mx', 'soft', '$9d000000', '$00004000', '$A0000000', '$00001000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX110F016D', 'PIC32MX1xxFxxxD', 'pic32mx', 'soft', '$9d000000', '$00004000', '$A0000000', '$00001000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX120F032B', 'PIC32MX1xxFxxxB', 'pic32mx', 'soft', '$9d000000', '$00008000', '$A0000000', '$00002000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX120F032C', 'PIC32MX1xxFxxxC', 'pic32mx', 'soft', '$9d000000', '$00008000', '$A0000000', '$00002000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX120F032D', 'PIC32MX1xxFxxxD', 'pic32mx', 'soft', '$9d000000', '$00008000', '$A0000000', '$00002000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX130F064B', 'PIC32MX1xxFxxxB', 'pic32mx', 'soft', '$9d000000', '$00010000', '$A0000000', '$00004000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX130F064C', 'PIC32MX1xxFxxxC', 'pic32mx', 'soft', '$9d000000', '$00010000', '$A0000000', '$00004000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX130F064D', 'PIC32MX1xxFxxxD', 'pic32mx', 'soft', '$9d000000', '$00010000', '$A0000000', '$00004000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX150F128B', 'PIC32MX1xxFxxxB', 'pic32mx', 'soft', '$9d000000', '$00020000', '$A0000000', '$00008000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX150F128C', 'PIC32MX1xxFxxxC', 'pic32mx', 'soft', '$9d000000', '$00020000', '$A0000000', '$00008000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX150F128D', 'PIC32MX1xxFxxxD', 'pic32mx', 'soft', '$9d000000', '$00020000', '$A0000000', '$00008000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX210F016B', 'PIC32MX2xxFxxxB', 'pic32mx', 'soft', '$9d000000', '$00004000', '$A0000000', '$00001000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX210F016C', 'PIC32MX2xxFxxxC', 'pic32mx', 'soft', '$9d000000', '$00004000', '$A0000000', '$00001000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX210F016D', 'PIC32MX2xxFxxxD', 'pic32mx', 'soft', '$9d000000', '$00004000', '$A0000000', '$00001000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX220F032B', 'PIC32MX2xxFxxxB', 'pic32mx', 'soft', '$9d000000', '$00008000', '$A0000000', '$00002000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX220F032C', 'PIC32MX2xxFxxxC', 'pic32mx', 'soft', '$9d000000', '$00008000', '$A0000000', '$00002000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX220F032D', 'PIC32MX2xxFxxxD', 'pic32mx', 'soft', '$9d000000', '$00008000', '$A0000000', '$00002000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX230F064B', 'PIC32MX2xxFxxxB', 'pic32mx', 'soft', '$9d000000', '$00010000', '$A0000000', '$00004000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX230F064C', 'PIC32MX2xxFxxxC', 'pic32mx', 'soft', '$9d000000', '$00010000', '$A0000000', '$00004000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX230F064D', 'PIC32MX2xxFxxxD', 'pic32mx', 'soft', '$9d000000', '$00010000', '$A0000000', '$00004000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX250F128B', 'PIC32MX2xxFxxxB', 'pic32mx', 'soft', '$9d000000', '$00020000', '$A0000000', '$00008000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX250F128C', 'PIC32MX2xxFxxxC', 'pic32mx', 'soft', '$9d000000', '$00020000', '$80000000', '$00008000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX250F128D', 'PIC32MX2xxFxxxD', 'pic32mx', 'soft', '$9d000000', '$00020000', '$A0000000', '$00008000', '0', '0', '$BFC00000', '$00000BEF'),
('PIC32MX775F256H', 'PIC32MX7x5FxxxH', 'pic32mx', 'soft', '$9d000000', '$00040000', '$A0000000', '$00010000', '0', '0', '$BFC00000', '$00002FEF'),
('PIC32MX775F256L', 'PIC32MX7x5FxxxL', 'pic32mx', 'soft', '$9d000000', '$00040000', '$A0000000', '$00010000', '0', '0', '$BFC00000', '$00002FEF'),
('PIC32MX775F512H', 'PIC32MX7x5FxxxH', 'pic32mx', 'soft', '$9d000000', '$00080000', '$A0000000', '$00010000', '0', '0', '$BFC00000', '$00002FEF'),
('PIC32MX775F512L', 'PIC32MX7x5FxxxL', 'pic32mx', 'soft', '$9d000000', '$00080000', '$A0000000', '$00010000', '0', '0', '$BFC00000', '$00002FEF'),
('PIC32MX795F512H', 'PIC32MX7x5FxxxH', 'pic32mx', 'soft', '$9d000000', '$00080000', '$A0000000', '$00020000', '0', '0', '$BFC00000', '$00002FEF'),
('PIC32MX795F512L', 'PIC32MX7x5FxxxL', 'pic32mx', 'soft', '$9d000000', '$00080000', '$A0000000', '$00020000', '0', '0', '$BFC00000', '$00002FEF'));
type
Ti386_ControllerDataList = array of array of String;
const
i386_ControllerDataList : Ti386_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
type
Tsparc64_ControllerDataList = array of array of String;
const
sparc64_ControllerDataList : Tsparc64_ControllerDataList = (
('controllertypestr', 'controllerunitstr', 'cputype', 'fputype', 'flashbase', 'flashsize', 'srambase', 'sramsize', 'eeprombase', 'eepromsize', 'bootbase', 'bootsize'));
implementation
begin
end.
|
unit uModbusProtocol;
interface
uses
Windows, System.SysUtils, uProtocol, uCommonDevice, uModbus, uTurnDef,
Web.Win.Sockets;
type
TCommonModbusDeviceEmul = class(TCommonModbusDevice)
private
FTCP: TTcpServer;
public
function ReadData(var data: AnsiString): TModbusError;
function WriteData(var data: AnsiString): TModbusError;
function ReadDataTCP(var data: AnsiString): TModbusError;
function WriteDataTCP(var data: AnsiString): TModbusError;
property TCP: TTcpServer read FTCP write FTCP;
procedure Accept(Sender: TObject; ClientSocket: TCustomIpClient);
function Deserialize(Data: AnsiString): AnsiString;
end;
TModbusProtocol = class(TProtocol)
private
FDev: TCommonModbusDeviceEmul;
FIsTCP: boolean;
protected
function Deserialize(Data: AnsiString): AnsiString; override;
procedure Execute; override;
public
constructor Create(Port: byte; Speed: integer); overload;
constructor Create(Host: ansistring; Port: word); overload;
destructor Destroy;
end;
implementation
{ TModbusProtocol }
constructor TModbusProtocol.Create(Port: byte; Speed: integer);
begin
inherited Create;
FIsTCP := false;
FDev := TCommonModbusDeviceEmul.Create;
FDev.Open(Port, speed);
if not FDev.Connect then
begin
FDev.Free;
FCommunicatorState := csNotConnected;
end
else
begin
FCommunicatorState := csConnected;
end;
resume;
end;
constructor TModbusProtocol.Create(Host: ansistring; Port: word);
begin
inherited Create;
FIsTCP := true;
FDev := TCommonModbusDeviceEmul.Create;
FDev.TCP := TTCPServer.Create(nil);
FDev.TCP.LocalHost := Host;
FDev.TCP.LocalPort := IntToStr(Port);
FDev.TCP.OnAccept := FDev.Accept;
FDev.TCP.BlockMode := bmThreadBlocking;
FDev.TCP.Open;
if not FDev.TCP.Active then
begin
FDev.TCP.Free;
FCommunicatorState := csNotConnected;
end
else
begin
FCommunicatorState := csConnected;
end;
resume;
end;
function TModbusProtocol.Deserialize(Data: AnsiString): AnsiString;
var
addr: byte; //адрес турникета
datain: word;
func: byte;
reg: word; //адрес регистра
s: ansistring;
begin
WriteLog('<= ' + data);
addr := ord(data[1]);
func := ord(data[2]);
s := AnsiChar(addr);
if (not Turnstiles.IsAddrExists(addr)) and (not Turnstiles.IsAddrExists(addr - 100)) then
begin
WriteLog('=> ' + 'Out of address');
exit;
end;
reg := ord(data[3]) shl 8 + ord(data[4]);
case func of
$2B: begin
s := s + #$2B + #$0E;
if ord(data[5]) = $00 then
s := s + #$00 + #$01 + #$FF + #$01 + #$03 + #$00 + #$07 + 'Lot LTD';
if ord(data[5]) = $01 then
s := s + #$01 + #$01 + #$FF + #$02 + #$03 + #$01 + #$07 + 'virtual';
if ord(data[5]) = $02 then
s := s + #$02 + #$01 + #$FF + #$03 + #$03 + #$02 + #$04 + 'ver1';
if ord(data[5]) = $03 then
s := s + #$03 + #$01 + #$00 + #$00 + #$03 + #$03 + #$03 + 'url';
end;
$03: begin
s := s + #$03;
//Состояние входа
if reg = $40 then
s := s + #$02 + AnsiChar(hi(Turnstiles.ByAddr(addr).EnterState)) + AnsiChar(lo(Turnstiles.ByAddr(addr).EnterState));
//Состояние выхода
if reg = $41 then
s := s + #$02 + AnsiChar(hi(Turnstiles.ByAddr(addr).ExitState)) + AnsiChar(lo(Turnstiles.ByAddr(addr).ExitState));
//Количество проходов в направлении вход младшие 16 бит
if reg = $44 then
s := s + #$02 + AnsiChar(LongRec(Turnstiles.ByAddr(addr).EnterCount).Bytes[1]) + AnsiChar(LongRec(Turnstiles.ByAddr(addr).EnterCount).Bytes[0]);
//Количество проходов в направлении вход старшие 16 бит
if reg = $45 then
s := s + #$02 + AnsiChar(LongRec(Turnstiles.ByAddr(addr).EnterCount).Bytes[3]) + AnsiChar(LongRec(Turnstiles.ByAddr(addr).EnterCount).Bytes[2]);
//Количество проходов в направлении выход младшие 16 бит
if reg = $46 then
s := s + #$02 + AnsiChar(LongRec(Turnstiles.ByAddr(addr).ExitCount).Bytes[1]) + AnsiChar(LongRec(Turnstiles.ByAddr(addr).ExitCount).Bytes[0]);
//Количество проходов в направлении выход старшие 16 бит
if reg = $47 then
s := s + #$02 + AnsiChar(LongRec(Turnstiles.ByAddr(addr).ExitCount).Bytes[3]) + AnsiChar(LongRec(Turnstiles.ByAddr(addr).ExitCount).Bytes[2]);
//Старший байт - флаг новизны данных сканера/считывателя в направлении выход
//0x0 – Новых данных нет
//0x1 – Новые данные
//Младший байт - количество данных в буфере принятых с выходного сканера
if reg = $100 then
// if Turnstiles.ByAddr(addr).EnterCardNum <> '' and then
if Turnstiles.ByAddr(addr).IsEnterNew then
s := s + #$02 + #$01 + AnsiChar(Length(Turnstiles.ByAddr(addr).EnterCardNum))
else
s := s + #$02 + #$00 + #$00;
if reg = $101 then
begin
s := s + AnsiChar(Length(Turnstiles.ByAddr(addr).EnterCardNum)) + Turnstiles.ByAddr(addr).EnterCardNum;
Turnstiles.ByAddr(addr).EnterCardNum := '';
end;
//Старший байт - флаг новизны данных сканера/считывателя в направлении выход
//0x0 – Новых данных нет
//0x1 – Новые данные
//Младший байт - количество данных в буфере принятых с выходного сканера
if reg = $200 then
// if Turnstiles.ByAddr(addr).ExitCardNum <> '' then
if Turnstiles.ByAddr(addr).IsExitNew then
s := s + #$02 + #$01 + AnsiChar(Length(Turnstiles.ByAddr(addr).ExitCardNum))
else
s := s + #$02 + #$00 + #$00;
if reg = $201 then
begin
s := s + AnsiChar(Length(Turnstiles.ByAddr(addr).ExitCardNum)) + Turnstiles.ByAddr(addr).ExitCardNum;
Turnstiles.ByAddr(addr).ExitCardNum := '';
end;
//0 - Установить нормальный режим
//1 - Установить режим Блокировки
//2 - Установить режим Антипаники
if reg = $3000 then
s := s + #$01 + #$00;
if (reg = $42) or (reg = $43) or (reg = $48) or (reg = $666) then
s := s + #$01 + #$00;
end;
$10: begin
s := s + #$10;
//Установка входа
if (reg = $40) and (addr < 100) then
begin
datain := ord(data[8]) shl 8 + ord(data[9]);
Turnstiles.ByAddr(addr).EnterState := datain;
s := s + #$00 + #$40 + #$00 + #$01;
end
else
Turnstiles.ByAddr(addr - 100).Indicator := copy(data, 8, 32);
//Установка выхода
if reg = $41 then
begin
datain := ord(data[8]) shl 8 + ord(data[9]);
Turnstiles.ByAddr(addr).ExitState := datain;
s := s + #$00 + #$41 + #$00 + #$01;
end;
end;
end;
if length(s) > 2 then
begin
WriteLog('=> ' + s);
if FIsTcp then
FDev.WriteDataTCP(s)
else
FDev.WriteData(s);
end;
end;
destructor TModbusProtocol.Destroy;
begin
if FCommunicatorState = csConnected then
begin
FDev.Close;
if Fdev.TCP.Active then
FDev.TCP.Close;
FDev.Free;
end;
end;
procedure TModbusProtocol.Execute;
var
data: ansistring;
begin
inherited;
while (not Terminated) and (FCommunicatorState = csConnected) do
begin
data := '';
if not FIsTCP then
FDev.ReadData(data)
else
FDev.ReadDataTCP(data);
if Length(data) > 0 then
Deserialize(data);
sleep(5);
end;
end;
{ TCommonModbusDeviceEmul }
procedure TCommonModbusDeviceEmul.Accept(Sender: TObject;
ClientSocket: TCustomIpClient);
var
data: AnsiString;
begin
// Sender := nil;
data := ClientSocket.Receiveln;
if Length(data) > 0 then
Deserialize(data);
// if crc16string(data) <> #0#0 then
// begin
// Result := merCRCError;
// exit;
// end;
end;
function TCommonModbusDeviceEmul.Deserialize(Data: AnsiString): AnsiString;
var
addr: byte; //адрес турникета
datain: word;
func: byte;
reg: word; //адрес регистра
s: ansistring;
begin
//WriteLog('<= ' + data);
addr := ord(data[1]);
func := ord(data[2]);
s := AnsiChar(addr);
reg := ord(data[3]) shl 8 + ord(data[4]);
case func of
$2B: begin
s := s + #$2B + #$0E;
if ord(data[5]) = $00 then
s := s + #$00 + #$01 + #$FF + #$01 + #$03 + #$00 + #$07 + 'Lot LTD';
if ord(data[5]) = $01 then
s := s + #$01 + #$01 + #$FF + #$02 + #$03 + #$01 + #$07 + 'virtual';
if ord(data[5]) = $02 then
s := s + #$02 + #$01 + #$FF + #$03 + #$03 + #$02 + #$04 + 'ver1';
if ord(data[5]) = $03 then
s := s + #$03 + #$01 + #$00 + #$00 + #$03 + #$03 + #$03 + 'url';
end;
$03: begin
s := s + #$03;
//Состояние входа
if reg = $40 then
s := s + #$02 + AnsiChar(hi(Turnstiles.ByAddr(addr).EnterState)) + AnsiChar(lo(Turnstiles.ByAddr(addr).EnterState));
//Состояние выхода
if reg = $41 then
s := s + #$02 + AnsiChar(hi(Turnstiles.ByAddr(addr).ExitState)) + AnsiChar(lo(Turnstiles.ByAddr(addr).ExitState));
//Количество проходов в направлении вход младшие 16 бит
if reg = $44 then
s := s + #$02 + AnsiChar(LongRec(Turnstiles.ByAddr(addr).EnterCount).Bytes[1]) + AnsiChar(LongRec(Turnstiles.ByAddr(addr).EnterCount).Bytes[0]);
//Количество проходов в направлении вход старшие 16 бит
if reg = $45 then
s := s + #$02 + AnsiChar(LongRec(Turnstiles.ByAddr(addr).EnterCount).Bytes[3]) + AnsiChar(LongRec(Turnstiles.ByAddr(addr).EnterCount).Bytes[2]);
//Количество проходов в направлении выход младшие 16 бит
if reg = $46 then
s := s + #$02 + AnsiChar(LongRec(Turnstiles.ByAddr(addr).ExitCount).Bytes[1]) + AnsiChar(LongRec(Turnstiles.ByAddr(addr).ExitCount).Bytes[0]);
//Количество проходов в направлении выход старшие 16 бит
if reg = $47 then
s := s + #$02 + AnsiChar(LongRec(Turnstiles.ByAddr(addr).ExitCount).Bytes[3]) + AnsiChar(LongRec(Turnstiles.ByAddr(addr).ExitCount).Bytes[2]);
//Старший байт - флаг новизны данных сканера/считывателя в направлении выход
//0x0 – Новых данных нет
//0x1 – Новые данные
//Младший байт - количество данных в буфере принятых с выходного сканера
if reg = $100 then
if Turnstiles.ByAddr(addr).EnterCardNum <> '' then
s := s + #$02 + #$01 + AnsiChar(Length(Turnstiles.ByAddr(addr).EnterCardNum))
else
s := s + #$02 + #$00 + #$00;
if reg = $101 then
begin
s := s + AnsiChar(Length(Turnstiles.ByAddr(addr).EnterCardNum)) + Turnstiles.ByAddr(addr).EnterCardNum;
Turnstiles.ByAddr(addr).EnterCardNum := '';
end;
//Старший байт - флаг новизны данных сканера/считывателя в направлении выход
//0x0 – Новых данных нет
//0x1 – Новые данные
//Младший байт - количество данных в буфере принятых с выходного сканера
if reg = $200 then
if Turnstiles.ByAddr(addr).ExitCardNum <> '' then
s := s + #$02 + #$01 + AnsiChar(Length(Turnstiles.ByAddr(addr).ExitCardNum))
else
s := s + #$02 + #$00 + #$00;
if reg = $201 then
begin
s := s + AnsiChar(Length(Turnstiles.ByAddr(addr).ExitCardNum)) + Turnstiles.ByAddr(addr).ExitCardNum;
Turnstiles.ByAddr(addr).ExitCardNum := '';
end;
if (reg = $42) or (reg = $43) or (reg = $48) or (reg = $666) then
s := s + #$01 + #$00;
end;
$10: begin
s := s + #$10;
//Установка входа
if reg = $40 then
begin
datain := ord(data[8]) shl 8 + ord(data[9]);
Turnstiles.ByAddr(addr).EnterState := datain;
s := s + #$00 + #$40 + #$00 + #$01;
end;
//Установка выхода
if reg = $41 then
begin
datain := ord(data[8]) shl 8 + ord(data[9]);
Turnstiles.ByAddr(addr).ExitState := datain;
s := s + #$00 + #$41 + #$00 + #$01;
end;
end;
end;
if length(s) > 2 then
begin
// WriteLog('=> ' + s);
//if FIsTcp then
WriteDataTCP(s)
// else
// WriteData(s);
end;
end;
function TCommonModbusDeviceEmul.ReadData(var data: AnsiString): TModbusError;
var
s: AnsiString;
cnt: integer;
i: integer;
tmp: cardinal;
TxSleep: integer;
begin
TxSleep := 40;
Result := merNone;
if not FModbus.Port.Connected then
begin
Result := merCantOpenPort;
exit;
end;
TxSleep := GetTickCount + TxSleep;
while (GetTickCount < TxSleep) do
begin
cnt := FModbus.Port.InputCount;
if cnt <> 0 then
begin
tmp := GetTickCount;
if TxSleep > tmp then
sleep(TxSleep - tmp);
break;
end;
end;
// sleep(TxSleep);
data := '';
// cnt := FPort.InputCount;
if cnt <> 0 then
FModbus.Port.ReadStr(data, cnt)
else
Result := merTimeout;
// похоже выгребли не все
i := 5;
while ((data = '') or (crc16string(data) <> #0#0)) and (i > 0) do
begin
sleep(20);
FModbus.Port.ReadStr(s, FModbus.Port.InputCount);
data := data + s;
if s <> '' then
Result := merNone;
i := i - 1;
end;
if Result <> merNone then exit;
if crc16string(data) <> #0#0 then
begin
Result := merCRCError;
exit;
end;
end;
function TCommonModbusDeviceEmul.ReadDataTCP(
var data: AnsiString): TModbusError;
var
s: AnsiString;
cnt: integer;
i: integer;
tmp: cardinal;
begin
Result := merNone;
if not FTCP.Active then
begin
Result := merCantOpenPort;
exit;
end;
data := FTCP.Receiveln;
if crc16string(data) <> #0#0 then
begin
Result := merCRCError;
exit;
end;
end;
function TCommonModbusDeviceEmul.WriteData(
var data: AnsiString): TModbusError;
var
s: AnsiString;
begin
Result := merNone;
s := data + crc16string(data);
if not FModbus.Port.Connected then
begin
Result := merCantOpenPort;
exit;
end;
//flush
FModbus.Port.ReadStr(data, FModbus.Port.InputCount);
//write
FModbus.Port.WriteStr(s);
end;
function TCommonModbusDeviceEmul.WriteDataTCP(
var data: AnsiString): TModbusError;
var
s: AnsiString;
begin
Result := merNone;
s := data + crc16string(data);
if not FTCP.Active then
begin
Result := merCantOpenPort;
exit;
end;
FTCP.Sendln(data);
end;
end.
|
unit uImageViewerThread;
interface
uses
Winapi.Windows,
Winapi.ActiveX,
System.SysUtils,
Vcl.Graphics,
Vcl.Imaging.PngImage,
GraphicCrypt,
uTime,
uMemory,
uConstants,
uThreadForm,
uLogger,
uIImageViewer,
uDBThread,
uDBEntities,
uDBManager,
uImageLoader,
uPortableDeviceUtils,
uBitmapUtils,
uGraphicUtils,
uRAWImage,
uPNGUtils,
uJpegUtils,
uExifInfo,
uSettings,
uAnimatedJPEG,
uProgramStatInfo,
uSessionPasswords,
uFaceDetection,
uFaceDetectionThread;
type
TImageViewerThread = class(TDBThread)
private
FOwnerControl: IImageViewer;
FThreadId: TGUID;
FInfo: TMediaItem;
FDisplaySize: TSize;
FIsPreview: Boolean;
FPageNumber: Integer;
FDetectFaces: Boolean;
FTotalPages: Integer;
FRealWidth: Integer;
FRealHeight: Integer;
FRealZoomScale: Double;
FIsTransparent: Boolean;
//TODO; remove
FTransparentColor: TColor;
FGraphic: TGraphic;
FBitmap: TBitmap;
FExifInfo: IExifInfo;
procedure SetStaticImage;
procedure SetAnimatedImageAsynch;
procedure SetNOImageAsynch(ErrorMessage: string);
procedure FinishDetectionFaces;
protected
procedure Execute; override;
public
constructor Create(OwnerForm: TThreadForm; OwnerControl: IImageViewer; ThreadId: TGUID;
Info: TMediaItem; DisplaySize: TSize; IsPreview: Boolean; PageNumber: Integer; DetectFaces: Boolean);
destructor Destroy; override;
end;
implementation
{ TImageViewerThread }
constructor TImageViewerThread.Create(OwnerForm: TThreadForm;
OwnerControl: IImageViewer; ThreadId: TGUID; Info: TMediaItem;
DisplaySize: TSize; IsPreview: Boolean; PageNumber: Integer; DetectFaces: Boolean);
begin
if Info = nil then
raise EArgumentNilException.Create('Info is nil!');
inherited Create(OwnerForm, False);
FOwnerControl := OwnerControl;
FThreadId := ThreadId;
FInfo := Info.Copy;
FDisplaySize := DisplaySize;
FIsPreview := IsPreview;
FPageNumber := PageNumber;
FDetectFaces := DetectFaces;
//TODO: remove
FTransparentColor := Theme.PanelColor;
end;
destructor TImageViewerThread.Destroy;
begin
F(FInfo);
inherited;
end;
procedure TImageViewerThread.Execute;
var
Password: string;
LoadFlags: TImageLoadFlags;
ImageInfo: ILoadImageInfo;
PNG: TPNGImage;
begin
inherited;
FreeOnTerminate := True;
CoInitialize(nil);
try
try
Password := '';
FTotalPages := 1;
FRealZoomScale := 0;
FIsTransparent := False;
if not IsDevicePath(FInfo.FileName) and ValidCryptGraphicFile(FInfo.FileName) then
begin
Password := SessionPasswords.FindForFile(FInfo.FileName);
if Password = '' then
begin
SetNOImageAsynch('');
Exit;
end;
end;
FGraphic := nil;
ImageInfo := nil;
FExifInfo := nil;
try
LoadFlags := [ilfGraphic, ilfICCProfile, ilfPassword, ilfEXIF, ilfUseCache, ilfThrowError];
try
if not LoadImageFromPath(FInfo, FPageNumber, Password, LoadFlags, ImageInfo, FDisplaySize.cx, FDisplaySize.cy) then
begin
SetNOImageAsynch('');
Exit;
end;
FTotalPages := ImageInfo.ImageTotalPages;
FGraphic := ImageInfo.ExtractGraphic;
TW.I.Start('Start EXIF reading');
FillExifInfo(ImageInfo.ExifData, ImageInfo.RawExif, FExifInfo);
TW.I.Start('End EXIF reading');
except
on e: Exception do
begin
EventLog(e);
SetNOImageAsynch(e.Message);
Exit;
end;
end;
FRealWidth := FGraphic.Width;
FRealHeight := FGraphic.Height;
if FIsPreview then
JPEGScale(FGraphic, FDisplaySize.cx, FDisplaySize.cy);
//statistics
if FGraphic is TAnimatedJPEG then
ProgramStatistics.Image3dUsed;
FRealZoomScale := 1;
if FGraphic.Width <> 0 then
FRealZoomScale := FRealWidth / FGraphic.Width;
if FGraphic is TRAWImage then
FRealZoomScale := TRAWImage(FGraphic).Width / TRAWImage(FGraphic).GraphicWidth;
if IsAnimatedGraphic(FGraphic) then
begin
SynchronizeEx(SetAnimatedImageAsynch);
end else
begin
FBitmap := TBitmap.Create;
try
try
if FGraphic is TPNGImage then
begin
FIsTransparent := True;
PNG := (FGraphic as TPNGImage);
if PNG.TransparencyMode <> ptmNone then
LoadPNGImage32bit(PNG, FBitmap, FTransparentColor)
else
AssignGraphic(FBitmap, FGraphic);
end else
begin
if (FGraphic is TBitmap) then
begin
if PSDTransparent then
begin
if (FGraphic as TBitmap).PixelFormat = pf32bit then
begin
FIsTransparent := True;
LoadBMPImage32bit(FGraphic as TBitmap, FBitmap, FTransparentColor);
end else
AssignGraphic(FBitmap, FGraphic);
end else
AssignGraphic(FBitmap, FGraphic);
end else
AssignGraphic(FBitmap, FGraphic);
end;
FBitmap.PixelFormat := pf24bit;
except
on e: Exception do
begin
SetNOImageAsynch(e.Message);
Exit;
end;
end;
ImageInfo.AppllyICCProfile(FBitmap);
ApplyRotate(FBitmap, FInfo.Rotation);
if not SynchronizeEx(SetStaticImage) then
F(FBitmap);
finally
F(FBitmap);
end;
end;
finally
if FDetectFaces and AppSettings.Readbool('FaceDetection', 'Enabled', True) and FaceDetectionManager.IsActive then
begin
if CanDetectFacesOnImage(FInfo.FileName, FGraphic) then
FaceDetectionDataManager.RequestFaceDetection(FOwnerControl.GetObject, DBManager.DBContext, FGraphic, FInfo)
else
FinishDetectionFaces;
end else
FinishDetectionFaces;
F(FGraphic);
end;
except
on Ex: Exception do
begin
EventLog(Ex);
SetNOImageAsynch(Ex.Message);
end;
end;
finally
CoUninitialize;
end;
end;
procedure TImageViewerThread.FinishDetectionFaces;
begin
SynchronizeEx(procedure
begin
if FOwnerControl <> nil then
FOwnerControl.FinishDetectionFaces;
end
);
end;
procedure TImageViewerThread.SetAnimatedImageAsynch;
begin
if IsEqualGUID(FOwnerControl.ActiveThreadId, FThreadId) then
begin
FOwnerControl.SetAnimatedImage(FGraphic, FRealWidth, FRealHeight, FInfo.Rotation, FRealZoomScale, FExifInfo);
Pointer(FGraphic) := nil;
end;
end;
procedure TImageViewerThread.SetNOImageAsynch(ErrorMessage: string);
begin
SynchronizeEx(
procedure
begin
if IsEqualGUID(FOwnerControl.ActiveThreadId, FThreadId) then
FOwnerControl.FailedToLoadImage(ErrorMessage);
end
);
end;
procedure TImageViewerThread.SetStaticImage;
begin
if IsEqualGUID(FOwnerControl.ActiveThreadId, FThreadId) then
begin
FOwnerControl.SetStaticImage(FBitmap, FRealWidth, FRealHeight, FInfo.Rotation, FRealZoomScale, FExifInfo);
FBitmap := nil;
end else
F(FBitmap);
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSmoothNavigator<p>
An extention of TGLNavigator, which allows to move objects with inertia
Note: it is not completely FPS-independant. Only Moving code is, but
MoveAroundTarget, Turn[Vertical/Horizontal] and AdjustDistanceTo[..] is not.
Don't know why, but when I make their code identical, these function stop
working completely. So you probably have to call the AutoScaleParameters
procedure once in a while for it to adjust to the current framerate.
If someone knows a better way to solve this issue, please contact me via
glscene newsgroups.<p>
<b>History : </b><font size=-1><ul>
<li>25/02/07 - DaStr - Added the AdjustDistanceTo[..] procedures
<li>23/02/07 - DaStr - Initial version (contributed to GLScene)
TODO:
1) Scale "Old values" too, when callin the Scale parameter procedure to
avoid the temporary "freeze" of controls.
2) AddImpulse procedures.
Previous version history:
v1.0 10 December '2005 Creation
v1.0.2 11 December '2005 TurnMaxAngle added
v1.1 04 March '2006 Inertia became FPS-independant
TGLSmoothNavigatorParameters added
v1.1.6 18 February '2007 Merged with GLInertedUserInterface.pas
All parameters moved into separate classes
Added MoveAroudTargetWithInertia
v1.2 23 February '2007 Finally made it trully FPS-independant
Added default values to every property
Contributed to GLScene
}
unit GLSmoothNavigator;
interface
{$I GLScene.inc}
uses
// VCL
Classes,
// GLScene
GLNavigator, GLVectorGeometry, GLScene, GLCrossPlatform, GLCoordinates, GLScreen;
type
{: TGLNavigatorAdjustDistanceParameters is wrapper for all parameters that
affect how the AdjustDisanceTo[...] methods work<p>
}
TGLNavigatorAdjustDistanceParameters = class(TPersistent)
private
FOwner: TPersistent;
OldDistanceRatio: Single;
FInertia: Single;
FSpeed: Single;
FImpulseSpeed: Single;
function StoreInertia: Boolean;
function StoreSpeed: Boolean;
function StoreImpulseSpeed: Boolean;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
procedure AddImpulse(const Impulse: Single); virtual;
published
property Inertia: Single read FInertia write FInertia stored StoreInertia;
property Speed: Single read FSpeed write FSpeed stored StoreSpeed;
property ImpulseSpeed: Single read FImpulseSpeed write FImpulseSpeed stored StoreImpulseSpeed;
end;
{: TGLNavigatorInertiaParameters is wrapper for all parameters that affect the
smoothness of movement<p>
}
TGLNavigatorInertiaParameters = class(TPersistent)
private
FOwner: TPersistent;
OldTurnHorizontalAngle: Single;
OldTurnVerticalAngle: Single;
OldMoveForwardDistance: Single;
OldStrafeHorizontalDistance: Single;
OldStrafeVerticalDistance: Single;
FTurnInertia: Single;
FTurnSpeed: Single;
FTurnMaxAngle: Single;
FMovementAcceleration: Single;
FMovementInertia: Single;
FMovementSpeed: Single;
function StoreTurnMaxAngle: Boolean;
function StoreMovementAcceleration: Boolean;
function StoreMovementInertia: Boolean;
function StoreMovementSpeed: Boolean;
function StoreTurnInertia: Boolean;
function StoreTurnSpeed: Boolean;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
published
property MovementAcceleration: Single read FMovementAcceleration write FMovementAcceleration stored StoreMovementAcceleration;
property MovementInertia: Single read FMovementInertia write FMovementInertia stored StoreMovementInertia;
property MovementSpeed: Single read FMovementSpeed write FMovementSpeed stored StoreMovementSpeed;
property TurnMaxAngle: Single read FTurnMaxAngle write FTurnMaxAngle stored StoreTurnMaxAngle;
property TurnInertia: Single read FTurnInertia write FTurnInertia stored StoreTurnInertia;
property TurnSpeed: Single read FTurnSpeed write FTurnSpeed stored StoreTurnSpeed;
end;
{: TGLNavigatorGeneralParameters is a wrapper for all general inertia parameters.
These properties mean that if ExpectedMaxFPS is 100, FAutoScaleMin is 0.1,
FAutoScaleMax is 0.75 then the "safe range" for it to change is [10..75].
If these bounds are violated, then ExpectedMaxFPS is automaticly increased
or decreased by AutoScaleMult.
}
TGLNavigatorGeneralParameters = class(TPersistent)
private
FOwner: TPersistent;
FAutoScaleMin: Single;
FAutoScaleMax: Single;
FAutoScaleMult: Single;
function StoreAutoScaleMax: Boolean;
function StoreAutoScaleMin: Boolean;
function StoreAutoScaleMult: Boolean;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
published
property AutoScaleMin: Single read FAutoScaleMin write FAutoScaleMin stored StoreAutoScaleMin;
property AutoScaleMax: Single read FAutoScaleMax write FAutoScaleMax stored StoreAutoScaleMax;
property AutoScaleMult: Single read FAutoScaleMult write FAutoScaleMult stored StoreAutoScaleMult;
end;
{: TGLNavigatorMoveAroundParameters is a wrapper for all parameters that
effect how the TGLBaseSceneObject.MoveObjectAround() procedure works
}
TGLNavigatorMoveAroundParameters = class(TPersistent)
private
FOwner: TPersistent;
FTargetObject: TGLBaseSceneObject;
FOldPitchInertiaAngle : Single;
FOldTurnInertiaAngle : Single;
FPitchSpeed : Single;
FTurnSpeed : Single;
FInertia : Single;
FMaxAngle : Single;
function StoreInertia: Boolean;
function StoreMaxAngle: Boolean;
function StorePitchSpeed: Boolean;
function StoreTurnSpeed: Boolean;
procedure SetTargetObject(const Value: TGLBaseSceneObject);
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
published
property Inertia: Single read FInertia write FInertia stored StoreInertia;
property MaxAngle: Single read FMaxAngle write FMaxAngle stored StoreMaxAngle;
property PitchSpeed: Single read FPitchSpeed write FPitchSpeed stored StorePitchSpeed;
property TurnSpeed: Single read FTurnSpeed write FTurnSpeed stored StoreTurnSpeed;
property TargetObject: TGLBaseSceneObject read FTargetObject write SetTargetObject;
end;
// TGLSmoothNavigator
//
{: TGLSmoothNavigator is the component for moving a TGLBaseSceneObject, and all
classes based on it, this includes all the objects from the Scene Editor.<p>
The four calls to get you started are
<ul>
<li>TurnHorisontal : it turns left and right.
<li>TurnVertical : it turns up and down.
<li>MoveForward : moves back and forth.
<li>FlyForward : moves back and forth in the movingobject's direction
</ul>
The three properties to get you started is
<ul>
<li>MovingObject : The Object that you are moving.
<li>UseVirtualUp : When UseVirtualUp is set you navigate Quake style. If it isn't
it's more like Descent.
<li>AngleLock : Allows you to block the Vertical angles. Should only be used in
conjunction with UseVirtualUp.
<li>MoveUpWhenMovingForward : Changes movement from Quake to Arcade Airplane...
(no tilt and flying)
<li>InvertHorizontalSteeringWhenUpsideDown : When using virtual up, and vertically
rotating beyond 90 degrees, will make steering seem inverted,
so we "invert" back to normal.
</ul>
}
TGLSmoothNavigator = class(TGLNavigator)
private
FMaxExpectedDeltaTime: Single;
FInertiaParams: TGLNavigatorInertiaParameters;
FGeneralParams: TGLNavigatorGeneralParameters;
FMoveAroundParams: TGLNavigatorMoveAroundParameters;
FAdjustDistanceParams: TGLNavigatorAdjustDistanceParameters;
procedure SetInertiaParams(const Value: TGLNavigatorInertiaParameters);
function StoreMaxExpectedDeltaTime: Boolean;
procedure SetGeneralParams(const Value: TGLNavigatorGeneralParameters);
procedure SetMoveAroundParams(const Value: TGLNavigatorMoveAroundParameters);
procedure SetAdjustDistanceParams(const Value: TGLNavigatorAdjustDistanceParameters);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
//: Constructors-destructors
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
//: From TGLNavigator
procedure SetObject(Value: TGLBaseSceneObject); override;
//: InertiaParams
procedure TurnHorizontal(Angle: Single; DeltaTime: Single); virtual;
procedure TurnVertical(Angle: Single; DeltaTime: Single); virtual;
procedure FlyForward(const Plus, Minus: Boolean; DeltaTime: Single; const Accelerate: Boolean = False); virtual;
procedure MoveForward(const Plus, Minus: Boolean; DeltaTime: Single; const Accelerate: Boolean = False); virtual;
procedure StrafeHorizontal(const Plus, Minus: Boolean; DeltaTime: Single; const Accelerate: Boolean = False); virtual;
procedure StrafeVertical(const Plus, Minus: Boolean; DeltaTime: Single; const Accelerate: Boolean = False); virtual;
//: MoveAroundParams
procedure MoveAroundTarget(const PitchDelta, TurnDelta : Single; const DeltaTime: Single); virtual;
procedure MoveObjectAround(const AObject: TGLBaseSceneObject; PitchDelta, TurnDelta : Single; DeltaTime: Single); virtual;
//: AdjustDistanceParams
procedure AdjustDistanceToPoint(const APoint: TVector; const DistanceRatio : Single; DeltaTime: Single); virtual;
procedure AdjustDistanceToTarget(const DistanceRatio : Single; const DeltaTime: Single); virtual;
//: GeneralParams
{: In ScaleParameters, Value should be around 1. }
procedure ScaleParameters(const Value: Single); virtual;
procedure AutoScaleParameters(const FPS: Single); virtual;
procedure AutoScaleParametersUp(const FPS: Single); virtual;
published
property MaxExpectedDeltaTime: Single read FMaxExpectedDeltaTime write FMaxExpectedDeltaTime stored StoreMaxExpectedDeltaTime;
property InertiaParams: TGLNavigatorInertiaParameters read FInertiaParams write SetInertiaParams;
property GeneralParams: TGLNavigatorGeneralParameters read FGeneralParams write SetGeneralParams;
property MoveAroundParams: TGLNavigatorMoveAroundParameters read FMoveAroundParams write SetMoveAroundParams;
property AdjustDistanceParams: TGLNavigatorAdjustDistanceParameters read FAdjustDistanceParams write SetAdjustDistanceParams;
end;
// TGLSmoothUserInterface
//
{: TGLSmoothUserInterface is the component which reads the userinput and transform it into action.<p>
<ul>
<li>Mouselook(deltaTime: double) : handles mouse look... Should be called
in the Cadencer event. (Though it works everywhere!)
</ul>
The four properties to get you started are:
<ul>
<li>InvertMouse : Inverts the mouse Y axis.
<li>AutoUpdateMouse : If enabled (by defaul), than handles all mouse updates.
<li>GLNavigator : The Navigator which receives the user movement.
<li>GLVertNavigator : The Navigator which if set receives the vertical user
movement. Used mostly for cameras....
</ul>
}
TGLSmoothUserInterface = class(TComponent)
private
FAutoUpdateMouse: Boolean;
FMouseLookActive: Boolean;
FSmoothNavigator: TGLSmoothNavigator;
FSmoothVertNavigator: TGLSmoothNavigator;
FInvertMouse: Boolean;
FOriginalMousePos: TGLCoordinates2;
procedure SetSmoothNavigator(const Value: TGLSmoothNavigator); virtual;
procedure SetOriginalMousePos(const Value: TGLCoordinates2); virtual;
procedure SetSmoothVertNavigator(const Value: TGLSmoothNavigator); virtual;
procedure SetMouseLookActive(const Value: Boolean); virtual;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure TurnHorizontal(const Angle : Single; const DeltaTime: Single); virtual;
procedure TurnVertical(const Angle : Single; const DeltaTime: Single); virtual;
procedure MouseLookActiveToggle; virtual;
function MouseLook(const DeltaTime: Single): Boolean; overload;
function MouseLook(const NewXY: TGLPoint; const DeltaTime: Single): Boolean; overload;
function MouseLook(const NewX, NewY: Integer; const DeltaTime: Single): Boolean; overload;
published
property AutoUpdateMouse: Boolean read FAutoUpdateMouse write FAutoUpdateMouse default True;
property MouseLookActive: Boolean read FMouseLookActive write SetMouseLookActive default False;
property SmoothVertNavigator: TGLSmoothNavigator read FSmoothVertNavigator write SetSmoothVertNavigator;
property SmoothNavigator: TGLSmoothNavigator read FSmoothNavigator write SetSmoothNavigator;
property InvertMouse: Boolean read FInvertMouse write FInvertMouse default False;
property OriginalMousePos: TGLCoordinates2 read FOriginalMousePos write SetOriginalMousePos;
end;
implementation
const
EPS = 0.001;
EPS2 = 0.0001;
{ TGLSmoothNavigator }
constructor TGLSmoothNavigator.Create(AOwner: TComponent);
begin
inherited;
FMaxExpectedDeltaTime := 0.001;
FInertiaParams := TGLNavigatorInertiaParameters.Create(Self);
FGeneralParams := TGLNavigatorGeneralParameters.Create(Self);
FMoveAroundParams := TGLNavigatorMoveAroundParameters.Create(Self);
FAdjustDistanceParams := TGLNavigatorAdjustDistanceParameters.Create(Self);
end;
destructor TGLSmoothNavigator.Destroy;
begin
FInertiaParams.Free;
FGeneralParams.Free;
FMoveAroundParams.Free;
FAdjustDistanceParams.Free;
inherited;
end;
procedure TGLSmoothNavigator.SetInertiaParams(
const Value: TGLNavigatorInertiaParameters);
begin
FInertiaParams.Assign(Value);
end;
procedure TGLSmoothNavigator.TurnHorizontal(Angle: Single; DeltaTime: Single);
var
FinalAngle: Single;
begin
with FInertiaParams do
begin
FinalAngle := 0;
Angle := Angle * FTurnSpeed;
while DeltaTime > FMaxExpectedDeltaTime do
begin
Angle := ClampValue((Angle * FMaxExpectedDeltaTime + OldTurnHorizontalAngle * FTurnInertia) / (FTurnInertia + 1), -FTurnMaxAngle, FTurnMaxAngle);
OldTurnHorizontalAngle := Angle;
DeltaTime := DeltaTime - FMaxExpectedDeltaTime;
FinalAngle := FinalAngle + Angle;
end;
end;
if (Abs(FinalAngle) > EPS) then
inherited TurnHorizontal(FinalAngle);
end;
procedure TGLSmoothNavigator.TurnVertical(Angle: Single; DeltaTime: Single);
var
FinalAngle: Single;
begin
with FInertiaParams do
begin
FinalAngle := 0;
Angle := Angle * FTurnSpeed;
while DeltaTime > FMaxExpectedDeltaTime do
begin
Angle := ClampValue((Angle * FMaxExpectedDeltaTime + OldTurnVerticalAngle * FTurnInertia) / (FTurnInertia + 1), -FTurnMaxAngle, FTurnMaxAngle);
OldTurnVerticalAngle := Angle;
DeltaTime := DeltaTime - FMaxExpectedDeltaTime;
FinalAngle := FinalAngle + Angle;
end;
end;
if (Abs(FinalAngle) > EPS) then
inherited TurnVertical(FinalAngle);
end;
procedure TGLSmoothNavigator.MoveForward(const Plus, Minus: Boolean; DeltaTime: Single; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while DeltaTime > FMaxExpectedDeltaTime do
begin
OldMoveForwardDistance := (Distance * FMaxExpectedDeltaTime + OldMoveForwardDistance * FMovementInertia) / (FMovementInertia + 1);
DeltaTime := DeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldMoveForwardDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited MoveForward(FinalDistance);
end;
procedure TGLSmoothNavigator.FlyForward(const Plus, Minus: Boolean; DeltaTime: Single; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while DeltaTime > FMaxExpectedDeltaTime do
begin
OldMoveForwardDistance := (Distance * FMaxExpectedDeltaTime + OldMoveForwardDistance * FMovementInertia) / (FMovementInertia + 1);
DeltaTime := DeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldMoveForwardDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited FlyForward(FinalDistance);
end;
procedure TGLSmoothNavigator.StrafeHorizontal(const Plus, Minus: Boolean; DeltaTime: Single; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while DeltaTime > FMaxExpectedDeltaTime do
begin
OldStrafeHorizontalDistance := (Distance * FMaxExpectedDeltaTime + OldStrafeHorizontalDistance * FMovementInertia) / (FMovementInertia + 1);
DeltaTime := DeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldStrafeHorizontalDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited StrafeHorizontal(FinalDistance);
end;
procedure TGLSmoothNavigator.StrafeVertical(const Plus, Minus: Boolean; DeltaTime: Single; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while DeltaTime > FMaxExpectedDeltaTime do
begin
OldStrafeVerticalDistance := (Distance * FMaxExpectedDeltaTime + OldStrafeVerticalDistance * FMovementInertia) / (FMovementInertia + 1);
DeltaTime := DeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldStrafeVerticalDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited StrafeVertical(FinalDistance);
end;
procedure TGLSmoothNavigator.AutoScaleParameters(const FPS: Single);
begin
with FGeneralParams do
begin
if FPS > FAutoScaleMax / FMaxExpectedDeltatime then
ScaleParameters(FAutoScaleMult)
else if FPS < FAutoScaleMin / FMaxExpectedDeltatime then
ScaleParameters(1/FAutoScaleMult);
end;
end;
procedure TGLSmoothNavigator.AutoScaleParametersUp(const FPS: Single);
begin
with FGeneralParams do
begin
if FPS > FAutoScaleMax / FMaxExpectedDeltatime then
ScaleParameters(FAutoScaleMult)
end;
end;
procedure TGLSmoothNavigator.ScaleParameters(const Value: Single);
begin
Assert(Value > 0);
FMaxExpectedDeltatime := FMaxExpectedDeltatime / Value;
FInertiaParams.ScaleParameters(Value);
FMoveAroundParams.ScaleParameters(Value);
FAdjustDistanceParams.ScaleParameters(Value);
end;
function TGLSmoothNavigator.StoreMaxExpectedDeltaTime: Boolean;
begin
Result := Abs(FMaxExpectedDeltaTime - 0.001) > EPS2;
end;
procedure TGLSmoothNavigator.SetGeneralParams(
const Value: TGLNavigatorGeneralParameters);
begin
FGeneralParams.Assign(Value);
end;
procedure TGLSmoothNavigator.SetMoveAroundParams(
const Value: TGLNavigatorMoveAroundParameters);
begin
FMoveAroundParams.Assign(Value);
end;
procedure TGLSmoothNavigator.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation = opRemove then
begin
if AComponent = FMoveAroundParams.FTargetObject then
FMoveAroundParams.FTargetObject := nil;
end;
end;
procedure TGLSmoothNavigator.SetObject(Value: TGLBaseSceneObject);
var
I: Integer;
begin
inherited;
// Try to detect a TargetObject.
if Value <> nil then
if FMoveAroundParams.TargetObject = nil then
begin
// May be it is a camera...
if Value is TGLCamera then
FMoveAroundParams.TargetObject := TGLCamera(Value).TargetObject
else
begin
// May be it has camera children...
if Value.Count <> 0 then
for I := 0 to Value.Count - 1 do
if Value.Children[I] is TGLCamera then
begin
FMoveAroundParams.TargetObject := TGLCamera(Value.Children[I]).TargetObject;
Exit;
end;
end;
end;
end;
procedure TGLSmoothNavigator.MoveAroundTarget(const PitchDelta, TurnDelta,
DeltaTime: Single);
begin
MoveObjectAround(FMoveAroundParams.FTargetObject, PitchDelta, TurnDelta, DeltaTime);
end;
procedure TGLSmoothNavigator.MoveObjectAround(
const AObject: TGLBaseSceneObject; PitchDelta, TurnDelta,
DeltaTime: Single);
var
FinalPitch: Single;
FinalTurn: Single;
begin
FinalPitch := 0;
FinalTurn := 0;
with FMoveAroundParams do
begin
PitchDelta := PitchDelta * FPitchSpeed;
TurnDelta := TurnDelta * FTurnSpeed;
while DeltaTime > FMaxExpectedDeltatime do
begin
PitchDelta := ClampValue((PitchDelta * FMaxExpectedDeltatime + FOldPitchInertiaAngle * FInertia) / (FInertia + 1), - FMaxAngle, FMaxAngle);
FOldPitchInertiaAngle := PitchDelta;
FinalPitch := FinalPitch + PitchDelta;
TurnDelta := ClampValue((TurnDelta * FMaxExpectedDeltatime + FOldTurnInertiaAngle * FInertia) / (FInertia + 1), - FMaxAngle, FMaxAngle);
FOldTurnInertiaAngle := TurnDelta;
FinalTurn := FinalTurn + TurnDelta;
DeltaTime := DeltaTime - FMaxExpectedDeltatime;
end;
if (Abs(FinalPitch) > EPS) or (Abs(FinalTurn) > EPS) then
MovingObject.MoveObjectAround(AObject, FinalPitch, FinalTurn);
end;
end;
procedure TGLSmoothNavigator.AdjustDistanceToPoint(const APoint: TVector;
const DistanceRatio: Single; DeltaTime: Single);
// Based on TGLCamera.AdjustDistanceToTarget
procedure DoAdjustDistanceToPoint(const DistanceRatio: Single);
var
vect: TVector;
begin
vect := VectorSubtract(MovingObject.AbsolutePosition, APoint);
ScaleVector(vect, (distanceRatio - 1));
AddVector(vect, MovingObject.AbsolutePosition);
if Assigned(MovingObject.Parent) then
vect := MovingObject.Parent.AbsoluteToLocal(vect);
MovingObject.Position.AsVector := vect;
end;
var
FinalDistanceRatio: Single;
TempDistanceRatio: Single;
begin
with FAdjustDistanceParams do
begin
TempDistanceRatio := DistanceRatio * FSpeed;
FinalDistanceRatio := 0;
while DeltaTime > FMaxExpectedDeltaTime do
begin
TempDistanceRatio := (TempDistanceRatio * FMaxExpectedDeltaTime + OldDistanceRatio * FInertia) / (FInertia + 1);
OldDistanceRatio := TempDistanceRatio;
DeltaTime := DeltaTime - FMaxExpectedDeltaTime;
FinalDistanceRatio := FinalDistanceRatio + OldDistanceRatio / FMaxExpectedDeltaTime;
end;
if Abs(FinalDistanceRatio) > EPS2 then
begin
if FinalDistanceRatio > 0 then
DoAdjustDistanceToPoint(1 / (1 + FinalDistanceRatio))
else
DoAdjustDistanceToPoint(1 * (1 - FinalDistanceRatio))
end;
end;
end;
procedure TGLSmoothNavigator.AdjustDistanceToTarget(const DistanceRatio,
DeltaTime: Single);
begin
Assert(FMoveAroundParams.FTargetObject <> nil);
AdjustDistanceToPoint(FMoveAroundParams.FTargetObject.AbsolutePosition,
DistanceRatio, DeltaTime);
end;
procedure TGLSmoothNavigator.SetAdjustDistanceParams(
const Value: TGLNavigatorAdjustDistanceParameters);
begin
FAdjustDistanceParams.Assign(Value);
end;
{ TGLSmoothUserInterface }
function TGLSmoothUserInterface.MouseLook(
const DeltaTime: Single): Boolean;
var
MousePos: TGLPoint;
begin
Assert(FAutoUpdateMouse, 'AutoUpdateMouse must be True to use this function');
if FMouseLookActive then
begin
GLGetCursorPos(MousePos);
Result := Mouselook(MousePos.X, MousePos.Y, DeltaTime);
GLSetCursorPos(Round(OriginalMousePos.X), Round(OriginalMousePos.Y));
end
else
Result := False;
end;
function TGLSmoothUserInterface.Mouselook(const NewX, NewY: Integer; const DeltaTime: Single): Boolean;
var
DeltaX, DeltaY: Single;
begin
Result := False;
if FMouseLookActive then
begin
Deltax := (NewX - FOriginalMousePos.X);
Deltay := (FOriginalMousePos.Y - NewY);
if InvertMouse then
DeltaY := -DeltaY;
SmoothNavigator.TurnHorizontal(DeltaX, DeltaTime);
SmoothNavigator.TurnVertical(DeltaY, DeltaTime);
Result := (DeltaX <> 0) or (DeltaY <> 0);
end;
end;
function TGLSmoothUserInterface.MouseLook(const NewXY: TGLPoint; const DeltaTime: Single): Boolean;
begin
Result := Mouselook(NewXY.X, NewXY.Y, DeltaTime);
end;
constructor TGLSmoothUserInterface.Create(AOwner: TComponent);
begin
inherited;
FMouseLookActive := False;
FAutoUpdateMouse := True;
FOriginalMousePos := TGLCoordinates2.CreateInitialized(Self,
VectorMake(GLGetScreenWidth div 2,
GLGetScreenHeight div 2, 0, 0), csPoint2D);
end;
procedure TGLSmoothUserInterface.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
begin
if AComponent = FSmoothNavigator then
FSmoothNavigator := nil;
if AComponent = FSmoothVertNavigator then
FSmoothNavigator := nil;
end;
end;
procedure TGLSmoothUserInterface.SetSmoothNavigator(
const Value: TGLSmoothNavigator);
begin
if FSmoothNavigator <> nil then
FSmoothNavigator.RemoveFreeNotification(Self);
FSmoothNavigator := Value;
if FSmoothNavigator <> nil then
FSmoothNavigator.FreeNotification(Self);
end;
destructor TGLSmoothUserInterface.Destroy;
begin
FOriginalMousePos.Destroy;
inherited;
end;
procedure TGLSmoothUserInterface.SetOriginalMousePos(
const Value: TGLCoordinates2);
begin
FOriginalMousePos.Assign(Value);
end;
procedure TGLSmoothUserInterface.SetSmoothVertNavigator(
const Value: TGLSmoothNavigator);
begin
if FSmoothVertNavigator <> nil then
FSmoothVertNavigator.RemoveFreeNotification(Self);
FSmoothVertNavigator := Value;
if FSmoothVertNavigator <> nil then
FSmoothVertNavigator.FreeNotification(Self);
end;
procedure TGLSmoothUserInterface.MouseLookActiveToggle;
begin
if FMouseLookActive then
SetMouseLookActive(False)
else
SetMouseLookActive(True)
end;
procedure TGLSmoothUserInterface.SetMouseLookActive(const Value: Boolean);
var
MousePos: TGLPoint;
begin
if FMouseLookActive = Value then Exit;
FMouseLookActive := Value;
if FMouseLookActive then
begin
if FAutoUpdateMouse then
begin
GLGetCursorPos(MousePos);
FOriginalMousePos.SetPoint2D(MousePos.X, MousePos.Y);
GLShowCursor(False);
end;
end
else
begin
if FAutoUpdateMouse then
GLShowCursor(True);
end;
end;
procedure TGLSmoothUserInterface.TurnHorizontal(const Angle: Single;
const DeltaTime: Single);
begin
FSmoothNavigator.TurnHorizontal(Angle, DeltaTime);
end;
procedure TGLSmoothUserInterface.TurnVertical(const Angle: Single;
const DeltaTime: Single);
begin
if Assigned(FSmoothNavigator) then
FSmoothNavigator.TurnVertical(Angle, DeltaTime)
else
FSmoothVertNavigator.TurnVertical(Angle, DeltaTime);
end;
{ TGLNavigatorInertiaParameters }
procedure TGLNavigatorInertiaParameters.Assign(Source: TPersistent);
begin
if Source is TGLNavigatorInertiaParameters then
begin
FMovementAcceleration := TGLNavigatorInertiaParameters(Source).FMovementAcceleration;
FMovementInertia := TGLNavigatorInertiaParameters(Source).FMovementInertia;
FMovementSpeed := TGLNavigatorInertiaParameters(Source).FMovementSpeed;
FTurnMaxAngle := TGLNavigatorInertiaParameters(Source).FTurnMaxAngle;
FTurnInertia := TGLNavigatorInertiaParameters(Source).FTurnInertia;
FTurnSpeed := TGLNavigatorInertiaParameters(Source).FTurnSpeed;
end
else
inherited; //to the pit of doom ;)
end;
constructor TGLNavigatorInertiaParameters.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
FTurnInertia := 150;
FTurnSpeed := 50;
FTurnMaxAngle := 0.5;
FMovementAcceleration := 7;
FMovementInertia := 200;
FMovementSpeed := 200;
end;
function TGLNavigatorInertiaParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TGLNavigatorInertiaParameters.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value > 1 then
begin
FMovementInertia := FMovementInertia * GLVectorGeometry.Power(2, 1 / Value);
FTurnInertia := FTurnInertia * GLVectorGeometry.Power(2, 1 / Value);
end
else
begin
FMovementInertia := FMovementInertia / GLVectorGeometry.Power(2, Value);
FTurnInertia := FTurnInertia / GLVectorGeometry.Power(2, Value);
end;
FTurnMaxAngle := FTurnMaxAngle / Value;
FTurnSpeed := FTurnSpeed * Value;
end;
function TGLNavigatorInertiaParameters.StoreTurnMaxAngle: Boolean;
begin
Result := Abs(FTurnMaxAngle - 0.5) > EPS;
end;
function TGLNavigatorInertiaParameters.StoreMovementAcceleration: Boolean;
begin
Result := Abs(FMovementAcceleration - 7) > EPS;
end;
function TGLNavigatorInertiaParameters.StoreMovementInertia: Boolean;
begin
Result := Abs(FMovementInertia - 200) > EPS;
end;
function TGLNavigatorInertiaParameters.StoreMovementSpeed: Boolean;
begin
Result := Abs(FMovementSpeed - 200) > EPS;
end;
function TGLNavigatorInertiaParameters.StoreTurnInertia: Boolean;
begin
Result := Abs(FTurnInertia - 150) > EPS;
end;
function TGLNavigatorInertiaParameters.StoreTurnSpeed: Boolean;
begin
Result := Abs(FTurnSpeed - 50) > EPS;
end;
{ TGLNavigatorGeneralParameters }
procedure TGLNavigatorGeneralParameters.Assign(Source: TPersistent);
begin
if Source is TGLNavigatorGeneralParameters then
begin
FAutoScaleMin := TGLNavigatorGeneralParameters(Source).FAutoScaleMin;
FAutoScaleMax := TGLNavigatorGeneralParameters(Source).FAutoScaleMax;
FAutoScaleMult := TGLNavigatorGeneralParameters(Source).FAutoScaleMult;
end
else
inherited; //die!
end;
constructor TGLNavigatorGeneralParameters.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
FAutoScaleMin := 0.1;
FAutoScaleMax := 0.75;
FAutoScaleMult := 2;
end;
function TGLNavigatorGeneralParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TGLNavigatorGeneralParameters.StoreAutoScaleMax: Boolean;
begin
Result := Abs(FAutoScaleMax - 0.75) > EPS;
end;
function TGLNavigatorGeneralParameters.StoreAutoScaleMin: Boolean;
begin
Result := Abs(FAutoScaleMin - 0.1) > EPS;
end;
function TGLNavigatorGeneralParameters.StoreAutoScaleMult: Boolean;
begin
Result := Abs(FAutoScaleMult - 2) > EPS;
end;
{ TGLNavigatorMoveAroundParameters }
procedure TGLNavigatorMoveAroundParameters.Assign(Source: TPersistent);
begin
if Source is TGLNavigatorMoveAroundParameters then
begin
FMaxAngle := TGLNavigatorMoveAroundParameters(Source).FMaxAngle;
FInertia := TGLNavigatorMoveAroundParameters(Source).FInertia;
FPitchSpeed := TGLNavigatorMoveAroundParameters(Source).FPitchSpeed;
FTurnSpeed := TGLNavigatorMoveAroundParameters(Source).FTurnSpeed;
end
else
inherited; //die
end;
constructor TGLNavigatorMoveAroundParameters.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
FPitchSpeed := 500;
FTurnSpeed := 500;
FInertia := 65;
FMaxAngle := 1.5;
end;
function TGLNavigatorMoveAroundParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TGLNavigatorMoveAroundParameters.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value < 1 then
FInertia := FInertia / GLVectorGeometry.Power(2, Value)
else
FInertia := FInertia * GLVectorGeometry.Power(2, 1 / Value);
FMaxAngle := FMaxAngle / Value;
FPitchSpeed := FPitchSpeed * Value;
FTurnSpeed := FTurnSpeed * Value;
end;
procedure TGLNavigatorMoveAroundParameters.SetTargetObject(
const Value: TGLBaseSceneObject);
begin
if FTargetObject <> nil then
if FOwner is TGLSmoothNavigator then
FTargetObject.RemoveFreeNotification(TGLSmoothNavigator(FOwner));
FTargetObject := Value;
if FTargetObject <> nil then
if FOwner is TGLSmoothNavigator then
FTargetObject.FreeNotification(TGLSmoothNavigator(FOwner));
end;
function TGLNavigatorMoveAroundParameters.StoreInertia: Boolean;
begin
Result := Abs(FInertia - 65) > EPS;
end;
function TGLNavigatorMoveAroundParameters.StoreMaxAngle: Boolean;
begin
Result := Abs(FMaxAngle - 1.5) > EPS;
end;
function TGLNavigatorMoveAroundParameters.StorePitchSpeed: Boolean;
begin
Result := Abs(FPitchSpeed - 500) > EPS;
end;
function TGLNavigatorMoveAroundParameters.StoreTurnSpeed: Boolean;
begin
Result := Abs(FTurnSpeed - 500) > EPS;
end;
{ TGLNavigatorAdjustDistanceParameters }
procedure TGLNavigatorAdjustDistanceParameters.AddImpulse(
const Impulse: Single);
begin
OldDistanceRatio := OldDistanceRatio + Impulse * FSpeed / FInertia * FImpulseSpeed;
end;
procedure TGLNavigatorAdjustDistanceParameters.Assign(Source: TPersistent);
begin
if Source is TGLNavigatorAdjustDistanceParameters then
begin
FInertia := TGLNavigatorAdjustDistanceParameters(Source).FInertia;
FSpeed := TGLNavigatorAdjustDistanceParameters(Source).FSpeed;
FImpulseSpeed := TGLNavigatorAdjustDistanceParameters(Source).FImpulseSpeed;
end
else
inherited; //to the pit of doom ;)
end;
constructor TGLNavigatorAdjustDistanceParameters.Create(
AOwner: TPersistent);
begin
FOwner := AOwner;
FInertia := 100;
FSpeed := 0.005;
FImpulseSpeed := 0.02;
end;
function TGLNavigatorAdjustDistanceParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TGLNavigatorAdjustDistanceParameters.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value < 1 then
FInertia := FInertia / GLVectorGeometry.Power(2, Value)
else
FInertia := FInertia * GLVectorGeometry.Power(2, 1 / Value);
FImpulseSpeed := FImpulseSpeed / Value;
end;
function TGLNavigatorAdjustDistanceParameters.StoreImpulseSpeed: Boolean;
begin
Result := Abs(FImpulseSpeed - 0.02) > EPS;
end;
function TGLNavigatorAdjustDistanceParameters.StoreInertia: Boolean;
begin
Result := Abs(FInertia - 100) > EPS;
end;
function TGLNavigatorAdjustDistanceParameters.StoreSpeed: Boolean;
begin
Result := Abs(FSpeed - 0.005) > EPS2;
end;
initialization
RegisterClasses([
TGLSmoothNavigator, TGLSmoothUserInterface,
TGLNavigatorInertiaParameters, TGLNavigatorGeneralParameters,
TGLNavigatorMoveAroundParameters, TGLNavigatorAdjustDistanceParameters
]);
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 183315
////////////////////////////////////////////////////////////////////////////////
unit org.apache.http.impl.conn.SingleClientConnManager;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
org.apache.http.conn.scheme.SchemeRegistry,
org.apache.http.conn.ClientConnectionOperator,
org.apache.http.impl.conn.SingleClientConnManager_PoolEntry,
org.apache.http.impl.conn.SingleClientConnManager_ConnAdapter,
org.apache.http.params.HttpParams,
org.apache.http.conn.ClientConnectionRequest,
org.apache.http.conn.routing.HttpRoute,
org.apache.http.conn.ManagedClientConnection;
type
JSingleClientConnManager = interface;
JSingleClientConnManagerClass = interface(JObjectClass)
['{356C7C0A-D463-48CE-B894-DA139D60CE02}']
function _GetMISUSE_MESSAGE : JString; cdecl; // A: $19
function getConnection(route : JHttpRoute; state : JObject) : JManagedClientConnection; cdecl;// (Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Object;)Lorg/apache/http/conn/ManagedClientConnection; A: $1
function getSchemeRegistry : JSchemeRegistry; cdecl; // ()Lorg/apache/http/conn/scheme/SchemeRegistry; A: $1
function init(params : JHttpParams; schreg : JSchemeRegistry) : JSingleClientConnManager; cdecl;// (Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/scheme/SchemeRegistry;)V A: $1
function requestConnection(route : JHttpRoute; state : JObject) : JClientConnectionRequest; cdecl;// (Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Object;)Lorg/apache/http/conn/ClientConnectionRequest; A: $11
procedure closeExpiredConnections ; cdecl; // ()V A: $1
procedure closeIdleConnections(idletime : Int64; tunit : JTimeUnit) ; cdecl;// (JLjava/util/concurrent/TimeUnit;)V A: $1
procedure releaseConnection(conn : JManagedClientConnection; validDuration : Int64; timeUnit : JTimeUnit) ; cdecl;// (Lorg/apache/http/conn/ManagedClientConnection;JLjava/util/concurrent/TimeUnit;)V A: $1
procedure shutdown ; cdecl; // ()V A: $1
property MISUSE_MESSAGE : JString read _GetMISUSE_MESSAGE; // Ljava/lang/String; A: $19
end;
[JavaSignature('org/apache/http/impl/conn/SingleClientConnManager$ConnAdapter')]
JSingleClientConnManager = interface(JObject)
['{0194AF21-FB21-4689-BA55-E0C4AF793BA6}']
function getConnection(route : JHttpRoute; state : JObject) : JManagedClientConnection; cdecl;// (Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Object;)Lorg/apache/http/conn/ManagedClientConnection; A: $1
function getSchemeRegistry : JSchemeRegistry; cdecl; // ()Lorg/apache/http/conn/scheme/SchemeRegistry; A: $1
procedure closeExpiredConnections ; cdecl; // ()V A: $1
procedure closeIdleConnections(idletime : Int64; tunit : JTimeUnit) ; cdecl;// (JLjava/util/concurrent/TimeUnit;)V A: $1
procedure releaseConnection(conn : JManagedClientConnection; validDuration : Int64; timeUnit : JTimeUnit) ; cdecl;// (Lorg/apache/http/conn/ManagedClientConnection;JLjava/util/concurrent/TimeUnit;)V A: $1
procedure shutdown ; cdecl; // ()V A: $1
end;
TJSingleClientConnManager = class(TJavaGenericImport<JSingleClientConnManagerClass, JSingleClientConnManager>)
end;
const
TJSingleClientConnManagerMISUSE_MESSAGE = 'Invalid use of SingleClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.';
implementation
end.
|
unit tools;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Figures, Graphics, GraphMath, LCLType,
LCLIntf, LCL, Scale, ExtCtrls, StdCtrls, Spin, Dialogs, Buttons;
type
TParam = class
procedure CreateObjects(Panel: TPanel; pos: Integer); virtual; abstract;
end;
TPenColorParam = class(Tparam)
procedure ChangePenColor(Sender: TObject);
procedure CreateObjects(Panel: TPanel; pos: Integer); override;
end;
TBrushColorParam = class(TParam)
procedure ChangeBrushColor(Sender: TObject);
procedure CreateObjects(Panel: TPanel; pos: Integer); override;
end;
TWidthParam = class(TParam)
procedure ChangeWidth(Sender: TObject);
procedure CreateObjects(Panel: TPanel; pos: Integer); override;
end;
TRoundingRadiusParamX = class(TParam)
procedure ChangeRoundX(Sender: TObject);
procedure CreateObjects(Panel: TPanel; pos: Integer); override;
end;
TRoundingRadiusParamY = class(TParam)
procedure ChangeRoundY(Sender: TObject);
procedure CreateObjects(Panel: TPanel; pos: Integer); override;
end;
TBrushStyleParam = class(TParam)
const BStyles: array [0..7] of TBrushStyle = (bsSolid, bsClear,
bsHorizontal, bsVertical, bsFDiagonal, bsBDiagonal, bsCross, bsDiagCross);
procedure ChangeBrushStyle(Sender: TObject);
procedure CreateObjects(Panel: TPanel; pos: Integer); override;
end;
TPenStyleParam = class(TParam)
procedure ChangePenStyle(Sender: TObject);
procedure CreateObjects(Panel: TPanel; pos: Integer); override;
const PStyles: array[0..5] of TPenStyle = (psSolid, psClear, psDot,
psDash, psDashDot, psDashDotDot);
end;
TFigureTool = class
Points: array of TFloatPoint;
Icons: string;
Param: array of TParam;
procedure MouseDown(AX: integer;AY: integer); virtual; abstract;
procedure MouseMove(X: integer;Y: integer); virtual; abstract;
procedure MouseUp(X: integer;Y: integer; ACanvas: TCanvas); virtual; abstract;
procedure ParamListCreate(); virtual;abstract;
procedure ParamsCreate(Panel: TPanel);
end;
TLineFigureTool = class(TFigureTool)
procedure ParamListCreate(); override;
procedure Mouseup(X: integer;Y: integer; ACanvas: TCanvas); override;
end;
TObjectFigureTool = class(TLineFigureTool)
procedure ParamListCreate(); override;
end;
TPolyLineTool = class(TLineFigureTool)
procedure MouseDown(X: integer;Y: integer); override;
procedure MouseMove(X: integer;Y: integer); override;
end;
TLineTool = class(TLineFigureTool)
procedure MouseDown(X: integer;Y: integer); override;
procedure MouseMove(X: integer;Y: integer); override;
end;
TEllipceTool = class(TObjectFigureTool)
procedure MouseDown(X: integer;Y: integer); override;
procedure MouseMove(X: integer;Y: integer); override;
end;
TRectangleTool = class(TObjectFigureTool)
procedure MouseDown(X: integer;Y: integer); override;
procedure MouseMove(X: integer;Y: integer); override;
end;
TPawTool = class(TFigureTool)
FirstPoint: TPoint;
procedure MouseDown(X: integer;Y: integer); override;
procedure MouseMove(X: integer;Y: integer); override;
procedure MouseUp(X: Integer; Y:Integer; ACanvas: TCanvas); override;
procedure ParamListCreate(); override;
end;
TMagnifierTool = class(TFigureTool)
procedure MouseDown(X: integer;Y: integer); override;
procedure MouseMove(X: integer;Y: integer); override;
procedure MouseUp(X: integer;Y: integer; ACanvas: TCanvas); override;
procedure ParamListCreate(); override;
end;
TRoundedRectangleTool = class(TObjectFigureTool)
procedure MouseDown(X: integer;Y: integer); override;
procedure MouseMove(X: integer;Y: integer); override;
procedure ParamListCreate(); override;
end;
TSelectTool = class(TFigureTool)
SelectedChangeSize: Boolean;
ChangeSizeIndex: Integer;
APoint: TPoint;
procedure MouseDown(X: integer;Y: integer); override;
procedure MouseMove(X: integer;Y: integer); override;
procedure MouseUp(X: integer;Y: integer; ACanvas: TCanvas); override;
procedure ParamListCreate(); override;
procedure SelectParamListCreate();
end;
var
Tool: array of TFigureTool;
APenColor, ABrushColor: TColor;
AWidth,ARadiusX,ARadiusY: integer;
APenStyle: TPenStyle;
ABrushStyle: TBrushStyle;
SelectedBStyleIndex, SelectedPStyleIndex: integer;
SelectedCreateParamFlag: Boolean;
SelectedChangeSize: Boolean;
SelectedFigureForChangingSize, SelectedPoint: integer;
SelectedFigure: TFigureTool;
Invalidate_: procedure of Object;
implementation
procedure TPenColorParam.CreateObjects(Panel: TPanel; pos: integer);
var
ColorLabel: TLabel;
PenColor: TColorButton;
begin
ColorLabel := TLabel.Create(Panel);
ColorLabel.Caption := 'Цвет карандаша';
ColorLabel.Top := pos;
ColorLabel.Parent:=Panel;
PenColor := TColorButton.Create(panel);
PenColor.Top := pos + 20;
PenColor.Parent := Panel;
PenColor.ButtonColor := APenColor;
PenColor.OnColorChanged := @ChangePenColor;
end;
procedure TPenColorParam.ChangePenColor(Sender: TObject);
var
i: Integer;
begin
APenColor := (Sender as TColorButton).ButtonColor;
for I:=0 to High(CurrentFigures) do
if CurrentFigures[i].Selected then (CurrentFigures[i] as TLineFigure).PenColor := APenColor;
Invalidate_;
CreateArrayOfActions();
end;
procedure TPenStyleParam.CreateObjects(Panel: TPanel; pos: Integer);
var
StyleLabel: TLabel;
PenStyle: TComboBox;
i: integer;
s: string;
begin
StyleLabel := TLabel.Create(Panel);
StyleLabel.Caption := 'Стиль линии';
StyleLabel.Top := pos;
StyleLabel.Parent:=Panel;
PenStyle := TComboBox.Create(panel);
for i:=0 to 5 do
begin
WriteStr(s, PStyles[i]);
PenStyle.Items.Add(s);
end;
PenStyle.Top := pos + 20;
PenStyle.Parent := Panel;
PenStyle.ReadOnly := True;
PenStyle.ItemIndex := SelectedPStyleIndex;
PenStyle.OnChange := @ChangePenStyle;
end;
procedure TPenStyleParam.ChangePenStyle(Sender: TObject);
var
i: integer;
begin
APenStyle := PStyles[(Sender as TComboBox).ItemIndex];
SelectedPStyleIndex := (Sender as TComboBox).ItemIndex;
for I:=0 to High(CurrentFigures) do
if CurrentFigures[i].Selected then (CurrentFigures[i] as TLineFigure).PenStyle := APenStyle;
Invalidate_;
CreateArrayOfActions();
end;
procedure TWidthParam.CreateObjects(Panel: TPanel; pos: Integer);
var
WidthLabel: TLabel;
WidthParam: TSpinEdit;
begin
WidthLabel := TLabel.Create(Panel);
WidthLabel.Caption := 'Ширина карандаша';
WidthLabel.Top := pos;
WidthLabel.Parent := Panel;
WidthParam := TSpinEdit.Create(Panel);
WidthParam.Top := pos + 20;
WidthParam.MinValue := 1;
WidthParam.Parent:= Panel;
WidthParam.Value := AWidth;
WidthParam.OnChange := @ChangeWidth;
end;
procedure TWidthParam.ChangeWidth(Sender: TObject);
var
i: integer;
begin
AWidth := (Sender as TSpinEdit).Value;
for I:=0 to High(CurrentFigures) do
if CurrentFigures[i].Selected then (CurrentFigures[i] as TLineFigure).Width := AWidth;
Invalidate_;
CreateArrayOfActions();
end;
procedure TBrushColorParam.CreateObjects(Panel: TPanel; pos: Integer);
var
ColorLabel: TLabel;
BrushColor: TColorButton;
begin
ColorLabel := TLabel.Create(Panel);
ColorLabel.Caption := 'Цвет заливки';
ColorLabel.Top := pos;
ColorLabel.Parent := Panel;
BrushColor := TColorButton.Create(Panel);
BrushColor.Top := pos + 20;
BrushColor.Parent := Panel;
BrushColor.ButtonColor := ABrushColor;
BrushColor.OnColorChanged := @ChangeBrushColor;
end;
procedure TBrushColorParam.ChangeBrushColor(Sender: TObject);
var
i: Integer;
begin
ABrushColor := (Sender as TColorButton).ButtonColor;
for I:=0 to High(CurrentFigures) do
if (CurrentFigures[i].Selected) and not (CurrentFigures[i].Index = 1)
then (CurrentFigures[i] as TObjectFigure).BrushColor := ABrushColor;
Invalidate_;
CreateArrayOfActions();
end;
procedure TBrushStyleParam.CreateObjects(Panel: TPanel; pos: Integer);
var
StyleLabel: TLabel;
BrushStyle: TComboBox;
i: Integer;
s: String;
begin
StyleLabel := TLabel.Create(Panel);
StyleLabel.Caption := 'Стиль заливки ';
StyleLabel.Top := pos;
StyleLabel.Parent:=Panel;
BrushStyle := TComboBox.Create(panel);
for i:=0 to 5 do
begin
WriteStr(s, BStyles[i]);
BrushStyle.Items.Add(s);
end;
BrushStyle.Top := pos + 20;
BrushStyle.Parent := Panel;
BrushStyle.ItemIndex := SelectedBStyleIndex;
BrushStyle.ReadOnly := True;
BrushStyle.OnChange := @ChangeBrushStyle;
end;
procedure TBrushStyleParam.ChangeBrushStyle(Sender: TObject);
var
i: integer;
begin
ABrushStyle := BStyles[(Sender as TComboBox).ItemIndex];
SelectedBStyleIndex := (Sender as TComboBox).ItemIndex;
for I:=0 to High(CurrentFigures) do
if (CurrentFigures[i].Selected) and not (CurrentFigures[i].Index = 1)
then (CurrentFigures[i] as TObjectFigure).BrushStyle := ABrushStyle;
Invalidate_;
CreateArrayOfActions();
end;
procedure TRoundingRadiusParamX.CreateObjects(Panel: TPanel; pos: Integer);
var
RoundingRadiusLabel: TLabel;
RoundingRadiusX: TSpinEdit;
begin
RoundingRadiusLabel := TLabel.Create(Panel);
RoundingRadiusLabel.Caption := 'Радиус округления X';
RoundingRadiusLabel.Top := pos;
RoundingRadiusLabel.Parent := Panel;
RoundingRadiusX := TSpinEdit.Create(Panel);
RoundingRadiusX.Top := pos + 20;
RoundingRadiusX.MinValue := 0;
RoundingRadiusX.OnChange := @ChangeRoundX;
RoundingRadiusX.Parent := Panel;
RoundingRadiusX.Value := ARadiusX;
end;
procedure TRoundingRadiusParamX.ChangeRoundX(Sender: TObject);
var
i: Integer;
begin
ARadiusX := (Sender as TSpinEdit).Value;
for I:=0 to High(CurrentFigures) do
if (CurrentFigures[i].Selected) and (CurrentFigures[i].Index = 3)
then (CurrentFigures[i] as TRoundedRectangle).RoundingRadiusX := ARadiusX;
Invalidate_;
CreateArrayOfActions();
end;
procedure TRoundingRadiusParamY.CreateObjects(Panel: TPanel; pos: Integer);
var
RoundingRadiusLabel: TLabel;
RoundingRadiusY: TSpinEdit;
begin
RoundingRadiusLabel := TLabel.Create(Panel);
RoundingRadiusLabel.Caption := 'Радиус округления Y';
RoundingRadiusLabel.Top := pos;
RoundingRadiusLabel.Parent :=Panel;
RoundingRadiusY := TSpinEdit.Create(Panel);
RoundingRadiusY.Top := pos + 20;
RoundingRadiusY.MinValue := 0;
RoundingRadiusY.Parent := Panel;
RoundingRadiusY.Value := ARadiusY;
RoundingRadiusY.OnChange := @ChangeRoundY;
end;
procedure TRoundingRadiusParamY.ChangeRoundY(Sender: TObject);
var
i: Integer;
begin
ARadiusY := (Sender as TSpinEdit).Value;
for I:=0 to High(CurrentFigures) do
if (CurrentFigures[i].Selected) and (CurrentFigures[i].Index = 3)
then (CurrentFigures[i] as TRoundedRectangle).RoundingRadiusY := ARadiusY;
Invalidate_;
CreateArrayOfActions();
end;
procedure TLineFigureTool.ParamListCreate();
begin
SetLength(Param, 0);
SetLength(Param, Length(Param) + 3);
Param[High(Param) - 2] := TPenColorParam.Create();
Param[High(Param) - 1] := TPenStyleParam.Create();
Param[High(Param)] := TWidthParam.Create();
end;
procedure TObjectFigureTool.ParamListCreate();
begin
Inherited;
SetLength(Param,Length(Param) + 2);
Param[High(Param) - 1]:= TBrushColorParam.Create();
Param[High(Param)]:= TBrushStyleParam.Create();
end;
procedure TRoundedRectangleTool.ParamListCreate();
begin
Inherited;
SetLength(Param,Length(Param) + 2);
Param[High(Param)-1] := TRoundingRadiusParamX.Create();
Param[High(Param)] := TRoundingRadiusParamY.Create();
end;
procedure TPawTool.ParamListCreate();
begin
end;
procedure TMagnifierTool.ParamListCreate();
begin
end;
procedure TSelectTool.ParamListCreate();
begin
end;
procedure TFigureTool.ParamsCreate(Panel: TPanel);
var
i, pos: Integer;
begin
ParamListCreate();
For i:=0 to high(Param) do begin
Param[i].CreateObjects(Panel, i * 60);
end;
end;
procedure RegisterTool(ATool: TFigureTool; S: string);
begin
Setlength(Tool, Length(Tool)+1);
Tool[high(Tool)] := ATool;
Tool[high(Tool)].Icons := s;
Atool.ParamListCreate();
end;
procedure TLineFigureTool.MouseUp(X: Integer;Y: Integer; ACanvas: TCanvas);
begin
CreateArrayOfActions();
end;
procedure TMagnifierTool.MouseUp(X: integer;Y: integer; ACanvas: TCanvas);
begin
RectZoom(AHeightPB,AWidthPB,(CurrentFigures[high(CurrentFigures)] as TLineFigure).Points[0],(CurrentFigures[high(CurrentFigures)] as TLineFigure).Points[1]);
SetLength(CurrentFigures, Length(CurrentFigures) - 1);
end;
procedure TMagnifierTool.MouseDown(X: integer;Y: integer);
var
AFigure: TRectangleMagnifier;
begin
SetLength(CurrentFigures, Length(CurrentFigures) + 1);
CurrentFigures[high(CurrentFigures)] := TRectangleMagnifier.Create();
AFigure := (CurrentFigures[high(CurrentFigures)] as TRectangleMagnifier);
SetLength(AFigure.Points, 2);
AFigure.Points[0] := ScreenToWorld(Point(X,Y));
end;
procedure TMagnifierTool.MouseMove(X: integer;Y: integer);
begin
(CurrentFigures[high(CurrentFigures)] as TLineFigure).Points[1] := ScreenToWorld(Point(X,Y));
end;
procedure TPawTool.MouseDown(X: integer;Y: integer);
begin
FirstPoint := Point(X,Y);
end;
procedure TPawTool.MouseMove(X: integer;Y: integer);
begin
offset.x += FirstPoint.X - X;
offset.y += FirstPoint.Y - Y;
FirstPoint:=Point(X,Y);
end;
procedure TPawTool.MouseUp(X: Integer; Y:Integer; ACanvas: TCanvas);
begin
end;
procedure TPolyLineTool.MouseDown(X: integer;Y: integer);
var
AFigure: TLineFigure;
begin
StopUndo;
Setlength(CurrentFigures, Length(CurrentFigures) + 1);
CurrentFigures[high(CurrentFigures)] := TPolyLine.Create();
AFigure := (CurrentFigures[high(CurrentFigures)] as TLineFigure);
SetLength((CurrentFigures[high(CurrentFigures)] as TLineFigure).Points, Length((CurrentFigures[high(CurrentFigures)] as TLineFigure).points) + 1);
(CurrentFigures[high(CurrentFigures)] as TLineFigure).Points[high((CurrentFigures[high(CurrentFigures)] as TLineFigure).Points)] := ScreenToWorld(Point(X,Y));
AFigure.PenColor := APenColor;
AFigure.Width := AWidth;
AFigure.PenStyle := APenStyle;
AFigure.Index := 1;
MaxMin(Point(X,Y));
end;
procedure TLineTool.MouseDown(X: integer;Y: integer);
var
AFigure: TLineFigure;
begin
StopUndo;
Setlength(CurrentFigures, length(CurrentFigures) + 1);
CurrentFigures[high(CurrentFigures)] := TLine.Create();
AFigure := (CurrentFigures[high(CurrentFigures)] as TLineFigure);
SetLength(AFigure.Points, 2);
AFigure.Points[0] := ScreenToWorld(Point(X,Y));
AFigure.Points[1] := ScreenToWorld(Point(X,Y));
AFigure.PenColor := APenColor;
AFigure.Width := AWidth;
AFigure.PenStyle := APenStyle;
AFigure.Index := 1;
MaxMin(Point(X,Y));
end;
procedure TRectangleTool.MouseDown(X: integer;Y: integer);
var
AFigure: TObjectFigure;
begin
StopUndo;
Setlength(CurrentFigures, Length(CurrentFigures) + 1);
CurrentFigures[high(CurrentFigures)] := TRectangle.Create();
AFigure := (CurrentFigures[high(CurrentFigures)] as TObjectFigure);
SetLength(AFigure.Points, 2);
AFigure.Points[0] := ScreenToWorld(Point(X,Y));
AFigure.Points[1] := ScreenToWorld(Point(X,Y));
AFigure.PenColor := APenColor;
AFigure.Width := AWidth;
AFigure.BrushColor := ABrushColor;
AFigure.PenStyle := APenStyle;
AFigure.BrushStyle := ABrushStyle;
AFigure.Index := 2;
MaxMin(Point(X,Y));
end;
procedure TRoundedRectangleTool.MouseDown(X: integer;Y: integer);
var
AFigure: TObjectFigure;
begin
StopUndo;
Setlength(CurrentFigures, Length(CurrentFigures) + 1);
CurrentFigures[high(CurrentFigures)] := TRoundedRectangle.Create();
AFigure := (CurrentFigures[high(CurrentFigures)] as TObjectFigure);
SetLength(AFigure.Points, 2);
AFigure.Points[0] := ScreenToWorld(Point(X,Y));
AFigure.Points[1] := ScreenToWorld(Point(X,Y));
AFigure.PenColor := APenColor;
AFigure.Width := AWidth;
AFigure.BrushColor := ABrushColor;
AFigure.RoundingRadiusX := ARadiusX;
AFigure.RoundingRadiusY:= ARadiusY;
AFigure.PenStyle := APenStyle;
AFigure.BrushStyle := ABrushStyle;
AFigure.Index := 3;
MaxMin(Point(X,Y));
end;
procedure TEllipceTool.MouseDown(X: integer;Y: integer);
var
AFigure: TObjectFigure;
begin
StopUndo;
SetLength(CurrentFigures, Length(CurrentFigures) + 1);
CurrentFigures[high(CurrentFigures)] := TEllipce.Create();
AFigure := (CurrentFigures[high(CurrentFigures)] as TObjectFigure);
SetLength(AFigure.Points, 2);
AFigure.Points[0] := ScreenToWorld(Point(X,Y));
AFigure.Points[1] := ScreenToWorld(Point(X,Y));
AFigure.PenColor := APenColor;
AFigure.Width := AWidth;
AFigure.BrushColor := ABrushColor;
AFigure.PenStyle := APenStyle;
AFigure.BrushStyle := ABrushStyle;
AFigure.Index := 2;
MaxMin(Point(X,Y));
end;
procedure TLineTool.MouseMove(X: integer;Y: integer);
begin
(CurrentFigures[high(CurrentFigures)] as TLineFigure).Points[1] := ScreenToWorld(Point(X,Y));
MaxMin(Point(X,Y));
end;
procedure TEllipceTool.MouseMove(X: integer;Y: integer);
begin
(CurrentFigures[high(CurrentFigures)] as TLineFigure).Points[1] := ScreenToWorld(Point(X,Y));
MaxMin(Point(X,Y));
end;
procedure TRectangleTool.MouseMove(X: integer;Y: integer);
begin
(CurrentFigures[high(CurrentFigures)] as TLineFigure).Points[1] := ScreenToWorld(Point(X,Y));
MaxMin(Point(X,Y));
end;
procedure TRoundedRectangleTool.MouseMove(X: integer;Y: integer);
begin
(CurrentFigures[high(CurrentFigures)] as TLineFigure).Points[1] := ScreenToWorld(Point(X,Y));
MaxMin(Point(X,Y));
end;
procedure TPolyLineTool.MouseMove(X: integer;Y: integer);
begin
SetLength((CurrentFigures[high(CurrentFigures)] as TLineFigure).points, length((CurrentFigures[high(CurrentFigures)] as TLineFigure).points) + 1);
(CurrentFigures[high(CurrentFigures)] as TLineFigure).Points[high((CurrentFigures[high(CurrentFigures)] as TLineFigure).Points)] := ScreenToWorld(Point(X,Y));
MaxMin(Point(X,Y));
end;
procedure TSelectTool.MouseDown(X: Integer; Y: Integer);
var
AFigure: TRectangleMagnifier;
width, i, j: Integer;
begin
for i:=0 to high(CurrentFigures) do begin
width := (CurrentFigures[i] as TLineFigure).Width;
if (x >= WorldToScreen(CurrentFigures[i].Points[0]).x - 15 - Width div 2) and
(y >= WorldToScreen(CurrentFigures[i].Points[0]).y - 15 - Width div 2) and
(x <= WorldToScreen(CurrentFigures[i].Points[0]).x - 5 - Width div 2) and
(y <= WorldToScreen(CurrentFigures[i].Points[0]).y - 5 - width div 2) and
(length(CurrentFigures[i].Points) = 2) then begin
SelectedFigureForChangingSize := i;
SelectedChangeSize := True;
ChangeSizeIndex := 1;
end;
if (x <= WorldToScreen(CurrentFigures[i].Points[1]).x + 15 - Width div 2) and
(y <= WorldToScreen(CurrentFigures[i].Points[1]).y + 15 - Width div 2) and
(x >= WorldToScreen(CurrentFigures[i].Points[1]).x + 5 - Width div 2) and
(y >= WorldToScreen(CurrentFigures[i].Points[1]).y + 5 - width div 2) and
(length(CurrentFigures[i].Points) = 2) then begin
SelectedFigureForChangingSize := i;
SelectedChangeSize := True;
ChangeSizeIndex := 2;
end;
if (x <= WorldToScreen(CurrentFigures[i].Points[0]).x + 15 - Width div 2) and
(y <= WorldToScreen(CurrentFigures[i].Points[1]).y - 15 - Width div 2) and
(x >= WorldToScreen(CurrentFigures[i].Points[0]).x + 5 - Width div 2) and
(y >= WorldToScreen(CurrentFigures[i].Points[1]).y - 5 - width div 2) and
(length(CurrentFigures[i].Points) = 2) then begin
SelectedFigureForChangingSize := i;
SelectedChangeSize := True;
ChangeSizeIndex := 3;
end;
if (x >= WorldToScreen(CurrentFigures[i].Points[1]).x - 15 - Width div 2) and
(y <= WorldToScreen(CurrentFigures[i].Points[0]).y + 15 - Width div 2) and
(x <= WorldToScreen(CurrentFigures[i].Points[1]).x - 5 - Width div 2) and
(y >= WorldToScreen(CurrentFigures[i].Points[0]).y + 5 - width div 2) and
(length(CurrentFigures[i].Points) = 2) then begin
SelectedFigureForChangingSize := i;
SelectedChangeSize := True;
ChangeSizeIndex := 4;
end;
if (x >= WorldToScreen(CurrentFigures[i].Points[0]).x + 15 - Width div 2) and
(y >= WorldToScreen(CurrentFigures[i].Points[0]).y + 15 - Width div 2) and
(x <= WorldToScreen(CurrentFigures[i].Points[0]).x + 5 - Width div 2) and
(y <= WorldToScreen(CurrentFigures[i].Points[0]).y + 5 - width div 2) and
(length(CurrentFigures[i].Points) = 2) then begin
SelectedFigureForChangingSize := i;
SelectedChangeSize := True;
ChangeSizeIndex := 1;
end;
if (x <= WorldToScreen(CurrentFigures[i].Points[1]).x - 15 - Width div 2) and
(y <= WorldToScreen(CurrentFigures[i].Points[1]).y - 15 - Width div 2) and
(x >= WorldToScreen(CurrentFigures[i].Points[1]).x - 5 - Width div 2) and
(y >= WorldToScreen(CurrentFigures[i].Points[1]).y - 5 - width div 2) and
(length(CurrentFigures[i].Points) = 2) then begin
SelectedFigureForChangingSize := i;
SelectedChangeSize := True;
ChangeSizeIndex := 2;
end;
if (x <= WorldToScreen(CurrentFigures[i].Points[2]).x - 15 - Width div 2) and
(y <= WorldToScreen(CurrentFigures[i].Points[1]).y + 15 - Width div 2) and
(x >= WorldToScreen(CurrentFigures[i].Points[2]).x - 5 - Width div 2) and
(y >= WorldToScreen(CurrentFigures[i].Points[1]).y + 5 - width div 2) and
(length(CurrentFigures[i].Points) = 2) then begin
SelectedFigureForChangingSize := i;
SelectedChangeSize := True;
ChangeSizeIndex := 3;
end;
if (x >= WorldToScreen(CurrentFigures[i].Points[1]).x + 15 - Width div 2) and
(y <= WorldToScreen(CurrentFigures[i].Points[2]).y - 15 - Width div 2) and
(x <= WorldToScreen(CurrentFigures[i].Points[1]).x + 5 - Width div 2) and
(y >= WorldToScreen(CurrentFigures[i].Points[2]).y - 5 - width div 2) and
(length(CurrentFigures[i].Points) = 2) then begin
SelectedFigureForChangingSize := i;
SelectedChangeSize := True;
ChangeSizeIndex := 4;
end;
if (length(CurrentFigures[i].Points) > 2) then begin
for j:=0 to high(CurrentFigures[i].Points) do begin
if (x >= WorldToScreen((CurrentFigures[i] as TPolyLine).Points[j]).x - 5 - Width div 2) and
(y >= WorldToScreen((CurrentFigures[i] as TPolyLine).Points[j]).y - 5 - Width div 2) and
(x <= WorldToScreen((CurrentFigures[i] as TPolyLine).Points[j]).x + 5 - Width div 2) and
(y <= WorldToScreen((CurrentFigures[i] as TPolyLine).Points[j]).y + 5 - width div 2)
then begin
SelectedFigureForChangingSize := i;
SelectedChangeSize := True;
SelectedPoint := J;
ChangeSizeIndex := 5;
End;
end;
end;
end;
if not SelectedChangeSize then begin
SetLength(CurrentFigures, Length(CurrentFigures) + 1);
CurrentFigures[high(CurrentFigures)] := TRectangleMagnifier.Create();
AFigure := (CurrentFigures[high(CurrentFigures)] as TRectangleMagnifier);
SetLength(AFigure.Points, 2);
AFigure.Points[0] := ScreenToWorld(Point(X,Y));
AFigure.Points[1] := ScreenToWorld(Point(X,Y));
SelectedCreateParamFlag := True;
end;
end;
procedure TSelectTool.MouseMove(X: Integer; Y: Integer);
var
i, j: Integer;
begin
if SelectedChangeSize then
begin
case ChangeSizeIndex of
1: begin
CurrentFigures[SelectedFigureForChangingSize].Points[0].X := ScreenToWorld(Point(X,Y)).X;
CurrentFigures[SelectedFigureForChangingSize].Points[0].Y := ScreenToWorld(Point(X,Y)).Y;
end;
2: begin
CurrentFigures[SelectedFigureForChangingSize].Points[1].X := ScreenToWorld(Point(X,Y)).X;
CurrentFigures[SelectedFigureForChangingSize].Points[1].Y := ScreenToWorld(Point(X,Y)).Y;
end;
3: begin
CurrentFigures[SelectedFigureForChangingSize].Points[1].X := ScreenToWorld(Point(X,Y)).X;
CurrentFigures[SelectedFigureForChangingSize].Points[2].Y := ScreenToWorld(Point(X,Y)).Y;
end;
4: begin
CurrentFigures[SelectedFigureForChangingSize].Points[2].X := ScreenToWorld(Point(X,Y)).X;
CurrentFigures[SelectedFigureForChangingSize].Points[1].Y := ScreenToWorld(Point(X,Y)).Y;
end;
5: begin
CurrentFigures[SelectedFigureForChangingSize].Points[SelectedPoint].X := ScreenToWorld(Point(X,Y)).X;
CurrentFigures[SelectedFigureForChangingSize].Points[SelectedPoint].Y := ScreenToWorld(Point(X,Y)).Y;
end;
end;
end;
if not SelectedChangeSize then (CurrentFigures[high(CurrentFigures)] as TLineFigure).Points[1] := ScreenToWorld(Point(X,Y));
end;
procedure TSelectTool.MouseUp(X: Integer; Y: Integer; ACanvas: TCanvas);
var
SelectRegion: HRGN;
i:integer;
ToolRegio: HRGN;
begin
if not SelectedChangeSize then begin
SelectRegion := CreateRectRgn((WorldToScreen((CurrentFigures[high(CurrentFigures)] as TRectangleMagnifier).Points[0]).x),
(WorldToScreen((CurrentFigures[high(CurrentFigures)] as TRectangleMagnifier).Points[0]).y),
(WorldToScreen((CurrentFigures[high(CurrentFigures)] as TRectangleMagnifier).Points[1]).x),
(WorldToScreen((CurrentFigures[high(CurrentFigures)] as TRectangleMagnifier).Points[1]).y));
with CurrentFigures[high(CurrentFigures)] do begin
for i := 0 to high(CurrentFigures)-1 do
begin
DeleteObject(CurrentFigures[i].Region);
CurrentFigures[i].SetRegion;
ToolRegio := CreateRectRgn(1,1,2,2);
if (CombineRgn(ToolRegio,CurrentFigures[i].Region,SelectRegion,RGN_AND)
<> NULLREGION) then
begin
if CurrentFigures[i].Selected = false then
CurrentFigures[i].Selected := true
else
CurrentFigures[i].Selected := false;
end;
DeleteObject(ToolRegio);
end;
end;
SetLength(CurrentFigures, Length(CurrentFigures) - 1);
SelectParamListCreate();
end;
SelectedChangeSize := false;
ChangeSizeIndex := 0;
SelectedFigureForChangingSize := -1;
SelectedPoint := -1;
end;
procedure TSelectTool.SelectParamListCreate();
var
i: Integer;
highIndex: Integer;
f1: TLineFigureTool;
f2: TObjectFigureTool;
f3: TRoundedRectangleTool;
begin
highIndex := 0;
for i := 0 to high(CurrentFigures) do
if CurrentFigures[i].Selected then
if (CurrentFigures[i].Index > highIndex) then highIndex := CurrentFigures[i].Index;
f1 := TLineFigureTool.Create();
f2 := TObjectFigureTool.Create();
f3 := TRoundedRectangleTool.Create();
case highIndex of
1: begin
f1.ParamListCreate();
SelectedFigure := f1;
end;
2: begin
f2.ParamListCreate();
SelectedFigure := f2;
end;
3: begin
f3.ParamListCreate();
SelectedFigure := f3;
end;
end;
end;
begin
Setlength(Tool, 8);
Tool[0] := TPolyLineTool.Create();
Tool[0].Icons := 'TPolyLine';
Tool[1] := TLineTool.Create();
Tool[1].Icons := 'TLine';
Tool[2] := TRectangleTool.Create();
Tool[2].Icons := 'TRectangle';
Tool[3] := TEllipceTool.Create();
Tool[3].Icons := 'TEllipce';
Tool[4] := TPawTool.Create();
Tool[4].Icons := 'TPaw';
Tool[5] := TMagnifierTool.Create();
Tool[5].Icons := 'TMagnifier';
Tool[6] := TRoundedRectangleTool.Create();
Tool[6].Icons := 'TRoundedRectangle';
Tool[7] := TSelectTool.Create();
Tool[7].Icons := 'TSelect';
end.
|
unit trtm_master_lng;
interface
const
TXT_STEP = 'Шаг ';
LABEL_GENERAL_SCREEN = 'Общая информация о проекте';
LABEL_GENERAL_AUTHOR = 'ФИО, кафедра';
LABEL_GENERAL_PROJECT = 'Название проекта';
HELP_GENERAL = 'Например, первое поле: ' +
#13#10 +
'Василий Пупкин, каф. РС' +
#13#10 +
'Второе поле:' +
#13#10 +
'Способы повышения качества разрабатываемого программного обеспечения'
;
LABEL_STATE_GENERAL = TXT_STEP + ' 1/10';
LABEL_SCREEN_TASK = 'Задача';
LABEL_TASK = 'Формулировка задачи';
HELP_TASK = 'Например:' +
#13#10 +
'Повысить качество ПО в десять раз'
;
LABEL_STATE_TASK = TXT_STEP + ' 2/10';
LABEL_SCREEN_AC = 'Административное противоречие';
LABEL_AC = 'Формулировка административного противоречия';
HELP_AC = 'Например:' +
#13#10 +
'Нужно повысить качество ПО в десять раз и нельзя'+
' повысить качество ПО в десять раз, так как нет' +
' критерия качества ПО'
;
LABEL_STATE_AC = TXT_STEP + ' 3/10';
LABEL_SCREEN_TC = 'Техническое противоречие';
LABEL_TC = 'Формулировка технического противоречия';
HELP_TC = 'Например:' +
#13#10 +
'Нужно посчитать количество ошибок ПО'+
' и нельзя посчитать количество ошибок' +
' так как нет универсального алгоритма поиска ошибок ПО'
;
LABEL_STATE_TC = TXT_STEP + ' 4/10';
LABEL_SCREEN_PHC = 'Физическое противоречие';
LABEL_PHC = 'Формулировка физического противоречия';
HELP_PHC = 'Например:' +
#13#10 +
'Нужно посчитать количество ошибок ПО'+
' и нельзя посчитать количество ошибок' +
' так как программное обеспечение является видом творчества и трудноформализуемо'
;
LABEL_STATE_PHC = TXT_STEP + ' 5/10';
LABEL_SCREEN_OBJ = 'Изменение системы';
LABEL_OBJ = 'Введите изменяемый параметр';
HELP_OBJ = 'Например:' +
#13#10 +
'Изменяем надёжность: '+
#13#10 +
' 27'
;
BTN_SHOW_OBJ = 'П&оказать список параметров';
LABEL_STATE_OBJ = TXT_STEP + ' 6/10';
LABEL_SCREEN_BAD = 'Анализ системы';
LABEL_BAD = 'Введите ухудшающеся параметры (через запятую)';
HELP_BAD = 'Например:' +
#13#10 +
'Появились потери времени, ухудшилась универсальность: '+
#13#10 +
'25, 35'
;
LABEL_STATE_BAD = TXT_STEP + ' 7/10';
LABEL_SCREEN_METH = 'Отбор способов';
LABEL_GOOD_METH = 'Подходящие методы';
LABEL_NOT_GOOD_METH = 'Неподходящие методы';
HELP_METH = 'Теперь, посмотрев предложенные способы решения задачи, нужно отобрать подходящие и неподходящие методы.' +
#13#10 +
'Например:'+
#13#10 +
'Подходящие методы:'+
#13#10 +
'10, 4'+
#13#10 +
'Неподходящие методы:' +
#13#10 +
'8, 35'
;
LABEL_STATE_METH = TXT_STEP + ' 8/10';
LABEL_SCREEN_DECIS = 'Решение';
LABEL_DECISION = 'Формулировка решения';
HELP_DECISION = 'Теперь, основываясь на предложенных способах разрешения противоречия, сформулируйте решения' +
#13#10 +
'Например:'+
#13#10 +
'Писать качественное ПО, основываясь на сертифицированном процессе разработки (ISO-9001-1)'
;
LABEL_STATE_DECIS = TXT_STEP + ' 9/10';
LABEL_SCREEN_REPORT = 'Сохранение результата';
HELP_REPORT = 'На данном этапе считаем, что задача решена, теперь можно распечатать отчёт, можно сохранить' +
' данные в файл, выбрав сохранение в другом формате, пожно получить html-страничку для публикации'+
'в сети Internet'
;
LABEL_STATE_REPORT = TXT_STEP + ' 10/10';
BTN_SHOW_SAVE = '&Сохранить файл';
BTN_SHOW_SAVE_AS = 'Сохр&анить файл как...';
BTN_SHOW_METH = 'П&оказать список методов';
MEMO_RESULT_ALL_METH = 'Предложенные методы:';
MEMO_RESULT_POP_METH = 'Повторяющиеся методы:';
MEMO_RESULT_NO_METH = 'Таковые отсутствуют';
MEMO_RESULT_ALL_MET_T = 'Расшифровки предложенных методов:';
MSG_NEED_INPUT_NUM = 'Следует ввести номер';
MSG_NEED_CHNG = MSG_NEED_INPUT_NUM + ' изменяемого свойства';
MSG_NEED_BADS = MSG_NEED_INPUT_NUM + 'а ухудшающихся свойств';
implementation
end.
|
//
// Pascal-Performance
// Version 1.0
// By: Vernieri
// 19 Octouber 2017
// GitHub: github.com/vernieri
// Last Update: 16 August 2018
//
program pascal_performance;
uses DateUtils, CRT, sysutils;
var vector: array[0..99999] of longint;
FromTime, ToTime: TDateTime;
DiffSeconds: real;
//x: longint;
Procedure Prime;
var p, e, n, primes: integer;
i: longint;
begin
primes := 0;
for i:=0 to 99999 do
begin
e := 0;
n := vector[i];
p := 2;
while p<n do
begin
if(n mod p <> 0)then
begin
e:=e+1;
end;
p:=p+1;
end;
if(e+2 = n)then
begin
primes:=primes+1;
end;
end;
writeln('Primes numbers found: ', primes);
end;
Procedure Randomico;
var
i : longint;
begin
writeln('Lets Generate some numbers: ');
for i:=0 to 99999 do
begin
//randomize;
vector[i] := (random(199999));
end;
for i:=0 to 99999 do
begin
writeln('Random Numbers: ', vector[i]);
end;
Prime;
end;
Begin
FromTime := Now;
//x := 64000;
// You can define a X and but in the Loops if u want
// example: for i:=0 to x do
Randomico;
ToTime := Now;
DiffSeconds := SecondsBetween(ToTime,FromTime);
writeln('Time in seconds: ', DiffSeconds);
End.
//fpc pascal-performance
|
unit LifeUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, LifeEngine;
const
BoardSize: TSize = (cx: 500; cy: 500);
type
TLifeForm = class(TForm)
PaintBox1: TPaintBox;
Button1: TButton;
CheckBox1: TCheckBox;
Button2: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Button3: TButton;
OpenDialog1: TOpenDialog;
HorzScrollBar: TScrollBar;
VertScrollBar: TScrollBar;
Button4: TButton;
procedure FormResize(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject);
procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure CheckBox1Click(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure VertScrollBarChange(Sender: TObject);
procedure HorzScrollBarChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
var
FLifeEngine: TLifeEngine;
FLifeBoard: TLifeBoard;
FGensPerSecond, FMaxGensPerSecond: Double;
FViewOffset, FViewSize: TPoint;
procedure LifeEngineUpdate(Sender: TObject);
public
{ Public declarations }
end;
var
LifeForm: TLifeForm;
implementation
uses System.Math, System.Threading, System.Diagnostics;
{$R *.dfm}
procedure TLifeForm.Button1Click(Sender: TObject);
begin
if not FLifeEngine.Running then
begin
FLifeEngine.Start;
Button1.Caption := '&Stop';
end else
begin
FLifeEngine.Stop;
Button1.Caption := '&Start';
end;
end;
procedure TLifeForm.Button2Click(Sender: TObject);
begin
if not FLifeEngine.Running then
begin
FLifeEngine.Clear;
FLifeBoard := FLifeEngine.LifeBoard;
FormResize(Sender);
PaintBox1.Invalidate;
end;
end;
procedure TLifeForm.Button3Click(Sender: TObject);
begin
if not FLifeEngine.Running and OpenDialog1.Execute then
begin
FLifeEngine.LoadPattern(OpenDialog1.FileName);
Hint := FLifeEngine.Description;
end;
end;
procedure TLifeForm.Button4Click(Sender: TObject);
begin
HorzScrollBar.Position := (Length(FLifeBoard) - FViewSize.X) div 2;
VertScrollBar.Position := (Length(FLifeBoard[0]) - FViewSize.Y) div 2;
end;
procedure TLifeForm.CheckBox1Click(Sender: TObject);
begin
if FLifeEngine <> nil then
FLifeEngine.Parallel := CheckBox1.Checked;
// UseOmniThread.Enabled := CheckBox1.Checked;
end;
procedure TLifeForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if FLifeEngine.Running then
Button1Click(Sender);
CanClose := not FLifeEngine.Running;
end;
procedure TLifeForm.FormCreate(Sender: TObject);
begin
FLifeEngine := TLifeEngine.Create(BoardSize);
FLifeEngine.OnUpdate := LifeEngineUpdate;
FLifeBoard := FLifeEngine.LifeBoard;
FLifeEngine.UpdateRate := 30;
DoubleBuffered := True;
{$IFDEF USE_OMNITHREAD}
UseOmniThread.Visible := True;
{$ENDIF}
end;
procedure TLifeForm.FormDestroy(Sender: TObject);
begin
FLifeEngine.Free;
end;
procedure TLifeForm.FormResize(Sender: TObject);
begin
FViewSize := Point((PaintBox1.Width - 10) div 10, (PaintBox1.Height - 10) div 10);
HorzScrollBar.Max := Length(FLifeBoard){ - FViewSize.X};
HorzScrollBar.PageSize := FViewSize.X;
VertScrollBar.Max := Length(FLifeBoard[0]){ - FViewSize.Y};
VertScrollBar.PageSize := FViewSize.Y;
end;
procedure TLifeForm.HorzScrollBarChange(Sender: TObject);
begin
FViewOffset.X := HorzScrollBar.Position;
PaintBox1.Invalidate;
end;
procedure TLifeForm.LifeEngineUpdate(Sender: TObject);
begin
FLifeBoard := FLifeEngine.LifeBoard;
FGensPerSecond := FLifeEngine.GensPerSecond;
FMaxGensPerSecond := FLifeEngine.MaxGensPerSecond;
Label2.Caption := Format('%f Generations Per Second', [FGensPerSecond]);
Label3.Caption := Format('%f Max Generations Per Second', [FMaxGensPerSecond]);
PaintBox1.Invalidate;
end;
procedure TLifeForm.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
Row, Column: Integer;
begin
if not FLifeEngine.Running and (Button = mbLeft) then
begin
Row := Y div 10;
Column := X div 10;
if (Row >= 0) and (Row <= FViewSize.Y) and
(Column >= 0) and (Column <= FViewSize.X) then
begin
FLifeBoard[FViewOffset.X + Column, FViewOffset.Y + Row] :=
FLifeBoard[FViewOffset.X + Column, FViewOffset.Y + Row] xor 1;
PaintBox1.Invalidate;
end;
Label1.Caption := Format('%d, %d', [FViewOffset.X + Column, FViewOffset.Y + Row]);
end;
end;
procedure TLifeForm.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
Label1.Caption := Format('%d, %d', [FViewOffset.X + X div 10, FViewOffset.Y + Y div 10]);
end;
procedure TLifeForm.PaintBox1Paint(Sender: TObject);
var
I, J: Integer;
Gens, Max: Integer;
Scale: Integer;
begin
PaintBox1.Canvas.Pen.Color := clGrayText;
if Length(FLifeBoard) > 0 then
for I := 0 to FViewSize.X - 1 do
for J := 0 to FViewSize.Y - 1 do
begin
if FLifeBoard[Min(FViewOffset.X + I, High(FLifeBoard)), Min(FViewOffset.Y + J, High(FLifeBoard[0]))] <> 0 then
with PaintBox1.Canvas do
begin
Brush.Color := clBlack;
Rectangle(Rect(I * 10, J * 10, I * 10 + 11, J * 10 + 11));
end else
with PaintBox1.Canvas do
begin
Brush.Color := clBtnFace;
Rectangle(Rect(I * 10, J * 10, I * 10 + 11, J * 10 + 11));
end;
end;
with PaintBox1.Canvas do
begin
// Calculate the scale for the graph
Scale := 1000000;
while Scale > 10 do
if FMaxGensPerSecond * 10 < Scale then
Scale := Scale div 10
else
Break;
Gens := MulDiv(Trunc(FGensPerSecond), PaintBox1.Height, Scale);
Max := MulDiv(Trunc(FMaxGensPerSecond), PaintBox1.Height, Scale);
Brush.Color := clGreen;
FillRect(Rect(PaintBox1.Width - 4, PaintBox1.Height - Gens, PaintBox1.Width, PaintBox1.Height));
Pen.Color := clRed;
MoveTo(PaintBox1.Width - 4, PaintBox1.Height - Max);
LineTo(PaintBox1.Width, PaintBox1.Height - Max);
end;
end;
procedure TLifeForm.VertScrollBarChange(Sender: TObject);
begin
FViewOffset.Y := VertScrollBar.Position;
PaintBox1.Invalidate;
end;
//procedure TLifeForm.TLifeThread.UpdateGeneration;
//begin
// FForm.FLifeBoard := FNewBoard;
// FOriginalBoard := nil;
// FNewBoard := nil;
// FForm.PaintBox1.Invalidate;
// FForm.Label2.Caption := Format('%f Generations Per Second', [FGensPerSecond]);
// FForm.FGensPerSecond := FGensPerSecond;
// FForm.FGraphCount := FForm.FGraphCount + FElapsed;
// if FForm.FGraphCount > TStopwatch.Frequency * 2 then
// begin
// FForm.FMaxGensPerSecond := 0.0;
// FForm.FGraphCount := 0;
// end;
// FForm.FMaxGensPerSecond := Max(FForm.FMaxGensPerSecond, FForm.FGensPerSecond);
// FForm.Label3.Caption := Format('%f Max Generations Per Second', [FForm.FMaxGensPerSecond]);
// FUpdating := False;
//end;
end.
|
unit Dabout;
{$MODE Delphi}
{-------------------------------------------------------------------}
{ Unit: Dabout.pas }
{ Project: EPANET2W }
{ Version: 2.0 }
{ Date: 5/31/00 }
{ 9/7/00 }
{ 12/29/00 }
{ 1/5/01 }
{ 3/1/01 }
{ 11/19/01 }
{ 12/8/01 }
{ 6/24/02 }
{ Author: L. Rossman }
{ }
{ Form unit containing the "About" dialog box for EPANET2W. }
{-------------------------------------------------------------------}
interface
uses {WinTypes, WinProcs,} Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, LResources;
type
{ TAboutBoxForm }
TAboutBoxForm = class(TForm)
Build1: TLabel;
Label10: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Panel1: TPanel;
Panel3: TPanel;
Panel4: TPanel;
ProductName: TLabel;
ProductName1: TLabel;
ProgramIcon1: TImage;
Version: TLabel;
Label3: TLabel;
Button1: TButton;
Build: TLabel;
Panel2: TPanel;
ProgramIcon: TImage;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
Label5: TLabel;
Version1: TLabel;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
//var
// AboutBoxForm: TAboutBoxForm;
implementation
procedure TAboutBoxForm.FormCreate(Sender: TObject);
begin
//Build.Caption := 'Build 2.00.11';
end;
procedure TAboutBoxForm.Button1Click(Sender: TObject);
begin
end;
initialization
{$i Dabout.lrs}
{$i Dabout.lrs}
end.
|
unit Win32.DXVA2API;
// Checked and Updated to SDK 10.0.17763.0
// (c) Translation to Pascal by Norbert Sonnleitner
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Windows, Classes, SysUtils, ActiveX, Direct3D9;
const
DXVA2_DLL = 'Dxva2.dll';
const
DXVA2_ModeMPEG2_MoComp: TGUID = '{e6a9f44b-61b0-4563-9ea4-63d2a3c6fe66}';
DXVA2_ModeMPEG2_IDCT: TGUID = '{bf22ad00-03ea-4690-8077-473346209b7e}';
DXVA2_ModeMPEG2_VLD: TGUID = '{ee27417f-5e28-4e65-beea-1d26b508adc9}';
DXVA2_ModeMPEG1_VLD: TGUID = '{6f3ec719-3735-42cc-8063-65cc3cb36616}';
DXVA2_ModeMPEG2and1_VLD: TGUID = '{86695f12-340e-4f04-9fd3-9253dd327460}';
DXVA2_ModeH264_A: TGUID = '{1b81be64-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_MoComp_NoFGT: TGUID = '{1b81be64-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_B: TGUID = '{1b81be65-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_MoComp_FGT: TGUID = '{1b81be65-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_C: TGUID = '{1b81be66-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_IDCT_NoFGT: TGUID = '{1b81be66-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_D: TGUID = '{1b81be67-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_IDCT_FGT: TGUID = '{1b81be67-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_E: TGUID = '{1b81be68-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_VLD_NoFGT: TGUID = '{1b81be68-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_F: TGUID = '{1b81be69-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_VLD_FGT: TGUID = '{1b81be69-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeH264_VLD_WithFMOASO_NoFGT: TGUID = '{d5f04ff9-3418-45d8-9561-32a76aae2ddd}';
DXVA2_ModeH264_VLD_Stereo_Progressive_NoFGT: TGUID = '{d79be8da-0cf1-4c81-b82a-69a4e236f43d}';
DXVA2_ModeH264_VLD_Stereo_NoFGT: TGUID = '{f9aaccbb-c2b6-4cfc-8779-5707b1760552}';
DXVA2_ModeH264_VLD_Multiview_NoFGT: TGUID = '{705b9d82-76cf-49d6-b7e6-ac8872db013c}';
DXVA2_ModeWMV8_A: TGUID = '{1b81be80-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeWMV8_PostProc: TGUID = '{1b81be80-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeWMV8_B: TGUID = '{1b81be81-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeWMV8_MoComp: TGUID = '{1b81be81-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeWMV9_A: TGUID = '{1b81be90-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeWMV9_PostProc: TGUID = '{1b81be90-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeWMV9_B: TGUID = '{1b81be91-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeWMV9_MoComp: TGUID = '{1b81be91-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeWMV9_C: TGUID = '{1b81be94-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeWMV9_IDCT: TGUID = '{1b81be94-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeVC1_A: TGUID = '{1b81beA0-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeVC1_PostProc: TGUID = '{1b81beA0-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeVC1_B: TGUID = '{1b81beA1-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeVC1_MoComp: TGUID = '{1b81beA1-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeVC1_C: TGUID = '{1b81beA2-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeVC1_IDCT: TGUID = '{1b81beA2-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeVC1_D: TGUID = '{1b81beA3-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeVC1_VLD: TGUID = '{1b81beA3-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_ModeVC1_D2010: TGUID = '{1b81beA4-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_NoEncrypt: TGUID = '{1b81beD0-a0c7-11d3-b984-00c04f2e73c5}';
DXVA2_VideoProcProgressiveDevice: TGUID = '{5a54a0c9-c7ec-4bd9-8ede-f3c75dc4393b}';
DXVA2_VideoProcBobDevice: TGUID = '{335aa36e-7884-43a4-9c91-7f87faf3e37e}';
DXVA2_VideoProcSoftwareDevice: TGUID = '{4553d47f-ee7e-4e3f-9475-dbf1376c4810}';
DXVA2_ModeMPEG4pt2_VLD_Simple: TGUID = '{efd64d74-c9e8-41d7-a5e9-e9b0e39fa319}';
DXVA2_ModeMPEG4pt2_VLD_AdvSimple_NoGMC: TGUID = '{ed418a9f-010d-4eda-9ae3-9a65358d8d2e}';
DXVA2_ModeMPEG4pt2_VLD_AdvSimple_GMC: TGUID = '{ab998b5b-4258-44a9-9feb-94e597a6baae}';
DXVA2_ModeHEVC_VLD_Main: TGUID = '{5b11d51b-2f4c-4452-bcc3-09f2a1160cc0}';
DXVA2_ModeHEVC_VLD_Main10: TGUID = '{107af0e0-ef1a-4d19-aba8-67a163073d13}';
DXVA2_ModeVP9_VLD_Profile0: TGUID = '{463707f8-a1d0-4585-876d-83aa6d60b89e}';
DXVA2_ModeVP9_VLD_10bit_Profile2: TGUID = '{a4c749ef-6ecf-48aa-8448-50a7a1165ff7}';
DXVA2_ModeVP8_VLD: TGUID = '{90b899ea-3a62-4705-88b3-8df04b2744e7}';
const
IID_IDirect3DDeviceManager9: TGUID = '{a0cade0f-06d5-4cf4-a1c7-f3cdd725aa75}';
IID_IDirectXVideoAccelerationService: TGUID = '{fc51a550-d5e7-11d9-af55-00054e43ff02}';
IID_IDirectXVideoDecoderService: TGUID = '{fc51a551-d5e7-11d9-af55-00054e43ff02}';
IID_IDirectXVideoProcessorService: TGUID = '{fc51a552-d5e7-11d9-af55-00054e43ff02}';
IID_IDirectXVideoDecoder: TGUID = '{f2b0810a-fd00-43c9-918c-df94e2d8ef7d}';
IID_IDirectXVideoProcessor: TGUID = '{8c3a39f0-916e-4690-804f-4c8001355d25}';
IID_IDirectXVideoMemoryConfiguration: TGUID = '{b7f916dd-db3b-49c1-84d7-e45ef99ec726}';
const
DXVA2_E_NOT_INITIALIZED = HRESULT($80041000);
DXVA2_E_NEW_VIDEO_DEVICE = HRESULT($80041001);
DXVA2_E_VIDEO_DEVICE_LOCKED = HRESULT($80041002);
DXVA2_E_NOT_AVAILABLE = HRESULT($80041003);
const
MAX_DEINTERLACE_SURFACES = 32;
MAX_SUBSTREAMS = 15;
DXVA2_DeinterlaceTech_Unknown = 0;
DXVA2_DeinterlaceTech_BOBLineReplicate = $1;
DXVA2_DeinterlaceTech_BOBVerticalStretch = $2;
DXVA2_DeinterlaceTech_BOBVerticalStretch4Tap = $4;
DXVA2_DeinterlaceTech_MedianFiltering = $8;
DXVA2_DeinterlaceTech_EdgeFiltering = $10;
DXVA2_DeinterlaceTech_FieldAdaptive = $20;
DXVA2_DeinterlaceTech_PixelAdaptive = $40;
DXVA2_DeinterlaceTech_MotionVectorSteered = $80;
DXVA2_DeinterlaceTech_InverseTelecine = $100;
DXVA2_DeinterlaceTech_Mask = $1ff;
DXVA2_NoiseFilterLumaLevel = 1;
DXVA2_NoiseFilterLumaThreshold = 2;
DXVA2_NoiseFilterLumaRadius = 3;
DXVA2_NoiseFilterChromaLevel = 4;
DXVA2_NoiseFilterChromaThreshold = 5;
DXVA2_NoiseFilterChromaRadius = 6;
DXVA2_DetailFilterLumaLevel = 7;
DXVA2_DetailFilterLumaThreshold = 8;
DXVA2_DetailFilterLumaRadius = 9;
DXVA2_DetailFilterChromaLevel = 10;
DXVA2_DetailFilterChromaThreshold = 11;
DXVA2_DetailFilterChromaRadius = 12;
DXVA2_NoiseFilterTech_Unsupported = 0;
DXVA2_NoiseFilterTech_Unknown = $1;
DXVA2_NoiseFilterTech_Median = $2;
DXVA2_NoiseFilterTech_Temporal = $4;
DXVA2_NoiseFilterTech_BlockNoise = $8;
DXVA2_NoiseFilterTech_MosquitoNoise = $10;
DXVA2_NoiseFilterTech_Mask = $1f;
DXVA2_DetailFilterTech_Unsupported = 0;
DXVA2_DetailFilterTech_Unknown = $1;
DXVA2_DetailFilterTech_Edge = $2;
DXVA2_DetailFilterTech_Sharpening = $4;
DXVA2_DetailFilterTech_Mask = $7;
DXVA2_ProcAmp_None = 0;
DXVA2_ProcAmp_Brightness = $1;
DXVA2_ProcAmp_Contrast = $2;
DXVA2_ProcAmp_Hue = $4;
DXVA2_ProcAmp_Saturation = $8;
DXVA2_ProcAmp_Mask = $f;
DXVA2_VideoProcess_None = 0;
DXVA2_VideoProcess_YUV2RGB = $1;
DXVA2_VideoProcess_StretchX = $2;
DXVA2_VideoProcess_StretchY = $4;
DXVA2_VideoProcess_AlphaBlend = $8;
DXVA2_VideoProcess_SubRects = $10;
DXVA2_VideoProcess_SubStreams = $20;
DXVA2_VideoProcess_SubStreamsExtended = $40;
DXVA2_VideoProcess_YUV2RGBExtended = $80;
DXVA2_VideoProcess_AlphaBlendExtended = $100;
DXVA2_VideoProcess_Constriction = $200;
DXVA2_VideoProcess_NoiseFilter = $400;
DXVA2_VideoProcess_DetailFilter = $800;
DXVA2_VideoProcess_PlanarAlpha = $1000;
DXVA2_VideoProcess_LinearScaling = $2000;
DXVA2_VideoProcess_GammaCompensated = $4000;
DXVA2_VideoProcess_MaintainsOriginalFieldData = $8000;
DXVA2_VideoProcess_Mask = $ffff;
DXVA2_VPDev_HardwareDevice = $1;
DXVA2_VPDev_EmulatedDXVA1 = $2;
DXVA2_VPDev_SoftwareDevice = $4;
DXVA2_VPDev_Mask = $7;
DXVA2_SampleData_RFF = $1;
DXVA2_SampleData_TFF = $2;
DXVA2_SampleData_RFF_TFF_Present = $4;
DXVA2_SampleData_Mask = $ffff;
DXVA2_DestData_RFF = $1;
DXVA2_DestData_TFF = $2;
DXVA2_DestData_RFF_TFF_Present = $4;
DXVA2_DestData_Mask = $ffff;
DXVA2_PictureParametersBufferType = 0;
DXVA2_MacroBlockControlBufferType = 1;
DXVA2_ResidualDifferenceBufferType = 2;
DXVA2_DeblockingControlBufferType = 3;
DXVA2_InverseQuantizationMatrixBufferType = 4;
DXVA2_SliceControlBufferType = 5;
DXVA2_BitStreamDateBufferType = 6;
DXVA2_MotionVectorBuffer = 7;
DXVA2_FilmGrainBuffer = 8;
DXVA2_VideoDecoderRenderTarget = 0;
DXVA2_VideoProcessorRenderTarget = 1;
DXVA2_VideoSoftwareRenderTarget = 2;
// DXVA2_DECODE_GET_DRIVER_HANDLE is an extension function that allows the
// driver to return a handle for the DXVA2 decode device that can be used to
// associate it with a IDirect3DCryptoSession9 interface. When this function
// is used:
// pPrivateInputData = NULL
// pPrivateInputDataSize = 0
// pPrivateOutputData = HANDLE*
// pPrivateOutputDataSize = sizeof(HANDLE)
DXVA2_DECODE_GET_DRIVER_HANDLE = $725;
// DXVA2_DECODE_SPECIFY_ENCRYPTED_BLOCKS is an extension function that that allows
// the decoder to specify which portions of the compressed buffers are encrypted.
// If this fucntion is not used to specify this information, it is assumed that
// the entire buffer is encrypted.
// pPrivateInputData = D3DENCRYPTED_BLOCK_INFO*;
// PrivateInputDataSize = sizeof(D3DENCRYPTED_BLOCK_INFO);
// pPrivateOutputData = NULL;
// PrivateOutputDataSize = 0;
DXVA2_DECODE_SPECIFY_ENCRYPTED_BLOCKS = $724;
type
// The following declarations within the 'if 0' block are dummy typedefs used to make
// the evr.idl file build. The actual definitions are contained in d3d9.h
{ IDirect3DDevice9 = DWORD; }
PIDirect3DDevice9 = ^IDirect3DDevice9;
{ IDirect3DSurface9 = DWORD; }
PIDirect3DSurface9 = ^IDirect3DSurface9;
TD3DFORMAT = DWORD;
PD3DFORMAT = ^TD3DFORMAT;
TD3DPOOL = DWORD;
PD3DPOOL = ^TD3DPOOL;
{$IFDEF FPC}
TDXVA2_ExtendedFormat = bitpacked record
case integer of
0: (
SampleFormat: 0..255;
VideoChromaSubsampling: 0..15;
NominalRange: 0..7;
VideoTransferMatrix: 0..7;
VideoLighting: 0..15;
VideoPrimaries: 0..31;
VideoTransferFunction: 0..31;
);
1: (Value: UINT);
end;
{$ELSE}
TDXVA2_ExtendedFormat = record
Value: UINT;
end;
{$ENDIF}
TDXVA2_SampleFormat = (
DXVA2_SampleFormatMask = $ff,
DXVA2_SampleUnknown = 0,
DXVA2_SampleProgressiveFrame = 2,
DXVA2_SampleFieldInterleavedEvenFirst = 3,
DXVA2_SampleFieldInterleavedOddFirst = 4,
DXVA2_SampleFieldSingleEven = 5,
DXVA2_SampleFieldSingleOdd = 6,
DXVA2_SampleSubStream = 7
);
TDXVA2_VideoChromaSubSampling = (
DXVA2_VideoChromaSubsamplingMask = $f,
DXVA2_VideoChromaSubsampling_Unknown = 0,
DXVA2_VideoChromaSubsampling_ProgressiveChroma = $8,
DXVA2_VideoChromaSubsampling_Horizontally_Cosited = $4,
DXVA2_VideoChromaSubsampling_Vertically_Cosited = $2,
DXVA2_VideoChromaSubsampling_Vertically_AlignedChromaPlanes = $1,
DXVA2_VideoChromaSubsampling_MPEG2 = Ord(DXVA2_VideoChromaSubsampling_Horizontally_Cosited) or Ord(
DXVA2_VideoChromaSubsampling_Vertically_AlignedChromaPlanes),
DXVA2_VideoChromaSubsampling_MPEG1 = DXVA2_VideoChromaSubsampling_Vertically_AlignedChromaPlanes,
DXVA2_VideoChromaSubsampling_DV_PAL = Ord(DXVA2_VideoChromaSubsampling_Horizontally_Cosited) or Ord(
DXVA2_VideoChromaSubsampling_Vertically_Cosited),
DXVA2_VideoChromaSubsampling_Cosited = Ord(DXVA2_VideoChromaSubsampling_Horizontally_Cosited) or Ord(
DXVA2_VideoChromaSubsampling_Vertically_Cosited) or Ord(DXVA2_VideoChromaSubsampling_Vertically_AlignedChromaPlanes)
);
TDXVA2_NominalRange = (
DXVA2_NominalRangeMask = $7,
DXVA2_NominalRange_Unknown = 0,
DXVA2_NominalRange_Normal = 1,
DXVA2_NominalRange_Wide = 2,
DXVA2_NominalRange_0_255 = 1,
DXVA2_NominalRange_16_235 = 2,
DXVA2_NominalRange_48_208 = 3
);
TDXVA2_VideoTransferMatrix = (
DXVA2_VideoTransferMatrixMask = $7,
DXVA2_VideoTransferMatrix_Unknown = 0,
DXVA2_VideoTransferMatrix_BT709 = 1,
DXVA2_VideoTransferMatrix_BT601 = 2,
DXVA2_VideoTransferMatrix_SMPTE240M = 3
);
TDXVA2_VideoLighting = (
DXVA2_VideoLightingMask = $f,
DXVA2_VideoLighting_Unknown = 0,
DXVA2_VideoLighting_bright = 1,
DXVA2_VideoLighting_office = 2,
DXVA2_VideoLighting_dim = 3,
DXVA2_VideoLighting_dark = 4
);
TDXVA2_VideoPrimaries = (
DXVA2_VideoPrimariesMask = $1f,
DXVA2_VideoPrimaries_Unknown = 0,
DXVA2_VideoPrimaries_reserved = 1,
DXVA2_VideoPrimaries_BT709 = 2,
DXVA2_VideoPrimaries_BT470_2_SysM = 3,
DXVA2_VideoPrimaries_BT470_2_SysBG = 4,
DXVA2_VideoPrimaries_SMPTE170M = 5,
DXVA2_VideoPrimaries_SMPTE240M = 6,
DXVA2_VideoPrimaries_EBU3213 = 7,
DXVA2_VideoPrimaries_SMPTE_C = 8
);
TDXVA2_VideoTransferFunction = (
DXVA2_VideoTransFuncMask = $1f,
DXVA2_VideoTransFunc_Unknown = 0,
DXVA2_VideoTransFunc_10 = 1,
DXVA2_VideoTransFunc_18 = 2,
DXVA2_VideoTransFunc_20 = 3,
DXVA2_VideoTransFunc_22 = 4,
DXVA2_VideoTransFunc_709 = 5,
DXVA2_VideoTransFunc_240M = 6,
DXVA2_VideoTransFunc_sRGB = 7,
DXVA2_VideoTransFunc_28 = 8,
// Deprecated labels - please use the ones in the DXVA2_VideoTransferFunction enum.
DXVA2_VideoTransFunc_22_709 = DXVA2_VideoTransFunc_709,
DXVA2_VideoTransFunc_22_240M = DXVA2_VideoTransFunc_240M,
DXVA2_VideoTransFunc_22_8bit_sRGB = DXVA2_VideoTransFunc_sRGB);
TDXVA2_Frequency = record
Numerator: UINT;
Denominator: UINT;
end;
TDXVA2_VideoDesc = record
SampleWidth: UINT;
SampleHeight: UINT;
SampleFormat: TDXVA2_ExtendedFormat;
Format: TD3DFORMAT;
InputSampleFreq: TDXVA2_Frequency;
OutputFrameFreq: TDXVA2_Frequency;
UABProtectionLevel: UINT;
Reserved: UINT;
end;
TDXVA2_VideoProcessorCaps = record
DeviceCaps: UINT;
InputPool: TD3DPOOL;
NumForwardRefSamples: UINT;
NumBackwardRefSamples: UINT;
Reserved: UINT;
DeinterlaceTechnology: UINT;
ProcAmpControlCaps: UINT;
VideoProcessorOperations: UINT;
NoiseFilterTechnology: UINT;
DetailFilterTechnology: UINT;
end;
TDXVA2_Fixed32 = record
case integer of
0: (Fraction: USHORT;
Value: SHORT
);
1: (ll: longint);
end;
PDXVA2_Fixed32 = ^TDXVA2_Fixed32;
TDXVA2_AYUVSample8 = record
Cr: UCHAR;
Cb: UCHAR;
Y: UCHAR;
Alpha: UCHAR;
end;
TDXVA2_AYUVSample16 = record
Cr: USHORT;
Cb: USHORT;
Y: USHORT;
Alpha: USHORT;
end;
TREFERENCE_TIME = LONGLONG;
TDXVA2_VideoSample = record
Start: TREFERENCE_TIME;
Ende: TREFERENCE_TIME;
SampleFormat: TDXVA2_ExtendedFormat;
SrcSurface: IDirect3DSurface9;
SrcRect: TRECT;
DstRect: TRECT;
Pal: array [0.. 15] of TDXVA2_AYUVSample8;
PlanarAlpha: TDXVA2_Fixed32;
SampleData: DWORD;
end;
PDXVA2_VideoSample = ^TDXVA2_VideoSample;
TDXVA2_ValueRange = record
MinValue: TDXVA2_Fixed32;
MaxValue: TDXVA2_Fixed32;
DefaultValue: TDXVA2_Fixed32;
StepSize: TDXVA2_Fixed32;
end;
TDXVA2_ProcAmpValues = record
Brightness: TDXVA2_Fixed32;
Contrast: TDXVA2_Fixed32;
Hue: TDXVA2_Fixed32;
Saturation: TDXVA2_Fixed32;
end;
TDXVA2_FilterValues = record
Level: TDXVA2_Fixed32;
Threshold: TDXVA2_Fixed32;
Radius: TDXVA2_Fixed32;
end;
TDXVA2_VideoProcessBltParams = record
TargetFrame: TREFERENCE_TIME;
TargetRect: TRECT;
ConstrictionSize: TSIZE;
StreamingFlags: UINT;
BackgroundColor: TDXVA2_AYUVSample16;
DestFormat: TDXVA2_ExtendedFormat;
ProcAmpValues: TDXVA2_ProcAmpValues;
Alpha: TDXVA2_Fixed32;
NoiseFilterLuma: TDXVA2_FilterValues;
NoiseFilterChroma: TDXVA2_FilterValues;
DetailFilterLuma: TDXVA2_FilterValues;
DetailFilterChroma: TDXVA2_FilterValues;
DestData: DWORD;
end;
TDXVA2_ConfigPictureDecode = record
guidConfigBitstreamEncryption: TGUID;
guidConfigMBcontrolEncryption: TGUID;
guidConfigResidDiffEncryption: TGUID;
ConfigBitstreamRaw: UINT;
ConfigMBcontrolRasterOrder: UINT;
ConfigResidDiffHost: UINT;
ConfigSpatialResid8: UINT;
ConfigResid8Subtraction: UINT;
ConfigSpatialHost8or9Clipping: UINT;
ConfigSpatialResidInterleaved: UINT;
ConfigIntraResidUnsigned: UINT;
ConfigResidDiffAccelerator: UINT;
ConfigHostInverseScan: UINT;
ConfigSpecificIDCT: UINT;
Config4GroupedCoefs: UINT;
ConfigMinRenderTargetBuffCount: USHORT;
ConfigDecoderSpecific: USHORT;
end;
PDXVA2_ConfigPictureDecode = ^TDXVA2_ConfigPictureDecode;
TDXVA2_DecodeBufferDesc = record
CompressedBufferType: DWORD;
BufferIndex: UINT;
DataOffset: UINT;
DataSize: UINT;
FirstMBaddress: UINT;
NumMBsInBuffer: UINT;
Width: UINT;
Height: UINT;
Stride: UINT;
ReservedBits: UINT;
pvPVPState: Pointer;
end;
PDXVA2_DecodeBufferDesc = ^TDXVA2_DecodeBufferDesc;
// The value in pvPVPState depends on the type of crypo used. For
// D3DCRYPTOTYPE_AES128_CTR, pvPState points to the following structure:
TDXVA2_AES_CTR_IV = record
IV: UINT64;
Count: UINT64;
end;
TDXVA2_DecodeExtensionData = record
_Function: UINT;
pPrivateInputData: Pointer;
PrivateInputDataSize: UINT;
pPrivateOutputData: Pointer;
PrivateOutputDataSize: UINT;
end;
PDXVA2_DecodeExtensionData = ^TDXVA2_DecodeExtensionData;
TDXVA2_DecodeExecuteParams = record
NumCompBuffers: UINT;
pCompressedBuffers: PDXVA2_DecodeBufferDesc;
pExtensionData: PDXVA2_DecodeExtensionData;
end;
IDirect3DDeviceManager9 = interface(IUnknown)
['{a0cade0f-06d5-4cf4-a1c7-f3cdd725aa75}']
function ResetDevice(pDevice: IDirect3DDevice9; resetToken: UINT): HResult; stdcall;
function OpenDeviceHandle(out phDevice: THANDLE): HResult; stdcall;
function CloseDeviceHandle(hDevice: THANDLE): HResult; stdcall;
function TestDevice(hDevice: THANDLE): HResult; stdcall;
function LockDevice(hDevice: THANDLE; out ppDevice: IDirect3DDevice9; fBlock: boolean): HResult; stdcall;
function UnlockDevice(hDevice: THANDLE; fSaveState: boolean): HResult; stdcall;
function GetVideoService(hDevice: THANDLE; const riid: TGUID; out ppService): HResult; stdcall;
end;
IDirectXVideoAccelerationService = interface(IUnknown)
['{fc51a550-d5e7-11d9-af55-00054e43ff02}']
function CreateSurface(Width: UINT; Height: UINT; BackBuffers: UINT; Format: TD3DFORMAT; Pool: TD3DPOOL;
Usage: DWORD; DxvaType: DWORD; out ppSurface: IDirect3DSurface9; pSharedHandle: PHANDLE): HResult; stdcall;
end;
IDirectXVideoDecoder = interface;
IDirectXVideoProcessor = interface;
IDirectXVideoDecoderService = interface(IDirectXVideoAccelerationService)
['{fc51a551-d5e7-11d9-af55-00054e43ff02}']
function GetDecoderDeviceGuids(out pCount: UINT; out pGuids {arraysize pCount}: PGUID): HResult; stdcall;
function GetDecoderRenderTargets(const Guid: TGUID; out pCount: UINT; out pFormats {arraysize pCount}: PD3DFORMAT): HResult; stdcall;
function GetDecoderConfigurations(const Guid: TGUID; const pVideoDesc: TDXVA2_VideoDesc; pReserved: Pointer;
out pCount: UINT; out ppConfigs{arraysize pCount}: PDXVA2_ConfigPictureDecode): HResult; stdcall;
function CreateVideoDecoder(const Guid: TGUID; const pVideoDesc: TDXVA2_VideoDesc; const pConfig: TDXVA2_ConfigPictureDecode;
ppDecoderRenderTargets{arraysize NumRenderTargets}: PIDirect3DSurface9; NumRenderTargets: UINT; out ppDecode: IDirectXVideoDecoder): HResult; stdcall;
end;
IDirectXVideoProcessorService = interface(IDirectXVideoAccelerationService)
['{fc51a552-d5e7-11d9-af55-00054e43ff02}']
function RegisterVideoProcessorSoftwareDevice(pCallbacks: pointer): HResult; stdcall;
function GetVideoProcessorDeviceGuids(const pVideoDesc: TDXVA2_VideoDesc; out pCount: UINT; out pGuids{arraysize pCount}: PGUID): HResult; stdcall;
function GetVideoProcessorRenderTargets(const VideoProcDeviceGuid: TGUID; const pVideoDesc: TDXVA2_VideoDesc;
out pCount: UINT; out pFormats{arraysize pCount}: PD3DFORMAT): HResult; stdcall;
function GetVideoProcessorSubStreamFormats(const VideoProcDeviceGuid: TGUID; const pVideoDesc: TDXVA2_VideoDesc;
RenderTargetFormat: TD3DFORMAT; out pCount: UINT; out pFormats: PD3DFORMAT): HResult; stdcall;
function GetVideoProcessorCaps(const VideoProcDeviceGuid: TGUID; const pVideoDesc: TDXVA2_VideoDesc;
RenderTargetFormat: TD3DFORMAT; out pCaps: TDXVA2_VideoProcessorCaps): HResult; stdcall;
function GetProcAmpRange(const VideoProcDeviceGuid: TGUID; const pVideoDesc: TDXVA2_VideoDesc;
RenderTargetFormat: TD3DFORMAT; ProcAmpCap: UINT; out pRange: TDXVA2_ValueRange): HResult; stdcall;
function GetFilterPropertyRange(const VideoProcDeviceGuid: TGUID; const pVideoDesc: TDXVA2_VideoDesc;
RenderTargetFormat: TD3DFORMAT; FilterSetting: UINT; out pRange: TDXVA2_ValueRange): HResult; stdcall;
function CreateVideoProcessor(const VideoProcDeviceGuid: TGUID; const pVideoDesc: TDXVA2_VideoDesc;
RenderTargetFormat: TD3DFORMAT; MaxNumSubStreams: UINT; out ppVidProcess: IDirectXVideoProcessor): HResult; stdcall;
end;
IDirectXVideoDecoder = interface(IUnknown)
['{f2b0810a-fd00-43c9-918c-df94e2d8ef7d}']
function GetVideoDecoderService(out ppService: IDirectXVideoDecoderService): HResult; stdcall;
function GetCreationParameters(out pDeviceGuid: TGUID; out pVideoDesc: TDXVA2_VideoDesc;
out pConfig: TDXVA2_ConfigPictureDecode; out pDecoderRenderTargets{arraysize pNumSurfaces}: PIDirect3DSurface9;
out pNumSurfaces: UINT): HResult; stdcall;
function GetBuffer(BufferType: UINT; out ppBuffer:pointer; out pBufferSize: UINT): HResult; stdcall;
function ReleaseBuffer(BufferType: UINT): HResult; stdcall;
function BeginFrame(pRenderTarget: IDirect3DSurface9; pvPVPData: Pointer): HResult; stdcall;
function EndFrame(var pHandleComplete: THANDLE): HResult; stdcall;
function Execute(const pExecuteParams: TDXVA2_DecodeExecuteParams): HResult; stdcall;
end;
IDirectXVideoProcessor = interface(IUnknown)
['{8c3a39f0-916e-4690-804f-4c8001355d25}']
function GetVideoProcessorService(out ppService: IDirectXVideoProcessorService): HResult; stdcall;
function GetCreationParameters(out pDeviceGuid: TGUID; out pVideoDesc: TDXVA2_VideoDesc;
out pRenderTargetFormat: TD3DFORMAT; out pMaxNumSubStreams: UINT): HResult; stdcall;
function GetVideoProcessorCaps(out pCaps: TDXVA2_VideoProcessorCaps): HResult; stdcall;
function GetProcAmpRange(ProcAmpCap: UINT; out pRange: TDXVA2_ValueRange): HResult; stdcall;
function GetFilterPropertyRange(FilterSetting: UINT; out pRange: TDXVA2_ValueRange): HResult; stdcall;
function VideoProcessBlt(pRenderTarget: IDirect3DSurface9; const pBltParams: TDXVA2_VideoProcessBltParams;
const pSamples{arraysize NumSamples}: PDXVA2_VideoSample; NumSamples: UINT; var pHandleComplete: THANDLE): HResult; stdcall;
end;
TDXVA2_SurfaceType = (
DXVA2_SurfaceType_DecoderRenderTarget = 0,
DXVA2_SurfaceType_ProcessorRenderTarget = 1,
DXVA2_SurfaceType_D3DRenderTargetTexture = 2
);
IDirectXVideoMemoryConfiguration = interface(IUnknown)
['{b7f916dd-db3b-49c1-84d7-e45ef99ec726}']
function GetAvailableSurfaceTypeByIndex(dwTypeIndex: DWORD; out pdwType: TDXVA2_SurfaceType): HResult; stdcall;
function SetSurfaceType(dwType: TDXVA2_SurfaceType): HResult; stdcall;
end;
function DXVA2CreateDirect3DDeviceManager9(out pResetToken: UINT; out ppDeviceManager: IDirect3DDeviceManager9): HResult;
stdcall; external DXVA2_DLL;
function DXVA2CreateVideoService(pDD: IDirect3DDevice9; const riid: TGUID; out ppService): HResult;
stdcall; external DXVA2_DLL;
function DXVA2FloatToFixed(const _float: single): TDXVA2_Fixed32; inline;
function DXVA2FixedToFloat(const _fixed: TDXVA2_Fixed32): single; inline;
function DXVA2_Fixed32TransparentAlpha(): TDXVA2_Fixed32; inline;
function DXVA2_Fixed32OpaqueAlpha(): TDXVA2_Fixed32; inline;
implementation
function DXVA2FloatToFixed(const _float: single): TDXVA2_Fixed32; inline;
var
lTemp: longint;
begin
lTemp := Trunc(_float * $10000);
Result.Fraction := LOWORD(lTemp);
Result.Value := HIWORD(lTemp);
end;
function DXVA2FixedToFloat(const _fixed: TDXVA2_Fixed32): single; inline;
begin
Result := (_fixed.Value) + (_fixed.Fraction / $10000);
end;
function DXVA2_Fixed32TransparentAlpha(): TDXVA2_Fixed32; inline;
begin
Result.Fraction := 0;
Result.Value := 0;
end;
function DXVA2_Fixed32OpaqueAlpha(): TDXVA2_Fixed32; inline;
begin
Result.Fraction := 0;
Result.Value := 1;
end;
end.
|
unit MagentoInvoker;
interface
uses
Magento.Interfaces, System.Classes;
type
TMagentoInvoker = class (TInterfacedObject, iInvoker)
private
// FList : TList<iCommand>;
public
constructor Create;
destructor Destroy; override;
class function New : iInvoker;
function Add(value : iCommand) : iInvoker;
function Execute : iInvoker;
end;
implementation
{ TMagentoInvoker }
function TMagentoInvoker.Add(value: iCommand): iInvoker;
begin
Result := Self;
// FList.Add(value);
end;
constructor TMagentoInvoker.Create;
begin
// FList := TList<iCommand>.Create;
end;
destructor TMagentoInvoker.Destroy;
begin
// FList.DisposeOf;
inherited;
end;
function TMagentoInvoker.Execute: iInvoker;
var
Command : iCommand;
begin
Result := Self;
// for Command in FList do
// begin
// TThread.CreateAnonymousThread(
// procedure
// begin
// Command.Execute;
// end;
// );
// end;
end;
class function TMagentoInvoker.New: iInvoker;
begin
Result := self.Create;
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 170637
////////////////////////////////////////////////////////////////////////////////
unit android.graphics.Paint_Align;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JPaint_Align = interface;
JPaint_AlignClass = interface(JObjectClass)
['{AF7BCC6F-5A1D-4A12-AF3D-0FD1924708CC}']
function _GetCENTER : JPaint_Align; cdecl; // A: $4019
function _GetLEFT : JPaint_Align; cdecl; // A: $4019
function _GetRIGHT : JPaint_Align; cdecl; // A: $4019
function valueOf(&name : JString) : JPaint_Align; cdecl; // (Ljava/lang/String;)Landroid/graphics/Paint$Align; A: $9
function values : TJavaArray<JPaint_Align>; cdecl; // ()[Landroid/graphics/Paint$Align; A: $9
property CENTER : JPaint_Align read _GetCENTER; // Landroid/graphics/Paint$Align; A: $4019
property LEFT : JPaint_Align read _GetLEFT; // Landroid/graphics/Paint$Align; A: $4019
property RIGHT : JPaint_Align read _GetRIGHT; // Landroid/graphics/Paint$Align; A: $4019
end;
[JavaSignature('android/graphics/Paint_Align')]
JPaint_Align = interface(JObject)
['{1F78BE58-DD7F-4BFF-A096-2EE2894CDCDF}']
end;
TJPaint_Align = class(TJavaGenericImport<JPaint_AlignClass, JPaint_Align>)
end;
implementation
end.
|
unit EST0001L.View;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, LocalizarBase.View, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver, cxControls, cxContainer,
cxEdit, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator,
cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxTextEdit,
dxGDIPlusClasses, Vcl.ExtCtrls, cxLabel, Vcl.StdCtrls, cxButtons, ormbr.container.DataSet.interfaces,
TESTPRODUTO.Entidade.Model, ormbr.container.fdmemtable, Base.View.Interf,
dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinBlack, dxSkinDarkRoom, dxSkinSilver;
type
TFEST0001LView = class(TFLocalizarView, IBaseLocalizarView)
BtSalvar: TcxButton;
FdDadosCODIGO: TStringField;
FdDadosIDPRODUTO: TIntegerField;
FdDadosCODIGO_SINAPI: TStringField;
FdDadosDESCRICAO: TStringField;
FdDadosUNIDMEDIDA: TStringField;
FdDadosPRMEDIO: TCurrencyField;
FdDadosPRMEDIO_SINAPI: TCurrencyField;
FdDadosORIGEM_PRECO: TStringField;
VwDadosIDPRODUTO: TcxGridDBColumn;
VwDadosDESCRICAO: TcxGridDBColumn;
VwDadosCODIGO_SINAPI: TcxGridDBColumn;
VwDadosUNIDMEDIDA: TcxGridDBColumn;
StGrid: TcxStyleRepository;
StHeader: TcxStyle;
StBackground: TcxStyle;
StContentOdd: TcxStyle;
StContentEven: TcxStyle;
StSelection: TcxStyle;
StInactive: TcxStyle;
procedure FormCreate(Sender: TObject);
procedure BtSalvarClick(Sender: TObject);
procedure TePesquisaPropertiesChange(Sender: TObject);
private
FCampoOrdem: string;
FContainer: IContainerDataSet<TTESTPRODUTO>;
FCodigoSelecionado: string;
procedure filtrarRegistros;
public
{ Public declarations }
class function New: IBaseLocalizarView;
procedure listarRegistros;
function exibir: string;
end;
var
FEST0001LView: TFEST0001LView;
implementation
{$R *.dfm}
procedure TFEST0001LView.BtSalvarClick(Sender: TObject);
begin
inherited;
FCodigoSelecionado := FdDadosCODIGO.AsString;
Close;
end;
function TFEST0001LView.exibir: string;
begin
listarRegistros;
ShowModal;
Result := FCodigoSelecionado;
end;
procedure TFEST0001LView.filtrarRegistros;
begin
FdDados.Filtered := false;
if not(TePesquisa.Text = EmptyStr) then
begin
FdDados.Filter := UpperCase(FCampoOrdem) + ' Like ''%' +
AnsiUpperCase(TePesquisa.Text) + '%''';
FdDados.Filtered := True;
end;
end;
procedure TFEST0001LView.FormCreate(Sender: TObject);
begin
inherited;
FContainer := TContainerFDMemTable<TTESTPRODUTO>.Create(FConexao, FdDados);
FCampoOrdem := 'DESCRICAO';
Self.Width := Screen.Width - 300;
Self.Height := Screen.Height - 300;
end;
procedure TFEST0001LView.listarRegistros;
begin
FContainer.OpenWhere('', FCampoOrdem);
end;
class function TFEST0001LView.New: IBaseLocalizarView;
begin
Result := Self.Create(nil);
end;
procedure TFEST0001LView.TePesquisaPropertiesChange(Sender: TObject);
begin
inherited;
filtrarRegistros;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
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 Kitto.Ext.Start;
interface
type
TKExtStart = class
private
class var FIsService: Boolean;
public
class procedure Start;
class property IsService: Boolean read FIsService;
end;
implementation
uses
SysUtils, Forms, Classes, SvcMgr, ShlObj, Themes, Styles,
EF.SysUtils, EF.Logger, EF.Localization, EF.Tree,
Kitto.Config,
Kitto.Ext.MainFormUnit, Kitto.Ext.Service;
{ TKExtStart }
class procedure TKExtStart.Start;
procedure Configure;
var
LConfig: TKConfig;
LLogNode: TEFNode;
begin
LConfig := TKConfig.Create;
try
LLogNode := LConfig.Config.FindNode('Log');
TEFLogger.Instance.Configure(LLogNode, LConfig.MacroExpansionEngine);
TEFLogger.Instance.Log(Format('Using configuration: %s',[LConfig.BaseConfigFileName]));
finally
FreeAndNil(LConfig);
end;
end;
begin
FIsService := not FindCmdLineSwitch('a');
if FIsService then
begin
Configure;
TEFLogger.Instance.Log('Starting as service.');
if not SvcMgr.Application.DelayInitialize or SvcMgr.Application.Installing then
SvcMgr.Application.Initialize;
SvcMgr.Application.CreateForm(TKExtService, KExtService);
SvcMgr.Application.Run;
end
else
begin
if FindCmdLineSwitch('c') then
TKConfig.BaseConfigFileName := ParamStr(3);
Configure;
TEFLogger.Instance.Log('Starting as application.');
Forms.Application.Initialize;
Forms.Application.CreateForm(TKExtMainForm, KExtMainForm);
Forms.Application.Run;
end;
end;
end.
|
unit ProdutoOperacaoDuplicar.Controller;
interface
uses Produto.Controller.interf, Produto.Model.interf,
TESTPRODUTO.Entidade.Model, System.SysUtils;
type
TProdutosOperacoesDuplicarController = class(TInterfacedObject,
IProdutoOperacaoDuplicarController)
private
FProdutoModel: IProdutoModel;
FRegistro: TTESTPRODUTO;
FCodigoSinapi: string;
FDescricao: string;
FUnidMedida: string;
FOrigemPreco: string;
FPrMedio: Currency;
FPrMedioSinap: Currency;
public
constructor Create;
destructor Destroy; override;
class function New: IProdutoOperacaoDuplicarController;
function produtoModel(AValue: IProdutoModel): IProdutoOperacaoDuplicarController;
function produtoSelecionado(AValue: TTESTPRODUTO): IProdutoOperacaoDuplicarController;
function codigoSinapi(AValue: string): IProdutoOperacaoDuplicarController;
function descricao(AValue: string): IProdutoOperacaoDuplicarController;
function unidMedida(AValue: string): IProdutoOperacaoDuplicarController;
function origemPreco(AValue: string): IProdutoOperacaoDuplicarController;
function prMedio(AValue: Currency): IProdutoOperacaoDuplicarController; overload;
function prMedio(AValue: string): IProdutoOperacaoDuplicarController; overload;
function prMedioSinapi(AValue: Currency): IProdutoOperacaoDuplicarController; overload;
function prMedioSinapi(AValue: string): IProdutoOperacaoDuplicarController; overload;
procedure finalizar;
end;
implementation
{ TProdutosOperacoesDuplicarController }
function TProdutosOperacoesDuplicarController.codigoSinapi(AValue: string)
: IProdutoOperacaoDuplicarController;
begin
Result := Self;
FCodigoSinapi := AValue;
end;
constructor TProdutosOperacoesDuplicarController.Create;
begin
end;
function TProdutosOperacoesDuplicarController.descricao(AValue: string)
: IProdutoOperacaoDuplicarController;
begin
Result := Self;
FDescricao := AValue;
end;
destructor TProdutosOperacoesDuplicarController.Destroy;
begin
inherited;
end;
procedure TProdutosOperacoesDuplicarController.finalizar;
begin
FProdutoModel.Entidade(TTESTPRODUTO.Create);
FProdutoModel.Entidade.CODIGO_SINAPI := FCodigoSinapi;
FProdutoModel.Entidade.DESCRICAO := FDescricao;
FProdutoModel.Entidade.UNIDMEDIDA := FUnidMedida;
FProdutoModel.Entidade.ORIGEM_PRECO := FOrigemPreco;
FProdutoModel.Entidade.PRMEDIO := FPrMedio;
FProdutoModel.Entidade.PRMEDIO_SINAPI := FPrMedioSinap;
FProdutoModel.DAO.Insert(FProdutoModel.Entidade);
end;
class function TProdutosOperacoesDuplicarController.New
: IProdutoOperacaoDuplicarController;
begin
Result := Self.Create;
end;
function TProdutosOperacoesDuplicarController.origemPreco(
AValue: string): IProdutoOperacaoDuplicarController;
begin
Result := Self;
FOrigemPreco := AValue;
end;
function TProdutosOperacoesDuplicarController.prMedio(
AValue: string): IProdutoOperacaoDuplicarController;
begin
Result := Self;
if AValue = EmptyStr then
AValue := '0';
FPrMedio := StrToCurr(AValue);
end;
function TProdutosOperacoesDuplicarController.prMedio(
AValue: Currency): IProdutoOperacaoDuplicarController;
begin
Result := Self;
FPrMedio := AValue;
end;
function TProdutosOperacoesDuplicarController.prMedioSinapi(AValue: string)
: IProdutoOperacaoDuplicarController;
begin
Result := Self;
if AValue = EmptyStr then
AValue := '0';
FPrMedioSinap := StrToCurr(AValue);
end;
function TProdutosOperacoesDuplicarController.prMedioSinapi(AValue: Currency)
: IProdutoOperacaoDuplicarController;
begin
Result := Self;
FPrMedioSinap := AValue;
end;
function TProdutosOperacoesDuplicarController.produtoModel(AValue: IProdutoModel)
: IProdutoOperacaoDuplicarController;
begin
Result := Self;
FProdutoModel := AValue;
end;
function TProdutosOperacoesDuplicarController.produtoSelecionado(
AValue: TTESTPRODUTO): IProdutoOperacaoDuplicarController;
begin
Result := Self;
FRegistro := AValue;
end;
function TProdutosOperacoesDuplicarController.unidMedida(AValue: string)
: IProdutoOperacaoDuplicarController;
begin
Result := Self;
FUnidMedida := AValue;
end;
end.
|
unit FormQuery;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls,iOPCTypes,ScktComp,Ini,LogsUnit,superobject,
StrUtils,Common,iOPCFunctions,ComObj;
type
TStringMap = class(TPersistent)
private
function GetItems(Key: string): string;
function GetCount: Integer;
public
Keys: TStrings;
Values: array of string;
property Items[Key: string]: string read GetItems; default;
property Count: Integer read GetCount;
function Add(Key: string; Value: string): Integer;
procedure clear;
function Remove(Key: string): Integer;
constructor Create; overload;
end;
TServer = class(TObject)
public
OPCItemMgt : IOPCItemMgt;
OPCServer : IOPCServer;
GroupHandle: OPCHANDLE
end;
TServers = class(TPersistent)
private
function GetItems(Key: string): TServer;
function GetCount: Integer;
public
Keys: TStrings;
Values: array of TServer;
property Items[Key: string]: TServer read GetItems; default; //获取其单一元素
property Count: Integer read GetCount; //获取个数
function Add(Key: string; Value: TServer): Integer; //添加元素
procedure clear;
function Remove(Key: string): Integer; //移除
constructor Create; overload;
end;
TDevice = class(TObject)
public
OHandel : OPCHANDLE; //句柄
OValue : string; //值
OName : string; //名称
Server : TServer; //服务
end;
TLogicDevice = class(TObject)
public
LogicDeviceId : string;
IsOk : Boolean; //物理删除标识
Address : string;
Value : string;
Devices : array of TDevice;
procedure Add(Device:TDevice);
end;
TScokets = class(TPersistent)
private
function GetItems(Key: string): TCustomWinSocket;
function GetCount: Integer;
public
Keys: TStrings;
Values: array of TCustomWinSocket;
property Items[Key: string]: TCustomWinSocket read GetItems; default; //获取其单一元素
property Count: Integer read GetCount; //获取个数
function Add(Key: string; Value: TCustomWinSocket): Integer; //添加元素
procedure clear;
function Remove(Key: string): Integer; //移除
constructor Create; overload;
end;
TFormQueryUnit = class(TForm)
Logs: TMemo;
LogClear: TCheckBox;
ClearLogBtn: TButton;
Timer: TTimer;
DeBugCk: TCheckBox;
ReadServer: TTimer;
procedure FormShow(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure ClearLogBtnClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ReadServerTimer(Sender: TObject);
private
{ Private declarations }
HasError : Boolean;
IsAdd : Boolean;
Servers : TServers;
Devices : array of TLogicDevice;
Scokets : TScokets;
Port : Integer; //本地监听端口
ScoketServer : TServerSocket; //本地监听scoket
TimeSpan : Integer; //定时扫描间隔
ServerPath : string;
RegeditStrings : TStringMap; //引擎注册字符串集合
procedure AddLogs(Content:string);
procedure Start;
procedure OnClientConnect(Sender: TObject;Socket: TCustomWinSocket);
procedure OnClientDisConnect(Sender: TObject;Socket: TCustomWinSocket);
procedure OnClientRead(Sender: TObject;Socket: TCustomWinSocket);
procedure OnErrorEvent(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure OnClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure GetNewData; //读取新数据
public
{ Public declarations }
end;
var
FormQueryUnit: TFormQueryUnit;
implementation
{$R *.dfm}
procedure TLogicDevice.Add(Device:TDevice);
begin
SetLength(Devices,Length(Devices)+1);
Devices[Length(Devices)-1] := Device;
end;
constructor TStringMap.Create;
begin
Keys := TStringList.Create;
SetLength(Values, 0);
end;
procedure TStringMap.clear;
begin
SetLength(Values, 0);
Keys.Clear;
end;
function TStringMap.GetItems(Key: string): string;
var
KeyIndex: Integer;
begin
KeyIndex := Keys.IndexOf(Key);
if KeyIndex <> -1 then
Result := Values[KeyIndex]
else
Result := '';
end;
function TStringMap.Add(Key: string; Value: string): Integer;
begin
if Keys.IndexOf(Key) = -1 then
begin
Keys.Add(Key);
SetLength(Values, Length(Values) + 1);
Values[Length(Values) - 1] := Value;
end
else
Values[Keys.IndexOf(Key)] := Value;
Result := Length(Values) - 1;
end;
function TStringMap.GetCount: Integer;
begin
Result := Keys.Count;
end;
function TStringMap.Remove(Key: string): Integer;
var
Index : Integer;
Count : Integer;
begin
Index := Keys.IndexOf(Key);
Count := Length(Values);
if Index <> -1 then
begin
Keys.Delete(Index);
Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0]));
SetLength(Values, Count - 1);
end;
Result := Count - 1;
end;
constructor TServers.Create;
begin
Keys := TStringList.Create;
SetLength(Values, 0);
end;
procedure TServers.clear;
begin
SetLength(Values, 0);
Keys.Clear;
end;
function TServers.GetItems(Key: string): TServer;
var
KeyIndex: Integer;
begin
KeyIndex := Keys.IndexOf(Key);
if KeyIndex <> -1 then
begin
Result := Values[KeyIndex];
end
else
Result := nil;
end;
function TServers.Add(Key: string; Value: TServer): Integer;
begin
if Keys.IndexOf(Key) = -1 then
begin
Keys.Add(Key);
SetLength(Values, Length(Values) + 1);
Values[Length(Values) - 1] := Value;
end
else
begin
Values[Keys.IndexOf(Key)] := Value;
end;
Result := Length(Values) - 1;
end;
function TServers.GetCount: Integer;
begin
Result := Keys.Count;
end;
function TServers.Remove(Key: string): Integer;
var
Index : Integer;
Count : Integer;
begin
Index := Keys.IndexOf(Key);
Count := Length(Values);
if Index <> -1 then
begin
Keys.Delete(Index);
Values[Index].Free;
Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0]));
SetLength(Values, Count - 1);
end;
Result := Count - 1;
end;
constructor TScokets.Create;
begin
Keys := TStringList.Create;
SetLength(Values, 0);
end;
procedure TScokets.clear;
begin
SetLength(Values, 0);
Keys.Clear;
end;
function TScokets.GetItems(Key: string): TCustomWinSocket;
var
KeyIndex: Integer;
begin
KeyIndex := Keys.IndexOf(Key);
if KeyIndex <> -1 then
Result := Values[KeyIndex]
else
Result := nil;
end;
function TScokets.Add(Key: string; Value: TCustomWinSocket): Integer;
begin
if Keys.IndexOf(Key) = -1 then
begin
Keys.Add(Key);
SetLength(Values, Length(Values) + 1);
Values[Length(Values) - 1] := Value;
end
else
Values[Keys.IndexOf(Key)] := Value;
Result := Length(Values) - 1;
end;
function TScokets.GetCount: Integer;
begin
Result := Keys.Count;
end;
function TScokets.Remove(Key: string): Integer;
var
Index : Integer;
Count : Integer;
begin
Index := Keys.IndexOf(Key);
Count := Length(Values);
if Index <> -1 then
begin
Keys.Delete(Index);
Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0]));
SetLength(Values, Count - 1);
end;
Result := Count - 1;
end;
procedure TFormQueryUnit.ClearLogBtnClick(Sender: TObject);
begin
Logs.Lines.Clear;
end;
procedure TFormQueryUnit.FormDestroy(Sender: TObject);
begin
Servers.clear;
end;
procedure TFormQueryUnit.FormShow(Sender: TObject);
begin
DeBugCk.Checked := True;
end;
procedure TFormQueryUnit.Start;
var
temp : TStrings;
begin
if not DirectoryExists(ExtractFileDir(PARAMSTR(0)) + '\logs') then CreateDirectory(PChar(ExtractFilePath(ParamStr(0)) + '\logs'), nil);
if not FileExists(ExtractFileDir(PARAMSTR(0)) + '\config.ini') then
begin
temp := TStringList.Create;
temp.Add('[server]');
temp.Add('port=5000');
temp.Add('serverpath=');
temp.Add('time=500');
AddLogs('没有找到配置文件,默认端口5000,连接本地..');
temp.SaveToFile(ExtractFileDir(PARAMSTR(0)) + '\config.ini');
Port := 5000;
TimeSpan := 500;
end
else
begin
Port := StrToInt(Ini.ReadIni('server','port'));
TimeSpan := StrToInt(Ini.ReadIni('server','time'));
ServerPath := Ini.ReadIni('server','serverpath');
end;
ScoketServer := TServerSocket.Create(Application);
ScoketServer.Port := Port;
ScoketServer.OnClientConnect := OnClientConnect;
ScoketServer.OnClientRead := OnClientRead;
ScoketServer.OnClientDisconnect := OnClientDisConnect;
ScoketServer.Socket.OnErrorEvent := OnErrorEvent;
ScoketServer.Socket.OnClientError := OnClientError;
try
ScoketServer.Open;
AddLogs('成功监听在端口:' + IntToStr(Port));
except
AddLogs('打开失败,可能是端口被占用了,当前端口:' + IntToStr(Port));
end;
Servers := TServers.Create;
Scokets := TScokets.Create;
RegeditStrings := TStringMap.Create;
HasError:= False;
IsAdd := False;
ReadServer.Interval := TimeSpan;
ReadServer.Enabled := True;
end;
procedure TFormQueryUnit.TimerTimer(Sender: TObject);
begin
Timer.Enabled := False;
Start;
end;
procedure TFormQueryUnit.GetNewData;
var
I :Integer;
NeedSend :Boolean;
Scoket :TCustomWinSocket;
K :Integer;
tempValue :string;
ItemQuality : Word;
RObject :ISuperObject;
begin
if IsAdd then Exit;
if HasError then
begin
SetLength(Devices,0);
Scokets.clear;
HasError := False;
Exit;
end;
for I := 0 to Length(Devices) - 1 do
begin
if not Devices[I].IsOk then Continue;
RObject := SO('{}');
NeedSend := False;
RObject.S['id'] := Devices[I].LogicDeviceId;
for K := 0 to Length(Devices[I].Devices) - 1 do
begin
try
iOPCFunctions.OPCReadGroupItemValue(Devices[I].Devices[K].Server.OPCItemMgt,Devices[I].Devices[K].OHandel,tempValue,ItemQuality);
if tempValue <> Devices[I].Devices[K].OValue then
NeedSend := True;
Devices[I].Devices[K].OValue := tempValue;
RObject['value[]'] := SO(tempValue);
except
AddLogs('ID为' + Devices[I].LogicDeviceId+'的逻辑设备的点:'+Devices[I].Devices[K].OName+'查询失败,移除该设备!');
Devices[I].IsOk := False;
end;
end;
if NeedSend and Devices[I].IsOk then
begin
Devices[I].Value := Common.encode(RObject.AsString);
Scoket := Scokets.Items[Devices[I].Address];
if Assigned(Scoket) and Scoket.Connected then
begin
Scoket.SendText(Devices[I].Value+#$D#$A);
end;
end;
end;
end;
procedure TFormQueryUnit.AddLogs(Content:string);
begin
if DeBugCk.Checked then
begin
Logs.Lines.Add(Content);
end
else
begin
if (LogClear.Checked) and (Logs.Lines.Count >= 100) then
begin
Logs.Lines.Clear;
end;
LogsUnit.addErrors(Content);
end;
end;
procedure TFormQueryUnit.OnClientConnect(Sender: TObject;Socket: TCustomWinSocket);
var
address : string;
begin
address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
AddLogs(address + '已经连接');
end;
procedure TFormQueryUnit.OnClientDisConnect(Sender: TObject;Socket: TCustomWinSocket);
var
address : string;
begin
address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
AddLogs(address + '断开连接');
HasError:= True;
end;
procedure TFormQueryUnit.OnClientRead(Sender: TObject;Socket: TCustomWinSocket);
var
RevText : string;
Temp : string;
Index : Integer;
RevObj : ISuperObject;
Address : string;
Devs : TSuperArray;
Dev : ISuperObject;
I : Integer;
K : Integer;
ALogicDevice : TLogicDevice;
Points : TSuperArray;
phDev : ISuperObject;
Server : TServer;
Device : TDevice;
CanonicalType : TVarType;
Active : Boolean;
begin
Address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
RevText := Trim(Socket.ReceiveText);
Index := Pos('^_^',RevText);
if Index = 0 then
begin
Temp := RegeditStrings.Items[Address];
Temp := Temp + RevText;
RegeditStrings.Add(Address,Temp);
Exit;
end;
Temp := RegeditStrings.Items[Address];
Temp := Temp + RevText;
RevText := '';
RegeditStrings.Remove(Address);
Temp := LeftStr(Temp,Length(Temp)-3);
try
RevText := Common.decode(Temp);
except
AddLogs('解码发生异常!('+Address+')'+RevText);
Exit;
end;
IsAdd := True;
RevObj := SO(RevText);
if not Assigned(RevObj) then
begin
AddLogs('解析格式错误('+Address+')'+RevText);
Exit;
end;
Devs := RevObj.A['device'];
if not Assigned(Devs) then
begin
AddLogs('解析格式错误('+Address+')'+RevText);
Exit;
end;
Scokets.Add(Address,Socket);
for I := 0 to Devs.Length - 1 do
begin
Dev := Devs.O[I];
ALogicDevice := TLogicDevice.Create;
ALogicDevice.LogicDeviceId := Dev.S['id'];
ALogicDevice.Address := Address;
ALogicDevice.IsOk := True;
Points := Dev.A['device'];
Active := True;
for K := 0 to Points.Length - 1 do
begin
phDev := Points.O[K];
Server := Servers.Items[phDev.S['serverName']];
Device := TDevice.Create;
Device.OName := phDev.S['itemName'];
if not Assigned(Server) then
begin
try
Server := TServer.Create;
Server.OPCServer := (CreateComObject(ProgIDToClassID(phDev.S['serverName'])) as IOPCServer);
iOPCFunctions.OPCServerAddGroup(Server.OPCServer,phDev.S['serverName'] + '_group1',True,500,Server.OPCItemMgt,Server.GroupHandle);
Servers.Add(phDev.S['serverName'],Server);
except
AddLogs(phDev.S['serverName'] + '服务注册失败');
Server.Free;
Server := nil;
Servers.Remove(phDev.S['serverName']);
end;
end;
if Assigned(Server) then
begin
iOPCFunctions.OPCGroupAddItem(Server.OPCItemMgt,Device.OName,Server.GroupHandle,varString,Device.OHandel,CanonicalType);
Device.Server := Server;
ALogicDevice.Add(Device);
end
else
begin
AddLogs(Device.OName + '点注册失败');
Active := False;
end;
end;
if Active then
begin
SetLength(Devices,Length(Devices)+1);
Devices[Length(Devices)-1] := ALogicDevice;
end;
end;
IsAdd := False;
end;
procedure TFormQueryUnit.OnErrorEvent(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
var
address:string;
begin
address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
AddLogs(address + '发生异常');
ErrorCode := 0;
HasError:= True;
end;
procedure TFormQueryUnit.ReadServerTimer(Sender: TObject);
begin
GetNewData;
end;
procedure TFormQueryUnit.OnClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
var
address : string;
begin
address := Socket.RemoteAddress+':'+ InttoStr(Socket.RemotePort);
AddLogs(address + '发生异常');
ErrorCode := 0;
HasError:= True;
end;
end.
|
(*
-----------------------------------------------------------------------------------------------------
Version : (288 - 276)
Date : 12.09.2010
Author : Antonio Marcos Fernandes de Souza (amfsouza)
Issue : component loosing numeric format.
Solution: I linked correct property to component.
Version : (288 - 277)
-----------------------------------------------------------------------------------------------------
*)
unit uFrmAskPrice;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls,
SuperEdit, SuperEditCurrency;
type
TFrmAskPrice = class(TFrmParentAll)
lbPrice: TLabel;
lbModel: TLabel;
btOk: TButton;
edtSalePrice: TSuperEditCurrency;
procedure edtSalePriceKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure edtSalePricePressEnter(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
function Start(sModel, sDesc: String):Currency;
end;
implementation
uses
uCharFunctions, uNumericFunctions, uDM;
{$R *.dfm}
{ TFrmAskPrice }
function TFrmAskPrice.Start(sModel, sDesc: String): Currency;
begin
lbModel.Caption := (sModel + ' - ' + sDesc);
ShowModal;
Result := MyStrToMoney(edtSalePrice.Text);
end;
procedure TFrmAskPrice.edtSalePriceKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := ValidateCurrency(Key);
if Key = ThousandSeparator then
Key := #0;
end;
procedure TFrmAskPrice.FormShow(Sender: TObject);
begin
inherited;
edtSalePrice.SetFocus;
end;
procedure TFrmAskPrice.edtSalePricePressEnter(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrmAskPrice.FormCreate(Sender: TObject);
begin
inherited;
//amfsouza 12.09.2010
edtSalePrice.DisplayFormat := DM.FQtyDecimalFormat;
end;
end.
|
(*
* Copyright (c) 2004
* HouSisong@gmail.com
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*)
//------------------------------------------------------------------------------
// 具现化的Byte类型的声明
// Create by HouSisong, 2006.10.21
//------------------------------------------------------------------------------
unit DGL_Word;
interface
uses
SysUtils;
{$I DGLCfg.inc_h}
type
_ValueType = Word;
const
_NULL_Value:Word=0;
{$define _DGL_NotHashFunction}
{$I DGL.inc_h}
type
TWordAlgorithms = _TAlgorithms;
IWordIterator = _IIterator;
IWordContainer = _IContainer;
IWordSerialContainer = _ISerialContainer;
IWordVector = _IVector;
IWordList = _IList;
IWordDeque = _IDeque;
IWordStack = _IStack;
IWordQueue = _IQueue;
IWordPriorityQueue = _IPriorityQueue;
IWordSet = _ISet;
IWordMultiSet = _IMultiSet;
TWordVector = _TVector;
TWordDeque = _TDeque;
TWordList = _TList;
IWordVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:)
IWordDequeIterator = _IDequeIterator; //速度比_IIterator稍快一点:)
IWordListIterator = _IListIterator; //速度比_IIterator稍快一点:)
TWordStack = _TStack;
TWordQueue = _TQueue;
TWordPriorityQueue = _TPriorityQueue;
IWordMapIterator = _IMapIterator;
IWordMap = _IMap;
IWordMultiMap = _IMultiMap;
TWordSet = _TSet;
TWordMultiSet = _TMultiSet;
TWordMap = _TMap;
TWordMultiMap = _TMultiMap;
TWordHashSet = _THashSet;
TWordHashMultiSet = _THashMultiSet;
TWordHashMap = _THashMap;
TWordHashMultiMap = _THashMultiMap;
implementation
{$I DGL.inc_pas}
end.
|
unit StreamUtils;
{$WEAKPACKAGEUNIT ON}
{
Stream helpers. Cached readers/writers.
Some comments are in Russian, deal with it *puts on glasses*.
(c) himselfv, me@boku.ru.
}
interface
uses SysUtils, Classes{$IFDEF DCC}, Windows{$ENDIF};
type
EStreamException = class(Exception);
const
sCannotReadData = 'Cannot read data from the stream';
sCannotWriteData = 'Cannot write data to the stream';
{
A class to speed up reading from low latency streams (usually file streams).
Every time you request something from TFileStream, it reads the data from a
file. Even with drive cache enabled, it's a kernel-mode operation which is slow.
This class tries to overcome the problem by reading data in large chunks.
Whenever you request your byte or two, it reads the whole chunk and stores
it in local memory. Next time you request another two bytes you'll get
them right away, because they're already here.
Please remember that you CAN'T use StreamReader on a Stream "for a while".
The moment you read your first byte through StreamReader the underlying
stream is NOT YOURS ANYMORE. You shouldn't make any reads to the Stream
except than through StreamReader.
}
const
DEFAULT_CHUNK_SIZE = 4096;
type
TStreamReader = class(TStream)
protected
FStream: TStream;
FOwnStream: boolean;
FBytesRead: int64;
public
property Stream: TStream read FStream;
property OwnStream: boolean read FOwnStream;
property BytesRead: int64 read FBytesRead;
protected
flag_reallocbuf: boolean;
FNextChunkSize: integer; //size of a chunk we'll try to read next time
FChunkSize: integer; //size of current chunk
buf: pbyte; //cached data
ptr: pbyte; //current location in buf
adv: integer; //number of bytes read from buf
rem: integer; //number of bytes remaining in buf.
//adv+rem not always equals to FChunkSize since we could have read only
//partial chunk or FChunkSize could have been changed after that.
function NewChunk: integer;
function UpdateChunk: integer;
procedure SetChunkSize(AValue: integer);
procedure ResetBuf;
function ReallocBuf(ASize: integer): boolean;
procedure FreeBuf;
public
property ChunkSize: integer read FChunkSize write SetChunkSize;
property ChunkBytesRemaining: integer read rem;
public
constructor Create(AStream: TStream; AOwnStream: boolean = false);
destructor Destroy; override;
procedure JoinStream(AStream: TStream; AOwnsStream: boolean = false);
procedure ReleaseStream;
protected
function GetSize: Int64; override;
function GetInternalPosition: integer;
function LocalSeek(Offset: Int64; Origin: TSeekOrigin): boolean;
public
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
function Read(var Buffer; Count: Longint): Longint; override;
function ReadBuf(ABuf: pbyte; ALen: integer): integer; inline;
function Write(const Buffer; Count: Longint): Longint; override;
function Peek(var Buffer; ASize: integer): integer;
function PeekByte(out b: byte): boolean;
end;
TStreamWriter = class(TStream)
protected
FStream: TStream;
FOwnStream: boolean;
FBytesWritten: int64;
public
property Stream: TStream read FStream;
property OwnStream: boolean read FOwnStream;
property BytesWritten: int64 read FBytesWritten;
protected
FChunkSize: integer;
buf: pbyte;
ptr: pbyte;
used: integer;
procedure ResetBuf;
procedure FreeBuf;
procedure SetChunkSize(AValue: integer);
public
property ChunkSize: integer read FChunkSize write SetChunkSize;
public
constructor Create(AStream: TStream; AOwnStream: boolean = false);
destructor Destroy; override;
procedure JoinStream(AStream: TStream; AOwnsStream: boolean = false);
procedure ReleaseStream;
protected
function GetSize: Int64; override;
procedure SetSize(NewSize: Longint); overload; override;
procedure SetSize(const NewSize: Int64); overload; override;
function GetInternalPosition: integer;
public
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function WriteBuf(ABuf: PByte; ALen: integer): integer; inline;
procedure Flush;
end;
{ TStringStream
Stores or retrieves raw data from a string.
If you pass a string, it will be read/updated, else internal buffer is used. }
{ Don't instantiate }
TCustomStringStream = class(TStream)
protected
FPtr: PByte;
FPos: integer; //in bytes
function RemainingSize: integer;
public
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
end;
{ Single-byte strings }
TAnsiStringStream = class(TCustomStringStream)
protected
FOwnBuffer: AnsiString;
FString: PAnsiString;
function GetString: AnsiString;
function GetSize: Int64; override;
procedure SetSize(NewSize: Longint); override;
public
constructor Create(AString: PAnsiString = nil);
property Data: AnsiString read GetString;
end;
{ Double-byte strings }
TUnicodeStringStream = class(TCustomStringStream)
protected
FOwnBuffer: UnicodeString;
FString: PUnicodeString;
function GetString: UnicodeString;
function GetSize: Int64; override;
procedure SetSize(NewSize: Longint); override;
public
constructor Create(AString: PUnicodeString = nil);
property Data: UnicodeString read GetString;
end;
TStringStream = TUnicodeStringStream;
implementation
type
//IntPtr is missing in older versions of Delphi and it's easier to simply redeclare it
//FPC and Delphi use a lot of different define
{$IF Defined(CPU64) or Defined(CPUX64) or Defined(CPUX86_64)}
IntPtr = int64;
{$ELSEIF Defined(CPU32) or Defined(CPUX86) or Defined(CPU386) or Defined(CPUI386) or Defined(I386) }
IntPtr = integer;
{$ELSE}
{$MESSAGE Error 'Cannot declare IntPtr for this target platform'}
{$IFEND}
{ TStreamReader }
constructor TStreamReader.Create(AStream: TStream; AOwnStream: boolean = false);
begin
inherited Create;
FStream := AStream;
FOwnStream := AOwnStream;
buf := nil;
ptr := nil;
adv := 0;
rem := 0;
FChunkSize := 0;
SetChunkSize(DEFAULT_CHUNK_SIZE);
end;
destructor TStreamReader.Destroy;
begin
FreeBuf;
if OwnStream then
FreeAndNil(FStream)
else
FStream := nil;
inherited;
end;
procedure TStreamReader.JoinStream(AStream: TStream; AOwnsStream: boolean = false);
begin
ReleaseStream;
FStream := AStream;
FOwnStream := AOwnsStream;
ResetBuf;
end;
//Releases the stream and synchronizes it's position with the expected one
procedure TStreamReader.ReleaseStream;
begin
if FStream=nil then exit;
//Scroll back (Seek support required!)
FStream.Seek(int64(-adv-rem), soCurrent);
//Release the stream
FStream := nil;
FOwnStream := false;
ResetBuf;
end;
procedure TStreamReader.SetChunkSize(AValue: integer);
begin
//If we can't realloc right now, set delayed reallocation
if ReallocBuf(AValue) then
FChunkSize := AValue
else begin
flag_reallocbuf := true;
FNextChunkSize := AValue;
end;
end;
{ Downloads a complete new chunk of data. Returns the number of bytes read. }
function TStreamReader.NewChunk: integer;
begin
//Delayed reallocation
if flag_reallocbuf and ReallocBuf(FNextChunkSize) then begin
FChunkSize := FNextChunkSize;
flag_reallocbuf := false;
end;
rem := FStream.Read(buf^, FChunkSize);
adv := 0;
ptr := buf;
Result := rem;
end;
{ Moves remaining data to the beginning of the cache and downloads more.
Returns the number of bytes read. }
function TStreamReader.UpdateChunk: integer;
var DataPtr: Pbyte;
begin
//Full cache download
if rem <= 0 then begin
Result := NewChunk;
exit;
end;
//Partial download
Move(ptr^, buf^, rem);
ptr := buf;
adv := 0;
if flag_reallocbuf and ReallocBuf(FNextChunkSize) then begin
FChunkSize := FNextChunkSize;
flag_reallocbuf := false;
end;
DataPtr := PByte(cardinal(buf) + cardinal(adv+rem));
Result := Stream.Read(DataPtr^, FChunkSize-adv-rem);
rem := rem + Result;
end;
//Clears the contents of the cache
procedure TStreamReader.ResetBuf;
begin
adv := 0;
rem := 0;
ptr := buf;
end;
function TStreamReader.ReallocBuf(ASize: integer): boolean;
begin
//We can't decrease buffer size cause there's still data inside.
if adv + rem > ASize then begin
Result := false;
exit;
end;
ReallocMem(buf, ASize);
ptr := pointer(IntPtr(buf) + adv);
Result := true;
end;
procedure TStreamReader.FreeBuf;
begin
if Assigned(buf) then
FreeMem(buf);
end;
function TStreamReader.GetSize: Int64;
begin
Result := FStream.Size;
end;
function TStreamReader.GetInternalPosition: integer;
begin
Result := FStream.Position - rem;
end;
//If possible, try to Seek inside the buffer
function TStreamReader.LocalSeek(Offset: Int64; Origin: TSeekOrigin): boolean;
var pos,sz: Int64;
begin
if Origin=soEnd then begin
sz := FStream.Size;
//Convert to from beginning
Offset := sz - Offset;
Origin := soBeginning;
end;
if Origin=soBeginning then begin
pos := FStream.Position;
if (Offset>=pos) or (Offset<pos-adv-rem) then begin
Result := false; //not in this chunk
exit;
end;
//Convert to relative
Offset := rem-(pos-Offset);
Origin := soCurrent;
end;
if Origin=soCurrent then begin
if (Offset<-adv) or (Offset>=rem) then begin
Result := false;
exit;
end;
adv := adv+Offset;
rem := rem-Offset;
Inc(ptr, Offset);
Result := true;
end else
Result := false;
end;
function TStreamReader.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
//TStream calls Seek(0,soCurrent) to determine Position, so be fast in this case
if (Origin=soCurrent) and (Offset=0) then
Result := GetInternalPosition()
else
if LocalSeek(Offset, Origin) then
Result := GetInternalPosition()
else begin
Result := FStream.Seek(Offset, Origin);
ResetBuf;
end;
end;
function TStreamReader.Read(var Buffer; Count: Longint): Longint;
var pbuf: PByte;
begin
if Count=0 then begin
Result := 0;
exit;
end;
//The most common case
if Count <= rem then begin
Move(ptr^, Buffer, Count);
Inc(ptr, Count);
Inc(adv, Count);
Dec(rem, Count);
Inc(FBytesRead, Count);
Result := Count;
exit;
end;
//Read first part
pbuf := @Buffer;
if rem > 0 then begin
Move(ptr^, pbuf^, rem);
Inc(ptr, rem);
Inc(adv, rem);
//Update variables
Inc(pbuf, rem);
Dec(Count, rem);
Result := rem;
rem := 0;
end else
Result := 0;
//Download the remaining part
//If it's smaller than a chunk, read the whole chunk
if Count < FChunkSize then begin
NewChunk;
if rem < Count then //rem was already updated in NewChunk
Count := rem;
Move(ptr^, pbuf^, Count);
Inc(ptr, Count);
Inc(adv, Count);
Dec(rem, Count);
Inc(Result, Count);
end else
//Else just read it from stream
Result := Result + FStream.Read(pbuf^, Count);
Inc(FBytesRead, Result);
end;
function TStreamReader.ReadBuf(ABuf: pbyte; ALen: integer): integer;
begin
Result := Read(ABuf^, ALen);
end;
function TStreamReader.Write(const Buffer; Count: Longint): Longint;
begin
raise Exception.Create('StreamReader cannot write.');
end;
//Won't Peek for more than CacheSize
function TStreamReader.Peek(var Buffer; ASize: integer): integer;
begin
//If the data is in cache, it's simple
if ASize <= rem then begin
Move(ptr^, Buffer, ASize);
Result := ASize;
exit;
end;
//Else return the best possible amount. Make the cache completely fresh
if rem <= FChunkSize then
UpdateChunk;
//If the complete data fit, return it
if ASize <= rem then begin
Move(ptr^, Buffer, ASize);
Result := ASize;
exit;
end;
//Didn't fit => return all that's available
Move(ptr^, Buffer, rem);
Result := rem;
end;
//Уж один-то байт мы всегда можем подсмотреть, если в файле осталось.
function TStreamReader.PeekByte(out b: byte): boolean;
begin
//Если буфер непуст, берём первый байт
if rem >= 0 then begin
b := ptr^;
Result := true;
exit;
end;
//Иначе буфер пуст. Качаем следующий кусочек.
NewChunk;
if rem >= 0 then begin
b := ptr^;
Result := true;
end else
Result := false;
end;
{ TStreamWriter }
constructor TStreamWriter.Create(AStream: TStream; AOwnStream: boolean = false);
begin
inherited Create;
FStream := AStream;
FOwnStream := AOwnStream;
FChunkSize := 0;
buf := nil;
ptr := nil;
used := 0;
SetChunkSize(DEFAULT_CHUNK_SIZE);
end;
destructor TStreamWriter.Destroy;
begin
Flush();
FreeBuf;
if OwnStream then
FreeAndNil(FStream)
else
FStream := nil;
inherited;
end;
procedure TStreamWriter.JoinStream(AStream: TStream; AOwnsStream: boolean = false);
begin
//Освобождаем старый поток
ReleaseStream;
//Цепляемся к потоку
FStream := AStream;
FOwnStream := AOwnsStream;
//Сбрасываем буфер на всякий случай
ResetBuf;
end;
//Освобождает поток, синхронизируя его положение с ожидаемым
procedure TStreamWriter.ReleaseStream;
begin
if FStream=nil then exit;
//Сбрасываем
Flush;
//Отпускаем поток
FStream := nil;
FOwnStream := false;
end;
//Сбрасывает на диск содержимое буфера и обнуляет буфер.
procedure TStreamWriter.Flush;
begin
if used <= 0 then exit;
FStream.Write(buf^, used);
ptr := buf;
used := 0;
end;
procedure TStreamWriter.ResetBuf;
begin
ptr := buf;
used := 0;
end;
procedure TStreamWriter.FreeBuf;
begin
if Assigned(buf) then
FreeMem(buf);
buf := nil;
ptr := nil;
used := 0;
end;
procedure TStreamWriter.SetChunkSize(AValue: integer);
begin
//Если в новый буфер текущие данные не влезают, сбрасываем их в поток
if AValue < used then
Flush;
FChunkSize := AValue;
ReallocMem(buf, FChunkSize);
//Обновляем указатель на текущий байт
ptr := pointer(IntPtr(buf) + used);
end;
//Use this instead of underlying Stream's Position
function TStreamWriter.GetInternalPosition: integer;
begin
Result := FStream.Position + used;
end;
function TStreamWriter.GetSize: Int64;
begin
Result := FStream.Size + used;
end;
procedure TStreamWriter.SetSize(NewSize: Longint);
begin
SetSize(int64(NewSize));
end;
procedure TStreamWriter.SetSize(const NewSize: Int64);
begin
Flush();
FStream.Size := NewSize;
end;
function TStreamWriter.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
if (Origin=soCurrent) and (Offset=0) then
Result := GetInternalPosition() //TStream uses this to determine Position
else begin
Flush;
Result := FStream.Seek(Offset, Origin);
end;
end;
function TStreamWriter.Read(var Buffer; Count: Longint): Longint;
begin
raise Exception.Create('StreamWriter cannot read.');
end;
function TStreamWriter.Write(const Buffer; Count: Longint): Longint;
var rem: integer;
pbuf: PByte;
begin
if Count<=0 then begin
Result := 0;
exit;
end;
//Если влезает в кэш, кладём туда
rem := FChunkSize - used;
if Count <= rem then begin
Move(Buffer, ptr^, Count);
Inc(used, Count);
Inc(ptr, Count);
Result := Count;
Inc(FBytesWritten, Count);
exit;
end;
//Иначе нас просят записать нечто большее. Вначале добиваем текущий буфер
pbuf := @Buffer;
if used > 0 then begin
if rem > 0 then begin
Move(pbuf^, ptr^, rem);
Inc(ptr, rem);
Inc(used, rem);
//Update variables
Inc(pbuf, rem);
Dec(Count, rem);
Result := rem;
end else
Result := 0;
Flush;
end else
Result := 0;
//Если остаток меньше буфера, сохраняем его в буфер
if Count < FChunkSize then begin
Move(pbuf^, ptr^, Count);
Inc(ptr, Count);
Inc(used, Count);
Inc(Result, Count);
end else
//Иначе пишем его напрямую
Result := Result + FStream.Write(pbuf^, Count);
Inc(FBytesWritten, Result);
end;
function TStreamWriter.WriteBuf(ABuf: PByte; ALen: integer): integer;
begin
Result := Write(ABuf^, ALen);
end;
{
TCustomStringStream
}
function TCustomStringStream.RemainingSize: integer;
begin
Result := Self.Size-FPos;
end;
function TCustomStringStream.Read(var Buffer; Count: Longint): Longint;
begin
if Count>RemainingSize then
Count := RemainingSize;
Move(PByte(IntPtr(FPtr)+FPos)^,Buffer,Count);
Inc(FPos,Count);
Result := Count;
end;
function TCustomStringStream.Write(const Buffer; Count: Longint): Longint;
begin
if RemainingSize<Count then
SetSize(FPos+Count);
Move(Buffer,PByte(IntPtr(FPtr)+FPos)^,Count);
Inc(FPos,Count);
Result := Count;
end;
function TCustomStringStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
if Origin=soCurrent then begin
if Offset=0 then begin
Result := FPos;
exit;
end;
Result := FPos+Offset;
end else
if Origin=soEnd then begin
Result := GetSize-Offset;
end else
Result := Offset;
if Result<0 then
Result := 0
else
if Result>GetSize then
Result := GetSize;
FPos := Result;
end;
{
TAnsiStringStream
}
constructor TAnsiStringStream.Create(AString: PAnsiString = nil);
begin
inherited Create();
if AString=nil then
FString := @FOwnBuffer
else
FString := AString;
FPos := 0;
FPtr := pointer(FString^);
end;
function TAnsiStringStream.GetString: AnsiString;
begin
Result := FString^;
end;
function TAnsiStringStream.GetSize: Int64;
begin
Result := Length(FString^)*SizeOf(AnsiChar);
end;
procedure TAnsiStringStream.SetSize(NewSize: Longint);
begin
SetLength(FString^, NewSize);
FPtr := pointer(FString^);
end;
{
TUnicodeStringStream
}
constructor TUnicodeStringStream.Create(AString: PUnicodeString = nil);
begin
inherited Create();
if AString=nil then
FString := @FOwnBuffer
else
FString := AString;
FPos := 0;
FPtr := pointer(FString^);
end;
function TUnicodeStringStream.GetString: UnicodeString;
begin
Result := FString^;
end;
function TUnicodeStringStream.GetSize: Int64;
begin
Result := Length(FString^)*SizeOf(WideChar);
end;
procedure TUnicodeStringStream.SetSize(NewSize: Longint);
begin
if NewSize mod 2 = 0 then
SetLength(FString^, NewSize div SizeOf(WideChar))
else
SetLength(FString^, NewSize div SizeOf(WideChar) + 1); //no choice but to allocate one more symbol
FPtr := pointer(FString^);
end;
end.
|
unit vwuFoodsAllComposition;
interface
uses
System.SysUtils, System.Classes, Variants, vwuCommon, 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, fruDateTimeFilter;
type
TvwFoodsAllComposition = class(TvwCommon)
FCardCode: TWideStringField;
FCustomerName: TWideStringField;
FName: TWideStringField;
FPrice: TFloatField;
FQuantity: TFloatField;
FSumMoney: TFloatField;
FDiscountSum: TFloatField;
FPaySum: TFloatField;
private
FDateFilter: TfrDateTimeFilter;
FCustomerFilter: Variant;
FCardNumFilter: Variant;
function GetSqlDateFilter(): string;
function GetSqlCustomerFilter(): string;
function GetSqlCardNumFilter(): string;
public
constructor Create(Owner: TComponent); override;
class function ViewName(): string; override;
function GetViewText(aFilter: string): string; override;
property DateFilter: TfrDateTimeFilter read FDateFilter write FDateFilter;
property CustomerFilter: Variant read FCustomerFilter write FCustomerFilter;
property CardNumFilter: Variant read FCardNumFilter write FCardNumFilter;
end;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TvwFoodsAllComposition }
constructor TvwFoodsAllComposition.Create(Owner: TComponent);
begin
inherited;
FDateFilter := nil;
FCustomerFilter := Null;
FCardNumFilter := Null;
end;
function TvwFoodsAllComposition.GetSqlDateFilter: String;
begin
if Assigned(FDateFilter) then
Result := FDateFilter.GetSqlFilter('Orders.EndService', 'GlobalShifts.ShiftDate')
else
Result := '';
end;
function TvwFoodsAllComposition.GetSqlCustomerFilter: String;
begin
if FCustomerFilter <> Null then
Result := ' AND (DishDiscounts.Holder = N' + QuotedStr(FCustomerFilter) + ')'
else
Result := '';
end;
function TvwFoodsAllComposition.GetSqlCardNumFilter: String;
begin
if FCardNumFilter <> Null then
Result := ' AND (DishDiscounts.CardCode = N' + QuotedStr(FCardNumFilter) + ')'
else
Result := '';
end;
class function TvwFoodsAllComposition.ViewName: string;
begin
Result := 'VW_FOODS_ALL_COMPOSITION';
end;
function TvwFoodsAllComposition.GetViewText(aFilter: string): string;
const
NewLine = #13#10;
begin
Result :=
' SELECT * ' + NewLine +
' FROM ( ' + NewLine +
' SELECT ' + NewLine +
' CAST(ROW_NUMBER() OVER(ORDER BY DishDiscounts.CardCode) as INT) as ID, ' + NewLine +
' DishDiscounts.CardCode as CardCode, ' + NewLine +
' DishDiscounts.Holder as CustomerName, ' + NewLine +
' SaleObjects.Name AS Name, ' + NewLine +
' AVG(SessionDishes.Price) as Price, ' + NewLine +
' SUM(PayBindings.Quantity) AS Quantity, ' + NewLine +
' SUM(SessiOnDishes.Price * PayBindings.Quantity) as SumMoney, ' + NewLine +
' SUM(CASE ' + NewLine +
' WHEN Discparts.Sum IS NOT NULL ' + NewLine +
' THEN Discparts.Sum ' + NewLine +
' ELSE 0 ' + NewLine +
' END) as DiscountSum, ' + NewLine +
' SUM(PayBindings.PaySum) AS PaySum ' + NewLine +
{информация о сменах работы ресторана}
' FROM GlobalShifts ' + NewLine +
{информацию о кассовых серверах}
' INNER JOIN CashGroups ON (CashGroups.SIFR = GlobalShifts.Midserver) ' + NewLine +
{Информация о заказе, состоит из пакетов}
' INNER JOIN Orders ON (GlobalShifts.MidServer = Orders.MidServer) ' + NewLine +
' AND (GlobalShifts.ShiftNum = Orders.iCommonShift) ' + NewLine +
{Содержит информацию о скидках}
' INNER JOIN Discparts ON (Orders.Visit = DiscParts.Visit) ' + NewLine +
' AND (Orders.MidServer = DiscParts.MidServer) ' + NewLine +
' AND (Orders.IdentInVisit = DiscParts.OrderIdent) ' + NewLine +
{Содержит информацию о скидках/наценках}
' INNER JOIN DishDiscounts ON (DishDiscounts.Visit = DiscParts.Visit) ' + NewLine +
' AND (DishDiscounts.MidServer = DiscParts.MidServer) ' + NewLine +
' AND (DishDiscounts.UNI = DiscParts.DiscLineUNI) ' + NewLine +
' AND (DishDiscounts.CardCode <> '''') ' + NewLine +
' AND (DishDiscounts.ChargeSource = 5) ' + NewLine +
GetSqlCardNumFilter() + NewLine +
GetSqlCustomerFilter() + NewLine +
{платежи}
' INNER JOIN PayBindings ON (PayBindings.Visit = DiscParts.Visit) ' + NewLine +
' AND (PayBindings.MidServer = DiscParts.MidServer) ' + NewLine +
' AND (PayBindings.UNI = DiscParts.BindingUNI) ' + NewLine +
{Содержит информацию о платежи с учетом валюты}
' INNER JOIN CurrLines ON (CurrLines.Visit = PayBindings.Visit) ' + NewLine +
' AND (CurrLines.MidServer = PayBindings.MidServer) ' + NewLine +
' AND (CurrLines.UNI = PayBindings.CurrUNI) ' + NewLine +
{информацию о чеках}
' INNER JOIN PrintChecks ON (PrintChecks.Visit = CurrLines.Visit) ' + NewLine +
' AND (PrintChecks.MidServer = CurrLines.MidServer) ' + NewLine +
' AND (PrintChecks.UNI = CurrLines.CheckUNI) ' + NewLine +
' AND ((PrintChecks.State = 6) OR (PrintChecks.State = 7)) ' + NewLine +
' AND (PrintChecks.Deleted = 0) ' + NewLine +
' INNER JOIN SaleObjects ON (SaleObjects.Visit = PayBindings.Visit) ' + NewLine +
' AND (SaleObjects.MidServer = PayBindings.MidServer) ' + NewLine +
' AND (SaleObjects.DishUNI = PayBindings.DishUNI) ' + NewLine +
' AND (SaleObjects.ChargeUNI = PayBindings.ChargeUNI) ' + NewLine +
' INNER JOIN SessionDishes ON (SessionDishes.Visit = SaleObjects.Visit) ' + NewLine +
' AND (SessionDishes.MidServer = SaleObjects.MidServer) ' + NewLine +
' AND (SessionDishes.UNI = SaleObjects.DishUNI) ' + NewLine +
' GROUP BY ' +
' DishDiscounts.CardCode, ' + NewLine +
' DishDiscounts.Holder, ' + NewLine +
' SaleObjects.Name ' + NewLine +
' ) VW_FOODS_COMPOSITION ' + NewLine +
' WHERE (1 = 1)';
end;
end.
|
unit uFrmPrintShippingOption;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls;
type
TFrmPrintShippingOption = class(TFrmParentAll)
btnPrint: TButton;
lbReport: TLabel;
cbxReport: TComboBox;
lbNumCopies: TLabel;
edtNumCopy: TEdit;
chkPreview: TCheckBox;
cbxPrinter: TComboBox;
lbPrinter: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnPrintClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
private
FReceiptType,
FIDPreSale : Integer;
procedure FillDefaultPrinter;
public
function Start(IDPreSale, ReceiptType : Integer):Boolean;
end;
implementation
uses uDM, uPrintReceipt, Printers, Registry;
{$R *.dfm}
procedure TFrmPrintShippingOption.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TFrmPrintShippingOption.btnPrintClick(Sender: TObject);
var
AReport : String;
APrinter : String;
NumCopy : Integer;
APreview : Boolean;
begin
inherited;
case cbxReport.ItemIndex of
0 : AReport := DM.fCashRegister.ShippingPackingRep;
1 : AReport := DM.fCashRegister.ShippingPickRep;
2 : AReport := DM.fPrintReceipt.ReportPath;
end;
NumCopy := StrToIntDef(edtNumCopy.Text, 1);
APrinter := cbxPrinter.Text;
APreview := chkPreview.Checked;
with TPrintReceipt.Create(Self) do
StartShipping(FIDPreSale, FReceiptType, NumCopy, AReport, APrinter, APreview, 0);
Close;
end;
function TFrmPrintShippingOption.Start(IDPreSale, ReceiptType : Integer): Boolean;
begin
FReceiptType := ReceiptType;
FIDPreSale := IDPreSale;
cbxPrinter.Items := Printer.Printers;
FillDefaultPrinter;
ShowModal;
end;
procedure TFrmPrintShippingOption.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrmPrintShippingOption.FillDefaultPrinter;
var
Reg : TRegistry;
s : String;
p : Integer;
begin
try
Reg := Tregistry.create;
Reg.access := KEY_READ;
Reg.rootKey := HKEY_CURRENT_USER;
if Reg.openKey('\Software\Microsoft\Windows NT\CurrentVersion\Windows', False) then
s := Reg.readString('device');
if s <> '' then
begin
p := pos(',',s);
cbxPrinter.Text := copy(s,0,p-1);
end;
finally
Reg.CloseKey;
Reg.Free;
end;
end;
end.
|
unit Main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, GLScene,
GLObjects, GLVectorFileObjects, GLMaterial, GLCadencer, GLSArchiveManager,
GLLCLViewer, BaseClasses, VectorGeometry,
GLFileMS3D, TGA, GLFileZLIB;
type
{ TForm1 }
TForm1 = class(TForm)
GLCadencer1: TGLCadencer;
GLCamera: TGLCamera;
GLDummyCube1: TGLDummyCube;
GLFreeForm: TGLFreeForm;
GLFreeForm1: TGLFreeForm;
GLLightSource1: TGLLightSource;
GLMaterialLibrary1: TGLMaterialLibrary;
GLPlane1: TGLPlane;
GLSArchiveManager1: TGLSArchiveManager;
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
procedure FormCreate(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: double);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double);
begin
GLCamera.Position.Rotate(VectorMake(0, 1, 0), deltaTime * 0.1);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
path: UTF8String;
p: integer;
begin
path := ExtractFilePath(ParamStrUTF8(0));
p := Pos('DemosLCL', path);
Delete(path, p + 5, Length(path));
path := IncludeTrailingPathDelimiter(path) + 'media';
SetCurrentDirUTF8(path);
with GLSArchiveManager1.Archives[0] do
begin
LoadFromFile('Chair.zlib');
if FileName = '' then
ShowMessage('Archive Can not be Loaded');
{: Automatic loading from archive.
If file is not in archive, then it's loaded from harddrive. }
GLFreeForm.LoadFromFile('Chair.ms3d');
{: Direct loading from archive }
GLFreeForm1.LoadFromStream('Chair.ms3d', GetContent('Chair.ms3d'));
end;
end;
end.
|
// RemObjects CS to Pascal 0.1
namespace UT3Bots.UTItems;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Text,
UT3Bots.Communications;
type
UTMap = public class
private
//Private Members
var _navList: List<UTNavPoint> := new List<UTNavPoint>();
var _itemList: List<UTItemPoint> := new List<UTItemPoint>();
var _theBot: UTBotSelfState;
assembly
method UpdateState(Message: Message);
method GetLocationFromId(Id: String): UTVector;
method GetLocationFromId(Id: UTIdentifier): UTVector;
public
/// <summary>
/// Returns the nearest UTNavPoint to your bot's current location
/// </summary>
method GetNearestNavPoint(): UTNavPoint;
/// <summary>
/// Returns the nearest UTNavPoint to your bot's current location, excluding the UTNavpoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="toExclude">The UTNavPoint to ignore during the search</param>
method GetNearestNavPoint(toExclude: UTNavPoint): UTNavPoint;
/// <summary>
/// Returns the nearest UTNavPoint to the specified location
/// </summary>
/// <param name="location">The location you want to find the nearest nav point to</param>
/// <returns>The closest UTNavPoint to that location</returns>
method GetNearestNavPoint(location: UTVector): UTNavPoint;
/// <summary>
/// Returns the nearest UTNavPoint to the specified location, excluding the UTNavpoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="location">The location you want to find the nearest nav point to</param>
/// <param name="toExclude">The UTNavPoint to ignore during the search</param>
/// <returns>The closest UTNavPoint to that location</returns>
method GetNearestNavPoint(location: UTVector; toExclude: UTNavPoint): UTNavPoint;
//Set as new closest
/// <summary>
/// Returns the nearest UTItemPoint to your bot's current location
/// </summary>
/// <returns>The closest UTItemPoint to that location</returns>
method GetNearestItemPoint(): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint to your bot's current location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <returns>The closest UTItemPoint to that location</returns>
method GetNearestItemPoint(toExclude: UTItemPoint): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint to the specified location
/// </summary>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <returns>The closest UTItemPoint to that location</returns>
method GetNearestItemPoint(location: UTVector): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint to the specified location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint to that location</returns>
method GetNearestItemPoint(location: UTVector; toExclude: UTItemPoint): UTItemPoint;
//Set as new closest
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to your bot's current location
/// </summary>
/// <param name="type">The type to look for</param>
/// <returns>The closest UTItemPoint of that type to your bot's location</returns>
method GetNearestItem(&type: ItemType): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to your bot's current location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint of that type to your bot's location</returns>
method GetNearestItem(&type: ItemType; toExclude: UTItemPoint): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to the specified location
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <returns>The closest UTItemPoint of that type to that location</returns>
method GetNearestItem(&type: ItemType; location: UTVector): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to the specified location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint of that type to that location</returns>
method GetNearestItem(&type: ItemType; location: UTVector; toExclude: UTItemPoint): UTItemPoint;
//Set as new closest
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to your bot's current location
/// </summary>
/// <param name="type">The type to look for</param>
/// <returns>The closest UTItemPoint of that type to your bot's location</returns>
method GetNearestItem(&type: WeaponType): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to your bot's current location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint of that type to your bot's location</returns>
method GetNearestItem(&type: WeaponType; toExclude: UTItemPoint): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to the specified location
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <returns>The closest UTItemPoint of that type to that location</returns>
method GetNearestItem(&type: WeaponType; location: UTVector): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to the specified location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint of that type to that location</returns>
method GetNearestItem(&type: WeaponType; location: UTVector; toExclude: UTItemPoint): UTItemPoint;
//Set as new closest
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to your bot's current location
/// </summary>
/// <param name="type">The type to look for</param>
/// <returns>The closest UTItemPoint of that type to your bot's location</returns>
method GetNearestItem(&type: HealthType): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to your bot's current location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint of that type to your bot's location</returns>
method GetNearestItem(&type: HealthType; toExclude: UTItemPoint): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to the specified location
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <returns>The closest UTItemPoint of that type to that location</returns>
method GetNearestItem(&type: HealthType; location: UTVector): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to the specified location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint of that type to that location</returns>
method GetNearestItem(&type: HealthType; location: UTVector; toExclude: UTItemPoint): UTItemPoint;
//Set as new closest
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to your bot's current location
/// </summary>
/// <param name="type">The type to look for</param>
/// <returns>The closest UTItemPoint of that type to your bot's location</returns>
method GetNearestItem(&type: AmmoType): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to your bot's current location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint of that type to your bot's location</returns>
method GetNearestItem(&type: AmmoType; toExclude: UTItemPoint): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to the specified location
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <returns>The closest UTItemPoint of that type to that location</returns>
method GetNearestItem(&type: AmmoType; location: UTVector): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to the specified location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint of that type to that location</returns>
method GetNearestItem(&type: AmmoType; location: UTVector; toExclude: UTItemPoint): UTItemPoint;
//Set as new closest
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to your bot's current location
/// </summary>
/// <param name="type">The type to look for</param>
/// <returns>The closest UTItemPoint of that type to your bot's location</returns>
method GetNearestItem(&type: ArmorType): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to your bot's current location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint of that type to your bot's location</returns>
method GetNearestItem(&type: ArmorType; toExclude: UTItemPoint): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to the specified location
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <returns>The closest UTItemPoint of that type to that location</returns>
method GetNearestItem(&type: ArmorType; location: UTVector): UTItemPoint;
/// <summary>
/// Returns the nearest UTItemPoint of a certain type to the specified location, excluding the UTItemPoint specified.
/// Useful for ignoring the point your bot may already be stood on
/// </summary>
/// <param name="type">The type to look for</param>
/// <param name="location">The location you want to find the nearest item point to</param>
/// <param name="toExclude">The UTItemPoint to ignore during the search</param>
/// <returns>The closest UTItemPoint of that type to that location</returns>
method GetNearestItem(&type: ArmorType; location: UTVector; toExclude: UTItemPoint): UTItemPoint;
//Constructor
constructor(theBot: UTBotSelfState);
property NavPoints: List<UTNavPoint> read get_NavPoints;
method get_NavPoints: List<UTNavPoint>;
property InvItems: List<UTItemPoint> read get_InvItems;
method get_InvItems: List<UTItemPoint>;
end;
implementation
method UTMap.UpdateState(Message: Message);
begin
if ((Message <> nil) and (Message.&Event = EventMessage.STATE)) then
begin
case (Message.Info) of
InfoMessage.NAV_INFO:
begin
var nav: UTNavPoint := new UTNavPoint(new UTIdentifier(Message.Arguments[0]), UTVector.Parse(Message.Arguments[1]), Boolean.Parse(Message.Arguments[2]));
Self._navList.&Add(nav);
end;
InfoMessage.PICKUP_INFO:
begin
var item: UTItemPoint := new UTItemPoint(new UTIdentifier(Message.Arguments[0]), UTVector.Parse(Message.Arguments[1]), Message.Arguments[2], Boolean.Parse(Message.Arguments[3]), Boolean.Parse(Message.Arguments[4]));
Self._itemList.&Add(item);
end;
end; // case Message.Info of
end; // if ((Message..
end;
method UTMap.GetLocationFromId(Id: String): UTVector;
begin
var tempId: UTIdentifier := new UTIdentifier(Id);
exit GetLocationFromId(tempId)
end;
method UTMap.GetLocationFromId(Id: UTIdentifier): UTVector;
begin
for each n: UTNavPoint in Self._navList do
begin
if n.Id = Id then
begin
exit n.Location
end
else
begin
end
end;
for each i: UTItemPoint in Self._itemList do
begin
if i.Id = Id then
begin
exit i.Location
end
else
begin
end
end;
exit nil;
end;
method UTMap.GetNearestNavPoint(): UTNavPoint;
begin
Result := GetNearestNavPoint(_theBot.Location, nil);
end;
method UTMap.GetNearestNavPoint(toExclude: UTNavPoint): UTNavPoint;
begin
Result := GetNearestNavPoint(_theBot.Location, toExclude);
end;
method UTMap.GetNearestNavPoint(location: UTVector): UTNavPoint;
begin
Result := GetNearestNavPoint(location, nil);
end;
method UTMap.GetNearestNavPoint(location: UTVector; toExclude: UTNavPoint): UTNavPoint;
begin
var closest: UTNavPoint := nil;
var closestDistance: Single := -1;
for each n: UTNavPoint in Self._navList do
begin
var myDistance: Single := n.Location.DistanceFrom(location);
if ((n <> toExclude) and (myDistance < closestDistance < 0)) then
begin
closest := n;
closestDistance := myDistance
end;
end;
Result := closest;
end;
method UTMap.GetNearestItemPoint(): UTItemPoint;
begin
Result := GetNearestItemPoint(_theBot.Location, nil);
end;
method UTMap.GetNearestItemPoint(toExclude: UTItemPoint): UTItemPoint;
begin
Result := GetNearestItemPoint(_theBot.Location, toExclude);
end;
method UTMap.GetNearestItemPoint(location: UTVector): UTItemPoint;
begin
Result := GetNearestItemPoint(location, nil);
end;
method UTMap.GetNearestItemPoint(location: UTVector; toExclude: UTItemPoint): UTItemPoint;
begin
var closest: UTItemPoint := nil;
var closestDistance: Single := -1;
for each i: UTItemPoint in Self._itemList do
begin
var myDistance: Single := i.Location.DistanceFrom(location);
if ((i <> toExclude) and (myDistance < closestDistance < 0)) then
begin
closest := i;
closestDistance := myDistance
end;
end;
Result := closest;
end;
method UTMap.GetNearestItem(&type: ItemType): UTItemPoint;
begin
Result := GetNearestItem(&type, _theBot.Location, nil);
end;
method UTMap.GetNearestItem(&type: ItemType; toExclude: UTItemPoint): UTItemPoint;
begin
Result := GetNearestItem(&type, _theBot.Location, toExclude);
end;
method UTMap.GetNearestItem(&type: ItemType; location: UTVector): UTItemPoint;
begin
Result := GetNearestItem(&type, location, nil);
end;
method UTMap.GetNearestItem(&type: ItemType; location: UTVector; toExclude: UTItemPoint): UTItemPoint;
begin
var closest: UTItemPoint := nil;
var closestDistance: Single := -1;
for each i: UTItemPoint in Self._itemList do
begin
var myDistance: Single := i.Location.DistanceFrom(location);
if ((i <> toExclude) and (myDistance < closestDistance < 0) and (i.Item.IsItem(&type))) then
begin
closest := i;
closestDistance := myDistance
end;
end;
Result := closest;
end;
method UTMap.GetNearestItem(&type: WeaponType): UTItemPoint;
begin
Result := GetNearestItem(&type, _theBot.Location, nil);
end;
method UTMap.GetNearestItem(&type: WeaponType; toExclude: UTItemPoint): UTItemPoint;
begin
Result := GetNearestItem(&type, _theBot.Location, toExclude);
end;
method UTMap.GetNearestItem(&type: WeaponType; location: UTVector): UTItemPoint;
begin
Result := GetNearestItem(&type, location, nil);
end;
method UTMap.GetNearestItem(&type: WeaponType; location: UTVector; toExclude: UTItemPoint): UTItemPoint;
begin
var closest: UTItemPoint := nil;
var closestDistance: Single := -1;
for each i: UTItemPoint in Self._itemList do
begin
var myDistance: Single := i.Location.DistanceFrom(location);
if ((i <> toExclude) and (myDistance < closestDistance < 0) and (i.Item.IsItem(&type))) then
begin
closest := i;
closestDistance := myDistance;
end;
end;
Result := closest;
end;
method UTMap.GetNearestItem(&type: HealthType): UTItemPoint;
begin
Result := GetNearestItem(&type, _theBot.Location, nil);
end;
method UTMap.GetNearestItem(&type: HealthType; toExclude: UTItemPoint): UTItemPoint;
begin
Result := GetNearestItem(&type, _theBot.Location, toExclude);
end;
method UTMap.GetNearestItem(&type: HealthType; location: UTVector): UTItemPoint;
begin
Result := GetNearestItem(&type, location, nil);
end;
method UTMap.GetNearestItem(&type: HealthType; location: UTVector; toExclude: UTItemPoint): UTItemPoint;
begin
var closest: UTItemPoint := nil;
var closestDistance: Single := -1;
for each i: UTItemPoint in Self._itemList do
begin
var myDistance: Single := i.Location.DistanceFrom(location);
if ((i <> toExclude) and (myDistance < closestDistance < 0) and (i.Item.IsItem(&type))) then
begin
closest := i;
closestDistance := myDistance;
end;
end;
Result := closest;
end;
method UTMap.GetNearestItem(&type: AmmoType): UTItemPoint;
begin
Result := GetNearestItem(&type, _theBot.Location, nil);
end;
method UTMap.GetNearestItem(&type: AmmoType; toExclude: UTItemPoint): UTItemPoint;
begin
Result := GetNearestItem(&type, _theBot.Location, toExclude);
end;
method UTMap.GetNearestItem(&type: AmmoType; location: UTVector): UTItemPoint;
begin
Result := GetNearestItem(&type, location, nil);
end;
method UTMap.GetNearestItem(&type: AmmoType; location: UTVector; toExclude: UTItemPoint): UTItemPoint;
begin
var closest: UTItemPoint := nil;
var closestDistance: Single := -1;
for each i: UTItemPoint in Self._itemList do
begin
var myDistance: Single := i.Location.DistanceFrom(location);
if ((i <> toExclude) and (myDistance < closestDistance < 0) and (i.Item.IsItem(&type))) then
begin
closest := i;
closestDistance := myDistance
end;
end;
Result := closest;
end;
method UTMap.GetNearestItem(&type: ArmorType): UTItemPoint;
begin
Result := GetNearestItem(&type, _theBot.Location, nil);
end;
method UTMap.GetNearestItem(&type: ArmorType; toExclude: UTItemPoint): UTItemPoint;
begin
Result := GetNearestItem(&type, _theBot.Location, toExclude);
end;
method UTMap.GetNearestItem(&type: ArmorType; location: UTVector): UTItemPoint;
begin
Result := GetNearestItem(&type, location, nil);
end;
method UTMap.GetNearestItem(&type: ArmorType; location: UTVector; toExclude: UTItemPoint): UTItemPoint;
begin
var closest: UTItemPoint := nil;
var closestDistance: Single := -1;
for each i: UTItemPoint in Self._itemList do
begin
var myDistance: Single := i.Location.DistanceFrom(location);
if ((i <> toExclude) and (myDistance < closestDistance < 0) and (i.Item.IsItem(&type))) then
begin
closest := i;
closestDistance := myDistance
end;
end;
Result := closest;
end;
constructor UTMap(theBot: UTBotSelfState);
begin
Self._theBot := theBot;
end;
method UTMap.get_NavPoints: List<UTNavPoint>;
begin
Result := Self._navList;
end;
method UTMap.get_InvItems: List<UTItemPoint>;
begin
Result := Self._itemList;
end;
end.
|
program const2;
const max = 100;
min = max div 2;
var i, j: integer ;
function soma(a,b : integer):integer;
const inutil = max div min;
(* const inutil = max+i+a; *) (* o fpc não aceia isto, mas *)
(* seu compilador tem que aceitar! *)
begin
soma:=inutil;
end;
begin
i:=min;
while i <= max do
begin
j:=soma(i,max);
i:=i+1;
end;
writeln (j) ;
end.
|
unit RegExpressionsUtil;
interface
type
TRegularExpressionEngine = class
public
class function IsMatch(const Input, Pattern: string): boolean;
class function IsValidEmail(const EmailAddress: string): boolean;
end;
implementation
uses
RegularExpressions;
{ TRegularExpressionEngine }
class function TRegularExpressionEngine.IsMatch(const Input,
Pattern: string): boolean;
begin
Result := TRegEx.IsMatch(Input, Pattern);
end;
class function TRegularExpressionEngine.IsValidEmail(
const EmailAddress: string): boolean;
const
EMAIL_REGEX = '^((?>[a-zA-Z\d!#$%&''*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])'
+'[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)'
+'(?>\.?[a-zA-Z\d!#$%&''*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])'
+'[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]'
+'{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d))'
+'{4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\'
+'[\x01-\x7f])+)\])(?(angle)>)$';
begin
Result := IsMatch(EmailAddress, EMAIL_REGEX);
end;
end.
|
unit data_type;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, contnrs, file_data_type;
type
{ TCategory }
TCategory = Class(TObjectList)
private
FName: String;
FHtmlPath: String;
procedure SetName(AName: String);
function GetName: String;
procedure SetActionItem(Index: Integer; AObject: TAction);
function GetActionItem(Index: Integer): TAction;
public
property Name: String read GetName write SetName;
property Actions[Index: Integer]: TAction read GetActionItem write SetActionItem; default;
end;
TLocationName=(BuiltInLocation, SystemLocation, UserLocation, CustomLocation, CheckListLibraryLocation);
{ TLocation }
TLocation = Class(TObjectList)
private
FPath: String;
FName: TLocationName;
FHtmlPath: String;
procedure SetPath(APath: String);
function GetPath: String;
procedure SetName(AName: TLocationName);
function GetName: TLocationName;
procedure SetCategoryItem(Index: Integer; AObject: TCategory);
function GetCategoryItem(Index: Integer): TCategory;
public
property Path: String read GetPath write SetPath;
property Name: TLocationName read GetName write SetName;
property Categorys[Index: Integer]: TCategory read GetCategoryItem write SetCategoryItem; default;
end;
implementation
{ TCategory }
procedure TCategory.SetName(AName: String);
begin
end;
function TCategory.GetName: String;
begin
end;
procedure TCategory.SetActionItem(Index: Integer; AObject: TAction);
begin
end;
function TCategory.GetActionItem(Index: Integer): TAction;
begin
end;
{ TLocation }
procedure TLocation.SetPath(APath: String);
begin
end;
function TLocation.GetPath: String;
begin
end;
procedure TLocation.SetName(AName: TLocationName);
begin
end;
function TLocation.GetName: TLocationName;
begin
end;
procedure TLocation.SetCategoryItem(Index: Integer; AObject: TCategory);
begin
end;
function TLocation.GetCategoryItem(Index: Integer): TCategory;
begin
end;
end.
|
unit frmReceiveBenchMark;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, ValEdit;
type
TReceiveBenchMarkForm = class(TForm)
GFTypeEditor: TValueListEditor;
btnRefresh: TButton;
btnSave: TButton;
btnClose: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnRefreshClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure GFTypeEditorValidate(Sender: TObject; ACol, ARow: Integer;
const KeyName, KeyValue: String);
private
{ Private declarations }
public
{ Public declarations }
end;
var
ReceiveBenchMarkForm: TReceiveBenchMarkForm;
implementation
uses ServerDllPub, uGlobal, frmMain, uShowMessage, uLogin, uDictionary;
{$R *.dfm}
procedure TReceiveBenchMarkForm.FormCreate(Sender: TObject);
begin
Dictionary.cds_ReceiveBenchMarkList.Close;
TGlobal.FillItemsFromDataSet(Dictionary.cds_ReceiveBenchMarkList, 'GF_Type', 'Quantity', '=', GFtYPEEditor.Strings);
end;
procedure TReceiveBenchMarkForm.FormDestroy(Sender: TObject);
begin
ReceiveBenchMarkForm := nil;
end;
procedure TReceiveBenchMarkForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TReceiveBenchMarkForm.btnRefreshClick(Sender: TObject);
begin
Dictionary.cds_ReceiveBenchMarkList.Close;
TGlobal.FillItemsFromDataSet(Dictionary.cds_ReceiveBenchMarkList, 'GF_Type', 'Quantity', '=', GFTypeEditor.Strings);
end;
procedure TReceiveBenchMarkForm.btnSaveClick(Sender: TObject);
var
vData: OleVariant;
iCount,i: Integer;
sErrorMsg: WideString;
begin
iCount := GFTypeEditor.RowCount - 1;
vData := VarArrayCreate([0, iCount-1], VarVariant);
for i := 0 to iCount - 1 do
vData[i] := varArrayOf([GFTypeEditor.Strings[i],Login.LoginName]);
FNMServerObj.SaveReceiveBenchMark(vData,iCount,sErrorMsg);
if sErrorMsg <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg,mtError);
Exit;
end;
TMsgDialog.ShowMsgDialog('保存数据成功', mtInformation);
end;
procedure TReceiveBenchMarkForm.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TReceiveBenchMarkForm.GFTypeEditorValidate(Sender: TObject; ACol,
ARow: Integer; const KeyName, KeyValue: String);
begin
TGlobal.CheckValueIsNumeric(KeyValue,'请输入数字');
end;
end.
|
unit BitwiseAndOpTest;
interface
uses
DUnitX.TestFramework,
uIntXLibTypes,
uIntX,
uConstants;
type
[TestFixture]
TBitwiseAndOpTest = class(TObject)
public
[Test]
procedure ShouldBitwiseAndTwoIntX();
[Test]
procedure ShouldBitwiseAndPositiveAndNegativeIntX();
[Test]
procedure ShouldBitwiseAndTwoNegativeIntX();
[Test]
procedure ShouldBitwiseAndIntXAndZero();
[Test]
procedure ShouldBitwiseAndTwoBigIntX();
end;
implementation
[Test]
procedure TBitwiseAndOpTest.ShouldBitwiseAndTwoIntX();
var
int1, int2, result: TIntX;
begin
int1 := TIntX.Create(11);
int2 := TIntX.Create(13);
result := int1 and int2;
Assert.IsTrue(result.Equals(9));
end;
[Test]
procedure TBitwiseAndOpTest.ShouldBitwiseAndPositiveAndNegativeIntX();
var
int1, int2, result: TIntX;
begin
int1 := TIntX.Create(-11);
int2 := TIntX.Create(13);
result := int1 and int2;
Assert.IsTrue(result.Equals(9));
end;
[Test]
procedure TBitwiseAndOpTest.ShouldBitwiseAndTwoNegativeIntX();
var
int1, int2, result: TIntX;
begin
int1 := TIntX.Create(-11);
int2 := TIntX.Create(-13);
result := int1 and int2;
Assert.IsTrue(result.Equals(-9));
end;
[Test]
procedure TBitwiseAndOpTest.ShouldBitwiseAndIntXAndZero();
var
int1, int2, result: TIntX;
begin
int1 := TIntX.Create(11);
int2 := TIntX.Create(0);
result := int1 and int2;
Assert.IsTrue(result.Equals(0));
end;
[Test]
procedure TBitwiseAndOpTest.ShouldBitwiseAndTwoBigIntX();
var
temp1, temp2, temp3: TIntXLibUInt32Array;
int1, int2, result: TIntX;
begin
SetLength(temp1, 4);
temp1[0] := 11;
temp1[1] := 6;
temp1[2] := TConstants.MaxUInt32Value;
temp1[3] := TConstants.MaxUInt32Value;
SetLength(temp2, 3);
temp2[0] := 13;
temp2[1] := 3;
temp2[2] := 0;
SetLength(temp3, 2);
temp3[0] := 9;
temp3[1] := 2;
int1 := TIntX.Create(temp1, False);
int2 := TIntX.Create(temp2, False);
result := int1 and int2;
Assert.IsTrue(result.Equals(TIntX.Create(temp3, False)));
end;
initialization
TDUnitX.RegisterTestFixture(TBitwiseAndOpTest);
end.
|
unit Model.Mapper;
interface
uses
System.Classes, System.Generics.Collections, ZDataSet;
type
IReader = interface(IInterface)
function ReadString(const Name: string; const DefaultValue: string): string;
function ReadInteger(const Name: string; const DefaultValue: Integer): Integer;
function ReadFloat(const Name: string; const DefaultValue: Double): Double;
function ReadDate(const Name: string; const DefaultValue: TDate): TDate;
function ReadDateTime(const Name: string; const DefaultValue: TDateTime): TDateTime;
function ReadTime(const Name: string; const DefaultValue: TTime): TTime;
end;
IWriter = interface(IInterface)
procedure WriteString(const Name: string; const Value: string);
procedure WriteInteger(const Name: string; const Value: Integer);
procedure WriteFloat(const Name: string; const Value: Double);
procedure WriteDate(const Name: string; const Value: TDate);
procedure WriteDateTime(const Name: string; const Value: TDateTime);
procedure WriteTime(const Name: string; const Value: TTime);
end;
IReadable = interface(IInterface)
procedure Read(Reader: IReader);
end;
IWritable = interface(IInterface)
procedure Write(Writer: IWriter);
end;
TMap = class
Key: string;
Value: Variant;
end;
TMapValues = class(TObjectList<TMap>)
published
function Put(const Name: string; Value: Variant): TMapValues;
end;
TValuesReader = class(TInterfacedObject, IReader)
private
FQuery: TZQuery;
published
property Query: TZQuery read FQuery write FQuery;
function ReadString(const Name: string; const DefaultValue: string): string;
function ReadInteger(const Name: string; const DefaultValue: Integer): Integer;
function ReadFloat(const Name: string; const DefaultValue: Double): Double;
function ReadDate(const Name: string; const DefaultValue: TDate): TDate;
function ReadDateTime(const Name: string; const DefaultValue: TDateTime): TDateTime;
function ReadTime(const Name: string; const DefaultValue: TTime): TTime;
destructor Destroy; overload;
end;
TValuesWriter = class(TInterfacedObject, IWriter)
private
FMapValues: TMapValues;
published
property MapValues: TMapValues read FMapValues write FMapValues;
procedure WriteString(const Name: string; const Value: string);
procedure WriteInteger(const Name: string; const Value: Integer);
procedure WriteFloat(const Name: string; const Value: Double);
procedure WriteDate(const Name: string; const Value: TDate);
procedure WriteDateTime(const Name: string; const Value: TDateTime);
procedure WriteTime(const Name: string; const Value: TTime);
destructor Destroy; overload;
end;
implementation
uses
System.SysUtils;
{ TValuesReader }
destructor TValuesReader.Destroy;
begin
FreeAndNil(FQuery);
inherited;
end;
function TValuesReader.ReadDate(const Name: string;
const DefaultValue: TDate): TDate;
begin
Result := Query.FieldByName(Name).AsDateTime;
end;
function TValuesReader.ReadDateTime(const Name: string;
const DefaultValue: TDateTime): TDateTime;
begin
Result := Query.FieldByName(Name).AsDateTime;
end;
function TValuesReader.ReadFloat(const Name: string;
const DefaultValue: Double): Double;
begin
Result := Query.FieldByName(Name).AsFloat;
end;
function TValuesReader.ReadInteger(const Name: string;
const DefaultValue: Integer): Integer;
begin
Result := Query.FieldByName(Name).AsInteger;
end;
function TValuesReader.ReadString(const Name, DefaultValue: string): string;
begin
Result := Query.FieldByName(Name).AsString;
end;
function TValuesReader.ReadTime(const Name: string;
const DefaultValue: TTime): TTime;
begin
Result := Query.FieldByName(Name).AsDateTime;
end;
{ TValuesWriter }
destructor TValuesWriter.Destroy;
begin
FreeAndNil(FMapValues);
inherited;
end;
procedure TValuesWriter.WriteDate(const Name: string; const Value: TDate);
begin
MapValues.Put(Name, Value);
end;
procedure TValuesWriter.WriteDateTime(const Name: string;
const Value: TDateTime);
begin
MapValues.Put(Name, Value);
end;
procedure TValuesWriter.WriteFloat(const Name: string; const Value: Double);
begin
MapValues.Put(Name, Value);
end;
procedure TValuesWriter.WriteInteger(const Name: string; const Value: Integer);
begin
MapValues.Put(Name, Value);
end;
procedure TValuesWriter.WriteString(const Name, Value: string);
begin
MapValues.Put(Name, Value);
end;
procedure TValuesWriter.WriteTime(const Name: string; const Value: TTime);
begin
MapValues.Put(Name, Value);
end;
{ TMapValues }
function TMapValues.Put(const Name: string; Value: Variant): TMapValues;
var
Map: TMap;
begin
Map := TMap.Create;
Map.Key := Name;
Map.Value := Value;
Self.Add(Map);
end;
end.
|
{this unit has a group of useful routines for use with OpenGL}
{ TsceneGL: a 3D scene,
has a group of entities and a group of lights.
Tlight: a light, has color, position and orientation.
by now only the color attributes have any effect.
T3dMouse: enables a normal mouse
to interact easily with one 3D object
By: Ricardo Sarmiento
delphiman@hotmail.com
}
unit nGL;
interface
uses Windows, Messages, SysUtils, Classes,
GL, GLU, n3DPolys;
type
TsceneGL = class(Tobject)
DC: HDC; {somewhat private}
HRC: HGLRC; {somewhat private}
WindowHandle: Thandle;
{handle to the host window, a Tpanel most times}
Entities: Tlist; {Availiable entities in the scene}
Lights: Tlist; {Availiable lights in the scene}
Active: boolean;
{true: InitRC has been called already}
Fperspective: boolean;
{true: use perspective projection,
false: use orthogonal projection}
Angle, DistNear, DistFar: single;
{values for Field-of-view angle,
distance to near clipping plane,
distance to far clipping plane}
texturing: boolean;
{true: use textures and texture information,
false: donīt use textures}
BackR, BackG, BackB: float;
{Background color (RGB), between 0.0 and 1.0 }
fogColor: array[0..3] of glFloat;
{fog color (RGBA), between 0.0 and 1.0 }
fogDensity, fogMinDist, fogMaxDist: float;
fogEnabled: boolean;
fogtype: GLint;
constructor create; {creates a new scene}
destructor destroy; override;
{donīt call this directly, call free instead}
{initialization of the Rendering Context,
receives the handle of the
display control, frecuently it is a Tpanel}
procedure InitRC(iHandle: THandle);
procedure Redraw; {redraw scene}
{set values for the pixelīs format.
donīt call this Function directly,
call instead InitRC.}
procedure SetDCPixelFormat;
{Free all resources taken by InitRC.
donīt call this Function directly}
procedure ReleaseRC;
{reflects changes in the width and height
(ancho,alto) of the display control}
procedure UpdateArea(width, height: integer);
{Set the perspective values for
Field-of-view angle,
distance to near clipping plane,
distance to far clipping plane}
procedure SetPerspective(iAngle, iDistNear, iDistFar: single);
end; {TsceneGL}
Tlight = class(Tobject)
Source: Tvertex;
{position and orientation of the light,
not yet implemented}
Fambient,
FdIffuse,
Fspecular: array[0..3] of GLfloat;
{ambient, dIffuse and specular components}
Number: LongInt;
{number of the light, from 1 to 8}
constructor Create(num: Byte);
{create a new, white Ambient light. num goes from 1 to 8}
destructor Destroy; override;
{donīt call directly, call instead free}
procedure Ambient(r, g, b, a: GLfloat);
{change the Ambient component of the light}
procedure DIffuse(r, g, b, a: GLfloat);
{change the dIffuse component of the light}
procedure Specular(r, g, b, a: GLfloat);
{change the specular component of the light}
procedure Redraw;
{executes the OpenGL code for this light}
end; {Tlight}
T3dMouse = class(Tobject)
{ease manipulation of 3D objects with the mouse}
Button1, {left button on mouse}
Button2: boolean; {right button on mouse}
Mode: integer; {movement mode:
1-move x,y-z,
2-turn rx,ry-rz
3-turn rx,ry-rz+move z.}
Entity: Tentity;
{points to the entity to be modIfied, just one at a time}
Start: array[1..6] of single;
{x,y,z - rx,ry,rz
saves the initial position when dragging mouse}
Scaling: array[1..6] of single;
{x,y,z - rx,ry,rz
stores the speed relations between mouse and 3D}
BlockStatus: array[1..6] of boolean;
{x,y,z - rx,ry,rz which movements are blocked}
constructor Create(iEntity: Tentity);
{iEntity is the pointer to one entity in the scene}
procedure Move(x, y: single; Botones: TShIftState);
{move or turn the entity according to the mode}
procedure Scale(x, y, z, rx, ry, rz: single);
{controls the relative speed between the mouse and the object}
procedure Block(num: integer; valor: boolean);
{blocks movement and/or rotation on any of 6 axis.}
procedure FindVertex(x, y: integer;
Scene: TsceneGL;
var pt: Tvertex);
{return a pointer to the vertex which was nearer to the mouse}
{Scene is the scene to be evaluated,
pt is the chosen vertex,
can be nil If none was found under the mouse}
{x,y are the coordinates of the mouse}
end; {num goes from 1 to 6,
valor=true:block,
valor=false: donīt block movement}
const
MaxHits = 200;
var
xxx, yyy, nnn: integer;
numFound: integer;
VertexHits: array[1..MaxHits] of integer;
{This function can convert a BMP file into a RGBA file}
{parameters: BMPname: name of the BMP file,
RGBAname: name of the new file,
transparent: color that will be treated as transparent}
function ConvertBMP(BMPname: string;
RGBAname: string;
Transparent: longint): integer;
{this is to avoid certain problems with borland tools.
donīt call them yourself}
function MaskExceptions: Pointer;
procedure UnmaskExceptions(OldMask: Pointer);
implementation
constructor TsceneGL.create;
begin
inherited create;
Entities := Tlist.create;
Lights := Tlist.create;
Active := false;
Fperspective := true;
fogEnabled := false;
Angle := 30; {degrees for Field-of-view angle}
DistNear := 1; {1 unit of distance to near clipping plane}
DistFar := 100; {distance to far clipping plane}
texturing := true; {use textures}
end;
destructor TsceneGL.destroy;
begin
if Active then
ReleaseRC;
Lights.free;
Entities.free;
inherited destroy;
end;
procedure TsceneGL.InitRC;
begin
{set the area where the OpenGL rendering will take place}
WindowHandle := iHandle;
DC := GetDC(WindowHandle);
SetDCPixelFormat;
HRC := wglCreateContext(DC);
wglMakeCurrent(DC, HRC);
{ enable depht testing and back face rendering}
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING); {enable Lights}
Active := True;
end;
procedure TsceneGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
with pfd do begin
nSize := sizeof(pfd); // Size of this structure
nVersion := 1; // Version number
dwFlags := PFD_DRAW_TO_WINDOW or
PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER; // Flags
iPixelType := PFD_TYPE_RGBA; // RGBA pixel values
cColorBits := 24; // 24-bit color
cDepthBits := 32; // 32-bit depth buffer
iLayerType := PFD_MAIN_PLANE; // Layer type
end;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
DescribePixelFormat(DC, nPixelFormat,
sizeof(TPixelFormatDescriptor), pfd);
end;
procedure TsceneGL.ReleaseRC;
begin
wglMakeCurrent(0, 0);
wglDeleteContext(HRC);
ReleaseDC(WindowHandle, DC);
Active := False;
end;
procedure TsceneGL.UpdateArea;
var
gldAspect: GLdouble;
ratio, range: GlFloat;
begin
{ redefine the visible volume
and the viewport when the windowīs size is modIfied}
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
if Fperspective then
begin
gldAspect := width / height;
gluPerspective(Angle, // Field-of-view angle
gldAspect, // Aspect ratio of viewing volume
DistNear, // Distance to near clipping plane
DistFar); // Distance to far clipping plane
end
else
begin { Orthogonal projection}
range := 6;
if width <= height then
begin
ratio := height / width;
GlOrtho(-range, range,
-range * ratio,
range * ratio,
-range * 4, range * 4);
end
else
begin
ratio := width / height;
GlOrtho(-range * ratio,
range * ratio,
-range, range,
-range * 4, range * 4);
end;
end;
glViewport(0, 0, width, height);
end;
procedure TsceneGL.Redraw;
const
glfMaterialColor: array[0..3] of GLfloat = (0.5, 1.0, 0.5, 1.0);
var
i, num: integer;
ps: TPaintStruct;
pp: Pointer;
begin
if Active then
begin
{initialization}
pp := MaskExceptions;
BeginPaint(WindowHandle, ps);
{place Lights}
i := 0;
num := Lights.count;
while i < num do
begin
Tlight(Lights.items[i]).Redraw;
inc(i);
end;
{clear depht and color buffers}
glclearcolor(backR, backG, backB, 1);
{specify background color}
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
{Clear the rendering area}
glenable(gl_color_material);
{tell OpenGL to pay attention to GlColor orders}
if fogEnabled then
begin
glenable(GL_fog);
{too slow: glhint(gl_fog_hint, gl_nicest);}
{good fog, but a little slow}
glfogi(gl_fog_mode, fogtype);
glfogfv(gl_fog_color, @fogColor);
if fogtype <> GL_linear then
{density doesnt work with linear fog}
glfogf(gl_fog_density, FogDensity);
glfogf(GL_fog_start, fogMinDist);
glfogf(GL_fog_end, fogMaxDist);
end else
gldisable(GL_fog);
if texturing then
begin
gldisable(GL_texture_1d);
glenable(gl_texture_2d);
end
else
begin
glDisable(GL_texture_1d);
glDisable(gl_texture_2d);
end;
if PutNames then
begin
glInitNames;
{init the name stack,
not necessary If your objects arenīt named}
glPushName(0);
{init the name stack}
end;
{draw entities}
i := 0;
num := Entities.count;
while i < num do
begin
Tentity(Entities.items[i]).Redraw;
inc(i);
end;
{finalization}
{swap the rendering buffers so there is no flickering}
SwapBuffers(DC);
EndPaint(WindowHandle, ps);
UnmaskExceptions(pp);
end;
end;
procedure TsceneGL.SetPerspective;
begin
Angle := iAngle;
DistNear := iDistNear;
DistFar := iDistFar;
end;
{by default a light is created white }
constructor Tlight.Create;
begin
inherited create;
Source := Tvertex.create(nil, 0, 0, 0);
{light with no orientation...}
Source.Point := TGLpoint.Create(0, 0, 0);
{...and placed in the center of the scene}
Ambient(0.5, 0.5, 0.5, 1);
DIffuse(0.25, 0.25, 0.25, 1);
Specular(0.1, 0.1, 0.1, 1);
case num of
1: Number := GL_Light0;
2: Number := GL_Light1;
3: Number := GL_Light2;
4: Number := GL_Light3;
5: Number := GL_Light4;
6: Number := GL_Light5;
7: Number := GL_Light6;
8: Number := GL_Light7;
end; {case}
end;
destructor Tlight.destroy;
begin
Source.point.free;
Source.free;
end;
procedure Tlight.Ambient;
begin
Fambient[0] := r;
Fambient[1] := g;
Fambient[2] := b;
Fambient[3] := a;
end;
procedure Tlight.DIffuse;
begin
fDIffuse[0] := r;
fDIffuse[1] := g;
fDIffuse[2] := b;
fDIffuse[3] := a;
end;
procedure Tlight.Specular;
begin
Fspecular[0] := r;
Fspecular[1] := g;
Fspecular[2] := b;
Fspecular[3] := a;
end;
procedure Tlight.Redraw;
begin
glLightfv(Number, GL_AMBIENT, @Fambient);
glLightfv(Number, GL_DIfFUSE, @fDIffuse);
glLightfv(Number, GL_SPECULAR, @Fspecular);
glEnable(Number); {enable light number N}
end;
constructor T3dMouse.Create;
var
i: integer;
begin
inherited create;
Entity := iEntity;
Mode := 3;
{this is the mode used by defect,
just because it fits my needs}
Button1 := false;
Button2 := false;
for i := 1 to 6 do
BlockStatus[i] := false;
end;
procedure T3dMouse.Move;
begin
if assigned(Entity) then
begin
if not Button1 then
begin
if ssLeft in botones then
begin
if mode = 1 then {X,Y,Z}
begin
Start[1] := x - Entity.Position[1] / Scaling[1]; {X}
Start[2] := y - Entity.Position[2] / Scaling[2]; {Y}
end;
if mode in [2, 3] then {2:rx,ry,rz 3:rx,ry,rz,Z}
begin
Start[6] := x - Entity.rotation[3] / Scaling[6]; {rx}
Start[4] := y - Entity.rotation[1] / Scaling[4]; {ry}
end;
Button1 := true;
end;
end
else
begin
if ssLeft in botones then
begin
if mode = 1 then
begin
if not BlockStatus[1] then
Entity.Position[1] := (x - Start[1]) * Scaling[1]; {X}
if not BlockStatus[2] then
Entity.Position[2] := (y - Start[2]) * Scaling[2]; {Y}
end;
if mode in [2, 3] then
begin
if not BlockStatus[4] then
Entity.rotation[3] := (x - Start[6]) * Scaling[6]; {rx}
if not BlockStatus[5] then
Entity.rotation[1] := (y - Start[4]) * Scaling[4]; {ry}
end;
end
else
Button1 := false;
end;
if not Button2 then
begin
if ssRight in botones then
begin
if mode in [1, 3] then
Start[3] := y - Entity.Position[3] / Scaling[3]; {z}
if mode in [2, 3] then
Start[5] := x - Entity.rotation[2] / Scaling[5]; {rz}
Button2 := true;
end;
end
else
begin
if ssRight in botones then
begin
if mode in [1, 3] then
if not BlockStatus[3] then
Entity.Position[3] := (y - Start[3]) * Scaling[3]; {Z}
if mode in [2, 3] then
if not BlockStatus[6] then
Entity.rotation[2] := (x - Start[5]) * Scaling[5]; {rz}
end
else
Button2 := false;
end;
end;
end;
procedure T3dMouse.Scale;
begin
Scaling[1] := x;
Scaling[2] := y;
Scaling[3] := z;
Scaling[4] := rx;
Scaling[5] := ry;
Scaling[6] := rz;
end;
procedure T3dMouse.Block;
begin
if num in [1..6] then
BlockStatus[num] := valor;
end;
procedure T3dMouse.FindVertex;
const
tambuffer = 8000; {8000 items reserved for the rendering buffer}
radio = 15; {this is the search radius}
var
buffer: array[0..tamBuffer] of GLfloat;
size, i, j, count: integer;
nx, ny: integer;
PreviousPutNames: boolean;
ActualVertex: LongInt;
begin
PreviousPutNames := PutNames;
{preserve the previous value of PutNames}
PutNames := true; {put names on each vertex}
numFound := 0;
GlFeedBackBuffer(tamBuffer, GL_2D, @buffer);
GlRenderMode(GL_feedBack);
Scene.Redraw;
size := GlRenderMode(GL_render);
{now that we got the 2D coordinates of each vertex,
find which vertex is near}
i := 0;
try
while i < size do
begin
if buffer[i] = GL_Pass_Through_token then
{the G.P.T.T. is a marker to divide the buffer in sections}
if buffer[i + 1] = Entity.id then
{this is the entity we are dealing with}
begin
inc(i, 2);
// continue cycling until we find another Object marker:
while (buffer[i] = GL_Pass_Through_token) do
begin
ActualVertex := round(Buffer[i + 1]);
if buffer[i + 2] = GL_Polygon_Token then
{this is a polygon, letīs check it out}
begin
count := trunc(buffer[i + 3]);
inc(i, 4);
for j := 0 to count - 1 do
{letīs take a look at each vertex of this polygon}
begin
nx := round(buffer[i]);
{x coordinate of a vertex}
ny := round(buffer[i + 1]);
{y coordinate of a vertex}
if (nx + radio > x) and (nx - radio < x)
and (ny + radio > y) and (ny - radio < y)
and (NumFound < MaxHits) then
begin
inc(numFound);
VertexHits[numFound] := ActualVertex + j;
end;
inc(i, 2); {x and y}
end;
end
else
inc(i, 2);
end;
end;
inc(i);
end;
except
end;
{restore the previous value of PutNames}
PutNames := PreviousPutNames;
end;
{MWMWMWMWMWMWMWMWMW END OF CLASS IMPLEMENTATION WMWMWMWMWM}
function MaskExceptions: Pointer;
var
OldMask: Pointer;
begin
asm
fnstcw WORD PTR OldMask;
mov eax, OldMask;
or eax, $3f;
mov WORD PTR OldMask+2,ax;
fldcw WORD PTR OldMask+2;
end;
result := OldMask;
end;
procedure UnmaskExceptions(OldMask: Pointer);
begin
asm
fnclex;
fldcw WORD PTR OldMask;
end;
end;
function ConvertBMP(BMPname: string;
RGBAname: string;
Transparent: longint): integer;
begin
{this will convert a RGB bmp to a RGBA bmp,
it is not ready yet}
result := 0;
end;
end.
|
unit shader_m;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, gl, GLext, matrix;
type
{ TShader }
TShader = class
public
ID: GLuint;
constructor Create(const vertexPath, fragmentPath: string);
procedure use();
procedure setBool(const name: string; value: Boolean);
procedure setInt(const name: string; value: GLint);
procedure setFloat(const name: string; value: GLfloat);
procedure setVec2(const name:string; const value: Tvector2_single);
procedure setVec2(const name:string; x, y: Single);
procedure setVec3(const name:string; const value: Tvector3_single);
procedure setVec3(const name:string; x, y, z: Single);
procedure setVec4(const name:string; const value: Tvector4_single);
procedure setVec4(const name:string; x, y, z, w: Single);
procedure setMat2(const name:string; const value: Tmatrix2_single);
procedure setMat3(const name:string; const value: Tmatrix3_single);
procedure setMat4(const name:string; const value: Tmatrix4_single);
private
procedure checkCompileErrors(shader: GLuint; type_: string);
end;
implementation
{ TShader }
// constructor generates the shader on the fly
// ------------------------------------------------------------------------
constructor TShader.Create(const vertexPath, fragmentPath: string);
var
vShaderFile: TStringList;
fShaderFile: TStringList;
vShaderCode: PGLchar;
fShaderCode: PGLchar;
vertexCode: String;
fragmentCode: String;
vertex: GLuint;
fragment: GLuint;
begin
vShaderFile := nil;
fShaderFile := nil;
try
try
vShaderFile := TStringList.Create;
fShaderFile := TStringList.Create;
vShaderFile.LoadFromFile(vertexPath);
fShaderFile.LoadFromFile(fragmentPath);
vertexCode := vShaderFile.Text;
fragmentCode := fShaderFile.Text;
except
Writeln('ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ');
end;
finally
FreeAndNil(vShaderFile);
FreeAndNil(fShaderFile);
end;
vShaderCode := PGLchar(vertexCode);
fShaderCode := PGLchar(fragmentCode);
// 2. compile shaders
// vertex shader
vertex := glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, @vShaderCode, nil);
glCompileShader(vertex);
checkCompileErrors(vertex, 'VERTEX');
// fragment Shader
fragment := glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, @fShaderCode, nil);
glCompileShader(fragment);
checkCompileErrors(fragment, 'FRAGMENT');
// shader Program
ID := glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
checkCompileErrors(ID, 'PROGRAM');
// delete the shaders as they're linked into our program now and no longer necessary
glDeleteShader(vertex);
glDeleteShader(fragment);
end;
// activate the shader
// ------------------------------------------------------------------------
procedure TShader.use();
begin
glUseProgram(ID);
end;
// utility uniform functions
// ------------------------------------------------------------------------
procedure TShader.setBool(const name: string; value: Boolean);
begin
glUniform1i(glGetUniformLocation(ID, PGLchar(name)), GLInt(value));
end;
// ------------------------------------------------------------------------
procedure TShader.setInt(const name: string; value: GLint);
begin
glUniform1i(glGetUniformLocation(ID, PGLchar(name)), value);
end;
// ------------------------------------------------------------------------
procedure TShader.setFloat(const name: string; value: GLfloat);
begin
glUniform1f(glGetUniformLocation(ID, PGLchar(name)), value);
end;
procedure TShader.setVec2(const name: string; const value: Tvector2_single);
begin
glUniform2fv(glGetUniformLocation(ID, PGLchar(name)), 1, @value.data);
end;
procedure TShader.setVec2(const name: string; x, y: Single);
begin
glUniform2f(glGetUniformLocation(ID, PGLchar(name)), x, y);
end;
procedure TShader.setVec3(const name: string; const value: Tvector3_single);
begin
glUniform3fv(glGetUniformLocation(ID, PGLchar(name)), 1, @value.data);
end;
procedure TShader.setVec3(const name: string; x, y, z: Single);
begin
glUniform3f(glGetUniformLocation(ID, PGLchar(name)), x, y, z);
end;
procedure TShader.setVec4(const name: string; const value: Tvector4_single);
begin
glUniform4fv(glGetUniformLocation(ID, PGLchar(name)), 1, @value.data);
end;
procedure TShader.setVec4(const name: string; x, y, z, w: Single);
begin
glUniform4f(glGetUniformLocation(ID, PGLchar(name)), x, y, z, w);
end;
procedure TShader.setMat2(const name: string; const value: Tmatrix2_single);
begin
glUniformMatrix2fv(glGetUniformLocation(ID, PGLchar(name)), 1, GL_FALSE, @value.data);
end;
procedure TShader.setMat3(const name: string; const value: Tmatrix3_single);
begin
glUniformMatrix3fv(glGetUniformLocation(ID, PGLchar(name)), 1, GL_FALSE, @value.data);
end;
procedure TShader.setMat4(const name: string; const value: Tmatrix4_single);
begin
glUniformMatrix4fv(glGetUniformLocation(ID, PGLchar(name)), 1, GL_FALSE, @value.data);
end;
// utility function for checking shader compilation/linking errors.
// ------------------------------------------------------------------------
procedure TShader.checkCompileErrors(shader: GLuint; type_: string);
var
success: GLint;
infoLog : array [0..1023] of GLchar;
begin
if type_ <> 'PROGRAM' then
begin
glGetShaderiv(shader, GL_COMPILE_STATUS, @success);
if success <> GL_TRUE then
begin
glGetShaderInfoLog(shader, 1024, nil, @infoLog); //in static array @infoLog = @infoLog[0]
Writeln('ERROR::SHADER_COMPILATION_ERROR of type: ' + type_ + LineEnding + infoLog + LineEnding + '-- --------------------------------------------------- -- ');
end;
end
else
begin
glGetProgramiv(shader, GL_LINK_STATUS, @success);
if success <> GL_TRUE then
begin
glGetProgramInfoLog(shader, 1024, nil, @infoLog);
Writeln('ERROR::PROGRAM_COMPILATION_ERROR of type: ' + type_ + LineEnding + infoLog + LineEnding + '-- --------------------------------------------------- -- ');
end;
end;
end;
end.
|
unit uFrmCreateModel;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel, cxClasses,
cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, DBClient;
type
TFrmCreateModel = class(TForm)
Panel1: TPanel;
btnClose: TBitBtn;
btnSave: TBitBtn;
btnOpen: TBitBtn;
gridModelList: TcxGrid;
gridModelListDBTableView: TcxGridDBTableView;
gridModelListLevel1: TcxGridLevel;
gridModelListDBTableViewCategory: TcxGridDBColumn;
gridModelListDBTableViewModel: TcxGridDBColumn;
gridModelListDBTableViewDescription: TcxGridDBColumn;
gridModelListDBTableViewCostPrice: TcxGridDBColumn;
gridModelListDBTableViewSalePrice: TcxGridDBColumn;
gridModelListDBTableViewQty: TcxGridDBColumn;
gridModelListDBTableViewBarcode: TcxGridDBColumn;
pnlCategory: TPanel;
cbxTipoNegocio: TComboBox;
SV: TSaveDialog;
OP: TOpenDialog;
btnCopySave: TButton;
cdsNewModel: TClientDataSet;
cdsNewModelCategory: TStringField;
cdsNewModelModel: TStringField;
cdsNewModelDescription: TStringField;
cdsNewModelCostPrice: TCurrencyField;
cdsNewModelSalePrice: TCurrencyField;
cdsNewModelQty: TFloatField;
cdsNewModelBarcode: TStringField;
cdsNewModelSizeAndColor: TBooleanField;
Button1: TButton;
cdsNewModelIDModel: TIntegerField;
procedure btnCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cbxTipoNegocioChange(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
procedure btnCopySaveClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
procedure Start;
end;
implementation
uses uDMExport, uDMParent;
{$R *.dfm}
procedure TFrmCreateModel.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TFrmCreateModel.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmCreateModel.Start;
begin
DMExport.OpenCategory;
DMExport.OpenModel;
ShowModal;
end;
procedure TFrmCreateModel.cbxTipoNegocioChange(Sender: TObject);
begin
DMExport.CloseCategory;
DMExport.OpenCategory;
DMExport.LoadCategories(cbxTipoNegocio.Text);
end;
procedure TFrmCreateModel.btnSaveClick(Sender: TObject);
var
FFileName : String;
FFileData : TStringList;
begin
SV.InitialDir := DMExport.LocalPath + 'Category';
SV.FileName := cbxTipoNegocio.Text + '.xml';
if SV.Execute then
begin
FFileData := TStringList.Create;
try
FFileName := SV.FileName;
FFileData.Text := DMExport.cdsModel.XMLData;
FFileData.SaveToFile(FFileName);
finally
FreeAndNil(FFileData);
end;
end;
end;
procedure TFrmCreateModel.btnOpenClick(Sender: TObject);
var
FFileName : String;
FFileData : TStringList;
begin
OP.InitialDir := DMExport.LocalPath + 'Category';
if OP.Execute then
begin
FFileData := TStringList.Create;
try
FFileName := OP.FileName;
FFileData.LoadFromFile(FFileName);
DMExport.cdsModel.XMLData := FFileData.Text;
finally
FreeAndNil(FFileData);
end;
end;
end;
procedure TFrmCreateModel.btnCopySaveClick(Sender: TObject);
var
FFileName : String;
FFileData : TStringList;
begin
SV.InitialDir := DMExport.LocalPath + 'Category';
SV.FileName := cbxTipoNegocio.Text + '.xml';
if SV.Execute then
begin
FFileData := TStringList.Create;
try
if not cdsNewModel.Active then
cdsNewModel.CreateDataSet;
DMExport.cdsModel.First;
while not DMExport.cdsModel.Eof do
begin
cdsNewModel.Append;
cdsNewModel.FieldByName('Category').Value := DMExport.cdsModel.FieldByName('Category').Value;
cdsNewModel.FieldByName('Barcode').Value := DMExport.cdsModel.FieldByName('Barcode').Value;
cdsNewModel.FieldByName('Model').Value := DMExport.cdsModel.FieldByName('Model').Value;
cdsNewModel.FieldByName('Description').Value := DMExport.cdsModel.FieldByName('Description').Value;
cdsNewModel.FieldByName('Qty').Value := DMExport.cdsModel.FieldByName('Qty').Value;
cdsNewModel.FieldByName('CostPrice').Value := DMExport.cdsModel.FieldByName('CostPrice').Value;
cdsNewModel.FieldByName('SalePrice').Value := DMExport.cdsModel.FieldByName('SalePrice').Value;
cdsNewModel.FieldByName('SizeAndColor').Value := DMExport.cdsModel.FieldByName('SizeAndColor').Value;
//DMExport.SizeAndColorCategory(DMExport.cdsModel.FieldByName('Category').Value,s1, s2);
cdsNewModel.Post;
DMExport.cdsModel.Next;
end;
FFileName := SV.FileName;
FFileData.Text := cdsNewModel.XMLData;
FFileData.SaveToFile(FFileName);
finally
FreeAndNil(FFileData);
cdsNewModel.Close;
end;
end;
end;
procedure TFrmCreateModel.Button1Click(Sender: TObject);
begin
DMExport.cdsModel.Edit;
DMExport.cdsModel.Delete;
{
Categoria := DMExport.cdsModel.FieldByName('Category').AsString;
DMExport.cdsModel.First;
while not DMExport.cdsModel.EOF do
begin
if DMExport.cdsModel.FieldByName('Category').AsString <> Categoria then
begin
DMExport.cdsModel.Edit;
DMExport.cdsModel.Delete;
end
else
Break;
DMExport.cdsModel.Next;
end;
}
end;
end.
|
unit ThCanvas;
interface
uses
DebugUtils,
System.Classes, System.SysUtils, System.Types, System.UITypes, System.UIConsts,
FMX.Types, FMX.Controls, FMX.Ani,
ThTypes, ThItem, ThZoomAnimation, ThAlertAnimation;
type
// {TODO} IThItemContainer를 상속받는게 맞을 지 검토 필요
// Viewer에서도 사용할까?
TThContents = class(TControl, IThItemContainer)
private
FTrackingPos: TPointF;
FZoomScale: Single;
procedure SetZoomScale(const Value: Single);
function GetScaledPoint: TPointF;
function GetItem(Index: Integer): TThItem;
function GetItemCount: Integer;
protected
procedure Paint; override;
function GetClipRect: TRectF; override;
function DoGetUpdateRect: TRectF; override;
procedure DoAddObject(const AObject: TFmxObject); override;
procedure DoRemoveObject(const AObject: TFmxObject); override;
public
constructor Create(AOwner: TComponent); override;
procedure AddTrackingPos(const Value: TPointF);
function FindParent(AChild: TThItem): TFMXObject;
procedure ContainChildren(AContainer: TThItem);
property ZoomScale: Single read FZoomScale write SetZoomScale;
property ScaledPoint: TPointF read GetScaledPoint;
property Items[Index: Integer]: TThItem read GetItem;
property ItemCount: Integer read GetItemCount;
end;
TThCanvas = class(TControl, IThCanvas, IThZoomObject)
private
FUseMouseTracking: Boolean;
FBgColor: TAlphaColor;
// 마우스가 마지막으로 이동한 거리
FLastDelta: TPointF;
FVertTrackAni,
FHorzTrackAni: TFloatAnimation;
FZoomAni: TZoomAni;
FTrackAnimated: Boolean;
FZoomAnimated: Boolean;
FAlert: TAlertAnimation;
FOnZoom: TNotifyEvent;
function GetViewPortPosition: TPosition;
function GetItemCount: Integer;
procedure SetBgColor(const Value: TAlphaColor);
function GetZoomScale: Single;
function GetViewPortSize: TSizeF;
procedure AlertMessage(msg: string);
function GetCenterPoint: TPointF;
protected
FContents: TThContents;
FMouseDownPos, // MouseDown 시 좌표
FMouseCurrPos: TPointF; // MouseMove 시 좌표
procedure Show; override;
procedure Paint; override;
procedure DoAddObject(const AObject: TFmxObject); override;
procedure DoZoom(AScale: Single; ATargetPos: TPointF);
procedure DoZoomHome;
procedure DoZoomIn(ATargetPos: TPointF); virtual;
procedure DoZoomOut(ATargetPos: TPointF); virtual;
procedure ClickCanvas; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Initialize;
// Interface method
function IsDrawingItem: Boolean; virtual;
function IsMultiSelected: Boolean; virtual;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseMove(Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); override;
procedure ZoomIn;
procedure ZoomOut;
procedure ZoomHome;
procedure ZoomInAtPoint(X, Y: Single);
procedure ZoomOutAtPoint(X, Y: Single);
property ZoomScale: Single read GetZoomScale;
property ViewPortPosition: TPosition read GetViewPortPosition;
property ViewPortSize: TSizeF read GetViewPortSize;
property ItemCount: Integer read GetItemCount;
property BgColor: TAlphaColor read FBgColor write SetBgColor;
property TrackAnimated: Boolean read FTrackAnimated write FTrackAnimated;
property ZoomAnimated: Boolean read FZoomAnimated write FZoomAnimated;
property CenterPoint: TPointF read GetCenterPoint;
property OnZoom: TNotifyEvent read FOnZoom write FOnZoom;
end;
implementation
uses
ThConsts, FMX.Forms, FMX.Graphics, ThResourceString;
{ TThContent }
procedure TThContents.AddTrackingPos(const Value: TPointF);
begin
FTrackingPos := Value;
Position.X := Position.X + Value.X;
Position.Y := Position.Y + Value.Y;
// Debug('AddTrackingPos: %f, %f', [Position.X, Position.Y]);
end;
procedure TThContents.ContainChildren(AContainer: TThItem);
var
I: Integer;
CurrItem: TThItem;
begin
AContainer.LastContainItems.Clear;
for I := 0 to ItemCount - 1 do
begin
CurrItem := Items[I];
if not Assigned(CurrItem) or (AContainer = CurrItem) then
Continue;
if AContainer.IsContain(CurrItem) then
// 여기서 Parent를 바꾸면 Items / ItemCount가 줄어듬
// CurrItem.Parent := AParent;
AContainer.LastContainItems.Add(CurrItem);
end;
for CurrItem in AContainer.LastContainItems do
begin
CurrItem.Parent := AContainer;
AContainer.ContainChildren(CurrItem);
end;
end;
constructor TThContents.Create(AOwner: TComponent);
begin
inherited;
FZoomScale := 1;
end;
procedure TThContents.DoAddObject(const AObject: TFmxObject);
var
Item: TThItem;
begin
if AObject is TThItem then
begin
Item := TThItem(AObject);
if Assigned(Item.BeforeParent) and (Item.BeforeParent is TThItem) then
Item.Position.Point := TThItem(Item.BeforeParent).AbsolutePoint + Item.Position.Point;
end;
inherited;
// 아이템 추가 시 화면에 기존아이템이 없을 경우 다시 그리지 않아
// 아이템이 표시되지 않음. 그래서 다시 그리도록 처리
// RecalcUpdateRect;
FRecalcUpdateRect := True;
end;
procedure TThContents.DoRemoveObject(const AObject: TFmxObject);
var
Item: TThItem;
begin
if not (csDestroying in ComponentState) and (AObject is TThItem) then
begin
Item := TThItem(AObject);
Item.BeforeParent := Self;
Item.BeforeIndex := AObject.Index;
end;
// 초기화 전에 하장
inherited;
end;
function TThContents.FindParent(AChild: TThItem): TFMXObject;
var
I: Integer;
CurrItem: TThItem;
begin
Result := nil;
for I := ItemCount - 1 downto 0 do
begin
CurrItem := Items[I];
if not Assigned(CurrItem) or (CurrItem = AChild) then
Continue;
if CurrItem.IsContain(AChild) then
begin
Result := CurrItem.FindParent(AChild);
if not Assigned(Result) then
begin
Result := CurrItem;
Exit;
end;
end;
end;
if not Assigned(Result) then
Result := Self;
end;
function TThContents.GetClipRect: TRectF;
begin
Result := TControl(Parent).ClipRect;
OffsetRect(Result, -Position.X, -Position.Y);
end;
function TThContents.GetItem(Index: Integer): TThItem;
begin
Result := nil;
if (Children.Count > Index) and not (Children[Index].ClassType = TThItem) then
Result := TThItem(Children[Index]);
end;
function TThContents.GetItemCount: Integer;
begin
Result := Children.Count;
end;
function TThContents.GetScaledPoint: TPointF;
begin
Result.X := Position.X / ZoomScale;
Result.Y := Position.Y / ZoomScale;
end;
function TThContents.DoGetUpdateRect: TRectF;
begin
if not Assigned(Parent) then
Exit;
{ ClipClildren := True 설정 시 Canvas 영역을 빠져나가면 Contents 표시 멈춤
TControl.GetUpdateRect 11 line
if TControl(P).ClipChildren or TControl(P).SmallSizeControl then
IntersectRect(FUpdateRect, FUpdateRect, TControl(P).UpdateRect);}
TControl(Parent).ClipChildren := False;
try
Result := inherited DoGetUpdateRect;
finally
TControl(Parent).ClipChildren := True;
end;
end;
procedure TThContents.Paint;
{$IFDEF DEBUG}
var
R: TRectF;
{$ENDIF}
begin
inherited;
{$IFDEF DEBUG}
R := R.Empty;
InflateRect(R, 100, 100);
Canvas.Stroke.Color := $FFFF0000;
Canvas.DrawEllipse(R, 1);
{$ENDIF}
end;
procedure TThContents.SetZoomScale(const Value: Single);
begin
if FZoomScale = Value then
Exit;
FZoomScale := Value;
Scale.X := Value;
Scale.Y := value;
end;
{ TThCanvas }
constructor TThCanvas.Create(AOwner: TComponent);
function _CreateTrackAni(APropertyName: string): TFloatAnimation;
begin
Result := TFloatAnimation.Create(Self);
Result.Parent := Self;
Result.AnimationType := TAnimationType.Out;
Result.Interpolation := TInterpolationType.Quadratic;
Result.PropertyName := APropertyName;
Result.StartFromCurrent := True;
Result.Delay := 0;
Result.Duration := CanvasTrackDuration;
end;
begin
inherited;
ClipChildren := True; // 컨트롤이 영역밖에 표시되지 않도록 처리
AutoCapture := True; // 영역밖으로 나가도 컨트롤 되도록 처리
FUseMouseTracking := True;
FTrackAnimated := True;
FZoomAnimated := True;
FContents := TThContents.Create(Self);
FContents.Parent := Self;
FContents.HitTest := False;
FContents.Stored := False;
FContents.Locked := True;
{$IFDEF DEBUG}
FContents.Name := FContents.ClassName;
{$ENDIF}
// DoZoomHome;
FVertTrackAni := _CreateTrackAni('ViewPortPosition.Y');
FHorzTrackAni := _CreateTrackAni('ViewPortPosition.X');
FZoomAni := TZoomCircleAni.Create(Self);
FZoomAni.Parent := Self;
FAlert := TAlertAnimation.Create(Self);
FAlert.Parent := Self;
{$IFDEF DEBUG}
FBgColor := $FFDDFFDD;
{$ELSE}
FBgColor := $FFFFFFFF;
{$ENDIF}
end;
destructor TThCanvas.Destroy;
begin
FAlert.Free;
FZoomAni.Free;
FContents.Free;
inherited;
end;
procedure TThCanvas.DoAddObject(const AObject: TFmxObject);
begin
if Assigned(FContents) and (AObject <> FContents)
and (not (AObject is TAnimation)) and (not (AObject is TZoomAni)) and (not (AObject is TAlertAnimation)) then
FContents.AddObject(AObject)
else
inherited;
end;
procedure TThCanvas.DoZoom(AScale: Single; ATargetPos: TPointF);
var
P: TPointF;
begin
P := FContents.Position.Point;
FContents.Position.X := P.X * AScale + (Width * (1 - AScale)) * (ATargetPos.X / Width);
FContents.Position.Y := P.Y * AScale + (Height * (1 - AScale)) * (ATargetPos.Y / Height);
FContents.ZoomScale := FContents.ZoomScale * AScale;
if Assigned(FOnZoom) then
FOnZoom(Self);
end;
procedure TThCanvas.DoZoomHome;
var
P: TPointF;
begin
// P := BoundsRect.CenterPoint;
P.X := (BoundsRect.Right - BoundsRect.Left)/2;
P.Y := (BoundsRect.Bottom - BoundsRect.Top)/2;
FContents.Position.Point := P;//PointF(0, 0);
FContents.ZoomScale := CanvasZoomScaleDefault;
if Assigned(FOnZoom) then
FOnZoom(Self);
end;
procedure TThCanvas.DoZoomIn(ATargetPos: TPointF);
begin
if FContents.ZoomScale * CanvasZoomOutRate > CanvasZoomScaleMax then
begin
AlertMessage(MsgCanvasZoomInMaxAlert);
Exit;
end;
if FZoomAnimated then
FZoomAni.ZoomIn(ATargetPos);
DoZoom(CanvasZoomInRate, ATargetPos);
end;
procedure TThCanvas.DoZoomOut(ATargetPos: TPointF);
begin
if FContents.ZoomScale * CanvasZoomInRate < CanvasZoomScaleMin then
begin
AlertMessage(MsgCanvasZoomOutMinAlert);
Exit;
end;
if FZoomAnimated then
FZoomAni.ZoomOut(ATargetPos);
DoZoom(CanvasZoomOutRate, ATargetPos);
end;
procedure TThCanvas.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
if Pressed and FUseMouseTracking then
begin
FMouseDownPos := PointF(X / ZoomScale, Y / ZoomScale);
FMouseCurrPos := PointF(X, Y);
// Debug('MouseDown: %f, %f', [FMouseDownPos.X, FMouseDownPos.Y]);
if FVertTrackAni.Running then
FVertTrackAni.StopAtCurrent;
if FHorzTrackAni.Running then
FHorzTrackAni.StopAtCurrent;
end;
end;
procedure TThCanvas.MouseMove(Shift: TShiftState; X, Y: Single);
begin
// Debug('Not pressed');
if Pressed and FUseMouseTracking then
begin
FLastDelta := PointF(X - FMouseCurrPos.X, Y - FMouseCurrPos.Y);
FMouseCurrPos := PointF(X, Y);
// Debug('MouseMove: %f, %f', [FMouseCurrPos.X, FMouseCurrPos.Y]);
FContents.AddTrackingPos(FLastDelta);
end;
end;
procedure TThCanvas.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
if not (ssShift in Shift) and not (ssCtrl in Shift) and (FMouseDownPos = PointF(X / ZoomScale, Y / ZoomScale)) then
ClickCanvas
else if FTrackAnimated and (not IsDrawingItem) then
begin
if FLastDelta.Y <> 0 then
begin
if FVertTrackAni.Running then
FVertTrackAni.StopAtCurrent;
FVertTrackAni.StartValue := ViewPortPosition.Y;
FVertTrackAni.StopValue := ViewPortPosition.Y + FLastDelta.Y * CanvasTrackAniCount;
FVertTrackAni.Start;
end;
if FLastDelta.X <> 0 then
begin
if FHorzTrackAni.Running then
FHorzTrackAni.StopAtCurrent;
FHorzTrackAni.StartValue := ViewPortPosition.X;
FHorzTrackAni.StopValue := ViewPortPosition.X + FLastDelta.X * CanvasTrackAniCount;
FHorzTrackAni.Start;
end;
end;
end;
procedure TThCanvas.MouseWheel(Shift: TShiftState; WheelDelta: Integer;
var Handled: Boolean);
var
P: TPointF;
begin
inherited;
P := Screen.MousePos;
P := ScreenToLocal(P);
if WheelDelta < 0 then DoZoomOut(P)
else DoZoomIn(P);
end;
procedure TThCanvas.Paint;
begin
inherited;
Canvas.Fill.Color := FBgColor;
Canvas.FillRect(ClipRect, 0, 0, AllCorners, 1);
{$IFDEF DEBUG}
Canvas.Stroke.Thickness := 1;
Canvas.Stroke.Color := claBlack;
Canvas.DrawLine(PointF(Width/2, Top), PointF(Width/2, Height), 1);
Canvas.DrawLine(PointF(Left, Height/2), PointF(Width, Height/2), 1);
{$ENDIF}
end;
procedure TThCanvas.AlertMessage(msg: string);
begin
FAlert.Message(msg);
end;
procedure TThCanvas.ClickCanvas;
begin
end;
procedure TThCanvas.SetBgColor(const Value: TAlphaColor);
begin
if FBgColor = Value then
Exit;
FBgColor := Value;
Repaint;
end;
procedure TThCanvas.Show;
begin
if Width > 0 then
begin
end;
DoZoomHome;
end;
procedure TThCanvas.ZoomHome;
begin
DoZoomHome;
end;
procedure TThCanvas.ZoomIn;
begin
DoZoomIn(ClipRect.CenterPoint)
end;
procedure TThCanvas.ZoomInAtPoint(X, Y: Single);
begin
DoZoomIn(PointF(X, Y));
end;
procedure TThCanvas.ZoomOut;
begin
DoZoomOut(ClipRect.CenterPoint);
end;
procedure TThCanvas.ZoomOutAtPoint(X, Y: Single);
begin
DoZoomOut(PointF(X, Y));
end;
function TThCanvas.GetZoomScale: Single;
begin
Result := FContents.ZoomScale;
end;
procedure TThCanvas.Initialize;
begin
DoZoomHome;
end;
function TThCanvas.IsDrawingItem: Boolean;
begin
Result := False;
end;
function TThCanvas.IsMultiSelected: Boolean;
begin
Result := False;
end;
function TThCanvas.GetViewPortPosition: TPosition;
begin
Result := FContents.Position;
end;
function TThCanvas.GetViewPortSize: TSizeF;
begin
Result.Width := Width / ZoomScale;
Result.Height := Height / ZoomScale;
end;
function TThCanvas.GetCenterPoint: TPointF;
begin
Result := PointF(Width / ZoomScale / 2, Height / ZoomScale / 2)
end;
function TThCanvas.GetItemCount: Integer;
begin
Result := FContents.ChildrenCount;
end;
end.
|
unit Lib.HTTPHeaders;
interface
uses
System.SysUtils,
Lib.HTTPUtils;
type
THeaders = class
private type
TLocation = record
Pos: Integer;
Len: Integer;
end;
private
FData: string;
function GetLocation(const Name: string): TLocation;
procedure SetData(const Value: string);
public
constructor Create;
procedure Assign(Source: TObject);
procedure AddValue(const Name,Value: string);
procedure SetValue(const Name,Value: string);
function GetValue(const Name: string): string;
procedure Clear;
function FirstLine: string;
procedure DeleteFirstLine;
property Text: string read FData write SetData;
public
procedure SetConnection(KeepAlive: Boolean; Timeout: Integer);
function ConnectionClose: Boolean;
function ConnectionKeepAlive: Boolean;
function KeepAliveTimeout: Integer;
function ContentType: string;
function ContentTypeCharset: string;
end;
implementation
const
CR = #13;
LF = #10;
CRLF = CR+LF;
constructor THeaders.Create;
begin
Clear;
end;
procedure THeaders.Assign(Source: TObject);
begin
if Source is THeaders then Text:=THeaders(Source).Text;
end;
procedure THeaders.Clear;
begin
FData:='';
end;
procedure THeaders.SetData(const Value: string);
begin
FData:=Value.Trim([CR,LF])+CRLF;
end;
function THeaders.GetLocation(const Name: string): TLocation;
var P,L: Integer;
begin
P:=(CRLF+FData.ToLower).IndexOf(CRLF+Name.ToLower+':');
L:=P;
if P<>-1 then
begin
L:=(FData+CRLF).IndexOf(CRLF,P);
while FData.Substring(L+Length(CRLF),1)=' ' do
L:=(FData+CRLF).IndexOf(CRLF,L+Length(CRLF));
end;
Result.Pos:=P;
Result.Len:=L-P;
end;
procedure THeaders.AddValue(const Name,Value: string);
begin
FData:=FData+Name+': '+Value+CRLF;
end;
procedure THeaders.SetValue(const Name,Value: string);
var L: TLocation;
begin
L:=GetLocation(Name);
if L.Pos=-1 then
AddValue(Name,Value)
else
FData:=FData.Remove(L.Pos,L.Len).Insert(L.Pos,Name+': '+Value);
end;
function THeaders.GetValue(const Name: string): string;
var L: TLocation;
begin
L:=GetLocation(Name);
if L.Pos=-1 then
Result:=''
else
Result:=HTTPGetValue(FData.Substring(L.Pos,L.Len));
end;
function THeaders.FirstLine: string;
var P: Integer;
begin
P:=FData.IndexOf(CRLF);
if P=-1 then Result:=FData else Result:=FData.Substring(0,P);
end;
procedure THeaders.DeleteFirstLine;
var P: Integer;
begin
P:=FData.IndexOf(CRLF);
if P=-1 then FData:='' else FData:=FData.Remove(0,P+Length(CRLF));
end;
procedure THeaders.SetConnection(KeepAlive: Boolean; Timeout: Integer);
begin
if KeepAlive then
begin
SetValue('Connection','keep-alive');
if Timeout>0 then
SetValue('Keep-Alive','timeout='+Timeout.ToString);
end else
SetValue('Connection','close');
end;
function THeaders.ConnectionClose: Boolean;
begin
Result:=SameText(GetValue('Connection'),'close');
end;
function THeaders.ConnectionKeepAlive: Boolean;
begin
Result:=SameText(GetValue('Connection'),'keep-alive');
end;
function THeaders.KeepAliveTimeout: Integer;
var TagTimeout: string;
begin
Result:=0;
TagTimeout:=HTTPGetTag(GetValue('Keep-Alive'),'timeout');
if TagTimeout<>'' then
Result:=StrToIntDef(HTTPGetTagValue(TagTimeout),0);
end;
function THeaders.ContentType: string;
var P: Integer;
begin
Result:=GetValue('Content-Type');
P:=Result.IndexOf(';');
if P>-1 then Result:=Result.Substring(0,P).Trim;
end;
function THeaders.ContentTypeCharset: string;
begin
Result:=
HTTPGetTagValue(
HTTPGetTag(
GetValue('Content-Type'),'charset'));
end;
end.
|
unit UPessoa;
interface
uses UCidade;
type
TPessoa = class(TObject)
private
protected
FId:integer;
FTelefone:String;
FCelular:String;
FCidade:TCidade;
FBairro:String;
FNumero:integer;
FCep:String;
FStatus:String;
FLogradouro:String;
FFax:string;
FEmail:string;
FObservacoes:string;
FTipo:String;
FDataCadastro:String;
FDataAlteracao:String;
public
//Construtor e Destrutor
constructor Create;
destructor Destroy;
//Procedimentos da classe Pais
procedure setId(vId:integer);
procedure setTelefone(vTelefone:String);
procedure setCelular(vCelular:String);
procedure setCidade(vCidade:TCidade);
procedure setBairro(vBairro:String);
procedure setNumero(vNumero:integer);
procedure setCep(vCep:String);
procedure setLogradouro(vLogradouro:String);
procedure setFax(vFax:string);
procedure setEmail(vEmail:string);
procedure setObservacoes(vObservacoes:string);
procedure setTipo(VTipo:string);
procedure setDataCadastro(vDataCadastro:String);
procedure setDataAlteracao(vDataAlteracao:String);
procedure setStatus(vStatus:string);
//Funçoes da classe Pais
function getId:integer;
function getTelefone:String;
function getCelular:String;
function getCidade:TCidade;
function getBairro:String;
function getNumero:integer;
function getCep:String;
function getLogradouro:String;
function getFax:string;
function getEmail:string;
function getObservacoes:string;
function getTipo:string;
function getDataCadastro:String;
function getDataAlteracao:String;
function getStatus:String;
//Property the Substitute os Get and Set
property Id:Integer read getId write setId;
property Telefone:String read getTelefone write setTelefone;
property Celular:string read getCelular write setCelular;
property Cidade:TCidade read getCidade write setCidade;
property Bairro:string read getBairro write setBairro;
property Numero:Integer read getNumero write setNumero;
property Cep:string read getCep write setCep;
property Logradouro:string read getLogradouro write setLogradouro;
property Fax:string read getFax write setFax;
property Email:String read getEmail write setEmail;
property Tipo:string read getTipo write setTipo;
property Observacoes:string read getObservacoes write setObservacoes;
property Status:string read getStatus write setStatus;
property DataCadastro:string read getDataCadastro write setDataCadastro;
property DataAlteracao:string read getDataAlteracao write setDataAlteracao;
end;
implementation
{ TPessoa }
constructor TPessoa.Create;
begin
FId:=0;
FTelefone:='';
FCelular:='';
FBairro:='';
FNumero:=0;
FCep:='';
FLogradouro:='';
FFax:='';
FEmail:='';
FObservacoes:='';
FDataCadastro:='';
FStatus:='';
FDataAlteracao:='';
FCidade:=TCidade.Create;
end;
destructor TPessoa.Destroy;
begin
FCidade.Destroy;
end;
function TPessoa.getBairro: String;
begin
Result:=FBairro;
end;
function TPessoa.getCelular: String;
begin
Result:= FCelular;
end;
function TPessoa.getCep: String;
begin
Result:=FCep;
end;
function TPessoa.getCidade: TCidade;
begin
Result:=FCidade;
end;
function TPessoa.getDataAlteracao: String;
begin
Result:= FDataAlteracao;
end;
function TPessoa.getDataCadastro: String;
begin
Result:= FDataCadastro;
end;
function TPessoa.getEmail: string;
begin
Result:= FEmail;
end;
function TPessoa.getFax: string;
begin
Result:= FFax;
end;
function TPessoa.getId: integer;
begin
Result:=FId;
end;
function TPessoa.getLogradouro: String;
begin
Result:= FLogradouro;
end;
function TPessoa.getNumero: integer;
begin
Result:= FNumero;
end;
function TPessoa.getObservacoes: string;
begin
Result:=FObservacoes;
end;
function TPessoa.getStatus: String;
begin
Result:=FStatus;
end;
function TPessoa.getTelefone: String;
begin
Result:= FTelefone;
end;
function TPessoa.getTipo: string;
begin
Result:=FTipo;
end;
procedure TPessoa.setBairro(vBairro: String);
begin
FBairro:=vBairro;
end;
procedure TPessoa.setCelular(vCelular: String);
begin
FCelular:=vCelular;
end;
procedure TPessoa.setCep(vCep: String);
begin
FCep:=vCep;
end;
procedure TPessoa.setCidade(vCidade: TCidade);
begin
FCidade:=vCidade;
end;
procedure TPessoa.setDataAlteracao(vDataAlteracao: String);
begin
FDataAlteracao:=vDataAlteracao;
end;
procedure TPessoa.setDataCadastro(vDataCadastro: String);
begin
FDataCadastro:=vDataCadastro;
end;
procedure TPessoa.setEmail(vEmail: string);
begin
FEmail:=vEmail;
end;
procedure TPessoa.setFax(vFax: string);
begin
FFax:=vFax;
end;
procedure TPessoa.setId(vId: integer);
begin
FId:=vId;
end;
procedure TPessoa.setLogradouro(vLogradouro: String);
begin
FLogradouro:=vLogradouro;
end;
procedure TPessoa.setNumero(vNumero: integer);
begin
FNumero:=vNumero;
end;
procedure TPessoa.setObservacoes(vObservacoes: string);
begin
FObservacoes:=vObservacoes;
end;
procedure TPessoa.setStatus(vStatus: string);
begin
FStatus:= vStatus;
end;
procedure TPessoa.setTelefone(vTelefone: String);
begin
FTelefone:=vTelefone;
end;
procedure TPessoa.setTipo(VTipo: string);
begin
FTipo:=VTipo;
end;
end.
|
unit PNGIconMaker;
interface
uses SysUtils, Types, Windows, Graphics, PNGImage, common;
type
TPNGIconMaker = class
private
FN: Byte;
FIcon: TIcon;
FBGSTR,FNUMSTR: String;
public
constructor Create(const BGSTR,NUMSTR: String);
destructor Destroy; override;
function MakeIcon(n: byte): TIcon;
property N: Byte read FN;
property Icon: TIcon read FIcon;
property BGSTR: String read FBGSTR write FBGSTR;
property NUMSTR: String read FNUMSTR write FNUMSTR;
end;
implementation
constructor TPNGIconMaker.Create(const BGSTR,NUMSTR: String);
begin
inherited Create;
FIcon := TIcon.Create;
FBGSTR := BGSTR;
FNUMSTR := NUMSTR;
// FIcon.Handle := LoadIcon(hInstance,PWideChar('ZICON'));
FIcon.Width := 16;
FIcon.Height := 16;
FN := 1;
// MakeIcon(0);
end;
destructor TPNGIconMaker.Destroy;
begin
FreeAndNil(FIcon);
inherited Destroy;
end;
function TPNGIconMaker.MakeIcon(n: byte): TIcon;
var
BG,NUM: TPNGIMAGE;
begin
Result := FIcon;
if n > 99 then
n := 99;
if FN = N then
Exit;
BG := TPNGIMAGE.Create;
NUM := TPNGIMAGE.Create;
BG.LoadFromResourceName(hInstance,FBGSTR);
NUM.LoadFromResourceName(hInstance,FNUMSTR+IntToStr((N div 10)));
NUM.Draw(BG.Canvas,Rect(3,4,NUM.Width+3,NUM.Height+4));
NUM.LoadFromResourceName(hInstance,FNUMSTR+IntToStr((N mod 10)));
NUM.Draw(BG.Canvas,Rect(8,4,NUM.Width+8,NUM.Height+4));
if not FIcon.HandleAllocated then
DestroyIcon(FIcon.Handle);
FIcon.Handle := PngToIcon(BG);
FN := N;
FreeAndNil(BG);
FreeAndNil(NUM);
end;
end.
|
unit UCollections;
(*====================================================================
Collections - similar to Delphi Lists
======================================================================*)
interface
uses UTypes;
const
{$ifdef DELPHI1}
MaxQCollectionSize = 65520 div SizeOf(Pointer);
{$else}
MaxQCollectionSize = 262144; // 1 MB just for pointers...
{$endif}
type
TPQString = ^ShortString;
TPQObject = ^TQObject;
TQObject = object
constructor Init;
procedure Free;
destructor Done; virtual;
end;
TPItemList = ^TItemList;
TItemList = array[0..MaxQCollectionSize - 1] of Pointer;
TPQCollection = ^TQCollection;
TQCollection = object(TQObject)
Items: TPItemList;
Count: Integer;
Limit: Integer;
Delta: Integer;
constructor Init(ALimit, ADelta: Integer);
destructor Done; virtual;
function At(Index: Integer): Pointer;
procedure AtDelete(Index: Integer);
procedure AtFree(Index: Integer);
procedure AtInsert(Index: Integer; Item: Pointer);
procedure AtPut(Index: Integer; Item: Pointer);
procedure Delete(Item: Pointer);
procedure DeleteAll;
procedure Free(Item: Pointer);
procedure FreeAll;
procedure FreeItem(Item: Pointer); virtual;
function IndexOf(Item: Pointer): Integer; virtual;
procedure Insert(Item: Pointer); virtual;
procedure SetLimit(ALimit: Integer); virtual;
end;
TPQSortedCollection = ^TQSortedCollection;
TQSortedCollection = object(TQCollection)
Duplicates: Boolean;
constructor Init(ALimit, ADelta: Integer);
function Compare(Key1, Key2: Pointer): Integer; virtual;
function IndexOf(Item: Pointer): Integer; virtual;
procedure Insert(Item: Pointer); virtual;
function KeyOf(Item: Pointer): Pointer; virtual;
function Search(Key: Pointer; var Index: Integer): Boolean; virtual;
end;
TPQStringCollection = ^TQStringCollection;
TQStringCollection = object(TQSortedCollection)
function Compare (Key1, Key2: Pointer): Integer; virtual;
procedure FreeItem(Item: Pointer); virtual;
end;
function QNewStr(const S: ShortString): TPQString;
procedure QDisposeStr(var P: TPQString);
//=============================================================================
implementation
uses UExceptions, ULang;
procedure Abstract;
begin
raise EQDirFatalException.Create(lsAbstractMethodUsed);
end;
//--- TQObject ----------------------------------------------------------------
constructor TQObject.Init;
begin
end;
//-----------------------------------------------------------------------------
procedure TQObject.Free;
begin
if @Self <> nil then Dispose(TPQObject(@Self), Done);
end;
//-----------------------------------------------------------------------------
destructor TQObject.Done;
begin
end;
//--- TQCollection ------------------------------------------------------------
constructor TQCollection.Init(ALimit, ADelta: Integer);
begin
TQObject.Init;
Items := nil;
Count := 0;
Limit := 0;
Delta := ADelta;
SetLimit(ALimit);
end;
//-----------------------------------------------------------------------------
destructor TQCollection.Done;
begin
FreeAll;
SetLimit(0);
end;
//-----------------------------------------------------------------------------
function TQCollection.At(Index: Integer): Pointer;
begin
if (Index >= 0) and (Index < Count)
then
Result := Items^[Index]
else
begin
raise EQDirFatalException.Create(lsInvalidIndex);
end;
end;
//-----------------------------------------------------------------------------
procedure TQCollection.AtDelete(Index: Integer);
begin
if (Index < 0) and (Index >= Count) then
raise EQDirFatalException.Create(lsInvalidIndex);
dec(Count);
if Count > Index then
move(Items^[succ(Index)], Items^[Index], (Count - Index)*SizeOf(Pointer));
end;
//-----------------------------------------------------------------------------
procedure TQCollection.AtFree(Index: Integer);
var
Item: Pointer;
begin
Item := At(Index);
AtDelete(Index);
FreeItem(Item);
end;
//-----------------------------------------------------------------------------
procedure TQCollection.AtInsert(Index: Integer; Item: Pointer);
begin
if Count = Limit then
begin
SetLimit(Limit + Delta);
if Count = Limit then
raise EQDirFatalException.Create(lsCollectionOverflow);
end;
if (Index < 0) and (Index > Count) then
raise EQDirFatalException.Create(lsInvalidIndex);
if Count > Index then
move(Items^[Index], Items^[succ(Index)], (Count - Index)*SizeOf(Pointer));
Items^[Index] := Item;
inc(Count);
end;
//-----------------------------------------------------------------------------
procedure TQCollection.AtPut(Index: Integer; Item: Pointer);
begin
if (Index < 0) and (Index >= Count) then
raise EQDirFatalException.Create(lsInvalidIndex);
Items^[Index] := Item;
end;
//-----------------------------------------------------------------------------
procedure TQCollection.Delete(Item: Pointer);
begin
AtDelete(IndexOf(Item));
end;
//-----------------------------------------------------------------------------
procedure TQCollection.DeleteAll;
begin
Count := 0;
end;
//-----------------------------------------------------------------------------
procedure TQCollection.Free(Item: Pointer);
begin
Delete(Item);
FreeItem(Item);
end;
//-----------------------------------------------------------------------------
procedure TQCollection.FreeAll;
var
I: Integer;
begin
for I := 0 to Count - 1 do FreeItem(At(I));
Count := 0;
end;
//-----------------------------------------------------------------------------
procedure TQCollection.FreeItem(Item: Pointer);
begin
if Item <> nil then Dispose(TPQObject(Item), Done);
end;
//-----------------------------------------------------------------------------
function TQCollection.IndexOf(Item: Pointer): Integer;
var
i : Integer;
begin
for i := 0 to pred(Count) do
if Item = Items^[i] then
begin
IndexOf := i;
exit;
end;
IndexOf := -1;
end;
//-----------------------------------------------------------------------------
procedure TQCollection.Insert(Item: Pointer);
begin
AtInsert(Count, Item);
end;
//-----------------------------------------------------------------------------
procedure TQCollection.SetLimit(ALimit: Integer);
var
AItems: TPItemList;
begin
if ALimit < Count then ALimit := Count;
if ALimit > MaxQCollectionSize then ALimit := MaxQCollectionSize;
if ALimit <> Limit then
begin
if ALimit = 0 then AItems := nil else
begin
GetMem(AItems, ALimit * SizeOf(Pointer));
if (Count <> 0) and (Items <> nil) then
Move(Items^, AItems^, Count * SizeOf(Pointer));
end;
if Limit <> 0 then FreeMem(Items, Limit * SizeOf(Pointer));
Items := AItems;
Limit := ALimit;
end;
end;
//--- TQSortedCollection ------------------------------------------------------
constructor TQSortedCollection.Init(ALimit, ADelta: Integer);
begin
TQCollection.Init(ALimit, ADelta);
Duplicates := False;
end;
//-----------------------------------------------------------------------------
function TQSortedCollection.Compare(Key1, Key2: Pointer): Integer;
begin
Result := 0;
Abstract;
end;
//-----------------------------------------------------------------------------
function TQSortedCollection.IndexOf(Item: Pointer): Integer;
var
I: Integer;
begin
IndexOf := -1;
if Search(KeyOf(Item), I) then
begin
if Duplicates then
while (I < Count) and (Item <> Items^[I]) do Inc(I);
if I < Count then IndexOf := I;
end;
end;
//-----------------------------------------------------------------------------
procedure TQSortedCollection.Insert(Item: Pointer);
var
I: Integer;
begin
if not Search(KeyOf(Item), I) or Duplicates then AtInsert(I, Item);
end;
//-----------------------------------------------------------------------------
function TQSortedCollection.KeyOf(Item: Pointer): Pointer;
begin
KeyOf := Item;
end;
//-----------------------------------------------------------------------------
function TQSortedCollection.Search(Key: Pointer; var Index: Integer): Boolean;
var
L, H, I, C: Integer;
begin
Search := False;
L := 0;
H := Count - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := Compare(KeyOf(Items^[I]), Key);
if C < 0 then L := I + 1 else
begin
H := I - 1;
if C = 0 then
begin
Search := True;
if not Duplicates then L := I;
end;
end;
end;
Index := L;
end;
//--- TQStringCollection ------------------------------------------------------
function TQStringCollection.Compare(Key1, Key2: Pointer): Integer;
begin
if TPQString(Key1)^ > TPQString(Key2)^
then
Compare := 1
else
if TPQString(Key1)^ < TPQString(Key2)^
then Compare := -1
else Compare := 0;
end;
//-----------------------------------------------------------------------------
procedure TQStringCollection.FreeItem(Item: Pointer);
begin
QDisposeStr(TPQString(Item));
end;
{--- Dynamic string handling routines ------------------------------}
function QNewStr(const S: ShortString): TPQString;
var
P : TPQString;
Len: SmallInt;
begin
Len := ((Length(S) + 16) div 16) * 16;
GetMem(P, Len);
P^ := S;
QNewStr := P;
end;
//-----------------------------------------------------------------------------
procedure QDisposeStr(var P: TPQString);
var
Len: SmallInt;
begin
if P <> nil then
begin
Len := ((Length(P^) + 16) div 16) * 16;
FreeMem(P, Len);
P := nil;
end;
end;
//-----------------------------------------------------------------------------
end.
|
unit Xplat.Inifiles;
interface
uses
Xplat.Services, System.Classes, System.IniFiles;
type
TXplatIniFile = class(TInterfacedObject, IIniFileService)
private
FIniFile: TCustomIniFile;
FFreeIni: Boolean;
FUpdateAfterWrite: Boolean;
public
function ReadBool(const Section, Ident: string; Default: Boolean): Boolean;
procedure WriteBool(const Section, Ident: string; Value: Boolean);
function ReadString(const Section, Ident, Default: string): string;
procedure WriteString(const Section, Ident, Value: String);
function ReadInteger(const Section, Ident: string; Default: Integer): Integer;
procedure WriteInteger(const Section, Ident: string; Value: Integer);
function ReadDate(const Section, Ident: string; Default: TDateTime): TDateTime;
procedure WriteDate(const Section, Ident: string; Value: TDateTime);
function ReadDateTime(const Section, Ident: string; Default: TDateTime): TDateTime;
procedure WriteDateTime(const Section, Ident: string; Value: TDateTime);
function ReadTime(const Section, Ident: string; Default: TDateTime): TDateTime;
procedure WriteTime(const Section, Ident: string; Value: TDateTime);
function ReadFloat(const Section, Ident: string; Default: Double): Double;
procedure WriteFloat(const Section, Ident: string; Value: Double);
procedure ReadSection(const Section: string; Strings: TStrings);
procedure ReadSections(Strings: TStrings);
procedure ReadSectionValues(const Section: string; Strings: TStrings);
procedure EraseSection(const Section: string);
procedure DeleteKey(const Section, Ident: String);
procedure UpdateFile;
//The TIniFile implementation used by non-Windows compilers is actually
//a TMemIniFile descendant. This means there is no explicit file write with
//each call to Write*. To preserve the same behaviour as Windows, set
//UpdateAfterWrite to True (which is the default).
property UpdateAfterWrite: Boolean read FUpdateAfterWrite write FUpdateAfterWrite;
constructor Create(AIniFile: TCustomIniFile; AFreeIni: Boolean = True;
AUpdateAfterWrite: Boolean = {$IFDEF MSWINDOWS}False{$ELSE}True{$ENDIF}); overload;
constructor Create; overload;
destructor Destroy; override;
end;
implementation
uses
System.SysUtils, System.IOUtils;
constructor TXplatIniFile.Create(AIniFile: TCustomIniFile; AFreeIni: Boolean;
AUpdateAfterWrite: Boolean);
begin
inherited Create;
FIniFile := AIniFile;
FFreeIni := AFreeIni;
FUpdateAfterWrite := AUpdateAfterWrite;
end;
constructor TXplatIniFile.Create;
const
cnFileNameFmt = '%s%s%s.ini';
cnDefaultPrefsName = 'Prefs';
var
lFileName: string;
lPrefsName: string;
begin
lPrefsName := TPath.GetFileNameWithoutExtension(ParamStr(0));
if lPrefsName = '' then
lPrefsName := cnDefaultPrefsName;
lFileName := Format(cnFileNameFmt, [TPath.GetDocumentsPath, TPath.DirectorySeparatorChar, lPrefsName]);
Self.Create(TIniFile.Create(lFileName), True);
end;
procedure TXplatIniFile.DeleteKey(const Section, Ident: String);
begin
FIniFile.DeleteKey(Section, Ident);
if FUpdateAfterWrite then
FIniFile.UpdateFile;
end;
destructor TXplatIniFile.Destroy;
begin
if FFreeIni then
FIniFile.Free;
inherited;
end;
procedure TXplatIniFile.EraseSection(const Section: string);
begin
FIniFile.EraseSection(Section);
if FUpdateAfterWrite then
FIniFile.UpdateFile;
end;
function TXplatIniFile.ReadBool(const Section, Ident: string;
Default: Boolean): Boolean;
begin
Result := FIniFile.ReadBool(Section, Ident, Default);
end;
function TXplatIniFile.ReadDate(const Section, Ident: string;
Default: TDateTime): TDateTime;
begin
Result := FIniFile.ReadDate(Section, Ident, Default);
end;
function TXplatIniFile.ReadDateTime(const Section, Ident: string;
Default: TDateTime): TDateTime;
begin
Result := FIniFile.ReadDateTime(Section, Ident, Default);
end;
function TXplatIniFile.ReadFloat(const Section, Ident: string;
Default: Double): Double;
begin
Result := FIniFile.ReadFloat(Section, Ident, Default);
end;
function TXplatIniFile.ReadInteger(const Section, Ident: string;
Default: Integer): Integer;
begin
Result := FIniFile.ReadInteger(Section, Ident, Default);
end;
procedure TXplatIniFile.ReadSection(const Section: string; Strings: TStrings);
begin
FIniFile.ReadSection(Section, Strings);
end;
procedure TXplatIniFile.ReadSections(Strings: TStrings);
begin
FIniFile.ReadSections(Strings);
end;
procedure TXplatIniFile.ReadSectionValues(const Section: string;
Strings: TStrings);
begin
FIniFile.ReadSectionValues(Section, Strings);
end;
function TXplatIniFile.ReadString(const Section, Ident,
Default: string): string;
begin
Result := FIniFile.ReadString(Section, Ident, Default);
end;
function TXplatIniFile.ReadTime(const Section, Ident: string;
Default: TDateTime): TDateTime;
begin
Result := FIniFile.ReadTime(Section, Ident, Default);
end;
procedure TXplatIniFile.UpdateFile;
begin
FIniFile.UpdateFile;
end;
procedure TXplatIniFile.WriteBool(const Section, Ident: string;
Value: Boolean);
begin
FIniFile.WriteBool(Section, Ident, Value);
if FUpdateAfterWrite then
FIniFile.UpdateFile;
end;
procedure TXplatIniFile.WriteDate(const Section, Ident: string;
Value: TDateTime);
begin
FIniFile.WriteDate(Section, Ident, Value);
if FUpdateAfterWrite then
FIniFile.UpdateFile;
end;
procedure TXplatIniFile.WriteDateTime(const Section, Ident: string;
Value: TDateTime);
begin
FIniFile.WriteDateTime(Section, Ident, Value);
if FUpdateAfterWrite then
FIniFile.UpdateFile;
end;
procedure TXplatIniFile.WriteFloat(const Section, Ident: string;
Value: Double);
begin
FIniFile.WriteFloat(Section, Ident, Value);
if FUpdateAfterWrite then
FIniFile.UpdateFile;
end;
procedure TXplatIniFile.WriteInteger(const Section, Ident: string;
Value: Integer);
begin
FIniFile.WriteInteger(Section, Ident, Value);
if FUpdateAfterWrite then
FIniFile.UpdateFile;
end;
procedure TXplatIniFile.WriteString(const Section, Ident, Value: String);
begin
FIniFile.WriteString(Section, Ident, Value);
if FUpdateAfterWrite then
FIniFile.UpdateFile;
end;
procedure TXplatIniFile.WriteTime(const Section, Ident: string;
Value: TDateTime);
begin
FIniFile.WriteTime(Section, Ident, Value);
if FUpdateAfterWrite then
FIniFile.UpdateFile;
end;
end.
|
// 307. 区域和检索 - 数组可修改
//
// 给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
//
// update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。
//
// 示例:
//
// Given nums = [1, 3, 5]
//
// sumRange(0, 2) -> 9
// update(1, 2)
// sumRange(0, 2) -> 8
// 说明:
//
// 1.数组仅可以在 update 函数下进行修改。
// 2.你可以假设 update 函数与 sumRange 函数的调用次数是均匀分布的。
//
// class NumArray {
//
// public NumArray(int[] nums) {
//
// }
//
// public void update(int i, int val) {
//
// }
//
// public int sumRange(int i, int j) {
//
// }
// }
//
// /**
// * Your NumArray object will be instantiated and called as such:
// * NumArray obj = new NumArray(nums);
// * obj.update(i,val);
// * int param_2 = obj.sumRange(i,j);
// */
unit DSA.LeetCode._307;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Interfaces.DataStructure,
DSA.Utils,
DSA.Tree.SegmentTree;
type
TsegmentTree_int = specialize TSegmentTree<integer>;
TNumArray = class
private
__sgt: TsegmentTree_int;
public
constructor Create(nums: TArray_int);
procedure update(i, val: integer);
function sumRange(i, j: integer): integer;
end;
procedure Main;
implementation
procedure Main;
var
nums: TArray_int;
numArray: TNumArray;
begin
nums := [1, 3, 5];
numArray := TNumArray.Create(nums);
Writeln(numArray.sumRange(0, 2));
numArray.update(1, 2);
Writeln(numArray.sumRange(0, 2));
end;
{ TNumArray }
constructor TNumArray.Create(nums: TArray_int);
begin
__sgt := TsegmentTree_int.Create(nums, TMerger.Create);
end;
function TNumArray.sumRange(i, j: integer): integer;
begin
Result := __sgt.Query(i, j);
end;
procedure TNumArray.update(i, val: integer);
begin
__sgt.Set_(i, val);
end;
end.
|
unit uServiceUtils;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.FileCtrl,
JPEG, Data.DB, IniFiles, Generics.Collections, {$IFNDEF EXTDLL}JvZlibMultiple,{$ENDIF}
FireDAC.Stan.Param;
function MessageDlgExt(aMessage, aCaption: String; aDlgType: TMsgDlgType;
aButtons: TMsgDlgButtons): Integer;
{сообщение об ошибке без возбуждения исключения}
procedure ErrorMessage(aMessage: String; Args: array of const); overload;
{сообщение об ошибке без возбуждения исключения}
procedure ErrorMessage(aMessage: String); overload;
{возбуждить исключенияe}
procedure Error(aMessage: String);
{запрос подтверждения (Да, Нет)}
function Confirm(aMessage: String): Boolean;
{сообщение}
procedure Information(aMessage: String);
{выравнивание кнопок по центру}
procedure CenterButtons(aWidth: Integer; aButton1, aButton2: TWinControl); overload;
{освобождение объекта с проверкой на существование}
procedure FreeWithCheckExist(Instance: TObject);
{проверяет входной параметр валидность ID}
function IsNullID(aValue: Variant): Boolean;
{Если Value=Null, то возвращаем ReplaceValue}
function isNull(aValue, aReplaceValue: Variant): Variant;
{Если Value=aNullValue, то возвращаем Null}
function ifNull(aValue, aNullValue: Variant): Variant;
{очистить список}
procedure ClearList(aList: TList);
{очистить и удалить список}
procedure ClearAndFreeList(aList: TList);
{очистить типизированный список}
procedure ClearTypedList(aList: TList<TObject>);
{очистить и удалить типизированный список}
procedure ClearAndFreeTypedList(aList: TList<TObject>);
{покать фото в имедже}
function ShowPhoto(aPicture: TPicture; aPhoto: TJPEGImage): Boolean;
{получить фото с Blob поля}
function GetPhotoFromBlob(aField: TBlobField): TJPEGImage;
{создать JPEG c Image-a}
function CreateJEPG(aPicture: TPicture): TJPEGImage;
{шифрование/дешифрование строки}
function CodeString(sText: String; aCrypt: Boolean): String;
{получение родительской формы для компонента}
function GetParentForm(aControl: TWinControl): TForm;
{$IFNDEF EXTDLL}
{архивирование каталога}
procedure CompressDirectory(aSource, aFileName: String);
{разархивирование файла}
procedure DecompressFile(aFileName, aOutput: String);
{$ENDIF}
{выбор каталога}
function ChooseDirectory(aOwner: TWinControl; aCaption: String; var vFolder: String): Boolean;
{{получить имя файла без расширения}
function ExtractFileNameWithoutExt(aFileName: String): String;
function VarEquals(const Value1, Value2: Variant): Boolean;
{добавить разделители хэш сумме}
function HashAddDelimiter(aValue: String): String;
function LoadPhotoToParam(aPhoto: TJPEGImage; aParam: TFDParam): Boolean;
function GetCurrentHID(aValue: Integer): String;
procedure ControlSetFocus(aControl: TWinControl);
// RenameFile(Application.ExeName, ExtractFileDir(Application.ExeName)+'\Cards_old_Version.exe');
implementation
function MessageDlgExt(aMessage, aCaption: String; aDlgType: TMsgDlgType;
aButtons: TMsgDlgButtons): Integer;
var oIcon: Cardinal;
oButton: Cardinal;
begin
{иконка диалога сообщения}
case aDlgType of
mtWarning:
begin
oIcon:= MB_ICONERROR;
end;
mtError:
begin
oIcon:= MB_ICONERROR;
end;
mtInformation:
begin
oIcon:= MB_ICONINFORMATION;
end;
mtConfirmation:
begin
oIcon:= MB_ICONQUESTION;
end;
mtCustom:
begin
oIcon:= MB_USERICON;
end
else oIcon:= 0;
end;
if (mbYes in aButtons) or
(mbOk in aButtons)
then
begin
oButton:= MB_OK;
end;
if (mbYes in aButtons) and
(mbNo in aButtons)
then
begin
oButton:= MB_YESNO;
end;
if (mbOK in aButtons) and
(mbCancel in aButtons)
then
begin
oButton:= MB_OKCANCEL;
end;
{MB_OK
MB_OKCANCEL
MB_ABORTRETRYIGNORE
MB_YESNOCANCEL
MB_YESNO
MB_RETRYCANCEL}
Result:= Application.MessageBox(PWideChar(aMessage), PWideChar(aCaption), oIcon or oButton);
end;
procedure ErrorMessage(aMessage: String; Args: array of const);
begin
MessageDlgExt(Format(aMessage, Args), 'ОШИБКА', mtError, [mbOK]);
end;
procedure ErrorMessage(aMessage: String); overload;
begin
MessageDlgExt(aMessage, 'ОШИБКА', mtError, [mbOK]);
end;
procedure Error(aMessage: String);
begin
raise Exception.Create(aMessage);
end;
function Confirm(aMessage: String): Boolean;
begin
if (aMessage <> '') and (aMessage[Length(aMessage)] <> '?')
then
begin
aMessage:= aMessage + '?';
end;
Result:= MessageDlgExt(aMessage, 'ПОДТВЕРЖДЕНИЕ', mtConfirmation, [mbYes, mbNo]) = mrYes;
Application.ProcessMessages;
end;
procedure Information(aMessage: String);
begin
MessageDlgExt(aMessage, 'ИНФОРМАЦИЯ', mtInformation, [mbOK]);
end;
procedure CenterButtons(aWidth: Integer; aButton1, aButton2: TWinControl);
var iWidth: Integer;
iLeft: Integer;
begin
iWidth:= 0;
if aButton1.Visible
then
begin
iWidth:= iWidth + AButton1.Width;
end;
if aButton2.Visible
then
begin
iWidth:= iWidth + AButton2.Width;
end;
if aButton1.Visible and aButton2.Visible
then
begin
Inc(iWidth, 10);
end;
iLeft:= (aWidth div 2) - (iWidth div 2);
if (iLeft <= 0)
then
begin
iLeft:= 1;
end;
if aButton1.Visible and aButton2.Visible
then
begin
AButton1.Left:= iLeft;
AButton2.Left:= iLeft + 10 + AButton1.Width + 1;
end
else
if aButton1.Visible
then
begin
AButton1.Left:= iLeft;
end
else
if aButton2.Visible
then
begin
AButton2.Left:= iLeft;
end;
end;
procedure FreeWithCheckExist(Instance: TObject);
begin
if Assigned(Instance) then
Instance.Free;
Instance := nil;
end;
function IsNullID(aValue: Variant): Boolean;
begin
Result:= VarIsEmpty(aValue) or
VarIsNull(aValue) or
(VarToStr(aValue) = '') or
(VarToStr(aValue) = '0');
end;
function isNull(aValue, aReplaceValue: Variant): Variant;
begin
if aValue = Null
then
begin
Result:= aReplaceValue;
end
else
begin
Result:= aValue;
end;
end;
function ifNull(aValue, aNullValue: Variant): Variant;
begin
if (aValue = aNullValue)
then
begin
Result:= Null
end
else
begin
Result:= aValue;
end;
end;
procedure ClearList(aList: TList);
var i: Integer;
begin
if Assigned(aList) and
not (aList = nil)
then
begin
for i:= 0 to aList.Count - 1 do
begin
TObject(aList.Items[i]).Free;
end;
aList.Clear;
end;
end;
procedure ClearAndFreeList(aList: TList);
begin
if Assigned(aList) and
not (aList = nil)
then
begin
ClearList(aList);
aList.Free;
aList:= nil;
end;
end;
function ShowPhoto(aPicture: TPicture; aPhoto: TJPEGImage): Boolean;
begin
Result:= True;
if Assigned(aPhoto) and
(not (aPhoto = nil))
then
begin
aPicture.Bitmap.Assign(aPhoto);
Result:= True;
end;
end;
function GetPhotoFromBlob(aField: TBlobField): TJPEGImage;
var oMemoryStream: TMemoryStream;
begin
Result:= nil;
if ((aField.DataSet.Active) and
(not aField.IsNull) and
not (aField.AsString = ''))
then
begin
oMemoryStream:= TmemoryStream.Create;
Result:= TJPEGImage.Create;
try
oMemoryStream.Position:= 0;
aField.SaveToStream(oMemoryStream);
oMemoryStream.Position:= 0;
Result.LoadFromStream(oMemoryStream);
finally
oMemoryStream.Free;
end;
end;
end;
function CreateJEPG(aPicture: TPicture): TJPEGImage;
begin
Result:= nil;
if not (aPicture.Graphic = nil)
then
begin
Result:= TJPEGImage.Create;
Result.Assign(aPicture.Graphic);
if (Result.Width > 512) or
(Result.Height > 512)
then
begin
Result.CompressionQuality:= 35;
Result.Compress;
end;
end;
end;
function CodeString(sText: String; aCrypt: Boolean): String;
const
Pas=10;
var
i: Integer;
iDelta: Integer;
iRes: Integer;
begin
Result:= '';
for i:= 1 to Length(sText) do
begin
iDelta:= ((i xor Pas) mod (256 - 32));
if aCrypt
then
begin
iRes:= ((Ord(sText[i]) + iDelta) mod (256 - 32)) + 32;
end
else
begin
iRes:= Ord(sText[i]) - iDelta - 32;
if (iRes < 32)
then
begin
iRes:= iRes + 256 - 32;
end;
end;
Result:= Result + Chr(iRes);
end;
end;
function GetParentForm(aControl: TWinControl): TForm;
var oParent: TWinControl;
begin
oParent:= aControl;
while Assigned(oParent) and
not (oParent.Parent is TForm) do
begin
oParent:= oParent.Parent;
end;
if Assigned(oParent) and
(oParent is TForm)
then
begin
Result:= TForm(oParent);
end;
end;
procedure ClearTypedList(aList: TList<TObject>);
var i: Integer;
begin
if Assigned(aList) and
not (aList = nil)
then
begin
for i:= 0 to aList.Count - 1 do
begin
TObject(aList.Items[i]).Free;
end;
aList.Clear;
end;
end;
procedure ClearAndFreeTypedList(aList: TList<TObject>);
begin
if Assigned(aList) and
not (aList = nil)
then
begin
ClearTypedList(aList);
aList.Free;
aList:= nil;
end;
end;
{$IFNDEF EXTDLL}
procedure CompressDirectory(aSource, aFileName: String);
var
oZip: TJvZlibMultiple;
begin
oZip:= TJvZlibMultiple.Create(nil);
try
oZip.CompressDirectory(aSource, True, aFileName);
finally
oZip.Free;
end;
end;
procedure DecompressFile(aFileName, aOutput: String);
var oZip: TJvZlibMultiple;
begin
oZip:= TJvZlibMultiple.Create(nil);
try
oZip.DecompressFile(aFileName, aOutput, True);
finally
oZip.Free;
end;
end;
{$ENDIF}
function ChooseDirectory(aOwner: TWinControl; aCaption: String; var vFolder: String): Boolean;
begin
Result:= False;
if aCaption = ''
then
begin
aCaption:= 'Выберите каталог';
end;
if SelectDirectory(aCaption, '', vFolder, [sdNewUI], aOwner)
then
begin
Result:= True;
end;
end;
function ExtractFileNameWithoutExt(aFileName: String): String;
var sFileExt: String;
begin
{имя файла с расширением}
Result:= ExtractFileName(aFileName);
{расширение файла}
sFileExt:= ExtractFileExt(aFileName);
{имя файла без расширения}
Result:= Copy(Result, 1, Length(Result) - Length(sFileExt));
end;
function VarEquals(const Value1, Value2: Variant): Boolean;
begin
Result:= False;
try
Result:= Value1 = Value2;
except
end;
end;
function HashAddDelimiter(aValue: String): String;
begin
Result:= aValue;
if Length(aValue) = 32
then
begin
Result:= Copy(aValue, 1, 8) + '-' +
Copy(aValue, 9, 8) + '-' +
Copy(aValue, 17, 8) + '-' +
Copy(aValue, 25, 8);
end;
end;
function LoadPhotoToParam(aPhoto: TJPEGImage; aParam: TFDParam): Boolean;
var oStream: TStream;
begin
Result:= False;
if not Assigned(aPhoto) and
aPhoto.Empty
then
begin
//aParam.
Exit;
end;
oStream:= TMemoryStream.Create;
try
aPhoto.SaveToStream(oStream);
oStream.Position:= 0;
oStream.Size;
aParam.LoadFromStream(oStream, ftBlob);
Result:= True;
finally
oStream.Free;
end;
end;
function GetCurrentHID(aValue: Integer): String;
const HID_SIZE = 4;
begin
Result:= IntToStr(aValue);
Result:= StringOfChar('0', HID_SIZE - Length(Result)) + Result;
end;
procedure ControlSetFocus(aControl: TWinControl);
begin
if (aControl.Visible) and (aControl.Enabled)
then
begin
aControl.SetFocus;
end;
end;
end.
|
unit uXMLClasses;
interface
uses SysUtils, Classes;
type
TXMLContent = class
private
FXML: String;
function GetTagValue(ATagName: String): String;
function GetAttributeValue(AAttributeName: String): String;
function GetAttributeValueByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): String;
public
function GetTagInteger(ATagName: String): Integer;
function GetTagBoolean(ATagName: String): Boolean;
function GetTagDouble(ATagName: String): Double;
function GetTagString(ATagName: String): String;
function GetTagDateTime(ATagName: String): TDateTime;
function GetAttributeInteger(AAttributeName: String): Integer;
function GetAttributeBoolean(AAttributeName: String): Boolean;
function GetAttributeDouble(AAttributeName: String): Double;
function GetAttributeString(AAttributeName: String): String;
function GetAttributeDateTime(AAttributeName: String): TDateTime;
function GetAttributeIntegerByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): Integer;
function GetAttributeBooleanByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): Boolean;
function GetAttributeDoubleByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): Double;
function GetAttributeStringByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): String;
function GetAttributeDateTimeByNodeIndex(ANodeName, AAttributeName: String; AIndex: Integer): TDateTime;
function CutNode(ANodeName: String): String;
function GetNode(ANodeName: String): String;
function GetNodeByIndex(ANodeName: String; AIndex: Integer): String;
function GetNodeCount(ANodeName: String): Integer;
function GetNodeCountByNodeIndex(ANodeMasterName, ANodeName: String; AIndex: Integer): Integer;
property XML: String read FXML write FXML;
end;
TXMLRequest = class
private
FUserName: String;
FUserPassword: String;
FURLSite: String;
FActionName: String;
public
function GetXMLRequestByID(ID: Integer): String;
property URLSite: String read FURLSite write FURLSite;
property ActionName: String read FActionName write FActionName;
property UserName: String read FUserName write FUserName;
property UserPassword: String read FUserPassword write FUserPassword;
end;
TXMLResponse = class
private
FXMLContent: TXMLContent;
public
constructor Create;
destructor Destroy; override;
function GetXMLResponse(ContentStream: TStream): String;
property XMLContent: TXMLContent read FXMLContent write FXMLContent;
end;
implementation
uses DateUtils;
{ TXMLRequest }
function TXMLRequest.GetXMLRequestByID(ID: Integer): String;
begin
Result := '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:e="http://www.e-plataforma.com.br">' +
' <soapenv:Header/>' +
' <soapenv:Body>' +
' <e:' + FActionName + '>' +
' <!--Optional:-->' +
' <e:Usuario>' + FUserName + '</e:Usuario>' +
' <!--Optional:-->' +
' <e:Senha>' + FUserPassword + '</e:Senha>' +
' <!--Optional:-->' +
' <e:UrlSite>' + FURLSite + '</e:UrlSite>' +
' <!--Optional:-->' +
' <e:Id>' + IntToStr(ID) + '</e:Id>' +
' </e:' + FActionName + '>' +
' </soapenv:Body>' +
'</soapenv:Envelope>';
end;
{ TXMLResponse }
constructor TXMLResponse.Create;
begin
FXMLContent := TXMLContent.Create;
end;
destructor TXMLResponse.Destroy;
begin
FXMLContent.Free;
inherited Destroy;
end;
function TXMLResponse.GetXMLResponse(ContentStream: TStream): String;
var
ContentStringStream: TStringStream;
begin
Result := '';
ContentStringStream := TStringStream.Create('');
try
ContentStringStream.CopyFrom(ContentStream, 0);
FXMLContent.XML := UTF8Decode(ContentStringStream.DataString);
Result := FXMLContent.XML;
finally
ContentStringStream.Free;
end;
end;
{ TXMLContent }
function TXMLContent.CutNode(ANodeName: String): String;
begin
Result := GetNode(ANodeName);
FXML := StringReplace(FXML, Result, '', [rfReplaceAll]);
end;
function TXMLContent.GetAttributeBoolean(AAttributeName: String): Boolean;
begin
Result := StrToBool(GetAttributeValue(AAttributeName));
end;
function TXMLContent.GetAttributeBooleanByNodeIndex(ANodeName, AAttributeName: String;
AIndex: Integer): Boolean;
begin
Result := StrToBool(GetAttributeValueByNodeIndex(ANodeName, AAttributeName, AIndex));
end;
function TXMLContent.GetAttributeDateTime(AAttributeName: String): TDateTime;
var
sValue: String;
Year, Month, Day, Hour, Minute, Second, MilliSecond: Word;
begin
sValue := GetAttributeValue(AAttributeName);
if sValue = '' then
Result := Now
else
begin
Year := StrToInt(Copy(sValue, 1, 4));
Month := StrToInt(Copy(sValue, 6, 2));
Day := StrToInt(Copy(sValue, 9, 2));
Hour := StrToInt(Copy(sValue, 12, 2));
Minute := StrToInt(Copy(sValue, 15, 2));
Second := StrToInt(Copy(sValue, 18, 2));
MilliSecond := StrToInt('00');
Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, MilliSecond);
end;
end;
function TXMLContent.GetAttributeDateTimeByNodeIndex(ANodeName, AAttributeName: String;
AIndex: Integer): TDateTime;
var
sValue: String;
Year, Month, Day, Hour, Minute, Second, MilliSecond: Word;
begin
sValue := GetAttributeValueByNodeIndex(ANodeName, AAttributeName, AIndex);
if sValue = '' then
Result := Now
else
begin
Year := StrToInt(Copy(sValue, 1, 4));
Month := StrToInt(Copy(sValue, 6, 2));
Day := StrToInt(Copy(sValue, 9, 2));
Hour := StrToInt(Copy(sValue, 12, 2));
Minute := StrToInt(Copy(sValue, 15, 2));
Second := StrToInt(Copy(sValue, 18, 2));
MilliSecond := StrToInt('00');
Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, MilliSecond);
end;
end;
function TXMLContent.GetAttributeDouble(AAttributeName: String): Double;
var
sValue: String;
begin
sValue := GetAttributeValue(AAttributeName);
sValue := StringReplace(sValue, '.', ',', [rfReplaceAll]);
Result := StrToFloat(sValue);
end;
function TXMLContent.GetAttributeDoubleByNodeIndex(ANodeName, AAttributeName: String;
AIndex: Integer): Double;
var
sValue: String;
begin
sValue := GetAttributeValueByNodeIndex(ANodeName, AAttributeName, AIndex);
sValue := StringReplace(sValue, '.', ',', [rfReplaceAll]);
Result := StrToFloat(sValue);
end;
function TXMLContent.GetAttributeInteger(AAttributeName: String): Integer;
begin
Result := StrToInt(GetAttributeValue(AAttributeName));
end;
function TXMLContent.GetAttributeIntegerByNodeIndex(ANodeName, AAttributeName: String;
AIndex: Integer): Integer;
var
sAttributeValue: String;
begin
sAttributeValue := GetAttributeValueByNodeIndex(ANodeName, AAttributeName, AIndex);
if sAttributeValue = '' then
Result := -1
else
Result := StrToInt(sAttributeValue);
end;
function TXMLContent.GetAttributeString(AAttributeName: String): String;
begin
Result := GetAttributeValue(AAttributeName);
end;
function TXMLContent.GetAttributeStringByNodeIndex(ANodeName, AAttributeName: String;
AIndex: Integer): String;
begin
Result := GetAttributeValueByNodeIndex(ANodeName, AAttributeName, AIndex);
end;
function TXMLContent.GetAttributeValue(AAttributeName: String): String;
var
iBegin, iEnd, iSize: Integer;
begin
iBegin := Pos('<a:' + AAttributeName + '>', XML);
iEnd := Pos('</a:' + AAttributeName + '>', XML);
iSize := Length('<a:' + AAttributeName + '>');
Result := Copy(XML, iBegin + iSize, iEnd - (iBegin + iSize));
end;
function TXMLContent.GetAttributeValueByNodeIndex(ANodeName, AAttributeName: String;
AIndex: Integer): String;
var
i, iNodeEndPos, iNodeEndLen: Integer;
XMLNodeContent: TXMLContent;
begin
Result := '';
XMLNodeContent := TXMLContent.Create;
try
XMLNodeContent.XML := FXML;
iNodeEndLen := Length('</a:'+ANodeName+'>');
iNodeEndPos := Pos('</a:'+ANodeName+'>', XMLNodeContent.XML);
for i := 0 to AIndex do
begin
if i <> AIndex then
begin
XMLNodeContent.XML := Copy(XMLNodeContent.XML, iNodeEndPos + iNodeEndLen, Length(XMLNodeContent.XML));
iNodeEndPos := Pos('</a:'+ANodeName+'>', XMLNodeContent.XML);
end;
end;
Result := XMLNodeContent.GetAttributeValue(AAttributeName);
finally
XMLNodeContent.Free;
end;
end;
function TXMLContent.GetNode(ANodeName: String): String;
var
i, iNodeBeginPos, iNodeEndPos, iNodeEndLen: Integer;
XMLNodeContent: TXMLContent;
begin
Result := '';
XMLNodeContent := TXMLContent.Create;
try
XMLNodeContent.XML := FXML;
iNodeEndLen := Length('</a:'+ANodeName+'>');
iNodeBeginPos := Pos('<a:'+ANodeName+'>', XMLNodeContent.XML);
iNodeEndPos := Pos('</a:'+ANodeName+'>', XMLNodeContent.XML);
XMLNodeContent.XML := Copy(XMLNodeContent.XML, iNodeBeginPos, (iNodeEndPos + iNodeEndLen) - iNodeBeginPos);
iNodeEndPos := Pos('</a:'+ANodeName+'>', XMLNodeContent.XML);
Result := XMLNodeContent.XML;
finally
XMLNodeContent.Free;
end;
end;
function TXMLContent.GetNodeByIndex(ANodeName: String; AIndex: Integer): String;
var
i, iNodeEndPos, iNodeEndLen: Integer;
XMLNodeContent: TXMLContent;
begin
Result := '';
XMLNodeContent := TXMLContent.Create;
try
XMLNodeContent.XML := FXML;
iNodeEndLen := Length('</a:'+ANodeName+'>');
iNodeEndPos := Pos('</a:'+ANodeName+'>', XMLNodeContent.XML);
for i := 0 to AIndex do
begin
if i <> AIndex then
begin
XMLNodeContent.XML := Copy(XMLNodeContent.XML, iNodeEndPos + iNodeEndLen, Length(XMLNodeContent.XML));
iNodeEndPos := Pos('</a:'+ANodeName+'>', XMLNodeContent.XML);
end;
end;
Result := XMLNodeContent.XML;
finally
XMLNodeContent.Free;
end;
end;
function TXMLContent.GetNodeCount(ANodeName: String): Integer;
var
iNodePos, iNodeLen: Integer;
sTempXML: String;
begin
Result := 0;
sTempXML := FXML;
iNodeLen := Length('<a:'+ANodeName+'>');
iNodePos := Pos('<a:'+ANodeName+'>', sTempXML);
while iNodePos <> 0 do
begin
sTempXML := Copy(sTempXML, iNodePos + iNodeLen, Length(sTempXML));
iNodePos := Pos('<a:'+ANodeName+'>', sTempXML);
Inc(Result);
end;
end;
function TXMLContent.GetNodeCountByNodeIndex(ANodeMasterName,
ANodeName: String; AIndex: Integer): Integer;
var
i, iNodeMasterPos, iNodePos, iNodeMasterLen, iNodeLen: Integer;
sTempXML: String;
begin
Result := 0;
sTempXML := FXML;
iNodeMasterLen := Length('<a:'+ANodeMasterName+'>');
for i := 0 to AIndex do
begin
iNodeMasterPos := Pos('<a:'+ANodeMasterName+'>', sTempXML);
while iNodePos <> 0 do
begin
sTempXML := Copy(sTempXML, iNodeMasterPos + iNodeMasterLen, Length(sTempXML));
iNodeMasterPos := Pos('<a:'+ANodeMasterName+'>', sTempXML);
Inc(Result);
end;
end;
iNodeLen := Length('<a:'+ANodeName+'>');
iNodePos := Pos('<a:'+ANodeName+'>', sTempXML);
while iNodePos <> 0 do
begin
sTempXML := Copy(sTempXML, iNodePos + iNodeLen, Length(sTempXML));
iNodePos := Pos('<a:'+ANodeName+'>', sTempXML);
Inc(Result);
end;
end;
function TXMLContent.GetTagBoolean(ATagName: String): Boolean;
begin
Result := StrToBool(GetTagValue(ATagName));
end;
function TXMLContent.GetTagDateTime(ATagName: String): TDateTime;
var
sValue: String;
//Year, Month, Day, Hour, Minute, Second, MilliSecond: Word;
begin
sValue := GetTagValue(ATagName);
//Year := Copy(sValue, 1, 4);
//Month := Copy(sValue, 6, 2);
//Day := Copy(sValue, 9, 2);
//Hour := Copy(sValue, 12, 2);
//Minute := Copy(sValue, 15, 2);
//Second := Copy(sValue, 18, 2);
//MilliSecond := '00';
//Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, MilliSecond);
Result := Now;
end;
function TXMLContent.GetTagDouble(ATagName: String): Double;
var
sValue: String;
begin
sValue := GetTagValue(ATagName);
sValue := StringReplace(sValue, '.', ',', [rfReplaceAll]);
Result := StrToFloat(sValue);
end;
function TXMLContent.GetTagInteger(ATagName: String): Integer;
var
sTagValue: String;
begin
sTagValue := GetTagValue(ATagName);
if sTagValue = '' then
Result := -1
else
Result := StrToInt(sTagValue);
end;
function TXMLContent.GetTagString(ATagName: String): String;
begin
Result := GetTagValue(ATagName);
end;
function TXMLContent.GetTagValue(ATagName: String): String;
var
iBegin, iEnd, iSize: Integer;
begin
iBegin := Pos('<' + ATagName + '>', XML);
iEnd := Pos('</' + ATagName + '>', XML);
iSize := Length('<' + ATagName + '>');
Result := Copy(XML, iBegin + iSize, iEnd - (iBegin + iSize));
end;
end.
|
{..............................................................................}
{ }
{ Summary Demo how to create a new component on the PCB }
{ }
{ 1/ Run CreateAComponentOnPCB procedure first to create a new component }
{ 2/ Then run CreateANewCompHeight procedure to set a new height for this comp.}
{ 3/ Then run the FetchComponentMidPoints procedure to fetch mid points. }
{ 4/ Run the RotateAComponent procedure to rotate and flip this new comp. }
{ }
{ Copyright (c) 2007 by Altium Limited }
{..............................................................................}
{..............................................................................}
Var
Board : IPCB_Board;
WorkSpace : IWorkSpace;
{..............................................................................}
{..............................................................................}
Function PlaceAPCBTrack(AX1, AY1, AX2, AY2 : TCoord; AWidth : TCoord; ALayer : TLayer) : IPCB_Track;
Var
T : IPCB_Track;
Begin
PCBServer.PreProcess;
T := PCBServer.PCBObjectFactory(eTrackObject,eNoDimension,eCreate_Default);
T.X1 := MilsToCoord(AX1);
T.Y1 := MilsToCoord(AY1);
T.X2 := MilsToCoord(AX2);
T.Y2 := MilsToCoord(AY2);
T.Layer := ALayer;
T.Width := MilsToCoord(AWidth);
PCBServer.PostProcess;
Result := T;
End;
{..............................................................................}
{..............................................................................}
Function PlaceAPCBPad(AX,AY : TCoord; ATopXSize, ATopYSize : TCoord; AHoleSize : TCoord; ALayer : TLayer; AName : String) : IPCB_Pad;
Var
P : IPCB_Pad;
PadCache : TPadCache;
Begin
Result := Nil;
Try
PCBServer.PreProcess;
P := PcbServer.PCBObjectFactory(ePadObject,eNoDimension,eCreate_Default);
If P = Nil Then Exit;
P.X := MilsToCoord(AX);
P.Y := MilsToCoord(AY);
P.TopXSize := MilsToCoord(ATopXSize);
P.TopYSize := MilsToCoord(ATopYSize);
P.HoleSize := MilsToCoord(AHoleSize);
P.Layer := ALayer;
P.Name := AName;
(* Setup a pad cache *)
Padcache := P.GetState_Cache;
Padcache.ReliefAirGap := MilsToCoord(11);
Padcache.PowerPlaneReliefExpansion := MilsToCoord(11);
Padcache.PowerPlaneClearance := MilsToCoord(11);
Padcache.ReliefConductorWidth := MilsToCoord(11);
Padcache.SolderMaskExpansion := MilsToCoord(11);
Padcache.SolderMaskExpansionValid := eCacheManual;
Padcache.PasteMaskExpansion := MilsToCoord(11);
Padcache.PasteMaskExpansionValid := eCacheManual;
(* Assign the new pad cache to the pad*)
P.SetState_Cache(Padcache);
Finally
PCBServer.PostProcess;
End;
Result := P;
End;
{..............................................................................}
{..............................................................................}
Procedure Place4Tracks(NewComp : IPCB_Component);
Var
NewTrack : IPCB_Track;
Begin
// Create a first track
NewTrack := PlaceAPCBTrack(50,50,250,50,10,eTopOverlay);
NewComp.AddPCBObject(NewTrack);
PCBServer.SendMessageToRobots(NewComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewTrack.I_ObjectAddress);
// Create a second track
NewTrack := PlaceAPCBTrack(250,50,250,-150,10,eTopOverlay);
NewComp.AddPCBObject(NewTrack);
PCBServer.SendMessageToRobots(NewComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewTrack.I_ObjectAddress);
// Create a third track
NewTrack := PlaceAPCBTrack(250,-150,50,-150,10,eTopOverlay);
NewComp.AddPCBObject(NewTrack);
PCBServer.SendMessageToRobots(NewComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewTrack.I_ObjectAddress);
// Create a second track
NewTrack := PlaceAPCBTrack(50,-150,50,50,10,eTopOverlay);
NewComp.AddPCBObject(NewTrack);
PCBServer.SendMessageToRobots(NewComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewTrack.I_ObjectAddress);
End;
{..............................................................................}
{..............................................................................}
Procedure Place4Pads(NewComp : IPCB_Component);
Var
NewPad : IPCB_Pad;
Begin
// Create a first pad
NewPad := PlaceAPCBPad(0,0,62,62,28,eMultiLayer,'1');
NewComp.AddPCBObject(NewPad);
PCBServer.SendMessageToRobots(NewComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewPad.I_ObjectAddress);
// Create a second pad
NewPad := PlaceAPCBPad(0,-100,62,62,28,eMultiLayer,'2');
NewComp.AddPCBObject(NewPad);
PCBServer.SendMessageToRobots(NewComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewPad.I_ObjectAddress);
// Create a third pad
NewPad := PlaceAPCBPad(300,0,62,62,28,eMultiLayer,'3');
NewComp.AddPCBObject(NewPad);
PCBServer.SendMessageToRobots(NewComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewPad.I_ObjectAddress);
// Create a fourth pad
NewPad := PlaceAPCBPad(300,-100,62,62,28,eMultiLayer,'4');
NewComp.AddPCBObject(NewPad);
PCBServer.SendMessageToRobots(NewComp.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,NewPad.I_ObjectAddress);
End;
{..............................................................................}
{..............................................................................}
Procedure PlaceAPCBComponent(AX,AY : TCoord);
Var
Comp : IPCB_Component;
Begin
PCBServer.PreProcess;
Comp := PCBServer.PCBObjectFactory(eComponentObject, eNoDimension, eCreate_Default);
If Comp = Nil Then Exit;
Place4Tracks(Comp);
Place4Pads (Comp);
// Set the reference point of the Component
Comp.X := MilsToCoord(AX);
Comp.Y := MilsToCoord(AY);
Comp.Layer := eTopLayer;
// Make the designator text visible;
Comp.NameOn := True;
Comp.Name.Text := 'Custom';
Comp.Name.XLocation := MilsToCoord(AX) - MilsToCoord(220);
Comp.Name.YLocation := MilsToCoord(AY) - MilsToCoord(220);
// Make the comment text visible;
Comp.CommentOn := True;
Comp.Comment.Text := 'Comment';
Comp.Comment.XLocation := MilsToCoord(AX) - MilsToCoord(220);
Comp.Comment.YLocation := MilsToCoord(AY) - MilsToCoord(300);
PCBServer.SendMessageToRobots(Board.I_ObjectAddress,c_Broadcast,PCBM_BoardRegisteration,Comp.I_ObjectAddress);
Board.AddPCBObject(Comp);
PCBServer.PostProcess;
End;
{..............................................................................}
{..............................................................................}
Procedure CreateAComponentOnPCB;
Var
OffSetX : Integer;
OffSetY : Integer;
NewPad : IPCB_Pad;
NewTrack : IPCB_Track;
BR : TCoordRect;
Begin
Client.StartServer('PCB');
// Create a new pcb document
WorkSpace := GetWorkSpace;
If WorkSpace = Nil Then Exit;
Workspace.DM_CreateNewDocument('PCB');
// Check if PCB document exists
If PCBServer = Nil Then Exit;
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil then exit;
// obtain the offsets so we can place objects inside the PCB board outline.
BR := Board.BoardOutline.BoundingRectangle;
OffsetX := Trunc(CoordToMils(BR.Left));
OffsetY := Trunc(CoordToMils(BR.Bottom)); //TReal to Integer
PlaceAPCBComponent(OffsetX + 3000, OffsetY + 1000);
Board.ViewManager_FullUpdate;
// Refresh PCB screen
Client.CommandLauncher.LaunchCommand('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView);
End;{..............................................................................}
{..............................................................................}
Procedure RotateAComponent;
Var
Board : IPCB_Board;
Iterator : IPCB_BoardIterator;
Component : IPCB_Component;
Layer : TLayer;
Begin
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil Then Exit;
// Initialize the PCB editor.
PCBServer.PreProcess;
//Grab the first component from the PCB only.
Iterator := Board.BoardIterator_Create;
Iterator.AddFilter_ObjectSet(MkSet(eComponentObject));
Iterator.AddFilter_LayerSet(AllLayers);
Iterator.AddFilter_Method(eProcessAll);
Component := Iterator.FirstPCBObject;
// If no components found, exit.
If Component = Nil Then
Begin
Board.BoardIterator_Destroy(Iterator);
Exit;
End;
// Notify the PCB that the pcb object is going to be modified
PCBServer.SendMessageToRobots(Component.I_ObjectAddress, c_Broadcast, PCBM_BeginModify , c_NoEventData);
// Set the reference point of the component.
// Note that IPCB_Component is inherited from IPCB_Group
// and thus the X,Y properties are inherited.
Component.X := Component.X + MilsToCoord(100);
Component.Y := Component.Y + MilsToCoord(100);
// Rotate a component 45 degrees.
Component.Rotation := 45;
// If Component is on Top layer, its placed on bottom layer and vice versa.
Layer := Component.Layer;
If (Layer = eTopLayer) Then
Begin
Component.Layer := eBottomLayer;
End
Else If (Layer = eBottomLayer) Then
Component.Layer := eTopLayer;
// Notify the PCB editor that the pcb object has been modified
PCBServer.SendMessageToRobots(Component.I_ObjectAddress, c_Broadcast, PCBM_EndModify , c_NoEventData);
Board.BoardIterator_Destroy(Iterator);
// Reset the PCB
PCBServer.PostProcess;
Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView);
End;
{..............................................................................}
{..............................................................................}
Var
MinX, MinY, MaxX, MaxY : Integer;
{..............................................................................}
{..............................................................................}
Procedure ProcessObjectsOfAComponent(Const P : IPCB_Primitive);
Var
R : TCoordRect;
Begin
// check for comment / name objects
If P.ObjectId <> eTextObject Then
Begin
R := P.BoundingRectangle;
If R.left < MinX Then MinX := R.left;
If R.bottom < MinY Then MinY := R.bottom;
If R.right > MaxX Then MaxX := R.right;
If R.top > MaxY Then MaxY := R.top;
End;
End;
{..............................................................................}
{..............................................................................}
Procedure FetchComponentMidPoints;
Var
MidX, MidY : Double;
Component : IPCB_Component;
Iterator : IPCB_BoardIterator;
Board : IPCB_Board;
S : TPCBString;
GroupIterator : IPCB_GroupIterator;
GroupHandle : IPCB_Primitive;
Begin
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil Then Exit;
BeginHourGlass;
// setting extreme constants...
MinX := 2147483647;
MinY := 2147483647;
MaxX := -2147483647;
MaxY := -2147483647;
// set up filter for component objects only
Iterator := Board.BoardIterator_Create;
Iterator.AddFilter_ObjectSet(MkSet(eComponentObject));
Iterator.AddFilter_LayerSet(AllLayers);
Iterator.AddFilter_Method(eProcessAll);
// Looks for the first component and then calculates the Mid X and MidY
// of this component taking all the prims of this component into account.
Component := Iterator.FirstPCBObject;
If Component <> Nil Then
Begin
GroupIterator := Component.GroupIterator_Create;
GroupIterator.AddFilter_ObjectSet(AllObjects);
GroupHandle := GroupIterator.FirstPCBObject;
While GroupHandle <> Nil Do
Begin
ProcessObjectsOfAComponent(GroupHandle);
GroupHandle := GroupIterator.NextPCBObject;
End;
Component.GroupIterator_Destroy(GroupIterator);
End;
Board.BoardIterator_Destroy(Iterator);
MidX := (MinX + MaxX)/2;
MidY := (MinY + MaxY)/2;
EndHourGlass;
S := Component.Name.Text;
ShowInfo('Component''s ' + S + ' midpoint X and Y are : '+ #13 +
'MidX = ' + FloatToStr(MidX) + ', MidY = ' + FloatToStr(MidY));
End;
{..............................................................................}
{..............................................................................}
Procedure CreateANewCompHeight;
Var
Component : IPCB_Component;
Iterator : IPCB_BoardIterator;
Board : IPCB_Board;
Begin
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil Then Exit;
Iterator := Board.BoardIterator_Create;
Iterator.AddFilter_ObjectSet(MkSet(eComponentObject));
Iterator.AddFilter_LayerSet(AllLayers);
Iterator.AddFilter_Method(eProcessAll);
// very first component on PCB document fetched.
// best have a PCB with only one component.
Component := Iterator.FirstPCBObject;
If Component <> Nil Then
Begin
ShowInfo('Component Designator ' + Component.SourceDesignator + #13 +
'Component''s Original Height = ' + IntToStr(Component.Height));
(* Notify PCB of a modify- the height of a component is going to be changed *)
Try
PCBServer.PreProcess;
PCBServer.SendMessageToRobots(Component.I_ObjectAddress, c_Broadcast, PCBM_BeginModify, c_noEventData);
(* objects coordinates are stored in internal coordinates values *)
Component.Height := MilsToCoord(25);
// notify PCB that the document is dirty bec comp height changed.
PCBServer.SendMessageToRobots(Component.I_ObjectAddress, c_Broadcast, PCBM_EndModify, c_noEventData);
Board.BoardIterator_Destroy(Iterator);
Finally
PCBServer.PostProcess;
End;
(* Check if component height has changed *)
ShowInfo('Component Designator ' + Component.SourceDesignator + #13 +
'Component''s New Height = ' + IntToStr(CoordToMils(Component.Height)) + ' mils');
End;
End;
{..............................................................................}
{..............................................................................}
End.
|
unit DesignTest;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TDesignHandle = class(TCustomControl)
protected
FHitRect: Integer;
FMouseIsDown: Boolean;
FMouseOffset: TPoint;
protected
function HandleRect(inIndex: Integer): TRect;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Paint; override;
end;
//
TDesignPanel = class(TCustomControl)
protected
FMouseIsDown: Boolean;
FMouseButton: TMouseButton;
FMouseOffset: TPoint;
protected
procedure AdjustClientRect(var Rect: TRect); override;
procedure DoEnter; override;
procedure DoExit; override;
procedure DrawFocusRect;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Paint; override;
procedure WndProc(var Message: TMessage); override;
public
constructor Create(inOwner: TComponent); override;
end;
//
TDesignTestForm = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Handles: array[0..3] of TDesignHandle;
Selected: TControl;
procedure UpdateHandles;
end;
var
DesignTestForm: TDesignTestForm;
implementation
{$R *.dfm}
const
S = 6;
Q = 8;
var
ShadedBits: TBitmap;
function NeedShadedBits: TBitmap;
begin
if ShadedBits = nil then
begin
//ShadedBits := AllocPatternBitmap(clSilver, clGray);
ShadedBits := TBitmap.Create;
ShadedBits.Width := 4;
ShadedBits.Height := 2;
ShadedBits.Canvas.Pixels[0, 0] := clGray;
ShadedBits.Canvas.Pixels[1, 0] := clBtnFace;
ShadedBits.Canvas.Pixels[2, 0] := clBtnFace;
ShadedBits.Canvas.Pixels[3, 0] := clBtnFace;
ShadedBits.Canvas.Pixels[0, 1] := clBtnFace;
ShadedBits.Canvas.Pixels[1, 1] := clBtnFace;
ShadedBits.Canvas.Pixels[2, 1] := clGray;
ShadedBits.Canvas.Pixels[3, 1] := clBtnFace;
end;
Result := ShadedBits;
end;
procedure DrawBitmapBrushFrame(inRect: TRect; inCanvas: TCanvas);
begin
with inCanvas do
begin
Brush.Bitmap := NeedShadedBits;
with inRect do
begin
FillRect(Rect(Left, Top, Left, Top + S));
FillRect(Rect(Left, Top, Left + S, Bottom));
FillRect(Rect(Right-S, Top, Right, Bottom));
FillRect(Rect(Left, Bottom - S, Left, Bottom));
end;
end;
end;
{ TDesignHandle }
function TDesignHandle.HandleRect(inIndex: Integer): TRect;
begin
case inIndex of
0: Result := Rect(0, 0, Q, Q);
1: Result := Rect((Width - Q) div 2, 0, (Width + Q) div 2, Q);
2: Result := Rect(Width - Q, 0, Width, Q);
3: Result := Rect(0, (Height - Q) div 2, Q, (Height + Q) div 2);
end;
end;
procedure TDesignHandle.Paint;
begin
inherited;
with Canvas do
begin
Brush.Bitmap := NeedShadedBits;
FillRect(ClientRect);
Brush.Bitmap := nil;
Brush.Color := clWhite;
Pen.Color := clBlack;
if (Width > Height) then
begin
Rectangle(HandleRect(0));
Rectangle(HandleRect(1));
Rectangle(HandleRect(2));
// Rectangle(0, 0, Q, Q);
// Rectangle((Width - Q) div 2, 0, (Width + Q) div 2, Q);
// Rectangle(Width - Q, 0, Width, Q);
end
else
Rectangle(HandleRect(3));
// Rectangle(0, (Height - Q) div 2, Q, (Height + Q) div 2);
end;
end;
procedure TDesignHandle.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
function HitRect(inR: Integer): Boolean;
var
r: TRect;
begin
r := HandleRect(inR);
Result := PtInRect(r, Point(X, Y));
end;
var
i: Integer;
begin
inherited;
for i := 0 to 3 do
if HitRect(i) then
begin
FHitRect := i;
FMouseIsDown := true;
FMouseOffset := Point(X, Y);
break;
end;
end;
procedure TDesignHandle.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
if FMouseIsDown then
begin
with ClientToParent(Point(X, Y)) do
begin
case FHitRect of
1:
begin
DesignTestForm.Selected.Height := DesignTestForm.Selected.Height
- ((Y - FMouseOffset.Y) - DesignTestForm.Selected.Top);
DesignTestForm.Selected.Top := Y - FMouseOffset.Y;
end;
3:
begin
DesignTestForm.Selected.Width := DesignTestForm.Selected.Width
- ((X - FMouseOffset.X) - DesignTestForm.Selected.Left);
DesignTestForm.Selected.Left := X - FMouseOffset.X;
end;
end;
DesignTestForm.UpdateHandles;
end;
end;
end;
procedure TDesignHandle.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
FMouseIsDown := false;
end;
{ TDesignPanel }
constructor TDesignPanel.Create(inOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [ csAcceptsControls ];
end;
type
TControlCracker = class(TControl);
procedure TDesignPanel.WndProc(var Message: TMessage);
var
ctrlWndProc: TWndMethod;
begin
case Message.Msg of
WM_MOUSEFIRST..WM_MOUSELAST:
begin
TMethod(ctrlWndProc).code := @TControlCracker.WndProc;
TMethod(ctrlWndProc).data := Self;
ctrlWndProc( Message );
end
else
inherited WndProc( Message );
end;
end;
procedure TDesignPanel.AdjustClientRect(var Rect: TRect);
begin
inherited;
//InflateRect(Rect, -8, -8);
end;
{
procedure TDesignPanel.DrawFocusRect;
var
r: TRect;
desktopWindow: HWND;
dc: HDC;
c: TCanvas;
begin
with r do
begin
topLeft := ClientToScreen(Point(0, 0));
bottomRight := ClientToScreen(Point(Width, Height));
end;
//
desktopWindow := GetDesktopWindow;
dc := GetDCEx(desktopWindow, 0, DCX_CACHE or DCX_LOCKWINDOWUPDATE);
try
c := TCanvas.Create;
try
c.Handle := dc;
DrawBitmapBrushFrame(r, c);
finally
c.Free;
end;
finally
ReleaseDC(desktopWindow, dc);
end;
end;
}
procedure TDesignPanel.DrawFocusRect;
begin
with Canvas do
begin
if Brush.Bitmap = nil then
begin
Brush.Bitmap := TBitmap.Create;
Brush.Bitmap.Height := 2;
Brush.Bitmap.Width := 2;
Brush.Bitmap.Canvas.Pixels[0, 0] := clSilver;
Brush.Bitmap.Canvas.Pixels[1, 0] := clGray;
Brush.Bitmap.Canvas.Pixels[1, 1] := clSilver;
Brush.Bitmap.Canvas.Pixels[0, 1] := clGray;
end;
//
//Brush.Style := bsBDiagonal;
//Brush.Color := clGray;
//SetBkColor(Canvas.Handle, clSilver);
FillRect(Rect(0, 0, Width, S));
FillRect(Rect(0, 0, S, Height));
FillRect(Rect(Width-S, 0, Width, Height));
FillRect(Rect(0, Height - S, Width, Height));
end;
end;
procedure TDesignPanel.Paint;
begin
inherited;
// if Focused then
// DrawFocusRect;
end;
procedure TDesignPanel.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
SetFocus;
FMouseIsDown := true;
FMouseOffset := Point(X, Y);
end;
procedure TDesignPanel.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
if FMouseIsDown then
begin
//FMouseLast := ClientToParent(X, Y);
with ClientToParent(Point(X, Y)) do
begin
X := X - FMouseOffset.X;
Y := Y - FMouseOffset.Y;
BoundsRect := Rect(X, Y, X + Width, Y + Height);
DesignTestForm.UpdateHandles;
end;
end;
end;
procedure TDesignPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
// Mouse.Capture := 0;
FMouseIsDown := false;
end;
procedure TDesignPanel.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited;
if FMouseIsDown and (Key = VK_ESCAPE) then
begin
// Mouse.Capture := 0;
FMouseIsDown := false;
end;
end;
procedure TDesignPanel.DoEnter;
begin
inherited;
DesignTestForm.Selected := Self;
DesignTestForm.UpdateHandles;
//Invalidate;
end;
procedure TDesignPanel.DoExit;
begin
inherited;
Invalidate;
end;
{ TDesignTestForm }
procedure TDesignTestForm.FormCreate(Sender: TObject);
var
p: TDesignPanel;
begin
Handles[0] := TDesignHandle.Create(Self);
Handles[0].Parent := Self;
Handles[1] := TDesignHandle.Create(Self);
Handles[1].Parent := Self;
Handles[2] := TDesignHandle.Create(Self);
Handles[2].Parent := Self;
Handles[3] := TDesignHandle.Create(Self);
Handles[3].Parent := Self;
//
p := TDesignPanel.Create(Self);
with p do
begin
Left := 24;
Top := 24;
Width := 96;
Height := 84;
Parent := Self;
end;
with TLabel.Create(p) do
begin
Caption := 'Test1';
Align := alClient;
Color := clWhite;
Parent := p;
end;
p := TDesignPanel.Create(Self);
with p do
begin
Left := 44;
Top := 44;
Width := 96;
Height := 84;
Parent := Self;
end;
with TLabel.Create(p) do
begin
Caption := 'Test2';
Align := alClient;
Color := clWhite;
Parent := p;
end;
Selected := p;
UpdateHandles;
Show;
end;
procedure TDesignTestForm.UpdateHandles;
var
i: Integer;
begin
if Selected <> nil then
with Selected.BoundsRect do
begin
Handles[0].BoundsRect := Rect(Left - Q, Top - Q, Right + Q, Top);
Handles[1].BoundsRect := Rect(Left - Q, Top, Left, Bottom);
Handles[2].BoundsRect := Rect(Right, Top, Right + Q, Bottom);
Handles[3].BoundsRect := Rect(Left - Q, Bottom, Right + Q, Bottom + Q);
end;
for i := 0 to 3 do
begin
Handles[i].Visible := Selected <> nil;
Handles[i].BringToFront;
end;
DesignTestForm.Update;
end;
end.
|
unit InflatablesList_HTML_ElementFinder;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
AuxTypes,
InflatablesList_Types,
InflatablesList_HTML_TagAttributeArray,
InflatablesList_HTML_Document;
type
TILSearchOperator = (ilsoAND,ilsoOR,ilsoXOR);
TILFinderBaseClass = class(TObject)
protected
fVariables: TILItemShopParsingVariables;
fStringPrefix: String; // all returned strings are prepended with, not saved
fStringSuffix: String; // appended to all returned strings, not saved
fIndex: Integer; // index in comparator croup
fEmptyStrAllow: Boolean; // marks whether AsString can return an empty string or must return at least a placeholder
fIsLeading: Boolean; // transient (not copied in copy constructor)
procedure SetStringPrefix(const Value: String);
procedure SetStringSuffix(const Value: String);
Function GetTotalItemCount: Integer; virtual;
Function GetIsSimple: Boolean; virtual;
public
constructor Create;
constructor CreateAsCopy(Source: TILFinderBaseClass; UniqueCopy: Boolean);
procedure Prepare(Variables: TILItemShopParsingVariables); virtual;
Function AsString(Decorate: Boolean = True): String; virtual; // returns string describing the comparator
Function Search(const SearchSettings: TILAdvSearchSettings): Boolean; virtual;
property Variables: TILItemShopParsingVariables read fVariables;
property StringPrefix: String read fStringPrefix write SetStringPrefix;
property StringSuffix: String read fStringSuffix write SetStringSuffix;
property Index: Integer read fIndex write fIndex;
property EmptyStringAllowed: Boolean read fEmptyStrAllow write fEmptyStrAllow;
property TotalItemCount: Integer read GetTotalItemCount;
{
IsSimple is true for comparators and groups with only simple comparator,
false for other groups (more than one subitem, or no subitem)
}
property IsSimple: Boolean read GetIsSimple;
{
IsLeading is true when object is first in a group or is standalone,
false otherwise.
It is initialized to true and must be managed externally.
}
property IsLeading: Boolean read fIsLeading write fIsLeading;
end;
//------------------------------------------------------------------------------
TILComparatorBase = class(TILFinderBaseClass)
protected
fVariableIdx: Integer;
fNegate: Boolean;
fOperator: TILSearchOperator;
fResult: Boolean; // result of the comparison operation, not saved
public
constructor Create;
constructor CreateAsCopy(Source: TILComparatorBase; UniqueCopy: Boolean);
procedure ReInit; virtual;
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
property VariableIndex: Integer read fVariableIdx write fVariableIdx;
property Negate: Boolean read fNegate write fNegate;
property Operator: TILSearchOperator read fOperator write fOperator;
property Result: Boolean read fResult;
end;
//==============================================================================
TILTextComparatorBase = class(TILComparatorBase)
public
// following methods must be implemented in all text comparators
procedure Compare(const Text: String); overload; virtual; abstract;
procedure Compare(const Text: TILReconvString); overload; virtual; abstract;
end;
//------------------------------------------------------------------------------
TILTextComparator = class(TILTextComparatorBase)
protected
fStr: String; // string that will be compared with text passed to Compare methods
fCaseSensitive: Boolean;
fAllowPartial: Boolean;
procedure SetStr(const Value: String);
public
constructor Create;
constructor CreateAsCopy(Source: TILTextComparator; UniqueCopy: Boolean);
Function AsString(Decorate: Boolean = True): String; override;
Function Search(const SearchSettings: TILAdvSearchSettings): Boolean; override;
procedure Compare(const Text: String); override;
procedure Compare(const Text: TILReconvString); override;
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromStream(Stream: TStream); override;
property Str: String read fStr write SetStr;
property CaseSensitive: Boolean read fCaseSensitive write fCaseSensitive;
property AllowPartial: Boolean read fAllowPartial write fAllowPartial;
end;
//------------------------------------------------------------------------------
TILTextComparatorGroup = class(TILTextComparatorBase)
protected
fItems: array of TILTextComparatorBase;
Function GetItemCount: Integer;
Function GetItem(Index: Integer): TILTextComparatorBase;
Function GetTotalItemCount: Integer; override;
Function GetIsSimple: Boolean; override;
procedure ReIndex; virtual;
procedure MarkLeading; virtual;
public
constructor Create;
constructor CreateAsCopy(Source: TILTextComparatorGroup; UniqueCopy: Boolean);
destructor Destroy; override;
Function AsString(Decorate: Boolean = True): String; override;
Function Search(const SearchSettings: TILAdvSearchSettings): Boolean; override;
procedure Prepare(Variables: TILItemShopParsingVariables); override;
procedure ReInit; override;
Function IndexOf(Item: TObject): Integer; virtual;
Function AddComparator(Negate: Boolean = False; Operator: TILSearchOperator = ilsoAND): TILTextComparator; virtual;
Function AddGroup(Negate: Boolean = False; Operator: TILSearchOperator = ilsoAND): TILTextComparatorGroup; virtual;
Function Remove(Item: TObject): Integer; virtual;
procedure Delete(Index: Integer); virtual;
procedure Clear; virtual;
procedure Compare(const Text: String); override;
procedure Compare(const Text: TILReconvString); override;
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromStream(Stream: TStream); override;
property Count: Integer read GetItemCount;
property Items[Index: Integer]: TILTextComparatorBase read GetItem; default;
end;
//==============================================================================
TILAttributeComparatorBase = class(TILComparatorBase)
public
procedure Compare(TagAttribute: TILHTMLTagAttribute); virtual; abstract;
end;
//------------------------------------------------------------------------------
TILAttributeComparator = class(TILAttributeComparatorBase)
protected
fName: TILTextComparatorGroup;
fValue: TILTextComparatorGroup;
Function GetTotalItemCount: Integer; override;
Function GetIsSimple: Boolean; override;
public
constructor Create;
constructor CreateAsCopy(Source: TILAttributeComparator; UniqueCopy: Boolean);
destructor Destroy; override;
Function AsString(Decorate: Boolean = True): String; override;
Function Search(const SearchSettings: TILAdvSearchSettings): Boolean; override;
procedure Prepare(Variables: TILItemShopParsingVariables); override;
procedure ReInit; override;
procedure Compare(TagAttribute: TILHTMLTagAttribute); override;
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromStream(Stream: TStream); override;
property Name: TILTextComparatorGroup read fName;
property Value: TILTextComparatorGroup read fValue;
end;
//------------------------------------------------------------------------------
TILAttributeComparatorGroup = class(TILAttributeComparatorBase)
protected
fItems: array of TILAttributeComparatorBase;
Function GetItemCount: Integer;
Function GetItem(Index: Integer): TILAttributeComparatorBase;
Function GetTotalItemCount: Integer; override;
Function GetIsSimple: Boolean; override;
procedure ReIndex; virtual;
procedure MarkLeading; virtual;
public
constructor Create;
constructor CreateAsCopy(Source: TILAttributeComparatorGroup; UniqueCopy: Boolean);
destructor Destroy; override;
Function AsString(Decorate: Boolean = True): String; override;
Function Search(const SearchSettings: TILAdvSearchSettings): Boolean; override;
procedure Prepare(Variables: TILItemShopParsingVariables); override;
procedure ReInit; override;
Function IndexOf(Item: TObject): Integer; virtual;
Function AddComparator(Negate: Boolean = False; Operator: TILSearchOperator = ilsoAND): TILAttributeComparator; virtual;
Function AddGroup(Negate: Boolean = False; Operator: TILSearchOperator = ilsoAND): TILAttributeComparatorGroup; virtual;
Function Remove(Item: TObject): Integer; virtual;
procedure Delete(Index: Integer); virtual;
procedure Clear; virtual;
procedure Compare(TagAttribute: TILHTMLTagAttribute); override;
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromStream(Stream: TStream); override;
property Count: Integer read GetItemCount;
property Items[Index: Integer]: TILAttributeComparatorBase read GetItem; default;
end;
//==============================================================================
TILElementComparator = class(TILFinderBaseClass)
protected
fTagName: TILTextComparatorGroup;
fAttributes: TILAttributeComparatorGroup;
fText: TILTextComparatorGroup;
fNestedText: Boolean;
fResult: Boolean;
Function GetTotalItemCount: Integer; override;
Function GetIsSimple: Boolean; override;
public
constructor Create;
constructor CreateAsCopy(Source: TILElementComparator; UniqueCopy: Boolean);
destructor Destroy; override;
Function AsString(Decorate: Boolean = True): String; override;
Function Search(const SearchSettings: TILAdvSearchSettings): Boolean; override;
procedure Prepare(Variables: TILItemShopParsingVariables); override;
procedure ReInit; virtual;
procedure Compare(Element: TILHTMLElementNode); virtual;
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
property TagName: TILTextComparatorGroup read fTagName;
property Attributes: TILAttributeComparatorGroup read fAttributes;
property Text: TILTextComparatorGroup read fText;
property NestedText: Boolean read fNestedText write fNestedText;
property Result: Boolean read fResult;
end;
//==============================================================================
TILElementFinderStage = class(TILFinderBaseClass)
protected
fItems: array of TILElementComparator;
Function GetItemCount: Integer;
Function GetItem(Index: Integer): TILElementComparator;
Function GetTotalItemCount: Integer; override;
procedure ReIndex; virtual;
public
constructor Create;
constructor CreateAsCopy(Source: TILElementFinderStage; UniqueCopy: Boolean);
destructor Destroy; override;
Function AsString(Decorate: Boolean = True): String; override;
Function Search(const SearchSettings: TILAdvSearchSettings): Boolean; override;
procedure Prepare(Variables: TILItemShopParsingVariables); override;
procedure ReInit; virtual;
Function IndexOf(Item: TObject): Integer; virtual;
Function AddComparator: TILElementComparator; virtual;
Function Remove(Item: TObject): Integer; virtual;
procedure Delete(Index: Integer); virtual;
procedure Clear; virtual;
Function Compare(Element: TILHTMLElementNode): Boolean; virtual;
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
property Count: Integer read GetItemCount;
property Items[Index: Integer]: TILElementComparator read GetItem; default;
end;
//------------------------------------------------------------------------------
TILElementFinder = class(TILFinderBaseClass)
private
fStages: array of TILElementFinderStage;
Function GetStageCount: Integer;
Function GetStage(Index: Integer): TILElementFinderStage;
protected
Function GetTotalItemCount: Integer; override;
procedure ReIndex; virtual;
public
constructor Create;
constructor CreateAsCopy(Source: TILElementFinder; UniqueCopy: Boolean);
destructor Destroy; override;
Function Search(const SearchSettings: TILAdvSearchSettings): Boolean; override;
procedure Prepare(Variables: TILItemShopParsingVariables); override;
procedure ReInit; virtual;
Function StageIndexOf(Stage: TObject): Integer; virtual;
Function StageAdd: TILElementFinderStage; virtual;
Function StageRemove(Stage: TObject): Integer; virtual;
procedure StageDelete(Index: Integer); virtual;
procedure StageClear; virtual;
Function FindElements(Document: TILHTMLDocument; out Elements: TILHTMLElements): Boolean; virtual;
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
property StageCount: Integer read GetStageCount;
property Stages[Index: Integer]: TILElementFinderStage read GetStage; default;
end;
//******************************************************************************
Function IL_SearchOperatorToNum(SearchOperator: TILSearchOperator): Int32;
Function IL_NumToSearchOperator(Num: Int32): TILSearchOperator;
Function IL_SearchOperatorAsStr(SearchOperator: TILSearchOperator): String;
Function IL_NegateValue(Value,Negate: Boolean): Boolean; overload;
Function IL_CombineUsingOperator(A,B: Boolean; Operator: TILSearchOperator): Boolean;
implementation
uses
SysUtils,
BinaryStreaming, CountedDynArrayObject,
InflatablesList_Utils;
const
IL_SEARCH_TEXTCOMPARATOR = UInt32($FFAA3400);
IL_SEARCH_TEXTCOMPARATORGROUP = UInt32($FFAA3401);
IL_SEARCH_ATTRCOMPARATOR = UInt32($FFAA3402);
IL_SEARCH_ATTRCOMPARATORGROUP = UInt32($FFAA3403);
IL_SEARCH_ELEMENTCOMPARATOR = UInt32($FFAA3404);
IL_SEARCH_ELEMENTCOMPARATORGROUP = UInt32($FFAA3405);
//==============================================================================
Function IL_SearchOperatorToNum(SearchOperator: TILSearchOperator): Int32;
begin
case SearchOperator of
ilsoOR: Result := 1;
ilsoXOR: Result := 2;
else
{ilsoAND}
Result := 0;
end;
end;
//------------------------------------------------------------------------------
Function IL_NumToSearchOperator(Num: Int32): TILSearchOperator;
begin
case Num of
1: Result := ilsoOR;
2: Result := ilsoXOR;
else
Result := ilsoAND;
end;
end;
//------------------------------------------------------------------------------
Function IL_SearchOperatorAsStr(SearchOperator: TILSearchOperator): String;
begin
case SearchOperator of
ilsoOR: Result := 'or';
ilsoXOR: Result := 'xor';
else
{ilsoAND}
Result := 'and';
end;
end;
//------------------------------------------------------------------------------
Function IL_NegateValue(Value,Negate: Boolean): Boolean;
begin
If Negate then
Result := not Value
else
Result := Value;
end;
//------------------------------------------------------------------------------
Function IL_CombineUsingOperator(A,B: Boolean; Operator: TILSearchOperator): Boolean;
begin
case Operator of
ilsoOR: Result := A or B;
ilsoXOR: Result := A xor B;
else
{ilsoAND}
Result := A and B;
end;
end;
//******************************************************************************
//******************************************************************************
procedure TILFinderBaseClass.SetStringPrefix(const Value: String);
begin
fStringPrefix := Value;
UniqueString(fStringPrefix);
end;
//------------------------------------------------------------------------------
procedure TILFinderBaseClass.SetStringSuffix(const Value: String);
begin
fStringSuffix := Value;
UniqueString(fStringSuffix);
end;
//------------------------------------------------------------------------------
Function TILFinderBaseClass.GetTotalItemCount: Integer;
begin
Result := 1;
end;
//------------------------------------------------------------------------------
Function TILFinderBaseClass.GetIsSimple: Boolean;
begin
Result := True;
end;
//==============================================================================
constructor TILFinderBaseClass.Create;
var
i: Integer;
begin
inherited Create;
For i := Low(fVariables.Vars) to High(fVariables.Vars) do
fVariables.Vars[i] := '';
fStringPrefix := '';
fStringSuffix := '';
fIndex := -1;
fEmptyStrAllow := True;
fIsLeading := True;
end;
//------------------------------------------------------------------------------
constructor TILFinderBaseClass.CreateAsCopy(Source: TILFinderBaseClass; UniqueCopy: Boolean);
begin
Create;
fVariables := IL_ThreadSafeCopy(Source.Variables);
fStringPrefix := Source.StringPrefix;
UniqueString(fStringPrefix);
fStringSuffix := Source.StringSuffix;
UniqueString(fStringSuffix);
fIndex := Source.Index;
fEmptyStrAllow := Source.EmptyStringAllowed;
end;
//------------------------------------------------------------------------------
procedure TILFinderBaseClass.Prepare(Variables: TILItemShopParsingVariables);
begin
fVariables := IL_ThreadSafeCopy(Variables);
end;
//------------------------------------------------------------------------------
Function TILFinderBaseClass.AsString(Decorate: Boolean = True): String;
begin
If Decorate then
Result := IL_Format('%s%s(%p)%s',[fStringPrefix,Self.ClassName,Pointer(Self),fStringSuffix])
else
Result := IL_Format('%s(%p)',[Self.ClassName,Pointer(Self)])
end;
//------------------------------------------------------------------------------
Function TILFinderBaseClass.Search(const SearchSettings: TILAdvSearchSettings): Boolean;
begin
Result := False;
end;
//******************************************************************************
//******************************************************************************
constructor TILComparatorBase.Create;
begin
inherited Create;
fVariableIdx := -1;
fNegate := False;
fOperator := ilsoAND;
fResult := False;
end;
//------------------------------------------------------------------------------
constructor TILComparatorBase.CreateAsCopy(Source: TILComparatorBase; UniqueCopy: Boolean);
begin
inherited CreateAsCopy(Source,UniqueCopy);
fVariableIdx := Source.VariableIndex;
fNegate := Source.Negate;
fOperator := Source.Operator;
fResult := Source.Result;
end;
//------------------------------------------------------------------------------
procedure TILComparatorBase.ReInit;
begin
fResult := False;
end;
//------------------------------------------------------------------------------
procedure TILComparatorBase.SaveToStream(Stream: TStream);
begin
Stream_WriteInt32(Stream,fVariableIdx);
Stream_WriteBool(Stream,fNegate);
Stream_WriteInt32(Stream,IL_SearchOperatorToNum(fOperator));
end;
//------------------------------------------------------------------------------
procedure TILComparatorBase.LoadFromStream(Stream: TStream);
begin
fVariableIdx := Stream_ReadInt32(Stream);
fNegate := Stream_ReadBool(Stream);
fOperator := IL_NumToSearchOperator(Stream_ReadInt32(Stream));
end;
//******************************************************************************
//******************************************************************************
procedure TILTextComparator.SetStr(const Value: String);
begin
fStr := Value;
UniqueString(fStr);
end;
//==============================================================================
constructor TILTextComparator.Create;
begin
inherited Create;
fStr := '';
fCaseSensitive := False;
fAllowPartial := False;
end;
//------------------------------------------------------------------------------
constructor TILTextComparator.CreateAsCopy(Source: TILTextComparator; UniqueCopy: Boolean);
begin
inherited CreateAsCopy(Source,UniqueCopy);
fStr := Source.Str;
UniqueString(fStr);
fCaseSensitive := Source.CaseSensitive;
fAllowPartial := Source.AllowPartial;
end;
//------------------------------------------------------------------------------
Function TILTextComparator.AsString(Decorate: Boolean = True): String;
begin
If fCaseSensitive or fAllowPartial or fNegate or (fIndex > 0) then
Result := '"%s"'
else
Result := '%s';
If fCaseSensitive then
Result := IL_Format('?^%s',[Result]);
If fAllowPartial then
Result := IL_Format('*.%s.*',[Result]);
If fNegate then
Result := IL_Format('not(%s)',[Result]);
If Decorate then
begin
If fIndex > 0 then
Result := IL_Format('%s%s %s%s',[fStringPrefix,IL_SearchOperatorAsStr(fOperator),Result,fStringSuffix])
else
Result := IL_Format('%s%s%s',[fStringPrefix,Result,fStringSuffix]);
end
else
begin
If fIndex > 0 then
Result := IL_Format('%s %s',[IL_SearchOperatorAsStr(fOperator),Result]);
// current result does not change for fIndex <= 0
end;
If fVariableIdx < 0 then
begin
If Length(Result) + Length(fStr) > 25 then
Result := IL_Format(Result,['...'])
else
Result := IL_Format(Result,[fStr]);
end
else Result := IL_Format(Result,[IL_Format('#VAR%d#',[fVariableIdx + 1])]);
end;
//------------------------------------------------------------------------------
Function TILTextComparator.Search(const SearchSettings: TILAdvSearchSettings): Boolean;
begin
Result := SearchSettings.CompareFunc(fStr,True,True,False);
end;
//------------------------------------------------------------------------------
procedure TILTextComparator.Compare(const Text: String);
var
Temp: String;
begin
If (fVariableIdx >= Low(fVariables.Vars)) and (fVariableIdx <= High(fVariables.Vars)) then
Temp := fVariables.Vars[fVariableIdx]
else
Temp := fStr;
If fCaseSensitive then
begin
If fAllowPartial then
fResult := IL_ContainsStr(Text,Temp)
else
fResult := IL_SameStr(Text,Temp);
end
else
begin
If fAllowPartial then
fResult := IL_ContainsText(Text,Temp)
else
fResult := IL_SameText(Text,Temp);
end;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TILTextComparator.Compare(const Text: TILReconvString);
begin
fResult := False;
Compare(Text.Str);
If not Result then
begin
Compare(Text.UTF8Reconv);
If not Result then
Compare(Text.AnsiReconv);
end;
end;
//------------------------------------------------------------------------------
procedure TILTextComparator.SaveToStream(Stream: TStream);
begin
Stream_WriteUInt32(Stream,IL_SEARCH_TEXTCOMPARATOR);
inherited SaveToStream(Stream);
Stream_WriteString(Stream,fStr);
Stream_WriteBool(Stream,fCaseSensitive);
Stream_WriteBool(Stream,fAllowPartial);
end;
//------------------------------------------------------------------------------
procedure TILTextComparator.LoadFromStream(Stream: TStream);
begin
If Stream_ReadUInt32(Stream) <> IL_SEARCH_TEXTCOMPARATOR then
raise Exception.Create('TILTextComparator.LoadFromStream: Invalid stream format.');
inherited LoadFromStream(Stream);
fStr := Stream_ReadString(Stream);
fCaseSensitive := Stream_ReadBool(Stream);
fAllowPartial := Stream_ReadBool(Stream);
end;
//******************************************************************************
//******************************************************************************
Function TILTextComparatorGroup.GetItemCount: Integer;
begin
Result := Length(fItems);
end;
//------------------------------------------------------------------------------
Function TILTextComparatorGroup.GetItem(Index: Integer): TILTextComparatorBase;
begin
If (Index >= Low(fItems)) and (Index <= High(fItems)) then
Result := fItems[Index]
else
raise Exception.CreateFmt('TILTextComparatorGroup.GetItem: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TILTextComparatorGroup.GetTotalItemCount: Integer;
var
i: Integer;
begin
Result := inherited GetTotalItemCount;
For i := Low(fItems) to High(fItems) do
Inc(Result,fItems[i].TotalItemCount);
end;
//------------------------------------------------------------------------------
Function TILTextComparatorGroup.GetIsSimple: Boolean;
begin
If Length(fItems) = 1 then
Result := fItems[Low(fItems)] is TILTextComparator
else
Result := False;
end;
//------------------------------------------------------------------------------
procedure TILTextComparatorGroup.ReIndex;
var
i: Integer;
begin
For i := Low(fItems) to High(fItems) do
fItems[i].Index := i;
end;
//------------------------------------------------------------------------------
procedure TILTextComparatorGroup.MarkLeading;
var
i: Integer;
begin
For i := Low(fItems) to High(fItems) do
fItems[i].IsLeading := i <= Low(fItems);
end;
//==============================================================================
constructor TILTextComparatorGroup.Create;
begin
inherited Create;
SetLength(fItems,0);
end;
//------------------------------------------------------------------------------
constructor TILTextComparatorGroup.CreateAsCopy(Source: TILTextComparatorGroup; UniqueCopy: Boolean);
var
i: Integer;
begin
inherited CreateAsCopy(Source,UniqueCopy);
SetLength(fItems,Source.Count);
For i := Low(fItems) to High(fItems) do
If Source.Items[i] is TILTextComparatorGroup then
fItems[i] := TILTextComparatorGroup.CreateAsCopy(TILTextComparatorGroup(Source.Items[i]),UniqueCopy)
else
fItems[i] := TILTextComparator.CreateAsCopy(TILTextComparator(Source.Items[i]),UniqueCopy);
MarkLeading;
end;
//------------------------------------------------------------------------------
destructor TILTextComparatorGroup.Destroy;
begin
Clear;
inherited;
end;
//------------------------------------------------------------------------------
Function TILTextComparatorGroup.AsString(Decorate: Boolean = True): String;
begin
If GetIsSimple then
begin
// there is exactly one subnode and that is a plain text comparator
// do not decorate it, it will be done further here
Result := fItems[Low(fItems)].AsString(False);
If (Length(Result) <= 0) and not fEmptyStrAllow then
Result := '(...)';
end
else
begin
If Length(fItems) > 1 then
Result := IL_Format('(...x%d)',[Length(fItems)])
else If Length(fItems) = 1 then
Result := '(...)'
else If not fEmptyStrAllow then
Result := '()'
else
Result := '';
end;
If fNegate then
Result := IL_Format('not(%s)',[Result]);
If Decorate then
begin
If fIndex > 0 then
Result := IL_Format('%s%s %s%s',[fStringPrefix,IL_SearchOperatorAsStr(fOperator),Result,fStringSuffix])
else
Result := IL_Format('%s%s%s',[fStringPrefix,Result,fStringSuffix]);
end
else
begin
If fIndex > 0 then
Result := IL_Format('%s %s',[IL_SearchOperatorAsStr(fOperator),Result]);
end;
end;
//------------------------------------------------------------------------------
Function TILTextComparatorGroup.Search(const SearchSettings: TILAdvSearchSettings): Boolean;
var
i: Integer;
begin
Result := False;
For i := Low(fItems) to High(fItems) do
If fItems[i].Search(SearchSettings) then
begin
Result := True;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
procedure TILTextComparatorGroup.Prepare(Variables: TILItemShopParsingVariables);
var
i: Integer;
begin
inherited Prepare(Variables);
For i := Low(fItems) to High(fItems) do
fItems[i].Prepare(Variables);
end;
//------------------------------------------------------------------------------
procedure TILTextComparatorGroup.ReInit;
var
i: Integer;
begin
inherited;
For i := Low(fItems) to High(fItems) do
fItems[i].ReInit;
end;
//------------------------------------------------------------------------------
Function TILTextComparatorGroup.IndexOf(Item: TObject): Integer;
var
i: Integer;
begin
Result := -1;
For i := Low(fItems) to High(fItems) do
If fItems[i] = Item then
begin
Result := i;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
Function TILTextComparatorGroup.AddComparator(Negate: Boolean = False; Operator: TILSearchOperator = ilsoAND): TILTextComparator;
begin
SetLength(fItems,Length(fItems) + 1);
Result := TILTextComparator.Create;
fItems[High(fItems)] := Result;
Result.Index := High(fItems);
Result.Negate := Negate;
Result.Operator := Operator;
MarkLeading;
end;
//------------------------------------------------------------------------------
Function TILTextComparatorGroup.AddGroup(Negate: Boolean = False; Operator: TILSearchOperator = ilsoAND): TILTextComparatorGroup;
begin
SetLength(fItems,Length(fItems) + 1);
Result := TILTextComparatorGroup.Create;
fItems[High(fItems)] := Result;
Result.Index := High(fItems);
Result.EmptyStringAllowed := False;
Result.Negate := Negate;
Result.Operator := Operator;
MarkLeading;
end;
//------------------------------------------------------------------------------
Function TILTextComparatorGroup.Remove(Item: TObject): Integer;
begin
Result := IndexOf(Item);
If Result >= 0 then
Delete(Result);
end;
//------------------------------------------------------------------------------
procedure TILTextComparatorGroup.Delete(Index: Integer);
var
i: Integer;
begin
If (Index >= Low(fItems)) and (Index <= High(fItems)) then
begin
fItems[Index].Free;
For i := Index to Pred(High(fItems)) do
fItems[i] := fItems[i + 1];
SetLength(fItems,Length(fItems) - 1);
ReIndex;
MarkLeading;
end
else raise Exception.CreateFmt('TILTextComparatorGroup.Delete: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TILTextComparatorGroup.Clear;
var
i: Integer;
begin
For i := Low(fItems) to High(fItems) do
fItems[i].Free;
SetLength(fItems,0);
end;
//------------------------------------------------------------------------------
procedure TILTextComparatorGroup.Compare(const Text: String);
var
i: Integer;
begin
If Length(fItems) > 0 then
begin
// do comparison
For i := Low(fItems) to High(fItems) do
fItems[i].Compare(Text);
// get result from first item and then combine it with other results
fResult := IL_NegateValue(fItems[Low(fItems)].Result,fItems[Low(fItems)].Negate);
For i := Succ(Low(fItems)) to High(fItems) do
fResult := IL_CombineUsingOperator(
fResult,IL_NegateValue(fItems[i].Result,fItems[i].Negate),fItems[i].Operator)
end
else fResult := False;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TILTextComparatorGroup.Compare(const Text: TILReconvString);
begin
fResult := False;
Compare(Text.Str);
If not Result then
begin
Compare(Text.UTF8Reconv);
If not Result then
Compare(Text.AnsiReconv);
end;
end;
//------------------------------------------------------------------------------
procedure TILTextComparatorGroup.SaveToStream(Stream: TStream);
var
i: Integer;
begin
Stream_WriteUInt32(Stream,IL_SEARCH_TEXTCOMPARATORGROUP);
inherited SaveToStream(Stream);
Stream_WriteUInt32(Stream,Length(fItems));
For i := Low(fItems) to High(fItems) do
fItems[i].SaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILTextComparatorGroup.LoadFromStream(Stream: TStream);
var
i: Integer;
begin
Clear;
If Stream_ReadUInt32(Stream) <> IL_SEARCH_TEXTCOMPARATORGROUP then
raise Exception.Create('TILTextComparatorGroup.LoadFromStream: Invalid stream format.');
inherited LoadFromStream(Stream);
SetLength(fItems,Stream_ReadUInt32(Stream));
For i := Low(fItems) to High(fItems) do
begin
case Stream_ReadUInt32(Stream,False) of
IL_SEARCH_TEXTCOMPARATOR: fItems[i] := TILTextComparator.Create;
IL_SEARCH_TEXTCOMPARATORGROUP: fItems[i] := TILTextComparatorGroup.Create;
else
raise Exception.Create('TILTextComparatorGroup.LoadFromStream: Invalid subitem.');
end;
fItems[i].LoadFromStream(Stream);
fItems[i].Index := i;
If fItems[i] is TILTextComparatorGroup then
fItems[i].EmptyStringAllowed := False;
fItems[i].IsLeading := i <= Low(fItems);
end;
end;
//******************************************************************************
//******************************************************************************
Function TILAttributeComparator.GetTotalItemCount: Integer;
begin
Result := inherited GetTotalItemCount;
Inc(Result,fName.TotalItemCount);
Inc(Result,fValue.TotalItemCount);
end;
//------------------------------------------------------------------------------
Function TILAttributeComparator.GetIsSimple: Boolean;
begin
Result := fName.IsSimple and fValue.IsSimple;
end;
//==============================================================================
constructor TILAttributeComparator.Create;
begin
inherited Create;
fName := TILTextComparatorGroup.Create;
fName.StringPrefix := 'Name: ';
fValue := TILTextComparatorGroup.Create;
fValue.StringPrefix := 'Value: ';
end;
//------------------------------------------------------------------------------
constructor TILAttributeComparator.CreateAsCopy(Source: TILAttributeComparator; UniqueCopy: Boolean);
begin
inherited CreateAsCopy(Source,UniqueCopy);
fName := TILTextComparatorGroup.CreateAsCopy(Source.Name,UniqueCopy);
fName.StringPrefix := 'Name: ';
fValue := TILTextComparatorGroup.CreateAsCopy(Source.Value,UniqueCopy);
fValue.StringPrefix := 'Value: ';
end;
//------------------------------------------------------------------------------
destructor TILAttributeComparator.Destroy;
begin
fValue.Free;
fName.Free;
inherited;
end;
//------------------------------------------------------------------------------
Function TILAttributeComparator.AsString(Decorate: Boolean = True): String;
begin
If GetIsSimple then
begin
// exactly one string comparator in both name and value
Result := IL_Format('%s="%s"',[fName.AsString(False),fValue.AsString(False)]);
end
else
begin
If (fName.Count > 0) and (fValue.Count > 0) then
Result := 'attribute name="value"'
else If fName.Count > 0 then
Result := 'attribute name'
else If fValue.Count > 0 then
Result := 'attribute *="value"'
else
Result := 'attribute';
end;
If fNegate then
Result := IL_Format('not(%s)',[Result]);
If Decorate then
begin
If fIndex > 0 then
Result := IL_Format('%s%s %s%s',[fStringPrefix,IL_SearchOperatorAsStr(fOperator),Result,fStringSuffix])
else
Result := IL_Format('%s%s%s',[fStringPrefix,Result,fStringSuffix]);
end
else
begin
If fIndex > 0 then
Result := IL_Format('%s %s',[IL_SearchOperatorAsStr(fOperator),Result])
end;
end;
//------------------------------------------------------------------------------
Function TILAttributeComparator.Search(const SearchSettings: TILAdvSearchSettings): Boolean;
begin
Result := fName.Search(SearchSettings) or fValue.Search(SearchSettings);
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparator.Prepare(Variables: TILItemShopParsingVariables);
begin
inherited Prepare(Variables);
fName.Prepare(Variables);
fValue.Prepare(Variables);
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparator.ReInit;
begin
inherited;
fName.ReInit;
fValue.ReInit;
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparator.Compare(TagAttribute: TILHTMLTagAttribute);
begin
// compare
fName.Compare(TagAttribute.Name);
fValue.Compare(TagAttribute.Value);
// combine results
If (fName.Count > 0) and (fValue.Count > 0) then
fResult := IL_NegateValue(fName.Result,fName.Negate) and
IL_NegateValue(fValue.Result,fValue.Negate)
else If fName.Count > 0 then
fResult := IL_NegateValue(fName.Result,fName.Negate)
else If fValue.Count > 0 then
fResult := IL_NegateValue(fValue.Result,fValue.Negate)
else
fResult := False;
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparator.SaveToStream(Stream: TStream);
begin
Stream_WriteUInt32(Stream,IL_SEARCH_ATTRCOMPARATOR);
inherited SaveToStream(Stream);
fName.SaveToStream(Stream);
fValue.SaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparator.LoadFromStream(Stream: TStream);
begin
If Stream_ReadUInt32(Stream) <> IL_SEARCH_ATTRCOMPARATOR then
raise Exception.Create('TILAttributeComparator.LoadFromStream: Invalid stream format.');
inherited LoadFromStream(Stream);
fName.LoadFromStream(Stream);
fValue.LoadFromStream(Stream);
end;
//******************************************************************************
//******************************************************************************
Function TILAttributeComparatorGroup.GetItemCount: Integer;
begin
Result := Length(fItems);
end;
//------------------------------------------------------------------------------
Function TILAttributeComparatorGroup.GetItem(Index: Integer): TILAttributeComparatorBase;
begin
If (Index >= Low(fItems)) and (Index <= High(fItems)) then
Result := fItems[Index]
else
raise Exception.CreateFmt('TILAttributeComparator.GetItem: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TILAttributeComparatorGroup.GetTotalItemCount: Integer;
var
i: Integer;
begin
Result := inherited GetTotalItemCount;
For i := Low(fItems) to High(fItems) do
Inc(Result,fItems[i].TotalItemCount);
end;
//------------------------------------------------------------------------------
Function TILAttributeComparatorGroup.GetIsSimple: Boolean;
begin
If Length(fItems) = 1 then
begin
{
there is one subnode, which is of type TILAttributeComparator
this subnode has exactly one name and one value subnode, both of type
TILTextComparator
}
If fItems[Low(fItems)] is TILAttributeComparator then
Result := fItems[Low(fItems)].IsSimple
else
Result := False;
end
else Result := False;
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparatorGroup.ReIndex;
var
i: Integer;
begin
For i := Low(fItems) to High(fItems) do
fItems[i].Index := i;
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparatorGroup.MarkLeading;
var
i: Integer;
begin
For i := Low(fItems) to High(fItems) do
fItems[i].IsLeading := i <= Low(fItems);
end;
//==============================================================================
constructor TILAttributeComparatorGroup.Create;
begin
inherited Create;
SetLength(fItems,0);
end;
//------------------------------------------------------------------------------
constructor TILAttributeComparatorGroup.CreateAsCopy(Source: TILAttributeComparatorGroup; UniqueCopy: Boolean);
var
i: Integer;
begin
inherited CreateAsCopy(Source,UniqueCopy);
SetLength(fItems,Source.Count);
For i := Low(fItems) to High(fItems) do
If Source.Items[i] is TILAttributeComparatorGroup then
fItems[i] := TILAttributeComparatorGroup.CreateAsCopy(TILAttributeComparatorGroup(Source.Items[i]),UniqueCopy)
else
fItems[i] := TILAttributeComparator.CreateAsCopy(TILAttributeComparator(Source.Items[i]),UniqueCopy);
MarkLeading;
end;
//------------------------------------------------------------------------------
destructor TILAttributeComparatorGroup.Destroy;
begin
Clear;
inherited;
end;
//------------------------------------------------------------------------------
Function TILAttributeComparatorGroup.AsString(Decorate: Boolean = True): String;
begin
If GetIsSimple then
begin
Result := fItems[Low(fItems)].AsString(False);
If (Length(Result) <= 0) and not fEmptyStrAllow then
Result := '(...)';
end
else
begin
If Length(fItems) > 1 then
Result := IL_Format('(...x%d)',[Length(fItems)])
else If Length(fItems) = 1 then
Result := '(...)'
else If not fEmptyStrAllow then
Result := '()'
else
Result := '';
end;
If fNegate then
Result := IL_Format('not%s',[Result]);
If Decorate then
begin
If fIndex > 0 then
Result := IL_Format('%s%s %s%s',[fStringPrefix,IL_SearchOperatorAsStr(fOperator),Result,fStringSuffix])
else
Result := IL_Format('%s%s%s',[fStringPrefix,Result,fStringSuffix]);
end
else
begin
If fIndex > 0 then
Result := IL_Format('%s %s',[IL_SearchOperatorAsStr(fOperator),Result])
end;
end;
//------------------------------------------------------------------------------
Function TILAttributeComparatorGroup.Search(const SearchSettings: TILAdvSearchSettings): Boolean;
var
i: Integer;
begin
Result := False;
For i := Low(fItems) to High(fItems) do
If fItems[i].Search(SearchSettings) then
begin
Result := True;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparatorGroup.Prepare(Variables: TILItemShopParsingVariables);
var
i: Integer;
begin
inherited Prepare(Variables);
For i := Low(fItems) to High(fItems) do
fItems[i].Prepare(Variables);
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparatorGroup.ReInit;
var
i: Integer;
begin
inherited;
For i := Low(fItems) to High(fItems) do
fItems[i].ReInit;
end;
//------------------------------------------------------------------------------
Function TILAttributeComparatorGroup.IndexOf(Item: TObject): Integer;
var
i: Integer;
begin
Result := -1;
For i := Low(fItems) to High(fItems) do
If fItems[i] = Item then
begin
Result := i;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
Function TILAttributeComparatorGroup.AddComparator(Negate: Boolean = False; Operator: TILSearchOperator = ilsoAND): TILAttributeComparator;
begin
SetLength(fItems,Length(fItems) + 1);
Result := TILAttributeComparator.Create;
fItems[High(fItems)] := Result;
Result.Index := High(fItems);
Result.EmptyStringAllowed := False;
Result.Negate := Negate;
Result.Operator := Operator;
MarkLeading;
end;
//------------------------------------------------------------------------------
Function TILAttributeComparatorGroup.AddGroup(Negate: Boolean = False; Operator: TILSearchOperator = ilsoAND): TILAttributeComparatorGroup;
begin
SetLength(fItems,Length(fItems) + 1);
Result := TILAttributeComparatorGroup.Create;
fItems[High(fItems)] := Result;
Result.Index := High(fItems);
Result.Negate := Negate;
Result.Operator := Operator;
MarkLeading;
end;
//------------------------------------------------------------------------------
Function TILAttributeComparatorGroup.Remove(Item: TObject): Integer;
begin
Result := IndexOf(Item);
If Result >= 0 then
Delete(Result);
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparatorGroup.Delete(Index: Integer);
var
i: Integer;
begin
If (Index >= Low(fItems)) and (Index <= High(fItems)) then
begin
fItems[Index].Free;
For i := Index to Pred(High(fItems)) do
fItems[i] := fItems[i + 1];
SetLength(fItems,Length(fItems) - 1);
ReIndex;
MarkLeading;
end
else raise Exception.CreateFmt('TILAttributeComparatorGroup.Delete: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparatorGroup.Clear;
var
i: Integer;
begin
For i := Low(fItems) to High(fItems) do
fItems[i].Free;
SetLength(fItems,0);
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparatorGroup.Compare(TagAttribute: TILHTMLTagAttribute);
var
i: Integer;
begin
// compare
For i := Low(fItems) to High(fItems) do
If not fItems[i].Result then
fItems[i].Compare(TagAttribute);
// combine results
If Length(fItems) > 0 then
begin
fResult := IL_NegateValue(fItems[Low(fItems)].Result,fItems[Low(fItems)].Negate);
For i := Succ(Low(fItems)) to High(fItems) do
fResult := IL_CombineUsingOperator(
fResult,IL_NegateValue(fItems[i].Result,fItems[i].Negate),fItems[i].Operator);
end
else fResult := False;
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparatorGroup.SaveToStream(Stream: TStream);
var
i: Integer;
begin
Stream_WriteUInt32(Stream,IL_SEARCH_ATTRCOMPARATORGROUP);
inherited SaveToStream(Stream);
Stream_WriteUInt32(Stream,Length(fItems));
For i := Low(fItems) to High(fItems) do
fItems[i].SaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILAttributeComparatorGroup.LoadFromStream(Stream: TStream);
var
i: Integer;
begin
Clear;
If Stream_ReadUInt32(Stream) <> IL_SEARCH_ATTRCOMPARATORGROUP then
raise Exception.Create('TILAttributeComparatorGroup.LoadFromStream: Invalid stream format.');
inherited LoadFromStream(Stream);
SetLength(fItems,Stream_ReadUInt32(Stream));
For i := Low(fItems) to High(fItems) do
begin
case Stream_ReadUInt32(Stream,False) of
IL_SEARCH_ATTRCOMPARATOR: fItems[i] := TILAttributeComparator.Create;
IL_SEARCH_ATTRCOMPARATORGROUP: fItems[i] := TILAttributeComparatorGroup.Create;
else
raise Exception.Create('TILAttributeComparatorGroup.LoadFromStream: Invalid subitem.');
end;
fItems[i].LoadFromStream(Stream);
fItems[i].Index := i;
If fItems[i] is TILAttributeComparatorGroup then
fItems[i].EmptyStringAllowed := False;
fItems[i].IsLeading := i <= Low(fItems);
end;
end;
//******************************************************************************
//******************************************************************************
Function TILElementComparator.GetTotalItemCount: Integer;
begin
Result := inherited GetTotalItemCount;
Inc(Result,fTagName.TotalItemCount);
Inc(Result,fAttributes.TotalItemCount);
Inc(Result,fText.TotalItemCount);
end;
//------------------------------------------------------------------------------
Function TILElementComparator.GetIsSimple: Boolean;
begin
Result := fTagName.IsSimple and (fAttributes.IsSimple or (fAttributes.Count <= 0)) and
(fText.IsSimple or (fText.Count <= 0));
end;
//==============================================================================
constructor TILElementComparator.Create;
begin
inherited Create;
fTagName := TILTextComparatorGroup.Create;
fTagName.StringPrefix := 'Tag name: ';
fAttributes := TILAttributeComparatorGroup.Create;
fAttributes.StringPrefix := 'Attributes: ';
fText := TILTextComparatorGroup.Create;
fText.StringPrefix := 'Text: ';
fNestedText := False;
end;
//------------------------------------------------------------------------------
constructor TILElementComparator.CreateAsCopy(Source: TILElementComparator; UniqueCopy: Boolean);
begin
inherited CreateAsCopy(Source,UniqueCopy);
fTagName := TILTextComparatorGroup.CreateAsCopy(Source.TagName,UniqueCopy);
fTagName.StringPrefix := 'Tag name: ';
fAttributes := TILAttributeComparatorGroup.CreateAsCopy(Source.Attributes,UniqueCopy);
fAttributes.StringPrefix := 'Attributes: ';
fText := TILTextComparatorGroup.CreateAsCopy(Source.Text,UniqueCopy);
fText.StringPrefix := 'Text: ';
fNestedText := Source.NestedText;
fResult := Source.Result;
end;
//------------------------------------------------------------------------------
destructor TILElementComparator.Destroy;
begin
fText.Free;
fAttributes.Free;
fTagName.Free;
inherited;
end;
//------------------------------------------------------------------------------
Function TILElementComparator.AsString(Decorate: Boolean = True): String;
begin
If GetIsSimple then
begin
If fAttributes.Count > 0 then
Result := IL_Format('<%s %s>%s',[fTagName.AsString(False),
fAttributes.AsString(False),fText.AsString(False)])
else
Result := IL_Format('<%s>%s',[fTagName.AsString(False),
fText.AsString(False)]);
end
else
begin
If fIndex >= 0 then
Result := IL_Format('<element #%d>',[fIndex])
else
Result := '<element>';
end;
If fIndex > 0 then
Result := IL_Format('or %s',[Result]);
If fNestedText then
Result := IL_Format('%s<<>>',[Result]);
end;
//------------------------------------------------------------------------------
Function TILElementComparator.Search(const SearchSettings: TILAdvSearchSettings): Boolean;
begin
Result := fTagName.Search(SearchSettings) or fAttributes.Search(SearchSettings) or fText.Search(SearchSettings);
end;
//------------------------------------------------------------------------------
procedure TILElementComparator.Prepare(Variables: TILItemShopParsingVariables);
begin
inherited Prepare(Variables);
fTagName.Prepare(Variables);
fAttributes.Prepare(Variables);
fText.Prepare(Variables);
end;
//------------------------------------------------------------------------------
procedure TILElementComparator.ReInit;
begin
inherited;
fTagName.ReInit;
fAttributes.ReInit;
fText.ReInit;
end;
//------------------------------------------------------------------------------
procedure TILElementComparator.Compare(Element: TILHTMLElementNode);
var
i: Integer;
begin
fTagName.Compare(Element.Name);
fResult := IL_NegateValue(fTagName.Result,fTagName.Negate);
If fResult then
begin
// name match, look for attributes match...
If fAttributes.Count > 0 then
begin
For i := 0 to Pred(Element.AttributeCount) do
begin
fAttributes.Compare(Element.Attributes[i]);
If fAttributes.Result then
Break{For i}; // no need to continue when match was found
end;
// get result and combine it with name
fResult := fResult and IL_NegateValue(fAttributes.Result,fAttributes.Negate);
end;
// and now for the text...
If (fText.Count > 0) and fResult then
begin
If fNestedText then
fText.Compare(Element.NestedText)
else
fText.Compare(Element.Text);
fResult := fResult and IL_NegateValue(fText.Result,fText.Negate);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TILElementComparator.SaveToStream(Stream: TStream);
begin
Stream_WriteUInt32(Stream,IL_SEARCH_ELEMENTCOMPARATOR);
fTagName.SaveToStream(Stream);
fAttributes.SaveToStream(Stream);
fText.SaveToStream(Stream);
Stream_WriteBool(Stream,fNestedText);
end;
//------------------------------------------------------------------------------
procedure TILElementComparator.LoadFromStream(Stream: TStream);
begin
If Stream_ReadUInt32(Stream) <> IL_SEARCH_ELEMENTCOMPARATOR then
raise Exception.Create('TILElementComparator.LoadFromStream: Invalid stream format.');
fTagName.LoadFromStream(Stream);
fAttributes.LoadFromStream(Stream);
fText.LoadFromStream(Stream);
fNestedText := Stream_ReadBool(Stream);
end;
//******************************************************************************
//******************************************************************************
Function TILElementFinderStage.GetItemCount: Integer;
begin
Result := Length(fItems);
end;
//------------------------------------------------------------------------------
Function TILElementFinderStage.GetItem(Index: Integer): TILElementComparator;
begin
If (Index >= Low(fItems)) and (Index <= High(fItems)) then
Result := fItems[Index]
else
raise Exception.CreateFmt('TILElementFinderStage.GetItem: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TILElementFinderStage.GetTotalItemCount: Integer;
var
i: Integer;
begin
Result := inherited GetTotalItemCount;
For i := Low(fItems) to High(fItems) do
Inc(Result,fItems[i].TotalItemCount);
end;
//------------------------------------------------------------------------------
procedure TILElementFinderStage.ReIndex;
var
i: Integer;
begin
For i := Low(fItems) to High(fItems) do
fItems[i].Index := i;
end;
//==============================================================================
constructor TILElementFinderStage.Create;
begin
inherited Create;
SetLength(fItems,0);
end;
//------------------------------------------------------------------------------
constructor TILElementFinderStage.CreateAsCopy(Source: TILElementFinderStage; UniqueCopy: Boolean);
var
i: Integer;
begin
inherited CreateAsCopy(Source,UniqueCopy);
SetLength(fItems,Source.Count);
For i := Low(fItems) to High(fItems) do
fItems[i] := TILElementComparator.CreateAsCopy(Source.Items[i],UniqueCopy);
end;
//------------------------------------------------------------------------------
destructor TILElementFinderStage.Destroy;
begin
Clear;
inherited;
end;
//------------------------------------------------------------------------------
Function TILElementFinderStage.AsString(Decorate: Boolean = True): String;
begin
If Length(fItems) = 1 then
Result := IL_Format('Stage #%d (1 element option)',[Index])
else If Length(fItems) > 1 then
Result := IL_Format('Stage #%d (%d element options)',[Index,Length(fItems)])
else
Result := IL_Format('Stage #%d',[Index]);
// both index and operator are ignored
end;
//------------------------------------------------------------------------------
Function TILElementFinderStage.Search(const SearchSettings: TILAdvSearchSettings): Boolean;
var
i: Integer;
begin
Result := False;
For i := Low(fItems) to High(fItems) do
If fItems[i].Search(SearchSettings) then
begin
Result := True;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
procedure TILElementFinderStage.Prepare(Variables: TILItemShopParsingVariables);
var
i: Integer;
begin
inherited Prepare(Variables);
For i := Low(fItems) to High(fItems) do
fItems[i].Prepare(Variables);
end;
//------------------------------------------------------------------------------
procedure TILElementFinderStage.ReInit;
var
i: Integer;
begin
For i := Low(fItems) to High(fItems) do
fItems[i].ReInit;
end;
//------------------------------------------------------------------------------
Function TILElementFinderStage.IndexOf(Item: TObject): Integer;
var
i: Integer;
begin
Result := -1;
For i := Low(fItems) to High(fItems) do
If fItems[i] = Item then
begin
Result := i;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
Function TILElementFinderStage.AddComparator: TILElementComparator;
begin
SetLength(fItems,Length(fItems) + 1);
Result := TILElementComparator.Create;
fItems[High(fItems)] := Result;
Result.Index := High(fITems);
end;
//------------------------------------------------------------------------------
Function TILElementFinderStage.Remove(Item: TObject): Integer;
begin
Result := IndexOf(Item);
If Result >= 0 then
Delete(Result);
end;
//------------------------------------------------------------------------------
procedure TILElementFinderStage.Delete(Index: Integer);
var
i: Integer;
begin
If (Index >= Low(fItems)) and (Index <= High(fItems)) then
begin
fItems[Index].Free;
For i := Index to Pred(High(fItems)) do
fItems[i] := fItems[i + 1];
SetLength(fItems,Length(fItems) - 1);
ReIndex;
end
else raise Exception.CreateFmt('TILElementFinderStage.Delete: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TILElementFinderStage.Clear;
var
i: Integer;
begin
For i := Low(fItems) to High(fItems) do
fItems[i].Free;
SetLength(fItems,0);
end;
//------------------------------------------------------------------------------
Function TILElementFinderStage.Compare(Element: TILHTMLElementNode): Boolean;
var
i: Integer;
begin
If Length(fItems) > 0 then
begin
// compare
For i := Low(fItems) to High(fItems) do
fItems[i].Compare(Element);
// get result
Result := fItems[Low(fItems)].Result;
For i := Succ(Low(fItems)) to High(fItems) do
Result := Result or fItems[i].Result;
end
else Result := False;
end;
//------------------------------------------------------------------------------
procedure TILElementFinderStage.SaveToStream(Stream: TStream);
var
i: Integer;
begin
Stream_WriteUInt32(Stream,IL_SEARCH_ELEMENTCOMPARATORGROUP);
Stream_WriteUInt32(Stream,Length(fItems));
For i := Low(fItems) to High(fItems) do
fItems[i].SaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILElementFinderStage.LoadFromStream(Stream: TStream);
var
i: Integer;
begin
Clear;
If Stream_ReadUInt32(Stream) <> IL_SEARCH_ELEMENTCOMPARATORGROUP then
raise Exception.Create('TILElementFinderStage.LoadFromStream: Invalid stream format.');
SetLength(fItems,Stream_ReadUInt32(Stream));
For i := Low(fItems) to High(fItems) do
begin
fItems[i] := TILElementComparator.Create;
fItems[i].LoadFromStream(Stream);
fItems[i].Index := i;
end;
end;
//******************************************************************************
//******************************************************************************
Function TILElementFinder.GetStageCount: Integer;
begin
Result := Length(fStages);
end;
//------------------------------------------------------------------------------
Function TILElementFinder.GetStage(Index: Integer): TILElementFinderStage;
begin
If (Index >= Low(fStages)) and (Index <= High(fStages)) then
Result := fStages[Index]
else
raise Exception.CreateFmt('TILElementFinder.GetStage: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TILElementFinder.GetTotalItemCount: Integer;
var
i: Integer;
begin
Result := inherited GetTotalItemCount;
For i := Low(fStages) to High(fStages) do
Inc(Result,fStages[i].TotalItemCount);
end;
//------------------------------------------------------------------------------
procedure TILElementFinder.ReIndex;
var
i: Integer;
begin
For i := Low(fStages) to High(fStages) do
fStages[i].Index := i;
end;
//==============================================================================
constructor TILElementFinder.Create;
begin
inherited Create;
SetLength(fStages,0);
end;
//------------------------------------------------------------------------------
constructor TILElementFinder.CreateAsCopy(Source: TILElementFinder; UniqueCopy: Boolean);
var
i: Integer;
begin
inherited CreateAsCopy(Source,UniqueCopy);
SetLength(fStages,Source.StageCount);
For i := Low(fStages) to High(fStages) do
fStages[i] := TILElementFinderStage.CreateAsCopy(Source.Stages[i],UniqueCopy);
end;
//------------------------------------------------------------------------------
destructor TILElementFinder.Destroy;
begin
StageClear;
inherited;
end;
//------------------------------------------------------------------------------
Function TILElementFinder.Search(const SearchSettings: TILAdvSearchSettings): Boolean;
var
i: Integer;
begin
Result := False;
For i := Low(fStages) to High(fStages) do
If fStages[i].Search(SearchSettings) then
begin
Result := True;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
procedure TILElementFinder.Prepare(Variables: TILItemShopParsingVariables);
var
i: Integer;
begin
inherited Prepare(Variables);
For i := Low(fStages) to High(fStages) do
fStages[i].Prepare(Variables);
end;
//------------------------------------------------------------------------------
procedure TILElementFinder.ReInit;
var
i: Integer;
begin
For i := Low(fStages) to High(fStages) do
fStages[i].ReInit;
end;
//------------------------------------------------------------------------------
Function TILElementFinder.StageIndexOf(Stage: TObject): Integer;
var
i: Integer;
begin
Result := -1;
For i := Low(fStages) to High(fStages) do
If fStages[i] = Stage then
begin
Result := i;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
Function TILElementFinder.StageAdd: TILElementFinderStage;
begin
SetLength(fStages,Length(fStages) + 1);
Result := TILElementFinderStage.Create;
fStages[High(fStages)] := Result;
Result.Index := High(fStages);
end;
//------------------------------------------------------------------------------
Function TILElementFinder.StageRemove(Stage: TObject): Integer;
begin
Result := StageIndexOf(Stage);
If Result >= 0 then
StageDelete(Result);
end;
//------------------------------------------------------------------------------
procedure TILElementFinder.StageDelete(Index: Integer);
var
i: Integer;
begin
If (Index >= Low(fStages)) and (Index <= High(fStages)) then
begin
fStages[Index].Free;
For i := Index to Pred(High(fStages)) do
fStages[i] := fStages[i + 1];
SetLength(fStages,Length(fStages) - 1);
ReIndex;
end
else raise Exception.CreateFmt('TILElementFinder.StageDelete: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TILElementFinder.StageClear;
var
i: Integer;
begin
For i := Low(fStages) to High(fStages) do
fStages[i].Free;
SetLength(fStages,0);
end;
//------------------------------------------------------------------------------
Function TILElementFinder.FindElements(Document: TILHTMLDocument; out Elements: TILHTMLElements): Boolean;
var
FoundNodesL1: TObjectCountedDynArray;
FoundNodesL2: TObjectCountedDynArray;
i,j: Integer;
begin
SetLength(Elements,0);
CDA_Init(FoundNodesL1);
CDA_Init(FoundNodesL2);
CDA_Add(FoundNodesL1,Document);
// traverse stages
For i := Low(fStages) to High(fStages) do
begin
CDA_Clear(FoundNodesL2);
For j := CDA_Low(FoundNodesL1) to CDA_High(FoundNodesL1) do
TILHTMLElementNode(CDA_GetItem(FoundNodesL1,j)).
Find(fStages[i],(i = Low(fStages)),FoundNodesL2);
CDA_Clear(FoundNodesL1);
FoundNodesL1 := CDA_Copy(FoundNodesL2);
end;
If (CDA_Count(FoundNodesL1) >= 1) and (Length(fStages) > 0) then
begin
SetLength(Elements,CDA_Count(FoundNodesL1));
For i := Low(Elements) to High(Elements) do
Elements[i] := TILHTMLElementNode(CDA_GetItem(FoundNodesL1,i));
end;
Result := Length(Elements) > 0;
end;
//------------------------------------------------------------------------------
procedure TILElementFinder.SaveToStream(Stream: TStream);
var
i: Integer;
begin
Stream_WriteUInt32(Stream,Length(fStages));
For i := Low(fStages) to High(fStages) do
fStages[i].SaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILElementFinder.LoadFromStream(Stream: TStream);
var
i: Integer;
begin
StageClear;
SetLength(fStages,Stream_ReadUInt32(Stream));
For i := Low(fStages) to High(fStages) do
begin
fStages[i] := TILElementFinderStage.Create;
fStages[i].LoadFromStream(Stream);
fStages[i].Index := i;
end;
end;
end.
|
{ THREAD COMPONENT
Auteur : Bacterius
Ce composant permet d'introduire facilement un thread dans votre application.
Une notion interessante et utile qui est mise en application dans ce composant
est la "monodépendance". Je m'explique : ici, le composant encapsulant le thread
a bien sûr accès au thread. Mais la réciproque n'est pas vraie ! Le thread n'a pas
accès au composant qui l'encapsule. C'est pourquoi l'on est obligé de stocker
quelques variables dans le thread lui-même, ainsi que dans le composant (pour
pouvoir gérer les propriétés du composant, ET pour pouvoir laisser au thread l'accès
à des informations indispensables à son fonctionnement correct, tels l'intervalle
ou encore la priorité demandée par l'utilisateur du composant).
Remarque : Le paramètre Sender des différents évènements de ce composant n'est
pas le même selon les évènements. Voici un tableau de correspondance :
_______________________________________________________
| Evènement | Paramètre Sender |
| ________________________|_____________________________|
| OnExecute | TThread |
| OnResume | TThreadComponent |
| OnSuspend | TThreadComponent |
|_________________________|_____________________________|
La raison de cette différence dans OnExecute est que le gestionnaire OnExecute
est appelé par le thread et non par le composant encapsulant le thread (contrairement
aux deux autres évènements OnResume et OnSuspend).
De plus, un type TThreadComponentList est fourni pour gérer une liste de threads,
à laquelle vous pouvez bien sûr ajouter, retirer et gérer des threads.
Notez que le fait de retirer un thread par les méthodes Delete ou Clear ou Free
a pour effet de terminer ce thread afin de ne pas le laisser hors de contrôle.
Pour ne pas terminer le thread (le garder en fonctionnement tout en le retirant
de la liste), utilisez la méthode Extract.
}
unit ThreadComponent;
interface
uses
Windows,
Classes,
Forms;
type
TRuntimeCheck=function: Boolean of Object; // Fonction pour savoir depuis le thread
// si le composant est en runtime.
TMyThread = class(TThread) // Classe thread basique
private
FInterval: Cardinal; // Intervalle dans le thread
FOnExecute: TNotifyEvent; // Gestionnaire OnExecute dans le thread
FRuntimeCheck: TRuntimeCheck; // Fonction de liaison à IsRuntime dans le composant
procedure CentralControl; // Méthode principale du thread
protected
procedure Execute; override; // Boucle principale du thread
end;
TThreadComponent = class(TComponent) // Le composant encapsulant le thread
private
FThread: TMyThread; // Le thread à encapsuler
FInterval: Cardinal; // L'intervalle
FActive: Boolean; // L'état (actif/inactif)
FPriority: TThreadPriority; // La priorité du thread
FOnSuspend: TNotifyEvent; // Le gestionnaire OnSuspend
FOnResume: TNotifyEvent; // Le gestionnaire OnResume
FOnExecute: TNotifyEvent; // Le gestionnaire OnExecute
procedure SetInterval(Value: Cardinal); // Setter pour la propriété Interval
procedure SetPriority(Value: TThreadPriority); // Setter pour la propriété Priority
procedure SetActive(Value: Boolean); // Setter pour la propriété Active
procedure SetOnExecute(Value: TNotifyEvent); // Setter pour le gestionnaire OnExecute
function GetThreadHandle: Cardinal; // Getter pour le handle du thread
function GetThreadID: Cardinal; // Getter pour l'identificateur du thread
function IsRuntime: Boolean; // Fonction pour savoir si le composant est en runtime
public
constructor Create(AOwner: TComponent); override; // Constructeur surchargé
destructor Destroy; override; // Destructeur surchargé
published
property Interval: Cardinal read FInterval write SetInterval; // Propriété Interval
property Priority: TThreadPriority read FPriority write SetPriority; // Propriété Priority
property Active: Boolean read FActive write SetActive; // Propriété Active
property ThreadHandle: Cardinal read GetThreadHandle; // Propriété ThreadHandle
property ThreadID: Cardinal read GetThreadID; // Propriété ThreadID
property OnSuspend: TNotifyEvent read FOnSuspend write FOnSuspend; // Gestionnaire OnSuspend
property OnResume: TNotifyEvent read FOnResume write FOnResume; // Gestionnaire OnResume
property OnExecute: TNotifyEvent read FOnExecute write SetOnExecute; // Gestionnaire OnExecute
end;
PThreadComponent = ^TThreadComponent; // Pointeur sur le type TThreadComponent
procedure Register; // Procédure de recensement du composant
{-------------------------------------------------------------------------------
------------------------------- TTHREADLISTEX ----------------------------------
-------------------------------------------------------------------------------}
type TThreadListEx = class // Classe TThreadListEx
private
FList: TList; // La liste de pointeurs privée
function GetCount: Cardinal; // Getter Count
function GetCapacity: Cardinal; // Getter Capacity
procedure SetCapacity(Value: Cardinal); // Setter Capacity
function GetThread(Index: Integer): TThreadComponent; // Getter Threads
public
constructor Create; reintroduce; // Constructeur réintroduit pour la classe
destructor Destroy; override; // Destructeur surchargé
function AddNew: TThreadComponent; // Ajoute un nouveau thread
procedure Add(var Thread: TThreadComponent); // Ajoute un thread déjà créé
procedure Insert(At: Integer; var Thread: TThreadComponent); // Insère un thread dans la liste
function Extract(At: Integer): TThreadComponent; // Supprime un thread sans le terminer
procedure Delete(At: Integer); // Supprime un thread de la liste
procedure SetNil(At: Integer); // "Gomme" un thread sans le supprimer de la liste
procedure Exchange(Src, Dest: Integer); // On échange 2 threads de place dans la liste
procedure Pack; // Compression et nettoyage de la liste
procedure Clear; // Elimine tous les threads de la liste
property Count: Cardinal read GetCount; // Propriété Count (nombre de threads dans la liste)
property Capacity: Cardinal read GetCapacity write SetCapacity; // Propriété Capacity
property Threads[Index: Integer]: TThreadComponent read GetThread; // Propriété tableau Threads
end;
implementation
procedure Register; // Procédure de recensement du composant
begin
RegisterComponents('Système', [TThreadComponent]);
// Recensement de TThreadComponent dans la page Système.
end;
procedure TMyThread.CentralControl; // Méthode principale
begin
if (FRuntimeCheck) and Assigned(FOnExecute) then FOnExecute(self);
// Si on est en runtime et que le gestionnaire OnExecute est assigné, on execute ce dernier
end;
procedure TMyThread.Execute; // Boucle du thread
begin
repeat // On répète l'execution du thread ...
Sleep(FInterval); // On attend l'intervalle demandé
Application.ProcessMessages; // On laisse l'application traiter ses messages
Synchronize(CentralControl); // On synchronise avec la méthode principale
until Terminated; // ... jusqu'à ce que le thread soit terminé
end;
function TThreadComponent.IsRuntime: Boolean; // Vérifie si le composant est un runtime
begin
Result := not (csDesigning in ComponentState);
// csDesigning indique que l'on est en mode conception
end;
procedure TThreadComponent.SetOnExecute(Value: TNotifyEvent); // On définit le gestionnaire OnExecute
begin
if @Value <> @FOnExecute then // Si on a changé de gestionnaire ...
begin
FOnExecute := Value; // On change le gestionnaire
FThread.FOnExecute := Value; // On le change aussi dans le thread
end;
end;
procedure TThreadComponent.SetInterval(Value: Cardinal); // On définit l'intervalle du thread
begin
if Value <> FInterval then // Si l'intervalle a changé
begin
FInterval := Value; // On change la propriété
FThread.FInterval := Value; // Et on change aussi la variable dans le thread
end;
end;
procedure TThreadComponent.SetPriority(Value: TThreadPriority); // On définit la priorité du thread
begin
if Value <> FPriority then // Si la priorité a changé
begin
FPriority := Value; // On change la propriété
FThread.Priority := Value; // Et on change réellement la priorité du thread
end;
end;
procedure TThreadComponent.SetActive(Value: Boolean); // On définit l'état du thread
begin
if Value <> FActive then // Si on change d'état
begin
FActive := Value; // On change la propriété
case FActive of // Selon le nouvel état ...
False: // Désactivé
begin
FThread.Suspend; // On arrête le thread
if (IsRuntime) and (Assigned(FOnSuspend)) then FOnSuspend(self);
// Si on a défini un gestionnaire OnSuspend et que l'on est en runtime, on lance ce gestionnaire
end;
True: // Activé
begin
FThread.Resume; // On reprend l'execution du thread
if (IsRuntime) and (Assigned(FOnResume)) then FOnResume(self);
// Si on a défini un gestionnaire OnResume et que l'on est en runtime, on lance ce gestionnaire
end;
end;
end;
end;
function TThreadComponent.GetThreadHandle: Cardinal; // On récupère le handle du thread
begin
Result := FThread.Handle; // Ce handle peut être utilisé dans des APIs concernant les threads
end;
function TThreadComponent.GetThreadID: Cardinal; // On récupère l'identificateur du thread
begin
Result := FThread.ThreadID; // Peut être utilisé également dans certaines APIs
end;
constructor TThreadComponent.Create(AOwner: TComponent); // Création du composant
begin
inherited Create(AOwner); // On laisse Delphi faire le sale boulot à notre place ...
FThread := TMyThread.Create(True); // On crée le thread arrêté
FThread.FRuntimeCheck := IsRuntime; // On établit une liaison entre la fonction de
// vérification du runtime dans le composant avec une fonction similaire du thread.
// En effet, on ne peut pas savoir à partir du thread si notre composant est en runtime.
FThread.FInterval := 1000; // On définit l'intervalle à 1 seconde dans le thread
FActive := False; // On met la propriété Active à False
FInterval := 1000; // On définit l'intervalle à 1 seconde dans le composant
FPriority := tpNormal; // On définit une priorité normale
FThread.Priority := tpNormal; // On fait de même, mais dans le thread
end;
destructor TThreadComponent.Destroy; // Destruction du composant
begin
FThread.Terminate; // On demande l'arrêt du thread
while not FThread.Terminated do ; // Tant que le thread n'est pas terminé, on attend ...
inherited Destroy; // Puis on laisse Delphi finir la destruction du composant.
end;
{-------------------------------------------------------------------------------
------------------------------- TTHREADLISTEX ----------------------------------
-------------------------------------------------------------------------------}
constructor TThreadListEx.Create; // Création de la classe
begin
inherited Create; // Création inhéritée de la classe
FList := TList.Create; // Création de la liste de pointeurs
end;
destructor TThreadListEx.Destroy; // Destruction de la classe
Var
I: Integer; // Variable de contrôle de boucle
begin
for I := 0 to FList.Count - 1 do // Pour chaque thread dans la liste
TThreadComponent(FList.Items[I]^).Free; // On libère chacun des threads
FList.Free; // Finalement, on libère la liste de pointeurs
inherited Destroy; // Puis on détruit la classe
end;
function TThreadListEx.GetCount: Cardinal; // Récupère le nombre d'éléments dans la liste
begin
Result := FList.Count; // Récupère directement le résultat dans la liste de pointeurs
end;
function TThreadListEx.GetCapacity: Cardinal; // Getter Capacity
begin
Result := FList.Capacity; // Récupère directement le résultat dans la liste de pointeurs
end;
procedure TThreadListEx.SetCapacity(Value: Cardinal); // Setter Capacity
begin
FList.Capacity := Value; // Attention aux erreurs d'allocation mémoire EOutOfMemory !
end;
function TThreadListEx.GetThread(Index: Integer): TThreadComponent; // Getter Threads
begin
Result := TThreadComponent(FList.Items[Index]^); // On le récupère de la liste
end;
function TThreadListEx.AddNew: TThreadComponent; // Ajoute un nouveau thread
begin
Result := TThreadComponent.Create(nil); // Crée un nouveau thread
FList.Add(@Result); // Ajoute cet objet dans la liste, à la fin
end;
procedure TThreadListEx.Add(var Thread: TThreadComponent); // Ajoute un thread déjà créé
begin
if Assigned(Thread) then FList.Add(@Thread); // Si l'objet thread existe, on l'ajoute
end;
procedure TThreadListEx.Insert(At: Integer; var Thread: TThreadComponent); // Insère un thread dans la liste
begin
if Assigned(Thread) then FList.Insert(At, @Thread); // Si l'objet thread existe, on l'insère
end;
function TThreadListEx.Extract(At: Integer): TThreadComponent; // Supprime un thread sans le terminer
begin
Result := TThreadComponent(FList.Items[At]^); // On récupère le thread
FList.Items[At] := nil; // On le retire de la liste
end;
procedure TThreadListEx.Delete(At: Integer); // Supprime un thread de la liste
begin
TThreadComponent(FList.Items[At]).Free; // On termine le thread
FList.Delete(At); // La liste le supprime
end;
procedure TThreadListEx.SetNil(At: Integer); // "Gomme" un thread sans le supprimer de la liste
begin
TThreadComponent(FList.Items[At]).Free; // On termine le thread
FList.Items[At] := nil; // L'objet n'existera plus mais occupera toujours une place dans la liste ...
// ... en tant que nil.
end;
procedure TThreadListEx.Exchange(Src, Dest: Integer); // On échange 2 threads de place dans la liste
begin
FList.Exchange(Src, Dest); // La liste possède une méthode pour pouvoir le faire aisément
end;
procedure TThreadListEx.Pack; // Compression et nettoyage de la liste
begin
FList.Pack; // On enlève toutes les références à nil
end;
procedure TThreadListEx.Clear; // Elimine tous les threads de la liste
Var
I: Integer; // Variable de contrôle de boucle
begin
for I := 0 to FList.Count - 1 do // Pour chaque thread dans la liste
TThreadComponent(FList.Items[I]).Free; // On libère chacun des threads
FList.Clear; // Pour finir, on nettoie la liste de pointeurs totalement !
end;
end.
|
unit futils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
{ Returns application name }
function AppName: string;
{ Returns Paramstr(index) as a input po filename. If
a file with a name equal to paramstr(index) does not exist
the a .po extension is added and that is returned}
function ParamFilename(index: integer): string;
{ If filename exists, then adds .bak, .bak1, .bak2, etc extention
to the filename until a non existing file is found. Then filename is
renamed to that new name. Returns false should renaming the file not
work or true otherwise (including when filename does not exist)}
function SaveToBackup(const filename: string): boolean;
{ Returns filename if it does not exist, otherwise returns filenameXXXX
where XXXX are random digits chosen so that this new name does not
exits.}
function UniqueFilename(const filename: string): string;
implementation
function AppName: string;
begin
result := changefileext(extractfilename(paramstr(0)), '');
end;
function ParamFilename(index: integer): string;
begin
result := paramstr(index);
if (result <> '') and not fileexists(result) then
result := result + '.po';
end;
function SaveToBackup(const filename: string): boolean;
var
i: integer;
fname: string;
stub: string;
begin
result := true;
if fileexists(filename) then begin
fname := filename + '.bak';
stub := fname;
i := 0;
while fileexists(fname) do begin
inc(i);
fname := stub + inttostr(i);
end;
result := renamefile(filename, fname);
end;
end;
function UniqueFilename(const filename: string): string;
var
ext, stub: string;
i: integer;
begin
ext := extractfileext(filename);
stub := changefileext(filename, '');
i := 0;
result := filename;
while fileexists(result) do begin
inc(i);
result := Format('%s-%d%s', [stub, i, ext]);
end;
end;
initialization
randomize;
end.
|
unit ItemPicturesForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Menus,
ItemPictureFrame,
InflatablesList_Item,
InflatablesList_Manager;
type
TfItemPicturesForm = class(TForm)
lbPictures: TListBox;
lblPictures: TLabel;
pmnPictures: TPopupMenu;
mniIP_Add: TMenuItem;
mniIP_LoadThumb: TMenuItem;
mniIP_AddWithThumb: TMenuItem;
mniIP_Remove: TMenuItem;
mniIP_RemoveAll: TMenuItem;
N1: TMenuItem;
mniIP_Reload: TMenuItem;
mniIP_ReloadAll: TMenuItem;
N2: TMenuItem;
mniIP_ImportPics: TMenuItem;
mniIP_ExportPic: TMenuItem;
mniIP_ExportThumb: TMenuItem;
mniIP_ExportPicAll: TMenuItem;
mniIP_ExportThumbAll: TMenuItem;
N3: TMenuItem;
mniIP_ItemPicture: TMenuItem;
mniIP_PackagePicture: TMenuItem;
mniIP_SecondaryPicture: TMenuItem;
N4: TMenuItem;
mniIP_MoveUp: TMenuItem;
mniIP_MoveDown: TMenuItem;
diaOpenDialog: TOpenDialog;
diaSaveDialog: TSaveDialog;
gbPictureDetails: TGroupBox;
frmItemPictureFrame: TfrmItemPictureFrame;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lbPicturesClick(Sender: TObject);
procedure lbPicturesDblClick(Sender: TObject);
procedure lbPicturesMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure lbPicturesDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure pmnPicturesPopup(Sender: TObject);
procedure mniIP_AddClick(Sender: TObject);
procedure mniIP_LoadThumbClick(Sender: TObject);
procedure mniIP_AddWithThumbClick(Sender: TObject);
procedure mniIP_RemoveClick(Sender: TObject);
procedure mniIP_RemoveAllClick(Sender: TObject);
procedure mniIP_ReloadClick(Sender: TObject);
procedure mniIP_ReloadAllClick(Sender: TObject);
procedure mniIP_ImportPicsClick(Sender: TObject);
procedure mniIP_ExportPicClick(Sender: TObject);
procedure mniIP_ExportThumbClick(Sender: TObject);
procedure mniIP_ExportPicAllClick(Sender: TObject);
procedure mniIP_ExportThumbAllClick(Sender: TObject);
procedure mniIP_ItemPictureClick(Sender: TObject);
procedure mniIP_PackagePictureClick(Sender: TObject);
procedure mniIP_SecondaryPictureClick(Sender: TObject);
procedure mniIP_MoveUpClick(Sender: TObject);
procedure mniIP_MoveDownClick(Sender: TObject);
private
{ Private declarations }
fILManager: TILManager;
fCurrentItem: TILItem;
fDrawBuffer: TBitmap;
fDirPics: String;
fDirThumbs: String;
fDirExport: String;
protected
procedure FillList;
procedure UpdateIndex;
public
{ Public declarations }
procedure Initialize(ILManager: TILManager);
procedure Finalize;
procedure ShowPictures(Item: TILItem);
end;
var
fItemPicturesForm: TfItemPicturesForm;
implementation
{$R *.dfm}
uses
WinFileInfo, StrRect,
ItemSelectForm,
InflatablesList_Utils,
InflatablesList_ItemPictures_Base;
procedure TfItemPicturesForm.FillList;
var
i: Integer;
begin
If Assigned(fCurrentItem) then
begin
lbPictures.Items.BeginUpdate;
try
// adjust count
If lbPictures.Count < fCurrentItem.Pictures.Count then
For i := lbPictures.Count to Pred(fCurrentItem.Pictures.Count) do
lbPictures.Items.Add('')
else If lbPictures.Count > fCurrentItem.Pictures.Count then
For i := lbPictures.Count downto Pred(fCurrentItem.Pictures.Count) do
lbPictures.Items.Delete(i);
// fill
For i := fCurrentItem.Pictures.LowIndex to fCurrentItem.Pictures.HighIndex do
lbPictures.Items[i] := fCurrentItem.Pictures[i].PictureFile;
finally
lbPictures.Items.EndUpdate;
end;
end
else lbPictures.Clear;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.UpdateIndex;
begin
If Assigned(fCurrentItem) then
begin
If lbPictures.ItemIndex >= 0 then
lblPictures.Caption := IL_Format('Pictures (%d/%d):',[lbPictures.ItemIndex + 1,fCurrentItem.Pictures.Count])
else
lblPictures.Caption := IL_Format('Pictures (%d):',[fCurrentItem.Pictures.Count]);
end
else lblPictures.Caption := 'Pictures:';
end;
//==============================================================================
procedure TfItemPicturesForm.Initialize(ILManager: TILManager);
begin
fILManager := ILManager;
fDirPics := IL_ExcludeTrailingPathDelimiter(fILManager.StaticSettings.DefaultPath);
fDirThumbs := fDirPics;
fDirExport := fDirPics;
frmItemPictureFrame.Initialize(ILManager);
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.Finalize;
begin
frmItemPictureFrame.Finalize;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.ShowPictures(Item: TILItem);
begin
If Assigned(Item) then
begin
fCurrentItem := Item;
Caption := IL_Format('%s - pictures',[fCurrentItem.TitleStr]);
FillList;
If lbPictures.Count > 0 then
lbPictures.ItemIndex := 0;
lbPictures.OnClick(nil);
ShowModal;
end;
end;
//==============================================================================
procedure TfItemPicturesForm.FormCreate(Sender: TObject);
begin
fDrawBuffer := TBitmap.Create;
fDrawBuffer.PixelFormat := pf24bit;
fDrawBuffer.Canvas.Font.Assign(lbPictures.Font);
lbPictures.DoubleBuffered := True;
// shortcuts for popup menu
mniIP_ExportThumb.ShortCut := ShortCut(Ord('E'),[ssCtrl,ssShift]);
mniIP_MoveUp.ShortCut := ShortCut(VK_UP,[ssShift]);
mniIP_MoveDown.ShortCut := ShortCut(VK_DOWN,[ssShift]);
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.FormShow(Sender: TObject);
begin
lbPictures.SetFocus;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(fDrawBuffer);
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.lbPicturesClick(Sender: TObject);
begin
frmItemPictureFrame.SetPicture(fCurrentItem.Pictures,lbPictures.ItemIndex,True);
UpdateIndex;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.lbPicturesDblClick(Sender: TObject);
begin
If fCurrentItem.Pictures.CheckIndex(lbPictures.ItemIndex) then
fCurrentItem.Pictures.OpenPictureFile(lbPictures.ItemIndex);
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.lbPicturesMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Index: Integer;
begin
If Button = mbRight then
begin
Index := lbPictures.ItemAtPos(Point(X,Y),True);
If Index >= 0 then
lbPictures.ItemIndex := Index
else
lbPictures.ItemIndex := -1;
lbPictures.OnClick(nil);
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.lbPicturesDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
BoundsRect: TRect;
TempInt: Integer;
TempStr: String;
begin
If Assigned(fDrawBuffer) then
begin
// adjust draw buffer size
If fDrawBuffer.Width < (Rect.Right - Rect.Left) then
fDrawBuffer.Width := Rect.Right - Rect.Left;
If fDrawBuffer.Height < (Rect.Bottom - Rect.Top) then
fDrawBuffer.Height := Rect.Bottom - Rect.Top;
BoundsRect := Classes.Rect(0,0,Rect.Right - Rect.Left,Rect.Bottom - Rect.Top);
with fDrawBuffer.Canvas do
begin
// background
Pen.Style := psClear;
Brush.Style := bsSolid;
Brush.Color := clWindow;
Rectangle(BoundsRect.Left,BoundsRect.Top,BoundsRect.Right + 1,BoundsRect.Bottom);
// side strip
Brush.Color := $00F7F7F7;
Rectangle(BoundsRect.Left,BoundsRect.Top,BoundsRect.Left + 10,BoundsRect.Bottom);
// separator line
Pen.Style := psSolid;
Pen.Color := clSilver;
MoveTo(BoundsRect.Left,BoundsRect.Bottom - 1);
LineTo(BoundsRect.Right,BoundsRect.Bottom - 1);
// text
Brush.Style := bsClear;
Font.Style := [fsBold];
TextOut(12,3,fCurrentItem.Pictures[Index].PictureFile);
// icons
TempInt := 12;
Pen.Style := psSolid;
Brush.Style := bsSolid;
If fCurrentItem.Pictures.CurrentSecondary = Index then
begin
Pen.Color := $00FFAC22;
Brush.Color := $00FFBF55;
Polygon([Point(TempInt,20),Point(TempInt,31),Point(TempInt + 11,26)]);
Inc(TempInt,14);
end;
If fCurrentItem.Pictures[Index].ItemPicture then
begin
Pen.Color := $0000E700;
Brush.Color := clLime;
Ellipse(TempInt,20,TempInt + 11,31);
Inc(TempInt,14);
end;
If fCurrentItem.Pictures[Index].PackagePicture then
begin
Pen.Color := $0000D3D9;
Brush.Color := $002BFAFF;
Rectangle(TempInt,20,TempInt + 11,31);
end;
// thumbnail
TempInt := BoundsRect.Right - fILManager.DataProvider.EmptyPictureMini.Width - 5;
If Assigned(fCurrentItem.Pictures[Index].ThumbnailMini) and not fILManager.StaticSettings.NoPictures then
begin
Draw(TempInt,BoundsRect.Top + 1,fCurrentItem.Pictures[Index].ThumbnailMini);
fCurrentItem.Pictures[Index].ThumbnailMini.Dormant;
end
else Draw(TempInt,BoundsRect.Top + 1,fILManager.DataProvider.EmptyPictureMini);
Dec(TempInt,7);
// size (bytes) and resolution
Font.Style := Font.Style - [fsBold];
Brush.Style := bsClear;
TempStr := SizeToStr(fCurrentItem.Pictures[Index].PictureSize);
TextOut(TempInt - TextWidth(TempStr),2,TempStr);
If (fCurrentItem.Pictures[Index].PictureWidth > 0) and (fCurrentItem.Pictures[Index].PictureHeight > 0) then
begin
TempStr := IL_Format('%d x %d px',[fCurrentItem.Pictures[Index].PictureWidth,fCurrentItem.Pictures[Index].PictureHeight]);
TextOut(TempInt - TextWidth(TempStr),17,TempStr);
end;
// state
If odSelected in State then
begin
Pen.Style := psClear;
Brush.Style := bsSolid;
Brush.Color := clLime;
Rectangle(BoundsRect.Left,BoundsRect.Top,BoundsRect.Left + 10,BoundsRect.Bottom);
end;
end;
// move drawbuffer to the canvas
lbPictures.Canvas.CopyRect(Rect,fDrawBuffer.Canvas,BoundsRect);
// disable focus rect
If odFocused in State then
lbPictures.Canvas.DrawFocusRect(Rect);
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.pmnPicturesPopup(Sender: TObject);
begin
mniIP_LoadThumb.Enabled := lbPictures.ItemIndex >= 0;
mniIP_Remove.Enabled := lbPictures.ItemIndex >= 0;
mniIP_RemoveAll.Enabled := lbPictures.Count > 0;
mniIP_Reload.Enabled := lbPictures.ItemIndex >= 0;
mniIP_ReloadAll.Enabled := lbPictures.Count > 0;
mniIP_ExportPic.Enabled := lbPictures.ItemIndex >= 0;
mniIP_ExportThumb.Enabled := lbPictures.ItemIndex >= 0;
mniIP_ExportPicAll.Enabled := lbPictures.Count > 0;
mniIP_ExportThumbAll.Enabled := lbPictures.Count > 0;
If Assigned(fCurrentItem) and (lbPictures.ItemIndex >= 0) then
begin
mniIP_ItemPicture.Enabled := True;
mniIP_ItemPicture.Checked := fCurrentItem.Pictures[lbPictures.ItemIndex].ItemPicture;
mniIP_PackagePicture.Enabled := True;
mniIP_PackagePicture.Checked := fCurrentItem.Pictures[lbPictures.ItemIndex].PackagePicture;
mniIP_SecondaryPicture.Enabled := not fCurrentItem.Pictures[lbPictures.ItemIndex].ItemPicture and
not fCurrentItem.Pictures[lbPictures.ItemIndex].PackagePicture;
mniIP_SecondaryPicture.Checked := mniIP_SecondaryPicture.Enabled and (lbPictures.ItemIndex = fCurrentItem.Pictures.CurrentSecondary);
end
else
begin
mniIP_ItemPicture.Enabled := False;
mniIP_ItemPicture.Checked := False;
mniIP_PackagePicture.Enabled := False;
mniIP_PackagePicture.Checked := False;
mniIP_SecondaryPicture.Enabled := False;
mniIP_SecondaryPicture.Checked := False;
end;
mniIP_MoveUp.Enabled := lbPictures.ItemIndex > 0;
mniIP_MoveDown.Enabled := (lbPictures.Count > 0) and ((lbPictures.ItemIndex >= 0) and (lbPictures.ItemIndex < Pred(lbPictures.Count)));
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_AddClick(Sender: TObject);
var
i: Integer;
Info: TILPictureAutomationInfo;
Cntr: Integer;
begin
diaOpenDialog.Filter := 'JPEG/JFIF image (*.jpg;*jpeg)|*.jpg;*.jpeg|All files (*.*)|*.*';
diaOpenDialog.InitialDir := fDirPics;
diaOpenDialog.FileName := '';
diaOpenDialog.Title := 'Add pictures';
diaOpenDialog.Options := diaOpenDialog.Options + [ofAllowMultiselect];
If diaOpenDialog.Execute then
begin
If diaOpenDialog.Files.Count > 0 then
fDirPics := IL_ExtractFileDir(diaOpenDialog.Files[Pred(diaOpenDialog.Files.Count)]);
Cntr := 0;
fCurrentItem.Pictures.BeginUpdate;
try
Screen.Cursor := crHourGlass;
try
For i := 0 to Pred(diaOpenDialog.Files.Count) do
If fCurrentItem.Pictures.AutomatePictureFile(diaOpenDialog.Files[i],Info) then
begin
fCurrentItem.Pictures.Add(Info);
Inc(Cntr);
end;
finally
Screen.Cursor := crDefault;
end;
finally
fCurrentItem.Pictures.EndUpdate;
end;
FillList;
If Cntr > 0 then
begin
lbPictures.ItemIndex := Pred(lbPictures.Count);
lbPictures.OnClick(nil); // updates index
end
else UpdateIndex;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_AddWithThumbClick(Sender: TObject);
var
Info: TILPictureAutomationInfo;
PicFileName: String;
Index: Integer;
Thumbnail: TBitmap;
begin
diaOpenDialog.Filter := 'JPEG/JFIF image (*.jpg;*jpeg)|*.jpg;*.jpeg|All files (*.*)|*.*';
diaOpenDialog.InitialDir := fDirPics;
diaOpenDialog.FileName := '';
diaOpenDialog.Title := 'Add picture';
diaOpenDialog.Options := diaOpenDialog.Options - [ofAllowMultiselect];
If diaOpenDialog.Execute then
begin
fDirPics := IL_ExtractFileDir(diaOpenDialog.FileName);
PicFileName := diaOpenDialog.FileName;
// now for thumbnail...
diaOpenDialog.Filter := 'Windows bitmap image (*.bmp)|*.bmp|All files (*.*)|*.*';
diaOpenDialog.InitialDir := fDirThumbs;
diaOpenDialog.FileName := '';
diaOpenDialog.Title := 'Select thumbnail for the picture';
If diaOpenDialog.Execute then
begin
fDirThumbs := IL_ExtractFileDir(diaOpenDialog.FileName);
If fCurrentItem.Pictures.AutomatePictureFile(PicFileName,Info) then
begin
Thumbnail := TBitmap.Create;
try
Thumbnail.LoadFromFile(StrToRTL(diaOpenDialog.FileName));
If (Thumbnail.Width = 96) and (Thumbnail.Height = 96) and (Thumbnail.PixelFormat = pf24bit) then
begin
fCurrentItem.Pictures.BeginUpdate;
try
Index := fCurrentItem.Pictures.Add(Info);
fCurrentItem.Pictures.SetThumbnail(Index,Thumbnail,True);
finally
fCurrentItem.Pictures.EndUpdate;
end;
FillList;
lbPictures.ItemIndex := Pred(lbPictures.Count);
lbPictures.OnClick(nil); // also updates index
end
else MessageDlg('Invalid format of the thumbnail.',mtError,[mbOK],0);
finally
Thumbnail.Free;
end;
end;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_LoadThumbClick(Sender: TObject);
var
Thumbnail: TBitmap;
begin
If lbPictures.ItemIndex >= 0 then
begin
diaOpenDialog.Filter := 'Windows bitmap image (*.bmp)|*.bmp|All files (*.*)|*.*';
diaOpenDialog.InitialDir := fDirThumbs;
diaOpenDialog.FileName := '';
diaOpenDialog.Title := 'Select thumbnail';
diaOpenDialog.Options := diaOpenDialog.Options - [ofAllowMultiselect];
If diaOpenDialog.Execute then
begin
fDirThumbs := IL_ExtractFileDir(diaOpenDialog.FileName);
Thumbnail := TBitmap.Create;
try
Thumbnail.LoadFromFile(StrToRTL(diaOpenDialog.FileName));
If (Thumbnail.Width = 96) and (Thumbnail.Height = 96) and (Thumbnail.PixelFormat = pf24bit) then
begin
frmItemPictureFrame.SetPicture(nil,-1,False);
fCurrentItem.Pictures.SetThumbnail(lbPictures.ItemIndex,Thumbnail,True);
frmItemPictureFrame.SetPicture(fCurrentItem.Pictures,lbPictures.ItemIndex,True);
FillList;
end
else MessageDlg('Invalid format of the thumbnail.',mtError,[mbOK],0);
finally
Thumbnail.Free;
end;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_RemoveClick(Sender: TObject);
var
Index: Integer;
begin
If lbPictures.ItemIndex >= 0 then
If MessageDlg('Are you sure you want to remove the following picture?' + sLineBreak +
sLineBreak +
fCurrentItem.Pictures[lbPictures.ItemIndex].PictureFile,
mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
frmItemPictureFrame.SetPicture(nil,-1,False);
Index := lbPictures.ItemIndex;
fCurrentItem.Pictures.Delete(lbPictures.ItemIndex);
lbPictures.Items.Delete(lbPictures.ItemIndex);
If lbPictures.Count > 0 then
begin
If Index < lbPictures.Count then
lbPictures.ItemIndex := Index
else
lbPictures.ItemIndex := Pred(lbPictures.Count);
end
else lbPictures.ItemIndex := -1;
lbPictures.OnClick(nil);
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_RemoveAllClick(Sender: TObject);
begin
If lbPictures.Count > 0 then
If MessageDlg('Are you sure you want to remove all pictures?',mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
lbPictures.ItemIndex := -1;
fCurrentItem.Pictures.Clear;
lbPictures.Items.Clear;
lbPictures.OnClick(nil);
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_ReloadClick(Sender: TObject);
begin
If lbPictures.ItemIndex >= 0 then
begin
fCurrentItem.Pictures.RealodPictureInfo(lbPictures.ItemIndex);
FillList;
lbPictures.Invalidate;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_ReloadAllClick(Sender: TObject);
var
i: Integer;
begin
If lbPictures.Count > 0 then
begin
Screen.Cursor := crHourGlass;
try
For i := fCurrentItem.Pictures.LowIndex to fCurrentItem.Pictures.HighIndex do
fCurrentItem.Pictures.RealodPictureInfo(i);
finally
Screen.Cursor := crDefault;
end;
FillList;
lbPictures.Invalidate;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_ImportPicsClick(Sender: TObject);
var
Index: Integer;
Cntr: Integer;
begin
Index := fItemSelectForm.ShowItemSelect('Select an item for pictures import',fCurrentItem.Index);
If fILManager.CheckIndex(Index) then
begin
If fCurrentItem <> fILManager[Index] then
begin
If fILManager[Index].Pictures.Count > 0 then
begin
Cntr := fCurrentItem.Pictures.ImportPictures(fILManager[Index].Pictures);
If Cntr > 1 then
MessageDlg(IL_Format('%d pictures successfully imported, %d failed.',
[Cntr,fILManager[Index].Pictures.Count - Cntr]),mtInformation,[mbOK],0)
else If Cntr > 0 then
MessageDlg(IL_Format('One picture successfully imported, %d failed.',
[fILManager[Index].Pictures.Count - Cntr]),mtInformation,[mbOK],0)
else
MessageDlg('Import completely failed.',mtInformation,[mbOK],0);
FillList;
If lbPictures.ItemIndex < 0 then
begin
lbPictures.ItemIndex := 0;
lbPictures.OnClick(nil);
end;
end
else MessageDlg('Source item does not contain any picture for import.',mtInformation,[mbOK],0);
end
else MessageDlg('Source item is the same as destination item.' + sLineBreak +
'Pictures cannot be imported this way.',mtInformation,[mbOK],0);
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_ExportPicClick(Sender: TObject);
var
Directory: String;
begin
If lbPictures.ItemIndex >= 0 then
begin
Directory := fDirExport;
If IL_SelectDirectory('Select directory for picture export',Directory) then
begin
fDirExport := IL_ExcludeTrailingPAthDelimiter(Directory);
If fCurrentItem.Pictures.ExportPicture(lbPictures.ItemIndex,IL_ExcludeTrailingPathDelimiter(Directory)) then
MessageDlg('Picture successfully exported.',mtInformation,[mbOK],0)
else
MessageDlg('Picture export has failed.',mtError,[mbOK],0)
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_ExportThumbClick(Sender: TObject);
var
Directory: String;
begin
If lbPictures.ItemIndex >= 0 then
If Assigned(fCurrentItem.Pictures[lbPictures.ItemIndex].Thumbnail) then
begin
Directory := fDirExport;
If IL_SelectDirectory('Select directory for thumbnail export',Directory) then
begin
fDirExport := IL_ExcludeTrailingPAthDelimiter(Directory);
If fCurrentItem.Pictures.ExportThumbnail(lbPictures.ItemIndex,IL_ExcludeTrailingPathDelimiter(Directory)) then
MessageDlg('Picture thumbnail successfully exported.',mtInformation,[mbOK],0)
else
MessageDlg('Picture thumbnail export has failed.',mtError,[mbOK],0)
end;
end
else MessageDlg('No thumbnail is assigned to this picture.',mtInformation,[mbOK],0)
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_ExportPicAllClick(Sender: TObject);
var
Directory: String;
i,Cntr: Integer;
begin
If lbPictures.Count > 0 then
begin
Directory := fDirExport;
If IL_SelectDirectory('Select directory for pictures export',Directory) then
begin
fDirExport := IL_ExcludeTrailingPAthDelimiter(Directory);
Cntr := 0;
Screen.Cursor := crHourGlass;
try
For i := fCurrentItem.Pictures.LowIndex to fCurrentItem.Pictures.HighIndex do
If fCurrentItem.Pictures.ExportPicture(i,IL_ExcludeTrailingPathDelimiter(Directory)) then
Inc(Cntr);
finally
Screen.Cursor := crDefault;
end;
MessageDlg(IL_Format('%d pictures successfully exported, %d failed.',
[Cntr,fCurrentItem.Pictures.Count - Cntr]),mtInformation,[mbOK],0);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_ExportThumbAllClick(Sender: TObject);
var
Directory: String;
i,Cntr: Integer;
begin
If lbPictures.Count > 0 then
begin
Directory := fDirExport;
If IL_SelectDirectory('Select directory for thumbnails export',Directory) then
begin
fDirExport := IL_ExcludeTrailingPAthDelimiter(Directory);
Cntr := 0;
Screen.Cursor := crHourGlass;
try
For i := fCurrentItem.Pictures.LowIndex to fCurrentItem.Pictures.HighIndex do
If fCurrentItem.Pictures.ExportThumbnail(i,IL_ExcludeTrailingPathDelimiter(Directory)) then
Inc(Cntr);
finally
Screen.Cursor := crDefault;
end;
MessageDlg(IL_Format('%d picture thumbnails successfully exported, %d failed.',
[Cntr,fCurrentItem.Pictures.Count - Cntr]),mtInformation,[mbOK],0);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_ItemPictureClick(Sender: TObject);
begin
If mniIP_ItemPicture.Enabled then
begin
fCurrentItem.Pictures.SetItemPicture(lbPictures.ItemIndex,not mniIP_ItemPicture.Checked);
mniIP_ItemPicture.Checked := not mniIP_ItemPicture.Checked;
lbPictures.Invalidate;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_PackagePictureClick(Sender: TObject);
begin
If mniIP_PackagePicture.Enabled then
begin
fCurrentItem.Pictures.SetPackagePicture(lbPictures.ItemIndex,not mniIP_PackagePicture.Checked);
mniIP_PackagePicture.Checked := not mniIP_PackagePicture.Checked;
lbPictures.Invalidate;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_SecondaryPictureClick(
Sender: TObject);
begin
If mniIP_SecondaryPicture.Enabled and not mniIP_SecondaryPicture.Checked then
begin
fCurrentItem.Pictures.CurrentSecondary := lbPictures.ItemIndex;
mniIP_SecondaryPicture.Checked := True;
lbPictures.Invalidate;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_MoveUpClick(Sender: TObject);
var
Index: Integer;
begin
If lbPictures.ItemIndex > 0 then
begin
Index := lbPictures.ItemIndex;
lbPictures.Items.Exchange(Index,Index - 1);
fCurrentItem.Pictures.Exchange(Index,Index - 1);
lbPictures.ItemIndex := Index - 1;
lbPictures.Invalidate;
UpdateIndex;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemPicturesForm.mniIP_MoveDownClick(Sender: TObject);
var
Index: Integer;
begin
If (lbPictures.Count > 0) and ((lbPictures.ItemIndex >= 0) and (lbPictures.ItemIndex < Pred(lbPictures.Count))) then
begin
Index := lbPictures.ItemIndex;
lbPictures.Items.Exchange(Index,Index + 1);
fCurrentItem.Pictures.Exchange(Index,Index + 1);
lbPictures.ItemIndex := Index + 1;
lbPictures.Invalidate;
UpdateIndex;
end;
end;
end.
|
unit Moto360Device;
interface
implementation
uses
system.Devices, system.Types, system.SysUtils;
const
ViewName = 'Moto360'; // The name of the view.
{
Add this after MobileDevices in
%AppData%\Roaming\Embarcadero\BDS\15.0\MobileDevices.xml
<MobileDevice>
<Displayname>Moto360</Displayname>
<Name>Moto360</Name>
<DevicePlatform>3</DevicePlatform>
<FormFactor>2</FormFactor>
<Portrait Enabled="True" Width="240" Height="218" Top="102" Left="29" StatusbarHeight="0" StatusBarPos="0" Artwork="<Fullpath>\Moto360View\Moto360.png" />
<UpsideDown Enabled="False" Width="240" Height="218" Top="0" Left="0" StatusbarHeight="0" StatusBarPos="0" Artwork="" />
<LandscapeLeft Enabled="False" Width="240" Height="218" Top="0" Left="0" StatusbarHeight="0" StatusBarPos="0" Artwork="" />
<LandscapeRight Enabled="False" Width="240" Height="218" Top="0" Left="0" StatusbarHeight="0" StatusBarPos="0" Artwork="" />
</MobileDevice>
}
initialization
TDeviceinfo.AddDevice(TDeviceinfo.TDeviceClass.Tablet, ViewName,
// The Moto360 is 320x290 phyiscal and 240x218 logical with 213 PPI
// The Android Wear emulator is 320x320 and 213x213 logical with 240 PPI
TSize.Create(320, 290), TSize.Create(240, 218), // MinPhysicalSize(max, min), MinLogicalSize(max, min)
TOSVersion.TPlatform.pfAndroid, 213, //Select the platform and the pixel density.
True); // Exclusive
finalization
TDeviceinfo.RemoveDevice(ViewName); // To unregister the view after unistalling the package.
end.
|
unit DistanceFormulas;
interface
uses BasicMathsTypes;
const
CDF_IGNORED = 0;
CDF_LINEAR = 1;
CDF_LINEAR_INV = 2;
CDF_QUADRIC = 3;
CDF_QUADRIC_INV = 4;
CDF_CUBIC = 5;
CDF_CUBIC_INV = 6;
CDF_LANCZOS = 7;
CDF_LANCZOS_INV_A1 = 8;
CDF_LANCZOS_INV_A3 = 9;
CDF_LANCZOS_INV_AC = 10;
CDF_SINC = 11;
CDF_SINC_INV = 12;
CDF_EULER = 13;
CDF_EULERSQUARED = 14;
CDF_SINCINFINITE = 15;
CDF_SINCINFINITE_INV = 16;
function GetDistanceFormula(_ID: integer): TDistanceFunc;
// Distance Functions
function GetIgnoredDistance(_Distance : single): single;
function GetLinearDistance(_Distance : single): single;
function GetLinearInvDistance(_Distance : single): single;
function GetQuadricDistance(_Distance : single): single;
function GetQuadricInvDistance(_Distance : single): single;
function GetCubicDistance(_Distance : single): single;
function GetCubicInvDistance(_Distance : single): single;
function GetLanczosDistance(_Distance : single): single;
function GetLanczosInvA1Distance(_Distance : single): single;
function GetLanczosInvA3Distance(_Distance : single): single;
function GetLanczosInvACDistance(_Distance : single): single;
function GetSincDistance(_Distance : single): single;
function GetSincInvDistance(_Distance : single): single;
function GetEulerDistance(_Distance : single): single;
function GetEulerSquaredDistance(_Distance : single): single;
function GetSincInfiniteDistance(_Distance : single): single;
function GetSincInfiniteInvDistance(_Distance : single): single;
implementation
uses Math, GLConstants;
function GetDistanceFormula(_ID: integer): TDistanceFunc;
begin
case (_ID) of
CDF_IGNORED: Result := GetIgnoredDistance;
CDF_LINEAR: Result := GetLinearDistance;
CDF_LINEAR_INV: Result := GetLinearInvDistance;
CDF_QUADRIC: Result := GetQuadricDistance;
CDF_QUADRIC_INV: Result := GetQuadricInvDistance;
CDF_CUBIC: Result := GetCubicDistance;
CDF_CUBIC_INV: Result := GetCubicInvDistance;
CDF_LANCZOS: Result := GetLanczosDistance;
CDF_LANCZOS_INV_A1: Result := GetLanczosInvA1Distance;
CDF_LANCZOS_INV_A3: Result := GetLanczosInvA3Distance;
CDF_LANCZOS_INV_AC: Result := GetLanczosInvACDistance;
CDF_SINC: Result := GetSincDistance;
CDF_SINC_INV: Result := GetSincInvDistance;
CDF_EULER: Result := GetEulerDistance;
CDF_EULERSQUARED: Result := GetEulerSquaredDistance;
CDF_SINCINFINITE: Result := GetSincInfiniteDistance;
CDF_SINCINFINITE_INV: Result := GetSincInfiniteInvDistance;
else
Result := GetIgnoredDistance;
end;
end;
// Distance Formulas
function GetIgnoredDistance(_Distance : single): single;
begin
Result := 1;
end;
function GetLinearDistance(_Distance : single): single;
begin
Result := _Distance;
end;
function GetLinearInvDistance(_Distance : single): single;
begin
Result := 1 / (abs(_Distance) + 1);
end;
function GetQuadricDistance(_Distance : single): single;
const
FREQ_NORMALIZER = 4/3;
begin
Result := Power(FREQ_NORMALIZER * _Distance,2);
if _Distance < 0 then
Result := Result * -1;
end;
function GetQuadricInvDistance(_Distance : single): single;
const
FREQ_NORMALIZER = 4/3;
begin
Result := 1 / (1 + Power(FREQ_NORMALIZER * _Distance,2));
if _Distance < 0 then
Result := Result * -1;
end;
function GetCubicDistance(_Distance : single): single;
const
FREQ_NORMALIZER = 1.5;
begin
Result := Power(FREQ_NORMALIZER * _Distance,3);
end;
function GetCubicInvDistance(_Distance : single): single;
begin
Result := 1 / (1 + Power(_Distance,3));
end;
function GetLanczosDistance(_Distance : single): single;
const
PIDIV3 = Pi / 3;
begin
Result := ((3 * sin(Pi * _Distance) * sin(PIDIV3 * _Distance)) / Power(Pi * _Distance,2));
if _Distance < 0 then
Result := Result * -1;
end;
function GetLanczosInvA1Distance(_Distance : single): single;
begin
Result := 0;
if _Distance <> 0 then
Result := 1 - (Power(sin(Pi * _Distance),2) / Power(Pi * _Distance,2));
if _Distance < 0 then
Result := Result * -1;
end;
function GetLanczosInvA3Distance(_Distance : single): single;
const
PIDIV3 = Pi / 3;
begin
Result := 0;
if _Distance <> 0 then
Result := 1 - ((3 * sin(Pi * _Distance) * sin(PIDIV3 * _Distance)) / Power(Pi * _Distance,2));
if _Distance < 0 then
Result := Result * -1;
end;
function GetLanczosInvACDistance(_Distance : single): single;
const
CONST_A = 3;//15;
NORMALIZER = 2 * Pi;
PIDIVA = Pi / CONST_A;
var
Distance: single;
begin
Result := 0;
Distance := _Distance * C_FREQ_NORMALIZER;
if _Distance <> 0 then
// Result := NORMALIZER * (1 - ((CONST_A * sin(Distance) * sin(Distance / CONST_A)) / Power(Distance,2)));
Result := (1 - ((CONST_A * sin(Pi * Distance) * sin(PIDIVA * Distance)) / Power(Pi * Distance,2)));
if _Distance < 0 then
Result := Result * -1;
end;
function GetSincDistance(_Distance : single): single;
const
NORMALIZER = 2 * Pi; //6.307993515;
var
Distance: single;
begin
Result := 0;
// Distance := _Distance * C_FREQ_NORMALIZER;
if _Distance <> 0 then
Result := (sin(Distance) / Distance);
if _Distance < 0 then
Result := Result * -1;
end;
function GetSincInvDistance(_Distance : single): single;
const
NORMALIZER = 2 * Pi; //6.307993515;
var
Distance: single;
begin
Result := 0;
Distance := _Distance * C_FREQ_NORMALIZER;
if _Distance <> 0 then
Result := 1 - (NORMALIZER * (sin(Distance) / Distance));
if _Distance < 0 then
Result := Result * -1;
end;
function GetEulerDistance(_Distance : single): single;
var
i,c : integer;
Distance : single;
begin
i := 2;
Result := 1;
c := 0;
Distance := abs(_Distance);
while c <= 30 do
begin
Result := Result * cos(Distance / i);
i := i * 2;
inc(c);
end;
if _Distance < 0 then
Result := -Result;
end;
function GetEulerSquaredDistance(_Distance : single): single;
var
i,c : integer;
begin
i := 2;
Result := 1;
c := 0;
while c <= 30 do
begin
Result := Result * cos(_Distance / i);
i := i * 2;
inc(c);
end;
Result := Result * Result;
if _Distance < 0 then
Result := -Result;
end;
function GetSincInfiniteDistance(_Distance : single): single;
var
i,c : integer;
Distance2: single;
begin
c := 0;
i := 1;
Distance2 := _Distance * _Distance;
Result := 1;
while c <= 100 do
begin
Result := Result * (1 - (Distance2 / (i * i)));
inc(c);
inc(i);
end;
if _Distance < 0 then
Result := -Result;
end;
function GetSincInfiniteInvDistance(_Distance : single): single;
var
i,c : integer;
Distance2: single;
begin
c := 0;
i := 1;
Distance2 := _Distance * _Distance;
Result := 1;
while c <= 100 do
begin
Result := Result * (1 - (Distance2 / (i * i)));
inc(c);
inc(i);
end;
Result := 1 - Result;
if _Distance < 0 then
Result := -Result;
end;
end.
|
unit uFrmUserMessageSend;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaideTodosGeral, siComp, siLangRT, StdCtrls, Buttons, ExtCtrls,
uFrmUserMessageUserList;
const
TYPE_NEW = 0;
TYPE_REPLAY = 1;
TYPE_FORWARD = 2;
type
TFrmUserMessageSend = class(TFrmParentAll)
pnlUsers: TPanel;
btnSendTo: TSpeedButton;
Label1: TLabel;
edtSubject: TEdit;
mmReceivers: TMemo;
pnlBody: TPanel;
memBody: TMemo;
btnSend: TButton;
lbChar: TLabel;
memoHistory: TMemo;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure btnSendToClick(Sender: TObject);
procedure memBodyChange(Sender: TObject);
procedure btnSendClick(Sender: TObject);
private
fIDs, fUsers : String;
fType : Integer;
fFrmUsers: TFrmUserMessageUserList;
function ValidadeFields:Boolean;
procedure BuildHistory(Subject, Body : String);
public
function Start(iType:Integer; var sSubject, sMsg, sIDUser : String;
sHistory : String):Boolean;
end;
implementation
{$R *.dfm}
procedure TFrmUserMessageSend.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
FreeAndNil(fFrmUsers);
end;
function TFrmUserMessageSend.Start(iType: Integer; var sSubject, sMsg,
sIDUser : String; sHistory: String): Boolean;
begin
fType := iType;
memoHistory.Visible := False;
case fType of
TYPE_REPLAY : begin
mmReceivers.Text := sIDUser;
edtSubject.Text := 'Re: ' + sSubject;
btnSendTo.Enabled := False;
BuildHistory(edtSubject.Text, sHistory);
end;
TYPE_FORWARD : begin
edtSubject.Text := 'Fw: ' + sSubject;
btnSendTo.Enabled := True;
BuildHistory(edtSubject.Text, sHistory);
end;
else
begin
btnSendTo.Enabled := True;
end;
end;
ShowModal;
Result := (ModalResult = mrOK);
sIDUser := fIDs;
sSubject := edtSubject.Text;
sMsg := memBody.Text;
end;
procedure TFrmUserMessageSend.FormCreate(Sender: TObject);
begin
inherited;
fFrmUsers := TFrmUserMessageUserList.Create(Self);
end;
procedure TFrmUserMessageSend.btnSendToClick(Sender: TObject);
begin
inherited;
if fFrmUsers.Start(fIDs, fUsers) then
begin
mmReceivers.Clear;
mmReceivers.Text := fUsers;
end;
end;
procedure TFrmUserMessageSend.memBodyChange(Sender: TObject);
begin
inherited;
lbChar.Caption := IntToStr(225-Length(memBody.Lines.Text)) + ' character(s)';
end;
function TFrmUserMessageSend.ValidadeFields: Boolean;
begin
Result := False;
if Trim(edtSubject.Text) = '' then
Exit;
if Trim(memBody.Text) = '' then
Exit;
Result := True;
end;
procedure TFrmUserMessageSend.btnSendClick(Sender: TObject);
begin
inherited;
if not ValidadeFields then
ModalResult := mrNone;
end;
procedure TFrmUserMessageSend.BuildHistory(Subject, Body: String);
begin
memoHistory.Visible := True;
memoHistory.Clear;
memoHistory.Lines.Add(Subject);
memoHistory.Lines.Add('======================');
memoHistory.Lines.Add(Body);
end;
end.
|
unit TestBitmapUtils;
interface
uses
TestFramework,
Generics.Collections,
System.Math,
System.SysUtils,
System.Classes,
Vcl.Forms,
Vcl.Graphics,
Vcl.Imaging.Jpeg,
Dmitry.Controls.WebLink,
Dmitry.Controls.WebLinkList,
uBitmapUtils,
uMediaInfo;
type
TTestBitmapUtils = class(TTestCase)
strict private
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestImageScale;
procedure TestWebLinkCreate;
end;
implementation
procedure TTestBitmapUtils.SetUp;
begin
FailsOnMemoryLeak := True;
FailsOnMemoryRecovery := True;
end;
procedure TTestBitmapUtils.TearDown;
begin
end;
procedure TTestBitmapUtils.TestImageScale;
var
FileName: string;
S, D: TBitmap;
J: TJpegImage;
I: Integer;
begin
FileName := ExtractFileDir(ExtractFileDir(ExtractFileDir(ExtractFileDir(ExtractFileDir(Application.Exename))))) + '\Test Images\IMG_2702_small.jpg';
J := TJpegImage.Create;
J.LoadFromFile(FileName);
S := TBitmap.Create;
S.Assign(J);
D := TBitmap.Create;
for I := 0 to 1000 do
SmoothResize(500, 500, S, D);
D.Free;
S.Free;
J.Free;
end;
procedure TTestBitmapUtils.TestWebLinkCreate;
var
I: Integer;
WLL: TWebLinkList;
WL: TWebLink;
F: TForm;
begin
F := TForm.Create(nil);
WLL := TWebLinkList.Create(F);
WLL.Parent := F;
F.Show;
for I := 0 to 100 do
WLL.AddLink(True).Text := IntToStr(I);
WLL.AutoHeight(100);
F.Free;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TTestBitmapUtils.Suite);
end.
|
unit uAOCUtils;
interface
uses
inifiles, System.SysUtils, System.Generics.Collections, AOCBase, RTTI, System.Classes,
System.Net.HttpClient, System.Net.urlclient, system.Generics.Defaults;
type AOCconfig = Record
BaseUrl: string;
BaseFilePath: string;
SessionCookie: string;
procedure LoadConfig;
End;
type TAdventOfCodeRef = class of TAdventOfCode;
type TDirection = (Up = 0, Right, Down, Left);
type AOCUtils = class
public
class var Config: AOCConfig;
class function GetAdventOfCode: TList<TAdventOfCodeRef>;
class function DayIndexFromClassName(Const aClassName: String): String;
class procedure DoAdventOfCode(aAdventOfCodeRef: TAdventOfCodeRef);
class procedure DownLoadPuzzleInput(var InputList: TStrings; Const DayIndex: String);
end;
type TAOCDictionary<TKey,TValue> = class(TDictionary<TKey,TValue>)
public
procedure AddOrIgnoreValue(const Key: TKey; const Value: TValue);
constructor Create(const aOnValueNoify: TCollectionNotifyEvent<TValue>); overload;
procedure Free; overload;
end;
type
TPosition = record
x: integer;
y: Integer;
function SetIt(const aX, aY: integer): TPosition;
function AddDelta(const aX, aY: Integer): TPosition;
function Equals(Const Other: TPosition): Boolean;
function Clone: TPosition;
function ApplyDirection(Const aDirection: TDirection): TPosition;
end;
function GCD(Number1, Number2: int64): int64;
function OccurrencesOfChar(const S: string; const C: string): integer;
implementation
procedure AOCconfig.LoadConfig;
const Config: string = 'Config';
var Ini: TIniFile;
begin
Ini := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
try
BaseUrl := Ini.ReadString(Config, 'BaseUrl', '');
BaseFilePath := Ini.ReadString(Config, 'BaseFilePath', '');
SessionCookie := Ini.ReadString(Config, 'SessionCookie', '');
finally
Ini.Free;
end;
end;
class function AOCUtils.GetAdventOfCode: TList<TAdventOfCodeRef>;
var
ctx: TRttiContext;
lType: TRttiType;
AdventOfCode: TAdventOfCodeRef;
Comparison: TComparison<TAdventOfCodeRef>;
begin
result := TList<TAdventOfCodeRef>.Create;
ctx := TRttiContext.Create;
Writeln('Discovering advent of code');
for lType in ctx.GetTypes do
if (lType is TRttiInstanceType) and (TRttiInstanceType(lType).MetaclassType.InheritsFrom(TAdventOfCode))
then
begin
AdventOfCode := TAdventOfCodeRef(TRttiInstanceType(lType).MetaclassType);
if AdventOfCode.ClassName <> TAdventOfCode.ClassName then
begin
Writeln('Found '+ AdventOfCode.ClassName);
Result.Add(adventOfCode);
end;
end;
Comparison :=
function(const Left, Right: TAdventOfCodeRef): Integer
begin
Result := StrToInt(AOCUtils.DayIndexFromClassName(Left.ClassName)) -
StrToInt(AOCUtils.DayIndexFromClassName(Right.ClassName));
end;
Result.Sort(TComparer<TAdventOfCodeRef>.Construct(Comparison));
end;
class function AOCUtils.DayIndexFromClassName(Const aClassName: String): String;
var i: Integer;
begin
i := Length('TAdventOfCodeDay');
Result := Copy(aClassName, i + 1, Length(aClassName) - i);
end;
class procedure AOCUtils.DoAdventOfCode(aAdventOfCodeRef: TAdventOfCodeRef);
var AdventOfCode: TAdventOfCode;
begin
AdventOfCode := aAdventOfCodeRef.Create;
try
AdventOfCode.Solve;
finally
AdventOfCode.Free;
end;
end;
class procedure AOCUtils.DownLoadPuzzleInput(var InputList: TStrings; Const DayIndex: String);
var HttpClient: THttpClient;
lHeader: TNetHeader;
Headers: TNetHeaders;
MemoryStream: TMemoryStream;
Url: string;
begin
Url := AOCUtils.Config.BaseUrl+'/day/'+DayIndex+'/input';
WriteLn('Downloading puzzle data from ' + Url);
HttpClient := THTTPClient.Create;
lHeader := LHeader.Create('cookie', AOCUtils.Config.SessionCookie );
SetLength(Headers, 1);
Headers[0] := lHeader;
MemoryStream := TMemoryStream.Create;
try
HttpClient.Get(Url, MemoryStream, Headers);
InputList.LoadFromStream(MemoryStream);
finally
HttpClient.Free;
MemoryStream.Free;
end;
end;
procedure TAOCDictionary<TKey,TValue>.AddOrIgnoreValue(const Key: TKey; const Value: TValue);
begin
if not Self.ContainsKey(Key) then
Self.Add(Key, Value);
end;
constructor TAOCDictionary<TKey,TValue>.Create(const aOnValueNoify: TCollectionNotifyEvent<TValue>);
begin
inherited Create;
OnValueNotify := aOnValueNoify;
end;
procedure TAOCDictionary<TKey,TValue>.Free;
begin
Self.Clear;
inherited Free;
end;
function TPosition.SetIt(const aX: Integer; const aY: Integer): TPosition;
begin
x := aX;
y := aY;
Result := Self;
end;
function TPosition.AddDelta(const aX, aY: Integer): TPosition;
begin
x := x + aX;
y := y + aY;
Result := Self;
end;
function TPosition.Equals(Const Other: TPosition): Boolean;
begin
Result := (x = Other.x) and (y = Other.y);
end;
function TPosition.Clone: TPosition;
begin
Result.x := Self.x;
Result.y := Self.y;
end;
function TPosition.ApplyDirection(Const aDirection: TDirection): TPosition;
begin
case aDirection of
Up: AddDelta(0, -1);
Right: AddDelta(1, 0);
Down: AddDelta(0, 1);
Left: AddDelta(-1, 0);
end;
Result := Self
end;
function GCD(Number1, Number2: int64): int64;
var Temp: int64;
begin
if Number1 < 0 then Number1 := -Number1;
if Number2 < 0 then Number2 := -Number2;
repeat
if Number1 < Number2 then
begin
Temp := Number1;
Number1 := Number2;
Number2 := Temp;
end;
Number1 := Number1 mod Number2;
until (Number1 = 0);
result := Number2;
end;
function OccurrencesOfChar(const S: string; const C: string): integer;
var
i: Integer;
begin
result := 0;
i := Pos(c, s);
if i = 0 then
exit;
while i > 0 do
begin
Inc(Result);
i := Pos(c, s, i+1);
end;
end;
end.
|
unit uPedidoVendaDAOClient;
interface
uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, Generics.Collections, PedidoVenda, ItemPedidoVenda, DBXJSONReflect;
type
TPedidoVendaDAOClient = class(TDSAdminClient)
private
FNextCodigoCommand: TDBXCommand;
FInsertCommand: TDBXCommand;
FDeleteCommand: TDBXCommand;
FUpdateCommand: TDBXCommand;
FInsertItemNoPedidoCommand: TDBXCommand;
FDeleteItemDoPedidoCommand: TDBXCommand;
FAtualizaItemDoPedidoCommand: TDBXCommand;
FRelatorioPedidosVendaCommand: TDBXCommand;
FVendasFechadasCommand: TDBXCommand;
FVendasAbertasCommand: TDBXCommand;
FReciboCommand: TDBXCommand;
FFindByCodigoCommand: TDBXCommand;
FCancelarVendaCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function NextCodigo: string;
function Insert(PedidoVenda: TPedidoVenda): Boolean;
function Delete(CodigoPedidoVenda: string): Boolean;
function Update(PedidoVenda: TPedidoVenda): Boolean;
function InsertItemNoPedido(CodigoPedidoVenda: string; Item: TItemPedidoVenda): Boolean;
function DeleteItemDoPedido(CodigoProduto: string; CodigoPedidoVenda: string): Boolean;
function AtualizaItemDoPedido(CodigoPedidoVenda: string; Item: TItemPedidoVenda): Boolean;
function RelatorioPedidosVenda(DataInicial, DataFinal: TDateTime; TipoPagamento: Integer; ClienteCodigo: string): TDBXReader;
function VendasFechadas: TDBXReader;
function VendasAbertas: TDBXReader;
function Recibo(CodigoPedidoVenda: string): TDBXReader;
function FindByCodigo(Codigo: string): TPedidoVenda;
function CancelarVenda(CodigoPedidoVenda: string): Boolean;
end;
implementation
function TPedidoVendaDAOClient.NextCodigo: string;
begin
if FNextCodigoCommand = nil then
begin
FNextCodigoCommand := FDBXConnection.CreateCommand;
FNextCodigoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FNextCodigoCommand.Text := 'TPedidoVendaDAO.NextCodigo';
FNextCodigoCommand.Prepare;
end;
FNextCodigoCommand.ExecuteUpdate;
Result := FNextCodigoCommand.Parameters[0].Value.GetWideString;
end;
function TPedidoVendaDAOClient.Insert(PedidoVenda: TPedidoVenda): Boolean;
begin
if FInsertCommand = nil then
begin
FInsertCommand := FDBXConnection.CreateCommand;
FInsertCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsertCommand.Text := 'TPedidoVendaDAO.Insert';
FInsertCommand.Prepare;
end;
if not Assigned(PedidoVenda) then
FInsertCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FInsertCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FInsertCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(PedidoVenda), True);
if FInstanceOwner then
PedidoVenda.Free
finally
FreeAndNil(FMarshal)
end
end;
FInsertCommand.ExecuteUpdate;
Result := FInsertCommand.Parameters[1].Value.GetBoolean;
end;
function TPedidoVendaDAOClient.Delete(CodigoPedidoVenda: string): Boolean;
begin
if FDeleteCommand = nil then
begin
FDeleteCommand := FDBXConnection.CreateCommand;
FDeleteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDeleteCommand.Text := 'TPedidoVendaDAO.Delete';
FDeleteCommand.Prepare;
end;
FDeleteCommand.Parameters[0].Value.SetWideString(CodigoPedidoVenda);
FDeleteCommand.ExecuteUpdate;
Result := FDeleteCommand.Parameters[1].Value.GetBoolean;
end;
function TPedidoVendaDAOClient.InsertItemNoPedido(CodigoPedidoVenda: string; Item: TItemPedidoVenda): Boolean;
begin
if FInsertItemNoPedidoCommand = nil then
begin
FInsertItemNoPedidoCommand := FDBXConnection.CreateCommand;
FInsertItemNoPedidoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsertItemNoPedidoCommand.Text := 'TPedidoVendaDAO.InsertItemNoPedido';
FInsertItemNoPedidoCommand.Prepare;
end;
FInsertItemNoPedidoCommand.Parameters[0].Value.SetWideString(CodigoPedidoVenda);
if not Assigned(Item) then
FInsertItemNoPedidoCommand.Parameters[1].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FInsertItemNoPedidoCommand.Parameters[1].ConnectionHandler).GetJSONMarshaler;
try
FInsertItemNoPedidoCommand.Parameters[1].Value.SetJSONValue(FMarshal.Marshal(Item), True);
if FInstanceOwner then
Item.Free
finally
FreeAndNil(FMarshal)
end
end;
FInsertItemNoPedidoCommand.ExecuteUpdate;
Result := FInsertItemNoPedidoCommand.Parameters[2].Value.GetBoolean;
end;
function TPedidoVendaDAOClient.DeleteItemDoPedido(CodigoProduto: string; CodigoPedidoVenda: string): Boolean;
begin
if FDeleteItemDoPedidoCommand = nil then
begin
FDeleteItemDoPedidoCommand := FDBXConnection.CreateCommand;
FDeleteItemDoPedidoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDeleteItemDoPedidoCommand.Text := 'TPedidoVendaDAO.DeleteItemDoPedido';
FDeleteItemDoPedidoCommand.Prepare;
end;
FDeleteItemDoPedidoCommand.Parameters[0].Value.SetWideString(CodigoProduto);
FDeleteItemDoPedidoCommand.Parameters[1].Value.SetWideString(CodigoPedidoVenda);
FDeleteItemDoPedidoCommand.ExecuteUpdate;
Result := FDeleteItemDoPedidoCommand.Parameters[2].Value.GetBoolean;
end;
function TPedidoVendaDAOClient.Recibo(CodigoPedidoVenda: string): TDBXReader;
begin
if FReciboCommand = nil then
begin
FReciboCommand := FDBXConnection.CreateCommand;
FReciboCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FReciboCommand.Text := 'TPedidoVendaDAO.Recibo';
FReciboCommand.Prepare;
end;
FReciboCommand.Parameters[0].Value.AsString := CodigoPedidoVenda;
FReciboCommand.ExecuteUpdate;
Result := FReciboCommand.Parameters[1].Value.GetDBXReader(FInstanceOwner);
end;
function TPedidoVendaDAOClient.RelatorioPedidosVenda(DataInicial, DataFinal: TDateTime; TipoPagamento: Integer; ClienteCodigo: string): TDBXReader;
begin
if FRelatorioPedidosVendaCommand = nil then
begin
FRelatorioPedidosVendaCommand := FDBXConnection.CreateCommand;
FRelatorioPedidosVendaCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FRelatorioPedidosVendaCommand.Text := 'TPedidoVendaDAO.RelatorioPedidosVenda';
FRelatorioPedidosVendaCommand.Prepare;
end;
FRelatorioPedidosVendaCommand.Parameters[0].Value.AsDateTime := DataInicial;
FRelatorioPedidosVendaCommand.Parameters[1].Value.AsDateTime := DataFinal;
FRelatorioPedidosVendaCommand.Parameters[2].Value.AsInt32 := TipoPagamento;
FRelatorioPedidosVendaCommand.Parameters[3].Value.AsString := ClienteCodigo;
FRelatorioPedidosVendaCommand.ExecuteUpdate;
Result := FRelatorioPedidosVendaCommand.Parameters[4].Value.GetDBXReader(FInstanceOwner);
end;
function TPedidoVendaDAOClient.Update(PedidoVenda: TPedidoVenda): Boolean;
begin
if FUpdateCommand = nil then
begin
FUpdateCommand := FDBXConnection.CreateCommand;
FUpdateCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FUpdateCommand.Text := 'TPedidoVendaDAO.Update';
FUpdateCommand.Prepare;
end;
if not Assigned(PedidoVenda) then
FUpdateCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FUpdateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FUpdateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(PedidoVenda), True);
if FInstanceOwner then
PedidoVenda.Free
finally
FreeAndNil(FMarshal)
end
end;
FUpdateCommand.ExecuteUpdate;
Result := FUpdateCommand.Parameters[1].Value.GetBoolean;
end;
function TPedidoVendaDAOClient.VendasAbertas: TDBXReader;
begin
if FVendasAbertasCommand = nil then
begin
FVendasAbertasCommand := FDBXConnection.CreateCommand;
FVendasAbertasCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FVendasAbertasCommand.Text := 'TPedidoVendaDAO.VendasAbertas';
FVendasAbertasCommand.Prepare;
end;
FVendasAbertasCommand.ExecuteUpdate;
Result := FVendasAbertasCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
function TPedidoVendaDAOClient.VendasFechadas: TDBXReader;
begin
if FVendasFechadasCommand = nil then
begin
FVendasFechadasCommand := FDBXConnection.CreateCommand;
FVendasFechadasCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FVendasFechadasCommand.Text := 'TPedidoVendaDAO.VendasFechadas';
FVendasFechadasCommand.Prepare;
end;
FVendasFechadasCommand.ExecuteUpdate;
Result := FVendasFechadasCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
constructor TPedidoVendaDAOClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
function TPedidoVendaDAOClient.AtualizaItemDoPedido(CodigoPedidoVenda: string; Item: TItemPedidoVenda): Boolean;
begin
if FAtualizaItemDoPedidoCommand = nil then
begin
FAtualizaItemDoPedidoCommand := FDBXConnection.CreateCommand;
FAtualizaItemDoPedidoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FAtualizaItemDoPedidoCommand.Text := 'TPedidoVendaDAO.AtualizaItemDoPedido';
FAtualizaItemDoPedidoCommand.Prepare;
end;
FAtualizaItemDoPedidoCommand.Parameters[0].Value.SetWideString(CodigoPedidoVenda);
if not Assigned(Item) then
FAtualizaItemDoPedidoCommand.Parameters[1].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FAtualizaItemDoPedidoCommand.Parameters[1].ConnectionHandler).GetJSONMarshaler;
try
FAtualizaItemDoPedidoCommand.Parameters[1].Value.SetJSONValue(FMarshal.Marshal(Item), True);
if FInstanceOwner then
Item.Free
finally
FreeAndNil(FMarshal)
end;
end;
FAtualizaItemDoPedidoCommand.ExecuteUpdate;
Result := FAtualizaItemDoPedidoCommand.Parameters[2].Value.GetBoolean;
end;
function TPedidoVendaDAOClient.CancelarVenda(CodigoPedidoVenda: string): Boolean;
begin
if FCancelarVendaCommand = nil then
begin
FCancelarVendaCommand := FDBXConnection.CreateCommand;
FCancelarVendaCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FCancelarVendaCommand.Text := 'TPedidoVendaDAO.CancelarVenda';
FCancelarVendaCommand.Prepare;
end;
FCancelarVendaCommand.Parameters[0].Value.AsString := CodigoPedidoVenda;
FCancelarVendaCommand.ExecuteUpdate;
Result := FCancelarVendaCommand.Parameters[1].Value.GetBoolean(FInstanceOwner);
end;
constructor TPedidoVendaDAOClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TPedidoVendaDAOClient.Destroy;
begin
FreeAndNil(FNextCodigoCommand);
FreeAndNil(FInsertCommand);
FreeAndNil(FDeleteCommand);
FreeAndNil(FUpdateCommand);
FreeAndNil(FInsertItemNoPedidoCommand);
FreeAndNil(FDeleteItemDoPedidoCommand);
FreeAndNil(FAtualizaItemDoPedidoCommand);
FreeAndNil(FRelatorioPedidosVendaCommand);
FreeAndNil(FVendasFechadasCommand);
FreeAndNil(FVendasAbertasCommand);
FreeAndNil(FReciboCommand);
FreeAndNil(FFindByCodigoCommand);
inherited;
end;
function TPedidoVendaDAOClient.FindByCodigo(Codigo: string): TPedidoVenda;
begin
if FFindByCodigoCommand = nil then
begin
FFindByCodigoCommand := FDBXConnection.CreateCommand;
FFindByCodigoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FFindByCodigoCommand.Text := 'TPedidoVendaDAO.FindByCodigo';
FFindByCodigoCommand.Prepare;
end;
FFindByCodigoCommand.Parameters[0].Value.SetWideString(Codigo);
FFindByCodigoCommand.ExecuteUpdate;
if not FFindByCodigoCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDBXClientCommand(FFindByCodigoCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TPedidoVenda(FUnMarshal.UnMarshal(FFindByCodigoCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FFindByCodigoCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdActns, System.Actions,
Vcl.ActnList, Vcl.Menus, Vcl.ComCtrls, unit2, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
ActionList1: TActionList;
FileExit1: TFileExit;
FileOpen1: TFileOpen;
StatusBar1: TStatusBar;
MainMenu1: TMainMenu;
File1: TMenuItem;
Open1: TMenuItem;
Exit1: TMenuItem;
FileSaveAs1: TFileSaveAs;
SaveAs1: TMenuItem;
Image1: TImage;
procedure FileOpen1Accept(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FileSaveAs1Accept(Sender: TObject);
procedure FileSaveAs1Update(Sender: TObject);
procedure FileSaveAs1BeforeExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
l: TTRLevel;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
System.UITypes, unit3;
procedure TForm1.FileOpen1Accept(Sender: TObject);
var
r: uint8;
begin
if LowerCase(ExtractFileExt(FileOpen1.Dialog.FileName)) <> '.tr4' then
begin
MessageDlg('Not a TR4 file!', mtError, [mbOK], 0);
Exit;
end;
if l.file_version > 0 then l.Free;
r := l.Load(FileOpen1.Dialog.FileName);
case r of
1:
begin
MessageDlg('File does not exist!', mtError, [mbOK], 0);
Exit;
end;
2:
begin
MessageDlg('Not a TR4 file!', mtError, [mbOK], 0);
Exit;
end;
3:
begin
MessageDlg('Encrypted TR4 file!', mtError, [mbOK], 0);
Exit;
end;
end; //case
Image1.Picture.Bitmap:=l.bmp;
end;
procedure TForm1.FileSaveAs1Accept(Sender: TObject);
var
p: TTRProject;
begin
p := l.ConvertToPRJ(FileSaveAs1.Dialog.FileName);
p.Save(FileSaveAs1.Dialog.FileName);
p.Free;
// Halt(0);
end;
procedure TForm1.FileSaveAs1BeforeExecute(Sender: TObject);
var
s : string;
begin
s := ExtractFileName(FileOpen1.Dialog.FileName);
s := ChangeFileExt(s,'');
FileSaveAs1.Dialog.FileName := s;
end;
procedure TForm1.FileSaveAs1Update(Sender: TObject);
begin
FileSaveAs1.Enabled := l.file_version > 0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
l := TTRLevel.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
l.Free;
end;
end.
|
unit uSysMenu;
interface
uses
Menus, Forms, Windows, Classes, ShellAPI, DBClient, Dialogs, SysUtils, Controls, Messages,
uParamObject, uFactoryFormIntf;
type
TShowMDIEvent = procedure(Sender: TObject; ACaption: string; AFormIntf: IFormIntf) of object;
//记录每个创建窗体的信息
TFrmObj = class(TObject)
private
FFrmMDI: IFormIntf;
FCreateTime: TDateTime;
public
constructor Create(AFrm: IFormIntf);
destructor Destroy; override;
published
property FrmMDI: IFormIntf read FFrmMDI;
end;
TSysMenu = class(TObject)
private
FMainMenu: TMainMenu; //设置了ower时父类释放,子类也就释放了
FOwner: TForm;
FMDIClent: TWinControl; //MDI窗体显示的区域
FMenus: TstringList;
FOnShowMDI: TShowMDIEvent; //创建MDI窗体的时候回调此函数
function FindParent(var ASubMenu: TMenuItem; const AParentMenuId: string): Boolean;
procedure AddSeparators(const AParMenuId: string); {添加分割线}
procedure AddMenu(const AMenuId: string; {定义唯一的个menuid,方便寻找}
const Acaption: string; {acaption菜单标题}
const AParMenuId: string; {父菜单的id}
const AParamter: string; { 传入窗体的参数 多个参数以,(逗号)号隔开 1=a,2=b}
AMdlNo: Integer; {对应模块号}
AOnClick: TNotifyEvent; {FOnClick 对于特殊菜单的点击事件}
AShortKey: string = ''); {快捷键 添加方式:'Ctrl+W' 'Ctrl+Shift+Alt+S'}
procedure LoadMenu;
procedure GetParamList(const AParam: string; AList: TParamObject);
{菜单点击事件方法声明区}
procedure DefaultMethod(Sender: TObject); //默认点击菜单发生的事件
procedure TestIntfMethod(Sender: TObject); //测试接口,发布是可以删除
function GetCaption(AFromNo: Integer): string;
public
procedure CallFormClass(AFromNo: Integer; AParam: TParamObject); //打开窗体
function GetMainMenu: TMainMenu;
constructor Create(AOwner: TForm; AMDIClent: TWinControl);
destructor Destroy; override;
published
property OnShowMDI: TShowMDIEvent read FOnShowMDI write FOnShowMDI;
end;
implementation
uses uSysSvc, uOtherIntf, uTestdllInf, uMoudleNoDef, uDefCom, uVchTypeDef;
{ TSysMenu }
procedure TSysMenu.AddMenu(const AMenuId, Acaption, AParMenuId,
AParamter: string; AMdlNo: Integer; AOnClick: TNotifyEvent;
AShortKey: string);
var
tempMenu: TMenuItem;
begin
//这里使用对象自定义的属性,而没有专门封装一些属性,是为了节省内存空间类的抽象复杂度
tempMenu := TMenuItem.Create(FmainMenu);
with tempMenu do
begin
Name := AMenuId; //不能重复
Caption := Acaption;
if AParamter <> '' then
Hint := AParamter; //用Hint来记录Paramter
HelpContext := AMdlNo; //用HelpContext记录模块号
if Assigned(AOnClick) then
OnClick := AOnClick
else
begin
OnClick := DefaultMethod;
end;
if not FindParent(tempMenu, AParMenuId) then
begin
raise(SysService as IExManagement).CreateSysEx('对不起,加载菜单出错!');
end;
if AShortKey <> '' then
begin
ShortCut := TextToShortCut(AShortKey);
end;
end;
FMenus.AddObject(AMenuId, tempMenu);
end;
procedure TSysMenu.AddSeparators(const AParMenuId: string);
begin
end;
procedure TSysMenu.CallFormClass(AFromNo: Integer; AParam: TParamObject);
var
aCaption: string;
aFrm: IFormIntf;
begin
aFrm := (SysService as IFromFactory).GetFormAsFromNo(AFromNo, AParam, FMDIClent);
aCaption := GetCaption(AFromNo);
if aFrm.FrmShowStyle = fssShow then
begin
aFrm.FrmShow;
if Assigned(OnShowMDI) then OnShowMDI(Self, aCaption, aFrm);
end
else if aFrm.FrmShowStyle = fssShowModal then
begin
try
aFrm.FrmShowModal;
finally
aFrm.FrmFree();
end;
end
else if aFrm.FrmShowStyle = fssClose then
begin
aFrm.FrmFree();
end
else
begin
raise(SysService as IExManagement).CreateSysEx('没有找到<' + aCaption + '>窗体显示的方式!');
end;
end;
constructor TSysMenu.Create(AOwner: TForm; AMDIClent: TWinControl);
begin
FMainMenu := TMainMenu.Create(AOwner);
FOwner := AOwner;
FMDIClent := AMDIClent;
FMainMenu.AutoHotkeys := maManual;
FMenus := TStringList.Create;
LoadMenu;
end;
procedure TSysMenu.DefaultMethod(Sender: TObject);
var
aList: TParamObject;
sHelpId, HelpItem: string;
aFrm: IFormIntf;
begin
//子菜单项
if TMenuItem(Sender).Count = 0 then
begin
case TMenuItem(Sender).HelpContext of
fnMdlHelp_Calc: //计算器
ShellExecute(Application.Handle, '', 'Calc.exe', '', nil, SW_SHOW);
else
begin
aList := TParamObject.Create;
try
GetParamList(TMenuItem(Sender).Hint, aList);
CallFormClass(TMenuItem(Sender).HelpContext, aList);
finally
aList.Free;
end;
end;
end;
end;
end;
destructor TSysMenu.Destroy;
begin
FMenus.Free;
inherited;
end;
function TSysMenu.FindParent(var ASubMenu: TMenuItem;
const AParentMenuId: string): Boolean;
var
i: Integer;
begin
Result := False;
if not (AParentMenuId = '') then
begin
i := -1;
i := FMenus.IndexOf(AParentMenuId);
if i >= 0 then
begin
TMenuItem(FMenus.Objects[i]).Insert(TMenuItem(FMenus.Objects[i]).Count,
ASubMenu);
Result := True;
end;
end
else
begin
FmainMenu.Items.Add(ASubMenu);
Result := True;
end;
end;
function TSysMenu.GetCaption(AFromNo: Integer): string;
var
i: Integer;
aObjects: TObject;
begin
Result := '';
for i := 0 to FMenus.Count - 1 do
begin
aObjects := FMenus.Objects[i];
if Assigned(aObjects) then
begin
if TMenuItem(aObjects).HelpContext = AFromNo then
begin
Result := TMenuItem(aObjects).Caption;
Exit;
end;
end;
end;
end;
function TSysMenu.GetMainMenu: TMainMenu;
begin
if Assigned(FMainMenu) then
Result := FMainMenu
else
Result := nil;
end;
procedure TSysMenu.GetParamList(const AParam: string; AList: TParamObject);
var
tempStrings: TStrings;
i: Integer;
begin
try
if Aparam = '' then
begin
Exit;
end
else
begin
tempStrings := TStringList.Create;
try
tempStrings.CommaText := Aparam;
Alist.Clear;
//逗号分隔所产生的stringlist
for i := 0 to tempStrings.Count - 1 do
begin
Alist.Add(tempStrings.Names[i],
tempStrings.Values[tempStrings.Names[i]]); //参数名称定义
end;
finally
tempStrings.Free;
end;
end;
except
raise(SysService as IExManagement).CreateSysEx('菜单参数定义错误!');
end;
end;
procedure TSysMenu.LoadMenu;
procedure LoadMenuMember;
begin
AddMenu('m1000', '系统维护', '', '', 0, nil);
AddMenu('m10001000', '系统参数设置', 'm1000', '', 0, nil);
AddMenu('m100010001000', '加载包设置', 'm10001000', '', fnMdlLoadItemSet, nil);
AddMenu('m100010002000', '系统表格配置', 'm10001000', '', fnMdlBaseTbxCfg, nil);
AddMenu('m10002000', '系统重建', 'm1000', '', fnDialogReBuild, nil);
AddMenu('m10003000', '权限管理', 'm1000', '', 0, nil);
AddMenu('m1000300010000', '角色管理', 'm10003000', '', fnMdlLimitRole, nil);
AddMenu('m1000300020000', '用户管理', 'm10003000', '', fnDialogLimitSet, nil);
AddMenu('m10004000', '流程设置', 'm1000', '', fnFlow, nil);
AddMenu('m10001111', '测试接口', 'm1000', '', 0, TestIntfMethod);
AddMenu('m2000', '基本资料', '', '', 0, nil);
AddMenu('m20001000', '商品信息', 'm2000', 'Mode=P', fnMdlBasePtypeList, nil);
AddMenu('m20002000', '单位信息', 'm2000', 'Mode=B', fnMdlBaseBtypeList, nil);
AddMenu('m20003000', '职员信息', 'm2000', 'Mode=E', fnMdlBaseEtypeList, nil);
AddMenu('m20004000', '仓库信息', 'm2000', 'Mode=K', fnMdlBaseKtypeList, nil);
AddMenu('m20005000', '-', 'm2000', '', 0, nil);
AddMenu('m20006000', '部门信息', 'm2000', 'Mode=D', fnMdlBaseDtypeList, nil);
AddMenu('m20007000', '-', 'm2000', '', 0, nil);
AddMenu('m20008000', '期初建账', 'm2000', '', 0, nil);
AddMenu('m200080001000', '期初库存商品', 'm20008000', '', fnMdlStockGoodsIni, nil);
AddMenu('m200080002000', '期初应收应付', 'm20008000', '', 0, nil);
AddMenu('m20009000', '期初建账..开账', 'm2000', '', fnDialogInitOver, nil);
AddMenu('m3000', '业务录入', '', '', 0, nil);
AddMenu('m30001000', '进货订单', 'm3000', 'Vchtype=' + IntToStr(VchType_Order_Buy), fnMdlBillOrderBuy, nil);
AddMenu('m30002000', '进货单', 'm3000', 'Vchtype=' + IntToStr(VchType_Buy), fnMdlBillBuy, nil);
AddMenu('m30003000', '付款单', 'm3000', 'Vchtype=' + IntToStr(VchType_Payment), fnMdlBillPayment, nil);
AddMenu('m30004000', '-', 'm3000', '', 0, nil);
AddMenu('m30005000', '销售订单', 'm3000', 'Vchtype=' + IntToStr(VchType_Order_Sale), fnMdlBillOrderSale, nil);
AddMenu('m30006000', '销售单', 'm3000', 'Vchtype=' + IntToStr(VchType_Sale), fnMdlBillSale, nil);
AddMenu('m30007000', '收款单', 'm3000', 'Vchtype=' + IntToStr(VchType_Gathering), fnMdlBillGathering, nil);
AddMenu('m30008000', '-', 'm3000', '', 0, nil);
AddMenu('m30009000', '调拨单', 'm3000', 'Vchtype=' + IntToStr(VchType_Allot), fnMdlBillAllot, nil);
AddMenu('m30010000', '仓库盘点', 'm3000', '', fnMdlCheckGoods, nil);
AddMenu('m4000', '数据查询', '', '', 0, nil);
AddMenu('m40001000', '库存状况', 'm4000', '', fnMdlReportGoods, nil);
AddMenu('m40002000', '进货订单查询', 'm4000', 'Mode=B', fnMdlReportOrderBuy, nil);
AddMenu('m40003000', '进货单查询', 'm4000', 'Mode=B', fnMdlReportBuy, nil);
AddMenu('m40004000', '销售订单查询', 'm4000', 'Mode=S', fnMdlReportOrderSale, nil);
AddMenu('m40005000', '销售单查询', 'm4000', 'Mode=S', fnMdlReportSale, nil);
AddMenu('m5000', '辅助功能', '', '', 0, nil);
AddMenu('m50000001', '我的审核', 'm5000', '', fnMdlMyFlow, nil);
AddMenu('m9000', '帮助', '', '', 0, nil);
AddMenu('m90001000', '在线帮助', 'm9000', '', fnMdlHelp_Online, nil);
AddMenu('m90002000', '计算器', 'm9000', '', fnMdlHelp_Calc, nil, 'F5');
end;
begin
//初始化顺序时一定要先定义了主菜单,然后再加次级菜单
//强调: 顺序不能乱
{Mid默认对应为模块编号对于没有模块的父级菜单采用如下的编码方式
以字母m开头,
每一级菜单以四位字符串表示
子菜单的第一个mid从1000开始命名,然后递增 1000 2000 3000 }
{使用tab控制符,美观界面,方便查找}
// if gobjSys.CompilerOption.VerNoIndustry = cnVernoMember then
begin
//通用版菜单实现区
LoadMenuMember();
end;
end;
procedure TSysMenu.TestIntfMethod(Sender: TObject);
var
aExInf: IExManagement;
aMsgBox: IMsgBox;
aTestdllInf: ITestdll;
nIntfCount, I: Integer;
pIntfTable: PInterfaceTable;
aStr: string;
begin
// aExInf := SysService as IExManagement;
// raise aExInf.CreateSysEx('多岁的');
aMsgBox := SysService as IMsgBox;
aMsgBox.MsgBox('IMsgBox');
aTestdllInf := SysService as ITestdll;
aTestdllInf.TestAAA('ITestdll');
pIntfTable := FOwner.GetInterfaceTable;
nIntfCount := pintfTable.EntryCount;
aStr := '';
if nIntfCount > 0 then
begin
for I := 0 to nIntfCount - 1 do
begin
//如果不写GUID的话 默认的是零,打印出来一行0
aStr := aStr + IntToStr(I) + ':' + GUIDToString(pIntfTable.Entries[I].IID);
end;
end;
ShowMessage(aStr);
end;
{ TFrmObj }
constructor TFrmObj.Create(AFrm: IFormIntf);
begin
FFrmMDI := AFrm;
FCreateTime := Now;
end;
destructor TFrmObj.Destroy;
begin
inherited;
end;
end.
|
unit wfsU;
interface
uses
System.Types,
System.Classes,
System.SysUtils,
System.SyncObjs,
Winapi.Windows,
UnitDBDeclare,
ExplorerTypes,
uGOM,
uMemory,
uTime,
uThreadEx,
uDBThread,
uThreadForm,
uInterfaces,
uLockedFileNotifications;
type
WFSError = class(Exception);
const
WathBufferSize = 64 * 1024;
type
TWFS = class(TDBThread)
private
FName: string;
FFilter: Cardinal;
FSubTree: Boolean;
FInfoCallback: TWatchFileSystemCallback;
FWatchHandle: THandle;
FWatchBuf: array [0 .. WathBufferSize - 1] of Byte;
FOverLapp: TOverlapped;
FPOverLapp: POverlapped;
FBytesWrite: DWORD;
FCompletionPort: THandle;
FNumBytes: DWORD;
FOldFileName: string;
InfoCallback: TInfoCallBackDirectoryChangedArray;
FOnNeedClosing: TThreadExNotify;
FOnThreadClosing: TNotifyEvent;
FPublicOwner: TObject;
FCID: TGUID;
FWatchType: TDirectoryWatchType;
function CreateDirHandle(ADir: string): THandle;
procedure WatchEvent;
procedure HandleEvent;
protected
procedure Execute; override;
procedure DoCallBack;
procedure TerminateWatch;
procedure DoClosingEvent;
public
constructor Create(PublicOwner: TObject; pName: string;
WatchType: TDirectoryWatchType; pSubTree: boolean; pInfoCallback: TWatchFileSystemCallback;
OnNeedClosing: TThreadExNotify; OnThreadClosing: TNotifyEvent; CID: TGUID);
destructor Destroy; override;
end;
TWachDirectoryClass = class(TObject)
private
WFS: TWFS;
FOnDirectoryChanged: TNotifyDirectoryChangeW;
FCID: TGUID;
FOwner: TObject;
FWatcherCallBack: IDirectoryWatcher;
FWatchType: TDirectoryWatchType;
{ Start monitoring file system
Parametrs:
pName - Directory name for monitoring
pFilter - Monitoring type ( FILE_NOTIFY_XXX )
pSubTree - Watch sub directories
pInfoCallback - callback porcedure, this procedure called with synchronization for main thread }
procedure StartWatch(PName: string; WatchType: TDirectoryWatchType; PSubTree: Boolean;
PInfoCallback: TWatchFileSystemCallback; CID: TGUID);
procedure CallBack(WatchType: TDirectoryWatchType; PInfo: TInfoCallBackDirectoryChangedArray);
procedure OnNeedClosing(Sender: TObject; StateID: TGUID);
procedure OnThreadClosing(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
procedure Start(Directory: string; Owner: TObject; WatcherCallBack: IDirectoryWatcher; CID: TGUID;
WatchSubTree: Boolean; WatchType: TDirectoryWatchType = dwtBoth);
procedure StopWatch;
procedure UpdateStateID(NewStateID: TGUID);
property OnDirectoryChanged: TNotifyDirectoryChangeW read FOnDirectoryChanged write FOnDirectoryChanged;
end;
TIoCompletionManager = class(TObject)
private
FList: TList;
FCounter: Cardinal;
FSync: TCriticalSection;
public
constructor Create;
destructor Destroy; override;
class function Instance: TIoCompletionManager;
function CreateIoCompletion(Handle: THandle; var CompletionKey: NativeUInt) : THandle;
procedure FinishIoCompletion(CompletionPort: THandle);
procedure GetQueuedCompletionStatus(CompletionPort: THandle;
var lpNumberOfBytesTransferred: DWORD;
var lpCompletionKey: NativeUInt;
var lpOverlapped: POverlapped);
end;
implementation
{uses
ExplorerUnit, uManagerExplorer; }
var
OM: TManagerObjects = nil;
FSync: TCriticalSection = nil;
FIoCompletionManager: TIoCompletionManager = nil;
procedure TWachDirectoryClass.CallBack(WatchType: TDirectoryWatchType; PInfo: TInfoCallBackDirectoryChangedArray);
begin
if GOM.IsObj(FOwner) then
FWatcherCallBack.DirectoryChanged(Self, FCID, PInfo, FWatchType)
end;
constructor TWachDirectoryClass.Create;
begin
WFS := nil;
OM.AddObj(Self);
end;
destructor TWachDirectoryClass.Destroy;
begin
OM.RemoveObj(Self);
inherited;
end;
procedure TWachDirectoryClass.OnNeedClosing(Sender: TObject; StateID : TGUID);
begin
if GOM.IsObj(FOwner) then
FWatcherCallBack.TerminateWatcher(Self, StateID, WFS.FName);
end;
procedure TWachDirectoryClass.OnThreadClosing(Sender: TObject);
begin
//empty stub
end;
procedure TWachDirectoryClass.Start(Directory: string; Owner: TObject; WatcherCallBack: IDirectoryWatcher; CID: TGUID; WatchSubTree: Boolean; WatchType: TDirectoryWatchType);
begin
TW.I.Start('TWachDirectoryClass.Start');
FCID := CID;
FOwner := Owner;
FWatcherCallBack := WatcherCallBack;
FWatchType := WatchType;
FSync.Enter;
try
StartWatch(Directory, FWatchType, WatchSubTree, CallBack, CID);
finally
FSync.Leave;
end;
end;
procedure TWachDirectoryClass.StartWatch(PName: string; WatchType: TDirectoryWatchType; PSubTree: Boolean;
PInfoCallback: TWatchFileSystemCallback; CID : TGUID);
begin
TW.I.Start('TWFS.Create');
WFS := TWFS.Create(Self, PName, WatchType, pSubTree, PInfoCallback, OnNeedClosing, OnThreadClosing, CID);
end;
procedure TWachDirectoryClass.StopWatch;
var
Port : THandle;
begin
Port := 0;
FSync.Enter;
try
TW.I.Start('TWachDirectoryClass.StopWatch');
if OM.IsObj(WFS) then
begin
Port := WFS.FCompletionPort;
WFS.Terminate;
WFS := nil;
end;
finally
FSync.Leave;
end;
if Port <> 0 then
begin
TW.I.Start('StopWatch.CLOSE = ' + IntToStr(Port));
TIoCompletionManager.Instance.FinishIoCompletion(Port);
end;
end;
procedure TWachDirectoryClass.UpdateStateID(NewStateID: TGUID);
begin
FSync.Enter;
try
FCID := NewStateID;
TW.I.Start('TWachDirectoryClass.StopWatch');
if OM.IsObj(WFS) then
WFS.FCID := NewStateID;
finally
FSync.Leave;
end;
end;
constructor TWFS.Create(PublicOwner: TObject; PName: string; WatchType: TDirectoryWatchType; PSubTree: Boolean; PInfoCallback: TWatchFileSystemCallback;
OnNeedClosing: TThreadExNotify; OnThreadClosing: TNotifyEvent; CID: TGUID);
begin
TW.I.Start('TWFS.Create');
inherited Create(nil, False);
TW.I.Start('TWFS.Created');
OM.AddObj(Self);
FPublicOwner := PublicOwner;
FName := IncludeTrailingBackslash(pName);
FWatchType := WatchType;
FFilter := 0;
if (FWatchType = dwtBoth) or (FWatchType = dwtFiles) then
FFilter := FFilter + FILE_NOTIFY_CHANGE_FILE_NAME + FILE_NOTIFY_CHANGE_SIZE + FILE_NOTIFY_CHANGE_CREATION + FILE_NOTIFY_CHANGE_LAST_WRITE;
if (FWatchType = dwtBoth) or (FWatchType = dwtDirectories) then
FFilter := FFilter + FILE_NOTIFY_CHANGE_DIR_NAME;
FSubTree := pSubTree;
FOldFileName := EmptyStr;
ZeroMemory(@FOverLapp, SizeOf(TOverLapped));
FPOverLapp := @FOverLapp;
ZeroMemory(@FWatchBuf, SizeOf(FWatchBuf));
FInfoCallback := PInfoCallback;
FOnNeedClosing := OnNeedClosing;
FOnThreadClosing := OnThreadClosing;
FCID := CID;
end;
destructor TWFS.Destroy;
begin
FSync.Enter;
try
TW.I.Start('TWFS.Destroy');
TW.I.Start('Destroy.CLOSE = ' + IntToStr(FCompletionPort));
TIoCompletionManager.Instance.FinishIoCompletion(FCompletionPort);
CloseHandle(FWatchHandle);
CloseHandle(FCompletionPort);
inherited;
finally
FSync.Leave;
end;
end;
function TWFS.CreateDirHandle(aDir: string): THandle;
var
Dir: string;
begin
Dir := ExcludeTrailingBackslash(aDir);
//drive should be like c:\
if Length(Dir) = 2 then
Dir := IncludeTrailingBackslash(Dir);
Result := CreateFile(PChar(Dir),
FILE_LIST_DIRECTORY, FILE_SHARE_READ + FILE_SHARE_DELETE + FILE_SHARE_WRITE,
nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or FILE_FLAG_OVERLAPPED, 0);
TW.I.Start('FWatchHandle = {0}, Error = {1}', [IntToStr(Result), GetLastError()]);
end;
procedure TWFS.Execute;
begin
inherited;
TW.I.Start('TWFS.Execute - START');
FreeOnTerminate := True;
FWatchHandle := CreateDirHandle(FName);
WatchEvent;
Synchronize(DoClosingEvent);
OM.RemoveObj(Self);
TW.I.Start('TWFS.Execute - END');
end;
procedure TWFS.HandleEvent;
var
FInfoCallback: TInfoCallback;
Ptr: Pointer;
FileName: PWideChar;
NoMoreFilesFound, FileSkipped: Boolean;
begin
SetLength(InfoCallback, 0);
Ptr := @FWatchBuf[0];
repeat
GetMem(FileName, PFileNotifyInformation(Ptr).FileNameLength + 2);
try
ZeroMemory(FileName, PFileNotifyInformation(Ptr).FileNameLength + 2);
LstrcpynW(FileName, PFileNotifyInformation(Ptr).FileName, PFileNotifyInformation(Ptr).FileNameLength div 2 + 1);
FileSkipped := False;
NoMoreFilesFound := False;
if NoMoreFilesFound then
Break
else if FileSkipped then
Continue;
FInfoCallback.Action := PFileNotifyInformation(Ptr).Action;
if (FInfoCallback.Action = 0) and (FileName = '') and not DirectoryExists(FName + FileName) then
begin
TW.I.Start('WATCHER - CLOSE, file = "' + FName + FileName + '", BytesWrite = ' + IntToStr(FBytesWrite)
+ ' hEvent = ' + IntToStr(FPOverLapp.hEvent)
+ ' Internal = ' + IntToStr(FPOverLapp.Internal)
+ ' InternalHigh = ' + IntToStr(FPOverLapp.InternalHigh)
+ ' Offset = ' + IntToStr(FPOverLapp.Offset)
+ ' OffsetHigh = ' + IntToStr(FPOverLapp.OffsetHigh));
Synchronize(TerminateWatch);
Terminate;
Exit;
end;
FInfoCallback.NewFileName := FName + FileName;
case PFileNotifyInformation(Ptr).Action of
FILE_ACTION_RENAMED_OLD_NAME:
FOldFileName := FName + FileName;
FILE_ACTION_RENAMED_NEW_NAME:
FInfoCallback.OldFileName := FOldFileName;
end;
if PFileNotifyInformation(Ptr).Action <> FILE_ACTION_RENAMED_OLD_NAME then
begin
SetLength(InfoCallback, Length(InfoCallback) + 1);
InfoCallback[Length(InfoCallback) - 1] := FInfoCallback;
end;
finally
FreeMem(FileName);
end;
if PFileNotifyInformation(Ptr).NextEntryOffset = 0 then
Break
else
Inc(NativeUInt(Ptr), PFileNotifyInformation(Ptr).NextEntryOffset);
until Terminated;
Synchronize(DoCallBack);
end;
procedure TWFS.WatchEvent;
var
CompletionKey: NativeUInt;
begin
FCompletionPort := TIoCompletionManager.Instance.CreateIoCompletion(FWatchHandle, CompletionKey);
TW.I.Start('FCompletionPort = ' + IntToStr(FCompletionPort));
ZeroMemory(@FWatchBuf, SizeOf(FWatchBuf));
if not ReadDirectoryChanges(FWatchHandle, @FWatchBuf, SizeOf(FWatchBuf), FSubTree,
FFilter, @FBytesWrite, @FOverLapp, nil) then
begin
//unable to watch - close thread
Terminate;
end else
begin
while not Terminated do
begin
TIoCompletionManager.Instance.GetQueuedCompletionStatus(FCompletionPort, FNumBytes, CompletionKey, FPOverLapp);
if CompletionKey <> 0 then
begin
TW.I.Start('CompletionKey <> 0, BytesWrite = ' + IntToStr(FBytesWrite)
+ ' CompletionKey = ' + IntToStr(CompletionKey)
+ ' FCompletionPort = ' + IntToStr(FCompletionPort)
+ ' hEvent = ' + IntToStr(FPOverLapp.hEvent)
+ ' Internal = ' + IntToStr(FPOverLapp.Internal)
+ ' InternalHigh = ' + IntToStr(FPOverLapp.InternalHigh)
+ ' Offset = ' + IntToStr(FPOverLapp.Offset)
+ ' OffsetHigh = ' + IntToStr(FPOverLapp.OffsetHigh));
HandleEvent;
if not Terminated then
begin
ZeroMemory(@FWatchBuf, SizeOf(FWatchBuf));
FBytesWrite := 0;
ReadDirectoryChanges(FWatchHandle, @FWatchBuf, SizeOf(FWatchBuf), FSubTree, FFilter,
@FBytesWrite, @FOverLapp, nil);
end;
end else
Terminate;
end
end
end;
procedure TWFS.DoCallBack;
begin
if OM.IsObj(FPublicOwner) then
FInfoCallback(FWatchType, InfoCallback);
end;
procedure TWFS.TerminateWatch;
begin
if OM.IsObj(FPublicOwner) then
FOnNeedClosing(Self, FCID);
end;
procedure TWFS.DoClosingEvent;
begin
if OM.IsObj(FPublicOwner) then
FOnThreadClosing(Self);
end;
{ TIoCompletionManager }
constructor TIoCompletionManager.Create;
begin
FSync := TCriticalSection.Create;
FList := TList.Create;
FCounter := 0;
end;
function TIoCompletionManager.CreateIoCompletion(Handle: THandle; var CompletionKey: NativeUInt): THandle;
begin
FSync.Enter;
try
Inc(FCounter);
CompletionKey := FCounter;
Result := CreateIoCompletionPort(Handle, 0, CompletionKey, 0);
FList.Add(Pointer(Result));
finally
FSync.Leave;
end;
end;
destructor TIoCompletionManager.Destroy;
begin
F(FList);
F(FSync);
end;
procedure TIoCompletionManager.FinishIoCompletion(CompletionPort : THandle);
begin
FSync.Enter;
try
if FList.IndexOf(Pointer(CompletionPort)) > -1 then
begin
FList.Remove(Pointer(CompletionPort));
PostQueuedCompletionStatus(CompletionPort, 0, 0, nil);
end;
finally
FSync.Leave;
end;
end;
procedure TIoCompletionManager.GetQueuedCompletionStatus(
CompletionPort: THandle; var lpNumberOfBytesTransferred: DWORD;
var lpCompletionKey: NativeUInt; var lpOverlapped: POverlapped);
begin
Winapi.Windows.GetQueuedCompletionStatus(CompletionPort,
lpNumberOfBytesTransferred,
lpCompletionKey, lpOverlapped, INFINITE);
end;
class function TIoCompletionManager.Instance: TIoCompletionManager;
begin
if FIoCompletionManager = nil then
FIoCompletionManager := TIoCompletionManager.Create;
Result := FIoCompletionManager;
end;
initialization
OM := TManagerObjects.Create;
FSync := TCriticalSection.Create;
finalization
F(FSync);
F(OM);
F(FIoCompletionManager);
end.
|
{=====================================================================================
Copyright (C) combit GmbH
--------------------------------------------------------------------------------------
File : rtfform.pas, rtfform.dfm, rtfdemo.dpr
Module : List & Label rtf sample
Descr. : D: Dieses Beispiel demonstriert die Verwendung von RTF-Variablen
US: This example demonstrates how to deal with RTF-variables.
======================================================================================}
unit rtfform;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, L28, cmbtll28, Registry;
type
TForm1 = class(TForm)
LoadButton: TButton;
DesignButton: TButton;
PreviewButton: TButton;
PrintButton: TButton;
OpenDialog1: TOpenDialog;
Label1: TLabel;
Label2: TLabel;
LL: TL28_;
RTF: TLL28RTFObject;
procedure LoadButtonClick(Sender: TObject);
procedure DesignButtonClick(Sender: TObject);
procedure PreviewButtonClick(Sender: TObject);
procedure PrintButtonClick(Sender: TObject);
procedure LLDefineVariables(Sender: TObject; UserData: Integer;
IsDesignMode: Boolean; var Percentage: Integer;
var IsLastRecord: Boolean; var EventResult: Integer);
procedure FormCreate(Sender: TObject);
private
workingPath: String;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.LoadButtonClick(Sender: TObject);
var Buffer: TMemoryStream;
begin
{D: Dateiauswahldialog öffnen und RTF-Control füllen}
{US: execute file open dialog and fill RTF-Control }
OpenDialog1.InitialDir := workingPath;
If OpenDialog1.execute then
begin
Buffer:=TMemoryStream.create;
Buffer.LoadFromFile(OpenDialog1.FileName);
RTF.Text:=String(PAnsiChar(Buffer.Memory));
PrintButton.enabled:=true;
PreviewButton.enabled:=true;
DesignButton.enabled:=true;
Buffer.Free;
end;
end;
procedure TForm1.DesignButtonClick(Sender: TObject);
begin
{D: Designer für Datei rtf.lbl aufrufen }
{US: call designer for file rtf.lbl }
LL.Design(0,handle,'Design Label', LL_PROJECT_LABEL,
workingPath + 'rtf.lbl', true, true);
end;
procedure TForm1.PreviewButtonClick(Sender: TObject);
begin
{D: Projekt 'rtf.lbl als Vorschau ausdrucken}
{US: Print project 'rtf.lbl' to preview }
LL.Print(0,LL_PROJECT_LABEL, workingPath + 'rtf.lbl', true, LL_PRINT_PREVIEW,
LL_BOXTYPE_STDWAIT,handle,'Print labels to preview', true,
'');
end;
procedure TForm1.PrintButtonClick(Sender: TObject);
begin
{D: Projekt 'rtf.lbl auf Drucker/Export ausdrucken}
{US: Print project 'rtf.lbl' to printer/export }
LL.Print(0,LL_PROJECT_LABEL, workingPath + 'rtf.lbl', true, LL_PRINT_EXPORT,
LL_BOXTYPE_STDWAIT,handle,'Print labels to preview', true,
'');
end;
procedure TForm1.FormCreate(Sender: TObject);
var registry: TRegistry;
var regKeyPath: String;
var tmp: String;
begin
// D: Datenbankpfad auslesen
// US: Read database path
registry := TRegistry.Create();
registry.RootKey := HKEY_CURRENT_USER;
regKeyPath := 'Software\combit\cmbtll\';
if registry.KeyExists(regKeyPath) then
begin
if registry.OpenKeyReadOnly(regKeyPath) then
begin
tmp := registry.ReadString('LL' + IntToStr(LL.LlGetVersion(LL_VERSION_MAJOR)) + 'SampleDir');
if (tmp[Length(tmp)] = '\') then
begin
workingPath := tmp + 'Delphi\BDE (Legacy)\Samples\RTF Example\';
end
else
workingPath := tmp + '\Delphi\BDE (Legacy)\Samples\RTF Example\';
registry.CloseKey();
end;
end;
registry.Free();
end;
procedure TForm1.LLDefineVariables(Sender: TObject; UserData: Integer;
IsDesignMode: Boolean; var Percentage: Integer;
var IsLastRecord: Boolean; var EventResult: Integer);
{D: Diese Routine wird von List & Label aufgerufen, um den Inhalt des
RichEdit-Controls zu übergeben
US: This routine is called by List & Label to hand over the contents of
the RichEdit-Control }
begin
LL.LlDefineVariableExt('RTF-Field', RTF.Text,
LL_RTF);
{D: Nur eine RTF-Variable in diesem Beispiel vorhanden}
{US: only one RTF-variable is used for this example }
if not (IsDesignMode) then
IsLastRecord:=true;
end;
end.
|
unit htStyle;
interface
uses
Classes, Messages, SysUtils, Types, Graphics,
htPersistBase, htStyleList, htPicture;
{ThMessages, ThStyleList, ThPicture;}
type
ThtStyleBase = class(ThtPersistBase);
//
ThtFontWeight = ( fwDefault, fwNormal, fwBold );
ThtFontSizeRelEnum = ( fsDefault, fs_1_XxSmall, fs_2_XSmall, fs_3_Small,
fs_4_Medium, fs_5_Large, fs_6_XLarge, fs_7_XxLarge );
ThtFontSizeRel = string;
ThtFontDecorations = ( fdDefault, fdInherit, fdNone, fdUnderline,
fdOverline, fdLineThrough, fdBlink );
ThtFontDecoration = set of ThtFontDecorations;
ThtFontStyle = ( fstDefault, fstInherit, fstNormal, fstItalic,
fstOblique );
//
//:$ Describes CSS font properties.
ThtFont = class(ThtStyleBase)
private
FFontSizeRel: ThtFontSizeRel;
FFontFamily: TFontName;
FFontWeight: ThtFontWeight;
FFontSizePx: Integer;
FFontSizePt: Integer;
FFontColor: TColor;
FFontDecoration: ThtFontDecoration;
FFontStyle: ThtFontStyle;
FDefaultFontPx: Integer;
FDefaultFontFamily: string;
protected
function GetFontDecorationValue: string;
function GetRelFontSize: Integer;
function GetSizeValue: string;
procedure SetDefaultFontFamily(const Value: string);
procedure SetDefaultFontPx(const Value: Integer);
procedure SetFontColor(const Value: TColor);
procedure SetFontFamily(const Value: TFontName);
procedure SetRelFontSize(const Value: ThtFontSizeRel);
procedure SetFontWeight(const Value: ThtFontWeight);
procedure SetFontSizePx(const Value: Integer);
procedure SetFontSizePt(const Value: Integer);
procedure SetFontDecoration(const Value: ThtFontDecoration);
procedure SetFontStyle(const Value: ThtFontStyle);
public
//:$ Copy all properties from another style instance.
procedure Assign(Source: TPersistent); override;
constructor Create;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: ThtStyleList);
//:$ Converts a ThtFont to a TFont.
procedure ToFont(inFont: TFont);
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inFont: ThtFont);
public
property DefaultFontFamily: string read FDefaultFontFamily write SetDefaultFontFamily;
property DefaultFontPx: Integer read FDefaultFontPx write SetDefaultFontPx;
//:$ Font size, in points. Not published to encourage use of 'pixel'
//:: size instead. Pixel sizes translate better in browsers.
property FontSizePt: Integer read FFontSizePt write SetFontSizePt
default 0;
published
//:$ Font color.
property FontColor: TColor read FFontColor write SetFontColor
default clNone;
//:$ Font decoration.
property FontDecoration: ThtFontDecoration read FFontDecoration
write SetFontDecoration default [ fdDefault ];
//:$ Font family (face).
property FontFamily: TFontName read FFontFamily write SetFontFamily;
//:$ Font size, in pixels.
property FontSizePx: Integer read FFontSizePx write SetFontSizePx
default 0;
//:$ Relative font size.
property FontSizeRel: ThtFontSizeRel read FFontSizeRel
write SetRelFontSize;
//:$ Font style.
property FontStyle: ThtFontStyle read FFontStyle write SetFontStyle
default fstDefault;
//:$ Font weight.
property FontWeight: ThtFontWeight read FFontWeight
write SetFontWeight default fwDefault;
end;
//
//:$ Describes CSS background properties.
//:: Usually available as a member of a ThtStyle.
ThtBackground = class(ThtStyleBase)
private
//FOwner: TComponent;
FPicture: ThtPicture;
protected
procedure SetPicture(const Value: ThtPicture);
protected
procedure PictureChange(inSender: TObject);
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ Copy all properties from another style instance.
procedure Assign(Source: TPersistent); override;
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inBackground: ThtBackground);
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: ThtStyleList);
published
//$ Optional picture to be used as background.
//:: Background pictures are tiled to fill the style object.
property Picture: ThtPicture read FPicture write SetPicture;
end;
//
ThtBorderProp = ( bpWidth, bpStyle, bpColor);
ThtBorderStyle = ( bsDefault, bsInherit, bsNone, bsHidden, bsDotted,
bsDashed, bsSolidBorder, bsGroove, bsRidge, bsInset, bsOutset, bsDouble );
ThtBorderSide = ( bsAll, bsLeft, bsTop, bsRight, bsBottom );
//
//:$ Describes a CSS border.
//:: Usually available as a member of a ThtBorders object.
ThtBorder = class(ThtStyleBase)
private
FBorderColor: TColor;
FBorderPrefix: string;
FBorderSide: ThtBorderSide;
FBorderStyle: ThtBorderStyle;
FBorderWidth: string;
FDefaultBorderPixels: Integer;
FOwnerStyle: ThtStyleBase;
protected
function CanCompoundStyle: Boolean;
function GetBorderWidthValue: string;
procedure SetBorderColor(const Value: TColor);
procedure SetBorderStyle(const Value: ThtBorderStyle);
procedure SetBorderWidth(const Value: string);
public
constructor Create(inOwner: ThtStyleBase; inSide: ThtBorderSide);
function BorderVisible: Boolean; virtual;
function GetBorderPixels: Integer; overload;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
procedure Change; override;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: ThtStyleList);
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inBorder: ThtBorder);
procedure Assign(Source: TPersistent); override;
public
property BorderSide: ThtBorderSide read FBorderSide write FBorderSide;
property DefaultBorderPixels: Integer read FDefaultBorderPixels
write FDefaultBorderPixels;
published
property BorderWidth: string read FBorderWidth write SetBorderWidth;
property BorderColor: TColor read FBorderColor write SetBorderColor
default clDefault;
property BorderStyle: ThtBorderStyle read FBorderStyle
write SetBorderStyle default bsDefault;
end;
//
//:$ Describes CSS border properties.
//:: Aggregates ThtBorder objects. Usually available as a member of a
//:: ThtStyle.
ThtBorderDetail = class(ThtStyleBase)
private
FBorderLeft: ThtBorder;
FBorderTop: ThtBorder;
FBorderRight: ThtBorder;
FBorderBottom: ThtBorder;
protected
procedure SetBorderBottom(const Value: ThtBorder);
procedure SetBorderLeft(const Value: ThtBorder);
procedure SetBorderRight(const Value: ThtBorder);
procedure SetBorderTop(const Value: ThtBorder);
procedure SetDefaultBorderPixels(inPixels: Integer);
public
constructor Create(inOwnerStyle: ThtStyleBase);
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function BorderVisible: Boolean;
function GetBorder(inSide: ThtBorderSide): ThtBorder;
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inDetail: ThtBorderDetail);
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: ThtStyleList);
public
property DefaultBorderPixels: Integer write SetDefaultBorderPixels;
published
property BorderLeft: ThtBorder read FBorderLeft write SetBorderLeft;
property BorderRight: ThtBorder read FBorderRight
write SetBorderRight;
property BorderTop: ThtBorder read FBorderTop write SetBorderTop;
property BorderBottom: ThtBorder read FBorderBottom
write SetBorderBottom;
end;
//
//:$ Describes CSS border properties.
//:: Aggregates ThtBorder objects. Usually available as a member of a
//:: ThtStyle.
ThtBorders = class(ThtBorder)
private
FEdges: ThtBorderDetail;
protected
procedure SetEdges(const Value: ThtBorderDetail);
procedure SetDefaultBorderPixels(inPixels: Integer);
public
constructor Create;
destructor Destroy; override;
//procedure Change; override;
function BorderVisible: Boolean; override;
function GetBorderColor(inSide: ThtBorderSide): TColor;
function GetBorderStyle(inSide: ThtBorderSide): ThtBorderStyle;
function GetBorderPixels(inSide: ThtBorderSide): Integer; overload;
procedure Assign(Source: TPersistent); override;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: ThtStyleList);
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inBox: ThtBorders);
public
property DefaultBorderPixels: Integer write SetDefaultBorderPixels;
published
property Edges: ThtBorderDetail read FEdges
write SetEdges;
end;
//
ThtPadDetail = class(ThtStyleBase)
private
FOwnerStyle: ThtStyleBase;
FPadLeft: Integer;
FPadBottom: Integer;
FPadTop: Integer;
FPadRight: Integer;
protected
procedure SetPadding(const Value: Integer);
procedure SetPadBottom(const Value: Integer);
procedure SetPadLeft(const Value: Integer);
procedure SetPadRight(const Value: Integer);
procedure SetPadTop(const Value: Integer);
public
constructor Create(inOwnerStyle: ThtStyleBase);
procedure Change; override;
//:$ Determine if any padding has been set.
//:: Returns true if any of the padding properties are non-zero.
function HasPadding: Boolean;
//:$ Return the total width of padding.
//:: Returns PadLeft + PadRight.
function PadWidth: Integer;
//:$ Return the total height of padding.
//:: Returns PadTop + PadBottom.
function PadHeight: Integer;
//:$ Copy all properties from another style instance.
procedure Assign(Source: TPersistent); override;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: ThtStyleList);
//:$ Add attribute values to an HTML node.
//:: Adds the attribute values for the style class to the list of
//:: style attributes maintained by the node.
//procedure Stylize(inNode: ThtHtmlNode);
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inPad: ThtPadDetail);
public
property Padding: Integer write SetPadding;
published
property PadLeft: Integer read FPadLeft write SetPadLeft default 0;
property PadRight: Integer read FPadRight write SetPadRight default 0;
property PadTop: Integer read FPadTop write SetPadTop default 0;
property PadBottom: Integer read FPadBottom write SetPadBottom default 0;
end;
//
//:$ Describes CSS padding properties.
//:: Usually available as a member of a ThtStyle.
ThtPadding = class(ThtStyleBase)
private
FPadding: Integer;
FPaddingDetails: ThtPadDetail;
protected
procedure SetPadding(const Value: Integer);
procedure SetPaddingDetails(const Value: ThtPadDetail);
public
constructor Create;
destructor Destroy; override;
//:$ Copy all properties from another style instance.
procedure Assign(Source: TPersistent); override;
procedure Change; override;
//:$ Determine if any padding has been set.
//:: Returns true if any of the padding properties are non-zero.
function HasPadding: Boolean;
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inPad: ThtPadding);
//:$ Returns formatted style attribute.
//:: InlineAttribute returns a style attribute formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: ThtStyleList);
function PadBottom: Integer;
//:$ Return the total height of padding.
//:: Returns PadTop + PadBottom.
function PadHeight: Integer;
function PadLeft: Integer;
function PadRight: Integer;
function PadTop: Integer;
//:$ Return the total width of padding.
//:: Returns PadLeft + PadRight.
function PadWidth: Integer;
published
property Padding: Integer read FPadding write SetPadding default 0;
property PaddingDetails: ThtPadDetail read FPaddingDetails
write SetPaddingDetails;
end;
//
//:$ ThtStyle combines various style objects. Commonly used as
//:$ a property in objects needing style information.
ThtStyle = class(ThtStyleBase)
private
FBackground: ThtBackground;
FBorders: ThtBorders;
FColor: TColor;
FCursor: string;
FExtraStyles: string;
FFont: ThtFont;
FName: string;
//FOverflow: ThtOverflow;
FOwner: TComponent;
FPadding: ThtPadding;
FParentColor: Boolean;
FParentFont: Boolean;
protected
procedure SetBackground(const Value: ThtBackground);
procedure SetBorders(const Value: ThtBorders);
procedure SetColor(const Value: TColor);
procedure SetCursor(const Value: string);
procedure SetExtraStyles(const Value: string);
procedure SetFont(const Value: ThtFont);
procedure SetName(const Value: string);
procedure SetPadding(const Value: ThtPadding);
//procedure SetOverflow(const Value: ThtOverflow);
procedure SetParentColor(const Value: Boolean);
procedure SetParentFont(const Value: Boolean);
protected
procedure InternalChange(inSender: TObject); virtual;
public
constructor Create(AOwner: TComponent); virtual;
destructor Destroy; override;
function InlineColorAttribute: string;
function StyleAttribute: string;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: ThtStyleList);
procedure Assign(Source: TPersistent); override;
procedure AssignFromParent(inParent: ThtStyle);
procedure Inherit(inStyle: ThtStyle);
procedure ToFont(inFont: TFont);
function GetBoxLeft: Integer;
function GetBoxTop: Integer;
function GetBoxRight: Integer;
function GetBoxBottom: Integer;
// procedure ExpandRect(var ioRect: TRect);
function UnboxRect(const inRect: TRect): TRect;
procedure UnpadRect(var ioRect: TRect);
function GetBoxHeightMargin: Integer;
function GetBoxWidthMargin: Integer;
procedure AdjustClientRect(var ioRect: TRect);
function AdjustHeight(inHeight: Integer): Integer;
function AdjustWidth(inWidth: Integer): Integer;
function Owner: TComponent;
property Name: string read FName write SetName;
property ParentFont: Boolean read FParentFont write SetParentFont;
property ParentColor: Boolean read FParentColor write SetParentColor;
published
property Background: ThtBackground read FBackground write SetBackground;
property Border: ThtBorders read FBorders write SetBorders;
property Color: TColor read FColor write SetColor default clNone;
property Cursor: string read FCursor write SetCursor;
property ExtraStyles: string read FExtraStyles write SetExtraStyles;
property Font: ThtFont read FFont write SetFont;
//property Overflow: ThtOverflow read FOverflow write SetOverflow;
property Padding: ThtPadding read FPadding write SetPadding;
end;
const
ssPx = 'px';
ssPerc = '%';
ss100Percent = '100%';
//
ssHeight = 'height';
ssWidth = 'width';
ssLeft = 'left';
ssTop = 'top';
ssRight = 'right';
ssBottom = 'bottom';
ssCenter = 'center';
ssMarginLeft = 'margin-left';
ssMarginRight = 'margin-right';
ssPosition = 'position';
ssTextAlign = 'text-align';
ssColor = 'color';
ssBackgroundColor = 'background-color';
ssBackgroundImage = 'background-image';
ssBorderStyle = 'border-style';
ssBorderWidth = 'border-width';
ssBorderColor = 'border-color';
ssFont = 'font';
ssFontFamily = 'font-family';
ssFontSize = 'font-size';
ssFontWeight = 'font-weight';
ssFontStyle = 'font-style';
ssTextDecoration = 'text-decoration';
ssPadding = 'padding';
ssPaddingLeft = 'padding-left';
ssPaddingRight = 'padding-right';
ssPaddingTop = 'padding-top';
ssPaddingBottom = 'padding-bottom';
ssOverflow = 'overflow';
ssOverflowX = 'overflow-x';
ssOverflowY = 'overflow-y';
ssCursor = 'cursor';
//
ssStyle = 'style';
ssBorderPrefix = 'border';
ssBorderLeftPrefix = 'border-left';
ssBorderTopPrefix = 'border-top';
ssBorderRightPrefix = 'border-right';
ssBorderBottomPrefix = 'border-bottom';
//
ssBorderPrefixi: array[ThtBorderSide] of string =
(ssBorderPrefix, ssBorderLeftPrefix, ssBorderTopPrefix,
ssBorderRightPrefix, ssBorderBottomPrefix);
//
ssBorderStyles: array[ThtBorderStyle] of string =
('', 'inherit', 'none', 'hidden', 'dotted', 'dashed', 'solid', 'groove',
'ridge', 'inset', 'outset', 'double');
//
//ssPositions: array[ThtPosition] of string = ( 'absolute', 'relative' );
//
ssFontWeights: array[ThtFontWeight] of string =
('', 'normal', 'bold' );
ssRelFontSizes: array[ThtFontSizeRelEnum] of string =
('', 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large',
'xx-large');
cTFontSizes: array[ThtFontSizeRelEnum] of Integer =
(12, 7, 8, 12, 14, 18, 24, 36 );
ssTextDecorations: array[ThtFontDecorations] of string =
('', 'inherit', 'none', 'underline', 'overline', 'line-through', 'blink');
ssFontStyles: array[ThtFontStyle] of string =
('', 'inherit', 'normal', 'italic', 'oblique');
//
// ssOverflowStyles: array[ThtOverflowStyle] of string = ( '', 'inherit',
// 'visible', 'hidden', 'scroll', 'auto' );
//
ssNumCursors = 19;
ssCursors: array[0..18] of string =
('', 'inherit', 'default', 'auto', 'n-resize', 'ne-resize', 'e-resize',
'se-resize', 's-resize', 'sw-resize', 'w-resize', 'nw-resize',
'crosshair', 'pointer', 'move', 'text', 'wait', 'help', 'hand');
const
chtDefaultFontFamily: string = 'Times New Roman';
chtDefaultFontPx: Integer = 16;
var
NilStyle: ThtStyle;
implementation
uses
LrVclUtils, htUtils;
{ ThtFont }
constructor ThtFont.Create;
begin
FontColor := clNone;
DefaultFontFamily := chtDefaultFontFamily;
DefaultFontPx := chtDefaultFontPx;
end;
procedure ThtFont.SetFontFamily(const Value: TFontName);
begin
if FFontFamily <> Value then
begin
FFontFamily := Value;
Change;
end;
end;
procedure ThtFont.SetRelFontSize(const Value: ThtFontSizeRel);
begin
if FFontSizeRel <> Value then
begin
FFontSizeRel := Value;
Change;
end;
end;
procedure ThtFont.SetFontWeight(const Value: ThtFontWeight);
begin
if FFontWeight <> Value then
begin
FFontWeight := Value;
Change;
end;
end;
procedure ThtFont.SetFontSizePx(const Value: Integer);
begin
if FFontSizePx <> Value then
begin
FFontSizePx := Value;
Change;
end;
end;
procedure ThtFont.SetFontSizePt(const Value: Integer);
begin
if FFontSizePt <> Value then
begin
FFontSizePt := Value;
Change;
end;
end;
procedure ThtFont.SetFontColor(const Value: TColor);
begin
if FFontColor <> Value then
begin
FFontColor := Value;
Change;
end;
end;
procedure ThtFont.SetFontDecoration(
const Value: ThtFontDecoration);
begin
FFontDecoration := Value;
Change;
end;
procedure ThtFont.SetFontStyle(const Value: ThtFontStyle);
begin
FFontStyle := Value;
Change;
end;
function ThtFont.GetSizeValue: string;
begin
if (FontSizeRel <> '') then
Result := FontSizeRel
else if (FontSizePt <> 0) then
Result := Format('%dpt', [ FontSizePt ])
else if (FontSizePx <> 0) then
Result := htPxValue(FontSizePx)
else
Result := '';
end;
function ThtFont.GetFontDecorationValue: string;
var
i: ThtFontDecorations;
begin
for i := Low(ThtFontDecorations) to High(ThtFontDecorations) do
if i in FontDecoration then
Result := LrCat([Result, ssTextDecorations[i]]);
end;
function ThtFont.InlineAttribute: string;
var
fs: string;
begin
fs := GetSizeValue;
if (FontFamily <> '') and (fs <> '') then
begin
Result := LrCat([ ssFontStyles[FontStyle], ssFontWeights[FontWeight], fs,
FontFamily ]);
Result := htStyleProp(ssFont, Result);
end
else begin
Result := LrCat([ htStyleProp(ssFontFamily, FontFamily),
htStyleProp(ssFontSize, fs),
htStyleProp(ssFontWeight, ssFontWeights[FontWeight]),
htStyleProp(ssFontStyle, ssFontStyles[FontStyle]) ]);
end;
Result := LrCat([ Result, htStyleProp(ssColor, FontColor),
htStyleProp(ssTextDecoration, GetFontDecorationValue) ]);
end;
procedure ThtFont.ListStyles(inStyles: ThtStyleList);
var
fs, s: string;
begin
fs := GetSizeValue;
if (FontFamily <> '') and (fs <> '') then
begin
s := LrCat([ ssFontStyles[FontStyle], ssFontWeights[FontWeight], fs,
FontFamily ]);
inStyles.Add(ssFont, s);
end
else begin
inStyles.Add(ssFontFamily, FontFamily);
inStyles.Add(ssFontSize, fs);
inStyles.Add(ssFontWeight, ssFontWeights[FontWeight]);
inStyles.Add(ssFontStyle, ssFontStyles[FontStyle]);
end;
inStyles.AddColor(ssColor, FontColor);
inStyles.Add(ssTextDecoration, GetFontDecorationValue);
end;
function ThtFont.GetRelFontSize: Integer;
var
i: ThtFontSizeRelEnum;
begin
Result := cTFontSizes[fsDefault];
for i := Low(ThtFontSizeRelEnum) to High(ThtFontSizeRelEnum) do
if (ssRelFontSizes[i] = FontSizeRel) then
begin
Result := cTFontSizes[i];
break;
end;
end;
procedure ThtFont.ToFont(inFont: TFont);
var
s: TFontStyles;
begin
with inFont do
begin
if FontFamily <> '' then
Name := FontFamily
else
Name := DefaultFontFamily;
s := [];
if FontWeight = fwBold then
s := s + [ fsBold ];
if fdUnderline in FontDecoration then
s := s + [ fsUnderline ];
if fdLineThrough in FontDecoration then
s := s + [ fsStrikeOut ];
if (FontStyle = fstItalic) or (FontStyle = fstOblique) then
s := s + [ fsItalic ];
Style := s;
if FontSizeRel <> '' then
Size := GetRelFontSize
else if (FontSizePt <> 0) then
Height := -FontSizePt * 4 div 3
else if (FontSizePx <> 0) then
Height := -FontSizePx
else
Height := -DefaultFontPx;
if htVisibleColor(FontColor) then
Color := FontColor
else
Color := clBlack;
end;
end;
procedure ThtFont.Inherit(inFont: ThtFont);
begin
if inFont <> nil then
begin
if (FFontFamily = '') then
FFontFamily := inFont.FFontFamily;
if (FontWeight = fwDefault) then
FFontWeight := inFont.FFontWeight;
if not htVisibleColor(FFontColor) then
FFontColor := inFont.FFontColor;
if (FFontDecoration = [ fdDefault ]) then
FFontDecoration := inFont.FFontDecoration;
if (FFontStyle = fstDefault) then
FFontStyle := inFont.FFontStyle;
if (FFontSizePx = 0) then
begin
FFontSizePx := inFont.FFontSizePx;
if (FFontSizePt = 0) then
begin
FFontSizePt := inFont.FFontSizePt;
if (FFontSizeRel = '') then
FFontSizeRel := inFont.FFontSizeRel;
end;
end;
end;
end;
procedure ThtFont.Assign(Source: TPersistent);
begin
if not (Source is ThtFont) then
inherited
else with ThtFont(Source) do
begin
Self.FFontSizeRel := FFontSizeRel;
Self.FFontFamily := FFontFamily;
Self.FFontWeight := FFontWeight;
Self.FFontSizePx := FFontSizePx;
Self.FFontSizePt := FFontSizePt;
Self.FFontColor := FFontColor;
Self.FFontDecoration := FFontDecoration;
Self.FFontStyle := FFontStyle;
end;
end;
procedure ThtFont.SetDefaultFontFamily(const Value: string);
begin
FDefaultFontFamily := Value;
end;
procedure ThtFont.SetDefaultFontPx(const Value: Integer);
begin
FDefaultFontPx := Value;
end;
{ ThtBackground }
constructor ThtBackground.Create(AOwner: TComponent);
begin
inherited Create;
FPicture := ThtPicture.Create; //(AOwner);
FPicture.OnChange := PictureChange;
end;
destructor ThtBackground.Destroy;
begin
FPicture.Free;
inherited;
end;
procedure ThtBackground.Assign(Source: TPersistent);
begin
if not (Source is ThtBackground) then
inherited
else with ThtBackground(Source) do
Self.Picture := Picture;
end;
procedure ThtBackground.Inherit(inBackground: ThtBackground);
begin
if not Picture.HasGraphic then
Picture := inBackground.Picture;
end;
function ThtBackground.InlineAttribute: string;
begin
if Picture.Url <> '' then
Result := htStyleProp(ssBackgroundImage, 'url(' + Picture.Url + ')')
else
Result := '';
end;
procedure ThtBackground.ListStyles(inStyles: ThtStyleList);
begin
if Picture.Url <> '' then
inStyles.Add(ssBackgroundImage, 'url(' + Picture.Url + ')');
end;
procedure ThtBackground.PictureChange(inSender: TObject);
begin
Change;
end;
procedure ThtBackground.SetPicture(const Value: ThtPicture);
begin
Picture.Assign(Value);
end;
{ ThtBorder }
constructor ThtBorder.Create(inOwner: ThtStyleBase;
inSide: ThtBorderSide);
begin
FOwnerStyle := inOwner;
BorderSide := inSide;
FBorderPrefix := ssBorderPrefixi[inSide];
FBorderColor := clDefault;
end;
procedure ThtBorder.Change;
begin
inherited;
if FOwnerStyle <> nil then
FOwnerStyle.Change;
end;
function ThtBorder.BorderVisible: Boolean;
begin
case BorderStyle of
bsDefault: Result := DefaultBorderPixels <> 0;
bsNone, bsHidden: Result := false;
else Result := true;
end;
inherited;
end;
function ThtBorder.GetBorderPixels: Integer;
const
cThickBorder = 6;
cMediumBorder = 4;
cThinBorder = 2;
cDefaultBorder = cMediumBorder;
begin
Result := 0;
if BorderVisible then
begin
if BorderStyle = bsDefault then
Result := DefaultBorderPixels
else if BorderWidth = '' then
Result := cDefaultBorder
else if BorderWidth = 'thin' then
Result := cThinBorder
else if BorderWidth = 'medium' then
Result := cMediumBorder
else if BorderWidth = 'thick' then
Result := cThickBorder
else
Result := StrToIntDef(BorderWidth, cDefaultBorder);
end;
end;
procedure ThtBorder.SetBorderColor(const Value: TColor);
begin
FBorderColor := Value;
Change;
end;
procedure ThtBorder.SetBorderStyle(const Value: ThtBorderStyle);
begin
FBorderStyle := Value;
Change;
end;
procedure ThtBorder.SetBorderWidth(const Value: string);
begin
FBorderWidth := Value;
Change;
end;
function ThtBorder.GetBorderWidthValue: string;
begin
if LrStringIsDigits(BorderWidth) then
Result := BorderWidth + 'px'
else
Result := BorderWidth;
end;
function ThtBorder.CanCompoundStyle: Boolean;
begin
Result := (ssBorderStyles[BorderStyle] <> '') and (BorderWidth <> '') and
htVisibleColor(BorderColor);
end;
function ThtBorder.InlineAttribute: string;
begin
if BorderStyle = bsDefault then
Result := ''
else if CanCompoundStyle then
Result := htStyleProp(FBorderPrefix,
LrCat([ GetBorderWidthValue, ssBorderStyles[BorderStyle],
htColorToHtml(BorderColor) ]))
else
Result := LrCat([
htStyleProp(FBorderPrefix + '-' + ssStyle, ssBorderStyles[BorderStyle]),
htStyleProp(FBorderPrefix + '-' + ssWidth, GetBorderWidthValue),
htStyleProp(FBorderPrefix + '-' + ssColor, BorderColor) ]);
end;
procedure ThtBorder.ListStyles(inStyles: ThtStyleList);
begin
if BorderStyle <> bsDefault then
if CanCompoundStyle then
inStyles.Add(FBorderPrefix,
LrCat([ GetBorderWidthValue, ssBorderStyles[BorderStyle],
htColorToHtml(BorderColor) ]))
else begin
inStyles.Add(FBorderPrefix + '-' + ssStyle, ssBorderStyles[BorderStyle]);
inStyles.Add(FBorderPrefix + '-' + ssWidth, GetBorderWidthValue);
inStyles.AddColor(FBorderPrefix + '-' + ssColor, BorderColor);
end;
end;
procedure ThtBorder.Assign(Source: TPersistent);
begin
if not (Source is ThtBorder) then
inherited
else with ThtBorder(Source) do
begin
Self.FBorderWidth := FBorderWidth;
Self.FBorderStyle := FBorderStyle;
Self.FBorderColor := FBorderColor;
end;
end;
procedure ThtBorder.Inherit(inBorder: ThtBorder);
begin
if inBorder.FBorderWidth <> '' then
FBorderWidth := inBorder.FBorderWidth;
if inBorder.FBorderStyle <> bsDefault then
FBorderStyle := inBorder.FBorderStyle;
if htVisibleColor(inBorder.FBorderColor) then
FBorderColor := inBorder.FBorderColor;
end;
{ ThtBorderDetail }
constructor ThtBorderDetail.Create(inOwnerStyle: ThtStyleBase);
begin
inherited Create;
FBorderLeft := ThtBorder.Create(inOwnerStyle, bsLeft);
FBorderTop := ThtBorder.Create(inOwnerStyle, bsTop);
FBorderRight := ThtBorder.Create(inOwnerStyle, bsRight);
FBorderBottom := ThtBorder.Create(inOwnerStyle, bsBottom);
end;
destructor ThtBorderDetail.Destroy;
begin
FBorderLeft.Free;
FBorderTop.Free;
FBorderRight.Free;
FBorderBottom.Free;
inherited;
end;
function ThtBorderDetail.BorderVisible: Boolean;
begin
Result := BorderLeft.BorderVisible or
BorderTop.BorderVisible or
BorderRight.BorderVisible or
BorderBottom.BorderVisible;
end;
procedure ThtBorderDetail.Assign(Source: TPersistent);
begin
if not (Source is ThtBorderDetail) then
inherited
else with ThtBorderDetail(Source) do
begin
Self.FBorderLeft.Assign(FBorderLeft);
Self.FBorderTop.Assign(FBorderTop);
Self.FBorderRight.Assign(FBorderRight);
Self.FBorderBottom.Assign(FBorderBottom);
end;
end;
procedure ThtBorderDetail.Inherit(inDetail: ThtBorderDetail);
begin
FBorderLeft.Inherit(inDetail.FBorderLeft);
FBorderTop.Inherit(inDetail.FBorderTop);
FBorderRight.Inherit(inDetail.FBorderRight);
FBorderBottom.Inherit(inDetail.FBorderBottom);
end;
function ThtBorderDetail.InlineAttribute: string;
begin
Result := BorderLeft.InlineAttribute
+ BorderTop.InlineAttribute
+ BorderRight.InlineAttribute
+ BorderBottom.InlineAttribute;
end;
procedure ThtBorderDetail.ListStyles(inStyles: ThtStyleList);
begin
BorderLeft.ListStyles(inStyles);
BorderTop.ListStyles(inStyles);
BorderRight.ListStyles(inStyles);
BorderBottom.ListStyles(inStyles);
end;
function ThtBorderDetail.GetBorder(inSide: ThtBorderSide): ThtBorder;
begin
case inSide of
bsLeft: Result := BorderLeft;
bsTop: Result := BorderTop;
bsRight: Result := BorderRight;
bsBottom: Result := BorderBottom;
else Result := BorderLeft;
end;
end;
procedure ThtBorderDetail.SetBorderBottom(const Value: ThtBorder);
begin
FBorderBottom.Assign(Value);
end;
procedure ThtBorderDetail.SetBorderLeft(const Value: ThtBorder);
begin
FBorderLeft.Assign(Value);
end;
procedure ThtBorderDetail.SetBorderRight(const Value: ThtBorder);
begin
FBorderRight.Assign(Value);
end;
procedure ThtBorderDetail.SetBorderTop(const Value: ThtBorder);
begin
FBorderTop.Assign(Value);
end;
procedure ThtBorderDetail.SetDefaultBorderPixels(inPixels: Integer);
begin
BorderLeft.DefaultBorderPixels := inPixels;
BorderTop.DefaultBorderPixels := inPixels;
BorderRight.DefaultBorderPixels := inPixels;
BorderBottom.DefaultBorderPixels := inPixels;
end;
{ ThtBorders }
constructor ThtBorders.Create;
begin
inherited Create(nil, bsAll);
FEdges := ThtBorderDetail.Create(Self);
Change;
end;
destructor ThtBorders.Destroy;
begin
FEdges.Free;
inherited;
end;
procedure ThtBorders.Assign(Source: TPersistent);
begin
inherited;
if (Source is ThtBorders) then
with ThtBorders(Source) do
Self.Edges.Assign(Edges);
end;
procedure ThtBorders.Inherit(inBox: ThtBorders);
begin
inherited Inherit(inBox);
Edges.Inherit(inBox.Edges);
end;
function ThtBorders.InlineAttribute: string;
begin
if BorderStyle <> bsDefault then
Result := inherited InlineAttribute
else
Result := Edges.InlineAttribute;
end;
procedure ThtBorders.ListStyles(inStyles: ThtStyleList);
begin
if BorderStyle <> bsDefault then
inherited ListStyles(inStyles)
else
Edges.ListStyles(inStyles);
end;
function ThtBorders.GetBorderColor(inSide: ThtBorderSide): TColor;
begin
if BorderStyle <> bsDefault then
Result := BorderColor
else
Result := Edges.GetBorder(inSide).BorderColor;
end;
function ThtBorders.GetBorderStyle(
inSide: ThtBorderSide): ThtBorderStyle;
begin
if BorderStyle <> bsDefault then
Result := BorderStyle
else
Result := Edges.GetBorder(inSide).BorderStyle;
end;
function ThtBorders.GetBorderPixels(inSide: ThtBorderSide): Integer;
begin
if BorderStyle <> bsDefault then
Result := GetBorderPixels
else
Result := Edges.GetBorder(inSide).GetBorderPixels;
end;
function ThtBorders.BorderVisible: Boolean;
begin
Result := inherited BorderVisible or Edges.BorderVisible;
end;
procedure ThtBorders.SetDefaultBorderPixels(inPixels: Integer);
begin
FDefaultBorderPixels := inPixels;
Edges.DefaultBorderPixels := inPixels;
end;
procedure ThtBorders.SetEdges(const Value: ThtBorderDetail);
begin
FEdges.Assign(Value);
end;
{ ThtPadDetail }
constructor ThtPadDetail.Create(inOwnerStyle: ThtStyleBase);
begin
FOwnerStyle := inOwnerStyle;
end;
procedure ThtPadDetail.Change;
begin
inherited;
if FOwnerStyle <> nil then
FOwnerStyle.Change;
end;
function ThtPadDetail.HasPadding: Boolean;
begin
Result := (PadLeft <> 0) or (PadRight <> 0) or (PadTop <> 0)
or (PadBottom <> 0);
end;
procedure ThtPadDetail.Assign(Source: TPersistent);
begin
if not (Source is ThtPadDetail) then
inherited
else with ThtPadDetail(Source) do
begin
Self.FPadLeft := FPadLeft;
Self.FPadTop := FPadTop;
Self.FPadRight := FPadRight;
Self.FPadBottom := FPadBottom;
end;
end;
procedure ThtPadDetail.Inherit(inPad: ThtPadDetail);
begin
if (inPad.FPadLeft <> 0) then
FPadLeft := inPad.FPadLeft;
if (inPad.FPadTop <> 0) then
FPadTop := inPad.FPadTop;
if (inPad.FPadRight <> 0) then
FPadRight := inPad.FPadRight;
if (inPad.FPadBottom <> 0) then
FPadBottom := inPad.FPadBottom;
end;
function ThtPadDetail.InlineAttribute: string;
begin
Result := '';
if (PadLeft <> 0) then
LrCat(Result, htStyleProp(ssPaddingLeft, htPxValue(PadLeft)));
if (PadTop <> 0) then
LrCat(Result, htStyleProp(ssPaddingTop, htPxValue(PadTop)));
if (PadRight <> 0) then
LrCat(Result, htStyleProp(ssPaddingRight, htPxValue(PadRight)));
if (PadBottom <> 0) then
LrCat(Result, htStyleProp(ssPaddingBottom, htPxValue(PadBottom)));
end;
procedure ThtPadDetail.ListStyles(inStyles: ThtStyleList);
begin
with inStyles do
begin
AddIfNonZero(ssPaddingLeft, PadLeft, ssPx);
AddIfNonZero(ssPaddingTop, PadTop, ssPx);
AddIfNonZero(ssPaddingRight, PadRight, ssPx);
AddIfNonZero(ssPaddingBottom, PadBottom, ssPx);
end;
end;
function ThtPadDetail.PadHeight: Integer;
begin
Result := PadTop + PadBottom;
end;
function ThtPadDetail.PadWidth: Integer;
begin
Result := PadLeft + PadRight;
end;
procedure ThtPadDetail.SetPadBottom(const Value: Integer);
begin
FPadBottom := Value;
Change;
end;
procedure ThtPadDetail.SetPadLeft(const Value: Integer);
begin
FPadLeft := Value;
Change;
end;
procedure ThtPadDetail.SetPadRight(const Value: Integer);
begin
FPadRight := Value;
Change;
end;
procedure ThtPadDetail.SetPadTop(const Value: Integer);
begin
FPadTop := Value;
Change;
end;
procedure ThtPadDetail.SetPadding(const Value: Integer);
begin
FPadLeft := Value;
FPadRight := Value;
FPadTop := Value;
FPadBottom := Value;
Change;
end;
{ ThtPadding }
constructor ThtPadding.Create;
begin
inherited;
FPaddingDetails := ThtPadDetail.Create(Self);
end;
destructor ThtPadding.Destroy;
begin
FPaddingDetails.Free;
inherited;
end;
procedure ThtPadding.Change;
begin
if PaddingDetails.HasPadding then
FPadding := 0;
inherited;
end;
function ThtPadding.HasPadding: Boolean;
begin
Result := (Padding <> 0) or PaddingDetails.HasPadding;
end;
function ThtPadding.PadHeight: Integer;
begin
if Padding <> 0 then
Result := Padding + Padding
else
Result := PaddingDetails.PadHeight;
end;
function ThtPadding.PadWidth: Integer;
begin
if Padding <> 0 then
Result := Padding + Padding
else
Result := PaddingDetails.PadWidth;
end;
function ThtPadding.PadLeft: Integer;
begin
if Padding <> 0 then
Result := Padding
else
Result := PaddingDetails.PadLeft;
end;
function ThtPadding.PadTop: Integer;
begin
if Padding <> 0 then
Result := Padding
else
Result := PaddingDetails.PadTop;
end;
function ThtPadding.PadRight: Integer;
begin
if Padding <> 0 then
Result := Padding
else
Result := PaddingDetails.PadRight;
end;
function ThtPadding.PadBottom: Integer;
begin
if Padding <> 0 then
Result := Padding
else
Result := PaddingDetails.PadBottom;
end;
procedure ThtPadding.Assign(Source: TPersistent);
begin
if not (Source is ThtPadding) then
inherited
else with ThtPadding(Source) do
begin
Self.Padding := Padding;
Self.PaddingDetails.Assign(PaddingDetails);
end;
end;
procedure ThtPadding.Inherit(inPad: ThtPadding);
begin
if (inPad.Padding <> 0) then
Padding := inPad.Padding;
PaddingDetails.Inherit(inPad.PaddingDetails);
end;
function ThtPadding.InlineAttribute: string;
begin
if (Padding <> 0) then
Result := htStyleProp(ssPadding, htPxValue(Padding))
else
Result := PaddingDetails.InlineAttribute;
end;
procedure ThtPadding.ListStyles(inStyles: ThtStyleList);
begin
if (Padding <> 0) then
inStyles.Add(ssPadding, Padding, 'px')
else
PaddingDetails.ListStyles(inStyles);
end;
procedure ThtPadding.SetPadding(const Value: Integer);
begin
FPadding := Value;
Change;
end;
procedure ThtPadding.SetPaddingDetails(const Value: ThtPadDetail);
begin
FPaddingDetails.Assign(Value);
end;
{ ThtStyle }
constructor ThtStyle.Create(AOwner: TComponent);
begin
inherited Create;
FOwner := AOwner;
FBackground := ThtBackground.Create(AOwner);
FBackground.OnChange := InternalChange;
FFont := ThtFont.Create;
FFont.OnChange := InternalChange;
FBorders := ThtBorders.Create;
FBorders.OnChange := InternalChange;
FPadding := ThtPadding.Create;
FPadding.OnChange := InternalChange;
// FOverflow := ThtOverflow.Create;
// FOverflow.OnChange := InternalChange;
FColor := clNone;
end;
destructor ThtStyle.Destroy;
begin
// FOverflow.Free;
FPadding.Free;
FBorders.Free;
FFont.Free;
FBackground.Free;
inherited;
end;
function ThtStyle.Owner: TComponent;
begin
Result := FOwner;
end;
procedure ThtStyle.InternalChange(inSender: TObject);
begin
Change;
end;
function ThtStyle.StyleAttribute: string;
begin
Result := InlineAttribute;
if Result <> '' then
Result := ' style="' + Result + '"';
end;
function ThtStyle.InlineColorAttribute: string;
begin
Result := htStyleProp(ssBackgroundColor, Color);
end;
function ThtStyle.InlineAttribute: string;
begin
Result := LrCat([
FFont.InlineAttribute,
InlineColorAttribute,
FBackground.InlineAttribute,
FBorders.InlineAttribute,
FPadding.InlineAttribute,
{FOverflow.InlineAttribute,}
ExtraStyles
]);
end;
procedure ThtStyle.ListStyles(inStyles: ThtStyleList);
begin
FFont.ListStyles(inStyles);
inStyles.AddColor(ssBackgroundColor, Color);
FBackground.ListStyles(inStyles);
FBorders.ListStyles(inStyles);
FPadding.ListStyles(inStyles);
inStyles.Add(ssCursor, Cursor);
inStyles.ExtraStyles := inStyles.ExtraStyles + ExtraStyles;
end;
procedure ThtStyle.ToFont(inFont: TFont);
begin
Font.ToFont(inFont);
end;
procedure ThtStyle.AssignFromParent(inParent: ThtStyle);
begin
if FParentFont then
FFont.Assign(inParent.FFont);
if FParentColor then
FColor := inParent.FColor;
end;
procedure ThtStyle.Assign(Source: TPersistent);
begin
if Source <> nil then
if not (Source is ThtStyle) then
inherited
else with ThtStyle(Source) do
begin
Self.FBackground.Assign(FBackground);
Self.FBorders.Assign(FBorders);
Self.FFont.Assign(FFont);
//Self.FOverflow.Assign(FOverflow);
Self.FPadding.Assign(FPadding);
Self.FColor := FColor;
Self.FCursor := FCursor;
Self.ExtraStyles := ExtraStyles;
end;
end;
procedure ThtStyle.Inherit(inStyle: ThtStyle);
begin
if (inStyle <> nil) then
begin
FBackground.Inherit(inStyle.FBackground);
FBorders.Inherit(inStyle.FBorders);
FFont.Inherit(inStyle.FFont);
//FOverflow.Inherit(inStyle.FOverflow);
FPadding.Inherit(inStyle.FPadding);
if not htVisibleColor(FColor) then
FColor := inStyle.FColor;
if (inStyle.FCursor <> '') then
FCursor := inStyle.FCursor;
//ExtraStyles := ThConcatWithDelim(ExtraStyles, inStyle.ExtraStyles, ';');
end;
end;
procedure ThtStyle.SetBorders(const Value: ThtBorders);
begin
FBorders.Assign(Value);
Change;
end;
procedure ThtStyle.SetBackground(const Value: ThtBackground);
begin
FBackground.Assign(Value);
Change;
end;
procedure ThtStyle.SetFont(const Value: ThtFont);
begin
FFont.Assign(Value);
Change;
end;
//procedure ThtStyle.SetOverflow(const Value: ThtOverflow);
//begin
// FOverflow.Assign(Value);
// Change;
//end;
procedure ThtStyle.SetPadding(const Value: ThtPadding);
begin
FPadding.Assign(Value);
Change;
end;
procedure ThtStyle.SetName(const Value: string);
begin
FName := Value;
end;
procedure ThtStyle.SetColor(const Value: TColor);
begin
FColor := Value;
if (FOwner = nil) or not (csLoading in FOwner.ComponentState) then
begin
FParentColor := false;
Change;
end;
end;
procedure ThtStyle.SetExtraStyles(const Value: string);
begin
FExtraStyles := Value;
end;
procedure ThtStyle.SetCursor(const Value: string);
begin
FCursor := Value;
Change;
end;
procedure ThtStyle.SetParentColor(const Value: Boolean);
begin
FParentColor := Value;
Change;
end;
procedure ThtStyle.SetParentFont(const Value: Boolean);
begin
FParentFont := Value;
Change;
//Font.ParentFont := FParentFont;
end;
function ThtStyle.GetBoxBottom: Integer;
begin
Result := Border.GetBorderPixels(bsBottom) + Padding.PadBottom;
end;
function ThtStyle.GetBoxLeft: Integer;
begin
Result := Border.GetBorderPixels(bsLeft) + Padding.PadLeft;
end;
function ThtStyle.GetBoxRight: Integer;
begin
Result := Border.GetBorderPixels(bsRight) + Padding.PadRight;
end;
function ThtStyle.GetBoxTop: Integer;
begin
Result := Border.GetBorderPixels(bsTop) + Padding.PadTop;
end;
procedure ThtStyle.UnpadRect(var ioRect: TRect);
begin
with ioRect do
begin
Left := Left + Padding.PadLeft;
Right := Right - Padding.PadRight;
Top := Top + Padding.PadTop;
Bottom := Bottom - Padding.PadBottom;
end;
end;
function ThtStyle.UnboxRect(const inRect: TRect): TRect;
begin
with Result do
begin
Left := inRect.Left + GetBoxLeft;
Right := inRect.Right - GetBoxRight;
Top := inRect.Top + GetBoxTop;
Bottom := inRect.Bottom - GetBoxBottom;
end;
end;
{
procedure ThtStyle.ExpandRect(var ioRect: TRect);
begin
with ioRect do
begin
Left := Left - GetBoxLeft;
Right := Right + GetBoxRight;
Top := Top - GetBoxTop;
Bottom := Bottom + GetBoxBottom;
end;
end;
}
procedure ThtStyle.AdjustClientRect(var ioRect: TRect);
begin
with ioRect do
begin
Inc(Left, GetBoxLeft);
Inc(Top, GetBoxTop);
Dec(Right, GetBoxRight);
Dec(Bottom, GetBoxBottom);
// Left := Left + GetBoxLeft;
// Right := Right - GetBoxRight;
// Top := Top + GetBoxTop;
// Bottom := Bottom - GetBoxBottom;
end;
end;
function ThtStyle.GetBoxWidthMargin: Integer;
begin
Result := GetBoxLeft + GetBoxRight;
end;
function ThtStyle.GetBoxHeightMargin: Integer;
begin
Result := GetBoxTop + GetBoxBottom;
end;
function ThtStyle.AdjustWidth(inWidth: Integer): Integer;
begin
Result := inWidth - GetBoxWidthMargin;
end;
function ThtStyle.AdjustHeight(inHeight: Integer): Integer;
begin
Result := inHeight - GetBoxHeightMargin;
end;
initialization
NilStyle := ThtStyle.Create(nil);
finalization
NilStyle.Free;
end.
|
unit DSincronizadorModuloWeb;
interface
uses
ActiveX, SysUtils, Classes, ExtCtrls, DIntegradorModuloWeb, Dialogs, Windows, IDataPrincipalUnit,
ISincronizacaoNotifierUnit, IdHTTP;
type
TStepGettersEvent = procedure(name: string; step, total: integer) of object;
TServerToClientBlock = array of TDataIntegradorModuloWebClass;
TGetterBlocks = array of TServerToClientBlock;
TDataSincronizadorModuloWeb = class(TDataModule)
sincronizaRetaguardaTimer: TTimer;
procedure DataModuleCreate(Sender: TObject);
procedure sincronizaRetaguardaTimerTimer(Sender: TObject);
private
atualizando: boolean;
FonStepGetters: TStepGettersEvent;
procedure SetonStepGetters(const Value: TStepGettersEvent);
function ShouldContinue: boolean;
protected
Fnotifier: ISincronizacaoNotifier;
FThreadControl: IThreadControl;
FCustomParams: ICustomParams;
FDataLog: ILog;
public
posterDataModules: array of TDataIntegradorModuloWebClass;
getterBlocks: TGetterBlocks;
function getNewDataPrincipal: IDataPrincipal; virtual; abstract;
procedure addPosterDataModule(dm: TDataIntegradorModuloWebClass);
procedure addGetterBlock(getterBlock: TServerToClientBlock);
procedure ativar;
procedure desativar;
procedure getUpdatedData;
procedure threadedGetUpdatedData;
procedure saveAllToRemote(wait: boolean = false); virtual;
property notifier: ISincronizacaoNotifier read FNotifier write FNotifier;
property threadControl: IThreadControl read FthreadControl write FthreadControl;
property CustomParams: ICustomParams read FCustomParams write FCustomParams;
property Datalog: ILog read FDataLog write FDataLog;
published
property onStepGetters: TStepGettersEvent read FonStepGetters write SetonStepGetters;
end;
TCustomRunnerThread = class(TThread)
private
procedure Setnotifier(const Value: ISincronizacaoNotifier);
procedure Setsincronizador(const Value: TDataSincronizadorModuloWeb);
protected
Fnotifier: ISincronizacaoNotifier;
FthreadControl: IThreadControl;
Fsincronizador: TDataSincronizadorModuloWeb;
FCustomParams: ICustomParams;
FDataLog: ILog;
function ShouldContinue: boolean;
procedure Log(const aLog, aClasse: string);
public
property notifier: ISincronizacaoNotifier read Fnotifier write Setnotifier;
property sincronizador: TDataSincronizadorModuloWeb read Fsincronizador write Setsincronizador;
property threadControl: IThreadControl read FthreadControl write FthreadControl;
property CustomParams: ICustomParams read FCustomParams write FCustomParams;
property DataLog: ILog read FDataLog write FDataLog;
end;
TRunnerThreadGetters = class(TCustomRunnerThread)
private
procedure setMainFormGettingFalse;
procedure finishGettingProcess;
protected
procedure setMainFormGettingTrue;
public
procedure Execute; override;
end;
TRunnerThreadPuters = class(TCustomRunnerThread)
protected
procedure setMainFormPuttingTrue;
procedure finishPuttingProcess;
public
procedure Execute; override;
end;
var
DataSincronizadorModuloWeb: TDataSincronizadorModuloWeb;
salvandoRetaguarda, gravandoVenda: boolean;
implementation
uses ComObj, acNetUtils;
{$R *.dfm}
procedure TDataSincronizadorModuloWeb.addPosterDataModule(
dm: TDataIntegradorModuloWebClass);
var
size: integer;
begin
size := length(posterDataModules);
SetLength(posterDataModules, size + 1);
posterDataModules[size] := dm;
end;
procedure TDataSincronizadorModuloWeb.threadedGetUpdatedData;
var
t: TRunnerThreadGetters;
begin
t := TRunnerThreadGetters.Create(true);
t.sincronizador := self;
t.threadControl := self.threadControl;
t.CustomParams := self.CustomParams;
t.DataLog := Self.Datalog;
t.notifier := notifier;
t.Start;
end;
function TDataSincronizadorModuloWeb.ShouldContinue: boolean;
begin
Result := true;
if Self.FThreadControl <> nil then
result := Self.FThreadControl.getShouldContinue;
end;
procedure TDataSincronizadorModuloWeb.getUpdatedData;
var
i, j: integer;
block: TServerToClientBlock;
dm: IDataPrincipal;
http: TidHTTP;
dimw: TDataIntegradorModuloWeb;
begin
CoInitializeEx(nil, 0);
try
dm := getNewDataPrincipal;
http := getHTTPInstance;
try
for i := 0 to length(getterBlocks) - 1 do
begin
if not Self.ShouldContinue then
Break;
block := getterBlocks[i];
dm.startTransaction;
try
for j := 0 to length(block) - 1 do
begin
if not Self.ShouldContinue then
Break;
dimw := block[j].Create(nil);
try
dimw.notifier := Self.Fnotifier;
dimw.dmPrincipal := dm;
dimw.threadcontrol := Self.FThreadControl;
dimw.CustomParams := Self.FCustomParams;
dimw.DataLog := Self.FDataLog;
dimw.getDadosAtualizados(http);
if Assigned(onStepGetters) then onStepGetters(dimw.getHumanReadableName, i+1, length(getterBlocks));
finally
dimw.free;
end;
end;
dm.commit;
except
dm.rollback;
end;
end;
finally
dm := nil;
http := nil;
end;
finally
CoUninitialize;
end;
end;
procedure TDataSincronizadorModuloWeb.DataModuleCreate(Sender: TObject);
begin
SetLength(posterDataModules, 0);
SetLength(getterBlocks, 0);
sincronizaRetaguardaTimer.Enabled := false;
atualizando := false;
salvandoRetaguarda := false;
gravandoVenda := false;
end;
procedure TDataSincronizadorModuloWeb.ativar;
begin
sincronizaRetaguardaTimer.Enabled := true;
end;
procedure TDataSincronizadorModuloWeb.desativar;
begin
sincronizaRetaguardaTimer.Enabled := false;
end;
procedure TDataSincronizadorModuloWeb.addGetterBlock(
getterBlock: TServerToClientBlock);
var
size: integer;
begin
size := length(getterBlocks);
SetLength(getterBlocks, size + 1);
getterBlocks[size] := getterBlock;
end;
procedure TDataSincronizadorModuloWeb.sincronizaRetaguardaTimerTimer(
Sender: TObject);
begin
SaveAllToRemote;
end;
procedure TDataSincronizadorModuloWeb.SaveAllToRemote(wait: boolean = false);
var
t: TRunnerThreadPuters;
begin
t := TRunnerThreadPuters.Create(true);
t.sincronizador := self;
t.notifier := notifier;
t.threadControl := Self.FThreadControl;
t.CustomParams := Self.FCustomParams;
t.FreeOnTerminate := not wait;
t.DataLog := Self.FDataLog;
t.Start;
if wait then
begin
t.WaitFor;
FreeAndNil(t);
end;
end;
procedure TDataSincronizadorModuloWeb.SetonStepGetters(
const Value: TStepGettersEvent);
begin
FonStepGetters := Value;
end;
{TRunnerThreadGetters}
procedure TRunnerThreadGetters.finishGettingProcess;
var
i, j: integer;
block: TServerToClientBlock;
begin
//DataPrincipal.refreshData;
for i := 0 to length(sincronizador.getterBlocks) - 1 do
begin
block := sincronizador.getterBlocks[i];
for j := 0 to length(block) - 1 do
begin
block[j].updateDataSets;
end;
end;
setMainFormGettingFalse;
end;
procedure TRunnerThreadGetters.setMainFormGettingFalse;
begin
if notifier <> nil then
notifier.unflagBuscandoDadosServidor;
end;
procedure TRunnerThreadGetters.setMainFormGettingTrue;
begin
if notifier <> nil then
notifier.flagBuscandoDadosServidor;
end;
procedure TRunnerThreadGetters.Execute;
begin
inherited;
FreeOnTerminate := True;
if Self.Fnotifier <> nil then
Synchronize(Self.setMainFormGettingTrue);
CoInitializeEx(nil, 0);
try
sincronizador.notifier := Self.notifier;
sincronizador.threadControl := Self.threadControl;
sincronizador.Datalog := Self.DataLog;
sincronizador.CustomParams := Self.CustomParams;
sincronizador.getUpdatedData;
finally
CoUninitialize;
if Self.Fnotifier <> nil then
Synchronize(finishGettingProcess);
end;
end;
{TRunnerThreadPuters}
procedure TRunnerThreadPuters.finishPuttingProcess;
begin
if notifier <> nil then
notifier.unflagSalvandoDadosServidor;
end;
procedure TRunnerThreadPuters.setMainFormPuttingTrue;
begin
if FNotifier <> nil then
FNotifier.flagSalvandoDadosServidor;
end;
procedure TRunnerThreadPuters.Execute;
var
i: integer;
dm: IDataPrincipal;
dmIntegrador: TDataIntegradorModuloWeb;
http: TIdHTTP;
begin
inherited;
if salvandoRetaguarda or gravandoVenda then exit;
if Self.Fnotifier <> nil then
Synchronize(setMainFormPuttingTrue);
salvandoRetaguarda := true;
try
CoInitializeEx(nil, 0);
try
http := nil;
if gravandoVenda then exit;
dm := sincronizador.getNewDataPrincipal;
try
try
http := getHTTPInstance;
for i := 0 to length(sincronizador.posterDataModules)-1 do
begin
if not Self.ShouldContinue then
Break;
dmIntegrador := sincronizador.posterDataModules[i].Create(nil);
try
dmIntegrador.notifier := FNotifier;
dmIntegrador.threadControl := Self.FthreadControl;
dmIntegrador.CustomParams := Self.FCustomParams;
dmIntegrador.dmPrincipal := dm;
dmIntegrador.DataLog := Self.FDataLog;
dmIntegrador.postRecordsToRemote(http);
finally
FreeAndNil(dmIntegrador);
end;
end;
except
on e: Exception do
begin
Self.log('Erros ao dar saveAllToRemote. Erro: ' + e.Message, 'Sync');
end;
end;
finally
dm := nil;
if http <> nil then
FreeAndNil(http);
end;
finally
CoUninitialize;
end;
finally
salvandoRetaguarda := false;
if Self.Fnotifier <> nil then
Synchronize(finishPuttingProcess);
end;
end;
{ TCustomRunnerThread }
procedure TCustomRunnerThread.Log(const aLog, aClasse: string);
begin
if Self.FDataLog <> nil then
Self.FDataLog.log(aLog, aClasse);
end;
procedure TCustomRunnerThread.Setnotifier(const Value: ISincronizacaoNotifier);
begin
Fnotifier := Value;
end;
procedure TCustomRunnerThread.Setsincronizador(const Value: TDataSincronizadorModuloWeb);
begin
Fsincronizador := Value;
end;
function TCustomRunnerThread.ShouldContinue: boolean;
begin
result := true;
if Self.FThreadControl <> nil then
result := Self.FThreadControl.getShouldContinue;
end;
end.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.StdCtrls, IPPeerClient, REST.Client, Data.Bind.Components,
Data.Bind.ObjectScope;
type
TMainForm = class(TForm)
ToolBar1: TToolBar;
ToolBar2: TToolBar;
Label1: TLabel;
butLeft: TSpeedButton;
butRight: TSpeedButton;
lblPersonagem: TLabel;
imgPersonagem: TImage;
RESTClient1: TRESTClient;
RESTRequest1: TRESTRequest;
RESTResponse1: TRESTResponse;
procedure FormCreate(Sender: TObject);
procedure butLeftClick(Sender: TObject);
procedure butRightClick(Sender: TObject);
private
{ Private declarations }
FOffSet: integer;
procedure ExecuteRequest;
procedure OnAfterRequest;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
{$R *.XLgXhdpiTb.fmx ANDROID}
{ TForm1 }
uses System.UIConsts, System.DateUtils, System.JSON,
IdHashMessageDigest, Xplat.Utils, FMX.Graphics.HelperClass;
const
PUBLIC_KEY: string = 'a058d39a512955bc78905eea7307f733';
PRIVATE_KEY: string = 'c082618550a1a3937d9aacb4a484658fac81e30a';
procedure TMainForm.butLeftClick(Sender: TObject);
begin
if FOffSet >= 1 then
Dec(FOffSet);
ExecuteRequest;
end;
procedure TMainForm.butRightClick(Sender: TObject);
begin
Inc(FOffSet);
ExecuteRequest;
end;
procedure TMainForm.ExecuteRequest;
var
TS: string;
HASHStr: string;
imd5: TIdHashMessageDigest;
begin
StartWait;
TS := IntToStr(DateTimeToUnix(Now));
RESTRequest1.Params.ParameterByName('OFFSET').Value := FOffSet.ToString;
RESTRequest1.Params.ParameterByName('TS').Value := TS;
RESTRequest1.Params.ParameterByName('APIKEY').Value := PUBLIC_KEY;
imd5 := TIdHashMessageDigest5.Create;
try
HASHStr := TS + PRIVATE_KEY + PUBLIC_KEY;
RESTRequest1.Params.ParameterByName('HASH').Value :=
imd5.HashStringAsHex(HASHStr).ToLower;
RESTRequest1.ExecuteAsync(OnAfterRequest);
finally
imd5.Free;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
FOffSet := 0;
ExecuteRequest;
end;
procedure TMainForm.OnAfterRequest;
var
RetObject: TJSONObject;
RetData: TJSONObject;
MResult: TJSONObject;
Thumbnail: TJSONObject;
URL: string;
begin
try
RetObject := TJSONObject.ParseJSONValue(RESTResponse1.Content)
as TJSONObject;
RetData := RetObject.GetValue('data') as TJSONObject;
MResult := (RetData.GetValue('results') as TJSONArray).Get(0)
as TJSONObject;
Thumbnail := MResult.GetValue('thumbnail') as TJSONObject;
lblPersonagem.Text := MResult.GetValue('name').Value;
// utilizando um class helper para ler a imagem em segundo plano...
imgPersonagem.Bitmap.Clear(TAlphaColor(claWhitesmoke));
URL := Thumbnail.GetValue('path').Value + '.' +
Thumbnail.GetValue('extension').Value;
imgPersonagem.Bitmap.LoadFromUrl(URL);
finally
StopWait;
end;
end;
end.
|
unit uAppCache;
interface
uses
SysUtils,
Classes,
OmniXML,
uI2XConstants,
uHashTable,
uHashTableXML,
JclStrings,
uFileDir,
uStrUtil
;
const
UNIT_NAME = 'uAppCache';
type
TApplicationCacheBase = class(TObject)
private
protected
FOnChange : TNotifyEvent;
FIsDirty : boolean;
FSaveAfterEachUpdate : boolean;
procedure OnChangeHandler();
public
property OnChange : TNotifyEvent read FOnChange write FOnChange;
property AutoSave : boolean read FSaveAfterEachUpdate write FSaveAfterEachUpdate;
property IsDirty : boolean read FIsDirty write FIsDirty;
function AsXML() : string; virtual; abstract;
procedure ApplyChanges(); virtual; abstract;
constructor Create(); virtual;
destructor Destroy(); override;
end;
TApplicationCache = class(TApplicationCacheBase)
private
FFileName : TFileName;
FRootName : string;
oFileDir : CFileDir;
FVarCache : THashStringTableXML;
function getMinMessageDisplayed: boolean;
procedure setMinMessageDisplayed(const Value: boolean);
function getAutoScan: boolean;
function getOutputFolder: string;
function getSubPath: string;
procedure setAutoScan(const Value: boolean);
procedure setOutputFolder(const Value: string);
procedure setSubPath(const Value: string);
function getLastFolderSearched: string;
procedure setLastFolderSearched(const Value: string);
function getLastUserFolderSearched: string;
procedure setLastUserFolderSearched(const Value: string);
published
property MinMessageDisplayed : boolean read getMinMessageDisplayed write setMinMessageDisplayed;
property OutputFolder : string read getOutputFolder write setOutputFolder;
property SubPath : string read getSubPath write setSubPath;
property AutoScan : boolean read getAutoScan write setAutoScan;
property LastFolderSearched : string read getLastFolderSearched write setLastFolderSearched;
property LastUserFolderSearched : string read getLastUserFolderSearched write setLastUserFolderSearched;
function getVar( const varName : string ) : string;
procedure setVar( const varName : string; const varValue : string );
protected
function getVarCache( const varName : string ) : string; overload;
function getVarCache( const varName : string; const DefaultValue : integer ) : integer; overload;
function getVarCache( const varName : string; const DefaultValue : boolean ) : boolean; overload;
function getVarCache( const varName : string; const DefaultValue : extended ) : extended; overload;
procedure setVarCache( const varName : string; const varValue : string ); overload;
procedure setVarCache( const varName : string; const varValue : integer ); overload;
procedure setVarCache( const varName : string; const varValue : boolean ); overload;
procedure setVarCache( const varName : string; const varValue : extended ); overload;
public
property FileName : TFileName read FFileName write FFileName;
property RootName : string read FRootName write FRootName;
function AsXML() : string; override;
procedure ApplyChanges(); override;
constructor Create(); override;
destructor Destroy(); override;
end;
var
AppCache : TApplicationCache;
implementation
{ TApplicationCacheBase }
constructor TApplicationCacheBase.Create;
begin
FIsDirty := false;
end;
destructor TApplicationCacheBase.Destroy;
begin
end;
procedure TApplicationCacheBase.OnChangeHandler;
begin
self.FIsDirty := true;
if ( Assigned( self.FOnChange )) then
self.FOnChange( self );
if ( FSaveAfterEachUpdate ) then
self.ApplyChanges();
end;
{ TApplicationCache }
procedure TApplicationCache.ApplyChanges;
begin
self.FVarCache.SaveToFile( self.FFileName );
end;
function TApplicationCache.AsXML: string;
var
sarr : TStringBuilder;
begin
try
Result := FVarCache.AsXML();
finally
end;
end;
constructor TApplicationCache.Create;
begin
oFileDir := CFileDir.Create;
FRootName := 'AppCache';
self.FFileName := oFileDir.GetUserDir + I2XFULL_DIR_QUAL + 'appcache.dat';
if ( not DirectoryExists( ExtractFilePath( self.FFileName ) ) ) then
ForceDirectories( ExtractFilePath( self.FFileName ) );
self.FVarCache := THashStringTableXML.Create;
self.FVarCache.RootNode := FRootName;
if ( FileExists( FFileName ) ) then begin
FVarCache.LoadFromFile( FFileName );
end;
end;
destructor TApplicationCache.Destroy;
begin
FreeAndNil( FVarCache );
FreeAndNil( oFileDir );
inherited;
end;
function TApplicationCache.getVarCache(const varName: string;
const DefaultValue: integer): integer;
var
sRes : string;
begin
sRes := getVarCache( varName );
try
Result := StrToInt( sRes )
except
Result := DefaultValue;
end;
end;
function TApplicationCache.getVarCache(const varName: string;
const DefaultValue: boolean): boolean;
var
sRes : string;
begin
sRes := getVarCache( varName );
try
Result := StrToBool( sRes )
except
Result := DefaultValue;
end;
end;
function TApplicationCache.getAutoScan: boolean;
begin
Result := self.getVarCache( 'auto_scan', false );
end;
function TApplicationCache.getLastFolderSearched: string;
begin
Result := self.getVarCache( 'last_folder_searched' );
end;
function TApplicationCache.getLastUserFolderSearched: string;
begin
Result := self.getVarCache( 'last_user_folder_searched' );
if ( Length( Result ) = 0 ) then begin
Result := oFileDir.GetUserDir + I2XFULL_DIR_QUAL;
self.setLastFolderSearched( Result );
end;
end;
function TApplicationCache.getMinMessageDisplayed: boolean;
begin
Result := self.getVarCache( 'min_msg_displayed', false );
end;
function TApplicationCache.getOutputFolder: string;
begin
Result := self.getVarCache( 'output_folder' );
end;
function TApplicationCache.getSubPath: string;
begin
Result := self.getVarCache( 'sub_path' );
end;
function TApplicationCache.getVar(const varName: string): string;
begin
Result := self.getVarCache( varName );
end;
function TApplicationCache.getVarCache(const varName: string;
const DefaultValue: extended): extended;
var
sRes : string;
begin
sRes := getVarCache( varName );
try
Result := StrToFloat( sRes )
except
Result := DefaultValue;
end;
end;
function TApplicationCache.getVarCache(const varName: string): string;
begin
if (FVarCache.ContainsKey( varName )) then
Result := FVarCache.Items[ varName ]
else
Result := '';
end;
procedure TApplicationCache.setVarCache( const varName : string; const varValue: integer);
begin
self.setVarCache( varName, IntToStr( varValue ) );
end;
procedure TApplicationCache.setVarCache( const varName : string; const varValue: boolean);
begin
self.setVarCache( varName, BoolToStr( varValue ) );
end;
procedure TApplicationCache.setAutoScan(const Value: boolean);
begin
self.setVarCache( 'auto_scan', Value );
end;
procedure TApplicationCache.setLastFolderSearched(const Value: string);
begin
self.setVarCache( 'last_folder_searched', Value );
end;
procedure TApplicationCache.setLastUserFolderSearched(const Value: string);
begin
self.setVarCache( 'last_user_folder_searched', Value );
end;
procedure TApplicationCache.setMinMessageDisplayed(const Value: boolean);
begin
self.setVarCache( 'min_msg_displayed', Value );
end;
procedure TApplicationCache.setOutputFolder(const Value: string);
begin
self.setVarCache( 'output_folder', Value );
end;
procedure TApplicationCache.setSubPath(const Value: string);
begin
self.setVarCache( 'sub_path', Value );
end;
procedure TApplicationCache.setVar(const varName, varValue: string);
begin
self.setVarCache( varName, varValue );
end;
procedure TApplicationCache.setVarCache( const varName : string; const varValue: extended);
begin
self.setVarCache( varName, FloatToStr( varValue ) );
end;
procedure TApplicationCache.setVarCache( const varName : string; const varValue: string);
begin
if ( FVarCache.ContainsKey( varName ) ) then begin
if ( FVarCache.Items[ varName ] <> varValue ) then begin
FVarCache.Items[ varName ] := varValue;
self.OnChangeHandler();
end;
end else begin
FVarCache.Add( varName, varValue );
self.OnChangeHandler();
end;
end;
initialization
AppCache := TApplicationCache.Create;
finalization
FreeAndNil( AppCache );
END.
|
unit MixiAPIToken;
interface
uses
Classes, Contnrs, SysUtils, Crypt, HttpLib, superxmlparser, superobject;
type
TMixiAPIToken = class
private
FAccessToken: String;
FRefreshToken: String;
FExpire: TDateTime;
FTokenType: String;
FScope: String;
public
function isExpired: Boolean;
procedure SaveToFile(Path: String);
procedure LoadFromFile(Path: String);
property AccessToken: String read FAccessToken write FAccessToken;
property RefreshToken: String read FRefreshToken write FRefreshToken;
property Expire: TDateTime read FExpire write FExpire;
property TokenType: String read FTokenType write FTokenType;
property Scope: String read FScope write FScope;
end;
TMixiAPITokenFactory = class
private
FConsumerKey: String;
FConsumerSecret: String;
FRedirectUrl: String;
FTokenContainer: TObjectList;
public
constructor Create(key, secret: String; redirect: String = '');
destructor Destroy; override;
function CreateClientCredentials: TMixiAPIToken;
function RefreshToken(token: TMixiAPIToken): Boolean;
end;
ECreateTokenError = class(Exception);
const
TOKEN_DESCRIPTION = 'This is the mixi Graph API Project';
TOKEN_ENDPOINT = 'https://secure.mixi-platform.com/2/token';
HTTP_TIMEOUT = 300;
implementation
function TMixiAPIToken.isExpired;
begin
Result := FExpire < Now;
end;
procedure TMixiAPIToken.SaveToFile(Path: String);
var SL: TStringList;
begin
SL := TStringList.Create;
try
SL.Add(Encrypt(
CryptData(FAccessToken, TOKEN_DESCRIPTION)
));
SL.Add(Encrypt(
CryptData(FRefreshToken, TOKEN_DESCRIPTION)
));
SL.Add(DateTimeToStr(FExpire));
SL.SaveToFile(Path);
finally
SL.Free;
end;
end;
procedure TMixiAPIToken.LoadFromFile(Path: String);
var SL: TStringList;
cd: TCryptData;
begin
SL := TStringList.Create;
try
SL.LoadFromFile(Path);
if SL.Count < 3 then
raise Exception.Create('Invalid File');
cd := Decrypt(SL[0]);
if Not( cd.Description = TOKEN_DESCRIPTION ) then
raise Exception.Create('Invalid Access Token');
FAccessToken := cd.Data;
cd := Decrypt(SL[1]);
if Not( cd.Description = TOKEN_DESCRIPTION ) then
raise Exception.Create('Invalid Refresh Token');
FRefreshToken := cd.Data;
FExpire := StrToDateTime(SL[2]);
finally
SL.Free;
end;
end;
constructor TMixiAPITokenFactory.Create(key, secret, redirect: String);
begin
FConsumerKey := key;
FConsumerSecret := secret;
FRedirectUrl := redirect;
FTokenContainer := TObjectList.Create;
end;
destructor TMixiAPITokenFactory.Destroy;
begin
FTokenContainer.Free;
end;
function TMixiAPITokenFactory.CreateClientCredentials: TMixiAPIToken;
var req, res: TStringList;
ms: TMemoryStream;
json: ISuperObject;
token: TMixiAPIToken;
function CalcExpire(exp: Integer): TDateTime;
var hh, mm, ss: Integer;
begin
ss := exp mod 60;
mm := (exp div 60) mod 60;
hh := (exp div 3600) mod 24;
Result := Now + EncodeTime(hh, mm, ss, 0)
end;
begin
req := TStringList.Create;
res := TStringList.Create;
ms := TMemoryStream.Create;
try
req.Values['grant_type'] := 'client_credentials';
req.Values['client_id'] := FConsumerKey;
req.Values['client_secret'] := FConsumerSecret;
try
//Self.Post(TOKEN_ENDPOINT, req, ms);
UserAgent.Post(TOKEN_ENDPOINT, req, ms);
except
end;
ms.Position := 0;
res.LoadFromStream(ms);
json := SO(res.Text);
token := TMixiAPIToken.Create;
token.AccessToken := json['access_token'].AsString;
token.RefreshToken := json['refresh_token'].AsString;
token.Expire := CalcExpire(json['expires_in'].AsInteger);
token.TokenType := json['token_type'].AsString;
token.Scope := json['scope'].AsString;
FTokenContainer.Add(token);
Result := token;
finally
req.Free;
res.Free;
ms.Free;
end;
end;
function TMixiAPITokenFactory.RefreshToken(token: TMixiAPIToken): Boolean;
var req, res: TStringList;
ms: TMemoryStream;
json: ISuperObject;
function CalcExpire(exp: Integer): TDateTime;
var hh, mm, ss: Integer;
begin
ss := exp mod 60;
mm := (exp div 60) mod 60;
hh := (exp div 3600) mod 24;
Result := Now + EncodeTime(hh, mm, ss, 0)
end;
begin
req := TStringList.Create;
res := TStringList.Create;
ms := TMemoryStream.Create;
try
req.Values['grant_type'] := 'refresh_token';
req.Values['client_id'] := FConsumerKey;
req.Values['client_secret'] := FConsumerSecret;
req.Values['refresh_token'] := token.RefreshToken;
try
//Self.Post(TOKEN_ENDPOINT, req, ms);
UserAgent.Post(TOKEN_ENDPOINT, req, ms);
except
on E: Exception do
begin
raise ECreateTokenError.Create(E.Message);
end;
end;
ms.Position := 0;
res.LoadFromStream(ms);
json := SO(res.Text);
token.AccessToken := json['access_token'].AsString;
token.RefreshToken := json['refresh_token'].AsString;
token.Expire := CalcExpire(json['expires_in'].AsInteger);
token.TokenType := json['token_type'].AsString;
token.Scope := json['scope'].AsString;
finally
req.Free;
res.Free;
ms.Free;
end;
Result := True;
end;
end.
|
unit PAG0001L.View;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, LocalizarBase.View, cxGraphics,
cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver,
dxSkinOffice2016Colorful,
dxSkinOffice2016Dark, cxControls, cxContainer, cxEdit, cxStyles, cxCustomData,
cxFilter, cxData,
cxDataStorage, cxNavigator,
cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB,
cxDBData, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error,
FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView,
cxGridTableView,
cxGridDBTableView, cxGrid, cxTextEdit, cxLabel, dxGDIPlusClasses,
Vcl.ExtCtrls, Vcl.StdCtrls,
cxButtons, TPAGFORNECEDOR.Entidade.Model, ormbr.container.DataSet.interfaces,
ormbr.container.fdmemtable, Base.View.Interf, dxSkinBlack, dxSkinDarkRoom, dxSkinSilver;
type
TFPAG0001LView = class(TFLocalizarView, IBaseLocalizarView)
BtSalvar: TcxButton;
FdDadosCODIGO: TStringField;
FdDadosNOMEFANTASIA: TStringField;
VwDadosNOMEFANTASIA: TcxGridDBColumn;
FdDadosIDFORNECEDOR: TIntegerField;
VwDadosIDFORNECEDOR: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
procedure TePesquisaPropertiesChange(Sender: TObject);
procedure BtSalvarClick(Sender: TObject);
private
FCampoOrdem: string;
FContainer: IContainerDataSet<TTPAGFORNECEDOR>;
FCodigoSelecionado: string;
procedure filtrarRegistros;
public
class function New: IBaseLocalizarView;
procedure listarRegistros;
function exibir: string;
end;
var
FPAG0001LView: TFPAG0001LView;
implementation
{$R *.dfm}
{ TFPAG0001LView }
procedure TFPAG0001LView.BtSalvarClick(Sender: TObject);
begin
inherited;
FCodigoSelecionado := FdDadosCODIGO.AsString;
Close;
end;
function TFPAG0001LView.exibir: string;
begin
listarRegistros;
ShowModal;
Result := FCodigoSelecionado;
end;
procedure TFPAG0001LView.filtrarRegistros;
begin
FdDados.Filtered := false;
if not(TePesquisa.Text = EmptyStr) then
begin
FdDados.Filter := UpperCase(FCampoOrdem) + ' Like ''%' +
AnsiUpperCase(TePesquisa.Text) + '%''';
FdDados.Filtered := True;
end;
end;
procedure TFPAG0001LView.FormCreate(Sender: TObject);
begin
inherited;
FContainer := TContainerFDMemTable<TTPAGFORNECEDOR>.Create(FConexao, FdDados);
FCampoOrdem := 'NOMEFANTASIA';
Self.Width := Screen.Width - 450;
Self.Height := Screen.Height - 450;
end;
procedure TFPAG0001LView.listarRegistros;
begin
FContainer.OpenWhere('', FCampoOrdem);
end;
class function TFPAG0001LView.New: IBaseLocalizarView;
begin
Result := Self.Create(nil);
end;
procedure TFPAG0001LView.TePesquisaPropertiesChange(Sender: TObject);
begin
inherited;
filtrarRegistros;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.