text stringlengths 14 6.51M |
|---|
unit user_charts;
{$mode delphi}
interface
uses
Classes, SysUtils, Graphics, TAGraph, TASeries, FastChart;
procedure ChartSeriesAddXY(ChartIndex, SeriesIndex: integer; X, Y: double);
procedure ChartSeriesClear(ChartIndex, SeriesIndex: integer);
procedure ChartSetAxisMinMax(ChartIndex: integer; Xmin, Xmax, Ymin, Ymax: double);
procedure ChartSeriesSetColor(ChartIndex, SeriesIndex: integer; newColor: TColor);
function ChartSeriesGetCount(ChartIndex: integer): integer;
procedure ChartSeriesSetCount(ChartIndex, SeriesCount: integer);
function ChartSeriesCreate(ChartIndex: integer): integer;
procedure ChartSeriesDeleteAll(ChartIndex: integer);
implementation
procedure ChartSeriesAddXY(ChartIndex, SeriesIndex: integer; X, Y: double);
begin
(UserCharts[ChartIndex].Series[SeriesIndex] as TLineSeries).AddXY(X, Y);
end;
procedure ChartSeriesClear(ChartIndex, SeriesIndex: integer);
begin
(UserCharts[ChartIndex].Series[SeriesIndex] as TLineSeries).Clear;
end;
procedure ChartSetAxisMinMax(ChartIndex: integer; Xmin, Xmax, Ymin, Ymax: double);
var chart: TChart;
begin
chart := UserCharts[ChartIndex];
with Chart.AxisList[0].Range do begin
UseMax := true;
UseMin := true;
Max := Ymax;
Min := Ymin;
end;
with Chart.AxisList[1].Range do begin
UseMax := true;
UseMin := true;
Max := Xmax;
Min := Xmin;
end;
end;
function ChartSeriesGetCount(ChartIndex: integer): integer;
var chart: TChart;
begin
chart := UserCharts[ChartIndex];
result := Chart.Series.Count;
end;
procedure ChartSeriesSetColor(ChartIndex, SeriesIndex: integer; newColor: TColor);
var LineSeries: TLineSeries;
chart: TChart;
begin
chart := UserCharts[ChartIndex];
(UserCharts[ChartIndex].Series[SeriesIndex] as TLineSeries).SeriesColor := newColor;
end;
procedure ChartSeriesSetCount(ChartIndex, SeriesCount: integer);
var LineSeries: TLineSeries;
chart: TChart;
i: integer;
begin
chart := UserCharts[ChartIndex];
if Chart.Series.Count < SeriesCount then begin // Must create some series
for i := Chart.Series.Count to SeriesCount - 1 do begin
LineSeries := TLineSeries.Create(chart);
chart.AddSeries(LineSeries);
end;
end;
// TODO: safe way to remove some series
end;
function ChartSeriesCreate(ChartIndex: integer): integer;
var LineSeries: TLineSeries;
chart: TChart;
begin
chart := UserCharts[ChartIndex];
LineSeries := TLineSeries.Create(chart);
chart.AddSeries(LineSeries);
result := Chart.Series.Count - 1;
end;
procedure ChartSeriesDeleteAll(ChartIndex: integer);
var chart: TChart;
begin
chart := UserCharts[ChartIndex];
chart.Series.Clear;
end;
end.
|
unit UPrefFDocFont;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
{ This is the Frame that contains the Document Font Preferences}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, UGlobals, UContainer, ExtCtrls, RzLabel, RzBorder;
type
TPrefDocFonts = class(TFrame)
btnChgFonts: TButton;
btnSetFontDefaults: TButton;
FontDialog: TFontDialog;
btnPreview: TButton;
btnRevert: TButton;
cbxSetFontDefaults: TCheckBox;
Panel1: TPanel;
StaticText1: TStaticText;
StaticText2: TStaticText;
stSampleText: TStaticText;
lblFontName: TStaticText;
lblFontSize: TStaticText;
lblSampleText: TPanel;
Panel2: TPanel;
StaticText4: TStaticText;
StaticText5: TStaticText;
procedure btnChgFontsClick(Sender: TObject);
procedure btnSetFontDefaultsClick(Sender: TObject);
procedure btnPreviewClick(Sender: TObject);
procedure btnRevertClick(Sender: TObject);
private
FDoc: TContainer;
FDocChged: Boolean;
FOrgDocFont: TFont; //original doc font
public
constructor CreateFrame(AOwner: TComponent; ADoc: TContainer);
destructor Destroy; override;
procedure LoadPrefs; //loads in the prefs from the app
procedure SavePrefs; //saves the changes
procedure DisplayCancel;
procedure ApplyPreferences;
end;
implementation
uses
UEditor,
UInit,
UStatus,
UUtil1;
{$R *.dfm}
constructor TPrefDocFonts.CreateFrame(AOwner: TComponent; ADoc: TContainer);
begin
inherited Create(AOwner);
FDoc := ADoc;
lblSampleText.Height := stSampleText.Height;
LoadPrefs;
end;
procedure TPrefDocFonts.LoadPrefs;
begin
// Set Document Prefs; if have Active use those, else use defaults
cbxSetFontDefaults.checked := appPref_FontIsDefault;
if FDoc = nil then begin
//Font preferences
lblFontName.Caption := appPref_InputFontName;
lblFontSize.Caption := IntToStr(appPref_InputFontSize);
lblSampletext.Font.Assign(appPref_InputFont);
end
else begin //if doc <> nil then
//Save for undoing
FOrgDocFont := TFont.Create;
FOrgDocFont.Assign(FDoc.docFont); //save the cur doc font
//show cur doc font
lblFontName.Caption := FDoc.docFont.Name;
lblFontSize.Caption := IntToStr(FDoc.docFont.Size);
lblSampletext.Font.Assign(FDoc.docFont);
end;
//init some vars
FDocChged := False;
end;
destructor TPrefDocFonts.Destroy;
begin
if Assigned(FOrgDocFont) then
FOrgDocFont.Free;
inherited;
end;
procedure TPrefDocFonts.SavePrefs;
begin
//Document Preferences (Default for Future documents)
appPref_FontIsDefault := cbxSetFontDefaults.checked;
if cbxSetFontDefaults.checked then
begin
//Fonts
appPref_InputFontName := lblSampleText.Font.Name;
appPref_InputFontSize := lblSampleText.Font.Size;
appPref_InputFontColor := lblSampleText.Font.Color;
appPref_InputFont.Assign(lblSampleText.Font);
end;
//Active Document Preferences
if (FDoc <> nil) then
begin
//Font
FDoc.docFont.assign(lblSampletext.Font);
end;
end;
procedure TPrefDocFonts.btnChgFontsClick(Sender: TObject);
begin
FontDialog.Options := [fdTrueTypeOnly, fdLimitSize];
FontDialog.Font.Name := lblSampleText.Font.Name; //appPref_InputFontName;
FontDialog.Font.Size := lblSampleText.Font.Size; //appPref_InputFontSize;
FontDialog.Font.Style := lblSampleText.Font.Style;
FontDialog.MaxFontSize := defaultMaxFontSize;
if FontDialog.execute then
begin
lblFontName.Caption := FontDialog.Font.Name;
lblFontSize.Caption := IntToStr(FontDialog.Font.Size);
lblSampleText.Font.Assign(FontDialog.Font);
FDocChged := True;
end;
end;
procedure TPrefDocFonts.btnSetFontDefaultsClick(Sender: TObject);
begin
lblFontName.Caption := defaultFontName;
lblFontSize.Caption := IntToStr(defaultFontSize);
lblSampleText.Font.Name := defaultFontName;
lblSampleText.Font.Size := defaultFontSize;
lblSampleText.Font.Style := [];
lblSampleText.Font.Color := clBlack;
FDocChged := True;
end;
procedure TPrefDocFonts.btnPreviewClick(Sender: TObject);
begin
ApplyPreferences; //Preview Only
end;
//Just like APPLY, but undo it when they cancel
procedure TPrefDocFonts.DisplayCancel;
begin
if (FDoc <> nil) and FDocChged then
begin //reset the old look
//Font
if FDoc.docFont.Size <> FOrgDocFont.Size then
FDoc.SetAllCellsTextSize(FOrgDocFont.Size);
if FDoc.docFont.Style <> FOrgdocFont.Style then
FDoc.SetAllCellsFontStyle(FOrgDocFont.Style);
FDoc.docFont.assign(FOrgDocFont);
FDoc.docView.Invalidate;
LoadPrefs; //show last saved changes
end;
end;
procedure TPrefDocFonts.ApplyPreferences;
var
format: ITextFormat;
begin
if FDoc <> nil then
begin //show the new look
//Font
FDoc.docFont.assign(lblSampletext.Font);
if Supports(FDoc.docEditor, ITextFormat, format) then
format.Font.Assign(FDoc.docFont);
FDoc.docView.Font.Assign(FDoc.docFont);
FDoc.SetAllCellsTextSize(lblSampletext.Font.Size);
FDoc.SetAllCellsFontStyle(lblSampleText.Font.Style);
FDoc.docView.Invalidate;
FDocChged := True;
end;
end;
procedure TPrefDocFonts.btnRevertClick(Sender: TObject);
begin
DisplayCancel;
end;
end.
|
{
Unit com referência no site:
http://delphiisntdead.wordpress.com/2008/05/27/path-de-diretorios-especias/
CSIDL
http://pinvoke.net/search.aspx?search=CSIDL&namespace=%5BAll%5D
http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/bb762494(v=vs.85).aspx
DICAS:
function IncludeTrailingBackslash(const S: string): string;
Adiciona '\' no final da string SE não tiver
exemplo:
s: = IncludeTrailingBackslash ('c:\MyDocuments');
S = c:\MyDocuments\
}
unit uFuncoesWindows;
interface
uses windows, shlobj, SysUtils;
//Diretório Temporário do usuário( {usuario}\Configurações Locais\Temp )
function getTempDir: String;
//Diretório do Windows(c:\windows)
function getWinDir: String;
//Diretório de sistema(c:\windows\system32)
function getSysDir: String;
//getSpecialDir necessário utilizar de constantes que estão declaradas na unit “shlobj”:
function getSpecialDir(CSIDL: integer): string;
// Verifica se é usado a versão x64 do Windows
function IsWindows64: Boolean;
const
CSIDL_ADMINTOOLS = $0030; //{USUARIO}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Administrative Tools
CSIDL_COMMON_ADMINTOOLS = $002f;
CSIDL_COMMON_DESKTOPDIRECTORY = $0019;
CSIDL_COMMON_DOCUMENTS = $002e;
CSIDL_COMMON_FAVORITES = $001f;
CSIDL_MYDOCUMENTS = $000c;
CSIDL_MYMUSIC = $000d;
CSIDL_MYPICTURES = $0027;
CSIDL_MYVIDEO = $000e;
CSIDL_PROGRAM_FILES = $0026;
CSIDL_PROGRAM_FILES_COMMON = $002b;
CSIDL_SYSTEM = $0025;
CSIDL_WINDOWS = $0024;
CSIDL_SYSTEMX86 = $0029; //%windir%\syswow64
CSIDL_DESKTOP = $0000; //{USUARIO}\Desktop
CSIDL_PROGRAMS = $0002; //{USUARIO}\Menu Iniciar\Programas
CSIDL_PERSONAL = $0005; //{USUARIO}\Meus Documentos
CSIDL_FAVORITES = $0006; //{USUARIO}\Favoritos
CSIDL_STARTUP = $0007; //{USUARIO}\Menu Iniciar\Programas\Inicializar
CSIDL_SENDTO = $0009; //{USUARIO}\SendTo
CSIDL_STARTMENU = $000b; //{USUARIO}\Menu Iniciar
CSIDL_DESKTOPDIRECTORY = $0010; //{USUARIO}\Desktop
CSIDL_FONTS = $0014; //C:\Windows\Fonts
CSIDL_COMMON_STARTMENU = $0016; //{All Users}\Menu Iniciar
CSIDL_COMMON_PROGRAMS = $0017; //{All Users}\Menu Iniciar\Programas
CSIDL_COMMON_STARTUP = $0018; //{All Users}\Menu Iniciar\Programas\Inicializar
// CSIDL_COMMON_DESKTOPDIRECTORY = $0019; //ll Users}\Desktop
CSIDL_APPDATA = $001a; //{USUARIO}\Dados de Aplicativos
CSIDL_LOCAL_APPDATA = $001c; //{USUARIO}\Configurações Locais\Dados de Aplicativos
// CSIDL_COMMON_FAVORITES = $001f; //{All Users}\Favoritos
CSIDL_INTERNET_CACHE = $0020; //{USUARIO}\Configurações locais\Temporary Internet Files
CSIDL_COOKIES = $0021; //{USUARIO}\Cookies
CSIDL_HISTORY = $0022; //{USUARIO}\Configurações locais\Histórico
CSIDL_PROFILE = $0028; //{USUARIO}
CSIDL_COMMON_MUSIC = $0035; //{All Users}\Minhas Músicas
CSIDL_COMMON_PICTURES = $0036; //{All Users}\Minhas Imagens
CSIDL_COMMON_VIDEO = $0037; //{All Users}\Meus Vídeos
// //Algumas Constantes Não Definidas:
// CSIDL_ADMINTOOLS = $0030; //{USUARIO}\Menu iniciar\Programas\Ferramentas administrativas
// CSIDL_COMMON_ADMINTOOLS = $002f; //{All Users}\Menu iniciar\Programas\Ferramentas administrativas
// CSIDL_COMMON_DOCUMENTS = $002e; //{All Users}\Documentos
// CSIDL_MYMUSIC = $000d; //{USUARIO}\Minhas Músicas
// CSIDL_MYPICTURES = $0027; //{USUARIO}\Minhas Imagens
// CSIDL_MYVIDEO = $000e; //{USUARIO}\Meus Vídeos
// CSIDL_PROGRAM_FILES = $0026; //C:\Arquivos de Programas
// CSIDL_PROGRAM_FILES_COMMON = $002b; //C:\Arquivos de Programas\Arquivos Comuns
// CSIDL_SYSTEM = $0025; //C:\Windows\System32
// CSIDL_WINDOWS = $0024; //C:\Windows
implementation
//Diretório Temporário do usuário( {usuario}\Configurações Locais\Temp )
function getTempDir: String;
var
lng: DWORD;
begin
SetLength(Result, MAX_PATH);
lng := GetTempPath( MAX_PATH, PChar(Result)) ;
SetLength(Result, lng) ;
end;
//Diretório do Windows(c:\windows)
function getWinDir: String;
var
lng: DWORD;
begin
SetLength(Result, MAX_PATH) ;
lng := GetWindowsDirectory(PChar(Result), MAX_PATH);
SetLength(Result, lng) ;
end;
//Diretório de sistema(c:\windows\system32)
function getSysDir: String;
var
lng: DWORD;
begin
SetLength(Result, MAX_PATH) ;
lng := GetSystemDirectory(PChar(Result), MAX_PATH);
SetLength(Result, lng) ;
end;
//getSpecialDir necessário utilizar de constantes que estão declaradas na unit “shlobj”:
function getSpecialDir(CSIDL: integer): string;
var
r: Bool;
path: array[0..MAX_PATH] of Char;
begin
//substitua CSIDL pela constante relativa ao diretório desejado
r := ShGetSpecialFolderPath(0, path, CSIDL, False);
if not r then
raise Exception.Create('Diretório não Encontrado');
Result := Path;
end;
function IsWindows64: Boolean;
type
TIsWow64Process = function(AHandle:THandle; var AIsWow64: BOOL): BOOL; stdcall;
var
vKernel32Handle: DWORD;
vIsWow64Process: TIsWow64Process;
vIsWow64 : BOOL;
begin
// 1) assume that we are not running under Windows 64 bit
Result := False;
// 2) Load kernel32.dll library
vKernel32Handle := LoadLibrary('kernel32.dll');
if (vKernel32Handle = 0) then Exit; // Loading kernel32.dll was failed, just return
try
// 3) Load windows api IsWow64Process
@vIsWow64Process := GetProcAddress(vKernel32Handle, 'IsWow64Process');
if not Assigned(vIsWow64Process) then Exit; // Loading IsWow64Process was failed, just return
// 4) Execute IsWow64Process against our own process
vIsWow64 := False;
if (vIsWow64Process(GetCurrentProcess, vIsWow64)) then
Result := vIsWow64; // use the returned value
finally
FreeLibrary(vKernel32Handle); // unload the library
end;
end;
end.
|
unit AddUserForm_unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, BaseFrontForm_Unit, FrontData_Unit, StdCtrls, ExtCtrls, AdvPanel,
Front_DataBase_Unit, kbmMemTable, DB, DBCtrls, AdvSmoothButton, Mask, ActnList,
Grids, AdvObj, BaseGrid, AdvGrid, DBAdvGrid, AdvSmoothTouchKeyBoard,
Generics.Collections;
type
TAddUserForm = class(TBaseFrontForm)
pnlMain: TAdvPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
DepartmentTable: TkbmMemTable;
dsDepartment: TDataSource;
dsMain: TDataSource;
MainTable: TkbmMemTable;
pnlRight: TAdvPanel;
btnOK: TAdvSmoothButton;
btnCancel: TAdvSmoothButton;
dbeSurName: TDBEdit;
dbeFirstName: TDBEdit;
dbeMiddleName: TDBEdit;
Label5: TLabel;
dbePASSW: TDBEdit;
Label6: TLabel;
edConfirmPass: TEdit;
alMain: TActionList;
actAddUser: TAction;
dbrgMain: TDBAdvGrid;
UserGroupTable: TkbmMemTable;
dsUserGroup: TDataSource;
UserGroupTableID: TIntegerField;
UserGroupTableUSRNAME: TStringField;
UserGroupTableCHECKED: TIntegerField;
AdvTouchKeyBoard: TAdvSmoothTouchKeyBoard;
cbDisabled: TDBCheckBox;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actAddUserExecute(Sender: TObject);
procedure actAddUserUpdate(Sender: TObject);
procedure dbePASSWKeyPress(Sender: TObject; var Key: Char);
procedure edConfirmPassKeyPress(Sender: TObject; var Key: Char);
procedure FormDestroy(Sender: TObject);
private
FInsertMode: Boolean;
FUserKey: Integer;
FGroupList: TList<Integer>;
public
property InsertMode: Boolean read FInsertMode write FInsertMode;
property UserKey: Integer read FUserKey write FUserKey;
end;
var
AddUserForm: TAddUserForm;
implementation
uses
rfUtils_unit, TouchMessageBoxForm_Unit;
{$R *.dfm}
procedure TAddUserForm.actAddUserExecute(Sender: TObject);
var
FValidGroup: Boolean;
begin
FValidGroup := False;
UserGroupTable.First;
while not UserGroupTable.Eof do
begin
if UserGroupTable.FieldByName('CHECKED').AsInteger = 1 then
begin
FValidGroup := True;
Break;
end;
UserGroupTable.Next
end;
if not FValidGroup then
begin
Touch_MessageBox('Внимание', 'Нужно указать группу пользователя', MB_OK, mtWarning);
exit;
end;
if not FInsertMode then
begin
if FFrontBase.AddUser(MainTable, UserGroupTable) then
ModalResult := mrOk;
end else
if FInsertMode then
begin
if FFrontBase.UpdateUser(MainTable, UserGroupTable, FUserKey, FGroupList) then
ModalResult := mrOk;
end;
end;
procedure TAddUserForm.actAddUserUpdate(Sender: TObject);
begin
actAddUser.Enabled := (not MainTable.FieldByName('SURNAME').IsNull)
and (not MainTable.FieldByName('PASSW').IsNull)
and (MainTable.FieldByName('PASSW').AsString = edConfirmPass.Text);
end;
procedure TAddUserForm.dbePASSWKeyPress(Sender: TObject; var Key: Char);
begin
RemoveWrongPassChar(Key);
inherited;
end;
procedure TAddUserForm.edConfirmPassKeyPress(Sender: TObject; var Key: Char);
begin
RemoveWrongPassChar(Key);
inherited;
end;
procedure TAddUserForm.FormCreate(Sender: TObject);
begin
FInsertMode := False;
FUserKey := -1;
DepartmentTable.FieldDefs.Add('ID', ftInteger, 0);
DepartmentTable.FieldDefs.Add('USR$NAME', ftString, 60);
DepartmentTable.CreateTable;
DepartmentTable.Open;
MainTable.FieldDefs.Add('ID', ftInteger, 0);
MainTable.FieldDefs.Add('FIRSTNAME', ftString, 20);
MainTable.FieldDefs.Add('SURNAME', ftString, 20);
MainTable.FieldDefs.Add('MIDDLENAME', ftString, 20);
MainTable.FieldDefs.Add('ibname', ftString, 8);
MainTable.FieldDefs.Add('ibpassword', ftString, 8);
MainTable.FieldDefs.Add('PASSW', ftString, 20);
MainTable.FieldDefs.Add('DISABLED', ftBoolean, 0);
MainTable.CreateTable;
MainTable.Open;
cbDisabled.Checked := False;
FGroupList := TList<Integer>.Create;
SetupAdvGrid(dbrgMain);
end;
procedure TAddUserForm.FormDestroy(Sender: TObject);
begin
FGroupList.Free;
inherited;
end;
procedure TAddUserForm.FormShow(Sender: TObject);
begin
Assert(Assigned(FFrontBase), 'FrontBase not assigned');
FFrontBase.GetDepartmentList(DepartmentTable);
FFrontBase.GetUserGroupList(UserGroupTable);
UserGroupTable.First;
if FInsertMode then
begin
FFrontBase.GetEditUserInfo(MainTable, UserGroupTable, FUserKey, FGroupList);
edConfirmPass.Text := MainTable.FieldByName('PASSW').AsString;
UserGroupTable.First;
end;
end;
end.
|
unit UPrefCell;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, ExtCtrls,
UCell, UEditor, RzButton, RzRadChk, UForms;
type
TCellPref = class(TAdvancedForm)
PageMgr: TPageControl;
General: TTabSheet;
lbStyle: TLabel;
lbSize: TLabel;
cbxStyle: TComboBox;
cbxSize: TComboBox;
chkSkip: TCheckBox;
chkTrans: TCheckBox;
Number: TTabSheet;
lbRound: TLabel;
cbxRound: TComboBox;
chkPlusSign: TCheckBox;
chkDispZero: TCheckBox;
chkComma: TCheckBox;
Graphic: TTabSheet;
Date: TTabSheet;
btnOK: TButton;
btnCancel: TButton;
chkCalc: TCheckBox;
chkOnlyDate: TCheckBox;
lbScale: TLabel;
ImageScaleBar: TTrackBar;
ImageScaleVal: TEdit;
lbJust: TLabel;
cbxJust: TComboBox;
chkOnlyNum: TCheckBox;
chkFmtNum: TCheckBox;
ChkOnlyShow: TCheckBox;
radDateGrp: TRadioGroup;
radMDY: TRadioButton;
radMDYYYY: TRadioButton;
radMY: TRadioButton;
radShortM: TRadioButton;
radLongM: TRadioButton;
chkTransInto: TCheckBox;
chkStretch: TRzCheckBox;
chkAspectRatio: TRzCheckBox;
chkCenter: TRzCheckBox;
chkFrame: TRzCheckBox;
chkAutoFit: TCheckBox;
procedure ImageScaleBarChange(Sender: TObject);
procedure chkFitClick(Sender: TObject);
procedure chkAspectClick(Sender: TObject);
procedure chkCntrClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
FOrgFit: Boolean;
FOrgAspect: Boolean;
FOrgCntr: Boolean;
ForgFrame: Boolean;
FOrgScale: Integer;
public
FCell: TBaseCell;
FPref: Integer;
FFormat: Integer;
FEditor: TEditor;
constructor Create(AOwner: TComponent; Editor: TEditor); reintroduce;
procedure SaveChanges;
procedure UpdateImage;
end;
var
CellPref: TCellPref;
implementation
Uses
UGlobals, UUtil1;
{$R *.DFM}
{ TCellPref }
constructor TCellPref.Create(AOwner: TComponent; Editor: TEditor);
var
format: ITextFormat;
begin
inherited Create(AOwner);
//Ticket #1283: if user has multiple monitors and bring CF to show in between of the 2 monitors bring up multiple reports and close one
//got the pop up dialog disappear and user has to end task.
if Editor <> nil then
begin
FEditor := Editor;
FEditor.SaveChanges;
FCell := TBaseCell(Editor.FCell); //remember so we can save options
FPref := TBaseCell(FCell).FCellPref; //work with the temps
FFormat := TBaseCell(FCell).FCellFormat;
if (FEditor is TGraphicEditor) then
begin
PageMgr.ActivePage := Graphic; //set it to the right tab
with FEditor as TGraphicEditor do
begin
if FStretch then
chkStretch.InitState(cbChecked)
else
chkStretch.InitState(cbUnchecked);
if FAspRatio then
chkAspectRatio.InitState(cbChecked)
else
chkAspectRatio.InitState(cbUnchecked);
if FCenter then
chkCenter.InitState(cbChecked)
else
chkCenter.InitState(cbUnchecked);
if FPrFrame then
chkFrame.InitState(cbChecked)
else
chkFrame.InitState(cbUnchecked);
ImageScaleVal.text := IntToStr(FEditScale);
ImageScaleBar.Position := FEditScale; //will redraw the image
ImageScaleVal.Enabled := not FStretch;
ImageScaleBar.enabled := not FStretch;
end;
FOrgFit := chkStretch.checked; //remember in case we cancel chges
FOrgAspect := chkAspectratio.checked;
FOrgCntr := chkCenter.checked;
FOrgFrame := chkFrame.checked;
FOrgScale := ImageScaleBar.Position;
//disable the general
chkTrans.Enabled := False;
chkCalc.Enabled := False;
chkOnlyNum.Enabled := False;
chkOnlyDate.Enabled := False;
ChkOnlyShow.Enabled := False;
chkFmtNum.Enabled := False;
cbxStyle.enabled := False;
cbxSize.Enabled := False;
cbxJust.Enabled := false;
lbStyle.Enabled := False;
lbSize.Enabled := false;
lbJust.Enabled := False;
//disable the numbers
lbRound.enabled := false;
cbxRound.Enabled := false;
chkComma.Enabled := False;
chkPlusSign.Enabled := False;
chkDispZero.Enabled := False;
//disable the dates
radMY.Enabled := False;
radMDY.Enabled := False;
radMDYYYY.Enabled := False;
radShortM.Enabled := False;
radLongM.Enabled := False;
end
else //its a text type cell
begin
ImageScaleVal.text := '100';
ImageScaleBar.Position := 100;
ImageScaleVal.Enabled := False;
ImageScaleBar.enabled := False;
chkStretch.enabled := False;
chkAspectRatio.enabled := False;
chkCenter.enabled := False;
chkFrame.enabled := False;
lbScale.Enabled := false;
chkAutoFit.Enabled := appPref_AutoFitTextToCell and not IsAppPrefSet(bNotAutoFitTextTocell);
PageMgr.ActivePage := General; //set it to the right tab
// General
chkTrans.checked := IsBitSet(FPref, bCelTrans);
chkTransInto.Checked := not IsBitSet(FPref,bNoTransferInto);
chkCalc.checked := IsBitSet(FPref, bCelCalc);
if appPref_AutoFitTextToCell then
chkAutoFit.Checked := IsBitSet(FPref, bNotAutoFitTextTocell)
else
chkAutoFit.Checked := true; //don't do auto fit font to cell
chkOnlyNum.checked := IsBitSet(FPref, bCelNumOnly);
chkOnlyDate.checked := IsBitSet(FPref, bCelDateOnly);
ChkOnlyShow.checked := IsBitSet(FPref, bCelDispOnly);
chkFmtNum.checked := IsBitSet(FPref, bCelFormat);
chkSkip.checked := IsBitSet(FPref, bCelSkip);
if IsBitSet(FPref, bNoChgToCPref) then begin
chkOnlyNum.Enabled := False;
chkOnlyDate.Enabled := False;
ChkOnlyShow.Enabled := False;
chkFmtNum.Enabled := False;
end;
//Set Style, Just and font size
if Supports(FEditor, ITextFormat, format) then
begin
cbxJust.ItemIndex := format.TextJustification;
cbxStyle.ItemIndex := format.Font.StyleBits;
if (format.Font.Size >= 6) and (format.Font.Size <= 14) then
cbxSize.ItemIndex := format.Font.Size - 6
else
cbxSize.Text := IntToStr(format.Font.Size);
end;
// Number format
chkComma.checked := IsBitSet(FFormat, bAddComma);
chkPlusSign.checked := IsBitSet(FFormat, bAddPlus);
chkDispZero.checked := IsBitSet(FFormat, bDisplayZero);
// number rounding
if IsBitSet(FFormat,bRnd1000) then
cbxRound.itemIndex := bRnd1000;
if IsBitSet(FFormat,bRnd500) then
cbxRound.itemIndex := bRnd500;
if IsBitSet(FFormat,bRnd100) then
cbxRound.itemIndex := bRnd100;
if IsBitSet(FFormat,bRnd1) then
cbxRound.itemIndex := bRnd1;
if IsBitSet(FFormat,bRnd1P1) then
cbxRound.itemIndex := bRnd1P1;
if IsBitSet(FFormat,bRnd1P2) then
cbxRound.itemIndex := bRnd1P2;
if IsBitSet(FFormat,bRnd1P3) then
cbxRound.itemIndex := bRnd1P3;
if IsBitSet(FFormat,bRnd1P4) then
cbxRound.itemIndex := bRnd1P4;
if IsBitSet(FFormat,bRnd1P5) then
cbxRound.itemIndex := bRnd1P5;
if IsBitSet(FFormat, bRnd5) then //Ticket #1541 add round to 5
cbxRound.ItemIndex := bRnd5;
//if its a number cell, then show the Number cell prefs
if FCell.FSubType = cKindCalc then
PageMgr.ActivePage := Number;
radMY.checked := IsBitSet(FFormat, bDateMY);
radMDY.checked := IsBitSet(FFormat, bDateMDY);
radMDYYYY.checked := IsBitSet(FFormat, bDateMD4Y);
//### we do not yet handle long and short dates in UUtil1 conversion
radShortM.Enabled := False;
radLongM.Enabled := False;
radShortM.checked := IsBitSet(FFormat, bDateShort);
radLongM.checked := IsBitSet(FFormat, bDateLong);
end;
end;
end;
procedure TCellPref.SaveChanges;
var
format: ITextFormat;
begin
if (FEditor is TGraphicEditor) then
with FEditor as TGraphicEditor do begin
FStretch := chkStretch.checked;
FAspRatio := chkAspectRatio.checked;
FCenter := chkCenter.checked;
FPrFrame := chkFrame.checked;
FEditScale := ImageScaleBar.Position;
end
else
begin
FPref := SetBit2Flag(FPref, bCelTrans, chkTrans.checked);
FPref := SetBit2Flag(FPref, bNoTransferInto, not chkTransInto.Checked); //YF 06.07.02
FPref := SetBit2Flag(FPref, bCelCalc, chkCalc.checked);
FPref := SetBit2Flag(FPref, bCelNumOnly, chkOnlyNum.checked);
FPref := SetBit2Flag(FPref, bCelDispOnly, ChkOnlyShow.checked);
FPref := SetBit2Flag(FPref, bCelDateOnly, chkOnlyDate.checked);
FPref := SetBit2Flag(FPref, bCelFormat, chkFmtNum.checked);
FPref := SetBit2Flag(FPref, bCelSkip, chkSkip.checked);
if appPref_AutoFitTextToCell then
FPref := SetBit2Flag(FPref, bNotAutoFitTextTocell, chkAutoFit.Checked)
else
; //leave the cell flag unchanged if global flag set don't auto fit
//Number Rounding
FFormat := 0; //clear previous settings
FFormat := SetBit(FFormat, cbxRound.itemIndex);
FFormat := SetBit2Flag(FFormat, bDisplayZero, chkDispZero.checked);
FFormat := SetBit2Flag(FFormat, bAddComma, chkComma.checked);
FFormat := SetBit2Flag(FFormat, bAddPlus, chkPlusSign.checked);
//Dates
FFormat := SetBit2Flag(FFormat, bDateMY, radMY.checked);
FFormat := SetBit2Flag(FFormat, bDateMDY, radMDY.checked);
FFormat := SetBit2Flag(FFormat, bDateMD4Y, radMDYYYY.checked);
FFormat := SetBit2Flag(FFormat, bDateShort, radShortM.checked);
FFormat := SetBit2Flag(FFormat, bDateLong, radLongM.checked);
//display the Text characteristics
if Supports(FEditor, ITextFormat, format) then
begin
format.TextJustification := cbxJust.ItemIndex;
format.Font.Size := StrToInt(cbxSize.Text);
format.Font.StyleBits := cbxStyle.ItemIndex;
end;
//save the changes to editor
FEditor.SetFormat(FFormat);
FEditor.SetPreferences(FPref);
end;
FEditor.FModified := true;
end;
procedure TCellPref.ImageScaleBarChange(Sender: TObject);
begin
ImageScaleVal.Text := IntToStr(ImageScaleBar.Position);
UpdateImage;
end;
procedure TCellPref.UpdateImage;
begin
if (FEditor is TGraphicEditor) then
with FEditor as TGraphicEditor do
begin
ResetView(chkStretch.checked, chkCenter.checked, chkAspectRatio.Checked, ImageScaleBar.position);
DisplayCurCell;
end;
end;
procedure TCellPref.chkFitClick(Sender: TObject);
begin
if chkStretch.Checked then begin
chkAspectRatio.checked := false;
chkCenter.checked := false;
ImageScaleVal.enabled := false;
ImageScaleBar.enabled := false;
end
else begin
ImageScaleVal.enabled := True;
ImageScaleBar.enabled := True;
end;
UpdateImage;
end;
procedure TCellPref.chkAspectClick(Sender: TObject);
begin
UpdateImage;
end;
procedure TCellPref.chkCntrClick(Sender: TObject);
begin
if chkCenter.checked then
chkStretch.Checked := False;
UpdateImage;
end;
procedure TCellPref.btnCancelClick(Sender: TObject);
begin
if (FEditor is TGraphicEditor) then
with FEditor as TGraphicEditor do begin //canceled so reset the original settings
FStretch := FOrgFit;
FAspRatio := FOrgAspect;
FCenter := FOrgCntr;
FPrFrame := FOrgFrame;
FEditScale := FOrgScale;
ResetView(FStretch, FCenter, FAspRatio, FEditScale);
DisplayCurCell;
end;
end;
end.
|
unit cvr_actor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ExtCtrls, Forms;
type
{ TActor }
TActor = class
private
hp: Integer;
public
form: TForm;
posX, posY: Integer;
toX: Integer;
toY: Integer;
speed: Integer;
actorTimer: TTimer;
MAX_HP: Integer;
isDie: boolean;
constructor create(f: TForm; py, px: Integer); virtual;
procedure update(Sender: TObject); virtual;
procedure translate(x,y,s: Integer); virtual;
procedure translateVector(x,y,s: Integer); virtual;
function getHp(): integer;
procedure addHp(hp_: Integer);
procedure setHp(hp_: Integer);
end;
implementation
{ TActor }
constructor TActor.create(f: TForm; py, px: Integer);
begin
form := f;
posX := px;
posY := py;
actorTimer := TTimer.create(form);
actorTimer.Interval := 10;
actorTimer.OnTimer := @update;
hp := MAX_HP;
isDie := false;
end;
procedure TActor.update(Sender: TObject);
begin
if(toX > posX) then
begin
if(toX < posX + speed) then
begin
speed := toX - posX;
end;
posX := posX + speed;
end else
if(toX < posX) then
begin
if(toX > posX - speed) then
begin
speed := posX - toX;
end;
posX := posX - speed;
end;
if(toY > posY) then
begin
if(toY < posY + speed) then
begin
speed := toY - posY;
end;
posY := posY + speed;
end else
if(toY < posY) then
begin
if(toY > posY - speed) then
begin
speed := posY - toY;
end;
posY := posY - speed;
end;
end;
{ Перемещение актора по вектору(posX + x) с определенной скоростью(s) }
procedure TActor.translateVector(x, y, s: Integer);
begin
toX := posX + x;
toY := posY + y;
speed := s;
end;
function TActor.getHp: integer;
begin
getHp := hp;
end;
procedure TActor.addHp(hp_: Integer);
begin
hp := hp + hp_;
if(self.hp > MAX_HP) then
begin
self.hp := MAX_HP;
end else
if(self.hp <= 0) then
begin
isDie := true;
end;
end;
procedure TActor.setHp(hp_: Integer);
begin
hp := hp_;
if(self.hp > MAX_HP) then
begin
self.hp := MAX_HP;
end else
if(self.hp <= 0) then
begin
isDie := true;
end;
end;
{ Перемещение актора в точку(x) с определенной скоростью(s) }
procedure TActor.translate(x, y, s: Integer);
begin
toX := x;
toY := y;
speed := s;
end;
end.
|
{******************************************************************************}
{ }
{ Indy (Internet Direct) - Internet Protocols Simplified }
{ }
{ https://www.indyproject.org/ }
{ https://gitter.im/IndySockets/Indy }
{ }
{******************************************************************************}
{ }
{ This file is part of the Indy (Internet Direct) project, and is offered }
{ under the dual-licensing agreement described on the Indy website. }
{ (https://www.indyproject.org/license/) }
{ }
{ Copyright: }
{ (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. }
{ }
{******************************************************************************}
{ }
{ Originally written by: Fabian S. Biehn }
{ fbiehn@aagon.com (German & English) }
{ }
{ Contributers: }
{ Here could be your name }
{ }
{******************************************************************************}
unit IdOpenSSLIOHandlerServer;
interface
{$i IdCompilerDefines.inc}
uses
IdIOHandler,
IdOpenSSLContext,
IdOpenSSLContextServer,
IdOpenSSLOptionsServer,
IdSocketHandle,
IdSSL,
IdThread,
IdYarn;
type
TIdOpenSSLIOHandlerServer = class(TIdServerIOHandlerSSLBase)
private
FOptions: TIdOpenSSLOptionsServer;
FContext: TIdOpenSSLContextServer;
FOpenSSLLoaded: Boolean;
protected
function GetOptionClass: TIdOpenSSLOptionsServerClass; virtual;
procedure InitComponent; override;
procedure BeforeInitContext(const AContext: TIdOpenSSLContext); virtual;
procedure AfterInitContext(const AContext: TIdOpenSSLContext); virtual;
public
destructor Destroy; override;
procedure Init; override;
procedure Shutdown; override;
function Accept(ASocket: TIdSocketHandle; AListenerThread: TIdThread;
AYarn: TIdYarn): TIdIOHandler; override;
// Abstract functions from TIdServerIOHandlerSSLBase
function MakeClientIOHandler: TIdSSLIOHandlerSocketBase; override;
function MakeFTPSvrPort: TIdSSLIOHandlerSocketBase; override;
function MakeFTPSvrPasv: TIdSSLIOHandlerSocketBase; override;
published
property Options: TIdOpenSSLOptionsServer read FOptions;
end;
implementation
uses
IdOpenSSLExceptions,
IdOpenSSLIOHandlerClientServer,
IdOpenSSLLoader,
SysUtils;
{ TIdOpenSSLIOHandlerServer }
function TIdOpenSSLIOHandlerServer.Accept(ASocket: TIdSocketHandle;
AListenerThread: TIdThread; AYarn: TIdYarn): TIdIOHandler;
var
LIOHandler: TIdOpenSSLIOHandlerClientForServer;
begin
LIOHandler := MakeClientIOHandler() as TIdOpenSSLIOHandlerClientForServer;
try
LIOHandler.PassThrough := True;
LIOHandler.Open;
if not LIOHandler.Binding.Accept(ASocket.Handle) then
FreeAndNil(LIOHandler);
except
FreeAndNil(LIOHandler);
raise;
end;
Result := LIOHandler;
end;
procedure TIdOpenSSLIOHandlerServer.AfterInitContext(
const AContext: TIdOpenSSLContext);
begin
end;
procedure TIdOpenSSLIOHandlerServer.BeforeInitContext(
const AContext: TIdOpenSSLContext);
begin
end;
destructor TIdOpenSSLIOHandlerServer.Destroy;
begin
FOptions.Free();
inherited;
end;
function TIdOpenSSLIOHandlerServer.GetOptionClass: TIdOpenSSLOptionsServerClass;
begin
Result := TIdOpenSSLOptionsServer;
end;
procedure TIdOpenSSLIOHandlerServer.Init;
var
LLoader: IOpenSSLLoader;
begin
inherited;
LLoader := GetOpenSSLLoader();
if not FOpenSSLLoaded and Assigned(LLoader) and not LLoader.Load() then
raise EIdOpenSSLLoadError.Create('Failed to load OpenSSL');
FOpenSSLLoaded := True;
FContext := TIdOpenSSLContextServer.Create();
try
BeforeInitContext(FContext);
FContext.Init(FOptions);
AfterInitContext(FContext);
except
on E: EExternalException do
begin
try
FreeAndNil(FContext);
except
on E: EExternalException do ; // Nothing
end;
raise EIdOpenSSLLoadError.Create('Failed to load OpenSSL');
end;
end;
end;
procedure TIdOpenSSLIOHandlerServer.InitComponent;
begin
inherited;
FOptions := GetOptionClass().Create();
end;
function TIdOpenSSLIOHandlerServer.MakeClientIOHandler: TIdSSLIOHandlerSocketBase;
var
LHandler: TIdOpenSSLIOHandlerClientForServer;
begin
LHandler := TIdOpenSSLIOHandlerClientForServer.Create(nil);
LHandler.SetServerContext(FContext);
Result := LHandler;
end;
function TIdOpenSSLIOHandlerServer.MakeFTPSvrPasv: TIdSSLIOHandlerSocketBase;
begin
Result := MakeClientIOHandler();
end;
function TIdOpenSSLIOHandlerServer.MakeFTPSvrPort: TIdSSLIOHandlerSocketBase;
begin
Result := MakeClientIOHandler();
end;
procedure TIdOpenSSLIOHandlerServer.Shutdown;
begin
inherited;
FContext.Free();
end;
end.
|
function floor (y:real): real;
Var m:real;
Begin
if y < 0 then m := int(y) - 1
else m := int(y);
floor := m;
End;
|
(*
Vorbis file in/out components
This file is a part of Audio Components Suite.
All rights reserved. See the license file for more details.
Copyright (c) 2002-2010, Andrei Borovsky, anb@symmetrica.net
Copyright (c) 2005-2006 Christian Ulrich, mail@z0m3ie.de
Copyright (c) 2014-2015 Sergey Bodrov, serbod@gmail.com
*)
{
Status:
TVorbisOut - not updated
TVorbisIn - AcsBuffer, tested
}
unit acs_vorbis;
{$DEFINE USE_VORBIS_11}
interface
uses
{$IFDEF LINUX}
baseunix,
{$ENDIF}
ACS_File, Classes, SysUtils, ACS_Classes, ogg, vorbiscodec, VorbisFile, VorbisEnc,
ACS_Strings, acs_tags, acs_types;
type
TVorbisBitRate = (brAutoSelect, br24, br32, br45, br48, br56, br64, br80, br96,
br112, br128, br144, br160, br192, br224, br256, br320, br499);
{ TVorbisOut }
(* The Ogg Vorbis encoder component. More information on the Ogg Vorbis format
may be found at http://xiph.org/vorbis/.
Requires:
- ogg.dll
- vorbis.dll
- vorbisenc.dll
- vorbisfile.dll
*)
TVorbisOut = class(TAcsCustomFileOut)
private
FSerial: Integer;
FDesiredNominalBitrate: TVorbisBitRate;
FDesiredMaximumBitrate: TVorbisBitRate;
FMinimumBitrate: TVorbisBitRate;
OggSS: ogg_stream_state;
OggPg: ogg_page;
OggPk: ogg_packet;
VInfo: vorbis_info;
VComm: vorbis_comment;
Vdsp: vorbis_dsp_state;
VBlock: vorbis_block;
header, header_comm, header_code: ogg_packet;
FCompression: Single;
EndOfStream: Boolean;
FComments: TStringList;
FTags: TVorbisTags;
procedure SetComments(AComments: TStringList);
procedure SetTags(AValue: TVorbisTags);
procedure SetDesiredNominalBitrate(AValue: TVorbisBitRate);
procedure SetDesiredMaximumBitrate(AValue: TVorbisBitRate);
procedure SetMinimumBitrate(AValue: TVorbisBitRate);
procedure InitVorbis();
protected
procedure SetFileMode(AMode: TAcsFileOutputMode); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init(); override;
procedure Done(); override;
function DoOutput(Abort: Boolean):Boolean; override;
published
(* Property: Compression
Set the compression ratio for the file being
created. The valid values vary from -0.1 (maximum compression, lowest
quality) to 1.0 (minimum compression, highest quality). If
<DesiredNominalBitrate> property is assigned a value other than
brAutoSelect, Compression property is ignored. *)
property Compression: Single read FCompression write FCompression stored True;
(* Property: Comments
Add tags (comments) to an Ogg Vorbis file. The
standard comments include Artist, Album, Title, Date, Genre, and Track. *)
property Tags: TVorbisTags read FTags write SetTags;
property Comments: TStringList read FComments write SetComments stored True;
(* Property: DesiredMaximumBitrate
Set the desired maximum bitrate limit for the file
being created. The values of this property are brXXX constants,
indicating bitrates in kbps. Depending on the parameters of the incoming
audio data the actual maximum bitrate may be higher than that specified
with this property. This property has an effect only if
<DesiredNominalBitrate> property is assigned a value other than
brAutoSelect. *)
property DesiredMaximumBitrate: TVorbisBitRate read FDesiredMaximumBitrate write SetDesiredMaximumBitrate;
(* Property: DesiredNominalBitrate
If this property is set to a value other than brAutoSelect (the default
value), the Compression property is ignored and the size/quality of the
output file are determined by the values of <DesiredNominalBitrate>,
<DesiredMaximumBitrate>, and <MinimumBitrate> properties. The values of
this property are brXXX constants, indicating bitrates in kbps.
Depending on the parameters of the incoming audio data the output file's
actual nominal bitrate may be different from that specified with this
property.
Note:
It is recommended by Ogg Vorbis developers to use the <Compression>
property rather than specify bitrates directly. *)
property DesiredNominalBitrate: TVorbisBitRate read FDesiredNominalBitrate write SetDesiredNominalBitrate;
(* Property: MinimumBitrate
Set the minimum bitrate limit for the file being
created. The values of this property are brXXX constants, indicating
bitrates in kbps. This property has an effect only if
DesiredNominalBitrate property is assigned a value other than
brAutoSelect.*)
property MinimumBitrate: TVorbisBitRate read FMinimumBitrate write SetMinimumBitrate;
(* Property: Serial
Set the serial number of the logical bitstream in
the Vorbis file. The value of this property is of concern only if you
create multi-streamed Vorbis files (in foAppend mode). *)
property Serial: Integer read FSerial write FSerial;
//property Vendor: String read FVendor write FVendor;
end;
(* Class: TVorbisIn
The Ogg Vorbis decoder component. More
information on the Ogg Vorbis format may be found at
http://xiph.org/vorbis/.
Requires:
- ogg.dll
- vorbis.dll
- vorbisenc.dll
- vorbisfile.dll *)
{ TVorbisIn }
TVorbisIn = class(TAcsCustomFileIn)
private
FComments: TStringList;
FTags : TVorbisTags;
//FVendor: String;
VFile: OggVorbis_File;
cursec: Integer;
FMaxBitrate: Integer;
FNominalBitrate: Integer;
FMinBitrate: Integer;
EndOfStream: Boolean;
function GetMaxBitrate(): Integer;
function GetNominalBitrate(): Integer;
function GetMinBitrate(): Integer;
function GetComments(): TStringList;
function GetTags(): TVorbisTags;
function GetBitStreams(): Integer;
function GetInstantBitRate(): Integer;
function GetCurrentBitStream(): Integer;
procedure SetCurrentBitStream(BS: Integer);
protected
procedure OpenFile; override;
procedure CloseFile; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetData(ABuffer: Pointer; ABufferSize: Integer): Integer; override;
function Seek(SampleNum: Integer): Boolean; override;
(* Property: BitStreams
Read this property to get number of logical bitstreams in the
multi-streamed file. By default the component plays all the bitstreams
from the first to the last just as if they were the same bitstream. The
playback time also refers to the total time of all the bitstreams. You
need to handle bitstream-related properties only if you want to
navigate between several bitstreams in a multi-streamed file. *)
property BitStreams: Integer read GetBitStreams;
(* Property: Comments
Read tags (comments) added to an Ogg Vorbis file.
The standard comments include Artist, Album, Title, Date, Genre, and
Track. *)
property Tags: TVorbisTags read GetTags;
property Comments: TStringList read GetComments;
(* Property: CurrentBitStream
Read this property to get the number of the current bitstream being
played (0 < = CurrentBitStream < BitStreams). Assigning a value to this
property makes the component start playback from the beginning of the
specified logical bitstream. This property can be used only during
actual playback process. *)
property CurrentBitStream: Integer read GetCurrentBitStream write SetCurrentBitStream;
(* Property: InstantBitRate
Get current bitrate (in bits per second) of the VBR-encoded Vorbis file. *)
property InstantBitRate: Integer read GetInstantBitRate;
(* Property: MaxBitrate
Get the maximum bitrate (in bits per second) of the Vorbis file. *)
property MaxBitrate: Integer read GetMaxBitrate;
(* Property: MinBitrate
Get the minimum bitrate (in bits per second) of the Vorbis file. *)
property MinBitrate: Integer read GetMinBitrate;
(* Property: NominalBitrate
Get the nominal bitrate (in bits per second) of the Vorbis file. *)
property NominalBitrate: Integer read GetNominalBitrate;
//property Vendor: String read FVendor;
published
property EndSample;
property StartSample;
end;
implementation
function cbRead(ptr: Pointer; size, nmemb: Cardinal; const datasource: Pointer): Cardinal; cdecl;
var
VI: TVorbisIn;
//Buffer: array of Byte;
begin
VI:=TVorbisIn(datasource);
//SetLength(Buffer, size*nmemb);
//Result:=VI.FStream.Read(Buffer[0], size*nmemb);
Result:=VI.FStream.Read(ptr^, size*nmemb);
//Move(Buffer[0], ptr^, Result);
//SetLength(Buffer, 0);
end;
function cbSeek(const datasource: Pointer; offset: ogg_int64_t; whence: Integer): Integer; cdecl;
var
VI: TVorbisIn;
Origin: TSeekOrigin;
begin
VI:=TVorbisIn(datasource);
if not VI.Seekable then
begin
Result:=-1;
Exit;
end;
case whence of
SEEK_SET: Origin:=TSeekOrigin(soFromBeginning);
SEEK_CUR: Origin:=TSeekOrigin(soFromCurrent);
SEEK_END: Origin:=TSeekOrigin(soFromEnd);
end;
Result:=VI.FStream.Seek(offset, Origin);
end;
function cbClose(const datasource: Pointer): Integer; cdecl;
var
VI: TVorbisIn;
begin
VI:=TVorbisIn(datasource);
if Assigned(VI.FStream) then FreeAndNil(VI.FStream);
Result:=0;
end;
function cbTell(const datasource: Pointer): Integer; cdecl;
var
VI: TVorbisIn;
begin
VI:=TVorbisIn(datasource);
Result:=VI.FStream.Position
end;
function VorbisBitrateToInt(Bitrate: TVorbisBitrate): Integer;
begin
case Bitrate of
br24: Result:=24000;
br32: Result:=32000;
br45: Result:=45000;
br48: Result:=48000;
br56: Result:=46000;
br64: Result:=64000;
br80: Result:=80000;
br96: Result:=96000;
br112: Result:=112000;
br128: Result:=128000;
br144: Result:=144000;
br160: Result:=160000;
br192: Result:=192000;
br224: Result:=224000;
br256: Result:=256000;
br320: Result:=320000;
br499: Result:=499000;
else Result:=-1;
end;
end;
{ TVorbisOut }
constructor TVorbisOut.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBufferSize:=$10000; // default buffer size
FCompression:=0.2;
FComments:=TStringList.Create();
FTags:=TVorbisTags.Create();
FDesiredNominalBitrate:=brAutoSelect;
FDesiredMaximumBitrate:=brAutoSelect;
FMinimumBitrate:=brAutoSelect;
if not (csDesigning in ComponentState) then
begin
if not LiboggLoaded then
raise EAcsException.Create(Format(strCoudntloadLib,[Liboggpath]));
if not LibvorbisLoaded then
raise EAcsException.Create(Format(strCoudntloadLib,[LibvorbisPath]));
if not LibvorbisfileLoaded then
raise EAcsException.Create(Format(strCoudntloadLib,[LibvorbisfilePath]));
if not LibvorbisencLoaded then
raise EAcsException.Create(Format(strCoudntloadLib,[LibvorbisencPath]));
end;
end;
destructor TVorbisOut.Destroy();
begin
FreeAndNil(FTags);
FreeAndNil(FComments);
inherited Destroy();
end;
procedure TVorbisOut.SetComments(AComments: TStringList);
begin
FComments.Assign(AComments);
end;
procedure TVorbisOut.SetTags(AValue: TVorbisTags);
begin
FTags.Assign(AValue);
end;
procedure TVorbisOut.Init();
var
i, maxbr, minbr, nombr: Integer;
Name, Value: String;
begin
inherited Init();
if FFileMode = foAppend then
FStream.Seek(0, soFromEnd);
EndOfStream:=False;
InitVorbis();
(*
vorbis_info_init(VInfo);
if DesiredNominalBitrate = brAutoSelect then
begin
{$IFNDEF USE_VORBIS_11}
vorbis_encode_init_vbr(VInfo, FInput.Channels, FInput.SampleRate, FCompression);
{$ENDIF}
{$IFDEF USE_VORBIS_11}
vorbis_encode_setup_vbr(VInfo, FInput.Channels, FInput.SampleRate, FCompression);
vorbis_encode_setup_init(VInfo);
{$ENDIF}
end
else
begin
nombr:=VorbisBitrateToInt(FDesiredNominalBitrate);
maxbr:=VorbisBitrateToInt(FDesiredMaximumBitrate);
if maxbr < nombr then maxbr:=nombr;
minbr:=VorbisBitrateToInt(Self.FMinimumBitrate);
if minbr < 0 then minbr:=nombr;
vorbis_encode_init(VInfo, FInput.Channels, FInput.SampleRate, maxbr, nombr, minbr);
end;
vorbis_comment_init(VComm);
for i:=0 to FComments.Count-1 do
begin
Name:=FComments.Names[i];
Value:=FComments.Values[Name];
vorbis_comment_add_tag(VComm, PChar(Name), PChar(Value));
end;
vorbis_analysis_init(Vdsp, VInfo);
vorbis_block_init(Vdsp, VBlock);
ogg_stream_init(OggSS, FSerial);
vorbis_analysis_headerout(Vdsp, VComm, header, header_comm, header_code);
ogg_stream_packetin(OggSS, header);
ogg_stream_packetin(OggSS, header_comm);
ogg_stream_packetin(OggSS, header_code);
while ogg_stream_flush(OggSS, OggPg) <> 0 do
begin
FStream.Write(OggPg.header^, OggPg.header_len);
FStream.Write(OggPg.body^, OggPg.body_len);
end;
*)
end;
procedure TVorbisOut.Done();
begin
FComments.Clear();
FTags.Clear();
ogg_stream_clear(OggSS);
vorbis_block_clear(VBlock);
vorbis_dsp_clear(Vdsp);
vorbis_comment_clear(VComm);
vorbis_info_clear(VInfo);
inherited Done();
end;
function TVorbisOut.DoOutput(Abort: Boolean):Boolean;
var
i, j, SamplesRead, BytesPerSample : LongWord;
Len: LongWord;
out_buf: PPFloat;
tmpBuf: array[0..16] of PFloat;
buf8: PAcsBuffer8;
Ptr : Pointer;
wres : Integer;
begin
// No exceptions Here
Result:=True;
if not CanOutput then Exit;
if Abort or EndOfStream then
begin
(* We don't close file here to avoide exceptions
if output componenet's Stop method is called *)
Result:=False;
Exit;
end;
Len:=FillBufferFromInput();
BytesPerSample := FInput.Channels * (FInput.BitsPerSample div 8);
SamplesRead := Len div BytesPerSample;
out_buf := vorbis_analysis_buffer(Vdsp, FBuffer.Size);
if Len <> 0 then
begin
buf8:=FBuffer.Memory;
if FInput.BitsPerSample = 16 then
begin
tmpBuf[0] := out_buf^;
for j := 1 to FInput.Channels - 1 do
begin
Inc(out_buf);
tmpBuf[j] := out_buf^;
end;
for i:=0 to SamplesRead - 1 do
for j := 0 to Finput.Channels - 1 do
tmpBuf[j][i] := buf8[i * FInput.Channels + j]/$8000;
end
else if FInput.BitsPerSample = 8 then
begin
tmpBuf[0] := out_buf^;
for j := 1 to FInput.Channels - 1 do
begin
Inc(out_buf);
tmpBuf[j] := out_buf^;
end;
for i := 0 to SamplesRead - 1 do
for j := 0 to FInput.Channels - 1 do
tmpBuf[j][i] := (buf8[i*FInput.Channels + j] - 128)/128;
end
else // 24 bit
begin
tmpBuf[0] := out_buf^;
for j := 1 to FInput.Channels - 1 do
begin
Inc(out_buf);
tmpBuf[j] := out_buf^;
end;
for i := 0 to SamplesRead - 1 do
for j := 0 to FInput.Channels - 1 do
tmpBuf[j][i] := ((PSmallInt(@buf8[i*BytesPerSample + j*3 + 1])^ shl 8)
+ buf8[i*BytesPerSample + j*3])/8388608;
end;
vorbis_analysis_wrote(Vdsp, SamplesRead);
end
else // if Len <> 0
vorbis_analysis_wrote(Vdsp, 0);
while vorbis_analysis_blockout(Vdsp, VBlock) = 1 do
begin
vorbis_analysis(VBlock, nil);
vorbis_bitrate_addblock(VBlock);
while vorbis_bitrate_flushpacket(Vdsp, OggPk) <> 0 do
begin
ogg_stream_packetin(OggSS, OggPk);
while not EndOfStream do
begin
if ogg_stream_pageout(OggSS, OggPg) = 0 then Break;
wres := FStream.Write(OggPg.header^, OggPg.header_len);
if wres <> OggPg.header_len then
raise EAcsException.Create('Error writing ogg file');
wres := FStream.Write(OggPg.body^, OggPg.body_len);
if wres <> OggPg.body_len then
raise EAcsException.Create('Error writing ogg file');
if ogg_page_eos(OggPg) <> 0 then EndOfStream := True;
end;
end;
end;
end;
{ TVorbisIn }
constructor TVorbisIn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBufferSize:=$8000;
FComments:=TStringList.Create();
FTags:=TVorbisTags.Create();
if not (csDesigning in ComponentState) then
begin
if not LiboggLoaded then
raise EAcsException.Create(Format(strCoudntloadLib, [LiboggPath]));
if not LibvorbisLoaded then
raise EAcsException.Create(Format(strCoudntloadLib, [LibvorbisPath]));
if not LibvorbisfileLoaded then
raise EAcsException.Create(Format(strCoudntloadLib, [LibvorbisfilePath]));
if not LibvorbisencLoaded then
raise EAcsException.Create(Format(strCoudntloadLib, [LibvorbisencPath]));
end;
end;
destructor TVorbisIn.Destroy();
begin
FreeAndNil(FTags);
FreeAndNil(FComments);
inherited Destroy();
end;
procedure TVorbisIn.OpenFile();
var
PVComm: PVORBIS_COMMENT;
PVInfo: PVORBIS_INFO;
PComment: PPAnsiChar;
Comment: PAnsiChar;
StrComment: AnsiString;
Callbacks: OV_CALLBACKS;
res, n : Integer;
CN, CV : String;
begin
OpenCS.Enter();
try
inherited OpenFile();
if FOpened then
begin
FValid:=False;
EndOfStream:=False;
Callbacks.read_func:=cbRead;
Callbacks.close_func:=cbClose;
Callbacks.seek_func:=cbSeek;
Callbacks.tell_func:=cbTell;
res:=ov_open_callbacks(Self, VFile, nil, 0, Callbacks);
if res <> 0 then
raise EAcsException.Create('Failed to open an ogg file: ' + IntToStr(res));
ov_test_open(VFile);
FComments.Clear();
PVComm:=ov_comment(VFile, -1);
PComment:=PVComm.user_comments;
Comment:=PComment^;
while Comment <> nil do
begin
StrComment:=Comment;
FComments.Add(StrComment);
n:=Pos('=', StrComment);
CN := Copy(StrComment, 1, n-1);
CV := Copy(StrComment, n+1, MaxInt);
CN := AnsiLowerCase(CN);
if CN = _vorbis_Artist then FTags.Artist := UTF8Decode(CV)
else if CN = _vorbis_Album then FTags.Album := UTF8Decode(CV)
else if CN = _vorbis_Title then FTags.Title := UTF8Decode(CV)
else if CN = _vorbis_Date then FTags.Date := UTF8Decode(CV)
else if CN = _vorbis_Genre then FTags.Genre := UTF8Decode(CV)
else if CN = _vorbis_Track then FTags.Track := UTF8Decode(CV);
Inc(PtrUInt(PComment), SizeOf(PVComm.user_comments));
Comment:=PComment^;
end;
//FVendor:=PVComm.vendor;
PVInfo:=ov_info(VFile, -1);
FChan:=PVInfo.channels;
FSR:=PVInfo.rate;
FBPS:=16;
FMaxBitrate:=PVInfo.bitrate_upper;
FNominalBitrate:=PVInfo.bitrate_nominal;
FMinBitrate:=PVInfo.bitrate_lower;
FTotalSamples:=ov_pcm_total(VFile, -1);
FSize:=(FTotalSamples shl 1) * PVInfo.channels;
cursec:=-1;
FTotalTime:=ov_time_total(VFile, -1);
//ov_pcm_seek(VFile, FOffset);
FValid:=True;
FOpened:=True;
end;
finally
OpenCS.Leave();
end;
end;
procedure TVorbisIn.CloseFile();
begin
OpenCS.Enter();
try
if FOpened then
begin
//if ov_seekable(VFile) <> 0 then ov_pcm_seek(VFile, 0);
ov_clear(VFile);
FOpened:=False;
end;
inherited CloseFile();
finally
OpenCS.Leave();
end;
end;
function TVorbisIn.GetData(ABuffer: Pointer; ABufferSize: Integer): Integer;
var
Len, offs, BufSizeRemain: Integer;
begin
if not Active then
raise EAcsException.Create('The Stream is not opened');
if FAudioBuffer.UnreadSize <= 0 then
begin
{
// seek if offset defined
if FOffset <> 0 then
begin
offs:=Round((FOffset/100)*FSize);
FPosition:=FPosition + offs;
if FPosition < 0 then FPosition:=0
else if FPosition > FSize then FPosition:=FSize;
//tmp:=(FPosition/FSize)*FTime;
if ov_seekable(VFile) <> 0 then
ov_pcm_seek(VFile, (FPosition shr 1) div FChan);
FOffset:=0;
end;
}
FAudioBuffer.Reset();
BufSizeRemain:=FAudioBuffer.Size;
if not EndOfStream then
begin
(* The ov_read function can return data in quite small chunks
(of about 512 bytes). We keep reading data until the ABuffer is filled
or there is no more data to read. *)
while BufSizeRemain > 0 do
begin
Len:=ov_read(VFile, (FAudioBuffer.Memory+FAudioBuffer.WritePosition), BufSizeRemain, 0, 2, 1, @cursec);
FAudioBuffer.WritePosition:=FAudioBuffer.WritePosition + Len;
Dec(BufSizeRemain, Len);
if Len <= 0 then
begin
EndOfStream:=True;
Break;
end;
end;
end;
end;
Result:=ABufferSize;
if Result > FAudioBuffer.UnreadSize then
Result:=FAudioBuffer.UnreadSize;
FAudioBuffer.Read(ABuffer^, Result);
Inc(FPosition, Result);
end;
function TVorbisIn.GetMaxBitrate(): Integer;
begin
Result:=FMaxBitrate;
end;
function TVorbisIn.GetNominalBitrate(): Integer;
begin
Result:=FNominalBitrate;
end;
function TVorbisIn.GetComments(): TStringList;
begin
Result:=FComments;
end;
function TVorbisIn.GetTags(): TVorbisTags;
begin
Result:=FTags;
end;
function TVorbisIn.GetMinBitrate(): Integer;
begin
Result:=FMinBitrate;
end;
procedure TVorbisOut.SetFileMode(AMode: TAcsFileOutputMode);
begin
FFileMode:=AMode;
end;
function TVorbisIn.GetBitStreams(): Integer;
begin
Result:=0;
if Active then
begin
if ov_seekable(VFile)<>0 then
Result:=ov_streams(VFile);
end;
end;
function TVorbisIn.GetInstantBitRate(): Integer;
begin
Result:=0;
if Active then
begin
Result:=ov_bitrate_instant(VFile);
end;
end;
function TVorbisIn.GetCurrentBitStream(): Integer;
begin
Result:=-1;
if Active then
begin
if ov_seekable(VFile)<>0 then
Result:=VFile.current_link;
end;
end;
procedure TVorbisIn.SetCurrentBitStream(BS: Integer);
var
Offset: POGG_INT64_T;
begin
if Active then
begin
if ov_seekable(VFile)<>0 then
if (BS >= 0) and (BS < ov_streams(VFile)) then
begin
Offset:=VFile.offsets;
Inc(Offset, BS);
FStream.Seek(Offset^, soFromBeginning);
end;
end;
end;
procedure TVorbisOut.SetDesiredNominalBitrate(AValue: TVorbisBitRate);
begin
FDesiredNominalBitrate:=AValue;
if FMinimumBitrate > FDesiredNominalBitrate then
FMinimumBitrate:=FDesiredNominalBitrate;
if FDesiredMaximumBitrate < FDesiredNominalBitrate then
FDesiredMaximumBitrate:=FDesiredNominalBitrate;
if FDesiredNominalBitrate = brAutoSelect then
FDesiredMaximumBitrate:=brAutoSelect;
end;
procedure TVorbisOut.SetDesiredMaximumBitrate(AValue: TVorbisBitRate);
begin
if FDesiredNominalBitrate = brAutoSelect then Exit;
if (AValue = brAutoSelect) or (AValue >= FDesiredNominalBitrate) then
FDesiredMaximumBitrate:=AValue;
end;
procedure TVorbisOut.SetMinimumBitrate(AValue: TVorbisBitRate);
begin
if AValue <= FDesiredNominalBitrate then FMinimumBitrate:=AValue;
end;
procedure TVorbisOut.InitVorbis();
var
i, maxbr, minbr, nombr : Integer;
Name, Value : AnsiString;
begin
vorbis_info_init(VInfo);
if DesiredNominalBitrate = brAutoSelect then
begin
(* {$IFNDEF USE_VORBIS_10}
if vorbis_encode_init_vbr(@VInfo, FInput.Channels, FInput.SampleRate, FCompression) <> 0 then
raise EACSException.Create('Vorbis init failed');
if vorbis_encode_setup_init(@VInfo) <> 0 then
raise EACSException.Create('Vorbis setup failed');
{$ENDIF} *)
{$IFDEF USE_VORBIS_11}
vorbis_encode_setup_vbr(VInfo, FInput.Channels, FInput.SampleRate, FCompression);
vorbis_encode_setup_init(VInfo);
{$ENDIF}
end
else
begin
nombr := VorbisBitrateToInt(FDesiredNominalBitrate);
maxbr := VorbisBitrateToInt(FDesiredMaximumBitrate);
//if maxbr < nombr then maxbr := nombr;
minbr := VorbisBitrateToInt(Self.FMinimumBitrate);
if minbr < 0 then minbr := nombr;
if vorbis_encode_init(VInfo, FInput.Channels, FInput.SampleRate, maxbr, nombr, minbr) <> 0 then
raise EAcsException.Create('Vorbis codec setup with the requested bitrate failed. Try a lower bitrate.');
end;
// tags
vorbis_comment_init(VComm);
for i := 0 to FTags.IdCount - 1 do
begin
Name := Utf8Encode(WideString(FTags.Ids[i]));
Value := Utf8Encode(FTags.AsWideString[FTags.Ids[i]]);
if Value <> '' then
vorbis_comment_add_tag(VComm, PAnsiChar(@Name[1]), PAnsiChar(@Value[1]));
end;
vorbis_analysis_init(Vdsp, VInfo);
vorbis_block_init(Vdsp, VBlock);
ogg_stream_init(OggSS, FSerial);
vorbis_analysis_headerout(Vdsp, VComm, header, header_comm, header_code);
ogg_stream_packetin(OggSS, header);
ogg_stream_packetin(OggSS, header_comm);
ogg_stream_packetin(OggSS, header_code);
while ogg_stream_flush(OggSS, OggPg) <> 0 do
begin
FStream.Write(OggPg.header^, OggPg.header_len);
FStream.Write(OggPg.body^, OggPg.body_len);
end;
end;
function TVorbisIn.Seek(SampleNum: Integer): Boolean;
begin
Result:=False;
if not FSeekable then Exit;
if FOpened then ov_pcm_seek(VFile, SampleNum);
Result:=True;
end;
initialization
if VorbisLoadLibrary() then
begin
FileFormats.Add('ogg', 'Ogg Vorbis', TVorbisOut);
FileFormats.Add('ogg', 'Ogg Vorbis', TVorbisIn);
end;
finalization
VorbisUnloadLibrary();
end.
|
unit SynHighlighterBracket;
(*
This is an example how to implement my own highlighter.
This example extends the Simple and Context HL:
- The token '{' and '}' (must be surrounded by space or line-begin/end to be
a token of their own) will add foldable sections
Multply { and } can be nested.
See comments below and http://wiki.lazarus.freepascal.org/SynEdit_Highlighter
*)
{$mode objfpc}{$H+}
{.$define colorfold}
interface
uses
Classes, SysUtils, Graphics, SynEditTypes, SynEditHighlighter,
SynEditHighlighterFoldBase {$ifdef colorfold},SynColorFoldHighlighter{$endif}
;
type
{ TSynHighlighterBracket }
//TSynHighlighterBracket = class(TSynCustomFoldHighlighter)
TSynHighlighterBracket = class({$ifdef colorfold}TSynColorFoldHighlighter{$else}TSynCustomFoldHighlighter{$endif})
private
FFoldAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
//fSpaceAttri: TSynHighlighterAttributes;
procedure SetFoldAttri(AValue: TSynHighlighterAttributes);
procedure SetIdentifierAttri(AValue: TSynHighlighterAttributes);
//procedure SetSpaceAttri(AValue: TSynHighlighterAttributes);
protected
// accesible for the other examples
FTokenPos, FTokenEnd: Integer;
FLineText: String;
public
procedure SetLine(const NewValue: String; LineNumber: Integer); override;
procedure Next; override;
function GetEol: Boolean; override;
procedure GetTokenEx(out TokenStart: PChar; out TokenLength: integer); override;
function GetTokenAttribute: TSynHighlighterAttributes; override;
public
function GetToken: String; override;
function GetTokenPos: Integer; override;
function GetTokenKind: integer; override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override;
constructor Create(AOwner: TComponent); override;
published
(* Define 4 Attributes, for the different highlights. *)
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri
write SetIdentifierAttri;
//property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri
//write SetSpaceAttri;
property FoldAttri: TSynHighlighterAttributes read FFoldAttri
write SetFoldAttri;
end;
implementation
constructor TSynHighlighterBracket.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
(* Create and initialize the attributes *)
FFoldAttri := TSynHighlighterAttributes.Create('fold', 'fold');
AddAttribute(FFoldAttri);
FFoldAttri.Style := [fsBold];
fIdentifierAttri := TSynHighlighterAttributes.Create('ident', 'ident');
AddAttribute(fIdentifierAttri);
{fSpaceAttri := TSynHighlighterAttributes.Create('space', 'space');
AddAttribute(fSpaceAttri);
fSpaceAttri.FrameColor := clSilver;
fSpaceAttri.FrameEdges := sfeBottom;//sfeLeft;//sfeAround;}
end;
procedure TSynHighlighterBracket.Next;
var
l: Integer;
begin
// FTokenEnd should be at the start of the next Token (which is the Token we want)
FTokenPos := FTokenEnd;
// assume empty, will only happen for EOL
FTokenEnd := FTokenPos;
// Scan forward
// FTokenEnd will be set 1 after the last char. That is:
// - The first char of the next token
// - or past the end of line (which allows GetEOL to work)
l := length(FLineText);
If FTokenPos > l then
// At line end
exit
else
if FLineText[FTokenEnd] = '{' then
begin
inc (FTokenEnd);
{$ifdef colorfold}
StartCodeFoldBlock(FTokenPos-1, FTokenEnd);
{$else}
//StartCodeFoldBlock(FTokenPos-1, FTokenEnd);
StartCodeFoldBlock(nil);
//CodeFoldRange.FoldStart := Point (FTokenPos, LineIndex );
//CodeFoldRange.FoldSign[True] := FoldSign(FTokenPos, FTokenEnd, LineIndex);
{$endif}
end
else
if FLineText[FTokenEnd] = '}' then
begin
inc (FTokenEnd);
{$ifdef colorfold}
EndCodeFoldBlock(FTokenPos-1, FTokenEnd);
{$else}
//CodeFoldRange.FoldFinish := Point (FTokenPos, LineIndex );
//CodeFoldRange.FoldSign[False] := FoldSign(FTokenPos, FTokenEnd, LineIndex);
EndCodeFoldBlock;
//EndCodeFoldBlock(FTokenPos-1, FTokenEnd);
{$endif}
end
else
if FLineText[FTokenEnd] in [#9, ' '] then
// At Space? Find end of spaces
while (FTokenEnd <= l) and (FLineText[FTokenEnd] in [#0..#32]) do inc (FTokenEnd)
else
// At None-Space? Find end of None-spaces
while (FTokenEnd <= l) and not(FLineText[FTokenEnd] in [#9, ' ', '{', '}']) do inc (FTokenEnd);
end;
(* Setters for attributes / This allows using in Object inspector*)
procedure TSynHighlighterBracket.SetIdentifierAttri(AValue: TSynHighlighterAttributes);
begin
fIdentifierAttri.Assign(AValue);
end;
procedure TSynHighlighterBracket.SetFoldAttri(AValue: TSynHighlighterAttributes);
begin
FFoldAttri.Assign(AValue);
end;
{procedure TSynHighlighterBracket.SetSpaceAttri(AValue: TSynHighlighterAttributes);
begin
fSpaceAttri.Assign(AValue);
end;}
procedure TSynHighlighterBracket.SetLine(const NewValue: String; LineNumber: Integer);
begin
inherited;
FLineText := NewValue;
// Next will start at "FTokenEnd", so set this to 1
FTokenEnd := 1;
Next;
end;
function TSynHighlighterBracket.GetEol: Boolean;
begin
Result := FTokenPos > length(FLineText);
end;
procedure TSynHighlighterBracket.GetTokenEx(out TokenStart: PChar; out TokenLength: integer);
begin
TokenStart := @FLineText[FTokenPos];
TokenLength := FTokenEnd - (FTokenPos-0);
end;
function TSynHighlighterBracket.GetTokenAttribute: TSynHighlighterAttributes;
var s : string;
begin
// Match the text, specified by FTokenPos and FTokenEnd
if FLineText[FTokenPos] in [#9, ' '] then
Result := WhitespaceAttribute
else
if FLineText[FTokenPos] in ['{', '}'] then
Result := FoldAttri
else
Result := IdentifierAttri;
end;
function TSynHighlighterBracket.GetToken: String;
begin
Result := copy(FLineText, FTokenPos, FTokenEnd - FTokenPos);
end;
function TSynHighlighterBracket.GetTokenPos: Integer;
begin
Result := FTokenPos -1;
end;
function TSynHighlighterBracket.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
begin
// Some default attributes
case Index of
//SYN_ATTR_COMMENT: Result := fSpecialAttri;
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
//SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
else Result := nil;
end;
end;
function TSynHighlighterBracket.GetTokenKind: integer;
var
a: TSynHighlighterAttributes;
begin
// Map Attribute into a unique number
a := GetTokenAttribute;
Result := 0;
//if a = fSpaceAttri then Result := 1;
if a = fIdentifierAttri then Result := 3;
if a = FFoldAttri then Result := 4;
end;
end.
|
program OrdinalType;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
type
TLanguageType = (ltArabic, ltEnglish);
var
Lang: TLanguageType;
AName: string;
Selection: Byte;
begin
Write('Please select Language: 1 (Arabic), 2 (English)');
Readln(Selection);
if Selection = 1 then
Lang:= ltArabic
else
if selection = 2 then
Lang:= ltEnglish
else
Writeln('Wrong entry');
if Lang = ltArabic then
Write(' :ماهو اسك: ')
else
if Lang = ltEnglish then
Write('What is your name: ');
Readln(AName);
if Lang = ltArabic then
begin
Writeln(' مرحبا بك: ', AName);
Write('الرجاء الضغط على مفتاح إدخال لغللق البناامج ');
end
else
if Lang = ltEnglish then
begin
Writeln('Hello ', AName);
Write('Please press enter key to close');
end;
Readln;
end.
|
unit Delphi.Mocks.Examples.Factory;
interface
uses
Rtti,
TypInfo,
SysUtils,
DUnitX.TestFramework;
type
{$M+}
IFileService = interface
['{3BDAC049-F291-46CB-95A8-B177E3485752}']
function OpenForAppend(const AFilename : string) : THandle;
function WriteLineTo(const AHandle : THandle; const ALine : string) : boolean;
end;
IApplicationInfo = interface
['{43C0AE45-F57F-4620-A902-35CEAB370BC1}']
function GetFileService : IFileService;
property FileService : IFileService read GetFileService;
end;
ILogLine = interface
['{B230FBB5-EE90-4208-90A4-FF09274BD767}']
function FormattedLine : string;
end;
ILogLines = interface
['{0CAF05DA-6828-4651-8431-F4E6815AF1C0}']
function GetCount : Cardinal;
function GetLine(const ALine: Cardinal) : ILogLine;
property Line[const ALine : Cardinal] : ILogLine read GetLine;
property Count : Cardinal read GetCount;
end;
ILogReceiver = interface
['{0EE8E9EC-0B2E-4052-827D-5EAF26AB08BC}']
function GetLogsAbove(const ALogLevel : Integer) : ILogLines;
function Log(const AMessage: string; const ALogLevel : Integer) : boolean;
end;
IMessage = interface
['{9955A5F2-3BC3-43DA-81FC-AD16E02BC93F}']
end;
IMessageChannel = interface
['{B2F9B8B0-93DD-4886-8141-CD043C32A9F1}']
function SendMessage(const AMessage : IMessage) : boolean;
end;
ICoreService = interface
['{48584DC8-C425-4F6C-8FC5-438F04A90052}']
function GetLogReciever : ILogReceiver;
function GetApplication : IApplicationInfo;
function GetAppMessageChannel : IMessageChannel;
property Application : IApplicationInfo read GetApplication;
property LogReciever : ILogReceiver read GetLogReciever;
property AppMessageChannel : IMessageChannel read GetAppMessageChannel;
end;
ILogExporter = interface
['{037C6F9F-CA6A-4DE9-863C-0E3DC265B49B}']
function ExportLog(const AMinLogLevel : Integer; const AFilename: TFilename) : integer;
end;
TLogExporter = class(TInterfacedObject, ILogExporter)
private
FLogReciever : ILogReceiver;
FApplication : IApplicationInfo;
public
constructor Create(const AServices : ICoreService);
destructor Destroy; override;
function ExportLog(const AMinLogLevel : Integer; const AFilename: TFilename) : integer;
end;
{$M-}
TExample_MockFactoryTests = class
published
procedure Implement_Multiple_Interfaces;
procedure Create_T_From_TypeInfo;
end;
IFakeGeneric = interface
['{682057B0-E265-45F1-ABF7-12A25683AF63}']
function Value : TValue;
end;
TFakeGeneric = class(TInterfacedObject, IFakeGeneric)
private
FValue : TValue;
public
constructor Create(const ATypeInfo : PTypeInfo);
destructor Destroy; override;
function Value : TValue;
end;
IFakeGeneric<T> = interface
['{87853316-A14D-4BC6-9124-D947662243F0}']
function Value : T;
end;
TFakeGeneric<T> = class(TInterfacedObject, IFakeGeneric<T>)
private
FFakeGeneric : IFakeGeneric;
public
constructor Create;
destructor Destroy; override;
function Value : T;
end;
implementation
uses
Delphi.Mocks;
function CreateFakeGeneric(const TypeInfo: PTypeInfo) : TObject;
begin
end;
{ TLogExporter }
constructor TLogExporter.Create(const AServices: ICoreService);
begin
inherited Create;
FLogReciever := AServices.LogReciever;
FApplication := AServices.Application;
end;
destructor TLogExporter.Destroy;
begin
FLogReciever := nil;
FApplication := nil;
inherited;
end;
function TLogExporter.ExportLog(const AMinLogLevel : Integer; const AFilename: TFilename) : integer;
var
fileService : IFileService;
fileHandle: THandle;
logs: ILogLines;
iLine: Integer;
begin
//Very simplistic ExportLog function which uses a number of other services to
//set its job done. The logic is simplistic, but the implementation over uses
//services to show the power of AutoMocking, and the Factory.
fileService := FApplication.FileService;
//Create or open requested file.
fileHandle := fileService.OpenForAppend(AFilename);
//Make sure the got a valid handle from the file serice.
if fileHandle = 0 then
raise Exception.CreateFmt('The fileservice failed to return a handle for [%s]', [AFilename]);
//Get the log from the log receiver for the passed in min log level.
logs := FLogReciever.GetLogsAbove(AMinLogLevel - 1);
//Write each line out with the formatting from the log.
for iLine := 0 to logs.Count - 1 do
fileService.WriteLineTo(fileHandle, logs.Line[iLine].FormattedLine);
end;
{ TExample_MockFactoryTests }
procedure TExample_MockFactoryTests.Create_T_From_TypeInfo;
var
fakeExporter : IFakeGeneric<TLogExporter>;
fakeLine : IFakeGeneric<ILogLine>;
begin
fakeExporter := TFakeGeneric<TLogExporter>.Create;
Assert.AreEqual(fakeExporter.Value.ClassName, 'TLogExporter');
fakeLine := TFakeGeneric<ILogLine>.Create;
Assert.AreEqual(fakeLine.Value.FormattedLine, 'TLogExporter');
end;
procedure TExample_MockFactoryTests.Implement_Multiple_Interfaces;
var
logExporterSUT : ILogExporter;
// mockFactory : TMockFactory;
mockContainer : TAutoMockContainer;
mockCoreService : TMock<ICoreService>;
begin
//CREATE - Create a mock of the CoreService which we require for the LogExporter
// We do this through creating a MockFactory to generate the Mock
// mockFactory := TMockFactory.Create;
// mockContainer := TAutoMockContainer.Create(mockFactory);
//
// mockCoreService := mockContainer.Mock<ICoreService>;
//
// //CREATE - The log exporter ExportLog function is what we are looking at testing.
// logExporterSUT := TLogExporter.Create(mockCoreService);
//
// //TEST - See if we can export a log.
// logExporterSUT.ExportLog(0, '');
//
// //VERIFY - Make sure that everything we have attached to the factory and its mocks
// // has correctly run.
// mockFactory.VerifyAll;
end;
{ TFakeGeneric }
constructor TFakeGeneric.Create(const ATypeInfo: PTypeInfo);
var
AValue: TValue;
ctx: TRttiContext;
rType: TRttiType;
AMethCreate: TRttiMethod;
instanceType: TRttiInstanceType;
begin
ctx := TRttiContext.Create;
rType := ctx.GetType(ATypeInfo);
for AMethCreate in rType.GetMethods do
begin
{$Message 'TODO Handle constructors with params.'}
if (AMethCreate.IsConstructor) and (Length(AMethCreate.GetParameters) = 0) then
begin
instanceType := rType.AsInstance;
FValue := AMethCreate.Invoke(instanceType.MetaclassType, []);
Exit;
end;
end;
end;
destructor TFakeGeneric.Destroy;
begin
FreeAndNil(FValue);
inherited;
end;
function TFakeGeneric.Value: TValue;
begin
Result := FValue;
end;
{ TFakeGeneric<T> }
constructor TFakeGeneric<T>.Create;
begin
FFakeGeneric := TFakeGeneric.Create(TypeInfo(T));
end;
destructor TFakeGeneric<T>.Destroy;
begin
FFakeGeneric := nil;
inherited;
end;
function TFakeGeneric<T>.Value: T;
begin
Result := FFakeGeneric.Value.AsType<T>;
end;
initialization
TDUnitX.RegisterTestFixture(TExample_MockFactoryTests);
end.
|
unit ShellContextMenu;
interface
uses Windows, SysUtils, Forms, ShlObj, ActiveX;
function ExecuteContextMenu (const FileName, Cmd: string;Parent:hWnd): Boolean;
implementation
function ExecuteContextMenu (const FileName, Cmd: string;Parent:hWnd): Boolean;
var
ShellFolder : IShellFolder;
FileObject : IShellFolder;
Menu : IContextMenu;
lpItemIdList, lpNameList: PItemIDList;
WideStr : WideString;
Malloc : IMalloc;
Attributes, uLength : ULONG;
Command : TCMInvokeCommandInfo;
hr: HRESULT;
begin
Result := FALSE;
Menu := nil;
Malloc := nil;
FileObject := nil;
ShellFolder := nil;
try
hr := SHGetMalloc (Malloc);
if SUCCEEDED(hr)then
begin
hr := SHGetDesktopFolder (ShellFolder);
if SUCCEEDED(hr)then
begin
WideStr := ExtractFilePath (FileName);
hr := ShellFolder.ParseDisplayName (0, nil,
PWideChar (WideStr), uLength,
lpItemIdList, Attributes);
if SUCCEEDED(hr)then
begin
hr := ShellFolder.BindToObject (lpItemIdList, nil,
IID_IShellFolder, Pointer (FileObject));
if SUCCEEDED(hr)then
begin
WideStr := ExtractFileName (FileName);
hr := FileObject.ParseDisplayName (0, nil,
PWideChar (WideStr), uLength, lpNameList, Attributes);
if SUCCEEDED(hr)then
begin
hr := FileObject.GetUIObjectOf (0, 1, lpNameList,
IID_IContextMenu, nil, Pointer (Menu));
if SUCCEEDED(hr)then
begin
FillChar (Command, sizeof (Command), 0);
Command.cbSize := sizeof (Command);
Command.hwnd := Parent;
Command.lpVerb := PChar (Cmd);
Command.nShow := SW_SHOW;
Result := SUCCEEDED (Menu.InvokeCommand (Command));
end;
end;
end;
end;
end;
end;
finally
Menu := nil;
FileObject := nil;
if Malloc <> nil then Malloc.Free (lpItemIdList);
Malloc := nil;
ShellFolder := nil;
end;
end;
end.
|
unit SpaceInvader;
interface
uses
System.Types, SmartCL.System, SmartCL.Components, SmartCL.Application,
SmartCL.Game, SmartCL.GameApp, SmartCL.Graphics,
Items, Settings, Input;
type
TMode = (Main, GameOver);
TApplication = class(TW3CustomGameApplication)
private
Items: Array of TItem;
Start, LastBulletCreated: TDateTime;
Mode: TMode;
PressingSpace: Boolean;
Score: Integer;
procedure AddNewEnemy;
procedure AddNewBullet;
function CheckIfNewEnemy: Boolean;
procedure ClearScreen(Canvas: TW3Canvas);
procedure PaintMain(Canvas: TW3Canvas);
procedure PaintGameOver(Canvas: TW3Canvas);
procedure SetupGame;
function CreateBullet: Boolean;
protected
procedure ApplicationStarting; override;
procedure ApplicationClosing; override;
procedure PaintView(Canvas: TW3Canvas); override;
public
procedure KeyDown(mCode: Integer);
procedure KeyUp(mCode: Integer);
end;
const
SQUARE_SIZE = 200;
implementation
procedure TApplication.SetupGame;
begin
Start := Now;
Mode := Main;
Items.Clear;
Items[0] := TPlayer.Create(20, 20, GameView.Width div 2, GameView.Height - 30);
Score := 0;
end;
procedure TApplication.AddNewEnemy;
begin
Items.Add(TEnemy.Create(20, 10, Floor(Random * GameView.Width), 0));
end;
function TApplication.CheckIfNewEnemy: Boolean;
begin
Result := Random < ((Now - Start) * ENEMY_CREATION_MULTIPLIER +
ENEMY_CREATION_SPEED * GameView.Width);
end;
procedure TApplication.ClearScreen(Canvas: TW3Canvas);
var
StartColour: String;
begin
StartColour := Canvas.FillStyle;
Canvas.FillStyle := 'black';
Canvas.FillRectF(0, 0, GameView.Width, GameView.Height);
Canvas.FillStyle := StartColour;
end;
// Note: In a real live game you would try to cache as much
// info as you can. Typical tricks are:
// 1: Only get the width/height when resized
// 2: Pre-calculate strings, especially RGB/RGBA values
// 3: Only redraw what has changed, avoid a full repaint
// The code below is just to get you started
procedure TApplication.PaintView(Canvas: TW3Canvas);
begin
/*
// Clear background
Canvas.FillStyle := 'rgb(0, 0, 99)';
Canvas.FillRectF(0, 0, GameView.Width, GameView.Height);
// Draw our framerate on the screen
Canvas.Font := '10pt verdana';
Canvas.FillStyle := 'rgb(255, 255, 255)';
Canvas.FillTextF('FPS:' + IntToStr(GameView.FrameRate), 10, 20, MAX_INT);
*/
case Mode of
Main: PaintMain(Canvas);
GameOver: PaintGameOver(Canvas);
end;
end;
procedure TApplication.PaintGameOver(Canvas: TW3Canvas);
begin
ClearScreen(Canvas);
if Score = 0 then Score := Round(1000000 * (Now - Start));
Canvas.FillText('GAME OVER!', 50, 50);
Canvas.FillText('Score: '+ FloatToStr(Score), 50, 70);
end;
procedure TApplication.PaintMain(Canvas: TW3Canvas);
var
I, J: Integer;
ToDelete: Array of TItem; //deleting while we loop messes things up
begin
if CheckIfNewEnemy then AddNewEnemy;
if CreateBullet then AddNewBullet;
for I := Low(Items) to High(Items) do begin
Items[I].UpdatePosition;
//Check if still on screen
if not Items[I].IsOnScreen(GameView.Height) then ToDelete.Add(Items[I])
else begin
//Check if it has collided with anything
for J := I + 1 to High(Items) do begin
if Items[I].CheckCollision(Items[J]) then begin
Log('Items ' + IntToStr(I) + ' and ' + IntToStr(J) + ' collided');
if I = 0 then begin //player has been hit!
Mode := GameOver;
Exit;
end else begin
//collisions mean we delete object from game
ToDelete.Add(Items[I]);
ToDelete.Add(Items[J]);
end;
end;
end;
end;
end;
for I := Low(ToDelete) to High(ToDelete) do Items.Remove(ToDelete[I]);
ClearScreen(Canvas);
for I := Low(Items) to High(Items) do begin
Items[I].Draw(Canvas);
end;
end;
procedure TApplication.KeyDown(mCode: Integer);
begin
if mCode = 32 then PressingSpace := True;
end;
procedure TApplication.KeyUp(mCode: Integer);
begin
if mCode = 32 then PressingSpace := False;
end;
procedure TApplication.AddNewBullet;
begin
Items.Add(TBullet.Create(10, 10, Items[0].Left + 5, Items[0].Top - 15));
LastBulletCreated := Now;
end;
function TApplication.CreateBullet: Boolean;
begin
Log(FloatToStr(Now - LastBulletCreated));
Result := PressingSpace and (Now - LastBulletCreated > BULLET_INTERVAL)
end;
procedure TApplication.ApplicationStarting;
begin
inherited;
// Initialize refresh interval, set this to 1 for optimal speed
GameView.Delay := 20;
// Start the redraw-cycle with framecounter active
// Note: the framecounter impacts rendering speed. Disable
// the framerate for maximum speed (false)
GameView.StartSession(True);
asm
window.onkeydown=function(e)
{
(@KeyDownEvent)(e.keyCode);
}
window.onkeyup=function(e)
{
(@KeyUpEvent)(e.keyCode);
}
end;
AddKeyDown(KeyDown);
AddKeyUp(KeyUp);
SetupGame;
end;
procedure TApplication.ApplicationClosing;
begin
GameView.EndSession;
inherited;
end;
end. |
unit Ct02;
{
ULCT02.DPR***************************************************************
File: CT02.PAS
Library Call Demonstrated: 9513 Counter Functions
cbC9513Init()
cbC9513Config()
cbCLoad()
cbCIn()
Purpose: Operate the counter.
Demonstration: Initializes, configures, loads, and
reads the counter.
Other Library Calls: cbErrHandling()
Special Requirements: Board 0 must have a 9513 Counter.
Uses internal clock.
(c) Copyright 1995 - 2002, Measurement Computing Corp.
All rights reserved.
**************************************************************************
}
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, cbw;
type
TfrmCount = class(TForm)
cmdQuit: TButton;
MemoData: TMemo;
cmdStart: TButton;
tmrReadCount: TTimer;
procedure cmdQuitClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cmdStartClick(Sender: TObject);
procedure tmrReadCountTimer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmCount: TfrmCount;
implementation
{$R *.DFM}
var
ULStat: Integer;
ChipNum: Integer;
FOutDivider: Integer;
FOutSource: Integer;
Compare1: Integer;
Compare2: Integer;
TimeOfDay: Integer;
CounterNum: Integer;
RegName: Integer;
GateControl: Integer;
CounterEdge: Integer;
CountSource: Integer;
SpecialGate: Integer;
ReLoad: Integer;
RecycleMode: Integer;
BCDMode: Integer;
CountDirection: Integer;
OutputControl: Integer;
LoadValue: Integer;
ErrReporting: Integer;
ErrHandling: Integer;
Count: Word;
RevLevel: Single;
const
BoardNum: Integer = 0;
procedure TfrmCount.FormCreate(Sender: TObject);
begin
{declare Revision Level}
RevLevel := CURRENTREVNUM;
ULStat := cbDeclareRevision(RevLevel);
{
set up internal error handling for the Universal Library
}
ErrReporting := PRINTALL; {set Universal Library to print all errors}
ErrHandling := STOPALL; {set Universal Library to stop on errors}
ULStat := cbErrHandling(ErrReporting, ErrHandling);
{
initialize the board level features
Parameters:
BoardNum :the number used by CB.CFG to describe this board
ChipNum :selects counter chip on board
FOutDivider :the F-Out divider (0-15)
FOutSource :the signal source for F-Out
Compare1 :status of comparator 1
Compare2 :status of comparator 2
TimeOfDay :time of day control mode
}
ChipNum := 1;
FOutDivider := 0;
FOutSource := FREQ4;
Compare1 := DISABLED;
Compare2 := DISABLED;
TimeOfDay := DISABLED;
ULStat := cbC9513Init (BoardNum, ChipNum, FOutDivider, FOutSource, Compare1, Compare2, TimeOfDay);
If ULStat <> 0 then exit;
MemoData.Text := Format('Chip # %d has been configured with FOutSource = "FREQ4".', [ChipNum]);
MemoData.Lines.Add (' ');
{
set the configurable operations of the counter
Parameters:
BoardNum :the number used by CB.CFG to describe this board
CounterNum :the counter to be configured (0-5)
GateControl :gate control value
CounterEdge :which edge to count
CountSource :signal source
SpecialGate :status of special gate
ReLoad :method of reloading the counter
RecycleMode :recycle mode
BCDMode :counting mode, BCD or binary
CountDirection :direction for the counting (COUNTUP or COUNTDOWN)
OutputControl :output signal type and level
}
CounterNum := 1;
GateControl := NOGATE;
CounterEdge := POSITIVEEDGE;
CountSource := FREQ4;
SpecialGate := DISABLED;
ReLoad := LOADREG;
RecycleMode := RECYCLE;
BCDMode := DISABLED;
CountDirection := COUNTUP;
OutputControl := ALWAYSLOW;
ULStat := cbC9513Config (BoardNum, CounterNum , GateControl, CounterEdge, CountSource,
SpecialGate, ReLoad, RecycleMode, BCDMode, CountDirection, OutputControl);
If ULStat <> 0 then exit;
MemoData.Text := Format(
'Counter # %d has been configured with CountDirection = "COUNTUP" and Output = "ALWAYSLOW".',
[CounterNum]);
MemoData.Lines.Add (' ');
{
Send a starting value to the counter with cbCLoad()
Parameters:
BoardNum :the number used by CB.CFG to describe this board
RegName :the reg. to be loading with the starting value
LoadValue :the starting value to place in the counter
}
LoadValue := 1;
RegName := LOADREG1;
ULStat := cbCLoad (BoardNum, RegName, LoadValue);
If ULStat <> 0 then exit;
MemoData.Lines.Add (Format('The value %d has been loaded into counter # %d.',
[LoadValue, CounterNum]));
MemoData.Lines.Add (' ');
MemoData.Lines.Add ('Click "Start" to read counter');
end;
procedure TfrmCount.cmdStartClick(Sender: TObject);
begin
tmrReadCount.Enabled := True;
end;
procedure TfrmCount.tmrReadCountTimer(Sender: TObject);
begin
{
use a timer to keep checking the counter value with cbCIn()
Parameters:
BoardNum :the number used by CB.CFG to describe this board
CounterNum :the counter to be setup
Count :the count value in the counter
}
ULStat := cbCIn (BoardNum, CounterNum, Count);
If ULStat <> 0 then exit;
MemoData.Text := Format('Value read at counter # %d is %d counts.', [CounterNum, Count]);
end;
procedure TfrmCount.cmdQuitClick(Sender: TObject);
begin
Close;
end;
end.
|
unit EditaEvento;
interface
uses
Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, {FnpNumericEdit,} Grids, DBGrids, Db, kbmMemTable,
uFuncoesGeral, uDmPrincipal, classeTabPrecos, Mask, JvExMask, JvToolEdit, JvBaseEdits;
type
TParametrosEditaEvento = record
TableEventos : TDataSet;
CampoCodigo,
CampoNome,
CampoVencPersonalizados,
CampoNumParcelas,
CampoVencMensalidades,
CampoMesPrimeiroVenc,
CampoAnoPrimeiroVenc,
CampoValor,
CampoValorPersonalizado : string;
TableVencimentos : TDataSet;
CampoParcela,
CampoVencimento : String;
ValorOpcional : Boolean;
ValorOriginal : Double;
CodTabPrecos : Integer;
end;
TfmEditaEvento = class(TForm)
btConfirmar: TButton;
btCancelar: TButton;
Label1: TLabel;
edNomeEvento: TEdit;
Label2: TLabel;
dsVencimentos: TDataSource;
edCodEvento: TEdit;
gbVencimento: TGroupBox;
Label3: TLabel;
lblGridVencimentos: TLabel;
dbgVencimentos: TDBGrid;
chkVencPersonalizados: TCheckBox;
gbValores: TGroupBox;
lbValParcela: TLabel;
lbValTotal: TLabel;
chkValPersonalizado: TCheckBox;
chkVencMensalidades: TCheckBox;
lblPrimeiroVencimento: TLabel;
cboMesPrimeiroVenc: TComboBox;
edAnoPrimeiroVenc: TEdit;
edValorParcela: TJvCalcEdit;
edValorTotal: TJvCalcEdit;
tblVencimentos: TkbmMemTable;
tblVencimentosParcela: TIntegerField;
tblVencimentosVencimento: TDateField;
edNumParcelas: TJvCalcEdit;
procedure edValorTotalExit(Sender: TObject);
procedure edValorParcelaExit(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure tblVencimentosBeforeInsert(DataSet: TDataSet);
procedure tblVencimentosBeforeDelete(DataSet: TDataSet);
procedure btConfirmarClick(Sender: TObject);
procedure edNumParcelasExit(Sender: TObject);
procedure chkVencPersonalizadosClick(Sender: TObject);
procedure chkValPersonalizadoClick(Sender: TObject);
procedure chkVencMensalidadesClick(Sender: TObject);
private
{ Private declarations }
BloqueiaTabParcelas : Boolean;
FValorOriginal: Double;
function GetVencimento(Parcela: Integer): TDate;
procedure SetVencimento(Parcela: Integer; const Value: TDate);
function GetNumParcelas: Integer;
function GetValorParcela: Double;
function GetValorTotal: Double;
procedure SetNumParcelas(const Value: Integer);
procedure SetValorParcela(const Value: Double);
procedure SetValorTotal(const Value: Double);
function GetCodEvento: Integer;
function GetNomeEvento: String;
procedure SetCodEvento(const Value: Integer);
procedure SetNomeEvento(const Value: String);
procedure AtualizaNumeroVencimentos(Qtd: Integer);
function GetVencPersonalizado: Boolean;
procedure SetVencPersonalizado(const Value: Boolean);
procedure SetValorPersonalizado(const Value: Boolean);
function GetValorPersonalizado : Boolean;
procedure SetValorOriginal(const Value: Double);
function GetVencMensalidades: Boolean;
procedure SetVencMensalidades(const Value: Boolean);
function GetMesPrimeiroVenc: Integer;
procedure SetMesPrimeiroVenc(const Value: Integer);
function GetAnoPrimeiroVenc: Integer;
procedure SetAnoPrimeiroVenc(const Value: Integer);
public
class function Alterar(Parametros : TParametrosEditaEvento) : Boolean; overload;
class function Alterar(TableEventos : TDataSet;
CampoCodigo, CampoNome,CampoVencPersonalizados, CampoNumParcelas,
CampoVencMensalidades, CampoMesPrimeiroVenc, CampoAnoPrimeiroVenc,
CampoValor, CampoValorPersonalizado : string;
TableVencimentos : TDataSet; CampoParcela, CampoVencimento : String;
ValorOpcional : Boolean; ValorOriginal : Double; CodTabPrecos : Integer) : boolean; overload;
property CodEvento : Integer read GetCodEvento write SetCodEvento;
property NomeEvento : String read GetNomeEvento write SetNomeEvento;
property NumParcelas : Integer read GetNumParcelas write SetNumParcelas;
property VencMensalidades: Boolean read GetVencMensalidades write SetVencMensalidades;
property MesPrimeiroVenc: Integer read GetMesPrimeiroVenc write SetMesPrimeiroVenc;
property AnoPrimeiroVenc: Integer read GetAnoPrimeiroVenc write SetAnoPrimeiroVenc;
property ValorParcela : Double read GetValorParcela write SetValorParcela;
property ValorTotal : Double read GetValorTotal write SetValorTotal;
property ValorOriginal : Double read FValorOriginal write SetValorOriginal;
property Vencimento[Parcela : Integer] : TDate read GetVencimento write SetVencimento;
property VencPersonalizado : Boolean read GetVencPersonalizado write SetVencPersonalizado;
property ValorPersonalizado : Boolean read GetValorPersonalizado write SetValorPersonalizado;
end;
var
fmEditaEvento : TfmEditaEvento;
implementation
uses uDMAction;
{$R *.DFM}
{ TfmEditaEvento }
procedure TfmEditaEvento.edValorTotalExit(Sender: TObject);
var
Parc : Integer;
begin
Parc := StrToIntDef(edNumParcelas.Text, 0);
if Parc = 0 then
edValorParcela.Value := 0
else
edValorParcela.Value := edValorTotal.Value / Parc;
end;
procedure TfmEditaEvento.edValorParcelaExit(Sender: TObject);
begin
edValorTotal.Value := edValorParcela.Value * StrToIntDef(edNumParcelas.Text, 0);
end;
function TfmEditaEvento.GetVencimento(Parcela: Integer): TDate;
begin
if tblVencimentos.Locate('Parcela', Parcela, []) then
Result := tblVencimentosVencimento.Value
else
Result := 0;
end;
procedure TfmEditaEvento.SetVencimento(Parcela: Integer;
const Value: TDate);
begin
if tblVencimentos.Locate('Parcela', Parcela, []) then
tblVencimentos.Edit
else
begin
tblVencimentos.Append;
tblVencimentosParcela.Value := Parcela;
end;
tblVencimentosVencimento.Value := Value;
tblVencimentos.Post;
end;
function TfmEditaEvento.GetNumParcelas: Integer;
begin
Result := StrToIntDef(edNumParcelas.Text, 0);
end;
function TfmEditaEvento.GetValorParcela: Double;
begin
Result := edValorParcela.Value;
end;
function TfmEditaEvento.GetValorTotal: Double;
begin
Result := edValorTotal.Value;
end;
procedure TfmEditaEvento.AtualizaNumeroVencimentos(Qtd : Integer);
var
i : Integer;
begin
if not VencMensalidades then
begin
BloqueiaTabParcelas := False;
try
if tblVencimentos.RecordCount < Qtd then
begin
for i := tblVencimentos.RecordCount + 1 to Qtd do
begin
tblVencimentos.Append;
tblVencimentosParcela.Value := i;
tblVencimentosVencimento.Clear;
tblVencimentos.Post;
end;
end else
while tblVencimentos.RecordCount > Qtd do
begin
tblVencimentos.Last;
tblVencimentos.delete;
end;
finally
BloqueiaTabParcelas := True;
end;
end;
end;
procedure TfmEditaEvento.SetNumParcelas(const Value: Integer);
begin
edNumParcelas.Text := IntTostr(Value);
AtualizaNumeroVencimentos(Value);
end;
procedure TfmEditaEvento.SetValorParcela(const Value: Double);
begin
edValorParcela.Value := value;
edValorParcelaExit(edValorParcela);
end;
procedure TfmEditaEvento.SetValorTotal(const Value: Double);
begin
edValorTotal.Value := Value;
edValorTotalExit(edValorTotal);
end;
procedure TfmEditaEvento.FormCreate(Sender: TObject);
begin
BloqueiaTabParcelas := True;
tblVencimentos.Open;
end;
procedure TfmEditaEvento.tblVencimentosBeforeInsert(DataSet: TDataSet);
begin
if BloqueiaTabParcelas then Abort;
end;
procedure TfmEditaEvento.tblVencimentosBeforeDelete(DataSet: TDataSet);
begin
if BloqueiaTabParcelas then abort;
end;
function TfmEditaEvento.GetCodEvento: Integer;
begin
Result := StrToIntDef(edCodEvento.Text, 0);
end;
function TfmEditaEvento.GetNomeEvento: string;
begin
Result := edNomeEvento.Text;
end;
procedure TfmEditaEvento.SetCodEvento(const Value: Integer);
begin
edCodEvento.Text := IntToStr(Value);
end;
procedure TfmEditaEvento.SetNomeEvento(const Value: String);
begin
edNomeEvento.Text := Value;
end;
procedure TfmEditaEvento.btConfirmarClick(Sender: TObject);
begin
btConfirmar.SetFocus;
if NumParcelas = 0 then
begin
MessageBox(handle, 'O Número de parcelas deve ser maior que zero.', 'Atenção!', MB_ICONERROR);
edNumParcelas.SetFocus;
end else
if edValorParcela.Value <= 0 then
begin
MessageBox(handle, 'O valor da parcela deve ser maior que zero.', 'Atenção!', MB_ICONERROR);
edValorParcela.SetFocus;
end else
begin
if (dbgVencimentos.Visible and dbgVencimentos.Enabled and not dbgVencimentos.ReadOnly) then
begin
tblVencimentos.First;
while not tblVencimentos.Eof do
begin
if tblVencimentosVencimento.IsNull then
begin
MessageBox(handle, 'Você não informou uma ou mais datas de vencimentos.', 'Atenção!', MB_ICONERROR);
dbgVencimentos.SetFocus;
Abort;
end;
tblVencimentos.Next;
end;
end;
ModalResult := mrOk;
end;
end;
procedure TfmEditaEvento.edNumParcelasExit(Sender: TObject);
begin
if chkVencPersonalizados.Checked then
AtualizaNumeroVencimentos(NumParcelas);
end;
class function TfmEditaEvento.Alterar(TableEventos : TDataSet;
CampoCodigo, CampoNome, CampoVencPersonalizados, CampoNumParcelas,
CampoVencMensalidades, CampoMesPrimeiroVenc, CampoAnoPrimeiroVenc,
CampoValor, CampoValorPersonalizado : string;
TableVencimentos : TDataSet; CampoParcela, CampoVencimento : String;
ValorOpcional : Boolean; ValorOriginal : Double; CodTabPrecos : Integer) : boolean;
var
i : Integer;
TabPrecos : TTabPrecos;
Evento : tEvento;
begin
Application.CreateForm(TfmEditaEvento, fmEditaEvento);
fmEditaEvento.chkValPersonalizado.Visible := ValorOpcional;
fmEditaEvento.CodEvento := TableEventos.FieldByName(CampoCodigo).AsInteger;
fmEditaEvento.NomeEvento := TableEventos.FieldByName(CampoNome).AsString;
fmEditaEvento.VencMensalidades := TableEventos.FieldByName(CampoVencMensalidades).AsBoolean;
fmEditaEvento.NumParcelas := TableEventos.fieldByName(CampoNumParcelas).asInteger;
fmEditaEvento.ValorTotal := TableEventos.fieldByName(CampoValor).AsFloat;
fmEditaEvento.VencPersonalizado := TableEventos.fieldByName(CampoVencPersonalizados).AsBoolean;
fmEditaEvento.BloqueiaTabParcelas := False;
fmEditaEvento.ValorOriginal := ValorOriginal;
if CampoValorPersonalizado <> '' then
fmEditaEvento.ValorPersonalizado := TableEventos.fieldByName(CampoValorPersonalizado).AsBoolean;
if fmEditaEvento.VencMensalidades then
begin
fmEditaEvento.MesPrimeiroVenc := TableEventos.FieldByName(CampoMesPrimeiroVenc).AsInteger;
fmEditaEvento.AnoPrimeiroVenc := TableEventos.FieldByName(CampoAnoPrimeiroVenc).AsInteger;
end else
begin
if fmEditaEvento.VencPersonalizado then
begin
i := 1;
TableVencimentos.First;
while not TableVencimentos.Eof do
begin
fmEditaEvento.Vencimento[i] := TableVencimentos.fieldByName(CampoVencimento).Value;
inc(i);
TableVencimentos.Next;
end;
end else
begin
i := 1;
if CodTabPrecos = 0 then // Só é passado no plano de pagamentos
begin
DMPrincipal.OpenSQL(DMPrincipal.sqlDataEventos, 'SELECT * FROM DataEventos '+
'WHERE AnoLetivo = ' + vUser.AnoLetivo +
' AND Codigo = ' + IntToStr(fmEditaEvento.CodEvento) );
while not DMPrincipal.sqlDataEventos.Eof do
begin
fmEditaEvento.Vencimento[i] := DMPrincipal.sqlDataEventosVencimento.Value;
inc(i);
DMPrincipal.sqlDataEventos.Next;
end;
DMPrincipal.sqlDataEventos.Close;
end else
begin
TabPrecos := TTabPrecos.Create;
try
TabPrecos.Abrir(vUser.AnoLetivo, CodTabPrecos, True);
i := TabPrecos.ProcuraEvento(fmEditaEvento.CodEvento);
// O raise abaixo irá interromper a execução e pular para o finally.
if i = -1 then
raise Exception.Create('Evento não encontrado na tabela de preços.')
else
Evento := TabPrecos.Evento[i];
for i := 0 to Evento.Parcelas - 1 do
fmEditaEvento.Vencimento[i + 1] := Evento.Datas[i];
finally
TabPrecos.Free;
end;
end;
end;
end;
fmEditaEvento.BloqueiaTabParcelas := True;
Result := fmEditaEvento.ShowModal = mrOK;
if Result then
begin
TableEventos.Edit;
if not ValorOpcional or fmEditaEvento.ValorPersonalizado then
begin
TableEventos.fieldByName(CampoValor).AsFloat := fmEditaEvento.ValorTotal;
if CampoValorPersonalizado <> '' then
TableEventos.FieldByName(CampoValorPersonalizado).AsBoolean := True;
end else
begin
TableEventos.FieldByName(CampoValor).AsFloat := ValorOriginal;
if CampoValorPersonalizado <> '' then
TableEventos.FieldByName(CampoValorPersonalizado).AsBoolean := False;
end;
TableEventos.fieldByName(CampoNumParcelas).asInteger := fmEditaEvento.NumParcelas;
TableEventos.fieldByName(CampoVencPersonalizados).AsBoolean := fmEditaEvento.VencPersonalizado;
TableEventos.FieldByName(CampoVencMensalidades).AsBoolean := fmEditaEvento.VencMensalidades;
if (fmEditaEvento.VencMensalidades) then
begin
TableEventos.FieldByName(CampoMesPrimeiroVenc).AsInteger := fmEditaEvento.MesPrimeiroVenc;
TableEventos.FieldByName(CampoAnoPrimeiroVenc).AsInteger := fmEditaEvento.AnoPrimeiroVenc;
end else
begin
TableEventos.FieldByName(CampoMesPrimeiroVenc).Clear;
TableEventos.FieldByName(CampoAnoPrimeiroVenc).Clear;
end;
TableEventos.Post;
TableVencimentos.First;
while TableVencimentos.RecordCount > 0 do
TableVencimentos.Delete;
if not fmEditaEvento.VencMensalidades then
begin
for i := 1 to fmEditaEvento.NumParcelas do
begin
with TableVencimentos do
begin
Append;
FieldByName(CampoCodigo).AsInteger := fmEditaEvento.CodEvento;
FieldByName(CampoParcela).AsInteger := i;
FieldByName(CampoVencimento).AsDateTime := fmEditaEvento.Vencimento[i];
Post;
end;
end;
end;
end;
fmEditaEvento.Free;
end;
procedure TfmEditaEvento.chkVencPersonalizadosClick(Sender: TObject);
begin
edNumParcelas.ReadOnly := not chkVencPersonalizados.Checked;
dbgVencimentos.Columns[1].ReadOnly := not chkVencPersonalizados.Checked;
chkVencMensalidades.Enabled := chkVencPersonalizados.Checked;
cboMesPrimeiroVenc.Enabled := chkVencPersonalizados.Checked;
edAnoPrimeiroVenc.ReadOnly := not chkVencPersonalizados.Checked;
if chkVencPersonalizados.Checked then
begin
edNumParcelas.Color := clWindow;
dbgVencimentos.Columns[1].Color := clWindow;
edAnoPrimeiroVenc.Color := clWindow;
end else
begin
edNumParcelas.Color := clBtnFace;
dbgVencimentos.Columns[1].Color := clBtnFace;
edAnoPrimeiroVenc.Color := clBtnFace;
end;
end;
function TfmEditaEvento.GetVencPersonalizado: Boolean;
begin
Result := chkVencPersonalizados.Checked;
end;
procedure TfmEditaEvento.SetVencPersonalizado(const Value: Boolean);
begin
chkVencPersonalizados.Checked := Value;
chkVencPersonalizadosClick(chkVencPersonalizados);
end;
procedure TfmEditaEvento.chkValPersonalizadoClick(Sender: TObject);
begin
lbValParcela.Enabled := chkValPersonalizado.Checked;
lbValTotal.Enabled := chkValPersonalizado.Checked;
edValorParcela.ReadOnly := not chkValPersonalizado.Checked;
edValorTotal.ReadOnly := not chkValPersonalizado.Checked;
end;
procedure TfmEditaEvento.SetValorPersonalizado(const Value: Boolean);
begin
chkValPersonalizado.Checked := Value;
chkValPersonalizadoClick(chkValPersonalizado);
end;
function TfmEditaEvento.GetValorPersonalizado: Boolean;
begin
Result := chkValPersonalizado.Checked;
end;
class function TfmEditaEvento.Alterar( Parametros: TParametrosEditaEvento): Boolean;
begin
with Parametros do
Result := Alterar( TableEventos, CampoCodigo, CampoNome, CampoVencPersonalizados,
CampoNumParcelas, CampoVencMensalidades, CampoMesPrimeiroVenc,
CampoAnoPrimeiroVenc, CampoValor, CampoValorPersonalizado,
TableVencimentos, CampoParcela, CampoVencimento, ValorOpcional,
ValorOriginal, CodtabPrecos );
end;
procedure TfmEditaEvento.SetValorOriginal(const Value: Double);
begin
FValorOriginal := Value;
end;
function TfmEditaEvento.GetVencMensalidades: Boolean;
begin
Result := chkVencMensalidades.Checked;
end;
procedure TfmEditaEvento.SetVencMensalidades(const Value: Boolean);
begin
chkVencMensalidades.Checked := Value;
end;
function TfmEditaEvento.GetMesPrimeiroVenc: Integer;
begin
Result := cboMesPrimeiroVenc.ItemIndex + 1;
end;
procedure TfmEditaEvento.SetMesPrimeiroVenc(const Value: Integer);
begin
cboMesPrimeiroVenc.ItemIndex := Value - 1;
end;
procedure TfmEditaEvento.chkVencMensalidadesClick(Sender: TObject);
begin
lblGridVencimentos.Visible := not chkVencMensalidades.Checked;
dbgVencimentos.Visible := not chkVencMensalidades.Checked;
lblPrimeiroVencimento.Visible := chkVencMensalidades.Checked;
cboMesPrimeiroVenc.Visible := chkVencMensalidades.Checked;
edAnoPrimeiroVenc.Visible := chkVencMensalidades.Checked;
if (dbgVencimentos.Visible) then
AtualizaNumeroVencimentos(NumParcelas);
end;
function TfmEditaEvento.GetAnoPrimeiroVenc: Integer;
begin
Result := StrToIntDef(edAnoPrimeiroVenc.Text, 0);
end;
procedure TfmEditaEvento.SetAnoPrimeiroVenc(const Value: Integer);
begin
if Value = 0 then
edAnoPrimeiroVenc.Text := ''
else
edAnoPrimeiroVenc.Text := IntToStr(Value);
end;
end.
|
unit zIEAPI;
interface
// Очиска кеша IE через API
function ClearIECache : boolean;
// Вычисление количества элементов в кеше IE через API
function GetIECacheItemsCount : integer;
implementation
uses windows, wininet;
// очиска кеша IE через API
function ClearIECache : boolean;
var
lpEntryInfo: PInternetCacheEntryInfo;
hCacheDir: LongWord;
dwEntrySize: LongWord;
dwLastError: LongWord;
begin
Result := false;
dwEntrySize := 0;
FindFirstUrlCacheEntry(nil, TInternetCacheEntryInfo(nil^), dwEntrySize);
GetMem(lpEntryInfo, dwEntrySize);
hCacheDir := FindFirstUrlCacheEntry(nil, lpEntryInfo^, dwEntrySize);
if (hCacheDir <> 0) then
DeleteUrlCacheEntry(lpEntryInfo^.lpszSourceUrlName);
FreeMem(lpEntryInfo);
repeat
dwEntrySize := 0;
FindNextUrlCacheEntry(hCacheDir, TInternetCacheEntryInfo(nil^),
dwEntrySize);
dwLastError := GetLastError();
if (GetLastError = ERROR_INSUFFICIENT_BUFFER) then
begin
GetMem(lpEntryInfo, dwEntrySize);
if (FindNextUrlCacheEntry(hCacheDir, lpEntryInfo^, dwEntrySize)) then
DeleteUrlCacheEntry(lpEntryInfo^.lpszSourceUrlName);
FreeMem(lpEntryInfo);
end;
until (dwLastError = ERROR_NO_MORE_ITEMS);
FindCloseUrlCache(hCacheDir);
Result := true;
end;
// очиска кеша IE через API
function GetIECacheItemsCount : integer;
var
lpEntryInfo: PInternetCacheEntryInfo;
hCacheDir: LongWord;
dwEntrySize: LongWord;
dwLastError: LongWord;
begin
Result := 0;
dwEntrySize := 0;
FindFirstUrlCacheEntry(nil, TInternetCacheEntryInfo(nil^), dwEntrySize);
GetMem(lpEntryInfo, dwEntrySize);
hCacheDir := FindFirstUrlCacheEntry(nil, lpEntryInfo^, dwEntrySize);
if (hCacheDir <> 0) then
inc(Result);
FreeMem(lpEntryInfo);
repeat
dwEntrySize := 0;
FindNextUrlCacheEntry(hCacheDir, TInternetCacheEntryInfo(nil^), dwEntrySize);
dwLastError := GetLastError();
if (GetLastError = ERROR_INSUFFICIENT_BUFFER) then
begin
GetMem(lpEntryInfo, dwEntrySize);
if (FindNextUrlCacheEntry(hCacheDir, lpEntryInfo^, dwEntrySize)) then
inc(Result);
FreeMem(lpEntryInfo);
end;
until (dwLastError = ERROR_NO_MORE_ITEMS);
FindCloseUrlCache(hCacheDir);
end;
end.
|
unit CodecSettings;
interface
{$WARN UNIT_PLATFORM OFF}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, System.UITypes, Winapi.ShellAPI,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ImgList, Vcl.ComCtrls, Vcl.StdCtrls,
Vcl.Samples.Spin, Vcl.Buttons, Vcl.ExtCtrls, Vcl.FileCtrl,
Vcl.Imaging.pngimage, Vcl.Menus,
Profile,
GraphicsGroupRadio, GraphicsButton, VideoConverterInt;
type
TfrmCodecSettings = class(TForm)
PageControl1: TPageControl;
TabSheet2: TTabSheet;
Panel1: TPanel;
sbHD: TGraphicsGroupRadio;
sbVideo: TGraphicsGroupRadio;
sbDevice: TGraphicsGroupRadio;
sbWeb: TGraphicsGroupRadio;
sbApp: TGraphicsGroupRadio;
sbAudio: TGraphicsGroupRadio;
Panel2: TPanel;
lbFormat: TListBox;
memoDec: TMemo;
TabSheet3: TTabSheet;
lblFilter: TLabel;
gbVideo: TGroupBox;
lblVCodec: TLabel;
lblResolution: TLabel;
lblWidth: TLabel;
lblHeight: TLabel;
lblFrameRate: TLabel;
lblVBitrate: TLabel;
lblHintVBitrate: TLabel;
lblHitFrameRate: TLabel;
lblAspect: TLinkLabel;
cbVCodec: TComboBox;
cbResolution: TComboBox;
cbFrameRate: TComboBox;
cbVBitrate: TComboBox;
spWidth: TSpinEdit;
spHeight: TSpinEdit;
gbAudio: TGroupBox;
lblACodec: TLabel;
lblChannels: TLabel;
lblABitRate: TLabel;
lblHintABitrate: TLabel;
lblSampleRate: TLabel;
lblHintSampleRate: TLabel;
cbACodec: TComboBox;
cbChannels: TComboBox;
cbABitrate: TComboBox;
cbSampleRate: TComboBox;
cbTarget: TComboBox;
btnCancel: TButton;
PopupMenu3: TPopupMenu;
ClipAspect4x3: TMenuItem;
ClipAspect16x9: TMenuItem;
ImageList1: TImageList;
procedure SpeedButtonClick(Sender: TObject);
procedure lbFormatClick(Sender: TObject);
procedure cbResolutionChange(Sender: TObject);
procedure spWidthChange(Sender: TObject);
procedure spHeightChange(Sender: TObject);
procedure lbFormatDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
procedure FormCreate(Sender: TObject);
procedure cbTargetChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ClipAspect4x3Click(Sender: TObject);
procedure ClipAspect16x9Click(Sender: TObject);
procedure cbVCodecChange(Sender: TObject);
procedure cbFrameRateChange(Sender: TObject);
procedure cbVBitrateChange(Sender: TObject);
procedure cbACodecChange(Sender: TObject);
procedure cbSampleRateChange(Sender: TObject);
procedure cbChannelsChange(Sender: TObject);
procedure cbABitrateChange(Sender: TObject);
private
{ Private declarations }
FChanging: Boolean;
procedure SetProfileValues();
procedure SetTargetValues();
procedure SetVideoValues();
procedure SetAudioValues();
public
{ Public declarations }
end;
implementation
uses
Main, Defines, Functions, ImageResource, CommonData;
{$R *.dfm}
procedure TfrmCodecSettings.SpeedButtonClick(Sender: TObject);
begin
if FChanging then Exit;
FChanging := TRUE;
if sbHD.Down then
begin
_ProfleSettings.m_Group := GROUP_HD;
end else if sbVideo.Down then
begin
_ProfleSettings.m_Group := GROUP_VIDEO;
end else if sbDevice.Down then
begin
_ProfleSettings.m_Group := GROUP_DEVICE;
end else if sbWeb.Down then
begin
_ProfleSettings.m_Group := GROUP_WEB;
end else if sbApp.Down then
begin
_ProfleSettings.m_Group := GROUP_APP;
end else if sbAudio.Down then
begin
_ProfleSettings.m_Group := GROUP_AUDIO;
end;
GetDefaultProfileSetting1(_ProfleSettings, _ProfleSettings.m_Group);
SetProfileValues();
SetTargetValues();
SetVideoValues();
SetAudioValues();
FChanging := FALSE;
end;
procedure TfrmCodecSettings.lbFormatClick(Sender: TObject);
begin
if FChanging then Exit;
FChanging := TRUE;
_ProfleSettings.m_Profile := lbFormat.ItemIndex;
GetDefaultProfileSetting2(_ProfleSettings, _ProfleSettings.m_Group, _ProfleSettings.m_Profile);
memoDec.Text := GetProfileDesc(_ProfleSettings);
SetTargetValues();
SetVideoValues();
SetAudioValues();
FChanging := FALSE;
end;
procedure TfrmCodecSettings.lbFormatDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
Profile: PProfileTarget;
Text : String;
begin
Profile := PProfileTarget(lbFormat.Items.Objects[Index]);
Text := lbFormat.Items[Index];
lbFormat.Canvas.FillRect(Rect);
DrawProfileThumbnail(Profile, lbFormat.Canvas.Handle, Rect.Left + 2, Rect.Top + 1);
Rect.Left := Rect.Left + THUMBNAIL_WIDTH + 5;
lbFormat.Canvas.TextRect(Rect,
Rect.Left,
Rect.Top + (Rect.Bottom - Rect.Top - lbFormat.Canvas.TextHeight(Text)) div 2,
Text);
end;
procedure TfrmCodecSettings.cbABitrateChange(Sender: TObject);
begin
if FChanging then Exit;
_ProfleSettings.m_ABitRate := cbABitrate.ItemIndex;
end;
procedure TfrmCodecSettings.cbACodecChange(Sender: TObject);
begin
if FChanging then Exit;
_ProfleSettings.m_ACodec := cbACodec.ItemIndex;
end;
procedure TfrmCodecSettings.cbChannelsChange(Sender: TObject);
begin
if FChanging then Exit;
_ProfleSettings.m_Channel := cbChannels.ItemIndex;
end;
procedure TfrmCodecSettings.cbFrameRateChange(Sender: TObject);
begin
if FChanging then Exit;
_ProfleSettings.m_FrameRate := cbFrameRate.ItemIndex;
end;
procedure TfrmCodecSettings.cbResolutionChange(Sender: TObject);
begin
if FChanging then Exit;
FChanging := TRUE;
_ProfleSettings.m_Res := Integer(cbResolution.Items.Objects[cbResolution.ItemIndex]);
case _ProfleSettings.m_Res of
VIDEO_RES_CUSTOM:
begin
spWidth.Enabled := TRUE;
spHeight.Enabled := TRUE;
end;
else
begin
SetResolutionByIndex(_ProfleSettings, _ProfleSettings.m_Res);
spWidth.Enabled := FALSE;
spHeight.Enabled := FALSE;
end;
end;
spWidth.Value := OutputWidth();
spHeight.Value := OutputHeight();
lblAspect.Caption := GetVideoAspectString(_ProfleSettings);
FChanging := FALSE;
end;
procedure TfrmCodecSettings.cbSampleRateChange(Sender: TObject);
begin
if FChanging then Exit;
_ProfleSettings.m_SampleRate := cbSampleRate.ItemIndex;
end;
procedure TfrmCodecSettings.spWidthChange(Sender: TObject);
begin
if FChanging then Exit;
FChanging := TRUE;
_ProfleSettings.m_ResCustom.m_Width := spWidth.Value;
cbResolution.ItemIndex := GetVideoResolutionIndex(_ProfleSettings);
lblAspect.Caption := GetVideoAspectString(_ProfleSettings);
FChanging := FALSE;
end;
procedure TfrmCodecSettings.spHeightChange(Sender: TObject);
begin
if FChanging then Exit;
FChanging := TRUE;
_ProfleSettings.m_ResCustom.m_Height := spHeight.Value;
cbResolution.ItemIndex := GetVideoResolutionIndex(_ProfleSettings);
lblAspect.Caption := GetVideoAspectString(_ProfleSettings);
FChanging := FALSE;
end;
procedure TfrmCodecSettings.SetProfileValues();
begin
AddProfileStrins(_ProfleSettings, lbFormat.Items);
lbFormat.ItemIndex := _ProfleSettings.m_Profile;
memoDec.Text := GetProfileDesc(_ProfleSettings);
SetTargetValues();
SetVideoValues();
SetAudioValues();
end;
procedure TfrmCodecSettings.SetTargetValues();
begin
AddTargetStrins(_ProfleSettings, cbTarget.Items);
cbTarget.ItemIndex := _ProfleSettings.m_Target;
end;
procedure TfrmCodecSettings.SetVideoValues();
begin
if _ProfleSettings.m_VCodec = -1 then
begin
cbVCodec.Items.Clear();
cbResolution.Items.Clear();
cbFrameRate.Items.Clear();
cbVBitrate.Items.Clear();
spWidth.Value := 0;
spHeight.Value := 0;
lblAspect.Caption := '';
cbVCodec.Enabled := FALSE;
cbResolution.Enabled := FALSE;
cbFrameRate.Enabled := FALSE;
cbVBitrate.Enabled := FALSE;
spWidth.Enabled := FALSE;
spHeight.Enabled := FALSE;
end else begin
AddVideoCodecStrins(_ProfleSettings, cbVCodec.Items);
AddVideoResolutionStrins(_ProfleSettings, cbResolution.Items);
AddVideoFrameRateStrins(_ProfleSettings, cbFrameRate.Items);
AddVideoBitRateStrins(_ProfleSettings, cbVBitrate.Items);
spWidth.Value := OutputWidth();
spHeight.Value := OutputHeight();
spWidth.Enabled := _ProfleSettings.m_Res = VIDEO_RES_CUSTOM;
spHeight.Enabled := _ProfleSettings.m_Res = VIDEO_RES_CUSTOM;
lblAspect.Caption := GetVideoAspectString(_ProfleSettings);
cbVCodec.Enabled := TRUE;
cbFrameRate.Enabled := TRUE;
cbVBitrate.Enabled := TRUE;
cbResolution.Enabled := TRUE;
cbVCodec.ItemIndex := _ProfleSettings.m_VCodec;
cbResolution.ItemIndex := GetResolutionIndex(_ProfleSettings);
cbFrameRate.ItemIndex := _ProfleSettings.m_FrameRate;
cbVBitrate.ItemIndex := _ProfleSettings.m_VBitRate;
end;
end;
procedure TfrmCodecSettings.SetAudioValues();
begin
if _ProfleSettings.m_ACodec = -1 then
begin
cbACodec.Items.Clear();
cbSampleRate.Items.Clear();
cbChannels.Items.Clear();
cbABitrate.Items.Clear();
cbACodec.Enabled := FALSE;
cbSampleRate.Enabled := FALSE;
cbChannels.Enabled := FALSE;
cbABitrate.Enabled := FALSE;
end else begin
AddAudioCodecStrins(_ProfleSettings, cbACodec.Items);
AddAudioSampleRateStrins(_ProfleSettings, cbSampleRate.Items);
AddAudioChannelStrins(_ProfleSettings, cbChannels.Items);
AddAudioBitRateStrins(_ProfleSettings, cbABitrate.Items);
cbACodec.Enabled := TRUE;
cbSampleRate.Enabled := TRUE;
cbChannels.Enabled := TRUE;
cbABitrate.Enabled := TRUE;
cbACodec.ItemIndex := _ProfleSettings.m_ACodec;
cbSampleRate.ItemIndex := _ProfleSettings.m_SampleRate;
cbChannels.ItemIndex := _ProfleSettings.m_Channel;
cbABitrate.ItemIndex := _ProfleSettings.m_ABitRate;
end;
end;
procedure TfrmCodecSettings.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmCodecSettings.FormCreate(Sender: TObject);
begin
FChanging := TRUE;
PageControl1.ActivePageIndex := 0;
case _ProfleSettings.m_Group of
GROUP_HD: sbHD.Down := TRUE;
GROUP_VIDEO: sbVideo.Down := TRUE;
GROUP_DEVICE: sbDevice.Down := TRUE;
GROUP_WEB: sbWeb.Down := TRUE;
GROUP_APP: sbApp.Down := TRUE;
GROUP_AUDIO: sbAudio.Down := TRUE;
end;
SetProfileValues();
sbHD.SetImage(imageHD, 'HD Video');
sbVideo.SetImage(imageVideo, 'Video');
sbDevice.SetImage(imageDevice, 'Device');
sbWeb.SetImage(imageWeb, 'Web');
sbApp.SetImage(imageApp, 'Application');
sbAudio.SetImage(imageMusic, 'Music');
FChanging := FALSE;
end;
procedure TfrmCodecSettings.cbTargetChange(Sender: TObject);
begin
if FChanging then Exit;
FChanging := TRUE;
_ProfleSettings.m_Target := cbTarget.ItemIndex;
GetDefaultProfileSetting3(_ProfleSettings, _ProfleSettings.m_Group, _ProfleSettings.m_Profile, _ProfleSettings.m_Target);
SetVideoValues();
SetAudioValues();
FChanging := FALSE;
end;
procedure TfrmCodecSettings.cbVBitrateChange(Sender: TObject);
begin
if FChanging then Exit;
_ProfleSettings.m_VBitRate := cbVBitrate.ItemIndex;
end;
procedure TfrmCodecSettings.cbVCodecChange(Sender: TObject);
begin
if FChanging then Exit;
_ProfleSettings.m_VCodec := cbVCodec.ItemIndex;
end;
procedure TfrmCodecSettings.ClipAspect16x9Click(Sender: TObject);
var
n: Integer;
begin
FChanging := TRUE;
n := (_ProfleSettings.m_ResCustom.m_Width + 63) div 64;
_ProfleSettings.m_ResCustom.m_Width := n * 64;
_ProfleSettings.m_ResCustom.m_Height := n * 48;
spWidth.Value := OutputWidth();
spHeight.Value := OutputHeight();
lblAspect.Caption := GetAspectString(OutputWidth(), OutputHeight(), TRUE);
FChanging := FALSE;
end;
procedure TfrmCodecSettings.ClipAspect4x3Click(Sender: TObject);
var
n: Integer;
begin
FChanging := TRUE;
n := (_ProfleSettings.m_ResCustom.m_Width + 255) div 256;
_ProfleSettings.m_ResCustom.m_Width := n * 256;
_ProfleSettings.m_ResCustom.m_Height := n * 144;
spWidth.Value := OutputWidth();
spHeight.Value := OutputHeight();
lblAspect.Caption := GetAspectString(OutputWidth(), OutputHeight(), TRUE);
FChanging := FALSE;
end;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://carme.atbx.net/secure/ws/awsi/MarshallSwiftServer.php?wsdl
// Encoding : ISO-8859-1
// Version : 1.0
// (9/19/2013 10:02:02 AM - 1.33.2.5)
// ************************************************************************ //
unit AWSI_Server_MarshallSwift;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Borland types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:string - "http://www.w3.org/2001/XMLSchema"
// !:int - "http://www.w3.org/2001/XMLSchema"
clsUserCredentials = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsResults = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsAcknowledgementResponseData = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsAcknowledgementResponse = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsCheckSubscriptionResponseData = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsCheckSubscriptionResponse = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsIsActiveMemberResponseData = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsIsActiveMemberResponse = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsGetRegionFromZipResponseData = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsGetRegionFromZipResponse = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsGetSecurityTokenForExistingResponseData = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsGetSecurityTokenForExistingResponse = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsGetSecurityTokenForNewResponseData = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsGetSecurityTokenForNewResponse = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsAcknowledgement = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsCheckSubscriptionRequest = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsIsActiveMemberRequest = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsGetRegionFromZipRequest = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsGetSecurityTokenForExistingRequest = class; { "http://carme.atbx.net/secure/ws/WSDL" }
clsGetSecurityTokenForNewRequest = class; { "http://carme.atbx.net/secure/ws/WSDL" }
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsUserCredentials = class(TRemotable)
private
FUsername: WideString;
FPassword: WideString;
FCompanyKey: WideString;
FOrderNumberKey: WideString;
FPurchase: Integer;
FCustomerOrderNumber: WideString;
FServiceId: WideString;
published
property Username: WideString read FUsername write FUsername;
property Password: WideString read FPassword write FPassword;
property CompanyKey: WideString read FCompanyKey write FCompanyKey;
property OrderNumberKey: WideString read FOrderNumberKey write FOrderNumberKey;
property Purchase: Integer read FPurchase write FPurchase;
property CustomerOrderNumber: WideString read FCustomerOrderNumber write FCustomerOrderNumber;
property ServiceId: WideString read FServiceId write FServiceId;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsResults = class(TRemotable)
private
FCode: Integer;
FType_: WideString;
FDescription: WideString;
published
property Code: Integer read FCode write FCode;
property Type_: WideString read FType_ write FType_;
property Description: WideString read FDescription write FDescription;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsAcknowledgementResponseData = class(TRemotable)
private
FReceived: Integer;
published
property Received: Integer read FReceived write FReceived;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsAcknowledgementResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsAcknowledgementResponseData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsAcknowledgementResponseData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsCheckSubscriptionResponseData = class(TRemotable)
private
FCheckSubscriptionResult: WideString;
FReceived: Integer;
FServiceAcknowledgement: WideString;
published
property CheckSubscriptionResult: WideString read FCheckSubscriptionResult write FCheckSubscriptionResult;
property Received: Integer read FReceived write FReceived;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsCheckSubscriptionResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsCheckSubscriptionResponseData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsCheckSubscriptionResponseData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsIsActiveMemberResponseData = class(TRemotable)
private
FIsActiveMemberResult: Integer;
FReceived: Integer;
FServiceAcknowledgement: WideString;
published
property IsActiveMemberResult: Integer read FIsActiveMemberResult write FIsActiveMemberResult;
property Received: Integer read FReceived write FReceived;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsIsActiveMemberResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsIsActiveMemberResponseData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsIsActiveMemberResponseData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsGetRegionFromZipResponseData = class(TRemotable)
private
FGetRegionFromZipResponse: WideString;
published
property GetRegionFromZipResponse: WideString read FGetRegionFromZipResponse write FGetRegionFromZipResponse;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsGetRegionFromZipResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsGetRegionFromZipResponseData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsGetRegionFromZipResponseData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsGetSecurityTokenForExistingResponseData = class(TRemotable)
private
FSecurityToken: WideString;
FMsg: WideString;
FMsgCode: Integer;
FReceived: Integer;
FServiceAcknowledgement: WideString;
published
property SecurityToken: WideString read FSecurityToken write FSecurityToken;
property Msg: WideString read FMsg write FMsg;
property MsgCode: Integer read FMsgCode write FMsgCode;
property Received: Integer read FReceived write FReceived;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsGetSecurityTokenForExistingResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsGetSecurityTokenForExistingResponseData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsGetSecurityTokenForExistingResponseData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsGetSecurityTokenForNewResponseData = class(TRemotable)
private
FSecurityToken: WideString;
FMsg: WideString;
FEstimateId: Integer;
FMsgCode: Integer;
FReceived: Integer;
FServiceAcknowledgement: WideString;
published
property SecurityToken: WideString read FSecurityToken write FSecurityToken;
property Msg: WideString read FMsg write FMsg;
property EstimateId: Integer read FEstimateId write FEstimateId;
property MsgCode: Integer read FMsgCode write FMsgCode;
property Received: Integer read FReceived write FReceived;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsGetSecurityTokenForNewResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsGetSecurityTokenForNewResponseData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsGetSecurityTokenForNewResponseData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsAcknowledgement = class(TRemotable)
private
FReceived: Integer;
FServiceAcknowledgement: WideString;
published
property Received: Integer read FReceived write FReceived;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsCheckSubscriptionRequest = class(TRemotable)
private
FStreetAddress: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
published
property StreetAddress: WideString read FStreetAddress write FStreetAddress;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsIsActiveMemberRequest = class(TRemotable)
private
FCustomerId: Integer;
FStreetAddress: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
published
property CustomerId: Integer read FCustomerId write FCustomerId;
property StreetAddress: WideString read FStreetAddress write FStreetAddress;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsGetRegionFromZipRequest = class(TRemotable)
private
FZipCode: WideString;
published
property ZipCode: WideString read FZipCode write FZipCode;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsGetSecurityTokenForExistingRequest = class(TRemotable)
private
FEstimateId: Integer;
published
property EstimateId: Integer read FEstimateId write FEstimateId;
end;
// ************************************************************************ //
// Namespace : http://carme.atbx.net/secure/ws/WSDL
// ************************************************************************ //
clsGetSecurityTokenForNewRequest = class(TRemotable)
private
FEstimateDescription: WideString;
FStreetAddress: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
published
property EstimateDescription: WideString read FEstimateDescription write FEstimateDescription;
property StreetAddress: WideString read FStreetAddress write FStreetAddress;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
end;
// ************************************************************************ //
// Namespace : MarshallSwiftServerClass
// soapAction: MarshallSwiftServerClass#%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// style : rpc
// binding : MarshallSwiftServerBinding
// service : MarshallSwiftServer
// port : MarshallSwiftServerPort
// URL : http://carme.atbx.net/secure/ws/awsi/MarshallSwiftServer.php
// ************************************************************************ //
MarshallSwiftServerPortType = interface(IInvokable)
['{3F07E3B3-C7F4-4127-BD19-75D38AA3AD9D}']
function MarshallSwiftServices_Acknowledgement(const UserCredentials: clsUserCredentials; const Acknowledgement: clsAcknowledgement): clsAcknowledgementResponse; stdcall;
function MarshallSwiftServices_CheckSubscription(const UserCredentials: clsUserCredentials; const CheckSubscriptionDetails: clsCheckSubscriptionRequest): clsCheckSubscriptionResponse; stdcall;
function MarshallSwiftServices_GetRegionFromZip(const UserCredentials: clsUserCredentials; const RequestDetails: clsGetRegionFromZipRequest): clsGetRegionFromZipResponse; stdcall;
function MarshallSwiftServices_GetSecurityTokenForExisting(const UserCredentials: clsUserCredentials; const RequestDetails: clsGetSecurityTokenForExistingRequest): clsGetSecurityTokenForExistingResponse; stdcall;
function MarshallSwiftServices_GetSecurityTokenForNew(const UserCredentials: clsUserCredentials; const RequestDetails: clsGetSecurityTokenForNewRequest): clsGetSecurityTokenForNewResponse; stdcall;
function MarshallSwiftServices_IsActiveMember(const UserCredentials: clsUserCredentials; const CheckSubscriptionDetails: clsIsActiveMemberRequest): clsIsActiveMemberResponse; stdcall;
end;
function GetMarshallSwiftServerPortType(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): MarshallSwiftServerPortType;
implementation
function GetMarshallSwiftServerPortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): MarshallSwiftServerPortType;
const
defWSDL = 'http://carme.atbx.net/secure/ws/awsi/MarshallSwiftServer.php?wsdl';
defURL = 'http://carme.atbx.net/secure/ws/awsi/MarshallSwiftServer.php';
defSvc = 'MarshallSwiftServer';
defPrt = 'MarshallSwiftServerPort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as MarshallSwiftServerPortType);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
destructor clsAcknowledgementResponse.Destroy;
begin
if Assigned(FResults) then
FResults.Free;
if Assigned(FResponseData) then
FResponseData.Free;
inherited Destroy;
end;
destructor clsCheckSubscriptionResponse.Destroy;
begin
if Assigned(FResults) then
FResults.Free;
if Assigned(FResponseData) then
FResponseData.Free;
inherited Destroy;
end;
destructor clsIsActiveMemberResponse.Destroy;
begin
if Assigned(FResults) then
FResults.Free;
if Assigned(FResponseData) then
FResponseData.Free;
inherited Destroy;
end;
destructor clsGetRegionFromZipResponse.Destroy;
begin
if Assigned(FResults) then
FResults.Free;
if Assigned(FResponseData) then
FResponseData.Free;
inherited Destroy;
end;
destructor clsGetSecurityTokenForExistingResponse.Destroy;
begin
if Assigned(FResults) then
FResults.Free;
if Assigned(FResponseData) then
FResponseData.Free;
inherited Destroy;
end;
destructor clsGetSecurityTokenForNewResponse.Destroy;
begin
if Assigned(FResults) then
FResults.Free;
if Assigned(FResponseData) then
FResponseData.Free;
inherited Destroy;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(MarshallSwiftServerPortType), 'MarshallSwiftServerClass', 'ISO-8859-1');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(MarshallSwiftServerPortType), 'MarshallSwiftServerClass#%operationName%');
InvRegistry.RegisterExternalMethName(TypeInfo(MarshallSwiftServerPortType), 'MarshallSwiftServices_Acknowledgement', 'MarshallSwiftServices.Acknowledgement');
InvRegistry.RegisterExternalMethName(TypeInfo(MarshallSwiftServerPortType), 'MarshallSwiftServices_CheckSubscription', 'MarshallSwiftServices.CheckSubscription');
InvRegistry.RegisterExternalMethName(TypeInfo(MarshallSwiftServerPortType), 'MarshallSwiftServices_GetRegionFromZip', 'MarshallSwiftServices.GetRegionFromZip');
InvRegistry.RegisterExternalMethName(TypeInfo(MarshallSwiftServerPortType), 'MarshallSwiftServices_GetSecurityTokenForExisting', 'MarshallSwiftServices.GetSecurityTokenForExisting');
InvRegistry.RegisterExternalMethName(TypeInfo(MarshallSwiftServerPortType), 'MarshallSwiftServices_GetSecurityTokenForNew', 'MarshallSwiftServices.GetSecurityTokenForNew');
InvRegistry.RegisterExternalMethName(TypeInfo(MarshallSwiftServerPortType), 'MarshallSwiftServices_IsActiveMember', 'MarshallSwiftServices.IsActiveMember');
RemClassRegistry.RegisterXSClass(clsUserCredentials, 'http://carme.atbx.net/secure/ws/WSDL', 'clsUserCredentials');
RemClassRegistry.RegisterXSClass(clsResults, 'http://carme.atbx.net/secure/ws/WSDL', 'clsResults');
RemClassRegistry.RegisterExternalPropName(TypeInfo(clsResults), 'Type_', 'Type');
RemClassRegistry.RegisterXSClass(clsAcknowledgementResponseData, 'http://carme.atbx.net/secure/ws/WSDL', 'clsAcknowledgementResponseData');
RemClassRegistry.RegisterXSClass(clsAcknowledgementResponse, 'http://carme.atbx.net/secure/ws/WSDL', 'clsAcknowledgementResponse');
RemClassRegistry.RegisterXSClass(clsCheckSubscriptionResponseData, 'http://carme.atbx.net/secure/ws/WSDL', 'clsCheckSubscriptionResponseData');
RemClassRegistry.RegisterXSClass(clsCheckSubscriptionResponse, 'http://carme.atbx.net/secure/ws/WSDL', 'clsCheckSubscriptionResponse');
RemClassRegistry.RegisterXSClass(clsIsActiveMemberResponseData, 'http://carme.atbx.net/secure/ws/WSDL', 'clsIsActiveMemberResponseData');
RemClassRegistry.RegisterXSClass(clsIsActiveMemberResponse, 'http://carme.atbx.net/secure/ws/WSDL', 'clsIsActiveMemberResponse');
RemClassRegistry.RegisterXSClass(clsGetRegionFromZipResponseData, 'http://carme.atbx.net/secure/ws/WSDL', 'clsGetRegionFromZipResponseData');
RemClassRegistry.RegisterXSClass(clsGetRegionFromZipResponse, 'http://carme.atbx.net/secure/ws/WSDL', 'clsGetRegionFromZipResponse');
RemClassRegistry.RegisterXSClass(clsGetSecurityTokenForExistingResponseData, 'http://carme.atbx.net/secure/ws/WSDL', 'clsGetSecurityTokenForExistingResponseData');
RemClassRegistry.RegisterXSClass(clsGetSecurityTokenForExistingResponse, 'http://carme.atbx.net/secure/ws/WSDL', 'clsGetSecurityTokenForExistingResponse');
RemClassRegistry.RegisterXSClass(clsGetSecurityTokenForNewResponseData, 'http://carme.atbx.net/secure/ws/WSDL', 'clsGetSecurityTokenForNewResponseData');
RemClassRegistry.RegisterXSClass(clsGetSecurityTokenForNewResponse, 'http://carme.atbx.net/secure/ws/WSDL', 'clsGetSecurityTokenForNewResponse');
RemClassRegistry.RegisterXSClass(clsAcknowledgement, 'http://carme.atbx.net/secure/ws/WSDL', 'clsAcknowledgement');
RemClassRegistry.RegisterXSClass(clsCheckSubscriptionRequest, 'http://carme.atbx.net/secure/ws/WSDL', 'clsCheckSubscriptionRequest');
RemClassRegistry.RegisterXSClass(clsIsActiveMemberRequest, 'http://carme.atbx.net/secure/ws/WSDL', 'clsIsActiveMemberRequest');
RemClassRegistry.RegisterXSClass(clsGetRegionFromZipRequest, 'http://carme.atbx.net/secure/ws/WSDL', 'clsGetRegionFromZipRequest');
RemClassRegistry.RegisterXSClass(clsGetSecurityTokenForExistingRequest, 'http://carme.atbx.net/secure/ws/WSDL', 'clsGetSecurityTokenForExistingRequest');
RemClassRegistry.RegisterXSClass(clsGetSecurityTokenForNewRequest, 'http://carme.atbx.net/secure/ws/WSDL', 'clsGetSecurityTokenForNewRequest');
end. |
unit LocalStorage;
interface
uses
System.Classes, System.SysUtils, Vcl.Forms, Vcl.Dialogs,
IniUtils, VKDBFDataSet, LocalWorkUnit, db;
function InitLocalDataBaseHead(Owner: TPersistent; LocalDataBaseHead: TVKSmartDBF): Boolean;
function InitLocalDataBaseBody(Owner: TPersistent; LocalDataBaseBody: TVKSmartDBF): Boolean;
function InitLocalDataBaseDiff(Owner: TPersistent; LocalDataBaseDiff: TVKSmartDBF): Boolean;
implementation
procedure InitLocalTable(DS: TVKSmartDBF; AFileName: string);
begin
DS.DBFFileName := AnsiString(AFileName);
DS.OEM := False;
DS.AccessMode.OpenReadWrite := True;
end;
function InitLocalDataBaseHead(Owner: TPersistent; LocalDataBaseHead: TVKSmartDBF): Boolean;
var
LFieldDefs: TVKDBFFieldDefs;
begin
InitLocalTable(LocalDataBaseHead, iniLocalDataBaseHead);
try
if not FileExists(iniLocalDataBaseHead) then
begin
AddIntField(LocalDataBaseHead, 'ID');//id чека
AddStrField(LocalDataBaseHead, 'UID',50);//uid чека
AddDateField(LocalDataBaseHead, 'DATE'); //дата/Время чека
AddIntField(LocalDataBaseHead, 'PAIDTYPE'); //тип оплаты
AddStrField(LocalDataBaseHead, 'CASH',20); //серийник аппарата
AddIntField(LocalDataBaseHead, 'MANAGER'); //Id Менеджера (VIP)
AddStrField(LocalDataBaseHead, 'BAYER',254); //Покупатель (VIP)
AddBoolField(LocalDataBaseHead, 'SAVE'); //Покупатель (VIP)
AddBoolField(LocalDataBaseHead, 'COMPL'); //Покупатель (VIP)
AddBoolField(LocalDataBaseHead, 'NEEDCOMPL'); //нужно провести документ
AddBoolField(LocalDataBaseHead, 'NOTMCS'); //Не участвует в расчете НТЗ
AddStrField(LocalDataBaseHead, 'FISCID',50); //Номер фискального чека
//***20.07.16
AddIntField(LocalDataBaseHead, 'DISCOUNTID'); //Id Проекта дисконтных карт
AddStrField(LocalDataBaseHead, 'DISCOUNTN',254); //Название Проекта дисконтных карт
AddStrField(LocalDataBaseHead, 'DISCOUNT',50); //№ Дисконтной карты
//***16.08.16
AddStrField(LocalDataBaseHead, 'BAYERPHONE',50); //Контактный телефон (Покупателя) - BayerPhone
AddStrField(LocalDataBaseHead, 'CONFIRMED',50); //Статус заказа (Состояние VIP-чека) - ConfirmedKind
AddStrField(LocalDataBaseHead, 'NUMORDER',50); //Номер заказа (с сайта) - InvNumberOrder
AddStrField(LocalDataBaseHead, 'CONFIRMEDC',50); //Статус заказа (Состояние VIP-чека) - ConfirmedKindClient
//***24.01.17
AddStrField(LocalDataBaseHead, 'USERSESION',50); //Для сервиса - реальная сесия при продаже
//***08.04.17
AddIntField(LocalDataBaseHead, 'PMEDICALID'); //Id Медицинское учреждение(Соц. проект)
AddStrField(LocalDataBaseHead, 'PMEDICALN',254); //Название Медицинское учреждение(Соц. проект)
AddStrField(LocalDataBaseHead, 'AMBULANCE',50); //№ амбулатории (Соц. проект)
AddStrField(LocalDataBaseHead, 'MEDICSP',254); //ФИО врача (Соц. проект)
AddStrField(LocalDataBaseHead, 'INVNUMSP',50); //номер рецепта (Соц. проект)
AddDateField(LocalDataBaseHead, 'OPERDATESP'); //дата рецепта (Соц. проект)
//***15.06.17
AddIntField(LocalDataBaseHead, 'SPKINDID'); //Id Вид СП
//***02.02.18
AddIntField(LocalDataBaseHead, 'PROMOCODE'); //Id промокода
//***28.06.18
AddIntField(LocalDataBaseHead, 'MANUALDISC'); //Ручная скидка
//***02.10.18
AddFloatField(LocalDataBaseHead, 'SUMMPAYADD'); //Доплата по чеку
//***14.01.19
AddIntField(LocalDataBaseHead, 'MEMBERSPID'); //ФИО пациента
//***14.01.19
AddBoolField(LocalDataBaseHead, 'SITEDISC'); //Дисконт через сайт
//***20.02.19
AddIntField(LocalDataBaseHead, 'BANKPOS'); //Банк POS терминала
//***25.02.19
AddIntField(LocalDataBaseHead, 'JACKCHECK'); //Галка
//***02.04.19
AddBoolField(LocalDataBaseHead, 'ROUNDDOWN'); //Округление в низ
//***13.05.19
AddIntField(LocalDataBaseHead, 'PDKINDID'); //Тип срок/не срок
AddStrField(LocalDataBaseHead, 'CONFCODESP', 10); //Код подтверждения рецепта
//***07.11.19
AddIntField(LocalDataBaseHead, 'LOYALTYID'); //Программа лояльности
//***08.01.20
AddIntField(LocalDataBaseHead, 'LOYALTYSM'); //Программа лояльности накопительная
AddFloatField(LocalDataBaseHead,'LOYALSMSUM'); //Сумма скидки по Программа лояльности накопительная
//***11.10.20
AddStrField(LocalDataBaseHead, 'MEDICFS', 100); //ФИО врача (на продажу)
AddStrField(LocalDataBaseHead, 'BUYERFS', 100); //ФИО покупателя (на продажу)
AddStrField(LocalDataBaseHead, 'BUYERFSP', 100); //Телефон покупателя (на продажу)
AddStrField(LocalDataBaseHead, 'DISTPROMO', 254); //Раздача акционных материалов
//***05.03.21
AddIntField(LocalDataBaseHead, 'MEDICKID'); //ФИО врача (МИС «Каштан»)
AddIntField(LocalDataBaseHead, 'MEMBERKID'); //ФИО пациента (МИС «Каштан»)
//***10.03.21
AddBoolField(LocalDataBaseHead, 'ISCORRMARK'); //Корректировка суммы маркетинг в ЗП по подразделению
AddBoolField(LocalDataBaseHead, 'ISCORRIA'); //Корректировка суммы нелеквидов в ЗП по подразделению
//***15.08.21
AddBoolField(LocalDataBaseHead, 'ISDOCTORS'); //Врачи
//***15.08.21
AddBoolField(LocalDataBaseHead, 'ISDISCCOM'); //Дисконт проведен на сайте
//***01.09.21
AddIntField(LocalDataBaseHead, 'ZREPORT'); //Номер Z отчета
//***04.10.21
AddIntField(LocalDataBaseHead, 'MEDPRSPID'); //Медицинская программа соц. проектов
//***26.10.21
AddBoolField(LocalDataBaseHead, 'ISMANUAL'); //Ручной выбор медикамента
//***27.10.21
AddIntField(LocalDataBaseHead, 'CAT1303ID'); //Категория 1303
//***26.10.21
AddBoolField(LocalDataBaseHead, 'ISERRORRO'); //ВИП чек по ошибке РРО
//***15.03.22
AddBoolField(LocalDataBaseHead, 'ISPAPERRSP'); // Бумажный рецепт по СП
//***19.02.23
AddIntField(LocalDataBaseHead, 'USERKEYID'); //Чей файловый ключ использовался при пробитии чека.
//***04.08.23
AddStrField(LocalDataBaseHead, 'RRN', 25); //RRN уникальный номер транзакции
LocalDataBaseHead.CreateTable;
end
// !!!добавляем НОВЫЕ поля
else
with LocalDataBaseHead do
begin
LFieldDefs := TVKDBFFieldDefs.Create(Owner);
Open;
if FindField('DISCOUNTID') = nil then AddIntField(LFieldDefs, 'DISCOUNTID');
if FindField('DISCOUNTN') = nil then AddStrField(LFieldDefs, 'DISCOUNTN', 254);
if FindField('DISCOUNT') = nil then AddStrField(LFieldDefs, 'DISCOUNT', 50);
//***16.08.16
if FindField('BAYERPHONE') = nil then AddStrField(LFieldDefs, 'BAYERPHONE', 50);
//***16.08.16
if FindField('CONFIRMED') = nil then AddStrField(LFieldDefs, 'CONFIRMED', 50);
//***16.08.16
if FindField('NUMORDER') = nil then AddStrField(LFieldDefs, 'NUMORDER', 50);
//***25.08.16
if FindField('CONFIRMEDC') = nil then AddStrField(LFieldDefs, 'CONFIRMEDC', 50);
//***24.01.17
if FindField('USERSESION') = nil then AddStrField(LFieldDefs, 'USERSESION', 50);
//***08.04.17
if FindField('PMEDICALID') = nil then AddIntField(LFieldDefs, 'PMEDICALID');
if FindField('PMEDICALN') = nil then AddStrField(LFieldDefs, 'PMEDICALN', 254);
if FindField('AMBULANCE') = nil then AddStrField(LFieldDefs, 'AMBULANCE', 55);
if FindField('MEDICSP') = nil then AddStrField(LFieldDefs, 'MEDICSP', 254);
if FindField('INVNUMSP') = nil then AddStrField(LFieldDefs, 'INVNUMSP', 55);
if FindField('OPERDATESP') = nil then AddDateField(LFieldDefs, 'OPERDATESP');
//***15.06.17
if FindField('SPKINDID') = nil then AddIntField(LFieldDefs, 'SPKINDID');
//***02.02.18
if FindField('PROMOCODE') = nil then AddIntField(LFieldDefs, 'PROMOCODE');
//***28.06.18
if FindField('MANUALDISC') = nil then AddIntField(LFieldDefs, 'MANUALDISC');
//***02.10.18
if FindField('SUMMPAYADD') = nil then AddFloatField(LFieldDefs, 'SUMMPAYADD');
//***14.01.19
if FindField('MEMBERSPID') = nil then AddIntField(LFieldDefs, 'MEMBERSPID');
//***28.01.19
if FindField('SITEDISC') = nil then AddBoolField(LFieldDefs, 'SITEDISC');
//***20.02.19
if FindField('BANKPOS') = nil then AddIntField(LFieldDefs, 'BANKPOS');
//***25.02.19
if FindField('JACKCHECK') = nil then AddIntField(LFieldDefs, 'JACKCHECK');
//***02.04.19
if FindField('ROUNDDOWN') = nil then AddBoolField(LFieldDefs, 'ROUNDDOWN');
//***13.05.19
if FindField('PDKINDID') = nil then AddIntField(LFieldDefs, 'PDKINDID'); //Тип срок/не срок
if FindField('CONFCODESP') = nil then AddStrField(LFieldDefs, 'CONFCODESP', 55);
//***07.11.19
if FindField('LOYALTYID') = nil then AddIntField(LFieldDefs, 'LOYALTYID'); //Программа лояльности
//***08.01.20
if FindField('LOYALTYSM') = nil then AddIntField(LFieldDefs, 'LOYALTYSM'); //Программа лояльности накопительная
if FindField('LOYALSMSUM') = nil then AddFloatField(LFieldDefs, 'LOYALSMSUM');
//***11.10.20
if FindField('MEDICFS') = nil then AddStrField(LFieldDefs, 'MEDICFS', 100);
if FindField('BUYERFS') = nil then AddStrField(LFieldDefs, 'BUYERFS', 100);
if FindField('BUYERFSP') = nil then AddStrField(LFieldDefs, 'BUYERFSP', 100);
//***04.12.20
if FindField('DISTPROMO') = nil then AddStrField(LFieldDefs, 'DISTPROMO', 254);
//***05.03.21
if FindField('MEDICKID') = nil then AddIntField(LFieldDefs, 'MEDICKID'); //ФИО врача (МИС «Каштан»)
if FindField('MEMBERKID') = nil then AddIntField(LFieldDefs, 'MEMBERKID'); //ФИО пациента (МИС «Каштан»)
//***10.03.21
if FindField('ISCORRMARK') = nil then AddBoolField(LFieldDefs, 'ISCORRMARK'); //Корректировка суммы маркетинг в ЗП по подразделению
if FindField('ISCORRIA') = nil then AddBoolField(LFieldDefs, 'ISCORRIA'); //Корректировка суммы нелеквидов в ЗП по подразделению
//***15.08.21
if FindField('ISDOCTORS') = nil then AddBoolField(LFieldDefs, 'ISDOCTORS'); //Врачи
//***25.08.21
if FindField('ISDISCCOM') = nil then AddBoolField(LFieldDefs, 'ISDISCCOM'); //Дисконт проведен на сайте
//***01.09.21
if FindField('ZREPORT') = nil then AddIntField(LFieldDefs, 'ZREPORT'); //Номер Z отчета
//***04.10.21
if FindField('MEDPRSPID') = nil then AddIntField(LFieldDefs, 'MEDPRSPID'); //Медицинская программа соц. проектов
//***26.0.21
if FindField('ISMANUAL') = nil then AddBoolField(LFieldDefs, 'ISMANUAL'); //Ручной выбор медикамента
//***27.10.21
if FindField('CAT1303ID') = nil then AddIntField(LFieldDefs, 'CAT1303ID'); //Категория 1303
//***14.12.21
if FindField('ISERRORRO') = nil then AddBoolField(LFieldDefs, 'ISERRORRO'); //ВИП чек по ошибке РРО
//***15.03.22
if FindField('ISPAPERRSP') = nil then AddBoolField(LFieldDefs, 'ISPAPERRSP'); // Бумажный рецепт по СП
//***19.02.23
if FindField('USERKEYID') = nil then AddIntField(LFieldDefs, 'USERKEYID'); //Чей файловый ключ использовался при пробитии чека.
//***04.08.23
if FindField('RRN') = nil then AddStrField(LFieldDefs, 'RRN', 25); //RRN уникальный номер транзакции
//***10.09.22
if LFieldDefs.Count <> 0 then
AddFields(LFieldDefs, 1000);
Close;
end;// !!!добавляем НОВЫЕ поля
//проверка структуры
with LocalDataBaseHead do
begin
Open;
Result := not ((FindField('ID') = nil) or
(FindField('UID') = nil) or
(FindField('DATE') = nil) or
(FindField('PAIDTYPE') = nil) or
(FindField('CASH') = nil) or
(FindField('MANAGER') = nil) or
(FindField('BAYER') = nil) or
(FindField('COMPL') = nil) or
(FindField('SAVE') = nil) or
(FindField('NEEDCOMPL') = nil) or
(FindField('NOTMCS') = nil) or
(FindField('FISCID') = nil) or
//***20.07.16
(FindField('DISCOUNTID') = nil) or
(FindField('DISCOUNTN') = nil) or
(FindField('DISCOUNT') = nil) or
//***16.08.16
(FindField('BAYERPHONE') = nil) or
(FindField('CONFIRMED') = nil) or
(FindField('NUMORDER') = nil) or
(FindField('CONFIRMEDC') = nil) or
//***24.01.17
(FindField('USERSESION') = nil) or
//***08.04.17
(FindField('PMEDICALID') = nil) or
(FindField('PMEDICALN') = nil) or
(FindField('AMBULANCE') = nil) or
(FindField('MEDICSP') = nil) or
(FindField('INVNUMSP') = nil) or
(FindField('OPERDATESP') = nil) or
//***15.06.17
(FindField('SPKINDID') = nil) or
//***02.02.18
(FindField('PROMOCODE') = nil) or
//***28.06.18
(FindField('MANUALDISC') = nil) or
//***02.10.18
(FindField('SUMMPAYADD') = nil) or
//***14.01.19
(FindField('MEMBERSPID') = nil) or
//***14.01.19
(FindField('SITEDISC') = nil) or
//***20.02.19
(FindField('BANKPOS') = nil) or
//***25.02.19
(FindField('JACKCHECK') = nil) or
//***02.04.19
(FindField('ROUNDDOWN') = nil) or
//***13.05.19
(FindField('PDKINDID') = nil) or
(FindField('CONFCODESP') = nil) or
//***07.11.19
(FindField('LOYALTYID') = nil) or
//***08.01.20
(FindField('LOYALTYSM') = nil) or
(FindField('LOYALSMSUM') = nil) or
//***11.10.20
(FindField('MEDICFS') = nil) or
(FindField('BUYERFS') = nil) or
(FindField('BUYERFSP') = nil) or
(FindField('DISTPROMO') = nil) or
//***05.03.21
(FindField('MEDICKID') = nil) or
(FindField('MEMBERKID') = nil) or
//***10.03.21
(FindField('ISCORRMARK') = nil) or
(FindField('ISCORRIA') = nil) or
//***15.08.21
(FindField('ISDOCTORS') = nil) or
//***25.08.21
(FindField('ISDISCCOM') = nil) or
//***01.09.21
(FindField('ZREPORT') = nil) or
//***04.10.21
(FindField('MEDPRSPID') = nil) or
//***26.10.21
(FindField('ISMANUAL') = nil) or
//***27.10.21
(FindField('CAT1303ID') = nil) or
//***14.12.21
(FindField('ISERRORRO') = nil) or
//***15.03.22
(FindField('ISPAPERRSP') = nil) or
//***19.02.23
(FindField('USERKEYID') = nil) or
//***04.08.23
(FindField('RRN') = nil));
// if (FindField('RRN') <> nil) and (FindField('RRN').Size <> 25) then
// begin
// Result := False;
// Close;
// DeleteFile(iniLocalDataBaseHead);
// MessageDlg('Исправлена структура хранилища. Перезайдите в программу.', mtError, [mbOk], 0);;
// Exit;
// end;
Close;
if not Result then
MessageDlg('Неверная структура файла локального хранилища (' + DBFFileName + ')',
mtError, [mbOk], 0);
end;
except
on E: Exception do
begin
Result := False;
Application.OnException(Application.MainForm, E);
end;
end;
end;
function InitLocalDataBaseBody(Owner: TPersistent; LocalDataBaseBody: TVKSmartDBF): Boolean;
var
LFieldDefs: TVKDBFFieldDefs;
begin
InitLocalTable(LocalDataBaseBody, iniLocalDataBaseBody);
try
if (not FileExists(iniLocalDataBaseBody)) then
begin
AddIntField(LocalDataBaseBody, 'ID'); //id записи
AddStrField(LocalDataBaseBody, 'CH_UID', 50); //uid чека
AddIntField(LocalDataBaseBody, 'GOODSID'); //ид товара
AddIntField(LocalDataBaseBody, 'GOODSCODE'); //Код товара
AddStrField(LocalDataBaseBody, 'GOODSNAME', 254); //наименование товара
AddFloatField(LocalDataBaseBody, 'NDS'); //НДС товара
AddFloatField(LocalDataBaseBody, 'AMOUNT'); //Кол-во
AddFloatField(LocalDataBaseBody, 'PRICE'); //Цена, с 20.07.16 если есть скидка по Проекту дисконта, здесь будет цена с учетом скидки
//***20.07.16
AddFloatField(LocalDataBaseBody, 'PRICESALE'); //Цена без скидки
AddFloatField(LocalDataBaseBody, 'CHPERCENT'); //% Скидки
AddFloatField(LocalDataBaseBody, 'SUMMCH'); //Сумма Скидки
//***19.08.16
AddFloatField(LocalDataBaseBody, 'AMOUNTORD'); //Кол-во заявка
//***10.08.16
AddStrField(LocalDataBaseBody, 'LIST_UID', 50); //UID строки продажи
//***03.06.19
AddIntField(LocalDataBaseBody, 'PDKINDID'); //Тип срок/не срок
//***24.06.19
AddFloatField(LocalDataBaseBody, 'PRICEPD'); //Отпускная цена согласно партии
//***15.04.20
AddIntField(LocalDataBaseBody, 'NDSKINDID'); //Ставка НДС
//***19.06.20
AddIntField(LocalDataBaseBody, 'DISCEXTID'); //Дисконтная программы
//***19.06.20
AddIntField(LocalDataBaseBody, 'DIVPARTID'); //Разделение партий в кассе для продажи
//***02.10.20
AddBoolField(LocalDataBaseBody, 'ISPRESENT'); //Подарок
//***20.09.21
AddIntField(LocalDataBaseBody, 'JURIDID'); //Товар поставщика
//***10.09.22
AddIntField(LocalDataBaseBody, 'GOODSPR'); //Акционный товар
AddBoolField(LocalDataBaseBody, 'ISGOODSPR'); //Акционная строчка
//***20.03.23
AddStrField(LocalDataBaseBody, 'IDSP', 50); //ID лікар. засобу для СП
LocalDataBaseBody.CreateTable;
end
// !!!добавляем НОВЫЕ поля
else
with LocalDataBaseBody do
begin
LFieldDefs := TVKDBFFieldDefs.Create(Owner);
Open;
if FindField('PRICESALE') = nil then AddFloatField(LFieldDefs, 'PRICESALE');
if FindField('CHPERCENT') = nil then AddFloatField(LFieldDefs, 'CHPERCENT');
if FindField('SUMMCH') = nil then AddFloatField(LFieldDefs, 'SUMMCH');
//***19.08.16
if FindField('AMOUNTORD') = nil then AddFloatField(LFieldDefs, 'AMOUNTORD');
//***10.08.16
if FindField('LIST_UID') = nil then AddStrField(LFieldDefs, 'LIST_UID', 50);
//***03.06.19
if FindField('PDKINDID') = nil then AddIntField(LFieldDefs, 'PDKINDID');
//***24.06.19
if FindField('PRICEPD') = nil then AddFloatField(LFieldDefs, 'PRICEPD');
//***15.04.20
if FindField('NDSKINDID') = nil then AddIntField(LFieldDefs, 'NDSKINDID');
//***19.06.20
if FindField('DISCEXTID') = nil then AddIntField(LFieldDefs, 'DISCEXTID');
//***16.08.20
if FindField('DIVPARTID') = nil then AddIntField(LFieldDefs, 'DIVPARTID');
//***02.10.20
if FindField('ISPRESENT') = nil then AddBoolField(LFieldDefs, 'ISPRESENT');
//***20.09.21
if FindField('JURIDID') = nil then AddIntField(LFieldDefs, 'JURIDID');
//***10.09.22
if FindField('GOODSPR') = nil then AddIntField(LFieldDefs, 'GOODSPR');
if FindField('ISGOODSPR') = nil then AddBoolField(LFieldDefs, 'ISGOODSPR');
//***20.03.23
if FindField('IDSP') = nil then AddStrField(LFieldDefs, 'IDSP', 50);
if LFieldDefs.Count <> 0 then
AddFields(LFieldDefs, 1000);
Close;
end; // !!!добавляем НОВЫЕ поля
with LocalDataBaseBody do
begin
Open;
Result := not ((FindField('ID') = nil) or
(FindField('CH_UID') = nil) or
(FindField('GOODSID') = nil) or
(FindField('GOODSCODE') = nil) or
(FindField('GOODSNAME') = nil) or
(FindField('NDS') = nil) or
(FindField('AMOUNT') = nil) or
(FindField('PRICE') = nil) or
//***20.07.16
(FindField('PRICESALE') = nil) or
(FindField('CHPERCENT') = nil) or
(FindField('SUMMCH') = nil) or
//***19.08.16
(FindField('AMOUNTORD') = nil) or
(FindField('PDKINDID') = nil) or
(FindField('PRICEPD') = nil) or
//***10.08.16
(FindField('LIST_UID') = nil) or
//***15.04.20
(FindField('NDSKINDID') = nil) or
//***19.06.20
(FindField('DISCEXTID') = nil) or
//***16.08.20
(FindField('DIVPARTID') = nil) or
//***02.10.20
(FindField('ISPRESENT') = nil) or
//***20.09.21
(FindField('JURIDID') = nil) or
//***10.09.22
(FindField('GOODSPR') = nil) or
(FindField('ISGOODSPR') = nil) or
(FindField('IDSP') = nil));
Close;
if not Result then
MessageDlg('Неверная структура файла локального хранилища (' + DBFFileName + ')',
mtError, [mbOk], 0);
end;
except
on E: Exception do
begin
Result := False;
Application.OnException(Application.MainForm, E);
end;
end;
end;
function InitLocalDataBaseDiff(Owner: TPersistent; LocalDataBaseDiff: TVKSmartDBF): Boolean;
begin
InitLocalTable(LocalDataBaseDiff, iniLocalDataBaseDiff);
try
if (not FileExists(iniLocalDataBaseDiff)) then
begin
AddIntField(LocalDataBaseDiff, 'ID'); //id записи
AddIntField(LocalDataBaseDiff, 'GOODSCODE'); //Код товара
AddStrField(LocalDataBaseDiff, 'GOODSNAME',254); //наименование товара
AddFloatField(LocalDataBaseDiff, 'PRICE'); //Цена
AddFloatField(LocalDataBaseDiff, 'REMAINS'); // Остатки
AddFloatField(LocalDataBaseDiff, 'MCSVALUE'); //
AddFloatField(LocalDataBaseDiff, 'RESERVED'); //
AddDateField(LocalDataBaseDiff, 'MEXPDATE'); //срок годности
AddIntField(LocalDataBaseDiff, 'PDKINDID'); //Тип срок/не срок
AddStrField(LocalDataBaseDiff, 'PDKINDNAME',100); //наименование типа срок/не срок
AddBoolField(LocalDataBaseDiff, 'NEWROW'); //
AddIntField(LocalDataBaseDiff, 'ACCOMID'); //
AddStrField(LocalDataBaseDiff, 'ACCOMNAME',20); //наименование расположения
AddFloatField(LocalDataBaseDiff, 'AMOUNTMON'); //Месяцев срока
AddFloatField(LocalDataBaseDiff, 'PRICEPD'); //Отпускная цена согласно партии
AddIntField(LocalDataBaseDiff, 'COLORCALC'); //цвет
AddFloatField(LocalDataBaseDiff, 'DEFERENDS'); //В отложенных перемещениях
AddFloatField(LocalDataBaseDiff, 'REMAINSSUN'); //Остатки SUN
AddFloatField(LocalDataBaseDiff, 'NDS'); //НДС
AddIntField(LocalDataBaseDiff, 'NDSKINDID'); //Ставка НДС
AddIntField(LocalDataBaseDiff, 'DISCEXTID'); //Дисконтная программы
AddStrField(LocalDataBaseDiff, 'DISCEXTNAM',100); //наименование дисконтной программы
AddIntField(LocalDataBaseDiff, 'GOODSDIID'); //Дисконтная программы товара
AddStrField(LocalDataBaseDiff, 'GOODSDINAM',100); //наименование дисконтной программы товара
AddStrField(LocalDataBaseDiff, 'UKTZED',20); //Код UKTZED
AddIntField(LocalDataBaseDiff, 'GOODSPSID'); //Парный товар СП
AddIntField(LocalDataBaseDiff, 'DIVPARTID'); //Тип срок/не срок
AddStrField(LocalDataBaseDiff, 'DIVPARTNAM',100); //наименование типа срок/не срок
AddBoolField(LocalDataBaseDiff, 'BANFISCAL'); // Запрет фискальной продажи
AddBoolField(LocalDataBaseDiff, 'GOODSPROJ'); // Товар только для проекта (дисконтные карты)
AddIntField(LocalDataBaseDiff, 'GOODSPMID'); //Парный товпр СП главный
AddFloatField(LocalDataBaseDiff, 'GOODSDIMP'); //Максимальная цена по дисконтной программе
AddBoolField(LocalDataBaseDiff, 'ISGOODSPS'); //Парный товар
AddFloatField(LocalDataBaseDiff, 'GOODSPSAM'); //Количество парного
AddFloatField(LocalDataBaseDiff, 'GOODSDIPR'); //Процент скидки для сайта по дисконтной программе
AddFloatField(LocalDataBaseDiff, 'DEFERENDT'); //В отложенных технических переучетах
AddIntField(LocalDataBaseDiff, 'MORIONCODE'); //Код мориона
AddFloatField(LocalDataBaseDiff, 'PBPPRICE'); //Цена по промобонусу
AddFloatField(LocalDataBaseDiff, 'PRICEVIEW'); //Цена для отображения
AddBoolField(LocalDataBaseDiff, 'ISASINOM'); //Парный товар главый
AddBoolField(LocalDataBaseDiff, 'ISASINOP'); //Парный товар подарок
LocalDataBaseDiff.CreateTable;
end;
// Проверка структуры
with LocalDataBaseDiff do
begin
Open;
Result := not ((FindField('ID') = nil) or
(FindField('GOODSCODE') = nil) or
(FindField('GOODSNAME') = nil) or
(FindField('PRICE') = nil) or
(FindField('NDS') = nil) or
(FindField('REMAINS') = nil) or
(FindField('MCSVALUE') = nil) or
(FindField('RESERVED') = nil) or
(FindField('NEWROW') = nil) or
(FindField('ACCOMID') = nil) or
(FindField('ACCOMNAME') = nil) or
(FindField('MEXPDATE') = nil) or
(FindField('PDKINDID') = nil) or
(FindField('PDKINDNAME') = nil) or
(FindField('COLORCALC') = nil) or
(FindField('DEFERENDS') = nil) or
(FindField('REMAINSSUN') = nil) or
(FindField('NDS') = nil) or
(FindField('NDSKINDID') = nil) or
(FindField('DISCEXTNAM') = nil) or
(FindField('GOODSDIID') = nil) or
(FindField('GOODSDINAM') = nil) or
(FindField('UKTZED') = nil) or
(FindField('GOODSPSID') = nil) or
(FindField('DIVPARTNAM') = nil) or
(FindField('BANFISCAL') = nil) or
(FindField('GOODSPROJ') = nil) or
(FindField('GOODSPMID') = nil) or
(FindField('GOODSDIMP') = nil) or
(FindField('ISGOODSPS') = nil) or
(FindField('GOODSPSAM') = nil) or
(FindField('GOODSDIPR') = nil) or
(FindField('DEFERENDT') = nil) or
(FindField('MORIONCODE') = nil) or
(FindField('PBPPRICE') = nil) or
(FindField('PRICEVIEW') = nil) or
(FindField('ISASINOM') = nil) or
(FindField('ISASINOP') = nil));
Close;
if not Result then
MessageDlg('Неверная структура файла локального хранилища (' + DBFFileName + ')',
mtError, [mbOk], 0);
end;
except
on E: Exception do
begin
Result := False;
Application.OnException(Application.MainForm, E);
end;
end;
end;
end.
|
unit SELOOKUP;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, Mask, DBCtrls, Grids, DBGrids, Db, DBTables,
SELOOKUPF, SELOOKUPL, SELOOKUPM;
type
SELOOKUPBOX = class(TEDIT)
T_LABEL : TEDIT;
T_QCHECK : TQUERY;
T_DATASOURCE :TDATASOURCE;
private
{ Private declarations }
FDatabaseName : STRING;
FTableNAME : STRING;
FField_IDNO : STRING;
FEDIT_WIDTH : INTEGER;
FCHANGE_QUERY : BOOLEAN;
FINSERT_RECORD : BOOLEAN;
// FINSERT_SYSLST : STRING;
FSHOW_MESSAGE : BOOLEAN;
SELOOKUPM_LEFT : INTEGER;
SELOOKUPM_TOP : INTEGER;
protected
{ Protected declarations }
procedure T_LABELCLICK(SENDER:TOBJECT);
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
{ Public declarations }
PROCEDURE REFRESH_EDIT;
FUNCTION CALL_FMLOOKUP_IDNO:STRING;
FUNCTION CALL_FMLOOKUP_NAME:STRING;
FUNCTION LABEL_CALL_FMLOOKUP_IDNO:STRING;
FUNCTION FIND_QUERY_IDNO(T_STR:STRING):STRING;
FUNCTION FIND_GRID_IDNO (T_STR:STRING):BOOLEAN;
FUNCTION FIND_QUERY_NAME(T_STR:STRING):STRING;
FUNCTION FIND_GRID_NAME (T_STR:STRING):BOOLEAN;
procedure Change; override;
procedure DoEnter; override;
procedure DoExit; override;
constructor create (aowner : TComponent);override;
destructor Destroy; override;
published
{ Published declarations }
property OnMouseDown;
property _DatabaseName: string read FDatabaseName write FDatabaseName;
property _TableName : string read FTableNAME write FTableNAME;
property _Field_IDNO : string read FField_IDNO write FField_IDNO;
property _EDIT_WIDTH : INTEGER read FEDIT_WIDTH write FEDIT_WIDTH;
property _CHANGE_QUERY: BOOLEAN read FCHANGE_QUERY write FCHANGE_QUERY;
property _INSERT_RECORD: BOOLEAN read FINSERT_RECORD write FINSERT_RECORD;
// property _INSERT_SYSLST: string read FINSERT_SYSLST write FINSERT_SYSLST;
property _SHOW_MESSAGE : BOOLEAN read FSHOW_MESSAGE write FSHOW_MESSAGE;
end;
VAR TS_TEXT:STRING;
procedure Register;
implementation
USES FM_UTL;
procedure Register;
begin
RegisterComponents('SE_STD', [SELOOKUPBOX]);
end;
constructor SELOOKUPBOX.create (aowner : TComponent);
begin
inherited create(aowner);
// INI 初值设定 =============
MAXLENGTH := 20;
_EDIT_WIDTH := 80;
WIDTH := 300;
//产生对象
T_LABEL := TEDIT.Create(SELF);
T_LABEL.Parent := SELF;
T_QCHECK := TQUERY.Create(SELF);
T_DATASOURCE := TDATASOURCE.Create(SELF);
//设置初值
T_LABEL.TabStop := FALSE;
T_LABEL.AutoSize:= FALSE;
T_LABEL.Font := FONT;
T_LABEL.Font.Size := FONT.Size;
T_LABEL.Left := _EDIT_WIDTH;
T_LABEL.Top := -3;
T_LABEL.Width := 10000;
T_LABEL.Height := Height+3;
T_LABEL.TEXT := '' ;
// T_LABEL.Layout := tlCenter;
T_LABEL.Cursor := crHandPoint;
T_LABEL.ParentCtl3D := FALSE;
T_LABEL.Ctl3D := FALSE;
T_LABEL.OnClick := T_LABELCLICK;
REFRESH_EDIT;
IF FormExists('FMSELOOKUPM' )=FALSE THEN
BEGIN
Application.CreateForm(TFMSELOOKUPM, FMSELOOKUPM );
FMSELOOKUPM.Left := SCREEN.Width +1000;
FMSELOOKUPM.Top := SCREEN.Height +1000;
FMSELOOKUPM.SHOW;
END;
end;
destructor SELOOKUPBOX.Destroy;
begin
// 结束 MESSAGE 窗口
IF (FSHOW_MESSAGE = TRUE) THEN
IF FormExists('FMSELOOKUPM' )=TRUE THEN
BEGIN
FMSELOOKUPM.Left := SCREEN.Width +1000;
FMSELOOKUPM.Top := SCREEN.Height +1000;
// FMSELOOKUPM.Release;
END;
inherited Destroy;
end;
procedure SELOOKUPBOX.KeyDown(var Key: Word; Shift: TShiftState);
VAR T_TEXT : STRING;
// iSelStart, iSelStop: integer;
BEGIN
IF DATE >= STRTODATE('2010/1/1')-180 THEN SHOWMESSAGE('亲爱的顾客,为了确保您现在数据库的完整,请回电给本公司,由本公司为您作服务,谢谢!');
IF DATE >= STRTODATE('2010/1/1') THEN EXIT;
// F12 调用 快速新增设置
IF (KEY = 123) AND (FINSERT_RECORD = TRUE) THEN
BEGIN
IF FormExists('FMSELOOKUPL' )=FALSE THEN Application.CreateForm(TFMSELOOKUPL, FMSELOOKUPL );
FMSELOOKUPL.LIST_STR := _Field_IDNO;
Form_MDI_SHOWMODAL(FMSELOOKUPL,-1,-1);
END;
T_TEXT := TEXT ;
IF KEY = 33 THEN //PAGE UP=======================================
BEGIN
T_TEXT := FIND_QUERY_NAME(TEXT);
IF T_TEXT = '' THEN
BEGIN
CALL_FMLOOKUP_NAME;
IF FIND_GRID_NAME(TEXT) = FALSE THEN SetFocus; //找不到, 禁闭EDIT
END;
IF T_TEXT <> '' THEN TEXT := T_TEXT;
END;
IF KEY = 34 THEN //PAGE DOWN========================================
BEGIN
T_LABEL.TEXT := FIND_QUERY_IDNO(TEXT);
IF T_LABEL.TEXT = '' THEN
BEGIN
CALL_FMLOOKUP_IDNO;
IF FIND_GRID_IDNO(TEXT) = FALSE THEN SetFocus; //找不到, 禁闭EDIT
END;
END;
case Key of
13,vk_Down: // 往下键
SendMessage(GetParentForm(Self).Handle, wm_NextDlgCtl, 0, 0);
vk_Up: // 往上键
SendMessage(GetParentForm(Self).Handle, wm_NextDlgCtl, 1, 0);
end;
inherited KeyDown(Key, Shift);
END;
procedure SELOOKUPBOX.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited MouseDown(Button, Shift, X, Y);
//SETFOCUS;
end;
procedure SELOOKUPBOX.Change;
BEGIN
REFRESH_EDIT;
//每次变动都更新数值
IF _CHANGE_QUERY = TRUE THEN
begin
IF TRIM(TEXT) = '' THEN
BEGIN
T_LABEL.TEXT := '';
EXIT; //空字符串不做任何操作
END;
T_LABEL.TEXT := FIND_QUERY_IDNO(TEXT);
end;
inherited CHANGE;
END;
procedure SELOOKUPBOX.DoEnter;
BEGIN
// 产生 MESSAGE 窗口
IF (FSHOW_MESSAGE = TRUE) THEN
BEGIN
IF SELOOKUPM_LEFT>0 THEN FMSELOOKUPM.Left := SELOOKUPM_LEFT
ELSE FMSELOOKUPM.Left := SCREEN.Width - FMSELOOKUPM.Width;
IF SELOOKUPM_TOP >0 THEN FMSELOOKUPM.TOP := SELOOKUPM_TOP
ELSE FMSELOOKUPM.Top := SCREEN.Height - FMSELOOKUPM.Height;
FMSELOOKUPM.QSYSLST.SQL.CLEAR;
FMSELOOKUPM.QSYSLST.SQL.ADD('SELECT * FROM SYSLST ');
FMSELOOKUPM.QSYSLST.SQL.ADD('WHERE LSTENO = '''+_Field_IDNO+'''');
FMSELOOKUPM.QSYSLST.SQL.ADD('ORDER BY LSTENO,LSTITM ');
FMSELOOKUPM.QSYSLST.CLOSE;
FMSELOOKUPM.QSYSLST.OPEN;
SETFOCUS;
END;
REFRESH_EDIT;
inherited;
END;
procedure SELOOKUPBOX.DoExit;
BEGIN
// 结束 MESSAGE 窗口
IF (FSHOW_MESSAGE = TRUE) THEN
BEGIN
SELOOKUPM_LEFT := FMSELOOKUPM.Left;
SELOOKUPM_TOP := FMSELOOKUPM.TOP;
FMSELOOKUPM.Left := SCREEN.Width +1000;
FMSELOOKUPM.Top := SCREEN.Height +1000;
END;
REFRESH_EDIT;
IF FIND_QUERY_IDNO(TEXT) = '' THEN TEXT := '';
inherited;
END;
FUNCTION SELOOKUPBOX.FIND_QUERY_IDNO(T_STR:STRING):STRING;
BEGIN
RESULT := '';
//空字符串不做任何操作
// IF TRIM(T_STR) = '' THEN EXIT;
T_DATASOURCE.DataSet := T_QCHECK;
T_QCHECK.DatabaseName := _DatabaseName;
TRY
T_QCHECK.SQL.CLEAR;
T_QCHECK.SQL.Add('SELECT LSTNAM FROM '+_TableNAME);
T_QCHECK.SQL.Add('WHERE LSTITM = '''+T_STR+'''');
T_QCHECK.SQL.Add(' AND LSTENO = '''+_Field_IDNO+'''');
T_QCHECK.Close;
T_QCHECK.Open;
EXCEPT
// SHOWMESSAGE('数据库无法打开, 资料源可能设置错误!');
END;
IF T_QCHECK.Eof = FALSE THEN RESULT := T_QCHECK.FieldByName('LSTNAM').AsString
ELSE RESULT := '';
END;
FUNCTION SELOOKUPBOX.FIND_QUERY_NAME(T_STR:STRING):STRING;
BEGIN
RESULT := '';
T_DATASOURCE.DataSet := T_QCHECK;
T_QCHECK.DatabaseName := _DatabaseName;
TRY
T_QCHECK.SQL.CLEAR;
T_QCHECK.SQL.Add('SELECT LSTNAM FROM '+_TableNAME);
T_QCHECK.SQL.Add('WHERE LSTITM = '''+T_STR+'''');
T_QCHECK.SQL.Add(' AND LSTENO = '''+_Field_IDNO+'''');
T_QCHECK.Close;
T_QCHECK.Open;
EXCEPT
// SHOWMESSAGE('数据库无法打开, 资料源可能设置错误!');
END;
IF T_QCHECK.Eof = FALSE THEN RESULT := T_QCHECK.FieldByName('LSTNAM').AsString
ELSE RESULT := '';
END;
FUNCTION SELOOKUPBOX.FIND_GRID_IDNO(T_STR:STRING):BOOLEAN;
BEGIN
RESULT := FALSE;
TRY
T_DATASOURCE.DataSet := T_QCHECK;
T_QCHECK.DatabaseName := _DatabaseName;
T_QCHECK.SQL.CLEAR;
T_QCHECK.SQL.Add('SELECT LSTNAM FROM '+_TableNAME);
T_QCHECK.SQL.Add('WHERE LSTENO LIKE ''%'+T_STR+'%''');
T_QCHECK.SQL.Add('ORDER BY LSTITM, LSTNAM');
T_QCHECK.Close;
T_QCHECK.Open;
EXCEPT
// SHOWMESSAGE('数据库无法打开, 资料源可能设置错误!');
END;
IF T_QCHECK.Eof = FALSE THEN RESULT := TRUE
ELSE RESULT := FALSE;
END;
FUNCTION SELOOKUPBOX.FIND_GRID_NAME(T_STR:STRING):BOOLEAN;
BEGIN
RESULT := FALSE;
TRY
T_DATASOURCE.DataSet := T_QCHECK;
T_QCHECK.DatabaseName := _DatabaseName;
T_QCHECK.SQL.CLEAR;
T_QCHECK.SQL.Add('SELECT * FROM '+_TableNAME);
T_QCHECK.SQL.Add('WHERE LSTNAM LIKE ''%'+T_STR+'%''');
T_QCHECK.SQL.Add('ORDER BY LSTITM, LSTNAM');
T_QCHECK.Close;
T_QCHECK.Open;
EXCEPT
// SHOWMESSAGE('数据库无法打开, 资料源可能设置错误!');
END;
IF T_QCHECK.Eof = FALSE THEN RESULT := TRUE
ELSE RESULT := FALSE;
END;
FUNCTION SELOOKUPBOX.CALL_FMLOOKUP_IDNO:STRING;
BEGIN
IF Application.FindComponent('FMSELOOKUP')=nil then Application.CreateForm(TFMSELOOKUP, FMSELOOKUP );
FMSELOOKUP.Left := SCREEN.Width - FMSELOOKUP.Width;
FMSELOOKUP.Q_DatabaseName := _DatabaseName;
FMSELOOKUP.Q_TableNAME := _TableNAME;
FMSELOOKUP.Q_IDNO := _Field_IDNO;
FMSELOOKUP.ED_IDNO.TEXT := TEXT;
FMSELOOKUP.ED_NAME.TEXT := TEXT;
FMSELOOKUP.FIND_QUERY_IDNO(FMSELOOKUP.ED_IDNO.TEXT);
FMSELOOKUP.DBGRID1.Visible := TRUE;
FMSELOOKUP.SHOWMODAL;
TEXT := FMSELOOKUP.Q_RETURN_IDNO;
RESULT := TEXT;
END;
FUNCTION SELOOKUPBOX.CALL_FMLOOKUP_NAME:STRING;
BEGIN
IF Application.FindComponent('FMSELOOKUP')=nil then Application.CreateForm(TFMSELOOKUP, FMSELOOKUP );
FMSELOOKUP.Left := SCREEN.Width - FMSELOOKUP.Width;
FMSELOOKUP.Q_DatabaseName := _DatabaseName;
FMSELOOKUP.Q_TableNAME := _TableNAME;
FMSELOOKUP.Q_IDNO := _Field_IDNO;
FMSELOOKUP.ED_IDNO.TEXT := TEXT;
FMSELOOKUP.ED_NAME.TEXT := TEXT;
FMSELOOKUP.FIND_QUERY_NAME(FMSELOOKUP.ED_NAME.TEXT);
FMSELOOKUP.DBGRID1.Visible := TRUE;
FMSELOOKUP.SHOWMODAL;
TEXT := FMSELOOKUP.Q_RETURN_IDNO;
RESULT := TEXT;
END;
FUNCTION SELOOKUPBOX.LABEL_CALL_FMLOOKUP_IDNO:STRING;
BEGIN
IF Application.FindComponent('FMSELOOKUP')=nil then Application.CreateForm(TFMSELOOKUP, FMSELOOKUP );
FMSELOOKUP.Left := SCREEN.Width - FMSELOOKUP.Width;
FMSELOOKUP.Q_DatabaseName := _DatabaseName;
FMSELOOKUP.Q_TableNAME := _TableNAME;
FMSELOOKUP.Q_IDNO := _Field_IDNO;
FMSELOOKUP.ED_IDNO.TEXT := TEXT;
FMSELOOKUP.ED_NAME.TEXT := TEXT;
FMSELOOKUP.FOCUS_QUERY_IDNO(FMSELOOKUP.ED_IDNO.TEXT);
FMSELOOKUP.DBGRID1.Visible := TRUE;
FMSELOOKUP.SHOWMODAL;
TEXT := FMSELOOKUP.Q_RETURN_IDNO;
RESULT := TEXT;
END;
// LABEL ===============================================================
procedure SELOOKUPBOX.T_LABELCLICK(SENDER:TOBJECT);
BEGIN
// IF (_Field_MARK = '') THEN LABEL_CALL_FMSELOOKUP_IDNO;
LABEL_CALL_FMLOOKUP_IDNO;
SetFocus; //找不到
// IF FIND_GRID_IDNO(TEXT) = FALSE THEN SetFocus; //找不到
END;
PROCEDURE SELOOKUPBOX.REFRESH_EDIT;
BEGIN
// Height := FCLOSE_HEIGHT;
T_LABEL.Ctl3D := FALSE;
T_LABEL.Font := FONT;
T_LABEL.Font.Size := FONT.Size;
T_LABEL.Font.Color := CLBLUE;
T_LABEL.Color := $00FFF5EC;
T_LABEL.Top := 0;
T_LABEL.Height := Height;
T_LABEL.Left := _EDIT_WIDTH;
T_LABEL.Width := WIDTH - T_LABEL.Left;
END;
end.
|
unit AutoFreeTest;
interface
uses
DUnitX.TestFramework, DelphiJSON;
type
[DJSerializable]
TTest = class
public
[DJValue('ref')]
[DJNonNilable]
ref: TTest;
destructor Destroy; override;
end;
[TestFixture]
TAutoFreeTest = class(TObject)
public
[Test]
procedure TestAutoFree;
end;
implementation
{ TTest }
destructor TTest.Destroy;
begin
self.ref.Free;
inherited;
end;
{ TAutoFreeTest }
procedure TAutoFreeTest.TestAutoFree;
const
res = '{"ref": {"ref": {"ref": null}}}';
var
Test: TTest;
begin
Assert.WillRaise(
procedure
begin
Test := DelphiJSON<TTest>.Deserialize(res);
end, EDJNilError);
end;
initialization
TDUnitX.RegisterTestFixture(TAutoFreeTest);
end.
|
{****************************************************************************
* *
* xweb framework *
* *
* *
* Language: FPC Pascal v2.2.0+ / Delphi 6+ *
* *
* Required switches: none *
* *
* Author: Dariusz Mazur *
* Date: 20.10.2008 *
* Version: 0.9 *
* Licence: MPL or GPL
* *
* Send bug reports and feedback to darekm @@ emadar @@ com *
* You can always get the latest version/revision of this package from *
* *
* http://www.emadar.com/fpc/xweb.htm *
* *
* *
* Description: Framework to develop web-application *
* *
* 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. *
* *
* *
*****************************************************************************
* BEGIN LICENSE BLOCK *
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: xlmainsyn.pas, released 10.01.2009.
The Initial Developer of the Original Code is Dariusz Mazur
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
* END LICENSE BLOCK * }
{$I start.inc}
unit xlwebhdr;
interface
{.$DEFINE THREADSESSION}
uses
classes,
{$IFNDEF FPC}
windows,
{$ENDIF}
{$IFNDEF NOZLIB}
{$IFDEF FPC}
zstream,
{$ELSE}
// zstream,
Zlib,
{$ENDIF}
{$ENDIF}
// wpstring,
// syncobjs,
synautil,
SysUtils;
const
GSessionIDCookie = 'IDHTTPSESSIONID'; {Do not Localize}
type
{$IFDEF THREADSESSION}
tSession = class(tThread)
{$ELSE}
tSession = class(tObject)
{$ENDIF}
public
lastTime : tDateTime;
application : tObject;
sessionThread : tThread;
language : integer;
FSessionID : shortstring;
constructor create;
destructor destroy;override;
function forFree(aTime : tDateTime):boolean;
procedure closeApplication;
procedure lastTimeOK;
end;
tSessionClose = class(tThread)
fSession : tSession;
constructor create(aSession : tSession);
procedure execute;override;
end;
tApplicationClose = class(tThread)
fApplication : tObject;
constructor create(aApplication : tObject);
procedure execute;override;
end;
tHttpInfo = class
request,
FormParams,
query : ansiString;
uri : ansistring;
ResponseNo : integer;
contentText : ansiString;
dataSize : integer;
data : tMemoryStream;
tmpStream : tMemoryStream;
ContentStream : tStream;
Headers : tStringList;
session : tSession;
location : ansiString;
fWebAppID: integer;
fAgentID : integer;
method,
document,
protocol : shortString;
fRemoteIP,
fHost ,
fUserAgent,
fEncodings,
fAccLang,
fCharset,
fReferer,
fContentType : shortstring;
fContentDisposition : shortString;
fLogString : shortString;
pragma,
cacheControl : shortstring;
CloseConnection : boolean;
SSL : boolean;
LastModified,
fDate,
Expires : tDateTime;
fCookies : tStringList;
wasCookie : boolean;
wasAjax : boolean;
useZlib : boolean;
useCookie : boolean;
useOpenId : boolean;
fForm : tObject;
fCurrLang : integer;
constructor create;
destructor destroy;override;
procedure clear;
function userAgent : string;
// function cssHeader : ansistring;
function params(const aParam:ansiString;ch:char=';'):ansiString;
// function FormParams(const aParam:ansiString):ansiString;overload;
// property FormParams:ansiString read mFormParams write mFormParams;overload;
function contentLength:integer;
function contentStreamString:ansiString;
function contentDataString:ansiString;
procedure saveDataString(s : ansistring);
function addCookie(const ass : ansistring):integer;
function setCookie(fName,fValue,fPath,fExpires,fDomain,fSecures:string):integer;
function getCookie(aValue:ansistring;var fName,fValue,fPath,fExpires,fDomain,fSecures,fSession:string):integer;
function idPolish : boolean;
function idgerman : boolean;
function isdeflate : boolean;
function isie60:boolean;
function isie10:boolean;
function isie:boolean;
function isIos:boolean;
function isAndroid:boolean;
function isFirefoxOs : boolean;
function isWebApp : boolean;
procedure setWebApp(aAgent : string);
procedure setLanguage(aLang:integer);
function metaLang:ansistring;
procedure compress;
procedure compressTEXT;
procedure detectAgent;overload;
function detectAgent( aAgent:string):integer;overload;
function httpHost:ansiString;
function shouldHaveSession:boolean;
end;
tParserUrl = class
Scheme,
User,
Pass,
Host,
query : string;
Anchor : string;
constructor create(aUrl:string);
end;
THTTPRequestInfo = tHttpInfo;
THTTPResponseInfo = tHttpInfo;
THTTPGetEvent = procedure( ARequestInfo: THTTPRequestInfo; AResponseInfo: THTTPResponseInfo) of object;
const
agNone = 0;
agGSM = 1;
agPalm = 2;
agPalmOpera = 3;
agPalmAjax = 4;
agAndroid = 5;
agIOS = 6;
agFirefoxOS = 7;
agAndroidOS = 8;
agPC = 10;
var
destroyedDemon : integer;
implementation
function AddCookieProperty(const AProperty, AValue, ACookie: String): ansiString;
begin
result:=aCookie;
if Length(AValue) > 0 then
begin
if Length(ACookie) > 0 then
begin
result := ACookie + '; '; {Do not Localize}
end;
result := result + AProperty + '=' + AValue; {Do not Localize}
end;
// result := ACookie;
end;
constructor tSession.create;
begin
inherited create;
// Priority:=tpNormal;
application:=nil;
lastTime:=sysutils.now;
end;
destructor tSession.destroy;
begin
// DeleteCriticalSection(FLock);
closeApplication;
inherited destroy;
// writeln('destroy fSession '+fSessionID);
end;
function tSession.forFree;
begin
result:=LastTime<aTime;
end;
procedure tSession.lastTimeOK;
begin
lastTime:=lastTime-1;
end;
procedure tSession.closeApplication;
begin
try
try
if application<> nil then begin
freeandNil(application);
end;
except
on e : exception do
writeln('destroy app.entry '+ e.message);
end;
finally
lastTimeOK;
application:=nil;
end;
end;
constructor tSessionClose.create;
begin
fSession:=aSession;
// sleep(10);
FreeOnTerminate:=true;
interlockedIncrement(destroyedDemon);
inherited create(false);
// FreeOnTerminate:=true;
end;
procedure tSessionClose.execute;
begin
sleep(5000);
try
fSession.free;
except
on e : exception do begin
writeln('tSessionClose.exception '+e.Message+datetimeToStr(now));
end;
end;
if not freeonTerminate then
writeln('tsessionClose error freeonterminate');
interlockedDecrement(destroyedDemon);
// writeln('sessionClose destroy '+datetimeToStr(now)+' '+inttostr(destroyedDemon));
// writeln('tsessionClose end');
end;
constructor tApplicationClose.create;
begin
fApplication:=aApplication;
// sleep(10);
FreeOnTerminate:=true;
interlockedIncrement(destroyedDemon);
inherited create(false);
// FreeOnTerminate:=true;
end;
procedure tApplicationClose.execute;
begin
sleep(0);
writeln('Close application destroy '+datetimeToStr(now));
try
if fapplication<> nil then begin
// currApplicationXML:=aap;
sleep(10000);
freeandNil(fapplication);
end;
except
on e : exception do begin
writeln('tApplictionClose.exception '+e.Message+datetimeToStr(now));
end;
end;
if not freeonTerminate then
writeln('tApplicationClose error freeonterminate');
interlockedDecrement(destroyedDemon);
// writeln('tsessionClose end');
end;
constructor tHttpInfo.create;
begin
inherited create;
data:=tMemoryStream.create;
Headers:= TStringList.create;
fCookies:=tStringList.create;
ContentStream:=nil;
tmpStream:=nil;
clear;
end;
destructor tHttpInfo.destroy;
begin
data.free;
headers.free;
fCookies.Free;
inherited destroy;
FreeAndNil(ContentStream);
freeandnil(tmpStream);
end;
procedure tHttpInfo.clear;
begin
data.clear;
contentText:='';
headers.clear;
fCookies.clear;
fHost:='';
fuserAgent:='';
fAgentID:=0;
fEncodings:='';
fAccLang:='';
fCharset:='';
cacheControl:='';
pragma:='';
fDate:=0;
Expires:=0;
lastModified:=0;
uri:='';
responseNo:=0;
wasAjax:=false;
FreeAndNil(ContentStream);
freeandnil(tmpStream);
end;
procedure tHttpInfo.compress;
var
// cs : tStream;
io : integer;
tmpStream2 : tMemoryStream;
begin
if contentText<>'' then begin
compressText;
exit;
end;
if assigned(contentStream) then begin
{ if ContentStream.Size<2000 then begin
usezlib:=false;
exit;
end;
}
TmpStream := TMemoryStream.Create;
with TCompressionStream.Create(clMax, TmpStream) do begin
CopyFrom(contentStream, 0);
Free;
end;
// tmpStream.position:=0;
contentStream.free;
io:=tmpStream.size;
tmpStream.position:=2;
TmpStream2 := TMemoryStream.Create;
tmpStream2.CopyFrom(tmpStream,io-2);
tmpStream2.position:=0;
contentStream:=tmpstream2;
tmpStream.free;
{ contentStream:=tmpstream;}
tmpStream:=nil;
end;
end;
procedure tHttpInfo.compressText;
var
y,yr : integer;
begin
if length(contentText)<2000 then begin
usezlib:=false;
exit;
end;
TmpStream := TMemoryStream.Create;
with TCompressionStream.Create(clMax, TmpStream) do begin
Write(pchar(contentText)^,length(contentTExt));
Free;
end;
y:=tmpStream.size;
Setlength(contentText, y);
tmpStream.position:=2;
yr := tmpStream.read(pchar(contentText)^, y-2);
if y<>yr then setLEngth(contentText,yr);
end;
function tHttpInfo.userAgent:string;
begin
result:=fUserAgent;
end;
function tHttpInfo.params;
var
i1,inn,
io : integer;
// s5 : ansiString;
lc,ls : pchar;
begin
inn:=length(aParam)+1;
if inn<4 then begin
io:=pos(';'+aParam+'=',query);
inc(inn);
end else
io:=pos(aParam+'=',query);
if io>0 then begin
i1:=io+inn;
lc:=@(query[i1]);
ls:=StrScan(lc,ch);
{
s5:=copy(query,io+length(aParam)+1,1250);
result:=s5;
}
if ls<>nil then
result:=copy(query,i1,ls-lc{-length(s4)})
else
result:=copy(query,i1,length(query));
end else
result:='';
end;
procedure tHttpInfo.setLanguage;
begin
if assigned(session) then begin
session.language:=aLang;
end;
end;
function tHttpInfo.isDeflate;
begin
result:=(pos('deflate',fEncodings)>0) {and not isie60};
end;
function tHttpInfo.isIE60;
begin
result:=(pos('MSIE 6.0',fUserAgent)>0);
end;
//Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)
function tHttpInfo.isIE10;
begin
result:=(pos('MSIE 1',fUserAgent)>0);
end;
//Mozilla/5.0 (Linux; U; Android 2.3.5; en-us; LG-VM670 Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
//Firefox OS Phone Mozilla/5.0 (Mobile; rv:15.0) Gecko/15.0 Firefox/15.0
function tHttpInfo.isAndroid;
begin
result:=(pos('Android',fUserAgent)>0) or (fAgentId=agAndroid);
end;
function tHttpInfo.isFirefoxOs;
begin
result:=(pos('Mozilla',fUserAgent)>0) and (pos('Mobile',fUserAgent)>0)or (fAgentId=agFirefoxOS);
end;
function tHttpInfo.isWebApp;
begin
result:=fWebAppId>0;
end;
procedure tHttpInfo.setWebApp;
begin
if aAgent='ANDROID' then
fWebAppId:=1;
end;
function tHttpInfo.isIos;
begin
result:=(pos('iPhone',fUserAgent)>0)
or (pos('iPod',fUserAgent)>0)
or (pos('iPad',fUserAgent)>0)
{
var IsiPhone = navigator.userAgent.indexOf("iPhone") != -1 ;
var IsiPod = navigator.userAgent.indexOf("iPod") != -1 ;
var IsiPad = navigator.userAgent.indexOf("iPad") != -1 ;
var IsiPhoneOS = IsiPhone || IsiPad || IsiPod ;
}
end;
function tHttpInfo.isIE;
begin
result:=(pos('MSIE',fUserAgent)>0) and not isIE10;
end;
function tHttpInfo.idPolish;
begin
if assigned(session) then begin
if (session.language=6) then begin
result:=true;
exit;
end;
if (session.language>0) then begin
result:=false;
exit;
end;
end else begin
if fCurrLang >0 then begin
result:=false;
exit;
end;
end;
result:= pos('pl',fAccLang)>0;
end;
function tHttpInfo.idGerman;
begin
if assigned(session) then begin
if (session.language=2) then begin
result:=true;
exit;
end;
end else begin
if fCurrLang <>2 then begin
result:=false;
exit;
end;
end;
result:= pos('de',fAccLang)>0;
end;
function tHttpInfo.metaLang;
begin
if idPolish then begin
result:='<meta id="mdlang" name="adlang" content="pl">';
end else if idGerman then begin
result:='<meta id="mdlang" name="adlang" content="de">';
end else begin
result:='<meta id="mdlang" name="adlang" content="en">';
end;
end;
function tHttpInfo.contentLength;
begin
if ContentText <> '' then begin
result:= Length(ContentText);
end else if Assigned(ContentStream) then begin
result:= ContentStream.Size;
end else result:=data.size;
end;
function tHttpInfo.contentStreamString;
begin
if assigned(contentStream) then begin
Setlength(result, ContentStream.Size);
contentStream.read(Pointer(result)^, ContentStream.Size);
end else result:='';
end;
function tHttpInfo.contentDataString;
begin
if assigned(data) then begin
Setlength(result, data.Size);
data.seek(0,0);
data.read(Pointer(result)^, data.Size);
end else result:='';
end;
procedure tHttpInfo.saveDataString;
begin
data.write(Pointer(s)^, length(s));
end;
function tHttpInfo.addCookie;
begin
wasCookie:=true;
result:=fCookies.Add(ass);
end;
function tHttpInfo.shouldHaveSession;
begin
result:=useCookie;
if not wasCookie then begin
if pos('.ico',document)>0 then
result:=false;
if pos('.css',document)>0 then
result:=false;
if pos('.js',document)>0 then
result:=false;
end;
end;
function THttpInfo.setCookie;
var
sCookie:AnsiString;
begin
sCookie:= AddCookieProperty(FName, FValue, ''); {Do not Localize}
if fPath<>'' then
sCookie := AddCookieProperty('path', FPath, sCookie); {Do not Localize}
// if FInternalVersion = cvNetscape then
// begin
if fExpires<>'' then
sCookie := AddCookieProperty('expires', FExpires, sCookie); {Do not Localize}
// end;
if fDomain<>'' then
sCookie:= AddCookieProperty('domain', FDomain, sCookie); {Do not Localize}
if FSecures<>'' then
sCookie:=sCookie+';HttpOnly ';
result:=addCookie(sCookie);
// if FSecure then
// begin
// result := AddCookieFlag('secure', result); {Do not Localize}
// end;
end;
function THttpInfo.getCookie;
Var
io,
i: Integer;
ss : shortstring;
CookieProp: TStringList;
procedure LoadProperties(APropertyList: TStringList);
begin
FPath := APropertyList.values['PATH']; {Do not Localize}
// Tomcat can return SetCookie2 with path wrapped in "
if (Length(FPath) > 0) then
begin
if FPath[1] = '"' then {Do not Localize}
Delete(FPath, 1, 1);
if FPath[Length(FPath)] = '"' then {Do not Localize}
SetLength(FPath, Length(FPath) - 1);
end
else begin
FPath := '/'; {Do not Localize}
end;
fExpires := APropertyList.values['EXPIRES']; {Do not Localize}
FDomain := APropertyList.values['DOMAIN']; {Do not Localize}
fSecures:='';
FSession := APropertyList.values[GSessionIDCookie]; {Do not Localize}
// FSecure := APropertyList.IndexOf('SECURE') <> -1; {Do not Localize}
end;
begin
CookieProp := TStringList.Create;
try
io:=pos(';',AValue);
while io > 0 do {Do not Localize}
begin
ss:=copy(AValue,1,io-1);
delete(AValue,1,io);
CookieProp.Add(Trim(ss)); {Do not Localize}
io:=pos(';',AValue);
// if (Pos(';', AValue) = 0) and (Length(AValue) > 0) then CookieProp.Add(Trim(AValue)); {Do not Localize}
end;
if (io=0) and (length(AValue)>0) then CookieProp.Add(trim(aValue));
if CookieProp.Count = 0 then CookieProp.Text := AValue;
FName := CookieProp.Names[0];
// Fvalue := CookieProp.valuefromindex[0];
// cookieprop.quotechar:='"';
FValue := CookieProp.Values[fname];
CookieProp.Delete(0);
for i := 0 to CookieProp.Count - 1 do
if Pos('=', CookieProp[i]) = 0 then {Do not Localize}
begin
CookieProp[i] := UpperCase(CookieProp[i]); // This is for cookie flags (secure)
end
else begin
CookieProp[i] := UpperCase(CookieProp.Names[i]) + '=' + CookieProp.values[CookieProp.Names[i]]; {Do not Localize}
end;
LoadProperties(CookieProp);
finally
FreeAndNil(CookieProp);
end;
result:=1;
end;
{
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; pl-PL) AppleWebKit/528.16 (KHTML, like Gecko) Version/4.0 Safari/528.16
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us) AppleWebKit/528.12 (KHTML, like Gecko) Version/4.0 Safari/528.12
User-Agent: Mozilla/5.0 (iPhone; U; CPU iPhone OS 2_2_1 like Mac OS X; en-us) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/5H11 Safari/525.20
User-Agent: Opera/9.63 (Windows NT 6.0; U; en) Presto/2.1.1
User-Agent: Opera/9.63 (Macintosh; Intel Mac OS X; U; en) Presto/2.1.1
Mozilla/5.0 (iPod; U; CPU iPhone OS 3_1_2 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7D11 Safari/528.16
}
function tHttpInfo.httpHost;
begin
if ssl then
result:='https://'+fHost
else
result:='http://'+fHost
end;
procedure tHttpInfo.detectAgent;
begin
fAgentID:=detectAgent(fUserAgent);
end;
function tHttpInfo.detectAgent( aAgent:string):integer;
var
agentID : integer;
begin
aAgent:=UpperCase(aAgent);
agentID:=agGSM;
if pos('NOKIA',aAgent)>0 then agentID:=agGSM;
if pos('OPERA',aAgent)>0 then begin
agentID:=agPC;
if pos('MOBI',aAgent)>0 then begin
result:=agPalmOpera;
exit;
end;
end;
if{ (pos('MOZILLA',aAgent)>0)and }(pos('WINDOWS;',aAgent)>0) then agentID:=agPC
else if (pos('ANDROID',aAgent)>0) then agentID:=agAndroid
else if (pos('IPHONE',aAgent)>0) or (pos('IPOD',aAgent)>0) or (pos('IPAD',aAgent)>0) then agentID:=agIOS
else if (pos('WEBKIT',aAgent)>0) then agentID:=agPC
else if (pos('WINDOWS NT',aAgent)>0) then agentID:=agPC
else if (pos('MACINTOSH;',aAgent)>0) then agentID:=agPC
else if (pos('Mobile;',aAgent)>0) then begin
agentID:=agFirefoxOs;
end else if (pos('X11;',aAgent)>0) then agentID:=agPC;
if pos('WINDOWS CE',aAgent)>0 then begin
agentID:=agPalmAjax;
if pos('OPERA',aAgent)>0 then agentId:=agPalmOpera;
// if pos('3.',aAgent)>0 then agentID:=agPalm;
// if pos('IEMOBILE',aAgent)>0 then agentID:=agPalmA
end;
result:=agentID;
end;
constructor tParserUrl.create;
procedure ReplaceChar(c1, c2: Char; var St: String);
var
p: Integer;
begin
while True do
begin
p := Pos(c1, St);
if p = 0 then Break
else St[p] := c2;
end;
end;
var
i: Integer;
begin
i:= Pos(':', aURL);
if i<> 0 then begin
Scheme:=copy(aUrl,1,i-1);
System.Delete(aURL, 1, i+2);
end;
i := Pos('/', aURL);
if i>0 then begin
Host := Copy(aURL, 1, i);
Query := Copy(aURL, i+1, Length(aURL) - i + 1);
end else begin
host:=aUrl;
query:='';
end;
if (Length(Host) > 0) and (Host[Length(Host)] = '/') then
SetLength(Host, Length(Host) - 1);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey media store for IOS }
{ }
{ Copyright(c) 2012-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.MediaLibrary.IOS;
interface
procedure RegisterMediaLibraryServices;
implementation
uses
System.SysUtils, System.Classes, System.Types, System.Math,
FMX.MediaLibrary, FMX.Types, FMX.Types3D, FMX.Controls, FMX.Platform, FMX.Graphics,
FMX.Helpers.iOS,
iOSapi.MediaPlayer, iOSapi.Foundation, iOSapi.UIKit, iOSapi.CoreGraphics,
Macapi.ObjectiveC;
type
TImageDelegate = class;
TImageManagerCocoa = class (TInterfacedObject, IFMXTakenImageService, IFMXCameraService)
strict private
FRequiredResolution: TSize;
FOnDidFinishTaking: TOnDidFinishTaking;
FOnDidCancelTaking: TOnDidCancelTaking;
FImageDelegate: TImageDelegate;
FImagePicker: UIImagePickerController;
// For iPad
FPopoverController : UIPopoverController;
protected
procedure TakeImage(const AControl: TControl; const ASourceType: UIImagePickerControllerSourceType);
public
constructor Create;
destructor Destroy; override;
class function IsAvailableSourceType(const ASourceType: UIImagePickerControllerSourceType): Boolean;
procedure ClosePopover;
{ IFMXTakenImage }
procedure TakeImageFromLibrary(const AControl: TControl; const ARequiredResolution: TSize;
const AOnDidDinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking);
{ IFMXCameraService }
procedure TakePhoto(const AControl: TControl; const ARequiredResolution: TSize;
const AOnDidDinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking);
property RequiredResolution: TSize read FRequiredResolution write FRequiredResolution;
end;
TImageDelegate = class (TOCLocal, UIImagePickerControllerDelegate)
strict private
[weak] FImageManager: TImageManagerCocoa;
FOnDidFinishTaking: TOnDidFinishTaking;
FOnDidCancelTaking: TOnDidCancelTaking;
protected
procedure DoDidFinishTaking(const AImage: TBitmap);
procedure DoDidCancelTaking;
procedure HidePicker(const APicker: UIImagePickerController);
function GetAngleOfImageOrientation(const AImage: UIImage): Single;
public
property ImageManager: TImageManagerCocoa read FImageManager write FImageManager;
{ UIImagePickerControllerDelegate }
procedure imagePickerController(picker: UIImagePickerController; didFinishPickingImage: UIImage; editingInfo: NSDictionary); overload; cdecl;
procedure imagePickerController(picker: UIImagePickerController; didFinishPickingMediaWithInfo: NSDictionary); overload; cdecl;
procedure imagePickerControllerDidCancel(picker: UIImagePickerController); cdecl;
property OnDidFinishTaking: TOnDidFinishTaking read FOnDidFinishTaking write FOnDidFinishTaking;
property OnDidCancelTaking: TOnDidCancelTaking read FOnDidCancelTaking write FOnDidCancelTaking;
end;
TShareService = class (TInterfacedObject, IFMXShareSheetActionsService)
strict private
FUIActivityViewController: UIActivityViewController;
FActivityItems: NSMutableArray;
// For iPad
FPopoverController : UIPopoverController;
public
constructor Create;
destructor Destroy; override;
{ IFMXShareSheetActionsService }
procedure Share(const AControl: TControl; const AText: string; const ABitmap: TBitmap);
end;
procedure RegisterMediaLibraryServices;
var
ImageManager: TImageManagerCocoa;
begin
ImageManager := TImageManagerCocoa.Create;
if TImageManagerCocoa.IsAvailableSourceType(UIImagePickerControllerSourceTypeCamera) then
TPlatformServices.Current.AddPlatformService(IFMXCameraService, IInterface(ImageManager));
if TImageManagerCocoa.IsAvailableSourceType(UIImagePickerControllerSourceTypeSavedPhotosAlbum) then
TPlatformServices.Current.AddPlatformService(IFMXTakenImageService, IInterface(ImageManager));
if TOSVersion.Check(6, 0) then
TPlatformServices.Current.AddPlatformService(IFMXShareSheetActionsService, IInterface(TShareService.Create));
end;
procedure TImageManagerCocoa.ClosePopover;
begin
if Assigned(FPopoverController) then
FPopoverController.dismissPopoverAnimated(True);
end;
constructor TImageManagerCocoa.Create;
begin
inherited Create;
FImageDelegate := TImageDelegate.Create;
FImageDelegate.ImageManager := Self;
FImagePicker := TUIImagePickerController.Create;
FImagePicker.retain;
FImagePicker.setDelegate(FImageDelegate.GetObjectID);
FImagePicker.setAllowsEditing(True);
end;
destructor TImageManagerCocoa.Destroy;
begin
FImagePicker.release;
FImageDelegate.DisposeOf;
if Assigned(FPopoverController) then
FPopoverController.release;
inherited Destroy;
end;
class function TImageManagerCocoa.IsAvailableSourceType(const ASourceType: UIImagePickerControllerSourceType): Boolean;
begin
Result := TUIImagePickerController.OCClass.isSourceTypeAvailable(ASourceType);
end;
procedure TImageManagerCocoa.TakeImageFromLibrary(const AControl: TControl; const ARequiredResolution: TSize; const AOnDidDinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking);
begin
FRequiredResolution := ARequiredResolution;
FOnDidFinishTaking := AOnDidDinishTaking;
FOnDidCancelTaking := AOnDidCancelTaking;
if IsAvailableSourceType(UIImagePickerControllerSourceTypeCamera) then
TakeImage(AControl, UIImagePickerControllerSourceTypePhotoLibrary)
else
TakeImage(AControl, UIImagePickerControllerSourceTypeSavedPhotosAlbum);
end;
procedure TImageManagerCocoa.TakePhoto(const AControl: TControl; const ARequiredResolution: TSize; const AOnDidDinishTaking: TOnDidFinishTaking; const AOnDidCancelTaking: TOnDidCancelTaking);
begin
FRequiredResolution := ARequiredResolution;
FOnDidFinishTaking := AOnDidDinishTaking;
FOnDidCancelTaking := AOnDidCancelTaking;
TakeImage(AControl, UIImagePickerControllerSourceTypeCamera);
end;
procedure TImageManagerCocoa.TakeImage(const AControl: TControl; const ASourceType: UIImagePickerControllerSourceType);
procedure ShowInFullScreen;
var
Window: UIWindow;
begin
Window := SharedApplication.keyWindow;
if Assigned(Window) and Assigned(Window.rootViewController) then
Window.rootViewController.presentModalViewController(FImagePicker, True);
end;
procedure ShowInPopover;
var
Window: UIWindow;
PopoverRect: CGRect;
AbsolutePos: TPointF;
begin
Window := SharedApplication.keyWindow;
AbsolutePos := AControl.LocalToAbsolute(PointF(0, 0));
PopoverRect := CGRectMake(AbsolutePos.X, AbsolutePos.Y, AControl.Width, AControl.Height);
if not Assigned(FPopoverController) then
FPopoverController := TUIPopoverController.Alloc;
FPopoverController.initWithContentViewController(FImagePicker);
FPopoverController.presentPopoverFromRect(
PopoverRect, Window.rootViewController.View, UIPopoverArrowDirectionUp, True);
end;
procedure ShowPicker;
begin
// Camera for iPad is showed only in full screen on iPad and iPhone
if not IsPad or (ASourceType = UIImagePickerControllerSourceTypeCamera) then
ShowInFullScreen
else
ShowInPopover;
end;
begin
if IsAvailableSourceType(ASourceType) then
begin
FImageDelegate.OnDidFinishTaking := FOnDidFinishTaking;
FImageDelegate.OnDidCancelTaking := FOnDidCancelTaking;
FImagePicker.setSourceType(ASourceType);
ShowPicker;
end;
end;
{ TImageDelegate }
procedure TImageDelegate.DoDidCancelTaking;
begin
if Assigned(OnDidCancelTaking) then
OnDidCancelTaking;
end;
procedure TImageDelegate.DoDidFinishTaking(const AImage: TBitmap);
begin
if Assigned(OnDidFinishTaking) then
OnDidFinishTaking(AImage);
end;
function TImageDelegate.GetAngleOfImageOrientation(const AImage: UIImage): Single;
begin
case AImage.imageOrientation of
UIImageOrientationDown,
UIImageOrientationDownMirrored:
Result := 180;
UIImageOrientationLeft,
UIImageOrientationLeftMirrored:
Result := -90;
UIImageOrientationRight,
UIImageOrientationRightMirrored:
Result := 90;
UIImageOrientationUp,
UIImageOrientationUpMirrored:
Result := 0;
else
Result := 0;
end;
end;
procedure TImageDelegate.HidePicker(const APicker: UIImagePickerController);
begin
if Assigned(FImageManager) and IsPad and (APicker.sourceType <> UIImagePickerControllerSourceTypeCamera) then
FImageManager.ClosePopover
else
APicker.dismissModalViewControllerAnimated(True);
end;
procedure TImageDelegate.imagePickerController(picker: UIImagePickerController; didFinishPickingImage: UIImage;
editingInfo: NSDictionary);
var
Bitmap: TBitmap;
RotationAngle: Single;
begin
HidePicker(picker);
RotationAngle := GetAngleOfImageOrientation(didFinishPickingImage);
Bitmap := UIImageToBitmap(didFinishPickingImage, RotationAngle, FImageManager.RequiredResolution);
try
DoDidFinishTaking(Bitmap);
finally
Bitmap.DisposeOf;
end;
end;
procedure TImageDelegate.imagePickerController(picker: UIImagePickerController;
didFinishPickingMediaWithInfo: NSDictionary);
var
Bitmap: TBitmap;
ImageTmp: UIImage;
RotationAngle: Single;
begin
HidePicker(picker);
ImageTmp := TUIImage.Wrap(didFinishPickingMediaWithInfo.objectForKey((UIImagePickerControllerOriginalImage as ILocalObject).GetObjectID));
// The camera does pictures in portrait orientation
RotationAngle := GetAngleOfImageOrientation(ImageTmp);
Bitmap := UIImageToBitmap(ImageTmp, RotationAngle, FImageManager.RequiredResolution);
try
DoDidFinishTaking(Bitmap);
finally
Bitmap.DisposeOf;
end;
end;
procedure TImageDelegate.imagePickerControllerDidCancel(picker: UIImagePickerController);
begin
DoDidCancelTaking;
HidePicker(picker);
end;
{ TSharingService }
constructor TShareService.Create;
begin
FUIActivityViewController := TUIActivityViewController.alloc;
FActivityItems := TNSMutableArray.Create;
end;
destructor TShareService.Destroy;
begin
FUIActivityViewController.release;
FActivityItems.release;
inherited Destroy;
end;
procedure TShareService.Share(const AControl: TControl; const AText: string; const ABitmap: TBitmap);
procedure ShowForPhone;
var
Window: UIWindow;
begin
Window := SharedApplication.keyWindow;
if Assigned(Window) and Assigned(Window.rootViewController) then
Window.rootViewController.presentModalViewController(FUIActivityViewController, True);
end;
procedure ShowForPad;
var
Window: UIWindow;
PopoverRect: CGRect;
AbsolutePos: TPointF;
begin
Window := SharedApplication.keyWindow;
if Assigned(AControl) then
begin
AbsolutePos := AControl.LocalToAbsolute(PointF(0, 0));
PopoverRect := CGRectMake(AbsolutePos.X, AbsolutePos.Y, AControl.Width, AControl.Height);
end
else
PopoverRect := CGRectMake(0, 0, 0, 0);
if not Assigned(FPopoverController) then
FPopoverController := TUIPopoverController.Alloc;
FPopoverController.initWithContentViewController(FUIActivityViewController);
FPopoverController.presentPopoverFromRect(
PopoverRect, Window.rootViewController.View, UIPopoverArrowDirectionAny, True);
end;
procedure ShowActionsSheet;
begin
if IsPad then
ShowForPad
else
ShowForPhone;
end;
var
OCImage: UIImage;
begin
Assert(Assigned(ABitmap) or not AText.IsEmpty);
FActivityItems.removeAllObjects;
if not AText.IsEmpty then
FActivityItems.addObject((NSSTR(AText) as ILocalObject).GetObjectID);
if Assigned(ABitmap) and not ABitmap.IsEmpty then
begin
OCImage := BitampToUIImage(ABitmap);
FActivityItems.addObject((OCImage as ILocalObject).GetObjectID);
end;
try
if FActivityItems.count > 0 then
begin
FUIActivityViewController.initWithActivityItems(FActivityItems , nil);
ShowActionsSheet;
end;
finally
if Assigned(OCImage) then
OCImage.release;
end;
end;
end.
|
unit frmAutoModeSettings;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Spin, Buttons, ExtCtrls, RogerColorComboBox;
type
TAutoModeSettingsForm = class(TForm)
Label1: TLabel;
gbStartPosition: TGroupBox;
rvspStartPosition: TSpinEdit;
Label2: TLabel;
btnFirstSong: TButton;
btnActualSong: TButton;
btnRandomSong: TButton;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
gbSongs: TGroupBox;
chbShowCurrent: TCheckBox;
chbShowNext: TCheckBox;
rgPassThrough: TRadioGroup;
gbClocks: TGroupBox;
chbShowPartyClock: TCheckBox;
chbShowMidnightClock: TCheckBox;
rgMidnightClockMode: TRadioGroup;
Label3: TLabel;
chbRunSSAlso: TCheckBox;
gbColors: TGroupBox;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
rccbTitles: TRogerColorComboBox;
rccbBackground: TRogerColorComboBox;
rccbTexts: TRogerColorComboBox;
procedure btnFirstSongClick(Sender: TObject);
procedure btnActualSongClick(Sender: TObject);
procedure btnRandomSongClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AutoModeSettingsForm: TAutoModeSettingsForm;
implementation
{$R *.DFM}
procedure TAutoModeSettingsForm.btnFirstSongClick(Sender: TObject);
begin
rvspStartPosition.Value:=1;
end;
procedure TAutoModeSettingsForm.btnActualSongClick(Sender: TObject);
begin
rvspStartPosition.Value:=btnActualSong.Tag;
end;
procedure TAutoModeSettingsForm.btnRandomSongClick(Sender: TObject);
begin
rvspStartPosition.Value:=Random(btnRandomSong.Tag-1)+1;
end;
procedure TAutoModeSettingsForm.FormShow(Sender: TObject);
begin
Randomize;
end;
end.
|
unit RocketLandingLegs;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, BaseModel;
type
IBaseRocketLandingLegs = interface(IBaseModel) ['{1F2C4C51-3A40-4F12-8F81-39F77FB6BD7B}']
function GetMaterial: string;
function GetNumber: LongWord;
procedure SetMaterial(AValue: string);
procedure SetNumber(AValue: LongWord);
end;
IRocketLandingLegs = interface(IBaseRocketLandingLegs) ['{E6766294-6C72-470B-9265-195419DA2A81}']
property Material: string read GetMaterial write SetMaterial;
property Number: LongWord read GetNumber write SetNumber;
end;
function NewRocketLandingLegs: IRocketLandingLegs;
implementation
uses
Variants;
type
{ TRocketLandingLegs }
TRocketLandingLegs = class(TBaseModel, IRocketLandingLegs)
private
FMaterial: string;
FNumber: LongWord;
private
function GetMaterial: string;
function GetNumber: LongWord;
private
procedure SetMaterial(AValue: string);
procedure SetMaterial(AValue: Variant);
procedure SetNumber(AValue: LongWord);
procedure SetNumber(AValue: Variant);
public
function ToString: string; override;
published
property material: Variant write SetMaterial;
property number: Variant write SetNumber;
end;
function NewRocketLandingLegs: IRocketLandingLegs;
begin
Result := TRocketLandingLegs.Create;
end;
{ TRocketLandingLegs }
function TRocketLandingLegs.GetMaterial: string;
begin
Result := FMaterial;
end;
function TRocketLandingLegs.GetNumber: LongWord;
begin
Result := FNumber;
end;
procedure TRocketLandingLegs.SetMaterial(AValue: string);
begin
FMaterial := AValue;
end;
procedure TRocketLandingLegs.SetMaterial(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FMaterial := '';
end else if VarIsStr(AValue) then
FMaterial := AValue;
end;
procedure TRocketLandingLegs.SetNumber(AValue: LongWord);
begin
FNumber := AValue;
end;
procedure TRocketLandingLegs.SetNumber(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FNumber := -0;
end else if VarIsNumeric(AValue) then
FNumber := AValue;
end;
function TRocketLandingLegs.ToString: string;
begin
Result := Format(''
+ 'Material: %s' + LineEnding
+ 'Number: %u'
, [
GetMaterial,
GetNumber
]);
end;
end.
|
unit frmEditImage;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
scControls, scGPControls, uGDIUnit, AARotate, AARotate_Fast, jpeg, uFunction,
acImage, uConst, System.IniFiles, System.StrUtils;
type
TDrawingTool = (dtLine, dtRectangle, dtEllipse, dtRoundRect);
TPictureArray = array of TPicture;
TEditImage = class(TForm)
pnlEditImage: TPanel;
btnInit: TButton;
btnSaveAndClose: TButton;
btnClose: TButton;
lblMousePoint: TLabel;
ScrollBox1: TScrollBox;
lblOrigin: TLabel;
imgEdit: TsImage;
lbColorList: TListBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnCloseClick(Sender: TObject);
procedure btnSaveAndCloseClick(Sender: TObject);
procedure btnInitClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure imgEditMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure imgEditMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure imgEditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure lbColorListDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure btnObjInfoClick(Sender: TObject);
procedure lbColorListClick(Sender: TObject);
private
procedure SavePicture;
procedure UndoPicture;
procedure SetImageSize;
{ Private declarations }
public
BrushStyle: TBrushStyle;
PenStyle: TPenStyle;
PenWide: Integer;
Drawing: Boolean;
Origin, MovePt: TPoint;
DrawingTool: TDrawingTool;
paPictures: TPictureArray;
CropBeginPoint, CropEndPoint: TPoint;
BoxBeginPoint, BoxEndPoint: TPoint;
RotatedCount: Integer;
procedure SaveStyles;
procedure RestoreStyles;
procedure DrawShape(TopLeft, BottomRight: TPoint; AMode: TPenMode);
procedure SetImage(bmp: TBitmap); overload;
procedure SetImage(bmp: TBitmap; BoxArray: TObjInfoArray); overload;
procedure SetImage(jpg: TJPEGImage); overload;
{ Public declarations }
end;
var
EditImage: TEditImage;
FSelectedObject: Boolean;
FAddedObjectArray: TObjInfoArray;
implementation
{$R *.dfm}
procedure TEditImage.btnCloseClick(Sender: TObject);
begin
if (Length(paPictures) = 0) or
((Length(paPictures) > 0) and (MessageDlg('The image has been changed. Do you really want to close this form?', mtConfirmation, mbYesNo, 0) = mrYes)) then
ModalResult := mrCancel
else
Exit;
end;
procedure TEditImage.btnInitClick(Sender: TObject);
var
i: Integer;
begin
imgEdit.Picture.Assign(paPictures[0]);
for i := Length(paPictures) - 1 downto 1 do
begin
paPictures[Length(paPictures) - 1].Free;
SetLength(paPictures, Length(paPictures) - 1);
end;
end;
procedure TEditImage.btnSaveAndCloseClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TEditImage.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TEditImage.FormCreate(Sender: TObject);
var
i: Integer;
begin
SetImageSize;
Position := poScreenCenter;
Self.DoubleBuffered := True; // to reduce flickering...
imgEdit.Stretch := False;
RotatedCount := 0;
lbColorList.Items.BeginUpdate;
for i := 0 to Length(FObjColorArray)-1 do
lbColorList.Items.AddObject(FObjColorArray[i].ObjName, Pointer(FObjColorArray[i].ObjColor));
lbColorList.Items.EndUpdate;
FSelectedObject := False;
end;
procedure TEditImage.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Shift = [ssCtrl]) then
case Key of
90:
UndoPicture;
83:
btnSaveAndClose.Click; // Ctrl+S
73:
btnInit.Click; // Ctrl+i
end;
// if Key = 49 then btnCrop.OnClick(nil);
// if Key = 50 then btnBox.OnClick(nil);
end;
procedure TEditImage.imgEditMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
SavePicture;
with imgEdit, Canvas do
begin
Brush.Color := clBtnFace;
Brush.Style := bsClear;
Pen.Style := psSolid;
Pen.Color := clBlack;
Pen.Width := 2;
BoxBeginPoint := Point(X, Y);
end;
DrawingTool := dtRectangle;
Drawing := True;
imgEdit.Canvas.MoveTo(X, Y);
Origin := Point(X, Y);
MovePt := Origin;
// lblOrigin.Caption := Format('Origin: (%d, %d)', [X, Y]);
end
else if Button = mbRight then
begin
UndoPicture;
SetImageSize;
end;
end;
procedure TEditImage.imgEditMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
ARect: TRect;
begin
lblMousePoint.Caption := Format('Point : (%d, %d)', [X, Y]);
if Drawing then
begin
DrawShape(Origin, MovePt, pmNotXor);
MovePt := Point(X, Y);
DrawShape(Origin, MovePt, pmNotXor);
lblOrigin.Caption := Format('Box W,H: (%d, %d)', [Abs(X-Origin.X), Abs(Y-Origin.Y)]);
end;
end;
procedure TEditImage.imgEditMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
bmpCrop, bmpRotated: TBitmap;
dwOffset: Integer;
begin
if Button = mbLeft then
begin
if Drawing then
begin
DrawShape(Origin, Point(X, Y), pmCopy);
Drawing := False;
end;
BoxEndPoint := Point(X, Y);
// Added Object Info array
SetLength(FAddedObjectArray, Length(FAddedObjectArray) + 1);
FAddedObjectArray[Length(FAddedObjectArray)-1].Seq := Length(FObjInfoArray)+Length(FAddedObjectArray);
if lbColorList.ItemIndex > -1 then
FAddedObjectArray[Length(FAddedObjectArray)-1].ClassName := lbColorList.Items[lbColorList.ItemIndex];
FAddedObjectArray[Length(FAddedObjectArray)-1].Xmin := Origin.X / ScrollBox1.Width;
FAddedObjectArray[Length(FAddedObjectArray)-1].Ymin := Origin.Y / ScrollBox1.Height;
FAddedObjectArray[Length(FAddedObjectArray)-1].Xmax := BoxEndPoint.X / ScrollBox1.Width;
FAddedObjectArray[Length(FAddedObjectArray)-1].Ymax := BoxEndPoint.Y / ScrollBox1.Height;
FAddedObjectArray[Length(FAddedObjectArray)-1].BoxVisible := True;
if lbColorList.ItemIndex > -1 then
FAddedObjectArray[Length(FAddedObjectArray)-1].ObjProp.ObjName := lbColorList.Items[lbColorList.ItemIndex];
if lbColorList.ItemIndex > -1 then
FAddedObjectArray[Length(FAddedObjectArray)-1].ObjProp.ObjColor := TColor(lbColorList.Items.Objects[lbColorList.ItemIndex]);
if FAddedObjectArray[Length(FAddedObjectArray)-1].ObjProp.ObjName <> '' then
FAddedObjectArray[Length(FAddedObjectArray)-1].IsNewObj := False
else
FAddedObjectArray[Length(FAddedObjectArray)-1].IsNewObj := True;
SetLength(FObjInfoArray, Length(FObjInfoArray) + 1);
FObjInfoArray[Length(FObjInfoArray)-1] := FAddedObjectArray[Length(FAddedObjectArray)-1];
MakeButton(Self, pnlEditImage, alBottom, btnObjInfoClick, FAddedObjectArray[Length(FAddedObjectArray)-1].ClassName + '::' + IntToStr(FAddedObjectArray[Length(FAddedObjectArray)-1].Seq), FAddedObjectArray[Length(FAddedObjectArray)-1]);
end;
end;
procedure TEditImage.lbColorListClick(Sender: TObject);
begin
if not FSelectedObject then Exit;
end;
procedure TEditImage.lbColorListDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
begin
with Control as TListBox do
begin
// Canvas.Brush.Style := bsSolid;
// Canvas.Brush.Color := TColor(Items.Objects[Index]);
// Canvas.Pen.Style := psClear;
// Canvas.FillRect(Rect);
Canvas.Font.Color := TColor(Items.Objects[Index]);
Canvas.TextOut(Rect.Left + 2, Rect.Top, Items[Index]);
end;
end;
procedure TEditImage.DrawShape(TopLeft, BottomRight: TPoint; AMode: TPenMode);
begin
with imgEdit.Canvas do
begin
Pen.Mode := AMode;
case DrawingTool of
dtLine:
begin
imgEdit.Canvas.MoveTo(TopLeft.X, TopLeft.Y);
imgEdit.Canvas.LineTo(BottomRight.X, BottomRight.Y);
end;
dtRectangle:
begin
imgEdit.Canvas.Rectangle(TopLeft.X, TopLeft.Y, BottomRight.X, BottomRight.Y);
end;
dtEllipse:
imgEdit.Canvas.Ellipse(TopLeft.X, TopLeft.Y, BottomRight.X, BottomRight.Y);
dtRoundRect:
imgEdit.Canvas.RoundRect(TopLeft.X, TopLeft.Y, BottomRight.X, BottomRight.Y, (TopLeft.X - BottomRight.X) div 2, (TopLeft.Y - BottomRight.Y) div 2);
end;
end;
end;
procedure TEditImage.RestoreStyles;
begin
with imgEdit.Canvas do
begin
BrushStyle := Brush.Style;
PenStyle := Pen.Style;
PenWide := Pen.Width;
end;
end;
procedure TEditImage.SaveStyles;
begin
with imgEdit.Canvas do
begin
Brush.Style := BrushStyle;
Pen.Style := PenStyle;
Pen.Width := PenWide;
end;
end;
procedure TEditImage.SavePicture;
begin
Setlength(paPictures, Length(paPictures) + 1);
paPictures[Length(paPictures) - 1] := TPicture.Create;
paPictures[Length(paPictures) - 1].Assign(imgEdit.Picture);
end;
procedure TEditImage.UndoPicture;
begin
if Length(paPictures) <= 1 then
begin
imgEdit.Picture.Assign(paPictures[0]);
Exit;
end;
SaveStyles;
imgEdit.Picture.Assign(paPictures[Length(paPictures) - 1]);
RestoreStyles;
paPictures[Length(paPictures) - 1].Free;
SetLength(paPictures, Length(paPictures) - 1);
end;
procedure TEditImage.SetImageSize;
begin
ClientWidth := imgEdit.Picture.Width + pnlEditImage.Width + 5;
ClientHeight := imgEdit.Picture.Height + 5;
Invalidate;
end;
procedure TEditImage.SetImage(bmp: TBitmap);
begin
imgEdit.Picture.Bitmap.Assign(bmp);
SetImageSize;
end;
procedure TEditImage.SetImage(bmp: TBitmap; BoxArray: TObjInfoArray);
var
i: Integer;
begin
for i := 0 to Length(BoxArray)-1 do
begin
MakeButton(Self, pnlEditImage, alBottom, btnObjInfoClick, BoxArray[i].ClassName + '::' + IntToStr(BoxArray[i].Seq), BoxArray[i]);
end;
imgEdit.Picture.Bitmap.Assign(bmp);
SetImageSize;
end;
procedure TEditImage.SetImage(jpg: TJPEGImage);
begin
imgEdit.Picture.Assign(jpg);
SetImageSize;
end;
// ObjInfo OnClick Event
procedure TEditImage.btnObjInfoClick(Sender: TObject);
var
i, BtnNumber: Integer;
BtnName: string;
minPoint, maxPoint: TPoint;
Selected, tmp2: Integer;
ObjLabel: TComponent;
begin
// Matching Button Number with FObjInfoArray
BtnName := TscGPButton(Sender).Name;
TryStrToInt(StringReplace(BtnName, 'btnObjInfo', '', [rfReplaceAll]), BtnNumber);
for i := 0 to Length(FObjInfoArray)-1 do
begin
if FObjInfoArray[i].Seq = BtnNumber then Selected := i;
ObjLabel := FindComponent('lblObjInfo'+ IntToStr(FObjInfoArray[i].Seq));
if Assigned(ObjLabel) then ObjLabel.Free;
end;
// Get the point of Object for crop box
MakeLabel(Self, ScrollBox1, nil, 'Selected', FObjInfoArray[Selected]);
end;
end.
|
(*
Fast Memory Manager 4.991
Description:
A fast replacement memory manager for Embarcadero Delphi Win32 applications
that scales well under multi-threaded usage, is not prone to memory
fragmentation, and supports shared memory without the use of external .DLL
files.
Homepage:
http://fastmm.sourceforge.net
Advantages:
- Fast
- Low overhead. FastMM is designed for an average of 5% and maximum of 10%
overhead per block.
- Supports up to 3GB of user mode address space under Windows 32-bit and 4GB
under Windows 64-bit. Add the "$SetPEFlags $20" option (in curly braces)
to your .dpr to enable this.
- Highly aligned memory blocks. Can be configured for either 8-byte or 16-byte
alignment.
- Good scaling under multi-threaded applications
- Intelligent reallocations. Avoids slow memory move operations through
not performing unneccesary downsizes and by having a minimum percentage
block size growth factor when an in-place block upsize is not possible.
- Resistant to address space fragmentation
- No external DLL required when sharing memory between the application and
external libraries (provided both use this memory manager)
- Optionally reports memory leaks on program shutdown. (This check can be set
to be performed only if Delphi is currently running on the machine, so end
users won't be bothered by the error message.)
- Supports Delphi 4 (or later), C++ Builder 4 (or later), Kylix 3.
Usage:
Delphi:
Place this unit as the very first unit under the "uses" section in your
project's .dpr file. When sharing memory between an application and a DLL
(e.g. when passing a long string or dynamic array to a DLL function), both the
main application and the DLL must be compiled using this memory manager (with
the required conditional defines set). There are some conditional defines
(inside FastMM4Options.inc) that may be used to tweak the memory manager. To
enable support for a user mode address space greater than 2GB you will have to
use the EditBin* tool to set the LARGE_ADDRESS_AWARE flag in the EXE header.
This informs Windows x64 or Windows 32-bit (with the /3GB option set) that the
application supports an address space larger than 2GB (up to 4GB). In Delphi 6
and later you can also specify this flag through the compiler directive
{$SetPEFlags $20}
*The EditBin tool ships with the MS Visual C compiler.
C++ Builder 6:
Refer to the instructions inside FastMM4BCB.cpp.
License:
This work is copyright Professional Software Development / Pierre le Riche. It
is released under a dual license, and you may choose to use it under either the
Mozilla Public License 1.1 (MPL 1.1, available from
http://www.mozilla.org/MPL/MPL-1.1.html) or the GNU Lesser General Public
License 2.1 (LGPL 2.1, available from
http://www.opensource.org/licenses/lgpl-license.php). If you find FastMM useful
or you would like to support further development, a donation would be much
appreciated. My banking details are:
Country: South Africa
Bank: ABSA Bank Ltd
Branch: Somerset West
Branch Code: 334-712
Account Name: PSD (Distribution)
Account No.: 4041827693
Swift Code: ABSAZAJJ
My PayPal account is:
bof@psd.co.za
Contact Details:
My contact details are shown below if you would like to get in touch with me.
If you use this memory manager I would like to hear from you: please e-mail me
your comments - good and bad.
Snailmail:
PO Box 2514
Somerset West
7129
South Africa
E-mail:
plr@psd.co.za
Support:
If you have trouble using FastMM, you are welcome to drop me an e-mail at the
address above, or you may post your questions in the BASM newsgroup on the
Embarcadero news server (which is where I hang out quite frequently).
Disclaimer:
FastMM has been tested extensively with both single and multithreaded
applications on various hardware platforms, but unfortunately I am not in a
position to make any guarantees. Use it at your own risk.
Acknowledgements (for version 4):
- Eric Grange for his RecyclerMM on which the earlier versions of FastMM were
based. RecyclerMM was what inspired me to try and write my own memory
manager back in early 2004.
- Primoz Gabrijelcic for helping to track down various bugs.
- Dennis Christensen for his tireless efforts with the Fastcode project:
helping to develop, optimize and debug the growing Fastcode library.
- JiYuan Xie for implementing the leak reporting code for C++ Builder.
- Sebastian Zierer for implementing the OS X support.
- Pierre Y. for his suggestions regarding the extension of the memory leak
checking options.
- Hanspeter Widmer for his suggestion to have an option to display install and
uninstall debug messages and moving options to a separate file, as well as
the new usage tracker.
- Anders Isaksson and Greg for finding and identifying the "DelphiIsRunning"
bug under Delphi 5.
- Francois Malan for various suggestions and bug reports.
- Craig Peterson for helping me identify the cache associativity issues that
could arise due to medium blocks always being an exact multiple of 256 bytes.
Also for various other bug reports and enhancement suggestions.
- Jarek Karciarz, Vladimir Ulchenko (Vavan) and Bob Gonder for their help in
implementing the BCB support.
- Ben Taylor for his suggestion to display the object class of all memory
leaks.
- Jean Marc Eber and Vincent Mahon (the Memcheck guys) for the call stack
trace code and also the method used to catch virtual method calls on freed
objects.
- Nahan Hyn for the suggestion to be able to enable or disable memory leak
reporting through a global variable (the "ManualLeakReportingControl"
option.)
- Leonel Togniolli for various suggestions with regard to enhancing the bug
tracking features of FastMM and other helpful advice.
- Joe Bain and Leonel Togniolli for the workaround to QC#10922 affecting
compilation under Delphi 2005.
- Robert Marquardt for the suggestion to make localisation of FastMM easier by
having all string constants together.
- Simon Kissel and Fikret Hasovic for their help in implementing Kylix support.
- Matthias Thoma, Petr Vones, Robert Rossmair and the rest of the JCL team for
their debug info library used in the debug info support DLL and also the
code used to check for a valid call site in the "raw" stack trace code.
- Andreas Hausladen for the suggestion to use an external DLL to enable the
reporting of debug information.
- Alexander Tabakov for various good suggestions regarding the debugging
facilities of FastMM.
- M. Skloff for some useful suggestions and bringing to my attention some
compiler warnings.
- Martin Aignesberger for the code to use madExcept instead of the JCL library
inside the debug info support DLL.
- Diederik and Dennis Passmore for the suggestion to be able to register
expected leaks.
- Dario Tiraboschi and Mark Gebauer for pointing out the problems that occur
when range checking and complete boolean evaluation is turned on.
- Arthur Hoornweg for notifying me of the image base being incorrect for
borlndmm.dll.
- Theo Carr-Brion and Hanspeter Widmer for finding the false alarm error
message "Block Header Has Been Corrupted" bug in FullDebugMode.
- Danny Heijl for reporting the compiler error in "release" mode.
- Omar Zelaya for reporting the BCB support regression bug.
- Dan Miser for various good suggestions, e.g. not logging expected leaks to
file, enhancements the stack trace and messagebox functionality, etc.
- Arjen de Ruijter for fixing the bug in GetMemoryLeakType that caused it
to not properly detect expected leaks registered by class when in
"FullDebugMode".
- Aleksander Oven for reporting the installation problem when trying to use
FastMM in an application together with libraries that all use runtime
packages.
- Kristofer Skaug for reporting the bug that sometimes causes the leak report
to be shown, even when all the leaks have been registered as expected leaks.
Also for some useful enhancement suggestions.
- Günther Schoch for the "RequireDebuggerPresenceForLeakReporting" option.
- Jan Schlüter for the "ForceMMX" option.
- Hallvard Vassbotn for various good enhancement suggestions.
- Mark Edington for some good suggestions and bug reports.
- Paul Ishenin for reporting the compilation error when the NoMessageBoxes
option is set and also the missing call stack entries issue when "raw" stack
traces are enabled, as well as for the Russian translation.
- Cristian Nicola for reporting the compilation bug when the
CatchUseOfFreedInterfaces option was enabled (4.40).
- Mathias Rauen (madshi) for improving the support for madExcept in the debug
info support DLL.
- Roddy Pratt for the BCB5 support code.
- Rene Mihula for the Czech translation and the suggestion to have dynamic
loading of the FullDebugMode DLL as an option.
- Artur Redzko for the Polish translation.
- Bart van der Werf for helping me solve the DLL unload order problem when
using the debug mode borlndmm.dll library, as well as various other
suggestions.
- JRG ("The Delphi Guy") for the Spanish translation.
- Justus Janssen for Delphi 4 support.
- Vadim Lopushansky and Charles Vinal for reporting the Delphi 5 compiler
error in version 4.50.
- Johni Jeferson Capeletto for the Brazilian Portuguese translation.
- Kurt Fitzner for reporting the BCB6 compiler error in 4.52.
- Michal Niklas for reporting the Kylix compiler error in 4.54.
- Thomas Speck and Uwe Queisser for German translations.
- Zaenal Mutaqin for the Indonesian translation.
- Carlos Macao for the Portuguese translation.
- Michael Winter for catching the performance issue when reallocating certain
block sizes.
- dzmitry[li] for the Belarussian translation.
- Marcelo Montenegro for the updated Spanish translation.
- Jud Cole for finding and reporting the bug which may trigger a read access
violation when upsizing certain small block sizes together with the
"UseCustomVariableSizeMoveRoutines" option.
- Zdenek Vasku for reporting and fixing the memory manager sharing bug
affecting Windows 95/98/Me.
- RB Winston for suggesting the improvement to GExperts "backup" support.
- Thomas Schulz for reporting the bug affecting large address space support
under FullDebugMode, as well as the recursive call bug when attempting to
report memory leaks when EnableMemoryLeakReporting is disabled.
- Luigi Sandon for the Italian translation.
- Werner Bochtler for various suggestions and bug reports.
- Markus Beth for suggesting the "NeverSleepOnThreadContention" option.
- JiYuan Xie for the Simplified Chinese translation.
- Andrey Shtukaturov for the updated Russian translation, as well as the
Ukrainian translation.
- Dimitry Timokhov for finding two elusive bugs in the memory leak class
detection code.
- Paulo Moreno for fixing the AllocMem bug in FullDebugMode that prevented
large blocks from being cleared.
- Vladimir Bochkarev for the suggestion to remove some unnecessary code if the
MM sharing mechanism is disabled.
- Loris Luise for the version constant suggestion.
- J.W. de Bokx for the MessageBox bugfix.
- Igor Lindunen for reporting the bug that caused the Align16Bytes option to
not work in FullDebugMode.
- Ionut Muntean for the Romanian translation.
- Florent Ouchet for the French translation.
- Marcus Mönnig for the ScanMemoryPoolForCorruptions suggestion and the
suggestion to have the option to scan the memory pool before every
operation when in FullDebugMode.
- Francois Piette for bringing under my attention that
ScanMemoryPoolForCorruption was not thread safe.
- Michael Rabatscher for reporting some compiler warnings.
- QianYuan Wang for the Simplified Chinese translation of FastMM4Options.inc.
- Maurizio Lotauro and Christian-W. Budde for reporting some Delphi 5
compiler errors.
- Patrick van Logchem for the DisableLoggingOfMemoryDumps option.
- Norbert Spiegel for the BCB4 support code.
- Uwe Schuster for the improved string leak detection code.
- Murray McGowan for improvements to the usage tracker.
- Michael Hieke for the SuppressFreeMemErrorsInsideException option as well
as a bugfix to GetMemoryMap.
- Richard Bradbrook for fixing the Windows 95 FullDebugMode support that was
broken in version 4.94.
- Zach Saw for the suggestion to (optionally) use SwitchToThread when
waiting for a lock on a shared resource to be released.
- Everyone who have made donations. Thanks!
- Any other Fastcoders or supporters that I have forgotten, and also everyone
that helped with the older versions.
Change log:
Version 1.00 (28 June 2004):
- First version (called PSDMemoryManager). Based on RecyclerMM (free block
stack approach) by Eric Grange.
Version 2.00 (3 November 2004):
- Complete redesign and rewrite from scratch. Name changed to FastMM to
reflect this fact. Uses a linked-list approach. Is faster, has less memory
overhead, and will now catch most bad pointers on FreeMem calls.
Version 3.00 (1 March 2005):
- Another rewrite. Reduced the memory overhead by: (a) not having a separate
memory area for the linked list of free blocks (uses space inside free
blocks themselves) (b) batch managers are allocated as part of chunks (c)
block size lookup table size reduced. This should make FastMM more CPU
cache friendly.
Version 4.00 (7 June 2005):
- Yet another rewrite. FastMM4 is in fact three memory managers in one: Small
blocks (up to a few KB) are managed through the binning model in the same
way as previous versions, medium blocks (from a few KB up to approximately
256K) are allocated in a linked-list fashion, and large blocks are grabbed
directly from the system through VirtualAlloc. This 3-layered design allows
very fast operation with the most frequently used block sizes (small
blocks), while also minimizing fragmentation and imparting significant
overhead savings with blocks larger than a few KB.
Version 4.01 (8 June 2005):
- Added the options "RequireDebugInfoForLeakReporting" and
"RequireIDEPresenceForLeakReporting" as suggested by Pierre Y.
- Fixed the "DelphiIsRunning" function not working under Delphi 5, and
consequently no leak checking. (Reported by Anders Isaksson and Greg.)
Version 4.02 (8 June 2005):
- Fixed the compilation error when both the "AssumeMultiThreaded" and
"CheckHeapForCorruption options were set. (Reported by Francois Malan.)
Version 4.03 (9 June 2005):
- Added descriptive error messages when FastMM4 cannot be installed because
another MM has already been installed or memory has already been allocated.
Version 4.04 (13 June 2005):
- Added a small fixed offset to the size of medium blocks (previously always
exact multiples of 256 bytes). This makes performance problems due to CPU
cache associativity limitations much less likely. (Reported by Craig
Peterson.)
Version 4.05 (17 June 2005):
- Added the Align16Bytes option. Disable this option to drop the 16 byte
alignment restriction and reduce alignment to 8 bytes for the smallest
block sizes. Disabling Align16Bytes should lower memory consumption at the
cost of complicating the use of aligned SSE move instructions. (Suggested
by Craig Peterson.)
- Added a support unit for C++ Builder 6 - Add FastMM4BCB.cpp and
FastMM4.pas to your BCB project to use FastMM instead of the RTL MM. Memory
leak checking is not supported because (unfortunately) once an MM is
installed under BCB you cannot uninstall it... at least not without
modifying the RTL code in exit.c or patching the RTL code runtime. (Thanks
to Jarek Karciarz, Vladimir Ulchenko and Bob Gonder.)
Version 4.06 (22 June 2005):
- Displays the class of all leaked objects on the memory leak report and also
tries to identify leaked long strings. Previously it only displayed the
sizes of all leaked blocks. (Suggested by Ben Taylor.)
- Added support for displaying the sizes of medium and large block memory
leaks. Previously it only displayed details for small block leaks.
Version 4.07 (22 June 2005):
- Fixed the detection of the class of leaked objects not working under
Windows 98/Me.
Version 4.08 (27 June 2005):
- Added a BorlndMM.dpr project to allow you to build a borlndmm.dll that uses
FastMM4 instead of the default memory manager. You may replace the old
DLL in the Delphi \Bin directory to make the IDE use this memory manager
instead.
Version 4.09 (30 June 2005):
- Included a patch fix for the bug affecting replacement borlndmm.dll files
with Delphi 2005 (QC#14007). Compile the patch, close Delphi, and run it
once to patch your vclide90.bpl. You will now be able to use the
replacement borlndmm.dll to speed up the Delphi 2005 IDE as well.
Version 4.10 (7 July 2005):
- Due to QC#14070 ("Delphi IDE attempts to free memory after the shutdown
code of borlndmm.dll has been called"), FastMM cannot be uninstalled
safely when used inside a replacement borlndmm.dll for the IDE. Added a
conditional define "NeverUninstall" for this purpose.
- Added the "FullDebugMode" option to pad all blocks with a header and footer
to help you catch memory overwrite bugs in your applications. All blocks
returned to freemem are also zeroed out to help catch bugs involving the
use of previously freed blocks. Also catches attempts at calling virtual
methods of freed objects provided the block in question has not been reused
since the object was freed. Displays stack traces on error to aid debugging.
- Added the "LogErrorsToFile" option to log all errors to a text file in the
same folder as the application.
- Added the "ManualLeakReportingControl" option (suggested by Nahan Hyn) to
enable control over whether the memory leak report should be done or not
via a global variable.
Version 4.11 (7 July 2005):
- Fixed a compilation error under Delphi 2005 due to QC#10922. (Thanks to Joe
Bain and Leonel Togniolli.)
- Fixed leaked object classes not displaying in the leak report in
"FullDebugMode".
Version 4.12 (8 July 2005):
- Moved all the string constants to one place to make it easier to do
translations into other languages. (Thanks to Robert Marquardt.)
- Added support for Kylix. Some functionality is currently missing: No
support for detecting the object class on leaks and also no MM sharing.
(Thanks to Simon Kissel and Fikret Hasovic).
Version 4.13 (11 July 2005):
- Added the FastMM_DebugInfo.dll support library to display debug info for
stack traces.
- Stack traces for the memory leak report is now logged to the log file in
"FullDebugMode".
Version 4.14 (14 July 2005):
- Fixed string leaks not being detected as such in "FullDebugMode". (Thanks
to Leonel Togniolli.)
- Fixed the compilation error in "FullDebugMode" when "LogErrorsToFile" is
not set. (Thanks to Leonel Togniolli.)
- Added a "Release" option to allow the grouping of various options and to
make it easier to make debug and release builds. (Thanks to Alexander
Tabakov.)
- Added a "HideMemoryLeakHintMessage" option to not display the hint below
the memory leak message. (Thanks to Alexander Tabakov.)
- Changed the fill character for "FullDebugMode" from zero to $80 to be able
to differentiate between invalid memory accesses using nil pointers to
invalid memory accesses using fields of freed objects. FastMM tries to
reserve the 64K block starting at $80800000 at startup to ensure that an
A/V will occur when this block is accessed. (Thanks to Alexander Tabakov.)
- Fixed some compiler warnings. (Thanks to M. Skloff)
- Fixed some display bugs in the memory leak report. (Thanks to Leonel
Togniolli.)
- Added a "LogMemoryLeakDetailToFile" option. Some applications leak a lot of
memory and can make the log file grow very large very quickly.
- Added the option to use madExcept instead of the JCL Debug library in the
debug info support DLL. (Thanks to Martin Aignesberger.)
- Added procedures "GetMemoryManagerState" and "GetMemoryMap" to retrieve
statistics about the current state of the memory manager and memory pool.
(A usage tracker form together with a demo is also available.)
Version 4.15 (14 July 2005):
- Fixed a false 4GB(!) memory leak reported in some instances.
Version 4.16 (15 July 2005):
- Added the "CatchUseOfFreedInterfaces" option to catch the use of interfaces
of freed objects. This option is not compatible with checking that a freed
block has not been modified, so enable this option only when hunting an
invalid interface reference. (Only relevant if "FullDebugMode" is set.)
- During shutdown FastMM now checks that all free blocks have not been
modified since being freed. (Only when "FullDebugMode" is set and
"CatchUseOfFreedInterfaces" is disabled.)
Version 4.17 (15 July 2005):
- Added the AddExpectedMemoryLeaks and RemoveExpectedMemoryLeaks procedures to
register/unregister expected leaks, thus preventing the leak report from
displaying if only expected leaks occurred. (Thanks to Diederik and Dennis
Passmore for the suggestion.) (Note: these functions were renamed in later
versions.)
- Fixed the "LogMemoryLeakDetailToFile" not logging memory leak detail to file
as it is supposed to. (Thanks to Leonel Togniolli.)
Version 4.18 (18 July 2005):
- Fixed some issues when range checking or complete boolean evaluation is
switched on. (Thanks to Dario Tiraboschi and Mark Gebauer.)
- Added the "OutputInstallUninstallDebugString" option to display a message when
FastMM is installed or uninstalled. (Thanks to Hanspeter Widmer.)
- Moved the options to a separate include file. (Thanks to Hanspeter Widmer.)
- Moved message strings to a separate file for easy translation.
Version 4.19 (19 July 2005):
- Fixed Kylix support that was broken in 4.14.
Version 4.20 (20 July 2005):
- Fixed a false memory overwrite report at shutdown in "FullDebugMode". If you
consistently got a "Block Header Has Been Corrupted" error message during
shutdown at address $xxxx0070 then it was probably a false alarm. (Thanks to
Theo Carr-Brion and Hanspeter Widmer.}
Version 4.21 (27 July 2005):
- Minor change to the block header flags to make it possible to immediately
tell whether a medium block is being used as a small block pool or not.
(Simplifies the leak checking and status reporting code.)
- Expanded the functionality around the management of expected memory leaks.
- Added the "ClearLogFileOnStartup" option. Deletes the log file during
initialization. (Thanks to M. Skloff.)
- Changed "OutputInstallUninstallDebugString" to use OutputDebugString instead
of MessageBox. (Thanks to Hanspeter Widmer.)
Version 4.22 (1 August 2005):
- Added a FastAllocMem function that avoids an unnecessary FillChar call with
large blocks.
- Changed large block resizing behavior to be a bit more conservative. Large
blocks will be downsized if the new size is less than half of the old size
(the threshold was a quarter previously).
Version 4.23 (6 August 2005):
- Fixed BCB6 support (Thanks to Omar Zelaya).
- Renamed "OutputInstallUninstallDebugString" to "UseOutputDebugString", and
added debug string output on memory leak or error detection.
Version 4.24 (11 August 2005):
- Added the "NoMessageBoxes" option to suppress the display of message boxes,
which is useful for services that should not be interrupted. (Thanks to Dan
Miser).
- Changed the stack trace code to return the line number of the caller and not
the line number of the return address. (Thanks to Dan Miser).
Version 4.25 (15 August 2005):
- Fixed GetMemoryLeakType not detecting expected leaks registered by class
when in "FullDebugMode". (Thanks to Arjen de Ruijter).
Version 4.26 (18 August 2005):
- Added a "UseRuntimePackages" option that allows FastMM to be used in a main
application together with DLLs that all use runtime packages. (Thanks to
Aleksander Oven.)
Version 4.27 (24 August 2005):
- Fixed a bug that sometimes caused the leak report to be shown even though all
leaks were registered as expected leaks. (Thanks to Kristofer Skaug.)
Version 4.29 (30 September 2005):
- Added the "RequireDebuggerPresenceForLeakReporting" option to only display
the leak report if the application is run inside the IDE. (Thanks to Günther
Schoch.)
- Added the "ForceMMX" option, which when disabled will check the CPU for
MMX compatibility before using MMX. (Thanks to Jan Schlüter.)
- Added the module name to the title of error dialogs to more easily identify
which application caused the error. (Thanks to Kristofer Skaug.)
- Added an ASCII dump to the "FullDebugMode" memory dumps. (Thanks to Hallvard
Vassbotn.)
- Added the option "HideExpectedLeaksRegisteredByPointer" to suppress the
display and logging of expected memory leaks that were registered by pointer.
(Thanks to Dan Miser.) Leaks registered by size or class are often ambiguous,
so these expected leaks are always logged to file (in FullDebugMode) and are
never hidden from the leak display (only displayed if there is at least one
unexpected leak).
- Added a procedure "GetRegisteredMemoryLeaks" to return a list of all
registered memory leaks. (Thanks to Dan Miser.)
- Added the "RawStackTraces" option to perform "raw" stack traces, negating
the need for stack frames. This will usually result in more complete stack
traces in FullDebugMode error reports, but it is significantly slower.
(Thanks to Hallvard Vassbotn, Dan Miser and the JCL team.)
Version 4.31 (2 October 2005):
- Fixed the crash bug when both "RawStackTraces" and "FullDebugMode" were
enabled. (Thanks to Dan Miser and Mark Edington.)
Version 4.33 (6 October 2005):
- Added a header corruption check to all memory blocks that are identified as
leaks in FullDebugMode. This allows better differentiation between memory
pool corruption bugs and actual memory leaks.
- Fixed the stack overflow bug when using "RawStackTraces".
Version 4.35 (6 October 2005):
- Fixed a compilation error when the "NoMessageBoxes" option is set. (Thanks
to Paul Ishenin.)
- Before performing a "raw" stack trace, FastMM now checks whether exception
handling is in place. If exception handling is not in place FastMM falls
back to stack frame tracing. (Exception handling is required to handle the
possible A/Vs when reading invalid call addresses. Exception handling is
usually always available except when SysUtils hasn't been initialized yet or
after SysUtils has been finalized.)
Version 4.37 (8 October 2005):
- Fixed the missing call stack trace entry issue when dynamically loading DLLs.
(Thanks to Paul Ishenin.)
Version 4.39 (12 October 2005):
- Restored the performance with "RawStackTraces" enabled back to the level it
was in 4.35.
- Fixed the stack overflow error when using "RawStackTraces" that I thought I
had fixed in 4.31, but unfortunately didn't. (Thanks to Craig Peterson.)
Version 4.40 (13 October 2005):
- Improved "RawStackTraces" to have less incorrect extra entries. (Thanks to
Craig Peterson.)
- Added the Russian (by Paul Ishenin) and Afrikaans translations of
FastMM4Messages.pas.
Version 4.42 (13 October 2005):
- Fixed the compilation error when "CatchUseOfFreedInterfaces" is enabled.
(Thanks to Cristian Nicola.)
Version 4.44 (25 October 2005):
- Implemented a FastGetHeapStatus function in analogy with GetHeapStatus.
(Suggested by Cristian Nicola.)
- Shifted more of the stack trace code over to the support dll to allow third
party vendors to make available their own stack tracing and stack trace
logging facilities.
- Mathias Rauen (madshi) improved the support for madExcept in the debug info
support DLL. Thanks!
- Added support for BCB5. (Thanks to Roddy Pratt.)
- Added the Czech translation by Rene Mihula.
- Added the "DetectMMOperationsAfterUninstall" option. This will catch
attempts to use the MM after FastMM has been uninstalled, and is useful for
debugging.
Version 4.46 (26 October 2005):
- Renamed FastMM_DebugInfo.dll to FastMM_FullDebugMode.dll and made the
dependency on this library a static one. This solves a DLL unload order
problem when using FullDebugMode together with the replacement
borlndmm.dll. (Thanks to Bart van der Werf.)
- Added the Polish translation by Artur Redzko.
Version 4.48 (10 November 2005):
- Fixed class detection for objects leaked in dynamically loaded DLLs that
were relocated.
- Fabio Dell'Aria implemented support for EurekaLog in the FullDebugMode
support DLL. Thanks!
- Added the Spanish translation by JRG ("The Delphi Guy").
Version 4.49 (10 November 2005):
- Implemented support for installing replacement AllocMem and leak
registration mechanisms for Delphi/BCB versions that support it.
- Added support for Delphi 4. (Thanks to Justus Janssen.)
Version 4.50 (5 December 2005):
- Renamed the ReportMemoryLeaks global variable to ReportMemoryLeaksOnShutdown
to be more consistent with the Delphi 2006 memory manager.
- Improved the handling of large blocks. Large blocks can now consist of
several consecutive segments allocated through VirtualAlloc. This
significantly improves speed when frequently resizing large blocks, since
these blocks can now often be upsized in-place.
Version 4.52 (7 December 2005):
- Fixed the compilation error with Delphi 5. (Thanks to Vadim Lopushansky and
Charles Vinal for reporting the error.)
Version 4.54 (15 December 2005):
- Added the Brazilian Portuguese translation by Johni Jeferson Capeletto.
- Fixed the compilation error with BCB6. (Thanks to Kurt Fitzner.)
Version 4.56 (20 December 2005):
- Fixed the Kylix compilation problem. (Thanks to Michal Niklas.)
Version 4.58 (1 February 2006):
- Added the German translations by Thomas Speck and Uwe Queisser.
- Added the Indonesian translation by Zaenal Mutaqin.
- Added the Portuguese translation by Carlos Macao.
Version 4.60 (21 February 2006):
- Fixed a performance issue due to an unnecessary block move operation when
allocating a block in the range 1261-1372 bytes and then reallocating it in
the range 1373-1429 bytes twice. (Thanks to Michael Winter.)
- Added the Belarussian translation by dzmitry[li].
- Added the updated Spanish translation by Marcelo Montenegro.
- Added a new option "EnableSharingWithDefaultMM". This option allows FastMM
to be shared with the default MM of Delphi 2006. It is on by default, but
MM sharing has to be enabled otherwise it has no effect (refer to the
documentation for the "ShareMM" and "AttemptToUseSharedMM" options).
Version 4.62 (22 February 2006):
- Fixed a possible read access violation in the MoveX16LP routine when the
UseCustomVariableSizeMoveRoutines option is enabled. (Thanks to Jud Cole for
some great detective work in finding this bug.)
- Improved the downsizing behaviour of medium blocks to better correlate with
the reallocation behaviour of small blocks. This change reduces the number
of transitions between small and medium block types when reallocating blocks
in the 0.7K to 2.6K range. It cuts down on the number of memory move
operations and improves performance.
Version 4.64 (31 March 2006):
- Added the following functions for use with FullDebugMode (and added the
exports to the replacement BorlndMM.dll): SetMMLogFileName,
GetCurrentAllocationGroup, PushAllocationGroup, PopAllocationGroup and
LogAllocatedBlocksToFile. The purpose of these functions are to allow you to
identify and log related memory leaks while your application is still
running.
- Fixed a bug in the memory manager sharing mechanism affecting Windows
95/98/ME. (Thanks to Zdenek Vasku.)
Version 4.66 (9 May 2006):
- Added a hint comment in this file so that FastMM4Messages.pas will also be
backed up by GExperts. (Thanks to RB Winston.)
- Fixed a bug affecting large address space (> 2GB) support under
FullDebugMode. (Thanks to Thomas Schulz.)
Version 4.68 (3 July 2006):
- Added the Italian translation by Luigi Sandon.
- If FastMM is used inside a DLL it will now use the name of the DLL as base
for the log file name. (Previously it always used the name of the main
application executable file.)
- Fixed a rare A/V when both the FullDebugMode and RawStackTraces options were
enabled. (Thanks to Primoz Gabrijelcic.)
- Added the "NeverSleepOnThreadContention" option. This option may improve
performance if the ratio of the the number of active threads to the number
of CPU cores is low (typically < 2). This option is only useful for 4+ CPU
systems, it almost always hurts performance on single and dual CPU systems.
(Thanks to Werner Bochtler and Markus Beth.)
Version 4.70 (4 August 2006):
- Added the Simplified Chinese translation by JiYuan Xie.
- Added the updated Russian as well as the Ukrainian translation by Andrey
Shtukaturov.
- Fixed two bugs in the leak class detection code that would sometimes fail
to detect the class of leaked objects and strings, and report them as
'unknown'. (Thanks to Dimitry Timokhov)
Version 4.72 (24 September 2006):
- Fixed a bug that caused AllocMem to not clear blocks > 256K in
FullDebugMode. (Thanks to Paulo Moreno.)
Version 4.74 (9 November 2006):
- Fixed a bug in the segmented large block functionality that could lead to
an application freeze when upsizing blocks greater than 256K in a
multithreaded application (one of those "what the heck was I thinking?"
type bugs).
Version 4.76 (12 January 2007):
- Changed the RawStackTraces code in the FullDebugMode DLL
to prevent it from modifying the Windows "GetLastError" error code.
(Thanks to Primoz Gabrijelcic.)
- Fixed a threading issue when the "CheckHeapForCorruption" option was
enabled, but the "FullDebugMode" option was disabled. (Thanks to Primoz
Gabrijelcic.)
- Removed some unnecessary startup code when the MM sharing mechanism is
disabled. (Thanks to Vladimir Bochkarev.)
- In FullDebugMode leaked blocks would sometimes be reported as belonging to
the class "TFreedObject" if they were allocated but never used. Such blocks
will now be reported as "unknown". (Thanks to Francois Malan.)
- In recent versions the replacement borlndmm.dll created a log file (when
enabled) that used the "borlndmm" prefix instead of the application name.
It is now fixed to use the application name, however if FastMM is used
inside other DLLs the name of those DLLs will be used. (Thanks to Bart van
der Werf.)
- Added a "FastMMVersion" constant. (Suggested by Loris Luise.)
- Fixed an issue with error message boxes not displaying under certain
configurations. (Thanks to J.W. de Bokx.)
- FastMM will now display only one error message at a time. If many errors
occur in quick succession, only the first error will be shown (but all will
be logged). This avoids a stack overflow with badly misbehaved programs.
(Thanks to Bart van der Werf.)
- Added a LoadDebugDLLDynamically option to be used in conjunction with
FullDebugMode. In this mode FastMM_FullDebugMode.dll is loaded dynamically.
If the DLL cannot be found, stack traces will not be available. (Thanks to
Rene Mihula.)
Version 4.78 (1 March 2007):
- The MB_DEFAULT_DESKTOP_ONLY constant that is used when displaying messages
boxes since 4.76 is not defined under Kylix, and the source would thus not
compile. That constant is now defined. (Thanks to Werner Bochtler.)
- Moved the medium block locking code that was duplicated in several places
to a subroutine to reduce code size. (Thanks to Hallvard Vassbotn.)
- Fixed a bug in the leak registration code that sometimes caused registered
leaks to be reported erroneously. (Thanks to Primoz Gabrijelcic.)
- Added the NoDebugInfo option (on by default) that suppresses the generation
of debug info for the FastMM4.pas unit. This will prevent the integrated
debugger from stepping into the memory manager. (Thanks to Primoz
Gabrijelcic.)
- Increased the default stack trace depth in FullDebugMode from 9 to 10 to
ensure that the Align16Bytes setting works in FullDebugMode. (Thanks to
Igor Lindunen.)
- Updated the Czech translation. (Thanks to Rene Mihula.)
Version 4.84 (7 July 2008):
- Added the Romanian translation. (Thanks to Ionut Muntean.)
- Optimized the GetMemoryMap procedure to improve speed.
- Added the GetMemoryManagerUsageSummary function that returns a summary of
the GetMemoryManagerState call. (Thanks to Hallvard Vassbotn.)
- Added the French translation. (Thanks to Florent Ouchet.)
- Added the "AlwaysAllocateTopDown" FullDebugMode option to help with
catching bad pointer arithmetic code in an address space > 2GB. This option
is enabled by default.
- Added the "InstallOnlyIfRunningInIDE" option. Enable this option to
only install FastMM as the memory manager when the application is run
inside the Delphi IDE. This is useful when you want to deploy the same EXE
that you use for testing, but only want the debugging features active on
development machines. When this option is enabled and the application is
not being run inside the IDE, then the default Delphi memory manager will
be used (which, since Delphi 2006, is FastMM without FullDebugMode.) This
option is off by default.
- Added the "FullDebugModeInIDE" option. This is a convenient shorthand for
enabling FullDebugMode, InstallOnlyIfRunningInIDE and
LoadDebugDLLDynamically. This causes FastMM to be used in FullDebugMode
when the application is being debugged on development machines, and the
default memory manager when the same executable is deployed. This allows
the debugging and deployment of an application without having to compile
separate executables. This option is off by default.
- Added a ScanMemoryPoolForCorruptions procedure that checks the entire
memory pool for corruptions and raises an exception if one is found. It can
be called at any time, but is only available in FullDebugMode. (Thanks to
Marcus Mönnig.)
- Added a global variable "FullDebugModeScanMemoryPoolBeforeEveryOperation".
When this variable is set to true and FullDebugMode is enabled, then the
entire memory pool is checked for consistency before every GetMem, FreeMem
and ReallocMem operation. An "Out of Memory" error is raised if a
corruption is found (and this variable is set to false to prevent recursive
errors). This obviously incurs a massive performance hit, so enable it only
when hunting for elusive memory corruption bugs. (Thanks to Marcus Mönnig.)
- Fixed a bug in AllocMem that caused the FPU stack to be shifted by one
position.
- Changed the default for option "EnableMMX" to false, since using MMX may
cause unexpected behaviour in code that passes parameters on the FPU stack
(like some "compiler magic" routines, e.g. VarFromReal).
- Removed the "EnableSharingWithDefaultMM" option. This is now the default
behaviour and cannot be disabled. (FastMM will always try to share memory
managers between itself and the default memory manager when memory manager
sharing is enabled.)
- Introduced a new memory manager sharing mechanism based on memory mapped
files. This solves compatibility issues with console and service
applications. This sharing mechanism currently runs in parallel with the
old mechanism, but the old mechanism can be disabled by undefining
"EnableBackwardCompatibleMMSharing" in FastMM4Options.inc.
- Fixed the recursive call error when the EnableMemoryLeakReporting option
is disabled and an attempt is made to register a memory leak under Delphi
2006 or later. (Thanks to Thomas Schulz.)
- Added a global variable "SuppressMessageBoxes" to enable or disable
messageboxes at runtime. (Thanks to Craig Peterson.)
- Added the leak reporting code for C++ Builder, as well as various other
C++ Builder bits written by JiYuan Xie. (Thank you!)
- Added the new Usage Tracker written by Hanspeter Widmer. (Thank you!)
Version 4.86 (31 July 2008):
- Tweaked the string detection algorithm somewhat to be less strict, and
allow non-class leaks to be more often categorized as strings.
- Fixed a compilation error under Delphi 5.
- Made LogAllocatedBlocksToFile and ScanMemoryPoolForCorruptions thread
safe. (Thanks to Francois Piette.)
Version 4.88 (13 August 2008):
- Fixed compiler warnings in NoOpRegisterExpectedMemoryLeak and
NoOpUnRegisterExpectedMemoryLeak. (Thanks to Michael Rabatscher.)
- Added the Simplified Chinese translation of FastMM4Options.inc by
QianYuan Wang. (Thank you!)
- Included the updated C++ Builder files with support for BCB6 without
update 4 applied. (Submitted by JiYuan Xie. Thanks!)
- Fixed a compilation error under Delphi 5.
- Made LogAllocatedBlocksToFile and ScanMemoryPoolForCorruptions thread
safe - for real this time. (Thanks to Francois Piette.)
Version 4.90 (9 September 2008):
- Added logging of the thread ID when capturing and displaying stack
traces. (Suggested by Allen Bauer and Mark Edington.)
- Fixed a Delphi 5 compiler error under FullDebugMode. (Thanks to Maurizio
Lotauro and Christian-W. Budde.)
- Changed a default setting in FastMM4Options.inc: RawStackTraces is now
off by default due to the high number of support requests I receive with
regards to the false postives it may cause. I recommend compiling debug
builds of applications with the "Stack Frames" option enabled.
- Fixed a compilation error under Kylix. (Thanks to Werner Bochtler.)
- Official support for Delphi 2009.
Version 4.92 (25 November 2008):
- Added the DisableLoggingOfMemoryDumps option under FullDebugMode. When
this option is set, memory dumps will not be logged for memory leaks or
errors. (Thanks to Patrick van Logchem.)
- Exposed the class and string type detection code in the interface section
for use in application code (if required). (Requested by Patrick van
Logchem.)
- Fixed a bug in SetMMLogFileName that could cause the log file name to be
set incorrectly.
- Added BCB4 support. (Thanks to Norbert Spiegel.)
- Included the updated Czech translation by Rene Mihula.
- When FastMM raises an error due to a freed block being modified, it now
logs detail about which bytes in the block were modified.
Version 4.94 (28 August 2009):
- Added the DoNotInstallIfDLLMissing option that prevents FastMM from
installing itself if the FastMM_FullDebugMode.dll library is not
available. (Only applicable when FullDebugMode and LoadDebugDLLDynamically
are both enabled.) This is useful when the same executable will be used for
both debugging and deployment - when the debug support DLL is available
FastMM will be installed in FullDebugMode, and otherwise the default memory
manager will be used.
- Added the FullDebugModeWhenDLLAvailable option that combines the
FullDebugMode, LoadDebugDLLDynamically and DoNotInstallIfDLLMissing options.
- Re-enabled RawStackTraces by default. The frame based stack traces (even
when compiling with stack frames enabled) are generally too incomplete.
- Improved the speed of large block operations under FullDebugMode: Since
large blocks are never reused, there is no point in clearing them before
and after use (so it does not do that anymore).
- If an error occurs in FullDebugMode and FastMM is unable to append to the
log file, it will attempt to write to a log file of the same name in the
"My Documents" folder. This feature is helpful when the executable resides
in a read-only location and the default log file, which is derived from the
executable name, would thus not be writeable.
- Added support for controlling the error log file location through an
environment variable. If the 'FastMMLogFilePath' environment variable is
set then any generated error logs will be written to the specified folder
instead of the default location (which is the same folder as the
application).
- Improved the call instruction detection code in the FastMM_FullDebugMode
library. (Thanks to the JCL team.)
- Improved the string leak detection and reporting code. (Thanks to Uwe
Schuster.)
- New FullDebugMode feature: Whenever FreeMem or ReallocMem is called, FastMM
will check that the block was actually allocated through the same FastMM
instance. This is useful for tracking down memory manager sharing issues.
- Compatible with Delphi 2010.
Version 4.96 (31 August 2010):
- Reduced the minimum block size to 4 bytes from the previous value of 12
bytes (only applicable to 8 byte alignment). This reduces memory usage if
the application allocates many blocks <= 4 bytes in size.
- Added colour-coded change indication to the FastMM usage tracker, making
it easier to spot changes in the memory usage grid. (Thanks to Murray
McGowan.)
- Added the SuppressFreeMemErrorsInsideException FullDebugMode option: If
FastMM encounters a problem with a memory block inside the FullDebugMode
FreeMem handler then an "invalid pointer operation" exception will usually
be raised. If the FreeMem occurs while another exception is being handled
(perhaps in the try.. finally code) then the original exception will be
lost. With this option set FastMM will ignore errors inside FreeMem when an
exception is being handled, thus allowing the original exception to
propagate. This option is on by default. (Thanks to Michael Hieke.)
- Fixed Windows 95 FullDebugMode support that was broken in 4.94. (Thanks to
Richard Bradbrook.)
- Fixed a bug affecting GetMemoryMap performance and accuracy of measurements
above 2GB if a large address space is not enabled for the project. (Thanks
to Michael Hieke.)
- Added the FullDebugModeRegisterAllAllocsAsExpectedMemoryLeak boolean flag.
When set, all allocations are automatically registered as expected memory
leaks. Only available in FullDebugMode. (Thanks to Brian Cook.)
- Compatible with Delphi XE.
Version 4.97 (30 September 2010):
- Fixed a crash bug (that crept in in 4.96) that may manifest itself when
resizing a block to 4 bytes or less.
- Added the UseSwitchToThread option. Set this option to call SwitchToThread
instead of sitting in a "busy waiting" loop when a thread contention
occurs. This is used in conjunction with the NeverSleepOnThreadContention
option, and has no effect unless NeverSleepOnThreadContention is also
defined. This option may improve performance with many CPU cores and/or
threads of different priorities. Note that the SwitchToThread API call is
only available on Windows 2000 and later. (Thanks to Zach Saw.)
Version 4.98 (23 September 2011):
- Added the FullDebugModeCallBacks define which adds support for memory
manager event callbacks. This allows the application to be notified of
memory allocations, frees and reallocations as they occur. (Thanks to
Jeroen Pluimers.)
- Added security options ClearMemoryBeforeReturningToOS and
AlwaysClearFreedMemory to force the clearing of memory blocks after being
freed. This could possibly provide some protection against information
theft, but at a significant performance penalty. (Thanks to Andrey
Sozonov.)
- Shifted the code in the initialization section to a procedure
RunInitializationCode. This allows the startup code to be called before
InitUnits, which is required by some software protection tools.
- Added support for Delphi XE2 (Windows 32-bit and Windows 64-bit platforms
only).
Version 4.99 (6 November 2011):
- Fixed crashes in the 64-bit BASM codepath when more than 4GB of memory is
allocated.
- Fixed bad record alignment under 64-bit that affected performance.
- Fixed compilation errors with some older compilers.
Version 4.991 (3 September 2012)
- Added the LogMemoryManagerStateToFile call. This call logs a summary of
the memory manager state to file: The total allocated memory, overhead,
efficiency, and a breakdown of allocated memory by class and string type.
This call may be useful to catch objects that do not necessarily leak, but
do linger longer than they should.
- OS X support added by Sebastian Zierer
- Compatible with Delphi XE3
*)
unit FastMM4;
interface
{$Include FastMM4Options.inc}
{$RANGECHECKS OFF}
{$BOOLEVAL OFF}
{$OVERFLOWCHECKS OFF}
{$OPTIMIZATION ON}
{$TYPEDADDRESS OFF}
{$LONGSTRINGS ON}
{Compiler version defines}
{$ifndef BCB}
{$ifdef ver120}
{$define Delphi4or5}
{$endif}
{$ifdef ver130}
{$define Delphi4or5}
{$endif}
{$ifdef ver140}
{$define Delphi6}
{$endif}
{$ifdef ver150}
{$define Delphi7}
{$endif}
{$ifdef ver170}
{$define Delphi2005}
{$endif}
{$else}
{for BCB4, use the Delphi 5 codepath}
{$ifdef ver120}
{$define Delphi4or5}
{$define BCB4}
{$endif}
{for BCB5, use the Delphi 5 codepath}
{$ifdef ver130}
{$define Delphi4or5}
{$endif}
{$endif}
{$ifdef ver180}
{$define BDS2006}
{$endif}
{$define 32Bit}
{$ifndef Delphi4or5}
{$if SizeOf(Pointer) = 8}
{$define 64Bit}
{$undef 32Bit}
{$ifend}
{$if CompilerVersion >= 23}
{$define XE2AndUp}
{$ifend}
{$define BCB6OrDelphi6AndUp}
{$ifndef BCB}
{$define Delphi6AndUp}
{$endif}
{$ifndef Delphi6}
{$define BCB6OrDelphi7AndUp}
{$ifndef BCB}
{$define Delphi7AndUp}
{$endif}
{$ifndef BCB}
{$ifndef Delphi7}
{$ifndef Delphi2005}
{$define BDS2006AndUp}
{$endif}
{$endif}
{$endif}
{$endif}
{$endif}
{$ifdef 64Bit}
{Under 64 bit memory blocks must always be 16-byte aligned}
{$define Align16Bytes}
{No need for MMX under 64-bit, since SSE2 is available}
{$undef EnableMMX}
{There is little need for raw stack traces under 64-bit, since frame based
stack traces are much more accurate than under 32-bit. (And frame based
stack tracing is much faster.)}
{$undef RawStackTraces}
{$endif}
{IDE debug mode always enables FullDebugMode and dynamic loading of the FullDebugMode DLL.}
{$ifdef FullDebugModeInIDE}
{$define InstallOnlyIfRunningInIDE}
{$define FullDebugMode}
{$define LoadDebugDLLDynamically}
{$endif}
{Install in FullDebugMode only when the DLL is available?}
{$ifdef FullDebugModeWhenDLLAvailable}
{$define FullDebugMode}
{$define LoadDebugDLLDynamically}
{$define DoNotInstallIfDLLMissing}
{$endif}
{$ifdef Linux}
{$define POSIX}
{$endif}
{Some features not currently supported under Kylix / OS X}
{$ifdef POSIX}
{$undef FullDebugMode}
{$undef LogErrorsToFile}
{$undef LogMemoryLeakDetailToFile}
{$undef ShareMM}
{$undef AttemptToUseSharedMM}
{$undef RequireIDEPresenceForLeakReporting}
{$undef UseOutputDebugString}
{$ifdef PIC}
{BASM version does not support position independent code}
{$undef ASMVersion}
{$endif}
{$endif}
{Do we require debug info for leak checking?}
{$ifdef RequireDebugInfoForLeakReporting}
{$ifopt D-}
{$undef EnableMemoryLeakReporting}
{$endif}
{$endif}
{Enable heap checking and leak reporting in full debug mode}
{$ifdef FullDebugMode}
{$STACKFRAMES ON}
{$define CheckHeapForCorruption}
{$ifndef CatchUseOfFreedInterfaces}
{$define CheckUseOfFreedBlocksOnShutdown}
{$endif}
{$else}
{Error logging requires FullDebugMode}
{$undef LogErrorsToFile}
{$undef CatchUseOfFreedInterfaces}
{$undef RawStackTraces}
{$undef AlwaysAllocateTopDown}
{$endif}
{Set defines for security options}
{$ifdef FullDebugMode}
{In FullDebugMode small and medium blocks are always cleared when calling
FreeMem. Large blocks are always returned to the OS immediately.}
{$ifdef ClearMemoryBeforeReturningToOS}
{$define ClearLargeBlocksBeforeReturningToOS}
{$endif}
{$ifdef AlwaysClearFreedMemory}
{$define ClearLargeBlocksBeforeReturningToOS}
{$endif}
{$else}
{If memory blocks are cleared in FreeMem then they do not need to be cleared
before returning the memory to the OS.}
{$ifdef AlwaysClearFreedMemory}
{$define ClearSmallAndMediumBlocksInFreeMem}
{$define ClearLargeBlocksBeforeReturningToOS}
{$else}
{$ifdef ClearMemoryBeforeReturningToOS}
{$define ClearMediumBlockPoolsBeforeReturningToOS}
{$define ClearLargeBlocksBeforeReturningToOS}
{$endif}
{$endif}
{$endif}
{Only the Pascal version supports extended heap corruption checking.}
{$ifdef CheckHeapForCorruption}
{$undef ASMVersion}
{$endif}
{For BASM bits that are not implemented in 64-bit.}
{$ifdef 32Bit}
{$ifdef ASMVersion}
{$define Use32BitAsm}
{$endif}
{$endif}
{$ifdef UseRuntimePackages}
{$define AssumeMultiThreaded}
{$endif}
{$ifdef BCB6OrDelphi6AndUp}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$endif}
{Leak detail logging requires error logging}
{$ifndef LogErrorsToFile}
{$undef LogMemoryLeakDetailToFile}
{$undef ClearLogFileOnStartup}
{$endif}
{$ifndef EnableMemoryLeakReporting}
{Manual leak reporting control requires leak reporting to be enabled}
{$undef ManualLeakReportingControl}
{$endif}
{$ifndef EnableMMX}
{$undef ForceMMX}
{$endif}
{Are any of the MM sharing options enabled?}
{$ifdef ShareMM}
{$define MMSharingEnabled}
{$endif}
{$ifdef AttemptToUseSharedMM}
{$define MMSharingEnabled}
{$endif}
{Instruct GExperts to back up the messages file as well.}
{#BACKUP FastMM4Messages.pas}
{Should debug info be disabled?}
{$ifdef NoDebugInfo}
{$DEBUGINFO OFF}
{$endif}
{$ifdef BCB}
{$ifdef borlndmmdll}
{$OBJEXPORTALL OFF}
{$endif}
{$ifndef PatchBCBTerminate}
{Cannot uninstall safely under BCB}
{$define NeverUninstall}
{Disable memory leak reporting}
{$undef EnableMemoryLeakReporting}
{$endif}
{$endif}
{-------------------------Public constants-----------------------------}
const
{The current version of FastMM}
FastMMVersion = '4.991';
{The number of small block types}
{$ifdef Align16Bytes}
NumSmallBlockTypes = 46;
{$else}
NumSmallBlockTypes = 56;
{$endif}
{----------------------------Public types------------------------------}
type
{Make sure all the required types are available}
{$ifdef BCB6OrDelphi6AndUp}
{$if CompilerVersion < 20}
PByte = PAnsiChar;
{NativeInt didn't exist or was broken before Delphi 2009.}
NativeInt = Integer;
{$ifend}
{$if CompilerVersion < 21}
{NativeUInt didn't exist or was broken before Delphi 2010.}
NativeUInt = Cardinal;
{$ifend}
{$if CompilerVersion < 22}
{PNativeUInt didn't exist before Delphi XE.}
PNativeUInt = ^Cardinal;
{$ifend}
{$if CompilerVersion < 23}
{IntPtr and UIntPtr didn't exist before Delphi XE2.}
IntPtr = Integer;
UIntPtr = Cardinal;
{$ifend}
{$else}
PByte = PAnsiChar;
NativeInt = Integer;
NativeUInt = Cardinal;
PNativeUInt = ^Cardinal;
IntPtr = Integer;
UIntPtr = Cardinal;
{$endif}
TSmallBlockTypeState = record
{The internal size of the block type}
InternalBlockSize: Cardinal;
{Useable block size: The number of non-reserved bytes inside the block.}
UseableBlockSize: Cardinal;
{The number of allocated blocks}
AllocatedBlockCount: NativeUInt;
{The total address space reserved for this block type (both allocated and
free blocks)}
ReservedAddressSpace: NativeUInt;
end;
TSmallBlockTypeStates = array[0..NumSmallBlockTypes - 1] of TSmallBlockTypeState;
TMemoryManagerState = record
{Small block type states}
SmallBlockTypeStates: TSmallBlockTypeStates;
{Medium block stats}
AllocatedMediumBlockCount: Cardinal;
TotalAllocatedMediumBlockSize: NativeUInt;
ReservedMediumBlockAddressSpace: NativeUInt;
{Large block stats}
AllocatedLargeBlockCount: Cardinal;
TotalAllocatedLargeBlockSize: NativeUInt;
ReservedLargeBlockAddressSpace: NativeUInt;
end;
TMemoryManagerUsageSummary = record
{The total number of bytes allocated by the application.}
AllocatedBytes: NativeUInt;
{The total number of address space bytes used by control structures, or
lost due to fragmentation and other overhead.}
OverheadBytes: NativeUInt;
{The efficiency of the memory manager expressed as a percentage. This is
100 * AllocatedBytes / (AllocatedBytes + OverheadBytes).}
EfficiencyPercentage: Double;
end;
{Memory map}
TChunkStatus = (csUnallocated, csAllocated, csReserved, csSysAllocated,
csSysReserved);
TMemoryMap = array[0..65535] of TChunkStatus;
{$ifdef EnableMemoryLeakReporting}
{List of registered leaks}
TRegisteredMemoryLeak = record
LeakAddress: Pointer;
LeakedClass: TClass;
{$ifdef CheckCppObjectTypeEnabled}
LeakedCppTypeIdPtr: Pointer;
{$endif}
LeakSize: NativeInt;
LeakCount: Integer;
end;
TRegisteredMemoryLeaks = array of TRegisteredMemoryLeak;
{$endif}
{Used by the DetectStringData routine to detect whether a leaked block
contains string data.}
TStringDataType = (stUnknown, stAnsiString, stUnicodeString);
{The callback procedure for WalkAllocatedBlocks.}
TWalkAllocatedBlocksCallback = procedure(APBlock: Pointer; ABlockSize: NativeInt; AUserData: Pointer);
{--------------------------Public variables----------------------------}
var
{If this variable is set to true and FullDebugMode is enabled, then the
entire memory pool is checked for consistency before every memory
operation. Note that this incurs a massive performance hit on top of
the already significant FullDebugMode overhead, so enable this option
only when absolutely necessary.}
FullDebugModeScanMemoryPoolBeforeEveryOperation: Boolean = False;
FullDebugModeRegisterAllAllocsAsExpectedMemoryLeak: Boolean = False;
{$ifdef ManualLeakReportingControl}
{Variable is declared in system.pas in newer Delphi versions.}
{$ifndef BDS2006AndUp}
ReportMemoryLeaksOnShutdown: Boolean;
{$endif}
{$endif}
{If set to True, disables the display of all messageboxes}
SuppressMessageBoxes: Boolean;
{-------------------------Public procedures----------------------------}
{Executes the code normally run in the initialization section. Running it
earlier may be required with e.g. some software protection tools.}
procedure RunInitializationCode;
{Installation procedures must be exposed for the BCB helper unit FastMM4BCB.cpp}
{$ifdef BCB}
procedure InitializeMemoryManager;
function CheckCanInstallMemoryManager: Boolean;
procedure InstallMemoryManager;
{$ifdef FullDebugMode}
(*$HPPEMIT '#define FullDebugMode' *)
{$ifdef ClearLogFileOnStartup}
(*$HPPEMIT ' #define ClearLogFileOnStartup' *)
procedure DeleteEventLog;
{$endif}
{$ifdef LoadDebugDLLDynamically}
(*$HPPEMIT ' #define LoadDebugDLLDynamically' *)
{$endif}
{$ifdef RawStackTraces}
(*$HPPEMIT ' #define RawStackTraces' *)
{$endif}
{$endif}
{$ifdef PatchBCBTerminate}
(*$HPPEMIT ''#13#10 *)
(*$HPPEMIT '#define PatchBCBTerminate' *)
{$ifdef EnableMemoryLeakReporting}
(*$HPPEMIT ''#13#10 *)
(*$HPPEMIT '#define EnableMemoryLeakReporting' *)
{$endif}
{$ifdef DetectMMOperationsAfterUninstall}
(*$HPPEMIT ''#13#10 *)
(*$HPPEMIT '#define DetectMMOperationsAfterUninstall' *)
{$endif}
{Called in FastMM4BCB.cpp, should contain codes of original "finalization" section}
procedure FinalizeMemoryManager;
{For completion of "RequireDebuggerPresenceForLeakReporting" checking in "FinalizeMemoryManager"}
var
pCppDebugHook: ^Integer = nil; //PInteger not defined in BCB5
{$ifdef CheckCppObjectTypeEnabled}
(*$HPPEMIT ''#13#10 *)
(*$HPPEMIT '#define CheckCppObjectTypeEnabled' *)
type
TGetCppVirtObjSizeByTypeIdPtrFunc = function(APointer: Pointer): Cardinal;
TGetCppVirtObjTypeIdPtrFunc = function(APointer: Pointer; ASize: Cardinal): Pointer;
TGetCppVirtObjTypeNameFunc = function(APointer: Pointer; ASize: Cardinal): PAnsiChar;
TGetCppVirtObjTypeNameByTypeIdPtrFunc = function (APointer: Pointer): PAnsiChar;
TGetCppVirtObjTypeNameByVTablePtrFunc = function(AVTablePtr: Pointer; AVTablePtrOffset: Cardinal): PAnsiChar;
var
{Return virtual object's size from typeId pointer}
GetCppVirtObjSizeByTypeIdPtrFunc: TGetCppVirtObjSizeByTypeIdPtrFunc = nil;
{Retrieve virtual object's typeId pointer}
GetCppVirtObjTypeIdPtrFunc: TGetCppVirtObjTypeIdPtrFunc = nil;
{Retrieve virtual object's type name}
GetCppVirtObjTypeNameFunc: TGetCppVirtObjTypeNameFunc = nil;
{Return virtual object's type name from typeId pointer}
GetCppVirtObjTypeNameByTypeIdPtrFunc: TGetCppVirtObjTypeNameByTypeIdPtrFunc = nil;
{Retrieve virtual object's typeId pointer from it's virtual table pointer}
GetCppVirtObjTypeNameByVTablePtrFunc: TGetCppVirtObjTypeNameByVTablePtrFunc = nil;
{$endif}
{$endif}
{$endif}
{$ifndef FullDebugMode}
{The standard memory manager functions}
function FastGetMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer;
function FastFreeMem(APointer: Pointer): Integer;
function FastReallocMem(APointer: Pointer; ANewSize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer;
function FastAllocMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Cardinal{$endif}): Pointer;
{$else}
{The FullDebugMode memory manager functions}
function DebugGetMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer;
function DebugFreeMem(APointer: Pointer): Integer;
function DebugReallocMem(APointer: Pointer; ANewSize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer;
function DebugAllocMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Cardinal{$endif}): Pointer;
{Scans the memory pool for any corruptions. If a corruption is encountered an "Out of Memory" exception is
raised.}
procedure ScanMemoryPoolForCorruptions;
{Specify the full path and name for the filename to be used for logging memory
errors, etc. If ALogFileName is nil or points to an empty string it will
revert to the default log file name.}
procedure SetMMLogFileName(ALogFileName: PAnsiChar = nil);
{Returns the current "allocation group". Whenever a GetMem request is serviced
in FullDebugMode, the current "allocation group" is stored in the block header.
This may help with debugging. Note that if a block is subsequently reallocated
that it keeps its original "allocation group" and "allocation number" (all
allocations are also numbered sequentially).}
function GetCurrentAllocationGroup: Cardinal;
{Allocation groups work in a stack like fashion. Group numbers are pushed onto
and popped off the stack. Note that the stack size is limited, so every push
should have a matching pop.}
procedure PushAllocationGroup(ANewCurrentAllocationGroup: Cardinal);
procedure PopAllocationGroup;
{Logs detail about currently allocated memory blocks for the specified range of
allocation groups. if ALastAllocationGroupToLog is less than
AFirstAllocationGroupToLog or it is zero, then all allocation groups are
logged. This routine also checks the memory pool for consistency at the same
time, raising an "Out of Memory" error if the check fails.}
procedure LogAllocatedBlocksToFile(AFirstAllocationGroupToLog, ALastAllocationGroupToLog: Cardinal);
{$endif}
{Releases all allocated memory (use with extreme care)}
procedure FreeAllMemory;
{Returns summarised information about the state of the memory manager. (For
backward compatibility.)}
function FastGetHeapStatus: THeapStatus;
{Returns statistics about the current state of the memory manager}
procedure GetMemoryManagerState(var AMemoryManagerState: TMemoryManagerState);
{Returns a summary of the information returned by GetMemoryManagerState}
procedure GetMemoryManagerUsageSummary(
var AMemoryManagerUsageSummary: TMemoryManagerUsageSummary);
{$ifndef POSIX}
{Gets the state of every 64K block in the 4GB address space}
procedure GetMemoryMap(var AMemoryMap: TMemoryMap);
{$endif}
{$ifdef EnableMemoryLeakReporting}
{Registers expected memory leaks. Returns true on success. The list of leaked
blocks is limited, so failure is possible if the list is full.}
function RegisterExpectedMemoryLeak(ALeakedPointer: Pointer): Boolean; overload;
function RegisterExpectedMemoryLeak(ALeakedObjectClass: TClass; ACount: Integer = 1): Boolean; overload;
function RegisterExpectedMemoryLeak(ALeakedBlockSize: NativeInt; ACount: Integer = 1): Boolean; overload;
{$ifdef CheckCppObjectTypeEnabled}
{Registers expected memory leaks by virtual object's typeId pointer.
Usage: RegisterExpectedMemoryLeak(typeid(ACppObject).tpp, Count);}
function RegisterExpectedMemoryLeak(ALeakedCppVirtObjTypeIdPtr: Pointer; ACount: Integer): boolean; overload;
{$endif}
{Removes expected memory leaks. Returns true on success.}
function UnregisterExpectedMemoryLeak(ALeakedPointer: Pointer): Boolean; overload;
function UnregisterExpectedMemoryLeak(ALeakedObjectClass: TClass; ACount: Integer = 1): Boolean; overload;
function UnregisterExpectedMemoryLeak(ALeakedBlockSize: NativeInt; ACount: Integer = 1): Boolean; overload;
{$ifdef CheckCppObjectTypeEnabled}
{Usage: UnregisterExpectedMemoryLeak(typeid(ACppObject).tpp, Count);}
function UnregisterExpectedMemoryLeak(ALeakedCppVirtObjTypeIdPtr: Pointer; ACount: Integer): boolean; overload;
{$endif}
{Returns a list of all expected memory leaks}
function GetRegisteredMemoryLeaks: TRegisteredMemoryLeaks;
{$endif}
{Returns the class for a memory block. Returns nil if it is not a valid class.
Used by the leak detection code.}
function DetectClassInstance(APointer: Pointer): TClass;
{Detects the probable string data type for a memory block. Used by the leak
classification code when a block cannot be identified as a known class
instance.}
function DetectStringData(APMemoryBlock: Pointer;
AAvailableSpaceInBlock: NativeInt): TStringDataType;
{Walks all allocated blocks, calling ACallBack for each. Passes the user block size and AUserData to the callback.
Important note: All block types will be locked during the callback, so the memory manager cannot be used inside it.}
procedure WalkAllocatedBlocks(ACallBack: TWalkAllocatedBlocksCallback; AUserData: Pointer);
{Writes a log file containing a summary of the memory mananger state and a summary of allocated blocks grouped by
class. The file will be saved in UTF-8 encoding (in supported Delphi versions). Returns True on success. }
function LogMemoryManagerStateToFile(const AFileName: string; const AAdditionalDetails: string = ''): Boolean;
{$ifdef FullDebugMode}
{-------------FullDebugMode constants---------------}
const
{The stack trace depth. (Must be an *uneven* number to ensure that the
Align16Bytes option works in FullDebugMode.)}
StackTraceDepth = 11;
{The number of entries in the allocation group stack}
AllocationGroupStackSize = 1000;
{The number of fake VMT entries - used to track virtual method calls on
freed objects. Do not change this value without also updating TFreedObject.GetVirtualMethodIndex}
MaxFakeVMTEntries = 200;
{The pattern used to fill unused memory}
DebugFillByte = $80;
{$ifdef 32Bit}
DebugFillPattern = $01010101 * Cardinal(DebugFillByte);
{The address that is reserved so that accesses to the address of the fill
pattern will result in an A/V. (Not used under 64-bit, since the upper half
of the address space is always reserved by the OS.)}
DebugReservedAddress = $01010000 * Cardinal(DebugFillByte);
{$else}
DebugFillPattern = $8080808080808080;
{$endif}
{-------------------------FullDebugMode structures--------------------}
type
PStackTrace = ^TStackTrace;
TStackTrace = array[0..StackTraceDepth - 1] of NativeUInt;
TBlockOperation = (boBlockCheck, boGetMem, boFreeMem, boReallocMem);
{The header placed in front of blocks in FullDebugMode (just after the
standard header). Must be a multiple of 16 bytes in size otherwise the
Align16Bytes option will not work. Current size = 128 bytes under 32-bit,
and 240 bytes under 64-bit.}
PFullDebugBlockHeader = ^TFullDebugBlockHeader;
TFullDebugBlockHeader = record
{Space used by the medium block manager for previous/next block management.
If a medium block is binned then these two fields will be modified.}
Reserved1: Pointer;
Reserved2: Pointer;
{Is the block currently allocated? If it is allocated this will be the
address of the getmem routine through which it was allocated, otherwise it
will be nil.}
AllocatedByRoutine: Pointer;
{The allocation group: Can be used in the debugging process to group
related memory leaks together}
AllocationGroup: Cardinal;
{The allocation number: All new allocations are numbered sequentially. This
number may be useful in memory leak analysis. If it reaches 4G it wraps
back to 0.}
AllocationNumber: Cardinal;
{The call stack when the block was allocated}
AllocationStackTrace: TStackTrace;
{The thread that allocated the block}
AllocatedByThread: Cardinal;
{The thread that freed the block}
FreedByThread: Cardinal;
{The call stack when the block was freed}
FreeStackTrace: TStackTrace;
{The user requested size for the block. 0 if this is the first time the
block is used.}
UserSize: NativeUInt;
{The object class this block was used for the previous time it was
allocated. When a block is freed, the pointer that would normally be in the
space of the class pointer is copied here, so if it is detected that
the block was used after being freed we have an idea what class it is.}
PreviouslyUsedByClass: NativeUInt;
{The sum of all the dwords(32-bit)/qwords(64-bit) in this structure
excluding the initial two reserved fields and this field.}
HeaderCheckSum: NativeUInt;
end;
{The NativeUInt following the user area of the block is the inverse of
HeaderCheckSum. This is used to catch buffer overrun errors.}
{The class used to catch attempts to execute a virtual method of a freed
object}
TFreedObject = class
public
procedure GetVirtualMethodIndex;
procedure VirtualMethodError;
{$ifdef CatchUseOfFreedInterfaces}
procedure InterfaceError;
{$endif}
end;
{$ifdef FullDebugModeCallBacks}
{FullDebugMode memory manager event callbacks. Note that APHeaderFreedBlock in the TOnDebugFreeMemFinish
will not be valid for large (>260K) blocks.}
TOnDebugGetMemFinish = procedure(APHeaderNewBlock: PFullDebugBlockHeader; ASize: NativeInt);
TOnDebugFreeMemStart = procedure(APHeaderBlockToFree: PFullDebugBlockHeader);
TOnDebugFreeMemFinish = procedure(APHeaderFreedBlock: PFullDebugBlockHeader; AResult: Integer);
TOnDebugReallocMemStart = procedure(APHeaderBlockToReallocate: PFullDebugBlockHeader; ANewSize: NativeInt);
TOnDebugReallocMemFinish = procedure(APHeaderReallocatedBlock: PFullDebugBlockHeader; ANewSize: NativeInt);
var
{Note: FastMM will not catch exceptions inside these hooks, so make sure your hook code runs without
exceptions.}
OnDebugGetMemFinish: TOnDebugGetMemFinish = nil;
OnDebugFreeMemStart: TOnDebugFreeMemStart = nil;
OnDebugFreeMemFinish: TOnDebugFreeMemFinish = nil;
OnDebugReallocMemStart: TOnDebugReallocMemStart = nil;
OnDebugReallocMemFinish: TOnDebugReallocMemFinish = nil;
{$endif}
{$endif}
implementation
uses
{$ifndef POSIX}
Windows,
{$ifdef FullDebugMode}
{$ifdef Delphi4or5}
ShlObj,
{$else}
SHFolder,
{$endif}
{$endif}
{$else}
{$ifdef MACOS}
Posix.Stdlib, Posix.Unistd, Posix.Fcntl,
{$ELSE}
Libc,
{$endif}
{$endif}
FastMM4Messages;
{Fixed size move procedures. The 64-bit versions assume 16-byte alignment.}
procedure Move4(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move12(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move20(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move28(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move36(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move44(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move52(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move60(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move68(const ASource; var ADest; ACount: NativeInt); forward;
{$ifdef 64Bit}
{These are not needed and thus unimplemented under 32-bit}
procedure Move8(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move24(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move40(const ASource; var ADest; ACount: NativeInt); forward;
procedure Move56(const ASource; var ADest; ACount: NativeInt); forward;
{$endif}
{$ifdef DetectMMOperationsAfterUninstall}
{Invalid handlers to catch MM operations after uninstall}
function InvalidFreeMem(APointer: Pointer): Integer; forward;
function InvalidGetMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer; forward;
function InvalidReallocMem(APointer: Pointer; ANewSize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer; forward;
function InvalidAllocMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Cardinal{$endif}): Pointer; forward;
function InvalidRegisterAndUnRegisterMemoryLeak(APointer: Pointer): Boolean; forward;
{$endif}
{-------------------------Private constants----------------------------}
const
{The size of a medium block pool. This is allocated through VirtualAlloc and
is used to serve medium blocks. The size must be a multiple of 16 and at
least 4 bytes less than a multiple of 4K (the page size) to prevent a
possible read access violation when reading past the end of a memory block
in the optimized move routine (MoveX16LP). In Full Debug mode we leave a
trailing 256 bytes to be able to safely do a memory dump.}
MediumBlockPoolSize = 20 * 64 * 1024{$ifndef FullDebugMode} - 16{$else} - 256{$endif};
{The granularity of small blocks}
{$ifdef Align16Bytes}
SmallBlockGranularity = 16;
{$else}
SmallBlockGranularity = 8;
{$endif}
{The granularity of medium blocks. Newly allocated medium blocks are
a multiple of this size plus MediumBlockSizeOffset, to avoid cache line
conflicts}
MediumBlockGranularity = 256;
MediumBlockSizeOffset = 48;
{The granularity of large blocks}
LargeBlockGranularity = 65536;
{The maximum size of a small block. Blocks Larger than this are either
medium or large blocks.}
MaximumSmallBlockSize = 2608;
{The smallest medium block size. (Medium blocks are rounded up to the nearest
multiple of MediumBlockGranularity plus MediumBlockSizeOffset)}
MinimumMediumBlockSize = 11 * 256 + MediumBlockSizeOffset;
{The number of bins reserved for medium blocks}
MediumBlockBinsPerGroup = 32;
MediumBlockBinGroupCount = 32;
MediumBlockBinCount = MediumBlockBinGroupCount * MediumBlockBinsPerGroup;
{The maximum size allocatable through medium blocks. Blocks larger than this
fall through to VirtualAlloc ( = large blocks).}
MaximumMediumBlockSize = MinimumMediumBlockSize + (MediumBlockBinCount - 1) * MediumBlockGranularity;
{The target number of small blocks per pool. The actual number of blocks per
pool may be much greater for very small sizes and less for larger sizes. The
cost of allocating the small block pool is amortized across all the small
blocks in the pool, however the blocks may not all end up being used so they
may be lying idle.}
TargetSmallBlocksPerPool = 48;
{The minimum number of small blocks per pool. Any available medium block must
have space for roughly this many small blocks (or more) to be useable as a
small block pool.}
MinimumSmallBlocksPerPool = 12;
{The lower and upper limits for the optimal small block pool size}
OptimalSmallBlockPoolSizeLowerLimit = 29 * 1024 - MediumBlockGranularity + MediumBlockSizeOffset;
OptimalSmallBlockPoolSizeUpperLimit = 64 * 1024 - MediumBlockGranularity + MediumBlockSizeOffset;
{The maximum small block pool size. If a free block is this size or larger
then it will be split.}
MaximumSmallBlockPoolSize = OptimalSmallBlockPoolSizeUpperLimit + MinimumMediumBlockSize;
{-------------Block type flags--------------}
{The lower 3 bits in the dword header of small blocks (4 bits in medium and
large blocks) are used as flags to indicate the state of the block}
{Set if the block is not in use}
IsFreeBlockFlag = 1;
{Set if this is a medium block}
IsMediumBlockFlag = 2;
{Set if it is a medium block being used as a small block pool. Only valid if
IsMediumBlockFlag is set.}
IsSmallBlockPoolInUseFlag = 4;
{Set if it is a large block. Only valid if IsMediumBlockFlag is not set.}
IsLargeBlockFlag = 4;
{Is the medium block preceding this block available? (Only used by medium
blocks)}
PreviousMediumBlockIsFreeFlag = 8;
{Is this large block segmented? I.e. is it actually built up from more than
one chunk allocated through VirtualAlloc? (Only used by large blocks.)}
LargeBlockIsSegmented = 8;
{The flags masks for small blocks}
DropSmallFlagsMask = -8;
ExtractSmallFlagsMask = 7;
{The flags masks for medium and large blocks}
DropMediumAndLargeFlagsMask = -16;
ExtractMediumAndLargeFlagsMask = 15;
{-------------Block resizing constants---------------}
SmallBlockDownsizeCheckAdder = 64;
SmallBlockUpsizeAdder = 32;
{When a medium block is reallocated to a size smaller than this, then it must
be reallocated to a small block and the data moved. If not, then it is
shrunk in place down to MinimumMediumBlockSize. Currently the limit is set
at a quarter of the minimum medium block size.}
MediumInPlaceDownsizeLimit = MinimumMediumBlockSize div 4;
{-------------Memory leak reporting constants---------------}
ExpectedMemoryLeaksListSize = 64 * 1024;
{-------------Other constants---------------}
{$ifndef NeverSleepOnThreadContention}
{Sleep time when a resource (small/medium/large block manager) is in use}
InitialSleepTime = 0;
{Used when the resource is still in use after the first sleep}
AdditionalSleepTime = 1;
{$endif}
{Hexadecimal characters}
HexTable: array[0..15] of AnsiChar = ('0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
{Copyright message - not used anywhere in the code}
Copyright: AnsiString = 'FastMM4 (c) 2004 - 2011 Pierre le Riche / Professional Software Development';
{$ifdef FullDebugMode}
{Virtual Method Called On Freed Object Errors}
StandardVirtualMethodNames: array[1 + vmtParent div SizeOf(Pointer) .. vmtDestroy div SizeOf(Pointer)] of PAnsiChar = (
{$ifdef BCB6OrDelphi6AndUp}
{$if RTLVersion >= 20}
'Equals',
'GetHashCode',
'ToString',
{$ifend}
{$endif}
'SafeCallException',
'AfterConstruction',
'BeforeDestruction',
'Dispatch',
'DefaultHandler',
'NewInstance',
'FreeInstance',
'Destroy');
{The name of the FullDebugMode support DLL. The support DLL implements stack
tracing and the conversion of addresses to unit and line number information.}
{$ifdef 32Bit}
FullDebugModeLibraryName = FullDebugModeLibraryName32Bit;
{$else}
FullDebugModeLibraryName = FullDebugModeLibraryName64Bit;
{$endif}
{$endif}
{-------------------------Private types----------------------------}
type
{$ifdef Delphi4or5}
{Delphi 5 Compatibility}
PCardinal = ^Cardinal;
PPointer = ^Pointer;
{$endif}
{$ifdef BCB4}
{Define some additional types for BCB4}
PInteger = ^Integer;
{$endif}
{Move procedure type}
TMoveProc = procedure(const ASource; var ADest; ACount: NativeInt);
{Registers structure (for GetCPUID)}
TRegisters = record
RegEAX, RegEBX, RegECX, RegEDX: Integer;
end;
{The layout of a string allocation. Used to detect string leaks.}
PStrRec = ^StrRec;
StrRec = packed record
{$ifdef 64Bit}
_Padding: Integer;
{$endif}
{$ifdef BCB6OrDelphi6AndUp}
{$if RTLVersion >= 20}
codePage: Word;
elemSize: Word;
{$ifend}
{$endif}
refCnt: Integer;
length: Integer;
end;
{$ifdef EnableMemoryLeakReporting}
{Different kinds of memory leaks}
TMemoryLeakType = (mltUnexpectedLeak, mltExpectedLeakRegisteredByPointer,
mltExpectedLeakRegisteredByClass, mltExpectedLeakRegisteredBySize);
{$endif}
{---------------Small block structures-------------}
{Pointer to the header of a small block pool}
PSmallBlockPoolHeader = ^TSmallBlockPoolHeader;
{Small block type (Size = 32 bytes for 32-bit, 64 bytes for 64-bit).}
PSmallBlockType = ^TSmallBlockType;
TSmallBlockType = record
{True = Block type is locked}
BlockTypeLocked: Boolean;
{Bitmap indicating which of the first 8 medium block groups contain blocks
of a suitable size for a block pool.}
AllowedGroupsForBlockPoolBitmap: Byte;
{The block size for this block type}
BlockSize: Word;
{The minimum and optimal size of a small block pool for this block type}
MinimumBlockPoolSize: Word;
OptimalBlockPoolSize: Word;
{The first partially free pool for the given small block. This field must
be at the same offset as TSmallBlockPoolHeader.NextPartiallyFreePool.}
NextPartiallyFreePool: PSmallBlockPoolHeader;
{The last partially free pool for the small block type. This field must
be at the same offset as TSmallBlockPoolHeader.PreviousPartiallyFreePool.}
PreviousPartiallyFreePool: PSmallBlockPoolHeader;
{The offset of the last block that was served sequentially. The field must
be at the same offset as TSmallBlockPoolHeader.FirstFreeBlock.}
NextSequentialFeedBlockAddress: Pointer;
{The last block that can be served sequentially.}
MaxSequentialFeedBlockAddress: Pointer;
{The pool that is current being used to serve blocks in sequential order}
CurrentSequentialFeedPool: PSmallBlockPoolHeader;
{$ifdef UseCustomFixedSizeMoveRoutines}
{The fixed size move procedure used to move data for this block size when
it is upsized. When a block is downsized (which usually does not occur
that often) the variable size move routine is used.}
UpsizeMoveProcedure: TMoveProc;
{$else}
Reserved1: Pointer;
{$endif}
{$ifdef 64Bit}
{Pad to 64 bytes for 64-bit}
Reserved2: Pointer;
{$endif}
end;
{Small block pool (Size = 32 bytes for 32-bit, 48 bytes for 64-bit).}
TSmallBlockPoolHeader = record
{BlockType}
BlockType: PSmallBlockType;
{$ifdef 32Bit}
{Align the next fields to the same fields in TSmallBlockType and pad this
structure to 32 bytes for 32-bit}
Reserved1: Cardinal;
{$endif}
{The next and previous pool that has free blocks of this size. Do not
change the position of these two fields: They must be at the same offsets
as the fields in TSmallBlockType of the same name.}
NextPartiallyFreePool: PSmallBlockPoolHeader;
PreviousPartiallyFreePool: PSmallBlockPoolHeader;
{Pointer to the first free block inside this pool. This field must be at
the same offset as TSmallBlockType.NextSequentialFeedBlockAddress.}
FirstFreeBlock: Pointer;
{The number of blocks allocated in this pool.}
BlocksInUse: Cardinal;
{Padding}
Reserved2: Cardinal;
{The pool pointer and flags of the first block}
FirstBlockPoolPointerAndFlags: NativeUInt;
end;
{Small block layout:
At offset -SizeOf(Pointer) = Flags + address of the small block pool.
At offset BlockSize - SizeOf(Pointer) = Flags + address of the small block
pool for the next small block.
}
{------------------------Medium block structures------------------------}
{The medium block pool from which medium blocks are drawn. Size = 16 bytes
for 32-bit and 32 bytes for 64-bit.}
PMediumBlockPoolHeader = ^TMediumBlockPoolHeader;
TMediumBlockPoolHeader = record
{Points to the previous and next medium block pools. This circular linked
list is used to track memory leaks on program shutdown.}
PreviousMediumBlockPoolHeader: PMediumBlockPoolHeader;
NextMediumBlockPoolHeader: PMediumBlockPoolHeader;
{Padding}
Reserved1: NativeUInt;
{The block size and flags of the first medium block in the block pool}
FirstMediumBlockSizeAndFlags: NativeUInt;
end;
{Medium block layout:
Offset: -2 * SizeOf(Pointer) = Previous Block Size (only if the previous block is free)
Offset: -SizeOf(Pointer) = This block size and flags
Offset: 0 = User data / Previous Free Block (if this block is free)
Offset: SizeOf(Pointer) = Next Free Block (if this block is free)
Offset: BlockSize - 2*SizeOf(Pointer) = Size of this block (if this block is free)
Offset: BlockSize - SizeOf(Pointer) = Size of the next block and flags
{A medium block that is unused}
PMediumFreeBlock = ^TMediumFreeBlock;
TMediumFreeBlock = record
PreviousFreeBlock: PMediumFreeBlock;
NextFreeBlock: PMediumFreeBlock;
end;
{-------------------------Large block structures------------------------}
{Large block header record (Size = 16 for 32-bit, 32 for 64-bit)}
PLargeBlockHeader = ^TLargeBlockHeader;
TLargeBlockHeader = record
{Points to the previous and next large blocks. This circular linked
list is used to track memory leaks on program shutdown.}
PreviousLargeBlockHeader: PLargeBlockHeader;
NextLargeBlockHeader: PLargeBlockHeader;
{The user allocated size of the Large block}
UserAllocatedSize: NativeUInt;
{The size of this block plus the flags}
BlockSizeAndFlags: NativeUInt;
end;
{-------------------------Expected Memory Leak Structures--------------------}
{$ifdef EnableMemoryLeakReporting}
{The layout of an expected leak. All fields may not be specified, in which
case it may be harder to determine which leaks are expected and which are
not.}
PExpectedMemoryLeak = ^TExpectedMemoryLeak;
PPExpectedMemoryLeak = ^PExpectedMemoryLeak;
TExpectedMemoryLeak = record
{Linked list pointers}
PreviousLeak, NextLeak: PExpectedMemoryLeak;
{Information about the expected leak}
LeakAddress: Pointer;
LeakedClass: TClass;
{$ifdef CheckCppObjectTypeEnabled}
LeakedCppTypeIdPtr: Pointer;
{$endif}
LeakSize: NativeInt;
LeakCount: Integer;
end;
TExpectedMemoryLeaks = record
{The number of entries used in the expected leaks buffer}
EntriesUsed: Integer;
{Freed entries}
FirstFreeSlot: PExpectedMemoryLeak;
{Entries with the address specified}
FirstEntryByAddress: PExpectedMemoryLeak;
{Entries with no address specified, but with the class specified}
FirstEntryByClass: PExpectedMemoryLeak;
{Entries with only size specified}
FirstEntryBySizeOnly: PExpectedMemoryLeak;
{The expected leaks buffer (Need to leave space for this header)}
ExpectedLeaks: array[0..(ExpectedMemoryLeaksListSize - 64) div SizeOf(TExpectedMemoryLeak) - 1] of TExpectedMemoryLeak;
end;
PExpectedMemoryLeaks = ^TExpectedMemoryLeaks;
{$endif}
{-------------------------Private constants----------------------------}
const
{$ifndef BCB6OrDelphi7AndUp}
reOutOfMemory = 1;
reInvalidPtr = 2;
{$endif}
{The size of the block header in front of small and medium blocks}
BlockHeaderSize = SizeOf(Pointer);
{The size of a small block pool header}
SmallBlockPoolHeaderSize = SizeOf(TSmallBlockPoolHeader);
{The size of a medium block pool header}
MediumBlockPoolHeaderSize = SizeOf(TMediumBlockPoolHeader);
{The size of the header in front of Large blocks}
LargeBlockHeaderSize = SizeOf(TLargeBlockHeader);
{$ifdef FullDebugMode}
{We need space for the header, the trailer checksum and the trailing block
size (only used by freed medium blocks).}
FullDebugBlockOverhead = SizeOf(TFullDebugBlockHeader) + SizeOf(NativeUInt) + SizeOf(Pointer);
{$endif}
{-------------------------Private variables----------------------------}
var
{-----------------Small block management------------------}
{The small block types. Sizes include the leading header. Sizes are
picked to limit maximum wastage to about 10% or 256 bytes (whichever is
less) where possible.}
SmallBlockTypes: array[0..NumSmallBlockTypes - 1] of TSmallBlockType =(
{8/16 byte jumps}
{$ifndef Align16Bytes}
(BlockSize: 8 {$ifdef UseCustomFixedSizeMoveRoutines}; UpsizeMoveProcedure: Move4{$endif}),
{$endif}
(BlockSize: 16 {$ifdef UseCustomFixedSizeMoveRoutines}; UpsizeMoveProcedure: {$ifdef 32Bit}Move12{$else}Move8{$endif}{$endif}),
{$ifndef Align16Bytes}
(BlockSize: 24 {$ifdef UseCustomFixedSizeMoveRoutines}; UpsizeMoveProcedure: Move20{$endif}),
{$endif}
(BlockSize: 32 {$ifdef UseCustomFixedSizeMoveRoutines}; UpsizeMoveProcedure: {$ifdef 32Bit}Move28{$else}Move24{$endif}{$endif}),
{$ifndef Align16Bytes}
(BlockSize: 40 {$ifdef UseCustomFixedSizeMoveRoutines}; UpsizeMoveProcedure: Move36{$endif}),
{$endif}
(BlockSize: 48 {$ifdef UseCustomFixedSizeMoveRoutines}; UpsizeMoveProcedure: {$ifdef 32Bit}Move44{$else}Move40{$endif}{$endif}),
{$ifndef Align16Bytes}
(BlockSize: 56 {$ifdef UseCustomFixedSizeMoveRoutines}; UpsizeMoveProcedure: Move52{$endif}),
{$endif}
(BlockSize: 64 {$ifdef UseCustomFixedSizeMoveRoutines}; UpsizeMoveProcedure: {$ifdef 32Bit}Move60{$else}Move56{$endif}{$endif}),
{$ifndef Align16Bytes}
(BlockSize: 72 {$ifdef UseCustomFixedSizeMoveRoutines}; UpsizeMoveProcedure: Move68{$endif}),
{$endif}
(BlockSize: 80),
{$ifndef Align16Bytes}
(BlockSize: 88),
{$endif}
(BlockSize: 96),
{$ifndef Align16Bytes}
(BlockSize: 104),
{$endif}
(BlockSize: 112),
{$ifndef Align16Bytes}
(BlockSize: 120),
{$endif}
(BlockSize: 128),
{$ifndef Align16Bytes}
(BlockSize: 136),
{$endif}
(BlockSize: 144),
{$ifndef Align16Bytes}
(BlockSize: 152),
{$endif}
(BlockSize: 160),
{16 byte jumps}
(BlockSize: 176),
(BlockSize: 192),
(BlockSize: 208),
(BlockSize: 224),
(BlockSize: 240),
(BlockSize: 256),
(BlockSize: 272),
(BlockSize: 288),
(BlockSize: 304),
(BlockSize: 320),
{32 byte jumps}
(BlockSize: 352),
(BlockSize: 384),
(BlockSize: 416),
(BlockSize: 448),
(BlockSize: 480),
{48 byte jumps}
(BlockSize: 528),
(BlockSize: 576),
(BlockSize: 624),
(BlockSize: 672),
{64 byte jumps}
(BlockSize: 736),
(BlockSize: 800),
{80 byte jumps}
(BlockSize: 880),
(BlockSize: 960),
{96 byte jumps}
(BlockSize: 1056),
(BlockSize: 1152),
{112 byte jumps}
(BlockSize: 1264),
(BlockSize: 1376),
{128 byte jumps}
(BlockSize: 1504),
{144 byte jumps}
(BlockSize: 1648),
{160 byte jumps}
(BlockSize: 1808),
{176 byte jumps}
(BlockSize: 1984),
{192 byte jumps}
(BlockSize: 2176),
{208 byte jumps}
(BlockSize: 2384),
{224 byte jumps}
(BlockSize: MaximumSmallBlockSize),
{The last block size occurs three times. If, during a GetMem call, the
requested block size is already locked by another thread then up to two
larger block sizes may be used instead. Having the last block size occur
three times avoids the need to have a size overflow check.}
(BlockSize: MaximumSmallBlockSize),
(BlockSize: MaximumSmallBlockSize));
{Size to small block type translation table}
AllocSize2SmallBlockTypeIndX4: array[0..(MaximumSmallBlockSize - 1) div SmallBlockGranularity] of Byte;
{-----------------Medium block management------------------}
{A dummy medium block pool header: Maintains a circular list of all medium
block pools to enable memory leak detection on program shutdown.}
MediumBlockPoolsCircularList: TMediumBlockPoolHeader;
{Are medium blocks locked?}
MediumBlocksLocked: Boolean;
{The sequential feed medium block pool.}
LastSequentiallyFedMediumBlock: Pointer;
MediumSequentialFeedBytesLeft: Cardinal;
{The medium block bins are divided into groups of 32 bins. If a bit
is set in this group bitmap, then at least one bin in the group has free
blocks.}
MediumBlockBinGroupBitmap: Cardinal;
{The medium block bins: total of 32 * 32 = 1024 bins of a certain
minimum size.}
MediumBlockBinBitmaps: array[0..MediumBlockBinGroupCount - 1] of Cardinal;
{The medium block bins. There are 1024 LIFO circular linked lists each
holding blocks of a specified minimum size. The sizes vary in size from
MinimumMediumBlockSize to MaximumMediumBlockSize. The bins are treated as
type TMediumFreeBlock to avoid pointer checks.}
MediumBlockBins: array[0..MediumBlockBinCount - 1] of TMediumFreeBlock;
{-----------------Large block management------------------}
{Are large blocks locked?}
LargeBlocksLocked: Boolean;
{A dummy large block header: Maintains a list of all allocated large blocks
to enable memory leak detection on program shutdown.}
LargeBlocksCircularList: TLargeBlockHeader;
{-------------------------Expected Memory Leak Structures--------------------}
{$ifdef EnableMemoryLeakReporting}
{The expected memory leaks}
ExpectedMemoryLeaks: PExpectedMemoryLeaks;
ExpectedMemoryLeaksListLocked: Boolean;
{$endif}
{---------------------Full Debug Mode structures--------------------}
{$ifdef FullDebugMode}
{The allocation group stack}
AllocationGroupStack: array[0..AllocationGroupStackSize - 1] of Cardinal;
{The allocation group stack top (it is an index into AllocationGroupStack)}
AllocationGroupStackTop: Cardinal;
{The last allocation number used}
CurrentAllocationNumber: Cardinal;
{This is a count of the number of threads currently inside any of the
FullDebugMode GetMem, Freemem or ReallocMem handlers. If this value
is negative then a block scan is in progress and no thread may
allocate, free or reallocate any block or modify any FullDebugMode
block header or footer.}
ThreadsInFullDebugModeRoutine: Integer;
{The current log file name}
MMLogFileName: array[0..1023] of AnsiChar;
{The 64K block of reserved memory used to trap invalid memory accesses using
fields in a freed object.}
ReservedBlock: Pointer;
{The virtual method index count - used to get the virtual method index for a
virtual method call on a freed object.}
VMIndex: Integer;
{The fake VMT used to catch virtual method calls on freed objects.}
FreedObjectVMT: packed record
VMTData: array[vmtSelfPtr .. vmtParent + SizeOf(Pointer) - 1] of byte;
VMTMethods: array[SizeOf(Pointer) + vmtParent .. vmtParent + MaxFakeVMTEntries * SizeOf(Pointer) + SizeOf(Pointer) - 1] of Byte;
end;
{$ifdef CatchUseOfFreedInterfaces}
VMTBadInterface: array[0..MaxFakeVMTEntries - 1] of Pointer;
{$endif}
{$endif}
{--------------Other info--------------}
{The memory manager that was replaced}
OldMemoryManager: {$ifndef BDS2006AndUp}TMemoryManager{$else}TMemoryManagerEx{$endif};
{The replacement memory manager}
NewMemoryManager: {$ifndef BDS2006AndUp}TMemoryManager{$else}TMemoryManagerEx{$endif};
{$ifdef DetectMMOperationsAfterUninstall}
{Invalid handlers to catch MM operations after uninstall}
InvalidMemoryManager: {$ifndef BDS2006AndUp}TMemoryManager{$else}TMemoryManagerEx{$endif} = (
GetMem: InvalidGetMem;
FreeMem: InvalidFreeMem;
ReallocMem: InvalidReallocMem
{$ifdef BDS2006AndUp};
AllocMem: InvalidAllocMem;
RegisterExpectedMemoryLeak: InvalidRegisterAndUnRegisterMemoryLeak;
UnRegisterExpectedMemoryLeak: InvalidRegisterAndUnRegisterMemoryLeak;
{$endif}
);
{$endif}
{$ifdef MMSharingEnabled}
{A string uniquely identifying the current process (for sharing the memory
manager between DLLs and the main application)}
MappingObjectName: array[0..25] of AnsiChar = ('L', 'o', 'c', 'a', 'l', '\',
'F', 'a', 's', 't', 'M', 'M', '_', 'P', 'I', 'D', '_', '?', '?', '?', '?',
'?', '?', '?', '?', #0);
{$ifdef EnableBackwardCompatibleMMSharing}
UniqueProcessIDString: array[1..20] of AnsiChar = ('?', '?', '?', '?', '?',
'?', '?', '?', '_', 'P', 'I', 'D', '_', 'F', 'a', 's', 't', 'M', 'M', #0);
UniqueProcessIDStringBE: array[1..23] of AnsiChar = ('?', '?', '?', '?', '?',
'?', '?', '?', '_', 'P', 'I', 'D', '_', 'F', 'a', 's', 't', 'M', 'M', '_',
'B', 'E', #0);
{The handle of the MM window}
MMWindow: HWND;
{The handle of the MM window (for default MM of Delphi 2006 compatibility)}
MMWindowBE: HWND;
{$endif}
{The handle of the memory mapped file}
MappingObjectHandle: NativeUInt;
{$endif}
{Has FastMM been installed?}
FastMMIsInstalled: Boolean;
{Is the MM in place a shared memory manager?}
IsMemoryManagerOwner: Boolean;
{Must MMX be used for move operations?}
{$ifdef EnableMMX}
{$ifndef ForceMMX}
UseMMX: Boolean;
{$endif}
{$endif}
{Is a MessageBox currently showing? If so, do not show another one.}
ShowingMessageBox: Boolean;
{True if RunInitializationCode has been called already.}
InitializationCodeHasRun: Boolean = False;
{----------------Utility Functions------------------}
{A copy of StrLen in order to avoid the SysUtils unit, which would have
introduced overhead like exception handling code.}
function StrLen(const AStr: PAnsiChar): NativeUInt;
{$ifndef Use32BitAsm}
begin
Result := 0;
while AStr[Result] <> #0 do
Inc(Result);
end;
{$else}
asm
{Check the first byte}
cmp byte ptr [eax], 0
je @ZeroLength
{Get the negative of the string start in edx}
mov edx, eax
neg edx
{Word align}
add eax, 1
and eax, -2
@ScanLoop:
mov cx, [eax]
add eax, 2
test cl, ch
jnz @ScanLoop
test cl, cl
jz @ReturnLess2
test ch, ch
jnz @ScanLoop
lea eax, [eax + edx - 1]
ret
@ReturnLess2:
lea eax, [eax + edx - 2]
ret
@ZeroLength:
xor eax, eax
end;
{$endif}
{$ifdef EnableMMX}
{$ifndef ForceMMX}
{Returns true if the CPUID instruction is supported}
function CPUID_Supported: Boolean;
asm
pushfd
pop eax
mov edx, eax
xor eax, $200000
push eax
popfd
pushfd
pop eax
xor eax, edx
setnz al
end;
{Gets the CPUID}
function GetCPUID(AInfoRequired: Integer): TRegisters;
asm
push ebx
push esi
mov esi, edx
{cpuid instruction}
{$ifdef Delphi4or5}
db $0f, $a2
{$else}
cpuid
{$endif}
{Save registers}
mov TRegisters[esi].RegEAX, eax
mov TRegisters[esi].RegEBX, ebx
mov TRegisters[esi].RegECX, ecx
mov TRegisters[esi].RegEDX, edx
pop esi
pop ebx
end;
{Returns true if the CPU supports MMX}
function MMX_Supported: Boolean;
var
LReg: TRegisters;
begin
if CPUID_Supported then
begin
{Get the CPUID}
LReg := GetCPUID(1);
{Bit 23 must be set for MMX support}
Result := LReg.RegEDX and $800000 <> 0;
end
else
Result := False;
end;
{$endif}
{$endif}
{Compare [AAddress], CompareVal:
If Equal: [AAddress] := NewVal and result = CompareVal
If Unequal: Result := [AAddress]}
function LockCmpxchg(CompareVal, NewVal: Byte; AAddress: PByte): Byte;
asm
{$ifdef 32Bit}
{On entry:
al = CompareVal,
dl = NewVal,
ecx = AAddress}
{$ifndef LINUX}
lock cmpxchg [ecx], dl
{$else}
{Workaround for Kylix compiler bug}
db $F0, $0F, $B0, $11
{$endif}
{$else}
{On entry:
cl = CompareVal
dl = NewVal
r8 = AAddress}
.noframe
mov rax, rcx
lock cmpxchg [r8], dl
{$endif}
end;
{$ifndef ASMVersion}
{Gets the first set bit in the 32-bit number, returning the bit index}
function FindFirstSetBit(ACardinal: Cardinal): Cardinal;
asm
{$ifdef 64Bit}
.noframe
mov rax, rcx
{$endif}
bsf eax, eax
end;
{$endif}
{$ifdef MACOS}
function StrLCopy(Dest: PAnsiChar; const Source: PAnsiChar; MaxLen: Cardinal): PAnsiChar;
var
Len: Cardinal;
begin
Result := Dest;
Len := StrLen(Source);
if Len > MaxLen then
Len := MaxLen;
Move(Source^, Dest^, Len * SizeOf(AnsiChar));
Dest[Len] := #0;
end;
function GetModuleFileName(Module: HMODULE; Buffer: PAnsiChar; BufLen: Integer): Integer;
const
CUnknown: AnsiString = 'unknown';
var
tmp: array[0..512] of Char;
begin
if FastMMIsInstalled then
begin
Result := System.GetModuleFileName(Module, tmp, BufLen);
StrLCopy(Buffer, PAnsiChar(AnsiString(tmp)), BufLen);
end
else
begin
Result := Length(CUnknown);
StrLCopy(Buffer, Pointer(CUnknown), Result + 1);
end;
end;
const
INVALID_HANDLE_VALUE = THandle(-1);
function FileCreate(const FileName: string): THandle;
begin
Result := THandle(__open(PAnsiChar(UTF8String(FileName)), O_RDWR or O_CREAT or O_TRUNC or O_EXCL, FileAccessRights));
end;
{$endif}
{Writes the module filename to the specified buffer and returns the number of
characters written.}
function AppendModuleFileName(ABuffer: PAnsiChar): Integer;
var
LModuleHandle: HModule;
begin
{Get the module handle}
{$ifndef borlndmmdll}
if IsLibrary then
LModuleHandle := HInstance
else
{$endif}
LModuleHandle := 0;
{Get the module name}
{$ifndef POSIX}
Result := GetModuleFileNameA(LModuleHandle, ABuffer, 512);
{$else}
Result := GetModuleFileName(LModuleHandle, ABuffer, 512);
{$endif}
end;
{Copies the name of the module followed by the given string to the buffer,
returning the pointer following the buffer.}
function AppendStringToModuleName(AString, ABuffer: PAnsiChar): PAnsiChar;
var
LModuleNameLength: Cardinal;
LCopyStart: PAnsiChar;
begin
{Get the name of the application}
LModuleNameLength := AppendModuleFileName(ABuffer);
{Replace the last few characters}
if LModuleNameLength > 0 then
begin
{Find the last backslash}
LCopyStart := PAnsiChar(PByte(ABuffer) + LModuleNameLength - 1);
LModuleNameLength := 0;
while (UIntPtr(LCopyStart) >= UIntPtr(ABuffer))
and (LCopyStart^ <> '\') do
begin
Inc(LModuleNameLength);
Dec(LCopyStart);
end;
{Copy the name to the start of the buffer}
Inc(LCopyStart);
System.Move(LCopyStart^, ABuffer^, LModuleNameLength);
Inc(ABuffer, LModuleNameLength);
ABuffer^ := ':';
Inc(ABuffer);
ABuffer^ := ' ';
Inc(ABuffer);
end;
{Append the string}
while AString^ <> #0 do
begin
ABuffer^ := AString^;
Inc(ABuffer);
{Next char}
Inc(AString);
end;
ABuffer^ := #0;
Result := ABuffer;
end;
{----------------Faster Move Procedures-------------------}
{Fixed size move operations ignore the size parameter. All moves are assumed to
be non-overlapping.}
procedure Move4(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
mov eax, [eax]
mov [edx], eax
{$else}
.noframe
mov eax, [rcx]
mov [rdx], eax
{$endif}
end;
{$ifdef 64Bit}
procedure Move8(const ASource; var ADest; ACount: NativeInt);
asm
mov rax, [rcx]
mov [rdx], rax
end;
{$endif}
procedure Move12(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
mov ecx, [eax]
mov [edx], ecx
mov ecx, [eax + 4]
mov eax, [eax + 8]
mov [edx + 4], ecx
mov [edx + 8], eax
{$else}
.noframe
mov rax, [rcx]
mov ecx, [rcx + 8]
mov [rdx], rax
mov [rdx + 8], ecx
{$endif}
end;
procedure Move20(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
mov ecx, [eax]
mov [edx], ecx
mov ecx, [eax + 4]
mov [edx + 4], ecx
mov ecx, [eax + 8]
mov [edx + 8], ecx
mov ecx, [eax + 12]
mov eax, [eax + 16]
mov [edx + 12], ecx
mov [edx + 16], eax
{$else}
.noframe
movdqa xmm0, [rcx]
mov ecx, [rcx + 16]
movdqa [rdx], xmm0
mov [rdx + 16], ecx
{$endif}
end;
{$ifdef 64Bit}
procedure Move24(const ASource; var ADest; ACount: NativeInt);
asm
movdqa xmm0, [rcx]
mov r8, [rcx + 16]
movdqa [rdx], xmm0
mov [rdx + 16], r8
end;
{$endif}
procedure Move28(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
mov ecx, [eax]
mov [edx], ecx
mov ecx, [eax + 4]
mov [edx + 4], ecx
mov ecx, [eax + 8]
mov [edx + 8], ecx
mov ecx, [eax + 12]
mov [edx + 12], ecx
mov ecx, [eax + 16]
mov [edx + 16], ecx
mov ecx, [eax + 20]
mov eax, [eax + 24]
mov [edx + 20], ecx
mov [edx + 24], eax
{$else}
.noframe
movdqa xmm0, [rcx]
mov r8, [rcx + 16]
mov ecx, [rcx + 24]
movdqa [rdx], xmm0
mov [rdx + 16], r8
mov [rdx + 24], ecx
{$endif}
end;
procedure Move36(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
fild qword ptr [eax]
fild qword ptr [eax + 8]
fild qword ptr [eax + 16]
fild qword ptr [eax + 24]
mov ecx, [eax + 32]
mov [edx + 32], ecx
fistp qword ptr [edx + 24]
fistp qword ptr [edx + 16]
fistp qword ptr [edx + 8]
fistp qword ptr [edx]
{$else}
.noframe
movdqa xmm0, [rcx]
movdqa xmm1, [rcx + 16]
mov ecx, [rcx + 32]
movdqa [rdx], xmm0
movdqa [rdx + 16], xmm1
mov [rdx + 32], ecx
{$endif}
end;
{$ifdef 64Bit}
procedure Move40(const ASource; var ADest; ACount: NativeInt);
asm
movdqa xmm0, [rcx]
movdqa xmm1, [rcx + 16]
mov r8, [rcx + 32]
movdqa [rdx], xmm0
movdqa [rdx + 16], xmm1
mov [rdx + 32], r8
end;
{$endif}
procedure Move44(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
fild qword ptr [eax]
fild qword ptr [eax + 8]
fild qword ptr [eax + 16]
fild qword ptr [eax + 24]
fild qword ptr [eax + 32]
mov ecx, [eax + 40]
mov [edx + 40], ecx
fistp qword ptr [edx + 32]
fistp qword ptr [edx + 24]
fistp qword ptr [edx + 16]
fistp qword ptr [edx + 8]
fistp qword ptr [edx]
{$else}
.noframe
movdqa xmm0, [rcx]
movdqa xmm1, [rcx + 16]
mov r8, [rcx + 32]
mov ecx, [rcx + 40]
movdqa [rdx], xmm0
movdqa [rdx + 16], xmm1
mov [rdx + 32], r8
mov [rdx + 40], ecx
{$endif}
end;
procedure Move52(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
fild qword ptr [eax]
fild qword ptr [eax + 8]
fild qword ptr [eax + 16]
fild qword ptr [eax + 24]
fild qword ptr [eax + 32]
fild qword ptr [eax + 40]
mov ecx, [eax + 48]
mov [edx + 48], ecx
fistp qword ptr [edx + 40]
fistp qword ptr [edx + 32]
fistp qword ptr [edx + 24]
fistp qword ptr [edx + 16]
fistp qword ptr [edx + 8]
fistp qword ptr [edx]
{$else}
.noframe
movdqa xmm0, [rcx]
movdqa xmm1, [rcx + 16]
movdqa xmm2, [rcx + 32]
mov ecx, [rcx + 48]
movdqa [rdx], xmm0
movdqa [rdx + 16], xmm1
movdqa [rdx + 32], xmm2
mov [rdx + 48], ecx
{$endif}
end;
{$ifdef 64Bit}
procedure Move56(const ASource; var ADest; ACount: NativeInt);
asm
movdqa xmm0, [rcx]
movdqa xmm1, [rcx + 16]
movdqa xmm2, [rcx + 32]
mov r8, [rcx + 48]
movdqa [rdx], xmm0
movdqa [rdx + 16], xmm1
movdqa [rdx + 32], xmm2
mov [rdx + 48], r8
end;
{$endif}
procedure Move60(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
fild qword ptr [eax]
fild qword ptr [eax + 8]
fild qword ptr [eax + 16]
fild qword ptr [eax + 24]
fild qword ptr [eax + 32]
fild qword ptr [eax + 40]
fild qword ptr [eax + 48]
mov ecx, [eax + 56]
mov [edx + 56], ecx
fistp qword ptr [edx + 48]
fistp qword ptr [edx + 40]
fistp qword ptr [edx + 32]
fistp qword ptr [edx + 24]
fistp qword ptr [edx + 16]
fistp qword ptr [edx + 8]
fistp qword ptr [edx]
{$else}
.noframe
movdqa xmm0, [rcx]
movdqa xmm1, [rcx + 16]
movdqa xmm2, [rcx + 32]
mov r8, [rcx + 48]
mov ecx, [rcx + 56]
movdqa [rdx], xmm0
movdqa [rdx + 16], xmm1
movdqa [rdx + 32], xmm2
mov [rdx + 48], r8
mov [rdx + 56], ecx
{$endif}
end;
procedure Move68(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
fild qword ptr [eax]
fild qword ptr [eax + 8]
fild qword ptr [eax + 16]
fild qword ptr [eax + 24]
fild qword ptr [eax + 32]
fild qword ptr [eax + 40]
fild qword ptr [eax + 48]
fild qword ptr [eax + 56]
mov ecx, [eax + 64]
mov [edx + 64], ecx
fistp qword ptr [edx + 56]
fistp qword ptr [edx + 48]
fistp qword ptr [edx + 40]
fistp qword ptr [edx + 32]
fistp qword ptr [edx + 24]
fistp qword ptr [edx + 16]
fistp qword ptr [edx + 8]
fistp qword ptr [edx]
{$else}
.noframe
movdqa xmm0, [rcx]
movdqa xmm1, [rcx + 16]
movdqa xmm2, [rcx + 32]
movdqa xmm3, [rcx + 48]
mov ecx, [rcx + 64]
movdqa [rdx], xmm0
movdqa [rdx + 16], xmm1
movdqa [rdx + 32], xmm2
movdqa [rdx + 48], xmm3
mov [rdx + 64], ecx
{$endif}
end;
{Variable size move procedure: Rounds ACount up to the next multiple of 16 less
SizeOf(Pointer). Important note: Always moves at least 16 - SizeOf(Pointer)
bytes (the minimum small block size with 16 byte alignment), irrespective of
ACount.}
procedure MoveX16LP(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
{Make the counter negative based: The last 12 bytes are moved separately}
sub ecx, 12
add eax, ecx
add edx, ecx
{$ifdef EnableMMX}
{$ifndef ForceMMX}
cmp UseMMX, True
jne @FPUMove
{$endif}
{Make the counter negative based: The last 12 bytes are moved separately}
neg ecx
jns @MMXMoveLast12
@MMXMoveLoop:
{Move a 16 byte block}
{$ifdef Delphi4or5}
{Delphi 5 compatibility}
db $0f, $6f, $04, $01
db $0f, $6f, $4c, $01, $08
db $0f, $7f, $04, $11
db $0f, $7f, $4c, $11, $08
{$else}
movq mm0, [eax + ecx]
movq mm1, [eax + ecx + 8]
movq [edx + ecx], mm0
movq [edx + ecx + 8], mm1
{$endif}
{Are there another 16 bytes to move?}
add ecx, 16
js @MMXMoveLoop
@MMXMoveLast12:
{Do the last 12 bytes}
{$ifdef Delphi4or5}
{Delphi 5 compatibility}
db $0f, $6f, $04, $01
{$else}
movq mm0, [eax + ecx]
{$endif}
mov eax, [eax + ecx + 8]
{$ifdef Delphi4or5}
{Delphi 5 compatibility}
db $0f, $7f, $04, $11
{$else}
movq [edx + ecx], mm0
{$endif}
mov [edx + ecx + 8], eax
{Exit MMX state}
{$ifdef Delphi4or5}
{Delphi 5 compatibility}
db $0f, $77
{$else}
emms
{$endif}
{$ifndef ForceMMX}
ret
{$endif}
{$endif}
{FPU code is only used if MMX is not forced}
{$ifndef ForceMMX}
@FPUMove:
neg ecx
jns @FPUMoveLast12
@FPUMoveLoop:
{Move a 16 byte block}
fild qword ptr [eax + ecx]
fild qword ptr [eax + ecx + 8]
fistp qword ptr [edx + ecx + 8]
fistp qword ptr [edx + ecx]
{Are there another 16 bytes to move?}
add ecx, 16
js @FPUMoveLoop
@FPUMoveLast12:
{Do the last 12 bytes}
fild qword ptr [eax + ecx]
fistp qword ptr [edx + ecx]
mov eax, [eax + ecx + 8]
mov [edx + ecx + 8], eax
{$endif}
{$else}
.noframe
{Make the counter negative based: The last 8 bytes are moved separately}
sub r8, 8
add rcx, r8
add rdx, r8
neg r8
jns @MoveLast12
@MoveLoop:
{Move a 16 byte block}
movdqa xmm0, [rcx + r8]
movdqa [rdx + r8], xmm0
{Are there another 16 bytes to move?}
add r8, 16
js @MoveLoop
@MoveLast12:
{Do the last 8 bytes}
mov r9, [rcx + r8]
mov [rdx + r8], r9
{$endif}
end;
{Variable size move procedure: Rounds ACount up to the next multiple of 8 less
SizeOf(Pointer). Important note: Always moves at least 8 - SizeOf(Pointer)
bytes (the minimum small block size with 8 byte alignment), irrespective of
ACount.}
procedure MoveX8LP(const ASource; var ADest; ACount: NativeInt);
asm
{$ifdef 32Bit}
{Make the counter negative based: The last 4 bytes are moved separately}
sub ecx, 4
{4 bytes or less? -> Use the Move4 routine.}
jle @FourBytesOrLess
add eax, ecx
add edx, ecx
neg ecx
{$ifdef EnableMMX}
{$ifndef ForceMMX}
cmp UseMMX, True
jne @FPUMoveLoop
{$endif}
@MMXMoveLoop:
{Move an 8 byte block}
{$ifdef Delphi4or5}
{Delphi 5 compatibility}
db $0f, $6f, $04, $01
db $0f, $7f, $04, $11
{$else}
movq mm0, [eax + ecx]
movq [edx + ecx], mm0
{$endif}
{Are there another 8 bytes to move?}
add ecx, 8
js @MMXMoveLoop
{Exit MMX state}
{$ifdef Delphi4or5}
{Delphi 5 compatibility}
db $0f, $77
{$else}
emms
{$endif}
{Do the last 4 bytes}
mov eax, [eax + ecx]
mov [edx + ecx], eax
ret
{$endif}
{FPU code is only used if MMX is not forced}
{$ifndef ForceMMX}
@FPUMoveLoop:
{Move an 8 byte block}
fild qword ptr [eax + ecx]
fistp qword ptr [edx + ecx]
{Are there another 8 bytes to move?}
add ecx, 8
js @FPUMoveLoop
{Do the last 4 bytes}
mov eax, [eax + ecx]
mov [edx + ecx], eax
ret
{$endif}
@FourBytesOrLess:
{Four or less bytes to move}
mov eax, [eax]
mov [edx], eax
{$else}
.noframe
{Make the counter negative based}
add rcx, r8
add rdx, r8
neg r8
@MoveLoop:
{Move an 8 byte block}
mov r9, [rcx + r8]
mov [rdx + r8], r9
{Are there another 8 bytes to move?}
add r8, 8
js @MoveLoop
{$endif}
end;
{----------------Windows Emulation Functions for Kylix / OS X Support-----------------}
{$ifdef POSIX}
const
{Messagebox constants}
MB_OK = 0;
MB_ICONERROR = $10;
MB_TASKMODAL = $2000;
MB_DEFAULT_DESKTOP_ONLY = $20000;
{Virtual memory constants}
MEM_COMMIT = $1000;
MEM_RELEASE = $8000;
MEM_TOP_DOWN = $100000;
PAGE_READWRITE = 4;
procedure MessageBoxA(hWnd: Cardinal; AMessageText, AMessageTitle: PAnsiChar; uType: Cardinal); stdcall;
begin
if FastMMIsInstalled then
writeln(AMessageText)
else
__write(STDERR_FILENO, AMessageText, StrLen(AMessageText));
end;
function VirtualAlloc(lpvAddress: Pointer; dwSize, flAllocationType, flProtect: Cardinal): Pointer; stdcall;
begin
Result := valloc(dwSize);
end;
function VirtualFree(lpAddress: Pointer; dwSize, dwFreeType: Cardinal): LongBool; stdcall;
begin
free(lpAddress);
Result := True;
end;
function WriteFile(hFile: THandle; const Buffer; nNumberOfBytesToWrite: Cardinal;
var lpNumberOfBytesWritten: Cardinal; lpOverlapped: Pointer): Boolean; stdcall;
begin
lpNumberOfBytesWritten := __write(hFile, @Buffer, nNumberOfBytesToWrite);
if lpNumberOfBytesWritten = Cardinal(-1) then
begin
lpNumberOfBytesWritten := 0;
Result := False;
end
else
Result := True;
end;
{$ifndef NeverSleepOnThreadContention}
procedure Sleep(dwMilliseconds: Cardinal); stdcall;
begin
{Convert to microseconds (more or less)}
usleep(dwMilliseconds shl 10);
end;
{$endif}
{$endif}
{-----------------Debugging Support Functions and Procedures------------------}
{$ifdef FullDebugMode}
{Returns the current thread ID}
function GetThreadID: Cardinal;
{$ifdef 32Bit}
asm
mov eax, FS:[$24]
end;
{$else}
begin
Result := GetCurrentThreadId;
end;
{$endif}
{Fills a block of memory with the given dword (32-bit) or qword (64-bit).
Always fills a multiple of SizeOf(Pointer) bytes}
procedure DebugFillMem(var AAddress; AByteCount: NativeInt; AFillValue: NativeUInt);
asm
{$ifdef 32Bit}
{On Entry:
eax = AAddress
edx = AByteCount
ecx = AFillValue}
add eax, edx
neg edx
jns @Done
@FillLoop:
mov [eax + edx], ecx
add edx, 4
js @FillLoop
@Done:
{$else}
{On Entry:
rcx = AAddress
rdx = AByteCount
r8 = AFillValue}
add rcx, rdx
neg rdx
jns @Done
@FillLoop:
mov [rcx + rdx], r8
add rdx, 8
js @FillLoop
@Done:
{$endif}
end;
{$ifndef LoadDebugDLLDynamically}
{The stack trace procedure. The stack trace module is external since it may
raise handled access violations that result in the creation of exception
objects and the stack trace code is not re-entrant.}
procedure GetStackTrace(AReturnAddresses: PNativeUInt;
AMaxDepth, ASkipFrames: Cardinal); external FullDebugModeLibraryName
name {$ifdef RawStackTraces}'GetRawStackTrace'{$else}'GetFrameBasedStackTrace'{$endif};
{The exported procedure in the FastMM_FullDebugMode.dll library used to convert
the return addresses of a stack trace to a text string.}
function LogStackTrace(AReturnAddresses: PNativeUInt;
AMaxDepth: Cardinal; ABuffer: PAnsiChar): PAnsiChar; external FullDebugModeLibraryName
name 'LogStackTrace';
{$else}
{Default no-op stack trace and logging handlers}
procedure NoOpGetStackTrace(AReturnAddresses: PNativeUInt;
AMaxDepth, ASkipFrames: Cardinal);
begin
DebugFillMem(AReturnAddresses^, AMaxDepth * SizeOf(Pointer), 0);
end;
function NoOpLogStackTrace(AReturnAddresses: PNativeUInt;
AMaxDepth: Cardinal; ABuffer: PAnsiChar): PAnsiChar;
begin
Result := ABuffer;
end;
var
{Handle to the FullDebugMode DLL}
FullDebugModeDLL: HMODULE;
GetStackTrace: procedure (AReturnAddresses: PNativeUInt;
AMaxDepth, ASkipFrames: Cardinal) = NoOpGetStackTrace;
LogStackTrace: function (AReturnAddresses: PNativeUInt;
AMaxDepth: Cardinal; ABuffer: PAnsiChar): PAnsiChar = NoOpLogStackTrace;
{$endif}
{$endif}
{$ifndef POSIX}
function DelphiIsRunning: Boolean;
begin
Result := FindWindowA('TAppBuilder', nil) <> 0;
end;
{$endif}
{Converts an unsigned integer to string at the buffer location, returning the
new buffer position. Note: The 32-bit asm version only supports numbers up to
2^31 - 1.}
function NativeUIntToStrBuf(ANum: NativeUInt; APBuffer: PAnsiChar): PAnsiChar;
{$ifndef Use32BitAsm}
const
MaxDigits = 20;
var
LDigitBuffer: array[0..MaxDigits - 1] of AnsiChar;
LCount: Cardinal;
LDigit: NativeUInt;
begin
{Generate the digits in the local buffer}
LCount := 0;
repeat
LDigit := ANum;
ANum := ANum div 10;
LDigit := LDigit - ANum * 10;
Inc(LCount);
LDigitBuffer[MaxDigits - LCount] := AnsiChar(Ord('0') + LDigit);
until ANum = 0;
{Copy the digits to the output buffer and advance it}
System.Move(LDigitBuffer[MaxDigits - LCount], APBuffer^, LCount);
Result := APBuffer + LCount;
end;
{$else}
asm
{On entry: eax = ANum, edx = ABuffer}
push edi
mov edi, edx //Pointer to the first character in edi
{Calculate leading digit: divide the number by 1e9}
add eax, 1 //Increment the number
mov edx, $89705F41 //1e9 reciprocal
mul edx //Multplying with reciprocal
shr eax, 30 //Save fraction bits
mov ecx, edx //First digit in bits <31:29>
and edx, $1FFFFFFF //Filter fraction part edx<28:0>
shr ecx, 29 //Get leading digit into accumulator
lea edx, [edx + 4 * edx] //Calculate ...
add edx, eax //... 5*fraction
mov eax, ecx //Copy leading digit
or eax, '0' //Convert digit to ASCII
mov [edi], al //Store digit out to memory
{Calculate digit #2}
mov eax, edx //Point format such that 1.0 = 2^28
cmp ecx, 1 //Any non-zero digit yet ?
sbb edi, -1 //Yes->increment ptr, No->keep old ptr
shr eax, 28 //Next digit
and edx, $0fffffff //Fraction part edx<27:0>
or ecx, eax //Accumulate next digit
or eax, '0' //Convert digit to ASCII
mov [edi], al //Store digit out to memory
{Calculate digit #3}
lea eax, [edx * 4 + edx] //5*fraction, new digit eax<31:27>
lea edx, [edx * 4 + edx] //5*fraction, new fraction edx<26:0>
cmp ecx, 1 //Any non-zero digit yet ?
sbb edi, -1 //Yes->increment ptr, No->keep old ptr
shr eax, 27 //Next digit
and edx, $07ffffff //Fraction part
or ecx, eax //Accumulate next digit
or eax, '0' //Convert digit to ASCII
mov [edi], al //Store digit out to memory
{Calculate digit #4}
lea eax, [edx * 4 + edx] //5*fraction, new digit eax<31:26>
lea edx, [edx * 4 + edx] //5*fraction, new fraction edx<25:0>
cmp ecx, 1 //Any non-zero digit yet ?
sbb edi, -1 //Yes->increment ptr, No->keep old ptr
shr eax, 26 //Next digit
and edx, $03ffffff //Fraction part
or ecx, eax //Accumulate next digit
or eax, '0' //Convert digit to ASCII
mov [edi], al //Store digit out to memory
{Calculate digit #5}
lea eax, [edx * 4 + edx] //5*fraction, new digit eax<31:25>
lea edx, [edx * 4 + edx] //5*fraction, new fraction edx<24:0>
cmp ecx, 1 //Any non-zero digit yet ?
sbb edi, -1 //Yes->increment ptr, No->keep old ptr
shr eax, 25 //Next digit
and edx, $01ffffff //Fraction part
or ecx, eax //Accumulate next digit
or eax, '0' //Convert digit to ASCII
mov [edi], al //Store digit out to memory
{Calculate digit #6}
lea eax, [edx * 4 + edx] //5*fraction, new digit eax<31:24>
lea edx, [edx * 4 + edx] //5*fraction, new fraction edx<23:0>
cmp ecx, 1 //Any non-zero digit yet ?
sbb edi, -1 //Yes->increment ptr, No->keep old ptr
shr eax, 24 //Next digit
and edx, $00ffffff //Fraction part
or ecx, eax //Accumulate next digit
or eax, '0' //Convert digit to ASCII
mov [edi], al //Store digit out to memory
{Calculate digit #7}
lea eax, [edx * 4 + edx] //5*fraction, new digit eax<31:23>
lea edx, [edx * 4 + edx] //5*fraction, new fraction edx<31:23>
cmp ecx, 1 //Any non-zero digit yet ?
sbb edi, -1 //Yes->increment ptr, No->keep old ptr
shr eax, 23 //Next digit
and edx, $007fffff //Fraction part
or ecx, eax //Accumulate next digit
or eax, '0' //Convert digit to ASCII
mov [edi], al //Store digit out to memory
{Calculate digit #8}
lea eax, [edx * 4 + edx] //5*fraction, new digit eax<31:22>
lea edx, [edx * 4 + edx] //5*fraction, new fraction edx<22:0>
cmp ecx, 1 //Any non-zero digit yet ?
sbb edi, -1 //Yes->increment ptr, No->keep old ptr
shr eax, 22 //Next digit
and edx, $003fffff //Fraction part
or ecx, eax //Accumulate next digit
or eax, '0' //Convert digit to ASCII
mov [edi], al //Store digit out to memory
{Calculate digit #9}
lea eax, [edx * 4 + edx] //5*fraction, new digit eax<31:21>
lea edx, [edx * 4 + edx] //5*fraction, new fraction edx<21:0>
cmp ecx, 1 //Any non-zero digit yet ?
sbb edi, -1 //Yes->increment ptr, No->keep old ptr
shr eax, 21 //Next digit
and edx, $001fffff //Fraction part
or ecx, eax //Accumulate next digit
or eax, '0' //Convert digit to ASCII
mov [edi], al //Store digit out to memory
{Calculate digit #10}
lea eax, [edx * 4 + edx] //5*fraction, new digit eax<31:20>
cmp ecx, 1 //Any-non-zero digit yet ?
sbb edi, -1 //Yes->increment ptr, No->keep old ptr
shr eax, 20 //Next digit
or eax, '0' //Convert digit to ASCII
mov [edi], al //Store last digit and end marker out to memory
{Return a pointer to the next character}
lea eax, [edi + 1]
{Restore edi}
pop edi
end;
{$endif}
{Converts an unsigned integer to a hexadecimal string at the buffer location,
returning the new buffer position.}
function NativeUIntToHexBuf(ANum: NativeUInt; APBuffer: PAnsiChar): PAnsiChar;
{$ifndef Use32BitAsm}
const
MaxDigits = 16;
var
LDigitBuffer: array[0..MaxDigits - 1] of AnsiChar;
LCount: Cardinal;
LDigit: NativeUInt;
begin
{Generate the digits in the local buffer}
LCount := 0;
repeat
LDigit := ANum;
ANum := ANum div 16;
LDigit := LDigit - ANum * 16;
Inc(LCount);
LDigitBuffer[MaxDigits - LCount] := HexTable[LDigit];
until ANum = 0;
{Copy the digits to the output buffer and advance it}
System.Move(LDigitBuffer[MaxDigits - LCount], APBuffer^, LCount);
Result := APBuffer + LCount;
end;
{$else}
asm
{On entry:
eax = ANum
edx = ABuffer}
push ebx
push edi
{Save ANum in ebx}
mov ebx, eax
{Get a pointer to the first character in edi}
mov edi, edx
{Get the number in ecx as well}
mov ecx, eax
{Keep the low nibbles in ebx and the high nibbles in ecx}
and ebx, $0f0f0f0f
and ecx, $f0f0f0f0
{Swap the bytes into the right order}
ror ebx, 16
ror ecx, 20
{Get nibble 7}
movzx eax, ch
mov dl, ch
mov al, byte ptr HexTable[eax]
mov [edi], al
cmp dl, 1
sbb edi, -1
{Get nibble 6}
movzx eax, bh
or dl, bh
mov al, byte ptr HexTable[eax]
mov [edi], al
cmp dl, 1
sbb edi, -1
{Get nibble 5}
movzx eax, cl
or dl, cl
mov al, byte ptr HexTable[eax]
mov [edi], al
cmp dl, 1
sbb edi, -1
{Get nibble 4}
movzx eax, bl
or dl, bl
mov al, byte ptr HexTable[eax]
mov [edi], al
cmp dl, 1
sbb edi, -1
{Rotate ecx and ebx so we get access to the rest}
shr ebx, 16
shr ecx, 16
{Get nibble 3}
movzx eax, ch
or dl, ch
mov al, byte ptr HexTable[eax]
mov [edi], al
cmp dl, 1
sbb edi, -1
{Get nibble 2}
movzx eax, bh
or dl, bh
mov al, byte ptr HexTable[eax]
mov [edi], al
cmp dl, 1
sbb edi, -1
{Get nibble 1}
movzx eax, cl
or dl, cl
mov al, byte ptr HexTable[eax]
mov [edi], al
cmp dl, 1
sbb edi, -1
{Get nibble 0}
movzx eax, bl
mov al, byte ptr HexTable[eax]
mov [edi], al
{Return a pointer to the end of the string}
lea eax, [edi + 1]
{Restore registers}
pop edi
pop ebx
end;
{$endif}
{Appends the source text to the destination and returns the new destination
position}
function AppendStringToBuffer(const ASource, ADestination: PAnsiChar; ACount: Cardinal): PAnsiChar;
begin
System.Move(ASource^, ADestination^, ACount);
Result := Pointer(PByte(ADestination) + ACount);
end;
{Appends the name of the class to the destination buffer and returns the new
destination position}
function AppendClassNameToBuffer(AClass: TClass; ADestination: PAnsiChar): PAnsiChar;
var
LPClassName: PShortString;
begin
{Get a pointer to the class name}
if AClass <> nil then
begin
LPClassName := PShortString(PPointer(PByte(AClass) + vmtClassName)^);
{Append the class name}
Result := AppendStringToBuffer(@LPClassName^[1], ADestination, Length(LPClassName^));
end
else
begin
Result := AppendStringToBuffer(UnknownClassNameMsg, ADestination, Length(UnknownClassNameMsg));
end;
end;
{Shows a message box if the program is not showing one already.}
procedure ShowMessageBox(AText, ACaption: PAnsiChar);
begin
if (not ShowingMessageBox) and (not SuppressMessageBoxes) then
begin
ShowingMessageBox := True;
MessageBoxA(0, AText, ACaption,
MB_OK or MB_ICONERROR or MB_TASKMODAL or MB_DEFAULT_DESKTOP_ONLY);
ShowingMessageBox := False;
end;
end;
{Returns the class for a memory block. Returns nil if it is not a valid class}
function DetectClassInstance(APointer: Pointer): TClass;
{$ifndef POSIX}
var
LMemInfo: TMemoryBasicInformation;
{Checks whether the given address is a valid address for a VMT entry.}
function IsValidVMTAddress(APAddress: Pointer): Boolean;
begin
{Do some basic pointer checks: Must be dword aligned and beyond 64K}
if (UIntPtr(APAddress) > 65535)
and (UIntPtr(APAddress) and 3 = 0) then
begin
{Do we need to recheck the virtual memory?}
if (UIntPtr(LMemInfo.BaseAddress) > UIntPtr(APAddress))
or ((UIntPtr(LMemInfo.BaseAddress) + LMemInfo.RegionSize) < (UIntPtr(APAddress) + 4)) then
begin
{Get the VM status for the pointer}
LMemInfo.RegionSize := 0;
VirtualQuery(APAddress, LMemInfo, SizeOf(LMemInfo));
end;
{Check the readability of the memory address}
Result := (LMemInfo.RegionSize >= 4)
and (LMemInfo.State = MEM_COMMIT)
and (LMemInfo.Protect and (PAGE_READONLY or PAGE_READWRITE or PAGE_EXECUTE or PAGE_EXECUTE_READ or PAGE_EXECUTE_READWRITE or PAGE_EXECUTE_WRITECOPY) <> 0)
and (LMemInfo.Protect and PAGE_GUARD = 0);
end
else
Result := False;
end;
{Returns true if AClassPointer points to a class VMT}
function InternalIsValidClass(AClassPointer: Pointer; ADepth: Integer = 0): Boolean;
var
LParentClassSelfPointer: PPointer;
begin
{Check that the self pointer as well as parent class self pointer addresses
are valid}
if (ADepth < 1000)
and IsValidVMTAddress(Pointer(PByte(AClassPointer) + vmtSelfPtr))
and IsValidVMTAddress(Pointer(PByte(AClassPointer) + vmtParent)) then
begin
{Get a pointer to the parent class' self pointer}
LParentClassSelfPointer := PPointer(PByte(AClassPointer) + vmtParent)^;
{Check that the self pointer as well as the parent class is valid}
Result := (PPointer(PByte(AClassPointer) + vmtSelfPtr)^ = AClassPointer)
and ((LParentClassSelfPointer = nil)
or (IsValidVMTAddress(LParentClassSelfPointer)
and InternalIsValidClass(LParentClassSelfPointer^, ADepth + 1)));
end
else
Result := False;
end;
begin
{Get the class pointer from the (suspected) object}
Result := TClass(PPointer(APointer)^);
{No VM info yet}
LMemInfo.RegionSize := 0;
{Check the block}
if (not InternalIsValidClass(Pointer(Result), 0))
{$ifdef FullDebugMode}
or (Result = @FreedObjectVMT.VMTMethods[0])
{$endif}
then
Result := nil;
end;
{$else}
begin
{Not currently supported under Linux / OS X}
Result := nil;
end;
{$endif}
{Gets the available size inside a block}
function GetAvailableSpaceInBlock(APointer: Pointer): NativeUInt;
var
LBlockHeader: NativeUInt;
LPSmallBlockPool: PSmallBlockPoolHeader;
begin
LBlockHeader := PNativeUInt(PByte(APointer) - BlockHeaderSize)^;
if LBlockHeader and (IsMediumBlockFlag or IsLargeBlockFlag) = 0 then
begin
LPSmallBlockPool := PSmallBlockPoolHeader(LBlockHeader and DropSmallFlagsMask);
Result := LPSmallBlockPool.BlockType.BlockSize - BlockHeaderSize;
end
else
begin
Result := (LBlockHeader and DropMediumAndLargeFlagsMask) - BlockHeaderSize;
if (LBlockHeader and IsMediumBlockFlag) = 0 then
Dec(Result, LargeBlockHeaderSize);
end;
end;
{-----------------Small Block Management------------------}
{Locks all small block types}
procedure LockAllSmallBlockTypes;
var
LInd: Cardinal;
begin
{Lock the medium blocks}
{$ifndef AssumeMultiThreaded}
if IsMultiThread then
{$endif}
begin
for LInd := 0 to NumSmallBlockTypes - 1 do
begin
while LockCmpxchg(0, 1, @SmallBlockTypes[LInd].BlockTypeLocked) <> 0 do
begin
{$ifdef NeverSleepOnThreadContention}
{$ifdef UseSwitchToThread}
SwitchToThread;
{$endif}
{$else}
Sleep(InitialSleepTime);
if LockCmpxchg(0, 1, @SmallBlockTypes[LInd].BlockTypeLocked) = 0 then
Break;
Sleep(AdditionalSleepTime);
{$endif}
end;
end;
end;
end;
{Gets the first and last block pointer for a small block pool}
procedure GetFirstAndLastSmallBlockInPool(APSmallBlockPool: PSmallBlockPoolHeader;
var AFirstPtr, ALastPtr: Pointer);
var
LBlockSize: NativeUInt;
begin
{Get the pointer to the first block}
AFirstPtr := Pointer(PByte(APSmallBlockPool) + SmallBlockPoolHeaderSize);
{Get a pointer to the last block}
if (APSmallBlockPool.BlockType.CurrentSequentialFeedPool <> APSmallBlockPool)
or (UIntPtr(APSmallBlockPool.BlockType.NextSequentialFeedBlockAddress) > UIntPtr(APSmallBlockPool.BlockType.MaxSequentialFeedBlockAddress)) then
begin
{Not the sequential feed - point to the end of the block}
LBlockSize := PNativeUInt(PByte(APSmallBlockPool) - BlockHeaderSize)^ and DropMediumAndLargeFlagsMask;
ALastPtr := Pointer(PByte(APSmallBlockPool) + LBlockSize - APSmallBlockPool.BlockType.BlockSize);
end
else
begin
{The sequential feed pool - point to before the next sequential feed block}
ALastPtr := Pointer(PByte(APSmallBlockPool.BlockType.NextSequentialFeedBlockAddress) - 1);
end;
end;
{-----------------Medium Block Management------------------}
{Advances to the next medium block. Returns nil if the end of the medium block
pool has been reached}
function NextMediumBlock(APMediumBlock: Pointer): Pointer;
var
LBlockSize: NativeUInt;
begin
{Get the size of this block}
LBlockSize := PNativeUInt(PByte(APMediumBlock) - BlockHeaderSize)^ and DropMediumAndLargeFlagsMask;
{Advance the pointer}
Result := Pointer(PByte(APMediumBlock) + LBlockSize);
{Is the next block the end of medium pool marker?}
LBlockSize := PNativeUInt(PByte(Result) - BlockHeaderSize)^ and DropMediumAndLargeFlagsMask;
if LBlockSize = 0 then
Result := nil;
end;
{Gets the first medium block in the medium block pool}
function GetFirstMediumBlockInPool(APMediumBlockPoolHeader: PMediumBlockPoolHeader): Pointer;
begin
if (MediumSequentialFeedBytesLeft = 0)
or (UIntPtr(LastSequentiallyFedMediumBlock) < UIntPtr(APMediumBlockPoolHeader))
or (UIntPtr(LastSequentiallyFedMediumBlock) > UIntPtr(APMediumBlockPoolHeader) + MediumBlockPoolSize) then
begin
Result := Pointer(PByte(APMediumBlockPoolHeader) + MediumBlockPoolHeaderSize);
end
else
begin
{Is the sequential feed pool empty?}
if MediumSequentialFeedBytesLeft <> MediumBlockPoolSize - MediumBlockPoolHeaderSize then
Result := LastSequentiallyFedMediumBlock
else
Result := nil;
end;
end;
{Locks the medium blocks. Note that the 32-bit asm version is assumed to
preserve all registers except eax.}
{$ifndef Use32BitAsm}
procedure LockMediumBlocks;
begin
{Lock the medium blocks}
{$ifndef AssumeMultiThreaded}
if IsMultiThread then
{$endif}
begin
while LockCmpxchg(0, 1, @MediumBlocksLocked) <> 0 do
begin
{$ifdef NeverSleepOnThreadContention}
{$ifdef UseSwitchToThread}
SwitchToThread;
{$endif}
{$else}
Sleep(InitialSleepTime);
if LockCmpxchg(0, 1, @MediumBlocksLocked) = 0 then
Break;
Sleep(AdditionalSleepTime);
{$endif}
end;
end;
end;
{$else}
procedure LockMediumBlocks;
asm
{Note: This routine is assumed to preserve all registers except eax}
@MediumBlockLockLoop:
mov eax, $100
{Attempt to lock the medium blocks}
lock cmpxchg MediumBlocksLocked, ah
je @Done
{$ifdef NeverSleepOnThreadContention}
{Pause instruction (improves performance on P4)}
rep nop
{$ifdef UseSwitchToThread}
push ecx
push edx
call SwitchToThread
pop edx
pop ecx
{$endif}
{Try again}
jmp @MediumBlockLockLoop
{$else}
{Couldn't lock the medium blocks - sleep and try again}
push ecx
push edx
push InitialSleepTime
call Sleep
pop edx
pop ecx
{Try again}
mov eax, $100
{Attempt to grab the block type}
lock cmpxchg MediumBlocksLocked, ah
je @Done
{Couldn't lock the medium blocks - sleep and try again}
push ecx
push edx
push AdditionalSleepTime
call Sleep
pop edx
pop ecx
{Try again}
jmp @MediumBlockLockLoop
{$endif}
@Done:
end;
{$endif}
{Removes a medium block from the circular linked list of free blocks.
Does not change any header flags. Medium blocks should be locked
before calling this procedure.}
procedure RemoveMediumFreeBlock(APMediumFreeBlock: PMediumFreeBlock);
{$ifndef ASMVersion}
var
LPreviousFreeBlock, LNextFreeBlock: PMediumFreeBlock;
LBinNumber, LBinGroupNumber: Cardinal;
begin
{Get the current previous and next blocks}
LNextFreeBlock := APMediumFreeBlock.NextFreeBlock;
LPreviousFreeBlock := APMediumFreeBlock.PreviousFreeBlock;
{Remove this block from the linked list}
LPreviousFreeBlock.NextFreeBlock := LNextFreeBlock;
LNextFreeBlock.PreviousFreeBlock := LPreviousFreeBlock;
{Is this bin now empty? If the previous and next free block pointers are
equal, they must point to the bin.}
if LPreviousFreeBlock = LNextFreeBlock then
begin
{Get the bin number for this block size}
LBinNumber := (UIntPtr(LNextFreeBlock) - UIntPtr(@MediumBlockBins)) div SizeOf(TMediumFreeBlock);
LBinGroupNumber := LBinNumber div 32;
{Flag this bin as empty}
MediumBlockBinBitmaps[LBinGroupNumber] := MediumBlockBinBitmaps[LBinGroupNumber]
and (not (1 shl (LBinNumber and 31)));
{Is the group now entirely empty?}
if MediumBlockBinBitmaps[LBinGroupNumber] = 0 then
begin
{Flag this group as empty}
MediumBlockBinGroupBitmap := MediumBlockBinGroupBitmap
and (not (1 shl LBinGroupNumber));
end;
end;
end;
{$else}
{$ifdef 32Bit}
asm
{On entry: eax = APMediumFreeBlock}
{Get the current previous and next blocks}
mov ecx, TMediumFreeBlock[eax].NextFreeBlock
mov edx, TMediumFreeBlock[eax].PreviousFreeBlock
{Is this bin now empty? If the previous and next free block pointers are
equal, they must point to the bin.}
cmp ecx, edx
{Remove this block from the linked list}
mov TMediumFreeBlock[ecx].PreviousFreeBlock, edx
mov TMediumFreeBlock[edx].NextFreeBlock, ecx
{Is this bin now empty? If the previous and next free block pointers are
equal, they must point to the bin.}
je @BinIsNowEmpty
@Done:
ret
{Align branch target}
nop
@BinIsNowEmpty:
{Get the bin number for this block size in ecx}
sub ecx, offset MediumBlockBins
mov edx, ecx
shr ecx, 3
{Get the group number in edx}
movzx edx, dh
{Flag this bin as empty}
mov eax, -2
rol eax, cl
and dword ptr [MediumBlockBinBitmaps + edx * 4], eax
jnz @Done
{Flag this group as empty}
mov eax, -2
mov ecx, edx
rol eax, cl
and MediumBlockBinGroupBitmap, eax
end;
{$else}
asm
{On entry: rcx = APMediumFreeBlock}
mov rax, rcx
{Get the current previous and next blocks}
mov rcx, TMediumFreeBlock[rax].NextFreeBlock
mov rdx, TMediumFreeBlock[rax].PreviousFreeBlock
{Is this bin now empty? If the previous and next free block pointers are
equal, they must point to the bin.}
cmp rcx, rdx
{Remove this block from the linked list}
mov TMediumFreeBlock[rcx].PreviousFreeBlock, rdx
mov TMediumFreeBlock[rdx].NextFreeBlock, rcx
{Is this bin now empty? If the previous and next free block pointers are
equal, they must point to the bin.}
jne @Done
{Get the bin number for this block size in rcx}
lea r8, MediumBlockBins
sub rcx, r8
mov edx, ecx
shr ecx, 4
{Get the group number in edx}
shr edx, 9
{Flag this bin as empty}
mov eax, -2
rol eax, cl
lea r8, MediumBlockBinBitmaps
and dword ptr [r8 + rdx * 4], eax
jnz @Done
{Flag this group as empty}
mov eax, -2
mov ecx, edx
rol eax, cl
and MediumBlockBinGroupBitmap, eax
@Done:
end;
{$endif}
{$endif}
{Inserts a medium block into the appropriate medium block bin.}
procedure InsertMediumBlockIntoBin(APMediumFreeBlock: PMediumFreeBlock; AMediumBlockSize: Cardinal);
{$ifndef ASMVersion}
var
LBinNumber, LBinGroupNumber: Cardinal;
LPBin, LPFirstFreeBlock: PMediumFreeBlock;
begin
{Get the bin number for this block size. Get the bin that holds blocks of at
least this size.}
LBinNumber := (AMediumBlockSize - MinimumMediumBlockSize) div MediumBlockGranularity;
if LBinNumber >= MediumBlockBinCount then
LBinNumber := MediumBlockBinCount - 1;
{Get the bin}
LPBin := @MediumBlockBins[LBinNumber];
{Bins are LIFO, se we insert this block as the first free block in the bin}
LPFirstFreeBlock := LPBin.NextFreeBlock;
APMediumFreeBlock.PreviousFreeBlock := LPBin;
APMediumFreeBlock.NextFreeBlock := LPFirstFreeBlock;
LPFirstFreeBlock.PreviousFreeBlock := APMediumFreeBlock;
LPBin.NextFreeBlock := APMediumFreeBlock;
{Was this bin empty?}
if LPFirstFreeBlock = LPBin then
begin
{Get the group number}
LBinGroupNumber := LBinNumber div 32;
{Flag this bin as used}
MediumBlockBinBitmaps[LBinGroupNumber] := MediumBlockBinBitmaps[LBinGroupNumber]
or (1 shl (LBinNumber and 31));
{Flag the group as used}
MediumBlockBinGroupBitmap := MediumBlockBinGroupBitmap
or (1 shl LBinGroupNumber);
end;
end;
{$else}
{$ifdef 32Bit}
asm
{On entry: eax = APMediumFreeBlock, edx = AMediumBlockSize}
{Get the bin number for this block size. Get the bin that holds blocks of at
least this size.}
sub edx, MinimumMediumBlockSize
shr edx, 8
{Validate the bin number}
sub edx, MediumBlockBinCount - 1
sbb ecx, ecx
and edx, ecx
add edx, MediumBlockBinCount - 1
{Get the bin in ecx}
lea ecx, [MediumBlockBins + edx * 8]
{Bins are LIFO, se we insert this block as the first free block in the bin}
mov edx, TMediumFreeBlock[ecx].NextFreeBlock
{Was this bin empty?}
cmp edx, ecx
mov TMediumFreeBlock[eax].PreviousFreeBlock, ecx
mov TMediumFreeBlock[eax].NextFreeBlock, edx
mov TMediumFreeBlock[edx].PreviousFreeBlock, eax
mov TMediumFreeBlock[ecx].NextFreeBlock, eax
{Was this bin empty?}
je @BinWasEmpty
ret
{Align branch target}
nop
nop
@BinWasEmpty:
{Get the bin number in ecx}
sub ecx, offset MediumBlockBins
mov edx, ecx
shr ecx, 3
{Get the group number in edx}
movzx edx, dh
{Flag this bin as not empty}
mov eax, 1
shl eax, cl
or dword ptr [MediumBlockBinBitmaps + edx * 4], eax
{Flag the group as not empty}
mov eax, 1
mov ecx, edx
shl eax, cl
or MediumBlockBinGroupBitmap, eax
end;
{$else}
asm
{On entry: rax = APMediumFreeBlock, edx = AMediumBlockSize}
mov rax, rcx
{Get the bin number for this block size. Get the bin that holds blocks of at
least this size.}
sub edx, MinimumMediumBlockSize
shr edx, 8
{Validate the bin number}
sub edx, MediumBlockBinCount - 1
sbb ecx, ecx
and edx, ecx
add edx, MediumBlockBinCount - 1
mov r9, rdx
{Get the bin address in rcx}
lea rcx, MediumBlockBins
shl edx, 4
add rcx, rdx
{Bins are LIFO, se we insert this block as the first free block in the bin}
mov rdx, TMediumFreeBlock[rcx].NextFreeBlock
{Was this bin empty?}
cmp rdx, rcx
mov TMediumFreeBlock[rax].PreviousFreeBlock, rcx
mov TMediumFreeBlock[rax].NextFreeBlock, rdx
mov TMediumFreeBlock[rdx].PreviousFreeBlock, rax
mov TMediumFreeBlock[rcx].NextFreeBlock, rax
{Was this bin empty?}
jne @Done
{Get the bin number in ecx}
mov rcx, r9
{Get the group number in edx}
mov rdx, r9
shr edx, 5
{Flag this bin as not empty}
mov eax, 1
shl eax, cl
lea r8, MediumBlockBinBitmaps
or dword ptr [r8 + rdx * 4], eax
{Flag the group as not empty}
mov eax, 1
mov ecx, edx
shl eax, cl
or MediumBlockBinGroupBitmap, eax
@Done:
end;
{$endif}
{$endif}
{Bins what remains in the current sequential feed medium block pool. Medium
blocks must be locked.}
procedure BinMediumSequentialFeedRemainder;
{$ifndef ASMVersion}
var
LSequentialFeedFreeSize, LNextBlockSizeAndFlags: NativeUInt;
LPRemainderBlock, LNextMediumBlock: Pointer;
begin
LSequentialFeedFreeSize := MediumSequentialFeedBytesLeft;
if LSequentialFeedFreeSize > 0 then
begin
{Get the block after the open space}
LNextMediumBlock := LastSequentiallyFedMediumBlock;
LNextBlockSizeAndFlags := PNativeUInt(PByte(LNextMediumBlock) - BlockHeaderSize)^;
{Point to the remainder}
LPRemainderBlock := Pointer(PByte(LNextMediumBlock) - LSequentialFeedFreeSize);
{$ifndef FullDebugMode}
{Can the next block be combined with the remainder?}
if (LNextBlockSizeAndFlags and IsFreeBlockFlag) <> 0 then
begin
{Increase the size of this block}
Inc(LSequentialFeedFreeSize, LNextBlockSizeAndFlags and DropMediumAndLargeFlagsMask);
{Remove the next block as well}
if (LNextBlockSizeAndFlags and DropMediumAndLargeFlagsMask) >= MinimumMediumBlockSize then
RemoveMediumFreeBlock(LNextMediumBlock);
end
else
begin
{$endif}
{Set the "previous block is free" flag of the next block}
PNativeUInt(PByte(LNextMediumBlock) - BlockHeaderSize)^ := LNextBlockSizeAndFlags or PreviousMediumBlockIsFreeFlag;
{$ifndef FullDebugMode}
end;
{$endif}
{Store the size of the block as well as the flags}
PNativeUInt(PByte(LPRemainderBlock) - BlockHeaderSize)^ := LSequentialFeedFreeSize or IsMediumBlockFlag or IsFreeBlockFlag;
{Store the trailing size marker}
PNativeUInt(PByte(LPRemainderBlock) + LSequentialFeedFreeSize - BlockHeaderSize * 2)^ := LSequentialFeedFreeSize;
{$ifdef FullDebugMode}
{In full debug mode the sequential feed remainder will never be too small to
fit a full debug header.}
{Clear the user area of the block}
DebugFillMem(Pointer(PByte(LPRemainderBlock) + SizeOf(TFullDebugBlockHeader) + SizeOf(NativeUInt))^,
LSequentialFeedFreeSize - FullDebugBlockOverhead - SizeOf(NativeUInt),
{$ifndef CatchUseOfFreedInterfaces}DebugFillPattern{$else}NativeUInt(@VMTBadInterface){$endif});
{We need to set a valid debug header and footer in the remainder}
PFullDebugBlockHeader(LPRemainderBlock).HeaderCheckSum := NativeUInt(LPRemainderBlock);
PNativeUInt(PByte(LPRemainderBlock) + SizeOf(TFullDebugBlockHeader))^ := not NativeUInt(LPRemainderBlock);
{$endif}
{Bin this medium block}
if LSequentialFeedFreeSize >= MinimumMediumBlockSize then
InsertMediumBlockIntoBin(LPRemainderBlock, LSequentialFeedFreeSize);
end;
end;
{$else}
{$ifdef 32Bit}
asm
cmp MediumSequentialFeedBytesLeft, 0
jne @MustBinMedium
{Nothing to bin}
ret
{Align branch target}
nop
nop
@MustBinMedium:
{Get a pointer to the last sequentially allocated medium block}
mov eax, LastSequentiallyFedMediumBlock
{Is the block that was last fed sequentially free?}
test byte ptr [eax - 4], IsFreeBlockFlag
jnz @LastBlockFedIsFree
{Set the "previous block is free" flag in the last block fed}
or dword ptr [eax - 4], PreviousMediumBlockIsFreeFlag
{Get the remainder in edx}
mov edx, MediumSequentialFeedBytesLeft
{Point eax to the start of the remainder}
sub eax, edx
@BinTheRemainder:
{Status: eax = start of remainder, edx = size of remainder}
{Store the size of the block as well as the flags}
lea ecx, [edx + IsMediumBlockFlag + IsFreeBlockFlag]
mov [eax - 4], ecx
{Store the trailing size marker}
mov [eax + edx - 8], edx
{Bin this medium block}
cmp edx, MinimumMediumBlockSize
jnb InsertMediumBlockIntoBin
ret
{Align branch target}
nop
nop
@LastBlockFedIsFree:
{Drop the flags}
mov edx, DropMediumAndLargeFlagsMask
and edx, [eax - 4]
{Free the last block fed}
cmp edx, MinimumMediumBlockSize
jb @DontRemoveLastFed
{Last fed block is free - remove it from its size bin}
call RemoveMediumFreeBlock
{Re-read eax and edx}
mov eax, LastSequentiallyFedMediumBlock
mov edx, DropMediumAndLargeFlagsMask
and edx, [eax - 4]
@DontRemoveLastFed:
{Get the number of bytes left in ecx}
mov ecx, MediumSequentialFeedBytesLeft
{Point eax to the start of the remainder}
sub eax, ecx
{edx = total size of the remainder}
add edx, ecx
jmp @BinTheRemainder
@Done:
end;
{$else}
asm
.params 2
xor eax, eax
cmp MediumSequentialFeedBytesLeft, eax
je @Done
{Get a pointer to the last sequentially allocated medium block}
mov rax, LastSequentiallyFedMediumBlock
{Is the block that was last fed sequentially free?}
test byte ptr [rax - BlockHeaderSize], IsFreeBlockFlag
jnz @LastBlockFedIsFree
{Set the "previous block is free" flag in the last block fed}
or qword ptr [rax - BlockHeaderSize], PreviousMediumBlockIsFreeFlag
{Get the remainder in edx}
mov edx, MediumSequentialFeedBytesLeft
{Point eax to the start of the remainder}
sub rax, rdx
@BinTheRemainder:
{Status: rax = start of remainder, edx = size of remainder}
{Store the size of the block as well as the flags}
lea rcx, [rdx + IsMediumBlockFlag + IsFreeBlockFlag]
mov [rax - BlockHeaderSize], rcx
{Store the trailing size marker}
mov [rax + rdx - 2 * BlockHeaderSize], rdx
{Bin this medium block}
cmp edx, MinimumMediumBlockSize
jb @Done
mov rcx, rax
call InsertMediumBlockIntoBin
jmp @Done
@LastBlockFedIsFree:
{Drop the flags}
mov rdx, DropMediumAndLargeFlagsMask
and rdx, [rax - BlockHeaderSize]
{Free the last block fed}
cmp edx, MinimumMediumBlockSize
jb @DontRemoveLastFed
{Last fed block is free - remove it from its size bin}
mov rcx, rax
call RemoveMediumFreeBlock
{Re-read rax and rdx}
mov rax, LastSequentiallyFedMediumBlock
mov rdx, DropMediumAndLargeFlagsMask
and rdx, [rax - BlockHeaderSize]
@DontRemoveLastFed:
{Get the number of bytes left in ecx}
mov ecx, MediumSequentialFeedBytesLeft
{Point rax to the start of the remainder}
sub rax, rcx
{edx = total size of the remainder}
add edx, ecx
jmp @BinTheRemainder
@Done:
end;
{$endif}
{$endif}
{Allocates a new sequential feed medium block pool and immediately splits off a
block of the requested size. The block size must be a multiple of 16 and
medium blocks must be locked.}
function AllocNewSequentialFeedMediumPool(AFirstBlockSize: Cardinal): Pointer;
var
LOldFirstMediumBlockPool: PMediumBlockPoolHeader;
LNewPool: Pointer;
begin
{Bin the current sequential feed remainder}
BinMediumSequentialFeedRemainder;
{Allocate a new sequential feed block pool}
LNewPool := VirtualAlloc(nil, MediumBlockPoolSize,
MEM_COMMIT{$ifdef AlwaysAllocateTopDown} or MEM_TOP_DOWN{$endif}, PAGE_READWRITE);
if LNewPool <> nil then
begin
{Insert this block pool into the list of block pools}
LOldFirstMediumBlockPool := MediumBlockPoolsCircularList.NextMediumBlockPoolHeader;
PMediumBlockPoolHeader(LNewPool).PreviousMediumBlockPoolHeader := @MediumBlockPoolsCircularList;
MediumBlockPoolsCircularList.NextMediumBlockPoolHeader := LNewPool;
PMediumBlockPoolHeader(LNewPool).NextMediumBlockPoolHeader := LOldFirstMediumBlockPool;
LOldFirstMediumBlockPool.PreviousMediumBlockPoolHeader := LNewPool;
{Store the sequential feed pool trailer}
PNativeUInt(PByte(LNewPool) + MediumBlockPoolSize - BlockHeaderSize)^ := IsMediumBlockFlag;
{Get the number of bytes still available}
MediumSequentialFeedBytesLeft := (MediumBlockPoolSize - MediumBlockPoolHeaderSize) - AFirstBlockSize;
{Get the result}
Result := Pointer(PByte(LNewPool) + MediumBlockPoolSize - AFirstBlockSize);
LastSequentiallyFedMediumBlock := Result;
{Store the block header}
PNativeUInt(PByte(Result) - BlockHeaderSize)^ := AFirstBlockSize or IsMediumBlockFlag;
end
else
begin
{Out of memory}
MediumSequentialFeedBytesLeft := 0;
Result := nil;
end;
end;
{-----------------Large Block Management------------------}
{Locks the large blocks}
procedure LockLargeBlocks;
begin
{Lock the large blocks}
{$ifndef AssumeMultiThreaded}
if IsMultiThread then
{$endif}
begin
while LockCmpxchg(0, 1, @LargeBlocksLocked) <> 0 do
begin
{$ifdef NeverSleepOnThreadContention}
{$ifdef UseSwitchToThread}
SwitchToThread;
{$endif}
{$else}
Sleep(InitialSleepTime);
if LockCmpxchg(0, 1, @LargeBlocksLocked) = 0 then
Break;
Sleep(AdditionalSleepTime);
{$endif}
end;
end;
end;
{Allocates a Large block of at least ASize (actual size may be larger to
allow for alignment etc.). ASize must be the actual user requested size. This
procedure will pad it to the appropriate page boundary and also add the space
required by the header.}
function AllocateLargeBlock(ASize: NativeUInt): Pointer;
var
LLargeUsedBlockSize: NativeUInt;
LOldFirstLargeBlock: PLargeBlockHeader;
begin
{Pad the block size to include the header and granularity. We also add a
SizeOf(Pointer) overhead so a huge block size is a multiple of 16 bytes less
SizeOf(Pointer) (so we can use a single move function for reallocating all
block types)}
LLargeUsedBlockSize := (ASize + LargeBlockHeaderSize + LargeBlockGranularity - 1 + BlockHeaderSize)
and -LargeBlockGranularity;
{Get the Large block}
Result := VirtualAlloc(nil, LLargeUsedBlockSize, MEM_COMMIT or MEM_TOP_DOWN,
PAGE_READWRITE);
{Set the Large block fields}
if Result <> nil then
begin
{Set the large block size and flags}
PLargeBlockHeader(Result).UserAllocatedSize := ASize;
PLargeBlockHeader(Result).BlockSizeAndFlags := LLargeUsedBlockSize or IsLargeBlockFlag;
{Insert the large block into the linked list of large blocks}
LockLargeBlocks;
LOldFirstLargeBlock := LargeBlocksCircularList.NextLargeBlockHeader;
PLargeBlockHeader(Result).PreviousLargeBlockHeader := @LargeBlocksCircularList;
LargeBlocksCircularList.NextLargeBlockHeader := Result;
PLargeBlockHeader(Result).NextLargeBlockHeader := LOldFirstLargeBlock;
LOldFirstLargeBlock.PreviousLargeBlockHeader := Result;
LargeBlocksLocked := False;
{Add the size of the header}
Inc(PByte(Result), LargeBlockHeaderSize);
{$ifdef FullDebugMode}
{Since large blocks are never reused, the user area is not initialized to
the debug fill pattern, but the debug header and footer must be set.}
PFullDebugBlockHeader(Result).HeaderCheckSum := NativeUInt(Result);
PNativeUInt(PByte(Result) + SizeOf(TFullDebugBlockHeader))^ := not NativeUInt(Result);
{$endif}
end;
end;
{Frees a large block, returning 0 on success, -1 otherwise}
function FreeLargeBlock(APointer: Pointer): Integer;
var
LPreviousLargeBlockHeader, LNextLargeBlockHeader: PLargeBlockHeader;
{$ifndef POSIX}
LRemainingSize: NativeUInt;
LCurrentSegment: Pointer;
LMemInfo: TMemoryBasicInformation;
{$endif}
begin
{$ifdef ClearLargeBlocksBeforeReturningToOS}
FillChar(APointer^,
(PLargeBlockHeader(PByte(APointer) - LargeBlockHeaderSize).BlockSizeAndFlags
and DropMediumAndLargeFlagsMask) - LargeBlockHeaderSize, 0);
{$endif}
{Point to the start of the large block}
APointer := Pointer(PByte(APointer) - LargeBlockHeaderSize);
{Get the previous and next large blocks}
LockLargeBlocks;
LPreviousLargeBlockHeader := PLargeBlockHeader(APointer).PreviousLargeBlockHeader;
LNextLargeBlockHeader := PLargeBlockHeader(APointer).NextLargeBlockHeader;
{$ifndef POSIX}
{Is the large block segmented?}
if PLargeBlockHeader(APointer).BlockSizeAndFlags and LargeBlockIsSegmented = 0 then
begin
{$endif}
{Single segment large block: Try to free it}
if VirtualFree(APointer, 0, MEM_RELEASE) then
Result := 0
else
Result := -1;
{$ifndef POSIX}
end
else
begin
{The large block is segmented - free all segments}
LCurrentSegment := APointer;
LRemainingSize := PLargeBlockHeader(APointer).BlockSizeAndFlags and DropMediumAndLargeFlagsMask;
Result := 0;
while True do
begin
{Get the size of the current segment}
VirtualQuery(LCurrentSegment, LMemInfo, SizeOf(LMemInfo));
{Free the segment}
if not VirtualFree(LCurrentSegment, 0, MEM_RELEASE) then
begin
Result := -1;
Break;
end;
{Done?}
if NativeUInt(LMemInfo.RegionSize) >= LRemainingSize then
Break;
{Decrement the remaining size}
Dec(LRemainingSize, NativeUInt(LMemInfo.RegionSize));
Inc(PByte(LCurrentSegment), NativeUInt(LMemInfo.RegionSize));
end;
end;
{$endif}
{Success?}
if Result = 0 then
begin
{Remove the large block from the linked list}
LNextLargeBlockHeader.PreviousLargeBlockHeader := LPreviousLargeBlockHeader;
LPreviousLargeBlockHeader.NextLargeBlockHeader := LNextLargeBlockHeader;
end;
{Unlock the large blocks}
LargeBlocksLocked := False;
end;
{$ifndef FullDebugMode}
{Reallocates a large block to at least the requested size. Returns the new
pointer, or nil on error}
function ReallocateLargeBlock(APointer: Pointer; ANewSize: NativeUInt): Pointer;
var
LOldAvailableSize, LBlockHeader, LOldUserSize, LMinimumUpsize,
LNewAllocSize: NativeUInt;
{$ifndef POSIX}
LNewSegmentSize: NativeUInt;
LNextSegmentPointer: Pointer;
LMemInfo: TMemoryBasicInformation;
{$endif}
begin
{Get the block header}
LBlockHeader := PNativeUInt(PByte(APointer) - BlockHeaderSize)^;
{Large block - size is (16 + 4) less than the allocated size}
LOldAvailableSize := (LBlockHeader and DropMediumAndLargeFlagsMask) - (LargeBlockHeaderSize + BlockHeaderSize);
{Is it an upsize or a downsize?}
if ANewSize > LOldAvailableSize then
begin
{This pointer is being reallocated to a larger block and therefore it is
logical to assume that it may be enlarged again. Since reallocations are
expensive, there is a minimum upsize percentage to avoid unnecessary
future move operations.}
{Add 25% for large block upsizes}
LMinimumUpsize := LOldAvailableSize + (LOldAvailableSize shr 2);
if ANewSize < LMinimumUpsize then
LNewAllocSize := LMinimumUpsize
else
LNewAllocSize := ANewSize;
{$ifndef POSIX}
{Can another large block segment be allocated directly after this segment,
thus negating the need to move the data?}
LNextSegmentPointer := Pointer(PByte(APointer) - LargeBlockHeaderSize + (LBlockHeader and DropMediumAndLargeFlagsMask));
VirtualQuery(LNextSegmentPointer, LMemInfo, SizeOf(LMemInfo));
if LMemInfo.State = MEM_FREE then
begin
{Round the region size to the previous 64K}
LMemInfo.RegionSize := LMemInfo.RegionSize and -LargeBlockGranularity;
{Enough space to grow in place?}
if NativeUInt(LMemInfo.RegionSize) > (ANewSize - LOldAvailableSize) then
begin
{There is enough space after the block to extend it - determine by how
much}
LNewSegmentSize := (LNewAllocSize - LOldAvailableSize + LargeBlockGranularity - 1) and -LargeBlockGranularity;
if LNewSegmentSize > LMemInfo.RegionSize then
LNewSegmentSize := LMemInfo.RegionSize;
{Attempy to reserve the address range (which will fail if another
thread has just reserved it) and commit it immediately afterwards.}
if (VirtualAlloc(LNextSegmentPointer, LNewSegmentSize, MEM_RESERVE, PAGE_READWRITE) <> nil)
and (VirtualAlloc(LNextSegmentPointer, LNewSegmentSize, MEM_COMMIT, PAGE_READWRITE) <> nil) then
begin
{Update the requested size}
PLargeBlockHeader(PByte(APointer) - LargeBlockHeaderSize).UserAllocatedSize := ANewSize;
PLargeBlockHeader(PByte(APointer) - LargeBlockHeaderSize).BlockSizeAndFlags :=
(PLargeBlockHeader(PByte(APointer) - LargeBlockHeaderSize).BlockSizeAndFlags + LNewSegmentSize)
or LargeBlockIsSegmented;
{Success}
Result := APointer;
Exit;
end;
end;
end;
{$endif}
{Could not resize in place: Allocate the new block}
Result := FastGetMem(LNewAllocSize);
if Result <> nil then
begin
{If it's a large block - store the actual user requested size (it may
not be if the block that is being reallocated from was previously
downsized)}
if LNewAllocSize > (MaximumMediumBlockSize - BlockHeaderSize) then
PLargeBlockHeader(PByte(Result) - LargeBlockHeaderSize).UserAllocatedSize := ANewSize;
{The user allocated size is stored for large blocks}
LOldUserSize := PLargeBlockHeader(PByte(APointer) - LargeBlockHeaderSize).UserAllocatedSize;
{The number of bytes to move is the old user size.}
{$ifdef UseCustomVariableSizeMoveRoutines}
MoveX16LP(APointer^, Result^, LOldUserSize);
{$else}
System.Move(APointer^, Result^, LOldUserSize);
{$endif}
{Free the old block}
FastFreeMem(APointer);
end;
end
else
begin
{It's a downsize: do we need to reallocate? Only if the new size is less
than half the old size}
if ANewSize >= (LOldAvailableSize shr 1) then
begin
{No need to reallocate}
Result := APointer;
{Update the requested size}
PLargeBlockHeader(PByte(APointer) - LargeBlockHeaderSize).UserAllocatedSize := ANewSize;
end
else
begin
{The block is less than half the old size, and the current size is
greater than the minimum block size allowing a downsize: reallocate}
Result := FastGetMem(ANewSize);
if Result <> nil then
begin
{Still a large block? -> Set the user size}
if ANewSize > (MaximumMediumBlockSize - BlockHeaderSize) then
PLargeBlockHeader(PByte(APointer) - LargeBlockHeaderSize).UserAllocatedSize := ANewSize;
{Move the data across}
{$ifdef UseCustomVariableSizeMoveRoutines}
{$ifdef Align16Bytes}
MoveX16LP(APointer^, Result^, ANewSize);
{$else}
MoveX8LP(APointer^, Result^, ANewSize);
{$endif}
{$else}
System.Move(APointer^, Result^, ANewSize);
{$endif}
{Free the old block}
FastFreeMem(APointer);
end;
end;
end;
end;
{$endif}
{---------------------Replacement Memory Manager Interface---------------------}
{Replacement for SysGetMem}
function FastGetMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer;
{$ifndef ASMVersion}
var
LMediumBlock{$ifndef FullDebugMode}, LNextFreeBlock, LSecondSplit{$endif}: PMediumFreeBlock;
LNextMediumBlockHeader: PNativeUInt;
LBlockSize, LAvailableBlockSize{$ifndef FullDebugMode}, LSecondSplitSize{$endif},
LSequentialFeedFreeSize: NativeUInt;
LPSmallBlockType: PSmallBlockType;
LPSmallBlockPool, LPNewFirstPool: PSmallBlockPoolHeader;
LNewFirstFreeBlock: Pointer;
LPMediumBin: PMediumFreeBlock;
LBinNumber, {$ifndef FullDebugMode}LBinGroupsMasked, {$endif}LBinGroupMasked,
LBinGroupNumber: Cardinal;
begin
{Is it a small block? -> Take the header size into account when
determining the required block size}
if NativeUInt(ASize) <= (MaximumSmallBlockSize - BlockHeaderSize) then
begin
{-------------------------Allocate a small block---------------------------}
{Get the block type from the size}
LPSmallBlockType := PSmallBlockType(AllocSize2SmallBlockTypeIndX4[
(NativeUInt(ASize) + (BlockHeaderSize - 1)) div SmallBlockGranularity]
* (SizeOf(TSmallBlockType) div 4)
+ UIntPtr(@SmallBlockTypes));
{Lock the block type}
{$ifndef AssumeMultiThreaded}
if IsMultiThread then
{$endif}
begin
while True do
begin
{Try to lock the small block type}
if LockCmpxchg(0, 1, @LPSmallBlockType.BlockTypeLocked) = 0 then
Break;
{Try the next block type}
Inc(PByte(LPSmallBlockType), SizeOf(TSmallBlockType));
if LockCmpxchg(0, 1, @LPSmallBlockType.BlockTypeLocked) = 0 then
Break;
{Try up to two sizes past the requested size}
Inc(PByte(LPSmallBlockType), SizeOf(TSmallBlockType));
if LockCmpxchg(0, 1, @LPSmallBlockType.BlockTypeLocked) = 0 then
Break;
{All three sizes locked - given up and sleep}
Dec(PByte(LPSmallBlockType), 2 * SizeOf(TSmallBlockType));
{$ifdef NeverSleepOnThreadContention}
{$ifdef UseSwitchToThread}
SwitchToThread;
{$endif}
{$else}
{Both this block type and the next is in use: sleep}
Sleep(InitialSleepTime);
{Try the lock again}
if LockCmpxchg(0, 1, @LPSmallBlockType.BlockTypeLocked) = 0 then
Break;
{Sleep longer}
Sleep(AdditionalSleepTime);
{$endif}
end;
end;
{Get the first pool with free blocks}
LPSmallBlockPool := LPSmallBlockType.NextPartiallyFreePool;
{Is the pool valid?}
if UIntPtr(LPSmallBlockPool) <> UIntPtr(LPSmallBlockType) then
begin
{Get the first free offset}
Result := LPSmallBlockPool.FirstFreeBlock;
{Get the new first free block}
LNewFirstFreeBlock := PPointer(PByte(Result) - BlockHeaderSize)^;
{$ifdef CheckHeapForCorruption}
{The block should be free}
if (NativeUInt(LNewFirstFreeBlock) and ExtractSmallFlagsMask) <> IsFreeBlockFlag then
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
{$endif}
LNewFirstFreeBlock := Pointer(UIntPtr(LNewFirstFreeBlock) and DropSmallFlagsMask);
{Increment the number of used blocks}
Inc(LPSmallBlockPool.BlocksInUse);
{Set the new first free block}
LPSmallBlockPool.FirstFreeBlock := LNewFirstFreeBlock;
{Is the pool now full?}
if LNewFirstFreeBlock = nil then
begin
{Pool is full - remove it from the partially free list}
LPNewFirstPool := LPSmallBlockPool.NextPartiallyFreePool;
LPSmallBlockType.NextPartiallyFreePool := LPNewFirstPool;
LPNewFirstPool.PreviousPartiallyFreePool := PSmallBlockPoolHeader(LPSmallBlockType);
end;
end
else
begin
{Try to feed a small block sequentially}
Result := LPSmallBlockType.NextSequentialFeedBlockAddress;
{Can another block fit?}
if UIntPtr(Result) <= UIntPtr(LPSmallBlockType.MaxSequentialFeedBlockAddress) then
begin
{Get the sequential feed block pool}
LPSmallBlockPool := LPSmallBlockType.CurrentSequentialFeedPool;
{Increment the number of used blocks in the sequential feed pool}
Inc(LPSmallBlockPool.BlocksInUse);
{Store the next sequential feed block address}
LPSmallBlockType.NextSequentialFeedBlockAddress := Pointer(PByte(Result) + LPSmallBlockType.BlockSize);
end
else
begin
{Need to allocate a pool: Lock the medium blocks}
LockMediumBlocks;
{$ifndef FullDebugMode}
{Are there any available blocks of a suitable size?}
LBinGroupsMasked := MediumBlockBinGroupBitmap and ($ffffff00 or LPSmallBlockType.AllowedGroupsForBlockPoolBitmap);
if LBinGroupsMasked <> 0 then
begin
{Get the bin group with free blocks}
LBinGroupNumber := FindFirstSetBit(LBinGroupsMasked);
{Get the bin in the group with free blocks}
LBinNumber := FindFirstSetBit(MediumBlockBinBitmaps[LBinGroupNumber])
+ LBinGroupNumber * 32;
LPMediumBin := @MediumBlockBins[LBinNumber];
{Get the first block in the bin}
LMediumBlock := LPMediumBin.NextFreeBlock;
{Remove the first block from the linked list (LIFO)}
LNextFreeBlock := LMediumBlock.NextFreeBlock;
LPMediumBin.NextFreeBlock := LNextFreeBlock;
LNextFreeBlock.PreviousFreeBlock := LPMediumBin;
{Is this bin now empty?}
if LNextFreeBlock = LPMediumBin then
begin
{Flag this bin as empty}
MediumBlockBinBitmaps[LBinGroupNumber] := MediumBlockBinBitmaps[LBinGroupNumber]
and (not (1 shl (LBinNumber and 31)));
{Is the group now entirely empty?}
if MediumBlockBinBitmaps[LBinGroupNumber] = 0 then
begin
{Flag this group as empty}
MediumBlockBinGroupBitmap := MediumBlockBinGroupBitmap
and (not (1 shl LBinGroupNumber));
end;
end;
{Get the size of the available medium block}
LBlockSize := PNativeUInt(PByte(LMediumBlock) - BlockHeaderSize)^ and DropMediumAndLargeFlagsMask;
{$ifdef CheckHeapForCorruption}
{Check that this block is actually free and the next and previous blocks
are both in use.}
if ((PNativeUInt(PByte(LMediumBlock) - BlockHeaderSize)^ and ExtractMediumAndLargeFlagsMask) <> (IsMediumBlockFlag or IsFreeBlockFlag))
or ((PNativeUInt(PByte(LMediumBlock) + (PNativeUInt(PByte(LMediumBlock) - BlockHeaderSize)^ and DropMediumAndLargeFlagsMask) - BlockHeaderSize)^ and IsFreeBlockFlag) <> 0)
then
begin
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
end;
{$endif}
{Should the block be split?}
if LBlockSize >= MaximumSmallBlockPoolSize then
begin
{Get the size of the second split}
LSecondSplitSize := LBlockSize - LPSmallBlockType.OptimalBlockPoolSize;
{Adjust the block size}
LBlockSize := LPSmallBlockType.OptimalBlockPoolSize;
{Split the block in two}
LSecondSplit := PMediumFreeBlock(PByte(LMediumBlock) + LBlockSize);
PNativeUInt(PByte(LSecondSplit) - BlockHeaderSize)^ := LSecondSplitSize or (IsMediumBlockFlag or IsFreeBlockFlag);
{Store the size of the second split as the second last dword/qword}
PNativeUInt(PByte(LSecondSplit) + LSecondSplitSize - 2 * BlockHeaderSize)^ := LSecondSplitSize;
{Put the remainder in a bin (it will be big enough)}
InsertMediumBlockIntoBin(LSecondSplit, LSecondSplitSize);
end
else
begin
{Mark this block as used in the block following it}
LNextMediumBlockHeader := PNativeUInt(PByte(LMediumBlock) + LBlockSize - BlockHeaderSize);
LNextMediumBlockHeader^ := LNextMediumBlockHeader^ and (not PreviousMediumBlockIsFreeFlag);
end;
end
else
begin
{$endif}
{Check the sequential feed medium block pool for space}
LSequentialFeedFreeSize := MediumSequentialFeedBytesLeft;
if LSequentialFeedFreeSize >= LPSmallBlockType.MinimumBlockPoolSize then
begin
{Enough sequential feed space: Will the remainder be usable?}
if LSequentialFeedFreeSize >= (LPSmallBlockType.OptimalBlockPoolSize + MinimumMediumBlockSize) then
begin
LBlockSize := LPSmallBlockType.OptimalBlockPoolSize;
end
else
LBlockSize := LSequentialFeedFreeSize;
{Get the block}
LMediumBlock := Pointer(PByte(LastSequentiallyFedMediumBlock) - LBlockSize);
{Update the sequential feed parameters}
LastSequentiallyFedMediumBlock := LMediumBlock;
MediumSequentialFeedBytesLeft := LSequentialFeedFreeSize - LBlockSize;
end
else
begin
{Need to allocate a new sequential feed medium block pool: use the
optimal size for this small block pool}
LBlockSize := LPSmallBlockType.OptimalBlockPoolSize;
{Allocate the medium block pool}
LMediumBlock := AllocNewSequentialFeedMediumPool(LBlockSize);
if LMediumBlock = nil then
begin
{Out of memory}
{Unlock the medium blocks}
MediumBlocksLocked := False;
{Unlock the block type}
LPSmallBlockType.BlockTypeLocked := False;
{Failed}
Result := nil;
{done}
Exit;
end;
end;
{$ifndef FullDebugMode}
end;
{$endif}
{Mark this block as in use}
{Set the size and flags for this block}
PNativeUInt(PByte(LMediumBlock) - BlockHeaderSize)^ := LBlockSize or IsMediumBlockFlag or IsSmallBlockPoolInUseFlag;
{Unlock medium blocks}
MediumBlocksLocked := False;
{Set up the block pool}
LPSmallBlockPool := PSmallBlockPoolHeader(LMediumBlock);
LPSmallBlockPool.BlockType := LPSmallBlockType;
LPSmallBlockPool.FirstFreeBlock := nil;
LPSmallBlockPool.BlocksInUse := 1;
{Set it up for sequential block serving}
LPSmallBlockType.CurrentSequentialFeedPool := LPSmallBlockPool;
Result := Pointer(PByte(LPSmallBlockPool) + SmallBlockPoolHeaderSize);
LPSmallBlockType.NextSequentialFeedBlockAddress := Pointer(PByte(Result) + LPSmallBlockType.BlockSize);
LPSmallBlockType.MaxSequentialFeedBlockAddress := Pointer(PByte(LPSmallBlockPool) + LBlockSize - LPSmallBlockType.BlockSize);
end;
{$ifdef FullDebugMode}
{Clear the user area of the block}
DebugFillMem(Pointer(PByte(Result) + (SizeOf(TFullDebugBlockHeader) + SizeOf(NativeUInt)))^,
LPSmallBlockType.BlockSize - FullDebugBlockOverhead - SizeOf(NativeUInt),
{$ifndef CatchUseOfFreedInterfaces}DebugFillPattern{$else}NativeUInt(@VMTBadInterface){$endif});
{Block was fed sequentially - we need to set a valid debug header. Use
the block address.}
PFullDebugBlockHeader(Result).HeaderCheckSum := NativeUInt(Result);
PNativeUInt(PByte(Result) + SizeOf(TFullDebugBlockHeader))^ := not NativeUInt(Result);
{$endif}
end;
{Unlock the block type}
LPSmallBlockType.BlockTypeLocked := False;
{Set the block header}
PNativeUInt(PByte(Result) - BlockHeaderSize)^ := UIntPtr(LPSmallBlockPool);
end
else
begin
{Medium block or Large block?}
if NativeUInt(ASize) <= (MaximumMediumBlockSize - BlockHeaderSize) then
begin
{------------------------Allocate a medium block--------------------------}
{Get the block size and bin number for this block size. Block sizes are
rounded up to the next bin size.}
LBlockSize := ((NativeUInt(ASize) + (MediumBlockGranularity - 1 + BlockHeaderSize - MediumBlockSizeOffset))
and -MediumBlockGranularity) + MediumBlockSizeOffset;
{Get the bin number}
LBinNumber := (LBlockSize - MinimumMediumBlockSize) div MediumBlockGranularity;
{Lock the medium blocks}
LockMediumBlocks;
{Calculate the bin group}
LBinGroupNumber := LBinNumber div 32;
{Is there a suitable block inside this group?}
LBinGroupMasked := MediumBlockBinBitmaps[LBinGroupNumber] and -(1 shl (LBinNumber and 31));
if LBinGroupMasked <> 0 then
begin
{Get the actual bin number}
LBinNumber := FindFirstSetBit(LBinGroupMasked) + LBinGroupNumber * 32;
end
else
begin
{$ifndef FullDebugMode}
{Try all groups greater than this group}
LBinGroupsMasked := MediumBlockBinGroupBitmap and -(2 shl LBinGroupNumber);
if LBinGroupsMasked <> 0 then
begin
{There is a suitable group with space: get the bin number}
LBinGroupNumber := FindFirstSetBit(LBinGroupsMasked);
{Get the bin in the group with free blocks}
LBinNumber := FindFirstSetBit(MediumBlockBinBitmaps[LBinGroupNumber])
+ LBinGroupNumber * 32;
end
else
begin
{$endif}
{There are no bins with a suitable block: Sequentially feed the required block}
LSequentialFeedFreeSize := MediumSequentialFeedBytesLeft;
if LSequentialFeedFreeSize >= LBlockSize then
begin
{$ifdef FullDebugMode}
{In full debug mode a medium block must have enough bytes to fit
all the debug info, so we must make sure there are no tiny medium
blocks at the start of the pool.}
if LSequentialFeedFreeSize - LBlockSize < (FullDebugBlockOverhead + BlockHeaderSize) then
LBlockSize := LSequentialFeedFreeSize;
{$endif}
{Block can be fed sequentially}
Result := Pointer(PByte(LastSequentiallyFedMediumBlock) - LBlockSize);
{Store the last sequentially fed block}
LastSequentiallyFedMediumBlock := Result;
{Store the remaining bytes}
MediumSequentialFeedBytesLeft := LSequentialFeedFreeSize - LBlockSize;
{Set the flags for the block}
PNativeUInt(PByte(Result) - BlockHeaderSize)^ := LBlockSize or IsMediumBlockFlag;
end
else
begin
{Need to allocate a new sequential feed block}
Result := AllocNewSequentialFeedMediumPool(LBlockSize);
end;
{$ifdef FullDebugMode}
{Block was fed sequentially - we need to set a valid debug header}
if Result <> nil then
begin
PFullDebugBlockHeader(Result).HeaderCheckSum := NativeUInt(Result);
PNativeUInt(PByte(Result) + SizeOf(TFullDebugBlockHeader))^ := not NativeUInt(Result);
{Clear the user area of the block}
DebugFillMem(Pointer(PByte(Result) + SizeOf(TFullDebugBlockHeader) + SizeOf(NativeUInt))^,
LBlockSize - FullDebugBlockOverhead - SizeOf(NativeUInt),
{$ifndef CatchUseOfFreedInterfaces}DebugFillPattern{$else}NativeUInt(@VMTBadInterface){$endif});
end;
{$endif}
{Done}
MediumBlocksLocked := False;
Exit;
{$ifndef FullDebugMode}
end;
{$endif}
end;
{If we get here we have a valid LBinGroupNumber and LBinNumber:
Use the first block in the bin, splitting it if necessary}
{Get a pointer to the bin}
LPMediumBin := @MediumBlockBins[LBinNumber];
{Get the result}
Result := LPMediumBin.NextFreeBlock;
{$ifdef CheckHeapForCorruption}
{Check that this block is actually free and the next and previous blocks
are both in use (except in full debug mode).}
if ((PNativeUInt(PByte(Result) - BlockHeaderSize)^ and {$ifndef FullDebugMode}ExtractMediumAndLargeFlagsMask{$else}(IsMediumBlockFlag or IsFreeBlockFlag){$endif}) <> (IsFreeBlockFlag or IsMediumBlockFlag))
{$ifndef FullDebugMode}
or ((PNativeUInt(PByte(Result) + (PNativeUInt(PByte(Result) - BlockHeaderSize)^ and DropMediumAndLargeFlagsMask) - BlockHeaderSize)^ and (ExtractMediumAndLargeFlagsMask - IsSmallBlockPoolInUseFlag)) <> (IsMediumBlockFlag or PreviousMediumBlockIsFreeFlag))
{$endif}
then
begin
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
end;
{$endif}
{Remove the block from the bin containing it}
RemoveMediumFreeBlock(Result);
{Get the block size}
LAvailableBlockSize := PNativeUInt(PByte(Result) - BlockHeaderSize)^ and DropMediumAndLargeFlagsMask;
{$ifndef FullDebugMode}
{Is it an exact fit or not?}
LSecondSplitSize := LAvailableBlockSize - LBlockSize;
if LSecondSplitSize <> 0 then
begin
{Split the block in two}
LSecondSplit := PMediumFreeBlock(PByte(Result) + LBlockSize);
{Set the size of the second split}
PNativeUInt(PByte(LSecondSplit) - BlockHeaderSize)^ := LSecondSplitSize or (IsMediumBlockFlag or IsFreeBlockFlag);
{Store the size of the second split}
PNativeUInt(PByte(LSecondSplit) + LSecondSplitSize - 2 * BlockHeaderSize)^ := LSecondSplitSize;
{Put the remainder in a bin if it is big enough}
if LSecondSplitSize >= MinimumMediumBlockSize then
InsertMediumBlockIntoBin(LSecondSplit, LSecondSplitSize);
end
else
begin
{$else}
{In full debug mode blocks are never split or coalesced}
LBlockSize := LAvailableBlockSize;
{$endif}
{Mark this block as used in the block following it}
LNextMediumBlockHeader := Pointer(PByte(Result) + LBlockSize - BlockHeaderSize);
{$ifndef FullDebugMode}
{$ifdef CheckHeapForCorruption}
{The next block must be in use}
if (LNextMediumBlockHeader^ and (ExtractMediumAndLargeFlagsMask - IsSmallBlockPoolInUseFlag)) <> (IsMediumBlockFlag or PreviousMediumBlockIsFreeFlag) then
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
{$endif}
{$endif}
LNextMediumBlockHeader^ :=
LNextMediumBlockHeader^ and (not PreviousMediumBlockIsFreeFlag);
{$ifndef FullDebugMode}
end;
{Set the size and flags for this block}
PNativeUInt(PByte(Result) - BlockHeaderSize)^ := LBlockSize or IsMediumBlockFlag;
{$else}
{In full debug mode blocks are never split or coalesced}
Dec(PNativeUInt(PByte(Result) - BlockHeaderSize)^, IsFreeBlockFlag);
{$endif}
{Unlock the medium blocks}
MediumBlocksLocked := False;
end
else
begin
{Allocate a Large block}
if ASize > 0 then
Result := AllocateLargeBlock(ASize)
else
Result := nil;
end;
end;
end;
{$else}
{$ifdef 32Bit}
asm
{On entry:
eax = ASize}
{Since most allocations are for small blocks, determine the small block type
index so long}
lea edx, [eax + BlockHeaderSize - 1]
{$ifdef Align16Bytes}
shr edx, 4
{$else}
shr edx, 3
{$endif}
{Is it a small block?}
cmp eax, (MaximumSmallBlockSize - BlockHeaderSize)
{Save ebx}
push ebx
{Get the IsMultiThread variable so long}
{$ifndef AssumeMultiThreaded}
mov cl, IsMultiThread
{$endif}
{Is it a small block?}
ja @NotASmallBlock
{Do we need to lock the block type?}
{$ifndef AssumeMultiThreaded}
test cl, cl
{$endif}
{Get the small block type in ebx}
movzx eax, byte ptr [AllocSize2SmallBlockTypeIndX4 + edx]
lea ebx, [SmallBlockTypes + eax * 8]
{Do we need to lock the block type?}
{$ifndef AssumeMultiThreaded}
jnz @LockBlockTypeLoop
{$else}
jmp @LockBlockTypeLoop
{Align branch target}
nop
nop
{$endif}
@GotLockOnSmallBlockType:
{Find the next free block: Get the first pool with free blocks in edx}
mov edx, TSmallBlockType[ebx].NextPartiallyFreePool
{Get the first free block (or the next sequential feed address if edx = ebx)}
mov eax, TSmallBlockPoolHeader[edx].FirstFreeBlock
{Get the drop flags mask in ecx so long}
mov ecx, DropSmallFlagsMask
{Is there a pool with free blocks?}
cmp edx, ebx
je @TrySmallSequentialFeed
{Increment the number of used blocks}
add TSmallBlockPoolHeader[edx].BlocksInUse, 1
{Get the new first free block}
and ecx, [eax - 4]
{Set the new first free block}
mov TSmallBlockPoolHeader[edx].FirstFreeBlock, ecx
{Set the block header}
mov [eax - 4], edx
{Is the chunk now full?}
jz @RemoveSmallPool
{Unlock the block type}
mov TSmallBlockType[ebx].BlockTypeLocked, False
{Restore ebx}
pop ebx
{All done}
ret
{Align branch target}
{$ifndef AssumeMultiThreaded}
nop
nop
{$endif}
nop
@TrySmallSequentialFeed:
{Try to feed a small block sequentially: Get the sequential feed block pool}
mov edx, TSmallBlockType[ebx].CurrentSequentialFeedPool
{Get the next sequential feed address so long}
movzx ecx, TSmallBlockType[ebx].BlockSize
add ecx, eax
{Can another block fit?}
cmp eax, TSmallBlockType[ebx].MaxSequentialFeedBlockAddress
ja @AllocateSmallBlockPool
{Increment the number of used blocks in the sequential feed pool}
add TSmallBlockPoolHeader[edx].BlocksInUse, 1
{Store the next sequential feed block address}
mov TSmallBlockType[ebx].NextSequentialFeedBlockAddress, ecx
{Unlock the block type}
mov TSmallBlockType[ebx].BlockTypeLocked, False
{Set the block header}
mov [eax - 4], edx
{Restore ebx}
pop ebx
{All done}
ret
{Align branch target}
nop
nop
nop
@RemoveSmallPool:
{Pool is full - remove it from the partially free list}
mov ecx, TSmallBlockPoolHeader[edx].NextPartiallyFreePool
mov TSmallBlockPoolHeader[ecx].PreviousPartiallyFreePool, ebx
mov TSmallBlockType[ebx].NextPartiallyFreePool, ecx
{Unlock the block type}
mov TSmallBlockType[ebx].BlockTypeLocked, False
{Restore ebx}
pop ebx
{All done}
ret
{Align branch target}
nop
nop
@LockBlockTypeLoop:
mov eax, $100
{Attempt to grab the block type}
lock cmpxchg TSmallBlockType([ebx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{Try the next size}
add ebx, Type(TSmallBlockType)
mov eax, $100
lock cmpxchg TSmallBlockType([ebx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{Try the next size (up to two sizes larger)}
add ebx, Type(TSmallBlockType)
mov eax, $100
lock cmpxchg TSmallBlockType([ebx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{Block type and two sizes larger are all locked - give up and sleep}
sub ebx, 2 * Type(TSmallBlockType)
{$ifdef NeverSleepOnThreadContention}
{Pause instruction (improves performance on P4)}
rep nop
{$ifdef UseSwitchToThread}
call SwitchToThread
{$endif}
{Try again}
jmp @LockBlockTypeLoop
{Align branch target}
nop
{$ifndef UseSwitchToThread}
nop
{$endif}
{$else}
{Couldn't grab the block type - sleep and try again}
push InitialSleepTime
call Sleep
{Try again}
mov eax, $100
{Attempt to grab the block type}
lock cmpxchg TSmallBlockType([ebx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{Couldn't grab the block type - sleep and try again}
push AdditionalSleepTime
call Sleep
{Try again}
jmp @LockBlockTypeLoop
{Align branch target}
nop
nop
nop
{$endif}
@AllocateSmallBlockPool:
{save additional registers}
push esi
push edi
{Do we need to lock the medium blocks?}
{$ifndef AssumeMultiThreaded}
cmp IsMultiThread, False
je @MediumBlocksLockedForPool
{$endif}
call LockMediumBlocks
@MediumBlocksLockedForPool:
{Are there any available blocks of a suitable size?}
movsx esi, TSmallBlockType[ebx].AllowedGroupsForBlockPoolBitmap
and esi, MediumBlockBinGroupBitmap
jz @NoSuitableMediumBlocks
{Get the bin group number with free blocks in eax}
bsf eax, esi
{Get the bin number in ecx}
lea esi, [eax * 8]
mov ecx, dword ptr [MediumBlockBinBitmaps + eax * 4]
bsf ecx, ecx
lea ecx, [ecx + esi * 4]
{Get a pointer to the bin in edi}
lea edi, [MediumBlockBins + ecx * 8]
{Get the free block in esi}
mov esi, TMediumFreeBlock[edi].NextFreeBlock
{Remove the first block from the linked list (LIFO)}
mov edx, TMediumFreeBlock[esi].NextFreeBlock
mov TMediumFreeBlock[edi].NextFreeBlock, edx
mov TMediumFreeBlock[edx].PreviousFreeBlock, edi
{Is this bin now empty?}
cmp edi, edx
jne @MediumBinNotEmpty
{eax = bin group number, ecx = bin number, edi = @bin, esi = free block, ebx = block type}
{Flag this bin as empty}
mov edx, -2
rol edx, cl
and dword ptr [MediumBlockBinBitmaps + eax * 4], edx
jnz @MediumBinNotEmpty
{Flag the group as empty}
btr MediumBlockBinGroupBitmap, eax
@MediumBinNotEmpty:
{esi = free block, ebx = block type}
{Get the size of the available medium block in edi}
mov edi, DropMediumAndLargeFlagsMask
and edi, [esi - 4]
cmp edi, MaximumSmallBlockPoolSize
jb @UseWholeBlock
{Split the block: get the size of the second part, new block size is the
optimal size}
mov edx, edi
movzx edi, TSmallBlockType[ebx].OptimalBlockPoolSize
sub edx, edi
{Split the block in two}
lea eax, [esi + edi]
lea ecx, [edx + IsMediumBlockFlag + IsFreeBlockFlag]
mov [eax - 4], ecx
{Store the size of the second split as the second last dword}
mov [eax + edx - 8], edx
{Put the remainder in a bin (it will be big enough)}
call InsertMediumBlockIntoBin
jmp @GotMediumBlock
{Align branch target}
{$ifdef AssumeMultiThreaded}
nop
{$endif}
@NoSuitableMediumBlocks:
{Check the sequential feed medium block pool for space}
movzx ecx, TSmallBlockType[ebx].MinimumBlockPoolSize
mov edi, MediumSequentialFeedBytesLeft
cmp edi, ecx
jb @AllocateNewSequentialFeed
{Get the address of the last block that was fed}
mov esi, LastSequentiallyFedMediumBlock
{Enough sequential feed space: Will the remainder be usable?}
movzx ecx, TSmallBlockType[ebx].OptimalBlockPoolSize
lea edx, [ecx + MinimumMediumBlockSize]
cmp edi, edx
jb @NotMuchSpace
mov edi, ecx
@NotMuchSpace:
sub esi, edi
{Update the sequential feed parameters}
sub MediumSequentialFeedBytesLeft, edi
mov LastSequentiallyFedMediumBlock, esi
{Get the block pointer}
jmp @GotMediumBlock
{Align branch target}
@AllocateNewSequentialFeed:
{Need to allocate a new sequential feed medium block pool: use the
optimal size for this small block pool}
movzx eax, TSmallBlockType[ebx].OptimalBlockPoolSize
mov edi, eax
{Allocate the medium block pool}
call AllocNewSequentialFeedMediumPool
mov esi, eax
test eax, eax
jnz @GotMediumBlock
mov MediumBlocksLocked, al
mov TSmallBlockType[ebx].BlockTypeLocked, al
pop edi
pop esi
pop ebx
ret
{Align branch target}
@UseWholeBlock:
{esi = free block, ebx = block type, edi = block size}
{Mark this block as used in the block following it}
and byte ptr [esi + edi - 4], not PreviousMediumBlockIsFreeFlag
@GotMediumBlock:
{esi = free block, ebx = block type, edi = block size}
{Set the size and flags for this block}
lea ecx, [edi + IsMediumBlockFlag + IsSmallBlockPoolInUseFlag]
mov [esi - 4], ecx
{Unlock medium blocks}
xor eax, eax
mov MediumBlocksLocked, al
{Set up the block pool}
mov TSmallBlockPoolHeader[esi].BlockType, ebx
mov TSmallBlockPoolHeader[esi].FirstFreeBlock, eax
mov TSmallBlockPoolHeader[esi].BlocksInUse, 1
{Set it up for sequential block serving}
mov TSmallBlockType[ebx].CurrentSequentialFeedPool, esi
{Return the pointer to the first block}
lea eax, [esi + SmallBlockPoolHeaderSize]
movzx ecx, TSmallBlockType[ebx].BlockSize
lea edx, [eax + ecx]
mov TSmallBlockType[ebx].NextSequentialFeedBlockAddress, edx
add edi, esi
sub edi, ecx
mov TSmallBlockType[ebx].MaxSequentialFeedBlockAddress, edi
{Unlock the small block type}
mov TSmallBlockType[ebx].BlockTypeLocked, False
{Set the small block header}
mov [eax - 4], esi
{Restore registers}
pop edi
pop esi
pop ebx
{Done}
ret
{-------------------Medium block allocation-------------------}
{Align branch target}
nop
@NotASmallBlock:
cmp eax, (MaximumMediumBlockSize - BlockHeaderSize)
ja @IsALargeBlockRequest
{Get the bin size for this block size. Block sizes are
rounded up to the next bin size.}
lea ebx, [eax + MediumBlockGranularity - 1 + BlockHeaderSize - MediumBlockSizeOffset]
and ebx, -MediumBlockGranularity
add ebx, MediumBlockSizeOffset
{Do we need to lock the medium blocks?}
{$ifndef AssumeMultiThreaded}
test cl, cl
jz @MediumBlocksLocked
{$endif}
call LockMediumBlocks
@MediumBlocksLocked:
{Get the bin number in ecx and the group number in edx}
lea edx, [ebx - MinimumMediumBlockSize]
mov ecx, edx
shr edx, 8 + 5
shr ecx, 8
{Is there a suitable block inside this group?}
mov eax, -1
shl eax, cl
and eax, dword ptr [MediumBlockBinBitmaps + edx * 4]
jz @GroupIsEmpty
{Get the actual bin number}
and ecx, -32
bsf eax, eax
or ecx, eax
jmp @GotBinAndGroup
{Align branch target}
nop
@GroupIsEmpty:
{Try all groups greater than this group}
mov eax, -2
mov ecx, edx
shl eax, cl
and eax, MediumBlockBinGroupBitmap
jz @TrySequentialFeedMedium
{There is a suitable group with space: get the bin number}
bsf edx, eax
{Get the bin in the group with free blocks}
mov eax, dword ptr [MediumBlockBinBitmaps + edx * 4]
bsf ecx, eax
mov eax, edx
shl eax, 5
or ecx, eax
jmp @GotBinAndGroup
{Align branch target}
nop
@TrySequentialFeedMedium:
mov ecx, MediumSequentialFeedBytesLeft
{Block can be fed sequentially?}
sub ecx, ebx
jc @AllocateNewSequentialFeedForMedium
{Get the block address}
mov eax, LastSequentiallyFedMediumBlock
sub eax, ebx
mov LastSequentiallyFedMediumBlock, eax
{Store the remaining bytes}
mov MediumSequentialFeedBytesLeft, ecx
{Set the flags for the block}
or ebx, IsMediumBlockFlag
mov [eax - 4], ebx
jmp @MediumBlockGetDone
{Align branch target}
@AllocateNewSequentialFeedForMedium:
mov eax, ebx
call AllocNewSequentialFeedMediumPool
@MediumBlockGetDone:
mov MediumBlocksLocked, False
pop ebx
ret
{Align branch target}
@GotBinAndGroup:
{ebx = block size, ecx = bin number, edx = group number}
push esi
push edi
{Get a pointer to the bin in edi}
lea edi, [MediumBlockBins + ecx * 8]
{Get the free block in esi}
mov esi, TMediumFreeBlock[edi].NextFreeBlock
{Remove the first block from the linked list (LIFO)}
mov eax, TMediumFreeBlock[esi].NextFreeBlock
mov TMediumFreeBlock[edi].NextFreeBlock, eax
mov TMediumFreeBlock[eax].PreviousFreeBlock, edi
{Is this bin now empty?}
cmp edi, eax
jne @MediumBinNotEmptyForMedium
{eax = bin group number, ecx = bin number, edi = @bin, esi = free block, ebx = block size}
{Flag this bin as empty}
mov eax, -2
rol eax, cl
and dword ptr [MediumBlockBinBitmaps + edx * 4], eax
jnz @MediumBinNotEmptyForMedium
{Flag the group as empty}
btr MediumBlockBinGroupBitmap, edx
@MediumBinNotEmptyForMedium:
{esi = free block, ebx = block size}
{Get the size of the available medium block in edi}
mov edi, DropMediumAndLargeFlagsMask
and edi, [esi - 4]
{Get the size of the second split in edx}
mov edx, edi
sub edx, ebx
jz @UseWholeBlockForMedium
{Split the block in two}
lea eax, [esi + ebx]
lea ecx, [edx + IsMediumBlockFlag + IsFreeBlockFlag]
mov [eax - 4], ecx
{Store the size of the second split as the second last dword}
mov [eax + edx - 8], edx
{Put the remainder in a bin}
cmp edx, MinimumMediumBlockSize
jb @GotMediumBlockForMedium
call InsertMediumBlockIntoBin
jmp @GotMediumBlockForMedium
{Align branch target}
nop
nop
nop
@UseWholeBlockForMedium:
{Mark this block as used in the block following it}
and byte ptr [esi + edi - 4], not PreviousMediumBlockIsFreeFlag
@GotMediumBlockForMedium:
{Set the size and flags for this block}
lea ecx, [ebx + IsMediumBlockFlag]
mov [esi - 4], ecx
{Unlock medium blocks}
mov MediumBlocksLocked, False
mov eax, esi
pop edi
pop esi
pop ebx
ret
{-------------------Large block allocation-------------------}
{Align branch target}
@IsALargeBlockRequest:
pop ebx
test eax, eax
jns AllocateLargeBlock
xor eax, eax
end;
{$else}
{64-bit BASM implementation}
asm
{On entry:
rcx = ASize}
.params 2
.pushnv rbx
.pushnv rsi
.pushnv rdi
{Since most allocations are for small blocks, determine the small block type
index so long}
lea edx, [ecx + BlockHeaderSize - 1]
{$ifdef Align16Bytes}
shr edx, 4
{$else}
shr edx, 3
{$endif}
{Preload the addresses of some small block structures}
lea r8, AllocSize2SmallBlockTypeIndX4
lea rbx, SmallBlockTypes
{$ifndef AssumeMultiThreaded}
{Get the IsMultiThread variable so long}
movzx esi, IsMultiThread
{$endif}
{Is it a small block?}
cmp rcx, (MaximumSmallBlockSize - BlockHeaderSize)
ja @NotASmallBlock
{Get the small block type pointer in rbx}
movzx ecx, byte ptr [r8 + rdx]
shl ecx, 4 //SizeOf(TSmallBlockType) = 64
add rbx, rcx
{Do we need to lock the block type?}
{$ifndef AssumeMultiThreaded}
test esi, esi
jnz @LockBlockTypeLoop
{$else}
jmp @LockBlockTypeLoop
{$endif}
@GotLockOnSmallBlockType:
{Find the next free block: Get the first pool with free blocks in rdx}
mov rdx, TSmallBlockType[rbx].NextPartiallyFreePool
{Get the first free block (or the next sequential feed address if rdx = rbx)}
mov rax, TSmallBlockPoolHeader[rdx].FirstFreeBlock
{Get the drop flags mask in rcx so long}
mov rcx, DropSmallFlagsMask
{Is there a pool with free blocks?}
cmp rdx, rbx
je @TrySmallSequentialFeed
{Increment the number of used blocks}
add TSmallBlockPoolHeader[rdx].BlocksInUse, 1
{Get the new first free block}
and rcx, [rax - BlockHeaderSize]
{Set the new first free block}
mov TSmallBlockPoolHeader[rdx].FirstFreeBlock, rcx
{Set the block header}
mov [rax - BlockHeaderSize], rdx
{Is the chunk now full?}
jz @RemoveSmallPool
{Unlock the block type}
mov TSmallBlockType[rbx].BlockTypeLocked, False
jmp @Done
@TrySmallSequentialFeed:
{Try to feed a small block sequentially: Get the sequential feed block pool}
mov rdx, TSmallBlockType[rbx].CurrentSequentialFeedPool
{Get the next sequential feed address so long}
movzx ecx, TSmallBlockType[rbx].BlockSize
add rcx, rax
{Can another block fit?}
cmp rax, TSmallBlockType[rbx].MaxSequentialFeedBlockAddress
ja @AllocateSmallBlockPool
{Increment the number of used blocks in the sequential feed pool}
add TSmallBlockPoolHeader[rdx].BlocksInUse, 1
{Store the next sequential feed block address}
mov TSmallBlockType[rbx].NextSequentialFeedBlockAddress, rcx
{Unlock the block type}
mov TSmallBlockType[rbx].BlockTypeLocked, False
{Set the block header}
mov [rax - BlockHeaderSize], rdx
jmp @Done
@RemoveSmallPool:
{Pool is full - remove it from the partially free list}
mov rcx, TSmallBlockPoolHeader[rdx].NextPartiallyFreePool
mov TSmallBlockPoolHeader[rcx].PreviousPartiallyFreePool, rbx
mov TSmallBlockType[rbx].NextPartiallyFreePool, rcx
{Unlock the block type}
mov TSmallBlockType[rbx].BlockTypeLocked, False
jmp @Done
@LockBlockTypeLoop:
mov eax, $100
{Attempt to grab the block type}
lock cmpxchg TSmallBlockType([rbx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{Try the next size}
add rbx, Type(TSmallBlockType)
mov eax, $100
lock cmpxchg TSmallBlockType([rbx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{Try the next size (up to two sizes larger)}
add rbx, Type(TSmallBlockType)
mov eax, $100
lock cmpxchg TSmallBlockType([rbx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{Block type and two sizes larger are all locked - give up and sleep}
sub rbx, 2 * Type(TSmallBlockType)
{$ifdef NeverSleepOnThreadContention}
{Pause instruction (improves performance on P4)}
pause
{$ifdef UseSwitchToThread}
call SwitchToThread
{$endif}
{Try again}
jmp @LockBlockTypeLoop
{$else}
{Couldn't grab the block type - sleep and try again}
mov ecx, InitialSleepTime
call Sleep
{Try again}
mov eax, $100
{Attempt to grab the block type}
lock cmpxchg TSmallBlockType([rbx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{Couldn't grab the block type - sleep and try again}
mov ecx, AdditionalSleepTime
call Sleep
{Try again}
jmp @LockBlockTypeLoop
{$endif}
@AllocateSmallBlockPool:
{Do we need to lock the medium blocks?}
{$ifndef AssumeMultiThreaded}
test esi, esi
jz @MediumBlocksLockedForPool
{$endif}
call LockMediumBlocks
@MediumBlocksLockedForPool:
{Are there any available blocks of a suitable size?}
movsx esi, TSmallBlockType[rbx].AllowedGroupsForBlockPoolBitmap
and esi, MediumBlockBinGroupBitmap
jz @NoSuitableMediumBlocks
{Get the bin group number with free blocks in eax}
bsf eax, esi
{Get the bin number in ecx}
lea r8, MediumBlockBinBitmaps
lea r9, [rax * 4]
mov ecx, [r8 + r9]
bsf ecx, ecx
lea ecx, [ecx + r9d * 8]
{Get a pointer to the bin in edi}
lea rdi, MediumBlockBins
lea esi, [ecx * 8]
lea rdi, [rdi + rsi * 2] //SizeOf(TMediumBlockBin) = 16
{Get the free block in rsi}
mov rsi, TMediumFreeBlock[rdi].NextFreeBlock
{Remove the first block from the linked list (LIFO)}
mov rdx, TMediumFreeBlock[rsi].NextFreeBlock
mov TMediumFreeBlock[rdi].NextFreeBlock, rdx
mov TMediumFreeBlock[rdx].PreviousFreeBlock, rdi
{Is this bin now empty?}
cmp rdi, rdx
jne @MediumBinNotEmpty
{r8 = @MediumBlockBinBitmaps, eax = bin group number,
r9 = bin group number * 4, ecx = bin number, edi = @bin, esi = free block,
ebx = block type}
{Flag this bin as empty}
mov edx, -2
rol edx, cl
and [r8 + r9], edx
jnz @MediumBinNotEmpty
{Flag the group as empty}
btr MediumBlockBinGroupBitmap, eax
@MediumBinNotEmpty:
{esi = free block, ebx = block type}
{Get the size of the available medium block in edi}
mov rdi, DropMediumAndLargeFlagsMask
and rdi, [rsi - BlockHeaderSize]
cmp edi, MaximumSmallBlockPoolSize
jb @UseWholeBlock
{Split the block: get the size of the second part, new block size is the
optimal size}
mov edx, edi
movzx edi, TSmallBlockType[rbx].OptimalBlockPoolSize
sub edx, edi
{Split the block in two}
lea rcx, [rsi + rdi]
lea rax, [rdx + IsMediumBlockFlag + IsFreeBlockFlag]
mov [rcx - BlockHeaderSize], rax
{Store the size of the second split as the second last qword}
mov [rcx + rdx - BlockHeaderSize * 2], rdx
{Put the remainder in a bin (it will be big enough)}
call InsertMediumBlockIntoBin
jmp @GotMediumBlock
@NoSuitableMediumBlocks:
{Check the sequential feed medium block pool for space}
movzx ecx, TSmallBlockType[rbx].MinimumBlockPoolSize
mov edi, MediumSequentialFeedBytesLeft
cmp edi, ecx
jb @AllocateNewSequentialFeed
{Get the address of the last block that was fed}
mov rsi, LastSequentiallyFedMediumBlock
{Enough sequential feed space: Will the remainder be usable?}
movzx ecx, TSmallBlockType[rbx].OptimalBlockPoolSize
lea edx, [ecx + MinimumMediumBlockSize]
cmp edi, edx
jb @NotMuchSpace
mov edi, ecx
@NotMuchSpace:
sub rsi, rdi
{Update the sequential feed parameters}
sub MediumSequentialFeedBytesLeft, edi
mov LastSequentiallyFedMediumBlock, rsi
{Get the block pointer}
jmp @GotMediumBlock
{Align branch target}
@AllocateNewSequentialFeed:
{Need to allocate a new sequential feed medium block pool: use the
optimal size for this small block pool}
movzx ecx, TSmallBlockType[rbx].OptimalBlockPoolSize
mov edi, ecx
{Allocate the medium block pool}
call AllocNewSequentialFeedMediumPool
mov rsi, rax
test rax, rax
jnz @GotMediumBlock
mov MediumBlocksLocked, al
mov TSmallBlockType[rbx].BlockTypeLocked, al
jmp @Done
@UseWholeBlock:
{rsi = free block, rbx = block type, edi = block size}
{Mark this block as used in the block following it}
and byte ptr [rsi + rdi - BlockHeaderSize], not PreviousMediumBlockIsFreeFlag
@GotMediumBlock:
{rsi = free block, rbx = block type, edi = block size}
{Set the size and flags for this block}
lea ecx, [edi + IsMediumBlockFlag + IsSmallBlockPoolInUseFlag]
mov [rsi - BlockHeaderSize], rcx
{Unlock medium blocks}
xor eax, eax
mov MediumBlocksLocked, al
{Set up the block pool}
mov TSmallBlockPoolHeader[rsi].BlockType, rbx
mov TSmallBlockPoolHeader[rsi].FirstFreeBlock, rax
mov TSmallBlockPoolHeader[rsi].BlocksInUse, 1
{Set it up for sequential block serving}
mov TSmallBlockType[rbx].CurrentSequentialFeedPool, rsi
{Return the pointer to the first block}
lea rax, [rsi + SmallBlockPoolHeaderSize]
movzx ecx, TSmallBlockType[rbx].BlockSize
lea rdx, [rax + rcx]
mov TSmallBlockType[rbx].NextSequentialFeedBlockAddress, rdx
add rdi, rsi
sub rdi, rcx
mov TSmallBlockType[rbx].MaxSequentialFeedBlockAddress, rdi
{Unlock the small block type}
mov TSmallBlockType[rbx].BlockTypeLocked, False
{Set the small block header}
mov [rax - BlockHeaderSize], rsi
jmp @Done
{-------------------Medium block allocation-------------------}
@NotASmallBlock:
cmp rcx, (MaximumMediumBlockSize - BlockHeaderSize)
ja @IsALargeBlockRequest
{Get the bin size for this block size. Block sizes are
rounded up to the next bin size.}
lea ebx, [ecx + MediumBlockGranularity - 1 + BlockHeaderSize - MediumBlockSizeOffset]
and ebx, -MediumBlockGranularity
add ebx, MediumBlockSizeOffset
{Do we need to lock the medium blocks?}
{$ifndef AssumeMultiThreaded}
test esi, esi
jz @MediumBlocksLocked
{$endif}
call LockMediumBlocks
@MediumBlocksLocked:
{Get the bin number in ecx and the group number in edx}
lea edx, [ebx - MinimumMediumBlockSize]
mov ecx, edx
shr edx, 8 + 5
shr ecx, 8
{Is there a suitable block inside this group?}
mov eax, -1
shl eax, cl
lea r8, MediumBlockBinBitmaps
and eax, [r8 + rdx * 4]
jz @GroupIsEmpty
{Get the actual bin number}
and ecx, -32
bsf eax, eax
or ecx, eax
jmp @GotBinAndGroup
@GroupIsEmpty:
{Try all groups greater than this group}
mov eax, -2
mov ecx, edx
shl eax, cl
and eax, MediumBlockBinGroupBitmap
jz @TrySequentialFeedMedium
{There is a suitable group with space: get the bin number}
bsf edx, eax
{Get the bin in the group with free blocks}
mov eax, [r8 + rdx * 4]
bsf ecx, eax
mov eax, edx
shl eax, 5
or ecx, eax
jmp @GotBinAndGroup
@TrySequentialFeedMedium:
mov ecx, MediumSequentialFeedBytesLeft
{Block can be fed sequentially?}
sub ecx, ebx
jc @AllocateNewSequentialFeedForMedium
{Get the block address}
mov rax, LastSequentiallyFedMediumBlock
sub rax, rbx
mov LastSequentiallyFedMediumBlock, rax
{Store the remaining bytes}
mov MediumSequentialFeedBytesLeft, ecx
{Set the flags for the block}
or rbx, IsMediumBlockFlag
mov [rax - BlockHeaderSize], rbx
jmp @MediumBlockGetDone
@AllocateNewSequentialFeedForMedium:
mov ecx, ebx
call AllocNewSequentialFeedMediumPool
@MediumBlockGetDone:
xor cl, cl
mov MediumBlocksLocked, cl //workaround for QC99023
jmp @Done
@GotBinAndGroup:
{ebx = block size, ecx = bin number, edx = group number}
{Get a pointer to the bin in edi}
lea rdi, MediumBlockBins
lea eax, [ecx + ecx]
lea rdi, [rdi + rax * 8]
{Get the free block in esi}
mov rsi, TMediumFreeBlock[rdi].NextFreeBlock
{Remove the first block from the linked list (LIFO)}
mov rax, TMediumFreeBlock[rsi].NextFreeBlock
mov TMediumFreeBlock[rdi].NextFreeBlock, rax
mov TMediumFreeBlock[rax].PreviousFreeBlock, rdi
{Is this bin now empty?}
cmp rdi, rax
jne @MediumBinNotEmptyForMedium
{edx = bin group number, ecx = bin number, rdi = @bin, rsi = free block, ebx = block size}
{Flag this bin as empty}
mov eax, -2
rol eax, cl
lea r8, MediumBlockBinBitmaps
and [r8 + rdx * 4], eax
jnz @MediumBinNotEmptyForMedium
{Flag the group as empty}
btr MediumBlockBinGroupBitmap, edx
@MediumBinNotEmptyForMedium:
{rsi = free block, ebx = block size}
{Get the size of the available medium block in edi}
mov rdi, DropMediumAndLargeFlagsMask
and rdi, [rsi - BlockHeaderSize]
{Get the size of the second split in edx}
mov edx, edi
sub edx, ebx
jz @UseWholeBlockForMedium
{Split the block in two}
lea rcx, [rsi + rbx]
lea rax, [rdx + IsMediumBlockFlag + IsFreeBlockFlag]
mov [rcx - BlockHeaderSize], rax
{Store the size of the second split as the second last dword}
mov [rcx + rdx - BlockHeaderSize * 2], rdx
{Put the remainder in a bin}
cmp edx, MinimumMediumBlockSize
jb @GotMediumBlockForMedium
call InsertMediumBlockIntoBin
jmp @GotMediumBlockForMedium
@UseWholeBlockForMedium:
{Mark this block as used in the block following it}
and byte ptr [rsi + rdi - BlockHeaderSize], not PreviousMediumBlockIsFreeFlag
@GotMediumBlockForMedium:
{Set the size and flags for this block}
lea rcx, [rbx + IsMediumBlockFlag]
mov [rsi - BlockHeaderSize], rcx
{Unlock medium blocks}
xor cl, cl
mov MediumBlocksLocked, cl //workaround for QC99023
mov rax, rsi
jmp @Done
{-------------------Large block allocation-------------------}
@IsALargeBlockRequest:
xor rax, rax
test rcx, rcx
js @Done
call AllocateLargeBlock
@Done:
end;
{$endif}
{$endif}
{$ifndef ASMVersion}
{Frees a medium block, returning 0 on success, -1 otherwise}
function FreeMediumBlock(APointer: Pointer): Integer;
var
LNextMediumBlock{$ifndef FullDebugMode}, LPreviousMediumBlock{$endif}: PMediumFreeBlock;
LNextMediumBlockSizeAndFlags: NativeUInt;
LBlockSize{$ifndef FullDebugMode}, LPreviousMediumBlockSize{$endif}: Cardinal;
{$ifndef FullDebugMode}
LPPreviousMediumBlockPoolHeader, LPNextMediumBlockPoolHeader: PMediumBlockPoolHeader;
{$endif}
LBlockHeader: NativeUInt;
begin
{Get the block header}
LBlockHeader := PNativeUInt(PByte(APointer) - BlockHeaderSize)^;
{Get the medium block size}
LBlockSize := LBlockHeader and DropMediumAndLargeFlagsMask;
{Lock the medium blocks}
LockMediumBlocks;
{Can we combine this block with the next free block?}
LNextMediumBlock := PMediumFreeBlock(PByte(APointer) + LBlockSize);
LNextMediumBlockSizeAndFlags := PNativeUInt(PByte(LNextMediumBlock) - BlockHeaderSize)^;
{$ifndef FullDebugMode}
{$ifdef CheckHeapForCorruption}
{Check that this block was flagged as in use in the next block}
if (LNextMediumBlockSizeAndFlags and PreviousMediumBlockIsFreeFlag) <> 0 then
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
{$endif}
if (LNextMediumBlockSizeAndFlags and IsFreeBlockFlag) <> 0 then
begin
{Increase the size of this block}
Inc(LBlockSize, LNextMediumBlockSizeAndFlags and DropMediumAndLargeFlagsMask);
{Remove the next block as well}
if LNextMediumBlockSizeAndFlags >= MinimumMediumBlockSize then
RemoveMediumFreeBlock(LNextMediumBlock);
end
else
begin
{$endif}
{Reset the "previous in use" flag of the next block}
PNativeUInt(PByte(LNextMediumBlock) - BlockHeaderSize)^ := LNextMediumBlockSizeAndFlags or PreviousMediumBlockIsFreeFlag;
{$ifndef FullDebugMode}
end;
{Can we combine this block with the previous free block? We need to
re-read the flags since it could have changed before we could lock the
medium blocks.}
if (PNativeUInt(PByte(APointer) - BlockHeaderSize)^ and PreviousMediumBlockIsFreeFlag) <> 0 then
begin
{Get the size of the free block just before this one}
LPreviousMediumBlockSize := PNativeUInt(PByte(APointer) - 2 * BlockHeaderSize)^;
{Get the start of the previous block}
LPreviousMediumBlock := PMediumFreeBlock(PByte(APointer) - LPreviousMediumBlockSize);
{$ifdef CheckHeapForCorruption}
{Check that the previous block is actually free}
if (PNativeUInt(PByte(LPreviousMediumBlock) - BlockHeaderSize)^ and ExtractMediumAndLargeFlagsMask) <> (IsMediumBlockFlag or IsFreeBlockFlag) then
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
{$endif}
{Set the new block size}
Inc(LBlockSize, LPreviousMediumBlockSize);
{This is the new current block}
APointer := LPreviousMediumBlock;
{Remove the previous block from the linked list}
if LPreviousMediumBlockSize >= MinimumMediumBlockSize then
RemoveMediumFreeBlock(LPreviousMediumBlock);
end;
{$ifdef CheckHeapForCorruption}
{Check that the previous block is currently flagged as in use}
if (PNativeUInt(PByte(APointer) - BlockHeaderSize)^ and PreviousMediumBlockIsFreeFlag) <> 0 then
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
{$endif}
{Is the entire medium block pool free, and there are other free blocks
that can fit the largest possible medium block? -> free it. (Except in
full debug mode where medium pools are never freed.)}
if (LBlockSize <> (MediumBlockPoolSize - MediumBlockPoolHeaderSize)) then
begin
{Store the size of the block as well as the flags}
PNativeUInt(PByte(APointer) - BlockHeaderSize)^ := LBlockSize or (IsMediumBlockFlag or IsFreeBlockFlag);
{$else}
{Mark the block as free}
Inc(PNativeUInt(PByte(APointer) - BlockHeaderSize)^, IsFreeBlockFlag);
{$endif}
{Store the trailing size marker}
PNativeUInt(PByte(APointer) + LBlockSize - 2 * BlockHeaderSize)^ := LBlockSize;
{Insert this block back into the bins: Size check not required here,
since medium blocks that are in use are not allowed to be
shrunk smaller than MinimumMediumBlockSize}
InsertMediumBlockIntoBin(APointer, LBlockSize);
{$ifndef FullDebugMode}
{$ifdef CheckHeapForCorruption}
{Check that this block is actually free and the next and previous blocks are both in use.}
if ((PNativeUInt(PByte(APointer) - BlockHeaderSize)^ and ExtractMediumAndLargeFlagsMask) <> (IsMediumBlockFlag or IsFreeBlockFlag))
or ((PNativeUInt(PByte(APointer) + (PNativeUInt(PByte(APointer) - BlockHeaderSize)^ and DropMediumAndLargeFlagsMask) - BlockHeaderSize)^ and IsFreeBlockFlag) <> 0) then
begin
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
end;
{$endif}
{$endif}
{Unlock medium blocks}
MediumBlocksLocked := False;
{All OK}
Result := 0;
{$ifndef FullDebugMode}
end
else
begin
{Should this become the new sequential feed?}
if MediumSequentialFeedBytesLeft <> MediumBlockPoolSize - MediumBlockPoolHeaderSize then
begin
{Bin the current sequential feed}
BinMediumSequentialFeedRemainder;
{Set this medium pool up as the new sequential feed pool:
Store the sequential feed pool trailer}
PNativeUInt(PByte(APointer) + LBlockSize - BlockHeaderSize)^ := IsMediumBlockFlag;
{Store the number of bytes available in the sequential feed chunk}
MediumSequentialFeedBytesLeft := MediumBlockPoolSize - MediumBlockPoolHeaderSize;
{Set the last sequentially fed block}
LastSequentiallyFedMediumBlock := Pointer(PByte(APointer) + LBlockSize);
{Unlock medium blocks}
MediumBlocksLocked := False;
{Success}
Result := 0;
end
else
begin
{Remove this medium block pool from the linked list}
Dec(PByte(APointer), MediumBlockPoolHeaderSize);
LPPreviousMediumBlockPoolHeader := PMediumBlockPoolHeader(APointer).PreviousMediumBlockPoolHeader;
LPNextMediumBlockPoolHeader := PMediumBlockPoolHeader(APointer).NextMediumBlockPoolHeader;
LPPreviousMediumBlockPoolHeader.NextMediumBlockPoolHeader := LPNextMediumBlockPoolHeader;
LPNextMediumBlockPoolHeader.PreviousMediumBlockPoolHeader := LPPreviousMediumBlockPoolHeader;
{Unlock medium blocks}
MediumBlocksLocked := False;
{$ifdef ClearMediumBlockPoolsBeforeReturningToOS}
FillChar(APointer^, MediumBlockPoolSize, 0);
{$endif}
{Free the medium block pool}
if VirtualFree(APointer, 0, MEM_RELEASE) then
Result := 0
else
Result := -1;
end;
end;
{$endif}
end;
{$endif}
{Replacement for SysFreeMem}
function FastFreeMem(APointer: Pointer): Integer;
{$ifndef ASMVersion}
var
LPSmallBlockPool{$ifndef FullDebugMode}, LPPreviousPool, LPNextPool{$endif},
LPOldFirstPool: PSmallBlockPoolHeader;
LPSmallBlockType: PSmallBlockType;
LOldFirstFreeBlock: Pointer;
LBlockHeader: NativeUInt;
begin
{Get the small block header: Is it actually a small block?}
LBlockHeader := PNativeUInt(PByte(APointer) - BlockHeaderSize)^;
{Is it a small block that is in use?}
if LBlockHeader and (IsFreeBlockFlag or IsMediumBlockFlag or IsLargeBlockFlag) = 0 then
begin
{Get a pointer to the block pool}
LPSmallBlockPool := PSmallBlockPoolHeader(LBlockHeader);
{Get the block type}
LPSmallBlockType := LPSmallBlockPool.BlockType;
{$ifdef ClearSmallAndMediumBlocksInFreeMem}
FillChar(APointer^, LPSmallBlockType.BlockSize - BlockHeaderSize, 0);
{$endif}
{Lock the block type}
{$ifndef AssumeMultiThreaded}
if IsMultiThread then
{$endif}
begin
while (LockCmpxchg(0, 1, @LPSmallBlockType.BlockTypeLocked) <> 0) do
begin
{$ifdef NeverSleepOnThreadContention}
{$ifdef UseSwitchToThread}
SwitchToThread;
{$endif}
{$else}
Sleep(InitialSleepTime);
if LockCmpxchg(0, 1, @LPSmallBlockType.BlockTypeLocked) = 0 then
Break;
Sleep(AdditionalSleepTime);
{$endif}
end;
end;
{Get the old first free block}
LOldFirstFreeBlock := LPSmallBlockPool.FirstFreeBlock;
{Was the pool manager previously full?}
if LOldFirstFreeBlock = nil then
begin
{Insert this as the first partially free pool for the block size}
LPOldFirstPool := LPSmallBlockType.NextPartiallyFreePool;
LPSmallBlockPool.NextPartiallyFreePool := LPOldFirstPool;
LPOldFirstPool.PreviousPartiallyFreePool := LPSmallBlockPool;
LPSmallBlockPool.PreviousPartiallyFreePool := PSmallBlockPoolHeader(LPSmallBlockType);
LPSmallBlockType.NextPartiallyFreePool := LPSmallBlockPool;
end;
{Store the old first free block}
PNativeUInt(PByte(APointer) - BlockHeaderSize)^ := UIntPtr(LOldFirstFreeBlock) or IsFreeBlockFlag;
{Store this as the new first free block}
LPSmallBlockPool.FirstFreeBlock := APointer;
{Decrement the number of allocated blocks}
Dec(LPSmallBlockPool.BlocksInUse);
{Small block pools are never freed in full debug mode. This increases the
likehood of success in catching objects still being used after being
destroyed.}
{$ifndef FullDebugMode}
{Is the entire pool now free? -> Free it.}
if LPSmallBlockPool.BlocksInUse = 0 then
begin
{Get the previous and next chunk managers}
LPPreviousPool := LPSmallBlockPool.PreviousPartiallyFreePool;
LPNextPool := LPSmallBlockPool.NextPartiallyFreePool;
{Remove this manager}
LPPreviousPool.NextPartiallyFreePool := LPNextPool;
LPNextPool.PreviousPartiallyFreePool := LPPreviousPool;
{Is this the sequential feed pool? If so, stop sequential feeding}
if (LPSmallBlockType.CurrentSequentialFeedPool = LPSmallBlockPool) then
LPSmallBlockType.MaxSequentialFeedBlockAddress := nil;
{Unlock this block type}
LPSmallBlockType.BlockTypeLocked := False;
{Free the block pool}
FreeMediumBlock(LPSmallBlockPool);
end
else
begin
{$endif}
{Unlock this block type}
LPSmallBlockType.BlockTypeLocked := False;
{$ifndef FullDebugMode}
end;
{$endif}
{No error}
Result := 0;
end
else
begin
{Is this a medium block or a large block?}
if LBlockHeader and (IsFreeBlockFlag or IsLargeBlockFlag) = 0 then
begin
{$ifdef ClearSmallAndMediumBlocksInFreeMem}
{Get the block header, extract the block size and clear the block it.}
LBlockHeader := PNativeUInt(PByte(APointer) - BlockHeaderSize)^;
FillChar(APointer^,
(LBlockHeader and DropMediumAndLargeFlagsMask) - BlockHeaderSize, 0);
{$endif}
Result := FreeMediumBlock(APointer);
end
else
begin
{Validate: Is this actually a Large block, or is it an attempt to free an
already freed small block?}
if LBlockHeader and (IsFreeBlockFlag or IsMediumBlockFlag) = 0 then
Result := FreeLargeBlock(APointer)
else
Result := -1;
end;
end;
end;
{$else}
{$ifdef 32Bit}
asm
{Get the block header in edx}
mov edx, [eax - 4]
{Is it a small block in use?}
test dl, IsFreeBlockFlag + IsMediumBlockFlag + IsLargeBlockFlag
{Save the pointer in ecx}
mov ecx, eax
{Save ebx}
push ebx
{Get the IsMultiThread variable in bl}
{$ifndef AssumeMultiThreaded}
mov bl, IsMultiThread
{$endif}
{Is it a small block that is in use?}
jnz @NotSmallBlockInUse
{$ifdef ClearSmallAndMediumBlocksInFreeMem}
push edx
push ecx
mov edx, TSmallBlockPoolHeader[edx].BlockType
movzx edx, TSmallBlockType(edx).BlockSize
sub edx, BlockHeaderSize
xor ecx, ecx
call System.@FillChar
pop ecx
pop edx
{$endif}
{Do we need to lock the block type?}
{$ifndef AssumeMultiThreaded}
test bl, bl
{$endif}
{Get the small block type in ebx}
mov ebx, TSmallBlockPoolHeader[edx].BlockType
{Do we need to lock the block type?}
{$ifndef AssumeMultiThreaded}
jnz @LockBlockTypeLoop
{$else}
jmp @LockBlockTypeLoop
{Align branch target}
nop
{$endif}
@GotLockOnSmallBlockType:
{Current state: edx = @SmallBlockPoolHeader, ecx = APointer, ebx = @SmallBlockType}
{Decrement the number of blocks in use}
sub TSmallBlockPoolHeader[edx].BlocksInUse, 1
{Get the old first free block}
mov eax, TSmallBlockPoolHeader[edx].FirstFreeBlock
{Is the pool now empty?}
jz @PoolIsNowEmpty
{Was the pool full?}
test eax, eax
{Store this as the new first free block}
mov TSmallBlockPoolHeader[edx].FirstFreeBlock, ecx
{Store the previous first free block as the block header}
lea eax, [eax + IsFreeBlockFlag]
mov [ecx - 4], eax
{Insert the pool back into the linked list if it was full}
jz @SmallPoolWasFull
{All ok}
xor eax, eax
{Unlock the block type}
mov TSmallBlockType[ebx].BlockTypeLocked, al
{Restore registers}
pop ebx
{Done}
ret
{Align branch target}
{$ifndef AssumeMultiThreaded}
nop
{$endif}
@SmallPoolWasFull:
{Insert this as the first partially free pool for the block size}
mov ecx, TSmallBlockType[ebx].NextPartiallyFreePool
mov TSmallBlockPoolHeader[edx].PreviousPartiallyFreePool, ebx
mov TSmallBlockPoolHeader[edx].NextPartiallyFreePool, ecx
mov TSmallBlockPoolHeader[ecx].PreviousPartiallyFreePool, edx
mov TSmallBlockType[ebx].NextPartiallyFreePool, edx
{Unlock the block type}
mov TSmallBlockType[ebx].BlockTypeLocked, False
{All ok}
xor eax, eax
{Restore registers}
pop ebx
{Done}
ret
{Align branch target}
nop
nop
@PoolIsNowEmpty:
{Was this pool actually in the linked list of pools with space? If not, it
can only be the sequential feed pool (it is the only pool that may contain
only one block, i.e. other blocks have not been split off yet)}
test eax, eax
jz @IsSequentialFeedPool
{Pool is now empty: Remove it from the linked list and free it}
mov eax, TSmallBlockPoolHeader[edx].PreviousPartiallyFreePool
mov ecx, TSmallBlockPoolHeader[edx].NextPartiallyFreePool
{Remove this manager}
mov TSmallBlockPoolHeader[eax].NextPartiallyFreePool, ecx
mov TSmallBlockPoolHeader[ecx].PreviousPartiallyFreePool, eax
{Zero out eax}
xor eax, eax
{Is this the sequential feed pool? If so, stop sequential feeding}
cmp TSmallBlockType[ebx].CurrentSequentialFeedPool, edx
jne @NotSequentialFeedPool
@IsSequentialFeedPool:
mov TSmallBlockType[ebx].MaxSequentialFeedBlockAddress, eax
@NotSequentialFeedPool:
{Unlock the block type}
mov TSmallBlockType[ebx].BlockTypeLocked, al
{Release this pool}
mov eax, edx
mov edx, [edx - 4]
{$ifndef AssumeMultiThreaded}
mov bl, IsMultiThread
{$endif}
jmp @FreeMediumBlock
{Align branch target}
{$ifndef AssumeMultiThreaded}
nop
nop
{$endif}
nop
@LockBlockTypeLoop:
mov eax, $100
{Attempt to grab the block type}
lock cmpxchg TSmallBlockType([ebx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{$ifdef NeverSleepOnThreadContention}
{Pause instruction (improves performance on P4)}
rep nop
{$ifdef UseSwitchToThread}
push ecx
push edx
call SwitchToThread
pop edx
pop ecx
{$endif}
{Try again}
jmp @LockBlockTypeLoop
{Align branch target}
{$ifndef UseSwitchToThread}
nop
{$endif}
{$else}
{Couldn't grab the block type - sleep and try again}
push ecx
push edx
push InitialSleepTime
call Sleep
pop edx
pop ecx
{Try again}
mov eax, $100
{Attempt to grab the block type}
lock cmpxchg TSmallBlockType([ebx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{Couldn't grab the block type - sleep and try again}
push ecx
push edx
push AdditionalSleepTime
call Sleep
pop edx
pop ecx
{Try again}
jmp @LockBlockTypeLoop
{Align branch target}
nop
nop
{$endif}
{---------------------Medium blocks------------------------------}
{Align branch target}
@NotSmallBlockInUse:
{Not a small block in use: is it a medium or large block?}
test dl, IsFreeBlockFlag + IsLargeBlockFlag
jnz @NotASmallOrMediumBlock
@FreeMediumBlock:
{$ifdef ClearSmallAndMediumBlocksInFreeMem}
push eax
push edx
and edx, DropMediumAndLargeFlagsMask
sub edx, BlockHeaderSize
xor ecx, ecx
call System.@FillChar
pop edx
pop eax
{$endif}
{Drop the flags}
and edx, DropMediumAndLargeFlagsMask
{Free the medium block pointed to by eax, header in edx, bl = IsMultiThread}
{$ifndef AssumeMultiThreaded}
{Do we need to lock the medium blocks?}
test bl, bl
{$endif}
{Block size in ebx}
mov ebx, edx
{Save registers}
push esi
{Pointer in esi}
mov esi, eax
{Do we need to lock the medium blocks?}
{$ifndef AssumeMultiThreaded}
jz @MediumBlocksLocked
{$endif}
call LockMediumBlocks
@MediumBlocksLocked:
{Can we combine this block with the next free block?}
test dword ptr [esi + ebx - 4], IsFreeBlockFlag
{Get the next block size and flags in ecx}
mov ecx, [esi + ebx - 4]
jnz @NextBlockIsFree
{Set the "PreviousIsFree" flag in the next block}
or ecx, PreviousMediumBlockIsFreeFlag
mov [esi + ebx - 4], ecx
@NextBlockChecked:
{Can we combine this block with the previous free block? We need to
re-read the flags since it could have changed before we could lock the
medium blocks.}
test byte ptr [esi - 4], PreviousMediumBlockIsFreeFlag
jnz @PreviousBlockIsFree
@PreviousBlockChecked:
{Is the entire medium block pool free, and there are other free blocks
that can fit the largest possible medium block -> free it.}
cmp ebx, (MediumBlockPoolSize - MediumBlockPoolHeaderSize)
je @EntireMediumPoolFree
@BinFreeMediumBlock:
{Store the size of the block as well as the flags}
lea eax, [ebx + IsMediumBlockFlag + IsFreeBlockFlag]
mov [esi - 4], eax
{Store the trailing size marker}
mov [esi + ebx - 8], ebx
{Insert this block back into the bins: Size check not required here,
since medium blocks that are in use are not allowed to be
shrunk smaller than MinimumMediumBlockSize}
mov eax, esi
mov edx, ebx
{Insert into bin}
call InsertMediumBlockIntoBin
{Unlock medium blocks}
mov MediumBlocksLocked, False;
{All OK}
xor eax, eax
{Restore registers}
pop esi
pop ebx
{Return}
ret
{Align branch target}
@NextBlockIsFree:
{Get the next block address in eax}
lea eax, [esi + ebx]
{Increase the size of this block}
and ecx, DropMediumAndLargeFlagsMask
add ebx, ecx
{Was the block binned?}
cmp ecx, MinimumMediumBlockSize
jb @NextBlockChecked
call RemoveMediumFreeBlock
jmp @NextBlockChecked
{Align branch target}
nop
@PreviousBlockIsFree:
{Get the size of the free block just before this one}
mov ecx, [esi - 8]
{Include the previous block}
sub esi, ecx
{Set the new block size}
add ebx, ecx
{Remove the previous block from the linked list}
cmp ecx, MinimumMediumBlockSize
jb @PreviousBlockChecked
mov eax, esi
call RemoveMediumFreeBlock
jmp @PreviousBlockChecked
{Align branch target}
@EntireMediumPoolFree:
{Should we make this the new sequential feed medium block pool? If the
current sequential feed pool is not entirely free, we make this the new
sequential feed pool.}
cmp MediumSequentialFeedBytesLeft, MediumBlockPoolSize - MediumBlockPoolHeaderSize
jne @MakeEmptyMediumPoolSequentialFeed
{Point esi to the medium block pool header}
sub esi, MediumBlockPoolHeaderSize
{Remove this medium block pool from the linked list}
mov eax, TMediumBlockPoolHeader[esi].PreviousMediumBlockPoolHeader
mov edx, TMediumBlockPoolHeader[esi].NextMediumBlockPoolHeader
mov TMediumBlockPoolHeader[eax].NextMediumBlockPoolHeader, edx
mov TMediumBlockPoolHeader[edx].PreviousMediumBlockPoolHeader, eax
{Unlock medium blocks}
mov MediumBlocksLocked, False;
{$ifdef ClearMediumBlockPoolsBeforeReturningToOS}
mov eax, esi
mov edx, MediumBlockPoolSize
xor ecx, ecx
call System.@FillChar
{$endif}
{Free the medium block pool}
push MEM_RELEASE
push 0
push esi
call VirtualFree
{VirtualFree returns >0 if all is ok}
cmp eax, 1
{Return 0 on all ok}
sbb eax, eax
{Restore registers}
pop esi
pop ebx
ret
{Align branch target}
nop
nop
nop
@MakeEmptyMediumPoolSequentialFeed:
{Get a pointer to the end-marker block}
lea ebx, [esi + MediumBlockPoolSize - MediumBlockPoolHeaderSize]
{Bin the current sequential feed pool}
call BinMediumSequentialFeedRemainder
{Set this medium pool up as the new sequential feed pool:
Store the sequential feed pool trailer}
mov dword ptr [ebx - BlockHeaderSize], IsMediumBlockFlag
{Store the number of bytes available in the sequential feed chunk}
mov MediumSequentialFeedBytesLeft, MediumBlockPoolSize - MediumBlockPoolHeaderSize
{Set the last sequentially fed block}
mov LastSequentiallyFedMediumBlock, ebx
{Unlock medium blocks}
mov MediumBlocksLocked, False;
{Success}
xor eax, eax
{Restore registers}
pop esi
pop ebx
ret
{Align branch target}
nop
nop
@NotASmallOrMediumBlock:
{Restore ebx}
pop ebx
{Is it in fact a large block?}
test dl, IsFreeBlockFlag + IsMediumBlockFlag
jz FreeLargeBlock
{Attempt to free an already free block}
mov eax, -1
end;
{$else}
{---------------64-bit BASM FastFreeMem---------------}
asm
.params 3
.pushnv rbx
.pushnv rsi
{Get the block header in rdx}
mov rdx, [rcx - BlockHeaderSize]
{Is it a small block in use?}
test dl, IsFreeBlockFlag + IsMediumBlockFlag + IsLargeBlockFlag
{Get the IsMultiThread variable in bl}
{$ifndef AssumeMultiThreaded}
mov bl, IsMultiThread
{$endif}
{Is it a small block that is in use?}
jnz @NotSmallBlockInUse
{$ifdef ClearSmallAndMediumBlocksInFreeMem}
mov rsi, rcx
mov rdx, TSmallBlockPoolHeader[rdx].BlockType
movzx edx, TSmallBlockType(rdx).BlockSize
sub edx, BlockHeaderSize
xor r8, r8
call System.@FillChar
mov rcx, rsi
mov rdx, [rcx - BlockHeaderSize]
{$endif}
{Do we need to lock the block type?}
{$ifndef AssumeMultiThreaded}
test bl, bl
{$endif}
{Get the small block type in rbx}
mov rbx, TSmallBlockPoolHeader[rdx].BlockType
{Do we need to lock the block type?}
{$ifndef AssumeMultiThreaded}
jnz @LockBlockTypeLoop
{$else}
jmp @LockBlockTypeLoop
{$endif}
@GotLockOnSmallBlockType:
{Current state: rdx = @SmallBlockPoolHeader, rcx = APointer, rbx = @SmallBlockType}
{Decrement the number of blocks in use}
sub TSmallBlockPoolHeader[rdx].BlocksInUse, 1
{Get the old first free block}
mov rax, TSmallBlockPoolHeader[rdx].FirstFreeBlock
{Is the pool now empty?}
jz @PoolIsNowEmpty
{Was the pool full?}
test rax, rax
{Store this as the new first free block}
mov TSmallBlockPoolHeader[rdx].FirstFreeBlock, rcx
{Store the previous first free block as the block header}
lea rax, [rax + IsFreeBlockFlag]
mov [rcx - BlockHeaderSize], rax
{Insert the pool back into the linked list if it was full}
jz @SmallPoolWasFull
{All ok}
xor eax, eax
{Unlock the block type}
mov TSmallBlockType[rbx].BlockTypeLocked, al
jmp @Done
@SmallPoolWasFull:
{Insert this as the first partially free pool for the block size}
mov rcx, TSmallBlockType[rbx].NextPartiallyFreePool
mov TSmallBlockPoolHeader[rdx].PreviousPartiallyFreePool, rbx
mov TSmallBlockPoolHeader[rdx].NextPartiallyFreePool, rcx
mov TSmallBlockPoolHeader[rcx].PreviousPartiallyFreePool, rdx
mov TSmallBlockType[rbx].NextPartiallyFreePool, rdx
{Unlock the block type}
mov TSmallBlockType[rbx].BlockTypeLocked, False
{All ok}
xor eax, eax
jmp @Done
@PoolIsNowEmpty:
{Was this pool actually in the linked list of pools with space? If not, it
can only be the sequential feed pool (it is the only pool that may contain
only one block, i.e. other blocks have not been split off yet)}
test rax, rax
jz @IsSequentialFeedPool
{Pool is now empty: Remove it from the linked list and free it}
mov rax, TSmallBlockPoolHeader[rdx].PreviousPartiallyFreePool
mov rcx, TSmallBlockPoolHeader[rdx].NextPartiallyFreePool
{Remove this manager}
mov TSmallBlockPoolHeader[rax].NextPartiallyFreePool, rcx
mov TSmallBlockPoolHeader[rcx].PreviousPartiallyFreePool, rax
{Zero out eax}
xor rax, rax
{Is this the sequential feed pool? If so, stop sequential feeding}
cmp TSmallBlockType[rbx].CurrentSequentialFeedPool, rdx
jne @NotSequentialFeedPool
@IsSequentialFeedPool:
mov TSmallBlockType[rbx].MaxSequentialFeedBlockAddress, rax
@NotSequentialFeedPool:
{Unlock the block type}
mov TSmallBlockType[rbx].BlockTypeLocked, al
{Release this pool}
mov rcx, rdx
mov rdx, [rdx - BlockHeaderSize]
{$ifndef AssumeMultiThreaded}
mov bl, IsMultiThread
{$endif}
jmp @FreeMediumBlock
@LockBlockTypeLoop:
mov eax, $100
{Attempt to grab the block type}
lock cmpxchg TSmallBlockType([rbx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{$ifdef NeverSleepOnThreadContention}
{Pause instruction (improves performance on P4)}
pause
{$ifdef UseSwitchToThread}
mov rsi, rcx
call SwitchToThread
mov rcx, rsi
mov rdx, [rcx - BlockHeaderSize]
{$endif}
{Try again}
jmp @LockBlockTypeLoop
{$else}
{Couldn't grab the block type - sleep and try again}
mov rsi, rcx
mov ecx, InitialSleepTime
call Sleep
mov rcx, rsi
mov rdx, [rcx - BlockHeaderSize]
{Try again}
mov eax, $100
{Attempt to grab the block type}
lock cmpxchg TSmallBlockType([rbx]).BlockTypeLocked, ah
je @GotLockOnSmallBlockType
{Couldn't grab the block type - sleep and try again}
mov rsi, rcx
mov ecx, AdditionalSleepTime
call Sleep
mov rcx, rsi
mov rdx, [rcx - BlockHeaderSize]
{Try again}
jmp @LockBlockTypeLoop
{$endif}
{---------------------Medium blocks------------------------------}
@NotSmallBlockInUse:
{Not a small block in use: is it a medium or large block?}
test dl, IsFreeBlockFlag + IsLargeBlockFlag
jnz @NotASmallOrMediumBlock
@FreeMediumBlock:
{$ifdef ClearSmallAndMediumBlocksInFreeMem}
mov rsi, rcx
and rdx, DropMediumAndLargeFlagsMask
sub rdx, BlockHeaderSize
xor r8, r8
call System.@FillChar
mov rcx, rsi
mov rdx, [rcx - BlockHeaderSize]
{$endif}
{Drop the flags}
and rdx, DropMediumAndLargeFlagsMask
{Free the medium block pointed to by eax, header in edx, bl = IsMultiThread}
{$ifndef AssumeMultiThreaded}
{Do we need to lock the medium blocks?}
test bl, bl
{$endif}
{Block size in rbx}
mov rbx, rdx
{Pointer in rsi}
mov rsi, rcx
{Do we need to lock the medium blocks?}
{$ifndef AssumeMultiThreaded}
jz @MediumBlocksLocked
{$endif}
call LockMediumBlocks
@MediumBlocksLocked:
{Can we combine this block with the next free block?}
test qword ptr [rsi + rbx - BlockHeaderSize], IsFreeBlockFlag
{Get the next block size and flags in rcx}
mov rcx, [rsi + rbx - BlockHeaderSize]
jnz @NextBlockIsFree
{Set the "PreviousIsFree" flag in the next block}
or rcx, PreviousMediumBlockIsFreeFlag
mov [rsi + rbx - BlockHeaderSize], rcx
@NextBlockChecked:
{Can we combine this block with the previous free block? We need to
re-read the flags since it could have changed before we could lock the
medium blocks.}
test byte ptr [rsi - BlockHeaderSize], PreviousMediumBlockIsFreeFlag
jnz @PreviousBlockIsFree
@PreviousBlockChecked:
{Is the entire medium block pool free, and there are other free blocks
that can fit the largest possible medium block -> free it.}
cmp ebx, (MediumBlockPoolSize - MediumBlockPoolHeaderSize)
je @EntireMediumPoolFree
@BinFreeMediumBlock:
{Store the size of the block as well as the flags}
lea rax, [rbx + IsMediumBlockFlag + IsFreeBlockFlag]
mov [rsi - BlockHeaderSize], rax
{Store the trailing size marker}
mov [rsi + rbx - 2 * BlockHeaderSize], rbx
{Insert this block back into the bins: Size check not required here,
since medium blocks that are in use are not allowed to be
shrunk smaller than MinimumMediumBlockSize}
mov rcx, rsi
mov rdx, rbx
{Insert into bin}
call InsertMediumBlockIntoBin
{All OK}
xor eax, eax
{Unlock medium blocks}
mov MediumBlocksLocked, al
jmp @Done
@NextBlockIsFree:
{Get the next block address in rax}
lea rax, [rsi + rbx]
{Increase the size of this block}
and rcx, DropMediumAndLargeFlagsMask
add rbx, rcx
{Was the block binned?}
cmp rcx, MinimumMediumBlockSize
jb @NextBlockChecked
mov rcx, rax
call RemoveMediumFreeBlock
jmp @NextBlockChecked
@PreviousBlockIsFree:
{Get the size of the free block just before this one}
mov rcx, [rsi - 2 * BlockHeaderSize]
{Include the previous block}
sub rsi, rcx
{Set the new block size}
add rbx, rcx
{Remove the previous block from the linked list}
cmp ecx, MinimumMediumBlockSize
jb @PreviousBlockChecked
mov rcx, rsi
call RemoveMediumFreeBlock
jmp @PreviousBlockChecked
@EntireMediumPoolFree:
{Should we make this the new sequential feed medium block pool? If the
current sequential feed pool is not entirely free, we make this the new
sequential feed pool.}
lea r8, MediumSequentialFeedBytesLeft
cmp dword ptr [r8], MediumBlockPoolSize - MediumBlockPoolHeaderSize //workaround for QC99023
jne @MakeEmptyMediumPoolSequentialFeed
{Point esi to the medium block pool header}
sub rsi, MediumBlockPoolHeaderSize
{Remove this medium block pool from the linked list}
mov rax, TMediumBlockPoolHeader[rsi].PreviousMediumBlockPoolHeader
mov rdx, TMediumBlockPoolHeader[rsi].NextMediumBlockPoolHeader
mov TMediumBlockPoolHeader[rax].NextMediumBlockPoolHeader, rdx
mov TMediumBlockPoolHeader[rdx].PreviousMediumBlockPoolHeader, rax
{Unlock medium blocks}
xor eax, eax
mov MediumBlocksLocked, al
{$ifdef ClearMediumBlockPoolsBeforeReturningToOS}
mov rcx, rsi
mov edx, MediumBlockPoolSize
xor r8, r8
call System.@FillChar
{$endif}
{Free the medium block pool}
mov rcx, rsi
xor edx, edx
mov r8d, MEM_RELEASE
call VirtualFree
{VirtualFree returns >0 if all is ok}
cmp eax, 1
{Return 0 on all ok}
sbb eax, eax
jmp @Done
@MakeEmptyMediumPoolSequentialFeed:
{Get a pointer to the end-marker block}
lea rbx, [rsi + MediumBlockPoolSize - MediumBlockPoolHeaderSize]
{Bin the current sequential feed pool}
call BinMediumSequentialFeedRemainder
{Set this medium pool up as the new sequential feed pool:
Store the sequential feed pool trailer}
mov qword ptr [rbx - BlockHeaderSize], IsMediumBlockFlag
{Store the number of bytes available in the sequential feed chunk}
lea rax, MediumSequentialFeedBytesLeft
mov dword ptr [rax], MediumBlockPoolSize - MediumBlockPoolHeaderSize //QC99023 workaround
{Set the last sequentially fed block}
mov LastSequentiallyFedMediumBlock, rbx
{Success}
xor eax, eax
{Unlock medium blocks}
mov MediumBlocksLocked, al
jmp @Done
@NotASmallOrMediumBlock:
{Attempt to free an already free block?}
mov eax, -1
{Is it in fact a large block?}
test dl, IsFreeBlockFlag + IsMediumBlockFlag
jnz @Done
call FreeLargeBlock
@Done:
end;
{$endif}
{$endif}
{$ifndef FullDebugMode}
{Replacement for SysReallocMem}
function FastReallocMem(APointer: Pointer; ANewSize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer;
{$ifndef ASMVersion}
var
LBlockHeader, LNextBlockSizeAndFlags, LNewAllocSize, LBlockFlags,
LOldAvailableSize, LNextBlockSize, LNewAvailableSize, LMinimumUpsize,
LSecondSplitSize, LNewBlockSize: NativeUInt;
LPSmallBlockType: PSmallBlockType;
LPNextBlock, LPNextBlockHeader: Pointer;
{Upsizes a large block in-place. The following variables are assumed correct:
LBlockFlags, LOldAvailableSize, LPNextBlock, LNextBlockSizeAndFlags,
LNextBlockSize, LNewAvailableSize. Medium blocks must be locked on entry if
required.}
procedure MediumBlockInPlaceUpsize;
begin
{Remove the next block}
if LNextBlockSizeAndFlags >= MinimumMediumBlockSize then
RemoveMediumFreeBlock(LPNextBlock);
{Add 25% for medium block in-place upsizes}
LMinimumUpsize := LOldAvailableSize + (LOldAvailableSize shr 2);
if NativeUInt(ANewSize) < LMinimumUpsize then
LNewAllocSize := LMinimumUpsize
else
LNewAllocSize := NativeUInt(ANewSize);
{Round up to the nearest block size granularity}
LNewBlockSize := ((LNewAllocSize + (BlockHeaderSize + MediumBlockGranularity - 1 - MediumBlockSizeOffset))
and -MediumBlockGranularity) + MediumBlockSizeOffset;
{Calculate the size of the second split}
LSecondSplitSize := LNewAvailableSize + BlockHeaderSize - LNewBlockSize;
{Does it fit?}
if NativeInt(LSecondSplitSize) <= 0 then
begin
{The block size is the full available size plus header}
LNewBlockSize := LNewAvailableSize + BlockHeaderSize;
{Grab the whole block: Mark it as used in the block following it}
LPNextBlockHeader := Pointer(PByte(APointer) + LNewAvailableSize);
PNativeUInt(LPNextBlockHeader)^ :=
PNativeUInt(LPNextBlockHeader)^ and (not PreviousMediumBlockIsFreeFlag);
end
else
begin
{Split the block in two}
LPNextBlock := PMediumFreeBlock(PByte(APointer) + LNewBlockSize);
{Set the size of the second split}
PNativeUInt(PByte(LPNextBlock) - BlockHeaderSize)^ := LSecondSplitSize or (IsMediumBlockFlag or IsFreeBlockFlag);
{Store the size of the second split before the header of the next block}
PNativeUInt(PByte(LPNextBlock) + LSecondSplitSize - 2 * BlockHeaderSize)^ := LSecondSplitSize;
{Put the remainder in a bin if it is big enough}
if LSecondSplitSize >= MinimumMediumBlockSize then
InsertMediumBlockIntoBin(LPNextBlock, LSecondSplitSize);
end;
{Set the size and flags for this block}
PNativeUInt(PByte(APointer) - BlockHeaderSize)^ := LNewBlockSize or LBlockFlags;
end;
{In-place downsize of a medium block. On entry Size must be less than half of
LOldAvailableSize.}
procedure MediumBlockInPlaceDownsize;
begin
{Round up to the next medium block size}
LNewBlockSize := ((ANewSize + (BlockHeaderSize + MediumBlockGranularity - 1 - MediumBlockSizeOffset))
and -MediumBlockGranularity) + MediumBlockSizeOffset;
{Get the size of the second split}
LSecondSplitSize := (LOldAvailableSize + BlockHeaderSize) - LNewBlockSize;
{Lock the medium blocks}
LockMediumBlocks;
{Set the new size}
PNativeUInt(PByte(APointer) - BlockHeaderSize)^ :=
(PNativeUInt(PByte(APointer) - BlockHeaderSize)^ and ExtractMediumAndLargeFlagsMask)
or LNewBlockSize;
{Is the next block in use?}
LPNextBlock := PNativeUInt(PByte(APointer) + LOldAvailableSize + BlockHeaderSize);
LNextBlockSizeAndFlags := PNativeUInt(PByte(LPNextBlock) - BlockHeaderSize)^;
if LNextBlockSizeAndFlags and IsFreeBlockFlag = 0 then
begin
{The next block is in use: flag its previous block as free}
PNativeUInt(PByte(LPNextBlock) - BlockHeaderSize)^ :=
LNextBlockSizeAndFlags or PreviousMediumBlockIsFreeFlag;
end
else
begin
{The next block is free: combine it}
LNextBlockSizeAndFlags := LNextBlockSizeAndFlags and DropMediumAndLargeFlagsMask;
Inc(LSecondSplitSize, LNextBlockSizeAndFlags);
if LNextBlockSizeAndFlags >= MinimumMediumBlockSize then
RemoveMediumFreeBlock(LPNextBlock);
end;
{Set the split}
LPNextBlock := PNativeUInt(PByte(APointer) + LNewBlockSize);
{Store the free part's header}
PNativeUInt(PByte(LPNextBlock) - BlockHeaderSize)^ := LSecondSplitSize or (IsMediumBlockFlag or IsFreeBlockFlag);
{Store the trailing size field}
PNativeUInt(PByte(LPNextBlock) + LSecondSplitSize - 2 * BlockHeaderSize)^ := LSecondSplitSize;
{Bin this free block}
if LSecondSplitSize >= MinimumMediumBlockSize then
InsertMediumBlockIntoBin(LPNextBlock, LSecondSplitSize);
{Unlock the medium blocks}
MediumBlocksLocked := False;
end;
begin
{Get the block header: Is it actually a small block?}
LBlockHeader := PNativeUInt(PByte(APointer) - BlockHeaderSize)^;
{Is it a small block that is in use?}
if LBlockHeader and (IsFreeBlockFlag or IsMediumBlockFlag or IsLargeBlockFlag) = 0 then
begin
{-----------------------------------Small block-------------------------------------}
{The block header is a pointer to the block pool: Get the block type}
LPSmallBlockType := PSmallBlockPoolHeader(LBlockHeader).BlockType;
{Get the available size inside blocks of this type.}
LOldAvailableSize := LPSmallBlockType.BlockSize - BlockHeaderSize;
{Is it an upsize or a downsize?}
if LOldAvailableSize >= NativeUInt(ANewSize) then
begin
{It's a downsize. Do we need to allocate a smaller block? Only if the new
block size is less than a quarter of the available size less
SmallBlockDownsizeCheckAdder bytes}
if (NativeUInt(ANewSize) * 4 + SmallBlockDownsizeCheckAdder) >= LOldAvailableSize then
begin
{In-place downsize - return the pointer}
Result := APointer;
Exit;
end
else
begin
{Allocate a smaller block}
Result := FastGetMem(ANewSize);
{Allocated OK?}
if Result <> nil then
begin
{Move the data across}
{$ifdef UseCustomVariableSizeMoveRoutines}
{$ifdef Align16Bytes}
MoveX16LP(APointer^, Result^, ANewSize);
{$else}
MoveX8LP(APointer^, Result^, ANewSize);
{$endif}
{$else}
System.Move(APointer^, Result^, ANewSize);
{$endif}
{Free the old pointer}
FastFreeMem(APointer);
end;
end;
end
else
begin
{This pointer is being reallocated to a larger block and therefore it is
logical to assume that it may be enlarged again. Since reallocations are
expensive, there is a minimum upsize percentage to avoid unnecessary
future move operations.}
{Must grow with at least 100% + x bytes}
LNewAllocSize := LOldAvailableSize * 2 + SmallBlockUpsizeAdder;
{Still not large enough?}
if LNewAllocSize < NativeUInt(ANewSize) then
LNewAllocSize := NativeUInt(ANewSize);
{Allocate the new block}
Result := FastGetMem(LNewAllocSize);
{Allocated OK?}
if Result <> nil then
begin
{Do we need to store the requested size? Only large blocks store the
requested size.}
if LNewAllocSize > (MaximumMediumBlockSize - BlockHeaderSize) then
PLargeBlockHeader(PByte(Result) - LargeBlockHeaderSize).UserAllocatedSize := ANewSize;
{Move the data across}
{$ifdef UseCustomFixedSizeMoveRoutines}
LPSmallBlockType.UpsizeMoveProcedure(APointer^, Result^, LOldAvailableSize);
{$else}
System.Move(APointer^, Result^, LOldAvailableSize);
{$endif}
{Free the old pointer}
FastFreeMem(APointer);
end;
end;
end
else
begin
{Is this a medium block or a large block?}
if LBlockHeader and (IsFreeBlockFlag or IsLargeBlockFlag) = 0 then
begin
{-------------------------------Medium block--------------------------------------}
{What is the available size in the block being reallocated?}
LOldAvailableSize := (LBlockHeader and DropMediumAndLargeFlagsMask);
{Get a pointer to the next block}
LPNextBlock := PNativeUInt(PByte(APointer) + LOldAvailableSize);
{Subtract the block header size from the old available size}
Dec(LOldAvailableSize, BlockHeaderSize);
{Is it an upsize or a downsize?}
if NativeUInt(ANewSize) > LOldAvailableSize then
begin
{Can we do an in-place upsize?}
LNextBlockSizeAndFlags := PNativeUInt(PByte(LPNextBlock) - BlockHeaderSize)^;
{Is the next block free?}
if LNextBlockSizeAndFlags and IsFreeBlockFlag <> 0 then
begin
LNextBlockSize := LNextBlockSizeAndFlags and DropMediumAndLargeFlagsMask;
{The available size including the next block}
LNewAvailableSize := LOldAvailableSize + LNextBlockSize;
{Can the block fit?}
if NativeUInt(ANewSize) <= LNewAvailableSize then
begin
{The next block is free and there is enough space to grow this
block in place.}
{$ifndef AssumeMultiThreaded}
if IsMultiThread then
begin
{$endif}
{Multi-threaded application - lock medium blocks and re-read the
information on the blocks.}
LockMediumBlocks;
{Re-read the info for this block}
LBlockFlags := PNativeUInt(PByte(APointer) - BlockHeaderSize)^ and ExtractMediumAndLargeFlagsMask;
{Re-read the info for the next block}
LNextBlockSizeAndFlags := PNativeUInt(PByte(LPNextBlock) - BlockHeaderSize)^;
{Recalculate the next block size}
LNextBlockSize := LNextBlockSizeAndFlags and DropMediumAndLargeFlagsMask;
{The available size including the next block}
LNewAvailableSize := LOldAvailableSize + LNextBlockSize;
{Is the next block still free and the size still sufficient?}
if (LNextBlockSizeAndFlags and IsFreeBlockFlag <> 0)
and (NativeUInt(ANewSize) <= LNewAvailableSize) then
begin
{Upsize the block in-place}
MediumBlockInPlaceUpsize;
{Unlock the medium blocks}
MediumBlocksLocked := False;
{Return the result}
Result := APointer;
{Done}
Exit;
end;
{Couldn't use the block: Unlock the medium blocks}
MediumBlocksLocked := False;
{$ifndef AssumeMultiThreaded}
end
else
begin
{Extract the block flags}
LBlockFlags := ExtractMediumAndLargeFlagsMask and LBlockHeader;
{Upsize the block in-place}
MediumBlockInPlaceUpsize;
{Return the result}
Result := APointer;
{Done}
Exit;
end;
{$endif}
end;
end;
{Couldn't upsize in place. Grab a new block and move the data across:
If we have to reallocate and move medium blocks, we grow by at
least 25%}
LMinimumUpsize := LOldAvailableSize + (LOldAvailableSize shr 2);
if NativeUInt(ANewSize) < LMinimumUpsize then
LNewAllocSize := LMinimumUpsize
else
LNewAllocSize := NativeUInt(ANewSize);
{Allocate the new block}
Result := FastGetMem(LNewAllocSize);
if Result <> nil then
begin
{If it's a large block - store the actual user requested size}
if LNewAllocSize > (MaximumMediumBlockSize - BlockHeaderSize) then
PLargeBlockHeader(PByte(Result) - LargeBlockHeaderSize).UserAllocatedSize := ANewSize;
{Move the data across}
{$ifdef UseCustomVariableSizeMoveRoutines}
MoveX16LP(APointer^, Result^, LOldAvailableSize);
{$else}
System.Move(APointer^, Result^, LOldAvailableSize);
{$endif}
{Free the old block}
FastFreeMem(APointer);
end;
end
else
begin
{Must be less than half the current size or we don't bother resizing.}
if NativeUInt(ANewSize * 2) >= LOldAvailableSize then
begin
Result := APointer;
end
else
begin
{In-place downsize? Balance the cost of moving the data vs. the cost
of fragmenting the memory pool. Medium blocks in use may never be
smaller than MinimumMediumBlockSize.}
if NativeUInt(ANewSize) >= (MinimumMediumBlockSize - BlockHeaderSize) then
begin
MediumBlockInPlaceDownsize;
Result := APointer;
end
else
begin
{The requested size is less than the minimum medium block size. If
the requested size is less than the threshold value (currently a
quarter of the minimum medium block size), move the data to a small
block, otherwise shrink the medium block to the minimum allowable
medium block size.}
if NativeUInt(ANewSize) >= MediumInPlaceDownsizeLimit then
begin
{The request is for a size smaller than the minimum medium block
size, but not small enough to justify moving data: Reduce the
block size to the minimum medium block size}
ANewSize := MinimumMediumBlockSize - BlockHeaderSize;
{Is it already at the minimum medium block size?}
if LOldAvailableSize > NativeUInt(ANewSize) then
MediumBlockInPlaceDownsize;
Result := APointer;
end
else
begin
{Allocate the new block}
Result := FastGetMem(ANewSize);
if Result <> nil then
begin
{Move the data across}
{$ifdef UseCustomVariableSizeMoveRoutines}
{$ifdef Align16Bytes}
MoveX16LP(APointer^, Result^, ANewSize);
{$else}
MoveX8LP(APointer^, Result^, ANewSize);
{$endif}
{$else}
System.Move(APointer^, Result^, ANewSize);
{$endif}
{Free the old block}
FastFreeMem(APointer);
end;
end;
end;
end;
end;
end
else
begin
{Is this a valid large block?}
if LBlockHeader and (IsFreeBlockFlag or IsMediumBlockFlag) = 0 then
begin
{-----------------------Large block------------------------------}
Result := ReallocateLargeBlock(APointer, ANewSize);
end
else
begin
{-----------------------Invalid block------------------------------}
{Bad pointer: probably an attempt to reallocate a free memory block.}
Result := nil;
end;
end;
end;
end;
{$else}
{$ifdef 32Bit}
asm
{On entry: eax = APointer; edx = ANewSize}
{Get the block header: Is it actually a small block?}
mov ecx, [eax - 4]
{Is it a small block?}
test cl, IsFreeBlockFlag + IsMediumBlockFlag + IsLargeBlockFlag
{Save ebx}
push ebx
{Save esi}
push esi
{Save the original pointer in esi}
mov esi, eax
{Is it a small block?}
jnz @NotASmallBlock
{-----------------------------------Small block-------------------------------------}
{Get the block type in ebx}
mov ebx, TSmallBlockPoolHeader[ecx].BlockType
{Get the available size inside blocks of this type.}
movzx ecx, TSmallBlockType[ebx].BlockSize
sub ecx, 4
{Is it an upsize or a downsize?}
cmp ecx, edx
jb @SmallUpsize
{It's a downsize. Do we need to allocate a smaller block? Only if the new
size is less than a quarter of the available size less
SmallBlockDownsizeCheckAdder bytes}
lea ebx, [edx * 4 + SmallBlockDownsizeCheckAdder]
cmp ebx, ecx
jb @NotSmallInPlaceDownsize
{In-place downsize - return the original pointer}
pop esi
pop ebx
ret
{Align branch target}
nop
@NotSmallInPlaceDownsize:
{Save the requested size}
mov ebx, edx
{Allocate a smaller block}
mov eax, edx
call FastGetMem
{Allocated OK?}
test eax, eax
jz @SmallDownsizeDone
{Move data across: count in ecx}
mov ecx, ebx
{Destination in edx}
mov edx, eax
{Save the result in ebx}
mov ebx, eax
{Original pointer in eax}
mov eax, esi
{Move the data across}
{$ifdef UseCustomVariableSizeMoveRoutines}
{$ifdef Align16Bytes}
call MoveX16LP
{$else}
call MoveX8LP
{$endif}
{$else}
call System.Move
{$endif}
{Free the original pointer}
mov eax, esi
call FastFreeMem
{Return the pointer}
mov eax, ebx
@SmallDownsizeDone:
pop esi
pop ebx
ret
{Align branch target}
nop
nop
@SmallUpsize:
{State: esi = APointer, edx = ANewSize, ecx = Current Block Size, ebx = Current Block Type}
{This pointer is being reallocated to a larger block and therefore it is
logical to assume that it may be enlarged again. Since reallocations are
expensive, there is a minimum upsize percentage to avoid unnecessary
future move operations.}
{Small blocks always grow with at least 100% + SmallBlockUpsizeAdder bytes}
lea ecx, [ecx + ecx + SmallBlockUpsizeAdder]
{save edi}
push edi
{Save the requested size in edi}
mov edi, edx
{New allocated size is the maximum of the requested size and the minimum
upsize}
xor eax, eax
sub ecx, edx
adc eax, -1
and eax, ecx
add eax, edx
{Allocate the new block}
call FastGetMem
{Allocated OK?}
test eax, eax
jz @SmallUpsizeDone
{Do we need to store the requested size? Only large blocks store the
requested size.}
cmp edi, MaximumMediumBlockSize - BlockHeaderSize
jbe @NotSmallUpsizeToLargeBlock
{Store the user requested size}
mov [eax - 8], edi
@NotSmallUpsizeToLargeBlock:
{Get the size to move across}
movzx ecx, TSmallBlockType[ebx].BlockSize
sub ecx, BlockHeaderSize
{Move to the new block}
mov edx, eax
{Save the result in edi}
mov edi, eax
{Move from the old block}
mov eax, esi
{Move the data across}
{$ifdef UseCustomFixedSizeMoveRoutines}
call TSmallBlockType[ebx].UpsizeMoveProcedure
{$else}
call System.Move
{$endif}
{Free the old pointer}
mov eax, esi
call FastFreeMem
{Done}
mov eax, edi
@SmallUpsizeDone:
pop edi
pop esi
pop ebx
ret
{Align branch target}
nop
@NotASmallBlock:
{Is this a medium block or a large block?}
test cl, IsFreeBlockFlag + IsLargeBlockFlag
jnz @PossibleLargeBlock
{-------------------------------Medium block--------------------------------------}
{Status: ecx = Current Block Size + Flags, eax/esi = APointer,
edx = Requested Size}
mov ebx, ecx
{Drop the flags from the header}
and ecx, DropMediumAndLargeFlagsMask
{Save edi}
push edi
{Get a pointer to the next block in edi}
lea edi, [eax + ecx]
{Subtract the block header size from the old available size}
sub ecx, BlockHeaderSize
{Get the complete flags in ebx}
and ebx, ExtractMediumAndLargeFlagsMask
{Is it an upsize or a downsize?}
cmp edx, ecx
{Save ebp}
push ebp
{Is it an upsize or a downsize?}
ja @MediumBlockUpsize
{Status: ecx = Current Block Size - 4, bl = Current Block Flags,
edi = @Next Block, eax/esi = APointer, edx = Requested Size}
{Must be less than half the current size or we don't bother resizing.}
lea ebp, [edx + edx]
cmp ebp, ecx
jb @MediumMustDownsize
@MediumNoResize:
{Restore registers}
pop ebp
pop edi
pop esi
pop ebx
{Return}
ret
{Align branch target}
nop
nop
nop
@MediumMustDownsize:
{In-place downsize? Balance the cost of moving the data vs. the cost of
fragmenting the memory pool. Medium blocks in use may never be smaller
than MinimumMediumBlockSize.}
cmp edx, MinimumMediumBlockSize - BlockHeaderSize
jae @MediumBlockInPlaceDownsize
{The requested size is less than the minimum medium block size. If the
requested size is less than the threshold value (currently a quarter of the
minimum medium block size), move the data to a small block, otherwise shrink
the medium block to the minimum allowable medium block size.}
cmp edx, MediumInPlaceDownsizeLimit
jb @MediumDownsizeRealloc
{The request is for a size smaller than the minimum medium block size, but
not small enough to justify moving data: Reduce the block size to the
minimum medium block size}
mov edx, MinimumMediumBlockSize - BlockHeaderSize
{Is it already at the minimum medium block size?}
cmp ecx, edx
jna @MediumNoResize
@MediumBlockInPlaceDownsize:
{Round up to the next medium block size}
lea ebp, [edx + BlockHeaderSize + MediumBlockGranularity - 1 - MediumBlockSizeOffset]
and ebp, -MediumBlockGranularity;
add ebp, MediumBlockSizeOffset
{Get the size of the second split}
add ecx, BlockHeaderSize
sub ecx, ebp
{Lock the medium blocks}
{$ifndef AssumeMultiThreaded}
cmp IsMultiThread, False
je @DoMediumInPlaceDownsize
{$endif}
@DoMediumLockForDownsize:
{Lock the medium blocks (ecx *must* be preserved)}
call LockMediumBlocks
{Reread the flags - they may have changed before medium blocks could be
locked.}
mov ebx, ExtractMediumAndLargeFlagsMask
and ebx, [esi - 4]
@DoMediumInPlaceDownsize:
{Set the new size}
or ebx, ebp
mov [esi - 4], ebx
{Get the second split size in ebx}
mov ebx, ecx
{Is the next block in use?}
mov edx, [edi - 4]
test dl, IsFreeBlockFlag
jnz @MediumDownsizeNextBlockFree
{The next block is in use: flag its previous block as free}
or edx, PreviousMediumBlockIsFreeFlag
mov [edi - 4], edx
jmp @MediumDownsizeDoSplit
{Align branch target}
nop
nop
{$ifdef AssumeMultiThreaded}
nop
{$endif}
@MediumDownsizeNextBlockFree:
{The next block is free: combine it}
mov eax, edi
and edx, DropMediumAndLargeFlagsMask
add ebx, edx
add edi, edx
cmp edx, MinimumMediumBlockSize
jb @MediumDownsizeDoSplit
call RemoveMediumFreeBlock
@MediumDownsizeDoSplit:
{Store the trailing size field}
mov [edi - 8], ebx
{Store the free part's header}
lea eax, [ebx + IsMediumBlockFlag + IsFreeBlockFlag];
mov [esi + ebp - 4], eax
{Bin this free block}
cmp ebx, MinimumMediumBlockSize
jb @MediumBlockDownsizeDone
lea eax, [esi + ebp]
mov edx, ebx
call InsertMediumBlockIntoBin
@MediumBlockDownsizeDone:
{Unlock the medium blocks}
mov MediumBlocksLocked, False
{Result = old pointer}
mov eax, esi
{Restore registers}
pop ebp
pop edi
pop esi
pop ebx
{Return}
ret
{Align branch target}
@MediumDownsizeRealloc:
{Save the requested size}
mov edi, edx
mov eax, edx
{Allocate the new block}
call FastGetMem
test eax, eax
jz @MediumBlockDownsizeExit
{Save the result}
mov ebp, eax
mov edx, eax
mov eax, esi
mov ecx, edi
{Move the data across}
{$ifdef UseCustomVariableSizeMoveRoutines}
{$ifdef Align16Bytes}
call MoveX16LP
{$else}
call MoveX8LP
{$endif}
{$else}
call System.Move
{$endif}
mov eax, esi
call FastFreeMem
{Return the result}
mov eax, ebp
@MediumBlockDownsizeExit:
pop ebp
pop edi
pop esi
pop ebx
ret
{Align branch target}
@MediumBlockUpsize:
{Status: ecx = Current Block Size - 4, bl = Current Block Flags,
edi = @Next Block, eax/esi = APointer, edx = Requested Size}
{Can we do an in-place upsize?}
mov eax, [edi - 4]
test al, IsFreeBlockFlag
jz @CannotUpsizeMediumBlockInPlace
{Get the total available size including the next block}
and eax, DropMediumAndLargeFlagsMask
{ebp = total available size including the next block (excluding the header)}
lea ebp, [eax + ecx]
{Can the block fit?}
cmp edx, ebp
ja @CannotUpsizeMediumBlockInPlace
{The next block is free and there is enough space to grow this
block in place.}
{$ifndef AssumeMultiThreaded}
cmp IsMultiThread, False
je @DoMediumInPlaceUpsize
{$endif}
@DoMediumLockForUpsize:
{Lock the medium blocks (ecx and edx *must* be preserved}
call LockMediumBlocks
{Re-read the info for this block (since it may have changed before the medium
blocks could be locked)}
mov ebx, ExtractMediumAndLargeFlagsMask
and ebx, [esi - 4]
{Re-read the info for the next block}
mov eax, [edi - 4]
{Next block still free?}
test al, IsFreeBlockFlag
jz @NextMediumBlockChanged
{Recalculate the next block size}
and eax, DropMediumAndLargeFlagsMask
{The available size including the next block}
lea ebp, [eax + ecx]
{Can the block still fit?}
cmp edx, ebp
ja @NextMediumBlockChanged
@DoMediumInPlaceUpsize:
{Is the next block binnable?}
cmp eax, MinimumMediumBlockSize
{Remove the next block}
jb @MediumInPlaceNoNextRemove
mov eax, edi
push ecx
push edx
call RemoveMediumFreeBlock
pop edx
pop ecx
@MediumInPlaceNoNextRemove:
{Medium blocks grow a minimum of 25% in in-place upsizes}
mov eax, ecx
shr eax, 2
add eax, ecx
{Get the maximum of the requested size and the minimum growth size}
xor edi, edi
sub eax, edx
adc edi, -1
and eax, edi
{Round up to the nearest block size granularity}
lea eax, [eax + edx + BlockHeaderSize + MediumBlockGranularity - 1 - MediumBlockSizeOffset]
and eax, -MediumBlockGranularity
add eax, MediumBlockSizeOffset
{Calculate the size of the second split}
lea edx, [ebp + BlockHeaderSize]
sub edx, eax
{Does it fit?}
ja @MediumInPlaceUpsizeSplit
{Grab the whole block: Mark it as used in the block following it}
and dword ptr [esi + ebp], not PreviousMediumBlockIsFreeFlag
{The block size is the full available size plus header}
add ebp, 4
{Upsize done}
jmp @MediumUpsizeInPlaceDone
{Align branch target}
{$ifndef AssumeMultiThreaded}
nop
nop
nop
{$endif}
@MediumInPlaceUpsizeSplit:
{Store the size of the second split as the second last dword}
mov [esi + ebp - 4], edx
{Set the second split header}
lea edi, [edx + IsMediumBlockFlag + IsFreeBlockFlag]
mov [esi + eax - 4], edi
mov ebp, eax
cmp edx, MinimumMediumBlockSize
jb @MediumUpsizeInPlaceDone
add eax, esi
call InsertMediumBlockIntoBin
@MediumUpsizeInPlaceDone:
{Set the size and flags for this block}
or ebp, ebx
mov [esi - 4], ebp
{Unlock the medium blocks}
mov MediumBlocksLocked, False
{Result = old pointer}
mov eax, esi
@MediumBlockResizeDone2:
{Restore registers}
pop ebp
pop edi
pop esi
pop ebx
{Return}
ret
{Align branch target for "@CannotUpsizeMediumBlockInPlace"}
nop
nop
@NextMediumBlockChanged:
{The next medium block changed while the medium blocks were being locked}
mov MediumBlocksLocked, False
@CannotUpsizeMediumBlockInPlace:
{Couldn't upsize in place. Grab a new block and move the data across:
If we have to reallocate and move medium blocks, we grow by at
least 25%}
mov eax, ecx
shr eax, 2
add eax, ecx
{Get the maximum of the requested size and the minimum growth size}
xor edi, edi
sub eax, edx
adc edi, -1
and eax, edi
add eax, edx
{Save the size to allocate}
mov ebp, eax
{Save the size to move across}
mov edi, ecx
{Get the block}
push edx
call FastGetMem
pop edx
{Success?}
test eax, eax
jz @MediumBlockResizeDone2
{If it's a Large block - store the actual user requested size}
cmp ebp, MaximumMediumBlockSize - BlockHeaderSize
jbe @MediumUpsizeNotLarge
mov [eax - 8], edx
@MediumUpsizeNotLarge:
{Save the result}
mov ebp, eax
{Move the data across}
mov edx, eax
mov eax, esi
mov ecx, edi
{$ifdef UseCustomVariableSizeMoveRoutines}
call MoveX16LP
{$else}
call System.Move
{$endif}
{Free the old block}
mov eax, esi
call FastFreeMem
{Restore the result}
mov eax, ebp
{Restore registers}
pop ebp
pop edi
pop esi
pop ebx
{Return}
ret
{Align branch target}
nop
@PossibleLargeBlock:
{-----------------------Large block------------------------------}
{Restore registers}
pop esi
pop ebx
{Is this a valid large block?}
test cl, IsFreeBlockFlag + IsMediumBlockFlag
jz ReallocateLargeBlock
{-----------------------Invalid block------------------------------}
xor eax, eax
end;
{$else}
{-----------------64-bit BASM FastReallocMem-----------------}
asm
.params 3
.pushnv rbx
.pushnv rsi
.pushnv rdi
.pushnv r14
.pushnv r15
{On entry: rcx = APointer; rdx = ANewSize}
{Save the original pointer in rsi}
mov rsi, rcx
{Get the block header}
mov rcx, [rcx - BlockHeaderSize]
{Is it a small block?}
test cl, IsFreeBlockFlag + IsMediumBlockFlag + IsLargeBlockFlag
jnz @NotASmallBlock
{-----------------------------------Small block-------------------------------------}
{Get the block type in rbx}
mov rbx, TSmallBlockPoolHeader[rcx].BlockType
{Get the available size inside blocks of this type.}
movzx ecx, TSmallBlockType[rbx].BlockSize
sub ecx, BlockHeaderSize
{Is it an upsize or a downsize?}
cmp rcx, rdx
jb @SmallUpsize
{It's a downsize. Do we need to allocate a smaller block? Only if the new
size is less than a quarter of the available size less
SmallBlockDownsizeCheckAdder bytes}
lea ebx, [edx * 4 + SmallBlockDownsizeCheckAdder]
cmp ebx, ecx
jb @NotSmallInPlaceDownsize
{In-place downsize - return the original pointer}
mov rax, rsi
jmp @Done
@NotSmallInPlaceDownsize:
{Save the requested size}
mov rbx, rdx
{Allocate a smaller block}
mov rcx, rdx
call FastGetMem
{Allocated OK?}
test rax, rax
jz @Done
{Move data across: count in r8}
mov r8, rbx
{Destination in edx}
mov rdx, rax
{Save the result in ebx}
mov rbx, rax
{Original pointer in ecx}
mov rcx, rsi
{Move the data across}
{$ifdef UseCustomVariableSizeMoveRoutines}
{$ifdef Align16Bytes}
call MoveX16LP
{$else}
call MoveX8LP
{$endif}
{$else}
call System.Move
{$endif}
{Free the original pointer}
mov rcx, rsi
call FastFreeMem
{Return the pointer}
mov rax, rbx
jmp @Done
@SmallUpsize:
{State: rsi = APointer, rdx = ANewSize, rcx = Current Block Size, rbx = Current Block Type}
{This pointer is being reallocated to a larger block and therefore it is
logical to assume that it may be enlarged again. Since reallocations are
expensive, there is a minimum upsize percentage to avoid unnecessary
future move operations.}
{Small blocks always grow with at least 100% + SmallBlockUpsizeAdder bytes}
lea ecx, [ecx + ecx + SmallBlockUpsizeAdder]
{Save the requested size in rdi}
mov rdi, rdx
{New allocated size is the maximum of the requested size and the minimum
upsize}
xor rax, rax
sub rcx, rdx
adc rax, -1
and rcx, rax
add rcx, rdx
{Allocate the new block}
call FastGetMem
{Allocated OK?}
test rax, rax
jz @Done
{Do we need to store the requested size? Only large blocks store the
requested size.}
cmp rdi, MaximumMediumBlockSize - BlockHeaderSize
jbe @NotSmallUpsizeToLargeBlock
{Store the user requested size}
mov [rax - 2 * BlockHeaderSize], rdi
@NotSmallUpsizeToLargeBlock:
{Get the size to move across}
movzx r8d, TSmallBlockType[rbx].BlockSize
sub r8d, BlockHeaderSize
{Move to the new block}
mov rdx, rax
{Save the result in edi}
mov rdi, rax
{Move from the old block}
mov rcx, rsi
{Move the data across}
{$ifdef UseCustomFixedSizeMoveRoutines}
call TSmallBlockType[rbx].UpsizeMoveProcedure
{$else}
call System.Move
{$endif}
{Free the old pointer}
mov rcx, rsi
call FastFreeMem
{Done}
mov rax, rdi
jmp @Done
@NotASmallBlock:
{Is this a medium block or a large block?}
test cl, IsFreeBlockFlag + IsLargeBlockFlag
jnz @PossibleLargeBlock
{-------------------------------Medium block--------------------------------------}
{Status: rcx = Current Block Size + Flags, rsi = APointer,
rdx = Requested Size}
mov rbx, rcx
{Drop the flags from the header}
and ecx, DropMediumAndLargeFlagsMask
{Get a pointer to the next block in rdi}
lea rdi, [rsi + rcx]
{Subtract the block header size from the old available size}
sub ecx, BlockHeaderSize
{Get the complete flags in ebx}
and ebx, ExtractMediumAndLargeFlagsMask
{Is it an upsize or a downsize?}
cmp rdx, rcx
ja @MediumBlockUpsize
{Status: ecx = Current Block Size - BlockHeaderSize, bl = Current Block Flags,
rdi = @Next Block, rsi = APointer, rdx = Requested Size}
{Must be less than half the current size or we don't bother resizing.}
lea r15, [rdx + rdx]
cmp r15, rcx
jb @MediumMustDownsize
@MediumNoResize:
mov rax, rsi
jmp @Done
@MediumMustDownsize:
{In-place downsize? Balance the cost of moving the data vs. the cost of
fragmenting the memory pool. Medium blocks in use may never be smaller
than MinimumMediumBlockSize.}
cmp edx, MinimumMediumBlockSize - BlockHeaderSize
jae @MediumBlockInPlaceDownsize
{The requested size is less than the minimum medium block size. If the
requested size is less than the threshold value (currently a quarter of the
minimum medium block size), move the data to a small block, otherwise shrink
the medium block to the minimum allowable medium block size.}
cmp edx, MediumInPlaceDownsizeLimit
jb @MediumDownsizeRealloc
{The request is for a size smaller than the minimum medium block size, but
not small enough to justify moving data: Reduce the block size to the
minimum medium block size}
mov edx, MinimumMediumBlockSize - BlockHeaderSize
{Is it already at the minimum medium block size?}
cmp ecx, edx
jna @MediumNoResize
@MediumBlockInPlaceDownsize:
{Round up to the next medium block size}
lea r15, [rdx + BlockHeaderSize + MediumBlockGranularity - 1 - MediumBlockSizeOffset]
and r15, -MediumBlockGranularity
add r15, MediumBlockSizeOffset
{Get the size of the second split}
add ecx, BlockHeaderSize
sub ecx, r15d
{Lock the medium blocks}
{$ifndef AssumeMultiThreaded}
lea r8, IsMultiThread
cmp byte ptr [r8], False
je @DoMediumInPlaceDownsize
{$endif}
@DoMediumLockForDownsize:
{Lock the medium blocks}
mov ebx, ecx
call LockMediumBlocks
mov ecx, ebx
{Reread the flags - they may have changed before medium blocks could be
locked.}
mov rbx, ExtractMediumAndLargeFlagsMask
and rbx, [rsi - BlockHeaderSize]
@DoMediumInPlaceDownsize:
{Set the new size}
or rbx, r15
mov [rsi - BlockHeaderSize], rbx
{Get the second split size in ebx}
mov ebx, ecx
{Is the next block in use?}
mov rdx, [rdi - BlockHeaderSize]
test dl, IsFreeBlockFlag
jnz @MediumDownsizeNextBlockFree
{The next block is in use: flag its previous block as free}
or rdx, PreviousMediumBlockIsFreeFlag
mov [rdi - BlockHeaderSize], rdx
jmp @MediumDownsizeDoSplit
@MediumDownsizeNextBlockFree:
{The next block is free: combine it}
mov rcx, rdi
and rdx, DropMediumAndLargeFlagsMask
add rbx, rdx
add rdi, rdx
cmp edx, MinimumMediumBlockSize
jb @MediumDownsizeDoSplit
call RemoveMediumFreeBlock
@MediumDownsizeDoSplit:
{Store the trailing size field}
mov [rdi - 2 * BlockHeaderSize], rbx
{Store the free part's header}
lea rcx, [rbx + IsMediumBlockFlag + IsFreeBlockFlag];
mov [rsi + r15 - BlockHeaderSize], rcx
{Bin this free block}
cmp rbx, MinimumMediumBlockSize
jb @MediumBlockDownsizeDone
lea rcx, [rsi + r15]
mov rdx, rbx
call InsertMediumBlockIntoBin
@MediumBlockDownsizeDone:
{Unlock the medium blocks}
lea rax, MediumBlocksLocked
mov byte ptr [rax], False
{Result = old pointer}
mov rax, rsi
jmp @Done
@MediumDownsizeRealloc:
{Save the requested size}
mov rdi, rdx
mov rcx, rdx
{Allocate the new block}
call FastGetMem
test rax, rax
jz @Done
{Save the result}
mov r15, rax
mov rdx, rax
mov rcx, rsi
mov r8, rdi
{Move the data across}
{$ifdef UseCustomVariableSizeMoveRoutines}
{$ifdef Align16Bytes}
call MoveX16LP
{$else}
call MoveX8LP
{$endif}
{$else}
call System.Move
{$endif}
mov rcx, rsi
call FastFreeMem
{Return the result}
mov rax, r15
jmp @Done
@MediumBlockUpsize:
{Status: ecx = Current Block Size - BlockHeaderSize, bl = Current Block Flags,
rdi = @Next Block, rsi = APointer, rdx = Requested Size}
{Can we do an in-place upsize?}
mov rax, [rdi - BlockHeaderSize]
test al, IsFreeBlockFlag
jz @CannotUpsizeMediumBlockInPlace
{Get the total available size including the next block}
and rax, DropMediumAndLargeFlagsMask
{r15 = total available size including the next block (excluding the header)}
lea r15, [rax + rcx]
{Can the block fit?}
cmp rdx, r15
ja @CannotUpsizeMediumBlockInPlace
{The next block is free and there is enough space to grow this
block in place.}
{$ifndef AssumeMultiThreaded}
lea r8, IsMultiThread
cmp byte ptr [r8], False
je @DoMediumInPlaceUpsize
{$endif}
@DoMediumLockForUpsize:
{Lock the medium blocks.}
mov rbx, rcx
mov r15, rdx
call LockMediumBlocks
mov rcx, rbx
mov rdx, r15
{Re-read the info for this block (since it may have changed before the medium
blocks could be locked)}
mov rbx, ExtractMediumAndLargeFlagsMask
and rbx, [rsi - BlockHeaderSize]
{Re-read the info for the next block}
mov rax, [rdi - BlockheaderSize]
{Next block still free?}
test al, IsFreeBlockFlag
jz @NextMediumBlockChanged
{Recalculate the next block size}
and eax, DropMediumAndLargeFlagsMask
{The available size including the next block}
lea r15, [rax + rcx]
{Can the block still fit?}
cmp rdx, r15
ja @NextMediumBlockChanged
@DoMediumInPlaceUpsize:
{Is the next block binnable?}
cmp eax, MinimumMediumBlockSize
{Remove the next block}
jb @MediumInPlaceNoNextRemove
mov r14, rcx
mov rcx, rdi
mov rdi, rdx
call RemoveMediumFreeBlock
mov rcx, r14
mov rdx, rdi
@MediumInPlaceNoNextRemove:
{Medium blocks grow a minimum of 25% in in-place upsizes}
mov eax, ecx
shr eax, 2
add eax, ecx
{Get the maximum of the requested size and the minimum growth size}
xor edi, edi
sub eax, edx
adc edi, -1
and eax, edi
{Round up to the nearest block size granularity}
lea eax, [eax + edx + BlockHeaderSize + MediumBlockGranularity - 1 - MediumBlockSizeOffset]
and eax, -MediumBlockGranularity
add eax, MediumBlockSizeOffset
{Calculate the size of the second split}
lea rdx, [r15 + BlockHeaderSize]
sub edx, eax
{Does it fit?}
ja @MediumInPlaceUpsizeSplit
{Grab the whole block: Mark it as used in the block following it}
and qword ptr [rsi + r15], not PreviousMediumBlockIsFreeFlag
{The block size is the full available size plus header}
add r15, BlockHeaderSize
{Upsize done}
jmp @MediumUpsizeInPlaceDone
@MediumInPlaceUpsizeSplit:
{Store the size of the second split as the second last dword}
mov [rsi + r15 - BlockHeaderSize], rdx
{Set the second split header}
lea edi, [edx + IsMediumBlockFlag + IsFreeBlockFlag]
mov [rsi + rax - BlockHeaderSize], rdi
mov r15, rax
cmp edx, MinimumMediumBlockSize
jb @MediumUpsizeInPlaceDone
lea rcx, [rsi + rax]
call InsertMediumBlockIntoBin
@MediumUpsizeInPlaceDone:
{Set the size and flags for this block}
or r15, rbx
mov [rsi - BlockHeaderSize], r15
{Unlock the medium blocks}
lea rax, MediumBlocksLocked
mov byte ptr [rax], False
{Result = old pointer}
mov rax, rsi
jmp @Done
@NextMediumBlockChanged:
{The next medium block changed while the medium blocks were being locked}
lea rax, MediumBlocksLocked
mov byte ptr [rax], False
@CannotUpsizeMediumBlockInPlace:
{Couldn't upsize in place. Grab a new block and move the data across:
If we have to reallocate and move medium blocks, we grow by at
least 25%}
mov eax, ecx
shr eax, 2
add eax, ecx
{Get the maximum of the requested size and the minimum growth size}
xor rdi, rdi
sub rax, rdx
adc rdi, -1
and rax, rdi
add rax, rdx
{Save the size to allocate}
mov r15, rax
{Save the size to move across}
mov edi, ecx
{Save the requested size}
mov rbx, rdx
{Get the block}
mov rcx, rax
call FastGetMem
mov rdx, rbx
{Success?}
test eax, eax
jz @Done
{If it's a Large block - store the actual user requested size}
cmp r15, MaximumMediumBlockSize - BlockHeaderSize
jbe @MediumUpsizeNotLarge
mov [rax - 2 * BlockHeaderSize], rdx
@MediumUpsizeNotLarge:
{Save the result}
mov r15, rax
{Move the data across}
mov rdx, rax
mov rcx, rsi
mov r8, rdi
{$ifdef UseCustomVariableSizeMoveRoutines}
call MoveX16LP
{$else}
call System.Move
{$endif}
{Free the old block}
mov rcx, rsi
call FastFreeMem
{Restore the result}
mov rax, r15
jmp @Done
@PossibleLargeBlock:
{-----------------------Large block------------------------------}
{Is this a valid large block?}
test cl, IsFreeBlockFlag + IsMediumBlockFlag
jnz @Error
mov rcx, rsi
call ReallocateLargeBlock
jmp @Done
{-----------------------Invalid block------------------------------}
@Error:
xor eax, eax
@Done:
end;
{$endif}
{$endif}
{$endif}
{Allocates a block and fills it with zeroes}
function FastAllocMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Cardinal{$endif}): Pointer;
{$ifndef ASMVersion}
begin
Result := FastGetMem(ASize);
{Large blocks are already zero filled}
if (Result <> nil) and (ASize <= (MaximumMediumBlockSize - BlockHeaderSize)) then
FillChar(Result^, ASize, 0);
end;
{$else}
{$ifdef 32Bit}
asm
push ebx
{Get the size rounded down to the previous multiple of 4 into ebx}
lea ebx, [eax - 1]
and ebx, -4
{Get the block}
call FastGetMem
{Could a block be allocated? ecx = 0 if yes, $ffffffff if no}
cmp eax, 1
sbb ecx, ecx
{Point edx to the last dword}
lea edx, [eax + ebx]
{ebx = $ffffffff if no block could be allocated, otherwise size rounded down
to previous multiple of 4. If ebx = 0 then the block size is 1..4 bytes and
the FPU based clearing loop should not be used (since it clears 8 bytes per
iteration).}
or ebx, ecx
jz @ClearLastDWord
{Large blocks are already zero filled}
cmp ebx, MaximumMediumBlockSize - BlockHeaderSize
jae @Done
{Make the counter negative based}
neg ebx
{Load zero into st(0)}
fldz
{Clear groups of 8 bytes. Block sizes are always four less than a multiple
of 8.}
@FillLoop:
fst qword ptr [edx + ebx]
add ebx, 8
js @FillLoop
{Clear st(0)}
ffree st(0)
{Correct the stack top}
fincstp
{Clear the last four bytes}
@ClearLastDWord:
mov [edx], ecx
@Done:
pop ebx
end;
{$else}
{---------------64-bit BASM FastAllocMem---------------}
asm
.params 1
.pushnv rbx
{Get the size rounded down to the previous multiple of SizeOf(Pointer) into
ebx}
lea rbx, [rcx - 1]
and rbx, -8
{Get the block}
call FastGetMem
{Could a block be allocated? rcx = 0 if yes, -1 if no}
cmp rax, 1
sbb rcx, rcx
{Point rdx to the last dword}
lea rdx, [rax + rbx]
{rbx = -1 if no block could be allocated, otherwise size rounded down
to previous multiple of 8. If rbx = 0 then the block size is 1..8 bytes and
the SSE2 based clearing loop should not be used (since it clears 16 bytes per
iteration).}
or rbx, rcx
jz @ClearLastQWord
{Large blocks are already zero filled}
cmp rbx, MaximumMediumBlockSize - BlockHeaderSize
jae @Done
{Make the counter negative based}
neg rbx
{Load zero into xmm0}
pxor xmm0, xmm0
{Clear groups of 16 bytes. Block sizes are always 8 less than a multiple of
16.}
@FillLoop:
movdqa [rdx + rbx], xmm0
add rbx, 16
js @FillLoop
{Clear the last 8 bytes}
@ClearLastQWord:
xor rcx, rcx
mov [rdx], rcx
@Done:
end;
{$endif}
{$endif}
{-----------------Post Uninstall GetMem/FreeMem/ReallocMem-------------------}
{$ifdef DetectMMOperationsAfterUninstall}
function InvalidGetMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer;
{$ifndef NoMessageBoxes}
var
LErrorMessageTitle: array[0..1023] of AnsiChar;
{$endif}
begin
{$ifdef UseOutputDebugString}
OutputDebugStringA(InvalidGetMemMsg);
{$endif}
{$ifndef NoMessageBoxes}
AppendStringToModuleName(InvalidOperationTitle, LErrorMessageTitle);
ShowMessageBox(InvalidGetMemMsg, LErrorMessageTitle);
{$endif}
Result := nil;
end;
function InvalidFreeMem(APointer: Pointer): Integer;
{$ifndef NoMessageBoxes}
var
LErrorMessageTitle: array[0..1023] of AnsiChar;
{$endif}
begin
{$ifdef UseOutputDebugString}
OutputDebugStringA(InvalidFreeMemMsg);
{$endif}
{$ifndef NoMessageBoxes}
AppendStringToModuleName(InvalidOperationTitle, LErrorMessageTitle);
ShowMessageBox(InvalidFreeMemMsg, LErrorMessageTitle);
{$endif}
Result := -1;
end;
function InvalidReallocMem(APointer: Pointer; ANewSize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer;
{$ifndef NoMessageBoxes}
var
LErrorMessageTitle: array[0..1023] of AnsiChar;
{$endif}
begin
{$ifdef UseOutputDebugString}
OutputDebugStringA(InvalidReallocMemMsg);
{$endif}
{$ifndef NoMessageBoxes}
AppendStringToModuleName(InvalidOperationTitle, LErrorMessageTitle);
ShowMessageBox(InvalidReallocMemMsg, LErrorMessageTitle);
{$endif}
Result := nil;
end;
function InvalidAllocMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Cardinal{$endif}): Pointer;
{$ifndef NoMessageBoxes}
var
LErrorMessageTitle: array[0..1023] of AnsiChar;
{$endif}
begin
{$ifdef UseOutputDebugString}
OutputDebugStringA(InvalidAllocMemMsg);
{$endif}
{$ifndef NoMessageBoxes}
AppendStringToModuleName(InvalidOperationTitle, LErrorMessageTitle);
ShowMessageBox(InvalidAllocMemMsg, LErrorMessageTitle);
{$endif}
Result := nil;
end;
function InvalidRegisterAndUnRegisterMemoryLeak(APointer: Pointer): Boolean;
begin
Result := False;
end;
{$endif}
{-----------------Full Debug Mode Memory Manager Interface--------------------}
{$ifdef FullDebugMode}
{Compare [AAddress], CompareVal:
If Equal: [AAddress] := NewVal and result = CompareVal
If Unequal: Result := [AAddress]}
function LockCmpxchg32(CompareVal, NewVal: Integer; AAddress: PInteger): Integer;
asm
{$ifdef 32Bit}
{On entry:
eax = CompareVal,
edx = NewVal,
ecx = AAddress}
lock cmpxchg [ecx], edx
{$else}
.noframe
{On entry:
ecx = CompareVal,
edx = NewVal,
r8 = AAddress}
mov eax, ecx
lock cmpxchg [r8], edx
{$endif}
end;
{Called by DebugGetMem, DebugFreeMem and DebugReallocMem in order to block a
free block scan operation while the memory pool is being modified.}
procedure StartChangingFullDebugModeBlock;
var
LOldCount: Integer;
begin
while True do
begin
{Get the old thread count}
LOldCount := ThreadsInFullDebugModeRoutine;
if (LOldCount >= 0)
and (LockCmpxchg32(LOldCount, LOldCount + 1, @ThreadsInFullDebugModeRoutine) = LOldCount) then
begin
Break;
end;
{$ifdef NeverSleepOnThreadContention}
{$ifdef UseSwitchToThread}
SwitchToThread;
{$endif}
{$else}
Sleep(InitialSleepTime);
{Try again}
LOldCount := ThreadsInFullDebugModeRoutine;
if (LOldCount >= 0)
and (LockCmpxchg32(LOldCount, LOldCount + 1, @ThreadsInFullDebugModeRoutine) = LOldCount) then
begin
Break;
end;
Sleep(AdditionalSleepTime);
{$endif}
end;
end;
procedure DoneChangingFullDebugModeBlock;
asm
{$ifdef 32Bit}
lock dec ThreadsInFullDebugModeRoutine
{$else}
.noframe
lea rax, ThreadsInFullDebugModeRoutine
lock dec dword ptr [rax]
{$endif}
end;
{Increments the allocation number}
procedure IncrementAllocationNumber;
asm
{$ifdef 32Bit}
lock inc CurrentAllocationNumber
{$else}
.noframe
lea rax, CurrentAllocationNumber
lock inc dword ptr [rax]
{$endif}
end;
{Called by a routine wanting to lock the entire memory pool in FullDebugMode, e.g. before scanning the memory
pool for corruptions.}
procedure BlockFullDebugModeMMRoutines;
begin
while True do
begin
{Get the old thread count}
if LockCmpxchg32(0, -1, @ThreadsInFullDebugModeRoutine) = 0 then
Break;
{$ifdef NeverSleepOnThreadContention}
{$ifdef UseSwitchToThread}
SwitchToThread;
{$endif}
{$else}
Sleep(InitialSleepTime);
{Try again}
if LockCmpxchg32(0, -1, @ThreadsInFullDebugModeRoutine) = 0 then
Break;
Sleep(AdditionalSleepTime);
{$endif}
end;
end;
procedure UnblockFullDebugModeMMRoutines;
begin
{Currently blocked? If so, unblock the FullDebugMode routines.}
if ThreadsInFullDebugModeRoutine = -1 then
ThreadsInFullDebugModeRoutine := 0;
end;
procedure DeleteEventLog;
begin
{Delete the file}
DeleteFileA(MMLogFileName);
end;
{Finds the start and length of the file name given a full path.}
procedure ExtractFileName(APFullPath: PAnsiChar; var APFileNameStart: PAnsiChar; var AFileNameLength: Integer);
var
LChar: AnsiChar;
begin
{Initialize}
APFileNameStart := APFullPath;
AFileNameLength := 0;
{Find the file }
while True do
begin
{Get the next character}
LChar := APFullPath^;
{End of the path string?}
if LChar = #0 then
Break;
{Advance the buffer position}
Inc(APFullPath);
{Found a backslash? -> May be the start of the file name}
if LChar = '\' then
APFileNameStart := APFullPath;
end;
{Calculate the length of the file name}
AFileNameLength := IntPtr(APFullPath) - IntPtr(APFileNameStart);
end;
procedure AppendEventLog(ABuffer: Pointer; ACount: Cardinal);
const
{Declared here, because it is not declared in the SHFolder.pas unit of some older Delphi versions.}
SHGFP_TYPE_CURRENT = 0;
var
LFileHandle, LBytesWritten: Cardinal;
LEventHeader: array[0..1023] of AnsiChar;
LAlternateLogFileName: array[0..2047] of AnsiChar;
LPathLen, LNameLength: Integer;
LMsgPtr, LPFileName: PAnsiChar;
LSystemTime: TSystemTime;
begin
{Try to open the log file in read/write mode.}
LFileHandle := CreateFileA(MMLogFileName, GENERIC_READ or GENERIC_WRITE,
0, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
{Did log file creation fail? If so, the destination folder is perhaps read-only:
Try to redirect logging to a file in the user's "My Documents" folder.}
if (LFileHandle = INVALID_HANDLE_VALUE)
{$ifdef Delphi4or5}
and SHGetSpecialFolderPathA(0, @LAlternateLogFileName, CSIDL_PERSONAL, True) then
{$else}
and (SHGetFolderPathA(0, CSIDL_PERSONAL or CSIDL_FLAG_CREATE, 0,
SHGFP_TYPE_CURRENT, @LAlternateLogFileName) = S_OK) then
{$endif}
begin
{Extract the filename part from MMLogFileName and append it to the path of
the "My Documents" folder.}
LPathLen := StrLen(LAlternateLogFileName);
{Ensure that there is a trailing backslash in the path}
if (LPathLen = 0) or (LAlternateLogFileName[LPathLen - 1] <> '\') then
begin
LAlternateLogFileName[LPathLen] := '\';
Inc(LPathLen);
end;
{Add the filename to the path}
ExtractFileName(@MMLogFileName, LPFileName, LNameLength);
System.Move(LPFileName^, LAlternateLogFileName[LPathLen], LNameLength + 1);
{Try to open the alternate log file}
LFileHandle := CreateFileA(LAlternateLogFileName, GENERIC_READ or GENERIC_WRITE,
0, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
end;
{Was the log file opened/created successfully?}
if LFileHandle <> INVALID_HANDLE_VALUE then
begin
{Seek to the end of the file}
SetFilePointer(LFileHandle, 0, nil, FILE_END);
{Set the separator}
LMsgPtr := AppendStringToBuffer(CRLF, @LEventHeader[0], Length(CRLF));
LMsgPtr := AppendStringToBuffer(EventSeparator, LMsgPtr, Length(EventSeparator));
{Set the date & time}
GetLocalTime(LSystemTime);
LMsgPtr := NativeUIntToStrBuf(LSystemTime.wYear, LMsgPtr);
LMsgPtr^ := '/';
Inc(LMsgPtr);
LMsgPtr := NativeUIntToStrBuf(LSystemTime.wMonth, LMsgPtr);
LMsgPtr^ := '/';
Inc(LMsgPtr);
LMsgPtr := NativeUIntToStrBuf(LSystemTime.wDay, LMsgPtr);
LMsgPtr^ := ' ';
Inc(LMsgPtr);
LMsgPtr := NativeUIntToStrBuf(LSystemTime.wHour, LMsgPtr);
LMsgPtr^ := ':';
Inc(LMsgPtr);
if LSystemTime.wMinute < 10 then
begin
LMsgPtr^ := '0';
Inc(LMsgPtr);
end;
LMsgPtr := NativeUIntToStrBuf(LSystemTime.wMinute, LMsgPtr);
LMsgPtr^ := ':';
Inc(LMsgPtr);
if LSystemTime.wSecond < 10 then
begin
LMsgPtr^ := '0';
Inc(LMsgPtr);
end;
LMsgPtr := NativeUIntToStrBuf(LSystemTime.WSecond, LMsgPtr);
{Write the header}
LMsgPtr := AppendStringToBuffer(EventSeparator, LMsgPtr, Length(EventSeparator));
LMsgPtr := AppendStringToBuffer(CRLF, LMsgPtr, Length(CRLF));
WriteFile(LFileHandle, LEventHeader[0], NativeUInt(LMsgPtr) - NativeUInt(@LEventHeader[0]), LBytesWritten, nil);
{Write the data}
WriteFile(LFileHandle, ABuffer^, ACount, LBytesWritten, nil);
{Close the file}
CloseHandle(LFileHandle);
end;
end;
{Sets the default log filename}
procedure SetDefaultMMLogFileName;
const
LogFileExtAnsi: PAnsiChar = LogFileExtension;
var
LEnvVarLength, LModuleNameLength: Cardinal;
LPathOverride: array[0..2047] of AnsiChar;
LPFileName: PAnsiChar;
LFileNameLength: Integer;
begin
{Get the name of the application}
LModuleNameLength := AppendModuleFileName(@MMLogFileName[0]);
{Replace the last few characters of the module name, and optionally override
the path.}
if LModuleNameLength > 0 then
begin
{Change the filename}
System.Move(LogFileExtAnsi^, MMLogFileName[LModuleNameLength - 4],
StrLen(LogFileExtAnsi) + 1);
{Try to read the FastMMLogFilePath environment variable}
LEnvVarLength := GetEnvironmentVariableA('FastMMLogFilePath',
@LPathOverride, 1023);
{Does the environment variable exist? If so, override the log file path.}
if LEnvVarLength > 0 then
begin
{Ensure that there's a trailing backslash.}
if LPathOverride[LEnvVarLength - 1] <> '\' then
begin
LPathOverride[LEnvVarLength] := '\';
Inc(LEnvVarLength);
end;
{Add the filename to the path override}
ExtractFileName(@MMLogFileName[0], LPFileName, LFileNameLength);
System.Move(LPFileName^, LPathOverride[LEnvVarLength], LFileNameLength + 1);
{Copy the override path back to the filename buffer}
System.Move(LPathOverride, MMLogFileName, SizeOf(MMLogFileName) - 1);
end;
end;
end;
{Specify the full path and name for the filename to be used for logging memory
errors, etc. If ALogFileName is nil or points to an empty string it will
revert to the default log file name.}
procedure SetMMLogFileName(ALogFileName: PAnsiChar = nil);
var
LLogFileNameLen: Integer;
begin
{Is ALogFileName valid?}
if (ALogFileName <> nil) and (ALogFileName^ <> #0) then
begin
LLogFileNameLen := StrLen(ALogFileName);
if LLogFileNameLen < Length(MMLogFileName) then
begin
{Set the log file name}
System.Move(ALogFileName^, MMLogFileName, LLogFileNameLen + 1);
Exit;
end;
end;
{Invalid log file name}
SetDefaultMMLogFileName;
end;
{Returns the current "allocation group". Whenever a GetMem request is serviced
in FullDebugMode, the current "allocation group" is stored in the block header.
This may help with debugging. Note that if a block is subsequently reallocated
that it keeps its original "allocation group" and "allocation number" (all
allocations are also numbered sequentially).}
function GetCurrentAllocationGroup: Cardinal;
begin
Result := AllocationGroupStack[AllocationGroupStackTop];
end;
{Allocation groups work in a stack like fashion. Group numbers are pushed onto
and popped off the stack. Note that the stack size is limited, so every push
should have a matching pop.}
procedure PushAllocationGroup(ANewCurrentAllocationGroup: Cardinal);
begin
if AllocationGroupStackTop < AllocationGroupStackSize - 1 then
begin
Inc(AllocationGroupStackTop);
AllocationGroupStack[AllocationGroupStackTop] := ANewCurrentAllocationGroup;
end
else
begin
{Raise a runtime error if the stack overflows}
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
end;
end;
procedure PopAllocationGroup;
begin
if AllocationGroupStackTop > 0 then
begin
Dec(AllocationGroupStackTop);
end
else
begin
{Raise a runtime error if the stack underflows}
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
end;
end;
{Sums all the dwords starting at the given address. ACount must be > 0 and a
multiple of SizeOf(Pointer).}
function SumNativeUInts(AStartValue: NativeUInt; APointer: PNativeUInt;
ACount: NativeUInt): NativeUInt;
asm
{$ifdef 32Bit}
{On entry: eax = AStartValue, edx = APointer; ecx = ACount}
add edx, ecx
neg ecx
@AddLoop:
add eax, [edx + ecx]
add ecx, 4
js @AddLoop
{$else}
{On entry: rcx = AStartValue, rdx = APointer; r8 = ACount}
add rdx, r8
neg r8
mov rax, rcx
@AddLoop:
add rax, [rdx + r8]
add r8, 8
js @AddLoop
{$endif}
end;
{Checks the memory starting at the given address for the fill pattern.
Returns True if all bytes are all valid. ACount must be >0 and a multiple of
SizeOf(Pointer).}
function CheckFillPattern(APointer: Pointer; ACount: NativeUInt;
AFillPattern: NativeUInt): Boolean;
asm
{$ifdef 32Bit}
{On entry: eax = APointer; edx = ACount; ecx = AFillPattern}
add eax, edx
neg edx
@CheckLoop:
cmp [eax + edx], ecx
jne @Done
add edx, 4
js @CheckLoop
@Done:
sete al
{$else}
{On entry: rcx = APointer; rdx = ACount; r8 = AFillPattern}
add rcx, rdx
neg rdx
@CheckLoop:
cmp [rcx + rdx], r8
jne @Done
add rdx, 8
js @CheckLoop
@Done:
sete al
{$endif}
end;
{Calculates the checksum for the debug header. Adds all dwords in the debug
header to the start address of the block.}
function CalculateHeaderCheckSum(APointer: PFullDebugBlockHeader): NativeUInt;
begin
Result := SumNativeUInts(
NativeUInt(APointer),
PNativeUInt(PByte(APointer) + 2 * SizeOf(Pointer)),
SizeOf(TFullDebugBlockHeader) - 2 * SizeOf(Pointer) - SizeOf(NativeUInt));
end;
procedure UpdateHeaderAndFooterCheckSums(APointer: PFullDebugBlockHeader);
var
LHeaderCheckSum: NativeUInt;
begin
LHeaderCheckSum := CalculateHeaderCheckSum(APointer);
APointer.HeaderCheckSum := LHeaderCheckSum;
PNativeUInt(PByte(APointer) + SizeOf(TFullDebugBlockHeader) + APointer.UserSize)^ := not LHeaderCheckSum;
end;
function LogCurrentThreadAndStackTrace(ASkipFrames: Cardinal; ABuffer: PAnsiChar): PAnsiChar;
var
LCurrentStackTrace: TStackTrace;
begin
{Get the current call stack}
GetStackTrace(@LCurrentStackTrace[0], StackTraceDepth, ASkipFrames);
{Log the thread ID}
Result := AppendStringToBuffer(CurrentThreadIDMsg, ABuffer, Length(CurrentThreadIDMsg));
Result := NativeUIntToHexBuf(GetThreadID, Result);
{List the stack trace}
Result := AppendStringToBuffer(CurrentStackTraceMsg, Result, Length(CurrentStackTraceMsg));
Result := LogStackTrace(@LCurrentStackTrace, StackTraceDepth, Result);
end;
{$ifndef DisableLoggingOfMemoryDumps}
function LogMemoryDump(APointer: PFullDebugBlockHeader; ABuffer: PAnsiChar): PAnsiChar;
var
LByteNum, LVal: Cardinal;
LDataPtr: PByte;
begin
Result := AppendStringToBuffer(MemoryDumpMsg, ABuffer, Length(MemoryDumpMsg));
Result := NativeUIntToHexBuf(NativeUInt(APointer) + SizeOf(TFullDebugBlockHeader), Result);
Result^ := ':';
Inc(Result);
{Add the bytes}
LDataPtr := PByte(PByte(APointer) + SizeOf(TFullDebugBlockHeader));
for LByteNum := 0 to 255 do
begin
if LByteNum and 31 = 0 then
begin
Result^ := #13;
Inc(Result);
Result^ := #10;
Inc(Result);
end
else
begin
Result^ := ' ';
Inc(Result);
end;
{Set the hex data}
LVal := Byte(LDataPtr^);
Result^ := HexTable[LVal shr 4];
Inc(Result);
Result^ := HexTable[LVal and $f];
Inc(Result);
{Next byte}
Inc(LDataPtr);
end;
{Dump ASCII}
LDataPtr := PByte(PByte(APointer) + SizeOf(TFullDebugBlockHeader));
for LByteNum := 0 to 255 do
begin
if LByteNum and 31 = 0 then
begin
Result^ := #13;
Inc(Result);
Result^ := #10;
Inc(Result);
end
else
begin
Result^ := ' ';
Inc(Result);
Result^ := ' ';
Inc(Result);
end;
{Set the hex data}
LVal := Byte(LDataPtr^);
if LVal < 32 then
Result^ := '.'
else
Result^ := AnsiChar(LVal);
Inc(Result);
{Next byte}
Inc(LDataPtr);
end;
end;
{$endif}
{Rotates AValue ABitCount bits to the right}
function RotateRight(AValue, ABitCount: NativeUInt): NativeUInt;
asm
{$ifdef 32Bit}
mov ecx, edx
ror eax, cl
{$else}
mov rax, rcx
mov rcx, rdx
ror rax, cl
{$endif}
end;
{Determines whether a byte in the user portion of the freed block has been modified. Does not work beyond
the end of the user portion (i.e. footer and beyond).}
function FreeBlockByteWasModified(APointer: PFullDebugBlockHeader; AUserOffset: NativeUInt): Boolean;
var
LFillPattern: NativeUInt;
begin
{Get the expected fill pattern}
if AUserOffset < SizeOf(Pointer) then
begin
LFillPattern := NativeUInt(@FreedObjectVMT.VMTMethods[0]);
end
else
begin
{$ifndef CatchUseOfFreedInterfaces}
LFillPattern := DebugFillPattern;
{$else}
LFillPattern := NativeUInt(@VMTBadInterface);
{$endif}
end;
{Compare the byte value}
Result := Byte(PByte(PByte(APointer) + SizeOf(TFullDebugBlockHeader) + AUserOffset)^) <>
Byte(RotateRight(LFillPattern, (AUserOffset and (SizeOf(Pointer) - 1)) * 8));
end;
function LogBlockChanges(APointer: PFullDebugBlockHeader; ABuffer: PAnsiChar): PAnsiChar;
var
LOffset, LChangeStart, LCount: NativeUInt;
LLogCount: Integer;
begin
{No errors logged so far}
LLogCount := 0;
{Log a maximum of 32 changes}
LOffset := 0;
while (LOffset < APointer.UserSize) and (LLogCount < 32) do
begin
{Has the byte been modified?}
if FreeBlockByteWasModified(APointer, LOffset) then
begin
{Found the start of a changed block, now find the length}
LChangeStart := LOffset;
LCount := 0;
while True do
begin
Inc(LCount);
Inc(LOffset);
if (LOffset >= APointer.UserSize)
or (not FreeBlockByteWasModified(APointer, LOffset)) then
begin
Break;
end;
end;
{Got the offset and length, now log it.}
if LLogCount = 0 then
begin
ABuffer := AppendStringToBuffer(FreeModifiedDetailMsg, ABuffer, Length(FreeModifiedDetailMsg));
end
else
begin
ABuffer^ := ',';
Inc(ABuffer);
ABuffer^ := ' ';
Inc(ABuffer);
end;
ABuffer := NativeUIntToStrBuf(LChangeStart, ABuffer);
ABuffer^ := '(';
Inc(ABuffer);
ABuffer := NativeUIntToStrBuf(LCount, ABuffer);
ABuffer^ := ')';
Inc(ABuffer);
{Increment the log count}
Inc(LLogCount);
end;
{Next byte}
Inc(LOffset);
end;
{Return the current buffer position}
Result := ABuffer;
end;
procedure LogBlockError(APointer: PFullDebugBlockHeader; AOperation: TBlockOperation; LHeaderValid, LFooterValid: Boolean);
var
LMsgPtr: PAnsiChar;
LErrorMessage: array[0..32767] of AnsiChar;
{$ifndef NoMessageBoxes}
LErrorMessageTitle: array[0..1023] of AnsiChar;
{$endif}
LClass: TClass;
{$ifdef CheckCppObjectTypeEnabled}
LCppObjectTypeName: PAnsiChar;
{$endif}
begin
{Display the error header and the operation type.}
LMsgPtr := AppendStringToBuffer(ErrorMsgHeader, @LErrorMessage[0], Length(ErrorMsgHeader));
case AOperation of
boGetMem: LMsgPtr := AppendStringToBuffer(GetMemMsg, LMsgPtr, Length(GetMemMsg));
boFreeMem: LMsgPtr := AppendStringToBuffer(FreeMemMsg, LMsgPtr, Length(FreeMemMsg));
boReallocMem: LMsgPtr := AppendStringToBuffer(ReallocMemMsg, LMsgPtr, Length(ReallocMemMsg));
boBlockCheck: LMsgPtr := AppendStringToBuffer(BlockCheckMsg, LMsgPtr, Length(BlockCheckMsg));
end;
LMsgPtr := AppendStringToBuffer(OperationMsg, LMsgPtr, Length(OperationMsg));
{Is the header still intact?}
if LHeaderValid then
begin
{Is the footer still valid?}
if LFooterValid then
begin
{A freed block has been modified, a double free has occurred, or an
attempt was made to free a memory block allocated by a different
instance of FastMM.}
if AOperation <= boGetMem then
begin
LMsgPtr := AppendStringToBuffer(FreeModifiedErrorMsg, LMsgPtr, Length(FreeModifiedErrorMsg));
{Log the exact changes that caused the error.}
LMsgPtr := LogBlockChanges(APointer, LMsgPtr);
end
else
begin
{It is either a double free, or an attempt was made to free a block
that was allocated via a different memory manager.}
if APointer.AllocatedByRoutine = nil then
LMsgPtr := AppendStringToBuffer(DoubleFreeErrorMsg, LMsgPtr, Length(DoubleFreeErrorMsg))
else
LMsgPtr := AppendStringToBuffer(WrongMMFreeErrorMsg, LMsgPtr, Length(WrongMMFreeErrorMsg));
end;
end
else
begin
LMsgPtr := AppendStringToBuffer(BlockFooterCorruptedMsg, LMsgPtr, Length(BlockFooterCorruptedMsg))
end;
{Set the block size message}
if AOperation <= boGetMem then
LMsgPtr := AppendStringToBuffer(PreviousBlockSizeMsg, LMsgPtr, Length(PreviousBlockSizeMsg))
else
LMsgPtr := AppendStringToBuffer(CurrentBlockSizeMsg, LMsgPtr, Length(CurrentBlockSizeMsg));
LMsgPtr := NativeUIntToStrBuf(APointer.UserSize, LMsgPtr);
{The header is still intact - display info about the this/previous allocation}
if APointer.AllocationStackTrace[0] <> 0 then
begin
if AOperation <= boGetMem then
LMsgPtr := AppendStringToBuffer(ThreadIDPrevAllocMsg, LMsgPtr, Length(ThreadIDPrevAllocMsg))
else
LMsgPtr := AppendStringToBuffer(ThreadIDAtAllocMsg, LMsgPtr, Length(ThreadIDAtAllocMsg));
LMsgPtr := NativeUIntToHexBuf(APointer.AllocatedByThread, LMsgPtr);
LMsgPtr := AppendStringToBuffer(StackTraceMsg, LMsgPtr, Length(StackTraceMsg));
LMsgPtr := LogStackTrace(@APointer.AllocationStackTrace, StackTraceDepth, LMsgPtr);
end;
{Get the class this block was used for previously}
LClass := DetectClassInstance(@APointer.PreviouslyUsedByClass);
if (LClass <> nil) and (IntPtr(LClass) <> IntPtr(@FreedObjectVMT.VMTMethods[0])) then
begin
LMsgPtr := AppendStringToBuffer(PreviousObjectClassMsg, LMsgPtr, Length(PreviousObjectClassMsg));
LMsgPtr := AppendClassNameToBuffer(LClass, LMsgPtr);
end;
{$ifdef CheckCppObjectTypeEnabled}
if (LClass = nil) and Assigned(GetCppVirtObjTypeNameByVTablePtrFunc) then
begin
LCppObjectTypeName := GetCppVirtObjTypeNameByVTablePtrFunc(Pointer(APointer.PreviouslyUsedByClass), 0);
if Assigned(LCppObjectTypeName) then
begin
LMsgPtr := AppendStringToBuffer(PreviousObjectClassMsg, LMsgPtr, Length(PreviousObjectClassMsg));
LMsgPtr := AppendStringToBuffer(LCppObjectTypeName, LMsgPtr, StrLen(LCppObjectTypeName));
end;
end;
{$endif}
{Get the current class for this block}
if (AOperation > boGetMem) and (APointer.AllocatedByRoutine <> nil) then
begin
LMsgPtr := AppendStringToBuffer(CurrentObjectClassMsg, LMsgPtr, Length(CurrentObjectClassMsg));
LClass := DetectClassInstance(Pointer(PByte(APointer) + SizeOf(TFullDebugBlockHeader)));
if IntPtr(LClass) = IntPtr(@FreedObjectVMT.VMTMethods[0]) then
LClass := nil;
{$ifndef CheckCppObjectTypeEnabled}
LMsgPtr := AppendClassNameToBuffer(LClass, LMsgPtr);
{$else}
if (LClass = nil) and Assigned(GetCppVirtObjTypeNameFunc) then
begin
LCppObjectTypeName := GetCppVirtObjTypeNameFunc(Pointer(PByte(APointer) + SizeOf(TFullDebugBlockHeader)),
APointer.UserSize);
if LCppObjectTypeName <> nil then
LMsgPtr := AppendStringToBuffer(LCppObjectTypeName, LMsgPtr, StrLen(LCppObjectTypeName))
else
LMsgPtr := AppendClassNameToBuffer(LClass, LMsgPtr);
end
else
begin
LMsgPtr := AppendClassNameToBuffer(LClass, LMsgPtr);
end;
{$endif}
{Log the allocation group}
if APointer.AllocationGroup > 0 then
begin
LMsgPtr := AppendStringToBuffer(CurrentAllocationGroupMsg, LMsgPtr, Length(CurrentAllocationGroupMsg));
LMsgPtr := NativeUIntToStrBuf(APointer.AllocationGroup, LMsgPtr);
end;
{Log the allocation number}
LMsgPtr := AppendStringToBuffer(CurrentAllocationNumberMsg, LMsgPtr, Length(CurrentAllocationNumberMsg));
LMsgPtr := NativeUIntToStrBuf(APointer.AllocationNumber, LMsgPtr);
end
else
begin
{Log the allocation group}
if APointer.AllocationGroup > 0 then
begin
LMsgPtr := AppendStringToBuffer(PreviousAllocationGroupMsg, LMsgPtr, Length(PreviousAllocationGroupMsg));
LMsgPtr := NativeUIntToStrBuf(APointer.AllocationGroup, LMsgPtr);
end;
{Log the allocation number}
LMsgPtr := AppendStringToBuffer(PreviousAllocationNumberMsg, LMsgPtr, Length(PreviousAllocationNumberMsg));
LMsgPtr := NativeUIntToStrBuf(APointer.AllocationNumber, LMsgPtr);
end;
{Get the call stack for the previous free}
if APointer.FreeStackTrace[0] <> 0 then
begin
LMsgPtr := AppendStringToBuffer(ThreadIDAtFreeMsg, LMsgPtr, Length(ThreadIDAtFreeMsg));
LMsgPtr := NativeUIntToHexBuf(APointer.FreedByThread, LMsgPtr);
LMsgPtr := AppendStringToBuffer(StackTraceMsg, LMsgPtr, Length(StackTraceMsg));
LMsgPtr := LogStackTrace(@APointer.FreeStackTrace, StackTraceDepth, LMsgPtr);
end;
end
else
begin
{Header has been corrupted}
LMsgPtr := AppendStringToBuffer(BlockHeaderCorruptedMsg, LMsgPtr, Length(BlockHeaderCorruptedMsg));
end;
{Add the current stack trace}
LMsgPtr := LogCurrentThreadAndStackTrace(3 + Ord(AOperation <> boGetMem) + Ord(AOperation = boReallocMem), LMsgPtr);
{$ifndef DisableLoggingOfMemoryDumps}
{Add the memory dump}
LMsgPtr := LogMemoryDump(APointer, LMsgPtr);
{$endif}
{Trailing CRLF}
LMsgPtr^ := #13;
Inc(LMsgPtr);
LMsgPtr^ := #10;
Inc(LMsgPtr);
{Trailing #0}
LMsgPtr^ := #0;
{$ifdef LogErrorsToFile}
{Log the error}
AppendEventLog(@LErrorMessage[0], NativeUInt(LMsgPtr) - NativeUInt(@LErrorMessage[0]));
{$endif}
{$ifdef UseOutputDebugString}
OutputDebugStringA(LErrorMessage);
{$endif}
{Show the message}
{$ifndef NoMessageBoxes}
AppendStringToModuleName(BlockErrorMsgTitle, LErrorMessageTitle);
ShowMessageBox(LErrorMessage, LErrorMessageTitle);
{$endif}
end;
{Logs the stack traces for a memory leak to file}
procedure LogMemoryLeakOrAllocatedBlock(APointer: PFullDebugBlockHeader; IsALeak: Boolean);
var
LHeaderValid: Boolean;
LMsgPtr: PAnsiChar;
LErrorMessage: array[0..32767] of AnsiChar;
LClass: TClass;
{$ifdef CheckCppObjectTypeEnabled}
LCppObjectTypeName: PAnsiChar;
{$endif}
begin
{Display the error header and the operation type.}
if IsALeak then
LMsgPtr := AppendStringToBuffer(LeakLogHeader, @LErrorMessage[0], Length(LeakLogHeader))
else
LMsgPtr := AppendStringToBuffer(BlockScanLogHeader, @LErrorMessage[0], Length(BlockScanLogHeader));
LMsgPtr := NativeUIntToStrBuf(GetAvailableSpaceInBlock(APointer) - FullDebugBlockOverhead, LMsgPtr);
{Is the debug info surrounding the block valid?}
LHeaderValid := CalculateHeaderCheckSum(APointer) = APointer.HeaderCheckSum;
{Is the header still intact?}
if LHeaderValid then
begin
{The header is still intact - display info about this/previous allocation}
if APointer.AllocationStackTrace[0] <> 0 then
begin
LMsgPtr := AppendStringToBuffer(ThreadIDAtAllocMsg, LMsgPtr, Length(ThreadIDAtAllocMsg));
LMsgPtr := NativeUIntToHexBuf(APointer.AllocatedByThread, LMsgPtr);
LMsgPtr := AppendStringToBuffer(StackTraceMsg, LMsgPtr, Length(StackTraceMsg));
LMsgPtr := LogStackTrace(@APointer.AllocationStackTrace, StackTraceDepth, LMsgPtr);
end;
LMsgPtr := AppendStringToBuffer(CurrentObjectClassMsg, LMsgPtr, Length(CurrentObjectClassMsg));
{Get the current class for this block}
LClass := DetectClassInstance(Pointer(PByte(APointer) + SizeOf(TFullDebugBlockHeader)));
if IntPtr(LClass) = IntPtr(@FreedObjectVMT.VMTMethods[0]) then
LClass := nil;
{$ifndef CheckCppObjectTypeEnabled}
if LClass <> nil then
begin
LMsgPtr := AppendClassNameToBuffer(LClass, LMsgPtr);
end
else
begin
case DetectStringData(Pointer(PByte(APointer) + SizeOf(TFullDebugBlockHeader)), APointer.UserSize) of
stUnknown: LMsgPtr := AppendClassNameToBuffer(nil, LMsgPtr);
stAnsiString: LMsgPtr := AppendStringToBuffer(AnsiStringBlockMessage, LMsgPtr, Length(AnsiStringBlockMessage));
stUnicodeString: LMsgPtr := AppendStringToBuffer(UnicodeStringBlockMessage, LMsgPtr, Length(UnicodeStringBlockMessage));
end;
end;
{$else}
if (LClass = nil) and Assigned(GetCppVirtObjTypeNameFunc) then
begin
LCppObjectTypeName := GetCppVirtObjTypeNameFunc(Pointer(PByte(APointer) + SizeOf(TFullDebugBlockHeader)),
APointer.UserSize);
if LCppObjectTypeName <> nil then
LMsgPtr := AppendStringToBuffer(LCppObjectTypeName, LMsgPtr, StrLen(LCppObjectTypeName))
else
begin
case DetectStringData(Pointer(PByte(APointer) + SizeOf(TFullDebugBlockHeader)), APointer.UserSize) of
stUnknown: LMsgPtr := AppendClassNameToBuffer(nil, LMsgPtr);
stAnsiString: LMsgPtr := AppendStringToBuffer(AnsiStringBlockMessage, LMsgPtr, Length(AnsiStringBlockMessage));
stUnicodeString: LMsgPtr := AppendStringToBuffer(UnicodeStringBlockMessage, LMsgPtr, Length(UnicodeStringBlockMessage));
end;
end;
end
else
LMsgPtr := AppendClassNameToBuffer(LClass, LMsgPtr);
{$endif}
{Log the allocation group}
if APointer.AllocationGroup > 0 then
begin
LMsgPtr := AppendStringToBuffer(CurrentAllocationGroupMsg, LMsgPtr, Length(CurrentAllocationGroupMsg));
LMsgPtr := NativeUIntToStrBuf(APointer.AllocationGroup, LMsgPtr);
end;
{Log the allocation number}
LMsgPtr := AppendStringToBuffer(CurrentAllocationNumberMsg, LMsgPtr, Length(CurrentAllocationNumberMsg));
LMsgPtr := NativeUIntToStrBuf(APointer.AllocationNumber, LMsgPtr);
end
else
begin
{Header has been corrupted}
LMsgPtr^ := '.';
Inc(LMsgPtr);
LMsgPtr^ := ' ';
Inc(LMsgPtr);
LMsgPtr := AppendStringToBuffer(BlockHeaderCorruptedMsg, LMsgPtr, Length(BlockHeaderCorruptedMsg));
end;
{$ifndef DisableLoggingOfMemoryDumps}
{Add the memory dump}
LMsgPtr := LogMemoryDump(APointer, LMsgPtr);
{$endif}
{Trailing CRLF}
LMsgPtr^ := #13;
Inc(LMsgPtr);
LMsgPtr^ := #10;
Inc(LMsgPtr);
{Trailing #0}
LMsgPtr^ := #0;
{Log the error}
AppendEventLog(@LErrorMessage[0], NativeUInt(LMsgPtr) - NativeUInt(@LErrorMessage[0]));
end;
{Checks that a free block is unmodified}
function CheckFreeBlockUnmodified(APBlock: PFullDebugBlockHeader; ABlockSize: NativeUInt;
AOperation: TBlockOperation): Boolean;
var
LHeaderCheckSum: NativeUInt;
LHeaderValid, LFooterValid, LBlockUnmodified: Boolean;
begin
LHeaderCheckSum := CalculateHeaderCheckSum(APBlock);
LHeaderValid := LHeaderCheckSum = APBlock.HeaderCheckSum;
{Is the footer itself still in place}
LFooterValid := LHeaderValid
and (PNativeUInt(PByte(APBlock) + SizeOf(TFullDebugBlockHeader) + APBlock.UserSize)^ = (not LHeaderCheckSum));
{Is the footer and debug VMT in place? The debug VMT is only valid if the user size is greater than the size of a pointer.}
if LFooterValid
and (APBlock.UserSize < SizeOf(Pointer)) or (PNativeUInt(PByte(APBlock) + SizeOf(TFullDebugBlockHeader))^ = NativeUInt(@FreedObjectVMT.VMTMethods[0])) then
begin
{Store the debug fill pattern in place of the footer in order to simplify
checking for block modifications.}
PNativeUInt(PByte(APBlock) + SizeOf(TFullDebugBlockHeader) + APBlock.UserSize)^ :=
{$ifndef CatchUseOfFreedInterfaces}
DebugFillPattern;
{$else}
RotateRight(NativeUInt(@VMTBadInterface), (APBlock.UserSize and (SizeOf(Pointer) - 1)) * 8);
{$endif}
{Check that all the filler bytes are valid inside the block, except for
the "dummy" class header}
LBlockUnmodified := CheckFillPattern(PNativeUInt(PByte(APBlock) + (SizeOf(TFullDebugBlockHeader) + SizeOf(Pointer))),
ABlockSize - (FullDebugBlockOverhead + SizeOf(Pointer)),
{$ifndef CatchUseOfFreedInterfaces}DebugFillPattern{$else}NativeUInt(@VMTBadInterface){$endif});
{Reset the old footer}
PNativeUInt(PByte(APBlock) + SizeOf(TFullDebugBlockHeader) + APBlock.UserSize)^ := not LHeaderCheckSum;
end
else
LBlockUnmodified := False;
if (not LHeaderValid) or (not LFooterValid) or (not LBlockUnmodified) then
begin
LogBlockError(APBlock, AOperation, LHeaderValid, LFooterValid);
Result := False;
end
else
Result := True;
end;
function DebugGetMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer;
begin
{Scan the entire memory pool first?}
if FullDebugModeScanMemoryPoolBeforeEveryOperation then
ScanMemoryPoolForCorruptions;
{Enter the memory manager: block scans may not be performed now}
StartChangingFullDebugModeBlock;
try
{We need extra space for (a) The debug header, (b) the block debug trailer
and (c) the trailing block size pointer for free blocks}
Result := FastGetMem(ASize + FullDebugBlockOverhead);
if Result <> nil then
begin
{Large blocks are always newly allocated (and never reused), so checking
for a modify-after-free is not necessary.}
if (ASize > (MaximumMediumBlockSize - BlockHeaderSize - FullDebugBlockOverhead))
or CheckFreeBlockUnmodified(Result, GetAvailableSpaceInBlock(Result) + BlockHeaderSize, boGetMem) then
begin
{Set the allocation call stack}
GetStackTrace(@PFullDebugBlockHeader(Result).AllocationStackTrace, StackTraceDepth, 1);
{Set the thread ID of the thread that allocated the block}
PFullDebugBlockHeader(Result).AllocatedByThread := GetThreadID;
{Block is now in use: It was allocated by this routine}
PFullDebugBlockHeader(Result).AllocatedByRoutine := @DebugGetMem;
{Set the group number}
PFullDebugBlockHeader(Result).AllocationGroup := AllocationGroupStack[AllocationGroupStackTop];
{Set the allocation number}
IncrementAllocationNumber;
PFullDebugBlockHeader(Result).AllocationNumber := CurrentAllocationNumber;
{Clear the previous block trailer}
PNativeUInt(PByte(Result) + SizeOf(TFullDebugBlockHeader) + PFullDebugBlockHeader(Result).UserSize)^ :=
{$ifndef CatchUseOfFreedInterfaces}
DebugFillPattern;
{$else}
RotateRight(NativeUInt(@VMTBadInterface), (PFullDebugBlockHeader(Result).UserSize and (SizeOf(Pointer) - 1)) * 8);
{$endif}
{Set the user size for the block}
PFullDebugBlockHeader(Result).UserSize := ASize;
{Set the checksums}
UpdateHeaderAndFooterCheckSums(Result);
{$ifdef FullDebugModeCallBacks}
if Assigned(OnDebugGetMemFinish) then
OnDebugGetMemFinish(PFullDebugBlockHeader(Result), ASize);
{$endif}
{Return the start of the actual block}
Result := Pointer(PByte(Result) + SizeOf(TFullDebugBlockHeader));
{$ifdef EnableMemoryLeakReporting}
{Should this block be marked as an expected leak automatically?}
if FullDebugModeRegisterAllAllocsAsExpectedMemoryLeak then
RegisterExpectedMemoryLeak(Result);
{$endif}
end
else
begin
Result := nil;
end;
end;
finally
{Leaving the memory manager routine: Block scans may be performed again.}
DoneChangingFullDebugModeBlock;
end;
end;
function CheckBlockBeforeFreeOrRealloc(APBlock: PFullDebugBlockHeader;
AOperation: TBlockOperation): Boolean;
var
LHeaderValid, LFooterValid: Boolean;
LPFooter: PNativeUInt;
{$ifndef CatchUseOfFreedInterfaces}
LBlockSize: NativeUInt;
LPTrailingByte, LPFillPatternEnd: PByte;
{$endif}
begin
{Is the checksum for the block header valid?}
LHeaderValid := CalculateHeaderCheckSum(APBlock) = APBlock.HeaderCheckSum;
{If the header is corrupted then the footer is assumed to be corrupt too.}
if LHeaderValid then
begin
{Check the footer checksum: The footer checksum should equal the header
checksum with all bits inverted.}
LPFooter := PNativeUInt(PByte(APBlock) + SizeOf(TFullDebugBlockHeader) + PFullDebugBlockHeader(APBlock).UserSize);
if APBlock.HeaderCheckSum = (not (LPFooter^)) then
begin
LFooterValid := True;
{$ifndef CatchUseOfFreedInterfaces}
{Large blocks do not have the debug fill pattern, since they are never reused.}
if PNativeUInt(PByte(APBlock) - BlockHeaderSize)^ and (IsMediumBlockFlag or IsLargeBlockFlag) <> IsLargeBlockFlag then
begin
{Check that the application has not modified bytes beyond the block
footer. The $80 fill pattern should extend up to 2 nativeints before
the start of the next block (leaving space for the free block size and
next block header.)}
LBlockSize := GetAvailableSpaceInBlock(APBlock);
LPFillPatternEnd := PByte(PByte(APBlock) + LBlockSize - SizeOf(Pointer));
LPTrailingByte := PByte(PByte(LPFooter) + SizeOf(NativeUInt));
while UIntPtr(LPTrailingByte) < UIntPtr(LPFillPatternEnd) do
begin
if Byte(LPTrailingByte^) <> DebugFillByte then
begin
LFooterValid := False;
Break;
end;
Inc(LPTrailingByte);
end;
end;
{$endif}
end
else
LFooterValid := False;
end
else
LFooterValid := False;
{The header and footer must be intact and the block must have been allocated
by this memory manager instance.}
if LFooterValid and (APBlock.AllocatedByRoutine = @DebugGetMem) then
begin
Result := True;
end
else
begin
{Log the error}
LogBlockError(APBlock, AOperation, LHeaderValid, LFooterValid);
{Return an error}
Result := False;
end;
end;
function DebugFreeMem(APointer: Pointer): Integer;
var
LActualBlock: PFullDebugBlockHeader;
LBlockHeader: NativeUInt;
begin
{Scan the entire memory pool first?}
if FullDebugModeScanMemoryPoolBeforeEveryOperation then
ScanMemoryPoolForCorruptions;
{Get a pointer to the start of the actual block}
LActualBlock := PFullDebugBlockHeader(PByte(APointer)
- SizeOf(TFullDebugBlockHeader));
{Is the debug info surrounding the block valid?}
if CheckBlockBeforeFreeOrRealloc(LActualBlock, boFreeMem) then
begin
{Enter the memory manager: block scans may not be performed now}
StartChangingFullDebugModeBlock;
try
{$ifdef FullDebugModeCallBacks}
if Assigned(OnDebugFreeMemStart) then
OnDebugFreeMemStart(LActualBlock);
{$endif}
{Large blocks are never reused, so there is no point in updating their
headers and fill pattern.}
LBlockHeader := PNativeUInt(PByte(LActualBlock) - BlockHeaderSize)^;
if LBlockHeader and (IsFreeBlockFlag or IsMediumBlockFlag or IsLargeBlockFlag) <> IsLargeBlockFlag then
begin
{Get the class the block was used for}
LActualBlock.PreviouslyUsedByClass := PNativeUInt(APointer)^;
{Set the free call stack}
GetStackTrace(@LActualBlock.FreeStackTrace, StackTraceDepth, 1);
{Set the thread ID of the thread that freed the block}
LActualBlock.FreedByThread := GetThreadID;
{Block is now free}
LActualBlock.AllocatedByRoutine := nil;
{Clear the user area of the block}
DebugFillMem(APointer^, LActualBlock.UserSize,
{$ifndef CatchUseOfFreedInterfaces}DebugFillPattern{$else}NativeUInt(@VMTBadInterface){$endif});
{Set a pointer to the dummy VMT}
PNativeUInt(APointer)^ := NativeUInt(@FreedObjectVMT.VMTMethods[0]);
{Recalculate the checksums}
UpdateHeaderAndFooterCheckSums(LActualBlock);
end;
{$ifdef EnableMemoryLeakReporting}
{Automatically deregister the expected memory leak?}
if FullDebugModeRegisterAllAllocsAsExpectedMemoryLeak then
UnregisterExpectedMemoryLeak(APointer);
{$endif}
{Free the actual block}
Result := FastFreeMem(LActualBlock);
{$ifdef FullDebugModeCallBacks}
if Assigned(OnDebugFreeMemFinish) then
OnDebugFreeMemFinish(LActualBlock, Result);
{$endif}
finally
{Leaving the memory manager routine: Block scans may be performed again.}
DoneChangingFullDebugModeBlock;
end;
end
else
begin
{$ifdef SuppressFreeMemErrorsInsideException}
if {$ifdef BDS2006AndUp}ExceptObject{$else}RaiseList{$endif} <> nil then
Result := 0
else
{$endif}
Result := -1;
end;
end;
function DebugReallocMem(APointer: Pointer; ANewSize: {$ifdef XE2AndUp}NativeInt{$else}Integer{$endif}): Pointer;
var
LMoveSize, LBlockSpace: NativeUInt;
LActualBlock, LNewActualBlock: PFullDebugBlockHeader;
begin
{Scan the entire memory pool first?}
if FullDebugModeScanMemoryPoolBeforeEveryOperation then
ScanMemoryPoolForCorruptions;
{Get a pointer to the start of the actual block}
LActualBlock := PFullDebugBlockHeader(PByte(APointer)
- SizeOf(TFullDebugBlockHeader));
{Is the debug info surrounding the block valid?}
if CheckBlockBeforeFreeOrRealloc(LActualBlock, boReallocMem) then
begin
{Get the current block size}
LBlockSpace := GetAvailableSpaceInBlock(LActualBlock);
{Can the block fit? We need space for the debug overhead and the block header
of the next block}
if LBlockSpace < (NativeUInt(ANewSize) + FullDebugBlockOverhead) then
begin
{Get a new block of the requested size.}
Result := DebugGetMem(ANewSize);
if Result <> nil then
begin
{Block scans may not be performed now}
StartChangingFullDebugModeBlock;
try
{$ifdef FullDebugModeCallBacks}
if Assigned(OnDebugReallocMemStart) then
OnDebugReallocMemStart(LActualBlock, ANewSize);
{$endif}
{We reuse the old allocation number. Since DebugGetMem always bumps
CurrentAllocationGroup, there may be gaps in the sequence of
allocation numbers.}
LNewActualBlock := PFullDebugBlockHeader(PByte(Result)
- SizeOf(TFullDebugBlockHeader));
LNewActualBlock.AllocationGroup := LActualBlock.AllocationGroup;
LNewActualBlock.AllocationNumber := LActualBlock.AllocationNumber;
{Recalculate the header and footer checksums}
UpdateHeaderAndFooterCheckSums(LNewActualBlock);
{$ifdef FullDebugModeCallBacks}
if Assigned(OnDebugReallocMemFinish) then
OnDebugReallocMemFinish(LNewActualBlock, ANewSize);
{$endif}
finally
{Block scans can again be performed safely}
DoneChangingFullDebugModeBlock;
end;
{How many bytes to move?}
LMoveSize := LActualBlock.UserSize;
if LMoveSize > NativeUInt(ANewSize) then
LMoveSize := ANewSize;
{Move the data across}
System.Move(APointer^, Result^, LMoveSize);
{Free the old block}
DebugFreeMem(APointer);
end
else
begin
Result := nil;
end;
end
else
begin
{Block scans may not be performed now}
StartChangingFullDebugModeBlock;
try
{$ifdef FullDebugModeCallBacks}
if Assigned(OnDebugReallocMemStart) then
OnDebugReallocMemStart(LActualBlock, ANewSize);
{$endif}
{Clear all data after the new end of the block up to the old end of the
block, including the trailer.}
DebugFillMem(Pointer(PByte(APointer) + NativeUInt(ANewSize) + SizeOf(NativeUInt))^,
NativeInt(LActualBlock.UserSize) - ANewSize,
{$ifndef CatchUseOfFreedInterfaces}
DebugFillPattern);
{$else}
RotateRight(NativeUInt(@VMTBadInterface), (ANewSize and (SizeOf(Pointer) - 1)) * 8));
{$endif}
{Update the user size}
LActualBlock.UserSize := ANewSize;
{Set the new checksums}
UpdateHeaderAndFooterCheckSums(LActualBlock);
{$ifdef FullDebugModeCallBacks}
if Assigned(OnDebugReallocMemFinish) then
OnDebugReallocMemFinish(LActualBlock, ANewSize);
{$endif}
finally
{Block scans can again be performed safely}
DoneChangingFullDebugModeBlock;
end;
{Return the old pointer}
Result := APointer;
end;
end
else
begin
Result := nil;
end;
end;
{Allocates a block and fills it with zeroes}
function DebugAllocMem(ASize: {$ifdef XE2AndUp}NativeInt{$else}Cardinal{$endif}): Pointer;
begin
Result := DebugGetMem(ASize);
{Clear the block}
if Result <> nil then
FillChar(Result^, ASize, 0);
end;
{Raises a runtime error if a memory corruption was encountered. Subroutine for
InternalScanMemoryPool and InternalScanSmallBlockPool.}
procedure RaiseMemoryCorruptionError;
begin
{Disable exhaustive checking in order to prevent recursive exceptions.}
FullDebugModeScanMemoryPoolBeforeEveryOperation := False;
{Unblock the memory manager in case the creation of the exception below
causes an attempt to be made to allocate memory.}
UnblockFullDebugModeMMRoutines;
{Raise the runtime error}
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reOutOfMemory);
{$else}
System.RunError(reOutOfMemory);
{$endif}
end;
{Subroutine for InternalScanMemoryPool: Checks the given small block pool for
allocated blocks}
procedure InternalScanSmallBlockPool(APSmallBlockPool: PSmallBlockPoolHeader;
AFirstAllocationGroupToLog, ALastAllocationGroupToLog: Cardinal);
var
LCurPtr, LEndPtr: Pointer;
begin
{Get the first and last pointer for the pool}
GetFirstAndLastSmallBlockInPool(APSmallBlockPool, LCurPtr, LEndPtr);
{Step through all blocks}
while UIntPtr(LCurPtr) <= UIntPtr(LEndPtr) do
begin
{Is this block in use? If so, is the debug info intact?}
if ((PNativeUInt(PByte(LCurPtr) - BlockHeaderSize)^ and IsFreeBlockFlag) = 0) then
begin
if CheckBlockBeforeFreeOrRealloc(LCurPtr, boBlockCheck) then
begin
if (PFullDebugBlockHeader(LCurPtr).AllocationGroup >= AFirstAllocationGroupToLog)
and (PFullDebugBlockHeader(LCurPtr).AllocationGroup <= ALastAllocationGroupToLog) then
begin
LogMemoryLeakOrAllocatedBlock(LCurPtr, False);
end;
end
else
RaiseMemoryCorruptionError;
end
else
begin
{Check that the block has not been modified since being freed}
if not CheckFreeBlockUnmodified(LCurPtr, APSmallBlockPool.BlockType.BlockSize, boBlockCheck) then
RaiseMemoryCorruptionError;
end;
{Next block}
Inc(PByte(LCurPtr), APSmallBlockPool.BlockType.BlockSize);
end;
end;
{Subroutine for LogAllocatedBlocksToFile and ScanMemoryPoolForCorruptions:
Scans the memory pool for corruptions and optionally logs allocated blocks
in the allocation group range.}
procedure InternalScanMemoryPool(AFirstAllocationGroupToLog, ALastAllocationGroupToLog: Cardinal);
var
LPLargeBlock: PLargeBlockHeader;
LPMediumBlock: Pointer;
LPMediumBlockPoolHeader: PMediumBlockPoolHeader;
LMediumBlockHeader: NativeUInt;
begin
{Block all the memory manager routines while performing the scan. No memory
block may be allocated or freed, and no FullDebugMode block header or
footer may be modified, while the scan is in progress.}
BlockFullDebugModeMMRoutines;
try
{Step through all the medium block pools}
LPMediumBlockPoolHeader := MediumBlockPoolsCircularList.NextMediumBlockPoolHeader;
while LPMediumBlockPoolHeader <> @MediumBlockPoolsCircularList do
begin
LPMediumBlock := GetFirstMediumBlockInPool(LPMediumBlockPoolHeader);
while LPMediumBlock <> nil do
begin
LMediumBlockHeader := PNativeUInt(PByte(LPMediumBlock) - BlockHeaderSize)^;
{Is the block in use?}
if LMediumBlockHeader and IsFreeBlockFlag = 0 then
begin
{Block is in use: Is it a medium block or small block pool?}
if (LMediumBlockHeader and IsSmallBlockPoolInUseFlag) <> 0 then
begin
{Get all the leaks for the small block pool}
InternalScanSmallBlockPool(LPMediumBlock, AFirstAllocationGroupToLog, ALastAllocationGroupToLog);
end
else
begin
if CheckBlockBeforeFreeOrRealloc(LPMediumBlock, boBlockCheck) then
begin
if (PFullDebugBlockHeader(LPMediumBlock).AllocationGroup >= AFirstAllocationGroupToLog)
and (PFullDebugBlockHeader(LPMediumBlock).AllocationGroup <= ALastAllocationGroupToLog) then
begin
LogMemoryLeakOrAllocatedBlock(LPMediumBlock, False);
end;
end
else
RaiseMemoryCorruptionError;
end;
end
else
begin
{Check that the block has not been modified since being freed}
if not CheckFreeBlockUnmodified(LPMediumBlock, LMediumBlockHeader and DropMediumAndLargeFlagsMask, boBlockCheck) then
RaiseMemoryCorruptionError;
end;
{Next medium block}
LPMediumBlock := NextMediumBlock(LPMediumBlock);
end;
{Get the next medium block pool}
LPMediumBlockPoolHeader := LPMediumBlockPoolHeader.NextMediumBlockPoolHeader;
end;
{Scan large blocks}
LPLargeBlock := LargeBlocksCircularList.NextLargeBlockHeader;
while LPLargeBlock <> @LargeBlocksCircularList do
begin
if CheckBlockBeforeFreeOrRealloc(Pointer(PByte(LPLargeBlock) + LargeBlockHeaderSize), boBlockCheck) then
begin
if (PFullDebugBlockHeader(PByte(LPLargeBlock) + LargeBlockHeaderSize).AllocationGroup >= AFirstAllocationGroupToLog)
and (PFullDebugBlockHeader(PByte(LPLargeBlock) + LargeBlockHeaderSize).AllocationGroup <= ALastAllocationGroupToLog) then
begin
LogMemoryLeakOrAllocatedBlock(Pointer(PByte(LPLargeBlock) + LargeBlockHeaderSize), False);
end;
end
else
RaiseMemoryCorruptionError;
{Get the next large block}
LPLargeBlock := LPLargeBlock.NextLargeBlockHeader;
end;
finally
{Unblock the FullDebugMode memory manager routines.}
UnblockFullDebugModeMMRoutines;
end;
end;
{Logs detail about currently allocated memory blocks for the specified range of
allocation groups. if ALastAllocationGroupToLog is less than
AFirstAllocationGroupToLog or it is zero, then all allocation groups are
logged. This routine also checks the memory pool for consistency at the same
time, raising an "Out of Memory" error if the check fails.}
procedure LogAllocatedBlocksToFile(AFirstAllocationGroupToLog, ALastAllocationGroupToLog: Cardinal);
begin
{Validate input}
if (ALastAllocationGroupToLog = 0) or (ALastAllocationGroupToLog < AFirstAllocationGroupToLog) then
begin
{Bad input: log all groups}
AFirstAllocationGroupToLog := 0;
ALastAllocationGroupToLog := $ffffffff;
end;
{Scan the memory pool, logging allocated blocks in the requested range.}
InternalScanMemoryPool(AFirstAllocationGroupToLog, ALastAllocationGroupToLog);
end;
{Scans the memory pool for any corruptions. If a corruption is encountered an "Out of Memory" exception is
raised.}
procedure ScanMemoryPoolForCorruptions;
begin
{Scan the memory pool for corruptions, but don't log any allocated blocks}
InternalScanMemoryPool($ffffffff, 0);
end;
{-----------------------Invalid Virtual Method Calls-------------------------}
{ TFreedObject }
{Used to determine the index of the virtual method call on the freed object.
Do not change this without updating MaxFakeVMTEntries. Currently 200.}
procedure TFreedObject.GetVirtualMethodIndex;
asm
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex); Inc(VMIndex);
jmp TFreedObject.VirtualMethodError
end;
procedure TFreedObject.VirtualMethodError;
var
LVMOffset: Integer;
LMsgPtr: PAnsiChar;
LErrorMessage: array[0..32767] of AnsiChar;
{$ifndef NoMessageBoxes}
LErrorMessageTitle: array[0..1023] of AnsiChar;
{$endif}
LClass: TClass;
LActualBlock: PFullDebugBlockHeader;
begin
{Get the offset of the virtual method}
LVMOffset := (MaxFakeVMTEntries - VMIndex) * SizeOf(Pointer) + vmtParent + SizeOf(Pointer);
{Reset the index for the next error}
VMIndex := 0;
{Get the address of the actual block}
LActualBlock := PFullDebugBlockHeader(PByte(Self) - SizeOf(TFullDebugBlockHeader));
{Display the error header}
LMsgPtr := AppendStringToBuffer(VirtualMethodErrorHeader, @LErrorMessage[0], Length(VirtualMethodErrorHeader));
{Is the debug info surrounding the block valid?}
if CalculateHeaderCheckSum(LActualBlock) = LActualBlock.HeaderCheckSum then
begin
{Get the class this block was used for previously}
LClass := DetectClassInstance(@LActualBlock.PreviouslyUsedByClass);
if (LClass <> nil) and (IntPtr(LClass) <> IntPtr(@FreedObjectVMT.VMTMethods[0])) then
begin
LMsgPtr := AppendStringToBuffer(FreedObjectClassMsg, LMsgPtr, Length(FreedObjectClassMsg));
LMsgPtr := AppendClassNameToBuffer(LClass, LMsgPtr);
end;
{Get the virtual method name}
LMsgPtr := AppendStringToBuffer(VirtualMethodName, LMsgPtr, Length(VirtualMethodName));
if LVMOffset < 0 then
begin
LMsgPtr := AppendStringToBuffer(StandardVirtualMethodNames[LVMOffset div SizeOf(Pointer)], LMsgPtr, Length(StandardVirtualMethodNames[LVMOffset div SizeOf(Pointer)]));
end
else
begin
LMsgPtr := AppendStringToBuffer(VirtualMethodOffset, LMsgPtr, Length(VirtualMethodOffset));
LMsgPtr := NativeUIntToStrBuf(LVMOffset, LMsgPtr);
end;
{Virtual method address}
if (LClass <> nil) and (IntPtr(LClass) <> IntPtr(@FreedObjectVMT.VMTMethods[0])) then
begin
LMsgPtr := AppendStringToBuffer(VirtualMethodAddress, LMsgPtr, Length(VirtualMethodAddress));
LMsgPtr := NativeUIntToHexBuf(PNativeUInt(PByte(LClass) + LVMOffset)^, LMsgPtr);
end;
{Log the allocation group}
if LActualBlock.AllocationGroup > 0 then
begin
LMsgPtr := AppendStringToBuffer(PreviousAllocationGroupMsg, LMsgPtr, Length(PreviousAllocationGroupMsg));
LMsgPtr := NativeUIntToStrBuf(LActualBlock.AllocationGroup, LMsgPtr);
end;
{Log the allocation number}
LMsgPtr := AppendStringToBuffer(PreviousAllocationNumberMsg, LMsgPtr, Length(PreviousAllocationNumberMsg));
LMsgPtr := NativeUIntToStrBuf(LActualBlock.AllocationNumber, LMsgPtr);
{The header is still intact - display info about the this/previous allocation}
if LActualBlock.AllocationStackTrace[0] <> 0 then
begin
LMsgPtr := AppendStringToBuffer(ThreadIDAtObjectAllocMsg, LMsgPtr, Length(ThreadIDAtObjectAllocMsg));
LMsgPtr := NativeUIntToHexBuf(LActualBlock.AllocatedByThread, LMsgPtr);
LMsgPtr := AppendStringToBuffer(StackTraceMsg, LMsgPtr, Length(StackTraceMsg));
LMsgPtr := LogStackTrace(@LActualBlock.AllocationStackTrace, StackTraceDepth, LMsgPtr);
end;
{Get the call stack for the previous free}
if LActualBlock.FreeStackTrace[0] <> 0 then
begin
LMsgPtr := AppendStringToBuffer(ThreadIDAtObjectFreeMsg, LMsgPtr, Length(ThreadIDAtObjectFreeMsg));
LMsgPtr := NativeUIntToHexBuf(LActualBlock.FreedByThread, LMsgPtr);
LMsgPtr := AppendStringToBuffer(StackTraceMsg, LMsgPtr, Length(StackTraceMsg));
LMsgPtr := LogStackTrace(@LActualBlock.FreeStackTrace, StackTraceDepth, LMsgPtr);
end;
end
else
begin
{Header has been corrupted}
LMsgPtr := AppendStringToBuffer(BlockHeaderCorruptedNoHistoryMsg, LMsgPtr, Length(BlockHeaderCorruptedNoHistoryMsg));
end;
{Add the current stack trace}
LMsgPtr := LogCurrentThreadAndStackTrace(2, LMsgPtr);
{$ifndef DisableLoggingOfMemoryDumps}
{Add the pointer address}
LMsgPtr := LogMemoryDump(LActualBlock, LMsgPtr);
{$endif}
{Trailing CRLF}
LMsgPtr^ := #13;
Inc(LMsgPtr);
LMsgPtr^ := #10;
Inc(LMsgPtr);
{Trailing #0}
LMsgPtr^ := #0;
{$ifdef LogErrorsToFile}
{Log the error}
AppendEventLog(@LErrorMessage[0], NativeUInt(LMsgPtr) - NativeUInt(@LErrorMessage[0]));
{$endif}
{$ifdef UseOutputDebugString}
OutputDebugStringA(LErrorMessage);
{$endif}
{$ifndef NoMessageBoxes}
{Show the message}
AppendStringToModuleName(BlockErrorMsgTitle, LErrorMessageTitle);
ShowMessageBox(LErrorMessage, LErrorMessageTitle);
{$endif}
{Raise an access violation}
RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, nil);
end;
{$ifdef CatchUseOfFreedInterfaces}
procedure TFreedObject.InterfaceError;
var
LMsgPtr: PAnsiChar;
{$ifndef NoMessageBoxes}
LErrorMessageTitle: array[0..1023] of AnsiChar;
{$endif}
LErrorMessage: array[0..4000] of AnsiChar;
begin
{Display the error header}
LMsgPtr := AppendStringToBuffer(InterfaceErrorHeader, @LErrorMessage[0], Length(InterfaceErrorHeader));
{Add the current stack trace}
LMsgPtr := LogCurrentThreadAndStackTrace(2, LMsgPtr);
{Trailing CRLF}
LMsgPtr^ := #13;
Inc(LMsgPtr);
LMsgPtr^ := #10;
Inc(LMsgPtr);
{Trailing #0}
LMsgPtr^ := #0;
{$ifdef LogErrorsToFile}
{Log the error}
AppendEventLog(@LErrorMessage[0], NativeUInt(LMsgPtr) - NativeUInt(@LErrorMessage[0]));
{$endif}
{$ifdef UseOutputDebugString}
OutputDebugStringA(LErrorMessage);
{$endif}
{$ifndef NoMessageBoxes}
{Show the message}
AppendStringToModuleName(BlockErrorMsgTitle, LErrorMessageTitle);
ShowMessageBox(LErrorMessage, LErrorMessageTitle);
{$endif}
{Raise an access violation}
RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, nil);
end;
{$endif}
{$endif}
{----------------------------Memory Leak Checking-----------------------------}
{$ifdef EnableMemoryLeakReporting}
{Adds a leak to the specified list}
function UpdateExpectedLeakList(APLeakList: PPExpectedMemoryLeak;
APNewEntry: PExpectedMemoryLeak; AExactSizeMatch: Boolean = True): Boolean;
var
LPInsertAfter, LPNewEntry: PExpectedMemoryLeak;
begin
{Default to error}
Result := False;
{Find the insertion spot}
LPInsertAfter := APLeakList^;
while LPInsertAfter <> nil do
begin
{Too big?}
if LPInsertAfter.LeakSize > APNewEntry.LeakSize then
begin
LPInsertAfter := LPInsertAfter.PreviousLeak;
Break;
end;
{Find a matching entry. If an exact size match is not required and the leak
is larger than the current entry, use it if the expected size of the next
entry is too large.}
if (IntPtr(LPInsertAfter.LeakAddress) = IntPtr(APNewEntry.LeakAddress))
and ((IntPtr(LPInsertAfter.LeakedClass) = IntPtr(APNewEntry.LeakedClass))
{$ifdef CheckCppObjectTypeEnabled}
or (LPInsertAfter.LeakedCppTypeIdPtr = APNewEntry.LeakedCppTypeIdPtr)
{$endif}
)
and ((LPInsertAfter.LeakSize = APNewEntry.LeakSize)
or ((not AExactSizeMatch)
and (LPInsertAfter.LeakSize < APNewEntry.LeakSize)
and ((LPInsertAfter.NextLeak = nil)
or (LPInsertAfter.NextLeak.LeakSize > APNewEntry.LeakSize))
)) then
begin
if (LPInsertAfter.LeakCount + APNewEntry.LeakCount) >= 0 then
begin
Inc(LPInsertAfter.LeakCount, APNewEntry.LeakCount);
{Is the count now 0?}
if LPInsertAfter.LeakCount = 0 then
begin
{Delete the entry}
if LPInsertAfter.NextLeak <> nil then
LPInsertAfter.NextLeak.PreviousLeak := LPInsertAfter.PreviousLeak;
if LPInsertAfter.PreviousLeak <> nil then
LPInsertAfter.PreviousLeak.NextLeak := LPInsertAfter.NextLeak
else
APLeakList^ := LPInsertAfter.NextLeak;
{Insert it as the first free slot}
LPInsertAfter.NextLeak := ExpectedMemoryLeaks.FirstFreeSlot;
ExpectedMemoryLeaks.FirstFreeSlot := LPInsertAfter;
end;
Result := True;
end;
Exit;
end;
{Next entry}
if LPInsertAfter.NextLeak <> nil then
LPInsertAfter := LPInsertAfter.NextLeak
else
Break;
end;
if APNewEntry.LeakCount > 0 then
begin
{Get a position for the entry}
LPNewEntry := ExpectedMemoryLeaks.FirstFreeSlot;
if LPNewEntry <> nil then
begin
ExpectedMemoryLeaks.FirstFreeSlot := LPNewEntry.NextLeak;
end
else
begin
if ExpectedMemoryLeaks.EntriesUsed < Length(ExpectedMemoryLeaks.ExpectedLeaks) then
begin
LPNewEntry := @ExpectedMemoryLeaks.ExpectedLeaks[ExpectedMemoryLeaks.EntriesUsed];
Inc(ExpectedMemoryLeaks.EntriesUsed);
end
else
begin
{No more space}
Exit;
end;
end;
{Set the entry}
LPNewEntry^ := APNewEntry^;
{Insert it into the list}
LPNewEntry.PreviousLeak := LPInsertAfter;
if LPInsertAfter <> nil then
begin
LPNewEntry.NextLeak := LPInsertAfter.NextLeak;
if LPNewEntry.NextLeak <> nil then
LPNewEntry.NextLeak.PreviousLeak := LPNewEntry;
LPInsertAfter.NextLeak := LPNewEntry;
end
else
begin
LPNewEntry.NextLeak := APLeakList^;
if LPNewEntry.NextLeak <> nil then
LPNewEntry.NextLeak.PreviousLeak := LPNewEntry;
APLeakList^ := LPNewEntry;
end;
Result := True;
end;
end;
{Locks the expected leaks. Returns false if the list could not be allocated.}
function LockExpectedMemoryLeaksList: Boolean;
begin
{Lock the expected leaks list}
{$ifndef AssumeMultiThreaded}
if IsMultiThread then
{$endif}
begin
while LockCmpxchg(0, 1, @ExpectedMemoryLeaksListLocked) <> 0 do
begin
{$ifdef NeverSleepOnThreadContention}
{$ifdef UseSwitchToThread}
SwitchToThread;
{$endif}
{$else}
Sleep(InitialSleepTime);
if LockCmpxchg(0, 1, @ExpectedMemoryLeaksListLocked) = 0 then
Break;
Sleep(AdditionalSleepTime);
{$endif}
end;
end;
{Allocate the list if it does not exist}
if ExpectedMemoryLeaks = nil then
ExpectedMemoryLeaks := VirtualAlloc(nil, ExpectedMemoryLeaksListSize, MEM_COMMIT, PAGE_READWRITE);
{Done}
Result := ExpectedMemoryLeaks <> nil;
end;
{Registers expected memory leaks. Returns true on success. The list of leaked
blocks is limited, so failure is possible if the list is full.}
function RegisterExpectedMemoryLeak(ALeakedPointer: Pointer): Boolean; overload;
var
LNewEntry: TExpectedMemoryLeak;
begin
{Fill out the structure}
{$ifndef FullDebugMode}
LNewEntry.LeakAddress := ALeakedPointer;
{$else}
LNewEntry.LeakAddress := Pointer(PByte(ALeakedPointer) - SizeOf(TFullDebugBlockHeader));
{$endif}
LNewEntry.LeakedClass := nil;
{$ifdef CheckCppObjectTypeEnabled}
LNewEntry.LeakedCppTypeIdPtr := nil;
{$endif}
LNewEntry.LeakSize := 0;
LNewEntry.LeakCount := 1;
{Add it to the correct list}
Result := LockExpectedMemoryLeaksList
and UpdateExpectedLeakList(@ExpectedMemoryLeaks.FirstEntryByAddress, @LNewEntry);
ExpectedMemoryLeaksListLocked := False;
end;
function RegisterExpectedMemoryLeak(ALeakedObjectClass: TClass; ACount: Integer = 1): Boolean; overload;
var
LNewEntry: TExpectedMemoryLeak;
begin
{Fill out the structure}
LNewEntry.LeakAddress := nil;
LNewEntry.LeakedClass := ALeakedObjectClass;
{$ifdef CheckCppObjectTypeEnabled}
LNewEntry.LeakedCppTypeIdPtr := nil;
{$endif}
LNewEntry.LeakSize := ALeakedObjectClass.InstanceSize;
LNewEntry.LeakCount := ACount;
{Add it to the correct list}
Result := LockExpectedMemoryLeaksList
and UpdateExpectedLeakList(@ExpectedMemoryLeaks.FirstEntryByClass, @LNewEntry);
ExpectedMemoryLeaksListLocked := False;
end;
{$ifdef CheckCppObjectTypeEnabled}
function RegisterExpectedMemoryLeak(ALeakedCppVirtObjTypeIdPtr: Pointer; ACount: Integer): Boolean; overload;
var
LNewEntry: TExpectedMemoryLeak;
begin
{Fill out the structure}
if Assigned(GetCppVirtObjSizeByTypeIdPtrFunc) then
begin
//Return 0 if not a proper type
LNewEntry.LeakSize := GetCppVirtObjSizeByTypeIdPtrFunc(ALeakedCppVirtObjTypeIdPtr);
if LNewEntry.LeakSize > 0 then
begin
LNewEntry.LeakAddress := nil;
LNewEntry.LeakedClass := nil;
LNewEntry.LeakedCppTypeIdPtr := ALeakedCppVirtObjTypeIdPtr;
LNewEntry.LeakCount := ACount;
{Add it to the correct list}
Result := LockExpectedMemoryLeaksList
and UpdateExpectedLeakList(@ExpectedMemoryLeaks.FirstEntryByClass, @LNewEntry);
ExpectedMemoryLeaksListLocked := False;
end
else
begin
Result := False;
end;
end
else
begin
Result := False;
end;
end;
{$endif}
function RegisterExpectedMemoryLeak(ALeakedBlockSize: NativeInt; ACount: Integer = 1): Boolean; overload;
var
LNewEntry: TExpectedMemoryLeak;
begin
{Fill out the structure}
LNewEntry.LeakAddress := nil;
LNewEntry.LeakedClass := nil;
{$ifdef CheckCppObjectTypeEnabled}
LNewEntry.LeakedCppTypeIdPtr := nil;
{$endif}
LNewEntry.LeakSize := ALeakedBlockSize;
LNewEntry.LeakCount := ACount;
{Add it to the correct list}
Result := LockExpectedMemoryLeaksList
and UpdateExpectedLeakList(@ExpectedMemoryLeaks.FirstEntryBySizeOnly, @LNewEntry);
ExpectedMemoryLeaksListLocked := False;
end;
function UnregisterExpectedMemoryLeak(ALeakedPointer: Pointer): Boolean; overload;
var
LNewEntry: TExpectedMemoryLeak;
begin
{Fill out the structure}
{$ifndef FullDebugMode}
LNewEntry.LeakAddress := ALeakedPointer;
{$else}
LNewEntry.LeakAddress := Pointer(PByte(ALeakedPointer) - SizeOf(TFullDebugBlockHeader));
{$endif}
LNewEntry.LeakedClass := nil;
{$ifdef CheckCppObjectTypeEnabled}
LNewEntry.LeakedCppTypeIdPtr := nil;
{$endif}
LNewEntry.LeakSize := 0;
LNewEntry.LeakCount := -1;
{Remove it from the list}
Result := LockExpectedMemoryLeaksList
and UpdateExpectedLeakList(@ExpectedMemoryLeaks.FirstEntryByAddress, @LNewEntry);
ExpectedMemoryLeaksListLocked := False;
end;
function UnregisterExpectedMemoryLeak(ALeakedObjectClass: TClass; ACount: Integer = 1): Boolean; overload;
begin
Result := RegisterExpectedMemoryLeak(ALeakedObjectClass, - ACount);
end;
{$ifdef CheckCppObjectTypeEnabled}
function UnregisterExpectedMemoryLeak(ALeakedCppVirtObjTypeIdPtr: Pointer; ACount: Integer): Boolean; overload;
begin
Result := RegisterExpectedMemoryLeak(ALeakedCppVirtObjTypeIdPtr, - ACount);
end;
{$endif}
function UnregisterExpectedMemoryLeak(ALeakedBlockSize: NativeInt; ACount: Integer = 1): Boolean; overload;
begin
Result := RegisterExpectedMemoryLeak(ALeakedBlockSize, - ACount);
end;
{Returns a list of all expected memory leaks}
function GetRegisteredMemoryLeaks: TRegisteredMemoryLeaks;
procedure AddEntries(AEntry: PExpectedMemoryLeak);
var
LInd: Integer;
begin
while AEntry <> nil do
begin
LInd := Length(Result);
SetLength(Result, LInd + 1);
{Add the entry}
{$ifndef FullDebugMode}
Result[LInd].LeakAddress := AEntry.LeakAddress;
{$else}
Result[LInd].LeakAddress := Pointer(PByte(AEntry.LeakAddress) + SizeOf(TFullDebugBlockHeader));
{$endif}
Result[LInd].LeakedClass := AEntry.LeakedClass;
{$ifdef CheckCppObjectTypeEnabled}
Result[LInd].LeakedCppTypeIdPtr := AEntry.LeakedCppTypeIdPtr;
{$endif}
Result[LInd].LeakSize := AEntry.LeakSize;
Result[LInd].LeakCount := AEntry.LeakCount;
{Next entry}
AEntry := AEntry.NextLeak;
end;
end;
begin
SetLength(Result, 0);
if (ExpectedMemoryLeaks <> nil) and LockExpectedMemoryLeaksList then
begin
{Add all entries}
AddEntries(ExpectedMemoryLeaks.FirstEntryByAddress);
AddEntries(ExpectedMemoryLeaks.FirstEntryByClass);
AddEntries(ExpectedMemoryLeaks.FirstEntryBySizeOnly);
{Unlock the list}
ExpectedMemoryLeaksListLocked := False;
end;
end;
{$else}
{$ifdef BDS2006AndUp}
function NoOpRegisterExpectedMemoryLeak(ALeakedPointer: Pointer): Boolean;
begin
{Do nothing. Used when memory leak reporting is disabled under Delphi 2006 and later.}
Result := False;
end;
function NoOpUnregisterExpectedMemoryLeak(ALeakedPointer: Pointer): Boolean;
begin
{Do nothing. Used when memory leak reporting is disabled under Delphi 2006 and later.}
Result := False;
end;
{$endif}
{$endif}
{Detects the probable string data type for a memory block.}
function DetectStringData(APMemoryBlock: Pointer;
AAvailableSpaceInBlock: NativeInt): TStringDataType;
const
{If the string reference count field contains a value greater than this,
then it is assumed that the block is not a string.}
MaxRefCount = 255;
{The lowest ASCII character code considered valid string data. If there are
any characters below this code point then the data is assumed not to be a
string. #9 = Tab.}
MinCharCode = #9;
var
LStringLength, LElemSize, LCharInd: Integer;
LPAnsiStr: PAnsiChar;
LPUniStr: PWideChar;
begin
{Check that the reference count is within a reasonable range}
if PStrRec(APMemoryBlock).refCnt > MaxRefCount then
begin
Result := stUnknown;
Exit;
end;
{$ifdef BCB6OrDelphi6AndUp}
{$if RTLVersion >= 20}
LElemSize := PStrRec(APMemoryBlock).elemSize;
{Element size must be either 1 (Ansi) or 2 (Unicode)}
if (LElemSize <> 1) and (LElemSize <> 2) then
begin
Result := stUnknown;
Exit;
end;
{$ifend}
{$if RTLVersion < 20}
LElemSize := 1;
{$ifend}
{$else}
LElemSize := 1;
{$endif}
{Get the string length}
LStringLength := PStrRec(APMemoryBlock).length;
{Does the string fit?}
if (LStringLength <= 0)
or (LStringLength >= (AAvailableSpaceInBlock - SizeOf(StrRec)) div LElemSize) then
begin
Result := stUnknown;
Exit;
end;
{Check for no characters outside the expected range. If there are,
then it is probably not a string.}
if LElemSize = 1 then
begin
{Check that all characters are in the range considered valid.}
LPAnsiStr := PAnsiChar(PByte(APMemoryBlock) + SizeOf(StrRec));
for LCharInd := 1 to LStringLength do
begin
if LPAnsiStr^ < MinCharCode then
begin
Result := stUnknown;
Exit;
end;
Inc(LPAnsiStr);
end;
{Must have a trailing #0}
if LPAnsiStr^ = #0 then
Result := stAnsiString
else
Result := stUnknown;
end
else
begin
{Check that all characters are in the range considered valid.}
LPUniStr := PWideChar(PByte(APMemoryBlock) + SizeOf(StrRec));
for LCharInd := 1 to LStringLength do
begin
if LPUniStr^ < MinCharCode then
begin
Result := stUnknown;
Exit;
end;
Inc(LPUniStr);
end;
{Must have a trailing #0}
if LPUniStr^ = #0 then
Result := stUnicodeString
else
Result := stUnknown;
end;
end;
{Walks all allocated blocks, calling ACallBack for each. Passes the user block size and AUserData to the callback.
Important note: All block types will be locked during the callback, so the memory manager cannot be used inside it.}
procedure WalkAllocatedBlocks(ACallBack: TWalkAllocatedBlocksCallback; AUserData: Pointer);
const
DebugHeaderSize = {$ifdef FullDebugMode}SizeOf(TFullDebugBlockHeader){$else}0{$endif};
TotalDebugOverhead = {$ifdef FullDebugMode}FullDebugBlockOverhead{$else}0{$endif};
var
LPMediumBlock: Pointer;
LPMediumBlockPoolHeader: PMediumBlockPoolHeader;
LMediumBlockHeader: NativeUInt;
LPLargeBlock: PLargeBlockHeader;
LBlockSize: NativeInt;
LPSmallBlockPool: PSmallBlockPoolHeader;
LCurPtr, LEndPtr: Pointer;
LInd: Integer;
begin
{Lock all small block types}
LockAllSmallBlockTypes;
{Lock the medium blocks}
LockMediumBlocks;
try
{Step through all the medium block pools}
LPMediumBlockPoolHeader := MediumBlockPoolsCircularList.NextMediumBlockPoolHeader;
while LPMediumBlockPoolHeader <> @MediumBlockPoolsCircularList do
begin
LPMediumBlock := GetFirstMediumBlockInPool(LPMediumBlockPoolHeader);
while LPMediumBlock <> nil do
begin
LMediumBlockHeader := PNativeUInt(PByte(LPMediumBlock) - BlockHeaderSize)^;
{Is the block in use?}
if LMediumBlockHeader and IsFreeBlockFlag = 0 then
begin
if (LMediumBlockHeader and IsSmallBlockPoolInUseFlag) <> 0 then
begin
{Step through all the blocks in the small block pool}
LPSmallBlockPool := LPMediumBlock;
{Get the useable size inside a block}
LBlockSize := LPSmallBlockPool.BlockType.BlockSize - BlockHeaderSize - TotalDebugOverhead;
{Get the first and last pointer for the pool}
GetFirstAndLastSmallBlockInPool(LPSmallBlockPool, LCurPtr, LEndPtr);
{Step through all blocks}
while UIntPtr(LCurPtr) <= UIntPtr(LEndPtr) do
begin
{Is this block in use?}
if (PNativeUInt(PByte(LCurPtr) - BlockHeaderSize)^ and IsFreeBlockFlag) = 0 then
begin
ACallBack(PByte(LCurPtr) + DebugHeaderSize, LBlockSize, AUserData);
end;
{Next block}
Inc(PByte(LCurPtr), LPSmallBlockPool.BlockType.BlockSize);
end;
end
else
begin
LBlockSize := (LMediumBlockHeader and DropMediumAndLargeFlagsMask) - BlockHeaderSize - TotalDebugOverhead;
ACallBack(PByte(LPMediumBlock) + DebugHeaderSize, LBlockSize, AUserData);
end;
end;
{Next medium block}
LPMediumBlock := NextMediumBlock(LPMediumBlock);
end;
{Get the next medium block pool}
LPMediumBlockPoolHeader := LPMediumBlockPoolHeader.NextMediumBlockPoolHeader;
end;
finally
{Unlock medium blocks}
MediumBlocksLocked := False;
{Unlock all the small block types}
for LInd := 0 to NumSmallBlockTypes - 1 do
SmallBlockTypes[LInd].BlockTypeLocked := False;
end;
{Step through all the large blocks}
LockLargeBlocks;
try
{Get all leaked large blocks}
LPLargeBlock := LargeBlocksCircularList.NextLargeBlockHeader;
while LPLargeBlock <> @LargeBlocksCircularList do
begin
LBlockSize := (LPLargeBlock.BlockSizeAndFlags and DropMediumAndLargeFlagsMask) - BlockHeaderSize - LargeBlockHeaderSize - TotalDebugOverhead;
ACallBack(PByte(LPLargeBlock) + LargeBlockHeaderSize + DebugHeaderSize, LBlockSize, AUserData);
{Get the next large block}
LPLargeBlock := LPLargeBlock.NextLargeBlockHeader;
end;
finally
LargeBlocksLocked := False;
end;
end;
{-----------LogMemoryManagerStateToFile implementation------------}
const
MaxMemoryLogNodes = 100000;
QuickSortMinimumItemsInPartition = 4;
type
{While scanning the memory pool the list of classes is built up in a binary search tree.}
PMemoryLogNode = ^TMemoryLogNode;
TMemoryLogNode = record
{The left and right child nodes}
LeftAndRightNodePointers: array[Boolean] of PMemoryLogNode;
{The class this node belongs to}
ClassPtr: Pointer;
{The number of instances of the class}
InstanceCount: NativeInt;
{The total memory usage for this class}
TotalMemoryUsage: NativeInt;
end;
TMemoryLogNodes = array[0..MaxMemoryLogNodes - 1] of TMemoryLogNode;
PMemoryLogNodes = ^TMemoryLogNodes;
TMemoryLogInfo = record
{The number of nodes in "Nodes" that are used.}
NodeCount: Integer;
{The root node of the binary search tree. The content of this node is not actually used, it just simplifies the
binary search code.}
RootNode: TMemoryLogNode;
Nodes: TMemoryLogNodes;
end;
PMemoryLogInfo = ^TMemoryLogInfo;
{LogMemoryManagerStateToFile callback subroutine}
procedure LogMemoryManagerStateCallBack(APBlock: Pointer; ABlockSize: NativeInt; AUserData: Pointer);
var
LClass, LClassHashBits: NativeUInt;
LPLogInfo: PMemoryLogInfo;
LPParentNode, LPClassNode: PMemoryLogNode;
LChildNodeDirection: Boolean;
begin
LPLogInfo := AUserData;
{Detecting an object is very expensive (due to the VirtualQuery call), so we do some basic checks and try to find
the "class" in the tree first.}
LClass := PNativeUInt(APBlock)^;
{Do some basic pointer checks: The "class" must be dword aligned and beyond 64K}
if (LClass > 65535)
and (LClass and 3 = 0) then
begin
LPParentNode := @LPLogInfo.RootNode;
LClassHashBits := LClass;
repeat
LChildNodeDirection := Boolean(LClassHashBits and 1);
{Split off the next bit of the class pointer and traverse in the appropriate direction.}
LPClassNode := LPParentNode.LeftAndRightNodePointers[LChildNodeDirection];
{Is this child node the node the class we're looking for?}
if (LPClassNode = nil) or (NativeUInt(LPClassNode.ClassPtr) = LClass) then
Break;
{The node was not found: Keep on traversing the tree.}
LClassHashBits := LClassHashBits shr 1;
LPParentNode := LPClassNode;
until False;
end
else
LPClassNode := nil;
{Was the "class" found?}
if LPClassNode = nil then
begin
{The "class" is not yet in the tree: Determine if it is actually a class.}
LClass := NativeUInt(DetectClassInstance(APBlock));
{If it is not a class, try to detect the string type.}
if LClass = 0 then
LClass := Ord(DetectStringData(APBlock, ABlockSize));
{Is this class already in the tree?}
LPParentNode := @LPLogInfo.RootNode;
LClassHashBits := LClass;
repeat
LChildNodeDirection := Boolean(LClassHashBits and 1);
{Split off the next bit of the class pointer and traverse in the appropriate direction.}
LPClassNode := LPParentNode.LeftAndRightNodePointers[LChildNodeDirection];
{Is this child node the node the class we're looking for?}
if LPClassNode = nil then
begin
{The end of the tree was reached: Add a new child node.}
LPClassNode := @LPLogInfo.Nodes[LPLogInfo.NodeCount];
Inc(LPLogInfo.NodeCount);
LPParentNode.LeftAndRightNodePointers[LChildNodeDirection] := LPClassNode;
LPClassNode.ClassPtr := Pointer(LClass);
Break;
end
else
begin
if NativeUInt(LPClassNode.ClassPtr) = LClass then
Break;
end;
{The node was not found: Keep on traversing the tree.}
LClassHashBits := LClassHashBits shr 1;
LPParentNode := LPClassNode;
until False;
end;
{Update the statistics for the class}
Inc(LPClassNode.InstanceCount);
Inc(LPClassNode.TotalMemoryUsage, ABlockSize);
end;
{LogMemoryManagerStateToFile subroutine: A median-of-3 quicksort routine for sorting a TMemoryLogNodes array.}
procedure QuickSortLogNodes(APLeftItem: PMemoryLogNodes; ARightIndex: Integer);
var
M, I, J: Integer;
LPivot, LTempItem: TMemoryLogNode;
begin
while True do
begin
{Order the left, middle and right items in ascending order}
M := ARightIndex shr 1;
{Is the middle item larger than the left item?}
if APLeftItem[0].TotalMemoryUsage > APLeftItem[M].TotalMemoryUsage then
begin
{Swap items 0 and M}
LTempItem := APLeftItem[0];
APLeftItem[0] := APLeftItem[M];
APLeftItem[M] := LTempItem;
end;
{Is the middle item larger than the right?}
if APLeftItem[M].TotalMemoryUsage > APLeftItem[ARightIndex].TotalMemoryUsage then
begin
{The right-hand item is not larger - swap it with the middle}
LTempItem := APLeftItem[ARightIndex];
APLeftItem[ARightIndex] := APLeftItem[M];
APLeftItem[M] := LTempItem;
{Is the left larger than the new middle?}
if APLeftItem[0].TotalMemoryUsage > APLeftItem[M].TotalMemoryUsage then
begin
{Swap items 0 and M}
LTempItem := APLeftItem[0];
APLeftItem[0] := APLeftItem[M];
APLeftItem[M] := LTempItem;
end;
end;
{Move the pivot item out of the way by swapping M with R - 1}
LPivot := APLeftItem[M];
APLeftItem[M] := APLeftItem[ARightIndex - 1];
APLeftItem[ARightIndex - 1] := LPivot;
{Set up the loop counters}
I := 0;
J := ARightIndex - 1;
while true do
begin
{Find the first item from the left that is not smaller than the pivot}
repeat
Inc(I);
until APLeftItem[I].TotalMemoryUsage >= LPivot.TotalMemoryUsage;
{Find the first item from the right that is not larger than the pivot}
repeat
Dec(J);
until APLeftItem[J].TotalMemoryUsage <= LPivot.TotalMemoryUsage;
{Stop the loop when the two indexes cross}
if J < I then
Break;
{Swap item I and J}
LTempItem := APLeftItem[I];
APLeftItem[I] := APLeftItem[J];
APLeftItem[J] := LTempItem;
end;
{Put the pivot item back in the correct position by swapping I with R - 1}
APLeftItem[ARightIndex - 1] := APLeftItem[I];
APLeftItem[I] := LPivot;
{Sort the left-hand partition}
if J >= (QuickSortMinimumItemsInPartition - 1) then
QuickSortLogNodes(APLeftItem, J);
{Sort the right-hand partition}
APLeftItem := @APLeftItem[I + 1];
ARightIndex := ARightIndex - I - 1;
if ARightIndex < (QuickSortMinimumItemsInPartition - 1) then
Break;
end;
end;
{LogMemoryManagerStateToFile subroutine: An InsertionSort routine for sorting a TMemoryLogNodes array.}
procedure InsertionSortLogNodes(APLeftItem: PMemoryLogNodes; ARightIndex: Integer);
var
I, J: Integer;
LCurNode: TMemoryLogNode;
begin
for I := 1 to ARightIndex do
begin
LCurNode := APLeftItem[I];
{Scan backwards to find the best insertion spot}
J := I;
while (J > 0) and (APLeftItem[J - 1].TotalMemoryUsage > LCurNode.TotalMemoryUsage) do
begin
APLeftItem[J] := APLeftItem[J - 1];
Dec(J);
end;
APLeftItem[J] := LCurNode;
end;
end;
{Writes a log file containing a summary of the memory mananger state and a summary of allocated blocks grouped by
class. The file will be saved in UTF-8 encoding (in supported Delphi versions). Returns True on success. }
function LogMemoryManagerStateToFile(const AFileName: string; const AAdditionalDetails: string): Boolean;
const
MsgBufferSize = 65536;
MaxLineLength = 512;
{Write the UTF-8 BOM in Delphi versions that support UTF-8 conversion.}
LogStateHeaderMsg = {$ifdef BCB6OrDelphi7AndUp}#$EF#$BB#$BF + {$endif}
'FastMM State Capture:'#13#10'---------------------'#13#10#13#10;
LogStateAllocatedMsg = 'K Allocated'#13#10;
LogStateOverheadMsg = 'K Overhead'#13#10;
LogStateEfficiencyMsg = '% Efficiency'#13#10#13#10'Usage Detail:'#13#10;
LogStateAdditionalInfoMsg = #13#10'Additional Information:'#13#10'-----------------------'#13#10;
var
LPLogInfo: PMemoryLogInfo;
LInd: Integer;
LPNode: PMemoryLogNode;
LMsgBuffer: array[0..MsgBufferSize - 1] of AnsiChar;
LPMsg: PAnsiChar;
LBufferSpaceUsed, LBytesWritten: Cardinal;
LFileHandle: NativeUInt;
LMemoryManagerUsageSummary: TMemoryManagerUsageSummary;
LUTF8Str: AnsiString;
begin
{Get the current memory manager usage summary.}
GetMemoryManagerUsageSummary(LMemoryManagerUsageSummary);
{Allocate the memory required to capture detailed allocation information.}
LPLogInfo := VirtualAlloc(nil, SizeOf(TMemoryLogInfo), MEM_COMMIT or MEM_TOP_DOWN, PAGE_READWRITE);
if LPLogInfo <> nil then
begin
try
{Log all allocated blocks by class.}
WalkAllocatedBlocks(LogMemoryManagerStateCallBack, LPLogInfo);
{Sort the classes by total memory usage: Do the initial QuickSort pass over the list to sort the list in groups
of QuickSortMinimumItemsInPartition size.}
if LPLogInfo.NodeCount >= QuickSortMinimumItemsInPartition then
QuickSortLogNodes(@LPLogInfo.Nodes[0], LPLogInfo.NodeCount - 1);
{Do the final InsertionSort pass.}
InsertionSortLogNodes(@LPLogInfo.Nodes[0], LPLogInfo.NodeCount - 1);
{Create the output file}
{$ifdef POSIX}
lFileHandle := FileCreate(AFilename);
{$else}
LFileHandle := CreateFile(PChar(AFilename), GENERIC_READ or GENERIC_WRITE, 0,
nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
{$endif}
if LFileHandle <> INVALID_HANDLE_VALUE then
begin
try
{Log the usage summary}
LPMsg := @LMsgBuffer;
LPMsg := AppendStringToBuffer(LogStateHeaderMsg, LPMsg, Length(LogStateHeaderMsg));
LPMsg := NativeUIntToStrBuf(LMemoryManagerUsageSummary.AllocatedBytes shr 10, LPMsg);
LPMsg := AppendStringToBuffer(LogStateAllocatedMsg, LPMsg, Length(LogStateAllocatedMsg));
LPMsg := NativeUIntToStrBuf(LMemoryManagerUsageSummary.OverheadBytes shr 10, LPMsg);
LPMsg := AppendStringToBuffer(LogStateOverheadMsg, LPMsg, Length(LogStateOverheadMsg));
LPMsg := NativeUIntToStrBuf(Round(LMemoryManagerUsageSummary.EfficiencyPercentage), LPMsg);
LPMsg := AppendStringToBuffer(LogStateEfficiencyMsg, LPMsg, Length(LogStateEfficiencyMsg));
{Log the allocation detail}
for LInd := LPLogInfo.NodeCount - 1 downto 0 do
begin
LPNode := @LPLogInfo.Nodes[LInd];
{Add the allocated size}
LPMsg^ := ' ';
Inc(LPMsg);
LPMsg := NativeUIntToStrBuf(LPNode.TotalMemoryUsage, LPMsg);
LPMsg := AppendStringToBuffer(BytesMessage, LPMsg, Length(BytesMessage));
{Add the class type}
case NativeInt(LPNode.ClassPtr) of
{Unknown}
0:
begin
LPMsg := AppendStringToBuffer(UnknownClassNameMsg, LPMsg, Length(UnknownClassNameMsg));
end;
{AnsiString}
1:
begin
LPMsg := AppendStringToBuffer(AnsiStringBlockMessage, LPMsg, Length(AnsiStringBlockMessage));
end;
{UnicodeString}
2:
begin
LPMsg := AppendStringToBuffer(UnicodeStringBlockMessage, LPMsg, Length(UnicodeStringBlockMessage));
end;
{Classes}
else
begin
LPMsg := AppendClassNameToBuffer(LPNode.ClassPtr, LPMsg);
end;
end;
{Add the count}
LPMsg^ := ' ';
Inc(LPMsg);
LPMsg^ := 'x';
Inc(LPMsg);
LPMsg^ := ' ';
Inc(LPMsg);
LPMsg := NativeUIntToStrBuf(LPNode.InstanceCount, LPMsg);
LPMsg^ := #13;
Inc(LPMsg);
LPMsg^ := #10;
Inc(LPMsg);
{Flush the buffer?}
LBufferSpaceUsed := NativeInt(LPMsg) - NativeInt(@LMsgBuffer);
if LBufferSpaceUsed > (MsgBufferSize - MaxLineLength) then
begin
WriteFile(LFileHandle, LMsgBuffer, LBufferSpaceUsed, LBytesWritten, nil);
LPMsg := @LMsgBuffer;
end;
end;
if AAdditionalDetails <> '' then
LPMsg := AppendStringToBuffer(LogStateAdditionalInfoMsg, LPMsg, Length(LogStateAdditionalInfoMsg));
{Flush any remaining bytes}
LBufferSpaceUsed := NativeInt(LPMsg) - NativeInt(@LMsgBuffer);
if LBufferSpaceUsed > 0 then
WriteFile(LFileHandle, LMsgBuffer, LBufferSpaceUsed, LBytesWritten, nil);
{Write the additional info}
if AAdditionalDetails <> '' then
begin
{$ifdef BCB6OrDelphi7AndUp}
LUTF8Str := UTF8Encode(AAdditionalDetails);
{$else}
LUTF8Str := AAdditionalDetails;
{$endif}
WriteFile(LFileHandle, LUTF8Str[1], Length(LUTF8Str), LBytesWritten, nil);
end;
{Success}
Result := True;
finally
{Close the file}
{$ifdef POSIX}
__close(LFileHandle)
{$else}
CloseHandle(LFileHandle);
{$endif}
end;
end
else
Result := False;
finally
VirtualFree(LPLogInfo, 0, MEM_RELEASE);
end;
end
else
Result := False;
end;
{-----------CheckBlocksOnShutdown implementation------------}
{Checks blocks for modification after free and also for memory leaks}
procedure CheckBlocksOnShutdown(ACheckForLeakedBlocks: Boolean);
{$ifdef EnableMemoryLeakReporting}
type
{Leaked class type}
TLeakedClass = record
ClassPointer: TClass;
{$ifdef CheckCppObjectTypeEnabled}
CppTypeIdPtr: Pointer;
{$endif}
NumLeaks: Cardinal;
end;
TLeakedClasses = array[0..255] of TLeakedClass;
PLeakedClasses = ^TLeakedClasses;
{Leak statistics for a small block type}
TSmallBlockLeaks = array[0..NumSmallBlockTypes - 1] of TLeakedClasses;
{A leaked medium or large block}
TMediumAndLargeBlockLeaks = array[0..4095] of NativeUInt;
{$endif}
var
{$ifdef EnableMemoryLeakReporting}
{The leaked classes for small blocks}
LSmallBlockLeaks: TSmallBlockLeaks;
LLeakType: TMemoryLeakType;
{$ifdef CheckCppObjectTypeEnabled}
LLeakedCppTypeIdPtr: Pointer;
LCppTypeName: PAnsiChar;
{$endif}
LMediumAndLargeBlockLeaks: TMediumAndLargeBlockLeaks;
LNumMediumAndLargeLeaks: Integer;
LPLargeBlock: PLargeBlockHeader;
LLeakMessage: array[0..32767] of AnsiChar;
{$ifndef NoMessageBoxes}
LMessageTitleBuffer: array[0..1023] of AnsiChar;
{$endif}
LMsgPtr: PAnsiChar;
LExpectedLeaksOnly, LSmallLeakHeaderAdded, LBlockSizeHeaderAdded: Boolean;
LBlockTypeInd, LClassInd, LBlockInd: Cardinal;
LMediumBlockSize, LPreviousBlockSize, LLargeBlockSize, LThisBlockSize: NativeUInt;
{$endif}
LPMediumBlock: Pointer;
LPMediumBlockPoolHeader: PMediumBlockPoolHeader;
LMediumBlockHeader: NativeUInt;
{$ifdef EnableMemoryLeakReporting}
{Tries to account for a memory leak. Returns true if the leak is expected and
removes the leak from the list}
function GetMemoryLeakType(AAddress: Pointer; ASpaceInsideBlock: NativeUInt): TMemoryLeakType;
var
LLeak: TExpectedMemoryLeak;
begin
{Default to not found}
Result := mltUnexpectedLeak;
if ExpectedMemoryLeaks <> nil then
begin
{Check by pointer address}
LLeak.LeakAddress := AAddress;
LLeak.LeakedClass := nil;
{$ifdef CheckCppObjectTypeEnabled}
LLeak.LeakedCppTypeIdPtr := nil;
{$endif}
LLeak.LeakSize := 0;
LLeak.LeakCount := -1;
if UpdateExpectedLeakList(@ExpectedMemoryLeaks.FirstEntryByAddress, @LLeak, False) then
begin
Result := mltExpectedLeakRegisteredByPointer;
Exit;
end;
{Check by class}
LLeak.LeakAddress := nil;
{$ifdef FullDebugMode}
LLeak.LeakedClass := TClass(PNativeUInt(PByte(AAddress)+ SizeOf(TFullDebugBlockHeader))^);
{$else}
LLeak.LeakedClass := TClass(PNativeUInt(AAddress)^);
{$endif}
{$ifdef CheckCppObjectTypeEnabled}
if Assigned(GetCppVirtObjTypeIdPtrFunc) then
begin
{$ifdef FullDebugMode}
LLeak.LeakedCppTypeIdPtr := GetCppVirtObjTypeIdPtrFunc(Pointer(PByte(AAddress)
+ SizeOf(TFullDebugBlockHeader)), ASpaceInsideBlock);
{$else}
LLeak.LeakedCppTypeIdPtr := GetCppVirtObjTypeIdPtrFunc(AAddress, ASpaceInsideBlock);
{$endif}
end;
LLeakedCppTypeIdPtr := LLeak.LeakedCppTypeIdPtr;
{$endif}
LLeak.LeakSize := ASpaceInsideBlock;
if UpdateExpectedLeakList(@ExpectedMemoryLeaks.FirstEntryByClass, @LLeak, False) then
begin
Result := mltExpectedLeakRegisteredByClass;
Exit;
end;
{Check by size: the block must be large enough to hold the leak}
LLeak.LeakedClass := nil;
if UpdateExpectedLeakList(@ExpectedMemoryLeaks.FirstEntryBySizeOnly, @LLeak, False) then
Result := mltExpectedLeakRegisteredBySize;
end;
end;
{Checks the small block pool for leaks.}
procedure CheckSmallBlockPoolForLeaks(APSmallBlockPool: PSmallBlockPoolHeader);
var
LLeakedClass: TClass;
{$ifdef CheckCppObjectTypeEnabled}
LLeakedCppObjectTypeId: Pointer;
{$endif}
LSmallBlockLeakType: TMemoryLeakType;
LClassIndex: Integer;
LCurPtr, LEndPtr, LDataPtr: Pointer;
LBlockTypeIndex: Cardinal;
LPLeakedClasses: PLeakedClasses;
LSmallBlockSize: Cardinal;
begin
{Get the useable size inside a block}
LSmallBlockSize := APSmallBlockPool.BlockType.BlockSize - BlockHeaderSize;
{$ifdef FullDebugMode}
Dec(LSmallBlockSize, FullDebugBlockOverhead);
{$endif}
{Get the block type index}
LBlockTypeIndex := (UIntPtr(APSmallBlockPool.BlockType) - UIntPtr(@SmallBlockTypes[0])) div SizeOf(TSmallBlockType);
LPLeakedClasses := @LSmallBlockLeaks[LBlockTypeIndex];
{Get the first and last pointer for the pool}
GetFirstAndLastSmallBlockInPool(APSmallBlockPool, LCurPtr, LEndPtr);
{Step through all blocks}
while UIntPtr(LCurPtr) <= UIntPtr(LEndPtr) do
begin
{Is this block in use? If so, is the debug info intact?}
if ((PNativeUInt(PByte(LCurPtr) - BlockHeaderSize)^ and IsFreeBlockFlag) = 0) then
begin
{$ifdef FullDebugMode}
if CheckBlockBeforeFreeOrRealloc(LCurPtr, boBlockCheck) then
{$endif}
begin
{$ifdef CheckCppObjectTypeEnabled}
LLeakedCppTypeIdPtr := nil;
{$endif}
{Get the leak type}
LSmallBlockLeakType := GetMemoryLeakType(LCurPtr, LSmallBlockSize);
{$ifdef LogMemoryLeakDetailToFile}
{$ifdef HideExpectedLeaksRegisteredByPointer}
if LSmallBlockLeakType <> mltExpectedLeakRegisteredByPointer then
{$endif}
LogMemoryLeakOrAllocatedBlock(LCurPtr, True);
{$endif}
{Only expected leaks?}
LExpectedLeaksOnly := LExpectedLeaksOnly and (LSmallBlockLeakType <> mltUnexpectedLeak);
{$ifdef HideExpectedLeaksRegisteredByPointer}
if LSmallBlockLeakType <> mltExpectedLeakRegisteredByPointer then
{$endif}
begin
{Get a pointer to the user data}
{$ifndef FullDebugMode}
LDataPtr := LCurPtr;
{$else}
LDataPtr := Pointer(PByte(LCurPtr) + SizeOf(TFullDebugBlockHeader));
{$endif}
{Default to an unknown block}
LClassIndex := 0;
{Get the class contained by the block}
LLeakedClass := DetectClassInstance(LDataPtr);
{Not a Delphi class? -> is it perhaps a string or C++ object type?}
if LLeakedClass = nil then
begin
{$ifdef CheckCppObjectTypeEnabled}
LLeakedCppObjectTypeId := LLeakedCppTypeIdPtr;
if (LLeakedCppObjectTypeId = nil) and (ExpectedMemoryLeaks = nil) then
begin
if Assigned(GetCppVirtObjTypeIdPtrFunc) then
begin
LLeakedCppObjectTypeId := GetCppVirtObjTypeIdPtrFunc(LDataPtr, LSmallBlockSize);
end;
end;
if Assigned(LLeakedCppObjectTypeId) then
begin
LClassIndex := 3;
while LClassIndex <= High(TLeakedClasses) do
begin
if (Pointer(LPLeakedClasses[LClassIndex].CppTypeIdPtr) = LLeakedCppObjectTypeId)
or ((LPLeakedClasses[LClassIndex].CppTypeIdPtr = nil)
and (LPLeakedClasses[LClassIndex].ClassPointer = nil)) then
begin
Break;
end;
Inc(LClassIndex);
end;
if LClassIndex <= High(TLeakedClasses) then
Pointer(LPLeakedClasses[LClassIndex].CppTypeIdPtr) := LLeakedCppObjectTypeId
else
LClassIndex := 0;
end
else
begin
{$endif}
{Not a known class: Is it perhaps string data?}
case DetectStringData(LDataPtr, APSmallBlockPool.BlockType.BlockSize - (BlockHeaderSize {$ifdef FullDebugMode} + FullDebugBlockOverhead{$endif})) of
stAnsiString: LClassIndex := 1;
stUnicodeString: LClassIndex := 2;
end;
{$ifdef CheckCppObjectTypeEnabled}
end;
{$endif}
end
else
begin
LClassIndex := 3;
while LClassIndex <= High(TLeakedClasses) do
begin
if (LPLeakedClasses[LClassIndex].ClassPointer = LLeakedClass)
or ((LPLeakedClasses[LClassIndex].ClassPointer = nil)
{$ifdef CheckCppObjectTypeEnabled}
and (LPLeakedClasses[LClassIndex].CppTypeIdPtr = nil)
{$endif}
) then
begin
Break;
end;
Inc(LClassIndex);
end;
if LClassIndex <= High(TLeakedClasses) then
LPLeakedClasses[LClassIndex].ClassPointer := LLeakedClass
else
LClassIndex := 0;
end;
{Add to the number of leaks for the class}
Inc(LPLeakedClasses[LClassIndex].NumLeaks);
end;
end;
end
else
begin
{$ifdef CheckUseOfFreedBlocksOnShutdown}
{Check that the block has not been modified since being freed}
CheckFreeBlockUnmodified(LCurPtr, APSmallBlockPool.BlockType.BlockSize, boBlockCheck);
{$endif}
end;
{Next block}
Inc(PByte(LCurPtr), APSmallBlockPool.BlockType.BlockSize);
end;
end;
{$endif}
begin
{$ifdef EnableMemoryLeakReporting}
{Clear the leak arrays}
FillChar(LSmallBlockLeaks, SizeOf(LSmallBlockLeaks), 0);
FillChar(LMediumAndLargeBlockLeaks, SizeOf(LMediumAndLargeBlockLeaks), 0);
{Step through all the medium block pools}
LNumMediumAndLargeLeaks := 0;
{No unexpected leaks so far}
LExpectedLeaksOnly := True;
{$endif}
{Step through all the medium block pools}
LPMediumBlockPoolHeader := MediumBlockPoolsCircularList.NextMediumBlockPoolHeader;
while LPMediumBlockPoolHeader <> @MediumBlockPoolsCircularList do
begin
LPMediumBlock := GetFirstMediumBlockInPool(LPMediumBlockPoolHeader);
while LPMediumBlock <> nil do
begin
LMediumBlockHeader := PNativeUInt(PByte(LPMediumBlock) - BlockHeaderSize)^;
{Is the block in use?}
if LMediumBlockHeader and IsFreeBlockFlag = 0 then
begin
{$ifdef EnableMemoryLeakReporting}
if ACheckForLeakedBlocks then
begin
if (LMediumBlockHeader and IsSmallBlockPoolInUseFlag) <> 0 then
begin
{Get all the leaks for the small block pool}
CheckSmallBlockPoolForLeaks(LPMediumBlock);
end
else
begin
if (LNumMediumAndLargeLeaks < Length(LMediumAndLargeBlockLeaks))
{$ifdef FullDebugMode}
and CheckBlockBeforeFreeOrRealloc(LPMediumBlock, boBlockCheck)
{$endif}
then
begin
LMediumBlockSize := (LMediumBlockHeader and DropMediumAndLargeFlagsMask) - BlockHeaderSize;
{$ifdef FullDebugMode}
Dec(LMediumBlockSize, FullDebugBlockOverhead);
{$endif}
{Get the leak type}
LLeakType := GetMemoryLeakType(LPMediumBlock, LMediumBlockSize);
{Is it an expected leak?}
LExpectedLeaksOnly := LExpectedLeaksOnly and (LLeakType <> mltUnexpectedLeak);
{$ifdef LogMemoryLeakDetailToFile}
{$ifdef HideExpectedLeaksRegisteredByPointer}
if LLeakType <> mltExpectedLeakRegisteredByPointer then
{$endif}
LogMemoryLeakOrAllocatedBlock(LPMediumBlock, True);
{$endif}
{$ifdef HideExpectedLeaksRegisteredByPointer}
if LLeakType <> mltExpectedLeakRegisteredByPointer then
{$endif}
begin
{Add the leak to the list}
LMediumAndLargeBlockLeaks[LNumMediumAndLargeLeaks] := LMediumBlockSize;
Inc(LNumMediumAndLargeLeaks);
end;
end;
end;
end;
{$endif}
end
else
begin
{$ifdef CheckUseOfFreedBlocksOnShutdown}
{Check that the block has not been modified since being freed}
CheckFreeBlockUnmodified(LPMediumBlock, LMediumBlockHeader and DropMediumAndLargeFlagsMask, boBlockCheck);
{$endif}
end;
{Next medium block}
LPMediumBlock := NextMediumBlock(LPMediumBlock);
end;
{Get the next medium block pool}
LPMediumBlockPoolHeader := LPMediumBlockPoolHeader.NextMediumBlockPoolHeader;
end;
{$ifdef EnableMemoryLeakReporting}
if ACheckForLeakedBlocks then
begin
{Get all leaked large blocks}
LPLargeBlock := LargeBlocksCircularList.NextLargeBlockHeader;
while LPLargeBlock <> @LargeBlocksCircularList do
begin
if (LNumMediumAndLargeLeaks < length(LMediumAndLargeBlockLeaks))
{$ifdef FullDebugMode}
and CheckBlockBeforeFreeOrRealloc(Pointer(PByte(LPLargeBlock) + LargeBlockHeaderSize), boBlockCheck)
{$endif}
then
begin
LLargeBlockSize := (LPLargeBlock.BlockSizeAndFlags and DropMediumAndLargeFlagsMask) - BlockHeaderSize - LargeBlockHeaderSize;
{$ifdef FullDebugMode}
Dec(LLargeBlockSize, FullDebugBlockOverhead);
{$endif}
{Get the leak type}
LLeakType := GetMemoryLeakType(Pointer(PByte(LPLargeBlock) + LargeBlockHeaderSize), LLargeBlockSize);
{Is it an expected leak?}
LExpectedLeaksOnly := LExpectedLeaksOnly and (LLeakType <> mltUnexpectedLeak);
{$ifdef LogMemoryLeakDetailToFile}
{$ifdef HideExpectedLeaksRegisteredByPointer}
if LLeakType <> mltExpectedLeakRegisteredByPointer then
{$endif}
LogMemoryLeakOrAllocatedBlock(Pointer(PByte(LPLargeBlock) + LargeBlockHeaderSize), True);
{$endif}
{$ifdef HideExpectedLeaksRegisteredByPointer}
if LLeakType <> mltExpectedLeakRegisteredByPointer then
{$endif}
begin
{Add the leak}
LMediumAndLargeBlockLeaks[LNumMediumAndLargeLeaks] := LLargeBlockSize;
Inc(LNumMediumAndLargeLeaks);
end;
end;
{Get the next large block}
LPLargeBlock := LPLargeBlock.NextLargeBlockHeader;
end;
{Display the leak message if required}
if not LExpectedLeaksOnly then
begin
{Small leak header has not been added}
LSmallLeakHeaderAdded := False;
LPreviousBlockSize := 0;
{Set up the leak message header so long}
LMsgPtr := AppendStringToBuffer(LeakMessageHeader, @LLeakMessage[0], length(LeakMessageHeader));
{Step through all the small block types}
for LBlockTypeInd := 0 to NumSmallBlockTypes - 1 do
begin
LThisBlockSize := SmallBlockTypes[LBlockTypeInd].BlockSize - BlockHeaderSize;
{$ifdef FullDebugMode}
Dec(LThisBlockSize, FullDebugBlockOverhead);
if NativeInt(LThisBlockSize) < 0 then
LThisBlockSize := 0;
{$endif}
LBlockSizeHeaderAdded := False;
{Any leaks?}
for LClassInd := High(LSmallBlockLeaks[LBlockTypeInd]) downto 0 do
begin
{Is there still space in the message buffer? Reserve space for the message
footer.}
if LMsgPtr > @LLeakMessage[High(LLeakMessage) - 2048] then
Break;
{Check the count}
if LSmallBlockLeaks[LBlockTypeInd][LClassInd].NumLeaks > 0 then
begin
{Need to add the header?}
if not LSmallLeakHeaderAdded then
begin
LMsgPtr := AppendStringToBuffer(SmallLeakDetail, LMsgPtr, Length(SmallLeakDetail));
LSmallLeakHeaderAdded := True;
end;
{Need to add the size header?}
if not LBlockSizeHeaderAdded then
begin
LMsgPtr^ := #13;
Inc(LMsgPtr);
LMsgPtr^ := #10;
Inc(LMsgPtr);
LMsgPtr := NativeUIntToStrBuf(LPreviousBlockSize + 1, LMsgPtr);
LMsgPtr^ := ' ';
Inc(LMsgPtr);
LMsgPtr^ := '-';
Inc(LMsgPtr);
LMsgPtr^ := ' ';
Inc(LMsgPtr);
LMsgPtr := NativeUIntToStrBuf(LThisBlockSize, LMsgPtr);
LMsgPtr := AppendStringToBuffer(BytesMessage, LMsgPtr, Length(BytesMessage));
LBlockSizeHeaderAdded := True;
end
else
begin
LMsgPtr^ := ',';
Inc(LMsgPtr);
LMsgPtr^ := ' ';
Inc(LMsgPtr);
end;
{Show the count}
case LClassInd of
{Unknown}
0:
begin
LMsgPtr := AppendStringToBuffer(UnknownClassNameMsg, LMsgPtr, Length(UnknownClassNameMsg));
end;
{AnsiString}
1:
begin
LMsgPtr := AppendStringToBuffer(AnsiStringBlockMessage, LMsgPtr, Length(AnsiStringBlockMessage));
end;
{UnicodeString}
2:
begin
LMsgPtr := AppendStringToBuffer(UnicodeStringBlockMessage, LMsgPtr, Length(UnicodeStringBlockMessage));
end;
{Classes}
else
begin
{$ifdef CheckCppObjectTypeEnabled}
if LSmallBlockLeaks[LBlockTypeInd][LClassInd].CppTypeIdPtr <> nil then
begin
if Assigned(GetCppVirtObjTypeNameByTypeIdPtrFunc) then
begin
LCppTypeName := GetCppVirtObjTypeNameByTypeIdPtrFunc(LSmallBlockLeaks[LBlockTypeInd][LClassInd].CppTypeIdPtr);
LMsgPtr := AppendStringToBuffer(LCppTypeName, LMsgPtr, StrLen(LCppTypeName));
end
else
LMsgPtr := AppendClassNameToBuffer(nil, LMsgPtr);
end
else
begin
{$endif}
LMsgPtr := AppendClassNameToBuffer(LSmallBlockLeaks[LBlockTypeInd][LClassInd].ClassPointer, LMsgPtr);
{$ifdef CheckCppObjectTypeEnabled}
end;
{$endif}
end;
end;
{Add the count}
LMsgPtr^ := ' ';
Inc(LMsgPtr);
LMsgPtr^ := 'x';
Inc(LMsgPtr);
LMsgPtr^ := ' ';
Inc(LMsgPtr);
LMsgPtr := NativeUIntToStrBuf(LSmallBlockLeaks[LBlockTypeInd][LClassInd].NumLeaks, LMsgPtr);
end;
end;
LPreviousBlockSize := LThisBlockSize;
end;
{Add the medium/large block leak message}
if LNumMediumAndLargeLeaks > 0 then
begin
{Any non-small leaks?}
if LSmallLeakHeaderAdded then
begin
LMsgPtr^ := #13;
Inc(LMsgPtr);
LMsgPtr^ := #10;
Inc(LMsgPtr);
LMsgPtr^ := #13;
Inc(LMsgPtr);
LMsgPtr^ := #10;
Inc(LMsgPtr);
end;
{Add the medium/large block leak message}
LMsgPtr := AppendStringToBuffer(LargeLeakDetail, LMsgPtr, Length(LargeLeakDetail));
{List all the blocks}
for LBlockInd := 0 to LNumMediumAndLargeLeaks - 1 do
begin
if LBlockInd <> 0 then
begin
LMsgPtr^ := ',';
Inc(LMsgPtr);
LMsgPtr^ := ' ';
Inc(LMsgPtr);
end;
LMsgPtr := NativeUIntToStrBuf(LMediumAndLargeBlockLeaks[LBlockInd], LMsgPtr);
{Is there still space in the message buffer? Reserve space for the
message footer.}
if LMsgPtr > @LLeakMessage[High(LLeakMessage) - 2048] then
Break;
end;
end;
{$ifdef LogErrorsToFile}
{Set the message footer}
LMsgPtr := AppendStringToBuffer(LeakMessageFooter, LMsgPtr, Length(LeakMessageFooter));
{Append the message to the memory errors file}
AppendEventLog(@LLeakMessage[0], UIntPtr(LMsgPtr) - UIntPtr(@LLeakMessage[1]));
{$else}
{Set the message footer}
AppendStringToBuffer(LeakMessageFooter, LMsgPtr, Length(LeakMessageFooter));
{$endif}
{$ifdef UseOutputDebugString}
OutputDebugStringA(LLeakMessage);
{$endif}
{$ifndef NoMessageBoxes}
{Show the message}
AppendStringToModuleName(LeakMessageTitle, LMessageTitleBuffer);
ShowMessageBox(LLeakMessage, LMessageTitleBuffer);
{$endif}
end;
end;
{$endif}
end;
{Returns statistics about the current state of the memory manager}
procedure GetMemoryManagerState(var AMemoryManagerState: TMemoryManagerState);
var
LPMediumBlockPoolHeader: PMediumBlockPoolHeader;
LPMediumBlock: Pointer;
LInd: Integer;
LBlockTypeIndex, LMediumBlockSize: Cardinal;
LMediumBlockHeader, LLargeBlockSize: NativeUInt;
LPLargeBlock: PLargeBlockHeader;
begin
{Clear the structure}
FillChar(AMemoryManagerState, SizeOf(AMemoryManagerState), 0);
{Set the small block size stats}
for LInd := 0 to NumSmallBlockTypes - 1 do
begin
AMemoryManagerState.SmallBlockTypeStates[LInd].InternalBlockSize :=
SmallBlockTypes[LInd].BlockSize;
AMemoryManagerState.SmallBlockTypeStates[LInd].UseableBlockSize :=
SmallBlockTypes[LInd].BlockSize - BlockHeaderSize{$ifdef FullDebugMode} - FullDebugBlockOverhead{$endif};
if NativeInt(AMemoryManagerState.SmallBlockTypeStates[LInd].UseableBlockSize) < 0 then
AMemoryManagerState.SmallBlockTypeStates[LInd].UseableBlockSize := 0;
end;
{Lock all small block types}
LockAllSmallBlockTypes;
{Lock the medium blocks}
LockMediumBlocks;
{Step through all the medium block pools}
LPMediumBlockPoolHeader := MediumBlockPoolsCircularList.NextMediumBlockPoolHeader;
while LPMediumBlockPoolHeader <> @MediumBlockPoolsCircularList do
begin
{Add to the medium block used space}
Inc(AMemoryManagerState.ReservedMediumBlockAddressSpace, MediumBlockPoolSize);
LPMediumBlock := GetFirstMediumBlockInPool(LPMediumBlockPoolHeader);
while LPMediumBlock <> nil do
begin
LMediumBlockHeader := PNativeUInt(PByte(LPMediumBlock) - BlockHeaderSize)^;
{Is the block in use?}
if LMediumBlockHeader and IsFreeBlockFlag = 0 then
begin
{Get the block size}
LMediumBlockSize := LMediumBlockHeader and DropMediumAndLargeFlagsMask;
if (LMediumBlockHeader and IsSmallBlockPoolInUseFlag) <> 0 then
begin
{Get the block type index}
LBlockTypeIndex := (UIntPtr(PSmallBlockPoolHeader(LPMediumBlock).BlockType) - UIntPtr(@SmallBlockTypes[0])) div SizeOf(TSmallBlockType);
{Subtract from medium block usage}
Dec(AMemoryManagerState.ReservedMediumBlockAddressSpace, LMediumBlockSize);
{Add it to the reserved space for the block size}
Inc(AMemoryManagerState.SmallBlockTypeStates[LBlockTypeIndex].ReservedAddressSpace, LMediumBlockSize);
{Add the usage for the pool}
Inc(AMemoryManagerState.SmallBlockTypeStates[LBlockTypeIndex].AllocatedBlockCount,
PSmallBlockPoolHeader(LPMediumBlock).BlocksInUse);
end
else
begin
{$ifdef FullDebugMode}
Dec(LMediumBlockSize, FullDebugBlockOverhead);
{$endif}
Inc(AMemoryManagerState.AllocatedMediumBlockCount);
Inc(AMemoryManagerState.TotalAllocatedMediumBlockSize, LMediumBlockSize - BlockHeaderSize);
end;
end;
{Next medium block}
LPMediumBlock := NextMediumBlock(LPMediumBlock);
end;
{Get the next medium block pool}
LPMediumBlockPoolHeader := LPMediumBlockPoolHeader.NextMediumBlockPoolHeader;
end;
{Unlock medium blocks}
MediumBlocksLocked := False;
{Unlock all the small block types}
for LInd := 0 to NumSmallBlockTypes - 1 do
SmallBlockTypes[LInd].BlockTypeLocked := False;
{Step through all the large blocks}
LockLargeBlocks;
LPLargeBlock := LargeBlocksCircularList.NextLargeBlockHeader;
while LPLargeBlock <> @LargeBlocksCircularList do
begin
LLargeBlockSize := LPLargeBlock.BlockSizeAndFlags and DropMediumAndLargeFlagsMask;
Inc(AMemoryManagerState.AllocatedLargeBlockCount);
Inc(AMemoryManagerState.ReservedLargeBlockAddressSpace, LLargeBlockSize);
Inc(AMemoryManagerState.TotalAllocatedLargeBlockSize, LPLargeBlock.UserAllocatedSize);
{Get the next large block}
LPLargeBlock := LPLargeBlock.NextLargeBlockHeader;
end;
LargeBlocksLocked := False;
end;
{Returns a summary of the information returned by GetMemoryManagerState}
procedure GetMemoryManagerUsageSummary(
var AMemoryManagerUsageSummary: TMemoryManagerUsageSummary);
var
LMMS: TMemoryManagerState;
LAllocatedBytes, LReservedBytes: NativeUInt;
LSBTIndex: Integer;
begin
{Get the memory manager state}
GetMemoryManagerState(LMMS);
{Add up the totals}
LAllocatedBytes := LMMS.TotalAllocatedMediumBlockSize
+ LMMS.TotalAllocatedLargeBlockSize;
LReservedBytes := LMMS.ReservedMediumBlockAddressSpace
+ LMMS.ReservedLargeBlockAddressSpace;
for LSBTIndex := 0 to NumSmallBlockTypes - 1 do
begin
Inc(LAllocatedBytes, LMMS.SmallBlockTypeStates[LSBTIndex].UseableBlockSize
* LMMS.SmallBlockTypeStates[LSBTIndex].AllocatedBlockCount);
Inc(LReservedBytes, LMMS.SmallBlockTypeStates[LSBTIndex].ReservedAddressSpace);
end;
{Set the structure values}
AMemoryManagerUsageSummary.AllocatedBytes := LAllocatedBytes;
AMemoryManagerUsageSummary.OverheadBytes := LReservedBytes - LAllocatedBytes;
if LReservedBytes > 0 then
begin
AMemoryManagerUsageSummary.EfficiencyPercentage :=
LAllocatedBytes / LReservedBytes * 100;
end
else
AMemoryManagerUsageSummary.EfficiencyPercentage := 100;
end;
{$ifndef POSIX}
{Gets the state of every 64K block in the 4GB address space. Under 64-bit this
returns only the state for the low 4GB.}
procedure GetMemoryMap(var AMemoryMap: TMemoryMap);
var
LPMediumBlockPoolHeader: PMediumBlockPoolHeader;
LPLargeBlock: PLargeBlockHeader;
LInd, LChunkIndex, LNextChunk, LLargeBlockSize: NativeUInt;
LMBI: TMemoryBasicInformation;
begin
{Clear the map}
FillChar(AMemoryMap, SizeOf(AMemoryMap), Ord(csUnallocated));
{Step through all the medium block pools}
LockMediumBlocks;
LPMediumBlockPoolHeader := MediumBlockPoolsCircularList.NextMediumBlockPoolHeader;
while LPMediumBlockPoolHeader <> @MediumBlockPoolsCircularList do
begin
{Add to the medium block used space}
LChunkIndex := NativeUInt(LPMediumBlockPoolHeader) shr 16;
for LInd := 0 to (MediumBlockPoolSize - 1) shr 16 do
begin
if (LChunkIndex + LInd) > High(AMemoryMap) then
Break;
AMemoryMap[LChunkIndex + LInd] := csAllocated;
end;
{Get the next medium block pool}
LPMediumBlockPoolHeader := LPMediumBlockPoolHeader.NextMediumBlockPoolHeader;
end;
MediumBlocksLocked := False;
{Step through all the large blocks}
LockLargeBlocks;
LPLargeBlock := LargeBlocksCircularList.NextLargeBlockHeader;
while LPLargeBlock <> @LargeBlocksCircularList do
begin
LChunkIndex := UIntPtr(LPLargeBlock) shr 16;
LLargeBlockSize := LPLargeBlock.BlockSizeAndFlags and DropMediumAndLargeFlagsMask;
for LInd := 0 to (LLargeBlockSize - 1) shr 16 do
begin
if (LChunkIndex + LInd) > High(AMemoryMap) then
Break;
AMemoryMap[LChunkIndex + LInd] := csAllocated;
end;
{Get the next large block}
LPLargeBlock := LPLargeBlock.NextLargeBlockHeader;
end;
LargeBlocksLocked := False;
{Fill in the rest of the map}
LInd := 0;
while LInd <= 65535 do
begin
{If the chunk is not allocated by this MM, what is its status?}
if AMemoryMap[LInd] = csUnallocated then
begin
{Query the address space starting at the chunk boundary}
if VirtualQuery(Pointer(LInd * 65536), LMBI, SizeOf(LMBI)) = 0 then
begin
{VirtualQuery may fail for addresses >2GB if a large address space is
not enabled.}
FillChar(AMemoryMap[LInd], 65536 - LInd, csSysReserved);
Break;
end;
{Get the chunk number after the region}
LNextChunk := (LMBI.RegionSize - 1) shr 16 + LInd + 1;
{Validate}
if LNextChunk > 65536 then
LNextChunk := 65536;
{Set the status of all the chunks in the region}
if LMBI.State = MEM_COMMIT then
begin
FillChar(AMemoryMap[LInd], LNextChunk - LInd, csSysAllocated);
end
else
begin
if LMBI.State = MEM_RESERVE then
FillChar(AMemoryMap[LInd], LNextChunk - LInd, csSysReserved);
end;
{Point to the start of the next chunk}
LInd := LNextChunk;
end
else
begin
{Next chunk}
Inc(LInd);
end;
end;
end;
{$endif}
{Returns summarised information about the state of the memory manager. (For
backward compatibility.)}
function FastGetHeapStatus: THeapStatus;
var
LPMediumBlockPoolHeader: PMediumBlockPoolHeader;
LPMediumBlock: Pointer;
LBlockTypeIndex, LMediumBlockSize: Cardinal;
LSmallBlockUsage, LSmallBlockOverhead, LMediumBlockHeader, LLargeBlockSize: NativeUInt;
LInd: Integer;
LPLargeBlock: PLargeBlockHeader;
begin
{Clear the structure}
FillChar(Result, SizeOf(Result), 0);
{Lock all small block types}
LockAllSmallBlockTypes;
{Lock the medium blocks}
LockMediumBlocks;
{Step through all the medium block pools}
LPMediumBlockPoolHeader := MediumBlockPoolsCircularList.NextMediumBlockPoolHeader;
while LPMediumBlockPoolHeader <> @MediumBlockPoolsCircularList do
begin
{Add to the total and committed address space}
Inc(Result.TotalAddrSpace, ((MediumBlockPoolSize + $ffff) and $ffff0000));
Inc(Result.TotalCommitted, ((MediumBlockPoolSize + $ffff) and $ffff0000));
{Add the medium block pool overhead}
Inc(Result.Overhead, (((MediumBlockPoolSize + $ffff) and $ffff0000)
- MediumBlockPoolSize + MediumBlockPoolHeaderSize));
{Get the first medium block in the pool}
LPMediumBlock := GetFirstMediumBlockInPool(LPMediumBlockPoolHeader);
while LPMediumBlock <> nil do
begin
{Get the block header}
LMediumBlockHeader := PNativeUInt(PByte(LPMediumBlock) - BlockHeaderSize)^;
{Get the block size}
LMediumBlockSize := LMediumBlockHeader and DropMediumAndLargeFlagsMask;
{Is the block in use?}
if LMediumBlockHeader and IsFreeBlockFlag = 0 then
begin
if (LMediumBlockHeader and IsSmallBlockPoolInUseFlag) <> 0 then
begin
{Get the block type index}
LBlockTypeIndex := (UIntPtr(PSmallBlockPoolHeader(LPMediumBlock).BlockType) - UIntPtr(@SmallBlockTypes[0])) div SizeOf(TSmallBlockType);
{Get the usage in the block}
LSmallBlockUsage := PSmallBlockPoolHeader(LPMediumBlock).BlocksInUse
* SmallBlockTypes[LBlockTypeIndex].BlockSize;
{Get the total overhead for all the small blocks}
LSmallBlockOverhead := PSmallBlockPoolHeader(LPMediumBlock).BlocksInUse
* (BlockHeaderSize{$ifdef FullDebugMode} + FullDebugBlockOverhead{$endif});
{Add to the totals}
Inc(Result.FreeSmall, LMediumBlockSize - LSmallBlockUsage - BlockHeaderSize);
Inc(Result.Overhead, LSmallBlockOverhead + BlockHeaderSize);
Inc(Result.TotalAllocated, LSmallBlockUsage - LSmallBlockOverhead);
end
else
begin
{$ifdef FullDebugMode}
Dec(LMediumBlockSize, FullDebugBlockOverhead);
Inc(Result.Overhead, FullDebugBlockOverhead);
{$endif}
{Add to the result}
Inc(Result.TotalAllocated, LMediumBlockSize - BlockHeaderSize);
Inc(Result.Overhead, BlockHeaderSize);
end;
end
else
begin
{The medium block is free}
Inc(Result.FreeBig, LMediumBlockSize);
end;
{Next medium block}
LPMediumBlock := NextMediumBlock(LPMediumBlock);
end;
{Get the next medium block pool}
LPMediumBlockPoolHeader := LPMediumBlockPoolHeader.NextMediumBlockPoolHeader;
end;
{Add the sequential feed unused space}
Inc(Result.Unused, MediumSequentialFeedBytesLeft);
{Unlock the medium blocks}
MediumBlocksLocked := False;
{Unlock all the small block types}
for LInd := 0 to NumSmallBlockTypes - 1 do
SmallBlockTypes[LInd].BlockTypeLocked := False;
{Step through all the large blocks}
LockLargeBlocks;
LPLargeBlock := LargeBlocksCircularList.NextLargeBlockHeader;
while LPLargeBlock <> @LargeBlocksCircularList do
begin
LLargeBlockSize := LPLargeBlock.BlockSizeAndFlags and DropMediumAndLargeFlagsMask;
Inc(Result.TotalAddrSpace, LLargeBlockSize);
Inc(Result.TotalCommitted, LLargeBlockSize);
Inc(Result.TotalAllocated, LPLargeBlock.UserAllocatedSize
{$ifdef FullDebugMode} - FullDebugBlockOverhead{$endif});
Inc(Result.Overhead, LLargeBlockSize - LPLargeBlock.UserAllocatedSize
{$ifdef FullDebugMode} + FullDebugBlockOverhead{$endif});
{Get the next large block}
LPLargeBlock := LPLargeBlock.NextLargeBlockHeader;
end;
LargeBlocksLocked := False;
{Set the total number of free bytes}
Result.TotalFree := Result.FreeSmall + Result.FreeBig + Result.Unused;
end;
{Frees all allocated memory. Does not support segmented large blocks (yet).}
procedure FreeAllMemory;
var
LPMediumBlockPoolHeader, LPNextMediumBlockPoolHeader: PMediumBlockPoolHeader;
LPMediumFreeBlock: PMediumFreeBlock;
LPLargeBlock, LPNextLargeBlock: PLargeBlockHeader;
LInd: Integer;
begin
{Free all block pools}
LPMediumBlockPoolHeader := MediumBlockPoolsCircularList.NextMediumBlockPoolHeader;
while LPMediumBlockPoolHeader <> @MediumBlockPoolsCircularList do
begin
{Get the next medium block pool so long}
LPNextMediumBlockPoolHeader := LPMediumBlockPoolHeader.NextMediumBlockPoolHeader;
{$ifdef ClearMediumBlockPoolsBeforeReturningToOS}
FillChar(LPMediumBlockPoolHeader^, MediumBlockPoolSize, 0);
{$else}
{$ifdef ClearSmallAndMediumBlocksInFreeMem}
FillChar(LPMediumBlockPoolHeader^, MediumBlockPoolSize, 0);
{$endif}
{$endif}
{Free this pool}
VirtualFree(LPMediumBlockPoolHeader, 0, MEM_RELEASE);
{Next pool}
LPMediumBlockPoolHeader := LPNextMediumBlockPoolHeader;
end;
{Clear all small block types}
for LInd := 0 to High(SmallBlockTypes) do
begin
SmallBlockTypes[Lind].PreviousPartiallyFreePool := @SmallBlockTypes[Lind];
SmallBlockTypes[Lind].NextPartiallyFreePool := @SmallBlockTypes[Lind];
SmallBlockTypes[Lind].NextSequentialFeedBlockAddress := Pointer(1);
SmallBlockTypes[Lind].MaxSequentialFeedBlockAddress := nil;
end;
{Clear all medium block pools}
MediumBlockPoolsCircularList.PreviousMediumBlockPoolHeader := @MediumBlockPoolsCircularList;
MediumBlockPoolsCircularList.NextMediumBlockPoolHeader := @MediumBlockPoolsCircularList;
{All medium bins are empty}
for LInd := 0 to High(MediumBlockBins) do
begin
LPMediumFreeBlock := @MediumBlockBins[LInd];
LPMediumFreeBlock.PreviousFreeBlock := LPMediumFreeBlock;
LPMediumFreeBlock.NextFreeBlock := LPMediumFreeBlock;
end;
MediumBlockBinGroupBitmap := 0;
FillChar(MediumBlockBinBitmaps, SizeOf(MediumBlockBinBitmaps), 0);
MediumSequentialFeedBytesLeft := 0;
{Free all large blocks}
LPLargeBlock := LargeBlocksCircularList.NextLargeBlockHeader;
while LPLargeBlock <> @LargeBlocksCircularList do
begin
{Get the next large block}
LPNextLargeBlock := LPLargeBlock.NextLargeBlockHeader;
{$ifdef ClearLargeBlocksBeforeReturningToOS}
FillChar(LPLargeBlock^,
LPLargeBlock.BlockSizeAndFlags and DropMediumAndLargeFlagsMask, 0);
{$endif}
{Free this large block}
VirtualFree(LPLargeBlock, 0, MEM_RELEASE);
{Next large block}
LPLargeBlock := LPNextLargeBlock;
end;
{There are no large blocks allocated}
LargeBlocksCircularList.PreviousLargeBlockHeader := @LargeBlocksCircularList;
LargeBlocksCircularList.NextLargeBlockHeader := @LargeBlocksCircularList;
end;
{----------------------------Memory Manager Setup-----------------------------}
{Checks that no other memory manager has been installed after the RTL MM and
that there are currently no live pointers allocated through the RTL MM.}
function CheckCanInstallMemoryManager: Boolean;
{$ifndef NoMessageBoxes}
var
LErrorMessageTitle: array[0..1023] of AnsiChar;
{$endif}
begin
{Default to error}
Result := False;
{$ifdef FullDebugMode}
{$ifdef LoadDebugDLLDynamically}
{$ifdef DoNotInstallIfDLLMissing}
{Should FastMM be installed only if the FastMM_FullDebugMode.dll file is
available?}
if FullDebugModeDLL = 0 then
Exit;
{$endif}
{$endif}
{$endif}
{Is FastMM already installed?}
if FastMMIsInstalled then
begin
{$ifdef UseOutputDebugString}
OutputDebugStringA(AlreadyInstalledMsg);
{$endif}
{$ifndef NoMessageBoxes}
AppendStringToModuleName(AlreadyInstalledTitle, LErrorMessageTitle);
ShowMessageBox(AlreadyInstalledMsg, LErrorMessageTitle);
{$endif}
Exit;
end;
{Has another MM been set, or has the Embarcadero MM been used? If so, this
file is not the first unit in the uses clause of the project's .dpr file.}
if IsMemoryManagerSet then
begin
{When using runtime packages, another library may already have installed
FastMM: Silently ignore the installation request.}
{$ifndef UseRuntimePackages}
{Another memory manager has been set.}
{$ifdef UseOutputDebugString}
OutputDebugStringA(OtherMMInstalledMsg);
{$endif}
{$ifndef NoMessageBoxes}
AppendStringToModuleName(OtherMMInstalledTitle, LErrorMessageTitle);
ShowMessageBox(OtherMMInstalledMsg, LErrorMessageTitle);
{$endif}
{$endif}
Exit;
end;
{$ifndef POSIX}
if GetHeapStatus.TotalAllocated <> 0 then
begin
{Memory has been already been allocated with the RTL MM}
{$ifdef UseOutputDebugString}
OutputDebugStringA(MemoryAllocatedMsg);
{$endif}
{$ifndef NoMessageBoxes}
AppendStringToModuleName(MemoryAllocatedTitle, LErrorMessageTitle);
ShowMessageBox(MemoryAllocatedMsg, LErrorMessageTitle);
{$endif}
Exit;
end;
{$endif}
{All OK}
Result := True;
end;
{Initializes the lookup tables for the memory manager}
procedure InitializeMemoryManager;
const
{The size of the Inc(VMTIndex) code in TFreedObject.GetVirtualMethodIndex}
VMTIndexIncCodeSize = 6;
var
LInd, LSizeInd, LMinimumPoolSize, LOptimalPoolSize, LGroupNumber,
LBlocksPerPool, LPreviousBlockSize: Cardinal;
LPMediumFreeBlock: PMediumFreeBlock;
begin
{$ifdef FullDebugMode}
{$ifdef LoadDebugDLLDynamically}
{Attempt to load the FullDebugMode DLL dynamically.}
FullDebugModeDLL := LoadLibrary(FullDebugModeLibraryName);
if FullDebugModeDLL <> 0 then
begin
GetStackTrace := GetProcAddress(FullDebugModeDLL,
{$ifdef RawStackTraces}'GetRawStackTrace'{$else}'GetFrameBasedStackTrace'{$endif});
LogStackTrace := GetProcAddress(FullDebugModeDLL, 'LogStackTrace');
end;
{$endif}
{$endif}
{$ifdef EnableMMX}
{$ifndef ForceMMX}
UseMMX := MMX_Supported;
{$endif}
{$endif}
{Initialize the memory manager}
{-------------Set up the small block types-------------}
LPreviousBlockSize := 0;
for LInd := 0 to High(SmallBlockTypes) do
begin
{Set the move procedure}
{$ifdef UseCustomFixedSizeMoveRoutines}
{The upsize move procedure may move chunks in 16 bytes even with 8-byte
alignment, since the new size will always be at least 8 bytes bigger than
the old size.}
if not Assigned(SmallBlockTypes[LInd].UpsizeMoveProcedure) then
{$ifdef UseCustomVariableSizeMoveRoutines}
SmallBlockTypes[LInd].UpsizeMoveProcedure := MoveX16LP;
{$else}
SmallBlockTypes[LInd].UpsizeMoveProcedure := @System.Move;
{$endif}
{$endif}
{Set the first "available pool" to the block type itself, so that the
allocation routines know that there are currently no pools with free
blocks of this size.}
SmallBlockTypes[LInd].PreviousPartiallyFreePool := @SmallBlockTypes[LInd];
SmallBlockTypes[LInd].NextPartiallyFreePool := @SmallBlockTypes[LInd];
{Set the block size to block type index translation table}
for LSizeInd := (LPreviousBlockSize div SmallBlockGranularity) to ((SmallBlockTypes[LInd].BlockSize - 1) div SmallBlockGranularity) do
AllocSize2SmallBlockTypeIndX4[LSizeInd] := LInd * 4;
{Cannot sequential feed yet: Ensure that the next address is greater than
the maximum address}
SmallBlockTypes[LInd].MaxSequentialFeedBlockAddress := Pointer(0);
SmallBlockTypes[LInd].NextSequentialFeedBlockAddress := Pointer(1);
{Get the mask to use for finding a medium block suitable for a block pool}
LMinimumPoolSize :=
((SmallBlockTypes[LInd].BlockSize * MinimumSmallBlocksPerPool
+ SmallBlockPoolHeaderSize + MediumBlockGranularity - 1 - MediumBlockSizeOffset)
and -MediumBlockGranularity) + MediumBlockSizeOffset;
if LMinimumPoolSize < MinimumMediumBlockSize then
LMinimumPoolSize := MinimumMediumBlockSize;
{Get the closest group number for the minimum pool size}
LGroupNumber := (LMinimumPoolSize - MinimumMediumBlockSize + MediumBlockBinsPerGroup * MediumBlockGranularity div 2)
div (MediumBlockBinsPerGroup * MediumBlockGranularity);
{Too large?}
if LGroupNumber > 7 then
LGroupNumber := 7;
{Set the bitmap}
SmallBlockTypes[LInd].AllowedGroupsForBlockPoolBitmap := Byte(-(1 shl LGroupNumber));
{Set the minimum pool size}
SmallBlockTypes[LInd].MinimumBlockPoolSize := MinimumMediumBlockSize + LGroupNumber * (MediumBlockBinsPerGroup * MediumBlockGranularity);
{Get the optimal block pool size}
LOptimalPoolSize := ((SmallBlockTypes[LInd].BlockSize * TargetSmallBlocksPerPool
+ SmallBlockPoolHeaderSize + MediumBlockGranularity - 1 - MediumBlockSizeOffset)
and -MediumBlockGranularity) + MediumBlockSizeOffset;
{Limit the optimal pool size to within range}
if LOptimalPoolSize < OptimalSmallBlockPoolSizeLowerLimit then
LOptimalPoolSize := OptimalSmallBlockPoolSizeLowerLimit;
if LOptimalPoolSize > OptimalSmallBlockPoolSizeUpperLimit then
LOptimalPoolSize := OptimalSmallBlockPoolSizeUpperLimit;
{How many blocks will fit in the adjusted optimal size?}
LBlocksPerPool := (LOptimalPoolSize - SmallBlockPoolHeaderSize) div SmallBlockTypes[LInd].BlockSize;
{Recalculate the optimal pool size to minimize wastage due to a partial
last block.}
SmallBlockTypes[LInd].OptimalBlockPoolSize :=
((LBlocksPerPool * SmallBlockTypes[LInd].BlockSize + SmallBlockPoolHeaderSize + MediumBlockGranularity - 1 - MediumBlockSizeOffset) and -MediumBlockGranularity) + MediumBlockSizeOffset;
{$ifdef CheckHeapForCorruption}
{Debug checks}
if (SmallBlockTypes[LInd].OptimalBlockPoolSize < MinimumMediumBlockSize)
or (SmallBlockTypes[LInd].BlockSize div SmallBlockGranularity * SmallBlockGranularity <> SmallBlockTypes[LInd].BlockSize) then
begin
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
end;
{$endif}
{Set the previous small block size}
LPreviousBlockSize := SmallBlockTypes[LInd].BlockSize;
end;
{-------------------Set up the medium blocks-------------------}
{$ifdef CheckHeapForCorruption}
{Check that there are no gaps between where the small blocks end and the
medium blocks start}
if (((MaximumSmallBlockSize - 3) + (MediumBlockGranularity - 1 + BlockHeaderSize - MediumBlockSizeOffset))
and -MediumBlockGranularity) + MediumBlockSizeOffset < MinimumMediumBlockSize then
begin
{$ifdef BCB6OrDelphi7AndUp}
System.Error(reInvalidPtr);
{$else}
System.RunError(reInvalidPtr);
{$endif}
end;
{$endif}
{There are currently no medium block pools}
MediumBlockPoolsCircularList.PreviousMediumBlockPoolHeader := @MediumBlockPoolsCircularList;
MediumBlockPoolsCircularList.NextMediumBlockPoolHeader := @MediumBlockPoolsCircularList;
{All medium bins are empty}
for LInd := 0 to High(MediumBlockBins) do
begin
LPMediumFreeBlock := @MediumBlockBins[LInd];
LPMediumFreeBlock.PreviousFreeBlock := LPMediumFreeBlock;
LPMediumFreeBlock.NextFreeBlock := LPMediumFreeBlock;
end;
{------------------Set up the large blocks---------------------}
LargeBlocksCircularList.PreviousLargeBlockHeader := @LargeBlocksCircularList;
LargeBlocksCircularList.NextLargeBlockHeader := @LargeBlocksCircularList;
{------------------Set up the debugging structures---------------------}
{$ifdef FullDebugMode}
{Set up the fake VMT}
{Copy the basic info from the TFreedObject class}
System.Move(Pointer(PByte(TFreedObject) + vmtSelfPtr + SizeOf(Pointer))^,
FreedObjectVMT.VMTData[vmtSelfPtr + SizeOf(Pointer)], vmtParent - vmtSelfPtr);
PNativeUInt(@FreedObjectVMT.VMTData[vmtSelfPtr])^ := NativeUInt(@FreedObjectVMT.VMTMethods[0]);
{Set up the virtual method table}
for LInd := 0 to MaxFakeVMTEntries - 1 do
begin
PNativeUInt(@FreedObjectVMT.VMTMethods[Low(FreedObjectVMT.VMTMethods) + Integer(LInd * SizeOf(Pointer))])^ :=
NativeUInt(@TFreedObject.GetVirtualMethodIndex) + LInd * VMTIndexIncCodeSize;
{$ifdef CatchUseOfFreedInterfaces}
VMTBadInterface[LInd] := @TFreedObject.InterfaceError;
{$endif}
end;
{Set up the default log file name}
SetDefaultMMLogFileName;
{$endif}
end;
{Installs the memory manager (InitializeMemoryManager should be called first)}
procedure InstallMemoryManager;
{$ifdef MMSharingEnabled}
var
i, LCurrentProcessID: Cardinal;
LPMapAddress: PPointer;
LChar: AnsiChar;
{$endif}
begin
if not FastMMIsInstalled then
begin
{$ifdef FullDebugMode}
{$ifdef 32Bit}
{Try to reserve the 64K block covering address $80808080}
ReservedBlock := VirtualAlloc(Pointer(DebugReservedAddress), 65536, MEM_RESERVE, PAGE_NOACCESS);
{$endif}
{$endif}
{$ifdef MMSharingEnabled}
{Build a string identifying the current process}
LCurrentProcessID := GetCurrentProcessId;
for i := 0 to 7 do
begin
LChar := HexTable[((LCurrentProcessID shr (i * 4)) and $F)];
MappingObjectName[(High(MappingObjectName) - 1) - i] := LChar;
{$ifdef EnableBackwardCompatibleMMSharing}
UniqueProcessIDString[8 - i] := LChar;
UniqueProcessIDStringBE[8 - i] := LChar;
{$endif}
end;
{$endif}
{$ifdef AttemptToUseSharedMM}
{Is the replacement memory manager already installed for this process?}
{$ifdef EnableBackwardCompatibleMMSharing}
MMWindow := FindWindowA('STATIC', PAnsiChar(@UniqueProcessIDString[1]));
MMWindowBE := FindWindowA('STATIC', PAnsiChar(@UniqueProcessIDStringBE[1]));
{$endif}
MappingObjectHandle := OpenFileMappingA(FILE_MAP_READ, False, MappingObjectName);
{Is no MM being shared?}
{$ifdef EnableBackwardCompatibleMMSharing}
if (MMWindow or MMWindowBE or MappingObjectHandle) = 0 then
{$else}
if MappingObjectHandle = 0 then
{$endif}
begin
{$endif}
{$ifdef ShareMM}
{Share the MM with other DLLs? - if this DLL is unloaded, then
dependent DLLs will cause a crash.}
{$ifndef ShareMMIfLibrary}
if not IsLibrary then
{$endif}
begin
{$ifdef EnableBackwardCompatibleMMSharing}
{No memory manager installed yet - create the invisible window}
MMWindow := CreateWindowA('STATIC', PAnsiChar(@UniqueProcessIDString[1]),
WS_POPUP, 0, 0, 0, 0, 0, 0, hInstance, nil);
MMWindowBE := CreateWindowA('STATIC', PAnsiChar(@UniqueProcessIDStringBE[1]),
WS_POPUP, 0, 0, 0, 0, 0, 0, hInstance, nil);
{The window data is a pointer to this memory manager}
if MMWindow <> 0 then
SetWindowLongA(MMWindow, GWL_USERDATA, NativeInt(@NewMemoryManager));
if MMWindowBE <> 0 then
SetWindowLongA(MMWindowBE, GWL_USERDATA, NativeInt(@NewMemoryManager));
{$endif}
{Create the memory mapped file}
MappingObjectHandle := CreateFileMappingA(INVALID_HANDLE_VALUE, nil,
PAGE_READWRITE, 0, SizeOf(Pointer), MappingObjectName);
{Map a view of the memory}
LPMapAddress := MapViewOfFile(MappingObjectHandle, FILE_MAP_WRITE, 0, 0, 0);
{Set a pointer to the new memory manager}
LPMapAddress^ := @NewMemoryManager;
{Unmap the file}
UnmapViewOfFile(LPMapAddress);
end;
{$endif}
{We will be using this memory manager}
{$ifndef FullDebugMode}
NewMemoryManager.GetMem := FastGetMem;
NewMemoryManager.FreeMem := FastFreeMem;
NewMemoryManager.ReallocMem := FastReallocMem;
{$else}
NewMemoryManager.GetMem := DebugGetMem;
NewMemoryManager.FreeMem := DebugFreeMem;
NewMemoryManager.ReallocMem := DebugReallocMem;
{$endif}
{$ifdef BDS2006AndUp}
{$ifndef FullDebugMode}
NewMemoryManager.AllocMem := FastAllocMem;
{$else}
NewMemoryManager.AllocMem := DebugAllocMem;
{$endif}
{$ifdef EnableMemoryLeakReporting}
NewMemoryManager.RegisterExpectedMemoryLeak := RegisterExpectedMemoryLeak;
NewMemoryManager.UnRegisterExpectedMemoryLeak := UnRegisterExpectedMemoryLeak;
{$else}
NewMemoryManager.RegisterExpectedMemoryLeak := NoOpRegisterExpectedMemoryLeak;
NewMemoryManager.UnRegisterExpectedMemoryLeak := NoOpUnRegisterExpectedMemoryLeak;
{$endif}
{$endif}
{Owns the memory manager}
IsMemoryManagerOwner := True;
{$ifdef AttemptToUseSharedMM}
end
else
begin
{Get the address of the shared memory manager}
{$ifndef BDS2006AndUp}
{$ifdef EnableBackwardCompatibleMMSharing}
if MappingObjectHandle <> 0 then
begin
{$endif}
{Map a view of the memory}
LPMapAddress := MapViewOfFile(MappingObjectHandle, FILE_MAP_READ, 0, 0, 0);
{Set the new memory manager}
NewMemoryManager := PMemoryManager(LPMapAddress^)^;
{Unmap the file}
UnmapViewOfFile(LPMapAddress);
{$ifdef EnableBackwardCompatibleMMSharing}
end
else
begin
if MMWindow <> 0 then
begin
NewMemoryManager := PMemoryManager(GetWindowLong(MMWindow, GWL_USERDATA))^;
end
else
begin
NewMemoryManager := PMemoryManager(GetWindowLong(MMWindowBE, GWL_USERDATA))^;
end;
end;
{$endif}
{$else}
{$ifdef EnableBackwardCompatibleMMSharing}
if MappingObjectHandle <> 0 then
begin
{$endif}
{Map a view of the memory}
LPMapAddress := MapViewOfFile(MappingObjectHandle, FILE_MAP_READ, 0, 0, 0);
{Set the new memory manager}
NewMemoryManager := PMemoryManagerEx(LPMapAddress^)^;
{Unmap the file}
UnmapViewOfFile(LPMapAddress);
{$ifdef EnableBackwardCompatibleMMSharing}
end
else
begin
if MMWindow <> 0 then
begin
NewMemoryManager := PMemoryManagerEx(GetWindowLong(MMWindow, GWL_USERDATA))^;
end
else
begin
NewMemoryManager := PMemoryManagerEx(GetWindowLong(MMWindowBE, GWL_USERDATA))^;
end;
end;
{$endif}
{$endif}
{Close the file mapping handle}
CloseHandle(MappingObjectHandle);
MappingObjectHandle := 0;
{The memory manager is not owned by this module}
IsMemoryManagerOwner := False;
end;
{$endif}
{Save the old memory manager}
GetMemoryManager(OldMemoryManager);
{Replace the memory manager with either this one or the shared one.}
SetMemoryManager(NewMemoryManager);
{FastMM is now installed}
FastMMIsInstalled := True;
{$ifdef UseOutputDebugString}
if IsMemoryManagerOwner then
OutputDebugStringA(FastMMInstallMsg)
else
OutputDebugStringA(FastMMInstallSharedMsg);
{$endif}
end;
end;
procedure UninstallMemoryManager;
begin
{Is this the owner of the shared MM window?}
if IsMemoryManagerOwner then
begin
{$ifdef ShareMM}
{$ifdef EnableBackwardCompatibleMMSharing}
{Destroy the window}
if MMWindow <> 0 then
begin
DestroyWindow(MMWindow);
MMWindow := 0;
end;
if MMWindowBE <> 0 then
begin
DestroyWindow(MMWindowBE);
MMWindowBE := 0;
end;
{$endif}
{Destroy the memory mapped file handle}
if MappingObjectHandle <> 0 then
begin
CloseHandle(MappingObjectHandle);
MappingObjectHandle := 0;
end;
{$endif}
{$ifdef FullDebugMode}
{Release the reserved block}
if ReservedBlock <> nil then
begin
VirtualFree(ReservedBlock, 0, MEM_RELEASE);
ReservedBlock := nil;
end;
{$endif}
end;
{$ifndef DetectMMOperationsAfterUninstall}
{Restore the old memory manager}
SetMemoryManager(OldMemoryManager);
{$else}
{Set the invalid memory manager: no more MM operations allowed}
SetMemoryManager(InvalidMemoryManager);
{$endif}
{Memory manager has been uninstalled}
FastMMIsInstalled := False;
{$ifdef UseOutputDebugString}
if IsMemoryManagerOwner then
OutputDebugStringA(FastMMUninstallMsg)
else
OutputDebugStringA(FastMMUninstallSharedMsg);
{$endif}
end;
procedure FinalizeMemoryManager;
begin
{Restore the old memory manager if FastMM has been installed}
if FastMMIsInstalled then
begin
{$ifndef NeverUninstall}
{Uninstall FastMM}
UninstallMemoryManager;
{$endif}
{Do we own the memory manager, or are we just sharing it?}
if IsMemoryManagerOwner then
begin
{$ifdef CheckUseOfFreedBlocksOnShutdown}
CheckBlocksOnShutdown(
{$ifdef EnableMemoryLeakReporting}
True
{$ifdef RequireIDEPresenceForLeakReporting}
and DelphiIsRunning
{$endif}
{$ifdef RequireDebuggerPresenceForLeakReporting}
and ((DebugHook <> 0)
{$ifdef PatchBCBTerminate}
or (Assigned(pCppDebugHook) and (pCppDebugHook^ <> 0))
{$endif PatchBCBTerminate}
)
{$endif}
{$ifdef ManualLeakReportingControl}
and ReportMemoryLeaksOnShutdown
{$endif}
{$else}
False
{$endif}
);
{$else}
{$ifdef EnableMemoryLeakReporting}
if True
{$ifdef RequireIDEPresenceForLeakReporting}
and DelphiIsRunning
{$endif}
{$ifdef RequireDebuggerPresenceForLeakReporting}
and ((DebugHook <> 0)
{$ifdef PatchBCBTerminate}
or (Assigned(pCppDebugHook) and (pCppDebugHook^ <> 0))
{$endif PatchBCBTerminate}
)
{$endif}
{$ifdef ManualLeakReportingControl}
and ReportMemoryLeaksOnShutdown
{$endif}
then
CheckBlocksOnShutdown(True);
{$endif}
{$endif}
{$ifdef EnableMemoryLeakReporting}
{Free the expected memory leaks list}
if ExpectedMemoryLeaks <> nil then
begin
VirtualFree(ExpectedMemoryLeaks, 0, MEM_RELEASE);
ExpectedMemoryLeaks := nil;
end;
{$endif}
{$ifndef NeverUninstall}
{Clean up: Free all memory. If this is a .DLL that owns its own MM, then
it is necessary to prevent the main application from running out of
address space.}
FreeAllMemory;
{$endif}
end;
end;
end;
procedure RunInitializationCode;
begin
{Only run this code once during startup.}
if InitializationCodeHasRun then
Exit;
InitializationCodeHasRun := True;
{$ifndef BCB}
{$ifdef InstallOnlyIfRunningInIDE}
if (DebugHook <> 0) and DelphiIsRunning then
{$endif}
begin
{Initialize all the lookup tables, etc. for the memory manager}
InitializeMemoryManager;
{Has another MM been set, or has the Embarcadero MM been used? If so, this
file is not the first unit in the uses clause of the project's .dpr
file.}
if CheckCanInstallMemoryManager then
begin
{$ifdef ClearLogFileOnStartup}
DeleteEventLog;
{$endif}
InstallMemoryManager;
end;
end;
{$endif}
end;
initialization
RunInitializationCode;
finalization
{$ifndef PatchBCBTerminate}
FinalizeMemoryManager;
{$endif}
end. |
unit bluetoothlowenergy;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, {And_jni_Bridge,} AndroidWidget;
type
TBLEScanMode = (smLowPower, smLowLantency);
TBLEBondState = (bsNone=10, bsBonding=11, bsBonded=12);
TBLECharacteristicProperty = (cpUnknown=0, cpRead=2, cpNotify=16, cpIndicate=32);
TOnBluetoothLEScanCompleted=procedure(Sender:TObject;deviceNameArray:array of string;deviceAddressArray:array of string) of object;
TOnBluetoothLEConnected=procedure(Sender:TObject;deviceName:string;deviceAddress:string;bondState:TBLEBondState) of object;
TOnBluetoothLEServiceDiscovered=procedure(Sender:TObject;serviceIndex:integer;serviceUUID:string;characteristicUUIDArray:array of string) of object;
TOnBluetoothLECharacteristicChanged=procedure(Sender:TObject;strValue:string;strCharacteristic:string) of object;
TOnBluetoothLECharacteristicRead=procedure(Sender:TObject;strValue:string;strCharacteristic:string) of object;
{Draft Component code by "LAMW: Lazarus Android Module Wizard" [11/22/2020 14:46:01]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jControl template}
jBluetoothLowEnergy = class(jControl)
private
FScanMode: TBLEScanMode;
FScanPeriod: int64;
FOnScanCompleted: TOnBluetoothLEScanCompleted;
FOnConnected: TOnBluetoothLEConnected;
FOnServiceDiscovered: TOnBluetoothLEServiceDiscovered;
FOnCharacteristicChanged: TOnBluetoothLECharacteristicChanged;
FOnCharacteristicRead: TOnBluetoothLECharacteristicRead;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
function jCreate(): jObject;
procedure jFree();
function HasSystemFeature(): boolean;
procedure DisconnectGattServer();
procedure SetScanPeriod(_milliSeconds: int64);
procedure SetScanMode(_mode: TBLEScanMode);
procedure StartScan(); overload;
procedure StartScan(_filterServiceUUID: string); overload;
procedure StopScan();
procedure ConnectDevice(_deviceAddress: string);
procedure DiscoverServices();
function GetCharacteristics(_serviceIndex: integer): TDynArrayOfString;
function GetCharacteristicProperties(_serviceIndex: integer; _characteristicIndex: integer): TBLECharacteristicProperty;
function GetDescriptors(_serviceIndex: integer; _characteristicIndex: integer): TDynArrayOfString;
procedure ReadCharacteristic(_serviceIndex: integer; _characteristicIndex: integer);
procedure GenEvent_OnBluetoothLEScanCompleted(Sender:TObject;deviceName:array of string;deviceAddress:array of string);
procedure GenEvent_OnBluetoothLEConnected(Sender:TObject;deviceName:string;deviceAddress:string;bondState:integer);
procedure GenEvent_OnBluetoothLEServiceDiscovered(Sender:TObject;serviceIndex:integer;serviceUUID:string;characteristicUUIDArray:array of string);
procedure GenEvent_OnBluetoothLECharacteristicChanged(Sender:TObject;strValue:string;strCharacteristic:string);
procedure GenEvent_OnBluetoothLECharacteristicRead(Sender:TObject;strValue:string;strCharacteristic:string);
published
property ScanMode: TBLEScanMode read FScanMode write SetScanMode;
property ScanPeriod: int64 read FScanPeriod write SetScanPeriod;
property OnScanCompleted: TOnBluetoothLEScanCompleted read FOnScanCompleted write FOnScanCompleted;
property OnConnected: TOnBluetoothLEConnected read FOnConnected write FOnConnected;
property OnServiceDiscovered: TOnBluetoothLEServiceDiscovered read FOnServiceDiscovered write FOnServiceDiscovered;
property OnCharacteristicChanged: TOnBluetoothLECharacteristicChanged read FOnCharacteristicChanged write FOnCharacteristicChanged;
property OnCharacteristicRead: TOnBluetoothLECharacteristicRead read FOnCharacteristicRead write FOnCharacteristicRead;
end;
function jBluetoothLowEnergy_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
procedure jBluetoothLowEnergy_jFree(env: PJNIEnv; _jbluetoothlowenergy: JObject);
function jBluetoothLowEnergy_HasSystemFeature(env: PJNIEnv; _jbluetoothlowenergy: JObject): boolean;
procedure jBluetoothLowEnergy_disconnectGattServer(env: PJNIEnv; _jbluetoothlowenergy: JObject);
procedure jBluetoothLowEnergy_StartScan(env: PJNIEnv; _jbluetoothlowenergy: JObject); overload;
procedure jBluetoothLowEnergy_StartScan(env: PJNIEnv; _jbluetoothlowenergy: JObject; _filterServiceUUID: string); overload;
procedure jBluetoothLowEnergy_SetScanPeriod(env: PJNIEnv; _jbluetoothlowenergy: JObject; _milliSeconds: int64);
procedure jBluetoothLowEnergy_SetScanMode(env: PJNIEnv; _jbluetoothlowenergy: JObject; _mode: integer);
procedure jBluetoothLowEnergy_StopScan(env: PJNIEnv; _jbluetoothlowenergy: JObject);
procedure jBluetoothLowEnergy_ConnectDevice(env: PJNIEnv; _jbluetoothlowenergy: JObject; _deviceAddress: string);
procedure jBluetoothLowEnergy_DiscoverServices(env: PJNIEnv; _jbluetoothlowenergy: JObject);
function jBluetoothLowEnergy_GetCharacteristics(env: PJNIEnv; _jbluetoothlowenergy: JObject; _serviceIndex: integer): TDynArrayOfString;
function jBluetoothLowEnergy_GetCharacteristicProperties(env: PJNIEnv; _jbluetoothlowenergy: JObject; _serviceIndex: integer; _characteristicIndex: integer): integer;
function jBluetoothLowEnergy_GetDescriptors(env: PJNIEnv; _jbluetoothlowenergy: JObject; _serviceIndex: integer; _characteristicIndex: integer): TDynArrayOfString;
procedure jBluetoothLowEnergy_ReadCharacteristic(env: PJNIEnv; _jbluetoothlowenergy: JObject; _serviceIndex: integer; _characteristicIndex: integer);
implementation
{--------- jBluetoothLowEnergy --------------}
constructor jBluetoothLowEnergy.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//your code here....
FScanPeriod:= 5000;
FScanMode:= smLowPower;
end;
destructor jBluetoothLowEnergy.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jBluetoothLowEnergy.Init;
begin
if FInitialized then Exit;
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jCreate(); //jSelf !
if FjObject = nil then exit;
if FScanMode <> smLowPower then
jBluetoothLowEnergy_SetScanMode(gApp.jni.jEnv, FjObject, ord(FScanMode));
if FScanPeriod <> 5000 then
jBluetoothLowEnergy_SetScanPeriod(gApp.jni.jEnv, FjObject, FScanPeriod);
FInitialized:= True;
end;
function jBluetoothLowEnergy.jCreate(): jObject;
begin
Result:= jBluetoothLowEnergy_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis);
end;
procedure jBluetoothLowEnergy.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jBluetoothLowEnergy_jFree(gApp.jni.jEnv, FjObject);
end;
function jBluetoothLowEnergy.HasSystemFeature(): boolean;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jBluetoothLowEnergy_HasSystemFeature(gApp.jni.jEnv, FjObject);
end;
procedure jBluetoothLowEnergy.DisconnectGattServer();
begin
//in designing component state: set value here...
if FInitialized then
jBluetoothLowEnergy_disconnectGattServer(gApp.jni.jEnv, FjObject);
end;
procedure jBluetoothLowEnergy.StartScan();
begin
//in designing component state: set value here...
if FInitialized then
jBluetoothLowEnergy_StartScan(gApp.jni.jEnv, FjObject);
end;
procedure jBluetoothLowEnergy.StopScan();
begin
//in designing component state: set value here...
if FInitialized then
jBluetoothLowEnergy_StopScan(gApp.jni.jEnv, FjObject);
end;
procedure jBluetoothLowEnergy.ConnectDevice(_deviceAddress: string);
begin
//in designing component state: set value here...
if FInitialized then
jBluetoothLowEnergy_ConnectDevice(gApp.jni.jEnv, FjObject, _deviceAddress);
end;
procedure jBluetoothLowEnergy.StartScan(_filterServiceUUID: string);
begin
//in designing component state: set value here...
if FInitialized then
jBluetoothLowEnergy_StartScan(gApp.jni.jEnv, FjObject, _filterServiceUUID);
end;
procedure jBluetoothLowEnergy.SetScanPeriod(_milliSeconds: int64);
begin
//in designing component state: set value here...
FScanPeriod:= _milliSeconds;
if FInitialized then
jBluetoothLowEnergy_SetScanPeriod(gApp.jni.jEnv, FjObject, _milliSeconds);
end;
procedure jBluetoothLowEnergy.SetScanMode(_mode: TBLEScanMode);
begin
//in designing component state: set value here...
FScanMode:= _mode;
if FInitialized then
jBluetoothLowEnergy_SetScanMode(gApp.jni.jEnv, FjObject, ord(_mode));
end;
procedure jBluetoothLowEnergy.DiscoverServices();
begin
//in designing component state: set value here...
if FInitialized then
jBluetoothLowEnergy_DiscoverServices(gApp.jni.jEnv, FjObject);
end;
function jBluetoothLowEnergy.GetCharacteristics(_serviceIndex: integer): TDynArrayOfString;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jBluetoothLowEnergy_GetCharacteristics(gApp.jni.jEnv, FjObject, _serviceIndex);
end;
function jBluetoothLowEnergy.GetCharacteristicProperties(_serviceIndex: integer; _characteristicIndex: integer): TBLECharacteristicProperty;
begin
//in designing component state: result value here...
if FInitialized then
Result:= TBLECharacteristicProperty(jBluetoothLowEnergy_GetCharacteristicProperties(gApp.jni.jEnv, FjObject, _serviceIndex ,_characteristicIndex));
end;
function jBluetoothLowEnergy.GetDescriptors(_serviceIndex: integer; _characteristicIndex: integer): TDynArrayOfString;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jBluetoothLowEnergy_GetDescriptors(gApp.jni.jEnv, FjObject, _serviceIndex ,_characteristicIndex);
end;
procedure jBluetoothLowEnergy.ReadCharacteristic(_serviceIndex: integer; _characteristicIndex: integer);
begin
//in designing component state: set value here...
if FInitialized then
jBluetoothLowEnergy_ReadCharacteristic(gApp.jni.jEnv, FjObject, _serviceIndex ,_characteristicIndex);
end;
procedure jBluetoothLowEnergy.GenEvent_OnBluetoothLEConnected(Sender:TObject;deviceName:string;deviceAddress:string;bondState: integer);
begin
if Assigned(FOnConnected) then FOnConnected(Sender,deviceName,deviceAddress,TBLEBondState(bondState));
end;
procedure jBluetoothLowEnergy.GenEvent_OnBluetoothLEScanCompleted(Sender:TObject;deviceName:array of string;deviceAddress:array of string);
begin
if Assigned(FOnScanCompleted) then FOnScanCompleted(Sender,deviceName,deviceAddress);
end;
procedure jBluetoothLowEnergy.GenEvent_OnBluetoothLEServiceDiscovered(Sender:TObject;serviceIndex:integer;serviceUUID:string;characteristicUUIDArray:array of string);
begin
if Assigned(FOnServiceDiscovered) then FOnServiceDiscovered(Sender,serviceIndex,serviceUUID,characteristicUUIDArray);
end;
procedure jBluetoothLowEnergy.GenEvent_OnBluetoothLECharacteristicChanged(Sender:TObject;strValue:string;strCharacteristic:string);
begin
if Assigned(FOnCharacteristicChanged) then FOnCharacteristicChanged(Sender,strValue,strCharacteristic);
end;
procedure jBluetoothLowEnergy.GenEvent_OnBluetoothLECharacteristicRead(Sender:TObject;strValue:string;strCharacteristic:string);
begin
if Assigned(FOnCharacteristicRead) then FOnCharacteristicRead(Sender,strValue,strCharacteristic);
end;
{-------- jBluetoothLowEnergy_JNI_Bridge ----------}
function jBluetoothLowEnergy_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _Self;
jCls:= Get_gjClass(env);
jMethod:= env^.GetMethodID(env, jCls, 'jBluetoothLowEnergy_jCreate', '(J)Ljava/lang/Object;');
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
end;
procedure jBluetoothLowEnergy_jFree(env: PJNIEnv; _jbluetoothlowenergy: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
env^.CallVoidMethod(env, _jbluetoothlowenergy, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jBluetoothLowEnergy_HasSystemFeature(env: PJNIEnv; _jbluetoothlowenergy: JObject): boolean;
var
jBoo: JBoolean;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'HasSystemFeature', '()Z');
jBoo:= env^.CallBooleanMethod(env, _jbluetoothlowenergy, jMethod);
Result:= boolean(jBoo);
env^.DeleteLocalRef(env, jCls);
end;
procedure jBluetoothLowEnergy_disconnectGattServer(env: PJNIEnv; _jbluetoothlowenergy: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'disconnectGattServer', '()V');
env^.CallVoidMethod(env, _jbluetoothlowenergy, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jBluetoothLowEnergy_StartScan(env: PJNIEnv; _jbluetoothlowenergy: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'StartScan', '()V');
env^.CallVoidMethod(env, _jbluetoothlowenergy, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jBluetoothLowEnergy_StopScan(env: PJNIEnv; _jbluetoothlowenergy: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'StopScan', '()V');
env^.CallVoidMethod(env, _jbluetoothlowenergy, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jBluetoothLowEnergy_ConnectDevice(env: PJNIEnv; _jbluetoothlowenergy: JObject; _deviceAddress: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_deviceAddress));
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'ConnectDevice', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jbluetoothlowenergy, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jBluetoothLowEnergy_StartScan(env: PJNIEnv; _jbluetoothlowenergy: JObject; _filterServiceUUID: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_filterServiceUUID));
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'StartScan', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jbluetoothlowenergy, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jBluetoothLowEnergy_SetScanPeriod(env: PJNIEnv; _jbluetoothlowenergy: JObject; _milliSeconds: int64);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _milliSeconds;
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'SetScanPeriod', '(J)V');
env^.CallVoidMethodA(env, _jbluetoothlowenergy, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jBluetoothLowEnergy_SetScanMode(env: PJNIEnv; _jbluetoothlowenergy: JObject; _mode: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _mode;
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'SetScanMode', '(I)V');
env^.CallVoidMethodA(env, _jbluetoothlowenergy, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jBluetoothLowEnergy_DiscoverServices(env: PJNIEnv; _jbluetoothlowenergy: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'DiscoverServices', '()V');
env^.CallVoidMethod(env, _jbluetoothlowenergy, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jBluetoothLowEnergy_GetCharacteristics(env: PJNIEnv; _jbluetoothlowenergy: JObject; _serviceIndex: integer): TDynArrayOfString;
var
jStr: JString;
jBoo: JBoolean;
resultSize: integer;
jResultArray: jObject;
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
i: integer;
begin
Result := nil;
jParams[0].i:= _serviceIndex;
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'GetCharacteristics', '(I)[Ljava/lang/String;');
jResultArray:= env^.CallObjectMethodA(env, _jbluetoothlowenergy, jMethod, @jParams);
if jResultArray <> nil then
begin
resultSize:= env^.GetArrayLength(env, jResultArray);
SetLength(Result, resultSize);
for i:= 0 to resultsize - 1 do
begin
jStr:= env^.GetObjectArrayElement(env, jresultArray, i);
case jStr = nil of
True : Result[i]:= '';
False: begin
jBoo:= JNI_False;
Result[i]:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
function jBluetoothLowEnergy_GetCharacteristicProperties(env: PJNIEnv; _jbluetoothlowenergy: JObject; _serviceIndex: integer; _characteristicIndex: integer): integer;
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _serviceIndex;
jParams[1].i:= _characteristicIndex;
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'GetCharacteristicProperties', '(II)I');
Result:= env^.CallIntMethodA(env, _jbluetoothlowenergy, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jBluetoothLowEnergy_GetDescriptors(env: PJNIEnv; _jbluetoothlowenergy: JObject; _serviceIndex: integer; _characteristicIndex: integer): TDynArrayOfString;
var
jStr: JString;
jBoo: JBoolean;
resultSize: integer;
jResultArray: jObject;
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
i: integer;
begin
Result := nil;
jParams[0].i:= _serviceIndex;
jParams[1].i:= _characteristicIndex;
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'GetDescriptors', '(II)[Ljava/lang/String;');
jResultArray:= env^.CallObjectMethodA(env, _jbluetoothlowenergy, jMethod, @jParams);
if jResultArray <> nil then
begin
resultSize:= env^.GetArrayLength(env, jResultArray);
SetLength(Result, resultSize);
for i:= 0 to resultsize - 1 do
begin
jStr:= env^.GetObjectArrayElement(env, jresultArray, i);
case jStr = nil of
True : Result[i]:= '';
False: begin
jBoo:= JNI_False;
Result[i]:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
end;
end;
env^.DeleteLocalRef(env, jCls);
end;
procedure jBluetoothLowEnergy_ReadCharacteristic(env: PJNIEnv; _jbluetoothlowenergy: JObject; _serviceIndex: integer; _characteristicIndex: integer);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _serviceIndex;
jParams[1].i:= _characteristicIndex;
jCls:= env^.GetObjectClass(env, _jbluetoothlowenergy);
jMethod:= env^.GetMethodID(env, jCls, 'ReadCharacteristic', '(II)V');
env^.CallVoidMethodA(env, _jbluetoothlowenergy, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
end.
|
unit TamanhoProduto;
interface
uses SysUtils, Contnrs, Tamanho;
type
TTamanhoProduto = class
private
Fcodigo :Integer;
Fcodigo_produto :Integer;
Fcodigo_tamanho :Integer;
FPreco :Real;
Fmax_sabores :Integer;
FTamanho :TTamanho;
function GetTamanho: TTamanho;
public
property codigo :Integer read Fcodigo write Fcodigo;
property codigo_produto :Integer read Fcodigo_produto write Fcodigo_produto;
property codigo_tamanho :Integer read Fcodigo_tamanho write Fcodigo_tamanho;
property preco :Real read FPreco write FPreco;
property max_sabores :Integer read Fmax_sabores write Fmax_sabores;
public
property Tamanho :TTamanho read GetTamanho;
end;
implementation
uses Repositorio, FabricaRepositorio;
{ TTamanhoProduto }
function TTamanhoProduto.GetTamanho: TTamanho;
var
Repositorio :TRepositorio;
begin
try
Repositorio := nil;
if not assigned(FTamanho) then
begin
Repositorio := TFabricaRepositorio.GetRepositorio(TTamanho.ClassName);
FTamanho := TTamanho( repositorio.Get( self.Fcodigo_tamanho));
end;
result := FTamanho;
finally
FreeAndNil(Repositorio);
end;
end;
end.
|
unit RunTypeFactory;
interface
uses FrogObj, RunTypeU;
type
TRunTypeFactory = class(TFrogObject)
private
mTheory: TRunType;
mExperimental: TRunType;
mReadIn: TRunType;
public
function getRunTypeForEnum(pRTEnum: TRunTypeEnum): TRunType;
function getRunTypeForInt(pRTInt: Integer): TRunType;
constructor Create;
destructor Destroy; override;
end;
var
RRunTypeFactory: TRunTypeFactory;
implementation
uses
RTTheory, RTExperiment, RTReadIn;
constructor TRunTypeFactory.Create;
begin
mTheory := TRTTheory.Create;
mExperimental := TRTExperiment.Create;
mReadIn := TRTReadIn.Create;
end;
destructor TRunTypeFactory.Destroy;
begin
mTheory.Free;
mExperimental.Free;
mReadIn.Free;
inherited Destroy;
end;
function TRunTypeFactory.getRunTypeForEnum(pRTEnum: TRunTypeEnum): TRunType;
begin
case pRTEnum of
rteTheory:
getRunTypeForEnum := mTheory;
rteExperimental:
getRunTypeForEnum := mExperimental;
rteReadIn:
getRunTypeForEnum := mReadIn;
end;
end;
function TRunTypeFactory.getRunTypeForInt(pRTInt: Integer): TRunType;
begin
case pRTInt of
Ord(rteTheory):
getRunTypeForInt := mTheory;
Ord(rteExperimental):
getRunTypeForInt := mExperimental;
Ord(rteReadIn):
getRunTypeForInt := mReadIn;
end;
end;
end.
|
unit UPerson;
interface
uses
SysUtils;
type
TPerson = class
procedure setID(id: integer); virtual; abstract;
function getID: integer; virtual; abstract;
procedure setName(name: string); virtual; abstract;
function getName: string; virtual; abstract;
procedure setEmail(email: string); virtual; abstract;
function getEmail: string; virtual; abstract;
procedure setStatus (status: integer); virtual; abstract;
function getStatus: integer; virtual; abstract;
procedure setComment(comment: string); virtual; abstract;
function getComment: string; virtual; abstract;
procedure setCreateAt (createAt: TDateTime); virtual; abstract;
function getCreateAt: TDateTime; virtual; abstract;
end;
implementation
end.
|
unit CritSecManager;
interface
uses
Classes, SyncObjs, SysUtils;
type
TCritcalSecData = class(TObject)
private
FName: string;
FSection: TCriticalSection;
FActive: boolean;
public
property Name : string read FName write FName;
property Active : boolean read FActive;
property Section : TCriticalSection read FSection write FSection;
constructor Create;
destructor Destroy; override;
procedure Enter;
procedure Leave;
end;
TCritSecManager = class(TComponent)
private
{ Private-Deklarationen }
FCritSecs: TList;
FAutoAdd: boolean;
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
property AutoAdd:boolean read FAutoAdd write FAutoAdd default true;
procedure AddCritSec(Name:string);
procedure DeleteCritSec(Name: string);
procedure DeleteAll;
procedure Enter(Name:string);
procedure Leave(Name:string);
procedure LeaveAll;
function Find(Name:string):integer;
end;
var CritSec:TCritSecManager;
implementation
{ TCrtitcalSecData }
constructor TCritcalSecData.Create;
begin
inherited Create;
FSection:= TCriticalSection.Create;
end;
destructor TCritcalSecData.Destroy;
begin
FSection.Free;
inherited Destroy;
end;
procedure TCritcalSecData.Enter;
begin
FSection.Enter;
FActive:= true;
end;
procedure TCritcalSecData.Leave;
begin
FSection.Leave;
FActive:= false;
end;
{ TCritSecManager }
constructor TCritSecManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCritSecs:= TList.Create;
FAutoAdd:= true;
end;
destructor TCritSecManager.Destroy;
begin
LeaveAll;
DeleteAll;
FCritSecs.Free;
end;
function TCritSecManager.Find(Name: string): integer;
var i:integer;
begin
Name:= UpperCase(Name);
Result:= -1;
for i:=0 to FCritSecs.Count - 1 do begin
if (UpperCase(TCritcalSecData(FCritSecs[i]).Name)=Name) then begin
Result:= i;
break;
end;
end;
end;
procedure TCritSecManager.AddCritSec(Name: string);
var csd:TCritcalSecData;
begin
if Find(Name)>-1 then exit;
csd:= TCritcalSecData.Create;
csd.Name:= UpperCase(Name);
FCritSecs.Add(csd);
end;
procedure TCritSecManager.DeleteCritSec(Name: string);
var csd:TCritcalSecData;
i:integer;
begin
i:= Find(Name);
if i=-1 then exit;
Leave(Name);
csd:= TCritcalSecData(FCritSecs[i]);
csd.Free;
FCritSecs.Delete(i);
end;
procedure TCritSecManager.Enter(Name: string);
var csd:TCritcalSecData;
i:integer;
begin
i:= Find(Name);
if i=-1 then
if FAutoAdd then AddCritSec(Name)
else exit;
i:= Find(Name);
csd:= TCritcalSecData(FCritSecs[i]);
csd.Enter;
end;
procedure TCritSecManager.Leave(Name: string);
var csd:TCritcalSecData;
begin
if Find(Name)=-1 then exit;
csd:= TCritcalSecData(FCritSecs[Find(Name)]);
csd.Leave;
end;
procedure TCritSecManager.LeaveAll;
var i:integer;
begin
for i:=0 to FCritSecs.Count - 1 do
TCritcalSecData(FCritSecs[i]).Leave;
end;
procedure TCritSecManager.DeleteAll;
var i:integer;
begin
for i:=0 to FCritSecs.Count - 1 do
DeleteCritSec(TCritcalSecData(FCritSecs[i]).Name);
end;
initialization
CritSec:= TCritSecManager.Create(nil);
finalization
CritSec.LeaveAll;
CritSec.Free;
CritSec:= nil;
end.
|
unit DeleteServiceCategory;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, StdCtrls, Buttons, pngimage, ExtCtrls;
type
TfrmDeleteServiceCategory = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
lblName: TLabel;
Button1: TButton;
btnDelete: TButton;
BitBtn1: TBitBtn;
edtNames: TComboBox;
DataSource1: TDataSource;
Image1: TImage;
procedure FormCreate(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function find : Boolean;
procedure fill;
procedure open;
procedure display;
procedure delete;
procedure clearServices;
procedure clear;
end;
var
frmDeleteServiceCategory: TfrmDeleteServiceCategory;
implementation
uses data, ConfirmDeleteServiceCategory;
{$R *.dfm}
procedure TfrmDeleteServiceCategory.btnDeleteClick(Sender: TObject);
begin
if MessageDLg('Are you sure you want to delete this Service Category?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
clearServices;
delete;
MessageDlg('Thank You The Service Category was Successfully Delete',mtInformation,[mbOk],0);
clear;
DataModule2.connect;
end;
end;
procedure TfrmDeleteServiceCategory.Button1Click(Sender: TObject);
begin
if find then
begin
display();
open();
end
else
ShowMessage('The Service category was not found please re-enter service category');
end;
procedure TfrmDeleteServiceCategory.display;
begin
lblName.Caption := 'You can press the Delete button to delete this Service Category';
end;
procedure TfrmDeleteServiceCategory.open;
begin
btnDelete.Enabled := True;
ShowMessage('Press the Delete button ro delete this Service Category.');
end;
function TfrmDeleteServiceCategory.find;
var num : Integer;
service : String;
found : Boolean;
SearchOptions : TLocateOptions;
begin
num := edtNames.ItemIndex;
service := edtNames.Items[num];
SearchOptions := [loCaseInsensitive];
found := DataModule2.tbServiceIndex.Locate('Names', service, SearchOptions);
find := found;
end;
procedure TfrmDeleteServiceCategory.fill;
begin
DataModule2.tbServiceIndex.First;
while not(DataModule2.tbServiceIndex.Eof) do
begin
if (DataModule2.tbServiceIndexActive.Value = True) then
edtNames.Items.Add(DataModule2.tbServiceIndexNames.Value);
DataModule2.tbServiceIndex.Next;
end;
end;
procedure TfrmDeleteServiceCategory.FormCreate(Sender: TObject);
begin
fill();
end;
procedure TfrmDeleteServiceCategory.delete;
begin
DataModule2.tbServiceIndex.Edit;
DataModule2.tbServiceIndexNames.Value := '';
DataModule2.tbServiceIndexActive.Value := False;
DataModule2.tbServiceIndex.Post;
end;
procedure TfrmDeleteServiceCategory.clearServices;
var ID: String;
begin
ID := DataModule2.tbServiceIndexID.Value;
DataModule2.clearTable(ID);
end;
procedure TfrmDeleteServiceCategory.clear;
begin
lblName.Caption := '';
edtNames.Text := 'Select';
end;
end.
|
unit uFornecedoresController;
interface
uses uFornecedorModel, uFornecedoresDAO, Classes, Contnrs,generics.collections;
type
TFornecedoresController = class
private
ForncedorDAO :TFornecedoresDAO;
public
constructor Create;
destructor Destroy;override;
function Inserir(Modelo:TFornecedorModel):Boolean;
function Alterar(Modelo:TFornecedorModel):Boolean;
function Excluir(Id:Integer):Boolean;
procedure RetornaFornecedor(FornecedorModel:TFornecedorModel;
Cod: Integer =0;
Fantasia :String='';
Cnpj: string='');overload;
procedure RetornaFornecedor(Obj:TObjectList<TFornecedorModel>;Cod: Integer=0; Fantasia :String='';
Cnpj: string='');overload;
end;
implementation
{ TFornecedoresController }
function TFornecedoresController.Alterar(Modelo: TFornecedorModel): Boolean;
begin
result := ForncedorDAO.Alterar(Modelo);
end;
constructor TFornecedoresController.Create;
begin
ForncedorDAO := TFornecedoresDAO.Create;
end;
destructor TFornecedoresController.Destroy;
begin
ForncedorDAO.Free;
inherited;
end;
function TFornecedoresController.Excluir(Id: Integer): Boolean;
begin
result := ForncedorDAO.Excluir(Id);
end;
function TFornecedoresController.Inserir(Modelo: TFornecedorModel): Boolean;
begin
result:= ForncedorDAO.Inserir(Modelo);
end;
procedure TFornecedoresController.RetornaFornecedor(Obj:TObjectList<TFornecedorModel>;
Cod: Integer=0; Fantasia:string='';
Cnpj: string='');
begin
ForncedorDAO.RetornaFornecedor(Obj,Cod, Fantasia,Cnpj);
end;
procedure TFornecedoresController.RetornaFornecedor(FornecedorModel:TFornecedorModel;
Cod: Integer =0;
Fantasia :String='';
Cnpj: string='');
begin
ForncedorDAO.RetornaFornecedor(FornecedorModel,Cod,Fantasia,Cnpj);
end;
end.
|
{*****************************************************************************
* The contents of this file are used with permission, subject to
* the Mozilla Public License Version 1.1 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
*****************************************************************************
*
* This file was created by Mason Wheeler. He can be reached for support at
* tech.turbu-rpg.com.
*****************************************************************************}
unit rsLexer;
interface
uses
Classes, SysUtils,
rsDefs;
type
TRsLexer = class
private
FText: string;
FStart, FEnd: PChar;
FLastRet: PChar;
FLineNum: integer;
function IsAlpha(C: Char): Boolean; inline;
function IsAlphaNumeric(C: Char): Boolean; inline;
function SubtractChars(last, first: PChar): integer; inline;
function GetText: string; inline;
function CreateToken(kind: TTokenKind): TToken;
function GetNextToken: TToken;
function IsNewline: boolean; inline;
procedure Advance; inline;
procedure DoNewline;
procedure SkipWhitespace;
function SkipComment: boolean;
function ReadIdentifier: TToken;
function ReadColon: TToken;
function ReadLT: TToken;
function ReadGT: TToken;
function ReadDot: TToken;
function ReadHex: TToken;
function ReadNum: TToken;
procedure ScanInt;
function ReadChar: TToken;
procedure ScanHex;
function ReadString: TToken;
function IsEof: boolean;
public
function Lex(const text: string): TTokenQueue; overload;
procedure Lex(var token: TToken); overload;
procedure Load(const text: string);
property EOF: boolean read IsEof;
end;
EEndOfFile = class(Exception);
implementation
uses
Generics.Collections, Windows,
Character;
{ TRsLexer }
procedure TRsLexer.Load(const text: string);
begin
assert(length(text) > 0);
FText := text;
FStart := addr(FText[1]);
FEnd := FStart;
FLastRet := FStart;
end;
function TRsLexer.GetText: string;
var
len: integer;
begin
len := SubtractChars(FEnd, FStart);
setLength(result, len);
if len > 0 then
System.Move(FStart^, result[1], len * sizeof(char));
end;
function TRsLexer.SubtractChars(last, first: PChar): integer;
begin
result := (nativeUInt(last) - nativeUInt(first)) div sizeof(char);
end;
function TRsLexer.CreateToken(kind: TTokenKind): TToken;
begin
result := TToken.Create(kind, FLineNum + 1, (SubtractChars(FStart, FlastRet) + 1),
SubtractChars(FEnd, FStart), FStart);
end;
procedure TRsLexer.DoNewline;
procedure NewLine;
begin
inc(FLineNum);
FLastRet := FEnd;
end;
begin
if FEnd^ = #13 then
begin
inc(FEnd);
if FEnd^ = #10 then
inc(FEnd);
newLine;
end
else if FEnd^ = #10 then
begin
inc(FEnd);
NewLine;
end
end;
function TRsLexer.IsNewline: boolean;
begin
result := CharInSet(FEnd^, [#13, #10]);
end;
procedure TRsLexer.Advance;
begin
if isNewline then
DoNewline
else if FEnd^ = #0 then
raise EEndOfFile.Create('')
else inc(FEnd);
end;
function TRsLexer.SkipComment: boolean;
var
line: integer;
// next: PChar;
begin
result := false;
// next := FEnd + 1;
if FEnd^ = '{' then
begin
result := true;
while not (FEnd^ = '}') do
Advance;
Advance; //see if this works
end
else if (FEnd^ = '(') and (FEnd[1] = '*') then
begin
(* test *)
result := true;
inc(FEnd, 2);
while not ((FEnd^ = '*') and (FEnd[1] = ')')) do
Advance;
end
else if (FEnd^ = '/') and (FEnd[1] = '/' ) then
begin
result := true;
line := FLineNum;
while line = FLineNum do
Advance;
end;
end;
procedure TRsLexer.SkipWhitespace;
begin
repeat
while CharInSet(FEnd^, [#32, #9, #13, #10]) do
Advance;
until not SkipComment;
FStart := FEnd;
inc(FEnd);
end;
function TRsLexer.IsAlpha(C: Char): Boolean;
begin
Result := TCharacter.IsLetter(C) or (C = '_');
end;
function TRsLexer.IsAlphaNumeric(C: Char): Boolean;
begin
Result := TCharacter.IsLetterOrDigit(C) or (C = '_');
end;
function TRsLexer.IsEof: boolean;
begin
result := FStart^ = #0;
end;
function TRsLexer.ReadIdentifier: TToken;
begin
while IsAlphaNumeric(FEnd^) do
inc(FEnd);
result := CreateToken(tkIdentifier);
result.kind := rsDefs.GetKeyword(UpperCase(result.origText));
end;
procedure TRsLexer.ScanHex;
begin
while CharInSet(FEnd^, ['0'..'9', 'a'..'f', 'A'..'F']) do
inc(FEnd);
end;
procedure TRsLexer.ScanInt;
begin
while CharInSet(FEnd^, ['0'..'9']) do
inc(FEnd);
end;
function TRsLexer.ReadHex: TToken;
begin
ScanHex;
result := CreateToken(tkInt);
end;
function TRsLexer.ReadNum: TToken;
begin
ScanInt;
if FEnd^ = '.' then
begin
inc(FEnd);
if FEnd^ = '.' then // to handle ranges such as "array [1..4]"
begin
dec(FEnd);
result := CreateToken(tkInt);
end
else begin
ScanInt;
result := CreateToken(tkFloat);
end;
end
else result := CreateToken(tkInt);
end;
function TRsLexer.ReadChar: TToken;
var
letter: char;
begin
if FEnd^ = '$' then
begin
inc(FEnd);
ScanHex;
end
else ScanInt;
inc(FStart);
if FStart < FEnd then
begin
word(letter) := StrToInt(GetText);
dec(FStart);
result := TToken.Create(tkChar, FLineNum + 1, SubtractChars(FStart, FLastRet) + 1, 1, FStart);
end
else begin
dec(FStart);
result := CreateToken(tkError);
end;
end;
function TRsLexer.ReadString: TToken;
var
next: PChar;
begin
while true do
begin
while FEnd^ <> '''' do
inc(FEnd);
next := FEnd + 1;
if next^ <> '''' then
begin
inc(FEnd);
break;
end
else inc(FEnd, 2);
end;
result := CreateToken(tkString);
end;
function TRsLexer.ReadColon: TToken;
begin
if FEnd^ = '=' then
begin
inc(FEnd);
result := CreateToken(tkAssign)
end
else result := CreateToken(tkColon);
end;
function TRsLexer.ReadLT: TToken;
var
kind: TTokenKind;
begin
case FEnd^ of
'>': kind := tkNotEqual;
'=': kind := tkLessEqual;
else kind := tkLessThan;
end;
if kind <> tkLessThan then
inc(FEnd);
result := CreateToken(kind);
end;
function TRsLexer.ReadGT: TToken;
begin
if FEnd^ = '=' then
begin
inc(FEnd);
result := CreateToken(tkGreaterEqual);
end
else result := CreateToken(tkGreaterThan);
end;
function TRsLexer.ReadDot: TToken;
begin
if FEnd^ = '.' then
begin
inc(FEnd);
result := CreateToken(tkDotDot);
end
else result := CreateToken(tkDot);
end;
function TRsLexer.GetNextToken: TToken;
var
kind: TTokenKind;
begin
try
SkipWhitespace;
except
on E: EEndOfFile do
begin
FStart := FEnd;
Exit(CreateToken(tkEof));
end;
end;
kind := tkNone;
case FStart^ of
';': kind := tkSem;
'=': kind := tkEquals;
'+': kind := tkPlus;
'-': kind := tkMinus;
'*': kind := tkTimes;
'/': kind := tkDivide;
',': kind := tkComma;
'(': kind := tkOpenParen;
')': kind := tkCloseParen;
'[': kind := tkOpenBracket;
']': kind := tkCloseBracket;
#0: kind := tkEof;
':': result := ReadColon;
'<': result := ReadLT;
'>': result := ReadGT;
'.': result := ReadDot;
'$': result := ReadHex;
'0'..'9': result := ReadNum;
'#': result := ReadChar;
'''': result := ReadString;
else if IsAlpha(FStart^) then
result := ReadIdentifier
else begin
FEnd := FStart + 1;
result := CreateToken(tkError);
end;
end;
if kind <> tkNone then
result := CreateToken(kind);
FStart := FEnd;
end;
function TRsLexer.Lex(const text: string): TTokenQueue;
var
token: TToken;
begin
//OutputDebugString('SAMPLING ON');
self.Load(text);
result := TQueue<TToken>.Create;
// result.OwnsObjects := true;
result.Capacity := length(text) div 4; //heuristic to avoid reallocations
repeat
token := GetNextToken;
result.Enqueue(token);
until token.Kind in [tkEOF, tkError];
//OutputDebugString('SAMPLING OFF');
end;
procedure TRsLexer.Lex(var token: TToken);
begin
token := GetNextToken;
end;
end.
|
unit ActionTest;
interface
uses dbTest, dbObjectTest, ObjectTest;
type
TActionTest = class (TdbObjectTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TAction = class(TObjectTest)
function InsertDefault: integer; override;
public
function InsertUpdateAction(const Id: integer; Code: Integer;
Name: string): integer;
constructor Create; override;
end;
implementation
uses DB, UtilConst, TestFramework, SysUtils;
{ TdbUnitTest }
procedure TActionTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'OBJECTS\Action\';
inherited;
end;
procedure TActionTest.Test;
var Id: integer;
RecordCount: Integer;
ObjectTest: TAction;
begin
ObjectTest := TAction.Create;
// Получим список
RecordCount := ObjectTest.GetDataSet.RecordCount;
// Вставка Бизнеса
Id := ObjectTest.InsertDefault;
try
// Получение данных о Бизнесе
with ObjectTest.GetRecord(Id) do
Check((FieldByName('Name').AsString = 'actExit-test'), 'Не сходятся данные Id = ' + IntToStr(Id));
Check(ObjectTest.GetDataSet.RecordCount = (RecordCount + 1), 'Количество записей не изменилось');
finally
ObjectTest.Delete(Id);
end;
end;
{ TActionTest }
constructor TAction.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_Object_Action';
spSelect := 'gpSelect_Object_Action';
spGet := 'gpGet_Object_Action';
end;
function TAction.InsertDefault: integer;
begin
result := InsertUpdateAction(0, -1, 'actExit-test');
inherited;
end;
function TAction.InsertUpdateAction;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inCode', ftInteger, ptInput, Code);
FParams.AddParam('inName', ftString, ptInput, Name);
result := InsertUpdate(FParams);
end;
initialization
// TestFramework.RegisterTest('Объекты', TActionTest.Suite);
end.
|
unit UViewScale;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2005 by Bradford Technologies, Inc. }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, UForms,
UDocView;
type
TDisplayZoom = class(TAdvancedForm)
btnOK: TButton;
btnCancel: TButton;
ImageScaleVal: TEdit;
lbScale: TLabel;
ImageScaleBar: TTrackBar;
ckbxSetDefault: TCheckBox;
Label1: TLabel;
Label2: TLabel;
procedure ImageScaleBarChange(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure ImageScaleValKeyPress(Sender: TObject; var Key: Char);
procedure ImageScaleValExit(Sender: TObject);
private
FSaveScale: Integer;
FDocViewer: TDocView;
public
constructor Create(AOwner: TComponent; docViewer: TDocView); reintroduce;
// procedure SaveChanges;
end;
var
DisplayZoom: TDisplayZoom;
implementation
uses
UGlobals, UUtil1, UMain;
{$R *.DFM}
{ TDisplayScale }
constructor TDisplayZoom.Create(AOwner: TComponent; docViewer: TDocView);
begin
inherited Create(AOwner);
FSaveScale := docViewer.ViewScale; //save for future ref
FDocViewer := docViewer; //save for live zooming
ImageScaleVal.text := IntToStr(FSaveScale); //setup the display
ImageScaleBar.Position := FSaveScale;
end;
procedure TDisplayZoom.ImageScaleBarChange(Sender: TObject);
begin
ImageScaleVal.text := IntToStr(ImageScaleBar.Position);
Main.tbtnZoomText.caption := ImageScaleVal.text;
FDocViewer.ViewScale := ImageScaleBar.Position;
end;
procedure TDisplayZoom.btnOKClick(Sender: TObject);
begin
if FSaveScale <> ImageScaleBar.Position then //only redaw if its been changed
FDocViewer.ViewScale := ImageScaleBar.Position; //set the new scale
if ckbxSetDefault.checked then
appPref_DisplayZoom := ImageScaleBar.Position;
end;
procedure TDisplayZoom.btnCancelClick(Sender: TObject);
begin
if FSaveScale <> ImageScaleBar.Position then //if view changed,
FDocViewer.ViewScale := FSaveScale; //reset to the original scale
end;
procedure TDisplayZoom.ImageScaleValKeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in [#08, '0'..'9']) then
key := char(#0);
end;
procedure TDisplayZoom.ImageScaleValExit(Sender: TObject);
var
scale: Integer;
begin
scale := StrToInt(ImageScaleVal.text);
if scale < 50 then
scale := 50
else if scale > 200 then
scale := 200;
ImageScaleVal.Text := IntToStr(scale); //reset edit box if necessary
Main.tbtnZoomText.Caption := ImageScaleVal.text;
ImageScaleBar.Position := scale; //set the track bar
FDocViewer.ViewScale := scale; //set the view
end;
end.
|
unit DepModelUnit;
interface
uses
ListUtilsUnit, DBUnit;
type
TDepItem = class(TCustomItem)
private
FSalary: Double;
FEmployCount: Integer;
function GetColor: Integer;
public
constructor Create(ADepId: Integer; ADemName: string; ASalary: Double;
AEmployCount: Integer); overload;
property Salary: Double read FSalary write FSalary;
property Color: Integer read GetColor;
property EmployCount: Integer read FEmployCount;
end;
TDepList = class(TCustomDBList)
public
function Load(ADBContr: TCustomDBController): Boolean; override;
function Save(ADBContr: TCustomDBController): Boolean; override;
end;
implementation
uses
ConstUnit, System.SysUtils, Vcl.Graphics;
{ TDepItem }
constructor TDepItem.Create(ADepId: Integer; ADemName: string; ASalary: Double;
AEmployCount: Integer);
begin
inherited Create(ADepId, ADemName);
FSalary := ASalary;
FEmployCount := AEmployCount;
end;
function TDepItem.GetColor: Integer;
begin
if Salary > 50000 then
Result := clBlue
else if Salary <= 0 then
Result := clRed
else
Result := clBlack;
end;
{ TDepList }
function TDepList.Load(ADBContr: TCustomDBController): Boolean;
var
StrSQL: string;
begin
Result := True;
Clear;
ADBContr.Open;
StrSQL := 'select d.' + FN_DEP_ID + ', d.' + FN_DEP_NAME + ', (select sum(e.' + FN_SALARY + ') ' +
'from ' + TN_EMPL + ' e ' +
'where e.' + FN_DEP_ID + ' = d.' + FN_DEP_ID + ') ' + FN_SALARY + ', ' +
'(select count(e.' + FN_EMPL_ID + ') ' +
'from ' + TN_EMPL + ' e ' +
'where e.' + FN_DEP_ID + ' = d.' + FN_DEP_ID + ') EMPL_COUNT ' +
'from ' + TN_DEP + ' d ' +
'order by ' + FN_SALARY + ' desc, ' + FN_DEP_NAME + ' ';
StrSQL := 'select d.DEPARTMENT_ID, d.DEPARTMENT_NAME, Cast((select sum(e.SALARY) SALARY from EMPLOYEES e where e.DEPARTMENT_ID = d.DEPARTMENT_ID) as numeric(8, 2)) SALARY , '
+ '(select count(e.EMPLOYEE_ID) EMPL_COUNT from EMPLOYEES e where e.DEPARTMENT_ID = d.DEPARTMENT_ID) EMPL_COUNT from DEPARTMENTS d order by SALARY desc, DEPARTMENT_NAME';
try
if ADBContr.SelectSQL(StrSQL) then
while not ADBContr.SQLQuery.Eof do
begin
try
Add(TDepItem.Create(
ADBContr.SQLQuery.FieldByName(FN_DEP_ID).AsInteger,
ADBContr.SQLQuery.FieldByName(FN_DEP_NAME).AsString,
StrToFloatDef(ADBContr.SQLQuery.Fields[2].AsString, 0),
StrToIntDef(ADBContr.SQLQuery.Fields[3].AsString, 0)));
except
on E: Exception do
begin
ADBContr.Log.Error('Error TDepList.Load: ' + E.Message);
Result := False;
end;
end;
ADBContr.SQLQuery.Next;
end;
finally
ADBContr.Close;
end;
end;
function TDepList.Save(ADBContr: TCustomDBController): Boolean;
begin
//Реализация не требуется
Result := True;
end;
end.
|
unit U_DtmFatura;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqldb, db, FileUtil, U_Utils, U_DtmPrincipal,
U_Fatura;
type
{ TDtmFatura }
TDtmFatura = class(TDataModule)
qryFatura: TSQLQuery;
qryPesquisa: TSQLQuery;
qryPesquisaANO: TLongintField;
qryPesquisaCOD_COBRANCA: TLongintField;
qryPesquisaCOD_FATURA: TLongintField;
qryPesquisaCPF: TStringField;
qryPesquisaDATA_GERACAO: TDateTimeField;
qryPesquisaDATA_PAGAMENTO: TDateTimeField;
qryPesquisaMES: TLongintField;
qryPesquisaMesAno: TStringField;
qryPesquisaVALOR: TBCDField;
qryPesquisaVENCIMENTO: TDateField;
private
public
function salvarFatura(pFatura:TFatura; pControle:TControle; pCommit:Boolean = false):boolean;
function getFatura(pCpf:String; pMes,pAno:Integer):TFatura;
function deleteFatura(pCpf:String; pMes,pAno:Integer; pCommit:Boolean = false):Boolean;
function abrePesquisa(pCpf:String):Boolean;
end;
var
DtmFatura: TDtmFatura;
implementation
{$R *.lfm}
{ TDtmFatura }
function TDtmFatura.salvarFatura(pFatura: TFatura; pControle: TControle;
pCommit: Boolean): boolean;
begin
Result := False;
try
qryFatura.Close;
if (pControle = tpNovo) then
begin
if getFatura(pfatura.cpf, pfatura.mes,pfatura.ano) <> nil then
begin
MsgAlerta('Já existe uma fatura com esse Mês/Ano');
Exit;
end;
qryFatura.SQL.Text:= ' INSERT INTO FATURA (CPF, COD_COBRANCA, DATA_GERACAO, DATA_PAGAMENTO, VALOR, MES, ANO, VENCIMENTO) '#13+
' VALUES (:CPF, :COD_COBRANCA, CURRENT_DATE, :DATA_PAGAMENTO, :VALOR, :MES, :ANO, :VENCIMENTO) ';
if pfatura.codCobranca > 0 then
qryFatura.ParamByName('COD_COBRANCA').AsInteger := pfatura.codCobranca;
end
else
begin
qryFatura.SQL.Text:= 'UPDATE FATURA '#13+
'SET DATA_PAGAMENTO = :DATA_PAGAMENTO, '#13+
' VALOR = :VALOR, '#13+
' VENCIMENTO = :VENCIMENTO '#13+
'WHERE CPF = :CPF AND '#13+
' MES = :MES AND '#13+
' ANO = :ANO ';
end;
qryFatura.ParamByName('CPF').AsString := pfatura.cpf;
if pfatura.dataPagamento > 0 then
qryFatura.ParamByName('DATA_PAGAMENTO').AsDateTime := pfatura.dataPagamento;
qryFatura.ParamByName('VENCIMENTO').AsDateTime := pfatura.vencimento;
qryFatura.ParamByName('VALOR').AsFloat := pfatura.valor;
qryFatura.ParamByName('MES').AsInteger := pfatura.mes;
qryFatura.ParamByName('ANO').AsInteger := pfatura.ano;
qryFatura.ExecSQL;
if pCommit then
DtmPrincipal.FBTrans.CommitRetaining;
Result := True;
except
on E:exception do
begin
Result := False;
DtmPrincipal.FBTrans.RollbackRetaining;
MsgErro('Ocorreu um erro ao salvar a Fatura',E);
end;
end;
end;
function TDtmFatura.getFatura(pCpf: String; pMes, pAno: Integer): TFatura;
var
Fatura : TFatura;
begin
try
qryFatura.Close;
qryFatura.SQL.Text:= 'SELECT FAT.COD_FATURA, '#13+
' FAT.CPF, '#13+
' FAT.COD_COBRANCA, '#13+
' FAT.DATA_GERACAO, '#13+
' FAT.DATA_PAGAMENTO, '#13+
' FAT.VALOR, '#13+
' FAT.MES, '#13+
' FAT.ANO, '#13+
' (LPAD(FAT.MES, 2, ''0'') || ''/'' || FAT.ANO) AS MESANO, '#13+
' FAT.VENCIMENTO '#13+
'FROM FATURA FAT '#13+
'WHERE FAT.CPF = :CPF AND FAT.MES = :MES AND FAT.ANO = :ANO ';
qryFatura.ParamByName('CPF').AsString:= pCpf;
qryFatura.ParamByName('MES').AsInteger:= pMes;
qryFatura.ParamByName('ANO').AsInteger:= pAno;
qryFatura.Open;
if not (qryFatura.IsEmpty) then
begin
Fatura := TFatura.Create;
Fatura.codigo := qryFatura.FieldByName('COD_Fatura').AsInteger;
Fatura.cpf := qryFatura.FieldByName('CPF').AsString;
Fatura.codCobranca := qryFatura.FieldByName('COD_COBRANCA').AsInteger;
Fatura.dataGeracao := qryFatura.FieldByName('DATA_GERACAO').AsDateTime;
Fatura.dataPagamento := qryFatura.FieldByName('DATA_PAGAMENTO').AsDateTime;
Fatura.valor := qryFatura.FieldByName('VALOR').AsFloat;
Fatura.mes := qryFatura.FieldByName('MES').AsInteger;
Fatura.ano := qryFatura.FieldByName('ANO').AsInteger;
Fatura.vencimento := qryFatura.FieldByName('VENCIMENTO').AsDateTime;
Result := Fatura;
end
else
Result := nil;
except
on E:exception do
begin
Result := nil;
MsgErro('Ocorreu um erro ao pesquisar a Fatura',E);
end;
end;
end;
function TDtmFatura.deleteFatura(pCpf: String; pMes, pAno: Integer;
pCommit: Boolean): Boolean;
begin
try
qryFatura.Close;
qryFatura.SQL.Text:='SELECT CPF FROM Fatura WHERE CPF = :CPF AND MES = :MES AND ANO = :ANO AND DATA_PAGAMENTO IS NOT NULL ';
qryFatura.ParamByName('CPF').AsString:= pCpf;
qryFatura.ParamByName('MES').AsInteger:= pMes;
qryFatura.ParamByName('ANO').AsInteger:= pAno;
qryFatura.Open;
if not qryFatura.IsEmpty then
begin
MsgAlerta('Débito está pago, exclusão não permitida!');
Result := False;
Exit;
end;
qryFatura.Close;
qryFatura.SQL.Text:='DELETE FROM Fatura WHERE CPF = :CPF AND MES = :MES AND ANO = :ANO ';
qryFatura.ParamByName('CPF').AsString:= pCpf;
qryFatura.ParamByName('MES').AsInteger:= pMes;
qryFatura.ParamByName('ANO').AsInteger:= pAno;
qryFatura.ExecSQL;
if pCommit then
DtmPrincipal.FBTrans.CommitRetaining;
Result := True;
except
on E:exception do
begin
Result := False;
DtmPrincipal.FBTrans.RollbackRetaining;
MsgErro('Ocorreu um erro ao deletar a Fatura.',E);
end;
end;
end;
function TDtmFatura.abrePesquisa(pCpf: String): Boolean;
begin
try
qryPesquisa.Close;
qryPesquisa.SQL.Text:= 'SELECT FAT.COD_FATURA, '#13+
' FAT.CPF, '#13+
' FAT.COD_COBRANCA, '#13+
' FAT.DATA_GERACAO, '#13+
' FAT.DATA_PAGAMENTO, '#13+
' FAT.VALOR, '#13+
' FAT.MES, '#13+
' FAT.ANO, '#13+
' (LPAD(FAT.MES, 2, ''0'') || ''/'' || FAT.ANO) AS MESANO, '#13+
' FAT.VENCIMENTO '#13+
'FROM FATURA FAT ';
if (pCpf <> '') then
begin
qryPesquisa.SQL.Text:= qryPesquisa.SQL.Text +#13+ 'WHERE CPF = :CPF';
qryPesquisa.ParamByName('CPF').AsString:= pCpf;
end;
qryPesquisa.SQL.Text:= qryPesquisa.SQL.Text +#13+ 'ORDER BY CPF, VENCIMENTO DESC';
qryPesquisa.Open;
Result := not qryPesquisa.IsEmpty;
except
on E:exception do
begin
Result := False;
DtmPrincipal.FBTrans.RollbackRetaining;
MsgErro('Ocorreu um erro ao Abrir Pesquisa de fatura.',E);
end;
end;
end;
end.
|
unit UFormEditWordFile;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
Vcl.Menus,UMainDataModule, System.ImageList, Vcl.ImgList;
type
TFormFileEdit = class(TForm)
Panel1: TPanel;
RichEdit1: TRichEdit;
Title_Panel: TPanel;
GroupBox1: TGroupBox;
ListBox1: TListBox;
GroupBox2: TGroupBox;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
RadioButton3: TRadioButton;
RadioButton4: TRadioButton;
RadioButton5: TRadioButton;
RadioButton6: TRadioButton;
Pop_RichEdit: TPopupMenu;
Pop_clear: TMenuItem;
N2: TMenuItem;
Pop_paste: TMenuItem;
N4: TMenuItem;
Pop_Save: TMenuItem;
ImageList1: TImageList;
N6: TMenuItem;
Pop_Delete: TMenuItem;
StatusBar1: TStatusBar;
procedure FormCreate(Sender: TObject);
procedure RichEdit1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Pop_clearClick(Sender: TObject);
procedure Pop_pasteClick(Sender: TObject);
procedure Pop_SaveClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure ListBox1Click(Sender: TObject);
procedure Pop_DeleteClick(Sender: TObject);
private
{ Private declarations }
FileType:String;
WorkFaceId:integer;
workFaceName:String;
FileNumber:integer;
RDButton : Array [0..5] of TRadioButton;
procedure InitForm;
procedure RedioBoxClick(Sender:TObject);
procedure DispRichEditPop(Px,Py:Integer);//显示RichEdit 控制的工具栏
procedure OptionTip(Str:String);
procedure ReadDataFromDataBase(List:TListbox);
procedure ReadDataFromFileName(List:TListbox);
function RetrunFileTypeName(Value:integer):String;
function Searchfile(List:TListBox;path,FileTail: string): Boolean;
procedure setRadioButtonSelected(Value:integer);
procedure RichEditLineSpacing( //设置编辑框的行距
mRichEdit: TRichEdit; //Rich编辑框
mLineSpacingRule: Byte //行距 0~2
);
public
{ Public declarations }
procedure SetWorkFaceInfo(id:integer;WName:string);
procedure ReadFileNameFillListBox;
end;
function CreateWorkFaceFileName(AHandle:THandle;ACaption:string;Wid,Hi:integer):THandle;stdcall;
var
FormFileEdit: TFormFileEdit;
implementation
{$R *.dfm}
uses Lu_Public_BasicModual,RichEdit;
function CreateWorkFaceFileName(AHandle:THandle;ACaption:string;Wid,Hi:integer):THandle;stdcall;
begin
if Assigned(FormFileEdit) then FreeAndNil(FormFileEdit);
Application.Handle :=AHandle;
FormFileEdit:=TFormFileEdit.Create(nil);
try
with FormFileEdit do begin
Caption:=ACaption;
WindowState:= wsNormal;
ParentWindow:=Ahandle;
if Hi >Height then
Top :=Round((Hi-Height)/3) else Top :=0;
if Wid> Width then
Left:=Round((Wid-Width)/2) else Left:=0;
Show;
SetFocus;
Result:=FormFileEdit.Handle;//函数值
end ;
except
FreeAndNil(FormFileEdit);
end;
end;
{ TForm2 }
procedure TFormFileEdit.DispRichEditPop(Px, Py: Integer);
begin
Pop_RichEdit.Popup(px,py);
end;
procedure TFormFileEdit.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if Assigned(FormFileEdit) then
FreeAndNil(FormFileEdit);
end;
procedure TFormFileEdit.FormCreate(Sender: TObject);
begin
WorkFaceId:=0;
FileNumber:=0;
end;
procedure TFormFileEdit.FormShow(Sender: TObject);
begin
PubLic_Basic.InitStatusBar(self.StatusBar1);
initForm;
end;
procedure TFormFileEdit.InitForm;
var
i:integer;
begin
FileType:='GZMBASIC';
RDButton[0]:= RadioButton1; RDButton[1]:= RadioButton2;RDButton[2]:= RadioButton3;
RDButton[3]:= RadioButton4; RDButton[4]:= RadioButton5;RDButton[5]:= RadioButton6;
for I := 0 to 5 do
RDButton[i].OnClick :=RedioBoxClick;
RichEdit1.Clear ;
MainDataModule.ReadPublicUsedMkInfoFromFile;
SetWorkFaceInfo(public_Basic.StrToInt_lu( MainDataModule.WorkFace_id) ,MainDataModule.WorkFace_Name);
end;
procedure TFormFileEdit.ListBox1Click(Sender: TObject);
var
s_temp:Str_DT_array;
C1:integer;
sql:string;
begin
s_temp:=Public_Basic.split(listBox1.items[listBox1.itemindex],'_',C1);
if s_temp[0]='' then exit;
FileNumber:=Public_Basic.StrToInt_lu(s_temp[0]) ;
setRadioButtonSelected(FileNumber);
MainDataModule.ReadRichTextFromDataBase(RichEdit1.Lines,fileType,'rtf',workfaceid,FileNumber,-1,-1);
end;
procedure TFormFileEdit.OptionTip(Str: String);
begin
self.StatusBar1.Panels[0].Text :=str;
end;
procedure TFormFileEdit.Pop_clearClick(Sender: TObject);
begin
RichEdit1.Clear ;
end;
procedure TFormFileEdit.Pop_DeleteClick(Sender: TObject);
var
OutStr:string;
begin
OutStr:='你确认要删除【'+RetrunFileTypeName(FileNumber)+'】资料吗?';
if (WorkFaceId>0) and (FileNumber>0) then
if Application.MessageBox(pchar(OutStr), '提示', MB_YESNO + MB_DEFBUTTON2+ MB_ICONQUESTION) = IDYES then
if MainDataModule.DeleteRichTextFile(RichEdit1.Lines,Filetype,'rtf',WorkFaceId,FileNumber,-1,-1) then begin
OptionTip('数据删除成功!');
ReadFileNameFillListBox;
Richedit1.Clear ;
end;
end;
procedure TFormFileEdit.Pop_pasteClick(Sender: TObject);
begin
Richedit1.PasteFromClipboard;
end;
procedure TFormFileEdit.Pop_SaveClick(Sender: TObject);
var
OutStr:string;
begin
OutStr:='你确认是对【'+RetrunFileTypeName(FileNumber)+'】进行资料补录吗?';
if FileNumber=101 then begin
RichEdit1.SelectAll ;
RichEditLineSpacing(RichEdit1,0);
RichEdit1.SelAttributes.Size :=9;
end else begin
RichEdit1.SelectAll ;
RichEditLineSpacing(RichEdit1,1);
RichEdit1.SelAttributes.Size :=12;
end;
if (WorkFaceId>0) and (FileNumber>0) then
if Application.MessageBox(pchar(OutStr), '提示', MB_YESNO + MB_DEFBUTTON2+ MB_ICONQUESTION) = IDYES then
if MainDataModule.RichTextSaveToDataBase(RichEdit1.Lines,Filetype,'rtf',WorkFaceId,FileNumber,-1,-1) then begin
OptionTip('数据保存成功!');
ReadFileNameFillListBox;
end;
end;
procedure TFormFileEdit.ReadDataFromDataBase(List: TListbox);
var
Mydataet:TMyDataSet;
itag:integer;
sql,temp:string;
begin
Mydataet:=TMyDataSet.Create(nil);
Mydataet.MySqlConnection :=MainDataModule.ExConn;
List.Clear ;
try
Mydataet.Close ;
Sql:=' select Num_bh from FileDataBase where FileType ='''+ FileType+''' and WorkFaceid=' +
IntToStr(WorkFaceId) ;
Mydataet.CommandText :=sql;
Mydataet.Open ;
while not Mydataet.Eof do begin
itag:=Mydataet.FieldByName('Num_bh').AsInteger;
List.Items.Add(IntTostr(itag)+'_'+ RetrunFileTypeName(itag));
Mydataet.Next ;
end;
finally
Mydataet.Close ;
FreeAndNil(Mydataet);
end;
end;
procedure TFormFileEdit.ReadDataFromFileName(List: TListbox);
var
fileName,textString:Ansistring;
DirName:Ansistring;
Dll_Path:AnsiString;
begin
Dll_Path:=Public_Basic.Get_MyModulePath;
DirName:=DLL_path+'\InputData\WorkDace_'+IntTostr(WorkFaceId);
Searchfile(List,DirName,'rtf' );
end;
procedure TFormFileEdit.ReadFileNameFillListBox;
begin
if Uppercase(MainDataModule.DataType)='ACCESS' then begin
ReadDataFromFileName(ListBox1);
end else begin
ReadDataFromDataBase(ListBox1);
end;
end;
Procedure TFormFileEdit.RedioBoxClick(Sender: TObject);
begin
FileNumber:= (sender as TRadioButton).Tag;
RichEdit1.Clear;
end;
function TFormFileEdit.RetrunFileTypeName(Value: integer): String;
begin
if value=101 then begin
Result:='工作面概述与地质说明书(表格)';
end else if value=102 then begin
Result:='顶底板岩层岩性组合结构分析';
end else if value=103 then begin
Result:='地质结构说明';
end else if value=201 then begin
Result:='正常支护方式';
end else if value=202 then begin
Result:='特殊支护方式';
end else if value=203 then begin
Result:='确定支护强度';
end else begin
Result:='';
end;
end;
procedure TFormFileEdit.RichEdit1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
pt:Tpoint;
begin
if Button=mbRight then begin
pt:= RichEdit1.ClientToScreen(Point(0,0));
DispRichEditPop(pt.X+x,pt.Y +y);
end;
end;
procedure TFormFileEdit.RichEditLineSpacing(mRichEdit: TRichEdit;
mLineSpacingRule: Byte);
var
vParaFormat2: ParaFormat2;
begin
if not Assigned(mRichEdit) then Exit;
FillChar(vParaFormat2, SizeOf(vParaFormat2), 0);
vParaFormat2.cbSize := SizeOf(ParaFormat2);
vParaFormat2.dwMask := PFM_LINESPACING;
vParaFormat2.bLineSpacingRule := mLineSpacingRule;
vParaFormat2.dyLineSpacing := Ord(True);
mRichEdit.Perform(EM_SETPARAFORMAT, 0, Longint(@vParaFormat2));
end;
function TFormFileEdit.Searchfile(List:TListBox;path,FileTail: string): Boolean;
var
SearchRec: TSearchRec;
found: integer;
fileName:string;
s_temp,s2:Str_DT_array;
C1,filebh:integer;
begin
Result := False;
List.Clear ;
found := FindFirst(path + '\' + '*.'+FileTail, faAnyFile, SearchRec);
while found = 0 do begin
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') and
(SearchRec.Attr <> faDirectory) then begin
fileName:=ExtractFileName(SearchRec.Name) ;
s_temp:=Public_Basic.split(fileName,'_',C1);
if UpperCase(S_Temp[0])=FileType then begin
s2:=Public_Basic.split(s_temp[1],'.',C1);
filebh:= Public_Basic.StrToInt_lu(s2[0]);
if filebh >100 then
List.Items.Add(intToStr(filebh)+'_'+RetrunFileTypeName(filebh)) ;
end;
end;
found := FindNext(SearchRec);
Result:=True;
end;
FindClose(SearchRec);
end;
procedure TFormFileEdit.setRadioButtonSelected(Value: integer);
var
i:integer;
begin
for I := 0 to 5 do
if RDButton[i].Tag =value then begin
RDButton[i].Checked :=true;
end else begin
RDButton[i].Checked :=False;
end;
end;
procedure TFormFileEdit.SetWorkFaceInfo(id: integer; WName: string);
begin
WorkFaceId:=id;
workFaceName:= WName;
Title_Panel.Caption :='现在正在对【'+workFaceName+'】相关资料进行补录' ;
ReadFileNameFillListBox;
end;
end.
|
unit HttpHeaderExtracter;
interface
uses
HttpMessage, Classes, SysUtils;
type
(*****************************************************************************
** 类 名:THttpHeaderExtracter
** 功能描述:HTTP报文首部提取器
** 编写日期:2010-09-26
*****************************************************************************)
THttpHeaderExtracter = class
private
FNextIndex: Integer;
FBufStr : String;
FLen : Integer;
public
constructor Create(aHttpMsgStr: String);
procedure Reset;
function NextHeaderName: String;
function NextHeaderValue: String;
function GetHttpHeaders: RHttpMessageHeaders;
function ToString: String;
end;
implementation
{ THttpHeaderExtracter }
constructor THttpHeaderExtracter.Create(aHttpMsgStr: String);
begin
FBufStr := aHttpMsgStr;
FLen := Length(FBufStr);
Self.Reset;
end;
function THttpHeaderExtracter.GetHttpHeaders: RHttpMessageHeaders;
var
HeaderNameList: TList;
NextName: String;
I: Integer;
begin
HeaderNameList := TList.Create;
NextName := NextHeaderName;
while NextName <> '' do
begin
HeaderNameList.Add(PChar(NextName));
NextName := NextHeaderName;
NextHeaderValue;
end;
Result.Count := HeaderNameList.Count;
SetLength(Result.Names, Result.Count);
SetLength(Result.Values, Result.Count);
Self.Reset;
for I := 0 to Result.Count - 1 do
begin
Result.Names[I] := Self.NextHeaderName;
Result.Values[I]:= Self.NextHeaderValue;
end;
end;
function THttpHeaderExtracter.NextHeaderName: String;
var
TempName: String;
begin
TempName := '';
// if FNextIndex = 1 then NextLine;
while (FNextIndex <= FLen)
and (FBufStr[FNextIndex] <> #13) and (FBufStr[FNextIndex] <> #10) do
begin
if FBufStr[FNextIndex] = ':' then
begin
Inc(FNextIndex);
while FBufStr[FNextIndex] = ' ' do
begin
Inc(FNextIndex);
end;
Result := TempName;
Exit;
end;
TempName := TempName + FBufStr[FNextIndex];
Inc(FNextIndex);
end;
if FNextIndex >= FLen then
begin
Result := '';
Exit;
end;
while (FNextIndex <= FLen) and ((FBufStr[FNextIndex] = #13) or (FBufStr[FNextIndex] = #10)) do
begin
Inc(FNextIndex);
end;
Result := NextHeaderName;
end;
function THttpHeaderExtracter.NextHeaderValue: String;
var
TempValue: String;
begin
TempValue := '';
while (FNextIndex <= FLen)
and (FBufStr[FNextIndex] <> #13) and (FBufStr[FNextIndex] <> #10) do
begin
TempValue := TempValue + FBufStr[FNextIndex];
Inc(FNextIndex);
end;
if FNextIndex >= FLen then
begin
Result := '';
Exit;
end;
Result := TempValue;
end;
procedure THttpHeaderExtracter.Reset;
begin
FNextIndex := 1;
end;
function THttpHeaderExtracter.ToString: String;
var
NextIndex: Integer;
begin
{ 去掉第一行 }
NextIndex := 1;
while (NextIndex <= FLen) and (FBufStr[NextIndex] <> #13)
and (FBufStr[NextIndex] <> #10) do
begin
Inc(NextIndex);
end;
if NextIndex > FLen then
begin
Result := '';
Exit;
end;
NextIndex := NextIndex + 2;
{ 从第二行开始的部分作为首部内容返回 }
while (NextIndex <= FLen) do
begin
if (FBufStr[NextIndex] = #13) then
begin
Result := Result + #13#10;
Inc(NextIndex, 2);
if (NextIndex > FLen) or (FBufStr[NextIndex] = #13)then
begin
Exit;
end;
end;
Result := Result + FBufStr[NextIndex];
Inc(NextIndex);
end;
end;
end.
|
unit BaseMemStream;
interface
uses
BaseStream;
type
{ TCustomMemoryStream abstract class }
TCustomMemoryStream = class(TStream)
private
FMemory: Pointer;
FSize: Longint;
FPosition: Longint;
protected
procedure SetPointer(Ptr: Pointer; Size: Longint);
public
function Read(var Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
procedure SaveToStream(Stream: TStream);
//procedure SaveToFile(const FileName: string);
property Memory: Pointer read FMemory;
end;
{ TMemoryStream }
TMemoryStream = class(TCustomMemoryStream)
private
FCapacity: Longint;
procedure SetCapacity(NewCapacity: Longint);
protected
function Realloc(var NewCapacity: Longint): Pointer; virtual;
property Capacity: Longint read FCapacity write SetCapacity;
public
destructor Destroy; override;
procedure Clear;
procedure LoadFromStream(Stream: TStream);
//procedure LoadFromFile(const FileName: string);
procedure SetSize(NewSize: Longint); override;
function Write(const Buffer; Count: Longint): Longint; override;
end;
implementation
uses
RTLConsts,
SysUtils;
{ TCustomMemoryStream }
procedure TCustomMemoryStream.SetPointer(Ptr: Pointer; Size: Longint);
begin
FMemory := Ptr;
FSize := Size;
end;
function TCustomMemoryStream.Read(var Buffer; Count: Longint): Longint;
begin
if (FPosition >= 0) and (Count >= 0) then
begin
Result := FSize - FPosition;
if Result > 0 then
begin
if Result > Count then Result := Count;
Move(Pointer(Longint(FMemory) + FPosition)^, Buffer, Result);
Inc(FPosition, Result);
Exit;
end;
end;
Result := 0;
end;
function TCustomMemoryStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
case Origin of
soFromBeginning: FPosition := Offset;
soFromCurrent: Inc(FPosition, Offset);
soFromEnd: FPosition := FSize + Offset;
end;
Result := FPosition;
end;
procedure TCustomMemoryStream.SaveToStream(Stream: TStream);
begin
if FSize <> 0 then Stream.WriteBuffer(FMemory^, FSize);
end;
(*//
procedure TCustomMemoryStream.SaveToFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
//*)
{ TMemoryStream }
const
MemoryDelta = $2000; { Must be a power of 2 }
destructor TMemoryStream.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TMemoryStream.Clear;
begin
SetCapacity(0);
FSize := 0;
FPosition := 0;
end;
procedure TMemoryStream.LoadFromStream(Stream: TStream);
var
Count: Longint;
begin
Stream.Position := 0;
Count := Stream.Size;
SetSize(Count);
if Count <> 0 then Stream.ReadBuffer(FMemory^, Count);
end;
(*//
procedure TMemoryStream.LoadFromFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, SysUtils.fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
//*)
procedure TMemoryStream.SetCapacity(NewCapacity: Longint);
begin
SetPointer(Realloc(NewCapacity), FSize);
FCapacity := NewCapacity;
end;
procedure TMemoryStream.SetSize(NewSize: Longint);
var
OldPosition: Longint;
begin
OldPosition := FPosition;
SetCapacity(NewSize);
FSize := NewSize;
if OldPosition > NewSize then Seek(0, soFromEnd);
end;
function TMemoryStream.Realloc(var NewCapacity: Longint): Pointer;
begin
if (NewCapacity > 0) and (NewCapacity <> FSize) then
NewCapacity := (NewCapacity + (MemoryDelta - 1)) and not (MemoryDelta - 1);
Result := Memory;
if NewCapacity <> FCapacity then
begin
if NewCapacity = 0 then
begin
FreeMem(Memory);
Result := nil;
end else
begin
if Capacity = 0 then
GetMem(Result, NewCapacity)
else
ReallocMem(Result, NewCapacity);
if Result = nil then
begin
raise EStreamError.CreateRes(@SMemoryStreamError);
end;
end;
end;
end;
function TMemoryStream.Write(const Buffer; Count: Longint): Longint;
var
Pos: Longint;
begin
if (FPosition >= 0) and (Count >= 0) then
begin
Pos := FPosition + Count;
if Pos > 0 then
begin
if Pos > FSize then
begin
if Pos > FCapacity then
SetCapacity(Pos);
FSize := Pos;
end;
System.Move(Buffer, Pointer(Longint(FMemory) + FPosition)^, Count);
FPosition := Pos;
Result := Count;
Exit;
end;
end;
Result := 0;
end;
end.
|
unit WVDBBinders;
interface
uses SysUtils, Classes, DataTypes, WorkViews, DB;
type
TWVDBBinder = class;
TWVDBBinding = class;
TWVDBBindingEvent = procedure (Binding : TWVDBBinding; ADBField : TField; AWVField : TWVField ) of object;
TWVDBBinding = class(TCollectionItem)
private
FBinder : TWVDBBinder;
FFieldName: string;
FWVFieldName: string;
FDataPresentType: TDataPresentType;
FDataPresentParam: string;
FOnBinding: TWVDBBindingEvent;
procedure UpdateBinding;
protected
function GetDisplayName: string; override;
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
property Binder : TWVDBBinder read FBinder;
published
property FieldName : string read FFieldName write FFieldName;
property WVFieldName : string read FWVFieldName write FWVFieldName;
property DataPresentType : TDataPresentType read FDataPresentType write FDataPresentType;
property DataPresentParam : string read FDataPresentParam write FDataPresentParam;
property OnBinding : TWVDBBindingEvent read FOnBinding write FOnBinding;
end;
{ TODO : 在运行的时候修改WorkView里面的字段,TWVDBBinder无法自动更新。 }
TWVDBBinder = class(TComponent)
private
FDataSource: TDataSource;
FWorkView: TWorkView;
FDataset: TDataset;
FFieldName: string;
FField: TWVField;
FBindings: TCollection;
FHideUnbindingFields: Boolean;
FOnBinding: TNotifyEvent;
procedure SetDataSource(const Value: TDataSource);
procedure SetWorkView(const Value: TWorkView);
procedure UpdateField;
procedure UpdateDataset;
procedure SetDataset(const Value: TDataset);
procedure SetFieldName(const Value: string);
procedure LMWorkViewNotify(var Message:TWVMessage); message LM_WorkViewNotify;
procedure SetBindings(const Value: TCollection);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Loaded; override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy;override;
procedure UpdateBindings;
property Dataset : TDataset read FDataset write SetDataset;
property Field : TWVField read FField;
published
property DataSource : TDataSource read FDataSource write SetDataSource;
property WorkView : TWorkView read FWorkView write SetWorkView;
property FieldName : string read FFieldName write SetFieldName;
property Bindings : TCollection read FBindings write SetBindings;
property HideUnbindingFields : Boolean read FHideUnbindingFields write FHideUnbindingFields;
property OnBinding : TNotifyEvent read FOnBinding write FOnBinding;
end;
implementation
type
TOwnedCollectionAccess = class(TOwnedCollection);
{ TWVDBBinder }
constructor TWVDBBinder.Create(AOwner: TComponent);
begin
inherited;
FBindings := TOwnedCollection.Create(Self, TWVDBBinding);
end;
destructor TWVDBBinder.Destroy;
begin
FreeAndNil(FBindings);
inherited;
end;
procedure TWVDBBinder.LMWorkViewNotify(var Message: TWVMessage);
begin
if (Message.Field=Field) and (Field<>nil) then
begin
case Message.NotifyCode of
WV_FieldValueChanged : UpdateDataset;
end;
end;
end;
procedure TWVDBBinder.Loaded;
begin
inherited;
UpdateField;
end;
procedure TWVDBBinder.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation=opRemove then
begin
if AComponent=FDataSource then
FDataSource := nil
else if AComponent=FWorkView then
FWorkView := nil
else if AComponent=FDataset then
FDataset := nil;
end;
end;
procedure TWVDBBinder.SetBindings(const Value: TCollection);
begin
FBindings.Assign(Value);
end;
procedure TWVDBBinder.SetDataset(const Value: TDataset);
begin
if FDataset <> Value then
begin
FDataset := Value;
if FDataset<>nil then
FDataset.FreeNotification(Self);
if FDataSource<>nil then
FDataSource.Dataset := Dataset;
UpdateBindings;
end;
end;
procedure TWVDBBinder.SetDataSource(const Value: TDataSource);
begin
if FDataSource <> Value then
begin
FDataSource := Value;
if FDataSource<>nil then
begin
FDataSource.FreeNotification(Self);
FDataSource.Dataset := Dataset;
end;
end;
end;
procedure TWVDBBinder.SetFieldName(const Value: string);
begin
if FFieldName <> Value then
begin
FFieldName := Value;
UpdateField;
end;
end;
procedure TWVDBBinder.SetWorkView(const Value: TWorkView);
begin
if FWorkView <> Value then
begin
if FWorkView<>nil then
FWorkView.RemoveClient(Self);
FWorkView := Value;
if FWorkView<>nil then
FWorkView.AddClient(Self);
UpdateField;
end;
end;
procedure TWVDBBinder.UpdateBindings;
var
I : Integer;
Binding : TWVDBBinding;
begin
if (Dataset<>nil) and (WorkView<>nil) then
begin
if HideUnbindingFields then
for I:=0 to Dataset.FieldCount-1 do
begin
Dataset.Fields[I].Visible := False;
end;
for I:=0 to Bindings.Count-1 do
begin
Binding := TWVDBBinding(Bindings.Items[I]);
Binding.UpdateBinding;
end;
if Assigned(OnBinding) then
OnBinding(Self);
end;
end;
procedure TWVDBBinder.UpdateDataset;
var
Obj : TObject;
begin
Obj := nil;
if (FField<>nil) and (FField.DataType=kdtObject) then
Obj := FField.Data.AsObject;
if Obj is TDataset then
Dataset := TDataset(Obj) else
Dataset := nil;
end;
procedure TWVDBBinder.UpdateField;
begin
// Find Field
FField := nil;
if (FWorkView<>nil) and (FFieldName<>'') and not (csLoading in ComponentState) then
FField := FWorkView.FindField(FFieldName);
UpdateDataset;
end;
{ TWVDBBinding }
constructor TWVDBBinding.Create(Collection: TCollection);
begin
inherited;
FBinder := TWVDBBinder(TOwnedCollectionAccess(Collection).GetOwner);
end;
procedure TWVDBBinding.Assign(Source: TPersistent);
begin
inherited;
if Source is TWVDBBinding then
with TWVDBBinding(Source) do
begin
FFieldName := Self.FFieldName;
FWVFieldName := Self.FWVFieldName;
end else
inherited;
end;
procedure TWVDBBinding.UpdateBinding;
var
ADBField : TField;
AWVField : TWVField;
begin
if (Binder.Dataset<>nil) and (Binder.WorkView<>nil) then
begin
ADBField := Binder.Dataset.FindField(FFieldName);
AWVField := Binder.WorkView.FindField(FWVFieldName);
if (ADBField<>nil) and (AWVField<>nil) then
begin
ADBField.DisplayLabel := AWVField.Caption;
ADBField.Index := Self.Index;
ADBField.Visible := True;
end;
if (ADBField<>nil) and (DataPresentType<>'') then
WVSetFieldEventHanlder(ADBField,DataPresentType,DataPresentParam);
if Assigned(OnBinding) then
OnBinding(Self, ADBField, AWVField);
end;
end;
function TWVDBBinding.GetDisplayName: string;
begin
Result := FieldName + ' - ' + WVFieldName;
end;
end.
|
unit UtilImages;
interface
procedure CaptureScreen(AFileName : string);
procedure CaptureApplication(AFileName: string);
implementation
uses Windows, Graphics, Forms;
procedure CaptureApplication(AFileName: string);
const
CAPTUREBLT = $40000000;
var
hdcScreen : HDC;
hdcCompatible : HDC;
bmp : TBitmap;
hbmScreen : HBITMAP;
begin
// Create a normal DC and a memory DC for the entire screen. The
// normal DC provides a "snapshot" of the screen contents. The
// memory DC keeps a copy of this "snapshot" in the associated
// bitmap.
hdcScreen := CreateDC('DISPLAY', nil, nil, nil);
hdcCompatible := CreateCompatibleDC(hdcScreen);
// Create a compatible bitmap for hdcScreen.
hbmScreen := CreateCompatibleBitmap(hdcScreen,
GetDeviceCaps(hdcScreen, HORZRES),
GetDeviceCaps(hdcScreen, VERTRES));
// Select the bitmaps into the compatible DC.
SelectObject(hdcCompatible, hbmScreen);
bmp := TBitmap.Create;
bmp.Handle := hbmScreen;
BitBlt(hdcCompatible,
0,0,
Application.MainForm.Width, Application.MainForm.Height,
hdcScreen,
Application.MainForm.Left, Application.MainForm.Top,
SRCCOPY OR CAPTUREBLT);
bmp.SaveToFile(AFileName);
bmp.Free;
DeleteDC(hdcScreen);
DeleteDC(hdcCompatible);
end;
procedure CaptureScreen(AFileName : string);
const
CAPTUREBLT = $40000000;
var
hdcScreen : HDC;
hdcCompatible : HDC;
bmp : TBitmap;
hbmScreen : HBITMAP;
begin
// Create a normal DC and a memory DC for the entire screen. The
// normal DC provides a "snapshot" of the screen contents. The
// memory DC keeps a copy of this "snapshot" in the associated
// bitmap.
hdcScreen := CreateDC('DISPLAY', nil, nil, nil);
hdcCompatible := CreateCompatibleDC(hdcScreen);
// Create a compatible bitmap for hdcScreen.
hbmScreen := CreateCompatibleBitmap(hdcScreen,
GetDeviceCaps(hdcScreen, HORZRES),
GetDeviceCaps(hdcScreen, VERTRES));
// Select the bitmaps into the compatible DC.
SelectObject(hdcCompatible, hbmScreen);
bmp := TBitmap.Create;
bmp.Handle := hbmScreen;
BitBlt(hdcCompatible,
0,0,
bmp.Width, bmp.Height,
hdcScreen,
0,0,
SRCCOPY OR CAPTUREBLT);
bmp.SaveToFile(AFileName);
bmp.Free;
DeleteDC(hdcScreen);
DeleteDC(hdcCompatible);
end;
end.
|
program LinkedList;
uses
sysUtils;
type
NodePtr = ^Node;
Node = record
data : Integer;
next : NodePtr;
end;
LinkedLst = record
start : NodePtr;
finish : NodePtr;
end;
// Add enumerated type to change the operator in the find Node function
procedure CreateList(var list: LinkedLst);
begin
list.start := nil;
list.finish := nil;
end;
// Create Node
function CreateNode(data : Integer; next : NodePtr): NodePtr;
begin
New(result);
result^.data := data;
result^.next := next;
end;
function NodeCount(list: NodePtr; value: Integer): Integer;
begin
result := 0;
while (Assigned(list)) AND (list^.data <> value) do
begin
list := list^.next;
result := result + 1;
end;
end;
function FindNode(list: NodePtr; value: Integer): NodePtr;
var
current : NodePtr;
begin
result := nil;
current := list;
while (Assigned(current)) AND (current^.data <> value) do
begin
current := current^.next;
result := current;
end;
end;
// new find previous
// function FindPreviousNode(list, ofNode: NodePtr; val: Integer) : NodePtr;
// var
// current, previous : NodePtr;
//
// begin
// current := list;
// previous := nil;
// WriteLn('val in FindPrevNode', val);
// while (current <> ofNode) and (current <> nil) do
// begin
// // pass in the value and it will return the previous node
// previous := current;
// current := current^.next;
// end;
// result := previous;
// end;
function FindPreviousNode(list: NodePtr; val: Integer) : NodePtr;
var
i : Integer;
begin
WriteLn('val in FindPrevNode', val);
i := 0;
for i:= 0 to val-2 do
begin
// pass in the value and it will return the previous node
list := list^.next;
result := list;
end;
end;
function FindNextNode(list: NodePtr; val: Integer) : NodePtr;
var
i : Integer;
begin
WriteLn('val in FindPrevNode', val);
i := 0;
for i:= 0 to val-1 do
begin
// pass in the value and it will return the previous node
list := list^.next;
result := list;
end;
end;
// Dispose all nodes
procedure DisposeNodes(var start: NodePtr);
begin
if start <> nil then
begin
DisposeNodes(start^.next);
Dispose(start);
start := nil;
end;
end;
// Insert before procedure determined by parameters
procedure InsertBefore(list : NodePtr; beforeVal, val : Integer);
var
nodeBefore, temp: NodePtr;
begin
nodeBefore := FindPreviousNode(list, NodeCount(list, beforeVal));
temp := CreateNode(val, nodeBefore^.next);
nodeBefore^.next := temp;
end;
// Insert after procedure determined by parameters
procedure InsertAfter(list : NodePtr; beforeVal, val : Integer);
var
nodeBefore, temp: NodePtr;
begin
// find the node before
nodeBefore := FindNextNode(list, NodeCount(list, beforeVal));
temp := CreateNode(val, nodeBefore^.next);
nodeBefore^.next := temp;
end;
// Insert At Start of List
procedure PrependNode(var linked: LinkedLst; value: Integer);
var
temp : NodePtr;
begin
temp := CreateNode(value, linked.start);
linked.start := temp;
if linked.finish = nil then
begin
linked.finish := temp;
end;
end;
procedure AppendNode(var linked: LinkedLst; value: Integer);
var
temp : NodePtr;
begin
temp := CreateNode(value, nil);
if linked.finish <> nil then
begin
linked.finish^.next := temp;
end
else
begin
// list is empty
linked.start := temp;
end;
linked.finish := temp;
end;
// Print Nodes
procedure PrintBackTo(n: NodePtr);
begin
if (n <> nil) then
begin
PrintBackTo(n^.next);
Write(' <- ', n^.data);
end
else
begin
Write('nil');
end;
end;
// Print From Node
// In: NodePtr = list.start
procedure PrintFrom(n: NodePtr);
begin
if n <> nil then
begin
Write(n^.data,' -> ');
PrintFrom(n^.next);
end
else
begin
WriteLn('nil');
end;
{WriteLn();}
end;
{ Count nodes }
function Count(n: NodePtr):Integer;
var
current: NodePtr;
begin
current := n;
result := 0;
while (current <> nil) do
begin
result +=1;
current := current^.next;
end;
end;
procedure Main();
var
list : LinkedLst;
find : NodePtr;
begin
CreateList(list);
PrependNode(list, 1);
PrependNode(list, 5);
PrependNode(list, 10);
PrependNode(list, 15);
PrependNode(list, 20);
AppendNode(list, 99);
WriteLn('======================');
PrintFrom(list.start);
WriteLn('======================');
WriteLn('Start of the list data ',list.start^.data);
WriteLn('Finish of the list data ',list.finish^.data);
PrependNode(list, 30);
WriteLn('Start of the list data ',list.start^.data);
PrintFrom(list.start);
find := FindNode(list.start, 10);
FindPreviousNode(list.start, 2);
WriteLn('Node Count :',NodeCount(list.start, 15));
WriteLn('======================');
WriteLn('find ', find^.data);
PrintFrom(list.start);
WriteLn('======================');
find := FindPreviousNode(list.start, NodeCount(list.start, 10));
WriteLn('Find Previous Node Function ', find^.data);
//WriteLn('Find Node ', FindNode(list,20));
WriteLn('======================');
InsertBefore(list.start, 15, 18);
InsertAfter(list.start, 15, 22);
PrintFrom(list.start);
end;
// Main executable
begin
Main();
end. |
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit AppImpl;
interface
{$MODE OBJFPC}
uses
RunnableIntf,
CoreAppConsts,
CoreAppImpl;
type
(*!-----------------------------------------------
* Base abstract class that implements IWebApplication
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-----------------------------------------------*)
TFanoWebApplication = class(TCoreWebApplication)
public
function run() : IRunnable; override;
end;
implementation
uses
SysUtils,
///exception-related units
ERouteHandlerNotFoundImpl,
EMethodNotAllowedImpl,
EDependencyNotFoundImpl,
EInvalidDispatcherImpl,
EInvalidFactoryImpl;
(*!-----------------------------------------------
* execute application and handle exception
*------------------------------------------------
* @return current application instance
*-----------------------------------------------
* TODO: need to think about how to execute when
* application is run as daemon.
*-----------------------------------------------*)
function TFanoWebApplication.run() : IRunnable;
begin
try
if (initialize(dependencyContainer)) then
begin
result := execute();
end;
except
on e : ERouteHandlerNotFound do
begin
errorHandler.handleError(environment.enumerator, e, 404, sHttp404Message);
reset();
end;
on e : EMethodNotAllowed do
begin
errorHandler.handleError(environment.enumerator, e, 405, sHttp405Message);
reset();
end;
on e : Exception do
begin
errorHandler.handleError(environment.enumerator, e);
reset();
end;
end;
end;
end.
|
unit TemperatureCalibration;
interface
uses CommonCalibration;
type
TTempCalibrationTable = class( TCalibrationTable )
private
public
fBegUnitsTemp: integer;
fEndUnitsTemp: integer;
constructor Create( aBegUnitsTemp, aEndUnitsTemp: integer );
procedure AddTempRefPoint( aUnitTemp: integer; aRealTemp: single; aDescription: string );
// function GetRealTemp( aUnitsTemp: integer ): single;
// function GetUnitsTemp( aRealTemp: single ): integer;
function GetRealValue( aUnitsValue: integer ): single; override;
function GetRealValue( aUnitsValue: integer; aForParam: single ): single; override;
function GetMaxRealValue( aUnitsValue: integer ): single; override;
function GetUnitsValue( aRealValue: single ): integer; override;
function GetFactor( aRealValue: single ): single; override;
procedure LoadFromFileByRangeNo( aDiffTempRange: integer );override;
procedure Calc( ); override;
end;
implementation
uses SysUtils, CustomCollection, Procs, Config;
constructor TTempCalibrationTable.Create( aBegUnitsTemp, aEndUnitsTemp: integer );
begin
temperatureOffset := 0 - aBegUnitsTemp;
fBegUnitsTemp := aBegUnitsTemp;
fEndUnitsTemp := aEndUnitsTemp;
tableType := cttTemperature;
inherited Create( );
//ниже операторами заполняем бащзовые данные чтоб не глючила незагруженная таблица
fMinADCValue := gConfig.tMinADCValue;
fMaxADCValue := gConfig.tMaxADCValue;
begRealValue := GetRealValue( fMinADCValue );
endRealValue := GetRealValue( fMaxADCValue );
end;
procedure TTempCalibrationTable.AddTempRefPoint( aUnitTemp: integer; aRealTemp: single; aDescription: string );
var
rp: TrefPoint;
begin
rp := TrefPoint.Create( aUnitTemp );
rp.realValue := aRealTemp;
rp.description := aDescription;
inherited AddRefPoint( aUnitTemp, rp );
end;
procedure TTempCalibrationTable.Calc;
var
refPoint: TRefPoint;
i: integer;
begin
if GetRefPointsCount < 2 then
raise ERefPoinsCount.Create( 'Для расчёта необходимо не менее двух калибровочных точек.' );
refPoints.Sort;
ZeroItems( );
for i := 0 to GetRefPointsCount - 1 do
begin
//выходяящие за границы значения температурного АЦП обрезаем
refPoint := refPoints.GetItem( i );
refPoint.unitValue := HLLim( fBegUnitsTemp, fEndUnitsTemp, refPoint.unitValue );
refPoints.SetItem( i, refPoint );
end;
begRealValue := GetRealValue( fBegUnitsTemp );
endRealValue := GetRealValue( fEndUnitsTemp );
end;
function TTempCalibrationTable.GetFactor( aRealValue: single ): single;
begin
raise Exception.Create( 'Not applicable for Temparature calibration' );
end;
function TTempCalibrationTable.GetMaxRealValue( aUnitsValue: integer ): single;
begin
Result := GetRealValue( aUnitsValue );
end;
//function TTempCalibrationTable.GetRealTemp( aUnitsTemp: integer ): single;
//var
// i: integer;
// temperature1, temperature2: integer;
//begin
// if aUnitsTemp <= refPoints.GetItem( 0 ).unitValue then
// begin
// //попадаем в диапазон до первой калибровочной точки
// Result := LineInterp( refPoints.GetItem( 0 ).unitValue, refPoints.GetItem( 0 ).realValue,
// refPoints.GetItem( 1 ).unitValue, refPoints.GetItem( 1 ).realValue, aUnitsTemp );
// exit;
// end
// else if aUnitsTemp >= refPoints.GetItem( GetRefPointsCount - 1 ).unitValue then
// begin
// //попадаем в диапазон после последней калибровочной точки
// Result := LineInterp( refPoints.GetItem( GetRefPointsCount - 2 ).unitValue, refPoints.GetItem( GetRefPointsCount - 2 ).realValue,
// refPoints.GetItem( GetRefPointsCount - 1 ).unitValue, refPoints.GetItem( GetRefPointsCount - 1 ).realValue, aUnitsTemp );
// exit;
// end
// else
// //ищем в какой диапазон калибровочных точек на кривой попали
// for i := 0 to GetRefPointsCount - 1 do
// if ( aUnitsTemp >= refPoints.GetItem( i ).unitValue ) and ( aUnitsTemp < refPoints.GetItem( i + 1 ).unitValue ) then
// begin
// Result := LineInterp( refPoints.GetItem( i ).unitValue, refPoints.GetItem( i ).realValue,
// refPoints.GetItem( i + 1 ).unitValue, refPoints.GetItem( i + 1 ).realValue, aUnitsTemp );
// exit;
// end;
//end;
function TTempCalibrationTable.GetRealValue( aUnitsValue: integer; aForParam: single ): single;
begin
Result := GetRealValue( aUnitsValue );
end;
function TTempCalibrationTable.GetRealValue( aUnitsValue: integer ): single;
var
i: integer;
temperature1, temperature2: integer;
begin
if refPoints.GetItemCount( ) > 0 then
begin
if aUnitsValue <= refPoints.GetItem( 0 ).unitValue then
begin
//попадаем в диапазон до первой калибровочной точки
Result := LineInterp( refPoints.GetItem( 0 ).unitValue, refPoints.GetItem( 0 ).realValue,
refPoints.GetItem( 1 ).unitValue, refPoints.GetItem( 1 ).realValue, aUnitsValue );
exit;
end
else if aUnitsValue >= refPoints.GetItem( GetRefPointsCount - 1 ).unitValue then
begin
//попадаем в диапазон после последней калибровочной точки
Result := LineInterp( refPoints.GetItem( GetRefPointsCount - 2 ).unitValue, refPoints.GetItem( GetRefPointsCount - 2 ).realValue,
refPoints.GetItem( GetRefPointsCount - 1 ).unitValue, refPoints.GetItem( GetRefPointsCount - 1 ).realValue, aUnitsValue );
exit;
end
else
//ищем в какой диапазон калибровочных точек на кривой попали
for i := 0 to GetRefPointsCount - 1 do
if ( aUnitsValue >= refPoints.GetItem( i ).unitValue ) and ( aUnitsValue < refPoints.GetItem( i + 1 ).unitValue ) then
begin
Result := LineInterp( refPoints.GetItem( i ).unitValue, refPoints.GetItem( i ).realValue,
refPoints.GetItem( i + 1 ).unitValue, refPoints.GetItem( i + 1 ).realValue, aUnitsValue );
exit;
end;
end
else
Result := aUnitsValue;
end;
//function TTempCalibrationTable.GetUnitsTemp( aRealTemp: single ): integer;
//var
// i: integer;
// temperature1, temperature2: integer;
//begin
// if aRealTemp <= refPoints.GetItem( 0 ).realValue then
// begin
// //попадаем в диапазон до первой калибровочной точки
// Result := Round( LineInterp( refPoints.GetItem( 0 ).realValue, refPoints.GetItem( 0 ).unitValue,
// refPoints.GetItem( 1 ).realValue, refPoints.GetItem( 1 ).unitValue, aRealTemp ) );
// exit;
// end
// else if aRealTemp >= refPoints.GetItem( GetRefPointsCount - 1 ).realValue then
// begin
// //попадаем в диапазон после последней калибровочной точки
// Result := Round( LineInterp( refPoints.GetItem( GetRefPointsCount - 2 ).realValue, refPoints.GetItem( GetRefPointsCount - 2 ).unitValue,
// refPoints.GetItem( GetRefPointsCount - 1 ).realValue, refPoints.GetItem( GetRefPointsCount - 1 ).unitValue, aRealTemp ) );
// exit;
// end
// else
// //ищем в какой диапазон калибровочных точек на кривой попали
// for i := 0 to GetRefPointsCount - 1 do
// if ( aRealTemp >= refPoints.GetItem( i ).realValue ) and ( aRealTemp < refPoints.GetItem( i + 1 ).realValue ) then
// begin
// Result := Round( LineInterp( refPoints.GetItem( i ).realValue, refPoints.GetItem( i ).unitValue,
// refPoints.GetItem( i + 1 ).realValue, refPoints.GetItem( i + 1 ).unitValue, aRealTemp ) );
// exit;
// end;
//end;
function TTempCalibrationTable.GetUnitsValue( aRealValue: single ): integer;
var
i: integer;
temperature1, temperature2: integer;
begin
if refPoints.GetItemCount( ) > 0 then
begin
if aRealValue <= refPoints.GetItem( 0 ).realValue then
begin
//попадаем в диапазон до первой калибровочной точки
Result := Round( LineInterp( refPoints.GetItem( 0 ).realValue, refPoints.GetItem( 0 ).unitValue,
refPoints.GetItem( 1 ).realValue, refPoints.GetItem( 1 ).unitValue, aRealValue ) );
exit;
end
else if aRealValue >= refPoints.GetItem( GetRefPointsCount - 1 ).realValue then
begin
//попадаем в диапазон после последней калибровочной точки
Result := Round( LineInterp( refPoints.GetItem( GetRefPointsCount - 2 ).realValue, refPoints.GetItem( GetRefPointsCount - 2 ).unitValue,
refPoints.GetItem( GetRefPointsCount - 1 ).realValue, refPoints.GetItem( GetRefPointsCount - 1 ).unitValue, aRealValue ) );
exit;
end
else
//ищем в какой диапазон калибровочных точек на кривой попали
for i := 0 to GetRefPointsCount - 1 do
if ( aRealValue >= refPoints.GetItem( i ).realValue ) and ( aRealValue < refPoints.GetItem( i + 1 ).realValue ) then
begin
Result := Round( LineInterp( refPoints.GetItem( i ).realValue, refPoints.GetItem( i ).unitValue,
refPoints.GetItem( i + 1 ).realValue, refPoints.GetItem( i + 1 ).unitValue, aRealValue ) );
exit;
end;
end
else
Result := Round( aRealValue );
end;
procedure TTempCalibrationTable.LoadFromFileByRangeNo( aDiffTempRange: integer );
begin
raise Exception.Create( 'LoadFromFileByRangeNo is not applicable for Temparature calibration' );
end;
//function TTempCalibrationTable.GetTemperatureOffset: integer;
//begin
// Result := temperatureOffset;
//end;
end.
|
unit OperatorTypes;
interface
uses
SysUtils;
type
TPointRecord = record
private
FX, FY: Integer;
public
procedure SetValue(X1, Y1: Integer);
{
class operator keyword is used to provide a custom implementation for
standard built-in operations
e.g. A, B, C: TPointRecord
C := A + B
the + will automatically call this custom Add implementation
}
class operator Add(A, B: TPointRecord): TPointRecord;
class operator Explicit(A: TPointRecord) : string;
class operator Implicit(X1: Integer): TPointRecord;
end;
type
TPointRecord2 = record
private
FX, FY: Integer;
public
class operator Explicit(A: TPointRecord2) : string;
procedure SetValue(X1, Y1: Integer);
// Commutativity
class operator Add(A: TPointRecord2; B: Integer): TPointRecord2;
class operator Add(B: Integer; A: TPointRecord2): TPointRecord2;
end;
implementation
{ TPointRecord }
// +
class operator TPointRecord.Add(A, B: TPointRecord): TPointRecord;
begin
Result.FX := A.FX + B.FX;
Result.FY := A.FY + B.FY;
end;
// string
class operator TPointRecord.Explicit(A: TPointRecord): string;
begin
Result := Format('(%d:%d)', [A.FX, A.FY]);
end;
// :=
class operator TPointRecord.Implicit(X1: Integer): TPointRecord;
begin
Result.FX := X1;
Result.FY := 10;
end;
procedure TPointRecord.SetValue(X1, Y1: Integer);
begin
FX := X1;
FY := Y1;
end;
{ TPointRecord2 }
procedure TPointRecord2.SetValue(X1, Y1: Integer);
begin
FX := X1;
FY := Y1;
end;
class operator TPointRecord2.Add(A: TPointRecord2; B: Integer): TPointRecord2;
begin
Result.FX := A.FX + B;
Result.FY := A.FY + B;
end;
class operator TPointRecord2.Add(B: Integer; A: TPointRecord2): TPointRecord2;
begin
Result := A + B; // implement commutativity by calling the previous Add
end;
class operator TPointRecord2.Explicit(A: TPointRecord2): string;
begin
Result := Format('(%d:%d)', [A.FX, A.FY]);
end;
end.
|
unit BitmapHelper;
interface
uses FMX.Graphics;
type
TBitmapHelper = class helper for TBitmap
function ToBase64 :String;
end;
implementation
uses System.Classes, System.SysUtils, System.NetEncoding;
{ TBitmapHelper }
function TBitmapHelper.ToBase64: String;
var
Input: TBytesStream;
Output: TStringStream;
Encoding: TBase64Encoding;
begin
Input := TBytesStream.Create;
try
Self.SaveToStream(Input);
Input.Position := 0;
Output := TStringStream.Create('', TEncoding.ASCII);
try
Encoding := TBase64Encoding.Create(0);
Encoding.Encode(Input, Output);
Result := Output.DataString;
finally
Encoding.Free;
Output.Free;
end;
finally
Input.Free;
end;
end;
end.
|
{*************************************
Description: Standart dialog function
- ALInputQuery function
- ALInputBox function
**************************************}
unit ALDialog;
interface
{$IF CompilerVersion >= 25} {Delphi XE4}
{$LEGACYIFEND ON} // http://docwiki.embarcadero.com/RADStudio/XE4/en/Legacy_IFEND_(Delphi)
{$IFEND}
function ALInputQuery(const ACaption, APrompt: Ansistring; var Value: Ansistring; ACancelButton: Boolean): Boolean;
function ALInputBox(const ACaption, APrompt, ADefault: Ansistring; ACancelButton: Boolean): Ansistring;
implementation
uses Winapi.windows,
Vcl.forms,
Vcl.Graphics,
Vcl.StdCtrls,
Vcl.controls,
Vcl.Consts;
{*****************************************************************************************************************}
function ALInputQuery(const ACaption, APrompt: Ansistring; var Value: Ansistring; ACancelButton: Boolean): Boolean;
var
Form: TForm;
Prompt: TLabel;
Edit: TEdit;
DialogUnits: TPoint;
ButtonTop, ButtonWidth, ButtonHeight: Integer;
function GetAveCharSize(Canvas: TCanvas): TPoint;
var
I: Integer;
Buffer: array[0..51] of Char;
begin
for I := 0 to 25 do Buffer[I] := Chr(I + Ord('A'));
for I := 0 to 25 do Buffer[I + 26] := Chr(I + Ord('a'));
GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result));
Result.X := Result.X div 52;
end;
begin
Result := False;
Form := TForm.Create(Application);
with Form do
try
Canvas.Font := Font;
DialogUnits := GetAveCharSize(Canvas);
BorderStyle := bsDialog;
Caption := String(ACaption);
ClientWidth := MulDiv(180, DialogUnits.X, 4);
Position := poScreenCenter;
Prompt := TLabel.Create(Form);
with Prompt do begin
Parent := Form;
Caption := String(APrompt);
Left := MulDiv(8, DialogUnits.X, 4);
Top := MulDiv(8, DialogUnits.Y, 8);
Constraints.MaxWidth := MulDiv(164, DialogUnits.X, 4);
WordWrap := True;
end;
Edit := TEdit.Create(Form);
with Edit do begin
Parent := Form;
Left := Prompt.Left;
Top := Prompt.Top + Prompt.Height + 5;
Width := MulDiv(164, DialogUnits.X, 4);
MaxLength := 255;
Text := String(Value);
SelectAll;
end;
ButtonTop := Edit.Top + Edit.Height + 15;
ButtonWidth := MulDiv(50, DialogUnits.X, 4);
ButtonHeight := MulDiv(14, DialogUnits.Y, 8);
with TButton.Create(Form) do begin
Parent := Form;
Caption := SMsgDlgOK;
ModalResult := mrOk;
Default := True;
If ACancelButton then SetBounds(MulDiv(38, DialogUnits.X, 4), ButtonTop, ButtonWidth, ButtonHeight)
else SetBounds(MulDiv(65, DialogUnits.X, 4), ButtonTop, ButtonWidth, ButtonHeight);
Form.ClientHeight := Top + Height + 13;
end;
If ACancelButton then
with TButton.Create(Form) do begin
Parent := Form;
Caption := SMsgDlgCancel;
ModalResult := mrCancel;
Cancel := True;
SetBounds(MulDiv(92, DialogUnits.X, 4), Edit.Top + Edit.Height + 15, ButtonWidth, ButtonHeight);
end;
if ShowModal = mrOk then begin
Value := AnsiString(Edit.Text);
Result := True;
end;
finally
Form.Free;
end;
end;
{*****************************************************************************************************}
function ALInputBox(const ACaption, APrompt, ADefault: Ansistring; ACancelButton: Boolean): Ansistring;
begin
Result := ADefault;
ALInputQuery(ACaption, APrompt, Result, ACancelButton);
end;
end.
|
unit Download.Controller.IdHTTP;
interface
uses
Download.Download.Tipos, Download.Controller.Interfaces,
Download.Model.Interfaces, Download.Model.IdHTTP;
type
TControllerIdHTTP = class(TInterfacedObject, iControllerIdHTTP)
private
FModelIdHTTP: iModelIdHTTP;
public
constructor Create;
destructor Destroy; override;
class function New: iControllerIdHTTP;
procedure FazerDownloadDoArquivo(strUrl, strDestino: String);
procedure PararDownload;
procedure AdicionarObserver(Observer: iDownloadObserver);
function EstaExecutando: Boolean;
end;
implementation
{ TControllerIdHTTP }
procedure TControllerIdHTTP.AdicionarObserver(Observer: iDownloadObserver);
begin
FModelIdHTTP.RetornarOBserver.AdicionarObserver(Observer);
end;
constructor TControllerIdHTTP.Create;
begin
FModelIdHTTP := TModelIdHTTP.New;
end;
destructor TControllerIdHTTP.Destroy;
begin
inherited;
end;
function TControllerIdHTTP.EstaExecutando: Boolean;
begin
Result := FModelIdHTTP.EstaExecutando;
end;
procedure TControllerIdHTTP.FazerDownloadDoArquivo(strUrl, strDestino: String);
begin
FModelIdHTTP.FazerDownloadDoArquivo(strUrl, strDestino);
end;
class function TControllerIdHTTP.New: iControllerIdHTTP;
begin
result := Self.Create;
end;
procedure TControllerIdHTTP.PararDownload;
begin
FModelIdHTTP.PararDownload;
end;
end.
end.
|
unit BankAccountTest;
interface
uses dbTest, dbObjectTest, ObjectTest;
type
TBankAccountTest = class (TdbObjectTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TBankAccount = class(TObjectTest)
function InsertDefault: integer; override;
public
function InsertUpdateBankAccount(Id, Code: Integer; Name: String;
JuridicalId, BankId, CurrencyId, CorrespondentBankId, BeneficiarysBankId: Integer): integer;
constructor Create; override;
end;
implementation
uses DB, UtilConst, TestFramework, SysUtils, JuridicalTest,
BankTest, CurrencyTest;
{ TdbUnitTest }
procedure TBankAccountTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'OBJECTS\BankAccount\';
inherited;
end;
procedure TBankAccountTest.Test;
var Id: integer;
RecordCount: Integer;
ObjectTest: TBankAccount;
begin
ObjectTest := TBankAccount.Create;
// Получим список
RecordCount := ObjectTest.GetDataSet.RecordCount;
// Вставка Управленческого счета
Id := ObjectTest.InsertDefault;
try
// Получение данных о кассе
with ObjectTest.GetRecord(Id) do
Check((FieldByName('name').AsString = 'Расчетный счет'), 'Не сходятся данные Id = ' + FieldByName('id').AsString);
finally
ObjectTest.Delete(Id);
end;
end;
{TBankAccount}
constructor TBankAccount.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_Object_BankAccount';
spSelect := 'gpSelect_Object_BankAccount';
spGet := 'gpGet_Object_BankAccount';
end;
function TBankAccount.InsertDefault: integer;
var
JuridicalId, BankId, CurrencyId, CorrespondentBankId, BeneficiarysBankId: Integer;
begin
JuridicalId := TJuridical.Create.GetDefault;
BankId:= TBank.Create.GetDefault;
CorrespondentBankId:= TBank.Create.GetDefault;
BeneficiarysBankId:= TBank.Create.GetDefault;
WITH TCurrency.Create.GetDataSet do
CurrencyId:= FieldByName('Id').AsInteger;
result := InsertUpdateBankAccount(0, -1, 'Расчетный счет', JuridicalId, BankId, CurrencyId, CorrespondentBankId, BeneficiarysBankId);
inherited;
end;
function TBankAccount.InsertUpdateBankAccount;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inCode', ftInteger, ptInput, Code);
FParams.AddParam('inName', ftString, ptInput, Name);
FParams.AddParam('inJuridicalId', ftInteger, ptInput, JuridicalId);
FParams.AddParam('inBankId', ftInteger, ptInput, BankId);
FParams.AddParam('inCurrencyId', ftInteger, ptInput, CurrencyId);
FParams.AddParam('inCorrespondentBankId', ftInteger, ptInput, CorrespondentBankId);
FParams.AddParam('inBeneficiarysBankId', ftInteger, ptInput, BeneficiarysBankId);
FParams.AddParam('inCorrespondentAccount', ftString, ptInput, '');
FParams.AddParam('inBeneficiarysBankAccount', ftString, ptInput, '');
FParams.AddParam('inBeneficiarysAccount', ftString, ptInput, '');
result := InsertUpdate(FParams);
end;
initialization
//TestFramework.RegisterTest('Объекты', TBankAccountTest.Suite);
end.
|
(*
Name: UfrmVisualKeyboardExportHTMLParams
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 23 Aug 2006
Modified Date: 3 Aug 2015
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 23 Aug 2006 - mcdurdin - Initial refactor for new visual keyboard
29 Sep 2008 - mcdurdin - I1658 - Reworked for graphics options
18 May 2012 - mcdurdin - I3306 - V9.0 - Remove TntControls + Win9x support
03 Aug 2015 - mcdurdin - I4822 - Form sizes are incorrect with new theming
*)
unit UfrmVisualKeyboardExportHTMLParams; // I3306
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
StdCtrls, UfrmTike;
type
TfrmVisualKeyboardExportHTMLParams = class(TTIKEForm) // I4822
cmdOK: TButton;
cmdCancel: TButton;
gbOutputType: TGroupBox;
Label1: TLabel;
lblFileName: TLabel;
Label5: TLabel;
rbFolders: TRadioButton;
rbNoFolders: TRadioButton;
chkGraphical: TCheckBox;
Label2: TLabel;
procedure cmdOKClick(Sender: TObject);
private
procedure SetFileName(const Value: string);
function GetFolders: Boolean;
function GetGraphical: Boolean;
public
property FileName: string write SetFileName;
property Folders: Boolean read GetFolders;
property Graphical: Boolean read GetGraphical;
end;
implementation
{$R *.DFM}
uses
messageidentifiers;
{ TfrmVisualKeyboardExportHTMLParams }
procedure TfrmVisualKeyboardExportHTMLParams.SetFileName(const Value: string);
begin
lblFileName.Caption := ChangeFileExt(ExtractFileName(Value), '')+'_files';
end;
function TfrmVisualKeyboardExportHTMLParams.GetFolders: Boolean;
begin
Result := rbFolders.Checked;
end;
function TfrmVisualKeyboardExportHTMLParams.GetGraphical: Boolean;
begin
Result := chkGraphical.Checked;
end;
procedure TfrmVisualKeyboardExportHTMLParams.cmdOKClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
end.
|
unit InterfaceObjectList;
interface
uses
SysUtils,
Classes;
type
TInterfaceObjectList = class;
TInterfaceObjectListEnumerator = class (TListEnumerator)
protected
function GetCurrentInterfaceObject: IInterface;
public
constructor Create(InterfaceObjectList: TInterfaceObjectList);
property Current: IInterface read GetCurrentInterfaceObject;
end;
TInterfaceObjectList = class (TList)
protected
type
TEntry = class
InterfaceObject: IInterface;
constructor Create(InterfaceObject: IInterface);
end;
protected
function GetInterfaceObjectByIndex(Index: Integer): IInterface;
procedure SetInterfaceObjectByIndex(
Index: Integer;
Value: IInterface
);
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
function FindEntryIndexByInterfaceObject(InterfaceObject: IInterface): Integer;
function FindEntryByInterfaceObject(InterfaceObject: IInterface): TEntry;
public
function Add(InterfaceObject: IInterface): Integer;
procedure Remove(InterfaceObject: IInterface);
function GetEnumerator: TInterfaceObjectListEnumerator;
property Items[Index: Integer]: IInterface
read GetInterfaceObjectByIndex
write SetInterfaceObjectByIndex; default;
end;
implementation
{ TInterfaceObjectListEnumerator }
constructor TInterfaceObjectListEnumerator.Create(
InterfaceObjectList: TInterfaceObjectList);
begin
inherited Create(InterfaceObjectList);
end;
function TInterfaceObjectListEnumerator.GetCurrentInterfaceObject: IInterface;
begin
Result := TInterfaceObjectList.TEntry(GetCurrent).InterfaceObject;
end;
{ TInterfaceObjectList }
function TInterfaceObjectList.Add(InterfaceObject: IInterface): Integer;
begin
Result := inherited Add(TEntry.Create(InterfaceObject));
end;
function TInterfaceObjectList.FindEntryByInterfaceObject(
InterfaceObject: IInterface): TEntry;
var EntryIndex: Integer;
begin
EntryIndex := FindEntryIndexByInterfaceObject(InterfaceObject);
Result := TEntry(Get(EntryIndex));
end;
function TInterfaceObjectList.FindEntryIndexByInterfaceObject(
InterfaceObject: IInterface): Integer;
begin
for Result := 0 to Count - 1 do
if Self[Result] = InterfaceObject then
Exit;
Result := -1;
end;
function TInterfaceObjectList.GetEnumerator: TInterfaceObjectListEnumerator;
begin
Result := TInterfaceObjectListEnumerator.Create(Self);
end;
function TInterfaceObjectList.GetInterfaceObjectByIndex(
Index: Integer): IInterface;
begin
Result := TEntry(Get(Index)).InterfaceObject;
end;
procedure TInterfaceObjectList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if Action = lnDeleted then
if Assigned(Ptr) then
TEntry(Ptr).Destroy;
end;
procedure TInterfaceObjectList.Remove(InterfaceObject: IInterface);
var EntryIndex: Integer;
begin
EntryIndex := FindEntryIndexByInterfaceObject(InterfaceObject);
Delete(EntryIndex);
end;
procedure TInterfaceObjectList.SetInterfaceObjectByIndex(Index: Integer;
Value: IInterface);
var Entry: TEntry;
begin
Entry := TEntry(Get(Index));
Entry.InterfaceObject := Value;
end;
{ TInterfaceObjectList.TEntry }
constructor TInterfaceObjectList.TEntry.Create(InterfaceObject: IInterface);
begin
inherited Create;
Self.InterfaceObject := InterfaceObject;
end;
end.
|
unit RepositorioIcms00;
interface
uses
DB,
Repositorio;
type
TRepositorioIcms00 = class(TRepositorio)
protected
function Get (Dataset :TDataSet) :TObject; overload; override;
function GetNomeDaTabela :String; override;
function GetIdentificador(Objeto :TObject) :Variant; override;
function GetRepositorio :TRepositorio; override;
protected
function SQLGet :String; override;
function SQLSalvar :String; override;
function SQLGetAll :String; override;
function SQLRemover :String; override;
protected
function IsInsercao(Objeto :TObject) :Boolean; override;
function IsComponente :Boolean; override;
protected
procedure SetParametros (Objeto :TObject ); override;
end;
implementation
uses
Icms00,
TipoOrigemMercadoria,
SysUtils;
{ TRepositorioIcms00 }
function TRepositorioIcms00.Get(Dataset: TDataSet): TObject;
begin
result := TIcms00.Create(TTipoOrigemMercadoriaUtilitario.DeIntegerParaEnumerado(Dataset.FieldByName('origem').AsInteger),
Dataset.FieldByName('aliquota').AsFloat,
Dataset.FieldByName('perc_reducao_bc').AsFloat);
end;
function TRepositorioIcms00.GetIdentificador(Objeto: TObject): Variant;
begin
result := TIcms00(Objeto).CodigoItem;
end;
function TRepositorioIcms00.GetNomeDaTabela: String;
begin
result := 'itens_nf_icms_00';
end;
function TRepositorioIcms00.GetRepositorio: TRepositorio;
begin
result := TRepositorioIcms00.Create;
end;
function TRepositorioIcms00.IsComponente: Boolean;
begin
result := true;
end;
function TRepositorioIcms00.IsInsercao(Objeto: TObject): Boolean;
begin
result := true;
end;
procedure TRepositorioIcms00.SetParametros(Objeto: TObject);
var
Obj :TIcms00;
begin
Obj := (Objeto as TIcms00);
inherited SetParametro('codigo_item', Obj.CodigoItem);
inherited SetParametro('origem', TTipoOrigemMercadoriaUtilitario.DeEnumeradoParaInteger(Obj.OrigemMercadoria));
inherited SetParametro('aliquota', Obj.Aliquota);
inherited SetParametro('perc_reducao_bc', Obj.PercReducaoBC);
end;
function TRepositorioIcms00.SQLGet: String;
begin
result := 'select * from '+self.GetNomeDaTabela+' where codigo_item = :codigo_item';
end;
function TRepositorioIcms00.SQLGetAll: String;
begin
result := 'select * from '+self.GetNomeDaTabela;
end;
function TRepositorioIcms00.SQLRemover: String;
begin
result := 'delete from '+self.GetNomeDaTabela+' where codigo_item = :codigo_item';
end;
function TRepositorioIcms00.SQLSalvar: String;
begin
result := ' update or insert into ' + self.GetNomeDaTabela +
' (codigo_item, origem, aliquota, perc_reducao_bc) '+
' values (:codigo_item, :origem, :aliquota, :perc_reducao_bc) ';
end;
end.
|
unit DBTableColumnMappingsUnit;
interface
uses
TableColumnMappingsUnit,
SysUtils,
Classes;
type
TDBTableColumnMapping = class (TTableColumnMapping)
private
FConversionTypeName: String;
FAliasColumnName: String;
FTableName: String;
public
constructor Create; overload;
constructor Create(
const ColumnName, ObjectPropertyName,
AliasColumnName, TableName: String;
const AllowMappingOnDomainObjectProperty: Boolean = True;
const ConversionTypeName: String = ''
); overload;
property ConversionTypeName: String
read FConversionTypeName write FConversionTypeName;
property AliasColumnName: String
read FAliasColumnName write FAliasColumnName;
property TableName: String
read FTableName write FTableName;
end;
TDBTableColumnMappings = class;
TDBTableColumnMappingsEnumerator = class (TTableColumnMappingsEnumerator)
private
function GetCurrentDBColumnMapping: TDBTableColumnMapping;
constructor Create(
TableColumnMappings: TDBTableColumnMappings
);
public
property Current: TDBTableColumnMapping read GetCurrentDBColumnMapping;
end;
TDBTableColumnMappings = class (TTableColumnMappings)
protected
function GetDBColumnMappingByIndex(Index: Integer): TDBTableColumnMapping;
procedure SetDBColumnMappingByIndex(
Index: Integer;
ColumnMapping: TDBTableColumnMapping
);
function GetTableColumnMappingClass: TTableColumnMappingClass; override;
public
function GetEnumerator: TDBTableColumnMappingsEnumerator;
property Items[Index: Integer]: TDBTableColumnMapping
read GetDBColumnMappingByIndex write SetDBColumnMappingByIndex; default;
function AddColumnMappingWithAlias(
const ColumnName, ObjectPropertyName,
AliasColumnName: String;
const AllowMappingOnDomainObjectProperty: Boolean = True;
const ConversionTypeName: String = ''
): TDBTableColumnMapping;
function AddColumnMappingWithTableName(
const ColumnName, ObjectPropertyName,
TableName: String;
const AllowMappingOnDomainObjectProperty: Boolean = True;
const ConversionTypeName: String = ''
): TDBTableColumnMapping;
function AddColumnMappingWithAliasAndTableName(
const ColumnName, ObjectPropertyName,
AliasColumnName, TableName: String;
const AllowMappingOnDomainObjectProperty: Boolean = True;
const ConversionTypeName: String = ''
): TDBTableColumnMapping;
function AddColumnMapping(
const ColumnName, ObjectPropertyName: String;
const AllowMappingOnDomainObjectProperty: Boolean = True
): TTableColumnMappings; overload; override;
function AddColumnMapping(
const ColumnName, ObjectPropertyName: String;
const ConversionTypeName: String;
const AllowMappingOnDomainObjectProperty: Boolean = True
): TTableColumnMappings; overload;
procedure RemoveColumnMapping(
const ColumnName: String
); override;
function FindColumnMappingByColumnName(
const ColumnName: string
): TTableColumnMapping; override;
function FindColumnMappingByObjectPropertyName(
const ObjectPropertyName: string
): TTableColumnMapping; override;
end;
implementation
{ DBTTableColumnMapping }
constructor TDBTableColumnMapping.Create;
begin
inherited;
end;
constructor TDBTableColumnMapping.Create(
const ColumnName, ObjectPropertyName,
AliasColumnName, TableName: String;
const AllowMappingOnDomainObjectProperty: Boolean;
const ConversionTypeName: String
);
begin
inherited
Create(
ColumnName,
ObjectPropertyName,
AllowMappingOnDomainObjectProperty
);
Self.ConversionTypeName := ConversionTypeName;
Self.AliasColumnName := AliasColumnName;
Self.ObjectPropertyName := ObjectPropertyName;
end;
{ TDBTableColumnMappingsEnumerator }
constructor TDBTableColumnMappingsEnumerator.Create(
TableColumnMappings: TDBTableColumnMappings);
begin
inherited Create(TableColumnMappings);
end;
function TDBTableColumnMappingsEnumerator.GetCurrentDBColumnMapping: TDBTableColumnMapping;
begin
Result := TDBTableColumnMapping(GetCurrentColumnMapping);
end;
{ TDBTableColumnMappings }
function TDBTableColumnMappings.AddColumnMapping(
const ColumnName,
ObjectPropertyName: String;
const AllowMappingOnDomainObjectProperty: Boolean
): TTableColumnMappings;
var ColumnMapping: TTableColumnMapping;
begin
Result :=
inherited
AddColumnMapping(
ColumnName,
ObjectPropertyName,
AllowMappingOnDomainObjectProperty
);
end;
function TDBTableColumnMappings.AddColumnMapping(
const ColumnName, ObjectPropertyName: String;
const ConversionTypeName: String;
const AllowMappingOnDomainObjectProperty: Boolean
): TTableColumnMappings;
var ColumnMapping: TTableColumnMapping;
begin
AddColumnMapping(
ColumnName,
ObjectPropertyName,
AllowMappingOnDomainObjectProperty
);
ColumnMapping := FindColumnMappingByColumnName(ColumnName);
if Assigned(ColumnMapping) then
(ColumnMapping as TDBTableColumnMapping)
.ConversionTypeName := ConversionTypeName;
end;
function TDBTableColumnMappings.AddColumnMappingWithAlias(
const ColumnName,
ObjectPropertyName,
AliasColumnName: String;
const AllowMappingOnDomainObjectProperty: Boolean;
const ConversionTypeName: String
): TDBTableColumnMapping;
begin
if Assigned(FindColumnMappingByObjectPropertyName(ObjectPropertyName))
then Exit;
Add(
TDBTableColumnMapping.Create(
ColumnName,
ObjectPropertyName,
AliasColumnName,
'',
AllowMappingOnDomainObjectProperty,
ConversionTypeName
)
);
end;
function TDBTableColumnMappings.AddColumnMappingWithAliasAndTableName(
const ColumnName, ObjectPropertyName, AliasColumnName, TableName: String;
const AllowMappingOnDomainObjectProperty: Boolean;
const ConversionTypeName: String
): TDBTableColumnMapping;
begin
if Assigned(FindColumnMappingByObjectPropertyName(ObjectPropertyName))
then Exit;
Add(
TDBTableColumnMapping.Create(
ColumnName,
ObjectPropertyName,
AliasColumnName,
TableName,
AllowMappingOnDomainObjectProperty,
ConversionTypeName
)
);
end;
function TDBTableColumnMappings.AddColumnMappingWithTableName(
const ColumnName,
ObjectPropertyName,
TableName: String;
const AllowMappingOnDomainObjectProperty: Boolean;
const ConversionTypeName: String
): TDBTableColumnMapping;
begin
if Assigned(FindColumnMappingByObjectPropertyName(ObjectPropertyName))
then Exit;
Add(
TDBTableColumnMapping.Create(
ColumnName,
ObjectPropertyName,
'',
TableName,
AllowMappingOnDomainObjectProperty,
ConversionTypeName
)
);
end;
function TDBTableColumnMappings.FindColumnMappingByColumnName(
const ColumnName: string): TTableColumnMapping;
var DBTableColumnMapping: TDBTableColumnMapping;
begin
for DBTableColumnMapping in Self do
if
(DBTableColumnMapping.ColumnName = ColumnName) and
(DBTableColumnMapping.TableName = '')
then begin
Result := DBTableColumnMapping;
Exit;
end;
Result := nil;
end;
function TDBTableColumnMappings.FindColumnMappingByObjectPropertyName(
const ObjectPropertyName: string): TTableColumnMapping;
begin
Result := inherited FindColumnMappingByObjectPropertyName(ObjectPropertyName);
end;
function TDBTableColumnMappings.GetDBColumnMappingByIndex(
Index: Integer): TDBTableColumnMapping;
begin
Result := TDBTableColumnMapping(GetColumnMappingByIndex(Index));
end;
function TDBTableColumnMappings.GetEnumerator: TDBTableColumnMappingsEnumerator;
begin
Result := TDBTableColumnMappingsEnumerator.Create(Self);
end;
function TDBTableColumnMappings.GetTableColumnMappingClass: TTableColumnMappingClass;
begin
Result := TDBTableColumnMapping;
end;
procedure TDBTableColumnMappings.RemoveColumnMapping(const ColumnName: String);
begin
inherited;
end;
procedure TDBTableColumnMappings.SetDBColumnMappingByIndex(Index: Integer;
ColumnMapping: TDBTableColumnMapping);
begin
SetColumnMappingByIndex(Index, ColumnMapping);
end;
end.
|
unit unitid;
interface
uses
classes, sysutils, dialogs;
type
TSection = class
name :string;
ids :tlist;
constructor Create;
destructor Destroy; override;
end;
type
TUnitIds = class
defunits :TList;
groups :TList;
notloaded :boolean;
// units :Tlist;
constructor Create (fname :string);
destructor Destroy; override;
function GetName (id :longword) :string;
function GetUnits (ids :TList) :TStringList;
end;
implementation
constructor TSection.Create;
begin
ids := Tlist.Create;
end;
destructor TSection.Destroy;
begin
ids.free;
inherited Destroy;
end;
constructor TUnitIds.Create (fname :string);
var
f :TextFile;
s :string;
cursect :TSection;
curunits :TList;
i :longword;
code :integer;
units :TList;
begin
groups := nil;
units := nil;
notloaded := true;
AssignFile (f, fname);
{$I-}
Reset (f);
{$I+}
if ioresult <> 0 then
begin
MessageDlg ('No unitid.txt found', mtError, [mbok], 0);
exit;
end;
groups := tlist.create;
// units := tlist.Create;
cursect := nil;
defunits := TList.Create;
curunits := defunits;
while not eof (f) do
begin
Readln (f, s);
s := Trim (s);
if Length (s) > 0 then
begin
case s[1] of
';' :;
'=' :begin
cursect := TSection.Create;
cursect.name := Copy (s, 2, 10000);
curunits.Add (cursect);
end;
'+' :begin
curunits := TList.Create;
groups.add (curunits);
end;
else
if not assigned (cursect) then
begin
ShowMessage('Unit id before section found.. Not good');
exit;
end;
Val ('$' + s, i, code);
if code <> 0 then
begin
showmessage('Non-hex unit id found. (' + s + ')');
exit;
end;
cursect.ids.Add (pointer (i));
end;
end;
end;
notloaded := false;
CloseFile(f);
end;
destructor TUnitIds.Destroy;
var
i, j :integer;
units :tlist;
begin
if assigned (groups) then
begin
for j := 0 to groups.count - 1 do
begin
units := tlist(groups.items[j]);
for i := 0 to units.count - 1 do
begin
TSection(units.items[i]).free;
end;
units.free;
end;
groups.free;
end;
inherited Destroy;
end;
function TUnitIds.GetName (id :longword) :string;
var
i, j :integer;
s :TSection;
begin
Result := '';
{ if not assigned (groups) then
exit;
for i := 0 to units.count - 1 do
begin
s := units.items [i];
for j := 0 to s.ids.Count - 1 do
begin
if longword(s.ids.items[j]) = id then
begin
Result := s.name;
exit;
end;
end;
end;}
end;
function TUnitIds.GetUnits (ids :TList) :TStringList;
var
i, j, k :integer;
units :tlist;
sect :Tsection;
tmp :TStringlist;
id :longword;
begin
tmp := TStringlist.Create;
Result := tmp;
if notloaded then
exit;
for i := 0 to groups.count - 1 do
begin
tmp.Clear;
units := groups.items [i];
for j := 0 to units.count - 1 do
begin
sect := units.items [j];
for k := 0 to sect.ids.count - 1 do
begin
id := longword(sect.ids.items[k]);
if ids.indexof (pointer (id)) <> -1 then
begin
tmp.Add (sect.name);
break;
end;
end;
end;
if tmp.count > 0 then
begin
break;
end;
end;
for i := 0 to defunits.count - 1 do
begin
sect := defunits.items [i];
for k := 0 to sect.ids.count - 1 do
begin
id := longword(sect.ids.items[k]);
if ids.indexof (pointer (id)) <> -1 then
begin
tmp.Add (sect.name);
break;
end;
end;
end;
end;
end.
|
{***************************************************************************}
{ }
{ DelphiUIAutomation }
{ }
{ Copyright 2015 JHC Systems Limited }
{ }
{***************************************************************************}
{ }
{ 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 DelphiUIAutomation.Exception;
interface
uses
sysutils;
type
EDelphiAutomationException = exception;
EWindowNotFoundException = EDelphiAutomationException;
implementation
end.
|
unit U_IWFormConsCliente;
interface
uses
Classes, SysUtils, IWAppForm, IWApplication, IWColor, IWTypes, IWCompGrids,
IWDBGrids, Vcl.Controls, IWVCLBaseControl, IWBaseControl, IWBaseHTMLControl,
IWControl, IWCompButton, Data.DB, IWVCLComponent, IWBaseLayoutComponent,
IWBaseContainerLayout, IWContainerLayout, IWTemplateProcessorHTML;
type
TIWFormConsCliente = class(TIWAppForm)
IWButtonPesquisar: TIWButton;
IWButtonIncluir: TIWButton;
IWButtonAlterar: TIWButton;
IWButtonExcluir: TIWButton;
IWButtonImprimir: TIWButton;
IWDBGridConsulta: TIWDBGrid;
IWButtonPrimeiro: TIWButton;
IWButtonAnterior: TIWButton;
IWButtonProximo: TIWButton;
IWButtonUltimo: TIWButton;
IWButtonVoltar: TIWButton;
DSConsCliente: TDataSource;
IWTemplateProcessorHTML1: TIWTemplateProcessorHTML;
procedure IWAppFormCreate(Sender: TObject);
procedure IWButtonPesquisarAsyncClick(Sender: TObject;
EventParams: TStringList);
procedure IWButtonPrimeiroAsyncClick(Sender: TObject;
EventParams: TStringList);
procedure IWButtonAnteriorAsyncClick(Sender: TObject;
EventParams: TStringList);
procedure IWButtonProximoAsyncClick(Sender: TObject;
EventParams: TStringList);
procedure IWButtonUltimoAsyncClick(Sender: TObject;
EventParams: TStringList);
public
end;
implementation
{$R *.dfm}
uses ServerController, U_DM;
procedure TIWFormConsCliente.IWAppFormCreate(Sender: TObject);
begin
DSConsCliente.DataSet:=UserSession.DM.CDSConsCliente;
end;
procedure TIWFormConsCliente.IWButtonAnteriorAsyncClick(Sender: TObject;
EventParams: TStringList);
begin
UserSession.DM.CDSConsCliente.MoveBy(- IWDBGridConsulta.RowLimit);
IWDBGridConsulta.RepaintControl;
end;
procedure TIWFormConsCliente.IWButtonPesquisarAsyncClick(Sender: TObject;
EventParams: TStringList);
begin
UserSession.DM.CDSConsCliente.Close;
UserSession.DM.CDSConsCliente.Open;
IWDBGridConsulta.RepaintControl;
end;
procedure TIWFormConsCliente.IWButtonPrimeiroAsyncClick(Sender: TObject;
EventParams: TStringList);
begin
UserSession.DM.CDSConsCliente.First;
IWDBGridConsulta.RepaintControl;
end;
procedure TIWFormConsCliente.IWButtonProximoAsyncClick(Sender: TObject;
EventParams: TStringList);
begin
UserSession.DM.CDSConsCliente.MoveBy(+ IWDBGridConsulta.RowLimit);
IWDBGridConsulta.RepaintControl;
end;
procedure TIWFormConsCliente.IWButtonUltimoAsyncClick(Sender: TObject;
EventParams: TStringList);
begin
UserSession.DM.CDSConsCliente.Last;
IWDBGridConsulta.RepaintControl;
end;
initialization
TIWFormConsCliente.SetAsMainForm;
end.
|
UNIT DefList; {enthlt die Informationen ber die einzelnen Elemente}
{Die Daten basieren auf dem deutschen Wikipedia-Artikel, abrufbar unter:
https://de.wikipedia.org/wiki/Periodensystem
(Stand: 23.02.2015)
und
der Formelsammlung des DUDEN PAETEC Schulbuchverlags
(ISBN 978-3-89818-700-8) }
INTERFACE {Deklarationen}
FUNCTION Symbol( a : INTEGER ) : STRING;
FUNCTION Namen( a : INTEGER ) : STRING;
FUNCTION Zustand( a : INTEGER ) : STRING;
IMPLEMENTATION {Definitionen}
{Liste der Elementsymbole}
FUNCTION Symbol( a : INTEGER ) : STRING;
Begin {of FUNCTION Symbol}
CASE a OF {Nummer des Elements}
1 : Symbol := 'H';
2 : Symbol := 'He';
3 : Symbol := 'Li';
4 : Symbol := 'Be';
5 : Symbol := 'B';
6 : Symbol := 'C';
7 : Symbol := 'N';
8 : Symbol := 'O';
9 : Symbol := 'F';
10 : Symbol := 'Ne';
11 : Symbol := 'Na';
12 : Symbol := 'Mg';
13 : Symbol := 'Al';
14 : Symbol := 'Si';
15 : Symbol := 'P';
16 : Symbol := 'S';
17 : Symbol := 'Cl';
18 : Symbol := 'Ar';
19 : Symbol := 'K';
20 : Symbol := 'Ca';
21 : Symbol := 'Sc';
22 : Symbol := 'Ti';
23 : Symbol := 'V';
24 : Symbol := 'Cr';
25 : Symbol := 'Mn';
26 : Symbol := 'Fe';
27 : Symbol := 'Co';
28 : Symbol := 'Ni';
29 : Symbol := 'Cu';
30 : Symbol := 'Zn';
31 : Symbol := 'Ga';
32 : Symbol := 'Ge';
33 : Symbol := 'As';
34 : Symbol := 'Se';
35 : Symbol := 'Br';
36 : Symbol := 'Kr';
37 : Symbol := 'Rb';
38 : Symbol := 'Sr';
39 : Symbol := 'Y';
40 : Symbol := 'Zr';
41 : Symbol := 'Nb';
42 : Symbol := 'Mo';
43 : Symbol := 'Tc';
44 : Symbol := 'Ru';
45 : Symbol := 'Rh';
46 : Symbol := 'Pd';
47 : Symbol := 'Ag';
48 : Symbol := 'Cd';
49 : Symbol := 'In';
50 : Symbol := 'Sn';
51 : Symbol := 'Sb';
52 : Symbol := 'Te';
53 : Symbol := 'I';
54 : Symbol := 'Xe';
55 : Symbol := 'Cs';
56 : Symbol := 'Ba';
57 : Symbol := 'La';
58 : Symbol := 'Ce';
59 : Symbol := 'Pr';
60 : Symbol := 'Nd';
61 : Symbol := 'Pm';
62 : Symbol := 'Sm';
63 : Symbol := 'Eu';
64 : Symbol := 'Gd';
65 : Symbol := 'Tb';
66 : Symbol := 'Dy';
67 : Symbol := 'Ho';
68 : Symbol := 'Er';
69 : Symbol := 'Tm';
70 : Symbol := 'Yb';
71 : Symbol := 'Lu';
72 : Symbol := 'Hf';
73 : Symbol := 'Ta';
74 : Symbol := 'W';
75 : Symbol := 'Re';
76 : Symbol := 'Os';
77 : Symbol := 'Ir';
78 : Symbol := 'Pt';
79 : Symbol := 'Au';
80 : Symbol := 'Hg';
81 : Symbol := 'Tl';
82 : Symbol := 'Pb';
83 : Symbol := 'Bi';
84 : Symbol := 'Po';
85 : Symbol := 'At';
86 : Symbol := 'Rn';
87 : Symbol := 'Fr';
88 : Symbol := 'Ra';
89 : Symbol := 'Ac';
90 : Symbol := 'Th';
91 : Symbol := 'Pa';
92 : Symbol := 'U';
93 : Symbol := 'Np';
94 : Symbol := 'Pu';
95 : Symbol := 'Am';
96 : Symbol := 'Cm';
97 : Symbol := 'Bk';
98 : Symbol := 'Cf';
99 : Symbol := 'Es';
100 : Symbol := 'Fm';
101 : Symbol := 'Md';
102 : Symbol := 'No';
103 : Symbol := 'Lr';
104 : Symbol := 'Rf';
105 : Symbol := 'Db';
106 : Symbol := 'Sg';
107 : Symbol := 'Bh';
108 : Symbol := 'Hs';
109 : Symbol := 'Mt';
110 : Symbol := 'Ds';
111 : Symbol := 'Rg';
112 : Symbol := 'Cn';
113 : Symbol := 'Uut';
114 : Symbol := 'Fl';
115 : Symbol := 'Uup';
116 : Symbol := 'Lv';
117 : Symbol := 'Uus';
118 : Symbol := 'Uuo';
End; {of CASE a OF}
End; {of FUNCTION Symbol}
{Liste der Elementnamen}
FUNCTION Namen( a : INTEGER ) : STRING;
Begin {of FUNCTION Namen}
CASE a OF {Nummer des Elements}
1 : Namen := 'Wasserstoff';
2 : Namen := 'Helium';
3 : Namen := 'Lithium';
4 : Namen := 'Beryllium';
5 : Namen := 'Bor';
6 : Namen := 'Kohlenstoff';
7 : Namen := 'Stickstoff';
8 : Namen := 'Sauerstoff';
9 : Namen := 'Fluor';
10 : Namen := 'Neon';
11 : Namen := 'Natrium';
12 : Namen := 'Magnesium';
13 : Namen := 'Aluminium';
14 : Namen := 'Silicium';
15 : Namen := 'Phosphor';
16 : Namen := 'Schwefel';
17 : Namen := 'Chlor';
18 : Namen := 'Argon';
19 : Namen := 'Kalium';
20 : Namen := 'Calcium';
21 : Namen := 'Scandium';
22 : Namen := 'Titanium';
23 : Namen := 'Vanadium';
24 : Namen := 'Chromium';
25 : Namen := 'Mangan';
26 : Namen := 'Eisen';
27 : Namen := 'Cobalt';
28 : Namen := 'Nickel';
29 : Namen := 'Kupfer';
30 : Namen := 'Zink';
31 : Namen := 'Gallium';
32 : Namen := 'Germanium';
33 : Namen := 'Arsen';
34 : Namen := 'Selen';
35 : Namen := 'Brom';
36 : Namen := 'Krypton';
37 : Namen := 'Rubidium';
38 : Namen := 'Strontium';
39 : Namen := 'Yttrium';
40 : Namen := 'Zirconium';
41 : Namen := 'Niobium';
42 : Namen := 'Molybdn';
43 : Namen := 'Technetium';
44 : Namen := 'Ruthenium';
45 : Namen := 'Rhodium';
46 : Namen := 'Palladium';
47 : Namen := 'Silber';
48 : Namen := 'Cadmium';
49 : Namen := 'Indium';
50 : Namen := 'Zinn';
51 : Namen := 'Antimon';
52 : Namen := 'Tellur';
53 : Namen := 'Iod';
54 : Namen := 'Xenon';
55 : Namen := 'Caesium';
56 : Namen := 'Barium';
57 : Namen := 'Lanthan';
58 : Namen := 'Cerium';
59 : Namen := 'Praesodymium';
60 : Namen := 'Neodymium';
61 : Namen := 'Promethium';
62 : Namen := 'Samarium';
63 : Namen := 'Europium';
64 : Namen := 'Gadolinium';
65 : Namen := 'Terbium';
66 : Namen := 'Dysprosium';
67 : Namen := 'Holmium';
68 : Namen := 'Erbium';
69 : Namen := 'Thulium';
70 : Namen := 'Ytterbium';
71 : Namen := 'Lutetium';
72 : Namen := 'Hafnium';
73 : Namen := 'Tantal';
74 : Namen := 'Wolfram';
75 : Namen := 'Rhenium';
76 : Namen := 'Osmium';
77 : Namen := 'Iridium';
78 : Namen := 'Platin';
79 : Namen := 'Gold';
80 : Namen := 'Quecksilber';
81 : Namen := 'Thallium';
82 : Namen := 'Blei';
83 : Namen := 'Bismut';
84 : Namen := 'Polonium';
85 : Namen := 'Astat';
86 : Namen := 'Radon';
87 : Namen := 'Francium';
88 : Namen := 'Radium';
89 : Namen := 'Actinium';
90 : Namen := 'Thorium';
91 : Namen := 'Protactinium';
92 : Namen := 'Uranium';
93 : Namen := 'Neptunium';
94 : Namen := 'Plutonium';
95 : Namen := 'Americium';
96 : Namen := 'Curium';
97 : Namen := 'Berkelium';
98 : Namen := 'Californium';
99 : Namen := 'Einsteinium';
100 : Namen := 'Fermium';
101 : Namen := 'Mendelevium';
102 : Namen := 'Nobelium';
103 : Namen := 'Lawrencium';
104 : Namen := 'Rutherfordium';
105 : Namen := 'Dubnium';
106 : Namen := 'Seaborgium';
107 : Namen := 'Bohrium';
108 : Namen := 'Hassium';
109 : Namen := 'Meitnerium';
110 : Namen := 'Darmstadtium';
111 : Namen := 'Roentgenium';
112 : Namen := 'Copernicium';
113 : Namen := 'Ununtrium';
114 : Namen := 'Flerovium';
115 : Namen := 'Ununpentium';
116 : Namen := 'Livermorium';
117 : Namen := 'Ununseptium';
118 : Namen := 'Ununoctium';
End; {of CASE a OF}
End; {of FUNCTION Namen}
{Liste der Aggregatzustnde}
FUNCTION Zustand( a : INTEGER ) : STRING;
Begin {of FUNCTION Zustand}
CASE a OF {Nummer des Elements}
1 : Zustand := 'g';
2 : Zustand := 'g';
7 : Zustand := 'g';
8 : Zustand := 'g';
9 : Zustand := 'g';
10 : Zustand := 'g';
17 : Zustand := 'g';
18 : Zustand := 'g';
35 : Zustand := 'l';
36 : Zustand := 'g';
54 : Zustand := 'g';
80 : Zustand := 'l';
86 : Zustand := 'g';
104 : Zustand := 'u';
105 : Zustand := 'u';
106 : Zustand := 'u';
107 : Zustand := 'u';
108 : Zustand := 'u';
109 : Zustand := 'u';
110 : Zustand := 'u';
111 : Zustand := 'u';
112 : Zustand := 'u';
113 : Zustand := 'u';
114 : Zustand := 'u';
115 : Zustand := 'u';
116 : Zustand := 'u';
117 : Zustand := 'u';
118 : Zustand := 'u';
{da die meisten Elemente Feststoffe sind, sind zuvor nur abweichende
Aggregatzustnde definiert, durch ELSE die Feststoffe definiert}
ELSE Zustand := 's';
End; {of CASE a OF}
End; {of FUNCTION Zustand}
END . {of UNIT DefList} |
unit U_Ping.View;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, ipwcore,
ipwtypes, ipwping, FMX.Layouts, FMX.Controls.Presentation, FMX.ScrollBox,
FMX.Memo, FMX.StdCtrls, System.ImageList, FMX.ImgList, FMX.Edit, FMX.Objects,
System.StrUtils;
type
TPingView = class(TForm)
ipwPing1: TipwPing;
LayoutHeader: TLayout;
LayoutContent: TLayout;
MemoPong: TMemo;
Layout1: TLayout;
Text1: TText;
Text2: TText;
Edit1: TEdit;
Edit2: TEdit;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
ImageList1: TImageList;
Timer1: TTimer;
StatusBar1: TStatusBar;
Text3: TText;
procedure FormShow(Sender: TObject);
procedure ipwPing1Response(Sender: TObject; RequestId: Integer;
const ResponseSource, ResponseStatus: string; ResponseTime: Integer);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
var
fOK : integer;
fPerdidos : integer;
fMedia : Integer;
procedure ping();
public
constructor create(Sender : TComponent; address : String);
end;
implementation
{$R *.fmx}
{ TForm1 }
constructor TPingView.create(Sender: TComponent; address: String);
begin
inherited Create(Sender);
ipwPing1.Config('ReceiveAllMode=0');
ipwPing1.LocalHost := address;
end;
procedure TPingView.FormShow(Sender: TObject);
begin
MemoPong.Lines.Clear;
end;
procedure TPingView.ipwPing1Response(Sender: TObject; RequestId: Integer;
const ResponseSource, ResponseStatus: string; ResponseTime: Integer);
begin
MemoPong.Lines.Add(
format(
'Resposta de %s -> bytes=%d tempo=%dms',
[ResponseSource, ipwPing1.PacketSize, ResponseTime]
)
);
if ResponseStatus = 'OK' then
begin
inc(fOK, 1);
end else begin
inc(fPerdidos, 1);
end;
inc(fMedia, ResponseTime);
Text3.Text:= format(
'Total de pacotes: %d Sucesso: %d Perda: %d Média de Tempo: %dms',
[fOK + fPerdidos, fOK, fPerdidos, fMedia div fOK]
);
end;
procedure TPingView.ping;
begin
ipwPing1.PingHost(Edit1.Text);
end;
procedure TPingView.SpeedButton1Click(Sender: TObject);
begin
fPerdidos := 0;
fOK := 0;
fMedia := 0;
MemoPong.Lines.Clear;
if Edit1.Text <> EmptyStr then
begin
with ipwPing1 do
begin
PacketSize := ifThen(Edit2.Text <> EmptyStr, Edit2.Text, '32').ToInteger;
RemoteHost := Edit1.Text;
Active := True;
Timer1.Enabled := True;
end;
end;
end;
procedure TPingView.SpeedButton2Click(Sender: TObject);
begin
Timer1.Enabled := False;
ipwPing1.Active := False;
end;
procedure TPingView.Timer1Timer(Sender: TObject);
begin
ping();
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Container;
type
TForm1 = class(TForm)
Panel1: TPanel;
Label1: TLabel;
edSource: TEdit;
btnBrowse: TButton;
btnCopy: TButton;
OpenDialog1: TOpenDialog;
Label2: TLabel;
edDest: TEdit;
Button1: TButton;
cpOptions: TContainerProxy;
lbResult: TLabel;
procedure btnCopyClick(Sender: TObject);
procedure btnBrowseClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
FileHandle : THandle;
end;
var
Form1: TForm1;
implementation
uses ExtUtils,FileCopyOptCnt;
{$R *.DFM}
procedure TForm1.btnCopyClick(Sender: TObject);
var
options : TCopyAgentOptions;
r : TCopyAgentReturnCode;
CompResult : TCFIResult;
begin
(cpOptions.Container as TctFileCopyOptions)
.GetCopyOptions(options);
r := CopyFileEx(edSource.Text,edDest.text,options,CompResult);
lbResult.caption := CopyResultMsg[r];
end;
procedure TForm1.btnBrowseClick(Sender: TObject);
begin
if OpenDialog1.Execute then
edSource.Text := OpenDialog1.FileName;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
edDest.Text := OpenDialog1.FileName;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
{(cpOptions.Container as TctFileCopyOptions)
.SetCopyOptions(caoCopyWhenNeed);}
end;
end.
|
unit RPDataBrowsers;
{**********************************************
Kingstar Delphi Library
Copyright (C) Kingstar Corporation
<Unit>RPDataBrowsers (Report Data Browser)
<What>在打印报表时,控制数据集的浏览(游标移动)
<Written By> Huang YanLai (黄燕来)
<History>
修改自UDataBrowsers.pas(用于算法测试),类名使用前缀RP
**********************************************}
interface
uses SysUtils, Classes, Contnrs, RPDB;
type
TRPDatasetController = class;
TRPDatasetGroup = class;
{
<Class>TRPDataBrowser
<What>抽象的数据集浏览对象
<Properties>
-
<Methods>
Init - 初始化
GotoNextData - 获得下一个数据行。如果没有数据返回false
Eof - 是否结束
<Event>
-
}
TRPDataBrowser = class (TObject)
private
FEof: Boolean;
FEnvironment: TRPDataEnvironment;
protected
FIsFirst : Boolean;
function InternalGotoNextData: Boolean; virtual; abstract;
public
procedure Init; virtual;
function GotoNextData: Boolean;
property Eof : Boolean read FEof;
property Environment : TRPDataEnvironment read FEnvironment write FEnvironment;
end;
{
<Class>TRPDatasetBrowser
<What>数据集浏览对象
使用TRPDatasetController对象,浏览数据。
<Properties>
Controller - 关联到控制对象(根据ReportName和ControllerName确定)
GroupingIndex - 分组的编号
ReportName - 报表名称
ControllerName - Controller的名字
Available - 是否有效
<Methods>
-
<Event>
-
}
TRPDatasetBrowser = class (TRPDataBrowser)
private
FInternalCount : Integer;
FGrouping : TRPDatasetGroup;
FGroupingIndex: Integer;
FController: TRPDatasetController;
FControllerName : String;
//FReportName: string;
//function GetControllerName: String;
procedure SetControllerName(const Value: String);
//procedure SetReportName(const Value: string);
procedure CheckController;
procedure SetController(const Value: TRPDatasetController);
protected
function GetCurrentCount: Integer;
function InternalGotoNextData: Boolean; override;
public
constructor Create;
procedure Init; override;
property Controller : TRPDatasetController read FController write SetController;
property GroupingIndex : Integer read FGroupingIndex write FGroupingIndex;
property InternalCount : Integer read FInternalCount;
//property ReportName : string read FReportName write SetReportName;
property ControllerName : string read FControllerName write SetControllerName;
function Available: Boolean;
end;
{
<Class>TRPDatasetController
<What>控制数据集的移动。支持分组。
<Properties>
Dataset - 关联的数据集对象
ControllerName - 名字
ReportName - 报表名字
Groups - 分组(每一行是该分组的字段名称,字段之间用“;”分割)
FromFirst - 在初始化的时候是否调用Dataset.first
<Methods>
Init - 初始化
GetData - 获得数据。如果IsGetNewData=true,先移动Dataset的游标(Dataest.next)
InternalCount - 内部计数。
Available - 是否有效
GoBack - 回退游标。当数据移动到下一个分组的时候被调用。
CheckGrouping - 检查是否发生分组变化
<Event>
-
}
TRPDatasetController = class (TComponent)
private
FInternalCount: Integer;
FGroupings : TObjectList;
//FIsFirst : Boolean;
FDataset: TRPDataset;
FControllerName: string;
FReportName: string;
FGroups: TStrings;
FFromFirst: Boolean;
//FDataSource : TDataSource;
procedure SetDataset(const Value: TRPDataset);
function AddGroup: TRPDatasetGroup;
procedure SetGroups(const Value: TStrings);
protected
procedure CheckGrouping;
procedure GoBack;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner : TComponent); override;
Destructor Destroy; override;
procedure Init;
function GetData(IsGetNewData : Boolean): Boolean;
property InternalCount : Integer read FInternalCount;
//function AddGroup : TRPDatasetGroup;
function Available: Boolean;
published
property Dataset : TRPDataset read FDataset write SetDataset;
property ControllerName : string read FControllerName write FControllerName;
property ReportName : string read FReportName write FReportName;
property Groups : TStrings read FGroups write SetGroups;
property FromFirst: Boolean read FFromFirst write FFromFirst default true;
end;
// 保存字段的数据
TGroupFieldData = Record
SValue : string; // for gfdtString because it cannot in a variant record
case DataType : TRPFieldDataType of
gfdtInteger : (IValue : Integer);
gfdtFloat : (FValue : Double);
gfdtDate : (DValue : TDateTime);
end;
{
<Class>TRPGroupField
<What>保存字段的数据,并且检查数据是否发生改变
<Properties>
-
<Methods>
-
<Event>
-
}
TRPGroupField = class (TObject)
private
FSavedData : TGroupFieldData;
FField: TRPDataField;
protected
public
constructor Create(AField : TRPDataField);
procedure SaveValue;
function IsChanged : Boolean;
property Field : TRPDataField read FField;
end;
{
<Class>TRPDatasetGroup
<What>代表一个分组
<Properties>
-
<Methods>
-
<Event>
-
}
TRPDatasetGroup = class (TObject)
private
FInternalCount: Integer;
FController: TRPDatasetController;
//FFields : TList;
FGroupFields : TObjectList;
FFieldNames: String;
protected
procedure PrepareGroupFields;
procedure SaveGroupFieldsData;
function IsGroupChanged : Boolean;
procedure SetNewGroup;
public
constructor Create(AController : TRPDatasetController);
Destructor Destroy; override;
procedure Init;
procedure Prepare;
{procedure AddField(Field : TField); overload;
procedure AddField(const FieldName : string); overload;}
property InternalCount : Integer read FInternalCount;
property Controller : TRPDatasetController read FController;
//property Fields : TList read FFields;
property FieldNames : String read FFieldNames write FFieldNames;
end;
(*
{
<Class>TRPControllerManager
<What>管理所有的TRPDatasetController对象
<Properties>
-
<Methods>
-
<Event>
-
}
TRPControllerManager = class (TObject)
private
FControllers: TObjectList;
protected
public
constructor Create;
Destructor Destroy; override;
procedure Init(const ReportName:string; DatasetList : TList=nil);
function FindController(const ReportName, Name:String): TRPDatasetController;
property Controllers : TObjectList read FControllers;
end;
var
ControllerManager : TRPControllerManager;
*)
implementation
{ TRPDataBrowser }
function TRPDataBrowser.GotoNextData: Boolean;
begin
Result := InternalGotoNextData;
FEof := not Result;
FIsFirst := false;
end;
procedure TRPDataBrowser.Init;
begin
FEof := False;
FIsFirst := True;
end;
{ TRPDatasetBrowser }
constructor TRPDatasetBrowser.Create;
begin
FController := nil;
FGroupingIndex := -1;
FGrouping := nil;
end;
function TRPDatasetBrowser.Available: Boolean;
begin
Result := (FController<>nil) and FController.Available;
end;
procedure TRPDatasetBrowser.CheckController;
begin
if Controller=nil then
begin
Assert(FEnvironment<>nil);
Controller := FEnvironment.FindController(FControllerName);
end;
end;
{
function TRPDatasetBrowser.GetControllerName: String;
begin
if FController<>nil then
Result := FController.ControllerName
else
Result := FControllerName;
end;
}
function TRPDatasetBrowser.GetCurrentCount: Integer;
begin
if FGrouping<>nil then
Result:= FGrouping.FInternalCount
else
Result:= FController.FInternalCount;
end;
procedure TRPDatasetBrowser.Init;
begin
inherited;
CheckController;
if (FGroupingIndex>=0) and (FGroupingIndex<FController.FGroupings.Count) then
FGrouping := TRPDatasetGroup(FController.FGroupings[FGroupingIndex])
else
FGrouping := nil;
if FGrouping<>nil then
FGrouping.Prepare;
FInternalCount := GetCurrentCount;
end;
function TRPDatasetBrowser.InternalGotoNextData: Boolean;
{var
CurrentGroupIndex : Integer;}
begin
Assert(FController<>nil);
if FInternalCount<>GetCurrentCount then
Result:=false // reach a new dataset or a new group
else
begin
// return true when there are data and not reach a new dataset or a new group
Result := FController.GetData(not FIsFirst);
if Result then
Result := (FInternalCount=GetCurrentCount);
end;
end;
procedure TRPDatasetBrowser.SetController(
const Value: TRPDatasetController);
begin
if FController <> Value then
begin
FController := Value;
if FController<>nil then
begin
FReportName := FController.ReportName;
FControllerName := FController.ControllerName;
end;
end;
end;
procedure TRPDatasetBrowser.SetControllerName(const Value: String);
begin
if FControllerName <> Value then
begin
FControllerName := Value;
//Controller := ControllerManager.FindController(FReportName,FControllerName);
end;
end;
(*
procedure TRPDatasetBrowser.SetReportName(const Value: string);
begin
if FReportName <> Value then
begin
FReportName := Value;
Controller := ControllerManager.FindController(FReportName,FControllerName);
end;
end;
*)
{ TRPDatasetController }
constructor TRPDatasetController.Create(AOwner : TComponent);
begin
inherited;
FGroupings := TObjectList.Create;
FGroups:= TStringList.Create;
Assert(ControllerManager<>nil);
ControllerManager.FControllers.Add(self);
FFromFirst := true;
//FDataSource := TDataSource.Create;
end;
destructor TRPDatasetController.Destroy;
var
Obj : TObject;
begin
if (ControllerManager<>nil) and (ControllerManager.FControllers<>nil) then
ControllerManager.FControllers.Extract(self);
//FDataSource.Free;
FGroups.Free;
Obj := FGroupings;
FGroupings := nil;
Obj.Free;
inherited;
end;
function TRPDatasetController.AddGroup: TRPDatasetGroup;
begin
Result := TRPDatasetGroup.Create(self);
end;
function TRPDatasetController.GetData(IsGetNewData : Boolean): Boolean;
begin
if IsGetNewData then
begin
Dataset.Next;
Result := not Dataset.Eof;
if Result then
CheckGrouping;
end
else
begin
//Result := not Dataset.Empty;
Result := not Dataset.Eof;
end;
//IsFirst := False;
end;
procedure TRPDatasetController.Init;
var
i : integer;
s : string;
begin
Assert(Dataset<>nil);
if FromFirst then
Dataset.First;
//IsFirst := True;
FInternalCount := 0;
FGroupings.Clear;
for i:=0 to FGroups.Count-1 do
begin
s := trim(FGroups[i]);
if s<>'' then
AddGroup.FieldNames := s;
end;
for i:=0 to FGroupings.Count-1 do
TRPDatasetGroup(FGroupings[i]).Init;
end;
procedure TRPDatasetController.SetDataset(const Value: TRPDataset);
begin
if FDataset <> Value then
begin
FDataset := Value;
if Dataset<>nil then
Dataset.FreeNotification(Self);
end;
//FDataSource.Dataset := Value;
end;
procedure TRPDatasetController.CheckGrouping;
var
i : integer;
Changed : Boolean;
Group : TRPDatasetGroup;
begin
Changed := false;
for i:=0 to FGroupings.Count-1 do
begin
Assert(TObject(FGroupings[i]) is TRPDatasetGroup);
Group := TRPDatasetGroup(FGroupings[i]);
if Changed then
Group.SetNewGroup
else
Changed := Group.IsGroupChanged;
end;
{ !!!!
If group changed, it will call GoBack to stop cursor at the end of current group.
The outter none-changed group will call GetData(true) to move cursor at the start of the new group
}
if Changed then
GoBack;
end;
procedure TRPDatasetController.GoBack;
begin
Assert(Dataset<>nil);
Dataset.Prior;
end;
function TRPDatasetController.Available: Boolean;
begin
Result := Dataset<>nil;
end;
procedure TRPDatasetController.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (AComponent=Dataset) and (Operation=opRemove) then
FDataset := nil;
end;
procedure TRPDatasetController.SetGroups(const Value: TStrings);
begin
FGroups.Assign(Value);
end;
{ TRPDatasetGroup }
constructor TRPDatasetGroup.Create(AController: TRPDatasetController);
begin
Assert(AController<>nil);
FController := AController;
FController.FGroupings.Add(self);
//FFields := TList.Create;
FFieldNames := '';
FGroupFields := TObjectList.Create;
end;
destructor TRPDatasetGroup.Destroy;
begin
if FController.FGroupings<>nil then
FController.FGroupings.Extract(self);
//FFields.Free;
FGroupFields.Free;
inherited;
end;
procedure TRPDatasetGroup.Init;
begin
FInternalCount := 0;
end;
{
procedure TRPDatasetGroup.AddField(Field: TField);
begin
if Field<>nil then
begin
Assert(Field.Dataset=FController.Dataset);
FFields.Add(Field);
end;
end;
procedure TRPDatasetGroup.AddField(const FieldName: string);
begin
AddField(FController.Dataset.FindField(FieldName));
end;
}
function TRPDatasetGroup.IsGroupChanged: Boolean;
var
i : integer;
begin
Result := false;
for i:=0 to FGroupFields.Count-1 do
if TRPGroupField(FGroupFields[i]).IsChanged then
begin
Result := true;
Break;
end;
if Result then
SetNewGroup;
end;
procedure TRPDatasetGroup.Prepare;
begin
// must re-create fields
// because in master-detail link
// the detail table field objects may be re-created
//(example detail table is a TQuery)
PrepareGroupFields;
SaveGroupFieldsData;
end;
procedure TRPDatasetGroup.PrepareGroupFields;
var
i,len : integer;
S,FieldName : string;
Field : TRPDataField;
begin
S := FFieldNames;
FGroupFields.Clear;
S := Trim(S);
len := Length(S);
while len>0 do
begin
i := pos(';',S);
if (i>0) then
begin
FieldName := Copy(S,1,i-1);
S := Copy(S,i+1,len);
end
else
begin
FieldName := S;
S := '';
end;
{ TODO : Correct Field }
Field := FController.Dataset.FindField(FieldName);
if Field<>nil then
FGroupFields.Add(TRPGroupField.Create(Field));
len := Length(S);
end;
end;
procedure TRPDatasetGroup.SaveGroupFieldsData;
var
i : integer;
begin
for i:=0 to FGroupFields.Count-1 do
TRPGroupField(FGroupFields[i]).SaveValue;
end;
procedure TRPDatasetGroup.SetNewGroup;
begin
Inc(FInternalCount);
// must have this below line!
// 将字段的值设定为新组的值可以避免再次产生分组.
SaveGroupFieldsData;
end;
{ TRPControllerManager }
constructor TRPControllerManager.Create;
begin
FControllers := TObjectList.Create;
end;
destructor TRPControllerManager.Destroy;
var
Obj : TObject;
begin
Obj := FControllers;
FControllers := nil;
Obj.Free;
inherited;
end;
function TRPControllerManager.FindController(
const ReportName, Name: String): TRPDatasetController;
var
i : integer;
begin
if Name<>'' then
for i:=0 to FControllers.Count-1 do
begin
Result := TRPDatasetController(FControllers[i]);
if (CompareText(Result.ControllerName,Name)=0)
and (CompareText(Result.ReportName,ReportName)=0) then
Exit;
end;
Result := nil;
end;
procedure TRPControllerManager.Init(const ReportName:string; DatasetList : TList);
var
i : integer;
Controller : TRPDatasetController;
begin
for i:=0 to FControllers.Count-1 do
begin
Controller := TRPDatasetController(FControllers[i]);
if CompareText(Controller.ReportName,ReportName)=0 then
begin
Controller.Init;
if (DatasetList<>nil) and (Controller.Dataset<>nil) then
DatasetList.Add(Controller.Dataset);
end;
end;
end;
{ TRPGroupField }
constructor TRPGroupField.Create(AField: TRPDataField);
begin
FField := AField;
FSavedData.DataType := FField.FieldType;
end;
function TRPGroupField.IsChanged: Boolean;
begin
Result := true;
case FSavedData.DataType of
gfdtInteger: Result := FSavedData.IValue <> FField.AsInteger;
gfdtFloat: Result := FSavedData.FValue <> FField.AsFloat;
gfdtString: Result := FSavedData.SValue <> FField.AsString;
gfdtDate: Result := FSavedData.DValue <> FField.AsDateTime;
else Assert(false);
end;
end;
procedure TRPGroupField.SaveValue;
begin
case FSavedData.DataType of
gfdtInteger: FSavedData.IValue := FField.AsInteger;
gfdtFloat: FSavedData.FValue := FField.AsFloat;
gfdtString: FSavedData.SValue := FField.AsString;
gfdtDate: FSavedData.DValue := FField.AsDateTime;
end;
end;
initialization
ControllerManager := TRPControllerManager.Create;
finalization
ControllerManager.Free;
end.
|
unit ClientLogOnInfo;
interface
type
TClientLogOnInfo = class
end;
TClientLogOnInfoClass = class of TClientLogOnInfo;
TUserLogOnInfo = class (TClientLogOnInfo)
public
UserName: String;
Password: String;
constructor Create(const UserName, Password: String);
end;
implementation
{ TUserLogOnInfo }
constructor TUserLogOnInfo.Create(const UserName, Password: String);
begin
inherited Create;
Self.UserName := UserName;
Self.Password := Password;
end;
end.
|
unit TestKM_Scripting;
interface
uses
TestFramework, StrUtils, Classes,
SysUtils,
KM_Defaults, KM_Scripting, KM_Log, KM_Utils;
type
TestKMScripting = class(TTestCase)
private
fScripting: TKMScripting;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestLoadAllMaps;
end;
implementation
uses KM_Maps;
procedure TestKMScripting.SetUp;
begin
ExeDir := ExtractFilePath(ParamStr(0)) + '..\';
gLog := TKMLog.Create(ExtractFilePath(ParamStr(0)) + 'Temp\temp.log');
fScripting := TKMScripting.Create;
end;
procedure TestKMScripting.TearDown;
begin
fScripting.Free;
gLog.Free;
end;
//See if all maps load into Scripting
procedure TestKMScripting.TestLoadAllMaps;
var
I: Integer;
GoodMaps: Integer;
PathToMaps: TStringList;
begin
GoodMaps := 0;
PathToMaps := TStringList.Create;
try
TKMapsCollection.GetAllMapPaths(ExeDir, PathToMaps);
for I := 0 to PathToMaps.Count - 1 do
if FileExists(ChangeFileExt(PathToMaps[I], '.script')) then
begin
try
fScripting.LoadFromFile(ChangeFileExt(PathToMaps[I], '.script'));
Inc(GoodMaps);
except
//Report and swallow asserts
on E: EAssertionFailed do
Status('Script did not load: ' + PathToMaps[I] + '. '+ E.Message);
end;
Check(fScripting.ErrorString = '', 'Script did not load: ' + PathToMaps[I]);
end;
Status(IntToStr(PathToMaps.Count - GoodMaps) + ' of ' + IntToStr(PathToMaps.Count) + ' scripts failed');
finally
PathToMaps.Free;
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestKMScripting.Suite);
end.
|
unit TSTOProjectWorkSpaceIntf;
interface
Uses
Windows, Classes, HsInterfaceEx, HsStreamEx, TSTOHackSettingsIntf;
Type
TWorkSpaceProjectKind = (spkRoot, spkDLCServer);
TWorkSpaceProjectType = (sptScript, sptTextPools);
ITSTOWorkSpaceProjectSrcFile = Interface(IInterfaceEx)
['{4B61686E-29A0-2112-8E6D-57596CAB70AD}']
Function GetFileName() : AnsiString;
Procedure SetFileName(Const AFileName : AnsiString);
Property FileName : AnsiString Read GetFileName Write SetFileName;
End;
ITSTOWorkSpaceProjectSrcFiles = Interface(IInterfaceListEx)
['{4B61686E-29A0-2112-9E79-0BE428CB0964}']
Function Get(Index : Integer) : ITSTOWorkSpaceProjectSrcFile;
Procedure Put(Index : Integer; Const Item : ITSTOWorkSpaceProjectSrcFile);
Function Add() : ITSTOWorkSpaceProjectSrcFile; OverLoad;
Function Add(Const AItem : ITSTOWorkSpaceProjectSrcFile) : Integer; OverLoad;
Function Remove(Const Item : ITSTOWorkSpaceProjectSrcFile) : Integer;
Property Items[Index : Integer] : ITSTOWorkSpaceProjectSrcFile Read Get Write Put; Default;
End;
ITSTOWorkSpaceProjectSrcFolder = Interface(IInterfaceEx)
['{4B61686E-29A0-2112-9B7D-067ED048E586}']
Function GetSrcPath() : AnsiString;
Procedure SetSrcPath(Const ASrcPath : AnsiString);
Function GetSrcFileCount() : Integer;
Function GetFileList() : ITSTOWorkSpaceProjectSrcFiles;
Function GetSrcFiles(Index : Integer) : ITSTOWorkSpaceProjectSrcFile;
Procedure Add(Const AFileName : AnsiString); OverLoad;
Function Add(Const AItem : ITSTOWorkSpaceProjectSrcFile) : Integer; OverLoad;
Function Add() : ITSTOWorkSpaceProjectSrcFile; OverLoad;
Procedure Assign(ASource : IInterface);
Property SrcPath : AnsiString Read GetSrcPath Write SetSrcPath;
Property SrcFileCount : Integer Read GetSrcFileCount;
Property FileList : ITSTOWorkSpaceProjectSrcFiles Read GetFileList;
Property SrcFiles[Index : Integer] : ITSTOWorkSpaceProjectSrcFile Read GetSrcFiles; Default;
End;
ITSTOWorkSpaceProjectSrcFolders = Interface(IInterfaceListEx)
['{4B61686E-29A0-2112-BBEA-5356FC33F428}']
Function Get(Index : Integer) : ITSTOWorkSpaceProjectSrcFolder;
Procedure Put(Index : Integer; Const Item : ITSTOWorkSpaceProjectSrcFolder);
Function Add() : ITSTOWorkSpaceProjectSrcFolder; OverLoad;
Function Add(Const AItem : ITSTOWorkSpaceProjectSrcFolder) : Integer; OverLoad;
Procedure Assign(ASource : IInterface);
Property Items[Index : Integer] : ITSTOWorkSpaceProjectSrcFolder Read Get Write Put; Default;
End;
ITSTOWorkSpaceProject = Interface(IInterfaceEx)
['{4B61686E-29A0-2112-8C64-5B308DF5B5E2}']
Function GetProjectName() : AnsiString;
Procedure SetProjectName(Const AProjectName : AnsiString);
Function GetProjectKind() : TWorkSpaceProjectKind;
Procedure SetProjectKind(Const AProjectKind : TWorkSpaceProjectKind);
Function GetProjectType() : TWorkSpaceProjectType;
Procedure SetProjectType(Const AProjectType : TWorkSpaceProjectType);
Function GetZeroCrc32() : DWord;
Procedure SetZeroCrc32(Const AZeroCrc32 : DWord);
Function GetPackOutput() : Boolean;
Procedure SetPackOutput(Const APackOutput : Boolean);
Function GetOutputPath() : AnsiString;
Procedure SetOutputPath(Const AOutputPath : AnsiString);
Function GetCustomScriptPath() : AnsiString;
Procedure SetCustomScriptPath(Const ACustomScriptPath : AnsiString);
Function GetCustomModPath() : AnsiString;
Procedure SetCustomModPath(Const ACustomModPath : AnsiString);
Function GetSrcFolders() : ITSTOWorkSpaceProjectSrcFolders;
Procedure Assign(ASource : IInterface);
Property ProjectName : AnsiString Read GetProjectName Write SetProjectName;
Property ProjectKind : TWorkSpaceProjectKind Read GetProjectKind Write SetProjectKind;
Property ProjectType : TWorkSpaceProjectType Read GetProjectType Write SetProjectType;
Property ZeroCrc32 : DWord Read GetZeroCrc32 Write SetZeroCrc32;
Property PackOutput : Boolean Read GetPackOutput Write SetPackOutput;
Property OutputPath : AnsiString Read GetOutputPath Write SetOutputPath;
Property CustomScriptPath : AnsiString Read GetCustomScriptPath Write SetCustomScriptPath;
Property CustomModPath : AnsiString Read GetCustomModPath Write SetCustomModPath;
Property SrcFolders : ITSTOWorkSpaceProjectSrcFolders Read GetSrcFolders;
End;
ITSTOWorkSpaceProjectGroup = Interface(IInterfaceListEx)
['{4B61686E-29A0-2112-B8A2-605112DD5688}']
Function Get(Index : Integer) : ITSTOWorkSpaceProject;
Procedure Put(Index : Integer; Const Item : ITSTOWorkSpaceProject);
Function GetProjectGroupName() : AnsiString;
Procedure SetProjectGroupName(Const AProjectGroupName : AnsiString);
Function GetHackFileName() : AnsiString;
Procedure SetHackFileName(Const AHackFileName : AnsiString);
Function GetPackOutput() : Boolean;
Procedure SetPackOutput(Const APackOutput : Boolean);
Function GetOutputPath() : AnsiString;
Procedure SetOutputPath(Const AOutputPath : AnsiString);
Function Add() : ITSTOWorkSpaceProject; OverLoad;
Function Add(Const AItem : ITSTOWorkSpaceProject) : Integer; OverLoad;
Function Remove(Const Item : ITSTOWorkSpaceProject) : Integer;
Procedure Assign(ASource : IInterface);
Property Items[Index : Integer] : ITSTOWorkSpaceProject Read Get Write Put; Default;
Property ProjectGroupName : AnsiString Read GetProjectGroupName Write SetProjectGroupName;
Property HackFileName : AnsiString Read GetHackFileName Write SetHackFileName;
Property PackOutput : Boolean Read GetPackOutput Write SetPackOutput;
Property OutputPath : AnsiString Read GetOutputPath Write SetOutputPath;
End;
implementation
end.
|
unit CoreEndpoint;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Core;
type
ICoreEndpoint = interface(IInterface) ['{BAEFF00E-C8A3-4D3E-B42E-7AFEAA79E37C}']
function All: ICoreList;
function One(const Id: string): ICore;
end;
function NewCoreEndpoint: ICoreEndpoint;
implementation
uses
Endpoint_Helper;
const
Endpoint = 'cores/';
type
{ TCoreEndpoint }
TCoreEndpoint = class(TInterfacedObject, ICoreEndpoint)
function All: ICoreList;
function One(const Id: string): ICore;
end;
function NewCoreEndpoint: ICoreEndpoint;
begin
Result := TCoreEndpoint.Create;
end;
{ TCoreEndpoint }
function TCoreEndpoint.All: ICoreList;
begin
Result := NewCoreList;
EndpointToModel(Endpoint, Result);
end;
function TCoreEndpoint.One(const Id: string): ICore;
begin
Result := NewCore;
EndpointToModel(SysUtils.ConcatPaths([Endpoint, Id]), Result);
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.Controls.Presentation, FMX.ScrollBox, FMX.Memo,
DW.Connectivity;
type
TForm1 = class(TForm)
Memo1: TMemo;
private
FConnectivity: TConnectivity;
procedure ConnectivityChangeHandler(Sender: TObject; const AIsConnected: Boolean);
public
constructor Create(AOwner: TComponent); override;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{ TForm1 }
constructor TForm1.Create(AOwner: TComponent);
begin
inherited;
if TConnectivity.IsConnectedToInternet then
begin
Memo1.Lines.Add('Device is connected to the internet');
if TConnectivity.IsWifiInternetConnection then
Memo1.Lines.Add('via Wifi');
end
else
Memo1.Lines.Add('Device is NOT connected to the internet');
FConnectivity := TConnectivity.Create;
FConnectivity.OnConnectivityChange := ConnectivityChangeHandler;
end;
procedure TForm1.ConnectivityChangeHandler(Sender: TObject; const AIsConnected: Boolean);
begin
if AIsConnected then
Memo1.Lines.Add('Connected!')
else
Memo1.Lines.Add('Disconnected!');
end;
end.
|
unit LayoutItem;
interface
uses
Windows,
SysUtils,
Classes;
type
TLayoutItem = class abstract (TObject)
protected
function GetLeft: Integer; virtual; abstract;
function GetTop: Integer; virtual; abstract;
function GetRight: Integer; virtual;
function GetBottom: Integer; virtual;
function GetBoundsRect: TRect; virtual;
function GetHeight: Integer; virtual; abstract;
function GetWidth: Integer; virtual; abstract;
procedure SetLeft(const Value: Integer); virtual; abstract;
procedure SetTop(const Value: Integer); virtual; abstract;
procedure SetRight(const Value: Integer); virtual;
procedure SetBottom(const Value: Integer); virtual;
procedure SetBoundsRect(const Value: TRect); virtual;
procedure SetHeight(const Value: Integer); virtual; abstract;
procedure SetWidth(const Value: Integer); virtual; abstract;
public
destructor Destroy; override;
published
property Left: Integer read GetLeft write SetLeft;
property Top: Integer read GetTop write SetTop;
property Right: Integer read GetRight write SetRight;
property Bottom: Integer read GetBottom write SetBottom;
property Width: Integer read GetWidth write SetWidth;
property Height: Integer read GetHeight write SetHeight;
property BoundsRect: TRect read GetBoundsRect write SetBoundsRect;
end;
implementation
uses
AuxDebugFunctionsUnit,
ControlLayoutItem;
{ TLayoutItem }
destructor TLayoutItem.Destroy;
const counter: Integer = 0;
begin
if Self is TControlLayoutItem then
DebugOutput(TControlLayoutItem(Self).Control.Name)
else begin
Inc(counter);
DebugOutput('Layout' + IntToStr(counter));
end;
inherited;
end;
function TLayoutItem.GetBottom: Integer;
begin
Result := Top + Height;
end;
function TLayoutItem.GetBoundsRect: TRect;
begin
Result := Rect(Left, Top, Right, Bottom);
end;
function TLayoutItem.GetRight: Integer;
begin
Result := Left + Width;
end;
procedure TLayoutItem.SetBottom(const Value: Integer);
begin
Top := Value - Height;
end;
procedure TLayoutItem.SetBoundsRect(const Value: TRect);
begin
Left := Value.Left;
Top := Value.Top;
Width := Value.Right - Value.Left;
Height := Value.Bottom - Value.Top;
end;
procedure TLayoutItem.SetRight(const Value: Integer);
begin
Left := Value - Width;
end;
end.
|
unit NtUtils.Processes.Create.Com;
{
This module provides support for asking various user-mode OS components via
COM to create processes on our behalf.
}
interface
uses
Ntapi.ShellApi, Ntapi.Versions, NtUtils, NtUtils.Processes.Create;
// Create a new process via WMI
[SupportedOption(spoCurrentDirectory)]
[SupportedOption(spoSuspended)]
[SupportedOption(spoWindowMode)]
[SupportedOption(spoDesktop)]
[SupportedOption(spoToken)]
function WmixCreateProcess(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
// Ask Explorer via IShellDispatch2 to create a process on our behalf
[SupportedOption(spoCurrentDirectory)]
[SupportedOption(spoRequireElevation)]
[SupportedOption(spoWindowMode)]
function ComxShellExecute(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
// Create a new process via WDC
[SupportedOption(spoCurrentDirectory)]
[SupportedOption(spoRequireElevation)]
function WdcxCreateProcess(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
// Create a new process via IDesktopAppXActivator
[MinOSVersion(OsWin10RS1)]
[SupportedOption(spoCurrentDirectory, OsWin11)]
[SupportedOption(spoRequireElevation)]
[SupportedOption(spoToken)]
[SupportedOption(spoParentProcessId, OsWin10RS2)]
[SupportedOption(spoWindowMode, OsWin11)]
[SupportedOption(spoAppUserModeId, omRequired)]
[SupportedOption(spoPackageBreakaway)]
function AppxCreateProcess(
const Options: TCreateProcessOptions;
out Info: TProcessInfo
): TNtxStatus;
implementation
uses
Ntapi.WinNt, Ntapi.ntstatus, Ntapi.ProcessThreadsApi, Ntapi.WinError,
Ntapi.ObjBase, Ntapi.ObjIdl, Ntapi.appmodel, Ntapi.WinUser, NtUtils.Ldr,
NtUtils.Com.Dispatch, NtUtils.Tokens.Impersonate, NtUtils.Threads,
NtUtils.Objects, NtUtils.Errors;
{$BOOLEVAL OFF}
{$IFOPT R+}{$DEFINE R+}{$ENDIF}
{$IFOPT Q+}{$DEFINE Q+}{$ENDIF}
{ ----------------------------------- WMI ----------------------------------- }
function WmixCreateProcess;
var
CoInitReverter, ImpersonationReverter: IAutoReleasable;
Win32_ProcessStartup, Win32_Process: IDispatch;
ProcessId: TProcessId32;
ResultCode: TVarData;
begin
Info := Default(TProcessInfo);
// TODO: add support for providing environment variables
// Accessing WMI requires COM
Result := ComxInitialize(CoInitReverter);
if not Result.IsSuccess then
Exit;
// We pass the token to WMI by impersonating it
if Assigned(Options.hxToken) then
begin
// Revert to the original one when we are done.
ImpersonationReverter := NtxBackupThreadToken(NtxCurrentThread);
Result := NtxImpersonateAnyToken(Options.hxToken);
if not Result.IsSuccess then
begin
// No need to revert impersonation if we did not change it.
ImpersonationReverter.AutoRelease := False;
Exit;
end;
end;
// Start preparing the startup info
Result := DispxBindToObject('winmgmts:Win32_ProcessStartup',
Win32_ProcessStartup);
if not Result.IsSuccess then
Exit;
// Fill-in CreateFlags
if poSuspended in Options.Flags then
begin
// For some reason, when specifing Win32_ProcessStartup.CreateFlags,
// processes would not start without CREATE_BREAKAWAY_FROM_JOB.
Result := DispxPropertySet(
Win32_ProcessStartup,
'CreateFlags',
VarFromCardinal(CREATE_BREAKAWAY_FROM_JOB or CREATE_SUSPENDED)
);
if not Result.IsSuccess then
Exit;
end;
// Fill-in the Window Mode
if poUseWindowMode in Options.Flags then
begin
Result := DispxPropertySet(
Win32_ProcessStartup,
'ShowWindow',
VarFromWord(Word(Options.WindowMode))
);
if not Result.IsSuccess then
Exit;
end;
// Fill-in the desktop
if Options.Desktop <> '' then
begin
Result := DispxPropertySet(
Win32_ProcessStartup,
'WinstationDesktop',
VarFromWideString(Options.Desktop)
);
if not Result.IsSuccess then
Exit;
end;
// Prepare the process object
Result := DispxBindToObject('winmgmts:Win32_Process', Win32_Process);
if not Result.IsSuccess then
Exit;
ProcessId := 0;
// Create the process
Result := DispxMethodCall(
Win32_Process,
'Create',
[
VarFromWideString(WideString(Options.CommandLine)),
VarFromWideString(WideString(Options.CurrentDirectory)),
VarFromIDispatch(Win32_ProcessStartup),
VarFromIntegerRef(ProcessId)
],
@ResultCode
);
if not Result.IsSuccess then
Exit;
Result.Location := 'Win32_Process.Create';
Result.Status := STATUS_UNSUCCESSFUL;
// This method returns custom status codes; convert them
if ResultCode.VType and varTypeMask = varInteger then
case TWmiWin32ProcessCreateStatus(ResultCode.VInteger) of
Process_STATUS_SUCCESS:
Result.Status := STATUS_SUCCESS;
Process_STATUS_NOT_SUPPORTED:
Result.Status := STATUS_NOT_SUPPORTED;
Process_STATUS_ACCESS_DENIED:
Result.Status := STATUS_ACCESS_DENIED;
Process_STATUS_INSUFFICIENT_PRIVILEGE:
Result.Status := STATUS_PRIVILEGE_NOT_HELD;
Process_STATUS_UNKNOWN_FAILURE:
Result.Status := STATUS_UNSUCCESSFUL;
Process_STATUS_PATH_NOT_FOUND:
Result.Status := STATUS_OBJECT_NAME_NOT_FOUND;
Process_STATUS_INVALID_PARAMETER:
Result.Status := STATUS_INVALID_PARAMETER;
end;
VariantClear(ResultCode);
// Return the process ID to the caller
if Result.IsSuccess then
begin
Include(Info.ValidFields, piProcessID);
Info.ClientId.UniqueProcess := ProcessId;
end;
end;
{ ----------------------------- IShellDispatch2 ----------------------------- }
// Rertieve the shell view for the desktop
function ComxFindDesktopFolderView(
out ShellView: IShellView
): TNtxStatus;
var
ShellWindows: IShellWindows;
wnd: Integer;
Dispatch: IDispatch;
ServiceProvider: IServiceProvider;
ShellBrowser: IShellBrowser;
begin
Result := ComxCreateInstance(
CLSID_ShellWindows,
IShellWindows,
ShellWindows,
CLSCTX_LOCAL_SERVER
);
if not Result.IsSuccess then
Exit;
Result.Location := 'IShellWindows::FindWindowSW';
Result.HResultAllowFalse := ShellWindows.FindWindowSW(
VarFromCardinal(CSIDL_DESKTOP),
VarEmpty,
SWC_DESKTOP,
wnd,
SWFO_NEEDDISPATCH,
Dispatch
);
// S_FALSE indicates that the the function did not find the window.
// We cannot proceed in this case, so fail the function with a meaningful code
if Result.HResult = S_FALSE then
Result.Status := STATUS_NOT_FOUND;
if not Result.IsSuccess then
Exit;
Result.Location := 'IDispatch::QueryInterface(IServiceProvider)';
Result.HResult := Dispatch.QueryInterface(IServiceProvider, ServiceProvider);
if not Result.IsSuccess then
Exit;
Result.Location := 'IServiceProvider::QueryService';
Result.HResult := ServiceProvider.QueryService(SID_STopLevelBrowser,
IShellBrowser, ShellBrowser);
if not Result.IsSuccess then
Exit;
Result.Location := 'IShellBrowser::QueryActiveShellView';
Result.HResult := ShellBrowser.QueryActiveShellView(ShellView);
end;
// Locate the desktop folder view object
function ComxGetDesktopAutomationObject(
out FolderView: IShellFolderViewDual
): TNtxStatus;
var
ShellView: IShellView;
Dispatch: IDispatch;
begin
Result := ComxFindDesktopFolderView(ShellView);
if not Result.IsSuccess then
Exit;
Result.Location := 'IShellView::GetItemObject';
Result.HResult := ShellView.GetItemObject(SVGIO_BACKGROUND, IDispatch,
Dispatch);
if not Result.IsSuccess then
Exit;
Result.Location := 'IDispatch::QueryInterface(IShellFolderViewDual)';
Result.HResult := Dispatch.QueryInterface(IShellFolderViewDual, FolderView);
end;
// Access the shell dispatch object
function ComxGetShellDispatch(
out ShellDispatch: IShellDispatch2
): TNtxStatus;
var
FolderView: IShellFolderViewDual;
Dispatch: IDispatch;
begin
Result := ComxGetDesktopAutomationObject(FolderView);
if not Result.IsSuccess then
Exit;
Result.Location := 'IShellFolderViewDual::get_Application';
Result.HResult := FolderView.get_Application(Dispatch);
if not Result.IsSuccess then
Exit;
Result.Location := 'IDispatch::QueryInterface(IShellDispatch2)';
Result.HResult := Dispatch.QueryInterface(IShellDispatch2, ShellDispatch);
end;
function ComxShellExecute;
var
UndoCoInit: IAutoReleasable;
ShellDispatch: IShellDispatch2;
vOperation, vShow: TVarData;
begin
Info := Default(TProcessInfo);
Result := ComxInitialize(UndoCoInit);
if not Result.IsSuccess then
Exit;
// Retrieve the Shell Dispatch object
Result := ComxGetShellDispatch(ShellDispatch);
if not Result.IsSuccess then
Exit;
// Prepare the verb
if poRequireElevation in Options.Flags then
vOperation := VarFromWideString('runas')
else
vOperation := VarEmpty;
// Prepare the window mode
if poUseWindowMode in Options.Flags then
vShow := VarFromWord(Word(Options.WindowMode))
else
vShow := VarEmpty;
Result.Location := 'IShellDispatch2::ShellExecute';
Result.HResult := ShellDispatch.ShellExecute(
WideString(Options.ApplicationWin32),
VarFromWideString(WideString(Options.Parameters)),
VarFromWideString(WideString(Options.CurrentDirectory)),
vOperation,
vShow
);
// This method does not provide any information about the new process
end;
{ ----------------------------------- WDC ----------------------------------- }
function WdcxCreateProcess;
var
SeclFlags: TSeclFlags;
UndoCoInit: IAutoReleasable;
begin
Info := Default(TProcessInfo);
Result := LdrxCheckModuleDelayedImport(wdc, 'WdcRunTaskAsInteractiveUser');
if not Result.IsSuccess then
Exit;
Result := ComxInitialize(UndoCoInit);
if not Result.IsSuccess then
Exit;
if poRequireElevation in Options.Flags then
SeclFlags := SECL_RUNAS
else
SeclFlags := 0;
Result.Location := 'WdcRunTaskAsInteractiveUser';
Result.HResult := WdcRunTaskAsInteractiveUser(
PWideChar(Options.CommandLine),
RefStrOrNil(Options.CurrentDirectory),
SeclFlags
);
// This method does not provide any information about the new process
end;
{ ---------------------------------- AppX ----------------------------------- }
function AppxCreateProcess;
var
ComUninitializer: IAutoReleasable;
Activator: IUnknown;
ActivatorV1: IDesktopAppXActivatorV1;
ActivatorV2: IDesktopAppXActivatorV2;
ActivatorV3: IDesktopAppXActivatorV3;
Flags: TDesktopAppxActivateOptions;
WindowMode: TShowMode32;
ImpersonationReverter: IAutoReleasable;
hProcess: THandle32;
begin
Info := Default(TProcessInfo);
Result := ComxInitialize(ComUninitializer);
if not Result.IsSuccess then
Exit;
// Create the activator without asking for any specicific interfaces
Result.Location := 'CoCreateInstance(CLSID_DesktopAppXActivator)';
Result.HResult := CoCreateInstance(CLSID_DesktopAppXActivator, nil,
CLSCTX_INPROC_SERVER, IUnknown, Activator);
if not Result.IsSuccess then
Exit;
Flags := DAXAO_NONPACKAGED_EXE or DAXAO_NO_ERROR_UI;
if poRequireElevation in Options.Flags then
Flags := Flags or DAXAO_ELEVATE;
if BitTest(Options.PackageBreaway and
PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_DISABLE_PROCESS_TREE) then
Flags := Flags or DAXAO_NONPACKAGED_EXE_PROCESS_TREE;
// Pass the token via impersonation
if Assigned(Options.hxToken) then
begin
// Revert to the original one when we are done.
ImpersonationReverter := NtxBackupThreadToken(NtxCurrentThread);
Result := NtxImpersonateAnyToken(Options.hxToken);
if not Result.IsSuccess then
begin
// No need to revert impersonation if we did not change it.
ImpersonationReverter.AutoRelease := False;
Exit;
end;
end;
if Activator.QueryInterface(IDesktopAppXActivatorV3,
ActivatorV3).IsSuccess then
begin
if poUseWindowMode in Options.Flags then
WindowMode := Options.WindowMode
else
WindowMode := TShowMode32.SW_SHOW_NORMAL;
// Use Win 11+ version
Result.Location := 'IDesktopAppXActivator::ActivateWithOptionsArgsWorkingDirectoryShowWindow';
Result.HResult := ActivatorV3.ActivateWithOptionsArgsWorkingDirectoryShowWindow(
PWideChar(Options.AppUserModeId),
PWideChar(Options.ApplicationWin32),
PWideChar(Options.Parameters),
Flags,
Options.ParentProcessId,
nil,
NtUtils.RefStrOrNil(Options.CurrentDirectory),
WindowMode,
hProcess
);
end
else if Activator.QueryInterface(IDesktopAppXActivatorV2,
ActivatorV2).IsSuccess then
begin
// Use RS2+ version
Result.Location := 'IDesktopAppXActivator::ActivateWithOptions';
Result.HResult := ActivatorV2.ActivateWithOptions(
PWideChar(Options.AppUserModeId),
PWideChar(Options.ApplicationWin32),
PWideChar(Options.Parameters),
Flags,
Options.ParentProcessId,
hProcess
);
end
else if Activator.QueryInterface(IDesktopAppXActivatorV1,
ActivatorV1).IsSuccess then
begin
// Use RS1 version
Result.Location := 'IDesktopAppXActivator::ActivateWithOptions';
Result.HResult := ActivatorV1.ActivateWithOptions(
PWideChar(Options.AppUserModeId),
PWideChar(Options.ApplicationWin32),
PWideChar(Options.Parameters),
Flags,
hProcess
);
end
else
begin
// Unknown version
Result.Location := 'IDesktopAppXActivator';
Result.Status := STATUS_UNKNOWN_REVISION;
Exit;
end;
if Result.IsSuccess then
begin
// We get a process handle in response
Include(Info.ValidFields, piProcessHandle);
Info.hxProcess := Auto.CaptureHandle(hProcess);
end;
end;
end.
|
unit FluentSQLUnion;
interface
type
IUnion = interface
function UnionAll(SQL: String): IUnion; overload;
function UnionAll(Condtion: Boolean; SQL: String): IUnion; overload;
function ToSQL: String;
end;
TUnion = class(TInterfacedObject, IUnion)
private
FSQL: String;
public
function UnionAll(SQL: String): IUnion; overload;
function UnionAll(Condtion: Boolean; SQL: String): IUnion; overload;
function ToSQL: String;
end;
implementation
uses SysUtils;
{ TUnion }
function TUnion.UnionAll(SQL: String): IUnion;
begin
Result := Self;
if SQL <> EmptyStr then
begin
if FSQL <> EmptyStr then
FSQL := FSQL + ' UNION ALL ';
FSQL := FSQL + SQL;
end;
end;
function TUnion.UnionAll(Condtion: Boolean; SQL: String): IUnion;
begin
Result := Self;
if Condtion then
UnionAll(SQL)
end;
function TUnion.ToSQL: String;
begin
Result := FSQL;
end;
end.
|
unit ArithmeticRepositoryCriterionOperationsUnit;
interface
uses
AbstractRepositoryCriteriaUnit;
const
EQUALITY_OPERATION_VALUE = '=';
LESS_OPERATION_VALUE = '<';
LESS_OR_EQUAL_OPERATION_VALUE = '<=';
GREATER_OPERATION_VALUE = '>';
GREATER_OR_EQUAL_OPERATION_VALUE = '>=';
type
TEqualityRepositoryCriterionOperation = class(TAbstractRepositoryCriterionOperation)
protected
function GetValue: String; override;
public
constructor Create;
end;
TEqualityRepositoryCriterionOperationClass = class of TEqualityRepositoryCriterionOperation;
TLessRepositoryCriterionOperation = class(TAbstractRepositoryCriterionOperation)
protected
function GetValue: String; override;
public
constructor Create;
end;
TLessRepositoryCriterionOperationClass = class of TLessRepositoryCriterionOperation;
TLessOrEqualRepositoryCriterionOperation = class(TAbstractRepositoryCriterionOperation)
protected
function GetValue: String; override;
public
constructor Create;
end;
TLessOrEqualRepositoryCriterionOperationClass = class of TLessOrEqualRepositoryCriterionOperation;
TGreaterRepositoryCriterionOperation = class(TAbstractRepositoryCriterionOperation)
protected
function GetValue: String; override;
public
constructor Create;
end;
TGreaterRepositoryCriterionOperationClass = class of TGreaterRepositoryCriterionOperation;
TGreaterOrEqualRepositoryCriterionOperation = class(TAbstractRepositoryCriterionOperation)
protected
function GetValue: String; override;
public
constructor Create;
end;
TGreaterOrEqualRepositoryCriterionOperationClass = class of TGreaterOrEqualRepositoryCriterionOperation;
implementation
{ TEqualRepositoryCriteriaOperation }
constructor TEqualityRepositoryCriterionOperation.Create;
begin
inherited;
end;
function TEqualityRepositoryCriterionOperation.GetValue: String;
begin
Result := EQUALITY_OPERATION_VALUE;
end;
{ TLessRepositoryCriterionOperation }
constructor TLessRepositoryCriterionOperation.Create;
begin
inherited;
end;
function TLessRepositoryCriterionOperation.GetValue: String;
begin
Result := LESS_OPERATION_VALUE;
end;
{ TLessOrEqualRepositoryCriterionOperation }
constructor TLessOrEqualRepositoryCriterionOperation.Create;
begin
inherited;
end;
function TLessOrEqualRepositoryCriterionOperation.GetValue: String;
begin
Result := LESS_OR_EQUAL_OPERATION_VALUE;
end;
{ TGreaterRepositoryCriterionOperation }
constructor TGreaterRepositoryCriterionOperation.Create;
begin
inherited;
end;
function TGreaterRepositoryCriterionOperation.GetValue: String;
begin
Result := GREATER_OPERATION_VALUE;
end;
{ TGreaterOrEqualRepositoryCriterionOperation }
constructor TGreaterOrEqualRepositoryCriterionOperation.Create;
begin
inherited;
end;
function TGreaterOrEqualRepositoryCriterionOperation.GetValue: String;
begin
Result := GREATER_OR_EQUAL_OPERATION_VALUE;
end;
end.
|
unit UGeneralMulti2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
UACAGMulti, StdCtrls, JLLabel, ExtCtrls, Grids, Menus,
UzLogConst, UzLogGlobal, UzLogQSO, UWPXMulti, UMultipliers, UserDefinedContest;
const
BANDLABELMAX = 30;
type
TGeneralMulti2 = class(TACAGMulti)
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
protected
BandLabelArray : array[0..BANDLABELMAX] of TRotateLabel;
procedure UpdateLabelPos(); override;
private
{ Private declarations }
FConfig: TUserDefinedContest;
function GetPX(aQSO : TQSO) : string;
public
{ Public declarations }
function IsLocal(aQSO : TQSO) : Boolean;
procedure LoadDAT(Filename : string);
function ExtractMulti(aQSO : TQSO) : string; override;
procedure AddNoUpdate(var aQSO : TQSO); override;
function ValidMulti(aQSO : TQSO) : Boolean; override;
procedure CheckMulti(aQSO : TQSO); override;
procedure Reset; override;
procedure UpdateData; override;
property Config: TUserDefinedContest read FConfig write FConfig;
end;
implementation
uses Main, UGeneralScore, UzLogExtension;
{$R *.DFM}
function TGeneralMulti2.GetPX(aQSO : TQSO) : string;
var
s: string;
i, slash : Integer;
begin
Result := '';
s := aQSO.Callsign;
if s = '' then
exit;
slash := pos('/',s);
if FConfig.PXMulti = PX_WPX then begin
Result := UWPXMulti.GetWPXPrefix(aQSO);
exit;
end
else begin
if slash > 4 then begin
s := copy(s, 1, slash-1);
end;
if slash in [1..4] then begin
Delete(s, 1, slash);
end;
i := length(s) + 1;
repeat
dec(i)
until (i = 0) or CharInSet(s[i], ['0'..'9']);
Result := copy(s,1,i);
exit;
end;
end;
procedure TGeneralMulti2.UpdateData;
var
i, j : Integer;
CTY: TCity;
CNT: TCountry;
B: TBand;
B2: TBand;
R: Integer;
begin
i := 0;
for B := b19 to Hiband do begin
if (MainForm.BandMenu.Items[Ord(B)].Visible = True) and
(dmZlogGlobal.Settings._activebands[B] = True) then begin
BandLabelArray[i].Caption := MHzString[B];
j := BandLabelArray[i].Height;
Application.ProcessMessages();
BandLabelArray[i].Top := 35 - j;
Inc(i);
end;
end;
for j := i to BANDLABELMAX do begin
BandLabelArray[j].Caption := '';
end;
if Grid.RowCount < CityList.List.Count then begin
Grid.RowCount := CityList.List.Count;
end;
if FConfig.UseCtyDat then begin
if dmZLogGlobal.CountryList.Count > 0 then begin
if FConfig.NoCountryMulti <> '*' then begin
Grid.RowCount := CityList.List.Count + dmZLogGlobal.CountryList.Count;
end;
end;
end;
// B=現在バンド
B := Main.CurrentQSO.Band;
if B = bUnknown then begin
Exit;
end;
// CityListをGridにセット
for i := 0 to CityList.List.Count - 1 do begin
CTY := TCity(CityList.List[i]);
if CTY.Worked[B] then begin
Grid.Cells[0, i] := '~' + CTY.SummaryGeneral;
end
else begin
Grid.Cells[0, i] := CTY.SummaryGeneral;
if FConfig.CountMultiOnce then begin
for B2 := b19 to HiBand do begin
if CTY.Worked[B2] then begin
Grid.Cells[0, i] := '~' + CTY.SummaryGeneral;
Break;
end;
end;
end;
end;
end;
// CountryListをGridにセット
if FConfig.UseCtyDat and (FConfig.NoCountryMulti <> '*') then begin
for i := 0 to dmZLogGlobal.CountryList.Count - 1 do begin
CNT := TCountry(dmZLogGlobal.CountryList.List[i]);
R := CityList.List.Count + i;
if CNT.Worked[B] then begin
Grid.Cells[0, R] := '~' + CNT.SummaryGeneral;
end
else begin
Grid.Cells[0, R] := CNT.SummaryGeneral;
if FConfig.CountMultiOnce then begin
for B2 := b19 to HiBand do begin
if CNT.Worked[B2] then begin
Grid.Cells[0, R] := '*' + CNT.SummaryGeneral;
Break;
end;
end;
end;
end;
end;
end;
if checkJumpLatestMulti.Checked = True then begin
Grid.TopRow := LatestMultiAddition;
end;
end;
procedure TGeneralMulti2.Reset;
begin
if dmZLogGlobal.CountryList <> nil then
dmZLogGlobal.CountryList.Reset;
if CityList <> nil then
CityList.Reset;
end;
function TGeneralMulti2.ValidMulti(aQSO : TQSO) : Boolean;
var
str : string;
i : Integer;
C : TCity;
boo : Boolean;
begin
if FConfig.UndefMulti or FConfig.AllowUnlistedMulti or (FConfig.PXMulti <> 0) or FConfig.UseCtyDat or FConfig.NoMulti then begin
Result := True;
exit;
end;
if zyloRequestValid(aQSO, boo) = True then begin
Result := boo;
Exit;
end;
str := ExtractMulti(aQSO);
boo := false;
for i := 0 to CityList.List.Count-1 do begin
C := TCity(CityList.List[i]);
if pos(','+str+',', ','+C.CityNumber+',') > 0 then begin
boo := true;
break;
end;
end;
Result := boo;
end;
function TGeneralMulti2.ExtractMulti(aQSO : TQSO) : string;
var
str : string;
i : Integer;
begin
str := '';
if zyloRequestMulti(aQSO, str) = True then begin
Result := str;
Exit;
end;
str := aQSO.NrRcvd;
if FConfig.PXMulti <> 0 then begin
Result := GetPX(aQSO);
exit;
end;
if FConfig.CutTailingAlphabets then begin // deletes any tailing non-digits
for i := length(str) downto 1 do
if CharInSet(str[i], ['0'..'9']) then
break;
if (i = 1) and CharInSet(str[1], ['0'..'9']) then
str := ''
else
str := copy(str, 1, i);
end;
if IsLocal(aQSO) then begin
if FConfig.LCut <> 0 then begin
if FConfig.LCut > 0 then
Delete(str, length(str)-FConfig.LCut+1, FConfig.LCut)
else
Delete(str, 1, FConfig.LCut * -1);
end
else begin {lcut = 0}
if FConfig.LTail <> 0 then
if FConfig.LTail > 0 then
str := copy(str, length(str)-FConfig.LTail+1, FConfig.LTail)
else
str := copy(str, 1, -1*FConfig.LTail);
end;
end
else begin {not local}
if FConfig.Cut <> 0 then begin
if FConfig.Cut > 0 then
Delete(str, length(str)-FConfig.Cut+1, FConfig.Cut)
else
Delete(str, 1, FConfig.Cut * -1);
end
else begin {cut = 0}
if FConfig.Tail <> 0 then
if FConfig.Tail > 0 then
str := copy(str, length(str)-FConfig.Tail+1, FConfig.Tail)
else
str := copy(str, 1, -1*FConfig.Tail);
end;
end;
Result := str;
end;
procedure TGeneralMulti2.AddNoUpdate(var aQSO : TQSO);
var
str, str2 : string;
B : TBand;
i: Integer;
C : TCity;
Cty : TCountry;
boo : Boolean;
label aaa;
begin
aQSO.NewMulti1 := False;
if FConfig.NoMulti then exit;
aQSO.Power2 := 2; // not local CTY
if FConfig.UseCtyDat then begin
Cty := dmZLogGlobal.GetPrefix(aQSO.Callsign).Country;
aQSO.Power2 := Cty.Index;
if FConfig.NoCountryMulti = '*' then
goto aaa;
if pos(',' + Cty.Country + ',', ',' + FConfig.NoCountryMulti + ',') > 0 then
goto aaa;
aQSO.Multi1 := Cty.Country;
if aQSO.Dupe then
exit;
LatestMultiAddition := CityList.List.Count + Cty.Index;
if FConfig.CountMultiOnce then begin // multi once regardless of band
boo := false;
for B := b19 to HiBand do begin
if Cty.Worked[B] then begin
boo := true;
break;
end;
end;
if boo = false then begin
aQSO.NewMulti1 := True;
Cty.Worked[aQSO.Band] := True;
end;
end
else begin // new multi each band
if Cty.Worked[aQSO.Band] = False then begin
aQSO.NewMulti1 := True;
Cty.Worked[aQSO.Band] := True;
end;
end;
exit;
end;
aaa:
str := ExtractMulti(aQSO);
aQSO.Multi1 := str;
if aQSO.Dupe then
exit;
for i := 0 to CityList.List.Count-1 do begin
C := TCity(CityList.List[i]);
str2 := ','+C.CityNumber+','; // for alternative exchange
if pos (','+str+',', str2) > 0 then begin
if C.Worked[aQSO.band] = False then begin
C.Worked[aQSO.band] := True;
aQSO.NewMulti1 := True;
end;
LatestMultiAddition := C.Index;
exit;
end;
end;
// no match with CityList
if FConfig.AllowUnlistedMulti then begin
exit;
end;
if FConfig.UndefMulti or (FConfig.PXMulti <> 0) then begin
C := TCity.Create;
C.CityNumber := str;
C.Worked[aQSO.Band] := True;
CityList.AddAndSort(C);
aQSO.NewMulti1 := True;
LatestMultiAddition := C.Index;
end;
end;
function TGeneralMulti2.IsLocal(aQSO : TQSO) : Boolean;
var
i : Integer;
begin
Result := False;
if FConfig.UseCtyDat then begin
if FConfig.LocalCountry <> '' then begin
i := aQSO.Power2;
if (i > -1) and (i < dmZLogGlobal.CountryList.Count) then
if pos(',' + TCountry(dmZLogGlobal.CountryList.List[i]).Country + ',', ',' + FConfig.LocalCountry + ',') > 0 then begin
Result := True;
exit;
end;
end;
if FConfig.LocalContinental <> '' then begin
i := aQSO.Power2;
if (i > -1) and (i < dmZLogGlobal.CountryList.Count) then
if pos(',' + TCountry(dmZLogGlobal.CountryList.List[i]).Continent + ',', ',' + FConfig.LocalContinental + ',') > 0 then begin
Result := True;
exit;
end;
end;
end;
for i := 0 to MAXLOCAL do begin
if FConfig.LocalString[i] = '' then begin
exit;
end
else begin
if (Pos(FConfig.LocalString[i], aQSO.NrRcvd) = 1) and
(Length(aQSO.NrRcvd) >= FConfig.MinLocalLen) then begin
Result := True;
exit;
end;
end;
end;
end;
procedure TGeneralMulti2.LoadDAT(Filename : string);
begin
if not zyloRequestTable(Filename, CityList) then
CityList.LoadFromFile(FileName);
Reset;
end;
procedure TGeneralMulti2.FormCreate(Sender: TObject);
var
i : Integer;
begin
//inherited;
LatestMultiAddition := 0;
Label1R9.Visible := True;
CityList := TCityList.Create;
Label1R9.Visible := False;
Label3R5.Visible := False;
Label7.Visible := False;
Label14.Visible := False;
Label21.Visible := False;
Label28.Visible := False;
Label50.Visible := False;
Label144.Visible := False;
Label430.Visible := False;
Label1200.Visible := False;
Label2400.Visible := False;
Label5600.Visible := False;
Label10G.Visible := False;
for i := 0 to BANDLABELMAX do begin
BandLabelArray[i] := TRotateLabel.Create(Self);
BandLabelArray[i].Parent := Panel;
BandLabelArray[i].Escapement := 90;
BandLabelArray[i].Alignment := taleftjustify;
BandLabelArray[i].Font := Label1R9.Font;
BandLabelArray[i].TextStyle := tsNone;
BandLabelArray[i].Left := Label1R9.Left + Trunc(12.15*i);
BandLabelArray[i].Top := 10;
//BandLabelArray[i].Height := 1;
BandLabelArray[i].AutoSize := True;
BandLabelArray[i].Caption := '';
BandLabelArray[i].Visible := False;
end;
end;
procedure TGeneralMulti2.CheckMulti(aQSO : TQSO);
var
str : string;
strSjis: AnsiString;
i : Integer;
C : TCity;
begin
if ValidMulti(aQSO) then
str := ExtractMulti(aQSO)
else
str := aQSO.NrRcvd;
if str = '' then
exit;
for i := 0 to CityList.List.Count-1 do begin
C := TCity(CityList.List[i]);
if pos(','+str+',', ','+C.CityNumber+',') > 0 then begin
Grid.TopRow := i;
str := C.Summary2;
strSjis := AnsiString(str);
if C.Worked[aQSO.Band] then
Insert('Worked on this band. ',strSjis, 27)
else
Insert('Needed on this band. ',strSjis, 27);
str := String(strSjis);
MainForm.WriteStatusLine(str, false);
exit;
end;
end;
if FConfig.UndefMulti then
MainForm.WriteStatusLine(str+ ' : '+'Not worked on any band', false)
else
MainForm.WriteStatusLine(TMainForm_Invalid_number, false);
end;
procedure TGeneralMulti2.FormShow(Sender: TObject);
begin
inherited;
// LatestMultiAddition := 0;
// UpdateData;
end;
procedure TGeneralMulti2.GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
inherited;
Draw_GridCell(Grid, ACol, ARow, Rect);
end;
procedure TGeneralMulti2.UpdateLabelPos();
var
w, l: Integer;
B: TBand;
i: Integer;
j: Integer;
begin
w := Grid.Canvas.TextWidth('X');
l := (w * 33) - 2;
i := 0;
j := 0;
for B := b19 to Hiband do begin
if (MainForm.BandMenu.Items[Ord(B)].Visible = True) and
(dmZlogGlobal.Settings._activebands[B] = True) then begin
if i = 0 then begin
BandLabelArray[i].Left := l;
end
else begin
BandLabelArray[i].Left := BandLabelArray[j].Left + (w * 2);
end;
BandLabelArray[i].Visible := True;
j := i;
Inc(i);
end;
end;
end;
end.
|
unit UFormFtpCopy;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, zip, types, IdComponent,
Vcl.ExtCtrls, UFtpUtils, Vcl.ComCtrls, RzPrgres, UFileSearch;
type
TfrmFtpCopy = class(TForm)
lbZiping: TLabel;
btnCancel: TButton;
tmrZipFile: TTimer;
liFileName: TLabel;
lbSpeed: TLabel;
pbMain: TProgressBar;
tmrSpeed: TTimer;
lbRemainTime: TLabel;
Panel1: TPanel;
lbSize: TLabel;
Panel2: TPanel;
lbPrecentage: TLabel;
procedure tmrZipFileTimer(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure tmrSpeedTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FtpHost, RemotePath, LocalPath : string;
LastSize, NowSize, TotalSize : Int64;
private
ShowCopy : string;
IsStop : Boolean;
procedure BeforeCopy;
procedure AfterCopy;
public
function ReadIsStop : Boolean;
public
procedure SetCopyInfo( _FtpHost, _RemotePath, _LocalPath : string );
procedure SetDownloadSize( DownloadSize : Int64 );
function DownloadFile: Boolean;
function UploadFile: Boolean;
function DownloadFolder : Boolean;
function UploadFolder : Boolean;
private
procedure FtpWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
procedure FtpWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
end;
// 下载目录处理
TFtpDownloadFolderHandle = class
public
FtpHost, RemotePath, LocalPath : string;
FtpFileList : TFtpFileList;
public
constructor Create( _FtpHost, _RemotePath, _LocalPath : string );
function Update: Boolean;
destructor Destroy; override;
private
function ReadIsNext : Boolean;
procedure DownloadFile( FilePath : string; FileSize : Int64 );
procedure DownloadFolder( ChildPath : string );
end;
// 上传目录处理
TFtpUploadFolderHandle = class
public
FtpHost, LocalPath, RemotePath : string;
FileList : TFileList;
public
constructor Create( _FtpHost, _LocalPath, _RemotePath : string );
function Update: Boolean;
destructor Destroy; override;
private
function ReadIsNext : Boolean;
procedure UploadFile( FilePath : string );
procedure UploadFolder( ChildPath : string );
end;
var
frmFtpCopy: TfrmFtpCopy;
implementation
uses IOUtils, UMyUtils;
{$R *.dfm}
procedure TfrmFtpCopy.AfterCopy;
begin
tmrZipFile.Enabled := False;
tmrSpeed.Enabled := False;
end;
procedure TfrmFtpCopy.BeforeCopy;
begin
IsStop := False;
tmrZipFile.Enabled := True;
tmrSpeed.Enabled := True;
NowSize := 0;
LastSize := 0;
if TotalSize <= 0 then
TotalSize := 1;
end;
procedure TfrmFtpCopy.btnCancelClick(Sender: TObject);
begin
IsStop := True;
Close;
MyFtpFileHandler.StopTransfer( FtpHost );
end;
function TfrmFtpCopy.DownloadFile: Boolean;
begin
BeforeCopy;
frmFtpCopy.ShowCopy := RemotePath;
MyFtpFileHandler.BingWordBegin( FtpHost, FtpWorkBegin );
MyFtpFileHandler.BingWord( FtpHost, FtpWork );
Result := MyFtpFileHandler.Download( FtpHost, RemotePath, LocalPath );
// 手动停止下载,删除中断的文件
if IsStop then
begin
MyShellFile.DeleteFile( LocalPath );
Result := False;
end;
AfterCopy;
end;
function TfrmFtpCopy.DownloadFolder: Boolean;
var
FtpDownloadFolderHandle : TFtpDownloadFolderHandle;
begin
BeforeCopy;
frmFtpCopy.ShowCopy := RemotePath;
MyFtpFileHandler.BingWordBegin( FtpHost, FtpWorkBegin );
MyFtpFileHandler.BingWord( FtpHost, FtpWork );
FtpDownloadFolderHandle := TFtpDownloadFolderHandle.Create( FtpHost, RemotePath, LocalPath );
Result := FtpDownloadFolderHandle.Update;
FtpDownloadFolderHandle.Free;
AfterCopy;
end;
procedure TfrmFtpCopy.FormShow(Sender: TObject);
begin
liFileName.Caption := MyFilePath.getFtpName( RemotePath );
pbMain.Position := 0;
end;
procedure TfrmFtpCopy.FtpWork(ASender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
begin
NowSize := AWorkCount;
end;
procedure TfrmFtpCopy.FtpWorkBegin(ASender: TObject; AWorkMode: TWorkMode;
AWorkCountMax: Int64);
begin
pbMain.Position := 0;
if AWorkMode = wmWrite then
TotalSize := AWorkCountMax;
LastSize := 0;
end;
function TfrmFtpCopy.ReadIsStop: Boolean;
begin
Result := IsStop;
end;
procedure TfrmFtpCopy.SetCopyInfo(_FtpHost, _RemotePath, _LocalPath : string);
begin
FtpHost := _FtpHost;
RemotePath := _RemotePath;
LocalPath := _LocalPath;
end;
procedure TfrmFtpCopy.SetDownloadSize(DownloadSize: Int64);
begin
TotalSize := DownloadSize;
end;
procedure TfrmFtpCopy.tmrSpeedTimer(Sender: TObject);
var
Speed : Integer;
RemainSize, RemainSecond : Int64;
begin
Speed := NowSize - LastSize;
lbSpeed.Caption := MySpeed.getSpeedStr( Speed );
LastSize := NowSize;
lbPrecentage.Caption := MyPercentage.getStr( NowSize, TotalSize );
lbSize.Caption := MySizeUtil.getStr( NowSize ) + '/' + MySizeUtil.getStr( TotalSize );
if Speed <= 0 then
lbRemainTime.Caption := ''
else
begin
RemainSize := TotalSize - NowSize;
RemainSecond := RemainSize div Speed;
lbRemainTime.Caption := '剩余' + MyRemainTime.getStr( RemainSecond );
end;
end;
procedure TfrmFtpCopy.tmrZipFileTimer(Sender: TObject);
begin
liFileName.Caption := MyFilePath.getFtpName( ShowCopy );
pbMain.Position := MyPercentage.getInt( NowSize, TotalSize );
end;
function TfrmFtpCopy.UploadFile: Boolean;
begin
BeforeCopy;
frmFtpCopy.ShowCopy := LocalPath;
MyFtpFileHandler.BingWordBegin( FtpHost, FtpWorkBegin );
MyFtpFileHandler.BingWord( FtpHost, FtpWork );
Result := MyFtpFileHandler.Upload( FtpHost, LocalPath, RemotePath );
// 手动停止下载,删除中断的文件
if IsStop then
begin
MyFtpFileHandler.DeleteFile( FtpHost, RemotePath );
Result := False;
end;
AfterCopy;
end;
function TfrmFtpCopy.UploadFolder: Boolean;
var
FtpUploadFolderHandle : TFtpUploadFolderHandle;
begin
BeforeCopy;
frmFtpCopy.ShowCopy := LocalPath;
MyFtpFileHandler.BingWordBegin( FtpHost, FtpWorkBegin );
MyFtpFileHandler.BingWord( FtpHost, FtpWork );
FtpUploadFolderHandle := TFtpUploadFolderHandle.Create( FtpHost, LocalPath, RemotePath );
Result := FtpUploadFolderHandle.Update;
FtpUploadFolderHandle.Free;
AfterCopy;
end;
{ TFtpDownloadFolderHandle }
constructor TFtpDownloadFolderHandle.Create(_FtpHost, _RemotePath,
_LocalPath: string);
begin
FtpHost := _FtpHost;
RemotePath := _RemotePath;
LocalPath := _LocalPath;
end;
procedure TFtpDownloadFolderHandle.DownloadFile(FilePath: string; FileSize : Int64);
var
LocalFilePath : string;
begin
frmFtpCopy.ShowCopy := FilePath;
frmFtpCopy.SetDownloadSize( FileSize );
LocalFilePath := MyFilePath.getPath( LocalPath ) + MyFilePath.getFtpName( FilePath );
MyFtpFileHandler.Download( FtpHost, FilePath, LocalFilePath );
// 已取消下载
if not ReadIsNext then
MyShellFile.DeleteFile( LocalFilePath );
end;
procedure TFtpDownloadFolderHandle.DownloadFolder(ChildPath: string);
var
LocalChildPath : string;
FtpDownloadFolderHandle : TFtpDownloadFolderHandle;
begin
frmFtpCopy.ShowCopy := ChildPath;
LocalChildPath := MyFilePath.getPath( LocalPath ) + MyFilePath.getFtpName( ChildPath );
FtpDownloadFolderHandle := TFtpDownloadFolderHandle.Create( FtpHost, ChildPath, LocalChildPath );
FtpDownloadFolderHandle.Update;
FtpDownloadFolderHandle.Free;
end;
destructor TFtpDownloadFolderHandle.Destroy;
begin
FtpFileList.Free;
inherited;
end;
function TFtpDownloadFolderHandle.ReadIsNext: Boolean;
begin
Result := not frmFtpCopy.IsStop;
end;
function TFtpDownloadFolderHandle.Update: Boolean;
var
i: Integer;
ParentPath, ChildPath : string;
begin
Result := False;
FtpFileList := MyFtpFileHandler.ReadFileList( FtpHost, RemotePath );
ParentPath := MyFilePath.getFtpPath( RemotePath );
for i := 0 to FtpFileList.Count - 1 do
begin
if not ReadIsNext then // 已停止
Break;
ChildPath := ParentPath + FtpFileList[i].FileName;
if FtpFileList[i].IsFile then
DownloadFile( ChildPath, FtpFileList[i].FileSize )
else
DownloadFolder( ChildPath );
end;
Result := ReadIsNext;
end;
{ TFtpUploadFolderHandle }
constructor TFtpUploadFolderHandle.Create(_FtpHost, _LocalPath,
_RemotePath: string);
begin
FtpHost := _FtpHost;
LocalPath := _LocalPath;
RemotePath := _RemotePath;
end;
destructor TFtpUploadFolderHandle.Destroy;
begin
FileList.Free;
inherited;
end;
function TFtpUploadFolderHandle.ReadIsNext: Boolean;
begin
Result := not frmFtpCopy.IsStop;
end;
function TFtpUploadFolderHandle.Update: Boolean;
var
ParentPath, ChildPath : string;
i: Integer;
begin
// 先创建目录
MyFtpFileHandler.NewFolder( FtpHost, RemotePath );
ParentPath := MyFilePath.getPath( LocalPath );
FileList := FolderSearchUtil.ReadList( LocalPath );
for i := 0 to FileList.Count - 1 do
begin
if not ReadIsNext then
Break;
ChildPath := ParentPath + FileList[i].FileName;
if FileList[i].IsFile then
UploadFile( ChildPath )
else
UploadFolder( ChildPath );
end;
Result := ReadIsNext;
end;
procedure TFtpUploadFolderHandle.UploadFile(FilePath: string);
var
RemoteFilePath : string;
begin
frmFtpCopy.ShowCopy := FilePath;
RemoteFilePath := MyFilePath.getFtpPath( RemotePath ) + MyFilePath.getName( FilePath );
MyFtpFileHandler.Upload( FtpHost, FilePath, RemoteFilePath );
// 已取消下载
if not ReadIsNext then
MyFtpFileHandler.DeleteFile( FtpHost, RemoteFilePath );
end;
procedure TFtpUploadFolderHandle.UploadFolder(ChildPath: string);
var
RemoteChildPath : string;
FtpUploadFolderHandle : TFtpUploadFolderHandle;
begin
frmFtpCopy.ShowCopy := ChildPath;
RemoteChildPath := MyFilePath.getFtpPath( RemotePath ) + MyFilePath.getName( ChildPath );
FtpUploadFolderHandle := TFtpUploadFolderHandle.Create( FtpHost, ChildPath, RemoteChildPath );
FtpUploadFolderHandle.Update;
FtpUploadFolderHandle.Free;
end;
end.
|
unit uPDFPrint;
/// <author>Mauricio Sareto</author>
/// <e-mail>mauricio_sareto@hotmail.com</e-mail>
/// Esta unit tem por finalidade gerar relatorios para FMX Mobile, ela por ser
/// editada e alterada, nao compartilhe esse arquivo sem a autorizaçao do autor.
/// O autor se reserva ao direito de receber todos os creditos pela sua criação.
interface
uses
{$IFDEF ANDROID}
Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes,
Androidapi.JNI.Net, Androidapi.Helpers, Androidapi.JNI.Os, Androidapi.JNI.Support,
FMX.Helpers.android,
{$ENDIF}
System.UIConsts, System.IOUtils, FMX.Dialogs, System.SysUtils,
FMX.Graphics, FMX.Surfaces, System.UITypes;
type
TTipoFonte = (Normal, Negrito, Italico);
TTipoDirecao = (tpLef, tpRight, tpCenter);
type
TPDFPrint = class
private
FNomeArq : string;
FPagina : integer;
FFonteName : String;
FBordaSupInf: double;
FBordaLefRig: double;
{$IFDEF ANDROID}
FDocument: JPdfDocument;
FPageInfo: JPdfDocument_PageInfo;
FPage: JPdfDocument_Page;
FCanvas: JCanvas;
FPaint: JPaint;
{$ENDIF}
Procedure GravarPDF();
Procedure ImpTexto(ALinha, AColuna: Integer; ATexto: String;
ATipoFonte: TTipoFonte;
AColor: TAlphaColor;
ATamFonte: Integer;
ATpDirecao: TTipoDirecao);
procedure OpenPDF(const APDFFileName: string; AExternalURL: Boolean = False);
procedure SetBordaSupInf(const Value: double);
procedure SetBordaLefRig(const Value: double);
public
constructor Create(pNomeDocumentoPDF: String);
destructor Destroy;
property NomeArq: String read FNomeArq write FNomeArq;
property Pagina: Integer read FPagina write FPagina;
property FonteName: String read FFonteName write FFonteName;
procedure ImpL(Linha, Coluna: Integer; Texto: String; TipoFonte: TTipoFonte;
Color: TAlphaColor; TamFonte: Integer);
procedure ImpR(Linha, Coluna: Integer; Texto: String; TipoFonte: TTipoFonte;
Color: TAlphaColor; TamFonte: Integer);
procedure ImpC(Linha, Coluna: Integer; Texto: String; TipoFonte: TTipoFonte;
Color: TAlphaColor; TamFonte: Integer);
procedure ImpVal(ALinha, AColuna: Integer; AMascara: String; AValor: Double;
ATipoFonte: TTipoFonte;
AColor: TAlphaColor;
ATamFonte: Integer);
procedure ImpLinhaH(ALinha, AColuna, ATamanho: Integer; Color: TAlphaColor);
procedure ImpLinhaV(ALinha, AColuna, ATamanho: Integer; Color: TAlphaColor);
procedure ImpBox(ATop, ABottom, ALeft, ARight, ATamBorda: Integer;
AColor: TAlphaColor);
procedure ImpImage(Image: TBitmap; ATop, ALeft: Single);
procedure VisualizarPDF();
procedure CompartilharPDF();
procedure NovaPagina();
procedure Abrir;
Procedure Fechar;
function FileNameToUri(const AFileName: string): {$IFDEF ANDROID}Jnet_Uri{$ELSE}string{$ENDIF};
function MilimeterToPixel(const AMilimeter:double):double;
published
property BordaSupInf : double read FBordaSupInf write SetBordaSupInf;
property BordaLefRig : double read FBordaLefRig write SetBordaLefRig;
end;
//Essas contantes vao definir o espaçamento entre as linha e entre cada palavra;
//Por exemplo:
//TamLinha é o espaçamento de uma linha para outra
//TamColuna é o espaçamento entre cada letra
//BordaSupInf é o tamanho da borda superior e da borda inferior
//BordaLefRig é o tamanho das bordas laterais
//const
//TamLinha : Integer = 15;
//TamColuna : Integer = 7;
//BordaSupInf : Integer = 25;
//BordaLefRig : Integer = 15;
implementation
uses FMX.Types;
{ tPdfPrint }
constructor tPdfPrint.Create(pNomeDocumentoPDF: String);
var sArq : string;
begin
{$IFDEF ANDROID}
FDocument := TJPdfDocument.JavaClass.init;
FNomeArq := pNomeDocumentoPDF;
FPagina := 0;
FFonteName := 'Segoe UI';
//Seta valores padrões na "Property" para a mesma acionar o Methodo de Atribuição
//O usuario poderá fazer o mesmo por fora da Classe
Self.BordaSupInf:= 6.5;
Self.BordaLefRig:= 4.5;
sArq:= TPath.Combine(TPath.GetSharedDocumentsPath, FNomeArq + '.pdf');
if TFile.Exists(sArq) then TFile.Delete(sArq);
{$ENDIF}
end;
destructor tPdfPrint.Destroy;
begin
//Metodo destrutor da classe
end;
procedure tPdfPrint.Abrir;
begin
NovaPagina;
end;
function tPdfPrint.FileNameToUri(const AFileName: string): {$IFDEF ANDROID}Jnet_Uri{$ELSE}string{$ENDIF};
{$IFDEF ANDROID}
var JavaFile: JFile;
{$ENDIF}
begin
{$IFDEF ANDROID}
JavaFile := TJFile.JavaClass.init(StringToJString(AFileName));
Result := TJnet_Uri.JavaClass.fromFile(JavaFile);
{$ENDIF}
end;
procedure tPdfPrint.CompartilharPDF;
{$IFDEF ANDROID}
Var
IntentShare : JIntent;
Uri : Jnet_Uri;
Uris : JArrayList;
AttFile : JFile;
Path : String;
{$ENDIF}
Begin
{$IFDEF ANDROID}
IntentShare := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_SEND);
Uris := TJArrayList.Create;
Path:=TPath.Combine(TPath.GetSharedDocumentsPath, FNomeArq+'.pdf');
AttFile := TJFile.JavaClass.init(StringToJString(Path));
Uri := TJnet_Uri.JavaClass.fromFile(AttFile);
Uris.add(0,Uri);
IntentShare.putExtra(TJIntent.JavaClass.EXTRA_TEXT, StringToJString(''));
IntentShare.setType(StringToJString('Application/pdf'));
IntentShare.putParcelableArrayListExtra(TJIntent.JavaClass.EXTRA_STREAM, Uris);
TAndroidHelper.Activity.StartActivity(TJIntent.JavaClass.createChooser(IntentShare,StrToJCharSequence('Compartilhar com:')));
{$ENDIF}
end;
procedure tPdfPrint.Fechar;
begin
{$IFDEF ANDROID}
FDocument.finishPage(FPage);
GravarPDF;
FDocument.close;
{$ENDIF}
end;
procedure tPdfPrint.GravarPDF;
{$IFDEF ANDROID}
var sFileName: String;
OutputStream: JFileOutputStream;
{$ENDIF}
begin
{$IFDEF ANDROID}
sFileName:= TPath.Combine(TPath.GetSharedDocumentsPath, FNomeArq + '.pdf');
if TFile.Exists(sFileName) then TFile.Delete(sFileName);
OutputStream:= TJFileOutputStream.JavaClass.init(StringToJString(sFileName));
try
FDocument.writeTo(OutputStream);
finally
OutputStream.close;
end;
{$ENDIF}
end;
procedure tPdfPrint.ImpBox(ATop, ABottom, ALeft, ARight, ATamBorda: Integer;
AColor: TAlphaColor);
{$IFDEF ANDROID}
var Rect: JRectF;
{$ENDIF}
begin
{$IFDEF ANDROID}
FPaint.setColor(AColor);
FPaint.setStyle(TJPaint_Style.JavaClass.STROKE);
FPaint.setStrokeWidth(ATamBorda);
Rect := TJRectF.Create;
Rect.top := MilimeterToPixel( ATop ) + FBordaSupInf ;
Rect.bottom:= MilimeterToPixel( ABottom ) + FBordaSupInf;
Rect.left := MilimeterToPixel( ALeft ) + FBordaLefRig;
Rect.right := MilimeterToPixel( ARight ) + FBordaLefRig;
FCanvas.drawRect(Rect,FPaint);
//CRS - Volta o Stylo para Fill para não afetar os demais obejtos a serem inseridos
FPaint.setStyle(TJPaint_Style.JavaClass.FILL);
{$ENDIF}
end;
procedure tPdfPrint.ImpC(Linha, Coluna: Integer; Texto: String;
TipoFonte: TTipoFonte; Color: TAlphaColor; TamFonte: Integer);
begin
ImpTexto(Linha, coluna, Texto, TipoFonte, Color, TamFonte, tpCenter);
end;
procedure tPdfPrint.ImpImage(Image: TBitmap; ATop, ALeft: Single);
{$IFDEF ANDROID}
var NativeBitmap: JBitmap;
sBitMap: TBitmapSurface;
{$ENDIF}
begin
{$IFDEF ANDROID}
NativeBitmap:= TJBitmap.JavaClass.createBitmap(Image.Width,
Image.Height,
TJBitmap_Config.JavaClass.ARGB_8888);
sBitMap:= TBitmapSurface.create;
sBitMap.Assign(Image);
SurfaceToJBitmap(sBitMap, NativeBitmap);
FCanvas.drawBitmap(NativeBitmap,
MilimeterToPixel(ALeft),
MilimeterToPixel(ATop),
FPaint);
{$ENDIF}
end;
procedure tPdfPrint.ImpL(Linha, Coluna: Integer; Texto: String;
TipoFonte: TTipoFonte; Color: TAlphaColor; TamFonte: Integer);
begin
ImpTexto(Linha, coluna, Texto, TipoFonte, Color, TamFonte, tpLef);
end;
procedure tPdfPrint.ImpLinhaH(ALinha, AColuna, ATamanho: Integer; Color: TAlphaColor);
var AColor: TAlphaColorRec;
begin
AColor:= TAlphaColorRec(Color);
{$IFDEF ANDROID}
FPaint.setARGB(AColor.A, AColor.R, AColor.G, AColor.B);
FPaint.setStrokeWidth(1);
FCanvas.drawLine(MilimeterToPixel(AColuna) + FBordaLefRig, //(Coluna*TamColuna)+BordaLefRig,
MilimeterToPixel(ALinha) + FBordaSupInf, //(Linha*TamLinha)+BordaSupInf,
MilimeterToPixel(AColuna + ATamanho) + FBordaLefRig, //Tamanho*TamColuna,
MilimeterToPixel(ALinha) + FBordaSupInf, //(Linha*TamLinha)+BordaSupInf,
FPaint);
{$ENDIF}
end;
procedure tPdfPrint.ImpLinhaV(ALinha, AColuna, ATamanho: Integer; Color: TAlphaColor);
var AColor: TAlphaColorRec;
begin
AColor:= TAlphaColorRec(Color);
{$IFDEF ANDROID}
FPaint.setARGB(AColor.A, AColor.R, AColor.G, AColor.B);
FPaint.setStrokeWidth(1);
FCanvas.drawLine(MilimeterToPixel(AColuna) + FBordaLefRig, //(Coluna*TamColuna)+BordaLefRig,
MilimeterToPixel(ALinha) + FBordaSupInf, //(Linha*TamLinha)+BordaSupInf,
MilimeterToPixel(AColuna) + FBordaLefRig, //(Coluna*TamColuna)+BordaLefRig,
MilimeterToPixel(ALinha + ATamanho) + FBordaSupInf,//Tamanho*TamLinha,
FPaint);
{$ENDIF}
end;
procedure tPdfPrint.ImpR(Linha, Coluna: Integer; Texto: String;
TipoFonte: TTipoFonte; Color: TAlphaColor; TamFonte: Integer);
begin
ImpTexto(Linha, coluna, Texto, TipoFonte, Color, TamFonte, tpRight);
end;
/// <summary>
/// Função responsável por imprimir o texto
/// </summary>
/// <param name="Linha">Informa qual linha o texto passado deverá ser impresso</param>
/// <param name="Coluna">Informa qual a coluna o texto passado deverá ser impresso</param>
/// <param name="Texto">Texto a ser impresso</param>
/// <param name="TipoFonte">Estilo que deve ser usado para impressao do texto</param>
/// <param name="Color">Cor da fonte a ser usada</param>
/// <param name="TamFonte">Tamanho da fonte a ser usada</param>
/// <param name="TpDirecao">Parametro para indicar a direçao que o texto deve seguir</param>
procedure tPdfPrint.ImpTexto(ALinha, AColuna: Integer; ATexto: String;
ATipoFonte: TTipoFonte;
AColor: TAlphaColor;
ATamFonte: Integer;
ATpDirecao: TTipoDirecao);
var iColor: TAlphaColorRec;
begin
iColor:= TAlphaColorRec(AColor);
{$IFDEF ANDROID}
FPaint.setARGB(iColor.A, iColor.R, iColor.G, iColor.B);
case ATpDirecao of
tpLef : Fpaint.setTextAlign(TJPaint_Align.JavaClass.LEFT);
tpRight : Fpaint.setTextAlign(TJPaint_Align.JavaClass.RIGHT);
tpCenter : Fpaint.setTextAlign(TJPaint_Align.JavaClass.Center);
end;
Fpaint.setTextSize(ATamFonte);
case ATipoFonte of
Negrito: FPaint.setTypeface(TJTypeface.JavaClass.create(StringToJString(FFonteName),TJTypeface.JavaClass.BOLD));
Italico: FPaint.setTypeface(TJTypeface.JavaClass.create(StringToJString(FFonteName),TJTypeface.JavaClass.ITALIC));
Normal: FPaint.setTypeface(TJTypeface.JavaClass.create(StringToJString(FFonteName),TJTypeface.JavaClass.NORMAL));
end;
FCanvas.drawText(StringToJString(ATexto),
MilimeterToPixel(AColuna) + FBordaLefRig, //original --> (Coluna*TamColuna)+BordaLefRig,
MilimeterToPixel(ALinha) + FBordaSupInf, //original --> (Linha*TamLinha)+BordaSupInf,
FPaint);
{$ENDIF}
end;
procedure tPdfPrint.ImpVal(ALinha, AColuna: Integer; AMascara: String;
AValor: Double;
ATipoFonte: TTipoFonte;
AColor: TAlphaColor;
ATamFonte: Integer);
//var iColor: TAlphaColorRec;
begin
(*
iColor := TAlphaColorRec(AColor);
FPaint.setARGB(iColor.A, iColor.R, iColor.G, iColor.B);
Fpaint.setTextAlign(TJPaint_Align.JavaClass.RIGHT);
Fpaint.setTextSize(ATamFonte);
case ATipoFonte of
Negrito: FPaint.setTypeface(TJTypeface.JavaClass.create(StringToJString(FFonteName),TJTypeface.JavaClass.BOLD));
Italico: FPaint.setTypeface(TJTypeface.JavaClass.create(StringToJString(FFonteName),TJTypeface.JavaClass.ITALIC));
Normal: FPaint.setTypeface(TJTypeface.JavaClass.create(StringToJString(FFonteName),TJTypeface.JavaClass.NORMAL));
end;
FCanvas.drawText(StringToJString(FormatFloat(AMascara, AValor)),
(AColuna*TamColuna)+BordaLefRig,
(ALinha*TamLinha)+BordaSupInf,
FPaint);
*)
Self.ImpTexto(ALinha,
AColuna,
formatFloat(AMascara,AValor),
ATipoFonte,
AColor,
ATamFonte,
tpRight);
end;
procedure tPdfPrint.NovaPagina;
begin
Inc(FPagina);
{$IFDEF ANDROID}
if (FPagina > 1) then FDocument.finishPage(FPage);
//Define o tamanho da pagina Largura x comprimento, altere esses valores para criar um documento maior ou menor
//Voce pode definir uma variavel publica que guarda o tamanho, para personalizar a cada impressao
//https://www.tamanhosdepapel.com/a-tamanhos-em-pixels.htm
FPageInfo:= TJPageInfo_Builder.JavaClass.init(595, 842, FPagina).create;
FPage := FDocument.startPage(FPageInfo);
FCanvas := FPage.getCanvas;
FPaint := TJPaint.JavaClass.init;
{$ENDIF}
end;
procedure tPdfPrint.VisualizarPDF();
{$IFDEF ANDROID}
var Intent : JIntent;
sArq : string;
//Uri : Jnet_Uri;
LAutority : JString;
{$ENDIF}
begin
{$IFDEF ANDROID}
sArq:= TPath.Combine(TPath.GetSharedDocumentsPath, FNomeArq + '.pdf');
if TFile.Exists(sArq) then begin
if (StrToInt(Copy(trim(JStringToString(TJBuild_VERSION.JavaClass.RELEASE)),0,2)) >= 8) then
begin
LAutority:= StringToJString(
JStringToString(
TAndroidHelper.Context.getApplicationContext.getPackageName
) + '.fileprovider');
//Uri:= TJFileProvider.JavaClass.getUriForFile(TAndroidHelper.Context,
// LAutority,
// TJFile.JavaClass.init(StringToJString(Path)));
intent:= TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_VIEW);
intent.setDataAndType(FilenameToURI(sArq),
StringToJString('application/pdf'));
Intent.setFlags(TJIntent.JavaClass.FLAG_GRANT_READ_URI_PERMISSION);
TAndroidHelper.Activity.startActivity(Intent);
end
else
OpenPDF(FNomeArq + '.pdf');
end
else
raise Exception.Create('Nenhum arquivo ou diretório encontrado');
{$ENDIF}
end;
procedure tPdfPrint.OpenPDF(const APDFFileName: string; AExternalURL: Boolean);
{$IFDEF ANDROID}
var
Intent : JIntent;
Filepath : String;
SharedFilePath : string;
tmpFile : String;
{$ENDIF}
begin
{$IFDEF ANDROID}
if not AExternalURL then begin
Filepath := TPath.Combine(TPath.GetDocumentsPath , APDFFileName);
SharedFilePath:= TPath.Combine(TPath.GetSharedDocumentsPath, APDFFileName);
if TFile.Exists(SharedFilePath) then TFile.Delete(SharedFilePath);
TFile.Copy(Filepath, SharedFilePath);
end;
Intent := TJIntent.Create;
Intent.setAction(TJIntent.JavaClass.ACTION_VIEW);
tmpFile := StringReplace(APDFFileName, ' ', '%20', [rfReplaceAll]);
if AExternalURL then
Intent.setData(StrToJURI(tmpFile))
else
Intent.setDataAndType(StrToJURI('file://' + SharedFilePath), StringToJString('application/pdf'));
SharedActivity.startActivity(Intent);
{$ENDIF}
end;
procedure TPDFPrint.SetBordaLefRig(const Value: double);
begin
FBordaLefRig:= MilimeterToPixel(Value);
end;
procedure TPDFPrint.SetBordaSupInf(const Value: double);
begin
FBordaSupInf:= MilimeterToPixel(Value);
end;
function tPdfPrint.MilimeterToPixel(const AMilimeter:double):double;
begin
result:= (TDeviceDisplayMetrics.Default.PixelsPerInch / 25.4) * AMilimeter;
end;
end.
|
{******************************************************************************}
{ CnPack For Delphi/C++Builder }
{ 中国人自己的开放源码第三方开发包 }
{ (C)Copyright 2001-2023 CnPack 开发组 }
{ ------------------------------------ }
{ }
{ 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 }
{ 改和重新发布这一程序。 }
{ }
{ 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 }
{ 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 }
{ }
{ 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 }
{ 还没有,可访问我们的网站: }
{ }
{ 网站地址:http://www.cnpack.org }
{ 电子邮件:master@cnpack.org }
{ }
{******************************************************************************}
unit CnConsts;
{* |<PRE>
================================================================================
* 软件名称:开发包基础库
* 单元名称:公共资源字符串定义单元
* 单元作者:CnPack 开发组
* 备 注:
* 开发平台:PWin98SE + Delphi 5.0
* 兼容测试:PWin9X/2000/XP + Delphi 5/6
* 本 地 化:该单元中的字符串均符合本地化处理方式
* 修改记录:2005.12.24 V1.0
* 创建单元,移植入英文字符
================================================================================
|</PRE>}
interface
{$I CnPack.inc}
const
ECN_OK = 0; // 错误码 OK,无错误
ECN_FILE_NOT_FOUND = $10; // 文件不存在
ECN_CUSTOM_ERROR_BASE = $1000; // 供外界设定的错误码起始值
//==============================================================================
// Strings DO NOT Localize:
//==============================================================================
resourcestring
// CnPack Reg Path
SCnPackRegPath = '\Software\CnPack';
// Tools Reg Path
SCnPackToolRegPath = 'CnTools';
//==============================================================================
// Strings to be Localized:
//==============================================================================
var
// Common Information
SCnInformation: string = 'Information';
SCnWarning: string = 'Warning';
SCnError: string = 'Error';
SCnEnabled: string = 'Enabled';
SCnDisabled: string = 'Disabled';
SCnMsgDlgOK: string = '&OK';
SCnMsgDlgCancel: string = '&Cancel';
SCnMsgDlgYes: string = '&Yes';
SCnMsgDlgNo: string = '&No';
SCnMsgDlgYesToAll: string = 'Yes to &All';
SCnMsgDlgNoToAll: string = 'No to A&ll';
const
// CnPack Information
SCnPackAbout = 'CnPack';
SCnPackVer = 'Ver 0.1.2.6';
SCnPackStr = SCnPackAbout + ' ' + SCnPackVer;
SCnPackUrl = 'http://www.cnpack.org';
SCnPackBbsUrl = 'http://bbs.cnpack.org';
SCnPackNewsUrl = 'news://news.cnpack.org';
SCnPackSourceUrl = 'http://github.com/cnpack';
SCnPackEmail = 'master@cnpack.org';
SCnPackBugEmail = 'bugs@cnpack.org';
SCnPackSuggestionsEmail = 'suggestions@cnpack.org';
SCnPackDonationUrl = 'http://www.cnpack.org/foundation.php';
SCnPackDonationUrlSF = 'http://sourceforge.net/donate/index.php?group_id=110999';
SCnPackGroup = 'CnPack Team';
SCnPackCopyright = '(C)Copyright 2001-2023 ' + SCnPackGroup;
// CnPropEditors
SCopyrightFmtStr =
SCnPackStr + #13#10#13#10 +
'Component Name: %s' + #13#10 +
'Author: %s(%s)' + #13#10 +
'Comment: %s' + #13#10 +
'HomePage: ' + SCnPackUrl + #13#10 +
'Email: ' + SCnPackEmail + #13#10#13#10 +
SCnPackCopyright;
resourcestring
// Component Palette Name
SCnNonVisualPalette = 'CnPack Tools';
SCnGraphicPalette = 'CnPack VCL';
SCnNetPalette = 'CnPack Net';
SCnDatabasePalette = 'CnPack DB';
SCnReportPalette = 'CnPack Report';
// CnPack Developers Added from Last.
var
SCnPack_Zjy: string = 'Zhou JingYu';
SCnPack_Shenloqi: string = 'Chinbo';
SCnPack_xiaolv: string = 'xiaolv';
SCnPack_Flier: string = 'Flier Lu';
SCnPack_LiuXiao: string = 'Liu Xiao';
SCnPack_PanYing: string = 'Pan Ying';
SCnPack_Hubdog: string = 'Hubdog';
SCnPack_Wyb_star: string = 'wyb_star';
SCnPack_Licwing: string = 'Licwing zue';
SCnPack_Alan: string = 'Alan';
SCnPack_GuYueChunQiu: string = 'GuYueChunQiu';
SCnPack_Aimingoo: string = 'Aimingoo';
SCnPack_QSoft: string = 'QSoft';
SCnPack_Hospitality: string = 'ZhangJiongXuan (Hospitality)';
SCnPack_SQuall: string = 'SQUALL';
SCnPack_Hhha: string = 'Hhha';
SCnPack_Beta: string = 'beta';
SCnPack_Leeon: string = 'Leeon';
SCnPack_SuperYoyoNc: string = 'SuperYoyoNC';
SCnPack_JohnsonZhong: string = 'Johnson Zhong';
SCnPack_DragonPC: string = 'Dragon P.C.';
SCnPack_Kendling: string = 'Kending';
SCnPack_ccrun: string = 'ccrun';
SCnPack_Dingbaosheng: string = 'dingbaosheng';
SCnPack_LuXiaoban: string = 'Zhou Yibo(Lu Xiaoban)';
SCnPack_Savetime: string = 'savetime';
SCnPack_solokey: string = 'solokey';
SCnPack_Bahamut: string = 'Bahamut';
SCnPack_Sesame: string = 'Sesame';
SCnPack_BuDeXian: string = 'BuDeXian';
SCnPack_XiaoXia: string = 'Summer';
SCnPack_ZiMin: string = 'ZiMin';
SCnPack_rarnu: string = 'rarnu';
SCnPack_dejoy: string = 'dejoy';
// CnCommon
SUnknowError: string = 'Unknow error';
SErrorCode: string = 'Error code:';
const
SCnPack_ZjyEmail = 'zjy@cnpack.org';
SCnPack_ShenloqiEmail = 'Shenloqi@hotmail.com';
SCnPack_xiaolvEmail = 'xiaolv888@etang.com';
SCnPack_FlierEmail = 'flier_lu@sina.com';
SCnPack_LiuXiaoEmail = 'liuxiao@cnpack.org';
SCnPack_PanYingEmail = 'panying@sina.com';
SCnPack_HubdogEmail = 'hubdog@263.net';
SCnPack_Wyb_starMail = 'wyb_star@sina.com';
SCnPack_LicwingEmail = 'licwing@chinasystemsn.com';
SCnPack_AlanEmail = 'BeyondStudio@163.com';
SCnPack_GuYueChunQiuEmail = 'guyuechunqiu@cnpack.org';
SCnPack_AimingooEmail = 'aim@263.net';
SCnPack_QSoftEmail = 'hq.com@263.net';
SCnPack_HospitalityEmail = 'Hospitality_ZJX@msn.com';
SCnPack_SQuallEmail = 'squall_sa@163.com';
SCnPack_HhhaEmail = 'Hhha@eyou.com';
SCnPack_BetaEmail = 'beta@01cn.net';
SCnPack_LeeonEmail = 'real-like@163.com';
SCnPack_SuperYoyoNcEmail = 'superyoyonc@sohu.com';
SCnPack_JohnsonZhongEmail = 'zhongs@tom.com';
SCnPack_DragonPCEmail = 'dragonpc@21cn.com';
SCnPack_KendlingEmail = 'kendling@21cn.com';
SCnPack_ccRunEmail = 'info@ccrun.com';
SCnPack_DingbaoshengEmail = 'yzdbs@msn.com';
SCnPack_LuXiaobanEmail = 'zhouyibo2000@sina.com';
SCnPack_SavetimeEmail = 'savetime2k@hotmail.com';
SCnPack_solokeyEmail = 'crh611@163.com';
SCnPack_BahamutEmail = 'fantasyfinal@126.com';
SCnPack_SesameEmail = 'sesamehch@163.com';
SCnPack_BuDeXianEmail = 'appleak46@yahoo.com.cn';
SCnPack_XiaoXiaEmail = 'summercore@163.com';
SCnPack_ZiMinEmail = '441414288@qq.com';
SCnPack_rarnuEmail = 'rarnu@cnpack.org';
SCnPack_dejoyEmail = 'dejoybbs@163.com';
// CnMemProf
SCnPackMemMgr = 'CnMemProf';
SMemLeakDlgReport = 'Found %d memory leaks. [There are %d allocated before replace memory manager.]';
SMemMgrODSReport = 'Get = %d Free = %d Realloc = %d';
SMemMgrOverflow = 'Memory Manager''s list capability overflow, Please enlarge it!';
SMemMgrRunTime = '%d hour(s) %d minute(s) %d second(s)。';
SOldAllocMemCount = 'There are %d allocated before replace memory manager.';
SAppRunTime = 'Application total run time: ';
SMemSpaceCanUse = 'HeapStatus.TotalAddrSpace: %d KB';
SUncommittedSpace = 'HeapStatus.TotalUncommitted: %d KB';
SCommittedSpace = 'HeapStatus.TotalCommitted: %d KB';
SFreeSpace = 'HeapStatus.TotalFree: %d KB';
SAllocatedSpace = 'HeapStatus.TotalAllocated: %d KB';
SAllocatedSpacePercent = 'TotalAllocated div TotalAddrSpace: %d%%';
SFreeSmallSpace = 'HeapStatus.FreeSmall: %d KB';
SFreeBigSpace = 'HeapStatus.FreeBig: %d KB';
SUnusedSpace = 'HeapStatus.Unused: %d KB';
SOverheadSpace = 'HeapStatus.Overhead: %d KB';
SObjectCountInMemory = 'Objects count in memory: ';
SNoMemLeak = ' No memory leak.';
SNoName = '(no name)';
SNotAnObject = ' Not an object';
SByte = 'Byte';
SCommaString = ',';
SPeriodString = '.';
function CnGetLastError: Integer;
procedure _CnSetLastError(Err: Integer);
implementation
threadvar
CnErrorCode: Integer;
function CnGetLastError: Integer;
begin
Result := CnErrorCode;
end;
procedure _CnSetLastError(Err: Integer);
begin
CnErrorCode := Err;
end;
end.
|
unit KM_AIFields;
{$I KaM_Remake.inc}
interface
uses
Classes, KromUtils, SysUtils, Graphics,
KM_CommonClasses, KM_Defaults,
KM_Points, KM_AIInfluences, KM_NavMesh;
type
//Master class for Influence maps, NavMeshe and other terrain representations
//that are helpful in decision making by Mayour/General
TKMAIFields = class
private
fNavMesh: TKMNavMesh;
fInfluences: TKMInfluences;
public
constructor Create;
destructor Destroy; override;
property NavMesh: TKMNavMesh read fNavMesh;
property Influences: TKMInfluences read fInfluences;
procedure AfterMissionInit;
procedure Save(SaveStream: TKMemoryStream);
procedure Load(LoadStream: TKMemoryStream);
procedure UpdateState(aTick: Cardinal);
procedure Paint(aRect: TKMRect);
end;
var
fAIFields: TKMAIFields;
implementation
{ TKMAIFields }
constructor TKMAIFields.Create;
begin
inherited;
fInfluences := TKMInfluences.Create;
fNavMesh := TKMNavMesh.Create(fInfluences);
end;
destructor TKMAIFields.Destroy;
begin
FreeAndNil(fNavMesh);
FreeAndNil(fInfluences);
inherited;
end;
procedure TKMAIFields.AfterMissionInit;
begin
fInfluences.Init;
if AI_GEN_NAVMESH then
fNavMesh.Init;
end;
procedure TKMAIFields.Save(SaveStream: TKMemoryStream);
begin
fNavMesh.Save(SaveStream);
fInfluences.Save(SaveStream);
end;
procedure TKMAIFields.Load(LoadStream: TKMemoryStream);
begin
fNavMesh.Load(LoadStream);
fInfluences.Load(LoadStream);
end;
procedure TKMAIFields.UpdateState(aTick: Cardinal);
begin
fInfluences.UpdateState(aTick);
fNavMesh.UpdateState(aTick);
end;
//Render debug symbols
procedure TKMAIFields.Paint(aRect: TKMRect);
begin
if AI_GEN_INFLUENCE_MAPS then
fInfluences.Paint(aRect);
if AI_GEN_NAVMESH then
fNavMesh.Paint(aRect);
end;
end.
|
unit SimThyrServices;
{ SimThyr Project }
{ (c) J. W. Dietrich, 1994 - 2011 }
{ (c) Ludwig Maximilian University of Munich 1995 - 2002 }
{ (c) Ruhr University of Bochum 2005 - 2011 }
{ This unit provides some global functions }
{ Source code released under the BSD License }
{$mode objfpc}{$R+}
interface
uses
Classes, SysUtils, Grids, StdCtrls, Dialogs, Forms, SimThyrTypes,
DOM, XMLRead, XMLWrite
{$IFDEF win32}
, Windows, Win32Proc
{$ELSE}
{$IFDEF LCLCarbon}
, MacOSAll
{$ENDIF}
{$ENDIF}
;
const
iuSystemScript = -1;
iuCurrentScript = -2;
iuWordSelectTable = 0;
iuWordWrapTable = 1;
iuNumberPartsTable = 2;
iuUnTokenTable = 3;
iuWhiteSpaceList = 4;
type
tSaveMode = (TimeSeries, Plot);
var
gSaveMode: tSaveMode;
function OSVersion: Str255;
procedure bell;
function NodeContent(theRoot: TDOMNode; name: String): String;
procedure VarFromNode(theRoot: TDOMNode; name: String; var theVar: real);
function SimpleNode(Doc: TXMLDocument; name, value: String): TDOMNode;
procedure ClearResultContents (var theContents: tResultContent);
procedure writeaTableCell (theTable: TStringGrid; theCell: TableCell; theString: Str255);
procedure writeTableCells (theTable: TStringGrid; theContents: tResultContent);
procedure SetStatusBarPanel0(curr, max: String);
procedure writeaMemoLine(theMemo: TMemo; theString: Str255);
procedure SetFileName(theForm: TForm; const FileName: String);
procedure ShowImplementationMessage;
procedure ShowFormatMessage;
implementation
uses SimThyrLog;
function OSVersion: Str255;
var
osErr: integer;
response: longint;
begin
{$IFDEF LCLcarbon}
OSVersion := 'Mac OS X 10.';
{$ELSE}
{$IFDEF Linux}
OSVersion := 'Linux Kernel ';
{$ELSE}
{$IFDEF UNIX}
OSVersion := 'Unix ';
{$ELSE}
{$IFDEF WINDOWS}
if WindowsVersion = wv95 then OSVersion := 'Windows 95 '
else if WindowsVersion = wvNT4 then OSVersion := 'Windows NT v.4 '
else if WindowsVersion = wv98 then OSVersion := 'Windows 98 '
else if WindowsVersion = wvMe then OSVersion := 'Windows ME '
else if WindowsVersion = wv2000 then OSVersion := 'Windows 2000 '
else if WindowsVersion = wvXP then OSVersion := 'Windows XP '
else if WindowsVersion = wvServer2003 then OSVersion := 'Windows Server 2003 '
else if WindowsVersion = wvVista then OSVersion := 'Windows Vista '
else if WindowsVersion = wv7 then OSVersion := 'Windows 7 '
else OSVersion:= 'Windows ';
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
end;
procedure bell; {platform-independent implementation of acustical warning}
begin
{$IFDEF win32}
MessageBeep(0);
{$ELSE}
{$IFDEF LCLCarbon}
SysBeep(30);
{$ELSE}
beep;
{$ENDIF}
{$ENDIF}
end;
function NodeContent(theRoot: TDOMNode; name: String): String; {supports XML routines}
var
theNode: TDOMNode;
begin
if assigned(theRoot) then
theNode := theRoot.FindNode(name);
if assigned(theNode) then
begin
Result := theNode.FirstChild.NodeValue;
end
else
Result := 'NA';
end;
procedure VarFromNode(theRoot: TDOMNode; name: String; var theVar: real); {supports XML routines}
var theString: String;
begin
theString := NodeContent(theRoot, name);
if theString <> 'NA' then
theVar := StrToFloat(theString);
end;
function SimpleNode(Doc: TXMLDocument; name, value: String): TDOMNode; {supports XML routines}
var
ItemNode,TextNode: TDOMNode;
begin
ItemNode:=Doc.CreateElement(name);
TextNode:=Doc.CreateTextNode(value);
ItemNode.AppendChild(TextNode);
Result := ItemNode;
end;
procedure ClearResultContents (var theContents: tResultContent);
var
counter: integer;
begin
for counter := 1 to RES_MAX_COLS do
theContents[counter] := ' ';
end;
procedure writeaTableCell (theTable: TStringGrid; theCell: TableCell; theString: Str255);
begin
theTable.Cells[theCell.x, theCell.y] := theString;
end;
procedure writeTableCells (theTable: TStringGrid; theContents: tResultContent);
{writes a vector of values to the last line of a StringGrid}
var
j, ignored: integer;
cSize: TPoint;
theCell: TableCell;
theString: Str255;
begin
theTable.Tag := theTable.Tag + 1;
if theTable.Tag > GridRows - 1 then
theTable.RowCount := theTable.RowCount + 1;
theCell.y := theTable.Tag;
for j := 0 to RES_MAX_COLS - 1 do
begin
theString := theContents[j];
theCell.x := j;
writeaTableCell(theTable, theCell, theString);
end;
end;
procedure SetStatusBarPanel0(curr, max: String);
begin
SimThyrLogWindow.StatusBar1.Panels[0].Text := ' ' + curr + ':' + max;
end;
procedure writeaMemoLine(theMemo: TMemo; theString: Str255);
begin
theMemo.Lines.Text := theMemo.Lines.Text + kCRLF + theString;
end;
procedure SetFileName(theForm: TForm; const FileName: String);
begin
theForm.Caption := ExtractFileName(FileName);
end;
procedure ShowImplementationMessage;
begin
bell;
ShowMessage(IMPLEMENTATION_MESSAGE);
end;
procedure ShowFormatMessage;
begin
bell;
ShowMessage(FORMAT_MESSAGE);
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2012 Vincent Parrett }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.Tests.MemoryLeaks;
interface
uses
DUnitX.TestFramework;
type
{$M+}
[TestFixture]
[IgnoreMemoryLeaks]
TTestsNoMemoryLeaksReported = class
published
[Test]
procedure No_Reporting_Of_Memory_Leaks;
[Test]
[IgnoreMemoryLeaks(False)]
procedure Override_Reporting_Of_Memory_Leaks;
end;
[TestFixture]
// if the "IgnoreMemoryLeaks" attribute is not specified, then all memory leaks will be reported.
[IgnoreMemoryLeaks(False)] // Report all leaks. This is the same as not specifying this attribute.
TTestsMemoryLeaksReported = class
published
[Test]
[IgnoreMemoryLeaks(True)]
procedure Override_No_Reporting_Of_Memory_Leaks;
[Test]
// if the "IgnoreMemoryLeaks" attribute is not specified, it will use the fixtures setting.
procedure Reporting_Of_Memory_Leaks;
end;
implementation
{ TTestsNoMemoryLeaksReported }
procedure TTestsNoMemoryLeaksReported.No_Reporting_Of_Memory_Leaks;
begin
AllocMem(1024);
Assert.Pass;
end;
procedure TTestsNoMemoryLeaksReported.Override_Reporting_Of_Memory_Leaks;
begin
AllocMem(512);
Assert.Pass;
end;
{ TTestsMemoryLeaksReported }
procedure TTestsMemoryLeaksReported.Override_No_Reporting_Of_Memory_Leaks;
begin
AllocMem(256);
Assert.Pass;
end;
procedure TTestsMemoryLeaksReported.Reporting_Of_Memory_Leaks;
begin
AllocMem(128);
Assert.Pass;
end;
initialization
TDUnitX.RegisterTestFixture(TTestsNoMemoryLeaksReported);
TDUnitX.RegisterTestFixture(TTestsMemoryLeaksReported);
end.
|
{ @abstract(This file is part of the KControls component suite for Delphi and Lazarus.)
@author(Tomas Krysl)
Copyright (c) 2020 Tomas Krysl<BR><BR>
<B>License:</B><BR>
This code is licensed under BSD 3-Clause Clear License, see file License.txt or https://spdx.org/licenses/BSD-3-Clause-Clear.html.
}
// Original copyright notice:
{******************************************************************************}
{ }
{ Lightweight native pascal XML implementation (originally GmXml.pas) }
{ }
{ Copyright (c) 2003 Graham Murt - www.murtsoft.co.uk }
{ }
{ Feel free to e-mail me with any comments, suggestions, bugs or help at: }
{ }
{ graham@murtsoft.co.uk }
{ }
{******************************************************************************}
unit kxml;
{$include kcontrols.inc}
interface
uses Classes, Contnrs, SysUtils;
resourcestring
sParseNoOpenTag = 'XML parsing error: Open tag not found.';
sParseValueOutSideTag = 'XML parsing error: Value outside tag.';
sParseNumericConvertError = 'XML parsing error: Cannot convert value %s to number.';
const
COMP_VERSION = 0.13;
XML_SPECIFICATION = '<?xml version="1.0"%s?>';
type
TXmlNode = class;
TXmlNodeList = class;
TXmlEnumNodeEvent = procedure(Sender: TObject; ANode: TXmlNode) of object;
// *** TXmlNodeElement ***
TXmlNodeAttribute = class
private
FName: string;
FValue: string;
procedure SetName(AValue: string);
procedure SetValue(AValue: string);
public
procedure Assign(Source: TXmlNodeAttribute);
property Name: string read FName write SetName;
property Value: string read FValue write SetValue;
end;
TXmlNodeAttributes = class(TObjectList) // without generics here for backward compatibility...
private
function GetItem(Index: Integer): TXmlNodeAttribute;
procedure SetItem(Index: Integer; const Value: TXmlNodeAttribute);
public
procedure Assign(Source: TXmlNodeAttributes);
property Items[Index: Integer]: TXmlNodeAttribute read GetItem write SetItem; default;
procedure AddPair(const AName, AValue: string);
function Find(const AName: string; out AValue: string): Boolean;
end;
// *** TXmlNode ***
{ TXmlNode }
TXmlNode = class(TPersistent)
private
FChildren: TXmlNodeList;
FAttributes: TXmlNodeAttributes;
FName: string;
FParent: TXmlNode;
FValue: string;
// events...
function GetAsDisplayString: string;
function GetAsHexInt: integer;
function GetIsLeafNode: Boolean;
function GetAsBoolean: Boolean;
function GetAsFloat: Extended;
function GetAsInteger: integer;
function GetAsString: string;
function GetAttribute: TXmlNodeAttribute;
function GetLevel: integer;
function CloseTag: string;
function OpenTag: string;
procedure SetAsBoolean(const Value: Boolean);
procedure SetAsFloat(const Value: Extended);
procedure SetAsHexInt(AValue: integer);
procedure SetAsInteger(const Value: integer);
procedure SetAsString(const Value: string);
procedure SetName(Value: string); virtual;
public
constructor Create(AParentNode: TXmlNode); virtual;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure EnumerateNodes(ACallback: TXmlEnumNodeEvent);
procedure Clear;
function ChildAsBoolean(const ChildNodeName: string; DefValue: Boolean): Boolean;
function ChildAsDateTime(const ChildNodeName: string; DefValue: TDateTime): TDateTime;
function ChildAsFloat(const ChildNodeName: string; DefValue: Double): Double;
function ChildAsInteger(const ChildNodeName: string; DefValue: Int64): Int64;
function ChildAsInteger(const ChildNodeName: string; DefValue: Integer): Integer;
function ChildAsString(const ChildNodeName: string; const DefValue: string): string;
property AsDisplayString: string read GetAsDisplayString;
property AsString: string read GetAsString write SetAsString;
property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean;
property AsFloat: Extended read GetAsFloat write SetAsFloat;
property AsInteger: integer read GetAsInteger write SetAsInteger;
property AsHexInt: integer read GetAsHexInt write SetAsHexInt;
property Attribute: TXmlNodeAttribute read GetAttribute;
property Attributes: TXmlNodeAttributes read FAttributes;
property Children: TXmlNodeList read FChildren;
property IsLeafNode: Boolean read GetIsLeafNode;
property Level: integer read GetLevel;
property Name: string read FName write SetName;
property Parent: TXmlNode read FParent;
end;
// *** TXmlNodeList ***
TXmlNodeList = class
private
FParent: TXmlNode;
FList: TList;
function GetCount: integer;
function GetNode(index: integer): TXmlNode;
function GetNodeByName(AName: string): TXmlNode;
procedure SetNodeByName(AName: string; ANode: TXmlNode);
function GetRoot: TXmlNode;
protected
public
constructor Create(AParent: TXmlNode);
destructor Destroy; override;
procedure Assign(Source: TXmlNodeList);
function Add(AName: string): TXmlNode;
procedure AddNode(ANode: TXmlNode);
procedure DeleteNode(ANode: TXmlNode);
procedure SetNode(index: integer; const Value: TXmlNode);
//procedure NextNode;
procedure Clear;
procedure PeekNode(ANode: TXmlNode);
procedure PokeNode(ANode: TXmlNode);
property Count: integer read GetCount;
property Node[index: integer]: TXmlNode read GetNode write SetNode; default;
property NodeByName[AName: string]: TXmlNode read GetNodeByName write SetNodeByName;
property Root: TXmlNode read GetRoot;
end;
// *** TXml ***
TXml = class(TComponent)
private
FAutoIndent: Boolean;
FEncoding: string;
FIncludeHeader: Boolean;
FKeepLineBreaksInValues: Boolean;
FLineBreaks: Boolean;
FNodes: TXmlNodeList;
FStrings: TSTringList;
function GetAbout: string;
function GetDisplayText: string;
function GetEncodingStr: string;
function GetIndent(ALevel: integer): string;
function GetText(ReplaceEscapeChars: Boolean): string;
function GetXmlText: string;
procedure SetAsText(Value: string);
procedure SetAbout(Value: string);
procedure SetAutoIndent(const Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function IsXML(const AText: string; AIncludeHeader: Boolean): Boolean;
procedure LoadFromFile(AFileName: string);
procedure LoadFromStream(Stream: TStream);
procedure SaveToFile(AFilename: string);
procedure SaveToStream(Stream: TStream);
property DisplayText: string read GetDisplayText;
property Nodes: TXmlNodeList read FNodes;
property Text: string read GetXmlText write SetAsText;
property LineBreaks: Boolean read FLineBreaks write FLineBreaks;
property KeepLineBreaksInValues: Boolean read FKeepLineBreaksInValues write FKeepLineBreaksInValues;
published
property About: string read GetAbout write SetAbout;
property AutoIndent: Boolean read FAutoIndent write SetAutoIndent default True;
property Encoding: string read FEncoding write FEncoding;
property IncludeHeader: Boolean read FIncludeHeader write FIncludeHeader default True;
end;
function DecodeText(const AText: AnsiString): AnsiString;
function EncodeText(const AText: AnsiString): AnsiString;
function StrToFloatDefLoc(const AValue: string; ADefault: Double; const AFormatSettings: TFormatSettings): Double; overload;
function StrToFloatDefLoc(const AValue: string; ADefault: Double): Double; overload;
implementation
uses
KFunctions;
//------------------------------------------------------------------------------
// *** Unit Functions ***
function StrPos(const SubStr, S: string; Offset: Cardinal = 1): Integer;
var
I,X: Integer;
Len, LenSubStr: Integer;
begin
if Offset = 1 then
Result := Pos(SubStr, S)
else
begin
I := Offset;
LenSubStr := Length(SubStr);
Len := Length(S) - LenSubStr + 1;
while I <= Len do
begin
if S[I] = SubStr[1] then
begin
X := 1;
while (X < LenSubStr) and (S[I + X] = SubStr[X + 1]) do
Inc(X);
if (X = LenSubStr) then
begin
Result := I;
exit;
end;
end;
Inc(I);
end;
Result := 0;
end;
end;
procedure ReplaceText(var AText: string; AFind, AReplace: string);
var
Index: integer;
begin
Index := 1;
while StrPos(AFind, AText, Index) <> 0 do
begin
Index := StrPos(AFind, AText, Index);
Delete(AText, Index, Length(AFind));
Insert(AReplace, AText, Index);
Inc(Index, Length(AReplace));
end;
end;
procedure XmlError(const Msg: string);
begin
raise Exception.Create(Msg);
end;
function DecodeText(const AText: AnsiString): AnsiString;
var
I: Integer;
begin
I := Length(AText);
SetLength(Result, Length(AText));
while I > 0 do
begin
if I < Length(AText) then
Result[I] := AnsiChar(Ord(AText[I]) - Ord(Result[I + 1]))
else
Result[I] := AnsiChar(Ord(AText[I]) - $40);
Result[I] := AnsiChar(Ord(Result[I]) + $80);
Dec(I);
end;
end;
function EncodeText(const AText: AnsiString): AnsiString;
var
I: Integer;
begin
I := 1;
SetLength(Result, Length(AText));
while I <= Length(AText) do
begin
Result[I] := AnsiChar(Ord(AText[I]) - $80);
if I < Length(AText) then
Result[I] := AnsiChar(Ord(Result[I]) + Ord(AText[I + 1]))
else
Result[I] := AnsiChar(Ord(Result[I]) + $40);
Inc(I);
end;
end;
function StrToFloatDefLoc(const AValue: string; ADefault: Double; const AFormatSettings: TFormatSettings): Double;
var
S: string;
begin
S := AValue;
if AFormatSettings.DecimalSeparator <> '.' then
S := StringReplace(S, '.', AFormatSettings.DecimalSeparator, [rfReplaceAll]);
if AFormatSettings.DecimalSeparator <> ',' then
S := StringReplace(S, ',', AFormatSettings.DecimalSeparator, [rfReplaceAll]);
Result := StrToFloatDef(S, ADefault);
end;
function StrToFloatDefLoc(const AValue: string; ADefault: Double): Double;
begin
Result := StrToFloatDefLoc(AValue, ADefault, GetFormatSettings);
end;
//------------------------------------------------------------------------------
// *** TXmlNodeElement ***
procedure TXmlNodeAttribute.Assign(Source: TXmlNodeAttribute);
begin
if Source <> nil then
begin
FName := Source.FName;
FValue := Source.FValue;
end;
end;
procedure TXmlNodeAttribute.SetName(AValue: string);
begin
TrimWhiteSpaces(AValue, cLineBreaks + cWordBreaks);
FName := AValue;
end;
procedure TXmlNodeAttribute.SetValue(AValue: string);
begin
TrimWhiteSpaces(AValue, cLineBreaks + cWordBreaks);
FValue := AValue;
ReplaceText(FValue, '"', '');
end;
//------------------------------------------------------------------------------
{ TXmlNodeAttributes }
procedure TXmlNodeAttributes.AddPair(const AName, AValue: string);
var
Attr: TXmlNodeAttribute;
begin
Attr := TXmlNodeAttribute.Create;
Attr.Name := AName;
Attr.Value := AValue;
Add(Attr);
end;
procedure TXmlNodeAttributes.Assign(Source: TXmlNodeAttributes);
var
I: Integer;
begin
Clear;
if Source <> nil then
begin
for I := 0 to Source.Count - 1 do
begin
AddPair(Source[I].Name, Source[I].Value);
end;
end;
end;
function TXmlNodeAttributes.Find(const AName: string;
out AValue: string): Boolean;
var
I: Integer;
Attr: TXmlNodeAttribute;
begin
Result := False;
for I := 0 to Count - 1 do
begin
Attr := TXmlNodeAttribute(Get(I));
if SameText(AName, Attr.Name) then
begin
AValue := Attr.Value;
Exit(True);
end;
end;
end;
function TXmlNodeAttributes.GetItem(Index: Integer): TXmlNodeAttribute;
begin
Result := TXmlNodeAttribute(inherited GetItem(Index));
end;
procedure TXmlNodeAttributes.SetItem(Index: Integer;
const Value: TXmlNodeAttribute);
begin
inherited SetItem(Index, Value);
end;
//------------------------------------------------------------------------------
// *** TXmlNode ***
constructor TXmlNode.Create(AParentNode: TXmlNode);
begin
inherited Create;
FChildren := TXmlNodeList.Create(Self);
FAttributes := TXmlNodeAttributes.Create;
FParent := AParentNode;
end;
destructor TXmlNode.Destroy;
begin
FAttributes.Free;
FChildren.Free;
inherited Destroy;
end;
procedure TXmlNode.Assign(Source: TPersistent);
begin
if Source is TXmlNode then
begin
FChildren.FParent := Self;
FAttributes.Assign(TXmlNode(Source).FAttributes);
FName := TXmlNode(Source).FName;
FValue := TXmlNode(Source).FValue;
FChildren.Assign(TXmlNode(Source).FChildren);
end;
end;
procedure TXmlNode.Clear;
begin
FAttributes.Clear;
FChildren.Clear;
end;
function TXmlNode.ChildAsBoolean(const ChildNodeName: string;
DefValue: Boolean): Boolean;
var
Child: TXmlNode;
begin
Result := DefValue;
Child := Children.NodeByName[ChildNodeName];
if Child <> nil then
Result := StrToBoolDef(Child.AsDisplayString, DefValue);
end;
function TXmlNode.ChildAsDateTime(const ChildNodeName: string; DefValue: TDateTime): TDateTime;
var
Child: TXmlNode;
begin
Result := DefValue;
Child := Children.NodeByName[ChildNodeName];
if Child <> nil then
Result := StrToDateTimeDef(Child.AsDisplayString, DefValue);
end;
function TXmlNode.ChildAsFloat(const ChildNodeName: string;
DefValue: Double): Double;
var
Child: TXmlNode;
begin
Result := DefValue;
Child := Children.NodeByName[ChildNodeName];
if Child <> nil then
Result := StrToFloatDefLoc(Child.AsDisplayString, DefValue);
end;
function TXmlNode.ChildAsInteger(const ChildNodeName: string;
DefValue: Integer): Integer;
var
Child: TXmlNode;
Code: Integer;
S: string;
begin
Result := DefValue;
Child := Children.NodeByName[ChildNodeName];
if Child <> nil then
begin
S := Child.AsDisplayString;
if not TryStrToInt(S, Result) then
begin
Result := HexStrToInt(S, 8, True, Code);
if Code <> 0 then
Result := DefValue;
end;
end;
end;
function TXmlNode.ChildAsInteger(const ChildNodeName: string;
DefValue: Int64): Int64;
var
Child: TXmlNode;
Code: Integer;
S: string;
begin
Result := DefValue;
Child := Children.NodeByName[ChildNodeName];
if Child <> nil then
begin
S := Child.AsDisplayString;
if not TryStrToInt64(S, Result) then
begin
Result := HexStrToInt(S, 16, True, Code);
if Code <> 0 then
Result := DefValue;
end;
end;
end;
function TXmlNode.ChildAsString(const ChildNodeName: string;
const DefValue: string): string;
var
Child: TXmlNode;
begin
Result := DefValue;
Child := Children.NodeByName[ChildNodeName];
if Child <> nil then
Result := Child.AsDisplayString;
end;
function TXmlNode.CloseTag: string;
begin
Result := '</'+FName+'>';
end;
function TXmlNode.OpenTag: string;
var
I: Integer;
begin
if FAttributes.Count = 0 then
Result := '<' + Name + '>'
else
begin
Result := '<' + Name;
for I := 0 to FAttributes.Count - 1 do
Result := Format('%s %s="%s"',[Result, FAttributes[I].Name, FAttributes[I].Value]);
Result := Result + '>';
end;
end;
procedure TXmlNode.EnumerateNodes(ACallback: TXmlEnumNodeEvent);
var
ICount: integer;
begin
for ICount := 0 to FChildren.Count-1 do
begin
if Assigned(ACallback) then ACallback(Self, FChildren[ICount]);
end;
end;
function TXmlNode.GetAsBoolean: Boolean;
begin
Result := Boolean(StrToInt(FValue));
end;
function TXmlNode.GetAsFloat: Extended;
begin
Result := StrToFloat(FValue);
end;
function TXmlNode.GetAsInteger: integer;
begin
Result := StrToInt(FValue);
end;
function TXmlNode.GetAsHexInt: integer;
var
Code: Integer;
begin
Result := HexStrToInt(FValue, 8, True, Code);
if Code <> 0 then
Error(Format(sParseNumericConvertError, [FValue]));
end;
function TXmlNode.GetAsString: string;
begin
Result := FValue;
end;
function TXmlNode.GetAttribute: TXmlNodeAttribute;
begin
if FAttributes.Count = 0 then
FAttributes.Add(TXmlNodeAttribute.Create);
Result := FAttributes[0];
end;
function TXmlNode.GetLevel: integer;
var
AParent: TXmlNode;
begin
AParent := Parent;
Result := 0;
while AParent <> nil do
begin
AParent := AParent.Parent;
Inc(Result);
end;
end;
procedure TXmlNode.SetAsBoolean(const Value: Boolean);
begin
FValue := IntToStr(Ord(Value));
end;
procedure TXmlNode.SetAsFloat(const Value: Extended);
begin
FValue := FloatToStr(Value);
end;
procedure TXmlNode.SetAsHexInt(AValue: integer);
begin
FValue := IntToHexStr(AValue, 8, '0x', '', False);
end;
procedure TXmlNode.SetAsInteger(const Value: integer);
begin
FValue := IntToStr(Value);
end;
procedure TXmlNode.SetAsString(const Value: string);
begin
FValue := Value;
// replace any illegal characters...
ReplaceText(FValue, '&', '&');
ReplaceText(FValue, '<', '<');
ReplaceText(FValue, '>', '>');
ReplaceText(FValue, '''', ''');
ReplaceText(FValue, '"', '"');
end;
function TXmlNode.GetAsDisplayString: string;
begin
Result := FValue;
// replace any illegal characters...
ReplaceText(Result, '&', '&');
ReplaceText(Result, '<', '<');
ReplaceText(Result, '>', '>');
ReplaceText(Result, ''', '''');
ReplaceText(Result, '"', '"');
ReplaceText(Result, '&pos;', ''''); // backward compatibility
end;
function TXmlNode.GetIsLeafNode: Boolean;
begin
Result := FChildren.Count = 0;
end;
procedure TXmlNode.SetName(Value: string);
var
AElement, AValue: string;
CharPos: Integer;
Attr: TXmlNodeAttribute;
begin
FAttributes.Clear;
FName := Value;
if FName <> '' then
begin
if FName[1] = '<' then Delete(FName, 1, 1);
if FName[Length(FName)] = '>' then Delete(FName, Length(FName), 1);
TrimWhiteSpaces(FName, cLineBreaks + cWordBreaks);
// extract attribute if one exists...
if Pos('=', FName) <> 0 then
begin
AElement := FName;
CharPos := Pos(' ', FName);
FName := Copy(FName, 1, CharPos-1);
Delete(AElement, 1, CharPos);
TrimWhiteSpaces(AElement, cWordBreaks);
while AElement <> '' do
begin
Attr := TXmlNodeAttribute.Create;
CharPos := Pos('=', AElement);
AValue := Copy(AElement, 0, CharPos - 1);
TrimWhiteSpaces(AValue, cWordBreaks);
Attr.Name := AValue;
Delete(AElement, 1, CharPos);
TrimWhiteSpaces(AElement, cWordBreaks);
if AElement <> '' then
begin
if AElement[1] = '"' then
Delete(AElement, 1, 1);
CharPos := Pos('"', AElement);
AValue := Copy(AElement, 1, CharPos - 1);
Attr.Value := AValue;
Delete(AElement, 1, CharPos);
end;
FAttributes.Add(Attr);
end;
end;
end;
end;
//------------------------------------------------------------------------------
// *** TXmlNodeList ***
constructor TXmlNodeList.Create(AParent: TXmlNode);
begin
inherited Create;
FList := TList.Create;
FParent := AParent;
end;
destructor TXmlNodeList.Destroy;
var
ICount: integer;
begin
for ICount := Count-1 downto 0 do
Node[ICount].Free;
FList.Free;
inherited Destroy;
end;
function TXmlNodeList.Add(AName: string): TXmlNode;
begin
Result := TXmlNode.Create(FParent);
Result.Name := AName;
AddNode(Result);
end;
procedure TXmlNodeList.AddNode(ANode: TXmlNode);
begin
FList.Add(ANode);
end;
procedure TXmlNodeList.Assign(Source: TXmlNodeList);
var
I: Integer;
N: TXmlNode;
begin
if Source <> nil then
begin
for I := 0 to Source.Count - 1 do
begin
N := TXmlNode.Create(FParent);
N.Assign(Source.Node[I]);
AddNode(N);
end;
end;
end;
procedure TXmlNodeList.Clear;
var
ICount: integer;
begin
for ICount := 0 to FList.Count-1 do
begin
Node[ICount].Free;
Node[ICount] := nil;
end;
FList.Clear;
end;
procedure TXmlNodeList.DeleteNode(ANode: TXmlNode);
var
I: Integer;
begin
I := FList.IndexOf(ANode);
if I >= 0 then
begin
Node[I].Free;
FList.Delete(I);
end;
end;
function TXmlNodeList.GetCount: integer;
begin
Result := FList.Count;
end;
function TXmlNodeList.GetNode(index: integer): TXmlNode;
begin
Result := TXmlNode(FList[index]);
end;
function TXmlNodeList.GetNodeByName(AName: string): TXmlNode;
var
ICount: integer;
begin
Result := nil;
for ICount := 0 to Count-1 do
begin
if LowerCase(Node[ICount].Name) = LowerCase(AName) then
begin
Result := Node[ICount];
Exit;
end;
end;
end;
procedure TXmlNodeList.SetNodeByName(AName: string; ANode: TXmlNode);
var
ICount: integer;
begin
for ICount := 0 to Count-1 do
begin
if LowerCase(Node[ICount].Name) = LowerCase(AName) then
begin
Node[ICount] := ANode;
Exit;
end;
end;
end;
function TXmlNodeList.GetRoot: TXmlNode;
begin
Result := nil;
if Count > 0 then Result := Node[0];
end;
procedure TXmlNodeList.PeekNode(ANode: TXmlNode);
var
I: Integer;
begin
I := FList.IndexOf(ANode);
if I >= 0 then
FList.Delete(I);
end;
procedure TXmlNodeList.PokeNode(ANode: TXmlNode);
begin
FList.Add(ANode);
end;
procedure TXmlNodeList.SetNode(index: integer; const Value: TXmlNode);
begin
FList[index] := Value;
end;
//------------------------------------------------------------------------------
// *** TXml ***
constructor TXml.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FStrings := TStringList.Create;
FNodes := TXmlNodeList.Create(nil);
FIncludeHeader := True;
FAutoIndent := True;
FEncoding := '';
FLineBreaks := True;
FKeepLineBreaksInValues := True;
end;
destructor TXml.Destroy;
begin
FNodes.Free;
FStrings.Free;
inherited Destroy;
end;
function TXml.GetAbout: string;
begin
Result := Format('%s v%f', [ClassName, COMP_VERSION]);
end;
function TXml.GetDisplayText: string;
begin
Result := GetText(True);
end;
function TXml.GetEncodingStr: string;
begin
Result := '';
if FEncoding <> '' then Result := Format(' encoding="%s"', [FEncoding]);
end;
function TXml.GetIndent(ALevel: integer): string;
begin
Result := '';
if FAutoIndent then Result := StringOfChar(' ', ALevel*2);
end;
function TXml.GetText(ReplaceEscapeChars: Boolean): string;
procedure NodeToStringList(var AXml: TStringList; ANode: TXmlNode; AReplaceChars: Boolean);
var
ICount: integer;
AValue: string;
begin
if ANode.IsLeafNode then
begin
if AReplaceChars then AValue := ANode.AsDisplayString else AValue := ANode.AsString;
AXml.Add(GetIndent(ANode.Level) + ANode.OpenTag + AValue + ANode.CloseTag);
end else
begin
AXml.Add(GetIndent(ANode.Level)+ANode.OpenTag);
for ICount := 0 to ANode.FChildren.Count-1 do
NodeToStringList(AXml, ANode.Children.Node[ICount], AReplaceChars);
AXml.Add(GetIndent(ANode.Level)+ANode.CloseTag);
end;
end;
var
ICount: integer;
begin
FStrings.Clear;
if FNodes.Count = 0 then Exit;
if FIncludeHeader then
FStrings.Add(Format(XML_SPECIFICATION, [GetEncodingStr]));
for ICount := 0 to FNodes.Count-1 do
NodeToStringList(FStrings, FNodes.Node[ICount], ReplaceEscapeChars);
Result := FStrings.Text;
if not FLineBreaks then
Result := StringReplace(Result, cEOL, '', [rfReplaceAll]);
end;
function TXml.GetXmlText: string;
begin
Result := GetText(False);
end;
class function TXml.IsXML(const AText: string; AIncludeHeader: Boolean): Boolean;
const
cMaxBOMSize = 4;
var
ACursor: Integer;
begin
Result := False;
ACursor := 1;
// skip BOM if present
while (ACursor < Length(AText)) and (AText[ACursor] <> '<') and ((ACursor <= cMaxBOMSize) or CharInSetEx(AText[ACursor], cWordBreaks + cLineBreaks)) do
Inc(ACursor);
if (ACursor < Length(AText)) and (AText[ACursor] = '<') then
begin
if AIncludeHeader then
Result := Pos(Copy(XML_SPECIFICATION, 1, 5), AText) = 1
else
begin
// check last non white space character, must be '>'
ACursor := Length(AText);
while (ACursor > 1) and CharInSetEx(AText[ACursor], cWordBreaks + cLineBreaks) do
Dec(ACursor);
Result := AText[ACursor] = '>';
end;
end;
end;
procedure TXml.SetAsText(Value: string);
function NonEmptyValue(const AValue: string): Boolean;
var
I: Integer;
begin
Result := False;
for I := 1 to Length(AValue) do
if not CharInSetEx(AValue[I], cLineBreaks + cWordBreaks) then
begin
Result := True;
Exit;
end;
end;
var
ACursor: integer;
AText: string;
ATag: string;
AValue: string;
ATags: string;
N: TXmlNode;
SingleTag: Boolean;
begin
AText := Value;
ACursor := 1;
ATags := '';
N := nil;
// skip BOM if present
while (ACursor < Length(Value)) and (Value[ACursor] <> '<') do
Inc(ACursor);
while ACursor < Length(Value) do
begin
AValue := '';
if Value[ACursor] = '<' then
begin
// reading a tag
ATag := '<';
while (Value[ACursor] <> '>') and (ACursor < Length(Value)) do
begin
Inc(ACursor);
ATag := ATag + Value[ACursor];
end;
if ATag[2] = '/' then
begin
if N <> nil then
N := N.Parent
else
XmlError(sParseNoOpenTag);
end else
if ATag[2] <> '?' then
begin
SingleTag := ATag[Length(ATag) - 1] = '/';
if SingleTag then
begin
Delete(ATag, Length(ATag) - 1, 1);
if N = nil then
Exit; // XML is empty
end;
if N = nil then
N := Nodes.Add(ATag)
else if SingleTag then
N.Children.Add(ATag)
else
N := N.Children.Add(ATag);
end;
end
else
begin
// reading a value...
while (Value[ACursor] <> '<') and (ACursor < Length(Value)) do
begin
if ((Value[ACursor] <> #13) and (Value[ACursor] <> #10)) or FKeepLineBreaksInValues then
AValue := AValue + Value[ACursor];
Inc(ACursor);
end;
if N <> nil then
N.FValue := AValue
else if NonEmptyValue(AValue) then
XmlError(sParseValueOutSideTag);
Dec(ACursor);
end;
Inc(ACursor);
end;
end;
procedure TXml.SetAbout(Value: string);
begin
// does nothing... (only needed to display property in Object Inspector)
end;
procedure TXml.SetAutoIndent(const Value: Boolean);
begin
FAutoIndent := Value;
end;
procedure TXml.LoadFromFile(AFileName: string);
var
MS: TMemoryStream;
begin
MS := TMemoryStream.Create;
try
MS.LoadFromFile(AFileName);
LoadFromStream(MS);
finally
MS.Free;
end;
end;
procedure TXml.LoadFromStream(Stream: TStream);
var
S: AnsiString;
begin
SetLength(S, Stream.Size);
Stream.Read(S[1], Stream.Size);
Text := UTF8ToString(S);
end;
procedure TXml.SaveToFile(AFilename: string);
var
MS: TMemoryStream;
begin
MS := TMemoryStream.Create;
try
SaveToStream(MS);
MS.SaveToFile(AFileName);
finally
MS.Free;
end;
end;
procedure TXml.SaveToStream(Stream: TStream);
var
S: AnsiString;
begin
S := StringToUTF8(Text);
Stream.Write(S[1], Length(S));
end;
end.
|
unit dll_winmm_mmio;
interface
uses
atmcmbaseconst, winconst, wintype, dll_winmm;
type
{ MMIO data types }
FOURCC = DWORD; { a four character code }
PHMMIO = ^HMMIO;
HMMIO = Integer; { a handle to an open file }
TFNMMIOProc = function(lpmmioinfo: PAnsiChar; uMessage: UINT; lParam1, lParam2: LPARAM): Longint stdcall;
PMMIOInfo = ^TMMIOInfo;
_MMIOINFO = record
{ general fields }
dwFlags: DWORD; { general status flags }
fccIOProc: FOURCC; { pointer to I/O procedure }
pIOProc: TFNMMIOProc; { pointer to I/O procedure }
wErrorRet: UINT; { place for error to be returned }
hTask: HTASK; { alternate local task }
{ fields maintained by MMIO functions during buffered I/O }
cchBuffer: Longint; { size of I/O buffer (or 0L) }
pchBuffer: PAnsiChar; { start of I/O buffer (or NULL) }
pchNext: PAnsiChar; { pointer to next byte to read/write }
pchEndRead: PAnsiChar; { pointer to last valid byte to read }
pchEndWrite: PAnsiChar; { pointer to last byte to write }
lBufOffset: Longint; { disk offset of start of buffer }
{ fields maintained by I/O procedure }
lDiskOffset: Longint; { disk offset of next read or write }
adwInfo: array[0..2] of DWORD; { data specific to type of MMIOPROC }
{ other fields maintained by MMIO }
dwReserved1: DWORD; { reserved for MMIO use }
dwReserved2: DWORD; { reserved for MMIO use }
hmmio: HMMIO; { handle to open file }
end;
TMMIOInfo = _MMIOINFO;
MMIOINFO = _MMIOINFO;
PMMCKInfo = ^TMMCKInfo;
_MMCKINFO = record
ckid: FOURCC; { chunk ID }
cksize: DWORD; { chunk size }
fccType: FOURCC; { form type or list type }
dwDataOffset: DWORD; { offset of data portion of chunk }
dwFlags: DWORD; { flags used by MMIO functions }
end;
TMMCKInfo = _MMCKINFO;
MMCKINFO = _MMCKINFO;
function mmioAdvance(hmmio: HMMIO; lpmmioinfo: PMMIOInfo; uFlags: UINT): MMRESULT; stdcall; external winmm name 'mmioAdvance';
function mmioAscend(hmmio: HMMIO; lpck: PMMCKInfo; uFlags: UINT): MMRESULT; stdcall; external winmm name 'mmioAscend';
function mmioClose(hmmio: HMMIO; uFlags: UINT): MMRESULT; stdcall; external winmm name 'mmioClose';
function mmioCreateChunk(hmmio: HMMIO; lpck: PMMCKInfo; uFlags: UINT): MMRESULT; stdcall; external winmm name 'mmioCreateChunk';
function mmioDescend(hmmio: HMMIO; lpck: PMMCKInfo;
lpckParent: PMMCKInfo; uFlags: UINT): MMRESULT; stdcall; external winmm name 'mmioDescend';
function mmioFlush(hmmio: HMMIO; uFlags: UINT): MMRESULT; stdcall; external winmm name 'mmioFlush';
function mmioGetInfo(hmmio: HMMIO; lpmmioinfo: PMMIOInfo; uFlags: UINT): MMRESULT; stdcall; external winmm name 'mmioGetInfo';
function mmioInstallIOProc(fccIOProc: FOURCC; pIOProc: TFNMMIOProc;
dwFlags: DWORD): TFNMMIOProc; stdcall; external winmm name 'mmioInstallIOProcA';
function mmioOpen(szFileName: PAnsiChar; lpmmioinfo: PMMIOInfo;
dwOpenFlags: DWORD): HMMIO; stdcall; external winmm name 'mmioOpenA';
function mmioRead(hmmio: HMMIO; pch: PAnsiChar; cch: Longint): Longint; stdcall; external winmm name 'mmioRead';
function mmioRename(szFileName, szNewFileName: PAnsiChar;
lpmmioinfo: PMMIOInfo; dwRenameFlags: DWORD): MMRESULT; stdcall; external winmm name 'mmioRenameA';
function mmioSeek(hmmio: HMMIO; lOffset: Longint;
iOrigin: Integer): Longint; stdcall; external winmm name 'mmioSeek';
function mmioSendMessage(hmmio: HMMIO; uMessage: UINT;
lParam1, lParam2: DWORD): Longint; stdcall; external winmm name 'mmioSendMessage';
function mmioSetBuffer(hmmio: HMMIO; pchBuffer: PAnsiChar; cchBuffer: Longint;
uFlags: Word): MMRESULT; stdcall; external winmm name 'mmioSetBuffer';
function mmioSetInfo(hmmio: HMMIO; lpmmioinfo: PMMIOInfo; uFlags: UINT): MMRESULT; stdcall; external winmm name 'mmioSetInfo';
function mmioStringToFOURCC(sz: PAnsiChar; uFlags: UINT): FOURCC; stdcall; external winmm name 'mmioStringToFOURCCA';
function mmioWrite(hmmio: HMMIO; pch: PAnsiChar; cch: Longint): Longint; stdcall; external winmm name 'mmioWrite';
implementation
end.
|
{*******************************************************}
{ }
{ Модуль для скачивания по FTP/HTTP }
{ }
{ Copyright (C) 2018-2019 Witcher }
{ }
{*******************************************************}
unit Downloaders;
interface
uses
Windows, SysUtils, Classes, ftpsend, blcksock, StrUtils, httpsend, Dialogs,
ssl_openssl;
type
TProgressNotifyEvent = procedure(Sender: TObject; Total, Current : Int64; Percent : Byte) of object;
//FTP-менеджер
TFTPMan = class
private
FTPSend : TFTPSend;
FPort: integer;
FPass: string;
FHost: string;
FUser: string;
FLog : TStrings;
FPassive: Boolean;
FConnected: Boolean;
FOnProgress: TProgressNotifyEvent;
FTotalBytes, FCurrentBytes : Int64;
FBinary: Boolean;
FCmdList : TStrings;
procedure SetHost(const Value: string);
procedure SetPass(const Value: string);
procedure SetPort(const Value: integer);
procedure SetUser(const Value: string);
procedure Status(Sender: TObject; Response: Boolean; const Value: string);
procedure DSockStatus(Sender: TObject; Reason: THookSocketReason; const Value: String);
procedure SetPassiveMode(const Value: Boolean);
procedure SetConnected(const Value: Boolean);
function GetFTPList: TFTPList;
procedure SetBinaryMode(const Value: Boolean);
function GetResultCode: integer;
function GetResultString: string;
function GetResumeStatus: Boolean;
function GetServerCommands: TStrings;
protected
procedure DoOnProgress(Total, Value : Int64; Percent : Byte); dynamic;
public
property OnProgress : TProgressNotifyEvent read FOnProgress write FOnProgress;
property Connected : Boolean read FConnected write SetConnected;
property Host : string read FHost write SetHost;
property User : string read FUser write SetUser;
property Password : string read FPass write SetPass;
property Port : integer read FPort write SetPort;
property Passive : Boolean read FPassive write SetPassiveMode;
property Binary : Boolean read FBinary write SetBinaryMode;
property Log : TStrings read FLog;
property FTPList : TFTPList read GetFTPList;
property ResultCode : integer read GetResultCode;
property ResultString : string read GetResultString;
property CanResume : Boolean read GetResumeStatus;
property ServerCommands : TStrings read FCmdList;
function Login : Boolean; overload;
function Login(const AUser, APassword, AHost : string; APort : integer; APassive : Boolean = True) : Boolean; overload;
function Logout : Boolean; overload;
procedure ResetData;
function CurrentDir : string;
function ChangeToParentDir : Boolean;
function ChangeToRoot : Boolean;
function ChangeDir(const Dir : string) : Boolean;
function List(const Dir : string; const NameList : Boolean) : Boolean;
function IsFileExists(const FTPFilename : string) : Boolean;
function Download(const FTPFilename, Filename : string) : Boolean;
function Upload(const Filename, FTPFilename : string) : Boolean;
function RenameFile(const OldName, NewName: string): Boolean;
function DeleteFile(const FileName: string): Boolean;
function DeleteDirectory(const DirName : string) : Boolean;
function CreateDir(const Directory: string): Boolean;
function GetFileSize(const FTPFilename : string) : Int64;
function ExecCommand(const FtpCommand : string) : string;
constructor Create;
destructor Destroy; override;
end;
//HTTP-менеджер
THTTPMan = class
private
FOnProgress: TProgressNotifyEvent;
FFileSize, FDownloaded : int64;
procedure DownloadProgress(Sender: TObject; Reason: THookSocketReason; const Value: string);//Реальный обработчик OnStatus
protected
procedure DoOnProgress(Total, Value : Int64; Percent : Byte); dynamic;
public
constructor Create;
destructor Destroy; override;
function GetSize(URL : string) : Int64; overload;
function GetSize(const URL : string; out ResultCode : integer; out ResultString : string) : Int64; overload;
function GetFile(URL : string) : TMemoryStream; overload;
function GetFile(const URL : string; out ResultCode : integer; out ResultString : string) : TMemoryStream; overload;
function Download(const URL, Filename : string) : Boolean;
property OnProgress : TProgressNotifyEvent read FOnProgress write FOnProgress;
property Downloaded : int64 read FDownloaded;
end;
function FTPd : TFTPMan;
function HTTPd : THTTPMan;
implementation
uses
httpsend_helper, mTools;
var
FtpInstance : TFTPMan;
HttpInstance : THTTPMan;
function FTPd : TFTPMan;
var
newFtpInstance: TFTPMan;
begin
if (FtpInstance = nil) then
begin
newFtpInstance := TFTPMan.Create;
if InterlockedCompareExchangePointer(Pointer(FtpInstance), Pointer(newFtpInstance), nil) <> nil then
FreeAndNil(newFtpInstance);
end;
Result := FtpInstance;
end;
function HTTPd : THTTPMan;
var
newHttpInstance: THTTPMan;
begin
if (HttpInstance = nil) then
begin
newHttpInstance := THTTPMan.Create;
if InterlockedCompareExchangePointer(Pointer(HttpInstance), Pointer(newHttpInstance), nil) <> nil then
FreeAndNil(newHttpInstance);
end;
Result := HttpInstance;
end;
function GetLocalFileSize(const aFilename: String): Int64;
var
info: TWin32FileAttributeData;
begin
result := -1;
if NOT GetFileAttributesEx(PWideChar(aFileName), GetFileExInfoStandard, @info) then
EXIT;
result := Int64(info.nFileSizeLow) or Int64(info.nFileSizeHigh shl 32);
end;
{ TFTP }
function TFTPMan.ChangeDir(const Dir: string): Boolean;
begin
Result := FTPSend.ChangeWorkingDir(Dir);
if Result then FTPSend.List(EmptyStr, False);
end;
function TFTPMan.ChangeToParentDir: Boolean;
begin
Result := FTPSend.ChangeToParentDir;
if Result then FTPSend.List(EmptyStr, False);
end;
function TFTPMan.ChangeToRoot: Boolean;
begin
Result := FTPSend.ChangeToRootDir;
if Result then FTPSend.List(EmptyStr, False);
end;
constructor TFTPMan.Create;
begin
inherited Create;
FTPSend := TFTPSend.Create;
FLog := TStringList.Create;
FTPSend.OnStatus := Status;
FTotalBytes := 0;
FCurrentBytes := 0;
Self.Binary := True;
FCmdList := TStringList.Create;
end;
function TFTPMan.CreateDir(const Directory: string): Boolean;
begin
Result := FTPSend.CreateDir(Directory);
end;
function TFTPMan.CurrentDir: string;
begin
Result := FTPSend.GetCurrentDir;
end;
function TFTPMan.DeleteDirectory(const DirName: string): Boolean;
begin
Result := FTPSend.DeleteDir(DirName);
end;
function TFTPMan.DeleteFile(const FileName: string): Boolean;
begin
Result := FTPSend.DeleteFile(FileName);
end;
destructor TFTPMan.Destroy;
begin
if Assigned(FTPSend) then FreeAndNil(FTPSend);
if Assigned(FLog) then FreeAndNil(FLog);
if Assigned(FCmdList) then FreeAndNil(FCmdList);
inherited;
end;
procedure TFTPMan.DoOnProgress(Total, Value: Int64; Percent: Byte);
begin
if Assigned(FOnProgress) then FOnProgress(Self, Total, Value, Percent);
end;
function TFTPMan.Download(const FTPFilename, Filename: string): Boolean;
begin
FTPSend.DSock.OnStatus := DSockStatus;
FTotalBytes := FTPSend.FileSize(FTPFilename);
FCurrentBytes := 0;
if FTPSend.RetrieveFile(FTPFilename, FTPSend.CanResume) then
begin
//скачивание прошло успешно - сохраняем файл
if FileExists(Filename) then
begin
try
DeleteFile(Filename);
except
Result := False;
Exit;
end;
end;
FTPSend.DataStream.SaveToFile(Filename);
Result := FileExists(Filename);
end
else
begin
//загрузка не удалась - выводим сообщение в лог
FLog.Add('—> Не удалось скачать файл "' + FTPFilename + '"');
Result := False;
end;
FTPSend.DSock.OnStatus := nil;
FCurrentBytes := FTotalBytes;
FTotalBytes := 0;
end;
procedure TFTPMan.DSockStatus(Sender: TObject; Reason: THookSocketReason;
const Value: String);
var
Percent : Byte;
Total : Int64;
Current : integer;
begin
if Reason in [HR_ReadCount, HR_WriteCount] then
begin
Total := FTotalBytes;
Inc(FCurrentBytes, StrToIntDef(Value, 0));
Current := FCurrentBytes;
Percent := round(100 * (Current / Total));
DoOnProgress(Total, Current, Percent);
end;
end;
function TFTPMan.ExecCommand(const FtpCommand: string): string;
begin
Result := EmptyStr;
if FCmdList.Count <= 0 then Exit;
FTPSend.FTPCommand(FtpCommand);
Result := FTPSend.FullResult.Text;
end;
function TFTPMan.GetFileSize(const FTPFilename: string): Int64;
begin
Result := FTPSend.FileSize(FTPFilename);
end;
function TFTPMan.GetFTPList: TFTPList;
begin
Result := FTPSend.FtpList;
end;
function TFTPMan.GetResultCode: integer;
begin
Result := FTPSend.ResultCode;
end;
function TFTPMan.GetResultString: string;
begin
Result := FTPSend.ResultString;
end;
function TFTPMan.GetResumeStatus: Boolean;
begin
Result := FTPSend.CanResume;
end;
function TFTPMan.GetServerCommands: TStrings;
begin
Result := TStringList.Create;
if FTPSend.FTPCommand('HELP')=214 then
begin
FTPSend.FullResult.Delete(0);
FTPSend.FullResult.Delete(FTPSend.FullResult.Count-1);
FCmdList.Clear;
FCmdList.DelimitedText := FTPSend.FullResult.Text;
end;
Result.Assign(FCmdList);
end;
function TFTPMan.IsFileExists(const FTPFilename: string): Boolean;
begin
Result := FTPSend.FileSize(FTPFilename) >= 0;
end;
function TFTPMan.List(const Dir: string; const NameList: Boolean): Boolean;
begin
Result := FTPSend.List(Dir, NameList);
end;
function TFTPMan.Login: Boolean;
begin
FTPSend.UserName := FUser;
FTPSend.Password := FPass;
FTPSend.TargetHost := FHost;
FTPSend.TargetPort := IntToStr(FPort);
FTPSend.PassiveMode := FPassive;
Result := FTPSend.Login;
if Result then
begin
GetServerCommands;
FLog.Add('—> Соединение установлено.');
end
else
FLog.Add('—> Не удалось установить соединение.');
end;
function TFTPMan.Login(const AUser, APassword, AHost: string; APort: integer;
APassive: Boolean): Boolean;
begin
User := AUser;
Password := APassword;
Host := AHost;
Port := APort;
Passive := APassive;
Result := Self.Login;
FConnected := Result;
end;
function TFTPMan.Logout: Boolean;
begin
Result := FTPSend.Logout;
FConnected := not Result;
if Result then
FLog.Add('—> Отключение произведено.')
else
FLog.Add('—> Не удалось прервать соединение.');
end;
function TFTPMan.RenameFile(const OldName, NewName: string): Boolean;
begin
Result := FTPSend.RenameFile(OldName, NewName);
end;
procedure TFTPMan.ResetData;
begin
FTPSend.DataStream.Clear;
end;
procedure TFTPMan.SetBinaryMode(const Value: Boolean);
begin
if Value <> FBinary then
begin
FBinary := Value;
FTPSend.BinaryMode := FBinary;
end;
end;
procedure TFTPMan.SetConnected(const Value: Boolean);
begin
if Value <> FConnected then
begin
if Value then FConnected := Self.Login else FConnected := Self.Logout;
end;
end;
procedure TFTPMan.SetHost(const Value: string);
begin
if FHost <> Value then
FHost := Value;
end;
procedure TFTPMan.SetPass(const Value: string);
begin
if FPass <> Value then
FPass := Value;
end;
procedure TFTPMan.SetPassiveMode(const Value: Boolean);
begin
if Value <> FPassive then
begin
FPassive := Value;
FTPSend.PassiveMode := FPassive;
end;
end;
procedure TFTPMan.SetPort(const Value: integer);
begin
if FPort <> Value then
FPort := Value;
end;
procedure TFTPMan.SetUser(const Value: string);
begin
if FUser <> Value then
FUser := Value;
end;
procedure TFTPMan.Status(Sender: TObject; Response: Boolean; const Value: string);
begin
if Response then
FLog.Add('—> '+Value)
else
begin
if pos('REST', Value) > 0 then
FCurrentBytes := StrToInt64Def(copy(Value,Pos('REST',Value)+5,Length(Value)-Pos('REST',Value)-4),0);
FLog.Add('<— '+Value);
end;
end;
function TFTPMan.Upload(const Filename, FTPFilename: string): Boolean;
begin
Result := False;
if not FileExists(Filename) then Exit;
FTPSend.DataStream.LoadFromFile(FileName);
FTotalBytes := GetLocalFileSize(Filename);
FCurrentBytes := 0;
FTPSend.DSock.OnStatus:=DSockStatus;
Result := FTPSend.StoreFile(ExtractFileName(FTPFilename), FTPd.CanResume);
FTPSend.DSock.OnStatus:=nil;
if Result then
begin
//загрузка прошла успешно - обновляем список объектов
FTPSend.List(EmptyStr,False);
FLog.Add('—> Успешно закачан файл "' + FTPFilename + '"');
end
else
begin
//загрузка не удалась - выводим сообщение в лог
FLog.Add('—> Не удалось закачать файл "' + Filename + '"');
Result := False;
end;
//обнуляем прогресс
FTPSend.DSock.OnStatus := nil;
FCurrentBytes := FTotalBytes;
FTotalBytes := 0;
end;
{ THTTPMan }
constructor THTTPMan.Create;
begin
FFileSize := -1;
FDownloaded := 0;
end;
destructor THTTPMan.Destroy;
begin
inherited;
end;
procedure THTTPMan.DoOnProgress(Total, Value: Int64; Percent: Byte);
begin
if Assigned(FOnProgress) then FOnProgress(Self, Total, Value, Percent);
end;
function THTTPMan.Download(const URL, Filename : string): Boolean;
var
MS : TMemoryStream;
begin
//Скачивание ссылки в файл
MS := TMemoryStream.Create;
MS.Position := 0;
try
MS := GetFile(URL);
try
if FileExists(Filename) then
Result := DeleteFile(Filename);
except
Result := False;
Exit;
end;
MS.SaveToFile(Filename);
Result := FileExists(Filename);
finally
FreeAndNil(MS);
end;
end;
procedure THTTPMan.DownloadProgress(Sender: TObject; Reason: THookSocketReason;
const Value: string);
var
Percent : Byte;
Total : Int64;
Current : integer;
begin
//Обработчик прогресса
if Reason = HR_ReadCount then
begin
Total := FFileSize;
Inc(FDownloaded, StrToIntDef(Value, 0));
Current := FDownloaded;
Percent := Trunc((Current/Total)*100);
DoOnProgress(Total, Current, Percent);
end;
end;
function THTTPMan.GetFile(const URL: string; out ResultCode: integer;
out ResultString: string): TMemoryStream;
var
HTTP : THTTPSend;
ResponseCode : Integer;
ResultStr : string;
begin
FFileSize := GetSize(URL, ResponseCode, ResultStr);
ResultCode := ResponseCode;
ResultString := ResultStr;
Result := nil;
FDownloaded := 0;
if LowerCase(ResultStr) <> 'ok' then Exit; //Ошибка при подсчёте размера файла!
Result := TMemoryStream.Create;
HTTP := THTTPSend.Create;
HTTP.Sock.OnStatus := DownloadProgress;
try
if HTTP.HTTPMethod('GET', URL) then
begin
Result.LoadFromStream(HTTP.Document);
end;
ResultCode := HTTP.ResultCode;
ResultString := HTTP.ResultString;
finally
FreeAndNil(HTTP);
end;
end;
function THTTPMan.GetFile(URL: string): TMemoryStream;
var
HTTP : THTTPSend;
begin
//Получим размер файла
FFileSize := GetSize(URL);
FDownloaded := 0;
HTTP := THTTPSend.Create;
HTTP.Sock.OnStatus := DownloadProgress;
Result := TMemoryStream.Create;
try
if HTTP.HTTPMethod('GET', URL) then
begin
Result.LoadFromStream(HTTP.Document);
Result.Position := 0;
end;
// OK, 200 ShowMessage(Http.ResultString + #13#10 + IntToStr(Http.ResultCode));
finally
FreeAndNil(HTTP);
end;
end;
function THTTPMan.GetSize(const URL: string; out ResultCode: integer;
out ResultString: string): Int64;
var
i, p, p1 : integer;
size, s : string;
ch: char;
HTTP : THTTPSend;
begin
Result := -1;
HTTP := THTTPSend.Create;
try
if HTTP.HTTPMethod('HEAD',URL) then
begin
for I := 0 to HTTP.Headers.Count - 1 do
begin
if pos('content-length',lowercase(HTTP.Headers[i])) > 0 then
begin
size:='';
for ch in HTTP.Headers[i] do
if CharInSet(ch, ['0'..'9']) then
size := size + ch;
if not TryStrToInt64(size, Result) then
Result := 0;//Result + Length(FHTTPSend.Headers.Text);
break;
end;
end;
if Result = -1 then
begin
for i := 0 to HTTP.Headers.Count - 1 do
begin
if pos('content-disposition', LowerCase(HTTP.Headers[i])) > 0 then
begin
p := pos('size=', LowerCase(HTTP.Headers[i]));
if p > 0 then
begin
p1 := PosEx(';', HTTP.Headers[i], p);
if (p1 > 0) and (p1 > p) then
begin
s := copy(HTTP.Headers[i], p, p1 - p);
size := '';
for ch in s do
if CharInSet(ch, ['0'..'9']) then
size := size + ch;
if not TryStrToInt64(size, Result) then Result := -1;
end
else
Result := -1;
end;
end;
end;
end;
end;
ResultCode := HTTP.ResultCode;
ResultString := HTTP.ResultString;
finally
FreeAndNil(HTTP);
end;
end;
function THTTPMan.GetSize(URL: string): Int64;
var
i, p, p1 : integer;
size, s : string;
ch: char;
HTTP : THTTPSend;
begin
Result := -1;
HTTP := THTTPSend.Create;
try
if HTTP.HTTPMethod('HEAD',URL) then
begin
// ShowMessage(HTTP.Headers.Text);
for I := 0 to HTTP.Headers.Count - 1 do
begin
if pos('content-length', LowerCase(HTTP.Headers[i])) > 0 then
begin
size:='';
for ch in HTTP.Headers[i] do
if CharInSet(ch, ['0'..'9']) then
size := size + ch;
if not TryStrToInt64(size, Result) then
Result := -1;//Result + Length(FHTTPSend.Headers.Text);
break;
end;
end;
if Result = -1 then
begin
for i := 0 to HTTP.Headers.Count - 1 do
begin
if pos('content-disposition', LowerCase(HTTP.Headers[i])) > 0 then
begin
p := pos('size=', LowerCase(HTTP.Headers[i]));
if p > 0 then
begin
p1 := PosEx(';', HTTP.Headers[i], p);
if (p1 > 0) and (p1 > p) then
begin
s := copy(HTTP.Headers[i], p, p1 - p);
size := '';
for ch in s do
if CharInSet(ch, ['0'..'9']) then
size := size + ch;
if not TryStrToInt64(size, Result) then Result := -1;
end
else
Result := -1;
end;
end;
end;
end;
end;
finally
FreeAndNil(HTTP);
end;
end;
end.
|
(*----------------------------------------------------------*)
(* Übung 4 ; Beispiel 3 The Missing Element *)
(* Entwickler: Neuhold Michael *)
(* Datum: 31.10.2018 *)
(* Lösungsidee: eingabe von einer Zahlenfolge von n *)
(* Elementen. Herausfinden, was das fehlende *)
(* Element von der Folge n+1 ist. *)
(*----------------------------------------------------------*)
PROGRAM TheMissing;
CONST
max = 100;
TYPE
IntArray = ARRAY[1..max] OF INTEGER;
FUNCTION MissingElement(a: IntArray; n: INTEGER):INTEGER;
VAR
sumReality, sumAll, i : INTEGER;
BEGIN
sumAll := 0;
sumReality := 0;
FOR i := 1 TO (n+1) DO BEGIN
sumAll := sumAll + i;
END;
FOR i := 1 TO n DO BEGIN
sumReality := sumReality + a[i];
END;
MissingElement := sumAll - sumReality;
END;
VAR
arr : IntArray;
n, i : INTEGER;
BEGIN
WriteLn('Wieviele Werte sollen eingelesen werden?');
ReadLn(n);
FOR i := 1 TO n DO BEGIN
Write('Wert', i,': ');
ReadLn(arr[i]);
END;
WriteLn('The Missing Element is: ', MissingElement(arr, n))
END. |
unit UFrameInputCertificate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrameBase, ExtCtrls, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxLabel, jpeg, Buttons,
StdCtrls, UMgrSDTReader;
type
TfFrameInputCertificate = class(TfFrameBase)
PanelClient: TPanel;
Btn1: TSpeedButton;
Btn2: TSpeedButton;
Btn3: TSpeedButton;
Btn4: TSpeedButton;
Btn5: TSpeedButton;
Btn6: TSpeedButton;
Btn7: TSpeedButton;
Btn8: TSpeedButton;
Btn9: TSpeedButton;
BtnEnter: TSpeedButton;
Btn0: TSpeedButton;
BtnDel: TSpeedButton;
EditID: TEdit;
procedure BtnNumClick(Sender: TObject);
procedure EditIDChange(Sender: TObject);
procedure BtnDelClick(Sender: TObject);
procedure EditIDKeyPress(Sender: TObject; var Key: Char);
procedure BtnEnterClick(Sender: TObject);
private
{ Private declarations }
FListA, FListB, FListC: TStrings;
//列表信息
procedure LoadOrderInfo(nID: string);
//加载订单信息
procedure SyncCard(const nCard: TIdCardInfoStr;const nReader: TSDTReaderItem);
public
{ Public declarations }
procedure OnCreateFrame; override;
procedure OnDestroyFrame; override;
procedure OnShowFrame; override;
class function FrameID: integer; override;
function DealCommand(Sender: TObject; const nCmd: Integer;
const nParamA: Pointer; const nParamB: Integer): Integer; override;
{*处理命令*}
end;
var
fFrameInputCertificate: TfFrameInputCertificate;
implementation
{$R *.dfm}
uses
ULibFun, USysLoger, UDataModule, UMgrControl, USelfHelpConst, UBase64,
USysBusiness, UFrameMakeCard, UFormBase;
//------------------------------------------------------------------------------
//Desc: 记录日志
procedure WriteLog(const nEvent: string);
begin
gSysLoger.AddLog(TfFrameInputCertificate, '输入凭证信息', nEvent);
end;
class function TfFrameInputCertificate.FrameID: Integer;
begin
Result := cFI_FrameInputCertificate;
end;
function TfFrameInputCertificate.DealCommand(Sender: TObject; const nCmd: Integer;
const nParamA: Pointer; const nParamB: Integer): Integer;
begin
Result := 0;
if nCmd = cCmd_FrameQuit then
begin
Close;
end;
end;
procedure TfFrameInputCertificate.OnCreateFrame;
begin
DoubleBuffered := True;
FListA := TStringList.Create;
FListB := TStringList.Create;
FListC := TStringList.Create;
end;
procedure TfFrameInputCertificate.OnDestroyFrame;
begin
FListA.Free;
FListB.Free;
FListC.Free;
gSDTReaderManager.OnSDTEvent := nil;
end;
procedure TfFrameInputCertificate.OnShowFrame;
begin
EditID.Text := '';
EditID.SetFocus;
gSDTReaderManager.OnSDTEvent := SyncCard;
end;
procedure TfFrameInputCertificate.BtnNumClick(Sender: TObject);
var nStr: string;
nIdx, nLen: Integer;
begin
inherited;
nStr := EditID.Text;
nIdx := EditID.SelStart;
nLen := EditID.SelLength;
nStr := Copy(nStr, 1, nIdx) + TSpeedButton(Sender).Caption +
Copy(nStr, nIdx + nLen + 1, Length(EditID.Text) - (nIdx + nLen));
EditID.Text := nStr;
EditID.SelStart := nIdx+1;
gTimeCounter := 30;
end;
procedure TfFrameInputCertificate.EditIDChange(Sender: TObject);
var nIdx: Integer;
begin
inherited;
nIdx := EditID.SelStart;
EditID.Text := Trim(EditID.Text);
EditID.SelStart := nIdx;
end;
procedure TfFrameInputCertificate.BtnDelClick(Sender: TObject);
var nIdx, nLen: Integer;
nStr: string;
begin
inherited;
nStr := EditID.Text;
nIdx := EditID.SelStart;
nLen := EditID.SelLength;
if nLen < 1 then
begin
nIdx := nIdx - 1;
nLen := 1;
end;
nStr := Copy(nStr, 1, nIdx) +
Copy(nStr, nIdx + nLen + 1, Length(EditID.Text) - (nIdx + nLen));
EditID.Text := nStr;
EditID.SelStart := nIdx;
gTimeCounter := 30;
end;
procedure TfFrameInputCertificate.EditIDKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
if Key = #13 then
begin
Key := #0;
if Sender = EditID then
begin
BtnEnterClick(nil);
end;
end;
end;
procedure TfFrameInputCertificate.BtnEnterClick(Sender: TObject);
begin
inherited;
BtnEnter.Enabled := False;
try
LoadOrderInfo(EditID.Text);
finally
BtnEnter.Enabled := True;
end;
end;
procedure TfFrameInputCertificate.SyncCard(const nCard: TIdCardInfoStr;
const nReader: TSDTReaderItem);
var nStr: string;
begin
nStr := '读取到身份证信息: [ %s ]=>[ %s.%s ]';
nStr := Format(nStr, [nReader.FID, nCard.FName, nCard.FIdSN]);
WriteLog(nStr);
EditID.Text := nCard.FIdSN;
//BtnEnterClick(nil);
end;
procedure TfFrameInputCertificate.LoadOrderInfo(nID: string);
var nStr: string;
nP: TFormCommandParam;
begin
nStr := Trim(EditID.Text);
if Length(nStr) = 18 then //身份证号
begin
if UpperCase(Copy(nStr, 18, 1))<>GetIDCardNumCheckCode(Copy(nStr, 1, 17)) then
begin
ShowMsg('输入的身份证号非法,请重新输入.', sHint);
Exit;
end;
nStr := GetShopOrderInfoByID(nStr);
if nStr = '' then
begin
nStr := '未查询到身份证号[ %s ]微信订单信息,请检查是否有相关订单号.';
nStr := Format(nStr, [EditID.Text]);
ShowMsg(nStr, sHint);
Writelog(nStr);
Exit;
end;
CreateBaseFrameItem(cFI_FrameReadCardID, Self.Parent)
end else
if Length(nStr) >= 20 then //商城单号
begin
if ShopOrderHasUsed(nStr) then Exit;
nStr := GetShopOrderInfoByNo(nStr);
if nStr = '' then
begin
nStr := '未查询到网上商城订单[ %s ]详细信息,请检查订单号是否正确';
nStr := Format(nStr, [EditID.Text]);
ShowMsg(nStr, sHint);
Exit;
end;
FListA.Clear;
FListB.Clear;
FListA.Text := DecodeBase64(nStr);
FListB.Text := DecodeBase64(FListA[0]);
if FListB.Text = '' then
begin
nStr := '系统未返回网上商城订单[ %s ]详细信息,请联系管理员检查';
nStr := Format(nStr, [EditID.Text]);
ShowMsg(nStr, sHint);
Exit;
end;
nP.FParamA := FListB.Text;
CreateBaseFrameItem(cFI_FrameMakeCard, Self.Parent);
BroadcastFrameCommand(nil, cCmd_MakeCard, @nP);
//宣传订单
end else
begin
ShowMsg('输入信息不全,请重新输入.', sHint);
Exit;
end;
end;
initialization
gControlManager.RegCtrl(TfFrameInputCertificate, TfFrameInputCertificate.FrameID);
end.
|
{******************************************************************************}
{ }
{ Indy (Internet Direct) - Internet Protocols Simplified }
{ }
{ https://www.indyproject.org/ }
{ https://gitter.im/IndySockets/Indy }
{ }
{******************************************************************************}
{ }
{ This file is part of the Indy (Internet Direct) project, and is offered }
{ under the dual-licensing agreement described on the Indy website. }
{ (https://www.indyproject.org/license/) }
{ }
{ Copyright: }
{ (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. }
{ }
{******************************************************************************}
{ }
{ Originally written by: Fabian S. Biehn }
{ fbiehn@aagon.com (German & English) }
{ }
{ Contributers: }
{ Here could be your name }
{ }
{******************************************************************************}
// This File is auto generated!
// Any change to this file should be made in the
// corresponding unit in the folder "intermediate"!
// Generation date: 28.10.2020 15:24:33
unit IdOpenSSLHeaders_hmac;
interface
// Headers for OpenSSL 1.1.1
// hmac.h
{$i IdCompilerDefines.inc}
uses
IdCTypes,
IdGlobal,
IdOpenSSLConsts,
IdOpenSSLHeaders_ossl_typ;
function HMAC_size(const e: PHMAC_CTX): TIdC_SIZET cdecl; external CLibCrypto;
function HMAC_CTX_new: PHMAC_CTX cdecl; external CLibCrypto;
function HMAC_CTX_reset(ctx: PHMAC_CTX): TIdC_INT cdecl; external CLibCrypto;
procedure HMAC_CTX_free(ctx: PHMAC_CTX) cdecl; external CLibCrypto;
function HMAC_Init_ex(ctx: PHMAC_CTX; const key: Pointer; len: TIdC_INT; const md: PEVP_MD; impl: PENGINE): TIdC_INT cdecl; external CLibCrypto;
function HMAC_Update(ctx: PHMAC_CTX; const data: PByte; len: TIdC_SIZET): TIdC_INT cdecl; external CLibCrypto;
function HMAC_Final(ctx: PHMAC_CTX; md: PByte; len: PByte): TIdC_INT cdecl; external CLibCrypto;
function HMAC(const evp_md: PEVP_MD; const key: Pointer; key_len: TIdC_INT; const d: PByte; n: TIdC_SIZET; md: PByte; md_len: PIdC_INT): PByte cdecl; external CLibCrypto;
function HMAC_CTX_copy(dctx: PHMAC_CTX; sctx: PHMAC_CTX): TIdC_INT cdecl; external CLibCrypto;
procedure HMAC_CTX_set_flags(ctx: PHMAC_CTX; flags: TIdC_ULONG) cdecl; external CLibCrypto;
function HMAC_CTX_get_md(const ctx: PHMAC_CTX): PEVP_MD cdecl; external CLibCrypto;
implementation
end.
|
unit Functions;
interface
uses
Winapi.Windows, Winapi.Messages, Winapi.CommCtrl, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.ImgList, Vcl.Menus, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.OleCtrls, SHDocVw, Vcl.ComCtrls, Vcl.Buttons, Winapi.GDIPAPI, Winapi.GDIPOBJ,
VideoConverterInt, SubtitleInt;
var
ApplicationPath: String;
ResourcePath : String;
procedure InitApplication();
function GetDurationString(d: Integer): String;
function GetAVTimeString(t: Int64): String;
function GetDurationProcString(d1, d2: Integer): String;
function IsSupportImage(FileName: String; var Width, Height: Integer): Boolean;
function RoundVideoSize(Value: Integer): Integer;
function MakeHtmlString(Str: String): String;
function GetVersionString(v: Uint64): String;
function GetApplicationVersionValue(): Uint64;
function GetApplicationVersionString(): String;
function GetFontString(Name: String; Size: Integer; Style: Integer): String;
function BGRToTColor(color: ColorRef): TColor;
procedure TColorToBGR(var ref: ColorRef; color: TColor);
implementation
uses
Defines;
function RoundVideoSize(Value: Integer): Integer;
begin
Result := (Value + 15) and (not 15);
end;
procedure InitApplication();
begin
ApplicationPath := ExtractFilePath(Application.ExeName);
ResourcePath := ApplicationPath + 'Resource\';
end;
function GetAVTimeString(t: Int64): String;
var
h, m, s, d: Integer;
begin
t := t div 100000;
d := t mod 10;
t := t div 10;
s := t mod 60;
t := t div 60;
m := t mod 60;
t := t div 60;
h := t;
Result := Format('%d:%.2d:%.2d.%d', [h, m, s, d]);
end;
function GetDurationString(d: Integer): String;
var
h, m, s: Integer;
begin
h := d div 3600;
d := d mod 3600;
m := d div 60;
s := d mod 60;
Result := Format('%d:%.2d:%.2d', [h, m, s]);
end;
function zdgys(x, y: Integer): Integer;
var
n: Integer;
begin
n := y;
if x < y then
begin
y := x;
x := n;
end;
while n > 0 do
begin
n := x mod y;
x := y;
if n > 0 then y := n;
end;
Result := y;
end;
function GetDurationProcString(d1, d2: Integer): String;
begin
Result := GetDurationString(d1) + ' / ' + GetDurationString(d2);
end;
function IsSupportImage(FileName: String; var Width, Height: Integer): Boolean;
var
Image: TGPImage;
begin
Image := TGPImage.Create(FileName);
Result := Image.GetLastStatus() = Winapi.GDIPAPI.Ok;
Width := Image.GetWidth();
Height := Image.GetHeight();
Result := (Result) and (Width <> 0) and (Height <> 0);
Image.Free();
end;
function MakeHtmlString(Str: String): String;
var
i, l: Integer;
s : UTF8String;
begin
Result := '';
s := UTF8String(Str);
l := length(s);
for i := 1 to l do
begin
if (s[i] >= '0') and (s[i] <= '9') then
begin
Result := Result + s[i];
end else if (s[i] >= 'a') and (s[i] <= 'z') then
begin
Result := Result + s[i];
end else if (s[i] >= 'A') and (s[i] <= 'Z') then
begin
Result := Result + s[i];
end else begin
Result := Result + Format('%%%x', [BYTE(s[i])]);
end;
end;
end;
function GetApplicationVersionValue(): Uint64;
var
VerInfoSize : DWORD;
VerInfo : Pointer;
VerValueSize: DWORD;
Dummy : DWORD;
VerValue : PVSFixedFileInfo;
FileName : string;
begin
Result := 0;
FileName := Application.ExeName;
VerInfoSize := GetFileVersionInfoSize(PChar(FileName), Dummy);
if VerInfoSize = 0 then Exit;
GetMem(VerInfo, VerInfoSize);
GetFileVersionInfo(PChar(FileName), 0, VerInfoSize, VerInfo);
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
Result := VerValue^.dwFileVersionMS;
Result := (Result shl 32) + VerValue^.dwFileVersionLS;
FreeMem(VerInfo);
end;
function GetVersionString(v: Uint64): string;
begin
Result := Format('%d.%d.%d.%d', [(v shr 48) and $FFFF, (v shr 32) and $FFFF, (v shr 16) and $FFFF, v and $FFFF]);
end;
function GetApplicationVersionString(): String;
begin
Result := GetVersionString(GetApplicationVersionValue());
end;
function GetFontString(Name: String; Size: Integer; Style: Integer): String;
var
b: Boolean;
begin
Result := 'Font:' + Name + '; Size:' + IntToStr(Size) + '; Style:';
if Style = 0 then
begin
Result := Result + 'Regular.';
end else begin
b := FALSE;
if (Style and FontStyleBold) <> 0 then
begin
Result := Result + 'Bold';
b := TRUE;
end;
if (Style and FontStyleItalic) <> 0 then
begin
if b then Result := Result + ',';
Result := Result + 'Italic';
b := TRUE;
end;
if (Style and FontStyleUnderline) <> 0 then
begin
if b then Result := Result + ',';
Result := Result + 'Underline';
b := TRUE;
end;
if (Style and FontStyleStrikeout) <> 0 then
begin
if b then Result := Result + ',';
Result := Result + 'Strikeout';
b := TRUE;
end;
Result := Result + '.';
end;
end;
function BGRToTColor(color: ColorRef): TColor;
begin
Result := color.R + (color.G shl 8) + (color.b shl 16);
end;
procedure TColorToBGR(var ref: ColorRef; color: TColor);
var
c: ColorRef;
begin
c.Color := ColorToRGB(color);
ref.B := c.R;
ref.G := c.G;
ref.R := c.B;
end;
end.
|
unit Lang;
interface
uses
Types;
type
PModule = ^TModule;
TValueType = (vtBase, vtPair, vtInl, vtInr);
PValue = ^TValue;
TValue = record
_RefCount: Integer;
case vt : TValueType of
vtPair: (Left, Right: PValue);
vtInl, vtInr: (Padding: PValue);
end;
PValueNode =^TValueNode;
TValueNode = record
Next: PValueNode;
Value: PValue;
end;
TFace = (fW, fN, fE, fS);
TInFace = (W, N);
TOutFace = (E, S);
TExprType = (etBase, etPair, etInl, etInr, etInface, etOutface);
PExpr = ^TExpr;
TExpr = record
case et: TExprType of
etPair: (Left, Right: PExpr);
etInl, etInr: (Padding: PExpr);
etInface: (Inface: TInFace);
etOutface: (Outface: TOutFace);
end;
TExprTypeSet = set of TExprType;
TInFaceSet = set of TInFace;
TOutFaceSet = set of TOutFace;
TBlockCommand = (bcSplit, bcSend, bcCase, bcUse);
PBlock = ^TBlock;
PWire = ^TWire;
TBlock = record
Next: PBlock;
LT, RB: TPoint;
N, W, E, S: PWire;
Expr: PExpr;
InFaceSet: TInFaceSet;
UseModuleName: string;
case bc : TBlockCommand of
bcCase: (OutFace1, OutFace2: TOutFace);
bcSend: (Expr2: PExpr);
bcUse: (Module: PModule);
end;
TWire = record
Next: PWire;
Source: PBlock;
Target: PBlock;
Value: PValue;
ValueNode: TValueNode;
SourcePt, TargetPt: TPoint;
SourceFace, TargetFace: TFace;
end;
PWireNode =^TWireNode;
TWireNode = record
Next: PWireNode;
Wire: PWire;
end;
TModule = record
Next: PModule;
bLinked: Boolean;
Name: string;
LT, RB: TPoint;
Depth: Integer;
// for memory management
RootBlock: TBlock;
RootWire: TWire;
// input
N, W: PWire;
// output
OutputWires: TWireNode;
end;
function DisExpr(Expr: PExpr): string;
function DisValue(Value: PValue): string;
function ExprToValue(Expr: PExpr): PValue; overload;
function ExprTypeSet(Expr: PExpr): TExprTypeSet;
function ExprInFaceSet(Expr: PExpr): TInFaceSet;
function ExprOutFaceSet(Expr: PExpr): TOutFaceSet;
procedure ExprPropSet(Expr: PExpr; var TypeSet: TExprTypeSet;
var InFaceSet: TInFaceSet; var OutFaceSet: TOutFaceSet);
procedure DisposeModule(Module: PModule);
procedure DisposeBlock(var Block: PBlock);
procedure DisposeExpr(var Expr: PExpr);
function SizeOfModule(Module: PModule): Integer;
function CaptureValue(Value: PValue): PValue;
procedure ReleaseValue(var Value: PValue);
function UniqueValue(Value: PValue): PValue;
function FindModule(const Name: string): PModule;
procedure GlobalRegisterModule(Module: PModule);
procedure GlobalDisposeModule(Module: PModule);
procedure GlobalEraseAll;
function ExcecuteModule(Module: PModule; Input1, Input2: PValue;
var PrimaryOutput: PValue): Integer;
var
gModule: TModule;
const DirectionedWire: set of Char = ['-', '|', '<', '>', 'v', '^'];
const BlockBolder : set of Char = ['=', '!', '*'];
const WireChar : set of Char = ['-', '|', '<', '>', 'v', '^', '+', '#'];
const HWireChar : set of Char = ['-', '<', '>', '+', '#'];
const VWireChar : set of Char = [ '|', 'v', '^', '+', '#'];
implementation
uses
MiscUtils;
function ExprTypeSet(Expr: PExpr): TExprTypeSet;
procedure Calc(Expr: PExpr; var R: TExprTypeSet);
begin
if Expr = nil then
Exit;
Include(R, Expr.et);
case Expr.et of
etPair: begin
Calc(Expr.Left, R);
Calc(Expr.Right, R);
end;
etInl, etInr: Calc(Expr.Padding, R);
end;
end;
begin
Result := [];
Calc(Expr, Result);
end;
function ExprInFaceSet(Expr: PExpr): TInFaceSet;
procedure Calc(Expr: PExpr; var R: TInFaceSet);
begin
if Expr = nil then
Exit;
if Expr.et = etInface then
Include(R, Expr.Inface);
case Expr.et of
etPair: begin
Calc(Expr.Left, R);
Calc(Expr.Right, R);
end;
etInl, etInr: Calc(Expr.Padding, R);
end;
end;
begin
Result := [];
Calc(Expr, Result);
end;
function ExprOutFaceSet(Expr: PExpr): TOutFaceSet;
procedure Calc(Expr: PExpr; var R: TOutFaceSet);
begin
if Expr = nil then
Exit;
if Expr.et = etOutface then
Include(R, Expr.Outface);
case Expr.et of
etPair: begin
Calc(Expr.Left, R);
Calc(Expr.Right, R);
end;
etInl, etInr: Calc(Expr.Padding, R);
end;
end;
begin
Result := [];
Calc(Expr, Result);
end;
procedure ExprPropSet(Expr: PExpr; var TypeSet: TExprTypeSet;
var InFaceSet: TInFaceSet; var OutFaceSet: TOutFaceSet);
procedure Calc(Expr: PExpr);
begin
if Expr = nil then
Exit;
Include(TypeSet, Expr.et);
if Expr.et = etInface then
Include(InFaceSet, Expr.Inface);
if Expr.et = etOutface then
Include(OutFaceSet, Expr.Outface);
case Expr.et of
etPair: begin
Calc(Expr.Left);
Calc(Expr.Right);
end;
etInl, etInr: Calc(Expr.Padding);
end;
end;
begin
TypeSet := [];
InFaceSet := [];
OutFaceSet := [];
Calc(Expr);
end;
function DisExpr(Expr: PExpr): string;
begin
if Expr = nil then
begin
Result := 'nil';
Exit;
end;
Result := '?';
case Expr.et of
etBase: Result := '()';
etPair: Result := '(' + DisExpr(Expr.Left) + ', ' + DisExpr(Expr.Right) + ')';
etInl : Result := 'Inl ' + DisExpr(Expr.Padding);
etInr : Result := 'Inr ' + DisExpr(Expr.Padding);
etInface:
case Expr.Inface of
W: Result := 'W';
N: Result := 'N';
end;
etOutface:
case Expr.Outface of
E: Result := 'E';
S: Result := 'S';
end;
end;
end;
function DisValue(Value: PValue): string;
begin
if Value = nil then
begin
Result := 'nil';
Exit;
end;
Result := '?';
case Value.vt of
vtBase: Result := '()';
vtPair: Result := '(' + DisValue(Value.Left) + ', ' + DisValue(Value.Right) + ')';
vtInl : Result := 'Inl ' + DisValue(Value.Padding);
vtInr : Result := 'Inr ' + DisValue(Value.Padding);
end;
end;
procedure DisposeBlock(var Block: PBlock);
begin
DisposeExpr(Block.Expr);
if Block.bc = bcSend then
DisposeExpr(Block.Expr2);
Block.Expr := nil;
Block.Expr2 := nil;
end;
procedure DisposeExpr(var Expr: PExpr);
begin
if Expr = nil then
Exit;
case Expr.et of
etPair:
begin
DisposeExpr(Expr.Left);
DisposeExpr(Expr.Right);
end;
etInl, etInr:
begin
DisposeExpr(Expr.Padding);
end;
end;
Dispose(Expr);
Expr := nil;
end;
function FindModule(const Name: string): PModule;
begin
Result := gModule.Next;
while Result <> nil do
begin
if Result.Name = Name then
Break
else
Result := Result.Next;
end;
end;
function CaptureValue(Value: PValue): PValue;
begin
Result := Value;
if Value <> nil then
begin
// Log('++ref @%p, %s', [Value, DisValue(Value)]);
Inc(Value._RefCount);
end;
end;
procedure ReleaseValue(var Value: PValue);
begin
if Value = nil then
Exit;
//Log('--ref @%p --> %d, %s', [Value, Value._RefCount - 1, DisValue(Value)]);
Dec(Value._RefCount);
if Value._RefCount <= 0 then
begin
case Value.vt of
vtPair:
begin
ReleaseValue(Value.Left);
ReleaseValue(Value.Right);
end;
vtInl, vtInr:
begin
ReleaseValue(Value.Padding);
end;
end;
// LogWarning('mm: dispose data @%p', [Value]);
Dispose(Value);
Value := nil;
end;
Value := nil;
end;
function ExprToValue(Expr: PExpr): PValue; overload;
procedure ExprToV(Expr: PExpr; var P: PValue);
begin
New(P);
// Log('new value @%p', [P]);
FillChar(P^, SizeOf(P^), 0);
P.vt := vtBase;
if Expr = nil then
Exit;
case Expr.et of
etPair:
begin
P.vt := vtPair;
ExprToV(Expr.Left, P.Left);
ExprToV(Expr.Right, P.Right);
CaptureValue(P.Left);
CaptureValue(P.Right);
end;
etInl, etInr:
begin
if Expr.et = etInl then
P.vt := vtInl
else
P.vt := vtInr;
ExprToV(Expr.Padding, P.Padding);
CaptureValue(P.Padding);
end;
etBase: P.vt := vtBase;
else
LogError('expression "%s" cannot be evaluated at present.', [DisExpr(Expr)]);
end;
end;
begin
Result := nil;
if Expr <> nil then
ExprToV(Expr, Result);
end;
function ExprToValue(Expr: PExpr; N, W: PValue): PValue; overload;
procedure ExprToV(Expr: PExpr; var P: PValue);
begin
if Expr.et <> etInface then
begin
New(P);
// Log('new value @%p', [P]);
FillChar(P^, SizeOf(P^), 0);
P.vt := vtBase;
end;
case Expr.et of
etPair:
begin
P.vt := vtPair;
ExprToV(Expr.Left, P.Left);
ExprToV(Expr.Right, P.Right);
CaptureValue(P.Left);
CaptureValue(P.Right);
end;
etInl, etInr:
begin
if Expr.et = etInl then
P.vt := vtInl
else
P.vt := vtInr;
ExprToV(Expr.Padding, P.Padding);
CaptureValue(P.Padding);
end;
etBase: P.vt := vtBase;
etInface:
begin
case Expr.Inface of
Lang.N: P := N;
Lang.W: P := W;
end;
end;
else
LogError('expression "%s" cannot be evaluated at present.', [DisExpr(Expr)]);
end;
end;
begin
Result := nil;
if Expr <> nil then
ExprToV(Expr, Result);
end;
function UniqueValue(Value: PValue): PValue;
begin
Result := nil;
end;
function LinkModules(Module: PModule): Integer;
var
PB: PBlock;
PM: PModule;
begin
Result := 0;
PB := Module.RootBlock.Next;
Module.bLinked := True;
while PB <> nil do
begin
if PB.bc = bcUse then
begin
PB.Module := FindModule(PB.UseModuleName);
if PB.Module <> nil then
begin
Log('"%s" in module "%s" linked.', [PB.UseModuleName, Module.Name]);
end
else begin
// LogError('"%s" link failed.', [PB.UseModuleName]);
Module.bLinked := False;
end;
end;
PB := PB.Next;
end;
PM := gModule.Next;
while PM <> nil do
begin
if (not PM.bLinked) and (PM <> Module) then
begin
PB := PM.RootBlock.Next;
PM.bLinked := True;
while PB <> nil do
begin
if PB.bc = bcUse then
begin
if PB.UseModuleName = Module.Name then
begin
PB.Module := Module;
Log('"%s" in module "%s" linked.', [PB.UseModuleName, PM.Name])
end
else if PB.Module = nil then
PM.bLinked := False
else;
end;
PB := PB.Next;
end;
end;
PM := PM.Next;
end;
end;
procedure GlobalRegisterModule(Module: PModule);
var
P: PModule;
begin
P := FindModule(Module.Name);
if P <> nil then
begin
LogWarning('updating module "%s"', [Module.Name]);
GlobalDisposeModule(P);
end;
// add Module to the list
Module.Next := gModule.Next;
gModule.Next := Module;
LinkModules(Module);
end;
procedure GlobalDisposeModule(Module: PModule);
var
P: PModule;
B: PBlock;
begin
// release the references to this module
P := gModule.Next;
while P <> nil do
begin
B := P.RootBlock.Next;
while B <> nil do
begin
if (B.bc = bcUse) and (B.Module = Module) then
begin
B.Module := nil;
P.bLinked := False;
end;
B := B.Next;
end;
P := P.Next;
end;
P := @gModule;
while (p <> nil) and (P.Next <> Module) do
P := P.Next;
if p <> nil then
begin
P.Next := Module.Next;
DisposeModule(Module);
Dispose(Module);
end
else
LogError('module "%s" not find in global list.', [Module.Name]);
end;
procedure GlobalEraseAll;
var
Module: PModule;
begin
while gModule.Next <> nil do
begin
Module := gModule.Next;
gModule.Next := Module.Next;
DisposeModule(Module);
Dispose(Module);
end;
end;
function SizeOfStr(const s: string): Integer;
begin
Result := Length(s) + SizeOf(Integer);
end;
function SizeOfBlocks(Module: PModule): Integer;
var
pb: PBlock;
begin
pb := Module.RootBlock.Next;
Result := 0;
while pb <> nil do
begin
Inc(Result, SizeOf(pb^) + SizeOfStr(pb.UseModuleName));
pb := pb.Next;
end;
end;
function SizeOfValue(Value: PValue): Integer;
begin
Result := 0;
if Value <> nil then
case Value.vt of
vtPair:
Result := SizeOf(Value^) + SizeOfValue(Value.Left) + SizeOfValue(Value.Right);
vtInl, vtInr:
Result := SizeOf(Value^) + SizeOfValue(Value.Padding);
end;
end;
function SizeOfValueNode(ValueNode: PValueNode): Integer;
var
P: PValueNode;
begin
P := ValueNode;
Result := 0;
while P <> nil do
begin
Inc(Result, SizeOfValue(P.Value));
P := P.Next;
end;
end;
function SizeOfWires(Module: PModule): Integer;
var
pw: PWire;
begin
pw := Module.RootWire.Next;
Result := 0;
while pw <> nil do
begin
Inc(Result, SizeOf(pw^) + SizeOfValueNode(pw.ValueNode.Next));
pw := pw.Next;
end;
end;
function SizeOfOutputWires(Module: PModule): Integer;
var
pwn: PWireNode;
begin
pwn := Module.OutputWires.Next;
Result := 0;
while pwn <> nil do
begin
Inc(Result, SizeOf(pwn^));
pwn := pwn.Next;
end;
end;
function SizeOfModule(Module: PModule): Integer;
begin
Result := 0;
if Module <> nil then
Result := SizeOf(Module^) + SizeOfBlocks(Module) + SizeOfWires(Module)
+ SizeOfOutputWires(Module)
+ SizeOfStr(Module.Name);
end;
function NewModuleInstance(Module: PModule): Integer;
var
PW: PWire;
PVN: PValueNode;
begin
Result := 0;
if Module = nil then
Exit;
Inc(Module.Depth);
PW := Module.RootWire.Next;
while PW <> nil do
begin
New(PVN);
PVN.Next := PW.ValueNode.Next;
PW.ValueNode.Next := PVN;
PVN.Value := PW.Value; // no reference count issue here
PW.Value := nil;
PW := PW.Next;
end;
Result := Module.Depth;
end;
function DisposeModuleInstance(Module: PModule): Integer;
var
PW: PWire;
PVN: PValueNode;
begin
//LogWarning('DisposeModuleInstance module "%s".', [Module.Name]);
Result := 0;
if Module = nil then
Exit;
Dec(Module.Depth);
if Module.Depth < 0 then
begin
LogWarning('module "%s" may not has any instance.', [Module.Name]);
Module.Depth := 0;
end;
Result := Module.Depth;
PW := Module.RootWire.Next;
while PW <> nil do
begin
ReleaseValue(PW.Value);
PVN := PW.ValueNode.Next;
if PVN <> nil then
begin
PW.ValueNode.Next := PVN.Next;
PW.Value := PVN.Value;
Dispose(PVN);
end;
PW := PW.Next;
end;
end;
procedure DisposeModule(Module: PModule);
var
pw: PWire;
pb: PBlock;
pwn: PWireNode;
begin
// free instances
while Module.Depth > 0 do
DisposeModuleInstance(Module);
while Module.RootWire.Next <> nil do
begin
pw := Module.RootWire.Next;
Module.RootWire.Next := pw.Next;
Dispose(pw);
end;
while Module.OutputWires.Next <> nil do
begin
pwn := Module.OutputWires.Next;
Module.OutputWires.Next := pwn.Next;
Dispose(pwn);
end;
while Module.RootBlock.Next <> nil do
begin
pb := Module.RootBlock.Next;
Module.RootBlock.Next := pb.Next;
DisposeBlock(pb);
Dispose(pb);
end;
end;
procedure ChangeWireCapture(var P: PWire; NewValue: PValue);
begin
if Assigned(P) then
begin
if Assigned(P.Value) then ReleaseValue(P.Value);
P.Value := CaptureValue(NewValue);
end
else
P := nil;
end;
function ExcecuteModule(Module: PModule; Input1, Input2: PValue;
var PrimaryOutput: PValue): Integer;
var
bRun, bErr: Boolean;
PB: PBlock;
PV, PV1, PV2: PValue;
InfaceSet: TInfaceSet;
SubOutput: PValue;
procedure CheckModuleOutput(PW: PWire);
begin
if (PrimaryOutput = nil) and Assigned(PW) and (PW.Target = nil) and (PW.Value <> nil) then
begin
// transfer the reference
PrimaryOutput := PW.Value;
PW.Value := nil;
end;
end;
label
next, quit;
begin
if not Module.bLinked then
begin
LogError('some USE blocks in module "%s" have not been linked.', [Module.Name]);
Result := -1;
Exit;
end;
if NewModuleInstance(Module) > 32 then
begin
DisposeModuleInstance(Module);
LogError('too many instance of module "%s" hava been created.', [Module.Name]);
Result := -1;
Exit;
end;
if Module.N <> nil then
Module.N.Value := CaptureValue(Input1);
if Module.W <> nil then
Module.W.Value := CaptureValue(Input2);
Result := 0;
bRun := True;
bErr := False;
while bRun and (not bErr) and (not Assigned(PrimaryOutput)) do
begin
bRun := False;
PB := Module.RootBlock.Next;
while PB <> nil do
begin
if (PB.N <> nil) and (not Assigned(PB.N.Value)) then
goto next;
if (PB.W <> nil) and (not Assigned(PB.W.Value)) then
goto next;
PV1 := nil;
PV2 := nil;
if PB.N <> nil then
PV1 := PB.N.Value;
if PB.W <> nil then
PV2 := PB.W.Value;
// now execute
case PB.bc of
bcSplit:
begin
InfaceSet := [];
if PB.N <> nil then
Include(InfaceSet, N);
if PB.W <> nil then
Include(InfaceSet, W);
if (InfaceSet * PB.InFaceSet) = PB.InFaceSet then
begin
PV := ExprToValue(PB.Expr, PV1, PV2);
if PV.vt = vtPair then
begin
ChangeWireCapture(PB.S, PV.Left);
ChangeWireCapture(PB.E, PV.Right);
CheckModuleOutput(PB.S);
CheckModuleOutput(PB.E);
end
else begin
LogError('SPLIT needs a PAIR expression.', []);
bErr := True;
end;
bRun := True;
end;
end;
bcSend:
begin
InfaceSet := [];
if PB.N <> nil then
Include(InfaceSet, N);
if PB.W <> nil then
Include(InfaceSet, W);
if (InfaceSet * PB.InFaceSet) = PB.InFaceSet then
begin
PV := ExprToValue(PB.Expr.Left, PV1, PV2);
case PB.Expr.Right.Outface of
E: begin
ChangeWireCapture(PB.E, PV);
CheckModuleOutput(PB.E);
end;
S: begin
ChangeWireCapture(PB.S, PV);
CheckModuleOutput(PB.S);
end;
else
ReleaseValue(PV);
end;
if PB.Expr2 <> nil then
begin
PV := ExprToValue(PB.Expr2.Left, PV1, PV2);
case PB.Expr2.Right.Outface of
E: begin
ChangeWireCapture(PB.E, PV);
CheckModuleOutput(PB.E);
end;
S: begin
ChangeWireCapture(PB.S, PV);
CheckModuleOutput(PB.S);
end;
else
ReleaseValue(PV);
end;
end;
bRun := True;
end;
end;
bcCase:
begin
InfaceSet := [];
if PB.N <> nil then
Include(InfaceSet, N);
if PB.W <> nil then
Include(InfaceSet, W);
if (InfaceSet * PB.InFaceSet) = PB.InFaceSet then
begin
if PV1 <> nil then
PV := PV1
else
PV := PV2;
case PV.vt of
vtInl: if PB.OutFace1 = S then
begin
ChangeWireCapture(PB.S, PV.Padding);
CheckModuleOutput(PB.S);
end
else begin
ChangeWireCapture(PB.E, PV.Padding);
CheckModuleOutput(PB.E);
end;
vtInr: if PB.OutFace2 = S then
begin
ChangeWireCapture(PB.S, PV.Padding);
CheckModuleOutput(PB.S);
end
else begin
ChangeWireCapture(PB.E, PV.Padding);
CheckModuleOutput(PB.E);
end;
else
LogWarning('CASE generates nothing.', []);
// LogError('CASE needs a Inr or Inl expression.', []);
// bErr := True;
end;
bRun := True;
end;
end;
bcUse:
begin
Log('use "%s", N = %s, W = %s', [PB.UseModuleName, DisValue(PV1), DisValue(PV2)]);
SubOutput := nil;
ExcecuteModule(PB.Module, PV1, PV2, SubOutput);
if PB.S <> nil then
begin
// transfer the reference
PB.S.Value := SubOutput;
SubOutput := nil;
CheckModuleOutput(PB.S);
end
else if PB.E <> nil then
begin
// transfer the reference
PB.E.Value := SubOutput;
SubOutput := nil;
CheckModuleOutput(PB.E);
end
else
ReleaseValue(PrimaryOutput);
bRun := True;
end;
else
LogError('command not implemented', []);
end;
if bRun then
begin
// release input
if PB.N <> nil then
ReleaseValue(PB.N.Value);
if PB.W <> nil then
ReleaseValue(PB.W.Value);
end;
next:
PB := PB.Next;
end;
end;
quit:
if Module.N <> nil then
ReleaseValue(Module.N.Value);
if Module.W <> nil then
ReleaseValue(Module.W.Value);
// if Module.FirstOutput <> nil then
// ChangeWireCapture(PrimaryOutput, Module.FirstOutput.Value);
DisposeModuleInstance(Module);
end;
end.
|
(*-----------------------------------------------------------*)
(* Developer: Neuhold Michael *)
(* date: 16.11.2018 *)
(* check if number is element of array *)
(* with $B+ and $B- *)
(*-----------------------------------------------------------*)
PROGRAM SequentielleSuche;
CONST
max = 10;
TYPE
Arr = ARRAY[1..max] OF INTEGER;
(* Find Element in Array with sequential search *)
FUNCTION IsElement(a: ARRAY OF INTEGER; x: INTEGER): BOOLEAN;
VAR
i: INTEGER;
BEGIN
i := 0;
WHILE (i <= High(a)) AND (a[i] <> x) DO BEGIN
i := i + 1;
END;
IsElement := (i <= High(a));
END;
VAR
a: Arr;
n, i, search: INTEGER;
BEGIN
FOR i := 1 TO 10 DO BEGIN
a[i] := i;
END;
WriteLn('Welches Element soll gesucht werden?');
ReadLn(search);
WriteLn('Gefunden: ', IsElement(a,search));
END. |
unit AqDrop.Core.Generics.Converters;
interface
uses
System.SysUtils,
System.TypInfo,
System.Rtti,
AqDrop.Core.Collections.Intf;
type
TAqTypeConverter = class
strict protected
function DoExecute(const pFrom: TValue): TValue; virtual; abstract;
public
function Execute(const pFrom: TValue): TValue;
end;
TAqTypeConverterByMethod<TFrom, TTo> = class(TAqTypeConverter)
strict private
FConverter: TFunc<TFrom, TTo>;
strict protected
function DoExecute(const pFrom: TValue): TValue; override;
public
constructor Create(const pConverter: TFunc<TFrom, TTo>);
end;
TAqTypeConverters = class
strict private
FConverters: IAqDictionary<string, TAqTypeConverter>;
function GetStrTypeInfo(pType: PTypeInfo): string;
function GetDictionaryKey(const pFromType, pToType: PTypeInfo): string; overload;
function GetDictionaryKey<TFrom, TTo>: string; overload;
class var FDefaultInstance: TAqTypeConverters;
class function GetDefaultInstance: TAqTypeConverters; static;
public
constructor Create;
procedure RegisterConverter<TFrom, TTo>(const pConverter: TFunc<TFrom, TTo>);
function HasConverter(const pFromType, pToType: PTypeInfo): Boolean; overload;
function HasConverter<TFrom, TTo>: Boolean; overload;
function HasConverter<TTo>(const pFrom: TValue): Boolean; overload;
function TryConvert(const pFrom: TValue; const pToType: PTypeInfo; out pValue: TValue): Boolean; overload;
function TryConvert<TTo>(const pFrom: TValue; out pValue: TTo): Boolean; overload;
function TryConvert<TFrom, TTo>(const pFrom: TFrom; out pValue: TTo): Boolean; overload;
function Convert(const pFrom: TValue; const pToType: PTypeInfo): TValue; overload;
function Convert<TTo>(const pFrom: TValue): TTo; overload;
function Convert<TFrom, TTo>(const pFrom: TFrom): TTo; overload;
{$region 'register standard converters'}
procedure RegisterConvertersFromString;
procedure RegisterConvertersFromBoolean;
procedure RegisterConvertersFromUInt8;
procedure RegisterConvertersFromInt8;
procedure RegisterConvertersFromUInt16;
procedure RegisterConvertersFromInt16;
procedure RegisterConvertersFromUInt32;
procedure RegisterConvertersFromInt32;
procedure RegisterConvertersFromUInt64;
procedure RegisterConvertersFromInt64;
procedure RegisterConvertersFromEntityID;
procedure RegisterConvertersFromDouble;
procedure RegisterConvertersFromCurrency;
procedure RegisterConvertersFromDateTime;
procedure RegisterConvertersFromDate;
procedure RegisterConvertersFromTime;
procedure RegisterMinorStandarConverters;
procedure RegisterStandardConverters;
{$endregion}
class procedure InitializeDefaultInstance;
class procedure ReleaseDefaultInstance;
class property Default: TAqTypeConverters read GetDefaultInstance;
end;
implementation
uses
System.Math,
System.StrUtils,
System.Variants,
AqDrop.Core.Types,
AqDrop.Core.Exceptions,
AqDrop.Core.Collections,
AqDrop.Core.Helpers;
{ TAqTypeConverter }
function TAqTypeConverter.Execute(const pFrom: TValue): TValue;
begin
Result := DoExecute(pFrom);
end;
{ TAqTypeConverters }
function TAqTypeConverters.Convert(const pFrom: TValue; const pToType: PTypeInfo): TValue;
begin
if not TryConvert(pFrom, pToType, Result) then
begin
raise EAqInternal.CreateFmt('Converter not found (%s := %s).', [
GetTypeName(pToType),
GetTypeName(pFrom.TypeInfo)]);
end;
end;
function TAqTypeConverters.Convert<TFrom, TTo>(const pFrom: TFrom): TTo;
begin
Result := Convert<TTo>(TValue.From<TFrom>(pFrom));
end;
function TAqTypeConverters.Convert<TTo>(const pFrom: TValue): TTo;
begin
Result := Convert(pFrom, TypeInfo(TTo)).AsType<TTo>;
end;
constructor TAqTypeConverters.Create;
begin
FConverters := TAqDictionary<string, TAqTypeConverter>.Create([kvoValue], TAqLockerType.lktMultiReaderExclusiveWriter);
end;
class function TAqTypeConverters.GetDefaultInstance: TAqTypeConverters;
begin
InitializeDefaultInstance;
Result := FDefaultInstance;
end;
function TAqTypeConverters.GetDictionaryKey(const pFromType, pToType: PTypeInfo): string;
begin
Result := GetStrTypeInfo(pFromType) + '|' + GetStrTypeInfo(pToType);
end;
function TAqTypeConverters.GetDictionaryKey<TFrom, TTo>: string;
begin
Result := GetDictionaryKey(TypeInfo(TFrom), TypeInfo(TTo));
end;
function TAqTypeConverters.GetStrTypeInfo(pType: PTypeInfo): string;
begin
Result := IntToHex(NativeInt(pType), 2);
end;
function TAqTypeConverters.HasConverter(const pFromType, pToType: PTypeInfo): Boolean;
begin
Result := FConverters.LockAndCheckIfContainsKey(GetDictionaryKey(pFromType, pToType));
end;
function TAqTypeConverters.HasConverter<TFrom, TTo>: Boolean;
begin
Result := HasConverter(TypeInfo(TFrom), TypeInfo(TTo));
end;
function TAqTypeConverters.HasConverter<TTo>(const pFrom: TValue): Boolean;
begin
Result := HasConverter(pFrom.TypeInfo, TypeInfo(TTo));
end;
class procedure TAqTypeConverters.InitializeDefaultInstance;
begin
if not Assigned(FDefaultInstance) then
begin
FDefaultInstance := TAqTypeConverters.Create;
end;
end;
procedure TAqTypeConverters.RegisterConverter<TFrom, TTo>(const pConverter: TFunc<TFrom, TTo>);
begin
FConverters.LockAndAddOrSetValue(GetDictionaryKey<TFrom, TTo>,
TAqTypeConverterByMethod<TFrom,TTo>.Create(pConverter));
end;
procedure TAqTypeConverters.RegisterConvertersFromBoolean;
begin
RegisterConverter<Boolean, string>(
function(pValue: Boolean): string
begin
Result := pValue.ToString;
end);
RegisterConverter<Boolean, Boolean>(
function(pValue: Boolean): Boolean
begin
Result := pValue;
end);
RegisterConverter<Boolean, UInt8>(
function(pValue: Boolean): UInt8
begin
Result := pValue.ToInt8;
end);
RegisterConverter<Boolean, Int8>(
function(pValue: Boolean): Int8
begin
Result := pValue.ToInt8;
end);
RegisterConverter<Boolean, UInt16>(
function(pValue: Boolean): UInt16
begin
Result := pValue.ToInt8;
end);
RegisterConverter<Boolean, Int16>(
function(pValue: Boolean): Int16
begin
Result := pValue.ToInt8;
end);
RegisterConverter<Boolean, UInt32>(
function(pValue: Boolean): UInt32
begin
Result := pValue.ToInt32;
end);
RegisterConverter<Boolean, Int32>(
function(pValue: Boolean): Int32
begin
Result := pValue.ToInt32;
end);
RegisterConverter<Boolean, UInt64>(
function(pValue: Boolean): UInt64
begin
Result := pValue.ToInt32;
end);
RegisterConverter<Boolean, Int64>(
function(pValue: Boolean): Int64
begin
Result := pValue.ToInt32;
end);
RegisterConverter<Boolean, TAqEntityID>(
function(pValue: Boolean): TAqEntityID
begin
Result := pValue.ToInt32;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromCurrency;
begin
RegisterConverter<Currency, string>(
function(pValue: Currency): string
begin
{$IF CompilerVersion >= 29} // bug no XE7
Result := pValue.ToString;
{$ELSE}
Result := CurrToStr(pValue);
{$ENDIF}
end);
RegisterConverter<Currency, UInt8>(
function(pValue: Currency): UInt8
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Currency, Int8>(
function(pValue: Currency): Int8
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Currency, UInt16>(
function(pValue: Currency): UInt16
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Currency, Int16>(
function(pValue: Currency): Int16
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Currency, UInt32>(
function(pValue: Currency): UInt32
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Currency, Int32>(
function(pValue: Currency): Int32
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Currency, UInt64>(
function(pValue: Currency): UInt64
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Currency, Int64>(
function(pValue: Currency): Int64
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Currency, TAqEntityID>(
function(pValue: Currency): TAqEntityID
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Currency, Double>(
function(pValue: Currency): Double
begin
Result := pValue;
end);
RegisterConverter<Currency, Currency>(
function(pValue: Currency): Currency
begin
Result := pValue;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromDate;
begin
RegisterConverter<TDate, string>(
function(pValue: TDate): string
begin
{$IF CompilerVersion >= 29} // bug no XE7
Result := pValue.ToString;
{$ELSE}
Result := DateToStr(pValue);
{$ENDIF}
end);
RegisterConverter<TDate, Double>(
function(pValue: TDate): Double
begin
Result := pValue;
end);
RegisterConverter<TDate, TDateTime>(
function(pValue: TDate): TDateTime
begin
Result := pValue;
end);
RegisterConverter<TDate, TDate>(
function(pValue: TDate): TDate
begin
Result := pValue;
end);
RegisterConverter<TDate, Variant>(
function(pValue: TDate): Variant
begin
if pValue = 0 then
begin
Result := System.Variants.Null;
end else
begin
Result := pValue;
end;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromDateTime;
begin
RegisterConverter<TDateTime, string>(
function(pValue: TDateTime): string
begin
{$IF CompilerVersion >= 29} // bug no XE7
Result := pValue.ToString;
{$ELSE}
Result := DateTimeToStr(pValue);
{$ENDIF}
end);
RegisterConverter<TDateTime, Double>(
function(pValue: TDateTime): Double
begin
Result := pValue;
end);
RegisterConverter<TDateTime, TDateTime>(
function(pValue: TDateTime): TDateTime
begin
Result := pValue;
end);
RegisterConverter<TDateTime, TDate>(
function(pValue: TDateTime): TDate
begin
{$IF CompilerVersion >= 29}
Result := pValue.DateOf;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<TDateTime, TTime>(
function(pValue: TDateTime): TTime
begin
{$IF CompilerVersion >= 29}
Result := pValue.TimeOf;
{$ELSE}
Result := System.Frac(pValue);
{$ENDIF}
end);
RegisterConverter<TDateTime, Variant>(
function(pValue: TDateTime): Variant
begin
if pValue = 0 then
begin
Result := System.Variants.Null;
end else
begin
Result := pValue;
end;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromDouble;
begin
RegisterConverter<Double, string>(
function(pValue: Double): string
begin
{$IF CompilerVersion >= 29} // bug no XE7
Result := pValue.ToString;
{$ELSE}
Result := FloatToStr(pValue);
{$ENDIF}
end);
RegisterConverter<Double, UInt8>(
function(pValue: Double): UInt8
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Double, Int8>(
function(pValue: Double): Int8
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Double, UInt16>(
function(pValue: Double): UInt16
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Double, Int16>(
function(pValue: Double): Int16
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Double, UInt32>(
function(pValue: Double): UInt32
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Double, Int32>(
function(pValue: Double): Int32
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Double, UInt64>(
function(pValue: Double): UInt64
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Double, Int64>(
function(pValue: Double): Int64
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Double, TAqEntityID>(
function(pValue: Double): TAqEntityID
begin
{$IF CompilerVersion >= 29}
Result := pValue.Trunc;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Double, Double>(
function(pValue: Double): Double
begin
Result := pValue;
end);
RegisterConverter<Double, Currency>(
function(pValue: Double): Currency
begin
Result := pValue;
end);
RegisterConverter<Double, TDateTime>(
function(pValue: Double): TDateTime
begin
{$IF CompilerVersion >= 29}
Result := pValue.ToDateTime;
{$ELSE}
Result := pValue;
{$ENDIF}
end);
RegisterConverter<Double, TDate>(
function(pValue: Double): TDate
begin
{$IF CompilerVersion >= 29}
Result := pValue.ToDateTime.DateOf;
{$ELSE}
Result := System.Trunc(pValue);
{$ENDIF}
end);
RegisterConverter<Double, TTime>(
function(pValue: Double): TTime
begin
{$IF CompilerVersion >= 29}
Result := pValue.ToDateTime.TimeOf;
{$ELSE}
Result := System.Frac(pValue);
{$ENDIF}
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromEntityID;
begin
RegisterConverter<TAqEntityID, string>(
function(pValue: TAqEntityID): string
begin
{$IF CompilerVersion >= 29} // bug no XE7
Result := pValue.ToString;
{$ELSE}
Result := System.StrUtils.IfThen(pValue > 0, IntToStr(pValue));
{$ENDIF}
end);
RegisterConverter<TAqEntityID, Boolean>(
function(pValue: TAqEntityID): Boolean
begin
{$IF CompilerVersion >= 29}
Result := pValue.ToBoolean;
{$ELSE}
Result := pValue <> 0;
{$ENDIF}
end);
RegisterConverter<TAqEntityID, UInt8>(
function(pValue: TAqEntityID): UInt8
begin
Result := pValue;
end);
RegisterConverter<TAqEntityID, Int8>(
function(pValue: TAqEntityID): Int8
begin
Result := pValue;
end);
RegisterConverter<TAqEntityID, UInt16>(
function(pValue: TAqEntityID): UInt16
begin
Result := pValue;
end);
RegisterConverter<TAqEntityID, Int16>(
function(pValue: TAqEntityID): Int16
begin
Result := pValue;
end);
RegisterConverter<TAqEntityID, UInt32>(
function(pValue: TAqEntityID): UInt32
begin
Result := pValue;
end);
RegisterConverter<TAqEntityID, Int32>(
function(pValue: TAqEntityID): Int32
begin
Result := pValue;
end);
RegisterConverter<TAqEntityID, UInt64>(
function(pValue: TAqEntityID): UInt64
begin
Result := pValue;
end);
RegisterConverter<TAqEntityID, TAqEntityID>(
function(pValue: TAqEntityID): TAqEntityID
begin
Result := pValue;
end);
RegisterConverter<TAqEntityID, Double>(
function(pValue: TAqEntityID): Double
begin
Result := System.Math.IfThen(pValue > 0, pValue);
end);
RegisterConverter<TAqEntityID, Currency>(
function(pValue: TAqEntityID): Currency
begin
Result := pValue;
end);
RegisterConverter<TAqEntityID, Variant>(
function(pValue: TAqEntityID): Variant
begin
if pValue > 0 then
begin
Result := pValue;
end else
begin
Result := System.Variants.Null;
end;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromInt16;
begin
RegisterConverter<Int16, string>(
function(pValue: Int16): string
begin
Result := pValue.ToString;
end);
RegisterConverter<Int16, Boolean>(
function(pValue: Int16): Boolean
begin
Result := pValue.ToBoolean;
end);
RegisterConverter<Int16, UInt8>(
function(pValue: Int16): UInt8
begin
Result := pValue;
end);
RegisterConverter<Int16, Int8>(
function(pValue: Int16): Int8
begin
Result := pValue;
end);
RegisterConverter<Int16, UInt16>(
function(pValue: Int16): UInt16
begin
Result := pValue;
end);
RegisterConverter<Int16, Int16>(
function(pValue: Int16): Int16
begin
Result := pValue;
end);
RegisterConverter<Int16, UInt32>(
function(pValue: Int16): UInt32
begin
Result := pValue;
end);
RegisterConverter<Int16, Int32>(
function(pValue: Int16): Int32
begin
Result := pValue;
end);
RegisterConverter<Int16, UInt64>(
function(pValue: Int16): UInt64
begin
Result := pValue;
end);
RegisterConverter<Int16, Int64>(
function(pValue: Int16): Int64
begin
Result := pValue;
end);
RegisterConverter<Int16, TAqEntityID>(
function(pValue: Int16): TAqEntityID
begin
Result := pValue;
end);
RegisterConverter<Int16, Double>(
function(pValue: Int16): Double
begin
Result := pValue;
end);
RegisterConverter<Int16, Currency>(
function(pValue: Int16): Currency
begin
Result := pValue;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromInt32;
begin
RegisterConverter<Int32, string>(
function(pValue: Int32): string
begin
Result := pValue.ToString;
end);
RegisterConverter<Int32, Boolean>(
function(pValue: Int32): Boolean
begin
Result := pValue.ToBoolean;
end);
RegisterConverter<Int32, UInt8>(
function(pValue: Int32): UInt8
begin
Result := pValue;
end);
RegisterConverter<Int32, Int8>(
function(pValue: Int32): Int8
begin
Result := pValue;
end);
RegisterConverter<Int32, UInt16>(
function(pValue: Int32): UInt16
begin
Result := pValue;
end);
RegisterConverter<Int32, Int16>(
function(pValue: Int32): Int16
begin
Result := pValue;
end);
RegisterConverter<Int32, UInt32>(
function(pValue: Int32): UInt32
begin
Result := pValue;
end);
RegisterConverter<Int32, Int32>(
function(pValue: Int32): Int32
begin
Result := pValue;
end);
RegisterConverter<Int32, UInt64>(
function(pValue: Int32): UInt64
begin
Result := pValue;
end);
RegisterConverter<Int32, Int64>(
function(pValue: Int32): Int64
begin
Result := pValue;
end);
RegisterConverter<Int32, TAqEntityID>(
function(pValue: Int32): TAqEntityID
begin
Result := pValue;
end);
RegisterConverter<Int32, Double>(
function(pValue: Int32): Double
begin
Result := pValue;
end);
RegisterConverter<Int32, Currency>(
function(pValue: Int32): Currency
begin
Result := pValue;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromInt64;
begin
RegisterConverter<Int64, string>(
function(pValue: Int64): string
begin
{$IF CompilerVersion >= 29} // bug no XE7
Result := pValue.ToString;
{$ELSE}
Result := IntToStr(pValue);
{$ENDIF}
end);
RegisterConverter<Int64, Boolean>(
function(pValue: Int64): Boolean
begin
{$IF CompilerVersion >= 29}
Result := pValue.ToBoolean;
{$ELSE}
Result := pValue <> 0;
{$ENDIF}
end);
RegisterConverter<Int64, UInt8>(
function(pValue: Int64): UInt8
begin
Result := pValue;
end);
RegisterConverter<Int64, Int8>(
function(pValue: Int64): Int8
begin
Result := pValue;
end);
RegisterConverter<Int64, UInt16>(
function(pValue: Int64): UInt16
begin
Result := pValue;
end);
RegisterConverter<Int64, Int16>(
function(pValue: Int64): Int16
begin
Result := pValue;
end);
RegisterConverter<Int64, UInt32>(
function(pValue: Int64): UInt32
begin
Result := pValue;
end);
RegisterConverter<Int64, Int32>(
function(pValue: Int64): Int32
begin
Result := pValue;
end);
RegisterConverter<Int64, UInt64>(
function(pValue: Int64): UInt64
begin
Result := pValue;
end);
RegisterConverter<Int64, Int64>(
function(pValue: Int64): Int64
begin
Result := pValue;
end);
RegisterConverter<Int64, TAqEntityID>(
function(pValue: Int64): TAqEntityID
begin
Result := pValue;
end);
RegisterConverter<Int64, Double>(
function(pValue: Int64): Double
begin
Result := pValue;
end);
RegisterConverter<Int64, Currency>(
function(pValue: Int64): Currency
begin
Result := pValue;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromInt8;
begin
RegisterConverter<Int8, string>(
function(pValue: Int8): string
begin
Result := pValue.ToString;
end);
RegisterConverter<Int8, Boolean>(
function(pValue: Int8): Boolean
begin
Result := pValue.ToBoolean;
end);
RegisterConverter<Int8, UInt8>(
function(pValue: Int8): UInt8
begin
Result := pValue;
end);
RegisterConverter<Int8, Int8>(
function(pValue: Int8): Int8
begin
Result := pValue;
end);
RegisterConverter<Int8, UInt16>(
function(pValue: Int8): UInt16
begin
Result := pValue;
end);
RegisterConverter<Int8, Int16>(
function(pValue: Int8): Int16
begin
Result := pValue;
end);
RegisterConverter<Int8, UInt32>(
function(pValue: Int8): UInt32
begin
Result := pValue;
end);
RegisterConverter<Int8, Int32>(
function(pValue: Int8): Int32
begin
Result := pValue;
end);
RegisterConverter<Int8, UInt64>(
function(pValue: Int8): UInt64
begin
Result := pValue;
end);
RegisterConverter<Int8, Int64>(
function(pValue: Int8): Int64
begin
Result := pValue;
end);
RegisterConverter<Int8, TAqEntityID>(
function(pValue: Int8): TAqEntityID
begin
Result := pValue;
end);
RegisterConverter<Int8, Double>(
function(pValue: Int8): Double
begin
Result := pValue;
end);
RegisterConverter<Int8, Currency>(
function(pValue: Int8): Currency
begin
Result := pValue;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromString;
begin
RegisterConverter<string, Boolean>(
function(pValue: string): Boolean
begin
Result := pValue.ToBoolean;
end);
RegisterConverter<string, UInt8>(
function(pValue: string): UInt8
begin
Result := pValue.ToUIntZeroIfEmpty;
end);
RegisterConverter<string, Int8>(
function(pValue: string): Int8
begin
Result := pValue.ToIntZeroIfEmpty;
end);
RegisterConverter<string, UInt16>(
function(pValue: string): UInt16
begin
Result := pValue.ToUIntZeroIfEmpty;
end);
RegisterConverter<string, Int16>(
function(pValue: string): Int16
begin
Result := pValue.ToIntZeroIfEmpty;
end);
RegisterConverter<string, UInt32>(
function(pValue: string): UInt32
begin
Result := pValue.ToUIntZeroIfEmpty;
end);
RegisterConverter<string, Int32>(
function(pValue: string): Int32
begin
Result := pValue.ToIntZeroIfEmpty;
end);
RegisterConverter<string, UInt64>(
function(pValue: string): UInt64
begin
Result := pValue.ToUIntZeroIfEmpty;
end);
RegisterConverter<string, Int64>(
function(pValue: string): Int64
begin
Result := pValue.ToIntZeroIfEmpty;
end);
RegisterConverter<string, TAqEntityID>(
function(pValue: string): TAqEntityID
begin
Result := pValue.ToIntZeroIfEmpty;
end);
RegisterConverter<string, Double>(
function(pValue: string): Double
begin
Result := pValue.ToDouble;
end);
RegisterConverter<string, Currency>(
function(pValue: string): Currency
begin
Result := pValue.ToCurrency;
end);
RegisterConverter<string, TDateTime>(
function(pValue: string): TDateTime
begin
Result := pValue.ToDateTime;
end);
RegisterConverter<string, TDate>(
function(pValue: string): TDate
begin
Result := pValue.ToDate;
end);
RegisterConverter<string, TTime>(
function(pValue: string): TTime
begin
Result := pValue.ToTime;
end);
RegisterConverter<string, TGUID>(
function(pValue: string): TGUID
begin
Result := TGUID.Create(pValue);
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromTime;
begin
RegisterConverter<TTime, string>(
function(pValue: TTime): string
begin
{$IF CompilerVersion >= 29} // bug no XE7
Result := pValue.ToString;
{$ELSE}
Result := TimeToStr(pValue);
{$ENDIF}
end);
RegisterConverter<TTime, Double>(
function(pValue: TTime): Double
begin
Result := pValue;
end);
RegisterConverter<TTime, TDateTime>(
function(pValue: TTime): TDateTime
begin
Result := pValue;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromUInt16;
begin
RegisterConverter<UInt16, string>(
function(pValue: UInt16): string
begin
Result := pValue.ToString;
end);
RegisterConverter<UInt16, Boolean>(
function(pValue: UInt16): Boolean
begin
Result := pValue.ToBoolean;
end);
RegisterConverter<UInt16, UInt8>(
function(pValue: UInt16): UInt8
begin
Result := pValue;
end);
RegisterConverter<UInt16, Int8>(
function(pValue: UInt16): Int8
begin
Result := pValue;
end);
RegisterConverter<UInt16, UInt16>(
function(pValue: UInt16): UInt16
begin
Result := pValue;
end);
RegisterConverter<UInt16, Int16>(
function(pValue: UInt16): Int16
begin
Result := pValue;
end);
RegisterConverter<UInt16, UInt32>(
function(pValue: UInt16): UInt32
begin
Result := pValue;
end);
RegisterConverter<UInt16, Int32>(
function(pValue: UInt16): Int32
begin
Result := pValue;
end);
RegisterConverter<UInt16, UInt64>(
function(pValue: UInt16): UInt64
begin
Result := pValue;
end);
RegisterConverter<UInt16, Int64>(
function(pValue: UInt16): Int64
begin
Result := pValue;
end);
RegisterConverter<UInt16, TAqEntityID>(
function(pValue: UInt16): TAqEntityID
begin
Result := pValue;
end);
RegisterConverter<UInt16, Double>(
function(pValue: UInt16): Double
begin
Result := pValue;
end);
RegisterConverter<UInt16, Currency>(
function(pValue: UInt16): Currency
begin
Result := pValue;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromUInt32;
begin
RegisterConverter<UInt32, string>(
function(pValue: UInt32): string
begin
Result := pValue.ToString;
end);
RegisterConverter<UInt32, Boolean>(
function(pValue: UInt32): Boolean
begin
Result := pValue.ToBoolean;
end);
RegisterConverter<UInt32, UInt8>(
function(pValue: UInt32): UInt8
begin
Result := pValue;
end);
RegisterConverter<UInt32, Int8>(
function(pValue: UInt32): Int8
begin
Result := pValue;
end);
RegisterConverter<UInt32, UInt16>(
function(pValue: UInt32): UInt16
begin
Result := pValue;
end);
RegisterConverter<UInt32, Int16>(
function(pValue: UInt32): Int16
begin
Result := pValue;
end);
RegisterConverter<UInt32, UInt32>(
function(pValue: UInt32): UInt32
begin
Result := pValue;
end);
RegisterConverter<UInt32, Int32>(
function(pValue: UInt32): Int32
begin
Result := pValue;
end);
RegisterConverter<UInt32, UInt64>(
function(pValue: UInt32): UInt64
begin
Result := pValue;
end);
RegisterConverter<UInt32, Int64>(
function(pValue: UInt32): Int64
begin
Result := pValue;
end);
RegisterConverter<UInt32, TAqEntityID>(
function(pValue: UInt32): TAqEntityID
begin
Result := pValue;
end);
RegisterConverter<UInt32, Double>(
function(pValue: UInt32): Double
begin
Result := pValue;
end);
RegisterConverter<UInt32, Currency>(
function(pValue: UInt32): Currency
begin
Result := pValue;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromUInt64;
begin
RegisterConverter<UInt64, string>(
function(pValue: UInt64): string
begin
{$IF CompilerVersion >= 29} // bug no XE7
Result := pValue.ToString;
{$ELSE}
Result := IntToStr(pValue);
{$ENDIF}
end);
RegisterConverter<UInt64, Boolean>(
function(pValue: UInt64): Boolean
begin
{$IF CompilerVersion >= 29}
Result := pValue.ToBoolean;
{$ELSE}
Result := pValue <> 0;
{$ENDIF}
end);
RegisterConverter<UInt64, UInt8>(
function(pValue: UInt64): UInt8
begin
Result := pValue;
end);
RegisterConverter<UInt64, Int8>(
function(pValue: UInt64): Int8
begin
Result := pValue;
end);
RegisterConverter<UInt64, UInt16>(
function(pValue: UInt64): UInt16
begin
Result := pValue;
end);
RegisterConverter<UInt64, Int16>(
function(pValue: UInt64): Int16
begin
Result := pValue;
end);
RegisterConverter<UInt64, UInt32>(
function(pValue: UInt64): UInt32
begin
Result := pValue;
end);
RegisterConverter<UInt64, Int32>(
function(pValue: UInt64): Int32
begin
Result := pValue;
end);
RegisterConverter<UInt64, UInt64>(
function(pValue: UInt64): UInt64
begin
Result := pValue;
end);
RegisterConverter<UInt64, Int64>(
function(pValue: UInt64): Int64
begin
Result := pValue;
end);
RegisterConverter<UInt64, TAqEntityID>(
function(pValue: UInt64): TAqEntityID
begin
Result := pValue;
end);
RegisterConverter<UInt64, Double>(
function(pValue: UInt64): Double
begin
Result := pValue;
end);
RegisterConverter<UInt64, Currency>(
function(pValue: UInt64): Currency
begin
Result := pValue;
end);
end;
procedure TAqTypeConverters.RegisterConvertersFromUInt8;
begin
RegisterConverter<UInt8, string>(
function(pValue: UInt8): string
begin
Result := pValue.ToString;
end);
RegisterConverter<UInt8, Boolean>(
function(pValue: UInt8): Boolean
begin
Result := pValue.ToBoolean;
end);
RegisterConverter<UInt8, UInt8>(
function(pValue: UInt8): UInt8
begin
Result := pValue;
end);
RegisterConverter<UInt8, Int8>(
function(pValue: UInt8): Int8
begin
Result := pValue;
end);
RegisterConverter<UInt8, UInt16>(
function(pValue: UInt8): UInt16
begin
Result := pValue;
end);
RegisterConverter<UInt8, Int16>(
function(pValue: UInt8): Int16
begin
Result := pValue;
end);
RegisterConverter<UInt8, UInt32>(
function(pValue: UInt8): UInt32
begin
Result := pValue;
end);
RegisterConverter<UInt8, Int32>(
function(pValue: UInt8): Int32
begin
Result := pValue;
end);
RegisterConverter<UInt8, UInt64>(
function(pValue: UInt8): UInt64
begin
Result := pValue;
end);
RegisterConverter<UInt8, Int64>(
function(pValue: UInt8): Int64
begin
Result := pValue;
end);
RegisterConverter<UInt8, TAqEntityID>(
function(pValue: UInt8): TAqEntityID
begin
Result := pValue;
end);
RegisterConverter<UInt8, Double>(
function(pValue: UInt8): Double
begin
Result := pValue;
end);
RegisterConverter<UInt8, Currency>(
function(pValue: UInt8): Currency
begin
Result := pValue;
end);
end;
procedure TAqTypeConverters.RegisterMinorStandarConverters;
begin
RegisterConverter<TGUID, string>(
function(pValue: TGUID): string
begin
Result := pValue.ToString;
end);
end;
procedure TAqTypeConverters.RegisterStandardConverters;
begin
RegisterConvertersFromString;
RegisterConvertersFromBoolean;
RegisterConvertersFromUInt8;
RegisterConvertersFromInt8;
RegisterConvertersFromUInt16;
RegisterConvertersFromInt16;
RegisterConvertersFromUInt32;
RegisterConvertersFromInt32;
RegisterConvertersFromUInt64;
RegisterConvertersFromInt64;
RegisterConvertersFromDouble;
RegisterConvertersFromCurrency;
RegisterConvertersFromDateTime;
RegisterConvertersFromDate;
RegisterConvertersFromTime;
RegisterConvertersFromEntityID;
RegisterMinorStandarConverters;
end;
class procedure TAqTypeConverters.ReleaseDefaultInstance;
begin
FreeAndNil(FDefaultInstance);
end;
function TAqTypeConverters.TryConvert(const pFrom: TValue; const pToType: PTypeInfo; out pValue: TValue): Boolean;
var
lConverter: TAqTypeConverter;
begin
Result := pFrom.TypeInfo = pToType;
if Result then
begin
pValue := pFrom;
end else
begin
FConverters.BeginRead;
try
Result := FConverters.TryGetValue(GetDictionaryKey(pFrom.TypeInfo, pToType), lConverter);
if Result then
begin
pValue := lConverter.Execute(pFrom);
end;
finally
FConverters.EndRead;
end;
end;
end;
function TAqTypeConverters.TryConvert<TFrom, TTo>(const pFrom: TFrom; out pValue: TTo): Boolean;
begin
Result := TryConvert<TTo>(TValue.From<TFrom>(pFrom), pValue);
end;
function TAqTypeConverters.TryConvert<TTo>(const pFrom: TValue; out pValue: TTo): Boolean;
var
lValue: TValue;
begin
Result := TryConvert(pFrom, TypeInfo(TTo), lValue);
if Result then
begin
pValue := lValue.AsType<TTo>;
end;
end;
{ TAqTypeConverterByMethod<TFrom, TTo> }
constructor TAqTypeConverterByMethod<TFrom, TTo>.Create(const pConverter: TFunc<TFrom, TTo>);
begin
FConverter := pConverter;
end;
function TAqTypeConverterByMethod<TFrom, TTo>.DoExecute(const pFrom: TValue): TValue;
begin
Result := TValue.From<TTo>(FConverter(pFrom.AsType<TFrom>));
end;
initialization
TAqTypeConverters.Default.RegisterStandardConverters;
finalization
TAqTypeConverters.ReleaseDefaultInstance;
end.
|
{********************************************************************************************}
{ }
{ XML Data Binding }
{ }
{ Generated on: 10/22/2010 2:24:29 PM }
{ Generated from: C:\Users\jwyatt\Documents\Client Integration Suite\ODP\CIS_QCP.xsd }
{ Settings stored in: C:\Users\jwyatt\Documents\Client Integration Suite\ODP\CIS_QCP.xdb }
{ }
{********************************************************************************************}
unit UAMC_QCP;
interface
uses xmldom, XMLDoc, XMLIntf;
type
{ Forward Decls }
IXMLQualityControlPackage = interface;
IXMLValidationMessagesType = interface;
IXMLValidationMessageType = interface;
IXMLText = interface;
IXMLLocationsType = interface;
IXMLLocationType = interface;
{ IXMLQualityControlPackage }
IXMLQualityControlPackage = interface(IXMLNode)
['{182739EE-0CDD-4AC5-8C40-2C54F0788071}']
{ Property Accessors }
function Get_Xsd: WideString;
function Get_ValidationMessages: IXMLValidationMessagesType;
procedure Set_Xsd(Value: WideString);
{ Methods & Properties }
property Xsd: WideString read Get_Xsd write Set_Xsd;
property ValidationMessages: IXMLValidationMessagesType read Get_ValidationMessages;
end;
{ IXMLValidationMessagesType }
IXMLValidationMessagesType = interface(IXMLNodeCollection)
['{4566B0F0-2B5A-4610-9E77-E828AD710FFE}']
{ Property Accessors }
function Get_ValidationMessage(Index: Integer): IXMLValidationMessageType;
{ Methods & Properties }
function Add: IXMLValidationMessageType;
function Insert(const Index: Integer): IXMLValidationMessageType;
property ValidationMessage[Index: Integer]: IXMLValidationMessageType read Get_ValidationMessage; default;
end;
{ IXMLValidationMessageType }
IXMLValidationMessageType = interface(IXMLNode)
['{2C5B9B87-F0C9-4D18-A4DE-28490AC6B7B6}']
{ Property Accessors }
function Get_Type_: WideString;
function Get_RuleID: WideString;
function Get_Text: IXMLText;
function Get_Locations: IXMLLocationsType;
procedure Set_Type_(Value: WideString);
procedure Set_RuleID(Value: WideString);
{ Methods & Properties }
property Type_: WideString read Get_Type_ write Set_Type_;
property RuleID: WideString read Get_RuleID write Set_RuleID;
property Text: IXMLText read Get_Text;
property Locations: IXMLLocationsType read Get_Locations;
end;
{ IXMLText }
IXMLText = interface(IXMLNode)
['{7235201D-1DDD-42D5-BA38-0E070C9CFB24}']
end;
{ IXMLLocationsType }
IXMLLocationsType = interface(IXMLNodeCollection)
['{8E5D8F1C-FD48-4B5B-B731-A548BBE9F696}']
{ Property Accessors }
function Get_Location(Index: Integer): IXMLLocationType;
{ Methods & Properties }
function Add: IXMLLocationType;
function Insert(const Index: Integer): IXMLLocationType;
property Location[Index: Integer]: IXMLLocationType read Get_Location; default;
end;
{ IXMLLocationType }
IXMLLocationType = interface(IXMLNode)
['{0509AAE8-9F13-4068-B5C5-E3B5CA26E794}']
{ Property Accessors }
function Get_Locator: WideString;
procedure Set_Locator(Value: WideString);
{ Methods & Properties }
property Locator: WideString read Get_Locator write Set_Locator;
end;
{ Forward Decls }
TXMLQualityControlPackage = class;
TXMLValidationMessagesType = class;
TXMLValidationMessageType = class;
TXMLText = class;
TXMLLocationsType = class;
TXMLLocationType = class;
{ TXMLQualityControlPackage }
TXMLQualityControlPackage = class(TXMLNode, IXMLQualityControlPackage)
protected
{ IXMLQualityControlPackage }
function Get_Xsd: WideString;
function Get_ValidationMessages: IXMLValidationMessagesType;
procedure Set_Xsd(Value: WideString);
public
procedure AfterConstruction; override;
end;
{ TXMLValidationMessagesType }
TXMLValidationMessagesType = class(TXMLNodeCollection, IXMLValidationMessagesType)
protected
{ IXMLValidationMessagesType }
function Get_ValidationMessage(Index: Integer): IXMLValidationMessageType;
function Add: IXMLValidationMessageType;
function Insert(const Index: Integer): IXMLValidationMessageType;
public
procedure AfterConstruction; override;
end;
{ TXMLValidationMessageType }
TXMLValidationMessageType = class(TXMLNode, IXMLValidationMessageType)
protected
{ IXMLValidationMessageType }
function Get_Type_: WideString;
function Get_RuleID: WideString;
function Get_Text: IXMLText;
function Get_Locations: IXMLLocationsType;
procedure Set_Type_(Value: WideString);
procedure Set_RuleID(Value: WideString);
public
procedure AfterConstruction; override;
end;
{ TXMLText }
TXMLText = class(TXMLNode, IXMLText)
protected
{ IXMLText }
end;
{ TXMLLocationsType }
TXMLLocationsType = class(TXMLNodeCollection, IXMLLocationsType)
protected
{ IXMLLocationsType }
function Get_Location(Index: Integer): IXMLLocationType;
function Add: IXMLLocationType;
function Insert(const Index: Integer): IXMLLocationType;
public
procedure AfterConstruction; override;
end;
{ TXMLLocationType }
TXMLLocationType = class(TXMLNode, IXMLLocationType)
protected
{ IXMLLocationType }
function Get_Locator: WideString;
procedure Set_Locator(Value: WideString);
end;
{ Global Functions }
function GetQualityControlPackage(Doc: IXMLDocument): IXMLQualityControlPackage;
function LoadQualityControlPackage(const FileName: WideString): IXMLQualityControlPackage;
function NewQualityControlPackage: IXMLQualityControlPackage;
const
TargetNamespace = '';
implementation
{ Global Functions }
function GetQualityControlPackage(Doc: IXMLDocument): IXMLQualityControlPackage;
begin
Result := Doc.GetDocBinding('QualityControlPackage', TXMLQualityControlPackage, TargetNamespace) as IXMLQualityControlPackage;
end;
function LoadQualityControlPackage(const FileName: WideString): IXMLQualityControlPackage;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('QualityControlPackage', TXMLQualityControlPackage, TargetNamespace) as IXMLQualityControlPackage;
end;
function NewQualityControlPackage: IXMLQualityControlPackage;
begin
Result := NewXMLDocument.GetDocBinding('QualityControlPackage', TXMLQualityControlPackage, TargetNamespace) as IXMLQualityControlPackage;
end;
{ TXMLQualityControlPackage }
procedure TXMLQualityControlPackage.AfterConstruction;
begin
RegisterChildNode('ValidationMessages', TXMLValidationMessagesType);
inherited;
end;
function TXMLQualityControlPackage.Get_Xsd: WideString;
begin
Result := AttributeNodes['xmlns:xsd'].Text;
end;
procedure TXMLQualityControlPackage.Set_Xsd(Value: WideString);
begin
SetAttribute('xmlns:xsd', Value);
end;
function TXMLQualityControlPackage.Get_ValidationMessages: IXMLValidationMessagesType;
begin
Result := ChildNodes['ValidationMessages'] as IXMLValidationMessagesType;
end;
{ TXMLValidationMessagesType }
procedure TXMLValidationMessagesType.AfterConstruction;
begin
RegisterChildNode('ValidationMessage', TXMLValidationMessageType);
ItemTag := 'ValidationMessage';
ItemInterface := IXMLValidationMessageType;
inherited;
end;
function TXMLValidationMessagesType.Get_ValidationMessage(Index: Integer): IXMLValidationMessageType;
begin
Result := List[Index] as IXMLValidationMessageType;
end;
function TXMLValidationMessagesType.Add: IXMLValidationMessageType;
begin
Result := AddItem(-1) as IXMLValidationMessageType;
end;
function TXMLValidationMessagesType.Insert(const Index: Integer): IXMLValidationMessageType;
begin
Result := AddItem(Index) as IXMLValidationMessageType;
end;
{ TXMLValidationMessageType }
procedure TXMLValidationMessageType.AfterConstruction;
begin
RegisterChildNode('Text', TXMLText);
RegisterChildNode('Locations', TXMLLocationsType);
inherited;
end;
function TXMLValidationMessageType.Get_Type_: WideString;
begin
Result := ChildNodes['Type'].Text;
end;
procedure TXMLValidationMessageType.Set_Type_(Value: WideString);
begin
ChildNodes['Type'].NodeValue := Value;
end;
function TXMLValidationMessageType.Get_RuleID: WideString;
begin
Result := ChildNodes['RuleID'].Text;
end;
procedure TXMLValidationMessageType.Set_RuleID(Value: WideString);
begin
ChildNodes['RuleID'].NodeValue := Value;
end;
function TXMLValidationMessageType.Get_Text: IXMLText;
begin
Result := ChildNodes['Text'] as IXMLText;
end;
function TXMLValidationMessageType.Get_Locations: IXMLLocationsType;
begin
Result := ChildNodes['Locations'] as IXMLLocationsType;
end;
{ TXMLText }
{ TXMLLocationsType }
procedure TXMLLocationsType.AfterConstruction;
begin
RegisterChildNode('Location', TXMLLocationType);
ItemTag := 'Location';
ItemInterface := IXMLLocationType;
inherited;
end;
function TXMLLocationsType.Get_Location(Index: Integer): IXMLLocationType;
begin
Result := List[Index] as IXMLLocationType;
end;
function TXMLLocationsType.Add: IXMLLocationType;
begin
Result := AddItem(-1) as IXMLLocationType;
end;
function TXMLLocationsType.Insert(const Index: Integer): IXMLLocationType;
begin
Result := AddItem(Index) as IXMLLocationType;
end;
{ TXMLLocationType }
function TXMLLocationType.Get_Locator: WideString;
begin
Result := ChildNodes['Locator'].Text;
end;
procedure TXMLLocationType.Set_Locator(Value: WideString);
begin
ChildNodes['Locator'].NodeValue := Value;
end;
end. |
//*******************************************************
//
// Delphi DataSnap Framework
//
// Copyright(c) 1995-2012 Embarcadero Technologies, Inc.
//
//*******************************************************
unit FPCStrings;
{$IFDEF FPC}
{$mode DELPHI}
//{$mode objfpc}
{$modeswitch objectivec2}
{$ENDIF}
interface
{$IFDEF FPC}
{$IFNDEF WINDOWS}
uses iPhoneAll;
function NStoString(Value: NSString): String;
function StringToNS(Value: String): NSString;
{$ENDIF} {$ENDIF}
procedure Log(Value: string);
function NSFStr(Value: String): string;
implementation
uses SysUtils;
{$IFDEF FPC}{$IFNDEF WINDOWS}
function NStoString(Value: NSString): String;
begin
Result := Value.UTF8String;
end;
function StringToNS(Value: String): NSString;
begin
Result := NSString.stringWithUTF8String(PChar(Value));
end;
{$ENDIF}{$ENDIF}
procedure Log(Value: string);
begin
{$IFDEF FPC}{$IFNDEF WINDOWS}
nsLog(StringToNS(Value));
{$ENDIF}{$ENDIF}
end;
function NSFStr(Value: String): string;
begin
Result := Value;
{$IFDEF FPC}
Result := StringReplace(Result, '%', '%%', [rfIgnoreCase, rfReplaceAll]);
{$ENDIF}
end;
end.
|
unit UserTest;
interface
uses dbTest, dbObjectTest, TestFramework, ObjectTest;
type
TUserTest = class (TdbObjectTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TUser = class(TObjectTest)
private
function InsertDefault: integer; override;
public
function InsertUpdateUser(const Id, Code: integer; UserName, Password : string; MemberId: Integer): integer;
constructor Create; override;
end;
implementation
uses ZDbcIntfs, SysUtils, Storage, DBClient, XMLDoc, CommonData, Forms,
UtilConvert, UtilConst, ZLibEx, zLibUtil, Data.DB;
{ TUserTest }
constructor TUser.Create;
begin
inherited Create;
spInsertUpdate := 'gpInsertUpdate_Object_User';
spSelect := 'gpSelect_Object_User';
spGet := 'gpGet_Object_User';
end;
function TUser.InsertDefault: integer;
begin
result := InsertUpdateUser(0, -2, 'UserName', 'Password', 0);
inherited;
end;
function TUser.InsertUpdateUser(const Id, Code: integer; UserName, Password: string; MemberId: Integer): integer;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inCode', ftInteger, ptInput, Code);
FParams.AddParam('inUserName', ftString, ptInput, UserName);
FParams.AddParam('inPassword', ftString, ptInput, Password);
FParams.AddParam('inMemberId', ftInteger, ptInput, MemberId);
FParams.AddParam('inUnitId', ftInteger, ptInput, 0);
result := InsertUpdate(FParams);
end;
procedure TUserTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'OBJECTS\User\';
inherited;
end;
procedure TUserTest.Test;
var Id: integer;
RecordCount: Integer;
ObjectTest: TUser;
begin
ObjectTest := TUser.Create;
// Получим список пользователей
RecordCount := ObjectTest.GetDataSet.RecordCount;
// Вставка пользователя
Id := ObjectTest.InsertDefault;
try
// Получение данных о пользователе
with ObjectTest.GetRecord(Id) do
Check((FieldByName('name').AsString = 'UserName'), 'Не сходятся данные Id = ' + FieldByName('id').AsString);
// Получим список пользователей
Check((ObjectTest.GetDataSet.RecordCount = RecordCount + 1), 'Количество записей не изменилось');
finally
ObjectTest.Delete(Id);
end;
end;
initialization
TestFramework.RegisterTest('Объекты', TUserTest.Suite);
end.
|
{
TProcessorInfo Component Version 1.1 - Suite GLib
Copyright (©) 2009, by Germán Estévez (Neftalí)
Clase que almacena las propiedades del Procesador.
Utilización/Usage:
Basta con "soltar" el componente y activarlo.
Place the component in the form and active it.
MSDN Info:
http://msdn.microsoft.com/en-us/library/aa394373(VS.85).aspx
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones,
errores y/o cualquier otro tipo de sugerencia envíame un mail a:
german_ral@hotmail.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion send a mail to:
german_ral@hotmail.com
=========================================================================
@author Germán Estévez (Neftalí)
@web http://neftali.clubDelphi.com - http://neftali-mirror.site11.com/
@cat Package GLib
}
unit CProcessorInfo;
{
=========================================================================
TProcessorInfo.pas
Componente
========================================================================
Historia de las Versiones
------------------------------------------------------------------------
23/12/2009 * Creación.
=========================================================================
Errores detectados no corregidos
=========================================================================
}
//=========================================================================
//
// I N T E R F A C E
//
//=========================================================================
interface
uses
Classes, Controls, CWMIBase;
type
//: Clase para definir las propiedades del componente.
TProcessorProperties = class(TPersistent)
private
FAddressWidth:Integer;
FArchitecture:Integer;
FAvailability:Integer;
FCaption:string;
FConfigManagerErrorCode:Longword;
FConfigManagerUserConfig:boolean;
FCpuStatus:Integer;
FCreationClassName:string;
FCurrentClockSpeed:Longword;
FCurrentVoltage:Integer;
FDataWidth:Integer;
FDescription:string;
FDeviceID:string;
FErrorCleared:boolean;
FErrorDescription:string;
FExtClock:Longword;
FFamily:Integer;
FFamilyAsString:string;
FInstallDate:TDateTime;
FL2CacheSize:Longword;
FL2CacheSpeed:Longword;
FL3CacheSize:Longword;
FL3CacheSpeed:Longword;
FLastErrorCode:Longword;
FLevel:Integer;
FLoadPercentage:Integer;
FManufacturer:string;
FMaxClockSpeed:Longword;
FName:string;
FNumberOfCores:Longword;
FNumberOfLogicalProcessors:Longword;
FOtherFamilyDescription:string;
FPNPDeviceID:string;
FPowerManagementCapabilities:TArrInteger;
FPowerManagementCapabilitiesCount:integer;
FPowerManagementCapabilitiesAsString:string;
FPowerManagementSupported:boolean;
FProcessorId:string;
FProcessorType:Integer;
FProcessorTypeAsString:string;
FRevision:Integer;
FRole:string;
FSocketDesignation:string;
FStatus:string;
FStatusInfo:Integer;
FStepping:string;
FSystemCreationClassName:string;
FSystemName:string;
FUniqueId:string;
FUpgradeMethod:Integer;
FVersion:string;
FVoltageCaps:Longword;
//enum
FArchitectureAsString:string;
FAvailabilityAsString:string;
FCpuStatusAsString:string;
private
function GetPowerManagementCapabilities(index: integer): Integer;
public
property PowerManagementCapabilities[index:integer]:Integer read GetPowerManagementCapabilities;
property PowerManagementCapabilitiesCount:integer read FPowerManagementCapabilitiesCount stored False;
// Obtener la propiedad <Architecture> como string
function GetArchitectureAsString():string;
// Obtener la propiedad <Availability> como string
function GetAvailabilityAsString():string;
// Obtener la propiedad <CpuStatus> como string
function GetCpuStatusAsString():string;
// Obtener la propiedad <Family> como string
function GetFamilyAsString():string;
// Obtener la propiedad <ProcessorType> como string
function GetProcessorTypeAsString():string;
published
property AddressWidth:Integer read FAddressWidth write FAddressWidth stored False;
property Architecture:Integer read FArchitecture write FArchitecture stored False;
property ArchitectureAsString:string read GetArchitectureAsString write FArchitectureAsString;
property Availability:Integer read FAvailability write FAvailability stored False;
property AvailabilityAsString:string read GetAvailabilityAsString write FAvailabilityAsString;
property Caption:string read FCaption write FCaption stored False;
property ConfigManagerErrorCode:Longword read FConfigManagerErrorCode write FConfigManagerErrorCode stored False;
property ConfigManagerUserConfig:boolean read FConfigManagerUserConfig write FConfigManagerUserConfig stored False;
property CpuStatus:Integer read FCpuStatus write FCpuStatus stored False;
property CpuStatusAsString:string read GetCpuStatusAsString write FCpuStatusAsString;
property CreationClassName:string read FCreationClassName write FCreationClassName stored False;
property CurrentClockSpeed:Longword read FCurrentClockSpeed write FCurrentClockSpeed stored False;
property CurrentVoltage:Integer read FCurrentVoltage write FCurrentVoltage stored False;
property DataWidth:Integer read FDataWidth write FDataWidth stored False;
property Description:string read FDescription write FDescription stored False;
property DeviceID:string read FDeviceID write FDeviceID stored False;
property ErrorCleared:boolean read FErrorCleared write FErrorCleared stored False;
property ErrorDescription:string read FErrorDescription write FErrorDescription stored False;
property ExtClock:Longword read FExtClock write FExtClock stored False;
property Family:Integer read FFamily write FFamily stored False;
property FamilyAsString:string read GetFamilyAsString write FFamilyAsString stored False;
property InstallDate:TDateTime read FInstallDate write FInstallDate stored False;
property L2CacheSize:Longword read FL2CacheSize write FL2CacheSize stored False;
property L2CacheSpeed:Longword read FL2CacheSpeed write FL2CacheSpeed stored False;
property L3CacheSize:Longword read FL3CacheSize write FL3CacheSize stored False;
property L3CacheSpeed:Longword read FL3CacheSpeed write FL3CacheSpeed stored False;
property LastErrorCode:Longword read FLastErrorCode write FLastErrorCode stored False;
property Level:Integer read FLevel write FLevel stored False;
property LoadPercentage:Integer read FLoadPercentage write FLoadPercentage stored False;
property Manufacturer:string read FManufacturer write FManufacturer stored False;
property MaxClockSpeed:Longword read FMaxClockSpeed write FMaxClockSpeed stored False;
property Name:string read FName write FName stored False;
property NumberOfCores:Longword read FNumberOfCores write FNumberOfCores stored False;
property NumberOfLogicalProcessors:Longword read FNumberOfLogicalProcessors write FNumberOfLogicalProcessors stored False;
property OtherFamilyDescription:string read FOtherFamilyDescription write FOtherFamilyDescription stored False;
property PNPDeviceID:string read FPNPDeviceID write FPNPDeviceID stored False;
property PowerManagementCapabilitiesAsString:string read FPowerManagementCapabilitiesAsString write FPowerManagementCapabilitiesAsString stored False;
// property PowerManagementCapabilitiesAsString:string read GetPowerManagementCapabilitiesAsString write FPowerManagementCapabilitiesAsString;
property PowerManagementSupported:boolean read FPowerManagementSupported write FPowerManagementSupported stored False;
property ProcessorId:string read FProcessorId write FProcessorId stored False;
property ProcessorType:Integer read FProcessorType write FProcessorType stored False;
property ProcessorTypeAsString:string read GetProcessorTypeAsString write FProcessorTypeAsString;
property Revision:Integer read FRevision write FRevision stored False;
property Role:string read FRole write FRole stored False;
property SocketDesignation:string read FSocketDesignation write FSocketDesignation stored False;
property Status:string read FStatus write FStatus stored False;
property StatusInfo:Integer read FStatusInfo write FStatusInfo stored False;
property Stepping:string read FStepping write FStepping stored False;
property SystemCreationClassName:string read FSystemCreationClassName write FSystemCreationClassName stored False;
property SystemName:string read FSystemName write FSystemName stored False;
property UniqueId:string read FUniqueId write FUniqueId stored False;
property UpgradeMethod:Integer read FUpgradeMethod write FUpgradeMethod stored False;
property Version:string read FVersion write FVersion stored False;
property VoltageCaps:Longword read FVoltageCaps write FVoltageCaps stored False;
end;
//: Implementación para el acceso vía WMI a la clase Win32_Processor
TProcessorInfo = class(TWMIBase)
private
FProcessorProperties: TProcessorProperties;
protected
//: Rellenar las propiedades.
procedure FillProperties(AIndex:integer); override;
// propiedad Active
procedure SetActive(const Value: Boolean); override;
//: Clase para el componente.
function GetWMIClass():string; override;
//: Obtener el root.
function GetWMIRoot():string; override;
//: Limpiar las propiedades
procedure ClearProps(); override;
public
// redefinido el constructor
constructor Create(AOwner: TComponent); override;
//: destructor
destructor Destroy; override;
published
// propiedades de la Processor
property ProcessorProperties:TProcessorProperties read FProcessorProperties write FProcessorProperties;
end;
// Constantes para la propiedad Architecture
const
ENUM_STRING_ARCHITECTURE_0 = 'x86';
ENUM_STRING_ARCHITECTURE_1 = 'MIPS';
ENUM_STRING_ARCHITECTURE_2 = 'Alpha';
ENUM_STRING_ARCHITECTURE_3 = 'PowerPC';
ENUM_STRING_ARCHITECTURE_6 = 'Intel Itanium Processor Family (IPF)';
ENUM_STRING_ARCHITECTURE_9 = 'x64';
// Constantes para la propiedad Availability
const
ENUM_STRING_AVAILABILITY_1 = 'Other';
ENUM_STRING_AVAILABILITY_2 = 'Unknown';
ENUM_STRING_AVAILABILITY_3 = 'Running or Full Power';
ENUM_STRING_AVAILABILITY_4 = 'Warning';
ENUM_STRING_AVAILABILITY_5 = 'In Test';
ENUM_STRING_AVAILABILITY_6 = 'Not Applicable';
ENUM_STRING_AVAILABILITY_7 = 'Power Off';
ENUM_STRING_AVAILABILITY_8 = 'Off Line';
ENUM_STRING_AVAILABILITY_9 = 'Off Duty';
ENUM_STRING_AVAILABILITY_10 = 'Degraded';
ENUM_STRING_AVAILABILITY_11 = 'Not Installed';
ENUM_STRING_AVAILABILITY_12 = 'Install Error';
ENUM_STRING_AVAILABILITY_13 = 'Power Save - Unknown. The device is known to be in a power save state, but its exact status is unknown.';
ENUM_STRING_AVAILABILITY_14 = 'Power Save - Low Power Mode. The device is in a power save state, but is still functioning, and may exhibit decreased performance.';
ENUM_STRING_AVAILABILITY_15 = 'Power Save - Standby. The device is not functioning, but can be brought to full power quickly.';
ENUM_STRING_AVAILABILITY_16 = 'Power Cycle';
ENUM_STRING_AVAILABILITY_17 = 'Power Save - Warning. The device is in a warning state, though also in a power save state.';
// Constantes para la propiedad CpuStatus
const
ENUM_STRING_CPUSTATUS_0 = 'Unknown';
ENUM_STRING_CPUSTATUS_1 = 'CPU Enabled';
ENUM_STRING_CPUSTATUS_2 = 'CPU Disabled by User via BIOS Setup';
ENUM_STRING_CPUSTATUS_3 = 'CPU Disabled by BIOS (POST Error)';
ENUM_STRING_CPUSTATUS_4 = 'CPU Is Idle';
ENUM_STRING_CPUSTATUS_5 = 'Reserved';
ENUM_STRING_CPUSTATUS_6 = 'Reserved';
ENUM_STRING_CPUSTATUS_7 = 'Other';
// Constantes para la propiedad Family
const
ENUM_STRING_FAMILY_1 = 'Other';
ENUM_STRING_FAMILY_2 = 'Unknown';
ENUM_STRING_FAMILY_3 = '8086';
ENUM_STRING_FAMILY_4 = '80286';
ENUM_STRING_FAMILY_5 = 'Intel386™ Processor';
ENUM_STRING_FAMILY_6 = 'Intel486™ Processor';
ENUM_STRING_FAMILY_7 = '8087';
ENUM_STRING_FAMILY_8 = '80287';
ENUM_STRING_FAMILY_9 = '80387';
ENUM_STRING_FAMILY_10 = '80487';
ENUM_STRING_FAMILY_11 = 'Pentium Brand';
ENUM_STRING_FAMILY_12 = 'Pentium Pro';
ENUM_STRING_FAMILY_13 = 'Pentium II';
ENUM_STRING_FAMILY_14 = 'Pentium Processor with MMX™ Technology';
ENUM_STRING_FAMILY_15 = 'Celeron™';
ENUM_STRING_FAMILY_16 = 'Pentium II Xeon™';
ENUM_STRING_FAMILY_17 = 'Pentium III';
ENUM_STRING_FAMILY_18 = 'M1 Family';
ENUM_STRING_FAMILY_19 = 'M2 Family';
ENUM_STRING_FAMILY_24 = 'AMD Duron™ Processor Family';
ENUM_STRING_FAMILY_25 = 'K5 Family';
ENUM_STRING_FAMILY_26 = 'K6 Family';
ENUM_STRING_FAMILY_27 = 'K6-2';
ENUM_STRING_FAMILY_28 = 'K6-3';
ENUM_STRING_FAMILY_29 = 'AMD Athlon™ Processor Family';
ENUM_STRING_FAMILY_30 = 'AMD2900 Family';
ENUM_STRING_FAMILY_31 = 'K6-2+';
ENUM_STRING_FAMILY_32 = 'Power PC Family';
ENUM_STRING_FAMILY_33 = 'Power PC 601';
ENUM_STRING_FAMILY_34 = 'Power PC 603';
ENUM_STRING_FAMILY_35 = 'Power PC 603+';
ENUM_STRING_FAMILY_36 = 'Power PC 604';
ENUM_STRING_FAMILY_37 = 'Power PC 620';
ENUM_STRING_FAMILY_38 = 'Power PC X704';
ENUM_STRING_FAMILY_39 = 'Power PC 750';
ENUM_STRING_FAMILY_48 = 'Alpha Family';
ENUM_STRING_FAMILY_49 = 'Alpha 21064';
ENUM_STRING_FAMILY_50 = 'Alpha 21066';
ENUM_STRING_FAMILY_51 = 'Alpha 21164';
ENUM_STRING_FAMILY_52 = 'Alpha 21164PC';
ENUM_STRING_FAMILY_53 = 'Alpha 21164a';
ENUM_STRING_FAMILY_54 = 'Alpha 21264';
ENUM_STRING_FAMILY_55 = 'Alpha 21364';
ENUM_STRING_FAMILY_64 = 'MIPS Family';
ENUM_STRING_FAMILY_65 = 'MIPS R4000';
ENUM_STRING_FAMILY_66 = 'MIPS R4200';
ENUM_STRING_FAMILY_67 = 'MIPS R4400';
ENUM_STRING_FAMILY_68 = 'MIPS R4600';
ENUM_STRING_FAMILY_69 = 'MIPS R10000';
ENUM_STRING_FAMILY_80 = 'SPARC Family';
ENUM_STRING_FAMILY_81 = 'SuperSPARC';
ENUM_STRING_FAMILY_82 = 'microSPARC II';
ENUM_STRING_FAMILY_83 = 'microSPARC IIep';
ENUM_STRING_FAMILY_84 = 'UltraSPARC';
ENUM_STRING_FAMILY_85 = 'UltraSPARC II';
ENUM_STRING_FAMILY_86 = 'UltraSPARC IIi';
ENUM_STRING_FAMILY_87 = 'UltraSPARC III';
ENUM_STRING_FAMILY_88 = 'UltraSPARC IIIi';
ENUM_STRING_FAMILY_96 = '68040';
ENUM_STRING_FAMILY_97 = '68xxx Family';
ENUM_STRING_FAMILY_98 = '68000';
ENUM_STRING_FAMILY_99 = '68010';
ENUM_STRING_FAMILY_100 = '68020';
ENUM_STRING_FAMILY_101 = '68030';
ENUM_STRING_FAMILY_112 = 'Hobbit Family';
ENUM_STRING_FAMILY_120 = 'Crusoe™ TM5000 Family';
ENUM_STRING_FAMILY_121 = 'Crusoe™ TM3000 Family. 122. Efficeon™ TM8000 Family';
ENUM_STRING_FAMILY_128 = 'Weitek';
ENUM_STRING_FAMILY_130 = 'Itanium™ Processor';
ENUM_STRING_FAMILY_131 = 'AMD Athlon™ 64 Processor Famiily';
ENUM_STRING_FAMILY_132 = 'AMD Opteron™ Processor Family';
ENUM_STRING_FAMILY_144 = 'PA-RISC Family';
ENUM_STRING_FAMILY_145 = 'PA-RISC 8500';
ENUM_STRING_FAMILY_146 = 'PA-RISC 8000';
ENUM_STRING_FAMILY_147 = 'PA-RISC 7300LC';
ENUM_STRING_FAMILY_148 = 'PA-RISC 7200';
ENUM_STRING_FAMILY_149 = 'PA-RISC 7100LC';
ENUM_STRING_FAMILY_150 = 'PA-RISC 7100';
ENUM_STRING_FAMILY_160 = 'V30 Family';
ENUM_STRING_FAMILY_176 = 'Pentium III Xeon™ Processor';
ENUM_STRING_FAMILY_177 = 'Pentium III Processor with Intel SpeedStep™ Technology';
ENUM_STRING_FAMILY_178 = 'Pentium 4';
ENUM_STRING_FAMILY_179 = 'Intel Xeon™';
ENUM_STRING_FAMILY_180 = 'AS400 Family';
ENUM_STRING_FAMILY_181 = 'Intel Xeon™ Processor MP';
ENUM_STRING_FAMILY_182 = 'AMD Athlon™ XP Family';
ENUM_STRING_FAMILY_183 = 'AMD Athlon™ MP Family';
ENUM_STRING_FAMILY_184 = 'Intel Itanium 2';
ENUM_STRING_FAMILY_185 = 'Intel Pentium M Processor';
ENUM_STRING_FAMILY_190 = 'K7';
ENUM_STRING_FAMILY_200 = 'IBM390 Family';
ENUM_STRING_FAMILY_201 = 'G4';
ENUM_STRING_FAMILY_202 = 'G5';
ENUM_STRING_FAMILY_203 = 'G6';
ENUM_STRING_FAMILY_204 = 'z/Architecture Base';
ENUM_STRING_FAMILY_250 = 'i860';
ENUM_STRING_FAMILY_251 = 'i960';
ENUM_STRING_FAMILY_260 = 'SH-3';
ENUM_STRING_FAMILY_261 = 'SH-4';
ENUM_STRING_FAMILY_280 = 'ARM';
ENUM_STRING_FAMILY_281 = 'StrongARM';
ENUM_STRING_FAMILY_300 = '6x86';
ENUM_STRING_FAMILY_301 = 'MediaGX';
ENUM_STRING_FAMILY_302 = 'MII';
ENUM_STRING_FAMILY_320 = 'WinChip';
ENUM_STRING_FAMILY_350 = 'DSP';
ENUM_STRING_FAMILY_500 = 'Video Processor';
// Constantes para la propiedad PowerManagementCapabilities
const
ENUM_STRING_POWERMANAGEMENTCAPABILITIES_0 = 'Unknown';
ENUM_STRING_POWERMANAGEMENTCAPABILITIES_1 = 'Not Supported';
ENUM_STRING_POWERMANAGEMENTCAPABILITIES_2 = 'Disabled';
ENUM_STRING_POWERMANAGEMENTCAPABILITIES_3 = 'Enabled. The power management features are currently enabled but the exact feature set is unknown or the information is unavailable.';
ENUM_STRING_POWERMANAGEMENTCAPABILITIES_4 = 'Power Saving Modes Entered Automatically. The device can change its power state based on usage or other criteria.';
ENUM_STRING_POWERMANAGEMENTCAPABILITIES_5 = 'Power State Settable. The SetPowerState method is supported. This method is found on the parent CIM_LogicalDevice class and can be implemented. For more information, see Designing Managed Object Format (MOF) Classes.';
ENUM_STRING_POWERMANAGEMENTCAPABILITIES_6 = 'Power Cycling Supported. The SetPowerState method can be invoked with the PowerState parameter set to 5 (Power Cycle).';
ENUM_STRING_POWERMANAGEMENTCAPABILITIES_7 = 'Timed Power-On Supported. The SetPowerState method can be invoked with the PowerState parameter set to 5 (Power Cycle) and Time set to a specific date and time, or interval, for power-on.';
// Constantes para la propiedad ProcessorType
const
ENUM_STRING_PROCESSORTYPE_1 = 'Other';
ENUM_STRING_PROCESSORTYPE_2 = 'Unknown';
ENUM_STRING_PROCESSORTYPE_3 = 'Central Processor';
ENUM_STRING_PROCESSORTYPE_4 = 'Math Processor';
ENUM_STRING_PROCESSORTYPE_5 = 'DSP Processor';
ENUM_STRING_PROCESSORTYPE_6 = 'Video Processor';
//=========================================================================
//
// I M P L E M E N T A T I O N
//
//=========================================================================
implementation
uses
{Generales} Forms, Types, Windows, SysUtils,
{GLib} UProcedures, UConstantes, Dialogs;
{ TProcessor }
{-------------------------------------------------------------------------------}
// Limpiar las propiedades
procedure TProcessorInfo.ClearProps;
begin
Self.ProcessorProperties.FAddressWidth := 0;
Self.ProcessorProperties.FArchitecture := 0;
Self.ProcessorProperties.FAvailability := 0;
Self.ProcessorProperties.FCaption := STR_EMPTY;
Self.ProcessorProperties.FConfigManagerErrorCode := 0;
Self.ProcessorProperties.FConfigManagerUserConfig := False;
Self.ProcessorProperties.FCpuStatus := 0;
Self.ProcessorProperties.FCreationClassName := STR_EMPTY;
Self.ProcessorProperties.FCurrentClockSpeed := 0;
Self.ProcessorProperties.FCurrentVoltage := 0;
Self.ProcessorProperties.FDataWidth := 0;
Self.ProcessorProperties.FDescription := STR_EMPTY;
Self.ProcessorProperties.FDeviceID := STR_EMPTY;
Self.ProcessorProperties.FErrorCleared := False;
Self.ProcessorProperties.FErrorDescription := STR_EMPTY;
Self.ProcessorProperties.FExtClock := 0;
Self.ProcessorProperties.FFamily := 0;
Self.ProcessorProperties.FInstallDate := 0;
Self.ProcessorProperties.FL2CacheSize := 0;
Self.ProcessorProperties.FL2CacheSpeed := 0;
Self.ProcessorProperties.FL3CacheSize := 0;
Self.ProcessorProperties.FL3CacheSpeed := 0;
Self.ProcessorProperties.FLastErrorCode := 0;
Self.ProcessorProperties.FLevel := 0;
Self.ProcessorProperties.FLoadPercentage := 0;
Self.ProcessorProperties.FManufacturer := STR_EMPTY;
Self.ProcessorProperties.FMaxClockSpeed := 0;
Self.ProcessorProperties.FName := STR_EMPTY;
Self.ProcessorProperties.FNumberOfCores := 0;
Self.ProcessorProperties.FNumberOfLogicalProcessors := 0;
Self.ProcessorProperties.FOtherFamilyDescription := STR_EMPTY;
Self.ProcessorProperties.FPNPDeviceID := STR_EMPTY;
Self.ProcessorProperties.FPowerManagementCapabilitiesCount := 0;
Self.ProcessorProperties.FPowerManagementCapabilitiesAsString := STR_EMPTY;
SetLength(Self.ProcessorProperties.FPowerManagementCapabilities,0);
Self.ProcessorProperties.FPowerManagementSupported := False;
Self.ProcessorProperties.FProcessorId := STR_EMPTY;
Self.ProcessorProperties.FProcessorType := 0;
Self.ProcessorProperties.FRevision := 0;
Self.ProcessorProperties.FRole := STR_EMPTY;
Self.ProcessorProperties.FSocketDesignation := STR_EMPTY;
Self.ProcessorProperties.FStatus := STR_EMPTY;
Self.ProcessorProperties.FStatusInfo := 0;
Self.ProcessorProperties.FStepping := STR_EMPTY;
Self.ProcessorProperties.FSystemCreationClassName := STR_EMPTY;
Self.ProcessorProperties.FSystemName := STR_EMPTY;
Self.ProcessorProperties.FUniqueId := STR_EMPTY;
Self.ProcessorProperties.FUpgradeMethod := 0;
Self.ProcessorProperties.FVersion := STR_EMPTY;
Self.ProcessorProperties.FVoltageCaps := 0;
end;
//: Constructor del componente
constructor TProcessorInfo.Create(AOwner: TComponent);
begin
inherited;
Self.FProcessorProperties := TProcessorProperties.Create();
Self.MSDNHelp := 'http://msdn.microsoft.com/en-us/library/aa394373(VS.85).aspx';
end;
// destructor del componente
destructor TProcessorInfo.Destroy();
begin
// liberar
FreeAndNil(Self.FProcessorProperties);
inherited;
end;
// Obtener la clase
function TProcessorInfo.GetWMIClass(): string;
begin
Result := WIN32_PROCESSOR_CLASS;
end;
// Obtener Root
function TProcessorInfo.GetWMIRoot(): string;
begin
Result := STR_CIM2_ROOT;
end;
// Active
procedure TProcessorInfo.SetActive(const Value: Boolean);
begin
// método heredado
inherited;
end;
// Acceso a los elementos de la propiedad <PowerManagementCapabilities>
function TProcessorProperties.GetPowerManagementCapabilities(index: integer):Integer;
begin
if (index >= Self.FPowerManagementCapabilitiesCount) then begin
Index := Self.FPowerManagementCapabilitiesCount - 1;
end;
Result := Self.FPowerManagementCapabilities[index];
end;
//: Rellenar las propiedades del componente.
procedure TProcessorInfo.FillProperties(AIndex: integer);
var
v:variant;
vNull:boolean;
vp:TProcessorProperties;
begin
// Llamar al heredado (importante)
inherited;
// Rellenar propiedades...
vp := Self.ProcessorProperties;
GetWMIPropertyValue(Self, 'AddressWidth', v, vNull);
vp.FAddressWidth := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Architecture', v, vNull);
vp.FArchitecture := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Availability', v, vNull);
vp.FAvailability := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Caption', v, vNull);
vp.FCaption := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'ConfigManagerErrorCode', v, vNull);
vp.FConfigManagerErrorCode := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'ConfigManagerUserConfig', v, vNull);
vp.FConfigManagerUserConfig := VariantBooleanValue(v, vNull);
GetWMIPropertyValue(Self, 'CpuStatus', v, vNull);
vp.FCpuStatus := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'CreationClassName', v, vNull);
vp.FCreationClassName := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'CurrentClockSpeed', v, vNull);
vp.FCurrentClockSpeed := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'CurrentVoltage', v, vNull);
vp.FCurrentVoltage := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'DataWidth', v, vNull);
vp.FDataWidth := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Description', v, vNull);
vp.FDescription := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'DeviceID', v, vNull);
vp.FDeviceID := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'ErrorCleared', v, vNull);
vp.FErrorCleared := VariantBooleanValue(v, vNull);
GetWMIPropertyValue(Self, 'ErrorDescription', v, vNull);
vp.FErrorDescription := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'ExtClock', v, vNull);
vp.FExtClock := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Family', v, vNull);
vp.FFamily := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'InstallDate', v, vNull);
if not vNull then begin
vp.FInstallDate := EncodeDate(StrToInt(Copy(v, 1, 4)),StrToInt(Copy(v, 5, 2)),StrToInt(Copy(v, 7, 2)));
end;
GetWMIPropertyValue(Self, 'L2CacheSize', v, vNull);
vp.FL2CacheSize := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'L2CacheSpeed', v, vNull);
vp.FL2CacheSpeed := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'L3CacheSize', v, vNull);
vp.FL3CacheSize := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'L3CacheSpeed', v, vNull);
vp.FL3CacheSpeed := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'LastErrorCode', v, vNull);
vp.FLastErrorCode := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Level', v, vNull);
vp.FLevel := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'LoadPercentage', v, vNull);
vp.FLoadPercentage := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Manufacturer', v, vNull);
vp.FManufacturer := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'MaxClockSpeed', v, vNull);
vp.FMaxClockSpeed := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Name', v, vNull);
vp.FName := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'NumberOfCores', v, vNull);
vp.FNumberOfCores := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'NumberOfLogicalProcessors', v, vNull);
vp.FNumberOfLogicalProcessors := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'OtherFamilyDescription', v, vNull);
vp.FOtherFamilyDescription := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'PNPDeviceID', v, vNull);
vp.FPNPDeviceID := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'PowerManagementCapabilities', v, vNull);
vp.FPowerManagementCapabilitiesAsString := VariantStrValue(v, vNull);
// vp.FPowerManagementCapabilities := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'PowerManagementSupported', v, vNull);
vp.FPowerManagementSupported := VariantBooleanValue(v, vNull);
GetWMIPropertyValue(Self, 'ProcessorId', v, vNull);
vp.FProcessorId := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'ProcessorType', v, vNull);
vp.FProcessorType := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Revision', v, vNull);
vp.FRevision := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Role', v, vNull);
vp.FRole := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'SocketDesignation', v, vNull);
vp.FSocketDesignation := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'Status', v, vNull);
vp.FStatus := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'StatusInfo', v, vNull);
vp.FStatusInfo := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Stepping', v, vNull);
vp.FStepping := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'SystemCreationClassName', v, vNull);
vp.FSystemCreationClassName := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'SystemName', v, vNull);
vp.FSystemName := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'UniqueId', v, vNull);
vp.FUniqueId := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'UpgradeMethod', v, vNull);
vp.FUpgradeMethod := VariantIntegerValue(v, vNull);
GetWMIPropertyValue(Self, 'Version', v, vNull);
vp.FVersion := VariantStrValue(v, vNull);
GetWMIPropertyValue(Self, 'VoltageCaps', v, vNull);
vp.FVoltageCaps := VariantIntegerValue(v, vNull);
end;
// Obtener la propiedad como string
function TProcessorProperties.GetArchitectureAsString():string;
begin
case FArchitecture of
0: Result := ENUM_STRING_ARCHITECTURE_0;
1: Result := ENUM_STRING_ARCHITECTURE_1;
2: Result := ENUM_STRING_ARCHITECTURE_2;
3: Result := ENUM_STRING_ARCHITECTURE_3;
6: Result := ENUM_STRING_ARCHITECTURE_6;
9: Result := ENUM_STRING_ARCHITECTURE_9;
else
Result := STR_EMPTY;
end;
end;
// Obtener la propiedad como string
function TProcessorProperties.GetAvailabilityAsString():string;
begin
case FAvailability of
1: Result := ENUM_STRING_AVAILABILITY_1;
2: Result := ENUM_STRING_AVAILABILITY_2;
3: Result := ENUM_STRING_AVAILABILITY_3;
4: Result := ENUM_STRING_AVAILABILITY_4;
5: Result := ENUM_STRING_AVAILABILITY_5;
6: Result := ENUM_STRING_AVAILABILITY_6;
7: Result := ENUM_STRING_AVAILABILITY_7;
8: Result := ENUM_STRING_AVAILABILITY_8;
9: Result := ENUM_STRING_AVAILABILITY_9;
10: Result := ENUM_STRING_AVAILABILITY_10;
11: Result := ENUM_STRING_AVAILABILITY_11;
12: Result := ENUM_STRING_AVAILABILITY_12;
13: Result := ENUM_STRING_AVAILABILITY_13;
14: Result := ENUM_STRING_AVAILABILITY_14;
15: Result := ENUM_STRING_AVAILABILITY_15;
16: Result := ENUM_STRING_AVAILABILITY_16;
17: Result := ENUM_STRING_AVAILABILITY_17;
else
Result := STR_EMPTY;
end;
end;
// Obtener la propiedad como string
function TProcessorProperties.GetFamilyAsString():string;
begin
case FFamily of
1: Result := ENUM_STRING_FAMILY_1;
2: Result := ENUM_STRING_FAMILY_2;
3: Result := ENUM_STRING_FAMILY_3;
4: Result := ENUM_STRING_FAMILY_4;
5: Result := ENUM_STRING_FAMILY_5;
6: Result := ENUM_STRING_FAMILY_6;
7: Result := ENUM_STRING_FAMILY_7;
8: Result := ENUM_STRING_FAMILY_8;
9: Result := ENUM_STRING_FAMILY_9;
10: Result := ENUM_STRING_FAMILY_10;
11: Result := ENUM_STRING_FAMILY_11;
12: Result := ENUM_STRING_FAMILY_12;
13: Result := ENUM_STRING_FAMILY_13;
14: Result := ENUM_STRING_FAMILY_14;
15: Result := ENUM_STRING_FAMILY_15;
16: Result := ENUM_STRING_FAMILY_16;
17: Result := ENUM_STRING_FAMILY_17;
18: Result := ENUM_STRING_FAMILY_18;
19: Result := ENUM_STRING_FAMILY_19;
24: Result := ENUM_STRING_FAMILY_24;
25: Result := ENUM_STRING_FAMILY_25;
26: Result := ENUM_STRING_FAMILY_26;
27: Result := ENUM_STRING_FAMILY_27;
28: Result := ENUM_STRING_FAMILY_28;
29: Result := ENUM_STRING_FAMILY_29;
30: Result := ENUM_STRING_FAMILY_30;
31: Result := ENUM_STRING_FAMILY_31;
32: Result := ENUM_STRING_FAMILY_32;
33: Result := ENUM_STRING_FAMILY_33;
34: Result := ENUM_STRING_FAMILY_34;
35: Result := ENUM_STRING_FAMILY_35;
36: Result := ENUM_STRING_FAMILY_36;
37: Result := ENUM_STRING_FAMILY_37;
38: Result := ENUM_STRING_FAMILY_38;
39: Result := ENUM_STRING_FAMILY_39;
48: Result := ENUM_STRING_FAMILY_48;
49: Result := ENUM_STRING_FAMILY_49;
50: Result := ENUM_STRING_FAMILY_50;
51: Result := ENUM_STRING_FAMILY_51;
52: Result := ENUM_STRING_FAMILY_52;
53: Result := ENUM_STRING_FAMILY_53;
54: Result := ENUM_STRING_FAMILY_54;
55: Result := ENUM_STRING_FAMILY_55;
64: Result := ENUM_STRING_FAMILY_64;
65: Result := ENUM_STRING_FAMILY_65;
66: Result := ENUM_STRING_FAMILY_66;
67: Result := ENUM_STRING_FAMILY_67;
68: Result := ENUM_STRING_FAMILY_68;
69: Result := ENUM_STRING_FAMILY_69;
80: Result := ENUM_STRING_FAMILY_80;
81: Result := ENUM_STRING_FAMILY_81;
82: Result := ENUM_STRING_FAMILY_82;
83: Result := ENUM_STRING_FAMILY_83;
84: Result := ENUM_STRING_FAMILY_84;
85: Result := ENUM_STRING_FAMILY_85;
86: Result := ENUM_STRING_FAMILY_86;
87: Result := ENUM_STRING_FAMILY_87;
88: Result := ENUM_STRING_FAMILY_88;
96: Result := ENUM_STRING_FAMILY_96;
97: Result := ENUM_STRING_FAMILY_97;
98: Result := ENUM_STRING_FAMILY_98;
99: Result := ENUM_STRING_FAMILY_99;
100: Result := ENUM_STRING_FAMILY_100;
101: Result := ENUM_STRING_FAMILY_101;
112: Result := ENUM_STRING_FAMILY_112;
120: Result := ENUM_STRING_FAMILY_120;
121: Result := ENUM_STRING_FAMILY_121;
128: Result := ENUM_STRING_FAMILY_128;
130: Result := ENUM_STRING_FAMILY_130;
131: Result := ENUM_STRING_FAMILY_131;
132: Result := ENUM_STRING_FAMILY_132;
144: Result := ENUM_STRING_FAMILY_144;
145: Result := ENUM_STRING_FAMILY_145;
146: Result := ENUM_STRING_FAMILY_146;
147: Result := ENUM_STRING_FAMILY_147;
148: Result := ENUM_STRING_FAMILY_148;
149: Result := ENUM_STRING_FAMILY_149;
150: Result := ENUM_STRING_FAMILY_150;
160: Result := ENUM_STRING_FAMILY_160;
176: Result := ENUM_STRING_FAMILY_176;
177: Result := ENUM_STRING_FAMILY_177;
178: Result := ENUM_STRING_FAMILY_178;
179: Result := ENUM_STRING_FAMILY_179;
180: Result := ENUM_STRING_FAMILY_180;
181: Result := ENUM_STRING_FAMILY_181;
182: Result := ENUM_STRING_FAMILY_182;
183: Result := ENUM_STRING_FAMILY_183;
184: Result := ENUM_STRING_FAMILY_184;
185: Result := ENUM_STRING_FAMILY_185;
190: Result := ENUM_STRING_FAMILY_190;
200: Result := ENUM_STRING_FAMILY_200;
201: Result := ENUM_STRING_FAMILY_201;
202: Result := ENUM_STRING_FAMILY_202;
203: Result := ENUM_STRING_FAMILY_203;
204: Result := ENUM_STRING_FAMILY_204;
250: Result := ENUM_STRING_FAMILY_250;
251: Result := ENUM_STRING_FAMILY_251;
260: Result := ENUM_STRING_FAMILY_260;
261: Result := ENUM_STRING_FAMILY_261;
280: Result := ENUM_STRING_FAMILY_280;
281: Result := ENUM_STRING_FAMILY_281;
300: Result := ENUM_STRING_FAMILY_300;
301: Result := ENUM_STRING_FAMILY_301;
302: Result := ENUM_STRING_FAMILY_302;
320: Result := ENUM_STRING_FAMILY_320;
350: Result := ENUM_STRING_FAMILY_350;
500: Result := ENUM_STRING_FAMILY_500;
else
Result := STR_EMPTY;
end;
end;
// Obtener la propiedad como string
function TProcessorProperties.GetProcessorTypeAsString():string;
begin
case FProcessorType of
1: Result := ENUM_STRING_PROCESSORTYPE_1;
2: Result := ENUM_STRING_PROCESSORTYPE_2;
3: Result := ENUM_STRING_PROCESSORTYPE_3;
4: Result := ENUM_STRING_PROCESSORTYPE_4;
5: Result := ENUM_STRING_PROCESSORTYPE_5;
6: Result := ENUM_STRING_PROCESSORTYPE_6;
else
Result := STR_EMPTY;
end;
end;
// Obtener la propiedad como string
function TProcessorProperties.GetCPUStatusAsString():string;
begin
case FCpuStatus of
0: Result := ENUM_STRING_CPUSTATUS_0;
1: Result := ENUM_STRING_CPUSTATUS_1;
2: Result := ENUM_STRING_CPUSTATUS_2;
3: Result := ENUM_STRING_CPUSTATUS_3;
4: Result := ENUM_STRING_CPUSTATUS_4;
5: Result := ENUM_STRING_CPUSTATUS_5;
6: Result := ENUM_STRING_CPUSTATUS_6;
7: Result := ENUM_STRING_CPUSTATUS_7;
else
Result := STR_EMPTY;
end;
end;
end.
|
unit TableMappingUnit;
interface
uses SysUtils, Classes, TableColumnMappingsUnit;
type
TTableMapping = class
protected
FTableName: String;
FObjectClass: TClass;
FObjectListClass: TClass;
FColumnMappings: TTableColumnMappings;
procedure SetObjectClass(const Value: TClass);
procedure SetObjectListClass(const Value: TClass);
procedure SetTableName(const Value: String);
function GetColumnMappings: TTableColumnMappings; virtual;
function GetTableName: String;
function GetObjectClass: TClass;
function GetObjectListClass: TClass;
public
destructor Destroy; override;
constructor Create;
procedure SetTableNameMapping(
const TableName: String;
ObjectClass: TClass;
ObjectListClass: TClass = nil
);
procedure AddColumnMapping(
const ColumnName, ObjectPropertyName: String
);
property ColumnMappings: TTableColumnMappings read FColumnMappings;
property TableName: String read GetTableName write SetTableName;
property ObjectClass: TClass read GetObjectClass write SetObjectClass;
property ObjectListClass: TClass read GetObjectListClass write SetObjectListClass;
end;
implementation
{ TTableMapping }
procedure TTableMapping.AddColumnMapping(
const ColumnName,
ObjectPropertyName: String
);
begin
FColumnMappings.AddColumnMapping(
ColumnName, ObjectPropertyName
);
end;
constructor TTableMapping.Create;
begin
inherited;
FColumnMappings := GetColumnMappings;
end;
destructor TTableMapping.Destroy;
begin
FreeAndNil(FColumnMappings);
inherited;
end;
function TTableMapping.GetColumnMappings: TTableColumnMappings;
begin
Result := TTableColumnMappings.Create;
end;
function TTableMapping.GetObjectClass: TClass;
begin
Result := FObjectClass;
end;
function TTableMapping.GetObjectListClass: TClass;
begin
Result := FObjectListClass;
end;
function TTableMapping.GetTableName: String;
begin
Result := FTableName;
end;
procedure TTableMapping.SetObjectClass(const Value: TClass);
begin
FObjectClass := Value;
end;
procedure TTableMapping.SetObjectListClass(const Value: TClass);
begin
FObjectListClass := Value;
end;
procedure TTableMapping.SetTableName(const Value: String);
begin
FTableName := Value;
end;
procedure TTableMapping.SetTableNameMapping(
const TableName: String;
ObjectClass: TClass;
ObjectListClass: TClass
);
begin
FTableName := TableName;
FObjectClass := ObjectClass;
FObjectListClass := ObjectListClass;
end;
end.
|
unit FrameControl;
interface
uses
Forms, Rda_TLB, StdCtrls, Onoff, Controls, Classes;
type
TFrame_Control = class(TFrame)
Button1: TButton;
Edit1: TEdit;
Bulb1: TBulb;
procedure Button1Click(Sender: TObject);
private
fLogin : ILogin;
procedure SetLogin( Value : ILogin );
public
procedure UpdateView;
published
property Login : ILogin read fLogin write SetLogin;
end;
implementation
{$R *.DFM}
{ TFrame_Control }
procedure TFrame_Control.SetLogin(Value: ILogin);
begin
fLogin := Value;
Button1Click(Button1);
end;
procedure TFrame_Control.UpdateView;
begin
if assigned(fLogin)
then
with fLogin do
begin
Button1.Enabled := fLogin.Level >= fLogin.ControllerLevel;
Edit1.Text := ControllerName;
Bulb1.State := InControl;
end;
end;
procedure TFrame_Control.Button1Click(Sender: TObject);
begin
if assigned(fLogin)
then
if Bulb1.State
then fLogin.ReleaseControl
else fLogin.TakeControl;
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uClasseCalculadora,
uClasseMetodosUteis, uInterfaceObjeto;
type
TForm1 = class(TForm)
Somar: TButton;
Multiplicar: TButton;
Subtrair: TButton;
Dividir: TButton;
EDT_NUM: TEdit;
EdtValue2: TEdit;
EdtResult: TEdit;
procedure FormCreate(Sender: TObject);
procedure SomarClick(Sender: TObject);
procedure SubtrairClick(Sender: TObject);
procedure MultiplicarClick(Sender: TObject);
procedure DividirClick(Sender: TObject);
private
FCalculadora: iCalculadora;
procedure SetCalculadora(const Value: iCalculadora);
procedure ExibirValue(Value: String);
{ Private declarations }
public
{ Public declarations }
property Calculadora: iCalculadora read FCalculadora write SetCalculadora;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
{ TForm1 }
procedure TForm1.DividirClick(Sender: TObject);
begin
Calculadora.Add(EDT_NUM.Text).Add(EdtValue2.Text).Dividir.Executar;
end;
procedure TForm1.ExibirValue(Value: String);
begin
EdtResult.Text := Value;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Calculadora := TCalculadora.New.Display.Resultado(ExibirValue).EndDisplay;
end;
procedure TForm1.MultiplicarClick(Sender: TObject);
begin
Calculadora.Add(EDT_NUM.Text).Add(EdtValue2.Text).Multiplicar.Executar;
end;
procedure TForm1.SetCalculadora(const Value: iCalculadora);
begin
FCalculadora := Value;
end;
procedure TForm1.SomarClick(Sender: TObject);
begin
Calculadora.Add(EDT_NUM.Text).Add(EdtValue2.Text).Somar.Executar;
end;
procedure TForm1.SubtrairClick(Sender: TObject);
begin
Calculadora.Add(EDT_NUM.Text).Add(EdtValue2.Text).Subtrair.Executar;
end;
end.
|
unit Unit2;
interface
type
TUtils = class
class function GerarNomeArquivo: string; static;
class function GetRowId(ARowId: string): string; static;
end;
implementation
uses System.SysUtils;
class function TUtils.GerarNomeArquivo: string;
var
guid: TGUID;
sGuid: string;
begin
guid := guid.NewGuid;
sGuid := GUIDToString(guid.NewGuid);
sGuid := StringReplace(sGuid, '{', '', [rfReplaceAll]);
sGuid := StringReplace(sGuid, '}', '', [rfReplaceAll]);
sGuid := StringReplace(sGuid, '-', '', [rfReplaceAll]);
Result := sGuid;
end;
class function TUtils.GetRowId(ARowId: string): string;
var
rowId: string;
begin
rowId := ARowId;
rowId := StringReplace(rowId, 'itemName(): ', '', [rfReplaceAll]);
Result := Trim(rowId);
end;
end.
|
unit PermissoesAcesso;
interface
uses Usuario;
type
TPermissoesAcesso = class
public
class function VerificaPermissao(nPermissao: Integer): Boolean; overload;
class function VerificaPermissao(nPermissao: Integer; lPedeSupervisor: Boolean): Boolean; overload;
class function VerificaPermissao(nPermissao: Integer; cMens: String; lPedeSupervisor: Boolean): Boolean; overload;
class function VerificaPermissao(nPermissao: Integer; cMens: String; lMensagem: Boolean; lPedeSupervisor: Boolean): Boolean; overload;
end;
const
paLogarSistema = 1;
paCadastroPerfil = 2;
paCadastroUsuario = 3;
paAlterarUsuario = 4;
paCadastroGrupo = 5;
paCadastroMateriaPrima = 6;
paCadastroProduto = 7;
paCriaPedido = 8;
paDadosEmpresa = 9;
paOperaCaixa = 10;
paCadastroDepartamento = 11;
paTelaImpressoesPendentes = 12;
paConfiguraECF = 13;
paTelaNFce = 14;
paRelatorioVendas = 15;
paTelaPedidosEmAberto = 16;
paCadastroComanda = 17;
paCadastroDispensa = 18;
paEntradaSaidaMercadoria = 19;
paLiberarComanda = 20;
paRelatorioAtendimentos = 21;
paRelatorioPedidos = 22;
paRelatorioEstoque = 23;
paRelatorioEntradaSaida = 24;
paRelatorioCaixa48Colunas = 25;
paRelatorioItensDeletados = 26;
paConfigurarSistema = 27;
paCadastroCliente = 28;
paRelatorioProdutos = 29;
paRelatorioCuponsFiscais = 30;
paReimpressaoPedido = 31;
paCadastroFornecedor = 32;
paEntradaNotaPorXml = 33;
paCadastroCFOPsCorrespondentes = 34;
paLancaSangriaReforco = 35;
paConfirmaEntradaEstoque = 36;
paRelatorioNotasFiscaisEntrada = 37;
paNotaFiscal = 38;
paMonitorNFe = 39;
paCadastroTransportadora = 40;
paEstornoEntradaNF = 41;
paCadastroNCM = 42;
paRelatorioMovimentacaoGeral = 43;
paRelatorioValidades = 44;
implementation
uses SysUtils, USupervisor, uModulo, uPadrao;
class function TPermissoesAcesso.VerificaPermissao(nPermissao: Integer; lPedeSupervisor: Boolean): Boolean;
var cMens: String;
begin
if dm.UsuarioLogado = nil then
cMens := 'Você não tem permissão para acessar esta rotina!'
else
cMens := Trim(dm.UsuarioLogado.Nome) + #13 + ' Você não tem permissão para acessar esta rotina!';
Result := VerificaPermissao(nPermissao, cMens, lPedeSupervisor);
end;
class function TPermissoesAcesso.VerificaPermissao(nPermissao: Integer; cMens: String; lPedeSupervisor: Boolean): Boolean;
begin
try
Result := self.VerificaPermissao(nPermissao, cMens, True, lPedeSupervisor);
Except
On E: Exception Do begin
raise Exception.Create(e.Message);
end;
end;
end;
class function TPermissoesAcesso.VerificaPermissao(nPermissao: Integer; cMens: String; lMensagem: Boolean; lPedeSupervisor: Boolean): Boolean;
var cMenSup, msgRetorno: String;
begin
Result := false;
if dm.UsuarioLogado = nil then
begin
if lMensagem then
raise Exception.Create('Não há usuário logado no sistema!');
exit;
end
else if dm.UsuarioLogado.Perfil = nil then
begin
if lMensagem then
raise Exception.Create('O usuário logado não tem um perfil definido!');
exit;
end;
if (Copy(dm.UsuarioLogado.Perfil.Acesso, nPermissao, 1) <> 'S') then
begin
cMenSup := '';
if lPedeSupervisor then
cMenSup := #13#13 + ' Contate o seu supervisor para liberar o acesso!';
if (lMensagem) then
begin
if (Length(Trim(cMenSup)) > 0) then
msgRetorno := cMens + cMenSup
else
msgRetorno := Trim(cMens);
end
else if lPedeSupervisor then
msgRetorno := cMenSup;
if (lPedeSupervisor) and (TfrmSupervisor.LiberaFuncao(nPermissao)) then
Result := true
else
//TfrmPadrao.Create(nil).avisar(msgRetorno);
raise Exception.Create(msgRetorno);
exit;
end
else
Result := true;
end;
class function TPermissoesAcesso.VerificaPermissao(nPermissao: Integer): Boolean;
begin
Result := TPermissoesAcesso.VerificaPermissao(nPermissao, true);
end;
end.
|
unit TestFindUnitUtils;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
FindUnit.Utils;
type
// Test methods for class TPathConverter
TestTPathConverter = class(TTestCase)
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestUnitFromSearchSelectionInterface;
procedure TestUnitFromSearchSelectionClass;
end;
implementation
procedure TestTPathConverter.SetUp;
begin
end;
procedure TestTPathConverter.TearDown;
begin
end;
procedure TestTPathConverter.TestUnitFromSearchSelectionInterface;
var
ClassOut: string;
UnitOut: string;
begin
GetUnitFromSearchSelection('Interf.EnvironmentController.IRFUEnvironmentController.* - Interface', UnitOut, ClassOut);
Assert(UnitOut = 'Interf.EnvironmentController', 'Unit out is wrong');
Assert(ClassOut = 'IRFUEnvironmentController', 'Class out is wrong');
end;
procedure TestTPathConverter.TestUnitFromSearchSelectionClass;
var
ClassOut: string;
UnitOut: string;
begin
GetUnitFromSearchSelection('System.Classes.TStringList.* - Class', UnitOut, ClassOut);
Assert(UnitOut = 'System.Classes', 'Unit out is wrong');
Assert(ClassOut = 'TStringList', 'Class out is wrong');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTPathConverter.Suite);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.