text stringlengths 14 6.51M |
|---|
unit UDSummaryInfo;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeSummaryInfoDlg = class(TForm)
pnlSummaryInfo: TPanel;
lblApplication: TLabel;
lblAuthor: TLabel;
lblKeywords: TLabel;
lblComments: TLabel;
lblSubject: TLabel;
lblTitle: TLabel;
lblTemplate: TLabel;
lblAppName: TLabel;
editAuthor: TEdit;
editKeywords: TEdit;
memoComments: TMemo;
editTitle: TEdit;
editSubject: TEdit;
editTemplate: TEdit;
btnOk: TButton;
btnCancel: TButton;
btnClear: TButton;
cbSavePreviewPicture: TCheckBox;
procedure UpdateSummaryInfo;
procedure btnOkClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
rAppName : string;
rAuthor : string;
rComments : TStringList;
rKeywords : string;
rTemplate : string;
rSubject : string;
rTitle : string;
bSavePP : boolean;
end;
var
CrpeSummaryInfoDlg: TCrpeSummaryInfoDlg;
bSummaryInfo : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeSummaryInfoDlg.FormCreate(Sender: TObject);
begin
bSummaryInfo := True;
LoadFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeSummaryInfoDlg.FormShow(Sender: TObject);
begin
{Store current VCL settings}
rAppName := Cr.SummaryInfo.AppName;
rAuthor := Cr.SummaryInfo.Author;
rComments := TStringList.Create;
rComments.Assign(Cr.SummaryInfo.Comments);
rKeywords := Cr.SummaryInfo.Keywords;
rTemplate := Cr.SummaryInfo.Template;
rSubject := Cr.SummaryInfo.Subject;
rTitle := Cr.SummaryInfo.Title;
bSavePP := Cr.SummaryInfo.SavePreviewPicture;
cbSavePreviewPicture.Enabled := (Cr.Version.Crpe.Major > 7);
UpdateSummaryInfo;
end;
{------------------------------------------------------------------------------}
{ UpdateSummaryInfo }
{------------------------------------------------------------------------------}
procedure TCrpeSummaryInfoDlg.UpdateSummaryInfo;
var
OnOff : Boolean;
begin
OnOff := not IsStrEmpty(Cr.ReportName);
InitializeControls(OnOff);
if OnOff then
begin
lblAppName.Caption := Cr.SummaryInfo.AppName;
editAuthor.Text := Cr.SummaryInfo.Author;
memoComments.Lines.Assign(Cr.SummaryInfo.Comments);
editKeywords.Text := Cr.SummaryInfo.Keywords;
editTemplate.Text := Cr.SummaryInfo.Template;
editSubject.Text := Cr.SummaryInfo.Subject;
editTitle.Text := Cr.SummaryInfo.Title;
cbSavePreviewPicture.Checked := Cr.SummaryInfo.SavePreviewPicture;
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeSummaryInfoDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TMemo then
begin
TMemo(Components[i]).Clear;
TMemo(Components[i]).Color := ColorState(OnOff);
TMemo(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeSummaryInfoDlg.btnClearClick(Sender: TObject);
begin
Cr.SummaryInfo.Clear;
UpdateSummaryInfo;
end;
{------------------------------------------------------------------------------}
{ btnOKClick }
{------------------------------------------------------------------------------}
procedure TCrpeSummaryInfoDlg.btnOKClick(Sender: TObject);
begin
Cr.SummaryInfo.Author := editAuthor.Text;
Cr.SummaryInfo.Keywords := editKeywords.Text;
Cr.SummaryInfo.Template := editTemplate.Text;
Cr.SummaryInfo.Subject := editSubject.Text;
Cr.SummaryInfo.Title := editTitle.Text;
Cr.SummaryInfo.Comments := TStringList(memoComments.Lines);
Cr.SummaryInfo.SavePreviewPicture := cbSavePreviewPicture.Checked;
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpeSummaryInfoDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeSummaryInfoDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ModalResult = mrCancel then
begin
{Restore Settings}
{Cr.SummaryInfo.AppName := rAppName;} {read only}
Cr.SummaryInfo.Author := rAuthor;
Cr.SummaryInfo.Comments.Assign(rComments);
Cr.SummaryInfo.Keywords := rKeywords;
Cr.SummaryInfo.Template := rTemplate;
Cr.SummaryInfo.Subject := rSubject;
Cr.SummaryInfo.Title := rTitle;
Cr.SummaryInfo.SavePreviewPicture := bSavePP;
end;
rComments.Free;
bSummaryInfo := False;
Release;
end;
end.
|
unit UpdateForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, Spin,
ConcurrentTasks,
InflatablesList_Item,
InflatablesList_ItemShop,
InflatablesList_Manager;
type
TILItemShopUpdateItem = record
Item: TILItem;
ItemTitle: String;
ItemShop: TILItemShop;
Done: Boolean;
end;
TILItemShopUpdateList = array of TILItemShopUpdateItem;
TfUpdateForm = class(TForm)
pnlInfo: TPanel;
btnAction: TButton;
pbProgress: TProgressBar;
seNumberOfThreads: TSpinEdit;
lblNumberOfThreads: TLabel;
bvlSplit: TBevel;
lblLog: TLabel;
meLog: TMemo;
tmrUpdate: TTimer;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure btnActionClick(Sender: TObject);
procedure seNumberOfThreadsChange(Sender: TObject);
procedure meLogKeyPress(Sender: TObject; var Key: Char);
procedure tmrUpdateTimer(Sender: TObject);
private
fILManager: TILManager;
fUpdateList: TILItemShopUpdateList;
fUpdater: TCNTSManager;
fCanContinue: Boolean;
fProcessedIndex: Integer; // index of next item to be processed
fLoggedIndex: Integer; // index of next item to be logged
fDoneCount: Integer;
fLastItemName: String;
fMaxShopNameLen: Integer;
protected
procedure MakeLog(Index: Integer);
procedure ContinueProcessing;
procedure TaskFinishHandler(Sender: TObject; TaskIndex: Integer);
public
procedure Initialize(ILManager: TILManager);
procedure Finalize;
Function ShowUpdate(var UpdateList: TILItemShopUpdateList): Boolean;
end;
var
fUpdateForm: TfUpdateForm;
implementation
uses
StrRect,
InflatablesList_Utils;
{$R *.dfm}
const
IL_NR_OF_THREADS_COEF = 2;
//==============================================================================
type
TILUpdateTask = class(TCNTSTask)
private
fProcessingIndex: Integer;
fItemShop: TILItemShop;
public
constructor Create(ILManager: TILManager; ItemShop: TILItemShop; ProcessingIndex: Integer);
destructor Destroy; override;
Function Main: Boolean; override;
property ProcessingIndex: Integer read fProcessingIndex;
property ItemShop: TILItemShop read fItemShop;
end;
//==============================================================================
constructor TILUpdateTask.Create(ILManager: TILManager; ItemShop: TILItemShop; ProcessingIndex: Integer);
var
Index: Integer;
begin
inherited Create;
fProcessingIndex := ProcessingIndex;
fItemShop := TILItemShop.CreateAsCopy(ItemShop,True);
// resolve reference and make local copy of processing settings
Index := ILManager.ShopTemplateIndexOf(fItemShop.ParsingSettings.TemplateReference);
If Index >= 0 then
fItemShop.ReplaceParsingSettings(ILManager.ShopTemplates[Index].ParsingSettings);
end;
//------------------------------------------------------------------------------
destructor TILUpdateTask.Destroy;
begin
fItemShop.Free;
inherited;
end;
//------------------------------------------------------------------------------
Function TILUpdateTask.Main: Boolean;
begin
If not Terminated then
Result := fItemShop.Update
else
Result := False;
Cycle;
end;
//==============================================================================
//------------------------------------------------------------------------------
//==============================================================================
procedure TfUpdateForm.MakeLog(Index: Integer);
var
TagStr: String;
begin
If not IL_SameText(fLastItemName,fUpdateList[Index].ItemTitle) then
begin
If meLog.Lines.Count > 0 then
meLog.Lines.Add(''); // empty line
meLog.Lines.Add(fUpdateList[Index].ItemTitle + sLineBreak);
fLastItemName := fUpdateList[Index].ItemTitle;
end;
If fUpdateList[Index].ItemShop.Selected then
TagStr := ' * '
else
TagStr := ' ';
meLog.Lines.Add(IL_Format('%s%s %s... %s',[TagStr,fUpdateList[Index].ItemShop.Name,
StringOfChar('.',fMaxShopNameLen - Length(fUpdateList[Index].ItemShop.Name)),
fUpdateList[Index].ItemShop.LastUpdateMsg]));
end;
//------------------------------------------------------------------------------
procedure TfUpdateForm.ContinueProcessing;
var
Index: Integer;
begin
If Assigned(fUpdater) and fCanContinue then
while (fProcessedIndex <= High(fUpdateList)) and
(fUpdater.GetActiveTaskCount < fUpdater.MaxConcurrentTasks) do
begin
Index := fUpdater.AddTask(
TILUpdateTask.Create(fILManager,fUpdateList[fProcessedIndex].ItemShop,fProcessedIndex));
fUpdater.StartTask(Index);
Inc(fProcessedIndex);
end;
end;
//------------------------------------------------------------------------------
procedure TfUpdateForm.TaskFinishHandler(Sender: TObject; TaskIndex: Integer);
begin
Inc(fDoneCount);
// retrieve results from the task
with TILUpdateTask(fUpdater.Tasks[TaskIndex].TaskObject) do
begin
fUpdateList[ProcessingIndex].ItemShop.SetValues(ItemShop.LastUpdateMsg,
ItemShop.LastUpdateRes,ItemShop.Available,ItemShop.Price);
fUpdateList[ProcessingIndex].Done := True;
end;
// log
while fLoggedIndex <= High(fUpdateList) do
begin
If fUpdateList[fLoggedIndex].Done then
begin
MakeLog(fLoggedIndex);
Inc(fLoggedIndex);
end
else Break{while...};
end;
//progress
If fDoneCount < Length(fUpdateList) then
begin
// show progress
If Length(fUpdateList) > 0 then
pbProgress.Position := Trunc((fDoneCount / Length(fUpdateList)) * pbProgress.Max)
else
pbProgress.Position := pbProgress.Max;
pnlInfo.Caption := IL_Format('%d item shops ready for update',[Length(fUpdateList) - fDoneCount]);
end
else
begin
pnlInfo.Caption := 'All shops updated, see log for details';
pbProgress.Position := pbProgress.Max;
btnAction.Tag := 2;
btnAction.Caption := 'Done';
end;
end;
//==============================================================================
procedure TfUpdateForm.Initialize(ILManager: TILManager);
begin
fILManager := ILManager;
fUpdater := nil;
seNumberOfThreads.Value := TCNTSManager.GetProcessorCount * IL_NR_OF_THREADS_COEF;
end;
//------------------------------------------------------------------------------
procedure TfUpdateForm.Finalize;
begin
// nothing to do here
end;
//------------------------------------------------------------------------------
Function TfUpdateForm.ShowUpdate(var UpdateList: TILItemShopUpdateList): Boolean;
var
i: Integer;
begin
Result := False;
If Length(UpdateList) > 0 then
begin
// init form
pnlInfo.Caption := IL_Format('%d item shops ready for update',[Length(UpdateList)]);
btnAction.Tag := 0;
btnAction.Caption := 'Start';
pbProgress.Position := 0;
meLog.Clear;
// init list of shops for processing
fUpdateList := UpdateList;
For i := Low(fUpdateList) to High(fUpdateList) do
fUpdateList[i].Done := False; // should be false atm, but to be sure
// init processing vars
fProcessedIndex := 0;
fLoggedIndex := 0;
fDoneCount := 0;
fLastItemName := '';
// calculate indentation correction
fMaxShopNameLen := 0;
For i := Low(fUpdateList) to High(fUpdateList) do
If Length(fUpdateList[i].ItemShop.Name) > fMaxShopNameLen then
fMaxShopNameLen := Length(fUpdateList[i].ItemShop.Name);
// create updater and show the window
tmrUpdate.Enabled := True;
fUpdater := TCNTSManager.Create(True);
try
fUpdater.MaxConcurrentTasks := seNumberOfThreads.Value;
fUpdater.OnTaskCompleted := TaskFinishHandler;
fCanContinue := False;
ShowModal;
fUpdater.WaitForRunningTasksToComplete;
finally
FreeAndNil(fUpdater);
end;
tmrUpdate.Enabled := False;
// save log
If (meLog.Lines.Count > 0) and not fILManager.StaticSettings.NoUpdateAutoLog then
meLog.Lines.SaveToFile(StrToRTL(fILManager.StaticSettings.ListPath + fILManager.StaticSettings.ListName + '.update.log'));
// return the changed list (done flag is used)
UpdateList := fUpdateList;
// indicate whether something was done
For i := Low(UpdateList) to High(UpdateList) do
If UpdateList[i].Done then
begin
Result := True;
Break{For i};
end;
end
else MessageDlg('No shop to update.',mtInformation,[mbOK],0);
end;
//==============================================================================
procedure TfUpdateForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
fCanContinue := False;
CanClose := True;
end;
//------------------------------------------------------------------------------
procedure TfUpdateForm.btnActionClick(Sender: TObject);
begin
case btnAction.Tag of
0: begin
// start
btnAction.Tag := 1;
btnAction.Caption := 'Stop';
fCanContinue := True;
ContinueProcessing;
end;
1: begin
// stop
btnAction.Tag := 0;
btnAction.Caption := 'Start';
fCanContinue := False;
end;
else
// finished, do nothing
Close;
end;
end;
//------------------------------------------------------------------------------
procedure TfUpdateForm.seNumberOfThreadsChange(Sender: TObject);
begin
If Assigned(fUpdater) then
fUpdater.MaxConcurrentTasks := seNumberOfThreads.Value;
end;
//------------------------------------------------------------------------------
procedure TfUpdateForm.meLogKeyPress(Sender: TObject; var Key: Char);
begin
If Key = ^A then
begin
meLog.SelectAll;
Key := #0;
end;
end;
//------------------------------------------------------------------------------
procedure TfUpdateForm.tmrUpdateTimer(Sender: TObject);
begin
If Assigned(fUpdater) then
begin
fUpdater.Update;
fUpdater.ClearCompletedTasks;
If fCanContinue then
ContinueProcessing;
end;
end;
end.
|
unit Reports;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, uniGUITypes, uniGUIAbstractClasses,uniDateUtils,
uniGUIClasses, uniGUIForm, BaseForm, siComp, uniGUIBaseClasses, uniPanel,
uniMultiItem, uniComboBox, uniDBComboBox, uniDBLookupComboBox, Data.DB,
DBAccess, Uni, MemDS, uniBasicGrid, uniDBGrid, uniButton, uniDateTimePicker,
uniMemo, uniRadioButton, frxClass, frxDBSet, uniCheckBox, uniLabel,
uniSpinEdit, uniRadioGroup, uniGridExporters;
type
TReportsF = class(TBaseFormF)
pnlHead: TUniContainerPanel;
EstatesQry: TUniQuery;
EstatesQryID: TIntegerField;
EstatesQryownerID: TIntegerField;
EstatesQryestNo: TIntegerField;
EstatesQryestName: TWideStringField;
EstatesQryestDistrict: TWideStringField;
EstatesQryestStreet: TWideStringField;
EstatesQryUnitsCount: TIntegerField;
EstatesQryUnitsRented: TIntegerField;
EstatesSrc: TUniDataSource;
ReportQry: TUniQuery;
EstQryS: TUniDataSource;
pnlEst: TUniContainerPanel;
EstateCB: TUniDBLookupComboBox;
cbEstReport: TUniComboBox;
pnlCtrl: TUniContainerPanel;
pnlDateCont: TUniContainerPanel;
FromD: TUniDateTimePicker;
TooD: TUniDateTimePicker;
estFinRpt1: TUniQuery;
UniQuery1: TUniQuery;
estFinRptS: TUniDataSource;
estMintRpt2: TUniQuery;
estMintRptS: TUniDataSource;
UniQuery2: TUniQuery;
TempRepQ: TUniQuery;
UniQuery3: TUniQuery;
UniContainerPanel1: TUniContainerPanel;
pnlUnit: TUniContainerPanel;
UniContainerPanel2: TUniContainerPanel;
rbEstRpt: TUniRadioButton;
rbUntRpt: TUniRadioButton;
UnitsQry: TUniQuery;
UnitsSrc: TUniDataSource;
UnitCB: TUniDBLookupComboBox;
cbUnitReport: TUniComboBox;
UnitsQryID: TIntegerField;
UnitsQryUnit: TWideStringField;
UnitsQryRooms: TWideStringField;
UnitsQryFloor: TWideStringField;
UnitsQryPrice1: TFloatField;
UnitsQryPrice2: TFloatField;
UnitsQryPrice3: TFloatField;
UnitsQryPrice4: TFloatField;
UnitsQryNotes: TWideStringField;
UnitsQryElectricity: TBooleanField;
UnitsQryKitchen: TBooleanField;
UnitsQryConditions: TBooleanField;
UnitsQryESTID: TIntegerField;
UnitsQryownerID: TIntegerField;
UnitsQryisRented: TBooleanField;
UniContainerPanel3: TUniContainerPanel;
UniContainerPanel4: TUniContainerPanel;
pnlCont: TUniContainerPanel;
UniContainerPanel6: TUniContainerPanel;
lookContractQ: TUniQuery;
LookContractQs: TUniDataSource;
ContractCB: TUniDBLookupComboBox;
cbContReport: TUniComboBox;
UniContainerPanel7: TUniContainerPanel;
rbConRpt: TUniRadioButton;
Lpnl2: TUniContainerPanel;
Lpnl1: TUniContainerPanel;
Lpnl3: TUniContainerPanel;
UniContainerPanel5: TUniContainerPanel;
btnExcute: TUniButton;
btnPrint: TUniButton;
QRY: TUniQuery;
QRYdataSrc: TUniDataSource;
frxDBDataset1: TfrxDBDataset;
frxReport1: TfrxReport;
chkAll: TUniCheckBox;
lblRecNo: TUniLabel;
UniSpinDays: TUniSpinEdit;
ESTReports: TUniButton;
UNITReports: TUniButton;
CONTReports: TUniButton;
OFFICEReports: TUniButton;
lookContractQContractID: TIntegerField;
lookContractQName: TWideStringField;
lookContractQEstNo: TIntegerField;
lookContractQestName: TWideStringField;
lookContractQestDistrict: TWideStringField;
lookContractQunitNo: TIntegerField;
lookContractQUnit: TWideStringField;
lookContractQFloor: TWideStringField;
pnlOfficeRpt: TUniContainerPanel;
UniRadioGroup1: TUniRadioGroup;
VouchTypeQry: TUniQuery;
VouchTypeQryID: TIntegerField;
VouchTypeQrySection: TWideStringField;
VouchTypeQryPSection: TIntegerField;
DS1: TUniDataSource;
CBvoucherType: TUniDBLookupComboBox;
UniContainerPanel8: TUniContainerPanel;
UniGridExcelExporter1: TUniGridExcelExporter;
Hpnl: TUniContainerPanel;
pnlDetails: TUniContainerPanel;
ReportQryGrid: TUniDBGrid;
BTNpnl: TUniContainerPanel;
btnExport: TUniButton;
procedure btnExcuteClick(Sender: TObject);
procedure ReportQryGridColumnSummary(Column: TUniDBGridColumn;
GroupFieldValue: Variant);
procedure ReportQryGridColumnSummaryResult(Column: TUniDBGridColumn;
GroupFieldValue: Variant; Attribs: TUniCellAttribs; var Result: string);
procedure btnPrintClick(Sender: TObject);
procedure rbEstRptClick(Sender: TObject);
procedure rbUntRptClick(Sender: TObject);
procedure rbConRptClick(Sender: TObject);
procedure frxReport1BeforePrint(Sender: TfrxReportComponent);
procedure chkAllChange(Sender: TObject);
procedure ReportQryAfterScroll(DataSet: TDataSet);
procedure cbContReportChange(Sender: TObject);
procedure pnlDetailsClick(Sender: TObject);
procedure ESTReportsClick(Sender: TObject);
procedure CONTReportsClick(Sender: TObject);
procedure UNITReportsClick(Sender: TObject);
procedure UniRadioGroup1Click(Sender: TObject);
procedure OFFICEReportsClick(Sender: TObject);
procedure ReportQryAfterOpen(DataSet: TDataSet);
procedure btnExportClick(Sender: TObject);
private
{ Private declarations }
NetAmount,Cred,Deb:Real;
ReportFName,RepTypeP,RepType2P ,Fdat,Tdat:String;
procedure ResetSQL(TableQry : String);
procedure LoadReportSTR();
public
{ Public declarations }
end;
function ReportsF: TReportsF;
implementation
{$R *.dfm}
uses
MainModule, uniGUIApplication, G_Funcs, ShowReport, ReportsDataM, Main,
FrToolsData;
function ReportsF: TReportsF;
begin
Result := TReportsF(UniMainModule.GetFormInstance(TReportsF));
end;
//==============================================================================
procedure TReportsF.ResetSQL(TableQry : String);
var SqlTxt:String;
begin
ReportQry.Close;
ReportQry.SQL.Clear;
ReportQry.SQL.Text.Empty;
//>>>>>>>>>>>>>>>>>>>>>> 1- ESTATE Reports >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// ExtWhereCond := ' + ' H.PeriodID ' + gConcatStrFun + ' H.TrxType ' + gConcatStrFun + ' H.TrxNo = ''' + fTrxID + ''' ';
if TableQry='EST' then begin
SqlTxt:= 'Select E.TransNo ,E.EstNo, U.Unit ,E.EXP,E.Income,E.Expense,E.TranDate '
+'From EstateBalance E '
+' left Join Units U On E.UnitNo = U.ID '
+'where E.TransNo is not null ';
end;
if TableQry='ESTcontracts' then begin
SqlTxt:= 'SELECT ContractID,conDate,EstNo,Unit,Name,'
+' contF, contT, RentAmount, Payments FROM contracts_rv '
+'where ContractID is not null And Active = True ' ;
if not EstateCB.IsBlank then begin
SqlTxt := SqlTxt + ' And EstNo = :EstN ';
end;
SqlTxt := SqlTxt +' UNION ' // اضافة الشقق الشاغرة
+'SELECT 0 , 0 , ESTID, Unit, concat(floor,'' - '',Rooms,'' [ 1- '',Price1,'' ] [ 2- '',Price2,'' ] [ 4- '',Price4,'' ]'') , Null , Null , 0 , isRented '
+' From Units '
+'Where isRented = False ';//old ID not in (Select UnitNo From Contracts) ';
if not EstateCB.IsBlank then begin
SqlTxt := SqlTxt + ' and ESTID = :EstN ';
end;
end;
if TableQry='ESTcontMove' then begin
SqlTxt:= 'SELECT ContractID,conDate,EstNo,Unit,'
+' contF, contT, RentAmount, TerminDate, '
+' DATEDIFF( :Edate,TerminDate) as EmptyDays, '
+' (RentAmount/360) * DATEDIFF( :Edate , TerminDate ) as EmpDaysVal '
+' FROM contracts_rv '
+'where Active = False '; //Expired = True ';//and TerminDate < CURDATE()' ;
end;
//>>>>>>>>>>>>>>>>>>>>>>>---------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//>>>>>>>>>>>>>>>>>>>>>> 3- Contracts Reports >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//>>>>>>>>>>>>>>>>>>>>>>>---------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
if TableQry='AllContracts' then // 0-All Contracts
SqlTxt:= 'SELECT ContractID, conDate, contF, contT, Payments, RentAmount, '
+'Name ,EstNo, Unit From contracts_rv Where ContractID is not null ';
if TableQry='Expired' then // 1- Expired Today > COntTO. and it is Active
SqlTxt:= 'SELECT ContractID, conDate, contF, contT, Payments, RentAmount, '
+' Name ,EstNo, Unit, Expired From contracts_rv Where ContractID is not null And Active = True AND contT < CURDATE()';
if TableQry='NotExpired' then // 2-Not Expired = ACTIVE = True
SqlTxt:= 'SELECT ContractID, conDate, contF, contT, Payments, RentAmount, '
+'Name ,EstNo, Unit From contracts_rv Where ContractID is not null And Active = True ';
if TableQry='Terminated' then // 3-Terminated= ACTIVE = False and Termination = true
SqlTxt:= 'SELECT ContractID, conDate, contF, contT, Payments, RentAmount, '
+'Name ,EstNo, Unit, Termination,TerminDate From contracts_rv Where ContractID is not null And Active = FALSE And Termination = TRUE ';
if TableQry='AboToExpire' then // 4-about to Expire
SqlTxt:= 'SELECT ContractID, conDate, contF, contT, Payments, RentAmount, '
+'Name ,EstNo, Unit From contracts_rv Where ContractID is not null And Active = True '
+'And DATEDIFF( contT , CURDATE() ) < :Ndays ';
if TableQry='PaidContPmts' then // 5- Paid Contract Payments
SqlTxt:= 'SELECT * FROM payments where Paid = 1';
if TableQry='UnPaidContPmts' then // 5- Not Paid Contract Payments
SqlTxt:= 'SELECT * FROM payments where Paid = 0';
ReportQry.SQL.Text:= SqlTxt;
end;
procedure TReportsF.UniRadioGroup1Click(Sender: TObject);
begin
inherited;
rbEstRpt.Checked := false;
rbUntRpt.Checked := false;
rbConRpt.Checked := false;
VouchTypeQry.Close;
VouchTypeQry.SQL.Clear;
if UniRadioGroup1.ItemIndex = 0 then
VouchTypeQry.SQL.Text:='Select * from secid where PSection=2 '
else
VouchTypeQry.SQL.Text:='Select * from secid where PSection=1 ';
VouchTypeQry.Open;
end;
procedure TReportsF.UNITReportsClick(Sender: TObject);
begin
inherited;
end;
//------------------------------------------------------
procedure TReportsF.LoadReportSTR();
begin
Fdat:=''; Tdat:='';
if rbEstRpt.Checked then begin // EST,REPORTS.
RepTypeP := cbEstReport.Text;
if EstateCB.IsBlank then
RepType2P := 'جميع العمائر'
else
RepType2P := EstateCB.Text;
case cbEstReport.ItemIndex of
0: begin
ReportFName := 'EstFinancial';
if not chkAll.Checked then begin
Fdat := ' من: ' + DateToStr(FromD.DateTime);
Tdat := ' إلى: ' + DateToStr(TooD.DateTime);
end;
end;
1: begin
ReportFName := 'EstMaintenance';
if not chkAll.Checked then begin
Fdat := ' من: ' + DateToStr(FromD.DateTime);
Tdat := ' إلى: ' + DateToStr(TooD.DateTime);
end;
end;
2 : begin
ReportFName := 'EstPaids';
if not chkAll.Checked then begin
Fdat := ' من: ' + DateToStr(FromD.DateTime);
Tdat := ' إلى: ' + DateToStr(TooD.DateTime);
end;
end;
3: ReportFName := 'EstContracts';
4: begin
ReportFName := 'EstContMove';
Fdat := ' من تاريخ الاخلاء ' ;// + DateToStr(FromD.DateTime);
if chkAll.Checked then
Tdat := ' إلى: ' + DateToStr(Date)
else
Tdat := ' إلى: ' + DateToStr(TooD.DateTime);
end;
5: begin
ReportFName := 'EstVacantUnits';
end;
end;
end;
//>>>>>>>>>>>>>>>>>>>
if rbConRpt.Checked then begin // Contracts ,REPORTS.
RepTypeP := cbContReport.Text;
case cbContReport.ItemIndex of
0,1,2,4 : begin
ReportFName := 'ContAll';
if not chkAll.Checked then begin
Fdat := ' من: ' + DateToStr(FromD.DateTime);
Tdat := ' إلى: ' + DateToStr(TooD.DateTime);
end;
end;
end;
end;
//>>>>>>>>>>>>>>>>>>> OFFICE REPORTS >>>>>>>>>>>>>>>>>>>>>>>>>
if (UniRadioGroup1.ItemIndex =0) Or (UniRadioGroup1.ItemIndex =1) then begin
ReportFName :='OfficeVoch';
RepType2P := CBvoucherType.Text;
if not chkAll.Checked then begin
Fdat := ' من: ' + DateToStr(FromD.DateTime);
Tdat := ' إلى: ' + DateToStr(TooD.DateTime);
end;
end;
DataFrTools.MyFrxLoad(frxReport1,ReportFName);
end;
procedure TReportsF.OFFICEReportsClick(Sender: TObject);
var SqlTxt:String;
begin
inherited;
ReportQry.Close;
ReportQry.SQL.Clear;
ReportQry.SQL.Text.Empty;
//if UniRadioGroup1.ItemIndex = 0 then
//`VID`, `vNo`, `vType`, `vSubType`, `vEXP`, `vIn`, `vOut`, `vDate` FROM `vouchers
SqlTxt:= 'SELECT V.VID TransNo, S.Section, V.vEXP EXP, V.vIn Income, V.vOut Expense, V.vDate TranDate'
+' FROM vouchers V Left Join SecID S on V.vSubType = S.ID '
+' where vType = '+VouchTypeQryPSection.AsString ;
if not CBvoucherType.IsBlank then
SqlTxt:= SqlTxt + ' AND vSubType = '+VouchTypeQryID.AsString;
ReportQry.SQL.Text:= SqlTxt;
end;
procedure TReportsF.pnlDetailsClick(Sender: TObject);
begin
inherited;
end;
//------------------------------------------------------
//------------------------------------------------------
//------------------------------------------------------
//------------------------------------------------------
procedure TReportsF.btnExcuteClick(Sender: TObject);
//var SdateP ,EdateP : TDate;
begin
inherited;
// SdateP := FromD.DateTime;
// EdateP := TooD.DateTime;
lblRecNo.Caption := '0';
if rbEstRpt.Checked then
ESTReportsClick(Sender);
if rbConRpt.Checked then
CONTReportsClick(Sender);
// if rbEstRpt.Checked then
if UniRadioGroup1.ItemIndex = 0 then
OFFICEReportsClick(Sender);
if UniRadioGroup1.ItemIndex = 1 then
OFFICEReportsClick(Sender);
// if rbEstRpt.Checked then begin //>>>>>>>> Estates Reports >>>>>>>>
//
// ResetSQL('EST');
// //0-ALL Transactions
// if cbEstReport.ItemIndex = 1 then //1-Maintenance Transactions
// ReportQry.SQL.Add('And TransType = 2 ');
// if cbEstReport.ItemIndex = 2 then //2-Income Transactions
// ReportQry.SQL.Add('And TransType = 1 ');
// if cbEstReport.ItemIndex = 3 then //3-Contracts on Estate
// ResetSQL('ESTcontracts');
// if cbEstReport.ItemIndex = 4 then //4-Contracts Move&Expire on Estate
// begin
// ResetSQL('ESTcontMove');
// ReportQry.ParamByName('Edate').AsDate := Date; //Get Till the CURDATE(). as Original
// end;
//
// if cbEstReport.ItemIndex = 5 then // Vacant UNITS.
// ReportQry.SQL.Text:='Select EstID as EstNo, Unit,Floor, Rooms, isRented from Units where isRented = False';
//
// if not chkAll.Checked then begin // Select A Dates ( DATE Between )12/15/2020
// case cbEstReport.ItemIndex of
// 0,1,2:begin
// ReportQry.SQL.Add('And TranDate between :Sdate and :Edate ');
// ReportQry.ParamByName('Sdate').AsDate := SdateP;
// ReportQry.ParamByName('Edate').AsDate := EdateP;
// end;
// 3 :begin
// ReportQry.SQL.Add('And conDate between :Sdate and :Edate ');
// ReportQry.ParamByName('Sdate').AsDate := SdateP;
// ReportQry.ParamByName('Edate').AsDate := EdateP;
// end;
// 4 : begin ReportQry.ParamByName('Edate').AsDate := EdateP;//Today
// //if Selected Date then CHange from Original CURDATE() to selected Date
//
// end;
//
// end;
//
//
//
// end;
//
// //----
//
// case cbEstReport.ItemIndex of // Parameters For Selected Estate ID.
// 0,1,2,4:begin
// if not EstateCB.IsBlank then begin
// ReportQry.SQL.Add(' And EstNo = :Est ');
// ReportQry.ParamByName('EST').AsInteger := EstatesQryestNo.Value;
// end;
// end;
// 5: begin
// if not EstateCB.IsBlank then begin
// ReportQry.SQL.Add(' And EstID = :Est ');
// ReportQry.ParamByName('EST').AsInteger := EstatesQryestNo.Value;
// end
// end;
// 3: begin
// if not EstateCB.IsBlank then
// ReportQry.ParamByName('EstN').AsInteger := EstatesQryestNo.Value
// end;
//
// end;
//
//
//
//
//
// end;
//--//>>>>>>>>--------//>>>>>>>>------//>>>>>>>>--------------........دددددددددددددددد
// if rbConRpt.Checked then begin //>>>>>>>> 3 Cotract Reports >>>>>>>>
//{ All Contracts
//Expired Contracts
//Not Expired Contracts
//ReNewed Contracts
//About to Expire}
//
// if cbContReport.ItemIndex = 0 then //0-ALL Contracts
// ResetSQL('AllContracts');
// if cbContReport.ItemIndex = 1 then //1-Expired Contracts
// ResetSQL('Expired');
// if cbContReport.ItemIndex = 2 then //2-Not Expired Contracts
// ResetSQL('NotExpired');
//// if cbContReport.ItemIndex = 3 then //3-ReNewed Contracts
//// ResetSQL('NotExpired');
// if cbContReport.ItemIndex = 4 then begin//4-About to Expire
// ResetSQL('AboToExpire');
// ReportQry.ParamByName('Ndays').AsInteger := UniSpinDays.Value;
// end;
//
// if cbContReport.ItemIndex = 5 then begin // Paid Payments On Selected Contract.
// ResetSQL('PaidContPmts');
// end;
//
// if not chkAll.Checked then begin // Select A Dates
// case cbContReport.ItemIndex of
// 0,1,2,3,4:begin
// ReportQry.SQL.Add('And conDate between :Sdate and :Edate ');
// ReportQry.ParamByName('Sdate').AsDate := SdateP;
// ReportQry.ParamByName('Edate').AsDate := EdateP;
// end;
//
//// 4 : begin
////
//// end;
//
// end;
//
//
//
// end;
//
// end;
//
//
//===++++LAST THINGS++++========
ReportQry.Open;
// AdjustFieldsWidth(ReportQry );
AdjustGridLng(ReportQryGrid);
end;
procedure TReportsF.btnExportClick(Sender: TObject);
begin
inherited;
ReportQryGrid.Exporter.Exporter := UniGridExcelExporter1;
ReportQryGrid.Exporter.ExportGrid;
end;
procedure TReportsF.btnPrintClick(Sender: TObject);
begin
inherited;
LoadReportSTR();
MainForm.DwnRepoFile:=false;
DataFrTools.MyFrxShow(frxReport1);
end;
procedure TReportsF.cbContReportChange(Sender: TObject);
begin
inherited;
UniSpinDays.Visible:= cbContReport.ItemIndex = 4;
end;
procedure TReportsF.chkAllChange(Sender: TObject);
begin
inherited;
FromD.Enabled:= not chkAll.Checked;
TooD.Enabled := not chkAll.Checked;
end;
procedure TReportsF.CONTReportsClick(Sender: TObject);
var SdateP ,EdateP : TDate;
begin
inherited;
SdateP := FromD.DateTime;
EdateP := TooD.DateTime;
// >>>>>>>> Estates Reports >>>>>>>>
if cbContReport.ItemIndex = 0 then //0-ALL Contracts
ResetSQL('AllContracts');
if cbContReport.ItemIndex = 1 then //1-Expired Contracts today is > from ContTo
ResetSQL('Expired');
if cbContReport.ItemIndex = 2 then //2-Not Expired Contracts ACTIVE = TRUE.
ResetSQL('NotExpired');
if cbContReport.ItemIndex = 3 then //3-Terminated Contracts
ResetSQL('Terminated');
if cbContReport.ItemIndex = 4 then begin//4-About to Expire
ResetSQL('AboToExpire');
ReportQry.ParamByName('Ndays').AsInteger := UniSpinDays.Value;
end;
if cbContReport.ItemIndex = 5 then // Paid Payments On Selected Contract.
ResetSQL('PaidContPmts');
if cbContReport.ItemIndex = 6 then // Not Paid Payments On Selected Contract.
ResetSQL('UnPaidContPmts');
if not chkAll.Checked then begin // Select A Dates
case cbContReport.ItemIndex of
0,1,2,3,4:begin
ReportQry.SQL.Add('And conDate between :Sdate and :Edate ');
ReportQry.ParamByName('Sdate').AsDate := SdateP;
ReportQry.ParamByName('Edate').AsDate := EdateP;
end;
// 4 : begin
//
// end;
end;
end;
case cbContReport.ItemIndex of // Parameters For Selected Contract ID.
5,6:begin
if not ContractCB.IsBlank then begin
ReportQry.SQL.Add(' And ContractNo = :ConID ');
ReportQry.ParamByName('ConID').AsInteger := lookContractQContractID.Value;
end;
end;
end;
// >>>>>>>> CONTRACT Reports >>>>>>>>--------------------------------------
end;
//----------------------------------------------------------------
procedure TReportsF.ESTReportsClick(Sender: TObject);
var SdateP ,EdateP : TDate;
begin
inherited;
SdateP := FromD.DateTime;
EdateP := TooD.DateTime;
// >>>>>>>> Estates Reports >>>>>>>>
ResetSQL('EST');
//0-ALL Transactions
if cbEstReport.ItemIndex = 1 then //1-Maintenance Transactions
ReportQry.SQL.Add('And TransType = 2 ');
if cbEstReport.ItemIndex = 2 then //2-Income Transactions
ReportQry.SQL.Add('And TransType = 1 ');
if cbEstReport.ItemIndex = 3 then //3-Contracts on Estate
ResetSQL('ESTcontracts');
if cbEstReport.ItemIndex = 4 then //4-Contracts Move&Expire on Estate
begin
ResetSQL('ESTcontMove');
ReportQry.ParamByName('Edate').AsDate := Date; //Get Till the CURDATE(). as Original
end;
if cbEstReport.ItemIndex = 5 then // Vacant UNITS.
ReportQry.SQL.Text:='Select EstID as EstNo, Unit,Floor, Rooms,Price1,Price2,Price4, isRented from Units where isRented = False';
if not chkAll.Checked then begin // Select A Dates ( DATE Between )12/15/2020
case cbEstReport.ItemIndex of
0,1,2:begin
ReportQry.SQL.Add('And TranDate between :Sdate and :Edate ');
ReportQry.ParamByName('Sdate').AsDate := SdateP;
ReportQry.ParamByName('Edate').AsDate := EdateP;
end;
3 :begin
ReportQry.SQL.Add('And conDate between :Sdate and :Edate ');
ReportQry.ParamByName('Sdate').AsDate := SdateP;
ReportQry.ParamByName('Edate').AsDate := EdateP;
end;
4 : begin ReportQry.ParamByName('Edate').AsDate := EdateP;//Today
//if Selected Date then CHange from Original CURDATE() to selected Date
end;
end;
end;
//----
case cbEstReport.ItemIndex of // Parameters For Selected Estate ID.
0,1,2,4:begin
if not EstateCB.IsBlank then begin
ReportQry.SQL.Add(' And EstNo = :Est ');
ReportQry.ParamByName('EST').AsInteger := EstatesQryestNo.Value;
end;
end;
5: begin
if not EstateCB.IsBlank then begin
ReportQry.SQL.Add(' And EstID = :Est ');
ReportQry.ParamByName('EST').AsInteger := EstatesQryestNo.Value;
end
end;
3: begin
if not EstateCB.IsBlank then
ReportQry.ParamByName('EstN').AsInteger := EstatesQryestNo.Value
end;
end;
// >>>>>>>> Estates Reports >>>>>>>>--------------------------------------
end;
procedure TReportsF.ReportQryAfterOpen(DataSet: TDataSet);
begin
inherited;
ReportQry.Last;
//frxDBDataset1.re
end;
procedure TReportsF.ReportQryAfterScroll(DataSet: TDataSet);
begin
inherited;
lblRecNo.Caption := IntToStr(ReportQry.RecNo) +'/'+ IntToStr(ReportQry.RecordCount);
end;
procedure TReportsF.ReportQryGridColumnSummary(Column: TUniDBGridColumn;
GroupFieldValue: Variant);
begin
inherited;
if SameText(Column.FieldName, 'Income') then //012
begin
if Column.AuxValue = NULL then Column.AuxValue:=0.0;
Column.AuxValue := Column.AuxValue + Column.Field.AsFloat;
Cred:= Column.AuxValue ;
end
else if SameText(Column.FieldName, 'Expense') then //012
begin
if Column.AuxValue = NULL then Column.AuxValue:=0.0;
Column.AuxValue := Column.AuxValue + Column.Field.AsFloat ;
Deb:= Column.AuxValue ;
end
// ------------------
else if SameText(Column.FieldName, 'RentAmount') then //3
begin
if Column.AuxValue = NULL then Column.AuxValue:=0.0;
Column.AuxValue := Column.AuxValue + Column.Field.AsFloat ;
Deb:= Column.AuxValue ;
end
// ------------------
else if SameText(Column.FieldName, 'EmptyDays') then //4
begin
if Column.AuxValue = NULL then Column.AuxValue:= 0;
Column.AuxValue := Column.AuxValue + Column.Field.AsInteger ;
Deb:= Column.AuxValue ;
end
else if SameText(Column.FieldName, 'EmpDaysVal') then //4
begin
if Column.AuxValue = NULL then Column.AuxValue:=0.0;
Column.AuxValue := Column.AuxValue + Column.Field.AsFloat ;
Deb:= Column.AuxValue ;
end
// ------------------
;
NetAmount := Cred-Deb;
end;
procedure TReportsF.ReportQryGridColumnSummaryResult(Column: TUniDBGridColumn;
GroupFieldValue: Variant; Attribs: TUniCellAttribs; var Result: string);
var I,E : Real;
begin
inherited;
if SameText(Column.FieldName, 'Income') then
begin
I:=Column.AuxValue;
Result:= FormatFloat('#,##0.##', I); // FormatFloat('0,0.00 ', I);
Attribs.Font.Style:=[fsBold];
Attribs.Font.Color:=clGreen;
end
else if SameText(Column.FieldName, 'Expense') then
begin
E:=Column.AuxValue;
Result:= FormatFloat('#,##0.##', E);
Attribs.Font.Style:=[fsBold];
Attribs.Font.Color:=clMaroon;
end
else if SameText(Column.FieldName, 'EXP') then
begin
Result:= ' الرصيد :: ' + FormatFloat('#,##0.##', NetAmount);
Attribs.Font.Style:=[fsBold];
Attribs.Font.Color:=clNavy;
end
// ------------------
else if SameText(Column.FieldName, 'RentAmount') then //3
begin
Result:= FormatFloat('#,##0.##', Column.AuxValue);
Attribs.Font.Style:=[fsBold];
Attribs.Font.Color:=clNavy;
end
// ------------------
else if SameText(Column.FieldName, 'EmptyDays') then //4
begin
Result:= Column.AuxValue;
Attribs.Font.Style:=[fsBold];
Attribs.Font.Color:=clNavy;
end
else if SameText(Column.FieldName, 'EmpDaysVal') then //4
begin
Result:= FormatFloat('#,##0.##', Column.AuxValue);
Attribs.Font.Style:=[fsBold];
Attribs.Font.Color:=clNavy;
end
// ------------------
;
Column.AuxValue:=NULL;
end;
procedure TReportsF.frxReport1BeforePrint(Sender: TfrxReportComponent);
begin
inherited;
// RepTypeP,RepType2P
if Sender.Name = 'RpTypTxt' then
(sender as TfrxMemoView).Memo.Text := RepTypeP;
if Sender.Name = 'RpParTxt' then
(sender as TfrxMemoView).Memo.Text := RepType2P;
if Sender.Name = 'MemFdate' then
(sender as TfrxMemoView).Memo.Text := Fdat;
if Sender.Name = 'MemTdate' then
(sender as TfrxMemoView).Memo.Text := Tdat;
end;
procedure TReportsF.rbConRptClick(Sender: TObject);
begin
inherited;
rbEstRpt.Checked:=false;
rbUntRpt.Checked:=false;
//rbConRpt.Checked:=false;
Lpnl1.Color := clSilver;
Lpnl2.Color := clSilver;
Lpnl3.Color := $000080FF;
UniRadioGroup1.ItemIndex := -1;
end;
procedure TReportsF.rbEstRptClick(Sender: TObject);
begin
inherited;
//rbEstRpt.Checked:=false;
rbUntRpt.Checked:=false;
rbConRpt.Checked:=false;
Lpnl1.Color := $000080FF;
Lpnl2.Color := clSilver;
Lpnl3.Color := clSilver;
UniRadioGroup1.ItemIndex := -1;
end;
procedure TReportsF.rbUntRptClick(Sender: TObject);
begin
inherited;
rbEstRpt.Checked:=false;
//rbUntRpt.Checked:=false;
rbConRpt.Checked:=false;
Lpnl1.Color := clSilver;
Lpnl2.Color := $000080FF;
Lpnl3.Color := clSilver;
UniRadioGroup1.ItemIndex := -1;
end;
end.
|
unit UserApiInterface;
interface
Const
C_GameShareDLLName = 'gameShare.DLL';
{uses
UserTypes;
function WinGBToBIG5(Source, Destination: PChar; iLen: integer; LanguageType: TLanguageType): WordBool; stdcall; External 'gameShare.DLL';
function WinBIG5ToGB(Source, Destination: PChar; iLen: integer; LanguageType: TLanguageType): WordBool; stdcall; External 'gameShare.DLL';
function LCMAPConvert(Source, Destination: PChar; iLen: integer; LanguageType: TLanguageType): WordBool; stdcall; External 'gameShare.DLL';}
function GetProcessID(EXE_Name: PChar): THandle;
stdcall; External C_GameShareDLLName;
function GetModuleMainFileName(ProcessID: THandle;
EXE_Name, ModuleMainFileName:PChar; iLen: Integer): integer;
stdcall; External C_GameShareDLLName;
function GetProcessMemory(EXE_Name: PChar;
Address: LongWord; Buf: Pointer; Len: LongWord): LongWord;
stdcall; External C_GameShareDLLName;
function SetProcessMemory(EXE_Name: PChar;
Address: LongWord; Buf: Pointer; Len: LongWord): LongWord;
stdcall; External C_GameShareDLLName;
function GetProcessMemoryForID(ProcessID: THandle;
Address: LongWord; Buf: Pointer; Len: LongWord): boolean;
stdcall; External C_GameShareDLLName;
function SetProcessMemoryForID(ProcessID: THandle;
Address: LongWord; Buf: Pointer; Len: LongWord): boolean;
stdcall; External C_GameShareDLLName;
function GetFileVersionInVersionInfo(pFileName, pInfo:PChar;
const BufLen:Integer):WordBool;
stdcall; External C_GameShareDLLName;
implementation
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2009 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_StreamToBlock;
interface
uses uTPLb_StreamCipher, uTPLb_BlockCipher, Classes, uTPLb_Decorators;
type
TStreamToBlock_Adapter = class( TInterfacedObject,
IStreamCipher, ICryptoGraphicAlgorithm, IControlObject,
IStreamCipherEx2)
private
FBlockCipher: IBlockCipher;
FChaining: IBlockChainingModel;
FAdvancedOptions: TSymetricEncryptionOptionSet;
FOnSetIV: TSetMemStreamProc;
function DisplayName: string;
function ProgId: string;
function Features: TAlgorithmicFeatureSet;
function DefinitionURL: string;
function WikipediaReference: string;
function GenerateKey( Seed: TStream): TSymetricKey;
function LoadKeyFromStream( Store: TStream): TSymetricKey;
function SeedByteSize: integer; // Size that the input of the GenerateKey must be.
function Parameterize( const Params: IInterface): IStreamCipher;
function Start_Encrypt( Key: TSymetricKey; CipherText: TStream): IStreamEncryptor; overload;
function Start_Decrypt( Key: TSymetricKey; PlainText : TStream): IStreamDecryptor; overload;
function Start_Encrypt( Key: TSymetricKey; CipherText: TStream; IV: TStream): IStreamEncryptor; overload;
function Start_Decrypt( Key: TSymetricKey; PlainText : TStream; IV: TStream): IStreamDecryptor; overload;
// IControlObject = interface
function ControlObject: TObject;
public
constructor Create;
end;
function StreamToBlock_Adapter_CSharpVariant: IStreamCipher;
// CSharp variant:
// 1. Only decrypt is implemented.
// 2. Not automatically registered with the library. You have to explicitly register.
// 3. Full IV is prepended in the ciphertext stream.
// 4. Straight zero padding.
implementation
uses SysUtils, Math, uTPLb_StreamUtils, uTPLb_CFB_Block, uTPLb_Constants,
uTPLb_CFB_8Bit, uTPLb_PointerArithmetic, uTPLb_I18n;
{ HOW THE STREAM TO BLOCK ADAPTER WORKS (Encryption direction)
=================================================================
We have a plaintext message (msg), which we which to encrypt and transmit
over an insecure channel using a block mode cipher.
Let the length of the plaintext message in bits be m.
Len( msg) = m
m >= 0
Let the block size in bits be B.
B >= 2
Because of our fileing system constraints, we must have
m mod 8 = 0
B mod 8 = 0
B >= 16 (B=8 would make block-mode pointless).
CASE ONE: The Trivial Case.
---------------------------
In this case the message is empty, that is to say m = 0.
we handle this with an empty emission. This is so, regardless of the
chaining mode and its features.
In all other cases ...
----------------------
In all other cases that follow, in general we will emit the following
data in the said order.
1. The IV Seed. This is emitted in the clear. This will not always be present.
2. The encryption of the following stream:
2.1 A prefix. This will not always be present.
2.2 The payload message, msg
2.3 Padding at the end. Whether this is present or not, depends on the mode.
The last ciphertext block of (2.) may be truncated according to mode.
Let the length of the IV seed in bits be s.
Let the length of the prefix in bits be pre.
Let the length of the end padding be pd.
Let the length of the input to to codec, before padding, be x.
x = pre + m
Let N be the number of blocks.
N = roof( x / B) = (x + B - 1) div B
Let xl be the length of the last ciphertext block, before padding.
if (x mod B) = 0 ==> xl = B
if (x mod B) <> 0 ==> xl = x mod B
8 <= xl <= B
Necessarily, we have ...
pd = (B - xl) + (k * B)
where k is some non-negative integer, which is going to depend on
our mode and padding scheme.
How we proceed next, depends on the chaining features.
Here is the definition again.
IBlockCipher.ChainingFeatures: TChainingFeature = (
cfNoNounce, // The chaining mode does not require any nounce nor
// does it require an IV. Ex: ECB
cfKeyStream, // A key-stream is at the heart of the chaining mode
// The final partial block can be padded arbitarily,
// encrypted as usual, and then truncated to the same
// length as the corresponding plaintext input.
// Examples: CFB, 8-bit CFB, OFB and CTR.
// Counter-examples: ECB and CBC
cf8bit); // Plaintext and cipher text are processed one byte at a time.
// Example: 8-bit CFB.
CASE TWO: cfNoNounce and cfKeyStream
------------------------------------
There are no stock modes which are an example of this. I don't expect
that there will even be any custom modes worth their salt (pun intended),
which has this combination of features. Never-the-less, this algorithm
deals with this case, just in case a custom cipher is so.
1. There is no IV seed.
s = 0
2. There is no prefix.
pre = 0
3. The IV is set to all zeros.
4. If the plaintext is not congruent to the block size (xl < B), then
pad out the last plaintext block with zeros. We will call this
type of padding, "short zero extend".
pd = B - xl
5. Encrypt the blocks in order
6. Truncate the last ciphertext block to xl.
7. Emit the ciphertext blocks.
CASE THREE: cfNoNounce and NOT cfKeyStream
-------------------------------------------
An example of such a mode is ECB.
1. There is no IV seed.
s = 0
2. There is no prefix.
pre = 0
3. The IV is set to all zeros.
4. Pad out the last block like this ..
4.1. Append a single '1' bit. ($80 in a byte)
4.2. Append as many zeros as required to make the final block full.
We will call this type of padding "Simple dimple".
xl < B ==> pd = B - xl
xl = B ==> pd = B
5. Encrypt the blocks in order
6. Do NOT truncate the last ciphertext block.
7. Emit the ciphertext blocks.
Otherwise ...
----------
1. Generate a 64 bit nonce from a random number generator.
2.1 If B >= 64, set the lower 64 bits of the IV to be the nonce,
and the remaining bits zero. The IV seed is the nonce, and
there is no prefix.
s = 64
pre = 0
2.2 If B < 64, we need to compensate for the weakness of the chaining mode
against the repeat-message attack, by salting or pre-seeding the
input plaintext proportionally. Set the IV to be the lower B bits
of the nounce. The IV seed is the IV. The prefix is the remaining
bits of the nonce.
s = B
pre = 64 - B
In either case: s + pre = 64
In what follows, use the following terminology.
If x < B then describe the message as a 'short message'.
If (x mod B) = 0 then describe the message as a 'round message'.
If (x > B) and ((x mod B) > 0) then describe the message as a 'sharp message'.
CASE FOUR: NOT cfNoNounce and NOT cfKeyStream and short message
----------------------------------------------------------------
CBC mode has NOT cfNoNounce and NOT cfKeyStream.
In this case, act as if the mode was CFB, which has feature set [cfKeyStream],
that is to say CFB has NOT cfNoNounce and cfKeyStream.
Refer to case 7 (NOT cfNoNounce, cfKeyStream)
CASE FIVE: NOT cfNoNounce and round message
--------------------------------------------
1. No padding is required.
xl = B
2. Encrypt the blocks in order.
3. There is no truncation of the last ciphertext block.
4. Emit the ciphertext blocks in natural order.
CASE SIX: NOT cfNoNounce and NOT cfKeyStream and sharp message
----------------------------------------------------------------
1. Apply ciphertext stealing to the last two blocks.
2. The last two ciphertext blocks are emitted in reverse order. That is
to say, the second last cipherblock (which has length xl) is emitted
last, and the naturally last cipherblock (which has length B) is emitted
second last.
CASE SEVEN: NOT cfNoNounce and cfKeyStream but not round message
----------------------------------------------------------------
1. Our cipher effectively a stream-mode cipher. So short zero extend the
last block.
2. Encrypt the blocks in natural order.
3. Truncate the last block to xl.
4. Emit the blocks in natural order.
}
type
TEncryptorDecryptor = class( TInterfacedObject)
protected
FChaining: IBlockChainingModel;
FEmitBuffer: TMemoryStream;
FBuffer: TMemoryStream;
FBlockLen: integer;
FCodec: IBlockCodec;
FBlockCipher: IBlockCipher;
FLenBuffer: integer;
FChainState: TBlockChainLink;
FIV: TMemoryStream;
FDataCount: int64;
FisAutoXOR: boolean;
Fis8bitMode: boolean;
FisEncrypting: boolean;
FEmissionStream: TStream;
procedure Reset; virtual;
procedure Emit( SourceBuf: TMemoryStream; EmitLen: integer = -1);
// ^ Encrypt/Decrypt and then emit.
procedure Emit_1stBuffer;
function ShortNonKeyStreamingChainMode: IBlockChainingModel;
procedure Chained_Encrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream);
procedure Chained_Decrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream);
public
constructor Start_EncDec(
Key1: TSymetricKey; EmissionStream1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel;
isEncrypting1: boolean);
destructor Destroy; override;
end;
TNoNonceEncryptor = class( TEncryptorDecryptor, IStreamEncryptor)
private
FCipherText: TStream;
FPad: TMemoryStream;
procedure Encrypt( const Plaintext: TStream);
procedure End_Encrypt;
protected
procedure Reset; override;
public
constructor Start_Encrypt(
Key1: TSymetricKey; CipherText1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel);
destructor Destroy; override;
end;
TNoncibleEncryptor = class( TEncryptorDecryptor, IStreamEncryptor)
private
FKey: TSymetricKey;
FCipherText: TStream;
F2ndBuffer: TMemoryStream;
Fis2ndBufferFull: boolean;
FIVSeedLen: integer;
FSaltLen: integer;
FNonce: TMemoryStream;
FisShortMessage: boolean;
FisAddingSalt: boolean;
FOnSetIV: TSetMemStreamProc;
procedure Encrypt( const Plaintext: TStream);
procedure End_Encrypt;
protected
procedure Reset; override;
public
constructor Start_Encrypt(
Key1: TSymetricKey; CipherText1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel;
OnSetIV1: TSetMemStreamProc);
destructor Destroy; override;
end;
TOpenSSLCompatEncryptor = class( TEncryptorDecryptor, IStreamEncryptor)
private
FKey: TSymetricKey;
FCipherText: TStream;
procedure Encrypt( const Plaintext: TStream);
procedure End_Encrypt;
protected
procedure Reset; override;
public
constructor Start_Encrypt(
Key1: TSymetricKey; CipherText1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel);
constructor Start_Encrypt_WithIV(
Key1: TSymetricKey; CipherText1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel;
IV1: TStream);
destructor Destroy; override;
end;
TNoncibleDecryptor = class( TEncryptorDecryptor, IStreamDecryptor)
private
FKey: TSymetricKey;
FPlainText: TStream;
F2ndBuffer: TMemoryStream;
Fis2ndBufferFull: boolean;
FSaltAbsorber: TDesalinationWriteStream;
FDataCount: int64;
FIVSeedLen: integer;
FSaltLen: integer;
FisShortMessage: boolean;
procedure Decrypt( const Ciphertext: TStream);
procedure End_Decrypt;
protected
procedure Reset; override;
public
constructor Start_Decrypt(
Key1: TSymetricKey; PlainText1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel);
destructor Destroy; override;
end;
TOpenSSLCompatDecryptor = class( TEncryptorDecryptor, IStreamDecryptor)
private
//Fis2ndBufferFull: boolean;
//FSaltAbsorber: TDesalinationWriteStream;
//FDataCount: int64;
//FIVSeedLen: integer;
//FSaltLen: integer;
//FisShortMessage: boolean;
procedure Decrypt( const Ciphertext: TStream);
procedure End_Decrypt;
protected
procedure Reset; override;
public
constructor Start_Decrypt(
Key1: TSymetricKey; PlainText1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel);
constructor Start_Decrypt_WithIV(
Key1: TSymetricKey; PlainText1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel;
IV1: TStream);
destructor Destroy; override;
end;
TNoNonceDecryptor = class( TEncryptorDecryptor, IStreamDecryptor)
private
FPlaintext: TStream;
FisSecondBufferFull: boolean;
F2ndBuffer: TMemoryStream;
procedure Decrypt( const Ciphertext: TStream);
procedure End_Decrypt;
protected
procedure Reset; override;
public
constructor Start_Decrypt(
Key1: TSymetricKey; PlainText1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel);
destructor Destroy; override;
end;
{ TStreamToBlock_Adapter }
function TStreamToBlock_Adapter.ControlObject: TObject;
var
ControlObject: IControlObject;
begin
if Supports( FBlockCipher, IControlObject, ControlObject) then
result := ControlObject.ControlObject
else
result := self
end;
constructor TStreamToBlock_Adapter.Create;
begin
FAdvancedOptions := []
end;
function TStreamToBlock_Adapter.DefinitionURL: string;
begin
result := ''
end;
function TStreamToBlock_Adapter.DisplayName: string;
begin
if assigned( FBlockCipher) then
result := FBlockCipher.DisplayName
else
result := BlockCipher_DisplayName
end;
function TStreamToBlock_Adapter.Features: TAlgorithmicFeatureSet;
begin
result := [afStar, afOpenSourceSoftware, afBlockAdapter, afDoesNotNeedSalt]
end;
function TStreamToBlock_Adapter.GenerateKey( Seed: TStream): TSymetricKey;
begin
if assigned( FBlockCipher) then
result := FBlockCipher.GenerateKey( Seed)
else
result := nil
end;
function TStreamToBlock_Adapter.LoadKeyFromStream( Store: TStream): TSymetricKey;
begin
if assigned( FBlockCipher) and assigned( Store) then
result := FBlockCipher.LoadKeyFromStream( Store)
else
result := nil
end;
function TStreamToBlock_Adapter.Parameterize(
const Params: IInterface): IStreamCipher;
var
BlockCipherSelector: IBlockCipherSelector;
BlockCipherSelectorEx2: IBlockCipherSelectorEx2;
BlockCipher: IBlockCipher;
Chaining: IBlockChainingModel;
Newbie: TStreamToBlock_Adapter;
begin
result := nil;
if assigned( FBlockCipher) and assigned( FChaining) then exit;
FAdvancedOptions := [];
if Supports( Params, IBlockCipherSelector, BlockCipherSelector) then
begin
BlockCipher := BlockCipherSelector.GetBlockCipher;
Chaining := BlockCipherSelector.GetChainMode;
if Supports( BlockCipherSelector, IBlockCipherSelectorEx2, BlockCipherSelectorEx2) then
FAdvancedOptions := BlockCipherSelectorEx2.GetAdvancedOptions2
end;
if not (assigned( BlockCipher) or assigned( Chaining)) then exit;
Newbie := TStreamToBlock_Adapter.Create;
Newbie.FBlockCipher := BlockCipher;
Newbie.FChaining := Chaining;
result := Newbie;
if (not assigned( BlockCipherSelectorEx2)) or
(not BlockCipherSelectorEx2.hasOnSetIVHandler( Newbie.FOnSetIV)) then
Newbie.FOnSetIV := nil
end;
function TStreamToBlock_Adapter.ProgId: string;
begin
result := BlockCipher_ProgId
end;
function TStreamToBlock_Adapter.SeedByteSize: integer;
begin
if assigned( FBlockCipher) then
result := FBlockCipher.SeedByteSize
else
result := -1
end;
function TStreamToBlock_Adapter.Start_Decrypt(
Key: TSymetricKey; PlainText: TStream): IStreamDecryptor;
begin
if optOpenSSL_CompatibilityMode in FAdvancedOptions then
begin
if not (cfNoNounce in FChaining.ChainingFeatures) then
raise Exception.Create( ES_OpenSSLCompat_RequiresIV);
result := TOpenSSLCompatDecryptor.Start_Decrypt(
Key, PlainText, FBlockCipher, FChaining)
end
else if cfNoNounce in FChaining.ChainingFeatures then
result := TNoNonceDecryptor.Start_Decrypt(
Key, PlainText, FBlockCipher, FChaining)
else
result := TNoncibleDecryptor.Start_Decrypt(
Key, PlainText, FBlockCipher, FChaining)
end;
function TStreamToBlock_Adapter.Start_Encrypt(
Key: TSymetricKey; CipherText: TStream): IStreamEncryptor;
begin
if optOpenSSL_CompatibilityMode in FAdvancedOptions then
// Valid only for ECB. Other chain modes for OpenSSL compatibility
// require an explicit user-supplied IV.
begin
if not (cfNoNounce in FChaining.ChainingFeatures) then
raise Exception.Create( ES_OpenSSLCompat_RequiresIV);
result := TOpenSSLCompatEncryptor.Start_Encrypt(
Key, CipherText, FBlockCipher, FChaining)
end
else if cfNoNounce in FChaining.ChainingFeatures then
result := TNoNonceEncryptor.Start_Encrypt(
Key, CipherText, FBlockCipher, FChaining)
else
result := TNoncibleEncryptor.Start_Encrypt(
Key, CipherText, FBlockCipher, FChaining, FOnSetIV)
end;
function TStreamToBlock_Adapter.Start_Decrypt(
Key: TSymetricKey; PlainText, IV: TStream): IStreamDecryptor;
var
sName: string;
begin
if optOpenSSL_CompatibilityMode in FAdvancedOptions then
result := TOpenSSLCompatDecryptor.Start_Decrypt_WithIV(
Key, PlainText, FBlockCipher, FChaining, IV)
else
begin
if assigned( FBlockCipher) then
sName := FBlockCipher.DisplayName
else
sName := '(no block cipher)';
raise Exception.CreateFmt( ES_NoOpenSSLCompat, [sName])
end;
end;
function TStreamToBlock_Adapter.Start_Encrypt(
Key: TSymetricKey; CipherText, IV: TStream): IStreamEncryptor;
var
sName: string;
begin
if optOpenSSL_CompatibilityMode in FAdvancedOptions then
result := TOpenSSLCompatEncryptor.Start_Encrypt_WithIV(
Key, CipherText, FBlockCipher, FChaining, IV)
else
begin
if assigned( FBlockCipher) then
sName := FBlockCipher.DisplayName
else
sName := '(no block cipher)';
raise Exception.CreateFmt( ES_NoOpenSSLCompat, [sName])
end;
end;
function TStreamToBlock_Adapter.WikipediaReference: string;
begin
result := ''
end;
{ TNoNonceEncryptor }
constructor TNoNonceEncryptor.Start_Encrypt( Key1: TSymetricKey;
CipherText1: TStream; const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel);
begin
inherited Start_EncDec( Key1, CipherText1, BlockCipher1, Chaining1, True);
FCipherText := CipherText1;
FIV.Size := FBlockLen;
ZeroFillStream( FIV);
FChainState := FChaining.Chain_EncryptBlock( Key1, FIV, FCodec);
if cfKeyStream in FChaining.ChainingFeatures then
FPad := nil
else
FPad := TMemoryStream.Create
end;
procedure TNoNonceEncryptor.Encrypt( const Plaintext: TStream);
var
X: int64;
Amnt: integer;
begin
Plaintext.Position := 0;
X := Plaintext.Size;
while X > 0 do
begin
Amnt := FBlockLen - FLenBuffer;
if X < FBlockLen then
Amnt := Min( Amnt, X);
if Amnt > 0 then
begin
ReadMem( Plaintext, FBuffer, FLenBuffer, Amnt);
Dec( X, Amnt);
Inc( FLenBuffer, Amnt);
Inc( FDataCount, Amnt)
end;
if FLenBuffer = FBlockLen then
Emit_1stBuffer
end
end;
const PadIntroducer: byte = $80;
procedure TNoNonceEncryptor.End_Encrypt;
begin
if (FDataCount <> 0) and (not (cfKeyStream in FChaining.ChainingFeatures)) then
begin
FPad.Size := FBlockLen - FLenBuffer;
ZeroFillStream( FPad);
PByte( FPad.Memory)^ := PadIntroducer;
Encrypt( FPad)
end;
if cfKeyStream in FChaining.ChainingFeatures then
Emit_1stBuffer;
Reset
end;
procedure TNoNonceEncryptor.Reset;
begin
inherited Reset;
FChainState.Reset( FIV);
if not (cfKeyStream in FChaining.ChainingFeatures) then
BurnMemoryStream( FPad)
end;
destructor TNoNonceEncryptor.Destroy;
begin
BurnMemoryStream( FPad); FPad.Free;
inherited
end;
{ TNoncibleEncryptor }
constructor TNoncibleEncryptor.Start_Encrypt(
Key1: TSymetricKey;
CipherText1: TStream; const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel; OnSetIV1: TSetMemStreamProc);
begin
inherited Start_EncDec( Key1, Ciphertext1, BlockCipher1, Chaining1, True);
FKey := Key1;
FCipherText := CipherText1;
FChainState := nil;
F2ndBuffer := TMemoryStream.Create;
F2ndBuffer.Size := FBlockLen;
Fis2ndBufferFull := False;
FIV.Size := FBlockLen;
FIVSeedLen := Min( FBlockLen, 8);
FSaltLen := 8 - FIVSeedLen;
FNonce := TMemoryStream.Create;
FIV.Size := FBlockLen;
FisShortMessage := True;
FisAddingSalt := False;
FOnSetIV := OnSetIV1
end;
procedure TNoncibleEncryptor.Encrypt( const Plaintext: TStream);
var
X: int64;
Amnt: integer;
Tmp: TMemoryStream;
begin
Plaintext.Position := 0;
X := Plaintext.Size;
if (X > 0) and (FDataCount = 0) and (not FisAddingSalt) then
begin
// 1. Acquire Nonce.
FNonce.Size := 8;
RandomFillStream( FNonce);
// 2. Determine the IV.
Move( FNonce.Memory^, FIV.Memory^, FIVSeedLen);
if FBlockLen > FIVSeedLen then
FillChar( MemStrmOffset( FIV, FIVSeedLen)^,
FBlockLen - FIVSeedLen, 0);
if assigned( FOnSetIV) then
FOnSetIV( FIV);
// 3. Emit IV seed in the clear.
if FIVSeedLen > 0 then
FCiphertext.WriteBuffer( FIV.Memory^, FIVSeedLen);
// 4. Pre-pend salt.
if FSaltLen > 0 then
begin
FisAddingSalt := True;
try
Move( MemStrmOffset( FNonce, FIVSeedLen)^,
FNonce.Memory^, FSaltLen);
FNonce.Size := FSaltLen;
Encrypt( FNonce)
finally
FisAddingSalt := False
end
end;
BurnMemoryStream( FNonce)
end;
while (X > 0) or (FLenBuffer = FBlockLen) do
begin
Amnt := FBlockLen - FLenBuffer;
if Amnt > X then
Amnt := X;
if Amnt > 0 then
begin
Amnt := ReadMem( Plaintext, FBuffer, FLenBuffer, Amnt);
if Amnt = 0 then
X := 0
else
Dec( X, Amnt);
Inc( FLenBuffer, Amnt);
Inc( FDataCount, Amnt)
end;
if FLenBuffer >= FBlockLen then
FisShortMessage := False;
if (FLenBuffer = FBlockLen) and (not Fis2ndBufferFull) then
begin
Tmp := F2ndBuffer;
F2ndBuffer := FBuffer;
FBuffer := Tmp;
Fis2ndBufferFull := True;
FLenBuffer := 0
end;
if (FLenBuffer = FBlockLen) and Fis2ndBufferFull then
begin
if not assigned( FChainState) then
FChainState := FChaining.Chain_EncryptBlock( FKey, FIV, FCodec);
Emit( F2ndBuffer);
Fis2ndBufferFull := False
end
end
end;
procedure TNoncibleEncryptor.End_Encrypt;
var
Actual: IBlockChainingModel;
ChainStateClone: TBlockChainLink;
begin
if FDataCount = 0 then
begin end
else
begin
if FisShortMessage and (not (cfKeyStream in FChaining.ChainingFeatures)) then
begin
Actual := ShortNonKeyStreamingChainMode;
Fis8bitMode := (cf8bit in Actual.ChainingFeatures) and
(cfKeyStream in Actual.ChainingFeatures)
end
else
Actual := FChaining;
FisAutoXOR := ([cfKeyStream, cfAutoXOR] * Actual.ChainingFeatures) =
[cfKeyStream, cfAutoXOR];
if not assigned( FChainState) then
FChainState := Actual.Chain_EncryptBlock( FKey, FIV, FCodec);
if FLenBuffer = 0 then
begin // Round case
Assert( Fis2ndBufferFull, AS_BlockToStream_EndEncrypt_InternalMarshalling);
Emit( F2ndBuffer);
end
else if cfKeyStream in Actual.ChainingFeatures then
begin // KeyStream case
if Fis2ndBufferFull then
Emit( F2ndBuffer);
Emit_1stBuffer
end
else
begin // Ciphertext stealing
Assert( Fis2ndBufferFull, AS_BlockToStream_EndEncrypt_InternalMarshalling);
ChainStateClone := FChainState.Clone;
try
Chained_Encrypt_Block( F2ndBuffer, FEmitBuffer);
Move( MemStrmOffset( FEmitBuffer, FLenBuffer)^,
MemStrmOffset( FBuffer, FLenBuffer)^,
FBlockLen - FLenBuffer); // << The steal!
FBuffer.Position := 0;
F2ndBuffer.Position := 0;
ChainStateClone.Encrypt_Block( FBuffer, F2ndBuffer);
FCiphertext.WriteBuffer( F2ndBuffer .Memory^, FBlockLen); // Swap emission order.
FCiphertext.WriteBuffer( FEmitBuffer.Memory^, FLenBuffer)
finally
ChainStateClone.Burn;
ChainStateClone.Free
end
end
end;
Reset
end;
procedure TNoncibleEncryptor.Reset;
begin
inherited Reset;
BurnMemory( F2ndBuffer .Memory^, FBlockLen);
FreeAndNil( FChainState);
Fis2ndBufferFull := False;
FisShortMessage := True;
BurnMemory( FIV.Memory^, FBlockLen);
BurnMemoryStream( FNonce)
end;
destructor TNoncibleEncryptor.Destroy;
begin
BurnMemoryStream( F2ndBuffer); FreeAndNil( F2ndBuffer);
BurnMemoryStream( FIV);
BurnMemoryStream( FNonce); FreeAndNil( FNonce);
FDataCount := 0;
inherited
end;
{ TNoNonceDecryptor }
constructor TNoNonceDecryptor.Start_Decrypt(
Key1: TSymetricKey; PlainText1: TStream;
const BlockCipher1: IBlockCipher; const Chaining1: IBlockChainingModel);
begin
inherited Start_EncDec( Key1, Plaintext1, BlockCipher1, Chaining1, False);
FPlainText := PlainText1;
FIV.Size := FBlockLen;
ZeroFillStream( FIV);
FChainState := FChaining.Chain_DecryptBlock( Key1, FIV, FCodec);
FisSecondBufferFull := False;
F2ndBuffer := TMemoryStream.Create;
F2ndBuffer.Size := FBlockLen
end;
procedure TNoNonceDecryptor.Decrypt( const Ciphertext: TStream);
var
X: int64;
Amnt: integer;
Tmp: TMemoryStream;
begin
Ciphertext.Position := 0;
X := Ciphertext.Size;
while (X > 0) or ((FLenBuffer = FBlockLen) and (not FisSecondBufferFull)) do
begin
Amnt := FBlockLen - FLenBuffer;
if X < FBlockLen then
Amnt := Min( Amnt, X);
if Amnt > 0 then
begin
ReadMem( Ciphertext, FBuffer, FLenBuffer, Amnt);
Dec( X, Amnt);
Inc( FLenBuffer, Amnt);
Inc( FDataCount, Amnt)
end;
if (FLenBuffer = FBlockLen) and (not FisSecondBufferFull) then
begin
Tmp := F2ndBuffer;
F2ndBuffer := FBuffer;
FBuffer := Tmp;
FisSecondBufferFull := True;
FLenBuffer := 0
end;
if FisSecondBufferFull and (FLenBuffer > 0) then
begin
Emit( F2ndBuffer);
FisSecondBufferFull := False
end
end
end;
procedure TNoNonceDecryptor.End_Decrypt;
var
Sentinal: PByte;
j: integer;
begin
if FDataCount = 0 then
begin end
else if cfKeyStream in FChaining.ChainingFeatures then
begin
if FisSecondBufferFull then
begin
Emit( F2ndBuffer);
FisSecondBufferFull := False
end;
Emit_1stBuffer
end
else
begin
Assert( FisSecondBufferFull and (FLenBuffer = 0),
AS_BlockPaddingCorrupt);
Chained_Decrypt_Block( FEmitBuffer, F2ndBuffer);
FLenBuffer := 0;
Sentinal := PByte( MemStrmOffset( FEmitBuffer, FBlockLen - 1));
for j := FBlockLen - 1 downto 0 do
begin
if Sentinal^ = PadIntroducer then
begin
FLenBuffer := j;
break
end;
Dec( Sentinal)
end;
if FLenBuffer > 0 then
FPlaintext.WriteBuffer( FEmitBuffer.Memory^, FLenBuffer)
end;
Reset
end;
procedure TNoNonceDecryptor.Reset;
begin
inherited Reset;
BurnMemory( F2ndBuffer .Memory^, FBlockLen);
FChainState.Reset( FIV);
FisSecondBufferFull := False
end;
destructor TNoNonceDecryptor.Destroy;
begin
BurnMemoryStream( F2ndBuffer); FreeAndNil( F2ndBuffer);
inherited
end;
{ TNoncibleDecryptor }
function TEncryptorDecryptor.ShortNonKeyStreamingChainMode: IBlockChainingModel;
begin
result := TCFB_8Bit.Create
// TCFB_Block is also a reasonable replacement.
end;
constructor TNoncibleDecryptor.Start_Decrypt(
Key1: TSymetricKey;
PlainText1: TStream; const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel);
begin
inherited Start_EncDec( Key1, Plaintext1, BlockCipher1, Chaining1, False);
FKey := Key1;
FPlainText := PlainText1;
FLenBuffer := 0;
F2ndBuffer := TMemoryStream.Create;
F2ndBuffer.Size := FBlockLen;
Fis2ndBufferFull := False;
FIV.Size := 0;
FIVSeedLen := Min( FBlockLen, 8);
FSaltLen := 8 - FIVSeedLen;
if FSaltLen > 0 then
begin
FSaltAbsorber := TDesalinationWriteStream.Create;
FSaltAbsorber.FreshwaterStream := FEmissionStream;
FEmissionStream := FSaltAbsorber;
FSaltAbsorber.SaltVolume := FSaltLen
end
else
FSaltAbsorber := nil;
FisShortMessage := True
end;
procedure TNoncibleDecryptor.Decrypt( const Ciphertext: TStream);
var
X: int64;
Amnt: integer;
Tmp: TMemoryStream;
OldSize: integer;
begin
Ciphertext.Position := 0;
X := Ciphertext.Size;
while (X > 0) or (FLenBuffer = FBlockLen) do
begin
// 1. Read the IV.
if FIVSeedLen > 0 then
begin
Amnt := FIVSeedLen;
if X < Amnt then
Amnt := X;
FIV.CopyFrom( Ciphertext, Amnt);
Dec( X, Amnt);
Dec( FIVSeedLen, Amnt);
OldSize := FIV.Size;
if (FIVSeedLen = 0) and (OldSize < FBlockLen) then
begin
FIV.Size := FBlockLen;
FillChar( MemStrmOffset( FIV, OldSize)^, FBlockLen - OldSize, 0)
end;
continue
end;
// 2. Now process the payload
Amnt := FBlockLen - FLenBuffer;
if X < Amnt then
Amnt := X;
if Amnt > 0 then
begin
ReadMem( Ciphertext, FBuffer, FLenBuffer, Amnt);
Dec( X, Amnt);
Inc( FLenBuffer, Amnt);
Inc( FDataCount, Amnt)
end;
if FLenBuffer >= FBlockLen then
FisShortMessage := False;
if (FLenBuffer = FBlockLen) and (not Fis2ndBufferFull) then
begin
Tmp := F2ndBuffer;
F2ndBuffer := FBuffer;
FBuffer := Tmp;
Fis2ndBufferFull := True;
FLenBuffer := 0
end;
if (FLenBuffer = FBlockLen) and Fis2ndBufferFull then
begin
if not assigned( FChainState) then
FChainState := FChaining.Chain_DecryptBlock( FKey, FIV, FCodec);
Emit( F2ndBuffer);
Fis2ndBufferFull := False
end
end
end;
procedure TNoncibleDecryptor.End_Decrypt;
var
Actual: IBlockChainingModel;
ChainStateClone: TBlockChainLink;
begin
if FDataCount = 0 then
begin end
else
begin
if FisShortMessage and (not (cfKeyStream in FChaining.ChainingFeatures)) then
begin
Actual := ShortNonKeyStreamingChainMode;
Fis8bitMode := (cf8bit in Actual.ChainingFeatures) and
(cfKeyStream in Actual.ChainingFeatures)
end
else
Actual := FChaining;
FisAutoXOR := ([cfKeyStream, cfAutoXOR] * Actual.ChainingFeatures) =
[cfKeyStream, cfAutoXOR];
if not assigned( FChainState) then
FChainState := Actual.Chain_DecryptBlock( FKey, FIV, FCodec);
if FLenBuffer = 0 then
begin // Round case
Assert( Fis2ndBufferFull, AS_BlockToStream_EndDecrypt_InternalMarshalling);
Emit( F2ndBuffer)
end
else if cfKeyStream in Actual.ChainingFeatures then
begin // KeyStream case
if Fis2ndBufferFull then
Emit( F2ndBuffer);
Emit_1stBuffer
end
else
begin // Ciphertext stealing
Assert( Fis2ndBufferFull, AS_BlockToStream_EndDecrypt_InternalMarshalling);
ChainStateClone := FChainState.Clone;
try
Chained_Decrypt_Block( FEmitBuffer, F2ndBuffer);
Move( MemStrmOffset( FEmitBuffer, FLenBuffer)^,
MemStrmOffset( FBuffer, FLenBuffer)^,
FBlockLen - FLenBuffer); // << Reverse the steal!
F2ndBuffer.Position := 0;
FBuffer.Position := 0;
ChainStateClone.Decrypt_Block( F2ndBuffer, FBuffer);
FPlaintext.WriteBuffer( F2ndBuffer .Memory^, FBlockLen);
FPlaintext.WriteBuffer( FEmitBuffer.Memory^, FLenBuffer)
finally
ChainStateClone.Burn;
ChainStateClone.Free
end
end
end;
Reset
end;
procedure TNoncibleDecryptor.Reset;
begin
inherited Reset;
BurnMemory( F2ndBuffer .Memory^, FBlockLen);
Fis2ndBufferFull := False;
FisShortMessage := True;
BurnMemoryStream( FIV);
if assigned( FChainState) then
begin
FChainState.Burn;
FChainState.Free;
FChainState := nil
end;
FIVSeedLen := Min( FBlockLen, 8);
FSaltLen := 8 - FIVSeedLen;
if FSaltLen > 0 then
FSaltAbsorber.SaltVolume := FSaltLen
end;
destructor TNoncibleDecryptor.Destroy;
begin
BurnMemoryStream( F2ndBuffer); FreeAndNil( F2ndBuffer);
FreeAndNil( FSaltAbsorber);
FDataCount := 0;
inherited
end;
{ TEncryptorDecryptor }
constructor TEncryptorDecryptor.Start_EncDec(
Key1: TSymetricKey; EmissionStream1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel; isEncrypting1: boolean);
begin
FEmissionStream := EmissionStream1;
FBlockCipher := BlockCipher1;
FChaining := Chaining1;
FEmitBuffer := TMemoryStream.Create;
FBuffer := TMemoryStream.Create;
FBlockLen := FBlockCipher.BlockSize div 8;
FCodec := FBlockCipher.MakeBlockCodec( Key1);
FBuffer.Size := FBlockLen;
FLenBuffer := 0;
FEmitBuffer.Size := FBlockLen;
FIV := TMemoryStream.Create;
FChainState := nil;
FDataCount := 0;
FisAutoXOR := ([cfKeyStream, cfAutoXOR] * FChaining.ChainingFeatures) =
[cfKeyStream, cfAutoXOR];
Fis8bitMode := (cf8bit in FChaining.ChainingFeatures) and
(cfKeyStream in FChaining.ChainingFeatures) and
(not (cfNoNounce in FChaining.ChainingFeatures));
// A chaining mode with cf8Bit MUST also have
// cfKeyStream and not cfNoNounce
FisEncrypting := isEncrypting1
end;
procedure TEncryptorDecryptor.Chained_Decrypt_Block(
Plaintext, Ciphertext: TMemoryStream);
begin
Plaintext.Position := 0;
Ciphertext.Position := 0;
FChainState.Decrypt_Block( Plaintext, Ciphertext)
end;
procedure TEncryptorDecryptor.Chained_Encrypt_Block(
Plaintext, Ciphertext: TMemoryStream);
begin
Plaintext.Position := 0;
Ciphertext.Position := 0;
FChainState.Encrypt_Block( Plaintext, Ciphertext)
end;
destructor TEncryptorDecryptor.Destroy;
begin
BurnMemoryStream( FEmitBuffer); FEmitBuffer.Free;
BurnMemoryStream( FBuffer); FBuffer.Free;
FCodec.Burn;
FCodec := nil;
if assigned( FChainState) then
begin
FChainState.Burn;
FChainState.Free
end;
BurnMemoryStream( FIV);
FIV.Free;
inherited
end;
procedure TEncryptorDecryptor.Emit(
SourceBuf: TMemoryStream; EmitLen: integer = -1);
var
PlaintextByte, CiphertextByte: byte;
P, Q: PByte;
j: integer;
begin
if EmitLen = -1 then
EmitLen := FBlockLen;
if FisEncrypting then
begin
if Fis8bitMode then
begin
P := SourceBuf.Memory;
Q := FEmitBuffer.Memory;
for j := 0 to EmitLen - 1 do
begin
PlaintextByte := P^;
FChainState.Encrypt_8bit( PlaintextByte, CiphertextByte);
Q^ := CiphertextByte;
Inc( P); Inc( Q)
end
end
else
Chained_Encrypt_Block( SourceBuf, FEmitBuffer)
end
else
begin
if Fis8bitMode then
begin
P := SourceBuf.Memory;
Q := FEmitBuffer.Memory;
for j := 0 to EmitLen - 1 do
begin
CiphertextByte := P^;
FChainState.Decrypt_8bit( PlaintextByte, CiphertextByte);
Q^ := PlaintextByte;
Inc( P); Inc( Q)
end
end
else
Chained_Decrypt_Block( FEmitBuffer, SourceBuf)
end;
if FisAutoXOR then
XOR_Streams2( FEmitBuffer, SourceBuf);
FEmissionStream.WriteBuffer( FEmitBuffer.Memory^, EmitLen)
end;
procedure TEncryptorDecryptor.Emit_1stBuffer;
begin
if FLenBuffer = 0 then exit;
Emit( FBuffer, FLenBuffer);
FLenBuffer := 0
end;
procedure TEncryptorDecryptor.Reset;
begin
BurnMemory( FEmitBuffer.Memory^, FBlockLen);
BurnMemory( FBuffer .Memory^, FBlockLen);
FCodec.Reset;
FLenBuffer := 0;
FDataCount := 0
end;
{ TOpenSSLCompatEncryptor }
constructor TOpenSSLCompatEncryptor.Start_Encrypt(
Key1: TSymetricKey; CipherText1: TStream;
const BlockCipher1: IBlockCipher; const Chaining1: IBlockChainingModel);
begin
// Valid only for ECB. Other chain modes for OpenSSL compatibility
// require an explicit user-supplied IV.
inherited Start_EncDec( Key1, Ciphertext1, BlockCipher1, Chaining1, True);
FKey := Key1;
FCipherText := CipherText1;
FIV.Size := FBlockLen;
ZeroFillStream( FIV);
FChainState := FChaining.Chain_EncryptBlock( Key1, FIV, FCodec);
end;
constructor TOpenSSLCompatEncryptor.Start_Encrypt_WithIV(
Key1: TSymetricKey; CipherText1: TStream; const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel; IV1: TStream);
begin
inherited Start_EncDec( Key1, Ciphertext1, BlockCipher1, Chaining1, True);
FKey := Key1;
FCipherText := CipherText1;
FIV.Size := 0;
FIV.CopyFrom( IV1, 0);
FChainState := FChaining.Chain_EncryptBlock( Key1, FIV, FCodec);
end;
destructor TOpenSSLCompatEncryptor.Destroy;
begin
// TODO
inherited;
end;
procedure TOpenSSLCompatEncryptor.Encrypt( const Plaintext: TStream);
var
X: int64;
Amnt: integer;
begin
Plaintext.Position := 0;
X := Plaintext.Size;
while (X > 0) or (FLenBuffer = FBlockLen) do
begin
Amnt := FBlockLen - FLenBuffer;
if Amnt > X then
Amnt := X;
if Amnt > 0 then
begin
Amnt := ReadMem( Plaintext, FBuffer, FLenBuffer, Amnt);
if Amnt = 0 then
X := 0
else
Dec( X, Amnt);
Inc( FLenBuffer, Amnt);
Inc( FDataCount, Amnt)
end;
if FLenBuffer = FBlockLen then
begin
Emit( FBuffer);
FLenBuffer := 0
end
end
end;
procedure TOpenSSLCompatEncryptor.End_Encrypt;
var
PadByte: byte;
begin
if not (cfKeyStream in FChaining.ChainingFeatures) then
begin
if FLenBuffer = 0 then
PadByte := FBlockLen
else
PadByte := FBlockLen - FLenBuffer;
FillChar( Offset( FBuffer.Memory, FLenBuffer)^, PadByte, PadByte);
FLenBuffer := FBlockLen;
end;
if FLenBuffer > 0 then
Emit( FBuffer, FLenBuffer);
FLenBuffer := 0;
end;
procedure TOpenSSLCompatEncryptor.Reset;
begin
inherited;
// TODO
end;
{ TOpenSSLCompatDecryptor }
procedure TOpenSSLCompatDecryptor.Decrypt(const Ciphertext: TStream);
begin
// TODO
end;
destructor TOpenSSLCompatDecryptor.Destroy;
begin
// TODO
inherited;
end;
procedure TOpenSSLCompatDecryptor.End_Decrypt;
begin
// TODO
end;
procedure TOpenSSLCompatDecryptor.Reset;
begin
inherited;
// TODO
end;
constructor TOpenSSLCompatDecryptor.Start_Decrypt(Key1: TSymetricKey;
PlainText1: TStream; const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel);
begin
// TODO
end;
constructor TOpenSSLCompatDecryptor.Start_Decrypt_WithIV(Key1: TSymetricKey;
PlainText1: TStream; const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel; IV1: TStream);
begin
// TODO
end;
/////////////////////////
//uses uTPLb_StreamCipher, uTPLb_BlockCipher, uTPLb_Decorators, uTPLb_Constants,
// uTPLb_StreamUtils, uTPLb_I18n, uTPLb_PointerArithmetic;
type
TCSharpStreamToBlock_Adapter = class( TInterfacedObject,
IStreamCipher, ICryptoGraphicAlgorithm, IControlObject)
private
FBlockCipher: IBlockCipher;
FChaining: IBlockChainingModel;
function DisplayName: string;
function ProgId: string;
function Features: TAlgorithmicFeatureSet;
function DefinitionURL: string;
function WikipediaReference: string;
function GenerateKey( Seed: TStream): TSymetricKey;
function LoadKeyFromStream( Store: TStream): TSymetricKey;
function SeedByteSize: integer; // Size that the input of the GenerateKey must be.
function Parameterize( const Params: IInterface): IStreamCipher;
function Start_Encrypt( Key: TSymetricKey; CipherText: TStream): IStreamEncryptor;
function Start_Decrypt( Key: TSymetricKey; PlainText : TStream): IStreamDecryptor;
// IControlObject = interface
function ControlObject: TObject;
public
constructor Create;
end;
TCSharpDecryptor = class( TInterfacedObject, IStreamDecryptor)
private
FChaining: IBlockChainingModel;
FEmitBuffer: TMemoryStream;
FBuffer: TMemoryStream;
FBlockLen: integer;
FCodec: IBlockCodec;
FBlockCipher: IBlockCipher;
FLenBuffer: integer;
FChainState: TBlockChainLink;
FIV: TMemoryStream;
FDataCount: int64;
FisAutoXOR: boolean;
Fis8bitMode: boolean;
FEmissionStream: TStream;
FKey: TSymetricKey;
procedure Reset;
procedure Emit( SourceBuf: TMemoryStream; EmitLen: integer = -1);
procedure Emit_1stBuffer;
procedure Chained_Decrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream);
procedure Decrypt( const Ciphertext: TStream);
procedure End_Decrypt;
public
constructor Start_Decrypt(
Key1: TSymetricKey; EmissionStream1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel);
destructor Destroy; override;
end;
function TCSharpStreamToBlock_Adapter.ControlObject: TObject;
var
ControlObject: IControlObject;
begin
if Supports( FBlockCipher, IControlObject, ControlObject) then
result := ControlObject.ControlObject
else
result := self
end;
constructor TCSharpStreamToBlock_Adapter.Create;
begin
end;
function TCSharpStreamToBlock_Adapter.DefinitionURL: string;
begin
result := ''
end;
function TCSharpStreamToBlock_Adapter.DisplayName: string;
begin
if assigned( FBlockCipher) then
result := FBlockCipher.DisplayName
else
result := BlockCipher_DisplayName + ' CSharp variant'
end;
function TCSharpStreamToBlock_Adapter.Features: TAlgorithmicFeatureSet;
begin
result := [afBlockAdapter, afDoesNotNeedSalt]
end;
function TCSharpStreamToBlock_Adapter.GenerateKey( Seed: TStream): TSymetricKey;
begin
if assigned( FBlockCipher) then
result := FBlockCipher.GenerateKey( Seed)
else
result := nil
end;
function TCSharpStreamToBlock_Adapter.LoadKeyFromStream( Store: TStream): TSymetricKey;
begin
if assigned( FBlockCipher) and assigned( Store) then
result := FBlockCipher.LoadKeyFromStream( Store)
else
result := nil
end;
function TCSharpStreamToBlock_Adapter.Parameterize(
const Params: IInterface): IStreamCipher;
var
BlockCipherSelector: IBlockCipherSelector;
//BlockCipherSelectorEx2: IBlockCipherSelectorEx2;
BlockCipher: IBlockCipher;
Chaining: IBlockChainingModel;
Newbie: TCSharpStreamToBlock_Adapter;
begin
result := nil;
if assigned( FBlockCipher) and assigned( FChaining) then exit;
if Supports( Params, IBlockCipherSelector, BlockCipherSelector) then
begin
BlockCipher := BlockCipherSelector.GetBlockCipher;
Chaining := BlockCipherSelector.GetChainMode;
end;
if not (assigned( BlockCipher) or assigned( Chaining)) then exit;
Newbie := TCSharpStreamToBlock_Adapter.Create;
Newbie.FBlockCipher := BlockCipher;
Newbie.FChaining := Chaining;
result := Newbie
end;
function TCSharpStreamToBlock_Adapter.ProgId: string;
begin
result := 'CSharp.StreamToBlock'
end;
function TCSharpStreamToBlock_Adapter.SeedByteSize: integer;
begin
if assigned( FBlockCipher) then
result := FBlockCipher.SeedByteSize
else
result := -1
end;
procedure NotSupported;
begin
raise Exception.Create('Feature not supported.');
end;
function TCSharpStreamToBlock_Adapter.Start_Decrypt(
Key: TSymetricKey; PlainText: TStream): IStreamDecryptor;
begin
if cfNoNounce in FChaining.ChainingFeatures then
NotSupported
else
result := TCSharpDecryptor.Start_Decrypt(
Key, PlainText, FBlockCipher, FChaining)
end;
function TCSharpStreamToBlock_Adapter.Start_Encrypt(
Key: TSymetricKey; CipherText: TStream): IStreamEncryptor;
begin
NotSupported
end;
function TCSharpStreamToBlock_Adapter.WikipediaReference: string;
begin
result := ''
end;
constructor TCSharpDecryptor.Start_Decrypt(
Key1: TSymetricKey; EmissionStream1: TStream;
const BlockCipher1: IBlockCipher;
const Chaining1: IBlockChainingModel);
begin
FEmissionStream := EmissionStream1;
FBlockCipher := BlockCipher1;
FChaining := Chaining1;
FEmitBuffer := TMemoryStream.Create;
FBuffer := TMemoryStream.Create;
FBlockLen := FBlockCipher.BlockSize div 8;
FCodec := FBlockCipher.MakeBlockCodec( Key1);
FBuffer.Size := FBlockLen;
FLenBuffer := 0;
FEmitBuffer.Size := FBlockLen;
FIV := TMemoryStream.Create;
FChainState := nil;
FDataCount := 0;
FisAutoXOR := ([cfKeyStream, cfAutoXOR] * FChaining.ChainingFeatures) =
[cfKeyStream, cfAutoXOR];
Fis8bitMode := (cf8bit in FChaining.ChainingFeatures) and
(cfKeyStream in FChaining.ChainingFeatures) and
(not (cfNoNounce in FChaining.ChainingFeatures));
// A chaining mode with cf8Bit MUST also have
// cfKeyStream and not cfNoNounce
FKey := Key1;
FLenBuffer := 0;
FIV.Size := 0;
end;
procedure TCSharpDecryptor.Chained_Decrypt_Block(
Plaintext, Ciphertext: TMemoryStream);
begin
Plaintext.Position := 0;
Ciphertext.Position := 0;
FChainState.Decrypt_Block( Plaintext, Ciphertext)
end;
destructor TCSharpDecryptor.Destroy;
begin
FDataCount := 0;
BurnMemoryStream( FEmitBuffer); FEmitBuffer.Free;
BurnMemoryStream( FBuffer); FBuffer.Free;
FCodec.Burn;
FCodec := nil;
if assigned( FChainState) then
begin
FChainState.Burn;
FChainState.Free
end;
BurnMemoryStream( FIV);
FIV.Free;
inherited
end;
procedure TCSharpDecryptor.Emit(
SourceBuf: TMemoryStream; EmitLen: integer = -1);
var
PlaintextByte, CiphertextByte: byte;
P, Q: PByte;
j: integer;
begin
if EmitLen = -1 then
EmitLen := FBlockLen;
if Fis8bitMode then
begin
P := SourceBuf.Memory;
Q := FEmitBuffer.Memory;
for j := 0 to EmitLen - 1 do
begin
CiphertextByte := P^;
FChainState.Decrypt_8bit( PlaintextByte, CiphertextByte);
Q^ := PlaintextByte;
Inc( P); Inc( Q)
end
end
else
Chained_Decrypt_Block( FEmitBuffer, SourceBuf);
if FisAutoXOR then
XOR_Streams2( FEmitBuffer, SourceBuf);
FEmissionStream.WriteBuffer( FEmitBuffer.Memory^, EmitLen)
end;
procedure TCSharpDecryptor.Emit_1stBuffer;
begin
if FLenBuffer = 0 then exit;
Emit( FBuffer, FLenBuffer);
FLenBuffer := 0
end;
procedure TCSharpDecryptor.Reset;
begin
BurnMemory( FEmitBuffer.Memory^, FBlockLen);
BurnMemory( FBuffer .Memory^, FBlockLen);
FCodec.Reset;
FLenBuffer := 0;
FDataCount := 0;
BurnMemoryStream( FIV);
if assigned( FChainState) then
begin
FChainState.Burn;
FChainState.Free;
FChainState := nil
end
end;
procedure TCSharpDecryptor.Decrypt( const Ciphertext: TStream);
var
X: int64;
Amnt: integer;
//Tmp: TMemoryStream;
//OldSize: integer;
begin
Ciphertext.Position := 0;
X := Ciphertext.Size;
while (X > 0) or (FLenBuffer = FBlockLen) do
begin
// 1. Read the IV.
if (FIV.Size < FBlockLen) and (X > 0) then
begin
Amnt := FBlockLen - FIV.Size;
if X < Amnt then
Amnt := X;
FIV.CopyFrom( Ciphertext, Amnt);
Dec( X, Amnt);
continue
end;
// 2. Now process the payload
Amnt := FBlockLen - FLenBuffer;
if X < Amnt then
Amnt := X;
if Amnt > 0 then
begin
ReadMem( Ciphertext, FBuffer, FLenBuffer, Amnt);
Dec( X, Amnt);
Inc( FLenBuffer, Amnt);
Inc( FDataCount, Amnt)
end;
if FLenBuffer = FBlockLen then
begin
if not assigned( FChainState) then
FChainState := FChaining.Chain_DecryptBlock( FKey, FIV, FCodec);
Emit_1stBuffer
end
end
end;
procedure TCSharpDecryptor.End_Decrypt;
//var
// ChainStateClone: TBlockChainLink;
begin
if FDataCount = 0 then
begin end
else
begin
FisAutoXOR := ([cfKeyStream, cfAutoXOR] * FChaining.ChainingFeatures) =
[cfKeyStream, cfAutoXOR];
if not assigned( FChainState) then
FChainState := FChaining.Chain_DecryptBlock( FKey, FIV, FCodec);
if (FLenBuffer = 0) or (cfKeyStream in FChaining.ChainingFeatures) then
Emit_1stBuffer
else
begin
Reset;
raise Exception.Create('Ciphertext not zero padded');
end
end;
Reset
end;
function StreamToBlock_Adapter_CSharpVariant: IStreamCipher;
begin
result := TCSharpStreamToBlock_Adapter.Create
end;
end.
|
//*******************************************************//
// //
// DelphiFlash.com //
// Copyright (c) 2004-2008 FeatherySoft, Inc. //
// info@delphiflash.com //
// //
//*******************************************************//
// Description: Streams for reading and writing of SWF file
// Last update: 12 mar 2008
{$I defines.inc}
unit SWFStreams;
interface
Uses Windows, Classes, SysUtils,
SWFConst, Contnrs, SWFObjects;
type
TSWFTagInfo = class (TObject)
BodySize: LongInt;
FramePlace: Word;
isLongSize: Boolean;
Position: LongInt;
SubTags: TObjectList;
selfDestroy: boolean;
SWFObject: TSWFObject;
TagID: Word;
constructor Create(ID: word; automake: boolean = true);
destructor Destroy; override;
function GetFullSize: LongInt;
end;
TBasedSWFStream = class;
TProgressWorkType = (pwtReadStream, pwtMakeStream, pwtCompressStream, pwtLoadXML, pwtParseXML, pwtSaveXML);
TSWFProgressEvent = procedure (sender: TBasedSWFStream; Percent: byte; WT: TProgressWorkType) of object;
TSWFParseTagBodyEvent = procedure (sender: TSWFTagInfo; var Parse: boolean) of object;
TSWFProcessTagEvent = procedure (sender: TSWFObject; var Process: boolean) of object;
TSWFRenameObjectEvent = procedure (sender: TSWFObject; var newname: string) of object;
// ================== TBasedSWFStream =========================
TBasedSWFStream = class (TObject)
private
FBodyStream: TStream;
SelfBodyStream: boolean;
FCompressed: Boolean;
FMultCoord: Byte;
FOnProgress: TSWFProgressEvent;
FSystemCoord: TSWFSystemCoord;
function GetBodyStream: TStream;
function GetFPS: Single;
function GetHeight: Integer;
function GetSWFRect: TRect;
function GetWidth: Integer;
procedure SetBodyStream(Src: TStream);
procedure SetCompressed(compr: Boolean);
procedure SetFPS(v: Single);
procedure SetHeight(Value: Integer);
procedure SetSystemCoord(v: TSWFSystemCoord);
procedure SetVersion(v: Byte);
procedure SetWidth(Value: Integer);
procedure OnProgressCompress(sender: TObject);
protected
procedure DoChangeHeader; virtual;
public
SWFHeader: TSWFHeader;
constructor Create; overload; virtual;
constructor Create(XMin, YMin, XMax, YMax: integer; fps: single; sc: TSWFSystemCoord = scTwips); overload; virtual;
destructor Destroy; override;
function FramePos(num: word): longint; virtual; abstract;
function GetHeaderSize: Integer;
procedure MakeStream; virtual; abstract;
procedure MoveResource(ToFrame, StartFrom, EndFrom: integer); virtual; abstract;
procedure SaveToFile(fn: string);
procedure SaveToStream(Stream: TStream);
procedure SetSWFRect(v: TRect);
procedure WriteHeader(stream: TStream; part: TSWFHeaderPart = hpAll);
property BodyStream: TStream read GetBodyStream write SetBodyStream;
property Compressed: Boolean read FCompressed write SetCompressed;
property FPS: Single read GetFPS write SetFPS;
property FramesCount: Word read SWFHeader.FramesCount;
property Height: Integer read GetHeight write SetHeight;
property MovieRect: TRect read GetSWFRect write SWFHeader.MovieRect;
property MultCoord: Byte read FMultCoord write FMultCoord;
property SystemCoord: TSWFSystemCoord read FSystemCoord write SetSystemCoord;
property Version: Byte read SWFHeader.Version write SetVersion;
property Width: Integer read GetWidth write SetWidth;
property OnProgress: TSWFProgressEvent read FOnProgress write FOnProgress;
end;
TSWFStreamReader = class (TBasedSWFStream)
private
FIsSWF: Boolean;
FOnParseTagBody: TSWFParseTagBodyEvent;
FOnRenameObject: TSWFRenameObjectEvent;
FOnRenumberTag: TSWFProcessTagEvent;
FTagList: TObjectList;
function GetTagInfo(index: word): TSWFTagInfo;
public
constructor Create(fn: string); overload;
constructor Create(stream: TStream); overload;
destructor Destroy; override;
function CheckSWF(stest: TStream): Boolean;
procedure DeleteTagByID(Place, Obj: boolean; ID: word);
procedure DeleteTagByName(Place, Obj: boolean; name: string);
function FindIDFromName(name: string): word;
function FindObjectFromID(ID: word): TSWFObject;
function FindObjectFromName(name: string): TSWFObject;
function FindPlaceFromID(ID: word): TSWFPlaceObject;
function FindPlaceFromName(name: string): TSWFPlaceObject2;
function FindTagFromID(ID: word): longint;
function FindTagFromObject(Obj: TSWFObject): longint;
function FindTagFromName(name: string): longint;
function FramePos(num: word): longint; override;
function GetMinVersion: Byte;
procedure LoadFromFile(fn: string);
procedure LoadFromStream(stream: TStream);
function LoadHeader(src: TStream; part: TSWFHeaderPart = hpAll): Integer;
procedure MakeStream; override;
procedure MoveResource(ToFrame, StartFrom, EndFrom: integer); override;
procedure ReadBody(ParseTagData, ParseActionData: boolean);
procedure Rename(prefix: string);
function Renumber(start: word): Word;
property IsSWF: Boolean read FIsSWF;
property OnParseTagBody: TSWFParseTagBodyEvent read FOnParseTagBody write FOnParseTagBody;
property OnRenameObject: TSWFRenameObjectEvent read FOnRenameObject write FOnRenameObject;
property OnRenumberTag: TSWFProcessTagEvent read FOnRenumberTag write FOnRenumberTag;
property TagInfo[index: word]: TSWFTagInfo read GetTagInfo;
property TagList: TObjectList read FTagList;
end;
implementation
Uses
SWFTools, Zlib, Math;
//=============== TBasedSWFStream ========================
{
****************************************************** TBasedSWFStream ******************************************************
}
constructor TBasedSWFStream.Create;
begin
inherited Create;
SWFHeader.Version := 5; // default Version
SystemCoord := scTwips;
end;
constructor TBasedSWFStream.Create(XMin, YMin, XMax, YMax: integer; fps: single; sc: TSWFSystemCoord = scTwips);
begin
inherited Create;
SystemCoord := sc;
SWFHeader.Version := 5; // default Version
SWFHeader.MovieRect := rect(XMin * MultCoord, YMin * MultCoord, XMax * MultCoord, YMax * MultCoord);
SetFPS(fps);
end;
destructor TBasedSWFStream.Destroy;
begin
if Assigned(FBodyStream) and SelfBodyStream then FBodyStream.Free;
inherited;
end;
procedure TBasedSWFStream.DoChangeHeader;
begin
// empty
end;
function TBasedSWFStream.GetBodyStream: TStream;
begin
if not Assigned(FBodyStream) then
begin
FBodyStream := TMemoryStream.Create;
SelfBodyStream := true;
end;
Result := FBodyStream;
end;
function TBasedSWFStream.GetFPS: Single;
begin
Result:=WordToSingle(SWFHeader.FPS);
end;
function TBasedSWFStream.GetHeaderSize: Integer;
begin
With SWFHeader.MovieRect do
Result := 12 + Ceil((5 + 4*GetBitsCount(SWFTools.MaxValue(left, top, right, bottom), 1)) / 8);
end;
function TBasedSWFStream.GetHeight: Integer;
begin
Result := (SWFHeader.MovieRect.Bottom - SWFHeader.MovieRect.Top) div MultCoord;
end;
function TBasedSWFStream.GetSWFRect: TRect;
begin
Result := Rect(SWFHeader.MovieRect.Left div MultCoord,
SWFHeader.MovieRect.Top div MultCoord,
SWFHeader.MovieRect.Right div MultCoord,
SWFHeader.MovieRect.Bottom div MultCoord);
end;
function TBasedSWFStream.GetWidth: Integer;
begin
Result := (SWFHeader.MovieRect.Right - SWFHeader.MovieRect.Left) div MultCoord;
end;
procedure TBasedSWFStream.SetBodyStream(Src: TStream);
begin
if (SelfBodyStream) then
FreeAndNil(FBodyStream);
FBodyStream := Src;
SelfBodyStream := false;
end;
procedure TBasedSWFStream.SaveToFile(fn: string);
var
fs: TFileStream;
begin
if fileExists(fn) then DeleteFile(fn);
try // added by Mironichev
fs := TFileStream.Create(fn, fmCreate);
SaveToStream(fs);
finally // added by Mironichev
fs.Free;
end;
end;
procedure TBasedSWFStream.SaveToStream(Stream: TStream);
var
CS: TCompressionStream;
begin
SWFHeader.FileSize := GetHeaderSize + BodyStream.Size;
BodyStream.Position:= 0;
if Compressed then
begin
SWFHeader.SIGN:=SWFSignCompress;
if SWFHeader.Version < SWFVer6 then SWFHeader.Version := SWFVer6;
WriteHeader(Stream, hp1);
CS := TCompressionStream.Create(clDefault, Stream);
CS.OnProgress := OnProgressCompress;
WriteHeader(CS, hp2);
CS.CopyFrom(BodyStream, BodyStream.Size);
CS.Free;
end
else
begin
SWFHeader.SIGN := SWFSign;
WriteHeader(Stream);
Stream.CopyFrom(BodyStream, BodyStream.Size);
end;
end;
procedure TBasedSWFStream.SetCompressed(compr: Boolean);
begin
FCompressed := compr;
if Compressed and (Version < SWFVer6) then SWFHeader.Version := SWFVer6;
DoChangeHeader;
end;
procedure TBasedSWFStream.OnProgressCompress(sender: TObject);
begin
if Assigned(FOnProgress) then
FOnProgress(self, Round(TStream(Sender).Position / (BodyStream.Size - 22) * 100), pwtCompressStream);
end;
procedure TBasedSWFStream.SetFPS(v: Single);
begin
SWFHeader.FPS := SingleToWord(v);
DoChangeHeader;
end;
procedure TBasedSWFStream.SetHeight(Value: Integer);
begin
SWFHeader.MovieRect.Bottom := SWFHeader.MovieRect.Top + Value * MultCoord;
DoChangeHeader;
end;
procedure TBasedSWFStream.SetSWFRect(v: TRect);
begin
SWFHeader.MovieRect := Rect(v.Left * MultCoord, v.Top * MultCoord,
v.Right * MultCoord, v.Bottom * MultCoord);
DoChangeHeader;
end;
procedure TBasedSWFStream.SetSystemCoord(v: TSWFSystemCoord);
begin
if v = scTwips then MultCoord := 1 else MultCoord := 20;
fSystemCoord := v;
end;
procedure TBasedSWFStream.SetVersion(v: Byte);
begin
if Compressed and (v < SWFVer6) then SWFHeader.Version := SWFVer6
else SWFHeader.Version := v;
DoChangeHeader;
end;
procedure TBasedSWFStream.SetWidth(Value: Integer);
begin
SWFHeader.MovieRect.Right := SWFHeader.MovieRect.Left + Value * MultCoord;
DoChangeHeader;
end;
procedure TBasedSWFStream.WriteHeader(stream: TStream; part: TSWFHeaderPart = hpAll);
var
BE: TBitsEngine;
begin
if part in [hpAll, hp1] then stream.Write(SWFHeader, SizeOfhp1);
if part in [hpAll, hp2] then
begin
BE:=TBitsEngine.Create(stream);
BE.WriteRect(SWFHeader.MovieRect);
BE.Free;
stream.Write(SWFheader.FPS, 2);
stream.Write(SWFheader.FramesCount, 2);
end;
end;
{
******************************************************** TSWFTagInfo ********************************************************
}
constructor TSWFTagInfo.Create(ID: word; automake: boolean = true);
begin
inherited Create;
TagID := ID;
selfDestroy := true;
if automake then
SWFObject := GenerateSWFObject(ID);
if ID in [tagDefineSprite] then SubTags := TObjectList.Create;
end;
destructor TSWFTagInfo.Destroy;
begin
if selfDestroy and Assigned(SWFObject) then SWFObject.Free;
if SubTags<>nil then SubTags.Free;
inherited;
end;
function TSWFTagInfo.GetFullSize: LongInt;
begin
Result := BodySize + 2 + Byte(isLongSize) * 4;
end;
//=============== TSWFStreamReader ========================
{
***************************************************** TSWFStreamReader ******************************************************
}
constructor TSWFStreamReader.Create(fn: string);
begin
inherited Create;
fTagList := TObjectList.Create;
if fn <> '' then LoadFromFile(fn);
end;
constructor TSWFStreamReader.Create(stream: TStream);
begin
inherited Create;
fTagList := TObjectList.Create;
LoadFromStream(stream);
end;
destructor TSWFStreamReader.Destroy;
begin
fTagList.Free;
inherited;
end;
function TSWFStreamReader.CheckSWF(stest: TStream): Boolean;
var
Sign: array [0..2] of char;
begin
result := false;
if stest.Size > 3 then
begin
stest.Seek(0, 0);
stest.Read(Sign, 3);
if (SWFSign = Sign) or (SWFSignCompress = Sign) then
begin
result := true;
fCompressed := SWFSignCompress = Sign;
end;
end;
fisSWF := result;
end;
procedure TSWFStreamReader.DeleteTagByID(Place, obj: boolean; ID: word);
var il, il2, iTag: longint;
begin
if FTagList.Count = 0 then exit;
if obj then
begin
iTag := FindTagFromID(ID);
FTagList.Delete(iTag);
Place := true;
end;
if Place then
begin
il := 0;
while il < FTagList.Count do
begin
Case TagInfo[il].TagID of
tagPlaceObject, tagPlaceObject2, tagPlaceObject3:
if ID = TSWFBasedPlaceObject(TagInfo[il].SWFObject).CharacterId then
begin
FTagList.Delete(il);
dec(il);
end;
tagDefineSprite:
with TSWFDefineSprite(TagInfo[il].SWFObject) do
if ControlTags.Count > 0 then
begin
il2 := 0;
while il2 < ControlTags.Count do
case TSWFObject(ControlTags[il2]).TagID of
tagPlaceObject, tagPlaceObject2, tagPlaceObject3:
begin
TagInfo[il].SubTags.Delete(il2);
ControlTags.Delete(il2);
dec(il2);
end;
end;
end;
end;
inc(il);
end;
end;
end;
procedure TSWFStreamReader.DeleteTagByName(Place, Obj: boolean; name: string);
var
il, il2, iTag: longint;
PO: TSWFPlaceObject2;
isend: boolean;
begin
if FTagList.Count = 0 then exit;
isend := false;
if fTagList.Count = 0 then exit;
For il := 0 to fTagList.Count - 1 do
begin
Case TagInfo[il].TagID of
tagPlaceObject2, tagPlaceObject3:
begin
PO := TSWFPlaceObject2(TagInfo[il].SWFObject);
if name = PO.Name then
begin
iTag := FindTagFromID(PO.CharacterId);
if obj then
FTagList.Delete(iTag);
if obj or Place then
FTagList.Delete(il - byte(il > iTag)* byte(obj));
Break;
end;
end;
tagExportAssets:
if obj then
with TSWFExportAssets(TagInfo[il].SWFObject) do
if Assets.Count > 0 then
begin
il2 := Assets.Count - 1;
iTag := 0;
while il2 >= 0 do
begin
if Assets[il2] = name then
begin
iTag := FindTagFromID(Longint(Assets.Objects[il2]));
if iTag > -1 then
begin
FTagList.Delete(iTag);
Assets.Delete(il2);
isend := true;
Break;
end;
end;
dec(il2);
end;
if Assets.Count = 0 then FTagList.Delete(il - byte(il > iTag));
if isend then Break;
end;
end;
end;
end;
function TSWFStreamReader.FindIDFromName(name: string): word;
var
il, il2: Word;
PO: TSWFPlaceObject2;
begin
Result := 0;
if fTagList.Count = 0 then exit;
For il := 0 to fTagList.Count - 1 do
begin
Case TagInfo[il].TagID of
tagDefineSprite:
with TSWFDefineSprite(TagInfo[il].SWFObject) do
if ControlTags.Count > 0 then
begin
for il2 := 0 to ControlTags.Count - 1 do
if TSWFObject(ControlTags[il2]).TagID in [tagPlaceObject2, tagPlaceObject3] then
begin
PO := TSWFPlaceObject2(ControlTags[il2]);
if PO.PlaceFlagHasName and PO.PlaceFlagHasCharacter and (name = PO.Name) then
begin
Result := PO.CharacterId;
Break;
end;
end;
if Result > 0 then Break;
end;
tagPlaceObject2, tagPlaceObject3:
begin
if name = TSWFPlaceObject2(TagInfo[il].SWFObject).Name then
begin
Result := TSWFPlaceObject2(TagInfo[il].SWFObject).CharacterId;
Break;
end;
end;
tagExportAssets:
with TSWFExportAssets(TagInfo[il].SWFObject) do
if Assets.Count > 0 then
begin
for il2 := 0 to Assets.Count - 1 do
if Assets[il2] = name then
begin
Result := Longint(Assets.Objects[il2]);
Break;
end;
if Result > 0 then Break;
end;
end;
end;
end;
function TSWFStreamReader.FindObjectFromID(ID: word): TSWFObject;
var
il: LongInt;
begin
il := FindTagFromID(ID);
if il = -1 then Result := nil else Result := TagInfo[il].SWFObject;
end;
function TSWFStreamReader.FindTagFromID(ID: word): longint;
var
il, il2: LongInt;
begin
Result := -1;
if FTagList.Count = 0 then exit;
For il := 0 to FTagList.Count - 1 do
begin
Case TagInfo[il].TagID of
tagDefineShape, tagDefineShape2, tagDefineShape3, tagDefineShape4:
if TSWFDefineShape(TagInfo[il].SWFObject).ShapeId = ID then
Result := il;
tagDefineMorphShape, tagDefineMorphShape2:
if TSWFDefineMorphShape(TagInfo[il].SWFObject).CharacterID = ID then
Result := il;
tagDefineBits, tagDefineBitsJPEG2, tagDefineBitsJPEG3,
tagDefineBitsLossless, tagDefineBitsLossless2 :
if TSWFImageTag(TagInfo[il].SWFObject).CharacterID = ID then
Result := il;
tagDefineFont, tagDefineFont2, tagDefineFont3:
if TSWFDefineFont(TagInfo[il].SWFObject).FontID = ID then
Result := il;
tagDefineFontInfo2:
if TSWFDefineFontInfo2(TagInfo[il].SWFObject).FontID = ID then
Result := il;
tagDefineText, tagDefineText2:
if TSWFDefineText(TagInfo[il].SWFObject).CharacterID = ID then
Result := il;
tagDefineEditText:
if TSWFDefineEditText(TagInfo[il].SWFObject).CharacterID = ID then
Result := il;
tagDefineSound:
if TSWFDefineSound(TagInfo[il].SWFObject).SoundId = ID then
Result := il;
tagDefineButton, tagDefineButton2:
if TSWFDefineButton(TagInfo[il].SWFObject).ButtonId = ID then
Result := il;
tagDefineSprite:
if TSWFDefineSprite(TagInfo[il].SWFObject).SpriteID = ID then
Result := il;
tagDefineVideoStream:
if TSWFDefineVideoStream(TagInfo[il].SWFObject).CharacterID = ID then
Result := il;
tagImportAssets:
with TSWFImportAssets(TagInfo[il].SWFObject) do
if Assets.Count > 0 then
for il2 := 0 to Assets.Count - 1 do
if Longint(Assets.Objects[il2]) = ID then
begin
Result := il;
Break;
end;
end;
if Result > -1 then Break;
end;
end;
function TSWFStreamReader.FindObjectFromName(name: string): TSWFObject;
var
il, il2: Word;
PO: TSWFPlaceObject2;
begin
Result := nil;
if fTagList.Count = 0 then exit;
For il := 0 to fTagList.Count - 1 do
begin
Case TagInfo[il].TagID of
tagDefineSprite:
with TSWFDefineSprite(TagInfo[il].SWFObject) do
if ControlTags.Count > 0 then
begin
for il2 := 0 to ControlTags.Count - 1 do
if TSWFObject(ControlTags[il2]).TagID in [tagPlaceObject2, tagPlaceObject3] then
begin
PO := TSWFPlaceObject2(ControlTags[il2]);
if PO.PlaceFlagHasName and PO.PlaceFlagHasCharacter and (name = PO.Name) then
begin
Result := FindObjectFromID(PO.CharacterId);
if Result <> nil then Break;
end;
end;
if Result <> nil then Break;
end;
tagPlaceObject2, tagPlaceObject3:
begin
if name = TSWFPlaceObject2(TagInfo[il].SWFObject).Name then
begin
Result := FindObjectFromID(TSWFPlaceObject2(TagInfo[il].SWFObject).CharacterId);
if Result <> nil then Break;
end;
end;
tagExportAssets:
with TSWFExportAssets(TagInfo[il].SWFObject) do
if Assets.Count > 0 then
begin
for il2 := 0 to Assets.Count - 1 do
if Assets[il2] = name then
begin
Result := FindObjectFromID(Longint(Assets.Objects[il2]));
if Result <> nil then Break;
end;
end;
end;
end;
end;
function TSWFStreamReader.FindPlaceFromID(ID: word): TSWFPlaceObject;
var
il, il2: Word;
PO: TSWFPlaceObject2;
begin
Result := nil;
if fTagList.Count = 0 then exit;
For il := 0 to fTagList.Count - 1 do
Case TagInfo[il].TagID of
tagDefineSprite:
with TSWFDefineSprite(TagInfo[il].SWFObject) do
if ControlTags.Count > 0 then
begin
for il2 := 0 to ControlTags.Count - 1 do
if TSWFObject(ControlTags[il2]).TagID in [tagPlaceObject2, tagPlaceObject3] then
begin
PO := TSWFPlaceObject2(ControlTags[il2]);
if PO.PlaceFlagHasCharacter and (ID = PO.CharacterID) then
begin
Result := TSWFPlaceObject(PO);
Break;
end;
end;
if Result <> nil then Break;
end;
tagPlaceObject2, tagPlaceObject3:
begin
PO := TSWFPlaceObject2(TagInfo[il].SWFObject);
if PO.PlaceFlagHasCharacter and (PO.CharacterId = ID) then
begin
Result := TSWFPlaceObject(PO);
Break;
end;
end;
end;
end;
function TSWFStreamReader.FindPlaceFromName(name: string): TSWFPlaceObject2;
var
il, il2: Word;
PO: TSWFPlaceObject2;
begin
Result := nil;
if fTagList.Count = 0 then exit;
For il := 0 to fTagList.Count - 1 do
Case TagInfo[il].TagID of
tagDefineSprite:
with TSWFDefineSprite(TagInfo[il].SWFObject) do
if ControlTags.Count > 0 then
begin
for il2 := 0 to ControlTags.Count - 1 do
if TSWFObject(ControlTags[il2]).TagID in [tagPlaceObject2, tagPlaceObject3] then
begin
PO := TSWFPlaceObject2(ControlTags[il2]);
if name = PO.Name then
begin
Result := PO;
Break;
end;
end;
if Result <> nil then Break;
end;
tagPlaceObject2, tagPlaceObject3:
begin
PO := TSWFPlaceObject2(TagInfo[il].SWFObject);
if name = PO.Name then
begin
Result := PO;
Break;
end;
end;
end;
end;
function TSWFStreamReader.FindTagFromObject(obj: TSWFObject): longint;
var il: longint;
begin
Result := -1;
for il := 0 to TagList.Count - 1 do
if obj = TagInfo[il].SWFObject then
begin
Result := il;
Break;
end;
end;
function TSWFStreamReader.FramePos(num: word): longint;
var il, cur: longint;
begin
cur := 0;
Result := 0;
if (num = 0) or (TagList.Count = 0) then Exit;
Result := -1;
for il := 0 to TagList.Count - 1 do
if TagInfo[il].TagID = tagShowFrame then
begin
inc(cur);
if num = cur then
begin
Result := il;
Break;
end;
end;
if Result = -1 then Result := TagList.Count - 1;
end;
function TSWFStreamReader.FindTagFromName(name: string): longint;
var
il, il2: Word;
PO: TSWFPlaceObject2;
begin
Result := -1;
if fTagList.Count = 0 then exit;
For il := 0 to fTagList.Count - 1 do
begin
Case TagInfo[il].TagID of
tagDefineSprite:
with TSWFDefineSprite(TagInfo[il].SWFObject) do
if ControlTags.Count > 0 then
begin
for il2 := 0 to ControlTags.Count - 1 do
if TSWFObject(ControlTags[il2]).TagID in [tagPlaceObject2, tagPlaceObject3] then
begin
PO := TSWFPlaceObject2(ControlTags[il2]);
if PO.PlaceFlagHasName and PO.PlaceFlagHasCharacter and (name = PO.Name) then
begin
Result := FindTagFromID(PO.CharacterId);
if Result > -1 then Break;
end;
end;
if Result > -1 then Break;
end;
tagPlaceObject2, tagPlaceObject3:
begin
if name = TSWFPlaceObject2(TagInfo[il].SWFObject).Name then
begin
Result := FindTagFromID(TSWFPlaceObject2(TagInfo[il].SWFObject).CharacterId);
if Result > -1 then Break;
end;
end;
tagExportAssets:
with TSWFExportAssets(TagInfo[il].SWFObject) do
if Assets.Count > 0 then
begin
for il2 := 0 to Assets.Count - 1 do
if Assets[il2] = name then
begin
Result := FindTagFromID(Longint(Assets.Objects[il2]));
if Result > -1 then Break;
end;
end;
end;
end;
end;
function TSWFStreamReader.GetMinVersion: Byte;
var
il: Integer;
SWFObject: TSWFObject;
begin
Result := 1;
if fTagList.Count = 0 then exit;
for il:=0 to fTagList.Count - 1 do
begin
SWFObject := TSWFTagInfo(fTagList.Items[il]).SWFObject;
if (SWFObject<>nil) and (Result < SWFObject.MinVersion) then
Result := SWFObject.MinVersion;
end;
end;
function TSWFStreamReader.GetTagInfo(index: word): TSWFTagInfo;
begin
Result := TSWFTagInfo(TagList[index]);
end;
procedure TSWFStreamReader.LoadFromFile(fn: string);
var
fs: TFileStream;
begin
fs:= TFileStream.Create(fn, fmOpenRead);
LoadFromStream(fs);
fs.Free;
end;
procedure TSWFStreamReader.LoadFromStream(stream: TStream);
var
ZStream: TDeCompressionStream;
tmpMem: TMemoryStream;
begin
if CheckSWF(stream) then
begin
stream.Position:=0;
if fCompressed then
begin
LoadHeader(stream, hp1);
ZStream := TDeCompressionStream.Create(stream);
try
tmpMem := TMemoryStream.Create;
tmpMem.CopyFrom(ZStream, SWFHeader.FileSize - SizeOfhp1);
tmpMem.Position := 0;
LoadHeader(tmpMem, hp2);
BodyStream.CopyFrom(tmpMem, tmpMem.Size - tmpMem.Position);
tmpMem.Free;
finally
ZStream.free;
end;
end else
begin
LoadHeader(stream);
BodyStream.CopyFrom(stream, stream.size - stream.Position);
end;
end;
end;
function TSWFStreamReader.LoadHeader(src: TStream; part: TSWFHeaderPart = hpAll): Integer;
var
BE: TBitsEngine;
begin
Result := src.Position;
if part in [hpAll, hp1] then src.Read(SWFHeader, SizeOfhp1);
if part in [hpAll, hp2] then
begin
BE:=TBitsEngine.Create(src);
SWFHeader.MovieRect := BE.ReadRect;
SWFHeader.FPS := BE.ReadWord;
SWFHeader.FramesCount := BE.ReadWord;
BE.Free;
end;
Result := src.Position - Result;
end;
procedure TSWFStreamReader.MakeStream;
var
NewBody: TMemoryStream;
il: LongInt;
BE: TBitsEngine;
begin
NewBody := TMemoryStream.Create;
BE := TBitsEngine.Create(NewBody);
if TagList.Count > 0 then
for il := 0 to TagList.Count - 1 do
begin
if Assigned(FOnProgress) then FOnProgress(self, Round((il+1)/TagList.Count*100), pwtMakeStream);
if TagInfo[il].SWFObject = nil then
begin
BodyStream.Position := TagInfo[il].Position;
NewBody.CopyFrom(BodyStream, TagInfo[il].GetFullSize);
end else TagInfo[il].SWFObject.WriteToStream(BE);
end;
BodyStream := NewBody;
SelfBodyStream := true;
BE.Free;
end;
procedure TSWFStreamReader.MoveResource(ToFrame, StartFrom, EndFrom: integer);
var il, iDelta, iTo, iStart, iEnd: longint;
begin
if ToFrame > StartFrom then ToFrame := StartFrom;
if EndFrom = -1 then EndFrom := FramesCount else
if (EndFrom = 0) or (EndFrom < StartFrom) then EndFrom := StartFrom;
iDelta := 0;
iTo := FramePos(ToFrame);
if TagInfo[iTo].TagID = tagShowFrame then inc(iTo);
if ToFrame = StartFrom
then iStart := iTo + 1
else iStart := FramePos(StartFrom) + 1;
iEnd := FramePos(EndFrom + 1);
if TagInfo[iEnd].TagID = tagShowFrame then dec(iEnd);
if iStart < iEnd then
for il := iStart to iEnd do
if TagInfo[il].TagID in [tagDefineBits,
tagJPEGTables, tagDefineBitsJPEG2, tagDefineBitsJPEG3,
tagDefineBitsLossless, tagDefineBitsLossless2,
tagDefineFont, tagDefineFont2, tagDefineFont3, tagDefineSound]
then
begin
TagList.Move(il, iTo + iDelta);
inc(iDelta);
end;
end;
procedure TSWFStreamReader.ReadBody(ParseTagData, ParseActionData: boolean);
var
SWFTag, SWFSubTag: TSWFTagInfo;
Obj: TSWFObject;
TmpW: Word;
CFrame, il: Word;
BE: TBitsEngine;
M1Pos, BodyPos: LongInt;
ET: TSWFByteCodeTag;
ParseBody: Boolean;
SndRoot: byte;
begin
CFrame := 1;
if fTagList.Count > 0 then fTagList.Clear;
BodyStream.Position := 0;
BE:= TBitsEngine.Create(BodyStream);
SndRoot := 0;
{$IFDEF UNREGISTRED}
ParseActionData := false;
{$ENDIF}
While BodyStream.Position < BodyStream.Size do
begin
if Assigned(FOnProgress) then FOnProgress(self, Round(BodyStream.Position / BodyStream.Size * 100), pwtReadStream);
BodyStream.Read(TmpW, 2);
SWFTag := TSWFTagInfo.Create(TmpW shr 6, false);
SWFTag.Position := BodyStream.Position-2;
SWFTag.BodySize := (TmpW and $3f);
if SWFTag.BodySize = $3f then
begin
SWFTag.isLongSize:=true;
BodyStream.Read(SWFTag.BodySize, 4);
end else SWFTag.isLongSize := false;
SWFTag.FramePlace := CFrame;
if SWFTag.TagID = 1 then inc(CFrame);
fTagList.Add(SWFTag);
if ParseTagData then
begin
if Assigned(FOnParseTagBody) then
begin
ParseBody := true;
FOnParseTagBody(SWFTag, ParseBody);
if ParseBody then
SWFTag.SWFObject := GenerateSWFObject(SWFTag.TagID);
end else SWFTag.SWFObject := GenerateSWFObject(SWFTag.TagID);
end;
if (SWFTag.BodySize>0) and (SWFTag.SWFObject<>nil) then
begin
case SWFTag.SWFObject.TagID of
tagPlaceObject2, tagPlaceObject3:
with TSWFPlaceObject2(SWFTag.SWFObject) do
begin
SWFVersion := Version;
ParseActions := ParseActionData;
end;
tagDefineButton, tagDefineButton2:
TSWFBasedButton(SWFTag.SWFObject).ParseActions := ParseActionData;
tagDefineSprite:
with (TSWFDefineSprite(SWFTag.SWFObject)) do
begin
SWFVersion := Version;
ParseActions := ParseActionData;
end;
tagSoundStreamBlock:
TSWFSoundStreamBlock(SWFTag.SWFObject).StreamSoundCompression := SndRoot;
tagDefineFont2, tagDefineFont3:
TSWFDefineFont2(SWFTag.SWFObject).SWFVersion := Version;
tagDefineFontInfo:
TSWFDefineFontInfo(SWFTag.SWFObject).SWFVersion := Version;
tagDoAction, tagDoInitAction:
TSWFDoAction(SWFTag.SWFObject).ParseActions := ParseActionData;
tagDoABC:
TSWFDoABC(SWFTag.SWFObject).ParseActions := ParseActionData;
end;
M1Pos := BodyStream.Position;
BodyPos := M1Pos;
SWFTag.SWFObject.BodySize := SWFTag.BodySize;
try
SWFTag.SWFObject.ReadFromStream(BE);
except
on E: Exception do
begin
ET := TSWFByteCodeTag.Create;
ET.Text := E.Message;
ET.TagIDFrom := SWFTag.TagID;
ET.BodySize := SWFTag.BodySize;
SWFTag.SWFObject.Free;
SWFTag.SWFObject := ET;
SWFTag.TagID := ET.TagId;
end;
end;
case SWFTag.SWFObject.TagID of
tagSoundStreamHead, tagSoundStreamHead2:
SndRoot := TSWFSoundStreamHead(SWFTag.SWFObject).StreamSoundCompression;
tagDefineSprite:
With TSWFDefineSprite(SWFTag.SWFObject) do
begin
for il:=0 to ControlTags.Count - 1 do
begin
Obj := TSWFObject(ControlTags[il]);
SWFSubTag := TSWFTagInfo.Create(Obj.TagID, false);
SWFSubTag.SWFObject := Obj;
SWFSubTag.selfDestroy := false;
SWFSubTag.BodySize := Obj.BodySize;
SWFSubTag.Position := M1Pos;
inc(M1Pos, Obj.GetFullSize);
SWFTag.SubTags.Add(SWFSubTag);
end;
end;
end;
if BodyStream.Position <> (BodyPos + SWFTag.BodySize) then
begin
BodyStream.Position := (BodyPos + SWFTag.BodySize);
end;
end else
begin
BodyStream.Position := BodyStream.Position + SWFTag.BodySize;
end;
end;
BE.Free;
end;
procedure TSWFStreamReader.Rename(prefix: string);
var
il, il2: Integer;
newname: string;
CT: TSWFObject;
begin
if fTagList.Count = 0 then exit;
For il := 0 to fTagList.Count - 1 do
begin
if TagInfo[il].SWFObject <> nil then
Case TagInfo[il].TagID of
tagDefineSprite:
with TSWFDefineSprite(TagInfo[il].SWFObject) do
if ControlTags.Count > 0 then
begin
for il2 := 0 to ControlTags.Count - 1 do
begin
CT := TSWFObject(ControlTags[il2]);
if (CT.TagID in [tagPlaceObject2, tagPlaceObject3]) and TSWFPlaceObject2(CT).PlaceFlagHasName then
begin
newname := prefix + TSWFPlaceObject2(CT).Name;
if Assigned(OnRenameObject) then OnRenameObject(TSWFPlaceObject2(CT), newname);
TSWFPlaceObject2(CT).Name := newname;
end;
end;
end;
tagPlaceObject2, tagPlaceObject3:
with TSWFPlaceObject2(TagInfo[il].SWFObject) do
if PlaceFlagHasName then
begin
newname := prefix + Name;
if Assigned(OnRenameObject) then OnRenameObject(TagInfo[il].SWFObject, newname);
Name := newname;
end;
tagExportAssets:
with TSWFExportAssets(TagInfo[il].SWFObject) do
if Assets.Count > 0 then
for il2 := 0 to Assets.Count - 1 do
begin
newname := prefix + Assets[il2];
if Assigned(OnRenameObject) then OnRenameObject(TagInfo[il].SWFObject, newname);
Assets[il2] := newname;
end;
end;
end;
end;
function TSWFStreamReader.Renumber(start: word): Word;
var
il, il2, il3, NewInd: LongInt;
ListID: TList;
Process: Boolean;
SCR: TSWFStyleChangeRecord;
begin
Result := start;
if TagList.Count = 0 then Exit;
ListID := TList.Create;
for il := 0 to TagList.Count - 1 do
With TagInfo[il] do
begin
Process := SWFObject <> nil;
if Process and Assigned(FOnRenumberTag) then OnRenumberTag(SWFObject, Process);
if Process then
Case TagID of
tagDefineShape, tagDefineShape2, tagDefineShape3, tagDefineShape4:
with TSWFDefineShape(SWFObject) do
ShapeId := start + ListID.Add(Pointer(Longint(ShapeId)));
tagDefineMorphShape, tagDefineMorphShape2:
with TSWFDefineMorphShape(SWFObject) do
CharacterID := start + ListID.Add(Pointer(Longint(CharacterID)));
tagDefineBits, tagDefineBitsJPEG2, tagDefineBitsJPEG3,
tagDefineBitsLossless, tagDefineBitsLossless2:
with TSWFImageTag(SWFObject) do
CharacterID := start + ListID.Add(Pointer(Longint(CharacterID)));
tagDefineFont, tagDefineFont2, tagDefineFont3:
with TSWFDefineFont(SWFObject) do
FontID := start + ListID.Add(Pointer(Longint(FontID)));
tagDefineText, tagDefineText2:
with TSWFDefineText(SWFObject) do
CharacterID := start + ListID.Add(Pointer(Longint(CharacterID)));
tagDefineEditText:
with TSWFDefineEditText(SWFObject) do
CharacterID := start + ListID.Add(Pointer(Longint(CharacterID)));
tagDefineSound:
with TSWFDefineSound(SWFObject) do
SoundId := start + ListID.Add(Pointer(Longint(SoundId)));
tagDefineButton, tagDefineButton2:
with TSWFDefineButton(SWFObject) do
ButtonId := start + ListID.Add(Pointer(Longint(ButtonId)));
tagDefineSprite:
with TSWFDefineSprite(SWFObject) do
SpriteID := start + ListID.Add(Pointer(Longint(SpriteID)));
tagDefineVideoStream:
with TSWFDefineVideoStream(SWFObject) do
CharacterID := start + ListID.Add(Pointer(Longint(CharacterID)));
tagImportAssets, tagImportAssets2:
with TSWFImportAssets(SWFObject) do
if Assets.Count > 0 then
for il2 := 0 to Assets.Count - 1 do
begin
ListID.Add(Assets.Objects[il2]);
Assets.Objects[il2] := Pointer(Longint(start + ListID.Count - 1));
end;
end;
end;
for il := 0 to TagList.Count - 1 do
With TagInfo[il] do
Case TagID of
tagExportAssets:
with TSWFExportAssets(SWFObject) do
if Assets.Count > 0 then
for il2 := 0 to Assets.Count - 1 do
begin
NewInd := ListID.IndexOf(Assets.Objects[il2]);
if NewInd > -1 then
Assets.Objects[il2] := Pointer(Longint(start + NewInd));
end;
tagDoInitAction:
with TSWFDoInitAction(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(SpriteID)));
if NewInd > -1 then SpriteID := start + NewInd;
end;
tagPlaceObject:
with TSWFPlaceObject(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(CharacterId)));
if NewInd > -1 then CharacterId := start + NewInd;
end;
tagPlaceObject2, tagPlaceObject3:
with TSWFPlaceObject2(SWFObject) do
if PlaceFlagHasCharacter then
begin
NewInd := ListID.IndexOf(Pointer(Longint(CharacterId)));
if NewInd > -1 then CharacterId := start + NewInd;
end;
tagRemoveObject:
with TSWFRemoveObject(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(CharacterId)));
if NewInd > -1 then CharacterId := start + NewInd;
end;
tagDefineFontInfo, tagDefineFontInfo2:
with TSWFDefineFontInfo(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(FontID)));
if NewInd > -1 then FontID := start + NewInd;
end;
tagDefineText, tagDefineText2:
with TSWFDefineText(SWFObject) do
if TextRecords.Count > 0 then
for il2 := 0 to TextRecords.Count - 1 do
if TextRecord[il2].StyleFlagsHasFont then
begin
NewInd := ListID.IndexOf(Pointer(Longint(TextRecord[il2].FontID)));
if NewInd > -1 then TextRecord[il2].FontID := start + NewInd;
end;
tagDefineEditText:
with TSWFDefineEditText(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(FontID)));
if NewInd > -1 then FontID := start + NewInd;
end;
tagDefineFontAlignZones:
with TSWFDefineFontAlignZones(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(FontID)));
if NewInd > -1 then FontID := start + NewInd;
end;
tagCSMTextSettings:
with TSWFCSMTextSettings(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(TextID)));
if NewInd > -1 then TextID := start + NewInd;
end;
tagStartSound:
with TSWFStartSound(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(SoundID)));
if NewInd > -1 then SoundID := start + NewInd;
end;
tagDefineButton, tagDefineButton2:
with TSWFBasedButton(SWFObject) do
if ButtonRecords.Count > 0 then
for il2 := 0 to ButtonRecords.Count - 1 do
begin
NewInd := ListID.IndexOf(Pointer(Longint(ButtonRecord[il2].CharacterID)));
if NewInd > -1 then ButtonRecord[il2].CharacterID := start + NewInd;
end;
tagDefineButtonSound:
with TSWFDefineButtonSound(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(ButtonId)));
if NewInd > -1 then ButtonId := start + NewInd;
if HasIdleToOverUp then
begin
NewInd := ListID.IndexOf(Pointer(Longint(SndIdleToOverUp.SoundId)));
if NewInd > -1 then SndIdleToOverUp.SoundId := start + NewInd;
end;
if HasOverDownToOverUp then
begin
NewInd := ListID.IndexOf(Pointer(Longint(SndOverDownToOverUp.SoundId)));
if NewInd > -1 then SndOverDownToOverUp.SoundId := start + NewInd;
end;
if HasOverUpToIdle then
begin
NewInd := ListID.IndexOf(Pointer(Longint(SndOverUpToIdle.SoundId)));
if NewInd > -1 then SndOverUpToIdle.SoundId := start + NewInd;
end;
if HasOverUpToOverDown then
begin
NewInd := ListID.IndexOf(Pointer(Longint(SndOverUpToOverDown.SoundId)));
if NewInd > -1 then SndOverUpToOverDown.SoundId := start + NewInd;
end;
end;
tagDefineButtonCxform:
with TSWFDefineButtonCxform(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(ButtonId)));
if NewInd > -1 then ButtonId := start + NewInd;
end;
tagVideoFrame:
with TSWFVideoFrame(SWFObject) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(StreamID)));
if NewInd > -1 then StreamID := start + NewInd;
end;
tagDefineSprite:
with TSWFDefineSprite(SWFObject) do
for il2 := 0 to ControlTags.Count - 1 do
case ControlTag[il2].TagID of
tagPlaceObject:
with TSWFPlaceObject(ControlTag[il2]) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(CharacterId)));
if NewInd > -1 then CharacterId := start + NewInd;
end;
tagPlaceObject2, tagPlaceObject3:
with TSWFPlaceObject2(ControlTag[il2]) do
if PlaceFlagHasCharacter then
begin
NewInd := ListID.IndexOf(Pointer(Longint(CharacterId)));
if NewInd > -1 then CharacterId := start + NewInd;
end;
tagStartSound:
with TSWFStartSound(ControlTag[il2]) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(SoundID)));
if NewInd > -1 then SoundID := start + NewInd;
end;
tagRemoveObject:
with TSWFRemoveObject(ControlTag[il2]) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(CharacterId)));
if NewInd > -1 then CharacterId := start + NewInd;
end;
tagVideoFrame:
with TSWFVideoFrame(ControlTag[il2]) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(StreamID)));
if NewInd > -1 then StreamID := start + NewInd;
end;
end;
tagDefineShape, tagDefineShape2, tagDefineShape3, tagDefineShape4:
with TSWFDefineShape(SWFObject) do
begin
if FillStyles.Count > 0 then
for il2 := 0 to FillStyles.Count - 1 do
if TSWFFillStyle(FillStyles[il2]).SWFFillType in
[SWFFillTileBitmap, SWFFillClipBitmap, SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap] then
with TSWFImageFill(FillStyles[il2]) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(ImageID)));
if NewInd > -1 then ImageID := start + NewInd;
end;
if Edges.Count > 0 then
for il3 := 0 to Edges.Count - 1 do
if (EdgeRecord[il3].ShapeRecType = StyleChangeRecord) then
begin
SCR := TSWFStyleChangeRecord(Edges[il3]);
if SCR.StateNewStyles then
for il2 := 0 to SCR.NewFillStyles.Count - 1 do
if TSWFFillStyle(SCR.NewFillStyles[il2]).SWFFillType in
[SWFFillTileBitmap, SWFFillClipBitmap, SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap] then
with TSWFImageFill(SCR.NewFillStyles[il2]) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(ImageID)));
if NewInd > -1 then ImageID := start + NewInd;
end;
end;
end;
tagDefineMorphShape:
with TSWFDefineMorphShape(SWFObject) do
if MorphFillStyles.Count > 0 then
for il2 := 0 to MorphFillStyles.Count - 1 do
if TSWFMorphFillStyle(MorphFillStyles[il2]).SWFFillType in
[SWFFillTileBitmap, SWFFillClipBitmap, SWFFillNonSmoothTileBitmap, SWFFillNonSmoothClipBitmap] then
with TSWFMorphImageFill(MorphFillStyles[il2]) do
begin
NewInd := ListID.IndexOf(Pointer(Longint(ImageID)));
if NewInd > -1 then ImageID := start + NewInd;
end;
end;
Result := start + ListID.Count;
ListID.Free;
end;
end.
|
//
// Generated by JavaToPas v1.5 20140918 - 132021
////////////////////////////////////////////////////////////////////////////////
unit android.os.AsyncTask_Status;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.os;
type
JAsyncTask_Status = interface;
JAsyncTask_StatusClass = interface(JObjectClass)
['{B80B2EBE-99A5-4D7D-BBC5-5644413433BE}']
function _GetFINISHED : JAsyncTask_Status; cdecl; // A: $4019
function _GetPENDING : JAsyncTask_Status; cdecl; // A: $4019
function _GetRUNNING : JAsyncTask_Status; cdecl; // A: $4019
function valueOf(&name : JString) : JAsyncTask_Status; cdecl; // (Ljava/lang/String;)Landroid/os/AsyncTask$Status; A: $9
function values : TJavaArray<JAsyncTask_Status>; cdecl; // ()[Landroid/os/AsyncTask$Status; A: $9
property FINISHED : JAsyncTask_Status read _GetFINISHED; // Landroid/os/AsyncTask$Status; A: $4019
property PENDING : JAsyncTask_Status read _GetPENDING; // Landroid/os/AsyncTask$Status; A: $4019
property RUNNING : JAsyncTask_Status read _GetRUNNING; // Landroid/os/AsyncTask$Status; A: $4019
end;
[JavaSignature('android/os/AsyncTask_Status')]
JAsyncTask_Status = interface(JObject)
['{79D20006-9DEA-4036-85E9-EFF172F6DE40}']
end;
TJAsyncTask_Status = class(TJavaGenericImport<JAsyncTask_StatusClass, JAsyncTask_Status>)
end;
implementation
end.
|
unit UDExportPagText;
interface
uses
SysUtils, Forms, Windows, StdCtrls, Buttons, Controls, Classes,
ExtCtrls, UCrpe32;
type
TCrpePagTextDlg = class(TForm)
panel1: TPanel;
lblLinesPerPage: TLabel;
editLinesPerPage: TEdit;
btnOk: TButton;
btnCancel: TButton;
Panel2: TPanel;
Label1: TLabel;
editCharPerInch: TEdit;
lblCharNote: TLabel;
lblLinesNote: TLabel;
Label2: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure editLinesPerPageKeyPress(Sender: TObject; var Key: Char);
procedure btnOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
end;
var
CrpePagTextDlg: TCrpePagTextDlg;
implementation
{$R *.DFM}
uses UDExportOptions, UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpePagTextDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpePagTextDlg.FormShow(Sender: TObject);
begin
editLinesPerPage.Text := IntToStr(Cr.ExportOptions.Text.LinesPerPage);
editCharPerInch.Text := IntToStr(Cr.ExportOptions.Text.CharPerInch);
end;
{------------------------------------------------------------------------------}
{ editLinesPerPageKeyPress }
{------------------------------------------------------------------------------}
procedure TCrpePagTextDlg.editLinesPerPageKeyPress(Sender: TObject;
var Key: Char);
begin
{Do not allow letters or extended ascii}
if Ord(Key) in [33..47] then Key := Char(0);
if Ord(Key) in [58..255] then Key := Char(0);
end;
{------------------------------------------------------------------------------}
{ btnOKClick }
{------------------------------------------------------------------------------}
procedure TCrpePagTextDlg.btnOKClick(Sender: TObject);
begin
SaveFormPos(Self);
Cr.ExportOptions.Text.LinesPerPage := CrStrToInteger(editLinesPerPage.Text);
Cr.ExportOptions.Text.CharPerInch := CrStrToInteger(editCharPerInch.Text);
end;
{------------------------------------------------------------------------------}
{ btnCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpePagTextDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpePagTextDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Release;
end;
end.
|
unit ufrmDialogSysParm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, StdCtrls,
System.Actions, Vcl.ActnList, ufraFooterDialog3Button;
type
TfrmDialogSysParm = class(TfrmMasterDialog)
Label9: TLabel;
edtId: TEdit;
edtNm: TEdit;
Label1: TLabel;
Label10: TLabel;
edtValue: TEdit;
Label2: TLabel;
edtGroup: TEdit;
edtDesc: TEdit;
Label3: TLabel;
procedure actDeleteExecute(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
Fid : Integer;
// FSysParm : TSysParm;
procedure SetData;
procedure ClearData;
public
{ Public declarations }
procedure ShowWithId(aId: integer = 0);
end;
var
frmDialogSysParm: TfrmDialogSysParm;
implementation
{$R *.dfm}
uses uTSCommonDlg, uRetnoUnit;
procedure TfrmDialogSysParm.actDeleteExecute(Sender: TObject);
begin
inherited;
/// tanya ke user dl mas, apakah yakin akan hapus DB
{
if MessageDlg('Apakah yakin akan menghapus System Parameter ' +
strgGrid.Cells[_KolNm , iy] + ' ?',
mtConfirmation,[mbYes,mbNo],0)=mrYes then
begin
if FSysParm.LoadByID(strgGrid.Ints[_kolId, iy]) then
begin
try
if FSysParm.RemoveFromDB then
begin
cCommitTrans;
CommonDlg.ShowMessage('Sukses Hapus System Parameter');
GetRec;
end
else
begin
cRollbackTrans;
CommonDlg.ShowError('Gagal Hapus System Parameter');
end;
finally
cRollbackTrans;
end;
end
else
begin
CommonDlg.ShowConfirmGlobal ('Data yang dihapus tidak ada!');
end;
end;
}
end;
procedure TfrmDialogSysParm.SetData;
begin
if FId <> 0 then
begin
{ if FSysParm.LoadById(FId) then
begin
edtId.Text := IntToStr(FSysParm.ParId);
edtNm.Text := FSysParm.ParNm;
edtValue.Text := FSysParm.ParValue;
edtGroup.Text := FSysParm.ParGroup;
edtDesc.Text := FSysParm.ParDesc;
end;
}
end
else
begin
ClearData;
end;
end;
procedure TfrmDialogSysParm.ClearData;
begin
edtId.Clear;
edtNm.Clear;
edtValue.Clear;
edtGroup.Clear;
edtDesc.Clear;
end;
procedure TfrmDialogSysParm.ShowWithId(aId: integer = 0);
begin
FId := aId;
// FSysParm := TSysParm.Create(nil);
SetData;
Self.ShowModal;
end;
procedure TfrmDialogSysParm.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
inherited;
{
try
with FSysParm do
begin
UpdateData(edtDesc.Text, edtGroup.Text, Fid,
edtNm.Text, edtValue.Text);
if not SaveToDB then
begin
cRollbackTrans;
CommonDlg.ShowError('Gagal Simpan Data System Parameter.');
end
else
begin
cCommitTrans;
CommonDlg.ShowMessage('Data System Parameter telah disimpan.');
Close;
end;
end;
finally
cRollbackTrans;
end;
}
end;
procedure TfrmDialogSysParm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
inherited;
end;
procedure TfrmDialogSysParm.FormDestroy(Sender: TObject);
begin
// FreeAndNil(FSysParm);
frmDialogSysParm := nil;
inherited;
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 171208
////////////////////////////////////////////////////////////////////////////////
unit java.net.CookiePolicy;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.net.URI,
java.net.HttpCookie;
type
JCookiePolicy = interface;
JCookiePolicyClass = interface(JObjectClass)
['{9C1F3BE5-3CB1-4475-B9E2-3FF63037BE80}']
function _GetACCEPT_ALL : JCookiePolicy; cdecl; // A: $19
function _GetACCEPT_NONE : JCookiePolicy; cdecl; // A: $19
function _GetACCEPT_ORIGINAL_SERVER : JCookiePolicy; cdecl; // A: $19
function shouldAccept(JURIparam0 : JURI; JHttpCookieparam1 : JHttpCookie) : boolean; cdecl;// (Ljava/net/URI;Ljava/net/HttpCookie;)Z A: $401
property ACCEPT_ALL : JCookiePolicy read _GetACCEPT_ALL; // Ljava/net/CookiePolicy; A: $19
property ACCEPT_NONE : JCookiePolicy read _GetACCEPT_NONE; // Ljava/net/CookiePolicy; A: $19
property ACCEPT_ORIGINAL_SERVER : JCookiePolicy read _GetACCEPT_ORIGINAL_SERVER;// Ljava/net/CookiePolicy; A: $19
end;
[JavaSignature('java/net/CookiePolicy')]
JCookiePolicy = interface(JObject)
['{FF7154DD-A47D-4A8F-9E01-DE9D51C97559}']
function shouldAccept(JURIparam0 : JURI; JHttpCookieparam1 : JHttpCookie) : boolean; cdecl;// (Ljava/net/URI;Ljava/net/HttpCookie;)Z A: $401
end;
TJCookiePolicy = class(TJavaGenericImport<JCookiePolicyClass, JCookiePolicy>)
end;
implementation
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls,vdi;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
OpenDialog1: TOpenDialog;
ProgressBar1: TProgressBar;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
function VDI2RAW(source,target:string):boolean;
public
{ Public declarations }
end;
var
Form1: TForm1;
CancelFlag:boolean;
implementation
{$R *.dfm}
function round512(n:cardinal):cardinal;
begin
if n mod 512=0
then result:= (n div 512) * 512
else result:= (1 + (n div 512)) * 512
end;
{
/** Normal dynamically growing base image file. */
VDI_IMAGE_TYPE_NORMAL = 1,
/** Preallocated base image file of a fixed size. */
VDI_IMAGE_TYPE_FIXED,
/** Dynamically growing image file for undo/commit changes support. */
VDI_IMAGE_TYPE_UNDO,
/** Dynamically growing image file for differencing support. */
VDI_IMAGE_TYPE_DIFF,
/** First valid image type value. */
VDI_IMAGE_TYPE_FIRST = VDI_IMAGE_TYPE_NORMAL,
/** Last valid image type value. */
VDI_IMAGE_TYPE_LAST = VDI_IMAGE_TYPE_DIFF
}
procedure TForm1.Button1Click(Sender: TObject);
var
Src,dst:thandle;
buffer:array[0..511] of byte;
byteswritten,readbytes:dword;
//blocks:array[0..4095] of dword;
blocks:array of dword;
i:word;
data,p:pointer;
filename,dd:string;
mapsize:cardinal;
begin
memo1.Clear ;
openDialog1.Filter :='VDI files|*.vdi';
if OpenDialog1.Execute =false then exit;
filename:=OpenDialog1.FileName ;
Src:=CreateFile(pchar(filename), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); //FILE_FLAG_NO_BUFFERING
if src<>dword(-1) then
begin
fillchar(buffer,sizeof(buffer),0);
ReadFile(Src, buffer, sizeof(buffer), readbytes, nil);
memo1.Lines.Add ('szFileInfo:'+strpas(PVDIPREHEADER(@buffer[0])^.szFileInfo));
memo1.Lines.Add ('u32Signature:'+inttohex(PVDIPREHEADER(@buffer[0])^.u32Signature,4));
memo1.Lines.Add ('u32Version:'+inttostr(PVDIPREHEADER(@buffer[0])^.u32Version));
memo1.Lines.Add ('cbHeader:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbHeader));
memo1.Lines.Add ('u32Type:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.u32Type));
memo1.Lines.Add ('fFlags:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.fFlags));
memo1.Lines.Add ('szComment:'+strpas(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.szComment));
memo1.Lines.Add ('offBlocks:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.offBlocks));
memo1.Lines.Add ('offData:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.offData));
memo1.Lines.Add ('cCylinders:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.Geometry.cCylinders ));
memo1.Lines.Add ('cHeads:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.Geometry.cHeads ));
memo1.Lines.Add ('cSectors:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.Geometry.cSectors ));
memo1.Lines.Add ('cbSector:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.Geometry.cbSector ));
memo1.Lines.Add ('cbSector:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.u32Translation ));
memo1.Lines.Add ('cbDisk:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbDisk ));
memo1.Lines.Add ('cbBlock:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbBlock ));
memo1.Lines.Add ('cbBlockExtra:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbBlockExtra ));
memo1.Lines.Add ('cBlocks:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cBlocks ));
memo1.Lines.Add ('cBlocksAllocated:'+inttostr(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cBlocksAllocated ));
//dynamic
if PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.u32Type=1 then
begin
ProgressBar1.Max := PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cBlocksAllocated;
dd:=ChangeFileExt(filename,'.dd');
dst:=CreateFile(pchar(dd), GENERIC_write, FILE_SHARE_write, nil, CREATE_ALWAYS , FILE_ATTRIBUTE_NORMAL, 0);
SetFilePointer(src, PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.offBlocks, nil, FILE_BEGIN);
//fillchar(blocks,sizeof(blocks),0);
//readfile(src,blocks,sizeof(blocks),readbytes,nil);
mapsize:=round512(PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cBlocks);
setlength(blocks,mapsize);
getmem(p,mapsize*sizeof(dword));
readfile(src,p^,mapsize*sizeof(dword),readbytes,nil);
copymemory(@blocks[0],p,mapsize*sizeof(dword));
freemem(p);
getmem(data,PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbBlock);
for i:=0 to PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cBlocksAllocated-1 do
begin
if SetFilePointer(src, PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.offData+(blocks[i]*PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbBlock), nil, FILE_BEGIN)<>INVALID_SET_FILE_POINTER
then readfile(src,data^,PVDIHEADER1(@buffer[sizeof(VDIPREHEADER)])^.cbBlock,readbytes,nil);
if readbytes >0
then writefile(dst,data^,readbytes,byteswritten,nil)
else break;
ProgressBar1.Position :=i;
end;
CloseHandle(dst);
end;
CloseHandle(Src);
end;
end;
function TForm1.VDI2RAW(source,target:string):boolean;
var
handle,dst:thandle;
size,offset:int64;
blocksize,bytesread,byteswritten:cardinal;
buffer:pointer;
begin
CancelFlag :=false;
//
handle:=vdi_open(pchar(source),1);
if handle<>dword(-1) then
begin
size:=vdi_get_media_size;
ProgressBar1.Max := size;
blocksize:=1024*1024;
getmem(buffer,blocksize );
offset:=0;
dst:=CreateFile(pchar(target), GENERIC_write, FILE_SHARE_write, nil, CREATE_ALWAYS , FILE_ATTRIBUTE_NORMAL, 0);
while (CancelFlag =false) and (bytesread>0) do
begin
ProgressBar1.Position :=offset;
bytesread:=vdi_read_buffer_at_offset(handle,buffer,blocksize,offset);
//if bytesread<>0 then
//begin
writefile(dst,buffer^,bytesread,byteswritten,nil);
//memo1.lines.Add(inttostr(offset)+'/'+inttostr(size)+ ' read '+inttostr(bytesread)+' write '+inttostr(byteswritten));
//end;
offset:=offset+blocksize;
end;
vdi_close(handle);
closehandle(dst);
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
filename,dd:string;
begin
memo1.Clear ;
openDialog1.Filter :='VDI files|*.vdi';
if OpenDialog1.Execute =false then exit;
filename:=OpenDialog1.FileName ;
dd:=ChangeFileExt(filename,'.dd');
VDI2RAW(filename,dd);
memo1.Lines.Add('done');
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
CancelFlag :=true;
end;
end.
|
unit fPCLGen;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids, DBGrids, ExtCtrls, DBTables, Buttons, FileUtil;
type
TfrmPCLGeneration = class(TForm)
Memo1: TMemo;
Panel1: TPanel;
btnErrorLog: TButton;
Timer: TTimer;
txtSurvey_id: TEdit;
lblSurvey_id: TLabel;
SpeedButton1: TSpeedButton;
procedure progressreport(s:string; const s_id,sm_id:string);
procedure btnErrorLogClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
CompName : string;
Version : string;
end;
var
frmPCLGeneration: TfrmPCLGeneration;
const
ServiceName = 'PCLGenService';
ServiceDisplayName = 'PCL Gen Service';
SERVICE_WIN32_OWN_PROCESS = $00000010;
SERVICE_DEMAND_START = $00000003;
SERVICE_ERROR_NORMAL = $00000001;
EVENTLOG_ERROR_TYPE = $0001;
implementation
uses dPCLGen, common, DOpenQ, log4Pascal;
{$R *.DFM}
procedure AddToMessageLog(sMsg: string);
var
sString: array[0..1] of string;
hEventSource: THandle;
begin
hEventSource := RegisterEventSource(nil, ServiceName);
if hEventSource > 0 then
begin
sString[0] := ServiceName + ' error: ';
sString[1] := sMsg;
ReportEvent(hEventSource, EVENTLOG_ERROR_TYPE, 0, 0, nil, 2, 0, @sString, nil);
DeregisterEventSource(hEventSource);
end;
end;
procedure TfrmPCLGeneration.progressreport(s:string; const s_id,sm_id:string); far;
var qry : string;
begin
// AddToMessageLog(s);
while memo1.lines.count > 100 do
memo1.lines.delete(0);
if (dmPCLGen = NIL) or (dmPCLGen.currentrun <= 0) then begin
// memo1.lines.add(TimeToStr(Time) + ' ' + s + ' (not logged to PCLGenLog table)');
Logger.Info(s);
end else begin
// memo1.lines.add(TimeToStr(Time) + ' ('+inttostr(dmPCLGen.currentrun)+') ' + s);
Logger.Info(s +' ('+inttostr(dmPCLGen.currentrun)+') ');
end;
memo1.update;
if (dmPCLGen <> NIL) and (dmPCLGen.currentrun > 0) then begin
qry := 'execute sp_PCL_LogEntry ' + inttostr(dmPCLGen.currentrun)+', '+dmOpenq.sqlstring(s,false)+', ';
if strtointdef(s_id,0)=0
then qry := qry + 'null, '
else qry := qry + s_id + ', ';
if strtointdef(sm_id,0)=0
then qry := qry + 'null'
else qry := qry + sm_id;
with dmPCLGen.wwq_Log do begin
sql.clear;
sql.add(qry);
execSQL;
end;
end;
end;
procedure TfrmPCLGeneration.btnErrorLogClick(Sender: TObject);
begin
dmPCLGen.ShowErrorLog;
end;
procedure TfrmPCLGeneration.FormCreate(Sender: TObject);
var dummy, suffix : string;
begin
suffix := '';
if uppercase(ExtractFileName(Application.ExeName)) <> 'PCLGEN.EXE' then
suffix := '-' + Copy(Application.ExeName, length(Application.ExeName)-4, 1);
CompName := ComputerName + suffix;
dummy := GetFileVersion(application.exename, Version);
if paramstr(4)='/C' then timer.interval := 1000;
timer.enabled := true;
memo1.Lines.Add('Log file in C:\NRC\Logs\'+ExtractFileName(Application.ExeName)+'\');
end;
procedure TfrmPCLGeneration.TimerTimer(Sender: TObject);
var zExeName : array[0..79] of char;
begin
timer.enabled := false;
DMPCLGen := TDMPCLGen.Create( Self );
if dmPCLGen.createOK and fileexists(dmopenq.tempdir+'\LocalSelTextBox.db') then
dmPCLGen.PCLGeneration
else
progressreport('forms weren''t created properly ... trying again','','');
if (not dmPCLGen.timer.enabled) then begin
MessageBeep(0); MessageBeep(0); MessageBeep(0);
btnErrorLog.Enabled := true;
{if dmopenq.createok and dmPCLGen.createok then} begin
frmPCLGeneration.progressreport('Relaunching PCLGen (from fPCLGen)','','');
winExec(strpcopy(zExeName,application.exename+' /2 '+paramstr(2)+' '+paramstr(3)),sw_shownormal)
end;
sleep(2000);
frmPCLGeneration.close;
end;
end;
procedure TfrmPCLGeneration.FormDestroy(Sender: TObject);
begin
dmPCLGen.free;
end;
end.
|
unit ibSHSQLEditorEditors;
interface
uses
SysUtils, Classes, DesignIntf, TypInfo, Dialogs,
SHDesignIntf, ibSHDesignIntf, ibSHCommonEditors, ibSHMessages;
type
TibSHSQLEditorPropEditor = class(TibBTPropertyEditor)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(AValues: TStrings); override;
procedure SetValue(const Value: string); override;
procedure Edit; override;
end;
IibSHAfterExecutePropEditor = interface
['{23EC5612-5932-4C6D-9BDB-A409CDA50EDE}']
end;
TibBTAfterExecutePropEditor = class(TibSHSQLEditorPropEditor, IibSHAfterExecutePropEditor)
end;
IibSHResultTypePropEditor = interface
['{6E492333-06B9-4580-90A1-89348C7F51FB}']
end;
TibBTResultTypePropEditor = class(TibSHSQLEditorPropEditor, IibSHResultTypePropEditor)
end;
IibSHIsolationLevelPropEditor = interface
['{2143B246-BB04-475F-A3FB-8739A5F5CDC0}']
end;
TibBTIsolationLevelPropEditor = class(TibSHSQLEditorPropEditor, IibSHIsolationLevelPropEditor)
end;
implementation
uses
ibSHConsts, ibSHValues;
{ TibSHSQLEditorPropEditor }
function TibSHSQLEditorPropEditor.GetAttributes: TPropertyAttributes;
begin
// if Supports(Self, IibSHSQLPropEditor) or
// Supports(Self, IibSHDDLPropEditor) then Result := [paReadOnly, paDialog];
if Supports(Self, IibSHAfterExecutePropEditor) or
Supports(Self, IibSHResultTypePropEditor) or
Supports(Self, IibSHIsolationLevelPropEditor) then Result := [paValueList];
end;
function TibSHSQLEditorPropEditor.GetValue: string;
begin
Result := inherited GetValue;
// if Supports(Self, IibSHSQLPropEditor) or
// Supports(Self, IibSHDDLPropEditor) then Result := ResultTypes[1];
end;
procedure TibSHSQLEditorPropEditor.GetValues(AValues: TStrings);
begin
if Supports(Self, IibSHAfterExecutePropEditor) then AValues.Text := GetAfterExecute;
if Supports(Self, IibSHResultTypePropEditor) then AValues.Text := GetResultType;
if Supports(Self, IibSHIsolationLevelPropEditor) then AValues.Text := GetIsolationLevel;
end;
procedure TibSHSQLEditorPropEditor.SetValue(const Value: string);
begin
if Supports(Self, IibSHAfterExecutePropEditor) then
if Designer.CheckPropValue(Value, GetAfterExecute) then inherited SetStrValue(Value);
if Supports(Self, IibSHResultTypePropEditor) then
if Designer.CheckPropValue(Value, GetResultType) then inherited SetStrValue(Value);
if Supports(Self, IibSHIsolationLevelPropEditor) then
if Designer.CheckPropValue(Value, GetIsolationLevel) then inherited SetStrValue(Value);
end;
procedure TibSHSQLEditorPropEditor.Edit;
begin
inherited Edit;
// if Supports(Self, IibSHSQLPropEditor) then
// Designer.ChangeNotification(Component, SCallSQL, opInsert)
// else
// if Supports(Self, IibSHDDLPropEditor) then
// Designer.ChangeNotification(Component, SCallDDL, opInsert);
end;
end.
|
unit UnitClipboard;
interface
Uses
windows,
shellapi;
function GetClipboardFiles(var Resultado: string): Boolean;
function GetClipboardText(Wnd: HWND; var Resultado: string): Boolean;
procedure SetClipboardText(const S: String);
implementation
function GetClipboardFiles(var Resultado: string): Boolean;
var
f: THandle;
buffer: Array [0..MAX_PATH] of Char;
i, numFiles: Integer;
begin
Result := FALSE;
Resultado := '';
OpenClipboard(0);
try
f := GetClipboardData(CF_HDROP);
If f <> 0 then
begin
numFiles := DragQueryFile(f, $FFFFFFFF, nil, 0);
Resultado := '';
for i:= 0 to numfiles - 1 do
begin
buffer[0] := #0;
DragQueryFile(f, i, buffer, sizeof(buffer));
Resultado := Resultado + string(buffer) + '|';
end;
Result := TRUE;
end;
finally
CloseClipboard;
end;
end;
function GetClipboardText(Wnd: HWND; var Resultado: string): Boolean;
var
hData: HGlobal;
begin
Result := True;
Resultado := '';
if OpenClipboard(Wnd) then
begin
try
hData := GetClipboardData(CF_TEXT);
if hData <> 0 then
begin
try
SetString(Resultado, PChar(GlobalLock(hData)), GlobalSize(hData));
finally
GlobalUnlock(hData);
end;
end
else
Result := False;
Resultado := PChar(@Resultado[1]);
finally
CloseClipboard;
end;
end
else
Result := False;
end;
function AllocMem(Size: Cardinal): Pointer;
begin
GetMem(Result, Size);
FillChar(Result^, Size, 0);
end;
procedure SetClipboardText(Const S: string);
var
Data: THandle;
DataPtr: Pointer;
Size: integer;
begin
Size := length(S);
OpenClipboard(0);
try
Data := GlobalAlloc(GMEM_MOVEABLE+GMEM_DDESHARE, Size);
try
DataPtr := GlobalLock(Data);
try
Move(S[1], DataPtr^, Size);
SetClipboardData(CF_TEXT, Data);
finally
GlobalUnlock(Data);
end;
except
GlobalFree(Data);
raise;
end;
finally
CloseClipboard;
end;
end;
end.
|
unit kiwi.s3;
interface
uses
System.Classes,
System.Zip,
System.SysUtils,
System.Generics.Collections,
Data.Cloud.AmazonApi,
Data.Cloud.CloudApi,
kiwi.s3.interfaces,
kiwi.s3.bucket,
kiwi.s3.client,
kiwi.s3.types;
type
tkiwiS3 = class(tinterfacedobject, ikiwiS3)
private
{ private declarations }
fstraccountName: string;
fstraccountKey: string;
fstrRegion: string;
fbooAccelerate: boolean;
fbucket: ikiwiS3Bucket;
function getaccountKey: string;
function getaccountName: string;
function getregion: string;
function getaccelerate: boolean;
public
{ public delcarations }
constructor create(pstraccountName: string = ''; pstraccountKey: string = ''; pstrRegion: string = ''; pbooAccelerate: boolean = false);
destructor destroy; override;
property accountName: string read getaccountName;
property accountKey: string read getaccountKey;
property region: string read getregion;
property accelerate: boolean read getaccelerate;
class function new(pstraccountName: string = ''; pstraccountKey: string = ''; pstrRegion: string = ''; pbooAccelerate: boolean = false): ikiwiS3;
function bucket(pstrBucket: string): ikiwiS3Bucket;
end;
implementation
{ tkiwi }
function tkiwiS3.bucket(pstrBucket: string): ikiwiS3Bucket;
begin
result := fbucket.name(pstrBucket);
end;
constructor tkiwiS3.create(pstraccountName: string = ''; pstraccountKey: string = ''; pstrRegion: string = ''; pbooAccelerate: boolean = false);
begin
fstraccountName := pstraccountName;
fstraccountKey := pstraccountKey;
fstrRegion := pstrRegion;
fbucket := tkiwiS3Bucket.create(self, fstraccountName, fstraccountKey);
end;
destructor tkiwiS3.destroy;
begin
if kiwiS3Client <> nil then
FreeAndNil(kiwiS3Client);
inherited;
end;
function tkiwiS3.getaccelerate: boolean;
begin
result := fbooAccelerate;
end;
function tkiwiS3.getaccountKey: string;
begin
result := fstraccountKey;
end;
function tkiwiS3.getaccountName: string;
begin
result := fstraccountName;
end;
function tkiwiS3.getregion: string;
begin
result := fstrRegion;
end;
class function tkiwiS3.new(pstraccountName: string = ''; pstraccountKey: string = ''; pstrRegion: string = ''; pbooAccelerate: boolean = false): ikiwiS3;
begin
result := self.create(pstraccountName, pstraccountKey, pstrRegion, pbooAccelerate);
end;
end.
|
unit Invoice.View.LogIn;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.pngimage;
type
TFormLogin = class(TForm)
btnCancel: TButton;
btnLogin: TButton;
EditPassword: TEdit;
EditUser: TEdit;
LabelUser: TLabel;
LabelPassword: TLabel;
imageBackground: TImage;
LabelSoftware: TLabel;
LabelDeveloper: TLabel;
LabelVersion: TLabel;
procedure btnLoginClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FLogin: Boolean;
//
procedure SetTitle;
procedure SetLabel;
public
{ Public declarations }
end;
var
FormLogin: TFormLogin;
implementation
{$R *.dfm}
uses Invoice.Controller.DataModule, Invoice.Controller.Facade;
procedure TFormLogin.SetLabel;
begin
LabelSoftware.Caption := Application.Title;
LabelDeveloper.Caption := TControllerGeneralFacade.New.AppInfoFactory.Default.CompanyName;
LabelVersion.Caption := 'Version ' + TControllerGeneralFacade.New.AppInfoFactory.Default.FileVersion;
end;
procedure TFormLogin.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFormLogin.btnLoginClick(Sender: TObject);
var
idUser: Integer;
begin
if (EditUser.Text <> '') and (EditPassword.Text <> '') then
begin
idUser := TControllerGeneralFacade.New.SecurityFactory.Default.LogIn(EditUser.Text, EditPassword.Text);
//
FLogin := (idUser > 0);
//
if FLogin then
begin
DataModuleLocal.SetidUser(idUser);
DataModuleLocal.SetUsername(EditUser.Text);
//
Close;
end
else
begin
EditPassword.Text := '';
//
MessageDlg('Invalid user or password.', mtError, [mbOK], 0);
end;
end
else
MessageDlg('Enter the username and password.', mtError, [mbOK], 0);
end;
procedure TFormLogin.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
//
if not FLogin then
Application.Terminate;
end;
procedure TFormLogin.FormCreate(Sender: TObject);
begin
FLogin := False;
//
SetTitle;
//
SetLabel;
end;
procedure TFormLogin.FormShow(Sender: TObject);
begin
EditUser.Text := TControllerGeneralFacade.New.WinInfoFactory.Default.UserName;
//
EditPassword.Text := '';
end;
procedure TFormLogin.SetTitle;
begin
Caption := Application.Title + ' - ' + Hint;
end;
end.
|
(*
Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED
Original name: 0041.PAS
Description: Convert REAL to INTEGER
Author: MARTIN RICHARDSON
Date: 09-26-93 09:25
*)
{*****************************************************************************
* Function ...... RTOI()
* Purpose ....... To convert a real to an integer
* Parameters .... RealNum Real type number
* Returns ....... The integer part of RealNum
* Notes ......... Simply truncates the decimals
* . Uses function Left
* Author ........ Martin Richardson
* Date .......... May 13, 1992
*****************************************************************************}
FUNCTION RTOI( RealNum: REAL ): LONGINT;
VAR
s: STRING;
l: LONGINT;
i: INTEGER;
BEGIN
STR( RealNum:17:2, s );
{s := Left( s, LENGTH(s) - 3 );}
s := copy( s, 1, LENGTH(s) - 3 );
VAL( s, l, i );
RTOI := l;
END;
begin
WriteLn( RTOI(3.24) );
end.
|
unit uPrecosCusto;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, adLabelComboBox, DB, ADODB,funcoes,FuncSQL, Grids,
DBGrids, SoftDBGrid, adLabelEdit, adLabelNumericEdit, TFlatButtonUnit,
TFlatCheckBoxUnit, fCtrls, adLabelSpinEdit;
type
TfmPrecoCustos = class(TForm)
edCodigo: TadLabelEdit;
query: TADOQuery;
Grid: TSoftDBGrid;
DataSource1: TDataSource;
edPcNovo: TadLabelNumericEdit;
btAjustaPreco: TFlatButton;
btConsultaProduto: TFlatButton;
cbCustoFiscal: TFlatCheckBox;
cbCustoMedio: TFlatCheckBox;
cbCustoMedioUnico: TFlatCheckBox;
cbajustaTodos: TFlatCheckBox;
cbLoja: TadLabelComboBox;
memoItens: TMemo;
Button1: TButton;
mmResult: TMemo;
Label1: TLabel;
Label2: TLabel;
edNome: TadLabelEdit;
cbLancaEstoque: TCheckBox;
GroupBox1: TGroupBox;
FlatButton1: TFlatButton;
edAjustaCusto: TadLabelSpinEdit;
FlatButton2: TFlatButton;
procedure edCodigoKeyDown(Sender: TObject; var Key: Word;Shift: TShiftState);
procedure btAjustaPrecoClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
function AjustaPreco(valor, percentual: string): string;
procedure btConsultaProdutoClick(Sender: TObject);
procedure cbCustoMedioUnicoClick(Sender: TObject);
procedure ajustaPrecoCusto(Sender:Tobject);
procedure Button1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure AcertaQuantidades(Sender:Tobject);
procedure Label1DblClick(Sender: TObject);
procedure LimparMemo(var memo:Tmemo);
procedure Label1Click(Sender: TObject);
procedure Label2Click(Sender: TObject);
procedure custosPorNota(is_nota:String);
procedure efetuaAjustDeNota(TipoAjuste:String);
procedure recalcularCmuNota(isNota:String);
procedure btRecalculaCMUItensNotaClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FlatButton1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmPrecoCustos: TfmPrecoCustos;
implementation
uses uMain, uCF;
{$R *.dfm}
var
UO_CD, CD_PES_EMP:String;
function TfmPrecoCustos.AjustaPreco(valor, percentual: string): string;
var
aux1,aux2,aux3:real;
begin
while pos('.',valor) > 0 do
delete(valor,pos('.',valor),01);
aux1 := Strtofloat(valor);
aux2 := Strtofloat(percentual);
aux3:= (aux1 * aux2);
valor := FloatTostr( aux3 );
AjustaPreco := FloatToStrF( aux3 ,ffFixed,18,02);
end;
procedure TfmPrecoCustos.btConsultaProdutoClick(Sender: TObject);
var
cod:string;
ds:TdataSet;
begin
SCREEN.Cursor := crHourGlass;
cod := funcSql.GetValorWell('O','Select is_ref from crefe where cd_ref = ' + QuotedStr(edCodigo.text), 'is_ref', fmMain.Conexao );
if cod <> '' then
begin
edNome.text := '';
edNome.text := funcSql.GetValorWell('O','Select CD_REF +'' ''+ds_ref AS DS_REF from crefe where cd_ref = ' + QuotedStr(edCodigo.text), 'ds_ref', fmMain.Conexao );
query.SQL.Clear;
query.sql.add( ' select is_uo, ds_uo as Loja, ' +
' dbo.Z_CF_funObterPrecoProduto_CF(001, ' +cod+', is_uo, ' +CD_PES_EMP+ ') VlCusto, ' +
' dbo.Z_CF_funObterPrecoProduto_CF(005, ' +cod+', is_uo, ' +CD_PES_EMP+ ') VlCMU, ' +
' dbo.Z_CF_funObterPrecoProduto_CF(103, ' +cod+', is_uo, ' +CD_PES_EMP+ ') VlAtacado, ' +
' dbo.Z_CF_funObterPrecoProduto_CF(103, ' +cod+', is_uo, ' +CD_PES_EMP+ ') * .70 as [70% de VlAtacado], ' +
' dbo.Z_CF_EstoqueNaLoja ( ' +cod+' , is_uo, 1 ) as Estoque ' +
' from tbuo with(Nolock) where tbuo.tp_estoque in (1,2) ');
if cbLoja.itemIndex > 0 then
query.sql.add( ' and is_uo in( ' +UO_CD+ ', ' + funcoes.getCodUO(cbLoja) +')' )
else
query.sql.add( ' and is_uo not in (10036710, 10042256, 10034573 ) ');
query.sql.add( ' order by tp_estoque, is_uo ');
Query.Open;
grid.Columns[0].visible := false;
grid.Columns[0+1].Width := 150;
grid.Columns[1+1].Width := 100;
grid.Columns[2+1].Width := 70;
grid.Columns[3+1].Width := 70;
end;
edPcNovo.SetFocus;
SCREEN.Cursor := crdefault;
end;
procedure TfmPrecoCustos.edCodigoKeyDown(Sender: TObject; var Key: Word;Shift: TShiftState);
begin
if key = VK_Return then
begin
btConsultaProdutoClick(SENDER);
end;
end;
procedure TfmPrecoCustos.ajustaPrecoCusto(Sender: Tobject);
var
cod, Erro:String;
cmd:String;
begin
cod := funcSql.GetValorWell('O','Select is_ref from crefe where cd_ref = ' + QuotedStr(edCodigo.text), 'is_ref', fmMain.Conexao );
begin
if cbCustoFiscal.Checked = true then
begin
funcSql.GetValorWell('E', ' Update dlest set ' +
' custoUnitario = ' + funcoes.StrToPrecoSQL(edPcNovo.Text) +
' where is_lanc in ( ' +
'select top 1 is_lanc from dlest with(Nolock) where '+
' is_ref = '+cod+
' and is_estoque = '+ query.fieldByname('is_uo').AsString +' and is_tpcte = 6 '+
'order by is_lanc desc '+
' ) '
,'@@error',fmMain.Conexao);
end;
if cbCustoMedio.Checked = true then
begin
funcSql.GetValorWell('E', ' Update dlest set '+
' CustoMedioUnitario = ' + funcoes.StrToPrecoSQL(edPcNovo.Text) +
' where is_lanc in ( ' +
'select top 1 is_lanc from dlest with(Nolock) where '+
' is_ref = '+cod+
' and is_estoque = '+ query.fieldByname('is_uo').AsString +' and is_tpcte = 6 '+
'order by is_lanc desc '+
' ) '
,'@@error',fmMain.Conexao);
end;
if cbCustoMedioUnico.Checked = true then
begin
funcSql.GetValorWell('E', ' Update dlest set '+
' CustoMedioUnitarioUnico = '+funcoes.StrToPrecoSQL(edPcNovo.Text) +
' where is_lanc in ( ' +
'select top 1 is_lanc from dlest with(Nolock) where '+
' is_ref = '+cod+
' and is_estoque = '+ query.fieldByname('is_uo').AsString +' and is_tpcte = 6 '+
'order by is_lanc desc '+
' ) '
,'@@error',fmMain.Conexao);
end;
{
if funcSql.GetValorWell('E', ' Update dlest set
' custoUnitario = ' + funcoes.StrToPrecoSQL(edPcNovo.Text) +
' ,CustoMedioUnitario = ' + funcoes.StrToPrecoSQL(edPcNovo.Text) +
' ,CustoMedioUnitarioUnico = '+funcoes.StrToPrecoSQL(edPcNovo.Text) +
' where is_lanc in ( ' +
'select top 1 is_lanc from dlest with(Nolock) where '+
' is_ref = '+cod+
' and is_estoque = '+ query.fieldByname('is_uo').AsString +' and is_tpcte = 6 '+
'order by is_lanc desc '+
' ) '
,'@@error',connection) = '0' then
}
end;
edNome.text := '';
edCodigo.SetFocus;
end;
procedure TfmPrecoCustos.FormActivate(Sender: TObject);
begin
edCodigo.SetFocus;
end;
procedure TfmPrecoCustos.cbCustoMedioUnicoClick(Sender: TObject);
begin
if (query.IsEmpty = false) then
if (cbCustoFiscal.Checked = false) and( cbCustoMedio.Checked = false ) and( cbCustoMedioUnico.Checked= false )then
begin
MsgTela('','Marque ao menos uma opção',mb_IconError+mb_ok);
cbCustoFiscal.Checked :=true;
end;
end;
procedure TfmPrecoCustos.btAjustaPrecoClick(Sender: TObject);
var
i:smallint;
erro:string;
begin
screen.Cursor := crHourGlass;
erro := '';
if edPcNovo.Text = '0,00' then
erro:= erro + 'Falta o valor'+ #13;
if erro <> '' then
begin
erro := ' Erros encontrados : ' + #13+ erro;
msgTela('', erro,mb_iconError + mb_ok);
end
else
begin
if cbajustaTodos.Checked then
begin
query.First;
while query.Eof = false do
begin
ajustaPrecoCusto(Sender);
query.Next;
end;
end
else
ajustaPrecoCusto(Sender);
end;
screen.Cursor := crDefault;
end;
procedure TfmPrecoCustos.FormClose(Sender: TObject; var Action: TCloseAction);
begin
mmResult.Lines.Clear();
memoItens.lines.clear();
edCodigo.Text := '';
edPcNovo.Text := '';
fmMain.fecharForm(fmPrecoCustos, Action);
action := CaFree;
fmPrecoCustos := nil;
end;
procedure TfmPrecoCustos.AcertaQuantidades(Sender: Tobject);
var
i:integer;
nmTable,cod:string;
quant,est:integer;
tbItens:TADOTable;
qrItens :TADOQuery;
begin
nmTable := '#'+funcoes.SohNumeros( dateTimeToStr(now) );
cod := 'Create table '+ nmTable+ ' ( quant integer, is_ref integer, preco money ) ';
funcsql.execSQL(cod,fmMain.Conexao);
tbItens := TADOTable.Create(nil);
tbitens.Connection := fmMain.Conexao;
tbItens.TableName := nmTable;
qrItens := TADOQuery.create(nil);
qrItens.Connection := fmMain.Conexao;
qrItens.SQL.Add('Select * from ' + nmTable);
qrItens.open;
for i:= 0 to memoItens.Lines.Count -1 do
if funcoes.SohNumeros(memoItens.lines[i]) <> '' then
begin
cod := funcSQl.openSQL('Select is_ref from crefe (nolock) where cd_ref = ' + quotedStr(fmMain.getCdRef(memoItens.lines[i])) {quotedStr(trim(copy(memoItens.lines[i],01,08))) } , 'is_ref', fmMain.Conexao);
if cod <> '' then
begin
if funcoes.SohNumeros( copy(memoItens.lines[i],09,20)) = '' then
quant := strToInt('0'+funcoes.SohNumeros(copy(memoItens.lines[i],09,20)))
else
quant := strToInt(funcoes.SohNumeros( copy(memoItens.lines[i],09,20)));
est := strToInt( funcSQl.openSQL(' select dbo.Z_CF_EstoqueNaLoja ( '+cod+','+ copy(cbLoja.Items[cbLoja.ItemIndex],51,08) + ' , 1 ) as Estoque ' , 'estoque', fmMain.Conexao) );
if quant > est then
begin
mmResult.Lines.Add('Acertar : ' + fmMain.getCdRef(memoItens.lines[i]) + ' quant:' + intToStr(quant-est) + ' Est: '+ inttostr(est));
qrItens.Append;
qrItens.fieldByName('quant').asString := inttostr( quant - est );
qrItens.fieldByName('is_ref').asString := cod;
qrItens.fieldByName('preco').asString := '0';
qrItens.Post;
end
else
mmResult.lines.Add('Já tem estoque: ' + memoItens.lines[i] +' estoque: '+ inttostr(est));
end
else
mmResult.lines.Add('Codigo invalido: ' + memoItens.lines[i] );
end;
qrItens.First;
funcSQl.AcertaQuantidadeItens( copy(cbLoja.Items[cbLoja.ItemIndex],51,08) , '10000592', qritens,fmMain.Conexao);
end;
procedure TfmPrecoCustos.Label1DblClick(Sender: TObject);
begin
memoItens.Lines.Clear;
end;
procedure TfmPrecoCustos.LimparMemo(var memo: Tmemo);
begin
memo.Lines.Clear
end;
procedure TfmPrecoCustos.Label1Click(Sender: TObject);
begin
LimparMemo( memoitens );
end;
procedure TfmPrecoCustos.Label2Click(Sender: TObject);
begin
LimparMemo( mmResult );
end;
procedure TfmPrecoCustos.Button1Click(Sender: TObject);
var
i:integer;
begin
if cbLancaEstoque.Checked = true then
AcertaQuantidades(Sender);
mmResult.Lines.Add('----------------------------------');
for i:=0 to memoItens.Lines.Count -1 do
begin
if funcoes.SohNumeros(trim(copy(memoItens.lines[i],01,08))) <> '' then
begin
edCodigo.Text := fmMain.getCdRef(memoItens.lines[i]); // funcoes.SohNumeros(copy(memoItens.lines[i],01,07));
btConsultaProdutoClick(Sender);
if edNome.text <> '' then
begin
query.first;
if query.fieldByName('VlCusto').AsFloat > 0 then
begin
edPcNovo.Text := query.fieldByName('VlCusto').asString;
btAjustaPrecoClick(Sender);
end
else if query.fieldByName('VlCMU').AsFloat > 0 then
begin
edPcNovo.Text := query.fieldByName('VlCMU').asString;
btAjustaPrecoClick(Sender);
end
else if query.fieldByName('VlAtacado').AsFloat > 0 then
edPcNovo.Text := query.fieldByName('VlAtacado').asString
else
mmResult.Lines.add(edCodigo.text + ' Sem preco: ' + copy(memoItens.lines[i],01,20));
if edPcNovo.Value > 0 then
begin
query.Next;
if query.fieldByName('estoque').asFloat > 0 then
begin
btAjustaPrecoClick(Sender);
mmResult.Lines.add(edCodigo.text + ' Lancado Preco')
end
else
mmResult.Lines.add(edCodigo.text + ' Sem estoque: ' + copy(memoItens.lines[i],08,20));
end;
end;
end;
end;
end;
procedure TfmPrecoCustos.custosPorNota(is_nota:String);
var
ds:TDataSEt;
cmd: String;
begin
cmd := '/* pegando os custo fiscal dos itens de uma nota */ ' +#13+
' select p.cd_ref, dbo.z_cf_funObterPrecoProduto_CF(1, p.is_ref, i.is_estoque, 0) as custo ' +
' from dmovi i (nolock) inner join crefe p (nolock) on i.is_ref = p.is_ref where i.is_nota = ' + is_nota;
ds := funcSQL.getDataSetQ( cmd, fmMain.Conexao);
ds.First();
while ds.Eof = false do
begin
edCodigo.Text := ds.fieldByName('cd_ref').AsString;
btConsultaProdutoClick(nil);
cmd := funcoes.floatToDinheiro(ds.FieldByName('custo').AsFloat);
if (edAjustaCusto.Value <> 0) then
edPcNovo.Value := ds.FieldByName('custo').AsFloat + ds.FieldByName('custo').AsFloat * (edAjustaCusto.Value / 100)
else
edPcNovo.Value := ds.FieldByName('custo').AsFloat;
mmResult.Lines.Add(ds.fieldByName('cd_ref').AsString +' valor antigo: ' + cmd + ' Valor novo: ' + funcoes.floatToDinheiro(edPcNovo.Value) );
btAjustaPrecoClick(nil);
ds.Next();
end;
ds.free();
end;
procedure TfmPrecoCustos.recalcularCmuNota(isNota: String);
var
ds:TdataSet;
begin
ds := uCF.getItensDeUmaNota(isNota);
cbCustoMedioUnico.Checked := true;
cbCustoFiscal.Checked := false;
cbCustoMedio.Checked := false;
while (ds.Eof = false) do
begin
edCodigo.Text := ds.fieldByName('cd_ref').asString;
btConsultaProdutoClick(nil);
edPcNovo.Text := uCF.recalcularCmuItem(ds.fieldByName('is_ref').asString);
mmResult.Lines.Add('cod: ' + ds.fieldByName('cd_ref').AsString +' valor: ' + edPcNovo.Text );
edCodigo.SetFocus();
btAjustaPrecoClick(nil);
ds.Next();
end;
mmResult.Lines.Add('OK!');
end;
procedure TfmPrecoCustos.efetuaAjustDeNota(TipoAjuste: String);
var
cmd:String;
begin
cmd := '';
cmd := fmMain.getIsNota();
if cmd <> '' then
begin
if (TipoAjuste = '1') then
custosPorNota(cmd)
else
recalcularCmuNota(cmd);
end;
end;
procedure TfmPrecoCustos.btRecalculaCMUItensNotaClick(Sender: TObject);
begin
// recalcular o CMU dos itens de uma nota.
efetuaAjustDeNota('2');
end;
procedure TfmPrecoCustos.FormCreate(Sender: TObject);
begin
fmMain.getParametrosForm(fmPrecoCustos);
uCF.getListaLojas(cbLoja, true , false, '');
UO_CD := fmMain.getParamBD('uoCd','');
CD_PES_EMP := fmMain.getParamBD('comum.codEmpresa','');
end;
procedure TfmPrecoCustos.FlatButton1Click(Sender: TObject);
begin
efetuaAjustDeNota('1');
end;
end.
|
unit uBonusBucks;
interface
uses ADOdb, DateUtils, uGynboSyncClasses;
const
BONUS_BUCKS_PREFIX = 'BB';
type
TDiscountPercList = array of Double;
TBonusBucksControl = class
private
FADOConnection: TADOConnection;
FIDModel: Integer;
FIDStore: Integer;
FDiscountValue: Currency;
FSellingPrice: Currency;
function GetModelDiscountPerc: Double;
function GetCalendarDiscountPerc: TDiscountPercList;
function GetBestDiscountPerc: Double;
procedure SetDiscountValue;
public
function GetDiscountValue: Currency;
property ADOConnection: TADOConnection read FADOConnection write FADOConnection;
property IDStore: Integer read FIDStore write FIDStore;
property IDModel: Integer read FIDModel write FIDModel;
property SellingPrice: Currency read FSellingPrice write FSellingPrice;
end;
TBonusBucks = class
private
FADOConnection: TADOConnection;
FIDPreSaleCreated: Integer;
FIDPreSaleUsed: Integer;
FDiscountValue: Currency;
FCreatedDate: TDateTime;
FBonusBucksControl: TBonusBucksControl;
FValidFromDate: TDateTime;
FExpirationDate: TDateTime;
FBonusCode: String;
FErrorMsg: String;
FBonusSync : TbgBonusSync;
function GetBonusBuckRedeemedPerc: Double;
function GetDiscountValue: Currency;
procedure CalcBonusBucks;
function IsExpiredCupon: Boolean;
function IsValidCupon: Boolean;
public
constructor Create(AADOConnection: TADOConnection; ABonusSync : TbgBonusSync);
destructor Destroy; override;
procedure LoadBySaleUsed(AIDPreSaleUsed: Integer);
procedure LoadByCupom(ACupom: String);
procedure SetUsed(AIDPreSaleUsed : Integer; ABonusCode: String);
procedure UndoSetUsed(AIDPreSaleUsed: Integer);
function ValidateCoupon: Boolean;
function HasPayment: Boolean;
property ADOConnection: TADOConnection read FADOConnection write FADOConnection;
property IDPreSaleCreated: Integer read FIDPreSaleCreated write FIDPreSaleCreated;
property IDPreSaleUsed: Integer read FIDPreSaleUsed write FIDPreSaleUsed;
property DiscountValue: Currency read GetDiscountValue write FDiscountValue;
property ValidCupon: Boolean read IsValidCupon;
property ExpiredCupon: Boolean read IsExpiredCupon;
property ErrorMsg: String read FErrorMsg write FErrorMsg;
property BonusCode: String read FBonusCode write FBonusCode;
property BonusSync : TbgBonusSync read FBonusSync write FBonusSync;
end;
implementation
uses DB, SysUtils, uMsgConstant, uNumericFunctions;
{ TBonusBucksControl }
function TBonusBucksControl.GetBestDiscountPerc: Double;
var
i: Integer;
aCalendarDiscountPerc: TDiscountPercList;
begin
Result := GetModelDiscountPerc;
aCalendarDiscountPerc := GetCalendarDiscountPerc;
for i := 0 to Pred(Length(aCalendarDiscountPerc)) do
if Result < aCalendarDiscountPerc[i] then
Result := aCalendarDiscountPerc[i];
end;
function TBonusBucksControl.GetCalendarDiscountPerc: TDiscountPercList;
begin
with TADODataSet.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'SELECT RC.DiscountPerc ' +
'FROM Sal_RebateItemCalendar RIC ' +
'JOIN Sal_RebateCalendar RC ON (RIC.IDRebateCalendar = RC.IDRebateCalendar) ' +
'JOIN Sal_RebateItem RI ON (RIC.IDRebateItem = RI.IDRebateItem) ' +
'WHERE ' +
' RI.IDModel = :IDModel ' +
' AND RI.IDStore = :IDStore ' +
' AND IsNull(RC.IDStore, :IDStore2) = :IDStore3 ' +
' AND RC.DaysOfWeek LIKE ' + QuotedStr('%') + ' + :DayOfWeek + ' + QuotedStr('%') +
' AND RC.StartDate <= :StartDate AND RC.EndDate >= :EndDate';
Parameters.ParamByName('IDModel').Value := FIDModel;
Parameters.ParamByName('IDStore').Value := FIDStore;
Parameters.ParamByName('IDStore2').Value := FIDStore;
Parameters.ParamByName('IDStore3').Value := FIDStore;
Parameters.ParamByName('DayOfWeek').Value := IntToStr(DayOfTheWeek(Now));
Parameters.ParamByName('StartDate').Value := Now;
Parameters.ParamByName('EndDate').Value := Now;
Open;
SetLength(Result, RecordCount);
while not Eof do
begin
Result[Pred(RecNo)] := FieldByName('DiscountPerc').AsCurrency;
Next;
end;
finally
Free;
end;
end;
function TBonusBucksControl.GetDiscountValue: Currency;
begin
SetDiscountValue;
Result := MyRound(FDiscountValue, 2);
end;
function TBonusBucksControl.GetModelDiscountPerc: Double;
begin
with TADODataSet.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'SELECT DiscountPerc ' +
'FROM Sal_RebateItem ' +
'WHERE IDModel = :IDModel AND IDStore = :IDStore';
Parameters.ParamByName('IDModel').Value := FIDModel;
Parameters.ParamByName('IDStore').Value := FIDStore;
Open;
Result := FieldByName('DiscountPerc').AsCurrency;
finally
Free;
end;
end;
procedure TBonusBucksControl.SetDiscountValue;
begin
FDiscountValue := FSellingPrice * (GetBestDiscountPerc / 100);
end;
{ TBonusBucks }
procedure TBonusBucks.CalcBonusBucks;
begin
with TADODataSet.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'SELECT IM.ModelID, IM.StoreID, ((IM.SalePrice * IM.Qty) - IM.Discount) as SalePrice ' +
'FROM PreInventoryMov IM JOIN Invoice I ON (IM.DocumentID = I.IDPreSale) ' +
'WHERE I.IDPreSale = :IDPreSale AND IM.Promo = 0';
Parameters.ParamByName('IDPreSale').Value := FIDPreSaleCreated;
Open;
First;
while not Eof do
begin
FBonusBucksControl.IDModel := FieldByName('ModelID').AsInteger;
FBonusBucksControl.IDStore := FieldByName('StoreID').AsInteger;
FBonusBucksControl.SellingPrice := FieldByName('SalePrice').AsCurrency;
FDiscountValue := FDiscountValue + FBonusBucksControl.GetDiscountValue;
Next;
end;
finally
Free;
end;
end;
constructor TBonusBucks.Create(AADOConnection: TADOConnection; ABonusSync : TbgBonusSync);
begin
FADOConnection := AADOConnection;
FBonusSync := ABonusSync;
FDiscountValue := 0;
FBonusBucksControl := TBonusBucksControl.Create;
FBonusBucksControl.ADOConnection := FADOConnection;
end;
destructor TBonusBucks.Destroy;
begin
FreeAndNil(FBonusBucksControl);
inherited;
end;
function TBonusBucks.GetBonusBuckRedeemedPerc: Double;
begin
with TADODataSet.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'SELECT PropertyValue FROM Sis_PropertyDomain WHERE Property = :Property';
Parameters.ParamByName('Property').Value := 'BonusBuckRedeemedPerc';
Open;
Result := StrToFloat(FieldByName('PropertyValue').AsString);
finally
Free;
end;
end;
function TBonusBucks.GetDiscountValue: Currency;
begin
if FDiscountValue = 0 then
begin
CalcBonusBucks;
FDiscountValue := MyRound(FDiscountValue - (FDiscountValue * (GetBonusBuckRedeemedPerc / 100)), 2);
end;
Result := FDiscountValue;
end;
function TBonusBucks.HasPayment: Boolean;
begin
with TADODataSet.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'SELECT IDLancamento ' +
'FROM Fin_Lancamento L ' +
' JOIN Fin_LancQuit LQ ON (L.IDLancamento = LQ.IDLancamento) ' +
' JOIN Fin_Quitacao Q ON (LQ.IDQuitacao = Q.IDQuitacao) ' +
' JOIN MeioPag MP ON (Q.IDQuitacaoMeio = MP.IDMeioPag) ' +
'WHERE L.IDPreSale = :IDPreSale AND MP.Tipo = 8';
Parameters.ParamByName('IDPreSale').Value := FIDPreSaleUsed;
Open;
Result := not IsEmpty;
finally
Free;
end;
end;
function TBonusBucks.IsExpiredCupon: Boolean;
begin
Result := Int(IncDay(FExpirationDate)) <= Int(Now);
end;
function TBonusBucks.IsValidCupon: Boolean;
begin
Result := FValidFromDate <= Now;
end;
procedure TBonusBucks.LoadByCupom(ACupom: String);
begin
with TADODataSet.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'SELECT RD.IDPreSaleCreated, RD.DiscountValue, RD.ValidFromDate, RD.ExpirationDate, RD.IDPreSaleUsed, RD.BonusCode, I.InvoiceDate ' +
'FROM Sal_RebateDiscount RD JOIN Invoice I ON (RD.IDPreSaleCreated = I.IDPreSale)' +
'WHERE (IDPreSaleCreated = :IDPreSaleCreated OR RD.BonusCode = :BonusCode)';
if (Length(ACupom) <> 34) then
begin
Parameters.ParamByName('IDPreSaleCreated').Value := StrToInt(StringReplace(Acupom, BONUS_BUCKS_PREFIX, '', [rfReplaceAll]));
Parameters.ParamByName('BonusCode').Value := '';
end
else
begin
Parameters.ParamByName('IDPreSaleCreated').Value := 0;
Parameters.ParamByName('BonusCode').Value := ACupom;
end;
Open;
if IsEmpty then
FIDPreSaleCreated := -1
else
begin
FIDPreSaleCreated := FieldByName('IDPreSaleCreated').AsInteger;
FIDPreSaleUsed := FieldByName('IDPreSaleUsed').AsInteger;
FDiscountValue := FieldByName('DiscountValue').AsFloat;
FValidFromDate := FieldByName('ValidFromDate').AsDateTime;
FExpirationDate := FieldByName('ExpirationDate').AsDateTime;
FCreatedDate := FieldByName('InvoiceDate').AsDateTime;
FBonusCode := FieldByName('BonusCode').AsString;
end;
finally
Free;
end;
end;
procedure TBonusBucks.LoadBySaleUsed(AIDPreSaleUsed: Integer);
begin
with TADODataSet.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'SELECT RD.IDPreSaleCreated, RD.DiscountValue, RD.ValidFromDate, RD.ExpirationDate, RD.IDPreSaleUsed, RD.BonusCode, I.InvoiceDate ' +
'FROM Sal_RebateDiscount RD JOIN Invoice I ON (RD.IDPreSaleCreated = I.IDPreSale)' +
'WHERE IDPreSaleUsed = :IDPreSaleUsed';
Parameters.ParamByName('IDPreSaleUsed').Value := AIDPreSaleUsed;
Open;
if IsEmpty then
FIDPreSaleCreated := -1
else
begin
FIDPreSaleCreated := FieldByName('IDPreSaleCreated').AsInteger;
FIDPreSaleUsed := FieldByName('IDPreSaleUsed').AsInteger;
FDiscountValue := FieldByName('DiscountValue').AsFloat;
FValidFromDate := FieldByName('ValidFromDate').AsDateTime;
FExpirationDate := FieldByName('ExpirationDate').AsDateTime;
FCreatedDate := FieldByName('InvoiceDate').AsDateTime;
FBonusCode := FieldByName('BonusCode').AsString;
end;
finally
Free;
end;
end;
procedure TBonusBucks.SetUsed(AIDPreSaleUsed : Integer; ABonusCode: String);
begin
with TADOCommand.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'UPDATE Sal_RebateDiscount SET IDPreSaleUsed = :IDPreSaleUsed WHERE BonusCode = :BonusCode';
Parameters.ParamByName('IDPreSaleUsed').Value := AIDPreSaleUsed;
Parameters.ParamByName('BonusCode').Value := ABonusCode;
Execute;
finally
Free;
end;
end;
procedure TBonusBucks.UndoSetUsed(AIDPreSaleUsed: Integer);
var
bError : Boolean;
begin
with TADODataSet.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'SELECT BonusCode FROM Sal_RebateDiscount WHERE IDPreSaleUsed = :IDPreSaleUsed ';
Parameters.ParamByName('IDPreSaleUsed').Value := FIDPreSaleUsed;
Open;
First;
while not EOF do
begin
FBonusSync.BonusCode := FieldByName('BonusCode').AsString;
if (FBonusSync.BonusCode <> '') then
begin
try
bError := True;
if FBonusSync.UnUse then
bError := (FBonusSync.IDResult <> 0);
except
end;
if bError then
begin
FErrorMsg := FBonusSync.ResultMessage;
raise Exception.Create(FBonusSync.ResultMessage);
end;
end;
Next;
end;
finally
Free;
end;
with TADOCommand.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'UPDATE Sal_RebateDiscount SET IDPreSaleUsed = NULL WHERE IDPreSaleUsed = :IDPreSaleUsed';
Parameters.ParamByName('IDPreSaleUsed').Value := AIDPreSaleUsed;
Execute;
finally
Free;
end;
end;
function TBonusBucks.ValidateCoupon: Boolean;
begin
Result := False;
if FIDPreSaleCreated = -1 then
begin
FErrorMsg := MSG_CRT_BONUS_NOT_FOUND;
Exit;
end
else if FIDPreSaleUsed = 0 then
begin
if not ValidCupon then
begin
FErrorMsg := MSG_CRT_BONUS_IS_NOT_VALID;
Exit;
end
else if ExpiredCupon then
begin
FErrorMsg := MSG_CRT_BONUS_EXPIRED;
Exit;
end;
end
else
begin
FErrorMsg := MSG_CRT_BONUS_ALREADY_UTILIZED;
Exit;
end;
Result := True;
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, TAGraph, TASeries, TAFuncSeries, Forms, Controls,
Graphics, Dialogs, ExtCtrls, StdCtrls, Grids, ParseMath, Funcs;
type
{ TForm1 }
TForm1 = class(TForm)
BEjecutar: TButton;
Chart1: TChart;
EdiPoints: TEdit;
HorizontalLine: TConstantLine;
Label1: TLabel;
Memo1: TMemo;
PanelClient: TPanel;
PanelXnum: TPanel;
PanelXs: TPanel;
Grid1: TStringGrid;
VerticalLine: TConstantLine;
procedure BEjecutarClick(Sender: TObject);
procedure EdiPointsChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
Parse : TParseMath;
Funcs : array of TFuncs;
public
pos : Integer;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.EdiPointsChange(Sender: TObject);
begin
if ( EdiPoints.Text = '' ) then
exit;
Grid1.ColCount := StrToInt(EdiPoints.Text) + 1;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Parse := TParseMath.create;
Parse.AddVariable('x',0);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Parse.Destroy;
end;
procedure TForm1.BEjecutarClick(Sender: TObject);
var x, i, n, j : Integer;
l : array of String;
begin
if Length(Funcs) < 0 then
begin
for i := 0 to Length(Funcs) do
Funcs[i].Destroy;
end;
pos := -1;
SetLength(Funcs,0);
n := StrToInt(EdiPoints.Text);
SetLength(l,n);
x := 0;
while x <= n - 1 do
begin
Parse.Expression := '';
for i := x to x + 6 do
begin
if i >= n then
break;
l[i] := '';
for j := x to x + 6 do
begin
if ( j = i ) or ( j >=n ) then
Continue;
if ( ((j = x + 6) or (j = n - 1) ) or ( (( j = x + 5) and ( i = x + 6 )) or (( j = n-2) and ( i = n-1 )) ) ) then
begin
l[i] := l[i] + '((x-' + Grid1.Cells[j+1,1] + ')/(' + Grid1.Cells[i+1,1] + '-' + Grid1.Cells[j+1,1] + '))';
continue;
end;
l[i] := l[i] + '((x-' + Grid1.Cells[j+1,1] + ')/(' + Grid1.Cells[i+1,1] + '-' + Grid1.Cells[j+1,1] + '))*';
end;
if ( i = x + 6 ) or ( i = n - 1 ) then
begin
Parse.Expression := Parse.Expression + Grid1.Cells[i+1,2] + '*' + l[i];
end
else
Parse.Expression := Parse.Expression + Grid1.Cells[i+1,2] + '*' + l[i] + '+';;
end;
Memo1.Lines.Add(Parse.Expression);
pos := pos + 1;
SetLength(Funcs,pos + 1);
Funcs[pos] := TFuncs.Create;
Funcs[pos].CreateGraph(n,x,Parse.Expression);
{Funcs[pos].Serie := TFuncSeries.Create(Chart1);
Chart1.AddSeries(Funcs[pos].Serie);
Funcs[pos].Serie.OnCalculate := @CalculateFunc;
Funcs[pos].Serie.Active := False;
Funcs[pos].Serie.Active := True; }
x := x + 4;
if x = n then
exit;
x := x-1;
if x >= n +1 then
begin
//ShowMessage('entro');
x := n - 4;
end;
end;
end;
end.
|
unit glcube;
//openGL cube
{$Include opts.inc}
{$mode objfpc}{$H+}
interface
uses
{$IFDEF COREGL}glcorearb, {$ELSE}gl, glext, {$ENDIF}
gl_core_matrix,
shaderu, Classes, SysUtils, Graphics, OpenGLContext, math, dialogs;
type
TGLCube = class
private
{$IFDEF COREGL}
uniform_mtx: GLint;
vbo_face2d, vao_point2d, shaderProgram: GLuint;
{$ELSE}displayLst: GLuint;{$ENDIF}
fAzimuth, fElevation,SizeFrac : Single;
scrnW, scrnH: integer;
isRedraw, isTopLeft: boolean;
procedure SetIsTopLeft(f: boolean);
procedure SetSize(f: single);
procedure SetAzimuth(f: single);
procedure SetElevation(f: single);
procedure ScreenSize(Width,Height: integer);
{$IFDEF COREGL}procedure CreateStrips;{$ENDIF}
procedure CreateCube(sz: single);
public
pitch: Single;
property TopLeft : boolean read isTopLeft write SetIsTopLeft;
property Azimuth : single read fAzimuth write SetAzimuth;
property Elevation : single read fElevation write fElevation;
property Size : single read SizeFrac write SetSize;
procedure Draw(Width,Height: integer); //must be called while TOpenGLControl is current context
constructor Create(Ctx: TOpenGLControl);
Destructor Destroy; override;
end;
{$IFNDEF COREGL}var GLErrorStr : string = '';{$ENDIF}
implementation
{$IFDEF COREGL}
type
TRGBA = packed record //Next: analyze Format Header structure
R,G,B,A : byte;
end;
TPoint3f = Packed Record
x,y,z: single;
end;
TVtxClr = Packed Record
vtx : TPoint3f; //vertex coordinates
clr : TRGBA;
end;
var
g2Dvnc: array of TVtxClr;
g2Drgba : TRGBA;
g2DNew: boolean;
gnface: integer;
const
kBlockSz = 8192;
kVert2D ='#version 330'
+#10'layout(location = 0) in vec3 Vert;'
+#10'layout(location = 3) in vec4 Clr;'
+#10'out vec4 vClr;'
+#10'uniform mat4 ModelViewProjectionMatrix;'
+#10'void main() {'
+#10' gl_Position = ModelViewProjectionMatrix * vec4(Vert, 1.0);'
+#10' vClr = Clr;'
+#10'}';
kFrag2D = '#version 330'
+#10'in vec4 vClr;'
+#10'out vec4 color;'
+#10'void main() {'
+#10' color = vClr;'
+#10'}';
procedure TGLCube.CreateStrips;
const
kATTRIB_VERT = 0; //vertex XYZ are positions 0,1,2
kATTRIB_CLR = 3; //color RGBA are positions 3,4,5,6
type
TInts = array of integer;
var
i: integer;
faces: TInts;
vbo_point : GLuint;
//mvp : TnMat44;
//mvpMat: GLint;
begin
//if not isRedraw then exit;
//nface := Length(g2Dvnc); //each face has 3 vertices
if gnface < 1 then exit;
if vao_point2d <> 0 then
glDeleteVertexArrays(1,@vao_point2d);
glGenVertexArrays(1, @vao_point2d);
if (vbo_face2d <> 0) then
glDeleteBuffers(1, @vbo_face2d);
glGenBuffers(1, @vbo_face2d);
vbo_point := 0;
glGenBuffers(1, @vbo_point);
glBindBuffer(GL_ARRAY_BUFFER, vbo_point);
glBufferData(GL_ARRAY_BUFFER, Length(g2Dvnc)*SizeOf(TVtxClr), @g2Dvnc[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Prepare vertrex array object (VAO)
glBindVertexArray(vao_point2d);
glBindBuffer(GL_ARRAY_BUFFER, vbo_point);
//Vertices
glVertexAttribPointer(kATTRIB_VERT, 3, GL_FLOAT, GL_FALSE, sizeof(TVtxClr), PChar(0));
glEnableVertexAttribArray(kATTRIB_VERT);
//Color
glVertexAttribPointer(kATTRIB_CLR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(TVtxClr), PChar( sizeof(TPoint3f)));
glEnableVertexAttribArray(kATTRIB_CLR);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
glDeleteBuffers(1, @vbo_point);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_face2d);
setlength(faces,gnface);
for i := 0 to (gnface-1) do
faces[i] := i;
glBufferData(GL_ELEMENT_ARRAY_BUFFER, gnface*sizeof(uint32), @faces[0], GL_STATIC_DRAW);
//glBufferData(GL_ELEMENT_ARRAY_BUFFER, Length(faces)*sizeof(TPoint3i), @faces[0], GL_STATIC_DRAW);
setlength(faces, 0 );
setlength(g2Dvnc,0);
end;
procedure nglBegin(mode: integer);
begin
g2DNew := true;
end;
procedure nglColor4ub (r,g,b,a: byte);
begin
g2Drgba.r := round(r );
g2Drgba.g := round(g );
g2Drgba.b := round(b );
g2Drgba.a := round(a );
end;
procedure nglVertex3f(x,y,z: single);
var
i: integer;
begin
i := gnface; //array indexed from 0 not 1
gnface := gnface + 1;
if (gnface+1) > length(g2Dvnc) then
setlength(g2Dvnc, length(g2Dvnc)+kBlockSz);
g2Dvnc[i].vtx.X := x;
g2Dvnc[i].vtx.Y := y;
g2Dvnc[i].vtx.Z := z;
g2Dvnc[i].clr := g2Drgba;
if not g2DNew then exit;
g2DNew := false;
g2Dvnc[gnface] := g2Dvnc[i];
gnface := gnface + 1;
end;
procedure nglEnd;
var
i: integer;
begin
//add tail
if gnface < 1 then exit;
i := gnface; //array indexed from 0 not 1
gnface := gnface + 1;
if gnface > length(g2Dvnc) then
setlength(g2Dvnc, length(g2Dvnc)+kBlockSz);
g2Dvnc[i] := g2Dvnc[i-1];
end;
(*procedure DrawTextCore (lScrnWid, lScrnHt: integer);
begin
nglMatrixMode(nGL_MODELVIEW);
nglLoadIdentity;
nglMatrixMode (nGL_PROJECTION);
nglLoadIdentity ();
nglOrtho (0, lScrnWid,0, lScrnHt,-10,10);
end; *)
{$ELSE} //for legacy OpenGL
procedure nglColor4ub (r,g,b,a: byte);
begin
glColor4ub (r,g,b,a);
end;
procedure nglVertex3f(x,y,z: single);
begin
glVertex3f(x,y,z);
end;
procedure nglVertex2f(x,y: single);
begin
glVertex2f(x,y);
end;
procedure nglBegin(mode: integer);
begin
glBegin(mode);
end;
procedure nglVertex2fr(x,y: single);
begin
nglVertex3f(round(x),round(y), -1);
end;
procedure nglEnd;
begin
glEnd();
end;
{$ENDIF}
procedure TGLCube.SetAzimuth(f: single);
begin
if (f <> fAzimuth) then isRedraw := true;
fAzimuth := f;
end;
procedure TGLCube.SetElevation(f: single);
begin
if (f <> fElevation) then isRedraw := true;
fElevation := f;
end;
procedure TGLCube.SetIsTopLeft(f: boolean);
begin
if (f <> isTopLeft) then isRedraw := true;
isTopLeft := f;
end;
procedure TGLCube.SetSize(f: single);
begin
if (f <> sizeFrac) then isRedraw := true;
sizeFrac := f;
if sizeFrac < 0.005 then sizeFrac := 0.005;
if sizeFrac > 0.25 then sizeFrac := 0.25;
end;
procedure TGLCube.ScreenSize(Width,Height: integer);
begin
if (Width = scrnW) and (Height = scrnH) then exit;
scrnW := Width;
scrnH := Height;
isRedraw := true;
end;
constructor TGLCube.Create(Ctx: TOpenGLControl);
begin
scrnH := 0;
SizeFrac := 0.03;
isRedraw := true;
fAzimuth := 30;
Pitch := 0;
fElevation := -15;
isTopLeft := false;
{$IFDEF COREGL}
vao_point2d := 0;
vbo_face2d := 0;
Ctx.MakeCurrent();
shaderProgram := initVertFrag(kVert2D, '', kFrag2D);
uniform_mtx := glGetUniformLocation(shaderProgram, pAnsiChar('ModelViewProjectionMatrix'));
//glFinish;
Ctx.ReleaseContext;
{$ELSE}
displayLst := 0;
{$ENDIF}
end;
{$DEFINE CUBETEXT}
{$IFDEF CUBETEXT}
Type
TVec4 = record
x,y,z,w: single;
end;
{$IFNDEF COREGL}
TnMat44 = array [0..3, 0..3] of single;
{$ENDIF}
{$ENDIF}
procedure MakeCube(sz: single);
{$IFDEF CUBETEXT}
const
kTiny = -0.01;
var
rot: TnMat44;
isBegun: boolean = false;
function setMat (a,b,c,d, e,f,g,h, i,j,k,l: single): TnMat44;
begin
result[0,0] := a;
result[0,1] := b;
result[0,2] := c;
result[0,3] := d;
result[1,0] := e;
result[1,1] := f;
result[1,2] := g;
result[1,3] := h;
result[2,0] := i;
result[2,1] := j;
result[2,2] := k;
result[2,3] := l;
result[3,0] := 0;
result[3,1] := 0;
result[3,2] := 0;
result[3,3] := 1;
end;
(*function mult(a:TnMat44; b: TVec4):TVec4;
begin
result.x:=(a[0,0]*b.x)+(a[1,0]*b.y)+(a[2,0]*b.z)+a[3,0];
result.y:=(a[0,1]*b.x)+(a[1,1]*b.y)+(a[2,1]*b.z)+a[3,1];
result.z:=(a[0,2]*b.x)+(a[1,2]*b.y)+(a[2,2]*b.z)+a[3,2];
end; *)
function mult(a:TnMat44; b: TVec4):TVec4;
begin
result.x:=(a[0,0]*b.x)+(a[0,1]*b.y)+(a[0,2]*b.z)+a[0,3];
result.y:=(a[1,0]*b.x)+(a[1,1]*b.y)+(a[1,2]*b.z)+a[1,3];
result.z:=(a[2,0]*b.x)+(a[2,1]*b.y)+(a[2,2]*b.z)+a[2,3];
end;
procedure vertex3f(x,y,z: single; rep: boolean = false);
begin
{$IFNDEF COREGL}
if (rep) and (not isBegun) then begin
nglBegin(GL_TRIANGLE_STRIP);
isBegun := true;
rep := false;
end;
{$ENDIF}
nglVertex3f(x,y,z);
{$IFDEF COREGL}
if (rep) then
nglVertex3f(x,y,z);
{$ELSE}
if (rep) then begin
nglEnd;
isBegun := false;
end;
{$ENDIF}
end;
procedure vertex2f(x,y: single; rep: boolean = false);
var
v: TVec4;
begin
v.x := 1-x;
v.y := 1-y;
v.z := 0;
v.w := 1;
v := mult(rot,v);
vertex3f(v.x, v.y, v.z, rep);
end;
procedure drawL();
begin
//setlength(vtxClrs, length(vtxClrs)+ 12);
vertex2f(0.275, 0.1, true);
vertex2f(0.275, 0.9);
vertex2f(0.375, 0.1);
vertex2f(0.375, 0.9, true);
vertex2f(0.375,0.1, true);
vertex2f(0.375,0.2);
vertex2f(0.725,0.1);
vertex2f(0.725,0.2, true);
end;
procedure drawR();
begin
//setlength(vtxClrs, length(vtxClrs)+ 30);
vertex2f(0.275, 0.1, true);
vertex2f(0.275, 0.9);
vertex2f(0.375, 0.1);
vertex2f(0.375, 0.9, true);
vertex2f(0.375, 0.8, true);
vertex2f(0.375, 0.9);
vertex2f(0.725, 0.8);
vertex2f(0.625, 0.9, true);
vertex2f(0.625, 0.55, true);
vertex2f(0.625, 0.8);
vertex2f(0.725, 0.55);
vertex2f(0.725, 0.8, true);
vertex2f(0.375, 0.45, true);
vertex2f(0.375, 0.55);
vertex2f(0.625, 0.45);
vertex2f(0.725, 0.55, true);
vertex2f(0.625, 0.1, true);
vertex2f(0.525, 0.45);
vertex2f(0.725, 0.1);
vertex2f(0.625, 0.45, true);
end;
procedure drawP();
begin
//setlength(vtxClrs, length(vtxClrs)+ 24);
vertex2f(0.275, 0.1, true);
vertex2f(0.275, 0.9);
vertex2f(0.375, 0.1);
vertex2f(0.375, 0.9, true);
vertex2f(0.375, 0.8, true);
vertex2f(0.375, 0.9);
vertex2f(0.725, 0.8);
vertex2f(0.625, 0.9, true);
vertex2f(0.625, 0.55, true);
vertex2f(0.625, 0.8);
vertex2f(0.725, 0.55);
vertex2f(0.725, 0.8, true);
vertex2f(0.375, 0.45, true);
vertex2f(0.375, 0.55);
vertex2f(0.625, 0.45);
vertex2f(0.725, 0.55, true);
end;
procedure drawS();
begin
//setlength(vtxClrs, length(vtxClrs)+ 42);
vertex2f(0.275, 0.2, true);
vertex2f(0.275, 0.3);
vertex2f(0.375, 0.1);
vertex2f(0.375, 0.3, true);
vertex2f(0.375, 0.1, true);
vertex2f(0.375, 0.2);
vertex2f(0.625, 0.1);
vertex2f(0.725, 0.2, true);
vertex2f(0.625, 0.1, true);
vertex2f(0.625, 0.55);
vertex2f(0.725, 0.2);
vertex2f(0.725, 0.45, true);
vertex2f(0.375, 0.45, true);
vertex2f(0.275, 0.55);
vertex2f(0.625, 0.45);
vertex2f(0.625, 0.55, true);
vertex2f(0.275, 0.55, true);
vertex2f(0.275, 0.8);
vertex2f(0.375, 0.55);
vertex2f(0.375, 0.9, true);
vertex2f(0.375, 0.8, true);
vertex2f(0.375, 0.9);
vertex2f(0.725, 0.8);
vertex2f(0.625, 0.9, true);
vertex2f(0.625, 0.7, true);
vertex2f(0.625, 0.8);
vertex2f(0.725, 0.7);
vertex2f(0.725, 0.8, true);
end;
procedure drawA();
begin
//setlength(vtxClrs, length(vtxClrs)+ 18);
vertex2f(0.275,0.1, true);
vertex2f(0.475,0.9);
vertex2f(0.375,0.1);
vertex2f(0.575,0.9, true);
vertex2f(0.625,0.1, true);
vertex2f(0.475,0.9);
vertex2f(0.725,0.1);
vertex2f(0.575,0.9, true);
vertex2f(0.4375,0.35, true);
vertex2f(0.4625,0.45);
vertex2f(0.6625,0.35);
vertex2f(0.6375,0.45, true);
end;
procedure drawI();
begin
//setlength(vtxClrs, length(vtxClrs)+ 6);
vertex2f(0.45,0.1, true);
vertex2f(0.45,0.9);
vertex2f(0.55,0.1);
vertex2f(0.55,0.9, true);
end;
{$ENDIF}
//draw a cube of size sz
var
sz2 : single;
begin
sz2 := sz;
nglColor4ub(204,204,204,255);
nglBegin(GL_TRIANGLE_STRIP); //* Top side
nglVertex3f(-sz, -sz, -sz2);
nglVertex3f(-sz, sz, -sz2);
nglVertex3f(sz, -sz, -sz2);
nglVertex3f(sz, sz, -sz2);
nglEnd;
nglColor4ub(56,56,56,255);
nglBegin(GL_TRIANGLE_STRIP); //* Bottom side
nglVertex3f(-sz, -sz, sz2);
nglVertex3f(sz, -sz, sz2);
nglVertex3f(-sz, sz, sz2);
nglVertex3f(sz, sz, sz2);
nglEnd;
nglColor4ub(0,0,153,255);
nglBegin(GL_TRIANGLE_STRIP); //* Front side
nglVertex3f(-sz, sz, -sz2);
nglVertex3f(-sz, sz, sz2);
nglVertex3f(sz, sz, -sz2);
nglVertex3f(sz, sz, sz2);
nglEnd;
nglColor4ub(77,0,77,255);
nglBegin(GL_TRIANGLE_STRIP);//* Back side
nglVertex3f(-sz, -sz, -sz2);
nglVertex3f(sz, -sz, -sz2);
nglVertex3f(-sz, -sz, sz2);
nglVertex3f(sz, -sz, sz2);
nglEnd;
nglColor4ub(153,0,0,255);
nglBegin(GL_TRIANGLE_STRIP); //* Left side
nglVertex3f(-sz, -sz, -sz2);
nglVertex3f(-sz, -sz, sz2);
nglVertex3f(-sz, sz, -sz2);
nglVertex3f(-sz, sz, sz2);
nglEnd;
nglColor4ub(0,128,0,255);
nglBegin(GL_TRIANGLE_STRIP); //* Right side
nglVertex3f(sz, -sz, -sz2);
nglVertex3f(sz, sz, -sz2);
nglVertex3f(sz, -sz, sz2);
nglVertex3f(sz, sz, sz2);
nglEnd();
{$IFDEF CUBETEXT}
nglColor4ub(0,0,0,255);
rot := setMat(sz*2,0,0,-sz, 0,0,0,sz+kTiny, 0,sz*2,0,-sz);
drawA();
rot := setMat(-sz*2,0,0,sz, 0,0,0,-sz-kTiny, 0,sz*2,0,-sz);
drawP();
rot := setMat(sz*2,0,0,-sz, 0,-sz*2,0,sz, 0,0,0,sz+kTiny);
drawI();
rot := setMat(sz*2,0,0,-sz, 0,sz*2,0,-sz, 0,0,0,-sz-kTiny);
drawS();
rot := setMat(0,0,0,-sz-kTiny, sz*2,0,0,-sz, 0,sz*2,0,-sz);
drawL();
rot := setMat(0,0,0,sz+kTiny, -sz*2,0,0,sz, 0,sz*2,0,-sz);
drawR();
{$ENDIF}
end; //MakeCube()
procedure TGLCube.CreateCube(sz: single);
begin
{$IFDEF COREGL}
gnface := 0;
setlength(g2Dvnc, 0);
{$ELSE}
if displayLst <> 0 then
glDeleteLists(displayLst, 1);
displayLst := glGenLists(1);
glNewList(displayLst, GL_COMPILE);
{$ENDIF}
MakeCube(sz);
{$IFDEF COREGL}
CreateStrips;
{$ELSE}
glEndList();
{$ENDIF}
isRedraw := false;
end;
procedure TGLCube.Draw(Width,Height: integer);
var
sz: single;
{$IFDEF COREGL}
mvp : TnMat44;
{$ENDIF}
begin
ScreenSize(Width,Height);
sz := ScrnW;
if sz > ScrnH then sz := ScrnH;
if sz < 10 then exit;
sz := sz * SizeFrac;
nglMatrixMode(nGL_MODELVIEW);
nglLoadIdentity;
nglMatrixMode (nGL_PROJECTION);
nglLoadIdentity ();
nglOrtho (0, ScrnW,0, ScrnH,-10*sz,10*sz);
nglTranslatef(0,0,sz*8);
if isTopLeft then
nglTranslatef(ScrnW - (1.8*sz), ScrnH-(1.8*sz),0)
else
nglTranslatef(1.8*sz,1.8*sz,0);
nglRotatef(fElevation-90,-1,0,0);
nglRotatef(-fAzimuth,0,0,1);
nglRotatef(Pitch,-1,0,0);
{$IFNDEF COREGL}
glUseProgram(0);
glEnable (GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable (GL_LIGHTING);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho (0, ScrnW,0, ScrnH,-10*sz,10*sz);
glTranslatef(0,0,sz*8);
if isTopLeft then
glTranslatef(ScrnW - (1.8*sz), ScrnH-(1.8*sz),0)
else
glTranslatef(1.8*sz,1.8*sz,0);
glRotatef(fElevation-90,-1,0,0);
glRotatef(-fAzimuth,0,0,1);
glRotatef(Pitch,-1,0,0);
glFrontFace(GL_CW);
(*glMatrixMode(GL_PROJECTION);
glLoadIdentity;
glOrtho(0, ScrnW, 0, ScrnH,-sz*10,sz*10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0,0,sz*8);
if isTopLeft then
glTranslatef(ScrnW - (1.8*sz), ScrnH-(1.8*sz),0)
else
glTranslatef(1.8*sz,1.8*sz,0);
glRotatef(fElevation-90,-1,0,0);
glRotatef(-fAzimuth,0,0,1);*)
{$ENDIF}
//glEnable( GL_MULTISAMPLE );
if isRedraw then
CreateCube(sz);
glEnable(GL_CULL_FACE);
{$IFDEF COREGL}
glUseProgram(shaderProgram);
mvp := ngl_ModelViewProjectionMatrix;
glUniformMatrix4fv(uniform_mtx, 1, GL_FALSE, @mvp[0,0]); // note model not MVP!
glBindVertexArray(vao_point2d);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_face2d);
glDrawElements(GL_TRIANGLE_STRIP, gnface, GL_UNSIGNED_INT, nil);
glBindVertexArray(0);
glUseProgram(0);
{$ELSE}
glCallList(displayLst);
{$ENDIF}
glDisable(GL_CULL_FACE);
end;
destructor TGLCube.Destroy;
begin
//call the parent destructor:
inherited;
end;
end.
|
unit ILPP_SaveLoad;
{$INCLUDE '.\ILPP_defs.inc'}
interface
uses
ILPP_SimpleBitmap;
{===============================================================================
Unit management functions
===============================================================================}
procedure Initialize;
procedure Finalize;
{===============================================================================
Picture loading functions
===============================================================================}
Function LoadFile_GDIPlus(const FileName: String; Bitmap: TSimpleBitmap): Boolean;
Function LoadFile_DevIL(const FileName: String; Bitmap: TSimpleBitmap): Boolean;
{===============================================================================
Picture saving functions
===============================================================================}
type
TPictureFormat = (pfBMP,pfJPG,pfPNG,pfTGA);
Function SaveFile_DevIL(const FileName: String; Bitmap: TSimpleBitmap; Format: TPictureFormat; Quality: Integer = 80 {only for JPG, 0..100}): Boolean;
implementation
uses
Windows, SysUtils,
AuxTypes, StrRect,
il{DevIL},
ILPP_Base,ILPP_Utils,ILPP_System;
{$R '..\resources\devil_dll.res'}
{===============================================================================
Unit management functions
===============================================================================}
var
GDIPToken: ULONG_PTR;
procedure Initialize;
var
input: TGdiplusStartupInput;
output: TGdiplusStartupOutput;
begin
ExtractResourceToFile('devil_dll',ExpandFileName('.\DevIL.dll'));
DevIL_Initialize;
input.GdiplusVersion := 1;
input.DebugEventCallback := nil;
input.SuppressBackgroundThread := False;
input.SuppressExternalCodecs := True;
If GdiplusStartup(@GDIPToken,@input,@output) <> 0 then
raise Exception.Create('Unable to initialize GDI+.');
end;
//------------------------------------------------------------------------------
procedure Finalize;
begin
GdiplusShutdown(GDIPToken);
DevIL_Finalize;
end;
{===============================================================================
Picture loading functions
===============================================================================}
Function LoadFile_GDIPlus(const FileName: String; Bitmap: TSimpleBitmap): Boolean;
var
GDIPBitmap: Pointer;
SWidth,SHeight: Single;
Line: PRGBALine;
X,Y: Integer;
{
Color is returned as 32bit quantity with layout A8-R8-G8-B8, and since we are
on little-endian system, it is actually in memory ordered in reverse (BGRA).
}
Color: TBGRAQuadruplet;
begin
try
GDIPlusError(GdipCreateBitmapFromFile(PWideChar(StrToWide(FileName)),@GDIPBitmap));
try
GDIPlusError(GdipGetImageDimension(GDIPBitmap,@SWidth,@SHeight));
Bitmap.Width := Trunc(SWidth);
Bitmap.Height := Trunc(SHeight);
For Y := 0 to Pred(Bitmap.Height) do
begin
Line := Bitmap.ScanLine(Y);
For X := 0 to Pred(Bitmap.Width) do
begin
GDIPlusError(GdipBitmapGetPixel(GDIPBitmap,X,Y,@Color));
Line^[X] := BGRAToRGBA(Color);
end;
end;
Result := True;
finally
GdipDisposeImage(GDIPBitmap);
end;
except
Result := False;
end;
end;
//------------------------------------------------------------------------------
Function LoadFile_DevIL(const FileName: String; Bitmap: TSimpleBitmap): Boolean;
var
Image: ILuint;
Inverted: Boolean;
Line: Pointer;
Y: UInt32;
begin
Result := False;
Image := ilGenImage;
try
ilBindImage(Image);
If ilLoadImage(PAnsiChar(StrToAnsi(FileName))) <> IL_FALSE then
begin
Bitmap.Width := ilGetInteger(IL_IMAGE_WIDTH);
Bitmap.Height := ilGetInteger(IL_IMAGE_HEIGHT);
Inverted := ilGetInteger(IL_IMAGE_ORIGIN) = IL_ORIGIN_LOWER_LEFT;
For Y := 0 to Pred(Bitmap.Height) do
begin
If Inverted then
Line := Bitmap.ScanLine(Pred(Bitmap.Height) - Y)
else
Line := Bitmap.ScanLine(Y);
ilCopyPixels(0,Y,0,Bitmap.Width,1,1,IL_RGBA,IL_UNSIGNED_BYTE,Line);
end;
Result := True;
end;
finally
IlDeleteImage(Image);
end;
end;
{===============================================================================
Picture saving functions
===============================================================================}
Function SaveFile_DevIL(const FileName: String; Bitmap: TSimpleBitmap; Format: TPictureFormat; Quality: Integer = 80): Boolean;
var
Image: ILuint;
Inverted: Boolean;
Line: Pointer;
Y: UInt32;
begin
Result := False;
Image := ilGenImage;
try
ilBindImage(Image);
If ilTexImage(Bitmap.Width,Bitmap.Height,1,3,IL_RGB,IL_UNSIGNED_BYTE,nil) <> IL_FALSE then
begin
// set datay by lines
Inverted := ilGetInteger(IL_IMAGE_ORIGIN) = IL_ORIGIN_LOWER_LEFT;
For Y := 0 to Pred(Bitmap.Height) do
begin
If Inverted then
Line := Bitmap.ScanLine(Pred(Bitmap.Height) - Y)
else
Line := Bitmap.ScanLine(Y);
ilSetPixels(0,Y,0,Bitmap.Width,1,1,IL_RGBA,IL_UNSIGNED_BYTE,Line);
end;
// DevIL cannot save if the file already exists
If FileExists(FileName) then
DeleteFile(FileName);
//save to selected format
case Format of
pfBMP: Result := ilSave(IL_BMP,PAnsiChar(StrToAnsi(FileName))) <> IL_FALSE;
pfJPG: begin
ilSetInteger(IL_JPG_QUALITY,Quality);
Result := ilSave(IL_JPG,PAnsiChar(StrToAnsi(FileName))) <> IL_FALSE;
end;
pfPNG: Result := ilSave(IL_PNG,PAnsiChar(StrToAnsi(FileName))) <> IL_FALSE;
pfTGA: Result := ilSave(IL_TGA,PAnsiChar(StrToAnsi(FileName))) <> IL_FALSE;
else
raise Exception.CreateFmt('SaveFile_DevIL: Invalid file format (%d).',[Ord(Format)]);
end;
end;
finally
IlDeleteImage(Image);
end;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clHttpHeader;
interface
{$I clVer.inc}
uses
Classes;
type
TclHttpEntityHeader = class(TPersistent)
private
FCacheControl: string;
FProxyConnection: string;
FConnection: string;
FContentEncoding: string;
FLastModified: string;
FContentType: string;
FContentLanguage: string;
FContentVersion: string;
FContentLength: string;
FExpires: string;
FDate: string;
FExtraFields: TStrings;
FTransferEncoding: string;
FBoundary: string;
FUpdateCount: Integer;
FKnownFields: TStrings;
FOnChanged: TNotifyEvent;
FCharSet: string;
procedure SetCacheControl(const Value: string);
procedure SetConnection(const Value: string);
procedure SetContentEncoding(const Value: string);
procedure SetContentLanguage(const Value: string);
procedure SetContentLength(const Value: string);
procedure SetContentType(const Value: string);
procedure SetContentVersion(const Value: string);
procedure SetDate(const Value: string);
procedure SetExpires(const Value: string);
procedure SetExtraFields(const Value: TStrings);
procedure SetLastModified(const Value: string);
procedure SetProxyConnection(const Value: string);
procedure SetTransferEncoding(const Value: string);
procedure SetBoundary(const Value: string);
procedure Changed;
procedure DoStringListChanged(Sender: TObject);
procedure SetCharSet(const Value: string);
protected
procedure SetListChangedEvent(AList: TStrings);
procedure RegisterField(const AField: string);
procedure RegisterFields; virtual;
procedure InternalParseHeader(AHeader, AFieldList: TStrings); virtual;
procedure InternalAssignHeader(AHeader: TStrings); virtual;
procedure ParseContentType(AHeader, AFieldList: TStrings); virtual;
procedure AssignContentType(AHeader: TStrings); virtual;
procedure DoCreate; virtual;
public
constructor Create;
destructor Destroy; override;
procedure Clear; virtual;
procedure Assign(Source: TPersistent); override;
procedure ParseHeader(AHeader: TStrings);
procedure AssignHeader(AHeader: TStrings);
procedure Update;
procedure BeginUpdate;
procedure EndUpdate;
property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
published
property Boundary: string read FBoundary write SetBoundary;
property CharSet: string read FCharSet write SetCharSet;
property CacheControl: string read FCacheControl write SetCacheControl;
property Connection: string read FConnection write SetConnection;
property ContentEncoding: string read FContentEncoding write SetContentEncoding;
property ContentLanguage: string read FContentLanguage write SetContentLanguage;
property ContentLength: string read FContentLength write SetContentLength;
property ContentType: string read FContentType write SetContentType;
property ContentVersion: string read FContentVersion write SetContentVersion;
property Date: string read FDate write SetDate;
property Expires: string read FExpires write SetExpires;
property LastModified: string read FLastModified write SetLastModified;
property ProxyConnection: string read FProxyConnection write SetProxyConnection;
property TransferEncoding: string read FTransferEncoding write SetTransferEncoding;
property ExtraFields: TStrings read FExtraFields write SetExtraFields;
end;
TclHttpRequestHeader = class(TclHttpEntityHeader)
private
FReferer: string;
FAcceptEncoding: string;
FAccept: string;
FUserAgent: string;
FAcceptLanguage: string;
FAcceptCharSet: string;
FAuthorization: string;
FProxyAuthorization: string;
FRange: string;
FHost: string;
procedure SetAccept(const Value: string);
procedure SetAcceptCharSet(const Value: string);
procedure SetAcceptEncoding(const Value: string);
procedure SetAcceptLanguage(const Value: string);
procedure SetAuthorization(const Value: string);
procedure SetReferer(const Value: string);
procedure SetUserAgent(const Value: string);
procedure SetProxyAuthorization(const Value: string);
procedure SetHost(const Value: string);
procedure SetRange(const Value: string);
protected
procedure RegisterFields; override;
procedure InternalParseHeader(AHeader, AFieldList: TStrings); override;
procedure InternalAssignHeader(AHeader: TStrings); override;
public
procedure Clear; override;
procedure Assign(Source: TPersistent); override;
published
property Accept: string read FAccept write SetAccept;
property AcceptCharSet: string read FAcceptCharSet write SetAcceptCharSet;
property AcceptEncoding: string read FAcceptEncoding write SetAcceptEncoding;
property AcceptLanguage: string read FAcceptLanguage write SetAcceptLanguage;
property Authorization: string read FAuthorization write SetAuthorization;
property Host: string read FHost write SetHost;
property ProxyAuthorization: string read FProxyAuthorization write SetProxyAuthorization;
property Range: string read FRange write SetRange;
property Referer: string read FReferer write SetReferer;
property UserAgent: string read FUserAgent write SetUserAgent;
end;
TclHttpResponseHeader = class(TclHttpEntityHeader)
private
FAge: string;
FAcceptRanges: string;
FRetryAfter: string;
FAuthenticate: TStrings;
FAllow: string;
FProxyAuthenticate: TStrings;
FContentRange: string;
FETag: string;
FServer: string;
FLocation: string;
procedure SetAcceptRanges(const Value: string);
procedure SetAge(const Value: string);
procedure SetAllow(const Value: string);
procedure SetAuthenticate(const Value: TStrings);
procedure SetContentRange(const Value: string);
procedure SetETag(const Value: string);
procedure SetLocation(const Value: string);
procedure SetProxyAuthenticate(const Value: TStrings);
procedure SetRetryAfter(const Value: string);
procedure SetServer(const Value: string);
procedure GetAuthChallenge(AHeader, AFieldList: TStrings; const AuthFieldName: string; AuthChallenge: TStrings);
procedure SetAuthChallenge(AHeader: TStrings; const AuthFieldName: string; AuthChallenge: TStrings);
protected
procedure RegisterFields; override;
procedure InternalParseHeader(AHeader, AFieldList: TStrings); override;
procedure InternalAssignHeader(AHeader: TStrings); override;
procedure DoCreate; override;
public
destructor Destroy; override;
procedure Clear; override;
procedure Assign(Source: TPersistent); override;
published
property AcceptRanges: string read FAcceptRanges write SetAcceptRanges;
property Age: string read FAge write SetAge;
property Allow: string read FAllow write SetAllow;
property Authenticate: TStrings read FAuthenticate write SetAuthenticate;
property ContentRange: string read FContentRange write SetContentRange;
property ETag: string read FETag write SetETag;
property Location: string read FLocation write SetLocation;
property ProxyAuthenticate: TStrings read FProxyAuthenticate write SetProxyAuthenticate;
property RetryAfter: string read FRetryAfter write SetRetryAfter;
property Server: string read FServer write SetServer;
end;
function AddHttpFieldItem(const AFieldValue, AItemName, AItemValue: string): string;
implementation
uses
SysUtils, clUtils;
function AddHttpFieldItem(const AFieldValue, AItemName, AItemValue: string): string;
begin
Result := AFieldValue;
if (AItemValue <> '') then
begin
Result := Format('%s; %s=%s', [Result, AItemName, AItemValue]);
end;
end;
{ TclHttpEntityHeader }
procedure TclHttpEntityHeader.Assign(Source: TPersistent);
var
Src: TclHttpEntityHeader;
begin
BeginUpdate();
try
if (Source is TclHttpEntityHeader) then
begin
Src := (Source as TclHttpEntityHeader);
Boundary := Src.Boundary;
CharSet := Src.CharSet;
CacheControl := Src.CacheControl;
Connection := Src.Connection;
ContentEncoding := Src.ContentEncoding;
ContentLanguage := Src.ContentLanguage;
ContentLength := Src.ContentLength;
ContentType := Src.ContentType;
ContentVersion := Src.ContentVersion;
Date := Src.Date;
Expires := Src.Expires;
LastModified := Src.LastModified;
ProxyConnection := Src.ProxyConnection;
TransferEncoding := Src.TransferEncoding;
ExtraFields := Src.ExtraFields;
end else
begin
inherited Assign(Source);
end;
finally
EndUpdate();
end;
end;
procedure TclHttpEntityHeader.AssignContentType(AHeader: TStrings);
var
s: string;
begin
s := ContentType;
if (s <> '') then
begin
s := AddHttpFieldItem(s, 'boundary', Boundary);
s := AddHttpFieldItem(s, 'charset', CharSet);
AddHeaderField(AHeader, 'Content-Type', s);
end;
end;
procedure TclHttpEntityHeader.AssignHeader(AHeader: TStrings);
begin
AHeader.BeginUpdate();
try
InternalAssignHeader(AHeader);
finally
AHeader.EndUpdate();
end;
end;
procedure TclHttpEntityHeader.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TclHttpEntityHeader.Changed;
begin
if Assigned(OnChanged) then
begin
OnChanged(Self);
end;
end;
procedure TclHttpEntityHeader.Clear;
begin
BeginUpdate();
try
Boundary := '';
CharSet := '';
CacheControl := '';
Connection := '';
ContentEncoding := '';
ContentLanguage := '';
ContentLength := '';
ContentType := '';
ContentVersion := '';
Date := '';
Expires := '';
LastModified := '';
ProxyConnection := '';
TransferEncoding := '';
ExtraFields.Clear();
finally
EndUpdate();
end;
end;
constructor TclHttpEntityHeader.Create;
begin
inherited Create();
DoCreate();
RegisterFields();
Clear();
end;
destructor TclHttpEntityHeader.Destroy;
begin
FExtraFields.Free();
FKnownFields.Free();
inherited Destroy();
end;
procedure TclHttpEntityHeader.DoCreate;
begin
FKnownFields := TStringList.Create();
FExtraFields := TStringList.Create();
SetListChangedEvent(FExtraFields);
end;
procedure TclHttpEntityHeader.DoStringListChanged(Sender: TObject);
begin
Update();
end;
procedure TclHttpEntityHeader.EndUpdate;
begin
if (FUpdateCount > 0) then
begin
Dec(FUpdateCount);
Update();
end;
end;
procedure TclHttpEntityHeader.InternalAssignHeader(AHeader: TStrings);
begin
AddHeaderField(AHeader, 'Content-Encoding', ContentEncoding);
AddHeaderField(AHeader, 'Content-Language', ContentLanguage);
AddHeaderField(AHeader, 'Content-Length', ContentLength);
AddHeaderField(AHeader, 'Content-Version', ContentVersion);
AssignContentType(AHeader);
AddHeaderField(AHeader, 'Date', Date);
AddHeaderField(AHeader, 'Expires', Expires);
AddHeaderField(AHeader, 'LastModified', LastModified);
AddHeaderField(AHeader, 'Transfer-Encoding', TransferEncoding);
AddHeaderField(AHeader, 'Cache-Control', CacheControl);
AddHeaderField(AHeader, 'Connection', Connection);
AddHeaderField(AHeader, 'Proxy-Connection', ProxyConnection);
AHeader.AddStrings(ExtraFields)
end;
procedure TclHttpEntityHeader.InternalParseHeader(AHeader, AFieldList: TStrings);
begin
CacheControl := GetHeaderFieldValue(AHeader, AFieldList, 'Cache-Control');
Connection := GetHeaderFieldValue(AHeader, AFieldList, 'Connection');
ContentEncoding := GetHeaderFieldValue(AHeader, AFieldList, 'Content-Encoding');
ContentLanguage := GetHeaderFieldValue(AHeader, AFieldList, 'Content-Language');
ContentLength := GetHeaderFieldValue(AHeader, AFieldList, 'Content-Length');
ContentVersion := GetHeaderFieldValue(AHeader, AFieldList, 'Content-Version');
Date := GetHeaderFieldValue(AHeader, AFieldList, 'Date');
Expires := GetHeaderFieldValue(AHeader, AFieldList, 'Expires');
LastModified := GetHeaderFieldValue(AHeader, AFieldList, 'Last-Modified');
ProxyConnection := GetHeaderFieldValue(AHeader, AFieldList, 'Proxy-Connection');
TransferEncoding := GetHeaderFieldValue(AHeader, AFieldList, 'Transfer-Encoding');
ParseContentType(AHeader, AFieldList);
end;
procedure TclHttpEntityHeader.ParseContentType(AHeader, AFieldList: TStrings);
var
s: string;
begin
s := GetHeaderFieldValue(AHeader, AFieldList, 'Content-Type');
ContentType := GetHeaderFieldValueItem(s, '');
Boundary := GetHeaderFieldValueItem(s, 'boundary=');
CharSet := GetHeaderFieldValueItem(s, 'charset=');
end;
procedure TclHttpEntityHeader.ParseHeader(AHeader: TStrings);
var
i: Integer;
s: string;
FieldList: TStrings;
begin
FieldList := nil;
BeginUpdate();
try
Clear();
FieldList := TStringList.Create();
GetHeaderFieldList(0, AHeader, FieldList);
InternalParseHeader(AHeader, FieldList);
for i := 0 to FieldList.Count - 1 do
begin
if (FindInStrings(FKnownFields, FieldList[i]) < 0) then
begin
s := system.Copy(AHeader[Integer(FieldList.Objects[i])], 1, Length(FieldList[i]));
ExtraFields.Add(s + ': ' + GetHeaderFieldValue(AHeader, FieldList, i));
end;
end;
finally
FieldList.Free();
EndUpdate();
end;
end;
procedure TclHttpEntityHeader.RegisterField(const AField: string);
begin
if (FindInStrings(FKnownFields, AField) < 0) then
begin
FKnownFields.Add(AField);
end;
end;
procedure TclHttpEntityHeader.RegisterFields;
begin
RegisterField('Cache-Control');
RegisterField('Connection');
RegisterField('Content-Encoding');
RegisterField('Content-Language');
RegisterField('Content-Length');
RegisterField('Content-Type');
RegisterField('Content-Version');
RegisterField('Date');
RegisterField('Expires');
RegisterField('Last-Modified');
RegisterField('Proxy-Connection');
RegisterField('Transfer-Encoding');
end;
procedure TclHttpEntityHeader.SetBoundary(const Value: string);
begin
if (FBoundary <> Value) then
begin
FBoundary := Value;
Update();
FBoundary := Value;
end;
end;
procedure TclHttpEntityHeader.SetCacheControl(const Value: string);
begin
if (FCacheControl <> Value) then
begin
FCacheControl := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetCharSet(const Value: string);
begin
if (FCharSet <> Value) then
begin
FCharSet := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetConnection(const Value: string);
begin
if (FConnection <> Value) then
begin
FConnection := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetContentEncoding(const Value: string);
begin
if (FContentEncoding <> Value) then
begin
FContentEncoding := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetContentLanguage(const Value: string);
begin
if (FContentLanguage <> Value) then
begin
FContentLanguage := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetContentLength(const Value: string);
begin
if (FContentLength <> Value) then
begin
FContentLength := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetContentType(const Value: string);
begin
if (FContentType <> Value) then
begin
FContentType := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetContentVersion(const Value: string);
begin
if (FContentVersion <> Value) then
begin
FContentVersion := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetDate(const Value: string);
begin
if (FDate <> Value) then
begin
FDate := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetExpires(const Value: string);
begin
if (FExpires <> Value) then
begin
FExpires := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetExtraFields(const Value: TStrings);
begin
FExtraFields.Assign(Value);
end;
procedure TclHttpEntityHeader.SetLastModified(const Value: string);
begin
if (FLastModified <> Value) then
begin
FLastModified := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetListChangedEvent(AList: TStrings);
begin
(AList as TStringList).OnChange := DoStringListChanged;
end;
procedure TclHttpEntityHeader.SetProxyConnection(const Value: string);
begin
if (FProxyConnection <> Value) then
begin
FProxyConnection := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.SetTransferEncoding(const Value: string);
begin
if (FTransferEncoding <> Value) then
begin
FTransferEncoding := Value;
Update();
end;
end;
procedure TclHttpEntityHeader.Update;
begin
if (FUpdateCount = 0) then
begin
Changed();
end;
end;
{ TclHttpRequestHeader }
procedure TclHttpRequestHeader.Assign(Source: TPersistent);
var
Src: TclHttpRequestHeader;
begin
BeginUpdate();
try
inherited Assign(Source);
if (Source is TclHttpRequestHeader) then
begin
Src := (Source as TclHttpRequestHeader);
Accept := Src.Accept;
AcceptCharSet := Src.AcceptCharSet;
AcceptEncoding := Src.AcceptEncoding;
AcceptLanguage := Src.AcceptLanguage;
Authorization := Src.Authorization;
Host := Src.Host;
ProxyAuthorization := Src.ProxyAuthorization;
Range := Src.Range;
Referer := Src.Referer;
UserAgent := Src.UserAgent;
end;
finally
EndUpdate();
end;
end;
procedure TclHttpRequestHeader.InternalAssignHeader(AHeader: TStrings);
begin
AddHeaderField(AHeader, 'Accept', Accept);
AddHeaderField(AHeader, 'Accept-Charset', AcceptCharSet);
AddHeaderField(AHeader, 'Accept-Encoding', AcceptEncoding);
AddHeaderField(AHeader, 'Accept-Language', AcceptLanguage);
AddHeaderField(AHeader, 'Range', Range);
AddHeaderField(AHeader, 'Referer', Referer);
AddHeaderField(AHeader, 'Host', Host);
AddHeaderField(AHeader, 'User-Agent', UserAgent);
AddHeaderField(AHeader, 'Authorization', Authorization);
AddHeaderField(AHeader, 'Proxy-Authorization', ProxyAuthorization);
inherited InternalAssignHeader(AHeader);
end;
procedure TclHttpRequestHeader.Clear;
begin
BeginUpdate();
try
inherited Clear();
Accept := '*/*';
AcceptCharSet := '';
AcceptEncoding := '';
AcceptLanguage := '';
Authorization := '';
Host := '';
ProxyAuthorization := '';
Range := '';
Referer := '';
UserAgent := '';
finally
EndUpdate();
end;
end;
procedure TclHttpRequestHeader.SetAccept(const Value: string);
begin
if (FAccept <> Value) then
begin
FAccept := Value;
Update();
end;
end;
procedure TclHttpRequestHeader.SetAcceptCharSet(const Value: string);
begin
if (FAcceptCharSet <> Value) then
begin
FAcceptCharSet := Value;
Update();
end;
end;
procedure TclHttpRequestHeader.SetAcceptEncoding(const Value: string);
begin
if (FAcceptEncoding <> Value) then
begin
FAcceptEncoding := Value;
Update();
end;
end;
procedure TclHttpRequestHeader.SetAcceptLanguage(const Value: string);
begin
if (FAcceptLanguage <> Value) then
begin
FAcceptLanguage := Value;
Update();
end;
end;
procedure TclHttpRequestHeader.SetAuthorization(const Value: string);
begin
if (FAuthorization <> Value) then
begin
FAuthorization := Value;
Update();
end;
end;
procedure TclHttpRequestHeader.SetHost(const Value: string);
begin
if (FHost <> Value) then
begin
FHost := Value;
Update();
end;
end;
procedure TclHttpRequestHeader.SetProxyAuthorization(const Value: string);
begin
if (FProxyAuthorization <> Value) then
begin
FProxyAuthorization := Value;
Update();
end;
end;
procedure TclHttpRequestHeader.SetRange(const Value: string);
begin
if (FRange <> Value) then
begin
FRange := Value;
Update();
end;
end;
procedure TclHttpRequestHeader.SetReferer(const Value: string);
begin
if (FReferer <> Value) then
begin
FReferer := Value;
Update();
end;
end;
procedure TclHttpRequestHeader.SetUserAgent(const Value: string);
begin
if (FUserAgent <> Value) then
begin
FUserAgent := Value;
Update();
end;
end;
procedure TclHttpRequestHeader.InternalParseHeader(AHeader, AFieldList: TStrings);
begin
inherited InternalParseHeader(AHeader, AFieldList);
Accept := GetHeaderFieldValue(AHeader, AFieldList, 'Accept');
AcceptCharSet := GetHeaderFieldValue(AHeader, AFieldList, 'Accept-Charset');
AcceptEncoding := GetHeaderFieldValue(AHeader, AFieldList, 'Accept-Encoding');
AcceptLanguage := GetHeaderFieldValue(AHeader, AFieldList, 'Accept-Language');
Authorization := GetHeaderFieldValue(AHeader, AFieldList, 'Authorization');
Host := GetHeaderFieldValue(AHeader, AFieldList, 'Host');
ProxyAuthorization := GetHeaderFieldValue(AHeader, AFieldList, 'Proxy-Authorization');
Range := GetHeaderFieldValue(AHeader, AFieldList, 'Range');
Referer := GetHeaderFieldValue(AHeader, AFieldList, 'Referer');
UserAgent := GetHeaderFieldValue(AHeader, AFieldList, 'User-Agent');
end;
procedure TclHttpRequestHeader.RegisterFields;
begin
inherited RegisterFields();
RegisterField('Accept');
RegisterField('Accept-Charset');
RegisterField('Accept-Encoding');
RegisterField('Accept-Language');
RegisterField('Authorization');
RegisterField('Host');
RegisterField('Proxy-Authorization');
RegisterField('Range');
RegisterField('Referer');
RegisterField('User-Agent');
end;
{ TclHttpResponseHeader }
procedure TclHttpResponseHeader.Assign(Source: TPersistent);
var
Src: TclHttpResponseHeader;
begin
BeginUpdate();
try
inherited Assign(Source);
if (Source is TclHttpResponseHeader) then
begin
Src := (Source as TclHttpResponseHeader);
AcceptRanges := Src.AcceptRanges;
Age := Src.Age;
Allow := Src.Allow;
Authenticate := Src.Authenticate;
ContentRange := Src.ContentRange;
ETag := Src.ETag;
Location := Src.Location;
ProxyAuthenticate := Src.ProxyAuthenticate;
RetryAfter := Src.RetryAfter;
Server := Src.Server;
end;
finally
EndUpdate();
end;
end;
procedure TclHttpResponseHeader.Clear;
begin
BeginUpdate();
try
inherited Clear();
AcceptRanges := '';
Age := '';
Allow := '';
Authenticate.Clear();
ContentRange := '';
ETag := '';
Location := '';
ProxyAuthenticate.Clear();
RetryAfter := '';
Server := '';
finally
EndUpdate();
end;
end;
destructor TclHttpResponseHeader.Destroy;
begin
FProxyAuthenticate.Free();
FAuthenticate.Free();
inherited Destroy();
end;
procedure TclHttpResponseHeader.InternalAssignHeader(AHeader: TStrings);
begin
AddHeaderField(AHeader, 'Allow', Allow);
AddHeaderField(AHeader, 'Accept-Ranges', AcceptRanges);
AddHeaderField(AHeader, 'Age', Age);
AddHeaderField(AHeader, 'Content-Range', ContentRange);
AddHeaderField(AHeader, 'ETag', ETag);
AddHeaderField(AHeader, 'Location', Location);
AddHeaderField(AHeader, 'Retry-After', RetryAfter);
AddHeaderField(AHeader, 'Server', Server);
AddHeaderField(AHeader, 'Transfer-Encoding', TransferEncoding);
SetAuthChallenge(AHeader, 'WWW-Authenticate', Authenticate);
SetAuthChallenge(AHeader, 'Proxy-Authenticate', ProxyAuthenticate);
inherited InternalAssignHeader(AHeader);
end;
procedure TclHttpResponseHeader.GetAuthChallenge(AHeader, AFieldList: TStrings;
const AuthFieldName: string; AuthChallenge: TStrings);
var
i: Integer;
begin
AuthChallenge.Clear();
for i := 0 to AFieldList.Count - 1 do
begin
if SameText(AuthFieldName, AFieldList[i]) then
begin
AuthChallenge.Add(GetHeaderFieldValue(AHeader, AFieldList, i));
end;
end;
end;
procedure TclHttpResponseHeader.SetAuthChallenge(AHeader: TStrings;
const AuthFieldName: string; AuthChallenge: TStrings);
var
i: Integer;
begin
for i := 0 to AuthChallenge.Count - 1 do
begin
AddHeaderField(AHeader, AuthFieldName, AuthChallenge[i]);
end;
end;
procedure TclHttpResponseHeader.InternalParseHeader(AHeader, AFieldList: TStrings);
begin
inherited InternalParseHeader(AHeader, AFieldList);
AcceptRanges := GetHeaderFieldValue(AHeader, AFieldList, 'Accept-Ranges');
Age := GetHeaderFieldValue(AHeader, AFieldList, 'Age');
Allow := GetHeaderFieldValue(AHeader, AFieldList, 'Allow');
ContentRange := GetHeaderFieldValue(AHeader, AFieldList, 'Content-Range');
ETag := GetHeaderFieldValue(AHeader, AFieldList, 'ETag');
Location := GetHeaderFieldValue(AHeader, AFieldList, 'Location');
RetryAfter := GetHeaderFieldValue(AHeader, AFieldList, 'Retry-After');
Server := GetHeaderFieldValue(AHeader, AFieldList, 'Server');
TransferEncoding := GetHeaderFieldValue(AHeader, AFieldList, 'Transfer-Encoding');
GetAuthChallenge(AHeader, AFieldList, 'WWW-Authenticate', Authenticate);
GetAuthChallenge(AHeader, AFieldList, 'Proxy-Authenticate', ProxyAuthenticate);
end;
procedure TclHttpResponseHeader.RegisterFields;
begin
inherited RegisterFields();
RegisterField('Accept-Ranges');
RegisterField('Age');
RegisterField('Allow');
RegisterField('WWW-Authenticate');
RegisterField('Content-Range');
RegisterField('ETag');
RegisterField('Location');
RegisterField('Proxy-Authenticate');
RegisterField('Retry-After');
RegisterField('Server');
RegisterField('Transfer-Encoding');
end;
procedure TclHttpResponseHeader.SetAcceptRanges(const Value: string);
begin
if (FAcceptRanges <> Value) then
begin
FAcceptRanges := Value;
Update();
end;
end;
procedure TclHttpResponseHeader.SetAge(const Value: string);
begin
if (FAge <> Value) then
begin
FAge := Value;
Update();
end;
end;
procedure TclHttpResponseHeader.SetAllow(const Value: string);
begin
if (FAllow <> Value) then
begin
FAllow := Value;
Update();
end;
end;
procedure TclHttpResponseHeader.SetAuthenticate(const Value: TStrings);
begin
FAuthenticate.Assign(Value);
end;
procedure TclHttpResponseHeader.SetContentRange(const Value: string);
begin
if (FContentRange <> Value) then
begin
FContentRange := Value;
Update();
end;
end;
procedure TclHttpResponseHeader.SetETag(const Value: string);
begin
if (FETag <> Value) then
begin
FETag := Value;
Update();
end;
end;
procedure TclHttpResponseHeader.SetLocation(const Value: string);
begin
if (FLocation <> Value) then
begin
FLocation := Value;
Update();
end;
end;
procedure TclHttpResponseHeader.SetProxyAuthenticate(const Value: TStrings);
begin
FProxyAuthenticate.Assign(Value);
end;
procedure TclHttpResponseHeader.SetRetryAfter(const Value: string);
begin
if (FRetryAfter <> Value) then
begin
FRetryAfter := Value;
Update();
end;
end;
procedure TclHttpResponseHeader.SetServer(const Value: string);
begin
if (FServer <> Value) then
begin
FServer := Value;
Update();
end;
end;
procedure TclHttpResponseHeader.DoCreate;
begin
inherited DoCreate();
FAuthenticate := TStringList.Create();
FProxyAuthenticate := TStringList.Create();
SetListChangedEvent(FAuthenticate);
SetListChangedEvent(FProxyAuthenticate);
end;
end.
|
program shaders_exercise3;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, glfw31, gl, GLext, shader_s;
const
// settings
SCR_WIDTH = 800;
SCR_HEIGHT = 600;
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
procedure processInput(window: pGLFWwindow); cdecl;
begin
if glfwGetKey(window, GLFW_KEY_ESCAPE) = GLFW_PRESS then
begin
glfwSetWindowShouldClose(window, GLFW_TRUE);
end;
end;
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
procedure framebuffer_size_callback(window: pGLFWwindow; width, height: Integer); cdecl;
begin
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
end;
procedure showError(error: GLFW_INT; description: PChar); cdecl;
begin
Writeln(description);
end;
var
window: pGLFWwindow;
ourShader :TShader;
// set up vertex data
// ------------------
vertices: array [0..17] of GLfloat = (
// positions // colors
-0.5, -0.5, 0.0, 1.0, 0.0, 0.0,
0.5, -0.5, 0.0, 0.0, 1.0, 0.0,
0.0, 0.5, 0.0, 0.0, 0.0, 1.0
);
VBO, VAO: GLuint;
begin
// glfw: initialize and configure
// ------------------------------
glfwInit;
glfwSetErrorCallback(@showError);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// glfw window creation
// --------------------
window := glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, 'LearnOpenGL', nil, nil);
if window = nil then
begin
Writeln('Failed to create GLFW window');
glfwTerminate;
Exit;
end;
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, @framebuffer_size_callback);
// GLext: load all OpenGL function pointers
// ----------------------------------------
if Load_GL_version_3_3_CORE = false then
begin
Writeln('OpenGL 3.3 is not supported!');
glfwTerminate;
Exit;
end;
// build and compile our shader program
// ------------------------------------
ourShader := TShader.Create('3.3.shader.vs', '3.3.shader.fs'); // you can name your shader files however you like
// set up buffer(s) and configure vertex attributes
// ------------------------------------------------
// VBO & VAO
glGenVertexArrays(1, @VAO);
glGenBuffers(1, @VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), @vertices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), PGLvoid(0));
glEnableVertexAttribArray(0);
// color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), PGLvoid(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
// glBindVertexArray(0);
// render loop
// -----------
while glfwWindowShouldClose(window) = GLFW_FALSE do
begin
// input
// -----
processInput(window);
// render
// ------
glClearColor(0.2, 0.3, 0.3, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
ourShader.use();
glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized
glDrawArrays(GL_TRIANGLES, 0, 3);
//glBindVertexArray(0); // no need to unbind it every time
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents;
end;
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, @VAO);
glDeleteBuffers(1, @VBO);
FreeAndNil(ourShader);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate;
end.
|
unit ContaPagar;
interface
uses
DBXJSONReflect, RTTI, DBXPlatform, Generics.Collections, ItemPedidoVenda, Fornecedor;
type
TDoubleInterceptor = class(TJSONInterceptor)
public
function StringConverter(Data: TObject; Field: string): string; override;
procedure StringReverter(Data: TObject; Field: string; Arg: string); override;
end;
TContaPagar = class
private
FId: integer;
FFornecedor: TFornecedor;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FVencimento: TDateTime;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FValor: Currency;
FObservacoes: string;
FBaixada: Boolean;
public
property Id: integer read FId write FId;
property Fornecedor: TFornecedor read FFornecedor write FFornecedor;
property Vencimento: TDateTime read FVencimento write FVencimento;
property Valor: Currency read FValor write FValor;
property Observacoes: string read FObservacoes write FObservacoes;
property Baixada: Boolean read FBaixada write FBaixada;
constructor Create; overload;
constructor Create(Id: integer); overload;
destructor Destroy; override;
end;
implementation
{ TDoubleInterceptor }
function TDoubleInterceptor.StringConverter(Data: TObject; Field: string): string;
var
LRttiContext: TRttiContext;
LValue: Double;
begin
LValue := LRttiContext.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<Double>;
Result := TDBXPlatform.JsonFloat(LValue);
end;
procedure TDoubleInterceptor.StringReverter(Data: TObject; Field, Arg: string);
var
LRttiContext: TRttiContext;
LValue: Double;
begin
LValue := TDBXPlatform.JsonToFloat(Arg);
LRttiContext.GetType(Data.ClassType).GetField(Field).SetValue(Data, TValue.From<Double>(LValue));
end;
{ TContaPagar }
constructor TContaPagar.Create;
begin
end;
constructor TContaPagar.Create(Id: integer);
begin
Self.Id := Id;
end;
destructor TContaPagar.Destroy;
begin
if Assigned(FFornecedor) then
FFornecedor.Free;
inherited;
end;
end.
|
unit htAutoTable;
interface
uses
Windows, Messages, SysUtils, Types, Classes, Controls, Graphics, Forms,
htInterfaces, htMarkup, htControls,
LrControlIterator;
type
ThtRow = class
protected
procedure FindMaxHeight(inControl: TControl);
public
RowHeight: Integer;
Controls: TList;
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure InsertCtrl(inC: TControl);
end;
//
ThtCustomAutoTable = class(ThtCustomControl)
protected
Iterator: TLrSortedCtrlIterator;
MouseIsDown: Boolean;
MousePos: TPoint;
MouseRow: Integer;
Rows: TList;
function AboveRowLine(inY: Integer; var outRow: Integer): Boolean;
function FindRowCtrl(inB: Integer): TControl;
function GetRowHeights(inIndex: Integer): Integer;
function InsertRowCtrl(inRow: ThtRow; inC: TControl): Boolean;
procedure AlignControls(AControl: TControl; var Rect: TRect); override;
procedure ClearRows;
procedure CMDesignHitTest(var Msg: TCMDesignHitTest);
message CM_DESIGNHITTEST;
procedure DrawDragLine(inY: Integer);
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 NormalizeBounds;
procedure NormalizeRows;
procedure SetRowHeights(inIndex: Integer; const Value: Integer);
procedure StylePaint; override;
procedure WMSetCursor(var Msg: TWMSetCursor); message WM_SETCURSOR;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); override;
property RowHeights[inIndex: Integer]: Integer read GetRowHeights
write SetRowHeights;
end;
//
ThtAutoTable = class(ThtCustomAutoTable)
published
property Align;
property Outline;
property Style;
property Visible;
end;
implementation
uses
LrVclUtils;
{ ThtRow }
constructor ThtRow.Create;
begin
Controls := TList.Create;
end;
destructor ThtRow.Destroy;
begin
Controls.Free;
inherited;
end;
procedure ThtRow.Clear;
begin
Controls.Clear;
inherited;
end;
procedure ThtRow.FindMaxHeight(inControl: TControl);
begin
inControl.Perform(CM_FONTCHANGED, 0, 0);
RowHeight := LrMax(inControl.Height, RowHeight);
end;
procedure ThtRow.InsertCtrl(inC: TControl);
var
i: Integer;
begin
FindMaxHeight(inC);
for i := 0 to Pred(Controls.Count) do
if TControl(Controls[i]).Left > inC.Left then
begin
Controls.Insert(i, inC);
exit;
end;
Controls.Add(inC);
end;
{ ThtCustomAutoTable }
constructor ThtCustomAutoTable.Create(inOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [ csAcceptsControls ];
Rows := TList.Create;
Transparent := true;
end;
destructor ThtCustomAutoTable.Destroy;
begin
Rows.Free;
inherited;
end;
procedure ThtCustomAutoTable.ClearRows;
var
i: Integer;
begin
for i := 0 to Pred(Rows.Count) do
ThtRow(Rows[i]).Free;
Rows.Clear;
end;
function ThtCustomAutoTable.FindRowCtrl(inB: Integer): TControl;
begin
Result := nil;
with Iterator do
begin
Reset;
while Next do
if Ctrl.Top < inB then
begin
Result := Ctrl;
break;
end;
end;
end;
function ThtCustomAutoTable.InsertRowCtrl(inRow: ThtRow;
inC: TControl): Boolean;
begin
Result := inC <> nil;
if Result then
begin
Iterator.Controls.Remove(inC);
inRow.InsertCtrl(inC);
end;
end;
procedure ThtCustomAutoTable.NormalizeRows;
var
t, h: Integer;
c: TControl;
row: ThtRow;
begin
ClearRows;
Iterator := TLrSortedCtrlIterator.Create(Self);
try
while not Iterator.Eof do
begin
// New row
row := ThTRow.Create;
Rows.Add(row);
// Get the first control
Iterator.Next;
// First available control is always the row starter
c := Iterator.Ctrl;
t := c.Top;
h := c.Height;
InsertRowCtrl(row, c);
// Fill the rest of the row
repeat
c := FindRowCtrl(t + h); //row.RowHeight);
InsertRowCtrl(row, c);
until c = nil;
// Start over with remaining controls
Iterator.Reset;
end;
finally
Iterator.Free;
end;
end;
procedure ThtCustomAutoTable.NormalizeBounds;
var
i, j, l, t: Integer;
c: TControl;
begin
t := 0;
for i := 0 to Pred(Rows.Count) do
begin
l := 0;
with ThtRow(Rows[i]) do
begin
for j := 0 to Pred(Controls.Count) do
begin
c := TControl(Controls[j]);
c.SetBounds(l, t, c.Width, RowHeight);
Inc(l, c.Width);
end;
Inc(t, RowHeight);
end;
end;
end;
procedure ThtCustomAutoTable.AlignControls(AControl: TControl;
var Rect: TRect);
begin
NormalizeRows;
NormalizeBounds;
Invalidate;
end;
function ThtCustomAutoTable.GetRowHeights(inIndex: Integer): Integer;
begin
Result := ThtRow(Rows[inIndex]).RowHeight;
end;
procedure ThtCustomAutoTable.SetRowHeights(inIndex: Integer;
const Value: Integer);
begin
ThtRow(Rows[inIndex]).RowHeight := Value;
end;
procedure ThtCustomAutoTable.StylePaint;
var
i, t: Integer;
begin
inherited;
with Canvas do
begin
Pen.Style := psDot;
Pen.Color := clSilver;
SetBkMode(Handle, Windows.TRANSPARENT);
t := 0;
for i := 0 to Pred(Rows.Count) do
begin
Inc(t, RowHeights[i]);
MoveTo(0, t);
LineTo(ClientWidth, t);
end;
end;
end;
function ThtCustomAutoTable.AboveRowLine(inY: Integer; var outRow: Integer): Boolean;
const
cHysteresis = 3;
var
t, i: Integer;
begin
Result := true;
t := 0;
for i := 0 to Pred(Rows.Count) do
begin
outRow := i;
Inc(t, Integer(RowHeights[i]));
if (abs(inY - t) < cHysteresis) then
exit;
end;
Result := false;
end;
procedure ThtCustomAutoTable.WMSetCursor(var Msg: TWMSetCursor);
var
cur: HCURSOR;
i: Integer;
begin
cur := 0;
if Msg.HitTest = HTCLIENT then
if AboveRowLine(ScreenToClient(Mouse.CursorPos).Y, i) then
cur := Screen.Cursors[crVSplit];
if cur <> 0 then
SetCursor(cur)
else
inherited;
end;
procedure ThtCustomAutoTable.DrawDragLine(inY: Integer);
begin
with Canvas do
begin
//SelectClipRgn(Handle, NULLREGION);
Pen.Color := clSilver;
Pen.Style := psDot;
//Pen.Mode := pmXor;
//Pen.Width := 3;
MoveTo(0, inY);
LineTo(0, inY);
end;
end;
procedure ThtCustomAutoTable.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
MouseIsDown := true;
MousePos := Point(X, Y);
end;
procedure ThtCustomAutoTable.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
if MouseIsDown and (MousePos.Y <> Y) then
begin
DrawDragLine(MousePos.Y);
RowHeights[MouseRow] := RowHeights[MouseRow] + Y - MousePos.Y;
DisableAlign;
NormalizeBounds;
EnableAlign;
MousePos := Point(X, Y);
DrawDragLine(MousePos.Y);
end;
end;
procedure ThtCustomAutoTable.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
MouseIsDown := false;
DrawDragLine(MousePos.Y);
end;
procedure ThtCustomAutoTable.CMDesignHitTest(var Msg: TCMDesignHitTest);
var
ss: Boolean;
begin
ss := MouseIsDown or AboveRowLine(Msg.Pos.Y, MouseRow);
Msg.Result := Longint(ss);
end;
procedure ThtCustomAutoTable.Generate(const inContainer: string;
inMarkup: ThtMarkup);
begin
//
end;
end.
|
//------------------------------------------------------------------------------
//InstanceMap UNIT
//------------------------------------------------------------------------------
// What it does -
// Object for instance map
//
// Changes -
// [2008/12/06] Aeomin - Created
//
//------------------------------------------------------------------------------
unit InstanceMap;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Classes,
Map,
List32
;
type
TInstanceMap = class(TMap)
private
//Instance Map ID
Identifier : String;
function LoadCache(const Name:String;var Memory : TMemoryStream):Boolean;
procedure LoadNpc;
public
BaseName : String;
procedure Load(const InstanceIdentifier, OriginalMapName:String);reintroduce;
constructor Create;
destructor Destroy;override;
end;
implementation
uses
SysUtils,
Main,
Globals,
MapTypes,
NPC
;
//------------------------------------------------------------------------------
//LoadCache PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Well, we need to cache 'em XD
//
// Changes -
// [2008/12/07] Aeomin - Created.
//------------------------------------------------------------------------------
function TInstanceMap.LoadCache(const Name:String;var Memory : TMemoryStream):Boolean;
const
FSTR_MAPFILE = '%s/%s.pms';
var
Index : Integer;
FileName : String;
begin
Result := False;
Index := MainProc.ZoneServer.InstanceCache.IndexOf(Name);
if Index > -1 then
begin
//COOL, we have cache
Memory := MainProc.ZoneServer.InstanceCache.Objects[Index] as TMemoryStream;
Memory.Position := 0;
Result := LoadFromStream(Memory);
end else
begin
//No? CREATE IT..
FileName :=
Format(
FSTR_MAPFILE,
[MainProc.Options.MapDirectory, Name]
);
if FileExists(FileName) then
begin
Memory := TMemoryStream.Create;
Memory.LoadFromFile(FileName);
MainProc.ZoneServer.InstanceCache.AddObject(Name,Memory);
Result := LoadFromStream(Memory);
end else
begin
Console.Message('Map ' + FileName + ' does not exist!', 'Zone Server');
end;
end;
end;{LoadCache}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//LOAD PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Override of Load in TMap.
//
// Changes -
// [2008/12/06] Aeomin - Created.
//------------------------------------------------------------------------------
procedure TInstanceMap.Load(const InstanceIdentifier, OriginalMapName:String);
Var
MapData : TMemoryStream;
XIndex : Integer;
YIndex : Integer;
Begin
State := LOADING;
BaseName := OriginalMapName;
Name := OriginalMapName;
if LoadCache(OriginalMapName, MapData) then
begin
MainProc.ZoneServer.Database.Map.LoadFlags(Flags, Name);
MapData.Seek(22,0);//skip other non-cell information
//Load Cell Information
SetLength(Cell, Size.X, Size.Y);
for YIndex := 0 to Size.Y - 1 do begin
for XIndex := 0 to Size.X - 1 do begin
MapData.Read(Cell[XIndex][YIndex].Attribute,1);
Cell[XIndex][YIndex].Position := Point(XIndex, YIndex);
Cell[XIndex][YIndex].ObstructionCount := 0;
Cell[XIndex][YIndex].Beings := TIntList32.Create;
Cell[XIndex][YIndex].Items := TIntList32.Create;
end;
end;
LoadNpc;
//Temporary hack..
// Path := 'Maps/'+Name+'.pms';
Identifier := InstanceIdentifier;
Name := InstanceIdentifier + '#' + OriginalMapName;
State := LOADED;
end else
begin
State := UNLOADED;
end;
end;{Load}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//LoadNpc PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Load & Clone npc object
//
// Changes -
// [2008/12/08] Aeomin - Created.
//------------------------------------------------------------------------------
procedure TInstanceMap.LoadNpc;
Var
ObjIndex : Integer;
AnNPC : TScriptNPC;
NewNPC : TScriptNPC;
begin
//Enable all npcs on this map.
for ObjIndex := 0 to MainProc.ZoneServer.NPCList.Count -1 do
begin
AnNPC := TScriptNPC(MainProc.ZoneServer.NPCList.Objects[ObjIndex]);
if AnNPC.Map = BaseName then
begin
if PointInRange(AnNPC.Position) then
begin
if AnNPC is TWarpNPC then
NewNPC := TWarpNPC.Create()
else
NewNPC := TScriptNPC.Create();
AnNPC.CloneTo(NewNPC);
//Let's clone it!
NewNPC.Map := Self.BaseName;
NewNPC.MapInfo := Self;
Cell[NewNPC.Position.X][NewNPC.Position.Y].Beings.AddObject(NewNPC.ID, NewNPC);
NewNPC.Enabled := True;
NPCList.AddObject(NewNPC.ID,NewNPC);
end;
end;
end;
end;{LoadNPC}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Create CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does -
// Create..
//
// Changes -
// [2008/12/08] Aeomin - Created.
//------------------------------------------------------------------------------
constructor TInstanceMap.Create;
begin
inherited;
end;{Create}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy DESTRUCTOR
//------------------------------------------------------------------------------
// What it does -
// Destroy..
//
// Changes -
// [2008/12/08] Aeomin - Created.
//------------------------------------------------------------------------------
destructor TInstanceMap.Destroy;
var
Index : Integer;
begin
for Index := 0 to NPCList.Count - 1 do
begin
NPCList.Objects[Index].Free;
end;
inherited;
end;{Destroy}
//------------------------------------------------------------------------------
end{InstanceMap}.
|
//
// Generated by JavaToPas v1.4 20140515 - 180821
////////////////////////////////////////////////////////////////////////////////
unit javax.net.ssl.SSLEngineResult_Status;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JSSLEngineResult_Status = interface;
JSSLEngineResult_StatusClass = interface(JObjectClass)
['{534A324C-E3C1-4B60-987A-B4659AC2E3FA}']
function _GetBUFFER_OVERFLOW : JSSLEngineResult_Status; cdecl; // A: $4019
function _GetBUFFER_UNDERFLOW : JSSLEngineResult_Status; cdecl; // A: $4019
function _GetCLOSED : JSSLEngineResult_Status; cdecl; // A: $4019
function _GetOK : JSSLEngineResult_Status; cdecl; // A: $4019
function valueOf(&name : JString) : JSSLEngineResult_Status; cdecl; // (Ljava/lang/String;)Ljavax/net/ssl/SSLEngineResult$Status; A: $9
function values : TJavaArray<JSSLEngineResult_Status>; cdecl; // ()[Ljavax/net/ssl/SSLEngineResult$Status; A: $19
property BUFFER_OVERFLOW : JSSLEngineResult_Status read _GetBUFFER_OVERFLOW;// Ljavax/net/ssl/SSLEngineResult$Status; A: $4019
property BUFFER_UNDERFLOW : JSSLEngineResult_Status read _GetBUFFER_UNDERFLOW;// Ljavax/net/ssl/SSLEngineResult$Status; A: $4019
property CLOSED : JSSLEngineResult_Status read _GetCLOSED; // Ljavax/net/ssl/SSLEngineResult$Status; A: $4019
property OK : JSSLEngineResult_Status read _GetOK; // Ljavax/net/ssl/SSLEngineResult$Status; A: $4019
end;
[JavaSignature('javax/net/ssl/SSLEngineResult_Status')]
JSSLEngineResult_Status = interface(JObject)
['{12863C46-4F5A-41B9-9B00-D0AEA6382809}']
end;
TJSSLEngineResult_Status = class(TJavaGenericImport<JSSLEngineResult_StatusClass, JSSLEngineResult_Status>)
end;
implementation
end.
|
unit unt_recommend_upload;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, unt_command;
procedure DoUpload(AApkFile: string; AIconFile: string; AUnixName: string; AMode: integer; AAccount: string; APassword: string);
implementation
procedure DoUploadFiles(AApkFile: string; AIconFile: string; AAccount: string; APassword: string);
var
path: string;
cmd: string;
ret: TStringList;
begin
path := ExtractFilePath(ParamStr(0));
cmd := path + 'upload.sh ';
cmd := cmd + AAccount + ' ' + APassword + ' ' + AApkFile + ' package';
ret := ExecuteCommandF(cmd, path);
WriteLn('upload apk: ' + ret.Text);
cmd := path + 'upload.sh ';
cmd := cmd + AAccount + ' ' + APassword + ' ' + AIconFile + ' icon';
ret := ExecuteCommandF(cmd, path);
WriteLn('upload icon: ' + ret.Text);
end;
procedure DoAdd(AApkFile: string; AIconFile: string; AUnixName: string; APackageName: string; ALabelName: string; AAccount: string; APassword: string);
var
path: string;
cmd: string;
ret: TStringList;
begin
path := ExtractFilePath(ParamStr(0));
DoUploadFiles(AApkFile, AIconFile, AAccount, APassword);
cmd := 'http://rarnu.7thgen.info/root_tools/admin/upload.php?';
cmd := cmd + 'name=' + ALabelName;
cmd := cmd + '&package_name=' + APackageName;
cmd := cmd + '&unix_name=' + AUnixName;
cmd := cmd + '&icon=' + ExtractFileName(AIconFile);
cmd := cmd + '&apk=' + ExtractFileName(AApkFile);
cmd := cmd + '&mode=0';
ret := ExecuteCommandF('curl ' + cmd, path);
WriteLn('query: ' + ret.Text);
end;
procedure DoUpdate(AApkFile: string; AIconFile: string; APackageName: string; ALabelName: string; AAccount: string; APassword: string);
var
path: string;
cmd: string;
ret: TStringList;
begin
path := ExtractFilePath(ParamStr(0));
DoUploadFiles(AApkFile, AIconFile, AAccount, APassword);
cmd := 'http://rarnu.7thgen.info/root_tools/admin/upload.php?';
cmd := cmd + 'name=' + ALabelName;
cmd := cmd + '&package_name=' + APackageName;
cmd := cmd + '&icon=' + ExtractFileName(AIconFile);
cmd := cmd + '&apk=' + ExtractFileName(AApkFile);
cmd := cmd + '&mode=1';
ret := ExecuteCommandF('curl ' + cmd, path);
WriteLn('query: ' + ret.Text);
end;
function extractPackageName(AStr: string): string;
begin
AStr := StringReplace(AStr, 'package: name=', '', [rfIgnoreCase, rfReplaceAll]);
AStr := StringReplace(AStr, '''', '', [rfReplaceAll, rfIgnoreCase]);
AStr := Copy(AStr, 1, Pos(' ', AStr) - 1);
Result := AStr;
end;
function extractLabelName(AStr: string): string;
begin
AStr := StringReplace(AStr, 'application-label:', '', [rfIgnoreCase, rfReplaceAll]);
AStr := StringReplace(AStr, '''', '', [rfIgnoreCase, rfReplaceAll]);
AStr := Trim(AStr);
Result := AStr;
end;
function extractLabelNameCn(AStr: string): string;
begin
AStr := StringReplace(AStr, 'application-label-zh_CN:', '', [rfIgnoreCase, rfReplaceAll]);
AStr := StringReplace(AStr, '''', '', [rfIgnoreCase, rfReplaceAll]);
AStr := Trim(AStr);
Result := AStr;
end;
procedure DoUpload(AApkFile: string; AIconFile: string; AUnixName: string; AMode: integer; AAccount: string; APassword: string);
var
apkInfo: TStringList;
path: string;
packageName: string = '';
labelName: string = '';
labelNameCn: string = '';
labelNameFinal: string;
newIconFile: string;
newApkFile: string;
i: integer;
begin
path := ExtractFilePath(ParamStr(0));
apkInfo := ExecuteCommandF('aapt d badging ' + AApkFile, path);
for i := 0 to apkInfo.Count - 1 do
begin
if (pos('package: name=', apkInfo[i]) > 0) and (packageName = '') then
begin
packageName := extractPackageName(apkInfo[i]);
end;
if (pos('application-label-zh_CN:', apkInfo[i]) > 0) and (labelNameCn = '') then
begin
labelNameCn := extractLabelNameCn(apkInfo[i]);
end;
if (pos('application-label:', apkInfo[i]) > 0) and (labelName = '') then
begin
labelName := extractLabelName(apkInfo[i]);
end;
end;
WriteLn(packageName);
newApkFile := ExtractFilePath(AApkFile) + packageName + '.apk';
RenameFile(AApkFile, newApkFile);
AApkFile := newApkFile;
newIconFile := ExtractFilePath(AIconFile) + packageName + '.png';
RenameFile(AIconFile, newIconFile);
AIconFile := newIconFile;
labelNameFinal := labelName;
if labelNameCn <> '' then
begin
labelNameFinal := labelNameCn;
end;
if (AMode = 0) then
begin
DoAdd(AApkFile, AIconFile, AUnixName, packageName, labelNameFinal, AAccount, APassword);
end
else if (AMode = 1) then
begin
DoUpdate(AApkFile, AIconFile, packageName, labelNameFinal, AAccount, APassword);
end;
end;
end.
|
unit ibSHTableStatisticClasses;
interface
uses
Classes, SysUtils,
SHDesignIntf, ibSHDriverIntf;
type
TTableStatistic = class(TSHComponent, IibSHDRVTableStatistics)
private
FTableName: string;
FIdxReads: Integer;
FSeqReads: Integer;
FUpdates: Integer;
FInserts: Integer;
FDeletes: Integer;
FBackout: Integer;
FExpunge: Integer;
FPurge: Integer;
protected
{IibSHDRVTableStatistic}
function GetTableName: string;
function GetIdxReads: Integer;
function GetSeqReads: Integer;
function GetUpdates: Integer;
function GetInserts: Integer;
function GetDeletes: Integer;
function GetBackout: Integer;
function GetExpunge: Integer;
function GetPurge: Integer;
public
constructor Create(AOwner: TComponent); override;
constructor CreateAsClone(AOwner: TComponent; ATableStatistic: TTableStatistic);
procedure CopyFrom(ATableStatistic: TTableStatistic);
procedure SetAllNull;
function IsNull: Boolean;
function IsGarbageNull: Boolean;
function IsFullyNull: Boolean;
property TableName: string read FTableName write FTableName;
property IdxReads: Integer read FIdxReads write FIdxReads;
property SeqReads: Integer read FSeqReads write FSeqReads;
property Updates: Integer read FUpdates write FUpdates;
property Inserts: Integer read FInserts write FInserts;
property Deletes: Integer read FDeletes write FDeletes;
property Backout: Integer read FBackout write FBackout;
property Expunge: Integer read FExpunge write FExpunge;
property Purge: Integer read FPurge write FPurge;
end;
TTablesStatisticList = class(TStringList)
private
// FLastUsedRelationID: Integer;
// FLastUsedIndex: Integer;
FMaxDeltaValue: Integer;
FMaxGarbageValue: Integer;
function GetStatistics(Index: Integer): TTableStatistic;
function GetStatisticByRelationID(Index: Integer): TTableStatistic;
protected
function CompareStrings(const S1, S2: string): Integer; override;
procedure CloneItem(const S: string; AObject: TTableStatistic);
public
constructor Create;
destructor Destroy; override;
function Add(const S: string): Integer; override;
procedure Delete(Index: Integer); override;
procedure Clear; override;
procedure SetAllNull;
procedure ClearNulls;
function ForceTableStatistic(RelationID: string): TTableStatistic;
procedure AssignClonedItems(ATablesStatisticList: TTablesStatisticList);
procedure SortByPerformance;
procedure SortByGarbageCollected;
procedure Sort; override;
function IsGarbageNull: Boolean;
property Statistics[Index: Integer]: TTableStatistic read GetStatistics;
property StatisticByRelationID[Index: Integer]: TTableStatistic read GetStatisticByRelationID;
property MaxDeltaValue: Integer read FMaxDeltaValue write FMaxDeltaValue;
property MaxGarbageValue: Integer read FMaxGarbageValue write FMaxGarbageValue;
end;
implementation
{ TTableStatistic }
function TTableStatistic.GetTableName: string;
begin
Result := FTableName;
end;
function TTableStatistic.GetIdxReads: Integer;
begin
Result := FIdxReads;
end;
function TTableStatistic.GetSeqReads: Integer;
begin
Result :=FSeqReads;
end;
function TTableStatistic.GetUpdates: Integer;
begin
Result := FUpdates;
end;
function TTableStatistic.GetInserts: Integer;
begin
Result := FInserts;
end;
function TTableStatistic.GetDeletes: Integer;
begin
Result := FDeletes;
end;
function TTableStatistic.GetBackout: Integer;
begin
Result := FBackout;
end;
function TTableStatistic.GetExpunge: Integer;
begin
Result := FExpunge;
end;
function TTableStatistic.GetPurge: Integer;
begin
Result := FPurge;
end;
procedure TTableStatistic.CopyFrom(ATableStatistic: TTableStatistic);
begin
FSeqReads := ATableStatistic.SeqReads;
FIdxReads := ATableStatistic.IdxReads;
FInserts := ATableStatistic.Inserts;
FDeletes := ATableStatistic.Deletes;
FTableName := ATableStatistic.TableName;
FBackout := ATableStatistic.Backout;
FExpunge := ATableStatistic.Expunge;
FPurge := ATableStatistic.Purge;
end;
constructor TTableStatistic.Create(AOwner: TComponent);
begin
inherited;
SetAllNull;
FTableName := '';
end;
constructor TTableStatistic.CreateAsClone(AOwner: TComponent; ATableStatistic: TTableStatistic);
begin
inherited Create(AOwner);
FSeqReads := ATableStatistic.SeqReads;
FIdxReads := ATableStatistic.IdxReads;
FUpdates := ATableStatistic.Updates;
FInserts := ATableStatistic.Inserts;
FDeletes := ATableStatistic.Deletes;
FTableName := ATableStatistic.TableName;
FBackout := ATableStatistic.Backout;
FExpunge := ATableStatistic.Expunge;
FPurge := ATableStatistic.Purge;
end;
function TTableStatistic.IsFullyNull: Boolean;
begin
Result := IsGarbageNull and IsNull;
end;
function TTableStatistic.IsGarbageNull: Boolean;
begin
Result := ((FExpunge = 0) and
(FBackout = 0) and
(FPurge = 0))
end;
function TTableStatistic.IsNull: Boolean;
begin
Result := ((FSeqReads = 0) and
(FIdxReads = 0) and
(FInserts = 0) and
(FDeletes = 0) and
(FUpdates = 0))
end;
procedure TTableStatistic.SetAllNull;
begin
FSeqReads := 0;
FIdxReads := 0;
FInserts := 0;
FDeletes := 0;
FUpdates := 0;
FBackout := 0;
FExpunge := 0;
FPurge := 0;
end;
{ TTablesStatisticList }
function TTablesStatisticList.Add(const S: string): Integer;
begin
Result := AddObject(S, TTableStatistic.Create(nil));
end;
procedure TTablesStatisticList.AssignClonedItems(
ATablesStatisticList: TTablesStatisticList);
var
I: Integer;
begin
Clear;
for I := 0 to ATablesStatisticList.Count -1 do
CloneItem(ATablesStatisticList[I], ATablesStatisticList.Statistics[I]);
FMaxDeltaValue := ATablesStatisticList.MaxDeltaValue;
FMaxGarbageValue := ATablesStatisticList.MaxGarbageValue;
end;
procedure TTablesStatisticList.Clear;
var
I: Integer;
begin
for I := 0 to Count - 1 do
Statistics[I].Free;
inherited Clear;
end;
procedure TTablesStatisticList.ClearNulls;
var
I: Integer;
begin
for I := (Count - 1) downto 0 do
if Statistics[I].IsFullyNull then
Delete(I);
end;
procedure TTablesStatisticList.CloneItem(const S: string;
AObject: TTableStatistic);
var
vTableStatistic: TTableStatistic;
begin
vTableStatistic := TTableStatistic.CreateAsClone(nil, AObject);
AddObject(S, vTableStatistic);
end;
function TTablesStatisticList.CompareStrings(const S1,
S2: string): Integer;
begin
Result := inherited CompareStrings(S1, S2);
end;
constructor TTablesStatisticList.Create;
begin
inherited Create;
// FLastUsedRelationID := -1;
// FLastUsedIndex := -1;
FMaxDeltaValue := 0;
FMaxGarbageValue := 0;
end;
procedure TTablesStatisticList.Delete(Index: Integer);
begin
TTableStatistic(Objects[Index]).Free;
inherited Delete(Index);
end;
destructor TTablesStatisticList.Destroy;
var
I: Integer;
begin
for I := 0 to Count - 1 do
Statistics[I].Free;
inherited Destroy;
end;
function TTablesStatisticList.ForceTableStatistic(
RelationID: string): TTableStatistic;
begin
Result := StatisticByRelationID[StrToInt(RelationID)];
if not Assigned(Result) then
Result := Statistics[Add(RelationID)];
end;
function TTablesStatisticList.GetStatisticByRelationID(
Index: Integer): TTableStatistic;
var
I: Integer;
begin
// if Index <> FLastUsedRelationID then
// begin
// FLastUsedRelationID := Index;
// FLastUsedIndex := IndexOf(IntToStr(FLastUsedRelationID));
// end;
// if FLastUsedIndex <> -1 then
// Result := Statistics[FLastUsedIndex]
// else
// Result := nil;
I := IndexOf(IntToStr(Index));
if I <> -1 then
Result := Statistics[I]
else
Result := nil;
end;
function TTablesStatisticList.GetStatistics(
Index: Integer): TTableStatistic;
begin
if ((Index > -1) and (Index < Count)) then
Result := TTableStatistic(Objects[Index])
else
Result := nil;
end;
function TTablesStatisticList.IsGarbageNull: Boolean;
var
I: Integer;
begin
Result := True;
for I := 0 to Count - 1 do
begin
Result := Statistics[I].IsGarbageNull;
if Result then Exit;
end;
end;
procedure TTablesStatisticList.SetAllNull;
var
I: Integer;
begin
for I := 0 to Count - 1 do
Statistics[I].SetAllNull;
end;
function TablesStatisticListCompareStrings(List: TStringList; Index1, Index2: Integer): Integer;
begin
with TTablesStatisticList(List) do
Result := CompareStrings(Statistics[Index1].TableName,
Statistics[Index2].TableName);
end;
procedure TTablesStatisticList.Sort;
begin
CustomSort(TablesStatisticListCompareStrings);
end;
function IntSortByGarbageCollected(List: TStringList; Index1, Index2: Integer): Integer;
var
Val1, Val2: Integer;
begin
with TTablesStatisticList(List).Statistics[Index1] do
Val1 := Backout + Expunge + Purge;
with TTablesStatisticList(List).Statistics[Index2] do
Val2 := Backout + Expunge + Purge;
if Val1 < Val2 then
Result := 1
else
if Val1 > Val2 then
Result := -1
else
begin
if TTablesStatisticList(List).Statistics[Index1].TableName <
TTablesStatisticList(List).Statistics[Index2].TableName then
Result := -1
else
if TTablesStatisticList(List).Statistics[Index1].TableName >
TTablesStatisticList(List).Statistics[Index2].TableName then
Result := 1
else
Result := 0;
end;
end;
procedure TTablesStatisticList.SortByGarbageCollected;
begin
CustomSort(IntSortByGarbageCollected);
end;
function IntSortByStatistic(List: TStringList; Index1, Index2: Integer): Integer;
var
Val1, Val2: Integer;
begin
with TTablesStatisticList(List).Statistics[Index1] do
Val1 := IdxReads + SeqReads + Inserts + Updates + Deletes;
with TTablesStatisticList(List).Statistics[Index2] do
Val2 := IdxReads + SeqReads + Inserts + Updates + Deletes;
if Val1 < Val2 then
Result := 1
else
if Val1 > Val2 then
Result := -1
else
begin
if TTablesStatisticList(List).Statistics[Index1].TableName <
TTablesStatisticList(List).Statistics[Index2].TableName then
Result := -1
else
if TTablesStatisticList(List).Statistics[Index1].TableName >
TTablesStatisticList(List).Statistics[Index2].TableName then
Result := 1
else
Result := 0;
end;
end;
procedure TTablesStatisticList.SortByPerformance;
begin
CustomSort(IntSortByStatistic);
end;
end.
|
unit ibSHDMLExporterActions;
interface
uses
SysUtils, Classes, Menus,
SHDesignIntf, ibSHDesignIntf;
type
TibSHDMLExporterPaletteAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDMLExporterFormAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDMLExporterToolbarAction_ = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDMLExporterEditorAction = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHDMLExporterToolbarAction_Run = class(TibSHDMLExporterToolbarAction_)
end;
TibSHDMLExporterToolbarAction_Pause = class(TibSHDMLExporterToolbarAction_)
end;
TibSHDMLExporterToolbarAction_Region = class(TibSHDMLExporterToolbarAction_)
end;
TibSHDMLExporterToolbarAction_Refresh = class(TibSHDMLExporterToolbarAction_)
end;
TibSHDMLExporterToolbarAction_SaveAs = class(TibSHDMLExporterToolbarAction_)
end;
TibSHDMLExporterToolbarAction_CheckAll = class(TibSHDMLExporterToolbarAction_)
end;
TibSHDMLExporterToolbarAction_UnCheckAll = class(TibSHDMLExporterToolbarAction_)
end;
TibSHDMLExporterToolbarAction_MoveDown = class(TibSHDMLExporterToolbarAction_)
end;
TibSHDMLExporterToolbarAction_MoveUp = class(TibSHDMLExporterToolbarAction_)
end;
TibSHDMLExporterEditorAction_ExportIntoScript = class(TibSHDMLExporterEditorAction)
end;
implementation
uses
ibSHConsts,
ibSHDMLExporterFrm;
{ TibSHDMLExporterPaletteAction }
constructor TibSHDMLExporterPaletteAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallPalette;
Category := Format('%s', ['Tools']);
Caption := Format('%s', ['DML Exporter']);
ShortCut := TextToShortCut('Shift+Ctrl+D');
end;
function TibSHDMLExporterPaletteAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(IibSHBranch, AClassIID) or IsEqualGUID(IfbSHBranch, AClassIID);
end;
procedure TibSHDMLExporterPaletteAction.EventExecute(Sender: TObject);
begin
Designer.CreateComponent(Designer.CurrentDatabase.InstanceIID, IibSHDMLExporter, EmptyStr);
end;
procedure TibSHDMLExporterPaletteAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDMLExporterPaletteAction.EventUpdate(Sender: TObject);
begin
Enabled := Assigned(Designer.CurrentDatabase) and
(Designer.CurrentDatabase as ISHRegistration).Connected and
SupportComponent(Designer.CurrentDatabase.BranchIID);
end;
{ TibSHDMLExporterFormAction }
constructor TibSHDMLExporterFormAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallForm;
Caption := SCallTargetScript;
SHRegisterComponentForm(IibSHDMLExporter, Caption, TibSHDMLExporterForm);
end;
function TibSHDMLExporterFormAction.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDMLExporter);
end;
procedure TibSHDMLExporterFormAction.EventExecute(Sender: TObject);
begin
Designer.ChangeNotification(Designer.CurrentComponent, Caption, opInsert);
end;
procedure TibSHDMLExporterFormAction.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDMLExporterFormAction.EventUpdate(Sender: TObject);
begin
FDefault := Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, Caption);
end;
{ TibSHDMLExporterToolbarAction_ }
constructor TibSHDMLExporterToolbarAction_.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallToolbar;
Caption := '-';
if Self is TibSHDMLExporterToolbarAction_Run then Tag := 1;
if Self is TibSHDMLExporterToolbarAction_Pause then Tag := 2;
if Self is TibSHDMLExporterToolbarAction_Region then Tag := 3;
if Self is TibSHDMLExporterToolbarAction_Refresh then Tag := 4;
if Self is TibSHDMLExporterToolbarAction_SaveAs then Tag := 5;
if Self is TibSHDMLExporterToolbarAction_CheckAll then Tag := 6;
if Self is TibSHDMLExporterToolbarAction_UnCheckAll then Tag := 7;
if Self is TibSHDMLExporterToolbarAction_MoveDown then Tag := 8;
if Self is TibSHDMLExporterToolbarAction_MoveUp then Tag := 9;
case Tag of
1:
begin
Caption := Format('%s', ['Run']);
ShortCut := TextToShortCut('Ctrl+Enter');
SecondaryShortCuts.Add('F9');
end;
2:
begin
Caption := Format('%s', ['Stop']);
ShortCut := TextToShortCut('Ctrl+BkSp');
end;
3: Caption := Format('%s', ['Editor']);
4:
begin
Caption := Format('%s', ['Refresh']);
ShortCut := TextToShortCut('F5');
end;
5:
begin
Caption := Format('%s', ['Save As']);
ShortCut := TextToShortCut('Ctrl+S');
end;
6: Caption := Format('%s', ['Check All']);
7: Caption := Format('%s', ['UnCheck All']);
8:
begin
Caption := Format('%s', ['Move Down']);
ShortCut := TextToShortCut('Alt+Down');
end;
9:
begin
Caption := Format('%s', ['Move Up']);
ShortCut := TextToShortCut('Alt+Up');
end;
end;
if Tag <> 0 then Hint := Caption;
AutoCheck := Tag = 3; // Editor
end;
function TibSHDMLExporterToolbarAction_.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHDMLExporter);
end;
procedure TibSHDMLExporterToolbarAction_.EventExecute(Sender: TObject);
begin
if Supports(Designer.CurrentComponentForm, ISHRunCommands) and
Supports(Designer.CurrentComponentForm, ISHFileCommands) and
Supports(Designer.CurrentComponentForm, IibSHDMLExporterForm) then
case Tag of
// Run
1: (Designer.CurrentComponentForm as ISHRunCommands).Run;
// Pause
2: (Designer.CurrentComponentForm as ISHRunCommands).Pause;
// Editor
3: (Designer.CurrentComponentForm as ISHRunCommands).ShowHideRegion(Checked);
// Refresh
4: (Designer.CurrentComponentForm as ISHRunCommands).Refresh;
// Save As
5: (Designer.CurrentComponentForm as ISHFileCommands).SaveAs;
6: (Designer.CurrentComponentForm as IibSHDMLExporterForm).CheckAll;
7: (Designer.CurrentComponentForm as IibSHDMLExporterForm).UnCheckAll;
8: (Designer.CurrentComponentForm as IibSHDMLExporterForm).MoveDown;
9: (Designer.CurrentComponentForm as IibSHDMLExporterForm).MoveUp;
end;
end;
procedure TibSHDMLExporterToolbarAction_.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHDMLExporterToolbarAction_.EventUpdate(Sender: TObject);
begin
if Assigned(Designer.CurrentComponentForm) and
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallTargetScript) then
begin
Visible := True;
case Tag of
// Separator
0: ;
// Run
1: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun;
// Pause
2: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanPause;
// Editor
3:;
// Refresh
4: Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRefresh;
// Save As
5: Enabled := (Designer.CurrentComponentForm as ISHFileCommands).CanSaveAs;
6, 7: Enabled := True;
8: Enabled := (Designer.CurrentComponentForm as IibSHDMLExporterForm).CanMoveDown;
9: Enabled := (Designer.CurrentComponentForm as IibSHDMLExporterForm).CanMoveUp;
end;
end else
Visible := False;
end;
{ TibSHDMLExporterEditorAction }
constructor TibSHDMLExporterEditorAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallEditor;
if Self is TibSHDMLExporterEditorAction_ExportIntoScript then Tag := 1;
case Tag of
0: Caption := '-'; // separator
1: Caption := SExportIntoScript;
end;
end;
function TibSHDMLExporterEditorAction.SupportComponent(
const AClassIID: TGUID): Boolean;
begin
case Tag of
1: Result := IsEqualGUID(AClassIID, IibSHTable) or
IsEqualGUID(AClassIID, IibSHSQLEditor);
else
Result := False;
end;
end;
procedure TibSHDMLExporterEditorAction.EventExecute(Sender: TObject);
var
vDMLExporterFactory: IibSHDMLExporterFactory;
vData: IibSHData;
vInstanceIID: TGUID;
vCaption: string;
begin
if Assigned(Designer.CurrentComponentForm) then
case Tag of
1:
begin
if Supports(Designer.CurrentComponent, IibSHData, vData) and
Supports(Designer.GetDemon(IibSHDMLExporterFactory), IibSHDMLExporterFactory, vDMLExporterFactory) then
begin
vInstanceIID := Designer.CurrentComponent.InstanceIID;
with vDMLExporterFactory do
begin
if vData.Dataset.Active then
begin
Mode := DMLExporterModes[1];
Data := vData;
vCaption := Designer.CreateComponent(Designer.CurrentComponent.OwnerIID, IibSHDMLExporter, EmptyStr).Caption;
Designer.JumpTo(vInstanceIID, IibSHDMLExporter, vCaption);
Mode := EmptyStr;
Data := nil;
end
else
begin
//Только таблица
Mode := DMLExporterModes[0];
TablesForDumping.Clear;
TablesForDumping.Add(Designer.CurrentComponent.Caption);
vCaption := Designer.CreateComponent(Designer.CurrentComponent.OwnerIID, IibSHDMLExporter, EmptyStr).Caption;
Designer.JumpTo(vInstanceIID, IibSHDMLExporter, vCaption);
Mode := EmptyStr;
TablesForDumping.Clear;
end;
vDMLExporterFactory := nil;
end;
end;
end;
end;
end;
procedure TibSHDMLExporterEditorAction.EventHint(var HintStr: String;
var CanShow: Boolean);
begin
end;
procedure TibSHDMLExporterEditorAction.EventUpdate(Sender: TObject);
var
vData: IibSHData;
begin
if Assigned(Designer.CurrentComponentForm) then
case Tag of
1:
begin
Enabled := Assigned(Designer.CurrentComponent) and
(Supports(Designer.CurrentComponent, IibSHTable) or
(
Supports(Designer.CurrentComponent, IibSHSQLEditor) and
Supports(Designer.CurrentComponent, IibSHData, vData) and vData.Dataset.Active)
);
Visible := Supports(Designer.CurrentComponent, IibSHSQLEditor) or
(Supports(Designer.CurrentComponent, ISHDBComponent) and
((Designer.CurrentComponent as ISHDBComponent).State <> csCreate)
);
end;
else
Enabled := False;
end;
end;
end.
|
unit fRptBox;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ORFn, ComCtrls, ExtCtrls, fFrame, fBase508Form,
VA508AccessibilityManager, uReports, Vcl.Menus;
type
TfrmReportBox = class(TfrmBase508Form)
lblFontTest: TLabel;
memReport: TRichEdit;
pnlButton: TPanel;
cmdPrint: TButton;
dlgPrintReport: TPrintDialog;
cmdClose: TButton;
pmnu: TPopupMenu;
mnuCopy: TMenuItem;
procedure memReportClick(Sender: TObject);
procedure cmdPrintClick(Sender: TObject);
procedure cmdCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormResize(Sender: TObject);
procedure mnuCopyClick(Sender: TObject);
end;
procedure ReportBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean);
function ModelessReportBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean): TfrmReportBox;
procedure PrintStrings(Form: TForm; StringText: TStrings; const Title, Trailer: string);
implementation
uses
uCore, rCore, rReports, Printers, rMisc;
{$R *.DFM}
function CreateReportBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean): TfrmReportBox;
var
i, AWidth, MinWidth, MaxWidth, AHeight: Integer;
Rect: TRect;
BtnArray: array of TButton;
BtnRight: array of integer;
BtnLeft: array of integer;
//cmdCloseRightMargin: integer;
//cmdPrintRightMargin: integer;
j, k: integer;
begin
Result := TfrmReportBox.Create(Application);
try
with Result do
begin
k := 0;
MinWidth := 0;
with pnlButton do for j := 0 to ControlCount - 1 do
if Controls[j] is TButton then
begin
SetLength(BtnArray, k+1);
SetLength(BtnRight, k+1);
BtnArray[j] := TButton(Controls[j]);
BtnRight[j] := ResizeWidth(Font, MainFont, BtnArray[j].Width - BtnArray[j].Width - BtnArray[j].Left);
k := k + 1;
end;
//cmdCloseRightMargin := ResizeWidth(Font, MainFont, pnlButton.Width - cmdClose.Width - cmdClose.Left);
//cmdPrintRightMargin := ResizeWidth(Font, MainFont, pnlButton.Width - cmdPrint.Width - cmdPrint.Left);
MaxWidth := 350;
for i := 0 to ReportText.Count - 1 do
begin
AWidth := lblFontTest.Canvas.TextWidth(ReportText[i]);
if AWidth > MaxWidth then MaxWidth := AWidth;
end;
cmdPrint.Visible := AllowPrint;
MaxWidth := MaxWidth + GetSystemMetrics(SM_CXVSCROLL);
AHeight := (ReportText.Count * (lblFontTest.Height + 2)) + pnlbutton.Height;
AHeight := HigherOf(AHeight, 250);
if AHeight > (Screen.Height - 80) then AHeight := Screen.Height - 80;
if MaxWidth > Screen.Width then MaxWidth := Screen.Width;
ClientWidth := MaxWidth;
ClientHeight := AHeight;
ResizeAnchoredFormToFont(Result);
memReport.Align := alClient; //CQ6661
//CQ6889 - force Print & Close buttons to bottom right of form regardless of selected font size
cmdClose.Left := (pnlButton.Left+pnlButton.Width)-cmdClose.Width;
cmdPrint.Left := (cmdClose.Left-cmdPrint.Width)-1;
//end CQ6889
SetLength(BtnLeft, k);
for j := 0 to k - 1 do
begin
BtnLeft[j] := pnlButton.Width - BtnArray[j].Width - BtnRight[j];
MinWidth := MinWidth + BtnArray[j].Width;
end;
Width := width + (GetSystemMetrics(SM_CXVSCROLL) *2);
Constraints.MinWidth := MinWidth + (MinWidth div 2) + (GetSystemMetrics(SM_CXVSCROLL) *2);
if (mainFontSize = 8) then Constraints.MinHeight := 285
else if (mainFontSize = 10) then Constraints.MinHeight := 325
else if (mainFontSize = 12) then Constraints.MinHeight := 390
else if mainFontSize = 14 then Constraints.MinHeight := 460
else Constraints.MinHeight := 575;
QuickCopy(ReportText, memReport);
for i := 1 to Length(ReportTitle) do if ReportTitle[i] = #9 then ReportTitle[i] := ' ';
Caption := ReportTitle;
memReport.SelStart := 0;
Rect := BoundsRect;
ForceInsideWorkArea(Rect);
BoundsRect := Rect;
end;
except
KillObj(@Result);
raise;
end;
end;
procedure ReportBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean);
var
frmReportBox: TfrmReportBox;
begin
Screen.Cursor := crHourglass; //wat cq 18425 added hourglass and disabled mnuFileOpen
fFrame.frmFrame.mnuFileOpen.Enabled := False;
frmReportBox := CreateReportBox(ReportText, ReportTitle, AllowPrint);
try
frmReportBox.ShowModal;
finally
frmReportBox.Release;
Screen.Cursor := crDefault;
fFrame.frmFrame.mnuFileOpen.Enabled := True;
end;
end;
function ModelessReportBox(ReportText: TStrings; ReportTitle: string; AllowPrint: boolean): TfrmReportBox;
begin
Result := CreateReportBox(ReportText, ReportTitle, AllowPrint);
Result.FormStyle := fsStayOnTop;
Result.Show;
end;
procedure PrintStrings(Form: TForm; StringText: TStrings; const Title, Trailer: string);
var
AHeader: TStringList;
memPrintReport: TRichEdit;
MaxLines, LastLine, ThisPage, i: integer;
ErrMsg: string;
// RemoteSiteID: string; //for Remote site printing
// RemoteQuery: string; //for Remote site printing
dlgPrintReport: TPrintDialog;
BM: TBitmap;
const
PAGE_BREAK = '**PAGE BREAK**';
begin
// RemoteSiteID := '';
// RemoteQuery := '';
BM := TBitmap.Create;
try
dlgPrintReport := TPrintDialog.Create(Form);
try
frmFrame.CCOWBusy := True;
if dlgPrintReport.Execute then
begin
AHeader := TStringList.Create;
CreatePatientHeader(AHeader, Title);
memPrintReport := CreateReportTextComponent(Form);
try
MaxLines := 60 - AHeader.Count;
LastLine := 0;
ThisPage := 0;
BM.Canvas.Font := memPrintReport.Font;
with memPrintReport do
begin
repeat
with Lines do
begin
for i := 0 to MaxLines do begin
if BM.Canvas.TextWidth(StringText[LastLine + i]) > Width then begin
MaxLines := Maxlines - (BM.Canvas.TextWidth(StringText[LastLine + i]) div Width);
end;
if i >= MaxLines then begin
break;
end;
if i < StringText.Count then
// Add(IntToStr(i) + ') ' + StringText[LastLine + i])
Add(StringText[LastLine + i])
else
Break;
end;
LastLine := LastLine + i;
Add(' ');
Add(' ');
Add(StringOfChar('-', 74));
if LastLine >= StringText.Count - 1 then
Add(Trailer)
else
begin
ThisPage := ThisPage + 1;
Add('Page ' + IntToStr(ThisPage));
Add(PAGE_BREAK);
MaxLines := 60 - AHeader.Count;
end;
end;
until LastLine >= StringText.Count - 1;
PrintWindowsReport(memPrintReport, PAGE_BREAK, Title, ErrMsg, True);
end;
finally
memPrintReport.Free;
AHeader.Free;
end;
end;
finally
frmFrame.CCOWBusy := False;
dlgPrintReport.Free;
end;
finally
BM.free;
end;
end;
procedure TfrmReportBox.memReportClick(Sender: TObject);
begin
//Close;
end;
procedure TfrmReportBox.mnuCopyClick(Sender: TObject);
begin
inherited;
memReport.CopyToClipboard;
end;
procedure TfrmReportBox.cmdPrintClick(Sender: TObject);
begin
PrintStrings(Self, memReport.Lines, Self.Caption, 'End of report');
memReport.Invalidate;
end;
procedure TfrmReportBox.cmdCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfrmReportBox.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if(not (fsModal in FormState)) then
Action := caFree;
end;
procedure TfrmReportBox.FormResize(Sender: TObject);
begin
inherited;
self.memReport.Refresh;
end;
end.
|
(* ========================================== *)
(* -- SOS UNIT 27.05.17 -- *)
(* ========================================== *)
UNIT SOSU;
INTERFACE
CONST
MAX = 10;
TYPE
(* ========================================== *)
(* -- SOS Class -- *)
(* ========================================== *)
SOSPtr = ^SOS;
SOS = OBJECT
PRIVATE
n: INTEGER;
a: ARRAY[1..MAX] OF STRING;
PUBLIC
CONSTRUCTOR Init;
DESTRUCTOR Done; VIRTUAL;
FUNCTION Empty: BOOLEAN; VIRTUAL;
FUNCTION Contains(val: STRING): BOOLEAN; VIRTUAL;
FUNCTION ContainsPos(val: STRING): INTEGER; VIRTUAL;
FUNCTION Cardinality: INTEGER; VIRTUAL;
PROCEDURE Add(val: STRING); VIRTUAL;
PROCEDURE Remove(val: STRING); VIRTUAL;
FUNCTION LookupPos(val: INTEGER): STRING; VIRTUAL;
PROCEDURE Print; VIRTUAL;
(* set operations *)
FUNCTION Union(b: SOSPtr): SOSPtr; VIRTUAL;
FUNCTION Intersection(b: SOSPtr): SOSPtr; VIRTUAL;
FUNCTION Difference(b: SOSPtr): SOSPtr; VIRTUAL;
FUNCTION Subset(b: SOSPtr): BOOLEAN; VIRTUAL;
END;
(* ========================================== *)
(* -- Sack Class -- *)
(* ========================================== *)
SackPtr = ^Sack;
Sack = OBJECT(SOS)
PRIVATE
counters: ARRAY[1..MAX] OF INTEGER;
PUBLIC
CONSTRUCTOR Init;
DESTRUCTOR Done;
FUNCTION Cardinality: INTEGER;
PROCEDURE Add(val: STRING);
PROCEDURE AddAmount(val: STRING; amount: INTEGER);
PROCEDURE Remove(val: STRING);
PROCEDURE LookupPos(val: INTEGER; VAR s: STRING; VAR amount: INTEGER);
PROCEDURE Print;
(* set operations *)
FUNCTION Union(b: SackPtr): SackPtr;
FUNCTION Difference(b: SackPtr): SackPtr;
FUNCTION Intersection(b: SackPtr): SackPtr;
END;
IMPLEMENTATION
(* ========================================== *)
(* -- Implementation of SOS -- *)
(* ========================================== *)
CONSTRUCTOR SOS.Init;
BEGIN
n := 0;
END;
DESTRUCTOR SOS.Done;
BEGIN
(* do nothing *)
END;
FUNCTION SOS.Empty: BOOLEAN;
BEGIN
Empty := n = 0;
END;
(* Returns TRUE if found*)
FUNCTION SOS.Contains(val: STRING): BOOLEAN;
VAR i: INTEGER;
BEGIN
Contains := FALSE;
FOR i := 1 TO n DO BEGIN
IF a[i] = val THEN BEGIN
Contains := TRUE;
break;
END;
END;
END;
(* returns pos of the found element *)
FUNCTION SOS.ContainsPos(val: STRING): INTEGER;
VAR i: INTEGER;
BEGIN
ContainsPos := 0;
FOR i := 1 TO n DO BEGIN
IF a[i] = val THEN BEGIN
ContainsPos := i;
break;
END;
END;
END;
FUNCTION SOS.Cardinality: INTEGER;
BEGIN
Cardinality := n;
END;
(* Adds to value to array, returns error msg if array is full *)
PROCEDURE SOS.Add(val: STRING);
BEGIN
IF n < MAX THEN BEGIN
n := n + 1;
a[n] := val;
END ELSE WriteLn('== ERROR ADD: Full! ==', #13#10);
END;
PROCEDURE SOS.Remove(val: STRING);
VAR i,j: INTEGER;
BEGIN
IF NOT Empty THEN BEGIN
FOR i := 0 TO n DO BEGIN
IF a[i] = val THEN BEGIN
FOR j := i TO n - 1 DO BEGIN
a[j] := a[j + 1];
END;
n := n - 1;
break;
END;
END;
END ELSE WriteLn('Empty');
END;
(* Returns value from array at position * *)
FUNCTION SOS.LookupPos(val: INTEGER): STRING;
BEGIN
LookupPos := '';
IF NOT Empty THEN BEGIN
IF (val <= n) AND (val >= 1) THEN LookupPos := a[val];
END;
END;
(* Print all elements to the console *)
PROCEDURE SOS.Print;
VAR
i: INTEGER;
BEGIN
FOR i := 1 TO n DO Write(a[i], ' ');
WriteLn;
END;
(* Union of two sos objects
Returns SOSPtr *)
FUNCTION SOS.Union(b: SOSPtr): SOSPtr;
VAR
i: INTEGER;
s: SOSPtr;
BEGIN
New(s,Init);
IF (Cardinality + b^.Cardinality) <= MAX THEN BEGIN
FOR i := 1 TO n DO BEGIN
s^.Add(a[i]);
END;
FOR i := 1 TO b^.Cardinality DO BEGIN
s^.Add(b^.LookupPos(i));
END;
END
ELSE BEGIN
WriteLn('== Union Error ==');
WriteLn(' Too big', #13#10' Cardinality m1: ', Cardinality, ' m2: '
, b^.Cardinality, '- MAX size: ', MAX);
END;
Union := s;
END;
(* Intersection of two sos objects
Returns SOSPtr *)
FUNCTION SOS.Intersection(b: SOSPtr): SOSPtr;
VAR
i: INTEGER;
s: SOSPtr;
BEGIN
New(s, Init);
FOR i := 1 TO n DO BEGIN
IF b^.Contains(a[i]) THEN s^.Add(a[i]);
END;
IF s^.Cardinality = 0 THEN BEGIN
WriteLn('== Intersection ==');
WriteLn(' Nothing in common');
END;
Intersection := s;
END;
(* Difference of two sos objects
Returns SOSPtr *)
FUNCTION SOS.Difference(b: SOSPtr): SOSPtr;
VAR
i: INTEGER;
s: SOSPtr;
BEGIN
New(s, Init);
FOR i := 1 TO n DO BEGIN
IF NOT b^.Contains(a[i]) THEN s^.Add(a[i]);
END;
IF s^.Cardinality = 0 THEN BEGIN
WriteLn('== Difference ==');
WriteLn(' No difference');
END;
Difference := s;
END;
(* True if calling object is subset of b *)
FUNCTION SOS.Subset(b: SOSPtr): BOOLEAN;
VAR
i: INTEGER;
BEGIN
Subset := TRUE;
FOR i := 1 TO n DO BEGIN
IF NOT b^.Contains(a[i]) THEN BEGIN
Subset := FALSE;
break;
END;
END;
END;
(* ========================================== *)
(* -- Implementation of Sack -- *)
(* ========================================== *)
CONSTRUCTOR Sack.Init;
BEGIN
INHERITED Init;
END;
DESTRUCTOR Sack.Done;
BEGIN
INHERITED Done;
END;
PROCEDURE Sack.Remove(val: STRING);
VAR i,j: INTEGER;
BEGIN
i := ContainsPos(val);
INHERITED Remove(val);
IF i > 0 THEN BEGIN
FOR j := i TO n - 1 DO BEGIN
counters[j] := counters[j + 1];
END;
END;
END;
(* Adds to value to array, returns error msg if array is full *)
PROCEDURE Sack.Add(val: STRING);
VAR
pos: INTEGER;
BEGIN
pos := ContainsPos(val);
IF pos = 0 THEN BEGIN
INHERITED Add(val);
counters[n] := counters[n] + 1;
END
ELSE counters[pos] := counters[pos] + 1;
END;
(* Adds to value to array, returns error msg if array is full *)
PROCEDURE Sack.AddAmount(val: STRING; amount: INTEGER);
VAR
pos: INTEGER;
BEGIN
pos := ContainsPos(val);
IF pos = 0 THEN BEGIN
INHERITED Add(val);
counters[n] := counters[n] + amount;
END
ELSE counters[pos] := counters[pos] + amount;
END;
FUNCTION Sack.Cardinality: INTEGER;
VAR
i: INTEGER;
BEGIN
Cardinality := 0;
FOR i := 1 TO n DO BEGIN
Cardinality := Cardinality + counters[i];
END;
END;
(* Returns value from array at position * *)
PROCEDURE Sack.LookupPos(val: INTEGER; VAR s: STRING; VAR amount:
INTEGER);
BEGIN
IF NOT Empty THEN BEGIN
IF (val <= n) AND (val >= 1) THEN BEGIN
s := a[val];
amount := counters[val];
END;
END;
END;
PROCEDURE Sack.Print;
VAR
i: INTEGER;
BEGIN
FOR i := 1 TO n DO Write(a[i], ' x', counters[i], ' ');
WriteLn;
END;
(* Union of two sos objects
Returns SackPtr *)
FUNCTION Sack.Union(b: SackPtr): SackPtr;
VAR
i, amount: INTEGER;
s: SackPtr;
str: STRING;
BEGIN
New(s,Init);
str := '';
amount := 0;
IF (Cardinality + b^.Cardinality) <= MAX THEN BEGIN
FOR i := 1 TO n DO BEGIN
s^.AddAmount(a[i], counters[i]);
END;
FOR i := 1 TO b^.Cardinality DO BEGIN
b^.LookupPos(i, str, amount);
s^.AddAmount(str, amount);
END;
END
ELSE BEGIN
WriteLn('== Union Error ==');
WriteLn(' Too big', #13#10' Cardinality m1: ', Cardinality, ' m2: '
, b^.Cardinality, '- MAX size: ', MAX);
END;
Union := s;
END;
(* Difference of two sos objects
Returns SackPtr *)
FUNCTION Sack.Difference(b: SackPtr):SackPtr;
VAR
i: INTEGER;
s: SackPtr;
BEGIN
New(s, Init);
FOR i := 1 TO n DO BEGIN
IF NOT b^.Contains(a[i]) THEN s^.AddAmount(a[i], counters[i]);
END;
IF s^.Cardinality = 0 THEN BEGIN
WriteLn('== Difference ==');
WriteLn(' No difference');
END;
Difference := s;
END;
(* Intersection of two sos objects
Returns SOSPtr *)
FUNCTION Sack.Intersection(b: SackPtr): SackPtr;
VAR
i: INTEGER;
s: SackPtr;
BEGIN
New(s, Init);
FOR i := 1 TO n DO BEGIN
IF b^.Contains(a[i]) THEN s^.Add(a[i]);
END;
IF s^.Cardinality = 0 THEN BEGIN
WriteLn('== Intersection ==');
WriteLn(' Nothing in common');
END;
Intersection := s;
END;
END. |
//
// Generated by JavaToPas v1.5 20171018 - 170630
////////////////////////////////////////////////////////////////////////////////
unit android.text.BidiFormatter_Builder;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.text.TextDirectionHeuristic,
android.text.BidiFormatter;
type
JBidiFormatter_Builder = interface;
JBidiFormatter_BuilderClass = interface(JObjectClass)
['{86EAEE56-91E5-4EE5-B518-A9A12F398483}']
function build : JBidiFormatter; cdecl; // ()Landroid/text/BidiFormatter; A: $1
function init : JBidiFormatter_Builder; cdecl; overload; // ()V A: $1
function init(locale : JLocale) : JBidiFormatter_Builder; cdecl; overload; // (Ljava/util/Locale;)V A: $1
function init(rtlContext : boolean) : JBidiFormatter_Builder; cdecl; overload;// (Z)V A: $1
function setTextDirectionHeuristic(heuristic : JTextDirectionHeuristic) : JBidiFormatter_Builder; cdecl;// (Landroid/text/TextDirectionHeuristic;)Landroid/text/BidiFormatter$Builder; A: $1
function stereoReset(stereoReset : boolean) : JBidiFormatter_Builder; cdecl;// (Z)Landroid/text/BidiFormatter$Builder; A: $1
end;
[JavaSignature('android/text/BidiFormatter_Builder')]
JBidiFormatter_Builder = interface(JObject)
['{2F925204-888F-43F7-AC46-27511CF27190}']
function build : JBidiFormatter; cdecl; // ()Landroid/text/BidiFormatter; A: $1
function setTextDirectionHeuristic(heuristic : JTextDirectionHeuristic) : JBidiFormatter_Builder; cdecl;// (Landroid/text/TextDirectionHeuristic;)Landroid/text/BidiFormatter$Builder; A: $1
function stereoReset(stereoReset : boolean) : JBidiFormatter_Builder; cdecl;// (Z)Landroid/text/BidiFormatter$Builder; A: $1
end;
TJBidiFormatter_Builder = class(TJavaGenericImport<JBidiFormatter_BuilderClass, JBidiFormatter_Builder>)
end;
implementation
end.
|
unit OpcodeLib;
{******************************************************************************}
{ Copyright (c) 2013-2015 Dmitry Mozulyov }
{ }
{ Permission is hereby granted, free of charge, to any person obtaining a copy }
{ of this software and associated documentation files (the "Software"), to deal}
{ in the Software without restriction, including without limitation the rights }
{ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell }
{ copies of the Software, and to permit persons to whom the Software is }
{ furnished to do so, subject to the following conditions: }
{ }
{ The above copyright notice and this permission notice shall be included in }
{ all copies or substantial portions of the Software. }
{ }
{ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR }
{ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, }
{ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE }
{ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER }
{ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,}
{ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN }
{ THE SOFTWARE. }
{ }
{ email: softforyou@inbox.ru }
{ skype: dimandevil }
{ repository: https://github.com/d-mozulyov/OpcodeLib }
{******************************************************************************}
// дифайн, который добавляет к обычной функциональности
// возможность компилировать в режимах ассемблера и гибрида
// как следствие - увеличивается размер приложения (а так библиотека компактная)
{$define OPCODE_MODES}
// этот дифайн позволяет сделать различные проверки диапазонов
// с другой стороны это увеличивает размер приложения
{$define OPCODE_TEST}
// compiler directives
{$ifdef FPC}
{$mode Delphi}
{$asmmode Intel}
{$define INLINESUPPORT}
{$ifdef CPU386}
{$define CPUX86}
{$endif}
{$ifdef CPUX86_64}
{$define CPUX64}
{$endif}
{$else}
{$if CompilerVersion >= 24}
{$LEGACYIFEND ON}
{$ifend}
{$if CompilerVersion >= 15}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ifend}
{$if (CompilerVersion < 23)}
{$define CPUX86}
{$ifend}
{$if (CompilerVersion >= 17)}
{$define INLINESUPPORT}
{$ifend}
{$if CompilerVersion >= 21}
{$WEAKLINKRTTI ON}
{$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])}
{$ifend}
{$if (not Defined(NEXTGEN)) and (CompilerVersion >= 20)}
{$define INTERNALCODEPAGE}
{$ifend}
{$endif}
{$U-}{$V+}{$B-}{$X+}{$T+}{$P+}{$H+}{$J-}{$Z1}{$A4}
{$O+}{$R-}{$I-}{$Q-}{$W-}
{$if Defined(CPUX86) or Defined(CPUX64)}
{$define CPUINTEL}
{$ifend}
{$if Defined(CPUX64) or Defined(CPUARM64)}
{$define LARGEINT}
{$else}
{$define SMALLINT}
{$ifend}
{$ifdef KOL_MCK}
{$define KOL}
{$endif}
interface
uses {$ifdef MSWINDOWS}Windows,{$endif}
Types, SysUtils;
{$if (not Defined(CPUX86)) and (not Defined(CPUX64))} (*and (not Defined(CPUARM))*)
{$define PUREPASCAL}
{$else}
{$undef PUREPASCAL}
{$ifend}
{$if (not Defined(PUREPASCAL)) and (not Defined(OPCODE_MODES))}
{$define OPCODE_FAST}
{$else}
{$undef OPCODE_FAST}
{$ifend}
{$if Defined(OPCODE_FAST) and (not Defined(OPCODE_TEST))}
{$define OPCODE_FASTEST}
{$else}
{$undef OPCODE_FASTEST}
{$ifend}
const
// reg_x86
al = 0;
cl = 1;
dl = 2;
bl = 3;
ah = 4;
ch = 5;
dh = 6;
bh = 7;
ax = 8;
cx = 9;
dx = 10;
bx = 11;
sp = 12;
bp = 13;
si = 14;
di = 15;
eax = 16;
ecx = 17;
edx = 18;
ebx = 19;
esp = 20;
ebp = 21;
esi = 22;
edi = 23;
// reg_x64_d_new
r8d = 24;
r9d = 25;
r10d = 26;
r11d = 27;
r12d = 28;
r13d = 29;
r14d = 30;
r15d = 31;
// reg_x64_w_new
r8w = 32;
r9w = 33;
r10w = 34;
r11w = 35;
r12w = 36;
r13w = 37;
r14w = 38;
r15w = 39;
// reg_x64_q_new
rax = 40;
rcx = 41;
rdx = 42;
rbx = 43;
rsp = 44;
rbp = 45;
rsi = 46;
rdi = 47;
r8 = 48;
r9 = 49;
r10 = 50;
r11 = 51;
r12 = 52;
r13 = 53;
r14 = 54;
r15 = 55;
// reg_x64_b_new
r8b = 56;
r9b = 57;
r10b = 58;
r11b = 59;
r12b = 60;
r13b = 61;
r14b = 62;
r15b = 63;
// reg_x64_b_new_warnign
spl = 64;
bpl = 65;
sil = 66;
dil = 67;
const
RET_OFF = high(word);
type
// список доступных регистров общего назначения
// для архитектуры x86
reg_x86 = al..edi;
// частные случаи
reg_x86_dwords = eax..edi;
reg_x86_wd = ax..edi;
reg_x86_bytes = al..bh;
// для адресов
reg_x86_addr = reg_x86_dwords;
// список доступных регистров общего назначения
// для архитектуры x64
reg_x64 = al..dil;
// частные случаи
reg_x64_dwords = eax..r15d;
reg_x64_wd = ax..r15w;
reg_x64_wdq = ax..r15;
reg_x64_wq = ax..r15;
reg_x64_dq = eax..r15;
reg_x64_qwords = rax..r15;
reg_x64_bytes = al..dil;
// для адресов
reg_x64_addr = reg_x64_qwords;
// список доступных регистров общего назначения
// для архитектуры ARM
reg_ARM = 0..0{todo};
// тип прыжка x86-64
intel_cc = (_o,_no,_b,_c,_nae,_ae,_nb,_nc,_e,_z,_nz,_ne,_be,_na,_a,_nbe,_s,_ns,
_p,_pe,_po,_np,_l,_nge,_ge,_nl,_le,_ng,_g,_nle);
// "масштаб" в адресе
intel_scale = (xNone, x1, x2, x4, x8, x1_plus, x2_plus, x4_plus, x8_plus);
// тип повторений для
intel_rep = (REP_SINGLE, REP, REPE, REPZ, REPNE, REPNZ);
// размерность операнда (памяти)
size_ptr = (byte_ptr, word_ptr, dword_ptr, qword_ptr, tbyte_ptr, dqword_ptr);
// индексы
index8 = 0..7;
index16 = 0..15;
// тип прыжка ARM
arm_cc = {bl=call,bal=jmp}(eq, ne, cs, hs{=cs}, cc, lo{=cc},
mi, pl, vs, vc, hi, ls, ge, lt, gt, le);
const
ptr_1 = byte_ptr;
ptr_2 = word_ptr;
ptr_4 = dword_ptr;
ptr_8 = qword_ptr;
ptr_10 = tbyte_ptr;
ptr_16 = dqword_ptr;
type
// эксепшн
EOpcodeLib = class(Exception);
// состояние кучи
// необходимо для сохранения и восстановления состояния
TOpcodeHeapState = record
PoolSize: integer;
Pool: pointer;
Current: pointer;
Margin: integer;
end;
// собственное "хранилище памяти"
// (для оптимизации по скорости)
TOpcodeHeap = class(TObject)
private
FState: TOpcodeHeapState;
procedure NewPool();
protected
function Alloc(const Size: integer): pointer;
{$ifdef OPCODE_MODES}
function Format(const FmtStr: ShortString; const Args: array of const): PShortString;
{$endif}
public
constructor Create;
destructor Destroy; override;
procedure Clear();
procedure SaveState(var HeapState: TOpcodeHeapState);
procedure RestoreState(const HeapState: TOpcodeHeapState);
end;
// типы-"указатели"
TOpcodeGlobal = class;
TOpcodeVariable = class;
TOpcodeStorage = class;
TOpcodeStorage_Intel = class;
TOpcodeStorage_x86 = class;
TOpcodeStorage_x64 = class;
TOpcodeStorage_ARM = class;
TOpcodeStorage_VM = class;
POpcodeConst = ^TOpcodeConst;
POpcodeAddress = ^TOpcodeAddress;
TOpcodeProc = class;
TOpcodeProc_Intel = class;
TOpcodeProc_x86 = class;
TOpcodeProc_x64 = class;
TOpcodeProc_ARM = class;
TOpcodeProc_VM = class;
POpcodeCmd = ^TOpcodeCmd;
POpcodeBlock = ^TOpcodeBlock;
POpcodeBinaryBlock = ^TOpcodeBinaryBlock;
POpcodeSwitchBlock = ^TOpcodeSwitchBlock;
POpcodeBlock_Intel = ^TOpcodeBlock_Intel;
POpcodeBlock_x86 = ^TOpcodeBlock_x86;
POpcodeBlock_x64 = ^TOpcodeBlock_x64;
POpcodeBlock_ARM = ^TOpcodeBlock_ARM;
POpcodeBlock_VM = ^TOpcodeBlock_VM;
TOpcodeProcClass = class of TOpcodeProc;
// вид информации на выходе
// реальный код(опкоды), ассемблер или "гибрид"
{$ifdef OPCODE_MODES}
TOpcodeMode = (omBinary, omAssembler, omHybrid);
{$endif}
// режим константы
const_kind = ((* используемые везде *)
ckValue, // реальное число
ckPValue, // указатель на число, которое будет рассчитано перед Fixup()
(* только в ассемблере и гибриде *)
// в качестве числовой константы может выступать не только константа
// в привычном понимании типа RET_OFF или FIXUPED_BLOCK_SIZE
// в качестве числовой константы может выступать целое выражение типа "TOpcodeAddress_offset + TOpcodeConst.FKind"
// отличие Condition от OffsetedCondition заключается в том
// что второе обязано начинаться с глобального объекта (переменной)
// и к нему может быть применена директива "offset ..."
{$ifdef OPCODE_MODES}
ckCondition, // RET_OFF или FIXUPED_BLOCK_SIZE или TOpcodeAddress_offset + TOpcodeConst.FKind
ckOffsetedCondition, // то же самое, но выражение начинается с имени глобальной переменной или функции
{$endif}
(* межфункциональный блок доступен только в бинарном варианте *)
(* блок внутри функции доступен так же из ассемблера и гибрида *)
ckBlock,
(* только в бинарном варианте *)
ckVariable
{
важно!
в конечном счёте в адрес/константа функцию
поступает либо конечное integer-число(Value),
либо [Offsetted]Condition (для текстов)
в случае "штрафного круга" Block-варианта для бинарного режима
перепрописываются данные. если локальный - в VariableOffset пишется 0
если глобальный, то в Variable пишется функция, а в VariableOffset - Reference
}
);
// базовая структура для констант
// наследники занимают ровно столько же байт
TOpcodeConst = object
protected
// 1 байт
FKind: const_kind;
// 8 байт на x86 и 12 байт на x64
F: packed record
case const_kind of
ckValue: ( case Boolean of
false: (Value: Integer);
true: (Value64: Int64);
);
ckPValue: ( case Boolean of
false: (pValue: PInteger);
true: (pValue64: PInt64);
);
{$ifdef OPCODE_MODES}
ckCondition: (Condition: PAnsiChar);
ckOffsetedCondition: (OffsetedCondition: PAnsiChar);
{$endif}
ckBlock: (Block: POpcodeBlock);
ckVariable: (Variable: TOpcodeVariable; VariableOffset: Integer);
end;
public
property Kind: const_kind read FKind write FKind;
{ckBlock}
property Block: POpcodeBlock read F.Block write F.Block;
{ckVariable}
property Variable: TOpcodeVariable read F.Variable write F.Variable;
property VariableOffset: Integer read F.VariableOffset write F.VariableOffset;
{$ifdef OPCODE_MODES}
{ckCondition}
property Condition: PAnsiChar read F.Condition write F.Condition;
{ckOffsetedCondition}
property OffsetedCondition: PAnsiChar read F.OffsetedCondition write F.OffsetedCondition;
{$endif}
end;
// константа, хранящая в себе 32 битное число
const_32 = object(TOpcodeConst)
public
{ckValue} property Value: Integer read F.Value write F.Value;
{ckPValue} property pValue: PInteger read F.pValue write F.pValue;
end;
// константа, хранящая в себе 64 битное число
// (применяется только для команды mov на платформе x64)
const_64 = object(TOpcodeConst)
public
{ckValue} property Value: Int64 read F.Value64 write F.Value64;
{ckPValue} property pValue: PInt64 read F.pValue64 write F.pValue64;
end;
// базовая структура для адреса
// наследники занимают столько же байт
TOpcodeAddress = object
protected
F: packed record
case Integer of
0: (Bytes: array[0..2] of byte);
1: (Reg: packed record
case Integer of
0: (v: byte);
1: (x86: reg_x86_addr);
2: (x64: reg_x64_addr);
// ?
end;
Plus: packed record
case Integer of
0: (v: byte);
1: (x86: reg_x86_addr);
2: (x64: reg_x64_addr);
// ?
end;
Scale: packed record
case Integer of
0: (intel: intel_scale);
// ?
end;
);
end;
function IntelInspect(const params: integer{x64}): integer;
public
offset: const_32;
end;
// адрес для архитектуры x86
address_x86 = object(TOpcodeAddress)
public
property reg: reg_x86_addr read F.Reg.x86 write F.Reg.x86;
property scale: intel_scale read F.Scale.intel write F.Scale.intel;
property plus: reg_x86_addr read F.Plus.x86 write F.Plus.x86;
{property offset: const_32 read/write}
end;
// адрес для архитектуры x64
address_x64 = object(TOpcodeAddress)
public
property reg: reg_x64_addr read F.Reg.x64 write F.Reg.x64;
property scale: intel_scale read F.Scale.intel write F.Scale.intel;
property plus: reg_x64_addr read F.Plus.x64 write F.Plus.x64;
{property offset: const_32 read/write}
end;
// адрес для архитектуры ARM
address_ARM = object(TOpcodeAddress)
private
// todo
end;
// тип команды
//
TOpcodeCmdMode = ( // бинарная последовательность байт
cmBinary,
// команда, представленная в виде ассемблера(текста), в т.ч. и для гибрида
{$ifdef OPCODE_MODES}
cmText,
{$endif}
// бинарность/текстовость + ret(n)(0), leave(1), jmp reg(2), jmp mem(3)
// ценность такой команды заключается в том, что этой командой заканчивается блок!
// кроме того при оптимизации прыжков, этой командой можно заменить безусловный прыжок
cmLeave,
// команда, содержащая сопроводительную информацию(переменную или блок) к другой команде: cmBinary/cmText/cmLeave
// в 2х младших битах Param содержится расположение (и количество) присоединённых данных. В остальных 6 битах кодируется TOpcodeCmdMode
// Size (Hybrid min/max) тоже копируется (для простоты подсчётов)
cmJoined,
(* наверное в будущем надо будет придумать тип команд для условных прыжков в память для ARM к примеру *)
// команда перенаправления в блок: jcc/jmp/call
// call объединён с прыжками в первую очередь из-за рассчёта offset и из-за логики внешних блоков
// с другой стороны команду jmp тоже стоит учитывать особо
cmJumpBlock,
// массив блоков, который нужен для операции case(switch)
// в ассемблерном и гибридном виде всегда текст
// Size хранит бинарный размер всего блока. Стало быть количество блоков равно Size div 4
cmSwitchBlock,
// специальное (временное) представление команды, когда
// в качестве аргумента(ов) числовой константы задаётся указатель
// в этом случае в момент фиксации получается истинное представление команды (UnpointerCmd)
cmPointer
);
// базовая структура для всех команд
TOpcodeCmd = object
private
FNext: POpcodeCmd;
F: packed record
case Integer of
0: (Value: integer);
{$ifdef OPCODE_MODES}
1: (HybridSize_MinMax: word);
2: (HybridSize_Min: byte; HybridSize_Max: byte);
{$endif}
3: (
// размер, который занимает бинарная команда в памяти
// для гибридных здесь располагаются min/max
// для ассемблера вообще не учитывается
// в случае switch block всегда количество * 4(размер одной записи)
Size: word;
case Boolean of
false: (
// в этом флаге указывается вариант используемой команды
// в основном команды бинарные (для бинарного режима) и текстовые (для ассемблера)
//
// но есть особые типы команд.
// прыжки, call, ret, ...
Mode: TOpcodeCmdMode;
// каждая команда может использовать данный байт на своё усмотрение
//
// на бинарные и текстовые команды байт не используют.
// для cmLeave закодирован вариант leave + бинарность/текстовость
// для cmJumpBlock указывается вариат прыжка: cc_ex
// в случае cmJoined в 2х битах кодируется расположение (и количество) присоединённых данных. В остальных 6 битах кодируется TOpcodeCmdMode основной команды: cmBinary/cmText/cmLeave
// ну а в cmPointer закодирован boolean-ы (0/1), будет ли команда после распаковки: jmp mem (cmLeave) / cmJoined
case Integer of
0: (Param: byte);
1: (cc_ex: shortint); {только для cmJumpBlock}
);
true:
(
ModeParam: word
);
);
end;
// нейтрализовать фейковую константу, заменить нулём, вернуть смещение
function NeutralizeFakeConst(const data_offs: integer=0): integer;
public
property Next: POpcodeCmd read FNext;
property Mode: TOpcodeCmdMode read F.Mode;
property Param: byte read F.Param;
property Size: word read F.Size;
{$ifdef OPCODE_MODES}
property HybridSize_MinMax: word read F.HybridSize_MinMax;
property HybridSize_Min: byte read F.HybridSize_Min;
property HybridSize_Max: byte read F.HybridSize_Max;
{$endif}
end;
// универсальные типы
// которые используются для команд с адресами и константами
{$ifdef OPCODE_MODES}
opused_const_32 = const_32;
{$else}
opused_const_32 = integer;
{$endif}
{$ifdef OPCODE_MODES}
opused_const_64 = const_64;
{$else}
opused_const_64 = int64;
{$endif}
opused_callback_0{const} = function (const params: integer; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd of object{TOpcodeBlock};
opused_callback_1{addr} = function (const params: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd of object{TOpcodeBlock};
opused_callback_2{addr,const} = function (const params: integer; const addr: TOpcodeAddress; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd of object{TOpcodeBlock};
opused_callback_3{const x64. только для mov} = function (const params: integer; const v_const: opused_const_64{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd of object{TOpcodeBlock};
// хранилище последовательности команд
TOpcodeBlock = object
protected
// список команд в блоке (в обратном порядке)
// при сборе команд в группу порядок восстанавливается
CmdList: POpcodeCmd;
function AddCmd(const CmdMode: TOpcodeCmdMode; const SizeCorrection: integer=0): POpcodeCmd;
{$ifdef OPCODE_MODES}
function AddCmdText(const Str: PShortString): POpcodeCmd{POpcodeCmdText}; overload;
function AddCmdText(const FmtStr: ShortString; const Args: array of const): POpcodeCmd{POpcodeCmdText}; overload;
{$endif}
// присоединить к команде сопроводительную информацию
// по блоку(ам) и/или переменной(ым), которые при фиксации станут ячейками
// под ячейкой стоит понимать 4хбайтную (в x86 и x64) переменную в фиксированных бинарных данных
// которые могут меняться в зависимости от данной функции или других глобальных объектов
procedure JoinCmdCellData(const relative: boolean; const v_const: TOpcodeConst); overload;
procedure JoinCmdCellData(const mode: byte; const v_addr, v_const: TOpcodeConst); overload;
// особый вид команд, используемый для констант
// когда значение будет известно только на этапе фиксации
function AddCmdPointer(params: integer; pvalue: pointer; addr_kind: integer; callback, diffcmd: pointer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd{POpcodeCmdPointer};
// команды jcc(intel_cc), jmp(-1), call(-2)
// или аналоги например для платформы ARM
function cmd_jump_block(const cc_ex: shortint; const Block: POpcodeBlock): POpcodeCmd{POpcodeCmdJumpBlock};
// текстовые команды jcc(intel_cc), jmp(-1), call(-2) к глобальным функциям
// или аналоги например для платформы ARM
{$ifdef OPCODE_MODES}
function cmd_textjump_proc(const cc_ex: shortint; const ProcName: pansichar): POpcodeCmd{POpcodeCmdJumpBlock};
{$endif}
protected
P: record
case integer of
0: (Proc: TOpcodeProc);
1: (Proc_x86: TOpcodeProc_x86);
2: (Proc_x64: TOpcodeProc_x64);
3: (Proc_ARM: TOpcodeProc_ARM);
4: (Proc_VM: TOpcodeProc_VM);
end;
N: record
case integer of
0: (Next: POpcodeBlock);
1: (Next_x86: POpcodeBlock_x86);
2: (Next_x64: POpcodeBlock_x64);
3: (Next_ARM: POpcodeBlock_ARM);
4: (Next_VM: POpcodeBlock_VM);
end;
O: packed record
case Boolean of
false: (Value: integer);
true: (
Fixuped: word; // назначенный номер фиксированного блока в массиве при фиксации. По умолчанию NO_FIXUPED
Reference: word; // внешний номер-идентификатор, позволяющий ссылаться на него извне. По умолчанию NO_REFERENCE
);
end;
protected
// вставить блок между Self и Next
function AppendBlock(const ResultSize: integer): POpcodeBlock;
public
// массивы констант и switch-блоков
function AppendBinaryBlock(const Size: {word}integer): POpcodeBinaryBlock;
function AppendSwitchBlock(const Count: {хз byte}integer): POpcodeSwitchBlock;
// промаркировать блок как возможный для внешней адресации
// в текстовом виде можно использовать для того чтобы пометить конкретные блоки метками (для читабельности)
function MakeReference(): word;
end;
// блок бинарных данных
// может использоваться как массив чисел
TOpcodeBinaryBlock = object(TOpcodeBlock)
private
FSize: integer;
Cmd: TOpcodeCmd;
public
// данные
Data: record
case Integer of
0: (Bytes: array[word] of byte);
1: (Words: array[word] of word);
2: (Dwords: array[word] of dword);
3: (Ints64: array[word] of int64);
end;
public
// размер
property Size: integer read FSize;
end;
// блок указателей на блоки
// используется для реализации case(switch)
TOpcodeSwitchBlock = object(TOpcodeBlock)
private
FCount: integer;
Cmd: TOpcodeCmd;
public
// блоки
Blocks: array[word] of POpcodeBlock;
public
// количество
property Count: integer read FCount;
end;
// последовательность команд
// общий класс для платформы x32-64
TOpcodeBlock_Intel = object(TOpcodeBlock)
private
// самая важная в архитектуре Intel умная команда
// позволяет за раз:
// - выделить необходимое количество памяти для команды
// - присоединиться к прошлой бинарной команде
// - записать все префиксы
// - опкод команды (1 или 2 байт)
// - запись Advanced (это может быть константа или какие-то дополнительные данные)
//
// формат:
// 4 старших бита - набор префиксов
// 4 бита - значения REX
// 1 или 2 байта - опкод команды
// 1 младший байт - дополнительный размер. это может быть например константа или другие данные
function AddSmartBinaryCmd(Parameters, Advanced: integer): POpcodeCmd;
// вспомогательная функция для гибрида
// позволяет определять Min_Max по параметрам
{$ifdef OPCODE_MODES}
function HybridSize_MinMax(base_params, Parameters{итоговые значения для AddSmartBinaryCmd}: integer; addr: POpcodeAddress): integer{word};
{$endif}
private
// блок универсальных(сложных) функций, которые вызываются из PRE-функций
// может быть будут перенесены в TOpcodeBlock
procedure diffcmd_const32(params: integer; const v_const: const_32; callback: opused_callback_0{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
procedure diffcmd_addr(params: integer; const addr: TOpcodeAddress; callback: opused_callback_1{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
procedure diffcmd_addr_const(params: integer; const addr: TOpcodeAddress; const v_const: const_32; callback: opused_callback_2{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
procedure diffcmd_const64(params: integer; const v_const: const_64; callback: opused_callback_3{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
private
// одна команда
// например emms | ud2
function cmd_single(const opcode: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
// цепочечные команды (r)esi-(r)edi
// например movsb(/w/d/q) | cmpsb(/w/d/q),
function cmd_rep_bwdq(const reps: intel_rep{=REP_SINGLE}; opcode: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
// команда с одним параметром-константой
// пока известна только push
// PRE-реализация делается на месте
function cmd_const_value(const opcode: integer; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
// команда с одним параметром-регистром
// например inc al | push bx | bswap esp | jmp esi
function cmd_reg(const opcode_reg: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
// один параметр адрес (без размера - он подразумевается)
// например jmp [edx] | call [ebp+4] | fldcw [r12]
function cmd_addr_value(const opcode: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
procedure PRE_cmd_addr(const opcode: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
// два параметра: ptr, addr
// например dec byte ptr [ecx*4] | push dword ptr [esp]
function cmd_ptr_addr_value(const base_opcode_ptr: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
procedure PRE_cmd_ptr_addr(const opcode_ptr: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
// два параметра: reg, reg
// например mov esi, ebx | add bh, cl | test ax, dx
function cmd_reg_reg(const base_opcode_reg, base_v_reg: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
// два параметра: reg, const_32
// например cmp edx, 15 | and r8, $ff | test ebx, $0100
function cmd_reg_const_value(const base_opcode_reg: integer; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
procedure PRE_cmd_reg_const(const opcode_reg: integer; const v_const: const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
// два параметра: reg, const_32 | reg, cl
// только для сдвиговых команд rcl,rcr,rol,ror,sal,sar,shl,shr
function shift_reg_const_value(const opcode_reg: integer; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
procedure PRE_shift_reg_const(const opcode_reg: integer; const v_const: const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
// два параметра: reg, addr или addr, reg. Направление определяется по опкоду
// например add esi, [ebp-$14] | xchg [offset variable + ecx*2 + 6], dx
function cmd_reg_addr_value(const opcode_reg: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
procedure PRE_cmd_reg_addr(const opcode_reg: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
// три параметра: ptr, addr, const_32
// например cmp byte ptr [eax+ebx*2-12], 0 | sbb qword ptr [r12 + rdx], $17
// участвуют так же сдвиги: rcl,rcr,rol,ror,sal,sar,shl,shr
function cmd_ptr_addr_const_value(const opcode_ptr: integer; const addr: TOpcodeAddress; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
procedure PRE_cmd_ptr_addr_const(const opcode_ptr: integer; const addr: TOpcodeAddress; const v_const: const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
// три параметра: reg, reg, const_32/cl
// только команды shld | shrd | imul
function cmd_reg_reg_const_value(const base_reg1_opcode_reg2: integer; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
procedure PRE_cmd_reg_reg_const(const reg1_opcode_reg2: integer; const v_const: const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
// три параметра(shld,shrd): addr, reg, const_32/cl
// или для imul: reg, addr, const_32
function cmd_addr_reg_const_value(const base_opcode_reg: integer; const addr: TOpcodeAddress; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
procedure PRE_cmd_addr_reg_const(const opcode_reg: integer; const addr: TOpcodeAddress; const v_const: const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
// два параметра: reg, reg
// для movzx и movsx
function movszx_reg_reg(const opcode_reg: integer; v_reg: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
// три параметра: reg, ptr, addr
// для movzx и movsx
function movszx_reg_ptr_addr_value(const reg_opcode_ptr: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
procedure PRE_movszx_reg_ptr_addr(const reg_opcode_ptr: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
// команды setcc r8 | cmovcc reg_wd, reg_wd
function setcmov_cc_regs(const params: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
// команды setcc addr8 | cmovcc reg_wd, addr
function setcmov_cc_addr_value(const params: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
procedure PRE_setcmov_cc_addr(const params: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
// todo
public
(* removed:
loop/loope/loopne - потому что неэффективная команда с ограничением на диапазон (-128..+127)
*)
{todo перенести в x86 потому что в x64 их нет}
procedure aaa;
procedure aad;
procedure aam;
procedure aas;
procedure daa;
procedure das;
{-------------}
procedure hlt;
// int (int_0/int_3)
procedure invd;
procedure invlpg;
procedure iret;
procedure lahf;
// lar ?
// lds, les, lfs, lgs, lss ?
{$ifdef OPCODE_MODES}
procedure call(ProcName: pansichar);
procedure j(cc: intel_cc; ProcName: pansichar);
procedure jmp(ProcName: pansichar);
{$endif}
procedure leave;
// lgdt, lidt
// lldt
// lmsw
// lsl
// ltr
procedure pause;
// popa/popad
// popf/popfd
// pusha/pushad
// pushf/pushd
procedure push(const v_const: const_32);
// rdmsr
// rdpmc
// rdtsc
procedure ret(const count: word=0);
// rsm
// sahf
// sfrence
// sldt
// smsw
// stc
// std
// sti
// str
// sysenter
// sysexit
procedure ud2;
// verr/verw
procedure wait;
procedure fwait;
// wbinvd
// wrmsr
// xlat, xlatb (что насчёт x64?)
(* цепочечные команды *)
procedure cmpsb(reps: intel_rep=REP_SINGLE);
procedure cmpsw(reps: intel_rep=REP_SINGLE);
procedure cmpsd(reps: intel_rep=REP_SINGLE);
procedure insb(reps: intel_rep=REP_SINGLE);
procedure insw(reps: intel_rep=REP_SINGLE);
procedure insd(reps: intel_rep=REP_SINGLE);
procedure scasb(reps: intel_rep=REP_SINGLE);
procedure scasw(reps: intel_rep=REP_SINGLE);
procedure scasd(reps: intel_rep=REP_SINGLE);
procedure stosb(reps: intel_rep=REP_SINGLE);
procedure stosw(reps: intel_rep=REP_SINGLE);
procedure stosd(reps: intel_rep=REP_SINGLE);
procedure lodsb(reps: intel_rep=REP_SINGLE);
procedure lodsw(reps: intel_rep=REP_SINGLE);
procedure lodsd(reps: intel_rep=REP_SINGLE);
procedure movsb(reps: intel_rep=REP_SINGLE);
procedure movsw(reps: intel_rep=REP_SINGLE);
procedure movsd(reps: intel_rep=REP_SINGLE);
(* команды сопроцессора *)
{подумать на счёт адресации x64 !!!}
procedure f2xm1;
procedure fabs;
procedure fadd(d, s: index8); overload;
procedure fadd(ptr: size_ptr; const addr: address_x86); overload;
procedure faddp(st: index8=1);
procedure fiadd(ptr: size_ptr; const addr: address_x86);
procedure fchs;
procedure fclex;
procedure fnclex;
procedure fcmov(cc: intel_cc; st_dest: index8);
procedure fcom(st: index8=1); overload;
procedure fcom(ptr: size_ptr; const addr: address_x86); overload;
procedure fcomp(st: index8=1); overload;
procedure fcomp(ptr: size_ptr; const addr: address_x86); overload;
procedure fcompp;
procedure ficom(ptr: size_ptr; const addr: address_x86);
procedure ficomp(ptr: size_ptr; const addr: address_x86);
procedure fcomi(st: index8=1);
procedure fcomip(st: index8=1);
procedure fucomi(st: index8=1);
procedure fucomip(st: index8=1);
procedure fucom(st: index8=1); overload;
procedure fucom(ptr: size_ptr; const addr: address_x86); overload;
procedure fucomp(st: index8=1); overload;
procedure fucomp(ptr: size_ptr; const addr: address_x86); overload;
procedure fucompp;
procedure fsin;
procedure fcos;
procedure fsincos;
procedure fdecstp;
procedure fincstp;
procedure fdiv(d, s: index8); overload;
procedure fdiv(ptr: size_ptr; const addr: address_x86); overload;
procedure fdivp(st: index8=1);
procedure fidiv(ptr: size_ptr; const addr: address_x86);
procedure fdivr(d, s: index8); overload;
procedure fdivr(ptr: size_ptr; const addr: address_x86); overload;
procedure fdivrp(st: index8=1);
procedure fidivr(ptr: size_ptr; const addr: address_x86);
procedure ffree;
procedure fild(ptr: size_ptr; const addr: address_x86);
// finit/fninit
procedure fist(ptr: size_ptr; const addr: address_x86);
procedure fistp(ptr: size_ptr; const addr: address_x86);
procedure fld1;
procedure fldl2t;
procedure fldl2e;
procedure fldlg2;
procedure fldln2;
procedure fldpi;
procedure fldz;
procedure fld(st: index8=1); overload;
procedure fld(ptr: size_ptr; const addr: address_x86); overload;
procedure fmul(d, s: index8); overload;
procedure fmul(ptr: size_ptr; const addr: address_x86); overload;
procedure fmulp(st: index8=1);
procedure fimul(ptr: size_ptr; const addr: address_x86);
procedure fnop;
procedure fptan;
procedure fpatan;
procedure fprem;
procedure fprem1;
procedure frndint;
procedure frstor;
procedure fscale;
procedure fsqrt;
procedure fst(st: index8=1); overload;
procedure fst(ptr: size_ptr; const addr: address_x86); overload;
procedure fstp(st: index8=1); overload;
procedure fstp(ptr: size_ptr; const addr: address_x86); overload;
procedure fstsw_ax;
procedure fnstsw_ax;
procedure fsub(d, s: index8); overload;
procedure fsub(ptr: size_ptr; const addr: address_x86); overload;
procedure fsubp(st: index8=1);
procedure fisub(ptr: size_ptr; const addr: address_x86);
procedure fsubr(d, s: index8); overload;
procedure fsubr(ptr: size_ptr; const addr: address_x86); overload;
procedure fsubrp(st: index8=1);
procedure fisubr(ptr: size_ptr; const addr: address_x86);
procedure ftst;
procedure fxam;
procedure fxch(st: index8=1);
procedure fxtract;
procedure fyl2x;
procedure fyl2xp1;
(* todo MMX, SSE*)
end;
// последовательность команд
// архитектура x86
TOpcodeBlock_x86 = object(TOpcodeBlock_Intel)
public
property Proc: TOpcodeProc_x86 read P.Proc_x86;
property Next: POpcodeBlock_x86 read N.Next_x86 write N.Next_x86;
public
function AppendBlock(): POpcodeBlock_x86;
procedure adc(reg: reg_x86; v_reg: reg_x86); overload;
procedure adc(reg: reg_x86; const v_const: const_32); overload;
procedure adc(reg: reg_x86; const addr: address_x86); overload;
procedure adc(const addr: address_x86; v_reg: reg_x86); overload;
procedure adc(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure lock_adc(const addr: address_x86; v_reg: reg_x86); overload;
procedure lock_adc(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure add(reg: reg_x86; v_reg: reg_x86); overload;
procedure add(reg: reg_x86; const v_const: const_32); overload;
procedure add(reg: reg_x86; const addr: address_x86); overload;
procedure add(const addr: address_x86; v_reg: reg_x86); overload;
procedure add(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure lock_add(const addr: address_x86; v_reg: reg_x86); overload;
procedure lock_add(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure and_(reg: reg_x86; v_reg: reg_x86); overload;
procedure and_(reg: reg_x86; const v_const: const_32); overload;
procedure and_(reg: reg_x86; const addr: address_x86); overload;
procedure and_(const addr: address_x86; v_reg: reg_x86); overload;
procedure and_(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure lock_and(const addr: address_x86; v_reg: reg_x86); overload;
procedure lock_and(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure bswap(reg: reg_x86_dwords);
//procedure bsf(dest: reg_x86_wd; src: reg_x86_wd); overload;
//procedure bsf(dest: reg_x86_wd; const addr: address_x86); overload;
// bt
// btc
// btr
// bts
// *lock
procedure call(block: POpcodeBlock_x86); overload;
procedure call(blocks: POpcodeSwitchBlock; index: reg_x86_addr; offset: integer=0); overload;
procedure call(reg: reg_x86_addr); overload;
procedure call(const addr: address_x86); overload;
// cbw
// cwde
// cwd
// cdq
// clc
// cld
// cli
// clts
// cmc
// clflush ?
procedure cmov(cc: intel_cc; reg: reg_x86_wd; v_reg: reg_x86_wd); overload;
procedure cmov(cc: intel_cc; reg: reg_x86_wd; const addr: address_x86); overload;
procedure cmp(reg: reg_x86; v_reg: reg_x86); overload;
procedure cmp(reg: reg_x86; const v_const: const_32); overload;
procedure cmp(reg: reg_x86; const addr: address_x86); overload;
procedure cmp(const addr: address_x86; v_reg: reg_x86); overload;
procedure cmp(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
// cmpxchg
// cmpxchg8b
// cpuid
procedure dec(reg: reg_x86); overload;
procedure dec(ptr: size_ptr; const addr: address_x86); overload;
procedure lock_dec(ptr: size_ptr; const addr: address_x86);
procedure div_(reg: reg_x86); overload;
procedure div_(ptr: size_ptr; const addr: address_x86); overload;
// enter
procedure idiv(reg: reg_x86); overload;
procedure idiv(ptr: size_ptr; const addr: address_x86); overload;
procedure imul(reg: reg_x86); overload;
procedure imul(ptr: size_ptr; const addr: address_x86); overload;
procedure imul(reg: reg_x86_wd; v_reg: reg_x86_wd); overload;
procedure imul(reg: reg_x86_wd; const addr: address_x86); overload;
procedure imul(reg: reg_x86_wd; const v_const: const_32); overload;
procedure imul(reg1, reg2: reg_x86_wd; const v_const: const_32); overload;
procedure imul(reg: reg_x86_wd; const addr: address_x86; const v_const: const_32); overload;
// in
procedure inc(reg: reg_x86); overload;
procedure inc(ptr: size_ptr; const addr: address_x86); overload;
procedure lock_inc(ptr: size_ptr; const addr: address_x86);
procedure j(cc: intel_cc; block: POpcodeBlock_x86);
procedure jmp(block: POpcodeBlock_x86); overload;
procedure jmp(blocks: POpcodeSwitchBlock; index: reg_x86_addr; offset: integer=0); overload;
procedure jmp(reg: reg_x86_addr); overload;
procedure jmp(const addr: address_x86); overload;
procedure lea(reg: reg_x86_addr; const addr: address_x86);
procedure mov(reg: reg_x86; v_reg: reg_x86); overload;
procedure mov(reg: reg_x86; const v_const: const_32); overload;
procedure mov(reg: reg_x86; const addr: address_x86); overload;
procedure mov(const addr: address_x86; v_reg: reg_x86); overload;
procedure mov(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure movsx(reg: reg_x86; v_reg: reg_x86); overload;
procedure movsx(reg: reg_x86; ptr: size_ptr; const addr: address_x86); overload;
procedure movzx(reg: reg_x86; v_reg: reg_x86); overload;
procedure movzx(reg: reg_x86; ptr: size_ptr; const addr: address_x86); overload;
procedure mul(reg: reg_x86); overload;
procedure mul(ptr: size_ptr; const addr: address_x86); overload;
procedure neg(reg: reg_x86); overload;
procedure neg(ptr: size_ptr; const addr: address_x86); overload;
procedure lock_neg(ptr: size_ptr; const addr: address_x86);
// nop(count)
procedure not_(reg: reg_x86); overload;
procedure not_(ptr: size_ptr; const addr: address_x86); overload;
procedure lock_not(ptr: size_ptr; const addr: address_x86);
procedure or_(reg: reg_x86; v_reg: reg_x86); overload;
procedure or_(reg: reg_x86; const v_const: const_32); overload;
procedure or_(reg: reg_x86; const addr: address_x86); overload;
procedure or_(const addr: address_x86; v_reg: reg_x86); overload;
procedure or_(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure lock_or(const addr: address_x86; v_reg: reg_x86); overload;
procedure lock_or(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure pop(reg: reg_x86_wd); overload;
procedure pop(ptr: size_ptr; const addr: address_x86); overload;
// prefetch0/prefetch1/prefetch2/prefetchnta ?
procedure push(reg: reg_x86_wd); overload;
procedure push(ptr: size_ptr; const addr: address_x86); overload;
procedure rcl_cl(reg: reg_x86); overload;
procedure rcl(reg: reg_x86; const v_const: const_32); overload;
procedure rcl_cl(ptr: size_ptr; const addr: address_x86); overload;
procedure rcl(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure rcr_cl(reg: reg_x86); overload;
procedure rcr(reg: reg_x86; const v_const: const_32); overload;
procedure rcr_cl(ptr: size_ptr; const addr: address_x86); overload;
procedure rcr(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure rol_cl(reg: reg_x86); overload;
procedure rol(reg: reg_x86; const v_const: const_32); overload;
procedure rol_cl(ptr: size_ptr; const addr: address_x86); overload;
procedure rol(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure ror_cl(reg: reg_x86); overload;
procedure ror(reg: reg_x86; const v_const: const_32); overload;
procedure ror_cl(ptr: size_ptr; const addr: address_x86); overload;
procedure ror(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure sal_cl(reg: reg_x86); overload;
procedure sal(reg: reg_x86; const v_const: const_32); overload;
procedure sal_cl(ptr: size_ptr; const addr: address_x86); overload;
procedure sal(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure sar_cl(reg: reg_x86); overload;
procedure sar(reg: reg_x86; const v_const: const_32); overload;
procedure sar_cl(ptr: size_ptr; const addr: address_x86); overload;
procedure sar(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure sbb(reg: reg_x86; v_reg: reg_x86); overload;
procedure sbb(reg: reg_x86; const v_const: const_32); overload;
procedure sbb(reg: reg_x86; const addr: address_x86); overload;
procedure sbb(const addr: address_x86; v_reg: reg_x86); overload;
procedure sbb(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure lock_sbb(const addr: address_x86; v_reg: reg_x86); overload;
procedure lock_sbb(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure set_(cc: intel_cc; reg: reg_x86_bytes); overload;
procedure set_(cc: intel_cc; const addr: address_x86); overload;
procedure shl_cl(reg: reg_x86); overload;
procedure shl_(reg: reg_x86; const v_const: const_32); overload;
procedure shl_cl(ptr: size_ptr; const addr: address_x86); overload;
procedure shl_(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure shr_cl(reg: reg_x86); overload;
procedure shr_(reg: reg_x86; const v_const: const_32); overload;
procedure shr_cl(ptr: size_ptr; const addr: address_x86); overload;
procedure shr_(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure shld_cl(reg1, reg2: reg_x86); overload;
procedure shld(reg1, reg2: reg_x86; const v_const: const_32); overload;
procedure shld_cl(const addr: address_x86; reg2: reg_x86); overload;
procedure shld(const addr: address_x86; reg2: reg_x86; const v_const: const_32); overload;
procedure shrd_cl(reg1, reg2: reg_x86); overload;
procedure shrd(reg1, reg2: reg_x86; const v_const: const_32); overload;
procedure shrd_cl(const addr: address_x86; reg2: reg_x86); overload;
procedure shrd(const addr: address_x86; reg2: reg_x86; const v_const: const_32); overload;
procedure sub(reg: reg_x86; v_reg: reg_x86); overload;
procedure sub(reg: reg_x86; const v_const: const_32); overload;
procedure sub(reg: reg_x86; const addr: address_x86); overload;
procedure sub(const addr: address_x86; v_reg: reg_x86); overload;
procedure sub(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure lock_sub(const addr: address_x86; v_reg: reg_x86); overload;
procedure lock_sub(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure test(reg: reg_x86; v_reg: reg_x86); overload;
procedure test(reg: reg_x86; const v_const: const_32); overload;
procedure test(reg: reg_x86; const addr: address_x86); overload;
procedure test(const addr: address_x86; v_reg: reg_x86); overload;
procedure test(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure xadd(reg: reg_x86; v_reg: reg_x86); overload;
procedure xadd(const addr: address_x86; v_reg: reg_x86); overload;
procedure lock_xadd(const addr: address_x86; v_reg: reg_x86);
procedure xchg(reg: reg_x86; v_reg: reg_x86); overload;
procedure xchg(const addr: address_x86; v_reg: reg_x86); overload;
procedure lock_xchg(const addr: address_x86; v_reg: reg_x86);
procedure xor_(reg: reg_x86; v_reg: reg_x86); overload;
procedure xor_(reg: reg_x86; const v_const: const_32); overload;
procedure xor_(reg: reg_x86; const addr: address_x86); overload;
procedure xor_(const addr: address_x86; v_reg: reg_x86); overload;
procedure xor_(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
procedure lock_xor(const addr: address_x86; v_reg: reg_x86); overload;
procedure lock_xor(ptr: size_ptr; const addr: address_x86; const v_const: const_32); overload;
// FPU и память
procedure fbld(const addr: address_x86);
procedure fbstp(const addr: address_x86);
procedure fldcw(const addr: address_x86);
procedure fldenv(const addr: address_x86);
procedure fsave(const addr: address_x86);
procedure fnsave(const addr: address_x86);
procedure fstcw(const addr: address_x86);
procedure fnstcw(const addr: address_x86);
procedure fstenv(const addr: address_x86);
procedure fnstenv(const addr: address_x86);
procedure fstsw(const addr: address_x86);
procedure fnstsw(const addr: address_x86);
end;
// последовательность команд
// архитектура x64
TOpcodeBlock_x64 = object(TOpcodeBlock_Intel)
private
// два параметра: reg, const_64
// пока применяется только для mov
// PRE-реализация делается на месте
function cmd_reg_const_value64(const opcode_reg: integer; const v_const: opused_const_64{$ifdef OPCODE_MODES}; const cmd: ShortString{$endif}): POpcodeCmd;
public
property Proc: TOpcodeProc_x64 read P.Proc_x64;
property Next: POpcodeBlock_x64 read N.Next_x64 write N.Next_x64;
public
function AppendBlock(): POpcodeBlock_x64;
procedure adc(reg: reg_x64; v_reg: reg_x64); overload;
procedure adc(reg: reg_x64; const v_const: const_32); overload;
procedure adc(reg: reg_x64; const addr: address_x64); overload;
procedure adc(const addr: address_x64; v_reg: reg_x64); overload;
procedure adc(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure lock_adc(const addr: address_x64; v_reg: reg_x64); overload;
procedure lock_adc(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure add(reg: reg_x64; v_reg: reg_x64); overload;
procedure add(reg: reg_x64; const v_const: const_32); overload;
procedure add(reg: reg_x64; const addr: address_x64); overload;
procedure add(const addr: address_x64; v_reg: reg_x64); overload;
procedure add(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure lock_add(const addr: address_x64; v_reg: reg_x64); overload;
procedure lock_add(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure and_(reg: reg_x64; v_reg: reg_x64); overload;
procedure and_(reg: reg_x64; const v_const: const_32); overload;
procedure and_(reg: reg_x64; const addr: address_x64); overload;
procedure and_(const addr: address_x64; v_reg: reg_x64); overload;
procedure and_(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure lock_and(const addr: address_x64; v_reg: reg_x64); overload;
procedure lock_and(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure bswap(reg: reg_x64_dq);
//procedure bsf(dest: reg_x64_wd; src: reg_x64_wd); overload;
//procedure bsf(dest: reg_x64_wd; const addr: address_x64); overload;
// bt
// btc
// btr
// bts
// *lock
procedure call(block: POpcodeBlock_x64); overload;
procedure call(blocks: POpcodeSwitchBlock; index: reg_x64_addr; offset: integer=0{$ifdef OPCODE_MODES};buffer: reg_x64_addr=r11{$endif}); overload;
procedure call(reg: reg_x64_addr); overload;
procedure call(const addr: address_x64); overload;
// cbw
// cwde
// cwd
// cdq
// clc
// cld
// cli
// clts
// cmc
// clflush ?
procedure cmov(cc: intel_cc; reg: reg_x64_wdq; v_reg: reg_x64_wdq); overload;
procedure cmov(cc: intel_cc; reg: reg_x64_wdq; const addr: address_x64); overload;
procedure cmp(reg: reg_x64; v_reg: reg_x64); overload;
procedure cmp(reg: reg_x64; const v_const: const_32); overload;
procedure cmp(reg: reg_x64; const addr: address_x64); overload;
procedure cmp(const addr: address_x64; v_reg: reg_x64); overload;
procedure cmp(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
// cmpxchg
// cmpxchg8b
// cpuid
procedure dec(reg: reg_x64); overload;
procedure dec(ptr: size_ptr; const addr: address_x64); overload;
procedure lock_dec(ptr: size_ptr; const addr: address_x64);
procedure div_(reg: reg_x64); overload;
procedure div_(ptr: size_ptr; const addr: address_x64); overload;
// enter
procedure idiv(reg: reg_x64); overload;
procedure idiv(ptr: size_ptr; const addr: address_x64); overload;
procedure imul(reg: reg_x64); overload;
procedure imul(ptr: size_ptr; const addr: address_x64); overload;
procedure imul(reg: reg_x64_wdq; v_reg: reg_x64_wdq); overload;
procedure imul(reg: reg_x64_wdq; const addr: address_x64); overload;
procedure imul(reg: reg_x64_wdq; const v_const: const_32); overload;
procedure imul(reg1, reg2: reg_x64_wdq; const v_const: const_32); overload;
procedure imul(reg: reg_x64_wdq; const addr: address_x64; const v_const: const_32); overload;
// in
procedure inc(reg: reg_x64); overload;
procedure inc(ptr: size_ptr; const addr: address_x64); overload;
procedure lock_inc(ptr: size_ptr; const addr: address_x64);
procedure j(cc: intel_cc; block: POpcodeBlock_x64);
procedure jmp(block: POpcodeBlock_x64); overload;
procedure jmp(blocks: POpcodeSwitchBlock; index: reg_x64_addr; offset: integer=0{$ifdef OPCODE_MODES};buffer: reg_x64_addr=r11{$endif}); overload;
procedure jmp(reg: reg_x64_addr); overload;
procedure jmp(const addr: address_x64); overload;
procedure lea(reg: reg_x64_addr; const addr: address_x64);
procedure mov(reg: reg_x64; v_reg: reg_x64); overload;
procedure mov(reg: reg_x64; const v_const: const_32); overload;
procedure mov(reg: reg_x64; const addr: address_x64); overload;
procedure mov(const addr: address_x64; v_reg: reg_x64); overload;
procedure mov(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure mov(reg: reg_x64{reg_x64_dwords}; const v_const: const_64); overload;
procedure movsx(reg: reg_x64; v_reg: reg_x64); overload;
procedure movsx(reg: reg_x64; ptr: size_ptr; const addr: address_x64); overload;
procedure movzx(reg: reg_x64; v_reg: reg_x64); overload;
procedure movzx(reg: reg_x64; ptr: size_ptr; const addr: address_x64); overload;
procedure mul(reg: reg_x64); overload;
procedure mul(ptr: size_ptr; const addr: address_x64); overload;
procedure neg(reg: reg_x64); overload;
procedure neg(ptr: size_ptr; const addr: address_x64); overload;
procedure lock_neg(ptr: size_ptr; const addr: address_x64);
// nop(count)
procedure not_(reg: reg_x64); overload;
procedure not_(ptr: size_ptr; const addr: address_x64); overload;
procedure lock_not(ptr: size_ptr; const addr: address_x64);
procedure or_(reg: reg_x64; v_reg: reg_x64); overload;
procedure or_(reg: reg_x64; const v_const: const_32); overload;
procedure or_(reg: reg_x64; const addr: address_x64); overload;
procedure or_(const addr: address_x64; v_reg: reg_x64); overload;
procedure or_(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure lock_or(const addr: address_x64; v_reg: reg_x64); overload;
procedure lock_or(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure pop(reg: reg_x64_wq); overload;
procedure pop(ptr: size_ptr; const addr: address_x64); overload;
// prefetch0/prefetch1/prefetch2/prefetchnta ?
procedure push(reg: reg_x64_wq); overload;
procedure push(ptr: size_ptr; const addr: address_x64); overload;
procedure rcl_cl(reg: reg_x64); overload;
procedure rcl(reg: reg_x64; const v_const: const_32); overload;
procedure rcl_cl(ptr: size_ptr; const addr: address_x64); overload;
procedure rcl(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure rcr_cl(reg: reg_x64); overload;
procedure rcr(reg: reg_x64; const v_const: const_32); overload;
procedure rcr_cl(ptr: size_ptr; const addr: address_x64); overload;
procedure rcr(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure rol_cl(reg: reg_x64); overload;
procedure rol(reg: reg_x64; const v_const: const_32); overload;
procedure rol_cl(ptr: size_ptr; const addr: address_x64); overload;
procedure rol(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure ror_cl(reg: reg_x64); overload;
procedure ror(reg: reg_x64; const v_const: const_32); overload;
procedure ror_cl(ptr: size_ptr; const addr: address_x64); overload;
procedure ror(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure sal_cl(reg: reg_x64); overload;
procedure sal(reg: reg_x64; const v_const: const_32); overload;
procedure sal_cl(ptr: size_ptr; const addr: address_x64); overload;
procedure sal(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure sar_cl(reg: reg_x64); overload;
procedure sar(reg: reg_x64; const v_const: const_32); overload;
procedure sar_cl(ptr: size_ptr; const addr: address_x64); overload;
procedure sar(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure sbb(reg: reg_x64; v_reg: reg_x64); overload;
procedure sbb(reg: reg_x64; const v_const: const_32); overload;
procedure sbb(reg: reg_x64; const addr: address_x64); overload;
procedure sbb(const addr: address_x64; v_reg: reg_x64); overload;
procedure sbb(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure lock_sbb(const addr: address_x64; v_reg: reg_x64); overload;
procedure lock_sbb(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure set_(cc: intel_cc; reg: reg_x64_bytes); overload;
procedure set_(cc: intel_cc; const addr: address_x64); overload;
procedure shl_cl(reg: reg_x64); overload;
procedure shl_(reg: reg_x64; const v_const: const_32); overload;
procedure shl_cl(ptr: size_ptr; const addr: address_x64); overload;
procedure shl_(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure shr_cl(reg: reg_x64); overload;
procedure shr_(reg: reg_x64; const v_const: const_32); overload;
procedure shr_cl(ptr: size_ptr; const addr: address_x64); overload;
procedure shr_(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure shld_cl(reg1, reg2: reg_x64); overload;
procedure shld(reg1, reg2: reg_x64; const v_const: const_32); overload;
procedure shld_cl(const addr: address_x64; reg2: reg_x64); overload;
procedure shld(const addr: address_x64; reg2: reg_x64; const v_const: const_32); overload;
procedure shrd_cl(reg1, reg2: reg_x64); overload;
procedure shrd(reg1, reg2: reg_x64; const v_const: const_32); overload;
procedure shrd_cl(const addr: address_x64; reg2: reg_x64); overload;
procedure shrd(const addr: address_x64; reg2: reg_x64; const v_const: const_32); overload;
procedure sub(reg: reg_x64; v_reg: reg_x64); overload;
procedure sub(reg: reg_x64; const v_const: const_32); overload;
procedure sub(reg: reg_x64; const addr: address_x64); overload;
procedure sub(const addr: address_x64; v_reg: reg_x64); overload;
procedure sub(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure lock_sub(const addr: address_x64; v_reg: reg_x64); overload;
procedure lock_sub(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure test(reg: reg_x64; v_reg: reg_x64); overload;
procedure test(reg: reg_x64; const v_const: const_32); overload;
procedure test(reg: reg_x64; const addr: address_x64); overload;
procedure test(const addr: address_x64; v_reg: reg_x64); overload;
procedure test(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure xadd(reg: reg_x64; v_reg: reg_x64); overload;
procedure xadd(const addr: address_x64; v_reg: reg_x64); overload;
procedure lock_xadd(const addr: address_x64; v_reg: reg_x64);
procedure xchg(reg: reg_x64; v_reg: reg_x64); overload;
procedure xchg(const addr: address_x64; v_reg: reg_x64); overload;
procedure lock_xchg(const addr: address_x64; v_reg: reg_x64);
procedure xor_(reg: reg_x64; v_reg: reg_x64); overload;
procedure xor_(reg: reg_x64; const v_const: const_32); overload;
procedure xor_(reg: reg_x64; const addr: address_x64); overload;
procedure xor_(const addr: address_x64; v_reg: reg_x64); overload;
procedure xor_(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure lock_xor(const addr: address_x64; v_reg: reg_x64); overload;
procedure lock_xor(ptr: size_ptr; const addr: address_x64; const v_const: const_32); overload;
procedure cmpsq(reps: intel_rep=REP_SINGLE);
procedure insq(reps: intel_rep=REP_SINGLE);
procedure scasq(reps: intel_rep=REP_SINGLE);
procedure stosq(reps: intel_rep=REP_SINGLE);
procedure lodsq(reps: intel_rep=REP_SINGLE);
procedure movsq(reps: intel_rep=REP_SINGLE);
// FPU и память
procedure fbld(const addr: address_x64);
procedure fbstp(const addr: address_x64);
procedure fldcw(const addr: address_x64);
procedure fldenv(const addr: address_x64);
procedure fsave(const addr: address_x64);
procedure fnsave(const addr: address_x64);
procedure fstcw(const addr: address_x64);
procedure fnstcw(const addr: address_x64);
procedure fstenv(const addr: address_x64);
procedure fnstenv(const addr: address_x64);
procedure fstsw(const addr: address_x64);
procedure fnstsw(const addr: address_x64);
end;
// последовательность команд
// архитектура ARM
TOpcodeBlock_ARM = object(TOpcodeBlock)
private
public
property Proc: TOpcodeProc_ARM read P.Proc_ARM;
property Next: POpcodeBlock_ARM read N.Next_ARM write N.Next_ARM;
public
function AppendBlock(): POpcodeBlock_ARM;
procedure b{jmp}(block: POpcodeBlock_ARM); overload;
procedure b{jcc}(cc: arm_cc; block: POpcodeBlock_ARM); overload;
procedure bl{call}(block: POpcodeBlock_ARM); overload;
{$ifdef OPCODE_MODES}
procedure b{jmp}(ProcName: pansichar); overload;
procedure b{jcc}(cc: arm_cc; ProcName: pansichar); overload;
procedure bl{call}(ProcName: pansichar); overload;
{$endif}
end;
// последовательность команд
// в виртуальной машине
TOpcodeBlock_VM = object(TOpcodeBlock)
private
public
property Proc: TOpcodeProc_VM read P.Proc_VM;
property Next: POpcodeBlock_VM read N.Next_VM write N.Next_VM;
public
function AppendBlock(): POpcodeBlock_VM;
end;
// элемент подписки глобального объекта
POpcodeSubscribe = ^TOpcodeSubscribe;
TOpcodeSubscribe = record
// организация списка
Next: POpcodeSubscribe;
// сам объект
case Integer of
0: (Global: TOpcodeGlobal);
1: (Proc: TOpcodeProc);
2: (Variable: TOpcodeVariable);
100500: (Block: POpcodeBlock{нужно внутри фиксации функции});
end;
// объект глобального пространства
// функция или переменная/тип.константа
TOpcodeGlobal = class(TObject)
protected
// хранилище
FStorage: record
case integer of
0: (uni: TOpcodeStorage);
1: (x86: TOpcodeStorage_x86);
2: (x64: TOpcodeStorage_x64);
3: (ARM: TOpcodeStorage_ARM);
4: (VM: TOpcodeStorage_VM);
end;
// для организации списка: prev, next
FPrev: record
case integer of
0: (uni: TOpcodeGlobal);
1: (vrb: TOpcodeVariable);
2: (x86: TOpcodeProc_x86);
3: (x64: TOpcodeProc_x64);
4: (ARM: TOpcodeProc_ARM);
5: (VM: TOpcodeProc_VM);
end;
FNext: record
case integer of
0: (uni: TOpcodeGlobal);
1: (vrb: TOpcodeVariable);
2: (x86: TOpcodeProc_x86);
3: (x64: TOpcodeProc_x64);
4: (ARM: TOpcodeProc_ARM);
5: (VM: TOpcodeProc_VM);
end;
private
FOFFSET: integer;
FSize: integer;
FAlignedSize: integer;
FMemory: pointer;
procedure Set_OFFSET(const Value: integer);
procedure SetSize(const Value: integer);
private
// список подписанных функций
// в случае изменения OFFSET в каждой функции вызывается соответствующий калбек
FSubscribedProcs: POpcodeSubscribe;
public
constructor Create; // error
destructor Destroy; override;
procedure FreeInstance; override;
// функционал подписки
// перехват неправильного деструктора!
// GlobalId
// счётчик ссылок ? = количество подписанных элементов
property Storage: TOpcodeStorage read FStorage.uni;
property Memory: pointer read FMemory;
property Size: integer read FSize write SetSize;
property AlignedSize: integer read FAlignedSize;
property OFFSET: integer read FOFFSET write Set_OFFSET;
end;
// глобальная переменная или типизированная константа
// (доступна только для Binary режима)
TOpcodeVariable = class(TOpcodeGlobal)
private
protected
public
property Prev: TOpcodeVariable read FPrev.vrb;
property Next: TOpcodeVariable read FNext.vrb;
end;
// целое хранилище, в рамках которого
// может существовать несколько функций
// и глобальные переменные с константами
//
// и менеджмент исполняемой памяти (JIT)
TOpcodeStorage = class(TObject)
private
{$ifdef OPCODE_MODES}
FMode: TOpcodeMode;
{$endif}
private
FOwnHeap: boolean;
FJIT: boolean;
FHeap: TOpcodeHeap;
protected
// 0 - Variable, 1 - Proc (конкретный класс под конкретную платформу)
F: record
case integer of
0: (Globals: array[0..1] of TOpcodeGlobal);
1: (Variables: TOpcodeVariable;
Procs: record
case integer of
0: (uni: TOpcodeProc);
1: (x86: TOpcodeProc_x86);
2: (x64: TOpcodeProc_x64);
3: (ARM: TOpcodeProc_ARM);
4: (VM: TOpcodeProc_VM);
end;)
end;
FFreeGlobals: array[0..1] of TOpcodeGlobal;
function CreateInstance(const AClass: TClass): TOpcodeGlobal;
function InternalCreateProc(const ProcClass: TOpcodeProcClass; const Callback: pointer; const AOwnHeap: boolean{=false}): TOpcodeProc;
private
FJITHeap: THandle;
function JIT_Alloc(const Size: integer): pointer;
procedure JIT_Free(const Proc: pointer);
protected
FSubscrBuffer: POpcodeSubscribe;
procedure SubscribeGlobal(var List: POpcodeSubscribe; const Global: TOpcodeGlobal);
procedure UnsubscribeGlobal(var List: POpcodeSubscribe; const Global: TOpcodeGlobal);
procedure ReleaseSubscribeList(const List: POpcodeSubscribe);
public
{$ifdef OPCODE_MODES}
property Mode: TOpcodeMode read FMode;
{$endif}
public
constructor Create(const AHeap: TOpcodeHeap=nil{$ifdef OPCODE_MODES}; const AMode: TOpcodeMode=omBinary{$endif});
destructor Destroy; override;
function CreateVariable(const Size: integer): TOpcodeVariable;
// function CreateProc(const AOwnHeap: boolean=false): TOpcodeProc... - для каждой платформы свой
property Heap: TOpcodeHeap read FHeap;
property OwnHeap: boolean read FOwnHeap;
property JIT: boolean read FJIT;
// списки
property Variables: TOpcodeVariable read F.Variables;
// property Procs: TOpcodeProc... - для каждой платформы
end;
TOpcodeStorage_Intel = class(TOpcodeStorage)
private
protected
public
end;
TOpcodeStorage_x86 = class(TOpcodeStorage_Intel)
private
protected
public
{$ifdef CPUX86}
constructor CreateJIT(const AHeap: TOpcodeHeap=nil);
{$endif}
function CreateProc(const AOwnHeap: boolean=false): TOpcodeProc_x86;
property Procs: TOpcodeProc_x86 read F.Procs.x86;
end;
TOpcodeStorage_x64 = class(TOpcodeStorage_Intel)
private
protected
public
{$ifdef CPUX64}
constructor CreateJIT(const AHeap: TOpcodeHeap=nil);
{$endif}
function CreateProc(const AOwnHeap: boolean=false): TOpcodeProc_x64;
property Procs: TOpcodeProc_x64 read F.Procs.x64;
end;
TOpcodeStorage_ARM = class(TOpcodeStorage)
private
protected
public
function CreateProc(const AOwnHeap: boolean=false): TOpcodeProc_ARM;
property Procs: TOpcodeProc_ARM read F.Procs.ARM;
end;
TOpcodeStorage_VM = class(TOpcodeStorage)
private
protected
public
function CreateProc(const AOwnHeap: boolean=false): TOpcodeProc_VM;
property Procs: TOpcodeProc_VM read F.Procs.VM;
end;
// универсальный тип, представляющий собой
TOpcodeProc = class(TOpcodeGlobal)
private
{$ifdef OPCODE_MODES}
FMode: TOpcodeMode;
{$endif}
private
FOwnHeap: boolean;
FExternalCellsCount: word; // зафиксировано (см. FFixupedInfo)
F: packed record
case Integer of
0: (Value: integer);
1: (BlocksReferenced: word{может свободно инкрементироваться после фиксации}; RetN: word);
end;
FHeap: TOpcodeHeap;
private
// для убыстрения записи бинарных команд
FLastBinaryCmd: POpcodeCmd;
FLastHeapCurrent: Pointer;
private
// умный список ячеек, которые потом необходимо будет отсортировать
// и "зафиксировать" в FFixupedInfo
FCells: pointer{POpcodeCellInfo};
// умная функция, добавляющая выделяющая память,
// заполняющая базовые поля, записывающая в список
// function AllocCell(const Global: TOpcodeGlobal; const LocalPtr ????; const Correction: integer): POpcodeExternalCell;
private
// общий внутренний буфер информации (выделяемый в глобальном менеджере памяти)
// в котором хранятся:
// 1) ReferencedBlocks: array[1..ReferencedBlocks[0]] of integer;
// это массив локальных смещений для каждого блока, который нужен извне
// длинна массива записана самым первым числом. Минимум 1 блок (prefix)
//
// 2) ExternalCells: array[0..FExternalCellsCount-1] of TOpcodeExternalCell;
// массив универсальных данных по внешним смещениям. Будь то переменные
// или внешние функции. Может быть прямой адрес, может быть относительный
//
// 3) LocalCells: array[1..LocalCells[0]] of integer;
// это массив внутренних указателей на блоки. Используется например в
// push @1, или в jmp [offset @case_edx + edx*4 - 4]
// Количество хранится в 0м элементе. И вполне может быть равно 0.
// Модицикация только с изменением ячейки на Delta смещения OFFSET.
FFixupedInfo: pointer;
// выделяем память под внутренний буфер
procedure AllocFixupedInfo(const Size: integer);
protected
// скрытый кусок кода, позволяющий вызывать альтернативный режим вызова
// используется редко, контроль прыжков заложен внутри
B_call_modes: record
case integer of
0: (uni: POpcodeBlock);
1: (x86: POpcodeBlock_x86);
2: (x64: POpcodeBlock_x64);
3: (ARM: POpcodeBlock_ARM);
4: (VM: POpcodeBlock_VM);
end;
// универсальные блоки, свойственные каждой функции
B_prefix: record
case integer of
0: (uni: POpcodeBlock);
1: (x86: POpcodeBlock_x86);
2: (x64: POpcodeBlock_x64);
3: (ARM: POpcodeBlock_ARM);
4: (VM: POpcodeBlock_VM);
end;
B_start: record
case integer of
0: (uni: POpcodeBlock);
1: (x86: POpcodeBlock_x86);
2: (x64: POpcodeBlock_x64);
3: (ARM: POpcodeBlock_ARM);
4: (VM: POpcodeBlock_VM);
end;
B_finish: record
case integer of
0: (uni: POpcodeBlock);
1: (x86: POpcodeBlock_x86);
2: (x64: POpcodeBlock_x64);
3: (ARM: POpcodeBlock_ARM);
4: (VM: POpcodeBlock_VM);
end;
B_postfix: record
case integer of
0: (uni: POpcodeBlock);
1: (x86: POpcodeBlock_x86);
2: (x64: POpcodeBlock_x64);
3: (ARM: POpcodeBlock_ARM);
4: (VM: POpcodeBlock_VM);
end;
// концепция калбека вместо виртуальных функций используется из соображения компактности экзешника
// потому что в случае виртуальных функций компилируются все виртуальные функции всех наследников TOpcodeProc
// потому что в TOpcodeStorage объявлена вариантная структура F
// Mode 0 - заполнить информационные таблицы по прыжкам JumpsInfo
// Mode 1 - заполнить структуру LastRetCmd
// Mode 2 - бинарная реализация прыжков
FCallback: procedure(const Mode: integer; const Storage: pointer{PFixupedStorage});
public
{$ifdef OPCODE_MODES}
property Mode: TOpcodeMode read FMode;
{$endif}
public
constructor Create(const AHeap: TOpcodeHeap=nil{$ifdef OPCODE_MODES}; const AMode: TOpcodeMode=omBinary{$endif});
// функция инициализации всех рабочих полей, инициализация блоков, чистит Heap (если собственный)
// вызывается в конструкторе автоматически
// но может понадобиться для новой перезаписи функции
// (поле RetN остаётся неизменным)
procedure Initialize();
// самая сложная функция, которая:
// 1) использует Heap в качестве менеджера рабочих данных
// 2) может зачистить свои рассчёты по окончанию Fixup-а
// 3) перезаполняет внутренний информационный буфер (FFixupedInfo)
// 4) проводит необходимые доводки команд
// 5) оптимизирует прыжки
// 6) размечает блоки
// 7) определяет итоговый размер
// 8) записывает данные
// 9) чистит за собой служебные данные
procedure Fixup();
// некоторые свойства
property Heap: TOpcodeHeap read FHeap;
property OwnHeap: boolean read FOwnHeap;
property RetN: word read F.RetN write F.RetN;
end;
TOpcodeProc_Intel = class(TOpcodeProc)
private
protected
public
// персональный калбек (сводится к ручному проставлению калбека)
constructor Create(const AHeap: TOpcodeHeap=nil{$ifdef OPCODE_MODES}; const AMode: TOpcodeMode=omBinary{$endif});
end;
TOpcodeProc_x86 = class(TOpcodeProc_Intel)
private
protected
public
// опциональный блок
property CallModes: POpcodeBlock_x86 read B_call_modes.x86;
// блоки
property Prefix: POpcodeBlock_x86 read B_prefix.x86;
property Start: POpcodeBlock_x86 read B_start.x86;
property Finish: POpcodeBlock_x86 read B_finish.x86;
property Postfix: POpcodeBlock_x86 read B_postfix.x86;
// хранилище
property Storage: TOpcodeStorage_x86 read FStorage.x86;
property Prev: TOpcodeProc_x86 read FPrev.x86;
property Next: TOpcodeProc_x86 read FNext.x86;
end;
TOpcodeProc_x64 = class(TOpcodeProc_Intel)
private
protected
public
// опциональный блок
property CallModes: POpcodeBlock_x64 read B_call_modes.x64;
// блоки
property Prefix: POpcodeBlock_x64 read B_prefix.x64;
property Start: POpcodeBlock_x64 read B_start.x64;
property Finish: POpcodeBlock_x64 read B_finish.x64;
property Postfix: POpcodeBlock_x64 read B_postfix.x64;
// хранилище
property Storage: TOpcodeStorage_x64 read FStorage.x64;
property Prev: TOpcodeProc_x64 read FPrev.x64;
property Next: TOpcodeProc_x64 read FNext.x64;
end;
TOpcodeProc_ARM = class(TOpcodeProc)
private
protected
public
// персональный калбек (сводится к ручному проставлению калбека)
constructor Create(const AHeap: TOpcodeHeap=nil{$ifdef OPCODE_MODES}; const AMode: TOpcodeMode=omBinary{$endif});
// опциональный блок
property CallModes: POpcodeBlock_ARM read B_call_modes.ARM;
// блоки
property Prefix: POpcodeBlock_ARM read B_prefix.ARM;
property Start: POpcodeBlock_ARM read B_start.ARM;
property Finish: POpcodeBlock_ARM read B_finish.ARM;
property Postfix: POpcodeBlock_ARM read B_postfix.ARM;
// хранилище
property Storage: TOpcodeStorage_ARM read FStorage.ARM;
property Prev: TOpcodeProc_ARM read FPrev.ARM;
property Next: TOpcodeProc_ARM read FNext.ARM;
end;
// универсальная функция для виртуальной машины
TOpcodeProc_VM = class(TOpcodeProc)
private
protected
public
// персональный калбек (сводится к ручному проставлению калбека)
constructor Create(const AHeap: TOpcodeHeap=nil{$ifdef OPCODE_MODES}; const AMode: TOpcodeMode=omBinary{$endif});
// опциональный блок
property CallModes: POpcodeBlock_VM read B_call_modes.VM;
// блоки
property Prefix: POpcodeBlock_VM read B_prefix.VM;
property Start: POpcodeBlock_VM read B_start.VM;
property Finish: POpcodeBlock_VM read B_finish.VM;
property Postfix: POpcodeBlock_VM read B_postfix.VM;
// хранилище
property Storage: TOpcodeStorage_VM read FStorage.VM;
property Prev: TOpcodeProc_VM read FPrev.VM;
property Next: TOpcodeProc_VM read FNext.VM;
end;
// типы по текущей платформе (def-типы)
{$ifdef CPUX86}
def_reg = reg_x86;
def_reg_addr = reg_x86_addr;
def_address = address_x86;
TDefOpcodeBlock = TOpcodeBlock_x86;
PDefOpcodeBlock = POpcodeBlock_x86;
TDefOpcodeProc = TOpcodeProc_x86;
TDefOpcodeStorage = TOpcodeStorage_x86;
{$elseif Defined(CPUX64)}
def_reg = reg_x64;
def_reg_addr = reg_x64_addr;
def_address = address_x64;
TDefOpcodeBlock = TOpcodeBlock_x64;
PDefOpcodeBlock = POpcodeBlock_x64;
TDefOpcodeProc = TOpcodeProc_x64;
TDefOpcodeStorage = TOpcodeStorage_x64;
{$elseif Defined(CPUXARM)}
def_reg = reg_ARM;
def_reg_addr = reg_ARM_addr;
def_address = address_ARM;
TDefOpcodeBlock = TOpcodeBlock_ARM;
PDefOpcodeBlock = POpcodeBlock_ARM;
TDefOpcodeProc = TOpcodeProc_ARM;
TDefOpcodeStorage = TOpcodeStorage_ARM;
{$ifend}
(* вспомогательные удобные функции для заполнения структур *)
function const32(const Value: Integer): const_32; overload;
function const32(const pValue: PInteger): const_32; overload;
{$ifdef OPCODE_MODES}
function const32(const Condition: PAnsiChar; const Offseted: boolean=false): const_32; overload;
{$endif}
function const32(const Proc: TOpcodeProc): const_32; overload;
function const32(const Block: POpcodeBlock): const_32; overload;
function const32(const Variable: TOpcodeVariable; const Offset: Integer=0): const_32; overload;
function const64(const Value: Int64): const_64; overload;
function const64(const pValue: PInt64): const_64; overload;
{$ifdef OPCODE_MODES}
function const64(const Condition: PAnsiChar; const Offseted: boolean=false): const_64; overload;
{$endif}
function address86(const reg: reg_x86_addr; const offset: integer=0): address_x86; overload;
function address86(const reg: reg_x86_addr; const scale: intel_scale; const plus: reg_x86_addr; const offset: integer=0): address_x86; overload;
{$ifdef OPCODE_MODES}
function address86(const reg: reg_x86_addr; const scale: intel_scale; const plus: reg_x86_addr; const Condition: PAnsiChar; const Offseted: boolean=false): address_x86; overload;
{$endif}
function address64(const reg: reg_x64_addr; const offset: integer=0): address_x64; overload;
function address64(const reg: reg_x64_addr; const scale: intel_scale; const plus: reg_x64_addr; const offset: integer=0): address_x64; overload;
{$ifdef OPCODE_MODES}
function address64(const reg: reg_x64_addr; const scale: intel_scale; const plus: reg_x64_addr; const Condition: PAnsiChar; const Offseted: boolean=false): address_x64; overload;
{$endif}
implementation
{$if CompilerVersion < 19}
type
NativeInt = Integer;
// NativeUInt = Cardinal;
{$ifend}
const
// внутренняя константа для блоков, означающая, что ссылки на блок нет
NO_REFERENCE = high(word);
// примерно аналогично для обозначения, что блоку не назначен фиксированный блок
NO_FIXUPED = high(word);
// константа, которая позволяет отключить объединение бинарных команд
// чаще всего это нужно для специфических команд
NO_CMD = POpcodeCmd(NativeInt(-1));
// константа нужна только для текстового варианта глобальных прыжков
{$ifdef OPCODE_MODES}
NO_PROC = TOpcodeProc(NativeInt(-1));
{$endif}
// информация по регистрам платформы x32-64: размер и флаги
reg_intel_info: array[reg_x64] of integer = ($00000001,$00090001,$00120001,$001B0001,$00240001,
$002D0001,$00360001,$003F0001,$20000102,$20090102,$20120102,$201B0102,$20240102,$202D0102,
$20360102,$203F0102,$00000104,$00090104,$00120104,$001B0104,$00240104,$002D0104,$00360104,
$003F0104,$47000104,$47090104,$47120104,$471B0104,$47240104,$472D0104,$47360104,$473F0104,
$67000102,$67090102,$67120102,$671B0102,$67240102,$672D0102,$67360102,$673F0102,$48000108,
$48090108,$48120108,$481B0108,$48240108,$482D0108,$48360108,$483F0108,$4F000108,$4F090108,
$4F120108,$4F1B0108,$4F240108,$4F2D0108,$4F360108,$4F3F0108,$47000001,$47090001,$47120001,
$471B0001,$47240001,$472D0001,$47360001,$473F0001,$40240001,$402D0001,$40360001,$403F0001);
// размерности регистров архитектуры ARM
reg_ARM_size: array[reg_ARM] of byte = (0{todo});
{$ifdef OPCODE_MODES}
// имена регистров платформы x32-64 (нужно для режима ассемблера)
reg_intel_names: array[reg_x64] of pansichar = (
'al','cl','dl','bl','ah','ch','dh','bh','ax','cx','dx','bx','sp','bp','si','di',
'eax','ecx','edx','ebx','esp','ebp','esi','edi','r8d','r9d','r10d','r11d','r12d','r13d','r14d','r15d',
'r8w','r9w','r10w','r11w','r12w','r13w','r14w','r15w','rax','rcx','rdx','rbx','rsp','rbp','rsi','rdi',
'r8','r9','r10','r11','r12','r13','r14','r15','r8b','r9b','r10b','r11b','r12b','r13b','r14b','r15b',
'spl','bpl','sil','dil');
// расшифровки вариантов cc (нужны для setcc,cmovcc,jcc)
// годится по сути и для прыжков и для setcc/cmovcc. Как pansichar и как PShortString(для прыжков)
// и даже для call и jmp
cc_intel_names: array[-2..ord(high(intel_cc))] of pansichar = (
#4'call',#3'jmp',#2'jo',#3'jno',#2'jb',#2'jc',#4'jnae',#3'jae',#3'jnb',#3'jnc',
#2'je',#2'jz',#3'jnz',#3'jne',#3'jbe',#3'jna',#2'ja',#4'jnbe',#2'js',#3'jns',#2'jp',
#3'jpe',#3'jpo',#3'jnp',#2'jl',#4'jnge',#3'jge',#3'jnl',#3'jle',#3'jng',#2'jg',#4'jnle');
// аналогичная логика, только для платформы ARM
cc_arm_names: array[-2..ord(high(intel_cc))] of pansichar = (
#2'bl',#1'b',#3'bvs',#3'bvc',#3'bcc',#3'bcc',#3'bcc',#3'bcs',#3'bcs',#3'bcs',
#3'beq',#3'beq',#3'bnz',#3'bnz',#3'bls',#3'bls',#3'bhi',#3'bhi',#3'bmi',#3'bpl',
nil,nil,nil,nil,#3'blt',#3'blt',#3'bge',#3'bge',#3'ble',#3'ble',#3'bgt',#3'bgt');
// названия вариантов для размеров ptr
size_ptr_names: array[size_ptr] of pansichar = ('byte', 'word', 'dword', 'qword', 'tbyte', 'dqword');
{$endif}
// реальные размеры, подразумеваемые под константами
size_ptr_size: array[size_ptr] of byte = (1, 2, 4, 8, 10, 16);
// текстовое написание команд ассемблера
{$ifdef OPCODE_MODES}
const
cmd_aaa: string[3] = 'aaa';
cmd_aad: string[3] = 'aad';
cmd_aam: string[3] = 'aam';
cmd_aas: string[3] = 'aas';
cmd_adc: string[3] = 'adc';
cmd_add: string[3] = 'add';
cmd_and: string[3] = 'and';
cmd_bound: string[5] = 'bound';
cmd_bsf: string[3] = 'bsf';
cmd_bswap: string[5] = 'bswap';
cmd_bt: string[2] = 'bt';
cmd_btc: string[3] = 'btc';
cmd_btr: string[3] = 'btr';
cmd_bts: string[3] = 'bts';
cmd_call: string[4] = 'call';
cmd_cbw: string[3] = 'cbw';
cmd_cdq: string[3] = 'cdq';
cmd_clc: string[3] = 'clc';
cmd_cld: string[3] = 'cld';
cmd_clflush: string[7] = 'clflush';
cmd_cli: string[3] = 'cli';
cmd_clts: string[4] = 'clts';
cmd_cmc: string[3] = 'cmc';
cmd_cmov: string[4] = 'cmov';
cmd_cmp: string[3] = 'cmp';
cmd_cmpsb: string[5] = 'cmpsb';
cmd_cmpsd: string[5] = 'cmpsd';
cmd_cmpsq: string[5] = 'cmpsq';
cmd_cmpsw: string[5] = 'cmpsw';
cmd_cmpxchg: string[7] = 'cmpxchg';
cmd_cmpxchg8b: string[9] = 'cmpxchg8b';
cmd_cpuid: string[5] = 'cpuid';
cmd_cwd: string[3] = 'cwd';
cmd_cwde: string[4] = 'cwde';
cmd_daa: string[3] = 'daa';
cmd_das: string[3] = 'das';
cmd_dec: string[3] = 'dec';
cmd_div: string[3] = 'div';
cmd_enter: string[5] = 'enter';
cmd_f2xm1: string[5] = 'f2xm1';
cmd_fabs: string[4] = 'fabs';
cmd_fadd: string[4] = 'fadd';
cmd_faddp: string[5] = 'faddp';
cmd_fbld: string[4] = 'fbld';
cmd_fbstp: string[5] = 'fbstp';
cmd_fchs: string[4] = 'fchs';
cmd_fclex: string[5] = 'fclex';
cmd_fcmov: string[5] = 'fcmov';
cmd_fcom: string[4] = 'fcom';
cmd_fcomi: string[5] = 'fcomi';
cmd_fcomip: string[6] = 'fcomip';
cmd_fcomp: string[5] = 'fcomp';
cmd_fcompp: string[6] = 'fcompp';
cmd_fcos: string[4] = 'fcos';
cmd_fdecstp: string[7] = 'fdecstp';
cmd_fdiv: string[4] = 'fdiv';
cmd_fdivp: string[5] = 'fdivp';
cmd_fdivr: string[5] = 'fdivr';
cmd_fdivrp: string[6] = 'fdivrp';
cmd_ffree: string[5] = 'ffree';
cmd_fiadd: string[5] = 'fiadd';
cmd_ficom: string[5] = 'ficom';
cmd_ficomp: string[6] = 'ficomp';
cmd_fidiv: string[5] = 'fidiv';
cmd_fidivr: string[6] = 'fidivr';
cmd_fild: string[4] = 'fild';
cmd_fimul: string[5] = 'fimul';
cmd_fincstp: string[7] = 'fincstp';
cmd_finit: string[5] = 'finit';
cmd_fist: string[4] = 'fist';
cmd_fistp: string[5] = 'fistp';
cmd_fisub: string[5] = 'fisub';
cmd_fld: string[3] = 'fld';
cmd_fld1: string[4] = 'fld1';
cmd_fldcw: string[5] = 'fldcw';
cmd_fldenv: string[6] = 'fldenv';
cmd_fldl2e: string[6] = 'fldl2e';
cmd_fldl2t: string[6] = 'fldl2t';
cmd_fldlg2: string[6] = 'fldlg2';
cmd_fldln2: string[6] = 'fldln2';
cmd_fldpi: string[5] = 'fldpi';
cmd_fldz: string[4] = 'fldz';
cmd_fmul: string[4] = 'fmul';
cmd_fmulp: string[5] = 'fmulp';
cmd_fnclex: string[6] = 'fnclex';
cmd_fninit: string[6] = 'fninit';
cmd_fnop: string[4] = 'fnop';
cmd_fnsave: string[6] = 'fnsave';
cmd_fnstcw: string[6] = 'fnstcw';
cmd_fnstenv: string[7] = 'fnstenv';
cmd_fnstsw: string[6] = 'fnstsw';
cmd_fpatan: string[6] = 'fpatan';
cmd_fprem: string[5] = 'fprem';
cmd_fprem1: string[6] = 'fprem1';
cmd_fptan: string[5] = 'fptan';
cmd_frndint: string[7] = 'frndint';
cmd_frstor: string[6] = 'frstor';
cmd_fsave: string[5] = 'fsave';
cmd_fscale: string[6] = 'fscale';
cmd_fsin: string[4] = 'fsin';
cmd_fsincos: string[7] = 'fsincos';
cmd_fsqrt: string[5] = 'fsqrt';
cmd_fst: string[3] = 'fst';
cmd_fstcw: string[5] = 'fstcw';
cmd_fstenv: string[6] = 'fstenv';
cmd_fstp: string[4] = 'fstp';
cmd_fstsw: string[5] = 'fstsw';
cmd_fsub: string[4] = 'fsub';
cmd_fsubp: string[5] = 'fsubp';
cmd_fsubr: string[5] = 'fsubr';
cmd_fsubrp: string[6] = 'fsubrp';
cmd_ftst: string[4] = 'ftst';
cmd_fucom: string[5] = 'fucom';
cmd_fucomi: string[6] = 'fucomi';
cmd_fucomip: string[7] = 'fucomip';
cmd_fucomp: string[6] = 'fucomp';
cmd_fucompp: string[7] = 'fucompp';
cmd_fwait: string[5] = 'fwait';
cmd_fxam: string[4] = 'fxam';
cmd_fxch: string[4] = 'fxch';
cmd_fxtract: string[7] = 'fxtract';
cmd_fyl2x: string[5] = 'fyl2x';
cmd_fyl2xp1: string[7] = 'fyl2xp1';
cmd_hlt: string[3] = 'hlt';
cmd_idiv: string[4] = 'idiv';
cmd_imul: string[4] = 'imul';
cmd_in: string[2] = 'in';
cmd_inc: string[3] = 'inc';
cmd_insb: string[4] = 'insb';
cmd_insd: string[4] = 'insd';
cmd_insq: string[4] = 'insq';
cmd_insw: string[4] = 'insw';
cmd_int: string[3] = 'int';
cmd_invd: string[4] = 'invd';
cmd_invlpg: string[6] = 'invlpg';
cmd_iret: string[4] = 'iret';
cmd_jmp: string[3] = 'jmp';
cmd_lahf: string[4] = 'lahf';
cmd_lar: string[3] = 'lar';
cmd_lds: string[3] = 'lds';
cmd_lea: string[3] = 'lea';
cmd_leave: string[5] = 'leave';
cmd_les: string[3] = 'les';
cmd_lfs: string[3] = 'lfs';
cmd_lgdt: string[4] = 'lgdt';
cmd_lgs: string[3] = 'lgs';
cmd_lidt: string[4] = 'lidt';
cmd_lldt: string[4] = 'lldt';
cmd_lmsw: string[4] = 'lmsw';
cmd_lock_adc: string[8] = 'lock adc';
cmd_lock_add: string[8] = 'lock add';
cmd_lock_and: string[8] = 'lock and';
cmd_lock_dec: string[8] = 'lock dec';
cmd_lock_inc: string[8] = 'lock inc';
cmd_lock_neg: string[8] = 'lock neg';
cmd_lock_not: string[8] = 'lock not';
cmd_lock_or: string[7] = 'lock or';
cmd_lock_sbb: string[8] = 'lock sbb';
cmd_lock_sub: string[8] = 'lock sub';
cmd_lock_xadd: string[9] = 'lock xadd';
cmd_lock_xchg: string[9] = 'lock xchg';
cmd_lock_xor: string[8] = 'lock xor';
cmd_lodsb: string[5] = 'lodsb';
cmd_lodsd: string[5] = 'lodsd';
cmd_lodsq: string[5] = 'lodsq';
cmd_lodsw: string[5] = 'lodsw';
cmd_lsl: string[3] = 'lsl';
cmd_lss: string[3] = 'lss';
cmd_ltr: string[3] = 'ltr';
cmd_mov: string[3] = 'mov';
cmd_movsb: string[5] = 'movsb';
cmd_movsd: string[5] = 'movsd';
cmd_movsq: string[5] = 'movsq';
cmd_movsw: string[5] = 'movsw';
cmd_movsx: string[5] = 'movsx';
cmd_movsxd: string[6] = 'movsxd';
cmd_movzx: string[5] = 'movzx';
cmd_mul: string[3] = 'mul';
cmd_neg: string[3] = 'neg';
cmd_nop: string[3] = 'nop';
cmd_not: string[3] = 'not';
cmd_or: string[2] = 'or';
cmd_out: string[3] = 'out';
cmd_outs: string[4] = 'outs';
cmd_outsb: string[5] = 'outsb';
cmd_outsd: string[5] = 'outsd';
cmd_outsw: string[5] = 'outsw';
cmd_pause: string[5] = 'pause';
cmd_pop: string[3] = 'pop';
cmd_popa: string[4] = 'popa';
cmd_popad: string[5] = 'popad';
cmd_popf: string[4] = 'popf';
cmd_popfd: string[5] = 'popfd';
cmd_prefetch0: string[9] = 'prefetch0';
cmd_prefetch1: string[9] = 'prefetch1';
cmd_prefetch2: string[9] = 'prefetch2';
cmd_prefetchnta: string[11] = 'prefetchnta';
cmd_push: string[4] = 'push';
cmd_pusha: string[5] = 'pusha';
cmd_pushad: string[6] = 'pushad';
cmd_pushd: string[5] = 'pushd';
cmd_pushf: string[5] = 'pushf';
cmd_rcl: string[3] = 'rcl';
cmd_rcr: string[3] = 'rcr';
cmd_rdmsr: string[5] = 'rdmsr';
cmd_rdpmc: string[5] = 'rdpmc';
cmd_rdtsc: string[5] = 'rdtsc';
cmd_ret: string[3] = 'ret';
cmd_rol: string[3] = 'rol';
cmd_ror: string[3] = 'ror';
cmd_rsm: string[3] = 'rsm';
cmd_sahf: string[4] = 'sahf';
cmd_sal: string[3] = 'sal';
cmd_sar: string[3] = 'sar';
cmd_sbb: string[3] = 'sbb';
cmd_scasb: string[5] = 'scasb';
cmd_scasd: string[5] = 'scasd';
cmd_scasq: string[5] = 'scasq';
cmd_scasw: string[5] = 'scasw';
cmd_set: string[3] = 'set';
cmd_sfrence: string[7] = 'sfrence';
cmd_shl: string[3] = 'shl';
cmd_shld: string[4] = 'shld';
cmd_shr: string[3] = 'shr';
cmd_shrd: string[4] = 'shrd';
cmd_sldt: string[4] = 'sldt';
cmd_smsw: string[4] = 'smsw';
cmd_stc: string[3] = 'stc';
cmd_std: string[3] = 'std';
cmd_sti: string[3] = 'sti';
cmd_stosb: string[5] = 'stosb';
cmd_stosd: string[5] = 'stosd';
cmd_stosq: string[5] = 'stosq';
cmd_stosw: string[5] = 'stosw';
cmd_str: string[3] = 'str';
cmd_sub: string[3] = 'sub';
cmd_sysenter: string[8] = 'sysenter';
cmd_sysexit: string[7] = 'sysexit';
cmd_test: string[4] = 'test';
cmd_ud2: string[3] = 'ud2';
cmd_verr: string[4] = 'verr';
cmd_verw: string[4] = 'verw';
cmd_wait: string[4] = 'wait';
cmd_wbinvd: string[6] = 'wbinvd';
cmd_wrmsr: string[5] = 'wrmsr';
cmd_xadd: string[4] = 'xadd';
cmd_xchg: string[4] = 'xchg';
cmd_xlat: string[4] = 'xlat';
cmd_xlatb: string[5] = 'xlatb';
cmd_xor: string[3] = 'xor';
{$endif}
// специализированная "константа" равная нулю
var
ZERO_CONST_32: const_32{зануляется автоматически};
const
// специальная фейковая константа, которая подставляется вместо Блока и Переменной
FAKE_CONST_32 = $0B0F0B0F; // ud2 ud2
const
// почему то синтаксис не позволяет обращаться по нормальному: [REG].TOpcodeAddress.offset. ...
// поэтому приходится использовать эту константу
TOpcodeAddress_offset = 3;
{$ifdef OPCODE_MODES}
// данная константа используется для текстовых команд
FMT_ONE_STRING: AnsiString = '%s';
{$endif}
type
{ TOpcodeCmdBinary = TOpcodeCmd + Data }
{$ifdef OPCODE_MODES}
// команда, представленная в виде ассемблера(текста), в т.ч. и для гибрида
TOpcodeCmdText = record {TOpcodeCmd}
Cmd: TOpcodeCmd;
Str: PShortString;
end;
POpcodeCmdText = ^TOpcodeCmdText;
{$endif}
{ TOpcodeCmdLeave = TOpcodeCmdBinary || TOpcodeCmdText }
// команда перенаправления в блок: jcc/jmp/call
// call объединён с прыжками в первую очередь из-за рассчёт
// с другой стороны команду jmp тоже стоит учитывать особо
// в качестве варианта прыжка выбран intel_cc, скорее всего он подойдёт и для ARM
// команды jcc(intel_cc), jmp(-1), call(-2)
TOpcodeCmdJumpBlock = record {TOpcodeCmd}
Cmd: TOpcodeCmd;
// адресация блока (по аналогии с TOpcodeCellData)
Proc: TOpcodeProc;
case Integer{is_global = (Proc <> Self)} of
0{local}: (Block: POpcodeBlock);
1{binary global}: (Reference: word{integer});
{$ifdef OPCODE_MODES}
2{text global}: (ProcName: pansichar);
{$endif}
end;
POpcodeCmdJumpBlock = ^TOpcodeCmdJumpBlock;
// структура, описывающая сопроводительную информацию(переменную или блок) к команде: cmBinary/cmText/cmLeave
// (используется внутри TOpcodeCmdJoined)
POpcodeJoinedData = ^TOpcodeJoinedData;
TOpcodeJoinedData = record
// смещение внутри команды
// если отлицательное - Relative (может пригодиться в адресе x64)
CmdOffset: integer;
case Integer of
-1: (Global: TOpcodeGlobal);
0: (Variable: TOpcodeVariable; VariableOffset: Integer);
1: (Proc: TOpcodeProc; //
case Boolean{is_global = (Proc <> Self)} of
false: (Block: POpcodeBlock);
true: (Reference: integer);
);
end;
// команда, содержащая сопроводительную информацию(переменную или блок) к другой команде: cmBinary/cmText/cmLeave
// в 2х младших битах Param содержится расположение (и количество) присоединённых данных. В остальных 6 битах кодируется TOpcodeCmdMode
// Size (Hybrid min/max) тоже копируется (для простоты подсчётов)
POpcodeCmdJoined = ^TOpcodeCmdJoined;
TOpcodeCmdJoined = record
Cmd: TOpcodeCmd;
Data: array[0..1]{но может содержать и 1 структуру!} of TOpcodeJoinedData;
end;
// специальное (временное) представление команды, когда
// в качестве аргумента(ов) числовой константы задаётся указатель
// в этом случае в момент фиксации получается истинное представление команды (UnpointerCmd)
TOpcodeCmdPointer = record {TOpcodeCmd}
Cmd: TOpcodeCmd;
params: integer;
pvalue: pointer{pinteger или pint64 или два TOpcodeConst [в случае addr/const]};
{$ifdef OPCODE_MODES}cmd_name: PShortString;{$endif}
addr_kind: integer; // 3 байта адреса(если необходимо) и kind (0..3)
callback: pointer;
// opused_callback_0{const} = function (params: integer; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd of object{TOpcodeBlock};
// opused_callback_1{addr} = function (params: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd of object{TOpcodeBlock};
// opused_callback_2{addr,const} = function (params: integer; const addr: TOpcodeAddress; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd of object{TOpcodeBlock};
// opused_callback_3{const x64. только для mov} = function (params: integer; const v_const: opused_const_64{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd of object{TOpcodeBlock};
diffcmd: record
case Integer of
-1: (ptr: pointer);
0: (_0: procedure{diffcmd_const32}(const Block: TOpcodeBlock; params: integer; const v_const: const_32; callback: opused_callback_0{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}));
1: (_1: procedure{diffcmd_addr}(const Block: TOpcodeBlock; params: integer; const addr: TOpcodeAddress; callback: opused_callback_1{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}));
2: (_2: procedure{diffcmd_addr_const}(const Block: TOpcodeBlock; params: integer; const addr: TOpcodeAddress; const v_const: const_32; callback: opused_callback_2{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}));
3: (_3: procedure{diffcmd_const64}(const Block: TOpcodeBlock; params: integer; const v_const: const_64; callback: opused_callback_3{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}));
end;
end;
POpcodeCmdPointer = ^TOpcodeCmdPointer;
// структура, благодаря которой можно получить универсальный
// доступ к данным
TOpcodeCmdData = record
Cmd: TOpcodeCmd;
case Integer of
0: (Bytes: array[word] of byte);
1: (Words: array[0..(high(word)+1) div 2 -1] of word);
2: (Dwords: array[0..(high(word)+1) div 4 -1] of dword);
3: (Str: PShortString);
end;
POpcodeCmdData = ^TOpcodeCmdData;
{$ifdef OPCODE_MODES}
// интерфейс для временного хранения текста (для ассемблера и гибрида)
TOpcodeTextBuffer = object
private
function InternalConst(const v_const: TOpcodeConst; const can_offsetted, use_sign: boolean; const Number: byte): PShortString;
public
value: record
case Integer of
0: (S: ShortString{max 255});
1: (bytes: array[0..511] of byte);
end;
function Format(const FmtStr: AnsiString; const Args: array of const; const Number: byte=0; const MakeLower: boolean=false): PShortString;
function Str(const S: pansichar; const Number: byte=0): PShortString;
function SizePtr(const params_ptr: integer; const Number: byte=0): PShortString;
function Const32(const v_const: const_32; const Number: byte=0): PShortString;
function Const64(const v_const: const_64; const Number: byte=0): PShortString;
function IntelAddress(const params: integer{x64}; const addr: TOpcodeAddress; const can_offsetted: boolean=true; const Number: byte=0): PShortString;
end;
{$endif}
(* POpcodeCell = ^TOpcodeCell;
TOpcodeCell = object
LocalPtr: integer; // смещение внутри данных функции, куда нужно прописать новый адрес
Correction: integer; // дополнительная коррекция смещения
end;
POpcodeExternalCell = ^TOpcodeExternalCell;
TOpcodeExternalCell = object(TOpcodeCell)
Relative: boolean; // тип смещения: относительное или прямое
__reserved: byte;
Reference: word; // внешний номер-идентификатор блока или NO_REFERENCE для переменной
end;
POpcodeCellInfo = ^TOpcodeCellInfo;
TOpcodeCellInfo = record
// для организации списка
Next: POpcodeCellInfo;
// переменная или функция
// которая сыграет роль при сортировке и уложении FFixupedInfo
Global: TOpcodeGlobal;
// сами данные по ячейке
// может быть и просто TOpcodeCell
Cell: TOpcodeExternalCell;
end; *)
// Под ячейкой понимается какое-то внутреннее хранилище, которое используется
// после рутины по фиксации, на финальном этапе доводки
//
// В бинарном режиме ячейки используются для менеджмента адресов блоков и глобальных переменных
// Используются как локальные смещения, так и глобальный адрес.
// При каждом изменении OFFSET (себя или другого глобального объекта) - некоторые ячейки нужно изменить.
// _
// Вся связанная с ячейками информация хранится в FFixupedInfo: экспортируемые блоки, локальные ячейки, внешние ячейки
//
//
// В текстовом режиме (ассемблер/гибрид) ячейки используются только как временное хранилище
// данных о локальном блоке и команде, которые используются для финальной подстановки его @номера вместо %s
// информация по локальной ячейке
// необходима только на этапе сбора
(* POpcodeLocalCell = ^TOpcodeLocalCell;
TOpcodeLocalCell = record
// смещение внутри данных функции, куда нужно прописать новый адрес
// если число отрицательное - то
LocalPtr: integer; // смещение внутри данных функции, куда нужно прописать новый адрес
Correction: integer; // дополнительная коррекция смещения
end;
{
TOpcodeExternalCell_Header = record
Global: TOpcodeGlobal;
Count: integer;
end;
}
TOpcodeExternalCell = record
LocalPtr: integer;
end; *)
{$ifndef PUREPASCAL}
procedure raise_not_realized_addr(CodeAddr: pointer);
begin
raise EOpcodeLib.Create('Command is not realized yet') at CodeAddr;
end;
{$endif}
procedure raise_not_realized;
{$ifdef PUREPASCAL}
begin
raise EOpcodeLib.Create('Command is not realized yet');
end;
{$else}
asm
{$ifdef CPUX86}
mov eax, [esp]
{$else .CPUX64}
mov RCX, [RSP]
{$endif}
jmp raise_not_realized_addr
end;
{$endif}
{$ifndef PUREPASCAL}
procedure raise_parameter_addr(CodeAddr: pointer);
begin
raise EOpcodeLib.Create('Wrong parameter') at CodeAddr;
end;
{$endif}
procedure raise_parameter;
{$ifdef PUREPASCAL}
begin
raise EOpcodeLib.Create('Wrong parameter');
end;
{$else}
asm
{$ifdef CPUX86}
mov eax, [esp]
{$else .CPUX64}
mov RCX, [RSP]
{$endif}
jmp raise_parameter_addr
end;
{$endif}
{ TOpcodeHeap }
const
// размер пула по умолчанию (для внутреннего менеджмента памяти)
DEFAULT_POOL_SIZE = 2*1024; // 2kb
constructor TOpcodeHeap.Create;
begin
inherited;
FState.PoolSize := DEFAULT_POOL_SIZE;
end;
procedure TOpcodeHeap.NewPool();
begin
GetMem(FState.Current, FState.PoolSize);
pointer(FState.Current^) := FState.Pool;
FState.Pool := FState.Current;
Inc(NativeInt(FState.Current), sizeof(Pointer));
FState.Margin := FState.PoolSize-sizeof(Pointer);
end;
// выделить необходимый блок памяти в куче
function TOpcodeHeap.Alloc(const Size: integer): pointer;
var
NewPoolSize: integer;
begin
if (FState.Margin < Size) then
begin
NewPoolSize := (sizeof(Pointer)+Size+(DEFAULT_POOL_SIZE-1)) and -DEFAULT_POOL_SIZE;
if (NewPoolSize > FState.PoolSize) then FState.PoolSize := NewPoolSize;
NewPool();
end;
Result := FState.Current;
Inc(NativeInt(FState.Current), Size);
Dec(FState.Margin, Size);
end;
{$ifdef OPCODE_MODES}
function TOpcodeHeap.Format(const FmtStr: ShortString; const Args: array of const): PShortString;
var
Count: integer;
begin
if (FState.Margin < 16) then NewPool();
Count := SysUtils.FormatBuf(pointer(NativeInt(FState.Current)+1)^, FState.Margin, FmtStr[1], Length(FmtStr), Args);
if (Count = FState.Margin) then
begin
NewPool();
Count := SysUtils.FormatBuf(pointer(NativeInt(FState.Current)+1)^, FState.Margin, FmtStr[1], Length(FmtStr), Args);
end;
if (Count < 0) or (Count > high(byte)) then raise_parameter;
Result := FState.Current;
pbyte(Result)^ := Count;
inc(Count);
inc(NativeInt(FState.Current), Count);
dec(FState.Margin, Count);
end;
{$endif}
destructor TOpcodeHeap.Destroy;
var
Pool, NewPool: pointer;
begin
Pool := FState.Pool;
while (Pool <> nil) do
begin
NewPool := Pointer(Pool^);
FreeMem(Pool);
Pool := NewPool;
end;
inherited;
end;
// удалить все пулы кроме первого
procedure TOpcodeHeap.Clear();
var
NewPool: pointer;
begin
if (FState.Pool <> nil) then
begin
while (true) do
begin
NewPool := Pointer(FState.Pool^);
if (NewPool = nil) then break;
FreeMem(FState.Pool);
FState.Pool := NewPool;
end;
FState.Current := FState.Pool;
FState.Margin := DEFAULT_POOL_SIZE;
FState.PoolSize := DEFAULT_POOL_SIZE;
end;
end;
procedure TOpcodeHeap.SaveState(var HeapState: TOpcodeHeapState);
begin
HeapState := FState;
end;
procedure TOpcodeHeap.RestoreState(const HeapState: TOpcodeHeapState);
var
NewPool, Pool: pointer;
begin
Pool := Self.FState.Pool;
while (Pool <> HeapState.Pool) do
begin
NewPool := Pointer(Pool^);
FreeMem(Pool);
Pool := NewPool;
end;
FState := HeapState;
end;
function const32(const Value: Integer): const_32;
begin
Result.Kind := ckValue;
Result.Value := Value;
end;
function const32(const pValue: PInteger): const_32;
begin
Result.Kind := ckPValue;
Result.pValue := pValue;
end;
{$ifdef OPCODE_MODES}
function const32(const Condition: PAnsiChar; const Offseted: boolean=false): const_32;
begin
if (not Offseted) then
begin
Result.Kind := ckCondition;
Result.Condition := Condition;
end else
begin
Result.Kind := ckOffsetedCondition;
Result.OffsetedCondition := Condition;
end;
end;
{$endif}
function const32(const Proc: TOpcodeProc): const_32;
begin
Result.Kind := ckBlock;
Result.Block := Proc.B_prefix.uni;
end;
function const32(const Block: POpcodeBlock): const_32;
begin
Result.Kind := ckBlock;
Result.Block := Block;
end;
function const32(const Variable: TOpcodeVariable; const Offset: Integer=0): const_32;
begin
Result.Kind := ckVariable;
Result.Variable := Variable;
Result.VariableOffset := Offset;
end;
function const64(const Value: Int64): const_64;
begin
Result.Kind := ckValue;
Result.Value := Value;
end;
function const64(const pValue: PInt64): const_64;
begin
Result.Kind := ckPValue;
Result.pValue := pValue;
end;
{$ifdef OPCODE_MODES}
function const64(const Condition: PAnsiChar; const Offseted: boolean=false): const_64;
begin
if (not Offseted) then
begin
Result.Kind := ckCondition;
Result.Condition := Condition;
end else
begin
Result.Kind := ckOffsetedCondition;
Result.OffsetedCondition := Condition;
end;
end;
{$endif}
function address86(const reg: reg_x86_addr; const offset: integer=0): address_x86;
begin
Result.reg := reg;
Result.scale := x1;
Result.offset.Kind := ckValue;
Result.offset.Value := offset;
end;
function address86(const reg: reg_x86_addr; const scale: intel_scale; const plus: reg_x86_addr; const offset: integer=0): address_x86;
begin
Result.reg := reg;
Result.scale := scale;
Result.plus := plus;
Result.offset.Kind := ckValue;
Result.offset.Value := offset;
end;
{$ifdef OPCODE_MODES}
function address86(const reg: reg_x86_addr; const scale: intel_scale; const plus: reg_x86_addr; const Condition: PAnsiChar; const Offseted: boolean=false): address_x86; overload;
begin
Result.reg := reg;
Result.scale := scale;
Result.plus := plus;
if (not Offseted) then
begin
Result.offset.Kind := ckCondition;
Result.offset.Condition := Condition;
end else
begin
Result.offset.Kind := ckOffsetedCondition;
Result.offset.OffsetedCondition := Condition;
end;
end;
{$endif}
function address64(const reg: reg_x64_addr; const offset: integer=0): address_x64;
begin
Result.reg := reg;
Result.scale := x1;
Result.offset.Kind := ckValue;
Result.offset.Value := offset;
end;
function address64(const reg: reg_x64_addr; const scale: intel_scale; const plus: reg_x64_addr; const offset: integer=0): address_x64;
begin
Result.reg := reg;
Result.scale := scale;
Result.plus := plus;
Result.offset.Kind := ckValue;
Result.offset.Value := offset;
end;
{$ifdef OPCODE_MODES}
function address64(const reg: reg_x64_addr; const scale: intel_scale; const plus: reg_x64_addr; const Condition: PAnsiChar; const Offseted: boolean=false): address_x64; overload;
begin
Result.reg := reg;
Result.scale := scale;
Result.plus := plus;
if (not Offseted) then
begin
Result.offset.Kind := ckCondition;
Result.offset.Condition := Condition;
end else
begin
Result.offset.Kind := ckOffsetedCondition;
Result.offset.OffsetedCondition := Condition;
end;
end;
{$endif}
{ TOpcodeGlobal }
constructor TOpcodeGlobal.Create;
begin
if (Storage = nil) then
raise EOpcodeLib.CreateFmt('You can not call constructor of %s class', [Self.ClassName]);
end;
destructor TOpcodeGlobal.Destroy;
var
Index: integer;
begin
Index := ord(TClass(Pointer(Self)^) <> TOpcodeVariable);
// что-то с подпиской ???
if (FSubscribedProcs <> nil) then
raise EOpcodeLib.CreateFmt('%s instance has subscribed procs', [Self.ClassName]);
// список
if (Storage <> nil) then
with Storage do
begin
// исключение из (двусвязного) списка
if (FPrev.uni = nil) then
begin
F.Globals[Index] := FNext.uni;
FNext.uni.FPrev.uni := nil;
end else
begin
FPrev.uni.FNext.uni := Self.FNext.uni;
if (Self.FNext.uni <> nil) then Self.FNext.uni.FPrev.uni := Self.FPrev.uni;
end;
// добавление в (односвязный) список свободных элементов
Self.FNext.uni := FFreeGlobals[Index];
FFreeGlobals[Index] := Self;
end;
// освободить память, универсальный подход
if (FSize <> 0) then
Self.Size := 0;
// память внутри функции
if (Index <> 0) then
with TOpcodeProc(Self) do
begin
if (FOwnHeap) then FHeap.Free;
if (FFixupedInfo <> nil) then FreeMem(FFixupedInfo);
end;
// предка вызывать не обязательно, там пусто
// inherited;
end;
// делать стандартную очистку памяти+FreeMem имеет только в том случае, если
// переменная создана стандартным образом (без хранилища)
//
// к тому же я надеюсь, никаких сложных типов (строки, дин массивы) в потомках не хранятся
procedure TOpcodeGlobal.FreeInstance;
begin
if (Storage = nil) then
inherited;
end;
procedure TOpcodeGlobal.SetSize(const Value: integer);
var
NewAlignedSize: integer;
begin
NewAlignedSize := (Value + 3) and -4;
if (FAlignedSize = NewAlignedSize) then
begin
FSize := Value;
exit;
end;
// память
if (Storage <> nil) and (Storage.JIT) and {Self is TOpcodeProc}(TClass(Pointer(Self)^) <> TOpcodeVariable) then
begin
if (FMemory <> nil) then Storage.JIT_Free(FMemory);
if (NewAlignedSize = 0) then FMemory := nil
else FMemory := Storage.JIT_Alloc(NewAlignedSize);
OFFSET := NativeInt(FMemory);
end else
begin
if (FMemory <> nil) then FreeMem(FMemory);
if (NewAlignedSize = 0) then FMemory := nil
else GetMem(FMemory, NewAlignedSize);
end;
// поля
FAlignedSize := NewAlignedSize;
FSize := Value;
end;
procedure TOpcodeGlobal.Set_OFFSET(const Value: integer);
var
subscr: POpcodeSubscribe;
begin
{$ifdef OPCODE_MODES}
if (Storage.FMode <> omBinary) then
raise EOpcodeLib.Create('OFFSET can be changed only in Binary mode');
{$endif}
// смещение
FOFFSET := Value;
// сигналы всем функциям
subscr := FSubscribedProcs;
while (subscr <> nil) do
begin
// todo subscr.Proc.
subscr := subscr.Next;
end;
end;
{ TOpcodeStorage }
constructor TOpcodeStorage.Create(const AHeap: TOpcodeHeap
{$ifdef OPCODE_MODES}; const AMode: TOpcodeMode{$endif});
begin
inherited Create;
FHeap := AHeap;
FOwnHeap := (AHeap = nil);
if (FOwnHeap) then FHeap := TOpcodeHeap.Create;
{$ifdef OPCODE_MODES}
FMode := AMode;
{$endif}
end;
destructor TOpcodeStorage.Destroy;
begin
// todo все функции и переменные ?
if (FOwnHeap) then FHeap.Free;
// если было занято JIT пространство
if (FJIT) then
begin
{$ifdef MSWINDOWS}
if (FJITHeap <> 0) then Windows.HeapDestroy(FJITHeap);
{$else}
{$MESSAGE 'Look JIT memory manager!'}
{$endif}
end;
inherited;
end;
function TOpcodeStorage.JIT_Alloc(const Size: integer): pointer;
begin
{$ifdef MSWINDOWS}
// создаём кучу если первый аллок
if (FJITHeap = 0) then FJITHeap := Windows.HeapCreate($00040000{HEAP_CREATE_ENABLE_EXECUTE}, 0, 0);
// выделение
Result := Windows.HeapAlloc(FJITHeap, 0, Size);
{$else}
{$MESSAGE 'Look JIT memory manager!'}
Result := nil;
{$endif}
// проверка диапазона на x64
{$ifdef CPUX64}
if ((NativeInt(Result)+NativeInt(Size)) >= high(Integer)) then
raise EOpcodeLib.Create('Address range overflow. You should use less virtual memory or call JIT routine before large memory allocating');
{$endif}
end;
procedure TOpcodeStorage.JIT_Free(const Proc: pointer);
begin
{$ifdef MSWINDOWS}
Windows.HeapFree(FJITHeap, 0, Proc);
{$else}
{$MESSAGE 'Look JIT memory manager!'}
{$endif}
end;
procedure TOpcodeStorage.SubscribeGlobal(var List: POpcodeSubscribe; const Global: TOpcodeGlobal);
var
Result: POpcodeSubscribe;
begin
// ищем. возможно такой объект уже есть в подписке
Result := List;
while (Result <> nil) do
begin
if (Result.Global = Global) then exit;
Result := Result.Next;
end;
// выделяем структуру
if (FSubscrBuffer <> nil) then
begin
Result := FSubscrBuffer;
FSubscrBuffer := Result.Next;
end else
with FHeap do
if (FState.Margin >= sizeof(TOpcodeSubscribe)) then
begin
Result := FState.Current;
Inc(NativeInt(FState.Current), sizeof(TOpcodeSubscribe));
Dec(FState.Margin, sizeof(TOpcodeSubscribe));
end else
begin
Result := Alloc(sizeof(TOpcodeSubscribe));
end;
// объект
Result.Global := Global;
// заносим в список
Result.Next := List;
List := Result;
end;
procedure TOpcodeStorage.UnsubscribeGlobal(var List: POpcodeSubscribe; const Global: TOpcodeGlobal);
var
Prev, Item: POpcodeSubscribe;
begin
Prev := nil;
Item := List;
if (Item = nil) then exit;
// ищем элемент
while (Item.Global <> Global) do
begin
Prev := Item;
Item := Item.Next;
if (Item = nil) then exit;
end;
// удаляем из списка
if (Prev = nil) then List := Item.Next
else Prev.Next := Item;
// добавляем Item в буфер
Item.Next := FSubscrBuffer;
FSubscrBuffer := Item;
end;
// предназначение этой функции добавить список элементов в FSubscrBuffer
// возможно потом добавится другой функционал
procedure TOpcodeStorage.ReleaseSubscribeList(const List: POpcodeSubscribe);
var
Last: POpcodeSubscribe;
begin
if (List <> nil) then
begin
if (FSubscrBuffer = nil) then FSubscrBuffer := List
else
begin
Last := List;
while (Last.Next <> nil) do Last := Last.Next;
Last.Next := FSubscrBuffer;
FSubscrBuffer := List;
end;
end;
end;
function TOpcodeStorage.CreateInstance(const AClass: TClass): TOpcodeGlobal;
const
OFFSET = sizeof(TClass)+sizeof(TOpcodeStorage)+2*sizeof(TOpcodeGlobal);
var
{Index,} Size: integer;
begin
// если можно - берём из списка свободных
// иначе выделяем в куче
Size{Index} := ord(AClass <> TOpcodeVariable);
Result := FFreeGlobals[Size{Index}];
if (Result <> nil) then
begin
FFreeGlobals[Size{Index}] := Result.FNext.uni;
Size := PInteger(@PAnsiChar(AClass)[vmtInstanceSize])^; // AClass.InstanceSize
end else
begin
with FHeap do
begin
Size := NativeInt(FState.Current) and 3;
if (Size <> 0) then
begin
Size := 4-Size;
Inc(NativeInt(FState.Current), Size);
Dec(FState.Margin, Size);
end;
Size := PInteger(@PAnsiChar(AClass)[vmtInstanceSize])^; // AClass.InstanceSize
if (FState.Margin >= Size) then
begin
Result := FState.Current;
Inc(NativeInt(FState.Current), Size);
Dec(FState.Margin, Size);
end else
begin
Result := Alloc(Size);
end;
end;
TClass(Pointer(Result)^) := AClass;
Result.FStorage.uni := Self;
end;
// чистка памяти
FillChar(Pointer(NativeInt(Result)+OFFSET)^, Size-OFFSET, #0);
// добавление в список
Size{Index} := ord(AClass <> TOpcodeVariable);
Result.FPrev.uni := nil;
Result.FNext.uni := F.Globals[Size{Index}];
F.Globals[Size{Index}] := Result;
if (Result.FNext.uni <> nil) then Result.FNext.uni.FPrev.uni := Result;
end;
function TOpcodeStorage.InternalCreateProc(const ProcClass: TOpcodeProcClass; const Callback: pointer; const AOwnHeap: boolean{=false}): TOpcodeProc;
var
H: TOpcodeHeap;
begin
Result := TOpcodeProc(CreateInstance(ProcClass));
H := nil;
if (not AOwnHeap) then H := Heap;
Result.Create(H{$ifdef OPCODE_MODES},Mode{$endif});
@Result.FCallback := Callback;
end;
function TOpcodeStorage.CreateVariable(const Size: integer): TOpcodeVariable;
begin
{$ifdef OPCODE_MODES}
if (Mode <> omBinary) then
raise EOpcodeLib.Create('Variable can be created only in Binary mode');
{$endif}
Result := TOpcodeVariable(CreateInstance(TOpcodeVariable));
// конструктор вызывать незачем Result.Create();
if (Size <> 0) then Result.Size := Size;
end;
{ TOpcodeProc }
// функция инициализации всех рабочих полей, инициализация блоков, чистит Heap (если собственный)
// вызывается в конструкторе автоматически
// но может понадобиться для новой перезаписи функции
// (поле RetN остаётся неизменным)
procedure TOpcodeProc.Initialize();
const
BLOCKS_COUNT = 5;
BLOCKS_SIZE = BLOCKS_COUNT*sizeof(TOpcodeBlock);
type
TBlocksArray = array[0..BLOCKS_COUNT-1] of TOpcodeBlock;
var
Blocks: ^TBlocksArray;
NIL_VALUE: pointer;
NO_FIX_REF: integer;
NEXT_BLOCK: POpcodeBlock;
begin
// если куча своя - имеет смысл её подчистить тоже
// особенно если куча своя
if (OwnHeap) and ({make faster}Heap.FState.Pool <> nil) then Heap.Clear();
// поля
{$ifdef OPCODE_MODES}
F.BlocksReferenced := ord(Self.Mode=omBinary);
{$else}
F.BlocksReferenced := 1; // F.BlocksReferenced := 0; \ prefix.MakeReference();
{$endif}
NIL_VALUE{make_smaller} := nil;
FLastBinaryCmd := NO_CMD;
FLastHeapCurrent := NIL_VALUE;
FCells := NIL_VALUE;
// первоначальные блоки заполняются скопом (быстро)
with Heap do
begin
Blocks := FState.Current;
if (FState.Margin >= BLOCKS_SIZE) then
begin
Inc(NativeInt(FState.Current), BLOCKS_SIZE);
Dec(FState.Margin, BLOCKS_SIZE);
end else
begin
Blocks := Alloc(BLOCKS_SIZE);
end;
end;
// FillChar(Blocks^, BLOCKS_SIZE, 0);
// call_modes
NO_FIX_REF{make_smaller} := NO_FIXUPED or (NO_REFERENCE shl 16);
B_call_modes.uni := @Blocks^[0];
Blocks^[0].CmdList := NIL_VALUE;
Blocks^[0].P.Proc := Self;
NEXT_BLOCK := @Blocks^[1];
Blocks^[0].N.Next := NEXT_BLOCK;
Blocks^[0].O.Value := NO_FIX_REF;
// prefix
B_prefix.uni := NEXT_BLOCK;
Blocks^[1].CmdList := NIL_VALUE;
Blocks^[1].P.Proc := Self;
NEXT_BLOCK := @Blocks^[2];
Blocks^[1].N.Next := NEXT_BLOCK;
Blocks^[1].O.Value := NO_FIXUPED; // B_prefix.uni.O.Reference := 0;
{$ifdef OPCODE_MODES}
if (Self.Mode <> omBinary) then Blocks^[1].O.Value := NO_FIX_REF;
{$endif}
// start
B_start.uni := NEXT_BLOCK;
Blocks^[2].CmdList := NIL_VALUE;
Blocks^[2].P.Proc := Self;
NEXT_BLOCK := @Blocks^[3];
Blocks^[2].N.Next := NEXT_BLOCK;
Blocks^[2].O.Value := NO_FIX_REF;
// finish
B_finish.uni := NEXT_BLOCK;
Blocks^[3].CmdList := NIL_VALUE;
Blocks^[3].P.Proc := Self;
NEXT_BLOCK := @Blocks^[4];
Blocks^[3].N.Next := NEXT_BLOCK;
Blocks^[3].O.Value := NO_FIX_REF;
// postfix
B_postfix.uni := NEXT_BLOCK;
Blocks^[4].CmdList := NIL_VALUE;
Blocks^[4].P.Proc := Self;
Blocks^[4].N.Next := NIL_VALUE;
Blocks^[4].O.Value := NO_FIX_REF;
end;
// выделяем память под внутренний буфер
procedure TOpcodeProc.AllocFixupedInfo(const Size: integer{может перевести в каунты ?});
begin
if (FFixupedInfo <> nil) then FreeMem(FFixupedInfo);
if (Size <> 0) then GetMem(FFixupedInfo, Size);
end;
constructor TOpcodeProc.Create(const AHeap: TOpcodeHeap{$ifdef OPCODE_MODES}; const AMode: TOpcodeMode{$endif});
begin
// Предок не вызывается! Там Exception!
// inherited Create;
FHeap := AHeap;
FOwnHeap := (AHeap = nil);
if (FOwnHeap) then FHeap := TOpcodeHeap.Create;
{$ifdef OPCODE_MODES}
FMode := AMode;
{$endif}
@FCallback := @raise_not_realized;
// вся инициализация блоков
Initialize();
end;
(* деструктор делается в предке
destructor TOpcodeProc.Destroy;
begin
if (FOwnHeap) then FHeap.Free;
if (FFixupedInfo <> nil) then FreeMem(FFixupedInfo);
inherited;
end;*)
const
// флаг, который показывает, что блок (1 команда или ряд) является текстовой
// это нужно для сбора текстов и бинарных блоков в случае гибрида
// в одном блоке не могут находиться одновременно текстовые и бинарные данные.
// собственно проверка на текстовость очень простая - если меньше нуля, значит текст
{$ifdef OPCODE_MODES}
REFID_FLAG_TEXT = Integer(1 shl 31);
{$endif}
// "флаг", указывающий, что выше существуют блоки, в которые есть прыжки
REFID_ISNEXT = Integer(1 shl 30);
// команды, требующие особого внимания - всегда располагаются в отдельном блоке
// обычная последовательность команд обозначается последовательностью (команда, Count>0, next)
// для всех особых случаев Count(SingleMode) <= 0
(*SINGLE_MODE_EMPTY = 0;
SINGLE_MODE_LEAVE = -1;
SINGLE_MODE_LEAVE_JOINED = -2;
SINGLE_MODE_JOINED = -3;
SINGLE_MODE_JUMP_BLOCK = -4;
SINGLE_MODE_INLINE = -5{!!!};
*)
// размер буферизируемых на стеке массивов
// (должно хватить для большинства случаев)
STACK_BUFFERED_SIZE = 300;
// размер буфера нескольких прыжков подряд
JUMP_STACK_SIZE = 30;
type
// тип информации, которая хранится в блоке
TFixupedKind = (fkEmpty, // пустой блок (при оптимизациях такое может произойти. в этом случае весь value равен 0)
fkNormal, // стандартная ситуация
fkJoined, // add edx, [... + offset ...] / mov esi, offset @1
fkLeaveJoined, // jmp [... + offset ...]
fkLeave, // ret(n), leave, jmp reg, jmp mem
fkGlobalJumpBlock, // call axml_get_attribute / jne PRE_cmd_ptr_addr_const
fkLocalJumpBlock, // jnle @2 / call @Specifier
fkInline // pop esi, pop edi, ret
);
// внутреннее структура
// представляющая блок команд
// из суммы таких блоков в конечном счёте получается бинарное(текстовое) представление
// 16(+4) байт под x86, 20(+4) байт под x64
PFixupedBlockArray = ^TFixupedBlockArray;
PFixupedBlock = ^TFixupedBlock;
TFixupedBlock = packed record
case Integer of
0: (RefId: integer); // используется для живых/нумерованых блоков. + указывается текстовость/бинарность
1: (Offset: integer{используется для бинарных ячеек: прыжков и call}; Size: integer{используется для бинарной записи});
{$ifdef OPCODE_MODES}
2: (_: integer;
HybridSize_Min: integer; {text length?}
case Integer of
0: (HybridSize_Max: integer);
1: (Number: integer{используется для нумерации в ассемблере и гибриде});
);
{$endif}
3: (header_info: array[0..1{$ifdef OPCODE_MODES}+1{$endif}] of integer;
case boolean of
false: (Value: integer; Cmd: POpcodeCmd);
true: (Kind: TFixupedKind;
case TFixupedKind of
// пустой блок (при оптимизациях такое может произойти. в этом случае весь value равен 0)
fkEmpty: ({в этом случае весь Value равен 0});
// стандартная ситуация
fkNormal: ({Cmd. Количество = (Value shr 8)});
// add edx, [... + offset ...] / mov esi, offset @1
fkJoined: ({Cmd + Cmd.Next});
// jmp [... + offset ...]
fkLeaveJoined: ({Cmd + Cmd.Next});
// ret(n), leave, jmp reg, jmp mem
fkLeave: ({Cmd});
fkGlobalJumpBlock,
fkLocalJumpBlock,
fkInline: ( // для прыжков в блок - стандартная ситуация
// для inline в случае <0 (-2) нет jncc прыжка
// смещение, бинарность/текстовость прыжка в этом случае определяется по размеру(ам) блока!
// получается inline-команду можно пропускать если mask = mask and jmp_dest_mask[]
// для этого как раз в inline и указывается -2(call) что если нет условия - пропускать нельзя
cc_ex: shortint;
case TFixupedKind of
fkGlobalJumpBlock: (Reference: word;
{$ifdef OPCODE_MODES}
case Boolean of
false: (Proc: TOpcodeProc);
true: (ProcName: pansichar);
{$else}
Proc: TOpcodeProc
{$endif}
);
// прыжок сначала содержит общую информацию
// потом чаще всего имеет бинарное представление
fkLocalJumpBlock: (Fixuped: word; JumpOffset: integer);
fkNormal: (JumpBuffer: array[0..5] of byte);
// важно, что заинлайненные блоки не имеют RefId !!!
// в случае если инлайн прыжковый, то для бинарной/гибридной
// реализации буфер располагается после InlineBlocks (4 байта)
//
// ещё важно понимать, что inline-последовательность это
// всегда бинарная последовательность (в гибриде тоже)
// связано это с размером команд и условиями оптимизации пр
// кстати ещё нужно будет подумать про VM-реализацию
fkInline: (InlineBlocksCount: word; InlineBlocks: PFixupedBlockArray);
);
););
end;
TFixupedBlockArray = array[0..{0}1] of TFixupedBlock;
TWordArray = array[0..0] of Word;
PWordArray = ^TWordArray;
TIntegerArray = array[0..0] of Integer;
PIntegerArray = ^TIntegerArray;
// массив для локальных прыжков (чтобы потом их оптимизировать)
TLocalJumpsArray = array[0..0] of PFixupedBlock;
PLocalJumpsArray = ^TLocalJumpsArray;
// массив имён прыжков
// нужен для (автоматической) текстовой реализации
{$ifdef OPCODE_MODES}
TLocalJumpsNames = array[-2{call,jmp}..ord(high(intel_cc))] of PShortString;
{$endif}
// общее хранилище (информация) по фиксации
// вся необходимая справочная информация здесь содержиться + дополняется
// в зависимости от разных проходов "компилятора"
TFixupedStorage = record
// общая информация
// нужна в первую очередь для обращения к куче
// Proc нужна для отслеживания режима + виртуальные функции
Heap: TOpcodeHeap;
Proc: TOpcodeProc;
{$ifdef OPCODE_MODES}
Mode: TOpcodeMode;
{$endif}
// механизм, позволяющий очистить от FixupedBlock целые линии блоков
// первый блок находится внутри, в случае нескольких линий - довыделяются куски из кучи
SubscribedLines: TOpcodeSubscribe;
// "не настоящий" блок, спользуемый главным образом для UnpointerCmd
FakeBlock: TOpcodeBlock;
// буферизированные переменные (чтобы увеличить эффективность регистров)
Current: POpcodeBlock;
CurrentRefId: dword;
StartBlock: integer;
TopResult: PFixupedBlock;
// организация массива фиксированных блоков
BlocksCount: integer;
BlocksAvailable: integer; // количество доступных в памяти блоков
Blocks: PFixupedBlockArray; // рабочий массив блоков (если не равно @BlocksBuffer - то выделен в куче)
EndBlock: PFixupedBlock; // последний (Ret-) блок. нужен для алгоритмов
// массив локальных прыжков, заканчивающийся NO_JUMP
LocalJumpsCount: integer;
LocalJumps: PLocalJumpsArray;
{$ifdef OPCODE_MODES}
TextBuffer: pansichar;
// информация по меткам (нужна только для текстовых режимов)
LabelCount: integer;
LabelLength: integer;
// буфер бинарных данных
BinaryBuffer: pointer;
BinarySize: integer;
{$endif}
// массив номеров блоков, на которые есть ссылки
References: PWordArray;
// имитация команды заключительной команды ret(n),
// которая нужна для последнего блока при фиксации
LastRetCmd: record {TOpcodeCmd}
Cmd: TOpcodeCmd;
case Integer of
0: (c3: byte);
1: (c2: byte; i16: word);
2: (arm_value: integer);
{$ifdef OPCODE_MODES}
3: (Str: PShortString; Chars: string[9]{ret 65535});
{$endif}
end;
// необходимая табличная информация
// для базовой оптимизиции (и текстовой реализации) прыжков
JumpsInfo: record
// размеры большого и малого прыжка
small_sizes: array[-2{call,jmp}..ord(high(intel_cc))] of byte;
big_sizes: array[-2{call,jmp}..ord(high(intel_cc))] of byte;
// специализированные таблицы для определения, можно ли вообще,
// имея величину смещения, преобразовать прыжок до малого
//
// например для intel можно сжимать прыжки если -126 <= offset <= 131
low_ranges: array[-2{call,jmp}..ord(high(intel_cc))] of integer;
high_ranges: array[-2{call,jmp}..ord(high(intel_cc))] of integer;
// имена (для текстовой реализации)
{$ifdef OPCODE_MODES}
names: ^TLocalJumpsNames{^array[-2..ord(high(intel_cc))] of PShortString};
{$endif}
end;
// буферы на стеке, которых хватит в большинстве случаев
BlocksBuffer: array[0..STACK_BUFFERED_SIZE-1] of TFixupedBlock;
LocalJumpsBuffers: array[0..STACK_BUFFERED_SIZE-1+1] of PFixupedBlock;
ReferencesBuffer: array[0..STACK_BUFFERED_SIZE-1] of word;
end;
// увеличить увеличить массив блоков вдвое
// на практике такого происходить практически не будет
// но на всякий случай заложиться стоит
procedure GrowFixupedBlocks(var Storage: TFixupedStorage);
begin
with Storage do
begin
BlocksAvailable := BlocksAvailable*2;
if (Blocks = pointer(@BlocksBuffer)) then
begin
GetMem(Blocks, BlocksAvailable*sizeof(TFixupedBlock));
CopyMemory(Blocks, @BlocksBuffer, sizeof(BlocksBuffer));
end else
begin
ReallocMem(Blocks, BlocksAvailable*sizeof(TFixupedBlock));
end;
end;
end;
// функция, получающая из временной (с указателем) команды
// команду из рассчёта текущего значения
function UnpointerCmd(var Storage: TFixupedStorage; const CmdPointer: POpcodeCmdPointer): POpcodeCmd;
var
addr: TOpcodeAddress;
v_const: TOpcodeConst;
p_const: ^const_32;
callback: TMethod;
begin
pinteger(@addr.F.Bytes)^ := CmdPointer.addr_kind and $00ffffff; // addr + kind=ckValue
v_const.Kind := ckValue;
callback.Data := nil;
callback.Code := CmdPointer.callback;
// вызываем
case byte(CmdPointer.addr_kind shr 24) of
0: begin
v_const.F.Value := pinteger(CmdPointer.pvalue)^;
CmdPointer.diffcmd._0(Storage.FakeBlock, CmdPointer.params, const_32(v_const),
opused_callback_0(callback){$ifdef OPCODE_MODES},CmdPointer.cmd_name^{$endif});
end;
1: begin
addr.offset.F.Value := pinteger(CmdPointer.pvalue)^;
CmdPointer.diffcmd._1(Storage.FakeBlock, CmdPointer.params, addr,
opused_callback_1(callback){$ifdef OPCODE_MODES},CmdPointer.cmd_name^{$endif});
end;
2: begin
p_const := CmdPointer.pvalue;
addr.offset := p_const^;
if (addr.offset.Kind = ckPValue) then
begin
addr.offset.Value := addr.offset.pValue^;
addr.offset.Kind := ckValue;
end;
inc(p_const);
v_const := p_const^;
if (v_const.Kind = ckPValue) then
begin
v_const.F.Value := v_const.F.pValue^;
v_const.Kind := ckValue;
end;
CmdPointer.diffcmd._2(Storage.FakeBlock, CmdPointer.params, addr, const_32(v_const),
opused_callback_2(callback){$ifdef OPCODE_MODES},CmdPointer.cmd_name^{$endif});
end;
3: begin
v_const.F.Value64 := pint64(CmdPointer.pvalue)^;
CmdPointer.diffcmd._3(Storage.FakeBlock, CmdPointer.params, const_64(v_const),
opused_callback_3(callback){$ifdef OPCODE_MODES},CmdPointer.cmd_name^{$endif});
end;
end;
Result := Storage.FakeBlock.CmdList;
Storage.Proc.FLastBinaryCmd := NO_CMD;
end;
// используется так же вспомогательная функция,
// которая вызывается если нужен блок, которого ещё нет среди Fixuped-блоков
function AddFixupedBlocksLineAsLink(var Storage: TFixupedStorage; const CurrentResult: PFixupedBlock; Block: POpcodeBlock=nil): PFixupedBlock; forward;
// теоретически рекурсивная функция. на практике скорее всего вызов будет один
// задача функции - распознать линию блоков, прописать списки команд, заполнить все необходимые поля
// в общем распознать и подготовить к платформозависимой оптимизации и реализации прыжков
//
// алгоритм построен таким образом, что сначала добавляется линия,
// а потом вторая итерация по всем локальным прыжкам - добавляются недобавленные
procedure AddFixupedBlocksLine(var Storage: TFixupedStorage{; const OpcodeBlock: POpcodeBlock});
label
line_loop, opcodeblock_loop, line_loop_continue, line_loop_finished,
first_iteration, second_iteration;
var
Result: PFixupedBlock;
OpcodeBlock: POpcodeBlock;
Reference: integer;
flags: integer{универсальный флаг-хранилище};
AdvBlocksCount: integer;
BottomCmd, Cmd: POpcodeCmd;
Subscr: POpcodeSubscribe;
i, Fixuped: integer;
JoinedData: POpcodeJoinedData;
begin
// добавляем OpcodeBlock в список линий, которые потом будут очищаться
if (Storage.SubscribedLines.Block = nil) then
begin
Storage.SubscribedLines.Block := Storage.Current{OpcodeBlock};
end else
begin
with Storage.Heap do
begin
Subscr := FState.Current;
if (FState.Margin >= sizeof(TOpcodeSubscribe)) then
begin
Inc(NativeInt(FState.Current), sizeof(TOpcodeSubscribe));
Dec(FState.Margin, sizeof(TOpcodeSubscribe));
end else
begin
Subscr := Alloc(sizeof(TOpcodeSubscribe));
end;
end;
Subscr.Block := Storage.Current{OpcodeBlock};
Subscr.Next := Storage.SubscribedLines.Next;
Storage.SubscribedLines.Next := Subscr;
end;
flags := Storage.BlocksCount;
Storage.StartBlock := flags;
// линия блоков заканчивается каким-то блоком (обозначаем его OpcodeBlock)
// он либо nil (ret(n)/прыжок в конец), либо другой уже обозначенный блок (прыжок в него)
// каждому добавленному блоку прописываем RefId из CurrentRefId
// Current - это тот, с которого надо начинать добавление
line_loop:
begin
// даже если Current это список пустых блоков, упирающихся в ранее созданный -
// фиксированный блок создаётся (добавляется) в любом случае
{$ifdef OPCODE_TEST}
if (flags = NO_FIXUPED) then raise_parameter;
{$endif}
if (flags = Storage.BlocksAvailable) then GrowFixupedBlocks(Storage);
Result := @Storage.Blocks[flags];
OpcodeBlock := Storage.Current;
OpcodeBlock.O.Fixuped := flags;
// прописываем RefId (который записан CurrentRefId)
Result.RefId := Storage.CurrentRefId;
// inc(Storage.BlocksCount);
Storage.BlocksCount := flags+1;
// инициализируем OpcodeBlock
// если он пустой - идём на следующую итерацию
// + если есть внешняя ссылка - добавляем 1 (и прописываем в массив)
// если список заканчивается (nil) или упирается в какой-то известный блок - прыгаем туда
opcodeblock_loop:
begin
// номер Fixuped-блока
OpcodeBlock.O.Fixuped := flags;
// внешняя ссылка
Reference := OpcodeBlock.O.Reference;
if (Reference <> NO_REFERENCE) then
begin
inc(Result.RefId);
Storage.References[Reference] := flags;
end;
// прописываем блок в буфер - на будущее
Storage.Current := OpcodeBlock;
// если пустой - идём на следующую итерацию
if (OpcodeBlock.CmdList = nil) then
begin
OpcodeBlock := OpcodeBlock.N.Next;
if (OpcodeBlock = nil) or (OpcodeBlock.O.Fixuped <> NO_FIXUPED) then
begin
Storage.Current := OpcodeBlock;
goto line_loop_finished;
end;
goto opcodeblock_loop;
end;
end;
// обработка блока Current в фиксированный(е) блок(и) Result
// фиксированные блоки имеют следующие типы
(*TFixupedKind = (fkEmpty, // пустой блок (при оптимизациях такое может произойти. в этом случае весь value равен 0)
fkNormal, // стандартная ситуация
fkLeave, // ret(n), leave, jmp reg, jmp mem
fkLeaveJoined, // jmp [... + offset ...]
fkJoined, // add edx, [... + offset ...] / mov esi, offset @1
fkGlobalJumpBlock, // call axml_get_attribute / jne PRE_cmd_ptr_addr_const
fkLocalJumpBlock, // jnle @2 / call @Specifier
fkInline // pop esi, pop edi, ret
);*)
// на первой итерации просто анализируем последовательность команд,
// попутно обрезая команды, которые не будут созданы.
BottomCmd := OpcodeBlock.CmdList;
AdvBlocksCount := -1;
flags := 0{0 означает, что при "обычной"(fkNormal) команде нельзя "спариваться" с предыдущими};
Storage.CurrentRefId := REFID_ISNEXT{по умолчанию после текущих блоков надо будет вставлять блоки с обычным следованием. но могут быть исключения (cmLeave)};
Cmd := BottomCmd;
first_iteration:
begin
case Cmd.Mode of
cmLeave, {cmLeave и cmJumpBlock объединены потому, что так читабельнее + меньше case прыжков}
cmJumpBlock: begin
// fkLeave, fkLocalJumpBlock или fkGlobalJumpBlock
flags := 0;
inc(AdvBlocksCount);
if (Cmd.Mode = cmLeave) or {cmJumpBlock}(Cmd.F.cc_ex = -1) then
begin
// ret(n), leave, jmp reg/mem/Block
BottomCmd := Cmd;
AdvBlocksCount := 0;
Storage.CurrentRefId := 0;
end;
end;
cmJoined: begin
// fkJoined или fkLeaveJoined
flags := 0;
inc(AdvBlocksCount);
if (TOpcodeCmdMode(Cmd.Param shr 2) = cmLeave) then
begin
// jmp mem - fkLeaveJoined
BottomCmd := Cmd;
AdvBlocksCount := 0;
Storage.CurrentRefId := 0;
end;
Cmd := Cmd.Next;
end;
cmPointer: begin
// под Pointer может скрываться любая команда,
// в любом случае для неё нужен отдельный блок
flags := 0;
inc(AdvBlocksCount);
// но если это jmp [mem] - то обрезаем
if (Cmd.Param and 2 <> 0) then
begin
BottomCmd := Cmd;
AdvBlocksCount := 0;
Storage.CurrentRefId := 0;
end
end;
else
{cmBinary/Text:}
// обычная бинарная/текстовая команда
inc(AdvBlocksCount, ord(flags=0));
inc(flags);
end;
// next
Cmd := Cmd.Next;
if (Cmd <> nil) then goto first_iteration;
end;
// для ряда обычных команд - логика простая
if (AdvBlocksCount = 0) and (flags <> 0) then
begin
flags := (flags shl 8) + ord({Kind}fkNormal);
Result.Cmd := BottomCmd;
Result.Value := flags;
goto line_loop_continue;
end;
// сначала необходимо добавить нужное количество фиксированных блоков
begin
flags{новое количество блоков} := AdvBlocksCount + Storage.BlocksCount;
Storage.BlocksCount := flags;
{$ifdef OPCODE_TEST}
if (flags > NO_FIXUPED) then raise_parameter;
{$endif}
while (flags > Storage.BlocksAvailable) do GrowFixupedBlocks(Storage);
Storage.TopResult := Result;
Result := @Storage.Blocks[flags-1];
end;
// цикл заполнения фиксированных блоков
flags := 0{0 означает, что прошлый блок был не fkNormal и к нему нельзя "прицепиться"};
second_iteration:
begin
// если команда указательная - значит надо её преобразовать до правильного вида
// и выставить флаг, указывающий, что команда не может спариваться с остальными командами
Cmd := BottomCmd;
if (BottomCmd.Mode = cmPointer) then
begin
Cmd := UnpointerCmd(Storage, POpcodeCmdPointer(BottomCmd));
flags := 0;
end;
case Cmd.Mode of
cmLeave: begin
Result.Kind := fkLeave;
Result.Cmd := Cmd;
flags := 0;
end;
cmJumpBlock: begin
Result.cc_ex := Cmd.F.cc_ex;
flags := 0;
if (POpcodeCmdJumpBlock(Cmd).Proc = Storage.Proc) then
begin
// локальный прыжок
Result.Kind := fkLocalJumpBlock;
POpcodeBlock(Result.Cmd) := POpcodeCmdJumpBlock(Cmd).Block{!!! потом будет преобразовано к Fixuped};
end else
begin
// глобальный прыжок
Result.Kind := fkGlobalJumpBlock;
{$ifdef OPCODE_MODES}
if (Storage.Mode <> omBinary) then
begin
// текстовый глобальный прыжок
Result.ProcName := POpcodeCmdJumpBlock(Cmd).ProcName;
end else
{$endif}
begin
// бинарный глобальный прыжок
Result.Proc := POpcodeCmdJumpBlock(Cmd).Proc;
Result.Reference := POpcodeCmdJumpBlock(Cmd).Reference;
end;
end;
end;
cmJoined: begin
Result.Kind := fkJoined;
Result.Cmd := Cmd;
flags := 0;
if (TOpcodeCmdMode(Cmd.Param shr 2) = cmLeave) then
begin
// jmp mem
Result.Kind := fkLeaveJoined;
end;
// Bottom переходит на следующий
// только в стандартном (не cmPointer) случае
if (Cmd = BottomCmd) then BottomCmd := BottomCmd.Next;
end;
else
{cmBinary/Text:}
// обычная бинарная/текстовая команда
// увеличиваем счётчик и в случае чего прописываем Kind равный fkNormal
if (flags = 0) then
begin
flags := $0100 or ord(fkNormal);
Result.Cmd := Cmd;
end else
begin
inc(flags, $0100);
inc(Result);
end;
Result.Value := flags;
if (Cmd <> BottomCmd{cmPointer}) then
flags := 0;
end;
BottomCmd := BottomCmd.Next;
if (BottomCmd <> nil) then
begin
if (Result <> Storage.TopResult) then Result.RefId := REFID_ISNEXT;
dec(Result);
goto second_iteration;
end;
end;
// смотрим следующий блок в линии
// если конец или уже известный блок - особая обработка
line_loop_continue:
OpcodeBlock := Storage.Current.N.Next;
flags := Storage.BlocksCount;
Storage.Current := OpcodeBlock;
if (OpcodeBlock <> nil) and (OpcodeBlock.O.Fixuped = NO_FIXUPED) then goto line_loop;
// линия завершилась - выделяем блок
if (flags = Storage.BlocksAvailable) then GrowFixupedBlocks(Storage);
{$ifdef OPCODE_TEST}
if (flags = NO_FIXUPED) then raise_parameter;
{$endif}
Result := @Storage.Blocks[flags];
Result.RefId := REFID_ISNEXT;
Storage.BlocksCount := flags+1;
end{цикл по всем Next-блокам в OpcodeBlock};
// в конечном счёте последний блок в линии найден
// это либо последний блок (временно проставляем nil)
// либо конкретный блок (временно проставляем значение)
// в зависимости от ситуации прописываем результирующий фиксированный блок
line_loop_finished:
Result.Kind := fkLocalJumpBlock;
Result.cc_ex := -1{jmp};
Result.Cmd := pointer(Storage.Current);
// в третьем этапе проходим по всем добавленным блокам и производим инкремент RefId
// нужных блоков. При необходимости - вызываем рекурсивное добавление блоков
// получилось конечно много копипаста, не не знаю как сделать элегантнее с той же скоростью
Result := @Storage.Blocks[Storage.StartBlock];
for i := Storage.StartBlock to Storage.BlocksCount-1 do
begin
case Result.Kind of
fkLeaveJoined,
fkJoined:
begin
JoinedData := @POpcodeCmdJoined(Result.Cmd).Data[0];
if (JoinedData.Proc = Storage.Proc) then
begin
OpcodeBlock := JoinedData.Block;
Fixuped := OpcodeBlock.O.Fixuped;
if (Fixuped <> NO_FIXUPED) then Inc(Storage.Blocks[Fixuped].RefId)
else
Result := AddFixupedBlocksLineAsLink(Storage, Result, OpcodeBlock);
end;
//inc(JoinedData);
if (Result.Cmd.Param and 3 = 3) then
begin
JoinedData := @POpcodeCmdJoined(Result.Cmd).Data[1];
if (JoinedData.Proc = Storage.Proc) then
begin
OpcodeBlock := JoinedData.Block;
Fixuped := OpcodeBlock.O.Fixuped;
if (Fixuped <> NO_FIXUPED) then Inc(Storage.Blocks[Fixuped].RefId)
else
Result := AddFixupedBlocksLineAsLink(Storage, Result, OpcodeBlock);
end;
end;
end;
fkLocalJumpBlock:
begin
OpcodeBlock := POpcodeBlock(Result.Cmd);
if (OpcodeBlock = nil) then
begin
// прыжок в конец, потом будет прописан нормальный Fixuped
Result.Fixuped := NO_FIXUPED;
end else
begin
// прыжок в конкретный блок
// либо инкремент ссылки, либо вызов рекурсии
// к сожалению не удаётся закешировать
Fixuped := OpcodeBlock.O.Fixuped;
if (Fixuped <> NO_FIXUPED) then
begin
Result.Fixuped := Fixuped;
Inc(Storage.Blocks[Fixuped].RefId);
end else
begin
Result := AddFixupedBlocksLineAsLink(Storage, Result);
end;
end;
end;
end;
inc(Result);
end;
end{функция};
// вспомогательная функция,
// которая вызывается если нужен блок, которого ещё нет среди Fixuped-блоков
function AddFixupedBlocksLineAsLink(var Storage: TFixupedStorage; const CurrentResult: PFixupedBlock; Block: POpcodeBlock=nil): PFixupedBlock;
var
Offset: NativeInt;
begin
Offset := NativeInt(CurrentResult)-NativeInt(Storage.Blocks);
if ({если в CurrentResult сидит прыжок}Block = nil) then
begin
CurrentResult.Fixuped := Storage.BlocksCount;
Block := POpcodeBlock(CurrentResult.Cmd);
end;
Storage.Current := Block;
Storage.CurrentRefId := 1;
AddFixupedBlocksLine(Storage);
Result := pointer(NativeInt(Storage.Blocks)+Offset);
end;
const
// обратное условие
// нужно для inline-оптимизации
intel_cc_invert: array[0..ord(high(intel_cc))] of intel_cc = (_no,_o,_nb,_nc,_ae,_nae,_b,_c,
_ne,_nz,_z,_e,_nbe,_na,_na,_be,_ns,_s,_np,_po,_pe,_p,_nl,_ge,_nge,_l,_nle,_g,_ng,_le);
// маски прыжков рассчитаны на сверку множеств
// call-->jmp (в том числе cc) оптимизировать можно, но jmp/call-->call нельзя
// X <= Y если mask[X] and mask[Y] = mask[X]
//
// но прыжковые команды могут подразумевать под собой ряд and-условий
// поэтому частные случаи выражаются через сумму cf/sf<>of/zf
_csoz_000 = (1 shl 0);
_csoz_001 = (1 shl 1);
_csoz_010 = (1 shl 2);
_csoz_011 = (1 shl 3);
_csoz_100 = (1 shl 4);
_csoz_101 = (1 shl 5);
_csoz_110 = (1 shl 6);
_csoz_111 = (1 shl 7);
_cf_0 = _csoz_000 or _csoz_001 or _csoz_010 or _csoz_011;
_cf_1 = _csoz_100 or _csoz_101 or _csoz_110 or _csoz_111;
_sfof_0{sf=of} = _csoz_000 or _csoz_001 or _csoz_100 or _csoz_101;
_sfof_1{sf<>of} = _csoz_010 or _csoz_011 or _csoz_110 or _csoz_111;
_zf_0 = _csoz_000 or _csoz_010 or _csoz_100 or _csoz_110;
_zf_1 = _csoz_001 or _csoz_011 or _csoz_101 or _csoz_111;
_cf_0_zf_0{для ja/jnbe} = _csoz_000 or _csoz_010;
_sfof_0_zf_0{для jg/jnle} = _csoz_000 or _csoz_100;
_of_0 = (1 shl 8);
_of_1 = (1 shl 9);
_sf_1 = (1 shl 10);
_sf_0 = (1 shl 11);
_pf_1 = (1 shl 12);
_pf_0 = (1 shl 13);
// call можно сделать только в jmp
// а если исходный call оставить 0, тогда условие X = X & Y ошибочно сработает
_call_f = (1 shl 15);
// базовый массив масок
// если src = src & dest - то можно смело прыгать дальше, минуя этот прыжок
// если src = src & ignore - то можно прыгать не в эту команду(прыжковую), а в следующую
jmp_src_mask: array[-2{call,jmp}..ord(high(intel_cc))] of word =
(
_call_f{call},
$ffff{jmp},
_of_1{_o},
_of_0{_no},
_cf_1,_cf_1,_cf_1{_b,_c,_nae},
_cf_0,_cf_0,_cf_0{_ae,_nb,_nc},
_zf_1,_zf_1{_e,_z},
_zf_0,_zf_0{_nz,_ne},
_cf_1 or _zf_1, _cf_1 or _zf_1{_be,_na},
_cf_0_zf_0, _cf_0_zf_0{_a,_nbe},
_sf_1{_s},
_sf_0{_ns},
_pf_1,_pf_1{_p,_pe},
_pf_0,_pf_0{_po,_np},
_sfof_1,_sfof_1{_l,_nge},
_sfof_0,_sfof_0{_ge,_nl},
_zf_1 or _sfof_1,_zf_1 or _sfof_1{_le,_ng},
_sfof_0_zf_0,_sfof_0_zf_0{_g,_nle}
);
// если src = src & dest - то можно смело прыгать дальше, минуя этот прыжок
// но в call уже прыгать нельзя
jmp_dest_mask: array[-2{call,jmp}..ord(high(intel_cc))] of word =
(
0,{call}
$ffff{jmp},
_of_1{_o},
_of_0{_no},
_cf_1,_cf_1,_cf_1{_b,_c,_nae},
_cf_0,_cf_0,_cf_0{_ae,_nb,_nc},
_zf_1,_zf_1{_e,_z},
_zf_0,_zf_0{_nz,_ne},
_cf_1 or _zf_1, _cf_1 or _zf_1{_be,_na},
_cf_0_zf_0, _cf_0_zf_0{_a,_nbe},
_sf_1{_s},
_sf_0{_ns},
_pf_1,_pf_1{_p,_pe},
_pf_0,_pf_0{_po,_np},
_sfof_1,_sfof_1{_l,_nge},
_sfof_0,_sfof_0{_ge,_nl},
_zf_1 or _sfof_1, _zf_1 or _sfof_1{_le,_ng},
_sfof_0_zf_0, _sfof_0_zf_0{_g,_nle}
);
// в случае если второй прыжок гарантированно не сработает - его нужно пропустить
// например jg --> jz, но call и jmp пропустить не удастся
// применять так: jmp_src_mask[X] = jmp_src_mask[X] and jmp_ignore_mask[Y]
//
// кстати раньше jmp_ignore_mask назывался jmp_invert_mask
// потому что формула идёт от противоречащих(противоположных) флагов
jmp_ignore_mask: array[-2{call,jmp}..ord(high(intel_cc))] of word =
(
0{call пропустить не удастся},
0{jmp тоже пропустить не удастся},
_of_0{_o},
_of_1{_no},
_cf_0,_cf_0,_cf_0{_b,_c,_nae},
_cf_1,_cf_1,_cf_1{_ae,_nb,_nc},
_zf_0,_zf_0{_e,_z},
_zf_1,_zf_1{_nz,_ne},
_cf_0_zf_0, _cf_0_zf_0{_be,_na},
_cf_1 or _zf_1, _cf_1 or _zf_1{_a,_nbe},
_sf_0{_s},
_sf_1{_ns},
_pf_0,_pf_0{_p,_pe},
_pf_1,_pf_1{_po,_np},
_sfof_0,_sfof_0{_l,_nge},
_sfof_1,_sfof_1{_ge,_nl},
_sfof_0_zf_0, _sfof_0_zf_0{_le,_ng},
_zf_1 or _sfof_1, _zf_1 or _sfof_1{_g,_nle}
);
// массив объединённых прыжков
// когда jump1 A / jump2 A --> X ===> jumpSUM A
// included_jumps: array[-2{call,jmp}..ord(high(intel_cc)), -2{call,jmp}..ord(high(intel_cc))] of shortint;
// доступ[X, Y]: X*included_jumps_pitch+Y
(* как получен:
mask := jmp_src_mask[X] or jmp_src_mask[Y];
for i := -1 to ord(high(intel_cc)) do if (jmp_src_mask[i] = mask) ...
*)
included_jumps_pitch{=32} = 2{call/jmp}+ord(high(intel_cc))+1;
included_jumps: array[-2*included_jumps_pitch-2..high(jmp_src_mask)*included_jumps_pitch+high(jmp_src_mask)] of shortint = (
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},
-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},
-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-1{jmp},-2{none},-1{jmp},ord(_o),-1{jmp},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-1{jmp},-1{jmp},ord(_no),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},ord(_b),ord(_c),
ord(_nae),-1{jmp},-1{jmp},-1{jmp},ord(_be),ord(_be),-2{none},-2{none},ord(_be),ord(_na),-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-1{jmp},-2{none},-2{none},ord(_b),ord(_c),ord(_nae),-1{jmp},-1{jmp},-1{jmp},ord(_be),ord(_be),-2{none},-2{none},
ord(_be),ord(_na),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},ord(_b),ord(_c),ord(_nae),-1{jmp},
-1{jmp},-1{jmp},ord(_be),ord(_be),-2{none},-2{none},ord(_be),ord(_na),-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},
-2{none},-2{none},-1{jmp},-1{jmp},-1{jmp},ord(_ae),ord(_nb),ord(_nc),-2{none},-2{none},-2{none},-2{none},-1{jmp},-1{jmp},
ord(_ae),ord(_ae),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},-1{jmp},-1{jmp},-1{jmp},ord(_ae),ord(_nb),ord(_nc),-2{none},
-2{none},-2{none},-2{none},-1{jmp},-1{jmp},ord(_nb),ord(_nb),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},-1{jmp},
-1{jmp},-1{jmp},ord(_ae),ord(_nb),ord(_nc),-2{none},-2{none},-2{none},-2{none},-1{jmp},-1{jmp},ord(_nc),ord(_nc),-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-1{jmp},-2{none},-2{none},ord(_be),ord(_be),ord(_be),-2{none},-2{none},-2{none},ord(_e),ord(_z),-1{jmp},-1{jmp},
ord(_be),ord(_na),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},ord(_le),ord(_le),-2{none},
-2{none},ord(_le),ord(_ng),-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},ord(_be),ord(_be),ord(_be),-2{none},
-2{none},-2{none},ord(_e),ord(_z),-1{jmp},-1{jmp},ord(_be),ord(_na),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},ord(_le),ord(_le),-2{none},-2{none},ord(_le),ord(_ng),-2{none},-2{none},-2{none},-1{jmp},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-1{jmp},ord(_nz),ord(_ne),-1{jmp},-1{jmp},ord(_nz),
ord(_nz),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-1{jmp},
ord(_nz),ord(_nz),-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},
-1{jmp},ord(_nz),ord(_ne),-1{jmp},-1{jmp},ord(_ne),ord(_ne),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-1{jmp},-1{jmp},ord(_ne),ord(_ne),-2{none},-1{jmp},-2{none},-2{none},ord(_be),
ord(_be),ord(_be),-1{jmp},-1{jmp},-1{jmp},ord(_be),ord(_be),-1{jmp},-1{jmp},ord(_be),ord(_na),-1{jmp},-1{jmp},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-1{jmp},-2{none},-2{none},ord(_na),ord(_na),ord(_na),-1{jmp},-1{jmp},-1{jmp},ord(_na),ord(_na),-1{jmp},-1{jmp},
ord(_be),ord(_na),-1{jmp},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},ord(_ae),
ord(_nb),ord(_nc),-2{none},-2{none},ord(_nz),ord(_ne),-1{jmp},-1{jmp},ord(_a),ord(_nbe),-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},
-2{none},-2{none},-2{none},-2{none},-2{none},ord(_ae),ord(_nb),ord(_nc),-2{none},-2{none},ord(_nz),ord(_ne),-1{jmp},
-1{jmp},ord(_a),ord(_nbe),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},ord(_s),-1{jmp},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-1{jmp},ord(_ns),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},ord(_p),ord(_pe),-1{jmp},
-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},ord(_p),ord(_pe),-1{jmp},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-1{jmp},ord(_po),ord(_np),
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-1{jmp},-1{jmp},ord(_po),ord(_np),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},ord(_le),ord(_le),
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},ord(_l),
ord(_nge),-1{jmp},-1{jmp},ord(_le),ord(_ng),-2{none},-2{none},-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},ord(_le),ord(_le),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},ord(_l),ord(_nge),-1{jmp},-1{jmp},ord(_le),ord(_ng),-2{none},-2{none},
-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-1{jmp},-1{jmp},
ord(_ge),ord(_nl),-1{jmp},-1{jmp},ord(_ge),ord(_ge),-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-1{jmp},-1{jmp},ord(_ge),ord(_nl),-1{jmp},-1{jmp},ord(_nl),ord(_nl),-2{none},-1{jmp},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},ord(_le),ord(_le),-1{jmp},-1{jmp},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},ord(_le),ord(_le),-1{jmp},-1{jmp},
ord(_le),ord(_ng),-1{jmp},-1{jmp},-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},ord(_ng),ord(_ng),-1{jmp},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},ord(_ng),ord(_ng),-1{jmp},-1{jmp},ord(_le),ord(_ng),-1{jmp},-1{jmp},-2{none},-1{jmp},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},ord(_nz),ord(_ne),-2{none},-2{none},-2{none},
-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},ord(_ge),ord(_nl),-1{jmp},-1{jmp},
ord(_g),ord(_nle),-2{none},-1{jmp},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},ord(_nz),ord(_ne),-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},-2{none},
-2{none},-2{none},ord(_ge),ord(_nl),-1{jmp},-1{jmp},ord(_g),ord(_nle));
// теоретически рекурсивная функция,
// задача которой очистить блок и подкорректировать счётчики ссылок
// label-ами добился, чтобы всё нормально раскидывалось по регистрам и стеку
procedure RemoveFixupedBlock(var Storage: TFixupedStorage; B: PFixupedBlock);
label
loop, loop_end;
var
N: array[0..1] of PFixupedBlock;
i, RefId: integer;
begin
//while (true) do
loop:
begin
// блок может указывать на другие блоки
// запоминаем их, чтобы потом уменьшить ссылки
N[0] := nil;
N[1] := N[0]{nil};
case B.Kind of
fkLeaveJoined,
fkJoined: begin
for i := 0 to 1 do
with POpcodeCmdJoined(B.Cmd).Data[i] do
begin
if (Global = Storage.Proc) then
N[i] := @Storage.Blocks[Block.O.Fixuped];
if (B.Cmd.Param and 3 <> 3) then break;
end;
end;
fkLocalJumpBlock: begin
RefId := B.Fixuped;
if (RefId <> NO_FIXUPED{может быть ещё не "сработала" ссылка}) then N[0] := @Storage.Blocks[RefId];
end;
fkInline: begin
if (B.cc_ex >= 0) then
N[0] := @PFixupedBlockArray(B)^[1];
end;
end;
RefId := 0;
B.Value := RefId{Kind := fkEmpty};
{$ifdef OPCODE_MODES}
B.HybridSize_Min := RefId;
B.HybridSize_Max := RefId;
{$else}
B.Size := RefId;
{$endif}
// если команда использует другую(ие) команду(ы) - уменьшить счётчик ссылок там
for i := 0 to 1 do
if (N[i] <> nil) then
begin
RefId := N[i].RefId-1;
N[i].RefId := RefId;
if (RefId(*{$ifdef OPCODE_MODES} shl 1{$endif}*) = 0) then RemoveFixupedBlock(Storage, N[i]);
end;
// заключительным этапом удаления блока является отслеживание, корректности счётчика ниже
// корректность можно сформулировать следующим образом:
// "блок ниже" может содержать ISNEXT если в текущем блоке или предке осталась хоть одна ссылка
RefId := B.RefId;
inc(B);
if (RefId(*{$ifdef OPCODE_MODES} shl 1{$endif}*) <> 0) then goto loop_end;
// в том блоке ссылок не осталось - поэтому лишаем ISNEXT-а следующий блок
RefId := B.RefId and (not REFID_ISNEXT);
B.RefId := RefId;
// если в этом блоке не осталось ссылок - то продолжаем удалять
if (RefId(*{$ifdef OPCODE_MODES} shl 1{$endif}*) = 0) then goto loop;
end;
loop_end:
end;
const
// константа, которая помогает более оптимально пройти
// масcив локальных прыжков
NO_JUMP = PFixupedBlock(NativeInt(-1));
// ОЧЕНЬ ВАЖНО!
//
// И в архитектуре x86-64, и в архитектуре ARMv7 Thumb
// размер малого прыжка равен 2м байтам.
// Хотелось бы конечно более универсального подхода, так было бы правильнее.
// Но в функции оптимизации и реализации прыжков Delphi просто отвратительно
// укладывает переменные в регистры. Поэтому я просто вынужден задавать размер
// малого прыжка константой. С другой стороны с константной - в любом случае получается быстрее.
//
// массив small_sizes в TFixupedStorage остаётся
// но только для того чтобы в одном подходе отслеживать невозможность сжать прыжок до малого
// (применяется для уже сжатых прыжков и для call)
// кроме того вполне может быть, что в VM вообще не будет малых прыжков.
// но если они будут - они обязаны быть размером в 2 байта.
SMALL_JUMP_SIZE = 2;
// эта константа нужна для того, чтобы помечать текстовые прыжки (в гибриде)
// это происходит в том случае, когда OffsetMin не равен OffsetMax
{$ifdef OPCODE_MODES}
JUMP_OFFSET_TEXT = low(integer);
{$endif}
// универсальная итеративная функция,
// которая чистит следующие ситуации:
// 0) jcc A --> jcc B - в случае невозможности второго прыжка по условиям первого, блок просто пропускается (как в случае fkEmpty)
// 1) jcc A / jcc B - удаляем несовершаемый прыжок B
// 2) jcc/jmp next - просто удаляем первый
// 3) jcc/jmp A + jcc/jmp A - если возможно объединение условий, первый удаляем, а во второй записываем объединение
//
// в функции полно меток вместо while(true)do циклов
// но это потому, что в циклах совсем неоптимально раскидываются переменные по регистрам
//
// Важны следующие переменные:
// Current(esi)^ - текущий прыжок (из массива локальных прыжков), который мы рассматриваем.
// по началу кешируем в переменной Next.
// Next(ebx) - следующая команда после Current^. Нужна потому, что от неё зависят все оптимизации!
// в случае поиска Next(от Current^) удаляем несовершаемые прыжки: случай 1)
// в случае прыжка из Current^ в Next - удаляем Current^: случай 2)
// если Current^ и Next указывают на один и тот же блок - то Current^ очищаем, а в Next записываем объединение: случай 3)
// Dest(edi) - переменная, в которой содержится блок, куда указывает прыжок Current^.
// Dest сама может указывать на прыжок - поэтому может быть Dest-цикл.
// B - временный буфер
// Storage(ebp) - хранилище общей информации
procedure RemoveExcessJumps(var Storage: TFixupedStorage);
{$ifdef OPCODE_TEST}
const
EXCEPTION_JUMP_TO_SELF: string = 'Jump to self';
{$endif}
label
main_while, for_loop,
foreach_dest, foreach_next,
loop_1, loop_1_end, loop_2, loop_2_end, loop_3, loop_4;
var
Current: ^PFixupedBlock;
Next, Dest, B: PFixupedBlock;
has_refs: integer;
mask: word;
StackCount: integer;
// переменные, которые гарантированно идут в стек
Stack: record
mask: word;
included_cc: shortint;
Changed: boolean; // флаг, указывающий, что оптимизация применена (блок удалён) - надо сделать ищё минимум одну итерацию
{$ifdef CPUX64}align_8: integer;{$endif}
// список прыжков из Current^
ReJumps: array[0..JUMP_STACK_SIZE-1] of PFixupedBlock;
BufNext: PFixupedBlock;
end;
begin
//while (true) do
main_while:
begin
Stack.Changed := false;
Current := pointer(Storage.LocalJumps);
dec(Current);
// while (true) do
// begin
for_loop:
inc(Current);
Next := Current^;
// сначала Next указывает на Current^
// потом будет найден следующий (next) блок после Current^
if (Next <> NO_JUMP) then //if (Next = NO_JUMP) then goto for_loop_end;
begin
if (Next = nil) then goto for_loop;
if (Next.Kind = fkEmpty{если уже удалён}) then
begin
Current^ := nil;
goto for_loop;
end;
// функция не удаляет call-ы
if (Next.cc_ex = -2) then goto for_loop;
// на первом этапе необходимо найти Next - т.е. следующий блок после Current^
// пропускаем Empty и несовершаемые прыжки (можно удалять): случай 1)
// здесь очень важен счётчик(флаг) входящих ссылок в промежуток от Current^ к Next
// нужен он для двух вещей.
// во-первых, для удаления несовершаемых прыжков
// во-вторых, для дальнейшего объединения (здесь уже нормально если в Next входит): случай 3)
// в конечном счёте has_refs(-1) сохраняется в included_cc, чтобы потом можно было применить в объединении
Stack.mask := jmp_dest_mask[Next.cc_ex]; // для Current^ определяем dest-маску
has_refs := 0{has_refs := false};
loop_1:
begin
inc(Next);
inc(has_refs, ord(Next.RefId and (REFID_ISNEXT-1){shl 2} <> 0)){has_refs := true};
case Next.Kind of
fkEmpty: goto loop_1;
fkGlobalJumpBlock,
fkLocalJumpBlock: begin
// неисполняемый блок если [Next] <= [Current^] (меньше либо равно)
// если !has_refs удаляем
mask := jmp_src_mask[Next.cc_ex];
if (mask = mask and {jmp_dest_mask[Current^]}Stack.mask) then
begin
if (has_refs = 0){not has_refs} then
begin
Stack.Changed := true;
RemoveFixupedBlock(Storage, Next);
end;
goto loop_1;
end;
end;
end;
end;
// сохраняем для объединения
Stack.included_cc := ord((has_refs-1) > 0);
// на втором этапе необходимо заполнить Dest массив (Stack.ReJumps)
// (не забываем пропускать блоки с невозможным прыжком: случай 0)
// он нужен для того, чтобы в итоге проверить возможность объединения: случай 3)
// кроме того проверям jmp/jcc Next: случай 2)
//
// для первого прыжка проводим дополнительные оптимизации
Stack.mask := jmp_src_mask[Current^.cc_ex];
Dest := @Storage.Blocks[Current^.Fixuped];
B := Dest;
//while (true) do
loop_2:
begin
{$ifdef OPCODE_TEST}
// проверка прыжка в себя
if (Dest = Current^) then raise EOpcodeLib.Create(EXCEPTION_JUMP_TO_SELF);
{$endif}
case Dest.Kind of
fkEmpty: ;
fkGlobalJumpBlock,
fkLocalJumpBlock: begin
if (Stack.mask <> Stack.mask and jmp_ignore_mask[Dest.cc_ex]) then goto loop_2_end;
end;
fkInline: begin
if (Stack.mask <> Stack.mask and jmp_dest_mask[Dest.cc_ex]) then goto loop_2_end;
end;
else
goto loop_2_end;
end;
inc(Dest);
inc(Current^.Fixuped);
goto loop_2;
end;
loop_2_end:
// в случае перемещения - вызываем обработку счётчика ссылок
if (Dest <> B) then
begin
inc(Dest.RefId);
dec(B.RefId);
if (B.RefId(*{$ifdef OPCODE_MODES} shl 1{$endif}*) = 0) then
begin
Stack.Changed := true;
RemoveFixupedBlock(Storage, B);
end;
end;
// продолжаем наполнять список(стек) прыжков
// заодно проверяем 2) - прыжок в Next
StackCount := 0;
//while (true) do
loop_3:
begin
inc(StackCount);
{$ifdef OPCODE_TEST}
// проверка прыжка в себя
if (Dest = Current^) then raise EOpcodeLib.Create(EXCEPTION_JUMP_TO_SELF);
{$endif}
// прыжок в next: случай 2)
if (NativeInt(Dest) <= NativeInt(Next)) and (NativeInt(Dest) > NativeInt(Current^)) then
begin
// RemoveFixupedBlock(Storage, Current^);
{
алгоритм удаления jcc/jmp Next был немного изменён.
необходимо проставить флаги REFID_ISNEXT от всех Current^+1 до Next
кроме того так быстрее (не вызываем функцию)
}
dec(Dest.RefId);
Dest := Current^;
StackCount := 0;
Dest.Value := StackCount{Kind := fkEmpty};
{$ifdef OPCODE_MODES}
Dest.HybridSize_Min := StackCount;
Dest.HybridSize_Max := StackCount;
{$else}
Dest.Size := StackCount;
{$endif}
repeat
Next.RefId := Next.RefId or REFID_ISNEXT;
dec(Next);
until (Next = Dest);
Stack.Changed := true;
Current^ := nil;
goto for_loop;
end;
// заносим в буфер
Stack.ReJumps[StackCount-1] := Dest;
// смотрим следующий (если это возможно)
if (StackCount <> JUMP_STACK_SIZE) and
(Dest.Kind = fkLocalJumpBlock) and
(Stack.mask = Stack.mask and jmp_dest_mask[Dest.cc_ex]) then
begin
Dest := @Storage.Blocks[Dest.Fixuped];
// пропускаем Dest до адекватного
loop_4:
begin
case Dest.Kind of
fkEmpty: ;
fkGlobalJumpBlock,
fkLocalJumpBlock: begin
if (Stack.mask <> Stack.mask and jmp_ignore_mask[Dest.cc_ex]) then goto loop_3;
end;
fkInline: begin
if (Stack.mask <> Stack.mask and jmp_dest_mask[Dest.cc_ex]) then goto loop_3;
end;
else
goto loop_3;
end;
inc(Dest);
goto loop_4;
end;
end;
end;
// на последнем этапе мы пытаемся объединить прыжок [Current^] и [Next]: случай 3)
// если они указывают в один и тот же блок (для определения сравниваются все Dest со всеми Next->).
//
// и возможно это минимум в том случае, когда между Current^ и Next нет прямых прыжков,
// если Next это локальный прыжок, и если вообще существует такой прыжок, который может объединить 2 этих прыжка
if (Stack.included_cc <> 0){has_refs} or (not (Next.Kind in [fkLocalJumpBlock, fkGlobalJumpBlock])) or (Next.cc_ex = -2) then goto for_loop;
// объединение
Stack.included_cc := included_jumps[Current^.cc_ex*included_jumps_pitch+Next.cc_ex];
if (Stack.included_cc = -2) then goto for_loop;
// запоминаем данные по Next
Stack.mask := jmp_src_mask[Next.cc_ex];
Stack.BufNext := Next;
Next := @Storage.Blocks[Next.Fixuped];
// foreach Dest do
// foreach Next do
foreach_dest:
begin
Dest := Stack.ReJumps[StackCount-1];
dec(StackCount);
foreach_next:
begin
// ситуация 2)
if (Dest = Next) then
begin
RemoveFixupedBlock(Storage, Current^);
//Stack.BufNext.cc_ex := Stack.included_cc;
Next := Stack.BufNext;
Next.cc_ex := Stack.included_cc;
if (Next.cc_ex = -1) then
begin
// в случае если объединённый прыжок - это jmp то в блоке ниже
// нужно убрать REFID_ISNEXT
inc(Next);
StackCount := Next.RefId and (not REFID_ISNEXT);
Next.RefId := StackCount;
if (StackCount = 0) then RemoveFixupedBlock(Storage, Next);
end;
Stack.Changed := true;
Current^ := nil;
goto for_loop;
end;
// смотрим следующий Next
// в случае неисполняемого прыжка - пропускаем
// в случае если можно продолжить - переходим в следующий прыжок
case Next.Kind of
fkEmpty: begin
inc(Next);
goto foreach_next;
end;
fkGlobalJumpBlock,
fkLocalJumpBlock: begin
if (Stack.mask = Stack.mask and jmp_ignore_mask[Next.cc_ex]) then
begin
inc(Next);
goto foreach_next;
end;
if (Next.Kind = fkLocalJumpBlock) and
(Stack.mask = Stack.mask and jmp_dest_mask[Next.cc_ex]) then
begin
Next := @Storage.Blocks[Next.Fixuped];
goto foreach_next;
end;
end;
fkInline: if (Stack.mask = Stack.mask and jmp_dest_mask[Next.cc_ex]) then
begin
inc(Next);
goto foreach_next;
end;
end;
end;
if (StackCount <> 0) then
begin
Next := @Storage.Blocks[Stack.BufNext.Fixuped];
goto foreach_dest;
end;
end;
{next jump} goto for_loop;
end;
if (Stack.Changed) then goto main_while;
end;
end;
// задачей функции являются 3 вещи:
// 1) определить, какие именно прыжки можно сделать бинарными (гибрид), а какие сто процентов текстовые
// 2) рассчитать номера блоков
// 3) определить самую длинную бинарную последовательность
{$ifdef OPCODE_MODES}
procedure MarkupTextRoutine(var Storage: TFixupedStorage);
var
i: integer;
Block: PFixupedBlock;
CurrentBlockNumber: integer;
LabelLength: byte;
BinarySize: integer;
BinaryMaxSize: integer;
begin
// чтобы не плодить лишних меток если они не нужны
Dec(Storage.Blocks[0].RefId);
if (Storage.Proc.RetN = RET_OFF) then Dec(Storage.EndBlock.RefId);
// прописываем текстовые и бинарные команды
// всё решается флагом REFID_FLAG_TEXT
Block := pointer(Storage.Blocks);
if (Storage.Mode = omAssembler) then
begin
// в текстовом режиме все блоки помечаются как текстовые
for i := 0 to Storage.BlocksCount-1 do
begin
Block.RefId := Block.RefId or REFID_FLAG_TEXT;
inc(Block);
end;
end else
begin
// в гибридном режиме более сложная логика
// часть команд бинарная, часть текстовая
for i := 0 to Storage.BlocksCount-1 do
begin
case Block.Kind of
// fkEmpty: {бинарная};
// fkNormal: {бинарная};
// fkLeave: {бинарная};
fkLeaveJoined, // всегда
fkJoined, // текстовые
fkGlobalJumpBlock: begin
Block.RefId := Block.RefId or REFID_FLAG_TEXT;
end;
fkLocalJumpBlock: // текстовая при неконстантном
// для бинарных уменьшаем количество ссылок
// чтобы не плодить лишних меток
begin
if (Block.JumpOffset = JUMP_OFFSET_TEXT) then
begin
Block.RefId := Block.RefId or REFID_FLAG_TEXT;
end else
begin
Dec(Storage.Blocks[Block.Fixuped].RefId);
end;
end;
// fkInline: {бинарная};
end;
inc(Block);
end;
end;
// прописываем номера блоков (для текстов: ассемблера и гибрида)
Block := pointer(Storage.Blocks);
CurrentBlockNumber := 0;
for i := 0 to Storage.BlocksCount-1 do
begin
if (Block.RefId and (REFID_ISNEXT-1) <> 0) then inc(CurrentBlockNumber);
Block.Number := CurrentBlockNumber;
inc(Block);
end;
// записываем параметры по меткам в хранилище
// манипуляция с байтом нужна потому, что так компилируется оптимальнее
Storage.LabelCount := CurrentBlockNumber;
LabelLength := ord(CurrentBlockNumber > 9) + ord(CurrentBlockNumber > 99)
+ ord(CurrentBlockNumber > 999) + ord(CurrentBlockNumber > 9999){ + byte(CurrentBlockNumber > 99999)}+1;
Storage.LabelLength := LabelLength;
// определяем самую длинную бинарную (для гибрида) последовательность
// и выделяем необходимую память
if (Storage.Mode = omAssembler) then exit;
BinarySize := 0;
BinaryMaxSize := 0;
for i := 0 to Storage.BlocksCount-1 do
begin
if (Block.RefId and (REFID_FLAG_TEXT or (REFID_ISNEXT-1)) <> 0) then
begin
// блок текстовый или в него есть ссылки (перед ним метка)
if (BinarySize > BinaryMaxSize) then BinaryMaxSize := BinarySize;
BinarySize := 0;
end else
begin
// бинарный блок
inc(BinarySize, Block.Size{Min});
end;
inc(Block);
end;
// выделяем
Storage.BinaryBuffer := Storage.Heap.Alloc(((BinaryMaxSize+3) and -4));
end;
{$endif}
const
// флаг, который прописывается в Storage.CurrentRefId на случай если был удалён блок
// данный флаг означает, что имеет смысл ещё раз вызвать RemoveExcessJumps
FLAG_BLOCKS_REMOVED = $0100;
// сложная оптимизирующая функция.
// вынесена в отдельный код потому, что в рамках RealizeJumps возникал уже маразм
// размещения переменных в регистрах. К тому же здесь действительно много переменных.
//
// функция вызывается тогда, когда гарантированно возможен реджамп из Block в Next.
// по сути необходимо проверить сразу несколько реджампов (на всякий случай)
// в случае изменения размера выставляем Storage.CurrentRefId равный 1
procedure OptimizeJumpsDifficult(var Storage: TFixupedStorage; Block, Next: PFixupedBlock);
label
rejump_loop, skip_next, skip_next_end,
offset_calc_prev, offset_calc_next;
var
src_mask: word;
Fixuped: integer;
Offset{Min}: integer;
{$ifdef OPCODE_MODES}
OffsetMax: integer;
{$endif}
Buffer: PFixupedBlock;
begin
Storage.FakeBlock.O.Reference{src_mask} := jmp_src_mask[Block.cc_ex];
rejump_loop:
begin
// смотрим, куда указывает Next
Fixuped := Next.Fixuped;
Next := @Storage.Blocks[Fixuped];
// пропускаем Next до адекватного
skip_next:
begin
case Next.Kind of
fkEmpty: ;
fkGlobalJumpBlock,
fkLocalJumpBlock: begin
src_mask := Storage.FakeBlock.O.Reference{src_mask};
if (src_mask <> src_mask and jmp_ignore_mask[Next.cc_ex]) then goto skip_next_end;
end;
fkInline: begin
src_mask := Storage.FakeBlock.O.Reference{src_mask};
if (src_mask <> src_mask and jmp_dest_mask[Next.cc_ex]) then goto skip_next_end;
end;
else
goto skip_next_end;
end;
inc(Next);
inc(Fixuped);
goto skip_next;
end;
skip_next_end:
Storage.FakeBlock.O.Fixuped := Fixuped;
// найти расстояние от Block до Next
Buffer := Next;
Offset{Min} := 0;
{$ifdef OPCODE_MODES}
OffsetMax := 0;
{$endif}
if (NativeInt(Buffer) <={вообще говоря не должно быть равно} NativeInt(Block)) then
begin
// подсчёт "назад"
offset_calc_prev:
begin
dec(Offset{Min}, Buffer.Size{Min});
{$ifdef OPCODE_MODES}
dec(OffsetMax, Buffer.HybridSize_Max);
{$endif}
inc(Buffer);
if (Buffer <> Block) then goto offset_calc_prev;
end;
end else
begin
// подсчёт "вперёд"
offset_calc_next:
begin
dec(Buffer);
inc(Offset{Min}, Buffer.Size{Min});
{$ifdef OPCODE_MODES}
inc(OffsetMax, Buffer.HybridSize_Max);
{$endif}
if (Buffer <> Block) then goto offset_calc_next;
end;
end;
// подменяем прыжок в Block если получается меньше или равно
// для начала запоминаем смещение, которое возможно пропишем в Block
Storage.StartBlock := Offset;
{$ifdef OPCODE_MODES}
if (Offset <> OffsetMax) then Storage.StartBlock := JUMP_OFFSET_TEXT;
{$endif}
// далее определяем размер, который возможен (Block.cc_ex закешировать не удаётся)
{$ifNdef OPCODE_MODES}Fixuped:=Block.cc_ex;{$endif}
if (Offset < Storage.JumpsInfo.low_ranges[{$ifdef OPCODE_MODES}Block.cc_ex{$else}Fixuped{$endif}]) or
(Offset > Storage.JumpsInfo.high_ranges[{$ifdef OPCODE_MODES}Block.cc_ex{$else}Fixuped{$endif}]) then
Offset := Storage.JumpsInfo.big_sizes[{$ifdef OPCODE_MODES}Block.cc_ex{$else}Fixuped{$endif}]
else
Offset := SMALL_JUMP_SIZE;
{$ifdef OPCODE_MODES}
if (OffsetMax < Storage.JumpsInfo.low_ranges[Block.cc_ex]) or
(OffsetMax > Storage.JumpsInfo.high_ranges[Block.cc_ex]) then
OffsetMax := Storage.JumpsInfo.big_sizes[Block.cc_ex]
else
OffsetMax := SMALL_JUMP_SIZE;
{$endif}
// сравниваем размер
{$ifNdef OPCODE_MODES}Fixuped:=Block.Size;{$endif}
if (Offset{Min} <= {$ifdef OPCODE_MODES}Block.Size{$else}Fixuped{$endif}){$ifdef OPCODE_MODES}and(OffsetMax<=Block.HybridSize_Max){$endif} then
begin
// можно заменять
// в случае необходимости выставляем флаг
if (Offset{Min} < {$ifdef OPCODE_MODES}Block.Size{$else}Fixuped{$endif})
{$ifdef OPCODE_MODES}or (OffsetMax < Block.HybridSize_Max){$endif}
then Storage.CurrentRefId := 1{SizeChanged:=true};
// копируем JumpOffset на случай если флаг не выставлен
Block.JumpOffset := Storage.StartBlock;
// размер
Block.Size := Offset{Min};
{$ifdef OPCODE_MODES}Block.HybridSize_Max := OffsetMax;{$endif}
// Next.RefId++ / Block.Next.RefId--
Buffer := @Storage.Blocks[Block.Fixuped];
Block.Fixuped := Storage.FakeBlock.O.Fixuped{Fixuped};
inc(Next.RefId);
dec(Buffer.RefId);
if (Buffer.RefId = 0) then
begin
inc(Storage.CurrentRefId, FLAG_BLOCKS_REMOVED);
RemoveFixupedBlock(Storage, Buffer);
end;
end;
// уходим на следующую итерацию если возможен перепрыжок
if (Next.Kind = fkLocalJumpBlock) then
begin
src_mask := Storage.FakeBlock.O.Reference{src_mask};
if (src_mask = src_mask and jmp_dest_mask[Next.cc_ex]) then goto rejump_loop;
end;
end;
end;
// по той же самой причине процесс заинлайнивания блоков вынесен в отдельную функцию
// Block прыгает в Storage.TopResult, а заканчивает в Next (fkLeaveJoined, fkLeave)
// до Next могут быть (а могут и не быть) только команды fkEmpty,fkNormal,fkJoined
// если команд не было, то Storage.TopResult=Next
//
// к этому времени в Block уже прописаны размеры (надо не забыть проставить JumpOffset и RefId++ в случае необходимости)
procedure OptimizeJumpsInlineBlocks(var Storage: TFixupedStorage; Block, Next: PFixupedBlock);
label
finalize_refid;
var
Count, X: integer;
Buffer: PFixupedBlock;
begin
// определяем количество команд в инлайне
Buffer := Storage.TopResult;
Count := 1;
while (Buffer <> Next) do
begin
dec(Next);
inc(Count);
end;
// отдельные условия для jmp варианта и для jcc
X := Block.cc_ex;
if (X = -1{jmp}) then
begin
if (Count = 1) then
begin
// только fkLeave или fkLeaveJoined
Block.Kind := Next.Kind;
Block.Cmd := Next.Cmd;
goto finalize_refid;
end else
begin
//Block.Kind := fkInline;
//Block.cc_ex := -2;
//Block.InlineBlocksCount := Count;
Block.Value := (Count shl 16) + ($fe00{-2 shl 2} + ord(fkInline));
end;
end else
begin
// jcc вариант
Inc(PFixupedBlockArray(Block)^[1].RefId); // Block.Next.RefId++
//Block.Kind := fkInline;
//Block.cc_ex := shortint(intel_cc_invert[X]);
//Block.InlineBlocksCount := Count;
Block.Value := (Count shl 16) + (ord(intel_cc_invert[X]) shl 8) + ord(fkInline);
end;
// выделяем память, копируем туда данные блоков
// очень важно понимать, что RefId внутри inline вообще не имеют никакого значения!
// делаю так потому, что компилятор глючит если делать наоборот
// в целом это не происходит только в том случае если jmp --> leave ===> leave
Count := Count*sizeof(TFixupedBlock);
Buffer := Storage.Heap.Alloc(Count+4{буфер для бинарной реализации прыжка});
Block.InlineBlocks := pointer(Buffer);
System.Move(Next^, Buffer^{Block.InlineBlocks^}, Count);
// чистим прыжок
finalize_refid:
Count := Next.RefId-1;
Next.RefId := Count;
if (Count(*{$ifdef OPCODE_MODES} shl 1{$endif}*) = 0) then
begin
inc(Storage.CurrentRefId, FLAG_BLOCKS_REMOVED);
RemoveFixupedBlock(Storage, Next);
end;
end;
// функция, выполняющая сразу несколько вещей:
// 1) удаляет блоки, на которые остались (такое тоже может быть) нулевые ссылки
// 2) дописывает реальный номер последнего блока и увеличивает счётчик ссылок на него
// 3) проставляет размеры каждого блока. информация для прыжков берётся из Storage (инициализация большими)
// 4) заполняет массив локальных прыжков
// 5) вызывает универсальную оптимизирующую функцию RemoveExcessJumps
// 6) вызов платформозависимой функции реализации и оптимизации прыжков
// 7) анализ используемых блоков, проставление номеров, инициализация ячеек и прочей информации FixupedInfo
// 8) подписывает номера блоков
// 9) доводит сложные текстовые команды
procedure RealizeJumps(var Storage: TFixupedStorage);
label
first_iteration, first_iteration_continue, normal_cmd_loop,
optimize_loop, local_jumps_loop, offset_calc_prev, offset_calc_next,
inline_loop_start, inline_loop;
var
Block: PFixupedBlock;
Cmd: POpcodeCmd;
Count, X: integer;
Size: integer;
Current: ^PFixupedBlock;
Offset{Min}: integer;
{$ifdef OPCODE_MODES}
OffsetMax: integer;
{$endif}
Next: PFixupedBlock;
Buffer: PFixupedBlock;
begin
// выделение памяти под массив LocalJumps
Storage.LocalJumpsCount := 0;
Size := sizeof(PFixupedBlock)*(Storage.BlocksCount+1);
Storage.LocalJumps := pointer(@Storage.LocalJumpsBuffers);
if (Size > sizeof(Storage.LocalJumpsBuffers)) then Storage.LocalJumps := Storage.Heap.Alloc(Size);
// сначала проходим по всем блокам
// попутно удаляя ненужное (если есть)
// в нормальном случае - подсчитываем размер
Block := pointer(Storage.Blocks);
first_iteration:
begin
if (Block.RefId{здесь ещё не появились текстовые блоки} = 0) then
begin
if (Block.Kind <> fkEmpty) then RemoveFixupedBlock(Storage, Block);
goto first_iteration_continue;
end;
{$ifdef OPCODE_MODES}
if (Storage.Mode = omAssembler) and (Block.Kind <> fkLocalJumpBlock) then goto first_iteration_continue;
{$endif}
case Block.Kind of
fkEmpty: {размер уже 0};
fkLeave: begin
// cmLeave всегда бинарный (даже в случае гибрида)
// ну а в случае ассемблера размер не будет учитываться
Block.Size{Min} := Block.Cmd.Size;
{$ifdef OPCODE_MODES}
Block.HybridSize_Max := Block.Size{Min};
{$endif}
end;
fkLeaveJoined, // jmp [... + offset ...]
fkJoined: // add edx, [... + offset ...] / mov esi, offset @1
begin
Cmd := Block.Cmd.Next;
X := Cmd.Size{HybridSize_MinMax};
// если команда бинарная или cmLeave - у неё просто берётся размер Size
// в случае гибрида - берётся Min/Max
// для ассемблера размер не играет роли
{$ifdef OPCODE_MODES}
if {Hybrid/ассемблер}(Cmd.Mode = cmText) then
begin
Block.HybridSize_Min := X and $ff{Cmd.HybridSize_Min};
Block.HybridSize_Max := X shr 8{Cmd.HybridSize_Max};
end else
{$endif}
begin
Block.Size{Min} := X;
{$ifdef OPCODE_MODES}
Block.HybridSize_Max := X;
{$endif}
end;
end;
fkGlobalJumpBlock: // call axml_get_attribute / jne PRE_cmd_ptr_addr_const
begin
// прыжки инициализируются как большие
Block.Size{Min} := Storage.JumpsInfo.big_sizes[Block.cc_ex];
{$ifdef OPCODE_MODES}
Block.HybridSize_Max := Block.Size;
{$endif}
end;
fkLocalJumpBlock: // jnle @2 / call @Specifier
begin
if (Block.Fixuped = NO_FIXUPED) then
begin
X := Storage.BlocksCount-1;
Block.Fixuped := X;
Inc(Storage.EndBlock.RefId);
end;
X := Storage.LocalJumpsCount;
Storage.LocalJumps[X] := Block;
inc(X);
Storage.LocalJumpsCount := X;
// прыжки инициализируются как большие
Block.Size{Min} := Storage.JumpsInfo.big_sizes[Block.cc_ex];
{$ifdef OPCODE_MODES}
Block.HybridSize_Max := Block.Size;
{$endif}
end;
{fkInline: ещё нет} // pop esi, pop edi, ret
else
// fkNormal: стандартная ситуация - массив команд
Cmd := Block.Cmd;
Count := Block.Value shr 8;
Size := 0{Min};
{$ifdef OPCODE_MODES}
Block.HybridSize_Max := Size{0};
{$endif}
normal_cmd_loop:
begin
X := Cmd.F.Value;
dec(Count);
{$ifdef OPCODE_MODES}
//if (Cmd.Mode = cmText) then
if (byte(X shr 16) = byte(cmText)) then
begin
// гибрид
Inc(Size, X and $ff);
Inc(Block.HybridSize_Max, (X shr 8) and $ff);
end else
// if (Cmd.Mode = cmBinary) then
{$endif}
begin
// бинарный
X := X and $ffff;
Inc(Size, X);
{$ifdef OPCODE_MODES}
Inc(Block.HybridSize_Max, X);
{$endif}
end;
Cmd := Cmd.Next;
if (Count <> 0) then goto normal_cmd_loop;
end;
Block.Size := Size{Min};
end;
first_iteration_continue:
if (Block <> Storage.EndBlock) then
begin
inc(Block);
goto first_iteration;
end;
end;
// завершаем список локальных прыжков
Storage.LocalJumps[Storage.LocalJumpsCount] := NO_JUMP;
// рассчёт смещений и оптимизация прыжков:
// 0) вызывается универсальная чистка
// 1) рассчитывается смещение
// 2) если есть возможность сжать до малого - сжать и выставить соответствующий флаг
// 3) тест на перепрыжок
// 4) тест на инлайн
{$ifdef OPCODE_MODES}
if (Storage.Mode = omAssembler) then
begin
RemoveExcessJumps(Storage);
end else
{$endif}
begin
Storage.CurrentRefId := FLAG_BLOCKS_REMOVED;
optimize_loop:
if (Storage.CurrentRefId > 1) then RemoveExcessJumps(Storage);
Storage.CurrentRefId := 0{SizeChanged:=false};
Current := pointer(Storage.LocalJumps);
dec(Current);
local_jumps_loop:
begin
inc(Current);
Block := Current^;
if (Block <> NO_JUMP) then //}if (Block = NO_JUMP) then goto local_jumps_loop_end;
begin
if (Block = nil) then goto local_jumps_loop;
// рассчёт смещения
// Next := @Storage.Blocks[Block.Fixuped]; / Storage.TopResult := Next;
Storage.TopResult := @Storage.Blocks[Block.Fixuped];{чтобы потом не вызывать Storage.Blocks[Block.Fixuped]};
Offset{Min} := 0;
Next := Storage.TopResult;
{$ifdef OPCODE_MODES}
OffsetMax := 0;
{$endif}
if (NativeInt(Next) <={вообще говоря не должно быть равно} NativeInt(Block)) then
begin
// подсчёт "назад"
offset_calc_prev:
begin
dec(Offset{Min}, Next.Size{Min});
{$ifdef OPCODE_MODES}
dec(OffsetMax, Next.HybridSize_Max);
{$endif}
inc(Next);
if (Next <> Block) then goto offset_calc_prev;
end;
end else
begin
// подсчёт "вперёд"
offset_calc_next:
begin
dec(Next);
inc(Offset{Min}, Next.Size{Min});
{$ifdef OPCODE_MODES}
inc(OffsetMax, Next.HybridSize_Max);
{$endif}
if (Next <> Block) then goto offset_calc_next;
end;
end;
// записываем новый Offset прыжка
// в "расширенном" режиме смещение может быть равно JUMP_OFFSET_TEXT
// это происходит тогда, когда смещение не константное (OffsetMin <> OffsetMax)
// в этом случае JumpOffset по сути становится не важен вообще
//
// кстати JumpOffset не важен ещё в случае если происходит изменение размера (Storage.CurrentRefId := true)
// потому что JumpOffset нужен для финального результата. А если выставлен флаг - будет как минимум ещё одна итерация
Block.JumpOffset := Offset;
{$ifdef OPCODE_MODES}
if (Offset <> OffsetMax) then Block.JumpOffset := JUMP_OFFSET_TEXT;
{$endif}
// далее пытаемся применить алгоритм сжатия прыжка (по умолчанию прыжок большой)
// но возможно он уже малый (текстовый/бинарный) или это call(фиксированный размер)
//
// по какой-то одному богу известной причине
// не удаётся откомпилировать этот код эффективнее
// но я сделал всё, что мог в данной ситуации, опробовал всё
// integer(Block.cc_ex) никак не получается по нормальному положить в регистр
{$ifNdef OPCODE_MODES}X := Block.cc_ex;{$endif}
if (Block.{$ifdef OPCODE_MODES}HybridSize_Max{$else}Size{$endif}<>Storage.JumpsInfo.small_sizes[{$ifdef OPCODE_MODES}Block.cc_ex{$else}X{$endif}]) then
begin
if (Storage.JumpsInfo.low_ranges[{$ifdef OPCODE_MODES}Block.cc_ex{$else}X{$endif}]<=Offset)
and (Offset<=Storage.JumpsInfo.high_ranges[{$ifdef OPCODE_MODES}Block.cc_ex{$else}X{$endif}]) then
begin
// сжимаем
Block.Size{Min} := SMALL_JUMP_SIZE{Storage.JumpsInfo.small_sizes[X]};
pbyte(@Storage.CurrentRefId)^ := 1;{SizeChanged:=true}
// смотрим/меняем верхнюю границу
// задавать Block.JumpOffset не имеет смысла
{$ifdef OPCODE_MODES}
if (Offset = OffsetMax) then Block.HybridSize_Max := SMALL_JUMP_SIZE{Storage.JumpsInfo.small_sizes[X]}
else
begin
Offset{X} := Block.cc_ex;
if (Storage.JumpsInfo.low_ranges[Offset{X}]<=OffsetMax)
and (OffsetMax<=Storage.JumpsInfo.high_ranges[Offset{X}]) then
Block.HybridSize_Max := SMALL_JUMP_SIZE{Storage.JumpsInfo.small_sizes[X]};
end;
{$endif}
end
end;
// осталось две ситуации:
// 3) тест на перепрыжок
// 4) тест на инлайн
//
// смотрим варианты перепрыжка в (глобальную)функцию или же прыжок,
// потом посмотрим возможность инлайна (если имеет смысл)
Next := Storage.TopResult;
case Next.Kind of
fkGlobalJumpBlock,
fkLocalJumpBlock:
begin
// if (jmp_src_mask[Block.cc_ex]=jmp_src_mask[Block.cc_ex]and jmp_dest_mask[Next.cc_ex])
// then OptimizeJumpsDifficult(Storage, Block, Next);
Offset := Block.cc_ex;
{$ifdef OPCODE_MODES}OffsetMax{$else}X{$endif} := Next.cc_ex;
Offset := jmp_src_mask[Offset];
{$ifdef OPCODE_MODES}OffsetMax{$else}X{$endif} := jmp_dest_mask[{$ifdef OPCODE_MODES}OffsetMax{$else}X{$endif}] and Offset;
if (Offset <> {$ifdef OPCODE_MODES}OffsetMax{$else}X{$endif}) then
begin
goto local_jumps_loop;
end else
begin
if (Next.Kind = fkLocalJumpBlock) then
begin
// сложный алгоритм, касающийся нескольких прыжков
OptimizeJumpsDifficult(Storage, Block, Next);
// Next := @Storage.Blocks[Block.Fixuped]; / Storage.TopResult := Next;
Storage.TopResult := @Storage.Blocks[Block.Fixuped];
Next := Storage.TopResult;
//goto inline_loop_start;
end else
begin
// переинлайн в глобальный возможен только в том случае
// если Block-прыжок большой.
// в этом случае просто подменяем Kind/Reference/Proc(Name)
if (Block.Size{Min} <> SMALL_JUMP_SIZE) then
begin
Current^ := nil{больше не локальный прыжок};
Block.Kind := fkGlobalJumpBlock;
Block.Reference := Next.Reference;
Block.Proc := Next.Proc{Name};
Dec(Next.RefId);
if (Next.RefId(*{$ifdef OPCODE_MODES} shl 1{$endif}*) = 0) then
begin
inc(Storage.CurrentRefId, FLAG_BLOCKS_REMOVED);
RemoveFixupedBlock(Storage, Next);
end;
end;
goto local_jumps_loop;
end;
end;
end;
end;
// 4) тест на инлайн (не работает для call)
// подсчитываем размер вплоть до fkLeave или fkLeaveJoined
// если инлайн не актуален - идём в следующую итерацию
Buffer := Next; {почему-то без этого "хака" с Next оптимизируется неправильно}
X := Block.cc_ex;
if (X{Block.cc_ex} = -2) then goto local_jumps_loop;
Offset{SizeMin} := (ord(X{Block.cc_ex}<>-1{jmp})*2); // 0 для jmp или SMALL_JUMP_SIZE для jcc
{$ifdef OPCODE_MODES}
OffsetMax{SizeMax} := Offset;
{$endif}
inline_loop:
begin
inc(Offset{SizeMin}, Buffer.Size{HybridSize_Min});
{$ifdef OPCODE_MODES}
inc(OffsetMax{SizeMax}, Buffer.HybridSize_Max);
{$endif}
if {$ifdef OPCODE_MODES}(OffsetMax > Block.HybridSize_Max){$else}(Offset > Block.Size){$endif}
or (Buffer{Next}.Kind > fkLeave{fkGlobalJumpBlock,fkLocalJumpBlock,fkInline}) then goto local_jumps_loop;
// команды
if (Buffer{Next}.Kind < fkLeaveJoined) then
begin
inc(Buffer{Next});
goto inline_loop;
end;
// делаем инлайн
// возможно нужно выставить флаг
if {$ifdef OPCODE_MODES}(OffsetMax < Block.HybridSize_Max) or{$endif}
(Offset < Block.Size{Min}) then pbyte(@Storage.CurrentRefId)^ := 1;{SizeChanged:=true}
// прописываем новые размеры
Block.Size := Offset;
{$ifdef OPCODE_MODES}
Block.HybridSize_Max := OffsetMax;
{$endif}
// для копирования вызываем отдельную функцию
OptimizeJumpsInlineBlocks(Storage, Block, Buffer{Next});
Current^ := nil{больше не локальный прыжок};
goto local_jumps_loop;
end;
end;
end;
if (Storage.CurrentRefId<>0{SizeChanged}) then goto optimize_loop;
end;
// подписать блоки, отделить текстовые от бинарных,
// узнать самую длинную бинарную последовательность
{$ifdef OPCODE_MODES}
if (Storage.Mode <> omBinary) then
begin
MarkupTextRoutine(Storage);
end;
{$endif}
// платформазависимая реализация бинарных прыжков
{$ifdef OPCODE_MODES}
if (Storage.Mode <> omAssembler) then
{$endif}
begin
Storage.Proc.FCallback(2, @Storage);
end;
end;
procedure BinaryBlocksWrite(Memory: pointer; Block: PFixupedBlock; var Storage: TFixupedStorage);
label
main_loop, cmd_list_loop, copy_case, next_block;
type
TMemoryParts = packed record
case Integer of
0: (Bytes: array[0..7] of byte);
1: (Words: array[0..3] of word);
2: (Dwords: array[0..2] of dword);
end;
PMemoryParts = ^TMemoryParts;
var
Cmd: POpcodeCmd;
CmdCount: integer;
Size: integer{dword};
begin
main_loop:
begin
if (Block.Kind = fkInline) then // inline например: pop esi, pop edi, ret
begin
// определяем и запоминаем количество блоков
CmdCount := Storage.BlocksCount;
Storage.BlocksCount := Block.InlineBlocksCount;
// сначала записываем отрицательный прыжок если есть
Size := 0;
if (Block.cc_ex >= 0) then
begin
pword(Memory)^ := pword(@Block.InlineBlocks[Block.InlineBlocksCount])^;
Size := SMALL_JUMP_SIZE{2};
end;
// потом вызываем "рекурсию" и восстанавливаем количество блоков
BinaryBlocksWrite(pointer(NativeInt(Memory)+integer(Size)), pointer(Block.InlineBlocks), Storage);
Storage.BlocksCount := CmdCount;
end else
begin
Cmd := Block.Cmd{вместо nil};
CmdCount := 0;
case Block.Kind of
fkEmpty: goto next_block;
fkNormal: begin
// стандартная ситуация
CmdCount := Block.Value shr 8;
end;
fkJoined, // add edx, [... + offset ...] / mov esi, offset @1
fkLeaveJoined: // jmp [... + offset ...]
begin
// todo join?
Cmd := Cmd.Next;
inc(CmdCount); //CmdCount := 1;
end;
fkLeave: begin
// ret(n), leave, jmp reg, jmp mem
inc(CmdCount); //CmdCount := 1;
end;
fkGlobalJumpBlock, // call axml_get_attribute / jne PRE_cmd_ptr_addr_const
fkLocalJumpBlock: // jnle @2 / call @Specifier
begin
inc(CmdCount); //CmdCount := 1;
Size := Block.Size;
Cmd := pointer(@Block.JumpBuffer);
dec(Cmd);
goto copy_case;
end;
end;
// код копирования данных по команде(ам) в буфер
// копирование происходит с конца блока в начало
Inc(NativeInt(Memory), Block.Size);
cmd_list_loop:
begin
Size := Cmd.Size;
// Memory -= Size; / CopyMemory(Memory, Cmd.Data, Size);
//
// к сожалению не получается сделать код копирования более цивилизованно
// потому что компилятор отказывается эффективно расходовать регистры
// в то время как edx/ecx можно свободно использовать
Dec(NativeInt(Memory), Size);
copy_case:
case Size of
0: ;
1: PMemoryParts(Memory).Bytes[0] := POpcodeCmdData(Cmd).Bytes[0];
2: PMemoryParts(Memory).Words[0] := POpcodeCmdData(Cmd).Words[0];
3: begin
PMemoryParts(Memory).Words[0] := POpcodeCmdData(Cmd).Words[0];
PMemoryParts(Memory).Bytes[2] := POpcodeCmdData(Cmd).Bytes[2];
end;
4: PMemoryParts(Memory).Dwords[0] := POpcodeCmdData(Cmd).Dwords[0];
5: begin
PMemoryParts(Memory).Dwords[0] := POpcodeCmdData(Cmd).Dwords[0];
PMemoryParts(Memory).Bytes[4] := POpcodeCmdData(Cmd).Bytes[4];
end;
6: begin
PMemoryParts(Memory).Dwords[0] := POpcodeCmdData(Cmd).Dwords[0];
PMemoryParts(Memory).Words[2] := POpcodeCmdData(Cmd).Words[2];
end;
7: begin
PMemoryParts(Memory).Dwords[0] := POpcodeCmdData(Cmd).Dwords[0];
PMemoryParts(Memory).Words[2] := POpcodeCmdData(Cmd).Words[2];
PMemoryParts(Memory).Bytes[6] := POpcodeCmdData(Cmd).Bytes[6];
end;
8: begin
PMemoryParts(Memory).Dwords[0] := POpcodeCmdData(Cmd).Dwords[0];
PMemoryParts(Memory).Dwords[1] := POpcodeCmdData(Cmd).Dwords[1];
end;
else
POpcodeCmd(Storage.Current) := Cmd;
System.Move(POpcodeCmdData(Cmd).Bytes, Memory^, Cmd.Size);
Cmd := POpcodeCmd(Storage.Current);
end;
// next Cmd
dec(CmdCount);
Cmd := Cmd.Next;
if (CmdCount <> 0) then goto cmd_list_loop;
end;
end;
// next block
next_block:
CmdCount := Storage.BlocksCount-1;
Inc(NativeInt(Memory), Block.Size);
Storage.BlocksCount := CmdCount;
inc(Block);
if (CmdCount <> 0) then goto main_loop;
end;
end;
{$ifdef OPCODE_MODES}
const
W_CRLF = 13 or (10 shl 8);
W_SPSP = 32 or (32 shl 8);
function MemoryFormat(const Memory: pansichar; const Fmt: ShortString; const Args: array of const): pansichar;
begin
Result := Memory + SysUtils.FormatBuf(Memory^, high(integer), Fmt[1], Length(Fmt), Args);
end;
// записываем бинарные данные в текстовом(гибридном) виде
// например
// DD $C0D9EED9,$64248489,$D9000001,$01A42494,$C0D90000,$C9D9C1D9,$CAD9CBD9,$6CE9C9D9,$90FFFFE9,$0026748D
// или
// DB $D9,$EE,$D9,$C0,$89,$84
function HybridBinaryWrite(Memory: pansichar; BinarySize{не 0}: integer; const Storage{Binary}: TFixupedStorage): pansichar;
label
dword_lines_loop, dword_line_start, dwords_loop, dwords_lines_end, bytes_loop;
const
_D = 32 or (32 shl 8) or (ord('D') shl 16);
_DD = _D or (ord('D') shl 24);
_DB = _D or (ord('B') shl 24);
_HEX_FIRST = 32 or (ord('$') shl 8);
_HEX_DEFAULT = ord(',') or (ord('$') shl 8);
HEX_CHARS: array[0..15] of ansichar = '0123456789ABCDEF';
var
flags: dword; // флаги и буфер
Binary: pdword;
Count: integer;
begin
flags := ord(Memory <> Storage.TextBuffer);
Binary := Storage.BinaryBuffer;
Result := Memory;
// записываем dword-линии
if (BinarySize < 40) then goto dwords_lines_end;
dword_lines_loop:
begin
Count := 10;
// начало линии
dword_line_start:
begin
if (flags <> 0{CRLF}) then
begin
pword(Result)^ := W_CRLF;
inc(Result, 2);
end;
// DD
pdword(Result)^ := _DD;
inc(Result, 4);
flags := _HEX_FIRST;
end;
// массив dword-ов
dwords_loop:
begin
pword(Result)^ := flags;
dec(Count);
flags := Binary^;
inc(Binary);
// hex
Result[9] := HEX_CHARS[flags and $f];
flags := flags shr 4;
Result[8] := HEX_CHARS[flags and $f];
flags := flags shr 4;
Result[7] := HEX_CHARS[flags and $f];
flags := flags shr 4;
Result[6] := HEX_CHARS[flags and $f];
flags := flags shr 4;
Result[5] := HEX_CHARS[flags and $f];
flags := flags shr 4;
Result[4] := HEX_CHARS[flags and $f];
flags := flags shr 4;
Result[3] := HEX_CHARS[flags and $f];
Result[2] := HEX_CHARS[flags shr 4];
// continue
inc(Result, 10);
flags := _HEX_DEFAULT;
if (Count <> 0) then goto dwords_loop;
end;
dec(BinarySize, 40);
end;
dwords_lines_end:
// некоторый (а возможно и весь остаток) можно записать dword-ами
if (BinarySize <> 0) and ((BinarySize and 3 = 0) or (BinarySize > 30)) then
begin
Count := BinarySize shr 2;
BinarySize := (BinarySize and 3) + 40{потому что потом будет декремент};
goto dword_line_start;
end;
// возможно остаток нужно дописать байтами
if (BinarySize <> 0) then
begin
if (flags <> 0{CRLF}) then
begin
pword(Result)^ := W_CRLF;
inc(Result, 2);
end;
// DB
pdword(Result)^ := _DB;
inc(Result, 4);
flags := _HEX_FIRST;
// массив байтов
bytes_loop:
begin
pword(Result)^ := flags;
dec(BinarySize);
flags := pbyte(Binary)^;
inc(pbyte(Binary));
// hex
Result[2] := HEX_CHARS[flags shr 4];
Result[3] := HEX_CHARS[flags and $f];
// continue
inc(Result, 4);
flags := _HEX_DEFAULT;
if (BinarySize <> 0) then goto bytes_loop;
end;
end;
end;
// задачи функции:
// 1) определить бинарную последовательность
// 2) узнать, сколько байт она займёт в гибридном виде
// 3) если разделение было только меткой - начать заново
// 4) вернуть топовый блок в Storage.TopResult
function SmartHybridBinarySize(Block: PFixupedBlock; var Storage: TFixupedStorage): integer;
label
binary_start, binary_loop;
const
LINE_LEFT_LENGTH = 2+4; // #13#10' DD'; // следующий пробел считается наравне с запятой
var
EndBlock: PFixupedBlock;
BinarySize: integer;
DD_Lines: integer;
begin
Result := 0;
EndBlock := Storage.EndBlock;
binary_start:
BinarySize := 0;
binary_loop:
begin
inc(BinarySize, Block.Size);
inc(Block);
if (NativeInt(Block) <= NativeInt(EndBlock)) and
((Block.Kind = fkEmpty) or (Block.RefId and (not REFID_ISNEXT) = 0)) then goto binary_loop;
end;
// переводим бинарный размер в гибридный
DD_Lines := BinarySize div 40;
BinarySize := BinarySize - DD_Lines*40; // mod 40
Result := Result + DD_Lines * (LINE_LEFT_LENGTH{отступ слева}+40*2{hex-представление}+2{,$}*10);
if (BinarySize <> 0) then
begin
if (BinarySize and 3 = 0) then
begin
// только DD
Result := Result + LINE_LEFT_LENGTH + (BinarySize shr 2)*(4*2{hex}+2{,$})
end else
if (BinarySize <= 30) then
begin
// только DB
Result := Result + LINE_LEFT_LENGTH + BinarySize*(2{hex}+2{,$})
end else
begin
// сначала DD, потом DB
Result := Result + LINE_LEFT_LENGTH + (BinarySize shr 2)*(4*2{hex}+2{,$}) +
LINE_LEFT_LENGTH + (BinarySize and 3)*(2{hex}+2{,$})
end;
end;
// если можно продолжить (после метки)
if (NativeInt(Block) <= NativeInt(EndBlock)) and
((Block.Kind = fkEmpty) or (Block.RefId and (REFID_ISNEXT-1) = 0)) then goto binary_start;
// топовый блок
dec(Block);
Storage.TopResult := Block;
end;
// функция по сути выполняет несколько действий:
// 1) подсчёт количества бинарных команд (последний бинарный нужно записать в Storage.TopResult)
// 2) запись бинарных данных через BinaryBlocksWrite()
// 3) запись гибридных данных в Memory через HybridBinaryWrite()
function SmartHybridBinaryWrite(const Memory: pansichar; Block: PFixupedBlock; var Storage: TFixupedStorage): pansichar;
label
binary_loop;
var
EndBlock: PFixupedBlock;
BinarySize, Count: integer;
begin
// рассчитываем размер и количество бинарных блоков
BinarySize := 0;
Count := 0;
Storage.TopResult := Block;
EndBlock := Storage.EndBlock;
binary_loop:
begin
inc(BinarySize, Block.Size);
inc(Block);
inc(Count);
if (NativeInt(Block) <= NativeInt(EndBlock)) and
((Block.Kind = fkEmpty) or (Block.RefId and (not REFID_ISNEXT) = 0)) then goto binary_loop;
end;
// восстанавливаем блок
// записываем последний бинарный блок
dec(Block);
// swap(Storage.TopResult, Block);
EndBlock := Storage.TopResult;
Storage.TopResult := Block;
Block := EndBlock;
// записываем бинарные данные
Storage.BlocksCount{восстанавливать не нужно, потому что всёравно смотрится Storage.EndBlock} := Count;
BinaryBlocksWrite(Storage.BinaryBuffer, Block, Storage);
// записываем гибридные данные
Result := HybridBinaryWrite(Memory, BinarySize, Storage);
end;
// размер списка (или одной) команд
(*function TextCmdListSize(Cmd: POpcodeCmd; Count: integer): integer;
label
main_loop;
begin
Result := 0;
main_loop:
begin
inc(Result, 4{#13#10__});
case Cmd.Mode of
cmJoined: begin
end;
cmJumpBlock: begin
Cmd.
end;
else
// cmText, cmLeave
Inc(Result, Length(POpcodeCmdText(Cmd).Str^));
end;
dec(Count);
if (Count <> 0) then goto main_loop;
end;
end; *)
// пишем форматированную метку
function TextLabelWrite(Memory: pansichar; LabelLength: integer; Number: integer): pansichar;
const
FMT: array[0..3] of ansichar = '@%*d';
begin
Result := Memory + SysUtils.FormatBuf(Memory^, high(integer), FMT, Length(FMT),[LabelLength, Number]);
while (Memory <> Result) do
begin
if (Memory^ = #32) then Memory^ := '0';
inc(Memory);
end;
end;
// записать инлайн-последовательность
function TextInlineBlocksWrite(Memory: pansichar; Block: PFixupedBlock; var Storage: TFixupedStorage): pansichar;
label
blocks_loop, cmd_loop;
var
S: PShortString;
BlocksCount, Size: integer;
begin
// прыжок
if (Block.cc_ex >= 0) then
begin
if (Storage.TextBuffer <> Memory) then
begin
pword(Memory)^ := W_CRLF;
inc(Memory, 2);
end;
// jmp/jcc
//Memory := MemoryFormat(Memory, ' %s ', [Storage.JumpsInfo.names^[Block.cc_ex]^]);
pword(Memory)^ := W_SPSP;
S := Storage.JumpsInfo.names^[Block.cc_ex];
Size := Length(S^);
inc(Memory, Size+2);
System.Move(S^[1], Pointer(NativeInt(Memory)-Size)^, Size);
// метка
Memory := TextLabelWrite(Memory, Storage.LabelLength, PFixupedBlockArray(Block)^[1].Number);
end;
// пишем последовательность, предварительно сохранив переменные
BlocksCount := Block.InlineBlocksCount;
Block := pointer(Block.InlineBlocks);
blocks_loop:
begin
if (Block.Kind <> fkEmpty) then
begin
if (Block.Kind = fkNormal) then
begin
//Cmd := Block.Cmd;
//CmdCount := Block.Value shr 8;
Storage.TopResult := Block;
Storage.CurrentRefId := BlocksCount;
BlocksCount{CmdCount} := Block.Value shr 8;
Block{Cmd} := pointer(Block.Cmd);
cmd_loop:
begin
if (Storage.TextBuffer <> Memory) then
begin
pword(Memory)^ := W_CRLF;
inc(Memory, 2);
end;
pword(Memory)^ := W_SPSP;
S := POpcodeCmdText(Block.Cmd).Str;
Size := Length(S^);
inc(Memory, Size+2);
System.Move(S^[1], Pointer(NativeInt(Memory)-Size)^, Size);
dec(BlocksCount{CmdCount});
Block{Cmd} := pointer(POpcodeCmd(Block{Cmd}).Next);
if (BlocksCount{CmdCount} <> 0) then goto cmd_loop;
end;
Block := Storage.TopResult;
BlocksCount := Storage.CurrentRefId;
end else
// fkLeave
begin
if (Storage.TextBuffer <> Memory) then
begin
pword(Memory)^ := W_CRLF;
inc(Memory, 2);
end;
pword(Memory)^ := W_SPSP;
S := POpcodeCmdText(Block.Cmd).Str;
Size := Length(S^);
inc(Memory, Size+2);
System.Move(S^[1], Pointer(NativeInt(Memory)-Size)^, Size);
end;
end;
dec(BlocksCount);
inc(Block);
if (BlocksCount <> 0) then goto blocks_loop;
end;
// результат
Result := Memory;
end;
// записать команду fkJoined или fkLeaveJoined
// в любом случае данные ссылаются на локальный прыжок!
// потому что инача имя функции уже прописалось бы в команду!
function TextJoinedCmdWrite(Memory: pansichar; const Joined: POpcodeCmdJoined; var Storage: TFixupedStorage): pansichar;
var
buffer1, buffer2: string[6]; // худший случай "@65535"
begin
// перевод каретки
if (Storage.TextBuffer <> Memory) then
begin
pword(Memory)^ := W_CRLF;
inc(Memory, 2);
end;
// пробелы
pword(Memory)^ := W_SPSP;
inc(Memory, 2);
// первый параметр - локальный или глобальный
pbyte(@buffer1)^ := Storage.LabelLength+1;
TextLabelWrite(pansichar(@buffer1[1]), Storage.LabelLength, Storage.Blocks[Joined.Data[0].Block.O.Fixuped].Number);
if (Joined.Cmd.Param and 3 <> 3) then
begin
// команда с одним блоком
Result := MemoryFormat(Memory, POpcodeCmdText(Joined.Cmd.Next).Str^, [buffer1]);
end else
begin
// команда с двумя блоками
pbyte(@buffer2)^ := Storage.LabelLength+1;
TextLabelWrite(pansichar(@buffer2[1]), Storage.LabelLength, Storage.Blocks[Joined.Data[1].Block.O.Fixuped].Number);
Result := MemoryFormat(Memory, POpcodeCmdText(Joined.Cmd.Next).Str^, [buffer1, buffer2]);
end;
end;
// записать команды fkNormal или fkLeave
// на этот раз я решил не выпендриваться и вызывать рекурсию от конца в начало в случае списка команд
// количество необходимых команд на запись - Storage.CurrentRefId
function TextCmdWrite(Memory: pansichar; const Cmd: POpcodeCmd; var Storage: TFixupedStorage): pansichar;
var
S: PShortString;
Size: integer;
begin
// рекурсия
dec(Storage.CurrentRefId);
if (Storage.CurrentRefId <> 0) then Memory := TextCmdWrite(Memory, Cmd.Next, Storage);
// перевод каретки
if (Storage.TextBuffer <> Memory) then
begin
pword(Memory)^ := W_CRLF;
inc(Memory, 2);
end;
// команда
pword(Memory)^ := W_SPSP;
S := POpcodeCmdText(Cmd).Str;
Size := Length(S^);
inc(Memory, Size+2);
System.Move(S^[1], Pointer(NativeInt(Memory)-Size)^, Size);
// результат
Result := Memory;
end;
// запись массива блоков вплоть до Storage.EndBlock
// т.е. по сути самая главная записывающая функция для текста
procedure TextBlocksWrite(Memory: pansichar; Block: PFixupedBlock; var Storage: TFixupedStorage);
label
main_loop;
var
LastNumber: integer;
S: PShortString;
Size: integer;
begin
LastNumber := 0;
Block := pointer(Storage.Blocks);
main_loop:
begin
// если нужна метка
if (LastNumber <> Block.Number) then
begin
LastNumber := Block.Number;
// перевод каретки
if (Storage.TextBuffer <> Memory) then
begin
pword(Memory)^ := W_CRLF;
inc(Memory, 2);
end;
// сама метка + двоеточие
Memory := TextLabelWrite(Memory, Storage.LabelLength, LastNumber);
Memory^ := ':';
inc(Memory);
end;
if (Block.RefId and REFID_FLAG_TEXT = 0) then
begin
// бинарная последовательность команд
Memory := SmartHybridBinaryWrite(Memory, Block, Storage);
Block := Storage.TopResult;
end else
begin
// текстовый блок
case Block.Kind of
fkNormal: // стандартная ситуация
begin
Storage.CurrentRefId{Count} := Block.Value shr 8;
Memory := TextCmdWrite(Memory, Block.Cmd, Storage);
end;
fkJoined, // add edx, [... + offset ...] / mov esi, offset @1
fkLeaveJoined: // jmp [... + offset ...]
begin
Memory := TextJoinedCmdWrite(Memory, POpcodeCmdJoined(Block.Cmd), Storage);
end;
fkLeave: // ret(n), leave, jmp reg, jmp mem
begin
Storage.CurrentRefId{Count} := 1;
Memory := TextCmdWrite(Memory, Block.Cmd, Storage);
end;
fkGlobalJumpBlock, // call axml_get_attribute / jne PRE_cmd_ptr_addr_const
fkLocalJumpBlock: // jnle @2 / call @Specifier
begin
// перевод каретки
if (Storage.TextBuffer <> Memory) then
begin
pword(Memory)^ := W_CRLF;
inc(Memory, 2);
end;
// jmp/jcc/call
pword(Memory)^ := W_SPSP;
S := Storage.JumpsInfo.names^[Block.cc_ex];
Size := Length(S^);
inc(Memory, Size+2);
System.Move(S^[1], Pointer(NativeInt(Memory)-Size)^, Size);
// метка или имя функции
Memory^ := #32;
inc(Memory);
if (Block.Kind = fkGlobalJumpBlock) then
begin
Size := StrLen(Block.ProcName);
inc(Memory, Size);
System.Move(Block.ProcName^, Pointer(NativeInt(Memory)-Size)^, Size);
end else
begin
Memory := TextLabelWrite(Memory, Storage.LabelLength, Storage.Blocks[Block.Fixuped].Number);
end;
end;
fkInline: // pop esi, pop edi, ret
begin
Memory := TextInlineBlocksWrite(Memory, Block, Storage);
end;
end;
end;
inc(Block);
if (NativeInt(Block) <= NativeInt(Storage.EndBlock)) then goto main_loop;
end;
{$ifdef OPCODE_TEST}
Size := NativeInt(Memory)-NativeInt(Storage.TextBuffer);
if (Size <> Storage.Proc.Size) then
raise EOpcodeLib.CreateFmt('Fail writed text size: %d bytes (%d needed)', [Size, Storage.Proc.Size]); //raise_parameter;
{$endif}
end;
{$endif}
// заключительная стадия фиксации - записать результирующие данные
// состоит из следующих подэтапов:
// 1) рассчитываем итоговый размер. Задаём размер памяти функции
// 2) записываем итоговый кусок
// 3) в случае бинарного режима управляем FFixupedInfo и заполняем нужные куски данных
//
// функция вызывает дочерние функции BinaryBlocksWrite()/TextBlocksWrite()
// только потому, что возможны инлайновые блоки - в этом случае логично вызывать вторую ветвь "рекурсии"
procedure FixupDataWrite(var Storage: TFixupedStorage);
{$ifdef OPCODE_MODES}
label
text_block_loop, text_block_cmd_loop, text_inline_loop, text_inline_cmd_loop, text_block_continue;
{$endif}
var
i: integer;
Block: PFixupedBlock;
ResultSize: integer;
{$ifdef OPCODE_MODES}
Count: integer;
Cmd: POpcodeCmd;
{$endif}
begin
Block := pointer(Storage.Blocks);
{$ifdef OPCODE_MODES}
if (Storage.Mode <> omBinary) then
begin
// ассемблер или гибрид
// подсчитываем размер
// сначала смотрим, сколько займут строки меток
ResultSize := (Storage.LabelLength+{#13#10@____:}4)*Storage.LabelCount;
// потом проходимся по всем блокам
// отдельно считаем бинарные последовательности и текст
text_block_loop:
begin
if (Block.RefId and REFID_FLAG_TEXT = 0) then
begin
Inc(ResultSize, SmartHybridBinarySize(Block, Storage));
Block := Storage.TopResult;
end else
begin
Cmd := Block.Cmd;
case Block.Kind of
fkNormal: // стандартная ситуация
begin
Count := Block.Value shr 8;
end;
fkLeave: // ret(n), leave, jmp reg, jmp mem
begin
Count := 1;
end;
fkLeaveJoined, // jmp [... + offset ...]
fkJoined: // add edx, [... + offset ...] / mov esi, offset @1
begin
// %s заменяется например на @label
Count := Storage.LabelLength-1;
Inc(ResultSize, Count);
if (Cmd.Param and 3 = 3) then Inc(ResultSize, Count);
Count := 1;
Cmd := Cmd.Next;
end;
fkGlobalJumpBlock: begin
// Count := 0;
Inc(ResultSize, 5{#13#10__XXX_});
Inc(ResultSize,StrLen(Block.ProcName));
goto text_block_continue;
end;
fkLocalJumpBlock: begin
// Count := 0;
Inc(ResultSize, Length(Storage.JumpsInfo.names[Block.cc_ex]^)+Storage.LabelLength+6{#13#10__XXX_@});
goto text_block_continue;
end;
{fkInline: не бывает в текстовом виде}
else
goto text_block_continue;
end;
text_block_cmd_loop:
begin
Inc(ResultSize, Length(POpcodeCmdText(Cmd).Str^) + 4{#13#10__});
dec(Count);
Cmd := Cmd.Next;
if (Count <> 0) then goto text_block_cmd_loop;
end;
end;
text_block_continue:
inc(Block);
if (NativeInt(Block) <= NativeInt(Storage.EndBlock)) then goto text_block_loop;
end;
// задаём размер(ы), записываем
if (ResultSize = 0) then
begin
Storage.Proc.Size := 0;
end else
begin
Storage.Proc.Size := ResultSize-{размер первого #13#10}2;
Storage.TextBuffer := Storage.Proc.Memory;
TextBlocksWrite(Storage.TextBuffer, pointer(Storage.Blocks), Storage);
end;
end else
{$endif}
begin
// бинарный режим
ResultSize := 0;
// прописываем смещение и одновременно подсчитываем общий размер
for i := 0 to Storage.BlocksCount-1 do
begin
Block.Offset := ResultSize;
inc(ResultSize, Block.Size);
inc(Block);
end;
// задаём размер, записываем
Storage.Proc.Size := ResultSize;
BinaryBlocksWrite(Storage.Proc.Memory, pointer(Storage.Blocks), Storage);
end;
end;
{$ifdef MSWINDOWS}
var
CurrentProcess: THandle=0;
{$endif}
// самая сложная функция, которая:
// 1) использует Heap в качестве менеджера рабочих данных
// 2) может зачистить свои рассчёты по окончанию Fixup-а
// 3) перезаполняет внутренний информационный буфер (FFixupedInfo)
// 4) проводит необходимые доводки команд
// 5) оптимизирует прыжки
// 6) размечает блоки
// 7) определяет итоговый размер
// 8) записывает данные
// 9) чистит за собой служебные данные
procedure TOpcodeProc.Fixup();
var
S: integer;
HeapState: TOpcodeHeapState;
SubsLine: POpcodeSubscribe;
SubsBlock: POpcodeBlock;
Storage: TFixupedStorage;
Block: PFixupedBlock;
begin
// сохраняем состояние памяти
// чтобы по окончании его восстановить
FHeap.SaveState(HeapState);
// выравниваем память в Heap на 4 байта
S := NativeInt(Heap.FState.Current) and 3;
if (S <> 0) then
begin
S := 4-S;
Inc(NativeInt(Heap.FState.Current), S);
Dec(Heap.FState.Margin, S);
end;
// инициализация
with Storage do
begin
Heap := Self.Heap;
Proc := Self;
{$ifdef OPCODE_MODES}
Mode := Self.Mode;
{$endif}
SubscribedLines.Next := nil;
SubscribedLines.Block := nil;
FakeBlock.CmdList := nil;
FakeBlock.P.Proc := Self;
BlocksCount := 0;
// заполнение таблиц
Self.FCallback(0, @Storage);
// блоки
BlocksAvailable := Length(BlocksBuffer);
Blocks := pointer(@BlocksBuffer);
// блоки, на которые есть внешние ссылки
References := pointer(@ReferencesBuffer);
S := Self.F.BlocksReferenced*sizeof(word);
if (S > sizeof(ReferencesBuffer)) then References := Heap.Alloc(S);
FillChar(References^, S, $ff{NO_FIXUPED});
end;
FLastBinaryCmd := NO_CMD;
try
// (рекурсивно) заполняем список блоков и подкоманд
// первый блок помечаем единицей чтобы не удалялся
Storage.CurrentRefId := 1;
Storage.Current := Self.B_call_modes.uni;
AddFixupedBlocksLine(Storage);
// в конечном счёте нужно прописать завершающую команду (EndBlock)
// в любом случае это будет fkLeave
// только в обычном случае размер команды маленький и RefId может быть равен нулю,
// а в случае RET_OFF размер делаем огромный (чтобы не инлайнелось) и RefId увеличиваем (чтобы не удалилось)
// RefId декрементируется внутри MarkupTextRoutine. Это важно для вставок меток(текстовый режим).
with Storage do
begin
// определяем RefId + быстрое удаление последнего local jump в EndBlock
S := integer(REFID_ISNEXT);
Block := @Blocks[BlocksCount-1];
while (Block <> pointer(Blocks)) and (Block.Kind = fkLocalJumpBlock) and (Block.Fixuped = NO_FIXUPED) do
begin
Block.Value := 0{fkEmpty};
Block.Size{Min} := 0;
{$ifdef OPCODE_MODES}
Block.HybridSize_Max := 0;
{$endif}
dec(Block);
end;
with Block^ do
case Kind of
// бинарность/текстовость + ret(n)(0), leave(1), jmp reg(2), jmp mem(3)
fkLeave, fkLeaveJoined: S := 0;
// прыжок в другой блок
fkLocalJumpBlock,
fkGlobalJumpBlock: if (cc_ex = -1{jmp}) then S := 0;
end;
{$ifdef OPCODE_TEST}
if (BlocksCount = NO_FIXUPED) then raise_parameter;
{$endif}
if (BlocksCount = BlocksAvailable) then GrowFixupedBlocks(Storage);
inc(BlocksCount);
EndBlock := @Blocks[BlocksCount-1];
with EndBlock^ do
begin
Kind := fkLeave;
Cmd := @LastRetCmd.Cmd;
if (Self.RetN <> RET_OFF) then
begin
Self.FCallback(1, @Storage);
end else
begin
inc(S);
{$ifdef OPCODE_MODES}
if (Storage.Proc.Mode = omAssembler) then
begin
LastRetCmd.Cmd.F.ModeParam := ord(cmLeave) + ((128{текст}+0{ret(n)}) shl 8);
end else
{$endif}
begin
LastRetCmd.Cmd.F.Size := high(word);
LastRetCmd.Cmd.F.ModeParam := ord(cmLeave) + ((0{бинарный}+0{ret(n)}) shl 8);
end;
end;
RefId := S;
end;
end;
// (до)реализовать и оптимизировать прыжки
RealizeJumps(Storage);
// снимаем размер с последнего блока если он фейк
if (Self.RetN = RET_OFF) then
with Storage.EndBlock^ do
begin
Size{Min} := 0;
{$ifdef OPCODE_MODES}
HybridSize_Max := 0;
{$endif}
Cmd.F.Size := 0;
end;
// записываем данные
FixupDataWrite(Storage);
// чистка кеша команд (чтобы не было проблем с JIT-выполнением этого кода)
if (Size <> 0) and (Self.Storage <> nil) and (Self.Storage.JIT) then
begin
{$ifdef MSWINDOWS}
if (CurrentProcess = 0) then CurrentProcess := Windows.GetCurrentProcess;
Windows.FlushInstructionCache(CurrentProcess, Self.Memory, Self.Size);
{$endif}
end;
// обновляем локальные смещения для внешних ссылок (работает только для бинарных)
{$ifdef OPCODE_MODES}
if (Storage.Mode = omBinary) then
{$endif}
begin
{ for S := 0 to Self.F.BlocksReferenced-1 do
if (Manager.FReferencedBlocks[S] <> nil) then
begin
// todo
end; }
end;
// чистка полей "FixupedBlock"
SubsLine := @Storage.SubscribedLines;
while (SubsLine <> nil) do
begin
SubsBlock := SubsLine.Block;
while (SubsBlock <> nil) and (SubsBlock.O.Fixuped <> NO_FIXUPED) do
begin
SubsBlock.O.Fixuped := NO_FIXUPED;
SubsBlock := SubsBlock.N.Next;
end;
SubsLine := SubsLine.Next;
end;
// восстанавливаем состояние памяти
FHeap.RestoreState(HeapState);
finally
// чистка памяти под буфер если был использован
if (Storage.Blocks <> pointer(@Storage.BlocksBuffer)) then
FreeMem(Storage.Blocks);
end;
end;
// -------------- универсальные тестовые функции -----------------------
{$ifdef OPCODE_TEST}
procedure test_size_ptr(ptr: size_ptr);
begin
if (ptr > high(size_ptr)) then raise_parameter;
end;
procedure test_intel_reps(reps: intel_rep);
begin
if (reps > high(intel_rep)) then raise_parameter;
end;
procedure test_intel_cc(cc: intel_cc);
begin
if (cc > high(intel_cc)) then raise_parameter;
end;
function test_const(const v_const: TOpcodeConst; const is64: boolean; const Proc: TOpcodeProc): integer{для проверки PValue};
begin
if (v_const.Kind > high(const_kind)) then raise_parameter;
// проверка актуальности значений
Result := 0;
case v_const.Kind of
ckPValue: begin
Result := v_const.F.PValue^;
if (is64) then inc(Result, v_const.F.PValue64^ shr 32);
end;
ckBlock: begin
Result := NativeInt(v_const.Block.CmdList);
{$ifdef OPCODE_MODES}
if (Proc.Mode <> omBinary) and (Proc <> v_const.Block.P.Proc) then
raise_parameter;
{$endif}
if (Proc.Storage <> v_const.Block.P.Proc.Storage) then raise_parameter;
{$ifdef OPCODE_MODES}
// на случай Storage nil
if (Proc.Mode <> v_const.Block.P.Proc.Mode) then raise_parameter;
{$endif}
end;
ckVariable: begin
Result := v_const.Variable.FOFFSET + NativeInt(v_const.Variable.FMemory);
{$ifdef OPCODE_MODES}
if (Proc.Mode <> omBinary) then raise_parameter;
{$endif}
if (Proc.Storage <> v_const.Variable.Storage) then raise_parameter;
end;
{$ifdef OPCODE_MODES}
ckCondition,ckOffsetedCondition:
begin
if (v_const.Condition = nil) or (v_const.Condition^ = #0) then raise_parameter;
if (Proc.Mode = omBinary) then raise_parameter;
end;
{$endif}
end;
end;
procedure test_intel_address(const addr: TOpcodeAddress; const x64: boolean; const Proc: TOpcodeProc);
begin
// регистры
if (addr.F.Scale.intel > high(intel_scale)) then raise_parameter;
if (x64) then
begin
if not (addr.F.Reg.v in [rax..r15{reg_x64_addr}]) then raise_parameter;
if (addr.F.Scale.intel >= x1_plus) and (not (addr.F.Plus.v in [rax..r15{reg_x64_addr}])) then raise_parameter;
end else
begin
if not (addr.F.Reg.v in [eax..edi{reg_x86_addr}]) then raise_parameter;
if (addr.F.Scale.intel >= x1_plus) and (not (addr.F.Plus.v in [eax..edi{reg_x86_addr}])) then raise_parameter;
end;
// проверка esp/rsp в качестве индекса
if (addr.F.Reg.v in [esp, rsp]) then
case addr.F.Scale.intel of
xNone, x1: {ничего};
x1_plus: if (addr.F.Plus.v in [esp, rsp]) then raise_parameter;
else
// x2, x4, x8, x2_plus, x4_plus, x8_plus
raise_parameter;
end;
// константа
{$ifdef OPCODE_MODES}
if (x64) and (Proc.Mode <> omBinary) and (addr.F.Scale.intel <> xNone) and
(not (addr.offset.Kind in [ckValue, ckPValue, ckCondition])) then raise_parameter;
{$endif}
test_const(addr.offset, false, Proc);
end;
{$endif}
// <<<----------- универсальные тестовые функции -----------------------
{ TOpcodeBlock }
const
CMD_CUSHION_SIZE = sizeof(integer);
function TOpcodeBlock.AddCmd(const CmdMode: TOpcodeCmdMode; const SizeCorrection: integer=0): POpcodeCmd;
const
CMD_SIZES: array[TOpcodeCmdMode] of integer = (
sizeof(TOpcodeCmd){cmBinary},
{$ifdef OPCODE_MODES}sizeof(TOpcodeCmdText),{cmText}{$endif}
0{cmLeave},
sizeof(TOpcodeCmd){cmJoined},
sizeof(TOpcodeCmdJumpBlock){cmJumpBlock},
0{cmSwitchBlock},
sizeof(TOpcodeCmdPointer){cmPointer}
);
var
ResultSize: integer;
begin
with P.Proc do
if (CmdMode = cmBinary) and(FLastBinaryCmd = Self.CmdList) and (FLastHeapCurrent = Heap.FState.Current)
and (Integer(Self.CmdList.F.Size) + SizeCorrection <= high(word))
and (Heap.FState.Margin >= (SizeCorrection+CMD_CUSHION_SIZE)) then
begin
// в данном случае SizeCorrection - это размер бинарных данных
Result := Self.CmdList;
Inc(Result.F.Size, SizeCorrection);
Inc(NativeInt(Heap.FState.Current), SizeCorrection);
Dec(Heap.FState.Margin, SizeCorrection);
FLastHeapCurrent := Heap.FState.Current;
end else
begin
// выравнивание выделение памяти
with Heap do
begin
// Align
ResultSize := NativeInt(FState.Current) and 3;
if (ResultSize <> 0) then
begin
ResultSize := 4-ResultSize;
Inc(NativeInt(FState.Current), ResultSize);
Dec(FState.Margin, ResultSize);
end;
// Size
ResultSize := CMD_SIZES[CmdMode]+SizeCorrection;
// Alloc
Result := FState.Current;
if (FState.Margin >= (ResultSize+CMD_CUSHION_SIZE)) then
begin
Inc(NativeInt(FState.Current), ResultSize);
Dec(FState.Margin, ResultSize);
end else
begin
Result := Alloc(ResultSize+CMD_CUSHION_SIZE);
Dec(NativeInt(FState.Current), CMD_CUSHION_SIZE);
Inc(FState.Margin, CMD_CUSHION_SIZE);
end;
end;
// fields
Result.F.Value := Integer(ord(CmdMode)) shl 16;
// особенности работы для бинарной и остальных видов команд
if (CmdMode = cmBinary) then
begin
Result.F.Size := SizeCorrection;
FLastBinaryCmd := Result;
FLastHeapCurrent := Heap.FState.Current;
end else
begin
FLastBinaryCmd := NO_CMD;
FLastHeapCurrent := nil;
end;
// cmd list
Result.FNext := CmdList;
CmdList := Result;
end;
end;
{$ifdef OPCODE_MODES}
function TOpcodeBlock.AddCmdText(const Str: PShortString): POpcodeCmd{POpcodeCmdText};
begin
Result := AddCmd(cmText);
POpcodeCmdText(Result).Str := Str;
end;
function TOpcodeBlock.AddCmdText(const FmtStr: ShortString; const Args: array of const): POpcodeCmd{POpcodeCmdText};
begin
Result := AddCmd(cmText);
POpcodeCmdText(Result).Str := P.Proc.Heap.Format(FmtStr, Args);
end;
{$endif}
// присоединить к команде сопроводительную информацию
// по блоку или переменной, которые при фиксации станут ячейками
// под ячейкой стоит понимать 4хбайтную (в x86 и x64) переменную в фиксированных бинарных данных
// которые могут меняться в зависимости от данной функции или других глобальных объектов
procedure TOpcodeBlock.JoinCmdCellData(const relative: boolean; const v_const: TOpcodeConst);
var
Result: POpcodeCmdJoined;
JoinedData: POpcodeJoinedData;
begin
// не даём объединиться двум динарным командам
Self.P.Proc.FLastBinaryCmd := NO_CMD;
// Result.Next - это команда, для которой применяется данная ячейка!
Result := POpcodeCmdJoined(AddCmd(cmJoined, sizeof(TOpcodeJoinedData)));
Result.Cmd.F.Size := Result.Cmd.Next.Size;
Result.Cmd.F.Param := 1 or (ord(Result.Cmd.Next.Mode) shl 2);
JoinedData := @Result.Data[0];
{$ifdef OPCODE_MODES}if (Self.P.Proc.Mode <> omBinary) then
begin
{ JoinedData.CmdOffset не имеет значения }
JoinedData.Proc := Self.P.Proc;
JoinedData.Block := v_const.Block;
end else
{$endif}
begin
if (v_const.Kind = ckBlock) then
begin
JoinedData.Proc := v_const.Block.P.Proc;
if (JoinedData.Proc = Self.P.Proc) then
begin
// local
JoinedData.Block := v_const.Block;
end else
begin
// global
with v_const.Block^ do
begin
JoinedData.Reference := O.Reference;
if (JoinedData.Reference = NO_REFERENCE) then JoinedData.Reference := MakeReference();
end;
end;
end else
// if (v_const.Kind = ckVariable) then
begin
JoinedData.Variable := v_const.Variable;
JoinedData.VariableOffset := v_const.VariableOffset;
end;
// смещение
JoinedData.CmdOffset := Result.Cmd.Next.NeutralizeFakeConst();
if (relative) then
JoinedData.CmdOffset := -JoinedData.CmdOffset;
end;
end;
// присоединить к команде сопроводительную информацию
// по блоку(ам) и/или переменной(ым), которые при фиксации станут ячейками
// под ячейкой стоит понимать 4хбайтную (в x86 и x64) переменную в фиксированных бинарных данных
// которые могут меняться в зависимости от данной функции или других глобальных объектов
procedure TOpcodeBlock.JoinCmdCellData(const mode: byte; const v_addr, v_const: TOpcodeConst);
var
Result: POpcodeCmdJoined;
JoinedData: POpcodeJoinedData;
PConst: POpcodeConst;
Count, i: integer;
begin
Count := ((mode shr 1) and 1) + (mode and 1);
// не даём объединиться двум динарным командам
Self.P.Proc.FLastBinaryCmd := NO_CMD;
// Result.Next - это команда, для которой применяется данная ячейка!
Result := POpcodeCmdJoined(AddCmd(cmJoined, Count*sizeof(TOpcodeJoinedData)));
Result.Cmd.F.Size := Result.Cmd.Next.Size;
Result.Cmd.F.Param := (mode and 3) or (ord(Result.Cmd.Next.Mode) shl 2);
JoinedData := @Result.Data[0];
if (mode and 1 <> 0) then PConst := @v_const else PConst := @v_addr;
// проходим по всем нужным переменным
for i := Count-1 downto 0 do
begin
with PConst^ do
{$ifdef OPCODE_MODES}if (Self.P.Proc.Mode <> omBinary) then
begin
{ JoinedData.CmdOffset не имеет значения }
JoinedData.Proc := Self.P.Proc;
JoinedData.Block := Block;
end else
{$endif}
begin
if (Kind = ckBlock) then
begin
if (VariableOffset = 0) then
begin
// local
JoinedData.Proc := Self.P.Proc;
JoinedData.Block := Block;
end else
begin
// global
JoinedData.Proc := TOpcodeProc(Variable);
JoinedData.Reference := VariableOffset;
end;
end else
// if (v_const.Kind = ckVariable) then
begin
JoinedData.Variable := Variable;
JoinedData.VariableOffset := VariableOffset;
end;
// смещение
JoinedData.CmdOffset := Result.Cmd.Next.NeutralizeFakeConst(ord(PConst = @v_addr));
if {relative}(mode and 4 <> 0) and (PConst = @v_addr) then
JoinedData.CmdOffset := -JoinedData.CmdOffset;
end;
dec(JoinedData);
PConst := @v_addr;
end;
end;
// особый вид команд, используемый для констант
// когда значение будет известно только на этапе фиксации
function TOpcodeBlock.AddCmdPointer(params: integer; pvalue: pointer; addr_kind: integer; callback, diffcmd: pointer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd{POpcodeCmdPointer};
type
TTwoConsts = array[0..1] of TOpcodeConst;
PTwoConsts = ^TTwoConsts;
var
R: POpcodeCmdPointer absolute Result;
begin
Result := AddCmd(cmPointer);
Result.F.Param{will_join} := ord((byte{Kind}(addr_kind shr 24)=2)and((PTwoConsts(pvalue)^[0].Kind>=ckBlock)or(PTwoConsts(pvalue)^[1].Kind>=ckBlock)));
R.params := params;
R.pvalue := pvalue;
R.addr_kind := addr_kind;
R.callback := callback;
R.diffcmd.ptr := diffcmd;
{$ifdef OPCODE_MODES}
R.cmd_name := @cmd;
{$endif}
end;
// команды jcc(intel_cc), jmp(-1), call(-2)
// или аналоги например для платформы ARM
// в случае необходимости проводятся проверка и подписка
function TOpcodeBlock.cmd_jump_block(const cc_ex: shortint; const Block: POpcodeBlock): POpcodeCmd{POpcodeCmdJumpBlock};
begin
{$ifdef OPCODE_TEST}
if (cc_ex < -2{call}) or (cc_ex > ord(high(intel_cc))) then raise_parameter;
if (P.Proc.Storage <> Block.P.Proc.Storage) then raise_parameter;
if (@Self = Block) then raise_parameter;
{$ifdef OPCODE_MODES}
// на случай Storage nil
if (P.Proc.Mode <> Block.P.Proc.Mode) then raise_parameter;
{$endif}
{$endif}
Result := AddCmd(cmJumpBlock);
Result.F.cc_ex := cc_ex;
if (Block.P.Proc <> Self.P.Proc) then
begin
// глобальный
with POpcodeCmdJumpBlock(Result)^ do
begin
Proc := Block.P.Proc;
Reference := Block.O.Reference;
if (Reference = NO_REFERENCE) then Reference := Block.MakeReference();
end;
// подписка
with Block.P.Proc do Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end else
begin
// локальный
POpcodeCmdJumpBlock(Result).Proc := Self.P.Proc;
POpcodeCmdJumpBlock(Result).Block := Block;
end;
end;
// текстовые команды jcc(intel_cc), jmp(-1), call(-2) к глобальным функциям
// или аналоги например для платформы ARM
{$ifdef OPCODE_MODES}
function TOpcodeBlock.cmd_textjump_proc(const cc_ex: shortint; const ProcName: pansichar): POpcodeCmd{POpcodeCmdJumpBlock};
begin
{$ifdef OPCODE_TEST}
if (cc_ex < -2{call}) or (cc_ex > ord(high(intel_cc))) then raise_parameter;
if (ProcName = nil) or (ProcName^ = #0) then raise_parameter;
if (P.Proc.Mode = omBinary) then raise_parameter;
{$endif}
Result := AddCmd(cmJumpBlock);
Result.F.cc_ex := cc_ex;
POpcodeCmdJumpBlock(Result).Proc := NO_PROC{маркировка "глобальный, текстовый"};
POpcodeCmdJumpBlock(Result).ProcName := ProcName;
end;
{$endif}
// вставить блок между Self и Next
function TOpcodeBlock.AppendBlock(const ResultSize: integer): POpcodeBlock;
begin
// Alloc
with P.Proc.Heap do
begin
Result := FState.Current;
if (FState.Margin >= ResultSize) then
begin
Inc(NativeInt(FState.Current), ResultSize);
Dec(FState.Margin, ResultSize);
end else
begin
Result := Alloc(ResultSize);
end;
end;
// base fields
Result.CmdList := nil;
Result.P.Proc := P.Proc;
Result.N.Next := N.Next;
N.Next := Result;
Result.O.Value := NO_FIXUPED or (NO_REFERENCE shl 16);
end;
function TOpcodeBlock.AppendBinaryBlock(const {word}Size: integer): POpcodeBinaryBlock;
begin
{$ifdef OPCODE_TEST}
if (Size <= 0) or (Size > high(word)) then raise_parameter;
{$endif}
Result := pointer(AppendBlock(sizeof(TOpcodeBlock)+sizeof(integer)+sizeof(TOpcodeCmd) + Size));
Result.FSize := Size;
Result.CmdList := @Result.Cmd;
Result.Cmd.F.Value := Size; // Size = Size, Mode = cmBinary.
end;
function TOpcodeBlock.AppendSwitchBlock(const {хз byte}Count: integer): POpcodeSwitchBlock;
begin
{$ifdef OPCODE_TEST}
if (Count <= 0) or (Count > (high(word) div 4)) then raise_parameter;
{$endif}
Result := pointer(AppendBlock(sizeof(TOpcodeBlock)+sizeof(integer)+sizeof(TOpcodeCmd) + {BinarySize}Count*sizeof(POpcodeBlock)));
FillChar(Result.Blocks, {BinarySize}Count*sizeof(POpcodeBlock), #0);
Result.FCount := Count;
Result.CmdList := @Result.Cmd;
Result.Cmd.F.Value := Count*4 + (ord(cmSwitchBlock) shl 16);
end;
// промаркировать блок как возможный для внешней адресации
// в текстовом виде можно использовать для того чтобы пометить конкретные блоки метками (для читабельности)
function TOpcodeBlock.MakeReference(): word;
begin
Result := O.Reference;
if (Result = NO_REFERENCE) then
with P.Proc do
begin
Result := F.BlocksReferenced;
inc(F.BlocksReferenced);
O.Reference := Result;
end;
end;
const
// флаги (старший байт opcode)
flag_0f = 1 shl 31;
flag_rex = 1 shl 30;
flag_word_ptr = 1 shl 29;
flag_lock = 1 shl 28;
flag_x64 = 1 shl 27;
flag_extra = 1 shl 26; // команда позволяет работать в особом режиме
// 25
// 24
// 4 бита rex, используются так же биты с 24 по 27
rex_W = flag_rex or (1 shl 27); // 1 - операнд 64 бита, 0 - операнд 32 бита
rex_R = flag_rex or (1 shl 26); // старший бит для reg в качестве первого аргумента
rex_X = flag_rex or (1 shl 25); // старший бит для sib
rex_B = flag_rex or (1 shl 24); // старший бит для reg/mem в качестве второго аргумента
// маска регистров r8..r15
rex_RXB = (rex_R or rex_X or rex_B) and (not flag_rex);
// бит в опкоде, показывающий, что аргумент не 1 байт (2, 4 или 8)
intel_nonbyte_mask = $0100;
// набор префиксов
intel_prefixes: array[0..15] of integer = ($00000000, $000000F0, $00000066,
$000066F0, $00000040, $000040F0, $00004066, $004066F0, $0000000F, $00000FF0,
$00000F66, $000F66F0, $00000F40, $000F40F0, $000F4066, $0F4066F0);
// размер набора и сдвиг в нём для rex
intel_prefixes_info: array[0..15] of word = ($0000, $0100, $0100,
$0200, $0100, $0208, $0208, $0310, $0100, $0200,
$0200, $0300, $0200, $0308, $0308, $0410);
// информация по размерностям: флаги и размер
ptr_intel_info: array[size_ptr] of integer = (0 or 1, flag_word_ptr or intel_nonbyte_mask or 2,
intel_nonbyte_mask or 4, rex_W or intel_nonbyte_mask or 8, 0, 0);
// варианты-константы сс
cc_intel_info: array[intel_cc] of byte =
(
0{_o},
1{_no},
2,2,2{_b,_c,_nae},
3,3,3{_ae,_nb,_nc},
4,4{_e,_z},
5,5{_nz,_ne},
6,6{_be,_na},
7,7{_a,_nbe},
8{_s},
9{_ns},
$a,$a{_p,_pe},
$b,$b{_po,_np},
$c,$c{_l,_nge},
$d,$d{_ge,_nl},
$e,$e{_le,_ng},
$f,$f{_g,_nle}
);
// сохраняем префиксы, опкоды, дополнительный размер 0
intel_opcode_mask = integer($f0ffff00);
// константа, вызволяющая из reg_intel_info биты, необходимые для modrm в качестве source
intel_modrm_src_index = (rex_R or (7 shl (16+3))) xor flag_rex;
intel_modrm_src_mask = integer($f0000000) or rex_W or intel_modrm_src_index or $ff00{intel_nonbyte_mask};
// константа, вызволяющая из reg_intel_info биты, необходимые для modrm в качестве destination
intel_modrm_dest_index = (rex_B or (7 shl 16)) xor flag_rex;
intel_modrm_dest_mask = integer($f0000000) or rex_W or intel_modrm_dest_index or $ff00{intel_nonbyte_mask};
// imm = (...)
imm0 = 0;
imm8 = 1;
imm32 = 2;
(*// если Intel x64
function TOpcodePackedAddress.Getx64: boolean;
begin
Result := (bytes[2] and 128 <> 0);
end;
// функция распаковыет 3 байта в требуемые 4 байта, возвращаемые по IntelInspect
function TOpcodePackedAddress.GetIntelInspect(opcode)(): integer;
const
CLEAN_MASK = rex_R or rex_X or rex_B or $00ffffff;
var
value, s: integer;
begin
// 3 байта
value := pinteger(@bytes)^ shl 8;
// размер
s := (value shr 28) and 3;
if (s = 3) then s := 4;
value := value or s;
// используется ли sib
if (value and (1 shl 27) <> 0) then value := value or $f0;
// удаление лишних бит
Result := value and CLEAN_MASK;
end; *)
// возвращается такой массив:
// REX | modrm | sib или 0 | imm size
// проверка переносится в отдельную функцию test_intel_address
function TOpcodeAddress.IntelInspect(const params: integer{x64}): integer;
const
IMM_VALUES: array[imm0..imm32] of integer =
($00000000{mod=00}, $00000001 or (01 shl (6+16)), $00000004 or (02 shl (6+16)));
// modm = (...)
m_imm32 = 0;
m_reg = 1;
m_sib_nobase = 2;
m_based_sib = 3;
// intel_scale = (xNone, x1, x2, x4, x8, x1_plus, x2_plus, x4_plus, x8_plus);
SCALES: array[intel_scale] of byte = (0, 1, 2, 3{4}, 4{8}, 1, 2, 3{4}, 4{8});
{$ifdef PUREPASCAL}
const
use_rex_R: array[0..1] of integer = (0, rex_R);
use_rex_X: array[0..1] of integer = (0, rex_X);
use_rex_B: array[0..1] of integer = (0, rex_B);
var
index, base, scale{0, 1, 2, 4, 8}: byte;
imm: byte;
modm: byte;
offset_value: integer;
begin
// базовое заполнение полей
if (params and flag_x64 <> 0{x64}) then
begin
index := (Self.F.Reg.v - rax) and $f;
base := (Self.F.Plus.v - rax) and $f;
end else
begin
index := Self.F.Reg.v - eax;
base := Self.F.Plus.v - eax;
end;
scale := SCALES[Self.F.Scale.intel];
// определяем imm по умолчанию
if (Self.offset.Kind <> ckValue) then imm := imm32
else
begin
offset_value := Self.offset.Value;
if (offset_value = 0) then imm := imm0
else
if (offset_value >= -128) and (offset_value <= 127) then imm := imm8
else
imm := imm32;
end;
// определяем вариант адресации
case Self.F.Scale.intel of
xNone: // [$...]
begin
modm := m_imm32; // устанавливать imm вручную не нужно
end;
x1: // [reg + $...]
begin
modm := m_reg;
case (index and 7) of
4{esp/rsp/r12}: begin
base := index;
index := 4;
modm := m_based_sib;
end;
5{ebp/rbp/r13}: begin
if (imm = imm0) then imm := imm8;
end;
end;
end;
x2: // [reg*2 + $...]
begin
modm := m_sib_nobase;
if (imm < imm32) then
begin
modm := m_based_sib;
base := index;
scale := 1;
end;
end;
x4,x8: // [reg*4/8 + $...]
begin
modm := m_sib_nobase;
end;
x1_plus: //[reg1 + reg_base + $...]
begin
modm := m_based_sib;
if (index = 4{esp/rsp}) then
begin
index := base;
base := 4;
end;
end;
else
// x2_plus, x4_plus, x8_plus
modm := m_based_sib;
end;
// модификация modm если в качестве базы в sib используется ebp и смещение 0
// комбинация [sib+0]/ebp используется для sib без базы
if (modm = m_based_sib) and (base and 7 = 5{ebp/rbp/r13}) and (imm = imm0) then imm := imm8;
// результат: REX | modrm | sib или 0 | imm size
case modm of
m_imm32: begin
Result := $00050004; // modm = imm32
end;
m_reg: begin
Result := // modm = reg (1 байт)
((index and 7) shl 16) // базовый регистр
or IMM_VALUES[imm] // тип imm, размер
or USE_REX_B[index shr 3];
end;
m_sib_nobase: begin
Result := $000405f4 // modm = sib, 4 байта на imm, base = *
or ((index and 7) shl 11) or ((scale-1) shl 14)
or USE_REX_X[index shr 3];
end;
else
// modm = m_based_sib
Result := $000400f0 or IMM_VALUES[imm]
or ((base and 7) or ((index and 7) shl 3) or ((scale-1) shl 6)) shl 8
or USE_REX_B[base shr 3] or USE_REX_X[index shr 3];
end;
end;
{$else .ASSEMBLER_MODE_x86-64}
const
sub_rax_rax = -((rax shl 8) or (rax));
sub_eax_eax = -((eax shl 8) or (eax));
asm
// заносим в eax значение const.kind | intel_scale | base | index
// в edx - константу вычитания, в ecx - значение imm (или $00ffffff {для imm32})
test edx, flag_x64
mov edx, sub_eax_eax
{$ifdef CPUX86}
mov ecx, sub_rax_rax
cmovnz edx, ecx
mov ecx, [EAX + TOpcodeAddress_offset + TOpcodeConst.F.Value]
mov eax, dword ptr [EAX].TOpcodeAddress.F.Bytes
{$else .CPUX64}
mov eax, sub_rax_rax
cmovnz edx, eax
mov eax, dword ptr [RCX].TOpcodeAddress.F.Bytes
mov ecx, [RCX + TOpcodeAddress_offset + TOpcodeConst.F.Value]
{$endif}
test eax, $ff000000 // cmp FKind.v32, ckValue
jz @offset_calculated
and eax, $00ffffff
mov ecx, $00ffffff
@offset_calculated:
// коррекция base для intel_scale None, x1, x2, x4, x8
cmp eax, $050000 // x1_plus
jae @base_corrected
or eax, $ff00
@base_corrected:
// рассчитываем тоговые scale-1| intel_scale | base | index --> edx
xadd eax, edx
shr edx, 16
and eax, $00ff0f0f
{$ifdef CPUX86}
mov edx, dword ptr [SCALES + edx]
{$else .CPUX64}
lea r11, [SCALES]
mov edx, [r11 + rdx]
{$endif}
shl edx, 24
sub ecx, -128 // ecx += 128
lea edx, [edx + eax - $01000000]
mov eax, imm32
// определяем imm по умолчанию
cmp ecx, 255
ja @imm_calculated
cmp ecx, 128
setne al
@imm_calculated:
// определяем вариант адресации
mov ecx, edx
{$ifdef CPUX64}
lea r11, [IMM_VALUES]
{$endif}
shr ecx, 16
cmp cl, x1_plus
ja @m_based_sib // x2_plus, x4_plus, x8_plus
je @x1_plus
cmp cl, x2
ja @m_sib_nobase // x4,x8
je @x2
test cl, cl
jz @m_imm32
@x1:
mov ecx, edx
and ecx, 7
sub ecx, 4
cmp ecx, 1
ja @m_reg
je @look_ebp_rbp_r13
@look_esp_rbp_r12:
mov dh, dl
mov dl, 4
jmp @m_based_sib_std
@look_ebp_rbp_r13:
test eax, eax
mov ecx, imm8
cmovz eax, ecx
jmp @m_reg
@x2:
cmp eax, imm32
je @m_sib_nobase
mov dh, dl
and edx, $0000ffff
jmp @m_based_sib
@x1_plus:
cmp dl, 4
jnz @m_based_sib
xchg dl, dh
jmp @m_based_sib
// результат: REX | modrm | sib или 0 | imm size
@m_imm32:
mov eax, $00050004
ret
@m_reg:
shl edx, 16
{$ifdef CPUX86}
mov eax, [offset IMM_VALUES + eax*4]
test edx, $080000
lea ecx, [eax+REX_B]
{$else .CPUX64}
mov eax, [r11 + rax*4]
test edx, $080000
lea rcx, [rax+REX_B]
{$endif}
cmovnz eax, ecx
and edx, $070000
or eax, edx
ret
@m_sib_nobase:
test dl, 8
mov eax, $000405f4
mov ecx, $000405f4 + REX_X
cmovnz eax, ecx
mov ecx, edx
and edx, 7
and ecx, $ff000000
shl edx, 11
shr ecx, 10
or eax, edx
or eax, ecx
ret
@m_based_sib:
// if (modm = m_based_sib) and (base and 7 = 5{ebp/rbp/r13}) and (imm = imm0) then imm := imm8;
test eax, eax
movzx ecx, dh
jnz @m_based_sib_std
and ecx, 7
cmp ecx, 5
mov ecx, imm8
cmove eax, ecx
@m_based_sib_std:
test dh, 8
{$ifdef CPUX86}
mov eax, [offset IMM_VALUES + eax*4]
push ebx
lea ecx, [eax+REX_B]
{$else .CPUX64}
mov eax, [r11 + rax*4]
xchg rbx, r8
lea rcx, [rax+REX_B]
{$endif}
mov ebx, REX_X
cmovnz eax, ecx
test dl, 8
mov ecx, 0
cmovz ebx, ecx
or eax, $000400f0
mov ecx, edx
or eax, ebx
and ecx, $ff000000
mov ebx, edx
and edx, 7
and ebx, $0700
shr ecx, 10
or eax, ebx
shl edx, 11
or eax, ecx
or eax, edx
// концовка
{$ifdef CPUX86}
pop ebx
{$else .CPUX64}
xchg rbx, r8
{$endif}
end;
{$endif}
// нейтрализовать фейковую константу, заменить нулём, вернуть смещение
function TOpcodeCmd.NeutralizeFakeConst(const data_offs: integer=0): integer;
var
Ptr: PInteger;
begin
// смещение
Ptr := Pointer(NativeInt(@Self) + sizeof(TOpcodeCmd) + integer(Self.Size) - sizeof(integer) - data_offs);
// находим
while (Ptr^ <> FAKE_CONST_32) do dec(PByte(Ptr));
// результат
Ptr^ := 0;
Result := NativeInt(Ptr)-NativeInt(@Self)-sizeof(TOpcodeCmd);
end;
// интерфейс для временного хранения текста (для ассемблера и гибрида)
{$ifdef OPCODE_MODES}
{ TOpcodeTextBuffer }
const
STR_UNKNOWN: string[9] = '<UNKNOWN>';
STR_CL: string[2] = 'cl';
STR_NULL: string[0] = '';
function TOpcodeTextBuffer.Format(const FmtStr: AnsiString; const Args: array of const; const Number: byte=0; const MakeLower: boolean=false): PShortString;
var
Offset: integer;
Len, i: integer;
begin
Offset := 0;
for i := 1 to Number do
begin
Offset := Offset + value.bytes[Offset] + sizeof(byte);
end;
if (Offset >= high(value.bytes)) then Result := nil
else
begin
Len := SysUtils.FormatBuf(value.bytes[Offset+1], high(value.bytes)-Offset, pointer(FmtStr)^, Length(FmtStr), Args);
if (Len > 255) then Len := 255;
value.bytes[Offset] := Len;
Result := PShortString(@value.bytes[Offset]);
if (MakeLower) then
for i := 1 to Len do
if (Result^[i] in ['A'..'Z']) then inc(Result^[i], 32);
end;
end;
function TOpcodeTextBuffer.Str(const S: pansichar; const Number: byte=0): PShortString;
begin
Result := Format(FMT_ONE_STRING, [S], Number);
end;
// ptr должен быть в младшем байте
function TOpcodeTextBuffer.SizePtr(const params_ptr: integer; const Number: byte=0): PShortString;
begin
Result := Format('%s ptr ', [size_ptr_names[size_ptr(params_ptr)]], Number);
end;
function TOpcodeTextBuffer.InternalConst(const v_const: TOpcodeConst; const can_offsetted, use_sign: boolean; const Number: byte): PShortString;
const
STR_INTHEX_FMT: array[boolean] of AnsiString = ('%d','$%x');
SIGNS: array[0..2] of AnsiString = ('', ' + ', ' - ');
var
X, sign: integer;
hex: boolean;
begin
with v_const do
case Kind of
ckValue: begin
X := F.Value;
hex := (X < -128) or (X > 127);
if (not use_sign) then
begin
Result := Format(STR_INTHEX_FMT[hex], [X], Number, {lower if hex}hex);
end else
begin
sign := 1;
if (X < 0) then
begin
X := -X;
sign := 2;
end;
if (hex) then Result := Format('%s$%x', [SIGNS[sign], X], Number, true)
else Result := Format('%s%d', [SIGNS[sign], X], Number);
end;
end;
ckCondition,
ckOffsetedCondition: begin
if (Kind = ckOffsetedCondition) and (can_offsetted) then
Result := Format('offset %s%s', [OffsetedCondition, SIGNS[ord(use_sign)]], Number)
else
Result := Format('%s%s', [SIGNS[ord(use_sign)], Condition], Number);
end;
ckBlock,
ckVariable: if (can_offsetted) then
Result := Format('offset %%s%s', [{Block,} SIGNS[ord(use_sign)]], Number)
else
Result := Format('%s%%s', [SIGNS[ord(use_sign)]{, Block}], Number);
else
Result := Format('%s%s', [SIGNS[ord(use_sign)], STR_UNKNOWN], Number);
end;
end;
function TOpcodeTextBuffer.Const32(const v_const: const_32; const Number: byte=0): PShortString;
begin
Result := InternalConst(v_const, true, false, Number);
end;
function TOpcodeTextBuffer.Const64(const v_const: const_64; const Number: byte=0): PShortString;
begin
with v_const do
if (Kind = ckValue) then
begin
if (Value < -128) then
begin
Result := {Int64}Format('-$%x', [-v_const.Value], Number, true);
exit;
end;
if (Value > 127) then
begin
Result := {Int64}Format('$%x', [v_const.Value], Number, true);
exit;
end;
end;
Result := InternalConst(v_const, true, false, Number);
end;
function TOpcodeTextBuffer.IntelAddress(const params: integer{x64}; const addr: TOpcodeAddress;
const can_offsetted: boolean=true; const Number: byte=0): PShortString;
const
BASE_REG: array[boolean{x64}] of integer = (eax, rax);
SCALES: array[0..3] of AnsiString = ('', '*2', '*4', '*8');
//offs_R = 26-4+1; // rex_R = flag_rex or (1 shl 26); // старший бит для reg в качестве первого аргумента
offs_X = 25-4+1; // rex_X = flag_rex or (1 shl 25); // старший бит для sib
offs_B = 24-4+1; // rex_B = flag_rex or (1 shl 24); // старший бит для reg/mem в качестве второго аргумента
var
addr_value: integer;
x64, const_left: boolean;
const_str: TOpcodeTextBuffer;
reg_str: PShortString;
// разбивка байта на 3 составляющих
low, middle, high, last_high: byte;
procedure inspect_byte(const b: byte);
begin
low := b and 7;
middle := (b shr 3) and 7;
high := b shr 6;
end;
// заполнение строки по регистрам
procedure MakeRegStr(const FmtStr: AnsiString; const Args: array of const);
begin
reg_str := const_str.Format(FmtStr, Args, 1);
end;
begin
x64 := (params and flag_x64 <> 0);
addr_value := addr.IntelInspect(params);
// берём составляющие modrm
inspect_byte(addr_value shr 16);
// для disp32 особая логика
if (high = 0) and (low = 5) then
begin
const_str.InternalConst(addr.offset, can_offsetted and (not x64), false, 0);
Result := Format('[%s]', [const_str.value.S], Number);
exit;
end;
// заполнение константы и режима
case addr.offset.Kind of
ckValue: if (addr.offset.Value = 0) then
begin
// для упрощения делаем пустую строку
const_left := true;
const_str.value.bytes[0] := 0;
end else
begin
// + <значение>
const_left := false;
const_str.InternalConst(addr.offset, false, true, 0);
end;
ckOffsetedCondition,
ckBlock,
ckVariable: begin
// offset ... +
const_left := true;
const_str.InternalConst(addr.offset, can_offsetted, true, 0);
end;
else
// + <UNKNOWN>
const_left := false;
const_str.InternalConst(addr.offset, can_offsetted, true, 0);
end;
// modrm/sib
if (low <> 4) then
begin
low := low + (addr_value shr offs_B) and 8;
MakeRegStr(reg_intel_names[BASE_REG[x64] + low], []);
end else
begin
// sib
last_high := high;
inspect_byte(addr_value shr 8);
middle := middle + (addr_value shr offs_X) and 8;
low := low + (addr_value shr offs_B) and 8;
if (low = 4) then
begin
// нет множителя
MakeRegStr(reg_intel_names[BASE_REG[x64] + low], []);
end else
if (last_high = 0) and (low in [5, 13]) then
begin
// только множитель (без базы)
MakeRegStr('%s%s',
[
reg_intel_names[BASE_REG[x64] + middle],
SCALES[high]
]);
end else
begin
// есть множитель
MakeRegStr('%s%s + %s',
[
reg_intel_names[BASE_REG[x64] + middle],
SCALES[high],
reg_intel_names[BASE_REG[x64] + low]
]);
end;
end;
// результат
if (const_left) then Result := Format('[%s%s]', [const_str.value.S, reg_str^], Number)
else Result := Format('[%s%s]', [reg_str^, const_str.value.S], Number);
end;
{$endif}
{ TOpcodeBlock_Intel }
// самая важная в архитектуре Intel умная команда
// позволяет за раз:
// - выделить необходимое количество памяти для команды
// - присоединиться к прошлой бинарной команде
// - записать все префиксы
// - опкод команды (1 или 2 байт)
// - запись Advanced (это может быть константа или какие-то дополнительные данные)
//
// формат:
// 4 старших бита - набор префиксов
// 4 бита - значения REX
// 1 байт опкода рабочий - сюда обычно пишут параметры modrm
// 1 байт опкода базовый - но он может отсутствовать (0)
// 8 бит (1 байт) - дополнительный размер. это может быть например константа или другие данные
function TOpcodeBlock_Intel.AddSmartBinaryCmd(Parameters, Advanced: integer): POpcodeCmd;
{$ifdef PURE_PASCAL}
var
Dest: pinteger;
X: integer;
OpcodeOffset, OpcodeSize: integer;
DataSize: integer;
begin
// набор префиксов
X := Parameters shr 28;
// размер набора префиксов
OpcodeOffset := intel_prefixes_info[X] shr 8;
// размер опкода: 1 или 2
OpcodeSize := 2;
if (Parameters and $00ff00 = 0) then
begin
Parameters := Parameters or ((Parameters and $ff0000) shr 8);
OpcodeSize := 1;
end;
// общий размер, добавляем команду
DataSize := OpcodeOffset + OpcodeSize + byte(Parameters);
Result := AddCmd(cmBinary, DataSize);
// записываем данные в буфер
Dest := pinteger(@Result.Data.Bytes[Result.Size-DataSize]);
// префиксы
Dest^ := intel_prefixes[X] or ((Parameters shr 24) and $f) shl byte(intel_prefixes_info[X]);
// опкод команды
Inc(NativeInt(Dest), OpcodeOffset);
Dest^ := Parameters shr 8;
// пишем Advanced
Inc(NativeInt(Dest), OpcodeSize);
Dest^ := Advanced;
end;
{$else .ASSEMBLER_MODE_x86-64}
const
CMD_HEADER_SIZE = sizeof(TOpcodeCmd);
CMD_HEADER_PLUS_CUSHION = CMD_HEADER_SIZE + CMD_CUSHION_SIZE;
asm
// сохраняем Advanced и Parameters
// "выделяем" ebx/rbx и rsi/esi
{$ifdef CPUX86}
push esi
push ebx
push ecx
push edx
{$else .CPUX64}
push r12
// mov r8, r8 - Advanced
mov r9, rsi
xchg r10, rbx
mov r11, rdx
// сохраняем Self в rax чтобы не путаться в регистрах
xchg rax, rcx
{$endif}
// заполняем массив информации - ebx
// вычисляем DataSize - ecx
mov esi, edx
shr edx, 28
mov ecx, 2
test esi, $00ff00
{$ifdef CPUX86}
movzx ebx, word ptr [intel_prefixes_info + edx*2]
{$else .CPUX64}
lea r12, [intel_prefixes_info]
movzx ebx, word ptr [r12 + rdx*2]
{$endif}
jnz @opcode_size_done
mov ecx, esi
and esi, $ff0000
shr esi, 8
or ecx, esi
{$ifdef CPUX86}
mov [esp], ecx
{$else .CPUX64}
mov r11, rcx
{$endif}
mov ecx, 1
@opcode_size_done:
shl edx, 24 // X | | |
mov esi, ecx
xadd ebx, edx // X | | opc offs | rex shl
shl esi, 16
shr edx, 8 // OpcodeOffset(PrefixesSize)
or ebx, esi // инфо в сборе
// дополнительный размер
{$ifdef CPUX86}
movzx esi, byte ptr [esp]
{$else .CPUX64}
movzx esi, r11b
{$endif}
add ecx, edx
// сохраняем ebx
{$ifdef CPUX86}
push ebx
{$else .CPUX64}
xchg rbx, r12
{$endif}
add ecx, esi
// Result := AddCmd(cmBinary, DataSize);
// [по сути полное переписывание этой команды под обе платформы]
// in:
// eax/rax - Self
// ebx - хранит инфо: X | OpcodeSize | OpcodeOffset | byte(intel_prefixes_info[X])
// ecx - DataSize
// edx и esi - буферы
// out:
// eax/rax - результат (CmdList)
// esi/rsi - Dest
{$ifdef CPUX86}
// with Self.P.Proc
mov esi, [EAX].TOpcodeBlock.P.Proc
// if LastBinaryCmd <> Self.CmdList (ebx)
mov ebx, [EAX].TOpcodeBlock.CmdList
cmp [ESI].TOpcodeProc.FLastBinaryCmd, ebx
jne @allocate_new
// if LastHeapCurrent <> Heap(esi).FState.Current
mov edx, [ESI].TOpcodeProc.FLastHeapCurrent
mov esi, [ESI].TOpcodeProc.FHeap
cmp [ESI].TOpcodeHeap.FState.Current, edx
jne @allocate_new
// if (Integer(Self.CmdList.F.Size) + DataSize > high(word))
add word ptr [EBX].TOpcodeCmd.F.Size, cx
jo @allocate_new_step_overflow
// if (Heap.FState.Margin < (DataSize+CMD_CUSHION_SIZE))
add ecx, CMD_CUSHION_SIZE
sub [ESI].TOpcodeHeap.FState.Margin, ecx
jl @allocate_new_step_margin
@allocate_append:
// проверки прошли успешно - просто добавляем опкоды в конец
// eax - TOpcodeBlock, esi - TOpcodeHeap, ebx - CmdList(Result), edx - Current, ecx - (DataSize+CMD_CUSHION_SIZE)
lea ecx, [ecx + edx - CMD_CUSHION_SIZE]
mov eax, [EAX].TOpcodeBlock.P.Proc
mov [ESI].TOpcodeHeap.FState.Current, ecx
xchg esi, edx
mov [EAX].TOpcodeProc.FLastHeapCurrent, ecx
xchg eax, ebx
jmp @allocating_done
@allocate_new_step_margin:
add [ESI].TOpcodeHeap.FState.Margin, ecx
sub ecx, CMD_CUSHION_SIZE
@allocate_new_step_overflow:
sub word ptr [EBX].TOpcodeCmd.F.Size, cx
@allocate_new:
// выделяем новую команду
mov esi, [EAX].TOpcodeBlock.P.Proc
mov ebx, [ESI].TOpcodeProc.FHeap
add ecx, CMD_HEADER_PLUS_CUSHION // ResultSize+CMD_CUSHION_SIZE
mov esi, [EBX].TOpcodeHeap.FState.Current
mov edx, [EBX].TOpcodeHeap.FState.Margin
// выравнивание на 4 байта
add esi, 3
and edx, -4
and esi, -4
// if FState.Margin < (ResultSize+CMD_CUSHION_SIZE) then @call_alloc_cmd()
sub edx, ecx
jl @call_alloc_cmd
@no_call_alloc_cmd:
// памяти хватает - просто меняем Current/Margin
// Margin := bufMargin + CMD_CUSHION_SIZE
add edx, CMD_CUSHION_SIZE
mov [EBX].TOpcodeHeap.FState.Margin, edx
// Current заполнится в @allocated_fields (= новый edx)
lea edx, [esi + ecx - CMD_CUSHION_SIZE]
jmp @allocated_fields
@call_alloc_cmd:
// обязательный вызов Heap.Alloc(), но уже выровненные Current и Margin
add edx, ecx
mov [EBX].TOpcodeHeap.FState.Current, esi
mov [EBX].TOpcodeHeap.FState.Margin, edx
push eax
push ecx
mov eax, ebx
mov edx, ecx
call TOpcodeHeap.Alloc
mov esi, eax
pop ecx
pop eax
mov edx, [EBX].TOpcodeHeap.FState.Current
add [EBX].TOpcodeHeap.FState.Margin, CMD_CUSHION_SIZE
sub edx, CMD_CUSHION_SIZE
@allocated_fields:
// eax - TOpcodeBlock, ebx - TOpcodeHeap, edx - new Heap.Current,
// ecx - (DataSize+Header+Cushion), esi - TOpcodeCmd (Result)
// размер
sub ecx, CMD_HEADER_PLUS_CUSHION
mov [ESI].TOpcodeCmd.F.Value, ecx
// необходимые поля
mov [EBX].TOpcodeHeap.FState.Current, edx
mov ecx, [EAX].TOpcodeBlock.P.Proc
mov ebx, [EAX].TOpcodeBlock.CmdList
mov [ECX].TOpcodeProc.FLastBinaryCmd, esi
mov [ECX].TOpcodeProc.FLastHeapCurrent, edx
// cmd list
mov [ESI].TOpcodeCmd.FNext, ebx
mov [EAX].TOpcodeBlock.CmdList, esi
// результат (eax) и Dest (esi)
mov eax, CMD_HEADER_SIZE
xadd esi, eax
{$else .CPUX64}
// with Self.P.Proc
mov rsi, [RAX].TOpcodeBlock.P.Proc
// if LastBinaryCmd <> Self.CmdList (ebx)
mov rbx, [RAX].TOpcodeBlock.CmdList
cmp [RSI].TOpcodeProc.FLastBinaryCmd, rbx
jne @allocate_new
// if LastHeapCurrent <> Heap(esi).FState.Current
mov rdx, [RSI].TOpcodeProc.FLastHeapCurrent
mov rsi, [RSI].TOpcodeProc.FHeap
cmp [RSI].TOpcodeHeap.FState.Current, rdx
jne @allocate_new
// if (Integer(Self.CmdList.F.Size) + DataSize > high(word))
add word ptr [RBX].TOpcodeCmd.F.Size, cx
jo @allocate_new_step_overflow
// if (Heap.FState.Margin < (DataSize+CMD_CUSHION_SIZE))
add ecx, CMD_CUSHION_SIZE
sub [RSI].TOpcodeHeap.FState.Margin, ecx
jl @allocate_new_step_margin
@allocate_append:
// проверки прошли успешно - просто добавляем опкоды в конец
// rax - TOpcodeBlock, rsi - TOpcodeHeap, rbx - CmdList(Result), rdx - Current, ecx - (DataSize+CMD_CUSHION_SIZE)
lea rcx, [rcx + rdx - CMD_CUSHION_SIZE]
mov rax, [RAX].TOpcodeBlock.P.Proc
mov [RSI].TOpcodeHeap.FState.Current, rcx
xchg rsi, rdx
mov [RAX].TOpcodeProc.FLastHeapCurrent, rcx
xchg rax, rbx
jmp @allocating_done
@allocate_new_step_margin:
add [RSI].TOpcodeHeap.FState.Margin, ecx
sub ecx, CMD_CUSHION_SIZE
@allocate_new_step_overflow:
sub word ptr [RBX].TOpcodeCmd.F.Size, cx
@allocate_new:
// выделяем новую команду
mov rsi, [RAX].TOpcodeBlock.P.Proc
mov rbx, [RSI].TOpcodeProc.FHeap
add ecx, CMD_HEADER_PLUS_CUSHION // ResultSize+CMD_CUSHION_SIZE
mov rsi, [RBX].TOpcodeHeap.FState.Current
mov edx, [RBX].TOpcodeHeap.FState.Margin
// выравнивание на 4 байта
add rsi, 3
and edx, -4
and rsi, -4
// if FState.Margin < (ResultSize+CMD_CUSHION_SIZE) then @call_alloc_cmd()
sub edx, ecx
jl @call_alloc_cmd
@no_call_alloc_cmd:
// памяти хватает - просто меняем Current/Margin
// Margin := bufMargin + CMD_CUSHION_SIZE
add edx, CMD_CUSHION_SIZE
mov [RBX].TOpcodeHeap.FState.Margin, edx
// Current заполнится в @allocated_fields (= новый edx)
lea rdx, [rsi + rcx - CMD_CUSHION_SIZE]
jmp @allocated_fields
@call_alloc_cmd:
// обязательный вызов Heap.Alloc(), но уже выровненные Current и Margin
add edx, ecx
mov [RBX].TOpcodeHeap.FState.Current, rsi
mov [RBX].TOpcodeHeap.FState.Margin, edx
push rax
push rcx
mov rcx, rbx
mov edx, ecx
push r8
push r9
push r10
push r11
call TOpcodeHeap.Alloc
pop r11
pop r10
pop r9
pop r8
mov rsi, rax
pop rcx
pop rax
mov rdx, [RBX].TOpcodeHeap.FState.Current
add [RBX].TOpcodeHeap.FState.Margin, CMD_CUSHION_SIZE
sub rdx, CMD_CUSHION_SIZE
@allocated_fields:
// rax - TOpcodeBlock, rbx - TOpcodeHeap, rdx - new Heap.Current,
// rcx - (DataSize+Header+Cushion), rsi - TOpcodeCmd (Result)
// размер
sub ecx, CMD_HEADER_PLUS_CUSHION
mov [RSI].TOpcodeCmd.F.Value, ecx
// необходимые поля
mov [RBX].TOpcodeHeap.FState.Current, rdx
mov rcx, [RAX].TOpcodeBlock.P.Proc
mov rbx, [RAX].TOpcodeBlock.CmdList
mov [RCX].TOpcodeProc.FLastBinaryCmd, rsi
mov [RCX].TOpcodeProc.FLastHeapCurrent, rdx
// cmd list
mov [RSI].TOpcodeCmd.FNext, rbx
mov [RAX].TOpcodeBlock.CmdList, rsi
// результат (rax) и Dest (rsi)
mov rax, CMD_HEADER_SIZE
xadd rsi, rax
{$endif}
@allocating_done:
// память выделена, результат уже лежит в eax/rax, Dest - в esi/rsi
// достаём ebx/rbx
{$ifdef CPUX86}
pop ebx
{$else .CPUX64}
xchg rbx, r12
{$endif}
// заносим данные: префиксы, опкод команды, advanced
// в свободном доступе edx и ecx
{$ifdef CPUX86}
// префиксы
mov edx, [esp]
shr edx, 24
mov ecx, ebx
and edx, $f
shl edx, cl
shr ecx, 24
or edx, [offset intel_prefixes + ecx*4]
mov [esi], edx
// опкод команды
pop edx
movzx ecx, bh
shr edx, 8
add esi, ecx
shr ebx, 16
mov [esi], edx
// advanced
and ebx, $ff
pop dword ptr [esi+ebx]
{$else .CPUX64}
// память выделена, результат уже лежит в rax, Dest - в rsi
// rbx содержит инфо: X | OpcodeSize | OpcodeOffset | byte(intel_prefixes_info[X])
// r8 - Advanced
// r9 - старый rsi
// r10 - старый rbx
// r11 - Parameters
// префиксы
lea rdx, [intel_prefixes]
mov r12, r11
mov ecx, ebx
shr r11, 24
shr ecx, 24
and r11, $f
mov edx, [rdx + rcx*4]
mov ecx, ebx
shr r12, 8
shl r11, cl
or rdx, r11
movzx ecx, bh
mov [rsi], edx
// опкод команды
add rsi, rcx
shr ebx, 16
mov [rsi], r12d
// advanced
and ebx, $ff
mov [rsi+rbx], r8d
{$endif}
// возврат регистров
{$ifdef CPUX86}
pop ebx
pop esi
{$else .CPUX64}
xchg r10, rbx
xchg r9, rsi
pop r12
{$endif}
end;
{$endif}
// вспомогательная функция для гибрида
// позволяет определять Min_Max по параметрам
{$ifdef OPCODE_MODES}
function TOpcodeBlock_Intel.HybridSize_MinMax(base_params, Parameters{итоговые значения для AddSmartBinaryCmd}: integer;
addr: POpcodeAddress): integer{word};
var
buf: TOpcodeAddress;
i1, i2: integer;
begin
Result := (intel_prefixes_info[Parameters shr 28] shr 8) + // размер набора префиксов
(1 + ord(Parameters and $00ff00 <> 0)) + // размер опкода: 1 или 2
byte(Parameters); // дополнительные байты
// Min_Max
Result := Result or (Result shl 8);
// корректировка Min для адреса
if (addr <> nil) and (addr.offset.Kind = ckCondition) then
begin
i1 := addr.IntelInspect(base_params);
buf := addr^;
buf.offset.Kind := ckValue;
buf.offset.Value := 0;
i2 := buf.IntelInspect(base_params);
Result := Result - ((i1 and $f)+ord(i1 and $f0))-((i2 and $f)+ord(i2 and $f0));
end;
end;
{$endif}
procedure TOpcodeBlock_Intel.diffcmd_const32(params: integer; const v_const: const_32; callback: opused_callback_0{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
var
fake_const: const_32;
use_const: ^const_32;
begin
use_const := @v_const;
if (TMethod(callback).Data <> nil) then
begin
{$ifdef OPCODE_TEST}
test_const(v_const, false, P.Proc);
{$endif}
// особые ситуации
if (v_const.Kind = ckPValue) then
begin
AddCmdPointer(params, v_const.pValue, 0 shl 24, TMethod(callback).Code, @TOpcodeBlock_Intel.diffcmd_const32{$ifdef OPCODE_MODES},cmd{$endif});
exit;
end else
if (v_const.Kind >= ckBlock) then
begin
{$ifdef OPCODE_MODES}if (Self.P.Proc.Mode <> omBinary) then
begin
fake_const.Kind := ckOffsetedCondition;
fake_const.OffsetedCondition := pointer(FMT_ONE_STRING);
end else
{$endif}
begin
fake_const.Kind := ckValue;
fake_const.Value := FAKE_CONST_32;
end;
use_const := @fake_const;
end;
end else
begin
TMethod(callback).Data := @Self;
end;
// вызываем
callback(params, {$ifdef OPCODE_MODES}use_const^,cmd{$else}use_const.Value{$endif});
// постобработка для сложного режима
// старое значение хранятся в v_const
if (use_const = @fake_const) then
begin
// подписка
with v_const do
if (Kind = ckBlock) then
begin
if (Block.P.Proc <> Self.P.Proc) then
with Block.P.Proc do
Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end else
// if (Kind = ckVariable) then
begin
with Variable do
Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end;
// присоединяем сопроводительную информацию
JoinCmdCellData(false, v_const);
end;
end;
procedure TOpcodeBlock_Intel.diffcmd_addr(params: integer; const addr: TOpcodeAddress; callback: opused_callback_1{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
var
fake_addr: TOpcodeAddress;
use_addr: ^TOpcodeAddress;
begin
use_addr := @addr;
if (TMethod(callback).Data <> nil) then
begin
{$ifdef OPCODE_TEST}
test_intel_address(addr, params and flag_x64 <> 0, P.Proc);
{$endif}
// особые ситуации
if (addr.offset.Kind = ckPValue) then
begin
AddCmdPointer(params, addr.offset.pValue, (pinteger(@addr.F.Bytes)^ and $00ffffff) or (1 shl 24),
TMethod(callback).Code, @TOpcodeBlock_Intel.diffcmd_addr{$ifdef OPCODE_MODES},cmd{$endif});
exit;
end else
if (addr.offset.Kind >= ckBlock) then
begin
pinteger(@fake_addr.F.Bytes)^ := pinteger(@addr.F.Bytes)^;
use_addr := @fake_addr;
{$ifdef OPCODE_MODES}if (Self.P.Proc.Mode <> omBinary) then
begin
fake_addr.offset.Kind := ckOffsetedCondition;
fake_addr.offset.OffsetedCondition := pointer(FMT_ONE_STRING);
end else
{$endif}
begin
fake_addr.offset.Kind := ckValue;
fake_addr.offset.Value := FAKE_CONST_32;
end;
end;
end else
begin
TMethod(callback).Data := @Self;
end;
// вызываем
callback(params, use_addr^{$ifdef OPCODE_MODES},cmd{$endif});
// постобработка для сложного режима
// старое значение хранятся в addr
if (use_addr = @fake_addr) then
begin
// подписка
with addr.offset do
if (Kind = ckBlock) then
begin
if (Block.P.Proc <> Self.P.Proc) then
with Block.P.Proc do
Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end else
// if (Kind = ckVariable) then
begin
with Variable do
Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end;
// присоединяем сопроводительную информацию
JoinCmdCellData({relative: boolean} (addr.F.Scale.intel = xNone) and
(params and flag_x64 <> 0) and (addr.offset.Kind = ckBlock)
, addr.offset);
end;
end;
procedure TOpcodeBlock_Intel.diffcmd_addr_const(params: integer; const addr: TOpcodeAddress; const v_const: const_32; callback: opused_callback_2{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
var
buf_addr, fake_addr: TOpcodeAddress;
buf_const, fake_const: const_32;
use_addr: POpcodeAddress;
use_const: ^const_32;
cmd_ptr_mode: boolean;
Consts: POpcodeConst;
difficult_mode: byte; {число от 0 до 3}
begin
use_addr := @addr;
use_const := @v_const;
if (TMethod(callback).Data <> nil) then
begin
{$ifdef OPCODE_TEST}
test_intel_address(addr, params and flag_x64 <> 0, P.Proc);
test_const(v_const, false, P.Proc);
{$endif}
// проводим различные манипуляции, определяем, вызывать ли "штрафной круг"
// смысл манипуляций в том, чтобы сразу сделать подписку (если нужно) и MakeReference()
cmd_ptr_mode := false;
with addr.offset do
case Kind of
ckPValue: cmd_ptr_mode := true;
ckBlock: // модификация данных используется только для блоков в бинарном режиме
{$ifdef OPCODE_MODES}if (Self.P.Proc.Mode = omBinary) then{$endif}
begin
use_addr := @buf_addr;
pinteger(@buf_addr.F.Bytes)^ := pinteger(@addr.F.Bytes)^;
if (Block.P.Proc <> Self.P.Proc) then
begin
// глобальный (бинарный режим) - перепрописываем Variable/VariableOffset
// пишем функцию и смещение
buf_addr.offset.Variable := TOpcodeVariable(Block.P.Proc);
// buf_addr.offset.VariableOffset := Block.MakeReference;
buf_addr.offset.VariableOffset := Block.O.Reference;
if (buf_addr.offset.VariableOffset = NO_REFERENCE) then buf_addr.offset.VariableOffset := Block.MakeReference;
// подписка
with Block.P.Proc do
Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end else
begin
// локальный: Блок + 0
buf_addr.offset.VariableOffset := 0;
end;
end;
ckVariable: begin
// подписка
with Variable do
Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end;
end;
with v_const do
case Kind of
ckPValue: cmd_ptr_mode := true;
ckBlock: // модификация данных используется только для блоков в бинарном режиме
{$ifdef OPCODE_MODES}if (Self.P.Proc.Mode = omBinary) then{$endif}
begin
use_const := @buf_const;
if (Block.P.Proc <> Self.P.Proc) then
begin
// глобальный (бинарный режим) - перепрописываем Variable/VariableOffset
// пишем функцию и смещение
buf_const.Variable := TOpcodeVariable(Block.P.Proc);
// buf_const.VariableOffset := Block.MakeReference;
buf_const.VariableOffset := Block.O.Reference;
if (buf_const.VariableOffset = NO_REFERENCE) then buf_const.VariableOffset := Block.MakeReference;
// подписка
with Block.P.Proc do
Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end else
begin
// локальный: Блок + 0
buf_const.VariableOffset := 0;
end;
end;
ckVariable: begin
// подписка
with Variable do
Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end;
end;
// если указатель
if (cmd_ptr_mode){(addr.offset.Kind = ckPValue) or (v_const.Kind = ckPValue)} then
begin
Consts := P.Proc.Heap.Alloc(2*sizeof(TOpcodeConst));
Consts^ := use_addr.offset;
inc(Consts);
Consts^ := use_const^;
dec(Consts);
AddCmdPointer(params, Consts, (pinteger(@use_addr.F.Bytes)^ and $00ffffff) or (2 shl 24),
TMethod(callback).Code, @TOpcodeBlock_Intel.diffcmd_addr_const{$ifdef OPCODE_MODES},cmd{$endif});
exit;
end;
end else
begin
TMethod(callback).Data := @Self;
end;
// обрабатываем сложные ситуации (Block и Variable)
difficult_mode := 0;
if (use_addr.offset.Kind >= ckBlock) then
begin
difficult_mode := 2;
// buf_addr в любом случае должен содержать старое значение
if (use_addr <> @buf_addr) then buf_addr := use_addr^{addr};
// use_addr := @FAKE_ADDRESS;
pinteger(@fake_addr.F.Bytes)^ := pinteger(@use_addr.F.Bytes)^;
{$ifdef OPCODE_MODES}if (Self.P.Proc.Mode <> omBinary) then
begin
fake_addr.offset.Kind := ckOffsetedCondition;
fake_addr.offset.OffsetedCondition := pointer(FMT_ONE_STRING);
end else
{$endif}
begin
fake_addr.offset.Kind := ckValue;
fake_addr.offset.Value := FAKE_CONST_32;
end;
use_addr := @fake_addr;
end;
if (use_const.Kind >= ckBlock) then
begin
inc(difficult_mode);
// buf_const в любом случае должен содержать старое значение
if (use_const <> @buf_const) then buf_const := use_const^{v_const};
// указатель на фейковую константу
{$ifdef OPCODE_MODES}if (Self.P.Proc.Mode <> omBinary) then
begin
fake_const.Kind := ckOffsetedCondition;
fake_const.OffsetedCondition := pointer(FMT_ONE_STRING);
end else
{$endif}
begin
fake_const.Kind := ckValue;
fake_const.Value := FAKE_CONST_32;
end;
use_const := @fake_const;
end;
// вызываем
callback(params, use_addr^, {$ifdef OPCODE_MODES}use_const^,cmd{$else}use_const.Value{$endif});
// постобработка для сложного режима
// старые значения хранятся в buf_addr/buf_const
if (difficult_mode <> 0) then
begin
// опционально выставляем флаг relative (mode |= 4)
if (difficult_mode and 2 <> 0) and (params and flag_x64 <> 0) and
(buf_addr.F.Scale.intel = xNone) and (buf_addr.offset.Kind = ckBlock) then
difficult_mode := difficult_mode or 4;
// присоединяем сопроводительную информацию
JoinCmdCellData(difficult_mode, buf_addr.offset, buf_const);
end;
end;
procedure TOpcodeBlock_Intel.diffcmd_const64(params: integer; const v_const: const_64; callback: opused_callback_3{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
var
fake_const: const_64;
use_const: ^const_64;
begin
use_const := @v_const;
if (TMethod(callback).Data <> nil) then
begin
{$ifdef OPCODE_TEST}
test_const(v_const, true, P.Proc);
{$endif}
// особые ситуации
if (v_const.Kind = ckPValue) then
begin
AddCmdPointer(params, v_const.pValue, 3 shl 24, TMethod(callback).Code, @TOpcodeBlock_Intel.diffcmd_const64{$ifdef OPCODE_MODES},cmd{$endif});
exit;
end else
if (v_const.Kind >= ckBlock) then
begin
{$ifdef OPCODE_MODES}if (Self.P.Proc.Mode <> omBinary) then
begin
fake_const.Kind := ckOffsetedCondition;
fake_const.OffsetedCondition := pointer(FMT_ONE_STRING);
end else
{$endif}
begin
fake_const.Kind := ckValue;
fake_const.Value := FAKE_CONST_32;
end;
use_const := @fake_const;
end;
end else
begin
TMethod(callback).Data := @Self;
end;
// вызываем
callback(params, {$ifdef OPCODE_MODES}use_const^,cmd{$else}use_const.Value{$endif});
// постобработка для сложного режима
// старое значение хранятся в v_const
if (use_const = @fake_const) then
begin
// подписка
with v_const do
if (Kind = ckBlock) then
begin
if (Block.P.Proc <> Self.P.Proc) then
with Block.P.Proc do
Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end else
if (Kind = ckVariable) then
begin
with Variable do
Storage.SubscribeGlobal(FSubscribedProcs, Self.P.Proc);
end;
// присоединяем сопроводительную информацию
JoinCmdCellData(false, v_const);
end;
end;
// одна команда
// например emms или ud2
function TOpcodeBlock_Intel.cmd_single(const opcode: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
{$ifndef OPCODE_FAST}
var
cmd_size: integer;
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
if (@cmd = nil) then Result := nil
else Result := AddCmdText(@cmd);
exit;
end;
{$endif}
// размер
if (opcode > $ffff) then
begin
if (opcode > $ffffff) then cmd_size := 4
else cmd_size := 3;
end else
begin
if (opcode > $ff) then cmd_size := 2
else cmd_size := 1;
end;
// добавляем
Result := AddCmd(cmBinary, cmd_size);
pinteger(@POpcodeCmdData(Result).Bytes[Result.Size-cmd_size])^ := opcode;
//Result := AddSmartBinaryCmd((cmd_size-1) or ((opcode and $ff) shl 16), opcode shr 8);
end;
{$else}
asm
{$ifdef CPUX64}
xchg rcx, r8
{$endif}
mov ecx, edx
movzx edx, dl
shl edx, 16
shr ecx, 8
jz @1
cmp ecx, $ff
jle @2
cmp ecx, $ffff
jle @3
@4: inc edx
@3: inc edx
@2: inc edx
@1:
{$ifdef CPUX64}
xchg rcx, r8
{$endif}
jmp AddSmartBinaryCmd
end;
{$endif}
// цепочечные команды (r)esi-(r)edi
// например movsb(/w/d/q), cmpsb(/w/d/q),
function TOpcodeBlock_Intel.cmd_rep_bwdq(const reps: intel_rep{=REP_SINGLE}; opcode: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
{$ifndef OPCODE_FASTEST}
var
CmdSize: integer;
X: integer;
{$ifdef OPCODE_MODES}
const
intel_rep_names: array[intel_rep] of pansichar = (nil, 'REP', 'REPE', 'REPZ', 'REPNE', 'REPNZ');
{$endif}
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
// RepToStr() + cmd
if (reps = REP_SINGLE) then Result := AddCmdText(@cmd)
else Result := AddCmdText('%s %s', [intel_rep_names[reps], cmd]);
exit;
end;
{$endif}
X := opcode;
CmdSize := 1;
if (opcode > $ff) then CmdSize := 2;
case reps of
REP, REPE, REPZ: begin
X := (X shl 8) or $F3;
System.Inc(CmdSize);
end;
REPNE, REPNZ: begin
X := (X shl 8) or $F2;
System.Inc(CmdSize);
end;
end;
// добавляем
//Result := AddCmd(cmBinary, CmdSize);
//Result.Data.Dwords[0] := X;
Result := AddSmartBinaryCmd((CmdSize-1) or ((X and $ff) shl 16), X shr 8);
end;
{$else}
asm
test dl, dl
jz @no_rep
{$ifdef CPUX86}
shl ecx, 8
or ecx, $F3
{$else .CPUX64}
shl r8, 8
or r8, $F3
{$endif}
cmp dl, REPZ
{$ifdef CPUX86}
lea edx, [ecx-1]
cmova ecx, edx
{$else .CPUX64}
lea rdx, [r8-1]
cmova r8, rdx
{$endif}
@no_rep:
{$ifdef CPUX86}
movzx edx, cl
{$else .CPUX64}
movzx rdx, r8b
{$endif}
shl edx, 16
{$ifdef CPUX86}
shr ecx, 8
{$else .CPUX64}
shr r8, 8
{$endif}
jz AddSmartBinaryCmd
{$ifdef CPUX86}
cmp ecx, $ff
lea edx, [edx + 1]
{$else .CPUX64}
cmp r8, $ff
lea rdx, [rdx + 1]
{$endif}
jna AddSmartBinaryCmd
inc edx
jmp AddSmartBinaryCmd
end;
{$endif}
// команда с одним параметром-константой
// пока известна только push
// PRE-реализация делается на месте
function TOpcodeBlock_Intel.cmd_const_value(const opcode: integer; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
var
X, value: integer;
// cmd + ConstToStr()
{$ifdef OPCODE_MODES}
const
HYBRID_MINMAX: array[boolean] of word = ($0502, $0505);
procedure FillAsText();
var
buffer: TOpcodeTextBuffer;
begin
buffer.Const32(v_const);
Result := AddCmdText('%s %s', [cmd, buffer.value.S]);
end;
{$endif}
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end else
if (P.Proc.Mode = omHybrid) and (v_const.Kind <> ckValue) then
begin
FillAsText();
Result.F.HybridSize_MinMax := HYBRID_MINMAX[(v_const.Kind = ckOffsetedCondition)];
exit;
end else
begin
value := v_const.Value;
end;
{$else}
value := v_const;
{$endif}
// варианты
if (value >= -128) and (value <= 127) then
begin
X := ((opcode and $ff) shl 16) or 1;
end else
begin
X := ((opcode and $ff00) shl 8) or 4;
end;
// вызов
Result := AddSmartBinaryCmd(X, value);
end;
// команда с одним параметром-регистром
// например inc al, push bx, bswap esp, jmp esi
function TOpcodeBlock_Intel.cmd_reg(const opcode_reg: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
const
UN_REX_W = (not rex_W);
UN_REX_W_ONLY = (not (rex_W xor flag_rex));
MP_JMP_LEAVE = ord(cmLeave) + ((0{бинарный}+2{jmp reg}) shl 8);
{$ifndef OPCODE_FASTEST}
var
Parameters: integer;
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
// cmd регистр
Result := AddCmdText('%s %s', [cmd, reg_intel_names[byte(opcode_reg)]]);
// jmp
if (word(opcode_reg shr 8) = $E0FE) then
begin
Result.F.ModeParam := MP_JMP_LEAVE + (128{текст} shl 8);
end;
exit;
end;
{$endif}
// оставляем префиксы и опкоды, дополнительный размер 0
Parameters := opcode_reg and intel_opcode_mask;
// выставляем все необходимые флаги, индекс в modrm
Parameters := Parameters or (reg_intel_info[byte(opcode_reg)] and intel_modrm_dest_mask);
// особые случаи
if (word(opcode_reg shr 8) = $E0FE) then
begin
// jmp reg
P.Proc.FLastBinaryCmd := NO_CMD;
Result := AddSmartBinaryCmd(Parameters, 0);
Result.F.ModeParam := MP_JMP_LEAVE;
exit;
end;
if (opcode_reg and flag_extra <> 0) and (byte(opcode_reg) >= ax) and (byte(opcode_reg) <= edi) then
begin
// под "экстра" случаем подразумеваются команды inc и dec,
// которые для платформы x86 и регистров ax..edi занимают один байт
Parameters := Parameters and $ff4f00ff;
end else
if (opcode_reg and $ff00 = 0) then
begin
// для команд pop и push всегда используется 1 байтовая операция
// в x64 для регистров rax..rdi не используется rex
Parameters := Parameters and $ffff00ff;
case byte(opcode_reg) of
rax..rdi: Parameters := Parameters and UN_REX_W;
r8..r15: Parameters := Parameters and UN_REX_W_ONLY;
end;
end;
// добавляем
Result := AddSmartBinaryCmd(Parameters, 0);
end;
{$else}
const
const_rax = rax;
const_ax = ax;
const_edi = edi;
asm
{$ifdef CPUX86}
push ebx
{$else .CPUX64}
xchg r8, rbx
xchg rax, rcx
lea r9, [reg_intel_info]
{$endif}
// edx - Parameters, ebx - расчётный буфер
// ecx - старая копия для "особых случаев"
movzx ebx, dl
mov ecx, edx
{$ifdef CPUX86}
mov ebx, [offset reg_intel_info + ebx*4]
{$else .CPUX64}
mov ebx, [r9 + rbx*4]
{$endif}
and edx, intel_opcode_mask
and ebx, intel_modrm_dest_mask
or edx, ebx
// особые случаи
mov ebx, ecx
shr ebx, 8
cmp bx, $E0FE
{$ifdef CPUX86}
pop ebx
{$endif}
jne @non_jmp
{$ifdef CPUX86}
mov ecx, [EAX].TOpcodeBlock.P.Proc
push offset @fill_cmleave
mov dword ptr [ECX].TOpcodeProc.FLastBinaryCmd, -1 //NO_CMD
{$else .CPUX64}
lea rcx, [@fill_cmleave]
or rbx, -1 //NO_CMD
push rcx
mov rcx, [RAX].TOpcodeBlock.P.Proc
mov [RCX].TOpcodeProc.FLastBinaryCmd, rbx
{$endif}
jmp @done
@non_jmp:
test ch, ch
jnz @non_push_pop
@push_pop:
sub cl, const_rax
and edx, $fff00ff
cmp cl, 15
ja @done
cmp cl, 7
ja @r8_r15
@rax_edi:
and edx, UN_REX_W
jmp @done
@r8_r15:
and edx, UN_REX_W_ONLY
jmp @done
@non_push_pop:
test ecx, flag_extra
jz @done
sub cl, const_ax
cmp cl, const_edi - const_ax
ja @done
and edx, $ff4f00ff
@done:
{$ifdef CPUX64}
xchg rcx, rax
xchg rbx, r8
{$endif}
jmp AddSmartBinaryCmd
@fill_cmleave:
{$ifdef CPUX86}
mov [EAX].TOpcodeCmd.F.ModeParam, MP_JMP_LEAVE
{$else .CPUX64}
mov [RAX].TOpcodeCmd.F.ModeParam, MP_JMP_LEAVE
{$endif}
end;
{$endif}
// один параметр адрес (без размера - он подразумевается)
// например jmp [edx], call [ebp+4], fldcw [r12]
function TOpcodeBlock_Intel.cmd_addr_value(const opcode: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
const
MP_JMP_LEAVE = ord(cmLeave) + ((0{бинарный}+3{jmp mem}) shl 8);
{$ifndef OPCODE_FAST}
var
X: integer;
cmd_jmp: boolean;
offset, leftover: integer;
// cmd + AddrToStr()
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
buffer: TOpcodeTextBuffer;
begin
buffer.IntelAddress(opcode, addr);
Result := AddCmdText('%s %s', [cmd, buffer.value.S]);
if (cmd_jmp) then
Result.F.ModeParam := MP_JMP_LEAVE + (128{текст} shl 8);
end;
{$endif}
begin
// общая информация
cmd_jmp := (dword(opcode shr 8) = $20FF{jmp mem});
X := addr.IntelInspect(opcode);
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end else
if (P.Proc.Mode = omBinary) or {omHybrid and}(addr.offset.Kind = ckValue) then
{$endif}
// для простоты extra добавляем просто $9B
// получается этот префикс может попасть в POpcodeCmd, а может и нет
// но отслеживание этого байта на практике врядли нужно
if (opcode and flag_extra <> 0) then cmd_single($9B{$ifdef OPCODE_MODES},PShortString(nil)^{$endif});
// смещение, остаток (для sib)
leftover := 0;
offset := addr.offset.Value;
if (X and $f0 <> 0) then
begin
leftover := offset shr 24;
offset := (offset shl 8) or ((X shr 8) and $ff);
X := (X and $ffff000f)+1;
end;
// вызов
X := (opcode and intel_opcode_mask) or X;
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (addr.offset.Kind <> ckValue) then
begin
FillAsText();
Result.F.HybridSize_MinMax := HybridSize_MinMax(opcode, X, @addr);
end else
{$endif}
begin
if (cmd_jmp) then P.Proc.FLastBinaryCmd := NO_CMD;
Result := AddSmartBinaryCmd(X, offset);
// дополнительный байт
if (byte(X) = 5) then
begin
POpcodeCmdData(Result).Bytes[Result.Size-1] := byte(leftover);
end;
if (cmd_jmp) then
Result.F.ModeParam := MP_JMP_LEAVE;
end;
end;
{$else}
asm
// проверка на jmp
// если да - пушим указатель на @fill_cmleave, чтобы функция при любом раскладе вернулась в неё
// и "обнуляем" P.Proc.FLastBinaryCmd
{$ifdef CPUX86}
mov [esp-4], edx
shr edx, 8
cmp dx, $20FF
je @jmp_mode
mov edx, [esp-4]
jmp @no_jmp_mode
@jmp_mode:
mov edx, [EAX].TOpcodeBlock.P.Proc
mov dword ptr [EDX].TOpcodeProc.FLastBinaryCmd, -1 //NO_CMD
mov edx, [esp-4]
push offset @fill_cmleave
{$else .CPUX64}
mov eax, edx
shr edx, 8
cmp dx, $20FF
mov edx, eax
jne @no_jmp_mode
or r9, -1 //NO_CMD
lea r10, [@fill_cmleave]
mov rax, [RCX].TOpcodeBlock.P.Proc
push r10
mov [RAX].TOpcodeProc.FLastBinaryCmd, r9
{$endif}
@no_jmp_mode:
// пуш параметров
// запись $9B если надо
{$ifdef CPUX86}
test edx, flag_extra
push eax // Self
push edx // opcode
jz @no_extra
push ecx
mov edx, $009B0000
call AddSmartBinaryCmd
pop ecx
mov edx, [esp]
mov eax, [esp+4]
{$else .CPUX64}
test edx, flag_extra
push rcx // Self
push rdx // opcode
jz @no_extra
push r8
mov edx, $009B0000
call AddSmartBinaryCmd
pop r8
mov rdx, [esp]
mov rcx, [esp+8]
{$endif}
@no_extra:
// offset := addr.offset.Value;
// X := addr.IntelInspect(opcode);
{$ifdef CPUX86}
push [ECX + TOpcodeAddress_offset + TOpcodeConst.F.Value] // offset
xchg eax, ecx
{$else .CPUX64}
push dword ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.F.Value] // offset
xchg rcx, r8
{$endif}
call TOpcodeAddress.IntelInspect
// ставим offset на последнее место в функции
// opcode заносим соответственно в edx
// if (X and $f0 <> 0) then {если есть sib}
test al, $f0
{$ifdef CPUX86}
pop ecx
pop edx
{$else .CPUX64}
pop r8 {$message 'может r8d?'}
pop rdx
{$endif}
// в стеке: Self
// в регистрах: eax - X, edx - opcode, ecx(r8d) - offset
jz @std_call
// изменяем X, offset
cmp al, $f4
jne @change_offset_change
@stack_correction:
// в данном случае надо подредактировать стек, чтобы по возвращении из AddSmartBinaryCmd
// дописать последний байт (offset shr 24)
{$ifdef CPUX86}
push offset @byte_finalizing
push [esp+4] // self
mov [esp+8], ecx
{$else .CPUX64}
lea r9, [@byte_finalizing]
push r9
push [rsp+8] // self
mov [rsp+16], r8
{$endif}
@change_offset_change:
{$ifdef CPUX86}
shl ecx, 8
mov cl, ah
{$else .CPUX64}
movzx ecx, ah
shl r8, 8
or r8, rcx
{$endif}
and eax, $ffff000f
inc eax
// AddSmartBinaryCmd((opcode and intel_opcode_mask) or X, offset);
@std_call:
and edx, intel_opcode_mask
or edx, eax
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
pop rcx
{$endif}
jmp AddSmartBinaryCmd
@fill_cmleave:
{$ifdef CPUX86}
mov [EAX].TOpcodeCmd.F.ModeParam, MP_JMP_LEAVE
{$else .CPUX64}
mov [RAX].TOpcodeCmd.F.ModeParam, MP_JMP_LEAVE
{$endif}
ret
// Result.Data.Bytes[Result.Size-1] := byte(leftover);
@byte_finalizing:
{$ifdef CPUX86}
pop ecx
movzx edx, word ptr [EAX].TOpcodeCmd.F.Size
shr ecx, 24
mov [eax + TOpcodeCmdData.bytes + edx - 1], cl
{$else .CPUX64}
pop rcx
movzx edx, word ptr [RAX].TOpcodeCmd.F.Size
shr ecx, 24
mov [rax + TOpcodeCmdData.bytes + rdx - 1], cl
{$endif}
end;
{$endif}
// один параметр адрес (без размера - он подразумевается)
// например jmp [edx], call [ebp+4], fldcw [r12]
procedure TOpcodeBlock_Intel.PRE_cmd_addr(const opcode: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// небольшое убыстрение для стандартных случаев
// или обычный вызов
if (addr.offset.Kind = ckValue) then
begin
{$ifdef OPCODE_TEST}
test_intel_address(addr, opcode and flag_x64 <> 0, P.Proc);
{$endif}
cmd_addr_value(opcode, addr{$ifdef OPCODE_MODES},cmd{$endif});
end else
begin
diffcmd_addr(opcode, addr, cmd_addr_value{$ifdef OPCODE_MODES},cmd{$endif});
// особая логика для jmp [pointer]
if (word(opcode shr 8) = $20FF) and (addr.offset.Kind = ckPValue) then
Inc(Self.CmdList.F.Param, 2);
end;
end;
// два параметра: ptr, addr
// например dec byte ptr [ecx*4] | push dword ptr [esp]
function TOpcodeBlock_Intel.cmd_ptr_addr_value(const base_opcode_ptr: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
{$ifndef OPCODE_FAST}
var
X, Y: integer;
offset, leftover: integer;
opcode_ptr: integer;
// cmd + PtrToStr(ptr) + AddrToStr()
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
buffer: TOpcodeTextBuffer;
str_ptr: PShortString;
begin
buffer.IntelAddress(base_opcode_ptr, addr);
if (false{!}) then str_ptr := PShortString(@STR_NULL)
else str_ptr := buffer.SizePtr(base_opcode_ptr, 1);
Result := AddCmdText('%s %s%s', [cmd, str_ptr^, buffer.value.S]);
end;
{$endif}
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end;
{$endif}
opcode_ptr := base_opcode_ptr;
// особый случай: push/pop для x64 и qword ptr
if (opcode_ptr and flag_extra <> 0) and (size_ptr(opcode_ptr) = qword_ptr) then System.Dec(opcode_ptr);
// общая информация
X := ptr_intel_info[size_ptr(opcode_ptr)];
Y := addr.IntelInspect(opcode_ptr);
// смещение, остаток (для sib)
leftover := 0;
offset := addr.offset.Value;
if (Y and $f0 <> 0) then
begin
leftover := offset shr 24;
offset := (offset shl 8) or ((Y shr 8) and $ff);
Y := (Y and $ffff000f)+1;
end;
// параметры
X := (opcode_ptr and intel_opcode_mask) or (X and integer($ffffff00)) or Y;
// вызов
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (addr.offset.Kind <> ckValue) then
begin
FillAsText();
Result.F.HybridSize_MinMax := HybridSize_MinMax(opcode_ptr, X, @addr);
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, offset);
// дополнительный байт
if (byte(X) = 5) then
begin
POpcodeCmdData(Result).Bytes[Result.Size-1] := byte(leftover);
end;
end;
end;
{$else}
const
qword_push_pop_mask = flag_extra or $ff;
qword_push_pop_id = flag_extra or ord(qword_ptr);
asm
// начало (перед вызовом TOpcodeAddress.IntelInspect)
{$ifdef CPUX86}
push eax // self
push [ECX + TOpcodeAddress_offset + TOpcodeConst.F.Value] // offset
push edx // opcode_ptr
mov eax, ecx // addr as Self
{$else .CPUX64}
mov eax, [r8 + TOpcodeAddress_offset + TOpcodeConst.F.Value]
push rcx // self
push rax // offset
push rdx // opcode_reg
mov rcx, r8 // addr as Self
{$endif}
call TOpcodeAddress.IntelInspect
// рассчитываем X
// if (opcode_ptr and flag_extra <> 0) and (size_ptr(opcode_ptr) = qword_ptr) then System.Dec(opcode_ptr);
// X := (ptr_intel_info[size_ptr(opcode_ptr)] and integer($ffffff00)) or (opcode_reg and intel_opcode_mask);
{$ifdef CPUX86}
pop edx
{$else .CPUX64}
pop rdx
{$endif}
mov ecx, edx
and edx, qword_push_pop_mask
and ecx, intel_opcode_mask
cmp edx, qword_push_pop_id
jne @after_extra
dec edx
@after_extra:
movzx edx, dl
{$ifdef CPUX86}
mov edx, [offset ptr_intel_info + edx*4]
{$else .CPUX64}
lea r11, [ptr_intel_info]
mov edx, [r11 + rdx*4]
{$endif}
and edx, $ffffff00
or edx, ecx
// смещение, остаток (для sib)
test al, $f0
{$ifdef CPUX86}
pop ecx
{$else .CPUX64}
pop rcx
{$endif}
jz @sib_done
cmp al, $f4
jne @sib_std
{$ifdef CPUX86}
push offset @finalize_byte
push [esp+4]
mov [esp+8], ecx
{$else .CPUX64}
lea r11, [@finalize_byte]
push r11
push [rsp+8]
mov [rsp+16], rcx
{$endif}
@sib_std:
shl ecx, 8
mov cl, ah
and eax, $ffff000f
inc eax
@sib_done:
or edx, eax
// вызов
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
mov r8, rcx
pop rcx
{$endif}
jmp AddSmartBinaryCmd
// последний (вытесненный) байт
@finalize_byte:
{$ifdef CPUX86}
pop ecx
movzx edx, word ptr [EAX].TOpcodeCmd.F.Size
shr ecx, 24
mov [eax + TOpcodeCmdData.bytes + edx - 1], cl
{$else .CPUX64}
pop rcx
movzx edx, word ptr [RAX].TOpcodeCmd.F.Size
shr ecx, 24
mov [rax + TOpcodeCmdData.bytes + rdx - 1], cl
{$endif}
end;
{$endif}
// два параметра: ptr, addr
// например dec byte ptr [ecx*4] | push dword ptr [esp]
procedure TOpcodeBlock_Intel.PRE_cmd_ptr_addr(const opcode_ptr: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// небольшое убыстрение для стандартных случаев
// или обычный вызов
if (addr.offset.Kind = ckValue) then
begin
{$ifdef OPCODE_TEST}
test_intel_address(addr, opcode_ptr and flag_x64 <> 0, P.Proc);
{$endif}
cmd_ptr_addr_value(opcode_ptr, addr{$ifdef OPCODE_MODES},cmd{$endif});
end else
diffcmd_addr(opcode_ptr, addr, cmd_ptr_addr_value{$ifdef OPCODE_MODES},cmd{$endif});
end;
// два параметра: reg, reg
// например mov esi, ebx | add bh, cl | test ax, dx
function TOpcodeBlock_Intel.cmd_reg_reg(const base_opcode_reg, base_v_reg: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
const
src_ax_eax_rax_mask = intel_modrm_src_index or intel_nonbyte_mask;
dest_ax_eax_rax_mask = intel_modrm_dest_index or intel_nonbyte_mask;
{$ifndef OPCODE_FASTEST}
var
X, Y: integer;
opcode_reg, v_reg: integer;
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// cmd регистр, регистр
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
Result := AddCmdText('%s %s, %s', [cmd, reg_intel_names[byte(base_opcode_reg)], reg_intel_names[byte(base_v_reg)]]);
exit;
end;
{$endif}
opcode_reg := base_opcode_reg;
v_reg := base_v_reg;
// для imul и add надо поменять местами аргументы
if (opcode_reg and flag_extra <> 0) then
begin
X := opcode_reg;
opcode_reg := (opcode_reg and integer($ffffff00)) or (v_reg and $ff);
v_reg := X;
end;
// рассчёт параметров
X := reg_intel_info[byte(opcode_reg)];
Y := reg_intel_info[byte(v_reg)];
// особая логика для xchg ax/eax/rax
if (byte(opcode_reg shr 8) = $86) then
begin
if (X and src_ax_eax_rax_mask = intel_nonbyte_mask) then
begin
X := Y xor intel_nonbyte_mask;
opcode_reg := $00900000;
Y := 0;
end else
if (Y and dest_ax_eax_rax_mask = intel_nonbyte_mask) then
begin
X := X xor intel_nonbyte_mask;
opcode_reg := $00900000;
Y := 0;
end;
end;
// результат (всегда бинарный)
Result := AddSmartBinaryCmd((opcode_reg and intel_opcode_mask) or
(X and intel_modrm_dest_mask) or (Y and intel_modrm_src_mask), 0);
end;
{$else}
asm
// подготовка
{$ifdef CPUX86}
push eax
{$else .CPUX64}
xchg rcx, r8 // Self := r8, v_reg := rcx
{$endif}
// в случае imul/add
test edx, flag_extra
jz @after_extra
xchg dl, cl
@after_extra:
// инициализируем X(eax)/Y(ecx)
mov eax, edx
and ecx, $ff
and eax, $ff
{$ifdef CPUX86}
mov ecx, [offset reg_intel_info + ecx*4]
mov eax, [offset reg_intel_info + eax*4]
{$else .CPUX64}
lea r9, [reg_intel_info]
mov ecx, [r9 + rcx*4]
mov eax, [r9 + rax*4]
{$endif}
// особая логика для xchg ax/eax/rax
cmp dh, $86
jne @calculate
{$ifdef CPUX86}
push ebx
{$else .CPUX64}
xchg rbx, r9
{$endif}
@param_src_test:
mov ebx, eax
and ebx, src_ax_eax_rax_mask
cmp ebx, intel_nonbyte_mask
jne @param_dest_test
mov eax, ecx
jmp @xchg_params
@param_dest_test:
mov ebx, ecx
and ebx, dest_ax_eax_rax_mask
cmp ebx, intel_nonbyte_mask
jne @after_xchg
@xchg_params:
xor eax, intel_nonbyte_mask
mov edx, $00900000
xor ecx, ecx
@after_xchg:
{$ifdef CPUX86}
pop ebx
{$else .CPUX64}
xchg rbx, r9
{$endif}
// рассчёт результата (edx)
@calculate:
and edx, intel_opcode_mask
and eax, intel_modrm_dest_mask
and ecx, intel_modrm_src_mask
or edx, eax
or edx, ecx
// концовка
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
xchg rcx, r8
{$endif}
// прыжок
jmp AddSmartBinaryCmd
end;
{$endif}
const
optimize_test_byte: array[al..dil] of reg_x64 = (al,cl,dl,bl,ah,ch,dh,bh,al,cl,dl,
bl,sp,bp,si,di,al,cl,dl,bl,sp,bp,si,di,r8b,r9b,r10b,r11b,r12b,r13b,r14b,r15b,r8b,
r9b,r10b,r11b,r12b,r13b,r14b,r15b,al,cl,dl,bl,spl,bpl,sil,dil,r8b,r9b,r10b,r11b,
r12b,r13b,r14b,r15b,r8b,r9b,r10b,r11b,r12b,r13b,r14b,r15b,spl,bpl,sil,dil);
optimize_test_word: array[al..dil] of reg_x64 = (al,cl,dl,bl,ah,ch,dh,bh,ax,cx,
dx,bx,sp,bp,si,di,ax,cx,dx,bx,sp,bp,si,di,r8w,r9w,r10w,r11w,r12w,r13w,r14w,r15w,
r8w,r9w,r10w,r11w,r12w,r13w,r14w,r15w,ax,cx,dx,bx,sp,bp,si,di,r8w,r9w,r10w,r11w,
r12w,r13w,r14w,r15w,r8b,r9b,r10b,r11b,r12b,r13b,r14b,r15b,spl,bpl,sil,dil);
// два параметра: reg, const_32
// например cmp edx, 15 | and r8, $ff | test ebx, $0100
function TOpcodeBlock_Intel.cmd_reg_const_value(const base_opcode_reg: integer; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
const
dif_spl_sp = spl-sp;
dif_rax_eax = rax-eax;
dif_r8_r8d = r8-r8d;
{$ifndef OPCODE_FAST}
var
REG: integer;
X: integer;
imm_size: integer;
value: integer;
opcode_reg: integer;
// cmd регистр, константа(%s или %d)
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
buffer: TOpcodeTextBuffer;
buf_const: const_32;
begin
if (v_const.Kind = ckValue) then
begin
buf_const.Kind := ckValue;
buf_const.Value := value;
end else
begin
buf_const := v_const;
end;
buffer.Const32(buf_const);
Result := AddCmdText('%s %s, %s', [cmd, reg_intel_names[REG], buffer.value.S]);
end;
{$endif}
begin
REG := base_opcode_reg and $ff;
opcode_reg := base_opcode_reg;
// оптимизация для test, and, mov
{$ifdef OPCODE_MODES}
value := v_const.Value;
if (v_const.Kind <> ckValue) then value := low(integer);
{$else}
value := v_const;
{$endif}
if (value >= 0) then
case byte(opcode_reg shr 8) of
$A8: begin
// test
if (value <> 0) and (value and $ffff00ff = 0) and (optimize_test_byte[REG] in [al..bl]) then
begin
REG := optimize_test_byte[REG] + 4;
value := value shr 8;
end else
case value of
0..$ff: begin
REG := optimize_test_byte[REG];
if (opcode_reg and flag_x64 <> 0) and (byte(REG) in [sp..di]) then REG := REG + dif_spl_sp;
end;
$0100..$ffff: begin
REG := optimize_test_word[REG];
end;
else
if (REG in [rax..rdi]) then REG := REG - dif_rax_eax;
end;
end;
$24: begin
// and
if (REG in [rax..rdi]) then REG := REG - dif_rax_eax;
end;
$00: begin
// mov
if (REG in [r8..r15]) then REG := REG - dif_r8_r8d
else
if (REG in [rax..rdi]) then REG := REG - dif_rax_eax;
end;
end;
opcode_reg := (opcode_reg and integer($ffffff00)) or REG;
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end;
{$endif}
// информация
X := reg_intel_info[byte(opcode_reg)];
// рассчёт опкода и размера операнда
if (opcode_reg and $ff00 = 0) then
begin
// особая логика для команды mov
imm_size := byte(X);
opcode_reg := opcode_reg or ((X and intel_nonbyte_mask) shl 11);
X := X and (not intel_nonbyte_mask);
if (imm_size = 8) then
begin
X := (opcode_reg and intel_opcode_mask) or (X and intel_modrm_dest_mask) or imm_size;
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (v_const.Kind <> ckValue) then
begin
FillAsText();
// размер константы всегда известен
Result.F.HybridSize_MinMax := HybridSize_MinMax(base_opcode_reg, X, nil);
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, value);
pinteger(@POpcodeCmdData(Result).Bytes[Result.Size-sizeof(integer)])^ := -1;
end;
exit;
end;
end else
begin
// размер операнда
if (byte(X) = 1) then imm_size := 1
else
begin
imm_size := 4;
if (opcode_reg and flag_extra = 0) and (value >= -128) and (value <= 127) then
begin
imm_size := 1;
X := X or $0200;
end else
if (byte(X) = 2) then
begin
imm_size := 2;
end;
end;
// опкод
if (X and intel_modrm_dest_index = 0) and (X and $0200 = 0) then
begin
// особая логика для al/ax/eax/rax
opcode_reg := opcode_reg or (X and intel_nonbyte_mask);
opcode_reg := (opcode_reg and integer($ff000000)) or ((opcode_reg and $0000ff00) shl 8);
X := X and $ffff00ff;
end else
begin
// стандартный способ
if (opcode_reg and flag_extra <> 0{test}) then opcode_reg := (opcode_reg and $ffff00ff) or $F600
else opcode_reg := (opcode_reg and $ffff00ff) or $8000;
end;
end;
// результат
X := (opcode_reg and intel_opcode_mask) or (X and intel_modrm_dest_mask) or imm_size;
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (v_const.Kind <> ckValue) then
begin
FillAsText();
// ручная корректировка Min (константа)
value := 0;
if (v_const.Kind = ckCondition) and (base_opcode_reg and $ff00 <> 0{не mov}) and
(opcode_reg and flag_extra = 0{не test}) then
begin
case byte(reg_intel_info[byte(base_opcode_reg)]) of
1: {imm_size = 1 byte only};
2: begin
// imm_size = 1 || 2 bytes
if (REG <> ax{в случае ax меньше на 1 байт не будет ни при каком раскладе}) then value := 1;
end;
else
// imm_size = 1 || 4 bytes
value := 3;
end;
end;
// MinMax с учётом ручной корректировки Min
Result.F.HybridSize_MinMax := HybridSize_MinMax(base_opcode_reg, X, nil)-value;
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, value);
end;
end;
{$else}
const
reg_rax = rax;
reg_sp = sp;
X_IMM_MASK = intel_modrm_dest_mask or $ff;
asm
// подготовка
{$ifdef CPUX86}
push eax
{$else .CPUX64}
xchg rcx, r8 // Self := r8, v_reg := rcx
{$endif}
// opcode_reg - edx
// X и imm_size - eax
// value - ecx
// оптимизация для test, and, mov
test ecx, ecx
jl @after_optimize
movzx eax, dl
cmp dh, $A8
je @opt_test
cmp dh, $24
je @opt_and
test dh, dh
jnz @after_optimize
@opt_mov:
sub eax, reg_rax
cmp eax, 15
ja @after_optimize
cmp eax, 7
jbe @rax_rdi_to_eax
sub edx, dif_r8_r8d
jmp @after_optimize
@opt_test:
{$ifdef CPUX86}
movzx eax, byte ptr [optimize_test_byte + eax]
{$else .CPUX64}
lea r11, [optimize_test_byte]
movzx eax, byte ptr [r11 + rax]
{$endif}
test ecx, ecx
jz @test_case
test ecx, $ffff00ff
jnz @test_case
cmp al, 3{bl}
ja @test_case
add eax, 4
shr ecx, 8
jmp @reg_correction
@test_case:
cmp ecx, $ffff
ja @test_4
cmp ecx, $ff
ja @test_2
@test_1:
test edx, flag_x64
jz @reg_correction
sub eax, reg_sp
cmp eax, 3
jbe @sp_di_to_spl
add eax, reg_sp
jmp @reg_correction
@sp_di_to_spl:
add eax, reg_sp + dif_spl_sp
jmp @reg_correction
@test_2:
movzx eax, dl
{$ifdef CPUX86}
movzx eax, byte ptr [optimize_test_word + eax]
{$else .CPUX64}
lea r11, [optimize_test_word]
movzx eax, byte ptr [r11 + rax]
{$endif}
jmp @reg_correction
@test_4:
movzx eax, dl
sub eax, reg_rax
cmp eax, 7
ja @after_optimize
jmp @rax_rdi_to_eax
@reg_correction:
and edx, $ffffff00
or edx, eax
jmp @after_optimize
@opt_and:
sub eax, reg_rax
cmp eax, 7
ja @after_optimize
@rax_rdi_to_eax:
sub edx, dif_rax_eax
@after_optimize:
// информация
movzx eax, dl
{$ifdef CPUX86}
mov eax, dword ptr [reg_intel_info + eax*4]
{$else .CPUX64}
lea r11, [reg_intel_info]
mov eax, [r11 + rax*4]
{$endif}
// рассчёт опкода и размера операнда
test dh, dh
jnz @opcode_standard
// особая логика для mov
test eax, intel_nonbyte_mask
jz @opcode_done
and eax, not intel_nonbyte_mask
or edx, $080000
// если размер константы должен быть 8 байт
cmp al, 8
jne @opcode_done
{$ifdef CPUX86}
push [esp] // copy eax
mov [esp+4], offset @mov_8_finalize
{$else .CPUX64}
lea r11, [@mov_8_finalize]
push r11
{$endif}
jmp @opcode_done
@mov_8_finalize:
{$ifdef CPUX86}
movzx edx, word ptr [EAX].TOpcodeCmd.F.Size
mov dword ptr [eax + TOpcodeCmdData.bytes + edx - 4], $ffffffff
{$else .CPUX64}
movzx edx, word ptr [RAX].TOpcodeCmd.F.Size
mov dword ptr [rax + TOpcodeCmdData.bytes + rdx - 4], $ffffffff
{$endif}
ret
@opcode_standard:
// стандартный подход (не mov)
@opcode_size:
cmp al, 1
je @opcode_choose_mode
test edx, flag_extra
lea ecx, [ecx+128]
jnz @opcode_retrieve_value
cmp ecx, 255
ja @opcode_retrieve_value
and eax, $ffffff00
add ecx, -128
or eax, $0201
jmp @opcode_choose_mode
@opcode_retrieve_value:
add ecx, -128
@opcode_size_2_4:
cmp al, 2
je @opcode_choose_mode
and eax, $ffffff00
or eax, 4
@opcode_choose_mode:
test eax, intel_modrm_dest_index or $0200
jnz @opcode_not_eax
@opcode_eax:
{$ifdef CPUX86}
push eax
{$else .CPUX64}
mov r9, rax
{$endif}
and eax, intel_nonbyte_mask
or edx, eax
mov eax, edx
and edx, $0000ff00
and eax, $ff000000
shl edx, 8
or edx, eax
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
mov rax, r9
{$endif}
and eax, $ffff00ff
jmp @opcode_done
@opcode_not_eax:
and edx, $fff00ff
test edx, flag_extra
jz @opcode_cmd_80
or edx, $F600
jmp @opcode_done
@opcode_cmd_80:
or edx, $8000
@opcode_done:
// параметры
and edx, intel_opcode_mask
and eax, X_IMM_MASK
or edx, eax
// концовка
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
xchg rcx, r8
{$endif}
// прыжок
jmp AddSmartBinaryCmd
end;
{$endif}
// два параметра: reg, const_32
// например cmp edx, 15 | and r8, $ff | test ebx, $0100
procedure TOpcodeBlock_Intel.PRE_cmd_reg_const(const opcode_reg: integer; const v_const: const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// небольшое убыстрение для стандартных случаев
// или обычный вызов
if (v_const.Kind = ckValue) then
begin
// проверку для ckValue делать не нужно
cmd_reg_const_value(opcode_reg, {$ifdef OPCODE_MODES}v_const,cmd{$else}v_const.Value{$endif});
end else
diffcmd_const32(opcode_reg, v_const, cmd_reg_const_value{$ifdef OPCODE_MODES},cmd{$endif});
end;
// два параметра: reg, const_32 | reg, cl
// только для сдвиговых команд rcl,rcr,rol,ror,sal,sar,shl,shr
function TOpcodeBlock_Intel.shift_reg_const_value(const opcode_reg: integer; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
{$ifndef OPCODE_FAST}
var
X: integer;
value: integer;
// cmd регистр, cl
// или
// cmd регистр, %d | %s
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
buffer: TOpcodeTextBuffer;
const_value: PShortString;
begin
if (opcode_reg and flag_extra <> 0{cl}) then const_value := PShortString(@STR_CL)
else const_value := buffer.Const32(v_const);
Result := AddCmdText('%s %s, %s', [cmd, reg_intel_names[byte(opcode_reg)], const_value^]);
end;
{$endif}
begin
{$ifdef OPCODE_MODES}
value := v_const.Value;
if (v_const.Kind <> ckValue) then value := low(integer);
{$else}
value := v_const;
{$endif}
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end;
{$endif}
// информация по регистру
X := reg_intel_info[byte(opcode_reg)];
// параметры
X := (opcode_reg and intel_opcode_mask) or (X and intel_modrm_dest_mask);
// размер константы, коррекция (для 1)
if (opcode_reg and flag_extra = 0{imm8}) then
begin
if (value = 1) then X := X + $1000 {C0-->D0}
else X := X + 1{value_size = 1};
end;
// вызов
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (opcode_reg and flag_extra = 0{константа}) and (v_const.Kind <> ckValue) then
begin
FillAsText();
Result.F.HybridSize_MinMax := HybridSize_MinMax(opcode_reg, X, nil) -
ord((opcode_reg and flag_extra = 0{imm8}) and (v_const.Kind = ckCondition));
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, value);
end;
end;
{$else}
const
value_1_correction = $1000-1;
asm
{$ifdef CPUX86}
push eax
{$endif}
// информация по регистру
movzx eax, dl
{$ifdef CPUX86}
mov eax, [offset reg_intel_info + eax*4]
{$else .CPUX64}
lea r11, [reg_intel_info]
mov eax, [r11 + rax*4]
{$endif}
and eax, intel_modrm_dest_mask
// размер константы, коррекция (для 1)
test edx, flag_extra
jnz @imm_done
{$ifdef CPUX86}
cmp ecx, 1
lea eax, [eax+1]
{$else .CPUX64}
cmp r8d, 1
lea rax, [rax+1]
{$endif}
jne @imm_done
add eax, value_1_correction
@imm_done:
// вызов
and edx, intel_opcode_mask
or edx, eax
{$ifdef CPUX86}
pop eax
{$endif}
jmp AddSmartBinaryCmd
end;
{$endif}
// два параметра: reg, const_32 | reg, cl
// только для сдвиговых команд rcl,rcr,rol,ror,sal,sar,shl,shr
procedure TOpcodeBlock_Intel.PRE_shift_reg_const(const opcode_reg: integer; const v_const: const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// небольшое убыстрение для стандартных случаев
// или обычный вызов
if (v_const.Kind = ckValue) then
begin
// проверку для ckValue делать не нужно
shift_reg_const_value(opcode_reg, {$ifdef OPCODE_MODES}v_const,cmd{$else}v_const.Value{$endif});
end else
diffcmd_const32(opcode_reg, v_const, shift_reg_const_value{$ifdef OPCODE_MODES},cmd{$endif});
end;
// два параметра: reg, addr или addr, reg. Направление определяется по опкоду
// например add esi, [ebp-$14] или xchg [offset variable + ecx*2 + 6], dx
function TOpcodeBlock_Intel.cmd_reg_addr_value(const opcode_reg: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
{$ifndef OPCODE_FAST}
var
X, Y: integer;
offset, leftover: integer;
// cmd регистр, адрес
// или
// cmd адрес, регистр
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
buffer: TOpcodeTextBuffer;
reg: pansichar;
begin
buffer.IntelAddress(opcode_reg, addr);
reg := reg_intel_names[byte(opcode_reg)];
if (opcode_reg and $0200 <> 0) then
Result := AddCmdText('%s %s, %s', [cmd, reg, buffer.value.S])
else
Result := AddCmdText('%s %s, %s', [cmd, buffer.value.S, reg]);
end;
{$endif}
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end;
{$endif}
// общая информация
X := reg_intel_info[byte(opcode_reg)];
Y := addr.IntelInspect(opcode_reg);
// смещение, остаток (для sib)
leftover := 0;
offset := addr.offset.Value;
if (Y and $f0 <> 0) then
begin
leftover := offset shr 24;
offset := (offset shl 8) or ((Y shr 8) and $ff);
Y := (Y and $ffff000f)+1;
end;
// параметры
X := (opcode_reg and intel_opcode_mask) or (X and intel_modrm_src_mask) or Y;
// вызов
if (X and $ff00 = 0) then
begin
// особый случай (add m8, r8)
X := X or $0100;
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (addr.offset.Kind <> ckValue) then
begin
FillAsText();
Result.F.HybridSize_MinMax := HybridSize_MinMax(opcode_reg, X, @addr);
exit;
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, offset);
POpcodeCmdData(Result).Bytes[Result.Size-byte(X)-2] := 0;
end;
end else
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (addr.offset.Kind <> ckValue) then
begin
FillAsText();
Result.F.HybridSize_MinMax := HybridSize_MinMax(opcode_reg, X, @addr);
exit;
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, offset);
end;
end;
// дополнительный байт
if (byte(X) = 5) then
begin
POpcodeCmdData(Result).Bytes[Result.Size-1] := byte(leftover);
end;
end;
{$else}
asm
// начало (перед вызовом TOpcodeAddress.IntelInspect)
{$ifdef CPUX86}
push ebx // буфер
push eax // self
push [ECX + TOpcodeAddress_offset + TOpcodeConst.F.Value] // offset
push edx // opcode_reg
mov eax, ecx // addr as Self
{$else .CPUX64}
push rbx // буфер
mov eax, [r8 + TOpcodeAddress_offset + TOpcodeConst.F.Value]
push rcx // self
push rax // offset
push rdx // opcode_reg
mov rcx, r8 // addr as Self
{$endif}
call TOpcodeAddress.IntelInspect
// возврат параметров
// Y - eax, edx - X, opcode_reg - ecx, ebx - буфер (leftover)
{$ifdef CPUX86}
pop ecx // opcode_reg
{$else .CPUX64}
pop rcx // opcode_reg
{$endif}
// X := reg_intel_info[opcode_reg and $ff];
// X := (opcode_reg and intel_opcode_mask) or (X and intel_modrm_src_mask){ or Y};
movzx edx, cl
xor ebx, ebx
{$ifdef CPUX86}
mov edx, [offset reg_intel_info + edx*4]
{$else .CPUX64}
lea r11, [reg_intel_info]
mov edx, [r11 + rdx*4]
{$endif}
and ecx, intel_opcode_mask
and edx, intel_modrm_src_mask
or edx, ecx
// возвращаем offset в ecx/
// if (Y and $f0 <> 0{используется sib}) then откорректировать leftover, offset, Y
test al, $f0
{$ifdef CPUX86}
pop ecx
{$else}
pop r8
{$endif}
jz @add_Y
{$ifdef CPUX64}
mov rcx, r8
{$endif}
mov ebx, ecx
shl ecx, 8
shr ebx, 24
mov cl, ah
and eax, $ffff000f
{$ifdef CPUX64}
mov r8, rcx
{$endif}
inc eax
@add_Y:
or edx, eax
// возвращаем параметр self
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
pop rcx
{$endif}
// особые варианты вызова
test dh, dh
jnz @std_look_adv_size
@mode_add_m8r8:
mov bh, dl
{$ifdef CPUX86}
push offset @finalize_add_m8r8
{$else .CPUX64}
lea r11, [@finalize_add_m8r8]
push r11
{$endif}
or edx, $0100
jmp AddSmartBinaryCmd
@std_look_adv_size:
cmp dl, 5
jne @std_call_proc
{$ifdef CPUX86}
push offset @finalize_leftover
{$else .CPUX64}
lea r11, [@finalize_leftover]
push r11
{$endif}
jmp AddSmartBinaryCmd
@std_call_proc:
// возвращаем ebx/rbx
{$ifdef CPUX86}
pop ebx
{$else .CPUX64}
pop rbx
{$endif}
jmp AddSmartBinaryCmd
@finalize_add_m8r8:
movzx ecx, bh
{$ifdef CPUX86}
movzx edx, word ptr [EAX].TOpcodeCmd.F.Size
sub edx, ecx
mov byte ptr [eax + TOpcodeCmdData.bytes + edx - 2], 0
{$else .CPUX64}
movzx edx, word ptr [RAX].TOpcodeCmd.F.Size
sub edx, ecx
mov byte ptr [rax + TOpcodeCmdData.bytes + rdx - 2], 0
{$endif}
add edx, ecx
cmp ecx, 5
je @fill_leftover
{$ifdef CPUX86}
pop ebx
{$else .CPUX64}
pop rbx
{$endif}
ret
@finalize_leftover:
{$ifdef CPUX86}
movzx edx, word ptr [EAX].TOpcodeCmd.F.Size
{$else .CPUX64}
movzx edx, word ptr [RAX].TOpcodeCmd.F.Size
{$endif}
@fill_leftover:
{$ifdef CPUX86}
mov [eax + TOpcodeCmdData.bytes + edx - 1], bl
pop ebx
{$else .CPUX64}
mov [rax + TOpcodeCmdData.bytes + rdx - 1], bl
pop rbx
{$endif}
end;
{$endif}
// два параметра: reg, addr или addr, reg. Направление определяется по опкоду
// например add esi, [ebp-$14] или xchg [offset variable + ecx*2 + 6], dx
procedure TOpcodeBlock_Intel.PRE_cmd_reg_addr(const opcode_reg: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// небольшое убыстрение для стандартных случаев
// или обычный вызов
if (addr.offset.Kind = ckValue) then
begin
{$ifdef OPCODE_TEST}
test_intel_address(addr, opcode_reg and flag_x64 <> 0, P.Proc);
{$endif}
cmd_reg_addr_value(opcode_reg, addr{$ifdef OPCODE_MODES},cmd{$endif});
end else
diffcmd_addr(opcode_reg, addr, cmd_reg_addr_value{$ifdef OPCODE_MODES},cmd{$endif});
end;
// три параметра: ptr, addr, const_32
// например cmp byte ptr [eax+ebx*2-12], 0 или sbb qword ptr [r12 + rdx], $17
// участвуют так же сдвиги: rcl,rcr,rol,ror,sal,sar,shl,shr
function TOpcodeBlock_Intel.cmd_ptr_addr_const_value(const opcode_ptr: integer; const addr: TOpcodeAddress; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
{$ifndef OPCODE_FAST}
var
X, Y: integer;
offset, left_over_info: integer;
Dest: pinteger;
value: integer;
// cmd + PtrToStr() + ptr адрес, %d | %s
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
buffer: TOpcodeTextBuffer;
const_value: PShortString;
str_ptr: PShortString;
begin
buffer.IntelAddress(opcode_ptr, addr);
if (opcode_ptr and flag_extra <> 0) and (byte(opcode_ptr shr 8) <> $D2) then const_value := PShortString(@STR_CL)
else const_value := buffer.Const32(v_const, 1);
if (false{!}) then str_ptr := PShortString(@STR_NULL)
else str_ptr := buffer.SizePtr(opcode_ptr, 1 + ord(pointer(const_value) <> @STR_CL));
// cmd ptr addr, cl/const
Result := AddCmdText('%s %s%s, %s', [cmd, str_ptr^, buffer.value.S, const_value^]);
end;
{$endif}
begin
{$ifdef OPCODE_MODES}
value := v_const.Value;
if (v_const.Kind <> ckValue) then value := low(integer);
{$else}
value := v_const;
{$endif}
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end;
{$endif}
X := ptr_intel_info[size_ptr(opcode_ptr)];
Y := addr.IntelInspect(opcode_ptr);
// размер константы и дополнительные вариации команды
if (opcode_ptr and flag_extra <> 0) then
begin
// сдвиги: rcl,rcr,rol,ror,sal,sar,shl,shr
X := X and $ffffff00;
if (byte(opcode_ptr shr 8) <> $D2{cmd addr, cl}) then
begin
if (value = 1) then X := X + $1000 {C0-->D0}
else X := X + 1{value_size = 1};
end;
end else
begin
// стандартный случай: adc,add,and,cmp,mov,or,sbb,sub,test,xor
if (byte(X) <> 1) then
begin
if (byte(opcode_ptr shr 8) = $80{не mov/test}) and (value >= -128) and (value <= 127) then
begin
X := (X and $ffffff00) or $0201;
end else
if (byte(X) <> 2) then
begin
X := (X and $ffffff00) or 4;
end;
end;
end;
// offset, sib, длинна value+sib
offset := addr.offset.Value;
left_over_info := (X and $ff) shl 16;
X := X + (Y and $0f{длинна оffset});
if (Y and $f0 <> 0{sib}) then
begin
if (Y and $0f = 4) then
begin
left_over_info := left_over_info + (offset shr 24) + $010100
end;
offset := (offset shl 8) or ((Y shr 8) and $ff);
X := X + 1;
end;
// опкод и смещение в адресе
X := (opcode_ptr and intel_opcode_mask) or X or (Y and integer($ffff0000));
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and ((addr.offset.Kind <> ckValue) or (v_const.Kind <> ckValue)) then
begin
FillAsText();
// ручная корректировка Min (константа)
value := 0;
if (v_const.Kind = ckCondition) then
begin
if (opcode_ptr and flag_extra <> 0) then
begin
// для сдвиговых
if (byte(opcode_ptr shr 8) <> $D2{imm8}) then value := 1;
end else
if (byte(opcode_ptr shr 8) = $80) then
begin
// не mov/test
case size_ptr(opcode_ptr) of
byte_ptr: {imm_size = 1 byte only};
word_ptr: begin
// imm_size = 1 || 2 bytes
value := 1;
end;
else
// imm_size = 1 || 4 bytes
value := 3;
end;
end;
end;
// MinMax с учётом ручной корректировки Min
Result.F.HybridSize_MinMax := HybridSize_MinMax(opcode_ptr, X, @addr)-value;
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, offset);
// "вытесненный" байт offset и value
Dest := pinteger(@POpcodeCmdData(Result).Bytes[Result.Size - (left_over_info shr 16)]);
if (left_over_info and $ff00 <> 0) then
begin
Dest^ := left_over_info;
System.Inc(NativeInt(Dest));
end;
Dest^ := value;
end;
end;
{$else}
asm
// начало (перед вызовом TOpcodeAddress.IntelInspect)
{$ifdef CPUX86}
push ebx // буфер
mov ebp, v_const // value
push eax // self
push edx // opcode_ptr
push [ECX + TOpcodeAddress_offset + TOpcodeConst.F.Value] // offset
mov eax, ecx // addr as Self
{$else .CPUX64}
push rbp
push rbx // буфер
mov rbp, r9 // value
mov eax, [r8 + TOpcodeAddress_offset + TOpcodeConst.F.Value]
push rcx // self
push rdx // opcode_ptr
push rax // offset
mov rcx, r8 // addr as Self
{$endif}
mov ebx, edx
call TOpcodeAddress.IntelInspect
// eax - Y, ebx - opcode_ptr, ecx - буфер
// X(edx) := ptr_intel_info[size_ptr(opcode_ptr)];
movzx edx, bl
test ebx, flag_extra
{$ifdef CPUX86}
mov edx, [offset ptr_intel_info + edx*4]
{$else .CPUX64}
lea rcx, [ptr_intel_info]
mov edx, [rcx + rdx*4]
{$endif}
// размер константы и дополнительные вариации команды
// для стандартных команд и для сдвигов
jz @cmd_std
@cmd_shift:
and edx, $ffffff00
cmp bh, $D2
je @cmd_done
cmp ebp, 1
{$ifdef CPUX86}
lea ecx, [edx+$1000]
lea edx, [edx+1]
{$else .CPUX64}
lea rcx, [rdx+$1000]
lea rdx, [rdx+1]
{$endif}
cmove edx, ecx
jmp @cmd_done
@cmd_std:
cmp dl, 1
{$ifdef CPUX86}
lea ecx, [ebp+128]
{$else .CPUX64}
lea rcx, [rbp+128]
{$endif}
je @cmd_done
cmp ecx, 255
ja @cmd_std_2_4
cmp bh, $80
jne @cmd_std_2_4
@cmd_std_1:
and edx, $ffffff00
or edx, $0201
jmp @cmd_done
@cmd_std_2_4:
cmp dl, 2
je @cmd_done
and edx, $ffffff00
or edx, 4
@cmd_done:
// offset, sib, длинна value+sib
mov ecx, eax
movzx ebx, dl
and ecx, $f
shl ebx, 16
test eax, $f0
{$ifdef CPUX86}
lea edx, [edx+ecx]
{$else .CPUX64}
lea rdx, [rdx+rcx]
{$endif}
jz @sib_no
@sib_using:
cmp ecx, 4
{$ifdef CPUX86}
pop ecx
{$else .CPUX64}
pop rcx
{$endif}
jne @sib_std
ror ecx, 24
mov bl, cl
rol ecx, 24
add ebx, $010100
@sib_std:
shl ecx, 8
inc edx
mov cl, ah
jmp @sib_done
@sib_no:
{$ifdef CPUX86}
pop ecx
{$else .CPUX64}
pop rcx
{$endif}
@sib_done:
// opcode_ptr - [esp/rsp], Y - eax, X - edx, offset - ecx, left_over_info - ebx
// вызов
and eax, $ffff0000
or edx, eax
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
pop rax
mov r8, rcx
{$endif}
and eax, intel_opcode_mask
or edx, eax
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
pop rcx
{$endif}
call AddSmartBinaryCmd
// Dest := pinteger(@Result.Data.Bytes[Result.Size - (left_over_info shr 16)]);
// if (left_over_info and $ff00 <> 0) then ...
mov ecx, ebx
{$ifdef CPUX86}
movzx edx, word ptr [EAX].TOpcodeCmd.F.Size
{$else .CPUX64}
movzx edx, word ptr [RAX].TOpcodeCmd.F.Size
{$endif}
shr ecx, 16
{$ifdef CPUX86}
neg ecx
{$else .CPUX64}
neg rcx
{$endif}
test bh, bh
{$ifdef CPUX86}
lea edx, [TOpcodeCmdData.bytes + edx+ecx]
{$else .CPUX64}
lea rdx, [TOpcodeCmdData.bytes + rdx+rcx]
{$endif}
jz @fill_value
@fill_over_byte:
{$ifdef CPUX86}
mov [eax + edx], ebx
{$else .CPUX64}
mov [rax + rdx], ebx
{$endif}
inc edx
@fill_value:
{$ifdef CPUX86}
mov [eax + edx], ebp
{$else .CPUX64}
mov [rax + rdx], ebp
{$endif}
// возврат ebx/rbx
{$ifdef CPUX86}
pop ebx
{$else .CPUX64}
pop rbx
pop rbp
{$endif}
end;
{$endif}
// три параметра: ptr, addr, const_32
// например cmp byte ptr [eax+ebx*2-12], 0 или sbb qword ptr [r12 + rdx], $17
// участвуют так же сдвиги: rcl,rcr,rol,ror,sal,sar,shl,shr
procedure TOpcodeBlock_Intel.PRE_cmd_ptr_addr_const(const opcode_ptr: integer; const addr: TOpcodeAddress; const v_const: const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// небольшое убыстрение для стандартных случаев
// или обычный вызов
if (addr.offset.Kind = ckValue) and (v_const.Kind = ckValue) then
begin
{$ifdef OPCODE_TEST}
test_intel_address(addr, opcode_ptr and flag_x64 <> 0, P.Proc);
// проверку для ckValue-константы делать не нужно
{$endif}
cmd_ptr_addr_const_value(opcode_ptr, addr,{$ifdef OPCODE_MODES}v_const,cmd{$else}v_const.Value{$endif});
end else
diffcmd_addr_const(opcode_ptr, addr, v_const, cmd_ptr_addr_const_value{$ifdef OPCODE_MODES},cmd{$endif});
end;
// три параметра: reg, reg, const_32/cl
// только команды shld | shrd | imul
// reg1 - младший байт, reg2 смещён на 16 бит
function TOpcodeBlock_Intel.cmd_reg_reg_const_value(const base_reg1_opcode_reg2: integer; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
const
opcode_mask = integer(intel_opcode_mask and $ff00ffff);
modrm_reg_reg = $C00000;
modrm_src_mask = integer(intel_modrm_src_mask and $ffff00ff);
modrm_dest_mask = integer(intel_modrm_dest_mask and $ffff00ff);
{$ifndef OPCODE_FAST}
var
X, Y: integer;
imm_size: integer;
value: integer;
reg1_opcode_reg2: integer;
// cmd регистр, регистр, cl | %d | %s
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
buffer: TOpcodeTextBuffer;
const_value: PShortString;
begin
if (byte(base_reg1_opcode_reg2 shr 8) in [$A5{shld_cl},$AD{shrd_cl}]) then const_value := PShortString(@STR_CL)
else const_value := buffer.Const32(v_const);
Result := AddCmdText('%s %s, %s, %s', [cmd, reg_intel_names[byte(base_reg1_opcode_reg2)], reg_intel_names[byte(base_reg1_opcode_reg2 shr 16)], const_value^]);
end;
{$endif}
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end;
{$endif}
reg1_opcode_reg2 := base_reg1_opcode_reg2;
{$ifdef OPCODE_MODES}
value := v_const.Value;
if (v_const.Kind <> ckValue) then value := low(integer);
{$else}
value := v_const;
{$endif}
// определяемся с параметрами
X := reg_intel_info[byte(reg1_opcode_reg2)];
Y := reg_intel_info[byte(reg1_opcode_reg2 shr 16)];
// размер константы, коррекция X/Y
if (reg1_opcode_reg2 and flag_extra <> 0) then
begin
// imul (src и dest почему-то меняются местами)
imm_size := X;
X := Y;
Y := imm_size;
if (value >= -128) and (value <= 127) then
begin
reg1_opcode_reg2 := reg1_opcode_reg2 or $0200;
imm_size := 1;
end else
if (byte(X) = 2) then imm_size := 2
else imm_size := 4;
end else
begin
// shld / shrd
// 1. для cl варианта - 0
imm_size := ((reg1_opcode_reg2 shr 8) xor 1) and 1;
end;
// вызов
X := modrm_reg_reg or (reg1_opcode_reg2 and opcode_mask)
or (X and modrm_dest_mask) or (Y and modrm_src_mask)
or imm_size;
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (v_const.Kind <> ckValue) then
begin
FillAsText();
// ручная корректировка Min (константа)
value := 0;
if (v_const.Kind = ckCondition) then
begin
if (base_reg1_opcode_reg2 and flag_extra <> 0) then
begin
// imul (трёхоперандный не работает для 8-битных регистров)
if (X and flag_word_ptr <> 0) then value := 1
else value := 3;
end else
begin
// shld / shrd
if not (byte(base_reg1_opcode_reg2 shr 8) in [$A5{shld_cl},$AD{shrd_cl}]) then value := 1;
end;
end;
// MinMax с учётом ручной корректировки Min
Result.F.HybridSize_MinMax := HybridSize_MinMax(base_reg1_opcode_reg2, X, nil)-value;
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, value);
end;
end;
{$else}
const
// чтобы в X хранилось также imm_size
modrm_dest_imm_mask = modrm_dest_mask or $ff;
asm
// начало
{$ifdef CPUX86}
push esi
push ebx
{$else .CPUX64}
xchg rsi, r9
xchg rbx, r10
{$endif}
// определяемся с параметрами
// ebx - X, esi - Y
{$ifdef CPUX64}
lea r11, [reg_intel_info]
{$endif}
mov esi, edx
movzx ebx, dl
shr esi, 16
{$ifdef CPUX86}
mov ebx, [offset reg_intel_info + ebx*4]
{$else .CPUX64}
mov ebx, [r11 + rbx*4]
{$endif}
and esi, $ff
{} test edx, flag_extra
{$ifdef CPUX86}
mov esi, [offset reg_intel_info + esi*4]
{$else .CPUX64}
mov esi, [r11 + rsi*4]
{$endif}
// размер константы, коррекция X/Y
// test edx, flag_extra
jz @cmd_shift
@cmd_imul:
// value += 128
{$ifdef CPUX86}
sub ecx, -128
{$else .CPUX64}
sub r8, -128
{$endif}
xchg ebx, esi
{$ifdef CPUX86}
cmp ecx, 255
{$else .CPUX64}
cmp r8, 255
{$endif}
ja @cmd_imul_2_4
// imm_size = 1
mov bl, 1
// value -= 128
{$ifdef CPUX86}
add ecx, -128
{$else .CPUX64}
add r8, -128
{$endif}
or edx, $0200
jmp @cmd_finish
@cmd_imul_2_4:
cmp bl, 2
{$ifdef CPUX86}
lea ecx, [ecx - 128]
{$else .CPUX64}
lea r8, [r8 - 128]
{$endif}
je @cmd_finish
mov bl, 4
jmp @cmd_finish
@cmd_shift:
// cl (0) или const (1)
test dh, 1
setz bl
@cmd_finish:
// вызов
and edx, opcode_mask
and ebx, modrm_dest_imm_mask
and esi, modrm_src_mask
{$ifdef CPUX86}
lea edx, [edx + ebx + modrm_reg_reg]
{$else .CPUX64}
lea rdx, [rdx + rbx + modrm_reg_reg]
{$endif}
or edx, esi
{$ifdef CPUX86}
pop ebx
pop esi
{$else .CPUX64}
xchg rbx, r10
xchg rsi, r9
{$endif}
jmp AddSmartBinaryCmd
end;
{$endif}
// три параметра: reg, reg, const_32/cl
// только команды shld | shrd | imul
// reg1 - младший байт, reg2 смещён на 16 бит
procedure TOpcodeBlock_Intel.PRE_cmd_reg_reg_const(const reg1_opcode_reg2: integer; const v_const: const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// небольшое убыстрение для стандартных случаев
// или обычный вызов
if (v_const.Kind = ckValue) then
begin
// проверку для ckValue делать не нужно
cmd_reg_reg_const_value(reg1_opcode_reg2, {$ifdef OPCODE_MODES}v_const,cmd{$else}v_const.Value{$endif});
end else
diffcmd_const32(reg1_opcode_reg2, v_const, cmd_reg_reg_const_value{$ifdef OPCODE_MODES},cmd{$endif});
end;
// три параметра(shld,shrd): addr, reg, const_32/cl
// или для imul: reg, addr, const_32
function TOpcodeBlock_Intel.cmd_addr_reg_const_value(const base_opcode_reg: integer; const addr: TOpcodeAddress; const v_const: opused_const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
const
modrm_src_mask = integer(intel_modrm_src_mask and (not intel_nonbyte_mask)) or $ff;
{$ifndef OPCODE_FAST}
var
X, Y: integer;
offset, left_over_info: integer;
Dest: pinteger;
opcode_reg: integer;
value: integer;
// cmd адрес, регистр, cl | %d | %s
// или
// imul регистр, адрес, %d | %s
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
reg_name: pansichar;
buffer: TOpcodeTextBuffer;
const_value: PShortString;
begin
reg_name := reg_intel_names[byte(base_opcode_reg)];
buffer.IntelAddress(base_opcode_reg, addr);
if (base_opcode_reg and flag_extra = 0) and (byte(base_opcode_reg shr 8) in [$A5{shld_cl},$AD{shrd_cl}]) then const_value := PShortString(@STR_CL)
else const_value := buffer.Const32(v_const, 1);
if (base_opcode_reg and flag_extra = 0) then
begin
// cmd адрес, регистр, cl | %d | %s
Result := AddCmdText('%s %s, %s, %s', [cmd, buffer.value.S, reg_name, const_value^]);
end else
begin
// imul регистр, адрес, %d | %s
Result := AddCmdText('%s %s, %s, %s', [cmd, reg_name, buffer.value.S, const_value^]);
end;
end;
{$endif}
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end;
{$endif}
opcode_reg := base_opcode_reg;
{$ifdef OPCODE_MODES}
value := v_const.Value;
if (v_const.Kind <> ckValue) then value := low(integer);
{$else}
value := v_const;
{$endif}
X := reg_intel_info[byte(opcode_reg)] and modrm_src_mask;
Y := addr.IntelInspect(opcode_reg);
// размер константы
if (opcode_reg and flag_extra <> 0) then
begin
// imul (src и dest почему-то меняются местами)
if (value >= -128) and (value <= 127) then
begin
opcode_reg := opcode_reg or $0200;
X := (X and $ffffff00) + 1;
end else
if (byte(X) <> 2) then X := (X and $ffffff00) + 4;
end else
begin
// shld / shrd
// 1. для cl варианта - 0
X := (X and integer($ffffff00)) + (((opcode_reg shr 8) xor 1) and 1);
end;
// offset, sib, длинна value+sib
offset := addr.offset.Value;
left_over_info := (X and $ff) shl 16;
X := X + (Y and $0f{длинна оffset});
if (Y and $f0 <> 0{sib}) then
begin
if (Y and $0f = 4) then
begin
left_over_info := left_over_info + (offset shr 24) + $010100
end;
offset := (offset shl 8) or ((Y shr 8) and $ff);
X := X + 1;
end;
// опкод и смещение в адресе
X := (opcode_reg and intel_opcode_mask) or X or (Y and integer($ffff0000));
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and ((addr.offset.Kind <> ckValue) or (v_const.Kind <> ckValue)) then
begin
FillAsText();
// ручная корректировка Min (константа)
value := 0;
if (v_const.Kind = ckCondition) then
begin
if (base_opcode_reg and flag_extra <> 0) then
begin
// imul (трёхоперандный не работает для 8-битных регистров)
if (X and flag_word_ptr <> 0) then value := 1
else value := 3;
end else
begin
// shld / shrd
if not (byte(base_opcode_reg shr 8) in [$A5{shld_cl},$AD{shrd_cl}]) then value := 1;
end;
end;
// MinMax с учётом ручной корректировки Min
Result.F.HybridSize_MinMax := HybridSize_MinMax(base_opcode_reg, X, @addr)-value;
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, offset);
// "вытесненный" байт offset и value
Dest := pinteger(@POpcodeCmdData(Result).Bytes[Result.Size - (left_over_info shr 16)]);
if (left_over_info and $ff00 <> 0) then
begin
Dest^ := left_over_info;
System.Inc(NativeInt(Dest));
end;
Dest^ := value;
end;
end;
{$else}
asm
// начало (перед вызовом TOpcodeAddress.IntelInspect)
{$ifdef CPUX86}
push ebx // буфер
mov ebp, v_const // value
push eax // self
push edx // opcode_reg
push [ECX + TOpcodeAddress_offset + TOpcodeConst.F.Value] // offset
mov eax, ecx // addr as Self
{$else .CPUX64}
push rbp
push rbx // буфер
mov rbp, r9 // value
mov eax, [r8 + TOpcodeAddress_offset + TOpcodeConst.F.Value]
push rcx // self
push rdx // opcode_reg
push rax // offset
mov rcx, r8 // addr as Self
{$endif}
mov ebx, edx
call TOpcodeAddress.IntelInspect
// eax - Y, ebx - opcode_reg, ecx - буфер
// X := reg_intel_info[byte(opcode_reg)] and modrm_src_mask;
movzx edx, bl
{$ifdef CPUX86}
mov edx, [offset reg_intel_info + edx*4]
{$else .CPUX64}
lea rcx, [reg_intel_info]
mov edx, [rcx + rdx*4]
{$endif}
and edx, modrm_src_mask
// размер константы
test ebx, flag_extra
{$ifdef CPUX86}
lea ecx, [ebp+128]
{$else .CPUX64}
lea rcx, [rbp+128]
{$endif}
jz @cmd_shift
@cmd_imul:
cmp ecx, 255
ja @cmd_imul_2_4
// imm_size = 1
mov dl, 1
{$ifdef CPUX86}
or byte ptr [esp+4+1], $02
{$else .CPUX64}
or byte ptr [rsp+8+1], $02
{$endif}
jmp @cmd_finish
@cmd_imul_2_4:
cmp dl, 2
je @cmd_finish
mov dl, 4
jmp @cmd_finish
@cmd_shift:
// cl (0) или const (1)
test bh, 1
setz dl
@cmd_finish:
// offset, sib, длинна value+sib
mov ecx, eax
movzx ebx, dl
and ecx, $f
shl ebx, 16
test eax, $f0
{$ifdef CPUX86}
lea edx, [edx+ecx]
{$else .CPUX64}
lea rdx, [rdx+rcx]
{$endif}
jz @sib_no
@sib_using:
cmp ecx, 4
{$ifdef CPUX86}
pop ecx
{$else .CPUX64}
pop rcx
{$endif}
jne @sib_std
ror ecx, 24
mov bl, cl
rol ecx, 24
add ebx, $010100
@sib_std:
shl ecx, 8
inc edx
mov cl, ah
jmp @sib_done
@sib_no:
{$ifdef CPUX86}
pop ecx
{$else .CPUX64}
pop rcx
{$endif}
@sib_done:
// opcode_ptr - [esp/rsp], Y - eax, X - edx, offset - ecx, left_over_info - ebx
// вызов
and eax, $ffff0000
or edx, eax
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
pop rax
mov r8, rcx
{$endif}
and eax, intel_opcode_mask
or edx, eax
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
pop rcx
{$endif}
call AddSmartBinaryCmd
// Dest := pinteger(@Result.Data.Bytes[Result.Size - (left_over_info shr 16)]);
// if (left_over_info and $ff00 <> 0) then ...
mov ecx, ebx
{$ifdef CPUX86}
movzx edx, word ptr [EAX].TOpcodeCmd.F.Size
{$else .CPUX64}
movzx edx, word ptr [RAX].TOpcodeCmd.F.Size
{$endif}
shr ecx, 16
{$ifdef CPUX86}
neg ecx
{$else .CPUX64}
neg rcx
{$endif}
test bh, bh
{$ifdef CPUX86}
lea edx, [TOpcodeCmdData.bytes + edx+ecx]
{$else .CPUX64}
lea rdx, [TOpcodeCmdData.bytes + rdx+rcx]
{$endif}
jz @fill_value
@fill_over_byte:
{$ifdef CPUX86}
mov [eax + edx], ebx
{$else .CPUX64}
mov [rax + rdx], ebx
{$endif}
inc edx
@fill_value:
{$ifdef CPUX86}
mov [eax + edx], ebp
{$else .CPUX64}
mov [rax + rdx], ebp
{$endif}
// возврат ebx/rbx
{$ifdef CPUX86}
pop ebx
{$else .CPUX64}
pop rbx
pop rbp
{$endif}
end;
{$endif}
// три параметра(shld,shrd): addr, reg, const_32/cl
// или для imul: reg, addr, const_32
procedure TOpcodeBlock_Intel.PRE_cmd_addr_reg_const(const opcode_reg: integer; const addr: TOpcodeAddress; const v_const: const_32{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// небольшое убыстрение для стандартных случаев
// или обычный вызов
if (addr.offset.Kind = ckValue) and (v_const.Kind = ckValue) then
begin
{$ifdef OPCODE_TEST}
test_intel_address(addr, opcode_reg and flag_x64 <> 0, P.Proc);
// проверку для ckValue-константы делать не нужно
{$endif}
cmd_addr_reg_const_value(opcode_reg, addr,{$ifdef OPCODE_MODES}v_const,cmd{$else}v_const.Value{$endif});
end else
diffcmd_addr_const(opcode_reg, addr, v_const, cmd_addr_reg_const_value{$ifdef OPCODE_MODES},cmd{$endif});
end;
// два параметра: reg, reg
// для movzx и movsx
function TOpcodeBlock_Intel.movszx_reg_reg(const opcode_reg: integer; v_reg: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
const
reg_mask = intel_modrm_src_mask and (not intel_nonbyte_mask);
v_reg_mask = intel_modrm_dest_mask and (not flag_word_ptr);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
Result := AddCmdText('%s %s, %s', [cmd, reg_intel_names[byte(opcode_reg)], reg_intel_names[byte(v_reg)]]);
exit;
end;
{$endif}
Result := AddSmartBinaryCmd(
(opcode_reg and intel_opcode_mask) or
(reg_intel_info[byte(opcode_reg)] and reg_mask) or
(reg_intel_info[byte(v_reg)] and v_reg_mask), 0);
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
push ebx
mov ecx, [offset reg_intel_info + ecx*4]
movzx ebx, dl
and ecx, v_reg_mask
mov ebx, [offset reg_intel_info + ebx*4]
and edx, intel_opcode_mask
and ebx, reg_mask
or edx, ecx
or edx, ebx
pop ebx
{$else .CPUX64}
movzx rax, r8b
lea r11, [reg_intel_info]
xchg rbx, r9
mov eax, [r11 + rax*4]
movzx ebx, dl
and eax, v_reg_mask
mov ebx, [r11 + rbx*4]
and edx, intel_opcode_mask
and ebx, reg_mask
or edx, eax
or edx, ebx
xchg rbx, r9
{$endif}
jmp AddSmartBinaryCmd
end;
{$endif}
// три параметра: reg, ptr, addr
// для movzx и movsx
function TOpcodeBlock_Intel.movszx_reg_ptr_addr_value(const reg_opcode_ptr: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
const
opcode_mask = intel_opcode_mask and integer($ff00ffff);
reg_mask = intel_modrm_src_mask and (not intel_nonbyte_mask);
ptr_mask = intel_modrm_dest_mask and (not flag_word_ptr);
{$ifndef OPCODE_FAST}
var
X, Y: integer;
offset, leftover: integer;
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
buffer: TOpcodeTextBuffer;
str_ptr: PShortString;
begin
buffer.IntelAddress(reg_opcode_ptr, addr);
if (false{!}) then str_ptr := PShortString(@STR_NULL)
else str_ptr := buffer.SizePtr(reg_opcode_ptr shr 16, 1);
Result := AddCmdText('%s %s, %s%s', [cmd,
reg_intel_names[byte(reg_opcode_ptr)],
str_ptr^, buffer.value.S]);
end;
{$endif}
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end;
{$endif}
// адрес, sib
Y := addr.IntelInspect(reg_opcode_ptr);
// общая информация
X := (reg_opcode_ptr and opcode_mask) or
(reg_intel_info[byte(reg_opcode_ptr)] and reg_mask) or
(ptr_intel_info[size_ptr(reg_opcode_ptr shr 16)] and ptr_mask);
// смещение, остаток (для sib)
leftover := 0;
offset := addr.offset.Value;
if (Y and $f0 <> 0) then
begin
leftover := offset shr 24;
offset := (offset shl 8) or ((Y shr 8) and $ff);
Y := (Y and $ffff000f)+1;
end;
// вызов
X := X or Y;
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (addr.offset.Kind <> ckValue) then
begin
FillAsText();
Result.F.HybridSize_MinMax := HybridSize_MinMax(reg_opcode_ptr, X, @addr);
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, offset);
// дополнительный байт
if (byte(Y) = 5) then
begin
POpcodeCmdData(Result).Bytes[Result.Size-1] := byte(leftover);
end;
end;
end;
{$else}
asm
// начало (перед вызовом TOpcodeAddress.IntelInspect)
{$ifdef CPUX86}
push ebx // буфер
push eax // self
push [ECX + TOpcodeAddress_offset + TOpcodeConst.F.Value] // offset
mov eax, ecx // addr as Self
{$else .CPUX64}
push rbx // буфер
push rcx // self
push [R8 + TOpcodeAddress_offset + TOpcodeConst.F.Value] // offset
mov rcx, r8 // addr as Self
{$endif}
mov ebx, edx
call TOpcodeAddress.IntelInspect
// X := (reg_opcode_ptr and opcode_mask) or
// (reg_intel_info[byte(reg_opcode_ptr)] and reg_mask) or
// (ptr_intel_info[size_ptr(reg_opcode_ptr shr 16)] and ptr_mask);
mov edx, ebx
movzx ecx, bl
shr ebx, 16
and edx, opcode_mask
movzx ebx, bl
{$ifdef CPUX86}
mov ecx, [offset reg_intel_info + ecx*4]
mov ebx, [offset ptr_intel_info + ebx*4]
{$else .CPUX64}
lea r10, [reg_intel_info]
lea r11, [ptr_intel_info]
mov ecx, [r10 + rcx*4]
mov ebx, [r11 + rbx*4]
{$endif}
and ecx, reg_mask
and ebx, ptr_mask
or edx, ecx
or edx, ebx
// offset, sib, длинна value+sib
// (в стеке: offset, self, ebx/rbx). eax - Y. edx - X
test al, $f0
{$ifdef CPUX86}
pop ecx
{$else .CPUX64}
pop rcx
{$endif}
jz @sib_done
mov ebx, ecx
shl ecx, 8
inc eax
shr ebx, 24
mov cl, ah
and eax, $ffff000f
@sib_done:
{$ifdef CPUX64}
xchg r8, rcx
{$endif}
or edx, eax
// 2 варианта вызова: обычный и с дописыванием байта
cmp al, 5
je @call_over_byte
@call_std:
{$ifdef CPUX86}
pop eax
pop ebx
{$else .CPUX64}
pop rcx
pop rbx
{$endif}
jmp AddSmartBinaryCmd
@call_over_byte:
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
pop rcx
{$endif}
call AddSmartBinaryCmd
mov ecx, ebx
{$ifdef CPUX86}
movzx edx, word ptr [EAX].TOpcodeCmd.F.Size
pop ebx
mov [EAX + TOpcodeCmdData.bytes + edx - 1], cl
{$else .CPUX64}
movzx edx, word ptr [RAX].TOpcodeCmd.F.Size
pop rbx
mov [RAX + TOpcodeCmdData.bytes + rdx - 1], cl
{$endif}
end;
{$endif}
// три параметра: reg, ptr, addr
// для movzx и movsx
procedure TOpcodeBlock_Intel.PRE_movszx_reg_ptr_addr(const reg_opcode_ptr: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// небольшое убыстрение для стандартных случаев
// или обычный вызов
if (addr.offset.Kind = ckValue) then
begin
{$ifdef OPCODE_TEST}
test_intel_address(addr, reg_opcode_ptr and flag_x64 <> 0, P.Proc);
{$endif}
movszx_reg_ptr_addr_value(reg_opcode_ptr, addr{$ifdef OPCODE_MODES},cmd{$endif});
end else
diffcmd_addr(reg_opcode_ptr, addr, movszx_reg_ptr_addr_value{$ifdef OPCODE_MODES},cmd{$endif});
end;
// команды setcc r8 | cmovcc reg_wd, reg_wd
// в параметрых: флаги extra и x64 | v_reg/0 | cc | reg
// extra - cmovcc
function TOpcodeBlock_Intel.setcmov_cc_regs(const params: integer{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
const
CMOVCC_OPCODE = flag_0f or ($C040 shl 8);
SETCC_OPCODE = flag_0f or ($C090 shl 8);
modrm_src_mask = intel_modrm_src_mask and (not intel_nonbyte_mask);
modrm_dest_mask = intel_modrm_dest_mask and (not intel_nonbyte_mask);
{$ifndef OPCODE_FASTEST}
var
X: integer;
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
if (params and flag_extra <> 0) then
begin
// cmovcc
Result := AddCmdText('%s%s %s, %s', [cmd, cc_intel_names[byte(params shr 8)]+2,
reg_intel_names[byte(params)], reg_intel_names[byte(params shr 16)]]);
end else
begin
// setcc
Result := AddCmdText('%s%s %s', [cmd, cc_intel_names[byte(params shr 8)]+2,
reg_intel_names[byte(params)]]);
end;
exit;
end;
{$endif}
if (params and flag_extra <> 0) then
begin
// cmovcc
X := CMOVCC_OPCODE or
(reg_intel_info[byte(params)] and modrm_src_mask) or
(reg_intel_info[byte(params shr 16)] and modrm_dest_mask) or
(ord(cc_intel_info[intel_cc(params shr 8)]) shl 8);
end else
begin
// setcc
X := SETCC_OPCODE or
(reg_intel_info[byte(params)] and modrm_dest_mask) or
(ord(cc_intel_info[intel_cc(params shr 8)]) shl 8);
end;
// добавляем
Result := AddSmartBinaryCmd(X, 0);
end;
{$else}
const
OFFSETED_FLAG = flag_extra shr 16;
asm
{$ifdef CPUX86}
push ebx
{$else .CPUX64}
xchg rax, rcx
xchg rbx, r8
lea r10, [cc_intel_info]
lea r11, [reg_intel_info]
{$endif}
movzx ebx, dh
movzx ecx, dl
shr edx, 16
{$ifdef CPUX86}
movzx ebx, byte ptr [cc_intel_info + ebx]
test edx, OFFSETED_FLAG
mov ecx, [offset reg_intel_info + ecx*4]
{$else .CPUX64}
movzx ebx, byte ptr [r10 + rbx]
test edx, OFFSETED_FLAG
mov ecx, [r11 + rcx*4]
{$endif}
jz @setcc
@cmovcc:
movzx edx, dl
shl ebx, 8
{$ifdef CPUX86}
mov edx, [offset reg_intel_info + edx*4]
{$else .CPUX64}
mov edx, [r11 + rdx*4]
{$endif}
and ecx, modrm_src_mask
and edx, modrm_dest_mask
lea ecx, [ebx + ecx + CMOVCC_OPCODE]
or edx, ecx
jmp @call
@setcc:
and ecx, modrm_dest_mask
shl ebx, 8
lea edx, [ecx + ebx + SETCC_OPCODE]
@call:
{$ifdef CPUX86}
pop ebx
{$else .CPUX64}
xchg rax, rcx
xchg rbx, r8
{$endif}
jmp AddSmartBinaryCmd
end;
{$endif}
// команды setcc addr8 | cmovcc reg_wd, addr
// в параметрых: флаги extra и x64 | 0 | 0/reg для movcc | cc
// extra - cmovcc
function TOpcodeBlock_Intel.setcmov_cc_addr_value(const params: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif}): POpcodeCmd;
const
CMOVCC_OPCODE = flag_0f or ($40 shl 8);
SETCC_OPCODE = flag_0f or ($90 shl 8);
reg_mask = intel_modrm_src_mask and (not intel_nonbyte_mask);
{$ifndef OPCODE_FAST}
var
X, Y: integer;
offset, leftover: integer;
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
cc_name: pansichar;
buffer: TOpcodeTextBuffer;
begin
cc_name := cc_intel_names[byte(params)]+2;
buffer.IntelAddress(params, addr);
if (params and flag_extra <> 0) then
begin
// cmovcc
Result := AddCmdText('%s%s %s, %s', [cmd, cc_name, reg_intel_names[byte(params shr 8)], buffer.value.S]);
end else
begin
// setcc
Result := AddCmdText('%s%s %s', [cmd, cc_name, buffer.value.S]);
end;
end;
{$endif}
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end;
{$endif}
// общая информация
X := (ord(cc_intel_info[intel_cc(params)]) shl 8);
if (params and flag_extra <> 0) then
begin
// cmovcc
X := X or CMOVCC_OPCODE or (reg_intel_info[byte(params shr 8)] and reg_mask);
end else
begin
// setcc
X := X or SETCC_OPCODE;
end;
// адрес, sib
Y := addr.IntelInspect(params);
// смещение, остаток (для sib)
leftover := 0;
offset := addr.offset.Value;
if (Y and $f0 <> 0) then
begin
leftover := offset shr 24;
offset := (offset shl 8) or ((Y shr 8) and $ff);
Y := (Y and $ffff000f)+1;
end;
// вызов
X := X or Y;
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (addr.offset.Kind <> ckValue) then
begin
FillAsText();
Result.F.HybridSize_MinMax := HybridSize_MinMax(params, X, @addr);
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, offset);
// дополнительный байт
if (byte(Y) = 5) then
begin
POpcodeCmdData(Result).Bytes[Result.Size-1] := byte(leftover);
end;
end;
end;
{$else}
asm
// начало (перед вызовом TOpcodeAddress.IntelInspect)
{$ifdef CPUX86}
push ebx // буфер
push eax // self
push [ECX + TOpcodeAddress_offset + TOpcodeConst.F.Value] // offset
mov eax, ecx // addr as Self
{$else .CPUX64}
push rbx // буфер
push rcx // self
push [R8 + TOpcodeAddress_offset + TOpcodeConst.F.Value] // offset
mov rcx, r8 // addr as Self
{$endif}
mov ebx, edx
call TOpcodeAddress.IntelInspect
// общая информация X := (ord(cc_intel_info[intel_cc(params)]) shl 8);
// if (params and flag_extra <> 0) then cmovcc/setcc
movzx edx, bl
movzx ecx, bh
test ebx, flag_extra
{$ifdef CPUX86}
movzx edx, byte ptr [cc_intel_info + edx]
{$else .CPUX64}
lea r9, [cc_intel_info]
movzx edx, byte ptr [r9 + rdx]
{$endif}
jz @setcc
@cmovcc:
//X := (X shl 8) or CMOVCC_OPCODE or (reg_intel_info[byte(params shr 8)] and reg_mask);
{$ifdef CPUX86}
mov ecx, [offset reg_intel_info + ecx*4]
{$else .CPUX64}
lea r9, [reg_intel_info]
mov ecx, [r9 + rcx*4]
{$endif}
shl edx, 8
and ecx, reg_mask
{$ifdef CPUX86}
lea edx, [edx + ecx + CMOVCC_OPCODE]
{$else .CPUX64}
lea rdx, [rdx + rcx + CMOVCC_OPCODE]
{$endif}
jmp @cc_done
@setcc:
shl edx, 8
or edx, SETCC_OPCODE
@cc_done:
// offset, sib, длинна value+sib
// (в стеке: offset, self, ebx/rbx). eax - Y. edx - X
test al, $f0
{$ifdef CPUX86}
pop ecx
{$else .CPUX64}
pop rcx
{$endif}
jz @sib_done
mov ebx, ecx
shl ecx, 8
inc eax
shr ebx, 24
mov cl, ah
and eax, $ffff000f
@sib_done:
{$ifdef CPUX64}
xchg r8, rcx
{$endif}
or edx, eax
// 2 варианта вызова: обычный и с дописыванием байта
cmp al, 5
je @call_over_byte
@call_std:
{$ifdef CPUX86}
pop eax
pop ebx
{$else .CPUX64}
pop rcx
pop rbx
{$endif}
jmp AddSmartBinaryCmd
@call_over_byte:
{$ifdef CPUX86}
pop eax
{$else .CPUX64}
pop rcx
{$endif}
call AddSmartBinaryCmd
mov ecx, ebx
{$ifdef CPUX86}
movzx edx, word ptr [EAX].TOpcodeCmd.F.Size
pop ebx
mov [EAX + TOpcodeCmdData.bytes + edx - 1], cl
{$else .CPUX64}
movzx edx, word ptr [RAX].TOpcodeCmd.F.Size
pop rbx
mov [RAX + TOpcodeCmdData.bytes + rdx - 1], cl
{$endif}
end;
{$endif}
// команды setcc addr8 | cmovcc reg_wd, addr
procedure TOpcodeBlock_Intel.PRE_setcmov_cc_addr(const params: integer; const addr: TOpcodeAddress{$ifdef OPCODE_MODES};const cmd: ShortString{$endif});
begin
{$ifdef OPCODE_TEST}
// todo проверки
{$endif}
// небольшое убыстрение для стандартных случаев
// или обычный вызов
if (addr.offset.Kind = ckValue) then
begin
{$ifdef OPCODE_TEST}
test_intel_address(addr, params and flag_x64 <> 0, P.Proc);
{$endif}
setcmov_cc_addr_value(params, addr{$ifdef OPCODE_MODES},cmd{$endif});
end else
diffcmd_addr(params, addr, setcmov_cc_addr_value{$ifdef OPCODE_MODES},cmd{$endif});
end;
procedure TOpcodeBlock_Intel.aaa;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.aad;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.aam;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.aas;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.daa;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.das;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.f2xm1;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fabs;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fadd(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fadd(d, s: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.faddp(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fchs;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fclex;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fcmov(cc: intel_cc; st_dest: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fcom(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fcom(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fcomi(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fcomip(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fcomp(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fcomp(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fcompp;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fcos;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fdecstp;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fdiv(d, s: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fdiv(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fdivp(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fdivr(d, s: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fdivr(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fdivrp(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.ffree;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fiadd(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.ficom(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.ficomp(ptr: size_ptr;
const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fidiv(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fidivr(ptr: size_ptr;
const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fild(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fimul(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fincstp;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fist(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fistp(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fisub(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fisubr(ptr: size_ptr;
const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fld(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fld(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fld1;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fldl2e;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fldl2t;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fldlg2;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fldln2;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fldpi;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fldz;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fmul(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fmul(d, s: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fmulp(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fnclex;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fnop;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fpatan;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fprem;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fprem1;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fptan;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.frndint;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.frstor;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fscale;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fsin;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fsincos;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fsqrt;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fst(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fst(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fstp(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fstp(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fstsw_ax;
begin
cmd_single($E0DF9B{$ifdef OPCODE_MODES}, 'fstsw ax'{$endif});
end;
procedure TOpcodeBlock_Intel.fnstsw_ax;
begin
cmd_single($E0DF{$ifdef OPCODE_MODES}, 'fnstsw ax'{$endif});
end;
procedure TOpcodeBlock_Intel.fsub(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fsub(d, s: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fsubp(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fsubr(d, s: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fsubr(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fsubrp(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.ftst;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fucom(ptr: size_ptr; const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fucom(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fucomi(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fucomip(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fucomp(ptr: size_ptr;
const addr: address_x86);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fucomp(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fucompp;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fwait;
begin
raise_not_realized();
end;
// cmp b/w/d/(q)
procedure TOpcodeBlock_Intel.cmpsb(reps: intel_rep=REP_SINGLE);
const
OPCODE = $A6{cmpsb};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_cmpsb{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.cmpsw(reps: intel_rep=REP_SINGLE);
const
OPCODE = $A766{cmpsw};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_cmpsw{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.cmpsd(reps: intel_rep=REP_SINGLE);
const
OPCODE = $A7{cmpsd};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_cmpsd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
// in b/w/d/(q)
procedure TOpcodeBlock_Intel.insb(reps: intel_rep=REP_SINGLE);
const
OPCODE = $6C{insb};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_insb{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.insw(reps: intel_rep=REP_SINGLE);
const
OPCODE = $6D66{insw};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_insw{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.insd(reps: intel_rep=REP_SINGLE);
const
OPCODE = $6D{insd};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_insd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
// sca b/w/d/(q)
procedure TOpcodeBlock_Intel.scasb(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AE{scasb};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_scasb{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.scasw(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AF66{scasw};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_scasw{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.scasd(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AF{scasd};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_scasd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
// sto b/w/d/(q)
procedure TOpcodeBlock_Intel.stosb(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AA{stosb};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_stosb{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.stosw(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AB66{stosw};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_stosw{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.stosd(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AB{stosd};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_stosd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
// lod b/w/d/(q)
procedure TOpcodeBlock_Intel.lodsb(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AC{lodsb};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_lodsb{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.lodsw(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AD66{lodsw};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_lodsw{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.lodsd(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AD{lodsd};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_lodsd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
// mov b/w/d/(q)
procedure TOpcodeBlock_Intel.movsb(reps: intel_rep=REP_SINGLE);
const
OPCODE = $A4{movsb};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_movsb{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.movsw(reps: intel_rep=REP_SINGLE);
const
OPCODE = $A566{movsw};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_movsw{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.movsd(reps: intel_rep=REP_SINGLE);
const
OPCODE = $A5{movsd};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_movsd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_Intel.fxam;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fxch(st: index8);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fxtract;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fyl2x;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.fyl2xp1;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.hlt;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.invd;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.invlpg;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.iret;
begin
raise_not_realized();
end;
procedure TOpcodeBlock_Intel.lahf;
begin
raise_not_realized();
end;
{$ifdef OPCODE_MODES}
procedure TOpcodeBlock_Intel.call(ProcName: pansichar);
{$ifdef PUREPASCAL}
begin
cmd_textjump_proc(-2{call}, ProcName);
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
mov dl, -2
jmp cmd_textjump_proc
end;
{$endif}
procedure TOpcodeBlock_Intel.j(cc: intel_cc; ProcName: pansichar);
{$ifdef PUREPASCAL}
begin
cmd_textjump_proc(shortint(cc), ProcName);
end;
{$else}
asm
jmp cmd_textjump_proc
end;
{$endif}
procedure TOpcodeBlock_Intel.jmp(ProcName: pansichar);
{$ifdef PUREPASCAL}
begin
cmd_cmd_textjump_proc(-1{jmp}, ProcName);
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
or edx, -1
jmp cmd_textjump_proc
end;
{$endif}
{$endif}
procedure TOpcodeBlock_Intel.leave;
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
AddCmdText(PShortString(@cmd_leave)).F.ModeParam := ord(cmLeave) + ((128{текст}+1{leave}) shl 8);
end else
{$endif}
begin
// cmLeave команды не должны спариваться с другими бинарными командами (может потом изменю логику)
P.Proc.FLastBinaryCmd := NO_CMD;
// добавляем
AddSmartBinaryCmd($00c90000, 0).F.ModeParam := ord(cmLeave) + ((0{бинарный}+1{leave}) shl 8);
end;
end;
procedure TOpcodeBlock_Intel.pause;
{$ifndef OPCODE_FAST}
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
AddCmdText(PShortString(@cmd_pause));
end else
{$endif}
begin
AddSmartBinaryCmd($0090F300, 0);
end;
end;
{$else}
asm
mov edx, $0090F300
jmp AddSmartBinaryCmd
end;
{$endif}
procedure TOpcodeBlock_Intel.push(const v_const: const_32);
const
OPCODE = $686A{push imm8(6A) | imm32(68)};
begin
if (v_const.Kind = ckValue) then
begin
// вызов сразу
cmd_const_value(OPCODE, {$ifdef OPCODE_MODES}v_const,cmd_push{$else}v_const.Value{$endif});
end else
begin
// сложный вызов
diffcmd_const32(OPCODE, v_const, cmd_const_value{$ifdef OPCODE_MODES},cmd_push{$endif});
end;
end;
procedure TOpcodeBlock_Intel.ret(const count: word=0);
var
Result: POpcodeCmd;
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
if (count = 0) then Result := AddCmdText(PShortString(@cmd_ret))
else Result := AddCmdText('ret %d', [count]);
Result.F.Param := 128{текст}+0{ret(n)};
end else
{$endif}
begin
// cmLeave команды не должны спариваться с другими бинарными командами (может потом изменю логику)
P.Proc.FLastBinaryCmd := NO_CMD;
// добавляем
if (count = 0) then Result := AddSmartBinaryCmd($00c30000, 0)
else Result := AddSmartBinaryCmd($00c20002, count);
// Result.F.Param := 0{бинарный}+0{ret(n)};
end;
// указываем, что команда cmLeave
Result.F.Mode := cmLeave;
end;
procedure TOpcodeBlock_Intel.ud2;
const
OPCODE = $0B0F{ud2};
{$ifndef OPCODE_FAST}
begin
cmd_single(OPCODE{$ifdef OPCODE_MODES},cmd_ud2{$endif});
end;
{$else}
asm
mov edx, OPCODE
jmp cmd_single
end;
{$endif}
procedure TOpcodeBlock_Intel.wait;
begin
raise_not_realized();
end;
{ TOpcodeBlock_x86 }
function TOpcodeBlock_x86.AppendBlock: POpcodeBlock_x86;
const
BLOCK_SIZE = sizeof(TOpcodeBlock);
{$ifdef PUREPASCAL}
begin
Result := POpcodeBlock_x86(inherited AppendBlock(BLOCK_SIZE));
end;
{$else}
asm
mov edx, BLOCK_SIZE
jmp TOpcodeBlock.AppendBlock
end;
{$endif}
// adc
procedure TOpcodeBlock_x86.adc(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = ($C010{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_adc{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.adc(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($D014{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_adc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.adc(reg: reg_x86; const addr: address_x86);
const
OPCODE = $0200 or ($10{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_adc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.adc(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($10{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_adc{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.adc(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = ($1080{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_adc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock adc
procedure TOpcodeBlock_x86.lock_adc(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = flag_lock or ($10{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_adc{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.lock_adc(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_lock or ($1080{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_adc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// add
procedure TOpcodeBlock_x86.add(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = flag_extra or ($C002{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_add{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.add(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($C004{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_add{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.add(reg: reg_x86; const addr: address_x86);
const
OPCODE = $0200 or ($00{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_add{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.add(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($00{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_add{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.add(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = ($0080{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_add{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock add
procedure TOpcodeBlock_x86.lock_add(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = flag_lock or ($00{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_add{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.lock_add(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_lock or ($0080{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_add{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// and
procedure TOpcodeBlock_x86.and_(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = ($C020{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_and{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.and_(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($E024{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_and{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.and_(reg: reg_x86; const addr: address_x86);
const
OPCODE = $0200 or ($20{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_and{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.and_(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($20{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_and{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.and_(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = ($2080{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_and{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock and
procedure TOpcodeBlock_x86.lock_and(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = flag_lock or ($20{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_and{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.lock_and(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_lock or ($2080{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_and{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// bswap
procedure TOpcodeBlock_x86.bswap(reg: reg_x86_dwords);
const
OPCODE = ($C80E{bswap} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_bswap{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
// call
procedure TOpcodeBlock_x86.call(block: POpcodeBlock_x86);
{$ifdef PUREPASCAL}
begin
cmd_jump_block(-2{call}, block);
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
mov dl, -2
jmp cmd_jump_block
end;
{$endif}
procedure TOpcodeBlock_x86.call(blocks: POpcodeSwitchBlock; index: reg_x86_addr; offset: integer=0);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_x86.call(reg: reg_x86_addr);
const
OPCODE = ($D0FE{call} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_call{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.call(const addr: address_x86);
const
OPCODE = ($10FF{call} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_call{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
// cmovcc
procedure TOpcodeBlock_x86.cmov(cc: intel_cc; reg: reg_x86_wd; v_reg: reg_x86_wd);
const
FLAGS = flag_extra;
{$ifndef OPCODE_FASTEST}
begin
setcmov_cc_regs(FLAGS or (ord(cc) shl 8) or byte(reg) or (ord(v_reg) shl 16){$ifdef OPCODE_MODES},cmd_cmov{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
movzx ebp, v_reg
movzx ecx, cl
shl ebp, 16
shl edx, 8
lea ecx, [ecx + ebp + FLAGS]
pop ebp
add edx, ecx
pop ecx
mov [esp], ecx
{$else .CPUX64}
movzx r9, r9b // v_reg
movzx r8, r8b
shl r9, 16
shl edx, 8
lea r8, [r8 + r9 + FLAGS]
add rdx, r8
{$endif}
jmp setcmov_cc_regs
end;
{$endif}
procedure TOpcodeBlock_x86.cmov(cc: intel_cc; reg: reg_x86_wd; const addr: address_x86);
const
FLAGS = flag_extra;
{$ifndef OPCODE_FASTEST}
begin
PRE_setcmov_cc_addr(FLAGS or ord(cc) or (ord(reg) shl 8), addr{$ifdef OPCODE_MODES},cmd_cmov{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
movzx edx, dl
shl ecx, 8
mov ebp, addr
lea edx, [edx + ecx + FLAGS]
mov ecx, [esp+4] // ret
add esp, 8
mov [esp], ecx
cmp byte ptr [EBP + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
xchg ecx, ebp
mov ebp, [esp-8]
{$else .CPUX64}
movzx r8, r8b
movzx edx, dl
shl r8, 8
cmp byte ptr [R9 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + r8 + FLAGS]
xchg r8, r9
{$endif}
je setcmov_cc_addr_value
jmp PRE_setcmov_cc_addr
end;
{$endif}
// cmp
procedure TOpcodeBlock_x86.cmp(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = ($C038{cmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_cmp{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.cmp(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($F83C{cmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_cmp{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.cmp(reg: reg_x86; const addr: address_x86);
const
OPCODE = $0200 or ($38{cmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_cmp{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.cmp(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($38{cmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_cmp{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.cmp(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = ($3880{cmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_cmp{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// dec
procedure TOpcodeBlock_x86.dec(reg: reg_x86);
const
OPCODE = flag_extra or ($C8FE{dec} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_dec{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.dec(ptr: size_ptr; const addr: address_x86);
const
OPCODE = ($08FE{dec} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_dec{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// lock dec
procedure TOpcodeBlock_x86.lock_dec(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_lock or ($08FE{dec} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_lock_dec{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// div
procedure TOpcodeBlock_x86.div_(reg: reg_x86);
const
OPCODE = ($F0F6{div} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_div{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.div_(ptr: size_ptr; const addr: address_x86);
const
OPCODE = ($30F6{div} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_div{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// idiv
procedure TOpcodeBlock_x86.idiv(reg: reg_x86);
const
OPCODE = ($F8F6{idiv} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_idiv{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.idiv(ptr: size_ptr; const addr: address_x86);
const
OPCODE = ($38F6{idiv} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_idiv{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// imul
procedure TOpcodeBlock_x86.imul(reg: reg_x86);
const
OPCODE = ($E8F6{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.imul(ptr: size_ptr; const addr: address_x86);
const
OPCODE = ($28F6{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
procedure TOpcodeBlock_x86.imul(reg: reg_x86_wd; v_reg: reg_x86_wd);
const
OPCODE = flag_0f or flag_extra or ($C0AE{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.imul(reg: reg_x86_wd; const addr: address_x86);
const
OPCODE = flag_0f or flag_extra or $0200 or ($AE{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.imul(reg: reg_x86_wd; const v_const: const_32);
begin
// бинарно команда imul r, imm
// представляется в виде команды imul r, r, imm
//
// и ради одной команды (в ассемблере) нет резона
// изменять cmd_reg_const_value()
imul(reg, reg, v_const);
end;
procedure TOpcodeBlock_x86.imul(reg1, reg2: reg_x86_wd; const v_const: const_32);
const
OPCODE = flag_extra or ($69{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_reg_const((ord(reg2) shl 16) or OPCODE or byte(reg1), v_const{$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
movzx ecx, cl
mov ebp, [esp+8] // v_const
shl ecx, 16
cmp [EBP].TOpcodeConst.FKind, ckValue
lea edx, [edx + ecx + OPCODE]
mov ecx, [esp+4] // ret
mov [esp+8], ecx
xchg ecx, ebp
mov ebp, [esp]
lea esp, [esp+8]
{$else .CPUX64}
movzx eax, r8b
xchg r8, r9
shl eax, 16
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + rax + OPCODE]
{$endif}
jne PRE_cmd_reg_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.imul(reg: reg_x86_wd; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_extra or ($69{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr_reg_const(OPCODE or byte(reg), addr, v_const{$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_addr_reg_const_value
@call_std:
pop ebp
jmp PRE_cmd_addr_reg_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_addr_reg_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_addr_reg_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_addr_reg_const_value
{$endif}
end;
{$endif}
// inc
procedure TOpcodeBlock_x86.inc(reg: reg_x86);
const
OPCODE = flag_extra or ($C0FE{inc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_inc{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.inc(ptr: size_ptr; const addr: address_x86);
const
OPCODE = ($00FE{inc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_inc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// lock inc
procedure TOpcodeBlock_x86.lock_inc(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_lock or ($00FE{inc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_lock_inc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// jcc
procedure TOpcodeBlock_x86.j(cc: intel_cc; block: POpcodeBlock_x86);
{$ifdef PUREPASCAL}
begin
cmd_jump_block(shortint(cc), block);
end;
{$else}
asm
jmp cmd_jump_block
end;
{$endif}
// jmp
procedure TOpcodeBlock_x86.jmp(block: POpcodeBlock_x86);
{$ifdef PUREPASCAL}
begin
cmd_jump_block(-1{jmp}, block);
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
or edx, -1
jmp cmd_jump_block
end;
{$endif}
procedure TOpcodeBlock_x86.jmp(blocks: POpcodeSwitchBlock; index: reg_x86_addr; offset: integer=0);
begin
raise_not_realized();
end;
procedure TOpcodeBlock_x86.jmp(reg: reg_x86_addr);
const
OPCODE = ($E0FE{jmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_jmp{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.jmp(const addr: address_x86);
const
OPCODE = ($20FF{jmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_jmp{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
// lea
procedure TOpcodeBlock_x86.lea(reg: reg_x86_addr; const addr: address_x86);
const
OPCODE = ($8D{lea} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_lea{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
// mov
procedure TOpcodeBlock_x86.mov(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = ($C088{mov} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.mov(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($B000{mov} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.mov(reg: reg_x86; const addr: address_x86);
const
OPCODE = $0200 or ($88{mov} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.mov(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($88{mov} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.mov(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = ($00C6{mov} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// movsx
procedure TOpcodeBlock_x86.movsx(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = flag_0f or ($C0BE{movsx} shl 8);
{$ifndef OPCODE_FASTEST}
begin
movszx_reg_reg(OPCODE or byte(reg), byte(v_reg){$ifdef OPCODE_MODES},cmd_movsx{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp movszx_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.movsx(reg: reg_x86; ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_0f or ($BE{movsx} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_movszx_reg_ptr_addr(ord(reg) or (ord(ptr) shl 16) or OPCODE,
addr{$ifdef OPCODE_MODES},cmd_movsx{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
movzx edx, dl
mov ebp, [ebp+8] // addr
shl ecx, 16
cmp byte ptr [EBP + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + ecx + OPCODE]
mov ecx, [esp+4]
lea esp, [esp + 8]
xchg ecx, ebp
mov [esp], ebp
mov ebp, [esp-8]
{$else .CPUX64}
movzx eax, r8b
movzx edx, dl
xchg r8, r9
shl eax, 16
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + rax + OPCODE]
{$endif}
je movszx_reg_ptr_addr_value
jmp PRE_movszx_reg_ptr_addr
end;
{$endif}
// movzx
procedure TOpcodeBlock_x86.movzx(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = flag_0f or ($C0B6{movsx} shl 8);
{$ifndef OPCODE_FASTEST}
begin
movszx_reg_reg(OPCODE or byte(reg), byte(v_reg){$ifdef OPCODE_MODES},cmd_movzx{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp movszx_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.movzx(reg: reg_x86; ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_0f or ($B6{movsx} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_movszx_reg_ptr_addr(ord(reg) or (ord(ptr) shl 16) or OPCODE,
addr{$ifdef OPCODE_MODES},cmd_movzx{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
movzx edx, dl
mov ebp, [ebp+8] // addr
shl ecx, 16
cmp byte ptr [EBP + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + ecx + OPCODE]
mov ecx, [esp+4]
lea esp, [esp + 8]
xchg ecx, ebp
mov [esp], ebp
mov ebp, [esp-8]
{$else .CPUX64}
movzx eax, r8b
movzx edx, dl
xchg r8, r9
shl eax, 16
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + rax + OPCODE]
{$endif}
je movszx_reg_ptr_addr_value
jmp PRE_movszx_reg_ptr_addr
end;
{$endif}
// mul
procedure TOpcodeBlock_x86.mul(reg: reg_x86);
const
OPCODE = ($E0F6{mul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_mul{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.mul(ptr: size_ptr; const addr: address_x86);
const
OPCODE = ($20F6{mul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_mul{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// neg
procedure TOpcodeBlock_x86.neg(reg: reg_x86);
const
OPCODE = ($D8F6{neg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_neg{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.neg(ptr: size_ptr; const addr: address_x86);
const
OPCODE = ($18F6{neg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_neg{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
procedure TOpcodeBlock_x86.lock_neg(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_lock or ($18F6{neg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_lock_neg{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// not
procedure TOpcodeBlock_x86.not_(reg: reg_x86);
const
OPCODE = ($D0F6{not} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_not{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.not_(ptr: size_ptr; const addr: address_x86);
const
OPCODE = ($10F6{not} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_not{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// lock not
procedure TOpcodeBlock_x86.lock_not(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_lock or ($10F6{not} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_lock_not{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// or
procedure TOpcodeBlock_x86.or_(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = ($C008{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_or{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.or_(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($C80C{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_or{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.or_(reg: reg_x86; const addr: address_x86);
const
OPCODE = $0200 or ($08{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_or{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.or_(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($08{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_or{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.or_(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = ($0880{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_or{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock or
procedure TOpcodeBlock_x86.lock_or(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = flag_lock or ($08{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_or{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.lock_or(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_lock or ($0880{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_or{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// pop
procedure TOpcodeBlock_x86.pop(reg: reg_x86_wd);
const
OPCODE = ($5800{pop} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_pop{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.pop(ptr: size_ptr; const addr: address_x86);
const
OPCODE = ($008F{pop} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_pop{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// push
procedure TOpcodeBlock_x86.push(reg: reg_x86_wd);
const
OPCODE = ($5000{push} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_push{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x86.push(ptr: size_ptr; const addr: address_x86);
const
OPCODE = ($30FF{push} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_push{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// rcl
procedure TOpcodeBlock_x86.rcl_cl(reg: reg_x86);
const
OPCODE = flag_extra or ($D0D2{rcl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_rcl{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.rcl(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($D0C0{rcl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_rcl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.rcl_cl(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_extra or ($10D2{rcl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_rcl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x86.rcl(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_extra or ($10C0{rcl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_rcl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// rcr
procedure TOpcodeBlock_x86.rcr_cl(reg: reg_x86);
const
OPCODE = flag_extra or ($D8D2{rcr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_rcr{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.rcr(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($D8C0{rcr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_rcr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.rcr_cl(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_extra or ($18D2{rcr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_rcr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x86.rcr(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_extra or ($18C0{rcr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_rcr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// rol
procedure TOpcodeBlock_x86.rol_cl(reg: reg_x86);
const
OPCODE = flag_extra or ($C0D2{rol} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_rol{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.rol(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($C0C0{rol} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_rol{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.rol_cl(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_extra or ($00D2{rol} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_rol{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x86.rol(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_extra or ($00C0{rol} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_rol{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// ror
procedure TOpcodeBlock_x86.ror_cl(reg: reg_x86);
const
OPCODE = flag_extra or ($C8D2{ror} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_ror{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.ror(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($C8C0{ror} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_ror{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.ror_cl(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_extra or ($08D2{ror} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_ror{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x86.ror(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_extra or ($08C0{ror} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_ror{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// sal
procedure TOpcodeBlock_x86.sal_cl(reg: reg_x86);
const
OPCODE = flag_extra or ($E0D2{sal} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_sal{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.sal(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($E0C0{sal} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_sal{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.sal_cl(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_extra or ($20D2{sal} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_sal{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x86.sal(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_extra or ($20C0{sal} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_sal{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// sar
procedure TOpcodeBlock_x86.sar_cl(reg: reg_x86);
const
OPCODE = flag_extra or ($F8D2{sar} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_sar{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.sar(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($F8C0{sar} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_sar{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.sar_cl(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_extra or ($38D2{sar} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_sar{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x86.sar(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_extra or ($38C0{sar} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_sar{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// sbb
procedure TOpcodeBlock_x86.sbb(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = ($C018{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_sbb{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.sbb(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($D81C{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_sbb{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.sbb(reg: reg_x86; const addr: address_x86);
const
OPCODE = $0200 or ($18{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_sbb{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.sbb(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($18{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_sbb{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.sbb(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = ($1880{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_sbb{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock sbb
procedure TOpcodeBlock_x86.lock_sbb(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = flag_lock or ($18{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_sbb{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.lock_sbb(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_lock or ($1880{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_sbb{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// setcc
procedure TOpcodeBlock_x86.set_(cc: intel_cc; reg: reg_x86_bytes);
{$ifndef OPCODE_FASTEST}
begin
setcmov_cc_regs((ord(cc) shl 8) or byte(reg){$ifdef OPCODE_MODES},cmd_set{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
movzx ecx, cl
shl edx, 8
or edx, ecx
{$else .CPUX64}
movzx r8, r8b
shl edx, 8
or rdx, r8
{$endif}
jmp setcmov_cc_regs
end;
{$endif}
procedure TOpcodeBlock_x86.set_(cc: intel_cc; const addr: address_x86);
{$ifndef OPCODE_FASTEST}
begin
PRE_setcmov_cc_addr(ord(cc), addr{$ifdef OPCODE_MODES},cmd_set{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
{$endif}
movzx edx, dl
je setcmov_cc_addr_value
jmp PRE_setcmov_cc_addr
end;
{$endif}
// shl
procedure TOpcodeBlock_x86.shl_cl(reg: reg_x86);
const
OPCODE = flag_extra or ($E0D2{shl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_shl{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.shl_(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($E0C0{shl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_shl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.shl_cl(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_extra or ($20D2{shl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_shl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x86.shl_(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_extra or ($20C0{shl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_shl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// shr
procedure TOpcodeBlock_x86.shr_cl(reg: reg_x86);
const
OPCODE = flag_extra or ($E8D2{shr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_shr{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.shr_(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($E8C0{shr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_shr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.shr_cl(ptr: size_ptr; const addr: address_x86);
const
OPCODE = flag_extra or ($28D2{shr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_shr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x86.shr_(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_extra or ($28C0{shr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_shr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// shld
procedure TOpcodeBlock_x86.shld_cl(reg1, reg2: reg_x86);
const
OPCODE = flag_0f or ($A5{shld_cl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистров
{$endif}
cmd_reg_reg_const_value((ord(reg2) shl 16) or OPCODE or byte(reg1), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_shld{$else}0{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
movzx edx, dl
shl ecx, 16
lea edx, [edx + ecx + OPCODE]
{$else .CPUX64}
movzx eax, r8b
movzx edx, dl
shl eax, 16
lea rdx, [rdx + rax + OPCODE]
{$endif}
jmp cmd_reg_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.shld(reg1, reg2: reg_x86; const v_const: const_32);
const
OPCODE = flag_0f or ($A4{shld} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_reg_const((ord(reg2) shl 16) or OPCODE or byte(reg1), v_const{$ifdef OPCODE_MODES},cmd_shld{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
movzx ecx, cl
mov ebp, [esp+8] // v_const
shl ecx, 16
cmp [EBP].TOpcodeConst.FKind, ckValue
lea edx, [edx + ecx + OPCODE]
mov ecx, [esp+4] // ret
mov [esp+8], ecx
xchg ecx, ebp
mov ebp, [esp]
lea esp, [esp+8]
{$else .CPUX64}
movzx eax, r8b
xchg r8, r9
shl eax, 16
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + rax + OPCODE]
{$endif}
jne PRE_cmd_reg_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.shld_cl(const addr: address_x86; reg2: reg_x86);
const
OPCODE = flag_0f or ($A5{shld_cl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr_reg_const(OPCODE or byte(reg2), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_shld{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
push [esp]
or ecx, OPCODE
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [esp+4], offset ZERO_CONST_32
xchg edx, ecx
{$else .CPUX64}
lea rax, [ZERO_CONST_32]
movzx r8, r8b
push [rsp]
or r8d, OPCODE
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [rsp+8], rax
xchg rdx, r8
{$endif}
je cmd_addr_reg_const_value
jmp PRE_cmd_addr_reg_const
end;
{$endif}
procedure TOpcodeBlock_x86.shld(const addr: address_x86; reg2: reg_x86; const v_const: const_32);
const
OPCODE = flag_0f or ($A4{shld} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr_reg_const(OPCODE or byte(reg2), addr, v_const{$ifdef OPCODE_MODES},cmd_shld{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
mov ebp, [esp+8] // v_const
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea ecx, [ecx + OPCODE]
xchg edx, ecx
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_addr_reg_const_value
@call_std:
pop ebp
jmp PRE_cmd_addr_reg_const
{$else .CPUX64}
movzx r8, r8b
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea r8, [r8 + OPCODE]
xchg rdx, r8
jne PRE_cmd_addr_reg_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_addr_reg_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_addr_reg_const_value
{$endif}
end;
{$endif}
// shrd
procedure TOpcodeBlock_x86.shrd_cl(reg1, reg2: reg_x86);
const
OPCODE = flag_0f or ($AD{shrd_cl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистров
{$endif}
cmd_reg_reg_const_value((ord(reg2) shl 16) or OPCODE or byte(reg1), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_shrd{$else}0{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
movzx edx, dl
shl ecx, 16
lea edx, [edx + ecx + OPCODE]
{$else .CPUX64}
movzx eax, r8b
movzx edx, dl
shl eax, 16
lea rdx, [rdx + rax + OPCODE]
{$endif}
jmp cmd_reg_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.shrd(reg1, reg2: reg_x86; const v_const: const_32);
const
OPCODE = flag_0f or ($AC{shrd} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_reg_const((ord(reg2) shl 16) or OPCODE or byte(reg1), v_const{$ifdef OPCODE_MODES},cmd_shrd{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
movzx ecx, cl
mov ebp, [esp+8] // v_const
shl ecx, 16
cmp [EBP].TOpcodeConst.FKind, ckValue
lea edx, [edx + ecx + OPCODE]
mov ecx, [esp+4] // ret
mov [esp+8], ecx
xchg ecx, ebp
mov ebp, [esp]
lea esp, [esp+8]
{$else .CPUX64}
movzx eax, r8b
xchg r8, r9
shl eax, 16
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + rax + OPCODE]
{$endif}
jne PRE_cmd_reg_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.shrd_cl(const addr: address_x86; reg2: reg_x86);
const
OPCODE = flag_0f or ($AD{shrd_cl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr_reg_const(OPCODE or byte(reg2), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_shrd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
push [esp]
or ecx, OPCODE
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [esp+4], offset ZERO_CONST_32
xchg edx, ecx
{$else .CPUX64}
lea rax, [ZERO_CONST_32]
movzx r8, r8b
push [rsp]
or r8d, OPCODE
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [rsp+8], rax
xchg rdx, r8
{$endif}
je cmd_addr_reg_const_value
jmp PRE_cmd_addr_reg_const
end;
{$endif}
procedure TOpcodeBlock_x86.shrd(const addr: address_x86; reg2: reg_x86; const v_const: const_32);
const
OPCODE = flag_0f or ($AC{shrd} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr_reg_const(OPCODE or byte(reg2), addr, v_const{$ifdef OPCODE_MODES},cmd_shrd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
mov ebp, [esp+8] // v_const
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea ecx, [ecx + OPCODE]
xchg edx, ecx
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_addr_reg_const_value
@call_std:
pop ebp
jmp PRE_cmd_addr_reg_const
{$else .CPUX64}
movzx r8, r8b
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea r8, [r8 + OPCODE]
xchg rdx, r8
jne PRE_cmd_addr_reg_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_addr_reg_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_addr_reg_const_value
{$endif}
end;
{$endif}
// sub
procedure TOpcodeBlock_x86.sub(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = ($C028{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_sub{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.sub(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($E82C{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_sub{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.sub(reg: reg_x86; const addr: address_x86);
const
OPCODE = $0200 or ($28{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_sub{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.sub(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($28{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_sub{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.sub(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = ($2880{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_sub{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock sub
procedure TOpcodeBlock_x86.lock_sub(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = flag_lock or ($28{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_sub{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.lock_sub(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_lock or ($2880{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_sub{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// test
procedure TOpcodeBlock_x86.test(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = ($C084{test} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_test{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.test(reg: reg_x86; const v_const: const_32);
const
OPCODE = flag_extra or ($C0A8{test} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_test{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.test(reg: reg_x86; const addr: address_x86);
const
OPCODE = $0200 or ($84{test} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_test{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.test(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($84{test} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_test{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.test(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = ($00F6{test} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_test{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// xadd
procedure TOpcodeBlock_x86.xadd(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = flag_0f or ($C0C0{xadd} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_xadd{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.xadd(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = flag_0f or ($C0{xadd} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_xadd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
// lock xadd
procedure TOpcodeBlock_x86.lock_xadd(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = flag_lock or flag_0f or ($C0{xadd} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_xadd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
// xchg
procedure TOpcodeBlock_x86.xchg(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = ($C086{xchg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_xchg{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.xchg(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($86{xchg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_xchg{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
// lock xchg
procedure TOpcodeBlock_x86.lock_xchg(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = flag_lock or ($86{xchg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_xchg{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
// xor
procedure TOpcodeBlock_x86.xor_(reg: reg_x86; v_reg: reg_x86);
const
OPCODE = ($C030{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_xor{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x86.xor_(reg: reg_x86; const v_const: const_32);
const
OPCODE = ($F034{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_xor{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x86.xor_(reg: reg_x86; const addr: address_x86);
const
OPCODE = $0200 or ($30{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_xor{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.xor_(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = ($30{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_xor{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.xor_(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = ($3080{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_xor{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock xor
procedure TOpcodeBlock_x86.lock_xor(const addr: address_x86; v_reg: reg_x86);
const
OPCODE = flag_lock or ($30{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_xor{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x86.lock_xor(ptr: size_ptr; const addr: address_x86; const v_const: const_32);
const
OPCODE = flag_lock or ($3080{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_xor{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// FPU и память
procedure TOpcodeBlock_x86.fbld(const addr: address_x86);
const
OPCODE = ($20DF{fbld} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fbld{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fbstp(const addr: address_x86);
const
OPCODE = ($30DF{fbstp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fbstp{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fldcw(const addr: address_x86);
const
OPCODE = ($28D9{fldcw} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fldcw{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fldenv(const addr: address_x86);
const
OPCODE = ($20D9{flden} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fldenv{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fsave(const addr: address_x86);
const
OPCODE = flag_extra or ($30DD{fsave} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fsave{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fnsave(const addr: address_x86);
const
OPCODE = ($30DD{fnsave} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fnsave{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fstcw(const addr: address_x86);
const
OPCODE = flag_extra or ($38D9{fstcw} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fstcw{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fnstcw(const addr: address_x86);
const
OPCODE = ($38D9{fnstcw} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fnstcw{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fstenv(const addr: address_x86);
const
OPCODE = flag_extra or ($30D9{fstenv} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fstenv{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fnstenv(const addr: address_x86);
const
OPCODE = ($30D9{fnstenv} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fnstenv{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fstsw(const addr: address_x86);
const
OPCODE = flag_extra or ($38DD{fstsw} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fstsw{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x86.fnstsw(const addr: address_x86);
const
OPCODE = ($38DD{fnstsw} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fnstsw{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
{ TOpcodeBlock_x64 }
function TOpcodeBlock_x64.AppendBlock: POpcodeBlock_x64;
const
BLOCK_SIZE = sizeof(TOpcodeBlock);
{$ifdef PUREPASCAL}
begin
Result := POpcodeBlock_x64(inherited AppendBlock(BLOCK_SIZE));
end;
{$else}
asm
mov edx, BLOCK_SIZE
jmp TOpcodeBlock.AppendBlock
end;
{$endif}
// adc
procedure TOpcodeBlock_x64.adc(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($C010{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_adc{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.adc(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($D014{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_adc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.adc(reg: reg_x64; const addr: address_x64);
const
OPCODE = flag_x64 or $0200 or ($10{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_adc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.adc(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($10{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_adc{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.adc(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($1080{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_adc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock adc
procedure TOpcodeBlock_x64.lock_adc(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_lock or ($10{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_adc{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.lock_adc(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_lock or ($1080{adc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_adc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// add
procedure TOpcodeBlock_x64.add(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_extra or ($C002{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_add{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.add(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($C004{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_add{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.add(reg: reg_x64; const addr: address_x64);
const
OPCODE = flag_x64 or $0200 or ($00{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_add{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.add(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($00{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_add{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.add(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($0080{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_add{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock add
procedure TOpcodeBlock_x64.lock_add(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_lock or ($00{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_add{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.lock_add(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_lock or ($0080{add} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_add{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// and
procedure TOpcodeBlock_x64.and_(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($C020{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_and{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.and_(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($E024{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_and{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.and_(reg: reg_x64; const addr: address_x64);
const
OPCODE = flag_x64 or $0200 or ($20{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_and{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.and_(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($20{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_and{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.and_(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($2080{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_and{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock and
procedure TOpcodeBlock_x64.lock_and(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_lock or ($20{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_and{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.lock_and(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_lock or ($2080{and} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_and{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// либо 4 байта, либо 8
procedure TOpcodeBlock_x64.bswap(reg: reg_x64_dq);
const
OPCODE = flag_x64 or ($C80E{bswap} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_bswap{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
// call
procedure TOpcodeBlock_x64.call(block: POpcodeBlock_x64);
{$ifdef PUREPASCAL}
begin
cmd_jump_block(-2{call}, block);
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
mov dl, -2
jmp cmd_jump_block
end;
{$endif}
procedure TOpcodeBlock_x64.call(blocks: POpcodeSwitchBlock; index: reg_x64_addr; offset: integer=0{$ifdef OPCODE_MODES};buffer: reg_x64_addr=r11{$endif});
begin
raise_not_realized;
end;
procedure TOpcodeBlock_x64.call(reg: reg_x64_addr);
const
OPCODE = flag_x64 or ($D0FE{call} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_call{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.call(const addr: address_x64);
const
OPCODE = flag_x64 or ($10FF{call} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_call{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
// cmov
procedure TOpcodeBlock_x64.cmov(cc: intel_cc; reg: reg_x64_wdq; v_reg: reg_x64_wdq);
const
FLAGS = flag_x64 or flag_extra;
{$ifndef OPCODE_FASTEST}
begin
setcmov_cc_regs(FLAGS or (ord(cc) shl 8) or byte(reg) or (ord(v_reg) shl 16){$ifdef OPCODE_MODES},cmd_cmov{$endif})
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
movzx ebp, v_reg
movzx ecx, cl
shl ebp, 16
shl edx, 8
lea ecx, [ecx + ebp + FLAGS]
pop ebp
add edx, ecx
pop ecx
mov [esp], ecx
{$else .CPUX64}
movzx r9, r9b // v_reg
movzx r8, r8b
shl r9, 16
shl edx, 8
lea r8, [r8 + r9 + FLAGS]
add rdx, r8
{$endif}
jmp setcmov_cc_regs
end;
{$endif}
procedure TOpcodeBlock_x64.cmov(cc: intel_cc; reg: reg_x64_wdq; const addr: address_x64);
const
FLAGS = flag_x64 or flag_extra;
{$ifndef OPCODE_FASTEST}
begin
PRE_setcmov_cc_addr(FLAGS or ord(cc) or (ord(reg) shl 8), addr{$ifdef OPCODE_MODES},cmd_cmov{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
movzx edx, dl
shl ecx, 8
mov ebp, addr
lea edx, [edx + ecx + FLAGS]
mov ecx, [esp+4] // ret
add esp, 8
mov [esp], ecx
cmp byte ptr [EBP + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
xchg ecx, ebp
mov ebp, [esp-8]
{$else .CPUX64}
movzx r8, r8b
movzx edx, dl
shl r8, 8
cmp byte ptr [R9 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + r8 + FLAGS]
xchg r8, r9
{$endif}
je setcmov_cc_addr_value
jmp PRE_setcmov_cc_addr
end;
{$endif}
// cmp
procedure TOpcodeBlock_x64.cmp(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($C038{cmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_cmp{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.cmp(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($F83C{cmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_cmp{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.cmp(reg: reg_x64; const addr: address_x64);
const
OPCODE = flag_x64 or $0200 or ($38{cmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_cmp{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.cmp(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($38{cmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_cmp{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.cmp(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($3880{cmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_cmp{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// dec
procedure TOpcodeBlock_x64.dec(reg: reg_x64);
const
OPCODE = flag_x64 or ($C8FE{dec} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_dec{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.dec(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or ($08FE{dec} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_dec{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// lock dec
procedure TOpcodeBlock_x64.lock_dec(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_lock or ($08FE{dec} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_lock_dec{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// div
procedure TOpcodeBlock_x64.div_(reg: reg_x64);
const
OPCODE = flag_x64 or ($F0F6{div} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_div{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.div_(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or ($30F6{div} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_div{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// idiv
procedure TOpcodeBlock_x64.idiv(reg: reg_x64);
const
OPCODE = flag_x64 or ($F8F6{idiv} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_idiv{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.idiv(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or ($38F6{idiv} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_idiv{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// imul
procedure TOpcodeBlock_x64.imul(reg: reg_x64);
const
OPCODE = flag_x64 or ($E8F6{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.imul(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or ($28F6{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
procedure TOpcodeBlock_x64.imul(reg: reg_x64_wdq; v_reg: reg_x64_wdq);
const
OPCODE = flag_x64 or flag_0f or flag_extra or ($C0AE{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.imul(reg: reg_x64_wdq; const addr: address_x64);
const
OPCODE = flag_x64 or flag_0f or flag_extra or $0200 or ($AE{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.imul(reg: reg_x64_wdq; const v_const: const_32);
begin
// бинарно команда imul r, imm
// представляется в виде команды imul r, r, imm
//
// и ради одной команды (в ассемблере) нет резона
// изменять cmd_reg_const_value()
imul(reg, reg, v_const);
end;
procedure TOpcodeBlock_x64.imul(reg1, reg2: reg_x64_wdq; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($69{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_reg_const((ord(reg2) shl 16) or OPCODE or byte(reg1), v_const{$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
movzx ecx, cl
mov ebp, [esp+8] // v_const
shl ecx, 16
cmp [EBP].TOpcodeConst.FKind, ckValue
lea edx, [edx + ecx + OPCODE]
mov ecx, [esp+4] // ret
mov [esp+8], ecx
xchg ecx, ebp
mov ebp, [esp]
lea esp, [esp+8]
{$else .CPUX64}
movzx eax, r8b
xchg r8, r9
shl eax, 16
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + rax + OPCODE]
{$endif}
jne PRE_cmd_reg_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.imul(reg: reg_x64_wdq; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($69{imul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr_reg_const(OPCODE or byte(reg), addr, v_const{$ifdef OPCODE_MODES},cmd_imul{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_addr_reg_const_value
@call_std:
pop ebp
jmp PRE_cmd_addr_reg_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_addr_reg_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_addr_reg_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_addr_reg_const_value
{$endif}
end;
{$endif}
// inc
procedure TOpcodeBlock_x64.inc(reg: reg_x64);
const
OPCODE = flag_x64 or ($C0FE{inc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_inc{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.inc(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or ($00FE{inc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_inc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// lock inc
procedure TOpcodeBlock_x64.lock_inc(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_lock or ($00FE{inc} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_lock_inc{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// jcc
procedure TOpcodeBlock_x64.j(cc: intel_cc; block: POpcodeBlock_x64);
{$ifdef PUREPASCAL}
begin
cmd_jump_block(shortint(cc), block);
end;
{$else}
asm
jmp cmd_jump_block
end;
{$endif}
// jmp
procedure TOpcodeBlock_x64.jmp(block: POpcodeBlock_x64);
{$ifdef PUREPASCAL}
begin
cmd_jump_block(-1{jmp}, block);
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
or edx, -1
jmp cmd_jump_block
end;
{$endif}
procedure TOpcodeBlock_x64.jmp(blocks: POpcodeSwitchBlock; index: reg_x64_addr; offset: integer=0{$ifdef OPCODE_MODES};buffer: reg_x64_addr=r11{$endif});
begin
raise_not_realized;
end;
procedure TOpcodeBlock_x64.jmp(reg: reg_x64_addr);
const
OPCODE = flag_x64 or ($E0FE{jmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_jmp{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.jmp(const addr: address_x64);
const
OPCODE = flag_x64 or ($20FF{jmp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_jmp{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
// lea
procedure TOpcodeBlock_x64.lea(reg: reg_x64_addr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($8D{lea} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_lea{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
// mov
procedure TOpcodeBlock_x64.mov(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($C088{mov} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.mov(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($B000{mov} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.mov(reg: reg_x64; const addr: address_x64);
const
OPCODE = flag_x64 or $0200 or ($88{mov} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.mov(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($88{mov} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.mov(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($00C6{mov} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// два параметра: reg, const_64
// пока применяется только для mov
// PRE-реализация делается на месте
function TOpcodeBlock_x64.cmd_reg_const_value64(const opcode_reg: integer; const v_const: opused_const_64{$ifdef OPCODE_MODES}; const cmd: ShortString{$endif}): POpcodeCmd;
const
dif_rax_eax = rax-eax;
dif_r8_r8d = r8-r8d;
high_dword = int64(high(dword));
var
REG, X, Y: integer;
// cmd регистр, константа(%s или %d)
{$ifdef OPCODE_MODES}
procedure FillAsText();
var
buffer: TOpcodeTextBuffer;
begin
buffer.Const64(v_const);
Result := AddCmdText('%s %s, %s', [cmd, reg_intel_names[REG], buffer.value.S]);
end;
{$endif}
begin
REG := byte(opcode_reg);
// оптимизация reg 8 --> 4
if (REG in [rax..r15]) and
{$ifdef OPCODE_MODES}
(P.Proc.Mode = omBinary) and (v_const.Kind = ckValue) and
((v_const.Value >= 0) and (v_const.Value <= high_dword)) then
{$else}
((v_const >= 0) and (v_const <= high_dword)) then
{$endif}
begin
if (REG in [r8..r15]) then REG := REG - dif_r8_r8d
else
{if (REG in [rax..rdi]) then }REG := REG - dif_rax_eax;
end;
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
FillAsText();
exit;
end;
{$endif}
// модификации скопированы из cmd_reg_const_value
X := reg_intel_info[REG];
Y := opcode_reg or ((X and intel_nonbyte_mask) shl 11);
X := X and (not intel_nonbyte_mask);
X := (Y and intel_opcode_mask) or (X and intel_modrm_dest_mask) or byte(X);
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omHybrid) and (v_const.Kind <> ckValue) then
begin
FillAsText();
// размер константы всегда известен
Result.F.HybridSize_MinMax := HybridSize_MinMax(opcode_reg, X, nil);
end else
{$endif}
begin
Result := AddSmartBinaryCmd(X, {4 младших байта}{$ifdef OPCODE_MODES}v_const.Value{$else}v_const{$endif});
if (byte(X){imm_size} = 8) then
pint64(@POpcodeCmdData(Result).Bytes[Result.Size-sizeof(int64)])^ := {$ifdef OPCODE_MODES}v_const.Value{$else}v_const{$endif};
end;
end;
procedure TOpcodeBlock_x64.mov(reg: reg_x64{reg_x64_qwords}; const v_const: const_64);
const
OPCODE = flag_x64 or ($B000{mov} shl 8);
var
opcode_reg: integer;
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
// и ещё нужно определить, подходит ли он для данного вида констант
{$endif}
opcode_reg := OPCODE or ord(reg);
if (v_const.Kind = ckValue) then
begin
// вызов сразу
cmd_reg_const_value64(opcode_reg, {$ifdef OPCODE_MODES}v_const,cmd_mov{$else}v_const.Value{$endif});
end else
begin
// сложный вызов
diffcmd_const64(opcode_reg, v_const, cmd_reg_const_value64{$ifdef OPCODE_MODES},cmd_mov{$endif});
end;
end;
// movsx
procedure TOpcodeBlock_x64.movsx(reg: reg_x64; v_reg: reg_x64);
const
OPCODE_MAIN = flag_x64 or flag_0f or ($C0BE{movsx} shl 8);
OPCODE_ALTER = flag_x64 or ($C063{movsxd, но в ассемблере читается и movsx} shl 8);
{$ifndef OPCODE_FASTEST}
var
OPCODE: integer;
{$ifdef OPCODE_MODES}cmd: pshortstring;{$endif}
begin
{$ifdef OPCODE_MODES}cmd := pshortstring(@cmd_movsx);{$endif}
OPCODE := OPCODE_MAIN;
// if (byte(reg_intel_info[byte(reg)]) = 8) and (byte(reg_intel_info[byte(v_reg)]) = 4) then
if (reg in [rax..r15]) and (v_reg in [eax..r15d]) then
begin
{$ifdef OPCODE_MODES}cmd := pshortstring(@cmd_movsxd);{$endif}
OPCODE := OPCODE_ALTER;
end;
movszx_reg_reg(OPCODE or byte(reg), byte(v_reg){$ifdef OPCODE_MODES},cmd^{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [offset reg_intel_info + edx*4], 8
movzx ecx, cl
jne @call_std
cmp byte ptr [offset reg_intel_info + ecx*4], 4
jne @call_std
{$else .CPUX64}
lea r11, [reg_intel_info]
movzx eax, r8b
cmp byte ptr [r11 + rdx*4], 8
jne @call_std
cmp byte ptr [r11 + rax*4], 4
jne @call_std
{$endif}
or edx, OPCODE_ALTER
jmp movszx_reg_reg
@call_std:
or edx, OPCODE_MAIN
jmp movszx_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.movsx(reg: reg_x64; ptr: size_ptr; const addr: address_x64);
const
OPCODE_MAIN = flag_x64 or flag_0f or ($BE{movsx} shl 8);
OPCODE_ALTER = flag_x64 or ($63{movsxd, но в ассемблере читается и movsx} shl 8);
OPCODE_DIF_MAIN_ALTER = OPCODE_MAIN-OPCODE_ALTER;
{$ifndef OPCODE_FASTEST}
var
reg_opcode_ptr: integer;
{$ifdef OPCODE_MODES}cmd: pshortstring;{$endif}
begin
{$ifdef OPCODE_MODES}cmd := pshortstring(@cmd_movsx);{$endif}
reg_opcode_ptr := OPCODE_MAIN;
// if (byte(reg_intel_info[byte(reg)]) = 8) and (ptr = dword_ptr) then
if (reg in [rax..r15]) and (ptr = dword_ptr) then
begin
{$ifdef OPCODE_MODES}cmd := pshortstring(@cmd_movsxd);{$endif}
reg_opcode_ptr := OPCODE_ALTER;
end;
// cmd_movsx
reg_opcode_ptr := reg_opcode_ptr or ord(reg) or (ord(ptr) shl 16);
PRE_movszx_reg_ptr_addr(reg_opcode_ptr, addr{$ifdef OPCODE_MODES},cmd^{$endif});
end;
{$else}
const
rax_value = rax;
dword_ptr_offseted = ord(dword_ptr) shl 16;
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, addr
movzx ecx, cl
add esp, 8
sub edx, rax_value
shl ecx, 16
{$else .CPUX64}
movzx eax, r8b
sub edx, rax_value
shl eax, 16
{$endif}
cmp edx, 15
{$ifdef CPUX86}
lea edx, [edx+rax_value]
{$else .CPUX64}
lea rdx, [rdx+rax_value]
{$endif}
ja @opcode_main
{$ifdef CPUX86}
cmp ecx, dword_ptr_offseted
{$else .CPUX64}
cmp eax, dword_ptr_offseted
{$endif}
jne @opcode_main
@opcode_alter:
sub edx, OPCODE_DIF_MAIN_ALTER
@opcode_main:
{$ifdef CPUX86}
lea edx, [edx + ecx + OPCODE_MAIN]
mov ecx, [esp-4] // ret
cmp byte ptr [EBP + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [esp], ecx
mov ecx, [esp-8]
xchg ecx, ebp
{$else .CPUX64}
cmp byte ptr [r9 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + rax + OPCODE_MAIN]
xchg r8, r9
{$endif}
je movszx_reg_ptr_addr_value
jmp PRE_movszx_reg_ptr_addr
end;
{$endif}
// movzx
procedure TOpcodeBlock_x64.movzx(reg: reg_x64; v_reg: reg_x64);
const
OPCODE_MAIN = flag_x64 or flag_0f or ($C0B6{movsx} shl 8);
OPCODE_ALTER = flag_x64 or ($C088{mov} shl 8);
dif_rax_eax = rax-eax;
OPCODE_ALTER_DIF = OPCODE_ALTER - dif_rax_eax;
{$ifndef OPCODE_FASTEST}
var
info_reg, info_vreg: integer;
begin
{$ifdef OPCODE_TEST}
// todo проверка регистров
{$endif}
info_reg := reg_intel_info[byte(reg)];
if (byte(info_reg) = 8) then
begin
info_vreg := reg_intel_info[byte(v_reg)];
if (byte(info_vreg) = 4) then
begin
cmd_reg_reg(OPCODE_ALTER_DIF+ord(reg), v_reg{$ifdef OPCODE_MODES},cmd_mov{$endif});
exit;
end else
if ((info_reg or info_vreg) and rex_RXB = 0) then
System.Dec(reg, dif_rax_eax);
end;
movszx_reg_reg(OPCODE_MAIN or byte(reg), byte(v_reg){$ifdef OPCODE_MODES},cmd_movzx{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
push ebx
mov ebx, [offset reg_intel_info + edx*4]
{$else .CPUX64}
xchg rbx, r9
lea r11, [reg_intel_info]
mov ebx, [r11 + rdx*4]
{$endif}
cmp bl, 8
jne @call_std
and ebx, $ffffff00
{$ifdef CPUX86}
movzx ecx, cl
or ebx, [offset reg_intel_info + ecx*4]
{$else .CPUX64}
movzx eax, r8b
or ebx, [r11 + rax*4]
{$endif}
cmp bl, 4
jne @call_std_check_correcttion
add edx, OPCODE_ALTER_DIF
{$ifdef CPUX86}
pop ebx
{$else .CPUX64}
xchg rbx, r9
{$endif}
jmp cmd_reg_reg
@call_std_check_correcttion:
test ebx, rex_RXB
{$ifdef CPUX86}
lea ebx, [edx - dif_rax_eax]
{$else .CPUX64}
lea rbx, [rdx - dif_rax_eax]
{$endif}
cmovz edx, ebx
@call_std:
or edx, OPCODE_MAIN
{$ifdef CPUX86}
pop ebx
{$else .CPUX64}
xchg rbx, r9
{$endif}
jmp movszx_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.movzx(reg: reg_x64; ptr: size_ptr; const addr: address_x64);
const
OPCODE_MAIN = flag_x64 or flag_0f or ($B6{movsx} shl 8);
OPCODE_ALTER = flag_x64 or $0200 or ($88{mov} shl 8);
dif_rax_eax = rax-eax;
OPCODE_ALTER_DIF = OPCODE_ALTER - dif_rax_eax;
{$ifndef OPCODE_FASTEST}
var
info_reg, reg_opcode_ptr: integer;
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
info_reg := reg_intel_info[byte(reg)];
if (byte(info_reg) = 8) then
begin
if (ptr = dword_ptr) then
begin
// mov
reg_opcode_ptr := OPCODE_ALTER_DIF + ord(reg);
PRE_cmd_reg_addr(reg_opcode_ptr, addr{$ifdef OPCODE_MODES},cmd_mov{$endif});
exit;
end else
if (info_reg and rex_RXB = 0) then
System.Dec(reg, dif_rax_eax);
end;
// movzx
reg_opcode_ptr := OPCODE_MAIN or ord(reg) or (ord(ptr) shl 16);
PRE_movszx_reg_ptr_addr(reg_opcode_ptr, addr{$ifdef OPCODE_MODES},cmd_movzx{$endif});
end;
{$else}
const
rax_value = rax;
dword_ptr_offseted = ord(dword_ptr) shl 16;
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, addr
movzx ecx, cl
add esp, 8
sub edx, rax_value
shl ecx, 16
{$else .CPUX64}
movzx eax, r8b
sub edx, rax_value
shl eax, 16
lea r10, [reg_intel_info]
{$endif}
cmp edx, 15
{$ifdef CPUX86}
lea edx, [edx+rax_value]
{$else .CPUX64}
lea rdx, [rdx+rax_value]
{$endif}
ja @call_main
{$ifdef CPUX86}
cmp ecx, dword_ptr_offseted
{$else .CPUX64}
cmp eax, dword_ptr_offseted
{$endif}
jne @call_main_try_correction
@call_mov:
{$ifdef CPUX86}
mov ecx, [esp-4] // ret
cmp byte ptr [EBP + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [esp], ecx
mov ecx, [esp-8]
lea edx, [edx + OPCODE_ALTER_DIF]
xchg ecx, ebp
{$else .CPUX64}
cmp byte ptr [r9 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE_ALTER_DIF]
xchg r8, r9
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
@call_main_try_correction:
{$ifdef CPUX86}
test [offset reg_intel_info + edx*4], rex_RXB
{$else .CPUX64}
test [r10 + rdx*4], rex_RXB
{$endif}
jnz @call_main
sub edx, dif_rax_eax
@call_main:
{$ifdef CPUX86}
lea edx, [edx + ecx + OPCODE_MAIN]
mov ecx, [esp-4] // ret
cmp byte ptr [EBP + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [esp], ecx
mov ecx, [esp-8]
xchg ecx, ebp
{$else .CPUX64}
cmp byte ptr [r9 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + rax + OPCODE_MAIN]
xchg r8, r9
{$endif}
je movszx_reg_ptr_addr_value
jmp PRE_movszx_reg_ptr_addr
end;
{$endif}
// mul
procedure TOpcodeBlock_x64.mul(reg: reg_x64);
const
OPCODE = flag_x64 or ($E0F6{mul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_mul{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.mul(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or ($20F6{mul} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_mul{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// neg
procedure TOpcodeBlock_x64.neg(reg: reg_x64);
const
OPCODE = flag_x64 or ($D8F6{neg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_neg{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.neg(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or ($18F6{neg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_neg{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// lock neg
procedure TOpcodeBlock_x64.lock_neg(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_lock or ($18F6{neg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_lock_neg{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// not
procedure TOpcodeBlock_x64.not_(reg: reg_x64);
const
OPCODE = flag_x64 or ($D0F6{not} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_not{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.not_(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or ($10F6{not} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_not{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// lock not
procedure TOpcodeBlock_x64.lock_not(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_lock or ($10F6{not} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_lock_not{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// or
procedure TOpcodeBlock_x64.or_(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($C008{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_or{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.or_(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($C80C{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_or{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.or_(reg: reg_x64; const addr: address_x64);
const
OPCODE = flag_x64 or $0200 or ($08{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_or{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.or_(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($08{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_or{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.or_(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($0880{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_or{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock or
procedure TOpcodeBlock_x64.lock_or(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_lock or ($08{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_or{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.lock_or(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_lock or ($0880{or} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_or{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// pop
procedure TOpcodeBlock_x64.pop(reg: reg_x64_wq);
const
OPCODE = flag_x64 or ($5800{pop} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_pop{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.pop(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($008F{pop} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_pop{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// push
procedure TOpcodeBlock_x64.push(reg: reg_x64_wq);
const
OPCODE = flag_x64 or ($5000{push} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg(OPCODE or byte(reg){$ifdef OPCODE_MODES},cmd_push{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg
end;
{$endif}
procedure TOpcodeBlock_x64.push(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($30FF{push} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr(OPCODE or byte(ptr), addr{$ifdef OPCODE_MODES},cmd_push{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_ptr_addr_value
jmp PRE_cmd_ptr_addr
end;
{$endif}
// rcl
procedure TOpcodeBlock_x64.rcl_cl(reg: reg_x64);
const
OPCODE = flag_x64 or flag_extra or ($D0D2{rcl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_rcl{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.rcl(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($D0C0{rcl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_rcl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.rcl_cl(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($10D2{rcl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_rcl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x64.rcl(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($10C0{rcl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_rcl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// rcr
procedure TOpcodeBlock_x64.rcr_cl(reg: reg_x64);
const
OPCODE = flag_x64 or flag_extra or ($D8D2{rcr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_rcr{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.rcr(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($D8C0{rcr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_rcr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.rcr_cl(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($18D2{rcr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_rcr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x64.rcr(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($18C0{rcr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_rcr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// rol
procedure TOpcodeBlock_x64.rol_cl(reg: reg_x64);
const
OPCODE = flag_x64 or flag_extra or ($C0D2{rol} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_rol{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.rol(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($C0C0{rol} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_rol{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.rol_cl(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($00D2{rol} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_rol{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x64.rol(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($00C0{rol} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_rol{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// ror
procedure TOpcodeBlock_x64.ror_cl(reg: reg_x64);
const
OPCODE = flag_x64 or flag_extra or ($C8D2{ror} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_ror{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.ror(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($C8C0{ror} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_ror{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.ror_cl(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($08D2{ror} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_ror{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x64.ror(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($08C0{ror} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_ror{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// sal
procedure TOpcodeBlock_x64.sal_cl(reg: reg_x64);
const
OPCODE = flag_x64 or flag_extra or ($E0D2{sal} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_sal{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.sal(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($E0C0{sal} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_sal{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.sal_cl(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($20D2{sal} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_sal{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x64.sal(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($20C0{sal} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_sal{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// sar
procedure TOpcodeBlock_x64.sar_cl(reg: reg_x64);
const
OPCODE = flag_x64 or flag_extra or ($F8D2{sar} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_sar{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.sar(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($F8C0{sar} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_sar{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.sar_cl(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($38D2{sar} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_sar{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x64.sar(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($38C0{sar} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_sar{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// sbb
procedure TOpcodeBlock_x64.sbb(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($C018{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_sbb{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.sbb(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($D81C{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_sbb{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.sbb(reg: reg_x64; const addr: address_x64);
const
OPCODE = flag_x64 or $0200 or ($18{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_sbb{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.sbb(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($18{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_sbb{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.sbb(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($1880{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_sbb{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock sbb
procedure TOpcodeBlock_x64.lock_sbb(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_lock or ($18{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_sbb{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.lock_sbb(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_lock or ($1880{sbb} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_sbb{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// setcc
procedure TOpcodeBlock_x64.set_(cc: intel_cc; reg: reg_x64_bytes);
const
FLAGS = flag_x64;
{$ifndef OPCODE_FASTEST}
begin
setcmov_cc_regs(FLAGS or (ord(cc) shl 8) or byte(reg){$ifdef OPCODE_MODES},cmd_set{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
movzx ecx, cl
shl edx, 8
lea edx, [edx + ecx + FLAGS]
{$else .CPUX64}
movzx r8, r8b
shl edx, 8
lea rdx, [rdx + r8 + FLAGS]
{$endif}
jmp setcmov_cc_regs
end;
{$endif}
procedure TOpcodeBlock_x64.set_(cc: intel_cc; const addr: address_x64);
const
FLAGS = flag_x64;
{$ifndef OPCODE_FASTEST}
begin
PRE_setcmov_cc_addr(FLAGS or ord(cc), addr{$ifdef OPCODE_MODES},cmd_set{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + FLAGS]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + FLAGS]
{$endif}
je setcmov_cc_addr_value
jmp PRE_setcmov_cc_addr
end;
{$endif}
// shl
procedure TOpcodeBlock_x64.shl_cl(reg: reg_x64);
const
OPCODE = flag_x64 or flag_extra or ($E0D2{shl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_shl{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.shl_(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($E0C0{shl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_shl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.shl_cl(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($20D2{shl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_shl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x64.shl_(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($20C0{shl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_shl{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// shr
procedure TOpcodeBlock_x64.shr_cl(reg: reg_x64);
const
OPCODE = flag_x64 or flag_extra or ($E8D2{shr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистра
{$endif}
shift_reg_const_value(OPCODE or byte(reg), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_shr{$else}0{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.shr_(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($E8C0{shr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_shift_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_shr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_shift_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp shift_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.shr_cl(ptr: size_ptr; const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($28D2{shr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_shr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
push [esp]
lea edx, [edx + OPCODE]
mov [esp+4], offset ZERO_CONST_32
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
mov r9, offset ZERO_CONST_32
{$endif}
je cmd_ptr_addr_const_value
jmp PRE_cmd_ptr_addr_const
end;
{$endif}
procedure TOpcodeBlock_x64.shr_(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($28C0{shr} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_shr{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// shld
procedure TOpcodeBlock_x64.shld_cl(reg1, reg2: reg_x64);
const
OPCODE = flag_x64 or flag_0f or ($A5{shld_cl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистров
{$endif}
cmd_reg_reg_const_value((ord(reg2) shl 16) or OPCODE or byte(reg1), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_shld{$else}0{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
movzx edx, dl
shl ecx, 16
lea edx, [edx + ecx + OPCODE]
{$else .CPUX64}
movzx eax, r8b
movzx edx, dl
shl eax, 16
lea rdx, [rdx + rax + OPCODE]
{$endif}
jmp cmd_reg_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.shld(reg1, reg2: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_0f or ($A4{shld} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_reg_const((ord(reg2) shl 16) or OPCODE or byte(reg1), v_const{$ifdef OPCODE_MODES},cmd_shld{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
movzx ecx, cl
mov ebp, [esp+8] // v_const
shl ecx, 16
cmp [EBP].TOpcodeConst.FKind, ckValue
lea edx, [edx + ecx + OPCODE]
mov ecx, [esp+4] // ret
mov [esp+8], ecx
xchg ecx, ebp
mov ebp, [esp]
lea esp, [esp+8]
{$else .CPUX64}
movzx eax, r8b
xchg r8, r9
shl eax, 16
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + rax + OPCODE]
{$endif}
jne PRE_cmd_reg_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.shld_cl(const addr: address_x64; reg2: reg_x64);
const
OPCODE = flag_x64 or flag_0f or ($A5{shld_cl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr_reg_const(OPCODE or byte(reg2), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_shld{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
push [esp]
or ecx, OPCODE
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [esp+4], offset ZERO_CONST_32
xchg edx, ecx
{$else .CPUX64}
lea rax, [ZERO_CONST_32]
movzx r8, r8b
push [rsp]
or r8d, OPCODE
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [rsp+8], rax
xchg rdx, r8
{$endif}
je cmd_addr_reg_const_value
jmp PRE_cmd_addr_reg_const
end;
{$endif}
procedure TOpcodeBlock_x64.shld(const addr: address_x64; reg2: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_0f or ($A4{shld} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr_reg_const(OPCODE or byte(reg2), addr, v_const{$ifdef OPCODE_MODES},cmd_shld{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
mov ebp, [esp+8] // v_const
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea ecx, [ecx + OPCODE]
xchg edx, ecx
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_addr_reg_const_value
@call_std:
pop ebp
jmp PRE_cmd_addr_reg_const
{$else .CPUX64}
movzx r8, r8b
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea r8, [r8 + OPCODE]
xchg rdx, r8
jne PRE_cmd_addr_reg_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_addr_reg_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_addr_reg_const_value
{$endif}
end;
{$endif}
// shrd
procedure TOpcodeBlock_x64.shrd_cl(reg1, reg2: reg_x64);
const
OPCODE = flag_x64 or flag_0f or ($AD{shrd_cl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
{$ifdef OPCODE_TEST}
// todo проверка регистров
{$endif}
cmd_reg_reg_const_value((ord(reg2) shl 16) or OPCODE or byte(reg1), {$ifdef OPCODE_MODES}ZERO_CONST_32,cmd_shrd{$else}0{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
movzx edx, dl
shl ecx, 16
lea edx, [edx + ecx + OPCODE]
{$else .CPUX64}
movzx eax, r8b
movzx edx, dl
shl eax, 16
lea rdx, [rdx + rax + OPCODE]
{$endif}
jmp cmd_reg_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.shrd(reg1, reg2: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_0f or ($AC{shrd} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_reg_const((ord(reg2) shl 16) or OPCODE or byte(reg1), v_const{$ifdef OPCODE_MODES},cmd_shrd{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
movzx ecx, cl
mov ebp, [esp+8] // v_const
shl ecx, 16
cmp [EBP].TOpcodeConst.FKind, ckValue
lea edx, [edx + ecx + OPCODE]
mov ecx, [esp+4] // ret
mov [esp+8], ecx
xchg ecx, ebp
mov ebp, [esp]
lea esp, [esp+8]
{$else .CPUX64}
movzx eax, r8b
xchg r8, r9
shl eax, 16
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + rax + OPCODE]
{$endif}
jne PRE_cmd_reg_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.shrd_cl(const addr: address_x64; reg2: reg_x64);
const
OPCODE = flag_x64 or flag_0f or ($AD{shrd_cl} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr_reg_const(OPCODE or byte(reg2), addr, ZERO_CONST_32{$ifdef OPCODE_MODES},cmd_shrd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
push [esp]
or ecx, OPCODE
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [esp+4], offset ZERO_CONST_32
xchg edx, ecx
{$else .CPUX64}
lea rax, [ZERO_CONST_32]
movzx r8, r8b
push [rsp]
or r8d, OPCODE
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov [rsp+8], rax
xchg rdx, r8
{$endif}
je cmd_addr_reg_const_value
jmp PRE_cmd_addr_reg_const
end;
{$endif}
procedure TOpcodeBlock_x64.shrd(const addr: address_x64; reg2: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_0f or ($AC{shrd} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr_reg_const(OPCODE or byte(reg2), addr, v_const{$ifdef OPCODE_MODES},cmd_shrd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
movzx ecx, cl
mov ebp, [esp+8] // v_const
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea ecx, [ecx + OPCODE]
xchg edx, ecx
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_addr_reg_const_value
@call_std:
pop ebp
jmp PRE_cmd_addr_reg_const
{$else .CPUX64}
movzx r8, r8b
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea r8, [r8 + OPCODE]
xchg rdx, r8
jne PRE_cmd_addr_reg_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_addr_reg_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_addr_reg_const_value
{$endif}
end;
{$endif}
// sub
procedure TOpcodeBlock_x64.sub(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($C028{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_sub{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.sub(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($E82C{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_sub{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.sub(reg: reg_x64; const addr: address_x64);
const
OPCODE = flag_x64 or $0200 or ($28{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_sub{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.sub(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($28{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_sub{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.sub(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($2880{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_sub{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock sub
procedure TOpcodeBlock_x64.lock_sub(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_lock or ($28{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_sub{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.lock_sub(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_lock or ($2880{sub} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_sub{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// test
procedure TOpcodeBlock_x64.test(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($C084{test} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_test{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.test(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_extra or ($C0A8{test} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_test{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.test(reg: reg_x64; const addr: address_x64);
const
OPCODE = flag_x64 or $0200 or ($84{test} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_test{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.test(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($84{test} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_test{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.test(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($00F6{test} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_test{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// xadd
procedure TOpcodeBlock_x64.xadd(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_0f or ($C0C0{xadd} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_xadd{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.xadd(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_0f or ($C0{xadd} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_xadd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
// lock xadd
procedure TOpcodeBlock_x64.lock_xadd(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_lock or flag_0f or ($C0{xadd} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_xadd{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
// xchg
procedure TOpcodeBlock_x64.xchg(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($C086{xchg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_xchg{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.xchg(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($86{xchg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_xchg{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
// lock xchg
procedure TOpcodeBlock_x64.lock_xchg(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_lock or ($86{xchg} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_xchg{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
// xor
procedure TOpcodeBlock_x64.xor_(reg: reg_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($C030{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
cmd_reg_reg(OPCODE or byte(reg), v_reg{$ifdef OPCODE_MODES},cmd_xor{$endif});
end;
{$else}
asm
movzx edx, dl
or edx, OPCODE
jmp cmd_reg_reg
end;
{$endif}
procedure TOpcodeBlock_x64.xor_(reg: reg_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($F034{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_const(OPCODE or byte(reg), v_const{$ifdef OPCODE_MODES},cmd_xor{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp [ECX].TOpcodeConst.FKind, ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp [R8].TOpcodeConst.FKind, ckValue
lea rdx, [rdx + OPCODE]
{$endif}
jne PRE_cmd_reg_const
{$ifdef CPUX86}
mov ecx, [ECX].TOpcodeConst.F.Value
{$else .CPUX64}
mov r8d, [R8].TOpcodeConst.F.Value
{$endif}
jmp cmd_reg_const_value
end;
{$endif}
procedure TOpcodeBlock_x64.xor_(reg: reg_x64; const addr: address_x64);
const
OPCODE = flag_x64 or $0200 or ($30{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(reg), addr{$ifdef OPCODE_MODES},cmd_xor{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.xor_(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or ($30{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_xor{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.xor_(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or ($3080{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_xor{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
// lock xor
procedure TOpcodeBlock_x64.lock_xor(const addr: address_x64; v_reg: reg_x64);
const
OPCODE = flag_x64 or flag_lock or ($30{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_reg_addr(OPCODE or byte(v_reg), addr{$ifdef OPCODE_MODES},cmd_lock_xor{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
xchg edx, ecx
{$else .CPUX64}
xchg rdx, r8
{$endif}
movzx edx, dl
{$ifdef CPUX86}
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
{$endif}
je cmd_reg_addr_value
jmp PRE_cmd_reg_addr
end;
{$endif}
procedure TOpcodeBlock_x64.lock_xor(ptr: size_ptr; const addr: address_x64; const v_const: const_32);
const
OPCODE = flag_x64 or flag_lock or ($3080{xor} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_ptr_addr_const(OPCODE or byte(ptr), addr, v_const{$ifdef OPCODE_MODES},cmd_lock_xor{$endif});
end;
{$else}
asm
movzx edx, dl
{$ifdef CPUX86}
mov ebp, [esp+8] // v_const
cmp byte ptr [ECX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea edx, [edx + OPCODE]
jne @call_std
cmp [EBP].TOpcodeConst.FKind, ckValue
mov ebp, [EBP].TOpcodeConst.F.Value
jne @call_std
mov [esp+8], ebp // value
pop ebp
jmp cmd_ptr_addr_const_value
@call_std:
pop ebp
jmp PRE_cmd_ptr_addr_const
{$else .CPUX64}
cmp byte ptr [R8 + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
lea rdx, [rdx + OPCODE]
jne PRE_cmd_ptr_addr_const
cmp [R9].TOpcodeConst.FKind, ckValue
jne PRE_cmd_ptr_addr_const
mov r9d, [R9].TOpcodeConst.F.Value
jmp cmd_ptr_addr_const_value
{$endif}
end;
{$endif}
procedure TOpcodeBlock_x64.cmpsq(reps: intel_rep=REP_SINGLE);
const
OPCODE = $A748{cmpsq};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_cmpsq{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_x64.insq(reps: intel_rep=REP_SINGLE);
const
OPCODE = $6D48{insq};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_insq{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_x64.scasq(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AF48{scasq};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_scasq{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_x64.stosq(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AB48{stosq};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_stosq{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_x64.lodsq(reps: intel_rep=REP_SINGLE);
const
OPCODE = $AD48{lodsq};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_lodsq{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
procedure TOpcodeBlock_x64.movsq(reps: intel_rep=REP_SINGLE);
const
OPCODE = $A548{movsq};
{$ifndef OPCODE_FASTEST}
begin
cmd_rep_bwdq(reps, OPCODE{$ifdef OPCODE_MODES}, cmd_movsq{$endif});
end;
{$else}
asm
{$ifdef CPUX86}
mov ecx, OPCODE
{$else .CPUX64}
mov r8d, OPCODE
{$endif}
jmp cmd_rep_bwdq
end;
{$endif}
// FPU и память
procedure TOpcodeBlock_x64.fbld(const addr: address_x64);
const
OPCODE = flag_x64 or ($20DF{fbld} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fbld{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fbstp(const addr: address_x64);
const
OPCODE = flag_x64 or ($30DF{fbstp} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fbstp{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fldcw(const addr: address_x64);
const
OPCODE = flag_x64 or ($28D9{fldcw} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fldcw{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fldenv(const addr: address_x64);
const
OPCODE = flag_x64 or ($20D9{flden} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fldenv{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fsave(const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($30DD{fsave} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fsave{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fnsave(const addr: address_x64);
const
OPCODE = flag_x64 or ($30DD{fnsave} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fnsave{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fstcw(const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($38D9{fstcw} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fstcw{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fnstcw(const addr: address_x64);
const
OPCODE = flag_x64 or ($38D9{fnstcw} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fnstcw{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fstenv(const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($30D9{fstenv} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fstenv{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fnstenv(const addr: address_x64);
const
OPCODE = flag_x64 or ($30D9{fnstenv} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fnstenv{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fstsw(const addr: address_x64);
const
OPCODE = flag_x64 or flag_extra or ($38DD{fstsw} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fstsw{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
procedure TOpcodeBlock_x64.fnstsw(const addr: address_x64);
const
OPCODE = flag_x64 or ($38DD{fnstsw} shl 8);
{$ifndef OPCODE_FASTEST}
begin
PRE_cmd_addr(OPCODE, addr{$ifdef OPCODE_MODES},cmd_fnstsw{$endif})
end;
{$else}
asm
{$ifdef CPUX86}
cmp byte ptr [EDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov ecx, OPCODE
xchg edx, ecx
{$else .CPUX64}
cmp byte ptr [RDX + TOpcodeAddress_offset + TOpcodeConst.FKind], ckValue
mov r8d, OPCODE
xchg rdx, r8
{$endif}
je cmd_addr_value
jmp PRE_cmd_addr
end;
{$endif}
{ TOpcodeBlock_ARM }
const
arm_cc_to_intel: array[arm_cc] of intel_cc = (_e{eq}, _ne{ne}, _nc{cs}, _ae{hs=cs},
_c{cc}, _b{lo=cc}, _s{mi}, _ns{pl}, _o{vs}, _no{vc}, _a{hi},
_be{ls}, _ge{ge}, _l{lt}, _g{gt}, _le{le});
function TOpcodeBlock_ARM.AppendBlock: POpcodeBlock_ARM;
const
BLOCK_SIZE = sizeof(TOpcodeBlock);
{$ifdef PUREPASCAL}
begin
Result := POpcodeBlock_ARM(inherited AppendBlock(BLOCK_SIZE));
end;
{$else}
asm
mov edx, BLOCK_SIZE
jmp TOpcodeBlock.AppendBlock
end;
{$endif}
procedure TOpcodeBlock_ARM.b{jmp}(block: POpcodeBlock_ARM);
begin
cmd_jump_block(-1{jmp}, block);
end;
procedure TOpcodeBlock_ARM.b{jcc}(cc: arm_cc; block: POpcodeBlock_ARM);
begin
{$ifdef OPCODE_TEST}if (ord(cc) > ord(high(arm_cc))) then raise_parameter;{$endif}
cmd_jump_block(shortint(arm_cc_to_intel[cc]), block);
end;
procedure TOpcodeBlock_ARM.bl{call}(block: POpcodeBlock_ARM);
begin
cmd_jump_block(-2{call}, block);
end;
{$ifdef OPCODE_MODES}
procedure TOpcodeBlock_ARM.b{jmp}(ProcName: pansichar);
begin
cmd_textjump_proc(-1{jmp}, ProcName);
end;
procedure TOpcodeBlock_ARM.b{jcc}(cc: arm_cc; ProcName: pansichar);
begin
{$ifdef OPCODE_TEST}if (ord(cc) > ord(high(arm_cc))) then raise_parameter;{$endif}
cmd_textjump_proc(shortint(arm_cc_to_intel[cc]), ProcName);
end;
procedure TOpcodeBlock_ARM.bl{call}(ProcName: pansichar);
begin
cmd_textjump_proc(-2{call}, ProcName);
end;
{$endif}
{ TOpcodeBlock_VM }
function TOpcodeBlock_VM.AppendBlock: POpcodeBlock_VM;
const
BLOCK_SIZE = sizeof(TOpcodeBlock);
{$ifdef PUREPASCAL}
begin
Result := POpcodeBlock_VM(inherited AppendBlock(BLOCK_SIZE));
end;
{$else}
asm
mov edx, BLOCK_SIZE
jmp TOpcodeBlock.AppendBlock
end;
{$endif}
{ TOpcodeProc_Intel }
// универсальная функция, которая используется для последнего блока при фиксации: ret(n)
// делается, подглядывая в универсальную функцию добавления команды
(*
procedure TOpcodeBlock_Intel.ret(const count: word=0);
var
Result: POpcodeCmd;
begin
{$ifdef OPCODE_MODES}
if (P.Proc.Mode = omAssembler) then
begin
if (count = 0) then Result := AddCmdText(PShortString(@cmd_ret))
else Result := AddCmdText('ret %d', [count]);
Result.F.Param := 128{текст}+0{ret(n)};
end else
{$endif}
begin
// cmLeave команды не должны спариваться с другими бинарными командами (может потом изменю логику)
P.Proc.FLastBinaryCmd := nil;
// добавляем
if (count = 0) then Result := AddSmartBinaryCmd($00c30000, 0)
else Result := AddSmartBinaryCmd($00c20002, count);
// Result.F.Param := 0{бинарный}+0{ret(n)};
end;
// указываем, что команда cmLeave
Result.F.Mode := cmLeave;
end;
*)
procedure TOpcodeProc_Intel_FillLastRetCmd(var Storage: TFixupedStorage; const count: word);
{$ifdef OPCODE_MODES}
const
RET_FMT: array[0..5] of ansichar = 'ret %d';
{$endif}
begin
{$ifdef OPCODE_MODES}
if (Storage.Proc.Mode = omAssembler) then
begin
if (count = 0) then
begin
// Storage.LastRetCmd.Str := @cmd_ret;
Storage.LastRetCmd.Str := PShortString(@cmd_ret);
end else
begin
// Storage.LastRetCmd.Str := Format('ret %d', [count]);
pbyte(@Storage.LastRetCmd.Chars)^ := SysUtils.FormatBuf(Storage.LastRetCmd.Chars[1], sizeof(Storage.LastRetCmd.Chars)-sizeof(byte),
RET_FMT, Length(RET_FMT), [count]);
Storage.LastRetCmd.Str := PShortString(@Storage.LastRetCmd.Chars);
end;
Storage.LastRetCmd.Cmd.F.ModeParam := ord(cmLeave) + ((128{текст}+0{ret(n)}) shl 8);
end else
{$endif}
begin
if (count = 0) then
begin
Storage.LastRetCmd.c3 := $c3;
Storage.LastRetCmd.Cmd.F.Size := 1;
end else
begin
Storage.LastRetCmd.c2 := $c2;
Storage.LastRetCmd.i16 := count;
Storage.LastRetCmd.Cmd.F.Size := 3;
end;
Storage.LastRetCmd.Cmd.F.ModeParam := ord(cmLeave) + ((0{бинарный}+0{ret(n)}) shl 8);
end;
end;
// функция, которая вызывается для архитектур x86 и x64 (из калбека TOpcodeProc_Intel)
// задача функции - прописать бинарные прыжки для бинарного варианта и для гибрида
procedure IntelRealizeBinaryJumps(var Storage: TFixupedStorage);
const
SMALL_JMP = $EB;
SMALL_JCC = $70;
BIG_CALL = $E8;
BIG_JMP = $E9;
BIG_JCC = $800F;
var
Block: PFixupedBlock;
i: integer;
Offset: integer;
begin
Block := pointer(Storage.Blocks);
for i := 0 to Storage.BlocksCount-1 do
begin
case Block.Kind of
fkGlobalJumpBlock: {$ifdef OPCODE_MODES}if (Storage.Mode = omBinary) then{$endif}
begin
// зануляем
pword(@Block.JumpBuffer)^ := 0;
pinteger(@Block.JumpBuffer[2])^ := 0;
// прописываем
case Block.cc_ex of
-2{call}: begin
Block.JumpBuffer[0] := BIG_CALL;
end;
-1{jmp}: begin
Block.JumpBuffer[0] := BIG_JMP;
end;
else
{jcc}
pword(@Block.JumpBuffer)^ := BIG_JCC;
end;
end;
fkLocalJumpBlock: begin
if (Block.Size = SMALL_JUMP_SIZE) then
begin
// малый прыжок
// сначала смещение
Block.JumpBuffer[1] := Block.JumpOffset - SMALL_JUMP_SIZE;
// потом вариант первый опкодный байт
if (Block.cc_ex = -1{jmp}) then Block.JumpBuffer[0] := SMALL_JMP
else Block.JumpBuffer[0] := SMALL_JCC + cc_intel_info[intel_cc(Block.cc_ex)];
end else
begin
// большой прыжок
Offset := Block.JumpOffset - SMALL_JUMP_SIZE;
case Block.cc_ex of
-2{call}: begin
Block.JumpBuffer[0] := BIG_CALL;
pinteger(@Block.JumpBuffer[1])^ := Offset;
end;
-1{jmp}: begin
Block.JumpBuffer[0] := BIG_JMP;
pinteger(@Block.JumpBuffer[1])^ := Offset;
end;
else
{jcc}
pword(@Block.JumpBuffer)^ := BIG_JCC + ord(cc_intel_info[intel_cc(Block.cc_ex)]) shl 8;
pinteger(@Block.JumpBuffer[2])^ := Offset;
end;
end;
end;
fkInline: begin
// в гибриде(и особенно в бинарном) вся последовательность бинарная
// надо прописать условный прыжок (буфер под него в конце)
if (Block.cc_ex >= 0) then
begin
pword(@Block.InlineBlocks[Block.InlineBlocksCount])^ :=
SMALL_JCC + (ord(cc_intel_info[intel_cc(Block.cc_ex)]) shl 8);
end;
end;
end;
inc(Block);
end;
end;
procedure TOpcodeProc_Intel_Callback(const Mode: integer; var Storage: TFixupedStorage);
var
i: integer;
begin
case Mode of
0: // заполнить информационные таблицы по прыжкам JumpsInfo
with Storage.JumpsInfo do
begin
FillChar(small_sizes, sizeof(small_sizes), {#2}SMALL_JUMP_SIZE);
small_sizes[-2{call}] := 5;
FillChar(big_sizes, sizeof(big_sizes), #6);
big_sizes[-2{call}] := 5;
big_sizes[-1{jmp}] := 5;
for i := 0 to ord(high(intel_cc)) do
begin
// jcc
low_ranges[i] := -126;
high_ranges[i] := 131;
end;
low_ranges[-1{jmp}] := -126;
high_ranges[-1{jmp}] := 130;
low_ranges[-2{call}] := 0;
high_ranges[-2{call}] := 0;
{$ifdef OPCODE_MODES}
names := pointer(@cc_intel_names);
{$endif}
end;
1: begin
// заполнить структуру LastRetCmd
TOpcodeProc_Intel_FillLastRetCmd(Storage, Storage.Proc.RetN);
end;
2: begin
// бинарная реализация прыжков
IntelRealizeBinaryJumps(Storage);
end;
end;
end;
constructor TOpcodeProc_Intel.Create(const AHeap: TOpcodeHeap=nil{$ifdef OPCODE_MODES}; const AMode: TOpcodeMode=omBinary{$endif});
begin
inherited;
@FCallback := @TOpcodeProc_Intel_Callback;
end;
{ TOpcodeProc_ARM }
procedure TOpcodeProc_ARM_Callback(const Mode: integer; var Storage: TFixupedStorage);
begin
case Mode of
0: begin
// заполнить информационные таблицы по прыжкам JumpsInfo
// todo
end;
1: begin
// заполнить структуру LastRetCmd
// todo
end;
2: begin
// бинарная реализация прыжков
// todo
end;
end;
end;
constructor TOpcodeProc_ARM.Create(const AHeap: TOpcodeHeap=nil{$ifdef OPCODE_MODES}; const AMode: TOpcodeMode=omBinary{$endif});
begin
inherited;
@FCallback := @TOpcodeProc_ARM_Callback;
end;
{ TOpcodeProc_VM }
procedure TOpcodeProc_VM_Callback(const Mode: integer; var Storage: TFixupedStorage);
begin
case Mode of
0: begin
// заполнить информационные таблицы по прыжкам JumpsInfo
// todo
end;
1: begin
// заполнить структуру LastRetCmd
// todo
end;
2: begin
// бинарная реализация прыжков
// todo
end;
end;
end;
constructor TOpcodeProc_VM.Create(const AHeap: TOpcodeHeap{$ifdef OPCODE_MODES};const AMode: TOpcodeMode{$endif});
begin
inherited;
@FCallback := @TOpcodeProc_VM_Callback;
end;
{ TOpcodeStorage_x86 }
{$ifdef CPUX86}
constructor TOpcodeStorage_x86.CreateJIT(const AHeap: TOpcodeHeap);
begin
FJIT := true;
Create(AHeap {всегда Binary});
end;
{$endif}
function TOpcodeStorage_x86.CreateProc(const AOwnHeap: boolean=false): TOpcodeProc_x86;
begin
Result := TOpcodeProc_x86(InternalCreateProc(TOpcodeProc_x86, @TOpcodeProc_Intel_Callback, AOwnHeap));
end;
{ TOpcodeStorage_x64 }
{$ifdef CPUX64}
constructor TOpcodeStorage_x64.CreateJIT(const AHeap: TOpcodeHeap);
begin
FJIT := true;
Create(AHeap {всегда Binary});
end;
{$endif}
function TOpcodeStorage_x64.CreateProc(const AOwnHeap: boolean=false): TOpcodeProc_x64;
begin
Result := TOpcodeProc_x64(InternalCreateProc(TOpcodeProc_x64, @TOpcodeProc_Intel_Callback, AOwnHeap));
end;
{ TOpcodeStorage_ARM }
function TOpcodeStorage_ARM.CreateProc(const AOwnHeap: boolean=false): TOpcodeProc_ARM;
begin
Result := TOpcodeProc_ARM(InternalCreateProc(TOpcodeProc_ARM, @TOpcodeProc_ARM_Callback, AOwnHeap));
end;
{ TOpcodeStorage_VM }
function TOpcodeStorage_VM.CreateProc(const AOwnHeap: boolean=false): TOpcodeProc_VM;
begin
Result := TOpcodeProc_VM(InternalCreateProc(TOpcodeProc_VM, @TOpcodeProc_VM_Callback, AOwnHeap));
end;
end.
|
unit ProcessorInterface;
interface
uses uCreditCardFunction;
type
IProcessor = Interface
procedure SetTerminalID(arg_terminalID: String);
function GetTerminalID(): String;
procedure SetDeviceInitialized(arg_initialized: Boolean);
function IsDeviceInitialized(): Boolean;
function GetClassTypeName(): String;
procedure SetPadType(arg_name: String);
function GetPadType(): String;
procedure SetSecureDevice(arg_sdcode: String);
function GetSecureDevice(): String;
procedure SetTax(arg_tax: double);
function GetTax(): Double;
procedure SetInvoiceNo(arg_invoiceNo: String);
function GetInvoiceNo(): String;
procedure SetOperatorID(arg_operatorID: String);
function GetOperatorID(): String;
procedure SetAuthCode(arg_authCode: String);
function GetAuthCode(): String;
procedure SetResultAcqRefData(arg_acqRefData: String);
function GetResultAcqRefData(): String;
procedure SetRefNo(arg_refNo: String);
function GetRefNo(): String;
procedure SetAcctNo(arg_acctNo: String);
function GetAcctNo(): String;
procedure SetLastDigits(arg_lastDigits: String);
function GetLastDigits(): String;
procedure SetMerchantID(arg_merchantID: String);
function GetMerchantID(): String;
procedure SetPurchase(arg_purchase: Currency);
function GetPurchase(): Currency;
procedure SetAuthorize(arg_authorize: Currency);
function GetAuthorize(): Currency;
procedure SetSequenceNo(arg_sequence: String);
function GetSequenceNo(): String;
procedure SetTrueCardTypeName(arg_name: String);
function GetTrueCardTypeName(): String;
procedure SetCardType(arg_type: String);
function GetCardType(): String;
procedure SetEntryMethod(arg_entryMethod: String);
function GetEntryMethod(): String;
procedure SetAppLabel(arg_appLabel: String);
function GetAppLabel(): String;
procedure SetRecordNo(arg_recordNo: String);
function GetRecordNo(): String;
procedure SetIPPort(arg_port: String);
function GetIPPort(): String;
procedure SetIPAddress(arg_address: String);
function GetIPAddress(): String;
function GetMerchandID(): String;
procedure SetIPProcessorAddress(arg_address: String);
function GetIPProcessorAddres(): String;
procedure SetConnectionTimeOut(arg_timeOut: Integer);
function GetConnectionTimeOut(): Integer;
procedure SetResponseTimeOut(arg_responseTimeOut: Integer);
function GetResponseTimeOut(): Integer;
procedure SetMessage(arg_msg: String);
function GetMessage(): String;
procedure SetGiftIP(arg_giftIP: String);
function GetGiftIP(): String;
procedure SetGiftPort(arg_giftPort: String);
function GetGiftPort(): String;
procedure SetGiftMerchantID(arg_merchantid: String);
function GetGiftMerchantID(): String;
procedure SetDialUpBridge(arg_dialBridge: Boolean);
function GetDialUpBridge(): Boolean;
procedure SetManualStreeAddress(arg_address: String);
function GetManualStreeAddress(): String;
procedure SetManualZipCode(arg_zipCode: String);
function GetManualZipCode(): String;
procedure SetManualCVV2(arg_cvv2: String);
function GetManualCvv2(): String;
procedure SetManualCardNumber(arg_cardNumber: String);
function GetManualCardNumber(): String;
procedure SetManualMemberName(arg_member: String);
function GetManualMemberName(): String;
procedure SetManualCvv(arg_cvv: String);
function GetManualCvv(): String;
procedure SetExpireDate(arg_date: String);
function GetExpireDate(): String;
procedure SetCustomerCode(arg_customerCode: String);
function GetCustomerCode(): String;
procedure SetIdPaymentType(arg_paymentType: Integer);
function GetIdPaymentType(): Integer;
procedure SetTransactionResult(arg_result: TTransactionReturn);
function GetTransactionResult(): TTransactionReturn;
procedure SetBalance(arg_balance: Currency);
function GetBalance(): Currency;
procedure SetTransactionErrorCode(arg_transerror: String);
function GetransactionErrorCode(): String;
// methods bellow are only to EMV transactions
procedure SetDateTransaction(arg_date: String);
function GetDateTransaction(): String;
procedure SetTimeTransaction(arg_time: String);
function GetTimeTransaction(): String;
procedure SetLabelAID(arg_label: String);
function GetLabelAID(): String;
procedure SetLabelTVR(arg_label: String);
function GetLabelTVR(): String;
procedure SetLabelIAD(arg_label: String);
function GetLAbelIAD(): String;
procedure SetLabelTSI(arg_label: String);
function GetLabelTSI(): String;
procedure SetLabelARC(arg_label: String);
function GetLabelARC(): String;
procedure SetLabelCVM(arg_label: String);
function GetLabelCVM(): String;
procedure SetTrancode(arg_trancode: String);
function GetTrancode(): String;
// Pin Pad Parameters
{ //PinPad
fPinPad.Device := ReadString('PinPadDevice');
fPinPad.Baud := ReadString('PinPadBaud');
fPinPad.Parity := ReadString('PinPadParity');
fPinPad.DataBits := ReadString('PinPadDataBits');
fPinPad.Comm := ReadString('PinPadComm');
fPinPad.EncryptMethod := ReadString('PinEncryptMethod');
fPinPad.TimeOut := ReadString('PinTimeOut');
}
end;
implementation
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Spatial partitioning related code that also uses scene objects
}
unit VXS.SpatialPartitioning;
interface
uses
VXS.OpenGL,
VXS.Scene,
VXS.Coordinates,
VXS.Win64Viewer,
VXS.SpacePartition,
VXS.VectorGeometry,
VXS.GeometryBB,
VXS.RenderContextInfo,
VXS.State;
type
{ Object for holding scene objects in a spatial partitioning }
TVXSceneObj = class(TSpacePartitionLeaf)
public
Obj: TVXBaseSceneObject;
procedure UpdateCachedAABBAndBSphere; override;
constructor CreateObj(Owner: TSectoredSpacePartition; aObj: TVXBaseSceneObject);
destructor Destroy; override;
end;
{ Render a spacial partitioning descending from TSectoredSpacePartition
(octree and quadtree) as a grid - great for debugging and visualisation }
procedure RenderSpatialPartitioning(var rci: TVXRenderContextInfo; const Space: TSectoredSpacePartition);
{ Create an extended frustum from a SceneViewer - this makes the unit
specific to the windows platform! }
function ExtendedFrustumMakeFromSceneViewer(const AFrustum: TFrustum; const vWidth, vHeight: integer; AVKCamera: TVXCamera)
: TExtendedFrustum; overload;
function ExtendedFrustumMakeFromSceneViewer(const AFrustum: TFrustum; const AVXSceneViewer: TVXSceneViewer)
: TExtendedFrustum; overload;
{ Renders an AABB as a line }
procedure RenderAABB(var rci: TVXRenderContextInfo; AABB: TAABB; w, r, g, b: single); overload;
procedure RenderAABB(var rci: TVXRenderContextInfo; AABB: TAABB); overload;
// -------------------------------------------------------------------
implementation
// -------------------------------------------------------------------
uses
VXS.VectorTypes,
VXS.Context;
procedure RenderAABB(var rci: TVXRenderContextInfo; AABB: TAABB);
begin
RenderAABB(rci, AABB, 1, 0.8, 0.8, 0.8);
end;
procedure RenderAABB(var rci: TVXRenderContextInfo; AABB: TAABB; w, r, g, b: single);
begin
glColor3f(r, g, b);
rci.VXStates.LineWidth := w;
glBegin(GL_LINE_STRIP);
glVertex3f(AABB.min.X, AABB.min.Y, AABB.min.Z);
glVertex3f(AABB.min.X, AABB.max.Y, AABB.min.Z);
glVertex3f(AABB.max.X, AABB.max.Y, AABB.min.Z);
glVertex3f(AABB.max.X, AABB.min.Y, AABB.min.Z);
glVertex3f(AABB.min.X, AABB.min.Y, AABB.min.Z);
glVertex3f(AABB.min.X, AABB.min.Y, AABB.max.Z);
glVertex3f(AABB.min.X, AABB.max.Y, AABB.max.Z);
glVertex3f(AABB.max.X, AABB.max.Y, AABB.max.Z);
glVertex3f(AABB.max.X, AABB.min.Y, AABB.max.Z);
glVertex3f(AABB.min.X, AABB.min.Y, AABB.max.Z);
glEnd;
glBegin(GL_LINES);
glVertex3f(AABB.min.X, AABB.max.Y, AABB.min.Z);
glVertex3f(AABB.min.X, AABB.max.Y, AABB.max.Z);
glVertex3f(AABB.max.X, AABB.max.Y, AABB.min.Z);
glVertex3f(AABB.max.X, AABB.max.Y, AABB.max.Z);
glVertex3f(AABB.max.X, AABB.min.Y, AABB.min.Z);
glVertex3f(AABB.max.X, AABB.min.Y, AABB.max.Z);
glEnd;
end;
procedure RenderSpatialPartitioning(var rci: TVXRenderContextInfo; const Space: TSectoredSpacePartition);
procedure RenderSectorNode(Node: TSectorNode);
var
i: integer;
AABB: TAABB;
begin
if Node.NoChildren then
begin
AABB := Node.AABB;
if Node.RecursiveLeafCount > 0 then
RenderAABB(rci, AABB, 1, 0, 0, 0)
else
RenderAABB(rci, AABB, 1, 0.8, 0.8, 0.8) // }
end
else
begin
for i := 0 to Node.ChildCount - 1 do
RenderSectorNode(Node.Children[i]);
end;
end;
begin
rci.VXStates.Disable(stLighting);
RenderSectorNode(Space.RootNode);
end;
function ExtendedFrustumMakeFromSceneViewer(const AFrustum: TFrustum; const AVXSceneViewer: TVXSceneViewer): TExtendedFrustum;
// old version
begin
Assert(Assigned(AVXSceneViewer.Camera), 'VXSceneViewer must have camera specified!');
result := ExtendedFrustumMake(AFrustum, AVXSceneViewer.Camera.NearPlane, AVXSceneViewer.Camera.DepthOfView,
AVXSceneViewer.FieldOfView, AVXSceneViewer.Camera.Position.AsAffineVector, AVXSceneViewer.Camera.Direction.AsAffineVector);
end;
function ExtendedFrustumMakeFromSceneViewer(const AFrustum: TFrustum; const vWidth, vHeight: integer; AVKCamera: TVXCamera)
: TExtendedFrustum; // changed version
var
buffov: single;
begin
if vWidth < vHeight then
buffov := AVKCamera.GetFieldOfView(vWidth)
else
buffov := AVKCamera.GetFieldOfView(vHeight);
result := ExtendedFrustumMake(AFrustum, AVKCamera.NearPlane, AVKCamera.DepthOfView, buffov, AVKCamera.Position.AsAffineVector,
AVKCamera.Direction.AsAffineVector);
end;
// --------- TVXSceneObj ------------
constructor TVXSceneObj.CreateObj(Owner: TSectoredSpacePartition; aObj: TVXBaseSceneObject);
begin
Obj := aObj;
inherited CreateOwned(Owner);
end;
destructor TVXSceneObj.Destroy;
begin
inherited;
end;
procedure TVXSceneObj.UpdateCachedAABBAndBSphere;
begin
FCachedAABB := Obj.AxisAlignedBoundingBox;
FCachedAABB.min := Obj.LocalToAbsolute(FCachedAABB.min);
FCachedAABB.max := Obj.LocalToAbsolute(FCachedAABB.max);
FCachedBSphere.Radius := Obj.BoundingSphereRadius;
FCachedBSphere.Center := AffineVectorMake(Obj.AbsolutePosition);
end;
end.
|
unit uFrmDadosFornecedorProduto;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmDadosBase, StdCtrls, Buttons, ExtCtrls, Mask,
DBClient, FornecedorProduto, uFramePesquisaFornecedor, DXPCurrencyEdit;
type
TFrmDadosFornecedorProduto = class(TFrmDadosBase)
Label5: TLabel;
FramePesquisaFornecedor: TFramePesquisaFornecedor;
cedPrecoCompra: TDXPCurrencyEdit;
procedure FramePesquisaFornecedoredtCodigoFornecedorExit(Sender: TObject);
private
{ Private declarations }
protected
procedure OnCreate; override;
procedure OnDestroy; override;
procedure OnSave; override;
procedure OnShow; override;
public
{ Public declarations }
FornecedorProduto: TFornecedorProduto;
end;
var
FrmDadosFornecedorProduto: TFrmDadosFornecedorProduto;
implementation
uses StringUtils, MensagensUtils, TypesUtils;
{$R *.dfm}
{ TFrmDadosFornecedorProduto }
procedure TFrmDadosFornecedorProduto.FramePesquisaFornecedoredtCodigoFornecedorExit(Sender: TObject);
var
cds: TClientDataSet;
begin
inherited;
FramePesquisaFornecedor.edtCodigoFornecedorExit(Sender);
cds := TClientDataSet(Owner.FindComponent('cdsFornecedores'));
if ( Operacao = opInsert ) and cds.FindKey([FramePesquisaFornecedor.edtCodigoFornecedor.Text]) then
begin
Atencao('Este fornecedor já foi inserido.');
FramePesquisaFornecedor.edtCodigoFornecedor.SetFocus;
Exit;
end;
end;
procedure TFrmDadosFornecedorProduto.OnCreate;
begin
inherited;
SetCamposObrigatorios([FramePesquisaFornecedor.edtCodigoFornecedor]);
end;
procedure TFrmDadosFornecedorProduto.OnDestroy;
begin
inherited;
end;
procedure TFrmDadosFornecedorProduto.OnSave;
var
cds: TClientDataSet;
begin
inherited;
cds := TClientDataSet(Owner.FindComponent('cdsFornecedores'));
if (Operacao = opInsert) then
begin
try
cds.Append;
cds.FieldByName('CODIGO_FORNECEDOR').AsString := FramePesquisaFornecedor.edtCodigoFornecedor.Text;
cds.FieldByName('NOME_FORNECEDOR').AsString := FramePesquisaFornecedor.edtNomeFornecedor.Text;
cds.FieldByName('PRECO_COMPRA').AsCurrency := cedPrecoCompra.Value;
cds.Post;
except
Erro('Ocorreu algum erro durante a inclusão.');
end;
end
else
begin
try
cds.Edit;
cds.FieldByName('CODIGO_FORNECEDOR').AsString := FramePesquisaFornecedor.edtCodigoFornecedor.Text;
cds.FieldByName('NOME_FORNECEDOR').AsString := FramePesquisaFornecedor.edtNomeFornecedor.Text;
cds.FieldByName('PRECO_COMPRA').AsCurrency := cedPrecoCompra.Value;
cds.Post;
except
Erro('Ocorreu algum erro durante a inclusão.');
end;
end;
end;
procedure TFrmDadosFornecedorProduto.OnShow;
begin
inherited;
if (Assigned(FornecedorProduto)) then
begin
try
FramePesquisaFornecedor.edtCodigoFornecedor.Text := FornecedorProduto.Fornecedor.Codigo;
FramePesquisaFornecedor.edtNomeFornecedor.Text := FornecedorProduto.Fornecedor.Nome;
cedPrecoCompra.Value := FornecedorProduto.PrecoCompra;
finally
FornecedorProduto.Free;
end;
end;
end;
end.
|
unit BCEditor.Editor.Caret.Offsets;
interface
uses
System.Classes;
type
TBCEditorCaretOffsets = class(TPersistent)
strict private
FOnChange: TNotifyEvent;
FX: Integer;
FY: Integer;
procedure DoChange(Sender: TObject);
procedure SetX(AValue: Integer);
procedure SetY(AValue: Integer);
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
published
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property X: Integer read FX write SetX default 0;
property Y: Integer read FY write SetY default 0;
end;
implementation
{ TBCEditorCaretOffsets }
constructor TBCEditorCaretOffsets.Create;
begin
inherited;
FX := 0;
FY := 0;
end;
procedure TBCEditorCaretOffsets.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TBCEditorCaretOffsets) then
with ASource as TBCEditorCaretOffsets do
begin
Self.FX := FX;
Self.FY := FY;
Self.DoChange(Self);
end
else
inherited Assign(ASource);
end;
procedure TBCEditorCaretOffsets.DoChange(Sender: TObject);
begin
if Assigned(FOnChange) then
FOnChange(Sender);
end;
procedure TBCEditorCaretOffsets.SetX(AValue: Integer);
begin
if FX <> AValue then
begin
FX := AValue;
DoChange(Self);
end;
end;
procedure TBCEditorCaretOffsets.SetY(AValue: Integer);
begin
if FY <> AValue then
begin
FY := AValue;
DoChange(Self);
end;
end;
end.
|
unit NeighborDetector;
interface
uses BasicMathsTypes, BasicDataTypes, BasicRenderingTypes, SysUtils, Windows, MeshGeometryList;
const
C_NEIGHBTYPE_VERTEX_VERTEX = 0; // vertex neighbors of vertexes.
C_NEIGHBTYPE_VERTEX_FACE = 1; // face neighbors of vertexes.
C_NEIGHBTYPE_FACE_VERTEX = 2; // vertex neighbors of faces.
C_NEIGHBTYPE_FACE_FACE_FROM_EDGE = 3; // face neighbors of faces, with common edges.
C_NEIGHBTYPE_FACE_FACE_FROM_VERTEX = 4; // face neighbors of faces, with common vertexes.
C_NEIGHBTYPE_MAX = C_NEIGHBTYPE_FACE_FACE_FROM_VERTEX;
type
PNeighborDetector = ^TNeighborDetector;
TNeighborDetector = class
private
FNeighbors: array of PIntegerItem;
FRequest : integer;
FNeighborID: integer;
FCurrentID: integer;
FNeighborhoodData: array of integer;
FDescriptorData: TADescriptor;
// Constructors and Destructors
procedure Initialize;
procedure InitializeNeighbors(_NumElements: integer);
procedure ClearFNeighbors;
// Executes
procedure OrganizeVertexVertex(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer); overload;
procedure OrganizeVertexVertex(const _Geometry: CMeshGeometryList; _NumVertexes: integer); overload;
procedure OrganizeVertexFace(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer);
procedure OrganizeFaceVertex(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer);
procedure OrganizeFaceFace(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer);
procedure OrganizeFaceFaceFromVertex(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer);
procedure DefragmentData;
// ReOrder
procedure ReOrderVertexVertex(const _Vertexes,_VertexNormals: TAVector3f);
procedure ReOrderVertexFace(const _Vertexes,_VertexNormals: TAVector3f; const _Faces: auint32; _VertexesPerFace: integer);
procedure ReOrderFaceVertex(const _Vertexes,_FaceNormals: TAVector3f; const _Faces: auint32; _VertexesPerFace: integer);
procedure ReOrderFaceFace(const _Vertexes,_FaceNormals: TAVector3f; const _Faces: auint32; _VertexesPerFace: integer);
procedure QuickSortAngles(_min, _max : integer; var _Order: auint32; var _Angles : afloat);
function GetTheVertexAfterMe(_VertexID,_VertexesPerFace: integer; const _Faces: auint32): integer;
function GetFaceCenterPosition(_Face: integer; const _Faces:auint32; const _Vertexes: TAVector3f; _VertexesPerFace: integer): TVector3f;
// Adds
procedure AddElementAtTarget(_Value: integer; _Target: integer);
procedure AddElementAtTargetWithoutRepetition(_Value: integer; _Target: integer);
public
VertexVertexNeighbors: TNeighborDetector;
VertexFaceNeighbors: TNeighborDetector;
NeighborType : byte;
IsValid: boolean;
// Constructors and Destructors
constructor Create; overload;
constructor Create(_Type : byte); overload;
constructor Create(const _Source: TNeighborDetector); overload;
destructor Destroy; override;
procedure Clear;
// I/O
procedure LoadState(_State: TNeighborDetectorSaveData);
function SaveState:TNeighborDetectorSaveData;
// Sets
procedure SetType(_Type: byte);
// Executes
procedure BuildUpData(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer); overload;
procedure BuildUpData(var _Geometry: CMeshGeometryList; _NumVertexes: integer); overload;
// ReOrder
procedure GetStarOrder(const _Vertexes,_FaceNormals,_VertexNormals: TAVector3f; const _Faces: auint32; _VertexesPerFace: integer);
// Requests
function GetNeighborFromID(_ID: integer): integer;
function GetNextNeighbor: integer;
function GetNumNeighbors(_ID: integer): integer;
function GetDataSize: integer;
// Copy
procedure Assign(const _Source: TNeighborDetector);
end;
implementation
uses MeshBRepGeometry, VertexTransformationUtils, math3d;
// Constructors and Destructors
constructor TNeighborDetector.Create;
begin
NeighborType := C_NEIGHBTYPE_VERTEX_VERTEX;
Initialize;
end;
constructor TNeighborDetector.Create(_Type : byte);
begin
NeighborType := _Type;
Initialize;
end;
constructor TNeighborDetector.Create(const _Source: TNeighborDetector);
begin
Assign(_Source);
end;
destructor TNeighborDetector.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TNeighborDetector.Initialize;
begin
FRequest := -1;
VertexVertexNeighbors := nil;
VertexFaceNeighbors := nil;
IsValid := false;
SetLength(FNeighbors,0);
SetLength(FNeighborhoodData,0);
SetLength(FDescriptorData,0);
end;
procedure TNeighborDetector.ClearFNeighbors;
var
i : integer;
Element, DisposedElement: PIntegerItem;
begin
for i := Low(FNeighbors) to High(FNeighbors) do
begin
// clear each element.
Element := FNeighbors[i];
while Element <> nil do
begin
DisposedElement := Element;
Element := Element^.Next;
Dispose(DisposedElement);
end;
FNeighbors[i] := nil;
end;
SetLength(FNeighbors,0);
end;
procedure TNeighborDetector.Clear;
begin
ClearFNeighbors;
Initialize;
end;
procedure TNeighborDetector.InitializeNeighbors(_NumElements: integer);
var
i : integer;
begin
SetLength(FNeighbors,_NumElements);
SetLength(FDescriptorData,_NumElements);
for i := Low(FNeighbors) to High(FNeighbors) do
begin
FNeighbors[i] := nil;
end;
end;
// I/O
procedure TNeighborDetector.LoadState(_State: TNeighborDetectorSaveData);
begin
FCurrentID := _State.cID;
FNeighborID := _State.nID;
FRequest := FNeighborhoodData[FDescriptorData[FCurrentID].Start + FNeighborID];
end;
function TNeighborDetector.SaveState:TNeighborDetectorSaveData;
begin
Result.nID := FNeighborID;
Result.cID := FCurrentID;
end;
// Sets
procedure TNeighborDetector.SetType(_Type: byte);
begin
if (not IsValid) and (_type <= C_NEIGHBTYPE_MAX) then
begin
NeighborType := _Type;
end;
end;
// Executes
procedure TNeighborDetector.BuildUpData(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer);
begin
Case(NeighborType) of
C_NEIGHBTYPE_VERTEX_VERTEX: // vertex neighbors of vertexes.
begin
OrganizeVertexVertex(_Faces,_VertexesPerFace,_NumVertexes);
end;
C_NEIGHBTYPE_VERTEX_FACE: // face neighbors of vertexes.
begin
OrganizeVertexFace(_Faces,_VertexesPerFace,_NumVertexes);
end;
C_NEIGHBTYPE_FACE_VERTEX: // vertex neighbors of faces.
begin
OrganizeFaceVertex(_Faces,_VertexesPerFace,_NumVertexes);
end;
C_NEIGHBTYPE_FACE_FACE_FROM_EDGE: // face neighbors of faces with common edges.
begin
OrganizeFaceFace(_Faces,_VertexesPerFace,_NumVertexes);
end;
C_NEIGHBTYPE_FACE_FACE_FROM_VERTEX: // face neighbors of faces with common vertexes.
begin
OrganizeFaceFaceFromVertex(_Faces,_VertexesPerFace,_NumVertexes);
end;
end;
DefragmentData;
IsValid := true;
end;
procedure TNeighborDetector.BuildUpData(var _Geometry: CMeshGeometryList; _NumVertexes: integer);
begin
Case(NeighborType) of
C_NEIGHBTYPE_VERTEX_VERTEX: // vertex neighbors of vertexes.
begin
OrganizeVertexVertex(_Geometry,_NumVertexes);
end;
C_NEIGHBTYPE_VERTEX_FACE: // face neighbors of vertexes.
begin
OrganizeVertexFace((_Geometry.Current^ as TMeshBRepGeometry).Faces,(_Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,_NumVertexes);
end;
C_NEIGHBTYPE_FACE_VERTEX: // vertex neighbors of faces.
begin
OrganizeFaceVertex((_Geometry.Current^ as TMeshBRepGeometry).Faces,(_Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,_NumVertexes);
end;
C_NEIGHBTYPE_FACE_FACE_FROM_EDGE: // face neighbors of faces with common edges.
begin
OrganizeFaceFace((_Geometry.Current^ as TMeshBRepGeometry).Faces,(_Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,_NumVertexes);
end;
C_NEIGHBTYPE_FACE_FACE_FROM_VERTEX: // face neighbors of faces with common vertexes.
begin
OrganizeFaceFaceFromVertex((_Geometry.Current^ as TMeshBRepGeometry).Faces,(_Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace,_NumVertexes);
end;
end;
DefragmentData;
IsValid := true;
end;
procedure TNeighborDetector.OrganizeVertexVertex(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer);
var
f, v, i : integer;
SearchArray : array of array of integer;
begin
// Setup Neighbors.
InitializeNeighbors(_NumVertexes);
SetLength(SearchArray,((_VertexesPerFace-1)*_VertexesPerFace) shr 1,2);
f := 0;
for v := 0 to _VertexesPerFace - 2 do
for i := v+1 to _VertexesPerFace -1 do
begin
SearchArray[f,0] := v;
SearchArray[f,1] := i;
inc(f);
end;
// Main loop goes here.
f := 0;
while f < High(_Faces) do
begin
// check all neighbors of each vertex of the face.
for i := Low(SearchArray) to High(SearchArray) do
begin
AddElementAtTarget(_Faces[f+SearchArray[i,0]],_Faces[f+SearchArray[i,1]]);
AddElementAtTarget(_Faces[f+SearchArray[i,1]],_Faces[f+SearchArray[i,0]]);
end;
inc(f,_VertexesPerFace);
end;
for i := Low(SearchArray) to High(SearchArray) do
begin
SetLength(SearchArray,i,0);
end;
SetLength(SearchArray,0);
end;
procedure TNeighborDetector.OrganizeVertexVertex(const _Geometry: CMeshGeometryList; _NumVertexes: integer);
var
f, v, i : integer;
SearchArray : array of array of integer;
VertexesPerFace: integer;
begin
// Setup Neighbors.
InitializeNeighbors(_NumVertexes);
_Geometry.GoToFirstElement;
while _Geometry.Current <> nil do
begin
VertexesPerFace := (_Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace;
SetLength(SearchArray,((VertexesPerFace-1)*VertexesPerFace) shr 1,2);
f := 0;
for v := 0 to VertexesPerFace - 2 do
for i := v+1 to VertexesPerFace -1 do
begin
SearchArray[f,0] := v;
SearchArray[f,1] := i;
inc(f);
end;
// Main loop goes here.
f := 0;
while f < High((_Geometry.Current^ as TMeshBRepGeometry).Faces) do
begin
// check all neighbors of each vertex of the face.
for i := Low(SearchArray) to High(SearchArray) do
begin
AddElementAtTarget((_Geometry.Current^ as TMeshBRepGeometry).Faces[f+SearchArray[i,0]],(_Geometry.Current^ as TMeshBRepGeometry).Faces[f+SearchArray[i,1]]);
AddElementAtTarget((_Geometry.Current^ as TMeshBRepGeometry).Faces[f+SearchArray[i,1]],(_Geometry.Current^ as TMeshBRepGeometry).Faces[f+SearchArray[i,0]]);
end;
inc(f,VertexesPerFace);
end;
for i := Low(SearchArray) to High(SearchArray) do
begin
SetLength(SearchArray,i,0);
end;
SetLength(SearchArray,0);
_Geometry.GoToNextElement;
end;
end;
procedure TNeighborDetector.OrganizeVertexFace(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer);
var
f,face, v : integer;
begin
// Setup Neighbors.
InitializeNeighbors(_NumVertexes);
// Main loop goes here.
f := 0;
face := 0;
while f < High(_Faces) do
begin
// check each vertex of the face.
for v := 0 to _VertexesPerFace - 1 do
begin
// Here we add the element to FNeighbors[f+v]
AddElementAtTargetWithoutRepetition(face,_Faces[f+v]);
end;
inc(f,_VertexesPerFace);
inc(face);
end;
end;
procedure TNeighborDetector.OrganizeFaceVertex(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer);
var
f, face, v, NumFaces, Value : integer;
TempDetector : TNeighborDetector;
begin
// Setup Neighbors.
NumFaces := (High(_Faces)+1) div _VertexesPerFace;
InitializeNeighbors(NumFaces);
// Get Vertex neighbors from vertexes.
if VertexVertexNeighbors = nil then
begin
TempDetector := TNeighborDetector.Create;
TempDetector.BuildUpData(_Faces,_VertexesPerFace,_NumVertexes);
end
else
begin
TempDetector := VertexVertexNeighbors;
end;
// Main loop goes here.
f := 0;
face := 0;
while f < High(_Faces) do
begin
// check each vertex of the face.
for v := 0 to _VertexesPerFace - 1 do
begin
Value := TempDetector.GetNeighborFromID(_Faces[f+v]);
while Value <> -1 do
begin
// Here we add the element to the face
AddElementAtTarget(Value,face);
Value := TempDetector.GetNextNeighbor;
end;
end;
inc(f,_VertexesPerFace);
inc(face);
end;
// Clean up memory
if VertexVertexNeighbors = nil then
TempDetector.Free;
end;
procedure TNeighborDetector.OrganizeFaceFace(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer);
var
f, face, v, vi, vn, fn, NumFaces, Value : integer;
TempDetector : TNeighborDetector;
label
FinishedVertex;
begin
// Setup Neighbors.
NumFaces := (High(_Faces)+1) div _VertexesPerFace;
InitializeNeighbors(NumFaces);
// Get face neighbors from vertexes.
if VertexFaceNeighbors = nil then
begin
TempDetector := TNeighborDetector.Create(C_NEIGHBTYPE_VERTEX_FACE);
TempDetector.BuildUpData(_Faces,_VertexesPerFace,_NumVertexes);
end
else
begin
TempDetector := VertexFaceNeighbors;
end;
// Main loop goes here.
f := 0;
face := 0;
while f < High(_Faces) do
begin
// check each vertex of the face.
for v := 0 to _VertexesPerFace - 2 do
begin
Value := TempDetector.GetNeighborFromID(_Faces[f+v]);
while Value <> -1 do
begin
// Here we check if an edge belongs to both faces.
fn := Value * _VertexesPerFace;
if (f <> fn) then
begin
for vi := (v + 1) to (_VertexesPerFace - 1) do
begin
for vn := 0 to _VertexesPerFace - 1 do
begin
if _Faces[f+vi] = _Faces[fn+vn] then
begin
// Here we add the element to the face
AddElementAtTarget(Value,face);
goto FinishedVertex;
end;
end;
end;
end;
FinishedVertex:
Value := TempDetector.GetNextNeighbor;
end;
end;
inc(f,_VertexesPerFace);
inc(face);
end;
// Clean up memory
if VertexFaceNeighbors = nil then
TempDetector.Free;
end;
// Another approach for Face neighbors of Faces, where each neighbor needs to have at least one common vertex instead of edge.
procedure TNeighborDetector.OrganizeFaceFaceFromVertex(const _Faces: auint32; _VertexesPerFace,_NumVertexes: integer);
var
f, face, v, NumFaces, Value : integer;
TempDetector : TNeighborDetector;
begin
// Setup Neighbors.
NumFaces := (High(_Faces)+1) div _VertexesPerFace;
InitializeNeighbors(NumFaces);
// Get face neighbors from vertexes.
if VertexFaceNeighbors = nil then
begin
TempDetector := TNeighborDetector.Create(C_NEIGHBTYPE_VERTEX_FACE);
TempDetector.BuildUpData(_Faces,_VertexesPerFace,_NumVertexes);
end
else
begin
TempDetector := VertexFaceNeighbors;
end;
// Main loop goes here.
f := 0;
face := 0;
while f < High(_Faces) do
begin
// check each vertex of the face.
for v := 0 to _VertexesPerFace - 2 do
begin
Value := TempDetector.GetNeighborFromID(_Faces[f+v]);
while Value <> -1 do
begin
// Here we check if an edge belongs to both faces.
if (face <> Value) then
begin
// Here we add the element to the face
AddElementAtTarget(Value,face);
end;
Value := TempDetector.GetNextNeighbor;
end;
end;
inc(f,_VertexesPerFace);
inc(face);
end;
// Clean up memory
if VertexFaceNeighbors = nil then
TempDetector.Free;
end;
// Transform the data at the fragmented FNeighbors into a single array.
procedure TNeighborDetector.DefragmentData;
var
e, i, Size: integer;
Element: PIntegerItem;
begin
Size := 0;
// Let's fill the descriptors first.
for i := Low(FNeighbors) to High(FNeighbors) do
begin
Element := FNeighbors[i];
FDescriptorData[i].Start := Size;
while Element <> nil do
begin
Element := Element^.Next;
inc(Size);
end;
FDescriptorData[i].Size := Size - FDescriptorData[i].Start;
end;
SetLength(FNeighborhoodData,Size);
// Now, we fill the data.
e := 0;
for i := Low(FNeighbors) to High(FNeighbors) do
begin
Element := FNeighbors[i];
while Element <> nil do
begin
FNeighborhoodData[e] := Element^.Value;
Element := Element^.Next;
inc(e);
end;
end;
// So... now that we've passed all the data from FNeighbors to an array, we
// need to get rid of FNeighbors.
ClearFNeighbors;
end;
// Adds
procedure TNeighborDetector.AddElementAtTarget(_Value: integer; _Target: integer);
var
Element,Previous: PIntegerItem;
begin
if FNeighbors[_Target] <> nil then
begin
Previous := FNeighbors[_Target];
if _Value <> Previous^.Value then
begin
while Previous^.Next <> nil do
begin
Previous := Previous^.Next;
if _Value = Previous^.Value then
exit;
end;
new(Element);
Element^.Value := _Value;
Element^.Next := nil;
Previous^.Next := Element;
end;
end
else
begin
new(Element);
Element^.Value := _Value;
Element^.Next := nil;
FNeighbors[_Target] := Element;
end;
end;
procedure TNeighborDetector.AddElementAtTargetWithoutRepetition(_Value: integer; _Target: integer);
var
Element,Previous: PIntegerItem;
begin
new(Element);
Element^.Value := _Value;
Element^.Next := nil;
if FNeighbors[_Target] <> nil then
begin
Previous := FNeighbors[_Target];
while Previous^.Next <> nil do
begin
Previous := Previous^.Next;
end;
Previous^.Next := Element;
end
else
begin
FNeighbors[_Target] := Element;
end;
end;
// ReOrder
procedure TNeighborDetector.GetStarOrder(const _Vertexes,_FaceNormals,_VertexNormals: TAVector3f; const _Faces: auint32; _VertexesPerFace: integer);
begin
Case(NeighborType) of
C_NEIGHBTYPE_VERTEX_VERTEX: // vertex neighbors of vertexes.
begin
ReOrderVertexVertex(_Vertexes,_VertexNormals);
end;
C_NEIGHBTYPE_VERTEX_FACE: // face neighbors of vertexes.
begin
if VertexVertexNeighbors <> nil then
begin
VertexVertexNeighbors.GetStarOrder(_Vertexes,_FaceNormals,_VertexNormals,_Faces,_VertexesPerFace);
end;
ReOrderVertexFace(_Vertexes,_VertexNormals,_Faces,_VertexesPerFace);
end;
C_NEIGHBTYPE_FACE_VERTEX: // vertex neighbors of faces.
begin
if VertexVertexNeighbors <> nil then
begin
VertexVertexNeighbors.GetStarOrder(_Vertexes,_FaceNormals,_VertexNormals,_Faces,_VertexesPerFace);
end;
ReOrderFaceVertex(_Vertexes,_FaceNormals,_Faces,_VertexesPerFace);
end;
else //C_NEIGHBTYPE_FACE_FACE_FROM_EDGE or C_NEIGHBTYPE_FACE_FACE_FROM_VERTEX
begin
if VertexFaceNeighbors <> nil then
begin
VertexFaceNeighbors.GetStarOrder(_Vertexes,_FaceNormals,_VertexNormals,_Faces,_VertexesPerFace);
end;
ReOrderFaceFace(_Vertexes,_FaceNormals,_Faces,_VertexesPerFace);
end;
end;
end;
procedure TNeighborDetector.ReOrderVertexVertex(const _Vertexes,_VertexNormals: TAVector3f);
var
v,i : integer;
Order: auint32;
Angles: afloat;
Util: TVertexTransformationUtils;
Direction,AxisX,AxisY: TVector3f;
begin
// Let's reorder every vertex.
Util := TVertexTransformationUtils.Create;
for v := 0 to High(FDescriptorData) do
begin
if FDescriptorData[v].Size > 0 then
begin
// Setup and Backup Order
SetLength(Order,FDescriptorData[v].Size);
for i := Low(Order) to High(Order) do
begin
Order[i] := FNeighborhoodData[FDescriptorData[v].Start + i];
end;
// Setup Angles
SetLength(Angles,FDescriptorData[v].Size);
// Obtain tangent plane.
i := Order[0];
Direction := SetVector(_Vertexes[i].X - _Vertexes[v].X,_Vertexes[i].Y - _Vertexes[v].Y,_Vertexes[i].Z - _Vertexes[v].Z);
Util.GetTangentPlaneFromNormalAndDirection(AxisX,AxisY,_VertexNormals[v],Direction);
// Now we obtain the angle from each neighbour
for i := Low(Order) to High(Order) do
begin
// Direction starts as the direction of the vertex composed of v
// and the neighbour
Direction := SetVector(_Vertexes[Order[i]].X - _Vertexes[v].X,_Vertexes[Order[i]].Y - _Vertexes[v].Y,_Vertexes[Order[i]].Z - _Vertexes[v].Z);
Direction := Util.ProjectVectorOnTangentPlane(_VertexNormals[v],Direction);
Normalize(Direction);
// Direction ends up as the projection of that in the tangent plane.
// What a mess! Sorry. But I'm lazy to create temp variables.
// Finally, we obtain the angle from Direction and the Tangent Plane
// (AxisX,AxisY).
Angles[i] := Util.CleanAngleRadians(Util.GetArcCosineFromTangentPlane(Direction,AxisX,AxisY));
end;
// ReOrder the angles.
QuickSortAngles(0,High(Angles),Order,Angles);
// Replace the values.
for i := Low(Order) to High(Order) do
begin
FNeighborhoodData[FDescriptorData[v].Start + i] := Order[i];
end;
end;
end;
SetLength(Order, 0);
SetLength(Angles, 0);
Util.Free;
end;
procedure TNeighborDetector.ReOrderVertexFace(const _Vertexes,_VertexNormals: TAVector3f; const _Faces: auint32; _VertexesPerFace: integer);
var
v,i: integer;
Order: auint32;
Angles: afloat;
Util: TVertexTransformationUtils;
Direction,AxisX,AxisY: TVector3f;
begin
// Let's reorder every vertex.
Util := TVertexTransformationUtils.Create;
for v := 0 to High(FDescriptorData) do
begin
if FDescriptorData[v].Size > 0 then
begin
// Setup and Backup Order
SetLength(Order,FDescriptorData[v].Size);
for i := Low(Order) to High(Order) do
begin
Order[i] := FNeighborhoodData[FDescriptorData[v].Start + i];
end;
// Setup Angles
SetLength(Angles,FDescriptorData[v].Size);
// Obtain tangent plane.
i := GetTheVertexAfterMe(v,_VertexesPerFace,_Faces);
Direction := SetVector(_Vertexes[i].X - _Vertexes[v].X,_Vertexes[i].Y - _Vertexes[v].Y,_Vertexes[i].Z - _Vertexes[v].Z);
Util.GetTangentPlaneFromNormalAndDirection(AxisX,AxisY,_VertexNormals[v],Direction);
// Now we obtain the angle from each neighbour
for i := Low(Order) to High(Order) do
begin
// Direction starts as the direction of the vertex composed of v
// and the neighbour
Direction := GetFaceCenterPosition(Order[i],_Faces,_Vertexes,_VertexesPerFace);
Direction := SetVector(Direction.X - _Vertexes[v].X,Direction.Y - _Vertexes[v].Y,Direction.Z - _Vertexes[v].Z);
Direction := Util.ProjectVectorOnTangentPlane(_VertexNormals[v],Direction);
Normalize(Direction);
// Direction ends up as the projection of that in the tangent plane.
// What a mess! Sorry. But I'm lazy to create temp variables.
// Finally, we obtain the angle from Direction and the Tangent Plane
// (AxisX,AxisY).
Angles[i] := Util.CleanAngleRadians(Util.GetArcCosineFromTangentPlane(Direction,AxisX,AxisY));
end;
// ReOrder the angles.
QuickSortAngles(0,High(Angles),Order,Angles);
// Replace the values.
for i := Low(Order) to High(Order) do
begin
FNeighborhoodData[FDescriptorData[v].Start + i] := Order[i];
end;
end;
end;
SetLength(Order, 0);
SetLength(Angles, 0);
Util.Free;
end;
procedure TNeighborDetector.ReOrderFaceVertex(const _Vertexes,_FaceNormals: TAVector3f; const _Faces: auint32; _VertexesPerFace: integer);
var
v,i : integer;
Order: auint32;
Angles: afloat;
Util: TVertexTransformationUtils;
Center,Direction,AxisX,AxisY: TVector3f;
begin
// Let's reorder every vertex.
Util := TVertexTransformationUtils.Create;
for v := 0 to High(FDescriptorData) do
begin
if FDescriptorData[v].Size > 0 then
begin
// Setup and Backup Order
SetLength(Order,FDescriptorData[v].Size);
for i := Low(Order) to High(Order) do
begin
Order[i] := FNeighborhoodData[FDescriptorData[v].Start + i];
end;
// Setup Angles
SetLength(Angles,FDescriptorData[v].Size);
// Obtain tangent plane.
Center := GetFaceCenterPosition(v,_Faces,_Vertexes,_VertexesPerFace);
i := Order[0];
Direction := SubtractVector(_Vertexes[i],Center);
Util.GetTangentPlaneFromNormalAndDirection(AxisX,AxisY,_FaceNormals[v],Direction);
// Now we obtain the angle from each neighbour
for i := Low(Order) to High(Order) do
begin
// Direction starts as the direction of the vertex composed of v
// and the neighbour
Direction := SetVector(_Vertexes[Order[i]].X - Center.X,_Vertexes[Order[i]].Y - Center.Y,_Vertexes[Order[i]].Z - Center.Z);
Direction := Util.ProjectVectorOnTangentPlane(_FaceNormals[v],Direction);
Normalize(Direction);
// Direction ends up as the projection of that in the tangent plane.
// What a mess! Sorry. But I'm lazy to create temp variables.
// Finally, we obtain the angle from Direction and the Tangent Plane
// (AxisX,AxisY).
Angles[i] := Util.CleanAngleRadians(Util.GetArcCosineFromTangentPlane(Direction,AxisX,AxisY));
end;
// ReOrder the angles.
QuickSortAngles(0,High(Angles),Order,Angles);
// Replace the values.
for i := Low(Order) to High(Order) do
begin
FNeighborhoodData[FDescriptorData[v].Start + i] := Order[i];
end;
end;
end;
SetLength(Order, 0);
SetLength(Angles, 0);
Util.Free;
end;
procedure TNeighborDetector.ReOrderFaceFace(const _Vertexes,_FaceNormals: TAVector3f; const _Faces: auint32; _VertexesPerFace: integer);
var
v,i : integer;
Order: auint32;
Angles: afloat;
Util: TVertexTransformationUtils;
Center,Direction,AxisX,AxisY: TVector3f;
begin
// Let's reorder every vertex.
Util := TVertexTransformationUtils.Create;
for v := 0 to High(FDescriptorData) do
begin
if FDescriptorData[v].Size > 0 then
begin
// Setup and Backup Order
SetLength(Order,FDescriptorData[v].Size);
for i := Low(Order) to High(Order) do
begin
Order[i] := FNeighborhoodData[FDescriptorData[v].Start + i];
end;
// Setup Angles
SetLength(Angles,FDescriptorData[v].Size);
// Obtain tangent plane.
Center := GetFaceCenterPosition(v,_Faces,_Vertexes,_VertexesPerFace);
i := Order[0];
Direction := SubtractVector(GetFaceCenterPosition(i,_Faces,_Vertexes,_VertexesPerFace),Center);
Util.GetTangentPlaneFromNormalAndDirection(AxisX,AxisY,_FaceNormals[v],Direction);
// Now we obtain the angle from each neighbour
for i := Low(Order) to High(Order) do
begin
// Direction starts as the direction of the vertex composed of v
// and the neighbour
Direction := SubtractVector(GetFaceCenterPosition(Order[i],_Faces,_Vertexes,_VertexesPerFace),Center);
Direction := Util.ProjectVectorOnTangentPlane(_FaceNormals[v],Direction);
Normalize(Direction);
// Direction ends up as the projection of that in the tangent plane.
// What a mess! Sorry. But I'm lazy to create temp variables.
// Finally, we obtain the angle from Direction and the Tangent Plane
// (AxisX,AxisY).
Angles[i] := Util.CleanAngleRadians(Util.GetArcCosineFromTangentPlane(Direction,AxisX,AxisY));
end;
// ReOrder the angles.
QuickSortAngles(0,High(Angles),Order,Angles);
// Replace the values.
for i := Low(Order) to High(Order) do
begin
FNeighborhoodData[FDescriptorData[v].Start + i] := Order[i];
end;
end;
end;
SetLength(Order, 0);
SetLength(Angles, 0);
Util.Free;
end;
// Ascending Quick Sort (To make it descending, change the > and < in both whiles)
procedure TNeighborDetector.QuickSortAngles(_min, _max : integer; var _Order: auint32; var _Angles : afloat);
var
Lo, Hi, Mid, T: Integer;
A : real;
begin
Lo := _min;
Hi := _max;
Mid := (Lo + Hi) div 2;
repeat
while (_Angles[Lo] - _Angles[Mid]) < 0 do Inc(Lo);
while (_Angles[Hi] - _Angles[Mid]) > 0 do Dec(Hi);
if Lo <= Hi then
begin
T := _Order[Lo];
_Order[Lo] := _Order[Hi];
_Order[Hi] := T;
A := _Angles[Lo];
_Angles[Lo] := _Angles[Hi];
_Angles[Hi] := A;
if (Lo = Mid) and (Hi <> Mid) then
Mid := Hi
else if (Hi = Mid) and (Lo <> Mid) then
Mid := Lo;
Inc(Lo);
Dec(Hi);
end;
until Lo > Hi;
if Hi > _min then
QuickSortAngles(_min, Hi, _Order, _Angles);
if Lo < _max then
QuickSortAngles(Lo, _max, _Order, _Angles);
end;
function TNeighborDetector.GetTheVertexAfterMe(_VertexID,_VertexesPerFace: integer; const _Faces: auint32): integer;
var
i,c : integer;
begin
i := _VertexID * _VertexesPerFace;
c := 0;
while _Faces[i] <> _VertexID do
begin
inc(i);
inc(c);
end;
if c = _VertexesPerFace then
begin
Result := _Faces[_VertexID * _VertexesPerFace];
end
else
begin
Result := _Faces[i+1];
end;
end;
function TNeighborDetector.GetFaceCenterPosition(_Face: integer; const _Faces:auint32; const _Vertexes: TAVector3f; _VertexesPerFace: integer): TVector3f;
var
i : integer;
begin
Result := SetVector(0,0,0);
for i := 0 to _VertexesPerFace do
begin
Result.X := Result.X + _Vertexes[_Faces[(_Face*_VertexesPerFace)+i]].X;
Result.Y := Result.Y + _Vertexes[_Faces[(_Face*_VertexesPerFace)+i]].Y;
Result.Z := Result.Z + _Vertexes[_Faces[(_Face*_VertexesPerFace)+i]].Z;
end;
Result.X := Result.X / _VertexesPerFace;
Result.Y := Result.Y / _VertexesPerFace;
Result.Z := Result.Z / _VertexesPerFace;
end;
// Requests
function TNeighborDetector.GetNeighborFromID(_ID: integer): integer;
begin
if (_ID >= 0) and (_ID <= High(FDescriptorData)) then
begin
FCurrentID := _ID;
FRequest := FNeighborhoodData[FDescriptorData[_ID].Start];
FNeighborID := 0;
end
else
begin
FRequest := -1;
end;
Result := FRequest;
end;
function TNeighborDetector.GetNextNeighbor: integer;
begin
if FRequest <> -1 then
begin
inc(FNeighborID);
if FNeighborID < FDescriptorData[FCurrentID].Size then
begin
FRequest := FNeighborhoodData[FDescriptorData[FCurrentID].Start + FNeighborID];
end
else
begin
FRequest := -1;
end;
Result := FRequest;
end
else
Result := -1;
end;
function TNeighborDetector.GetNumNeighbors(_ID: integer): integer;
begin
if (_ID >= 0) and (_ID <= High(FDescriptorData)) then
begin
Result := FDescriptorData[_ID].Size;
end
else
begin
Result := 0;
end;
end;
function TNeighborDetector.GetDataSize: integer;
begin
Result := High(FNeighborhoodData) + 1;
end;
// Copy
procedure TNeighborDetector.Assign(const _Source: TNeighborDetector);
var
i: integer;
Element, NewElement, PreviousElement: PIntegerItem;
begin
SetLength(FNeighbors, High(_Source.FNeighbors) + 1);
for i := Low(FNeighbors) to High(FNeighbors) do
begin
if _Source.FNeighbors[i] = nil then
begin
FNeighbors[i] := nil;
end
else
begin
Element := _Source.FNeighbors[i];
PreviousElement := nil;
while Element <> nil do
begin
new(NewElement);
NewElement^.Value := Element^.Value;
if PreviousElement <> nil then
begin
PreviousElement^.Next := NewElement;
end
else
begin
FNeighbors[i] := NewElement;
end;
NewElement^.Next := nil;
PreviousElement := NewElement;
Element := Element^.Next;
end;
end;
end;
FRequest := _Source.FRequest;
FNeighborID := _Source.FNeighborID;
FCurrentID := _Source.FCurrentID;
SetLength(FNeighborhoodData, High(_Source.FNeighborhoodData) + 1);
for i := Low(FNeighborhoodData) to High(FNeighborhoodData) do
begin
FNeighborhoodData[i] := _Source.FNeighborhoodData[i];
end;
SetLength(FDescriptorData, High(_Source.FDescriptorData) + 1);
for i := Low(FDescriptorData) to High(FDescriptorData) do
begin
FDescriptorData[i].Start := _Source.FDescriptorData[i].Start;
FDescriptorData[i].Size := _Source.FDescriptorData[i].Size;
end;
NeighborType := _Source.NeighborType;
IsValid := _Source.IsValid;
// It's highly recommended to change these ones later.
VertexVertexNeighbors := _Source.VertexVertexNeighbors;
VertexFaceNeighbors := _Source.VertexFaceNeighbors;
end;
end.
|
unit RailBaronDotNet;
interface
uses
System.Drawing, System.Collections, System.ComponentModel,
System.Windows.Forms, System.Data;
type
TWinForm = class(System.Windows.Forms.Form)
{$REGION 'Designer Managed Code'}
strict private
/// <summary>
/// Required designer variable.
/// </summary>
Components: System.ComponentModel.Container;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure InitializeComponent;
{$ENDREGION}
strict protected
/// <summary>
/// Clean up any resources being used.
/// </summary>
procedure Dispose(Disposing: Boolean); override;
private
{ Private Declarations }
public
constructor Create;
end;
[assembly: RuntimeRequiredAttribute(TypeOf(TWinForm))]
implementation
{$AUTOBOX ON}
{$REGION 'Windows Form Designer generated code'}
/// <summary>
/// Required method for Designer support -- do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure TWinForm.InitializeComponent;
begin
//
// TWinForm
//
Self.AutoScaleBaseSize := System.Drawing.Size.Create(5, 13);
Self.ClientSize := System.Drawing.Size.Create(824, 429);
Self.Name := 'TWinForm';
Self.Text := 'WinForm';
end;
{$ENDREGION}
procedure TWinForm.Dispose(Disposing: Boolean);
begin
if Disposing then
begin
if Components <> nil then
Components.Dispose();
end;
inherited Dispose(Disposing);
end;
constructor TWinForm.Create;
begin
inherited Create;
//
// Required for Windows Form Designer support
//
InitializeComponent;
//
// TODO: Add any constructor code after InitializeComponent call
//
end;
end.
|
unit DUlex4;
INTERFACE
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses classes, sysutils,
util1, NcDef2;
{ TUlex1 est une l'analyseur lexical utilisé par Ncompil3.
Le texte est fourni par un descendant de TUgetText. Ce qui permet d'avoir un
texte stocké de différentes façons. Seuls NextString et eof sont importants.
TUgetText fournit le texte ligne par ligne avec NextString.
eof signale qu'il n'y a plus de lignes disponibles.
Init doit placer le pointeur de lecture sur la première ligne.
Posmax et getPos permettent au compilateur de montrer la progression de
la compilation.
FileName s'affichera aussi dans la boite montrant la progression
}
type
TUgetText= class
procedure Init;virtual;abstract;
function NextString:AnsiString;virtual;abstract;
function eof:boolean;virtual;abstract;
function posMax:integer;virtual;abstract;
function getPos:integer;virtual;abstract;
function fileName:AnsiString;virtual;abstract;
end;
TUTextStringList=
class(TUgetText)
list0:TstringList;
line,Fpos:integer;
constructor create(list:Tstringlist);
procedure Init;override;
function NextString:AnsiString;override;
function eof:boolean;override;
function posMax:integer;override;
function getPos:integer;override;
function fileName:AnsiString;override;
end;
TUtextFile=class(TUgetText)
private
Fname:AnsiString;
f:Text;
size,Fpos:integer;
public
constructor create(stF:AnsiString);
destructor destroy;override;
procedure Init;override;
function NextString:AnsiString;override;
function eof:boolean;override;
function posMax:integer;override;
function getPos:integer;override;
function fileName:AnsiString;override;
end;
TUlex1=class
private
Finclus:boolean; { Fichier inclus en cours }
nomFinclus:AnsiString; { nom du fichier inclus en cours }
stList:TUgetText;
st0list:AnsiString;
numInc:integer;
public
constructor create(List:TUgetText);
destructor destroy;override;
procedure lire(var stMot:shortString;
var tp0;
var x:float;
var error:Integer;
var Ligne,colonne:integer;
var numInclus:integer);
procedure lireIgnore
(var stMot:shortString;
var tp0;
var x:float;
var error:Integer;
var Ligne,colonne:integer;
var numInclus:integer);
end;
{ Ulex1 décode essentiellement les nombres non signés, les chaînes, les
identificateurs et les symboles principaux.
stMot est le mot extrait de buf.
Un mot commence par une lettre ou @ suivie de chiffres, de lettres ou du
caractère '_'.
Ulex1 écarte aussi les commentaires encadrés par les accolades ou parenthèses-étoile.
x contient le nombre décodé ( nbi, nbL ou nbR )
error est le code d'erreur.
Les codes d'erreur possibles sont
0: pas d'erreur
1: Identificateur trop long
2: Nombre réel hors limites
3: Caractère inconnu
4: chaîne trop longue
10:erreur fichier inclus
}
IMPLEMENTATION
const
carfin=#26;
const
maxchaineCar=250;
longueurNom=250;
const
chiffre:set of char=['0'..'9'];
chiffreHexa:set of char=['0'..'9','A'..'F','a'..'f'];
lettre:set of char=['a'..'z','A'..'Z','_'];
const
maxBufFileChar=10000;
type
typeFileChar=object
f:TfileStream;
buf:array[-10..maxBufFileChar-1] of char;
p:Integer;
pa:integer;
eof0:boolean;
res:integer;
lig,col:integer;
constructor init(st: AnsiString);
function lire:char;
procedure renvoyer;
function fin:boolean;
destructor done;
end;
constructor typeFileChar.init(st:AnsiString);
begin
eof0:=false;
p:=0;
pa:=0;
f:=TfileStream.create(st,fmOpenRead);
res:=f.read(buf[0],maxBufFileChar);
eof0:=res<>maxBufFileChar;
lig:=1;
col:=1;
end;
function typeFileChar.lire:char;
begin
lire:=buf[p];
if result=#13 then
begin
inc(lig);
col:=1;
end
else
if result<>#10 then inc(col);
inc(p);
inc(pa);
if p=maxBufFileChar then
begin
move(buf[maxBufFileChar-10],buf[-10],10);
res:= f.read(buf[0],maxBufFileChar);
eof0:=res<>maxBufFileChar;
p:=0;
end;
end;
procedure typeFileChar.renvoyer;
begin
if p>-10 then
begin
dec(p);
dec(pa);
end;
end;
function typeFileChar.fin:boolean;
begin
fin:=eof0 and (p>=res);
end;
destructor typeFileChar.done;
begin
f.free;
end;
const
ffc:^typeFileChar=nil;
{ ************************************************************************** }
{ ********************* ANALYSEUR LEXICAL ********************************** }
{ ************************************************************************** }
procedure TUlex1.lire(var stMot:shortString;
var tp0;
var x:float;
var error:Integer;
var ligne,colonne:integer;
var numInclus:integer);
var
tp:typeLex ABSOLUTE tp0;
c,c1:char;
st0:shortString;
code:integer;
fin,flag,flagDebutINC,flag1,finCom:boolean;
nbdigit:integer;
w:integer;
stN:AnsiString;
function lire:char;
begin
if Finclus then
begin
lire:=ffc^.lire;
if ffc^.fin then
begin
dispose(ffc,done);
ffc:=nil;
Finclus:=false;
end;
end
else
begin
if stList.eof and (colonne>=length(st0list)) then lire:=carfin
else
begin
inc(colonne);
if colonne<=length(st0list) then lire:=st0list[colonne]
else
begin
inc(ligne);
colonne:=0;
lire:=' ';
if not stList.eof
then st0List:=stList.NextString
else st0List:='';
end;
end;
end;
numInclus:=numInc;
{messageCentral(result);}
if result=#9 then result:=' '; { Remplacer tabulation par espace }
end;
procedure renvoyer;
begin
if Finclus
then ffc^.renvoyer
else
if colonne>0 then dec(colonne);
end;
function FindAFile(stF, stParent:AnsiString):AnsiString;
var
withPath:boolean;
st1:AnsiString;
begin
withPath:= (pos(':',stF)>0) or (pos('\',stF)>0);
if withPath and FileExists(stF) then result:=stF
else
begin
st1:=extractFilePath(stParent)+extractFileName(stF);
if FileExists(st1) then result:=st1
else result:='';
end;
end;
procedure analyseINC;
var
st1:AnsiString;
begin
nomFinclus:='';
repeat
nomFinclus:=nomFinclus+lire
until (length(nomFinclus)>=90) or (nomFinclus[length(nomFinclus)]='}');
if length(nomFinclus)>=90 then
begin
repeat c:=lire until (c=carfin) or (c='}');
renvoyer;
end
else
begin
delete(nomFinclus,length(nomFinclus),1); { supprimer parenthèse de fin }
nomFinclus:=FsupespaceDebut(nomFinclus);
nomFinclus:=FsupespaceFin(nomFinclus); { supprimer les espaces de début et de fin }
st1:= FindAFile(nomFinclus,stList.fileName);
if nomFinclus='' then
begin
error:=10;
ffc:=nil;
exit;
end;
try
new(ffc,init(nomFinclus));
Finclus:=true;
inc(numInc);
except
error:=10;
dispose(ffc,done);
ffc:=nil;
Finclus:=false;
end;
end;
end;
begin
st0:='';
stMot:='';
x:=0;
tp:=vid;
error:=0;
flagDebutINC:=false;
repeat
repeat c:=lire until not(c in[' ',#10,#13,#0]);
flag1:=false;
flag:=(c='{');
if c='(' then
begin
flag1:=(lire='*');
if not flag1 then renvoyer;
end;
if flag or flag1 then
begin
c:=lire;
if flag and (c='$') then
begin
c1:=lire;
if c1<>'}' then
begin
c:=lire;
if not Finclus and ((c1='I') or (c1='i')) and (c=' ') then
begin
analyseINC;
flagDebutINC:=true;
end
else
begin
stMot:=c1+c;
while (c<>'}') and (c<>carfin) do
begin
c:=lire;
stMot:=stMot+c;
end;
if c='}' then delete(stMot,length(stMot),1);
tp:=directive;
exit;
end;
end
else renvoyer;
end
else renvoyer;
finCom:=false;
if not flagDebutINC then
repeat
c:=lire;
if flag and (c='}') then finCom:=true;
if flag1 and (c='*') then
begin
c:=lire;
if c=')' then fincom:=true else renvoyer;
end;
until (c=carfin) or finCom;
flagDebutInc:=false;
end;
until not (flag or flag1);
if c=carFin then
begin
renvoyer; { Les prochains appels renverront toujours Carfin }
tp:=FinFich;
exit;
end;
case c of
'+':tp:=plus;
'-':tp:=moins;
'*':tp:=mult;
'/':tp:=divis;
'^':tp:=expos;
'(':tp:=parOu;
')':tp:=parFer;
'[':tp:=croOu;
']':tp:=croFer;
',':tp:=virgule;
';':tp:=PointVirgule;
'=':tp:=egal;
':':
begin
c:=lire;
if c='=' then tp:=DeuxPointEgal
else
begin
tp:=DeuxPoint;
renvoyer;
end;
end;
'.':
begin
c:=lire;
if c='.' then tp:=PointDouble
else
begin
tp:=PointL;
renvoyer;
end;
end;
'''','#':
begin
stmot:='';
repeat
if c='''' then
begin
fin:=false;
repeat
stMot:=stMot+lire;
flag:=(length(stMot)>=maxchaineCar) or
(stMot[length(stMot)] in [carfin,#10,#13]);
if not flag and (stMot[length(stMot)]='''') then
begin
c:=lire;
if c<>'''' then
begin
renvoyer;
fin:=true;
end;
end;
until flag or fin;
delete(stMot,length(stMot),1);
end
else
if c='#' then
begin
c:=lire;
stN:='';
while c in chiffre do
begin
stN:=stN+c;
c:=lire;
end;
val(stN,w,code);
stMot:=stMot+chr(w);
renvoyer;
end;
c:=lire;
until flag or not( c in ['#','''']) ;
renvoyer;
if flag then error:=4;
if length(stMot)=1
then tp:=ConstCar
else tp:=chaineCar;
end;
'A'..'Z','a'..'z','@':
begin
st0:=c;
repeat
st0:=st0+lire;
until not( st0[length(st0)] in lettre+chiffre );
renvoyer;
delete(st0,length(st0),1);
stMot:=st0;
if length(st0)>longueurNom then error:=1;
end;
'0'..'9':
begin
st0:=c;
while st0[length(st0)] in chiffre do st0:=st0+lire;
if not (st0[length(st0)] in ['.','E','e']) then
begin
renvoyer;
delete(st0,length(st0),1);
val(st0,x,code);
if (x<=32767) then tp:=nbi
else
if (x<=2147483647) then tp:=nbL
else tp:=nbr;
exit;
end;
if st0[length(st0)]='.' then
begin
st0:=st0+lire;
if st0[length(st0)]='.' then
begin
renvoyer;
renvoyer;
delete(st0,length(st0)-1,2);
val(st0,x,code);
if (x<=32767) then tp:=nbi
else
if (x<=2147483647) then tp:=nbL
else tp:=nbr;
exit;
end;
while st0[length(st0)] in chiffre do st0:=st0+lire;
end;
if (st0[length(st0)]='E') or (st0[length(st0)]='e') then
begin
st0:=st0+lire;
if (st0[length(st0)]='+') or (st0[length(st0)]='-') then
st0:=st0+lire;
while st0[length(st0)] in chiffre do st0:=st0+lire;
end;
renvoyer;
delete(st0,length(st0),1);
val(st0,x,code);
if code=0 then tp:=nbr
else error:=2;
end;
'$':
begin
st0:=c;
nbDigit:=0;
repeat
st0:=st0+lire;
inc(nbDigit);
until not (st0[length(st0)] in chiffreHexa);
if nbDigit>9 then
begin
error:=2;
exit;
end;
renvoyer;
delete(st0,length(st0),1);
val(st0,w,code);
x:=w;
if (x<=32767) then tp:=nbi
else tp:=nbL;
exit;
end;
'<':
begin
c:=lire;
if c='=' then tp:=infEgal
else
if c='>' then tp:=different
else
begin
tp:=inf;
renvoyer;
end;
end;
'>':
begin
c:=lire;
if c='=' then tp:=SupEgal
else
begin
tp:=sup;
renvoyer;
end;
end;
else
begin
stMot:=c;
error:=3;
end;
end;
st0:=Fmaj(st0);
if st0='OR' then tp:=OpOR
else
if st0='AND' then tp:=OpAND
else
if st0='XOR' then tp:=OpXOR
else
if st0='NOT' then tp:=OpNOT
else
if st0='DIV' then tp:=OpDiv
else
if st0='MOD' then tp:=OpMod
else
if st0='SHL' then tp:=OpShl
else
if st0='SHR' then tp:=OpShr;
end;
procedure TUlex1.lireIgnore(var stMot:shortString;
var tp0;
var x:float;
var error:Integer;
var Ligne,colonne:integer;
var numInclus:integer);
var
tp:typeLex ABSOLUTE tp0;
c:char;
function lire:char;
begin
if stList.eof and (colonne>=length(st0list)) then lire:=carfin
else
begin
inc(colonne);
if colonne<=length(st0list) then lire:=st0list[colonne]
else
begin
inc(ligne);
colonne:=0;
lire:=' ';
if not stList.eof
then st0List:=stList.NextString
else st0List:='';
end;
end;
end;
procedure renvoyer;
begin
if colonne>0 then dec(colonne);
end;
begin
stMot:='';
x:=0;
tp:=vid;
error:=0;
repeat
repeat c:=lire until (c='{') or (c=carfin);
if c='{' then
begin
c:=lire;
if (c='$') then
begin
c:=lire;
stMot:=c;
while (c<>'}') and (c<>carfin) do
begin
c:=lire;
stMot:=stMot+c;
end;
if c='}' then delete(stMot,length(stMot),1);
supespace(stMot);
if (Fmaj(stMot)='ELSE') OR (Fmaj(stMot)='ENDIF') then
begin
tp:=directive;
exit;
end;
end;
end;
until c=carfin;
if c=carFin then
begin
renvoyer; { Les prochains appels renverront toujours Carfin }
tp:=FinFich;
exit;
end;
end;
constructor TUlex1.create(list:TUgetText);
begin
stList:=list;
st0list:='';
Finclus:=false;
numInc:=0;
stList.Init;
end;
Destructor TUlex1.destroy;
begin
if Finclus then
begin
if ffc<>nil then dispose(ffc,done);
ffc:=nil;
{Finclus:=false;}
end;
end;
{ TUTextStringList }
constructor TUTextStringList.create(list: Tstringlist);
begin
list0:=list;
end;
function TUTextStringList.eof: boolean;
begin
result:= (line>=list0.count);
end;
function TUTextStringList.fileName: AnsiString;
begin
result:='';
end;
function TUTextStringList.getPos: integer;
begin
result:=Fpos;
end;
procedure TUTextStringList.Init;
begin
inherited;
line:=0;
Fpos:=0;
end;
function TUTextStringList.NextString: AnsiString;
begin
result:='';
if line<list0.count then
begin
result:=list0[line];
Fpos:=Fpos+length(result);
inc(line);
end;
end;
function TUTextStringList.posMax: integer;
begin
posmax:=length(list0.text);
end;
{ TUtextFile }
constructor TUtextFile.create(stF:AnsiString);
begin
try
assignFile(f,stF);
reset(f);
size:=fileSize(f);
Fname:=stF;
except
Fname:='';
end;
end;
destructor TUtextFile.destroy;
begin
CloseFile(f);
inherited;
end;
function TUtextFile.eof: boolean;
begin
result:= system.eof(f);
end;
function TUtextFile.getPos: integer;
begin
result:=Fpos;
end;
procedure TUtextFile.Init;
begin
end;
function TUtextFile.NextString: AnsiString;
begin
if eof then result:=''
else
begin
readln(f,result);
inc(Fpos,length(result));
end;
end;
function TUtextFile.posMax: integer;
begin
result:=size;
end;
function TUtextFile.fileName:AnsiString;
begin
result:=Fname;
end;
end.
|
unit rpuFoodsReport;
interface
uses
System.SysUtils, System.Classes, Variants, frxClass, frxDBSet, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, vwuFoodsComposition, fruDateTimeFilter,
fruCusomerRKFilter, CR.Application;
type
TrpFoodsReport = class(TDataModule)
frDataset: TfrxDBDataset;
frDatasetOper: TfrxDBDataset;
F: TFDMemTable;
FID: TIntegerField;
FVisit: TIntegerField;
FMidServer: TIntegerField;
FIdentInVisit: TIntegerField;
FLogicDate: TSQLTimeStampField;
FCheckNum: TIntegerField;
FTableName: TWideStringField;
FSumMoney: TFloatField;
FDiscountSum: TFloatField;
FPaidSum: TFloatField;
FCardCode: TWideStringField;
FCustomerName: TWideStringField;
FOpenTable: TSQLTimeStampField;
FCloseTable: TSQLTimeStampField;
FDiscountName: TWideStringField;
FCurrencyName: TWideStringField;
FNetName: TWideStringField;
FRestaurantName: TWideStringField;
FComposition: TFDMemTable;
FCompositionID: TIntegerField;
FCompositionMidServer: TIntegerField;
FCompositionVisit: TIntegerField;
FCompositionName: TWideStringField;
FCompositionPrice: TFloatField;
FCompositionQuantity: TFloatField;
FCompositionSumMoney: TFloatField;
FCompositionDiscountSum: TFloatField;
FCompositionPaySum: TFloatField;
DS: TDataSource;
frReport: TfrxReport;
FCompositionIdentInVisit: TIntegerField;
procedure DataModuleCreate(Sender: TObject);
procedure frReportGetValue(const VarName: string; var Value: Variant);
private
FDateFilter: TfrDateTimeFilter;
FCustomerFilter: TfrCusomerRKFilter;
FCardNumFilter: Variant;
FUserFilter: String;
FFilterCaption: String;
function GetUserFilter(): String;
function GetCustomerFilterValue(): Variant;
function GetCustomerFilterCaption(): String;
function GetDateFilterCaption(): String;
function GetUserFilterCaption(): String;
public
procedure Init(const CheckList: TDataSet);
procedure Print();
property DateFilter: TfrDateTimeFilter read FDateFilter write FDateFilter;
property CustomerFilter: TfrCusomerRKFilter read FCustomerFilter write FCustomerFilter;
property CardNumFilter: Variant read FCardNumFilter write FCardNumFilter;
property UserFilter: String read FUserFilter write FUserFilter;
property FilterCaption: String read FFilterCaption write FFilterCaption;
end;
implementation
uses
uServiceUtils, eduPrintSample;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TrpFoodsReport }
procedure TrpFoodsReport.DataModuleCreate(Sender: TObject);
begin
F.Close;
F.CreateDataSet;
FComposition.Close;
FComposition.CreateDataSet;
end;
procedure TrpFoodsReport.frReportGetValue(const VarName: string; var Value: Variant);
begin
if AnsiCompareStr(VarName, 'Пользовательские фильтры') = 0 then
begin
Value := GetCustomerFilterCaption + GetDateFilterCaption() + GetUserFilterCaption();
if Value = '' then
Value := #13#10;
end;
//
// if AnsiCompareStr(VarName, 'Период фильтр') = 0 then
// Value := GetDateFilterCaption();
end;
function TrpFoodsReport.GetCustomerFilterValue(): Variant;
begin
Result := Null;
if Assigned(CustomerFilter) then
Result := CustomerFilter.KeyValue;
end;
function TrpFoodsReport.GetCustomerFilterCaption: String;
begin
if GetCustomerFilterValue <> Null then
Result := 'Владелец карты: ' + VarToStr(GetCustomerFilterValue) + #13#10
else
Result := '';
end;
function TrpFoodsReport.GetDateFilterCaption: String;
function GetDate(const Value: Variant): String;
begin
Result := '';
if Value <> Null then
Result := FormatDateTime('dd.mm.yyyy', Value);
end;
var
FromDate: String;
TillDate: String;
begin
Result := '';
if not Assigned(DateFilter) then
Exit;
FromDate := GetDate(DateFilter.FromDate);
TillDate := GetDate(DateFilter.TillDate);
if FromDate <> '' then
Result := 'c ' + FromDate;
if TillDate <> '' then
begin
if Result <> '' then
Result := Result + ' ';
Result := Result + 'по ' + TillDate;
end;
if Result <> '' then
Result := 'Период: ' + Result + #13#10;
end;
function TrpFoodsReport.GetUserFilterCaption(): String;
begin
Result := '';
if FFilterCaption <> '' then
Result := 'Пользовательские фильтры: ' + FFilterCaption + #13#10;
end;
function TrpFoodsReport.GetUserFilter: String;
begin
Result := '';
if FUserFilter <> '' then
Result := ' AND ' + FUserFilter;
end;
procedure TrpFoodsReport.Init;
var
KeyValue: Variant;
Composition: TvwFoodsComposition;
begin
if not CheckList.Active then
Exit;
KeyValue := CheckList.FieldByName('ID').Value;
CheckList.DisableControls;
try
CheckList.Filter := FUserFilter;
CheckList.Filtered := FUserFilter <> '';
CheckList.First;
while not CheckList.Eof do
begin
F.Append;
FID.Value := CheckList.FieldByName('ID').Value;
FVisit.Value := CheckList.FieldByName('Visit').Value;
FMidServer.Value := CheckList.FieldByName('MidServer').Value;
FIdentInVisit.Value := CheckList.FieldByName('IdentInVisit').Value;
FLogicDate.AsDateTime := CheckList.FieldByName('LogicDate').AsDateTime;
FCheckNum.Value := CheckList.FieldByName('CheckNum').Value;
FTableName.Value := CheckList.FieldByName('TableName').Value;
FSumMoney.Value := CheckList.FieldByName('SumMoney').Value;
FDiscountSum.Value := CheckList.FieldByName('DiscountSum').Value;
FPaidSum.Value := CheckList.FieldByName('PaidSum').Value;
FCardCode.Value := CheckList.FieldByName('CardCode').Value;
FCustomerName.Value := CheckList.FieldByName('CustomerName').Value;
FOpenTable.AsDateTime := CheckList.FieldByName('OpenTable').AsDateTime;
FCloseTable.AsDateTime := CheckList.FieldByName('CloseTable').AsDateTime;
FDiscountName.Value := CheckList.FieldByName('DiscountName').Value;
FCurrencyName.Value := CheckList.FieldByName('CurrencyName').Value;
FNetName.Value := CheckList.FieldByName('NetName').Value;
FRestaurantName.Value := CheckList.FieldByName('RestaurantName').Value;
F.Post;
CheckList.Next;
end;
finally
CheckList.Filter := '';
CheckList.Filtered := False;
CheckList.EnableControls;
if not IsNullID(KeyValue) then
CheckList.Locate('ID', KeyValue, []);
end;
Composition := TvwFoodsComposition.Create(Self);
try
Composition.DateFilter := FDateFilter;
Composition.CustomerFilter := Null;
Composition.Connection := CRApplication.DBConnection;
Composition.CustomerFilter := GetCustomerFilterValue();
Composition.CardNumFilter := FCardNumFilter;
Composition.AddCustomSqlFilter(GetUserFilter);
Composition.RefreshData(Null);
while not Composition.F.Eof do
begin
FComposition.Append;
FCompositionID.Value := Composition.FID.Value;
FCompositionMidServer.Value := Composition.FMidServer.Value;
FCompositionVisit.Value := Composition.FVisit.Value;
FCompositionName.Value := Composition.FName.Value;
FCompositionPrice.Value := Composition.FPrice.Value;
FCompositionQuantity.Value := Composition.FQuantity.Value;
FCompositionSumMoney.Value := Composition.FSumMoney.Value;
FCompositionDiscountSum.Value := Composition.FDiscountSum.Value;
FCompositionPaySum.Value := Composition.FPaySum.Value;
FComposition.Post;
Composition.F.Next;
end;
finally
Composition.Free;
end;
end;
procedure TrpFoodsReport.Print();
begin
TedPrintSample.Print(frReport, Self.ClassName, True, True);
end;
end.
|
unit sChart; // version 1.0 for delphi 10.3
interface
uses ExtCtrls, SysUtils, Graphics, Forms, Windows, System.Classes, System.Generics.Collections, Vcl.StdCtrls, System.Math, System.Types;
type
tCandle = class
Close: Extended;
High: Extended;
Low: Extended;
Open: Extended;
end;
tChartSet = class
Box: Boolean; // should be drawn only once in the same PaintBox
CandleColor: Boolean;
Decimal: Integer;
Gradation: Extended;
GradationExtend: Boolean;
HorizontalLine: Boolean; // can be used as a base line with HorizontalLineY
HorizontalLineY: Extended;
LabelWidth: Integer;
LineColor: Integer; // e.g. clRed
PaintBox: TPaintBox;
end;
tChart = class
private
X: Integer;
Height, Width: Integer;
SeriesMaxValue, SeriesMinValue: Extended;
Multiplier: Extended;
Range: Extended;
XWidth: Extended;
ChartSet: tChartSet;
Points: array of TPoint;
ColorList: TList<Integer>;
CandleLines: Boolean;
procedure Gradation;
procedure ChartInitialize;
procedure HorizontalLineDraw(_Canvas: TCanvas; _Y: Integer; _Horizon: Boolean);
procedure MultiplierCalculate;
public
procedure CandleDraw(_Candles: TList<tCandle>);
procedure LineDraw(_Extendeds: TList<Extended>); overload;
procedure LineDraw(_Integers: TList<Integer>); overload;
procedure LinesDraw(var _Lines: array of TList<Extended>);
procedure CandleLinesDraw(_Candles: TList<tCandle>; var _Lines: array of TList<Extended>);
constructor Create(_ChartSet: tChartSet);
end;
implementation
{ ChartClass }
procedure tChart.CandleDraw(_Candles: TList<tCandle>);
var
_Y1, _Y2: Integer;
i: Integer;
begin
ChartInitialize;
if _Candles.Count > 0 then
begin
if not CandleLines then
begin
SeriesMaxValue := _Candles.List[0].High;
SeriesMinValue := _Candles.List[0].Low;
for i := 0 to _Candles.Count - 1 do
begin
if CompareValue(_Candles.List[i].High, SeriesMaxValue) = GreaterThanValue then
begin
SeriesMaxValue := _Candles.List[i].High;
end;
if CompareValue(_Candles.List[i].Low, SeriesMinValue) = LessThanValue then
begin
SeriesMinValue := _Candles.List[i].Low;
end;
end;
end;
MultiplierCalculate;
Gradation;
if _Candles.Count = 1 then
begin
XWidth := 0;
end
else
begin
XWidth := Width / (_Candles.Count - 1);
end;
for i := 0 to _Candles.Count - 1 do
begin
if _Candles.Count = 1 then
begin
X := Round(Width / 2) + 5;
end
else
begin
X := Round(i * XWidth) + 5;
end;
if ChartSet.CandleColor then
begin
if CompareValue(_Candles.List[i].Close, _Candles.List[i].Open) = GreaterThanValue then
begin
ChartSet.PaintBox.Canvas.Pen.Color := clRed;
ChartSet.PaintBox.Canvas.Brush.Color := clRed;
end
else if CompareValue(_Candles.List[i].Close, _Candles.List[i].Open) = LessThanValue then
begin
ChartSet.PaintBox.Canvas.Pen.Color := clBlue;
ChartSet.PaintBox.Canvas.Brush.Color := clBlue;
end
else
begin
if i = 0 then
begin
ChartSet.PaintBox.Canvas.Pen.Color := clRed;
ChartSet.PaintBox.Canvas.Brush.Color := clRed;
end
else if CompareValue(_Candles.List[i].Close, _Candles.List[i - 1].Close) = GreaterThanValue then
begin
ChartSet.PaintBox.Canvas.Pen.Color := clRed;
ChartSet.PaintBox.Canvas.Brush.Color := clRed;
end
else if CompareValue(_Candles.List[i].Close, _Candles.List[i - 1].Close) = LessThanValue then
begin
ChartSet.PaintBox.Canvas.Pen.Color := clBlue;
ChartSet.PaintBox.Canvas.Brush.Color := clBlue;
end
else
begin
if CompareValue(_Candles.List[i - 1].Open, _Candles.List[i - 1].Close) = GreaterThanValue then
begin
ChartSet.PaintBox.Canvas.Pen.Color := clBlue;
ChartSet.PaintBox.Canvas.Brush.Color := clBlue;
end
else if CompareValue(_Candles.List[i - 1].Open, _Candles.List[i - 1].Close) = LessThanValue then
begin
ChartSet.PaintBox.Canvas.Pen.Color := clRed;
ChartSet.PaintBox.Canvas.Brush.Color := clRed;
end;
end;
end;
end
else
begin
ChartSet.PaintBox.Canvas.Pen.Color := clBlack;
ChartSet.PaintBox.Canvas.Brush.Color := clBlack;
end;
ChartSet.PaintBox.Canvas.MoveTo(X + 1, Round((SeriesMaxValue - _Candles.List[i].High) * Multiplier) + 5); // vertical penetration
ChartSet.PaintBox.Canvas.LineTo(X + 1, Round((SeriesMaxValue - _Candles.List[i].Low ) * Multiplier) + 5);
_Y1 := Round((SeriesMaxValue - _Candles.List[i].Open) * Multiplier) + 5;
_Y2 := Round((SeriesMaxValue - _Candles.List[i].Close) * Multiplier) + 5;
if CompareValue(_Candles.List[i].Open, _Candles.List[i].Close) = EqualsValue then
begin
if Range = 0 then // draws in vertical center height
begin
ChartSet.PaintBox.Canvas.MoveTo(X, Round(Height / 2) + 5);
ChartSet.PaintBox.Canvas.LineTo(X + 3, Round(Height / 2) + 5);
end
else
begin
ChartSet.PaintBox.Canvas.MoveTo(X, _Y1);
ChartSet.PaintBox.Canvas.LineTo(X + 3, _Y2);
end;
end
else
begin
ChartSet.PaintBox.Canvas.Rectangle(X, _Y1, X + 3, _Y2);
end;
end;
end;
end;
procedure tChart.LineDraw(_Extendeds: TList<Extended>);
var
i: Integer;
begin
ChartInitialize;
if _Extendeds.Count > 1 then
begin
SeriesMaxValue := _Extendeds[0];
SeriesMinValue := _Extendeds[0];
for i := 0 to _Extendeds.Count - 1 do
begin
if CompareValue(_Extendeds.List[i], SeriesMaxValue) = GreaterThanValue then
begin
SeriesMaxValue := _Extendeds.List[i];
end
else if CompareValue(_Extendeds.List[i], SeriesMinValue) = LessThanValue then
begin
SeriesMinValue := _Extendeds.List[i];
end;
end;
MultiplierCalculate;
Gradation;
XWidth := Width / (_Extendeds.Count - 1);
SetLength(Points, _Extendeds.Count);
ChartSet.PaintBox.Canvas.Pen.Color := ChartSet.LineColor;
for i := 0 to _Extendeds.Count - 1 do
begin
Points[i] := Point(Round((i) * XWidth) + 5, Round((SeriesMaxValue - _Extendeds.List[i]) * Multiplier) + 5);
end;
ChartSet.PaintBox.Canvas.Polyline(Points);
end;
end;
procedure tChart.CandleLinesDraw(_Candles: TList<tCandle>; var _Lines: array of TList<Extended>);
var
i, j: Integer;
begin
CandleLines := True;
SeriesMaxValue := _Candles.List[0].High;
SeriesMinValue := _Candles.List[0].Low;
for i := 0 to _Candles.Count - 1 do
begin
if CompareValue(_Candles.List[i].High, SeriesMaxValue) = GreaterThanValue then
begin
SeriesMaxValue := _Candles.List[i].High;
end;
if CompareValue(_Candles.List[i].Low, SeriesMinValue) = LessThanValue then
begin
SeriesMinValue := _Candles.List[i].Low;
end;
end;
for i := 0 to High(_Lines) do
begin
for j := 0 to _Lines[i].Count - 1 do
begin
if CompareValue(_Lines[i].List[j], SeriesMaxValue) = GreaterThanValue then
begin
SeriesMaxValue := _Lines[i].List[j];
end
else if CompareValue(_Lines[i].List[j], SeriesMinValue) = LessThanValue then
begin
SeriesMinValue := _Lines[i].List[j];
end;
end;
end;
CandleDraw(_Candles);
LinesDraw(_Lines);
CandleLines := False;
end;
procedure tChart.ChartInitialize;
begin
Width := ChartSet.PaintBox.Width - ChartSet.LabelWidth - 13;
Height := ChartSet.PaintBox.Height - 10;
if ChartSet.Box then // not include label
begin
ChartSet.PaintBox.Canvas.Brush.Color := clWhite;
ChartSet.PaintBox.Canvas.Pen.Color := clBlack;
ChartSet.PaintBox.Canvas.Rectangle(0, 0, Width + 13, Height + 10);
end;
end;
constructor tChart.Create(_ChartSet: tChartSet);
begin
ChartSet := _ChartSet;
ColorList := TList<Integer>.Create;
ColorList.Add(clBlack); // you may add more
ColorList.Add(clRed);
ColorList.Add(clBlue);
ColorList.Add(clGreen);
ColorList.Add(clLime);
end;
procedure tChart.Gradation;
var
_Max, _Min: Integer;
_Gradation, _GradationMinor, _GradiationX: Integer;
_Y: Integer;
_iExtended: Extended;
_Mod: Integer;
i: Integer;
begin
if ChartSet.Gradation > 0 then
begin
ChartSet.PaintBox.Canvas.Brush.Color := clWhite;
ChartSet.PaintBox.Canvas.Pen.Color := clBlack;
_Max := Round(Power10(SeriesMaxValue, ChartSet.Decimal)); // extended -> integer
_Min := Round(Power10(SeriesMinValue, ChartSet.Decimal));
_Gradation := Round(Power10(ChartSet.Gradation, ChartSet.Decimal));
_GradationMinor := Round(_Gradation / 5);
_GradiationX := ChartSet.PaintBox.Width - ChartSet.LabelWidth;
if _Max > _Min then
begin
for i := _Min to _Max do
begin
_Mod := i mod _Gradation;
if (_Mod = 0) or (i mod _GradationMinor = 0) then
begin
_iExtended := i / Power10(1, ChartSet.Decimal);
_Y := Round((SeriesMaxValue - _iExtended) * Multiplier) + 5;
ChartSet.PaintBox.Canvas.Pen.Color := clBlack;
if _Mod = 0 then
begin
ChartSet.PaintBox.Canvas.MoveTo(_GradiationX, _Y);
ChartSet.PaintBox.Canvas.LineTo(_GradiationX + 5, _Y);
SetTextAlign(ChartSet.PaintBox.Canvas.Handle, TA_RIGHT);
ChartSet.PaintBox.Canvas.TextOut(ChartSet.PaintBox.Width - 5, _Y - 7, Format('%.*n', [ChartSet.Decimal, _iextended]));
if ChartSet.GradationExtend then
begin
HorizontalLineDraw(ChartSet.PaintBox.Canvas, _Y, False);
end;
end
else
begin
ChartSet.PaintBox.Canvas.MoveTo(_GradiationX, _Y);
ChartSet.PaintBox.Canvas.LineTo(_GradiationX + 3, _Y);
end;
end;
end;
if ChartSet.HorizontalLine then
begin
_Y := Round((SeriesMaxValue - ChartSet.HorizontalLineY) * Multiplier) + 5;
HorizontalLineDraw(ChartSet.PaintBox.Canvas, _Y, True);
end;
end;
end;
end;
procedure tChart.HorizontalLineDraw(_Canvas: TCanvas; _Y: Integer; _Horizon: Boolean);
begin
if _Horizon then
begin
_Canvas.Pen.Color := clSilver;
end
else
begin
_Canvas.Pen.Color := clBtnFace;
end;
_Canvas.MoveTo(5, _Y);
_Canvas.LineTo(Width + 10, _Y);
end;
procedure tChart.LineDraw(_Integers: TList<Integer>);
var
i: Integer;
begin
ChartInitialize;
if _Integers.Count > 1 then
begin
SeriesMaxValue := _Integers[0];
SeriesMinValue := _Integers[0];
for i := 0 to _Integers.Count - 1 do
begin
if _Integers.List[i] > SeriesMaxValue then
begin
SeriesMaxValue := _Integers.List[i];
end
else if _Integers.List[i] < SeriesMinValue then
begin
SeriesMinValue := _Integers.List[i];
end;
end;
MultiplierCalculate;
Gradation;
XWidth := Width / (_Integers.Count - 1);
SetLength(Points, _Integers.Count);
ChartSet.PaintBox.Canvas.Pen.Color := ChartSet.LineColor;
for i := 0 to _Integers.Count - 1 do
begin
Points[i] := Point(Round((i) * XWidth) + 5, Round((SeriesMaxValue - _Integers.List[i]) * Multiplier) + 5);
end;
ChartSet.PaintBox.Canvas.Polyline(Points);
end;
end;
procedure tChart.LinesDraw(var _Lines: array of TList<Extended>);
var
i, j: Integer;
begin
if not CandleLines then
begin
ChartInitialize;
end;
if _Lines[0].Count > 1 then
begin
if not CandleLines then
begin
SeriesMaxValue := _Lines[0].List[0];
SeriesMinValue := _Lines[0].List[0];
for i := 0 to High(_Lines) do
begin
for j := 0 to _Lines[i].Count - 1 do
begin
if CompareValue(_Lines[i].List[j], SeriesMaxValue) = GreaterThanValue then
begin
SeriesMaxValue := _Lines[i].List[j];
end
else if CompareValue(_Lines[i].List[j], SeriesMinValue) = LessThanValue then
begin
SeriesMinValue := _Lines[i].List[j];
end;
end;
end;
end;
MultiplierCalculate;
if not CandleLines then
begin
Gradation;
end;
XWidth := Width / (_Lines[0].Count - 1);
SetLength(Points, _Lines[0].Count);
for i := 0 to High(_Lines) do
begin
for j := 0 to _Lines[i].Count - 1 do
begin
Points[j] := Point(Round(j * XWidth) + 5, Round((SeriesMaxValue - _Lines[i].List[j]) * Multiplier) + 5);
ChartSet.PaintBox.Canvas.Pen.Color := ColorList.List[i];
end;
ChartSet.PaintBox.Canvas.Polyline(Points);
end;
end;
end;
procedure tChart.MultiplierCalculate;
begin
Range := SeriesMaxValue - SeriesMinValue;
if CompareValue(Range, 0) = EqualsValue then
begin
Multiplier := 0;
end
else
begin
Multiplier := Height / Range;
end;
end;
end.
|
Unit read_write;
{ * Read_Write : *
* *
* Esta unidad contiene las llamadas al sistema DO_READ , DO_WRITE Y *
* DO_SEEK , importantisimas para el sistema de archivos , ya que ma *
* nipulan los ficheros *
* *
* Copyright (c) 2003-2005 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* 07 / 07 / 2005 : Reescritura integra de las syscalls para *
* la implementacion del VFS *
* *
* 26 / 12 / 2004 : Los threads de kernel no pueden realizar *
* llamadas al FS *
* *
* 06 / 08 / 2004 : Se aplica el modelo paginado , los threads tam *
* bien pueden realizar llamadas al FS *
* 30 / 03 / 2004 : Las copias son realizadas sobre el segmento FS *
* *
* 12 / 03 / 2004 : Primera Version *
* *
*********************************************************************
}
interface
{DEFINE DEBUG}
{$I ../include/toro/procesos.inc}
{$I ../include/head/asm.h}
{$I ../include/head/inodes.h}
{$I ../include/toro/buffer.inc}
{$I ../include/head/buffer.h}
{$I ../include/head/scheduler.h}
{$I ../include/head/blk_dev.h}
{$I ../include/head/printk_.h}
{$I ../include/head/procesos.h}
implementation
{$I ../include/head/lock.h}
{ * Sys_Seek : *
* *
* File_Desc : Descriptor del archivo *
* offset : Posicion donde se quiere posicionar el archivo *
* whence : Algoritmo que se utilizara *
* Devuelve : La nueva posicion del archivo o 0 si falla *
* *
* Se encarga de posicionar un archivo en un byte dado , segun el *
* algoritmo en whence , si la llamada fue correcta devuelve la *
* nueva posicion sino devuelve 0 *
* *
**************************************************************************
}
function sys_seek ( File_desc : dword ; offset , whence : dword ) : dword ; cdecl;[public , alias :'SYS_SEEK'];
var ret : dword ;
p_file : p_file_t ;
begin
{Se chequea el descriptor}
If File_desc > 32 then exit(0);
{Puntero al descriptor}
p_file := @Tarea_Actual^.Archivos[File_desc];
If p_file^.f_op = nil then exit(0);
if p_file^.f_op^.seek = nil then exit(0);
{no se puede hacer un seek sobre un inodo dir}
if p_file^.inodo^.mode = dt_dir then exit(0);
Inode_lock (@p_file^.inodo^.wait_on_inode);
{se llama al driver para que haga el trabajo}
if p_file^.f_op^.seek (p_file,whence,offset) = -1 then ret := 0 else ret := (p_file^.f_pos);
Inode_unlock (@p_file^.inodo^.wait_on_inode);
exit(ret);
end;
{ * Sys_Read: *
* *
* File_Desc : Descriptor del archivo *
* buffer : Puntero donde sera almacemado el contenido *
* nbytes : Numero de bytes leidos *
* Devuelve : El numero de bytes leidos *
* *
* Se encarga de la lectura de un fichero cualquiera sea este *
* *
***********************************************************************
}
function sys_read( File_Desc : dword ; buffer : pointer ; nbytes : dword ) : dword;cdecl;[public, alias :'SYS_READ'];
var pfile:p_file_t;
ret : dword ;
label _exit ;
begin
{Aqui es protegida el area del kernel}
If Buffer < pointer(High_Memory) then
begin
set_errno := -EFAULT ;
goto _exit ;
end;
set_errno := -EBADF ;
If File_desc > 31 then goto _exit ;
{Se puntea al descriptor del archivo}
pfile:=@Tarea_Actual^.Archivos[File_Desc];
{estan definidos los handlers??}
if (pfile^.f_op = nil) then goto _exit ;
{no se abrio para lectura!!}
if (pfile^.f_mode and O_RDONLY = O_RDONLY) then
else
begin
set_errno := -EACCES ;
goto _exit ;
end;
set_errno := -ENODEV;
if (pfile^.inodo^.mode = dt_dir ) and (pfile^.f_op^.readdir = nil) then exit(0)
else if pfile^.f_op^.read = nil then exit(0);
clear_errno;
{esto me asegura la consistencia del archivo}
Inode_lock (@pfile^.inodo^.wait_on_inode);
case pfile^.inodo^.mode of
dt_reg : ret := pfile^.f_op^.read (pfile,nbytes,buffer);
dt_dir : ret := pfile^.f_op^.readdir (pfile,buffer);
dt_blk : ret := Blk_Read (pfile, nbytes ,buffer );
dt_chr : ret := pfile^.f_op^.read(pfile,nbytes,buffer);
end;
Inode_unlock (@pfile^.inodo^.wait_on_inode);
exit(ret);
_exit :
exit(0);
end;
{ * Sys_Write : *
* *
* File_desc : Descriptor del archivo *
* Buffer : Lugar de donde se extraeran los datos *
* nbytes : Numero de bytes *
* Devuelve : Numero de bytes escritos *
* *
* Se encarga de escribir cualquier tipo de fichero *
* *
**********************************************************************
}
function sys_write ( file_desc : dword ; buffer : pointer ; nbytes : dword) : dword;cdecl;[PUBLIC , ALIAS :'SYS_WRITE'];
var pfile : p_file_t;
ret : dword ;
begin
{El buffer devera estar en el area del usuario}
If buffer < pointer(High_Memory) then
begin
set_errno := -EFAULT ;
exit(0);
end;
set_errno := -EBADF;
If File_Desc > 31 then exit(0);
{Se puntea al descriptor del archivo}
pfile:=@Tarea_Actual^.Archivos[File_Desc];
{estan definidos los handlers??}
if (pfile^.f_op = nil) then exit(0);
{no se abrio para escritura!!}
if (pfile^.f_mode and O_WRONLY = O_WRONLY) then
else
begin
set_errno := -EACCES ;
exit(0);
end;
set_errno := -ENODEV;
if (pfile^.inodo^.mode = dt_dir ) then exit(0)
else if pfile^.f_op^.write = nil then exit(0);
clear_errno;
{esta proteccion me asegura que dos procesos no escriban a la ves un mismo}
{archivo}
Inode_lock (@pfile^.inodo^.wait_on_inode);
{segun el tipo de archivo!!!}
case pfile^.inodo^.mode of
dt_reg : ret := (pfile^.f_op^.write (pfile,nbytes,buffer));
dt_blk : ret := (Blk_write (pfile, nbytes ,buffer ));
dt_chr : ret := (pfile^.f_op^.write(pfile,nbytes,buffer));
end;
Inode_unlock (@pfile^.inodo^.wait_on_inode);
exit(ret);
end;
end.
|
unit ufrmStageCreator;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids,
Vcl.ExtCtrls, Datasnap.DBClient, Vcl.DBCtrls, Vcl.StdCtrls,
Vcl.Imaging.pngimage, System.Generics.Collections;
type
TfrmStageCreator = class(TForm)
pnlInformations: TPanel;
pnlImages: TPanel;
dbgStages: TDBGrid;
cdsStages: TClientDataSet;
dsStages: TDataSource;
cdsStagesNumber: TIntegerField;
cdsStagesX: TIntegerField;
cdsStagesY: TIntegerField;
dbnStages: TDBNavigator;
BackGround: TGridPanel;
grpImages: TGridPanel;
pnlWall: TPanel;
imgWall: TImage;
pnlFloor: TPanel;
imgFloor: TImage;
pnlBox: TPanel;
imgBox: TImage;
pnlBoxGoal: TPanel;
imgBoxGoal: TImage;
pnlGoal: TPanel;
imgGoal: TImage;
pnlPlayer: TPanel;
imgPlayer: TImage;
pnlBackGround: TGridPanel;
btnSave: TButton;
cdsStagesPerfectMoves: TIntegerField;
procedure FormShow(Sender: TObject);
procedure imgWallClick(Sender: TObject);
procedure imgFloorClick(Sender: TObject);
procedure imgBoxClick(Sender: TObject);
procedure imgBoxGoalClick(Sender: TObject);
procedure imgGoalClick(Sender: TObject);
procedure imgPlayerClick(Sender: TObject);
procedure cdsStagesAfterPost(DataSet: TDataSet);
procedure btnSaveClick(Sender: TObject);
private
var
FPanels: TObjectDictionary<Integer, TPanel>;
FOpen: Boolean;
procedure NewBackGround(const X, Y: Int16);
procedure CreatPanels(const X, Y: Int16);
procedure LimparTags;
procedure LimparCores;
procedure PanelMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
function ReturnImage: TImage;
{ Private declarations }
public
{ Public declarations }
end;
var
frmStageCreator: TfrmStageCreator;
implementation
{$R *.dfm}
uses uStageJSON, StringFactory;
procedure TfrmStageCreator.btnSaveClick(Sender: TObject);
var
Stage: TStage;
Panel: TPanel;
Image: TImage;
I, X, Y: Integer;
Path: string;
JSON: string;
lJSON: TStringList;
begin
Stage := TStage.Create;
Stage.Stage.Number := cdsStagesNumber.AsInteger;
Stage.Stage.X := cdsStagesX.AsInteger;
Stage.Stage.Y := cdsStagesY.AsInteger;
Stage.Stage.PerfectMoves := cdsStagesPerfectMoves.AsInteger;
for Panel in FPanels.Values do
begin
for I := 0 to Panel.ControlCount - 1 do
begin
X := pnlBackGround.ControlCollection.Items[pnlBackGround.ControlCollection.IndexOf(Panel)].Column + 1;
Y := pnlBackGround.ControlCollection.Items[pnlBackGround.ControlCollection.IndexOf(Panel)].Row + 1;
Image := TImage(Panel.Controls[I]);
case Image.Tag of
1: Stage.Stage.AddWall(X, Y);
2: Stage.Stage.AddFloor(X, Y);
3:
begin
Stage.Stage.AddFloor(X, Y);
Stage.Stage.AddBox(X, Y);
end;
4:
begin
Stage.Stage.AddFloor(X, Y);
Stage.Stage.AddBoxGoal(X, Y);
end;
5:
begin
Stage.Stage.AddFloor(X, Y);
Stage.Stage.AddGoal(X, Y);
end;
6:
begin
Stage.Stage.AddFloor(X, Y);
Stage.Stage.AddPlayer(X, Y);
end;
end;
end;
end;
Path := System.SysUtils.IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'Stages';
JSON := Stage.ToJSONString;
lJSON := TStringList.Create;
try
lJSON.Add(JSON);
lJSON.SaveToFile(System.SysUtils.IncludeTrailingPathDelimiter(Path) + 'stage' + cdsStagesNumber.AsString + '.json');
finally
FreeAndNil(lJSON);
end;
end;
procedure TfrmStageCreator.cdsStagesAfterPost(DataSet: TDataSet);
var
I: Integer;
begin
if not(FOpen) then
begin
if Assigned(FPanels) then
begin
for I := FPanels.Count - 1 downto 0 do
begin
FPanels.Items[I].Free;
FPanels.Remove(I);
end;
FreeAndNil(FPanels);
end;
pnlBackGround.RowCollection.BeginUpdate;
try
pnlBackGround.RowCollection.Clear;
finally
pnlBackGround.RowCollection.EndUpdate;
end;
pnlBackGround.ColumnCollection.BeginUpdate;
try
pnlBackGround.ColumnCollection.Clear;
finally
pnlBackGround.ColumnCollection.EndUpdate;
end;
FPanels := TObjectDictionary<Integer, TPanel>.Create;
NewBackGround(cdsStagesX.AsInteger, cdsStagesY.AsInteger);
CreatPanels(cdsStagesX.AsInteger, cdsStagesY.AsInteger);
end;
end;
function TfrmStageCreator.ReturnImage: TImage;
begin
if pnlWall.Tag = 1 then
Result := imgWall
else if pnlFloor.Tag = 1 then
Result := imgFloor
else if pnlBox.Tag = 1 then
Result := imgBox
else if pnlBoxGoal.Tag = 1 then
Result := imgBoxGoal
else if pnlGoal.Tag = 1 then
Result := imgGoal
else if pnlPlayer.Tag = 1 then
Result := imgPlayer;
end;
procedure TfrmStageCreator.PanelMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
I: Integer;
Image, RetImage: TImage;
begin
if (Button = mbRight) then
begin
if (Sender is TImage) then
TImage(Sender).Free;
end
else
begin
if (Sender is TPanel) then
begin
RetImage := ReturnImage;
Image := TImage.Create(TComponent(Sender));
Image.Parent := TWinControl(Sender);
Image.Align := alClient;
Image.Picture.Graphic := RetImage.Picture.Graphic;
Image.OnMouseUp := PanelMouseUp;
Image.Tag := RetImage.Tag;
end;
end;
end;
procedure TfrmStageCreator.CreatPanels(const X, Y: Int16);
var
lRows, lColumns, Key: Integer;
Panel: TPanel;
function NewPanel: TPanel;
begin
Result := TPanel.Create(BackGround);
Result.Width := 33;
Result.Height := 33;
Result.OnMouseUp := PanelMouseUp;
end;
begin
Key := 0;
for lColumns := 0 to X - 1 do
begin
for lRows := 0 to Y - 1 do
begin
Panel := NewPanel;
Panel.Align := alClient;
Panel.Parent := pnlBackGround;
FPanels.Add(Key, Panel);
Key := Succ(Key);
end;
end;
end;
procedure TfrmStageCreator.FormShow(Sender: TObject);
var
F: TSearchRec;
Ret: Integer;
Stage: TStage;
Path: string;
function HaveAttr(const Attr, Val: Integer): Boolean;
begin
Result := Attr and Val = Val;
end;
begin
FOpen := True;
try
cdsStages.CreateDataSet;
Path := System.SysUtils.IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'Stages';
// Ret := FindFirst(Path + '\*.json', faAnyFile, F);
// try
// while (Ret = 0) do
// begin
// if not HaveAttr(F.Attr, faDirectory) then
// begin
// Stage := TStage.FromJSONString(TStringBuilder.New
// .LoadFromFile((Path + '\' + F.Name))
// .ToString);
// cdsStages.Append;
// cdsStagesNumber.AsInteger := Stage.Stage.Number;
// cdsStagesX.AsInteger := Stage.Stage.X;
// cdsStagesY.AsInteger := Stage.Stage.Y;
// cdsStagesPerfectMoves.AsInteger := Stage.Stage.PerfectMoves;
// cdsStages.Post;
// end;
//
// Ret := FindNext(F);
// end;
// finally
// FindClose(F);
// end;
finally
FOpen := False;
end;
end;
procedure TfrmStageCreator.imgBoxClick(Sender: TObject);
begin
LimparTags;
LimparCores;
pnlBox.Color := clGreen;
pnlBox.Tag := 1;
end;
procedure TfrmStageCreator.imgBoxGoalClick(Sender: TObject);
begin
LimparTags;
LimparCores;
pnlBoxGoal.Color := clGreen;
pnlBoxGoal.Tag := 1;
end;
procedure TfrmStageCreator.imgFloorClick(Sender: TObject);
begin
LimparTags;
LimparCores;
pnlFloor.Color := clGreen;
pnlFloor.Tag := 1;
end;
procedure TfrmStageCreator.imgGoalClick(Sender: TObject);
begin
LimparTags;
LimparCores;
pnlGoal.Color := clGreen;
pnlGoal.Tag := 1;
end;
procedure TfrmStageCreator.imgPlayerClick(Sender: TObject);
begin
LimparTags;
LimparCores;
pnlPlayer.Color := clGreen;
pnlPlayer.Tag := 1;
end;
procedure TfrmStageCreator.LimparCores;
begin
pnlWall.Color := clWhite;
pnlFloor.Color := clWhite;
pnlBox.Color := clWhite;
pnlBoxGoal.Color := clWhite;
pnlGoal.Color := clWhite;
pnlPlayer.Color := clWhite;
end;
procedure TfrmStageCreator.LimparTags;
begin
pnlWall.Tag := 0;
pnlFloor.Tag := 0;
pnlBox.Tag := 0;
pnlBoxGoal.Tag := 0;
pnlGoal.Tag := 0;
pnlPlayer.Tag := 0;
end;
procedure TfrmStageCreator.imgWallClick(Sender: TObject);
begin
LimparTags;
LimparCores;
pnlWall.Color := clGreen;
pnlWall.Tag := 1;
end;
procedure TfrmStageCreator.NewBackGround(const X, Y: Int16);
var
lRows, lColumns: Integer;
begin
pnlBackGround.ColumnCollection.BeginUpdate;
try
for lColumns := 0 to X - 1 do
begin
with pnlBackGround.ColumnCollection.Add do
begin
SizeStyle := ssAbsolute;
Value := 33;
end;
end;
finally
pnlBackGround.ColumnCollection.EndUpdate;
end;
pnlBackGround.RowCollection.BeginUpdate;
try
for lRows := 0 to Y - 1 do
begin
with pnlBackGround.RowCollection.Add do
begin
SizeStyle := ssAbsolute;
Value := 33;
end;
end;
finally
pnlBackGround.RowCollection.EndUpdate;
end;
end;
end.
|
unit ideSHSystemOptionsFrm;
interface
uses
SHDesignIntf, SHEvents,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, ELPropInsp, ExtCtrls, TypInfo;
type
TSystemOptionsForm = class(TSHComponentForm)
Panel1: TPanel;
PropInspector: TELPropertyInspector;
procedure PropInspectorFilterProp(Sender: TObject;
AInstance: TPersistent; APropInfo: PPropInfo;
var AIncludeProp: Boolean);
procedure PropInspectorGetEditorClass(Sender: TObject;
AInstance: TPersistent; APropInfo: PPropInfo;
var AEditorClass: TELPropEditorClass);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
procedure DoShowProps(AInspector: TELPropertyInspector; APersistent: TPersistent);
public
{ Public declarations }
{ ISHEventReceiver }
function ReceiveEvent(AEvent: TSHEvent): Boolean; override;
end;
var
SystemOptionsForm: TSystemOptionsForm;
implementation
uses
ideSHProxiPropEditors;
{$R *.dfm}
{ TSystemOptionsForm }
function TSystemOptionsForm.ReceiveEvent(AEvent: TSHEvent): Boolean;
begin
case AEvent.Event of
SHE_OPTIONS_DEFAULTS_RESTORED,
SHE_REFRESH_OBJECT_INSPECTOR: PropInspector.UpdateItems;
end;
Result := True;
end;
procedure TSystemOptionsForm.FormCreate(Sender: TObject);
begin
if Assigned(Component) then DoShowProps(PropInspector, Component);
end;
procedure TSystemOptionsForm.FormDestroy(Sender: TObject);
begin
PropInspector.Perform(CM_EXIT, 0, 0);
end;
procedure TSystemOptionsForm.DoShowProps(AInspector: TELPropertyInspector;
APersistent: TPersistent);
var
AList: TList;
begin
AList := TList.Create;
try
if Assigned(AInspector) then
with AInspector do
begin
BeginUpdate;
if Assigned(APersistent) then
begin
AList.Add(APersistent);
Objects.SetObjects(AList);
end else
Objects.Clear;
EndUpdate;
end;
finally
AList.Free;
end;
end;
procedure TSystemOptionsForm.PropInspectorFilterProp(
Sender: TObject; AInstance: TPersistent; APropInfo: PPropInfo;
var AIncludeProp: Boolean);
begin
if Assigned(Component) and not (AInstance is TFont) then
AIncludeProp := Component.CanShowProperty(APropInfo.Name);
end;
procedure TSystemOptionsForm.PropInspectorGetEditorClass(Sender: TObject;
AInstance: TPersistent; APropInfo: PPropInfo;
var AEditorClass: TELPropEditorClass);
begin
AEditorClass := BTGetProxiEditorClass(TELPropertyInspector(Sender),
AInstance, APropInfo);
end;
end.
|
unit FHIRPluginSettings;
interface
uses
SysUtils, IniFiles;
type
TFHIRPluginSettings = class
private
ini : TIniFIle;
function GetToolboxVisible: boolean;
procedure SetToolboxVisible(const Value: boolean);
function GetDefinitionsSource: string;
function GetTerminologyServer: string;
procedure SetDefinitionsSource(const Value: string);
procedure SetTerminologyServer(const Value: string);
public
Constructor Create(folder: String);
Destructor Destroy; override;
property ToolboxVisible : boolean read GetToolboxVisible write SetToolboxVisible;
property TerminologyServer : string read GetTerminologyServer write SetTerminologyServer;
property DefinitionsSource : string read GetDefinitionsSource write SetDefinitionsSource;
end;
var
Settings : TFHIRPluginSettings;
implementation
{ TFHIRPluginSettings }
constructor TFHIRPluginSettings.Create(folder: String);
begin
Inherited Create;
Ini := TIniFile.Create(IncludeTrailingPathDelimiter(folder)+'fhirplugin.ini');
end;
destructor TFHIRPluginSettings.Destroy;
begin
ini.Free;
inherited;
end;
function TFHIRPluginSettings.GetDefinitionsSource: string;
begin
result := ini.ReadString('Validation', 'DefinitionsSource', '');
end;
function TFHIRPluginSettings.GetTerminologyServer: string;
begin
result := ini.ReadString('Validation', 'TerminologyServer', 'http://fhir2.healthintersections.com.au/open');
end;
function TFHIRPluginSettings.GetToolboxVisible: boolean;
begin
result := ini.ReadBool('Toolbox', 'Visible', false);
end;
procedure TFHIRPluginSettings.SetDefinitionsSource(const Value: string);
begin
ini.WriteString('Validation', 'DefinitionsSource', Value);
end;
procedure TFHIRPluginSettings.SetTerminologyServer(const Value: string);
begin
ini.WriteString('Validation', 'TerminologyServer', Value);
end;
procedure TFHIRPluginSettings.SetToolboxVisible(const Value: boolean);
begin
ini.WriteBool('Toolbox', 'Visible', Value);
end;
end.
|
{: This help file explain all the entities classes defined in
the CADSys 4.0 library for both the 2D and 3D use.
These classes are defined in the CS4Shapes unit file
that you must include in the <B=uses> clause in all of your units
that access the types mentioned here.
}
unit CS4Shapes;
interface
uses SysUtils, Classes, Windows, Graphics,
CADSys4, CS4BaseTypes;
type
{: This type defines the type used to specify the name of
a <I=font type face> (like Times New Roman).
}
TFaceName = string[LF_FACESIZE];
{: This class encapsulates the interface for the GDI font of
Windows as defined by <Code=TLOGFONT> structure.
This font is used by the library for the <See Class=TText2D>
shape class. The use of it is somewhat difficult in the
context of a 2D or 3D drawing so it is better to use
the vectorial text shape <See Class=TJustifiedVectText2D> and
<See Class=TJustifiedVectText3D>.
}
TExtendedFont = class(TObject)
private
LogFont: TLOGFONT;
FHandle: HFONT;
FCanvas: TCanvas;
procedure SetNewValue;
procedure SetCanvas(Cnv: TCanvas);
procedure SetHeight(Value: Word);
function GetHeight: Word;
procedure SetWidth(Value: Word);
function GetWidth: Word;
procedure SetEscapement(Value: Word);
function GetEscapement: Word;
procedure SetWeight(Value: Word);
function GetWeight: Word;
procedure SetItalic(Value: Byte);
function GetItalic: Byte;
procedure SetUnderline(Value: Byte);
function GetUnderline: Byte;
procedure SetStrikeOut(Value: Byte);
function GetStrikeOut: Byte;
procedure SetCharSet(Value: Byte);
function GetCharSet: Byte;
procedure SetOutPrecision(Value: Byte);
function GetOutPrecision: Byte;
procedure SetClipPrecision(Value: Byte);
function GetClipPrecision: Byte;
procedure SetQuality(Value: Byte);
function GetQuality: Byte;
procedure SetPicthAndFamily(Value: Byte);
function GetPicthAndFamily: Byte;
procedure SetFaceName(Value: TFaceName);
function GetFaceName: TFaceName;
public
{: This is the constructor that creates an instance of a
font.
When a new font is created it is set using the
<I=DEFAULT_GUI_FONT> as defined in Windows specifications.
}
constructor Create;
{: This destructor frees the font informations.
It also detaches the font form a <I=Canvas>, if the font is
currently in use by it.
}
destructor Destroy; override;
{: This method assign the font data by using another font
class as a prototype.
Parameters:
<LI=<I=Obj> is the font being used as a prototype.>
}
procedure Assign(Obj: TExtendedFont);
{: This method saves the font informations into a stream.
Parameters:
<LI=<I=Strm> is the stream on which save the font structure.>
}
procedure SaveToStream(Strm: TStream);
{: This method retrieves the font informations from a stream.
Parameters:
<LI=<I=Strm> is the stream from which retrieve the font
structure.>
}
procedure LoadFromStream(Strm: TStream);
{: This property attaches the font to a Canvas.
If you want to use the font on a Canvas you must use this
property. After you have setted this propery, to detach
the font from the Canvas assign <B=nil> to this property.
}
property Canvas: TCanvas read FCanvas write SetCanvas;
{: This property contains the handle for the
<Code=TLOGFONT> structure.
}
property Handle: HFONT read FHandle;
{: This property specifies the <I=lfHeight> field of <Code=TLOGFONT>.
}
property Height: Word read GetHeight write SetHeight;
{: This property specifies the <I=lfWidth> field of <Code=TLOGFONT>.
}
property Width: Word read GetWidth write SetWidth;
{: This property specifies the <I=lfEscapement> field of
<Code=TLOGFONT>.
}
property Escapement: Word read GetEscapement write SetEscapement;
{: This property specifies the <I=lfWeight> field of
<Code=TLOGFONT>.
}
property Weight: Word read GetWeight write SetWeight;
{: This property specifies the <I=lfItalic> field of
<Code=TLOGFONT>.
}
property Italic: Byte read GetItalic write SetItalic;
{: This property specifies the <I=lfUnderline> field of
<Code=TLOGFONT>.
}
property Underline: Byte read GetUnderline write SetUnderline;
{: This property specifies the <I=lfStrikeOut> field of
<Code=TLOGFONT>.
}
property StrikeOut: Byte read GetStrikeOut write SetStrikeOut;
{: This property specifies the <I=lfCharSet> field of
<Code=TLOGFONT>.
}
property CharSet: Byte read GetCharSet write SetCharSet;
{: This property specifies the <I=lfOutPrecision> field of
<Code=TLOGFONT>.
}
property OutPrecision: Byte read GetOutPrecision write SetOutPrecision;
{: This property specifies the <I=lfClipPrecision> field of
<Code=TLOGFONT>.
}
property ClipPrecision: Byte read GetClipPrecision write SetClipPrecision;
{: This property specifies the <I=lfQuality> field of
<Code=TLOGFONT>.
}
property Quality: Byte read GetQuality write SetQuality;
{: This property specifies the <I=lfPitchAndFamily> field of
<Code=TLOGFONT>.
}
property PicthAndFamily: Byte read GetPicthAndFamily write SetPicthAndFamily;
{: This property specify the <I=lfFaceName> field of
<Code=TLOGFONT>.
}
property FaceName: TFaceName read GetFaceName write SetFaceName;
end;
{: This type defines the <I=saving mode> used by the <I=outline> primitive
shapes.
An <I=outline> primitive shape is an entity that is drawed as
a connected set of points (<I=profile points>) which displacement
is controlled by a set of <I=control points>. The points used
to draw the entity may be keept in memory or recomputed from
the control points whenever they are needed to draw the
shape. In the former a lot of memory may be used but the
drawing is faster, in the latter the drawing of the shape
may take a quite longer time but the memory is used
efficently.
This type is used to specify beetwen the two modes:
<LI=<I=stSpace> forces an <I=outline> to recompute the
shape's points whenever it must be drawed.>
<LI=<I=stTime> tell to the <I=outline> to store the
shape's points and compute them only when the control
points are changed.>
}
TPrimitiveSavingType = (stSpace, stTime);
{: This type specifies how to draw an arc segment:
<LI=in the <I=adClockwise> mode the arc segment is
drawed clockwise>.
<LI=in the <I=adCounterClockwise> mode the arc segment is
drawed counter clockwise>.
}
TArcDirection = (adClockwise, adCounterClockwise);
{: This is the class reference type for the
<See Class=TPrimitive2D> shape class.
}
TPrimitive2DClass = class of TPrimitive2D;
{: This handler can be used to modify a primitive by dragging its
control points.
See also <See Class=TObject2DHandler>.
}
TPrimitive2DHandler = class(TObject2DHandler)
public
procedure DrawControlPoints(const Sender: TObject2D; const VT: TTransf2D; const Cnv: TDecorativeCanvas; const Width: Integer); override;
function OnMe(const Sender: TObject2D; Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer; override;
end;
{: This class defines a <I=2D primitive>.
A primitive shape is an entity which shape is controlled
by a set of <I=control points>. This class stores and
handles this set of point allowing the developer to
focus on the way to draw the shape from these control
points.
This is the right class from which derive your own
entity classes.
See also <See Class=TOutline2D> and <See Class=TCurve2D>.
<B=Warning>: This is an abstract class that cannot be used
directly.
<B=Note>: The control points are always in the object model
coordinate system !
}
TPrimitive2D = class(TObject2D)
private
fPoints: TPointsSet2D;
protected
procedure _UpdateExtension; override;
{: This method allows you to change the type of the set
of points used to store the <I=control points> of the
primitive.
When the entity is created this method is called to
create the set of <I=control points> that defines
the shape of the entity.
By default a <See Class=TPointsSet2D> instance is created
to store a maximum of <I=Size> points.
You may want to override this property to create
a special set of points that is able to store more
information than a simple point. For instance you can
derive a new set from <See Class=TPointsSet2D> that for
every point store the kind of the point. This is the
first step to create a <I=path shape> that draw arc
segment as well as straight lines.
}
function CreateVect(const Size: Integer): TPointsSet2D; dynamic;
public
{: This is the constructor of the class.
The constructor need the identifier of the new graphic object.
This <See Property=TGraphicObject@ID> will be used to
identify the object in the <See Class=TCADCmp2D>.
If the object is added with the method <See Method=TCADCmp@AddObject>
and with the first parameter set to a number equal or greater that
0, the <I=ID> given here will be overriden.
If you derives from this class remember to call the
inherited method. In this case pass the desired number
of control points and set <See Property=TPointsSet2D@GrowingEnabled>
of <See Property=TPrimitive2D@Points> to the desired value.
Parameters:
<LI=<I=ID> is the ID of the object.>
<LI=<I=NPts> is the number of control points that the
primitive can store without growing the vector.>
}
constructor Create(ID: LongInt; NPts: Integer);
destructor Destroy; override;
constructor CreateFromStream(const Stream: TStream; const Version: TCADVersion); override;
procedure Assign(const Obj: TGraphicObject); override;
procedure SaveToStream(const Stream: TStream); override;
{: This property contains the set of <I=control points> used
to define the shape of the entity.
See the introduction of <See Class=TPrimitive2D> for details.
}
property Points: TPointsSet2D read fPoints write fPoints;
end;
{: This class defines a 2D line segment.
The entity has two <I=control points> that are the extremes of
the segment.
}
TLine2D = class(TPrimitive2D)
public
constructor Create(ID: LongInt; const P1, P2: TPoint2D);
procedure Assign(const Obj: TGraphicObject); override;
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
function OnMe(Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer; override;
end;
{: This class defines a <I=2D outline>.
An <I=outline> primitive shape is an entity that is drawed as
a connected set of points (<I=profile points>) which displacement
is controlled by a set of <I=control points>. The points used
to draw the entity may be keept in memory or recomputed from
the control points whenever they are needed to draw the
shape. In the former a lot of memory may be used but the
drawing is faster, in the latter the drawing of the shape
may take a quite longer time but the memory is used
efficently.
For an <I=outline> the control points are the same as
the <I=profile points>.
Before using the <I=profile points> you must call the
<See Method=TOutline2D@BeginUseProfilePoints> and after the
using you must call the
<See Method=TOutline2D@EndUseProfilePoints> method.
See also <See Class=TCurve2D>.
<B=Note>: The control points are always in the object model
coordinate system !
}
TOutline2D = class(TPrimitive2D)
protected
{: This method is called when the <I=profile points>
are needed.
It must returns the set of the <I=profile points>
created by the class.
<B=Warning>: You don't have to delete the set of points
returned by the method.
}
function GetProfilePoints: TPointsSet2D; virtual; abstract;
{: This method returns the number of <I=profile points>
that is equal (for an <I=outline>) to the number
of <I=control points>.
}
function GetNPts: Integer; virtual; abstract;
{: This method returns <B=True> if the set of <I=profile points>
is closed.
The fact that the set is closed influences the way in which
it is drawed and picked.
}
function GetIsClosed: Boolean; virtual;
public
{: This method initializes the profile points vector for using.
You must call this method before any use of the methods that
work on the set of <I=profile points>.
It is better to call this method in a <Code=try-finally>
block with <See Method=TOutline2D@EndUseProfilePoints>
in the finally part.
}
procedure BeginUseProfilePoints; dynamic;
{: This method finalizes the <I=profile points> when you
finish to use them.
You must call this method when you no longer need to use
the set of <I=profile points>. This allow the library
to eventually saves the memory used by the entity.
It is better to call this method in a <Code=try-finally>
block with this method in the finally part.
<B=Note>: This method must be called after the
<See Method=TOutline2D@BeginUseProfilePoints>.
}
procedure EndUseProfilePoints; dynamic;
{: This is the set of <I=profile points> that is used to
draw the entity.
See the class description of <See Class=TOutline2D>.
}
property ProfilePoints: TPointsSet2D read GetProfilePoints;
{: This property contains the size of the set of
<I=profile points> that is used to draw the entity.
See the class description of <See Class=TOutline2D>.
}
property NumberOfProfilePts: Integer read GetNPts;
{: This property is <B=True> when the shape of the
entity must be considere as closed.
}
property IsClosed: Boolean read GetIsClosed;
end;
{: This class defines a 2D polyline.
A polyline is obtained by connecting the <I=profile points> (in
this case are the same as the <I=control points>) with straight
line segments.
}
TPolyline2D = class(TOutline2D)
protected
function GetProfilePoints: TPointsSet2D; override;
function GetNPts: Integer; override;
public
{: This constructor creates a new 2D polyline.
Parameters:
<LI=<I=ID> is the object identifier.>
<LI=<I=Pts> is an array that contains the <I=control points> of
the polyline. If you want to create a pointless polyline
(because you want to add the points after the construction)
you must pass an array of only one point (an empty array is
not allowed by Delphi) and delete the point after the
construction phase by using the method of
<See Property=TPrimitive2D@Points>.>
}
constructor Create(ID: LongInt; const Pts: array of TPoint2D);
procedure Assign(const Obj: TGraphicObject); override;
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
function OnMe(Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer; override;
end;
TClosedPolyline2D = class(TPolyline2D)
protected
function GetIsClosed: Boolean; override;
public
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
function OnMe(Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer; override;
end;
{: This class defines a 2D polygon.
A polygon is obtained by connecting the <I=profile points> (
in this case they are the same as the <I=profile points>)
with straight segments and filling the shape with the current
brush of the Canvas.
}
TPolygon2D = class(TPolyline2D)
protected
function GetIsClosed: Boolean; override;
public
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
function OnMe(Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer; override;
end;
{: This class defines a 2D curve.
A <I=curve> primitive shape is an entity that is drawed as
a connected set of points (<I=profile points>) which displacement
is controlled by a set of <I=control points>. The points used
to draw the entity may be keept in memory or recomputed from
the control points whenever they are needed to draw the
shape. In the former a lot of memory may be used but the
drawing is faster, in the latter the drawing of the shape
may take a quite longer time but the memory is used
efficently.
A curve is a 2D polyline in which the points that define
the shape (<I=profile points>)are not the same as the
<I=control points> of the entity. In this case the control
points only control the shape of the curve.
For this class the <See property=TCurve2D@SavingType> property
defines the mode of saving used by the entity.
Before using the <I=profile points> you must call the
<See Method=TOutline2D@BeginUseProfilePoints> and after the
using you must call the
<See Method=TOutline2D@EndUseProfilePoints> method.
You have to put the code that defines the <I=profile points>
from the <I=control points> in the
<See Method=TCurve2D@PopulateCurvePoints> method.
See also <See Class=TOutline2D>.
<B=Note>: The control points and the profile points are
always in the object model coordinate system !
}
TCurve2D = class(TOutline2D)
private
fSavingType: TPrimitiveSavingType;
fCurvePrecision: Word;
fCurvePoints: TPointsSet2D;
fCountReference: Integer;
procedure SetCurvePrecision(N: Word);
procedure SetPrimitiveSavingType(S: TPrimitiveSavingType);
procedure FreeCurvePoints;
protected
procedure _UpdateExtension; override;
{: This method is called whenever the <I=profile points>
must be computed.
You must redefine this method to fill the set of
<I=control points> by using the actual set of
<I=control points>. In defining this method you have
to call the inherited method passing it the
right number of <I=profile points> used by the
entity as the <I=N> parameter.
In the method you may use the
<See Property=TOutline2D@ProfilePoints> to add the
points to the set of <I=profile points>.
<B=Warning>: Don't call
<See Method=TOutline2D@BeginUseProfilePoints> nor
<See Method=TOutline2D@EndUseProfilePoints> in this method.
Also don't access the <See Property=TOutline2D@NumberOfProfilePts>
property but use the number of points that you have
computed.
}
function PopulateCurvePoints(N: Word): TRect2D; dynamic;
function GetProfilePoints: TPointsSet2D; override;
function GetNPts: Integer; override;
public
constructor Create(ID: LongInt; NPts: Integer; CurvePrec: Word);
destructor Destroy; override;
procedure Assign(const Obj: TGraphicObject); override;
constructor CreateFromStream(const Stream: TStream; const Version: TCADVersion); override;
procedure SaveToStream(const Stream: TStream); override;
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
function OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer; override;
procedure BeginUseProfilePoints; override;
procedure EndUseProfilePoints; override;
{: This property may be used in the
<See Method=TCurve2D@PopulateCurvePoints> as a parameters
to control the precision (ie the number of <I=profile points>)
used to draw the curve profile.
By default it is 50.
}
property CurvePrecision: Word read fCurvePrecision write SetCurvePrecision;
{: This property specify the saving mode used by the
curve.
By default it is set to <I=stTime>.
See also <See Type=TPrimitiveSavingType>.
}
property SavingType: TPrimitiveSavingType read fSavingType write SetPrimitiveSavingType;
end;
{: This class defines a 2D rectangle.
The entity has two <I=control points> that are the corner
points of the rectangle.
}
TFrame2D = class(TCurve2D)
protected
function PopulateCurvePoints(N: Word): TRect2D; override;
public
{: This constructor creates a new 2D frame.
Parameters:
<LI=<I=ID> is the object identifier.>
<LI=<I=P1> is the bottom-left corner of the frame.>
<LI=<I=P2> is the upper-right corner of the frame.>
}
constructor Create(ID: LongInt; const P1, P2: TPoint2D);
procedure Assign(const Obj: TGraphicObject); override;
end;
{: This class defines a 2D filled rectangle.
The entity has two <I=control points> that are the corner
points of the rectangle (these are in the object model space).
}
TRectangle2D = class(TFrame2D)
public
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
function OnMe(Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer; override;
end;
{: This class defines an arc segment of a 2D ellipse.
The arc is defined by the two corner of the box that
contains the arc's ellipse, and the starting and ending
angles of the arc.
}
TArc2D = class(TCurve2D)
private
FStartAngle, FEndAngle: TRealType;
FDirection: TArcDirection;
procedure SetStartAngle(A: TRealType);
procedure SetEndAngle(A: TRealType);
procedure SetArcDirection(D: TArcDirection);
procedure GetArcParams(var CX, CY, RX, RY, SA, EA: TRealType);
protected
function PopulateCurvePoints(N: Word): TRect2D; override;
public
{: This constructor creates a new arc of a 2D ellipse.
Parameters:
<LI=<I=ID> is the object identifier.>
<LI=<I=P1> and <I=P2> are the corner points of the frame
that defines the arc's ellipse.>
<LI=<I=SA> is the starting angle (in radiants) of the
arc. The angle that correspond to zero radiants is
along the positive x-axis (if no transformation is applied
to the object).>
<LI=<I=SA> is the ending angle (in radiants) of the
arc. The angle that correspond to zero radiants is
along the positive x-axis (if no transformation is applied
to the object).>
Note: Once created, the arc has four control points. The
first two are <I=P1> and <I=P2>; the third is the point
that lies on the segment from the center of the arc's ellipse
and the starting point of the arc; the fourth is the point
that lies on the segment from the center of the arc's ellipse and
the ending point of the arc.
}
constructor Create(ID: LongInt; const P1, P2: TPoint2D; SA, EA: TRealType);
procedure Assign(const Obj: TGraphicObject); override;
constructor CreateFromStream(const Stream: TStream; const Version: TCADVersion); override;
procedure SaveToStream(const Stream: TStream); override;
{: This property contains the starting angle of the arc in radiants.
The angle that correspond to zero radiants is along the
positive x-axis (if no transformation is applied to the
object).
}
property StartAngle: TRealType read FStartAngle write SetStartAngle;
{: This property contains the ending angle of the arc in radiants.
The angle that correspond to zero radiants is along the
positive x-axis (if no transformation is applied to the
object).
}
property EndAngle: TRealType read FEndAngle write SetEndAngle;
{: This property contains the direction used to draw the arc.
See <See Type=TArcDirection> for details.
}
property Direction: TArcDirection read FDirection write SetArcDirection;
end;
TArc3Points2D = class(TCurve2D)
private
protected
function PopulateCurvePoints(N: Word): TRect2D; override;
public
constructor Create(ID: LongInt; const P0, P1, P2: TPoint2D);
procedure Assign(const Obj: TGraphicObject); override;
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
function OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer; override;
end;
TCircle2D = class(TCurve2D)
private
procedure GetCircleParams(var CX, CY, R: TRealType);
protected
function PopulateCurvePoints(N: Word): TRect2D; override;
public
{: This constructor creates a new circle.
Parameters:
P1 = Centrum pont
P2 = Radius end point
}
constructor Create(ID: LongInt; const P1: TPoint2D; R : TRealType);
procedure Assign(const Obj: TGraphicObject); override;
end;
{: This class defines a 2D ellipse.
The ellipse is defined by the two corner of the box that
contains it.
}
TEllipse2D = class(TCurve2D)
private
procedure GetEllipseParams(var CX, CY, RX, RY: TRealType);
protected
function PopulateCurvePoints(N: Word): TRect2D; override;
public
{: This constructor creates a new ellipse.
Parameters:
<LI=<I=ID> is the object identifier.>
<LI=<I=P1> and <I=P2> are the corner points of the frame
that contains the ellipse.>
}
constructor Create(ID: LongInt; const P1, P2: TPoint2D);
procedure Assign(const Obj: TGraphicObject); override;
end;
{: This class defines a 2D filled ellipse.
The ellipse is defined by the two corner of the box that
contains it.
}
TFilledEllipse2D = class(TEllipse2D)
public
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
function OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer; override;
end;
{: This class defines a 2D B-Spline curve.
The B-Spline is defined by its control points.
The order of the spline is 3 but you can change it.
}
TBSpline2D = class(TCurve2D)
private
fOrder: Byte;
protected
function PopulateCurvePoints(N: Word): TRect2D; override;
public
{: This constructor creates a new 2D spline.
Parameters:
<LI=<I=ID> is the object identifier.>
<LI=<I=Pts> is an array that contains the control points
of the spline. If you want to create a pointless spline
(because you want to add the points after the construction)
you must pass an array of only one point (an empty array is
not allowed by Delphi) and delete the point after the
construction.>
}
constructor Create(ID: LongInt; const Pts: array of TPoint2D);
procedure Assign(const Obj: TGraphicObject); override;
constructor CreateFromStream(const Stream: TStream; const Version: TCADVersion); override;
procedure SaveToStream(const Stream: TStream); override;
{: This property contains the order of the spline.
By default it is three (cubic spline).
}
property Order: Byte read FOrder write FOrder;
end;
{: This class defines a 2D text object that uses the Windows
font for drawing.
I created a new text object that is more suitable for a
2D/3D CAD programs. By the fact that any TTF may be
converted into the new font format, I discourage the use
of this object that is keept in the library only for
backward compatibility.
See <See Class=TVectFont> for information on the
new type of Text object.
<B=Note>: The new text object is not able to fill the
interior of characters. If you need this capability you
still have to use this kind of Text object.
}
TText2D = class(TPrimitive2D)
private
fText: AnsiString;
fHeight: TRealType;
fExtFont: TExtendedFont;
fDrawBox, fRecalcBox: Boolean;
fClippingFlags: Integer; // Win32s DrawText flags.
public
{: Create a new text entity in the rectangle <I=Rect1>, with
the given <I=Height> and <I=Text>.
Points[0] will be the left-bottom corner of the text
bounding box (also used as clipping box for the text)
and Points[1] the right-up corner.
The <I=width> of the text is set to the width of <I=Rect1>.
If you don’t know the dimension of the Text on screen, set
the <See Property=TText2D@AutoSize> property to <B=True>.
The first time the text will be drawed the bounding box will
be adjusted automatically.
The rectangle will be drawed in the current brush and pen
if <See Property=TText2D@DrawBox> property is <B=True>.
}
constructor Create(ID: LongInt; Rect1: TRect2D; Height: TRealType; Txt: AnsiString);
constructor CreateFromStream(const Stream: TStream; const Version: TCADVersion); override;
destructor Destroy; override;
procedure Assign(const Obj: TGraphicObject); override;
procedure SaveToStream(const Stream: TStream); override;
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
function OnMe(Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer; override;
{: This property contains the heigth of the text in world
units.
This is different from the Heigth of font used to render
the text object.
}
property Height: TRealType read fHeight write fHeight;
{: This property contains the <See Class=TExtendedFont>
instance used to render the text.
Use it to change the font.
}
property LogFont: TExtendedFont read FExtFont;
{: If this property is set to <B=True> the text box is
drawed below the text. Otherwise only the text is drawed.
By default it is <B=False>.
}
property DrawBox: Boolean read FDrawBox write FDrawBox;
{: If this property is <B=True>, the bounding box is changed
when the object is drawed so it contains the whole text.
By default it is <B=False>.
}
property AutoSize: Boolean read fRecalcBox write fRecalcBox;
{: This property contains the text string used by the
text entity.
You may include more than one line of text simply
adding <Code=#10#13> beetwen lines.
}
property Text: AnsiString read FText write FText;
{: This property contains the <I=clipping flags> used
by drawing the text with the <I=DrawText> API function.
By default the are setted to <I=DT_NOCLIP>.
}
property ClippingFlags: Integer read FClippingFlags write FClippingFlags;
end;
{: This class rapresents a scalable raster bitmap.
This object is useful when you want a bitmap with world
dimension that is scaled when you zoom in a portion of the
drawing. For instance this can be useful for GIS
applications. However this object isn’t fast and sometimes
the bitmap is not drawed. Maybe the problem is the Windows
95 bitmap support. I will add faster and reliable
raster capability to the library as soon as I have time.
You can however use a thirdy part library to enhance this
object by using this class as a blueprint for your
specific bitmap entity.
}
TBitmap2D = class(TPrimitive2D)
private
fBitmap: TBitmap;
fScaleFactor: TRealType;
fAspectRatio: TRealType;
fCopyMode: TCopyMode;
procedure SetScaleFactor(SF: TRealType);
procedure SetAspectRatio(AR: TRealType);
public
{: This constructor creates a new bitmap object.
<I=Bmp> is the bitmap to be drawed and it will be freed
by the object.
<I=P1> and <I=P2> are the corner points of the bitmap
in world coordinates (and the bitmap will be stretched
to fit in).
<B=Note>: The bitmap cannot be rotated !
}
constructor Create(ID: LongInt; const P1, P2: TPoint2D; Bmp: TBitmap);
destructor Destroy; override;
procedure Assign(const Obj: TGraphicObject); override;
constructor CreateFromStream(const Stream: TStream; const Version: TCADVersion); override;
procedure SaveToStream(const Stream: TStream); override;
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
{: This property contains the bitmap to be drawed.
It will be freed by the object.
}
property Bitmap: TBitmap read FBitmap;
{: This property may contains the scale factor to be used for the
bitmap.
If you set this property the bounding box is recomputed and
the bitmap is not stretched. The first Points will remain
in the position specified but the second point will be
repositioned using the ScaleFactor.
The value rapresent how many drawing unit correspond to
one pixel in the image. So an image of 50x50 pixels with
a ScaleFactor of 2.0 will be 100x100 drawing units large.
How many application units (cm, inch, etc) is a drawing
unit is left to you.
Setting it to zero (the default) means that no scale is
needed.
}
property ScaleFactor: TRealType read fScaleFactor write SetScaleFactor;
{: This property may contains the aspect ratio (Width/Heigth) to
be used for the bitmap.
This property is used only if ScaleFactor is not 0.0
Setting it to zero (the default) means that no aspect ratio is
needed.
}
property AspectRatio: TRealType read fAspectRatio write SetAspectRatio;
{: This property contains the CopyMode used to copy the
bitmap.
}
property CopyMode: TCopyMode read fCopyMode write fCopyMode;
end;
{: This class defines a 2D/3D vectorial char as a set of
polylines.
The number of polylines that can be used to define a char
is limited by the size given at the moment of creation.
In the char definition the polylines must be defined in the
unitary square that ranges from X:0,1 and Y:0,1, so that
the char may be scaled with a scale transformation.
When the char is drawed inside a string, the real dimension
of the char is used (the font is a proportional one).
<B=Note>: The vectorial character may be created with
conversion from Windows True Type Font with a
separate utility given with the library.
}
TVectChar = class(TObject)
private
fSubVects: TIndexedObjectList;
fExtension: TRect2D;
function GetVect(Idx: Integer): TPointsSet2D;
function GetVectCount: Integer;
public
{: This constructor creates an new instance of the vectorial char.
Parameters:
<LI=<I=NSubVect> is the number of polylines that defines
the char.>
}
constructor Create(NSubVect: Integer);
destructor Destroy; override;
{: This method create a new instance of a char definition by
retrieves its datas from a stream.
Parameters:
<LI=<I=Stream> is the stream that contains the char
definition (previously saved with
<See Method=TVectChar@SaveToStream>).>
}
constructor CreateFromStream(const Stream: TStream; const Version: TCADVersion);
{: This method saves a char definition into a stream.
Parameters:
<LI=<I=Stream> is the stream into which save the char
definition (that can be retrived with
<See Method=TVectCharCreateFromStream>).>
}
procedure SaveToStream(const Stream: TStream);
{: This method is used computes the real dimension of the
char.
This method <B=MUST> be called when the definition of
the char is finished (that is when you finish to
create the polylines of the char).
}
procedure UpdateExtension(Sender: TObject);
{: This property contains the set of polylines that defines
the char.
The polylines are stored in instances of
<See Class=TPointsSet2D>.
<I=Idx> is the index of the polyline in the set.
}
property Vectors[Idx: Integer]: TPointsSet2D read GetVect;
{: This property contains the number of polylines that
defines the char.
This property cannot be changed.
}
property VectorCount: Integer read GetVectCount;
{: This property contains the bounding box of the char.
This value is updated by calling
<See Method=TVectChar@UpdateExtension>. You must call
that method before use this property.
}
property Extension: TRect2D read fExtension;
end;
{: This class defines a 2D vectorial font typeface.
The typeface is made up of 256 instances of
<See Class=TVectChar> (so no unicode may be used). The font
may be stored and retrived from a font file.
The easy way to define a font typeface is by using the
<I=True Type Font> converter that create it from a TTF font.
The chars are indexed by their <I=ASCII> value. If a char
is not defined, it will not be drawed and an underline will
be shown.
The space and carriage returns are handled automatically,
but you can change their shape.
Any font used by the application is registered in the
system with an <I=Index>, that is used to save and retrieve
the font from the disk and associate the correct font to
the texts.
If you change the indexes among different drawings, you
could load the wrong file. In this case you will notice that
the text is drawed with a different font. If the index
doesn't correspond to any font and no default font is
defined an exception will be raised and the drawing will not
be loaded.
See <See Function=CADSysSetDefaultFont> and the other
registration functions for details.
}
TVectFont = class(TObject)
private
fVects: TIndexedObjectList;
function GetChar(Ch: Char): TVectChar;
public
constructor Create;
destructor Destroy; override;
{: This method creates an instance of the font and retrieves
its definition from a Stream.
Parameters:
<LI=<I=Stream> is the stream from which retrieve the
font definition.>
}
constructor CreateFromStream(const Stream: TStream; const Version: TCADVersion);
{: This method saves an instance of the font into a Stream.
Parameters:
<LI=<I=Stream> is the stream to which saves the font
definition.>
}
procedure SaveToStream(const Stream: TStream);
{: This method draws a char of the font on a canvas using a
transform mapping from a 2D viewing system.
Parameters:
<LI=<I=Ch> is the index (ASCII) of the char to be drawed.>
<LI=<I=DrawPoint> is the 2D point in world coordinates at
which draw the char (it is the botton-left corner of the
bounding box of the char). The point is changed by the
method into the position for the next char on the same
text line.>
<LI=<I=H> is the size of the char in world units. This value
is used to scale the char definition.>
<LI=<I=ICS> is the space between two chars (in normalized
units). For example a value of 0.2 means a space of
20% of H.>
<LI=<I=VT> is the mapping transform from world to screen.
It may be obtained from the
<See Property=TCADViewport@ViewportToScreenTransform>
property.>
<LI=<I=Cnv> is the canvas on which draw the char.>
}
procedure DrawChar2D(Ch: Char; var DrawPoint: TPoint2D; const H, ICS: TRealType; const VT: TTransf2D; Cnv: TDecorativeCanvas);
{: This method returns the bounding box of a vectorial text string
when the current font is used to draw it.
Parameters:
<LI=<I=Str> is the string.>
<LI=<I=H> is the size of the char in world units.>
<LI=<I=InterChar> is the space beetwen two chars
(in normalized units). For example a value of 0.2 means
a space of 20% of H.>
<LI=<I=InterLine> is the space beetwen two lines of the
text (in normalizaed units). For example a value of 0.2
means a space of 20% of H.>
}
function GetTextExtension(Str: AnsiString; H, InterChar, InterLine: TRealType): TRect2D;
{: This method creates a new char definition and returns the
<See Class=TVectChar> that rapresents it.
You must use the returned value to define the char.
If the char is already present it will be deleted.
Parameters:
<LI=<I=Ch> is the characted to be defined.>
<LI=<I=N> is the number of polylines used to draw the char.>
}
function CreateChar(Ch: Char; N: Integer): TVectChar;
{: This property contains the set of chars of the font.
The characters are indexed by their <I=ASCII> code.
}
property Chars[Ch: Char]: TVectChar read GetChar;
end;
{: This type defines the horizontal justification mode for a
2D/3D vectorial text:
<LI=<I=jhLeft> means left justification.>
<LI=<I=jhRight> means right justification.>
<LI=<I=jhCenter> means center justification.>
}
THJustification = (jhLeft, jhRight, jhCenter);
{: This type defines the vertical justification mode for a
2D/3D vectorial text:
<LI=<I=jvTop> means top justification.>
<LI=<I=jvBottom> means bottom justification.>
<LI=<I=jvCenter> means center justification.>
}
TVJustification = (jvTop, jvBottom, jvCenter);
{: This class defines the 2D vectorial text.
The text may be multilines and justified. It uses an
instance of <See Class=TVectFont> to extract the typeface
to be used.
}
TJustifiedVectText2D = class(TPrimitive2D)
private
fVectFont: TVectFont;
fText: AnsiString;
fHJustification: THJustification;
fVJustification: TVJustification;
fBasePoint: TPoint2D;
fHeight, fCharSpace, fInterLine: TRealType;
fDrawBox: Boolean;
procedure SetHeight(H: TRealType);
procedure SetCharSpace(S: TRealType);
procedure SetInterLine(S: TRealType);
procedure SetText(T: String);
function GetTextExtension: TRect2D;
procedure DrawText(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const DrawMode: Integer);
protected
procedure _UpdateExtension; override;
public
{: This constructor creates a new instance of the class.
Parameters:
<LI=<I=ID> is identifier that univocally identify the
object in the CAD. By means of the method used to add the
object to the CAD, the <I=ID> of the object might be different
from the one supplied here. See <See Method=TCADCmp@AddObject>
for details.>
<LI=<I=FontVect> is the font typeface. Use
<See Function=CADSysFindFontByIndex> and
<See Function=CADSysFindFontIndex> for details.>
<LI=<I=TextBox> is the rectangle used to justify the text.
The string is drawed from the upper-left corner of this
box.>
<LI=<I=Height> is the size of the font in world units.>
<LI=<I=Txt> is the text to be drawed.>
}
constructor Create(ID: LongInt; FontVect: TVectFont; TextBox: TRect2D; Height: TRealType; Txt: AnsiString);
constructor CreateFromStream(const Stream: TStream; const Version: TCADVersion); override;
procedure Assign(const Obj: TGraphicObject); override;
procedure SaveToStream(const Stream: TStream); override;
procedure Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer); override;
function OnMe(Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer; override;
{: This property contains the size of the font in world unit.
}
property Height: TRealType read fHeight write SetHeight;
{: This property contains the spacing beetwen chars in
normalized unit.
For example a value of 0.2 means a space of 20% of the
<See Property=TJustifiedVectText2D@Height>.
}
property CharSpace: TRealType read fCharSpace write SetCharSpace;
{: This property contains the spacing beetwen lines of the
text.
For example a value of 0.2 means a space of 20% of the
<See Property=TJustifiedVectText2D@Height>.
}
property InterLine: TRealType read fInterLine write SetInterLine;
{: This property contains the instance of the font that is
used to draw the text.
}
property VectFont: TVectFont read fVectFont write fVectFont;
{: If this property is <B=True>, a frame is drawed around
the text.
}
property DrawBox: Boolean read fDrawBox write fDrawBox;
{: This property contains the text to be drawed.
}
property Text: AnsiString read FText write SetText;
{: This property specifies the horizontal justification.
}
property HorizontalJust: THJustification read fHJustification write fHJustification;
{: This property specifies the vertical justification.
}
property VerticalJust: TVJustification read fVJustification write fVJustification;
end;
{: This procedure sets the default font.
}
procedure CADSysSetDefaultFont(const Font: TVectFont);
{: This function returns the default font.
}
function CADSysGetDefaultFont: TVectFont;
{: This function initializes the list of registered fonts.
}
procedure CADSysInitFontList;
{: This function clears the list of registered fonts.
}
procedure CADSysClearFontList;
{: This function returns the index of a font.
If the font is not registered an exception will be raised.
Parameters:
<LI=<I=Font> is the font to be searched.>
}
function CADSysFindFontIndex(const Font: TVectFont): Word;
{: This function returns the font that was registered with
the specified index.
If the index is not used and a default font is defined,
the function returns the default font. Otherwise an
exception will be raised.
Parameters:
<LI=<I=Index> is the index of the font to be searched for.>
}
function CADSysFindFontByIndex(Index: Word): TVectFont;
{: This function register a font by retriving it from
a file.
If the index of registration is already in use an
exception will be raised.
Parameters:
<LI=<I=Index> is the registration index.>
<LI=<I=FileName> is name of the file that contains the
font.>
<B=Note>: There are <I=MAX_REGISTERED_FONTS> slots in the
registration list.
}
procedure CADSysRegisterFontFromFile(Index: Word; const FileName: String);
{: This function register a font.
If the index of registration is already in use an
exception will be raised.
Parameters:
<LI=<I=Index> is the registration index.>
<LI=<I=Font> is the font to be registered.>
<B=Note>: There are <I=MAX_REGISTERED_FONTS> slots in the
registration list.
}
procedure CADSysRegisterFont(Index: Word; const Font: TVectFont);
{: This function clear the registration of a font.
Parameters:
<LI=<I=Index> is the registration index.>
}
procedure CADSysUnregisterFont(Index: Word);
const
{: This constats rapresent the maximum number of vectorial fonts
that may be used in the library.
}
MAX_REGISTERED_FONTS = 512;
implementation
uses Math, Dialogs;
var
VectFonts2DRegistered: array[0..MAX_REGISTERED_FONTS] of TVectFont;
_NullChar: TVectChar;
_DefaultFont: TVectFont;
_DefaultHandler2D: TPrimitive2DHandler;
// =====================================================================
// TExtendedFont
// =====================================================================
procedure TExtendedFont.SetHeight(Value: Word);
begin
LogFont.lfHeight := Value;
SetNewValue;
end;
function TExtendedFont.GetHeight: Word;
begin
Result := LogFont.lfHeight;
end;
procedure TExtendedFont.SetWidth(Value: Word);
begin
LogFont.lfWidth := Value;
SetNewValue;
end;
function TExtendedFont.GetWidth: Word;
begin
Result := LogFont.lfWidth;
end;
procedure TExtendedFont.SetEscapement(Value: Word);
begin
LogFont.lfEscapement := Value;
SetNewValue;
end;
function TExtendedFont.GetEscapement: Word;
begin
Result := LogFont.lfEscapement;
end;
procedure TExtendedFont.SetWeight(Value: Word);
begin
LogFont.lfWeight := Value;
SetNewValue;
end;
function TExtendedFont.GetWeight: Word;
begin
Result := LogFont.lfWeight;
end;
procedure TExtendedFont.SetItalic(Value: Byte);
begin
LogFont.lfItalic := Value;
SetNewValue;
end;
function TExtendedFont.GetItalic: Byte;
begin
Result := LogFont.lfItalic;
end;
procedure TExtendedFont.SetUnderline(Value: Byte);
begin
LogFont.lfUnderline := Value;
SetNewValue;
end;
function TExtendedFont.GetUnderline: Byte;
begin
Result := LogFont.lfUnderline;
end;
procedure TExtendedFont.SetStrikeOut(Value: Byte);
begin
LogFont.lfStrikeOut := Value;
SetNewValue;
end;
function TExtendedFont.GetStrikeOut: Byte;
begin
Result := LogFont.lfStrikeOut;
end;
procedure TExtendedFont.SetCharSet(Value: Byte);
begin
LogFont.lfCharSet := Value;
SetNewValue;
end;
function TExtendedFont.GetCharSet: Byte;
begin
Result := LogFont.lfCharSet;
end;
procedure TExtendedFont.SetOutPrecision(Value: Byte);
begin
LogFont.lfOutPrecision := Value;
SetNewValue;
end;
function TExtendedFont.GetOutPrecision: Byte;
begin
Result := LogFont.lfOutPrecision;
end;
procedure TExtendedFont.SetClipPrecision(Value: Byte);
begin
LogFont.lfClipPrecision := Value;
SetNewValue;
end;
function TExtendedFont.GetClipPrecision: Byte;
begin
Result := LogFont.lfClipPrecision;
end;
procedure TExtendedFont.SetQuality(Value: Byte);
begin
LogFont.lfQuality := Value;
SetNewValue;
end;
function TExtendedFont.GetQuality: Byte;
begin
Result := LogFont.lfQuality;
end;
procedure TExtendedFont.SetPicthAndFamily(Value: Byte);
begin
LogFont.lfPitchAndFamily := Value;
SetNewValue;
end;
function TExtendedFont.GetPicthAndFamily: Byte;
begin
Result := LogFont.lfPitchAndFamily;
end;
procedure TExtendedFont.SetFaceName(Value: TFaceName);
var
Cont: Byte;
begin
for Cont := 1 to Length(Value) do
LogFont.lfFaceName[Cont - 1] := Value[Cont];
LogFont.lfFaceName[Length(Value)] := #0;
SetNewValue;
end;
function TExtendedFont.GetFaceName: TFaceName;
begin
Result := LogFont.lfFaceName;
end;
procedure TExtendedFont.SetNewValue;
var
TmpHandle: HFONT;
begin
TmpHandle := CreateFontIndirect(LogFont);
if Assigned(FCanvas) then
SelectObject(FCanvas.Handle, TmpHandle);
DeleteObject(FHandle);
FHandle := TmpHandle;
end;
procedure TExtendedFont.SetCanvas(Cnv: TCanvas);
begin
if Assigned(FCanvas) then
SelectObject(FCanvas.Handle, FCanvas.Font.Handle);
FCanvas := Cnv;
if Assigned(FCanvas) then SelectObject(FCanvas.Handle, FHandle);
end;
constructor TExtendedFont.Create;
begin
inherited Create;
GetObject(GetStockObject(DEFAULT_GUI_FONT), SizeOf(LogFont), @LogFont);
LogFont.lfFaceName := 'Small Font';
FHandle := CreateFontIndirect(LogFont);
end;
procedure TExtendedFont.Assign(Obj: TExtendedFont);
begin
if Obj = Self then
Exit;
LogFont := TExtendedFont(Obj).LogFont;
SetNewValue;
end;
destructor TExtendedFont.Destroy;
begin
if Assigned(FCanvas) then
SelectObject(FCanvas.Handle, FCanvas.Font.Handle);
DeleteObject(FHandle);
inherited Destroy;
end;
procedure TExtendedFont.SaveToStream(Strm: TStream);
begin
with Strm do
Write(LogFont, SizeOf(LogFont));
end;
procedure TExtendedFont.LoadFromStream(Strm: TStream);
begin
with Strm do
begin
Read(LogFont, SizeOf(LogFont));
SetNewValue;
end;
end;
// =====================================================================
// TPrimitive2DHandler
// =====================================================================
procedure TPrimitive2DHandler.DrawControlPoints(const Sender: TObject2D; const VT: TTransf2D; const Cnv: TDecorativeCanvas; const Width: Integer);
var
TmpPt: TPoint2D;
Cont: Integer;
begin
if Sender is TPrimitive2D then
with TPrimitive2D(Sender) do
if not HasTransform then
for Cont := 0 to Points.Count - 1 do
begin
TmpPt := TransformPoint2D(Points[Cont], VT);
DrawPlaceHolder(Cnv, Round(TmpPt.X), Round(TmpPt.Y), Width);
end
else
for Cont := 0 to Points.Count - 1 do
begin
TmpPt := TransformPoint2D(Points[Cont], MultiplyTransform2D(ModelTransform, VT));
DrawPlaceHolder(Cnv, Round(TmpPt.X), Round(TmpPt.Y), Width);
end;
end;
function TPrimitive2DHandler.OnMe(const Sender: TObject2D; Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer;
var
Cont: Integer;
ResDist: TRealType;
begin
Result := PICK_NOOBJECT;
if Sender is TPrimitive2D then
with TPrimitive2D(Sender) do
if HasTransform then
begin
for Cont := 0 to Points.Count - 1 do
if NearPoint2D(Pt, TransformPoint2D(Points[Cont], ModelTransform), Aperture, ResDist) and
(ResDist <= Distance) then
begin
Result := Cont;
Distance := ResDist;
end;
end
else
begin
for Cont := 0 to Points.Count - 1 do
if NearPoint2D(Pt, Points[Cont], Aperture, ResDist) and
(ResDist <= Distance) then
begin
Result := Cont;
Distance := ResDist;
end;
end;
end;
// =====================================================================
// TPrimitive2D
// =====================================================================
procedure TPrimitive2D._UpdateExtension;
begin
if not Assigned(fPoints) or (fPoints.Count = 0) then
WritableBox := Rect2D(0, 0, 0, 0)
else
{ Change the extension. }
WritableBox := TransformBoundingBox2D(fPoints.Extension, ModelTransform);
end;
function TPrimitive2D.CreateVect(const Size: Integer): TPointsSet2D;
begin
Result := TPointsSet2D.Create(Size);
end;
constructor TPrimitive2D.Create(ID: LongInt; NPts: Integer);
begin
inherited Create(ID);
{ Create the internal vector. }
fPoints := CreateVect(NPts);
fPoints.OnChange := UpdateExtension;
SetSharedHandler(_DefaultHandler2D);
end;
procedure TPrimitive2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if (Obj is TPrimitive2D) then
begin // Per default non aggiunge i punti.
if not Assigned(fPoints) then
begin
fPoints := CreateVect(0);
fPoints.GrowingEnabled := True;
fPoints.OnChange := UpdateExtension;
end;
fPoints.Clear;
end;
end;
constructor TPrimitive2D.CreateFromStream(const Stream: TStream; const Version: TCADVersion);
var
TmpWord: Word;
Cont: Integer;
TmpPt: TPoint2D;
TmpBoolean: Boolean;
begin
{ Load the standard properties }
inherited;
with Stream do
begin
Read(TmpWord, SizeOf(TmpWord));
fPoints := CreateVect(TmpWord);
{ Read all the points. }
for Cont := 0 to TmpWord - 1 do
begin
Read(TmpPt, SizeOf(TmpPt));
fPoints.Points[Cont] := TmpPt;
end;
Read(TmpBoolean, SizeOf(TmpBoolean));
fPoints.GrowingEnabled := TmpBoolean;
end;
fPoints.OnChange := UpdateExtension;
end;
procedure TPrimitive2D.SaveToStream(const Stream: TStream);
var
TmpWord: Word;
Cont: Integer;
TmpPt: TPoint2D;
TmpBoolean: Boolean;
begin
{ Save the standard properties }
inherited SaveToStream(Stream);
with Stream do
begin
TmpWord := fPoints.Count;
Write(TmpWord, SizeOf(TmpWord));
{ Write all points. }
for Cont := 0 to TmpWord - 1 do
begin
TmpPt := fPoints.Points[Cont];
Write(TmpPt, SizeOf(TmpPt));
end;
TmpBoolean := fPoints.GrowingEnabled;
Write(TmpBoolean, SizeOf(TmpBoolean));
end;
end;
destructor TPrimitive2D.Destroy;
begin
if Assigned(fPoints) then
fPoints.Free;
inherited Destroy;
end;
// =====================================================================
// TLine2D
// =====================================================================
constructor TLine2D.Create(ID: LongInt; const P1, P2: TPoint2D);
begin
inherited Create(ID, 2);
Points.DisableEvents := True;
try
Points.Add(P1);
Points.Add(P2);
Points.GrowingEnabled := False;
finally
Points.DisableEvents := False;
UpdateExtension(Self);
end;
end;
procedure TLine2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if (Obj is TLine2D) then
begin
Points.Copy(TPrimitive2D(Obj).Points, 0, 1);
Points.GrowingEnabled := False;
end;
end;
procedure TLine2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
begin
if not HasTransform then
DrawLine2D(Cnv, Points[0], Points[1], ClipRect2D, VT)
else
DrawLine2D(Cnv, Points[0], Points[1], ClipRect2D, MultiplyTransform2D(ModelTransform, VT));
end;
function TLine2D.OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer;
var
TmpDist: TRealType;
begin
Result := inherited OnMe(Pt, Aperture, Distance);
if Result = PICK_INBBOX then
begin
Result := MaxIntValue([PICK_INBBOX, IsPointOnPolyLine2D(Points.PointsReference, Points.Count, Pt, TmpDist, Aperture, ModelTransform, False)]);
Distance := MinValue([Aperture, TmpDist]);
end;
end;
// =====================================================================
// TOutline2D
// =====================================================================
function TOutline2D.GetIsClosed: Boolean;
begin
BeginUseProfilePoints;
try
Result := (ProfilePoints.Count > 2) and
IsSamePoint2D(ProfilePoints[0], ProfilePoints[ProfilePoints.Count - 1]);
finally
EndUseProfilePoints;
end;
end;
procedure TOutline2D.BeginUseProfilePoints;
begin
// Due to the fact that ControlPoints are equal to ProfilePoints
// there is no need to do initialization here.
end;
procedure TOutline2D.EndUseProfilePoints;
begin
// Due to the fact that ControlPoints are equal to ProfilePoints
// there is no need to do finalization here.
end;
// =====================================================================
// TPolyline2D
// =====================================================================
constructor TPolyline2D.Create(ID: LongInt; const Pts: array of TPoint2D);
begin
inherited Create(ID, High(Pts) - Low(Pts) + 1);
Points.AddPoints(Pts);
end;
procedure TPolyLine2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if (Obj is TLine2D) or (Obj is TPolyline2D) or (Obj is TPolygon2D) or (Obj is TClosedPolyLine2D) then
begin
Points.Copy(TPrimitive2D(Obj).Points, 0, TPrimitive2D(Obj).Points.Count - 1);
Points.GrowingEnabled := True;
end;
end;
procedure TPolyLine2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
begin
if not HasTransform then
Points.DrawAsPolyline(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, VT)
else
Points.DrawAsPolyline(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, MultiplyTransform2D(ModelTransform, VT));
end;
function TPolyline2D.OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer;
var
TmpDist: TRealType;
begin
Result := inherited OnMe(Pt, Aperture, Distance);
if Result = PICK_INBBOX then
begin
Result := MaxIntValue([PICK_INBBOX, IsPointOnPolyLine2D(Points.PointsReference, Points.Count, Pt, TmpDist, Aperture, ModelTransform, False)]);
Distance := MinValue([Aperture, TmpDist]);
end;
end;
function TPolyline2D.GetProfilePoints: TPointsSet2D;
begin
Result := Points;
end;
function TPolyline2D.GetNPts: Integer;
begin
Result := Points.Count;
end;
// =====================================================================
// TClosedPolyLine2D
// =====================================================================
function TClosedPolyLine2D.GetIsClosed: Boolean;
begin
Result := True; // Sempre chiuso.
end;
procedure TClosedPolyLine2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
begin
{ Draw the polygon. }
if not HasTransform then
Points.DrawAsClosedPolyLine(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, VT)
else
Points.DrawAsClosedPolyLine(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, MultiplyTransform2D(ModelTransform, VT))
end;
function TClosedPolyLine2D.OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer;
var
TmpDist: TRealType;
begin
Result := inherited OnMe(Pt, Aperture, Distance);
if (Result = PICK_INBBOX) then
begin
Result := MaxIntValue([PICK_INBBOX, IsPointInPolygon2D(Points.PointsReference, Points.Count, Pt, TmpDist, Aperture, ModelTransform)]);
Distance := MinValue([Aperture, TmpDist]);
end;
end;
// =====================================================================
// TPolygon2D
// =====================================================================
function TPolygon2D.GetIsClosed: Boolean;
begin
Result := True; // Sempre chiuso.
end;
procedure TPolygon2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
begin
{ Draw the polygon. }
if not HasTransform then
Points.DrawAsPolygon(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, VT)
else
Points.DrawAsPolygon(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, MultiplyTransform2D(ModelTransform, VT))
end;
function TPolygon2D.OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer;
var
TmpDist: TRealType;
begin
Result := inherited OnMe(Pt, Aperture, Distance);
if (Result = PICK_INBBOX) then
begin
Result := MaxIntValue([PICK_INBBOX, IsPointInPolygon2D(Points.PointsReference, Points.Count, Pt, TmpDist, Aperture, ModelTransform)]);
Distance := MinValue([Aperture, TmpDist]);
end;
end;
// =====================================================================
// TCurve2D
// =====================================================================
procedure TCurve2D.SetPrimitiveSavingType(S: TPrimitiveSavingType);
begin
if S <> fSavingType then
begin
fSavingType := S;
UpdateExtension(Self);
end;
end;
procedure TCurve2D.SetCurvePrecision(N: Word);
begin
if fCurvePrecision <> N then
fCurvePrecision := N;
end;
function TCurve2D.PopulateCurvePoints(N: Word): TRect2D;
begin
if not Assigned(fCurvePoints) then
fCurvePoints := TPointsSet2D.Create(N)
else
fCurvePoints.Clear;
Inc(fCountReference);
fCurvePoints.GrowingEnabled := True;
Result := Rect2D(0, 0, 0, 0);
end;
procedure TCurve2D.FreeCurvePoints;
begin
Dec(fCountReference);
if fCountReference <= 0 then
begin
fCurvePoints.Free;
fCurvePoints := nil;
fCountReference := 0;
end;
end;
constructor TCurve2D.Create(ID: LongInt; NPts: Integer; CurvePrec: Word);
begin
inherited Create(ID, NPts);
fCurvePrecision := CurvePrec;
fCurvePoints := nil;
fCountReference := 0;
fSavingType := stTime;
end;
destructor TCurve2D.Destroy;
begin
fCountReference := 0;
FreeCurvePoints;
inherited;
end;
procedure TCurve2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited;
if Obj is TCurve2D then
begin
CurvePrecision := TCurve2D(Obj).fCurvePrecision;
SavingType := TCurve2D(Obj).fSavingType;
end;
end;
constructor TCurve2D.CreateFromStream(const Stream: TStream; const Version: TCADVersion);
begin
inherited;
with Stream do
begin
Read(fCurvePrecision, SizeOf(fCurvePrecision));
Read(fSavingType, SizeOf(fSavingType));
fCountReference := 0;
end;
end;
procedure TCurve2D.SaveToStream(const Stream: TStream);
begin
inherited;
with Stream do
begin
Write(fCurvePrecision, SizeOf(fCurvePrecision));
Write(fSavingType, SizeOf(fSavingType));
end;
end;
procedure TCurve2D._UpdateExtension;
begin
if not Assigned(Points) or (Points.Count = 0) then
Exit;
case fSavingType of
stSpace: begin
WritableBox := PopulateCurvePoints(0);
FreeCurvePoints;
end;
stTime: begin
FreeCurvePoints;
WritableBox := PopulateCurvePoints(0);
end;
end;
end;
procedure TCurve2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
begin
BeginUseProfilePoints;
try
if Assigned(fCurvePoints) then
begin
if not HasTransform then
fCurvePoints.DrawAsPolyline(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, VT)
else
fCurvePoints.DrawAsPolyline(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, MultiplyTransform2D(ModelTransform, VT));
end;
finally
EndUseProfilePoints;
end;
end;
function TCurve2D.OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer;
var
TmpDist: TRealType;
begin
Result := inherited OnMe(Pt, Aperture, Distance);
if Result = PICK_INBBOX then
begin
BeginUseProfilePoints;
try
if not Assigned(fCurvePoints) then
Exit;
Result := MaxIntValue([PICK_INBBOX, IsPointOnPolyLine2D(fCurvePoints.PointsReference, fCurvePoints.Count, Pt, TmpDist, Aperture, ModelTransform, False)]);
Distance := MinValue([Aperture, TmpDist]);
finally
EndUseProfilePoints;
end;
end;
end;
function TCurve2D.GetProfilePoints: TPointsSet2D;
begin
if not Assigned(fCurvePoints) then
Raise ECADSysException.Create('TCurve2D: Call BeginUseProfilePoints before accessing the curve points.');
Result := fCurvePoints;
end;
function TCurve2D.GetNPts: Integer;
begin
if not Assigned(fCurvePoints) then
Raise ECADSysException.Create('TCurve2D: Call BeginUseProfilePoints before accessing the curve points.');
Result := fCurvePoints.Count;
end;
procedure TCurve2D.BeginUseProfilePoints;
begin
if fSavingType = stSpace then
WritableBox := PopulateCurvePoints(0);
end;
procedure TCurve2D.EndUseProfilePoints;
begin
if fSavingType = stSpace then
FreeCurvePoints;
end;
// =====================================================================
// TArc2D
// =====================================================================
procedure TArc2D.GetArcParams(var CX, CY, RX, RY, SA, EA: TRealType);
var
P1, P0: TPoint2D;
begin
P0:= CartesianPoint2D(Points[0]);
P1 := CartesianPoint2D(Points[1]);
CX := (P1.X + P0.X) / 2.0;
CY := (P1.Y + P0.Y) / 2.0;
RX := Abs(P1.X - P0.X) / 2.0;
RY := Abs(P1.Y - P0.Y) / 2.0;
if Points.Count < 3 then
Exit;
P0:= CartesianPoint2D(Points[2]);
P1 := CartesianPoint2D(Points[3]);
case FDirection of
adClockwise: begin
SA := ArcTan2(CY - P0.Y, P0.X - CX);
EA := ArcTan2(CY - P1.Y, P1.X - CX);
end;
adCounterClockwise: begin
SA := ArcTan2(P0.Y - CY, P0.X - CX);
EA := ArcTan2(P1.Y - CY, P1.X - CX);
end;
end;
end;
procedure TArc2D.SetStartAngle(A: TRealType);
var
CX, RX, CY, RY, SA, EA: TRealType;
begin
if fStartAngle <> A then
begin
fStartAngle := A;
GetArcParams(CX, CY, RX, RY, SA, EA);
Points[2] := Point2D(CX + RX * Cos(A), CY + RY * Sin(A));
end;
end;
procedure TArc2D.SetEndAngle(A: TRealType);
var
CX, RX, CY, RY, SA, EA: TRealType;
begin
if fEndAngle <> A then
begin
fEndAngle := A;
GetArcParams(CX, CY, RX, RY, SA, EA);
Points[3] := Point2D(CX + RX * Cos(A), CY + RY * Sin(A));
end;
end;
procedure TArc2D.SetArcDirection(D: TArcDirection);
begin
if D <> FDirection then
begin
FDirection := D;
UpdateExtension(Self);
end;
end;
function TArc2D.PopulateCurvePoints(N: Word): TRect2D;
var
Cont, NPts: Integer;
CX, RX, CY, RY: TRealType;
Delta, CurrAngle: TRealType;
begin
if CurvePrecision = 0 then
begin
Result := Rect2D(0, 0, 0, 0);
Exit;
end;
GetArcParams(CX, CY, RX, RY, fStartAngle, fEndAngle);
// Calcola il numero di punti effetivi nella curva
NPts := CurvePrecision;
// Calcola il delta angolare tra due punti
if fStartAngle < fEndAngle then
Delta := (fEndAngle - fStartAngle) / (NPts + 1)
else
Delta := (TWOPI - fStartAngle + fEndAngle) / (NPts + 1);
// Crea il vettore curvilineo.
inherited PopulateCurvePoints(NPts + 1);
// Popola il vettore curvilineo.
if fDirection = adClockwise then
begin
CurrAngle := fStartAngle;
for Cont := 0 to NPts - 1 do
begin
ProfilePoints.Add(Point2D(CX + RX * Cos(CurrAngle), CY - RY * Sin(CurrAngle)));
CurrAngle := CurrAngle + Delta
end;
ProfilePoints.Add(Point2D(CX + RX * Cos(fEndAngle), CY - RY * Sin(fEndAngle)));
end
else
begin
CurrAngle := fStartAngle;
for Cont := 0 to NPts - 1 do
begin
ProfilePoints.Add(Point2D(CX + RX * Cos(CurrAngle), CY + RY * Sin(CurrAngle)));
CurrAngle := CurrAngle + Delta
end;
ProfilePoints.Add(Point2D(CX + RX * Cos(fEndAngle), CY + RY * Sin(fEndAngle)));
end;
Result := TransformBoundingBox2D(ProfilePoints.Extension, ModelTransform);
end;
{ Angles are in radiants. }
constructor TArc2D.Create(ID: LongInt; const P1, P2: TPoint2D; SA, EA: TRealType);
begin
inherited Create(ID, 4, 50);
Points.DisableEvents := True;
try
Points.Add(P1);
Points.Add(P2);
Points.Add(Point2D(0, 0));
Points.Add(Point2D(0, 0));
fDirection := adClockwise;
StartAngle := SA;
EndAngle := EA;
Points.GrowingEnabled := False;
finally
Points.DisableEvents := False;
UpdateExtension(Self);
end;
end;
procedure TArc2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if (Obj is TEllipse2D) or (Obj is TFrame2D) then
begin
fStartAngle := 0;
fEndAngle := TWOPI;
Points.DisableEvents := True;
try
Points.Copy(TPrimitive2D(Obj).Points, 0, 1);
Points.Add(Point2D(0, 0));
Points.Add(Point2D(0, 0));
Points.GrowingEnabled := False;
finally
Points.DisableEvents := False;
UpdateExtension(Self);
end;
end
else if Obj is TArc2D then
begin
fStartAngle := (Obj as TArc2D).StartAngle;
fEndAngle := (Obj as TArc2D).EndAngle;
fDirection := (Obj as TArc2D).Direction;
Points.Copy(TPrimitive2D(Obj).Points, 0, 3);
Points.GrowingEnabled := False;
end;
end;
constructor TArc2D.CreateFromStream(const Stream: TStream; const Version: TCADVersion);
begin
{ Load the standard properties }
inherited;
Points.DisableEvents := True;
with Stream do
try
Read(FDirection, SizeOf(FDirection));
finally
Points.DisableEvents := False;
end;
end;
procedure TArc2D.SaveToStream(const Stream: TStream);
begin
{ Save the standard properties }
inherited SaveToStream(Stream);
with Stream do
Write(fDirection, SizeOf(FDirection));
end;
// =====================================================================
// TArc3Points2D
// =====================================================================
function TArc3Points2D.PopulateCurvePoints(N: Word): TRect2D;
var
Cont, NPts: Integer;
begin
if CurvePrecision = 0 then
begin
Result := Rect2D(0, 0, 0, 0);
Exit;
end;
NPts := CurvePrecision;
inherited PopulateCurvePoints(NPts + 1);
ProfilePoints.Add(Points[0]);
ProfilePoints.Add(Points[1]);
ProfilePoints.Add(Points[2]);
Result := TransformBoundingBox2D(ProfilePoints.Extension, ModelTransform);
end;
{ Angles are in radiants. }
constructor TArc3Points2D.Create(ID: LongInt; const P0, P1, P2: TPoint2D);
begin
inherited Create(ID, 4, 50);
Points.DisableEvents := True;
try
Points.Add(P0);
Points.Add(P1);
Points.Add(P2);
Points.Add(Point2D(0, 0));
Points.Add(Point2D(0, 0));
Points.Add(Point2D(0, 0));
Points.GrowingEnabled := False;
finally
Points.DisableEvents := False;
UpdateExtension(Self);
end;
end;
procedure TArc3Points2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if Obj is TArc3Points2D then
begin
Points.Copy(TPrimitive2D(Obj).Points, 0, 3);
Points.GrowingEnabled := False;
end;
end;
procedure TArc3Points2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
begin
end;
function TArc3Points2D.OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer;
begin
end;
// =====================================================================
// TFrame2D
// =====================================================================
function TFrame2D.PopulateCurvePoints(N: Word): TRect2D;
begin
if CurvePrecision = 0 then
begin
Result := Rect2D(0, 0, 0, 0);
Exit;
end;
inherited PopulateCurvePoints(CurvePrecision + 1);
ProfilePoints.Add(Points[0]);
ProfilePoints.Add(Point2D(Points[0].X, Points[1].Y));
ProfilePoints.Add(Points[1]);
ProfilePoints.Add(Point2D(Points[1].X, Points[0].Y));
ProfilePoints.Add(Points[0]);
Result := TransformBoundingBox2D(ProfilePoints.Extension, ModelTransform);
end;
constructor TFrame2D.Create(ID: LongInt; const P1, P2: TPoint2D);
begin
inherited Create(ID, 2, 50);
Points.DisableEvents := True;
try
Points.Add(P1);
Points.Add(P2);
Points.GrowingEnabled := False;
finally
Points.DisableEvents := False;
UpdateExtension(Self);
end;
end;
procedure TFrame2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if (Obj is TFrame2D) or (Obj is TEllipse2D) or (Obj is TArc2D) then
begin
Points.Copy(TPrimitive2D(Obj).Points, 0, 1);
Points.GrowingEnabled := False;
end;
end;
// =====================================================================
// TRectangle2D
// =====================================================================
procedure TRectangle2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
begin
BeginUseProfilePoints;
try
if not HasTransform then
ProfilePoints.DrawAsPolygon(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, VT)
else
ProfilePoints.DrawAsPolygon(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, MultiplyTransform2D(ModelTransform, VT));
finally
EndUseProfilePoints;
end;
end;
function TRectangle2D.OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer;
var
TmpDist: TRealType;
begin
Result := inherited OnMe(Pt, Aperture, Distance);
if Result = PICK_INBBOX then
begin
{ Consider all segments in the arc. }
BeginUseProfilePoints;
try
Result := MaxIntValue([PICK_INBBOX, IsPointInPolygon2D(ProfilePoints.PointsReference, ProfilePoints.Count, Pt, TmpDist, Aperture, ModelTransform)]);
Distance := MinValue([Aperture, TmpDist]);
finally
EndUseProfilePoints;
end;
end;
end;
// =====================================================================
// TCircle2D
// =====================================================================
procedure TCircle2D.GetCircleParams(var CX, CY, R: TRealType);
var
P1, P0: TPoint2D;
begin
P0:= CartesianPoint2D(Points[0]);
P1 := CartesianPoint2D(Points[1]);
R := SQRT(SQR(P1.X - P0.X)+SQR(P1.Y - P0.Y)) ;
CX := P0.X;
CY := P0.Y;
end;
function TCircle2D.PopulateCurvePoints(N: Word): TRect2D;
var
Cont: Integer;
Delta, CurrAngle, CX, CY, R: TRealType;
begin
if CurvePrecision = 0 then
begin
Result := Rect2D(0, 0, 0, 0);
Exit;
end;
inherited PopulateCurvePoints(CurvePrecision + 1);
GetCircleParams(CX, CY, R);
Delta := TWOPI / CurvePrecision;
ProfilePoints.Add(Point2D(CX +R , CY));
CurrAngle := Delta;
for Cont := 1 to CurvePrecision do
begin
ProfilePoints.Add(Point2D(CX + R * Cos(CurrAngle), CY - R * Sin(CurrAngle)));
CurrAngle := CurrAngle + Delta
end;
Result := TransformBoundingBox2D(Points.Extension, ModelTransform);
end;
constructor TCircle2D.Create(ID: LongInt; const P1: TPoint2D; R : TRealType);
VAR P2 : TPoint2d;
begin
inherited Create(ID, 2, 50);
Points.DisableEvents := True;
try
Points.Add(P1);
P2 := P1; P2.X := P2.X + R;
Points.Add(P2);
Points.GrowingEnabled := False;
finally
Points.DisableEvents := False;
UpdateExtension(Self);
end;
end;
procedure TCircle2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if (Obj is TCircle2D) or (Obj is TFrame2D) then
begin
Points.Copy(TPrimitive2D(Obj).Points, 0, 1);
Points.GrowingEnabled := False;
end;
end;
// =====================================================================
// TEllipse2D
// =====================================================================
procedure TEllipse2D.GetEllipseParams(var CX, CY, RX, RY: TRealType);
var
P1, P0: TPoint2D;
begin
P0:= CartesianPoint2D(Points[0]);
P1 := CartesianPoint2D(Points[1]);
RX := Abs(P1.X - P0.X) / 2.0 ;
RY := Abs(P1.Y - P0.Y) / 2.0;
CX := (P1.X + P0.X) / 2.0;
CY := (P1.Y + P0.Y) / 2.0;
end;
function TEllipse2D.PopulateCurvePoints(N: Word): TRect2D;
var
Cont: Integer;
Delta, CurrAngle, CX, RX, CY, RY: TRealType;
begin
if CurvePrecision = 0 then
begin
Result := Rect2D(0, 0, 0, 0);
Exit;
end;
inherited PopulateCurvePoints(CurvePrecision + 1);
GetEllipseParams(CX, CY, RX, RY);
Delta := TWOPI / CurvePrecision;
ProfilePoints.Add(Point2D(CX + RX, CY));
CurrAngle := Delta;
for Cont := 1 to CurvePrecision - 1 do
begin
ProfilePoints.Add(Point2D(CX + RX * Cos(CurrAngle), CY - RY * Sin(CurrAngle)));
CurrAngle := CurrAngle + Delta
end;
ProfilePoints.Add(Point2D(CX + RX, CY));
Result := TransformBoundingBox2D(Points.Extension, ModelTransform);
end;
constructor TEllipse2D.Create(ID: LongInt; const P1, P2: TPoint2D);
begin
inherited Create(ID, 2, 50);
Points.DisableEvents := True;
try
Points.Add(P1);
Points.Add(P2);
Points.GrowingEnabled := False;
finally
Points.DisableEvents := False;
UpdateExtension(Self);
end;
end;
procedure TEllipse2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if (Obj is TEllipse2D) or (Obj is TFrame2D) or (Obj is TArc2D) then
begin
Points.Copy(TPrimitive2D(Obj).Points, 0, 1);
Points.GrowingEnabled := False;
end;
end;
// =====================================================================
// TFilledEllipse2D
// =====================================================================
procedure TFilledEllipse2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
begin
BeginUseProfilePoints;
try
if not HasTransform then
ProfilePoints.DrawAsPolygon(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, VT)
else
ProfilePoints.DrawAsPolygon(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), Box, MultiplyTransform2D(ModelTransform, VT));
finally
EndUseProfilePoints;
end;
end;
function TFilledEllipse2D.OnMe(Pt: TPoint2D; Aperture: TRealType;
var Distance: TRealType): Integer;
var
TmpDist: TRealType;
begin
Result := inherited OnMe(Pt, Aperture, Distance);
if Result = PICK_INBBOX then
begin
{ Consider all segments in the arc. }
BeginUseProfilePoints;
try
Result := MaxIntValue([PICK_INBBOX, IsPointInPolygon2D(ProfilePoints.PointsReference, ProfilePoints.Count, Pt, TmpDist, Aperture, ModelTransform)]);
Distance := MinValue([Aperture, TmpDist]);
finally
EndUseProfilePoints;
end;
end;
end;
// =====================================================================
// TBSpline2D
// =====================================================================
function Knot(I, K, N: Integer): Integer;
begin
if I < K then
Result := 0
else if I > N then
Result := N - K + 2
else
Result := I - K + 1;
end;
function NBlend(I, K, OK, N: Integer; U: TRealType): TRealType;
var
T: Integer;
V: TRealType;
begin
if K = 1 then
begin
V := 0;
if (Knot(i, OK, N) <= u) and (u < Knot(i + 1, OK, N)) then
V := 1;
end
else
begin
V := 0;
T := Knot(I + K - 1, OK, N) - Knot(I, OK, N);
if T <> 0 then
V := (U - Knot(I, OK, N)) * NBlend(I, K -1, OK, N, U) / T;
T := Knot(I + K, OK, N) - Knot(I + 1, OK, N);
if T <> 0 then
V := V + (Knot(I + K, OK, N) - U) * NBlend(I + 1, K - 1, OK, N, U) / T;
end;
Result := V;
end;
function BSpline2D(U: TRealType; N, K: Integer; const Points: TPointsSet2D): TPoint2D;
var
I: Integer;
B: TRealType;
TmpPt: TPoint2D;
begin
Result := Point2D(0.0, 0.0);
for I := 0 to N do
begin
B := NBlend(I, K, K, N, U);
TmpPt := CartesianPoint2D(Points[I]);
Result.X := Result.X + TmpPt.X * B;
Result.Y := Result.Y + TmpPt.Y * B;
Result.W := 1.0;
end;
end;
function TBSpline2D.PopulateCurvePoints(N: Word): TRect2D;
var
Cont: Integer;
begin
if CurvePrecision = 0 then
begin
Result := Rect2D(0, 0, 0, 0);
Exit;
end;
if Points.Count < FOrder then
begin
inherited PopulateCurvePoints(Points.Count);
ProfilePoints.Copy(Points, 0, Points.Count - 1);
end
else
begin
inherited PopulateCurvePoints(CurvePrecision + 1);
for Cont := 0 to CurvePrecision - 1 do
ProfilePoints.Add(BSpline2D(Cont / CurvePrecision * (Points.Count - 2),
Points.Count - 1, FOrder, Points));
ProfilePoints.Add(Points[Points.Count - 1]);
end;
Result := TransformBoundingBox2D(ProfilePoints.Extension, ModelTransform);
end;
constructor TBSpline2D.Create(ID: LongInt; const Pts: array of TPoint2D);
begin
inherited Create(ID, High(Pts) - Low(Pts) + 1, 50);
fOrder := 3; { The default spline is cubic. }
Points.AddPoints(Pts);
Points.GrowingEnabled := True;
end;
constructor TBSpline2D.CreateFromStream(const Stream: TStream; const Version: TCADVersion);
begin
{ Load the standard properties }
inherited;
with Stream do
{ Load the particular properties. }
Read(fOrder, SizeOf(fOrder));
end;
procedure TBSpline2D.SaveToStream(const Stream: TStream);
begin
{ Save the standard properties }
inherited SaveToStream(Stream);
with Stream do
Write(fOrder, SizeOf(fOrder));
end;
procedure TBSpline2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if (Obj is TBSpline2D) then
begin
fOrder := TBSpline2D(Obj).fOrder;
Points.Copy(TPrimitive2D(Obj).Points, 0, TPrimitive2D(Obj).Points.Count - 1);
Points.GrowingEnabled := True;
end;
end;
// =====================================================================
// TText2D
// =====================================================================
constructor TText2D.Create(ID: LongInt; Rect1: TRect2D; Height: TRealType;
Txt: AnsiString);
begin
inherited Create(ID, 2);
Points.DisableEvents := True;
try
fHeight := Height;
fText := Txt;
fRecalcBox := False;
fDrawBox := False;
fExtFont := TExtendedFont.Create;
WritableBox := Rect1;
fClippingFlags := 0;
Points.Add(Rect1.FirstEdge);
Points.Add(Rect1.SecondEdge);
Points.GrowingEnabled := False;
finally
Points.DisableEvents := False;
UpdateExtension(Self);
end;
end;
destructor TText2D.Destroy;
begin
fExtFont.Free;
inherited Destroy;
end;
procedure TText2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
var
TmpBox: TRect2D;
TmpHeight: Integer;
TmpRect: TRect;
TmpTransf: TTransf2D;
begin
{ Find the correct size. }
TmpBox.FirstEdge := Point2D(0, 0);
TmpBox.SecondEdge := Point2D(0, fHeight);
TmpBox := TransformRect2D(TmpBox, VT);
TmpHeight := Round(PointDistance2D(TmpBox.FirstEdge, TmpBox.SecondEdge));
if TmpHeight <= 0 then
Exit;
{ Build up the DrawText rect. }
TmpRect := Rect2DToRect(TransformRect2D(Box, VT));
FExtFont.Canvas := Cnv.Canvas;
try
FExtFont.Height := TmpHeight;
if fRecalcBox then
begin
Windows.DrawText(Cnv.Canvas.Handle, PChar(FText), Length(FText), TmpRect, DT_NOCLIP);
Windows.DrawText(Cnv.Canvas.Handle, PChar(FText), Length(FText), TmpRect, DT_CALCRECT);
if not HasTransform then
TmpTransf := VT
else
TmpTransf := MultiplyTransform2D(ModelTransform, VT);
TmpBox := TransformBoundingBox2D(RectToRect2D(TmpRect), InvertTransform2D(TmpTransf));
Points.DisableEvents := True;
try
Points[0] := TmpBox.FirstEdge;
Points[1] := TmpBox.SecondEdge;
finally
Points.DisableEvents := False;
UpdateExtension(Self);
end;
end;
if (Cnv.Canvas.Pen.Mode <> pmXor) then begin
Windows.DrawText(Cnv.Canvas.Handle, PChar(FText), Length(FText), TmpRect, DT_NOCLIP);
Windows.DrawText(Cnv.Canvas.Handle, PChar(FText), Length(FText), TmpRect, FClippingFlags);
end;
if FDrawBox or (Cnv.Canvas.Pen.Mode = pmXor) then
DrawRect2DAsPolyline(Cnv, Box, RectToRect2D(Cnv.Canvas.ClipRect), IdentityTransf2D, VT);
finally
FExtFont.Canvas := nil;
end;
end;
function TText2D.OnMe(Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer;
begin
Result := inherited OnMe(Pt, Aperture, Distance);
if Result = PICK_INBBOX then
Result := PICK_INOBJECT;
end;
constructor TText2D.CreateFromStream(const Stream: TStream; const Version: TCADVersion);
var
TmpInt: Integer;
begin
{ Load the standard properties }
inherited;
with Stream do
begin
Read(TmpInt, SizeOf(TmpInt));
SetString(FText, nil, TmpInt);
Read(Pointer(FText)^, TmpInt);
FExtFont := TExtendedFont.Create;
FExtFont.LoadFromStream(Stream);
Read(FClippingFlags, SizeOf(FClippingFlags));
Read(FDrawBox, SizeOf(FDrawBox));
Read(fHeight, SizeOf(fHeight))
end;
end;
procedure TText2D.SaveToStream(const Stream: TStream);
var
TmpInt: Integer;
begin
{ Save the standard properties }
inherited SaveToStream(Stream);
with Stream do
begin
TmpInt := Length(FText);
Write(TmpInt, SizeOf(TmpInt));
Write(Pointer(FText)^, Length(FText));
FExtFont.SaveToStream(Stream);
Write(FClippingFlags, SizeOf(FClippingFlags));
Write(FDrawBox, SizeOf(FDrawBox));
Write(fHeight, SizeOf(fHeight));
end;
end;
procedure TText2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if (Obj is TText2D) or (Obj is TFrame2D) then
begin
if Obj is TText2D then
begin
fText := (Obj as TText2D).Text;
fHeight := (Obj as TText2D).Height;
fDrawBox := (Obj as TText2D).DrawBox;
fRecalcBox := (Obj as TText2D).fRecalcBox;
fClippingFlags := (Obj as TText2D).ClippingFlags;
if not Assigned(FExtFont) then
FExtFont := TExtendedFont.Create;
fExtFont.Assign(TText2D(Obj).fExtFont);
end;
Points.Copy(TPrimitive2D(Obj).Points, 0, 1);
Points.GrowingEnabled := False;
end;
end;
// =====================================================================
// TBitmap2D
// =====================================================================
procedure TBitmap2D.SetScaleFactor(SF: TRealType);
var
TmpPt: TPoint2D;
begin
if( fScaleFactor <> SF ) then
begin
fScaleFactor := SF;
if( fScaleFactor <> 0.0 ) then
begin
if( fAspectRatio <> 0.0 ) then
TmpPt.X := Points[0].X + fBitmap.Height * fScaleFactor / fAspectRatio
else
TmpPt.X := Points[0].X + fBitmap.Width * fScaleFactor;
TmpPt.Y := Points[0].Y + fBitmap.Height * fScaleFactor;
TmpPt.W := 1.0;
Points[1] := TmpPt;
end;
end;
end;
procedure TBitmap2D.SetAspectRatio(AR: TRealType);
var
TmpPt: TPoint2D;
begin
if( fAspectRatio <> AR ) then
begin
fAspectRatio := AR;
if( fScaleFactor <> 0.0 ) then
begin
if( fAspectRatio <> 0.0 ) then
TmpPt.X := Points[0].X + fBitmap.Height * fScaleFactor / fAspectRatio
else
TmpPt.X := Points[0].X + fBitmap.Width * fScaleFactor;
TmpPt.Y := Points[0].Y + fBitmap.Height * fScaleFactor;
TmpPt.W := 1.0;
Points[1] := TmpPt;
end;
end;
end;
constructor TBitmap2D.Create(ID: LongInt; const P1, P2: TPoint2D; Bmp: TBitmap);
begin
inherited Create(ID, 2);
fScaleFactor := 0.0;
fAspectRatio := 0.0;
fCopyMode := cmSrcCopy;
Points.DisableEvents := True;
try
fBitmap := TBitmap.Create;
fBitmap.Assign(Bmp);
Points.Add(P1);
Points.Add(P2);
Points.GrowingEnabled := False;
finally
Points.DisableEvents := False;
UpdateExtension(Self);
end;
end;
procedure TBitmap2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited;
if (Obj is TBitmap2D) or (Obj is TFrame2D) then
begin
fScaleFactor := TBitmap2D(Obj).ScaleFactor;
fAspectRatio := TBitmap2D(Obj).AspectRatio;
fCopyMode := TBitmap2D(Obj).CopyMode;
if Obj is TBitmap2D then
fBitmap.Assign(TBitmap2D(Obj).fBitmap);
Points.Copy(TPrimitive2D(Obj).Points, 0, 1);
Points.GrowingEnabled := True;
end;
end;
destructor TBitmap2D.Destroy;
begin
fBitmap.Free;
inherited Destroy;
end;
constructor TBitmap2D.CreateFromStream(const Stream: TStream; const Version: TCADVersion);
begin
{ Load the standard properties }
inherited;
fBitmap := TBitmap.Create;
fBitmap.LoadFromStream(Stream);
if( Version >= 'CAD422' ) then
begin
Stream.Read(fScaleFactor, SizeOf(fScaleFactor));
Stream.Read(fAspectRatio, SizeOf(fAspectRatio));
Stream.Read(fCopyMode, SizeOf(fCopyMode));
end;
end;
procedure TBitmap2D.SaveToStream(const Stream: TStream);
begin
{ Save the standard properties }
inherited SaveToStream(Stream);
fBitmap.SaveToStream(Stream);
Stream.Write(fScaleFactor, SizeOf(fScaleFactor));
Stream.Write(fAspectRatio, SizeOf(fAspectRatio));
Stream.Write(fCopyMode, SizeOf(fCopyMode));
end;
procedure TBitmap2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
var
TmpPt1, TmpPt2: TPoint2D;
TmpTransf: TTransf2D;
TmpRect: TRect;
OldMode: TCopyMode;
begin
if not HasTransform then
TmpTransf := VT
else
TmpTransf := MultiplyTransform2D(ModelTransform, VT);
TmpPt1 := TransformPoint2D(Points[0], TmpTransf);
TmpPt2 := TransformPoint2D(Points[1], TmpTransf);
TmpRect := Rect2DToRect(Rect2D(TmpPt1.X, TmpPt1.Y, TmpPt2.X, TmpPt2.Y));
OldMode := Cnv.Canvas.CopyMode;
Cnv.Canvas.CopyMode := fCopyMode;
Cnv.Canvas.StretchDraw(TmpRect, fBitmap);
Cnv.Canvas.CopyMode := OldMode;
end;
// =====================================================================
// TVectFont
// =====================================================================
function TVectChar.GetVect(Idx: Integer): TPointsSet2D;
begin
Result := TPointsSet2D(fSubVects[Idx]);
end;
function TVectChar.GetVectCount: Integer;
begin
Result := fSubVects.NumberOfObjects;
end;
constructor TVectChar.Create(NSubVect: Integer);
var
Cont: Integer;
begin
inherited Create;
fSubVects := TIndexedObjectList.Create(NSubVect);
fSubVects.FreeOnClear := True;
for Cont := 0 to NSubVect - 1 do
fSubVects.Objects[Cont] := TPointsSet2D.Create(0);
end;
destructor TVectChar.Destroy;
begin
fSubVects.Free;
inherited;
end;
procedure TVectChar.UpdateExtension;
var
Cont: Integer;
begin
fExtension := Rect2D(0.0, 0.0, 0.0, 0.0);
for Cont := 0 to fSubVects.NumberOfObjects - 1 do
fExtension := BoxOutBox2D(fExtension, TPointsSet2D(fSubVects.Objects[Cont]).Extension);
end;
constructor TVectChar.CreateFromStream(const Stream: TStream; const Version: TCADVersion);
var
TmpInt, Cont: Integer;
TmpWord: Word;
TmpPt: TPoint2D;
begin
inherited Create;
if( Version >= 'CAD4 ' ) then
with Stream do
begin
Read(TmpInt, SizeOf(TmpInt));
fSubVects := TIndexedObjectList.Create(TmpInt);
// Lettura vettori.
for Cont := 0 to fSubVects.NumberOfObjects - 1 do
begin
Read(TmpWord, SizeOf(TmpWord));
fSubVects.Objects[Cont] := TPointsSet2D.Create(TmpWord);
while TmpWord > 0 do
begin
Read(TmpPt, SizeOf(TmpPt));
TPointsSet2D(fSubVects.Objects[Cont]).Add(TmpPt);
Dec(TmpWord);
end;
end;
UpdateExtension(Self);
end;
end;
procedure TVectChar.SaveToStream(const Stream: TStream);
var
TmpInt, Cont: Integer;
TmpWord: Word;
TmpPt: TPoint2D;
begin
with Stream do
begin
TmpInt := fSubVects.NumberOfObjects;
Write(TmpInt, SizeOf(TmpInt));
// Scrittura vettori.
for Cont := 0 to fSubVects.NumberOfObjects - 1 do
begin
TmpWord := TPointsSet2D(fSubVects.Objects[Cont]).Count;
Write(TmpWord, SizeOf(TmpWord));
while TmpWord > 0 do
begin
TmpPt := TPointsSet2D(fSubVects.Objects[Cont]).Points[TmpWord - 1];
Write(TmpPt, SizeOf(TmpPt));
Dec(TmpWord);
end;
end;
end;
end;
// =====================================================================
// TVectFont
// =====================================================================
function TVectFont.GetChar(Ch: Char): TVectChar;
begin
// if Ch= 'ë' then
// sleep(10);
Result := TVectChar(fVects[Ord(Ch)]);
//Result := TVectChar(fVects[211]);
end;
constructor TVectFont.Create;
begin
inherited;
// Al massimo ci sono 256 caratteri.
fVects := TIndexedObjectList.Create(256);
fVects.FreeOnClear := True;
end;
destructor TVectFont.Destroy;
begin
fVects.Free;
inherited;
end;
constructor TVectFont.CreateFromStream(const Stream: TStream; const Version: TCADVersion);
var
TmpInt: Integer;
begin
inherited Create;
with Stream do
begin
fVects := TIndexedObjectList.Create(256);
// Lettura caratteri.
while True do
begin
// Lettura numero carattere.
Read(TmpInt, SizeOf(TmpInt));
if TmpInt = -1 then
Break; // Fine.
fVects[TmpInt] := TVectChar.CreateFromStream(Stream, Version);
end;
end;
end;
procedure TVectFont.SaveToStream(const Stream: TStream);
var
TmpInt: Integer;
begin
with Stream do
begin
// Scrittura caratteri.
for TmpInt := 0 to fVects.NumberOfObjects - 1 do
if fVects[TmpInt] <> nil then
begin
// Scrittura numero carattere.
Write(TmpInt, SizeOf(TmpInt));
TVectChar(fVects[TmpInt]).SaveToStream(Stream);
end;
// Fine
TmpInt := -1;
Write(TmpInt, SizeOf(TmpInt));
end;
end;
function TVectFont.CreateChar(Ch: Char; N: Integer): TVectChar;
begin
if fVects[Ord(Ch)] <> nil then
fVects[Ord(Ch)].Free;
Result := TVectChar.Create(N);
fVects[Ord(Ch)] := Result;
end;
procedure TVectFont.DrawChar2D(Ch: Char; var DrawPoint: TPoint2D; const H, ICS: TRealType; const VT: TTransf2D; Cnv: TDecorativeCanvas);
var
Cont: Integer;
TmpTransf: TTransf2D;
TmpExt: TRect2D;
TmpCh: TVectChar;
begin
TmpCh := nil;
if (Ch = ' ') then
begin
DrawPoint.X := DrawPoint.X + (0.4 + ICS) * H;
Exit;
end
else if fVects[Ord(Ch)] <> nil then
TmpCh := GetChar(Ch)
else if (Ch <> #13) then
TmpCh := _NullChar;
if TmpCh <> nil then
begin
TmpTransf := IdentityTransf2D;
TmpTransf[1, 1] := H;
TmpTransf[2, 2] := H;
TmpTransf[3, 1] := DrawPoint.X;
TmpTransf[3, 2] := DrawPoint.Y;
TmpTransf[3, 3] := DrawPoint.W;
with TmpCh do
begin
TmpExt := Extension;
for Cont := 0 to VectorCount - 1 do
Vectors[Cont].DrawAsPolyline(Cnv, RectToRect2D(Cnv.Canvas.ClipRect), TmpExt, MultiplyTransform2D(TmpTransf, VT));
DrawPoint.X := DrawPoint.X + (TmpExt.Right + ICS) * H;
end;
end;
end;
function TVectFont.GetTextExtension(Str: AnsiString; H, InterChar, InterLine: TRealType): TRect2D;
var
Cont: Integer;
RowLen, RowHeight, MaxRowLen: TRealType;
begin
// Per i caratteri con la gambetta (come g) parto con Bottom = 1.0
Result := Rect2D(0.0, 1.0, 0.0, H);
MaxRowLen := 0.0;
RowLen := 0.0;
RowHeight := 0.0;
for Cont := 1 to Length(Str) do
begin
if fVects[Ord(Str[Cont])] <> nil then
with GetChar(Str[Cont]).Extension do
begin
RowLen := RowLen + (Right + InterChar);
// Bottom contiene l'eventuale gambetta.
RowHeight := MaxValue([RowHeight, 1.0 - Bottom]);
end
else if Str[Cont] = ' ' then
// Space.
RowLen := RowLen + (0.5 + InterChar)
else if Str[Cont] <> #13 then
// Carattere nullo.
with _NullChar.Extension do
RowLen := RowLen + (Right + InterChar);
if Str[Cont] = #13 then
begin
// New line. L'altezza è 1.3 per via delle gambette.
MaxRowLen := MaxValue([MaxRowLen, RowLen - InterChar]);
Result.Bottom := Result.Bottom - (InterLine + RowHeight);
RowLen := 0.0;
RowHeight := 0.0;
end;
end;
MaxRowLen := MaxValue([MaxRowLen, RowLen - InterChar]);
Result.Left := 0.0;
Result.Bottom := (Result.Bottom - RowHeight) * H;
Result.Right := MaxRowLen * H;
end;
// =====================================================================
// Registration functions
// =====================================================================
function CADSysFindFontIndex(const Font: TVectFont): Word;
var
Cont: Integer;
begin
for Cont := 0 to MAX_REGISTERED_FONTS do
if Assigned(VectFonts2DRegistered[Cont]) and
(VectFonts2DRegistered[Cont] = Font) then
begin
Result := Cont;
Exit;
end;
Raise ECADObjClassNotFound.Create('CADSysFindFontIndex: Font not found');
end;
function CADSysFindFontByIndex(Index: Word): TVectFont;
begin
if not Assigned(VectFonts2DRegistered[Index]) then
begin
if Assigned(_DefaultFont) then
Result := _DefaultFont
else
Raise ECADObjClassNotFound.Create('CADSysFindFontByIndex: Font not registered');
end
else
Result := VectFonts2DRegistered[Index];
end;
procedure CADSysRegisterFont(Index: Word; const Font: TVectFont);
begin
if Index > MAX_REGISTERED_FONTS then
Raise ECADOutOfBound.Create('CADSysRegisterFont: Out of bound registration index');
if Assigned(VectFonts2DRegistered[Index]) then
Raise ECADObjClassNotFound.Create('CADSysRegisterFont: Font index already allocated');
VectFonts2DRegistered[Index] := Font;
end;
procedure CADSysUnregisterFont(Index: Word);
begin
if Index > MAX_REGISTERED_FONTS then
Raise ECADOutOfBound.Create('CADSysUnregisterFont: Out of bound registration index');
if Assigned(VectFonts2DRegistered[Index]) then
begin
VectFonts2DRegistered[Index].Free;
VectFonts2DRegistered[Index] := nil;
end;
end;
procedure CADSysRegisterFontFromFile(Index: Word; const FileName: String);
var
TmpStream: TFileStream;
begin
if Index > MAX_REGISTERED_FONTS then
Raise ECADOutOfBound.Create('CADSysRegisterFontFromFile: Out of bound registration index');
if Assigned(VectFonts2DRegistered[Index]) then
Raise ECADObjClassNotFound.Create('CADSysRegisterFontFromFile: Font index already allocated');
TmpStream := TFileStream.Create(FileName, fmOpenRead);
try
VectFonts2DRegistered[Index] := TVectFont.CreateFromStream(TmpStream, CADSysVersion);
finally
TmpStream.Free;
end;
end;
procedure CADSysInitFontList;
var
Cont: Word;
begin
for Cont := 0 to MAX_REGISTERED_FONTS do
VectFonts2DRegistered[Cont] := nil;
end;
procedure CADSysClearFontList;
var
Cont: Word;
begin
for Cont := 0 to MAX_REGISTERED_FONTS do
if Assigned(VectFonts2DRegistered[Cont]) then
VectFonts2DRegistered[Cont].Free;
end;
function CADSysGetDefaultFont: TVectFont;
begin
Result := _DefaultFont;
end;
procedure CADSysSetDefaultFont(const Font: TVectFont);
begin
_DefaultFont := Font;
end;
// =====================================================================
// TJustifiedVectText2D
// =====================================================================
procedure TJustifiedVectText2D.SetHeight(H: TRealType);
begin
fHeight := H;
UpdateExtension(Self);
end;
procedure TJustifiedVectText2D.SetCharSpace(S: TRealType);
begin
fCharSpace := S;
UpdateExtension(Self);
end;
procedure TJustifiedVectText2D.SetInterLine(S: TRealType);
begin
fInterLine := S;
UpdateExtension(Self);
end;
procedure TJustifiedVectText2D.SetText(T: String);
begin
fText := T;
UpdateExtension(Self);
end;
function TJustifiedVectText2D.GetTextExtension: TRect2D;
var
TmpRect: TRect2D;
CurrRect: TRect2D;
DX, TX, TY: TRealType;
begin
if Assigned(fVectFont) then
TmpRect := fVectFont.GetTextExtension(fText, fHeight, fCharSpace, fInterLine)
else
TmpRect := Rect2D(0, 0, 0, 0);
CurrRect.FirstEdge := Points[0];
CurrRect.SecondEdge := Points[1];
CurrRect := ReorderRect2D(CurrRect);
fBasePoint := Point2D(CurrRect.Left, CurrRect.Top - TmpRect.Top);
DX := TmpRect.Right - TmpRect.Left;
case fHJustification of
jhLeft: TX := CurrRect.Left;
jhRight: TX := CurrRect.Right - DX;
jhCenter: TX := (CurrRect.Left + CurrRect.Right - DX) / 2.0;
else
TX := CurrRect.Left;
end;
case fVJustification of
jvTop: TY := CurrRect.Top - TmpRect.Top;
jvBottom: TY := CurrRect.Bottom - TmpRect.Bottom;
jvCenter: TY := (CurrRect.Top + CurrRect.Bottom) / 2.0;
else
TY := CurrRect.Top - TmpRect.Top;
end;
Result := TransformRect2D(TmpRect, Translate2D(TX, TY));
end;
procedure TJustifiedVectText2D.DrawText(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const DrawMode: Integer);
procedure DrawTextLine(BasePt: TPoint2D; Str: String; ObjTransf: TTransf2D);
var
Cont: Integer;
begin
for Cont := 1 to Length(Str) do
// Disegno il carattere.
fVectFont.DrawChar2D(Str[Cont], BasePt, fHeight, fCharSpace, ObjTransf, Cnv);
end;
var
TmpTransf: TTransf2D;
TmpStr, TmpRow: String;
CurrBasePt: TPoint2D;
TmpPos: Integer;
TmpTExt: TRect2D;
TmpRect: TRect; //agl
TmpBox: TRect2D; //agl
TmpHeight: Integer; //agl
LogFont: TLogFont;
begin
if not Assigned(fVectFont) then
Exit;
// sposto il testo, applico la trasformazione oggetto al testo e trasformo nel viewport.
TmpTransf := MultiplyTransform2D(ModelTransform, VT);
try
TmpTExt := GetTextExtension;
if fDrawBox then
DrawRect2DAsPolyline(Cnv, TmpTExt, RectToRect2D(Cnv.Canvas.ClipRect), ModelTransform, VT);
if DrawMode and DRAWMODE_VECTTEXTONLYBOX = DRAWMODE_VECTTEXTONLYBOX then
Exit;
CurrBasePt.X := TmpTExt.Left;
CurrBasePt.Y := TmpTExt.Top - fHeight;
CurrBasePt.W := 1.0;
// Estraggo le righe.
TmpStr := fText;
TmpPos := Pos(#13, TmpStr);
while TmpPos > 0 do
begin
TmpRow := Copy(TmpStr, 1, TmpPos - 1);
Delete(TmpStr, 1, TmpPos);
if TmpStr[1] = #10 then
Delete(TmpStr, 1, 1);
TmpPos := Pos(#13, TmpStr);
// Draw the string.
TmpTExt := fVectFont.GetTextExtension(TmpRow, fHeight, fCharSpace, fInterLine);
DrawTextLine(CurrBasePt, TmpRow, TmpTransf);
CurrBasePt.Y := CurrBasePt.Y - (TmpTExt.Top - TmpTExt.Bottom) - fHeight * fInterLine;
end;
// Draw the string.
// DrawTextLine(CurrBasePt, TmpStr, TmpTransf); //agl
//agl
{ Find the correct size. }
TmpBox.FirstEdge := Point2D(0, 0);
TmpBox.SecondEdge := Point2D(0, fHeight);
TmpBox := TransformRect2D(TmpBox, VT);
TmpHeight := Round(PointDistance2D(TmpBox.FirstEdge, TmpBox.SecondEdge));
TmpRect := Rect2DToRect(TransformRect2D(Box, VT));
cnv.Canvas.Font.Size := TmpHeight;
cnv.Canvas.Font.Name := 'Times New Roman';
cnv.Canvas.Font.Style := [fsItalic];
GetObject(cnv.Canvas.Font.Handle, sizeof(TLogFont), @LogFont);
LogFont.lfEscapement :=0 * 10; // óãîë ïîâîðîòà round(TmpTransf[1, 2]);
// z := TmpRect.Right + (TmpRect.Right - TmpRect.Left);
// TmpRect.Left := TmpRect.Right;
// TmpRect.Right := z;
LogFont.lfPitchAndFamily := FIXED_PITCH or FF_DONTCARE;
cnv.Canvas.Font.Handle := CreateFontIndirect(LogFont);
SetBkMode(Cnv.Canvas.Handle, TRANSPARENT);
Windows.DrawText(Cnv.Canvas.Handle, PChar(FText), Length(FText), TmpRect, DT_NOCLIP);
finally
end;
end;
constructor TJustifiedVectText2D.Create(ID: LongInt; FontVect: TVectFont; TextBox: TRect2D; Height: TRealType; Txt: AnsiString);
begin
inherited Create(ID, 2);
Points.DisableEvents := True;
try
Points.Add(TextBox.FirstEdge);
Points.Add(TextBox.SecondEdge);
Points.GrowingEnabled := False;
finally
Points.DisableEvents := False;
end;
fHeight := Height;
fCharSpace := 0.1;
fInterLine := 0.02;
fText := Txt;
fDrawBox := False;
fVectFont := FontVect;
fHJustification := jhLeft;
fVJustification := jvTop;
UpdateExtension(Self);
end;
constructor TJustifiedVectText2D.CreateFromStream(const Stream: TStream; const Version: TCADVersion);
var
TmpInt: Integer;
begin
{ Load the standard properties }
inherited;
with Stream do
begin
Read(TmpInt, SizeOf(TmpInt));
SetString(fText, nil, TmpInt);
Read(Pointer(fText)^, TmpInt);
// Lettura indice font.
Read(TmpInt, SizeOf(TmpInt));
try
fVectFont := CADSysFindFontByIndex(TmpInt);
except
on ECADObjClassNotFound do
begin
ShowMessage('Font class not found. Font not assigned');
fVectFont := nil;
end;
end;
Read(fHJustification, SizeOf(fHJustification));
Read(fVJustification, SizeOf(fVJustification));
Read(fDrawBox, SizeOf(fDrawBox));
Read(fHeight, SizeOf(fHeight));
Read(fInterLine, SizeOf(fInterLine));
Read(fCharSpace, SizeOf(fCharSpace));
end;
end;
procedure TJustifiedVectText2D.Assign(const Obj: TGraphicObject);
begin
if (Obj = Self) then
Exit;
inherited Assign(Obj);
if (Obj is TJustifiedVectText2D) or (Obj is TText2D) then
begin
if not Assigned(Points) then
begin
Points := CreateVect(2);
Points.GrowingEnabled := False;
Points.OnChange := UpdateExtension;
end;
if Obj is TJustifiedVectText2D then
begin
fText := (Obj as TJustifiedVectText2D).Text;
fHeight := (Obj as TJustifiedVectText2D).Height;
fInterLine := (Obj as TJustifiedVectText2D).InterLine;
fCharSpace := (Obj as TJustifiedVectText2D).CharSpace;
fDrawBox := (Obj as TJustifiedVectText2D).DrawBox;
fVectFont := (Obj as TJustifiedVectText2D).fVectFont;
fHJustification := (Obj as TJustifiedVectText2D).fHJustification;
fVJustification := (Obj as TJustifiedVectText2D).fVJustification;
end
else if Obj is TText2D then
begin
fText := (Obj as TText2D).Text;
fHeight := (Obj as TText2D).Height;
fDrawBox := (Obj as TText2D).DrawBox;
end;
Points.Clear;
Points.Copy(TPrimitive2D(Obj).Points, 0, 1);
end;
end;
procedure TJustifiedVectText2D.SaveToStream(const Stream: TStream);
var
TmpInt: Integer;
begin
{ Save the standard properties }
inherited;
with Stream do
begin
TmpInt := Length(fText);
Write(TmpInt, SizeOf(TmpInt));
Write(Pointer(fText)^, TmpInt);
// Scrittura indice font.
TmpInt := CADSysFindFontIndex(fVectFont);
Write(TmpInt, SizeOf(TmpInt));
Write(fHJustification, SizeOf(fHJustification));
Write(fVJustification, SizeOf(fVJustification));
Write(fDrawBox, SizeOf(fDrawBox));
Write(fHeight, SizeOf(fHeight));
Write(fInterLine, SizeOf(fInterLine));
Write(fCharSpace, SizeOf(fCharSpace));
end;
end;
procedure TJustifiedVectText2D.Draw(const VT: TTransf2D; const Cnv: TDecorativeCanvas; const ClipRect2D: TRect2D; const DrawMode: Integer);
begin
DrawText(VT, Cnv, DrawMode);
end;
function TJustifiedVectText2D.OnMe(Pt: TPoint2D; Aperture: TRealType; var Distance: TRealType): Integer;
var
TmpVect: TPointsSet2D;
TmpDist: TRealType;
TmpBox: TRect2D;
begin
Result := inherited OnMe(Pt, Aperture, Distance);
if (Result = PICK_INBBOX) then
begin
TmpBox := GetTextExtension;
TmpVect := TPointsSet2D.Create(4);
try
TmpVect.Add(TmpBox.FirstEdge);
TmpVect.Add(Point2D(TmpBox.Left, TmpBox.Top));
TmpVect.Add(TmpBox.SecondEdge);
TmpVect.Add(Point2D(TmpBox.Right, TmpBox.Bottom));
Result := MaxIntValue([PICK_INBBOX, IsPointInPolygon2D(TmpVect.PointsReference, TmpVect.Count, Pt, TmpDist, Aperture, ModelTransform)]);
Distance := MinValue([Aperture, TmpDist]);
finally
TmpVect.Free;
end;
end;
end;
procedure TJustifiedVectText2D._UpdateExtension;
begin
inherited;
WritableBox := TransformBoundingBox2D(GetTextExtension, ModelTransform);
end;
initialization
CADSysRegisterClass(3, TLine2D);
CADSysRegisterClass(4, TPolyline2D);
CADSysRegisterClass(5, TPolygon2D);
CADSysRegisterClass(6, TRectangle2D);
CADSysRegisterClass(7, TArc2D);
CADSysRegisterClass(8, TEllipse2D);
CADSysRegisterClass(9, TFilledEllipse2D);
CADSysRegisterClass(10, TText2D);
CADSysRegisterClass(11, TFrame2D);
CADSysRegisterClass(12, TBitmap2D);
CADSysRegisterClass(13, TBSpline2D);
CADSysRegisterClass(14, TJustifiedVectText2D);
CADSysRegisterClass(15, TArc3Points2D);
CADSysRegisterClass(16, TCircle2D);
// User definied shapes
CADSysRegisterClass(20, TClosedPolyline2D);
_DefaultHandler2D := TPrimitive2DHandler.Create(nil);
// Vectorial fonts
CADSysInitFontList;
_NullChar := TVectChar.Create(1);
_NullChar.Vectors[0].Add(Point2D(0.0, 0.0));
_NullChar.Vectors[0].Add(Point2D(0.8, 0.0));
_NullChar.UpdateExtension(nil);
_DefaultFont := nil;
finalization
CADSysClearFontList;
_NullChar.Free;
_DefaultHandler2D.Free;
end.
|
unit uStenography;
interface
uses
Math,
Classes,
SysUtils,
Windows,
Graphics,
Jpeg,
Dmitry.CRC32,
Dmitry.Utils.Files,
Dmitry.Graphics.Types,
uMemory,
uStrongCrypt,
DECUtil,
DECCipher;
const
MaxSizeWidthHeight = 32768;
StenoHeaderId = 'PHST';
StenoHeaderIdLength = SizeOf(StenoHeaderId);
type
StenographyHeader = record
ID: string[StenoHeaderIdLength];
Version : Byte;
FileSize : Integer;
Seed: TSeed;
FileName: TFileNameUnicode;
IsCrypted: Boolean;
PassCRC: Cardinal;
Chiper: Cardinal;
DataCRC: Cardinal;
end;
// BeginImage преобразовывается в Tbitmap с учётом информации Info с ячейкой размером Cell
function SaveInfoToBmpFile(BeginImage: TGraphic; ResultImage : TBitmap; Info: TStream; Cell: Integer): Boolean;
// достаём информацию из Bitmap
function ExtractInfoFromBitmap(Dest: TStream; Bitmap: TBitmap) : Boolean;
// Save file to stream, optional crypting
procedure SaveFileToCryptedStream(FileName: string; Password: string; Dest : TStream; HeaderInTheEnd: Boolean);
// максимально возможное количество информации, которое можо записать в Graphic с ячейкой размером Cell
function MaxSizeInfoInGraphic(Graphic: TGraphic; Cell: Integer): Integer;
// выдаёт размер Cell, наиболее оптимальный если сохранять в Graphic информацию о файле FileName
function GetMaxPixelsInSquare(FileName: string; Graphic: TGraphic): Integer;
//JPEG-steno
function CreateJPEGSteno(DataFileName, DestFileName: string; SourceJpegImage: string; Password: string): Boolean;
function CreateJPEGStenoEx(DataFileName, DestFileName: string; SourceJpegImage: TStream; Password: string): Boolean;
function IsValidJPEGSteno(FileName: string): Boolean;
function ExtractJPEGSteno(MS, Dest: TStream; out Header: StenographyHeader): Boolean;
implementation
procedure SetPixel(P: PRGB; var C: Integer); inline;
procedure SetByte(var B: Byte; var C: Integer); inline;
begin
if C > 0 then
begin
if B < $FF then
begin
B := B + 1;
C := C - 1;
end;
end
else if C < 0 then
begin
if B > $0 then
begin
B := B - 1;
C := C + 1;
end;
end;
end;
begin
SetByte(P.R, C);
SetByte(P.G, C);
SetByte(P.B, C);
end;
function SaveInfoToBmpFile(BeginImage: TGraphic; ResultImage : TBitmap; Info: TStream; Cell: Integer): Boolean;
var
XP: array of PARGB;
S, I, J, K, L, C, N, Size: Integer;
Bsize: array [1 .. 5] of Byte;
InfoByte : Byte;
begin
Randomize;
Result := False;
if Cell > 23 then
Exit;
if Cell < 2 then
Exit;
if BeginImage is TIcon then
begin
ResultImage.SetSize(BeginImage.Width, BeginImage.Height);
ResultImage.Canvas.Draw(0, 0, BeginImage);
end else
ResultImage.Assign(BeginImage);
ResultImage.PixelFormat := pf24bit;
SetLength(XP, ResultImage.Height);
for I := 0 to ResultImage.Height - 1 do
XP[I] := ResultImage.ScanLine[I];
//using no more than 2Gb
Size := Integer(Info.Size);
Bsize[1] := Cell;
Bsize[2] := Size and $FF;
Bsize[3] := (Size shr 8) and $FF;
Bsize[4] := (Size shr 16) and $FF;
Bsize[5] := (Size shr 24) and $FF;
N := 0;
S := XP[0, 0].R + XP[0, 0].G + XP[0, 0].B;
C := Cell - S mod 24;
if S + C > 254 * 3 then
C := C - 24;
if S + C < 0 then
C := C + 24;
repeat
SetPixel(@XP[0, 0], C);
until C = 0;
Info.Seek(0, soFromBeginning);
for I := 0 to (ResultImage.Height - 1) div Cell - 1 do
for J := 0 to (ResultImage.Width - 1) div Cell - 1 do
begin
C := 0;
Inc(N);
if I * ((ResultImage.Height - 1) div Cell - 1) + J = 5 then
N := 0;
for K := I * Cell to (I + 1) * Cell - 1 do
for L := J * Cell to (J + 1) * Cell - 1 do
if K + L <> 0 then
begin
Inc(C, XP[K, L].R);
Inc(C, XP[K, L].G);
Inc(C, XP[K, L].B);
end;
S := C;
if I * ((ResultImage.Height - 1) div Cell - 1) + J > 4 then
begin
if N > Size then
begin
// break;
// continue with random
C := Random(256) - C mod 256;
end else
begin
Info.Read(InfoByte, SizeOf(InfoByte));
C := InfoByte - C mod 256;
end;
if I + J = 0 then
if S + C > (Cell * Cell - 1) * 255 * 3 then
C := C - 256;
if I + J <> 0 then
if S + C > (Cell * Cell) * 255 * 3 then
C := C - 256;
if S + C < 0 then
C := C + 256;
end else
begin
C := Bsize[N] - C mod 256;
if I + J = 0 then
if S + C > (Cell * Cell - 1) * 255 * 3 then
C := C - 256;
if I + J <> 0 then
if S + C > (Cell * Cell) * 255 * 3 then
C := C - 256;
if S + C < 0 then
C := C + 256;
end;
repeat
for K := I * Cell to (I + 1) * Cell - 1 do
for L := J * Cell to (J + 1) * Cell - 1 do
if K + L <> 0 then
SetPixel(@XP[K, L], C);
until C = 0;
for K := I * Cell to (I + 1) * Cell - 1 do
for L := J * Cell to (J + 1) * Cell - 1 do
if K + L <> 0 then
begin
Inc(C, XP[K, L].R);
Inc(C, XP[K, L].G);
Inc(C, XP[K, L].B);
end;
end;
Result := True;
end;
function ExtractInfoFromBitmap(Dest: TStream; Bitmap: TBitmap): Boolean;
var
I, J, C, K, L, N, Cell: Integer;
Size: Int64;
XP: array of PARGB;
Bsize: array [1 .. 5] of Byte;
InfoByte : Byte;
begin
Size := 0;
Result := False;
Bitmap.PixelFormat := pf24bit;
SetLength(XP, Bitmap.Height);
for I := 0 to Bitmap.Height - 1 do
XP[I] := Bitmap.ScanLine[I];
N := 0;
Bsize[1] := (XP[0, 0].R + XP[0, 0].G + XP[0, 0].B) mod 24;
Cell := Bsize[1];
Cell := Max(Cell, 0);
Cell := Min(Cell, 24);
if Cell = 0 then
Exit(False);
for I := 0 to (Bitmap.Height - 1) div Cell - 1 do
for J := 0 to (Bitmap.Width - 1) div Cell - 1 do
begin
C := 0;
Inc(N);
for K := I * Cell to (I + 1) * Cell - 1 do
for L := J * Cell to (J + 1) * Cell - 1 do
if K + L <> 0 then
begin
if (K > (Bitmap.Height - 1)) or (L > (Bitmap.Width - 1)) then
begin
Bsize[1] := Bsize[1] + 1;
end;
C := C + XP[K, L].R;
C := C + XP[K, L].G;
C := C + XP[K, L].B;
end;
if I * ((Bitmap.Height - 1) div Cell - 1) + J > 4 then
begin
if N > Size then
begin
Result := True;
Exit;
end;
InfoByte := C and $FF;
Dest.Write(InfoByte, SizeOf(InfoByte));
end else
Bsize[N] := C mod 256;
if I * ((Bitmap.Height - 1) div Cell - 1) + J = 4 then
begin
Size := Bsize[2] + Bsize[3] * 256 + Bsize[4] * 256 * 256 + Bsize[5] * 256 * 256 * 256;
if (Size <= 0) or (Size > MaxSizeInfoInGraphic(Bitmap, 2)) then
begin
Result := False;
Exit;
end;
N := 0;
end;
end;
end;
function MaxSizeInfoInGraphic(Graphic: TGraphic; Cell: Integer): Integer;
begin
Result := ((Graphic.Height - 1) div Cell) * ((Graphic.Width - 1) div Cell) - SizeOf(StenographyHeader);
Result := Max(0, Result);
end;
procedure SaveFileToCryptedStream(FileName: string; Password: string; Dest: TStream; HeaderInTheEnd: Boolean);
var
FS: TFileStream;
I: Integer;
Header: StenographyHeader;
MS: TMemoryStream;
Seed: Binary;
Chiper: TDECCipherClass;
begin
try
FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
except
Exit;
end;
try
MS := TMemoryStream.Create;
try
MS.CopyFrom(FS, FS.Size);
//creating header
FillChar(Header, SizeOf(Header), 0);
Header.ID := StenoHeaderId;
Header.Version := 1;
FileName := ExtractFileName(FileName);
for I := 0 to SizeOf(Header.FileName) div SizeOf(Header.FileName[0]) - 1 do
Header.FileName[I] := #0;
for I := 0 to Min(SizeOf(Header.FileName) div SizeOf(Header.FileName[0]) - 1, Length(FileName) - 1) do
Header.FileName[I] := FileName[I + 1];
CalcBufferCRC32(MS.Memory^, MS.Size, Header.DataCRC);
Header.FileSize := Integer(MS.Size);
Header.IsCrypted := Length(Password) > 0;
if not Header.IsCrypted then
Header.PassCRC := 0
else
CalcStringCRC32(Password, Header.PassCRC);
Chiper := ValidCipher(nil);
Header.Chiper := Chiper.Identity;
Seed := RandomBinary(16);
Header.Seed := ConvertSeed(Seed);
if not HeaderInTheEnd then
Dest.Write(Header, SizeOf(Header));
//Saving data
MS.Seek(0, soFromBeginning);
if not Header.IsCrypted then
Dest.CopyFrom(MS, MS.Size)
else
begin
StrongCryptInit;
CryptStreamV2(MS, Dest, Password, Seed);
end;
if HeaderInTheEnd then
Dest.Write(Header, SizeOf(Header));
finally
F(MS);
end;
finally
F(FS);
end;
end;
function GetMaxPixelsInSquare(FileName: string; Graphic: TGraphic): Integer;
var
I, FileSize: Integer;
begin
FileSize := GetFileSizeByName(FileName) + 255;
Result := -1;
for I := 23 downto 2 do
begin
if MaxSizeInfoInGraphic(Graphic, I) >= FileSize then
begin
Result := I;
Break;
end;
end;
if Result < 2 then
Result := -1;
end;
function CreateJPEGSteno(DataFileName, DestFileName: string; SourceJpegImage: string; Password: string): Boolean;
var
SS: TFileStream;
begin
SS := TFileStream.Create(SourceJpegImage, fmOpenRead or fmShareDenyNone);
try
Result := CreateJPEGStenoEx(DataFileName, DestFileName, SS, Password);
finally
F(SS);
end;
end;
function CreateJPEGStenoEx(DataFileName, DestFileName: string; SourceJpegImage: TStream; Password: string): Boolean;
var
DS: TFileStream;
begin
DS := TFileStream.Create(DestFileName, fmCreate);
try
DS.CopyFrom(SourceJpegImage, SourceJpegImage.Size);
SaveFileToCryptedStream(DataFileName, Password, DS, True);
Result := True;
finally
F(DS);
end;
end;
function IsValidJPEGSteno(FileName: string): Boolean;
var
FS: TFileStream;
Header: StenographyHeader;
begin
Result := False;
FS := TFileStream.Create(FileName, fmOpenRead, fmShareDenyWrite);
try
if FS.Size > SizeOf(Header) then
begin
FS.Seek(SizeOf(Header), soFromEnd);
FS.Read(Header, SizeOf(Header));
Result := Header.ID = StenoHeaderId;
end;
finally
F(FS);
end;
end;
function ExtractJPEGSteno(MS, Dest: TStream; out Header: StenographyHeader): Boolean;
begin
Result := False;
if MS.Size > SizeOf(Header) then
begin
MS.Seek(-SizeOf(Header), soFromEnd);
MS.Read(Header, SizeOf(Header));
if Header.ID = StenoHeaderId then
begin
//valid jpeg steno
MS.Seek(-(SizeOf(Header) + Header.FileSize), soFromEnd);
Dest.CopyFrom(MS, Header.FileSize);
Result := True;
end;
end;
end;
end.
|
unit htInput;
interface
uses
SysUtils, Classes, Controls, Graphics,
LrGraphics, LrTextPainter,
htControls, htMarkup;
type
ThtInput = class(ThtGraphicControl)
private
FTextPainter: TLrTextPainter;
FPassword: Boolean;
FValue: string;
protected
function GetHAlign: TLrHAlign;
function GetValueText: string;
function GetWordWrap: Boolean;
procedure BuildStyle; override;
procedure Generate(const inContainer: string;
inMarkup: ThtMarkup); override;
procedure PerformAutoSize; override;
procedure SetHAlign(const Value: TLrHAlign);
procedure SetPassword(const Value: Boolean);
procedure SetValue(const Value: string);
procedure SetWordWrap(const Value: Boolean);
procedure StyleControl; override;
procedure StylePaint; override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
property TextPainter: TLrTextPainter read FTextPainter;
property ValueText: string read GetValueText;
published
property Align;
property AutoSize;
property HAlign: TLrHAlign read GetHAlign write SetHAlign;
property Value: string read FValue write SetValue;
property Outline;
property Password: Boolean read FPassword write SetPassword;
property Style;
property WordWrap: Boolean read GetWordWrap write SetWordWrap;
end;
implementation
uses
htUtils, htPaint, htStyle, htStylePainter;
{ ThtInput }
constructor ThtInput.Create(inOwner: TComponent);
begin
inherited;
FTextPainter := TLrTextPainter.Create;
TextPainter.Canvas := Canvas;
TextPainter.Transparent := true;
//TextPainter.OnChange := TextPainterChange;
end;
destructor ThtInput.Destroy;
begin
TextPainter.Free;
inherited;
end;
function ThtInput.GetHAlign: TLrHAlign;
begin
Result := TextPainter.HAlign;
end;
function ThtInput.GetWordWrap: Boolean;
begin
Result := TextPainter.WordWrap;
end;
procedure ThtInput.SetHAlign(const Value: TLrHAlign);
begin
TextPainter.HAlign := Value;
Invalidate;
end;
procedure ThtInput.SetWordWrap(const Value: Boolean);
begin
TextPainter.WordWrap := Value;
Invalidate;
AdjustSize;
end;
procedure ThtInput.SetValue(const Value: string);
begin
FValue := Value;
Invalidate;
AdjustSize;
end;
function ThtInput.GetValueText: string;
begin
if Password then
Result := StringOfChar('*', Length(Value))
else
Result := Value;
end;
procedure ThtInput.PerformAutoSize;
begin
SetBounds(Left, Top,
TextPainter.Width(ValueText) + Style.GetBoxWidthMargin,
TextPainter.Height(ValueText, ClientRect) + Style.GetBoxHeightMargin);
end;
procedure ThtInput.BuildStyle;
begin
inherited;
with CtrlStyle do
begin
if not Border.BorderVisible then
begin
//Border.BorderStyle := bsInset;
Border.BorderWidth := '1';
Border.BorderStyle := bsSolidBorder;
Border.BorderColor := $B99D7F;
end;
if not Padding.HasPadding then
Padding.Padding := 2;
if not htVisibleColor(Color) then
Color := clWhite;
end;
end;
procedure ThtInput.StyleControl;
begin
inherited;
end;
procedure ThtInput.StylePaint;
begin
StylePainter.PaintBackground;
StylePainter.PaintBorders;
with BoxRect do
TextPainter.PaintText(ValueText, Rect(Left + 2, Top, Right, Bottom));
if Outline then
htPaintOutline(Canvas, ClientRect);
end;
procedure ThtInput.SetPassword(const Value: Boolean);
begin
FPassword := Value;
end;
procedure ThtInput.Generate(const inContainer: string;
inMarkup: ThtMarkup);
var
n, s, t: string;
begin
n := Name;
s := {Ctrl}Style.InlineAttribute;
if (s <> '') then
inMarkup.Styles.Add(Format('#%s { %s }', [ n, s ]));
if Password then
t := 'password'
else
t := 'text';
inMarkup.Add(
Format('<input id="%s" name="%s" type="%s" value="%s" %s/>',
[ n, n, t, Value, ExtraAttributes ]));
//inMarkup.Add(Caption);
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, 2004.09.14
//------------------------------------------------------------------------------
unit DGL_Byte;
interface
uses
SysUtils;
{$I DGLCfg.inc_h}
type
_ValueType = Byte;
{$define _DGL_NotHashFunction}
const
_NULL_Value:Byte=0;
{$I DGL.inc_h}
type
TByteAlgorithms = _TAlgorithms;
IByteIterator = _IIterator;
IByteContainer = _IContainer;
IByteSerialContainer = _ISerialContainer;
IByteVector = _IVector;
IByteList = _IList;
IByteDeque = _IDeque;
IByteStack = _IStack;
IByteQueue = _IQueue;
IBytePriorityQueue = _IPriorityQueue;
IByteSet = _ISet;
IByteMultiSet = _IMultiSet;
TByteVector = _TVector;
TByteDeque = _TDeque;
TByteList = _TList;
IByteVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:)
IByteDequeIterator = _IDequeIterator; //速度比_IIterator稍快一点:)
IByteListIterator = _IListIterator; //速度比_IIterator稍快一点:)
TByteStack = _TStack;
TByteQueue = _TQueue;
TBytePriorityQueue = _TPriorityQueue;
//
IByteMapIterator = _IMapIterator;
IByteMap = _IMap;
IByteMultiMap = _IMultiMap;
TByteSet = _TSet;
TByteMultiSet = _TMultiSet;
TByteMap = _TMap;
TByteMultiMap = _TMultiMap;
TByteHashSet = _THashSet;
TByteHashMultiSet = _THashMultiSet;
TByteHashMap = _THashMap;
TByteHashMultiMap = _THashMultiMap;
implementation
{$I DGL.inc_pas}
end.
|
unit misc_utils;
{$MODE Delphi}
interface
uses Classes, SysUtils, GlobalVars, Forms, U_msgForm, StdCtrls;
{Miscellaneous help routines}
Const
CloseEnough=10e-5;
Type
TMsgType=(mt_info,mt_warning,mt_error); {Message Types for PanMessage() }
TIntList=class(TList)
Function GetInt(n:Integer):Integer;
Procedure SetInt(n:integer;I:Integer);
Function Add(i:integer):integer;
Procedure Insert(n:integer;i:integer);
Function IndexOf(i:integer):integer;
Property Ints[n:integer]:Integer read GetInt write SetInt; default;
end;
TDoubleList=class(TList)
Function GetD(n:Integer):Double;
Procedure SetD(n:integer;v:double);
Function Add(v:double):integer;
Property Ints[n:integer]:double read GetD write SetD; default;
Destructor Destroy;override;
end;
TSingleList=class(TList)
Function GetV(n:Integer):Single;
Procedure SetV(n:integer;v:Single);
Function Add(v:Single):integer;
Property Items[n:integer]:Single read GetV write SetV; default;
end;
TObjList=class(TList)
Procedure AddObject(obj:TObject);
Function FindObject(obj:TObject):integer;
Procedure DeleteAndFree(obj:TObject);
Destructor FreeAll;
Function GetObj(n:integer):TObject;
Procedure SetObj(n:integer;obj:TObject);
Property Objs[n:integer]:TObject read GetObj write SetObj; default;
end;
Function MsgBox(Txt, Caption:String;flags:Integer):Integer;
Function GetWord(const s:string;p:integer;var w:string):integer;
Function GetWordN(const s:String;n:integer):String;
Function PGetWord(ps:Pchar;pw:Pchar):Pchar; {Same thing, but for PChar strings}
Function StrToDouble(const s:String):Double;
Function StrToLongInt(const s:String):Longint;
Function HexToDword(const s:String):Longint;
Function StrToDword(const s:String):Longint;
Function DwordToStr(d:Longint):String;
Function PScanf(ps:pchar;const format:String;const Vals:array of pointer):boolean;
Function SScanf(const s:string;const format:String;const Vals:array of pointer):boolean;
{Lightweight version of Format(). formats floats differently -
accepts %f and %.#f and puts max of fractional # digits in the string}
Function SPrintf(const format:string;const vals:array of const):string;
Procedure PanMessage(mt:TMsgType; const msg:String);
Procedure PanMessageFmt(mt:TMsgType; const fmt:String;const v:array of const);
Function Real_Min(a,b:Double):Double;
Function Real_Max(a,b:Double):Double;
Function JKRound(d:Double):Double; {Rounds to 6 decimal points}
Function UVRound(d:single):single; {Round to 2 decimal digits}
Function DoubleToStr(d:double):String;
{handles the number -2147483648 ($80000000) properly.
for some reason, StrToInt gets confused by it}
Function ValInt(const s:String;var i:Integer):Boolean;
Function ValHex(const s:String;var h:LongInt):Boolean;
Function ValDword(const s:String; var d:LongInt):Boolean;
Function ValDouble(const s:String; var d:Double):Boolean;
Function ValSingle(const s:String; var f:single):Boolean;
Function ValVector(const s:string; var x,y,z:double):boolean;
Function PadRight(const s:string;tolen:integer):String;
Procedure RemoveComment(var s:String);
Function GetMSecs:Longint;
Function SubMSecs(startms,endms:longint):longint;
Function StrMSecs(ms:longint):string;
Procedure SizeFromToFit(f:TForm);
Function ScanForSpace(const s:string;p:integer):integer; {if p is negative - scan backwards}
Function ScanForNonSpace(const s:string;p:integer):integer; {if p is negative - scan backwards}
Function IsClose(d1,d2:double):boolean;
Function FindJedDataFile(const Name:string):String;
Function SetFlags(val,flags:integer):integer;
Function ClearFlags(val,flags:integer):integer;
Procedure SetEditText(ed:TEdit;const s:string);// Doesn't invoke OnChange
implementation
uses Windows, Jed_Main;
Function TIntList.GetInt(n:Integer):Integer;
begin
Result:=Integer(Items[n]);
end;
Procedure TIntList.SetInt(n:integer;I:Integer);
begin
Items[n]:=Pointer(i);
end;
Procedure TIntList.Insert(n:integer;i:integer);
begin
Inherited Insert(n,Pointer(i));
end;
Function TIntList.Add(i:integer):integer;
begin
Result:=Inherited Add(Pointer(i));
end;
Function TIntList.IndexOf(i:integer):integer;
begin
Result:=inherited IndexOf(Pointer(i));
end;
Function TSingleList.GetV(n:Integer):Single;
begin
if (n<0) or (n>=Count) then Result:=0 else
Result:=Single(List[n]);
end;
Procedure TSingleList.SetV(n:integer;v:Single);
begin
List[n]:=Pointer(v);
end;
Function TSingleList.Add(v:Single):integer;
begin
Result:=Inherited Add(Pointer(v));
end;
Function TDoubleList.GetD(n:Integer):Double;
begin
Result:=Double(Items[n]^);
end;
Procedure TDoubleList.SetD(n:integer;v:double);
begin
Double(Items[n]^):=v;
end;
Function TDoubleList.Add(v:double):integer;
var pv:pointer;
begin
GetMem(pv,sizeof(double));
Double(pv^):=v;
Inherited Add(pv);
end;
Destructor TDoubleList.Destroy;
var i:integer;
begin
for i:=0 to count-1 do
FreeMem(Items[i],sizeof(double));
inherited Destroy;
end;
Procedure TObjList.AddObject(obj:TObject);
begin
Add(obj);
end;
Function TObjList.FindObject(obj:TObject):integer;
begin
Result:=IndexOf(obj);
end;
Procedure TObjList.DeleteAndFree(obj:TObject);
var i:integer;
begin
i:=FindObject(obj);
if i<>-1 then Delete(i);
obj.destroy;
end;
Destructor TObjList.FreeAll;
var i:integer;
begin
for i:=0 to COunt-1 do Objs[i].Destroy;
Clear;
Destroy;
end;
Function TObjList.GetObj(n:integer):TObject;
begin
Result:=TObject(Items[n]);
end;
Procedure TObjList.SetObj(n:integer;obj:TObject);
begin
Items[n]:=obj;
end;
Function PadRight(const s:string;tolen:integer):String;
var i,len:integer;
begin
Result:=s;
len:=length(Result);
if len<tolen then SetLength(Result,toLen);
For i:=len+1 to tolen do Result[i]:=' ';
end;
Function ScanForSpace(const s:string;p:integer):integer; {if p is negative - scan backwards}
begin
if p<0 then {backwards}
begin
p:=-p;
while (p>1) and not (s[p] in [' ',#9]) do dec(p);
Result:=p;
end else
begin
While (p<=length(s)) and not (s[p] in [' ',#9]) do inc(p);
Result:=p;
end;
end;
Function ScanForNonSpace(const s:string;p:integer):integer; {if p is negative - scan backwards}
begin
if p<0 then {backwards}
begin
p:=-p;
while (p>1) and (s[p] in [' ',#9]) do dec(p);
Result:=p;
end else
begin
While (p<=length(s)) and (s[p] in [' ',#9]) do inc(p);
Result:=p;
end;
end;
Function GetWordN(const s:String;n:integer):String;
var i,p:Integer;
begin
p:=1;
for i:=1 to n do
begin
p:=ScanForNonSpace(s,p);
if i<>n then p:=ScanForSpace(s,p);
end;
i:=ScanForSpace(s,p);
Result:=UpperCase(Copy(s,p,i-p));
end;
Procedure RemoveComment(var s:String);
var p:integer;
begin
p:=Pos('#',s);
if p<>0 then SetLength(s,p-1);
end;
Function Real_Min(a,b:Double):Double;
begin
if a>b then result:=b else result:=a;
end;
Function Real_Max(a,b:Double):Double;
begin
if a>b then result:=a else result:=b;
end;
Function JKRound(d:Double):Double;
begin
Result:=Round(d*10000)/10000;
end;
Function UVRound(d:single):single;
begin
Result:=Round(d*1000)/1000;
end;
Function StrToDouble(const s:String):Double;
var a:Integer;
begin
if s='' then begin result:=0; exit; end;
Val(s,Result,a);
if a<>0 then raise EConvertError.Create('Invalid number: '+s);
end;
Function StrToLongInt(const s:String):Longint;
var a:Integer;
begin
Val(s,Result,a);
end;
Function HexToDword(const s:String):Longint;
var a:Integer;
begin
if s='' then begin result:=0; exit; end;
Val('$'+s,Result,a);
end;
Function ValInt(const s:String;var i:Integer):Boolean;
var a:Integer;
begin
Result:=true;
if s='' then begin i:=0; exit; end;
Val(s,i,a);
Result:=a=0;
end;
Function ValHex(const s:String;var h:LongInt):Boolean;
var a:Integer;s1:string;
begin
Result:=true;
if s='' then begin h:=0; exit; end;
if (length(s)>2) and (s[2] in ['X','x']) then
begin
s1:='$'+Copy(s,3,length(s)-2);
Val(s1,h,a);
Result:=a=0;
exit;
end;
Val('$'+s,h,a);
Result:=a=0;
end;
Function ValDword(const s:String; var d:LongInt):Boolean;
var a:Integer;
begin
Result:=true;
if s='' then begin d:=0; exit; end;
Val(s,d,a);
if a=10 then
if s[10] in ['0'..'9'] then
begin
d:=d*10+(ord(s[10])-ord('0'));
a:=0;
end;
Result:=not ((a<>0) and (s[a]<>#0));
end;
Function ValSingle(const s:String; var f:single):Boolean;
var a:Integer;
begin
Result:=true;
if s='' then begin f:=0; exit; end;
Val(s,f,a);
Result:=a=0;
end;
Function ValDouble(const s:String; var d:Double):Boolean;
var a:Integer;
begin
Result:=true;
if s='' then begin d:=0; exit; end;
Val(s,d,a);
Result:=a=0;
end;
Function ValVector(const s:string; var x,y,z:double):boolean;
var w:string;
p,a:integer;
begin
p:=getword(s,1,w);
val(w,x,a);
result:=a=0;
p:=getword(s,p,w);
val(w,y,a);
result:=result and (a=0);
p:=getword(s,p,w);
val(w,z,a);
result:=result and (a=0);
end;
Function StrToDword(const s:String):Longint;
var a:Integer;
begin
if s='' then begin result:=0; exit; end;
Val(s,Result,a);
if a=10 then
if s[10] in ['0'..'9'] then
begin
Result:=Result*10+(ord(s[10])-ord('0'));
a:=0;
end;
if (a<>0) and (s[a]<>#0)
then Raise EConvertError.Create(s+' is not a valid number');
end;
Function DwordToStr(d:Longint):String;
var c:Char;
a:Integer;
begin
if d>=0 then Str(d,Result)
else {32th bit set}
begin
asm {Divides D by 10 treating it as unsigned integer}
Mov eax,d
xor edx,edx
mov ecx,10
Div ecx
add dl,'0'
mov c,dl
mov d,eax
end;
Str(d,Result); Result:=Result+c;
end
end;
Function MsgBox(Txt, Caption:String;flags:Integer):Integer;
begin
Result:=Application.MessageBox(Pchar(Txt),Pchar(Caption),flags);
end;
Function GetWord(const s:string;p:integer;var w:string):integer;
var b,e:integer;
begin
if s='' then begin w:=''; result:=1; exit; end;
b:=p;
While (s[b] in [' ',#9]) and (b<=length(s)) do inc(b);
e:=b;
While (not (s[e] in [' ',#9])) and (e<=length(s)) do inc(e);
w:=Copy(s,b,e-b);
GetWord:=e;
end;
Function PGetWord(ps:Pchar;pw:Pchar):Pchar;
var pb,pe:PChar;
begin
if ps^=#0 then begin pw^:=#0; result:=ps; exit; end;
pb:=ps;
while pb^ in [' ',#9] do inc(pb);
pe:=pb;
while not (pe^ in [' ',#9,#0]) do inc(pe);
StrLCopy(pw,pb,pe-pb);
Result:=pe;
end;
{Accepted formatters - %s %d %x %.1f - %.6f}
Function SPrintf(const format:string;const vals:array of const):string;
var pres,pf,pe,pp,pa:pchar;
cv,i,ndig:integer;
pv:^TVarRec;
buf:array[0..4095] of char;
begin
result:='';
FillChar(buf,4096,0);
pf:=@format[1];
pres:=@buf;
cv:=0;
pa:=@buf;
repeat
pp:=StrScan(pf,'%');
if pp=nil then pe:=strEnd(pf) else pe:=pp;
StrLCopy(pres,pf,pe-pf);
pres:=StrEnd(pres);
if pp=nil then break;
inc(pp);
if cv>high(vals) then raise EconvertError.Create('Not enough parameters');
pv:=@vals[cv];
case pp^ of
's','S': begin
if pv^.vtype<>vtAnsiString then raise EconvertError.Create('Invalid parameter type');
if pv^.vAnsiString<>nil then pres:=StrECopy(pres,pchar(pv^.vAnsiString));
end;
'd','D': begin
if pv^.vtype<>vtInteger then raise EconvertError.Create('Invalid parameter type');
pres:=StrECopy(pres,pchar(IntToStr(pv^.vInteger)));
end;
'x','X': begin
if pv^.vtype<>vtInteger then raise EconvertError.Create('Invalid parameter type');
pres:=StrECopy(pres,pchar(IntToHex(pv^.vInteger,1)));
end;
'f','F','.':
begin
if pp^='.' then begin inc(pp); ndig:=ord(pp^)-ord('0'); inc(pp); end
else ndig:=2;
if pv^.vtype<>vtExtended then raise EconvertError.Create('Invalid parameter type');
case ndig of
1: i:=FloatToTextFmt(pres,pv.vExtended^,fvExtended,'.#');
2: i:=FloatToTextFmt(pres,pv.vExtended^,fvExtended,'.##');
3: i:=FloatToTextFmt(pres,pv.vExtended^,fvExtended,'.###');
4: i:=FloatToTextFmt(pres,pv.vExtended^,fvExtended,'.####');
5: i:=FloatToTextFmt(pres,pv.vExtended^,fvExtended,'.#####');
6: i:=FloatToTextFmt(pres,pv.vExtended^,fvExtended,'.######');
else i:=FloatToTextFmt(pres,pv.vExtended^,fvExtended,'.##');
end;
if i=0 then begin pres^:='0'; inc(pres); end else
inc(pres,i);
end;
else if i=0 then;
end;
if pp^<>#0 then Inc(pp);
pf:=pp;
pres:=StrEnd(pres);
inc(cv);
until false;
result:=buf;
if pa=nil then;
end;
Function PScanf(ps:pchar;const format:String;const Vals:array of pointer):boolean;
var pp, {position of % in format string}
pb, {beginning of the prefix}
pv, {position of the value}
pe, {end of the prefix}
pf:Pchar;
tmp:array[0..99] of char;
ptmp:Pchar;
Len:Integer; {Lenth of prefix string}
a, {Dummy variable for Val()}
nval:Integer; {Index in vals[] array}
lastdigit,dw:Dword;
c:Char;
begin
{$r-}
Result:=true;
nval:=0;
pf:=PChar(format);
Repeat
if ps^=#0 then break;
pp:=StrScan(pf,'%'); if pp=nil then break;
pb:=pf;
while (pb^ in [' ',#9]) and (pb<pp) do inc(pb);
if pp=pb then
begin
Len:=0; pv:=ps;
end
else
begin
pe:=pp-1;
while (pe^ in [' ',#9]) and (pe>pb) do dec(pe);
len:=pe-pb+1;
StrLCopy(tmp,pb,len);
pv:=StrPos(ps,tmp);
if pv=nil then begin pf:=pp+1; if pf^<>#0 then inc(pf); inc(nval); continue; end;
pv:=pv+len;
end;
ptmp:=@tmp[1];
ps:=PGetWord(pv,ptmp);
inc(pp); a:=0;
case pp^ of {format specifier}
'd','D': Val(Ptmp,Integer(Vals[nval]^),a);
'u','U': begin
Val(PTmp,dw,a);
if a<>0 then
begin
c:=(Ptmp+a-1)^;
if c in ['0'..'9'] then
begin
lastdigit:=Ord(c)-Ord('0');
dw:=dw*10+lastdigit;
a:=0;
end;
end;
Dword(Vals[nval]^):=dw;
end;
'f','F': Val(Ptmp,Double(Vals[nval]^),a);
'l','L': Val(Ptmp,Single(Vals[nval]^),a);
'b','B': Val(Ptmp,byte(Vals[nval]^),a);
'c','C': Char(Vals[nval]^):=Ptmp^;
's','S': String(Vals[nval]^):=ptmp;
'x','X': begin
if tmp[2] in ['x','X'] then
begin
ptmp:=@tmp[2];
tmp[2]:='$';
end
else
begin
ptmp:=@tmp;
tmp[0]:='$';
end;
Val(Ptmp,Integer(Vals[nval]^),a);
end;
else a:=1;
end;
if a<>0 then result:=false;
pf:=pp; if pf^<>#0 then inc(pf);
inc(nval);
until false;
{$r+}
end;
Function SScanf(const s:string;const format:String;const Vals:array of pointer):boolean;
begin
Result:=pScanf(PChar(s),format,vals);
end;
Procedure PanMessageFmt(mt:TMsgType; const fmt:String;const v:array of const);
begin
PanMessage(mt,Format(fmt,v));
end;
Procedure PanMessage(mt:TMsgType; const msg:String);
begin
case mt of
mt_info: begin
if sm_ShowInfo then MsgForm.AddMessage('Info: '+msg);
JedMain.Pmsg.Caption:=msg;
JedMain.Pmsg.Font.Color:=clBlack;
end;
mt_warning: begin
if sm_ShowWarnings then MsgForm.AddMessage('Warning: '+msg);
JedMain.Pmsg.Caption:=msg;
JedMain.Pmsg.Font.Color:=clRed;
MsgForm.Show;
end;
mt_error: begin
MsgBox(Msg,'Error',mb_OK);
MsgForm.AddMessage('Error: '+msg);
end;
end;
end;
Function StrToDoubleDef(const s:String;def:Double):Double;
var a:Integer;
begin
Val(s,result,a);
if a<>0 then Result:=def;
end;
{Procedure GetFormPos(f:TForm;var wpos:TWinPos);
begin
With WPos,f do
begin
Wwidth:=width;
Wheight:=height;
Wtop:=top;
Wleft:=left;
end;
end;
Procedure SetFormPos(f:TForm;const wpos:TWinPos);
begin
if WPos.WWidth=0 then exit;
With WPos do
F.SetBounds(Wleft,Wtop,Wwidth,Wheight);
end;}
Procedure SizeFromToFit(f:TForm);
var xmin,xmax,ymin,ymax:integer;
begin
end;
Function IsClose(d1,d2:double):boolean;
begin
result:=Abs(d2-d1)<CloseEnough;
end;
Const
MsPerDay=24*60*60*1000;
MsPerHour=60*60*1000;
MsPerMin=60*1000;
Function GetMSecs:Longint;
var
h,m,s,ms:word;
begin
DecodeTime(Now,h,m,s,ms);
Result:=h*MsPerHour+m*msPerMin+s*1000+ms;
end;
Function SubMSecs(startms,endms:longint):longint;
begin
if endms>=startms then Result:=endms-startms
else Result:=endms+MsPerDay-startms;
end;
Function StrMSecs(ms:longint):string;
Var rem:longint;
begin
Result:='';
rem:=ms mod MsPerHour;
if ms>rem then Result:=Format('%d hours ',[ms div MsPerHour]);
ms:=rem;
rem:=ms mod MsPerMin;
if ms>rem then Result:=Format('%s%d mins ',[Result,ms div MsPerMin]);
ms:=rem;
rem:=ms mod 1000;
if ms>rem then Result:=Format('%s%d secs ',[Result,ms div 1000]);
Result:=Format('%s%d ms',[Result,rem]);
end;
Function DoubleToStr(d:double):String;
var i:integer;
begin
Result:=FormatFloat('.######',d);
if result='' then result:='0';
{Format('%.6f',[d]);
For i:=length(Result) downto 1 do
begin
if Result[i]='0' then SetLength(Result,Length(Result)-1)
else if Result[i]='.' then begin SetLength(Result,Length(Result)-1); break; end
else break;
end;}
end;
Function FindJedDataFile(const Name:string):String;
begin
if ProjectDir<>'' then
begin
Result:=ProjectDir+Name;
if FileExists(Result) then exit;
end;
Result:=BaseDir+'JedDATA\'+Name;
end;
Function SetFlags(val,flags:integer):integer;
begin
Result:=val or flags;
end;
Function ClearFlags(val,flags:integer):integer;
begin
Result:=val and (not flags);
end;
Procedure SetEditText(ed:TEdit;const s:string);// Doesn't invoke OnChange
var a:TNotifyEvent;
begin
a:=ed.OnChange;
ed.OnChange:=nil;
ed.Text:=s;
ed.OnChange:=a;
end;
Initialization
end.
|
unit Cache.Root;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, Math,
System.Generics.Collections;
//------------------------------------------------------------------------------
const
//------------------------------------------------------------------------------
//! размер кэша при неуказании его
//------------------------------------------------------------------------------
CCacheSizeMax = 10000;
//------------------------------------------------------------------------------
type
//------------------------------------------------------------------------------
//! результат функции AddOrReplace
//------------------------------------------------------------------------------
TAORResult = (arAdded, arReplaced);
//------------------------------------------------------------------------------
//! forward
//------------------------------------------------------------------------------
TCache = class;
//------------------------------------------------------------------------------
//! дополнительный ключ
//------------------------------------------------------------------------------
TConnKey = class(TDictionary<string, string>)
public
constructor Create(
const AKeys: array of string
);
end;
TConnKeyPair = TPair<string, string>;
//------------------------------------------------------------------------------
//! корневой абстрактный класс данных
//------------------------------------------------------------------------------
TCacheDataObjectAbstract = class abstract
protected
function GetDTMark(): TDateTime; virtual; abstract;
public
function Clone(): TCacheDataObjectAbstract; virtual; abstract;
property DTMark: TDateTime read GetDTMark;
end;
TCacheDataObjectAbstractArray = TArray<TCacheDataObjectAbstract>;
//------------------------------------------------------------------------------
//! корневой абстрактный класс адаптера
//------------------------------------------------------------------------------
TCacheDataAdapterAbstract = class abstract
public
//! обновить все изменённые объекты
procedure Flush(
const ACache: TCache
); virtual; abstract;
//! добавление объекта
procedure Add(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
); virtual; abstract;
//! изменение объекта
procedure Change(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
); virtual; abstract;
//! удаление объекта
procedure Delete(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
); virtual; abstract;
//! получить ближайшее по времени время данных ДО заданного времени
(*!
return: 0 (30.12.1899) - если объект не существует
*)
function GetDTBefore(
const ACache: TCache;
const ADT: TDateTime
): TDateTime; virtual; abstract;
//! получить ближайшее по времени время данных ПОСЛЕ заданного времени
(*!
return: 0 (30.12.1899) - если объект не существует
*)
function GetDTAfter(
const ACache: TCache;
const ADT: TDateTime
): TDateTime; virtual; abstract;
//! подгрузить данные из источника
procedure LoadRange(
const ACache: TCache;
const AFrom: TDateTime;
const ATo: TDateTime;
var RObjects: TCacheDataObjectAbstractArray
); virtual; abstract;
end;
//------------------------------------------------------------------------------
//! кэш
//------------------------------------------------------------------------------
TCache = class
protected
FData: TCacheDataObjectAbstractArray;
FSize: Integer;
FSizeMax: Integer;
FAdapter: TCacheDataAdapterAbstract;
FWriteback: Boolean;
FLoadDelta: Double;
FKey: TConnKey;
FLoadedFrom: TDateTime;
FLoadedTo: TDateTime;
FMinAdapterDT: TDateTime;
FMaxAdapterDT: TDateTime;
FChanges: TDictionary<TDateTime, Integer>;
private
//! увеличить объём массива хранения
procedure Grow();
//! получить индекс элемента с запрошенным ИЛИ минимально большим временем
//! *** может вернуть индекс больше последнего занятого (= FSize) ***
function IndexOfEqualOrAbove(
const ADT: TDateTime
): Integer;
//! получить индекс элемента с запрошенным ИЛИ минимально меньшим временем
//! *** может вернуть индекс меньше первого занятого (= -1) ***
function IndexOfEqualOrLower(
const ADT: TDateTime
): Integer;
//! получить индекс элемента с запрошенным временем
(*!
return: -1 - если элемент не найден; иначе - индекс
*)
function IndexOf(
const ADT: TDateTime
): Integer;
//! внутренняя логика вставки нового элемента
(*!
return: True - если вставка успешна; False - в противном случае
*)
function InternalAdd(
const AObj: TCacheDataObjectAbstract
): Boolean;
//! внутренняя логика замены нового элемента
(*!
return: True - если замена успешна; False - в противном случае
*)
function InternalReplace(
const AObj: TCacheDataObjectAbstract
): Boolean;
//! внутренняя логика удаления элемента
(*!
return: ссылка на объект - если элемент был удалён; nil - если элемента не было в кэше
*)
function InternalDelete(
const ADT: TDateTime
): TCacheDataObjectAbstract;
//! проверка на нахождение даты/времени в границах загрузки из адаптера
function InLoadedRange(
const ADT: TDateTime
): Boolean;
//! дозагрузить данные из адаптера
procedure AdapterLoadRange(
const AFrom: TDateTime;
const ATo: TDateTime
);
function GetFirstDT: TDateTime;
function GetLastDT: TDateTime;
public
//!
(*
Adapter - адаптер данных (не может быть nil)
Writeback - отправлять ли изменения обратно в адаптер (если False - будет только чтение)
LoadDelta - расширение диапазона загрузки (фактически - TDateTime)
AKey - дополнительный ключ данных
*)
constructor Create(
const AAdapter: TCacheDataAdapterAbstract;
const AWriteback: Boolean;
const ALoadDelta: Double;
const ACacheSizeLimit: Integer;
const AKey: TConnKey
);
//!
destructor Destroy(); override;
//! очистить кэш
procedure Clear(); overload;
//! очистить кэш до заданного времени
procedure ClearTill(
const ATill: TDateTime
);
//! очистить кэш после заданного времени
procedure ClearFrom(
const AFrom: TDateTime
);
procedure Clear(
const AAround: TDateTime
); overload;
// //! проверить нахождение времени в границах кэша; очистить кэш, если вне границ
// procedure CheckAndClear(
// const ADT: TDateTime
// );
//! добавить или заменить объект
function AddOrReplace(
const AObj: TCacheDataObjectAbstract
): TAORResult;
//! заменить объект
(*!
return: True - объект заменён; False - объекта с таким временем нет в кэше
*)
function Replace(
const AObj: TCacheDataObjectAbstract
): Boolean;
//! добавить объект
(*!
return: True - объект добавлен; False - объект с таким временем уже есть в кэше
*)
function Add(
const AObj: TCacheDataObjectAbstract
): Boolean;
//! добавить объект; получить объект с заданным временем (переданный или из кэша)
(*!
return: объект
*)
function AddOrGet(
const AObj: TCacheDataObjectAbstract
): TCacheDataObjectAbstract;
//! сигнал о изменении объекта
procedure WasChanged(
const ADT: TDateTime
);
//!
procedure MarkChanged(
const ADT: TDateTime
);
//!
procedure Flush(
);
//! удаление объекта
function Delete(
const ADT: TDateTime
): Boolean;
//! удаление объекта, не затрагивающее БД - только из кэша
procedure DeleteNotDB(
const ADT: TDateTime
);
//! получить объект с запрошенным временем
(*!
return: nil - если объект не найден
*)
function Get(
const ADT: TDateTime
): TCacheDataObjectAbstract;
//! получить объект с максимальным временем меньше запрошенного
(*!
return: nil - если объект не найден
*)
function GetBefore(
const ADT: TDateTime;
const ACacheOnly: Boolean = False
): TCacheDataObjectAbstract;
//! получить объект с минимальным временем больше запрошенного
(*!
return: nil - если объект не найден
*)
function GetAfter(
const ADT: TDateTime;
const ACacheOnly: Boolean = False
): TCacheDataObjectAbstract;
//! количество объектов в кэше
property Count: Integer read FSize;
//! дополнительный ключ
property Key: TConnKey read FKey;
public // класс реализации for_in
type
TCacheEnumerator = class
private
FCache: TCache;
FIdx: Integer;
function GetCurrent(): TCacheDataObjectAbstract; inline;
public
constructor Create(ACache: TCache);
property Current: TCacheDataObjectAbstract read GetCurrent;
function MoveNext(): Boolean; inline;
end;
public // провайдер for_in
function GetEnumerator(): TCacheEnumerator;
function WillItBeCleaned(ADT: TDateTime): Boolean;
property FirstDT: TDateTime read GetFirstDT;
property LastDT: TDateTime read GetLastDT;
property LoadedFrom: TDateTime read FLoadedFrom;
property LoadedTo: TDateTime read FLoadedTo;
property LoadDelta: Double read FLoadDelta;
property Adapter: TCacheDataAdapterAbstract read FAdapter;
end;
//------------------------------------------------------------------------------
//! словарь кэшей с автоматическим освобождением
//------------------------------------------------------------------------------
TCacheDictionary<KeyType> = class(TDictionary<KeyType, TCache>)
private
procedure ValueEvent(
Sender: TObject;
const Item: TCache;
Action: TCollectionNotification
);
function GetCountAll: Integer;
public
property CountAll: Integer read GetCountAll;
constructor Create();
end;
//------------------------------------------------------------------------------
implementation
resourcestring
CNoAdapter = 'Отсутствует адаптер';
//------------------------------------------------------------------------------
const
//------------------------------------------------------------------------------
//! шаг увеличения буфера
//------------------------------------------------------------------------------
CCacheChunkSize = 64;
//------------------------------------------------------------------------------
// TCache
//------------------------------------------------------------------------------
constructor TCache.Create(
const AAdapter: TCacheDataAdapterAbstract;
const AWriteback: Boolean;
const ALoadDelta: Double;
const ACacheSizeLimit: Integer;
const AKey: TConnKey
);
begin
inherited Create();
//
if not Assigned(AAdapter) then
raise Exception.CreateRes(@CNoAdapter);
FLoadedFrom := Infinity;
FLoadedTo := NegInfinity;
FMinAdapterDT := NegInfinity;
FMaxAdapterDT := Infinity;
FAdapter := AAdapter;
FWriteback := AWriteback;
FLoadDelta := ALoadDelta;
FSizeMax := IfThen(ACacheSizeLimit <> 0, ACacheSizeLimit, CCacheSizeMax);
FKey := AKey;
FChanges := TDictionary<TDateTime, Integer>.Create;
end;
destructor TCache.Destroy();
begin
Clear();
FKey.Free();
FChanges.Free;
//
inherited Destroy();
end;
procedure TCache.Clear();
var
I: Integer;
//------------------------------------------------------------------------------
begin
if Assigned(FAdapter) then // проверка на случай исключения в конструкторе
FAdapter.Flush(Self);
FLoadedFrom := Infinity;
FLoadedTo := NegInfinity;
FMinAdapterDT := NegInfinity;
FMaxAdapterDT := Infinity;
for I := 0 to FSize - 1 do
begin
FData[I].Free();
end;
FSize := 0;
SetLength(FData, 0);
end;
procedure TCache.ClearTill(
const ATill: TDateTime
);
var
IdxLow: Integer;
I: Integer;
//------------------------------------------------------------------------------
begin
IdxLow := IndexOfEqualOrAbove(ATill - FLoadDelta);
if (IdxLow = 0) then
Exit;
if (IdxLow = FSize) then
begin
Clear();
Exit;
end;
if (FSize < FSizeMax) then
Exit;
FAdapter.Flush(Self);
for I := 0 to IdxLow - 1 do
begin
FData[I].Free();
end;
FSize := FSize - IdxLow;
Move(FData[IdxLow], FData[0], FSize * SizeOf(FData[0]));
FLoadedFrom := FData[0].DTMark;
end;
procedure TCache.ClearFrom(
const AFrom: TDateTime
);
var
IdxHi: Integer;
I: Integer;
//------------------------------------------------------------------------------
begin
IdxHi := IndexOfEqualOrLower(AFrom + FLoadDelta);
if (IdxHi = 0) then
Exit;
if (IdxHi < 0) then
begin
Clear();
Exit;
end;
if (FSize < FSizeMax) then
Exit;
FAdapter.Flush(Self);
for I := IdxHi + 1 to FSize - 1 do
begin
FData[I].Free();
end;
FSize := IdxHi;
FLoadedTo := FData[FSize - 1].DTMark;
end;
procedure TCache.Clear(
const AAround: TDateTime
);
begin
ClearTill(AAround);
ClearFrom(AAround);
end;
function TCache.AddOrReplace(
const AObj: TCacheDataObjectAbstract
): TAORResult;
var
ObjClone: TCacheDataObjectAbstract;
TempDT: TDateTime;
//------------------------------------------------------------------------------
begin
TempDT := AObj.DTMark;
if not InLoadedRange(TempDT) then
AdapterLoadRange(TempDT, TempDT);
ObjClone := AObj.Clone();
if InternalReplace(ObjClone) then
begin
if FWriteback then
FAdapter.Change(Self, ObjClone);
Result := arReplaced;
end
else
begin
InternalAdd(ObjClone);
if FWriteback then
FAdapter.Add(Self, ObjClone);
Result := arAdded;
end;
end;
function TCache.Replace(
const AObj: TCacheDataObjectAbstract
): Boolean;
var
ObjClone: TCacheDataObjectAbstract;
TempDT: TDateTime;
//------------------------------------------------------------------------------
begin
Result := False;
ObjClone := AObj.Clone();
try
TempDT := ObjClone.DTMark;
if not InLoadedRange(TempDT) then
AdapterLoadRange(TempDT, TempDT);
Result := InternalReplace(ObjClone);
if Result and FWriteback then
FAdapter.Change(Self, ObjClone);
finally
if not Result then
ObjClone.Free();
end;
end;
function TCache.Add(
const AObj: TCacheDataObjectAbstract
): Boolean;
var
ObjClone: TCacheDataObjectAbstract;
TempDT: TDateTime;
//------------------------------------------------------------------------------
begin
Result := False;
ObjClone := AObj.Clone();
try
TempDT := ObjClone.DTMark;
if not InLoadedRange(TempDT) then
AdapterLoadRange(TempDT, TempDT);
Result := InternalAdd(ObjClone);
if Result and FWriteback then
FAdapter.Add(Self, ObjClone);
finally
if not Result then
ObjClone.Free();
end;
end;
function TCache.AddOrGet(
const AObj: TCacheDataObjectAbstract
): TCacheDataObjectAbstract;
begin
Result := AObj;
if not Add(AObj) then
Result := Get(AObj.GetDTMark);
end;
procedure TCache.WasChanged(
const ADT: TDateTime
);
var
Poz: Integer;
//------------------------------------------------------------------------------
begin
if not FWriteback then
Exit;
if not InLoadedRange(ADT) then
AdapterLoadRange(ADT, ADT);
Poz := IndexOf(ADT);
if (Poz <> -1) then
FAdapter.Change(Self, FData[Poz]);
end;
procedure TCache.MarkChanged(const ADT: TDateTime);
begin
if not FChanges.ContainsKey(ADT) then
FChanges.Add(ADT, 0);
FChanges.Items[ADT] := FChanges.Items[ADT] + 1;
end;
procedure TCache.Flush;
var
DT: TDateTime;
begin
for DT in FChanges.Keys do
WasChanged(DT);
FChanges.Clear;
end;
function TCache.Delete(
const ADT: TDateTime
): Boolean;
var
Obj: TCacheDataObjectAbstract;
//------------------------------------------------------------------------------
begin
Result := True;
if not InLoadedRange(ADT) then
AdapterLoadRange(ADT, ADT);
Obj := InternalDelete(ADT);
if not Assigned(Obj) then
Exit(False);
try
if FWriteback then
FAdapter.Delete(Self, Obj);
finally
Obj.Free();
end;
end;
procedure TCache.DeleteNotDB(
const ADT: TDateTime
);
begin
if not InLoadedRange(ADT) then
AdapterLoadRange(ADT, ADT);
InternalDelete(ADT).Free();
end;
function TCache.Get(
const ADT: TDateTime
): TCacheDataObjectAbstract;
var
Index: Integer;
//------------------------------------------------------------------------------
begin
Result := nil;
if ADT = 0 then
Exit;
if not InLoadedRange(ADT) then
AdapterLoadRange(ADT, ADT);
Index := IndexOf(ADT);
if (Index <> -1) then
Result := FData[Index];
end;
function TCache.GetBefore(
const ADT: TDateTime;
const ACacheOnly: Boolean = False
): TCacheDataObjectAbstract;
var
TempDT: TDateTime;
//------------------------------------------------------------------------------
begin
Result := nil;
if (FSize = 0) or (ADT <= FData[0].DTMark) or (ADT > FData[FSize - 1].DTMark) then
begin
if (FSize = 0) or (ADT <= FData[0].DTMark) or IsInfinite(FMaxAdapterDT) then
begin
if (ADT <= FMinAdapterDT) then // достигли предела данных в адаптере - читать не имеет смысла
Exit;
if ACacheOnly then
Exit;
TempDT := FAdapter.GetDTBefore(Self, ADT);
if (TempDT = 0) then
begin
if (FSize <> 0) then
FMinAdapterDT := FData[0].DTMark
else
FMinAdapterDT := ADT;
Exit;
end;
AdapterLoadRange(TempDT, ADT);
Result := FData[IndexOf(TempDT)]; // не может не быть в границах (только что загрузили)
end
else
Result := FData[FSize - 1];
end
else
Result := FData[IndexOfEqualOrAbove(ADT) - 1]; // тут IndexOfEqualOrAbove не может быть равным 0 (условие в if)
end;
function TCache.GetAfter(
const ADT: TDateTime;
const ACacheOnly: Boolean = False
): TCacheDataObjectAbstract;
var
Index: Integer;
TempDT: TDateTime;
//------------------------------------------------------------------------------
begin
Result := nil;
if (FSize = 0) or (ADT < FData[0].DTMark) or (ADT >= FData[FSize - 1].DTMark) then
begin
if ACacheOnly then
Exit;
if (ADT >= FMaxAdapterDT) then // достигли предела данных в адаптере - читать не имеет смысла
Exit;
TempDT := FAdapter.GetDTAfter(Self, ADT);
if (TempDT = 0) then
begin
if (FSize <> 0) then
FMaxAdapterDT := FData[FSize - 1].DTMark
else
FMaxAdapterDT := ADT;
Exit;
end;
AdapterLoadRange(ADT, TempDT);
Result := FData[IndexOf(TempDT)]; // не может не быть в границах (только что загрузили)
end
else
begin
Index := IndexOfEqualOrAbove(ADT); // Index не может быть равен FSize (условие в if)
if (ADT = FData[Index].DTMark) then
Inc(Index);
Result := FData[Index]; // Index опять же не может быть равен FSize (условие в другом if)
end;
end;
procedure TCache.Grow();
begin
SetLength(FData, Length(FData) + CCacheChunkSize);
end;
function TCache.IndexOfEqualOrAbove(
const ADT: TDateTime
): Integer;
var
First, Last, Middle: Integer;
//------------------------------------------------------------------------------
begin
if (FSize = 0) then
Exit(0);
if (ADT > FData[FSize - 1].DTMark) then
Exit(FSize);
First := 0;
Last := FSize - 1;
while (First < Last) do
begin
Middle := ((Last - First) shr 1) + First;
if (ADT <= FData[Middle].DTMark) then
Last := Middle
else
First := Middle + 1;
end;
Result := Last;
end;
function TCache.IndexOfEqualOrLower(
const ADT: TDateTime
): Integer;
var
First, Last, Middle: Integer;
//------------------------------------------------------------------------------
begin
if (FSize = 0) then
Exit(0);
if (ADT < FData[0].DTMark) then
Exit(-1);
First := 0;
Last := FSize - 1;
while (First < Last) do
begin
Middle := ((Last - First) shr 1) + First;
if (ADT >= FData[Middle].DTMark) then
Last := Middle
else
First := Middle + 1;
end;
Result := Last;
end;
function TCache.IndexOf(
const ADT: TDateTime
): Integer;
begin
Result := IndexOfEqualOrAbove(ADT);
if (Result = FSize) or (FData[Result].DTMark <> ADT) then
Result := -1;
end;
function TCache.InternalAdd(
const AObj: TCacheDataObjectAbstract
): Boolean;
var
ObjDT: TDateTime;
Poz: Integer;
//------------------------------------------------------------------------------
begin
Result := True;
if (FSize = Length(FData)) then
Grow();
ObjDT := AObj.DTMark;
Poz := IndexOfEqualOrAbove(ObjDT);
if (Poz = FSize) then // добавление в конец списка
Inc(FSize)
else if (FData[Poz].DTMark <> ObjDT) then // добавление в середину/начало списка
begin
Move(FData[Poz], FData[Poz + 1], (FSize - Poz) * SizeOf(FData[0]));
Inc(FSize);
end
else // замена
Result := False;
if Result then
begin
FData[Poz] := AObj;
FLoadedFrom := Min(FLoadedFrom, ObjDT);
FLoadedTo := Max(FLoadedTo, ObjDT);
FMinAdapterDT := Min(FMinAdapterDT, ObjDT);
FMaxAdapterDT := Max(FMaxAdapterDT, ObjDT);
end;
end;
function TCache.InternalReplace(
const AObj: TCacheDataObjectAbstract
): Boolean;
var
Poz: Integer;
//------------------------------------------------------------------------------
begin
Poz := IndexOf(AObj.DTMark);
Result := Poz <> -1;
if Result then
begin
FData[Poz].Free();
FData[Poz] := AObj;
end;
end;
function TCache.WillItBeCleaned(ADT: TDateTime): Boolean;
var
IdxLow,
IdxHi: Integer;
begin
IdxLow := IndexOfEqualOrAbove(ADT - FLoadDelta);
IdxHi := IndexOfEqualOrLower(ADT + FLoadDelta);
Result := (Count > 0) and ((IdxLow = FSize) or (IdxHi < 0));
end;
function TCache.InternalDelete(
const ADT: TDateTime
): TCacheDataObjectAbstract;
var
Index: Integer;
//------------------------------------------------------------------------------
begin
Index := IndexOf(ADT);
if (Index = -1) then
Exit(nil);
if (FMinAdapterDT = ADT) and (Index < FSize - 2) then
FMinAdapterDT := FData[Index + 1].DTMark;
if (FMaxAdapterDT = ADT) and (Index > 0) then
FMaxAdapterDT := FData[Index - 1].DTMark;
Result := FData[Index];
Dec(FSize);
if (FSize <> Index) then // исключительно для предотвращения Range Check Error
Move(FData[Index + 1], FData[Index], (FSize - Index) * SizeOf(FData[0]));
end;
function TCache.InLoadedRange(
const ADT: TDateTime
): Boolean;
begin
Result := (FLoadedFrom <= ADT) and (ADT <= FLoadedTo);
end;
procedure TCache.AdapterLoadRange(
const AFrom: TDateTime;
const ATo: TDateTime
);
var
NewFrom, NewTo: TDateTime;
InCacheFromDT, InCacheToDT: TDateTime;
NewData: TCacheDataObjectAbstractArray;
I: Integer;
//------------------------------------------------------------------------------
begin
NewFrom := AFrom - FLoadDelta;
NewTo := ATo + FLoadDelta;
if (FSize <> 0) then
begin
InCacheFromDT := FData[0].DTMark;
InCacheToDT := FData[FSize - 1].DTMark;
if (InCacheFromDT <= AFrom) and (ATo <= InCacheToDT) then
Exit;
if (NewFrom > InCacheToDT) then
NewFrom := InCacheToDT;
if (NewTo < InCacheFromDT) then
NewTo := InCacheFromDT;
end;
FAdapter.LoadRange(Self, NewFrom, NewTo, NewData);
for I := Low(NewData) to High(NewData) do
begin
if (IndexOf(NewData[I].DTMark) = -1) then
InternalAdd(NewData[I])
else
NewData[I].Free();
end;
if (Length(NewData) <> 0) then
begin
FLoadedFrom := Min(FLoadedFrom, NewFrom);
FLoadedTo := Max(FLoadedTo, NewTo);
end;
end;
function TCache.GetEnumerator(): TCacheEnumerator;
begin
Result := TCacheEnumerator.Create(Self);
end;
function TCache.GetFirstDT: TDateTime;
begin
Result := 0;
if FSize > 0 then
Result := FData[0].DTMark;
end;
function TCache.GetLastDT: TDateTime;
begin
Result := 0;
if FSize > 0 then
Result := FData[FSize - 1].DTMark;
end;
//------------------------------------------------------------------------------
// TCache.TCacheEnumerator
//------------------------------------------------------------------------------
constructor TCache.TCacheEnumerator.Create(
ACache: TCache
);
begin
inherited Create();
//
FCache := ACache;
FIdx := -1;
end;
function TCache.TCacheEnumerator.GetCurrent(): TCacheDataObjectAbstract;
begin
Result := FCache.FData[FIdx];
end;
function TCache.TCacheEnumerator.MoveNext(): Boolean;
begin
Inc(FIdx);
Result := FIdx < FCache.FSize;
end;
//------------------------------------------------------------------------------
// TCacheDictionaryRoot<KeyType>
//------------------------------------------------------------------------------
constructor TCacheDictionary<KeyType>.Create();
begin
inherited Create();
//
OnValueNotify := ValueEvent;
end;
function TCacheDictionary<KeyType>.GetCountAll: Integer;
var
k: KeyType;
begin
Result := 0;
for k in Keys do
Result := Result + Items[k].Count;
end;
procedure TCacheDictionary<KeyType>.ValueEvent(
Sender: TObject;
const Item: TCache;
Action: TCollectionNotification
);
begin
if (Action = cnRemoved) then
Item.Free();
end;
//------------------------------------------------------------------------------
// TConnKey
//------------------------------------------------------------------------------
constructor TConnKey.Create(
const AKeys: array of string
);
var
k, v: string;
i: Integer;
//------------------------------------------------------------------------------
begin
inherited Create();
//
i := 0;
while (i + 1) < Length(AKeys) do
begin
k := AKeys[i];
v := AKeys[i + 1];
Add(k, v);
Inc(i, 2);
end;
end;
end.
|
namespace UT3Bots.UTItems;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Text;
type
UTVector = public class
private
_x: Double;
_y: Double;
_z: Double;
public
constructor (x, y, z: Double);
method get_X: Double;
method set_X(value: Double);
method get_Y: Double;
method set_Y(value: Double);
method get_Z: Double;
method set_Z(value: Double);
method DistanceFrom(a: UTVector): Double;
method ToString: String; override;
method GetHashCode: integer; override;
method Equals(obj: Object): boolean; override;
class operator Equal(obj1, obj2: UTVector): boolean;
class operator NotEqual(obj1, obj2: UTVector): boolean;
class method Parse(toParse: String): UTVector;
property X: Double read get_X write set_X;
property Y: Double read get_Y write set_Y;
property Z: Double read get_Z write set_Z;
end;
implementation
{$REGION Property Get and Set'ers}
method UTVector.get_X: Double;
begin
Result := _x;
end;
method UTVector.set_X(value: Double);
begin
Self._x := value;
end;
method UTVector.get_Y: Double;
begin
Result := _y;
end;
method UTVector.set_Y(value: Double);
begin
Self._y := value;
end;
method UTVector.get_Z: Double;
begin
Result := _z;
end;
method UTVector.set_Z(value: Double);
begin
Self._z := value;
end;
{$ENDREGION}
constructor UTVector(x, y, z: Double);
begin
Self._x := x;
Self._y := y;
Self._z := z;
end;
/// <summary>
/// Works out the distance between this UTVector and another.
/// (You should allow for a distance of about 300 if you are checking to see if you are at a specific location)
/// </summary>
/// <param name="a">The other UTVector to get the distance between</param>
/// <returns></returns>
method UTVector.DistanceFrom(a: UTVector): Double;
var
distance, xx, yy, zz: Double;
begin
xx := Math.Pow((Self._x - a.X), 2);
yy := Math.Pow((Self._y - a.Y), 2);
zz := Math.Pow((Self._z - a.Z), 2);
distance := (Math.Sqrt(xx + yy + zz));
if (double.IsNaN(distance)) then distance := 0;
Result := distance;
end;
method UTVector.ToString: String;
begin
Result := String.Format('{1:E}, {1:E}, {1:E}', [Self._x, Self._y, Self._z]);
end;
method UTVector.GetHashCode: integer;
begin
Result := inherited GetHashCode;
end;
method UTVector.Equals(obj: Object): boolean;
begin
Result := False;
if (obj is UTVector) then
begin
if ((Self._x = (obj as UTVector)._x) and (Self._y = (obj as UTVector)._y) and (Self._z = (obj as UTVector)._z)) then
begin
Result := True;
end;
end;
end;
class operator UTVector.Equal(obj1, obj2: UTVector): boolean;
begin
Result := False;
if System.Object.ReferenceEquals(obj1, obj2) then exit True;
if (((obj1 as Object) = nil) or ((obj1 as Object) = nil)) then exit False;
if ((obj1._x = obj2._x) and (obj1._y = obj2._y) and (obj1._z = obj2._z)) then exit True;
end;
class operator UTVector.NotEqual(obj1, obj2: UTVector): boolean;
begin
Result := (obj1 <> obj2);
end;
class method UTVector.Parse(toParse: String): UTVector;
var
parts: Array of string;
x, y, z: Double;
begin
try
parts := toParse.Split(UT3Bots.Communications.Message.MESSAGE_SUBSEPARATOR);
for i: Integer := 0 to parts.Length - 1 do
begin
if parts[i] = '' then parts[i] := '0.0';
end;
x := Double.Parse(parts[0]);
y := Double.Parse(parts[1]);
z := Double.Parse(parts[2]);
Result := new UTVector(x, y, z);
except
new ArgumentException(string.Format('Unable to parse {0} to UTVector', toParse));
end;
end;
end. |
unit DXPCurrencyEdit;
interface
uses
SysUtils, Classes, Controls, StdCtrls, Graphics, Messages,
Windows, CommCtrl, uIValidatable, Forms, DXPMessageOutPut,
DXPUtils, StrUtils;
type
// opRequired - Validar se foi preenchido;
// opPrimaryKey - Desabilita quando o crud esta em estado de dsEdit;
TOptions = set of TOption;
//
TDXPCurrencyEdit = class(TCustomEdit, IValidatable)
private
FBaseColor: TColor;
FOptions: TOptions;
FMessageOutPut: TDXPMessageOutPut;
FCaption: string;
FReadOnly: Boolean;
//
procedure SetValidations(const Value: TOptions);
procedure SetMessageOutPut(const Value: TDXPMessageOutPut);
procedure SetReadOnly(const Value: boolean);
function GetValue: Currency;
procedure SetValue(const Value: Currency);
{ Private declarations }
protected
procedure KeyPress(var Key: Char); override;
procedure DoEnter; override;
procedure DoExit; override;
procedure DoSetTextHint(const Value: string); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
//
function IsValid: boolean;
{ Public declarations }
published
property Align;
property Alignment;
property Anchors;
property AutoSelect;
property AutoSize;
property BevelEdges;
property BevelInner;
property BevelKind default bkFlat;
property BevelOuter;
property BevelWidth;
property BiDiMode;
property BorderStyle default bsNone;
property Caption: string read FCaption write FCaption;
property CharCase;
property Color;
property Constraints;
property Ctl3D;
property DoubleBuffered;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property HideSelection;
property ImeMode;
property ImeName;
property MaxLength;
property MessageOutPut: TDXPMessageOutPut read FMessageOutPut write SetMessageOutPut;
property NumbersOnly;
property OEMConvert;
property Options: TOptions read FOptions write SetValidations;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentDoubleBuffered;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property PopupMenu;
property ReadOnly: boolean read FReadOnly write SetReadOnly default false;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property TextHint;
property Touch;
property Value: Currency read GetValue write SetValue;
property Visible;
property OnChange;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGesture;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseActivate;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
{ Published declarations }
end;
implementation
{ TDXPCurrencyEdit }
function TDXPCurrencyEdit.GetValue: Currency;
begin
Result := 0;
if ( Text <> '' ) and ( Text <> Name ) then
begin
try
Result := StrToCurr( AnsiReplaceStr(Text, '.', '') );
except
ShowMsgInformation( 'Valor incorreto.' );
TryFocus( Self );
end;
end;
end;
constructor TDXPCurrencyEdit.Create(AOwner: TComponent);
begin
inherited Create( AOwner );
//
BorderStyle := bsNone;
BevelKind := bkFlat;
FReadOnly := false;
Alignment := taRightJustify;
Value := 0;
end;
destructor TDXPCurrencyEdit.Destroy;
begin
inherited Destroy;
end;
procedure TDXPCurrencyEdit.DoEnter;
begin
inherited;
//
FBaseColor := Color;
Color := clInfoBk;
end;
procedure TDXPCurrencyEdit.DoExit;
var
Value: Currency;
Converteu: Boolean;
begin
if ( Trim( Text ) <> '' ) then
begin
Converteu := False;
try
Value := StrToCurr( AnsiReplaceStr(Text, '.', '') );
//
Text := FormatCurr(',0.00', Value);
//
Converteu := True;
//
//if FMessageOutPut.ShowingOutPut then
//FMessageOutPut.Close;
except
if Assigned( FMessageOutPut ) then
begin
FMessageOutPut.ClearOutPut;
FMessageOutPut.AddMessage( 'Valor incorreto.', FCaption, Self );
FMessageOutPut.ShowOutPut;
end
else
begin
ShowMsgInformation( 'Valor incorreto.' );
TryFocus( Self );
end;
end;
//
if not( Converteu ) then
Exit;
end;
//
Color := FBaseColor;
//
inherited DoExit;
end;
procedure TDXPCurrencyEdit.DoSetTextHint(const Value: string);
begin
{TODO -oAraujo -cComponents : Validar versão do windows}
if CheckWin32Version( 5, 1 ) then
SendTextMessage( Handle, EM_SETCUEBANNER, WPARAM(0), Value );
end;
function TDXPCurrencyEdit.IsValid: boolean;
begin
Result := false;
//
if ( opRequired in FOptions ) and ( Trim( Text ) = '' ) then
begin
if Assigned( FMessageOutPut ) then
FMessageOutPut.AddMessage( 'Obrigatório.', FCaption, Self )
else
begin
ShowMsgInformation( FCaption + ': Informação obrigatória.' );
TryFocus( Self );
end;
//
Exit;
end;
//
Result := true;
end;
procedure TDXPCurrencyEdit.KeyPress(var Key: Char);
begin
inherited;
//
if not( CharInSet(Key, ['0'..'9',',',#8,#13] ) ) then
Key := #0;
end;
procedure TDXPCurrencyEdit.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification( AComponent, Operation );
//
if ( AComponent = FMessageOutPut ) and ( Operation = opRemove ) then
FMessageOutPut := nil;
end;
procedure TDXPCurrencyEdit.SetValue(const Value: Currency);
begin
Text := FormatCurr(',0.00', Value);
end;
procedure TDXPCurrencyEdit.SetMessageOutPut(const Value: TDXPMessageOutPut);
begin
if Assigned( FMessageOutPut ) then
FMessageOutPut.RemoveFreeNotification( Self );
//
FMessageOutPut := Value;
//
if Assigned( FMessageOutPut ) then
FMessageOutPut.FreeNotification( Self );
end;
procedure TDXPCurrencyEdit.SetReadOnly(const Value: boolean);
begin
inherited ReadOnly := Value;
FReadOnly := Value;
//
if FReadOnly then
Color := clBtnFace
else
Color := clWindow;
end;
procedure TDXPCurrencyEdit.SetValidations(const Value: TOptions);
begin
if Value <> FOptions then
FOptions := Value;
end;
end.
|
unit Validador.Core.UnificadorXML;
interface
uses
Validador.Data.dbChangeXML, Validador.DI, Xml.xmldom, Xml.XMLDoc, Xml.XMLIntf;
type
IUnificadorXML = interface(IInterface)
['{739AA013-AFEA-422B-BFF1-351B2980B117}']
procedure SetXMLAnterior(const Xml: IXMLDocument);
procedure SetXMLNovo(const Xml: IXMLDocument);
procedure PegarXMLMesclado(const AXMLDocument: IXMLDocument);
end;
implementation
end.
|
Unit Paging;
{ * Paging : *
* *
* Esta unidad se encarga de administrar la memoria paginada .Las *
* paginas se encuentran en dos listas una en mm_map , en que se guarda *
* info sobre el estado de la pagina y la cola de libres , que liga a *
* las paginas libre *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* 10 / 06 / 2004 : Primera Version *
* *
************************************************************************
}
interface
{DEFINE DEBUG}
{$I ../include/toro/procesos.inc}
{$I ../include/head/procesos.h}
{$I ../include/head/scheduler.h}
{$I ../include/head/asm.h}
{$I ../include/head/mm.h}
{$I ../include/head/printk_.h}
function kmapmem(add_f , add_l , add_dir:pointer;atributos:word):dword;external name 'KMAPMEM';
function kmalloc(Size:dword):pointer;external name 'KMALLOC';
function kfree_s(addr:pointer;size:dword):dword;external name 'KFREE_S';
var mem_map:P_page;
mem_map_size:dword;
dma_Page_free:p_page_free;
Low_Page_Free:p_Page_free;
High_Page_Free:p_page_free;
start_mem:pointer;
start_page:dword;
nr_page:dword;
nr_free_page:dword;
Kernel_PDT:pointer;
size_dir:array[1..9] of dir_alloc_entry;external name 'U_MALLOC_SIZE_DIR';
Mem_wait : wait_queue ;
implementation
{$I ../include/head/list.h}
{ * Clear_Page : *
* *
* Llena de 0 la pagina punteada en Add_f *
* *
*******************************************************
}
procedure clear_page(Add_f:pointer);inline;
begin
asm
mov edi , add_f
mov eax , 0
mov ecx ,1024
rep stosd
end;
end;
{ * Devuelve el indice de una dir logica * }
function get_page_index(Add_l:pointer):Indice;[public , alias :'GET_PAGE_INDEX'];
var tmp:dword;
begin
tmp:=longint(Add_l);
Get_Page_Index.Dir_i:= tmp div (Page_Size * 1024);
Get_Page_Index.Page_i := (tmp mod (Page_Size * 1024)) div Page_Size;
end;
{ * Coloca una pagina libre en la pila de paginas libres * }
procedure push_free_page(Dir_F:pointer);
var tmp:p_page_free;
begin
tmp:=Dir_f;
{Si pertenece a la memoria de kernel}
If Dir_F < pointer(High_Memory) then
begin
if (dir_f < pointer (dma_memory)) then
begin
tmp := dir_f ;
tmp^.next_page := dma_page_free ;
dma_page_free := tmp ;
exit;
end;
tmp := dir_f ;
tmp^.next_page := Low_Page_Free ;
Low_Page_Free := tmp ;
end
else {Si pertenece a las paginas del usuario}
begin
tmp := dir_f ;
tmp^.next_page := High_Page_Free ;
High_Page_Free := tmp;
end;
end;
{ * Pop_Free_Page : *
* *
* Devuelve un puntero a una pagina libre y la quita de la cola *
* .La pila es quitada de la cola de paginas libres de la memoria *
* alta *
* *
******************************************************************
}
function pop_free_page:pointer;
begin
If High_Page_Free=nil then exit(nil);
Pop_Free_Page := High_Page_Free;
High_Page_Free:=High_Page_Free^.next_page;
end;
{ * Kpop_Free_Page *
* *
* Quita una pagina libre de la cola de paginas de la memoria baja *
* *
***********************************************************************
}
function kpop_free_page:pointer;
begin
If Low_Page_Free=nil then exit(nil);
KPop_Free_Page := Low_Page_Free;
Low_Page_Free := Low_Page_Free^.next_page;
end;
{ * quita un pagina dma de la pila * }
function dma_pop_free_page : pointer ;
begin
If Dma_page_free = nil then exit(nil);
dma_pop_free_page := Dma_page_free ;
dma_page_free := Dma_Page_free^.next_page ;
end;
{ * Init_Lista_Page_Free : *
* *
* Inicializa la cola de paginas libres *
* *
*******************************************************************
}
procedure init_lista_page_free;
var last_page:dword;
ret:dword;
begin
last_page := (MM_TOTALMEM div Page_Size)-1;
for ret := start_page to last_page do push_free_page(pointer(ret * Page_Size));
for ret := 8 to $f do push_free_page (pointer(ret*page_size));
end;
{ * Get_Free_Page : *
* *
* Devuelve un puntero a un pagina libre *
* Utiliza la cola de paginas libres de la memoria alta , en caso *
* de no haber utiliza las de la baja *
* *
******************************************************************
}
function get_free_page:pointer;[public, alias : 'GET_FREE_PAGE'];
var tmp:pointer;
begin
{ Se trata de buscar una pagina de la zona alta }
tmp := Pop_Free_Page;
{ Si no toma de la baja }
If tmp=nil then
begin
tmp := kpop_free_page ;
{por ultimo es tomada una pagina de la zona dma}
if tmp = nil then tmp := dma_pop_free_page ;
if tmp = nil then exit(nil);
end;
{ Se aumenta el contador y se establece el tipo de pagina }
mem_map[longint(tmp) shr 12].count := 1;
mem_map[longint(tmp) shr 12].flags := PG_Null;
nr_free_page-=1;
MM_MemFree -= Page_Size;
clear_page(tmp);
exit(tmp);
end;
{ * Get_Free_Kpage : *
* *
* retorno : puntero a una pagina libre *
* *
* Esta funcion no es igual a Get_Free_Page , puesto que devuelve una *
* pagina libre de la memoria baja , utilizada por el kernel para las *
* pilas 0 , sino el kernel utiliza Get_Free_Page *
* *
***********************************************************************
}
function get_free_kpage:pointer;[public , alias :'GET_FREE_KPAGE'];
var tmp:pointer;
begin
tmp := KPop_Free_Page;
if tmp = nil then
begin
tmp := dma_pop_free_page ;
if tmp = nil then exit(nil);
end;
If tmp = nil then exit(nil);
{ Se aumenta el contador y se establece el tipo de pagina }
mem_map[longint(tmp) shr 12].count:=1;
mem_map[longint(tmp) shr 12].flags:=PG_Null;
nr_free_page -= 1;
MM_MemFree -= Page_Size;
clear_page(tmp);
exit(tmp);
end;
{ * Get_Dma_Page : *
* *
* Retorno : puntero a una pagina dma *
* *
* Funcion q devuelve un pagina dma libre *
* *
***********************************************************************
}
function get_dma_page : pointer ;[public , alias : 'GET_DMA_PAGE'];
var tmp : pointer;
begin
tmp := dma_pop_free_page ;
if tmp = nil then exit(nil);
mem_map[longint(tmp) shr 12].count:=1;
mem_map[longint(tmp) shr 12].flags:=PG_Null;
nr_free_page -= 1;
MM_MemFree -= Page_Size;
clear_page(tmp);
exit(tmp);
end;
{ * Free_Page : *
* *
* Add_f : Dir fisica de la pagina *
* *
* Dada una pagina , decrementa su uso y en caso de no tener usuarios *
* la agrega a la cola de libres *
* *
***********************************************************************
}
procedure free_page(Add_f:pointer);[public, alias : 'FREE_PAGE'];
begin
If mem_map[longint(add_f) shr 12].count=0 then exit ;
mem_map[longint(add_f) shr 12].count -= 1;
If mem_map[longint(add_f) shr 12].count = 0 then
begin
Push_Free_Page(Add_f);
MM_memfree += Page_Size ;
nr_free_page += 1;
end;
end;
{ * Esta funcion coloca los atributos a una pagina * }
function set_page_rights(add_l,add_dir:pointer;atributos:word):dword;[public ,alias :'SET_PAGE_RIGHTS'];
var i:indice;
dp,tp:^dword;
begin
i := Get_Page_Index(add_l);
dp := add_dir;
If (dp[i.dir_i] and Present_Page ) = 0 then exit(-1);
tp:=pointer(dp[I.dir_i] and $FFFFF000);
If (tp[i.page_i] and Present_Page ) = 0 then exit(-1);
atributos:=atributos and $FFF;
tp[i.page_i]:=tp[i.page_i] or atributos;
end;
{ * Unload_Page_Table : *
* *
* add_l : Direccion logica de la tabla *
* add_dir : Puntero al PDT *
* *
* Esta funcion a diferencia de kunmapmem , si libera todas las paginas *
* pertenecientes a una TP , la TP y la quita del PDT *
* *
*************************************************************************
}
function unload_page_table(add_l,add_dir:pointer):dword;[public , alias :'UNLOAD_PAGE_TABLE'];
var i:indice;
dp,tp:^dword;
ret:dword;
pg:pointer;
begin
i:=Get_Page_index(add_l);
dp:=add_dir;
{ Si el directorio no estubiese presente }
If (dp[i.dir_i] and Present_Page) = 0 then exit(-1);
tp:=pointer(dp[i.dir_i] and $FFFFF000);
{ Punteo al comienzo de la tabla de paginas }
{ Se busca en toda la tabla las paginas activas }
for ret:= 1 to (Page_Size div 4) do
begin
pg:=pointer(tp[ret] and $FFFFF000);
If (tp[ret] and Present_Page) = 0 then { No deve tener el bit P bajo }
else
{ La pagina deve estar alineada a los 4 kb }
If (longint(pg) and $FFF) = 0 then free_page(pg)
else Panic('Unload_Page_Table : Se quita una pagina no alineada');
end;
{ Se libera la PT }
free_page(pointer(dp[I.dir_i] and $FFFFF000));
{ Se borra la entrada en el PDT }
dp[I.dir_i]:=0;
end;
{ * Dup_Page_Table : *
* *
* add_tp : puntero a la tabla de paginas *
* *
* Esta funcion duplica una tp aumentando el contador de las paginas *
* que a las que apunta *
* *
***********************************************************************
}
function dup_page_table(add_tp:pointer):dword;[public , alias :'DUP_PAGE_TABLE'];
var tmp:dword;
pg:^dword;
p:pointer;
begin
pg:=add_tp;
for tmp:= 1 to (Page_Size div 4) do
begin
p:=pointer(pg[tmp] and $FFFFF000);
{ La pagina deve estar presente }
If (pg[tmp] and Present_Page ) = 0 then
else
{ La pagina deve estar alineada a los 4 kb }
If (longint(p) and $FFF ) = 0 then mem_map[longint(p) shr 12].count += 1;
end;
exit(0);
end;
{ * Devuelve la dir. fisica de una dir logica segun el pdt * }
function get_phys_add(add_l,Pdt:pointer):pointer;[public , alias :'GET_PHYS_ADD'];
var i:indice;
pd,pt:^dword;
begin
i:=Get_Page_Index(add_l);
pd:=Pdt;
{ Deve estar presente la dp }
If (pd[I.dir_i] and Present_Page ) = 0 then exit(nil);
pt:=pointer(longint(pd[I.dir_i]) and $FFFFF000);
{ Deve estar presente la tp }
If (pt[I.page_i] and Present_Page) = 0 then exit(nil);
exit(pointer(longint(pt[I.page_i]) and $FFFFF000));
end;
{ * Reserve_Page : *
* *
* add_f : Direcion fisica de la pagina *
* Retorno : 0 si ok i -1 si falla *
* *
* Funcion que reserva un pagina quitandola de la pila de disponibles *
* utilizada mas q nada para dispositivos hard que realizan io a traves*
* de memoria mapeada *
* *
***********************************************************************
}
function reserve_page (add_f:pointer):dword;[public , alias : 'RESERVE_PAGE'];
var npage,ppage : p_page_free ;
begin
{la pagina se encuentra actualmente en uso}
If mem_map[longint(add_f) shr 12].count = 1 then exit(-1) ;
npage := Low_Page_Free ;
ppage := Low_Page_Free ;
{se recorre la cola de paginas bajas}
while (npage <> nil ) do
begin
{se encontro la pagina}
if (npage = add_f) then
begin
if (npage = Low_Page_Free) then Low_Page_Free := npage^.next_page
else if (npage^.next_page = nil) then ppage^.next_page := nil
else ppage^.next_page := npage^.next_page ;
mem_map[longint(add_f) shr 12].flags := Pg_Reserver ;
{operacion correcta!!!}
exit(0);
end;
ppage := npage ;
npage := npage^.next_page ;
end;
npage := High_Page_Free ;
ppage := High_Page_Free ;
{se recorre la cola de paginas altas o de usuarios}
while (npage <> nil ) do
begin
{se encontro la pagina}
if (npage = add_f) then
begin
if (npage = Low_Page_Free) then Low_Page_Free := npage^.next_page
else if (npage^.next_page = nil) then ppage^.next_page := nil
else ppage^.next_page := npage^.next_page ;
exit(0);
end;
ppage := npage ;
npage := npage^.next_page ;
end;
{algo anda mal no se encontrol pagina !!! se encuentra debajo de memini}
exit(-1);
end;
{ * Free_Reserve_Page : *
* *
* addf : direcion fisica de la pagina *
* *
* Devuelve una pagina reservada *
* *
***********************************************************************
}
function free_reserve_page (add_f : pointer ) : dword;[public , alias : 'FREE_RESERVE_PAGE'];
begin
push_free_page (add_f);
mem_map[longint(add_f) shr 12].count := 0 ;
mem_map[longint(add_f) shr 12].count := Pg_Null;
end;
{ * Proceso que inicializa la paginacion atraves de la MMU * }
procedure paging_start;
var tmp:pointer;
ret:dword;
begin
{ Se mapea toda la memoria dentro del dir del kernel para que este }
{ la vea en el mismo espacio logico }
Kernel_PDT := get_free_kpage;
tmp:=nil;
for ret:= 0 to ((MM_TOTALMEM div Page_Size) -1) do
begin
tmp:=pointer(Page_Size * ret);
kmapmem(tmp,tmp,kernel_PDT,Present_Page or Write_Page);
end;
asm
mov eax , Kernel_Pdt
mov cr3 , eax
mov eax , cr0
or eax , $80000000
mov cr0 , eax
end;
end;
{ * Proceso que inicializa todo el sistema de paginacion como malloc , etc * }
procedure paging_init;[public, alias :'PAGING_INIT'];
var ret,size:dword;
l,k:pointer;
begin
{ Se calcula el numero de paginas y el tamano de mem_map }
nr_page:=(MM_MemFree div Page_Size);
mem_map_size:=nr_page * sizeof(T_page);
nr_page-=(mem_map_size div Page_Size);
nr_free_page:=nr_page;
start_page:=(MeM_Ini + mem_map_size) div Page_Size;
start_mem:=pointer(start_page * Page_Size);
Low_Page_Free:=nil;
High_Page_Free:=nil;
mem_map:= pointer (Mem_Ini) ;
{ Se inicializa la lista de paginas libres }
Init_Lista_Page_Free;
printk('/nCantidad de Paginas : /V%d \n',[nr_page]);
printk('/nPrimer Pagina : /V%d \n',[start_page]);
printk('/nPaginas en Mem_Map : /V%d \n',[mem_map_size div Page_Size]);
{ Se inicializa a la MMU }
paging_start;
{ Se iniciliza el directorio de Malloc }
printk('/nIniciando malloc ... ',[]);
size:=16;
for ret:= 1 to 9 do
begin
size_dir[ret].size:=size;
size_dir[ret].nr_page_desc:=0;
size_dir[ret].free_list:=nil;
size_dir[ret].busy_list:=nil;
size_dir[ret].Unassign_list:=nil;
size:=size * 2;
end;
printk('/VOk\n',[]);
mem_wait.lock_wait := nil ;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clPop3FileHandler;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
{$IFDEF DELPHI7}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ENDIF}
uses
Classes, clPop3Server, SyncObjs;
type
TclPop3LoadMessageEvent = procedure (Sender: TObject; AConnection: TclPop3CommandConnection;
const AMailBoxPath, AMessageFile: string; var ACanLoad: Boolean) of object;
TclPop3FileHandler = class(TComponent)
private
FServer: TclPop3Server;
FMailBoxDir: string;
FAccessor: TCriticalSection;
FOnLoadMessage: TclPop3LoadMessageEvent;
procedure SetServer(const Value: TclPop3Server);
procedure SetMailBoxDir(const Value: string);
procedure DoStateChanged(Sender: TObject; AConnection: TclPop3CommandConnection);
procedure DoMailBoxInfo(Sender: TObject; AConnection: TclPop3CommandConnection;
AMailBox: TclPop3MessageList);
procedure DoRetrieve(Sender: TObject; AConnection: TclPop3CommandConnection;
AMessageNo, ATopLines: Integer; ARetrieveAll: Boolean; AMessageSource: TStrings;
var Success: Boolean);
function GetMailBoxPath(const AUserName: string): string;
function GetMessageUid(const AFileName: string; AFileSize: Integer): string;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure CleanEventHandlers; virtual;
procedure InitEventHandlers; virtual;
procedure DoLoadMessage(AConnection: TclPop3CommandConnection;
const AMailBoxPath, AMessageFile: string; var ACanLoad: Boolean); virtual;
property Accessor: TCriticalSection read FAccessor;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Server: TclPop3Server read FServer write SetServer;
property MailBoxDir: string read FMailBoxDir write SetMailBoxDir;
property OnLoadMessage: TclPop3LoadMessageEvent read FOnLoadMessage write FOnLoadMessage;
end;
implementation
uses
Windows, SysUtils, clUtils, clImapUtils;
{ TclPop3FileHandler }
procedure TclPop3FileHandler.CleanEventHandlers;
begin
Server.OnMailBoxInfo := nil;
Server.OnRetrieve := nil;
Server.OnStateChanged := nil;
end;
constructor TclPop3FileHandler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAccessor := TCriticalSection.Create();
end;
destructor TclPop3FileHandler.Destroy;
begin
FAccessor.Free();
inherited Destroy();
end;
procedure TclPop3FileHandler.InitEventHandlers;
begin
Server.OnMailBoxInfo := DoMailBoxInfo;
Server.OnRetrieve := DoRetrieve;
Server.OnStateChanged := DoStateChanged;
end;
procedure TclPop3FileHandler.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation <> opRemove) then Exit;
if (AComponent = FServer) then
begin
CleanEventHandlers();
FServer := nil;
end;
end;
procedure TclPop3FileHandler.SetMailBoxDir(const Value: string);
begin
FAccessor.Enter();
try
FMailBoxDir := Value;
finally
FAccessor.Leave();
end;
end;
procedure TclPop3FileHandler.SetServer(const Value: TclPop3Server);
begin
if (FServer <> Value) then
begin
{$IFDEF DELPHI5}
if (FServer <> nil) then
begin
FServer.RemoveFreeNotification(Self);
CleanEventHandlers();
end;
{$ENDIF}
FServer := Value;
if (FServer <> nil) then
begin
FServer.FreeNotification(Self);
InitEventHandlers();
end;
end;
end;
function TclPop3FileHandler.GetMailBoxPath(const AUserName: string): string;
begin
Result := AddTrailingBackSlash(MailBoxDir) + AddTrailingBackSlash(AUserName);
end;
function TclPop3FileHandler.GetMessageUid(const AFileName: string; AFileSize: Integer): string;
begin
Result := UpperCase(StringReplace(AFileName, '.', ':', [rfReplaceAll])) + ':' + IntToStr(AFileSize);
Result := StringReplace(Result, #32, '_', [rfReplaceAll]);
end;
procedure TclPop3FileHandler.DoMailBoxInfo(Sender: TObject;
AConnection: TclPop3CommandConnection; AMailBox: TclPop3MessageList);
var
path: string;
searchRec: TSearchRec;
msgInfo: TclPop3MessageItem;
canLoad: Boolean;
begin
path := GetMailBoxPath(AConnection.UserName);
AMailBox.Clear();
if SysUtils.FindFirst(path + '*.*', 0, searchRec) = 0 then
begin
repeat
canLoad := not SameText(cImapMailBoxInfoFile, searchRec.Name);
DoLoadMessage(AConnection, path, searchRec.Name, canLoad);
if canLoad then
begin
msgInfo := AMailBox.Add();
msgInfo.Size := searchRec.Size;
msgInfo.UID := GetMessageUid(searchRec.Name, searchRec.Size);
msgInfo.ExtraInfo := path + searchRec.Name;
end;
until (SysUtils.FindNext(searchRec) <> 0);
SysUtils.FindClose(searchRec);
end;
end;
procedure TclPop3FileHandler.DoRetrieve(Sender: TObject; AConnection: TclPop3CommandConnection;
AMessageNo, ATopLines: Integer; ARetrieveAll: Boolean; AMessageSource: TStrings; var Success: Boolean);
var
s: string;
src: TStream;
begin
try
s := AConnection.MailBox.Items[AMessageNo - 1].ExtraInfo;
if ARetrieveAll then
begin
AMessageSource.LoadFromFile(s);
end else
begin
src := TFileStream.Create(s, fmOpenRead);
try
GetTopLines(src, ATopLines, AMessageSource);
finally
src.Free();
end;
end;
Success := True;
except
AMessageSource.Clear();
Success := False;
end;
end;
procedure TclPop3FileHandler.DoStateChanged(Sender: TObject; AConnection: TclPop3CommandConnection);
var
i: Integer;
begin
if (AConnection.ConnectionState <> csPop3Update) then Exit;
for i := 0 to AConnection.MailBox.Count - 1 do
begin
if AConnection.MailBox[i].IsDeleted then
begin
DeleteFile(AConnection.MailBox[i].ExtraInfo);
end;
end;
end;
procedure TclPop3FileHandler.DoLoadMessage(AConnection: TclPop3CommandConnection;
const AMailBoxPath, AMessageFile: string; var ACanLoad: Boolean);
begin
if Assigned(OnLoadMessage) then
begin
OnLoadMessage(Self, AConnection, AMailBoxPath, AMessageFile, ACanLoad);
end;
end;
end.
|
unit TB97;
{
Toolbar97
Copyright (C) 1998-2004 by Jordan Russell
http://www.jrsoftware.org/
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*PLEASE NOTE* Before making any bug reports please first verify you are
using the latest version by checking my home page. And if
you do report a bug, please, if applicable, include a code
sample.
Notes:
- I cannot support modified versions of this code. So if you encounter a
possible bug while using a modified version, always first revert back to
the my original code before making an attempt to contact me.
- While debugging the toolbar code you might want to enable the
'TB97DisableLock' conditional define, as described below.
- In the WM_NCPAINT handlers, GetWindowRect is used to work around a possible
VCL problem. The Width, Height, and BoundsRect properties are sometimes
wrong. So it avoids any use of these properties in the WM_NCPAINT handlers.
- In case you are unsure of its meaning, NewStyleControls is a VCL variable
set to True at application startup if the user is running Windows 95 or NT
4.0 or later.
$jrsoftware: tb97/Source/TB97.pas,v 1.5 2004/02/23 22:53:00 jr Exp $
}
{x$DEFINE TB97DisableLock}
{ Remove the 'x' to enable the define. It will disable calls to
LockWindowUpdate, which it calls to disable screen updates while dragging.
You should temporarily enable that while debugging so you are able to see
your code window if you have something like a breakpoint that's set inside
the dragging routines }
{$I TB97Ver.inc}
interface
uses
Windows, Messages, Classes, Controls, Forms, Graphics, Types,
TB97Vers;
const
WM_TB97PaintDockedNCArea = WM_USER + 5039; { used internally }
WM_TB97PaintFloatingNCArea = WM_USER + 5040; { used internally }
type
{ TDock97 }
TDockBoundLinesValues = (blTop, blBottom, blLeft, blRight);
TDockBoundLines = set of TDockBoundLinesValues;
TDockPosition = (dpTop, dpBottom, dpLeft, dpRight);
TDockType = (dtNotDocked, dtTopBottom, dtLeftRight);
TDockableTo = set of TDockPosition;
TCustomToolWindow97 = class;
TInsertRemoveEvent = procedure(Sender: TObject; Inserting: Boolean;
Bar: TCustomToolWindow97) of object;
TRequestDockEvent = procedure(Sender: TObject; Bar: TCustomToolWindow97;
var Accept: Boolean) of object;
TDock97 = class(TCustomControl)
private
{ Property values }
FPosition: TDockPosition;
FAllowDrag: Boolean;
FBoundLines: TDockBoundLines;
FBkg, FBkgCache: TBitmap;
FBkgTransparent, FBkgOnToolbars: Boolean;
FFixAlign: Boolean;
FLimitToOneRow: Boolean;
FOnInsertRemoveBar: TInsertRemoveEvent;
FOnRequestDock: TRequestDockEvent;
FOnResize: TNotifyEvent;
{ Internal }
FDisableArrangeToolbars: Integer; { Increment to disable ArrangeToolbars }
FArrangeToolbarsNeeded, FArrangeToolbarsClipPoses: Boolean;
FNonClientWidth, FNonClientHeight: Integer;
DockList: TList; { List of the toolbars docked, and those floating and have LastDock
pointing to the dock. Items are casted in TCustomToolWindow97's. }
DockVisibleList: TList; { Similar to DockList, but lists only docked and visible toolbars }
RowSizes: TList; { List of the width or height of each row, depending on what Position
is set to. Items are casted info Longint's }
{ Property access methods }
function GetVersion: TToolbar97Version;
procedure SetAllowDrag (Value: Boolean);
procedure SetBackground (Value: TBitmap);
procedure SetBackgroundOnToolbars (Value: Boolean);
procedure SetBackgroundTransparent (Value: Boolean);
procedure SetBoundLines (Value: TDockBoundLines);
procedure SetFixAlign (Value: Boolean);
procedure SetPosition (Value: TDockPosition);
procedure SetVersion (const Value: TToolbar97Version);
function GetToolbarCount: Integer;
function GetToolbars (Index: Integer): TCustomToolWindow97;
{ Internal }
procedure ArrangeToolbars (const ClipPoses: Boolean);
procedure BackgroundChanged (Sender: TObject);
procedure BuildRowInfo;
procedure ChangeDockList (const Insert: Boolean; const Bar: TCustomToolWindow97);
procedure ChangeWidthHeight (const NewWidth, NewHeight: Integer);
procedure DrawBackground (const DC: HDC;
const IntersectClippingRect: TRect; const ExcludeClippingRect: PRect;
const DrawRect: TRect);
procedure DrawNCArea (const DrawToDC: Boolean; const ADC: HDC;
const Clip: HRGN);
function GetDesignModeRowOf (const XY: Integer): Integer;
function GetNumberOfToolbarsOnRow (const Row: Integer;
const NotIncluding: TCustomToolWindow97): Integer;
function GetRowOf (const XY: Integer; var Before: Boolean): Integer;
function HasVisibleToolbars: Boolean;
procedure InsertRowBefore (const BeforeRow: Integer);
procedure InvalidateBackgrounds;
procedure RemoveBlankRows;
function ToolbarVisibleOnDock (const AToolbar: TCustomToolWindow97): Boolean;
procedure ToolbarVisibilityChanged (const Bar: TCustomToolWindow97;
const ForceRemove: Boolean);
function UsingBackground: Boolean;
{ Messages }
procedure CMColorChanged (var Message: TMessage); message CM_COLORCHANGED;
procedure CMSysColorChange (var Message: TMessage); message CM_SYSCOLORCHANGE;
procedure WMMove (var Message: TWMMove); message WM_MOVE;
procedure WMSize (var Message: TWMSize); message WM_SIZE;
procedure WMNCCalcSize (var Message: TWMNCCalcSize); message WM_NCCALCSIZE;
procedure WMNCPaint (var Message: TMessage); message WM_NCPAINT;
procedure WMPrint (var Message: TMessage); message WM_PRINT;
procedure WMPrintClient (var Message: TMessage); message WM_PRINTCLIENT;
protected
procedure AlignControls (AControl: TControl; var Rect: TRect); override;
function GetPalette: HPALETTE; override;
procedure Loaded; override;
procedure Notification (AComponent: TComponent; Operation: TOperation); override;
procedure SetParent (AParent: TWinControl); override;
procedure Paint; override;
public
constructor Create (AOwner: TComponent); override;
procedure CreateParams (var Params: TCreateParams); override;
destructor Destroy; override;
procedure BeginUpdate;
procedure EndUpdate;
function GetHighestRow: Integer;
function GetRowSize (const Row: Integer;
const DefaultToolbar: TCustomToolWindow97): Integer;
property NonClientWidth: Integer read FNonClientWidth;
property NonClientHeight: Integer read FNonClientHeight;
property ToolbarCount: Integer read GetToolbarCount;
property Toolbars[Index: Integer]: TCustomToolWindow97 read GetToolbars;
published
property AllowDrag: Boolean read FAllowDrag write SetAllowDrag default True;
property Background: TBitmap read FBkg write SetBackground;
property BackgroundOnToolbars: Boolean read FBkgOnToolbars write SetBackgroundOnToolbars default True;
property BackgroundTransparent: Boolean read FBkgTransparent write SetBackgroundTransparent default False;
property BoundLines: TDockBoundLines read FBoundLines write SetBoundLines default [];
property Color default clBtnFace;
property FixAlign: Boolean read FFixAlign write SetFixAlign default False;
property LimitToOneRow: Boolean read FLimitToOneRow write FLimitToOneRow default False;
property PopupMenu;
property Position: TDockPosition read FPosition write SetPosition default dpTop;
property Version: TToolbar97Version read GetVersion write SetVersion stored False;
property Visible;
property OnInsertRemoveBar: TInsertRemoveEvent read FOnInsertRemoveBar write FOnInsertRemoveBar;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnRequestDock: TRequestDockEvent read FOnRequestDock write FOnRequestDock;
property OnResize: TNotifyEvent read FOnResize write FOnResize;
end;
{ TFloatingWindowParent - internal }
TFloatingWindowParent = class(TForm)
private
FParentForm: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
FShouldShow: Boolean;
procedure CMShowingChanged (var Message: TMessage); message CM_SHOWINGCHANGED;
procedure CMDialogKey (var Message: TCMDialogKey); message CM_DIALOGKEY;
protected
procedure CreateParams (var Params: TCreateParams); override;
public
property ParentForm: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF} read FParentForm;
constructor Create (AOwner: TComponent); override;
end;
{ TCustomToolWindow97 }
TDockChangingExEvent = procedure(Sender: TObject; DockingTo: TDock97) of object;
TDragHandleStyle = (dhDouble, dhNone, dhSingle);
TToolWindowDockMode = (dmCanFloat, dmCannotFloat, dmCannotFloatOrChangeDocks);
TToolWindowFloatingMode = (fmOnTopOfParentForm, fmOnTopOfAllForms);
TToolWindowParams = record
CallAlignControls, ResizeEightCorner, ResizeClipCursor: Boolean;
end;
TToolWindowSizeHandle = (twshLeft, twshRight, twshTop, twshTopLeft,
twshTopRight, twshBottom, twshBottomLeft, twshBottomRight);
{ ^ must be in same order as HTLEFT..HTBOTTOMRIGHT }
TToolWindowNCRedrawWhatElement = (twrdBorder, twrdCaption, twrdCloseButton);
TToolWindowNCRedrawWhat = set of TToolWindowNCRedrawWhatElement;
TPositionReadIntProc = function(const ToolbarName, Value: String; const Default: Longint;
const ExtraData: Pointer): Longint;
TPositionReadStringProc = function(const ToolbarName, Value, Default: String;
const ExtraData: Pointer): String;
TPositionWriteIntProc = procedure(const ToolbarName, Value: String; const Data: Longint;
const ExtraData: Pointer);
TPositionWriteStringProc = procedure(const ToolbarName, Value, Data: String;
const ExtraData: Pointer);
TCustomToolWindow97 = class(TCustomControl)
private
{ Property variables }
FDockPos, FDockRow: Integer;
FDocked: Boolean;
FDockedTo, FDefaultDock, FLastDock: TDock97;
FOnClose, FOnDockChanged, FOnDockChanging, FOnMove, FOnRecreated,
FOnRecreating, FOnResize, FOnVisibleChanged: TNotifyEvent;
FOnCloseQuery: TCloseQueryEvent;
FOnDockChangingEx, FOnDockChangingHidden: TDockChangingExEvent;
FActivateParent, FHideWhenInactive, FCloseButton, FCloseButtonWhenDocked,
FFullSize, FResizable, FShowCaption, FUseLastDock: Boolean;
FBorderStyle: TBorderStyle;
FDockMode: TToolWindowDockMode;
FDragHandleStyle: TDragHandleStyle;
FDockableTo: TDockableTo;
FFloatingMode: TToolWindowFloatingMode;
FLastDockType: TDockType;
FLastDockTypeSet: Boolean;
FParams: TToolWindowParams;
{ Misc. }
FUpdatingBounds, { Incremented while internally changing the bounds. This allows
it to move the toolbar freely in design mode and prevents the
SizeChanging protected method from begin called }
FDisableArrangeControls, { Incremented to disable ArrangeControls }
FDisableOnMove, { Incremented to prevent WM_MOVE handler from calling the OnMoved handler }
FHidden: Integer; { Incremented while the toolbar is temporarily hidden }
FArrangeNeeded, FMoved: Boolean;
FInactiveCaption: Boolean; { True when the caption of the toolbar is currently the inactive color }
FFloatingTopLeft: TPoint;
FDockForms: TList;
FSavedAtRunTime: Boolean;
FNonClientWidth, FNonClientHeight: Integer;
{ When floating. These are not used in design mode }
FFloatParent: TFloatingWindowParent; { Run-time only: The actual Parent of the toolbar when it is floating }
FCloseButtonDown: Boolean; { True if Close button is currently depressed }
{ Property access methods }
function GetVersion: TToolbar97Version;
function IsLastDockStored: Boolean;
procedure SetBorderStyle (Value: TBorderStyle);
procedure SetCloseButton (Value: Boolean);
procedure SetCloseButtonWhenDocked (Value: Boolean);
procedure SetDefaultDock (Value: TDock97);
procedure SetDockedTo (Value: TDock97);
procedure SetDockPos (Value: Integer);
procedure SetDockRow (Value: Integer);
procedure SetDragHandleStyle (Value: TDragHandleStyle);
procedure SetFloatingMode (Value: TToolWindowFloatingMode);
procedure SetFullSize (Value: Boolean);
procedure SetLastDock (Value: TDock97);
procedure SetResizable (Value: Boolean);
procedure SetShowCaption (Value: Boolean);
procedure SetUseLastDock (Value: Boolean);
procedure SetVersion (const Value: TToolbar97Version);
{ Internal }
procedure CalculateNonClientSizes (R: PRect);
procedure MoveOnScreen (const OnlyIfFullyOffscreen: Boolean);
procedure DrawDraggingOutline (const DC: HDC; const NewRect, OldRect: PRect;
const NewDocking, OldDocking: Boolean);
procedure DrawFloatingNCArea (const DrawToDC: Boolean; const ADC: HDC;
const Clip: HRGN; RedrawWhat: TToolWindowNCRedrawWhat);
procedure DrawDockedNCArea (const DrawToDC: Boolean; const ADC: HDC;
const Clip: HRGN);
procedure InvalidateDockedNCArea;
procedure InvalidateFloatingNCArea (const RedrawWhat: TToolWindowNCRedrawWhat);
procedure ValidateDockedNCArea;
function ValidateFloatingNCArea: TToolWindowNCRedrawWhat;
procedure SetInactiveCaption (Value: Boolean);
procedure Moved;
function GetShowingState: Boolean;
procedure UpdateTopmostFlag;
procedure UpdateVisibility;
procedure ReadSavedAtRunTime (Reader: TReader);
procedure WriteSavedAtRunTime (Writer: TWriter);
{ Messages }
procedure CMColorChanged (var Message: TMessage); message CM_COLORCHANGED;
procedure CMTextChanged (var Message: TMessage); message CM_TEXTCHANGED;
procedure CMShowingChanged (var Message: TMessage); message CM_SHOWINGCHANGED;
procedure CMVisibleChanged (var Message: TMessage); message CM_VISIBLECHANGED;
procedure WMActivate (var Message: TWMActivate); message WM_ACTIVATE;
procedure WMClose (var Message: TWMClose); message WM_CLOSE;
procedure WMEnable (var Message: TWMEnable); message WM_ENABLE;
procedure WMGetMinMaxInfo (var Message: TWMGetMinMaxInfo); message WM_GETMINMAXINFO;
procedure WMMove (var Message: TWMMove); message WM_MOVE;
procedure WMMouseActivate (var Message: TWMMouseActivate); message WM_MOUSEACTIVATE;
procedure WMNCCalcSize (var Message: TWMNCCalcSize); message WM_NCCALCSIZE;
procedure WMNCHitTest (var Message: TWMNCHitTest); message WM_NCHITTEST;
procedure WMNCLButtonDown (var Message: TWMNCLButtonDown); message WM_NCLBUTTONDOWN;
procedure WMNCPaint (var Message: TMessage); message WM_NCPAINT;
procedure WMPrint (var Message: TMessage); message WM_PRINT;
procedure WMPrintClient (var Message: TMessage); message WM_PRINTCLIENT;
procedure WMTB97PaintDockedNCArea (var Message: TMessage); message WM_TB97PaintDockedNCArea;
procedure WMTB97PaintFloatingNCArea (var Message: TMessage); message WM_TB97PaintFloatingNCArea;
procedure WMSize (var Message: TWMSize); message WM_SIZE;
protected
property ActivateParent: Boolean read FActivateParent write FActivateParent default True;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
property Color default clBtnFace;
property CloseButton: Boolean read FCloseButton write SetCloseButton default True;
property CloseButtonWhenDocked: Boolean read FCloseButtonWhenDocked write SetCloseButtonWhenDocked default False;
property DefaultDock: TDock97 read FDefaultDock write SetDefaultDock;
property DockableTo: TDockableTo read FDockableTo write FDockableTo default [dpTop, dpBottom, dpLeft, dpRight];
property DockMode: TToolWindowDockMode read FDockMode write FDockMode default dmCanFloat;
property DragHandleStyle: TDragHandleStyle read FDragHandleStyle write SetDragHandleStyle default dhDouble;
property FloatingMode: TToolWindowFloatingMode read FFloatingMode write SetFloatingMode default fmOnTopOfParentForm;
property FullSize: Boolean read FFullSize write SetFullSize default False;
property HideWhenInactive: Boolean read FHideWhenInactive write FHideWhenInactive default True;
property LastDock: TDock97 read FLastDock write SetLastDock stored IsLastDockStored;
property Params: TToolWindowParams read FParams;
property Resizable: Boolean read FResizable write SetResizable default True;
property ShowCaption: Boolean read FShowCaption write SetShowCaption default True;
property UseLastDock: Boolean read FUseLastDock write SetUseLastDock default True;
property Version: TToolbar97Version read GetVersion write SetVersion stored False;
property OnClose: TNotifyEvent read FOnClose write FOnClose;
property OnCloseQuery: TCloseQueryEvent read FOnCloseQuery write FOnCloseQuery;
property OnDockChanged: TNotifyEvent read FOnDockChanged write FOnDockChanged;
property OnDockChanging: TNotifyEvent read FOnDockChanging write FOnDockChanging;
property OnDockChangingEx: TDockChangingExEvent read FOnDockChangingEx write FOnDockChangingEx;
property OnDockChangingHidden: TDockChangingExEvent read FOnDockChangingHidden write FOnDockChangingHidden;
property OnMove: TNotifyEvent read FOnMove write FOnMove;
property OnRecreated: TNotifyEvent read FOnRecreated write FOnRecreated;
property OnRecreating: TNotifyEvent read FOnRecreating write FOnRecreating;
property OnResize: TNotifyEvent read FOnResize write FOnResize;
property OnVisibleChanged: TNotifyEvent read FOnVisibleChanged write FOnVisibleChanged;
{ Overridden methods }
procedure AlignControls (AControl: TControl; var Rect: TRect); override;
procedure CreateParams (var Params: TCreateParams); override;
procedure DefineProperties (Filer: TFiler); override;
function GetPalette: HPALETTE; override;
procedure Loaded; override;
procedure MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure Notification (AComponent: TComponent; Operation: TOperation); override;
procedure Paint; override;
function PaletteChanged (Foreground: Boolean): Boolean; override;
procedure SetParent (AParent: TWinControl); override;
{ Methods accessible to descendants }
procedure ArrangeControls;
function ChildControlTransparent (Ctl: TControl): Boolean; dynamic;
procedure CustomArrangeControls (const PreviousDockType: TDockType;
const DockingTo: TDock97; const Resize: Boolean);
procedure DoDockChangingHidden (DockingTo: TDock97); dynamic;
procedure DoMove; dynamic;
procedure GetBarSize (var ASize: Integer; const DockType: TDockType); virtual; abstract;
procedure GetDockRowSize (var AHeightOrWidth: Integer);
procedure GetMinimumSize (var AClientWidth, AClientHeight: Integer); virtual; abstract;
procedure GetParams (var Params: TToolWindowParams); dynamic;
procedure InitializeOrdering; dynamic;
function OrderControls (CanMoveControls: Boolean; PreviousDockType: TDockType;
DockingTo: TDock97): TPoint; virtual; abstract;
procedure ResizeBegin (SizeHandle: TToolWindowSizeHandle); dynamic;
procedure ResizeEnd (Accept: Boolean); dynamic;
procedure ResizeTrack (var Rect: TRect; const OrigRect: TRect); dynamic;
procedure SizeChanging (const AWidth, AHeight: Integer); virtual;
public
property Docked: Boolean read FDocked;
property DockedTo: TDock97 read FDockedTo write SetDockedTo stored False;
property DockPos: Integer read FDockPos write SetDockPos default -1;
property DockRow: Integer read FDockRow write SetDockRow default 0;
property FloatingPosition: TPoint read FFloatingTopLeft write FFloatingTopLeft;
property NonClientWidth: Integer read FNonClientWidth;
property NonClientHeight: Integer read FNonClientHeight;
constructor Create (AOwner: TComponent); override;
destructor Destroy; override;
function GetParentComponent: TComponent; override;
function HasParent: Boolean; override;
procedure SetBounds (ALeft, ATop, AWidth, AHeight: Integer); override;
procedure AddDockForm (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF});
procedure AddDockedNCAreaToSize (var S: TPoint; const LeftRight: Boolean);
procedure AddFloatingNCAreaToSize (var S: TPoint);
procedure BeginMoving (const InitX, InitY: Integer);
procedure BeginSizing (const ASizeHandle: TToolWindowSizeHandle);
procedure BeginUpdate;
procedure DoneReadingPositionData (const ReadIntProc: TPositionReadIntProc;
const ReadStringProc: TPositionReadStringProc; const ExtraData: Pointer); dynamic;
procedure EndUpdate;
procedure GetDockedNCArea (var TopLeft, BottomRight: TPoint;
const LeftRight: Boolean);
function GetFloatingBorderSize: TPoint;
procedure GetFloatingNCArea (var TopLeft, BottomRight: TPoint);
procedure ReadPositionData (const ReadIntProc: TPositionReadIntProc;
const ReadStringProc: TPositionReadStringProc; const ExtraData: Pointer); dynamic;
procedure RemoveDockForm (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF});
procedure WritePositionData (const WriteIntProc: TPositionWriteIntProc;
const WriteStringProc: TPositionWriteStringProc; const ExtraData: Pointer); dynamic;
published
property Height stored False;
property Width stored False;
end;
procedure RegLoadToolbarPositions (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF}; const BaseRegistryKey: String);
procedure RegLoadToolbarPositionsEx (const Form: TCustomForm; const RootKey: HKEY; const BaseRegistryKey: String);
procedure RegSaveToolbarPositions (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF}; const BaseRegistryKey: String);
procedure RegSaveToolbarPositionsEx (const Form: TCustomForm; const RootKey: HKEY; const BaseRegistryKey: String);
procedure IniLoadToolbarPositions (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF}; const Filename, SectionNamePrefix: String);
procedure IniSaveToolbarPositions (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF}; const Filename, SectionNamePrefix: String);
procedure CustomLoadToolbarPositions (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
const ReadIntProc: TPositionReadIntProc;
const ReadStringProc: TPositionReadStringProc; const ExtraData: Pointer);
procedure CustomSaveToolbarPositions (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
const WriteIntProc: TPositionWriteIntProc;
const WriteStringProc: TPositionWriteStringProc; const ExtraData: Pointer);
function GetDockTypeOf (const Control: TDock97): TDockType;
function GetToolWindowParentForm (const ToolWindow: TCustomToolWindow97):
{$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
function ValidToolWindowParentForm (const ToolWindow: TCustomToolWindow97):
{$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
implementation
uses
Registry, IniFiles, SysUtils, Consts,
TB97Cmn, TB97Cnst;
const
DockedBorderSize = 2;
DockedBorderSize2 = DockedBorderSize*2;
DragHandleSizes: array[Boolean, TDragHandleStyle] of Integer =
((9, 0, 6), (14, 14, 14));
DragHandleOffsets: array[Boolean, TDragHandleStyle] of Integer =
((2, 0, 1), (3, 0, 5));
DefaultBarWidthHeight = 8;
ForceDockAtTopRow = 0;
ForceDockAtLeftPos = -8;
PositionLeftOrRight = [dpLeft, dpRight];
twrdAll = [Low(TToolWindowNCRedrawWhatElement)..High(TToolWindowNCRedrawWhatElement)];
{ Constants for TCustomToolWindow97 registry values/data.
Don't localize any of these names! }
rvRev = 'Rev';
rdCurrentRev = 3;
rvVisible = 'Visible';
rvDockedTo = 'DockedTo';
rdDockedToFloating = '+';
rvLastDock = 'LastDock';
rvDockRow = 'DockRow';
rvDockPos = 'DockPos';
rvFloatLeft = 'FloatLeft';
rvFloatTop = 'FloatTop';
var
FloatingToolWindows: TList = nil;
{ Misc. functions }
function GetSmallCaptionHeight: Integer;
{ Returns height of the caption of a small window }
begin
if NewStyleControls then
Result := GetSystemMetrics(SM_CYSMCAPTION)
else
{ Win 3.x doesn't support small captions, so, like Office 97, use the size
of normal captions minus one }
Result := GetSystemMetrics(SM_CYCAPTION) - 1;
end;
function GetPrimaryDesktopArea: TRect;
{ Returns a rectangle containing the "work area" of the primary display
monitor, which is the area not taken up by the taskbar. }
begin
if not SystemParametersInfo(SPI_GETWORKAREA, 0, @Result, 0) then
{ SPI_GETWORKAREA is only supported by Win95 and NT 4.0. So it fails under
Win 3.x. In that case, return a rectangle of the entire screen }
Result := Rect(0, 0, GetSystemMetrics(SM_CXSCREEN),
GetSystemMetrics(SM_CYSCREEN));
end;
function UsingMultipleMonitors: Boolean;
{ Returns True if the system has more than one display monitor configured. }
var
NumMonitors: Integer;
begin
NumMonitors := GetSystemMetrics(80 {SM_CMONITORS});
Result := (NumMonitors <> 0) and (NumMonitors <> 1);
{ ^ NumMonitors will be zero if not running Win98, NT 5, or later }
end;
type
HMONITOR = type Integer;
PMonitorInfoA = ^TMonitorInfoA;
TMonitorInfoA = record
cbSize: DWORD;
rcMonitor: TRect;
rcWork: TRect;
dwFlags: DWORD;
end;
const
MONITOR_DEFAULTTONEAREST = $2;
type
TMultiMonApis = record
funcMonitorFromRect: function(lprcScreenCoords: PRect; dwFlags: DWORD): HMONITOR; stdcall;
funcMonitorFromPoint: function(ptScreenCoords: TPoint; dwFlags: DWORD): HMONITOR; stdcall;
funcGetMonitorInfoA: function(hMonitor: HMONITOR; lpMonitorInfo: PMonitorInfoA): BOOL; stdcall;
end;
{ Under D4 I could be using the MultiMon unit for the multiple monitor
function imports, but its stubs for MonitorFromRect and MonitorFromPoint
are seriously bugged... So I chose to avoid the MultiMon unit entirely. }
function InitMultiMonApis (var Apis: TMultiMonApis): Boolean;
var
User32Handle: THandle;
begin
User32Handle := GetModuleHandle(user32);
Apis.funcMonitorFromRect := GetProcAddress(User32Handle, 'MonitorFromRect');
Apis.funcMonitorFromPoint := GetProcAddress(User32Handle, 'MonitorFromPoint');
Apis.funcGetMonitorInfoA := GetProcAddress(User32Handle, 'GetMonitorInfoA');
Result := Assigned(Apis.funcMonitorFromRect) and
Assigned(Apis.funcMonitorFromPoint) and Assigned(Apis.funcGetMonitorInfoA);
end;
function GetDesktopAreaOfMonitorContainingRect (const R: TRect): TRect;
{ Returns the work area of the monitor which the rectangle R intersects with
the most, or the monitor nearest R if no monitors intersect. }
var
Apis: TMultiMonApis;
M: HMONITOR;
MonitorInfo: TMonitorInfoA;
begin
if UsingMultipleMonitors and InitMultiMonApis(Apis) then begin
M := Apis.funcMonitorFromRect(@R, MONITOR_DEFAULTTONEAREST);
MonitorInfo.cbSize := SizeOf(MonitorInfo);
if Apis.funcGetMonitorInfoA(M, @MonitorInfo) then begin
Result := MonitorInfo.rcWork;
Exit;
end;
end;
Result := GetPrimaryDesktopArea;
end;
function GetDesktopAreaOfMonitorContainingPoint (const P: TPoint): TRect;
{ Returns the work area of the monitor containing the point P, or the monitor
nearest P if P isn't in any monitor's work area. }
var
Apis: TMultiMonApis;
M: HMONITOR;
MonitorInfo: TMonitorInfoA;
begin
if UsingMultipleMonitors and InitMultiMonApis(Apis) then begin
M := Apis.funcMonitorFromPoint(P, MONITOR_DEFAULTTONEAREST);
MonitorInfo.cbSize := SizeOf(MonitorInfo);
if Apis.funcGetMonitorInfoA(M, @MonitorInfo) then begin
Result := MonitorInfo.rcWork;
Exit;
end;
end;
Result := GetPrimaryDesktopArea;
end;
function GetMDIParent (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF}):
{$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
{ Returns the parent of the specified MDI child form. But, if Form isn't a
MDI child, it simply returns Form. }
var
I, J: Integer;
begin
Result := Form;
if Form = nil then Exit;
if {$IFDEF TB97D3} (Form is TForm) and {$ENDIF}
(TForm(Form).FormStyle = fsMDIChild) then
for I := 0 to Screen.FormCount-1 do
with Screen.Forms[I] do begin
if FormStyle <> fsMDIForm then Continue;
for J := 0 to MDIChildCount-1 do
if MDIChildren[J] = Form then begin
Result := Screen.Forms[I];
Exit;
end;
end;
end;
function GetDockTypeOf (const Control: TDock97): TDockType;
begin
if Control = nil then
Result := dtNotDocked
else begin
if not(Control.Position in PositionLeftOrRight) then
Result := dtTopBottom
else
Result := dtLeftRight;
end;
end;
function GetToolWindowParentForm (const ToolWindow: TCustomToolWindow97):
{$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
var
Ctl: TWinControl;
begin
Result := nil;
Ctl := ToolWindow;
while Assigned(Ctl.Parent) do begin
if Ctl.Parent is {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF} then
Result := {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF}(Ctl.Parent);
Ctl := Ctl.Parent;
end;
{ ^ for compatibility with ActiveX controls, that code is used instead of
GetParentForm because it returns nil unless the form is the *topmost*
parent }
if Result is TFloatingWindowParent then
Result := TFloatingWindowParent(Result).ParentForm;
end;
function ValidToolWindowParentForm (const ToolWindow: TCustomToolWindow97):
{$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
begin
Result := GetToolWindowParentForm(ToolWindow);
if Result = nil then
raise EInvalidOperation.{$IFDEF TB97D3}CreateFmt{$ELSE}CreateResFmt{$ENDIF}
(SParentRequired, [ToolWindow.Name]);
end;
procedure ToolbarHookProc (Code: THookProcCode; Wnd: HWND; WParam: WPARAM; LParam: LPARAM);
var
I: Integer;
ToolWindow: TCustomToolWindow97;
Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
begin
case Code of
hpSendActivateApp: begin
if Assigned(FloatingToolWindows) then
for I := 0 to FloatingToolWindows.Count-1 do
with TCustomToolWindow97(FloatingToolWindows.List[I]) do
{ Hide or restore toolbars when application is deactivated or activated.
UpdateVisibility also sets caption state active/inactive }
UpdateVisibility;
end;
hpSendWindowPosChanged: begin
if Assigned(FloatingToolWindows) then
for I := 0 to FloatingToolWindows.Count-1 do begin
ToolWindow := TCustomToolWindow97(FloatingToolWindows.List[I]);
with ToolWindow do begin
if (FFloatingMode = fmOnTopOfParentForm) and HandleAllocated then begin
with PWindowPos(LParam)^ do
{ Call UpdateVisibility if parent form's visibility has
changed, or if it has been minimized or restored }
if ((flags and (SWP_SHOWWINDOW or SWP_HIDEWINDOW) <> 0) or
(flags and SWP_FRAMECHANGED <> 0)) then begin
Form := GetToolWindowParentForm(ToolWindow);
if Assigned(Form) and Form.HandleAllocated and ((Wnd = Form.Handle) or IsChild(Wnd, Form.Handle)) then
UpdateVisibility;
end;
end;
end;
end;
end;
hpPreDestroy: begin
if Assigned(FloatingToolWindows) then
for I := 0 to FloatingToolWindows.Count-1 do begin
with TCustomToolWindow97(FloatingToolWindows.List[I]) do
{ It must remove the form window's ownership of the tool window
*before* the form gets destroyed, otherwise Windows will destroy
the tool window's handle. }
if HandleAllocated and (HWND(GetWindowLong(Handle, GWL_HWNDPARENT)) = Wnd) then
SetWindowLong (Handle, GWL_HWNDPARENT, Longint(Parent.Handle));
{ ^ Restore GWL_HWNDPARENT back to the TFloatingWindowParent }
end;
end;
end;
end;
procedure ProcessPaintMessages;
{ Dispatches all pending WM_PAINT messages. In effect, this is like an
'UpdateWindow' on all visible windows }
var
Msg: TMsg;
begin
while PeekMessage(Msg, 0, WM_PAINT, WM_PAINT, PM_NOREMOVE) do begin
case Integer(GetMessage(Msg, 0, WM_PAINT, WM_PAINT)) of
-1: Break; { if GetMessage failed }
0: begin
{ Repost WM_QUIT messages }
PostQuitMessage (Msg.WParam);
Break;
end;
end;
DispatchMessage (Msg);
end;
end;
type
PFindWindowData = ^TFindWindowData;
TFindWindowData = record
TaskActiveWindow, TaskFirstWindow, TaskFirstTopMost: HWND;
end;
function DoFindWindow (Wnd: HWND; Param: Longint): Bool; stdcall;
begin
with PFindWindowData(Param)^ do
if (Wnd <> TaskActiveWindow) and (Wnd <> Application.Handle) and
IsWindowVisible(Wnd) and IsWindowEnabled(Wnd) then begin
if GetWindowLong(Wnd, GWL_EXSTYLE) and WS_EX_TOPMOST = 0 then begin
if TaskFirstWindow = 0 then TaskFirstWindow := Wnd;
end
else begin
if TaskFirstTopMost = 0 then TaskFirstTopMost := Wnd;
end;
end;
Result := True;
end;
function FindTopLevelWindow (ActiveWindow: HWND): HWND;
var
FindData: TFindWindowData;
begin
with FindData do begin
TaskActiveWindow := ActiveWindow;
TaskFirstWindow := 0;
TaskFirstTopMost := 0;
EnumThreadWindows (GetCurrentThreadID, @DoFindWindow, Longint(@FindData));
if TaskFirstWindow <> 0 then
Result := TaskFirstWindow
else
Result := TaskFirstTopMost;
end;
end;
procedure RecalcNCArea (const Ctl: TWinControl);
begin
if Ctl.HandleAllocated then
SetWindowPos (Ctl.Handle, 0, 0, 0, 0, 0, SWP_FRAMECHANGED or
SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE or SWP_NOZORDER);
end;
function GetToolbarDockPos (Ctl: TControl): TGetToolbarDockPosType;
begin
Result := gtpNone;
while Assigned(Ctl) and not(Ctl is TCustomToolWindow97) do
Ctl := Ctl.Parent;
if Assigned(Ctl) and Assigned(TCustomToolWindow97(Ctl).DockedTo) then
Result := TGetToolbarDockPosType(TCustomToolWindow97(Ctl).DockedTo.Position);
{ ^ TDockPosition can be casted TGetToolbarDockPosType because its values
are in the same order }
end;
{ TDock97 - internal }
constructor TDock97.Create (AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csAcceptsControls] -
[csClickEvents, csCaptureMouse, csOpaque];
FAllowDrag := True;
FBkgOnToolbars := True;
DockList := TList.Create;
DockVisibleList := TList.Create;
RowSizes := TList.Create;
FBkg := TBitmap.Create;
FBkg.OnChange := BackgroundChanged;
Color := clBtnFace;
Position := dpTop;
end;
procedure TDock97.CreateParams (var Params: TCreateParams);
begin
inherited;
{ Disable complete redraws when size changes. CS_H/VREDRAW cause flicker
and are not necessary for this control at run time }
if not(csDesigning in ComponentState) then
with Params.WindowClass do
Style := Style and not(CS_HREDRAW or CS_VREDRAW);
end;
destructor TDock97.Destroy;
begin
FBkgCache.Free;
FBkg.Free;
inherited;
RowSizes.Free;
DockVisibleList.Free;
DockList.Free;
end;
procedure TDock97.SetParent (AParent: TWinControl);
begin
if (AParent is TCustomToolWindow97) or (AParent is TDock97) then
raise EInvalidOperation.Create(STB97DockParentNotAllowed);
inherited;
end;
procedure TDock97.BeginUpdate;
begin
Inc (FDisableArrangeToolbars);
end;
procedure TDock97.EndUpdate;
begin
Dec (FDisableArrangeToolbars);
if FArrangeToolbarsNeeded and (FDisableArrangeToolbars = 0) then
ArrangeToolbars (FArrangeToolbarsClipPoses);
end;
function TDock97.HasVisibleToolbars: Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to DockList.Count-1 do
if ToolbarVisibleOnDock(TCustomToolWindow97(DockList[I])) then begin
Result := True;
Break;
end;
end;
function TDock97.ToolbarVisibleOnDock (const AToolbar: TCustomToolWindow97): Boolean;
begin
Result := (AToolbar.Parent = Self) and
(AToolbar.Visible or (csDesigning in AToolbar.ComponentState));
end;
procedure TDock97.BuildRowInfo;
var
R, I, Size, HighestSize: Integer;
ToolbarOnRow: Boolean;
T: TCustomToolWindow97;
begin
RowSizes.Clear;
for R := 0 to GetHighestRow do begin
ToolbarOnRow := False;
HighestSize := 0;
for I := 0 to DockList.Count-1 do begin
T := TCustomToolWindow97(DockList[I]);
with T do
if (FDockRow = R) and ToolbarVisibleOnDock(T) then begin
ToolbarOnRow := True;
GetBarSize (Size, GetDockTypeOf(Self));
if Size > HighestSize then HighestSize := Size;
end;
end;
if ToolbarOnRow and (HighestSize < DefaultBarWidthHeight) then
HighestSize := DefaultBarWidthHeight;
RowSizes.Add (Pointer(HighestSize));
end;
end;
function TDock97.GetRowSize (const Row: Integer;
const DefaultToolbar: TCustomToolWindow97): Integer;
begin
Result := 0;
if Row < RowSizes.Count then
Result := Longint(RowSizes[Row]);
if (Result = 0) and Assigned(DefaultToolbar) then
DefaultToolbar.GetBarSize (Result, GetDockTypeOf(Self));
end;
function TDock97.GetRowOf (const XY: Integer; var Before: Boolean): Integer;
{ Returns row number of the specified coordinate. Before is set to True if it
was close to being in between two rows. }
var
HighestRow, R, CurY, NextY, CurRowSize: Integer;
begin
Result := 0; Before := False;
HighestRow := GetHighestRow;
CurY := 0;
for R := 0 to HighestRow+1 do begin
NextY := High(NextY);
if R <= HighestRow then begin
CurRowSize := GetRowSize(R, nil);
if CurRowSize = 0 then Continue;
NextY := CurY + CurRowSize + DockedBorderSize2;
end;
if XY < CurY+5 then begin
Result := R;
Before := True;
Break;
end;
if (XY >= CurY+5) and (XY < NextY-5) then begin
Result := R;
Break;
end;
CurY := NextY;
end;
end;
function TDock97.GetDesignModeRowOf (const XY: Integer): Integer;
{ Similar to GetRowOf, but is a little different to accomidate design mode
better }
var
HighestRowPlus1, R, CurY, CurRowSize: Integer;
begin
Result := 0;
HighestRowPlus1 := GetHighestRow+1;
CurY := 0;
for R := 0 to HighestRowPlus1 do begin
Result := R;
if R = HighestRowPlus1 then Break;
CurRowSize := GetRowSize(R, nil);
if CurRowSize = 0 then Continue;
Inc (CurY, CurRowSize + DockedBorderSize2);
if XY < CurY then
Break;
end;
end;
function TDock97.GetHighestRow: Integer;
{ Returns highest used row number, or -1 if no rows are used }
var
I: Integer;
begin
Result := -1;
for I := 0 to DockList.Count-1 do
with TCustomToolWindow97(DockList[I]) do
if FDockRow > Result then
Result := FDockRow;
end;
function TDock97.GetNumberOfToolbarsOnRow (const Row: Integer;
const NotIncluding: TCustomToolWindow97): Integer;
{ Returns number of toolbars on the specified row. The toolbar specified by
"NotIncluding" is not included in the count. }
var
I: Integer;
begin
Result := 0;
for I := 0 to DockList.Count-1 do
if (TCustomToolWindow97(DockList[I]).FDockRow = Row) and
(DockList[I] <> NotIncluding) then
Inc (Result);
end;
procedure TDock97.RemoveBlankRows;
{ Deletes any blank row numbers, adjusting the docked toolbars' FDockRow as
needed }
var
HighestRow, R, I: Integer;
RowIsEmpty: Boolean;
begin
HighestRow := GetHighestRow;
R := 0;
while R <= HighestRow do begin
RowIsEmpty := True;
for I := 0 to DockList.Count-1 do
if TCustomToolWindow97(DockList[I]).FDockRow = R then begin
RowIsEmpty := False;
Break;
end;
if RowIsEmpty then begin
{ Shift all ones higher than R back one }
for I := 0 to DockList.Count-1 do
with TCustomToolWindow97(DockList[I]) do
if FDockRow > R then
Dec (FDockRow);
Dec (HighestRow);
end
else
Inc (R);
end;
end;
procedure TDock97.InsertRowBefore (const BeforeRow: Integer);
{ Inserts a blank row before BeforeRow, adjusting all the docked toolbars'
FDockRow as needed }
var
I: Integer;
begin
for I := 0 to DockList.Count-1 do
with TCustomToolWindow97(DockList[I]) do
if FDockRow >= BeforeRow then
Inc (FDockRow);
end;
procedure TDock97.ChangeWidthHeight (const NewWidth, NewHeight: Integer);
{ Same as setting Width/Height directly, but does not lose Align position. }
begin
case Align of
alTop, alLeft:
SetBounds (Left, Top, NewWidth, NewHeight);
alBottom:
SetBounds (Left, Top-NewHeight+Height, NewWidth, NewHeight);
alRight:
SetBounds (Left-NewWidth+Width, Top, NewWidth, NewHeight);
end;
end;
procedure TDock97.AlignControls (AControl: TControl; var Rect: TRect);
begin
ArrangeToolbars (False);
end;
function CompareDockRowPos (const Item1, Item2, ExtraData: Pointer): Integer; far;
begin
if TCustomToolWindow97(Item1).FDockRow <> TCustomToolWindow97(Item2).FDockRow then
Result := TCustomToolWindow97(Item1).FDockRow - TCustomToolWindow97(Item2).FDockRow
else
Result := TCustomToolWindow97(Item1).FDockPos - TCustomToolWindow97(Item2).FDockPos;
end;
procedure TDock97.ArrangeToolbars (const ClipPoses: Boolean);
{ The main procedure to arrange all the toolbars docked to it }
type
PIntegerArray = ^TIntegerArray;
TIntegerArray = array[0..$7FFFFFFF div SizeOf(Integer)-1] of Integer;
var
LeftRight: Boolean;
EmptySize: Integer;
HighestRow, R, CurDockPos, CurRowPixel, I, J, K, ClientW, ClientH: Integer;
CurRowSize: Integer;
T: TCustomToolWindow97;
NewDockPos: PIntegerArray;
begin
if ClipPoses then
FArrangeToolbarsClipPoses := True;
if (FDisableArrangeToolbars > 0) or (csLoading in ComponentState) then begin
FArrangeToolbarsNeeded := True;
Exit;
end;
Inc (FDisableArrangeToolbars);
try
{ Work around VCL alignment bug when docking toolbars taller or wider than
the client height or width of the form. }
if not(csDesigning in ComponentState) and HandleAllocated then
SetWindowPos (Handle, HWND_TOP, 0, 0, 0, 0,
SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE);
LeftRight := Position in PositionLeftOrRight;
if not HasVisibleToolbars then begin
EmptySize := Ord(FFixAlign);
if csDesigning in ComponentState then
EmptySize := 9;
if not LeftRight then
ChangeWidthHeight (Width, EmptySize)
else
ChangeWidthHeight (EmptySize, Height);
Exit;
end;
{ It can't read the ClientWidth and ClientHeight properties because they
attempt to create a handle, which requires Parent to be set. "ClientW"
and "ClientH" are calculated instead. }
ClientW := Width - FNonClientWidth;
if ClientW < 0 then ClientW := 0;
ClientH := Height - FNonClientHeight;
if ClientH < 0 then ClientH := 0;
{ If LimitToOneRow is True, only use the first row }
if FLimitToOneRow then
for I := 0 to DockList.Count-1 do
with TCustomToolWindow97(DockList[I]) do
FDockRow := 0;
{ Remove any blank rows }
RemoveBlankRows;
{ Ensure DockList is in correct ordering according to DockRow/DockPos }
ListSortEx (DockList, CompareDockRowPos, nil);
ListSortEx (DockVisibleList, CompareDockRowPos, nil);
{ Find highest row number }
HighestRow := GetHighestRow;
{ Find FullSize toolbars and make sure there aren't any other toolbars
on the same row. If there are, shift them down a row. }
R := 0;
while R <= HighestRow do begin
for I := 0 to DockList.Count-1 do
with TCustomToolWindow97(DockList[I]) do
if (FDockRow = R) and FullSize then
for J := 0 to DockList.Count-1 do
if (J <> I) and (TCustomToolWindow97(DockList[J]).FDockRow = R) then begin
for K := 0 to DockList.Count-1 do
with TCustomToolWindow97(DockList[K]) do
if (K <> I) and (FDockRow >= R) then begin
Inc (FDockRow);
if FDockRow > HighestRow then
HighestRow := FDockRow;
end;
Break;
end;
Inc (R);
end;
{ Rebuild the RowInfo, since rows numbers may have shifted }
BuildRowInfo;
HighestRow := RowSizes.Count-1;
{ Adjust DockPos's of toolbars to make sure none of the them overlap }
for R := 0 to HighestRow do begin
CurDockPos := 0;
for I := 0 to DockList.Count-1 do begin
T := TCustomToolWindow97(DockList[I]);
with T do
if (FDockRow = R) and ToolbarVisibleOnDock(T) then begin
if FullSize then
FDockPos := 0
else begin
if FDockPos <= CurDockPos then
FDockPos := CurDockPos
else
CurDockPos := FDockPos;
if not LeftRight then
Inc (CurDockPos, Width)
else
Inc (CurDockPos, Height);
end;
end;
end;
end;
{ Create a temporary array that holds new DockPos's for the toolbars }
GetMem (NewDockPos, DockList.Count * SizeOf(Integer));
try
for I := 0 to DockList.Count-1 do
NewDockPos[I] := TCustomToolWindow97(DockList[I]).FDockPos;
{ Move toolbars that go off the edge of the dock to a fully visible
position if possible }
for R := 0 to HighestRow do begin
if not LeftRight then
CurDockPos := ClientW
else
CurDockPos := ClientH;
for I := DockList.Count-1 downto 0 do begin
T := TCustomToolWindow97(DockList[I]);
with T do
if (FDockRow = R) and ToolbarVisibleOnDock(T) and not FullSize then begin
if not LeftRight then
Dec (CurDockPos, Width)
else
Dec (CurDockPos, Height);
if NewDockPos[I] > CurDockPos then
NewDockPos[I] := CurDockPos;
CurDockPos := NewDockPos[I];
end;
end;
{ Since the above code will make the toolbars go off the left if the
width of all toolbars is more than the width of the dock, push them
back right if needed }
CurDockPos := 0;
for I := 0 to DockList.Count-1 do begin
T := TCustomToolWindow97(DockList[I]);
with T do
if (FDockRow = R) and ToolbarVisibleOnDock(T) and not FullSize then begin
if NewDockPos[I] <= CurDockPos then
NewDockPos[I] := CurDockPos
else
CurDockPos := NewDockPos[I];
if not LeftRight then
Inc (CurDockPos, Width)
else
Inc (CurDockPos, Height);
end;
end;
end;
{ If FArrangeToolbarsClipPoses (ClipPoses) is True, update all the
toolbars' DockPos's to match the actual positions }
if FArrangeToolbarsClipPoses then
for I := 0 to DockList.Count-1 do
TCustomToolWindow97(DockList[I]).FDockPos := NewDockPos[I];
{ Now actually move the toolbars }
CurRowPixel := 0;
for R := 0 to HighestRow do begin
CurRowSize := Longint(RowSizes[R]);
if CurRowSize <> 0 then
Inc (CurRowSize, DockedBorderSize2);
for I := 0 to DockList.Count-1 do begin
T := TCustomToolWindow97(DockList[I]);
with T do
if (FDockRow = R) and ToolbarVisibleOnDock(T) then begin
Inc (FUpdatingBounds);
try
if not LeftRight then begin
J := Width;
if FullSize then J := ClientW;
SetBounds (NewDockPos[I], CurRowPixel, J, CurRowSize)
end
else begin
J := Height;
if FullSize then J := ClientH;
SetBounds (CurRowPixel, NewDockPos[I], CurRowSize, J);
end;
finally
Dec (FUpdatingBounds);
end;
end;
end;
Inc (CurRowPixel, CurRowSize);
end;
finally
FreeMem (NewDockPos);
end;
{ Set the size of the dock }
if not LeftRight then
ChangeWidthHeight (Width, CurRowPixel + FNonClientHeight)
else
ChangeWidthHeight (CurRowPixel + FNonClientWidth, Height);
finally
Dec (FDisableArrangeToolbars);
FArrangeToolbarsNeeded := False;
FArrangeToolbarsClipPoses := False;
end;
end;
procedure TDock97.ChangeDockList (const Insert: Boolean;
const Bar: TCustomToolWindow97);
{ Inserts or removes Bar from DockList }
var
I: Integer;
begin
I := DockList.IndexOf(Bar);
if Insert then begin
if I = -1 then begin
Bar.FreeNotification (Self);
DockList.Add (Bar);
end;
end
else begin
if I <> -1 then
DockList.Delete (I);
end;
ToolbarVisibilityChanged (Bar, False);
end;
procedure TDock97.ToolbarVisibilityChanged (const Bar: TCustomToolWindow97;
const ForceRemove: Boolean);
var
Modified, VisibleOnDock: Boolean;
I: Integer;
begin
Modified := False;
I := DockVisibleList.IndexOf(Bar);
VisibleOnDock := not ForceRemove and ToolbarVisibleOnDock(Bar);
if VisibleOnDock then begin
if I = -1 then begin
DockVisibleList.Add (Bar);
Modified := True;
end;
end
else begin
if I <> -1 then begin
DockVisibleList.Remove (Bar);
Modified := True;
end;
end;
if Modified then begin
ArrangeToolbars (False);
if Assigned(FOnInsertRemoveBar) then
FOnInsertRemoveBar (Self, VisibleOnDock, Bar);
end;
end;
procedure TDock97.Loaded;
begin
inherited;
{ Rearranging is disabled while the component is loading, so now that it's
loaded, rearrange it. }
ArrangeToolbars (False);
end;
procedure TDock97.Notification (AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent is TCustomToolWindow97) then begin
DockList.Remove (AComponent);
DockVisibleList.Remove (AComponent);
end;
end;
function TDock97.GetPalette: HPALETTE;
begin
Result := FBkg.Palette;
end;
procedure TDock97.DrawBackground (const DC: HDC;
const IntersectClippingRect: TRect; const ExcludeClippingRect: PRect;
const DrawRect: TRect);
var
UseBmp: TBitmap;
R2: TRect;
SaveIndex: Integer;
DC2: HDC;
begin
UseBmp := FBkg;
{ When FBkgTransparent is True, it keeps a cached copy of the
background that has the transparent color already translated. Without the
cache, redraws can be very slow.
Note: The cache is cleared in the OnChange event of FBkg }
if FBkgTransparent then begin
if FBkgCache = nil then begin
FBkgCache := TBitmap.Create;
with FBkgCache do begin
Palette := CopyPalette(FBkg.Palette);
Width := FBkg.Width;
Height := FBkg.Height;
Canvas.Brush.Color := Self.Color;
Canvas.BrushCopy (Rect(0, 0, Width, Height), FBkg,
Rect(0, 0, Width, Height), FBkg.Canvas.Pixels[0, Height-1] or $02000000);
end;
end;
UseBmp := FBkgCache;
end;
SaveIndex := SaveDC(DC);
try
with IntersectClippingRect do
IntersectClipRect (DC, Left, Top, Right, Bottom);
if Assigned(ExcludeClippingRect) then
with ExcludeClippingRect^ do
ExcludeClipRect (DC, Left, Top, Right, Bottom);
if UseBmp.Palette <> 0 then begin
SelectPalette (DC, UseBmp.Palette, True);
RealizePalette (DC);
end;
R2 := DrawRect;
while R2.Left < R2.Right do begin
while R2.Top < R2.Bottom do begin
{ Note: versions of Toolbar97 prior to 1.68 used 'UseBmp.Canvas.Handle'
instead of DC2 in the BitBlt call. This was changed because there
seems to be a bug in D2/BCB1's Graphics.pas: if you called
<dockname>.Background.LoadFromFile(<filename>) twice the background
would not be shown. }
DC2 := CreateCompatibleDC(DC);
SelectObject (DC2, UseBmp.Handle);
BitBlt (DC, R2.Left, R2.Top, UseBmp.Width, UseBmp.Height,
DC2, 0, 0, SRCCOPY);
DeleteDC (DC2);
Inc (R2.Top, UseBmp.Height);
end;
R2.Top := DrawRect.Top;
Inc (R2.Left, UseBmp.Width);
end;
finally
{ Restores the clipping region and palette back }
RestoreDC (DC, SaveIndex);
end;
end;
procedure TDock97.Paint;
var
R, R2: TRect;
P1, P2: TPoint;
begin
inherited;
with Canvas do begin
R := ClientRect;
{ Draw dotted border in design mode }
if csDesigning in ComponentState then begin
Pen.Style := psDot;
Pen.Color := clBtnShadow;
Brush.Style := bsClear;
Rectangle (R.Left, R.Top, R.Right, R.Bottom);
Pen.Style := psSolid;
InflateRect (R, -1, -1);
end;
{ Draw the Background }
if UsingBackground then begin
R2 := ClientRect;
{ Make up for nonclient area }
P1 := ClientToScreen(Point(0, 0));
P2 := Parent.ClientToScreen(BoundsRect.TopLeft);
Dec (R2.Left, Left + (P1.X-P2.X));
Dec (R2.Top, Top + (P1.Y-P2.Y));
DrawBackground (Canvas.Handle, R, nil, R2);
end;
end;
end;
procedure TDock97.WMMove (var Message: TWMMove);
begin
inherited;
if UsingBackground then
InvalidateBackgrounds;
end;
procedure TDock97.WMSize (var Message: TWMSize);
begin
inherited;
ArrangeToolbars (False);
if not(csLoading in ComponentState) and Assigned(FOnResize) then
FOnResize (Self);
end;
procedure TDock97.WMNCCalcSize (var Message: TWMNCCalcSize);
begin
inherited;
{ note to self: non-client size is stored in FNonClientWidth &
FNonClientHeight }
with Message.CalcSize_Params^.rgrc[0] do begin
if blTop in BoundLines then Inc (Top);
if blBottom in BoundLines then Dec (Bottom);
if blLeft in BoundLines then Inc (Left);
if blRight in BoundLines then Dec (Right);
end;
end;
procedure TDock97.DrawNCArea (const DrawToDC: Boolean; const ADC: HDC;
const Clip: HRGN);
procedure DrawLine (const DC: HDC; const X1, Y1, X2, Y2: Integer);
begin
MoveToEx (DC, X1, Y1, nil); LineTo (DC, X2, Y2);
end;
var
RW, R, R2, RC: TRect;
DC: HDC;
HighlightPen, ShadowPen, SavePen: HPEN;
FillBrush: HBRUSH;
label 1;
begin
{ This works around WM_NCPAINT problem described at top of source code }
{no! R := Rect(0, 0, Width, Height);}
GetWindowRect (Handle, RW);
R := RW;
OffsetRect (R, -R.Left, -R.Top);
if not DrawToDC then
DC := GetWindowDC(Handle)
else
DC := ADC;
try
{ Use update region }
if not DrawToDC then
SelectNCUpdateRgn (Handle, DC, Clip);
{ Draw BoundLines }
R2 := R;
if (BoundLines <> []) and
((csDesigning in ComponentState) or HasVisibleToolbars) then begin
HighlightPen := CreatePen(PS_SOLID, 1, GetSysColor(COLOR_BTNHIGHLIGHT));
ShadowPen := CreatePen(PS_SOLID, 1, GetSysColor(COLOR_BTNSHADOW));
SavePen := SelectObject(DC, ShadowPen);
if blTop in BoundLines then begin
DrawLine (DC, R.Left, R.Top, R.Right, R.Top);
Inc (R2.Top);
end;
if blLeft in BoundLines then begin
DrawLine (DC, R.Left, R.Top, R.Left, R.Bottom);
Inc (R2.Left);
end;
SelectObject (DC, HighlightPen);
if blBottom in BoundLines then begin
DrawLine (DC, R.Left, R.Bottom-1, R.Right, R.Bottom-1);
Dec (R2.Bottom);
end;
if blRight in BoundLines then begin
DrawLine (DC, R.Right-1, R.Top, R.Right-1, R.Bottom);
Dec (R2.Right);
end;
SelectObject (DC, SavePen);
DeleteObject (ShadowPen);
DeleteObject (HighlightPen);
end;
Windows.GetClientRect (Handle, RC);
if not IsRectEmpty(RC) then begin
{ ^ ExcludeClipRect can't be passed rectangles that have (Bottom < Top) or
(Right < Left) since it doesn't treat them as empty }
MapWindowPoints (Handle, 0, RC, 2);
OffsetRect (RC, -RW.Left, -RW.Top);
if EqualRect(RC, R2) then
{ Skip FillRect because there would be nothing left after ExcludeClipRect }
goto 1;
ExcludeClipRect (DC, RC.Left, RC.Top, RC.Right, RC.Bottom);
end;
FillBrush := CreateSolidBrush(ColorToRGB(Color));
FillRect (DC, R2, FillBrush);
DeleteObject (FillBrush);
1:
finally
if not DrawToDC then
ReleaseDC (Handle, DC);
end;
end;
procedure TDock97.WMNCPaint (var Message: TMessage);
begin
DrawNCArea (False, 0, HRGN(Message.WParam));
end;
procedure DockNCPaintProc (Wnd: HWND; DC: HDC; AppData: Longint);
begin
TDock97(AppData).DrawNCArea (True, DC, 0);
end;
procedure TDock97.WMPrint (var Message: TMessage);
begin
HandleWMPrint (Handle, Message, DockNCPaintProc, Longint(Self));
end;
procedure TDock97.WMPrintClient (var Message: TMessage);
begin
HandleWMPrintClient (Self, Message);
end;
procedure TDock97.CMColorChanged (var Message: TMessage);
begin
if UsingBackground then
{ Erase the cache }
BackgroundChanged (FBkg);
inherited;
end;
procedure TDock97.CMSysColorChange (var Message: TMessage);
begin
inherited;
if UsingBackground then
{ Erase the cache }
BackgroundChanged (FBkg);
end;
{ TDock97 - property access methods }
procedure TDock97.SetAllowDrag (Value: Boolean);
var
I: Integer;
begin
if FAllowDrag <> Value then begin
FAllowDrag := Value;
for I := 0 to ControlCount-1 do
if Controls[I] is TCustomToolWindow97 then
RecalcNCArea (TCustomToolWindow97(Controls[I]));
end;
end;
procedure TDock97.SetBackground (Value: TBitmap);
begin
FBkg.Assign (Value);
end;
function TDock97.UsingBackground: Boolean;
begin
Result := (FBkg.Width <> 0) and (FBkg.Height <> 0);
end;
procedure TDock97.InvalidateBackgrounds;
{ Called after background is changed }
var
I: Integer;
T: TCustomToolWindow97;
begin
Invalidate;
{ Synchronize child toolbars also }
for I := 0 to DockList.Count-1 do begin
T := TCustomToolWindow97(DockList[I]);
with T do
if ToolbarVisibleOnDock(T) then begin
InvalidateDockedNCArea;
Invalidate;
end;
end;
end;
procedure TDock97.BackgroundChanged (Sender: TObject);
begin
{ Erase the cache }
FBkgCache.Free;
FBkgCache := nil;
InvalidateBackgrounds;
end;
procedure TDock97.SetBackgroundOnToolbars (Value: Boolean);
begin
if FBkgOnToolbars <> Value then begin
FBkgOnToolbars := Value;
InvalidateBackgrounds;
end;
end;
procedure TDock97.SetBackgroundTransparent (Value: Boolean);
begin
if FBkgTransparent <> Value then begin
FBkgTransparent := Value;
if UsingBackground then
{ Erase the cache }
BackgroundChanged (FBkg);
end;
end;
procedure TDock97.SetBoundLines (Value: TDockBoundLines);
var
X, Y: Integer;
B: TDockBoundLines;
begin
if FBoundLines <> Value then begin
FBoundLines := Value;
X := 0;
Y := 0;
B := BoundLines; { optimization }
if blTop in B then Inc (Y);
if blBottom in B then Inc (Y);
if blLeft in B then Inc (X);
if blRight in B then Inc (X);
FNonClientWidth := X;
FNonClientHeight := Y;
RecalcNCArea (Self);
end;
end;
procedure TDock97.SetFixAlign (Value: Boolean);
begin
if FFixAlign <> Value then begin
FFixAlign := Value;
ArrangeToolbars (False);
end;
end;
procedure TDock97.SetPosition (Value: TDockPosition);
begin
if (FPosition <> Value) and (ControlCount <> 0) then
raise EInvalidOperation.Create(STB97DockCannotChangePosition);
FPosition := Value;
case Position of
dpTop: Align := alTop;
dpBottom: Align := alBottom;
dpLeft: Align := alLeft;
dpRight: Align := alRight;
end;
end;
function TDock97.GetToolbarCount: Integer;
begin
Result := DockVisibleList.Count;
end;
function TDock97.GetToolbars (Index: Integer): TCustomToolWindow97;
begin
Result := TCustomToolWindow97(DockVisibleList[Index]);
end;
function TDock97.GetVersion: TToolbar97Version;
begin
Result := Toolbar97VersionPropText;
end;
procedure TDock97.SetVersion (const Value: TToolbar97Version);
begin
{ write method required for the property to show up in Object Inspector }
end;
{ TFloatingWindowParent - Internal }
constructor TFloatingWindowParent.Create (AOwner: TComponent);
begin
{ Don't use TForm's Create since it attempts to load a form resource, which
TFloatingWindowParent doesn't have. }
CreateNew (AOwner {$IFDEF VER93} , 0 {$ENDIF});
end;
procedure TFloatingWindowParent.CreateParams (var Params: TCreateParams);
begin
inherited;
{ The WS_EX_TOOLWINDOW style is needed to prevent the form from having
a taskbar button when Toolbar97 is used in a DLL or OCX. }
Params.ExStyle := Params.ExStyle or WS_EX_TOOLWINDOW;
end;
procedure TFloatingWindowParent.CMShowingChanged (var Message: TMessage);
const
ShowFlags: array[Boolean] of UINT = (
SWP_NOSIZE or SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_HIDEWINDOW,
SWP_NOSIZE or SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_SHOWWINDOW);
begin
{ Must override TCustomForm/TForm's CM_SHOWINGCHANGED handler so that the
form doesn't get activated when Visible is set to True. }
SetWindowPos (WindowHandle, 0, 0, 0, 0, 0, ShowFlags[Showing and FShouldShow]);
end;
procedure TFloatingWindowParent.CMDialogKey (var Message: TCMDialogKey);
begin
{ If Escape if pressed on a floating toolbar, return focus to the form }
if (Message.CharCode = VK_ESCAPE) and (KeyDataToShiftState(Message.KeyData) = []) and
Assigned(ParentForm) then begin
ParentForm.SetFocus;
Message.Result := 1;
end
else
inherited;
end;
{ Global procedures }
procedure CustomLoadToolbarPositions (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
const ReadIntProc: TPositionReadIntProc;
const ReadStringProc: TPositionReadStringProc; const ExtraData: Pointer);
var
Rev: Integer;
function FindDock (AName: String): TDock97;
var
I: Integer;
begin
Result := nil;
for I := 0 to Form.ComponentCount-1 do
if (Form.Components[I] is TDock97) and (Form.Components[I].Name = AName) then begin
Result := TDock97(Form.Components[I]);
Break;
end;
end;
procedure ReadValues (const Toolbar: TCustomToolWindow97; const NewDock: TDock97);
var
Pos: TPoint;
LastDockName: String;
ADock: TDock97;
begin
with Toolbar do begin
DockRow := ReadIntProc(Name, rvDockRow, DockRow, ExtraData);
DockPos := ReadIntProc(Name, rvDockPos, DockPos, ExtraData);
Pos.X := ReadIntProc(Name, rvFloatLeft, 0, ExtraData);
Pos.Y := ReadIntProc(Name, rvFloatTop, 0, ExtraData);
ReadPositionData (ReadIntProc, ReadStringProc, ExtraData);
FFloatingTopLeft := Pos;
if Assigned(NewDock) then
Parent := NewDock
else begin
Parent := Form;
SetBounds (Pos.X, Pos.Y, Width, Height);
MoveOnScreen (True);
if (Rev >= 3) and FUseLastDock then begin
LastDockName := ReadStringProc(Name, rvLastDock, '', ExtraData);
if LastDockName <> '' then begin
ADock := FindDock(LastDockName);
if Assigned(ADock) then
LastDock := ADock;
end;
end;
end;
ArrangeControls;
DoneReadingPositionData (ReadIntProc, ReadStringProc, ExtraData);
end;
end;
var
DocksDisabled: TList;
I: Integer;
ToolWindow: TComponent;
ADock: TDock97;
DockedToName: String;
begin
DocksDisabled := TList.Create;
try
with Form do
for I := 0 to ComponentCount-1 do
if Components[I] is TDock97 then begin
TDock97(Components[I]).BeginUpdate;
DocksDisabled.Add (Components[I]);
end;
for I := 0 to Form.ComponentCount-1 do begin
ToolWindow := Form.Components[I];
if ToolWindow is TCustomToolWindow97 then
with TCustomToolWindow97(ToolWindow) do begin
if Name = '' then
raise Exception.Create (STB97ToolWinNameNotSet);
Rev := ReadIntProc(Name, rvRev, 0, ExtraData);
if Rev in [2..3] then begin
Visible := ReadIntProc(Name, rvVisible, Ord(Visible), ExtraData) <> 0;
DockedToName := ReadStringProc(Name, rvDockedTo, '', ExtraData);
if DockedToName <> '' then begin
if DockedToName <> rdDockedToFloating then begin
ADock := FindDock(DockedToName);
if (ADock <> nil) and (ADock.FAllowDrag) then
ReadValues (TCustomToolWindow97(ToolWindow), ADock);
end
else
ReadValues (TCustomToolWindow97(ToolWindow), nil);
end;
end;
end;
end;
finally
for I := DocksDisabled.Count-1 downto 0 do
TDock97(DocksDisabled[I]).EndUpdate;
DocksDisabled.Free;
end;
end;
procedure CustomSaveToolbarPositions (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
const WriteIntProc: TPositionWriteIntProc;
const WriteStringProc: TPositionWriteStringProc; const ExtraData: Pointer);
var
I: Integer;
N, L: String;
begin
for I := 0 to Form.ComponentCount-1 do
if Form.Components[I] is TCustomToolWindow97 then
with TCustomToolWindow97(Form.Components[I]) do begin
if Name = '' then
raise Exception.Create (STB97ToolwinNameNotSet);
if not Docked then
N := rdDockedToFloating
else begin
if DockedTo.FAllowDrag then begin
N := DockedTo.Name;
if N = '' then
raise Exception.Create (STB97ToolwinDockedToNameNotSet);
end
else
N := '';
end;
L := '';
if Assigned(FLastDock) then
L := FLastDock.Name;
WriteIntProc (Name, rvRev, rdCurrentRev, ExtraData);
WriteIntProc (Name, rvVisible, Ord(Visible), ExtraData);
WriteStringProc (Name, rvDockedTo, N, ExtraData);
WriteStringProc (Name, rvLastDock, L, ExtraData);
WriteIntProc (Name, rvDockRow, FDockRow, ExtraData);
WriteIntProc (Name, rvDockPos, FDockPos, ExtraData);
WriteIntProc (Name, rvFloatLeft, FFloatingTopLeft.X, ExtraData);
WriteIntProc (Name, rvFloatTop, FFloatingTopLeft.Y, ExtraData);
WritePositionData (WriteIntProc, WriteStringProc, ExtraData);
end;
end;
type
PIniReadWriteData = ^TIniReadWriteData;
TIniReadWriteData = record
IniFile: TIniFile;
SectionNamePrefix: String;
end;
function IniReadInt (const ToolbarName, Value: String; const Default: Longint;
const ExtraData: Pointer): Longint; far;
begin
Result := PIniReadWriteData(ExtraData).IniFile.ReadInteger(
PIniReadWriteData(ExtraData).SectionNamePrefix + ToolbarName, Value, Default);
end;
function IniReadString (const ToolbarName, Value, Default: String;
const ExtraData: Pointer): String; far;
begin
Result := PIniReadWriteData(ExtraData).IniFile.ReadString(
PIniReadWriteData(ExtraData).SectionNamePrefix + ToolbarName, Value, Default);
end;
procedure IniWriteInt (const ToolbarName, Value: String; const Data: Longint;
const ExtraData: Pointer); far;
begin
PIniReadWriteData(ExtraData).IniFile.WriteInteger (
PIniReadWriteData(ExtraData).SectionNamePrefix + ToolbarName, Value, Data);
end;
procedure IniWriteString (const ToolbarName, Value, Data: String;
const ExtraData: Pointer); far;
begin
PIniReadWriteData(ExtraData).IniFile.WriteString (
PIniReadWriteData(ExtraData).SectionNamePrefix + ToolbarName, Value, Data);
end;
procedure IniLoadToolbarPositions (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
const Filename, SectionNamePrefix: String);
var
Data: TIniReadWriteData;
begin
Data.IniFile := TIniFile.Create(Filename);
try
Data.SectionNamePrefix := SectionNamePrefix;
CustomLoadToolbarPositions (Form, IniReadInt, IniReadString, @Data);
finally
Data.IniFile.Free;
end;
end;
procedure IniSaveToolbarPositions (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
const Filename, SectionNamePrefix: String);
var
Data: TIniReadWriteData;
begin
Data.IniFile := TIniFile.Create(Filename);
try
Data.SectionNamePrefix := SectionNamePrefix;
CustomSaveToolbarPositions (Form, IniWriteInt, IniWriteString, @Data);
finally
Data.IniFile.Free;
end;
end;
function RegReadInt (const ToolbarName, Value: String; const Default: Longint;
const ExtraData: Pointer): Longint; far;
begin
Result := TRegIniFile(ExtraData).ReadInteger(ToolbarName, Value, Default);
end;
function RegReadString (const ToolbarName, Value, Default: String;
const ExtraData: Pointer): String; far;
begin
Result := TRegIniFile(ExtraData).ReadString(ToolbarName, Value, Default);
end;
procedure RegWriteInt (const ToolbarName, Value: String; const Data: Longint;
const ExtraData: Pointer); far;
begin
TRegIniFile(ExtraData).WriteInteger (ToolbarName, Value, Data);
end;
procedure RegWriteString (const ToolbarName, Value, Data: String;
const ExtraData: Pointer); far;
begin
TRegIniFile(ExtraData).WriteString (ToolbarName, Value, Data);
end;
procedure RegLoadToolbarPositions (const Form: TCustomForm; const BaseRegistryKey: String);
begin
RegLoadToolbarPositionsEx (Form, HKEY_CURRENT_USER, BaseRegistryKey);
end;
procedure RegLoadToolbarPositionsEx (const Form: TCustomForm; const RootKey: HKEY; const BaseRegistryKey: String);
var
Reg: TRegIniFile;
begin
Reg := TRegIniFile.Create('');
try
Reg.RootKey := RootKey;
Reg.OpenKey (BaseRegistryKey, True); { assigning to RootKey resets the current key }
CustomLoadToolbarPositions (Form, RegReadInt, RegReadString, Reg);
finally
Reg.Free;
end;
end;
procedure RegSaveToolbarPositions (const Form: TCustomForm; const BaseRegistryKey: String);
begin
RegSaveToolbarPositionsEx (Form, HKEY_CURRENT_USER, BaseRegistryKey);
end;
procedure RegSaveToolbarPositionsEx (const Form: TCustomForm; const RootKey: HKEY; const BaseRegistryKey: String);
var
Reg: TRegIniFile;
begin
Reg := TRegIniFile.Create('');
try
Reg.RootKey := RootKey;
Reg.OpenKey (BaseRegistryKey, True); { assigning to RootKey resets the current key }
CustomSaveToolbarPositions (Form, RegWriteInt, RegWriteString, Reg);
finally
Reg.Free;
end;
end;
{ TCustomToolWindow97 - Internal }
constructor TCustomToolWindow97.Create (AOwner: TComponent);
begin
inherited;
GetToolbarDockPosProc := GetToolbarDockPos;
ControlStyle := ControlStyle +
[csAcceptsControls, csClickEvents, csDoubleClicks, csSetCaption] -
[csCaptureMouse{capturing is done manually}, csOpaque];
InstallHookProc (ToolbarHookProc,
[hpSendActivateApp, hpSendWindowPosChanged, hpPreDestroy],
csDesigning in ComponentState);
GetParams (FParams);
FActivateParent := True;
FBorderStyle := bsSingle;
FDockableTo := [dpTop, dpBottom, dpLeft, dpRight];
FCloseButton := True;
FResizable := True;
FShowCaption := True;
FHideWhenInactive := True;
FUseLastDock := True;
FDockPos := -1;
Color := clBtnFace;
end;
destructor TCustomToolWindow97.Destroy;
begin
inherited;
FDockForms.Free; { must be done after 'inherited' because Notification accesses FDockForms }
FFloatParent.Free;
UninstallHookProc (ToolbarHookProc);
end;
function TCustomToolWindow97.HasParent: Boolean;
begin
if Parent is TFloatingWindowParent then
Result := False
else
Result := inherited HasParent;
end;
function TCustomToolWindow97.GetParentComponent: TComponent;
begin
if Parent is TFloatingWindowParent then
Result := nil
else
Result := inherited GetParentComponent;
end;
procedure TCustomToolWindow97.SetInactiveCaption (Value: Boolean);
begin
if csDesigning in ComponentState then
Value := False;
if FInactiveCaption <> Value then begin
FInactiveCaption := Value;
InvalidateFloatingNCArea ([twrdCaption]);
end;
end;
procedure TCustomToolWindow97.Moved;
begin
if not(csLoading in ComponentState) and (FDisableOnMove <= 0) then
DoMove;
end;
procedure TCustomToolWindow97.WMMove (var Message: TWMMove);
begin
inherited;
FMoved := True;
if Docked and DockedTo.UsingBackground then begin
{ Needs to redraw so that background is lined up with the dock at the
new position }
InvalidateDockedNCArea;
{ To minimize flicker, InvalidateRect is called with the Erase parameter
set to False instead of calling the Invalidate method }
if HandleAllocated then
InvalidateRect (Handle, nil, False);
end;
Moved;
end;
procedure TCustomToolWindow97.WMSize (var Message: TWMSize);
begin
inherited;
if not(csLoading in ComponentState) and Assigned(FOnResize) then
FOnResize (Self);
end;
procedure TCustomToolWindow97.WMGetMinMaxInfo (var Message: TWMGetMinMaxInfo);
begin
inherited;
{ Because the window uses the WS_THICKFRAME style (but not for the usual
purpose), it must process the WM_GETMINMAXINFO message to remove the
minimum and maximum size limits it imposes by default. }
with Message.MinMaxInfo^ do begin
with ptMinTrackSize do begin
X := 1;
Y := 1;
{ Note to self: Don't put GetMinimumSize code here, since
ClientWidth/Height values are sometimes invalid during a RecreateWnd }
end;
with ptMaxTrackSize do begin
{ Because of the 16-bit (signed) size limitations of Windows 95,
Smallints must be used instead of Integers or Longints }
X := High(Smallint);
Y := High(Smallint);
end;
end;
end;
procedure TCustomToolWindow97.WMEnable (var Message: TWMEnable);
begin
inherited;
{ When a modal dialog is displayed and the toolbar window gets disabled as
a result, remove its topmost flag. }
if FFloatingMode = fmOnTopOfAllForms then
UpdateTopmostFlag;
end;
function TCustomToolWindow97.GetShowingState: Boolean;
var
HideFloatingToolbars: Boolean;
ParentForm, MDIParentForm: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
begin
Result := Showing and (FHidden = 0);
if not Docked and not(csDesigning in ComponentState) then begin
HideFloatingToolbars := FFloatingMode = fmOnTopOfParentForm;
if HideFloatingToolbars then begin
ParentForm := GetToolWindowParentForm(Self);
MDIParentForm := GetMDIParent(ParentForm);
if Assigned(ParentForm) and Assigned(MDIParentForm) then begin
HideFloatingToolbars := not ParentForm.HandleAllocated or
not MDIParentForm.HandleAllocated;
if not HideFloatingToolbars then begin
HideFloatingToolbars := IsIconic(Application.Handle) or
not IsWindowVisible(ParentForm.Handle) or IsIconic(ParentForm.Handle);
if MDIParentForm <> ParentForm then
HideFloatingToolbars := HideFloatingToolbars or
not IsWindowVisible(MDIParentForm.Handle) or IsIconic(MDIParentForm.Handle);
end;
end;
end;
Result := Result and not (HideFloatingToolbars or (FHideWhenInactive and not ApplicationIsActive));
end;
end;
procedure TCustomToolWindow97.UpdateVisibility;
begin
SetInactiveCaption (not Docked and (not FHideWhenInactive and not ApplicationIsActive));
if HandleAllocated and (IsWindowVisible(Handle) <> GetShowingState) then
Perform (CM_SHOWINGCHANGED, 0, 0);
end;
procedure TCustomToolWindow97.UpdateTopmostFlag;
function IsTopmost (const Wnd: HWND): Boolean;
begin
Result := GetWindowLong(Wnd, GWL_EXSTYLE) and WS_EX_TOPMOST <> 0;
end;
const
Wnds: array[Boolean] of HWND = (HWND_NOTOPMOST, HWND_TOPMOST);
var
ShouldBeTopmost: Boolean;
begin
if HandleAllocated then begin
if FFloatingMode = fmOnTopOfAllForms then
ShouldBeTopmost := IsWindowEnabled(Handle)
else
ShouldBeTopmost := IsTopmost(HWND(GetWindowLong(Handle, GWL_HWNDPARENT)));
if ShouldBeTopmost <> IsTopmost(Handle) then
{ ^ it must check if it already was topmost or non-topmost or else
it causes problems on Win95/98 for some reason }
SetWindowPos (Handle, Wnds[ShouldBeTopmost], 0, 0, 0, 0,
SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE);
end;
end;
procedure TCustomToolWindow97.CMShowingChanged (var Message: TMessage);
function GetPrevWnd (W: HWND): HWND;
var
Done: Boolean;
ParentWnd: HWND;
label 1;
begin
Result := W;
repeat
Done := True;
Result := GetWindow(Result, GW_HWNDPREV);
ParentWnd := Result;
while ParentWnd <> 0 do begin
ParentWnd := HWND(GetWindowLong(ParentWnd, GWL_HWNDPARENT));
if ParentWnd = W then begin
Done := False;
Break;
end;
end;
until Done;
end;
const
ShowFlags: array[Boolean] of UINT = (
SWP_NOSIZE or SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_HIDEWINDOW,
SWP_NOSIZE or SWP_NOMOVE or SWP_NOZORDER or SWP_NOACTIVATE or SWP_SHOWWINDOW);
var
Show: Boolean;
Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
begin
{ inherited isn't called since TCustomToolWindow97 handles CM_SHOWINGCHANGED
itself. For reference, the original TWinControl implementation is:
const
ShowFlags: array[Boolean] of Word = (
SWP_NOSIZE + SWP_NOMOVE + SWP_NOZORDER + SWP_NOACTIVATE + SWP_HIDEWINDOW,
SWP_NOSIZE + SWP_NOMOVE + SWP_NOZORDER + SWP_NOACTIVATE + SWP_SHOWWINDOW);
begin
SetWindowPos(FHandle, 0, 0, 0, 0, 0, ShowFlags[FShowing]);
end;
}
if HandleAllocated then begin
Show := GetShowingState;
if Parent is TFloatingWindowParent then begin
if Show then begin
{ If the toolbar is floating, set its "owner window" to the parent form
so that the toolbar window always stays on top of the form }
if FFloatingMode = fmOnTopOfParentForm then begin
Form := GetMDIParent(GetToolWindowParentForm(Self));
if Assigned(Form) and Form.HandleAllocated and
(HWND(GetWindowLong(Handle, GWL_HWNDPARENT)) <> Form.Handle) then begin
SetWindowLong (Handle, GWL_HWNDPARENT, Longint(Form.Handle));
{ Following is necessarily to make it immediately realize the
GWL_HWNDPARENT change }
SetWindowPos (Handle, GetPrevWnd(Form.Handle), 0, 0, 0, 0, SWP_NOACTIVATE or
SWP_NOMOVE or SWP_NOSIZE);
end;
UpdateTopmostFlag;
end
else begin
SetWindowLong (Handle, GWL_HWNDPARENT, Longint(Application.Handle));
UpdateTopmostFlag;
end;
end
else
UpdateTopmostFlag;
{ Show/hide the TFloatingWindowParent. The following lines had to be
added to fix a problem that was in 1.65d/e. In 1.65d/e, it always
kept TFloatingWindowParent visible (this change was made to improve
compatibility with D4's Actions), but this for some odd reason would
cause a Stack Overflow error if the program's main form was closed
while a floating toolwindow was focused. (This problem did not occur
on NT.) }
TFloatingWindowParent(Parent).FShouldShow := Show;
Parent.Perform (CM_SHOWINGCHANGED, 0, 0);
end;
SetWindowPos (Handle, 0, 0, 0, 0, 0, ShowFlags[Show]);
if not Show and (GetActiveWindow = Handle) then
{ If the window is hidden but is still active, find and activate a
different window }
SetActiveWindow (FindTopLevelWindow(Handle));
end;
end;
procedure TCustomToolWindow97.CreateParams (var Params: TCreateParams);
const
ThickFrames: array[Boolean] of DWORD = (0, WS_THICKFRAME);
begin
inherited;
{ Disable complete redraws when size changes. CS_H/VREDRAW cause flicker
and are not necessary for this control at run time }
if not(csDesigning in ComponentState) then
with Params.WindowClass do
Style := Style and not(CS_HREDRAW or CS_VREDRAW);
{ When floating... }
if not(Parent is TDock97) then
with Params do begin
{ Note: WS_THICKFRAME and WS_BORDER styles are included to ensure that
sizing grips are displayed on child controls with scrollbars. The
thick frame or border is not drawn by Windows; TCustomToolWindow97
handles all border drawing by itself. }
if not(csDesigning in ComponentState) then
Style := WS_POPUP or WS_BORDER or ThickFrames[FResizable]
else
Style := Style or WS_BORDER or ThickFrames[FResizable];
{ The WS_EX_TOOLWINDOW style is needed so there isn't a taskbar button
for the toolbar when FloatingMode = fmOnTopOfAllForms. }
ExStyle := WS_EX_TOOLWINDOW;
end;
end;
procedure TCustomToolWindow97.Notification (AComponent: TComponent; Operation: TOperation);
begin
inherited;
if Operation = opRemove then begin
if AComponent = FDefaultDock then
FDefaultDock := nil
else
if AComponent = FLastDock then
FLastDock := nil
else begin
if Assigned(FDockForms) then begin
FDockForms.Remove (AComponent);
if FDockForms.Count = 0 then begin
FDockForms.Free;
FDockForms := nil;
end;
end;
if Assigned(FFloatParent) and (AComponent = FFloatParent.FParentForm) then begin
if Parent = FFloatParent then begin
if FFloatingMode = fmOnTopOfParentForm then
Parent := nil
else
FFloatParent.FParentForm := nil;
end
else begin
FFloatParent.Free;
FFloatParent := nil;
end;
end;
end;
end;
end;
procedure TCustomToolWindow97.MoveOnScreen (const OnlyIfFullyOffscreen: Boolean);
{ Moves the (floating) toolbar so that it is fully (or at least mostly) in
view on the screen }
var
R, S, Test: TRect;
begin
if not Docked then begin
R := BoundsRect;
S := GetDesktopAreaOfMonitorContainingRect(R);
if OnlyIfFullyOffscreen and IntersectRect(Test, R, S) then
Exit;
if R.Right > S.Right then
OffsetRect (R, S.Right - R.Right, 0);
if R.Bottom > S.Bottom then
OffsetRect (R, 0, S.Bottom - R.Bottom);
if R.Left < S.Left then
OffsetRect (R, S.Left - R.Left, 0);
if R.Top < S.Top then
OffsetRect (R, 0, S.Top - R.Top);
BoundsRect := R;
end;
end;
procedure TCustomToolWindow97.ReadPositionData (const ReadIntProc: TPositionReadIntProc;
const ReadStringProc: TPositionReadStringProc; const ExtraData: Pointer);
begin
end;
procedure TCustomToolWindow97.DoneReadingPositionData (const ReadIntProc: TPositionReadIntProc;
const ReadStringProc: TPositionReadStringProc; const ExtraData: Pointer);
begin
end;
procedure TCustomToolWindow97.WritePositionData (const WriteIntProc: TPositionWriteIntProc;
const WriteStringProc: TPositionWriteStringProc; const ExtraData: Pointer);
begin
end;
procedure TCustomToolWindow97.InitializeOrdering;
begin
end;
procedure TCustomToolWindow97.GetDockRowSize (var AHeightOrWidth: Integer);
begin
if Docked then
with DockedTo do begin
BuildRowInfo;
AHeightOrWidth := DockedTo.GetRowSize(FDockRow, Self);
end
else
GetBarSize (AHeightOrWidth, dtNotDocked);
end;
procedure TCustomToolWindow97.SizeChanging (const AWidth, AHeight: Integer);
begin
end;
procedure TCustomToolWindow97.ReadSavedAtRunTime (Reader: TReader);
begin
FSavedAtRunTime := Reader.ReadBoolean;
end;
procedure TCustomToolWindow97.WriteSavedAtRunTime (Writer: TWriter);
begin
{ WriteSavedAtRunTime only called when not(csDesigning in ComponentState) }
Writer.WriteBoolean (True);
end;
procedure TCustomToolWindow97.DefineProperties (Filer: TFiler);
begin
inherited;
Filer.DefineProperty ('SavedAtRunTime', ReadSavedAtRunTime,
WriteSavedAtRunTime, not(csDesigning in ComponentState));
end;
procedure TCustomToolWindow97.Loaded;
var
R: TRect;
begin
inherited;
{ Adjust coordinates if it was initially floating }
if not FSavedAtRunTime and not(csDesigning in ComponentState) and
(Parent is TFloatingWindowParent) then begin
R := BoundsRect;
MapWindowPoints (ValidToolWindowParentForm(Self).Handle, 0, R, 2);
BoundsRect := R;
MoveOnScreen (False);
end;
InitializeOrdering;
{ Arranging of controls is disabled while component was loading, so rearrange
it now }
ArrangeControls;
end;
procedure TCustomToolWindow97.BeginUpdate;
begin
Inc (FDisableArrangeControls);
end;
procedure TCustomToolWindow97.EndUpdate;
begin
Dec (FDisableArrangeControls);
if FArrangeNeeded and (FDisableArrangeControls = 0) then
ArrangeControls;
end;
procedure TCustomToolWindow97.AddDockForm (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF});
begin
if Form = nil then Exit;
if FDockForms = nil then FDockForms := TList.Create;
if FDockForms.IndexOf(Form) = -1 then begin
FDockForms.Add (Form);
Form.FreeNotification (Self);
end;
end;
procedure TCustomToolWindow97.RemoveDockForm (const Form: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF});
begin
if Assigned(FDockForms) then begin
FDockForms.Remove (Form);
if FDockForms.Count = 0 then begin
FDockForms.Free;
FDockForms := nil;
end;
end;
end;
procedure TCustomToolWindow97.CustomArrangeControls (const PreviousDockType: TDockType;
const DockingTo: TDock97; const Resize: Boolean);
var
WH: Integer;
Size: TPoint;
begin
if (FDisableArrangeControls > 0) or
{ Prevent flicker while loading or destroying }
(csLoading in ComponentState) or
{ This will not work if it's destroying }
(csDestroying in ComponentState) or
(Parent = nil) or
(Parent.HandleAllocated and (csDestroying in Parent.ComponentState)) then begin
FArrangeNeeded := True;
Exit;
end;
FArrangeNeeded := False;
Inc (FDisableArrangeControls);
try
Size := OrderControls(True, PreviousDockType, DockingTo);
with Size do
if Resize then begin
if Docked then begin
GetDockRowSize (WH);
if not(DockedTo.Position in PositionLeftOrRight) then begin
if WH > Y then Y := WH;
if FullSize then
X := (DockedTo.Width-DockedTo.NonClientWidth) - FNonClientWidth;
end
else begin
if WH > X then X := WH;
if FullSize then
Y := (DockedTo.Height-DockedTo.NonClientHeight) - FNonClientHeight;
end;
end;
Inc (X, FNonClientWidth);
Inc (Y, FNonClientHeight);
if (Width <> X) or (Height <> Y) then begin
Inc (FUpdatingBounds);
try
SetBounds (Left, Top, X, Y);
finally
Dec (FUpdatingBounds);
end;
end;
end;
finally
Dec (FDisableArrangeControls);
end;
end;
procedure TCustomToolWindow97.ArrangeControls;
begin
CustomArrangeControls (GetDockTypeOf(DockedTo), DockedTo, True);
end;
procedure TCustomToolWindow97.AlignControls (AControl: TControl; var Rect: TRect);
{ VCL calls this whenever any child controls in the toolbar are moved, sized,
inserted, etc. It doesn't need to make use of the AControl and Rect
parameters. }
begin
if Params.CallAlignControls then
inherited;
ArrangeControls;
end;
procedure TCustomToolWindow97.SetBounds (ALeft, ATop, AWidth, AHeight: Integer);
begin
if (FUpdatingBounds = 0) and ((AWidth <> Width) or (AHeight <> Height)) then
SizeChanging (AWidth, AHeight);
{ This allows you to drag the toolbar around the dock at design time }
if (csDesigning in ComponentState) and not(csLoading in ComponentState) and
Docked and (FUpdatingBounds = 0) and ((ALeft <> Left) or (ATop <> Top)) then begin
if not(DockedTo.Position in PositionLeftOrRight) then begin
FDockRow := DockedTo.GetDesignModeRowOf(ATop+(Height div 2));
FDockPos := ALeft;
end
else begin
FDockRow := DockedTo.GetDesignModeRowOf(ALeft+(Width div 2));
FDockPos := ATop;
end;
inherited SetBounds (Left, Top, AWidth, AHeight); { only pass any size changes }
DockedTo.ArrangeToolbars (False); { let ArrangeToolbars take care of position changes }
end
else begin
inherited;
if not(csLoading in ComponentState) and not Docked and (FUpdatingBounds = 0) then
FFloatingTopLeft := BoundsRect.TopLeft;
end;
end;
procedure TCustomToolWindow97.SetParent (AParent: TWinControl);
procedure UpdateFloatingToolWindows;
begin
if Parent is TFloatingWindowParent then begin
if FloatingToolWindows = nil then
FloatingToolWindows := TList.Create;
if FloatingToolWindows.IndexOf(Self) = -1 then
FloatingToolWindows.Add (Self);
SetBounds (FFloatingTopLeft.X, FFloatingTopLeft.Y, Width, Height);
end
else
if Assigned(FloatingToolWindows) then begin
FloatingToolWindows.Remove (Self);
if FloatingToolWindows.Count = 0 then begin
FloatingToolWindows.Free;
FloatingToolWindows := nil;
end;
end;
end;
function ParentToDockedTo (const Ctl: TWinControl): TDock97;
begin
if Ctl is TDock97 then
Result := TDock97(Ctl)
else
Result := nil;
end;
var
NewFloatParent: TFloatingWindowParent;
OldDockedTo, NewDockedTo: TDock97;
OldParent: TWinControl;
begin
if (AParent <> nil) and not(AParent is TDock97) and
not(AParent is {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF}) then
raise EInvalidOperation.Create(STB97ToolwinParentNotAllowed);
if not(csDesigning in ComponentState) and
(AParent is {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF}) then begin
if (FFloatParent = nil) or (FFloatParent.FParentForm <> AParent) then begin
NewFloatParent := TFloatingWindowParent.Create(nil);
try
with NewFloatParent do begin
TWinControl(FParentForm) := AParent;
Name := Format('TB97FloatingWindowParent_%.8x', [Longint(NewFloatParent)]);
{ ^ Must assign a unique name. In previous versions, reading in
components at run-time that had no name caused them to get assigned
names like "_1" because a component with no name -- the
TFloatingWindowParent form -- already existed. }
BorderStyle := bsNone;
SetBounds (0, 0, 0, 0);
ShowHint := True;
Visible := True;
end;
except
NewFloatParent.Free;
raise;
end;
FFloatParent := NewFloatParent;
end;
AParent.FreeNotification (Self);
AParent := FFloatParent;
end;
OldDockedTo := ParentToDockedTo(Parent);
NewDockedTo := ParentToDockedTo(AParent);
if AParent = Parent then begin
{ Even though AParent is the same as the current Parent, this code is
necessary because when the VCL destroys the parent of the tool window,
it calls TWinControl.Remove to set FParent instead of using SetParent.
However TControl.Destroy does call SetParent(nil), so it is
eventually notified of the change before it is destroyed. }
FDockedTo := ParentToDockedTo(Parent);
FDocked := FDockedTo <> nil;
UpdateFloatingToolWindows;
end
else begin
if not(csDestroying in ComponentState) and Assigned(AParent) then begin
if Assigned(FOnDockChanging) then
FOnDockChanging (Self);
if Assigned(FOnDockChangingEx) then
FOnDockChangingEx (Self, NewDockedTo);
if Assigned(FOnRecreating) then
FOnRecreating (Self);
end;
{ Before changing between docked and floating state (and vice-versa)
or between docks, increment FHidden and call UpdateVisibility to hide the
toolbar. This prevents any flashing while it's being moved }
Inc (FHidden);
Inc (FDisableOnMove);
try
UpdateVisibility;
if Assigned(OldDockedTo) then
OldDockedTo.BeginUpdate;
if Assigned(NewDockedTo) then
NewDockedTo.BeginUpdate;
Inc (FUpdatingBounds);
try
if Assigned(AParent) then begin
DoDockChangingHidden (NewDockedTo);
{ Must pre-arrange controls in new dock orientation before changing
the Parent }
if FLastDockTypeSet then
CustomArrangeControls (FLastDockType, NewDockedTo, False);
end;
FArrangeNeeded := True; { force EndUpdate to rearrange }
BeginUpdate;
try
if Parent is TDock97 then begin
if not FUseLastDock then
TDock97(Parent).ChangeDockList (False, Self);
TDock97(Parent).ToolbarVisibilityChanged (Self, True);
end;
OldParent := Parent;
{ Ensure that the handle is destroyed now so that any messages in the queue
get flushed. This is neccessary since existing messages may reference
FDockedTo or FDocked, which is changed below. }
inherited SetParent (nil);
{ ^ Note to self: SetParent is used instead of DestroyHandle because it does
additional processing }
FDockedTo := NewDockedTo;
FDocked := FDockedTo <> nil;
try
inherited;
except
{ Failure is rare, but just in case, restore FDockedTo and FDocked back. }
FDockedTo := ParentToDockedTo(Parent);
FDocked := FDockedTo <> nil;
raise;
end;
{ Force a recalc of NC sizes now so that FNonClientWidth &
FNonClientHeight are accurate, even if the control didn't receive
a WM_NCCALCSIZE message because it has no handle. }
CalculateNonClientSizes (nil);
if OldParent is TFloatingWindowParent then begin
if FFloatParent = OldParent then FFloatParent := nil;
OldParent.Free;
end;
if Parent is TDock97 then begin
if FUseLastDock then begin
LastDock := TDock97(Parent); { calls ChangeDockList if LastDock changes }
TDock97(Parent).ToolbarVisibilityChanged (Self, False);
end
else
TDock97(Parent).ChangeDockList (True, Self);
end;
UpdateFloatingToolWindows;
finally
EndUpdate;
end;
if Assigned(Parent) then begin
FLastDockType := GetDockTypeOf(NewDockedTo);
FLastDockTypeSet := True;
end;
finally
Dec (FUpdatingBounds);
if Assigned(NewDockedTo) then
NewDockedTo.EndUpdate;
if Assigned(OldDockedTo) then
OldDockedTo.EndUpdate;
end;
finally
Dec (FDisableOnMove);
Dec (FHidden);
UpdateVisibility;
{ ^ The above UpdateVisibility call not only updates the tool window's
visibility after decrementing FHidden, it also sets the
active/inactive state of the caption. }
end;
if Assigned(Parent) then
Moved;
if not(csDestroying in ComponentState) and Assigned(AParent) then begin
if Assigned(FOnRecreated) then
FOnRecreated (Self);
if Assigned(FOnDockChanged) then
FOnDockChanged (Self);
end;
end;
end;
procedure TCustomToolWindow97.AddDockedNCAreaToSize (var S: TPoint;
const LeftRight: Boolean);
var
TopLeft, BottomRight: TPoint;
begin
GetDockedNCArea (TopLeft, BottomRight, LeftRight);
Inc (S.X, TopLeft.X + BottomRight.X);
Inc (S.Y, TopLeft.Y + BottomRight.Y);
end;
procedure TCustomToolWindow97.AddFloatingNCAreaToSize (var S: TPoint);
var
TopLeft, BottomRight: TPoint;
begin
GetFloatingNCArea (TopLeft, BottomRight);
Inc (S.X, TopLeft.X + BottomRight.X);
Inc (S.Y, TopLeft.Y + BottomRight.Y);
end;
procedure TCustomToolWindow97.GetDockedNCArea (var TopLeft, BottomRight: TPoint;
const LeftRight: Boolean);
var
Z: Integer;
begin
Z := DockedBorderSize; { code optimization... }
TopLeft.X := Z;
TopLeft.Y := Z;
BottomRight.X := Z;
BottomRight.Y := Z;
if not LeftRight then
Inc (TopLeft.X, DragHandleSizes[CloseButtonWhenDocked, DragHandleStyle])
else
Inc (TopLeft.Y, DragHandleSizes[CloseButtonWhenDocked, DragHandleStyle]);
end;
function TCustomToolWindow97.GetFloatingBorderSize: TPoint;
{ Returns size of a thick border. Note that, depending on the Windows version,
this may not be the same as the actual window metrics since it draws its
own border }
const
XMetrics: array[Boolean] of Integer = (SM_CXDLGFRAME, SM_CXFRAME);
YMetrics: array[Boolean] of Integer = (SM_CYDLGFRAME, SM_CYFRAME);
begin
Result.X := GetSystemMetrics(XMetrics[Resizable]);
Result.Y := GetSystemMetrics(YMetrics[Resizable]);
end;
procedure TCustomToolWindow97.GetFloatingNCArea (var TopLeft, BottomRight: TPoint);
begin
with GetFloatingBorderSize do begin
TopLeft.X := X;
TopLeft.Y := Y;
if ShowCaption then
Inc (TopLeft.Y, GetSmallCaptionHeight);
BottomRight.X := X;
BottomRight.Y := Y;
end;
end;
function GetCaptionRect (const Control: TCustomToolWindow97;
const AdjustForBorder, MinusCloseButton: Boolean): TRect;
begin
Result := Rect(0, 0, Control.ClientWidth, GetSmallCaptionHeight-1);
if MinusCloseButton then
Dec (Result.Right, Result.Bottom);
if AdjustForBorder then
with Control.GetFloatingBorderSize do
OffsetRect (Result, X, Y);
end;
function GetCloseButtonRect (const Control: TCustomToolWindow97;
const AdjustForBorder: Boolean): TRect;
begin
Result := GetCaptionRect(Control, AdjustForBorder, False);
Result.Left := Result.Right - (GetSmallCaptionHeight-1);
end;
function GetDockedCloseButtonRect (const Control: TCustomToolWindow97;
const LeftRight: Boolean): TRect;
var
X, Y, Z: Integer;
begin
Z := DragHandleSizes[Control.CloseButtonWhenDocked, Control.FDragHandleStyle] - 3;
if not LeftRight then begin
X := DockedBorderSize+1;
Y := DockedBorderSize;
end
else begin
X := (Control.ClientWidth + DockedBorderSize) - Z;
Y := DockedBorderSize+1;
end;
Result := Bounds(X, Y, Z, Z);
end;
procedure TCustomToolWindow97.CalculateNonClientSizes (R: PRect);
{ Recalculates FNonClientWidth and FNonClientHeight.
If R isn't nil, it deflates the rectangle to exclude the non-client area. }
var
Temp: TRect;
TL, BR: TPoint;
Z: Integer;
begin
if R = nil then
R := @Temp;
if not Docked then begin
GetFloatingNCArea (TL, BR);
FNonClientWidth := TL.X + BR.X;
FNonClientHeight := TL.Y + BR.Y;
with R^ do begin
Inc (Left, TL.X);
Inc (Top, TL.Y);
Dec (Right, BR.X);
Dec (Bottom, BR.Y);
end;
end
else begin
InflateRect (R^, -DockedBorderSize, -DockedBorderSize);
FNonClientWidth := DockedBorderSize2;
FNonClientHeight := DockedBorderSize2;
if DockedTo.FAllowDrag then begin
Z := DragHandleSizes[FCloseButtonWhenDocked, FDragHandleStyle];
if not(DockedTo.Position in PositionLeftOrRight) then begin
Inc (R.Left, Z);
Inc (FNonClientWidth, Z);
end
else begin
Inc (R.Top, Z);
Inc (FNonClientHeight, Z);
end;
end;
end;
end;
procedure TCustomToolWindow97.WMNCCalcSize (var Message: TWMNCCalcSize);
begin
{ Doesn't call inherited since it overrides the normal NC sizes }
Message.Result := 0;
CalculateNonClientSizes (@Message.CalcSize_Params^.rgrc[0]);
end;
procedure TCustomToolWindow97.DrawFloatingNCArea (const DrawToDC: Boolean;
const ADC: HDC; const Clip: HRGN; RedrawWhat: TToolWindowNCRedrawWhat);
{ Redraws all the non-client area (the border, title bar, and close button) of
the toolbar when it is floating. }
const
COLOR_GRADIENTACTIVECAPTION = 27;
COLOR_GRADIENTINACTIVECAPTION = 28;
CaptionBkColors: array[Boolean, Boolean] of Integer =
((COLOR_ACTIVECAPTION, COLOR_INACTIVECAPTION),
(COLOR_GRADIENTACTIVECAPTION, COLOR_GRADIENTINACTIVECAPTION));
CaptionTextColors: array[Boolean] of Integer =
(COLOR_CAPTIONTEXT, COLOR_INACTIVECAPTIONTEXT);
function GradientCaptionsEnabled: Boolean;
const
SPI_GETGRADIENTCAPTIONS = $1008; { Win98/NT5 only }
var
S: BOOL;
begin
Result := False;
if NewStyleControls and SystemParametersInfo(SPI_GETGRADIENTCAPTIONS, 0, @S, 0) then
Result := S;
end;
procedure Win3DrawCaption (const DC: HDC; const R: TRect);
{ Emulates DrawCaption, which isn't supported in Win 3.x }
const
Ellipsis = '...';
var
R2: TRect;
SaveTextColor, SaveBkColor: TColorRef;
SaveFont: HFONT;
Cap: String;
function CaptionTextWidth: Integer;
var
Size: TSize;
begin
GetTextExtentPoint32 (DC, PChar(Cap), Length(Cap), Size);
Result := Size.cx;
end;
begin
R2 := R;
{ Fill the rectangle }
FillRect (DC, R2, GetSysColorBrush(CaptionBkColors[False, FInactiveCaption]));
Inc (R2.Left);
Dec (R2.Right);
SaveFont := SelectObject(DC, CreateFont(-11, 0, 0, 0, FW_NORMAL, 0, 0, 0, 0, 0, 0, 0, 0, 'MS Sans Serif'));
{ Add ellipsis to caption if necessary }
Cap := Caption;
if CaptionTextWidth > R2.Right-R2.Left then begin
Cap := Cap + Ellipsis;
while (CaptionTextWidth > R2.Right-R2.Left) and (Length(Cap) > 4) do
Delete (Cap, Length(Cap)-Length(Ellipsis), 1)
end;
{ Draw the text }
SaveBkColor := SetBkColor(DC, GetSysColor(CaptionBkColors[False, FInactiveCaption]));
SaveTextColor := SetTextColor(DC, GetSysColor(CaptionTextColors[FInactiveCaption]));
DrawText (DC, PChar(Cap), Length(Cap), R2, DT_SINGLELINE or DT_NOPREFIX or DT_VCENTER);
SetTextColor (DC, SaveTextColor);
SetBkColor (DC, SaveBkColor);
DeleteObject (SelectObject(DC, SaveFont));
end;
const
CloseButtonState: array[Boolean] of UINT = (0, DFCS_PUSHED);
ActiveCaptionFlags: array[Boolean] of UINT = (DC_ACTIVE, 0);
DC_GRADIENT = $20;
GradientCaptionFlags: array[Boolean] of UINT = (0, DC_GRADIENT);
var
DC: HDC;
R: TRect;
Gradient: Boolean;
NewDrawCaption: function(p1: HWND; p2: HDC; const p3: TRect; p4: UINT): BOOL; stdcall;
SavePen: HPEN;
SaveIndex: Integer;
TL, BR: TPoint;
begin
if not DrawToDC then
RedrawWhat := RedrawWhat + ValidateFloatingNCArea;
if Docked or not HandleAllocated then Exit;
if not DrawToDC then
DC := GetWindowDC(Handle)
else
DC := ADC;
try
{ Use update region }
if not DrawToDC then
SelectNCUpdateRgn (Handle, DC, Clip);
Gradient := GradientCaptionsEnabled;
{ Border }
if twrdBorder in RedrawWhat then begin
{ This works around WM_NCPAINT problem described at top of source code }
{no! R := Rect(0, 0, Width, Height);}
GetWindowRect (Handle, R); OffsetRect (R, -R.Left, -R.Top);
DrawEdge (DC, R, EDGE_RAISED, BF_RECT);
SaveIndex := SaveDC(DC);
GetFloatingNCArea (TL, BR);
with R do
ExcludeClipRect (DC, Left + TL.X, Top + TL.Y, Right - BR.X, Bottom - BR.Y);
InflateRect (R, -2, -2);
FillRect (DC, R, GetSysColorBrush(COLOR_BTNFACE));
RestoreDC (DC, SaveIndex);
end;
if ShowCaption then begin
if (twrdCaption in RedrawWhat) and FCloseButton and (twrdCloseButton in RedrawWhat) then
SaveIndex := SaveDC(DC)
else
SaveIndex := 0;
try
if SaveIndex <> 0 then
with GetCloseButtonRect(Self, True) do
{ Reduces flicker }
ExcludeClipRect (DC, Left, Top, Right, Bottom);
{ Caption }
if twrdCaption in RedrawWhat then begin
R := GetCaptionRect(Self, True, FCloseButton);
if NewStyleControls then begin
{ Use a dynamic import of DrawCaption since it's Win95/NT 4.0 only.
Also note that Delphi's Win32 help for DrawCaption is totally wrong!
I got updated info from www.microsoft.com/msdn/sdk/ }
NewDrawCaption := GetProcAddress(GetModuleHandle(user32), 'DrawCaption');
NewDrawCaption (Handle, DC, R, DC_TEXT or DC_SMALLCAP or
ActiveCaptionFlags[FInactiveCaption] or
GradientCaptionFlags[Gradient]);
end
else
Win3DrawCaption (DC, R);
{ Line below caption }
R := GetCaptionRect(Self, True, False);
SavePen := SelectObject(DC, CreatePen(PS_SOLID, 1, GetSysColor(COLOR_BTNFACE)));
MoveToEx (DC, R.Left, R.Bottom, nil);
LineTo (DC, R.Right, R.Bottom);
DeleteObject (SelectObject(DC, SavePen));
end;
finally
if SaveIndex <> 0 then
RestoreDC (DC, SaveIndex);
end;
{ Close button }
if FCloseButton then begin
if twrdCloseButton in RedrawWhat then begin
R := GetCloseButtonRect(Self, True);
InflateRect (R, -1, -1);
DrawFrameControl (DC, R, DFC_CAPTION, DFCS_CAPTIONCLOSE or
CloseButtonState[FCloseButtonDown]);
end;
if twrdCaption in RedrawWhat then begin
{ Caption-colored frame around close button }
R := GetCloseButtonRect(Self, True);
FrameRect (DC, R, GetSysColorBrush(CaptionBkColors[Gradient, FInactiveCaption]));
end;
end;
end;
finally
if not DrawToDC then
ReleaseDC (Handle, DC);
end;
end;
procedure TCustomToolWindow97.ValidateDockedNCArea;
var
Msg: TMsg;
begin
{ Remove any WM_TB97PaintDockedNCArea messages from the queue }
if HandleAllocated then
while PeekMessage(Msg, Handle, WM_TB97PaintDockedNCArea,
WM_TB97PaintDockedNCArea, PM_REMOVE or PM_NOYIELD) do begin
if Msg.Message = WM_QUIT then begin
{ If a WM_QUIT message was posted with PostQuitMessage (and not
PostMessage(..., WM_QUIT, ...) which is NOT equivalent), it isn't
returned the same way as ordinary messages. First,
PeekMessage/GetMessage can return it even if the specified range
doesn't include WM_QUIT. Also, PeekMessage/GetMessage will only
return the WM_QUIT message if there are no other user messages in the
queue. So if a WM_QUIT message is returned here, there can't be any
WM_TB97PaintDockedNCArea messages in the queue. }
PostQuitMessage (Msg.wParam); { repost it }
Break;
end;
end;
end;
function TCustomToolWindow97.ValidateFloatingNCArea: TToolWindowNCRedrawWhat;
var
Msg: TMsg;
begin
Result := [];
{ Remove any WM_TB97PaintFloatingNCArea messages from the queue }
if HandleAllocated then
while PeekMessage(Msg, Handle, WM_TB97PaintFloatingNCArea,
WM_TB97PaintFloatingNCArea, PM_REMOVE or PM_NOYIELD) do begin
if Msg.Message = WM_QUIT then begin
{ If a WM_QUIT message was posted with PostQuitMessage (and not
PostMessage(..., WM_QUIT, ...) which is NOT equivalent), it isn't
returned the same way as ordinary messages. First,
PeekMessage/GetMessage can return it even if the specified range
doesn't include WM_QUIT. Also, PeekMessage/GetMessage will only
return the WM_QUIT message if there are no other user messages in the
queue. So if a WM_QUIT message is returned here, there can't be any
WM_TB97PaintFloatingNCArea messages in the queue. }
PostQuitMessage (Msg.wParam); { repost it }
Break;
end;
Result := Result + TToolWindowNCRedrawWhat(Byte(Msg.lParam));
end;
end;
procedure TCustomToolWindow97.InvalidateDockedNCArea;
begin
ValidateDockedNCArea;
if HandleAllocated and IsWindowVisible(Handle) then
PostMessage (Handle, WM_TB97PaintDockedNCArea, 0, 0);
end;
procedure TCustomToolWindow97.InvalidateFloatingNCArea (const RedrawWhat: TToolWindowNCRedrawWhat);
var
Old: TToolWindowNCRedrawWhat;
begin
Old := ValidateFloatingNCArea;
if HandleAllocated and IsWindowVisible(Handle) then
PostMessage (Handle, WM_TB97PaintFloatingNCArea, 0, Byte(RedrawWhat + Old));
end;
procedure TCustomToolWindow97.WMTB97PaintDockedNCArea (var Message: TMessage);
begin
DrawDockedNCArea (False, 0, 0);
end;
procedure TCustomToolWindow97.WMTB97PaintFloatingNCArea (var Message: TMessage);
begin
DrawFloatingNCArea (False, 0, 0, TToolWindowNCRedrawWhat(Byte(Message.LParam)));
end;
procedure TCustomToolWindow97.DrawDockedNCArea (const DrawToDC: Boolean;
const ADC: HDC; const Clip: HRGN);
{ Redraws all the non-client area of the toolbar when it is docked. }
var
DC: HDC;
R: TRect;
DockType: TDockType;
X, Y, Y2, Y3, S, SaveIndex: Integer;
R2, R3, R4: TRect;
P1, P2: TPoint;
Brush: HBRUSH;
Clr: TColorRef;
UsingBackground, B: Boolean;
procedure DrawRaisedEdge (R: TRect; const FillInterior: Boolean);
const
FillMiddle: array[Boolean] of UINT = (0, BF_MIDDLE);
begin
DrawEdge (DC, R, BDR_RAISEDINNER, BF_RECT or FillMiddle[FillInterior]);
end;
const
CloseButtonState: array[Boolean] of UINT = (0, DFCS_PUSHED);
begin
if not DrawToDC then
ValidateDockedNCArea;
if not Docked or not HandleAllocated then Exit;
if not DrawToDC then
DC := GetWindowDC(Handle)
else
DC := ADC;
try
{ Use update region }
if not DrawToDC then
SelectNCUpdateRgn (Handle, DC, Clip);
{ This works around WM_NCPAINT problem described at top of source code }
{no! R := Rect(0, 0, Width, Height);}
GetWindowRect (Handle, R); OffsetRect (R, -R.Left, -R.Top);
if not(DockedTo.Position in PositionLeftOrRight) then
DockType := dtTopBottom
else
DockType := dtLeftRight;
Brush := CreateSolidBrush(ColorToRGB(Color));
UsingBackground := DockedTo.UsingBackground and DockedTo.FBkgOnToolbars;
{ Border }
if BorderStyle = bsSingle then
DrawRaisedEdge (R, False)
else
FrameRect (DC, R, Brush);
R2 := R;
InflateRect (R2, -1, -1);
if not UsingBackground then
FrameRect (DC, R2, Brush);
{ Draw the Background }
if UsingBackground then begin
R2 := R;
P1 := DockedTo.ClientToScreen(Point(0, 0));
P2 := DockedTo.Parent.ClientToScreen(DockedTo.BoundsRect.TopLeft);
Dec (R2.Left, Left + DockedTo.Left + (P1.X-P2.X));
Dec (R2.Top, Top + DockedTo.Top + (P1.Y-P2.Y));
InflateRect (R, -1, -1);
GetWindowRect (Handle, R4);
R3 := ClientRect;
with ClientToScreen(Point(0, 0)) do
OffsetRect (R3, X-R4.Left, Y-R4.Top);
DockedTo.DrawBackground (DC, R, @R3, R2);
end;
{ The drag handle at the left, or top }
if DockedTo.FAllowDrag then begin
SaveIndex := SaveDC(DC);
if DockType <> dtLeftRight then
Y2 := ClientHeight
else
Y2 := ClientWidth;
Inc (Y2, DockedBorderSize);
Y3 := Y2;
S := DragHandleSizes[FCloseButtonWhenDocked, FDragHandleStyle];
if FDragHandleStyle <> dhNone then begin
X := DockedBorderSize + DragHandleOffsets[FCloseButtonWhenDocked, FDragHandleStyle];
Y := DockedBorderSize;
if FCloseButtonWhenDocked then begin
if DockType <> dtLeftRight then
Inc (Y, S - 2)
else
Dec (Y3, S - 2);
end;
Clr := GetSysColor(COLOR_BTNHIGHLIGHT);
for B := False to (FDragHandleStyle = dhDouble) do begin
if DockType <> dtLeftRight then
R := Rect(X, Y, X+3, Y2)
else
R := Rect(Y, X, Y3, X+3);
DrawRaisedEdge (R, True);
if DockType <> dtLeftRight then
SetPixelV (DC, X, Y2-1, Clr)
else
SetPixelV (DC, Y2-1, X, Clr);
ExcludeClipRect (DC, R.Left, R.Top, R.Right, R.Bottom);
Inc (X, 3);
end;
end;
{ Close button }
if FCloseButtonWhenDocked then begin
R := GetDockedCloseButtonRect(Self, DockType = dtLeftRight);
DrawFrameControl (DC, R, DFC_CAPTION,
DFCS_CAPTIONCLOSE or CloseButtonState[FCloseButtonDown]);
ExcludeClipRect (DC, R.Left, R.Top, R.Right, R.Bottom);
end;
if not UsingBackground then begin
if DockType <> dtLeftRight then
R := Rect(DockedBorderSize, DockedBorderSize,
DockedBorderSize+S, Y2)
else
R := Rect(DockedBorderSize, DockedBorderSize,
Y2, DockedBorderSize+S);
FillRect (DC, R, Brush);
end;
RestoreDC (DC, SaveIndex);
end;
DeleteObject (Brush);
finally
if not DrawToDC then
ReleaseDC (Handle, DC);
end;
end;
procedure TCustomToolWindow97.WMNCPaint (var Message: TMessage);
begin
{ Don't call inherited because it overrides the default NC painting }
if Docked then
DrawDockedNCArea (False, 0, HRGN(Message.WParam))
else
DrawFloatingNCArea (False, 0, HRGN(Message.WParam), twrdAll);
end;
procedure ToolWindowNCPaintProc (Wnd: HWND; DC: HDC; AppData: Longint);
begin
with TCustomToolWindow97(AppData) do begin
if Docked then
DrawDockedNCArea (True, DC, 0)
else
DrawFloatingNCArea (True, DC, 0, twrdAll);
end;
end;
procedure TCustomToolWindow97.WMPrint (var Message: TMessage);
begin
HandleWMPrint (Handle, Message, ToolWindowNCPaintProc, Longint(Self));
end;
procedure TCustomToolWindow97.WMPrintClient (var Message: TMessage);
begin
HandleWMPrintClient (Self, Message);
end;
procedure TCustomToolWindow97.Paint;
var
R, R2, R3: TRect;
P1, P2: TPoint;
begin
inherited;
if Docked and DockedTo.UsingBackground and DockedTo.FBkgOnToolbars then begin
R := ClientRect;
R2 := R;
P1 := DockedTo.ClientToScreen(Point(0, 0));
P2 := DockedTo.Parent.ClientToScreen(DockedTo.BoundsRect.TopLeft);
Dec (R2.Left, Left + DockedTo.Left + (P1.X-P2.X));
Dec (R2.Top, Top + DockedTo.Top + (P1.Y-P2.Y));
GetWindowRect (Handle, R3);
with ClientToScreen(Point(0, 0)) do begin
Inc (R2.Left, R3.Left-X);
Inc (R2.Top, R3.Top-Y);
end;
DockedTo.DrawBackground (Canvas.Handle, R, nil, R2);
end;
end;
function TCustomToolWindow97.GetPalette: HPALETTE;
begin
if Docked and DockedTo.UsingBackground then
Result := DockedTo.FBkg.Palette
else
Result := 0;
end;
function TCustomToolWindow97.PaletteChanged (Foreground: Boolean): Boolean;
begin
Result := inherited PaletteChanged(Foreground);
if Result and not Foreground then begin
{ There seems to be a bug in Delphi's palette handling. When the form is
inactive and another window realizes a palette, docked TToolbar97s
weren't getting redrawn. So this workaround code was added. }
InvalidateDockedNCArea;
Invalidate;
end;
end;
procedure DrawDragRect (const DC: HDC; const NewRect, OldRect: PRect;
const NewSize, OldSize: TSize; const Brush: HBRUSH; BrushLast: HBRUSH);
{ Draws a dragging outline, hiding the old one if neccessary. This is
completely flicker free, unlike the old DrawFocusRect method. In case
you're wondering, I got a lot of ideas from the MFC sources.
Either NewRect or OldRect can be nil or empty. }
function CreateNullRegion: HRGN;
var
R: TRect;
begin
SetRectEmpty (R);
Result := CreateRectRgnIndirect(R);
end;
var
SaveIndex: Integer;
rgnNew, rgnOutside, rgnInside, rgnLast, rgnUpdate: HRGN;
R: TRect;
begin
rgnLast := 0;
rgnUpdate := 0;
{ First, determine the update region and select it }
if NewRect = nil then begin
SetRectEmpty (R);
rgnOutside := CreateRectRgnIndirect(R);
end
else begin
R := NewRect^;
rgnOutside := CreateRectRgnIndirect(R);
InflateRect (R, -NewSize.cx, -NewSize.cy);
IntersectRect (R, R, NewRect^);
end;
rgnInside := CreateRectRgnIndirect(R);
rgnNew := CreateNullRegion;
CombineRgn (rgnNew, rgnOutside, rgnInside, RGN_XOR);
if BrushLast = 0 then
BrushLast := Brush;
if OldRect <> nil then begin
{ Find difference between new region and old region }
rgnLast := CreateNullRegion;
with OldRect^ do
SetRectRgn (rgnOutside, Left, Top, Right, Bottom);
R := OldRect^;
InflateRect (R, -OldSize.cx, -OldSize.cy);
IntersectRect (R, R, OldRect^);
SetRectRgn (rgnInside, R.Left, R.Top, R.Right, R.Bottom);
CombineRgn (rgnLast, rgnOutside, rgnInside, RGN_XOR);
{ Only diff them if brushes are the same }
if Brush = BrushLast then begin
rgnUpdate := CreateNullRegion;
CombineRgn (rgnUpdate, rgnLast, rgnNew, RGN_XOR);
end;
end;
{ Save the DC state so that the clipping region can be restored }
SaveIndex := SaveDC(DC);
try
if (Brush <> BrushLast) and (OldRect <> nil) then begin
{ Brushes are different -- erase old region first }
SelectClipRgn (DC, rgnLast);
GetClipBox (DC, R);
SelectObject (DC, BrushLast);
PatBlt (DC, R.Left, R.Top, R.Right-R.Left, R.Bottom-R.Top, PATINVERT);
end;
{ Draw into the update/new region }
if rgnUpdate <> 0 then
SelectClipRgn (DC, rgnUpdate)
else
SelectClipRgn (DC, rgnNew);
GetClipBox (DC, R);
SelectObject (DC, Brush);
PatBlt (DC, R.Left, R.Top, R.Right-R.Left, R.Bottom-R.Top, PATINVERT);
finally
{ Clean up DC }
RestoreDC (DC, SaveIndex);
end;
{ Free regions }
if rgnNew <> 0 then DeleteObject (rgnNew);
if rgnOutside <> 0 then DeleteObject (rgnOutside);
if rgnInside <> 0 then DeleteObject (rgnInside);
if rgnLast <> 0 then DeleteObject (rgnLast);
if rgnUpdate <> 0 then DeleteObject (rgnUpdate);
end;
procedure TCustomToolWindow97.DrawDraggingOutline (const DC: HDC;
const NewRect, OldRect: PRect; const NewDocking, OldDocking: Boolean);
function CreateHalftoneBrush: HBRUSH;
const
GrayPattern: array[0..7] of Word =
($5555, $AAAA, $5555, $AAAA, $5555, $AAAA, $5555, $AAAA);
var
GrayBitmap: HBITMAP;
begin
GrayBitmap := CreateBitmap(8, 8, 1, 1, @GrayPattern);
Result := CreatePatternBrush(GrayBitmap);
DeleteObject (GrayBitmap);
end;
var
NewSize, OldSize: TSize;
Brush: HBRUSH;
begin
Brush := CreateHalftoneBrush;
try
with GetFloatingBorderSize do begin
if NewDocking then NewSize.cx := 1 else NewSize.cx := X;
NewSize.cy := NewSize.cx;
if OldDocking then OldSize.cx := 1 else OldSize.cx := X;
OldSize.cy := OldSize.cx;
end;
DrawDragRect (DC, NewRect, OldRect, NewSize, OldSize, Brush, Brush);
finally
DeleteObject (Brush);
end;
end;
procedure TCustomToolWindow97.CMColorChanged (var Message: TMessage);
begin
{ Make sure non-client area is redrawn }
InvalidateDockedNCArea;
inherited; { the inherited handler calls Invalidate }
end;
procedure TCustomToolWindow97.CMTextChanged (var Message: TMessage);
begin
inherited;
{ Update the title bar to use the new Caption }
InvalidateFloatingNCArea ([twrdCaption]);
end;
procedure TCustomToolWindow97.CMVisibleChanged (var Message: TMessage);
begin
if not(csDesigning in ComponentState) and Docked then
DockedTo.ToolbarVisibilityChanged (Self, False);
inherited;
if Assigned(FOnVisibleChanged) then
FOnVisibleChanged (Self);
end;
procedure TCustomToolWindow97.WMActivate (var Message: TWMActivate);
var
ParentForm: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
begin
if Docked or (csDesigning in ComponentState) then begin
inherited;
Exit;
end;
ParentForm := GetMDIParent(GetToolWindowParentForm(Self));
if Assigned(ParentForm) and ParentForm.HandleAllocated then
SendMessage (ParentForm.Handle, WM_NCACTIVATE, Ord(Message.Active <> WA_INACTIVE), 0);
if Message.Active <> WA_INACTIVE then begin
{ This works around a "gotcha" in TCustomForm.CMShowingChanged. When a form
is hidden, it uses the internal VCL function FindTopMostWindow to
find a new active window. The problem is that handles of floating
toolbars on the form being hidden can be returned by
FindTopMostWindow, so the following code is used to prevent floating
toolbars on the hidden form from being left active. }
if not IsWindowVisible(Handle) then
{ ^ Calling IsWindowVisible with a floating toolbar handle will
always return False if its parent form is hidden since the
WH_CALLWNDPROC hook automatically updates the toolbars'
visibility. }
{ Find and activate a window besides this toolbar }
SetActiveWindow (FindTopLevelWindow(Handle))
else
{ If the toolbar is being activated and the previous active window wasn't
its parent form, the form is activated instead. This is done so that if
the application is deactivated while a floating toolbar was active and
the application is reactivated again, it returns focus to the form. }
if Assigned(ParentForm) and ParentForm.HandleAllocated and
(Message.ActiveWindow <> ParentForm.Handle) then
SetActiveWindow (ParentForm.Handle);
end;
end;
procedure TCustomToolWindow97.WMMouseActivate (var Message: TWMMouseActivate);
var
ParentForm, MDIParentForm: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
begin
if Docked or (csDesigning in ComponentState) then
inherited
else begin
{ When floating, prevent the toolbar from activating when clicked.
This is so it doesn't take the focus away from the window that had it }
Message.Result := MA_NOACTIVATE;
{ Similar to calling BringWindowToTop, but doesn't activate it }
SetWindowPos (Handle, HWND_TOP, 0, 0, 0, 0,
SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE);
{ Since it is returning MA_NOACTIVATE, activate the form instead. }
ParentForm := GetToolWindowParentForm(Self);
MDIParentForm := GetMDIParent(ParentForm);
if (FFloatingMode = fmOnTopOfParentForm) and FActivateParent and
Assigned(MDIParentForm) and (GetActiveWindow <> Handle) then begin
{ ^ Note to self: The GetActiveWindow check must be in there so that
double-clicks work properly on controls like Edits }
if MDIParentForm.HandleAllocated then
SetActiveWindow (MDIParentForm.Handle);
if (MDIParentForm <> ParentForm) and { if it's an MDI child form }
ParentForm.HandleAllocated then
BringWindowToTop (ParentForm.Handle);
end;
end;
end;
procedure TCustomToolWindow97.BeginMoving (const InitX, InitY: Integer);
type
PDockedSize = ^TDockedSize;
TDockedSize = record
Dock: TDock97;
Size: TPoint;
end;
var
DockList: TList;
NewDockedSizes: TList; {items are pointers to TDockedSizes}
MouseOverDock: TDock97;
MoveRect: TRect;
PreventDocking, PreventFloating: Boolean;
ScreenDC: HDC;
OldCursor: HCURSOR;
NPoint, DPoint: TPoint;
procedure Dropped;
var
NewDockRow: Integer;
Before: Boolean;
MoveRectClient: TRect;
C: Integer;
begin
if MouseOverDock <> nil then begin
MoveRectClient := MoveRect;
MapWindowPoints (0, MouseOverDock.Handle, MoveRectClient, 2);
if not(MouseOverDock.Position in PositionLeftOrRight) then
C := (MoveRectClient.Top+MoveRectClient.Bottom) div 2
else
C := (MoveRectClient.Left+MoveRectClient.Right) div 2;
NewDockRow := MouseOverDock.GetRowOf(C, Before);
if Before then
MouseOverDock.InsertRowBefore (NewDockRow)
else
if FullSize and
(MouseOverDock.GetNumberOfToolbarsOnRow(NewDockRow, Self) <> 0) then begin
Inc (NewDockRow);
MouseOverDock.InsertRowBefore (NewDockRow);
end;
FDockRow := NewDockRow;
if not(MouseOverDock.Position in PositionLeftOrRight) then
FDockPos := MoveRectClient.Left
else
FDockPos := MoveRectClient.Top;
Parent := MouseOverDock;
DockedTo.ArrangeToolbars (True);
end
else begin
FFloatingTopLeft := MoveRect.TopLeft;
if DockedTo <> nil then
Parent := ValidToolWindowParentForm(Self)
else
SetBounds (FFloatingTopLeft.X, FFloatingTopLeft.Y, Width, Height);
end;
{ Make sure it doesn't go completely off the screen }
MoveOnScreen (True);
end;
procedure MouseMoved;
var
OldMouseOverDock: TDock97;
OldMoveRect: TRect;
Pos: TPoint;
function CheckIfCanDockTo (Control: TDock97): Boolean;
const
DockSensX = 32;
DockSensY = 20;
var
R, S, Temp: TRect;
I: Integer;
Sens: Integer;
begin
with Control do begin
Result := False;
GetWindowRect (Handle, R);
for I := 0 to NewDockedSizes.Count-1 do
with PDockedSize(NewDockedSizes[I])^ do begin
if Dock <> Control then Continue;
S := Bounds(Pos.X-MulDiv(Size.X-1, NPoint.X, DPoint.X),
Pos.Y-MulDiv(Size.Y-1, NPoint.Y, DPoint.Y),
Size.X, Size.Y);
Break;
end;
if (R.Left = R.Right) or (R.Top = R.Bottom) then begin
if not(Control.Position in PositionLeftOrRight) then
InflateRect (R, 0, 1)
else
InflateRect (R, 1, 0);
end;
{ Like Office 97, distribute ~32 pixels of extra dock detection area
to the left side if the toolbar was grabbed at the left, both sides
if the toolbar was grabbed at the middle, or the right side if
toolbar was grabbed at the right. If outside, don't try to dock. }
Sens := MulDiv(DockSensX, NPoint.X, DPoint.X);
if (Pos.X < R.Left-(DockSensX-Sens)) or (Pos.X > R.Right-1+Sens) then
Exit;
{ Don't try to dock to the left or right if pointer is above or below
the boundaries of the dock }
if (Control.Position in PositionLeftOrRight) and
((Pos.Y < R.Top) or (Pos.Y >= R.Bottom)) then
Exit;
{ And also distribute ~20 pixels of extra dock detection area to
the top or bottom side }
Sens := MulDiv(DockSensY, NPoint.Y, DPoint.Y);
if (Pos.Y < R.Top-(DockSensY-Sens)) or (Pos.Y > R.Bottom-1+Sens) then
Exit;
Result := IntersectRect(Temp, R, S);
end;
end;
var
R, R2: TRect;
I: Integer;
Dock: TDock97;
Accept: Boolean;
TL, BR: TPoint;
begin
OldMouseOverDock := MouseOverDock;
OldMoveRect := MoveRect;
GetCursorPos (Pos);
{ Check if it can dock }
MouseOverDock := nil;
if not PreventDocking then
for I := 0 to DockList.Count-1 do begin
Dock := DockList[I];
if CheckIfCanDockTo(Dock) then begin
MouseOverDock := Dock;
Accept := True;
if Assigned(MouseOverDock.FOnRequestDock) then
MouseOverDock.FOnRequestDock (MouseOverDock, Self, Accept);
if Accept then
Break
else
MouseOverDock := nil;
end;
end;
{ If not docking, clip the point so it doesn't get dragged under the
taskbar }
if MouseOverDock = nil then begin
R := GetDesktopAreaOfMonitorContainingPoint(Pos);
if Pos.X < R.Left then Pos.X := R.Left;
if Pos.X > R.Right then Pos.X := R.Right;
if Pos.Y < R.Top then Pos.Y := R.Top;
if Pos.Y > R.Bottom then Pos.Y := R.Bottom;
end;
for I := 0 to NewDockedSizes.Count-1 do
with PDockedSize(NewDockedSizes[I])^ do begin
if Dock <> MouseOverDock then Continue;
MoveRect := Bounds(Pos.X-MulDiv(Size.X-1, NPoint.X, DPoint.X),
Pos.Y-MulDiv(Size.Y-1, NPoint.Y, DPoint.Y),
Size.X, Size.Y);
Break;
end;
{ Make sure title bar (or at least part of the toolbar) is still accessible
if it's dragged almost completely off the screen. This prevents the
problem seen in Office 97 where you drag it offscreen so that only the
border is visible, sometimes leaving you no way to move it back short of
resetting the toolbar. }
if MouseOverDock = nil then begin
R2 := GetDesktopAreaOfMonitorContainingPoint(Pos);
R := R2;
with GetFloatingBorderSize do
InflateRect (R, -(X+4), -(Y+4));
if MoveRect.Bottom < R.Top then
OffsetRect (MoveRect, 0, R.Top-MoveRect.Bottom);
if MoveRect.Top > R.Bottom then
OffsetRect (MoveRect, 0, R.Bottom-MoveRect.Top);
if MoveRect.Right < R.Left then
OffsetRect (MoveRect, R.Left-MoveRect.Right, 0);
if MoveRect.Left > R.Right then
OffsetRect (MoveRect, R.Right-MoveRect.Left, 0);
GetFloatingNCArea (TL, BR);
I := R2.Top + 4 - TL.Y;
if MoveRect.Top < I then
OffsetRect (MoveRect, 0, I-MoveRect.Top);
end;
{ Empty MoveRect if it's wanting to float but it's not allowed to, and
set the mouse cursor accordingly. }
if PreventFloating and not Assigned(MouseOverDock) then begin
SetRectEmpty (MoveRect);
SetCursor (LoadCursor(0, IDC_NO));
end
else
SetCursor (OldCursor);
{ Update the dragging outline }
DrawDraggingOutline (ScreenDC, @MoveRect, @OldMoveRect, MouseOverDock <> nil,
OldMouseOverDock <> nil);
end;
procedure BuildDockList;
procedure Recurse (const ParentCtl: TWinControl);
var
D: TDockPosition;
I: Integer;
begin
if ContainsControl(ParentCtl) or not ParentCtl.Showing then
Exit;
with ParentCtl do begin
for D := Low(D) to High(D) do
for I := 0 to ParentCtl.ControlCount-1 do
if (Controls[I] is TDock97) and (TDock97(Controls[I]).Position = D) then
Recurse (TWinControl(Controls[I]));
for I := 0 to ParentCtl.ControlCount-1 do
if (Controls[I] is TWinControl) and not(Controls[I] is TDock97) then
Recurse (TWinControl(Controls[I]));
end;
if (ParentCtl is TDock97) and TDock97(ParentCtl).FAllowDrag and
(TDock97(ParentCtl).Position in DockableTo) then
DockList.Add (ParentCtl);
end;
var
ParentForm: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
DockFormsList: TList;
I, J: Integer;
begin
ParentForm := GetToolWindowParentForm(Self);
DockFormsList := TList.Create;
try
if Assigned(FDockForms) then begin
for I := 0 to Screen.{$IFDEF TB97D3}CustomFormCount{$ELSE}FormCount{$ENDIF}-1 do begin
J := FDockForms.IndexOf(Screen.{$IFDEF TB97D3}CustomForms{$ELSE}Forms{$ENDIF}[I]);
if (J <> -1) and (FDockForms[J] <> ParentForm) then
DockFormsList.Add (FDockForms[J]);
end;
end;
if Assigned(ParentForm) then
DockFormsList.Insert (0, ParentForm);
for I := 0 to DockFormsList.Count-1 do
Recurse (DockFormsList[I]);
finally
DockFormsList.Free;
end;
end;
var
Accept: Boolean;
R: TRect;
Msg: TMsg;
NewDockedSize: PDockedSize;
I: Integer;
begin
Accept := False;
NPoint := Point(InitX, InitY);
{ Adjust for non-client area }
GetWindowRect (Handle, R);
R.BottomRight := ClientToScreen(Point(0, 0));
Dec (NPoint.X, R.Left-R.Right);
Dec (NPoint.Y, R.Top-R.Bottom);
DPoint := Point(Width-1, Height-1);
PreventDocking := GetKeyState(VK_CONTROL) < 0;
PreventFloating := DockMode <> dmCanFloat;
{ Build list of all TDock97's on the form }
DockList := TList.Create;
try
if DockMode <> dmCannotFloatOrChangeDocks then
BuildDockList
else
if Docked then
DockList.Add (DockedTo);
{ Set up potential sizes for each dock type }
NewDockedSizes := TList.Create;
try
New (NewDockedSize);
try
with NewDockedSize^ do begin
Dock := nil;
Size := OrderControls(False, GetDockTypeOf(DockedTo), nil);
AddFloatingNCAreaToSize (Size);
end;
NewDockedSizes.Add (NewDockedSize);
except
Dispose (NewDockedSize);
raise;
end;
for I := 0 to DockList.Count-1 do begin
New (NewDockedSize);
try
with NewDockedSize^ do begin
Dock := TDock97(DockList[I]);
if DockList[I] <> DockedTo then
Size := OrderControls(False, GetDockTypeOf(DockedTo), Dock)
else
Size := Self.ClientRect.BottomRight;
AddDockedNCAreaToSize (Size, Dock.Position in PositionLeftOrRight);
end;
NewDockedSizes.Add (NewDockedSize);
except
Dispose (NewDockedSize);
raise;
end;
end;
{ Before locking, make sure all pending paint messages are processed }
ProcessPaintMessages;
{ Save the original mouse cursor }
OldCursor := GetCursor;
{ This uses LockWindowUpdate to suppress all window updating so the
dragging outlines doesn't sometimes get garbled. (This is safe, and in
fact, is the main purpose of the LockWindowUpdate function)
IMPORTANT! While debugging you might want to enable the 'TB97DisableLock'
conditional define (see top of the source code). }
{$IFNDEF TB97DisableLock}
LockWindowUpdate (GetDesktopWindow);
{$ENDIF}
{ Get a DC of the entire screen. Works around the window update lock
by specifying DCX_LOCKWINDOWUPDATE. }
ScreenDC := GetDCEx(GetDesktopWindow, 0,
DCX_LOCKWINDOWUPDATE or DCX_CACHE or DCX_WINDOW);
try
SetCapture (Handle);
{ Initialize }
MouseOverDock := nil;
SetRectEmpty (MoveRect);
MouseMoved;
{ Stay in message loop until capture is lost. Capture is removed either
by this procedure manually doing it, or by an outside influence (like
a message box or menu popping up) }
while GetCapture = Handle do begin
case Integer(GetMessage(Msg, 0, 0, 0)) of
-1: Break; { if GetMessage failed }
0: begin
{ Repost WM_QUIT messages }
PostQuitMessage (Msg.WParam);
Break;
end;
end;
case Msg.Message of
WM_KEYDOWN, WM_KEYUP:
{ Ignore all keystrokes while dragging. But process Ctrl and Escape }
case Msg.WParam of
VK_CONTROL:
if PreventDocking <> (Msg.Message = WM_KEYDOWN) then begin
PreventDocking := Msg.Message = WM_KEYDOWN;
MouseMoved;
end;
VK_ESCAPE:
Break;
end;
WM_MOUSEMOVE:
{ Note to self: WM_MOUSEMOVE messages should never be dispatched
here to ensure no hints get shown during the drag process }
MouseMoved;
WM_LBUTTONDOWN, WM_LBUTTONDBLCLK:
{ Make sure it doesn't begin another loop }
Break;
WM_LBUTTONUP: begin
Accept := True;
Break;
end;
WM_RBUTTONDOWN..WM_MBUTTONDBLCLK:
{ Ignore all other mouse up/down messages }
;
else
TranslateMessage (Msg);
DispatchMessage (Msg);
end;
end;
finally
{ Since it sometimes breaks out of the loop without capture being
released }
if GetCapture = Handle then
ReleaseCapture;
{ Hide dragging outline. Since NT will release a window update lock if
another thread comes to the foreground, it has to release the DC
and get a new one for erasing the dragging outline. Otherwise,
the DrawDraggingOutline appears to have no effect when this happens. }
ReleaseDC (GetDesktopWindow, ScreenDC);
ScreenDC := GetDCEx(GetDesktopWindow, 0,
DCX_LOCKWINDOWUPDATE or DCX_CACHE or DCX_WINDOW);
DrawDraggingOutline (ScreenDC, nil, @MoveRect, True, MouseOverDock <> nil);
ReleaseDC (GetDesktopWindow, ScreenDC);
{ Release window update lock }
{$IFNDEF TB97DisableLock}
LockWindowUpdate (0);
{$ENDIF}
end;
finally
for I := NewDockedSizes.Count-1 downto 0 do
Dispose (PDockedSize(NewDockedSizes[I]));
NewDockedSizes.Free;
end;
finally
DockList.Free;
end;
{ Move to new position only if MoveRect isn't empty }
if Accept and not IsRectEmpty(MoveRect) then
Dropped;
end;
function TCustomToolWindow97.ChildControlTransparent (Ctl: TControl): Boolean;
begin
Result := False;
end;
procedure TCustomToolWindow97.MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
function ControlExistsAtPos (const P: TPoint): Boolean;
var
I: Integer;
begin
Result := False;
if PtInRect(ClientRect, P) then
for I := 0 to ControlCount-1 do
if not ChildControlTransparent(Controls[I]) and Controls[I].Visible and
PtInRect(Controls[I].BoundsRect, P) then begin
Result := True;
Break;
end;
end;
begin
inherited;
if (Button <> mbLeft) or
{ Ignore message if user clicked on a child control that was probably
disabled }
ControlExistsAtPos(Point(X, Y)) or
(Docked and not DockedTo.FAllowDrag) then
Exit;
{ Handle double click }
if ssDouble in Shift then begin
if Docked then begin
if DockMode = dmCanFloat then begin
Parent := GetToolWindowParentForm(Self);
MoveOnScreen (True);
end;
end
else
if Assigned(LastDock) then
Parent := LastDock
else
if Assigned(DefaultDock) then begin
FDockRow := ForceDockAtTopRow;
FDockPos := ForceDockAtLeftPos;
Parent := DefaultDock;
end;
Exit;
end;
BeginMoving (X, Y);
MouseUp (mbLeft, [], -1, -1);
end;
procedure TCustomToolWindow97.WMNCHitTest (var Message: TWMNCHitTest);
var
P: TPoint;
R: TRect;
BorderSize: TPoint;
C: Integer;
begin
inherited;
with Message do begin
P := SmallPointToPoint(Pos);
GetWindowRect (Handle, R);
Dec (P.X, R.Left); Dec (P.Y, R.Top);
if Docked then begin
if Result = HTNOWHERE then begin
if FCloseButtonWhenDocked and DockedTo.FAllowDrag and
PtInRect(GetDockedCloseButtonRect(Self, GetDockTypeOf(DockedTo) = dtLeftRight), P) then
Result := HTCLOSE
else
Result := HTCLIENT;
end;
end
else begin
if Result <> HTCLIENT then begin
if ShowCaption and PtInRect(GetCaptionRect(Self, True, False), P) then begin
if FCloseButton and PtInRect(GetCloseButtonRect(Self, True), P) then
Result := HTCLOSE
else
Result := HTCLIENT;
end
else begin
if Result in [HTLEFT..HTBOTTOMRIGHT] {set covers all resizing corners} then
Result := HTNOWHERE; { handles all resize hit-tests itself }
if Resizable then begin
BorderSize := GetFloatingBorderSize;
if not Params.ResizeEightCorner then begin
if (P.Y >= 0) and (P.Y < BorderSize.Y) then Result := HTTOP else
if (P.Y < Height) and (P.Y >= Height-BorderSize.Y-1) then Result := HTBOTTOM else
if (P.X >= 0) and (P.X < BorderSize.X) then Result := HTLEFT else
if (P.X < Width) and (P.X >= Width-BorderSize.X-1) then Result := HTRIGHT;
end
else begin
C := BorderSize.X + (GetSmallCaptionHeight-1);
if (P.X >= 0) and (P.X < BorderSize.X) then begin
Result := HTLEFT;
if (P.Y < C) then Result := HTTOPLEFT else
if (P.Y >= Height-C) then Result := HTBOTTOMLEFT;
end
else
if (P.X < Width) and (P.X >= Width-BorderSize.X-1) then begin
Result := HTRIGHT;
if (P.Y < C) then Result := HTTOPRIGHT else
if (P.Y >= Height-C) then Result := HTBOTTOMRIGHT;
end
else
if (P.Y >= 0) and (P.Y < BorderSize.Y) then begin
Result := HTTOP;
if (P.X < C) then Result := HTTOPLEFT else
if (P.X >= Width-C) then Result := HTTOPRIGHT;
end
else
if (P.Y < Height) and (P.Y >= Height-BorderSize.Y-1) then begin
Result := HTBOTTOM;
if (P.X < C) then Result := HTBOTTOMLEFT else
if (P.X >= Width-C) then Result := HTBOTTOMRIGHT;
end;
end;
end;
end;
end;
end;
end;
end;
procedure TCustomToolWindow97.WMNCLButtonDown (var Message: TWMNCLButtonDown);
procedure CloseButtonLoop;
procedure RedrawCloseButton;
begin
if not Docked then
InvalidateFloatingNCArea ([twrdCloseButton])
else
InvalidateDockedNCArea;
end;
var
Accept, NewCloseButtonDown: Boolean;
P: TPoint;
R: TRect;
Msg: TMsg;
begin
Accept := False;
FCloseButtonDown := True;
RedrawCloseButton;
SetCapture (Handle);
try
while GetCapture = Handle do begin
case Integer(GetMessage(Msg, 0, 0, 0)) of
-1: Break; { if GetMessage failed }
0: begin
{ Repost WM_QUIT messages }
PostQuitMessage (Msg.WParam);
Break;
end;
end;
case Msg.Message of
WM_KEYDOWN, WM_KEYUP:
{ Ignore all keystrokes while in a close button loop }
;
WM_MOUSEMOVE: begin
{ Note to self: WM_MOUSEMOVE messages should never be dispatched
here to ensure no hints get shown }
GetCursorPos (P);
GetWindowRect (Handle, R);
Dec (P.X, R.Left); Dec (P.Y, R.Top);
if not Docked then
NewCloseButtonDown := PtInRect(GetCloseButtonRect(Self, True), P)
else
NewCloseButtonDown := PtInRect(GetDockedCloseButtonRect(Self, GetDockTypeOf(DockedTo) = dtLeftRight), P);
if FCloseButtonDown <> NewCloseButtonDown then begin
FCloseButtonDown := NewCloseButtonDown;
RedrawCloseButton;
end;
end;
WM_LBUTTONDOWN, WM_LBUTTONDBLCLK:
{ Make sure it doesn't begin another loop }
Break;
WM_LBUTTONUP: begin
if FCloseButtonDown then
Accept := True;
Break;
end;
WM_RBUTTONDOWN..WM_MBUTTONDBLCLK:
{ Ignore all other mouse up/down messages }
;
else
TranslateMessage (Msg);
DispatchMessage (Msg);
end;
end;
finally
if GetCapture = Handle then
ReleaseCapture;
if FCloseButtonDown <> False then begin
FCloseButtonDown := False;
RedrawCloseButton;
end;
end;
if Accept then begin
{ Hide the window after close button is pushed }
if Assigned(FOnCloseQuery) then
FOnCloseQuery (Self, Accept);
{ Did the CloseQuery event return True? }
if Accept then begin
Hide;
if Assigned(FOnClose) then
FOnClose (Self);
end;
end;
end;
begin
case Message.HitTest of
HTLEFT..HTBOTTOMRIGHT:
BeginSizing (TToolWindowSizeHandle(Message.HitTest - HTLEFT));
HTCLOSE:
CloseButtonLoop;
else
inherited;
end;
end;
procedure TCustomToolWindow97.GetParams (var Params: TToolWindowParams);
begin
with Params do begin
CallAlignControls := True;
ResizeEightCorner := True;
ResizeClipCursor := True;
end;
end;
procedure TCustomToolWindow97.ResizeBegin;
begin
end;
procedure TCustomToolWindow97.ResizeTrack (var Rect: TRect; const OrigRect: TRect);
begin
end;
procedure TCustomToolWindow97.ResizeEnd;
begin
end;
procedure TCustomToolWindow97.BeginSizing (const ASizeHandle: TToolWindowSizeHandle);
var
DragX, DragY, ReverseX, ReverseY: Boolean;
MinWidth, MinHeight: Integer;
DragRect, OrigDragRect: TRect;
ScreenDC: HDC;
OrigPos, OldPos: TPoint;
procedure MouseMoved;
var
Pos: TPoint;
OldDragRect: TRect;
begin
GetCursorPos (Pos);
{ It needs to check if the cursor actually moved since last time. This is
because a call to LockWindowUpdate (apparently) generates a mouse move
message even when mouse hasn't moved. }
if (Pos.X = OldPos.X) and (Pos.Y = OldPos.Y) then Exit;
OldPos := Pos;
OldDragRect := DragRect;
DragRect := OrigDragRect;
if DragX then begin
if not ReverseX then Inc (DragRect.Right, Pos.X-OrigPos.X)
else Inc (DragRect.Left, Pos.X-OrigPos.X);
end;
if DragY then begin
if not ReverseY then Inc (DragRect.Bottom, Pos.Y-OrigPos.Y)
else Inc (DragRect.Top, Pos.Y-OrigPos.Y);
end;
if DragRect.Right-DragRect.Left < MinWidth then begin
if not ReverseX then DragRect.Right := DragRect.Left + MinWidth
else DragRect.Left := DragRect.Right - MinWidth;
end;
if DragRect.Bottom-DragRect.Top < MinHeight then begin
if not ReverseY then DragRect.Bottom := DragRect.Top + MinHeight
else DragRect.Top := DragRect.Bottom - MinHeight;
end;
ResizeTrack (DragRect, OrigDragRect);
DrawDraggingOutline (ScreenDC, @DragRect, @OldDragRect, False, False);
end;
var
Accept: Boolean;
Msg: TMsg;
R: TRect;
begin
if Docked then Exit;
Accept := False;
GetMinimumSize (MinWidth, MinHeight);
Inc (MinWidth, Width-ClientWidth);
Inc (MinHeight, Height-ClientHeight);
DragX := ASizeHandle in [twshLeft, twshRight, twshTopLeft, twshTopRight,
twshBottomLeft, twshBottomRight];
ReverseX := ASizeHandle in [twshLeft, twshTopLeft, twshBottomLeft];
DragY := ASizeHandle in [twshTop, twshTopLeft, twshTopRight, twshBottom,
twshBottomLeft, twshBottomRight];
ReverseY := ASizeHandle in [twshTop, twshTopLeft, twshTopRight];
ResizeBegin (ASizeHandle);
try
{ Before locking, make sure all pending paint messages are processed }
ProcessPaintMessages;
{ This uses LockWindowUpdate to suppress all window updating so the
dragging outlines doesn't sometimes get garbled. (This is safe, and in
fact, is the main purpose of the LockWindowUpdate function)
IMPORTANT! While debugging you might want to enable the 'TB97DisableLock'
conditional define (see top of the source code). }
{$IFNDEF TB97DisableLock}
LockWindowUpdate (GetDesktopWindow);
{$ENDIF}
{ Get a DC of the entire screen. Works around the window update lock
by specifying DCX_LOCKWINDOWUPDATE. }
ScreenDC := GetDCEx(GetDesktopWindow, 0,
DCX_LOCKWINDOWUPDATE or DCX_CACHE or DCX_WINDOW);
try
SetCapture (Handle);
if Params.ResizeClipCursor and not UsingMultipleMonitors then begin
R := GetPrimaryDesktopArea;
ClipCursor (@R);
end;
{ Initialize }
OrigDragRect := BoundsRect;
DragRect := OrigDragRect;
DrawDraggingOutline (ScreenDC, @DragRect, nil, False, False);
GetCursorPos (OrigPos);
OldPos := OrigPos;
{ Stay in message loop until capture is lost. Capture is removed either
by this procedure manually doing it, or by an outside influence (like
a message box or menu popping up) }
while GetCapture = Handle do begin
case Integer(GetMessage(Msg, 0, 0, 0)) of
-1: Break; { if GetMessage failed }
0: begin
{ Repost WM_QUIT messages }
PostQuitMessage (Msg.WParam);
Break;
end;
end;
case Msg.Message of
WM_KEYDOWN, WM_KEYUP:
{ Ignore all keystrokes while sizing except for Escape }
if Msg.WParam = VK_ESCAPE then
Break;
WM_MOUSEMOVE:
{ Note to self: WM_MOUSEMOVE messages should never be dispatched
here to ensure no hints get shown during the drag process }
MouseMoved;
WM_LBUTTONDOWN, WM_LBUTTONDBLCLK:
{ Make sure it doesn't begin another loop }
Break;
WM_LBUTTONUP: begin
Accept := True;
Break;
end;
WM_RBUTTONDOWN..WM_MBUTTONDBLCLK:
{ Ignore all other mouse up/down messages }
;
else
TranslateMessage (Msg);
DispatchMessage (Msg);
end;
end;
finally
{ Since it sometimes breaks out of the loop without capture being
released }
if GetCapture = Handle then
ReleaseCapture;
ClipCursor (nil);
{ Hide dragging outline. Since NT will release a window update lock if
another thread comes to the foreground, it has to release the DC
and get a new one for erasing the dragging outline. Otherwise,
the DrawDraggingOutline appears to have no effect when this happens. }
ReleaseDC (GetDesktopWindow, ScreenDC);
ScreenDC := GetDCEx(GetDesktopWindow, 0,
DCX_LOCKWINDOWUPDATE or DCX_CACHE or DCX_WINDOW);
DrawDraggingOutline (ScreenDC, nil, @DragRect, False, False);
ReleaseDC (GetDesktopWindow, ScreenDC);
{ Release window update lock }
{$IFNDEF TB97DisableLock}
LockWindowUpdate (0);
{$ENDIF}
end;
finally
ResizeEnd (Accept);
end;
if Accept then begin
BeginUpdate;
try
BoundsRect := DragRect;
finally
EndUpdate;
end;
{ Make sure it doesn't go completely off the screen }
MoveOnScreen (True);
end;
end;
procedure TCustomToolWindow97.WMClose (var Message: TWMClose);
var
MDIParentForm: {$IFDEF TB97D3} TCustomForm {$ELSE} TForm {$ENDIF};
begin
{ A floating toolbar does not use WM_CLOSE messages when its close button
is clicked, but Windows still sends a WM_CLOSE message if the user
presses Alt+F4 while one of the toolbar's controls is focused. Inherited
is not called since we do not want Windows' default processing - which
destroys the window. Instead, relay the message to the parent form. }
MDIParentForm := GetMDIParent(GetToolWindowParentForm(Self));
if Assigned(MDIParentForm) and MDIParentForm.HandleAllocated then
SendMessage (MDIParentForm.Handle, WM_CLOSE, 0, 0);
{ Note to self: MDIParentForm is used instead of OwnerForm since MDI
childs don't process Alt+F4 as Close }
end;
procedure TCustomToolWindow97.DoDockChangingHidden (DockingTo: TDock97);
begin
if not(csDestroying in ComponentState) and Assigned(FOnDockChangingHidden) then
FOnDockChangingHidden (Self, DockingTo);
end;
procedure TCustomToolWindow97.DoMove;
begin
if Assigned(FOnMove) then
FOnMove (Self);
end;
{ TCustomToolWindow97 - property access methods }
function TCustomToolWindow97.IsLastDockStored: Boolean;
begin
Result := FDockedTo = nil;
end;
procedure TCustomToolWindow97.SetCloseButton (Value: Boolean);
begin
if FCloseButton <> Value then begin
FCloseButton := Value;
{ Update the close button's visibility }
InvalidateFloatingNCArea ([twrdCaption, twrdCloseButton]);
end;
end;
procedure TCustomToolWindow97.SetCloseButtonWhenDocked (Value: Boolean);
begin
if FCloseButtonWhenDocked <> Value then begin
FCloseButtonWhenDocked := Value;
if Docked then
RecalcNCArea (Self);
end;
end;
procedure TCustomToolWindow97.SetDefaultDock (Value: TDock97);
begin
if FDefaultDock <> Value then begin
FDefaultDock := Value;
if Assigned(Value) then
Value.FreeNotification (Self);
end;
end;
procedure TCustomToolWindow97.SetDockedTo (Value: TDock97);
begin
if Assigned(Value) then
Parent := Value
else
Parent := ValidToolWindowParentForm(Self);
end;
procedure TCustomToolWindow97.SetDockPos (Value: Integer);
begin
FDockPos := Value;
if Docked then
DockedTo.ArrangeToolbars (False);
end;
procedure TCustomToolWindow97.SetDockRow (Value: Integer);
begin
FDockRow := Value;
if Docked then
DockedTo.ArrangeToolbars (False);
end;
procedure TCustomToolWindow97.SetBorderStyle (Value: TBorderStyle);
begin
if FBorderStyle <> Value then begin
FBorderStyle := Value;
if Docked then
RecalcNCArea (Self);
end;
end;
procedure TCustomToolWindow97.SetDragHandleStyle (Value: TDragHandleStyle);
begin
if FDragHandleStyle <> Value then begin
FDragHandleStyle := Value;
if Docked then
RecalcNCArea (Self);
end;
end;
procedure TCustomToolWindow97.SetFloatingMode (Value: TToolWindowFloatingMode);
begin
if FFloatingMode <> Value then begin
FFloatingMode := Value;
if HandleAllocated then
Perform (CM_SHOWINGCHANGED, 0, 0);
end;
end;
procedure TCustomToolWindow97.SetFullSize (Value: Boolean);
begin
if FFullSize <> Value then begin
FFullSize := Value;
ArrangeControls;
end;
end;
procedure TCustomToolWindow97.SetLastDock (Value: TDock97);
begin
if FUseLastDock and Assigned(FDockedTo) then
{ When docked, LastDock must be equal to DockedTo }
Value := FDockedTo;
if FLastDock <> Value then begin
if Assigned(FLastDock) and (FLastDock <> Parent) then
FLastDock.ChangeDockList (False, Self);
FLastDock := Value;
if Assigned(Value) then begin
FUseLastDock := True;
Value.FreeNotification (Self);
Value.ChangeDockList (True, Self);
end;
end;
end;
procedure TCustomToolWindow97.SetResizable (Value: Boolean);
begin
if FResizable <> Value then begin
FResizable := Value;
if not Docked then
{ Recreate the window handle because Resizable affects whether the
tool window is created with a WS_THICKFRAME style }
RecreateWnd;
end;
end;
procedure TCustomToolWindow97.SetShowCaption (Value: Boolean);
begin
if FShowCaption <> Value then begin
FShowCaption := Value;
if not Docked then
RecalcNCArea (Self);
end;
end;
procedure TCustomToolWindow97.SetUseLastDock (Value: Boolean);
begin
if FUseLastDock <> Value then begin
FUseLastDock := Value;
if not Value then
LastDock := nil
else
LastDock := FDockedTo;
end;
end;
function TCustomToolWindow97.GetVersion: TToolbar97Version;
begin
Result := Toolbar97VersionPropText;
end;
procedure TCustomToolWindow97.SetVersion (const Value: TToolbar97Version);
begin
{ write method required for the property to show up in Object Inspector }
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2018 Kike Pérez
Unit : Quick.Logger.Provider.Events
Description : Log Email Provider
Author : Kike Pérez
Version : 1.21
Created : 16/10/2017
Modified : 24/05/2018
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
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 Quick.Logger.Provider.Events;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
Quick.Commons,
Quick.Logger;
type
{$IFDEF FPC}
TLoggerEvent = procedure(LogItem : TLogItem) of object;
{$ELSE}
TLoggerEvent = reference to procedure(LogItem : TLogItem);
{$ENDIF}
TLogEventsProvider = class (TLogProviderBase)
private
fOnAny : TLoggerEvent;
fOnInfo : TLoggerEvent;
fOnSuccess : TLoggerEvent;
fOnWarning : TLoggerEvent;
fOnError : TLoggerEvent;
fOnCritical : TLoggerEvent;
fOnException : TLoggerEvent;
fOnDebug : TLoggerEvent;
fOnTrace : TLoggerEvent;
fOnCustom1 : TLoggerEvent;
fOnCustom2 : TLoggerEvent;
public
constructor Create; override;
destructor Destroy; override;
property OnAny : TLoggerEvent read fOnAny write fOnAny;
property OnInfo : TLoggerEvent read fOnInfo write fOnInfo;
property OnSuccess : TLoggerEvent read fOnSuccess write fOnSuccess;
property OnWarning : TLoggerEvent read fOnWarning write fOnWarning;
property OnError : TLoggerEvent read fOnError write fOnError;
property OnCritical : TLoggerEvent read fOnCritical write fOnCritical;
property OnException : TLoggerEvent read fOnException write fOnException;
property OnDebug : TLoggerEvent read fOnDebug write fOnDebug;
property OnTrace : TLoggerEvent read fOnTrace write fOnTrace;
property OnCustom1 : TLoggerEvent read fOnCustom1 write fOnCustom1;
property OnCustom2 : TLoggerEvent read fOnCustom2 write fOnCustom2;
procedure Init; override;
procedure Restart; override;
procedure WriteLog(cLogItem : TLogItem); override;
end;
var
GlobalLogEventsProvider : TLogEventsProvider;
implementation
constructor TLogEventsProvider.Create;
begin
inherited;
LogLevel := LOG_ALL;
end;
destructor TLogEventsProvider.Destroy;
begin
fOnAny := nil;
fOnInfo := nil;
fOnWarning := nil;
fOnError := nil;
fOnDebug := nil;
fOnTrace := nil;
fOnSuccess := nil;
fOnCritical := nil;
fOnException := nil;
fOnCustom1 := nil;
fOnCustom2 := nil;
inherited;
end;
procedure TLogEventsProvider.Init;
begin
inherited;
end;
procedure TLogEventsProvider.Restart;
begin
Stop;
Init;
end;
procedure TLogEventsProvider.WriteLog(cLogItem : TLogItem);
begin
case cLogItem.EventType of
etInfo : if Assigned(fOnInfo) then fOnInfo(cLogItem);
etSuccess : if Assigned(fOnSuccess) then fOnSuccess(cLogItem);
etWarning : if Assigned(fOnWarning) then fOnWarning(cLogItem);
etError : if Assigned(fOnError) then fOnError(cLogItem);
etCritical : if Assigned(fOnCritical) then fOnCritical(cLogItem);
etException : if Assigned(fOnException) then fOnException(cLogItem);
etTrace : if Assigned(fOnTrace) then fOnTrace(cLogItem);
etDebug : if Assigned(fOnDebug) then fOnDebug(cLogItem);
etCustom1 : if Assigned(fOnCustom1) then fOnCustom1(cLogItem);
etCustom2 : if Assigned(fOnCustom2) then fOnCustom2(cLogItem);
else if cLogItem.EventType <> etHeader then
raise ELogger.Create(Format('[TLogEventsProvider] : Not defined "%s" event',[EventTypeName[cLogItem.EventType]]));
end;
if Assigned(fOnAny) then fOnAny(cLogItem);
end;
initialization
GlobalLogEventsProvider := TLogEventsProvider.Create;
finalization
if Assigned(GlobalLogEventsProvider) and (GlobalLogEventsProvider.RefCount = 0) then GlobalLogEventsProvider.Free;
end.
|
namespace SnapTileSample;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Threading.Tasks,
Windows.Foundation,
Windows.UI.Core,
Windows.UI.Popups,
Windows.UI.ViewManagement,
Windows.UI.Xaml,
Windows.UI.Xaml.Controls,
Windows.UI.Xaml.Navigation,
Windows.UI.Xaml.Data;
type
MainPage = partial class
private
const ItemKey: String = "CurrentItem";
var programmaticUnsnapSucceeded: Boolean := false;
method UnsnapButton_Click(sender: Object; e: RoutedEventArgs);
method HyperlinkButton_Click(sender: Object; e: RoutedEventArgs);
method Data_ItemClick(sender: Object; e: ItemClickEventArgs);
method UpdateTextViewState;
method UpdateItemDisplay;
method OnWindowSizeChanged(sender: Object; args: WindowSizeChangedEventArgs);
protected
public
constructor;
CurrentItem: Item;
Data: DataSource;
end;
implementation
constructor MainPage;
begin
InitializeComponent;
Window.Current.SizeChanged += OnWindowSizeChanged;
Data := new DataSource;
var query := Data.Collection.OrderBy(item -> item.Category);
DataGridView.ItemsSource := query.ToList;
DataListView.ItemsSource := query.ToList;
if SuspensionManager.SessionState.ContainsKey(ItemKey) then begin
var selectedLink := SuspensionManager.SessionState[ItemKey] as String;
CurrentItem := (from i in query
where i.Link = selectedLink
select i).FirstOrDefault;
UpdateItemDisplay;
end;
end;
method MainPage.UnsnapButton_Click(sender: Object; e: RoutedEventArgs);
begin
programmaticUnsnapSucceeded := ApplicationView.TryUnsnap();
if not self.programmaticUnsnapSucceeded then begin
TextViewState.Text := 'Programmatic unsnap did not work.'
end else begin
UpdateTextViewState;
end;
end;
method MainPage.OnWindowSizeChanged(sender: Object; args: WindowSizeChangedEventArgs);
begin
case ApplicationView.Value of
Windows.UI.ViewManagement.ApplicationViewState.Filled: begin
VisualStateManager.GoToState(self, 'Fill', false);
end;
Windows.UI.ViewManagement.ApplicationViewState.FullScreenLandscape: begin
VisualStateManager.GoToState(self, 'Full', false);
end;
Windows.UI.ViewManagement.ApplicationViewState.Snapped: begin
VisualStateManager.GoToState(self, 'Snapped', false);
end;
Windows.UI.ViewManagement.ApplicationViewState.FullScreenPortrait: begin
VisualStateManager.GoToState(self, 'Portrait', false);
end
end;
UpdateTextViewState;
end;
method MainPage.UpdateTextViewState;
begin
var currentState: ApplicationViewState := Windows.UI.ViewManagement.ApplicationView.Value;
if currentState = ApplicationViewState.Snapped then begin
TextViewState.Text := 'This app is snapped';
end
else if currentState = ApplicationViewState.Filled then begin
TextViewState.Text := 'This app is in the fill state';
end
else if currentState = ApplicationViewState.FullScreenLandscape then begin
TextViewState.Text := 'This app is full-screen landscape';
end
else if currentState = ApplicationViewState.FullScreenPortrait then begin
TextViewState.Text := 'This app is full-screen portrait';
end;
if self.programmaticUnsnapSucceeded then begin
TextViewState.Text := TextViewState.Text + ' and this app was programmatically unsnapped.';
programmaticUnsnapSucceeded := false
end
else begin
TextViewState.Text := TextViewState.Text + '.'
end;
end;
method MainPage.Data_ItemClick(sender: Object; e: Windows.UI.Xaml.Controls.ItemClickEventArgs);
begin
CurrentItem := e.ClickedItem as Item;
UpdateItemDisplay;
SuspensionManager.SessionState[ItemKey] := CurrentItem.Link;
end;
method MainPage.UpdateItemDisplay;
begin
DetailsText.Text := CurrentItem.Subtitle;
DetailsImage.Source := CurrentItem.Image;
DetailsDescription.Text := CurrentItem.Description;
DetailsLink.Content := 'Click for more info';
end;
method MainPage.HyperlinkButton_Click(sender: Object; e: RoutedEventArgs);
begin
Windows.System.Launcher.LaunchUriAsync(new System.Uri(CurrentItem.Link));
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: dlgCodeTemplates
Author: Kiriakos Vlahos
Date: 08-Aug-2006
Purpose: Customization dialog for Code Templates
History:
-----------------------------------------------------------------------------}
unit dlgCodeTemplates;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ExtCtrls, JvExStdCtrls, JvEdit,
SynEdit, JvGroupBox, ActnList, TBXDkPanels;
type
TCodeTemplates = class(TForm)
Panel: TPanel;
lvItems: TListView;
btnCancel: TButton;
btnOK: TButton;
JvGroupBox: TJvGroupBox;
Label1: TLabel;
Label2: TLabel;
SynTemplate: TSynEdit;
edShortcut: TEdit;
ActionList: TActionList;
actAddItem: TAction;
actDeleteItem: TAction;
actMoveUp: TAction;
actMoveDown: TAction;
actUpdateItem: TAction;
Label5: TLabel;
edDescription: TEdit;
TBXButton1: TTBXButton;
TBXButton3: TTBXButton;
TBXButton4: TTBXButton;
TBXButton5: TTBXButton;
TBXButton2: TTBXButton;
Label4: TLabel;
Label3: TLabel;
btnHelp: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edShortcutKeyPress(Sender: TObject; var Key: Char);
procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
procedure actAddItemExecute(Sender: TObject);
procedure actDeleteItemExecute(Sender: TObject);
procedure actUpdateItemExecute(Sender: TObject);
procedure lvItemsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure actMoveUpExecute(Sender: TObject);
procedure actMoveDownExecute(Sender: TObject);
procedure lvItemsDeletion(Sender: TObject; Item: TListItem);
procedure btnHelpClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
CodeTemplateText : String;
procedure SetItems;
procedure GetItems;
end;
implementation
uses dmCommands;
{$R *.dfm}
procedure TCodeTemplates.FormDestroy(Sender: TObject);
begin
CommandsDataModule.ParameterCompletion.RemoveEditor(SynTemplate);
CommandsDataModule.ModifierCompletion.RemoveEditor(SynTemplate);
SynTemplate.Highlighter := nil;
end;
procedure TCodeTemplates.FormShow(Sender: TObject);
begin
SynTemplate.Highlighter := CommandsDataModule.SynPythonSyn;
CommandsDataModule.ParameterCompletion.Editor := SynTemplate;
CommandsDataModule.ModifierCompletion.Editor := SynTemplate;
SetItems;
end;
procedure TCodeTemplates.edShortcutKeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in ['a'..'z', 'A'..'Z', '0'..'9', #8]) then
Key := #0;
inherited;
end;
procedure TCodeTemplates.GetItems;
Var
i, j : integer;
begin
CodeTemplateText := '';
for i := 0 to lvItems.Items.Count - 1 do begin
CodeTemplateText := CodeTemplateText + lvItems.Items[i].Caption + sLineBreak;
if lvItems.Items[i].SubItems[0] <> '' then
CodeTemplateText := CodeTemplateText +'|' + lvItems.Items[i].SubItems[0] + sLineBreak;
for j := 0 to TStringList(lvItems.Items[i].Data).Count - 1 do
CodeTemplateText := CodeTemplateText + '=' +
TStringList(lvItems.Items[i].Data)[j] + sLineBreak;
end;
end;
procedure TCodeTemplates.SetItems;
Var
i, Count : integer;
List : TStringList;
begin
lvItems.Clear;
i := 0;
Count := 0;
List := TStringList.Create;
try
List.Text := CodeTemplateText;
while i < List.Count do begin
if not (List[i][1] in ['|', '=']) then begin
Inc(Count);
with lvItems.Items.Add() do begin
Caption := List[i];
Data := TStringList.Create;
Inc(i);
if List[i][1] = '|' then begin
SubItems.Add(Copy(List[i], 2, MaxInt));
Inc(i);
end else
SubItems.Add('');
end;
end else begin
if (Count > 0) and (List[i][1] = '=') then
TStringList(lvItems.Items[Count-1].Data).Add(Copy(List[i], 2, MaxInt));
Inc(i);
end;
end;
finally
List.Free;
end;
end;
procedure TCodeTemplates.ActionListUpdate(Action: TBasicAction;
var Handled: Boolean);
begin
actDeleteItem.Enabled := lvItems.ItemIndex >= 0;
actMoveUp.Enabled := lvItems.ItemIndex >= 1;
actMoveDown.Enabled := (lvItems.ItemIndex >= 0) and
(lvItems.ItemIndex < lvItems.Items.Count - 1);
actAddItem.Enabled := edShortCut.Text <> '';
actUpdateItem.Enabled := (edShortCut.Text <> '') and (lvItems.ItemIndex >= 0);
Handled := True;
end;
procedure TCodeTemplates.actAddItemExecute(Sender: TObject);
Var
Item : TListItem;
i : Integer;
begin
if edShortCut.Text <> '' then begin
for i := 0 to lvItems.Items.Count - 1 do
if CompareText(lvItems.Items[i].Caption, edShortCut.Text) = 0 then begin
Item := lvItems.Items[i];
Item.Caption := edShortCut.Text;
Item.SubItems[0] := edDescription.Text;
TStringList(Item.Data).Assign(SynTemplate.Lines);
Item.Selected := True;
Exit;
end;
with lvItems.Items.Add() do begin
Caption := edShortCut.Text;
SubItems.Add(edDescription.Text);
Data := Pointer(TStringList.Create);
TStringList(Data).Assign(SynTemplate.Lines);
end;
end;
end;
procedure TCodeTemplates.actDeleteItemExecute(Sender: TObject);
begin
if lvItems.ItemIndex >= 0 then
lvItems.Items.Delete(lvItems.ItemIndex);
end;
procedure TCodeTemplates.actUpdateItemExecute(Sender: TObject);
Var
i : integer;
begin
if (edShortCut.Text <> '') and (lvItems.ItemIndex >= 0) then begin
for i := 0 to lvItems.Items.Count - 1 do
if (CompareText(lvItems.Items[i].Caption, edShortCut.Text) = 0) and
(i <> lvItems.ItemIndex) then
begin
MessageDlg('Another item has the same name', mtError, [mbOK], 0);
Exit;
end;
with lvItems.Items[lvItems.ItemIndex] do begin
Caption := edShortCut.Text;
SubItems[0] := edDescription.Text;
TStringList(Data).Assign(SynTemplate.Lines);
end;
end;
end;
procedure TCodeTemplates.btnHelpClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TCodeTemplates.lvItemsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
if Item.Selected then begin
edShortCut.Text := Item.Caption;
edDescription.Text := Item.SubItems[0];
SynTemplate.Lines.Assign(TStringList(Item.Data));
end;
end;
procedure TCodeTemplates.actMoveUpExecute(Sender: TObject);
Var
Name, Value : string;
P : Pointer;
Index : integer;
begin
if lvItems.ItemIndex > 0 then begin
Index := lvItems.ItemIndex;
Name := lvItems.Items[Index].Caption;
Value := lvItems.Items[Index].SubItems[0];
P := lvItems.Items[Index].Data;
lvItems.Items[Index].Data := nil; // so that it does not get freed
lvItems.Items.Delete(Index);
with lvItems.Items.Insert(Index - 1) do begin
Caption := Name;
SubItems.Add(Value);
Data := P;
Selected := True;
end;
end;
end;
procedure TCodeTemplates.actMoveDownExecute(Sender: TObject);
Var
Name, Value : string;
P : Pointer;
Index : integer;
begin
if lvItems.ItemIndex < lvItems.Items.Count - 1 then begin
Index := lvItems.ItemIndex;
Name := lvItems.Items[Index].Caption;
Value := lvItems.Items[Index].SubItems[0];
P := lvItems.Items[Index].Data;
lvItems.Items[Index].Data := nil; // so that it does not get freed
lvItems.Items.Delete(Index);
with lvItems.Items.Insert(Index + 1) do begin
Caption := Name;
SubItems.Add(Value);
Data := P;
Selected := True;
end;
end;
end;
procedure TCodeTemplates.lvItemsDeletion(Sender: TObject; Item: TListItem);
begin
if Assigned(Item.Data) then
TStringList(Item.Data).Free;
end;
procedure TCodeTemplates.FormClose(Sender: TObject; var Action: TCloseAction);
begin
GetItems;
end;
end.
|
unit ZFpb_kdf;
{General Password Based Key Derivation Function 2}
interface
(*************************************************************************
DESCRIPTION : RFC 2898: Password Based Key Derivation Function 2
REQUIREMENTS : TP5-7, D1-D7/D9-D10, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : http://www.faqs.org/rfcs/rfc2898.html
http://www.faqs.org/rfcs/rfc3211.html [includes test vectors]
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 17.01.06 W.Ehrhardt Initial version based on keyderiv 1.29
0.11 17.01.06 we error codes
0.12 23.01.06 we new names: unit pb_kdf, functions kdf2/s
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2006 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
uses
ZFHash,ZFHMAC;
type
TKD_String = AnsiString; {easy short type for win32}
const
kdf_err_nil_pointer = $0001; {phash descriptor is nil}
kdf_err_digestlen = $0002; {digest length from descriptor is zero}
function kdf2(phash: PHashDesc; pPW: pointer; pLen: word; salt: pointer; sLen: word; C: longint; var DK; dkLen: word): integer;
{-Derive key DK from password pPW using salt and iteration count C, uses hash function from phash}
{$ifdef DLL} stdcall; {$endif}
function kdf2s(phash: PHashDesc; sPW: TKD_String; salt: pointer; sLen: word; C: longint; var DK; dkLen: word): integer;
{-Derive key DK from password string sPW using salt and iteration count C, uses hash function from phash}
{$ifdef DLL} stdcall; {$endif}
implementation
{helper type}
type
pByte = ^byte;
TMSBA = array[0..3] of byte;
{---------------------------------------------------------------------------}
procedure IncMSB(var CTR: TMSBA);
{-Increment CTR[3]..CTR[0], i.e. 32 Bit MSB counter}
var
j: integer;
begin
for j:=3 downto 0 do begin
inc(CTR[j]);
if CTR[j]<>0 then exit;
end;
end;
{---------------------------------------------------------------------------}
function kdf2(phash: PHashDesc; pPW: pointer; pLen: word; salt: pointer; sLen: word; C: longint; var DK; dkLen: word): integer;
{-Derive key DK from password pPW using salt and iteration count C, uses hash function from phash}
var
i, k, lk, hLen: word;
j: longint;
pDK: pByte; {pointer to DK }
ii: TMSBA; {i in big endian}
u, ucum: THashDigest;
ctx: THMAC_Context;
begin
if phash=nil then begin
kdf2 := kdf_err_nil_pointer;
exit;
end;
if phash^.HDigestLen=0 then begin
kdf2 := kdf_err_digestlen;
exit;
end;
kdf2 := 0;
hLen := phash^.HDigestLen;
lk := 0;
pDK := pByte(@DK);
fillchar(ii, sizeof(ii), 0);
for i:=1 to 1 + pred(dkLen) div hLen do begin
IncMSB(ii);
fillchar(ucum, sizeof(ucum),0);
for j:=1 to C do begin
hmac_init(ctx, phash, pPW, pLen);
if j=1 then begin
{U_1 = PRF(pPW, salt || ii)}
hmac_updateXL(ctx, salt, sLen);
hmac_updateXL(ctx, @ii, 4);
end
else begin
{U_i = PRF(pPW, U_(i-1)}
hmac_updateXL(ctx, @u, hLen);
end;
hmac_final(ctx, u);
{update cumulative XOR U_i}
for k:=0 to hLen-1 do ucum[k] := ucum[k] xor u[k];
end;
{T_i = F(P,S,C,l) = ucum}
for k:=0 to hLen-1 do begin
{concat T_i}
if lk<dkLen then begin
pDK^ := ucum[k];
inc(lk);
{$ifdef WIN64}
pDK := Pointer(NativeInt(pDK)+1);
{$else}
inc(longint(pDK));
{$endif}
end;
end;
end;
end;
{---------------------------------------------------------------------------}
function kdf2s(phash: PHashDesc; sPW: TKD_String; salt: pointer; sLen: word; C: longint; var DK; dkLen: word): integer;
{-Derive key DK from password string sPW using salt and iteration count C, uses hash function from phash}
begin
kdf2s := kdf2(phash, @sPW[1], length(sPW), salt, sLen, C, DK, dkLen);
end;
end.
|
(*
Category: SWAG Title: SORTING ROUTINES
Original name: 0016.PAS
Description: QUICK2.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:57
*)
{...This is as generic a QuickSort as I currently use:
}
Program QuickSortDemo;
Uses
Crt;
Const
coMaxItem = 30000;
Type
Item = Word;
arItem = Array[1..coMaxItem] of Item;
(***** QuickSort routine. *)
(* *)
Procedure QuickSort({update} Var arData : arItem;
{input } woLeft,
woRight : Word);
Var
Pivot,
TempItem : Item;
woIndex1,
woIndex2 : Word;
begin
woIndex1 := woLeft;
woIndex2 := woRight;
Pivot := arData[(woLeft + woRight) div 2];
Repeat
While (arData[woIndex1] < Pivot) do
inc(woIndex1);
While (Pivot < arData[woIndex2]) do
dec(woIndex2);
if (woIndex1 <= woIndex2) then
begin
TempItem := arData[woIndex1];
arData[woIndex1] := arData[woIndex2];
arData[woIndex2] := TempItem;
inc(woIndex1);
dec(woIndex2)
end
Until (woIndex1 > woIndex2);
if (woLeft < woIndex2) then
QuickSort(arData, woLeft, woIndex2);
if (woIndex1 < woRight) then
QuickSort(arData, woIndex1, woRight)
end; (* QuickSort. *)
Var
woIndex : Word;
Buffer : arItem;
begin
Write('Creating ', coMaxItem, ' random numbers... ');
For woIndex := 1 to coMaxItem do
Buffer[woIndex] := random(65535);
Writeln('Finished!');
Write('Sorting ', coMaxItem, ' random numbers... ');
QuickSort(Buffer, 1, coMaxItem);
Writeln('Finished!');
Writeln;
Writeln('Press the <ENTER> key to display all ', coMaxItem,
' sorted numbers...');
readln;
For woIndex := 1 to coMaxItem do
Write(Buffer[woIndex]:8)
end.
|
unit uPlotUtils;
{
*****************************************************************************
* This file is part of Multiple Acronym Math and Audio Plot - MAAPlot *
* *
* See the file COPYING. *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
* MAAplot for Lazarus/fpc *
* (C) 2014 Stefan Junghans *
*****************************************************************************
}
{$mode objfpc}{$H+}
//{$mode delphi}{$H+}
interface
uses
Classes, Types, sysutils, math, GraphMath, Dialogs, uPlotClass, uPlotAxis, FPimage, Graphics,
uPlotDataTypes, LazUTF8; //GraphUtil
type
TFPColorRange = record
min: TFPColor;
max: TFPColor;
end;
TColorRange = record
min: TColor;
max: TColor;
end;
// TODO: implement better return codes
function ValueToMathCoord(AAxis: uPlotClass.TPlotAxisBase; AValue: Extended; out MathPt: TFloatPoint): integer;
// pixel coordinates in math axis orientation relative to DrawOrigin 0/0
function MathCoordToValue(AAxis: uPlotClass.TPlotAxisBase; MathPt: TFloatPoint; out AValue: Extended): integer; // used for PixelZoom in axis
// pixel coordinates in math axis orientation relative to DrawOrigin 0/0
//function ValueToDataImage(AAxis: TPlotAxis; AValue: Extended; out ScrPt: TPoint): Integer; // will not work, as we need to respect all axes !
// pixel coordinates directly usable in DataImage
function XYZToDataImage(XAxis, YAxis, ZAxis: TPlotAxisBase; X, Y, Z: Extended; out ScrPt: TPoint): Integer;
// pixel coordinates directly usable in DataImage
function ValueToScreen(AAxis: uPlotClass.TPlotAxisBase; AValue: Extended; out ScrPt: TPoint): integer;
// pixel coordinates directly usable in Plot.PlotImage
function XYToScreen(XAxis, YAxis: uPlotClass.TPlotAxisBase; X, Y: Extended; out ScrPt: TPoint): integer;
function ScreenToXY(XAxis, YAxis: uPlotClass.TPlotAxisBase; out X, Y: Extended; ScrPt: TPoint): integer;
// pixel coordinates directly usable in Plot.PlotImage
function XYZToScreen(XAxis, YAxis, ZAxis: uPlotClass.TPlotAxisBase; X, Y, Z: Extended; out ScrPt: TPoint): integer;
// pixel coordinates directly usable in Plot.PlotImage
function ShiftPoint(AShiftSize: TSize ; var ScrPt: TPoint): integer;
function PlotImageCoordsToFrameRectCoords(APlotRect: TBasePlotRect; var ScrPt: TPoint): Integer; // used when calculated relative to PlotIMage (i.e. XYToScreen) but plotted into FrameRect (i.e. FBackBMP)
function PlotImageCoordsToDataRectCoords(APlotRect: TBasePlotRect; var ScrPt: TPoint): Integer; // used when calculated relative to PlotIMage (i.e. XYToScreen) but plotted into FrameRect (i.e. FBackBMP)
// for autoscaling
function ValueTo125(AValue: Extended; AUpwards: Boolean; APower: Integer): extended; // TODO: rework
function ValueToNext(AValue: Extended; AUpwards: Boolean; APower: Integer): extended; // TODO: rework
// tests 10.09.10
//function ScrCoordToPlotRect(X, Y: Integer; var PlotRectIndex: Integer): Integer;
function IsInsideRect(X, Y: Integer; ARect: TRect): Boolean; overload;
function IsInsideRect(APoint: TPoint; ARect: TRect): Boolean; overload;
function FormatNumber(ANumber: Extended; ANumberFormat: TNumberFormat; AFractionalDigits: Integer = 1): String;
// 15.09.14
function DigitsNeeded(ARange: TValueRange): integer;
// 09.10.14
function DigitsNeeded(AMainInterval: Extended): integer;
// new utils 10.10.12 for simplifying Axis drawindicator and innergrid
function MainTickInterval(ARange: TValueRange; ALogBase: Extended; AIsLogScale: Boolean): Extended;
function MainTickRange(ARange: TValueRange; ALogBase: Extended; AIsLogScale: Boolean): TValueRange;
//
function SimpleRoundUpDown(const AValue: Extended; AUpwards: Boolean; const Digits: TRoundToRange = -2): Extended;
procedure QuickSort_XYLine(var AXYLine: TXYLine; IdxStart, IdxStop: Integer; SortY: Boolean = false);
const
c_SUCCESS = 0;
c_NOAXIS = -1;
c_VALUE_OUTSIDE_VIEWRANGE = -2;
c_FPE = -4;
c_IPOL_EDGEPOINT = -8;
c_ERRUNKNOWN = -100;
implementation
//uses uPlotAxis;
resourcestring
S_WrongAxisType = 'Wrong Axis Type';
S_UnknownError = 'Unknown Error';
function ValueToMathCoord(AAxis: uPlotClass.TPlotAxisBase; AValue: Extended; out MathPt: TFloatPoint): integer;
// Returns math coordinate in pixels relaitve to axis origin set to 0-0
var
vZero, vOrigin : TFloatPoint;
vAngle, vR: Extended;
begin
Result := c_SUCCESS;
{disabled 03.09.14 for correct interpolator function
IF (AValue < AAxis.ViewRange.min) OR (AValue > AAxis.ViewRange.max)
THEN BEGIN
Result := c_VALUE_OUTSIDE_VIEWRANGE;
MathPt.X := c_INVALIDCOORDINATE;
MathPt.Y := c_INVALIDCOORDINATE;
exit;
END;
}
IF AAxis = nil THEN begin
Result := c_NOAXIS;
MathPt := FloatPoint(0,0);
exit;
end;
IF (AValue < AAxis.ViewRange.min) OR (AValue > AAxis.ViewRange.max)
THEN BEGIN
Result := c_VALUE_OUTSIDE_VIEWRANGE;
END;
// we calculate however... XYZtoDataImage shall respect this outside problem
vZero.X:=0; vZero.Y:=0;
IF AAxis is uPlotAxis.TPlotAxis
THEN BEGIN
vOrigin := vZero;
vangle := uPlotAxis.TPlotAxis(AAxis).DrawAngle;
END ELSE BEGIN
vOrigin := vZero;
IF uPlotClass.TPlotAxisBase(AAxis).Orientation = aoHorizontal
THEN vAngle := 0 ELSE vAngle := 90;
END;
// convert axis points
IF uPlotAxis.TPlotAxis(AAxis).LogScale AND (AValue <= 0) THEN BEGIN
Result := c_FPE;
//writeln('problem: ',FloatToStrF((AValue),ffFixed,4,3));
exit;
END;
IF uPlotAxis.TPlotAxis(AAxis).LogScale THEN
vR := (logn(uPlotAxis.TPlotAxis(AAxis).LogBase, AValue) - logn(uPlotAxis.TPlotAxis(AAxis).LogBase, AAxis.ViewRange.min))
* AAxis.PixelsPerValue ELSE
vR := (AValue - AAxis.ViewRange.min)* AAxis.PixelsPerValue;
MathPt := LineEndPoint(vOrigin, vAngle*16, vR);
MathPt.Y := - MathPt.Y;
end;
function MathCoordToValue(AAxis: uPlotClass.TPlotAxisBase; MathPt: TFloatPoint;
out AValue: Extended): integer;
// Returns value relaitve to axis origin set to 0-0 (please respect shift upwards and give shifted point !)
var
vAngle, vPixels, vR: Extended;
vValue: Extended;
vMindB, vMaxdB: Extended;
begin
Result := c_SUCCESS;
IF AAxis = nil THEN begin
Result := c_NOAXIS;
AValue := 0;
exit;
end;
// find vR, projected to axis
vR := sqrt( sqr(MathPt.X) + sqr(MathPt.Y) );
if MathPt.X <> 0 then
vAngle := arctan(MathPt.Y / MathPt.X)
else if (MathPt.Y < 0) then vAngle := 1.5*Pi() else vAngle := Pi()/2;
vAngle := vAngle - TPlotAxis(AAxis).DrawAngle * Pi() / 180;
vPixels := vR * cos(vAngle) / TPlotAxis(AAxis).DrawLength; // fraction of axis (when shifted to 0/0)
IF uPlotAxis.TPlotAxis(AAxis).LogScale THEN BEGIN
vMindB := TPlotAxis(AAxis).ReCalcValue(TPlotAxis(AAxis).ViewRange.min);
vMaxdB := TPlotAxis(AAxis).ReCalcValue(TPlotAxis(AAxis).ViewRange.max);
vValue := TPlotAxis(AAxis).ViewRange.min * TPlotAxis(AAxis).ReCalcValueInverse(vPixels * (vMaxdB - vMindB));
END ELSE BEGIN
vValue := TPlotAxis(AAxis).ViewRange.min + vPixels * (TPlotAxis(AAxis).ViewRange.max - TPlotAxis(AAxis).ViewRange.min);
END;
IF (vValue < AAxis.ViewRange.min) OR (vValue > AAxis.ViewRange.max)
THEN Result := c_VALUE_OUTSIDE_VIEWRANGE;
// we calculate however... XYZtoDataImage shall respect this outside problem
AValue:=vValue;
end;
function XYZToDataImage(XAxis, YAxis, ZAxis: TPlotAxisBase; X, Y, Z: Extended;
out ScrPt: TPoint): Integer;
var
vError: Integer;
vMathPt: TFloatPoint;
vScrPt: TPoint;
vOrigin, vNextOrigin: TPoint;
begin
Result := 0;
vScrPt.X:=0; vScrPt.Y:=0;
// XAxis
IF XAxis <> nil THEN BEGIN
vOrigin := TPLotAxis(XAxis).DrawOriginRel;
vError := ValueToMathCoord(XAxis, X, vMathPt);
if vError >= 0 then begin
vScrPt.X := vOrigin.X + round(vMathPt.X);
vScrPt.Y := -vOrigin.Y - round(vMathPt.Y);
end else begin
Result := min(Result, vError);
end;
END;
// YAxis
IF YAxis <> nil THEN BEGIN
vNextOrigin := TPLotAxis(YAxis).DrawOriginRel;
vScrPt.Y := vScrPt.Y - (vNextOrigin.Y-vOrigin.Y); // shift to Y-origin
vError := ValueToMathCoord(YAxis, Y, vMathPt);
if vError >= 0 then begin
vScrPt.X := vScrPt.X + round(vMathPt.X);
vScrPt.Y := vScrPt.Y - round(vMathPt.Y);
end else begin
Result := min(Result, vError);
end;
END;
// ZAxis
IF ZAxis <> nil THEN BEGIN
vNextOrigin := TPLotAxis(ZAxis).DrawOriginRel;
vScrPt.Y := vScrPt.Y - (vNextOrigin.Y-vOrigin.Y); // shift to Z-origin
vScrPt.X := vScrPt.X + (vNextOrigin.X-vOrigin.X); // shift to Z-origin
vError := ValueToMathCoord(ZAxis, Z, vMathPt);
if vError >= 0 then begin
vScrPt.X := vScrPt.X + round(vMathPt.X);
vScrPt.Y := vScrPt.Y - round(vMathPt.Y);
end else begin
Result := min(Result, vError);
end;
END;
vScrPt.Y := vScrPt.Y + (XAxis.OwnerPlotRect.DataRect.Bottom - XAxis.OwnerPlotRect.DataRect.Top);
ScrPt := vScrPt;
// results: 0 = OK
// -1 = c_outside_viewrange, screenpoint is interpolated to edge of viewport; break interpol line here...
// -2 = c_FPE some float exception, do not use point
end;
function ValueToScreen(AAxis: uPlotClass.TPlotAxisBase; AValue: Extended; out ScrPt: TPoint): integer;
// Returns Screen Point (directly useable for outer total image)
// TODO: use ValueToMathCoord to simplify this function ?
var
vOrigin: TPoint; // vOriginRel, vPt
vAngle, vR: Extended;
begin
Result := c_SUCCESS;
try
IF not ((AAxis is uPlotAxis.TPlotAxis) OR (AAxis is uPlotAxis.TPlotAxis))
THEN raise EPlot.CreateRes(@S_WrongAxisType);
IF (AValue > c_GLOBALMAX) OR (AValue < -c_GLOBALMAX) THEN exit;
// IF uPlotAxis.TPlotAxis(AAxis).LogScale;
IF AAxis is uPlotAxis.TPlotAxis
THEN BEGIN
//vOriginRel := uPlotAxis.TPlotAxis(AAxis).DrawOriginRel;
vOrigin := uPlotAxis.TPlotAxis(AAxis).DrawOrigin;
vangle := uPlotAxis.TPlotAxis(AAxis).DrawAngle;
END ELSE BEGIN
//vOriginRel.X := 0;
//vOriginRel.Y := 0;
vOrigin := uPlotClass.TPlotAxisBase(AAxis).OwnerPlotRect.BottomLeft;
IF uPlotClass.TPlotAxisBase(AAxis).Orientation = aoHorizontal
THEN vAngle := 0 ELSE vAngle := 90;
END;
// convert X-axis and Y-axis points
IF uPlotAxis.TPlotAxis(AAxis).LogScale THEN
vR := (logn(uPlotAxis.TPlotAxis(AAxis).LogBase, AValue) - logn(uPlotAxis.TPlotAxis(AAxis).LogBase, AAxis.ViewRange.min))
* AAxis.PixelsPerValue ELSE
vR := (AValue - AAxis.ViewRange.min)* AAxis.PixelsPerValue;
//ScrPt := LineEndPoint(vOriginRel, vAngle*16, vR);
ScrPt := LineEndPoint(vOrigin, vAngle*16, vR);
except
on E:EPlot do begin
MessageDlg('Error', E.Message, mtInformation, [mbOK], 0);
Result := c_ERRUNKNOWN;
end;
end;
end;
function XYToScreen(XAxis, YAxis: uPlotClass.TPlotAxisBase; X,
Y: Extended; out ScrPt: TPoint): integer;
var
vMathPtX, vMathPtY: TFloatPoint;
vPt: TPoint;
vXOrigin, vYOrigin: TPoint;
vError: Integer;
begin
Result := c_SUCCESS;
try
IF not ((XAxis is uPlotAxis.TPlotAxis) AND (YAxis is uPlotAxis.TPlotAxis))
THEN raise EPlot.CreateRes(@S_WrongAxisType);
IF (X < XAxis.ViewRange.min) OR (X > XAxis.ViewRange.max)
OR (Y < YAxis.ViewRange.min) OR (Y > YAxis.ViewRange.max)
THEN BEGIN
Result := c_VALUE_OUTSIDE_VIEWRANGE;
ScrPt.X := c_INVALIDCOORDINATE;
ScrPt.Y := c_INVALIDCOORDINATE;
exit;
END;
// Here is the coordinate conversion float to Canvas
IF XAxis is uPlotAxis.TPlotAxis
THEN BEGIN
vXOrigin := uPlotAxis.TPlotAxis(XAxis).DrawOrigin;
END ELSE BEGIN
vXOrigin := uPlotClass.TPlotAxisBase(XAxis).OwnerPlotRect.BottomLeft;
END;
IF YAxis is uPlotAxis.TPlotAxis
THEN BEGIN
vYOrigin := uPlotAxis.TPlotAxis(YAxis).DrawOrigin;
END ELSE BEGIN
vYOrigin := uPlotClass.TPlotAxisBase(YAxis).OwnerPlotRect.BottomLeft;
END;
// convert X-axis and Y-axis points
vError := uPlotUtils.ValueToMathCoord(XAxis, X, vMathPtX);
vError := uPlotUtils.ValueToMathCoord(YAxis, Y, vMathPtY);
IF vError < 0 THEN BEGIN
IF vError = c_FPE THEN Result := c_FPE ELSE Result := c_ERRUNKNOWN;
ScrPt.X := c_INVALIDCOORDINATE;
ScrPt.Y := c_INVALIDCOORDINATE;
raise EPlot.CreateRes(@S_UnknownError);
//exit;
END;
vPt.X := round(vMathPtX.X) + round(vMathPtY.X) + vXOrigin.X;
vPt.Y := -round(vMathPtX.Y) - round(vMathPtY.Y) + vYOrigin.Y;
ScrPt := vPt;
except
on E:EPlot do begin
MessageDlg('Error XYtoScreen', E.Message, mtInformation, [mbOK], 0);
Result := c_ERRUNKNOWN;
end;
end;
end;
function ScreenToXY(XAxis, YAxis: uPlotClass.TPlotAxisBase; out X, Y: Extended;
ScrPt: TPoint): integer;
var
vPixelPerCoord: Extended;
vPixels: Integer;
vValue: Extended;
begin
Result := 0;
// Xaxis
IF cos(TPlotAxis(XAxis).DrawAngle * pi/180) = 0 THEN vPixelPerCoord := c_GLOBALMAX
ELSE vPixelPerCoord := (1 / cos(TPlotAxis(XAxis).DrawAngle * pi/180)) * XAxis.PixelsPerValue;
vPixels := (ScrPt.X - TPlotAxis(XAxis).DrawOrigin.X); // TODO: check for angles with cos < 0
IF vPixels = 0 THEN BEGIN
Result := c_FPE;
exit;
END;
IF not uPlotAxis.TPlotAxis(XAxis).LogScale THEN
vValue := TPlotAxis(XAxis).ViewRange.min + (1 / (vPixelPerCoord / vPixels))
ELSE vValue := TPlotAxis(XAxis).ViewRange.min * power(uPlotAxis.TPlotAxis(XAxis).LogBase, 1 /(vPixelPerCoord / vPixels));
X := vValue;
// Yaxis
IF sin(TPlotAxis(YAxis).DrawAngle * pi/180) = 0 THEN vPixelPerCoord := -c_GLOBALMAX
ELSE vPixelPerCoord := (1 / sin(TPlotAxis(YAxis).DrawAngle * pi/180)) * YAxis.PixelsPerValue;
vPixels := (TPlotAxis(YAxis).DrawOrigin.Y - ScrPt.Y) ; // TODO: check for angles with cos < 0
IF vPixels = 0 THEN BEGIN
Result := c_FPE;
exit;
END;
IF not uPlotAxis.TPlotAxis(YAxis).LogScale THEN vValue := TPlotAxis(YAxis).ViewRange.min + (1 / (vPixelPerCoord / vPixels))
ELSE vValue := TPlotAxis(YAxis).ViewRange.min * power(uPlotAxis.TPlotAxis(YAxis).LogBase, 1 /(vPixelPerCoord / vPixels));
Y := vValue;
end;
function XYZToScreen(XAxis, YAxis, ZAxis: uPlotClass.TPlotAxisBase; X, Y,
Z: Extended; out ScrPt: TPoint): integer;
var
vMathPtX, vMathPtY, vMathPtZ: TFloatPoint;
vPt: TPoint;
vXOrigin, vYOrigin: TPoint; //vZOrigin: TPoint;
vError : Integer;
vWrongAxisError: Boolean;
vOutSide: Boolean;
begin
vOutSide:=false;
vWrongAxisError :=false;
vWrongAxisError := vWrongAxisError and not ((XAxis is TPlotAxis) or (XAxis = nil));
vWrongAxisError := vWrongAxisError and not ((YAxis is TPlotAxis) or (YAxis = nil));
vWrongAxisError := vWrongAxisError and not ((ZAxis is TPlotAxis) or (ZAxis = nil));
IF vWrongAxisError
THEN raise EPlot.CreateRes(@S_WrongAxisType);
vOutSide := (X < XAxis.ViewRange.min) OR (X > XAxis.ViewRange.max)
OR (Y < YAxis.ViewRange.min) OR (Y > YAxis.ViewRange.max);
IF (ZAxis <> nil) then vOutSide := vOutSide OR (Z < ZAxis.ViewRange.min) OR (Z > ZAxis.ViewRange.max) ;
IF vOutSide THEN
BEGIN
Result := c_VALUE_OUTSIDE_VIEWRANGE;
ScrPt.X := c_INVALIDCOORDINATE;
ScrPt.Y := c_INVALIDCOORDINATE;
exit;
END;
// Here is the coordinate conversion float to Canvas
IF XAxis is uPlotAxis.TPlotAxis
THEN BEGIN
vXOrigin := uPlotAxis.TPlotAxis(XAxis).DrawOrigin;
END ELSE
IF XAxis is TPlotAxisBase THEN BEGIN
vXOrigin := uPlotClass.TPlotAxisBase(XAxis).OwnerPlotRect.BottomLeft;
END ELSE begin
vXOrigin := Point(0,0);
end;
IF YAxis is uPlotAxis.TPlotAxis
THEN BEGIN
vYOrigin := uPlotAxis.TPlotAxis(YAxis).DrawOrigin;
END ELSE
IF YAxis is TPlotAxisBase THEN BEGIN
vYOrigin := uPlotClass.TPlotAxisBase(YAxis).OwnerPlotRect.BottomLeft;
END ELSE begin
vYOrigin := Point(0,0);
end;
{ // Z axis origin not needed because it is not respected
IF ZAxis is uPlotAxis.TPlotAxis
THEN BEGIN
vZOrigin := uPlotAxis.TPlotAxis(ZAxis).DrawOrigin;
END ELSE
IF ZAxis is TPlotAxisBase THEN BEGIN
vZOrigin := uPlotClass.TPlotAxisBase(ZAxis).OwnerPlotRect.BottomLeft;
END ELSE begin
vZOrigin := Point(0,0);
end;
}
// convert X-axis and Y-axis points
try
vError := uPlotUtils.ValueToMathCoord(XAxis, X, vMathPtX);
vError := min(vError, uPlotUtils.ValueToMathCoord(YAxis, Y, vMathPtY));
vError := min(vError, uPlotUtils.ValueToMathCoord(ZAxis, Z, vMathPtZ));
IF vError = c_NOAXIS THEN vError:=c_SUCCESS; //c_NOAXIS is without problem
IF (vError < 0) THEN BEGIN
Result := vError;
ScrPt.X := c_INVALIDCOORDINATE;
ScrPt.Y := c_INVALIDCOORDINATE;
exit;
END;
vPt.X := round(vMathPtX.X) + round(vMathPtY.X) + round(vMathPtZ.X) + vXOrigin.X;
vPt.Y := -round(vMathPtX.Y) - round(vMathPtY.Y) - round(vMathPtZ.Y) + vYOrigin.Y;
ScrPt := vPt;
Result := vError;
except
on E:EPlot do begin
MessageDlg('Error', E.Message, mtInformation, [mbOK], 0);
Result := c_ERRUNKNOWN;
end;
end;
end;
function ShiftPoint(AShiftSize: TSize; var ScrPt: TPoint): integer;
begin
Result := c_SUCCESS;
ScrPt.X := ScrPt.X - AShiftSize.cx;
ScrPt.Y := ScrPt.Y + AShiftSize.cy;
end;
function PlotImageCoordsToFrameRectCoords(APlotRect: TBasePlotRect;
var ScrPt: TPoint): Integer;
begin
ScrPt.X := ScrPt.X - APlotRect.FrameRect.Left;
ScrPt.Y := ScrPt.Y - APlotRect.FrameRect.Top;
Result := 0;
end;
function PlotImageCoordsToDataRectCoords(APlotRect: TBasePlotRect;
var ScrPt: TPoint): Integer;
begin
ScrPt.X := ScrPt.X - APlotRect.DataRect.Left;
ScrPt.Y := ScrPt.Y - APlotRect.DataRect.Top;
Result := 0;
end;
function ValueTo125(AValue: Extended; AUpwards: Boolean; APower: Integer): extended;
var
vResultValue: Extended;
vDigit: Integer;
vDigitStr: String;
vSign: TValueSign;
vpower: Integer;
begin
vDigit := 1;
IF (APower < -36) OR (APower > 36) THEN begin
Result := AValue;
exit;
end;
vResultValue:=AValue;
IF abs(vResultValue) > c_GLOBALMIN THEN BEGIN
vSign := Sign(vResultValue);
vpower := floor(log10(vResultValue));
vDigitStr := FloatToStrF(abs(vResultValue), ffExponent,2,2);
IF AUpwards THEN
CASE vDigitStr[1] OF
'0': vDigit := 1;
'1': vDigit := 2;
'2'..'4': vDigit := 5;
'5'..'9': vDigit := 10;
END
ELSE
CASE vDigitStr[1] OF
'1': vDigit := 0;
'2': vDigit := 1;
'3'..'5': vDigit := 2;
'6'..'9': vDigit := 5;
END;
vResultValue := vSign * vDigit * intpower(10, vpower);
END ELSE vResultValue := 0;
Result := vResultValue;
end;
function ValueToNext(AValue: Extended; AUpwards: Boolean; APower: Integer): extended;
begin
IF abs(AValue) < c_GLOBALMIN THEN begin
Result := 0;
exit;
end;
IF (APower < -36) OR (APower > 36) THEN begin
Result := AValue;
exit;
end;
Result := SimpleRoundUpDown(AValue, AUpwards, APower);
end;
function IsInsideRect(X, Y: Integer; ARect: TRect): Boolean;
begin
Result := FALSE;
IF (X >= ARect.Left) AND (X <= ARect.Right)
AND (Y >= ARect.Top) AND (Y <= ARect.Bottom) THEN Result := TRUE;
end;
function IsInsideRect(APoint: TPoint; ARect: TRect): Boolean; overload;
begin
Result := FALSE;
IF (APoint.X >= ARect.Left) AND (APoint.X <= ARect.Right)
AND (APoint.Y >= ARect.Top) AND (APoint.Y <= ARect.Bottom) THEN Result := TRUE;
end;
function FormatNumber(ANumber: Extended; ANumberFormat: TNumberFormat; AFractionalDigits: Integer = 1): String;
var
//vFloatSettings: TFormatSettings;
vPower : Integer;
vValue: Extended;
vEngStep: Integer;
fractionaldigits: Integer;
const
//precision = 2; // only for built-in function, after comma digits for exp notation
//digits = 1; // only for built-in functions, after comma digits for ffFixed
//format = ffFixed; // only for built-in functions
//fractionaldigits = 1;
floatcharacter = 'e';
cEngString = '_afpnµm kMGTPE_'; // 8 is plain
begin
// 15.09.14 estimate needed number of fractionaldigits
//fractionaldigits := min(c_MAININTERVAL_MAXDIGITS, AFractionalDigits);
fractionaldigits := EnsureRange(AFractionalDigits, 0, c_MAININTERVAL_MAXDIGITS);
//vFloatSettings.DecimalSeparator := ',';
case ANumberFormat of
nfPlain: begin
//Result := IntToStr(round(ANumber));
Result := FloatToStrF(ANumber, ffFixed,0,2); // precision (0) used for exp formates
end;
nfFloat: begin
//if fractionaldigits < 0 then fractionaldigits := 0;
IF ANumber = 0 THEN begin
Result := '0';
exit;
end ELSE
vPower := trunc(logn(10, abs(ANumber) ));
// when power <0 switches to next power at 1 not at 10
// power >0 -->numbers 1..9 // power <0 --> numbers 10e-3..9e-2
// solution "IF...=10" below:
IF (abs(ANumber) < 1) THEN vPower := vPower -1;
vValue := ANumber / power(10,vPower);
fractionaldigits := fractionaldigits + vPower;
fractionaldigits := EnsureRange(fractionaldigits, 0, c_MAININTERVAL_MAXDIGITS);
//if fractionaldigits < 0 then fractionaldigits := 0;
vValue := SimpleRoundTo(vValue, -fractionaldigits);
IF round(abs(vValue)) = 10 THEN begin // int()
vValue:= vValue / 10;
vPower:= vPower + 1;
end;
Result := FloatToStr(vValue) + floatcharacter + IntToStr(vPower);
end;
nfEngineering: begin
//writeln('digits: ', IntToStr(fractionaldigits));
IF ANumber = 0 THEN begin
Result := '0';
exit;
end ELSE
vPower := trunc(logn(10, abs(ANumber) ));
IF abs(ANumber) < 1 THEN vPower := vPower -3;
vEngStep := vPower DIV 3;
//writeln('value before div: ', FloatToStrF(ANumber, ffFixed, 15, 5));
vValue := ANumber / power(10,(vEngStep * 3));
//writeln('value after div : ', FloatToStrF(vValue, ffFixed, 15, 5));
fractionaldigits:=fractionaldigits + (abs(vEngStep) * 3);
fractionaldigits := EnsureRange(fractionaldigits, 0, c_MAININTERVAL_MAXDIGITS);
vValue:=RoundTo(vValue, -fractionaldigits);
IF round(abs(vValue)) = 1000 THEN begin // int()
vValue:= vValue / 1000;
vEngStep:= vEngStep + 1;
end;
Result := FloatToStr(vValue) + floatcharacter + IntToStr(vEngStep * 3);
//Result := FloatToStrF(vValue, ffFixed, 15, fractionaldigits) + floatcharacter + IntToStr(vEngStep * 3);
end;
nfEngineeringPrefix: begin
IF ANumber = 0 THEN begin
Result := '0';
exit;
end ELSE
vPower := trunc(logn(10, abs(ANumber) ));
IF abs(ANumber) < 1 THEN vPower := vPower -3;
vEngStep := vPower DIV 3;
//vValue := SimpleRoundTo(vValue, -fractionaldigits);
vValue := ANumber / power(10,(vEngStep * 3));
fractionaldigits := fractionaldigits + (abs(vEngStep) * 3);
fractionaldigits := EnsureRange(fractionaldigits, 0, c_MAININTERVAL_MAXDIGITS);
vValue:=RoundTo(vValue, -fractionaldigits);
IF round(abs(vValue)) = 1000 THEN begin // int()
vValue:= vValue / 1000;
vEngStep:= vEngStep + 1;
end;
IF (vEngStep < -6) OR (vEngStep > 6) THEN
//Result := FloatToStr(vValue) + 'e' + IntToStr(vPower)
Result := FloatToStrF(vValue, ffFixed, 10, fractionaldigits) + floatcharacter + IntToStr(vEngStep * 3)
ELSE
Result := FloatToStr(vValue) + UTF8Copy(cEngString, 8+vEngStep, 1); // cEngString[8+vEngStep];
//Result := FloatToStrF(vValue, ffFixed, 15, fractionaldigits) + cEngString[8+vEngStep];
end;
end;
end;
function DigitsNeeded(ARange: TValueRange): integer;
var
vFractionalDigits: Integer;
begin
Result := 1;
IF (ARange.max - ARange.min) <= 0 then exit;
vFractionalDigits := trunc(log10( (ARange.max - ARange.min) ));
//IF vFractionalDigits > 0 then Result := 0 else Result := abs(vFractionalDigits) + 0; // +1/ 2 ??
Result := -(vFractionalDigits) + 1; // +1/ 2 ??
end;
function DigitsNeeded(AMainInterval: Extended): integer;
begin
// if interval >=1 then we need 0 fractional digits
// if < 1 we need digits according to fraction
Result := trunc(abs(EnsureRange( log10(AMainInterval), -c_MAININTERVAL_MAXDIGITS , 0)) + 1); // -n ..0; 0 digits for values > 1
end;
function MainTickInterval(ARange: TValueRange; ALogBase: Extended;
AIsLogScale: Boolean): Extended;
var
vPower : Extended;
vRange : Extended;
begin
Result := c_GLOBALMIN;
vRange := (ARange.max) - (ARange.min);
//IF vRange < c_GLOBALMIN THEN vRange := c_GLOBALMIN; // too much digits ! leads to 45 digits
IF vRange < intpower(10, -c_MAININTERVAL_MAXDIGITS) THEN vRange := intpower(10, -c_MAININTERVAL_MAXDIGITS) ;
IF AIsLogScale OR (ALogBase=1) THEN begin
Result := 1;
exit end
ELSE begin
vPower:= trunc(logn(ALogBase,vRange) );
IF vRange < 1 THEN vPower:= vPower -1; // always round down
Result := ( power(ALogBase,vPower) ); // round for paranoia reason ? should be integer like
end;
end;
function MainTickRange(ARange: TValueRange; ALogBase: Extended;
AIsLogScale: Boolean): TValueRange;
begin
IF AIsLogScale THEN BEGIN
IF ARange.min <= 0 THEN ARange.min := c_GLOBALMIN;
Result.min := power(ALogBase, trunc(logn(ALogBase,ARange.min)));
IF ARange.max <= ARange.min THEN ARange.max := ARange.min + c_GLOBALMIN;
Result.max := power(ALogBase, trunc(logn(ALogBase,ARange.max))+1);
END ELSE BEGIN
IF abs(ARange.min) < c_GLOBALMIN THEN Result.min := 0 else begin
// new code for rounding:
Result.min := ARange.min / MainTickInterval(ARange, ALogBase, AIsLogScale); // power(vMinMax.min, -vPower);
IF Result.min < 0 THEN Result.min := Result.min-1;
Result.min := trunc(Result.min);
Result.min := Result.min * MainTickInterval(ARange, ALogBase, AIsLogScale);
end;
// high end point
IF abs(ARange.max) < c_GLOBALMIN THEN Result.max := 0 else begin // oder 0 ? Result.max := c_GLOBALMIN
// new code for rounding:
Result.max := ARange.max / MainTickInterval(ARange, ALogBase, AIsLogScale); //power(vMinMax.max, -vPower);
IF Result.max < 0 THEN Result.max := Result.max-1;
Result.max := trunc(Result.max+1);
Result.max := Result.max * MainTickInterval(ARange, ALogBase, AIsLogScale);
end;
END;
end;
function SimpleRoundUpDown(const AValue: Extended; AUpwards: Boolean; const Digits: TRoundToRange = -2): Extended;
var
RV : Extended;
vUpDown : integer;
begin
IF (Digits < -36) OR (Digits > 36) THEN begin
Result := AValue;
exit;
end;
if AUpwards and (AValue > 0) THEN vUpDown := 1 * Sign(AValue) ELSE vUpDown := 0; //?????????
//vUpDown:=0;
RV := IntPower(10, -Digits);
if AValue < 0 then
Result := Trunc((AValue*RV) - 1 + vUpDown)/RV // rounds betrag down
else
Result := Trunc((AValue*RV) + 0 + vUpDown)/RV;// rounds betrag down
end;
procedure QuickSort_XYLine(var AXYLine: TXYLine; IdxStart, IdxStop: Integer;
SortY: Boolean);
var
vL, vR: Integer;
Pivot: Extended;
vTempXYValue: TXYValue;
begin
if IdxStart < IdxStop then
begin
vL := IdxStart;
vR := IdxStop-1;
IF SortY THEN Pivot := AXYLine[IdxStop].Y ELSE
Pivot := AXYLine[IdxStop].X;
repeat
IF SortY THEN BEGIN
while (AXYLine[vL].Y <= Pivot) and (vL < IdxStop) do
begin
vL := vL + 1;
end;
while (AXYLine[vR].Y >= Pivot) and (vR > IdxStart) do
begin
vR := vR -1;
end;
END ELSE BEGIN
while (AXYLine[vL].X <= Pivot) and (vL < IdxStop) do
begin
vL := vL + 1;
end;
while (AXYLine[vR].X >= Pivot) and (vR > IdxStart) do
begin
vR := vR -1;
end;
END;
if vL < vR then
begin
vTempXYValue := AXYLine[vR];
AXYLine[vR] := AXYLine[vL];
AXYLine[vL] := vTempXYValue;
end;
until NOT (vL < vR);
IF SortY AND (AXYLine[vL].Y > Pivot) THEN begin
vTempXYValue := AXYLine[vL];
AXYLine[vL] := AXYLine[IdxStop];
AXYLine[IdxStop] := vTempXYValue;
end ELSE
IF (NOT SortY) AND (AXYLine[vL].X > Pivot) THEN begin
vTempXYValue := AXYLine[vL];
AXYLine[vL] := AXYLine[IdxStop];
AXYLine[IdxStop] := vTempXYValue;
end;
QuickSort_XYLine(AXYLine, IdxStart, vL-1, SortY);
QuickSort_XYLine(AXYLine, vL+1 , IdxStop, SortY);
end;
end;
end.
|
unit HashAlgSHA_U;
// Description: SHA Hash (Wrapper for the SHA Hashing Engine)
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Classes,
HashAlg_U,
HashValue_U,
HashAlgSHAEngine_U;
type
THashAlgSHA = class(THashAlg)
private
shaEngine: THashAlgSHAEngine;
context: SHA_CTX;
protected
{ Protected declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Init(); override;
procedure Update(const input: array of byte; const inputLen: cardinal); override;
procedure Final(digest: THashValue); override;
function PrettyPrintHashValue(const theHashValue: THashValue): string; override;
published
{ Published declarations }
end;
procedure Register;
implementation
uses
SysUtils; // needed for fmOpenRead
procedure Register;
begin
RegisterComponents('Hash', [THashAlgSHA]);
end;
constructor THashAlgSHA.Create(AOwner: TComponent);
begin
inherited;
shaEngine:= THashAlgSHAEngine.Create();
fTitle := 'SHA';
fHashLength := 160;
fBlockLength := 512;
end;
destructor THashAlgSHA.Destroy();
begin
// Nuke any existing context before freeing off the engine...
shaEngine.SHAInit(context);
shaEngine.Free();
inherited;
end;
procedure THashAlgSHA.Init();
begin
shaEngine.SHAInit(context);
end;
procedure THashAlgSHA.Update(const input: array of byte; const inputLen: cardinal);
begin
shaEngine.SHAUpdate(context, input, inputLen);
end;
procedure THashAlgSHA.Final(digest: THashValue);
begin
shaEngine.SHAFinal(digest, context);
end;
function THashAlgSHA.PrettyPrintHashValue(const theHashValue: THashValue): string;
var
retVal: string;
begin
retVal := inherited PrettyPrintHashValue(theHashValue);
insert(' ', retVal, 33);
insert(' ', retVal, 25);
insert(' ', retVal, 17);
insert(' ', retVal, 9);
Result := retVal;
end;
END.
|
unit VH_GL;
interface
Uses Windows,OpenGL15,VH_Global,VH_Display;//,OpenGLWrapper;
Procedure InitGL(Handle : HWND);
procedure glResizeWnd(Width, Height : Integer);
implementation
Procedure InitGL(Handle : HWND);
var
pfd : TPIXELFORMATDESCRIPTOR;
pf : Integer;
begin
InitOpenGL; // Don't forget, or first gl-Call will result in an access violation! exit;
// OpenGL initialisieren
h_DC:=GetDC(Handle);
// PixelFormat
pfd.nSize:=sizeof(pfd);
pfd.nVersion:=1;
pfd.dwFlags:=PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
pfd.iPixelType:=PFD_TYPE_RGBA; // PFD_TYPE_RGBA or PFD_TYPEINDEX
pfd.cColorBits:=32;
pfd.cStencilBits := 8;
pf :=ChoosePixelFormat(h_DC, @pfd); // Returns format that most closely matches above pixel format
SetPixelFormat(h_DC, pf, @pfd);
h_rc :=wglCreateContext(h_DC); // Rendering Context = window-glCreateContext
wglMakeCurrent(h_DC,h_rc); // Make the DC (Form1) the rendering Context
ActivateRenderingContext(h_DC, h_RC);
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
glClearColor(BGColor.X, BGColor.Y, BGColor.Z, 1.0);
glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading
glClearDepth(1.0); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enable Depth Buffer
glDepthFunc(GL_LESS); // The Type Of Depth Test To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //Realy Nice perspective calculations
BuildFont;
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
xRot := 0;
yRot := 0;
Depth := DefaultDepth;
oglloaded := true;
wglSwapIntervalEXT(0);
glResizeWnd(SCREEN_WIDTH,SCREEN_HEIGHT);
SwapBuffers(H_DC);
Randomize;
end;
procedure glResizeWnd(Width, Height : Integer);
begin
SCREEN_WIDTH := Width;
SCREEN_HEIGHT := Height;
if (Height = 0) then // prevent divide by zero exception
Height := 1;
glViewport(0, 0, Width, Height); // Set the viewport for the OpenGL window
glMatrixMode(GL_PROJECTION); // Change Matrix Mode to Projection
glLoadIdentity(); // Reset View
gluPerspective(FOV, Width/Height, 4.0, DEPTH_OF_VIEW); // Do the perspective calculations. Last value = max clipping depth
glMatrixMode(GL_MODELVIEW); // Return to the modelview matrix
glLoadIdentity(); // Reset View
FUpdateWorld := True;
end;
end.
|
unit logoscreen;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, jpeg, ExtCtrls, RzButton, Gauges, StdCtrls, RzLabel;
type
Tlogo = class(TForm)
img1: TImage;
RzBitBtn1: TRzBitBtn;
lblStatus: TLabel;
Gauge1: TGauge;
RzLabel1: TRzLabel;
RzLabel2: TRzLabel;
procedure RzBitBtn1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure RepaintForm;
public
{ Public declarations }
procedure BeginLoad;
procedure EndLoad;
procedure UpdateLoadStatus(const AStatusText: string; AProgress: Integer);
end;
var
logo: Tlogo;
implementation
{$R *.dfm}
procedure Tlogo.BeginLoad;
begin
lblStatus.Caption := 'LOADING......';
Gauge1.Progress := 0;
RepaintForm;
end;
procedure Tlogo.EndLoad;
begin
lblStatus.Caption := 'LOAD FINISH';
Gauge1.Progress := 100;
RepaintForm;
end;
procedure Tlogo.RepaintForm;
begin
Show;
Update;
Sleep(50); //为了演示,特延长时间 to 200。
end;
procedure Tlogo.RzBitBtn1Click(Sender: TObject);
begin
Close;
end;
procedure Tlogo.UpdateLoadStatus(const AStatusText: string;
AProgress: Integer);
begin
lblStatus.Caption := AStatusText;
Gauge1.Progress := AProgress;
RepaintForm;
end;
procedure Tlogo.FormCreate(Sender: TObject);
begin
lblStatus.Caption := '';
Gauge1.MinValue := 0;
Gauge1.MaxValue := 100;
end;
end.
|
unit ThUtils;
interface
uses
ThTypes,
GR32, clipper;
function PtInPolyPolygon(const APoint: TFloatPoint; const APolyPoly: TThPolyPoly): Boolean;
function EmptyRect: TFloatRect;
function EmptyPoint: TFloatPoint;
// Graphics32 <> clipper
function AAFloatPoint2AAPoint(const APolyPoly: TArrayOfArrayOfFloatPoint;
Decimals: Integer = 0): TPaths; overload;
function AAFloatPoint2AAPoint(const APoly: TArrayOfFloatPoint;
Decimals: Integer = 0): TPath; overload;
function AAPoint2AAFloatPoint(const APaths: TPaths;
Decimals: Integer = 0): TArrayOfArrayOfFloatPoint;
function ScaleRect(AFR: TFloatRect; AScale: TFloatPoint): TFloatRect;
function OffsetRect(AFR: TFloatRect; AOffset: TFloatPoint): TFloatRect;
function IntfEquals(AIntf1, AIntf2: IInterface): Boolean;
function PtInCircle(const Point, Center: TFloatPoint; Radius: TFloat): Boolean;
//function LocalToViewPort(
type
TFloatPointHelper = record helper for TFloatPoint
public
function Scale(Value: TFloatPoint): TFloatPoint;
function Offset(Value: TFloatPoint): TFloatPoint;
end;
TFloatRectHelper = record helper for TFloatRect
private
function GetBottomLeft: TFloatPoint;
function GetTopRight: TFloatPoint;
procedure SetBottomLeft(const Value: TFloatPoint);
procedure SetTopRight(const Value: TFloatPoint);
function GetWidth: TFloat;
procedure SetWidth(const Value: TFloat);
function GetHeight: TFloat;
procedure SetHeight(const Value: TFloat);
public
procedure Realign;
property TopRight: TFloatPoint read GetTopRight write SetTopRight;
property BottomLeft: TFloatPoint read GetBottomLeft write SetBottomLeft;
property Width: TFloat read GetWidth write SetWidth;
property Height: TFloat read GetHeight write SetHeight;
end;
implementation
uses
System.Math, GR32_Geometry;
function PtInPolyPolygon(const APoint: TFloatPoint; const APolyPoly: TThPolyPoly): Boolean;
var
Poly: TArrayOfFloatPoint;
begin
Result := False;
for Poly in APolyPoly do
begin
if PointInPolygon(APoint, Poly) then
Exit(True);
end;
end;
function EmptyRect: TFloatRect;
begin
Result.Left := 0;
Result.Top := 0;
Result.Right := 0;
Result.Bottom := 0;
end;
function EmptyPoint: TFloatPoint;
begin
Result := TFloatPoint.Zero;
end;
function AAFloatPoint2AAPoint(const APolyPoly: TArrayOfArrayOfFloatPoint;
Decimals: Integer = 0): TPaths; overload;
var
I, J, DecScale: integer;
begin
DecScale := Round(Power(10, Decimals));
Setlength(Result, Length(APolyPoly));
for I := 0 to high(APolyPoly) do
begin
Setlength(Result[I], Length(APolyPoly[I]));
for J := 0 to High(APolyPoly[I]) do
begin
Result[I][J].X := Round(APolyPoly[I][J].X * DecScale);
Result[I][J].Y := Round(APolyPoly[I][J].Y * DecScale);
end;
end;
end;
function AAFloatPoint2AAPoint(const APoly: TArrayOfFloatPoint;
Decimals: Integer = 0): TPath; overload;
var
I, DecScale: Integer;
begin
DecScale := Round(Power(10, Decimals));
Setlength(Result, Length(APoly));
for I := 0 to High(APoly) do
begin
Result[I].X := Round(APoly[I].X * DecScale);
Result[I].Y := Round(APoly[I].Y * DecScale);
end;
end;
//------------------------------------------------------------------------------
function AAPoint2AAFloatPoint(const APaths: TPaths;
Decimals: Integer = 0): TArrayOfArrayOfFloatPoint;
var
I, J, DecScale: Integer;
begin
DecScale := Round(Power(10, Decimals));
Setlength(Result, Length(APaths));
for I := 0 to High(APaths) do
begin
Setlength(Result[i], Length(APaths[i]));
for J := 0 to High(APaths[I]) do
begin
Result[I][J].X := APaths[I][J].X / DecScale;
Result[I][J].Y := APaths[I][J].Y / DecScale;
end;
end;
end;
function ScaleRect(AFR: TFloatRect; AScale: TFloatPoint): TFloatRect;
begin
Result.Left := AFR.Left * AScale.X;
Result.Top := AFR.Top * AScale.Y;
Result.Right := AFR.Right * AScale.X;
Result.Bottom := AFR.Bottom * AScale.Y;
end;
function OffsetRect(AFR: TFloatRect; AOffset: TFloatPoint): TFloatRect;
begin
Result.Left := AFR.Left + AOffset.X;
Result.Top := AFR.Top + AOffset.Y;
Result.Right := AFR.Right + AOffset.X;
Result.Bottom := AFR.Bottom + AOffset.Y;
end;
function IntfEquals(AIntf1, AIntf2: IInterface): Boolean;
begin
Result := AIntf1 as IInterface = AIntf2 as IInterface;
end;
function PtInCircle(const Point, Center: TFloatPoint; Radius: TFloat): Boolean;
begin
if Radius > 0 then
begin
Result := Sqr((Point.X - Center.X) / Radius) +
Sqr((Point.Y - Center.Y) / Radius) <= 1;
end
else
begin
Result := False;
end;
end;
{ TFloatRectHelper }
function TFloatRectHelper.GetBottomLeft: TFloatPoint;
begin
Result := FloatPoint(Self.Bottom, Self.Left);
end;
function TFloatRectHelper.GetHeight: TFloat;
begin
Result := Abs(Self.Bottom - Self.Top);
end;
function TFloatRectHelper.GetTopRight: TFloatPoint;
begin
Result := FloatPoint(Self.Top, Self.Right);
end;
function TFloatRectHelper.GetWidth: TFloat;
begin
Result := Abs(Self.Right - Self.Left);
end;
procedure TFloatRectHelper.Realign;
var
X, Y: TFloat;
begin
if Self.Right < Self.Left then
begin
X := Self.Left;
Self.Left := Self.Right;
Self.Right := X;
end;
if Self.Bottom < Self.Top then
begin
Y := Self.Top;
Self.Top := Self.Bottom;
Self.Bottom := Y;
end;
end;
procedure TFloatRectHelper.SetBottomLeft(const Value: TFloatPoint);
begin
Self.Bottom := Value.Y;
Self.Left := Value.X;
end;
procedure TFloatRectHelper.SetHeight(const Value: TFloat);
begin
Self.Bottom := Self.Top + Value;
end;
procedure TFloatRectHelper.SetTopRight(const Value: TFloatPoint);
begin
Self.Top := Value.Y;
Self.Right := value.X;
end;
procedure TFloatRectHelper.SetWidth(const Value: TFloat);
begin
Self.Right := Self.Left + Value;
end;
{ TFloatPointHelper }
function TFloatPointHelper.Offset(Value: TFloatPoint): TFloatPoint;
begin
Result.X := Self.X + Value.X;
Result.Y := Self.Y + Value.Y;
end;
function TFloatPointHelper.Scale(Value: TFloatPoint): TFloatPoint;
begin
Result.X := Self.X * Value.X;
Result.Y := Self.Y * Value.Y;
end;
end.
|
unit Chapter06._04_Solution1;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DeepStar.Utils,
DeepStar.DSA.Linear.ArrayList,
DeepStar.DSA.Linear.Queue,
AI.TreeNode;
/// 102. Binary Tree Level Order Traversal
/// https://leetcode.com/problems/binary-tree-level-order-traversal/description/
/// 二叉树的层序遍历
/// 时间复杂度: O(n), n为树的节点个数
/// 空间复杂度: O(n)
type
TList_int_int = specialize TArrayList<TList_int>;
TSolution = class(TObject)
public
function levelOrder(root: TTreeNode): TList_int_int;
end;
procedure Main;
implementation
procedure Main;
var
a: TArr_int;
t: TTreeNode;
l: TList_int_int;
i: integer;
begin
a := [9, 3, 20, 15, 7];
t := TTreeNode.Create(a);
with TSolution.Create do
begin
l := levelOrder(t);
for i := 0 to l.Count - 1 do
TArrayUtils_int.Print(l[i].ToArray);
for i := 0 to l.Count-1 do
l[i].Free;
l.Free;
Free;
end;
t.ClearAndFree;
end;
{ TSolution }
function TSolution.levelOrder(root: TTreeNode): TList_int_int;
type
TPair = record
node: TTreeNode;
level: integer;
end;
TQueue_pair = specialize TQueue<TPair>;
function __Pair__(node: TTreeNode; level: integer): TPair;
begin
Result.node := node;
Result.level := level;
end;
var
queue: TQueue_pair;
res: TList_int_int;
pair: TPair;
level: integer;
cur: TTreeNode;
begin
if root = nil then
Exit(nil);
res := TList_int_int.Create;
queue := TQueue_pair.Create;
queue.EnQueue(__Pair__(root, 0));
while not queue.IsEmpty do
begin
pair := queue.DeQueue;
level := pair.level;
cur := pair.node;
if level = res.Count then
res.AddLast(TList_int.Create);
res[level].AddLast(cur.Val);
if cur.Left <> nil then
queue.EnQueue(__Pair__(cur.Left, level + 1));
if cur.Right <> nil then
queue.EnQueue(__Pair__(cur.Right, level + 1));
end;
Result := res;
queue.Free;
end;
end.
|
unit OTFEStrongDiskTestApp_U;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
{$IFDEF LINUX}
This software is only intended for use under MS Windows
{$ENDIF}
{$WARN UNIT_PLATFORM OFF} // Useless warning about platform - we're already
// protecting against that!
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, FileCtrl, ComCtrls,
OTFE_U,
OTFEStrongDisk_U;
type
TOTFEStrongDiskTestApp_F = class(TForm)
pbClose: TButton;
pbVersion: TButton;
edTestIfMtdVolFile: TEdit;
DriveComboBox1: TDriveComboBox;
pbBrowse: TButton;
pbDisountVolume: TButton;
pbMountVolume: TButton;
pbDismountDrive: TButton;
pbClear: TButton;
pbGetDriveInfo: TButton;
rgActive: TRadioGroup;
pbGetFileMountedForDrive: TButton;
pbGetDriveMountedForFile: TButton;
pbNumDrivesMounted: TButton;
pbRefresh: TButton;
OpenDialog1: TOpenDialog;
pbGetMountedDrives: TButton;
pbDismountAll: TButton;
gbVolInfo: TGroupBox;
lblReadOnly: TLabel;
lblDriveMountedAs: TLabel;
lblFilename: TLabel;
Label15: TLabel;
Label22: TLabel;
Label23: TLabel;
lblAlgorithm: TLabel;
lblKeyGen: TLabel;
Label8: TLabel;
Label11: TLabel;
pbIsEncryptedVolFile: TButton;
Label1: TLabel;
lblVolumeType: TLabel;
pbIsDriverInstalled: TButton;
RichEdit1: TRichEdit;
OTFEStrongDisk1: TOTFEStrongDisk;
procedure pbCloseClick(Sender: TObject);
procedure rgActiveClick(Sender: TObject);
procedure pbVersionClick(Sender: TObject);
procedure pbNumDrivesMountedClick(Sender: TObject);
procedure pbDismountDriveClick(Sender: TObject);
procedure pbGetFileMountedForDriveClick(Sender: TObject);
procedure pbIsPGPDiskVolumeClick(Sender: TObject);
procedure pbMountVolumeClick(Sender: TObject);
procedure pbDisountVolumeClick(Sender: TObject);
procedure pbGetDriveMountedForFileClick(Sender: TObject);
procedure pbClearClick(Sender: TObject);
procedure pbBrowseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure pbRefreshClick(Sender: TObject);
procedure pbGetMountedDrivesClick(Sender: TObject);
procedure pbDismountAllClick(Sender: TObject);
procedure pbGetDriveInfoClick(Sender: TObject);
procedure pbIsDriverInstalledClick(Sender: TObject);
private
procedure ReportWhetherActive();
procedure RefreshDriveComboBox();
public
{ Public declarations }
end;
var
OTFEStrongDiskTestApp_F: TOTFEStrongDiskTestApp_F;
implementation
{$R *.DFM}
uses SDUGeneral;
procedure TOTFEStrongDiskTestApp_F.ReportWhetherActive();
begin
if OTFEStrongDisk1.Active then
begin
RichEdit1.lines.add('StrongDisk component ACTIVE');
rgActive.ItemIndex:=0;
end
else
begin
RichEdit1.lines.add('StrongDisk component NOT Active');
rgActive.ItemIndex:=1;
end;
end;
procedure TOTFEStrongDiskTestApp_F.pbCloseClick(Sender: TObject);
begin
Close;
end;
procedure TOTFEStrongDiskTestApp_F.pbVersionClick(Sender: TObject);
begin
RichEdit1.lines.add('StrongDisk driver version: 0x'+inttohex(OTFEStrongDisk1.Version(), 1));
end;
procedure TOTFEStrongDiskTestApp_F.pbIsPGPDiskVolumeClick(Sender: TObject);
var
filename: string;
output: string;
begin
filename := edTestIfMtdVolFile.text;
output := filename;
if OTFEStrongDisk1.IsEncryptedVolFile(filename) then
begin
output := output + ' IS ';
end
else
begin
output := output + ' is NOT ';
end;
output := output + 'a StrongDisk volume file';
RichEdit1.lines.add(output);
end;
procedure TOTFEStrongDiskTestApp_F.pbBrowseClick(Sender: TObject);
begin
OpenDialog1.Filename := edTestIfMtdVolFile.text;
if OpenDialog1.execute() then
begin
edTestIfMtdVolFile.text := OpenDialog1.FileName;
end;
end;
procedure TOTFEStrongDiskTestApp_F.pbMountVolumeClick(Sender: TObject);
begin
if OTFEStrongDisk1.Mount(edTestIfMtdVolFile.text)<>#0 then
begin
RichEdit1.lines.add(edTestIfMtdVolFile.text+' mounted OK');
end
else
begin
RichEdit1.lines.add(edTestIfMtdVolFile.text+' mount failed');
end;
RefreshDriveComboBox();
end;
procedure TOTFEStrongDiskTestApp_F.pbDisountVolumeClick(Sender: TObject);
begin
if OTFEStrongDisk1.Dismount(edTestIfMtdVolFile.text) then
begin
RichEdit1.lines.add(edTestIfMtdVolFile.text+' dismounted OK');
end
else
begin
RichEdit1.lines.add(edTestIfMtdVolFile.text+' dismount failed');
end;
RefreshDriveComboBox();
end;
procedure TOTFEStrongDiskTestApp_F.pbDismountDriveClick(Sender: TObject);
var
output: string;
begin
output := DriveComboBox1.drive + ': ';
if OTFEStrongDisk1.Dismount(DriveComboBox1.drive) then
begin
output := output + 'dismounted OK';
end
else
begin
output := output + 'dismount FAILED';
end;
RichEdit1.lines.add(output);
RefreshDriveComboBox();
end;
procedure TOTFEStrongDiskTestApp_F.RefreshDriveComboBox();
var
origCase: TTextCase;
begin
origCase := DriveComboBox1.TextCase;
DriveComboBox1.TextCase := tcUpperCase;
DriveComboBox1.TextCase := tcLowerCase;
DriveComboBox1.TextCase := origCase;
end;
procedure TOTFEStrongDiskTestApp_F.pbClearClick(Sender: TObject);
begin
RichEdit1.lines.Clear();
end;
procedure TOTFEStrongDiskTestApp_F.rgActiveClick(Sender: TObject);
begin
try
OTFEStrongDisk1.Active := (rgActive.ItemIndex=0);
finally
ReportWhetherActive();
end;
end;
procedure TOTFEStrongDiskTestApp_F.pbGetFileMountedForDriveClick(Sender: TObject);
var
output: string;
begin
output := DriveComboBox1.drive +
': is E4M volume file: "' +
OTFEStrongDisk1.GetVolFileForDrive(DriveComboBox1.drive) +
'"';
RichEdit1.lines.add(output);
end;
procedure TOTFEStrongDiskTestApp_F.pbGetDriveMountedForFileClick(Sender: TObject);
var
output: string;
drive: char;
begin
drive := OTFEStrongDisk1.GetDriveForVolFile(edTestIfMtdVolFile.text);
if drive=#0 then
begin
output := '"' +
edTestIfMtdVolFile.text +
'" not mounted';
end
else
begin
output := '"' +
edTestIfMtdVolFile.text +
'" is mounted as: '+
OTFEStrongDisk1.GetDriveForVolFile(edTestIfMtdVolFile.text) +
':';
end;
RichEdit1.lines.add(output);
end;
procedure TOTFEStrongDiskTestApp_F.FormCreate(Sender: TObject);
begin
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
edTestIfMtdVolFile.text := 'c:\e4mcipher.vol';
end
else
begin
edTestIfMtdVolFile.text := 'E:\VolumeFiles\E4Mtest_1.vol';
end;
edTestIfMtdVolFile.text := 'C:\Image1.grd';
end;
procedure TOTFEStrongDiskTestApp_F.pbNumDrivesMountedClick(Sender: TObject);
var
output: string;
begin
output := 'Number of volumes mounted: ';
output := output + inttostr(OTFEStrongDisk1.CountDrivesMounted());
RichEdit1.lines.add(output);
end;
procedure TOTFEStrongDiskTestApp_F.pbRefreshClick(Sender: TObject);
begin
RefreshDriveComboBox();
end;
procedure TOTFEStrongDiskTestApp_F.pbGetMountedDrivesClick(Sender: TObject);
begin
RichEdit1.lines.Add('Drives currently mounted are: '+OTFEStrongDisk1.DrivesMounted());
end;
procedure TOTFEStrongDiskTestApp_F.pbDismountAllClick(Sender: TObject);
var
output: string;
begin
output := '';
if length(OTFEStrongDisk1.DismountAll())=0 then
begin
output := output + 'DismountAll OK';
end
else
begin
output := output + 'DismountAll FAILED';
end;
RichEdit1.lines.add(output);
end;
procedure TOTFEStrongDiskTestApp_F.pbGetDriveInfoClick(Sender: TObject);
//var
// info: TOTFEE4MVolumeInfo;
begin
{
info := OTFEStrongDisk1.GetDriveInfo(DriveComboBox1.drive);
lblFilename.caption := info.volumeFilename;
lblDriveMountedAs.caption := info.mountedAs;
lblAlgorithm.caption := info.cipherName;
lblKeyGen.caption := info.hashName;
lblVolumeType.caption := info.volumeTypeName;
if info.readonly then
begin
lblReadOnly.caption := 'Readonly';
end
else
begin
lblReadOnly.caption := 'Read/Write';
end;
}
end;
procedure TOTFEStrongDiskTestApp_F.pbIsDriverInstalledClick(Sender: TObject);
begin
if OTFEStrongDisk1.IsDriverInstalled() then
begin
RichEdit1.lines.add('Driver installed');
end
else
begin
RichEdit1.lines.add('Driver NOT installed');
end;
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
{$WARN UNIT_PLATFORM ON}
// -----------------------------------------------------------------------------
END.
|
Unit RefObject;
Interface
Uses
Generics.Collections;
Type
TRefObject = Class
Private
FReferenceCount : Integer;
Public
Constructor Create; Reintroduce;
Function Reference:TRefObject;
Procedure Free; Reintroduce;
Procedure DisposeOf; Reintroduce;
Property ReferenceCount : Integer Read FReferenceCount;
end;
TRefObjectList<T: TRefObject> = Class (TObjectList<T>)
Protected
Procedure Notify(const Value: T; Action: TCollectionNotification); Override;
Public
end;
TRefObjectDictionary<K;V:TRefObject> = Class (TObjectDictionary<K, V>)
Protected
Procedure ValueNotify(const Value: V; Action: TCollectionNotification); Override;
Public
Constructor Create; Reintroduce;
end;
Implementation
Uses
Windows;
(** TRefObject **)
Constructor TRefObject.Create;
begin
Inherited Create;
InterlockedExchange(FReferenceCount, 1);
end;
Function TRefObject.Reference:TRefObject;
begin
InterlockedIncrement(FReferenceCount);
Result := Self;
end;
Procedure TRefObject.Free;
begin
If (Assigned(Self)) And
(InterlockedDecrement(FReferenceCount) = 0) Then
Inherited Free;
end;
Procedure TRefObject.DisposeOf;
begin
Free;
end;
(** TRefObjectList **)
Procedure TRefObjectList<T>.Notify(const Value: T; Action: TCollectionNotification);
begin
If Assigned(Value) THen
begin
Case action Of
cnAdded: Value.Reference;
cnRemoved: Value.Free;
end;
end;
If Assigned(OnNotify) Then
OnNotify(Self, Value, Action);
end;
(** TRefObjectDictionary **)
Constructor TRefObjectDictionary<K,V>.Create;
begin
Inherited Create([doOwnsValues]);
end;
Procedure TRefObjectDictionary<K,V>.ValueNotify(const Value: V; Action: TCollectionNotification);
begin
Case Action Of
cnAdded : Value.Reference;
cnRemoved : Value.Free;
end;
If Assigned(OnValueNotify) Then
OnValueNotify(Self, Value, Action);
end;
End.
|
(*
Category: SWAG Title: FILE & ENCRYPTION ROUTINES
Original name: 0031.PAS
Description: A small encryption unit
Author: LUDOVIC RUSSO
Date: 03-04-97 13:18
*)
{
Ludovic RUSSO offers you :
One recursive encrypt-decrypt program. Only the first char doesn't
change.
Because of the recursivity, the same char is *never* crpyted the same
way
(take a look at the points in the sentence)
}
PROGRAM RecursiveCrypt;
TYPE str80=string[80];
PROCEDURE Crypt(var mess:str80;lg:integer);
BEGIN
If lg>1 Then
Begin
crypt(mess,lg-1);
mess[lg]:=chr((ord(mess[lg-1])+ord(mess[lg])) mod 256);
End;
END;
PROCEDURE DeCrypt(var mess:str80;lg:integer);
BEGIN
If lg>=2 Then
Begin
mess[lg]:=chr((ord(mess[lg])-ord(mess[lg-1])+256) mod 256);
decrypt(mess,lg-1);
End;
END;
VAR w:str80;
BEGIN
w:='You can join me at lrusso@ice.unice.fr';
crypt(w,length(w));writeln('Crypted word : ',w);
decrypt(w,length(w));writeln('Uncrypted word : ',w);
END.
|
unit TarifGridAdd;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLabel, cxCurrencyEdit, cxControls, cxContainer, cxEdit,
cxTextEdit, cxLookAndFeelPainters, ActnList, StdCtrls, cxButtons,
cxMaskEdit, cxDropDownEdit, cxCalendar, uFControl, uLabeledFControl,
uCharControl, uFloatControl, cxCheckBox, BaseTypes, ExtCtrls, uIntControl,
DateUtils, DB, FIBDataSet, pFIBDataSet, Math;
type
TfrmTarifGridAdd = class(TForm)
btnOk: TcxButton;
btnCancel: TcxButton;
ActList: TActionList;
ActOk: TAction;
ActCancel: TAction;
DataSet: TpFIBDataSet;
TarifRate: TcxCurrencyEdit;
lblTarifRate: TcxLabel;
cxLabel1: TcxLabel;
MinValueEdit: TcxCurrencyEdit;
SumEdit: TcxCurrencyEdit;
cxLabel2: TcxLabel;
PeriodBox: TGroupBox;
lblDateBeg: TcxLabel;
TarifDateBeg: TcxDateEdit;
lblDateEnd: TcxLabel;
WithOutEndPeriod: TcxCheckBox;
TarifDateEnd: TcxDateEdit;
procedure ActOkExecute(Sender: TObject);
procedure ActCancelExecute(Sender: TObject);
procedure WithOutEndPeriodPropertiesChange(Sender: TObject);
procedure TarifRatePropertiesChange(Sender: TObject);
procedure TarifDateBegPropertiesChange(Sender: TObject);
private
LocDate:TDate;
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner:TComponent; EditMode:Boolean);
procedure FillMinValueEdit(ActualDate:TDate);
end;
var
frmTarifGridAdd: TfrmTarifGridAdd;
implementation
uses TarifGridMain;
{$R *.dfm}
constructor TfrmTarifGridAdd.Create(AOwner:TComponent; EditMode:Boolean);
begin
inherited Create(AOwner);
if EditMode=False then
begin
TarifDateBeg.Date:=EncodeDate(YearOf(Date), MonthOf(Date), 1);
TarifDateEnd.Date:=Date;
TarifRate.Value:=1;
WithOutEndPeriod.Checked:=True;
end;
FillMinValueEdit(TarifDateEnd.Date);
end;
procedure TfrmTarifGridAdd.FillMinValueEdit(ActualDate:TDate);
begin
try
DataSet.Close;
DataSet.SQLs.SelectSQL.Text:='select min_value from get_min_category(:act_date)';
DataSet.ParamByName('act_date').AsDate:=ActualDate;
DataSet.Open;
MinValueEdit.Text:=FloatToStr(DataSet['Min_Value']);
except on E:Exception
do begin
MinValueEdit.Text:='0';
end;
end;
end;
procedure TfrmTarifGridAdd.ActOkExecute(Sender: TObject);
begin
If (DateToStr(TarifDateBeg.Date)='00.00.0000') then
begin
TarifDateBeg.Style.Color:=clRed;
agMessageDlg('Увага', 'Треба заповнити дату початку!', mtInformation, [mbOK]);
Exit;
end;
If ((DateToStr(TarifDateEnd.Date)='00.00.0000') And (WithOutEndPeriod.Checked=False)) then
begin
TarifDateEnd.Style.Color:=clRed;
agMessageDlg('Увага', 'Треба заповнити дату кінця!', mtInformation, [mbOK]);
Exit;
end;
If (VarIsNull(TarifRate.Value)) then
begin
TarifRate.Style.Color:=clRed;
agMessageDlg('Увага', 'Треба ввести ставку першого розряду!', mtInformation, [mbOK]);
Exit;
end;
If (TarifDateBeg.Date>TarifDateEnd.Date) then
begin
TarifDateBeg.Style.Color:=clRed;
agMessageDlg('Увага', 'Дата початку повинна бути менш, ніж дата кінця!', mtInformation, [mbOK]);
Exit;
end;
TarifDateBeg.Date:=EncodeDate(YearOf(TarifDateBeg.Date), MonthOf(TarifDateBeg.Date), 1);
TarifDateEnd.Date:=EncodeDate(YearOf(TarifDateEnd.Date), MonthOf(TarifDateEnd.Date), DaysInMonth(TarifDateEnd.Date));
ModalResult:=mrOk;
end;
procedure TfrmTarifGridAdd.ActCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TfrmTarifGridAdd.WithOutEndPeriodPropertiesChange(
Sender: TObject);
begin
TarifDateEnd.Visible:=not WithOutEndPeriod.Checked;
If WithOutEndPeriod.Checked Then TarifDateEnd.Date:=EncodeDate(9999, 12, 31);
end;
procedure TfrmTarifGridAdd.TarifRatePropertiesChange(Sender: TObject);
var CurValue, MinVal:Double;
begin
try
CurValue:=StrToFloat(TarifRate.Text);
MinVal:=StrToFloat(MinValueEdit.Text);
except
CurValue:=0;
MinVal:=0;
end;
SumEdit.Text:=FloatToStr(SimpleRoundTo(CurValue*MinVal, -2));
end;
procedure TfrmTarifGridAdd.TarifDateBegPropertiesChange(Sender: TObject);
begin
if Length(TarifDateBeg.EditText)=10 then
begin
TarifDateBeg.Date:=StrToDate(TarifDateBeg.EditText);
FillMinValueEdit(TarifDateBeg.Date);
TarifRatePropertiesChange(Sender);
end;
end;
end.
|
unit ReCountFilter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ActnList, StdCtrls, cxButtons,
cxControls, cxContainer, cxEdit, cxRadioGroup, Unit_ZGlobal_Consts,
ZProc;
type
TFRecountFilter = class(TForm)
ItemsFilter: TcxRadioGroup;
CancelBtn: TcxButton;
YesBtn: TcxButton;
ActionList: TActionList;
ActionYes: TAction;
ActionCancel: TAction;
procedure ActionYesExecute(Sender: TObject);
procedure ActionCancelExecute(Sender: TObject);
private
PlanguageIndex:Byte;
public
constructor Create(AOwner:TComponent);reintroduce;
end;
function ViewFilter(AOwner:TComponent;AItemIndex:byte=1):byte;
implementation
{$R *.dfm}
function ViewFilter(AOwner:TComponent;AItemIndex:byte=1):byte;
var FormView:TFRecountFilter;
begin
FormView:=TFRecountFilter.Create(AOwner);
FormView.ItemsFilter.ItemIndex := AItemIndex-1;
if FormView.ShowModal=mrYes then Result:=FormView.ItemsFilter.ItemIndex+1
else Result:=0;
FormView.Destroy;
end;
constructor TFRecountFilter.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
PlanguageIndex:=LanguageIndex;
//******************************************************************************
Caption := FilterBtn_Caption[PlanguageIndex];
YesBtn.Caption := YesBtn_Caption[PlanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PlanguageIndex];
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Hint := CancelBtn.Caption;
//******************************************************************************
ItemsFilter.Properties.Items[0].Caption:=NotFilter_Const[PlanguageIndex];
ItemsFilter.Properties.Items[1].Caption:=SumMoreNull_Const[PlanguageIndex];
ItemsFilter.Properties.Items[2].Caption:=SumLessNull_Const[PlanguageIndex];
ItemsFilter.Properties.Items[3].Caption:=SumEqualNull_Const[PlanguageIndex];
ItemsFilter.Properties.Items[4].Caption:=SumIsNull_Const[PlanguageIndex];
end;
procedure TFRecountFilter.ActionYesExecute(Sender: TObject);
begin
ModalResult:=mrYes;
end;
procedure TFRecountFilter.ActionCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
end.
|
unit LrDocument;
interface
uses
SysUtils, Classes, Controls, Dialogs;
type
TLrDocument = class;
TLrDocumentClass = class of TLrDocument;
TLrDocumentController = class;
TLrDocumentControllerClass = class of TLrDocumentController;
//
TLrDocument = class
private
FActive: Boolean;
FClosed: Boolean;
FController: TLrDocumentController;
FFilename: string;
FModified: Boolean;
FUntitled: Boolean;
FOldFilename: string;
protected
function GetDisplayName: string; virtual;
function GetThisDocument: TLrDocument;
function GetUntitledName: string; virtual;
procedure Change;
procedure SetActive(const Value: Boolean); virtual;
procedure SetFilename(const Value: string); virtual;
procedure SetModified(const Value: Boolean); virtual;
procedure SetUntitled(const Value: Boolean); virtual;
public
constructor Create; virtual;
function CanClose: Boolean; virtual;
function Close: Boolean; virtual;
procedure Activate; virtual;
procedure Deactivate; virtual;
procedure DoModified(inSender: TObject); virtual;
procedure Load; virtual;
procedure Modify; virtual;
procedure New; virtual;
procedure Open(const inFilename: string); virtual;
procedure Save; virtual;
procedure SaveAs(const inFilename: string); virtual;
procedure Update; virtual;
property Active: Boolean read FActive write SetActive;
property Closed: Boolean read FClosed write FClosed;
property Controller: TLrDocumentController read FController
write FController;
property DisplayName: string read GetDisplayName;
property Filename: string read FFilename write SetFilename;
property OldFilename: string read FOldFilename write FOldFilename;
property Modified: Boolean read FModified write SetModified;
property ThisDocument: TLrDocument read GetThisDocument;
property Untitled: Boolean read FUntitled write SetUntitled;
property UntitledName: string read GetUntitledName;
end;
//
TLrDocumentController = class
private
FOnChange: TNotifyEvent;
public
class function GetDescription: string; virtual;
class function GetExt: string; virtual;
protected
procedure Change;
public
function CreateDocument(inClass: TLrDocumentClass): TLrDocument;
function New: TLrDocument; virtual;
procedure DocumentActivate(inDocument: TLrDocument); virtual;
procedure DocumentChange(inDocument: TLrDocument); virtual;
procedure DocumentClose(inDocument: TLrDocument); virtual;
procedure DocumentDeactivate(inDocument: TLrDocument); virtual;
procedure DocumentUpdate(inDocument: TLrDocument); virtual;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
{ TLrDocument }
constructor TLrDocument.Create;
begin
Untitled := true;
end;
procedure TLrDocument.Activate;
begin
if not Active then
begin
FActive := true;
Controller.DocumentActivate(Self);
end;
end;
procedure TLrDocument.Deactivate;
begin
if Active then
begin
Update;
Controller.DocumentDeactivate(Self);
FActive := false;
end;
end;
procedure TLrDocument.Change;
begin
Controller.DocumentChange(Self);
end;
procedure TLrDocument.SetModified(const Value: Boolean);
begin
if FModified <> Value then
FModified := Value;
Change;
end;
procedure TLrDocument.Modify;
begin
Modified := true;
end;
procedure TLrDocument.DoModified(inSender: TObject);
begin
Modify;
end;
function Confirm(const inMsg: string): TModalResult;
begin
Result := MessageDlg(inMsg, mtConfirmation, mbYesNoCancel, 0);
end;
function TLrDocument.CanClose: Boolean;
begin
Result := true;
if Modified then
case Confirm('Save changes to "' + DisplayName + '" before closing?') of
mrNo:
Modified := false;
mrYes:
if not Untitled then
Save;
mrCancel:
Result := false;
end;
end;
function TLrDocument.Close: Boolean;
begin
Update;
Closed := CanClose;
Controller.DocumentClose(Self);
Result := Closed;
end;
function TLrDocument.GetUntitledName: string;
begin
Result := 'Untitled' + Controller.GetExt;
end;
function TLrDocument.GetDisplayName: string;
begin
if Filename <> '' then
Result := ExtractFileName(Filename)
else
Result := UntitledName;
end;
procedure TLrDocument.New;
begin
//
end;
procedure TLrDocument.Load;
begin
//
end;
procedure TLrDocument.Open(const inFilename: string);
begin
Untitled := false;
Modified := false;
Filename := inFilename;
OldFilename := inFilename;
Load;
end;
procedure TLrDocument.Update;
begin
Controller.DocumentUpdate(Self);
end;
procedure TLrDocument.Save;
begin
Update;
Modified := false;
end;
procedure TLrDocument.SaveAs(const inFilename: string);
begin
OldFilename := Filename;
Filename := inFilename;
Untitled := false;
Save;
end;
procedure TLrDocument.SetActive(const Value: Boolean);
begin
if Active <> Value then
if Value then
Activate
else
Deactivate;
end;
procedure TLrDocument.SetUntitled(const Value: Boolean);
begin
FUntitled := Value;
end;
procedure TLrDocument.SetFilename(const Value: string);
begin
FFilename := Value;
//Untitled := Filename = '';
end;
function TLrDocument.GetThisDocument: TLrDocument;
begin
Result := Self;
end;
{ TLrDocumentController }
class function TLrDocumentController.GetDescription: string;
begin
Result := '';
end;
class function TLrDocumentController.GetExt: string;
begin
Result := '';
end;
procedure TLrDocumentController.Change;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
function TLrDocumentController.CreateDocument(
inClass: TLrDocumentClass): TLrDocument;
begin
Result := inClass.Create;
Result.Controller := Self;
end;
function TLrDocumentController.New: TLrDocument;
begin
Result := nil;
end;
procedure TLrDocumentController.DocumentActivate(inDocument: TLrDocument);
begin
//
end;
procedure TLrDocumentController.DocumentChange(inDocument: TLrDocument);
begin
Change;
end;
procedure TLrDocumentController.DocumentClose(inDocument: TLrDocument);
begin
//
end;
procedure TLrDocumentController.DocumentDeactivate(
inDocument: TLrDocument);
begin
//
end;
procedure TLrDocumentController.DocumentUpdate(inDocument: TLrDocument);
begin
//
end;
end.
|
unit SuperComboADO;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, DBCtrls, Buttons, DB, DBTables, LookUpADOQuery, DbGrids,
ExtCtrls, ADODb, uSystemTypes, Variants;
// Nova versao nao guardo mais o LookUpValue e ListValue no LookUpQuery, mas sim no
// Combo.
procedure Register;
const GridHeight = 12;
type
TSubButton = class( TBitBtn )
protected
procedure Click; override;
end;
type
TDbLookUpGrid = class( TDbGrid )
protected
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL;
constructor Create( AOwner: TComponent ); override;
public
ObjectSuperCombo : TObject;
OnClick : TNotifyEvent;
end;
type
TOnNotInListEvent = procedure (Sender : TObject; LastText : String) of object;
TEditCodePos = (taEditCodeLeft, taEditCodeRight);
TSuperComboADO = class(TMaskEdit)
private
{ Private declarations }
FOnBeforeOpenGrid : TNotifyEvent; {# Antes de abrir o grid }
AdjustBounds : Boolean;
OriginalWidth, OriginalLeft : Integer;
FLinkedRadioButton : TRadioButton;
FOtherColumns : String;
FButton : TSubButton; {## Something to push at }
EditCode : TEdit; {## Edit do codigo }
btnAddNew : TButton; {## Botao de Add New }
btnUpdate : TButton; {## Botao de Update }
LookUpForm : TForm;
LookUpPanel : TPanel; {## Botao de Update }
bmMemory: TBitmap; {## For the dots }
FEnab : Boolean; {## My Enabled-Property }
FVisible : Boolean; {## My Visible-Property }
FReadOnly : Boolean; {## My ReadOnly-Property }
FLookUpSource : TDataSource; { DataSource da Lista de valores }
FOnNotInList : TOnNotInListEvent; {# Evento quando item nao pertence a lista }
FOnSelectItem : TNotifyEvent; {# Evento quando item e selecionado }
FOnAfterAddUpdate : TNotifyEvent;
FOnBeforeSelectItem : TNotifyEvent; {# Evento antes de item selecionado }
LookUpADOQuery : TLookUpADOQuery; { Query LookUp }
LookUpGrid : TDbLookUpGrid; { Grid para visualizacao }
IsChange : Boolean; // Habilita/Desabilita o Evento Change
IsLocate : Boolean;
FShowBtnAddNew, FShowBtnUpdate, FShowBtnSelecao : Boolean;
FDropDownRows : integer;
FTop, FLeft, FWidth, FHeight : integer;
FLookUpValue : String;
FIsListFiltered, FFilterSugest,
IsLookUpQuerySet, IsKeyPressed : Boolean;
FSpcWhereClause, FltWhereClause : String;
OldValue, OldText : String;
FFilterFields : TStringList; { campos do filtro }
FFilterValues : TStringList; { valores do filtro }
IsFoundKey : Boolean;
LastText : String;
FShowEditCode, lExitSize : Boolean;
FCodeLength : Integer;
FEditCodePos : TEditCodePos;
ForcaTrocaLookUp, NoExtraKey : Boolean;
FMostraDesativado : TDesativadoState;
FMostraHidden : THiddenState;
First, IsLookUpValue, AllowSelectItem : Boolean;
FComboFields: TComboFields;
procedure AdjustComboBounds;
procedure SetShowBtnSelecao(Value : Boolean);
procedure SetFilterFields(Value : TStringList);
procedure SetFilterValues(Value : TStringList);
procedure SetExit(AShowing: Boolean = false);
procedure SetSpcWhereClause(Value: String);
procedure SetLookUpValue(Value: String);
procedure SetVisible(Value: Boolean);
procedure SetEnabled(Value: Boolean);
procedure SetReadOnly(Value: Boolean);
procedure SetLookUpSource(Value : TDataSource);
function GetLookUpFieldValue : Variant;
procedure OpenGrid;
procedure LookUpGridClick(Sender : TObject);
procedure LookUpGridDblClick(Sender : TObject);
procedure UpdateValues;
procedure SelectActualValue;
procedure AddUpdateClick(Sender : TObject);
procedure LookUpFormShow(Sender : TObject);
procedure OwnerDeactivate(Sender: TObject);
procedure CMCancelMode(var Message: TCMCancelMode); message CM_CancelMode;
procedure WMKillFocus(var Message: TMessage); message WM_KillFocus;
procedure CNKeyDown(var Message: TWMKeyDown); message CN_KEYDOWN; {handle esc}
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
Procedure DrawDropDownArrow(Canvas: TCanvas; R: TRect;
State: TButtonState;
Enabled: Boolean;
ControlState: TControlState);
procedure FillFieldValues(var AComboFields: TComboFields);
protected
{ Protected declarations }
FIDLanguage : Integer;
sAll, sErrorFilter,
sSelecLookUp, sDefineEvent,
sPossValues, sNewItem1,
sNewItem2, sUpdate1,
sUpdate2 : String;
procedure SetLookUpQuery;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
procedure Change; override; {## Chama o OpenGrid }
procedure DoEnter; override;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
procedure WMSize( var Message: TWMSize ); message WM_SIZE;
constructor Create( AOwner: TComponent ); override;
destructor Destroy; override;
public
{ Public declarations }
DataAware : Boolean;
CodeValue, ListValue : String;
procedure SetAll;
procedure CallUpdate;
procedure ClearFilters;
procedure GetFirstValue;
procedure GetLastValue;
procedure GetPriorValue;
procedure GetNextValue;
procedure GetPriorPage;
procedure GetNextPage;
function GetFieldByName(AFieldName: string): Variant;
procedure AddFilter(aFields, aValues : array of string);
procedure CreateParams( var Params: TCreateParams ); override;
property ComboFields: TComboFields read FComboFields;
property LookUpValue : String read FLookUpValue write SetLookUpValue;
property LookUpFieldValue : Variant read GetLookUpFieldValue;
property OnBeforeSelectItem : TNotifyEvent read FOnBeforeSelectItem write FOnBeforeSelectItem;
published
{ Published declarations }
property LinkedRadioButton : TRadioButton read FLinkedRadioButton write FLinkedRadioButton;
property CodeLength : Integer read FCodeLength write FCodeLength default 40;
property FilterFields : TStringList read FFilterFields write SetFilterFields;
property FilterValues : TStringList read FFilterValues write SetFilterValues;
property FilterSugest : Boolean read FFilterSugest write FFilterSugest default False;
property SpcWhereClause : String read FSpcWhereClause write SetSpcWhereClause;
property Enabled : Boolean read FEnab write SetEnabled default True;
property Visible : Boolean read FVisible write SetVisible default True;
property ReadOnly : Boolean read FReadOnly write SetReadOnly default False;
property LookUpSource : TDataSource read FLookUpSource write SetLookUpSource;
property IsListFiltered : Boolean read FIsListFiltered write FIsListFiltered default True;
property DropDownRows : integer read FDropDownRows write FDropDownRows default 20;
property ShowBtnAddNew : Boolean read FShowBtnAddNew write FShowBtnAddNew default True;
property ShowBtnUpdate : Boolean read FShowBtnUpdate write FShowBtnUpdate default True;
property ShowBtnSelecao : Boolean read FShowBtnSelecao write SetShowBtnSelecao default True;
property ShowEditCode : Boolean read FShowEditCode write FShowEditCode default False;
property EditCodePos : TEditCodePos read FEditCodePos write FEditCodePos default taEditCodeLeft;
property OtherColumns : String read FOtherColumns write FOtherColumns;
property MostraDesativado : TDesativadoState read FMostraDesativado write FMostraDesativado default STD_NAODESATIVADO;
property MostraHidden : THiddenState read FMostraHidden write FMostraHidden default STD_NAOHIDDEN;
property IDLanguage : Integer read FIDLanguage write FIDLanguage default 1;
// Eventos
property OnSelectItem : TNotifyEvent read FOnSelectItem write FOnSelectItem;
property OnBeforeOpenGrid : TNotifyEvent read FOnBeforeOpenGrid write FOnBeforeOpenGrid;
property OnNotInList : TOnNotInListEvent read FOnNotInList write FOnNotInList;
property OnAfterAddUpdate : TNotifyEvent read FOnAfterAddUpdate write FOnAfterAddUpdate;
{
// Herdados
property AutoSelect;
property AutoSize;
property BorderStyle;
property CharCase;
property Color;
property Ctl3D;
property DragCursor;
property DragMode;
property Font;
property MaxLength;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property Picture;
property PopupMenu;
property ShowVertScrollBar;
property ShowHint;
property TabOrder;
property TabStop;
property UsePictureMask;
property Visible;
property WantReturns;
property WordWrap;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnCheckValue;
}
end;
TDBSuperComboADO = class(TSuperComboADO)
private
FDataLink: TFieldDataLink;
FCanvas: TControlCanvas;
FAlignment: TAlignment;
FFocused: Boolean;
procedure DataChange(Sender: TObject);
procedure EditingChange(Sender: TObject);
function GetDataField: string;
function GetDataSource: TDataSource;
function GetField: TField;
function GetReadOnly: Boolean;
function GetTextMargins: TPoint;
procedure SetDataField(const Value: string);
procedure SetDataSource(Value: TDataSource);
procedure SetFocused(Value: Boolean);
procedure SetReadOnly(Value: Boolean);
procedure UpdateData(Sender: TObject);
procedure WMCut(var Message: TMessage); message WM_CUT;
procedure WMPaste(var Message: TMessage); message WM_PASTE;
procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK;
protected
procedure Change; override;
function EditCanModify: Boolean; override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure Reset; override;
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Field: TField read GetField;
published
property DataField : string read GetDataField write SetDataField;
property DataSource : TDataSource read GetDataSource write SetDataSource;
property ReadOnly : Boolean read GetReadOnly write SetReadOnly default False;
end;
implementation
uses xBase, uNumericFunctions;
{ ---- TSubButton ---- }
procedure TSubButton.Click;
begin
inherited Click;
TSuperComboADO(Parent).DoEnter;
if TSuperComboADO(Parent).LookUpForm.Visible then
begin
TSuperComboADO(Parent).LookUpForm.Close;
TSuperComboADO(Parent).SetFocus;
end
else
TSuperComboADO(Parent).OpenGrid;
end;
{ ---- TDBLookUpgrid ---- }
constructor TDbLookUpGrid.Create( AOwner: TComponent );
begin
inherited Create( AOwner);
ScrollBars := ssVertical;
end;
procedure TDbLookUpGrid.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
if (Button = mbLeft) and not (ssDouble in Shift) then
begin
// Click do grid, seta o foco no parent
OnClick(Self);
end;
end;
procedure TDbLookUpGrid.WMVScroll(var Message: TWMVScroll);
var
SI: TScrollInfo;
begin
if CanFocus and not (csDesigning in ComponentState) then
begin
SetFocus;
if not (Focused or (InplaceEditor <> nil) and InplaceEditor.Focused) then
Exit;
end;
if TDataSet(Datasource.DataSet).Active then
begin
with Message, TDataSet(Datasource.DataSet) do
case ScrollCode of
SB_LINEUP : TSuperComboADO(ObjectSuperCombo).GetPriorValue;
SB_LINEDOWN : TSuperComboADO(ObjectSuperCombo).GetNextValue;
SB_PAGEUP : TSuperComboADO(ObjectSuperCombo).GetPriorPage;
SB_PAGEDOWN : TSuperComboADO(ObjectSuperCombo).GetNextPage;
SB_THUMBPOSITION:
begin
if IsSequenced then
begin
SI.cbSize := sizeof(SI);
SI.fMask := SIF_ALL;
GetScrollInfo(Self.Handle, SB_VERT, SI);
if SI.nTrackPos <= 1 then First
else if SI.nTrackPos >= RecordCount then Last
else RecNo := SI.nTrackPos;
end
else
case Pos of
0: TSuperComboADO(ObjectSuperCombo).GetFirstValue;
1: TSuperComboADO(ObjectSuperCombo).GetPriorPage;
2: Exit;
3: TSuperComboADO(ObjectSuperCombo).GetNextPage;
4: TSuperComboADO(ObjectSuperCombo).GetLastValue;
end;
end;
SB_BOTTOM : TSuperComboADO(ObjectSuperCombo).GetLastValue;
SB_TOP : TSuperComboADO(ObjectSuperCombo).GetFirstValue;
end;
TSuperComboADO(ObjectSuperCombo).FillFieldValues(TSuperComboADO(ObjectSuperCombo).FComboFields);
end;
end;
{---- TSuperCombo----}
constructor TSuperComboADO.Create( AOwner: TComponent );
begin
inherited Create( AOwner );
Case FIDLanguage of
1 : begin
sAll := '<ALL>';
sErrorFilter := 'SuperCombo - Filter error';
sSelecLookUp := ' - You must set the LookUpSource';
sDefineEvent := 'SuperCombo - Event OnClickButton not defined';
sPossValues := 'Possible values';
sNewItem1 := 'New Item';
sNewItem2 := '&New';
sUpdate1 := 'Update selected Item';
sUpdate2 := '&Update';
end;
2 : begin
sAll := '<Todos>';
sErrorFilter := 'SuperCombo - erro na passagem do filtro';
sSelecLookUp := ' - selecione um LookUpSource';
sDefineEvent := 'SuperCombo - Evento OnClickButton nao foi definido';
sPossValues := 'Possível valores';
sNewItem1 := 'Novo item';
sNewItem2 := '&Novo';
sUpdate1 := 'Atualizar item selecionado';
sUpdate2 := 'At&ualizar';
end;
3 : begin
sAll := '<Todos>';
sErrorFilter := 'SuperCombo - erro na passagem do filtro';
sSelecLookUp := ' - selecione um LookUpSource';
sDefineEvent := 'SuperCombo - Evento OnClickButton nao foi definido';
sPossValues := 'Possível valores';
sNewItem1 := 'Novo item';
sNewItem2 := '&Novo';
sUpdate1 := 'Atualizar item selecionado';
sUpdate2 := 'At&ualizar';
end;
else begin
sAll := '<ALL>';
sErrorFilter := 'SuperCombo - Filter error';
sSelecLookUp := ' - You must set the LookUpSource';
sDefineEvent := 'SuperCombo - Event OnClickButton not defined';
sPossValues := 'Possible values';
sNewItem1 := 'New Item';
sNewItem2 := '&New';
sUpdate1 := 'Update selected Item';
sUpdate2 := '&Update';
end;
end;
// Inicializa tamanho do vetor de campos/valores
SetLength(FComboFields, 0);
// Cria o bitmap
bmMemory := TBitmap.Create;
// Cria o botao de chamar o grid
FButton := TSubButton.Create( Self );
with FButton do
begin
TabStop := False;
Hint := sPossValues;
ShowHint := True;
Width := 16;
Height := 16;
Visible := True;
Parent := Self;
ControlStyle := ControlStyle - [csSetCaption];
end;
if not (csDesigning in ComponentState) then
begin
// Cria o EditCode
EditCode := TEdit.Create( Self );
with EditCode do
begin
Color := clBtnFace;
Font.Style := Font.Style + [fsBold];
TabStop := False;
Enabled := True;
ReadOnly := True;
Parent := Self;
end;
// Cria o LookUpForm
with TForm(AOwner) do
OnDeactivate := OwnerDeactivate;
LookUpForm := TForm.Create( Self );
with LookUpForm do
begin
{By Carlos}
Parent := Self.Parent;
BorderStyle := bsNone;
FormStyle := fsStayOnTop;
OnShow := LookUpFormShow;
end;
// Cria o Panel
LookUpPanel := TPanel.Create( LookUpForm );
with LookUpPanel do
begin
Parent := LookUpForm;
Align := alClient;
BevelWidth := 1;
Caption := '';
end;
// Cria o grid
LookUpGrid := TDBLookUpGrid.Create( LookUpPanel );
with LookUpGrid do
begin
Parent := LookUpPanel;
ObjectSuperCombo := Self;
OnClick := LookUpGridClick;
OnDblClick := LookUpGridDblClick;
Options := [dgTabs, dgRowSelect, dgAlwaysShowSelection, dgColLines];
TabStop := False;
end;
// Cria o botao de AddNew
btnAddNew := TButton.Create( LookUpPanel );
with btnAddNew do
begin
TabStop := False;
Parent := LookUpPanel;
Hint := sNewItem1;
Caption := sNewItem2;
ShowHint := True;
Height := 20;
Tag := 0;
OnClick := AddUpdateClick;
end;
// Cria o botao de Update
btnUpdate := TButton.Create( LookUpPanel );
with btnUpdate do
begin
TabStop := False;
Parent := LookUpPanel;
Hint := sUpdate1;
Caption := sUpdate2;
ShowHint := True;
Height := 20;
Tag := 1;
OnClick := AddUpdateClick;
end;
end;
// Cria os filtros
FFilterFields := TStringList.Create;
FFilterValues := TStringList.Create;
FFilterSugest := False;
FltWhereClause := ''; // String Where vinda dos filter fields
FSpcWhereClause := ''; // String where especial
IsLookUpQuerySet := False;
IsKeyPressed := False;
LastText := '';
IsFoundKey := True;
OriginalWidth := 0;
OriginalLeft := 0;
First := True;
OldText := '';
OldValue := '';
FOtherColumns := '';
FDropDownRows := 20;
FCodeLength := 40;
FShowBtnAddNew := True;
FShowBtnUpdate := True;
FShowBtnSelecao := True;
ForcaTrocaLookUp := False;
FShowEditCode := False;
FIsListFiltered := True;
lExitSize := False;
IsLookUpValue := True;
AllowSelectItem := True;
FEditCodePos := taEditCodeLeft;
FMostraDesativado := STD_NAODESATIVADO;
FMostraHidden := STD_NAOHIDDEN;
IsLocate := True;
IsChange := True;
FEnab := True;
FVisible := True;
DataAware := False;
AdjustBounds := True;
end;
destructor TSuperComboADO.Destroy;
begin
SetLength(FComboFields, 0);
EditCode := nil;
LookUpForm.Free;
bmMemory.Free;
FButton := nil;
FFilterFields.Free;
FFilterValues.Free;
if Assigned(LookUpADOQuery) then
with LookUpADOQuery do
begin
if Active then Close;
// LookUpADOQuery.ResetValues;
// SQL.Text := OriginalSQL; // Restaura o antigo SQL
end;
inherited Destroy;
end;
procedure TSuperComboADO.SetAll;
begin
// Se tiver Linkado o RadioButton All coloca o checked
if Assigned(LinkedRadioButton) then
LinkedRadioButton.Checked := True
else
begin
LookUpValue := '';
Text := sAll;
end;
end;
procedure TSuperComboADO.DoEnter;
begin
inherited DoEnter;
IsFoundKey := True;
// Se tiver Linkado o RadioButton All tira o checked
if Assigned(LinkedRadioButton) then
begin
if LinkedRadioButton.Checked then
begin
Text := '';
LinkedRadioButton.Checked := False;
end;
end;
end;
procedure TSuperComboADO.SetSpcWhereClause(Value : String);
begin
FSpcWhereClause := Value;
if Assigned(LookUpADOQuery) then LookUpADOQuery.Close;
end;
procedure TSuperComboADO.SetFilterFields(Value : TStringList);
begin
if FFilterFields <> Value then
FFilterFields.Assign(Value);
end;
procedure TSuperComboADO.SetFilterValues(Value : TStringList);
begin
if FFilterValues <> Value then
FFilterValues.Assign(Value);
end;
procedure TSuperComboADO.ClearFilters;
begin
FFilterFields.Clear;
FFilterValues.Clear;
end;
procedure TSuperComboADO.AddFilter(aFields, aValues : array of string);
var
i : integer;
begin
ClearFilters;
if High(aFields) <> High(aValues) then
raise exception.create(sErrorFilter)
else
begin
for i := Low(aFields) to High(aFields) do
begin
FFilterFields.Add(aFields[i]);
FFilterValues.Add(aValues[i]);
end;
end;
end;
procedure TSuperComboADO.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
OldLeft, OldTop, OldHeight, OldWidth : integer;
begin
OldLeft := Left;
OldTop := Top;
OldHeight := Height;
OldWidth := Width;
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
if (ALeft <> OldLeft) or (ATop <> OldTop) or
(AWidth <> OldWidth) or (AHeight <> OldHeight) then
begin
if AdjustBounds then
AdjustComboBounds;
end;
end;
procedure TSuperComboADO.SetLookUpSource(Value: TDataSource);
begin
FLookUpSource := Value;
if Value <> nil then
begin
Value.FreeNotification(Self);
IsLookUpQuerySet := False;
try
ForcaTrocaLookUp := True;
SetLookUpQuery;
finally
ForcaTrocaLookUp := False;
end;
end;
end;
procedure TSuperComboADO.CreateParams( var Params: TCreateParams );
begin
inherited CreateParams( Params );
Params.Style := Params.Style or WS_CLIPCHILDREN;
end;
procedure TSuperComboADO.AdjustComboBounds;
begin
if not (csDesigning in ComponentState) then
begin
try
AdjustBounds := False;
if FShowEditCode then
begin
if OriginalWidth = 0 then
OriginalWidth := Width;
if OriginalLeft = 0 then
OriginalLeft := Left;
EditCode.Parent := Parent;
EditCode.Font := Self.Font;
EditCode.Top := Top;
EditCode.Height := Height;
EditCode.Width := FCodeLength;
if FEditCodePos = taEditCodeLeft then
begin
EditCode.Left := OriginalLeft;
Left := OriginalLeft + EditCode.Width + 2;
end
else
begin
EditCode.Left := OriginalLeft + OriginalWidth - EditCode.Width;
end;
try
lExitSize := True;
Width := OriginalWidth - (EditCode.Width + 3);
finally
lExitSize := False;
end;
end;
if Assigned(LookUpADOQuery) then
LookUpForm.Width := LookUpADOQuery.FieldByName(LookUpADOQuery.ListField).DisplayWidth * 6
else
LookUpForm.Width := Width + 20;
// Define tamanho do LookUpForm
if ShowEditCode then
LookUpForm.Width := LookUpForm.Width + EditCode.Width + 2;
if FShowbtnAddNew or FShowbtnUpdate then
LookUpForm.Height := FDropDownRows*GridHeight+30
else
LookUpForm.Height := FDropDownRows*GridHeight+3;
finally
AdjustBounds := True;
end;
end;
end;
procedure TSuperComboADO.WMSize( var Message: TWMSize );
var
rectDraw: TRect;
begin
if not (csDesigning in ComponentState) then
begin
if lExitSize then
Exit;
AllowSelectItem := True;
// Define datasources do Browse e query
SetLookUpQuery;
// Define os tamanhos e a posicao dos controles, que nao mudam conforme o
// form da o resize
// TEsta se deve mostrar o EditCode
EditCode.Visible := FShowEditCode;
if FShowEditCode then
begin
// Testa o Text
if not DataAWare then
begin
Text := '';
end;
end;
AdjustComboBounds;
// Define coordenadas do grid e datasource
LookUpGrid.Left := 3;
LookUpGrid.Width := LookUpForm.Width - 6;
LookUpGrid.Height := FDropDownRows*GridHeight;
// Define a fonte do grid
LookUpGrid.Font := Font;
// Define coordenadas do botao de Add e Update
if FShowbtnAddNew and FShowbtnUpdate then
begin
btnAddNew.Left := 5;
btnAddNew.Width := Trunc((LookUpForm.Width-15)/2);
btnUpdate.Left := 10+btnAddNew.Width;
btnUpdate.Width := btnAddNew.Width;
end
else if FShowbtnAddNew then
begin
btnAddNew.Left := 5;
btnAddNew.Width := LookUpForm.Width-10;
end
else if FShowbtnUpdate then
begin
btnUpdate.Left := 5;
btnUpdate.Width := LookUpForm.Width-10;
end;
// Seta o visible dos controls
btnAddNew.Visible := FShowbtnAddNew;
btnUpdate.Visible := FShowbtnUpdate;
end;
// Posicionamento do botao
FButton.Top := 1;
FButton.Height := Height - 6;
FButton.Width := Height - 4;
FButton.Left := Width - Height;
FButton.Visible := FShowBtnSelecao;
// Desenho do bitmap
SetRect(rectDraw, 0, 0, ClientWidth-1, ClientHeight-1);
bmMemory.Width := rectDraw.Right - rectDraw.Left + 1;
bmMemory.Height := rectDraw.Bottom - rectDraw.Top + 4;
DrawDropDownArrow(bmMemory.Canvas, rectDraw, bsDown, Enabled, ControlState);
FButton.Glyph := bmMemory;
end;
Procedure TSuperComboADO.DrawDropDownArrow(Canvas: TCanvas; R: TRect;
State: TButtonState;
Enabled: Boolean;
ControlState: TControlState);
var Flags: Integer;
begin
if not Enabled then
Flags := DFCS_SCROLLCOMBOBOX or DFCS_INACTIVE
else if (State=bsUp) or (csPaintCopy in ControlState) then
Flags := DFCS_SCROLLCOMBOBOX
else
Flags := DFCS_SCROLLCOMBOBOX or DFCS_FLAT or DFCS_PUSHED;
DrawFrameControl(Canvas.Handle, R, DFC_SCROLL, Flags);
end;
procedure TSuperComboADO.SetShowBtnSelecao(Value : Boolean);
begin
FShowBtnSelecao := Value;
FButton.Visible := Value;
FButton.Refresh;
end;
procedure TSuperComboADO.SetLookUpQuery;
var
i, OtherIndex : integer;
StrCol : String;
begin
if IsLookUpQuerySet then
Exit
else
IsLookUpQuerySet := True;
// Nao roda se estiver em design state
if (csDesigning in ComponentState) then
Exit;
if not Assigned(FLookUpSource) then
raise exception.create('SuperCombo ' + Name + sSelecLookUp);
if not Assigned(LookUpADOQuery) or ForcaTrocaLookUp then
begin
// Seta o query do grid
LookUpGrid.DataSource := FLookUpSource;
if not (FLookUpSource.DataSet is TLookUpADOQuery) then
begin
IsLookUpQuerySet := False;
Exit;
end;
LookUpADOQuery := TLookUpADOQuery(FLookUpSource.DataSet);
// Coluna do LookUpField nao aparece no grid
// Coloca na seguinte ordem :
// CodeField | ListField se ShowEditCode é True
// Criacao dinamica das colunas que aparecem
with LookUpGrid do
begin
Columns.Clear;
with Columns.Add do
begin
if ShowEditCode then
begin
if FEditCodePos = taEditCodeLeft then
begin
FieldName := LookUpADOQuery.CodeField;
Width := CodeLength-3;
with LookUpGrid.Columns.Add do
begin
FieldName := LookUpADOQuery.ListField;
if OriginalWidth = 0 then
Width := Self.Width-CodeLength-3
else
Width := OriginalWidth-CodeLength-3;
end;
end
else
begin
FieldName := LookUpADOQuery.ListField;
if OriginalWidth = 0 then
Width := Self.Width - CodeLength - 3
else
Width := OriginalWidth - CodeLength - 3;
with LookUpGrid.Columns.Add do
begin
FieldName := LookUpADOQuery.CodeField;
Width := CodeLength-3;
end;
end;
end
else
begin
FieldName := LookUpADOQuery.ListField;
Width := Width;
end;
end;
end;
end;
end;
procedure TSuperComboADO.LookUpFormShow(Sender : TObject);
var
rectDraw: TRect;
FormPoint, P : TPoint;
SizeListField, DifWidth : integer;
begin
// Define coordenadas do LookUpForm
rectDraw := ClientRect;
FormPoint.X := rectDraw.Left;
FormPoint.Y := rectDraw.Top;
LookUpForm.Left := ClientToScreen(FormPoint).X - 3;
// se editcode esta a esquerda o combo deve ter left iniciando no EditCode
if ShowEditCode and (FEditCodePos = taEditCodeLeft) then
begin
LookUpForm.Left := LookUpForm.Left - EditCode.Width - 2;
end;
{
// Seta o tamanho do LookUpForm
try
SizeListField := LookUpADOQuery.FieldByName(LookUpADOQuery.ListField).Size;
DifWidth := SizeListField*(Font.Size) - Width;
if DifWidth > 30 then
DifWidth := 30;
LookUpForm.Width := LookUpForm.Width + DifWidth;
except
raise exception.create('ListField nao foi encontrado');
end;
}
// Testa se esta fora da tela
if (ClientToScreen(FormPoint).Y + Height + LookUpForm.Height) < Screen.Height then
begin
LookUpForm.Top := ClientToScreen(FormPoint).Y + Height;
LookUpGrid.Top := 0;
btnAddNew.Top := LookUpForm.Height - 25;
btnUpdate.Top := btnAddNew.Top;
end
else
begin
btnAddNew.Top := 25 - btnAddNew.Height;
btnUpdate.Top := btnAddNew.Top;
LookUpGrid.Top := LookUpForm.Height - LookUpGrid.Height;
LookUpForm.Top := ClientToScreen(FormPoint).Y - LookUpForm.Height;
end;
// Nao sei porque, mas com o codigo abaixo o LookUpform fica sempre StayOnTop
P := LookUpForm.ClientOrigin;
SetWindowPos (LookUpForm.Handle, HWND_TOPMOST, P.X, P.Y, LookUpForm.Width,
LookUpForm.Height, SWP_NOACTIVATE)
end;
procedure TSuperComboADO.WMKillFocus(var Message: TMessage);
begin
inherited;
if not (csDesigning in ComponentState) then
EditCode.Parent := Parent;
// Fecha o lookupform quando clica fora da aplicacao
if Message.WParam = 0 then
LookUpForm.Close;
end;
procedure TSuperComboADO.OwnerDeactivate(Sender: TObject);
begin
// Da close no LookUpform se clicar fora do form owner
if not LookUpForm.Active then
LookUpForm.Close;
end;
procedure TSuperComboADO.CNKeyDown(var Message: TWMKeyDown);
begin
if not (csDesigning in ComponentState) then
begin
{TESTE}
{if LookUpGrid.CanFocus then
begin
LookUpGrid.SetFocus;
if not (LookUpGrid.Focused or (LookUpGrid.InplaceEditor <> nil) and LookUpGrid.InplaceEditor.Focused) then
begin
Exit;
Showmessage('foi');
end;
end;}
{/TESTE}
with Message do
begin
case charcode of
VK_DOWN : GetNextValue;
VK_END : GetLastValue;
VK_HOME : GetFirstValue;
VK_UP : GetPriorValue;
end;
if (LookUpForm.Visible) then
begin
//LookUpGrid.Refresh;
// Ambos os casos nao continua a capturar a tecla
case charcode of
VK_ESCAPE : begin
LookUpForm.Close;
LookUpValue := '';
Exit;
end;
VK_RETURN : begin
SetExit(True);
Exit;
end;
34 : GetNextPage; // Page Down
33 : GetPriorPage; // Page Up
end;
end
else
begin // Grid Fechado, forca a busca do valor
case charcode of
VK_DOWN,
VK_UP,
VK_END,
VK_HOME : LookUpGridDblClick(nil);
VK_RETURN : SetExit;
end;
end;
end;
FillFieldValues(FComboFields);
end;
inherited;
end;
procedure TSuperComboADO.GetFirstValue;
begin
if LookUpADOQuery.LocateFirst('', FIsListFiltered, False,
FFilterFields, FFilterValues,
FFilterSugest, FSpcWhereClause, True, FMostraDesativado, FMostraHidden) then
UpdateValues;
end;
procedure TSuperComboADO.GetLastValue;
begin
if LookUpADOQuery.LocateLast(FIsListFiltered,
FFilterFields, FFilterValues,
FFilterSugest, FSpcWhereClause, FMostraDesativado, FMostraHidden) then
UpdateValues;
end;
procedure TSuperComboADO.GetNextValue;
begin
if LookUpADOQuery.LocateNext(Text, FIsListFiltered, 1,
FFilterFields, FFilterValues,
FFilterSugest, FSpcWhereClause, FMostraDesativado, FMostraHidden) then
UpdateValues;
end;
procedure TSuperComboADO.GetNextPage;
begin
if LookUpADOQuery.LocateNext(Text, FIsListFiltered, LookUpGrid.VisibleRowCount,
FFilterFields, FFilterValues,
FFilterSugest, FSpcWhereClause, FMostraDesativado, FMostraHidden) then
UpdateValues;
end;
procedure TSuperComboADO.GetPriorValue;
begin
if LookUpADOQuery.LocatePrior(Text, FIsListFiltered, 1,
FFilterFields, FFilterValues,
FFilterSugest, FSpcWhereClause, FMostraDesativado, FMostraHidden) then
UpdateValues;
end;
procedure TSuperComboADO.GetPriorPage;
begin
if LookUpADOQuery.LocatePrior(Text, FIsListFiltered, LookUpGrid.VisibleRowCount,
FFilterFields, FFilterValues,
FFilterSugest, FSpcWhereClause, FMostraDesativado, FMostraHidden) then
UpdateValues;
end;
procedure TSuperComboADO.CMCancelMode(var Message: TCMCancelMode);
begin
inherited;
if (Message.Sender = Owner) or ((Message.Sender <> Self) and
(Message.Sender <> LookUpForm)) then
LookUpForm.Close;
end;
procedure TSuperComboADO.SetVisible(Value: Boolean);
begin
FVisible := Value;
inherited Visible := FVisible;
if not (csDesigning in ComponentState) then
EditCode.Visible := FShowEditCode and FVisible;
end;
procedure TSuperComboADO.SetEnabled(Value: Boolean);
begin
FEnab := Value;
inherited Enabled := FEnab;
FButton.Enabled := FEnab;
end;
procedure TSuperComboADO.SetReadOnly(Value: Boolean);
begin
FReadOnly := Value;
inherited ReadOnly := FReadOnly;
FButton.Enabled := not FReadOnly;
end;
procedure TSuperComboADO.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
// Forca para saber se houve aperto de tecla ou e babaquice do
// Delphi
// Se for RETURN or ESC nao chama o change
IsKeyPressed := ((Key <> 13) and (Key <> 27));
NoExtraKey := False;
if Shift = [ssAlt] then
begin
if UpperCase(Chr(Key)) = 'N' then
AddUpdateClick(btnAddNew)
else if UpperCase(Chr(Key)) = 'U' then
AddUpdateClick(btnUpdate);
end
else
begin
if Key = VK_F2 then
OpenGrid
else if (Key = 8) or (Key = VK_DELETE) then // BACKSPACE e DELETE
IsLocate := False;
end;
end;
procedure TSuperComboADO.KeyPress(var Key: Char);
begin
inherited;
end;
procedure TSuperComboADO.Change;
begin
inherited Change;
if not (csDesigning in ComponentState) then
begin
EditCode.Parent := Parent;
// Se campo estiver vazio forca o requery
if Text = '' then
IsFoundKey := True;
if IsChange and IsKeyPressed then
begin
OpenGrid;
IsKeyPressed := False;
end;
end;
end;
procedure TSuperComboADO.OpenGrid;
var
lExit : Boolean;
TextLen, LastTextLen : Integer;
begin
if Assigned(OnBeforeOpenGrid) then
FOnBeforeOpenGrid(Self);
with TLookUpADOQuery(FLookUpSource.DataSet) do
if Assigned(OnBeforeOpenGrid) then
FOnBeforeOpenGrid(Self);
if Assigned(LookUpADOQuery) and TForm(Owner).Active then
begin
// Se nao achou e o tamanho do text atual e maior nao faz nada
// Testes para saber se procura
lExit := False;
if (not IsFoundKey) then
begin
TextLen := Length(Trim(Text));
LastTextLen := Length(Trim(LastText));
if (TextLen > LastTextLen) and (LastTextLen > 0) then
lExit := True
else if TextLen = LastTextLen then
lExit := (TextLen >= LastTextLen)
else
lExit := False;
end;
LastText := Text;
if lExit then
Exit;
AllowSelectItem := True; // habilita o selectitem
{TESTE
if Text <> '' then
begin
LookUpADOQuery.Active := True;
IsLocate := True;
end;
{/TESTE}
IsFoundKey := LookUpADOQuery.LocateFirst(Text, FIsListFiltered, IsLocate,
FFilterFields, FFilterValues,
FFilterSugest, FSpcWhereClause, True, FMostraDesativado, FMostraHidden);
if IsFoundKey then
begin
// Seta o LookUpValue constantemente
FLookUpValue := LookUpADOQuery.LookUpValue;
ListValue := LookUpADOQuery.ListValue;
CodeValue := LookUpADOQuery.CodeValue;
LookUpGrid.Options := LookUpGrid.Options + [dgAlwaysShowSelection];
end
else
begin
LookUpGrid.Options := LookUpGrid.Options - [dgAlwaysShowSelection];
FLookUpValue := '';
ListValue := '';
CodeValue := '';
end;
IsLocate := True; // Reseta o locate;
if not LookUpForm.Visible and FEnab then
LookUpForm.Show;
// TForm(Owner).SetFocus;
// TWinControl(Parent).SetFocus;
SetFocus;
end;
{TESTE}
//LookUpGrid.Refresh;
{/TESTE}
end;
procedure TSuperComboADO.LookUpGridClick(Sender : TObject);
begin
LookUpGrid.Options := LookUpGrid.Options + [dgAlwaysShowSelection];
SetFocus;
if not (FShowBtnAddNew or FShowBtnUpdate) then
LookUpGridDblClick(Sender);
end;
procedure TSuperComboADO.LookUpGridDblClick(Sender : TObject);
begin
// Seta o valor corrente
UpdateValues;
LookUpForm.Close;
SelectActualValue;
end;
procedure TSuperComboADO.SelectActualValue;
begin
if FLookUpValue <> '' then
begin
AllowSelectItem := False;
FillFieldValues(FComboFields);
// Altera o field associado ao combo
if DataAware then
TDBSuperComboADO(Self).UpdateData(Self);
if Assigned(OnBeforeSelectItem) then
FOnBeforeSelectItem(Self);
if Assigned(OnSelectItem) then
FOnSelectItem(Self);
end;
end;
procedure TSuperComboADO.UpdateValues;
var
Key : Char;
begin
// Associa o LookUpValue, sem procurar pelo codigo
// ja que o usuario clickou no item
// Forca o delphi a saber que houve o edit state no DBSuperCombo
Key := #32;
KeyPress(Key);
IsKeyPressed := False;
// Muda o Text e o LookUpValue
LookUpADOQuery.UpdateValues;
ListValue := LookUpADOQuery.ListValue;
FLookUpValue := LookUpADOQuery.LookUpValue;
CodeValue := LookUpADOQuery.CodeValue;
AllowSelectItem := True;
try
IsChange := False;
Change; // Seta o modified do Tipo DB.
Text := ListValue;
EditCode.Text := Codevalue;
LastText := Text;
finally
IsChange := True;
end;
if not LookUpGrid.Visible then
begin
SetFocus;
SelectAll;
end;
end;
procedure TSuperComboADO.CMExit(var Message: TCMExit);
begin
SetExit(LookUpForm.Showing);
if not DataAware then
DoExit;
AllowSelectItem := True;
end;
procedure TSuperComboADO.SetExit(AShowing: Boolean = false);
var
OldText : String;
begin
if Assigned(LookUpADOQuery) then
begin
LookUpForm.Close;
OldText := Trim(Text);
FillFieldValues(FComboFields);
// Verifica se houve mudanca no text se e para refazer a query
if Trim(Text) = '' then
begin
LookUpValue := '';
end
else
begin
// testa se valor digitado e
try
IsLookUpValue := False;
LookUpValue := Text; // Testa se existe descricao que faca o 'match' do codigo
finally
IsLookUpValue := True;
end;
end;
// Sempre fecha o query na saida
with LookUpADOQuery do
if Active then Close;
if (FLookUpValue = '') and Assigned(OnNotInList) then
FOnNotInList(Self, OldText)
else if FLookUpValue <> '' then
begin
if AllowSelectItem then
begin
// Altera o field associado ao combo
if DataAware then
TDBSuperComboADO(Self).UpdateData(Self);
AllowSelectItem := False;
{By Carlos}
if AShowing then
begin
if Assigned(OnBeforeSelectItem) then
FOnBeforeSelectItem(Self);
if Assigned(OnSelectItem) then
FOnSelectItem(Self);
end;
end;
end;
end;
end;
function TSuperComboADO.GetLookUpFieldValue : Variant;
begin
// Retorna o valor no tipo certo do combo
// se nao houver nenhum valor retorna ''
with LookUpADOQuery do
begin
case FieldByName(LookupField).DataType of
ftString,
ftMemo : Result := LookUpValue;
ftDateTime,
ftDate : Result := StrToDateTime(LookUpValue);
ftInteger : Result := MyStrToInt(LookUpValue);
ftFloat : Result := MyStrToFloat(LookUpValue);
ftBoolean : Result := ( Pos(LookUpValue, 'TRUE,1') > 0 );
end;
end;
end;
procedure TSuperComboADO.FillFieldValues(Var AComboFields: TComboFields);
var
I : Integer;
begin
if (FLookUpSource <> Nil) and (FLookUpSource.DataSet <> Nil) then
begin
SetLength(AComboFields, 0);
for I := 0 to FLookUpSource.DataSet.FieldCount - 1 do
begin
SetLength(AComboFields, Length(AComboFields) + 1);
AComboFields[Length(AComboFields) - 1].FieldName := FLookUpSource.DataSet.Fields[I].FieldName;
AComboFields[Length(AComboFields) - 1].FieldValue := Null;
if not FLookUpSource.DataSet.IsEmpty then
AComboFields[Length(AComboFields) - 1].FieldValue := FLookUpSource.DataSet.Fields[I].Value;
end;
end;
end;
function TSuperComboADO.GetFieldByName(AFieldName: string) : Variant;
var
I : Integer;
begin
Result := Null;
for I := 0 to Length(FComboFields) - 1 do
if FComboFields[I].FieldName = AFieldName then
begin
Result := FComboFields[I].FieldValue;
Break;
end;
end;
procedure TSuperComboADO.SetLookUpValue(Value: String);
begin
// Define datasources do Browse e query
SetLookUpQuery;
if Value = '' then
begin
ListValue := '';
FLookUpValue := '';
OldValue := '';
CodeValue := '';
OldText := Text;
FillFieldValues(FComboFields);
end
else
if (Value <> OldValue) or (FLookUpValue = '') then
begin
OldValue := Value;
if LookUpADOQuery.DescLookUpField(Value, IsLookUpValue,
FFilterFields, FFilterValues,
FFilterSugest, FSpcWhereClause, FMostraDesativado, FMostraHidden) then
begin
ListValue := LookUpADOQuery.ListValue;
FLookUpValue := LookUpADOQuery.LookUpValue;
CodeValue := LookUpADOQuery.CodeValue;
end;
FillFieldValues(FComboFields);
LookUpADOQuery.Close;
end;
// Associa ao text o valor do campo
try
IsChange := False; // Desabilita o evento change
Text := ListValue;
EditCode.Text := CodeValue;
LastText := Text;
finally
IsChange := True; // habilita evento change
end;
SelectAll;
end;
procedure TSuperComboADO.AddUpdateClick(Sender : TObject);
begin
if not Assigned(LookUpADOQuery.OnClickButton) then
raise exception.create(sDefineEvent);
// Fecha o form LookUp
LookUpForm.Close;
LookUpADOQuery.FilterFields := FFilterFields;
LookUpADOQuery.FilterValues := FFilterValues;
if LookUpADOQuery.CallLookUpForm((TButton(Sender).Tag = 0)) and
Assigned(OnAfterAddUpdate) then
OnAfterAddUpdate(Self);
// Seta o valor corrente
UpdateValues;
SelectActualValue;
LookUpADOQuery.Close;
end;
procedure TSuperComboADO.CallUpdate;
begin
if FLookUpValue <> '' then
begin
LookUpADOQuery.LocateFirst(Text, FIsListFiltered, IsLocate,
FFilterFields, FFilterValues, FFilterSugest,
FSpcWhereClause, True, FMostraDesativado, FMostraHidden);
AddUpdateClick(btnUpdate);
end;
end;
{---- TDbSuperCombo----}
constructor TDbSuperComboADO.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
inherited ReadOnly := False;
ControlStyle := ControlStyle + [csReplicatable];
FDataLink := TFieldDataLink.Create;
FDataLink.Control := Self;
FDataLink.OnDataChange := DataChange;
FDataLink.OnEditingChange := EditingChange;
FDataLink.OnUpdateData := UpdateData;
DataAware := True;
end;
destructor TDbSuperComboADO.Destroy;
begin
FDataLink.Free;
FDataLink := nil;
FCanvas.Free;
inherited Destroy;
end;
procedure TDbSuperComboADO.Loaded;
begin
inherited Loaded;
if (csDesigning in ComponentState) then DataChange(Self);
end;
procedure TDbSuperComboADO.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (FDataLink <> nil) and
(AComponent = DataSource) then DataSource := nil;
end;
procedure TDbSuperComboADO.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
if (Key = VK_DELETE) or ((Key = VK_INSERT) and (ssShift in Shift)) then
FDataLink.Edit;
end;
procedure TDbSuperComboADO.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
// Retirado, pois o campo pode ser string ou Numero
{ if (Key in [#32..#255]) and (FDataLink.Field <> nil) then
and not FDataLink.Field.IsValidChar(Key) then
begin
MessageBeep(0);
Key := #0;
end;
}
case Key of
^H, ^V, ^X, #32..#255:
FDataLink.Edit;
#27:
begin
FDataLink.Reset;
SelectAll;
Key := #0;
end;
end;
end;
function TDbSuperComboADO.EditCanModify: Boolean;
begin
Result := FDataLink.Edit;
end;
procedure TDbSuperComboADO.Reset;
begin
FDataLink.Reset;
SelectAll;
end;
procedure TDbSuperComboADO.SetFocused(Value: Boolean);
begin
if FFocused <> Value then
begin
FFocused := Value;
if (FAlignment <> taLeftJustify) and not IsMasked then Invalidate;
FDataLink.Reset;
end;
end;
procedure TDbSuperComboADO.Change;
begin
inherited Change;
FDataLink.Modified;
end;
function TDbSuperComboADO.GetDataSource: TDataSource;
begin
Result := FDataLink.DataSource;
end;
procedure TDbSuperComboADO.SetDataSource(Value: TDataSource);
begin
FDataLink.DataSource := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
function TDbSuperComboADO.GetDataField: string;
begin
Result := FDataLink.FieldName;
end;
procedure TDbSuperComboADO.SetDataField(const Value: string);
begin
FDataLink.FieldName := Value;
end;
function TDbSuperComboADO.GetReadOnly: Boolean;
begin
Result := FDataLink.ReadOnly;
end;
procedure TDbSuperComboADO.SetReadOnly(Value: Boolean);
begin
inherited ReadOnly := Value;
FDataLink.ReadOnly := Value;
end;
function TDbSuperComboADO.GetField: TField;
begin
Result := FDataLink.Field;
end;
procedure TDbSuperComboADO.DataChange(Sender: TObject);
begin
if FDataLink.Field <> nil then
begin
EditMask := FDataLink.Field.EditMask;
if FDataLink.Field.DataType = ftString then
MaxLength := FDataLink.Field.Size else
MaxLength := 0;
LookUpValue := FDataLink.Field.AsString;
end else
begin
FAlignment := taLeftJustify;
EditMask := '';
MaxLength := 0;
if csDesigning in ComponentState then
Text := Name else
Text := '';
end;
end;
procedure TDbSuperComboADO.EditingChange(Sender: TObject);
begin
// inherited ReadOnly := not FDataLink.Editing;
end;
procedure TDbSuperComboADO.UpdateData(Sender: TObject);
begin
// Associa o valor ao field
FillFieldValues(FComboFields);
FDataLink.Edit; // Forca o edit state;
FDataLink.Field.AsString := LookUpValue;
end;
procedure TDbSuperComboADO.WMPaste(var Message: TMessage);
begin
FDataLink.Edit;
inherited;
end;
procedure TDbSuperComboADO.WMCut(var Message: TMessage);
begin
FDataLink.Edit;
inherited;
end;
procedure TDbSuperComboADO.CMEnter(var Message: TCMEnter);
begin
SetFocused(True);
inherited;
end;
procedure TDbSuperComboADO.CMExit(var Message: TCMExit);
begin
inherited CMExit(Message);;
try
FDataLink.UpdateRecord;
except
SelectAll;
SetFocus;
raise;
end;
SetFocused(False);
CheckCursor;
DoExit;
end;
procedure TDbSuperComboADO.WMPaint(var Message: TWMPaint);
var
Left: Integer;
Margins: TPoint;
R: TRect;
DC: HDC;
PS: TPaintStruct;
S: string;
begin
if ((FAlignment = taLeftJustify) or FFocused) and
not (csPaintCopy in ControlState) then
begin
inherited;
Exit;
end;
{ Since edit controls do not handle justification unless multi-line (and
then only poorly) we will draw right and center justify manually unless
the edit has the focus. }
if FCanvas = nil then
begin
FCanvas := TControlCanvas.Create;
FCanvas.Control := Self;
end;
DC := Message.DC;
if DC = 0 then DC := BeginPaint(Handle, PS);
FCanvas.Handle := DC;
try
FCanvas.Font := Font;
with FCanvas do
begin
R := ClientRect;
if not (NewStyleControls and Ctl3D) and (BorderStyle = bsSingle) then
begin
Brush.Color := clWindowFrame;
FrameRect(R);
InflateRect(R, -1, -1);
end;
Brush.Color := Color;
if (csPaintCopy in ControlState) and (FDataLink.Field <> nil) then
begin
S := FDataLink.Field.DisplayText;
case CharCase of
ecUpperCase: S := AnsiUpperCase(S);
ecLowerCase: S := AnsiLowerCase(S);
end;
end else
S := EditText;
if PasswordChar <> #0 then FillChar(S[1], Length(S), PasswordChar);
Margins := GetTextMargins;
case FAlignment of
taLeftJustify: Left := Margins.X;
taRightJustify: Left := ClientWidth - TextWidth(S) - Margins.X - 1;
else
Left := (ClientWidth - TextWidth(S)) div 2;
end;
TextRect(R, Left, Margins.Y, S);
end;
finally
FCanvas.Handle := 0;
if Message.DC = 0 then EndPaint(Handle, PS);
end;
end;
procedure TDbSuperComboADO.CMGetDataLink(var Message: TMessage);
begin
Message.Result := Integer(FDataLink);
end;
function TDbSuperComboADO.GetTextMargins: TPoint;
var
DC: HDC;
SaveFont: HFont;
I: Integer;
SysMetrics, Metrics: TTextMetric;
begin
if NewStyleControls then
begin
if BorderStyle = bsNone then I := 0 else
if Ctl3D then I := 1 else I := 2;
Result.X := SendMessage(Handle, EM_GETMARGINS, 0, 0) and $0000FFFF + I;
Result.Y := I;
end else
begin
if BorderStyle = bsNone then I := 0 else
begin
DC := GetDC(0);
GetTextMetrics(DC, SysMetrics);
SaveFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, SaveFont);
ReleaseDC(0, DC);
I := SysMetrics.tmHeight;
if I > Metrics.tmHeight then I := Metrics.tmHeight;
I := I div 4;
end;
Result.X := I;
Result.Y := I;
end;
end;
procedure Register;
begin
RegisterComponents('NewPower', [TSuperComboADO]);
RegisterComponents('NewPower', [TDBSuperComboADO]);
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmLabel
Purpose : This label has extra functionality for UI eye-candy.
Date : 07-09-1998
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmLabel;
interface
{$I CompilerDefines.INC}
uses Messages, Windows, SysUtils, Classes, Controls, forms, Graphics, extctrls, dialogs;
type
TrmBorderStyle = (rmbsNone, rmbsSingle, rmbsSunken, rmbsRaised, rmbsSunkenEdge, rmbsRaisedEdge);
TrmTextStyle = (rmtsNormal, rmtsRaised, rmtsLowered, rmtsShadow);
TrmTextLayout = (rmtlTop, rmtlCenter, rmtlBottom);
TrmGradientLayout = (rmglTopDown, rmglLeftRight);
TrmCustomLabel = class;
TrmLMouseOptions = class(TPersistent)
private
{ Private declarations }
fenabled: boolean;
FOwner: TrmCustomLabel;
FEnterColor: TColor;
FEnterBorderStyle: TrmBorderStyle;
FEnterTextStyle: TrmTextStyle;
protected
{ Protected declarations }
procedure SetEnterColor(Value: TColor);
procedure SetEnterBorderStyle(Value: TrmBorderStyle);
procedure SetEnterTextStyle(Value: TrmTextStyle);
public
{ Public declarations }
constructor Create(AOwner: TrmCustomLabel); virtual;
published
{ Published declarations }
property EnterColor: TColor read FEnterColor write SetEnterColor default clWindowText;
property EnterBorder: TrmBorderStyle read fEnterBorderStyle write SetEnterBorderStyle default rmbsNone;
property EnterTextStyle: TrmTextStyle read FEnterTextStyle write SetEnterTextStyle default rmtsNormal;
property Enabled: boolean read fEnabled write fenabled default false;
end; { TCompanyText }
TrmCustomLabel = class(TGraphicControl)
private
fOnMouseEnter: TNotifyEvent;
fOnMouseLeave: TNotifyEvent;
fMouseOptions: TrmLMouseOptions;
FFocusControl: TWinControl;
FAlignment: TAlignment;
FAutoSize: Boolean;
fdoublebuffered: boolean;
fbuffer: TBitmap;
fThickBorder: boolean;
FLayout: TrmTextLayout;
FWordWrap: Boolean;
FShowAccelChar: Boolean;
fGradTLColor, fGradBRColor: TColor;
fShadowColor: TColor;
fShadowdepth: integer;
fGradDir: TrmGradientLayout;
fBorderStyle: TrmBorderStyle;
fUseGradient: Boolean;
ftextstyle: TrmTextStyle;
fnormalcolor: tcolor;
fnormaltext: TrmTextStyle;
fnormalborder: TrmBorderstyle;
{$IFNDEF D6_or_higher}
procedure AdjustBounds;
{$ENDIF}
function DrawBorder(canvas: TCanvas): trect;
procedure DoDrawText(canvas: TCanvas; var Rect: TRect; Flags: Word);
function GetTransparent: Boolean;
function GetBorderWidth: integer;
procedure SetAlignment(Value: TAlignment);
procedure SetFocusControl(Value: TWinControl);
procedure SetShowAccelChar(Value: Boolean);
procedure SetTransparent(Value: Boolean);
procedure SetLayout(Value: TrmTextLayout);
procedure SetWordWrap(Value: Boolean);
procedure SetBorderStyle(Value: TrmBorderStyle);
procedure SetThickBorder(Value: Boolean);
procedure SetTextStyle(Value: TrmTextStyle);
procedure SetGradient(Value: Boolean);
procedure SetTLColor(value: TColor);
procedure SetBRColor(value: TColor);
procedure SetGradientDirection(value: TrmGradientLayout);
procedure GradientFill(canvas: TCanvas; R: TRect);
procedure setshadowcolor(value: tcolor);
procedure setshadowdepth(value: integer);
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
procedure CMMouseEnter(var Message: TCMEnter); message CM_MouseEnter;
procedure CMMouseLeave(var Message: TCMExit); message CM_MouseLeave;
protected
procedure Draw3DText(canvas: TCanvas; var Rect: TRect; Flags: Word; Raised: boolean);
function GetLabelText: string; virtual;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Paint; override;
{$IFNDEF D6_or_higher}
procedure SetAutoSize(Value: Boolean); virtual;
property AutoSize: Boolean read FAutoSize write SetAutoSize default True;
{$ENDIF}
property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify;
property DoubleBuffered: Boolean read fdoublebuffered write fdoublebuffered default true;
property FocusControl: TWinControl read FFocusControl write SetFocusControl;
property ShowAccelChar: Boolean read FShowAccelChar write SetShowAccelChar default True;
property Transparent: Boolean read GetTransparent write SetTransparent default False;
property Layout: TrmTextLayout read FLayout write SetLayout default rmtlTop;
property WordWrap: Boolean read FWordWrap write SetWordWrap default False;
property BorderStyle: TrmBorderStyle read fBorderStyle write SetBorderStyle default rmbsNone;
property UseGradient: Boolean read fuseGradient write SetGradient default false;
property TextStyle: TrmTextStyle read ftextstyle write settextstyle default rmtsNormal;
property GradientTLColor: TColor read fGradTLColor write SetTLColor default clbtnshadow;
property GradientBRColor: TColor read fGradBRColor write SetBRColor default clbtnface;
property GradientDirection: TrmGradientLayout read fGradDir write SetGradientDirection default rmglLeftRight;
property MouseOptions: TrmLMouseOptions read fmouseoptions write fmouseoptions stored true;
property ThickBorder: Boolean read fthickborder write setthickborder default false;
property Borderwidth: integer read GetBorderWidth;
property ShadowColor: tcolor read fshadowcolor write setShadowColor default clbtnshadow;
property ShadowDepth: integer read fshadowdepth write setshadowdepth default 4;
property OnMouseEnter: TNotifyEvent read fOnMouseEnter write fOnMouseEnter;
property OnMouseLeave: TNotifyEvent read fOnMouseLeave write fOnMouseLeave;
public
constructor Create(AOwner: TComponent); override;
destructor destroy; override;
property Canvas;
end;
TrmLabel = class(TrmCustomLabel)
public
property Borderwidth;
published
property Align;
property Alignment;
property AutoSize;
property DoubleBuffered;
property Caption;
property Color;
property DragCursor;
property DragMode;
property Enabled;
property FocusControl;
property Font;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowAccelChar;
property ShowHint;
property Transparent;
property Layout;
property Visible;
property WordWrap;
property BorderStyle;
property UseGradient;
property TextStyle;
property ThickBorder;
property GradientTLColor;
property GradientBRColor;
property GradientDirection;
property shadowcolor;
property shadowdepth;
property MouseOptions;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
property OnMouseEnter;
property OnMouseLeave;
end;
implementation
uses rmLibrary;
{ TrmLMouseOptions }
constructor TrmLMouseOptions.Create(AOwner: TrmCustomLabel);
begin
inherited create;
FOwner := aowner;
fenabled := false;
fEnterColor := clWindowText;
fEnterBorderStyle := rmbsNone;
fEnterTextStyle := rmtsNormal;
end;
procedure TrmLMouseOptions.SetEnterColor(Value: TColor);
begin
fEnterColor := value;
fowner.Invalidate;
end;
procedure TrmLMouseOptions.SetEnterBorderStyle(Value: TrmBorderStyle);
begin
fEnterBorderStyle := value;
fowner.Invalidate;
end;
procedure TrmLMouseOptions.SetEnterTextStyle(Value: TrmTextStyle);
begin
fEnterTextStyle := value;
fowner.Invalidate;
end;
{ TrmCustomLabel }
constructor TrmCustomLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csOpaque, csReplicatable];
fMouseOptions := TrmLMouseOptions.create(self);
fdoublebuffered := true;
fbuffer := tbitmap.create;
Width := 65;
Height := 17;
fshadowdepth := 4;
fshadowcolor := clbtnshadow;
FAutoSize := True;
FShowAccelChar := True;
fGradTLColor := clbtnshadow;
fGradBRColor := clbtnface;
fGradDir := rmglLeftRight;
fBorderStyle := rmbsNone;
fUseGradient := false;
ftextstyle := rmtsNormal;
end;
destructor TrmCustomLabel.destroy;
begin
fmouseoptions.free;
fbuffer.free;
inherited;
end;
function TrmCustomLabel.GetLabelText: string;
begin
Result := Caption;
end;
procedure TrmCustomLabel.Draw3DText(canvas: TCanvas; var Rect: TRect; Flags: Word; Raised: boolean);
var
top, bottom: tcolor;
begin
if raised then
begin
top := clBtnShadow;
bottom := clBtnHighlight;
end
else
begin
top := clBtnHighlight;
bottom := clBtnShadow;
end;
OffsetRect(Rect, 1, 1);
Canvas.Font.Color := top;
DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags);
OffsetRect(Rect, -2, -2);
Canvas.Font.Color := bottom;
DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags);
OffsetRect(Rect, 1, 1);
Canvas.Font.color := font.color;
DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags);
inflaterect(rect, 1, 1);
rect.right := rect.right + 1;
rect.bottom := rect.bottom + 1;
end;
procedure TrmCustomLabel.DoDrawText(canvas: TCanvas; var Rect: TRect; Flags: Word);
var
Text: string;
begin
Text := GetLabelText;
if (Flags and DT_CALCRECT <> 0) and ((Text = '') or FShowAccelChar and
(Text[1] = '&') and (Text[2] = #0)) then Text := Text + ' ';
if not FShowAccelChar then Flags := Flags or DT_NOPREFIX;
Canvas.Font := Font;
if not Enabled then
begin
OffsetRect(Rect, 1, 1);
Canvas.Font.Color := clBtnHighlight;
DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags);
OffsetRect(Rect, -1, -1);
Canvas.Font.Color := clBtnShadow;
DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags);
end
else
case TextStyle of
rmtsNormal: DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags);
rmtsRaised: Draw3DText(canvas, rect, flags, true);
rmtsLowered: Draw3DText(canvas, rect, flags, false);
rmtsShadow:
begin
OffsetRect(Rect, fshadowdepth, fshadowdepth);
Canvas.Font.Color := fshadowcolor;
DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags);
OffsetRect(Rect, -fshadowdepth, -fshadowdepth);
Canvas.Font.Color := font.color;
DrawText(Canvas.Handle, PChar(Text), Length(Text), Rect, Flags);
inflaterect(rect, fshadowdepth, fshadowdepth);
end;
end;
end;
procedure TrmCustomLabel.Paint;
const
Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER);
WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK);
var
WR, CalcRect: TRect;
DrawStyle: Integer;
bmp: TBitmap;
Workcanvas: TCanvas;
begin
bmp := nil;
if fdoublebuffered then
begin
bmp := tbitmap.create;
bmp.width := width;
bmp.height := height;
workcanvas := bmp.canvas
end
else
workcanvas := canvas;
with WorkCanvas do
begin
WR := DrawBorder(WorkCanvas);
if not Transparent then
begin
if UseGradient then GradientFill(WorkCanvas, wr)
else
begin
Brush.Color := Self.Color;
Brush.Style := bsSolid;
FillRect(WR);
end;
end
else
begin
if fdoublebuffered then
begin
if font.color = clblack then
bmp.transparentcolor := clred
else
font.color := clblue;
bmp.transparent := true;
Brush.color := bmp.transparentcolor;
Brush.Style := bsSolid;
fillRect(WR);
end;
end;
Brush.Style := bsClear;
DrawStyle := DT_EXPANDTABS or WordWraps[FWordWrap] or Alignments[FAlignment];
{ Calculate vertical layout }
if FLayout <> rmtlTop then
begin
CalcRect := WR;
DoDrawText(WorkCanvas, CalcRect, DrawStyle or DT_CALCRECT);
if FLayout = rmtlBottom then OffsetRect(WR, 0, Height - CalcRect.Bottom)
else OffsetRect(WR, 0, (Height - CalcRect.Bottom) div 2);
end;
DoDrawText(WorkCanvas, WR, DrawStyle);
end;
if (fdoublebuffered) and assigned(bmp) then
begin
canvas.Draw(0, 0, bmp);
bmp.free;
end;
end;
procedure TrmCustomLabel.Loaded;
begin
inherited Loaded;
{$ifndef D6_or_higher}
AdjustBounds;
{$endif}
end;
{$IFNDEF D6_or_higher}
procedure TrmCustomLabel.AdjustBounds;
const
WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK);
var
DC: HDC;
X: Integer;
WR: TRect;
begin
if not (csReading in ComponentState) and FAutoSize then
begin
wr := clientrect;
DC := GetDC(0);
Canvas.Handle := DC;
DoDrawText(canvas, wr, (DT_EXPANDTABS or DT_CALCRECT) or WordWraps[FWordWrap]);
Canvas.Handle := 0;
ReleaseDC(0, DC);
X := Left;
if FAlignment = taRightJustify then Inc(X, Width - (wr.Right + BorderWidth));
if (align in [altop, albottom, alclient]) then wr.right := width;
if (align in [alRight, alLeft, alclient]) then wr.bottom := height;
if (height <= wr.Bottom + borderwidth) or (width <= wr.Right + borderwidth) then
SetBounds(X, Top, wr.Right + borderwidth, wr.Bottom + borderwidth);
end;
end;
{$ENDIF}
procedure TrmCustomLabel.SetAlignment(Value: TAlignment);
begin
if FAlignment <> Value then
begin
FAlignment := Value;
Invalidate;
end;
end;
{$IFNDEF D6_or_higher}
procedure TrmCustomLabel.SetAutoSize(Value: Boolean);
begin
if FAutoSize <> Value then
begin
FAutoSize := Value;
AdjustBounds;
end;
end;
{$ENDIF}
function TrmCustomLabel.GetTransparent: Boolean;
begin
Result := not (csOpaque in ControlStyle);
end;
procedure TrmCustomLabel.SetFocusControl(Value: TWinControl);
begin
FFocusControl := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
procedure TrmCustomLabel.SetShowAccelChar(Value: Boolean);
begin
if FShowAccelChar <> Value then
begin
FShowAccelChar := Value;
Invalidate;
end;
end;
procedure TrmCustomLabel.SetTransparent(Value: Boolean);
begin
if Transparent <> Value then
begin
if Value then
ControlStyle := ControlStyle - [csOpaque] else
ControlStyle := ControlStyle + [csOpaque];
Invalidate;
end;
end;
procedure TrmCustomLabel.SetLayout(Value: TrmTextLayout);
begin
if FLayout <> Value then
begin
FLayout := Value;
Invalidate;
end;
end;
procedure TrmCustomLabel.SetWordWrap(Value: Boolean);
begin
if FWordWrap <> Value then
begin
FWordWrap := Value;
{$ifndef D6_or_higher}
AdjustBounds;
{$endif}
Invalidate;
end;
end;
procedure TrmCustomLabel.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FFocusControl) then
FFocusControl := nil;
end;
procedure TrmCustomLabel.CMTextChanged(var Message: TMessage);
begin
Invalidate;
{$ifndef D6_or_higher}
AdjustBounds;
{$endif}
end;
procedure TrmCustomLabel.CMFontChanged(var Message: TMessage);
begin
inherited;
{$ifndef D6_or_higher}
AdjustBounds;
{$endif}
end;
procedure TrmCustomLabel.CMDialogChar(var Message: TCMDialogChar);
begin
if (FFocusControl <> nil) and Enabled and ShowAccelChar and
IsAccel(Message.CharCode, Caption) then
with FFocusControl do
if CanFocus then
begin
SetFocus;
Message.Result := 1;
end;
end;
procedure TrmCustomLabel.SetBorderStyle(Value: TrmBorderStyle);
begin
if fBorderStyle <> value then fBorderStyle := value;
{$ifndef D6_or_higher}
Adjustbounds;
{$endif}
invalidate;
end;
procedure TrmCustomLabel.SetTextStyle(Value: TrmTextStyle);
begin
if ftextstyle <> value then ftextstyle := value;
{$ifndef D6_or_higher}
AdjustBounds;
{$endif}
invalidate;
end;
procedure TrmCustomLabel.SetGradient(Value: Boolean);
begin
if fUseGradient <> value then fUseGradient := value;
invalidate;
end;
procedure TrmCustomLabel.SetTLColor(value: TColor);
begin
if fGradTLColor <> value then fGradTLColor := value;
invalidate;
end;
procedure TrmCustomLabel.SetBRColor(value: TColor);
begin
if fGradBRColor <> value then fGradBRColor := value;
invalidate;
end;
procedure TrmCustomLabel.SetGradientDirection(value: TrmGradientLayout);
begin
if fGradDir <> value then fGradDir := value;
invalidate;
end;
function TrmCustomLabel.DrawBorder(canvas: TCanvas): trect;
var
Innertopcolor, Innerbottomcolor, Outertopcolor, Outerbottomcolor: TColor;
wr: TRect;
begin
wr := GetClientRect;
result := wr;
if BorderStyle = rmbsnone then exit;
InnerTopColor := clBlack;
InnerBottomColor := clblack;
OuterTopColor := clblack;
OuterBottomColor := clblack;
case borderstyle of
rmbsSunken:
begin
InnerTopColor := cl3ddkshadow;
InnerBottomColor := cl3dlight;
OuterTopColor := clBtnShadow;
OuterBottomColor := clBtnhighlight;
end;
rmbsRaised:
begin
InnerTopColor := clBtnhighlight;
InnerBottomColor := clBtnShadow;
if thickborder then
begin
OuterTopColor := cl3dlight;
OuterBottomColor := cl3ddkshadow;
end
else
begin
OuterTopColor := InnerTopColor;
OuterBottomColor := InnerBottomColor;
end
end;
rmbsRaisedEdge:
begin
InnerTopColor := clBtnShadow;
InnerBottomColor := clBtnhighlight;
OuterTopColor := clBtnhighlight;
OuterBottomColor := clBtnShadow;
end;
rmbsSunkenEdge:
begin
InnerTopColor := clBtnhighlight;
InnerBottomColor := clBtnShadow;
OuterTopColor := clBtnShadow;
OuterBottomColor := clBtnhighlight;
end;
end;
frame3d(canvas, wr, Outertopcolor, Outerbottomcolor, 1);
if (ThickBorder) or (borderstyle in [rmbsSunkenEdge, rmbsRaisedEdge]) then
frame3d(canvas, wr, Innertopcolor, Innerbottomcolor, 1);
result := wr;
end;
procedure TrmCustomLabel.GradientFill(canvas: TCanvas; R: TRect);
const
fNumColors = 63;
var
BeginRGBValue: array[0..2] of Byte;
RGBDifference: array[0..2] of integer;
ColorBand: TRect;
I: Integer;
Red: Byte;
Green: Byte;
Blue: Byte;
Brush, OldBrush: HBrush;
begin
BeginRGBValue[0] := GetRValue(ColorToRGB(fGradTLColor));
BeginRGBValue[1] := GetGValue(ColorToRGB(fGradTLColor));
BeginRGBValue[2] := GetBValue(ColorToRGB(fGradTLColor));
RGBDifference[0] := GetRValue(ColorToRGB(fGradBRColor)) - BeginRGBValue[0];
RGBDifference[1] := GetGValue(ColorToRGB(fGradBRColor)) - BeginRGBValue[1];
RGBDifference[2] := GetBValue(ColorToRGB(fGradBRColor)) - BeginRGBValue[2];
{ Calculate the color band's top and bottom coordinates }
{ for Left To Right fills }
if Gradientdirection = rmglLeftRight then
begin
ColorBand.Top := R.Top;
ColorBand.Bottom := R.Bottom;
end
else
begin
ColorBand.Left := R.Left;
ColorBand.Right := R.Right;
end;
{ Perform the fill }
for I := 0 to FNumColors - 1 do
begin { iterate through the color bands }
if Gradientdirection = rmglLeftRight then
begin
{ Calculate the color band's left and right coordinates }
ColorBand.Left := R.Left + MulDiv(I, R.Right - R.Left, FNumColors);
ColorBand.Right := R.Left + MulDiv(I + 1, R.Right - R.Left, FNumColors);
end
else
begin
ColorBand.Top := R.Top + MulDiv(I, R.Bottom - R.Top, FNumColors);
ColorBand.Bottom := R.Top + MulDiv(I + 1, R.Bottom - R.Top, FNumColors);
end;
{ Calculate the color band's color }
Red := BeginRGBValue[0] + MulDiv(I, RGBDifference[0], FNumColors - 1);
Green := BeginRGBValue[1] + MulDiv(I, RGBDifference[1], FNumColors - 1);
Blue := BeginRGBValue[2] + MulDiv(I, RGBDifference[2], FNumColors - 1);
{ Create a brush with the appropriate color for this band }
Brush := CreateSolidBrush(RGB(Red, Green, Blue));
{ Select that brush into the temporary DC. }
OldBrush := SelectObject(Canvas.handle, Brush);
try
{ Fill the rectangle using the selected brush -- PatBlt is faster than FillRect }
PatBlt(Canvas.handle, ColorBand.Left, ColorBand.Top, ColorBand.Right - ColorBand.Left, ColorBand.Bottom - ColorBand.Top, PATCOPY);
finally
{ Clean up the brush }
SelectObject(Canvas.handle, OldBrush);
DeleteObject(Brush);
end;
end; { iterate through the color bands }
end; { GradientFill }
procedure TrmCustomLabel.CMMouseEnter(var Message: TCMEnter);
begin
inherited;
if fmouseoptions.enabled then
begin
fnormalborder := borderstyle;
fnormalcolor := font.color;
fnormaltext := textstyle;
fborderstyle := fmouseoptions.EnterBorder;
ftextstyle := fmouseoptions.EnterTextStyle;
font.color := fmouseoptions.EnterColor;
end;
if assigned(fOnMouseEnter) then fOnMouseEnter(self);
end;
procedure TrmCustomLabel.CMMouseLeave(var Message: TCMExit);
begin
inherited;
if fmouseoptions.enabled then
begin
fborderstyle := fnormalborder;
ftextstyle := fnormaltext;
font.color := fNormalColor;
end;
if assigned(fOnMouseLeave) then fOnMouseLeave(self);
end;
procedure TrmCustomLabel.SetThickBorder(Value: Boolean);
begin
if fthickborder <> value then fthickborder := value;
invalidate;
end;
function TrmCustomLabel.GetBorderWidth: integer;
begin
result := 0;
case borderstyle of
rmbsRaisedEdge,
rmbsSunkenEdge: result := 2;
rmbsSingle,
rmbsRaised,
rmbsSunken: result := 1;
end;
if (ThickBorder) and (result = 1) then result := 2;
end;
procedure TrmCustomLabel.SetShadowColor(value: tcolor);
begin
fshadowcolor := value;
invalidate;
end;
procedure TrmCustomLabel.SetShadowDepth(value: integer);
begin
fshadowdepth := value;
invalidate;
end;
end.
|
namespace GlHelper;
interface
uses
rtl,
RemObjects.Elements.RTL,
OpenGL;
type
{ The kind of a TTexture map }
TextureKind = public (Diffuse, Specular, Normal, Height);
type
{ Represents a texture (map) as used by a TMesh }
Texture = public class
private
FId: GLuint;
FKind: TextureKind;
fValid : Boolean;
method IsPowerOfTwo(const AValue: Cardinal): Boolean; inline;
begin
exit ((AValue and (AValue - 1)) = 0);
end;
method prepareGlTexture(const img : glImageData);
public
constructor (const APath: String; const AKind: TextureKind := TextureKind.Normal);
finalizer;
{ OpenGL id of texture }
property Id: GLuint read FId;
{ Kind of texture }
property Kind: TextureKind read FKind;
property Valid : Boolean read fValid;
end;
implementation
constructor Texture(const APath: String; const AKind: TextureKind := TextureKind.Normal);
begin
inherited constructor();
FKind := AKind;
{ Generate OpenGL texture }
glGenTextures(1, @FId);
glBindTexture(GL_TEXTURE_2D, FId);
// Try load the Data
var Image := new GlImage(APath);
if Image.Valid then
prepareGlTexture(Image.Data);
{ Unbind }
glBindTexture(GL_TEXTURE_2D, 0);
glErrorCheck;
end;
method Texture.prepareGlTexture(const img : glImageData);
begin
if img.imgData <> nil then
begin
// writeLn('w '+Img.width.ToString + ' H '+Img.Height.ToString+' C '+Img.Components.ToString);
fValid := true;
var format: GLint;
case img.Components of
1: format := GL_RED;
3: format := GL_RGB;
4: format := GL_RGBA;
else
format := GL_RGBA;
end;
{ Set texture data }
glTexImage2D(GL_TEXTURE_2D, 0, format, img.width, img.Height, 0, format, GL_UNSIGNED_BYTE, img.imgData);
{ Generate mipmaps if possible. With OpenGL ES, mipmaps are only supported
if both dimensions are a power of two. }
var SupportsMipmaps := IsPowerOfTwo(img.width) and IsPowerOfTwo(img.Height);
if (SupportsMipmaps) then
glGenerateMipmap(GL_TEXTURE_2D);
{ Set texture parameters }
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
if (SupportsMipmaps) then
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
else
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
end;
end;
finalizer Texture;
begin
glDeleteTextures(1, @FId);
end;
end. |
unit ServerReact.Model.DAOGeneric;
interface
uses
System.JSON,
REST.Json,
SimpleInterface,
SimpleDAO,
SimpleAttributes,
SimpleQueryFiredac,
Data.DB,
ServerReact.Model.Connection,
DataSetConverter4D,
DataSetConverter4D.Impl,
DataSetConverter4D.Helper,
DataSetConverter4D.Util;
type
iDAOGeneric<T: class> = interface['{E719A822-4B08-43D1-8DF4-799C51A5AE62}']
function Find: TJsonArray; overload;
function Find (const aID: string): TJsonObject; overload;
function Insert (const aJsonObject: TJSONObject): TJsonObject;
function Update (const aJsonObject : TJsonObject) : TJsonObject;
function Delete (aField : String; aValue: String) : TJsonObject;
end;
TDAOGeneric<T : class, constructor> = class(TInterfacedObject, iDAOGeneric<T>)
private
FConn : iSimpleQuery;
FDAO : iSimpleDAO<T>;
FDataSource : TDataSource;
public
constructor Create;
destructor Destroy; override;
class function New: iDAOGeneric<T>;
function Find: TJsonArray; overload;
function Find (const aID: string): TJsonObject; overload;
function Insert (const aJsonObject: TJSONObject): TJsonObject;
function Update (const aJsonObject : TJsonObject) : TJsonObject;
function Delete (aField : String; aValue: String) : TJsonObject;
end;
implementation
uses
System.SysUtils;
{ TDAOGeneirc<T> }
constructor TDAOGeneric<T>.Create;
begin
FDataSource := TDataSource.Create(nil);
ServerReact.Model.Connection.Connected;
FConn := TSimpleQueryFiredac.New(ServerReact.Model.Connection.FConn);
FDAO := TSimpleDAO<T>.New(FConn).DataSource(FDataSource);
end;
function TDAOGeneric<T>.Delete(aField, aValue: String): TJsonObject;
begin
FDAO.Delete(aField, aValue);
Result := FDataSource.DataSet.AsJSONObject;
end;
destructor TDAOGeneric<T>.Destroy;
begin
FDataSource.Free;
ServerReact.Model.Connection.Disconnected;
inherited;
end;
function TDAOGeneric<T>.Find(const aID: string): TJsonObject;
begin
FDAO.Find(StrToInt(aID));
Result := FDataSource.DataSet.AsJSONObject;
end;
function TDAOGeneric<T>.Find: TJsonArray;
begin
FDAO.Find;
Result := FDataSource.DataSet.AsJSONArray;
end;
class function TDAOGeneric<T>.New: iDAOGeneric<T>;
begin
Result := Self.Create;
end;
function TDAOGeneric<T>.Insert(const aJsonObject: TJSONObject): TJsonObject;
begin
FDAO.Insert(TJson.JsonToObject<T>(aJsonObject));
Result := FDataSource.DataSet.AsJSONObject;
end;
function TDAOGeneric<T>.Update(const aJsonObject: TJsonObject): TJsonObject;
begin
FDAO.Update(TJson.JsonToObject<T>(aJsonObject));
Result := FDataSource.DataSet.AsJSONObject;
end;
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics,
VCL.TMSFNCGraphicsTypes, Vcl.ExtCtrls, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser,
VCL.TMSFNCMaps, VCL.TMSFNCGoogleMaps, Vcl.StdCtrls, AdvEdit, AdvGlowButton;
type
TFrmMain = class(TForm)
Map: TTMSFNCGoogleMaps;
Panel1: TPanel;
btnDisplay: TAdvGlowButton;
txtURL: TAdvEdit;
procedure FormCreate(Sender: TObject);
procedure MapMapInitialized(Sender: TObject);
procedure btnDisplayClick(Sender: TObject);
private
{ Private declarations }
procedure LoadKML;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses IOUtils, Flix.Utils.Maps, TMSFNCMapsCommonTypes, ClipBrd ;
const
DEFAULT_URL = 'http://webcore.flixengineering.com/data/13_Colonies.kml';
procedure TFrmMain.btnDisplayClick(Sender: TObject);
begin
LoadKML;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
var LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) );
try
Map.APIKey := LKeys.GetKey( msGoogleMaps );
finally
LKeys.Free;
end;
// set default coordinates to the Golden Gate Bridge
Map.Options.DefaultLatitude := 37.819722;
Map.Options.DefaultLongitude := -122.478611;
txtURL.Text := DEFAULT_URL;
btnDisplay.Enabled := False;
end;
procedure TFrmMain.LoadKML;
begin
Map.KMLLayers.Clear;
Map.AddKMLLayer(txtURL.Text, True );
end;
procedure TFrmMain.MapMapInitialized(Sender: TObject);
var
LCoord: TTMSFNCMapsCoordinate;
begin
btnDisplay.Enabled := True;
end;
end.
|
unit BsLgotClientEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, cxControls, cxContainer, cxEdit,
cxLabel, StdCtrls, cxLookAndFeelPainters, cxButtons, cxCalendar, DB,
FIBDataSet, pFIBDataSet, ExtCtrls, uCommon_Messages;
type
TfrmLgotEdit = class(TForm)
lblLgot: TcxLabel;
LgotBox: TcxLookupComboBox;
lblProc: TcxLabel;
lblGroup: TcxLabel;
GroupBox: TcxLookupComboBox;
BoxLgots: TGroupBox;
BoxFIO: TGroupBox;
BoxCustomerService: TGroupBox;
lblFirstName: TcxLabel;
lblName: TcxLabel;
lblPatronymic: TcxLabel;
FirstNameBox: TcxLookupComboBox;
NameBox: TcxLookupComboBox;
PatrBox: TcxLookupComboBox;
CustomerServiceBox: TcxLookupComboBox;
lblCustomerService: TcxLabel;
lblDate: TcxLabel;
DateBeg: TcxDateEdit;
DateEnd: TcxDateEdit;
lblDateEnd: TcxLabel;
NomerEdit: TcxTextEdit;
lblNomer: TcxLabel;
InnEdit: TcxTextEdit;
lblInn: TcxLabel;
btnOk: TcxButton;
btnCancel: TcxButton;
LgotDSet: TpFIBDataSet;
GroupDSet: TpFIBDataSet;
FirstNameDSet: TpFIBDataSet;
NameDSet: TpFIBDataSet;
PatrDSet: TpFIBDataSet;
CustServDset: TpFIBDataSet;
LgotDS: TDataSource;
GroupDS: TDataSource;
FirstNameDS: TDataSource;
NameDS: TDataSource;
PatrDS: TDataSource;
CustServDS: TDataSource;
TimerEdit: TTimer;
PeriodsDSet: TpFIBDataSet;
GetPersonPrivInfo: TpFIBDataSet;
CustServiceEdit: TcxTextEdit;
procedure TimerEditTimer(Sender: TObject);
procedure LgotBoxEnter(Sender: TObject);
procedure LgotBoxExit(Sender: TObject);
procedure LgotBoxClick(Sender: TObject);
procedure FirstNameBoxClick(Sender: TObject);
procedure FirstNameBoxEnter(Sender: TObject);
procedure FirstNameBoxExit(Sender: TObject);
procedure NameBoxClick(Sender: TObject);
procedure NameBoxEnter(Sender: TObject);
procedure NameBoxExit(Sender: TObject);
procedure PatrBoxClick(Sender: TObject);
procedure PatrBoxEnter(Sender: TObject);
procedure PatrBoxExit(Sender: TObject);
procedure CustomerServiceBoxExit(Sender: TObject);
procedure CustomerServiceBoxEnter(Sender: TObject);
procedure CustomerServiceBoxClick(Sender: TObject);
procedure LgotBoxKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FirstNameBoxKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure NameBoxKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure PatrBoxKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure CustomerServiceBoxKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure LgotBoxPropertiesInitPopup(Sender: TObject);
procedure FirstNameBoxPropertiesInitPopup(Sender: TObject);
procedure NameBoxPropertiesInitPopup(Sender: TObject);
procedure PatrBoxPropertiesInitPopup(Sender: TObject);
procedure CustomerServiceBoxPropertiesInitPopup(Sender: TObject);
procedure LgotBoxPropertiesChange(Sender: TObject);
private
{ Private declarations }
ContextInputType, LgotEditMode:SmallInt;
MDateBeg, MDateEnd:TDate;
function CheckData:Boolean;
public
{ Public declarations }
constructor Create(AOwner:TComponent; KodMachineIn, IdPersonPriv:Integer; EditMode:SmallInt);reintroduce;
end;
var
frmLgotEdit: TfrmLgotEdit;
implementation
{$R *.dfm}
uses BsClient, cxLookupDBGrid;
constructor TfrmLgotEdit.Create(AOwner:Tcomponent; KodMachineIn, IdPersonPriv:Integer; EditMode:SmallInt);
var i:SmallInt;
begin
//EditMode: 0 - добавление, 1 -редактирование, 2 - просмотр
inherited Create(Aowner);
LgotEditMode:=EditMode;
if PeriodsDSet.Active then PeriodsDSet.Close;
PeriodsDSet.SQLs.SelectSQL.Text:='SELECT MIN(DATE_BEG) AS MDATE_BEG, MAX(DATE_END) AS MDATE_END FROM BS_CLIENT_ACCOUNT WHERE KOD_MACHINE=:KOD';
PeriodsDSet.ParamByName('KOD').AsInteger:=KodMachineIn;
PeriodsDSet.Open;
if not PeriodsDSet.IsEmpty then
begin
MDateBeg:=PeriodsDSet['MDATE_BEG'];
MDateEnd:=PeriodsDSet['MDATE_END'];
end;
case EditMode of
0: begin
if IdPersonPriv=-1 then
begin
if GroupDSet.Active then GroupDSet.Close;
GroupDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_SP_PERSON_PRIV_TYPE';
GroupDSet.Open;
GroupBox.EditValue:=1;
GroupBox.Enabled:=False;
end
else
begin
if GroupDSet.Active then GroupDSet.Close;
GroupDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_SP_PERSON_PRIV_TYPE WHERE ID_PERSON_PRIV_TYPE<>1';
GroupDSet.Open;
if GetPersonPrivInfo.Active then GetPersonPrivInfo.Close;
GetPersonPrivInfo.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_PERSON_PRIVILEGES_DOC WHERE ID_PERSON_PRIV=:ID_PERSON_PRIV';
GetPersonPrivInfo.ParamByName('ID_PERSON_PRIV').AsInteger:=IdPersonPriv;
GetPersonPrivInfo.Open;
if not GetPersonPrivInfo.IsEmpty then
begin
if not VarIsNull(GetPersonPrivInfo['NUM_DOC']) then NomerEdit.Text:=GetPersonPrivInfo['NUM_DOC'];
NomerEdit.Enabled:=False;
if not VarIsNull(GetPersonPrivInfo['NAME_ORGANIZATION_DOC']) then CustServiceEdit.Text:=GetPersonPrivInfo['NAME_ORGANIZATION_DOC'];
CustServiceEdit.Enabled:=False;
DateBeg.Date:=GetPersonPrivInfo['DATE_BEG_DOC'];
DateBeg.Enabled:=False;
DateEnd.Date:=GetPersonPrivInfo['DATE_END_DOC'];
DateEnd.Enabled:=False;
LgotDSet.Close;
LgotDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_SP_LGOT_SEL_BY_ID(:ID_LGOT, :ACT_DATE)';
LgotDSet.ParamByName('ID_LGOT').AsString:=GetPersonPrivInfo['ID_PPRIVILEGES'];
LgotDSet.ParamByName('ACT_DATE').AsDate:=Date;
LgotDSet.Open;
LgotBox.EditValue:=GetPersonPrivInfo['ID_PPRIVILEGES'];
LgotBox.Enabled:=False;
end;
end;
end;
1: begin
lblGroup.Visible:=False;
GroupBox.Visible:=False;
lblFirstName.Visible:=False;
FirstNameBox.Visible:=False;
lblName.Visible:=False;
NameBox.Visible:=False;
lblPatronymic.Visible:=False;
PatrBox.Visible:=False;
BoxFIO.Visible:=False;
lblInn.Visible:=False;
InnEdit.Visible:=False;
BoxCustomerService.Top:=78;
btnOk.Top:=158;
btnCancel.Top:=158;
Self.Height:=220;
if GetPersonPrivInfo.Active then GetPersonPrivInfo.Close;
GetPersonPrivInfo.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_PERSON_PRIVILEGES_DOC WHERE ID_PERSON_PRIV=:ID_PRIV';
GetPersonPrivInfo.ParamByName('ID_PRIV').AsInteger:=IdPersonPriv;
GetPersonPrivInfo.Open;
if not GetPersonPrivInfo.IsEmpty then
begin
if not VarIsNull(GetPersonPrivInfo['NUM_DOC']) then NomerEdit.Text:=GetPersonPrivInfo['NUM_DOC'];
if not VarIsNull(GetPersonPrivInfo['NAME_ORGANIZATION_DOC']) then CustServiceEdit.Text:=GetPersonPrivInfo['NAME_ORGANIZATION_DOC'];
DateBeg.Date:=GetPersonPrivInfo['DATE_BEG_DOC'];
DateEnd.Date:=GetPersonPrivInfo['DATE_END_DOC'];
if LgotDSet.Active then LgotDSet.Close;
LgotDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_SP_LGOT_SEL_BY_ID(:ID_LGOT, :ACT_DATE)';
LgotDSet.ParamByName('ID_LGOT').AsString:=GetPersonPrivInfo['ID_PPRIVILEGES'];
LgotDSet.ParamByName('ACT_DATE').AsDate:=Date;
LgotDSet.Open;
LgotBox.EditValue:=GetPersonPrivInfo['ID_PPRIVILEGES'];
end;
end;
2: begin
if GetPersonPrivInfo.Active then GetPersonPrivInfo.Close;
GetPersonPrivInfo.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_PERSON_PRIV_GET_INFO_BY_ID(:ID_PERSON_PRIV, :ACT_DATE)';
GetPersonPrivInfo.ParamByName('ID_PERSON_PRIV').AsInteger:=IdPersonPriv;
GetPersonPrivInfo.ParamByName('ACT_DATE').AsDate:=Date;
GetPersonPrivInfo.Open;
if not GetPersonPrivInfo.IsEmpty then
begin
for i:=0 to Self.ComponentCount-1 do
begin
if Components[i] is TcxTextEdit then (Components[i] as TcxTextEdit).Enabled:=False
else if Components[i] is TcxDateEdit then (Components[i] as TcxDateEdit).Enabled:=False
else if Components[i] is TcxLookupComboBox then (Components[i] as TcxLookupComboBox).Enabled:=False;
if not VarIsNull(GetPersonPrivInfo['TIN_PERSON_PRIV']) then InnEdit.Text:=GetPersonPrivInfo['TIN_PERSON_PRIV'];
if not VarIsNull(GetPersonPrivInfo['NUM_DOC']) then NomerEdit.Text:=GetPersonPrivInfo['NUM_DOC'];
if not VarIsNull(GetPersonPrivInfo['NAME_ORGANIZATION_DOC']) then CustServiceEdit.Text:=GetPersonPrivInfo['NAME_ORGANIZATION_DOC'];
DateBeg.Date:=GetPersonPrivInfo['DATE_BEG_DOC'];
DateEnd.Date:=GetPersonPrivInfo['DATE_END_DOC'];
LgotDSet.Close;
LgotDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_SP_LGOT_SEL_BY_ID(:ID_LGOT, :ACT_DATE)';
LgotDSet.ParamByName('ID_LGOT').AsString:=GetPersonPrivInfo['ID_PPRIVILEGES'];
LgotDSet.ParamByName('ACT_DATE').AsDate:=Date;
LgotDSet.Open;
LgotBox.EditValue:=GetPersonPrivInfo['ID_PPRIVILEGES'];
if GroupDSet.Active then GroupDSet.Close;
GroupDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_SP_PERSON_PRIV_TYPE';
GroupDSet.Open;
GroupBox.EditValue:=GetPersonPrivInfo['ID_PERSON_PRIV_TYPE'];
if FirstNameDSet.Active then FirstNameDSet.Close;
FirstNameDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_GET_FIO_LGOT_BY_ID(:ID_PERSON_PRIV_KEY, :RADIO_BTN)';
FirstNameDSet.ParamByName('ID_PERSON_PRIV_KEY').AsInteger:=GetPersonPrivInfo['ID_PERSON_PRIV_KEY'];
FirstNameDSet.ParamByName('RADIO_BTN').AsShort:=0;
FirstNameDSet.Open;
FirstNameBox.EditValue:=1;
if NameDSet.Active then NameDSet.Close;
NameDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_GET_FIO_LGOT_BY_ID(:ID_PERSON_PRIV_KEY, :RADIO_BTN)';
NameDSet.ParamByName('ID_PERSON_PRIV_KEY').AsInteger:=GetPersonPrivInfo['ID_PERSON_PRIV_KEY'];
NameDSet.ParamByName('RADIO_BTN').AsShort:=1;
NameDSet.Open;
NameBox.EditValue:=1;
if PatrDSet.Active then PatrDSet.Close;
PatrDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_GET_FIO_LGOT_BY_ID(:ID_PERSON_PRIV_KEY, :RADIO_BTN)';
PatrDSet.ParamByName('ID_PERSON_PRIV_KEY').AsInteger:=GetPersonPrivInfo['ID_PERSON_PRIV_KEY'];
PatrDSet.ParamByName('RADIO_BTN').AsShort:=2;
PatrDSet.Open;
PatrBox.EditValue:=1;
end;
end;
end;
end;
end;
procedure TfrmLgotEdit.TimerEditTimer(Sender: TObject);
begin
TimerEdit.Enabled:=False;
case ContextInputType of
0:
begin
FirstNameDSet.Close;
FirstNameDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_FIO_LGOT_FILTER(:FILTER_STR, :RADIO_BTN)';
FirstNameDSet.ParamByName('FILTER_STR').AsString:=FirstNameBox.EditText;
FirstNameDSet.ParamByName('RADIO_BTN').AsShort:=0;
FirstNameDSet.Open;
if not FirstNameDSet.IsEmpty then
begin
FirstNameBox.DroppedDown:=True;
end;
end;
1:
begin
NameDSet.Close;
NameDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_FIO_LGOT_FILTER(:FILTER_STR, :RADIO_BTN)';
NameDSet.ParamByName('FILTER_STR').AsString:=NameBox.EditText;
NameDSet.ParamByName('RADIO_BTN').AsShort:=1;
NameDSet.Open;
if not NameDSet.IsEmpty then
begin
NameBox.DroppedDown:=True;
end;
end;
2:
begin
PatrDSet.Close;
PatrDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_FIO_LGOT_FILTER(:FILTER_STR, :RADIO_BTN)';
PatrDSet.ParamByName('FILTER_STR').AsString:=PatrBox.EditText;
PatrDSet.ParamByName('RADIO_BTN').AsShort:=2;
PatrDSet.Open;
if not PatrDSet.IsEmpty then
begin
PatrBox.DroppedDown:=True;
end;
end;
3:
begin
LgotDSet.Close;
LgotDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_SP_LGOT_FILTER(:FILTER_STR, :ACT_DATE)';
LgotDSet.ParamByName('FILTER_STR').AsString:=LgotBox.EditText;
LgotDSet.ParamByName('ACT_DATE').AsDate:=Date;
LgotDSet.Open;
if not LgotDSet.IsEmpty then
begin
LgotBox.DroppedDown:=True;
end;
end;
4:
begin
CustServDset.Close;
CustServDset.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_NAME_CUSTOM_SERVICE_FILTER(:FILTER_STR)';
CustServDset.ParamByName('FILTER_STR').AsString:=CustomerServiceBox.EditText;
CustServDset.Open;
if not CustServDset.IsEmpty then
begin
CustomerServiceBox.DroppedDown:=True;
end;
end;
end;
end;
function TfrmLgotEdit.CheckData:Boolean;
begin
Result:=True;
if (VarIsNull(GroupBox.EditValue) And (LgotEditMode=0)) then
begin
GroupBox.Style.Color:=$00DDBBFF;
GroupBox.SetFocus;
Result:=False;
bsShowMessage('Увага!', 'Ви не обрали групу!', mtInformation, [mbOK]);
end;
if ((VarIsNull(LgotBox.EditValue)) And (GroupBox.EditValue<>1)) then
begin
LgotBox.Style.Color:=$00DDBBFF;
LgotBox.SetFocus;
Result:=False;
bsShowMessage('Увага!', 'Ви не не обрали пільгу!', mtInformation, [mbOK]);
end;
if ((FirstNameBox.EditText='') And (LgotEditMode=0)) then
begin
FirstNameBox.Style.Color:=$00DDBBFF;
FirstNameBox.SetFocus;
Result:=False;
bsShowMessage('Увага!', 'Ви не заповнили поле "Прізвище"!', mtInformation, [mbOK]);
end;
if ((NameBox.EditText='') And (LgotEditMode=0)) then
begin
NameBox.Style.Color:=$00DDBBFF;
NameBox.SetFocus;
Result:=False;
bsShowMessage('Увага!', 'Ви не заповнили поле "І''мя"!', mtInformation, [mbOK]);
end;
if ((PatrBox.EditText='') And (LgotEditMode=0)) then
begin
PatrBox.Style.Color:=$00DDBBFF;
PatrBox.SetFocus;
Result:=False;
bsShowMessage('Увага!', 'Ви не заповнили поле "По батькові"!', mtInformation, [mbOK]);
end;
if DateBeg.Text='' then
begin
DateBeg.Style.Color:=$00DDBBFF;
DateBeg.SetFocus;
Result:=False;
bsShowMessage('Увага!', 'Ви не обрали дату початку!', mtInformation, [mbOK]);
end;
if DateEnd.Text='' then
begin
DateEnd.Style.Color:=$00DDBBFF;
DateEnd.SetFocus;
Result:=False;
bsShowMessage('Увага!', 'Ви не обрали дату кінця!', mtInformation, [mbOK]);
end;
if DateBeg.Date<MDateBeg then
begin
Result:=False;
bsShowMessage('Увага!', 'Дата початку дії пільги не може бути менш, ніж дата початку особового рахунку ('+DateToStr(MDateBeg)+')!', mtInformation, [mbOK]);
end;
if DateEnd.Date>MDateEnd then
begin
Result:=False;
bsShowMessage('Увага!', 'Дата кінця дії пільги не може бути більш, ніж дата кінця особового рахунку ('+DateToStr(MDateEnd)+')!', mtInformation, [mbOK]);
end;
if DateBeg.Date>DateEnd.Date then
begin
Result:=False;
bsShowMessage('Увага!', 'Дата початку дії пільги не може перевищувати дату кінця дії!', mtInformation, [mbOK]);
end;
end;
procedure TfrmLgotEdit.LgotBoxEnter(Sender: TObject);
begin
TimerEdit.Interval:=2000;
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.LgotBoxExit(Sender: TObject);
begin
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.LgotBoxClick(Sender: TObject);
begin
TimerEdit.Interval:=2000;
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.FirstNameBoxClick(Sender: TObject);
begin
TimerEdit.Interval:=500;
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.FirstNameBoxEnter(Sender: TObject);
begin
TimerEdit.Interval:=500;
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.FirstNameBoxExit(Sender: TObject);
begin
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.NameBoxClick(Sender: TObject);
begin
TimerEdit.Interval:=500;
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.NameBoxEnter(Sender: TObject);
begin
TimerEdit.Interval:=500;
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.NameBoxExit(Sender: TObject);
begin
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.PatrBoxClick(Sender: TObject);
begin
TimerEdit.Interval:=500;
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.PatrBoxEnter(Sender: TObject);
begin
TimerEdit.Interval:=500;
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.PatrBoxExit(Sender: TObject);
begin
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.CustomerServiceBoxExit(Sender: TObject);
begin
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.CustomerServiceBoxEnter(Sender: TObject);
begin
TimerEdit.Interval:=2000;
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.CustomerServiceBoxClick(Sender: TObject);
begin
TimerEdit.Interval:=2000;
TimerEdit.Enabled:=False;
end;
procedure TfrmLgotEdit.LgotBoxKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
ContextInputType:=3;
if LgotBox.EditText='' then
if LgotDSet.Active then LgotDSet.Close;
TimerEdit.Enabled:=not ((LgotBox.EditText='') or (Key=VK_RETURN));
end;
procedure TfrmLgotEdit.FirstNameBoxKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
ContextInputType:=0;
if FirstNameBox.EditText='' then
if FirstNameDSet.Active then FirstNameDSet.Close;
TimerEdit.Enabled:=not ((FirstNameBox.EditText='') or (Key=VK_RETURN));
end;
procedure TfrmLgotEdit.NameBoxKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
ContextInputType:=1;
if NameBox.EditText='' then
if NameDSet.Active then NameDSet.Close;
TimerEdit.Enabled:=not ((NameBox.EditText='') or (Key=VK_RETURN));
end;
procedure TfrmLgotEdit.PatrBoxKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
ContextInputType:=2;
if PatrBox.EditText='' then
if PatrDSet.Active then PatrDSet.Close;
TimerEdit.Enabled:= not ((PatrBox.EditText='') or (Key=VK_RETURN));
end;
procedure TfrmLgotEdit.CustomerServiceBoxKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
ContextInputType:=4;
if CustomerServiceBox.EditText='' then
if CustServDset.Active then CustServDset.Close;
TimerEdit.Enabled:= not (CustomerServiceBox.EditText='');
end;
procedure TfrmLgotEdit.btnOkClick(Sender: TObject);
begin
if CheckData then ModalResult:=mrOk;
end;
procedure TfrmLgotEdit.btnCancelClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TfrmLgotEdit.LgotBoxPropertiesInitPopup(Sender: TObject);
begin
if LgotBox.EditText='' then
begin
LgotDSet.Close;
LgotDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_SP_LGOT_FILTER(:FILTER_STR, :ACT_DATE)';
LgotDSet.ParamByName('FILTER_STR').AsString:=LgotBox.EditText;
LgotDSet.ParamByName('ACT_DATE').AsDate:=Date;
LgotDSet.Open;
end;
end;
procedure TfrmLgotEdit.FirstNameBoxPropertiesInitPopup(Sender: TObject);
begin
if FirstNameBox.EditText='' then
begin
FirstNameDSet.Close;
FirstNameDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_FIO_LGOT_FILTER(:FILTER_STR, :RADIO_BTN)';
FirstNameDSet.ParamByName('FILTER_STR').AsString:=FirstNameBox.EditText;
FirstNameDSet.ParamByName('RADIO_BTN').AsShort:=0;
FirstNameDSet.Open;
end;
end;
procedure TfrmLgotEdit.NameBoxPropertiesInitPopup(Sender: TObject);
begin
if NameBox.EditText='' then
begin
NameDSet.Close;
NameDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_FIO_LGOT_FILTER(:FILTER_STR, :RADIO_BTN)';
NameDSet.ParamByName('FILTER_STR').AsString:=NameBox.EditText;
NameDSet.ParamByName('RADIO_BTN').AsShort:=1;
NameDSet.Open;
end;
end;
procedure TfrmLgotEdit.PatrBoxPropertiesInitPopup(Sender: TObject);
begin
if PatrBox.EditText='' then
begin
PatrDSet.Close;
PatrDSet.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_FIO_LGOT_FILTER(:FILTER_STR, :RADIO_BTN)';
PatrDSet.ParamByName('FILTER_STR').AsString:=PatrBox.EditText;
PatrDSet.ParamByName('RADIO_BTN').AsShort:=2;
PatrDSet.Open;
end;
end;
procedure TfrmLgotEdit.CustomerServiceBoxPropertiesInitPopup(
Sender: TObject);
begin
if CustomerServiceBox.EditText='' then
begin
CustServDset.Close;
CustServDset.SQLs.SelectSQL.Text:='SELECT DISTINCT * FROM BS_NAME_CUSTOM_SERVICE_FILTER(:FILTER_STR)';
CustServDset.ParamByName('FILTER_STR').AsString:=CustomerServiceBox.EditText;
CustServDset.Open;
end;
end;
procedure TfrmLgotEdit.LgotBoxPropertiesChange(Sender: TObject);
begin
lblProc.Caption:='% '+FloatToStr(LgotBox.Properties.ListColumns.Items[1].Field.AsFloat);
end;
end.
|
namespace CirrusTrace;
interface
type
// Aspect declared in CirrusTraceAspectLibrary is applied to this class
// Build and start the application to see how it will affect the behaviour of
// Sum and Multiply methods
[CirrusTraceAspectLibrary.Trace]
WorkerClass = class
public
method Sum(aValueA: Int32; aValueB: Int32): Int32; virtual;
method Multiply(aValueA: Int32; aValueB: Int32; aValueC: Int32): Int32; virtual;
end;
implementation
method WorkerClass.Sum(aValueA: Int32; aValueB: Int32): Int32;
begin
Console.WriteLine('Sum method is processing data');
exit (aValueA + aValueB);
end;
method WorkerClass.Multiply(aValueA: Int32; aValueB: Int32; aValueC: Int32): Int32;
begin
Console.WriteLine('Multiply method is processing data');
exit (aValueA * aValueB * aValueC);
end;
end. |
{###############################################################################
https://github.com/wendelb/DelphiOTP
###############################################################################}
unit Base32U;
{
================================================================================
If you found this Unit as your were looking for a delphi Base32 Implementation,
that is also unicode ready, please see the Readme!
================================================================================
}
interface
uses
System.SysUtils; // For UpperCase (Base32Decode)
type
Base32 = class
public
/// <param name="inString">
/// Base32-String (Attention: No validity checks)
/// </param>
/// <summary>
/// Decodes a Base32-String
/// </summary>
/// <returns>
/// Unicode String containing the ANSI-Data from that Base32-Input
/// </returns>
class function Decode(const inString: String): String;
/// <param name="inString">
/// UTF8-String (Attention: No validity checks)
/// </param>
/// <summary>
/// Encodes a UTF-8String into a Base32-String
/// </summary>
/// <returns>
/// Unicode string containing the Base32 string encoded from that UTF8-Input
/// </returns>
class function Encode(const InString: UTF8String): string;
/// <summary>
/// Same as Encode but cleans up the trailing "=" at the end of the string.
/// </summary>
class function EncodeWithoutPadding(const InString: UTF8String): string;
end;
// As the FromBase32String Function doesn't has the result I'm looking for, here
// is my version of that function. This is converted from a PHP function, which
// can be found here: https://www.idontplaydarts.com/2011/07/google-totp-two-factor-authentication-for-php/
const
ValidChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
implementation
uses
System.Math;
{$REGION 'Base32Functions'}
function Base32Decode(const source: String): String;
var
UpperSource: String;
p, i, l, n, j: Integer;
begin
UpperSource := UpperCase(source);
l := Length(source);
n := 0; j := 0;
Result := '';
for i := 1 to l do
begin
n := n shl 5; // Move buffer left by 5 to make room
p := Pos(UpperSource[i], ValidChars);
if p >= 0 then
n := n + (p - 1); // Add value into buffer
j := j + 5; // Keep track of number of bits in buffer
if (j >= 8) then
begin
j := j - 8;
Result := Result + chr((n AND ($FF shl j)) shr j);
end;
end;
end;
function Base32Encode(str: UTF8String): string;
var
B: Int64;
i, j, len: Integer;
begin
Result := '';
// Every 5 characters are encoded in groups (5 characters x8 = 40 bits, 5 * 8 characters = 40 bits, and each character of BASE32 is represented by 5 bits)
len := length(str);
while len > 0 do
begin
if len >= 5 then
len := 5;
// Store the ASCII codes of these 5 characters in order into Int64 (8 bytes in total) integer
B := 0;
for i := 1 to len do
B := B shl 8 + Ord (str [i]); // Store a character, shift one byte to the left (8 bits)
B := B shl ((8-len) * 8); // Finally shift left 3 bytes (3 * 8)
j := system.Math.ceil(len * 8 / 5);
// Encoding, every 5 digits represent a character, 8 characters are exactly 40 digits
for i := 1 to 8 do
begin
if i <= j then
begin
Result := Result + ValidChars [B shr 59 + 1]; // shift right 7 * 8 digits +3 digits, take characters from BASE32 table
B := B shl 5; // Shift 5 bits to the left each time
end
else
Result := Result + '=';
end;
// Remove the processed 5 characters
delete(str, 1, len);
len := length(str);
end;
end;
{$ENDREGION}
{ Base32 }
class function Base32.Decode(const inString: String): String;
begin
Result := Base32Decode(inString);
end;
class function Base32.Encode(const inString: UTF8String): string;
begin
Result := Base32Encode(inString);
end;
class function Base32.EncodeWithoutPadding(const InString: UTF8String): string;
begin
Result := StringReplace(Base32Encode(inString),'=','',[rfReplaceAll]);
end;
end.
|
//
// Generated by JavaToPas v1.5 20150830 - 103229
////////////////////////////////////////////////////////////////////////////////
unit org.apache.http.client.protocol.ClientContextConfigurer;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
org.apache.http.protocol.HttpContext,
org.apache.http.cookie.CookieSpecRegistry,
org.apache.http.auth.AuthSchemeRegistry,
org.apache.http.client.CookieStore,
org.apache.http.client.CredentialsProvider;
type
JClientContextConfigurer = interface;
JClientContextConfigurerClass = interface(JObjectClass)
['{FD87BD25-9308-42BD-98A4-F2BE5E52CCFA}']
function init(context : JHttpContext) : JClientContextConfigurer; cdecl; // (Lorg/apache/http/protocol/HttpContext;)V A: $1
procedure setAuthSchemePref(list : JList) ; cdecl; // (Ljava/util/List;)V A: $1
procedure setAuthSchemeRegistry(registry : JAuthSchemeRegistry) ; cdecl; // (Lorg/apache/http/auth/AuthSchemeRegistry;)V A: $1
procedure setCookieSpecRegistry(registry : JCookieSpecRegistry) ; cdecl; // (Lorg/apache/http/cookie/CookieSpecRegistry;)V A: $1
procedure setCookieStore(store : JCookieStore) ; cdecl; // (Lorg/apache/http/client/CookieStore;)V A: $1
procedure setCredentialsProvider(provider : JCredentialsProvider) ; cdecl; // (Lorg/apache/http/client/CredentialsProvider;)V A: $1
end;
[JavaSignature('org/apache/http/client/protocol/ClientContextConfigurer')]
JClientContextConfigurer = interface(JObject)
['{4EAA18A1-BC31-4DDD-84B1-586E974D80E0}']
procedure setAuthSchemePref(list : JList) ; cdecl; // (Ljava/util/List;)V A: $1
procedure setAuthSchemeRegistry(registry : JAuthSchemeRegistry) ; cdecl; // (Lorg/apache/http/auth/AuthSchemeRegistry;)V A: $1
procedure setCookieSpecRegistry(registry : JCookieSpecRegistry) ; cdecl; // (Lorg/apache/http/cookie/CookieSpecRegistry;)V A: $1
procedure setCookieStore(store : JCookieStore) ; cdecl; // (Lorg/apache/http/client/CookieStore;)V A: $1
procedure setCredentialsProvider(provider : JCredentialsProvider) ; cdecl; // (Lorg/apache/http/client/CredentialsProvider;)V A: $1
end;
TJClientContextConfigurer = class(TJavaGenericImport<JClientContextConfigurerClass, JClientContextConfigurer>)
end;
implementation
end.
|
unit CatCSTimer;
{
Catarinka - Console Timer
Copyright (c) 2020 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
Based on TConsoleTimer by LU RD
Changes:
* 22.09.2020, FD - Added OnTimerCallBack that allows to work through callback
- Added Reset method
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
Winapi.Windows, System.Classes, SyncObjs, Diagnostics;
{$ELSE}
Windows, Classes, SyncObjs;
{$ENDIF}
type
TTimerArg = {$IFDEF DXE2_OR_UP}reference to procedure{$ELSE}procedure of object{$ENDIF};
type
TConsoleTimer = Class(TThread)
private
fCancelFlag: TSimpleEvent;
fTimerEnabledFlag: TSimpleEvent;
fTimerProc: TNotifyEvent; // method to call
fTimerCallBack: TTimerArg;
fInterval: integer;
procedure SetEnabled(doEnable: boolean);
function GetEnabled: boolean;
procedure SetInterval(interval: integer);
protected
procedure Execute; override;
public
constructor Create;
destructor Destroy; override;
procedure Reset;
property Enabled : boolean read GetEnabled write SetEnabled;
property Interval: integer read FInterval write SetInterval;
// Note: OnTimerEvent is executed in TConsoleTimer thread
property OnTimerEvent: TNotifyEvent read fTimerProc write fTimerProc;
property OnTimerCallBack: TTimerArg read fTimerCallback write fTimerCallBack;
end;
implementation
constructor TConsoleTimer.Create;
begin
inherited Create(false);
FTimerEnabledFlag := TSimpleEvent.Create;
FCancelFlag := TSimpleEvent.Create;
FTimerProc := nil;
FInterval := 1000;
Self.FreeOnTerminate := false; // Main thread controls for thread destruction
end;
destructor TConsoleTimer.Destroy; // Call TConsoleTimer.Free to cancel the thread
begin
Terminate;
FTimerEnabledFlag.ResetEvent; // Stop timer event
FCancelFlag.SetEvent; // Set cancel flag
Waitfor; // Synchronize
FCancelFlag.Free;
FTimerEnabledFlag.Free;
inherited;
end;
procedure TConsoleTimer.SetEnabled(doEnable: boolean);
begin
if doEnable then
FTimerEnabledFlag.SetEvent
else
FTimerEnabledFlag.ResetEvent;
end;
procedure TConsoleTimer.SetInterval(interval: integer);
begin
FInterval := interval;
end;
procedure TConsoleTimer.Execute;
var
waitList: array [0 .. 1] of THandle;
waitInterval,lastProcTime: Int64;
sw: TStopWatch;
begin
sw.Create;
waitList[0] := FTimerEnabledFlag.Handle;
waitList[1] := FCancelFlag.Handle;
lastProcTime := 0;
while not Terminated do
begin
if (WaitForMultipleObjects(2, @waitList[0], false, INFINITE) <>
WAIT_OBJECT_0) then
break; // Terminate thread when FCancelFlag is signaled
if Assigned(fTimerProc)
{$IFDEF DXE2_OR_UP}
or Assigned(fTimerCallBack)
{$ENDIF}
then
begin
waitInterval := FInterval - lastProcTime;
if (waitInterval < 0) then
waitInterval := 0;
if WaitForSingleObject(FCancelFlag.Handle,waitInterval) <> WAIT_TIMEOUT then
break;
if WaitForSingleObject(FTimerEnabledFlag.Handle, 0) = WAIT_OBJECT_0 then
begin
sw.Start;
if Assigned(fTimerProc) then
FTimerProc(Self);
{$IFDEF DXE2_OR_UP}
if Assigned(fTimerCallback) then
FTimerCallback;
{$ENDIF}
sw.Stop;
// Interval adjusted for FTimerProc execution time
lastProcTime := sw.ElapsedMilliSeconds;
end;
end;
end;
end;
function TConsoleTimer.GetEnabled: boolean;
begin
Result := (FTimerEnabledFlag.Waitfor(0) = wrSignaled);
end;
procedure TConsoleTimer.Reset;
begin
SetEnabled(false);
SetEnabled(true);
end;
{
Additional Notes:
How to make the event execute in the main thread:
Reading: Handling events in console application (TidIRC) gives the answer.
https://stackoverflow.com/a/11366186/576719
Add a method in TConsoleTimer:
procedure TConsoleTimer.SwapToMainThread;
begin
FTimerProc(Self);
end;
and change the call in the Execute method to:
Synchronize(SwapToMainThread);
To pump the synchronized calls, use CheckSynchronize() function in Classes unit:
while not KeyPressed do CheckSynchronize(); // Pump the synchronize queue
}
end. |
//
// Generated by JavaToPas v1.5 20171018 - 170742
////////////////////////////////////////////////////////////////////////////////
unit java.util.Comparator;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.util.function.Function,
java.util.function.ToIntFunction,
java.util.function.ToLongFunction,
java.util.function.ToDoubleFunction;
type
JComparator = interface;
JComparatorClass = interface(JObjectClass)
['{03162D52-F0B1-49C7-B0D4-6582C44A36B1}']
function compare(JObjectparam0 : JObject; JObjectparam1 : JObject) : Integer; cdecl;// (Ljava/lang/Object;Ljava/lang/Object;)I A: $401
function comparing(keyExtractor : JFunction) : JComparator; cdecl; overload;// (Ljava/util/function/Function;)Ljava/util/Comparator; A: $9
function comparing(keyExtractor : JFunction; keyComparator : JComparator) : JComparator; cdecl; overload;// (Ljava/util/function/Function;Ljava/util/Comparator;)Ljava/util/Comparator; A: $9
function comparingDouble(keyExtractor : JToDoubleFunction) : JComparator; cdecl;// (Ljava/util/function/ToDoubleFunction;)Ljava/util/Comparator; A: $9
function comparingInt(keyExtractor : JToIntFunction) : JComparator; cdecl; // (Ljava/util/function/ToIntFunction;)Ljava/util/Comparator; A: $9
function comparingLong(keyExtractor : JToLongFunction) : JComparator; cdecl;// (Ljava/util/function/ToLongFunction;)Ljava/util/Comparator; A: $9
function equals(JObjectparam0 : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $401
function naturalOrder : JComparator; cdecl; // ()Ljava/util/Comparator; A: $9
function nullsFirst(comparator : JComparator) : JComparator; cdecl; // (Ljava/util/Comparator;)Ljava/util/Comparator; A: $9
function nullsLast(comparator : JComparator) : JComparator; cdecl; // (Ljava/util/Comparator;)Ljava/util/Comparator; A: $9
function reverseOrder : JComparator; cdecl; // ()Ljava/util/Comparator; A: $9
function reversed : JComparator; cdecl; // ()Ljava/util/Comparator; A: $1
function thenComparing(keyExtractor : JFunction) : JComparator; cdecl; overload;// (Ljava/util/function/Function;)Ljava/util/Comparator; A: $1
function thenComparing(keyExtractor : JFunction; keyComparator : JComparator) : JComparator; cdecl; overload;// (Ljava/util/function/Function;Ljava/util/Comparator;)Ljava/util/Comparator; A: $1
function thenComparing(other : JComparator) : JComparator; cdecl; overload; // (Ljava/util/Comparator;)Ljava/util/Comparator; A: $1
function thenComparingDouble(keyExtractor : JToDoubleFunction) : JComparator; cdecl;// (Ljava/util/function/ToDoubleFunction;)Ljava/util/Comparator; A: $1
function thenComparingInt(keyExtractor : JToIntFunction) : JComparator; cdecl;// (Ljava/util/function/ToIntFunction;)Ljava/util/Comparator; A: $1
function thenComparingLong(keyExtractor : JToLongFunction) : JComparator; cdecl;// (Ljava/util/function/ToLongFunction;)Ljava/util/Comparator; A: $1
end;
[JavaSignature('java/util/Comparator')]
JComparator = interface(JObject)
['{F8D0F368-D642-4FB1-B01A-5D5A98C25844}']
function compare(JObjectparam0 : JObject; JObjectparam1 : JObject) : Integer; cdecl;// (Ljava/lang/Object;Ljava/lang/Object;)I A: $401
function equals(JObjectparam0 : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $401
function reversed : JComparator; cdecl; // ()Ljava/util/Comparator; A: $1
function thenComparing(keyExtractor : JFunction) : JComparator; cdecl; overload;// (Ljava/util/function/Function;)Ljava/util/Comparator; A: $1
function thenComparing(keyExtractor : JFunction; keyComparator : JComparator) : JComparator; cdecl; overload;// (Ljava/util/function/Function;Ljava/util/Comparator;)Ljava/util/Comparator; A: $1
function thenComparing(other : JComparator) : JComparator; cdecl; overload; // (Ljava/util/Comparator;)Ljava/util/Comparator; A: $1
function thenComparingDouble(keyExtractor : JToDoubleFunction) : JComparator; cdecl;// (Ljava/util/function/ToDoubleFunction;)Ljava/util/Comparator; A: $1
function thenComparingInt(keyExtractor : JToIntFunction) : JComparator; cdecl;// (Ljava/util/function/ToIntFunction;)Ljava/util/Comparator; A: $1
function thenComparingLong(keyExtractor : JToLongFunction) : JComparator; cdecl;// (Ljava/util/function/ToLongFunction;)Ljava/util/Comparator; A: $1
end;
TJComparator = class(TJavaGenericImport<JComparatorClass, JComparator>)
end;
implementation
end.
|
unit PestGlobalComparisonScriptWriterUnit;
interface
uses
CustomModflowWriterUnit, System.SysUtils;
type
TGlobalComparisonScriptWriter = class(TCustomFileWriter)
protected
class function Extension: string; override;
public
procedure WriteFile(const AFileName: string);
end;
resourcestring
StrTheObservationComp = 'The observation comparison item "%s" could not be' +
' exported. Check that it is defined correctly for this model.';
StrUnableToExportObs = 'Unable to export observations';
implementation
uses
PestObsUnit, ObservationComparisonsUnit, ScreenObjectUnit, GoPhastTypes,
frmErrorsAndWarningsUnit, ModelMuseUtilities;
{ TGlobalComparisonScriptWriter }
class function TGlobalComparisonScriptWriter.Extension: string;
begin
result := '.der_script';
end;
procedure TGlobalComparisonScriptWriter.WriteFile(const AFileName: string);
var
ScriptFileName: string;
ComparisonIndex: Integer;
GloCompItem: TGlobalObsComparisonItem;
FObsItemDictionary: TObsItemDictionary;
ObsItem: TCustomObservationItem;
PriorItem1: TCustomObservationItem;
PriorItem2: TCustomObservationItem;
ErrorMessage: string;
ObservationList: TObservationList;
ItemIndex: Integer;
function GetObName(ObjectIndex: Integer; Obs: TCustomObservationItem): string;
begin
Result := PrefixedObsName('Der', ObjectIndex, Obs);
end;
begin
{$IFNDEF PEST}
Exit;
{$ENDIF}
frmErrorsAndWarnings.RemoveWarningGroup(Model, StrUnableToExportObs);
if Model.ModflowGlobalObservationComparisons.Count = 0 then
begin
Exit;
end;
ScriptFileName := FileName(AFileName);
ObservationList := TObservationList.Create;
FObsItemDictionary := TObsItemDictionary.Create;
try
Model.FillObsItemList(ObservationList);
if ObservationList.Count = 0 then
begin
Exit;
end;
for ItemIndex := 0 to ObservationList.Count - 1 do
begin
ObsItem := ObservationList[ItemIndex];
FObsItemDictionary.Add(ObsItem.GUID, ObsItem);
end;
// FInputFileName := ScriptFileName;
OpenFile(ScriptFileName);
try
WriteString('BEGIN DERIVED_OBSERVATIONS');
NewLine;
WriteString(' # ');
WriteString('Global observation comparisons');
NewLine;
for ComparisonIndex := 0 to Model.ModflowGlobalObservationComparisons.Count - 1 do
begin
GloCompItem := Model.ModflowGlobalObservationComparisons[ComparisonIndex];
if FObsItemDictionary.TryGetValue(GloCompItem.GUID1, PriorItem1)
and FObsItemDictionary.TryGetValue(GloCompItem.GUID2, PriorItem2) then
begin
WriteString(' DIFFERENCE ');
WriteString(GetObName(ComparisonIndex, GloCompItem));
WriteString(' ');
WriteString(PriorItem1.ExportedName);
WriteString(' ');
WriteString(PriorItem2.ExportedName);
WriteFloat(GloCompItem.ObservedValue);
WriteFloat(GloCompItem.Weight);
if GloCompItem.Print then
begin
WriteString(' PRINT');
end;
NewLine;
end
else
begin
ErrorMessage := Format(StrTheObservationComp, [GloCompItem.Name]);
frmErrorsAndWarnings.AddWarning(Model, StrUnableToExportObs, ErrorMessage)
end;
end;
WriteString('END DERIVED_OBSERVATIONS');
finally
CloseFile;
end;
finally
FObsItemDictionary.Free;
ObservationList.Free;
end;
end;
end.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, System.StrUtils,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, System.Beacon,
System.Beacon.Components, FMX.Colors, FMX.ScrollBox, FMX.Memo;
type
TMainForm = class(TForm)
ToolBar1: TToolBar;
BeaconArea: TBeacon;
butStart: TButton;
butStop: TButton;
TimerArea: TTimer;
panArea: TColorBox;
labelArea: TLabel;
memArea: TMemo;
procedure butStartClick(Sender: TObject);
procedure butStopClick(Sender: TObject);
procedure BeaconAreaBeaconProximity(const Sender: TObject;
const ABeacon: IBeacon; Proximity: TBeaconProximity);
procedure TimerAreaTimer(Sender: TObject);
procedure BeaconAreaBeaconEnter(const Sender: TObject;
const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList);
private
{ Private declarations }
fBeacon: IBeacon;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
const
aBeaconList: array of string = ['30784', '29597', '30708', '29788', '1'];
implementation
{$R *.fmx}
{$R *.iPad.fmx IOS}
{$R *.NmXhdpiPh.fmx ANDROID}
procedure TMainForm.BeaconAreaBeaconEnter(const Sender: TObject;
const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList);
begin
if ABeacon <> nil then;
end;
procedure TMainForm.BeaconAreaBeaconProximity(const Sender: TObject;
const ABeacon: IBeacon; Proximity: TBeaconProximity);
var sMinor: string;
begin
if (Proximity = TBeaconProximity.Near) then
begin
sMinor := ABeacon.Minor.ToString;
if MatchStr(sMinor, aBeaconList) then
fBeacon := ABeacon;
end
else fBeacon := nil;
end;
procedure TMainForm.butStartClick(Sender: TObject);
begin
BeaconArea.StartScan;
TimerArea.Enabled := True;
butStart.Enabled := not TimerArea.Enabled;
butStop.Enabled := TimerArea.Enabled;
end;
procedure TMainForm.butStopClick(Sender: TObject);
begin
BeaconArea.StopScan;
TimerArea.Enabled := False;
butStart.Enabled := not TimerArea.Enabled;
butStop.Enabled := TimerArea.Enabled;
end;
procedure TMainForm.TimerAreaTimer(Sender: TObject);
begin
if fBeacon <> nil then
begin
memArea.Text := 'Beacon Details: ' + fBeacon.GUID.ToString + ' Major:' +
fBeacon.Major.ToString + ' Minor:' + fBeacon.Minor.ToString +
' Distance: ' + fBeacon.Distance.ToString + 'm';
labelArea.Text := 'Area #' + fBeacon.Minor.ToString;
panArea.Color := ($FF000000 or TAlphaColor(random($FFFFFF)));;
end;
end;
end.
|
{
This demo application accompanies the article
"How to call Delphi code from scripts running in a TWebBrowser" at
http://www.delphidabbler.com/articles?article=22.
This unit defines the IDocHostUIHandler implementation that provides the
external object to the TWebBrowser.
This code is copyright (c) P D Johnson (www.delphidabbler.com), 2005-2006.
v1.0 of 2005/05/09 - original version named UExternalUIHandler.pas
v2.0 of 2006/02/11 - revised to descend from new TNulWBContainer class
}
{$A8,B-,C+,D+,E-,F-,G+,H+,I+,J-,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
unit uWebJSExternalContainer;
interface
uses
// Delphi
ActiveX,
SHDocVw,
// Project
WebJS_TLB,
IntfDocHostUIHandler,
uWebNullContainer,
uWebJSExternal;
type
{
TExternalContainer:
UI handler that extends browser's external object.
}
TWebJSExternalContainer = class(TWebNullWBContainer, IDocHostUIHandler, IOleClientSite)
private
FExternalObj: IDispatch; // external object implementation
protected
{ Re-implemented IDocHostUIHandler method }
function GetExternal(out ppDispatch: IDispatch): HResult; stdcall;
public
constructor Create(const HostedBrowser: TWebBrowser; ExternalObject: IWebJSExternal);
end;
implementation
{ TExternalContainer }
constructor TWebJSExternalContainer.Create(const HostedBrowser: TWebBrowser; ExternalObject: IWebJSExternal);
begin
inherited Create(HostedBrowser);
FExternalObj := TWebJSExternal.Create(ExternalObject);
end;
function TWebJSExternalContainer.GetExternal(out ppDispatch: IDispatch): HResult;
begin
ppDispatch := FExternalObj;
Result := S_OK; // indicates we've provided script
end;
end.
|
unit GCDOpTest;
interface
uses
DUnitX.TestFramework,
uIntX;
type
[TestFixture]
TGCDOpTest = class(TObject)
public
[Test]
procedure GCDIntXBothPositive();
[Test]
procedure GCDIntXBothNegative();
[Test]
procedure GCDIntXBothSigns();
end;
implementation
procedure TGCDOpTest.GCDIntXBothPositive;
var
res: TIntX;
begin
res := TIntX.GCD(4, 6);
Assert.IsTrue(res = 2);
res := TIntX.GCD(24, 18);
Assert.IsTrue(res = 6);
res := TIntX.GCD(234, 100);
Assert.IsTrue(res = 2);
res := TIntX.GCD(235, 100);
Assert.IsTrue(res = 5);
end;
procedure TGCDOpTest.GCDIntXBothNegative;
var
res: TIntX;
begin
res := TIntX.GCD(-4, -6);
Assert.IsTrue(res = 2);
res := TIntX.GCD(-24, -18);
Assert.IsTrue(res = 6);
res := TIntX.GCD(-234, -100);
Assert.IsTrue(res = 2);
end;
procedure TGCDOpTest.GCDIntXBothSigns;
var
res: TIntX;
begin
res := TIntX.GCD(-4, +6);
Assert.IsTrue(res = 2);
res := TIntX.GCD(+24, -18);
Assert.IsTrue(res = 6);
res := TIntX.GCD(-234, +100);
Assert.IsTrue(res = 2);
end;
initialization
TDUnitX.RegisterTestFixture(TGCDOpTest);
end.
|
unit uFile;
interface
type
IFile = interface
function Drive: string;
function Path: string;
function FileName: string;
function Ext: string;
function Text: string;
end;
function NewFile(FilePath: string): IFile;
type
TFileAccess = class(TInterfacedObject, IFile)
function Drive: string;
function Path: string;
function Ext: string;
function FileName: string;
function Path_Relative: string;
function Path_Absolute: string;
function Text: string;
function Lines: TArray<string>;
constructor Create(FileName: string);
private
FFullFilePath: string;
end;
//------------------------------------------------------------------------------
function ExtractFileNameOnly(FileName: string): string;
implementation
uses
SysUtils, IOUtils;
function NewFile(FilePath: string): IFile;
begin
Result := TFileAccess.Create(FilePath);
end;
{ TFileAccess }
function TFileAccess.Text: string;
begin
Result := TFile.ReadAllText(FFullFilePath);
end;
function TFileAccess.Lines: TArray<string>;
begin
Result := TFile.ReadAllLines(FFullFilePath);
end;
constructor TFileAccess.Create(FileName: string);
begin
if TFile.Exists(FileName) then
FFullFilePath := FileName
else
raise Exception.Create('TFileAccess: File Does Not Exist: ' + FileName);
end;
function TFileAccess.Drive: string;
begin
Result := ExtractFileDrive(FFullFilePath);
end;
function TFileAccess.Ext: string;
begin
Result := ExtractFileExt(FFullFilePath);
end;
function TFileAccess.FileName: string;
begin
Result := ExtractFileName(FFullFilePath);
end;
function TFileAccess.Path_Absolute: string;
begin
Result := FFullFilePath;
end;
function TFileAccess.Path_Relative: string;
begin
Result := FFullFilePath;
end;
function TFileAccess.Path: string;
begin
Result := FFullFilePath;
end;
//------------------------------------------------------------------------------
function ExtractFileNameOnly(FileName: string): string;
begin
Result := ExtractFileName(ChangeFileExt(FileName, ''));
end;
end.
|
{ ****************************************************************************** }
{ * fast StreamQuery,writen by QQ 600585@qq.com * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
(*
update history
*)
unit ObjectDataHashItem;
{$INCLUDE zDefine.inc}
interface
uses SysUtils, ObjectDataManager, ItemStream, CoreClasses, PascalStrings, ListEngine;
type
TObjectDataHashItem = class;
THashItemData = record
qHash: THash;
LowerCaseName, OriginName: SystemString;
stream: TItemStream;
ItemHnd: TItemHandle;
CallCount: Integer;
ForceFreeCustomObject: Boolean;
CustomObject: TCoreClassObject;
ID: Integer;
Owner: TObjectDataHashItem;
end;
PHashItemData = ^THashItemData;
TObjectDataHashItem = class(TCoreClassObject)
protected
FCounter: Boolean;
FCount: Integer;
FName: SystemString;
FDescription: SystemString;
FDBEngine: TObjectDataManager;
FFieldPos: Int64;
FAryList: array of TCoreClassList;
FData: Pointer;
function GetListTable(hash: THash; AutoCreate: Boolean): TCoreClassList;
procedure RefreshDBLst(DBEngine_: TObjectDataManager; var FieldPos_: Int64);
procedure SetHashBlockCount(cnt: Integer);
function GetNames(Name_: SystemString): PHashItemData;
public
constructor Create(DBEngine_: TObjectDataManager; FieldPos_: Int64);
destructor Destroy; override;
procedure Clear;
procedure Refresh;
procedure GetOriginNameListFromFilter(Filter_: SystemString; Output_: TCoreClassStrings);
procedure GetListFromFilter(Filter_: SystemString; Output_: TCoreClassList);
procedure GetOriginNameList(Output_: TCoreClassStrings); overload;
procedure GetOriginNameList(Output_: TListString); overload;
procedure GetList(Output_: TCoreClassList);
function Find(Name_: SystemString): PHashItemData;
function Exists(Name_: SystemString): Boolean;
property Names[Name_: SystemString]: PHashItemData read GetNames; default;
property DBEngine: TObjectDataManager read FDBEngine;
property FieldPos: Int64 read FFieldPos;
property Name: SystemString read FName write FName;
property Description: SystemString read FDescription write FDescription;
property Counter: Boolean read FCounter write FCounter;
property Count: Integer read FCount;
property Data: Pointer read FData write FData;
end;
implementation
uses UnicodeMixedLib;
function TObjectDataHashItem.GetListTable(hash: THash; AutoCreate: Boolean): TCoreClassList;
var
idx: Integer;
begin
idx := hashMod(hash, length(FAryList));
if (AutoCreate) and (FAryList[idx] = nil) then
FAryList[idx] := TCoreClassList.Create;
Result := FAryList[idx];
end;
procedure TObjectDataHashItem.RefreshDBLst(DBEngine_: TObjectDataManager; var FieldPos_: Int64);
var
ItemSearchHnd: TItemSearch;
ICnt: Integer;
procedure AddLstItem(_ItemPos: Int64);
var
newhash: THash;
p: PHashItemData;
idxLst: TCoreClassList;
lName: SystemString;
ItemHnd: TItemHandle;
begin
if FDBEngine.ItemFastOpen(_ItemPos, ItemHnd) then
if umlGetLength(ItemHnd.Name) > 0 then
begin
lName := ItemHnd.Name.LowerText;
newhash := MakeHashS(@lName);
idxLst := GetListTable(newhash, True);
new(p);
p^.qHash := newhash;
p^.LowerCaseName := lName;
p^.OriginName := ItemHnd.Name;
p^.stream := nil;
p^.ItemHnd := ItemHnd;
p^.CallCount := 0;
p^.ForceFreeCustomObject := False;
p^.CustomObject := nil;
p^.ID := ICnt;
p^.Owner := Self;
idxLst.Add(p);
inc(ICnt);
end;
end;
begin
FDBEngine := DBEngine_;
FFieldPos := FieldPos_;
FCount := 0;
ICnt := 0;
if FDBEngine.ItemFastFindFirst(FFieldPos, '*', ItemSearchHnd) then
begin
repeat
inc(FCount);
AddLstItem(ItemSearchHnd.HeaderPOS);
until not FDBEngine.ItemFastFindNext(ItemSearchHnd);
end;
end;
procedure TObjectDataHashItem.SetHashBlockCount(cnt: Integer);
var
i: Integer;
begin
Clear;
SetLength(FAryList, cnt);
for i := low(FAryList) to high(FAryList) do
FAryList[i] := nil;
end;
constructor TObjectDataHashItem.Create(DBEngine_: TObjectDataManager; FieldPos_: Int64);
begin
inherited Create;
FCounter := True;
FCount := 0;
FData := nil;
SetLength(FAryList, 0);
SetHashBlockCount(10000);
RefreshDBLst(DBEngine_, FieldPos_);
end;
destructor TObjectDataHashItem.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TObjectDataHashItem.Clear;
var
i: Integer;
j: Integer;
begin
FCount := 0;
if length(FAryList) = 0 then
Exit;
for i := low(FAryList) to high(FAryList) do
begin
if FAryList[i] <> nil then
begin
with FAryList[i] do
begin
if Count > 0 then
begin
for j := 0 to Count - 1 do
begin
with PHashItemData(Items[j])^ do
begin
if stream <> nil then
begin
DisposeObject(stream);
if (ForceFreeCustomObject) and (CustomObject <> nil) then
begin
try
DisposeObject(CustomObject);
CustomObject := nil;
except
end;
end;
end;
end;
try
Dispose(PHashItemData(Items[j]));
except
end;
end;
end;
end;
DisposeObject(FAryList[i]);
FAryList[i] := nil;
end;
end;
end;
procedure TObjectDataHashItem.Refresh;
begin
Clear;
RefreshDBLst(FDBEngine, FFieldPos);
end;
procedure TObjectDataHashItem.GetOriginNameListFromFilter(Filter_: SystemString; Output_: TCoreClassStrings);
var
i: Integer;
L: TCoreClassList;
p: PHashItemData;
begin
L := TCoreClassList.Create;
GetList(L);
Output_.Clear;
if L.Count > 0 then
for i := 0 to L.Count - 1 do
begin
p := PHashItemData(L[i]);
if umlMultipleMatch(Filter_, p^.OriginName) then
Output_.Add(p^.OriginName);
end;
DisposeObject(L);
end;
procedure TObjectDataHashItem.GetListFromFilter(Filter_: SystemString; Output_: TCoreClassList);
var
i: Integer;
L: TCoreClassList;
p: PHashItemData;
begin
L := TCoreClassList.Create;
GetList(L);
Output_.Clear;
if L.Count > 0 then
for i := 0 to L.Count - 1 do
begin
p := PHashItemData(L[i]);
if umlMultipleMatch(Filter_, p^.OriginName) then
Output_.Add(p);
end;
DisposeObject(L);
end;
procedure TObjectDataHashItem.GetOriginNameList(Output_: TCoreClassStrings);
var
i: Integer;
L: TCoreClassList;
begin
L := TCoreClassList.Create;
GetList(L);
Output_.Clear;
if L.Count > 0 then
for i := 0 to L.Count - 1 do
Output_.Add(PHashItemData(L[i])^.OriginName);
DisposeObject(L);
end;
procedure TObjectDataHashItem.GetOriginNameList(Output_: TListString);
var
i: Integer;
L: TCoreClassList;
begin
L := TCoreClassList.Create;
GetList(L);
Output_.Clear;
if L.Count > 0 then
for i := 0 to L.Count - 1 do
Output_.Add(PHashItemData(L[i])^.OriginName);
DisposeObject(L);
end;
procedure TObjectDataHashItem.GetList(Output_: TCoreClassList);
function ListSortCompare(Item1, Item2: Pointer): Integer;
function Compare_(const a, b: Int64): Integer;
begin
if a = b then
Result := 0
else if a < b then
Result := -1
else
Result := 1;
end;
begin
Result := Compare_(PHashItemData(Item1)^.ID, PHashItemData(Item2)^.ID);
end;
procedure QuickSortList(var SortList: TCoreClassPointerList; L, r: Integer);
var
i, j: Integer;
p, t: Pointer;
begin
repeat
i := L;
j := r;
p := SortList[(L + r) shr 1];
repeat
while ListSortCompare(SortList[i], p) < 0 do
inc(i);
while ListSortCompare(SortList[j], p) > 0 do
dec(j);
if i <= j then
begin
if i <> j then
begin
t := SortList[i];
SortList[i] := SortList[j];
SortList[j] := t;
end;
inc(i);
dec(j);
end;
until i > j;
if L < j then
QuickSortList(SortList, L, j);
L := i;
until i >= r;
end;
var
i, j: Integer;
begin
Output_.Clear;
if Count > 0 then
begin
Output_.Capacity := Count;
for i := low(FAryList) to high(FAryList) do
begin
if FAryList[i] <> nil then
begin
with FAryList[i] do
if Count > 0 then
begin
for j := 0 to Count - 1 do
with PHashItemData(Items[j])^ do
begin
if stream = nil then
stream := TItemStream.Create(FDBEngine, ItemHnd)
else
stream.SeekStart;
if FCounter then
inc(CallCount);
Output_.Add(Items[j]);
end;
end;
end;
end;
if Output_.Count > 1 then
QuickSortList(Output_.ListData^, 0, Output_.Count - 1);
end;
end;
function TObjectDataHashItem.Find(Name_: SystemString): PHashItemData;
var
i, j: Integer;
begin
Result := nil;
for i := low(FAryList) to high(FAryList) do
begin
if FAryList[i] <> nil then
begin
with FAryList[i] do
if Count > 0 then
begin
for j := 0 to Count - 1 do
begin
if umlMultipleMatch(True, Name_, PHashItemData(Items[j])^.OriginName) then
begin
Result := Items[j];
if Result^.stream = nil then
Result^.stream := TItemStream.Create(FDBEngine, Result^.ItemHnd)
else
Result^.stream.SeekStart;
if FCounter then
inc(Result^.CallCount);
Exit;
end;
end;
end;
end;
end;
end;
function TObjectDataHashItem.Exists(Name_: SystemString): Boolean;
var
newhash: THash;
i: Integer;
idxLst: TCoreClassList;
lName: SystemString;
begin
Result := False;
if umlGetLength(Name_) > 0 then
begin
lName := LowerCase(Name_);
newhash := MakeHashS(@lName);
idxLst := GetListTable(newhash, False);
if idxLst <> nil then
if idxLst.Count > 0 then
for i := 0 to idxLst.Count - 1 do
if (newhash = PHashItemData(idxLst[i])^.qHash) and (PHashItemData(idxLst[i])^.LowerCaseName = lName) then
Exit(True);
end;
end;
function TObjectDataHashItem.GetNames(Name_: SystemString): PHashItemData;
var
newhash: THash;
i: Integer;
idxLst: TCoreClassList;
lName: SystemString;
begin
Result := nil;
if umlGetLength(Name_) > 0 then
begin
lName := LowerCase(Name_);
newhash := MakeHashS(@lName);
idxLst := GetListTable(newhash, False);
if idxLst <> nil then
if idxLst.Count > 0 then
for i := 0 to idxLst.Count - 1 do
begin
if (newhash = PHashItemData(idxLst[i])^.qHash) and (PHashItemData(idxLst[i])^.LowerCaseName = lName) then
begin
Result := idxLst[i];
if Result^.stream = nil then
Result^.stream := TItemStream.Create(FDBEngine, Result^.ItemHnd)
else
Result^.stream.SeekStart;
if FCounter then
inc(Result^.CallCount);
Exit;
end;
end;
end;
end;
end.
|
//------------------------------------------------------------------------------
// File: dxva2Trace.h
// Desc: DirectX Video Acceleration 2 header file for ETW data
// Copyright (c) 1999 - 2005, Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
unit Win32.DXVA2Trace;
// Updated to SDK 10.0.17763.0
// (c) Translation to Pascal by Norbert Sonnleitner
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Windows, Classes, SysUtils,
CMC.EVNTrace;
const
DXVA2Trace_Control: TGUID = '{a0386e75-f70c-464c-a9ce-33c44e091623}';
DXVA2Trace_DecodeDevCreated: TGUID = '{b4de17a1-c5b2-44fe-86d5-d97a648114ff}';
DXVA2Trace_DecodeDevDestroyed: TGUID = '{853ebdf2-4160-421d-8893-63dcea4f18bb}';
DXVA2Trace_DecodeDevBeginFrame: TGUID = '{9fd1acf6-44cb-4637-bc62-2c11a9608f90}';
DXVA2Trace_DecodeDevExecute: TGUID = '{850aeb4c-d19a-4609-b3b4-bcbf0e22121e}';
DXVA2Trace_DecodeDevGetBuffer: TGUID = '{57b128fb-72cb-4137-a575-d91fa3160897}';
DXVA2Trace_DecodeDevEndFrame: TGUID = '{9fb3cb33-47dc-4899-98c8-c0c6cd7cd3cb}';
DXVA2Trace_VideoProcessDevCreated: TGUID = '{895508c6-540d-4c87-98f8-8dcbf2dabb2a}';
DXVA2Trace_VideoProcessDevDestroyed: TGUID = '{f97f30b1-fb49-42c7-8ee8-88bdfa92d4e2}';
DXVA2Trace_VideoProcessBlt: TGUID = '{69089cc0-71ab-42d0-953a-2887bf05a8af}';
type
// -------------------------------------------------------------------------
// DXVA2 Video Decoder ETW definitions
// There are event for:
// Device creation
// Device destruction
// When the device is being used there are events for:
// Begin frame
// Begin execute
// End execute
// End frame
// -------------------------------------------------------------------------
TDXVA2Trace_DecodeDevCreatedData = record
{$IFNDEF DXVA2Trace_PostProcessing}
wmiHeader: TEVENT_TRACE_HEADER;
{$ENDIF}
pObject: ULONGLONG;
pD3DDevice: ULONGLONG;
DeviceGuid: TGUID;
Width: ULONG;
Height: ULONG;
Enter: boolean;
end;
TDXVA2Trace_DecodeDeviceData = record
{$IFNDEF DXVA2Trace_PostProcessing}
wmiHeader: TEVENT_TRACE_HEADER;
{$ENDIF}
pObject: ULONGLONG;
Enter: boolean;
end;
TDXVA2Trace_DecodeDevDestroyedData = TDXVA2Trace_DecodeDeviceData;
TDXVA2Trace_DecodeDevExecuteData = TDXVA2Trace_DecodeDeviceData;
TDXVA2Trace_DecodeDevEndFrameData = TDXVA2Trace_DecodeDeviceData;
TDXVA2Trace_DecodeDevBeginFrameData = record
{$IFNDEF DXVA2Trace_PostProcessing}
wmiHeader: TEVENT_TRACE_HEADER;
{$ENDIF}
pObject: ULONGLONG;
pRenderTarget: ULONGLONG;
Enter: boolean;
end;
TDXVA2Trace_DecodeDevGetBufferData = record
{$IFNDEF DXVA2Trace_PostProcessing}
wmiHeader: TEVENT_TRACE_HEADER;
{$ENDIF}
pObject: ULONGLONG;
BufferType: UINT;
Enter: boolean;
end;
// -------------------------------------------------------------------------
// DXVA2 Video Processing ETW definitions
// There are event for:
// Device creation
// Device destruction
// When the device is being used there are events for:
// Begin VideoProcessBlt
// End VideoProcessBlt
// -------------------------------------------------------------------------
TDXVA2Trace_VideoProcessDevCreatedData = record
{$IFNDEF DXVA2Trace_PostProcessing}
wmiHeader: TEVENT_TRACE_HEADER;
{$ENDIF}
pObject: ULONGLONG;
pD3DDevice: ULONGLONG;
DeviceGuid: TGUID;
RTFourCC: ULONG;
Width: ULONG;
Height: ULONG;
Enter: boolean;
end;
TDXVA2Trace_VideoProcessDeviceData = record
{$IFNDEF DXVA2Trace_PostProcessing}
wmiHeader: TEVENT_TRACE_HEADER;
{$ENDIF}
pObject: ULONGLONG;
Enter: boolean;
end;
TDXVA2Trace_VideoProcessDevDestroyedData = TDXVA2Trace_VideoProcessDeviceData;
TDXVA2Trace_VideoProcessBltEndData = TDXVA2Trace_VideoProcessDeviceData;
TDXVA2TraceVideoProcessBltData = record
{$IFNDEF DXVA2Trace_PostProcessing}
wmiHeader: TEVENT_TRACE_HEADER;
{$ENDIF}
pObject: ULONGLONG;
pRenderTarget: ULONGLONG;
TargetFrameTime: ULONGLONG;
TargetRect: TRECT;
Enter: boolean;
end;
TDXVA2TraceVideoProcessBltDataData = TDXVA2TraceVideoProcessBltData;
implementation
end.
|
unit GLInertias;
interface
uses
System.SysUtils,
System.Classes,
Vcl.Dialogs,
GLScene,
GLBaseClasses,
GLVectorGeometry,
GLXCollection,
GLVectorTypes,
GLPhysics,
GLCoordinates,
GLBehaviours
{, GLForceFields};
type
// TGLRigidBody=class;
TGLParticleInertia = class(TGLBaseInertia)
// modified from TGLBInertia by Dan Bartlett
private
FMass: Single;
FTranslationSpeed: TGLCoordinates;
FTranslationDamping: TGLDamping;
protected
function CalcLinearPositionDot(): TAffineVector;
function CalcLinearMomentumDot(): TAffineVector;
procedure SetTranslationSpeed(const val: TGLCoordinates);
procedure SetTranslationDamping(const val: TGLDamping);
public
fForce: TAffineVector;
LinearPosition: TAffineVector;
LinearMomentum: TAffineVector;
procedure StateToArray(var StateArray: TStateArray; StatePos: Integer); override;
procedure ArrayToState( { var } StateArray: TStateArray; StatePos: Integer); override;
procedure CalcStateDot(var StateArray: TStateArray; StatePos: Integer); override;
procedure RemoveForces(); override;
procedure CalculateForceFieldForce(ForceFieldEmitter
: TGLBaseForceFieldEmitter); override;
procedure CalcAuxiliary(); override;
procedure SetUpStartingState(); override;
function CalculateKE(): Real; override;
function CalculatePE(): Real; override;
procedure SetForce(x, y, z: Real); virtual;
procedure ApplyForce(x, y, z: Real); overload; virtual;
procedure ApplyForce(Force: TAffineVector); overload; virtual;
procedure ApplyForce(pos, Force: TAffineVector); overload; virtual;
procedure ApplyLocalForce(pos, Force: TAffineVector); virtual;
procedure ApplyImpulse(j, x, y, z: Real); overload; virtual;
procedure ApplyImpulse(j: Single; normal: TAffineVector); overload; virtual;
procedure ApplyDamping(damping: TGLDamping); virtual;
constructor Create(aOwner: TXCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure WriteToFiler(writer: TWriter); override;
procedure ReadFromFiler(reader: TReader); override;
class function FriendlyName: String; override;
class function FriendlyDescription: String; override;
class function UniqueItem: Boolean; override;
{ Inverts the translation vector }
procedure MirrorTranslation;
{ Bounce speed as if hitting a surface.
restitution is the coefficient of restituted energy (1=no energy loss,
0=no bounce). The normal is NOT assumed to be normalized. }
procedure SurfaceBounce(const surfaceNormal: TVector; restitution: Single);
published
property Mass: Single read FMass write FMass;
property TranslationSpeed: TGLCoordinates read FTranslationSpeed
write SetTranslationSpeed;
{ Enable/Disable damping (damping has a high cpu-cycle cost).
Damping is enabled by default. }
// property DampingEnabled : Boolean read FDampingEnabled write FDampingEnabled;
{ Damping applied to translation speed.<br>
Note that it is not "exactly" applied, ie. if damping would stop
your object after 0.5 time unit, and your progression steps are
of 1 time unit, there will be an integration error of 0.5 time unit. }
property TranslationDamping: TGLDamping read FTranslationDamping
write SetTranslationDamping;
end;
TGLRigidBodyInertia = class;
(* Stores Inertia Tensor for TGLRigidBodyInertia model *)
TGLInertiaTensor = class(TGLUpdateAbleObject)
private
fm11, fm12, fm13, fm21, fm22, fm23, fm31, fm32, fm33: Single;
public
constructor Create(aOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure WriteToFiler(writer: TWriter);
procedure ReadFromFiler(reader: TReader);
published
property m11: Single read fm11 write fm11;
property m12: Single read fm12 write fm12;
property m13: Single read fm13 write fm13;
property m21: Single read fm21 write fm21;
property m22: Single read fm22 write fm22;
property m23: Single read fm23 write fm23;
property m31: Single read fm31 write fm31;
property m32: Single read fm32 write fm32;
property m33: Single read fm33 write fm33;
end;
{ A more complex model than TGLBInertia for Inertia
By Dan Bartlett (danbartlett@freeuk.com) }
TGLRigidBodyInertia = class(TGLParticleInertia)
private
fDensity: Real;
fBodyInertiaTensor: TAffineMAtrix;
fBodyInverseInertiaTensor: TAffineMAtrix;
fInertiaTensor: TGLInertiaTensor;
InverseInertiaTensor: TAffineMAtrix;
// LinearVelocity:TAffineVector;
fRotationSpeed: TGLCoordinates;
// AngularVelocity:TAffineVector; //rotation about axis, magnitude=speed
// damping properties
FRotationDamping: TGLDamping;
{ Protected Declarations }
protected
// torques
fTorque: TAffineVector;
procedure SetLinearDamping(const val: TGLDamping);
procedure SetAngularDamping(const val: TGLDamping);
public
AngularOrientation: TQuaternion; // As Quat will help improve accuracy
R: TMatrix3f; // corresponds to AngularOrientation
AngularMomentum: TAffineVector;
procedure StateToArray(var StateArray: TStateArray;
StatePos: Integer); override;
procedure ArrayToState( { var } StateArray: TStateArray;
StatePos: Integer); override;
procedure CalcStateDot(var StateArray: TStateArray;
StatePos: Integer); override;
procedure ApplyImpulse(j, xpos, ypos, zpos, x, y, z: Real); overload;
procedure ApplyImpulse(j: Single; position, normal: TAffineVector);
overload;
procedure ApplyDamping(damping: TGLDamping); override;
// function CalcLinearPositionDot():TAffineVector;
// function CalcLinearMomentumDot():TAffineVector;
function CalcAngularOrientationDot(): TQuaternion;
function CalcAngularVelocityDot(): TAffineVector;
function CalculateKE(): Real; override;
function CalculatePE(): Real; override;
procedure CalcAuxiliary(); override;
procedure SetUpStartingState(); override;
constructor Create(aOwner: TXCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure WriteToFiler(writer: TWriter); override;
procedure ReadFromFiler(reader: TReader); override;
class function FriendlyName: String; override;
class function FriendlyDescription: String; override;
class function UniqueItem: Boolean; override;
// function Star(Vector:TAffineVector):TMatrix;
function QuaternionToString(Quat: TQuaternion): String;
procedure RemoveForces(); override;
procedure SetTorque(x, y, z: Real);
procedure ApplyTorque(x, y, z: Real);
procedure ApplyForce(pos, Force: TAffineVector); override;
procedure ApplyLocalForce(pos, Force: TVector3f); override;
procedure ApplyLocalImpulse(xpos, ypos, zpos, x, y, z: Real);
procedure SetInertiaTensor(newVal: TGLInertiaTensor);
procedure SetRotationSpeed(const val: TGLCoordinates);
procedure SetRotationDamping(const val: TGLDamping);
published
property Density: Real read fDensity write fDensity;
property InertiaTensor: TGLInertiaTensor read fInertiaTensor
write SetInertiaTensor;
property RotationSpeed: TGLCoordinates read fRotationSpeed
write SetRotationSpeed;
property RotationDamping: TGLDamping read FRotationDamping
write SetRotationDamping;
end;
{ Returns or creates the TGLParticleInertia within the given behaviours.
This helper function is convenient way to access a TGLParticleInertia. }
function GetOrCreateParticleInertia(behaviours: TGLBehaviours): TGLParticleInertia; overload;
{ Returns or creates the TGLParticleInertia within the given object's behaviours.
This helper function is convenient way to access a TGLParticleInertia. }
function GetOrCreateParticleInertia(obj: TGLBaseSceneObject): TGLParticleInertia; overload;
{ Returns or creates the TGLRigidBodyInertia within the given behaviours.
This helper function is convenient way to access a TGLRigidBodyInertia. }
function GetOrCreateRigidBodyInertia(behaviours: TGLBehaviours): TGLRigidBodyInertia; overload;
{ Returns or creates the TGLRigidBodyInertia within the given object's behaviours.
This helper function is convenient way to access a TGLRigidBodyInertia. }
function GetOrCreateRigidBodyInertia(obj: TGLBaseSceneObject): TGLRigidBodyInertia; overload;
const
DebugMode = false;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLParticleInertia ------------------
// ------------------
constructor TGLParticleInertia.Create(aOwner: TXCollection);
begin
inherited Create(aOwner);
FMass := 1;
StateSize := 6;
FTranslationSpeed := TGLCoordinates.CreateInitialized(Self, NullHmgVector, csVector);
LinearPosition := OwnerBaseSceneObject.position.AsAffineVector;
LinearMomentum := FTranslationSpeed.AsAffineVector;
FTranslationDamping := TGLDamping.Create(Self);
end;
destructor TGLParticleInertia.Destroy;
begin
FTranslationDamping.Free;
FTranslationSpeed.Free;
inherited Destroy;
end;
procedure TGLParticleInertia.Assign(Source: TPersistent);
begin
if Source.ClassType = Self.ClassType then
begin
FMass := TGLParticleInertia(Source).FMass;
FTranslationSpeed.Assign(TGLParticleInertia(Source).FTranslationSpeed);
LinearPosition := TGLParticleInertia(Source).LinearPosition;
LinearMomentum := TGLParticleInertia(Source).LinearMomentum;
// FDampingEnabled:=TGLInertia(Source).DampingEnabled;
FTranslationDamping.Assign(TGLParticleInertia(Source).TranslationDamping);
// FRotationDamping.Assign(TGLBInertia(Source).RotationDamping);
end;
inherited Assign(Source);
end;
procedure TGLParticleInertia.WriteToFiler(writer: TWriter);
begin
inherited;
with writer do
begin
WriteInteger(0); // Archive Version 0
WriteFloat(FMass);
Write(LinearPosition, SizeOf(LinearPosition));
Write(LinearMomentum, SizeOf(LinearMomentum));
Write(fForce, SizeOf(fForce));
FTranslationSpeed.WriteToFiler(writer);
FTranslationDamping.WriteToFiler(writer);
end;
end;
procedure TGLParticleInertia.ReadFromFiler(reader: TReader);
begin
inherited;
with reader do
begin
ReadInteger; // ignore archiveVersion
FMass := ReadFloat;
Read(LinearPosition, SizeOf(LinearPosition));
Read(LinearMomentum, SizeOf(LinearMomentum));
Read(fForce, SizeOf(fForce));
FTranslationSpeed.ReadFromFiler(reader);
FTranslationDamping.ReadFromFiler(reader);
end;
// Loaded;
SetUpStartingState();
end;
procedure TGLParticleInertia.SetTranslationSpeed(const val: TGLCoordinates);
begin
FTranslationSpeed.Assign(val);
LinearMomentum := VectorScale(FTranslationSpeed.AsAffineVector, FMass);
end;
procedure TGLParticleInertia.SetUpStartingState();
begin
LinearPosition := OwnerBaseSceneObject.position.AsAffineVector;
LinearMomentum := VectorScale(TranslationSpeed.AsAffineVector, Mass);
end;
procedure TGLParticleInertia.CalcAuxiliary( { RBody:TGLRigidBody } );
begin
TranslationSpeed.AsAffineVector := VectorScale(LinearMomentum, 1 / Mass);
// OwnerBaseSceneObject.Matrix:=QuaternionToMatrix(AngularOrientation);
OwnerBaseSceneObject.position.AsAffineVector := LinearPosition; // position
// OwnerBaseSceneObject.position.x:=LinearPosition[0];//position
// OwnerBaseSceneObject.position.y:=LinearPosition[1];
// OwnerBaseSceneObject.position.z:=LinearPosition[2];
end;
procedure TGLParticleInertia.RemoveForces();
begin
fForce := nullVector;
end;
procedure TGLParticleInertia.CalculateForceFieldForce(ForceFieldEmitter
: TGLBaseForceFieldEmitter);
begin
ForceFieldEmitter.CalculateForceField(Self.OwnerBaseSceneObject);
end;
function TGLParticleInertia.CalculateKE(): Real;
begin
Result := 1 / (2 * Mass) * VectorNorm(LinearMomentum);
end;
function TGLParticleInertia.CalculatePE(): Real;
begin
// need to find potentials due to fields acting on body
// may be easier to do via ForceFieldEmitters?
Result := 0;
end;
procedure TGLParticleInertia.SetForce(x, y, z: Real);
begin
fForce.x := x;
fForce.y := y;
fForce.z := z;
end;
procedure TGLParticleInertia.ApplyForce(x, y, z: Real);
begin
fForce.X := fForce.X + x;
fForce.Y := fForce.Y + y;
fForce.Z := fForce.Z + z;
end;
procedure TGLParticleInertia.ApplyForce(Force: TAffineVector);
begin
fForce := VectorAdd(fForce, Force);
end;
procedure TGLParticleInertia.ApplyForce(pos, Force: TAffineVector);
// var
// abspos:TAffineVector;
begin
fForce := VectorAdd(fForce, Force);
// abspos:=VectorTransform(pos,R);
// fTorque:=VectorAdd(fTorque,VectorCrossProduct(abspos,force));
// fForce:=VectorAdd(fForce,force);
end;
procedure TGLParticleInertia.ApplyLocalForce(pos, Force: TAffineVector);
// var
// abspos:TAffineVector;
// absForce:TAffineVector;
begin
// abspos:=VectorTransform(pos,R);
// absForce:=VectorTransform(Force,R);
// fTorque:=VectorAdd(fTorque,VectorCrossProduct(abspos,absforce));
fForce := VectorAdd(fForce, Force);
end;
procedure TGLParticleInertia.ApplyImpulse(j, x, y, z: Real);
begin
// V2 = V1 + (j/M)n
// V2.M = V1.M +j.n
LinearMomentum.X := LinearMomentum.X + j * x;
LinearMomentum.Y := LinearMomentum.Y + j * y;
LinearMomentum.Z := LinearMomentum.Z + j * z;
end;
procedure TGLParticleInertia.ApplyImpulse(j: Single; normal: TAffineVector);
begin
CombineVector(LinearMomentum, normal, j);
end;
procedure TGLParticleInertia.ApplyDamping(damping: TGLDamping);
var
velocity: TAffineVector;
v: Real;
dampingForce: TAffineVector;
begin
velocity := VectorScale(LinearMomentum, 1 / Mass); // v = p/m
// apply force in opposite direction to velocity
v := VectorLength(velocity);
// F = -Normalised(V)*( Constant + (Linear)*(V) + (Quadtratic)*(V)*(V) )
dampingForce := VectorScale(VectorNormalize(velocity),
-(damping.Constant + damping.Linear * v + damping.Quadratic * v * v));
// dampingForce:=VectorScale(VectorNormalize(velocity),-(Damping.Constant+Damping.Linear*v+Damping.Quadratic*v*v));
ApplyForce(dampingForce);
end;
procedure TGLParticleInertia.SetTranslationDamping(const val: TGLDamping);
begin
FTranslationDamping.Assign(val);
end;
class function TGLParticleInertia.FriendlyName: String;
begin
Result := 'Particle Inertia';
end;
class function TGLParticleInertia.FriendlyDescription: String;
begin
Result := 'A simple translation inertia';
end;
class function TGLParticleInertia.UniqueItem: Boolean;
begin
Result := True;
end;
function TGLParticleInertia.CalcLinearPositionDot(): TAffineVector;
begin
Result := VectorScale(LinearMomentum, 1 / FMass);
// Result:=FTranslationSpeed.AsAffineVector;
end;
function TGLParticleInertia.CalcLinearMomentumDot(): TAffineVector;
begin
Result := fForce;
end;
procedure TGLParticleInertia.StateToArray(var StateArray: TStateArray;
StatePos: Integer);
begin
// SetLength(Result,StateSize);
StateArray[StatePos] := LinearPosition.X; // position
StateArray[StatePos + 1] := LinearPosition.Y;
StateArray[StatePos + 2] := LinearPosition.Z;
StateArray[StatePos + 3] := LinearMomentum.X; // momentum
StateArray[StatePos + 4] := LinearMomentum.Y;
StateArray[StatePos + 5] := LinearMomentum.Z;
end;
procedure TGLParticleInertia.ArrayToState(StateArray: TStateArray;
StatePos: Integer);
begin
LinearPosition.X := StateArray[StatePos];
LinearPosition.Y := StateArray[StatePos + 1];
LinearPosition.Z := StateArray[StatePos + 2];
LinearMomentum.X := StateArray[StatePos + 3];
LinearMomentum.Y := StateArray[StatePos + 4];
LinearMomentum.Z := StateArray[StatePos + 5];
// TODO change?
{ OwnerBaseSceneObject.position.x:=StateArray[StatePos];//position
OwnerBaseSceneObject.position.y:=StateArray[StatePos+1];
OwnerBaseSceneObject.position.z:=StateArray[StatePos+2];
FTranslationSpeed.X:=StateArray[StatePos+3]/fMass;//velocity
FTranslationSpeed.Y:=StateArray[StatePos+4]/fMass;
FTranslationSpeed.Z:=StateArray[StatePos+5]/fMass;
}
end;
// CalcStateDot
//
procedure TGLParticleInertia.CalcStateDot(var StateArray: TStateArray;
StatePos: Integer);
var
LinPos, LinMom: TAffineVector;
begin
LinPos := CalcLinearPositionDot();
LinMom := CalcLinearMomentumDot();
StateArray[StatePos] := LinPos.X;
StateArray[StatePos + 1] := LinPos.Y;
StateArray[StatePos + 2] := LinPos.Z;
StateArray[StatePos + 3] := LinMom.X;
StateArray[StatePos + 4] := LinMom.Y;
StateArray[StatePos + 5] := LinMom.Z;
end;
procedure TGLParticleInertia.MirrorTranslation;
begin
FTranslationSpeed.Invert;
end;
procedure TGLParticleInertia.SurfaceBounce(const surfaceNormal: TVector;
restitution: Single);
var
f: Single;
begin
// does the current speed vector comply?
f := VectorDotProduct(FTranslationSpeed.AsVector, surfaceNormal);
if f < 0 then
begin
// remove the non-complying part of the speed vector
FTranslationSpeed.AddScaledVector(-f / VectorNorm(surfaceNormal) *
(1 + restitution), surfaceNormal);
end;
end;
function GetOrCreateParticleInertia(behaviours: TGLBehaviours)
: TGLParticleInertia;
var
i: Integer;
begin
i := behaviours.IndexOfClass(TGLParticleInertia);
if i >= 0 then
Result := TGLParticleInertia(behaviours[i])
else
Result := TGLParticleInertia.Create(behaviours);
end;
function GetOrCreateParticleInertia(obj: TGLBaseSceneObject)
: TGLParticleInertia;
begin
Result := GetOrCreateParticleInertia(obj.behaviours);
end;
// -----------------------------------------------------------------------
// ------------ TGLInertiaTensor
// -----------------------------------------------------------------------
constructor TGLInertiaTensor.Create(aOwner: TPersistent);
begin
inherited Create(aOwner);
fm11 := 1;
fm22 := 1;
fm33 := 1;
end;
destructor TGLInertiaTensor.Destroy;
begin
inherited Destroy;
end;
procedure TGLInertiaTensor.Assign(Source: TPersistent);
begin
inherited;
fm11 := TGLInertiaTensor(Source).fm11;
fm12 := TGLInertiaTensor(Source).fm12;
fm13 := TGLInertiaTensor(Source).fm13;
fm21 := TGLInertiaTensor(Source).fm21;
fm22 := TGLInertiaTensor(Source).fm22;
fm23 := TGLInertiaTensor(Source).fm23;
fm31 := TGLInertiaTensor(Source).fm31;
fm32 := TGLInertiaTensor(Source).fm32;
fm33 := TGLInertiaTensor(Source).fm33;
end;
procedure TGLInertiaTensor.WriteToFiler(writer: TWriter);
begin
inherited;
with writer do
begin
WriteInteger(0); // Archive Version 0
WriteFloat(fm11);
WriteFloat(fm12);
WriteFloat(fm13);
WriteFloat(fm21);
WriteFloat(fm22);
WriteFloat(fm23);
WriteFloat(fm31);
WriteFloat(fm32);
WriteFloat(fm33);
end;
end;
procedure TGLInertiaTensor.ReadFromFiler(reader: TReader);
begin
inherited;
with reader do
begin
ReadInteger(); // Archive Version 0
fm11 := ReadFloat();
fm12 := ReadFloat();
fm13 := ReadFloat();
fm21 := ReadFloat();
fm22 := ReadFloat();
fm23 := ReadFloat();
fm31 := ReadFloat();
fm32 := ReadFloat();
fm33 := ReadFloat();
end;
end;
//--------------------------
// TGLRigidBodyInertia
//--------------------------
procedure TGLRigidBodyInertia.SetInertiaTensor(newVal: TGLInertiaTensor);
begin
fInertiaTensor := newVal;
end;
procedure TGLRigidBodyInertia.SetRotationSpeed(const val: TGLCoordinates);
begin
AngularMomentum := VectorTransform(val.AsAffineVector, fBodyInertiaTensor);
fRotationSpeed.Assign(val);
end;
procedure TGLRigidBodyInertia.SetRotationDamping(const val: TGLDamping);
begin
FRotationDamping.Assign(val);
end;
procedure TGLRigidBodyInertia.ApplyImpulse(j, xpos, ypos, zpos, x, y, z: Real);
begin
// V2 = V1 + (j/M)n
// V2.M = V1.M +j.n
LinearMomentum.X := LinearMomentum.X + j * x;
LinearMomentum.Y := LinearMomentum.Y + j * y;
LinearMomentum.Z := LinearMomentum.Z + j * z;
AngularMomentum.X := AngularMomentum.X + j * x * xpos;
AngularMomentum.Y := AngularMomentum.Y + j * y * ypos;
AngularMomentum.Z := AngularMomentum.Z + j * z * zpos;
end;
procedure TGLRigidBodyInertia.ApplyImpulse(j: Single;
position, normal: TAffineVector);
begin
CombineVector(LinearMomentum, normal, j);
CombineVector(AngularMomentum, VectorCrossProduct(position, normal), j); // ?
end;
procedure TGLRigidBodyInertia.ApplyDamping(damping: TGLDamping);
var
velocity, angularvelocity: TAffineVector;
v, angularv: Real;
dampingForce: TAffineVector;
angulardampingForce: TAffineVector;
begin
velocity := VectorScale(LinearMomentum, 1 / Mass); // v = p/m
// apply force in opposite direction to velocity
v := VectorLength(velocity);
// F = -Normalised(V)*( Constant + (Linear)*(V) + (Quadtratic)*(V)*(V) )
dampingForce := VectorScale(VectorNormalize(velocity),
-(damping.Constant + damping.Linear * v + damping.Quadratic * v * v));
// ScaleVector(AngularMomentum,0.999);
// ScaleVector(AngularVelocity,Damping.Constant);
// dampingForce:=VectorScale(VectorNormalize(velocity),-(Damping.Constant+Damping.Linear*v+Damping.Quadratic*v*v));
ApplyForce(dampingForce);
angularvelocity := RotationSpeed.AsAffineVector; // v = p/m
// apply force in opposite direction to velocity
angularv := VectorLength(angularvelocity);
// F = -Normalised(V)*( Constant + (Linear)*(V) + (Quadtratic)*(V)*(V) )
angulardampingForce := VectorScale(VectorNormalize(angularvelocity),
-(RotationDamping.Constant + RotationDamping.Linear * v +
RotationDamping.Quadratic * v * v));
// ScaleVector(AngularMomentum,0.999);
// ScaleVector(AngularVelocity,Damping.Constant);
// dampingForce:=VectorScale(VectorNormalize(velocity),-(Damping.Constant+Damping.Linear*v+Damping.Quadratic*v*v));
ApplyTorque(angulardampingForce.X, angulardampingForce.Y, angulardampingForce.Z);
end;
procedure TGLRigidBodyInertia.CalcStateDot(var StateArray: TStateArray;
StatePos: Integer);
var
LinPos, LinMom, AngMom: TAffineVector;
AngPos: TQuaternion;
begin
LinPos := CalcLinearPositionDot();
LinMom := CalcLinearMomentumDot();
AngPos := CalcAngularOrientationDot();
AngMom := CalcAngularVelocityDot();
// SetLength(Result,StateSize);
StateArray[StatePos] := LinPos.X;
StateArray[StatePos + 1] := LinPos.Y;
StateArray[StatePos + 2] := LinPos.Z;
StateArray[StatePos + 3] := LinMom.X;
StateArray[StatePos + 4] := LinMom.Y;
StateArray[StatePos + 5] := LinMom.Z;
StateArray[StatePos + 6] := AngPos.imagPart.X;
StateArray[StatePos + 7] := AngPos.imagPart.Y;
StateArray[StatePos + 8] := AngPos.imagPart.Z;
StateArray[StatePos + 9] := AngPos.RealPart;
StateArray[StatePos + 10] := AngMom.X;
StateArray[StatePos + 11] := AngMom.Y;
StateArray[StatePos + 12] := AngMom.Z;
end;
function TGLRigidBodyInertia.CalculateKE(): Real;
begin
// Result:= "Linear KE" + "Angular KE"
// only linear part so far
Result := 1 / (2 * Mass) * VectorNorm(LinearMomentum);
end;
function TGLRigidBodyInertia.CalculatePE(): Real;
begin
// need to find potentials due to fields acting on body
// may be easier to do via forcefieldemitters?
Result := 0;
end;
function TGLRigidBodyInertia.CalcAngularOrientationDot(): TQuaternion;
var
q1: TQuaternion;
begin
q1.imagPart := VectorScale(RotationSpeed.AsAffineVector, 1 / 2); // v1;
q1.RealPart := 0;
Result := QuaternionMultiply(q1, AngularOrientation);
end;
function TGLRigidBodyInertia.CalcAngularVelocityDot(): TAffineVector;
begin
Result := fTorque;
end;
function TGLRigidBodyInertia.QuaternionToString(Quat: TQuaternion): String;
begin
Result := '<Quaternion><imagPart>' + FloatToSTr(Quat.imagPart.X) + ',' +
FloatToSTr(Quat.imagPart.Y) + ',' + FloatToSTr(Quat.imagPart.Z) +
'</imagPart><realPart>' + FloatToSTr(Quat.RealPart) +
'</realPart><Quaternion>';
end;
{
function TGLRigidBodyInertia.Star(Vector:TAffineVector):TMatrix;
begin
Result.X.X:=0; Result[0][1]:=-Vector[2]; Result[0][2]:=Vector[1]; Result[0][3]:=0;
Result[1][0]:=Vector[2]; Result[1][1]:=0; Result[1][2]:=-Vector[0]; Result[1][3]:=0;
Result[2][0]:=Vector[1]; Result[2][1]:=Vector[0]; Result[2][2]:=0; Result[2][3]:=0;
Result[3][0]:=0; Result[3][1]:=0; Result[3][2]:=0; Result[3][3]:=1;
end;
}
procedure TGLRigidBodyInertia.SetTorque(x, y, z: Real);
begin
fTorque.X := x;
fTorque.Y := y;
fTorque.Z := z;
end;
procedure TGLRigidBodyInertia.ApplyTorque(x, y, z: Real);
begin
fTorque.X := fTorque.X + x;
fTorque.Y := fTorque.Y + y;
fTorque.Z := fTorque.Z + z;
end;
{ procedure TGLRigidBodyInertia.ApplyImpulse(x,y,z:Real);
begin
//
end;
}
procedure TGLRigidBodyInertia.RemoveForces();
begin
fForce := nullVector;
fTorque := nullVector;
end;
procedure TGLRigidBodyInertia.ApplyForce(pos, Force: TVector3f);
var
abspos: TAffineVector;
begin
abspos := VectorTransform(pos, R);
fTorque := VectorAdd(fTorque, VectorCrossProduct(abspos, Force));
fForce := VectorAdd(fForce, Force);
end;
procedure TGLRigidBodyInertia.ApplyLocalForce(pos, Force: TVector3f);
var
abspos: TAffineVector;
absForce: TAffineVector;
begin
abspos := VectorTransform(pos, R);
absForce := VectorTransform(Force, R);
fTorque := VectorAdd(fTorque, VectorCrossProduct(abspos, absForce));
fForce := VectorAdd(fForce, absForce);
end;
procedure TGLRigidBodyInertia.ApplyLocalImpulse(xpos, ypos, zpos, x, y,
z: Real);
begin
//
end;
procedure TGLRigidBodyInertia.SetUpStartingState();
begin
//
inherited SetUpStartingState();
fBodyInertiaTensor.X.X := InertiaTensor.fm11;
fBodyInertiaTensor.X.Y := InertiaTensor.fm12;
fBodyInertiaTensor.X.Z := InertiaTensor.fm13;
fBodyInertiaTensor.Y.X := InertiaTensor.fm21;
fBodyInertiaTensor.Y.Y := InertiaTensor.fm22;
fBodyInertiaTensor.Y.Z := InertiaTensor.fm23;
fBodyInertiaTensor.Z.X := InertiaTensor.fm31;
fBodyInertiaTensor.Z.Y := InertiaTensor.fm32;
fBodyInertiaTensor.Z.Z := InertiaTensor.fm33;
fBodyInverseInertiaTensor := fBodyInertiaTensor;
InvertMatrix(fBodyInverseInertiaTensor);
// Messagedlg('setting BodyIit: '+Format('%f,%f,%f,%f,%f,%f,%f,%f,%f',[fBodyInverseInertiaTensor[0][0],fBodyInverseInertiaTensor[0][1],fBodyInverseInertiaTensor[0][2],fBodyInverseInertiaTensor[1][0],fBodyInverseInertiaTensor[1][1],fBodyInverseInertiaTensor[1][2],fBodyInverseInertiaTensor[2][0],fBodyInverseInertiaTensor[2][1],fBodyInverseInertiaTensor[2][2]]),mtinformation,[mbok],0);
AngularOrientation := IdentityQuaternion;
AngularMomentum := VectorTransform(RotationSpeed.AsAffineVector,
fBodyInertiaTensor);
end;
procedure TGLRigidBodyInertia.CalcAuxiliary();
var
IRt: TAffineMAtrix;
Rt: TAffineMAtrix;
Scale: TAffineVector;
RMatrix: TMatrix;
begin
// TODO: sort this out
fBodyInverseInertiaTensor := IdentityMatrix;
// compute auxiliary variables
R := QuaternionToAffineMatrix(AngularOrientation);
Rt := R;
TransposeMatrix(Rt);
IRt := MatrixMultiply(fBodyInverseInertiaTensor, Rt);
InverseInertiaTensor := MatrixMultiply(R, IRt);
RotationSpeed.AsAffineVector := VectorTransform(AngularMomentum,
InverseInertiaTensor);
TranslationSpeed.AsAffineVector := VectorScale(LinearMomentum, 1 / Mass);
Scale := OwnerBaseSceneObject.Scale.AsAffineVector;
OwnerBaseSceneObject.BeginUpdate;
SetMatrix(RMatrix, R);
OwnerBaseSceneObject.SetMatrix(RMatrix);
// OwnerBaseSceneObject.Matrix:=QuaternionToMatrix(AngularOrientation);
OwnerBaseSceneObject.Scale.AsAffineVector := Scale;
OwnerBaseSceneObject.position.x := LinearPosition.X; // position
OwnerBaseSceneObject.position.y := LinearPosition.Y;
OwnerBaseSceneObject.position.z := LinearPosition.Z;
OwnerBaseSceneObject.EndUpdate;
end;
procedure TGLRigidBodyInertia.StateToArray(var StateArray: TStateArray;
StatePos: Integer);
begin
// with State do
begin
// copy Linear Position
StateArray[StatePos] := LinearPosition.X;
StateArray[StatePos + 1] := LinearPosition.Y;
StateArray[StatePos + 2] := LinearPosition.Z;
// copy Linear Momentum
StateArray[StatePos + 3] := LinearMomentum.X;
StateArray[StatePos + 4] := LinearMomentum.Y;
StateArray[StatePos + 5] := LinearMomentum.Z;
// copy Angular Orientation
StateArray[StatePos + 6] := AngularOrientation.imagPart.X;
StateArray[StatePos + 7] := AngularOrientation.imagPart.Y;
StateArray[StatePos + 8] := AngularOrientation.imagPart.Z;
StateArray[StatePos + 9] := AngularOrientation.RealPart;
// copy Angular Momentum
StateArray[StatePos + 10] := AngularMomentum.X;
StateArray[StatePos + 11] := AngularMomentum.Y;
StateArray[StatePos + 12] := AngularMomentum.Z;
end;
end;
procedure TGLRigidBodyInertia.ArrayToState( { var } StateArray: TStateArray;
StatePos: Integer);
begin
// restore Linear Position
LinearPosition.X := StateArray[StatePos];
LinearPosition.Y := StateArray[StatePos + 1];
LinearPosition.Z := StateArray[StatePos + 2];
// restore Linear Momentum
LinearMomentum.X := StateArray[StatePos + 3];
LinearMomentum.Y := StateArray[StatePos + 4];
LinearMomentum.Z := StateArray[StatePos + 5];
// restore Angular Orientation
AngularOrientation.imagPart.X := StateArray[StatePos + 6];
AngularOrientation.imagPart.Y := StateArray[StatePos + 7];
AngularOrientation.imagPart.Z := StateArray[StatePos + 8];
AngularOrientation.RealPart := StateArray[StatePos + 9];
// restore Angular Momentum
AngularMomentum.X := StateArray[StatePos + 10];
AngularMomentum.Y := StateArray[StatePos + 11];
AngularMomentum.Z := StateArray[StatePos + 12];
end;
procedure TGLRigidBodyInertia.SetLinearDamping(const val: TGLDamping);
begin
// FLinearDamping.Assign(val);
end;
procedure TGLRigidBodyInertia.SetAngularDamping(const val: TGLDamping);
begin
// FAngularDamping.Assign(val);
end;
constructor TGLRigidBodyInertia.Create(aOwner: TXCollection);
begin
inherited Create(aOwner);
Mass := 1;
fDensity := 1;
StateSize := 13;
fInertiaTensor := TGLInertiaTensor.Create(Self);
fRotationSpeed := TGLCoordinates.CreateInitialized(Self, VectorMake(0, 0, 0));
// LinearPosition:=OwnerBaseSceneObject.Position.AsAffineVector;
AngularOrientation := IdentityQuaternion; // fromAngleAxis(0,XVector);
fTorque := nullVector;
fForce := nullVector;
// DampingEnabled:=False;
// FTranslationDamping:=TGLDamping.Create(Self);
FRotationDamping := TGLDamping.Create(Self);
// RotationDamping:=TGLDamping.Create(Self);
R := IdentityMatrix;
InverseInertiaTensor := IdentityMatrix;
// CalcAuxiliary();
// SetDESolver(ssEuler);
end;
destructor TGLRigidBodyInertia.Destroy;
begin
// FLinearDamping.Free;
// FAngularDamping.Free;
fInertiaTensor.Free();
fRotationSpeed.Free();
FRotationDamping.Free;
inherited Destroy;
end;
procedure TGLRigidBodyInertia.Assign(Source: TPersistent);
begin
if Source.ClassType = Self.ClassType then
begin
// FRigidBody.Assign(TGLRigidBodyInertia(Source));
Mass := TGLRigidBodyInertia(Source).Mass;
fDensity := TGLRigidBodyInertia(Source).fDensity;
fBodyInertiaTensor := TGLRigidBodyInertia(Source).fBodyInertiaTensor;
fBodyInverseInertiaTensor := TGLRigidBodyInertia(Source)
.fBodyInverseInertiaTensor;
InertiaTensor.Assign(TGLRigidBodyInertia(Source).InertiaTensor);
LinearPosition := TGLRigidBodyInertia(Source).LinearPosition;
AngularOrientation := TGLRigidBodyInertia(Source).AngularOrientation;
LinearMomentum := TGLRigidBodyInertia(Source).LinearMomentum;
AngularMomentum := TGLRigidBodyInertia(Source).AngularMomentum;
// TranslationSpeed.AsAffineVector:=TGLRigidBodyInertia(Source).TranslationSpeed.AsAffineVector;
RotationSpeed.Assign(TGLRigidBodyInertia(Source).RotationSpeed);
// fForce:=TGLRigidBodyInertia(Source).fForce;
fTorque := TGLRigidBodyInertia(Source).fTorque;
// fInverseInertiaTensor:=TGLRigidBodyInertia(Source).fInverseInertiaTensor;
// RigidBody.fTorque:=TGLRigidBodyInertia(Source).fTorque;
// RigidBody.fForce:=TGLRigidBodyInertia(Source).fForce;
FRotationDamping.Assign(TGLRigidBodyInertia(Source).FRotationDamping);
// DampingEnabled:=TGLRigidBodyInertia(Source).DampingEnabled;
// FTranslationDamping.Assign(TGLRigidBodyInertia(Source).LinearDamping);
// FRotationDamping.Assign(TGLRigidBodyInertia(Source).AngularDamping);
end;
inherited Assign(Source);
end;
class function TGLRigidBodyInertia.FriendlyName: String;
begin
Result := 'Rigid Body Inertia';
end;
class function TGLRigidBodyInertia.FriendlyDescription: String;
begin
Result := 'An inertia model for rigid bodies';
end;
class function TGLRigidBodyInertia.UniqueItem: Boolean;
begin
Result := True;
end;
// **************************************************************************
// ***************** DoProgress ************************************
// **************************************************************************
(* procedure TGLRigidBodyInertia.DoProgress(const progressTime : TProgressTimes);
var
TempScale:TaffineVector;
UndampedLinearMomentum,DampedLinearMomentum:Real;
UnDampedAngularMomentum,DampedAngularMomentum:Real;
i:integer;
begin
// messagedlg('Calculating next state...',mtinformation,[mbOk],0);
with OwnerBaseSceneObject do
with progressTime do
begin
if (DampingEnabled=true) then
begin
UndampedLinearMomentum:=VectorLength(LinearMomentum);
DampedLinearMomentum:=TranslationDamping.Calculate(UndampedLinearMomentum,deltaTime);
{ if GLVectorGeometry.vSIMD=1 then
// RigidBody.LinearMomentum:=VectorScale(VectorNormalize(RigidBody.LinearMomentum),DampedLinearMomentum)
else
} begin
if Length(LinearMomentum)<>0 then
LinearMomentum:=VectorScale(VectorNormalize(LinearMomentum),DampedLinearMomentum)
else
LinearMomentum:=NullVector; //line not required
end;
UndampedAngularMomentum:=VectorLength(AngularMomentum);
DampedAngularMomentum:=RotationDamping.Calculate(UndampedAngularMomentum,deltaTime);
AngularMomentum:=VectorScale(VectorNormalize(AngularMomentum),DampedAngularMomentum);
// ApplyForce(VectorScale(RigidBody.LinearVelocity,-0.5)); //Either apply resistive force & torque
// ApplyTorque(VectorLength(RigidBody.AngularVelocity)); //or use TGLDamping
end;
// Euler(RigidBody,deltaTime);
// RungeKutta4(DeltaTime);
//DESolver(RigidBody,DeltaTime);
//update OwnerBaseSceneObject
TempScale:=Scale.AsAffineVector;
Matrix:=QuaternionToMatrix(AngularOrientation);
position.AsAffineVector:=LinearPosition;
Scale.AsAffineVector:=TempScale;
//calc auxiliary variables for next iteration
CalcAuxiliary();
end;
end;
*)
procedure TGLRigidBodyInertia.WriteToFiler(writer: TWriter);
begin
inherited WriteToFiler(writer);
with writer do
begin
// WriteInteger(0); // Archive Version 0
// FRigidBody.WriteToFiler(writer);
// WriteFloat(fMass);
WriteFloat(fDensity);
Write(fBodyInertiaTensor, SizeOf(fBodyInertiaTensor));
Write(fBodyInverseInertiaTensor, SizeOf(fBodyInverseInertiaTensor));
fInertiaTensor.WriteToFiler(writer);
Write(AngularOrientation, SizeOf(AngularOrientation));
Write(AngularMomentum, SizeOf(AngularMomentum));
// Write(LinearVelocity,SizeOf(LinearVelocity));
RotationSpeed.WriteToFiler(writer);
// Write(AngularVelocity,SizeOf(AngularVelocity));
Write(fTorque, SizeOf(fTorque));
// Write(fForce,SizeOf(fForce));
FRotationDamping.WriteToFiler(writer);
// WriteInteger(Integer(FDESolverType));
// WriteBoolean(FDampingEnabled);
// FLinearDamping.WriteToFiler(writer);
// FAngularDamping.WriteToFiler(writer);
end;
end;
procedure TGLRigidBodyInertia.ReadFromFiler(reader: TReader);
begin
inherited ReadFromFiler(reader);
with reader do
begin
// ReadInteger; // ignore archiveVersion
// FRigidBody.ReadFromFiler(Reader);
// fMass:=ReadFloat;
fDensity := ReadFloat;
Read(fBodyInertiaTensor, SizeOf(fBodyInertiaTensor));
Read(fBodyInverseInertiaTensor, SizeOf(fBodyInverseInertiaTensor));
InertiaTensor.ReadFromFiler(reader);
Read(AngularOrientation, SizeOf(AngularOrientation));
Read(AngularMomentum, SizeOf(AngularMomentum));
// Read(LinearVelocity,SizeOf(LinearVelocity));
RotationSpeed.ReadFromFiler(reader);
// Read(AngularVelocity,SizeOf(AngularVelocity));
Read(fTorque, SizeOf(fTorque));
// Read(fForce, SizeOf(fForce));
FRotationDamping.ReadFromFiler(reader);
// SetDESolver(TDESolverType(ReadInteger));
// FDampingEnabled:=ReadBoolean;
// FLinearDamping.ReadFromFiler(reader);
// FAngularDamping.ReadFromFiler(reader);
end;
// SetDESolver(fDESolverType);
// CalcAuxiliary();
SetUpStartingState();
end;
function GetOrCreateRigidBodyInertia(behaviours: TGLBehaviours)
: TGLRigidBodyInertia;
var
i: Integer;
begin
i := behaviours.IndexOfClass(TGLRigidBodyInertia);
if i >= 0 then
Result := TGLRigidBodyInertia(behaviours[i])
else
Result := TGLRigidBodyInertia.Create(behaviours);
end;
function GetOrCreateRigidBodyInertia(obj: TGLBaseSceneObject)
: TGLRigidBodyInertia;
begin
Result := GetOrCreateRigidBodyInertia(obj.behaviours);
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterXCollectionItemClass(TGLParticleInertia);
RegisterXCollectionItemClass(TGLRigidBodyInertia);
end.
|
PROGRAM DEMO1
BEGIN
A:=3;
B:=45;
H:=-100023;
C:=A;
D123:=B34A;
BABOON:=GIRAFFE;
TEXT:="Hello world!";
END.
|
unit ParseTreeBase;
interface
uses
SysUtils, Classes, ObjVec, StrTbl;
const
CompoundNameDelimiter = '.';
type
EActionCompileError = class(Exception);
TNodeFlag = (nfDiscardResult, nfReference, nfNew, nfInitObject, nfInitArray,
nfDoWhile, nfPostfix, nfCommaExpr, nfClassMember, nfGetProp, nfSetProp);
TNodeFlags = set of TNodeFlag;
TSourcePos = record
FileName: string;
Line, Col: Integer;
end;
TParseTreeNode = class(TObject)
private
FFlags: TNodeFlags;
FSrcPos: TSourcePos;
protected
procedure CheckDiscardResult;
public
procedure AfterConstruction; override;
procedure Compile; virtual;
procedure SetFlag(Flag: TNodeFlag);
property Flags: TNodeFlags read FFlags;
property SrcPos: TSourcePos read FSrcPos write FSrcPos;
end;
TPairNode = class(TParseTreeNode)
public
First, Second: TParseTreeNode;
end;
TSourcePosNode = class(TParseTreeNode)
public
Value: TSourcePos;
end;
TItemRef = TParseTreeNode;
{$INCLUDE ObjVec.inc}
INodeList = IVector;
TNodeList = TVector;
TCompoundName = class(TParseTreeNode)
private
FItems: array of TStrId;
FLen: Integer;
FFull: TStrId;
function GetFull: TStrId;
function GetLast: TStrId;
function GetCount: Integer;
function GetItem(I: Integer): TStrId;
public
constructor Create(AIdent: TStrId);
constructor Parse(AIdent: TStrId);
procedure Add(AIdent: TStrId);
property Full: TStrId read GetFull;
property Last: TStrId read GetLast;
property Items[I: Integer]: TStrId read GetItem; default;
property Count: Integer read GetCount;
end;
function StrToken2(var Str: string; const Separators: string): string;
implementation
uses
GUtils, ActionCompiler;
{$DEFINE IMPL}
{$INCLUDE ObjVec.inc}
{ TParseTreeNode }
procedure TParseTreeNode.AfterConstruction;
begin
inherited AfterConstruction;
Context.AddToFreeList(Self);
{
Вызов AddToFreeList нельзя поместить в конструктор базового класса,
так как в конструкторе производного класса уже после вызова конструктора
базового класса и добавления объекта в список FreeList может произойти
исключение. В такой ситуации автоматически вызывается деструктор и
объект разрушается, но ссылка на него остается в FreeList. При освобождении
FreeList будет произведена попытка уничножить несуществующий объект.
}
end;
procedure TParseTreeNode.Compile;
begin
end;
procedure TParseTreeNode.SetFlag(Flag: TNodeFlag);
begin
FFlags := FFlags + [Flag];
end;
procedure TParseTreeNode.CheckDiscardResult;
begin
if nfDiscardResult in Flags then
WriteCmd(acPop);
end;
{ TCompoundName }
function StrToken2(var Str: string; const Separators: string): string;
var
L, I, J: Integer;
begin
L := Length(Str);
I := 1;
while (I <= L) and (Pos(Str[I], Separators) > 0) do
Inc(I);
if I > L then
begin
Str := '';
Result := '';
end
else
begin
J := I + 1;
while (J <= L) and (Pos(Str[J], Separators) = 0) do
Inc(J);
Result := Copy(Str, I, J - I);
Str := Copy(Str, J, L);
end;
end;
constructor TCompoundName.Create(AIdent: TStrId);
begin
inherited Create;
SetLength(FItems, 4);
FFull := -1;
Add(AIdent);
end;
constructor TCompoundName.Parse(AIdent: TStrId);
var
IdentStr, ItemStr: string;
begin
inherited Create;
SetLength(FItems, 4);
FFull := -1;
IdentStr := St[AIdent];
ItemStr := StrToken2(IdentStr, CompoundNameDelimiter);
if ItemStr = '' then
Add(AIdent)
else
repeat
Add(St.AddItem(ItemStr));
ItemStr := StrToken2(IdentStr, CompoundNameDelimiter);
until ItemStr = '';
end;
procedure TCompoundName.Add(AIdent: TStrId);
begin
if FLen = Length(FItems) then
SetLength(FItems, FLen + 4);
FItems[FLen] := AIdent;
Inc(FLen);
end;
function TCompoundName.GetFull: TStrId;
var
FullStr: string;
I: Integer;
begin
if FFull = -1 then
begin
FullStr := St[FItems[0]];
for I := 1 to FLen - 1 do
FullStr := FullStr + CompoundNameDelimiter + St[FItems[I]];
FFull := St.AddItem(FullStr);
end;
Result := FFull;
end;
function TCompoundName.GetLast: TStrId;
begin
Result := FItems[FLen - 1];
end;
function TCompoundName.GetCount: Integer;
begin
Result := FLen;
end;
function TCompoundName.GetItem(I: Integer): TStrId;
begin
Assert((I >= 0) and (I < Count));
Result := FItems[I];
end;
end.
|
unit UntBaseCadastroForm;
interface
uses
Forms,
UntBaseForm,
Classes, StdCtrls, TypInfo;
type
TBaseCadastroForm = class(TBaseForm)
protected
procedure LimparCampos; virtual;
procedure HabilitarCampos(habilitar: boolean = true); virtual;
procedure ParseFormToObject(obj: TObject);
procedure ParseObjectToForm(obj: TObject);
end;
implementation
{$R *.dfm}
uses
SysUtils, StrUtils, UntRttiHelper;
{ TBaseCadastroForm }
procedure TBaseCadastroForm.LimparCampos;
var
comp: TComponent;
index: integer;
begin
for index := 0 to pred(self.ComponentCount) do
begin
comp := self.Components[index];
if comp is TCustomEdit then
TCustomEdit(comp).Clear;
if comp is TCustomCombobox then
TCustomCombobox(comp).ItemIndex := -1;
end;
end;
procedure TBaseCadastroForm.HabilitarCampos(habilitar: boolean);
var
comp: TComponent;
compAux: TComponent;
index: integer;
begin
for index := 0 to pred(self.ComponentCount) do
begin
comp := self.Components[index];
if comp is TCustomEdit then
TCustomEdit(comp).Enabled := habilitar;
if comp is TCustomCombobox then
TCustomCombobox(comp).Enabled := habilitar;
end;
compAux := self.FindComponent('btnGravar');
if (compAux <> nil) and (compAux is TButton) then
TButton(compAux).Enabled := not habilitar;
compAux := self.FindComponent('btnCancelar');
if (compAux <> nil) and (compAux is TButton) then
TButton(compAux).Enabled := not habilitar;
end;
procedure TBaseCadastroForm.ParseFormToObject(obj: TObject);
var
index: integer;
comp: TComponent;
begin
for index := 0 to pred(self.ComponentCount) do
begin
comp := self.Components[index];
if comp is TCustomEdit then
TFormParser.ParseComponentToObject(comp, obj);
end;
end;
procedure TBaseCadastroForm.ParseObjectToForm(obj: TObject);
var
index: integer;
comp: TComponent;
begin
for index := 0 to pred(self.ComponentCount) do
begin
comp := self.Components[index];
if comp is TCustomEdit then
TFormParser.ParseObjectToComponent(obj, comp);
end;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation;
type
TForm1 = class(TForm)
Label1: TLabel;
MessageButton: TButton;
LanguageButton: TButton;
MessageLabel: TLabel;
DeviceLabel: TLabel;
procedure MessageButtonClick(Sender: TObject);
procedure LanguageButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure UpdateStrings;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{$R *.NmXhdpiPh.fmx ANDROID}
{$R *.SmXhdpiPh.fmx ANDROID}
{$R *.XLgXhdpiTb.fmx ANDROID}
{$R *.GGlass.fmx ANDROID}
{$R *.Windows.fmx MSWINDOWS}
{$R *.LgXhdpiTb.fmx ANDROID}
uses
NtResource,
FMX.NtLanguageDlg,
FMX.NtTranslator;
procedure TForm1.UpdateStrings;
begin
DeviceLabel.Text := Format(_T('Device is "%s"'), [TNtTranslator.GetDevice(Self)]);
MessageLabel.Text := _T('This is a sample');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
NtResources._T('English', 'en');
NtResources._T('Finnish', 'fi');
NtResources._T('German', 'de');
NtResources._T('French', 'fr');
NtResources._T('Japanese', 'ja');
_T(Self);
UpdateStrings
end;
procedure TForm1.MessageButtonClick(Sender: TObject);
begin
ShowMessage(_T('Hello world'));
end;
procedure TForm1.LanguageButtonClick(Sender: TObject);
begin
TNtLanguageDialog.Select(
procedure
begin
UpdateStrings;
end);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.